aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorMichael Lando <ml636r@att.com>2017-06-09 03:19:04 +0300
committerMichael Lando <ml636r@att.com>2017-06-09 03:19:04 +0300
commited64b5edff15e702493df21aa3230b81593e6133 (patch)
treea4cb01fdaccc34930a8db403a3097c0d1e40914b
parent280f8015d06af1f41a3ef12e8300801c7a5e0d54 (diff)
[SDC-29] catalog 1707 rebase commit.
Change-Id: I43c3dc5cf44abf5da817649bc738938a3e8388c1 Signed-off-by: Michael Lando <ml636r@att.com>
-rw-r--r--.gitignore154
-rw-r--r--asdc-tests/pom.xml248
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/api/AttSdcTest.java (renamed from asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/api/SdcTest.java)24
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/api/ComponentBaseTest.java223
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/api/ComponentInstanceBaseTest.java1
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/api/Urls.java22
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/config/Config.java29
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ArtifactReqDetails.java1
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ImportReqDetails.java3
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceAssetStructure.java18
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceDetailedAssetStructure.java18
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceExternalReqDetails.java105
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceInstanceAssetStructure.java16
-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/enums/ArtifactTypeEnum.java7
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/AssocType.java7
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/AuditEnum.java16
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/DistributionNotificationStatusEnum.java (renamed from ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/TypesEnum.java)33
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/LifeCycleStatesEnum.java2
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/MandatoryResourceArtifactTypeEnum.java6
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/NormativeTypesEnum.java18
-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.java4
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ResourceCategoryEnum.java5
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/RespJsonKeysEnum.java28
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/SearchCriteriaEnum.java (renamed from ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/CatalogFilterTitlesEnum.java)17
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ServiceApiArtifactEnum.java7
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ToscaKeysEnum.java5
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/UserRoleEnum.java31
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/HttpRequest.java27
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/TODO/ImportCapabilityTypeCITest.java8
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ArtifactServletTest.java2
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/CrudArt.java165
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/DownloadComponentArt.java362
-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.java12
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ValidateArtResponse.java9
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ValidateHeatArtFieldsFromUI.java444
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ValidateHeatArtFieldsTypes.java2
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/attribute/ComponentInstanceAttributeTest.java29
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/category/CatalogDataApiTest.java2
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/category/CategoriesTests.java14
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/category/ElementsApiTest.java1
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/category/GroupingTest.java4
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/category/SubCategoriesTest.java1
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/CRUDExternalAPI.java4044
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/ImportCsarUpdate.java173
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/ImportCsarValidateArtifacts.java5
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/OpsRejectDistribution.java68
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/SearchFilterCategoryExternalAPI.java344
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/ToscaGroupInsideVF.java2
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/VFCMTExternalAPI.java390
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/ValidateConformanceLevel.java78
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/test1.java102
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/distribution/DistributionDownloadArtifactTest.java70
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/externalapi/DownloadArtifactsTest.java131
-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.java473
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/general/BasicHttpAuthenticationTest.java115
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/general/ManageEcompConsumerCredentials.java66
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/CsarUtilsTest.java350
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ExportToscaTest.java544
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportCsarResourceTest.java345
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportGenericResourceCITest.java27
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportNewResourceCITest.java296
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportToscaResourceTest.java1512
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportUpdateResourseCsarTest.java1
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/inputs/InputsApiTests.java184
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/lifecycle/LCSbaseTest.java2
-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/product/ProductBaseTest.java17
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCheckoutTest.java1
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductComponentInstanceCRUDTest.java778
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCreateWithValidationsTest.java1
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCrudTest.java46
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductLifecycleTest.java3
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/property/AdditionalInformationServletTest.java6
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/property/ComponentInstancePropertyTest.java782
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/property/ComponentProperty.java4
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/property/PropertyApisTest.java12
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/CheckGetResource.java1
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/ComponentRelationshipInVfTest.java2
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/CreateResourceApiTest.java24
-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.java2
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/GetResourceNotAbstractApiTest.java4
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/ResourceApiTest.java10
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/SimultaneousApiTest.java22
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/UpdateResourceMetadataTest.java104
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/VFResourceInstanceNameCRUD.java1
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/ValidateExtendedVfData.java4
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/ChangeServiceDistributionStatusApiTest.java4
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/CreateServiceMetadataApiTest.java4
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/GetAllServiceVersions.java1
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/GetComponentAuditApiTest.java93
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/GetServiceLatestVersionTest.java1
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/ServiceComponentInstanceCRUDTest.java875
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/UpdateServiceMetadataTest.java346
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/user/ActivateDeActivateDeleteUser.java186
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/user/CreateUserApiTest.java246
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/user/GovernorWorkspaceApiTest.java43
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/migration/v1707/CommonMigrationUtils.java19
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/migration/v1707/postupgrade/AttKeyPropertiesRenameTest.java71
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/migration/v1707/preupgrade/AttKeyPropertiesBeforeRenameTest.java49
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/rules/MyTestWatcher.java10
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/run/ExtentReporterNG.java94
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/run/StartTest.java60
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/run/StartTest2backup.java26
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/sanity/CrudE2E.java159
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/sanity/MultipleResourceUpdate.java17
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaDefinition.java5
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/users/UserResponseMessageEnum.java19
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/ArtifactUtils.java25
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/DbUtils.java45
-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/Utils.java435
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/cassandra/CassandraUtils.java49
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/cassandra/CassandraUtils2.java30
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/AtomicOperationUtils.java97
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/Convertor.java43
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/ElementFactory.java147
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/FileUtils.java9
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/ImportUtils.java9
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/graph/GraphFileUtils.java39
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ArtifactRestUtils.java769
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/AssetRestUtils.java65
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/BaseRestUtils.java9
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CategoryRestUtils.java34
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ComponentInstanceRestUtils.java38
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ComponentRestUtils.java8
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ConsumerRestUtils.java87
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/EcompUserRestUtils.java39
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ImportRestUtils.java127
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/LifecycleRestUtils.java84
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ProductRestUtils.java31
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/PropertyRestUtils.java122
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResourceRestUtils.java218
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResourceRestUtilsExternalAPI.java64
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResponseParser.java123
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ServiceRestUtils.java49
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/UserRestUtils.java23
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ArtifactValidationUtils.java7
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/AuditValidationUtils.java86
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/BaseValidationUtils.java1
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/CategoryValidationUtils.java3
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/CsarValidationUtils.java58
-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.java15
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ResourceValidationUtils.java10
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ServiceValidationUtils.java6
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/TestYamlParser.java94
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/UserValidationUtils.java10
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/externalApis/GetAssetServlet.java33
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/externalApis/GetSpecificAssetMetadataServlet.java24
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/post/Install.java5
-rw-r--r--asdc-tests/src/main/resources/ci/conf/attsdc-packages.yaml (renamed from asdc-tests/src/main/resources/ci/conf/sdc-packages.yaml)0
-rw-r--r--asdc-tests/src/main/resources/ci/conf/attsdc.yaml (renamed from asdc-tests/src/main/resources/ci/conf/sdc.yaml)11
-rw-r--r--asdc-tests/src/main/resources/ci/conf/titan.properties2
-rw-r--r--asdc-tests/src/main/resources/ci/scripts/startTest.sh2
-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/ciFull.xml2
-rw-r--r--asdc-tests/src/main/resources/ci/testSuites/externalApis.xml3
-rw-r--r--asdc-tests/src/main/resources/ci/testSuites/resource.xml24
-rw-r--r--asdc-tests/src/main/resources/ci/testSuites/sanity.xml14
-rw-r--r--asdc-tests/src/test/resources/CI/configuration.yaml34
-rw-r--r--asdc-tests/src/test/resources/CI/csars/FCGI_with_inputs.csarbin35433 -> 35433 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/csars/ImportArtifactsToVFC.csarbin0 -> 57082 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/csars/ImportArtifactsToVFC_empty.csarbin0 -> 30674 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/csars/LDSA1_with_inputs.csarbin28243 -> 28284 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/csars/ToscaTemplateCsar.csarbin0 -> 6175 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/csars/VF_RI2_G4_withArtifacts.csarbin36440 -> 36439 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/csars/VF_RI2_G4_withArtifacts_a.csarbin36440 -> 36439 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/csars/VF_RI2_G4_withArtifacts_b.csarbin36444 -> 36443 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/csars/VF_RI2_G4_withArtifacts_group_naming_a.csarbin35874 -> 35872 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/csars/VF_RI2_G4_withArtifacts_group_naming_add_update.csarbin35854 -> 35852 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/csars/VF_RI2_G4_withArtifacts_group_naming_delete_update.csarbin35852 -> 35851 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/csars/jsonPropertyTypeTest.csarbin24762 -> 24750 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/csars/orig2G.csarbin38900 -> 38917 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/csars/orig2GV001.csarbin38994 -> 39002 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/csars/orig2GV001_a.csarbin38994 -> 39002 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/csars/orig2GV006-remove-all-nested-artifacts.csarbin38993 -> 39000 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/csars/orig2GV008-change-nested-oam-fileContent.csarbin39005 -> 39013 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/csars/orig2G_a.csarbin38900 -> 38917 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/csars/orig2G_updated.csarbin38775 -> 38791 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/csars/vf_relate_by_cap_name.csarbin25963 -> 25918 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/csars/vf_with_cap_prop_override_cap_type_prop1.csarbin1548 -> 1548 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/csars/vf_with_cap_prop_override_cap_type_prop1_failed.csarbin1546 -> 1546 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/csars/vfc_artifacts.csarbin0 -> 48225 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/csars/vfc_artifacts_delete_all.csar (renamed from ui-ci-dev/src/main/resources/Files/vf_with_groups.csar)bin25253 -> 26179 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/csars/vfc_artifacts_update.csarbin0 -> 48245 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/csars/vmmc_relate_by_cap_name.csarbin35606 -> 35467 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/demoResourcesWanLan/LAN_Connector/LAN_Connector.zipbin530 -> 493 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/demoResourcesWanLan/VNF/VNF.zipbin449 -> 411 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/demoResourcesWanLan/VNF_Container/VNF_Container.zipbin394 -> 357 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/demoResourcesWanLan/WAN_Connector/WAN_Connector.zipbin505 -> 467 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/demoResourcesWanLan/capabilityTypesWanLan.zipbin269 -> 231 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/demoResourcesWanLan/connector/connector.zipbin423 -> 384 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/demoResourcesWanLan/root/root.zipbin242 -> 205 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/demoResourcesWanLan/router/router.zipbin455 -> 418 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/error-configuration.yaml20
-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.json2
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.Cinder/asdc.nodes.network.Cinder.json2
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.OAM/asdc.nodes.network.OAM.json2
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/VCE_Brocade_Tosca.yaml40
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/capabilityTypes.zipbin1158 -> 1065 bytes
-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 -> 805 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.zipbin795 -> 795 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.zipbin796 -> 796 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.CP/org.openecomp.resource.nfv.CP.zipbin339 -> 339 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.json2
-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 -> 395 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.zipbin1751 -> 1751 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.VDU/org.openecomp.resource.nfv.VDU.zipbin344 -> 344 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.json2
-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.yaml2
-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.zipbin480 -> 442 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.json2
-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.zipbin475 -> 440 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.zipbin489 -> 453 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.json2
-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.zipbin550 -> 515 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.zipbin538 -> 502 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VL/org.openecomp.resource.nfv.VL.zipbin310 -> 310 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.json2
-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 -> 592 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VNF/org.openecomp.resource.nfv.VNF.json2
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VNF/org.openecomp.resource.nfv.VNF.zipbin309 -> 309 bytes
-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.zipbin0 -> 322 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/empty_contact/normative-types-new-empty_contact.zipbin445 -> 409 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/empty_resource_name/normative-types-new-empty_resource_name.zipbin456 -> 420 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/empty_tag/normative-types-new-empty_tag.zipbin436 -> 400 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/importResource4test/normative-types-new-importResource4test.zipbin630 -> 596 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/importResource4testCP/normative-types-new-importResource4testCP.zipbin637 -> 603 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/importResource4testMissingNameSpace/normative-types-new-importResource4testMissingNameSpace.zipbin662 -> 628 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/importResource4testUnknown/normative-types-new-importResource4testUnknown.zipbin651 -> 616 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/importResource4testUpdateVendorNameAndCategory/normative-types-new-importResource4testUpdateVendorNameAndCategory.zipbin447 -> 411 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/importResource4testUpdateWithoutReqCap/normative-types-new-importResource4testUpdateWithoutReqCap.zipbin460 -> 422 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/importResource4testVF/normative-types-new-importResource4testVF.zipbin637 -> 603 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/importResource4testVFC/normative-types-new-importResource4testVFC.zipbin641 -> 607 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/importResource4testVL/normative-types-new-importResource4testVL.zipbin637 -> 603 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/missing_category/normative-types-new-missing_category.zipbin450 -> 414 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/missing_contact/normative-types-new-missing_contact.zipbin449 -> 413 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/missing_desc/normative-types-new-missing_desc.zipbin442 -> 406 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/missing_icon/normative-types-new-missing_icon.zipbin442 -> 406 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/missing_payloadName/normative-types-new-missing_payloadName.zipbin456 -> 420 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/missing_resource_name/normative-types-new-missing_resource_name.zipbin460 -> 424 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/missing_tags/normative-types-new-missing_tags.zipbin442 -> 406 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/userCompute/normative-types-new-userCompute.zipbin610 -> 610 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/userUpdateCompute/normative-types-new-userUpdateCompute.zipbin580 -> 580 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeBoolean_valueInit/normative-types-new-validateProporties_typeBoolean_valueInit.zipbin578 -> 542 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeBoolean_valueString/normative-types-new-validateProporties_typeBoolean_valueString.zipbin579 -> 542 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeFloat_valueBoolean/normative-types-new-validateProporties_typeFloat_valueBoolean.zipbin575 -> 539 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeFloat_valueString/normative-types-new-validateProporties_typeFloat_valueString.zipbin574 -> 538 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeInit_valueBoolean/normative-types-new-validateProporties_typeInit_valueBoolean.zipbin574 -> 538 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeInit_valueFloat/normative-types-new-validateProporties_typeInit_valueFloat.zipbin572 -> 536 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeInit_valueString/normative-types-new-validateProporties_typeInit_valueString.zipbin572 -> 536 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeList_valueUrlCredential/normative-types-new-validateProporties_typeList_valueUrlCredential.zipbin717 -> 685 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeMap_valueUrlCredential/normative-types-new-validateProporties_typeMap_valueUrlCredential.zipbin628 -> 593 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeTestDataType/normative-types-new-validateProporties_typeMap.zipbin638 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeTestDataType/normative-types-new-validateProporties_typeTestDataType.zipbin0 -> 608 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importTypesTest/myHeatStack1/myHeatStack1.zipbin401 -> 400 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importTypesTest/myHeatStack2/myHeatStack2.zipbin386 -> 423 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/CPWithAttributes.yml9
-rw-r--r--asdc-tests/tarball.xml71
-rw-r--r--asdctool/.gitignore1
-rw-r--r--asdctool/.pydevproject5
-rw-r--r--asdctool/pom.xml275
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/App.java66
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/Utils.java4
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/DataMigration.java8
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/GraphJsonValidator.java57
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/GraphMLConverter.java44
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/PopulateComponentCache.java60
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/RestUtils.java2
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/TitanGraphInitializer.java404
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/UpdatePropertyOnVertex.java20
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/Migration.java17
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/MigrationException.java9
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/MigrationMsg.java36
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/MigrationOperationUtils.java119
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/AddGroupUuid.java9
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/AllowMultipleHeats.java14
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/AppConfig.java121
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/ServiceMigration.java529
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/VfcNamingAlignment.java3
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1610/TitanFixUtils.java7
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1610/ToscaArtifactsAlignment.java2
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1702/DataTypesUpdate.java428
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1702/Migration1702.java1408
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/Migration1707.java37
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/Migration1707Config.java240
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/MigrationTitanStrategy.java13
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/MigrationUtils.java27
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/RenameGraphPropertyKeys.java38
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/ToscaNamesUpdate.java368
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/ToscaTemplateRegeneration.java160
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/VfModulesPropertiesAdding.java227
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/CategoriesUtils.java25
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ComponentMigration.java48
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/JsonModelMigration.java90
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/MigrationByIdDerivedNodeTypeResolver.java23
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/NormativesMigration.java38
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/NormativesResolver.java81
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ResourceVersionMigration.java22
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ResourcesCategoriesMigration.java150
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ServiceCategoriesMigration.java46
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ServiceVersionMigration.java23
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ServicesMigration.java107
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/UserStatesMigration.java159
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/UsersMigration.java58
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/VFResourcesMigration.java53
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/VersionMigration.java126
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/relations/FulfilledCapabilitiesMigrationService.java84
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/relations/FulfilledCapabilityRequirementMigrationService.java164
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/relations/FulfilledRequirementsMigrationService.java84
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/relations/RequirementsCapabilitiesMigrationService.java91
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/main/DataSchemaMenu.java16
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/main/EsToCassandraDataMigrationMenu.java3
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/main/ExportImportMenu.java24
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/main/MigrationMenu.java116
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/main/UpdateIsVnfMenu.java2
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/servlets/EntryPoint.java (renamed from ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/BreadCrumbsButtonsEnum.java)28
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/servlets/ExportImportTitanServlet.java187
-rw-r--r--asdctool/src/main/resources/config/configuration.yaml288
-rw-r--r--asdctool/src/main/resources/config/dataTypes.yml1123
-rw-r--r--asdctool/src/main/resources/config/error-configuration.yaml18
-rw-r--r--asdctool/src/main/resources/config/groupTypes.yml72
-rw-r--r--asdctool/src/main/resources/config/logback.xml4
-rw-r--r--asdctool/src/main/resources/config/titan-migration.properties4
-rw-r--r--asdctool/src/main/resources/config/titan.properties1
-rw-r--r--asdctool/src/main/resources/scripts/dataMigration.sh29
-rw-r--r--asdctool/src/main/resources/scripts/dataMigration1702.sh35
-rw-r--r--asdctool/src/main/resources/scripts/dataMigration1707.sh35
-rw-r--r--asdctool/src/main/resources/scripts/sdcSchemaFileImport.sh33
-rw-r--r--asdctool/src/main/resources/scripts/titanSchemaCreation.sh33
-rw-r--r--asdctool/src/main/resources/scripts/vfModulePropertiesAdding.sh33
-rw-r--r--asdctool/src/test/java/org/openecomp/sdc/asdctool/AppTest.java (renamed from ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/GeneralCanvasItemsEnum.java)39
-rw-r--r--asdctool/tarball.xml50
-rw-r--r--catalog-be/.pydevproject5
-rw-r--r--catalog-be/pom.xml642
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditingLogFormatConstants.java50
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditingLogFormatUtil.java25
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/CambriaHandler.java192
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngine.java22
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineClusterHealth.java9
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionNotificationSender.java10
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/JsonContainerResourceInstance.java37
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/PublishNotificationRunnable.java4
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ServiceDistributionArtifactsBuilder.java137
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/TestQueue.java4
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/VfModuleArtifactPayload.java65
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AdditionalInformationBusinessLogic.java14
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactsBusinessLogic.java2267
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AttributeBusinessLogic.java53
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/BaseBusinessLogic.java504
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CategoriesImportManager.java24
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CommonImportManager.java6
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogic.java724
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogic.java1416
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogic.java3
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ConsumerBusinessLogic.java6
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CsarValidationUtils.java100
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogic.java486
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogic.java1523
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/HealthCheckBusinessLogic.java3
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/IDeploymentArtifactTypeConfigGetter.java4
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ImportUtils.java24
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InformationDeployedArtifactsBusinessLogic.java4
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogic.java1190
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManager.java2
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductBusinessLogic.java53
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductComponentInstanceBusinessLogic.java13
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PropertyBusinessLogic.java279
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogic.java2837
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceImportManager.java67
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogic.java509
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceComponentInstanceBusinessLogic.java10
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/VFComponentInstanceBusinessLogic.java11
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CertificationChangeTransition.java75
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTransition.java180
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckinTransition.java67
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckoutTransition.java96
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifeCycleTransition.java75
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleBusinessLogic.java404
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/StartCertificationTransition.java64
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/UndoCheckoutTransition.java59
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/api/CategoryTypeEnum.java2
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/UiComponentDataConverter.java218
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/EcompIntImpl.java39
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/EcompRoleConverter.java3
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/EcompUserConverter.java12
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/ArtifactExternalServlet.java307
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/AssetMetadataConverter.java105
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/AssetsDataServlet.java507
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ArtifactMetadata.java20
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceAssetDetailedMetadata.java10
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceInstanceMetadata.java10
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/filters/BasicAuthenticationFilter.java2
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/filters/BeServletFilter.java20
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/impl/ComponentsUtils.java33
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/impl/DownloadArtifactLogic.java9
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactTemplateInfo.java12
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/info/GroupDefinitionInfo.java57
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/info/GroupTemplateInfo.java4
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/info/MergedArtifactInfo.java22
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/listen/BEAppContextListener.java9
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AbstractValidationsServlet.java236
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AdditionalInformationServlet.java12
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ArtifactServlet.java188
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AttributeServlet.java10
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/BeGenericServlet.java58
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/BeMonitoringServlet.java14
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentInstanceServlet.java248
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentServlet.java200
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConfigServlet.java4
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConsumerServlet.java2
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/CsarBuildServlet.java142
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ElementServlet.java32
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/GroupServlet.java115
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/InputsServlet.java161
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/LifecycleServlet.java69
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/PropertyServlet.java140
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/RepresentationUtils.java11
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourceArtifactDownloadServlet.java37
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourceUploadServlet.java9
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourcesServlet.java47
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ServiceServlet.java100
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesFetchServlet.java5
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesUploadServlet.java43
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/UserAdminServlet.java18
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/switchover/detector/SwitchoverDetector.java16
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ArtifactTypes.java1
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CapabiltyRequirementConvertor.java89
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CsarUtils.java1255
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/tosca/PropertyConvertor.java5
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaExportHandler.java593
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaUtils.java4
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/IToscaMetadata.java3
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/SubstitutionMapping.java14
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaMetadata.java36
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTopolgyTemplate.java8
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/VfModuleToscaMetadata.java9
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/user/IUserBusinessLogic.java5
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/user/UserAdminValidator.java3
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/user/UserBusinessLogic.java33
-rw-r--r--catalog-be/src/main/resources/application-context.xml8
-rw-r--r--catalog-be/src/main/resources/config/Artifact-Generator.properties264
-rw-r--r--catalog-be/src/main/resources/config/SDC.zipbin0 -> 29236 bytes
-rw-r--r--catalog-be/src/main/resources/config/configuration.yaml254
-rw-r--r--catalog-be/src/main/resources/config/distribution-engine-configuration.yaml6
-rw-r--r--catalog-be/src/main/resources/config/error-configuration.yaml116
-rw-r--r--catalog-be/src/main/resources/config/logback.xml106
-rw-r--r--catalog-be/src/main/resources/config/titan.properties1
-rw-r--r--catalog-be/src/main/resources/elasticsearch.yml16
-rw-r--r--catalog-be/src/main/resources/import/tosca/capability-types/capabilityTypes.yml2
-rw-r--r--catalog-be/src/main/resources/import/tosca/capability-types/capabilityTypes.zipbin1385 -> 1402 bytes
-rw-r--r--catalog-be/src/main/resources/import/tosca/categories/categoryTypes.yml33
-rw-r--r--catalog-be/src/main/resources/import/tosca/categories/categoryTypes.zipbin848 -> 1061 bytes
-rw-r--r--catalog-be/src/main/resources/import/tosca/data-types/dataTypes.yml409
-rw-r--r--catalog-be/src/main/resources/import/tosca/data-types/dataTypes.zipbin3456 -> 5243 bytes
-rw-r--r--catalog-be/src/main/resources/import/tosca/group-types/groupTypes.yml55
-rw-r--r--catalog-be/src/main/resources/import/tosca/group-types/groupTypes.zipbin523 -> 1088 bytes
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types.zipbin0 -> 72549 bytes
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/Generic_Service/Generic_Service.json21
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/Generic_Service/Generic_Service.yml5
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/Generic_Service/Generic_Service.zipbin0 -> 289 bytes
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/Generic_VF/Generic_VF.json21
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/Generic_VF/Generic_VF.yml27
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/Generic_VF/Generic_VF.zipbin0 -> 436 bytes
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/Generic_VFC/Generic_VFC.json21
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/Generic_VFC/Generic_VFC.yml50
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/Generic_VFC/Generic_VFC.zipbin0 -> 577 bytes
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/abstractSubstitute/abstractSubstitute.yml7
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/abstractSubstitute/abstractSubstitute.zipbin469 -> 469 bytes
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/cinderVolume/cinderVolume.yml118
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/cinderVolume/cinderVolume.zipbin1425 -> 1229 bytes
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/contrailAbstractSubstitute/contrailAbstractSubstitute.yml7
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/contrailAbstractSubstitute/contrailAbstractSubstitute.zipbin1017 -> 1017 bytes
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/contrailCompute/contrailCompute.yml11
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/contrailCompute/contrailCompute.zipbin781 -> 786 bytes
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/contrailNetworkRules/contrailNetworkRules.yml7
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/contrailNetworkRules/contrailNetworkRules.zipbin675 -> 675 bytes
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/contrailPort/contrailPort.yml9
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/contrailPort/contrailPort.zipbin720 -> 727 bytes
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/contrailV2NetworkRules/contrailV2NetworkRules.yml7
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/contrailV2NetworkRules/contrailV2NetworkRules.zipbin638 -> 638 bytes
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/contrailV2VLANSubInterface/contrailV2VLANSubInterface.json15
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/contrailV2VLANSubInterface/contrailV2VLANSubInterface.yml70
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/contrailV2VLANSubInterface/contrailV2VLANSubInterface.zipbin0 -> 746 bytes
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/contrailV2VirtualMachineInterface/contrailV2VirtualMachineInterface.yml58
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/contrailV2VirtualMachineInterface/contrailV2VirtualMachineInterface.zipbin718 -> 740 bytes
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/contrailV2VirtualNetwork/contrailV2VirtualNetwork.yml9
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/contrailV2VirtualNetwork/contrailV2VirtualNetwork.zipbin764 -> 1014 bytes
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/contrailVirtualNetwork/contrailVirtualNetwork.yml11
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/contrailVirtualNetwork/contrailVirtualNetwork.zipbin826 -> 833 bytes
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/eline/eline.yml1
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/eline/eline.zipbin321 -> 683 bytes
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/extCp/extCp.json21
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/extCp/extCp.yml53
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/extCp/extCp.zipbin0 -> 790 bytes
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/extVl/extVl.json21
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/extVl/extVl.yml50
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/extVl/extVl.zipbin0 -> 767 bytes
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/globalCompute/globalCompute.json20
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/globalCompute/globalCompute.yml1300
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/globalCompute/globalCompute.zipbin0 -> 3932 bytes
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/globalNetwork/globalNetwork.json21
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/globalNetwork/globalNetwork.yml (renamed from ui-ci/src/main/resources/Files/VL.yml)8
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/globalNetwork/globalNetwork.zipbin0 -> 353 bytes
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/globalPort/globalPort.json15
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/globalPort/globalPort.yml334
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/globalPort/globalPort.zipbin0 -> 1245 bytes
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/internalVl/internalVl.json21
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/internalVl/internalVl.yml6
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/internalVl/internalVl.zipbin0 -> 284 bytes
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/neutronNet/neutronNet.yml9
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/neutronNet/neutronNet.zipbin972 -> 979 bytes
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/neutronPort/neutronPort.yml16
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/neutronPort/neutronPort.zipbin1192 -> 1320 bytes
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/novaServer/novaServer.json6
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/novaServer/novaServer.yml72
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/novaServer/novaServer.zipbin1840 -> 1848 bytes
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/securityRules/securityRules.yml9
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/securityRules/securityRules.zipbin692 -> 690 bytes
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/subInterface/subInterface.json15
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/subInterface/subInterface.yml4
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/subInterface/subInterface.zipbin0 -> 384 bytes
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/vl/vl.zipbin355 -> 355 bytes
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/volume/volume.json20
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/volume/volume.yml7
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/volume/volume.zipbin0 -> 308 bytes
-rw-r--r--catalog-be/src/main/resources/import/tosca/normative-types/compute/compute.json6
-rw-r--r--catalog-be/src/main/resources/import/tosca/policy-types/policyTypes.zipbin673 -> 673 bytes
-rw-r--r--catalog-be/src/main/resources/import/tosca/users/importUsers.yaml4
-rw-r--r--catalog-be/src/main/resources/portal.properties6
-rw-r--r--catalog-be/src/main/resources/scripts/import/tosca/importHeatTypes.py32
-rw-r--r--catalog-be/src/main/resources/scripts/import/tosca/importHeatTypes1.py97
-rw-r--r--catalog-be/src/main/resources/scripts/import/tosca/importNormativeAll1.py118
-rw-r--r--catalog-be/src/main/resources/scripts/import/tosca/importNormativeNoHeatAndNormativeTypes.py135
-rw-r--r--catalog-be/src/main/resources/scripts/import/tosca/importNormativeTypes.py2
-rw-r--r--catalog-be/src/main/resources/scripts/import/tosca/upgradeHeatTypes1707.py113
-rw-r--r--catalog-be/src/main/resources/scripts/import/tosca/upgradeNormative.py18
-rw-r--r--catalog-be/src/main/resources/scripts/import/tosca/upgradeNormativeVersion.py42
-rw-r--r--catalog-be/src/main/resources/scripts/import/tosca/upgradeNormativeVersionProd1702_3537.py129
-rw-r--r--catalog-be/src/main/resources/swagger/lib/backbone-min.js22
-rw-r--r--catalog-be/src/main/resources/swagger/lib/handlebars-2.0.0.js22
-rw-r--r--catalog-be/src/main/resources/swagger/lib/highlight.7.3.pack.js22
-rw-r--r--catalog-be/src/main/resources/swagger/lib/jquery-1.8.0.min.js22
-rw-r--r--catalog-be/src/main/resources/swagger/lib/jquery.ba-bbq.min.js22
-rw-r--r--catalog-be/src/main/resources/swagger/lib/jquery.slideto.min.js20
-rw-r--r--catalog-be/src/main/resources/swagger/lib/jquery.wiggle.min.js22
-rw-r--r--catalog-be/src/main/resources/swagger/lib/marked.js22
-rw-r--r--catalog-be/src/main/resources/swagger/lib/swagger-oauth.js22
-rw-r--r--catalog-be/src/main/resources/swagger/lib/underscore-min.js22
-rw-r--r--catalog-be/src/main/resources/swagger/swagger-ui.js22
-rw-r--r--catalog-be/src/main/resources/swagger/swagger-ui.min.js22
-rw-r--r--catalog-be/src/main/webapp/WEB-INF/web.xml20
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/ElementOperationMock.java1
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/TestExternalConfiguration.java1
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/ZipUtil.java1
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/ComponentBusinessLogicTest.java7
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/GroupBusinessLogicTest.java263
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/ResourceImportManagerTest.java11
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/ServiceBusinessLogicTest.java217
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactBusinessLogicTest.java91
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogicTest.java820
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceInstanceBusinessLogicTest.java130
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CertificationChangeTransitionTest.java27
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTest.java69
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CheckinTest.java5
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CheckoutTest.java4
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/LifecycleTestBase.java73
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/UndoCheckoutTest.java4
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/distribution/ServiceDistributionArtifactsBuilderTest.java89
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/externalapi/servlet/AssetsDataServletTest.java201
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ResourceServletTest.java16
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/tosca/CsarUtilsTest.java91
-rw-r--r--catalog-be/src/test/resources/config/catalog-be/configuration.yaml94
-rw-r--r--catalog-be/src/test/resources/config/catalog-be/distribution-engine-configuration.yaml6
-rw-r--r--catalog-be/src/test/resources/config/catalog-be/error-configuration.yaml215
-rw-r--r--catalog-be/tarball.xml54
-rw-r--r--catalog-dao/pom.xml193
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/DAOTitanStrategy.java12
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/TitanClientStrategy.java7
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/ActionStatus.java19
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/BasicDao.java3
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/ESGenericIdDAO.java6
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/ArtifactCassandraDao.java2
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/AuditAccessor.java20
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/ComponentCassandraDao.java29
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/SdcSchemaFilesAccessor.java14
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/SdcSchemaFilesCassandraDao.java112
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/SdcSchemaBuilder.java180
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/SdcSchemaUtils.java90
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/Table.java10
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ArtifactTableDescription.java9
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/AuthEventTableDescription.java16
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/CategoryEventTableDescription.java17
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ComponentCacheTableDescription.java8
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ConsumerEventTableDefinition.java10
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribDeployEventTableDesc.java17
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribDownloadEventTableDesc.java11
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribEngineEventTableDesc.java19
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribNotifEventTableDesc.java21
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribStatusEventTableDesc.java17
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ExternalApiEventTableDesc.java27
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/GetCatHierEventTableDesc.java9
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/GetUebClusterEventTableDesc.java10
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/GetUsersListEventTableDesc.java9
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/OldExternalApiEventTableDesc.java94
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ResAdminEventTableDescription.java55
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/SdcSchemaFilesTableDescription.java83
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/UserAccessEventTableDescription.java1
-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/es/ElasticSearchClient.java2
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/GraphElementFactory.java4
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/ESCatalogDAO.java5
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/ESTimeBasedDao.java4
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/Neo4jPropertyDAO.java47
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/Neo4jResourceDAO.java103
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/Neo4jUsersDAO.java4
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/GraphVertex.java153
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/TitanDao.java890
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/types/EdgeLabelEnum.java50
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/types/EdgePropertyEnum.java25
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/types/GraphJsonProperty.java19
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/types/JsonParseFlagEnum.java9
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/types/VertexTypeEnum.java62
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/utils/IdBuilderUtils.java23
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/utils/JsonParserUtils.java66
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/GraphEdgeLabels.java44
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/GraphEdgePropertiesDictionary.java12
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/GraphPropertiesDictionary.java25
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/Neo4jClient.java47
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/Neo4jGraphBatchBuilder.java7
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/rest/HttpRestClient.java30
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/TitanGenericDao.java170
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/TitanGraphClient.java565
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ArtifactData.java74
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/CapabilityData.java7
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ComponentInstanceData.java25
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ComponentMetadataData.java57
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ConsumerData.java19
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ESArtifactData.java10
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ESSdcSchemaFilesData.java102
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/GroupInstanceData.java127
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/RelationshipTypeData.java12
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/RequirementData.java8
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ResourceMetadataData.java42
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/UserData.java4
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditingActionEnum.java8
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuthEvent.java2
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/ExternalApiEvent.java96
-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/resources/ArtifactDaoTest.java8
-rw-r--r--catalog-dao/src/test/java/org/openecomp/sdc/be/resources/ESUsersDAOTest.java64
-rw-r--r--catalog-dao/src/test/java/org/openecomp/sdc/be/resources/JsonParserUtilsTests.java56
-rw-r--r--catalog-dao/src/test/java/org/openecomp/sdc/be/resources/TitanGenericDaoTest.java40
-rw-r--r--catalog-dao/src/test/resources/config/catalog-dao/configuration.yaml24
-rw-r--r--catalog-fe/pom.xml675
-rw-r--r--catalog-fe/src/main/java/org/openecomp/sdc/fe/Constants.java20
-rw-r--r--catalog-fe/src/main/java/org/openecomp/sdc/fe/client/BackendClient.java4
-rw-r--r--catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/ConfigMgrServlet.java8
-rw-r--r--catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/ConfigServlet.java4
-rw-r--r--catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/FeHealthCheckServlet.java4
-rw-r--r--catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/FeProxyServlet.java3
-rw-r--r--catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/HealthCheckService.java2
-rw-r--r--catalog-fe/src/main/resources/config/configuration.yaml12
-rw-r--r--catalog-fe/src/main/resources/portal.properties7
-rw-r--r--catalog-fe/src/main/webapp/WEB-INF/web.xml169
-rw-r--r--catalog-fe/src/test/jasmine-standalone-2.0.0/lib/jasmine-2.0.0/boot.js20
-rw-r--r--catalog-fe/src/test/jasmine-standalone-2.0.0/lib/jasmine-2.0.0/console.js20
-rw-r--r--catalog-fe/src/test/jasmine-standalone-2.0.0/lib/jasmine-2.0.0/jasmine-html.js20
-rw-r--r--catalog-fe/src/test/jasmine-standalone-2.0.0/lib/jasmine-2.0.0/jasmine.js20
-rw-r--r--catalog-fe/src/test/jasmine-standalone-2.0.0/spec/PlayerSpec.js20
-rw-r--r--catalog-fe/src/test/jasmine-standalone-2.0.0/spec/SpecHelper.js20
-rw-r--r--catalog-fe/src/test/jasmine-standalone-2.0.0/src/Player.js22
-rw-r--r--catalog-fe/src/test/jasmine-standalone-2.0.0/src/Song.js22
-rw-r--r--catalog-fe/src/test/java/org/openecomp/sdc/ContentDisposiotionDelegator.java1
-rw-r--r--catalog-fe/src/test/java/org/openecomp/sdc/TestExternalConfiguration.java1
-rw-r--r--catalog-fe/src/test/resources/config/catalog-fe/configuration.yaml10
-rw-r--r--catalog-fe/src/test/spec/codeSpec.js20
-rw-r--r--catalog-fe/src/test/testScripts/filesContents.js22
-rw-r--r--catalog-fe/src/test/testScripts/jasmine-fixture.js20
-rw-r--r--catalog-fe/tarball.xml32
-rw-r--r--catalog-model/pom.xml247
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/AdditionalInformationDefinition.java22
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/ArtifactDefinition.java61
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/CapabilityDefinition.java211
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/Component.java163
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstInputsMap.java17
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstance.java55
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceAttribute.java4
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceInput.java16
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstancePropInput.java (renamed from ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/PropertyInfo.java)79
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceProperty.java65
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentParametersView.java118
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/DerivedNodeTypeResolver.java15
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/DistributionStatusEnum.java8
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupDefinition.java86
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupInstance.java57
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupInstanceProperty.java (renamed from catalog-model/src/main/java/org/openecomp/sdc/be/model/GetInputValueInfo.java)65
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupProperty.java20
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/InputDefinition.java46
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/InterfaceDefinition.java31
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/Operation.java43
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/Product.java4
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/PropertyDefinition.java131
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/PropertyValueDefinition.java1
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/RequirementAndRelationshipPair.java35
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/RequirementDefinition.java217
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/Resource.java40
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/Service.java34
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/TargetCapabilityRelDef.java9
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadPropInfo.java9
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/ApplicationDataTypeCache.java7
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/ComponentCache.java43
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/DaoInfo.java27
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/jobs/CheckAndUpdateJob.java5
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/jobs/Job.java21
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/jobs/OverrideJob.java5
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/jobs/StoreJob.java6
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/heat/HeatParameterType.java3
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/datamodel/NodeType.java88
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/datamodel/TopologyTemplate.java199
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/datamodel/ToscaElement.java277
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/datamodel/ToscaElementTypeEnum.java29
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/enums/JsonConstantKeysEnum.java22
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ArtifactsOperations.java623
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/BaseOperation.java1316
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ByToscaNameDerivedNodeTypeResolver.java35
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/CategoryOperation.java73
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/GroupsOperation.java309
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/InstancesOperation.java5
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/NodeTemplateOperation.java1740
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/NodeTypeOperation.java774
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/TopologyTemplateOperation.java1037
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaDataOperation.java11
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementLifecycleOperation.java1192
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperation.java1198
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaOperationFacade.java2123
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/utils/ModelConverter.java1258
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IAdditionalInformationOperation.java56
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IArtifactOperation.java14
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICapabilityInstanceOperation.java39
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICapabilityOperation.java30
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICapabilityTypeOperation.java9
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IComponentInstanceOperation.java139
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IComponentOperation.java12
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IConsumerOperation.java23
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IDataTypeOperation.java3
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IElementOperation.java30
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGraphLockOperation.java3
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGroupInstanceOperation.java101
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGroupOperation.java79
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGroupTypeOperation.java12
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IInputsOperation.java32
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IInterfaceLifecycleOperation.java45
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ILifecycleOperation.java27
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IPolicyTypeOperation.java3
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IProductOperation.java3
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IPropertyOperation.java31
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IRequirementOperation.java30
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IResourceOperation.java67
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IServiceOperation.java31
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IUserAdminOperation.java8
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ToscaDefinitionPathCalculator.java12
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AbstractOperation.java8
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AdditionalInformationOperation.java346
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ArtifactOperation.java271
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AttributeOperation.java8
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CacheMangerOperation.java44
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityInstanceOperation.java363
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityOperation.java62
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityTypeOperation.java125
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperation.java832
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ComponentOperation.java491
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ConsumerOperation.java14
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CsarOperation.java6
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/DaoStatusConverter.java3
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ElementOperation.java236
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GraphLockOperation.java81
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupInstanceOperation.java1701
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupOperation.java879
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupTypeOperation.java99
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/HeatParametersOperation.java44
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/InputsOperation.java466
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/InterfaceLifecycleOperation.java468
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/LifecycleOperation.java326
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/OnboardingClient.java3
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/PolicyTypeOperation.java49
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ProductOperation.java306
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/PropertyOperation.java223
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/RequirementOperation.java683
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ResourceOperation.java643
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ServiceOperation.java647
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ToscaDefinitionPathCalculatorImpl.java27
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/UniqueIdBuilder.java27
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/UserAdminOperation.java161
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/migration/MigrationErrorInformer.java39
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/utils/ComponentValidationUtils.java53
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/utils/GraphDeleteUtil.java29
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/ToscaPropertyType.java38
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatBooleanConverter.java2
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatCommaDelimitedListConverter.java12
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatNumberConverter.java2
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatStringConverter.java14
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/IntegerConverter.java3
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ListConverter.java6
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/MapConverter.java4
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaListValueConverter.java17
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaMapValueConverter.java130
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaValueBaseConverter.java36
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/DataTypeValidatorConverter.java83
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/ListValidator.java10
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/MapValidator.java14
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/PropertyTypeValidator.java10
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/StringValidator.java20
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiCategories.java31
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiComponentDataTransfer.java255
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiComponentMetadata.java318
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiResourceDataTransfer.java93
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiResourceMetadata.java101
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiServiceDataTransfer.java29
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiServiceMetadata.java55
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/unittests/utils/FactoryUtils.java12
-rw-r--r--catalog-model/src/test/java/org/openecomp/sdc/be/model/ModelTestBase.java3
-rw-r--r--catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/JsonObjectTest.java12
-rw-r--r--catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/AdditionalInformationOperationTest.java36
-rw-r--r--catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ArtifactOperationTest.java172
-rw-r--r--catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/CapabilityTypeOperationTest.java45
-rw-r--r--catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperationSpringTest.java94
-rw-r--r--catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperationTest.java23
-rw-r--r--catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ComponentOperationTest.java102
-rw-r--r--catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ElementOperationTest.java3
-rw-r--r--catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/HeatParametersOperationTest.java60
-rw-r--r--catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/InterfaceOperationTest.java48
-rw-r--r--catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/LifecycleOperationTest.java778
-rw-r--r--catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/PolicyTypeOperationTest.java12
-rw-r--r--catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/PropertyOperationTest.java49
-rw-r--r--catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/RequirementOperationTest.java54
-rw-r--r--catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ResourceInstanceOperationTest.java787
-rw-r--r--catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ResourceOperationTest.java381
-rw-r--r--catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ServiceOperationTest.java192
-rw-r--r--catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ToscaDefinitionPathCalculatorTest.java61
-rw-r--r--catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ToscaElementLifecycleOperationTest.java579
-rw-r--r--catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/UserAdminOperationTest.java62
-rw-r--r--catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/util/PrintGraph.java2
-rw-r--r--catalog-model/src/test/resources/application-context-test.xml2
-rw-r--r--catalog-ui/Gruntfile.js807
-rw-r--r--catalog-ui/README.md39
-rw-r--r--catalog-ui/SETTING-ENVIRONMENT.md36
-rw-r--r--catalog-ui/SETTING-MOCK-SERVER.md53
-rw-r--r--catalog-ui/_angular-cli.json53
-rw-r--r--catalog-ui/app/index.html392
-rw-r--r--catalog-ui/app/scripts/app.ts936
-rw-r--r--catalog-ui/app/scripts/directives/clicked-outside/clicked-outside-directive.ts131
-rw-r--r--catalog-ui/app/scripts/directives/custom-validation/custom-validation.ts55
-rw-r--r--catalog-ui/app/scripts/directives/download-artifact/download-artifact.ts141
-rw-r--r--catalog-ui/app/scripts/directives/ecomp-header/ecomp-header.ts235
-rw-r--r--catalog-ui/app/scripts/directives/edit-name-popover/edit-name-popover-directive.ts98
-rw-r--r--catalog-ui/app/scripts/directives/edit-name-popover/edit-name-popover-view.html1
-rw-r--r--catalog-ui/app/scripts/directives/elements/checkbox/checkbox.ts66
-rw-r--r--catalog-ui/app/scripts/directives/elements/radiobutton/radiobutton.ts71
-rw-r--r--catalog-ui/app/scripts/directives/ellipsis/ellipsis-directive.ts80
-rw-r--r--catalog-ui/app/scripts/directives/events/on-last-repeat/on-last-repeat.ts61
-rw-r--r--catalog-ui/app/scripts/directives/file-opener/file-opener.ts77
-rw-r--r--catalog-ui/app/scripts/directives/file-type/file-type.ts66
-rw-r--r--catalog-ui/app/scripts/directives/file-upload/file-upload.ts134
-rw-r--r--catalog-ui/app/scripts/directives/graphs-v2/common/common-graph-utils.ts361
-rw-r--r--catalog-ui/app/scripts/directives/graphs-v2/composition-graph/composition-graph.directive.ts555
-rw-r--r--catalog-ui/app/scripts/directives/graphs-v2/composition-graph/utils/composition-graph-general-utils.ts243
-rw-r--r--catalog-ui/app/scripts/directives/graphs-v2/composition-graph/utils/composition-graph-links-utils.ts347
-rw-r--r--catalog-ui/app/scripts/directives/graphs-v2/composition-graph/utils/composition-graph-nodes-utils.ts220
-rw-r--r--catalog-ui/app/scripts/directives/graphs-v2/composition-graph/utils/match-capability-requierment-utils.ts265
-rw-r--r--catalog-ui/app/scripts/directives/graphs-v2/deployment-graph/deployment-graph.directive.ts114
-rw-r--r--catalog-ui/app/scripts/directives/graphs-v2/deployment-graph/deployment-utils/deployment-graph-general-utils.ts24
-rw-r--r--catalog-ui/app/scripts/directives/graphs-v2/image-creator/image-creator.service.ts46
-rw-r--r--catalog-ui/app/scripts/directives/graphs-v2/palette/palette.directive.ts327
-rw-r--r--catalog-ui/app/scripts/directives/graphs-v2/relation-menu/relation-menu.ts113
-rw-r--r--catalog-ui/app/scripts/directives/info-tooltip/info-tooltip.ts60
-rw-r--r--catalog-ui/app/scripts/directives/invalid-characters/invalid-characters.ts72
-rw-r--r--catalog-ui/app/scripts/directives/layout/top-nav/top-nav.ts155
-rw-r--r--catalog-ui/app/scripts/directives/layout/top-progress/top-progress.ts57
-rw-r--r--catalog-ui/app/scripts/directives/loader/loader-directive.ts155
-rw-r--r--catalog-ui/app/scripts/directives/modal/sdc-modal.ts103
-rw-r--r--catalog-ui/app/scripts/directives/page-scroller/page-scroller.html22
-rw-r--r--catalog-ui/app/scripts/directives/page-scroller/page-scroller.less98
-rw-r--r--catalog-ui/app/scripts/directives/page-scroller/page-scroller.ts247
-rw-r--r--catalog-ui/app/scripts/directives/perfect-scrollbar/angular-perfect-scrollbar.ts159
-rw-r--r--catalog-ui/app/scripts/directives/print-graph-screen/print-graph-screen.ts211
-rw-r--r--catalog-ui/app/scripts/directives/property-types/data-type-fields-structure/data-type-fields-structure.ts165
-rw-r--r--catalog-ui/app/scripts/directives/property-types/type-list/type-list-directive.ts130
-rw-r--r--catalog-ui/app/scripts/directives/property-types/type-map/type-map-directive.ts157
-rw-r--r--catalog-ui/app/scripts/directives/punch-out/punch-out.ts99
-rw-r--r--catalog-ui/app/scripts/directives/sdc-tabs/sdc-single-tab/sdc-single-tab-directive.ts67
-rw-r--r--catalog-ui/app/scripts/directives/sdc-tabs/sdc-tabs-directive.ts69
-rw-r--r--catalog-ui/app/scripts/directives/structure-tree/structure-tree-directive.ts197
-rw-r--r--catalog-ui/app/scripts/directives/tag/tag-directive.ts71
-rw-r--r--catalog-ui/app/scripts/directives/tutorial/image-template.html7
-rw-r--r--catalog-ui/app/scripts/directives/tutorial/text-template.html4
-rw-r--r--catalog-ui/app/scripts/directives/tutorial/tutorial-directive.html22
-rw-r--r--catalog-ui/app/scripts/directives/tutorial/tutorial-directive.less213
-rw-r--r--catalog-ui/app/scripts/directives/tutorial/tutorial-directive.ts147
-rw-r--r--catalog-ui/app/scripts/directives/user-header-details/user-header-details-directive.ts72
-rw-r--r--catalog-ui/app/scripts/directives/utils/expand-collapse-menu-box/expand-collaps-menu-box.ts66
-rw-r--r--catalog-ui/app/scripts/directives/utils/expand-collapse/expand-collapse.ts136
-rw-r--r--catalog-ui/app/scripts/directives/utils/page-selector/page-selector.html9
-rw-r--r--catalog-ui/app/scripts/directives/utils/page-selector/page-selector.less51
-rw-r--r--catalog-ui/app/scripts/directives/utils/page-selector/page-selector.ts106
-rw-r--r--catalog-ui/app/scripts/directives/utils/sdc-keyboard-events/sdc-keyboard-events.ts106
-rw-r--r--catalog-ui/app/scripts/directives/utils/sdc-tags/sdc-tags.ts97
-rw-r--r--catalog-ui/app/scripts/directives/utils/sdc_error_tooltip/sdc_error_tooltip.html6
-rw-r--r--catalog-ui/app/scripts/directives/utils/sdc_error_tooltip/sdc_error_tooltip.ts109
-rw-r--r--catalog-ui/app/scripts/directives/utils/sdc_messages/sdc-message.ts179
-rw-r--r--catalog-ui/app/scripts/directives/utils/sdc_messages/sdc-messages.less10
-rw-r--r--catalog-ui/app/scripts/directives/utils/sdc_messages/sdc-messages.ts245
-rw-r--r--catalog-ui/app/scripts/directives/utils/sdc_messages/sdc_messages.html1
-rw-r--r--catalog-ui/app/scripts/directives/utils/smart-tooltip/smart-tooltip.ts85
-rw-r--r--catalog-ui/app/scripts/directives/utils/wizard_steps/sdc-wizard-steps.html16
-rw-r--r--catalog-ui/app/scripts/directives/utils/wizard_steps/sdc-wizard-steps.less69
-rw-r--r--catalog-ui/app/scripts/directives/utils/wizard_steps/sdc-wizard-steps.ts139
-rw-r--r--catalog-ui/app/scripts/filters/_category-name-filter.ts40
-rw-r--r--catalog-ui/app/scripts/filters/capitalize-filter.ts43
-rw-r--r--catalog-ui/app/scripts/filters/catalog-status-filter.ts41
-rw-r--r--catalog-ui/app/scripts/filters/category-icon-filter.ts54
-rw-r--r--catalog-ui/app/scripts/filters/category-type-filter.ts45
-rw-r--r--catalog-ui/app/scripts/filters/graph-resource-name-filter.ts47
-rw-r--r--catalog-ui/app/scripts/filters/product-subcategory-name-filter.ts39
-rw-r--r--catalog-ui/app/scripts/filters/relation-name-fllter.ts53
-rw-r--r--catalog-ui/app/scripts/filters/resource-type-filter.ts38
-rw-r--r--catalog-ui/app/scripts/filters/string-to-date-filter.ts34
-rw-r--r--catalog-ui/app/scripts/filters/truncate-filter.ts48
-rw-r--r--catalog-ui/app/scripts/models/activity.ts48
-rw-r--r--catalog-ui/app/scripts/models/app-config.ts232
-rw-r--r--catalog-ui/app/scripts/models/artifacts.ts115
-rw-r--r--catalog-ui/app/scripts/models/aschema-property.ts63
-rw-r--r--catalog-ui/app/scripts/models/attributes.ts139
-rw-r--r--catalog-ui/app/scripts/models/capability.ts116
-rw-r--r--catalog-ui/app/scripts/models/category.ts67
-rw-r--r--catalog-ui/app/scripts/models/comments.ts33
-rw-r--r--catalog-ui/app/scripts/models/components/component.ts828
-rw-r--r--catalog-ui/app/scripts/models/components/displayComponent.ts98
-rw-r--r--catalog-ui/app/scripts/models/components/product.ts109
-rw-r--r--catalog-ui/app/scripts/models/components/resource.ts185
-rw-r--r--catalog-ui/app/scripts/models/components/service.ts147
-rw-r--r--catalog-ui/app/scripts/models/componentsInstances/componentInstance.ts126
-rw-r--r--catalog-ui/app/scripts/models/componentsInstances/productInstance.ts34
-rw-r--r--catalog-ui/app/scripts/models/componentsInstances/resourceInstance.ts36
-rw-r--r--catalog-ui/app/scripts/models/componentsInstances/serviceInstance.ts35
-rw-r--r--catalog-ui/app/scripts/models/csar-component.ts36
-rw-r--r--catalog-ui/app/scripts/models/data-type-properties.ts65
-rw-r--r--catalog-ui/app/scripts/models/data-types.ts55
-rw-r--r--catalog-ui/app/scripts/models/distribution.ts66
-rw-r--r--catalog-ui/app/scripts/models/file-download.ts28
-rw-r--r--catalog-ui/app/scripts/models/graph/d2-node.ts31
-rw-r--r--catalog-ui/app/scripts/models/graph/graph-links/common-base-link.ts53
-rw-r--r--catalog-ui/app/scripts/models/graph/graph-links/common-ci-link-base.ts50
-rw-r--r--catalog-ui/app/scripts/models/graph/graph-links/composition-graph-links/composition-ci-simple-link.ts31
-rw-r--r--catalog-ui/app/scripts/models/graph/graph-links/composition-graph-links/composition-ci-ucpe-link.ts37
-rw-r--r--catalog-ui/app/scripts/models/graph/graph-links/links-factory.ts80
-rw-r--r--catalog-ui/app/scripts/models/graph/graphTooltip.ts38
-rw-r--r--catalog-ui/app/scripts/models/graph/link-menu.ts38
-rw-r--r--catalog-ui/app/scripts/models/graph/match-relation.ts109
-rw-r--r--catalog-ui/app/scripts/models/graph/nodes/base-common-node.ts73
-rw-r--r--catalog-ui/app/scripts/models/graph/nodes/common-ci-node-base.ts46
-rw-r--r--catalog-ui/app/scripts/models/graph/nodes/composition-graph-nodes/composition-ci-node-base.ts72
-rw-r--r--catalog-ui/app/scripts/models/graph/nodes/composition-graph-nodes/composition-ci-node-cp.ts48
-rw-r--r--catalog-ui/app/scripts/models/graph/nodes/composition-graph-nodes/composition-ci-node-service.ts42
-rw-r--r--catalog-ui/app/scripts/models/graph/nodes/composition-graph-nodes/composition-ci-node-ucpe.ts50
-rw-r--r--catalog-ui/app/scripts/models/graph/nodes/composition-graph-nodes/composition-ci-node-vf.ts41
-rw-r--r--catalog-ui/app/scripts/models/graph/nodes/composition-graph-nodes/composition-ci-node-vfc.ts33
-rw-r--r--catalog-ui/app/scripts/models/graph/nodes/nodes-factory.ts63
-rw-r--r--catalog-ui/app/scripts/models/graph/point.ts26
-rw-r--r--catalog-ui/app/scripts/models/graph/relationMenuObjects.ts138
-rw-r--r--catalog-ui/app/scripts/models/graph/relationship.ts107
-rw-r--r--catalog-ui/app/scripts/models/inputs.ts74
-rw-r--r--catalog-ui/app/scripts/models/instance-inputs-properties-map.ts39
-rw-r--r--catalog-ui/app/scripts/models/instances-inputs-map.ts39
-rw-r--r--catalog-ui/app/scripts/models/left-panel.ts33
-rw-r--r--catalog-ui/app/scripts/models/member.ts39
-rw-r--r--catalog-ui/app/scripts/models/modules/base-module.ts108
-rw-r--r--catalog-ui/app/scripts/models/properties.ts176
-rw-r--r--catalog-ui/app/scripts/models/requirement.ts91
-rw-r--r--catalog-ui/app/scripts/models/tab.ts47
-rw-r--r--catalog-ui/app/scripts/models/tooltip-data.ts28
-rw-r--r--catalog-ui/app/scripts/models/user.ts117
-rw-r--r--catalog-ui/app/scripts/models/validate.ts29
-rw-r--r--catalog-ui/app/scripts/modules/directive-module.ts106
-rw-r--r--catalog-ui/app/scripts/modules/filters.ts44
-rw-r--r--catalog-ui/app/scripts/modules/service-module.ts64
-rw-r--r--catalog-ui/app/scripts/modules/view-model-module.ts96
-rw-r--r--catalog-ui/app/scripts/services/activity-log-service.ts48
-rw-r--r--catalog-ui/app/scripts/services/angular-js-bridge-service.ts22
-rw-r--r--catalog-ui/app/scripts/services/available-icons-service.ts105
-rw-r--r--catalog-ui/app/scripts/services/cache-service.ts58
-rw-r--r--catalog-ui/app/scripts/services/category-resource-service.ts83
-rw-r--r--catalog-ui/app/scripts/services/components/component-service.ts698
-rw-r--r--catalog-ui/app/scripts/services/components/product-service.ts61
-rw-r--r--catalog-ui/app/scripts/services/components/resource-service.ts61
-rw-r--r--catalog-ui/app/scripts/services/components/service-service.ts97
-rw-r--r--catalog-ui/app/scripts/services/components/utils/composition-left-palette-service.ts248
-rw-r--r--catalog-ui/app/scripts/services/cookie-service.ts95
-rw-r--r--catalog-ui/app/scripts/services/data-types-service.ts129
-rw-r--r--catalog-ui/app/scripts/services/ecomp-service.ts54
-rw-r--r--catalog-ui/app/scripts/services/entity-service.ts114
-rw-r--r--catalog-ui/app/scripts/services/event-listener-service.ts78
-rw-r--r--catalog-ui/app/scripts/services/header-interceptor.ts93
-rw-r--r--catalog-ui/app/scripts/services/http-error-interceptor.ts118
-rw-r--r--catalog-ui/app/scripts/services/loader-service.ts26
-rw-r--r--catalog-ui/app/scripts/services/onboarding-service.ts103
-rw-r--r--catalog-ui/app/scripts/services/progress-service.ts112
-rw-r--r--catalog-ui/app/scripts/services/relation-icons-service.ts61
-rw-r--r--catalog-ui/app/scripts/services/sdc-version-service.ts48
-rw-r--r--catalog-ui/app/scripts/services/sharing-service.ts41
-rw-r--r--catalog-ui/app/scripts/services/url-tobase64-service.ts52
-rw-r--r--catalog-ui/app/scripts/services/user-resource-service.ts123
-rw-r--r--catalog-ui/app/scripts/utils/artifacts-utils.ts121
-rw-r--r--catalog-ui/app/scripts/utils/change-lifecycle-state-handler.ts151
-rw-r--r--catalog-ui/app/scripts/utils/common-utils.ts81
-rw-r--r--catalog-ui/app/scripts/utils/component-factory.ts181
-rw-r--r--catalog-ui/app/scripts/utils/component-instance-factory.ts85
-rw-r--r--catalog-ui/app/scripts/utils/constants.ts247
-rw-r--r--catalog-ui/app/scripts/utils/dictionary/dictionary.ts257
-rw-r--r--catalog-ui/app/scripts/utils/file-utils.ts73
-rw-r--r--catalog-ui/app/scripts/utils/functions.ts58
-rw-r--r--catalog-ui/app/scripts/utils/menu-handler.ts145
-rw-r--r--catalog-ui/app/scripts/utils/modals-handler.ts275
-rw-r--r--catalog-ui/app/scripts/utils/prototypes.ts155
-rw-r--r--catalog-ui/app/scripts/utils/validation-utils.ts173
-rw-r--r--catalog-ui/app/scripts/view-models/admin-dashboard/add-category-modal/add-category-modal-view-model.ts94
-rw-r--r--catalog-ui/app/scripts/view-models/admin-dashboard/admin-dashboard-view-model.ts82
-rw-r--r--catalog-ui/app/scripts/view-models/admin-dashboard/category-management/category-management-view-model.ts197
-rw-r--r--catalog-ui/app/scripts/view-models/admin-dashboard/user-management/user-management-view-model.ts220
-rw-r--r--catalog-ui/app/scripts/view-models/catalog/catalog-view-model.ts312
-rw-r--r--catalog-ui/app/scripts/view-models/catalog/catalog-view-tests.ts309
-rw-r--r--catalog-ui/app/scripts/view-models/component-viewer/activity-log/activity-log-view.html16
-rw-r--r--catalog-ui/app/scripts/view-models/component-viewer/activity-log/activity-log-view.less18
-rw-r--r--catalog-ui/app/scripts/view-models/component-viewer/component-viewer-view-model.ts211
-rw-r--r--catalog-ui/app/scripts/view-models/component-viewer/component-viewer.html55
-rw-r--r--catalog-ui/app/scripts/view-models/component-viewer/component-viewer.less148
-rw-r--r--catalog-ui/app/scripts/view-models/component-viewer/properties/product-properties-view.html76
-rw-r--r--catalog-ui/app/scripts/view-models/component-viewer/properties/properties-view.less128
-rw-r--r--catalog-ui/app/scripts/view-models/component-viewer/properties/resource-properties-view.html169
-rw-r--r--catalog-ui/app/scripts/view-models/component-viewer/properties/service-properties-view.html167
-rw-r--r--catalog-ui/app/scripts/view-models/dashboard/cover/dashboard-cover-view-model.ts91
-rw-r--r--catalog-ui/app/scripts/view-models/dashboard/cover/dashboard-cover-view.html1
-rw-r--r--catalog-ui/app/scripts/view-models/dashboard/dashboard-view-model-tests.ts276
-rw-r--r--catalog-ui/app/scripts/view-models/dashboard/dashboard-view-model.ts415
-rw-r--r--catalog-ui/app/scripts/view-models/dashboard/dashboard-view.html106
-rw-r--r--catalog-ui/app/scripts/view-models/forms/artifact-form/artifact-form-view-model.ts354
-rw-r--r--catalog-ui/app/scripts/view-models/forms/attribute-form/attribute-from-view-model.ts255
-rw-r--r--catalog-ui/app/scripts/view-models/forms/env-parameters-form/env-parameters-form.html39
-rw-r--r--catalog-ui/app/scripts/view-models/forms/env-parameters-form/env-parameters-form.less74
-rw-r--r--catalog-ui/app/scripts/view-models/forms/env-parameters-form/env-parameters-form.ts149
-rw-r--r--catalog-ui/app/scripts/view-models/forms/property-form/property-form-view-model.ts330
-rw-r--r--catalog-ui/app/scripts/view-models/forms/resource-instance-name-form/resource-instance-name-model.ts105
-rw-r--r--catalog-ui/app/scripts/view-models/modals/confirmation-modal/confirmation-modal-view-model.ts96
-rw-r--r--catalog-ui/app/scripts/view-models/modals/email-modal/email-modal-view-model.ts117
-rw-r--r--catalog-ui/app/scripts/view-models/modals/error-modal/error-403-view.html4
-rw-r--r--catalog-ui/app/scripts/view-models/modals/error-modal/error-view-model.ts43
-rw-r--r--catalog-ui/app/scripts/view-models/modals/message-modal/message-base-modal-model.ts64
-rw-r--r--catalog-ui/app/scripts/view-models/modals/message-modal/message-server-modal/server-message-modal-view-model.ts45
-rw-r--r--catalog-ui/app/scripts/view-models/modals/onboarding-modal/onboarding-modal-view-model.ts249
-rw-r--r--catalog-ui/app/scripts/view-models/onboard-vendor/onboard-vendor-view-model.ts148
-rw-r--r--catalog-ui/app/scripts/view-models/preloading/preloading-view.less107
-rw-r--r--catalog-ui/app/scripts/view-models/preloading/preloading-view.ts47
-rw-r--r--catalog-ui/app/scripts/view-models/support/support-view-model.ts38
-rw-r--r--catalog-ui/app/scripts/view-models/tabs/hierarchy/hierarchy-view-model.ts99
-rw-r--r--catalog-ui/app/scripts/view-models/tabs/hierarchy/hierarchy-view.html57
-rw-r--r--catalog-ui/app/scripts/view-models/tutorial-end/tutorial-end.ts42
-rw-r--r--catalog-ui/app/scripts/view-models/welcome/slide0.html50
-rw-r--r--catalog-ui/app/scripts/view-models/welcome/slide1.html34
-rw-r--r--catalog-ui/app/scripts/view-models/welcome/slide2.html26
-rw-r--r--catalog-ui/app/scripts/view-models/welcome/slide3.html27
-rw-r--r--catalog-ui/app/scripts/view-models/welcome/slide4.html29
-rw-r--r--catalog-ui/app/scripts/view-models/welcome/slide5.html27
-rw-r--r--catalog-ui/app/scripts/view-models/welcome/slide6.html26
-rw-r--r--catalog-ui/app/scripts/view-models/welcome/welcome-steps-controller.ts74
-rw-r--r--catalog-ui/app/scripts/view-models/welcome/welcome-view.html22
-rw-r--r--catalog-ui/app/scripts/view-models/welcome/welcome-view.ts267
-rw-r--r--catalog-ui/app/scripts/view-models/wizard/ReadMe.txt54
-rw-r--r--catalog-ui/app/scripts/view-models/wizard/artifact-deployment-step/artifact-deployment-step.html137
-rw-r--r--catalog-ui/app/scripts/view-models/wizard/artifact-deployment-step/artifact-deployment-step.less107
-rw-r--r--catalog-ui/app/scripts/view-models/wizard/artifact-deployment-step/artifact-deployment-step.ts228
-rw-r--r--catalog-ui/app/scripts/view-models/wizard/artifact-form-step/artifact-form-step-view-model.ts304
-rw-r--r--catalog-ui/app/scripts/view-models/wizard/artifact-form-step/artifact-form-step-view.html147
-rw-r--r--catalog-ui/app/scripts/view-models/wizard/artifact-form-step/artifact-form-step.less45
-rw-r--r--catalog-ui/app/scripts/view-models/wizard/artifact-information-step/artifact-information-step.html48
-rw-r--r--catalog-ui/app/scripts/view-models/wizard/artifact-information-step/artifact-information-step.less50
-rw-r--r--catalog-ui/app/scripts/view-models/wizard/artifact-information-step/artifact-information-step.ts168
-rw-r--r--catalog-ui/app/scripts/view-models/wizard/general-step/general-step.html270
-rw-r--r--catalog-ui/app/scripts/view-models/wizard/general-step/general-step.less34
-rw-r--r--catalog-ui/app/scripts/view-models/wizard/general-step/general-step.ts381
-rw-r--r--catalog-ui/app/scripts/view-models/wizard/hierarchy-step/hierarchy-step.html40
-rw-r--r--catalog-ui/app/scripts/view-models/wizard/hierarchy-step/hierarchy-step.less125
-rw-r--r--catalog-ui/app/scripts/view-models/wizard/hierarchy-step/hierarchy-step.ts149
-rw-r--r--catalog-ui/app/scripts/view-models/wizard/icons-step/icons-step.html26
-rw-r--r--catalog-ui/app/scripts/view-models/wizard/icons-step/icons-step.less55
-rw-r--r--catalog-ui/app/scripts/view-models/wizard/icons-step/icons-step.ts150
-rw-r--r--catalog-ui/app/scripts/view-models/wizard/properties-step/properties-step.html57
-rw-r--r--catalog-ui/app/scripts/view-models/wizard/properties-step/properties-step.less55
-rw-r--r--catalog-ui/app/scripts/view-models/wizard/properties-step/properties-step.ts123
-rw-r--r--catalog-ui/app/scripts/view-models/wizard/property-form/property-form-view-model-tests.ts163
-rw-r--r--catalog-ui/app/scripts/view-models/wizard/property-form/property-form-view-model.ts250
-rw-r--r--catalog-ui/app/scripts/view-models/wizard/property-form/property-form.html133
-rw-r--r--catalog-ui/app/scripts/view-models/wizard/property-form/property-form.less7
-rw-r--r--catalog-ui/app/scripts/view-models/wizard/wizard-creation-base.html12
-rw-r--r--catalog-ui/app/scripts/view-models/wizard/wizard-creation-base.less60
-rw-r--r--catalog-ui/app/scripts/view-models/wizard/wizard-creation-base.ts399
-rw-r--r--catalog-ui/app/scripts/view-models/wizard/wizard-state/create-wizard.ts114
-rw-r--r--catalog-ui/app/scripts/view-models/wizard/wizard-state/edit-wizard.ts164
-rw-r--r--catalog-ui/app/scripts/view-models/wizard/wizard-state/import-wizard.ts64
-rw-r--r--catalog-ui/app/scripts/view-models/workspace/tabs/activity-log/activity-log.ts122
-rw-r--r--catalog-ui/app/scripts/view-models/workspace/tabs/attributes/attributes-view-model.ts107
-rw-r--r--catalog-ui/app/scripts/view-models/workspace/tabs/composition/composition-view-model.ts232
-rw-r--r--catalog-ui/app/scripts/view-models/workspace/tabs/composition/tabs/artifacts/artifacts-view-model.ts255
-rw-r--r--catalog-ui/app/scripts/view-models/workspace/tabs/composition/tabs/details/details-view-model.ts132
-rw-r--r--catalog-ui/app/scripts/view-models/workspace/tabs/composition/tabs/properties-and-attributes/properties-view-model.ts228
-rw-r--r--catalog-ui/app/scripts/view-models/workspace/tabs/composition/tabs/relations/relations-view-model.ts81
-rw-r--r--catalog-ui/app/scripts/view-models/workspace/tabs/composition/tabs/relations/relations-view.html57
-rw-r--r--catalog-ui/app/scripts/view-models/workspace/tabs/composition/tabs/structure/structure-view.ts34
-rw-r--r--catalog-ui/app/scripts/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts-view-model.ts253
-rw-r--r--catalog-ui/app/scripts/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts-view.html149
-rw-r--r--catalog-ui/app/scripts/view-models/workspace/tabs/deployment/deployment-view-model.ts127
-rw-r--r--catalog-ui/app/scripts/view-models/workspace/tabs/distribution/disribution-status-modal/disribution-status-modal-view-model.ts67
-rw-r--r--catalog-ui/app/scripts/view-models/workspace/tabs/distribution/distribution-view-model.ts135
-rw-r--r--catalog-ui/app/scripts/view-models/workspace/tabs/general/general-view-model.ts379
-rw-r--r--catalog-ui/app/scripts/view-models/workspace/tabs/icons/icons-view-model.ts131
-rw-r--r--catalog-ui/app/scripts/view-models/workspace/tabs/information-artifacts/information-artifacts-view-model.ts150
-rw-r--r--catalog-ui/app/scripts/view-models/workspace/tabs/inputs/resource-input/resource-inputs-view-model.ts145
-rw-r--r--catalog-ui/app/scripts/view-models/workspace/tabs/inputs/resource-input/resource-inputs-view.html136
-rw-r--r--catalog-ui/app/scripts/view-models/workspace/tabs/inputs/service-input/service-inputs-view-model.ts246
-rw-r--r--catalog-ui/app/scripts/view-models/workspace/tabs/inputs/service-input/service-inputs-view.html205
-rw-r--r--catalog-ui/app/scripts/view-models/workspace/tabs/network-call-flow/network-call-flow-view-model.ts80
-rw-r--r--catalog-ui/app/scripts/view-models/workspace/tabs/product-hierarchy/product-hierarchy-view-model.ts134
-rw-r--r--catalog-ui/app/scripts/view-models/workspace/tabs/properties/properties-view-model.ts114
-rw-r--r--catalog-ui/app/scripts/view-models/workspace/tabs/req-and-capabilities/req-and-capabilities-view-model.ts165
-rw-r--r--catalog-ui/app/scripts/view-models/workspace/tabs/tosca-artifacts/tosca-artifacts-view-model.ts87
-rw-r--r--catalog-ui/app/scripts/view-models/workspace/workspace-view-model.ts703
-rw-r--r--catalog-ui/app/scripts/view-models/workspace/workspace.less144
-rw-r--r--catalog-ui/app/styles/app.less122
-rw-r--r--catalog-ui/app/styles/images/resource-icons/compute-uncertified.pngbin2598 -> 0 bytes
-rw-r--r--catalog-ui/app/styles/images/sprites/sprite-global.pngbin71883 -> 0 bytes
-rw-r--r--catalog-ui/app/styles/images/welcome/SD&C_Welcome15.jpgbin3088201 -> 0 bytes
-rw-r--r--catalog-ui/app/styles/images/welcome/SD&C_Welcome15_b.jpgbin3082618 -> 0 bytes
-rw-r--r--catalog-ui/app/styles/images/welcome/bg/001.jpgbin278335 -> 0 bytes
-rw-r--r--catalog-ui/app/styles/images/welcome/bg/002.jpgbin503913 -> 0 bytes
-rw-r--r--catalog-ui/app/styles/images/welcome/bg/003.pngbin1470296 -> 0 bytes
-rw-r--r--catalog-ui/app/styles/images/welcome/bg/004.pngbin2906163 -> 0 bytes
-rw-r--r--catalog-ui/app/styles/images/welcome/bg/bg02.pngbin141906 -> 0 bytes
-rw-r--r--catalog-ui/app/styles/images/welcome/bg/bg03.pngbin148913 -> 0 bytes
-rw-r--r--catalog-ui/app/styles/images/welcome/bg/connection02.pngbin2735 -> 0 bytes
-rw-r--r--catalog-ui/app/styles/images/welcome/bg/connection03.pngbin7056 -> 0 bytes
-rw-r--r--catalog-ui/app/styles/images/welcome/bg/connection04.pngbin2712 -> 0 bytes
-rw-r--r--catalog-ui/app/styles/images/welcome/bg/global.pngbin58238 -> 0 bytes
-rw-r--r--catalog-ui/app/styles/images/welcome/bg/shape02.pngbin163714 -> 0 bytes
-rw-r--r--catalog-ui/app/styles/images/welcome/bg/shape03.pngbin89805 -> 0 bytes
-rw-r--r--catalog-ui/app/styles/images/welcome/bg/shape04.pngbin127232 -> 0 bytes
-rw-r--r--catalog-ui/app/styles/images/welcome/bg/shape05.pngbin299086 -> 0 bytes
-rw-r--r--catalog-ui/app/styles/images/welcome/laptop.pngbin83877 -> 0 bytes
-rw-r--r--catalog-ui/app/styles/images/welcome/logo_att.pngbin19214 -> 0 bytes
-rw-r--r--catalog-ui/app/styles/images/welcome/ss-01.pngbin3413794 -> 0 bytes
-rw-r--r--catalog-ui/app/styles/images/welcome/ss-02.pngbin67191 -> 0 bytes
-rw-r--r--catalog-ui/app/styles/images/welcome/ss-03.pngbin46870 -> 0 bytes
-rw-r--r--catalog-ui/app/styles/welcome-style.less651
-rw-r--r--catalog-ui/app/third-party/ng-infinite-scroll/.npmignore3
-rw-r--r--catalog-ui/app/third-party/ng-infinite-scroll/.travis.yml12
-rw-r--r--catalog-ui/app/third-party/ng-infinite-scroll/Gruntfile.coffee110
-rw-r--r--catalog-ui/app/third-party/ng-infinite-scroll/LICENSE22
-rw-r--r--catalog-ui/app/third-party/ng-infinite-scroll/README.md71
-rw-r--r--catalog-ui/app/third-party/ng-infinite-scroll/bower.json16
-rw-r--r--catalog-ui/app/third-party/ng-infinite-scroll/build/ng-infinite-scroll.js209
-rw-r--r--catalog-ui/app/third-party/ng-infinite-scroll/build/ng-infinite-scroll.min.js22
-rw-r--r--catalog-ui/app/third-party/ng-infinite-scroll/package.json80
-rw-r--r--catalog-ui/app/third-party/ng-infinite-scroll/src/infinite-scroll.coffee209
-rw-r--r--catalog-ui/app/third-party/ng-infinite-scroll/test/protractor-local.conf.js27
-rw-r--r--catalog-ui/app/third-party/ng-infinite-scroll/test/protractor-shared.conf.js26
-rw-r--r--catalog-ui/app/third-party/ng-infinite-scroll/test/protractor-travis.conf.js32
-rw-r--r--catalog-ui/app/third-party/ng-infinite-scroll/test/spec/ng-infinite-scroll.spec.coffee221
-rw-r--r--catalog-ui/bower dependecies29
-rw-r--r--catalog-ui/bower.json42
-rw-r--r--catalog-ui/build_catalog_ui.bat17
-rw-r--r--catalog-ui/build_catalog_ui.sh74
-rw-r--r--catalog-ui/configurations/dev.js431
-rw-r--r--catalog-ui/configurations/dev.json430
-rw-r--r--catalog-ui/configurations/menu.js (renamed from catalog-ui/configurations/menu.json)85
-rw-r--r--catalog-ui/configurations/mock.json13
-rw-r--r--catalog-ui/configurations/prod.js432
-rw-r--r--catalog-ui/configurations/prod.json432
-rw-r--r--catalog-ui/configurations/validation.json12
-rw-r--r--catalog-ui/docs/colors.jpgbin80399 -> 0 bytes
-rw-r--r--catalog-ui/e2e/app.e2e-spec.ts14
-rw-r--r--catalog-ui/e2e/app.po.ts11
-rw-r--r--catalog-ui/e2e/tsconfig.json16
-rw-r--r--catalog-ui/karma.conf.js43
-rw-r--r--catalog-ui/non_bower_components/cytoscape.js-edge-editation/README.md58
-rw-r--r--catalog-ui/non_bower_components/cytoscape.js-edge-editation/index.html169
-rw-r--r--catalog-ui/package.json145
-rw-r--r--catalog-ui/pom.xml386
-rw-r--r--catalog-ui/protractor.conf.js32
-rw-r--r--catalog-ui/server-mock/mock-data/artifact/artifact-types.json23
-rw-r--r--catalog-ui/server-mock/mock-data/category/category.json65
-rw-r--r--catalog-ui/server-mock/mock-data/element/element.json2915
-rw-r--r--catalog-ui/server-mock/mock-data/resource/properties.json35
-rw-r--r--catalog-ui/server-mock/mock-data/resource/resource.json153
-rw-r--r--catalog-ui/server-mock/mock-data/resources/resourcesAbstract.json284
-rw-r--r--catalog-ui/server-mock/mock-data/resources/resourcesNotAbstract.json510
-rw-r--r--catalog-ui/server-mock/mock-data/template/template.json37
-rw-r--r--catalog-ui/server-mock/mock-data/user/user.json7
-rw-r--r--catalog-ui/server-mock/mock-server.js140
-rw-r--r--catalog-ui/server-mock/routes/property.js45
-rw-r--r--catalog-ui/server-mock/routes/resource.js60
-rw-r--r--catalog-ui/server-mock/routes/resources.js38
-rw-r--r--catalog-ui/server-mock/routes/template.js45
-rw-r--r--catalog-ui/server-mock/routes/user.js45
-rw-r--r--catalog-ui/src/app/_favicon.png (renamed from catalog-ui/app/_favicon.png)bin6364 -> 6364 bytes
-rw-r--r--catalog-ui/src/app/app.ts837
-rw-r--r--catalog-ui/src/app/directives/capabilities-and-requirements/capabilities-requirements-list.less (renamed from catalog-ui/app/scripts/view-models/workspace/tabs/composition/tabs/relations/relations.less)41
-rw-r--r--catalog-ui/src/app/directives/capabilities-and-requirements/capability/capabilities-list-directive.ts40
-rw-r--r--catalog-ui/src/app/directives/capabilities-and-requirements/capability/capabilities-list-view.html14
-rw-r--r--catalog-ui/src/app/directives/capabilities-and-requirements/requirement/requirements-list-directive.ts71
-rw-r--r--catalog-ui/src/app/directives/capabilities-and-requirements/requirement/requirements-list-view.html19
-rw-r--r--catalog-ui/src/app/directives/clicked-outside/clicked-outside-directive.ts110
-rw-r--r--catalog-ui/src/app/directives/custom-validation/custom-validation.ts32
-rw-r--r--catalog-ui/src/app/directives/download-artifact/download-artifact.ts125
-rw-r--r--catalog-ui/src/app/directives/ecomp-footer/ecomp-footer.html8
-rw-r--r--catalog-ui/src/app/directives/ecomp-footer/ecomp-footer.less47
-rw-r--r--catalog-ui/src/app/directives/ecomp-footer/ecomp-footer.ts33
-rw-r--r--catalog-ui/src/app/directives/ecomp-header/ecomp-header.html (renamed from catalog-ui/app/scripts/directives/ecomp-header/ecomp-header.html)4
-rw-r--r--catalog-ui/src/app/directives/ecomp-header/ecomp-header.less (renamed from catalog-ui/app/scripts/directives/ecomp-header/ecomp-header.less)2
-rw-r--r--catalog-ui/src/app/directives/ecomp-header/ecomp-header.ts217
-rw-r--r--catalog-ui/src/app/directives/edit-name-popover/edit-module-name-popover.html (renamed from catalog-ui/app/scripts/directives/edit-name-popover/edit-module-name-popover.html)0
-rw-r--r--catalog-ui/src/app/directives/edit-name-popover/edit-name-popover-directive.ts77
-rw-r--r--catalog-ui/src/app/directives/edit-name-popover/edit-name-popover-view.html1
-rw-r--r--catalog-ui/src/app/directives/edit-name-popover/edit-name-popover.less (renamed from catalog-ui/app/scripts/directives/edit-name-popover/edit-name-popover.less)17
-rw-r--r--catalog-ui/src/app/directives/elements/checkbox/checkbox.html (renamed from catalog-ui/app/scripts/directives/elements/checkbox/checkbox.html)1
-rw-r--r--catalog-ui/src/app/directives/elements/checkbox/checkbox.less (renamed from catalog-ui/app/scripts/directives/elements/checkbox/checkbox.less)0
-rw-r--r--catalog-ui/src/app/directives/elements/checkbox/checkbox.ts43
-rw-r--r--catalog-ui/src/app/directives/elements/radiobutton/radiobutton.html (renamed from catalog-ui/app/scripts/directives/elements/radiobutton/radiobutton.html)0
-rw-r--r--catalog-ui/src/app/directives/elements/radiobutton/radiobutton.less (renamed from catalog-ui/app/scripts/directives/elements/radiobutton/radiobutton.less)0
-rw-r--r--catalog-ui/src/app/directives/elements/radiobutton/radiobutton.ts48
-rw-r--r--catalog-ui/src/app/directives/ellipsis/ellipsis-directive.html (renamed from catalog-ui/app/scripts/directives/ellipsis/ellipsis-directive.html)0
-rw-r--r--catalog-ui/src/app/directives/ellipsis/ellipsis-directive.less (renamed from catalog-ui/app/scripts/directives/ellipsis/ellipsis-directive.less)0
-rw-r--r--catalog-ui/src/app/directives/ellipsis/ellipsis-directive.ts57
-rw-r--r--catalog-ui/src/app/directives/events/on-last-repeat/on-last-repeat.ts40
-rw-r--r--catalog-ui/src/app/directives/export-json-to-excel/export-json-to-excel.html7
-rw-r--r--catalog-ui/src/app/directives/export-json-to-excel/export-json-to-excel.ts61
-rw-r--r--catalog-ui/src/app/directives/file-opener/file-opener.html (renamed from catalog-ui/app/scripts/directives/file-opener/file-opener.html)0
-rw-r--r--catalog-ui/src/app/directives/file-opener/file-opener.ts54
-rw-r--r--catalog-ui/src/app/directives/file-type/file-type.ts45
-rw-r--r--catalog-ui/src/app/directives/file-upload/file-upload.html (renamed from catalog-ui/app/scripts/directives/file-upload/file-upload.html)1
-rw-r--r--catalog-ui/src/app/directives/file-upload/file-upload.less (renamed from catalog-ui/app/scripts/directives/file-upload/file-upload.less)0
-rw-r--r--catalog-ui/src/app/directives/file-upload/file-upload.ts130
-rw-r--r--catalog-ui/src/app/directives/graphs-v2/asset-popover/asset-popover.html11
-rw-r--r--catalog-ui/src/app/directives/graphs-v2/asset-popover/asset-popover.less64
-rw-r--r--catalog-ui/src/app/directives/graphs-v2/asset-popover/asset-popover.ts (renamed from catalog-ui/app/scripts/filters/resource-name-filter.ts)48
-rw-r--r--catalog-ui/src/app/directives/graphs-v2/common/common-graph-utils.ts372
-rw-r--r--catalog-ui/src/app/directives/graphs-v2/common/style/component-instances-nodes-style.ts (renamed from catalog-ui/app/scripts/directives/graphs-v2/common/style/component-instances-nodes-style.ts)49
-rw-r--r--catalog-ui/src/app/directives/graphs-v2/common/style/module-node-style.ts (renamed from catalog-ui/app/scripts/directives/graphs-v2/common/style/module-node-style.ts)27
-rw-r--r--catalog-ui/src/app/directives/graphs-v2/composition-graph/composition-graph.directive.ts539
-rw-r--r--catalog-ui/src/app/directives/graphs-v2/composition-graph/composition-graph.html (renamed from catalog-ui/app/scripts/directives/graphs-v2/composition-graph/composition-graph.html)3
-rw-r--r--catalog-ui/src/app/directives/graphs-v2/composition-graph/composition-graph.less (renamed from catalog-ui/app/scripts/directives/graphs-v2/composition-graph/composition-graph.less)6
-rw-r--r--catalog-ui/src/app/directives/graphs-v2/composition-graph/utils/composition-graph-general-utils.ts244
-rw-r--r--catalog-ui/src/app/directives/graphs-v2/composition-graph/utils/composition-graph-links-utils.ts271
-rw-r--r--catalog-ui/src/app/directives/graphs-v2/composition-graph/utils/composition-graph-nodes-utils.ts266
-rw-r--r--catalog-ui/src/app/directives/graphs-v2/composition-graph/utils/composition-graph-palette-utils.ts163
-rw-r--r--catalog-ui/src/app/directives/graphs-v2/composition-graph/utils/match-capability-requierment-utils.ts259
-rw-r--r--catalog-ui/src/app/directives/graphs-v2/deployment-graph/deployment-graph.directive.ts122
-rw-r--r--catalog-ui/src/app/directives/graphs-v2/deployment-graph/deployment-graph.html (renamed from catalog-ui/app/scripts/directives/graphs-v2/deployment-graph/deployment-graph.html)2
-rw-r--r--catalog-ui/src/app/directives/graphs-v2/deployment-graph/deployment-graph.less (renamed from catalog-ui/app/scripts/directives/graphs-v2/deployment-graph/deployment-graph.less)2
-rw-r--r--catalog-ui/src/app/directives/graphs-v2/deployment-graph/deployment-utils/deployment-graph-general-utils.ts22
-rw-r--r--catalog-ui/src/app/directives/graphs-v2/image-creator/image-creator.service.ts45
-rw-r--r--catalog-ui/src/app/directives/graphs-v2/palette/interfaces/i-dragdrop-event.d.ts (renamed from catalog-ui/app/scripts/directives/graphs-v2/palette/interfaces/i-dragdrop-event.d.ts)0
-rw-r--r--catalog-ui/src/app/directives/graphs-v2/palette/palette.directive.ts349
-rw-r--r--catalog-ui/src/app/directives/graphs-v2/palette/palette.html (renamed from catalog-ui/app/scripts/directives/graphs-v2/palette/palette.html)4
-rw-r--r--catalog-ui/src/app/directives/graphs-v2/palette/palette.less (renamed from catalog-ui/app/scripts/directives/graphs-v2/palette/palette.less)0
-rw-r--r--catalog-ui/src/app/directives/graphs-v2/relation-menu/relation-menu.html (renamed from catalog-ui/app/scripts/directives/graphs-v2/relation-menu/relation-menu.html)0
-rw-r--r--catalog-ui/src/app/directives/graphs-v2/relation-menu/relation-menu.less (renamed from catalog-ui/app/scripts/directives/graphs-v2/relation-menu/relation-menu.less)0
-rw-r--r--catalog-ui/src/app/directives/graphs-v2/relation-menu/relation-menu.ts103
-rw-r--r--catalog-ui/src/app/directives/info-tooltip/info-tooltip.html (renamed from catalog-ui/app/scripts/directives/info-tooltip/info-tooltip.html)0
-rw-r--r--catalog-ui/src/app/directives/info-tooltip/info-tooltip.less (renamed from catalog-ui/app/scripts/directives/info-tooltip/info-tooltip.less)5
-rw-r--r--catalog-ui/src/app/directives/info-tooltip/info-tooltip.ts37
-rw-r--r--catalog-ui/src/app/directives/inputs-and-properties/inputs/input-row-directive.ts43
-rw-r--r--catalog-ui/src/app/directives/inputs-and-properties/inputs/input-row-view.html43
-rw-r--r--catalog-ui/src/app/directives/inputs-and-properties/inputs/input-row.less54
-rw-r--r--catalog-ui/src/app/directives/inputs-and-properties/properties/property-row-directive.ts42
-rw-r--r--catalog-ui/src/app/directives/inputs-and-properties/properties/property-row-view.html26
-rw-r--r--catalog-ui/src/app/directives/inputs-and-properties/properties/property-row-view.less35
-rw-r--r--catalog-ui/src/app/directives/invalid-characters/invalid-characters.ts51
-rw-r--r--catalog-ui/src/app/directives/layout/top-nav/top-nav.html (renamed from catalog-ui/app/scripts/directives/layout/top-nav/top-nav.html)2
-rw-r--r--catalog-ui/src/app/directives/layout/top-nav/top-nav.less (renamed from catalog-ui/app/scripts/directives/layout/top-nav/top-nav.less)0
-rw-r--r--catalog-ui/src/app/directives/layout/top-nav/top-nav.ts141
-rw-r--r--catalog-ui/src/app/directives/layout/top-progress/top-progress.html (renamed from catalog-ui/app/scripts/directives/layout/top-progress/top-progress.html)0
-rw-r--r--catalog-ui/src/app/directives/layout/top-progress/top-progress.less (renamed from catalog-ui/app/scripts/directives/layout/top-progress/top-progress.less)2
-rw-r--r--catalog-ui/src/app/directives/layout/top-progress/top-progress.ts36
-rw-r--r--catalog-ui/src/app/directives/loader/loader-directive.html (renamed from catalog-ui/app/scripts/directives/loader/loader-directive.html)0
-rw-r--r--catalog-ui/src/app/directives/loader/loader-directive.less (renamed from catalog-ui/app/scripts/directives/loader/loader-directive.less)0
-rw-r--r--catalog-ui/src/app/directives/loader/loader-directive.ts155
-rw-r--r--catalog-ui/src/app/directives/modal/sdc-modal.html (renamed from catalog-ui/app/scripts/directives/modal/sdc-modal.html)0
-rw-r--r--catalog-ui/src/app/directives/modal/sdc-modal.less (renamed from catalog-ui/app/scripts/directives/modal/sdc-modal.less)0
-rw-r--r--catalog-ui/src/app/directives/modal/sdc-modal.ts80
-rw-r--r--catalog-ui/src/app/directives/perfect-scrollbar/angular-perfect-scrollbar.ts125
-rw-r--r--catalog-ui/src/app/directives/print-graph-screen/print-graph-screen.ts190
-rw-r--r--catalog-ui/src/app/directives/property-types/data-type-fields-structure/data-type-fields-structure.html (renamed from catalog-ui/app/scripts/directives/property-types/data-type-fields-structure/data-type-fields-structure.html)13
-rw-r--r--catalog-ui/src/app/directives/property-types/data-type-fields-structure/data-type-fields-structure.less (renamed from catalog-ui/app/scripts/directives/property-types/data-type-fields-structure/data-type-fields-structure.less)0
-rw-r--r--catalog-ui/src/app/directives/property-types/data-type-fields-structure/data-type-fields-structure.ts154
-rw-r--r--catalog-ui/src/app/directives/property-types/type-list/type-list-directive.html (renamed from catalog-ui/app/scripts/directives/property-types/type-list/type-list-directive.html)5
-rw-r--r--catalog-ui/src/app/directives/property-types/type-list/type-list-directive.less (renamed from catalog-ui/app/scripts/directives/property-types/type-list/type-list-directive.less)4
-rw-r--r--catalog-ui/src/app/directives/property-types/type-list/type-list-directive.ts106
-rw-r--r--catalog-ui/src/app/directives/property-types/type-map/type-map-directive.html (renamed from catalog-ui/app/scripts/directives/property-types/type-map/type-map-directive.html)7
-rw-r--r--catalog-ui/src/app/directives/property-types/type-map/type-map-directive.less (renamed from catalog-ui/app/scripts/directives/property-types/type-map/type-map-directive.less)0
-rw-r--r--catalog-ui/src/app/directives/property-types/type-map/type-map-directive.ts143
-rw-r--r--catalog-ui/src/app/directives/punch-out/punch-out.ts80
-rw-r--r--catalog-ui/src/app/directives/sdc-tabs/sdc-single-tab/sdc-single-tab-directive.ts46
-rw-r--r--catalog-ui/src/app/directives/sdc-tabs/sdc-single-tab/sdc-single-tab.less (renamed from catalog-ui/app/scripts/directives/sdc-tabs/sdc-single-tab/sdc-single-tab.less)0
-rw-r--r--catalog-ui/src/app/directives/sdc-tabs/sdc-tabs-directive-view.html (renamed from catalog-ui/app/scripts/directives/sdc-tabs/sdc-tabs-directive-view.html)2
-rw-r--r--catalog-ui/src/app/directives/sdc-tabs/sdc-tabs-directive.ts48
-rw-r--r--catalog-ui/src/app/directives/sdc-tabs/sdc-tabs.less (renamed from catalog-ui/app/scripts/directives/sdc-tabs/sdc-tabs.less)9
-rw-r--r--catalog-ui/src/app/directives/select-property-types/select-data-type-fields-structure/select-data-type-fields-structure.html81
-rw-r--r--catalog-ui/src/app/directives/select-property-types/select-data-type-fields-structure/select-data-type-fields-structure.less117
-rw-r--r--catalog-ui/src/app/directives/select-property-types/select-data-type-fields-structure/select-data-type-fields-structure.ts184
-rw-r--r--catalog-ui/src/app/directives/select-property-types/select-type-list/select-type-list-directive.html56
-rw-r--r--catalog-ui/src/app/directives/select-property-types/select-type-list/select-type-list-directive.less85
-rw-r--r--catalog-ui/src/app/directives/select-property-types/select-type-list/select-type-list-directive.ts108
-rw-r--r--catalog-ui/src/app/directives/select-property-types/select-type-map/select-type-map-directive.html56
-rw-r--r--catalog-ui/src/app/directives/select-property-types/select-type-map/select-type-map-directive.less83
-rw-r--r--catalog-ui/src/app/directives/select-property-types/select-type-map/select-type-map-directive.ts139
-rw-r--r--catalog-ui/src/app/directives/structure-tree/structure-tree-directive.html (renamed from catalog-ui/app/scripts/directives/structure-tree/structure-tree-directive.html)0
-rw-r--r--catalog-ui/src/app/directives/structure-tree/structure-tree-directive.less (renamed from catalog-ui/app/scripts/directives/structure-tree/structure-tree-directive.less)0
-rw-r--r--catalog-ui/src/app/directives/structure-tree/structure-tree-directive.ts195
-rw-r--r--catalog-ui/src/app/directives/tag/tag-directive.html (renamed from catalog-ui/app/scripts/directives/tag/tag-directive.html)0
-rw-r--r--catalog-ui/src/app/directives/tag/tag-directive.less (renamed from catalog-ui/app/scripts/directives/tag/tag-directive.less)0
-rw-r--r--catalog-ui/src/app/directives/tag/tag-directive.ts49
-rw-r--r--catalog-ui/src/app/directives/user-header-details/user-header-details-directive.html (renamed from catalog-ui/app/scripts/directives/user-header-details/user-header-details-directive.html)0
-rw-r--r--catalog-ui/src/app/directives/user-header-details/user-header-details-directive.less (renamed from catalog-ui/app/scripts/directives/user-header-details/user-header-details-directive.less)2
-rw-r--r--catalog-ui/src/app/directives/user-header-details/user-header-details-directive.ts52
-rw-r--r--catalog-ui/src/app/directives/utils/expand-collapse-list-header/expand-collapse-list-header.html19
-rw-r--r--catalog-ui/src/app/directives/utils/expand-collapse-list-header/expand-collapse-list-header.less43
-rw-r--r--catalog-ui/src/app/directives/utils/expand-collapse-list-header/expand-collapse-list-header.ts66
-rw-r--r--catalog-ui/src/app/directives/utils/expand-collapse-menu-box/expand-collaps-menu-box.ts47
-rw-r--r--catalog-ui/src/app/directives/utils/expand-collapse-menu-box/expand-collapse-menu-box.html (renamed from catalog-ui/app/scripts/directives/utils/expand-collapse-menu-box/expand-collapse-menu-box.html)8
-rw-r--r--catalog-ui/src/app/directives/utils/expand-collapse-menu-box/expand-collapse-menu-box.less (renamed from catalog-ui/app/scripts/directives/utils/expand-collapse-menu-box/expand-collapse-menu-box.less)34
-rw-r--r--catalog-ui/src/app/directives/utils/expand-collapse/expand-collapse.html (renamed from catalog-ui/app/scripts/directives/utils/expand-collapse/expand-collapse.html)0
-rw-r--r--catalog-ui/src/app/directives/utils/expand-collapse/expand-collapse.less (renamed from catalog-ui/app/scripts/directives/utils/expand-collapse/expand-collapse.less)1
-rw-r--r--catalog-ui/src/app/directives/utils/expand-collapse/expand-collapse.ts115
-rw-r--r--catalog-ui/src/app/directives/utils/sdc-keyboard-events/sdc-keyboard-events.ts84
-rw-r--r--catalog-ui/src/app/directives/utils/sdc-tags/sdc-tags.html (renamed from catalog-ui/app/scripts/directives/utils/sdc-tags/sdc-tags.html)0
-rw-r--r--catalog-ui/src/app/directives/utils/sdc-tags/sdc-tags.less (renamed from catalog-ui/app/scripts/directives/utils/sdc-tags/sdc-tags.less)0
-rw-r--r--catalog-ui/src/app/directives/utils/sdc-tags/sdc-tags.ts75
-rw-r--r--catalog-ui/src/app/directives/utils/smart-tooltip/smart-tooltip.ts61
-rw-r--r--catalog-ui/src/app/directives/utils/validation-on-load/validation-on-load.ts48
-rw-r--r--catalog-ui/src/app/filters.ts15
-rw-r--r--catalog-ui/src/app/filters/catalog-status-filter.ts18
-rw-r--r--catalog-ui/src/app/filters/category-type-filter.ts28
-rw-r--r--catalog-ui/src/app/filters/clear-whitespaces-filter.ts16
-rw-r--r--catalog-ui/src/app/filters/entity-filter.ts (renamed from catalog-ui/app/scripts/filters/entity-filter.ts)59
-rw-r--r--catalog-ui/src/app/filters/graph-resource-name-filter.ts22
-rw-r--r--catalog-ui/src/app/filters/resource-name-filter.ts21
-rw-r--r--catalog-ui/src/app/filters/resource-type-filter.ts17
-rw-r--r--catalog-ui/src/app/filters/string-to-date-filter.ts12
-rw-r--r--catalog-ui/src/app/filters/tests-id-filter.ts11
-rw-r--r--catalog-ui/src/app/filters/trim-filter.ts15
-rw-r--r--catalog-ui/src/app/filters/truncate-filter.ts26
-rw-r--r--catalog-ui/src/app/models.ts84
-rw-r--r--catalog-ui/src/app/models/activity.ts27
-rw-r--r--catalog-ui/src/app/models/additional-information.ts20
-rw-r--r--catalog-ui/src/app/models/app-config.ts226
-rw-r--r--catalog-ui/src/app/models/artifacts.ts101
-rw-r--r--catalog-ui/src/app/models/aschema-property.ts56
-rw-r--r--catalog-ui/src/app/models/attributes.ts119
-rw-r--r--catalog-ui/src/app/models/button.ts20
-rw-r--r--catalog-ui/src/app/models/capability.ts95
-rw-r--r--catalog-ui/src/app/models/categories.ts10
-rw-r--r--catalog-ui/src/app/models/category.ts47
-rw-r--r--catalog-ui/src/app/models/comments.ts11
-rw-r--r--catalog-ui/src/app/models/component-metadata.ts89
-rw-r--r--catalog-ui/src/app/models/components/component.ts911
-rw-r--r--catalog-ui/src/app/models/components/displayComponent.ts111
-rw-r--r--catalog-ui/src/app/models/components/product.ts105
-rw-r--r--catalog-ui/src/app/models/components/resource.ts157
-rw-r--r--catalog-ui/src/app/models/components/service.ts150
-rw-r--r--catalog-ui/src/app/models/componentsInstances/componentInstance.ts113
-rw-r--r--catalog-ui/src/app/models/componentsInstances/productInstance.ts13
-rw-r--r--catalog-ui/src/app/models/componentsInstances/resourceInstance.ts15
-rw-r--r--catalog-ui/src/app/models/componentsInstances/serviceInstance.ts14
-rw-r--r--catalog-ui/src/app/models/csar-component.ts15
-rw-r--r--catalog-ui/src/app/models/data-type-properties.ts39
-rw-r--r--catalog-ui/src/app/models/data-types-map.ts17
-rw-r--r--catalog-ui/src/app/models/data-types.ts34
-rw-r--r--catalog-ui/src/app/models/distribution.ts43
-rw-r--r--catalog-ui/src/app/models/export-excel.ts12
-rw-r--r--catalog-ui/src/app/models/file-download.ts6
-rw-r--r--catalog-ui/src/app/models/filter-properties-assignment-data.ts10
-rw-r--r--catalog-ui/src/app/models/graph/assetPopoverObj.ts (renamed from catalog-ui/app/scripts/filters/trim-filter.ts)29
-rw-r--r--catalog-ui/src/app/models/graph/graph-links/common-base-link.ts (renamed from catalog-ui/app/scripts/models/graph/graph-links/module-graph-links/module-ci-link-base.ts)30
-rw-r--r--catalog-ui/src/app/models/graph/graph-links/common-ci-link-base.ts (renamed from catalog-ui/app/scripts/models/graph/nodes/modules-graph-nodes/module-node-base.ts)41
-rw-r--r--catalog-ui/src/app/models/graph/graph-links/composition-graph-links/composition-ci-link-base.ts (renamed from catalog-ui/app/scripts/services/configuration-ui-service.ts)39
-rw-r--r--catalog-ui/src/app/models/graph/graph-links/composition-graph-links/composition-ci-simple-link.ts (renamed from catalog-ui/app/scripts/filters/tests-id-filter.ts)17
-rw-r--r--catalog-ui/src/app/models/graph/graph-links/composition-graph-links/composition-ci-ucpe-host-link.ts (renamed from catalog-ui/app/scripts/models/graph/graph-links/composition-graph-links/composition-ci-ucpe-host-link.ts)15
-rw-r--r--catalog-ui/src/app/models/graph/graph-links/composition-graph-links/composition-ci-ucpe-link.ts (renamed from catalog-ui/app/scripts/models/data-types-map.ts)28
-rw-r--r--catalog-ui/src/app/models/graph/graph-links/composition-graph-links/composition-ci-vl-link.ts (renamed from catalog-ui/app/scripts/models/graph/graph-links/composition-graph-links/composition-ci-vl-link.ts)18
-rw-r--r--catalog-ui/src/app/models/graph/graph-links/composition-graph-links/composition-ci-vl-ucpe-link.ts (renamed from catalog-ui/app/scripts/models/graph/graph-links/composition-graph-links/composition-ci-vl-ucpe-link.ts)14
-rw-r--r--catalog-ui/src/app/models/graph/graph-links/links-factory.ts79
-rw-r--r--catalog-ui/src/app/models/graph/graph-links/module-graph-links/module-ci-link-base.ts (renamed from catalog-ui/app/scripts/models/graph/graph-links/module-graph-links/module-ci-vl-link.ts)18
-rw-r--r--catalog-ui/src/app/models/graph/graph-links/module-graph-links/module-ci-vl-link.ts (renamed from catalog-ui/app/scripts/filters/clear-whitespaces-filter.ts)22
-rw-r--r--catalog-ui/src/app/models/graph/graphTooltip.ts (renamed from catalog-ui/app/scripts/filters/underscoreless-filter.ts)22
-rw-r--r--catalog-ui/src/app/models/graph/link-menu.ts (renamed from catalog-ui/app/scripts/filters/product-category-name-filter.ts)29
-rw-r--r--catalog-ui/src/app/models/graph/match-relation.ts111
-rw-r--r--catalog-ui/src/app/models/graph/nodes/base-common-node.ts70
-rw-r--r--catalog-ui/src/app/models/graph/nodes/common-ci-node-base.ts (renamed from ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ToscaArtifactsPage.java)35
-rw-r--r--catalog-ui/src/app/models/graph/nodes/composition-graph-nodes/composition-ci-node-base.ts73
-rw-r--r--catalog-ui/src/app/models/graph/nodes/composition-graph-nodes/composition-ci-node-cp.ts50
-rw-r--r--catalog-ui/src/app/models/graph/nodes/composition-graph-nodes/composition-ci-node-service.ts (renamed from catalog-ui/app/scripts/models/schema-attribute.ts)26
-rw-r--r--catalog-ui/src/app/models/graph/nodes/composition-graph-nodes/composition-ci-node-ucpe-cp.ts (renamed from catalog-ui/app/scripts/models/graph/nodes/composition-graph-nodes/composition-ci-node-ucpe-cp.ts)26
-rw-r--r--catalog-ui/src/app/models/graph/nodes/composition-graph-nodes/composition-ci-node-ucpe.ts (renamed from catalog-ui/app/scripts/view-models/modals/message-modal/message-client-modal/client-message-modal-view-model.ts)37
-rw-r--r--catalog-ui/src/app/models/graph/nodes/composition-graph-nodes/composition-ci-node-vf.ts (renamed from catalog-ui/app/scripts/models/graph/graph-links/composition-graph-links/composition-ci-link-base.ts)37
-rw-r--r--catalog-ui/src/app/models/graph/nodes/composition-graph-nodes/composition-ci-node-vfc.ts (renamed from catalog-ui/app/scripts/models/additional-information.ts)30
-rw-r--r--catalog-ui/src/app/models/graph/nodes/composition-graph-nodes/composition-ci-node-vl.ts (renamed from catalog-ui/app/scripts/models/graph/nodes/composition-graph-nodes/composition-ci-node-vl.ts)36
-rw-r--r--catalog-ui/src/app/models/graph/nodes/modules-graph-nodes/module-node-base.ts (renamed from catalog-ui/app/scripts/modules/utils.ts)36
-rw-r--r--catalog-ui/src/app/models/graph/nodes/nodes-factory.ts63
-rw-r--r--catalog-ui/src/app/models/graph/point.ts20
-rw-r--r--catalog-ui/src/app/models/graph/relationMenuObjects.ts131
-rw-r--r--catalog-ui/src/app/models/graph/relationship.ts95
-rw-r--r--catalog-ui/src/app/models/heat-parameters.ts18
-rw-r--r--catalog-ui/src/app/models/input-property-base.ts26
-rw-r--r--catalog-ui/src/app/models/inputs-and-properties.ts22
-rw-r--r--catalog-ui/src/app/models/inputs.ts80
-rw-r--r--catalog-ui/src/app/models/instance-inputs-properties-map.ts67
-rw-r--r--catalog-ui/src/app/models/left-panel.ts11
-rw-r--r--catalog-ui/src/app/models/member.ts16
-rw-r--r--catalog-ui/src/app/models/modules/base-module.ts95
-rw-r--r--catalog-ui/src/app/models/properties-inputs/derived-fe-property.ts72
-rw-r--r--catalog-ui/src/app/models/properties-inputs/input-fe-model.ts32
-rw-r--r--catalog-ui/src/app/models/properties-inputs/property-be-model.ts84
-rw-r--r--catalog-ui/src/app/models/properties-inputs/property-fe-map.ts21
-rw-r--r--catalog-ui/src/app/models/properties-inputs/property-fe-model.ts132
-rw-r--r--catalog-ui/src/app/models/properties.ts141
-rw-r--r--catalog-ui/src/app/models/property-fe-model.ts78
-rw-r--r--catalog-ui/src/app/models/requirement.ts71
-rw-r--r--catalog-ui/src/app/models/schema-attribute.ts16
-rw-r--r--catalog-ui/src/app/models/tab.ts27
-rw-r--r--catalog-ui/src/app/models/tooltip-data.ts6
-rw-r--r--catalog-ui/src/app/models/user.ts96
-rw-r--r--catalog-ui/src/app/models/validate.ts7
-rw-r--r--catalog-ui/src/app/models/validation-config.ts20
-rw-r--r--catalog-ui/src/app/modules/directive-module.ts152
-rw-r--r--catalog-ui/src/app/modules/filters.ts26
-rw-r--r--catalog-ui/src/app/modules/service-module.ts66
-rw-r--r--catalog-ui/src/app/modules/utils.ts16
-rw-r--r--catalog-ui/src/app/modules/view-model-module.ts125
-rw-r--r--catalog-ui/src/app/ng2/app.component.css (renamed from catalog-ui/app/scripts/view-models/modals/message-modal/message-client-modal/client-message-modal.less)0
-rw-r--r--catalog-ui/src/app/ng2/app.component.html6
-rw-r--r--catalog-ui/src/app/ng2/app.component.ts15
-rw-r--r--catalog-ui/src/app/ng2/app.module.ts74
-rw-r--r--catalog-ui/src/app/ng2/app.routing.ts20
-rw-r--r--catalog-ui/src/app/ng2/components/dynamic-element/dynamic-element.component.less3
-rw-r--r--catalog-ui/src/app/ng2/components/dynamic-element/dynamic-element.component.ts117
-rw-r--r--catalog-ui/src/app/ng2/components/dynamic-element/dynamic-element.module.ts34
-rw-r--r--catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/checkbox/ui-element-checkbox.component.html1
-rw-r--r--catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/checkbox/ui-element-checkbox.component.less2
-rw-r--r--catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/checkbox/ui-element-checkbox.component.ts27
-rw-r--r--catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/dropdown/ui-element-dropdown.component.html3
-rw-r--r--catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/dropdown/ui-element-dropdown.component.less11
-rw-r--r--catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/dropdown/ui-element-dropdown.component.ts33
-rw-r--r--catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/input/ui-element-input.component.html13
-rw-r--r--catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/input/ui-element-input.component.less17
-rw-r--r--catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/input/ui-element-input.component.ts22
-rw-r--r--catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/popover-input/ui-element-popover-input.component.html26
-rw-r--r--catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/popover-input/ui-element-popover-input.component.less36
-rw-r--r--catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/popover-input/ui-element-popover-input.component.ts39
-rw-r--r--catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/ui-element-base.component.ts34
-rw-r--r--catalog-ui/src/app/ng2/components/filter-properties-assignment/filter-properties-assignment.component.html26
-rw-r--r--catalog-ui/src/app/ng2/components/filter-properties-assignment/filter-properties-assignment.component.less38
-rw-r--r--catalog-ui/src/app/ng2/components/filter-properties-assignment/filter-properties-assignment.component.ts77
-rw-r--r--catalog-ui/src/app/ng2/components/hierarchy-navigtion/hierarchy-display-options.ts12
-rw-r--r--catalog-ui/src/app/ng2/components/hierarchy-navigtion/hierarchy-navigation.component.html13
-rw-r--r--catalog-ui/src/app/ng2/components/hierarchy-navigtion/hierarchy-navigation.component.less51
-rw-r--r--catalog-ui/src/app/ng2/components/hierarchy-navigtion/hierarchy-navigation.component.ts28
-rw-r--r--catalog-ui/src/app/ng2/components/inputs-table/inputs-table.component.html37
-rw-r--r--catalog-ui/src/app/ng2/components/inputs-table/inputs-table.component.ts33
-rw-r--r--catalog-ui/src/app/ng2/components/popover/popover-content.component.html24
-rw-r--r--catalog-ui/src/app/ng2/components/popover/popover-content.component.less73
-rw-r--r--catalog-ui/src/app/ng2/components/popover/popover-content.component.ts258
-rw-r--r--catalog-ui/src/app/ng2/components/popover/popover.component.ts159
-rw-r--r--catalog-ui/src/app/ng2/components/popover/popover.module.ts27
-rw-r--r--catalog-ui/src/app/ng2/components/properties-table/derived-property/derived-property.component.html24
-rw-r--r--catalog-ui/src/app/ng2/components/properties-table/derived-property/derived-property.component.less35
-rw-r--r--catalog-ui/src/app/ng2/components/properties-table/derived-property/derived-property.component.ts46
-rw-r--r--catalog-ui/src/app/ng2/components/properties-table/dynamic-property/dynamic-property.component.html66
-rw-r--r--catalog-ui/src/app/ng2/components/properties-table/dynamic-property/dynamic-property.component.less48
-rw-r--r--catalog-ui/src/app/ng2/components/properties-table/dynamic-property/dynamic-property.component.ts149
-rw-r--r--catalog-ui/src/app/ng2/components/properties-table/list-property/list-property.component.html33
-rw-r--r--catalog-ui/src/app/ng2/components/properties-table/list-property/list-property.component.less3
-rw-r--r--catalog-ui/src/app/ng2/components/properties-table/list-property/list-property.component.ts85
-rw-r--r--catalog-ui/src/app/ng2/components/properties-table/map-property/map-property.component.html38
-rw-r--r--catalog-ui/src/app/ng2/components/properties-table/map-property/map-property.component.ts121
-rw-r--r--catalog-ui/src/app/ng2/components/properties-table/properties-table.component.html135
-rw-r--r--catalog-ui/src/app/ng2/components/properties-table/properties-table.component.less188
-rw-r--r--catalog-ui/src/app/ng2/components/properties-table/properties-table.component.ts93
-rw-r--r--catalog-ui/src/app/ng2/components/properties-table/properties-value-inner-table/properties-value-inner-table.component.html41
-rw-r--r--catalog-ui/src/app/ng2/components/properties-table/properties-value-inner-table/properties-value-inner-table.component.less71
-rw-r--r--catalog-ui/src/app/ng2/components/properties-table/properties-value-inner-table/properties-value-inner-table.component.ts37
-rw-r--r--catalog-ui/src/app/ng2/components/tooltip/tooltip-content.component.html12
-rw-r--r--catalog-ui/src/app/ng2/components/tooltip/tooltip-content.component.less11
-rw-r--r--catalog-ui/src/app/ng2/components/tooltip/tooltip-content.component.ts195
-rw-r--r--catalog-ui/src/app/ng2/components/tooltip/tooltip.component.ts81
-rw-r--r--catalog-ui/src/app/ng2/components/tooltip/tooltip.module.ts25
-rw-r--r--catalog-ui/src/app/ng2/pages/page404/page404.component.html3
-rw-r--r--catalog-ui/src/app/ng2/pages/page404/page404.component.less4
-rw-r--r--catalog-ui/src/app/ng2/pages/page404/page404.component.ts9
-rw-r--r--catalog-ui/src/app/ng2/pages/properties-assignment/properties-assignment.module.ts72
-rw-r--r--catalog-ui/src/app/ng2/pages/properties-assignment/properties-assignment.page.component.html57
-rw-r--r--catalog-ui/src/app/ng2/pages/properties-assignment/properties-assignment.page.component.less158
-rw-r--r--catalog-ui/src/app/ng2/pages/properties-assignment/properties-assignment.page.component.ts344
-rw-r--r--catalog-ui/src/app/ng2/pages/properties-assignment/properties.utils.ts78
-rw-r--r--catalog-ui/src/app/ng2/pipes/contentAfterLastDot.pipe.ts8
-rw-r--r--catalog-ui/src/app/ng2/pipes/filterChildProperties.pipe.ts18
-rw-r--r--catalog-ui/src/app/ng2/pipes/groupBy.pipe.ts19
-rw-r--r--catalog-ui/src/app/ng2/pipes/keys.pipe.ts12
-rw-r--r--catalog-ui/src/app/ng2/pipes/searchFilter.pipe.ts18
-rw-r--r--catalog-ui/src/app/ng2/services/authentication.service.ts40
-rw-r--r--catalog-ui/src/app/ng2/services/component-instance-services/component-instance.service.ts51
-rw-r--r--catalog-ui/src/app/ng2/services/component-services/component.service.ts149
-rw-r--r--catalog-ui/src/app/ng2/services/component-services/resource.service.ts18
-rw-r--r--catalog-ui/src/app/ng2/services/component-services/service.service.ts31
-rw-r--r--catalog-ui/src/app/ng2/services/config.service.ts51
-rw-r--r--catalog-ui/src/app/ng2/services/cookie.service.ts65
-rw-r--r--catalog-ui/src/app/ng2/services/data-type.service.ts69
-rw-r--r--catalog-ui/src/app/ng2/services/http.service.ts73
-rw-r--r--catalog-ui/src/app/ng2/services/mocks/properties.mock.ts16
-rw-r--r--catalog-ui/src/app/ng2/services/posts.service.ts54
-rw-r--r--catalog-ui/src/app/ng2/services/properties.service.ts249
-rw-r--r--catalog-ui/src/app/ng2/services/responses/component-generic-response.ts77
-rw-r--r--catalog-ui/src/app/ng2/services/responses/properties.response.ts7
-rw-r--r--catalog-ui/src/app/ng2/services/utils/serializable.ts6
-rw-r--r--catalog-ui/src/app/ng2/shared/checkbox/checkbox.component.html8
-rw-r--r--catalog-ui/src/app/ng2/shared/checkbox/checkbox.component.less64
-rw-r--r--catalog-ui/src/app/ng2/shared/checkbox/checkbox.component.ts30
-rw-r--r--catalog-ui/src/app/ng2/shared/checkbox/checkbox.module.ts28
-rw-r--r--catalog-ui/src/app/ng2/shared/navbar/navbar-routes.config.ts7
-rw-r--r--catalog-ui/src/app/ng2/shared/navbar/navbar.component.html23
-rw-r--r--catalog-ui/src/app/ng2/shared/navbar/navbar.component.less11
-rw-r--r--catalog-ui/src/app/ng2/shared/navbar/navbar.component.ts32
-rw-r--r--catalog-ui/src/app/ng2/shared/navbar/navbar.metadata.ts11
-rw-r--r--catalog-ui/src/app/ng2/shared/navbar/navbar.module.ts16
-rw-r--r--catalog-ui/src/app/ng2/shared/shared.module.ts20
-rw-r--r--catalog-ui/src/app/ng2/shared/tabs/tab/tab.component.ts18
-rw-r--r--catalog-ui/src/app/ng2/shared/tabs/tabs.component.html9
-rw-r--r--catalog-ui/src/app/ng2/shared/tabs/tabs.component.less85
-rw-r--r--catalog-ui/src/app/ng2/shared/tabs/tabs.component.ts58
-rw-r--r--catalog-ui/src/app/ng2/shared/tabs/tabs.module.ts35
-rw-r--r--catalog-ui/src/app/ng2/utils/ng1-upgraded-provider.ts51
-rw-r--r--catalog-ui/src/app/services.ts32
-rw-r--r--catalog-ui/src/app/services/activity-log-service.ts28
-rw-r--r--catalog-ui/src/app/services/angular-js-bridge-service.ts23
-rw-r--r--catalog-ui/src/app/services/available-icons-service.ts87
-rw-r--r--catalog-ui/src/app/services/cache-service.ts34
-rw-r--r--catalog-ui/src/app/services/category-resource-service.ts61
-rw-r--r--catalog-ui/src/app/services/components/component-service.ts755
-rw-r--r--catalog-ui/src/app/services/components/product-service.ts35
-rw-r--r--catalog-ui/src/app/services/components/resource-service.ts52
-rw-r--r--catalog-ui/src/app/services/components/service-service.ts86
-rw-r--r--catalog-ui/src/app/services/components/utils/composition-left-palette-service.ts120
-rw-r--r--catalog-ui/src/app/services/configuration-ui-service.ts25
-rw-r--r--catalog-ui/src/app/services/cookie-service.ts72
-rw-r--r--catalog-ui/src/app/services/data-types-service.ts125
-rw-r--r--catalog-ui/src/app/services/ecomp-service.ts30
-rw-r--r--catalog-ui/src/app/services/entity-service.ts94
-rw-r--r--catalog-ui/src/app/services/event-listener-service.ts85
-rw-r--r--catalog-ui/src/app/services/header-interceptor.ts69
-rw-r--r--catalog-ui/src/app/services/http-error-interceptor.ts99
-rw-r--r--catalog-ui/src/app/services/loader-service.ts24
-rw-r--r--catalog-ui/src/app/services/onboarding-service.ts82
-rw-r--r--catalog-ui/src/app/services/progress-service.ts85
-rw-r--r--catalog-ui/src/app/services/sdc-version-service.ts26
-rw-r--r--catalog-ui/src/app/services/sharing-service.ts20
-rw-r--r--catalog-ui/src/app/services/url-tobase64-service.ts30
-rw-r--r--catalog-ui/src/app/services/user-resource-service.ts103
-rw-r--r--catalog-ui/src/app/utils.ts15
-rw-r--r--catalog-ui/src/app/utils/artifacts-utils.ts104
-rw-r--r--catalog-ui/src/app/utils/change-lifecycle-state-handler.ts163
-rw-r--r--catalog-ui/src/app/utils/common-utils.ts96
-rw-r--r--catalog-ui/src/app/utils/component-factory.ts161
-rw-r--r--catalog-ui/src/app/utils/component-instance-factory.ts81
-rw-r--r--catalog-ui/src/app/utils/constants.ts277
-rw-r--r--catalog-ui/src/app/utils/dictionary/dictionary.ts235
-rw-r--r--catalog-ui/src/app/utils/file-utils.ts51
-rw-r--r--catalog-ui/src/app/utils/functions.ts35
-rw-r--r--catalog-ui/src/app/utils/menu-handler.ts125
-rw-r--r--catalog-ui/src/app/utils/modals-handler.ts389
-rw-r--r--catalog-ui/src/app/utils/prototypes.ts64
-rw-r--r--catalog-ui/src/app/utils/validation-utils.ts153
-rw-r--r--catalog-ui/src/app/view-models/admin-dashboard/add-category-modal/add-category-modal-view-model.ts72
-rw-r--r--catalog-ui/src/app/view-models/admin-dashboard/add-category-modal/add-category-modal-view.html (renamed from catalog-ui/app/scripts/view-models/admin-dashboard/add-category-modal/add-category-modal-view.html)8
-rw-r--r--catalog-ui/src/app/view-models/admin-dashboard/add-category-modal/add-category-modal-view.less (renamed from catalog-ui/app/scripts/view-models/admin-dashboard/add-category-modal/add-category-modal-view.less)0
-rw-r--r--catalog-ui/src/app/view-models/admin-dashboard/admin-dashboard-view-model.ts61
-rw-r--r--catalog-ui/src/app/view-models/admin-dashboard/admin-dashboard-view.html (renamed from catalog-ui/app/scripts/view-models/admin-dashboard/admin-dashboard-view.html)2
-rw-r--r--catalog-ui/src/app/view-models/admin-dashboard/admin-dashboard.less (renamed from catalog-ui/app/scripts/view-models/admin-dashboard/admin-dashboard.less)0
-rw-r--r--catalog-ui/src/app/view-models/admin-dashboard/category-management/category-management-view-model.ts176
-rw-r--r--catalog-ui/src/app/view-models/admin-dashboard/category-management/category-management-view.html (renamed from catalog-ui/app/scripts/view-models/admin-dashboard/category-management/category-management-view.html)0
-rw-r--r--catalog-ui/src/app/view-models/admin-dashboard/category-management/category-management.less (renamed from catalog-ui/app/scripts/view-models/admin-dashboard/category-management/category-management.less)0
-rw-r--r--catalog-ui/src/app/view-models/admin-dashboard/ecomp/ecomp-view.html (renamed from catalog-ui/app/scripts/view-models/admin-dashboard/ecomp/ecomp-view.html)0
-rw-r--r--catalog-ui/src/app/view-models/admin-dashboard/user-management/user-management-view-model.ts202
-rw-r--r--catalog-ui/src/app/view-models/admin-dashboard/user-management/user-management-view.html (renamed from catalog-ui/app/scripts/view-models/admin-dashboard/user-management/user-management-view.html)27
-rw-r--r--catalog-ui/src/app/view-models/admin-dashboard/user-management/user-management.less (renamed from catalog-ui/app/scripts/view-models/admin-dashboard/user-management/user-management.less)0
-rw-r--r--catalog-ui/src/app/view-models/catalog/catalog-view-model.ts303
-rw-r--r--catalog-ui/src/app/view-models/catalog/catalog-view.html (renamed from catalog-ui/app/scripts/view-models/catalog/catalog-view.html)63
-rw-r--r--catalog-ui/src/app/view-models/catalog/catalog.less (renamed from catalog-ui/app/scripts/view-models/catalog/catalog.less)10
-rw-r--r--catalog-ui/src/app/view-models/dashboard/dashboard-view-model.ts387
-rw-r--r--catalog-ui/src/app/view-models/dashboard/dashboard-view.html112
-rw-r--r--catalog-ui/src/app/view-models/dashboard/dashboard.less (renamed from catalog-ui/app/scripts/view-models/dashboard/dashboard.less)6
-rw-r--r--catalog-ui/src/app/view-models/dcae-app/dcae-app-view-model.ts112
-rw-r--r--catalog-ui/src/app/view-models/dcae-app/dcae-app-view.html17
-rw-r--r--catalog-ui/src/app/view-models/dcae-app/dcae-app.less303
-rw-r--r--catalog-ui/src/app/view-models/forms/artifact-form/artifact-form-view-model.ts358
-rw-r--r--catalog-ui/src/app/view-models/forms/artifact-form/artifact-form-view.html (renamed from catalog-ui/app/scripts/view-models/forms/artifact-form/artifact-form-view.html)6
-rw-r--r--catalog-ui/src/app/view-models/forms/artifact-form/artifact-form.less (renamed from catalog-ui/app/scripts/view-models/forms/artifact-form/artifact-form.less)0
-rw-r--r--catalog-ui/src/app/view-models/forms/attribute-form/attribute-form-view.html (renamed from catalog-ui/app/scripts/view-models/forms/attribute-form/attribute-form-view.html)5
-rw-r--r--catalog-ui/src/app/view-models/forms/attribute-form/attribute-from-view-model.ts241
-rw-r--r--catalog-ui/src/app/view-models/forms/env-parameters-form/env-parameters-form.html92
-rw-r--r--catalog-ui/src/app/view-models/forms/env-parameters-form/env-parameters-form.less178
-rw-r--r--catalog-ui/src/app/view-models/forms/env-parameters-form/env-parameters-form.ts153
-rw-r--r--catalog-ui/src/app/view-models/forms/env-parameters-form/env-parametr-description-popover.html4
-rw-r--r--catalog-ui/src/app/view-models/forms/input-form/input-form-view-modal.ts126
-rw-r--r--catalog-ui/src/app/view-models/forms/input-form/input-form-view.html125
-rw-r--r--catalog-ui/src/app/view-models/forms/property-forms/base-property-form/property-form-base-model.ts204
-rw-r--r--catalog-ui/src/app/view-models/forms/property-forms/base-property-form/property-form-base-view.html132
-rw-r--r--catalog-ui/src/app/view-models/forms/property-forms/base-property-form/property-form-base.less (renamed from catalog-ui/app/scripts/view-models/forms/property-form/property-form.less)0
-rw-r--r--catalog-ui/src/app/view-models/forms/property-forms/component-property-form/property-form-view-model.ts322
-rw-r--r--catalog-ui/src/app/view-models/forms/property-forms/component-property-form/property-form-view.html (renamed from catalog-ui/app/scripts/view-models/forms/property-form/property-form-view.html)56
-rw-r--r--catalog-ui/src/app/view-models/forms/property-forms/module-property-modal/module-property-model.ts206
-rw-r--r--catalog-ui/src/app/view-models/forms/property-forms/module-property-modal/module-property-view.html41
-rw-r--r--catalog-ui/src/app/view-models/forms/property-forms/select-datatype-modal/select-datatype-modal-view-model.ts97
-rw-r--r--catalog-ui/src/app/view-models/forms/property-forms/select-datatype-modal/select-datatype-modal-view.html74
-rw-r--r--catalog-ui/src/app/view-models/forms/property-forms/select-datatype-modal/select-datatype-modal.less63
-rw-r--r--catalog-ui/src/app/view-models/forms/resource-instance-name-form/resource-instance-name-model.ts95
-rw-r--r--catalog-ui/src/app/view-models/forms/resource-instance-name-form/resource-instance-name-view.html (renamed from catalog-ui/app/scripts/view-models/forms/resource-instance-name-form/resource-instance-name-view.html)0
-rw-r--r--catalog-ui/src/app/view-models/forms/resource-instance-name-form/resource-instance-name.less (renamed from catalog-ui/app/scripts/view-models/forms/resource-instance-name-form/resource-instance-name.less)0
-rw-r--r--catalog-ui/src/app/view-models/modals/confirmation-modal/confirmation-modal-view-model.ts73
-rw-r--r--catalog-ui/src/app/view-models/modals/confirmation-modal/confirmation-modal-view.html (renamed from catalog-ui/app/scripts/view-models/modals/confirmation-modal/confirmation-modal-view.html)0
-rw-r--r--catalog-ui/src/app/view-models/modals/confirmation-modal/confirmation-modal.less (renamed from catalog-ui/app/scripts/view-models/modals/confirmation-modal/confirmation-modal.less)0
-rw-r--r--catalog-ui/src/app/view-models/modals/email-modal/email-modal-view-model.ts96
-rw-r--r--catalog-ui/src/app/view-models/modals/email-modal/email-modal-view.html (renamed from catalog-ui/app/scripts/view-models/modals/email-modal/email-modal-view.html)2
-rw-r--r--catalog-ui/src/app/view-models/modals/email-modal/email-modal.less (renamed from catalog-ui/app/scripts/view-models/modals/email-modal/email-modal.less)1
-rw-r--r--catalog-ui/src/app/view-models/modals/error-modal/error-403-view.html4
-rw-r--r--catalog-ui/src/app/view-models/modals/error-modal/error-view-model.ts19
-rw-r--r--catalog-ui/src/app/view-models/modals/error-modal/error.less (renamed from catalog-ui/app/scripts/view-models/modals/error-modal/error.less)0
-rw-r--r--catalog-ui/src/app/view-models/modals/message-modal/message-base-modal-model.ts43
-rw-r--r--catalog-ui/src/app/view-models/modals/message-modal/message-client-modal/client-message-modal-view-model.ts22
-rw-r--r--catalog-ui/src/app/view-models/modals/message-modal/message-client-modal/client-message-modal-view.html (renamed from catalog-ui/app/scripts/view-models/modals/message-modal/message-client-modal/client-message-modal-view.html)0
-rw-r--r--catalog-ui/src/app/view-models/modals/message-modal/message-client-modal/client-message-modal.less (renamed from catalog-ui/app/scripts/view-models/modals/message-modal/message-server-modal/server-message-modal.less)0
-rw-r--r--catalog-ui/src/app/view-models/modals/message-modal/message-server-modal/server-message-modal-view-model.ts24
-rw-r--r--catalog-ui/src/app/view-models/modals/message-modal/message-server-modal/server-message-modal-view.html (renamed from catalog-ui/app/scripts/view-models/modals/message-modal/message-server-modal/server-message-modal-view.html)0
-rw-r--r--catalog-ui/src/app/view-models/modals/message-modal/message-server-modal/server-message-modal.less0
-rw-r--r--catalog-ui/src/app/view-models/modals/onboarding-modal/onboarding-modal-view-model.ts249
-rw-r--r--catalog-ui/src/app/view-models/modals/onboarding-modal/onboarding-modal-view.html (renamed from catalog-ui/app/scripts/view-models/modals/onboarding-modal/onboarding-modal-view.html)8
-rw-r--r--catalog-ui/src/app/view-models/modals/onboarding-modal/onboarding-modal.less (renamed from catalog-ui/app/scripts/view-models/modals/onboarding-modal/onboarding-modal.less)0
-rw-r--r--catalog-ui/src/app/view-models/onboard-vendor/onboard-vendor-view-model.ts125
-rw-r--r--catalog-ui/src/app/view-models/onboard-vendor/onboard-vendor-view.html (renamed from catalog-ui/app/scripts/view-models/onboard-vendor/onboard-vendor-view.html)2
-rw-r--r--catalog-ui/src/app/view-models/onboard-vendor/onboard-vendor.less (renamed from catalog-ui/app/scripts/view-models/onboard-vendor/onboard-vendor.less)10
-rw-r--r--catalog-ui/src/app/view-models/preloading/preloading-view.html (renamed from catalog-ui/app/scripts/view-models/preloading/preloading-view.html)0
-rw-r--r--catalog-ui/src/app/view-models/preloading/preloading-view.ts27
-rw-r--r--catalog-ui/src/app/view-models/support/support-view-model.ts16
-rw-r--r--catalog-ui/src/app/view-models/support/support-view.html (renamed from catalog-ui/app/scripts/view-models/support/support-view.html)4
-rw-r--r--catalog-ui/src/app/view-models/support/support.less (renamed from catalog-ui/app/scripts/view-models/support/support.less)0
-rw-r--r--catalog-ui/src/app/view-models/tabs/general-tab.less (renamed from catalog-ui/app/scripts/view-models/tabs/general-tab.less)13
-rw-r--r--catalog-ui/src/app/view-models/tabs/hierarchy/hierarchy-view-model.ts98
-rw-r--r--catalog-ui/src/app/view-models/tabs/hierarchy/hierarchy-view.html107
-rw-r--r--catalog-ui/src/app/view-models/tabs/hierarchy/hierarchy.less (renamed from catalog-ui/app/scripts/view-models/tabs/hierarchy/hierarchy.less)44
-rw-r--r--catalog-ui/src/app/view-models/tutorial-end/tutorial-end.html (renamed from catalog-ui/app/scripts/view-models/tutorial-end/tutorial-end.html)0
-rw-r--r--catalog-ui/src/app/view-models/tutorial-end/tutorial-end.less (renamed from catalog-ui/app/scripts/view-models/tutorial-end/tutorial-end.less)2
-rw-r--r--catalog-ui/src/app/view-models/tutorial-end/tutorial-end.ts20
-rw-r--r--catalog-ui/src/app/view-models/welcome/welcome-view.html9
-rw-r--r--catalog-ui/src/app/view-models/welcome/welcome-view.ts57
-rw-r--r--catalog-ui/src/app/view-models/workspace/conformance-level-modal/conformance-level-modal-view-model.ts29
-rw-r--r--catalog-ui/src/app/view-models/workspace/conformance-level-modal/conformance-level-modal-view.html22
-rw-r--r--catalog-ui/src/app/view-models/workspace/conformance-level-modal/conformance-level-modal.less3
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/activity-log/activity-log.html (renamed from catalog-ui/app/scripts/view-models/workspace/tabs/activity-log/activity-log.html)0
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/activity-log/activity-log.less (renamed from catalog-ui/app/scripts/view-models/workspace/tabs/activity-log/activity-log.less)0
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/activity-log/activity-log.ts103
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/attributes/attributes-view-model.ts80
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/attributes/attributes-view.html (renamed from catalog-ui/app/scripts/view-models/workspace/tabs/attributes/attributes-view.html)0
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/attributes/attributes.less (renamed from catalog-ui/app/scripts/view-models/workspace/tabs/attributes/attributes.less)0
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/composition/composition-view-model.ts242
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/composition/composition-view.html (renamed from catalog-ui/app/scripts/view-models/workspace/tabs/composition/composition-view.html)26
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/composition/composition.less (renamed from catalog-ui/app/scripts/view-models/workspace/tabs/composition/composition.less)57
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/artifacts/artifacts-view-model.ts301
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/artifacts/artifacts-view.html (renamed from catalog-ui/app/scripts/view-models/workspace/tabs/composition/tabs/artifacts/artifacts-view.html)46
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/artifacts/artifacts.less (renamed from catalog-ui/app/scripts/view-models/workspace/tabs/composition/tabs/artifacts/artifacts.less)2
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/details/details-view-model.ts132
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/details/details-view.html (renamed from catalog-ui/app/scripts/view-models/workspace/tabs/composition/tabs/details/details-view.html)11
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/details/details.less (renamed from catalog-ui/app/scripts/view-models/workspace/tabs/composition/tabs/details/details.less)4
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/properties-and-attributes/properties-view-model.ts217
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/properties-and-attributes/properties-view.html (renamed from catalog-ui/app/scripts/view-models/workspace/tabs/composition/tabs/properties-and-attributes/properties-view.html)76
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/properties-and-attributes/properties.less (renamed from catalog-ui/app/scripts/view-models/workspace/tabs/composition/tabs/properties-and-attributes/properties.less)22
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/relations/relations-view-model.ts156
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/relations/relations-view.html61
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/relations/relations.less14
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/structure/structure-view.html (renamed from catalog-ui/app/scripts/view-models/workspace/tabs/composition/tabs/structure/structure-view.html)0
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/structure/structure-view.ts14
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts-description-popover.html23
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts-view-model.ts276
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts-view.html126
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts.less (renamed from catalog-ui/app/scripts/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts.less)96
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/deployment/deployment-view-model.ts127
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/deployment/deployment-view.html (renamed from catalog-ui/app/scripts/view-models/workspace/tabs/deployment/deployment-view.html)4
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/deployment/deployment.less (renamed from catalog-ui/app/scripts/view-models/workspace/tabs/deployment/deployment.less)2
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/distribution/disribution-status-modal/disribution-status-modal-view-model.ts83
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/distribution/disribution-status-modal/disribution-status-modal-view.html (renamed from catalog-ui/app/scripts/view-models/workspace/tabs/distribution/disribution-status-modal/disribution-status-modal-view.html)10
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/distribution/disribution-status-modal/disribution-status-modal.less (renamed from catalog-ui/app/scripts/view-models/workspace/tabs/distribution/disribution-status-modal/disribution-status-modal.less)9
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/distribution/distribution-view-model.ts111
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/distribution/distribution-view.html (renamed from catalog-ui/app/scripts/view-models/workspace/tabs/distribution/distribution-view.html)42
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/distribution/distribution.less (renamed from catalog-ui/app/scripts/view-models/workspace/tabs/distribution/distribution.less)1
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/general/general-view-model.ts349
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/general/general-view.html (renamed from catalog-ui/app/scripts/view-models/workspace/tabs/general/general-view.html)71
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/general/general.less (renamed from catalog-ui/app/scripts/view-models/workspace/tabs/general/general.less)0
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/icons/icons-view-model.ts111
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/icons/icons-view.html (renamed from catalog-ui/app/scripts/view-models/workspace/tabs/icons/icons-view.html)0
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/icons/icons.less (renamed from catalog-ui/app/scripts/view-models/workspace/tabs/icons/icons.less)0
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/information-artifacts/information-artifacts-view-model.ts138
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/information-artifacts/information-artifacts-view.html (renamed from catalog-ui/app/scripts/view-models/workspace/tabs/information-artifacts/information-artifacts-view.html)15
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/information-artifacts/information-artifacts.less (renamed from catalog-ui/app/scripts/view-models/workspace/tabs/information-artifacts/information-artifacts.less)14
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/inputs/inputs.less (renamed from catalog-ui/app/scripts/view-models/workspace/tabs/inputs/inputs.less)95
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/inputs/resource-input/resource-inputs-view-model.ts117
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/inputs/resource-input/resource-inputs-view.html86
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/inputs/resource-input/resource-inputs.less (renamed from catalog-ui/app/scripts/view-models/workspace/tabs/inputs/resource-input/resource-inputs.less)0
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/inputs/service-input/service-inputs-view-model.ts378
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/inputs/service-input/service-inputs-view.html134
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/inputs/service-input/service-inputs.less (renamed from catalog-ui/app/scripts/view-models/workspace/tabs/inputs/service-input/service-inputs.less)19
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/management-workflow/management-workflow-view-model.ts (renamed from catalog-ui/app/scripts/view-models/workspace/tabs/management-workflow/management-workflow-view-model.ts)57
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/management-workflow/management-workflow-view.html (renamed from catalog-ui/app/scripts/view-models/workspace/tabs/management-workflow/management-workflow-view.html)0
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/network-call-flow/network-call-flow-view-model.ts79
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/network-call-flow/network-call-flow-view.html (renamed from catalog-ui/app/scripts/view-models/workspace/tabs/network-call-flow/network-call-flow-view.html)0
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/product-hierarchy/product-hierarchy-view-model.ts109
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/product-hierarchy/product-hierarchy-view.html (renamed from catalog-ui/app/scripts/view-models/workspace/tabs/product-hierarchy/product-hierarchy-view.html)0
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/product-hierarchy/product-hierarchy.less (renamed from catalog-ui/app/scripts/view-models/workspace/tabs/product-hierarchy/product-hierarchy.less)0
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/properties/properties-view-model.ts92
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/properties/properties-view.html (renamed from catalog-ui/app/scripts/view-models/workspace/tabs/properties/properties-view.html)21
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/properties/properties.less (renamed from catalog-ui/app/scripts/view-models/workspace/tabs/properties/properties.less)0
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/req-and-capabilities/req-and-capabilities-view-model.ts147
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/req-and-capabilities/req-and-capabilities-view.html (renamed from catalog-ui/app/scripts/view-models/workspace/tabs/req-and-capabilities/req-and-capabilities-view.html)47
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/req-and-capabilities/req-and-capabilities.less (renamed from catalog-ui/app/scripts/view-models/workspace/tabs/req-and-capabilities/req-and-capabilities.less)0
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/tosca-artifacts/tosca-artifacts-view-model.ts84
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/tosca-artifacts/tosca-artifacts-view.html (renamed from catalog-ui/app/scripts/view-models/workspace/tabs/tosca-artifacts/tosca-artifacts-view.html)16
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/tosca-artifacts/tosca-artifacts.less (renamed from catalog-ui/app/scripts/view-models/workspace/tabs/tosca-artifacts/tosca-artifacts.less)4
-rw-r--r--catalog-ui/src/app/view-models/workspace/workspace-view-model.ts718
-rw-r--r--catalog-ui/src/app/view-models/workspace/workspace-view.html (renamed from catalog-ui/app/scripts/view-models/workspace/workspace-view.html)14
-rw-r--r--catalog-ui/src/app/view-models/workspace/workspace.less150
-rw-r--r--catalog-ui/src/assets/.gitkeep0
-rw-r--r--catalog-ui/src/assets/languages/en_US.json (renamed from catalog-ui/app/languages/en_US_OS.json)31
-rw-r--r--catalog-ui/src/assets/styles/animation.less (renamed from catalog-ui/app/styles/animation.less)0
-rw-r--r--catalog-ui/src/assets/styles/app.less119
-rw-r--r--catalog-ui/src/assets/styles/buttons.less (renamed from catalog-ui/app/styles/buttons.less)0
-rw-r--r--catalog-ui/src/assets/styles/dark-header.less (renamed from catalog-ui/app/styles/dark-header.less)0
-rw-r--r--catalog-ui/src/assets/styles/fonts.less (renamed from catalog-ui/app/styles/fonts.less)0
-rw-r--r--catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-Bd.eot (renamed from catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-Bd.eot)bin92160 -> 92160 bytes
-rw-r--r--catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-Bd.svg (renamed from catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-Bd.svg)0
-rw-r--r--catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-Bd.ttf (renamed from catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-Bd.ttf)bin93916 -> 93916 bytes
-rw-r--r--catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-Bd.woff (renamed from catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-Bd.woff)bin42192 -> 42192 bytes
-rw-r--r--catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-BdIt.eot (renamed from catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-BdIt.eot)bin104184 -> 104184 bytes
-rw-r--r--catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-BdIt.svg (renamed from catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-BdIt.svg)0
-rw-r--r--catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-BdIt.ttf (renamed from catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-BdIt.ttf)bin105932 -> 105932 bytes
-rw-r--r--catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-BdIt.woff (renamed from catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-BdIt.woff)bin46444 -> 46444 bytes
-rw-r--r--catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-Bk.eot (renamed from catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-Bk.eot)bin86088 -> 86088 bytes
-rw-r--r--catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-Bk.svg (renamed from catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-Bk.svg)0
-rw-r--r--catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-Bk.ttf (renamed from catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-Bk.ttf)bin88696 -> 88696 bytes
-rw-r--r--catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-Bk.woff (renamed from catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-Bk.woff)bin39280 -> 39280 bytes
-rw-r--r--catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-BkIt.eot (renamed from catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-BkIt.eot)bin104224 -> 104224 bytes
-rw-r--r--catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-BkIt.svg (renamed from catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-BkIt.svg)0
-rw-r--r--catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-BkIt.ttf (renamed from catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-BkIt.ttf)bin105972 -> 105972 bytes
-rw-r--r--catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-BkIt.woff (renamed from catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-BkIt.woff)bin46676 -> 46676 bytes
-rw-r--r--catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-Lt.eot (renamed from catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-Lt.eot)bin89640 -> 89640 bytes
-rw-r--r--catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-Lt.svg (renamed from catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-Lt.svg)0
-rw-r--r--catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-Lt.ttf (renamed from catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-Lt.ttf)bin92288 -> 92288 bytes
-rw-r--r--catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-Lt.woff (renamed from catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-Lt.woff)bin40332 -> 40332 bytes
-rw-r--r--catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-LtIt.eot (renamed from catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-LtIt.eot)bin108396 -> 108396 bytes
-rw-r--r--catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-LtIt.svg (renamed from catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-LtIt.svg)0
-rw-r--r--catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-LtIt.ttf (renamed from catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-LtIt.ttf)bin110192 -> 110192 bytes
-rw-r--r--catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-LtIt.woff (renamed from catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-LtIt.woff)bin48120 -> 48120 bytes
-rw-r--r--catalog-ui/src/assets/styles/fonts/OmnesATT/AT&T Variation ID.tab (renamed from catalog-ui/app/styles/fonts/OmnesATT/AT&T Variation ID.tab)0
-rw-r--r--catalog-ui/src/assets/styles/fonts/OmnesATT/OmnesATTW02BoldItalic.eot (renamed from catalog-ui/app/styles/fonts/OmnesATT/OmnesATTW02BoldItalic.eot)bin31322 -> 31322 bytes
-rw-r--r--catalog-ui/src/assets/styles/fonts/OmnesATT/OmnesATTW02BoldItalic.svg (renamed from catalog-ui/app/styles/fonts/OmnesATT/OmnesATTW02BoldItalic.svg)0
-rw-r--r--catalog-ui/src/assets/styles/fonts/OmnesATT/OmnesATTW02BoldItalic.ttf (renamed from catalog-ui/app/styles/fonts/OmnesATT/OmnesATTW02BoldItalic.ttf)bin68660 -> 68660 bytes
-rw-r--r--catalog-ui/src/assets/styles/fonts/OmnesATT/OmnesATTW02BoldItalic.woff (renamed from catalog-ui/app/styles/fonts/OmnesATT/OmnesATTW02BoldItalic.woff)bin35986 -> 35986 bytes
-rw-r--r--catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02.eot (renamed from catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02.eot)bin30321 -> 30321 bytes
-rw-r--r--catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02.svg (renamed from catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02.svg)0
-rw-r--r--catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02.ttf (renamed from catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02.ttf)bin71692 -> 71692 bytes
-rw-r--r--catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02.woff (renamed from catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02.woff)bin35610 -> 35610 bytes
-rw-r--r--catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02Bold.eot (renamed from catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02Bold.eot)bin32077 -> 32077 bytes
-rw-r--r--catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02Bold.svg (renamed from catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02Bold.svg)0
-rw-r--r--catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02Bold.ttf (renamed from catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02Bold.ttf)bin71564 -> 71564 bytes
-rw-r--r--catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02Bold.woff (renamed from catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02Bold.woff)bin37149 -> 37149 bytes
-rw-r--r--catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02Italic.eot (renamed from catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02Italic.eot)bin32079 -> 32079 bytes
-rw-r--r--catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02Italic.svg (renamed from catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02Italic.svg)0
-rw-r--r--catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02Italic.ttf (renamed from catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02Italic.ttf)bin76564 -> 76564 bytes
-rw-r--r--catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02Italic.woff (renamed from catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02Italic.woff)bin37872 -> 37872 bytes
-rw-r--r--catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02Light.eot (renamed from catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02Light.eot)bin32072 -> 32072 bytes
-rw-r--r--catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02Light.svg (renamed from catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02Light.svg)0
-rw-r--r--catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02Light.ttf (renamed from catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02Light.ttf)bin73968 -> 73968 bytes
-rw-r--r--catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02Light.woff (renamed from catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02Light.woff)bin37342 -> 37342 bytes
-rw-r--r--catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02LightItalic.eot (renamed from catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02LightItalic.eot)bin30983 -> 30983 bytes
-rw-r--r--catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02LightItalic.svg (renamed from catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02LightItalic.svg)0
-rw-r--r--catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02LightItalic.ttf (renamed from catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02LightItalic.ttf)bin70088 -> 70088 bytes
-rw-r--r--catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02LightItalic.woff (renamed from catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02LightItalic.woff)bin36261 -> 36261 bytes
-rw-r--r--catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02Medium.eot (renamed from catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02Medium.eot)bin28695 -> 28695 bytes
-rw-r--r--catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02Medium.svg (renamed from catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02Medium.svg)0
-rw-r--r--catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02Medium.ttf (renamed from catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02Medium.ttf)bin65152 -> 65152 bytes
-rw-r--r--catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02Medium.woff (renamed from catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02Medium.woff)bin33641 -> 33641 bytes
-rw-r--r--catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02MediumItalic.eot (renamed from catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02MediumItalic.eot)bin33730 -> 33730 bytes
-rw-r--r--catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02MediumItalic.svg (renamed from catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02MediumItalic.svg)0
-rw-r--r--catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02MediumItalic.ttf (renamed from catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02MediumItalic.ttf)bin77508 -> 77508 bytes
-rw-r--r--catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02MediumItalic.woff (renamed from catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02MediumItalic.woff)bin39182 -> 39182 bytes
-rw-r--r--catalog-ui/src/assets/styles/fonts/OmnesATT/demo-async.htm (renamed from catalog-ui/app/styles/fonts/OmnesATT/demo-async.htm)0
-rw-r--r--catalog-ui/src/assets/styles/fonts/OmnesATT/demo.htm (renamed from catalog-ui/app/styles/fonts/OmnesATT/demo.htm)0
-rw-r--r--catalog-ui/src/assets/styles/form-elements.less (renamed from catalog-ui/app/styles/form-elements.less)0
-rw-r--r--catalog-ui/src/assets/styles/global.less (renamed from catalog-ui/app/styles/global.less)0
-rw-r--r--catalog-ui/src/assets/styles/images/anonymous.jpg (renamed from catalog-ui/app/styles/images/anonymous.jpg)bin1150 -> 1150 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/att-globe.svg1
-rw-r--r--catalog-ui/src/assets/styles/images/att_logo_white.png (renamed from catalog-ui/app/styles/images/att_logo_white.png)bin2827 -> 2827 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/relationship-icons/AttachesTo.svg (renamed from catalog-ui/app/styles/images/relationship-icons/AttachesTo.svg)0
-rw-r--r--catalog-ui/src/assets/styles/images/relationship-icons/BindsTo.svg (renamed from catalog-ui/app/styles/images/relationship-icons/BindsTo.svg)0
-rw-r--r--catalog-ui/src/assets/styles/images/relationship-icons/ConnectedTo.svg (renamed from catalog-ui/app/styles/images/relationship-icons/ConnectedTo.svg)0
-rw-r--r--catalog-ui/src/assets/styles/images/relationship-icons/DependsOn.svg (renamed from catalog-ui/app/styles/images/relationship-icons/DependsOn.svg)0
-rw-r--r--catalog-ui/src/assets/styles/images/relationship-icons/HostedOn.svg (renamed from catalog-ui/app/styles/images/relationship-icons/HostedOn.svg)0
-rw-r--r--catalog-ui/src/assets/styles/images/relationship-icons/LinksTo.svg (renamed from catalog-ui/app/styles/images/relationship-icons/LinksTo.svg)0
-rw-r--r--catalog-ui/src/assets/styles/images/relationship-icons/RoutesTo.svg (renamed from catalog-ui/app/styles/images/relationship-icons/RoutesTo.svg)0
-rw-r--r--catalog-ui/src/assets/styles/images/relationship-icons/arrow.png (renamed from catalog-ui/app/styles/images/relationship-icons/arrow.png)bin1111 -> 1111 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/relationship-icons/arrow.svg (renamed from catalog-ui/app/styles/images/relationship-icons/arrow.svg)0
-rw-r--r--catalog-ui/src/assets/styles/images/relationship-icons/arrow_connection_right.svg (renamed from catalog-ui/app/styles/images/relationship-icons/arrow_connection_right.svg)0
-rw-r--r--catalog-ui/src/assets/styles/images/relationship-icons/attach.png (renamed from catalog-ui/app/styles/images/relationship-icons/attach.png)bin1485 -> 1485 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/relationship-icons/binding.png (renamed from catalog-ui/app/styles/images/relationship-icons/binding.png)bin1385 -> 1385 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/relationship-icons/conected.png (renamed from catalog-ui/app/styles/images/relationship-icons/conected.png)bin1481 -> 1481 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/relationship-icons/conected.svg (renamed from catalog-ui/app/styles/images/relationship-icons/conected.svg)0
-rw-r--r--catalog-ui/src/assets/styles/images/relationship-icons/dependency.png (renamed from catalog-ui/app/styles/images/relationship-icons/dependency.png)bin1632 -> 1632 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/relationship-icons/host.png (renamed from catalog-ui/app/styles/images/relationship-icons/host.png)bin1836 -> 1836 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/relationship-icons/link.png (renamed from catalog-ui/app/styles/images/relationship-icons/link.png)bin1628 -> 1628 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/relationship-icons/local_storage.png (renamed from catalog-ui/app/styles/images/relationship-icons/local_storage.png)bin1485 -> 1485 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/relationship-icons/local_storage.svg (renamed from catalog-ui/app/styles/images/relationship-icons/local_storage.svg)0
-rw-r--r--catalog-ui/src/assets/styles/images/relationship-icons/rout.png (renamed from catalog-ui/app/styles/images/relationship-icons/rout.png)bin1630 -> 1630 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/Red_PLUS_HOVER.png (renamed from catalog-ui/app/styles/images/resource-icons/Red_PLUS_HOVER.png)bin1456 -> 1456 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/Resource_Icons_NB_COLLABORATION-.png (renamed from catalog-ui/app/styles/images/resource-icons/Resource_Icons_NB_COLLABORATION-.png)bin3898 -> 3898 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/Resource_Icons_NB_COMPUTE-AS-SERVICE-.png (renamed from catalog-ui/app/styles/images/resource-icons/Resource_Icons_NB_COMPUTE-AS-SERVICE-.png)bin3129 -> 3129 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/Resource_Icons_NB_MESSAGING-.png (renamed from catalog-ui/app/styles/images/resource-icons/Resource_Icons_NB_MESSAGING-.png)bin2376 -> 2376 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/Resource_Icons_NB_MOBILITY.png (renamed from catalog-ui/app/styles/images/resource-icons/Resource_Icons_NB_MOBILITY.png)bin3396 -> 3396 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/Resource_Icons_NB_NETWORK-.png (renamed from catalog-ui/app/styles/images/resource-icons/Resource_Icons_NB_NETWORK-.png)bin4190 -> 4190 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/Resource_Icons_NB_NETWORK-CLOUD-.png (renamed from catalog-ui/app/styles/images/resource-icons/Resource_Icons_NB_NETWORK-CLOUD-.png)bin2908 -> 2908 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/Resource_Icons_NB_NETWORK-L-1-3.png (renamed from catalog-ui/app/styles/images/resource-icons/Resource_Icons_NB_NETWORK-L-1-3.png)bin3239 -> 3239 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/Resource_Icons_NB_NETWORK-L-4.png (renamed from catalog-ui/app/styles/images/resource-icons/Resource_Icons_NB_NETWORK-L-4.png)bin3104 -> 3104 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/Resource_Icons_NB_NOTIFICATION-.png (renamed from catalog-ui/app/styles/images/resource-icons/Resource_Icons_NB_NOTIFICATION-.png)bin2818 -> 2818 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/Resource_Icons_NB_ORPHAN.png (renamed from catalog-ui/app/styles/images/resource-icons/Resource_Icons_NB_ORPHAN.png)bin3831 -> 3831 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/Resource_Icons_NB_PLATFORM-AS-SERVICE-.png (renamed from catalog-ui/app/styles/images/resource-icons/Resource_Icons_NB_PLATFORM-AS-SERVICE-.png)bin3728 -> 3728 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/Resource_Icons_NB_SECURITY-.png (renamed from catalog-ui/app/styles/images/resource-icons/Resource_Icons_NB_SECURITY-.png)bin3523 -> 3523 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/Resource_Icons_NB_SETTING-.png (renamed from catalog-ui/app/styles/images/resource-icons/Resource_Icons_NB_SETTING-.png)bin4019 -> 4019 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/Resource_Icons_NB_avater.png (renamed from catalog-ui/app/styles/images/resource-icons/Resource_Icons_NB_avater.png)bin3818 -> 3818 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/Resource_Icons_STORAGE-AS-SERVICE.png (renamed from catalog-ui/app/styles/images/resource-icons/Resource_Icons_STORAGE-AS-SERVICE.png)bin3106 -> 3106 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/alcatelLucent.png (renamed from catalog-ui/app/styles/images/resource-icons/alcatelLucent.png)bin3301 -> 3301 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/allotted_resource.pngbin0 -> 2163 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/applicationServer.png (renamed from catalog-ui/app/styles/images/resource-icons/applicationServer.png)bin2152 -> 2152 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/aricent.png (renamed from catalog-ui/app/styles/images/resource-icons/aricent.png)bin2407 -> 2407 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/att.png (renamed from catalog-ui/app/styles/images/resource-icons/att.png)bin3241 -> 3241 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/borderElement.png (renamed from catalog-ui/app/styles/images/resource-icons/borderElement.png)bin3744 -> 3744 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/broadsoft.png (renamed from catalog-ui/app/styles/images/resource-icons/broadsoft.png)bin2725 -> 2725 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/brocade.png (renamed from catalog-ui/app/styles/images/resource-icons/brocade.png)bin3601 -> 3601 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/call_controll.png (renamed from catalog-ui/app/styles/images/resource-icons/call_controll.png)bin3146 -> 3146 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/canvasPlusIcon-red.png (renamed from catalog-ui/app/styles/images/resource-icons/canvasPlusIcon-red.png)bin1434 -> 1434 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/canvasPlusIcon.png (renamed from catalog-ui/app/styles/images/resource-icons/canvasPlusIcon.png)bin1455 -> 1455 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/cisco.png (renamed from catalog-ui/app/styles/images/resource-icons/cisco.png)bin2702 -> 2702 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/closeModule.png (renamed from catalog-ui/app/styles/images/resource-icons/closeModule.png)bin15427 -> 15427 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/closeModuleHover.png (renamed from catalog-ui/app/styles/images/resource-icons/closeModuleHover.png)bin14979 -> 14979 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/cloud.png (renamed from catalog-ui/app/styles/images/resource-icons/cloud.png)bin3561 -> 3561 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/cloudep.png (renamed from catalog-ui/app/styles/images/resource-icons/cloudep.png)bin2944 -> 2944 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/compute.png (renamed from catalog-ui/app/styles/images/resource-icons/compute.png)bin2212 -> 2212 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/connector.png (renamed from catalog-ui/app/styles/images/resource-icons/connector.png)bin2040 -> 2040 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/cp.png (renamed from catalog-ui/app/styles/images/resource-icons/cp.png)bin1507 -> 1507 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/database.png (renamed from catalog-ui/app/styles/images/resource-icons/database.png)bin2447 -> 2447 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/dcae_analytics.png (renamed from catalog-ui/app/styles/images/resource-icons/dcae_analytics.png)bin2501 -> 2501 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/dcae_collector.png (renamed from catalog-ui/app/styles/images/resource-icons/dcae_collector.png)bin2582 -> 2582 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/dcae_database.png (renamed from catalog-ui/app/styles/images/resource-icons/dcae_database.png)bin2447 -> 2447 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/dcae_microservice.png (renamed from catalog-ui/app/styles/images/resource-icons/dcae_microservice.png)bin2485 -> 2485 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/dcae_policy.png (renamed from catalog-ui/app/styles/images/resource-icons/dcae_policy.png)bin2492 -> 2492 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/dcae_source.png (renamed from catalog-ui/app/styles/images/resource-icons/dcae_source.png)bin3451 -> 3451 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/dcae_utilty.png (renamed from catalog-ui/app/styles/images/resource-icons/dcae_utilty.png)bin3840 -> 3840 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/default.png (renamed from catalog-ui/app/styles/images/resource-icons/default.png)bin3831 -> 3831 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/defaulticon.png (renamed from catalog-ui/app/styles/images/resource-icons/defaulticon.png)bin2132 -> 2132 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/ericsson.png (renamed from catalog-ui/app/styles/images/resource-icons/ericsson.png)bin3606 -> 3606 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/firewall.png (renamed from catalog-ui/app/styles/images/resource-icons/firewall.png)bin3348 -> 3348 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/fortinet.png (renamed from catalog-ui/app/styles/images/resource-icons/fortinet.png)bin2016 -> 2016 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/gateway.png (renamed from catalog-ui/app/styles/images/resource-icons/gateway.png)bin2647 -> 2647 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/juniper.png (renamed from catalog-ui/app/styles/images/resource-icons/juniper.png)bin3505 -> 3505 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/loadBalancer.png (renamed from catalog-ui/app/styles/images/resource-icons/loadBalancer.png)bin2949 -> 2949 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/metaswitch.png (renamed from catalog-ui/app/styles/images/resource-icons/metaswitch.png)bin3141 -> 3141 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/module.png (renamed from catalog-ui/app/styles/images/resource-icons/module.png)bin1216 -> 1216 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/mysql.png (renamed from catalog-ui/app/styles/images/resource-icons/mysql.png)bin3033 -> 3033 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/network.png (renamed from catalog-ui/app/styles/images/resource-icons/network.png)bin4214 -> 4214 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/networkrules.png (renamed from catalog-ui/app/styles/images/resource-icons/networkrules.png)bin2920 -> 2920 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/nokia_siemens.png (renamed from catalog-ui/app/styles/images/resource-icons/nokia_siemens.png)bin2615 -> 2615 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/objectStorage.png (renamed from catalog-ui/app/styles/images/resource-icons/objectStorage.png)bin3031 -> 3031 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/openModule.png (renamed from catalog-ui/app/styles/images/resource-icons/openModule.png)bin14990 -> 14990 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/openModuleHover.png (renamed from catalog-ui/app/styles/images/resource-icons/openModuleHover.png)bin14989 -> 14989 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/oracle.png (renamed from catalog-ui/app/styles/images/resource-icons/oracle.png)bin2432 -> 2432 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/ossep.png (renamed from catalog-ui/app/styles/images/resource-icons/ossep.png)bin3768 -> 3768 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/personep.png (renamed from catalog-ui/app/styles/images/resource-icons/personep.png)bin3419 -> 3419 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/port.png (renamed from catalog-ui/app/styles/images/resource-icons/port.png)bin2359 -> 2359 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/premisesep.png (renamed from catalog-ui/app/styles/images/resource-icons/premisesep.png)bin2822 -> 2822 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/router.png (renamed from catalog-ui/app/styles/images/resource-icons/router.png)bin4031 -> 4031 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/securityrules.png (renamed from catalog-ui/app/styles/images/resource-icons/securityrules.png)bin2965 -> 2965 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/selectedCPInstance.png (renamed from catalog-ui/app/styles/images/resource-icons/selectedCPInstance.png)bin1090 -> 1090 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/selectedInstance.png (renamed from catalog-ui/app/styles/images/resource-icons/selectedInstance.png)bin1143 -> 1143 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/selectedUcpeInstance.png (renamed from catalog-ui/app/styles/images/resource-icons/selectedUcpeInstance.png)bin3850 -> 3850 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/selectedVLInstance.png (renamed from catalog-ui/app/styles/images/resource-icons/selectedVLInstance.png)bin1072 -> 1072 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/server.png (renamed from catalog-ui/app/styles/images/resource-icons/server.png)bin2078 -> 2078 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/tropo.png (renamed from catalog-ui/app/styles/images/resource-icons/tropo.png)bin3558 -> 3558 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/ucpe.png (renamed from catalog-ui/app/styles/images/resource-icons/ucpe.png)bin3983 -> 3983 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/uncertified.png (renamed from catalog-ui/app/styles/images/resource-icons/uncertified.png)bin1503 -> 1503 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/vfw.png (renamed from catalog-ui/app/styles/images/resource-icons/vfw.png)bin3730 -> 3730 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/vl.png (renamed from catalog-ui/app/styles/images/resource-icons/vl.png)bin3376741 -> 3376741 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/vrouter.png (renamed from catalog-ui/app/styles/images/resource-icons/vrouter.png)bin3088 -> 3088 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/wanx.png (renamed from catalog-ui/app/styles/images/resource-icons/wanx.png)bin3166 -> 3166 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/service-icons/call_controll.png (renamed from catalog-ui/app/styles/images/service-icons/call_controll.png)bin3238 -> 3238 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/service-icons/collaboration.png (renamed from catalog-ui/app/styles/images/service-icons/collaboration.png)bin3804 -> 3804 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/service-icons/collaboration1.png (renamed from catalog-ui/app/styles/images/service-icons/collaboration1.png)bin3194 -> 3194 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/service-icons/compute.png (renamed from catalog-ui/app/styles/images/service-icons/compute.png)bin3201 -> 3201 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/service-icons/defaulticon.png (renamed from catalog-ui/app/styles/images/service-icons/defaulticon.png)bin2168 -> 2168 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/service-icons/messaging.png (renamed from catalog-ui/app/styles/images/service-icons/messaging.png)bin2458 -> 2458 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/service-icons/mobility.png (renamed from catalog-ui/app/styles/images/service-icons/mobility.png)bin3333 -> 3333 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/service-icons/network_l_1-3.png (renamed from catalog-ui/app/styles/images/service-icons/network_l_1-3.png)bin3030 -> 3030 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/service-icons/network_l_4.png (renamed from catalog-ui/app/styles/images/service-icons/network_l_4.png)bin2961 -> 2961 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/service-icons/notification.png (renamed from catalog-ui/app/styles/images/service-icons/notification.png)bin2714 -> 2714 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/service-icons/platform.png (renamed from catalog-ui/app/styles/images/service-icons/platform.png)bin3762 -> 3762 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/service-icons/storage.png (renamed from catalog-ui/app/styles/images/service-icons/storage.png)bin3136 -> 3136 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/service-icons/uncertified.png (renamed from catalog-ui/app/styles/images/service-icons/uncertified.png)bin1503 -> 1503 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/sprites/sprite-global-old.png (renamed from catalog-ui/app/styles/images/sprites/sprite-global-old.png)bin84465 -> 84465 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/sprites/sprite-global.pngbin0 -> 95876 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/sprites/sprite-product-icons.png (renamed from catalog-ui/app/styles/images/sprites/sprite-product-icons.png)bin132122 -> 132122 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/sprites/sprite-resource-icons.png (renamed from catalog-ui/app/styles/images/sprites/sprite-resource-icons.png)bin469610 -> 474238 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/sprites/sprite-services-icons.png (renamed from catalog-ui/app/styles/images/sprites/sprite-services-icons.png)bin127233 -> 127233 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/sprites/tlv-sprite.png (renamed from catalog-ui/app/styles/images/sprites/tlv-sprite.png)bin14677 -> 14677 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/tutorial/10.png (renamed from catalog-ui/app/styles/images/tutorial/10.png)bin6707 -> 6707 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/tutorial/11.png (renamed from catalog-ui/app/styles/images/tutorial/11.png)bin7697 -> 7697 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/tutorial/13.png (renamed from catalog-ui/app/styles/images/tutorial/13.png)bin11072 -> 11072 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/tutorial/14.png (renamed from catalog-ui/app/styles/images/tutorial/14.png)bin2768 -> 2768 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/tutorial/15.png (renamed from catalog-ui/app/styles/images/tutorial/15.png)bin8250 -> 8250 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/tutorial/16.png (renamed from catalog-ui/app/styles/images/tutorial/16.png)bin11421 -> 11421 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/tutorial/17.png (renamed from catalog-ui/app/styles/images/tutorial/17.png)bin12030 -> 12030 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/tutorial/18.png (renamed from catalog-ui/app/styles/images/tutorial/18.png)bin10696 -> 10696 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/tutorial/19.png (renamed from catalog-ui/app/styles/images/tutorial/19.png)bin7678 -> 7678 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/tutorial/2.png (renamed from catalog-ui/app/styles/images/tutorial/2.png)bin5480 -> 5480 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/tutorial/20.png (renamed from catalog-ui/app/styles/images/tutorial/20.png)bin8421 -> 8421 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/tutorial/21.png (renamed from catalog-ui/app/styles/images/tutorial/21.png)bin11205 -> 11205 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/tutorial/22.png (renamed from catalog-ui/app/styles/images/tutorial/22.png)bin9610 -> 9610 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/tutorial/23.png (renamed from catalog-ui/app/styles/images/tutorial/23.png)bin9229 -> 9229 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/tutorial/24.png (renamed from catalog-ui/app/styles/images/tutorial/24.png)bin7842 -> 7842 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/tutorial/25.png (renamed from catalog-ui/app/styles/images/tutorial/25.png)bin7579 -> 7579 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/tutorial/26.png (renamed from catalog-ui/app/styles/images/tutorial/26.png)bin8364 -> 8364 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/tutorial/27.png (renamed from catalog-ui/app/styles/images/tutorial/27.png)bin10243 -> 10243 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/tutorial/28.png (renamed from catalog-ui/app/styles/images/tutorial/28.png)bin6838 -> 6838 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/tutorial/29.png (renamed from catalog-ui/app/styles/images/tutorial/29.png)bin9140 -> 9140 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/tutorial/3.png (renamed from catalog-ui/app/styles/images/tutorial/3.png)bin6717 -> 6717 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/tutorial/30.png (renamed from catalog-ui/app/styles/images/tutorial/30.png)bin8680 -> 8680 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/tutorial/4.png (renamed from catalog-ui/app/styles/images/tutorial/4.png)bin3154 -> 3154 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/tutorial/5.png (renamed from catalog-ui/app/styles/images/tutorial/5.png)bin3233 -> 3233 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/tutorial/6.png (renamed from catalog-ui/app/styles/images/tutorial/6.png)bin6294 -> 6294 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/tutorial/7.png (renamed from catalog-ui/app/styles/images/tutorial/7.png)bin6574 -> 6574 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/tutorial/8.png (renamed from catalog-ui/app/styles/images/tutorial/8.png)bin8534 -> 8534 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/welcome.png (renamed from catalog-ui/app/styles/images/welcome.png)bin44721 -> 44721 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/welcome/002.png (renamed from catalog-ui/app/styles/images/welcome/bg/002.png)bin2804026 -> 2804026 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/welcome/sprite.png (renamed from catalog-ui/app/styles/images/welcome/sprite.png)bin3386285 -> 3386285 bytes
-rw-r--r--catalog-ui/src/assets/styles/layout/header.less (renamed from catalog-ui/app/styles/layout/header.less)0
-rw-r--r--catalog-ui/src/assets/styles/layout/main.less (renamed from catalog-ui/app/styles/layout/main.less)16
-rw-r--r--catalog-ui/src/assets/styles/layout/sidebar.less (renamed from catalog-ui/app/styles/layout/sidebar.less)0
-rw-r--r--catalog-ui/src/assets/styles/mixins.less (renamed from catalog-ui/app/styles/mixins.less)52
-rw-r--r--catalog-ui/src/assets/styles/mixins_old.less (renamed from catalog-ui/app/styles/mixins_old.less)0
-rw-r--r--catalog-ui/src/assets/styles/modal.less (renamed from catalog-ui/app/styles/modal.less)1
-rw-r--r--catalog-ui/src/assets/styles/multi-level-expand-collapse.less33
-rw-r--r--catalog-ui/src/assets/styles/scroller.less (renamed from catalog-ui/app/styles/scroller.less)0
-rw-r--r--catalog-ui/src/assets/styles/sdc-ui.css361
-rw-r--r--catalog-ui/src/assets/styles/sprite-old.less (renamed from catalog-ui/app/styles/sprite-old.less)0
-rw-r--r--catalog-ui/src/assets/styles/sprite-product-icons.less (renamed from catalog-ui/app/styles/sprite-product-icons.less)0
-rw-r--r--catalog-ui/src/assets/styles/sprite-resource-icons.less (renamed from catalog-ui/app/styles/sprite-resource-icons.less)10
-rw-r--r--catalog-ui/src/assets/styles/sprite-services-icons.less (renamed from catalog-ui/app/styles/sprite-services-icons.less)0
-rw-r--r--catalog-ui/src/assets/styles/sprite.html (renamed from catalog-ui/app/styles/sprite.html)0
-rw-r--r--catalog-ui/src/assets/styles/sprite.less (renamed from catalog-ui/app/styles/sprite.less)45
-rw-r--r--catalog-ui/src/assets/styles/table-flex.less (renamed from catalog-ui/app/styles/table-flex.less)0
-rw-r--r--catalog-ui/src/assets/styles/tlv-buttons.less (renamed from catalog-ui/app/styles/tlv-buttons.less)0
-rw-r--r--catalog-ui/src/assets/styles/tlv-checkbox.less (renamed from catalog-ui/app/styles/tlv-checkbox.less)0
-rw-r--r--catalog-ui/src/assets/styles/tlv-loader.less (renamed from catalog-ui/app/styles/tlv-loader.less)0
-rw-r--r--catalog-ui/src/assets/styles/tlv-sprite.less (renamed from catalog-ui/app/styles/tlv-sprite.less)0
-rw-r--r--catalog-ui/src/assets/styles/tooltips.less (renamed from catalog-ui/app/styles/tooltips.less)60
-rw-r--r--catalog-ui/src/assets/styles/variables-old.less (renamed from catalog-ui/app/styles/variables-old.less)6
-rw-r--r--catalog-ui/src/assets/styles/variables.less (renamed from catalog-ui/app/styles/variables.less)15
-rw-r--r--catalog-ui/src/assets/styles/welcome-sprite.less (renamed from catalog-ui/app/styles/welcome-sprite.less)0
-rw-r--r--catalog-ui/src/assets/styles/welcome-style.less63
-rw-r--r--catalog-ui/src/index.html26
-rw-r--r--catalog-ui/src/main.ts30
-rw-r--r--catalog-ui/src/polyfills.ts39
-rw-r--r--catalog-ui/src/styles.less11
-rw-r--r--catalog-ui/src/third-party/PunchOutRegistry.js (renamed from catalog-ui/app/third-party/PunchOutRegistry.js)2
-rw-r--r--catalog-ui/src/third-party/cytoscape.js-edge-editation/CytoscapeEdgeEditation.js (renamed from catalog-ui/non_bower_components/cytoscape.js-edge-editation/CytoscapeEdgeEditation.js)5
-rw-r--r--catalog-ui/src/tsconfig.json32
-rw-r--r--catalog-ui/src/typings/angular-ui-bootstrap/angular-ui-bootstrap.d.ts (renamed from catalog-ui/typings/angular-ui-bootstrap/angular-ui-bootstrap.d.ts)2
-rw-r--r--catalog-ui/src/typings/angular-ui-router/angular-ui-router.d.ts (renamed from catalog-ui/typings/angular-ui-router/angular-ui-router.d.ts)0
-rw-r--r--catalog-ui/src/typings/angularjs/angular-mocks.d.ts (renamed from catalog-ui/typings/angularjs/angular-mocks.d.ts)46
-rw-r--r--catalog-ui/src/typings/angularjs/angular-resource.d.ts (renamed from catalog-ui/typings/angularjs/angular-resource.d.ts)0
-rw-r--r--catalog-ui/src/typings/angularjs/angular.d.ts (renamed from catalog-ui/typings/angularjs/angular.d.ts)0
-rw-r--r--catalog-ui/src/typings/angularjs/restangular.d.ts (renamed from catalog-ui/typings/angularjs/restangular.d.ts)0
-rw-r--r--catalog-ui/src/typings/cytoscape/cytoscape-extension.js (renamed from catalog-ui/typings/cytoscape/cytoscape-extension.js)0
-rw-r--r--catalog-ui/src/typings/cytoscape/cytoscape-extension.ts (renamed from catalog-ui/typings/cytoscape/cytoscape-extension.ts)0
-rw-r--r--catalog-ui/src/typings/cytoscape/cytoscape.d.ts (renamed from catalog-ui/typings/cytoscape/cytoscape.d.ts)20
-rw-r--r--catalog-ui/src/typings/cytoscape/edge-editation.d.ts (renamed from catalog-ui/typings/cytoscape/edge-editation.d.ts)1
-rw-r--r--catalog-ui/src/typings/d3/d3.d.ts (renamed from catalog-ui/typings/d3/d3.d.ts)0
-rw-r--r--catalog-ui/src/typings/jasmine/jasmine.d.ts (renamed from catalog-ui/typings/jasmine/jasmine.d.ts)0
-rw-r--r--catalog-ui/src/typings/jquery/jquery.d.ts (renamed from catalog-ui/typings/jquery/jquery.d.ts)0
-rw-r--r--catalog-ui/src/typings/jsMd5/md5.d.ts (renamed from catalog-ui/typings/jsMd5/md5.d.ts)0
-rw-r--r--catalog-ui/src/typings/lodash/lodash.d.ts (renamed from catalog-ui/typings/lodash/lodash.d.ts)2
-rw-r--r--catalog-ui/src/typings/notifyjs/notifyjs.d.ts (renamed from catalog-ui/typings/notifyjs/notifyjs.d.ts)0
-rw-r--r--catalog-ui/src/typings/tsd.d.ts (renamed from catalog-ui/typings/tsd.d.ts)0
-rw-r--r--catalog-ui/tests/karma.unit.conf.js149
-rw-r--r--catalog-ui/tsd.json15
-rw-r--r--catalog-ui/tslint.json172
-rw-r--r--catalog-ui/typings/cytoscape/cytoscape-extension.js.map1
-rw-r--r--catalog-ui/webpack.common.js313
-rw-r--r--catalog-ui/webpack.config.js64
-rw-r--r--catalog-ui/webpack.production.js59
-rw-r--r--catalog-ui/webpack.server.js80
-rw-r--r--common-app-api/pom.xml252
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/be/config/Configuration.java110
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/be/config/DistributionEngineConfiguration.java9
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/be/monitoring/BeMonitoringService.java9
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/api/ArtifactGroupTypeEnum.java9
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/api/ArtifactTypeEnum.java35
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/api/Constants.java8
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/api/ResponseInfo.java7
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/api/UploadArtifactInfo.java10
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/api/UserRoleEnum.java8
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorLogUtil.java2
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/config/generation/GenerateEcompErrorsCsv.java1
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/AuditingFieldsKeysEnum.java1
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/FunctionalInterfaces.java61
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/impl/ConfigFileChangeListener.java10
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/impl/FSConfigurationSource.java14
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/jsongraph/util/CommonUtility.java60
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/listener/AppContextListener.java7
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/monitoring/MonitoringEvent.java6
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/monitoring/MonitoringMetricsFetcher.java1
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/rest/api/RestClientServiceExeption.java6
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/rest/impl/HttpRestClientServiceImpl.java39
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/rest/impl/validator/RequestHeadersValidator.java6
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/util/GeneralUtility.java38
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/util/PairUtils.java19
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/util/SerializationUtils.java5
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/util/ValidationUtils.java51
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/util/YamlToObjectConverter.java29
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/util/ZipUtil.java1
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/exception/ResponseFormat.java3
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/fe/config/Configuration.java13
-rw-r--r--common-app-api/src/test/java/org/openecomp/sdc/common/test/CommonUtilsTest.java69
-rw-r--r--common-app-api/src/test/java/org/openecomp/sdc/common/test/TestExternalConfiguration.java83
-rw-r--r--common-app-api/src/test/java/org/openecomp/sdc/common/test/YamlTest.java4
-rw-r--r--common-be/pom.xml198
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/category/CategoryDataDefinition.java4
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/category/GroupingDataDefinition.java4
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/category/SubCategoryDataDefinition.java4
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/components/ComponentMetadataDataDefinition.java186
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/components/ResourceMetadataDataDefinition.java1
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/components/ServiceMetadataDataDefinition.java40
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/AdditionalInfoParameterDataDefinition.java14
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/AdditionalInfoParameterInfo.java (renamed from catalog-model/src/main/java/org/openecomp/sdc/be/model/AdditionalInfoParameterInfo.java)6
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ArtifactDataDefinition.java566
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/AttributeDataDefinition.java25
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/CapabilityDataDefinition.java310
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/CapabilityTypeDataDefinition.java71
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ComponentInstanceDataDefinition.java74
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/CompositionDataDefinition.java40
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ConsumerDataDefinition.java4
-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/GetInputValueDataDefinition.java166
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/GroupDataDefinition.java151
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/GroupInstanceDataDefinition.java246
-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/InputDataDefinition.java63
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/InputsValueDataDefinition.java5
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/InterfaceDataDefinition.java18
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ListCapabilityDataDefinition.java42
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ListDataDefinition.java69
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ListMapPropertiesDataDefinition.java36
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ListRequirementDataDefinition.java43
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapArtifactDataDefinition.java45
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapAttributesDataDefinition.java45
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapCapabiltyProperty.java27
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapDataDefinition.java60
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapGroupsDataDefinition.java45
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapListCapabiltyDataDefinition.java49
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapListRequirementDataDefinition.java50
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapPropertiesDataDefinition.java45
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/OperationDataDefinition.java32
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/PolicyTypeDataDefinition.java4
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ProductMetadataDataDefinition.java1
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/PropertyDataDefinition.java194
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/PropertyRule.java3
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/RelationshipInstDataDefinition.java193
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/RelationshipTypeDataDefinition.java128
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/RequirementDataDefinition.java308
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/SchemaDefinition.java20
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/ComponentFieldsEnum.java51
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/ComponentTypeEnum.java6
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/FilterKeyEnum.java6
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/GraphPropertyEnum.java103
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/JsonPresentationFields.java192
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/NodeTypeEnum.java3
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/OriginTypeEnum.java7
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/ResourceTypeEnum.java66
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/tosca/ToscaDataDefinition.java50
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/utils/CommonBeUtils.java43
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/workers/Worker.java2
-rw-r--r--common-be/src/test/java/org/openecomp/sdc/be/utils/CommonBeUtilsTest.java13
-rw-r--r--distribution-ci/.gitignore1
-rw-r--r--distribution-ci/etc/asdc-client.jksbin1177 -> 0 bytes
-rw-r--r--distribution-ci/etc/asdcclientstore.jksbin907 -> 0 bytes
-rw-r--r--distribution-ci/log4j.properties17
-rw-r--r--distribution-ci/pom.xml107
-rw-r--r--distribution-ci/src/main/java/org/openecomp/test/BaseInit.java122
-rw-r--r--distribution-ci/src/main/java/org/openecomp/test/CallableTask.java57
-rw-r--r--distribution-ci/src/main/java/org/openecomp/test/ClientTest.java33
-rw-r--r--distribution-ci/src/main/java/org/openecomp/test/E2eFlows.java108
-rw-r--r--distribution-ci/src/main/java/org/openecomp/test/NotificationCallback.java19
-rw-r--r--distribution-ci/src/main/java/org/openecomp/test/SimpleCallback.java275
-rw-r--r--distribution-ci/src/main/java/org/openecomp/test/SimpleConfiguration.java149
-rw-r--r--distribution-ci/src/main/resources/ci/conf/log4j.properties34
-rw-r--r--distribution-ci/src/main/resources/ci/conf/sdc-packages.yaml10
-rw-r--r--distribution-ci/src/main/resources/ci/conf/sdc.yaml35
-rw-r--r--distribution-ci/src/main/resources/ci/conf/titan.properties5
-rw-r--r--distribution-ci/src/main/resources/ci/scripts/startTest.sh87
-rw-r--r--distribution-ci/src/test/java/org/openecomp/sdc/ci/tests/execute/downloadArtifactUGN/ClientDownloadArtifact.java491
-rw-r--r--pom.xml8
-rw-r--r--sdc-os-chef/pom.xml73
-rw-r--r--sdc-os-chef/scripts/docker_build.sh196
-rwxr-xr-xsdc-os-chef/scripts/docker_clean.sh1
-rwxr-xr-xsdc-os-chef/scripts/docker_health.sh2
-rwxr-xr-xsdc-os-chef/scripts/docker_run.sh4
-rw-r--r--sdc-os-chef/sdc-backend/Dockerfile8
-rw-r--r--sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/attributes/default.rb4
-rw-r--r--sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/recipes/BE_4_setup_configuration.rb6
-rw-r--r--sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/templates/default/BE-configuration.yaml.erb2
-rw-r--r--sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/templates/default/BE-titan.properties.erb1
-rw-r--r--sdc-os-chef/sdc-cassandra/Dockerfile2
-rw-r--r--sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/files/default/alter_dox_db.cql7
-rw-r--r--sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/files/default/create_dox_db.cql52
-rw-r--r--sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/files/default/titan.properties6
-rw-r--r--sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/files/default/zusammen.tgzbin0 -> 43107275 bytes
-rw-r--r--sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/recipes/01-configureCassandra.rb3
-rw-r--r--sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/recipes/02-createCsUser.rb7
-rw-r--r--sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/recipes/03-createDoxKeyspace.rb26
-rw-r--r--sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/recipes/04-schemaCreation.rb27
-rw-r--r--sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/recipes/05-titanSchemaCreation.rb61
-rw-r--r--sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/recipes/06-migrateZusammenFromDox.rb14
-rw-r--r--sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/templates/default/configuration.yaml.erb154
-rw-r--r--sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/templates/default/create_dox_keyspace.sh.erb105
-rw-r--r--sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/templates/default/titan.properties.erb25
-rw-r--r--sdc-os-chef/sdc-cassandra/chef-solo/roles/cassandra-actions.json4
-rwxr-xr-xsdc-os-chef/sdc-cassandra/startup.sh13
-rw-r--r--sdc-os-chef/sdc-elasticsearch/Dockerfile4
-rw-r--r--sdc-os-chef/sdc-elasticsearch/chef-repo/cookbooks/sdc-elasticsearch/recipes/ES_6_create_kibana_dashboard_virtualization.rb8
-rw-r--r--sdc-os-chef/sdc-frontend/Dockerfile2
-rw-r--r--sdc-os-chef/sdc-kibana/Dockerfile3
-rw-r--r--sdc-os-chef/sdc-sanity/Dockerfile4
-rw-r--r--security-utils/pom.xml38
-rw-r--r--ui-ci-dev/.gitignore2
-rw-r--r--ui-ci-dev/pom.xml283
-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.java428
-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.java408
-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.java234
-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.java219
-rw-r--r--ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/run/StartTest.java394
-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.java346
-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/Files/CP.yml65
-rw-r--r--ui-ci-dev/src/main/resources/Files/CP_LAN - Copy.yml13
-rw-r--r--ui-ci-dev/src/main/resources/Files/CP_LAN.yml19
-rw-r--r--ui-ci-dev/src/main/resources/Files/CP_WAN.yml19
-rw-r--r--ui-ci-dev/src/main/resources/Files/Heat-File 1.yaml791
-rw-r--r--ui-ci-dev/src/main/resources/Files/Heat-File 2.yaml791
-rw-r--r--ui-ci-dev/src/main/resources/Files/Heat-File.yaml791
-rw-r--r--ui-ci-dev/src/main/resources/Files/InValid_tosca_File .yml34
-rw-r--r--ui-ci-dev/src/main/resources/Files/JDM_vf.yml57
-rw-r--r--ui-ci-dev/src/main/resources/Files/JDM_vfc.yml57
-rw-r--r--ui-ci-dev/src/main/resources/Files/Sample_CSAR.csarbin1094 -> 0 bytes
-rw-r--r--ui-ci-dev/src/main/resources/Files/Sample_CSAR2.csarbin1085 -> 0 bytes
-rw-r--r--ui-ci-dev/src/main/resources/Files/UCPE_VFC.yml65
-rw-r--r--ui-ci-dev/src/main/resources/Files/VF.yml17
-rw-r--r--ui-ci-dev/src/main/resources/Files/VFC.yml77
-rw-r--r--ui-ci-dev/src/main/resources/Files/VFCWithAttributes.yml43
-rw-r--r--ui-ci-dev/src/main/resources/Files/VL.yml17
-rw-r--r--ui-ci-dev/src/main/resources/Files/Valid xml.xml4
-rw-r--r--ui-ci-dev/src/main/resources/Files/Valid_tosca_Mycompute.yml35
-rw-r--r--ui-ci-dev/src/main/resources/Files/Valid_tosca_ReplaceTest.yml35
-rw-r--r--ui-ci-dev/src/main/resources/Files/hot-nimbus-oam-volumes_v0.3.env6
-rw-r--r--ui-ci-dev/src/main/resources/Files/hot-nimbus-oam_v0.6.env18
-rw-r--r--ui-ci-dev/src/main/resources/Files/hot-nimbus-oam_v0.6.yaml108
-rw-r--r--ui-ci-dev/src/main/resources/Files/hot-nimbus-pcm_v0.6.yaml80
-rw-r--r--ui-ci-dev/src/main/resources/Files/myYang.xml8
-rw-r--r--ui-ci-dev/src/main/resources/Files/mycompute.yml18
-rw-r--r--ui-ci-dev/src/main/resources/Files/service_with_inputs.csarbin35388 -> 0 bytes
-rw-r--r--ui-ci-dev/src/main/resources/Files/vADTRAN.zipbin2499 -> 0 bytes
-rw-r--r--ui-ci-dev/src/main/resources/Files/vCDN.zipbin4547 -> 0 bytes
-rw-r--r--ui-ci-dev/src/main/resources/Files/vFW_VF.yml58
-rw-r--r--ui-ci-dev/src/main/resources/Files/vFW_VFC.yml58
-rw-r--r--ui-ci-dev/src/main/resources/Files/vRouter_vfc.yml78
-rw-r--r--ui-ci-dev/src/main/resources/Files/valid HEAT_ENV files.env54
-rw-r--r--ui-ci-dev/src/main/resources/Files/validHEATfiles.yaml787
-rw-r--r--ui-ci-dev/src/main/resources/Files/valid_vf.csarbin1316 -> 0 bytes
-rw-r--r--ui-ci-dev/src/main/resources/Files/yamlSample.yml5
-rw-r--r--ui-ci-dev/src/main/resources/Files/yamlSample2.yml5
-rw-r--r--ui-ci-dev/src/main/resources/ci/conf/credentials.yaml48
-rw-r--r--ui-ci-dev/src/main/resources/ci/conf/log4j.properties34
-rw-r--r--ui-ci-dev/src/main/resources/ci/conf/sdc-packages.yaml2
-rw-r--r--ui-ci-dev/src/main/resources/ci/conf/sdc.yaml80
-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-dev/tarball.xml66
-rw-r--r--ui-ci/.gitignore3
-rw-r--r--ui-ci/pom.xml290
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ArtifactInfo.java85
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/CanvasElement.java65
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/CanvasManager.java250
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/CheckBoxStatusEnum.java50
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/CreateAndImportButtonsEnum.java27
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/CreateAndUpdateStepsEnum.java45
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/DataTestIdEnum.java380
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/LifeCycleStateEnum.java46
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/MenuOptionsEnum.java45
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceCategoriesNameEnum.java63
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceCategoriesNameEnum.java39
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/UserCredentials.java57
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/WorkMode.java25
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/environmentLocal10
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/adminworkspace/AdminUserManagment.java141
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resourceui/CatalogLeftFilterPanelCheckBoxTest.java272
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resourceui/CatalogSearchBoxTest.java130
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resourceui/ChangeLifeCycleStatFromCatalogTest.java103
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resourceui/ImportAssetInUITest.java480
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resourceui/VFCanvasTest.java91
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resourceui/VFUITest.java37
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resourceui/VfTests.java33
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resourceui/WorkspaceCheckBoxFilterTest.java120
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Import.java177
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Onboard.java222
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Vf.java377
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/OnboardCSVReport.java63
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/RemoteWebDriverTest.java45
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/SetupCDTest.java538
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ComponentLeftMenu.java25
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/CompositionPage.java56
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/DeploymentArtifactPage.java91
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/GeneralPageElements.java139
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/GovernorOperationPage.java46
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/IconPage.java51
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/InformationalArtifactPage.java57
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/OpsOperationPage.java183
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/PropertiesPage.java61
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/PropertyPopup.java77
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ResourceGeneralPage.java154
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ResourceLeftMenu.java63
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ServiceGeneralPage.java47
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/TesterOperationPage.java71
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/UploadArtifactPopup.java76
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/AdditionalConditions.java84
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/AdminWorkspaceUIUtilies.java71
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/ArtifactUIUtils.java302
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/AuditCDUtils.java67
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/CanvasElement.java54
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/CanvasManager.java181
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/CaptureFailedTests.java54
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/CatalogUIUtilitis.java148
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/FileHandling.java88
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/GeneralUIUtils.java1081
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/ImportAssetUIUtils.java50
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/OnboardingUtils.java457
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/PropertiesUIUtils.java92
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/ResourceUIUtils.java864
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/RestCDUtils.java182
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/ServiceUIUtils.java241
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/ServiceVerificator.java60
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/VfVerificator.java93
-rw-r--r--ui-ci/src/main/resources/Downloads/CP_WAN.yml23
-rw-r--r--ui-ci/src/main/resources/Downloads/Fortigate02_vFW_VFC.yml63
-rw-r--r--ui-ci/src/main/resources/Files/CP.yml65
-rw-r--r--ui-ci/src/main/resources/Files/CPWithAttributes.yml78
-rw-r--r--ui-ci/src/main/resources/Files/CP_LAN - Copy.yml12
-rw-r--r--ui-ci/src/main/resources/Files/CP_LAN.yml19
-rw-r--r--ui-ci/src/main/resources/Files/CP_WAN.yml19
-rw-r--r--ui-ci/src/main/resources/Files/DNSscaling12.8.16.zipbin2868 -> 0 bytes
-rw-r--r--ui-ci/src/main/resources/Files/Heat-File 1.yaml791
-rw-r--r--ui-ci/src/main/resources/Files/Heat-File 2.yaml791
-rw-r--r--ui-ci/src/main/resources/Files/Heat-File.yaml791
-rw-r--r--ui-ci/src/main/resources/Files/InValid_tosca_File .yml34
-rw-r--r--ui-ci/src/main/resources/Files/JDM_vf.yml57
-rw-r--r--ui-ci/src/main/resources/Files/JDM_vfc.yml57
-rw-r--r--ui-ci/src/main/resources/Files/Sample_CSAR.csarbin1085 -> 0 bytes
-rw-r--r--ui-ci/src/main/resources/Files/UCPE_VFC.yml65
-rw-r--r--ui-ci/src/main/resources/Files/VF.yml17
-rw-r--r--ui-ci/src/main/resources/Files/VFC.yml77
-rw-r--r--ui-ci/src/main/resources/Files/Valid xml.xml4
-rw-r--r--ui-ci/src/main/resources/Files/Valid_tosca_Mycompute.yml35
-rw-r--r--ui-ci/src/main/resources/Files/Valid_tosca_ReplaceTest.yml35
-rw-r--r--ui-ci/src/main/resources/Files/asc_heat 0 2.yaml787
-rw-r--r--ui-ci/src/main/resources/Files/hot-nimbus-oam-volumes_v0.3.env6
-rw-r--r--ui-ci/src/main/resources/Files/hot-nimbus-oam_v0.6.env18
-rw-r--r--ui-ci/src/main/resources/Files/hot-nimbus-oam_v0.6.yaml108
-rw-r--r--ui-ci/src/main/resources/Files/hot-nimbus-pcm_v0.6.yaml80
-rw-r--r--ui-ci/src/main/resources/Files/sample-xml-alldata-1-1.xml298
-rw-r--r--ui-ci/src/main/resources/Files/vFW_8.12.16.zipbin3650 -> 0 bytes
-rw-r--r--ui-ci/src/main/resources/Files/vFW_VF.yml58
-rw-r--r--ui-ci/src/main/resources/Files/vFW_VFC.yml58
-rw-r--r--ui-ci/src/main/resources/Files/vLB12.8.16.zipbin3484 -> 0 bytes
-rw-r--r--ui-ci/src/main/resources/Files/vRouter_vfc.yml78
-rw-r--r--ui-ci/src/main/resources/Files/valid HEAT_ENV files.env54
-rw-r--r--ui-ci/src/main/resources/Files/validHEATfiles.yaml787
-rw-r--r--ui-ci/src/main/resources/ci/conf/credentials.yaml48
-rw-r--r--ui-ci/src/main/resources/ci/conf/log4j.properties34
-rw-r--r--ui-ci/src/main/resources/ci/conf/sdc-packages.yaml2
-rw-r--r--ui-ci/src/main/resources/ci/conf/sdc.yaml57
-rw-r--r--ui-ci/src/main/resources/ci/conf/titan.properties7
-rw-r--r--ui-ci/src/main/resources/ci/scripts/startTest.sh96
-rw-r--r--ui-ci/src/main/resources/ci/testSuites/ui-ci.xml16
-rw-r--r--ui-ci/src/main/resources/images/gizmorambo.jpgbin16605 -> 0 bytes
-rw-r--r--ui-ci/src/test/Completetheform.js23
-rw-r--r--ui-ci/tarball.xml60
-rw-r--r--utils/webseal-simulator/README.txt (renamed from webseal-simulator/README.txt)0
-rw-r--r--utils/webseal-simulator/pom.xml110
-rw-r--r--utils/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/Login.java (renamed from webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/Login.java)36
-rw-r--r--utils/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/MethodEnum.java (renamed from webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/MethodEnum.java)0
-rw-r--r--utils/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/MutableHttpServletRequest.java (renamed from webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/MutableHttpServletRequest.java)0
-rw-r--r--utils/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/RequestsClient.java120
-rw-r--r--utils/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/SdcProxy.java (renamed from webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/SdcProxy.java)3
-rw-r--r--utils/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/User.java (renamed from webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/User.java)25
-rw-r--r--utils/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/conf/Conf.java (renamed from webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/conf/Conf.java)3
-rw-r--r--utils/webseal-simulator/src/main/resources/webseal.conf (renamed from webseal-simulator/src/main/resources/webseal.conf)31
-rw-r--r--utils/webseal-simulator/src/main/webapp/WEB-INF/jetty-web.xml6
-rw-r--r--utils/webseal-simulator/src/main/webapp/WEB-INF/web.xml (renamed from webseal-simulator/src/main/webapp/WEB-INF/web.xml)20
-rw-r--r--utils/webseal-simulator/src/main/webapp/login.html (renamed from webseal-simulator/src/main/webapp/login.html)4
-rw-r--r--webseal-simulator/Dockerfile20
-rw-r--r--webseal-simulator/pom.xml133
-rw-r--r--webseal-simulator/src/main/webapp/WEB-INF/jetty-web.xml8
2375 files changed, 109622 insertions, 96248 deletions
diff --git a/.gitignore b/.gitignore
index 2c9567e1a0..d5aacbdbd8 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,13 +1,149 @@
-target
-package
-.settings
-.project
+# Eclipse
.classpath
-.idea
+.project
+.settings/
+
+# Maven
+log/
+target/
+
+# Package Files #
+*.jar
+*.war
+*.ear
+
+# Other
+*.kpf
+*.class
+*.orig
+catalog-ui/.*
+catalog-ui/app/scripts/tsconfig.json
+catalog-ui/app/scripts/references.ts
+catalog-ui/app/scripts/**/*.js
+catalog-ui/app/scripts/**/*.js.map
-*.log
+# catalog-ui
+catalog-ui/app/**/*.css
+catalog-ui/.editorconfig
+catalog-ui/.jshintrc
+catalog-ui/.yo-rc.json
+catalog-ui/app/robots.txt
+catalog-ui/node_modules/
+catalog-ui/bower_components/
+catalog-ui/app/tsconfig.json
-### idea files
+
+catalog-be/.checkstyle
+catalog-be/bin/
+catalog-be/src/main/java/META-INF/MANIFEST.MF
+catalog-builders/src/test/java/com/att/tlv/sdc/be/builders/tosca/t1
+a4c/
+catalog-ui/*.tmp.txt
+catalog-dao/bin/
+catalog-ui/dist
+catalog-builders/bin/
+common-app-api/bin/
+data/compute.png
+data/loadbalancer.png
+data/mysql.png
+data/network.png
+data/normative-types-blockStorage.yml
+data/normative-types-compute.yml
+data/normative-types-database.yml
+data/normative-types-DBMS.yml
+data/normative-types-network.yml
+data/normative-types-objectStorage.yml
+data/normative-types-root.yml
+data/normative-types-softwareComponent.yml
+data/normative-types-webApplication.yml
+data/normative-types-webServer.yml
+data/objectstore.png
+data/relational_db.png
+data/root.png
+data/router.png
+data/software.png
+data/volume.png
+catalog-ui/app/dist/*
+catalog-fe/src/main/webapp/*
+catalog-fe/bin
+!catalog-fe/src/main/webapp/WEB-INF/
+!catalog-fe/src/main/webapp/META-INF/
+ui-ci/.tern-project
+catalog-be/data/*
+ci/src/main/java/com/att/tlv/sdc/ci/tests/execute/ShayPracticeTests.java
+ci/src/main/java/com/att/tlv/sdc/ci/tests/execute/ShayPracticeTests.java
+.metadata/*
+.metadata/*
+.idea/*
*.iml
-*.ipr
-*.iws
+catalog-ui/npm-debug.log
+sdnc-tests/logs/wordnik.log
+distribution-ci/logs/wordnik.log
+distribution-ci/logs/wordnik.log.1
+distribution-ci/logs/wordnik.log.10
+distribution-ci/logs/wordnik.log.2
+distribution-ci/logs/wordnik.log.3
+distribution-ci/logs/wordnik.log.4
+distribution-ci/logs/wordnik.log.5
+distribution-ci/logs/wordnik.log.6
+distribution-ci/logs/wordnik.log.7
+distribution-ci/logs/wordnik.log.8
+distribution-ci/logs/wordnik.log.9
+vagrant-asdc-all-in-one/
+catalog-ui/tests/Coverage/*
+catalog-ui/Chrome*
+catalog-ui/PhantomJS_1.9.8_(Windows_7_0.0.0)/*
+
+.metadata/
+bin/
+Vagrantfile
+sdnc-tests/test-output/*
+sdnc-tests-new-frame-work/test-output/*
+ui-ci/test-output/*
+ui-ci/test-output/Default suite/Default test.html
+ui-ci/test-output/Default suite/Default test.xml
+ui-ci/test-output/Default suite/testng-failed.xml
+ui-ci/test-output/emailable-report.html
+ui-ci/test-output/index.html
+ui-ci/test-output/old/Default suite/classes.html
+ui-ci/test-output/old/Default suite/methods.html
+ui-ci/test-output/old/Default suite/methods-alphabetical.html
+ui-ci/test-output/old/Default suite/testng.xml.html
+ui-ci/test-output/old/Default suite/toc.html
+ui-ci/test-output/old/index.html
+ui-ci/test-output/testng-failed.xml
+ui-ci/test-output/testng-results.xml
+ui-ci/src/main/resources/Files/outputMainServiceTemplate/*
+ui-ci/src/main/resources/Files/output/*
+
+sdnc-tests-new-frame-work/test-output/**
+asdc-tests/test-output/**
+
+asdc-chef/cookbooks/Deploy-SDandC/attributes/version.rb
+asdc-tests/ExtentReport/ASDC_CI_Extent_Report.html
+*.orig
+test-apis-ci/ExtentReport/*
+test-apis-ci/test-output/*
+test-apis-ci/test-output/*
+test-apis-ci/ExtentReport/*
+ui-ci/ExtentReport/*
+test-apis-ci/test-output/*
+test-apis-ci/ExtentReport/ASDC_CI_Extent_Report.html
+test-apis-ci/extent.html
+sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-normatives/files/default/normatives.tar.gz
+sdc-os-chef/sdc-normatives/chef-repo/cookbooks/sdc-normatives/files/default/normatives.tar.gz
+catalog-be/test-output/*
+test-apis-ci/logfile.log*
+ui-ci/logfile.log*
+catalog-ui/node/*
+log.home_IS_UNDEFINED/ASDC/ASDC-BE/audit.log
+log.home_IS_UNDEFINED/ASDC/ASDC-BE/debug.log
+log.home_IS_UNDEFINED/ASDC/ASDC-BE/debug_by_package.log
+log.home_IS_UNDEFINED/ASDC/ASDC-BE/Error.log
+log.home_IS_UNDEFINED/ASDC/ASDC-BE/transaction.log
+openecomp-be/tools/swagger-ui/api-docs/api.html
+openecomp-be/tools/swagger-ui/api-docs/api.json
+dox-sequence-diagram-ui/node/*
+openecomp-ui/node/*
+sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/files/default/SDC-*.zip
+sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/files/default/sdctool.tar
diff --git a/asdc-tests/pom.xml b/asdc-tests/pom.xml
index 50b7f65d92..0c0e9a2598 100644
--- a/asdc-tests/pom.xml
+++ b/asdc-tests/pom.xml
@@ -4,23 +4,14 @@
<modelVersion>4.0.0</modelVersion>
<artifactId>asdc-tests</artifactId>
-
+
<parent>
<groupId>org.openecomp.sdc</groupId>
<artifactId>sdc-main</artifactId>
<version>1.1.0-SNAPSHOT</version>
</parent>
-
-
- <dependencies>
-
- <dependency>
- <groupId>org.apache.commons</groupId>
- <artifactId>commons-lang3</artifactId>
- <version>${lang3.version}</version>
- <scope>compile</scope>
- </dependency>
+ <dependencies>
<dependency>
<groupId>com.google.guava</groupId>
@@ -28,89 +19,90 @@
<version>${guava.version}</version>
<scope>compile</scope>
</dependency>
-
+
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
- <version>4.12</version>
+ <version>${junit.version}</version>
<scope>compile</scope>
</dependency>
-
+
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
- <version>6.9.10</version>
+ <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-all</artifactId>
<version>1.10.19</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>${common-app-api.version}</version>
+ <version>${project.version}</version>
<scope>compile</scope>
</dependency>
-
+
<dependency>
<groupId>org.openecomp.sdc.be</groupId>
<artifactId>common-be</artifactId>
- <version>${common-be.version}</version>
+ <version>${project.version}</version>
<scope>compile</scope>
</dependency>
-
+
<!-- CHECK CATLOG MODEL -->
<dependency>
<groupId>org.openecomp.sdc.be</groupId>
<artifactId>catalog-model</artifactId>
- <version>${catalog-model.version}</version>
+ <version>${project.version}</version>
<scope>compile</scope>
</dependency>
-
+
<!-- catalog dao -->
<dependency>
<groupId>org.openecomp.sdc.be</groupId>
<artifactId>catalog-dao</artifactId>
- <version>${catalog-dao.version}</version>
+ <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 -->
@@ -121,107 +113,104 @@
<scope>compile</scope>
</dependency>
<!-- CASSANDRA END -->
-
-
+
<!-- slf4j + logback -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
- <version>1.7.10</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>
-
+
<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>2.0-SNAPSHOT</version>
+ <version>${commons-codec}</version>
<scope>compile</scope>
</dependency>
-
- <!-- Gson -->
+ <!-- Gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
- <version>2.3.1</version>
+ <version>${gson.version}</version>
<scope>compile</scope>
</dependency>
-
+
<!-- Snake Yaml -->
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
- <version>1.14</version>
+ <version>${snakeyaml.version}</version>
<scope>compile</scope>
</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>httpmime</artifactId>
- <version>${httpclient.version}</version>
+ <version>${httpclient.version}</version>
<scope>compile</scope>
- </dependency>
-
+ </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>1.2.1-SNAPSHOT</version>
+ <version>${commons-logging}</version>
<scope>compile</scope>
</dependency>
-
+
<!-- http core -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
- <version>${httpcore.version}</version>
+ <version>${httpcore.version}</version>
<scope>compile</scope>
</dependency>
-
+
<!-- TITAN -->
<dependency>
<groupId>com.thinkaurelius.titan</groupId>
@@ -235,7 +224,7 @@
</exclusion>
</exclusions>
</dependency>
-
+
<dependency>
<groupId>com.thinkaurelius.titan</groupId>
<artifactId>titan-cassandra</artifactId>
@@ -248,7 +237,7 @@
</exclusion>
</exclusions>
</dependency>
-
+
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
@@ -259,50 +248,75 @@
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
- <!--<version>2.3.1</version>-->
<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>2.3.1</version>-->
<version>${jackson.version}</version>
+ <!--<version>2.3.1</version>-->
<scope>compile</scope>
</dependency>
-
+
<dependency>
- <groupId>org.openecomp.sdc</groupId>
+ <groupId>org.openecomp.sdc.sdc-distribution-client</groupId>
<artifactId>sdc-distribution-client</artifactId>
- <version>1.0.0</version>
+ <version>1.1.9-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
-
+
<dependency>
<groupId>org.openecomp.ecompsdkos</groupId>
<artifactId>ecompFW</artifactId>
- <version>1.0.0</version>
+ <version>${ecomp.version}</version>
<scope>compile</scope>
- <exclusions>
- <exclusion>
- <artifactId>slf4j-log4j12</artifactId>
- <groupId>org.slf4j</groupId>
- </exclusion>
- </exclusions>
- </dependency>
-
+ <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>
-
+
+ <!-- ============================================= -->
+ <!-- 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>
@@ -312,16 +326,16 @@
</configuration>
</plugin>
- <!-- ============================================= -->
- <!-- Create the JAR file with its dependencies -->
- <!-- ============================================= -->
+ <!-- ============================================= -->
+ <!-- Create the JAR file with its dependencies -->
+ <!-- ============================================= -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
- <version>2.5.5</version>
+ <version>2.5.5</version>
<executions>
<execution>
- <id>create.jar.with.dependencies</id>
+ <id>create.jar.with.dependencies</id>
<phase>package</phase>
<goals>
<goal>single</goal>
@@ -339,53 +353,33 @@
</execution>
</executions>
</plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-assembly-plugin</artifactId>
- <version>2.6</version>
- <executions>
- <execution>
- <configuration>
- <finalName>${project.artifactId}</finalName>
- <appendAssemblyId>false</appendAssemblyId>
- <descriptor>${project.basedir}/tarball.xml</descriptor>
- </configuration>
- <id>assemble-file</id>
- <phase>package</phase>
- <goals>
- <goal>single</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-resources-plugin</artifactId>
- <version>3.0.2</version>
+ </plugins>
+ </build>
- <executions>
- <execution>
- <id>copy-asdc-tests</id>
- <phase>install</phase>
- <goals>
- <goal>copy-resources</goal>
- </goals>
+ <profiles>
+ <profile>
+ <id>Fortify</id>
+ <activation>
+ <activeByDefault>false</activeByDefault>
+ </activation>
+
+ <build>
+ <plugins>
+ <!-- =========================== -->
+ <!-- HP Fortifay scanner -->
+ <!-- =========================== -->
+ <plugin>
+ <groupId>com.fortify.ps.maven.plugin</groupId>
+ <artifactId>sca-maven-plugin</artifactId>
+ <version>4.30</version>
<configuration>
- <outputDirectory>${project.parent.basedir}/sdc-os-chef/sdc-sanity/chef-repo/cookbooks/sdc-sanity/files/default</outputDirectory>
- <resources>
- <resource>
- <directory>./target</directory>
- <includes>
- <include>asdc-tests.tar</include>
- </includes>
- </resource>
- </resources>
+ <scanEnabled>false</scanEnabled>
+ <skip>true</skip>
</configuration>
- </execution>
- </executions>
- </plugin>
-
- </plugins>
- </build>
+ </plugin>
+ </plugins>
+ </build>
+ </profile>
+ </profiles>
</project>
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/api/SdcTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/api/AttSdcTest.java
index ebad749097..6c0b96e15c 100644
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/api/SdcTest.java
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/api/AttSdcTest.java
@@ -20,6 +20,8 @@
package org.openecomp.sdc.ci.tests.api;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.File;
@@ -36,17 +38,18 @@ 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 org.slf4j.Logger;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
-public abstract class SdcTest {
+public abstract class AttSdcTest {
public static StringBuilder doc = new StringBuilder();
public static String file = null;
@@ -55,17 +58,17 @@ public abstract class SdcTest {
protected Gson prettyGson = new GsonBuilder().setPrettyPrinting().create();
protected TestName testName = null;
- protected Logger logger = null;
protected static boolean displayException = false;
-
- public SdcTest(TestName testName, String className) {
+ static Logger logger = LoggerFactory.getLogger(CrudArt.class.getName());
+
+
+ public AttSdcTest(TestName testName, String className) {
super();
StartTest.enableLogger();
this.testName = testName;
- this.logger = LoggerFactory.getLogger(className);
String displayEx = System.getProperty("displayException");
if (displayEx != null && Boolean.valueOf(displayEx).booleanValue()) {
@@ -108,6 +111,7 @@ public abstract class SdcTest {
@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());
@@ -120,13 +124,13 @@ public abstract class SdcTest {
config = Utils.getConfig();
assertTrue(config != null);
- // logger.info("Start running test " + testName.getMethodName());
+ logger.info("Start running test {}", testName.getMethodName());
}
@After
public void afterTest() throws FileNotFoundException {
- // logger.info("Finish running test " + testName.getMethodName());
+ logger.info("Finish running test {}", testName.getMethodName());
}
public void addTestSummary(String testName, boolean isSuccess) {
@@ -161,9 +165,9 @@ public abstract class SdcTest {
doc.append("</tr>");
if (isSuccess) {
- logger.debug("Test {} succeeded.", testName);
+ logger.debug("Test {} {}", testName, (isSuccess ? " SUCCEEDED " : " FAILED with error " + message));
} else {
- logger.error("Test {} failed with error: {}", testName, message);
+ logger.error("Test {} {}", testName, (isSuccess ? " SUCCEEDED " : " FAILED with error " + message));
}
}
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
index 370c195f53..0f85cc792d 100644
--- 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
@@ -27,10 +27,14 @@ 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 com.thinkaurelius.titan.core.TitanGraphQuery;
+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;
@@ -39,17 +43,27 @@ 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;
@@ -62,6 +76,7 @@ import org.testng.annotations.BeforeSuite;
import com.relevantcodes.extentreports.ExtentReports;
import com.relevantcodes.extentreports.ExtentTest;
import com.relevantcodes.extentreports.LogStatus;
+import com.relevantcodes.extentreports.NetworkMode;
import com.thinkaurelius.titan.core.TitanFactory;
import com.thinkaurelius.titan.core.TitanGraph;
import com.thinkaurelius.titan.core.TitanVertex;
@@ -99,7 +114,7 @@ public abstract class ComponentBaseTest {
}
@BeforeSuite(alwaysRun = true)
- public static void openTitan() throws FileNotFoundException {
+ public static void openTitan() throws Exception {
File dir = new File(REPORT_FOLDER);
try {
@@ -107,19 +122,36 @@ public abstract class ComponentBaseTest {
} 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();
- System.out.println("titan configuration path:\n"+titanConfigFilePath);
titanGraph = TitanFactory.open(titanConfigFilePath);
- System.out.println("is open:\n"+titanGraph.isOpen());
assertNotNull(titanGraph);
}
@AfterSuite(alwaysRun = true)
- public static void shutdownTitan() {
+ public static void shutdownTitan() throws Exception {
+ shutdownTitanLogic();
+ extentReport.flush();
+ }
+
+ protected static void shutdownTitanLogic() {
if (titanGraph.isOpen()) {
titanGraph.close();
}
@@ -129,8 +161,9 @@ public abstract class ComponentBaseTest {
@BeforeMethod(alwaysRun = true)
public void beforeState(java.lang.reflect.Method method) throws Exception {
- cleanComponents();
- CassandraUtils.truncateAllKeyspaces();
+ // deleteCreatedComponents(getCatalogAsMap());
+
+ performeClean();
extendTest = extentReport.startTest(method.getName());
extendTest.log(LogStatus.INFO, "Test started");
@@ -138,8 +171,7 @@ public abstract class ComponentBaseTest {
@AfterMethod(alwaysRun = true)
public void afterState(ITestResult result) throws Exception {
- cleanComponents();
- CassandraUtils.truncateAllKeyspaces();
+ performeClean();
if (result.isSuccess()) {
extendTest.log(LogStatus.PASS, "Test Result : <span class='label success'>Success</span>");
@@ -150,17 +182,21 @@ public abstract class ComponentBaseTest {
}
extentReport.endTest(extendTest);
- extentReport.flush();
}
+ 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 void cleanComponents() throws Exception {
+ private static void cleanComponents() throws Exception {
// Components to delete
List<String> vfResourcesToDelete = new ArrayList<String>();
@@ -179,10 +215,8 @@ public abstract class ComponentBaseTest {
List<String> resourcesNotToDelete = config.getResourcesNotToDelete();
List<String> resourceCategoriesNotToDelete = config.getResourceCategoriesNotToDelete();
List<String> serviceCategoriesNotToDelete = config.getServiceCategoriesNotToDelete();
- TitanGraphQuery<? extends TitanGraphQuery> query = titanGraph.query();
- query = query.has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.Resource.getName());
- Iterable<TitanVertex> vertices=query.vertices();
-// Iterable<TitanVertex> vertices = titanGraph.query().has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.Resource.getName()).vertices();
+
+ Iterable<TitanVertex> vertices = titanGraph.query().has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.Resource.getName()).vertices();
if (vertices != null) {
Iterator<TitanVertex> iter = vertices.iterator();
while (iter.hasNext()) {
@@ -195,13 +229,13 @@ public abstract class ComponentBaseTest {
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);
+ 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);
@@ -217,9 +251,9 @@ public abstract class ComponentBaseTest {
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);
- // }
+ if (name.startsWith("ci")) {
+ servicesToDelete.add(id);
+ }
}
}
@@ -230,9 +264,9 @@ public abstract class ComponentBaseTest {
Vertex vertex = iter.next();
String id = vertex.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
String name = vertex.value(GraphPropertiesDictionary.NAME.getProperty());
- //if (name.startsWith("ci")) {
+ if (name.startsWith("Ci")) {
productsToDelete.add(id);
- //}
+ }
}
}
@@ -345,4 +379,141 @@ public abstract class ComponentBaseTest {
}
+ 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
index 2b0a35d472..9428a9b695 100644
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/api/ComponentInstanceBaseTest.java
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/api/ComponentInstanceBaseTest.java
@@ -326,6 +326,7 @@ public class ComponentInstanceBaseTest extends ComponentBaseTest {
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));
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/api/Urls.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/api/Urls.java
index 5aceb4fae3..a8342f8879 100644
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/api/Urls.java
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/api/Urls.java
@@ -184,8 +184,15 @@ public interface Urls {
// ***********************************External API's
// (AssetData)****************************************
+
+ final String DELETE_EXTRNAL_API_DELETE_ARTIFACT_OF_ASSET = "http://%s:%s/asdc/v1/catalog/%s/%s/artifacts/%s";
+ final String DELETE_EXTRNAL_API_DELETE_ARTIFACT_OF_COMPONENTINSTANCE_ON_ASSET = "http://%s:%s/asdc/v1/catalog/%s/%s/resourceInstances/%s/artifacts/%s";
+ final String POST_EXTERNAL_API_UPDATE_ARTIFACT_OF_ASSET = "http://%s:%s/asdc/v1/catalog/%s/%s/artifacts/%s";
+ final String POST_EXTERNAL_API_UPDATE_ARTIFACT_OF_COMPONENTINSTANCE_ON_ASSET = "http://%s:%s/asdc/v1/catalog/%s/%s/resourceInstances/%s/artifacts/%s";
+
final String POST_EXTERNAL_API_UPLOAD_ARTIFACT_OF_ASSET = "http://%s:%s/asdc/v1/catalog/%s/%s/artifacts";
+ final String POST_EXTERNAL_API_UPLOAD_ARTIFACT_OF_COMPONENTINSTANCE_ON_ASSET = "http://%s:%s/asdc/v1/catalog/%s/%s/resourceInstances/%s/artifacts";
final String GET_DOWNLOAD_RESOURCE_ARTIFACT_OF_ASSET = "http://%s:%s/asdc/v1/catalog/resources/%s/artifacts/%s";
final String GET_DOWNLOAD_SERVICE_ARTIFACT_OF_ASSET = "http://%s:%s/asdc/v1/catalog/services/%s/artifacts/%s";
@@ -202,6 +209,11 @@ public interface Urls {
final String POST_AUTHORIZATION = "http://%s:%s/sdc2/rest/v1/consumers";
final String GET_DOWNLOAD_SERVICE_RI_ARTIFACT = "http://%s:%s/asdc/v1/catalog/services/%s/resourceInstances/%s/artifacts/%s";
final String GET_DOWNLOAD_SERVICE_ARTIFACT = "http://%s:%s/asdc/v1/catalog/services/%s/artifacts/%s";
+
+ final String POST_EXTERNAL_API_CREATE_RESOURCE = "http://%s:%s/asdc/v1/catalog/resources";
+
+ final String CHANGE_RESOURCE_LIFECYCLE_STATE_EXTERNAL_API = "http://%s:%s/asdc/v1/catalog/resources/%s/lifecycleState/%s";
+ final String CHANGE_SERVICE_LIFECYCLE_STATE_EXTERNAL_API = "http://%s:%s/asdc/v1/catalog/services/%s/lifecycleState/%s";
// *****************************************************************************************************
@@ -243,6 +255,7 @@ public interface Urls {
// *****************************************************************************************************
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";
@@ -255,14 +268,16 @@ public interface Urls {
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";
// Tal New API
final String UPDATE_MULTIPLE_COMPONENT_INSTANCE = "http://%s:%s/sdc2/rest/v1/catalog/%s/%s/resourceInstance/multipleComponentInstance";
- final String CHANGE__RESOURCE_INSTANCE_VERSION = "http://%s:%s/sdc2/rest/v1/catalog/%s/%s/resourceInstance/%s/changeVersion";
+ final String 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 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";
@@ -270,6 +285,7 @@ public interface Urls {
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";
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
index ce025715fd..0675dc11ba 100644
--- 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
@@ -31,7 +31,7 @@ import org.yaml.snakeyaml.Yaml;
public class Config {
- private static String WINDOWS_CONFIG_FILE = "src/main/resources/ci/conf/sdc.yaml";
+ private static String WINDOWS_CONFIG_FILE = "src/main/resources/ci/conf/attsdc.yaml";
String catalogBeHost;
String esHost;
@@ -40,6 +40,8 @@ public class Config {
String neoPort;
String disributionClientHost;
String disributionClientPort;
+ Boolean isDistributionClientRunning;
+
String errorConfigurationFile;
String resourceConfigDir;
@@ -47,6 +49,7 @@ public class Config {
String importResourceConfigDir;
String importResourceTestsConfigDir;
String importTypesConfigDir;
+
String testSuites;
String catalogFeHost;
@@ -70,6 +73,7 @@ public class Config {
private String url;
private String remoteTestingMachineIP;
private String remoteTestingMachinePort;
+ private String webSealSimulatorUrl;
private boolean remoteTesting;
private String cassandraHost;
@@ -86,6 +90,7 @@ public class Config {
private static Yaml yaml = new Yaml();
+
private Config() {
super();
}
@@ -168,6 +173,10 @@ public class Config {
}
}
+ // JsonReader jsonReader = new JsonReader(new FileReader(configFile));
+ // Config configAttOdlIt = new Gson().fromJson(jsonReader,
+ // Config.class);
+
return config;
}
@@ -175,7 +184,7 @@ public class Config {
int separator = Math.max(path.lastIndexOf("\\"), path.lastIndexOf("/"));
String dirPath = path.substring(0, separator + 1);
- String packagesFile = dirPath + File.separator + "sdc-packages.yaml";
+ 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.");
@@ -232,6 +241,14 @@ public class Config {
this.configurationFile = configurationFile;
}
+ public Boolean getIsDistributionClientRunning() {
+ return isDistributionClientRunning;
+ }
+
+ public void setIsDistributionClientRunning(Boolean isDistributionClientRunning) {
+ this.isDistributionClientRunning = isDistributionClientRunning;
+ }
+
public String getCatalogBePort() {
return catalogBePort;
}
@@ -497,6 +514,14 @@ public class Config {
+ outputFolder + ", reportName=" + reportName + ", configurationFile=" + configurationFile + "]";
}
+ public String getWebSealSimulatorUrl() {
+ return webSealSimulatorUrl;
+ }
+
+ public void setWebSealSimulatorUrl(String webSealSimulatorUrl) {
+ this.webSealSimulatorUrl = webSealSimulatorUrl;
+ }
+
public boolean isRemoteTesting() {
return remoteTesting;
}
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
index 28606af14d..489f229c61 100644
--- 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
@@ -22,6 +22,7 @@ package org.openecomp.sdc.ci.tests.datatypes;
import java.util.List;
+import org.openecomp.sdc.be.model.ArtifactDefinition;
import org.openecomp.sdc.be.model.HeatParameterDefinition;
public class ArtifactReqDetails {
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
index 0089eec5a7..638ece8c6d 100644
--- 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
@@ -32,9 +32,12 @@ import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
+import java.util.HashSet;
import java.util.Iterator;
+import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
+import java.util.Set;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jettison.json.JSONArray;
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
index d429d05a51..62f5e0c8f0 100644
--- 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
@@ -24,6 +24,8 @@ public class ResourceAssetStructure extends AssetStructure {
private String subCategory;
private String resourceType;
+ protected String lastUpdaterFullName;
+ protected String toscaResourceName;
public ResourceAssetStructure() {
super();
@@ -38,6 +40,22 @@ public class ResourceAssetStructure extends AssetStructure {
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;
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
index 737343f24c..b521b4bf08 100644
--- 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
@@ -24,8 +24,6 @@ import java.util.List;
public class ResourceDetailedAssetStructure extends ResourceAssetStructure {
- private String lastUpdaterFullName;
- private String toscaResourceName;
private List<ResourceInstanceAssetStructure> resources;
private List<ArtifactAssetStructure> artifacts;
@@ -42,22 +40,6 @@ public class ResourceDetailedAssetStructure extends ResourceAssetStructure {
this.artifacts = artifacts;
}
- 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 List<ResourceInstanceAssetStructure> getResources() {
return resources;
}
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
new file mode 100644
index 0000000000..a5132e8bf6
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceExternalReqDetails.java
@@ -0,0 +1,105 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.datatypes;
+
+import java.util.List;
+
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.Resource;
+
+public class ResourceExternalReqDetails extends ComponentReqDetails {
+ String vendorName;
+ String vendorRelease;
+ String category;
+ String subcategory;
+
+ private String resourceType = ResourceTypeEnum.VFC.toString(); // Default
+ // value
+ public ResourceExternalReqDetails() {
+ super();
+ }
+
+
+ public ResourceExternalReqDetails(String resourceName, String description, List<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
index 9172b8a632..6a69120a05 100644
--- 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
@@ -28,7 +28,7 @@ public class ResourceInstanceAssetStructure {
String resourceName;
String resourceInvariantUUID;
String resourceVersion;
- String resourceType;
+ String resoucreType;
String resourceUUID;
List<ArtifactAssetStructure> artifacts;
@@ -37,14 +37,14 @@ public class ResourceInstanceAssetStructure {
}
public ResourceInstanceAssetStructure(String resourceInstanceName, String resourceName,
- String resourceInvariantUUID, String resourceVersion, String resourceType, String resourceUUID,
+ 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.resourceType = resourceType;
+ this.resoucreType = resoucreType;
this.resourceUUID = resourceUUID;
this.artifacts = artifacts;
}
@@ -81,12 +81,12 @@ public class ResourceInstanceAssetStructure {
this.resourceVersion = resourceVersion;
}
- public String getResourceType() {
- return resourceType;
+ public String getResoucreType() {
+ return resoucreType;
}
- public void setResourceType(String resourceType) {
- this.resourceType = resourceType;
+ public void setResoucreType(String resoucreType) {
+ this.resoucreType = resoucreType;
}
public String getResourceUUID() {
@@ -109,7 +109,7 @@ public class ResourceInstanceAssetStructure {
public String toString() {
return "ResourceInstanceAssetStructure [resourceInstanceName=" + resourceInstanceName + ", resourceName="
+ resourceName + ", resourceInvariantUUID=" + resourceInvariantUUID + ", resourceVersion="
- + resourceVersion + ", resourceType=" + resourceType + ", resourceUUID=" + resourceUUID + ", artifacts="
+ + resourceVersion + ", resoucreType=" + resoucreType + ", resourceUUID=" + resourceUUID + ", 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
new file mode 100644
index 0000000000..dde1f27cca
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceDistributionStatus.java
@@ -0,0 +1,80 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.datatypes;
+
+public class ServiceDistributionStatus {
+
+ private String distributionID;
+ private String timestamp;
+ private String userId;
+ private String deployementStatus;
+
+ public ServiceDistributionStatus() {
+ super();
+ // TODO Auto-generated constructor stub
+ }
+
+ public ServiceDistributionStatus(String distributionID, String timestamp, String userId, String deployementStatus) {
+ super();
+ this.distributionID = distributionID;
+ this.timestamp = timestamp;
+ this.userId = userId;
+ this.deployementStatus = deployementStatus;
+ }
+
+ @Override
+ public String toString() {
+ return "ServiceDistributionStatus [distributionID=" + distributionID + ", timestamp=" + timestamp + ", userId=" + userId + ", deployementStatus=" + deployementStatus + "]";
+ }
+
+ public String getDistributionID() {
+ return distributionID;
+ }
+
+ public void setDistributionID(String distributionID) {
+ this.distributionID = distributionID;
+ }
+
+ public String getTimestamp() {
+ return timestamp;
+ }
+
+ public void setTimestamp(String timestamp) {
+ this.timestamp = timestamp;
+ }
+
+ public String getUserId() {
+ return userId;
+ }
+
+ public void setUserId(String userId) {
+ this.userId = userId;
+ }
+
+ public String getDeployementStatus() {
+ return deployementStatus;
+ }
+
+ public void setDeployementStatus(String deployementStatus) {
+ this.deployementStatus = deployementStatus;
+ }
+
+}
diff --git a/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
index 1e6b06a6c8..eafdf80a0a 100644
--- 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
@@ -32,13 +32,16 @@ public enum ArtifactTypeEnum {
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"),
+ HEAT_ARTIFACT("HEAT_ARTIFACT"), VF_MODULES_METADATA("VF_MODULES_METADATA"), LIFECYCLE_OPERATIONS("LIFECYCLE_OPERATIONS"),
+ VES_EVENTS("VES_EVENTS"), PERFORMANCE_COUNTER("PERFORMANCE_COUNTER"),
// 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")
+ 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) {
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/AssocType.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/AssocType.java
index b0da1f987d..82e9a36780 100644
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/AssocType.java
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/AssocType.java
@@ -22,11 +22,8 @@ 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");
+ 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;
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/AuditEnum.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/AuditEnum.java
index a73cff9373..a713d5089f 100644
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/AuditEnum.java
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/AuditEnum.java
@@ -22,20 +22,8 @@ package org.openecomp.sdc.ci.tests.datatypes.enums;
public enum AuditEnum {
- ACTION("ACTION"),
- RESOURCE_NAME("RESOURCE_NAME"),
- RESOURCE_TYPE("RESOURCE_TYPE"),
- PREV_VERSION("PREV_VERSION"),
- CURR_VERSION("CURR_VERSION"),
- MODIFIER("MODIFIER"),
- PREV_STATE("PREV_STATE"),
- CURR_STATE("CURR_STATE"),
- STATUS("STATUS-Type"),
- DESC("DESC"),
- URL("URL"),
- USER("USER"),
- AUTH_STATUS("AUTH_STATUS"),
- REALM("REALM");
+ ACTION("ACTION"), RESOURCE_NAME("RESOURCE_NAME"), RESOURCE_TYPE("RESOURCE_TYPE"), PREV_VERSION("PREV_VERSION"), CURR_VERSION("CURR_VERSION"), MODIFIER("MODIFIER"), PREV_STATE("PREV_STATE"),
+ CURR_STATE("CURR_STATE"), STATUS("STATUS-Type"), DESC("DESC"), URL("URL"), USER("USER"), AUTH_STATUS("AUTH_STATUS"), REALM("REALM");
String value;
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/TypesEnum.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/DistributionNotificationStatusEnum.java
index 1bff4d51e6..7042a954e7 100644
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/TypesEnum.java
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/DistributionNotificationStatusEnum.java
@@ -18,26 +18,35 @@
* ============LICENSE_END=========================================================
*/
-package org.openecomp.sdc.ci.tests.datatypes;
+package org.openecomp.sdc.ci.tests.datatypes.enums;
-public enum TypesEnum {
+public enum DistributionNotificationStatusEnum {
- RESOURCE("checkbox-resource"),
- VF("checkbox-vf"),
- VFC("checkbox-vfc"),
- CP("checkbox-cp"),
- VL("checkbox-vl"),
- SERVICE("checkbox-service"),
- PRODUCT("checkbox-product");
+ 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;
}
- private TypesEnum(String value) {
- this.value = 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/LifeCycleStatesEnum.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/LifeCycleStatesEnum.java
index 7c330a3d10..9edfb9aced 100644
--- 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
@@ -20,6 +20,8 @@
package org.openecomp.sdc.ci.tests.datatypes.enums;
+import java.util.List;
+
public enum LifeCycleStatesEnum {
CHECKOUT("checkout", "NOT_CERTIFIED_CHECKOUT"),
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
index 7769d19802..58892439b0 100644
--- 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
@@ -24,11 +24,7 @@ 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");
+ TEST_SCRIPTS(null, "testscripts"), FEATURES(null, "features"), CAPACITY(null, "capacity"), VENDOR_TEST_RESULT(null, "vendortestresult"), CLOUD_QUESTIONNAIRE(null, "cloudQuestionnaire");
String artifactName;
String logicalName;
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
index f1cfcf0c98..389b962f1c 100644
--- 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
@@ -21,20 +21,10 @@
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");
+ 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;
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
new file mode 100644
index 0000000000..d85a496241
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/OriginTypeEnum.java
@@ -0,0 +1,74 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.datatypes.enums;
+
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+
+public enum OriginTypeEnum {
+ PRODUCT("Product", "Product", "product instance", ComponentTypeEnum.PRODUCT),
+ SERVICE("Service", "Service", "service instance", ComponentTypeEnum.SERVICE),
+ VF("VF", "VF (Virtual Function)", "resource instance", ComponentTypeEnum.RESOURCE),
+ VFC("VFC", "VFC (Virtual Function Component)", "resource instance", ComponentTypeEnum.RESOURCE),
+ CP("CP", "CP (Connection Point)", "resource instance", ComponentTypeEnum.RESOURCE),
+ VL("VL", "VL (Virtual Link)", "resource instance", ComponentTypeEnum.RESOURCE),
+ VFCMT("VFCMT", "VFCMT (VFC Monitoring Template)", "resource instance", ComponentTypeEnum.RESOURCE),
+ VFi("VFi", "VFi (Virtual Function Instance)", "resource instance", ComponentTypeEnum.RESOURCE_INSTANCE);
+
+
+ private String value;
+ private String displayValue;
+ private String instanceType;
+ private ComponentTypeEnum componentType;
+
+ private OriginTypeEnum(String value, String displayValue, String instanceType, ComponentTypeEnum componentType) {
+ this.value = value;
+ this.displayValue = displayValue;
+ this.instanceType = instanceType;
+ this.componentType = componentType;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+ public String getDisplayValue() {
+ return displayValue;
+ }
+
+ public String getInstanceType() {
+ return instanceType;
+ }
+
+ public ComponentTypeEnum getComponentType() {
+ return componentType;
+ }
+
+ public static OriginTypeEnum findByValue(String value) {
+ OriginTypeEnum ret = null;
+ for (OriginTypeEnum curr : OriginTypeEnum.values()) {
+ if (curr.getValue().equals(value)) {
+ ret = curr;
+ break;
+ }
+ }
+ return ret;
+ }
+}
diff --git a/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
index 5dac326c70..76296acf82 100644
--- 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
@@ -20,6 +20,7 @@
package org.openecomp.sdc.ci.tests.datatypes.enums;
+import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
import org.openecomp.sdc.be.model.PropertyDefinition;
import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
@@ -27,7 +28,8 @@ 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),
+ 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())),
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
index 3ece77b8ec..47123a61e7 100644
--- 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
@@ -27,8 +27,9 @@ public enum ResourceCategoryEnum {
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");
-
+ 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;
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
index 4350cba105..2f2af97fd8 100644
--- 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
@@ -22,30 +22,10 @@ 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_ATT_UID("lastUpdaterUserId"),
- LAST_UPDATER_FULL_NAME("lastUpdaterFullName"),
- ARTIFACTS("artifacts"),
- DESCRIPTION("description"),
- UUID("uuid"),
- COST("cost"),
- LICENSE_TYPE("licenseType"),
- RESOURCE_TYPE("resourceType"),
- CATEGORIES("categories");
+ 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;
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/CatalogFilterTitlesEnum.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/SearchCriteriaEnum.java
index 1335b51788..f26423a35d 100644
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/CatalogFilterTitlesEnum.java
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/SearchCriteriaEnum.java
@@ -18,20 +18,21 @@
* ============LICENSE_END=========================================================
*/
-package org.openecomp.sdc.ci.tests.datatypes;
+package org.openecomp.sdc.ci.tests.datatypes.enums;
-public enum CatalogFilterTitlesEnum {
- TYPE("typeFilterTitle"), CATEGORIES("categoriesFilterTitle"), STATUS("statusFilterTitle");
- private String value;
+public enum SearchCriteriaEnum {
- public String getValue() {
- return value;
- }
+ RESOURCE_TYPE("resourceType"), CATEGORY("category"), SUBCATEGORY("subCategory");
- private CatalogFilterTitlesEnum(String value) {
+ 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
index 675e1d7502..4cfcc8a558 100644
--- 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
@@ -21,12 +21,7 @@
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());
+ CONFIGURATION("Configuration".toLowerCase()), INSTANTIATION("Instantiation".toLowerCase()), MONITORING("Monitoring".toLowerCase()), REPORTING("Reporting".toLowerCase()), LOGGING("Logging".toLowerCase()), TESTING("Testing".toLowerCase());
String logicalName;
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
index f8479e912c..b8635b3bda 100644
--- 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
@@ -22,10 +22,7 @@ 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");
+ TOSCA_DEFINITION_VERSION("tosca_definitions_version"), METADATA("metadata"), IMPORTS("imports"), NODE_TYPES("node_types"), TOPOLOGY_TEMPLATE("topology_template");
private String toscaKey;
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
index 399779fefe..fb04f6a68b 100644
--- 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
@@ -21,35 +21,39 @@
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;
+
+ 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.firstName = firstName;
this.lastName = lastName;
- this.userName = firstName+" " + 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;
}
@@ -69,8 +73,5 @@ public enum UserRoleEnum {
public void setLastName(String lastName) {
this.lastName = lastName;
}
-
}
-
-
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
index 7c2830ec5f..5801536973 100644
--- 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
@@ -92,7 +92,6 @@ public class HttpRequest {
response.append(result);
} catch (Exception e) {
- // logger.error("Error during getting input stream: ",e);
}
try {
@@ -101,7 +100,6 @@ public class HttpRequest {
response.append(result);
} catch (Exception e) {
- // logger.error("Error during getting error stream: ",e);
}
logger.debug("Response body: {}", response);
@@ -155,7 +153,7 @@ public class HttpRequest {
}
in.close();
} catch (Exception e) {
- logger.debug("response body is null");
+ logger.debug("response body is null", e);
}
String result;
@@ -190,7 +188,8 @@ public class HttpRequest {
return restResponse;
}
- public RestResponse httpSendByMethod(String url, String method, String body, Map<String, String> headers) throws IOException {
+ public RestResponse httpSendByMethod(String url, String method, String body, Map<String, String> headers)
+ throws IOException {
RestResponse restResponse = new RestResponse();
URL obj = new URL(url);
@@ -234,7 +233,7 @@ public class HttpRequest {
in.close();
} catch (Exception e) {
// response = null;
- logger.debug("response body is null");
+ logger.debug("response body is null", e);
}
String result;
@@ -353,7 +352,8 @@ public class HttpRequest {
return httpSendPost(url, body, headers, "PUT");
}
- public RestResponse httpSendPost(String url, String body, Map<String, String> headers, String methodType) throws IOException {
+ public RestResponse httpSendPost(String url, String body, Map<String, String> headers, String methodType)
+ throws IOException {
RestResponse restResponse = new RestResponse();
URL obj = new URL(url);
@@ -428,7 +428,8 @@ public class HttpRequest {
}
- public RestResponse httpSendDeleteWithBody2(String url, String body, Map<String, String> headers) throws ClientProtocolException, IOException {
+ public RestResponse httpSendDeleteWithBody2(String url, String body, Map<String, String> headers)
+ throws ClientProtocolException, IOException {
CloseableHttpClient httpclient = HttpClients.createDefault();
RestResponse restResponse = new RestResponse();
@@ -455,7 +456,8 @@ public class HttpRequest {
return restResponse;
}
- public RestResponse httpSendDeleteWithBody(String url, String body, Map<String, String> headers) throws IOException {
+ public RestResponse httpSendDeleteWithBody(String url, String body, Map<String, String> headers)
+ throws IOException {
RestResponse restResponse = new RestResponse();
URL obj = new URL(url);
@@ -600,7 +602,8 @@ public class HttpRequest {
}
- public RestResponse httpSendPostMultipart(String url, Map<String, String> headers, String jsonLocation, String zipLocation) throws IOException {
+ public RestResponse httpSendPostMultipart(String url, Map<String, String> headers, String jsonLocation,
+ String zipLocation) throws IOException {
Gson gson = new Gson();
String gsonToSend = null;
@@ -665,7 +668,8 @@ public class HttpRequest {
}
- public RestResponse httpSendPostWithAuth(String url, String body, Map<String, String> headers, String username, String password) throws IOException {
+ 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());
@@ -799,7 +803,8 @@ public class HttpRequest {
return restResponse;
}
- public static RestResponse sendHttpPostWithEntity(HttpEntity requestEntity, String url, Map<String, String> headers) throws IOException, ClientProtocolException {
+ public static RestResponse sendHttpPostWithEntity(HttpEntity requestEntity, String url, Map<String, String> headers)
+ throws IOException, ClientProtocolException {
CloseableHttpResponse response = null;
CloseableHttpClient client = HttpClients.createDefault();
try {
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
index 3af40c5bb8..71e75c9a1e 100644
--- 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
@@ -20,6 +20,9 @@
package org.openecomp.sdc.ci.tests.execute.TODO;
+import org.testng.annotations.AfterClass;
+import org.testng.annotations.Test;
+import org.testng.AssertJUnit;
import java.io.File;
import java.io.IOException;
@@ -33,11 +36,8 @@ 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 org.openecomp.sdc.ci.tests.utils.DbUtils.TitanState;
import fj.data.Either;
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
index cd0647d8b1..7e363202bb 100644
--- 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
@@ -61,8 +61,10 @@ import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum;
import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum;
import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.Utils;
import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils;
import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.general.FileUtils;
import org.openecomp.sdc.ci.tests.utils.rest.ArtifactRestUtils;
import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
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
index b3c3f3f5b6..28c346efc9 100644
--- 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
@@ -170,7 +170,7 @@ public class CrudArt extends ComponentBaseTest {
heatArtifactDetails.setPayload(payload);
RestResponse addInformationalArtifactToResource = ArtifactRestUtils.addInformationalArtifactToResource(heatArtifactDetails, sdncDesignerDetails1, vfResourceDetails.getUniqueId());
- logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ 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
@@ -313,7 +313,7 @@ public class CrudArt extends ComponentBaseTest {
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());
+ 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.
@@ -333,7 +333,7 @@ public class CrudArt extends ComponentBaseTest {
String fileName = heatSuccessFile;
List<String> listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath);
- logger.debug("listFileName: {}", listFileName.toString());
+ logger.debug("listFileName: {}", listFileName);
String payload = FileUtils.loadPayloadFile(listFileName, fileName, true);
ArtifactReqDetails heatArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType());
@@ -352,7 +352,7 @@ public class CrudArt extends ComponentBaseTest {
List<String> listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath);
// Add HEAT
- logger.debug("listFileName: {}", listFileName.toString());
+ logger.debug("listFileName: {}", listFileName);
String payload = FileUtils.loadPayloadFile(listFileName, fileName, true);
ArtifactReqDetails heatArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType());
heatArtifactDetails.setPayload(payload);
@@ -589,17 +589,8 @@ public class CrudArt extends ComponentBaseTest {
// ---------------------------------Service
// success--------------------------------
@Test()
- public void addAllTypesDepArtifactToService() throws Exception, Exception {
-
- // String fileName = heatSuccessFile;
- // List<String> listFileName =
- // FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath);
- // logger.debug("listFileName: {}", listFileName.toString());
-
- // String payload = FileUtils.loadPayloadFile(listFileName, fileName,
- // true);
+ public void addAllTypesDepArtifactToService() throws Exception {
ArtifactReqDetails otherArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.OTHER.getType());
- // otherArtifactDetails.setPayload(payload);
RestResponse addInformationalArtifactToService = ArtifactRestUtils.addInformationalArtifactToService(otherArtifactDetails, sdncDesignerDetails1, serviceDetails.getUniqueId());
logger.debug("addInformationalArtifactToService response: {}", addInformationalArtifactToService.getResponseMessage());
@@ -618,7 +609,7 @@ public class CrudArt extends ComponentBaseTest {
String fileName = muranoFile;
List<String> listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath);
- logger.debug("listFileName: {}", listFileName.toString());
+ logger.debug("listFileName: {}", listFileName);
String payload = FileUtils.loadPayloadFile(listFileName, fileName, true);
ArtifactReqDetails heatArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.MURANO_PKG.getType());
@@ -627,7 +618,7 @@ public class CrudArt extends ComponentBaseTest {
heatArtifactDetails.setArtifactLabel("Label");
RestResponse addInformationalArtifactToService = ArtifactRestUtils.addInformationalArtifactToService(heatArtifactDetails, sdncDesignerDetails1, serviceDetails.getUniqueId());
- logger.debug("addInformationalArtifactToService response: {}", addInformationalArtifactToService.getResponseMessage());
+ logger.debug("addInformationalArtifactToService response: {}", addInformationalArtifactToService.getResponseMessage());
assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToService.getErrorCode(), addInformationalArtifactToService.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
}
@@ -679,7 +670,7 @@ public class CrudArt extends ComponentBaseTest {
// update
heatArtifactDetails.setPayloadData(payload);
RestResponse updateInformationalArtifactToService = ArtifactRestUtils.updateInformationalArtifactOfServiceByMethod(heatArtifactDetails, serviceDetails.getUniqueId(), sdncDesignerDetails1, "POST");
- logger.debug("updateInformationalArtifactToService response: {}", updateInformationalArtifactToService.getResponseMessage());
+ logger.debug("updateInformationalArtifactToService response: {}", updateInformationalArtifactToService.getResponseMessage());
assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + updateInformationalArtifactToService.getErrorCode(), updateInformationalArtifactToService.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
}
@@ -716,7 +707,7 @@ public class CrudArt extends ComponentBaseTest {
String filename1 = heatSuccessFile;
// String filename2 = heatSuccessMiniFile;
List<String> listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath);
- logger.debug("listFileName: {}", listFileName.toString());
+ logger.debug("listFileName: {}", listFileName);
String payload = FileUtils.loadPayloadFile(listFileName, filename1, true);
@@ -753,7 +744,7 @@ public class CrudArt extends ComponentBaseTest {
String filename1 = heatSuccessFile;
String filename2 = heatSuccessMiniFile;
List<String> listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath);
- logger.debug("listFileName: {}", listFileName.toString());
+ logger.debug("listFileName: {}", listFileName);
String payload = FileUtils.loadPayloadFile(listFileName, filename1, true);
heatTypeArtifactDetails.setPayload(payload);
@@ -782,7 +773,7 @@ public class CrudArt extends ComponentBaseTest {
String fileName = heatInvalidFormat;
List<String> listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath);
- logger.debug("listFileName: {}", listFileName.toString());
+ logger.debug("listFileName: {}", listFileName);
String payload = FileUtils.loadPayloadFile(listFileName, fileName, true);
heatTypeArtifactDetails.setPayload(payload);
@@ -803,7 +794,7 @@ public class CrudArt extends ComponentBaseTest {
String fileName = yamlInvalidFormat;
List<String> listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath);
- logger.debug("listFileName: {}", listFileName.toString());
+ logger.debug("listFileName: {}", listFileName);
String payload = FileUtils.loadPayloadFile(listFileName, fileName, true);
heatTypeArtifactDetails.setPayload(payload);
@@ -824,7 +815,7 @@ public class CrudArt extends ComponentBaseTest {
String fileName = yangFile;
List<String> listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath);
- logger.debug("listFileName: {}", listFileName.toString());
+ logger.debug("listFileName: {}", listFileName);
String payload = FileUtils.loadPayloadFile(listFileName, fileName, true);
@@ -847,7 +838,7 @@ public class CrudArt extends ComponentBaseTest {
String fileName = heatSuccessFile;
List<String> listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath);
- logger.debug("listFileName: {}", listFileName.toString());
+ logger.debug("listFileName: {}", listFileName);
String payload = FileUtils.loadPayloadFile(listFileName, fileName, true);
heatTypeArtifactDetails.setPayload(payload);
@@ -892,7 +883,7 @@ public class CrudArt extends ComponentBaseTest {
String fileName1 = heatSuccessFile;
String fileName2 = heatSuccessMiniFile;
List<String> listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath);
- logger.debug("listFileName: {}", listFileName.toString());
+ logger.debug("listFileName: {}", listFileName);
String payload = FileUtils.loadPayloadFile(listFileName, fileName1, true);
ArtifactReqDetails heatArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.OTHER.getType());
@@ -925,7 +916,7 @@ public class CrudArt extends ComponentBaseTest {
String fileName = heatInvalidFormat;
List<String> listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath);
- logger.debug("listFileName: {}", listFileName.toString());
+ logger.debug("listFileName: {}", listFileName);
String payload = FileUtils.loadPayloadFile(listFileName, fileName, true);
@@ -943,13 +934,12 @@ public class CrudArt extends ComponentBaseTest {
}
- // TODO Andrey Obsolete
@Test(enabled = false)
public void addHeatArtifactInvalidYamlFormatToService() throws Exception, Exception {
String fileName = yamlInvalidFormat;
List<String> listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath);
- logger.debug("listFileName: {}", listFileName.toString());
+ logger.debug("listFileName: {}", listFileName);
String payload = FileUtils.loadPayloadFile(listFileName, fileName, true);
@@ -957,7 +947,7 @@ public class CrudArt extends ComponentBaseTest {
heatArtifactDetails.setPayload(payload);
RestResponse addInformationalArtifactToService = ArtifactRestUtils.addInformationalArtifactToService(heatArtifactDetails, sdncDesignerDetails1, serviceDetails.getUniqueId());
- logger.debug("addInformationalArtifactToService response: {}", addInformationalArtifactToService.getResponseMessage());
+ 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());
@@ -972,7 +962,7 @@ public class CrudArt extends ComponentBaseTest {
String fileName = muranoFile;
List<String> listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath);
- logger.debug("listFileName: {}", listFileName.toString());
+ logger.debug("listFileName: {}", listFileName);
String payload = FileUtils.loadPayloadFile(listFileName, fileName, true);
@@ -981,7 +971,7 @@ public class CrudArt extends ComponentBaseTest {
heatArtifactDetails.setArtifactName(fileName);
RestResponse addInformationalArtifactToService = ArtifactRestUtils.addInformationalArtifactToService(heatArtifactDetails, sdncDesignerDetails1, serviceDetails.getUniqueId());
- logger.debug("addInformationalArtifactToService response: {}", addInformationalArtifactToService.getResponseMessage());
+ 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());
@@ -1019,7 +1009,7 @@ public class CrudArt extends ComponentBaseTest {
String fileName = heatSuccessFile;
List<String> listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath);
- logger.debug("listFileName: {}", listFileName.toString());
+ logger.debug("listFileName: {}", listFileName);
String payload = FileUtils.loadPayloadFile(listFileName, fileName, true);
@@ -1063,7 +1053,7 @@ public class CrudArt extends ComponentBaseTest {
ArtifactTypeEnum artifactType = ArtifactTypeEnum.VNF_CATALOG;
RestResponse addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfResourceDetails);
- logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ 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);
@@ -1083,7 +1073,7 @@ public class CrudArt extends ComponentBaseTest {
artifactLabel = "Label3";
artifactType = ArtifactTypeEnum.VENDOR_LICENSE;
addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfResourceDetails);
- logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ 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);
@@ -1094,7 +1084,7 @@ public class CrudArt extends ComponentBaseTest {
artifactType = ArtifactTypeEnum.MODEL_INVENTORY_PROFILE;
addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfResourceDetails);
- logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ 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);
@@ -1105,7 +1095,7 @@ public class CrudArt extends ComponentBaseTest {
artifactType = ArtifactTypeEnum.MODEL_QUERY_SPEC;
addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfResourceDetails);
- logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ 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);
@@ -1116,7 +1106,7 @@ public class CrudArt extends ComponentBaseTest {
artifactType = ArtifactTypeEnum.APPC_CONFIG;
addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfResourceDetails);
- logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ 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);
@@ -1128,12 +1118,61 @@ public class CrudArt extends ComponentBaseTest {
artifactType = ArtifactTypeEnum.APPC_CONFIG;
addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfResourceDetails);
- logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ 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
@@ -1145,7 +1184,7 @@ public class CrudArt extends ComponentBaseTest {
ArtifactTypeEnum artifactType = ArtifactTypeEnum.VNF_CATALOG;
RestResponse addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfcResourceDetails);
- logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ 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);
@@ -1156,7 +1195,7 @@ public class CrudArt extends ComponentBaseTest {
artifactType = ArtifactTypeEnum.VF_LICENSE;
addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfcResourceDetails);
- logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ 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);
@@ -1167,7 +1206,7 @@ public class CrudArt extends ComponentBaseTest {
artifactType = ArtifactTypeEnum.VENDOR_LICENSE;
addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfcResourceDetails);
- logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ 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);
@@ -1178,7 +1217,7 @@ public class CrudArt extends ComponentBaseTest {
artifactType = ArtifactTypeEnum.MODEL_INVENTORY_PROFILE;
addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfcResourceDetails);
- logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ 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);
@@ -1189,7 +1228,7 @@ public class CrudArt extends ComponentBaseTest {
artifactType = ArtifactTypeEnum.MODEL_QUERY_SPEC;
addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfcResourceDetails);
- logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ 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);
@@ -1249,7 +1288,7 @@ public class CrudArt extends ComponentBaseTest {
String artifactLabel = "Label2";
ArtifactTypeEnum artifactType = ArtifactTypeEnum.VF_LICENSE;
RestResponse addDeploymentArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vlResourceDetails);
- logger.debug("addInformationalArtifactToResource response: {}", addDeploymentArtifactToResource.getResponseMessage());
+ 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);
@@ -1272,7 +1311,7 @@ public class CrudArt extends ComponentBaseTest {
String artifactLabel = "Label2";
ArtifactTypeEnum artifactType = ArtifactTypeEnum.VF_LICENSE;
RestResponse addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfResourceDetails);
- logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ 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);
@@ -1281,7 +1320,7 @@ public class CrudArt extends ComponentBaseTest {
artifactLabel = "Label3";
artifactType = ArtifactTypeEnum.VENDOR_LICENSE;
addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfResourceDetails);
- logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ 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);
@@ -1451,7 +1490,7 @@ public class CrudArt extends ComponentBaseTest {
String artifactLabel = "Label1";
ArtifactTypeEnum artifactType = ArtifactTypeEnum.VNF_CATALOG;
RestResponse addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfResourceDetails);
- logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ 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);
@@ -1462,7 +1501,7 @@ public class CrudArt extends ComponentBaseTest {
artifactLabel = "Label2";
artifactType = ArtifactTypeEnum.APPC_CONFIG;
addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfResourceDetails);
- logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ 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);
@@ -1473,7 +1512,7 @@ public class CrudArt extends ComponentBaseTest {
artifactType = ArtifactTypeEnum.MODEL_INVENTORY_PROFILE;
addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfResourceDetails);
- logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ 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);
@@ -1484,7 +1523,7 @@ public class CrudArt extends ComponentBaseTest {
artifactType = ArtifactTypeEnum.MODEL_QUERY_SPEC;
addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfResourceDetails);
- logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ 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);
@@ -1516,7 +1555,7 @@ public class CrudArt extends ComponentBaseTest {
String artifactLabel = "Label7";
ArtifactTypeEnum artifactType = ArtifactTypeEnum.APPC_CONFIG;
RestResponse addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfcResourceDetails);
- logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ 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);
@@ -1535,7 +1574,7 @@ public class CrudArt extends ComponentBaseTest {
String artifactLabel = "Label7";
ArtifactTypeEnum artifactType = ArtifactTypeEnum.APPC_CONFIG;
RestResponse addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, cpResourceDetails);
- logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ 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);
@@ -1554,7 +1593,7 @@ public class CrudArt extends ComponentBaseTest {
String artifactLabel = "Label7";
ArtifactTypeEnum artifactType = ArtifactTypeEnum.APPC_CONFIG;
RestResponse addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vlResourceDetails);
- logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ 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);
@@ -1585,7 +1624,7 @@ public class CrudArt extends ComponentBaseTest {
ArtifactTypeEnum artifactType = ArtifactTypeEnum.APPC_CONFIG;
RestResponse addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfResourceDetails);
- logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ 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<>();
@@ -1607,7 +1646,7 @@ public class CrudArt extends ComponentBaseTest {
ArtifactTypeEnum artifactType = ArtifactTypeEnum.VNF_CATALOG;
RestResponse addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, cpResourceDetails);
- logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ 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);
@@ -1618,7 +1657,7 @@ public class CrudArt extends ComponentBaseTest {
artifactType = ArtifactTypeEnum.MODEL_INVENTORY_PROFILE;
addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, cpResourceDetails);
- logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ 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);
@@ -1629,7 +1668,7 @@ public class CrudArt extends ComponentBaseTest {
artifactType = ArtifactTypeEnum.MODEL_QUERY_SPEC;
addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, cpResourceDetails);
- logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ 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);
@@ -1645,7 +1684,7 @@ public class CrudArt extends ComponentBaseTest {
ArtifactTypeEnum artifactType = ArtifactTypeEnum.VNF_CATALOG;
RestResponse addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vlResourceDetails);
- logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ 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);
@@ -1656,7 +1695,7 @@ public class CrudArt extends ComponentBaseTest {
artifactType = ArtifactTypeEnum.MODEL_INVENTORY_PROFILE;
addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vlResourceDetails);
- logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ 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);
@@ -1667,7 +1706,7 @@ public class CrudArt extends ComponentBaseTest {
artifactType = ArtifactTypeEnum.MODEL_QUERY_SPEC;
addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vlResourceDetails);
- logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ 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);
@@ -1683,7 +1722,7 @@ public class CrudArt extends ComponentBaseTest {
ArtifactTypeEnum artifactType = ArtifactTypeEnum.VNF_CATALOG;
RestResponse addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfcResourceDetails);
- logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ 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);
@@ -1694,7 +1733,7 @@ public class CrudArt extends ComponentBaseTest {
artifactType = ArtifactTypeEnum.MODEL_INVENTORY_PROFILE;
addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfcResourceDetails);
- logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ 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);
@@ -1705,7 +1744,7 @@ public class CrudArt extends ComponentBaseTest {
artifactType = ArtifactTypeEnum.MODEL_QUERY_SPEC;
addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfcResourceDetails);
- logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ 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);
@@ -1736,7 +1775,7 @@ public class CrudArt extends ComponentBaseTest {
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.toString());
+ logger.debug("listFileName: {}", listFileName);
String payload = FileUtils.loadPayloadFile(listFileName, artifactFileName, true);
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/DownloadComponentArt.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/DownloadComponentArt.java
index 0ae975207b..5ec4a86977 100644
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/DownloadComponentArt.java
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/DownloadComponentArt.java
@@ -91,7 +91,6 @@ 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;
@@ -108,229 +107,226 @@ public class DownloadComponentArt extends ComponentBaseTest {
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 {
+ public void init() throws Exception{
sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
- Resource resourceObj = AtomicOperationUtils
- .createResourceByType(ResourceTypeEnum.VFC, UserRoleEnum.DESIGNER, true).left().value();
+ Resource resourceObj = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VFC, UserRoleEnum.DESIGNER, true).left().value();
Service serviceObj = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value();
-
- resourceDetails = new ResourceReqDetails(resourceObj);
+
+
+ resourceDetails = new ResourceReqDetails(resourceObj);
serviceDetails = new ServiceReqDetails(serviceObj);
}
-
- @Rule
+
+ @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);
+ 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);
-
+ 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");
-
+
+ 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.");
-
+ 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 = "ArtifactDownload";
-
+
+ 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("/asdc/v1/catalog/resources/%s/artifacts/%s", resourceUUID, artifactUUID);
expectedResourceAuditJavaObject.setRESOURCE_URL(resource_url);
-
- AuditValidationUtils.validateAuditDownloadExternalAPI(expectedResourceAuditJavaObject, auditAction, null,
- false);
+
+ 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);
+ 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);
-
+ 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");
-
+
+ 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.");
+ 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);
+ 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();
+
+ 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");
-
+
+ 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.");
-
+ 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 = "ArtifactDownload";
-
+
+ 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("/asdc/v1/catalog/services/%s/artifacts/%s", resourceUUID, artifactUUID);
expectedResourceAuditJavaObject.setRESOURCE_URL(resource_url);
-
- AuditValidationUtils.validateAuditDownloadExternalAPI(expectedResourceAuditJavaObject, auditAction, null,
- false);
+
+ AuditValidationUtils.validateAuditDownloadExternalAPI(expectedResourceAuditJavaObject, auditAction, null, false);
}
-
- // External API - Download ComponentInstance artifact of service - negative
- // test
+
+
+
+
+
+
+ // 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);
+
+ 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();
+ 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);
+ 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();
-
+
+
+ ComponentInstance resourceDetailsVF1ins_01 = AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceDetailsVF_01, resourceDetailsService, UserRoleEnum.DESIGNER, true).left().value();
+
+
System.out.println("-----");
-
+
+
String resourceUUID = resourceDetailsService.getUUID();
- String componentInstanceUID = resourceDetailsVF1ins_01.getUniqueId();
+ String componentNormalizedName = resourceDetailsVF1ins_01.getNormalizedName();
String artifactUUID = heatArtifact.getArtifactUUID();
-
+
System.out.println("Resource UUID: " + resourceUUID);
- System.out.println("Component instance UID: " + componentInstanceUID);
+ System.out.println("Component NormalizedName: " + componentNormalizedName);
System.out.println("Artifact UUID: " + artifactUUID);
-
- RestResponse restResponse = ArtifactRestUtils.getComponentInstanceDeploymentArtifactExternalAPI(resourceUUID,
- componentInstanceUID, artifactUUID, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), "Service");
- //
+
+ 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.");
-
+ 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 = "ArtifactDownload";
-
+
+ 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("/asdc/v1/catalog/services/%s/resourceInstances/%s/artifacts/%s",
- resourceUUID, componentInstanceUID, artifactUUID);
+ String resource_url = String.format("/asdc/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);
}
-
+
+
+
+
+
+
+
+
+
@Test
public void downloadArtifactFromResourceTest() throws Exception {
@@ -339,8 +335,7 @@ public class DownloadComponentArt extends ComponentBaseTest {
String jsonBody = createUploadArtifactBodyJson();
String resourceId = resourceDetails.getUniqueId();
- String url = String.format(Urls.ADD_ARTIFACT_TO_RESOURCE, config.getCatalogBeHost(),
- config.getCatalogBePort(), resourceId);
+ 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();
@@ -349,25 +344,21 @@ public class DownloadComponentArt extends ComponentBaseTest {
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);
+
+ 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());
+ 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);
+
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor.constructFieldsForAuditValidation(resourceDetails, resourceDetails.getVersion(), sdncUserDetails);
String auditAction = "ArtifactDownload";
expectedResourceAuditJavaObject.setAction(auditAction);
expectedResourceAuditJavaObject.setPrevState("");
@@ -379,7 +370,7 @@ public class DownloadComponentArt extends ComponentBaseTest {
expectedResourceAuditJavaObject.setCurrArtifactUuid(origArtifact.getUniqueId());
expectedResourceAuditJavaObject.setPrevArtifactUuid("");
AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false);
-
+
} finally {
httpclient.close();
}
@@ -395,8 +386,7 @@ public class DownloadComponentArt extends ComponentBaseTest {
String jsonStr = createUploadArtifactBodyJson();
- String url = String.format(Urls.ADD_ARTIFACT_TO_SERVICE, config.getCatalogBeHost(),
- config.getCatalogBePort(), serviceDetails.getUniqueId());
+ 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();
@@ -406,22 +396,18 @@ public class DownloadComponentArt extends ComponentBaseTest {
addArtifactDataFromResponse(result, origArtifact);
String artifactId = origArtifact.getUniqueId();
- url = String.format(Urls.UI_DOWNLOAD_SERVICE_ARTIFACT, config.getCatalogBeHost(), config.getCatalogBePort(),
- serviceDetails.getUniqueId(), artifactId);
+ 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());
+ 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);
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = AuditValidationUtils.constructFieldsForAuditValidation(serviceDetails, serviceDetails.getVersion(), sdncUserDetails);
String auditAction = "ArtifactDownload";
expectedResourceAuditJavaObject.setAction(auditAction);
expectedResourceAuditJavaObject.setPrevState("");
@@ -432,14 +418,12 @@ public class DownloadComponentArt extends ComponentBaseTest {
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);
+// RestResponse response = ServiceRestUtils.deleteService(serviceDetails, serviceVersion, sdncUserDetails );
+// checkDeleteResponse(response);
httpclient.close();
}
}
@@ -455,9 +439,8 @@ public class DownloadComponentArt extends ComponentBaseTest {
ArtifactDefinition origArtifact = new ArtifactDefinition();
origArtifact.setUniqueId(artifactIdNotFound);
-
- String url = String.format(Urls.UI_DOWNLOAD_RESOURCE_ARTIFACT, config.getCatalogBeHost(),
- config.getCatalogBePort(), resourceId, 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();
@@ -465,8 +448,7 @@ public class DownloadComponentArt extends ComponentBaseTest {
// validate audit
ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.ARTIFACT_NOT_FOUND.name());
- ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor
- .constructFieldsForAuditValidation(resourceDetails, resourceDetails.getVersion(), sdncUserDetails);
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor.constructFieldsForAuditValidation(resourceDetails, resourceDetails.getVersion(), sdncUserDetails);
String auditAction = "ArtifactDownload";
expectedResourceAuditJavaObject.setAction(auditAction);
expectedResourceAuditJavaObject.setPrevState("");
@@ -495,8 +477,7 @@ public class DownloadComponentArt extends ComponentBaseTest {
ArtifactDefinition origArtifact = new ArtifactDefinition();
origArtifact.setUniqueId(artifactIdNotFound);
- String url = String.format(Urls.UI_DOWNLOAD_SERVICE_ARTIFACT, config.getCatalogBeHost(),
- config.getCatalogBePort(), serviceDetails.getUniqueId(), 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();
@@ -504,8 +485,7 @@ public class DownloadComponentArt extends ComponentBaseTest {
// validate audit
ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.ARTIFACT_NOT_FOUND.name());
- ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ServiceValidationUtils
- .constructFieldsForAuditValidation(serviceDetails, serviceDetails.getVersion(), sdncUserDetails);
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ServiceValidationUtils.constructFieldsForAuditValidation(serviceDetails, serviceDetails.getVersion(), sdncUserDetails);
String auditAction = "ArtifactDownload";
expectedResourceAuditJavaObject.setAction(auditAction);
expectedResourceAuditJavaObject.setPrevState("");
@@ -529,11 +509,9 @@ public class DownloadComponentArt extends ComponentBaseTest {
ArtifactReqDetails defaultArtifact = ElementFactory.getDefaultArtifact();
- RestResponse response = ArtifactRestUtils.addInformationalArtifactToResource(defaultArtifact, sdncUserDetails,
- resourceDetails.getUniqueId());
+ RestResponse response = ArtifactRestUtils.addInformationalArtifactToResource(defaultArtifact, sdncUserDetails, resourceDetails.getUniqueId());
int status = response.getErrorCode();
- AssertJUnit.assertEquals("add informational artifact request returned status: " + response.getErrorCode(), 200,
- status);
+ AssertJUnit.assertEquals("add informational artifact request returned status: " + response.getErrorCode(), 200, status);
RestResponse resourceResp = ResourceRestUtils.getResource(resourceDetails.getUniqueId());
Resource resource = ResponseParser.convertResourceResponseToJavaObject(resourceResp.getResponse());
@@ -549,7 +527,8 @@ public class DownloadComponentArt extends ComponentBaseTest {
}
AssertJUnit.assertTrue(isExist);
}
-
+
+
protected String createUploadArtifactBodyJson() {
Map<String, Object> jsonBody = new HashMap<String, Object>();
jsonBody.put("artifactName", UPLOAD_ARTIFACT_NAME);
@@ -561,12 +540,12 @@ public class DownloadComponentArt extends ComponentBaseTest {
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();
+ ArtifactDefinition artifact = new ArtifactDefinition();
String payload = null;
JsonElement artifactPayload = jsonElement.get(Constants.ARTIFACT_PAYLOAD_DATA);
if (artifactPayload != null && !artifactPayload.isJsonNull()) {
@@ -575,18 +554,17 @@ public class DownloadComponentArt extends ComponentBaseTest {
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");
- */
+
+ /*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);
@@ -594,53 +572,49 @@ public class DownloadComponentArt extends ComponentBaseTest {
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);
+
+ 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);
+ String responseString = EntityUtils.toString(entity);
JSONObject responseMap = (JSONObject) jsonParser.parse(responseString);
- artifact.setEsId((String) responseMap.get("esId"));
+ 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 {
+
+ 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 {
+
+ 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);
@@ -651,10 +625,10 @@ public class DownloadComponentArt extends ComponentBaseTest {
StringEntity input = new StringEntity(jsonBody);
input.setContentType("application/json");
httppost.setEntity(input);
- log.debug("Executing request {}", httppost.getRequestLine());
+ 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");
@@ -662,21 +636,20 @@ public class DownloadComponentArt extends ComponentBaseTest {
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);
+ ArtifactUiDownloadData artifactUiDownloadData = mapper.readValue(artifactUiDownloadDataStr, ArtifactUiDownloadData.class);
return artifactUiDownloadData;
} catch (Exception e) {
e.printStackTrace();
@@ -684,4 +657,5 @@ public class DownloadComponentArt extends ComponentBaseTest {
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
new file mode 100644
index 0000000000..2ca09b36f3
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/HeatEnvArtifact.java
@@ -0,0 +1,331 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 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
index 02bef89f2c..2e7b6ea4af 100644
--- 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
@@ -39,15 +39,20 @@ import org.javatuples.Pair;
import org.junit.Rule;
import org.junit.rules.TestName;
import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
import org.openecomp.sdc.be.model.ArtifactDefinition;
import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.Product;
import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.Service;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ProductReqDetails;
import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo;
import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
@@ -63,11 +68,14 @@ import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
import org.openecomp.sdc.ci.tests.utils.general.FileUtils;
import org.openecomp.sdc.ci.tests.utils.rest.ArtifactRestUtils;
import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ComponentInstanceRestUtils;
import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ProductRestUtils;
import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils;
+import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.BeforeMethod;
@@ -486,7 +494,7 @@ public class PlaceHolderValidations extends ComponentBaseTest {
RestResponse delteArtifactFromResource = ArtifactRestUtils.deleteInformationalArtifactFromResource(
resourceDetails1.getUniqueId(), heatArtifactDetails, sdncDesignerDetails2);
- logger.debug("addInformationalArtifactToResource response: {}", delteArtifactFromResource.getResponseMessage());
+ logger.debug("addInformationalArtifactToResource response: {} ",delteArtifactFromResource.getResponseMessage());
assertTrue("response code is not 200, returned :" + delteArtifactFromResource.getErrorCode(),
delteArtifactFromResource.getErrorCode() == 200);
@@ -685,7 +693,7 @@ public class PlaceHolderValidations extends ComponentBaseTest {
String sourceDir = config.getResourceConfigDir();
String testResourcesPath = sourceDir + File.separator + folderName;
List<String> listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath);
- logger.debug("listFileName: {}", listFileName.toString());
+ logger.debug("listFileName: {}",listFileName.toString());
String payload = FileUtils.loadPayloadFile(listFileName, ext, true);
ArtifactReqDetails updateArtifactReqDetails = ElementFactory.getDefaultDeploymentArtifactForType(artType);
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ValidateArtResponse.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ValidateArtResponse.java
index 01169630a4..abbaa3050d 100644
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ValidateArtResponse.java
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ValidateArtResponse.java
@@ -34,6 +34,7 @@ import org.openecomp.sdc.be.model.ArtifactDefinition;
import org.openecomp.sdc.be.model.HeatParameterDefinition;
import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.operations.impl.AllOperationsUtil;
import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
@@ -315,7 +316,7 @@ public class ValidateArtResponse extends ComponentBaseTest {
ArtifactDefinition ArtifactDefinitionRespJavaObject = ResponseParser
.convertArtifactDefinitionResponseToJavaObject(updateInformationalArtifactToResource.getResponse());
- List<HeatParameterDefinition> heatParameters = ArtifactDefinitionRespJavaObject.getHeatParameters();
+ List<HeatParameterDefinition> heatParameters = ArtifactDefinitionRespJavaObject.getListHeatParameters();
for (HeatParameterDefinition heatParameterDefinition : heatParameters) {
String verify = updateValueParam;
AssertJUnit.assertTrue("verification failed", verify.equals(heatParameterDefinition.getCurrentValue()));
@@ -389,7 +390,7 @@ public class ValidateArtResponse extends ComponentBaseTest {
ArtifactDefinition ArtifactDefinitionRespJavaObject = ResponseParser
.convertArtifactDefinitionResponseToJavaObject(updateInformationalArtifactToResource.getResponse());
- List<HeatParameterDefinition> heatParameters = ArtifactDefinitionRespJavaObject.getHeatParameters();
+ List<HeatParameterDefinition> heatParameters = ArtifactDefinitionRespJavaObject.getListHeatParameters();
for (HeatParameterDefinition heatParameterDefinition : heatParameters) {
String verify = updateValueParam;
AssertJUnit.assertTrue("verification failed", verify.equals(heatParameterDefinition.getCurrentValue()));
@@ -461,7 +462,7 @@ public class ValidateArtResponse extends ComponentBaseTest {
// verify change in update response
ArtifactDefinition ArtifactDefinitionRespJavaObject = ResponseParser
.convertArtifactDefinitionResponseToJavaObject(updateInformationalArtifactToResource.getResponse());
- List<HeatParameterDefinition> heatParameters = ArtifactDefinitionRespJavaObject.getHeatParameters();
+ List<HeatParameterDefinition> heatParameters = ArtifactDefinitionRespJavaObject.getListHeatParameters();
for (HeatParameterDefinition heatParameterDefinition : heatParameters) {
// String verify = updateValueParam;
if (heatParameterDefinition.getDefaultValue() != null) {
@@ -541,7 +542,7 @@ public class ValidateArtResponse extends ComponentBaseTest {
ArtifactDefinition ArtifactDefinitionRespJavaObject = ResponseParser
.convertArtifactDefinitionResponseToJavaObject(updateInformationalArtifactToResource.getResponse());
- List<HeatParameterDefinition> heatParameters = ArtifactDefinitionRespJavaObject.getHeatParameters();
+ List<HeatParameterDefinition> heatParameters = ArtifactDefinitionRespJavaObject.getListHeatParameters();
for (HeatParameterDefinition heatParameterDefinition : heatParameters) {
String verify = updateValueParam;
AssertJUnit.assertTrue("verification failed", verify.equals(heatParameterDefinition.getCurrentValue()));
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ValidateHeatArtFieldsFromUI.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ValidateHeatArtFieldsFromUI.java
deleted file mode 100644
index c22dcb96d4..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ValidateHeatArtFieldsFromUI.java
+++ /dev/null
@@ -1,444 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 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.testng.AssertJUnit;
-//import org.testng.annotations.Test;
-//
-//import org.openecomp.sdc.be.dao.api.ActionStatus;
-//import org.openecomp.sdc.be.model.ArtifactDefinition;
-//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.ci.tests.datatypes.ArtifactReqDetails;
-//import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
-//import org.openecomp.sdc.ci.tests.datatypes.enums.RespJsonKeysEnum;
-//import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
-//import org.openecomp.sdc.ci.tests.preRequisites.HeatEnvBaseTest;
-//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;
-//
-//public class ValidateHeatArtFieldsFromUI extends HeatEnvBaseTest {
-public class ValidateHeatArtFieldsFromUI {
- //
- //
- //
- // 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 ValidateHeatArtFieldsFromUI() {
- // super(name, ValidateHeatArtFieldsFromUI.class.getName());
- // }
- //
- // @Rule
- // public static TestName name = new TestName();
- //
- //
- // @Test
- // public void heatEnvValidateHeatArtFiledTypes_UpdateFailed() throws
- // Exception {
- //
- // //get relevant service
- // RestResponse serviceGetResponse =
- // ServiceRestUtils.getService(serviceDetails2, sdncDesignerDetails);
- // Service service =
- // ResponseParser.convertServiceResponseToJavaObject(serviceGetResponse.getResponse());
- // List<ComponentInstance> resourceInstances =
- // service.getComponentInstances();
- // ComponentInstance resourceInstance = resourceInstances.get(0);
- //
- //
- // String defaultParam = null;
- //
- // //update heatEnv with invalid value in number field
- //
- // ArtifactDefinition artifact = getCurrentArtifactDefinitionFromService();
- // String currentHeatEnvParamBeforeUpdate = replaceHeatParamsValue(artifact,
- // "home_number", "Tel Aviv");
- // ArtifactReqDetails artReq =
- // ResponseParser.convertArtifactDefinitionToArtifactReqDetailsObject(artifact);
- // RestResponse res = ArtifactRestUtils.updateDeploymentArtifactToRI(artReq,
- // sdncDesignerDetails, resourceInstance.getUniqueId(),
- // service.getUniqueId());
- //
- // // validate negative response
- // List<String> variables = Arrays.asList("HEAT_ENV", "number",
- // "home_number");
- // ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_HEAT_PARAMETER_VALUE.name(),
- // variables, res.getResponse());
- //
- // //validate current value not affected
- // artifact = getCurrentArtifactDefinitionFromService();
- // String currentHeatEnvParamAfterUpdate = getHeatParamsValue(artifact,
- // "home_number");
- // AssertJUnit.assertTrue("HeatEnvParam was not updated: " +
- // currentHeatEnvParamBeforeUpdate,
- // currentHeatEnvParamBeforeUpdate.equals(currentHeatEnvParamAfterUpdate));
- //
- // //update heatEnv with invalid value in boolean field
- //
- // artifact = getCurrentArtifactDefinitionFromService();
- // currentHeatEnvParamBeforeUpdate = replaceHeatParamsValue(artifact,
- // "private_building", "Tel Aviv");
- // artReq =
- // ResponseParser.convertArtifactDefinitionToArtifactReqDetailsObject(artifact);
- // res = ArtifactRestUtils.updateDeploymentArtifactToRI(artReq,
- // sdncDesignerDetails, resourceInstance.getUniqueId(),
- // service.getUniqueId());
- //
- // // validate negative response
- // variables = Arrays.asList("HEAT_ENV", "boolean", "private_building");
- // ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_HEAT_PARAMETER_VALUE.name(),
- // variables, res.getResponse());
- //
- // //validate current value not affected
- // artifact = getCurrentArtifactDefinitionFromService();
- // currentHeatEnvParamAfterUpdate = getHeatParamsValue(artifact,
- // "private_building");
- // AssertJUnit.assertTrue("HeatEnvParam was not updated: " +
- // currentHeatEnvParamBeforeUpdate,
- // currentHeatEnvParamBeforeUpdate.equals(currentHeatEnvParamAfterUpdate));
- //
- //
- //
- //
- // //update heatEnv with invalid value in boolean field
- //
- // artifact = getCurrentArtifactDefinitionFromService();
- // currentHeatEnvParamBeforeUpdate = replaceHeatParamsValue(artifact,
- // "city_name", "\uC2B5");
- // artReq =
- // ResponseParser.convertArtifactDefinitionToArtifactReqDetailsObject(artifact);
- // res = ArtifactRestUtils.updateDeploymentArtifactToRI(artReq,
- // sdncDesignerDetails, resourceInstance.getUniqueId(),
- // service.getUniqueId());
- // // validate negative response
- // variables = Arrays.asList("HEAT_ENV", "string", "city_name");
- // ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_HEAT_PARAMETER_VALUE.name(),
- // variables, res.getResponse());
- //
- // //validate current value not affected
- //
- // artifact = getCurrentArtifactDefinitionFromService();
- // currentHeatEnvParamAfterUpdate = getHeatParamsValue(artifact,
- // "city_name");
- // AssertJUnit.assertTrue("HeatEnvParam was not updated: " +
- // currentHeatEnvParamBeforeUpdate,
- // currentHeatEnvParamBeforeUpdate.equals(currentHeatEnvParamAfterUpdate));
- // }
- //
- // @Test
- // public void heatValidateHeatArtFiledTypes_UpdateFailed() throws Exception
- // {
- //
- //
- // RestResponse checkOutResponse =
- // LifecycleRestUtils.changeResourceState(resourceSC, sdncDesignerDetails,
- // LifeCycleStatesEnum.CHECKOUT);
- // AssertJUnit.assertTrue("response code is not 200, returned: " +
- // checkOutResponse.getErrorCode(),checkOutResponse.getErrorCode() == 200);
- // //get relevant service
- // RestResponse resourceGetResponse =
- // ResourceRestUtils.getResource(resourceSC, sdncDesignerDetails);
- // Resource resource =
- // ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
- //
- // //update heatEnv with invalid value in number field
- //
- // ArtifactDefinition artifact = getCurrentArtifactDefinitionFromResource();
- // String currentHeatEnvParamBeforeUpdate = replaceHeatParamsValue(artifact,
- // "home_number", "Tel Aviv");
- // ArtifactReqDetails artReq =
- // ResponseParser.convertArtifactDefinitionToArtifactReqDetailsObject(artifact);
- // RestResponse res =
- // ArtifactRestUtils.updateInformationalArtifactToResource(artReq,
- // sdncDesignerDetails, resource.getUniqueId());
- // // validate negative response
- // List<String> variables = Arrays.asList("HEAT", "number", "home_number");
- // ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_HEAT_PARAMETER_VALUE.name(),
- // variables, res.getResponse());
- //
- // //validate current value not affected
- //
- // artifact = getCurrentArtifactDefinitionFromResource();
- // String currentHeatEnvParamAfterUpdate = getHeatParamsValue(artifact,
- // "home_number");
- // AssertJUnit.assertTrue("HeatEnvParam was not updated: " +
- // currentHeatEnvParamBeforeUpdate,
- // currentHeatEnvParamBeforeUpdate.equals(currentHeatEnvParamAfterUpdate));
- //
- //
- // //update heatEnv with invalid value in boolean field
- //
- // artifact = getCurrentArtifactDefinitionFromResource();
- // currentHeatEnvParamBeforeUpdate = replaceHeatParamsValue(artifact,
- // "private_building", "Tel Aviv");
- // artReq =
- // ResponseParser.convertArtifactDefinitionToArtifactReqDetailsObject(artifact);
- // res = ArtifactRestUtils.updateDeploymentArtifactToResource(artReq,
- // sdncDesignerDetails, resource.getUniqueId());
- // // validate negative response
- // variables = Arrays.asList("HEAT", "boolean", "private_building");
- // ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_HEAT_PARAMETER_VALUE.name(),
- // variables, res.getResponse());
- //
- // //validate current value not affected
- //
- // artifact = getCurrentArtifactDefinitionFromResource();
- //
- // currentHeatEnvParamAfterUpdate = getHeatParamsValue(artifact,
- // "private_building");
- // AssertJUnit.assertTrue("HeatEnvParam was not updated: " +
- // currentHeatEnvParamBeforeUpdate,
- // currentHeatEnvParamBeforeUpdate.equals(currentHeatEnvParamAfterUpdate));
- //
- //
- // //update heatEnv with invalid value in boolean field
- //
- // artifact = getCurrentArtifactDefinitionFromResource();
- // currentHeatEnvParamBeforeUpdate = replaceHeatParamsValue(artifact,
- // "city_name", "\uC2B5");
- //
- // artReq =
- // ResponseParser.convertArtifactDefinitionToArtifactReqDetailsObject(artifact);
- // res = ArtifactRestUtils.updateDeploymentArtifactToResource(artReq,
- // sdncDesignerDetails, resource.getUniqueId());
- // // validate negative response
- // variables = Arrays.asList("HEAT", "string", "city_name");
- // ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_HEAT_PARAMETER_VALUE.name(),
- // variables, res.getResponse());
- //
- // //validate current value not affected
- //
- // artifact = getCurrentArtifactDefinitionFromResource();
- // currentHeatEnvParamAfterUpdate = getHeatParamsValue(artifact,
- // "city_name");
- // AssertJUnit.assertTrue("HeatEnvParam was not updated: " +
- // currentHeatEnvParamBeforeUpdate,
- // currentHeatEnvParamBeforeUpdate.equals(currentHeatEnvParamAfterUpdate));
- //
- // }
- //
- // @Test
- // public void heatEnvValidateHeatArtFiledTypes_boolNormalization_suc()
- // throws Exception {
- //
- // //get relevant service
- // RestResponse serviceGetResponse =
- // ServiceRestUtils.getService(serviceDetails2, sdncDesignerDetails);
- // Service service =
- // ResponseParser.convertServiceResponseToJavaObject(serviceGetResponse.getResponse());
- // List<ComponentInstance> resourceInstances =
- // service.getComponentInstances();
- // ComponentInstance resourceInstance = resourceInstances.get(0);
- //
- // String defaultParam = null;
- // String currentHeatEnvParamBefore = null;
- // String currentHeatEnvParamAfter = null;
- //
- //
- // List<String> listOfBoolValuesToValidate = Arrays.asList("T", "on", "1",
- // "yes", "y");
- //
- // for (String element : listOfBoolValuesToValidate) {
- //
- // //update heatEnv with invalid value in boolean field
- //
- // ArtifactDefinition artifact = getCurrentArtifactDefinitionFromService();
- // List<HeatParameterDefinition> heatParameters =
- // artifact.getHeatParameters();
- // for(HeatParameterDefinition param : heatParameters){
- // if (param.getName().equals("private_building")){
- // defaultParam = param.getDefaultValue();
- // currentHeatEnvParamBefore = param.getCurrentValue();
- // param.setCurrentValue(element);
- // }
- // }
- // artifact.setHeatParameters(heatParameters);
- // ArtifactReqDetails artReq =
- // ResponseParser.convertArtifactDefinitionToArtifactReqDetailsObject(artifact);
- // RestResponse res = ArtifactRestUtils.updateDeploymentArtifactToRI(artReq,
- // sdncDesignerDetails, resourceInstance.getUniqueId(),
- // service.getUniqueId());
- // AssertJUnit.assertTrue("response code is not 200, returned: " +
- // res.getErrorCode(), res.getErrorCode() == 200);
- //
- // //validate current value not affected
- //
- // artifact = getCurrentArtifactDefinitionFromService();
- // heatParameters = artifact.getHeatParameters();
- // for(HeatParameterDefinition param : heatParameters){
- // if (param.getName().equals("private_building")){
- // currentHeatEnvParamAfter = param.getCurrentValue();
- // }
- // }
- // AssertJUnit.assertTrue("HeatEnvParam was not updated: " +
- // currentHeatEnvParamBefore, currentHeatEnvParamAfter.equals("true"));
- //
- // }
- //
- // }
- //
- //
- // @Test
- // public void heatValidateHeatArtFiledTypes_boolNormalization_suc() throws
- // Exception {
- //
- // RestResponse checkOutResponse =
- // LifecycleRestUtils.changeResourceState(resourceSC, sdncDesignerDetails,
- // LifeCycleStatesEnum.CHECKOUT);
- // AssertJUnit.assertTrue("response code is not 200, returned: " +
- // checkOutResponse.getErrorCode(),checkOutResponse.getErrorCode() == 200);
- // //get relevant service
- // RestResponse resourceGetResponse =
- // ResourceRestUtils.getResource(resourceSC, sdncDesignerDetails);
- // Resource resource =
- // ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
- //
- //
- // String defaultParam = null;
- // String currentHeatEnvParamBefore = null;
- // String currentHeatEnvParamAfter = null;
- //
- //
- // List<String> listOfBoolValuesToValidate = Arrays.asList("T", "on", "1",
- // "yes", "y");
- //
- // for (String element : listOfBoolValuesToValidate) {
- //
- // //update heatEnv with invalid value in boolean field
- //
- // ArtifactDefinition artifact = getCurrentArtifactDefinitionFromResource();
- // List<HeatParameterDefinition> heatParameters =
- // artifact.getHeatParameters();
- // for(HeatParameterDefinition param : heatParameters){
- // if (param.getName().equals("private_building")){
- // defaultParam = param.getDefaultValue();
- // currentHeatEnvParamBefore = param.getCurrentValue();
- // param.setCurrentValue(element);
- // }
- // }
- // artifact.setHeatParameters(heatParameters);
- // ArtifactReqDetails artReq =
- // ResponseParser.convertArtifactDefinitionToArtifactReqDetailsObject(artifact);
- // RestResponse res =
- // ArtifactRestUtils.updateInformationalArtifactToResource(artReq,
- // sdncDesignerDetails, resource.getUniqueId());
- // AssertJUnit.assertTrue("response code is not 200, returned: " +
- // res.getErrorCode(), res.getErrorCode() == 200);
- //
- // //validate current value not affected
- //
- // artifact = getCurrentArtifactDefinitionFromResource();
- // heatParameters = artifact.getHeatParameters();
- // for(HeatParameterDefinition param : heatParameters){
- // if (param.getName().equals("private_building")){
- // currentHeatEnvParamAfter = param.getCurrentValue();
- // }
- // }
- // AssertJUnit.assertTrue("HeatEnvParam was not updated: " +
- // currentHeatEnvParamBefore, currentHeatEnvParamAfter.equals("true"));
- //
- // }
- //
- // }
- //
- //
- // private ArtifactDefinition getCurrentArtifactDefinitionFromResource()
- // throws Exception {
- //
- // RestResponse resourceGetResponse =
- // ResourceRestUtils.getResource(resourceSC, sdncDesignerDetails);
- // Resource resource =
- // ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
- //
- // ArtifactDefinition artifactDefinition =
- // resource.getDeploymentArtifacts().get("heat");
- //
- //
- // return artifactDefinition;
- //
- // }
- //
- //
- // private ArtifactDefinition getCurrentArtifactDefinitionFromService()
- // throws Exception {
- //
- // RestResponse serviceGetResponse =
- // ServiceRestUtils.getService(serviceDetails2, sdncDesignerDetails);
- // Service service =
- // ResponseParser.convertServiceResponseToJavaObject(serviceGetResponse.getResponse());
- // ArtifactDefinition artifactDefinition = new ArtifactDefinition();
- // artifactDefinition =
- // service.getComponentInstances().get(0).getDeploymentArtifacts().get("heatenv");
- //
- //
- // return artifactDefinition;
- //
- // }
- //
- // private String replaceHeatParamsValue(ArtifactDefinition artifact, String
- // paramName, String paramValue) {
- // String defaultParam;
- // String currentHeatEnvParam = null;
- // List<HeatParameterDefinition> heatParameters =
- // artifact.getHeatParameters();
- // for(HeatParameterDefinition param : heatParameters){
- // if (param.getName().equals(paramName)){
- // defaultParam = param.getDefaultValue();
- // currentHeatEnvParam = param.getCurrentValue();
- // param.setCurrentValue(paramValue);
- // }
- // }
- // artifact.setHeatParameters(heatParameters);
- // return currentHeatEnvParam;
- // }
- //
- // private String getHeatParamsValue(ArtifactDefinition artifact,
- // String paramName) {
- // List<HeatParameterDefinition> heatParameters =
- // artifact.getHeatParameters();
- // String currentHeatEnvParamValue = null;
- // for(HeatParameterDefinition param : heatParameters){
- // if (param.getName().equals(paramName)){
- // currentHeatEnvParamValue = param.getCurrentValue();
- // }
- // }
- // return currentHeatEnvParamValue;
- // }
-}
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
index 09cda0b73c..a00fceba49 100644
--- 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
@@ -103,7 +103,7 @@ public class ValidateHeatArtFieldsTypes extends ComponentBaseTest {
response.getErrorCode() == 200);
ArtifactDefinition artifactDefinitionJavaObject = ResponseParser
.convertArtifactDefinitionResponseToJavaObject(response.getResponse());
- List<HeatParameterDefinition> heatParameters = artifactDefinitionJavaObject.getHeatParameters();
+ List<HeatParameterDefinition> heatParameters = artifactDefinitionJavaObject.getListHeatParameters();
String currentValue = null;
for (HeatParameterDefinition heatParameterDefinition : heatParameters) {
if (heatParameterDefinition.getName().equals("city_name")) {
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/attribute/ComponentInstanceAttributeTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/attribute/ComponentInstanceAttributeTest.java
index 58e27177d1..d1b6ff5676 100644
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/attribute/ComponentInstanceAttributeTest.java
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/attribute/ComponentInstanceAttributeTest.java
@@ -59,23 +59,34 @@ public class ComponentInstanceAttributeTest extends ComponentBaseTest {
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();
+ 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, ComponentInstanceAttribute> attributeGetter = resourceVf -> resourceVf.getComponentInstancesAttributes().values().iterator().next().stream().filter(att -> att.getName().equals("private_address")).findAny().get();
+ Function<Resource, ComponentInstanceAttribute> 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));
+ final Resource vfWithInsatncePreUpdate = swallowException(
+ () -> (Resource) AtomicOperationUtils.getCompoenntObject(vf, UserRoleEnum.DESIGNER));
ComponentInstanceAttribute 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));
+ 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));
+ final Resource vfWithInsatncePostUpdate = swallowException(
+ () -> (Resource) AtomicOperationUtils.getCompoenntObject(vf, UserRoleEnum.DESIGNER));
ComponentInstanceAttribute 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
index d9df79350b..86641eb2c7 100644
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/category/CatalogDataApiTest.java
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/category/CatalogDataApiTest.java
@@ -24,6 +24,7 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
+import org.apache.log4j.lf5.util.ResourceUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
@@ -48,6 +49,7 @@ import org.openecomp.sdc.ci.tests.utils.rest.CatalogRestUtils;
import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils;
import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
import org.testng.AssertJUnit;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
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
index a3ee121611..3b85c052a1 100644
--- 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
@@ -54,6 +54,7 @@ import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedCategoryAudit;
import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
import org.openecomp.sdc.ci.tests.utils.DbUtils;
+import org.openecomp.sdc.ci.tests.utils.Utils;
import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
import org.openecomp.sdc.ci.tests.utils.rest.CategoryRestUtils;
@@ -61,6 +62,7 @@ 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;
@@ -2235,6 +2237,18 @@ public class CategoriesTests extends CategoriesBaseTest {
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
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
index 7f30f8ca92..2f48f4fa1e 100644
--- 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
@@ -26,6 +26,7 @@ import static org.testng.AssertJUnit.assertNotNull;
import java.util.HashMap;
import java.util.Map;
+import org.apache.log4j.lf5.util.ResourceUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
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
index 7858b3259f..f6b6113b99 100644
--- 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
@@ -32,6 +32,9 @@ import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_RE
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;
@@ -44,6 +47,7 @@ import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedCategoryAudit;
import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
import org.openecomp.sdc.ci.tests.utils.DbUtils;
+import org.openecomp.sdc.ci.tests.utils.Utils;
import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
import org.openecomp.sdc.ci.tests.utils.rest.CategoryRestUtils;
import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
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
index dd96ebfc2f..dcc3172d59 100644
--- 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
@@ -47,6 +47,7 @@ import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedCategoryAudit;
import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
import org.openecomp.sdc.ci.tests.utils.DbUtils;
+import org.openecomp.sdc.ci.tests.utils.Utils;
import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
import org.openecomp.sdc.ci.tests.utils.rest.CategoryRestUtils;
import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/CRUDExternalAPI.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/CRUDExternalAPI.java
index 418e8f6dc8..7e8d5cf8cc 100644
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/CRUDExternalAPI.java
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/CRUDExternalAPI.java
@@ -22,7 +22,9 @@ package org.openecomp.sdc.ci.tests.execute.devCI;
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;
@@ -35,13 +37,19 @@ 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;
@@ -54,10 +62,11 @@ 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.ResourceDetailedAssetStructure;
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;
@@ -68,13 +77,13 @@ 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.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.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;
@@ -86,9 +95,13 @@ 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;
+
+import static java.util.Arrays.asList;
+
public class CRUDExternalAPI extends ComponentBaseTest {
private static Logger log = LoggerFactory.getLogger(CRUDExternalAPI.class.getName());
@@ -99,781 +112,3254 @@ public class CRUDExternalAPI extends ComponentBaseTest {
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 {
+ public void init() throws Exception{
AtomicOperationUtils.createDefaultConsumer(true);
}
-
- @Rule
+
+
+ @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}
+ };
+ }
+
- @DataProvider(name = "uploadArtifactOnVFViaExternalAPI")
+
+ // 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.CHECKIN, "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" } };
+ 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 {
- // Method passed variable
- // artifactType = "YANG_XML";
- // chosenLifeCycleState = LifeCycleStatesEnum.CHECKOUT;
+ @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("/asdc/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("/asdc/v1/catalog/services/%s/resourceInstances/%s/artifacts/%s", resourceDetails.getUUID(), resourceDetails.getComponentInstances().get(0).getNormalizedName(), artifactDefinition.getArtifactUUID());
+// expectedResourceAuditJavaObject.setRESOURCE_URL(resource_url);
+//
+// AuditValidationUtils.validateAuditDownloadExternalAPI(expectedResourceAuditJavaObject, auditAction, null, false);
+// } else {
+// expectedResourceAuditJavaObject.setResourceName(resourceDetails.getName());
+// String resource_url = String.format("/asdc/v1/catalog/services/%s/artifacts/%s", resourceDetails.getUUID(), artifactDefinition.getArtifactUUID());
+// 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);
- // String operationType = "Upload";
- UserRoleEnum creatorUser = UserRoleEnum.DESIGNER;
- String specificUser = "DESIGNER";
+ }
+
+ 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);
- Component resourceDetails = getComponentInTargetLifeCycleState("vf", creatorUser, chosenLifeCycleState);
+ }
+
+ // 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("/asdc/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;
+
+ }
- String resourceUUID = resourceDetails.getUUID();
- System.out.println("Resource UUID: " + resourceUUID);
+
+
+
+
+
+ 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);
- // get artifact data
- ArtifactReqDetails artifactReqDetails = ElementFactory.getArtifactByType("Abcd", artifactType, true);
+ }
+
+ // 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("/asdc/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},
+ };
+ }
+
- RestResponse restResponse = ArtifactRestUtils.externalAPIUploadArtifactOfTheAsset(resourceDetails,
- ElementFactory.getDefaultUser(UserRoleEnum.valueOf(specificUser.toUpperCase())), artifactReqDetails);
+ // 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);
- Integer responseCode = restResponse.getErrorCode();
- Integer expectedCode = 200;
- Assert.assertEquals(responseCode, expectedCode, "Response code is not correct.");
+ 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);
- // ArtifactDefinition artifactJavaObject =
- // ResponseParser.convertArtifactDefinitionResponseToJavaObject(restResponse.getResponse());
- // AuditingActionEnum action =
- // AuditingActionEnum.ARTIFACT_UPLOAD_BY_API;
- // ExpectedExternalAudit expectedExternalAudit =
- // ElementFactory.getDefaultExternalArtifactAuditSuccess(AssetTypeEnum.RESOURCES,
- // action, artifactJavaObject, resourceUUID);
- // AuditValidationUtils.validateExternalAudit(expectedExternalAudit,
- // AuditingActionEnum.ARTIFACT_UPLOAD_BY_API.getName(), null);
}
+
+
+
+
+
+ @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"},
+ };
+ }
+
- @DataProvider(name = "uploadArtifactOnServiceViaExternalAPI")
- public static Object[][] dataProviderUploadArtifactOnServiceViaExternalAPI() {
+
+ // 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[][] {
- // {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 {
- Component resourceDetails = getComponentInTargetLifeCycleState("service", UserRoleEnum.DESIGNER,
- chosenLifeCycleState);
- double resourceVersion = Double.parseDouble(resourceDetails.getVersion());
+ {ComponentTypeEnum.SERVICE, "OTHER", null},
+ {ComponentTypeEnum.RESOURCE, "OTHER", null},
+ {ComponentTypeEnum.RESOURCE_INSTANCE, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.VF},
+ };
+ }
+
- // get artifact data
- ArtifactReqDetails artifactReqDetails = ElementFactory.getArtifactByType("Abcd", artifactType, true);
- System.out.println("Service UUID: " + resourceDetails.getUUID());
- System.out.println("Service Version: " + resourceVersion);
- System.out.println("Service life cycle state: " + chosenLifeCycleState);
- System.out.println("Artifact Type: " + artifactReqDetails.getArtifactType());
+ // 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);
- RestResponse restResponse = ArtifactRestUtils.externalAPIUploadArtifactOfTheAsset(resourceDetails,
- ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails);
+ }
+
+ // 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);
- // Check response of external API
- Integer responseCode = restResponse.getErrorCode();
- Integer expectedCode = 200;
- Assert.assertEquals(responseCode, expectedCode, "Response code is not correct.");
-
- // TODO: Check auditing for upload opeartion
- // ArtifactDefinition artifactJavaObject =
- // ResponseParser.convertArtifactDefinitionResponseToJavaObject(restResponse.getResponse());
- // AuditingActionEnum action =
- // AuditingActionEnum.ARTIFACT_UPLOAD_BY_API;
- // ExpectedExternalAudit expectedExternalAudit =
- // ElementFactory.getDefaultExternalArtifactAuditSuccess(AssetTypeEnum.RESOURCES,
- // action, artifactJavaObject, resourceUUID);
- // AuditValidationUtils.validateExternalAudit(expectedExternalAudit,
- // AuditingActionEnum.ARTIFACT_UPLOAD_BY_API.getName(), null);
-
- // Check Service version (increase by one if not in checkout)
- if (!chosenLifeCycleState.equals(LifeCycleStatesEnum.CHECKOUT)) {
- double resourceNewVersion = Double.parseDouble(resourceDetails.getVersion());
-
- System.out.println(resourceVersion);
- System.out.println(resourceNewVersion);
}
}
+
+
+ // 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);
- @Test
- public void artifactOperationOnRIViaExternalAPI() throws Exception {
- // Method passed variable
- String operationType = "Upload";
- LifeCycleStatesEnum chosenLifeCycleState = LifeCycleStatesEnum.CHECKOUT;
- UserRoleEnum creatorUser = UserRoleEnum.DESIGNER;
- String specificUser = "DESIGNER";
- String artifactType = "OTHER";
+ }
+ }
+
+
+ // 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);
- Component resourceDetails = getComponentInTargetLifeCycleState("service", creatorUser, chosenLifeCycleState);
- Component resourceInstanceDetails = getComponentInTargetLifeCycleState("vf", creatorUser, chosenLifeCycleState);
- ComponentInstance componentResourceInstanceDetails = AtomicOperationUtils
- .addComponentInstanceToComponentContainer(resourceInstanceDetails, resourceDetails,
- UserRoleEnum.DESIGNER, true)
- .left().value();
+ }
+ }
+
+
+ // 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);
- String resourceUUID = resourceDetails.getUUID();
- System.out.println("Resource UUID: " + resourceUUID);
+ }
+ }
+
+
+ // 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);
- // get artifact data
- ArtifactReqDetails artifactReqDetails = ElementFactory.getArtifactByType("Abcd", artifactType, true);
+ }
+ }
+
+
+ // Update artifact with invalid description via external API - empty description
+ protected void updateArtifactWithInvalidDescriptionEmpty(Component component, User sdncModifierDetails, String artifactType,
+ ComponentInstance componentInstance) throws Exception {
+
+ ArtifactReqDetails artifactReqDetails = ElementFactory.getArtifactByType("ci", artifactType, true, true);
+ String artifactUUID = null;
+ Map<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("/asdc/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("/asdc/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"},
+ };
+ }
+
- if (operationType.toLowerCase().equals("upload")) {
- restResponse = ArtifactRestUtils.externalAPIUploadArtifactOfTheAsset(resourceDetails,
- ElementFactory.getDefaultUser(UserRoleEnum.valueOf(specificUser.toUpperCase())),
- artifactReqDetails);
- System.out.println("1234");
+ // 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},
+ };
+ }
+
- ArtifactDefinition artifactJavaObject = ResponseParser
- .convertArtifactDefinitionResponseToJavaObject(restResponse.getResponse());
- AuditingActionEnum action = AuditingActionEnum.ARTIFACT_UPLOAD_BY_API;
- ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditSuccess(
- AssetTypeEnum.RESOURCES, action, artifactJavaObject, resourceUUID);
- AuditValidationUtils.validateExternalAudit(expectedExternalAudit,
- AuditingActionEnum.ARTIFACT_UPLOAD_BY_API.getName(), null);
- }
-
- // @Test
- // public void artifactViaExternalAPI() throws Exception {
- // // Method passed variable
- // String operationType = "Upload";
- // String assetType = "vf";
- // LifeCycleStatesEnum chosenLifeCycleState = LifeCycleStatesEnum.CHECKOUT;
- // String componentInstanceAssetType = "vf";
- // LifeCycleStatesEnum componentInstanceChosenLifeCycleState =
- // LifeCycleStatesEnum.CHECKOUT;
- // UserRoleEnum creatorUser = UserRoleEnum.DESIGNER;
- // String specificUser = "DESIGNER";
- // String artifactType = "HEAT";
- //
- //
- // Component resourceDetails = null;
- // Component resourceInstanceDetails = null;
- // ComponentInstance componentResourceInstanceDetails = null;
- //
- // String resourceUUID = null;
- // String resourceType = null;
- // String resourceInstanceName = null;
- //
- // // Create resource & resource instance of requested type and state
- // if (assetType.toLowerCase().equals("vf")) {
- // resourceDetails = getComponentInTargetLifeCycleState("vf", creatorUser,
- // chosenLifeCycleState);
- // } else if (assetType.toLowerCase().equals("service")) {
- // resourceDetails = getComponentInTargetLifeCycleState("service",
- // creatorUser, chosenLifeCycleState);
- // } else if (assetType.toLowerCase().equals("ri")) {
- // resourceInstanceDetails = getComponentInTargetLifeCycleState("vf",
- // creatorUser, chosenLifeCycleState);
- // if(componentInstanceAssetType.toLowerCase().equals("vf")) {
- // resourceDetails = getComponentInTargetLifeCycleState("vf", creatorUser,
- // componentInstanceChosenLifeCycleState);
- // componentResourceInstanceDetails =
- // AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceInstanceDetails,
- // resourceDetails, UserRoleEnum.DESIGNER, true).left().value();
- // } else if (componentInstanceAssetType.toLowerCase().equals("service")) {
- // resourceDetails = getComponentInTargetLifeCycleState("service",
- // creatorUser, componentInstanceChosenLifeCycleState);
- // componentResourceInstanceDetails =
- // AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceInstanceDetails,
- // resourceDetails, UserRoleEnum.DESIGNER, true).left().value();
- // } else {
- // Assert.assertEquals(false, true, "Component instance asset type is
- // wrong.");
- // }
- // } else {
- // Assert.assertEquals(false, true, "Asset type is wrong.");
- // }
- //
- //
- // // print uuid & resource instance name
- // if (assetType.toLowerCase().equals("ri")) {
- // resourceUUID = resourceDetails.getUUID();
- // resourceInstanceName =
- // componentResourceInstanceDetails.getNormalizedName();
- //
- //
- // System.out.println("Resource UUID: " + resourceUUID);
- // System.out.println("Resource instance name: " + resourceInstanceName);
- // System.out.println("Resource type: " + resourceType);
- // } else {
- // resourceUUID = resourceDetails.getUUID();
- //
- // System.out.println("Resource UUID: " + resourceUUID);
- // System.out.println("Resource type: " + resourceType);
- // }
- //
- // // get artifact data
- // ArtifactReqDetails artifactReqDetails =
- // ElementFactory.getArtifactByType("Abcd", artifactType, true);
- //
- //// RestResponse restResponse;
- // // using rest external api
- //// if(operationType.toLowerCase().equals("upload")) {
- //// if (!assetType.toLowerCase().equals("ri")) {
- // RestResponse restResponse =
- // ArtifactRestUtils.externalAPIUploadArtifactOfTheAsset(resourceDetails,
- // ElementFactory.getDefaultUser(UserRoleEnum.valueOf(specificUser.toUpperCase())),
- // artifactReqDetails);
- // System.out.println("1234");
- //// } else {
- ////
- //// }
- //// } else {
- ////
- //// }
- //
- // ArtifactDefinition artifactJavaObject =
- // ResponseParser.convertArtifactDefinitionResponseToJavaObject(restResponse.getResponse());
- //// AuditingActionEnum action = AuditingActionEnum.ARTIFACT_UPLOAD_BY_API;
- // AuditingActionEnum action = AuditingActionEnum.ARTIFACT_UPLOAD_BY_API;
- // ExpectedExternalAudit expectedExternalAudit =
- // ElementFactory.getDefaultExternalArtifactAuditSuccess(AssetTypeEnum.RESOURCES,
- // action, artifactJavaObject, resourceUUID);
- // AuditValidationUtils.validateExternalAudit(expectedExternalAudit,
- // AuditingActionEnum.ARTIFACT_UPLOAD_BY_API.getName(), null);
- //
- //
- //
- //
- // }
- //
-
- @Test
- 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);
- // TODO
- Either<ArtifactDefinition, RestResponse> artifactDefinition = 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.validateAudit(expectedAssetListAudit,
- // AuditingActionEnum.GET_ASSET_METADATA.getName(), null);
-
- }
-
- public Component getComponentInTargetLifeCycleState(String componentType, UserRoleEnum creatorUser,
- LifeCycleStatesEnum targetLifeCycleState) throws Exception {
- Component resourceDetails = null;
+ // 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);
- if (componentType.toLowerCase().equals("vf")) {
- Either<Resource, RestResponse> createdResource = AtomicOperationUtils
- .createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.ROOT,
- ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, creatorUser, true);
- resourceDetails = createdResource.left().value();
- resourceDetails = AtomicOperationUtils
- .changeComponentState(resourceDetails, creatorUser, targetLifeCycleState, true).getLeft();
+ }
+
+
+ // 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 {
- Either<Service, RestResponse> createdResource = AtomicOperationUtils.createDefaultService(creatorUser,
- true);
- resourceDetails = createdResource.left().value();
- resourceDetails = AtomicOperationUtils
- .changeComponentState(resourceDetails, creatorUser, targetLifeCycleState, true).getLeft();
+ 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);
}
+
+
- return resourceDetails;
+
+ }
+
+ @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);
- // // External API - Download artifact for resource - negative test
- // @Test
- // public void k() 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 = "ArtifactDownload";
- //
- // 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("/asdc/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 componentInstanceUID = resourceDetailsVF1ins_01.getUniqueId();
- // String artifactUUID = heatArtifact.getArtifactUUID();
- //
- // System.out.println("Resource UUID: " + resourceUUID);
- // System.out.println("Component instance UID: " + componentInstanceUID);
- // System.out.println("Artifact UUID: " + artifactUUID);
- //
- // RestResponse restResponse =
- // ArtifactRestUtils.getComponentInstanceDeploymentArtifactExternalAPI(resourceUUID,
- // componentInstanceUID, 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 = "ArtifactDownload";
- //
- // 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("/asdc/v1/catalog/services/%s/resourceInstances/%s/artifacts/%s",
- // resourceUUID, componentInstanceUID, 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);
- // }
+ }
+
+ // 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("/asdc/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("/asdc/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("/asdc/v1/catalog/services/%s/resourceInstances/%s/artifacts/%s", resourceDetails.getUUID(), resourceDetails.getComponentInstances().get(0).getNormalizedName(), artifactDefinition.getArtifactUUID());
+// expectedResourceAuditJavaObject.setRESOURCE_URL(resource_url);
+//
+// AuditValidationUtils.validateAuditDownloadExternalAPI(expectedResourceAuditJavaObject, auditAction, null, false);
+// } else {
+// expectedResourceAuditJavaObject.setResourceName(resourceDetails.getName());
+// String resource_url = String.format("/asdc/v1/catalog/services/%s/artifacts/%s", resourceDetails.getUUID(), artifactDefinition.getArtifactUUID());
+// 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);
@@ -885,32 +3371,54 @@ public class CRUDExternalAPI extends ComponentBaseTest {
jsonBody.put("artifactLabel", "configure");
return gson.toJson(jsonBody);
}
+
+ protected ArtifactDefinition getArtifactDataFromJson(String content) {
- 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;
+ 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);
@@ -918,53 +3426,49 @@ public class CRUDExternalAPI extends ComponentBaseTest {
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);
+
+ 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);
+ String responseString = EntityUtils.toString(entity);
JSONObject responseMap = (JSONObject) jsonParser.parse(responseString);
- artifact.setEsId((String) responseMap.get("esId"));
+ 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 {
+
+ 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 {
+
+ 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);
@@ -975,10 +3479,10 @@ public class CRUDExternalAPI extends ComponentBaseTest {
StringEntity input = new StringEntity(jsonBody);
input.setContentType("application/json");
httppost.setEntity(input);
- log.debug("Executing request {}", httppost.getRequestLine());
+ 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");
@@ -986,21 +3490,20 @@ public class CRUDExternalAPI extends ComponentBaseTest {
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);
+ ArtifactUiDownloadData artifactUiDownloadData = mapper.readValue(artifactUiDownloadDataStr, ArtifactUiDownloadData.class);
return artifactUiDownloadData;
} catch (Exception e) {
e.printStackTrace();
@@ -1008,4 +3511,5 @@ public class CRUDExternalAPI extends ComponentBaseTest {
return null;
}
+
}
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
index 2c9d96d79d..dd078377db 100644
--- 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
@@ -20,15 +20,20 @@
package org.openecomp.sdc.ci.tests.execute.devCI;
+import static org.testng.AssertJUnit.assertTrue;
+
import org.junit.Rule;
import org.junit.rules.TestName;
import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.Service;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum;
import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
import org.openecomp.sdc.ci.tests.execute.imports.ImportCsarResourceTest;
@@ -37,6 +42,7 @@ import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.validation.CsarValidationUtils;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
@@ -54,14 +60,14 @@ public class ImportCsarUpdate extends ComponentBaseTest {
@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" },
-
+ 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" }
};
}
@@ -69,12 +75,13 @@ public class ImportCsarUpdate extends ComponentBaseTest {
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" }, };
+ { "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
@@ -100,25 +107,18 @@ public class ImportCsarUpdate extends ComponentBaseTest {
resourceDetails.setName("hardcodedName");
resourceDetails.setCsarUUID("importCsar_2Gartifacts");
resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
- RestResponse createResource = ResourceRestUtils.createResource(resourceDetails,
- ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ 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();
+ 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");
+ RestResponse copyRes = ImportCsarResourceTest.copyCsarRest(sdncModifierDetails, "updateImportCsar_2Gartifacts_topologyChanged.csar", "importCsar_2Gartifacts.csar");
resourceDetails.setCsarUUID("importCsar_2Gartifacts");
- createResource = ResourceRestUtils.createResource(resourceDetails,
- ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
BaseRestUtils.checkCreateResponse(createResource);
- Resource resourceSecondImport = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(),
- Resource.class);
+ Resource resourceSecondImport = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
// Validation Part
@@ -133,14 +133,10 @@ public class ImportCsarUpdate extends ComponentBaseTest {
resourceDetails.setName("hardcodedName");
resourceDetails.setCsarUUID("importCsar_2Gartifacts");
resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
- RestResponse createResource = ResourceRestUtils.createResource(resourceDetails,
- ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ 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();
+ 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);
@@ -148,11 +144,9 @@ public class ImportCsarUpdate extends ComponentBaseTest {
// ImportCsarResourceTest.copyCsarRest(sdncModifierDetails,"updateImportCsar_2Gartifacts_topologyChanged.csar","importCsar_2Gartifacts.csar");
resourceDetails.setCsarUUID("importCsar_2Gartifacts");
- createResource = ResourceRestUtils.createResource(resourceDetails,
- ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
BaseRestUtils.checkCreateResponse(createResource);
- Resource resourceSecondImport = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(),
- Resource.class);
+ Resource resourceSecondImport = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
// Validation Part
@@ -167,25 +161,20 @@ public class ImportCsarUpdate extends ComponentBaseTest {
resourceDetails.setName("hardcodedName");
resourceDetails.setCsarUUID("importCsar_2Gartifacts");
resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
- RestResponse createResource = ResourceRestUtils.createResource(resourceDetails,
- ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
BaseRestUtils.checkCreateResponse(createResource);
- Resource resourceFirstImport = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(),
- Resource.class);
+ 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");
+ RestResponse copyRes = ImportCsarResourceTest.copyCsarRest(sdncModifierDetails, "updateImportCsar_2Gartifacts_topologyChanged.csar", "importCsar_2Gartifacts.csar");
resourceDetails.setCsarUUID("importCsar_2Gartifacts");
- createResource = ResourceRestUtils.createResource(resourceDetails,
- ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
BaseRestUtils.checkCreateResponse(createResource);
- Resource resourceSecondImport = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(),
- Resource.class);
+ Resource resourceSecondImport = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
// Validation Part
@@ -200,25 +189,18 @@ public class ImportCsarUpdate extends ComponentBaseTest {
resourceDetails.setName("hardcodedName");
resourceDetails.setCsarUUID("importCsar_2Gartifacts");
resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
- RestResponse createResource = ResourceRestUtils.createResource(resourceDetails,
- ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ 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();
+ 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");
+ RestResponse copyRes = ImportCsarResourceTest.copyCsarRest(sdncModifierDetails, "updateImportCsar_2Gartifacts_topologyChanged.csar", "importCsar_2Gartifacts.csar");
resourceDetails.setCsarUUID("importCsar_2Gartifacts");
- createResource = ResourceRestUtils.createResource(resourceDetails,
- ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
BaseRestUtils.checkCreateResponse(createResource);
- Resource resourceSecondImport = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(),
- Resource.class);
+ Resource resourceSecondImport = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
// Validation Part
@@ -233,24 +215,18 @@ public class ImportCsarUpdate extends ComponentBaseTest {
resourceDetails.setName("hardcodedName");
resourceDetails.setCsarUUID("importCsar_2Gartifacts");
resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
- RestResponse createResource = ResourceRestUtils.createResource(resourceDetails,
- ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ 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();
+ 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");
+ RestResponse copyRes = ImportCsarResourceTest.copyCsarRest(sdncModifierDetails, "updateImportCsar_2Gartifacts_topologyChanged.csar", "importCsar_2Gartifacts.csar");
resourceDetails.setCsarUUID("importCsar_2Gartifacts");
- createResource = ResourceRestUtils.createResource(resourceDetails,
- ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
BaseRestUtils.checkCreateResponse(createResource);
- Resource resourceSecondImport = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(),
- Resource.class);
+ Resource resourceSecondImport = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
// Validation Part
@@ -265,26 +241,19 @@ public class ImportCsarUpdate extends ComponentBaseTest {
resourceDetails.setName("hardcodedName");
resourceDetails.setCsarUUID("importCsar_2Gartifacts");
resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
- RestResponse createResource = ResourceRestUtils.createResource(resourceDetails,
- ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ 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();
+ 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");
+ 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));
+ createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
BaseRestUtils.checkCreateResponse(createResource);
- Resource resourceSecondImport = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(),
- Resource.class);
+ Resource resourceSecondImport = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
// Validation Part
@@ -299,23 +268,17 @@ public class ImportCsarUpdate extends ComponentBaseTest {
resourceDetails.setName("hardcodedName");
resourceDetails.setCsarUUID("importCsar_2Gartifacts");
resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
- RestResponse createResource = ResourceRestUtils.createResource(resourceDetails,
- ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ 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();
+ 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");
+ 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));
+ createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
}
@@ -325,14 +288,10 @@ public class ImportCsarUpdate extends ComponentBaseTest {
ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
resourceDetails.setName("hardcodedName");
resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
- RestResponse createResource = ResourceRestUtils.createResource(resourceDetails,
- ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ 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();
+ 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 =
@@ -341,11 +300,9 @@ public class ImportCsarUpdate extends ComponentBaseTest {
resourceDetails2.setName("hardcodedName");
resourceDetails2.setCsarUUID("importCsar_2Gartifacts");
resourceDetails2.setResourceType(ResourceTypeEnum.VF.name());
- createResource = ResourceRestUtils.createResource(resourceDetails2,
- ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ createResource = ResourceRestUtils.createResource(resourceDetails2, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
BaseRestUtils.checkCreateResponse(createResource);
- Resource resourceSecondImport = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(),
- Resource.class);
+ Resource resourceSecondImport = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
// Validation Part
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
index 49e5950db5..5ed71e53b0 100644
--- 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
@@ -25,11 +25,16 @@ import static org.testng.AssertJUnit.assertTrue;
import org.junit.Rule;
import org.junit.rules.TestName;
import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.Service;
import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils;
import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
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
new file mode 100644
index 0000000000..2ac31183d3
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/OpsRejectDistribution.java
@@ -0,0 +1,68 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 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.assertEquals;
+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.be.utils.CommonBeUtils;
+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.AfterTest;
+import org.testng.annotations.BeforeTest;
+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
new file mode 100644
index 0000000000..af4b9380fd
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/SearchFilterCategoryExternalAPI.java
@@ -0,0 +1,344 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.devCI;
+
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.util.Base64.Decoder;
+
+import javax.json.Json;
+
+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.apache.cassandra.cli.CliParser.operator_return;
+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.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.dao.graph.datatype.ActionEnum;
+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.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.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.ResourceDetailedAssetStructure;
+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.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.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.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.CategoryRestUtils;
+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.DistributionValidationUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils;
+import org.openecomp.sdc.common.api.ApplicationErrorCodesEnum;
+import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
+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.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 org.openecomp.sdc.utils.Pair;
+import com.google.common.base.CaseFormat;
+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.relevantcodes.extentreports.LogStatus;
+
+import fj.P;
+import fj.data.Either;
+import it.unimi.dsi.fastutil.bytes.ByteSortedSets.SynchronizedSortedSet;
+
+import static java.util.Arrays.asList;
+
+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
index bb86f8f336..3264efb280 100644
--- 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
@@ -20,6 +20,8 @@
package org.openecomp.sdc.ci.tests.execute.devCI;
+import static org.testng.AssertJUnit.assertEquals;
+
import java.util.HashMap;
import java.util.Map;
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
new file mode 100644
index 0000000000..955b501db1
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/VFCMTExternalAPI.java
@@ -0,0 +1,390 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 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.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.json.simple.parser.JSONParser;
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.datatypes.enums.AssetTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.config.Config;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceAssetStructure;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceExternalReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.SearchCriteriaEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedResourceAuditJavaObject;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.AssetRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtilsExternalAPI;
+import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils;
+import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.Assert;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+import com.google.common.util.concurrent.ListeningExecutorService;
+import com.google.gson.Gson;
+import com.google.gson.JsonArray;
+import com.google.gson.JsonElement;
+
+public class VFCMTExternalAPI extends ComponentBaseTest {
+
+ private static Logger log = LoggerFactory.getLogger(CRUDExternalAPI.class.getName());
+ protected static final String UPLOAD_ARTIFACT_PAYLOAD = "UHVUVFktVXNlci1LZXktRmlsZS0yOiBzc2gtcnNhDQpFbmNyeXB0aW9uOiBhZXMyNTYtY2JjDQpDb21tZW5wOA0K";
+ protected static final String UPLOAD_ARTIFACT_NAME = "TLV_prv.ppk";
+
+ protected Config config = Config.instance();
+ protected String contentTypeHeaderData = "application/json";
+ protected String acceptHeaderDate = "application/json";
+
+
+
+ protected Gson gson = new Gson();
+ protected JSONParser jsonParser = new JSONParser();
+
+
+ protected String serviceVersion;
+ protected ResourceReqDetails resourceDetails;
+ protected User sdncUserDetails;
+ protected ServiceReqDetails serviceDetails;
+
+
+ @BeforeMethod
+ public 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
new file mode 100644
index 0000000000..08e7539b28
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/ValidateConformanceLevel.java
@@ -0,0 +1,78 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.devCI;
+
+import static org.testng.Assert.assertEquals;
+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.be.utils.CommonBeUtils;
+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.AfterTest;
+import org.testng.annotations.BeforeTest;
+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.getUniqueId(), user.getUserId());
+ String 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
new file mode 100644
index 0000000000..be32d544ec
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/test1.java
@@ -0,0 +1,102 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.devCI;
+
+import static org.testng.AssertJUnit.assertNotNull;
+
+import java.io.IOException;
+import java.text.ParseException;
+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.DistributionUtils;
+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 org.openecomp.sdc.utils.DistributionStatusEnum;
+
+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/DistributionDownloadArtifactTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/distribution/DistributionDownloadArtifactTest.java
index 6cf5626e7e..255dfd9de2 100644
--- 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
@@ -37,6 +37,7 @@ 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;
@@ -45,13 +46,16 @@ 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;
@@ -103,10 +107,6 @@ public class DistributionDownloadArtifactTest extends ComponentBaseTest {
// serviceBaseVersion = "0.1";
// designerUser = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
// adminUser = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
- //// resourceDetails =
- // ElementFactory.getDefaultResource("tosca.nodes.newnotgenericresource4testNew",
- // NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS,
- // "jh0003");
// resourceDetails =
// ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC,
// NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS,
@@ -125,10 +125,6 @@ public class DistributionDownloadArtifactTest extends ComponentBaseTest {
serviceBaseVersion = "0.1";
designerUser = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
adminUser = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
- // resourceDetails =
- // ElementFactory.getDefaultResource("tosca.nodes.newnotgenericresource4testNew",
- // NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS,
- // "jh0003");
resourceDetails = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC,
NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, adminUser);
serviceDetails = ElementFactory.getDefaultService();
@@ -538,5 +534,63 @@ public class DistributionDownloadArtifactTest extends ComponentBaseTest {
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.calculateMD5ByByteArray(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
index 3325227ebc..80b70d675e 100644
--- 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
@@ -114,12 +114,22 @@ public class DownloadArtifactsTest extends ComponentBaseTest {
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());
+ 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
@@ -147,21 +157,33 @@ public class DownloadArtifactsTest extends ComponentBaseTest {
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);
+ 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.getNormalizedName(), artifact.getArtifactUUID());
+ 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");
@@ -174,14 +196,16 @@ public class DownloadArtifactsTest extends ComponentBaseTest {
sendAuthorizationRequest();
HttpRequest http = new HttpRequest();
RestResponse response = http.httpSendGet(url, headersMap);
- if (response.getErrorCode() != 200 && response.getResponse().getBytes() == null && response.getResponse().getBytes().length == 0) {
+ 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 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");
@@ -194,7 +218,8 @@ public class DownloadArtifactsTest extends ComponentBaseTest {
sendAuthorizationRequest();
HttpRequest http = new HttpRequest();
RestResponse response = http.httpSendGet(url, headersMap);
- if (response.getErrorCode() != 200 && response.getResponse().getBytes() == null && response.getResponse().getBytes().length == 0) {
+ if (response.getErrorCode() != 200 && response.getResponse().getBytes() == null
+ && response.getResponse().getBytes().length == 0) {
return null;
}
return response;
@@ -213,7 +238,9 @@ public class DownloadArtifactsTest extends ComponentBaseTest {
}
HttpRequest http = new HttpRequest();
- RestResponse response = http.httpSendPost(url, "{\"consumerName\":\"test\",\"consumerPassword\":\"0a0dc557c3bf594b1a48030e3e99227580168b21f44e285c69740b8d5b13e33b\",\"consumerSalt\":\"2a1f887d607d4515d4066fe0f5452a50\"}", headersMap);
+ RestResponse response = http.httpSendPost(url,
+ "{\"consumerName\":\"test\",\"consumerPassword\":\"0a0dc557c3bf594b1a48030e3e99227580168b21f44e285c69740b8d5b13e33b\",\"consumerSalt\":\"2a1f887d607d4515d4066fe0f5452a50\"}",
+ headersMap);
if (response.getErrorCode() != 201) {
return null;
}
@@ -223,8 +250,10 @@ public class DownloadArtifactsTest extends ComponentBaseTest {
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);
+ 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);
@@ -233,15 +262,19 @@ public class DownloadArtifactsTest extends ComponentBaseTest {
}
private void createTreeCheckedinVFInstances() throws Exception {
- RestResponse createFirstVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01, sdncDesignerDetails);
+ RestResponse createFirstVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01,
+ sdncDesignerDetails);
ResourceRestUtils.checkCreateResponse(createFirstVFInstResp);
- RestResponse createSecondVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_02, sdncDesignerDetails);
+ RestResponse createSecondVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_02,
+ sdncDesignerDetails);
ResourceRestUtils.checkCreateResponse(createSecondVFInstResp);
- RestResponse createThirdVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_03, sdncDesignerDetails);
+ RestResponse createThirdVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_03,
+ sdncDesignerDetails);
ResourceRestUtils.checkCreateResponse(createThirdVFInstResp);
}
- private Component getComponentAndValidateRIs(ComponentReqDetails componentDetails, int numberOfRIs, int numberOfRelations) throws IOException, Exception {
+ private Component getComponentAndValidateRIs(ComponentReqDetails componentDetails, int numberOfRIs,
+ int numberOfRelations) throws IOException, Exception {
RestResponse getResponse = null;
Component component = null;
@@ -258,42 +291,56 @@ public class DownloadArtifactsTest extends ComponentBaseTest {
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;
+ 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);
+ 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 {
+ 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 {
+ 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 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 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);
+ 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 userId, LifeCycleStatesEnum lifeCycleStates) throws Exception {
- RestResponse response = LifecycleRestUtils.changeResourceState(resourceDetails, userId, lifeCycleStates);
+ private void changeResourceLifecycleState(ResourceReqDetails resourceDetails, String userUserId,
+ LifeCycleStatesEnum lifeCycleStates) throws Exception {
+ RestResponse response = LifecycleRestUtils.changeResourceState(resourceDetails, userUserId, lifeCycleStates);
LifecycleRestUtils.checkLCS_Response(response);
}
@@ -324,7 +371,7 @@ public class DownloadArtifactsTest extends ComponentBaseTest {
private void importVfWithArtifacts(ImportReqDetails resourceDetailsVF_01) throws Exception {
String payloadName = "VF_RI2_G4_withArtifacts.csar";
- Path path = Paths.get(rootPath + "/src/test/resources/CI/csars/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);
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
new file mode 100644
index 0000000000..510d8076be
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/externalapi/LifeCycleExternalAPI.java
@@ -0,0 +1,270 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 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
new file mode 100644
index 0000000000..157f3157b8
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/externalapi/UserAPIs.java
@@ -0,0 +1,473 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 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.*;
+
+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.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.rest.UserRestUtils;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+import com.google.gson.Gson;
+import com.google.gson.reflect.TypeToken;
+
+import fj.data.Either;
+
+import org.testng.Assert;
+
+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
index 83a50baeeb..bc114e22c5 100644
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/general/BasicHttpAuthenticationTest.java
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/general/BasicHttpAuthenticationTest.java
@@ -52,6 +52,7 @@ import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedAuthenticationAudit
import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum;
import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
import org.openecomp.sdc.ci.tests.utils.DbUtils;
+import org.openecomp.sdc.ci.tests.utils.Utils;
import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils;
import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
import org.openecomp.sdc.ci.tests.utils.rest.ArtifactRestUtils;
@@ -120,24 +121,30 @@ public class BasicHttpAuthenticationTest extends ComponentBaseTest {
public void init() throws Exception {
sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
- Resource resourceObject = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VFC, UserRoleEnum.DESIGNER, true).left().value();
+ 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);
+ 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);
+ 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);
+ 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 =
@@ -152,13 +159,18 @@ public class BasicHttpAuthenticationTest extends ComponentBaseTest {
// 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("/asdc/".length(), expectedDownloadResourceUrl.length());
+ 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("/asdc/".length(),
+ expectedDownloadResourceUrl.length());
- expectedDownloadServiceUrl = String.format(Urls.DISTRIB_DOWNLOAD_SERVICE_ARTIFACT_RELATIVE_URL, ValidationUtils.convertToSystemName(serviceDetails.getName()), serviceDetails.getVersion(),
+ expectedDownloadServiceUrl = String.format(Urls.DISTRIB_DOWNLOAD_SERVICE_ARTIFACT_RELATIVE_URL,
+ ValidationUtils.convertToSystemName(serviceDetails.getName()), serviceDetails.getVersion(),
ValidationUtils.normalizeFileName(deploymentArtifact.getArtifactName()));
- expectedDownloadServiceUrl = expectedDownloadServiceUrl.substring("/asdc/".length(), expectedDownloadServiceUrl.length());
+ expectedDownloadServiceUrl = expectedDownloadServiceUrl.substring("/asdc/".length(),
+ expectedDownloadServiceUrl.length());
sdncAdminUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
consumerDataDefinition = createConsumer();
@@ -185,19 +197,24 @@ public class BasicHttpAuthenticationTest extends ComponentBaseTest {
// 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());
+ 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 {
+ protected void validateAuditAuthentication(String userName, String AuthStatus, ComponentTypeEnum compType)
+ throws Exception {
if (compType.equals(ComponentTypeEnum.RESOURCE)) {
- expectedAuthenticationAudit = new ExpectedAuthenticationAudit(expectedDownloadResourceUrl, userName, auditAction, AuthStatus);
+ expectedAuthenticationAudit = new ExpectedAuthenticationAudit(expectedDownloadResourceUrl, userName,
+ auditAction, AuthStatus);
} else {
- expectedAuthenticationAudit = new ExpectedAuthenticationAudit(expectedDownloadServiceUrl, userName, auditAction, AuthStatus);
+ expectedAuthenticationAudit = new ExpectedAuthenticationAudit(expectedDownloadServiceUrl, userName,
+ auditAction, AuthStatus);
}
AuditValidationUtils.validateAuthenticationAudit(expectedAuthenticationAudit);
}
@@ -213,9 +230,11 @@ public class BasicHttpAuthenticationTest extends ComponentBaseTest {
@Test
public void sendAuthenticatedRequestWithoutHeadersTest() throws Exception, Exception {
- RestResponse restResponse = ArtifactRestUtils.downloadServiceArtifact(serviceDetails, deploymentArtifact, sdncUserDetails, new HashMap<String, String>());
+ 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());
+ 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());
@@ -228,9 +247,11 @@ public class BasicHttpAuthenticationTest extends ComponentBaseTest {
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);
+ 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());
+ 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);
@@ -240,9 +261,11 @@ public class BasicHttpAuthenticationTest extends ComponentBaseTest {
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);
+ 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());
+ 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);
@@ -252,9 +275,11 @@ public class BasicHttpAuthenticationTest extends ComponentBaseTest {
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);
+ 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());
+ 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);
@@ -264,9 +289,11 @@ public class BasicHttpAuthenticationTest extends ComponentBaseTest {
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);
+ 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());
+ 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);
@@ -279,7 +306,8 @@ public class BasicHttpAuthenticationTest extends ComponentBaseTest {
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);
+ 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()));
@@ -289,11 +317,14 @@ public class BasicHttpAuthenticationTest extends ComponentBaseTest {
@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);
+ 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());
+ RestResponse secondRestResponse = ArtifactRestUtils.downloadServiceArtifact(serviceDetails, deploymentArtifact,
+ sdncUserDetails, authorizationHeader);
+ assertEquals("Check response code after second download artifact", 200,
+ secondRestResponse.getErrorCode().intValue());
}
@Test(enabled = false)
@@ -309,8 +340,10 @@ public class BasicHttpAuthenticationTest extends ComponentBaseTest {
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);
+ 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);
@@ -340,8 +373,10 @@ public class BasicHttpAuthenticationTest extends ComponentBaseTest {
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);
+ 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);
@@ -354,7 +389,8 @@ public class BasicHttpAuthenticationTest extends ComponentBaseTest {
@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);
+ RestResponse restResponse = ArtifactRestUtils.downloadServiceArtifact(serviceDetails, deploymentArtifact,
+ sdncUserDetails, authorizationHeader);
assertEquals("Check response code after download artifact", 200, restResponse.getErrorCode().intValue());
}
@@ -369,7 +405,8 @@ public class BasicHttpAuthenticationTest extends ComponentBaseTest {
@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);
+ RestResponse restResponse = ArtifactRestUtils.downloadServiceArtifact(serviceDetails, deploymentArtifact,
+ sdncUserDetails, authorizationHeader);
assertEquals("Check response code after download artifact", 200, restResponse.getErrorCode().intValue());
}
@@ -383,7 +420,8 @@ public class BasicHttpAuthenticationTest extends ComponentBaseTest {
// 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);
+ RestResponse restResponse = ArtifactRestUtils.downloadServiceArtifact(serviceDetails, deploymentArtifact,
+ sdncUserDetails, authorizationHeader);
assertEquals("Check response code after download artifact", 200, restResponse.getErrorCode().intValue());
}
@@ -396,7 +434,8 @@ public class BasicHttpAuthenticationTest extends ComponentBaseTest {
// @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);
+ 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/ManageEcompConsumerCredentials.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/general/ManageEcompConsumerCredentials.java
index 9e1b151c49..1551c99e66 100644
--- 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
@@ -35,6 +35,7 @@ import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedEcomConsumerAudit;
import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
import org.openecomp.sdc.ci.tests.utils.DbUtils;
+import org.openecomp.sdc.ci.tests.utils.Utils;
import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
import org.openecomp.sdc.ci.tests.utils.rest.ConsumerRestUtils;
import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils;
@@ -191,29 +192,49 @@ public class ManageEcompConsumerCredentials extends ComponentBaseTest {
}
@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());
+ 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());
+ 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);
+ 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());
+ 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());
+ 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);
+ AuditValidationUtils.createEcompConsumerAuditFailure(ADD_ECOMP_USER_CREDENTIALS, consumerDataDefinition,
+ sdncTesterUserDetails, ActionStatus.RESTRICTED_OPERATION);
}
@Test
- public void createEcompCredentialsByOps() throws Exception { // HttpCspUserId header contains OPS UserId
+ 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());
@@ -227,7 +248,13 @@ public class ManageEcompConsumerCredentials extends ComponentBaseTest {
}
@Test
- public void createEcompCredentialsByGovernor() throws Exception { // HttpCspUserId header contains Governor UserId Create Consumer
+ 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,
@@ -751,11 +778,11 @@ public class ManageEcompConsumerCredentials extends ComponentBaseTest {
ADD_ECOMP_USER_CREDENTIALS);
}
- // USER_ID (USER_ID is taken from USER_ID header)
+ // UserId (UserId is taken from USER_ID header)
@Test
public void createEcompCredentialsHttpCspUserIdIsEmpty() throws Exception {
- // USER_ID is taken from USER_ID header
+ // UserId is taken from USER_ID header
sdncAdminUserDetails.setUserId("");
RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition,
sdncAdminUserDetails);
@@ -775,7 +802,12 @@ public class ManageEcompConsumerCredentials extends ComponentBaseTest {
}
@Test
- public void createEcompCredentialsHttpCspUserIdIsNull() throws Exception { // USER_ID is taken from USER_ID header
+ public void createEcompCredentialsHttpCspUserIdIsNull() throws Exception { // UserId
+ // is
+ // taken
+ // from
+ // USER_ID
+ // header
sdncAdminUserDetails.setUserId(null);
RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition,
sdncAdminUserDetails);
@@ -813,10 +845,10 @@ public class ManageEcompConsumerCredentials extends ComponentBaseTest {
ADD_ECOMP_USER_CREDENTIALS);
}
- // add USER_ID in json body
+ // add UserId in json body
@Test
public void createEcompCredentiaJsonBodyContainLastModfierAtuid() throws Exception {
- // Add USER_ID (not admin) to json - we will ignore and create the user
+ // 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");
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/CsarUtilsTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/CsarUtilsTest.java
index 7aae0e9a4e..e99ecc7303 100644
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/CsarUtilsTest.java
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/CsarUtilsTest.java
@@ -57,96 +57,125 @@ 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.uploadArtifactByType(ArtifactTypeEnum.VENDOR_LICENSE, resourceVF, UserRoleEnum.DESIGNER,
+ true, true);
+ resourceVF = (Resource) AtomicOperationUtils
+ .changeComponentState(resourceVF, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+
AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceVF, service, UserRoleEnum.DESIGNER, true);
-
+
service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
-
+
User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
-
+
byte[] downloadCSAR = downloadCSAR(sdncModifierDetails, service);
-
+
csarBasicValidation(service, downloadCSAR);
}
-
+
@Test(enabled = true)
public void createResourceCsarBasicTest() throws Exception {
Resource resourceVF = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value();
- resourceVF = (Resource) AtomicOperationUtils.changeComponentState(resourceVF, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+ resourceVF = (Resource) AtomicOperationUtils
+ .changeComponentState(resourceVF, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
-
+
byte[] downloadCSAR = downloadCSAR(sdncModifierDetails, resourceVF);
-
+
csarBasicValidation(resourceVF, downloadCSAR);
}
-
+
@Test(enabled = true)
public void createServiceCsarInclDeploymentArtTest() throws Exception {
-
+
Service service = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value();
Resource resourceVF1 = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value();
Resource resourceVF2 = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value();
-
- resourceVF1 = (Resource) AtomicOperationUtils.changeComponentState(resourceVF1, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
-
- resourceVF2 = (Resource) AtomicOperationUtils.changeComponentState(resourceVF2, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
-
+
+ resourceVF1 = (Resource) AtomicOperationUtils
+ .changeComponentState(resourceVF1, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+
+ resourceVF2 = (Resource) AtomicOperationUtils
+ .changeComponentState(resourceVF2, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+
AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceVF1, service, UserRoleEnum.DESIGNER, true);
AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceVF2, service, UserRoleEnum.DESIGNER, true);
-
+
AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.YANG_XML, service, UserRoleEnum.DESIGNER, true, true);
-
+
service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
-
+
User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
-
+
byte[] downloadCSAR = downloadCSAR(sdncModifierDetails, service);
-
+
csarBasicValidation(service, downloadCSAR);
-
- validateServiceCsar(resourceVF1, resourceVF2, service, downloadCSAR, 3, 5, 1);
+
+ validateServiceCsar(resourceVF1, resourceVF2, service, downloadCSAR, 3, 3, 1, 0);
}
-
- @Test(enabled = true)
+
+ @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();
+
+ 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);
- //TODO when feature is integrated to OS should modify expected deployment artifacts in csar Artifacts folder to (0,1,1)
- validateVFCsar(resourceVF1, downloadCSAR, 1, 0, 0, 0);
+
+ 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);
+ }
+
private void csarBasicValidation(Component mainComponent, byte[] downloadCSAR) {
- try (ByteArrayInputStream ins = new ByteArrayInputStream(downloadCSAR); ZipInputStream zip = new ZipInputStream(ins);) {
+ try (ByteArrayInputStream ins = new ByteArrayInputStream(downloadCSAR);
+ ZipInputStream zip = new ZipInputStream(ins);) {
String resourceYaml = null;
byte[] buffer = new byte[1024];
@@ -157,16 +186,15 @@ public class CsarUtilsTest extends ComponentBaseTest {
while ((len = zip.read(buffer)) > 0) {
sb.append(new String(buffer, 0, len));
}
+ assertTrue(nextEntry.getName().equals("csar.meta"));
- assertTrue(nextEntry.getName().equals("TOSCA-Metadata/TOSCA.meta"));
+ readNextEntry(sb, len, buffer, zip);
- sb.setLength(0);
nextEntry = zip.getNextEntry();
-
- while ((len = zip.read(buffer)) > 0) {
- sb.append(new String(buffer, 0, len));
- }
-
+ assertTrue(nextEntry.getName().equals("TOSCA-Metadata/TOSCA.meta"));
+
+ readNextEntry(sb, len, buffer, zip);
+ nextEntry = zip.getNextEntry();
resourceYaml = sb.toString();
YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
@@ -181,16 +209,22 @@ public class CsarUtilsTest extends ComponentBaseTest {
e.printStackTrace();
}
}
-
- private void validateServiceCsar(Component certifiedVFC1, Component certifiedVFC2, Service fetchedService, byte[] resultByte, int toscaEntryIndexToPass, int generatorEntryIndexToPass, int deploymentArtifactIndexToPass) {
-
+
+ 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);) {
+ /*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();
@@ -208,6 +242,7 @@ public class CsarUtilsTest extends ComponentBaseTest {
int toscaEntryIndex = 0;
int generatorEntryIndex = 0;
int deploymentArtifactIndex = 0;
+ int informationalArtifactIndex = 0;
String fileName = null;
ArtifactDefinition artifactDefinition;
Component componentToValidate = null;
@@ -232,18 +267,18 @@ public class CsarUtilsTest extends ComponentBaseTest {
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);
@@ -253,7 +288,7 @@ public class CsarUtilsTest extends ComponentBaseTest {
if (entryName.contains(vfc2FileName)) {
componentToValidate = certifiedVFC2;
fileName = "Definitions/" + vfc2FileName;
-
+
assertEquals("Validate entry Name", (fileName), nextEntry.getName());
assertTrue(yamlToObjectConverter.isValidYaml(resourceYaml.getBytes()));
validateContent(resourceYaml, componentToValidate);
@@ -261,38 +296,52 @@ public class CsarUtilsTest extends ComponentBaseTest {
continue;
}
- if (entryName.contains(".xml") && !entryName.startsWith("Artifacts/AAI")) {
+ 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.startsWith("Artifacts/AAI")) {
- ++generatorEntryIndex;
+
+ 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 generated Deployment artifacts", deploymentArtifactIndexToPass, deploymentArtifactIndex);
-
+ 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 heatEnvDeploymentArtifactIndexToPass) {
-
+
+ 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);) {
+ /*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();
@@ -303,14 +352,23 @@ public class CsarUtilsTest extends ComponentBaseTest {
sb.append(new String(buffer, 0, len));
}
- assertTrue(nextEntry.getName().equals("TOSCA-Metadata/TOSCA.meta"));
+ assertTrue(nextEntry.getName().equals("csar.meta"));
+ readNextEntry(sb, len, buffer, zip);
+ nextEntry = zip.getNextEntry();
+ assertTrue(nextEntry.getName().equals("TOSCA-Metadata/TOSCA.meta"));
+
+ readNextEntry(sb, len, buffer, zip);
+
YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
int toscaEntryIndex = 0;
- int ymlEntryIndex = 0;
- int xmlArtifactsIndex = 0;
- int heatEnvDeploymentArtifactIndex = 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;
@@ -319,11 +377,8 @@ public class CsarUtilsTest extends ComponentBaseTest {
String vfFileName = artifactDefinition.getArtifactName();
while ((nextEntry = zip.getNextEntry()) != null) {
- sb.setLength(0);
-
- while ((len = zip.read(buffer)) > 0) {
- sb.append(new String(buffer, 0, len));
- }
+
+ readNextEntry(sb, len, buffer, zip);
String entryName = nextEntry.getName();
@@ -331,7 +386,7 @@ public class CsarUtilsTest extends ComponentBaseTest {
if (entryName.contains(vfFileName)) {
componentToValidate = certifiedVF;
fileName = "Definitions/" + vfFileName;
-
+
assertEquals("Validate entry Name", (fileName), nextEntry.getName());
assertTrue(yamlToObjectConverter.isValidYaml(resourceYaml.getBytes()));
validateContent(resourceYaml, componentToValidate);
@@ -339,35 +394,72 @@ public class CsarUtilsTest extends ComponentBaseTest {
continue;
}
- if (entryName.contains(".xml") && entryName.startsWith("Artifacts/")) {
- ++xmlArtifactsIndex;
- 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.startsWith("Artifacts/")) {
- ++heatEnvDeploymentArtifactIndex;
+ 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(".yml") && entryName.startsWith("Artifacts/")) {
- ++ymlEntryIndex;
+ if(entryName.contains("Definitions/")) {
+ if(isImportsFileValidation(entryName))
continue;
}
-
+
assertTrue("Unexpected entry: " + entryName, false);
}
+
+ //Definitions folder
assertEquals("Validate amount of entries", toscaEntryIndexToPass, toscaEntryIndex);
- assertEquals("Validate amount of YAML artifacts", ymlDeploymentArtifactIndexToPass, ymlEntryIndex);
- assertEquals("Validate amount of generated XML artifacts", xmlDeploymentArtifactIndexToPass, xmlArtifactsIndex);
- assertEquals("Validate amount of generated HEAT ENV artifacts", heatEnvDeploymentArtifactIndexToPass, heatEnvDeploymentArtifactIndex);
-
+
+ //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();
@@ -395,30 +487,34 @@ public class CsarUtilsTest extends ComponentBaseTest {
if (component.getComponentType().equals(ComponentTypeEnum.SERVICE)) {
assertEquals("Validate component type", component.getComponentType().getValue(), type);
} else {
- assertEquals("Validate component type", ((Resource) component).getResourceType(), ResourceTypeEnum.valueOf(type));
+ assertEquals("Validate component type", ((Resource) component).getResourceType(),
+ ResourceTypeEnum.valueOf(type));
}
}
-
+
private byte[] downloadCSAR(User sdncModifierDetails, Component createdComponent) throws Exception {
String artifactUniqeId = createdComponent.getToscaArtifacts().get("assettoscacsar").getUniqueId();
RestResponse getCsarResponse = null;
-
+
switch (createdComponent.getComponentType()) {
case RESOURCE:
- getCsarResponse = ArtifactRestUtils.downloadResourceArtifactInternalApi(createdComponent.getUniqueId(), sdncModifierDetails, artifactUniqeId);
- break;
+ getCsarResponse = ArtifactRestUtils.downloadResourceArtifactInternalApi(createdComponent.getUniqueId(),
+ sdncModifierDetails, artifactUniqeId);
+ break;
case SERVICE:
- getCsarResponse = ArtifactRestUtils.downloadServiceArtifactInternalApi(createdComponent.getUniqueId(), sdncModifierDetails, artifactUniqeId);
+ getCsarResponse = ArtifactRestUtils.downloadServiceArtifactInternalApi(createdComponent.getUniqueId(),
+ sdncModifierDetails, artifactUniqeId);
break;
default:
break;
}
-
+
assertNotNull(getCsarResponse);
BaseRestUtils.checkSuccess(getCsarResponse);
- ArtifactUiDownloadData artifactUiDownloadData = ResponseParser.parseToObject(getCsarResponse.getResponse(), ArtifactUiDownloadData.class);
+ ArtifactUiDownloadData artifactUiDownloadData = ResponseParser.parseToObject(getCsarResponse.getResponse(),
+ ArtifactUiDownloadData.class);
assertNotNull(artifactUiDownloadData);
@@ -427,4 +523,48 @@ public class CsarUtilsTest extends ComponentBaseTest {
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
index e4360329ad..192f6759c3 100644
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ExportToscaTest.java
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ExportToscaTest.java
@@ -31,130 +31,306 @@ 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.stream.Collectors;
import java.util.Optional;
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.ComponentInstInputsMap;
import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.ComponentInstanceInput;
import org.openecomp.sdc.be.model.ComponentInstanceProperty;
import org.openecomp.sdc.be.model.GroupDefinition;
import org.openecomp.sdc.be.model.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.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.ElementFactory;
import org.openecomp.sdc.ci.tests.utils.rest.ArtifactRestUtils;
import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ComponentInstanceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.InputsRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils;
import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.BaseValidationUtils;
import org.openecomp.sdc.common.api.Constants;
+import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.yaml.snakeyaml.Yaml;
import com.google.gson.Gson;
import com.google.gson.JsonParser;
+import com.google.gson.reflect.TypeToken;
public class ExportToscaTest extends ComponentBaseTest {
@Rule
public static TestName name = new TestName();
+ 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());
}
- @Test(enabled = true)
- public void exportVfModuleTest() throws Exception {
+ @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, "VSPPackage");
+ Resource createdResource = createVfFromCSAR(sdncModifierDetails, csarname);
- Map<String, Object> load = downloadAndParseToscaTemplate(sdncModifierDetails, createdResource);
+ 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");
- assertNotNull(groups);
- List<GroupDefinition> groupsOrigin = createdResource.getGroups();
+ if (includeGroups) {
+ assertNotNull(vfModulesInRes);
+ assertNotNull(groups);
- 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);
+ assertEquals("Validate count of vf module instanses", vfModulesInRes.size(), groups.size());
- Map<String, Object> metadata = (Map<String, Object>) groupTosca.get("metadata");
- assertNotNull(metadata);
+ vfModulesInRes.forEach(modInRes -> {
+ validateVfModuleVsInstance(normalizedName, groups, modInRes);
+ });
+ }else{
+ assertNull(groups);
+ }
+ }
- 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);
-
- String vf_module_type = (String) properties.get("vf_module_type");
- List<GroupProperty> props = group.getProperties();
- for (GroupProperty prop : props) {
- if (prop.getName().equals(Constants.IS_BASE)) {
- String value = prop.getValue() == null ? prop.getDefaultValue() : prop.getValue();
- boolean bvalue = Boolean.parseBoolean(value);
- if (bvalue) {
- assertEquals("Validate vf_module_type", "Base", vf_module_type);
- } else {
- assertEquals("Validate vf_module_type", "Expansion", vf_module_type);
- }
- break;
- }
+ 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);
}
- String vf_module_description = (String) properties.get("vf_module_description");
- assertEquals("Validate vf_module_description", group.getDescription(), vf_module_description);
-
- Boolean volume_group = (Boolean) properties.get("volume_group");
- boolean isVolume = false;
- List<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;
- }
+ }
+ });
+ }
+
+ 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 volume_group", isVolume, volume_group);
+ 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();
- } else {
- invariantUUID = (String) metadata.get("invariantUUID");
- name = (String) metadata.get("name");
- UUID = (String) metadata.get("UUID");
- version = (String) metadata.get("version");
- assertNull(properties);
+ 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 InvariantUUID", group.getInvariantUUID(), invariantUUID);
- assertEquals("Validate name", group.getName(), name);
- assertEquals("Validate UUID", group.getGroupUUID(), UUID);
- assertEquals("Validate version", group.getVersion(), version);
+ }
+ 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)
@@ -179,8 +355,7 @@ public class ExportToscaTest extends ComponentBaseTest {
validateInput(inputDef, inputInFile);
}
List<ComponentInstance> componentInstances = createdResource.getComponentInstances();
- Map<String, List<ComponentInstanceProperty>> componentInstancesProperties = createdResource
- .getComponentInstancesProperties();
+ Map<String, List<ComponentInstanceProperty>> componentInstancesProperties = createdResource.getComponentInstancesProperties();
Map<String, Object> node_templates = (Map<String, Object>) topology_template.get("node_templates");
assertNotNull(node_templates);
@@ -188,8 +363,7 @@ public class ExportToscaTest extends ComponentBaseTest {
for (Map.Entry<String, List<ComponentInstanceProperty>> entry : componentInstancesProperties.entrySet()) {
- Optional<ComponentInstance> findFirst = componentInstances.stream()
- .filter(ci -> ci.getUniqueId().equals(entry.getKey())).findFirst();
+ 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);
@@ -234,10 +408,8 @@ public class ExportToscaTest extends ComponentBaseTest {
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();
+ 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
@@ -258,6 +430,187 @@ public class ExportToscaTest extends ComponentBaseTest {
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<InputDefinition> instanceInputs = new Gson().fromJson(getComponentInstanceInputsResponse.getResponse(), new TypeToken<ArrayList<InputDefinition>>() {
+ }.getType());
+ // Take only the 2 first inputs
+ List<InputDefinition> 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"));
@@ -273,15 +626,19 @@ public class ExportToscaTest extends ComponentBaseTest {
assertEquals("validate input description", inputDef.getDescription(), (String) inputInFile.get("description"));
}
- // ----------------------------------------
- private Map<String, Object> downloadAndParseToscaTemplate(User sdncModifierDetails, Resource createdResource)
- throws Exception {
- String artifactUniqeId = createdResource.getToscaArtifacts().get("assettoscatemplate").getUniqueId();
-
- RestResponse toscaTemplate = ArtifactRestUtils.downloadResourceArtifactInternalApi(
- createdResource.getUniqueId(), sdncModifierDetails, artifactUniqeId);
- ArtifactUiDownloadData artifactUiDownloadData = ResponseParser.parseToObject(toscaTemplate.getResponse(),
- ArtifactUiDownloadData.class);
+ private 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();
@@ -292,20 +649,7 @@ public class ExportToscaTest extends ComponentBaseTest {
return load;
}
- private 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;
- }
-
- public ArtifactDefinition findMasterArtifact(Map<String, ArtifactDefinition> deplymentArtifact,
- List<ArtifactDefinition> artifacts, List<String> artifactsList) {
+ 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();
@@ -318,8 +662,7 @@ public class ExportToscaTest extends ComponentBaseTest {
ArtifactDefinition masterArtifact = null;
for (ArtifactDefinition artifactInfo : artifacts) {
String atrifactType = artifactInfo.getArtifactType();
- if (atrifactType.equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType())
- || atrifactType.equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType())) {
+ if (atrifactType.equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType()) || atrifactType.equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType())) {
masterArtifact = artifactInfo;
continue;
}
@@ -330,4 +673,13 @@ public class ExportToscaTest extends ComponentBaseTest {
}
return masterArtifact;
}
+
+ private ComponentInstInputsMap buildComponentInstInputsMap(String addToInput, List<InputDefinition> inputs) {
+ Map<String, List<InputDefinition>> 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/ImportCsarResourceTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportCsarResourceTest.java
index eab4e5bed2..6bf3477c1f 100644
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportCsarResourceTest.java
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportCsarResourceTest.java
@@ -39,6 +39,8 @@ import java.util.stream.Collectors;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.WordUtils;
+import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.apache.tinkerpop.gremlin.process.traversal.P;
import org.junit.Rule;
import org.junit.rules.TestName;
import org.openecomp.sdc.be.dao.api.ActionStatus;
@@ -46,18 +48,24 @@ import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
import org.openecomp.sdc.be.model.ArtifactDefinition;
import org.openecomp.sdc.be.model.CapabilityDefinition;
import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.ComponentInstanceProperty;
import org.openecomp.sdc.be.model.GroupDefinition;
import org.openecomp.sdc.be.model.GroupProperty;
import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.Service;
import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
import org.openecomp.sdc.ci.tests.api.Urls;
import org.openecomp.sdc.ci.tests.config.Config;
import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails;
import org.openecomp.sdc.ci.tests.datatypes.ImportReqDetails;
import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ServiceCategoriesEnum;
import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum;
import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest;
@@ -66,12 +74,15 @@ import org.openecomp.sdc.ci.tests.utils.Utils;
import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
import org.openecomp.sdc.ci.tests.utils.rest.ArtifactRestUtils;
import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ComponentInstanceRestUtils;
import org.openecomp.sdc.ci.tests.utils.rest.GroupRestUtils;
import org.openecomp.sdc.ci.tests.utils.rest.ImportRestUtils;
import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils;
import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils;
+import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
import org.openecomp.sdc.common.util.ValidationUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -83,7 +94,7 @@ 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() {
@@ -757,7 +768,7 @@ public class ImportCsarResourceTest extends ComponentBaseTest {
byte[] data = null;
String payloadData = null;
- path = Paths.get(rootPath + "/src/test/resources/CI/csars/valid_vf.csar");
+ path = Paths.get(rootPath + "/src/main/resources/ci/valid_vf.csar");
data = Files.readAllBytes(path);
payloadData = Base64.encodeBase64String(data);
resourceDetails.setPayloadData(payloadData);
@@ -775,7 +786,7 @@ public class ImportCsarResourceTest extends ComponentBaseTest {
assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue());
// change composition (resource should be updated)
- path = Paths.get(rootPath + "/src/test/resources/CI/csars/valid_vf_b.csar");
+ path = Paths.get(rootPath + "/src/main/resources/ci/valid_vf_b.csar");
data = Files.readAllBytes(path);
payloadData = Base64.encodeBase64String(data);
resourceDetails.setPayloadData(payloadData);
@@ -802,7 +813,7 @@ public class ImportCsarResourceTest extends ComponentBaseTest {
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/test/resources/CI/csars/valid_vf_c.csar");
+ path = Paths.get(rootPath + "/src/main/resources/ci/valid_vf_c.csar");
data = Files.readAllBytes(path);
payloadData = Base64.encodeBase64String(data);
resourceDetails.setPayloadData(payloadData);
@@ -817,7 +828,7 @@ public class ImportCsarResourceTest extends ComponentBaseTest {
// create new resource from other Csar
resourceDetails = ElementFactory.getDefaultImportResource();
- path = Paths.get(rootPath + "/src/test/resources/CI/csars/VF_RI2_G4_withArtifacts.csar");
+ path = Paths.get(rootPath + "/src/main/resources/ci/VF_RI2_G4_withArtifacts.csar");
data = Files.readAllBytes(path);
payloadData = Base64.encodeBase64String(data);
resourceDetails.setPayloadData(payloadData);
@@ -833,7 +844,7 @@ public class ImportCsarResourceTest extends ComponentBaseTest {
// wrong RI (with node types) resource shouldn't be created
resourceDetails.setCsarUUID("VF_RI2_G4_withArtifacts_b.csar");
- path = Paths.get(rootPath + "/src/test/resources/CI/csars/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);
@@ -854,7 +865,7 @@ public class ImportCsarResourceTest extends ComponentBaseTest {
byte[] data = null;
String payloadData = null;
- path = Paths.get(rootPath + "/src/test/resources/CI/csars/valid_vf.csar");
+ path = Paths.get(rootPath + "/src/main/resources/ci/valid_vf.csar");
data = Files.readAllBytes(path);
payloadData = Base64.encodeBase64String(data);
resourceDetails.setPayloadData(payloadData);
@@ -871,7 +882,7 @@ public class ImportCsarResourceTest extends ComponentBaseTest {
assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue());
// change composition and update resource
- path = Paths.get(rootPath + "/src/test/resources/CI/csars/valid_vf_b.csar");
+ path = Paths.get(rootPath + "/src/main/resources/ci/valid_vf_b.csar");
data = Files.readAllBytes(path);
payloadData = Base64.encodeBase64String(data);
resourceDetails.setPayloadData(payloadData);
@@ -899,7 +910,7 @@ public class ImportCsarResourceTest extends ComponentBaseTest {
// try to update resource with wrong RI (without node types, resource
// shouldn't be updated)
- path = Paths.get(rootPath + "/src/test/resources/CI/csars/valid_vf_c.csar");
+ path = Paths.get(rootPath + "/src/main/resources/ci/valid_vf_c.csar");
data = Files.readAllBytes(path);
payloadData = Base64.encodeBase64String(data);
resourceDetails.setPayloadData(payloadData);
@@ -1079,7 +1090,7 @@ public class ImportCsarResourceTest extends ComponentBaseTest {
byte[] data = null;
String payloadData = null;
- path = Paths.get(rootPath + "/src/test/resources/CI/csars/valid_vf.csar");
+ path = Paths.get(rootPath + "/src/main/resources/ci/valid_vf.csar");
data = Files.readAllBytes(path);
payloadData = Base64.encodeBase64String(data);
resourceDetails.setPayloadData(payloadData);
@@ -1097,7 +1108,7 @@ public class ImportCsarResourceTest extends ComponentBaseTest {
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/test/resources/CI/csars/valid_vf_d.csar");
+ path = Paths.get(rootPath + "/src/main/resources/ci/valid_vf_d.csar");
data = Files.readAllBytes(path);
payloadData = Base64.encodeBase64String(data);
resourceDetails.setPayloadData(payloadData);
@@ -1112,7 +1123,7 @@ public class ImportCsarResourceTest extends ComponentBaseTest {
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/test/resources/CI/csars/valid_vf_f.csar");
+ path = Paths.get(rootPath + "/src/main/resources/ci/valid_vf_f.csar");
data = Files.readAllBytes(path);
payloadData = Base64.encodeBase64String(data);
resourceDetails.setPayloadData(payloadData);
@@ -1268,7 +1279,7 @@ public class ImportCsarResourceTest extends ComponentBaseTest {
Map<String, String> createdMembers = groupDefinition1.get(0).getMembers();
verifyMembers(createdMembers, compNameToUniqueId);
- List<GroupProperty> properties = groupDefinition1.get(0).getProperties();
+ 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();
@@ -1465,7 +1476,7 @@ public class ImportCsarResourceTest extends ComponentBaseTest {
byte[] data = null;
String payloadData = null;
- path = Paths.get(rootPath + "/src/test/resources/CI/csars/vmmc_relate_by_cap_name.csar");
+ path = Paths.get(rootPath + CSARS_PATH + "vmmc_relate_by_cap_name.csar");
data = Files.readAllBytes(path);
payloadData = Base64.encodeBase64String(data);
resourceDetails.setPayloadData(payloadData);
@@ -1491,7 +1502,7 @@ public class ImportCsarResourceTest extends ComponentBaseTest {
byte[] data = null;
String payloadData = null;
- path = Paths.get(rootPath + "/src/test/resources/CI/csars/vf_relate_by_cap_name.csar");
+ path = Paths.get(rootPath + CSARS_PATH + "vf_relate_by_cap_name.csar");
data = Files.readAllBytes(path);
payloadData = Base64.encodeBase64String(data);
resourceDetails.setPayloadData(payloadData);
@@ -1514,6 +1525,310 @@ public class ImportCsarResourceTest extends ComponentBaseTest {
assertEquals(mappedByReqOwner.get(cp2Uid).get(0).getRelationships().get(0).getCapabilityUid(), capabilities.get("link").getUniqueId());
}
+ @Test(enabled = true)
+ public void importCsarCheckVfHeatEnv() throws Exception {
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setCsarUUID("csar_1");
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource);
+ Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+
+
+ Map<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();
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
index 873d33979f..7957edc9a7 100644
--- 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
@@ -46,9 +46,12 @@ 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;
@@ -82,9 +85,10 @@ 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_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();
@@ -503,7 +507,7 @@ public class ImportGenericResourceCITest extends ComponentBaseTest {
String fileName = FILE_NAME_MY_COMPUTE;
RestResponse response = ImportRestUtils.importNormativeResourceByName(RESOURCE_NAME_MY_COMPUTE, UserRoleEnum.ADMIN);
Integer statusCode = response.getErrorCode();
- assertTrue(statusCode == BaseRestUtils.STATUS_CODE_IMPORT_SUCCESS);
+ 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");
@@ -572,7 +576,7 @@ public class ImportGenericResourceCITest extends ComponentBaseTest {
String fileName = FILE_NAME_USER_COMPUTE;
RestResponse response = ImportRestUtils.importNormativeResourceByName(RESOURCE_NAME_USER_COMPUTE, UserRoleEnum.ADMIN);
Integer statusCode = response.getErrorCode();
- assertTrue(statusCode == ImportRestUtils.STATUS_CODE_IMPORT_SUCCESS);
+ 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");
@@ -595,5 +599,22 @@ public class ImportGenericResourceCITest extends ComponentBaseTest {
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
index ec335fa65f..9e8a2a1f95 100644
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportNewResourceCITest.java
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportNewResourceCITest.java
@@ -108,7 +108,8 @@ public class ImportNewResourceCITest extends ComponentBaseTest {
// init user
sdncModifierDetails.setUserId(UserRoleEnum.ADMIN.getUserId());
// init resource details
- resourceDetails = ElementFactory.getDefaultResource("importResource4test", NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, "jh0003");
+ resourceDetails = ElementFactory.getDefaultResource("importResource4test", NormativeTypesEnum.ROOT,
+ ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, "jh0003");
}
@Test
@@ -119,8 +120,10 @@ public class ImportNewResourceCITest extends ComponentBaseTest {
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());
+ RestResponse importResponse = ImportRestUtils.importNewResourceByName(currResource.getFolderName(),
+ UserRoleEnum.ADMIN);
+ System.err.println("import Resource " + "<" + currResource.getFolderName() + ">" + "response: "
+ + importResponse.getErrorCode());
// validate response
ImportRestUtils.validateImportTestTypesResp(currResource, importResponse);
@@ -143,7 +146,8 @@ public class ImportNewResourceCITest extends ComponentBaseTest {
expectedResourceAuditJavaObject.setCurrState("");
expectedResourceAuditJavaObject.setComment(null);
expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString());
- List<String> variables = (currResource.getErrorParams() != null ? currResource.getErrorParams() : new ArrayList<String>());
+ List<String> variables = (currResource.getErrorParams() != null ? currResource.getErrorParams()
+ : new ArrayList<String>());
String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables);
expectedResourceAuditJavaObject.setDesc(auditDesc);
AuditValidationUtils.validateAuditImport(expectedResourceAuditJavaObject, auditAction);
@@ -156,7 +160,8 @@ public class ImportNewResourceCITest extends ComponentBaseTest {
// init user
sdncModifierDetails.setUserId(userRoleEnum.getUserId());
// init resource details
- resourceDetails = ElementFactory.getDefaultResource("importResource4test", NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, "jh0003");
+ resourceDetails = ElementFactory.getDefaultResource("importResource4test", NormativeTypesEnum.ROOT,
+ ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, "jh0003");
// clean ES DB
DbUtils.cleanAllAudits();
// import new resource (expected checkOut state)
@@ -166,14 +171,19 @@ public class ImportNewResourceCITest extends ComponentBaseTest {
@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 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"
+ 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" + "}";
+ + " \"description\": \"ResourceDescription\",\r\n" + " \"vendorName\": \"VendorName\",\r\n"
+ + " \"vendorRelease\": \"VendorRelease\",\r\n" + " \"contactId\": \"AT1234\",\r\n"
+ + " \"icon\": \"router\",\r\n" + " \"tags\": [\r\n" + " \"importResource4test\"\r\n" + " ],\r\n"
+ + " \"payloadData\": \"" + encodedPayload + "\"\r\n" + "}";
String md5 = GeneralUtility.calculateMD5ByString(json);
@@ -226,8 +236,10 @@ public class ImportNewResourceCITest extends ComponentBaseTest {
resourceRespJavaObject.setLifecycleState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
// validate get response
- RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, resourceRespJavaObject.getUniqueId());
- Resource resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
+ RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails,
+ resourceRespJavaObject.getUniqueId());
+ Resource resourceFromGet = ResponseParser
+ .convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
assertNotNull(resourceFromGet);
// validate
@@ -235,7 +247,8 @@ public class ImportNewResourceCITest extends ComponentBaseTest {
// validate audit
resourceDetails.setVersion(resourceDetails.getVersion());
- ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor.constructFieldsForAuditValidation(resourceDetails, resourceVersion);
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor
+ .constructFieldsForAuditValidation(resourceDetails, resourceVersion);
auditAction = "ResourceImport";
expectedResourceAuditJavaObject.setAction(auditAction);
@@ -275,7 +288,8 @@ public class ImportNewResourceCITest extends ComponentBaseTest {
DbUtils.cleanAllAudits();
// import new resource while resource already exist in other state
- importResponse = ImportRestUtils.importNewResourceByName("importResource4testUpdateVendorNameAndCategory", UserRoleEnum.ADMIN);
+ 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());
@@ -290,8 +304,10 @@ public class ImportNewResourceCITest extends ComponentBaseTest {
resourceRespJavaObject.setLifecycleState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
// validate get response
- RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, resourceRespJavaObject.getUniqueId());
- Resource resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
+ RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails,
+ resourceRespJavaObject.getUniqueId());
+ Resource resourceFromGet = ResponseParser
+ .convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
assertNotNull(resourceFromGet);
// validate
@@ -299,7 +315,8 @@ public class ImportNewResourceCITest extends ComponentBaseTest {
// validate audit
resourceDetails.setVersion(resourceDetails.getVersion());
- ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor.constructFieldsForAuditValidation(resourceDetails);
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor
+ .constructFieldsForAuditValidation(resourceDetails);
auditAction = "ResourceImport";
resourceVersion = "0.1";
@@ -331,14 +348,17 @@ public class ImportNewResourceCITest extends ComponentBaseTest {
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());
+ 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());
+ List<String> variables = Arrays.asList(resourceFromImport.getName(), "resource", firstName, lastName,
+ resourceFromImport.getLastUpdaterUserId());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_IN_CHECKOUT_STATE.name(), variables,
+ importResponse.getResponse());
}
@@ -359,74 +379,88 @@ public class ImportNewResourceCITest extends ComponentBaseTest {
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());
+ 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());
+ 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);
+ 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());
+ 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);
+ 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());
+ 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);
+ 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());
+ 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);
+ 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());
+ 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);
+ 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());
+ 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);
+ 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());
@@ -464,8 +498,10 @@ public class ImportNewResourceCITest extends ComponentBaseTest {
resourceRespJavaObject.setLifecycleState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
// validate get response
- RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, resourceRespJavaObject.getUniqueId());
- Resource resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
+ RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails,
+ resourceRespJavaObject.getUniqueId());
+ Resource resourceFromGet = ResponseParser
+ .convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
assertNotNull(resourceFromGet);
// validate
@@ -473,7 +509,8 @@ public class ImportNewResourceCITest extends ComponentBaseTest {
// validate audit
resourceDetails.setVersion(resourceDetails.getVersion());
- ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor.constructFieldsForAuditValidation(resourceDetails);
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor
+ .constructFieldsForAuditValidation(resourceDetails);
auditAction = "ResourceImport";
resourceVersion = "0.1";
@@ -505,7 +542,8 @@ public class ImportNewResourceCITest extends ComponentBaseTest {
resourceVersion = resourceDetails.getVersion();
String checkinComment = "good checkin";
String checkinComentJson = "{\"userRemarks\": \"" + checkinComment + "\"}";
- RestResponse checkInResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, resourceVersion, LifeCycleStatesEnum.CHECKIN, checkinComentJson);
+ 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());
@@ -530,8 +568,10 @@ public class ImportNewResourceCITest extends ComponentBaseTest {
resourceRespJavaObject.setLifecycleState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
// validate get response
- RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, resourceRespJavaObject.getUniqueId());
- Resource resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
+ RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails,
+ resourceRespJavaObject.getUniqueId());
+ Resource resourceFromGet = ResponseParser
+ .convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
assertNotNull(resourceFromGet);
// validate
@@ -539,7 +579,8 @@ public class ImportNewResourceCITest extends ComponentBaseTest {
// validate audit
resourceDetails.setVersion(resourceDetails.getVersion());
- ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor.constructFieldsForAuditValidation(resourceDetails);
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor
+ .constructFieldsForAuditValidation(resourceDetails);
resourceVersion = "0.2";
auditAction = "ResourceImport";
@@ -565,9 +606,11 @@ public class ImportNewResourceCITest extends ComponentBaseTest {
resourceDetails = ResponseParser.parseToObject(importResponse.getResponse(), ResourceReqDetails.class);
resourceVersion = resourceDetails.getVersion();
- RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, resourceDetails.getUniqueId());
+ RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails,
+ resourceDetails.getUniqueId());
assertEquals("Check response code after get resource", 200, resourceGetResponse.getErrorCode().intValue());
- Resource resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
+ Resource resourceFromGet = ResponseParser
+ .convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
assertNotNull(resourceFromGet);
// add mandatory artifacts
// // resourceUtils.addResourceMandatoryArtifacts(sdncModifierDetails,
@@ -583,7 +626,8 @@ public class ImportNewResourceCITest extends ComponentBaseTest {
resourceVersion = resourceDetails.getVersion();
String checkinComment = "good checkin";
String checkinComentJson = "{\"userRemarks\": \"" + checkinComment + "\"}";
- RestResponse checkInResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, resourceVersion, LifeCycleStatesEnum.CHECKIN, checkinComentJson);
+ 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());
@@ -593,7 +637,8 @@ public class ImportNewResourceCITest extends ComponentBaseTest {
resourceDetails.setVersion(resourceFromGet.getVersion());
// req4cert resource
- RestResponse request4cert = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, resourceVersion, LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ 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());
@@ -614,11 +659,13 @@ public class ImportNewResourceCITest extends ComponentBaseTest {
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());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), variables,
+ importResponse.getResponse());
// validate audit
- ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor.constructFieldsForAuditValidation(resourceDetails, resourceVersion);
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor
+ .constructFieldsForAuditValidation(resourceDetails, resourceVersion);
String auditAction = "ResourceImport";
expectedResourceAuditJavaObject.setAction(auditAction);
@@ -649,9 +696,11 @@ public class ImportNewResourceCITest extends ComponentBaseTest {
resourceDetails = ResponseParser.parseToObject(importResponse.getResponse(), ResourceReqDetails.class);
resourceVersion = resourceDetails.getVersion();
- RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, resourceDetails.getUniqueId());
+ RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails,
+ resourceDetails.getUniqueId());
assertEquals("Check response code after get resource", 200, resourceGetResponse.getErrorCode().intValue());
- Resource resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
+ Resource resourceFromGet = ResponseParser
+ .convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
assertNotNull(resourceFromGet);
// add mandatory artifacts
// resourceUtils.addResourceMandatoryArtifacts(sdncModifierDetails,
@@ -667,12 +716,14 @@ public class ImportNewResourceCITest extends ComponentBaseTest {
resourceVersion = resourceDetails.getVersion();
String checkinComment = "good checkin";
String checkinComentJson = "{\"userRemarks\": \"" + checkinComment + "\"}";
- RestResponse checkInResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, resourceVersion, LifeCycleStatesEnum.CHECKIN, checkinComentJson);
+ 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);
+ 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());
@@ -687,18 +738,22 @@ public class ImportNewResourceCITest extends ComponentBaseTest {
importResponse = ImportRestUtils.importNewResourceByName("importResource4test", UserRoleEnum.DESIGNER);
// validate response
- ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_SENT_FOR_CERTIFICATION.name());
+ 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());
+ 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);
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor
+ .constructFieldsForAuditValidation(resourceDetails, resourceVersion);
String auditAction = "ResourceImport";
expectedResourceAuditJavaObject.setAction(auditAction);
expectedResourceAuditJavaObject.setModifierUid(UserRoleEnum.DESIGNER.getUserId());
@@ -727,9 +782,11 @@ public class ImportNewResourceCITest extends ComponentBaseTest {
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());
+ RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails,
+ resourceDetails.getUniqueId());
assertEquals("Check response code after get resource", 200, resourceGetResponse.getErrorCode().intValue());
- Resource resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
+ Resource resourceFromGet = ResponseParser
+ .convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
assertNotNull(resourceFromGet);
// add mandatory artifacts
@@ -746,12 +803,14 @@ public class ImportNewResourceCITest extends ComponentBaseTest {
resourceVersion = resourceDetails.getVersion();
String checkinComment = "good checkin";
String checkinComentJson = "{\"userRemarks\": \"" + checkinComment + "\"}";
- RestResponse checkInResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, resourceVersion, LifeCycleStatesEnum.CHECKIN, checkinComentJson);
+ 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);
+ 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());
@@ -790,7 +849,8 @@ public class ImportNewResourceCITest extends ComponentBaseTest {
ResourceValidationUtils.validateModelObjects(resourceFromImport, resourceFromGet);
// validate audit
- ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor.constructFieldsForAuditValidation(resourceDetails, resourceVersion);
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor
+ .constructFieldsForAuditValidation(resourceDetails, resourceVersion);
auditAction = "ResourceImport";
expectedResourceAuditJavaObject.setAction(auditAction);
expectedResourceAuditJavaObject.setPrevState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
@@ -812,9 +872,11 @@ public class ImportNewResourceCITest extends ComponentBaseTest {
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());
+ RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails,
+ resourceDetails.getUniqueId());
assertEquals("Check response code after get resource", 200, resourceGetResponse.getErrorCode().intValue());
- Resource resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
+ Resource resourceFromGet = ResponseParser
+ .convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
assertNotNull(resourceFromGet);
// add mandatory artifacts
@@ -831,12 +893,14 @@ public class ImportNewResourceCITest extends ComponentBaseTest {
resourceVersion = resourceDetails.getVersion();
String checkinComment = "good checkin";
String checkinComentJson = "{\"userRemarks\": \"" + checkinComment + "\"}";
- RestResponse checkInResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, resourceVersion, LifeCycleStatesEnum.CHECKIN, checkinComentJson);
+ 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);
+ 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());
@@ -845,7 +909,8 @@ public class ImportNewResourceCITest extends ComponentBaseTest {
resourceDetails.setVersion(resourceFromGet.getVersion());
// startCert
- RestResponse startCert = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, resourceVersion, LifeCycleStatesEnum.STARTCERTIFICATION);
+ 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());
@@ -866,10 +931,12 @@ public class ImportNewResourceCITest extends ComponentBaseTest {
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());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), variables,
+ importResponse.getResponse());
// validate audit
- ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor.constructFieldsForAuditValidation(resourceDetails, resourceVersion);
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor
+ .constructFieldsForAuditValidation(resourceDetails, resourceVersion);
String auditAction = "ResourceImport";
expectedResourceAuditJavaObject.setAction(auditAction);
expectedResourceAuditJavaObject.setResourceName("");
@@ -897,9 +964,11 @@ public class ImportNewResourceCITest extends ComponentBaseTest {
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());
+ RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails,
+ resourceDetails.getUniqueId());
assertEquals("Check response code after get resource", 200, resourceGetResponse.getErrorCode().intValue());
- Resource resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
+ Resource resourceFromGet = ResponseParser
+ .convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
assertNotNull(resourceFromGet);
// add mandatory artifacts
@@ -916,12 +985,14 @@ public class ImportNewResourceCITest extends ComponentBaseTest {
resourceVersion = resourceDetails.getVersion();
String checkinComment = "good checkin";
String checkinComentJson = "{\"userRemarks\": \"" + checkinComment + "\"}";
- RestResponse checkInResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, resourceVersion, LifeCycleStatesEnum.CHECKIN, checkinComentJson);
+ 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);
+ 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());
@@ -930,7 +1001,8 @@ public class ImportNewResourceCITest extends ComponentBaseTest {
resourceDetails.setVersion(resourceFromGet.getVersion());
// startCert
- RestResponse startCert = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, resourceVersion, LifeCycleStatesEnum.STARTCERTIFICATION);
+ 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());
@@ -944,15 +1016,19 @@ public class ImportNewResourceCITest extends ComponentBaseTest {
// 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());
+ 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());
+ 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);
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor
+ .constructFieldsForAuditValidation(resourceDetails, resourceVersion);
String auditAction = "ResourceImport";
expectedResourceAuditJavaObject.setAction(auditAction);
expectedResourceAuditJavaObject.setModifierUid(UserRoleEnum.DESIGNER.getUserId());
@@ -983,9 +1059,11 @@ public class ImportNewResourceCITest extends ComponentBaseTest {
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());
+ RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails,
+ resourceDetails.getUniqueId());
assertEquals("Check response code after get resource", 200, resourceGetResponse.getErrorCode().intValue());
- Resource resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
+ Resource resourceFromGet = ResponseParser
+ .convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
assertNotNull(resourceFromGet);
// add mandatory artifacts
@@ -1002,12 +1080,14 @@ public class ImportNewResourceCITest extends ComponentBaseTest {
resourceVersion = resourceDetails.getVersion();
String checkinComment = "good checkin";
String checkinComentJson = "{\"userRemarks\": \"" + checkinComment + "\"}";
- RestResponse checkInResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, resourceVersion, LifeCycleStatesEnum.CHECKIN, checkinComentJson);
+ 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);
+ 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());
@@ -1016,7 +1096,8 @@ public class ImportNewResourceCITest extends ComponentBaseTest {
resourceDetails.setVersion(resourceFromGet.getVersion());
// startCert
- RestResponse startCert = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, resourceVersion, LifeCycleStatesEnum.STARTCERTIFICATION);
+ 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());
@@ -1032,15 +1113,19 @@ public class ImportNewResourceCITest extends ComponentBaseTest {
importResponse = ImportRestUtils.importNewResourceByName("importResource4test", UserRoleEnum.ADMIN);
// validate response
- ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE.name());
+ 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());
+ 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);
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor
+ .constructFieldsForAuditValidation(resourceDetails, resourceVersion);
String auditAction = "ResourceImport";
expectedResourceAuditJavaObject.setAction(auditAction);
expectedResourceAuditJavaObject.setModifierUid(UserRoleEnum.ADMIN.getUserId());
@@ -1202,10 +1287,6 @@ public class ImportNewResourceCITest extends ComponentBaseTest {
// DbUtils.cleanAllAudits();
//
// // change resource details
- // resourceDetails =
- // ElementFactory.getDefaultResource("tosca.nodes.importResource4test",
- // NormativeTypesEnum.COMPUTE, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS,
- // "jh0003");
//
// // import new resource while resource already exist in other state
// importResponse =
@@ -1279,9 +1360,11 @@ public class ImportNewResourceCITest extends ComponentBaseTest {
resourceDetails = ResponseParser.parseToObject(importResponse.getResponse(), ResourceReqDetails.class);
resourceVersion = resourceDetails.getVersion();
- RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, resourceDetails.getUniqueId());
+ RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails,
+ resourceDetails.getUniqueId());
assertEquals("Check response code after get resource", 200, resourceGetResponse.getErrorCode().intValue());
- Resource resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
+ Resource resourceFromGet = ResponseParser
+ .convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
assertNotNull(resourceFromGet);
// add mandatory artifacts
// resourceUtils.addResourceMandatoryArtifacts(sdncModifierDetails,
@@ -1293,7 +1376,8 @@ public class ImportNewResourceCITest extends ComponentBaseTest {
resourceDetails = ResponseParser.parseToObject(importResponse.getResponse(), ResourceReqDetails.class);
resourceDetails.setVersion(resourceFromGet.getVersion());
- RestResponse checkInResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, "0.1", LifeCycleStatesEnum.CHECKIN);
+ 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());
@@ -1301,7 +1385,8 @@ public class ImportNewResourceCITest extends ComponentBaseTest {
assertTrue(ResourceValidationUtils.validateUuidAfterChangingStatus(oldUuid, newUuid));
// req4cert resource
- RestResponse request4cert = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, resourceVersion, LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ 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());
@@ -1313,7 +1398,8 @@ public class ImportNewResourceCITest extends ComponentBaseTest {
assertTrue(ResourceValidationUtils.validateUuidAfterChangingStatus(oldUuid, newUuid2));
// startCert
- RestResponse startCert = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, resourceVersion, LifeCycleStatesEnum.STARTCERTIFICATION);
+ 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());
@@ -1324,14 +1410,16 @@ public class ImportNewResourceCITest extends ComponentBaseTest {
String newUuid3 = ResponseParser.getValueFromJsonResponse(startCert.getResponse(), "uuid");
assertTrue(ResourceValidationUtils.validateUuidAfterChangingStatus(oldUuid, newUuid3));
- RestResponse certify = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, "0.1", LifeCycleStatesEnum.CERTIFY);
+ 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);
+ 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());
@@ -1349,7 +1437,8 @@ public class ImportNewResourceCITest extends ComponentBaseTest {
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();
+ PropertyDefinition propertyDefinition = properties.stream().filter(p -> p.getName().equals("validation_test"))
+ .findFirst().get();
String defaultValue = propertyDefinition.getDefaultValue();
Map mapValue = gson.fromJson(defaultValue, Map.class);
@@ -1371,7 +1460,8 @@ public class ImportNewResourceCITest extends ComponentBaseTest {
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();
+ PropertyDefinition propertyDefinition = properties.stream().filter(p -> p.getName().equals("validation_test"))
+ .findFirst().get();
String defaultValue = propertyDefinition.getDefaultValue();
List listValue = gson.fromJson(defaultValue, List.class);
@@ -1385,7 +1475,8 @@ public class ImportNewResourceCITest extends ComponentBaseTest {
assertEquals("check properties size", 2, attributes.size());
// Verify attribute from type map
- AttributeDefinition attributeMapDefinition = attributes.stream().filter(p -> p.getName().equals("validation_test_map")).findFirst().get();
+ AttributeDefinition 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());
@@ -1393,7 +1484,8 @@ public class ImportNewResourceCITest extends ComponentBaseTest {
checkMapValues(attributeMapValue, "key", 2, SPECIAL_CHARACTERS);
// Verify attribute from type list
- AttributeDefinition attributeListDefinition = attributes.stream().filter(p -> p.getName().equals("validation_test_list")).findFirst().get();
+ AttributeDefinition attributeListDefinition = attributes.stream()
+ .filter(p -> p.getName().equals("validation_test_list")).findFirst().get();
String defaultListValue = attributeListDefinition.getDefaultValue();
List attributeListValue = gson.fromJson(defaultListValue, List.class);
@@ -1408,7 +1500,8 @@ public class ImportNewResourceCITest extends ComponentBaseTest {
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 protocol value", "protocol" + index + (suffix == null ? "" : suffix),
+ map.get("protocol"));
assertEquals("check Map token value", "token" + index, map.get("token"));
}
@@ -1424,7 +1517,8 @@ public class ImportNewResourceCITest extends ComponentBaseTest {
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 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/ImportToscaResourceTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportToscaResourceTest.java
index b78bf3de36..0973135295 100644
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportToscaResourceTest.java
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportToscaResourceTest.java
@@ -95,6 +95,8 @@ import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
+import aj.org.objectweb.asm.Attribute;
+
/**
*
* @author Andrey + Pavel + Shay
@@ -135,10 +137,15 @@ public class ImportToscaResourceTest extends ComponentBaseTest {
@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
+ 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
@@ -166,20 +173,26 @@ public class ImportToscaResourceTest extends ComponentBaseTest {
// 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
+ { "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" },
+ 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
@@ -209,12 +222,13 @@ public class ImportToscaResourceTest extends ComponentBaseTest {
// 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
+ { "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
};
}
@@ -289,67 +303,93 @@ public class ImportToscaResourceTest extends ComponentBaseTest {
// 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);
+ 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());
+ 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);
+ 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());
+ 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));
+ 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 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);
+ 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));
+ 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 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);
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject,
+ AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false);
}
// ------------------------------Success---------------------------------
@@ -359,23 +399,34 @@ public class ImportToscaResourceTest extends ComponentBaseTest {
String resourceType = ResourceTypeEnum.VF.toString();
- importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, importSuccessVFFile);
+ 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));
+ 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 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);
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject,
+ AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false);
}
// ------------------------------Failure---------------------------------
@@ -384,195 +435,255 @@ public class ImportToscaResourceTest extends ComponentBaseTest {
public void importToscaResourceDerivedFromNotExist() throws Exception {
String fileName = importNoDerivedFromFile;
- importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, fileName);
+ 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());
+ 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());
+ 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());
+ 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());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.PARENT_RESOURCE_NOT_FOUND.name(), variables,
+ importResourceResponse.getResponse());
- ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultImportResourceAuditMsgFailure(errorInfo, variables);
+ 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);
+ 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());
+ 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());
+ 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());
+ 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());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_TOSCA_TEMPLATE.name(), variables,
+ importResourceResponse.getResponse());
- ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultImportResourceAuditMsgFailure(errorInfo, variables);
+ 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);
+ 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());
+ 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());
+ 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());
+ 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());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_RESOURCE_NAMESPACE.name(), variables,
+ importResourceResponse.getResponse());
- ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultImportResourceAuditMsgFailure(errorInfo, variables);
+ 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);
+ 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());
+ 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());
+ 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());
+ 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());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_TOSCA_TEMPLATE.name(), variables,
+ importResourceResponse.getResponse());
- ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultImportResourceAuditMsgFailure(errorInfo, variables);
+ 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);
+ 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());
+ 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());
+ 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());
+ 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());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_RESOURCE_PAYLOAD.name(), variables,
+ importResourceResponse.getResponse());
- ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultImportResourceAuditMsgFailure(errorInfo, variables);
+ 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);
+ 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());
+ 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());
+ 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());
+ 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());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.NOT_RESOURCE_TOSCA_TEMPLATE.name(), variables,
+ importResourceResponse.getResponse());
- ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultImportResourceAuditMsgFailure(errorInfo, variables);
+ 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);
+ 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());
+ 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());
+ 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());
+ 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());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.NOT_SINGLE_RESOURCE.name(), variables,
+ importResourceResponse.getResponse());
- ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultImportResourceAuditMsgFailure(errorInfo, variables);
+ 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);
+ 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);
+ 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 expectedResourceAuditJavaObject = ElementFactory
+ .getDefaultImportResourceAuditMsgSuccess();
expectedResourceAuditJavaObject.setResourceName(importReqDetails.getName());
expectedResourceAuditJavaObject.setModifierName(sdncUserDetails.getFullName());
expectedResourceAuditJavaObject.setModifierUid(sdncUserDetails.getUserId());
- ToscaNodeTypeInfo parseToscaNodeYaml = utils.parseToscaNodeYaml(Decoder.decode(importReqDetails.getPayloadData()));
+ ToscaNodeTypeInfo parseToscaNodeYaml = utils
+ .parseToscaNodeYaml(Decoder.decode(importReqDetails.getPayloadData()));
expectedResourceAuditJavaObject.setToscaNodeType(parseToscaNodeYaml.getNodeName());
- AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false);
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject,
+ AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false);
// import the same tosca resource with different resourceName
DbUtils.cleanAllAudits();
@@ -582,23 +693,27 @@ public class ImportToscaResourceTest extends ComponentBaseTest {
tags.add(importReqDetails.getName());
importReqDetails.setTags(tags);
importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
- logger.debug("import tosca resource response: {}", importResourceResponse.getResponseMessage());
+ 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());
+ 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());
+ 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());
+ 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);
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject,
+ AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false);
}
@@ -607,7 +722,8 @@ public class ImportToscaResourceTest extends ComponentBaseTest {
// create resource
String fileName = importSuccessFile;
- importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, fileName);
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath,
+ fileName);
resourceDetails = ElementFactory.getDefaultResource();
resourceDetails.setName(importReqDetails.getName());
@@ -622,50 +738,63 @@ public class ImportToscaResourceTest extends ComponentBaseTest {
// import the same tosca resource
DbUtils.cleanAllAudits();
- RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
- logger.debug("import tosca resource response: {}", importResourceResponse.getResponseMessage());
+ 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());
+ 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());
+ 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());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESOURCE_ALREADY_EXISTS.name(), variables,
+ importResourceResponse.getResponse());
- ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultImportResourceAuditMsgFailure(errorInfo, variables);
+ 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);
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject,
+ AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false);
}
@Test
public void importToscaResourceInvalidChecksum() throws Exception {
String fileName = importSuccessFile;
- importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, fileName);
+ 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());
+ 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());
+ 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());
+ 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());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_RESOURCE_CHECKSUM.name(), variables,
+ importResourceResponse.getResponse());
- ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultImportResourceAuditMsgFailure(errorInfo, variables);
+ 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);
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject,
+ AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false);
}
@Test
@@ -673,48 +802,67 @@ public class ImportToscaResourceTest extends ComponentBaseTest {
String resourceType = "invalidResourceType";
- importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, importSuccessFile);
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath,
+ importSuccessFile);
importReqDetails.setResourceType(resourceType);
- RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ 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());
+ 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());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_CONTENT.name(), variables,
+ importResourceResponse.getResponse());
// Validate audit message
- ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultImportResourceAuditMsgFailure(errorInfo, variables);
+ 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);
+ 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()));
+ 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 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);
+ 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);
+ assertTrue("certify resource request returned status:" + certifyResource.getErrorCode(),
+ certifyResource.getErrorCode() == 200);
// import second resource template derived from first resource
DbUtils.cleanAllAudits();
@@ -722,23 +870,32 @@ public class ImportToscaResourceTest extends ComponentBaseTest {
List<String> tags = new ArrayList<String>();
tags.add(importReqDetails.getName());
importReqDetails.setTags(tags);
- importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, derivedFromMyCompute);
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath,
+ derivedFromMyCompute);
importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
- logger.debug("import tosca resource response: {}", importResourceResponse.getResponseMessage());
+ logger.debug("import tosca resource response: {}", importResourceResponse.getResponseMessage());
- assertTrue("response code is not 201, returned :" + importResourceResponse.getErrorCode(), importResourceResponse.getErrorCode() == 201);
+ 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()));
+ 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();
+ 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);
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject2,
+ AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false);
}
@@ -746,16 +903,25 @@ public class ImportToscaResourceTest extends ComponentBaseTest {
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());
+ 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);
+ 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\"]"));
+ 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\"]"));
}
@@ -763,18 +929,23 @@ public class ImportToscaResourceTest extends ComponentBaseTest {
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());
+ 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());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE.name(), variables,
+ importResourceResponse.getResponse());
}
@@ -783,47 +954,60 @@ public class ImportToscaResourceTest extends ComponentBaseTest {
@Test
public void importToscaResourceListPropertySuccessFlow() throws Exception {
String fileName = importListPropertySuccess;
- importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, fileName);
- RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ 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()));
+ 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 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);
+ 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);
+ 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());
+ 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);
+ 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());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_PROPERTY_INNER_TYPE.name(), variables,
+ importResourceResponse.getResponse());
}
// BUG DE198676
@@ -832,46 +1016,59 @@ public class ImportToscaResourceTest extends ComponentBaseTest {
// "list"
// type
String ymlFile = "ListPropertyFalure16.yml";
- importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, ymlFile);
- RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ 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());
+ 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);
+ 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()));
+ 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 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);
+ 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);
+ 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());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE.name(), variables,
+ importResourceResponse.getResponse());
}
@Test
@@ -879,142 +1076,181 @@ public class ImportToscaResourceTest extends ComponentBaseTest {
// "Map"
// type
String ymlFile = "MapPropertyFalure16.yml";
- importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, ymlFile);
- RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ 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());
+ 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());
+ 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 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);
+ 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());
+ 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 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);
+ 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);
+ 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);
+ 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);
+ 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);
+ 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);
+ 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);
+ 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);
+ 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);
+ 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);
+ 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);
+ 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);
+ 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);
+ 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);
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath,
+ importToscaResourceReqCapDerivedFromParent);
+ RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails,
+ null);
BaseRestUtils.checkCreateResponse(importResourceResponse);
- ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultImportResourceAuditMsgSuccess();
+ 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);
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject,
+ AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false);
}
/************************ Shay ************************/
@@ -1023,31 +1259,39 @@ public class ImportToscaResourceTest extends ComponentBaseTest {
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);
+ 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);
+ 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);
+ 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);
+ 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);
+ 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 = 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);
+ requirementsFromResponse = parseReqOrCapFromResponse("requirements", importReqDetails,
+ expectedNumOfRequirements);
assertEquals(requirements.keySet().size(), requirementsFromResponse.keySet().size());
importReqDetails.compareRequirementsOrCapabilities(requirements, requirementsFromResponse);
@@ -1058,20 +1302,26 @@ public class ImportToscaResourceTest extends ComponentBaseTest {
private void checkImportedAssetAssociated(ImportReqDetails importDetails) throws IOException, Exception {
RestResponse importResourceResponse;
ImportReqDetails importReqDetails2 = ElementFactory.getDefaultImportResource();
- importReqDetails2 = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails2, testResourcesPath, "BindingAsset.yml");
+ 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());
+ 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);
+ LifecycleRestUtils.changeResourceState(importDetails, sdncUserDetails,
+ LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ LifecycleRestUtils.changeResourceState(importReqDetails2, sdncUserDetails,
+ LifeCycleStatesEnum.CERTIFICATIONREQUEST);
- RestResponse response = ResourceRestUtils.createResourceInstance(importDetails, sdncUserDetails, vf.getUniqueId());
+ RestResponse response = ResourceRestUtils.createResourceInstance(importDetails, sdncUserDetails,
+ vf.getUniqueId());
ResourceRestUtils.checkCreateResponse(response);
ComponentInstance riCap = ResponseParser.parseToObject(response.getResponse(), ComponentInstance.class);
@@ -1079,11 +1329,14 @@ public class ImportToscaResourceTest extends ComponentBaseTest {
ResourceRestUtils.checkCreateResponse(response);
ComponentInstance riReq = ResponseParser.parseToObject(response.getResponse(), ComponentInstance.class);
- RestResponse getResourceBeforeAssociate = ComponentRestUtils.getComponentRequirmentsCapabilities(sdncUserDetails, vf);
+ 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();
+ 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());
@@ -1102,7 +1355,8 @@ public class ImportToscaResourceTest extends ComponentBaseTest {
relationships.add(pair);
requirementDef.setRelationships(relationships);
- RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, sdncUserDetails, vf.getUniqueId(), ComponentTypeEnum.RESOURCE);
+ RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, sdncUserDetails,
+ vf.getUniqueId(), ComponentTypeEnum.RESOURCE);
assertEquals("Check response code ", STATUS_CODE_SUCCESS, associateInstances.getErrorCode().intValue());
}
@@ -1111,25 +1365,32 @@ public class ImportToscaResourceTest extends ComponentBaseTest {
String fileName = "CaseInsensitiveCapTest_1.yml";
int expectedNumOfCapabilities = 6;
- importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, fileName);
- RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ 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);
+ 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);
+ 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);
+ 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);
+ 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 = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath,
+ fileName2);
importReqDetails.setName("secondImportedResource");
importReqDetails.setTags(Arrays.asList(importReqDetails.getName()));
importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
@@ -1137,7 +1398,8 @@ public class ImportToscaResourceTest extends ComponentBaseTest {
importReqDetails.setCapabilities(testResourcesPath, fileName2, sdncUserDetails, null);
capabilities = importReqDetails.getCapabilities();
- capabilitiesFromResponse = parseReqOrCapFromResponse("capabilities", importReqDetails, expectedNumOfCapabilities);
+ capabilitiesFromResponse = parseReqOrCapFromResponse("capabilities", importReqDetails,
+ expectedNumOfCapabilities);
assertEquals(capabilities.keySet().size(), capabilitiesFromResponse.keySet().size());
importReqDetails.compareRequirementsOrCapabilities(capabilities, capabilitiesFromResponse);
@@ -1148,13 +1410,16 @@ public class ImportToscaResourceTest extends ComponentBaseTest {
String fileName = "DifferentReqFromCompute.yml";
int expectedNumOfRequirements = 3;
- importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, fileName);
- RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ 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);
+ Map<String, Object> requirementsFromResponse = parseReqOrCapFromResponse("requirements", importReqDetails,
+ expectedNumOfRequirements);
assertEquals(requirements.keySet().size(), requirementsFromResponse.keySet().size());
importReqDetails.compareRequirementsOrCapabilities(requirements, requirementsFromResponse);
@@ -1169,28 +1434,36 @@ public class ImportToscaResourceTest extends ComponentBaseTest {
importReqDetails.setName("father");
importReqDetails.setTags(Arrays.asList(importReqDetails.getName()));
- importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, fatherFileName);
- RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ 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);
+ 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);
+ 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);
+ 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);
+ 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);
+ importReqDetails.setRequirements(testResourcesPath, importReqDetails.getPayloadName(), sdncUserDetails,
+ derivedFromResourceName);
Map<String, Object> requirements = importReqDetails.getRequirements();
- Map<String, Object> requirementsFromResponse = parseReqOrCapFromResponse("requirements", importReqDetails, expectedNumOfRequirements);
+ Map<String, Object> requirementsFromResponse = parseReqOrCapFromResponse("requirements", importReqDetails,
+ expectedNumOfRequirements);
assertEquals(requirements.keySet().size(), requirementsFromResponse.keySet().size());
importReqDetails.compareRequirementsOrCapabilities(requirements, requirementsFromResponse);
@@ -1203,13 +1476,16 @@ public class ImportToscaResourceTest extends ComponentBaseTest {
importReqDetails.setName("child");
importReqDetails.setTags(Arrays.asList(importReqDetails.getName()));
- importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, childFileName);
- RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ 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);
+ Map<String, Object> requirementsFromResponse = parseReqOrCapFromResponse("requirements", importReqDetails,
+ expectedNumOfRequirements);
assertEquals(requirements.keySet().size(), requirementsFromResponse.keySet().size());
importReqDetails.compareRequirementsOrCapabilities(requirements, requirementsFromResponse);
}
@@ -1221,13 +1497,17 @@ public class ImportToscaResourceTest extends ComponentBaseTest {
importReqDetails.setName("child");
importReqDetails.setTags(Arrays.asList(importReqDetails.getName()));
- importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, childFileName);
- RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ 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");
+ importReqDetails.setCapabilities(testResourcesPath, importReqDetails.getPayloadName(), sdncUserDetails,
+ "Compute");
Map<String, Object> capabilities = importReqDetails.getCapabilities();
- Map<String, Object> capabilitiesFromResponse = parseReqOrCapFromResponse("capabilities", importReqDetails, expectedNumOfCapabilities);
+ Map<String, Object> capabilitiesFromResponse = parseReqOrCapFromResponse("capabilities", importReqDetails,
+ expectedNumOfCapabilities);
assertEquals(capabilities.keySet().size(), capabilitiesFromResponse.keySet().size());
importReqDetails.compareRequirementsOrCapabilities(capabilities, capabilitiesFromResponse);
}
@@ -1239,15 +1519,20 @@ public class ImportToscaResourceTest extends ComponentBaseTest {
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);
+ 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);
+ 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);
+ 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);
+ RestResponse changeResourceState3 = LifecycleRestUtils.changeResourceState(importReqDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.TESTER), LifeCycleStatesEnum.CERTIFY);
assertEquals(STATUS_CODE_SUCCESS, changeResourceState3.getErrorCode().intValue());
String derivedFromName = importReqDetails.getName();
@@ -1255,13 +1540,16 @@ public class ImportToscaResourceTest extends ComponentBaseTest {
importReqDetails = ElementFactory.getDefaultImportResource();
importReqDetails.setName("child");
importReqDetails.setTags(Arrays.asList(importReqDetails.getName()));
- importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, childFileName);
+ 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);
+ importReqDetails.setRequirements(testResourcesPath, importReqDetails.getPayloadName(), sdncUserDetails,
+ derivedFromName);
Map<String, Object> requirements = importReqDetails.getRequirements();
- Map<String, Object> requirementsFromResponse = parseReqOrCapFromResponse("requirements", importReqDetails, expectedNumOfRequirements);
+ Map<String, Object> requirementsFromResponse = parseReqOrCapFromResponse("requirements", importReqDetails,
+ expectedNumOfRequirements);
assertEquals(requirements.keySet().size(), requirementsFromResponse.keySet().size());
importReqDetails.compareRequirementsOrCapabilities(requirements, requirementsFromResponse);
@@ -1274,15 +1562,20 @@ public class ImportToscaResourceTest extends ComponentBaseTest {
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);
+ 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);
+ 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);
+ 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);
+ RestResponse changeResourceState3 = LifecycleRestUtils.changeResourceState(importReqDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.TESTER), LifeCycleStatesEnum.CERTIFY);
assertEquals(STATUS_CODE_SUCCESS, changeResourceState3.getErrorCode().intValue());
String derivedFromName = importReqDetails.getName();
@@ -1290,13 +1583,16 @@ public class ImportToscaResourceTest extends ComponentBaseTest {
importReqDetails = ElementFactory.getDefaultImportResource();
importReqDetails.setName("child");
importReqDetails.setTags(Arrays.asList(importReqDetails.getName()));
- importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, childFileName);
+ 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);
+ importReqDetails.setRequirements(testResourcesPath, importReqDetails.getPayloadName(), sdncUserDetails,
+ derivedFromName);
Map<String, Object> requirements = importReqDetails.getRequirements();
- Map<String, Object> requirementsFromResponse = parseReqOrCapFromResponse("requirements", importReqDetails, expectedNumOfRequirements);
+ Map<String, Object> requirementsFromResponse = parseReqOrCapFromResponse("requirements", importReqDetails,
+ expectedNumOfRequirements);
assertEquals(requirements.keySet().size(), requirementsFromResponse.keySet().size());
importReqDetails.compareRequirementsOrCapabilities(requirements, requirementsFromResponse);
}
@@ -1310,15 +1606,20 @@ public class ImportToscaResourceTest extends ComponentBaseTest {
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);
+ 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);
+ 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);
+ 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);
+ RestResponse changeResourceState3 = LifecycleRestUtils.changeResourceState(importReqDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.TESTER), LifeCycleStatesEnum.CERTIFY);
assertEquals(STATUS_CODE_SUCCESS, changeResourceState3.getErrorCode().intValue());
String fatherUniqueId = importReqDetails.getUniqueId();
@@ -1328,26 +1629,30 @@ public class ImportToscaResourceTest extends ComponentBaseTest {
importReqDetails = ElementFactory.getDefaultImportResource();
importReqDetails.setName("child");
importReqDetails.setTags(Arrays.asList(importReqDetails.getName()));
- importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, childFileName);
+ 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());
+ 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);
+ 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);
+ Map<String, Object> capabilitiesFromResponse = parseReqOrCapFromResponse("capabilities", importReqDetailsFather,
+ expectedNumOfCapabilities);
assertEquals(capabilities.keySet().size(), capabilitiesFromResponse.keySet().size());
importReqDetailsFather.compareRequirementsOrCapabilities(capabilities, capabilitiesFromResponse);
}
@@ -1360,15 +1665,20 @@ public class ImportToscaResourceTest extends ComponentBaseTest {
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);
+ 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);
+ 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);
+ 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);
+ RestResponse changeResourceState3 = LifecycleRestUtils.changeResourceState(importReqDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.TESTER), LifeCycleStatesEnum.CERTIFY);
assertEquals(STATUS_CODE_SUCCESS, changeResourceState3.getErrorCode().intValue());
String derivedFromName = importReqDetails.getName();
@@ -1376,19 +1686,24 @@ public class ImportToscaResourceTest extends ComponentBaseTest {
importReqDetails = ElementFactory.getDefaultImportResource();
importReqDetails.setName("child");
importReqDetails.setTags(Arrays.asList(importReqDetails.getName()));
- importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, childFileName);
+ 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);
+ importReqDetails.setRequirements(testResourcesPath, importReqDetails.getPayloadName(), sdncUserDetails,
+ derivedFromName);
Map<String, Object> requirements = importReqDetails.getRequirements();
- Map<String, Object> requirementsFromResponse = parseReqOrCapFromResponse("requirements", importReqDetails, expectedNumOfRequirements);
+ 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);
+ importReqDetails.setCapabilities(testResourcesPath, importReqDetails.getPayloadName(), sdncUserDetails,
+ derivedFromName);
Map<String, Object> capabilities = importReqDetails.getCapabilities();
- Map<String, Object> capabilitiesFromResponse = parseReqOrCapFromResponse("capabilities", importReqDetails, expectedNumOfCapabilities);
+ Map<String, Object> capabilitiesFromResponse = parseReqOrCapFromResponse("capabilities", importReqDetails,
+ expectedNumOfCapabilities);
assertEquals(capabilities.keySet().size(), capabilitiesFromResponse.keySet().size());
importReqDetails.compareRequirementsOrCapabilities(capabilities, capabilitiesFromResponse);
}
@@ -1401,15 +1716,20 @@ public class ImportToscaResourceTest extends ComponentBaseTest {
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);
+ 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);
+ 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);
+ 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);
+ RestResponse changeResourceState3 = LifecycleRestUtils.changeResourceState(importReqDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.TESTER), LifeCycleStatesEnum.CERTIFY);
assertEquals(STATUS_CODE_SUCCESS, changeResourceState3.getErrorCode().intValue());
String derivedFromName = importReqDetails.getName();
@@ -1417,19 +1737,24 @@ public class ImportToscaResourceTest extends ComponentBaseTest {
importReqDetails = ElementFactory.getDefaultImportResource();
importReqDetails.setName("child");
importReqDetails.setTags(Arrays.asList(importReqDetails.getName()));
- importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, childFileName);
+ 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);
+ importReqDetails.setRequirements(testResourcesPath, importReqDetails.getPayloadName(), sdncUserDetails,
+ derivedFromName);
Map<String, Object> requirements = importReqDetails.getRequirements();
- Map<String, Object> requirementsFromResponse = parseReqOrCapFromResponse("requirements", importReqDetails, expectedNumOfRequirements);
+ 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);
+ importReqDetails.setCapabilities(testResourcesPath, importReqDetails.getPayloadName(), sdncUserDetails,
+ derivedFromName);
Map<String, Object> capabilities = importReqDetails.getCapabilities();
- Map<String, Object> capabilitiesFromResponse = parseReqOrCapFromResponse("capabilities", importReqDetails, expectedNumOfCapabilities);
+ Map<String, Object> capabilitiesFromResponse = parseReqOrCapFromResponse("capabilities", importReqDetails,
+ expectedNumOfCapabilities);
assertEquals(capabilities.keySet().size(), capabilitiesFromResponse.keySet().size());
importReqDetails.compareRequirementsOrCapabilities(capabilities, capabilitiesFromResponse);
}
@@ -1443,15 +1768,20 @@ public class ImportToscaResourceTest extends ComponentBaseTest {
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);
+ 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);
+ 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);
+ 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);
+ RestResponse changeResourceState3 = LifecycleRestUtils.changeResourceState(importReqDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.TESTER), LifeCycleStatesEnum.CERTIFY);
assertEquals(STATUS_CODE_SUCCESS, changeResourceState3.getErrorCode().intValue());
String fatherUniqueId = importReqDetails.getUniqueId();
@@ -1460,25 +1790,29 @@ public class ImportToscaResourceTest extends ComponentBaseTest {
importReqDetails = ElementFactory.getDefaultImportResource();
importReqDetails.setName("child");
importReqDetails.setTags(Arrays.asList(importReqDetails.getName()));
- importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, childFileName);
+ 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());
+ 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);
+ 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);
+ Map<String, Object> capabilitiesFromResponse = parseReqOrCapFromResponse("capabilities", importReqDetailsFather,
+ expectedNumOfCapabilities);
assertEquals(capabilities.keySet().size(), capabilitiesFromResponse.keySet().size());
importReqDetailsFather.compareRequirementsOrCapabilities(capabilities, capabilitiesFromResponse);
}
@@ -1490,12 +1824,15 @@ public class ImportToscaResourceTest extends ComponentBaseTest {
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);
+ 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());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_CAPABILITY_TYPE.name(), variables,
+ importResourceResponse.getResponse());
}
@@ -1508,45 +1845,58 @@ public class ImportToscaResourceTest extends ComponentBaseTest {
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);
+ 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);
+ 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);
+ 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);
+ 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);
+ 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);
+ 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);
+ 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);
+ importReqDetails.setRequirements(testResourcesPath, importReqDetails.getPayloadName(), sdncUserDetails,
+ derivedFromName);
Map<String, Object> requirements = importReqDetails.getRequirements();
- Map<String, Object> twinRequirementsFromResponse = parseReqOrCapFromResponse("requirements", importReqDetails, expectedNumOfRequirements);
+ 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);
+ importReqDetails.setCapabilities(testResourcesPath, importReqDetails.getPayloadName(), sdncUserDetails,
+ derivedFromName);
Map<String, Object> capabilities = importReqDetails.getCapabilities();
- Map<String, Object> twinCapabilitiesFromResponse = parseReqOrCapFromResponse("capabilities", importReqDetails, expectedNumOfCapabilities);
+ Map<String, Object> twinCapabilitiesFromResponse = parseReqOrCapFromResponse("capabilities", importReqDetails,
+ expectedNumOfCapabilities);
assertEquals(capabilities.keySet().size(), twinCapabilitiesFromResponse.keySet().size());
importReqDetails.compareRequirementsOrCapabilities(capabilities, twinCapabilitiesFromResponse);
@@ -1562,7 +1912,8 @@ public class ImportToscaResourceTest extends ComponentBaseTest {
// create resource
importReqDetails.setName("import");
String invariantUuidDefinedByUser = "abcd1234";
- RestResponse importResourceResponse = importResourceWithRequestedInvariantUuid(importReqDetails, invariantUuidDefinedByUser);
+ RestResponse importResourceResponse = importResourceWithRequestedInvariantUuid(importReqDetails,
+ invariantUuidDefinedByUser);
String invariantUUIDcreation = ResponseParser.getInvariantUuid(importResourceResponse);
assertFalse(checkInvariantUuidEqual(invariantUuidDefinedByUser, importResourceResponse));
@@ -1571,94 +1922,114 @@ public class ImportToscaResourceTest extends ComponentBaseTest {
assertTrue(checkInvariantUuidEqual(invariantUUIDcreation, getResource));
// checkin resource
- RestResponse changeResourceState = LifecycleRestUtils.changeResourceState(importReqDetails, sdncUserDetails, LifeCycleStatesEnum.CHECKIN);
+ 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);
+ 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);
+ 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);
+ 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);
+ 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);
+ 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);
+ 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);
+ 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());
+ 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());
+ 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);
+ 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);
+ 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);
+ 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);
+ 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);
+ 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);
+ 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);
+ 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);
+ changeResourceState = LifecycleRestUtils.changeResourceState(importReqDetails, sdncUserDetails,
+ LifeCycleStatesEnum.CHECKOUT);
ArtifactReqDetails artifactDetails = ElementFactory.getDefaultArtifact();
- ArtifactRestUtils.addInformationalArtifactToResource(artifactDetails, sdncUserDetails, importReqDetails.getUniqueId());
+ ArtifactRestUtils.addInformationalArtifactToResource(artifactDetails, sdncUserDetails,
+ importReqDetails.getUniqueId());
assertEquals(STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue());
assertTrue(checkInvariantUuidEqual(invariantUUIDcreation, changeResourceState));
@@ -1666,8 +2037,10 @@ public class ImportToscaResourceTest extends ComponentBaseTest {
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);
+ 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));
@@ -1681,14 +2054,16 @@ public class ImportToscaResourceTest extends ComponentBaseTest {
@Test
public void checkCPHasImmutableInvariantUuidTest() throws Exception {
String filename = "FatherHasNoReqCap.yml";
- importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, filename);
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath,
+ filename);
checkResourceHasImmutableInvariantUuidTest(importReqDetails);
}
@Test
public void checkVFCHasImmutableInvariantUuidTest() throws Exception {
String filename = "computeCap11.yml";
- importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, filename);
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath,
+ filename);
checkResourceHasImmutableInvariantUuidTest(importReqDetails);
}
@@ -1713,17 +2088,21 @@ public class ImportToscaResourceTest extends ComponentBaseTest {
checkInvariantUuidIsImmutableInDifferentAction(importReqDetails);
}
- private static RestResponse importResourceWithRequestedInvariantUuid(ImportReqDetails importDetails, String invariantUuid) throws Exception {
+ private static RestResponse importResourceWithRequestedInvariantUuid(ImportReqDetails importDetails,
+ String invariantUuid) throws Exception {
importDetails.setInvariantUUID(invariantUuid);
- RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importDetails, sdncUserDetails, null);
+ 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 {
+ 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);
+ Map<String, Object> parsedFieldFromResponseToMap = ResponseParser.getJsonValueAsMap(getResource,
+ parsedFieldName);
Iterator<String> iterator = parsedFieldFromResponseToMap.keySet().iterator();
actualNumOfReqOrCap = 0;
while (iterator.hasNext()) {
@@ -1746,81 +2125,98 @@ public class ImportToscaResourceTest extends ComponentBaseTest {
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"));
+ 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"));
+ 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"));
+ 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"));
+ 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"));
+ 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"));
+ 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"));
+ 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\",\"$?^@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"));
+ 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"));
+ 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"));
+ 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"));
+ 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"));
+ 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"));
+ 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":
@@ -1850,31 +2246,36 @@ public class ImportToscaResourceTest extends ComponentBaseTest {
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"));
+ 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"));
+ 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"));
+ 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"));
+ 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"));
+ assertTrue("Check entrySchema Property Type ",
+ pro.getSchema().getProperty().getType().equals("boolean"));
isPropertyAppear = true;
break;
case "float_null_value":
@@ -2001,307 +2402,391 @@ public class ImportToscaResourceTest extends ComponentBaseTest {
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"));
+ 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"));
+ 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"));
+ 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"));
+ 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"));
+ 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"));
+ 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"));
+ 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"));
+ 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"));
+ 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"));
+ 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"));
+ 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"));
+ 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"));
+ 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"));
+ 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"));
+ 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"));
+ 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"));
+ 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"));
+ 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"));
+ 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"));
+ 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"));
+ 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"));
+ 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"));
+ 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"));
+ 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"));
+ 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"));
+ 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"));
+ 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"));
+ 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"));
+ 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"));
+ 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"));
+ 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"));
+ 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"));
+ 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"));
+ 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"));
+ 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"));
+ 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"));
+ 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"));
+ 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"));
+ 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"));
+ 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"));
+ 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"));
+ 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"));
+ 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"));
+ 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 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 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 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 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 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 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 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;
@@ -2313,7 +2798,8 @@ public class ImportToscaResourceTest extends ComponentBaseTest {
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 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;
@@ -2325,7 +2811,8 @@ public class ImportToscaResourceTest extends ComponentBaseTest {
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 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;
@@ -2340,11 +2827,15 @@ public class ImportToscaResourceTest extends ComponentBaseTest {
public void importToscaResourceAttributeSuccessFlow() throws Exception {
String fileName = importAttributeSuccess;
- importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, fileName);
- RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ 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()));
+ Resource resourceJavaObject = ResponseParser
+ .convertResourceResponseToJavaObject(importResourceResponse.getResponse());
+ ToscaNodeTypeInfo parseToscaNodeYaml = utils
+ .parseToscaNodeYaml(Decoder.decode(importReqDetails.getPayloadData()));
HashMap<String, AttributeDefinition> attr = new HashMap<>();
@@ -2379,13 +2870,14 @@ public class ImportToscaResourceTest extends ComponentBaseTest {
// verify Resource Attributes
validateResourceAttribute(resourceJavaObject, attr);
- // TO DO
- ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultImportResourceAuditMsgSuccess();
+ 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);
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject,
+ AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false);
}
private void validateResourceAttribute(Resource resource, Map<String, AttributeDefinition> attr) {
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
index 9e8b94e5a8..464ebe12ed 100644
--- 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
@@ -21,6 +21,7 @@
package org.openecomp.sdc.ci.tests.execute.imports;
import static org.testng.AssertJUnit.assertTrue;
+import static org.testng.AssertJUnit.assertEquals;
import java.nio.file.Files;
import java.nio.file.Path;
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
index 345b81eb3e..b71240b527 100644
--- 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
@@ -20,24 +20,33 @@
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;
@@ -48,6 +57,7 @@ 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;
@@ -55,6 +65,7 @@ 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;
@@ -164,6 +175,69 @@ public class InputsApiTests extends ComponentBaseTest {
}
/**
+ * 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
*
@@ -207,7 +281,40 @@ public class InputsApiTests extends ComponentBaseTest {
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
@@ -221,5 +328,80 @@ public class InputsApiTests extends ComponentBaseTest {
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
index e15652dddf..84bb5421ab 100644
--- 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
@@ -56,7 +56,7 @@ import org.testng.annotations.BeforeMethod;
/**
*
- * @author al714h
+ * @author alitvinsky
*
* resourceDetails - create, Add Heat, certify resourceDetails1 - create
* resource, LCS - CheckOut serviceDetails - create, add RI from
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
new file mode 100644
index 0000000000..53f1fd20d5
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/lifecycle/ServiceCertWithoutDeploymentArtifacts.java
@@ -0,0 +1,65 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.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/product/ProductBaseTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductBaseTest.java
index 7891f4a46b..623b29b8e6 100644
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductBaseTest.java
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductBaseTest.java
@@ -85,9 +85,11 @@ public abstract class ProductBaseTest extends ComponentBaseTest {
defaultCategories = createCategoriesChain(definitionsList);
}
- private List<CategoryDefinition> createCategoriesChain(List<CategoryDefinition> categoryDefinitions) throws Exception {
+ private List<CategoryDefinition> createCategoriesChain(List<CategoryDefinition> categoryDefinitions)
+ throws Exception {
for (CategoryDefinition categoryDefinition : categoryDefinitions) {
- RestResponse createCategory = CategoryRestUtils.createCategory(categoryDefinition, productStrategistUser1, PRODUCT_COMPONENT_TYPE);
+ RestResponse createCategory = CategoryRestUtils.createCategory(categoryDefinition, productStrategistUser1,
+ PRODUCT_COMPONENT_TYPE);
int status = createCategory.getErrorCode().intValue();
if (status == BaseRestUtils.STATUS_CODE_CREATED) {
String categoryId = ResponseParser.getUniqueIdFromResponse(createCategory);
@@ -95,7 +97,8 @@ public abstract class ProductBaseTest extends ComponentBaseTest {
}
List<SubCategoryDefinition> subcategories = categoryDefinition.getSubcategories();
for (SubCategoryDefinition subCategoryDefinition : subcategories) {
- RestResponse createSubCategory = CategoryRestUtils.createSubCategory(subCategoryDefinition, categoryDefinition, productStrategistUser1, PRODUCT_COMPONENT_TYPE);
+ RestResponse createSubCategory = CategoryRestUtils.createSubCategory(subCategoryDefinition,
+ categoryDefinition, productStrategistUser1, PRODUCT_COMPONENT_TYPE);
status = createSubCategory.getErrorCode().intValue();
if (status == BaseRestUtils.STATUS_CODE_CREATED) {
String subCategoryId = ResponseParser.getUniqueIdFromResponse(createSubCategory);
@@ -103,7 +106,8 @@ public abstract class ProductBaseTest extends ComponentBaseTest {
}
List<GroupingDefinition> groupings = subCategoryDefinition.getGroupings();
for (GroupingDefinition groupingDefinition : groupings) {
- RestResponse createGroupingRest = CategoryRestUtils.createGrouping(groupingDefinition, subCategoryDefinition, categoryDefinition, productStrategistUser1, PRODUCT_COMPONENT_TYPE);
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(groupingDefinition,
+ subCategoryDefinition, categoryDefinition, productStrategistUser1, PRODUCT_COMPONENT_TYPE);
status = createGroupingRest.getErrorCode().intValue();
if (status == BaseRestUtils.STATUS_CODE_CREATED) {
String groupingId = ResponseParser.getUniqueIdFromResponse(createGroupingRest);
@@ -114,8 +118,9 @@ public abstract class ProductBaseTest extends ComponentBaseTest {
}
RestResponse allCategories = CategoryRestUtils.getAllCategories(productStrategistUser1, PRODUCT_COMPONENT_TYPE);
Gson gson = new Gson();
- List<CategoryDefinition> res = gson.fromJson(allCategories.getResponse(), new TypeToken<List<CategoryDefinition>>() {
- }.getType());
+ List<CategoryDefinition> res = gson.fromJson(allCategories.getResponse(),
+ new TypeToken<List<CategoryDefinition>>() {
+ }.getType());
return res;
}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCheckoutTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCheckoutTest.java
index ec1f7ad38d..efb4a15255 100644
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCheckoutTest.java
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCheckoutTest.java
@@ -34,6 +34,7 @@ import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedProductAudit;
import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
import org.openecomp.sdc.ci.tests.utils.DbUtils;
+import org.openecomp.sdc.ci.tests.utils.Utils;
import org.openecomp.sdc.ci.tests.utils.general.Convertor;
import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils;
import org.openecomp.sdc.ci.tests.utils.rest.ProductRestUtils;
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductComponentInstanceCRUDTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductComponentInstanceCRUDTest.java
index ec3d9b75a5..fe5a6e34f9 100644
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductComponentInstanceCRUDTest.java
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductComponentInstanceCRUDTest.java
@@ -106,17 +106,13 @@ public class ProductComponentInstanceCRUDTest extends ComponentInstanceBaseTest
// addresourceDetailsCP_02 ,resourceDetailsVFC_02 and
// resourceDetailsVL_02 to resourceDetailsVF_02 check-in VF
- RestResponse createAtomicResourceInstance = createAtomicInstanceForVFDuringSetup(resourceDetailsVF_02,
- resourceDetailsVFC_02, sdncDesignerDetails);
+ RestResponse createAtomicResourceInstance = createAtomicInstanceForVFDuringSetup(resourceDetailsVF_02, resourceDetailsVFC_02, sdncDesignerDetails);
ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance);
- createAtomicResourceInstance = createAtomicInstanceForVFDuringSetup(resourceDetailsVF_02, resourceDetailsCP_02,
- sdncDesignerDetails);
+ createAtomicResourceInstance = createAtomicInstanceForVFDuringSetup(resourceDetailsVF_02, resourceDetailsCP_02, sdncDesignerDetails);
ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance);
- createAtomicResourceInstance = createAtomicInstanceForVFDuringSetup(resourceDetailsVF_02, resourceDetailsVL_02,
- sdncDesignerDetails);
+ createAtomicResourceInstance = createAtomicInstanceForVFDuringSetup(resourceDetailsVF_02, resourceDetailsVL_02, sdncDesignerDetails);
ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance);
- RestResponse restResponse = LifecycleRestUtils.changeResourceState(resourceDetailsVF_02, sdncDesignerDetails,
- LifeCycleStatesEnum.CHECKIN);
+ RestResponse restResponse = LifecycleRestUtils.changeResourceState(resourceDetailsVF_02, sdncDesignerDetails, LifeCycleStatesEnum.CHECKIN);
resourceDetailsVF_02.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
// addresourceDetailsCP_01 ,resourceDetailsVFC_01 and
// resourceDetailsVL_01 to resourceDetailsVF_01 and certify
@@ -130,19 +126,16 @@ public class ProductComponentInstanceCRUDTest extends ComponentInstanceBaseTest
// has
// check-in
// VF
- restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
- LifeCycleStatesEnum.CHECKIN);
+ restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, LifeCycleStatesEnum.CHECKIN);
ResourceRestUtils.checkSuccess(restResponse);
- restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_02, sdncDesignerDetails,
- LifeCycleStatesEnum.CHECKIN);
+ restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_02, sdncDesignerDetails, LifeCycleStatesEnum.CHECKIN);
ResourceRestUtils.checkSuccess(restResponse);
}
// pass
@Test
public void createServiceInstanceTest() throws Exception {
- RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
- sdncPmDetails1);
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
getComponentAndValidateRIs(productDetails_01, 1, 0);
}
@@ -151,33 +144,27 @@ public class ProductComponentInstanceCRUDTest extends ComponentInstanceBaseTest
@Test(enabled = false)
public void createServiceInstanceFromCheckedOutState() throws Exception {
// can't create instance of checked-out component
- RestResponse restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
- LifeCycleStatesEnum.CHECKOUT);
+ RestResponse restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, LifeCycleStatesEnum.CHECKOUT);
ResourceRestUtils.checkSuccess(restResponse);
- RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
- sdncPmDetails1);
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
getComponentAndValidateRIs(productDetails_01, 1, 0);
}
@Test
public void createServiceInstanceInToAnotherServiceInstance() throws Exception {
- RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02,
- sdncPmDetails1);
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
String uniqueIdFromResponse = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp);
getComponentAndValidateRIs(productDetails_01, 1, 0);
- ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory
- .getComponentResourceInstance(serviceDetails_01);
- createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails,
- sdncPmDetails1, uniqueIdFromResponse, ComponentTypeEnum.PRODUCT);
+ ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01);
+ createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, uniqueIdFromResponse, ComponentTypeEnum.PRODUCT);
assertTrue(createServiceInstanceResp.getErrorCode() == STATUS_CODE_NOT_FOUND);
}
@Test
public void createSeveralServiceInstanceFromSameServices() throws Exception {
- RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
- sdncPmDetails1);
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
@@ -186,8 +173,7 @@ public class ProductComponentInstanceCRUDTest extends ComponentInstanceBaseTest
@Test
public void createSeveralServiceInstanceFromDifferentServices() throws Exception {
- RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
- sdncPmDetails1);
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
@@ -197,22 +183,18 @@ public class ProductComponentInstanceCRUDTest extends ComponentInstanceBaseTest
@Test
public void createCertifiedServiceInstance() throws Exception {
changeServiceStateToCertified(serviceDetails_01);
- RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
- sdncPmDetails1);
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
getComponentAndValidateRIs(productDetails_01, 1, 0);
}
@Test
public void createServiceInstanceByPm() throws Exception {
- RestResponse restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
- LifeCycleStatesEnum.CHECKIN);
+ RestResponse restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, LifeCycleStatesEnum.CHECKIN);
ResourceRestUtils.checkSuccess(restResponse);
- restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
- LifeCycleStatesEnum.CHECKOUT);
+ restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, LifeCycleStatesEnum.CHECKOUT);
ResourceRestUtils.checkSuccess(restResponse);
- RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
- sdncPmDetails1);
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
getComponentAndValidateRIs(productDetails_01, 1, 0);
}
@@ -220,51 +202,43 @@ public class ProductComponentInstanceCRUDTest extends ComponentInstanceBaseTest
@Test
public void createServiceInstanceWithoutVf() throws Exception {
LifecycleRestUtils.changeServiceState(serviceDetails_03, sdncAdminDetails, "0.1", LifeCycleStatesEnum.CHECKIN);
- RestResponse createServiceInstanceResp = createServiceInstance(productDetails_02, serviceDetails_03,
- sdncPmDetails1);
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_02, serviceDetails_03, sdncPmDetails1);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
getComponentAndValidateRIs(productDetails_02, 1, 0);
}
@Test
public void createServiceInstanceByNonProductOwner() throws Exception {
- RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
- sdncPmDetails1);
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails2);
assertTrue(createServiceInstanceResp.getErrorCode() == STATUS_CODE_RESTRICTED_OPERATION);
- ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(),
- createServiceInstanceResp.getResponse());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(), createServiceInstanceResp.getResponse());
getComponentAndValidateRIs(productDetails_01, 1, 0);
}
@Test
public void createServiceInstanceByNonAsdcUser() throws Exception {
- RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
- sdncPmDetails1);
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
User nonExistingSdncUser = ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_MANAGER1);
;
nonExistingSdncUser.setUserId("bt1234");
createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, nonExistingSdncUser);
assertTrue(createServiceInstanceResp.getErrorCode() == STATUS_CODE_RESTRICTED_OPERATION);
- ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(),
- createServiceInstanceResp.getResponse());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(), createServiceInstanceResp.getResponse());
getComponentAndValidateRIs(productDetails_01, 1, 0);
}
@Test
public void createServiceInstanceToNotCheckOutProduct() throws Exception {
- RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
- sdncPmDetails1);
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
- RestResponse restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
- LifeCycleStatesEnum.CHECKIN);
+ RestResponse restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, LifeCycleStatesEnum.CHECKIN);
ResourceRestUtils.checkSuccess(restResponse);
createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
assertTrue(createServiceInstanceResp.getErrorCode() == STATUS_CODE_RESTRICTED_OPERATION);
- ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(),
- createServiceInstanceResp.getResponse());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(), createServiceInstanceResp.getResponse());
getComponentAndValidateRIs(productDetails_01, 1, 0);
}
@@ -274,25 +248,19 @@ public class ProductComponentInstanceCRUDTest extends ComponentInstanceBaseTest
String expectedServiceInstanceName = serviceDetails_01.getName() + " 1";
String expectedServiceInstancenormalizedName = serviceDetails_01.getName() + "1";
serviceDetails_01.setName("");
- RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
- sdncPmDetails1);
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
- String instanceNormalizedName = ResponseParser.getValueFromJsonResponse(createServiceInstanceResp.getResponse(),
- "normalizedName");
+ String instanceNormalizedName = ResponseParser.getValueFromJsonResponse(createServiceInstanceResp.getResponse(), "normalizedName");
String instanceName = ResponseParser.getValueFromJsonResponse(createServiceInstanceResp.getResponse(), "name");
- assertEquals("check Resource Instance normalizedName ", (expectedServiceInstancenormalizedName).toLowerCase(),
- instanceNormalizedName);
+ assertEquals("check Resource Instance normalizedName ", (expectedServiceInstancenormalizedName).toLowerCase(), instanceNormalizedName);
assertEquals("check Resource Instance Name ", expectedServiceInstanceName, instanceName);
getComponentAndValidateRIs(productDetails_01, 1, 0);
// get product and verify that service instanceName is correct
- RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(),
- sdncPmDetails1.getUserId());
- Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(),
- Product.class);
+ RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(), sdncPmDetails1.getUserId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(), Product.class);
ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0);
assertEquals(expectedServiceInstanceName, actualComponentInstance.getName());
- assertEquals((expectedServiceInstancenormalizedName).toLowerCase(),
- actualComponentInstance.getNormalizedName());
+ assertEquals((expectedServiceInstancenormalizedName).toLowerCase(), actualComponentInstance.getNormalizedName());
}
// pass
@@ -301,116 +269,91 @@ public class ProductComponentInstanceCRUDTest extends ComponentInstanceBaseTest
String expectedServiceInstanceName = serviceDetails_01.getName() + " 1";
String expectedServiceInstancenormalizedName = serviceDetails_01.getName() + "1";
serviceDetails_01.setName(null);
- RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
- sdncPmDetails1);
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
- String instanceNormalizedName = ResponseParser.getValueFromJsonResponse(createServiceInstanceResp.getResponse(),
- "normalizedName");
+ String instanceNormalizedName = ResponseParser.getValueFromJsonResponse(createServiceInstanceResp.getResponse(), "normalizedName");
String instanceName = ResponseParser.getValueFromJsonResponse(createServiceInstanceResp.getResponse(), "name");
- assertEquals("check Resource Instance normalizedName ", (expectedServiceInstancenormalizedName).toLowerCase(),
- instanceNormalizedName);
+ assertEquals("check Resource Instance normalizedName ", (expectedServiceInstancenormalizedName).toLowerCase(), instanceNormalizedName);
assertEquals("check Resource Instance Name ", expectedServiceInstanceName, instanceName);
getComponentAndValidateRIs(productDetails_01, 1, 0);
// get product and verify that service instanceName is correct
- RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(),
- sdncPmDetails1.getUserId());
- Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(),
- Product.class);
+ RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(), sdncPmDetails1.getUserId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(), Product.class);
ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0);
assertEquals(expectedServiceInstanceName, actualComponentInstance.getName());
- assertEquals((expectedServiceInstancenormalizedName).toLowerCase(),
- actualComponentInstance.getNormalizedName());
+ assertEquals((expectedServiceInstancenormalizedName).toLowerCase(), actualComponentInstance.getNormalizedName());
}
@Test(enabled = false)
public void createServiceInstanceToNonExistingProduct() throws Exception {
- RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
- sdncPmDetails1);
- ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
- ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory
- .getComponentResourceInstance(serviceDetails_01);
- createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails,
- sdncPmDetails1, "blabla", ComponentTypeEnum.PRODUCT);
- AssertJUnit.assertEquals("Check response code ", STATUS_CODE_NOT_FOUND,
- createServiceInstanceResp.getErrorCode().intValue());
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01);
+ createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, "blabla", ComponentTypeEnum.PRODUCT);
+ AssertJUnit.assertEquals("Check response code ", STATUS_CODE_NOT_FOUND, createServiceInstanceResp.getErrorCode().intValue());
ArrayList<String> varibales = new ArrayList<String>();
varibales.add("blabla");
- ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.PRODUCT_NOT_FOUND.name(), varibales,
- createServiceInstanceResp.getResponse());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.PRODUCT_NOT_FOUND.name(), varibales, createServiceInstanceResp.getResponse());
getComponentAndValidateRIs(productDetails_01, 1, 0);
}
@Test
public void createServiceInstanceToNonSupportedComponentType() throws Exception {
- RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
- sdncPmDetails1);
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
- ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory
- .getComponentResourceInstance(serviceDetails_01);
- createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails,
- sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.RESOURCE_INSTANCE);
+ ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01);
+ createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.RESOURCE_INSTANCE);
assertTrue(createServiceInstanceResp.getErrorCode() == STATUS_CODE_UNSUPPORTED_ERROR);
ArrayList<String> varibales = new ArrayList<String>();
varibales.add("null");
- ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.UNSUPPORTED_ERROR.name(), varibales,
- createServiceInstanceResp.getResponse());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.UNSUPPORTED_ERROR.name(), varibales, createServiceInstanceResp.getResponse());
getComponentAndValidateRIs(productDetails_01, 1, 0);
}
// pass
@Test
public void createServiceInstancePositionIsEmpty() throws Exception {
- ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory
- .getComponentResourceInstance(serviceDetails_01);
+ ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01);
serviceInstanceReqDetails.setPosX("");
serviceInstanceReqDetails.setPosY("");
- RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(
- serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
- ComponentInstance componentInstance = ResponseParser
- .parseToObjectUsingMapper(createServiceInstanceResp.getResponse(), ComponentInstance.class);
+ ComponentInstance componentInstance = ResponseParser.parseToObjectUsingMapper(createServiceInstanceResp.getResponse(), ComponentInstance.class);
addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.PRODUCT);
getComponentAndValidateRIs(productDetails_01, 1, 0);
}
@Test
public void createServiceInstancePositionIsNull() throws Exception {
- ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory
- .getComponentResourceInstance(serviceDetails_01);
+ ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01);
serviceInstanceReqDetails.setPosX(null);
serviceInstanceReqDetails.setPosY(null);
- RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(
- serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
- ComponentInstance componentInstance = ResponseParser
- .parseToObjectUsingMapper(createServiceInstanceResp.getResponse(), ComponentInstance.class);
+ ComponentInstance componentInstance = ResponseParser.parseToObjectUsingMapper(createServiceInstanceResp.getResponse(), ComponentInstance.class);
addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.PRODUCT);
getComponentAndValidateRIs(productDetails_01, 1, 0);
}
@Test
public void createServiceInstanceByDesigner() throws Exception {
- RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
- sdncPmDetails1);
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncDesignerDetails);
assertTrue(createServiceInstanceResp.getErrorCode() == STATUS_CODE_RESTRICTED_OPERATION);
- ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(),
- createServiceInstanceResp.getResponse());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(), createServiceInstanceResp.getResponse());
getComponentAndValidateRIs(productDetails_01, 1, 0);
}
@Test
public void createServiceInstanceUserIdIsEmpty() throws Exception {
- RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
- sdncPmDetails1);
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
User nonSdncDetails = ElementFactory.getDefaultUser(UserRoleEnum.TESTER);
nonSdncDetails.setUserId("");
createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, nonSdncDetails);
assertTrue(createServiceInstanceResp.getErrorCode() == STATUS_CODE_MISSING_INFORMATION);
- ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_INFORMATION.name(), new ArrayList<String>(),
- createServiceInstanceResp.getResponse());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_INFORMATION.name(), new ArrayList<String>(), createServiceInstanceResp.getResponse());
getComponentAndValidateRIs(productDetails_01, 1, 0);
}
@@ -419,34 +362,25 @@ public class ProductComponentInstanceCRUDTest extends ComponentInstanceBaseTest
@Test
public void updateServiceInstanceNameByPm() throws Exception {
// Check-in Product by PM and Check-out by PM
- RestResponse restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
- LifeCycleStatesEnum.CHECKIN);
+ RestResponse restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, LifeCycleStatesEnum.CHECKIN);
ResourceRestUtils.checkSuccess(restResponse);
- restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
- LifeCycleStatesEnum.CHECKOUT);
+ restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, LifeCycleStatesEnum.CHECKOUT);
ResourceRestUtils.checkSuccess(restResponse);
// Create service instance by PM
- ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory
- .getComponentResourceInstance(serviceDetails_01);
- RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(
- serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01);
+ RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
String newName = "abcD";
serviceInstanceReqDetails.setName(newName);
- RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
- serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
ResourceRestUtils.checkSuccess(updateServiceInstanceResponse);
- String instanceNormalizedName = ResponseParser
- .getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "normalizedName");
- String instanceName = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(),
- "name");
+ String instanceNormalizedName = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "normalizedName");
+ String instanceName = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "name");
assertEquals("check Resource Instance normalizedName ", (newName).toLowerCase(), instanceNormalizedName);
assertEquals("check Resource Instance Name ", newName, instanceName);
// get product and verify that service instanceName is correct
- RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(),
- sdncPmDetails1.getUserId());
- Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(),
- Product.class);
+ RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(), sdncPmDetails1.getUserId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(), Product.class);
ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0);
assertEquals(newName, actualComponentInstance.getName());
assertEquals((newName).toLowerCase(), actualComponentInstance.getNormalizedName());
@@ -454,23 +388,18 @@ public class ProductComponentInstanceCRUDTest extends ComponentInstanceBaseTest
@Test
public void updateServiceInstanceNewNameAndLocation() throws Exception {
- ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory
- .getComponentResourceInstance(serviceDetails_01);
- RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(
- serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01);
+ RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
String newName = "updaatedName100";
serviceInstanceReqDetails.setPosX("100");
serviceInstanceReqDetails.setPosY("100");
serviceInstanceReqDetails.setName(newName);
- RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
- serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
ResourceRestUtils.checkSuccess(updateServiceInstanceResponse);
// get product and verify that service instanceName is correct
- RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(),
- sdncPmDetails1.getUserId());
- Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(),
- Product.class);
+ RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(), sdncPmDetails1.getUserId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(), Product.class);
ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0);
assertEquals(serviceInstanceReqDetails.getPosX(), actualComponentInstance.getPosX());
assertEquals(serviceInstanceReqDetails.getPosY(), actualComponentInstance.getPosY());
@@ -480,29 +409,21 @@ public class ProductComponentInstanceCRUDTest extends ComponentInstanceBaseTest
@Test(enabled = false)
public void updateServiceInstanceNameRemoveSpacesFromBiginningAndEnd() throws Exception {
- ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory
- .getComponentResourceInstance(serviceDetails_01);
- RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(
- serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01);
+ RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
String newName = " Abcd ";
String expectedNewName = " Abcd ";
serviceInstanceReqDetails.setName(newName);
- RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
- serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
ResourceRestUtils.checkSuccess(updateServiceInstanceResponse);
- String instanceNormalizedName = ResponseParser
- .getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "normalizedName");
- String instanceName = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(),
- "name");
- assertEquals("check Resource Instance normalizedName ", (expectedNewName).toLowerCase(),
- instanceNormalizedName);
+ String instanceNormalizedName = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "normalizedName");
+ String instanceName = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "name");
+ assertEquals("check Resource Instance normalizedName ", (expectedNewName).toLowerCase(), instanceNormalizedName);
assertEquals("check Resource Instance Name ", expectedNewName, instanceName);
// get product and verify that service instanceName is correct
- RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(),
- sdncPmDetails1.getUserId());
- Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(),
- Product.class);
+ RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(), sdncPmDetails1.getUserId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(), Product.class);
ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0);
assertEquals(expectedNewName, actualComponentInstance.getName());
assertEquals((expectedNewName).toLowerCase(), actualComponentInstance.getNormalizedName());
@@ -511,28 +432,21 @@ public class ProductComponentInstanceCRUDTest extends ComponentInstanceBaseTest
// pass
@Test
public void updateServiceInstanceNameAllowedCharacters() throws Exception {
- ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory
- .getComponentResourceInstance(serviceDetails_01);
- RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(
- serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01);
+ RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
String newName = "qwer-TYUIOP_asd_0987654321.Abcd";
String ExpectedNormalizName = "qwertyuiopasd0987654321abcd";
serviceInstanceReqDetails.setName(newName);
- RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
- serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
ResourceRestUtils.checkSuccess(updateServiceInstanceResponse);
- String instanceNormalizedName = ResponseParser
- .getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "normalizedName");
- String instanceName = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(),
- "name");
+ String instanceNormalizedName = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "normalizedName");
+ String instanceName = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "name");
assertEquals("check Resource Instance normalizedName ", ExpectedNormalizName, instanceNormalizedName);
assertEquals("check Resource Instance Name ", newName, instanceName);
// get product and verify that service instanceName is correct
- RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(),
- sdncPmDetails1.getUserId());
- Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(),
- Product.class);
+ RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(), sdncPmDetails1.getUserId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(), Product.class);
ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0);
assertEquals(newName, actualComponentInstance.getName());
assertEquals(ExpectedNormalizName, actualComponentInstance.getNormalizedName());
@@ -541,54 +455,40 @@ public class ProductComponentInstanceCRUDTest extends ComponentInstanceBaseTest
@Test
public void updateInstanceNameInvalidCharacters() throws Exception {
- char invalidChars[] = { '~', '!', '$', '%', '^', '*', '(', ')', '"', '{', '}', '[', ']', '?', '>', '<', '/',
- '|', '\\', ',' };
- ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory
- .getComponentResourceInstance(serviceDetails_01);
- RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(
- serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ char invalidChars[] = { '~', '!', '$', '%', '^', '*', '(', ')', '"', '{', '}', '[', ']', '?', '>', '<', '/', '|', '\\', ',' };
+ ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01);
+ RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
String newName = "Abcd1";
String updateName;
for (int i = 0; i < invalidChars.length; i++) {
updateName = newName + invalidChars[i];
serviceInstanceReqDetails.setName(updateName);
- RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
- serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(),
- ComponentTypeEnum.PRODUCT);
- assertEquals("Check response code ", STATUS_CODE_INVALID_CONTENT,
- updateServiceInstanceResponse.getErrorCode().intValue());
+ RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ assertEquals("Check response code ", STATUS_CODE_INVALID_CONTENT, updateServiceInstanceResponse.getErrorCode().intValue());
ArrayList<String> varibales = new ArrayList<String>();
varibales.add("Service Instance");
- ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_COMPONENT_NAME.name(), varibales,
- updateServiceInstanceResponse.getResponse());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_COMPONENT_NAME.name(), varibales, updateServiceInstanceResponse.getResponse());
}
}
// pass
@Test
public void updateInstanceNameMaxLength() throws Exception {
- ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory
- .getComponentResourceInstance(serviceDetails_01);
- RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(
- serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01);
+ RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
String newName = "Qwertyuiop1234567890asdfAhjklzxcvbnmasdfghjkl12345";
serviceInstanceReqDetails.setName(newName);
- RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
- serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
ResourceRestUtils.checkSuccess(updateServiceInstanceResponse);
- String instanceNormalizedName = ResponseParser
- .getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "normalizedName");
- String instanceName = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(),
- "name");
+ String instanceNormalizedName = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "normalizedName");
+ String instanceName = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "name");
assertEquals("check Resource Instance normalizedName ", (newName).toLowerCase(), instanceNormalizedName);
assertEquals("check Resource Instance Name ", newName, instanceName);
// get product and verify that service instanceName is correct
- RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(),
- sdncPmDetails1.getUserId());
- Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(),
- Product.class);
+ RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(), sdncPmDetails1.getUserId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(), Product.class);
ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0);
assertEquals(newName, actualComponentInstance.getName());
assertEquals((newName).toLowerCase(), actualComponentInstance.getNormalizedName());
@@ -596,30 +496,22 @@ public class ProductComponentInstanceCRUDTest extends ComponentInstanceBaseTest
@Test
public void updateInstanceNameExceedMaxLength() throws Exception {
- ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory
- .getComponentResourceInstance(serviceDetails_01);
- RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(
- serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01);
+ RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
String expectedName = ResponseParser.getValueFromJsonResponse(createServiceInstanceResp.getResponse(), "name");
- String expectedNormalizedName = ResponseParser.getValueFromJsonResponse(createServiceInstanceResp.getResponse(),
- "normalizedName");
+ String expectedNormalizedName = ResponseParser.getValueFromJsonResponse(createServiceInstanceResp.getResponse(), "normalizedName");
String newName = "Qwertyuiop1234567890asdfAhjklzxcvbnmasdfghjkl123456";
serviceInstanceReqDetails.setName(newName);
- RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
- serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
- assertEquals("Check response code ", STATUS_CODE_COMPONENT_NAME_EXCEEDS_LIMIT,
- updateServiceInstanceResponse.getErrorCode().intValue());
+ RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ assertEquals("Check response code ", STATUS_CODE_COMPONENT_NAME_EXCEEDS_LIMIT, updateServiceInstanceResponse.getErrorCode().intValue());
ArrayList<String> varibales = new ArrayList<String>();
varibales.add("Service Instance");
varibales.add("50");
- ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT.name(), varibales,
- updateServiceInstanceResponse.getResponse());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT.name(), varibales, updateServiceInstanceResponse.getResponse());
// get product and verify that service instanceName is correct
- RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(),
- sdncPmDetails1.getUserId());
- Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(),
- Product.class);
+ RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(), sdncPmDetails1.getUserId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(), Product.class);
ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0);
assertEquals(expectedName, actualComponentInstance.getName());
assertEquals(expectedNormalizedName, actualComponentInstance.getNormalizedName());
@@ -630,28 +522,20 @@ public class ProductComponentInstanceCRUDTest extends ComponentInstanceBaseTest
// see US534663 In case a PS/PM removes the current service instance
// name then BE has to generate again the "default" service instance
// name
- ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory
- .getComponentResourceInstance(serviceDetails_01);
- RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(
- serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01);
+ RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
String newName = "";
serviceInstanceReqDetails.setName(newName);
- RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
- serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
ResourceRestUtils.checkSuccess(updateServiceInstanceResponse);
- String instanceNormalizedName = ResponseParser
- .getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "normalizedName");
- String instanceName = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(),
- "name");
- assertEquals("check Resource Instance normalizedName ", (serviceDetails_01.getName() + "2").toLowerCase(),
- instanceNormalizedName);
+ String instanceNormalizedName = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "normalizedName");
+ String instanceName = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "name");
+ assertEquals("check Resource Instance normalizedName ", (serviceDetails_01.getName() + "2").toLowerCase(), instanceNormalizedName);
assertEquals("check Resource Instance normalizedName ", (serviceDetails_01.getName() + " 2"), instanceName);
// get product and verify that service instanceName is correct
- RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(),
- sdncPmDetails1.getUserId());
- Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(),
- Product.class);
+ RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(), sdncPmDetails1.getUserId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(), Product.class);
ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0);
assertEquals(instanceName, actualComponentInstance.getName());
assertEquals(instanceNormalizedName, actualComponentInstance.getNormalizedName());
@@ -663,28 +547,20 @@ public class ProductComponentInstanceCRUDTest extends ComponentInstanceBaseTest
// see US534663 In case a PS/PM removes the current service instance
// name then BE has to generate again the "default" service instance
// name
- ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory
- .getComponentResourceInstance(serviceDetails_01);
- RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(
- serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01);
+ RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
String newName = null;
serviceInstanceReqDetails.setName(newName);
- RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
- serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
ResourceRestUtils.checkSuccess(updateServiceInstanceResponse);
- String instanceNormalizedName = ResponseParser
- .getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "normalizedName");
- String instanceName = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(),
- "name");
- assertEquals("check Resource Instance normalizedName ", (serviceDetails_01.getName() + "2").toLowerCase(),
- instanceNormalizedName);
+ String instanceNormalizedName = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "normalizedName");
+ String instanceName = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "name");
+ assertEquals("check Resource Instance normalizedName ", (serviceDetails_01.getName() + "2").toLowerCase(), instanceNormalizedName);
assertEquals("check Resource Instance normalizedName ", (serviceDetails_01.getName() + " 2"), instanceName);
// get product and verify that service instanceName is correct
- RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(),
- sdncPmDetails1.getUserId());
- Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(),
- Product.class);
+ RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(), sdncPmDetails1.getUserId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(), Product.class);
ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0);
assertEquals(instanceName, actualComponentInstance.getName());
assertEquals(instanceNormalizedName, actualComponentInstance.getNormalizedName());
@@ -695,125 +571,93 @@ public class ProductComponentInstanceCRUDTest extends ComponentInstanceBaseTest
// see US534663 In case a PS/PM removes the current service instance
// name then BE has to generate again the "default" service instance
// name
- ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory
- .getComponentResourceInstance(serviceDetails_01);
- RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(
- serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01);
+ RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
String newName = "blabla";
serviceInstanceReqDetails.setName(newName);
- RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
- serviceInstanceReqDetails, sdncPmDetails2, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
- assertEquals("Check response code ", STATUS_CODE_RESTRICTED_OPERATION,
- updateServiceInstanceResponse.getErrorCode().intValue());
- ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(),
- updateServiceInstanceResponse.getResponse());
+ RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(serviceInstanceReqDetails, sdncPmDetails2, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ assertEquals("Check response code ", STATUS_CODE_RESTRICTED_OPERATION, updateServiceInstanceResponse.getErrorCode().intValue());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(), updateServiceInstanceResponse.getResponse());
}
@Test
public void updateServiceInstance_UserIdIsNonAsdcUser() throws Exception {
- ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory
- .getComponentResourceInstance(serviceDetails_01);
- RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(
- serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01);
+ RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
String newName = "blabla";
serviceInstanceReqDetails.setName(newName);
User nonSdncUserDetails = new User();
nonSdncUserDetails.setUserId("bt4567");
- RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
- serviceInstanceReqDetails, nonSdncUserDetails, productDetails_01.getUniqueId(),
- ComponentTypeEnum.PRODUCT);
- assertEquals("Check response code ", STATUS_CODE_RESTRICTED_OPERATION,
- updateServiceInstanceResponse.getErrorCode().intValue());
- ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(),
- updateServiceInstanceResponse.getResponse());
+ RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(serviceInstanceReqDetails, nonSdncUserDetails, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ assertEquals("Check response code ", STATUS_CODE_RESTRICTED_OPERATION, updateServiceInstanceResponse.getErrorCode().intValue());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(), updateServiceInstanceResponse.getResponse());
}
@Test
public void updateServiceInstanceNameToAlreadyExisting() throws Exception {
- ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory
- .getComponentResourceInstance(serviceDetails_01);
- RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(
- serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01);
+ RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
String ServiceName1 = ResponseParser.getNameFromResponse(createServiceInstanceResp);
- createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails,
- sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
// Update service instance2 name to service instance1
serviceInstanceReqDetails.setName(ServiceName1);
- RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
- serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
- assertEquals("Check response code ", STATUS_CODE_ALREADY_EXISTS,
- updateServiceInstanceResponse.getErrorCode().intValue());
+ RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ assertEquals("Check response code ", STATUS_CODE_ALREADY_EXISTS, updateServiceInstanceResponse.getErrorCode().intValue());
ArrayList<String> varibales = new ArrayList<String>();
varibales.add("Service Instance");
varibales.add(ServiceName1);
- ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_NAME_ALREADY_EXIST.name(), varibales,
- updateServiceInstanceResponse.getResponse());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_NAME_ALREADY_EXIST.name(), varibales, updateServiceInstanceResponse.getResponse());
}
@Test
public void updateServiceInstanceForNonExistingProduct() throws Exception {
- ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory
- .getComponentResourceInstance(serviceDetails_01);
- RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(
- serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01);
+ RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
String newName = "blabla";
serviceInstanceReqDetails.setName(newName);
- RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
- serviceInstanceReqDetails, sdncPmDetails1, "blablabla", ComponentTypeEnum.PRODUCT);
- AssertJUnit.assertEquals("Check response code ", STATUS_CODE_NOT_FOUND,
- updateServiceInstanceResponse.getErrorCode().intValue());
+ RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, "blablabla", ComponentTypeEnum.PRODUCT);
+ AssertJUnit.assertEquals("Check response code ", STATUS_CODE_NOT_FOUND, updateServiceInstanceResponse.getErrorCode().intValue());
ArrayList<String> varibales = new ArrayList<String>();
varibales.add("");
- ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.PRODUCT_NOT_FOUND.name(), varibales,
- updateServiceInstanceResponse.getResponse());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.PRODUCT_NOT_FOUND.name(), varibales, updateServiceInstanceResponse.getResponse());
}
@Test
public void updateNonExistingServiceInstance() throws Exception {
- ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory
- .getComponentResourceInstance(serviceDetails_01);
- RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(
- serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01);
+ RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
String newName = "blabla";
serviceInstanceReqDetails.setName(newName);
serviceInstanceReqDetails.setUniqueId("11111111");
- RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
- serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
ArrayList<String> varibales = new ArrayList<String>();
varibales.add(newName);
varibales.add("service instance");
- AssertJUnit.assertEquals("Check response code ", STATUS_CODE_NOT_FOUND,
- updateServiceInstanceResponse.getErrorCode().intValue());
+ AssertJUnit.assertEquals("Check response code ", STATUS_CODE_NOT_FOUND, updateServiceInstanceResponse.getErrorCode().intValue());
// need to change ActionStatus.RESOURCE_INSTANCE_NOT_FOUND.name() to
// ActionStatus.SERVICE_INSTANCE_NOT_FOUND.name()
- ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND.name(), varibales,
- updateServiceInstanceResponse.getResponse());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND.name(), varibales, updateServiceInstanceResponse.getResponse());
}
@Test
public void updateServiceInstanceLocation() throws Exception {
- ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory
- .getComponentResourceInstance(serviceDetails_01);
- RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(
- serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01);
+ RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
serviceInstanceReqDetails.setPosX("50");
serviceInstanceReqDetails.setPosY("100");
- RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
- serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
ResourceRestUtils.checkSuccess(updateServiceInstanceResponse);
// get product and verify that service instanceName is correct
- RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(),
- sdncPmDetails1.getUserId());
- Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(),
- Product.class);
+ RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(), sdncPmDetails1.getUserId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(), Product.class);
ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0);
assertEquals(serviceInstanceReqDetails.getPosX(), actualComponentInstance.getPosX());
assertEquals(serviceInstanceReqDetails.getPosY(), actualComponentInstance.getPosY());
@@ -821,23 +665,18 @@ public class ProductComponentInstanceCRUDTest extends ComponentInstanceBaseTest
@Test
public void updateServiceInstanceToNonExistingLocation() throws Exception {
- ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory
- .getComponentResourceInstance(serviceDetails_01);
- RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(
- serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01);
+ RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
String nameFromResponse = ResponseParser.getNameFromResponse(createServiceInstanceResp);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
serviceInstanceReqDetails.setPosX("-50");
serviceInstanceReqDetails.setPosY("-100");
serviceInstanceReqDetails.setName(nameFromResponse);
- RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
- serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
ResourceRestUtils.checkSuccess(updateServiceInstanceResponse);
// get product and verify that service instanceName is correct
- RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(),
- sdncPmDetails1.getUserId());
- Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(),
- Product.class);
+ RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(), sdncPmDetails1.getUserId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(), Product.class);
ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0);
assertEquals(serviceInstanceReqDetails.getPosX(), actualComponentInstance.getPosX());
assertEquals(serviceInstanceReqDetails.getPosY(), actualComponentInstance.getPosY());
@@ -848,16 +687,13 @@ public class ProductComponentInstanceCRUDTest extends ComponentInstanceBaseTest
public void updateServiceInstanceLocationNameIsEmpty() throws Exception {
String expectedServiceInstanceName = serviceDetails_01.getName() + " 2";
String expectedServiceInstancenormalizedName = serviceDetails_01.getName() + "2";
- ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory
- .getComponentResourceInstance(serviceDetails_01);
- RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(
- serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01);
+ RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
serviceInstanceReqDetails.setPosX("100");
serviceInstanceReqDetails.setPosY("200");
serviceInstanceReqDetails.setName("");
- RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
- serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
ResourceRestUtils.checkSuccess(updateServiceInstanceResponse);
String nameFromResponse = ResponseParser.getNameFromResponse(updateServiceInstanceResponse);
String postX = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "posX");
@@ -866,10 +702,8 @@ public class ProductComponentInstanceCRUDTest extends ComponentInstanceBaseTest
assertEquals(postX, "100");
assertEquals(postY, "200");
// get product and verify that service instanceName is correct
- RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(),
- sdncPmDetails1.getUserId());
- Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(),
- Product.class);
+ RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(), sdncPmDetails1.getUserId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(), Product.class);
ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0);
assertEquals(serviceInstanceReqDetails.getPosX(), actualComponentInstance.getPosX());
assertEquals(serviceInstanceReqDetails.getPosY(), actualComponentInstance.getPosY());
@@ -880,10 +714,8 @@ public class ProductComponentInstanceCRUDTest extends ComponentInstanceBaseTest
// pass
@Test
public void updateServiceInstanceNameToProductName() throws Exception {
- ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory
- .getComponentResourceInstance(serviceDetails_01);
- RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(
- serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01);
+ RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
// ComponentInstance componentInstance =
// ResponseParser.parseToObjectUsingMapper(createServiceInstanceResp.getResponse(),
@@ -891,21 +723,15 @@ public class ProductComponentInstanceCRUDTest extends ComponentInstanceBaseTest
// addCompInstReqCapToExpected(componentInstance,
// ComponentTypeEnum.PRODUCT);
serviceInstanceReqDetails.setName(productDetails_01.getName());
- RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
- serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
ResourceRestUtils.checkSuccess(updateServiceInstanceResponse);
- String instanceNormalizedName = ResponseParser
- .getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "normalizedName");
- String instanceName = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(),
- "name");
- assertEquals("check Resource Instance normalizedName ", (serviceInstanceReqDetails.getName()).toLowerCase(),
- instanceNormalizedName);
+ String instanceNormalizedName = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "normalizedName");
+ String instanceName = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "name");
+ assertEquals("check Resource Instance normalizedName ", (serviceInstanceReqDetails.getName()).toLowerCase(), instanceNormalizedName);
assertEquals("check Resource Instance Name ", serviceInstanceReqDetails.getName(), instanceName);
// get product and verify that service instanceName is correct
- RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(),
- sdncPmDetails1.getUserId());
- Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(),
- Product.class);
+ RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(), sdncPmDetails1.getUserId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(), Product.class);
ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0);
assertEquals(serviceInstanceReqDetails.getName(), actualComponentInstance.getName());
assertEquals((serviceInstanceReqDetails.getName()).toLowerCase(), actualComponentInstance.getNormalizedName());
@@ -915,35 +741,29 @@ public class ProductComponentInstanceCRUDTest extends ComponentInstanceBaseTest
@Test
public void deleteAllServiceInstanceFromProduct() throws Exception {
- RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
- sdncPmDetails1);
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
String serviceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp);
getComponentAndValidateRIs(productDetails_01, 1, 0);
- RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01,
- sdncPmDetails1);
+ RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01, sdncPmDetails1);
assertTrue(deleteServiceInstanceResp.getErrorCode() == STATUS_CODE_SUCCESS_DELETE);
getComponentAndValidateRIs(productDetails_01, 0, 0);
}
@Test
public void deleteServiceWhileServiceInstanceExistInProduct() throws Exception {
- RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
- sdncPmDetails1);
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
String serviceInstanceUniqueIdFromResponse = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp);
getComponentAndValidateRIs(productDetails_01, 2, 0);
// Delete service while service instance of it exist in product
- RestResponse deleteServiceResponse = ServiceRestUtils.deleteServiceById(serviceDetails_01.getUniqueId(),
- sdncDesignerDetails.getUserId());
+ RestResponse deleteServiceResponse = ServiceRestUtils.deleteServiceById(serviceDetails_01.getUniqueId(), sdncDesignerDetails.getUserId());
assertTrue(deleteServiceResponse.getErrorCode() == STATUS_CODE_SUCCESS_DELETE);
// Get product and verify that service instance still exists
- RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(),
- sdncPmDetails1.getUserId());
- Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(),
- Product.class);
+ RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(), sdncPmDetails1.getUserId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(), Product.class);
// ComponentInstance actualComponentInstance =
// actualProduct.getComponentInstances().get(0);
// assertTrue(serviceInstanceUniqueIdFromResponse ==
@@ -954,89 +774,72 @@ public class ProductComponentInstanceCRUDTest extends ComponentInstanceBaseTest
// pass
@Test
public void deleteServiceInstanceByPm() throws Exception {
- RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
- sdncPmDetails1);
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
String serviceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp);
createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
getComponentAndValidateRIs(productDetails_01, 2, 0);
- RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01,
- sdncPmDetails1);
+ RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01, sdncPmDetails1);
assertTrue(deleteServiceInstanceResp.getErrorCode() == STATUS_CODE_SUCCESS_DELETE);
getComponentAndValidateRIs(productDetails_01, 1, 0);
}
@Test
public void deleteServiceInstanceByPmCreatedByPm() throws Exception {
- RestResponse restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
- LifeCycleStatesEnum.CHECKIN);
+ RestResponse restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, LifeCycleStatesEnum.CHECKIN);
ResourceRestUtils.checkSuccess(restResponse);
- restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
- LifeCycleStatesEnum.CHECKOUT);
+ restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, LifeCycleStatesEnum.CHECKOUT);
ResourceRestUtils.checkSuccess(restResponse);
productDetails_01.setUniqueId(ResponseParser.getUniqueIdFromResponse(restResponse));
- RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
- sdncPmDetails1);
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
String serviceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp);
createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
getComponentAndValidateRIs(productDetails_01, 2, 0);
- RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01,
- sdncPmDetails1);
+ RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01, sdncPmDetails1);
assertTrue(deleteServiceInstanceResp.getErrorCode() == STATUS_CODE_SUCCESS_DELETE);
getComponentAndValidateRIs(productDetails_01, 1, 0);
}
@Test
public void deleteServiceInstanceByPmWhichIsCheckedOutByAnotherPm() throws Exception {
- RestResponse restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
- LifeCycleStatesEnum.CHECKIN);
+ RestResponse restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, LifeCycleStatesEnum.CHECKIN);
ResourceRestUtils.checkSuccess(restResponse);
- restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
- LifeCycleStatesEnum.CHECKOUT);
+ restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, LifeCycleStatesEnum.CHECKOUT);
ResourceRestUtils.checkSuccess(restResponse);
- RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
- sdncPmDetails1);
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
String serviceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp);
createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
getComponentAndValidateRIs(productDetails_01, 2, 0);
- RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01,
- sdncPmDetails2);
+ RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01, sdncPmDetails2);
assertTrue(deleteServiceInstanceResp.getErrorCode() == STATUS_CODE_RESTRICTED_OPERATION);
- ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(),
- deleteServiceInstanceResp.getResponse());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(), deleteServiceInstanceResp.getResponse());
getComponentAndValidateRIs(productDetails_01, 2, 0);
}
// DE190189
@Test
public void deleteServiceInstanceByPmCreatedByPs() throws Exception {
- RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
- sdncPmDetails1);
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
String productOldUniqueId = productDetails_01.getUniqueId();
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
getComponentAndValidateRIs(productDetails_01, 1, 0);
- RestResponse restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
- LifeCycleStatesEnum.CHECKIN);
+ RestResponse restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, LifeCycleStatesEnum.CHECKIN);
ResourceRestUtils.checkSuccess(restResponse);
- restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
- LifeCycleStatesEnum.CHECKOUT);
+ restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, LifeCycleStatesEnum.CHECKOUT);
ResourceRestUtils.checkSuccess(restResponse);
String productNewUniqueId = ResponseParser.getUniqueIdFromResponse(restResponse);
updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId);
// get product and get service instance new uniquId
- RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(),
- sdncPmDetails1.getUserId());
- Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(),
- Product.class);
+ RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(), sdncPmDetails1.getUserId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(), Product.class);
ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0);
String serviceInstanceUniqueId = actualComponentInstance.getUniqueId();
- RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01,
- sdncPmDetails1);
+ RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01, sdncPmDetails1);
assertTrue(deleteServiceInstanceResp.getErrorCode() == STATUS_CODE_SUCCESS_DELETE);
getComponentAndValidateRIs(productDetails_01, 0, 0);
}
@@ -1044,120 +847,97 @@ public class ProductComponentInstanceCRUDTest extends ComponentInstanceBaseTest
// DE190189
@Test
public void deleteServiceInstanceByAdminCreatedByPs() throws Exception {
- RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
- sdncPmDetails1);
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
String productOldUniqueId = productDetails_01.getUniqueId();
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
getComponentAndValidateRIs(productDetails_01, 1, 0);
- RestResponse restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
- LifeCycleStatesEnum.CHECKIN);
+ RestResponse restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, LifeCycleStatesEnum.CHECKIN);
ResourceRestUtils.checkSuccess(restResponse);
- restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncAdminDetails,
- LifeCycleStatesEnum.CHECKOUT);
+ restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncAdminDetails, LifeCycleStatesEnum.CHECKOUT);
ResourceRestUtils.checkSuccess(restResponse);
String productNewUniqueId = ResponseParser.getUniqueIdFromResponse(restResponse);
updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId);
// get product and get service instance new uniquId
- RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(),
- sdncAdminDetails.getUserId());
- Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(),
- Product.class);
+ RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(), sdncAdminDetails.getUserId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(), Product.class);
ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0);
String serviceInstanceUniqueId = actualComponentInstance.getUniqueId();
- RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01,
- sdncAdminDetails);
+ RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01, sdncAdminDetails);
assertTrue(deleteServiceInstanceResp.getErrorCode() == STATUS_CODE_SUCCESS_DELETE);
getComponentAndValidateRIs(productDetails_01, 0, 0);
}
@Test
public void createAndDeleteServiceInstanceByAdmin() throws Exception {
- RestResponse restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
- LifeCycleStatesEnum.CHECKIN);
+ RestResponse restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, LifeCycleStatesEnum.CHECKIN);
ResourceRestUtils.checkSuccess(restResponse);
- restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncAdminDetails,
- LifeCycleStatesEnum.CHECKOUT);
+ restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncAdminDetails, LifeCycleStatesEnum.CHECKOUT);
ResourceRestUtils.checkSuccess(restResponse);
// productDetails_01.setUniqueId(ResponseParser.getUniqueIdFromResponse(restResponse));
- RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
- sdncAdminDetails);
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncAdminDetails);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
String serviceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp);
createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncAdminDetails);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
getComponentAndValidateRIs(productDetails_01, 2, 0);
- RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01,
- sdncAdminDetails);
+ RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01, sdncAdminDetails);
assertTrue(deleteServiceInstanceResp.getErrorCode() == STATUS_CODE_SUCCESS_DELETE);
getComponentAndValidateRIs(productDetails_01, 1, 0);
}
@Test
public void deleteServiceInstanceFromNonCheckOutProduct() throws Exception {
- RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
- sdncPmDetails1);
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
String serviceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp);
getComponentAndValidateRIs(productDetails_01, 1, 0);
- RestResponse restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
- LifeCycleStatesEnum.CHECKIN);
+ RestResponse restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, LifeCycleStatesEnum.CHECKIN);
ResourceRestUtils.checkSuccess(restResponse);
- RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01,
- sdncPmDetails1);
+ RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01, sdncPmDetails1);
assertTrue(deleteServiceInstanceResp.getErrorCode() == STATUS_CODE_RESTRICTED_OPERATION);
- ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(),
- deleteServiceInstanceResp.getResponse());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(), deleteServiceInstanceResp.getResponse());
getComponentAndValidateRIs(productDetails_01, 1, 0);
}
@Test
public void deleteServiceInstanceByDesigner() throws Exception {
- RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
- sdncPmDetails1);
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
String serviceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp);
createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
getComponentAndValidateRIs(productDetails_01, 2, 0);
- RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01,
- sdncDesignerDetails);
+ RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01, sdncDesignerDetails);
assertTrue(deleteServiceInstanceResp.getErrorCode() == STATUS_CODE_RESTRICTED_OPERATION);
- ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(),
- deleteServiceInstanceResp.getResponse());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(), deleteServiceInstanceResp.getResponse());
getComponentAndValidateRIs(productDetails_01, 2, 0);
}
@Test
public void deleteServiceInstanceByTester() throws Exception {
- RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
- sdncPmDetails1);
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
String serviceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp);
createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
getComponentAndValidateRIs(productDetails_01, 2, 0);
- RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01,
- sdncTesterDetails);
+ RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01, sdncTesterDetails);
assertTrue(deleteServiceInstanceResp.getErrorCode() == STATUS_CODE_RESTRICTED_OPERATION);
- ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(),
- deleteServiceInstanceResp.getResponse());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(), deleteServiceInstanceResp.getResponse());
getComponentAndValidateRIs(productDetails_01, 2, 0);
}
@Test
public void deleteServiceInstanceByPsWhichIsCheckedOutByAnotherPs() throws Exception {
- RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
- sdncPmDetails1);
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
String serviceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp);
createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
getComponentAndValidateRIs(productDetails_01, 2, 0);
- RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01,
- sdncPsDetails2);
+ RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01, sdncPsDetails2);
assertTrue(deleteServiceInstanceResp.getErrorCode() == STATUS_CODE_RESTRICTED_OPERATION);
- ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(),
- deleteServiceInstanceResp.getResponse());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(), deleteServiceInstanceResp.getResponse());
getComponentAndValidateRIs(productDetails_01, 2, 0);
}
@@ -1167,96 +947,80 @@ public class ProductComponentInstanceCRUDTest extends ComponentInstanceBaseTest
User nonExistingSdncUser = ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_MANAGER1);
;
nonExistingSdncUser.setUserId("bt1234");
- RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
- sdncPmDetails1);
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
String serviceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp);
createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
getComponentAndValidateRIs(productDetails_01, 2, 0);
- RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01,
- nonExistingSdncUser);
+ RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01, nonExistingSdncUser);
assertTrue(deleteServiceInstanceResp.getErrorCode() == STATUS_CODE_RESTRICTED_OPERATION);
- ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(),
- deleteServiceInstanceResp.getResponse());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(), deleteServiceInstanceResp.getResponse());
getComponentAndValidateRIs(productDetails_01, 2, 0);
}
@Test
public void deleteServiceInstanceFromNonExistingProduct() throws Exception {
- RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
- sdncPmDetails1);
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
String serviceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp);
createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
getComponentAndValidateRIs(productDetails_01, 2, 0);
- RestResponse deleteResourceInstanceResponse = ComponentInstanceRestUtils.deleteComponentInstance(sdncPmDetails1,
- "1234567890", serviceInstanceUniqueId, ComponentTypeEnum.PRODUCT);
+ RestResponse deleteResourceInstanceResponse = ComponentInstanceRestUtils.deleteComponentInstance(sdncPmDetails1, "1234567890", serviceInstanceUniqueId, ComponentTypeEnum.PRODUCT);
assertTrue(deleteResourceInstanceResponse.getErrorCode() == STATUS_CODE_NOT_FOUND);
ArrayList<String> varibales = new ArrayList<String>();
varibales.add("");
- ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.PRODUCT_NOT_FOUND.name(), varibales,
- deleteResourceInstanceResponse.getResponse());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.PRODUCT_NOT_FOUND.name(), varibales, deleteResourceInstanceResponse.getResponse());
getComponentAndValidateRIs(productDetails_01, 2, 0);
}
@Test
public void deleteNonExistingServiceInstanceFromProduct() throws Exception {
- RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
- sdncPmDetails1);
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
// String serviceInstanceUniqueId =
// ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp);
createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
getComponentAndValidateRIs(productDetails_01, 2, 0);
- RestResponse deleteResourceInstanceResponse = ComponentInstanceRestUtils.deleteComponentInstance(sdncPmDetails1,
- productDetails_01.getUniqueId(), "1234567890123456unExistingServiceInstance",
- ComponentTypeEnum.PRODUCT);
+ RestResponse deleteResourceInstanceResponse = ComponentInstanceRestUtils.deleteComponentInstance(sdncPmDetails1, productDetails_01.getUniqueId(), "1234567890123456unExistingServiceInstance", ComponentTypeEnum.PRODUCT);
assertTrue(deleteResourceInstanceResponse.getErrorCode() == STATUS_CODE_NOT_FOUND);
ArrayList<String> varibales = new ArrayList<String>();
varibales.add("1234567890123456unExistingServiceInstance");
- ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.PRODUCT_NOT_FOUND.name(), varibales,
- deleteResourceInstanceResponse.getResponse());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.PRODUCT_NOT_FOUND.name(), varibales, deleteResourceInstanceResponse.getResponse());
getComponentAndValidateRIs(productDetails_01, 2, 0);
}
@Test
public void deleteServiceInstanceFromNonSupportedComponentType() throws Exception {
- RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
- sdncPmDetails1);
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
String serviceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp);
createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
getComponentAndValidateRIs(productDetails_01, 2, 0);
- RestResponse deleteResourceInstanceResponse = ComponentInstanceRestUtils.deleteComponentInstance(sdncPmDetails1,
- productDetails_01.getUniqueId(), serviceInstanceUniqueId, ComponentTypeEnum.RESOURCE_INSTANCE);
+ RestResponse deleteResourceInstanceResponse = ComponentInstanceRestUtils.deleteComponentInstance(sdncPmDetails1, productDetails_01.getUniqueId(), serviceInstanceUniqueId, ComponentTypeEnum.RESOURCE_INSTANCE);
assertTrue(deleteResourceInstanceResponse.getErrorCode() == STATUS_CODE_UNSUPPORTED_ERROR);
ArrayList<String> varibales = new ArrayList<String>();
varibales.add("null");
- ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.UNSUPPORTED_ERROR.name(), varibales,
- deleteResourceInstanceResponse.getResponse());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.UNSUPPORTED_ERROR.name(), varibales, deleteResourceInstanceResponse.getResponse());
getComponentAndValidateRIs(productDetails_01, 2, 0);
}
@Test
public void deleteServiceInstanceComponentTypeIsNotProduct() throws Exception {
- RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
- sdncPmDetails1);
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
String serviceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp);
createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
getComponentAndValidateRIs(productDetails_01, 2, 0);
- RestResponse deleteResourceInstanceResponse = ComponentInstanceRestUtils.deleteComponentInstance(sdncPmDetails1,
- productDetails_01.getUniqueId(), serviceInstanceUniqueId, ComponentTypeEnum.SERVICE);
+ RestResponse deleteResourceInstanceResponse = ComponentInstanceRestUtils.deleteComponentInstance(sdncPmDetails1, productDetails_01.getUniqueId(), serviceInstanceUniqueId, ComponentTypeEnum.SERVICE);
assertTrue(deleteResourceInstanceResponse.getErrorCode() == STATUS_CODE_NOT_FOUND);
ArrayList<String> varibales = new ArrayList<String>();
varibales.add("");
- ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.SERVICE_NOT_FOUND.name(), varibales,
- deleteResourceInstanceResponse.getResponse());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.SERVICE_NOT_FOUND.name(), varibales, deleteResourceInstanceResponse.getResponse());
getComponentAndValidateRIs(productDetails_01, 2, 0);
}
@@ -1264,31 +1028,26 @@ public class ProductComponentInstanceCRUDTest extends ComponentInstanceBaseTest
public void deleteServiceInstanceUserIdIsEmpty() throws Exception {
User nonSdncDetails = ElementFactory.getDefaultUser(UserRoleEnum.TESTER);
nonSdncDetails.setUserId("");
- RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
- sdncPmDetails1);
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
String serviceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp);
getComponentAndValidateRIs(productDetails_01, 1, 0);
- RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01,
- nonSdncDetails);
+ RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01, nonSdncDetails);
assertTrue(deleteServiceInstanceResp.getErrorCode() == STATUS_CODE_MISSING_INFORMATION);
- ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_INFORMATION.name(), new ArrayList<String>(),
- deleteServiceInstanceResp.getResponse());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_INFORMATION.name(), new ArrayList<String>(), deleteServiceInstanceResp.getResponse());
getComponentAndValidateRIs(productDetails_01, 1, 0);
}
@Test
public void deleteCertifiedServiceInstance() throws Exception {
changeServiceStateToCertified(serviceDetails_01);
- RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
- sdncPmDetails1);
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
String serviceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp);
createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
getComponentAndValidateRIs(productDetails_01, 2, 0);
- RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01,
- sdncPmDetails1);
+ RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01, sdncPmDetails1);
assertTrue(deleteServiceInstanceResp.getErrorCode() == STATUS_CODE_SUCCESS_DELETE);
getComponentAndValidateRIs(productDetails_01, 1, 0);
}
@@ -1296,18 +1055,15 @@ public class ProductComponentInstanceCRUDTest extends ComponentInstanceBaseTest
////////////////////////////////////
private void certifyVf(ResourceReqDetails resource) throws Exception {
- RestResponse createAtomicResourceInstance = createAtomicInstanceForVFDuringSetup(resource, resourceDetailsCP_01,
- sdncDesignerDetails);
+ RestResponse createAtomicResourceInstance = createAtomicInstanceForVFDuringSetup(resource, resourceDetailsCP_01, sdncDesignerDetails);
ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance);
String cpCompInstId = ResponseParser.getUniqueIdFromResponse(createAtomicResourceInstance);
- createAtomicResourceInstance = createAtomicInstanceForVFDuringSetup(resource, resourceDetailsVFC_02,
- sdncDesignerDetails);
+ createAtomicResourceInstance = createAtomicInstanceForVFDuringSetup(resource, resourceDetailsVFC_02, sdncDesignerDetails);
ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance);
String computeCompInstId = ResponseParser.getUniqueIdFromResponse(createAtomicResourceInstance);
- createAtomicResourceInstance = createAtomicInstanceForVFDuringSetup(resource, resourceDetailsVL_01,
- sdncDesignerDetails);
+ createAtomicResourceInstance = createAtomicInstanceForVFDuringSetup(resource, resourceDetailsVL_01, sdncDesignerDetails);
ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance);
String vlCompInstId = ResponseParser.getUniqueIdFromResponse(createAtomicResourceInstance);
@@ -1317,35 +1073,29 @@ public class ProductComponentInstanceCRUDTest extends ComponentInstanceBaseTest
fulfillCpRequirement(resource, cpCompInstId, computeCompInstId, computeCompInstId, user, containerCompType);
consumeVlCapability(resource, cpCompInstId, vlCompInstId, cpCompInstId, user, containerCompType);
- RestResponse response = ArtifactRestUtils.addInformationalArtifactToResource(heatArtifactDetails,
- sdncDesignerDetails, resource.getUniqueId());
+ RestResponse response = ArtifactRestUtils.addInformationalArtifactToResource(heatArtifactDetails, sdncDesignerDetails, resource.getUniqueId());
ResourceRestUtils.checkSuccess(response);
RestResponse changeResourceStateToCertified = changeResourceStateToCertified(resource);
ResourceRestUtils.checkSuccess(changeResourceStateToCertified);
}
private RestResponse changeResourceStateToCertified(ResourceReqDetails resourceDetails) throws Exception {
- RestResponse restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncDesignerDetails,
- LifeCycleStatesEnum.CHECKIN);
+ RestResponse restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncDesignerDetails, LifeCycleStatesEnum.CHECKIN);
ResourceRestUtils.checkSuccess(restResponse);
- restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncDesignerDetails,
- LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncDesignerDetails, LifeCycleStatesEnum.CERTIFICATIONREQUEST);
if (restResponse.getErrorCode() == 200) {
- restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncTesterDetails,
- LifeCycleStatesEnum.STARTCERTIFICATION);
+ restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncTesterDetails, LifeCycleStatesEnum.STARTCERTIFICATION);
} else
return restResponse;
if (restResponse.getErrorCode() == 200) {
- restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncTesterDetails,
- LifeCycleStatesEnum.CERTIFY);
+ 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");
+ String uniqueIdFromRresponse = ResponseParser.getValueFromJsonResponse(restResponse.getResponse(), "uniqueId");
resourceDetails.setUniqueId(uniqueIdFromRresponse);
}
}
@@ -1354,28 +1104,21 @@ public class ProductComponentInstanceCRUDTest extends ComponentInstanceBaseTest
private RestResponse changeServiceStateToCertified(ServiceReqDetails serviceDetails) throws Exception {
/*
- * RestResponse restResponse =
- * LifecycleRestUtils.changeServiceState(serviceDetails,
- * sdncDesignerDetails, LifeCycleStatesEnum.CHECKIN);
- * ResourceRestUtils.checkSuccess(restResponse);
+ * RestResponse restResponse = LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, LifeCycleStatesEnum.CHECKIN); ResourceRestUtils.checkSuccess(restResponse);
*/
- RestResponse restResponse = LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails,
- LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ RestResponse restResponse = LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, LifeCycleStatesEnum.CERTIFICATIONREQUEST);
if (restResponse.getErrorCode() == 200) {
- restResponse = LifecycleRestUtils.changeServiceState(serviceDetails, sdncTesterDetails,
- LifeCycleStatesEnum.STARTCERTIFICATION);
+ restResponse = LifecycleRestUtils.changeServiceState(serviceDetails, sdncTesterDetails, LifeCycleStatesEnum.STARTCERTIFICATION);
} else
return restResponse;
if (restResponse.getErrorCode() == 200) {
- restResponse = LifecycleRestUtils.changeServiceState(serviceDetails, sdncTesterDetails,
- LifeCycleStatesEnum.CERTIFY);
+ restResponse = LifecycleRestUtils.changeServiceState(serviceDetails, sdncTesterDetails, LifeCycleStatesEnum.CERTIFY);
if (restResponse.getErrorCode() == 200) {
serviceDetails.setVersion("1.0");
serviceDetails.setLifecycleState(LifecycleStateEnum.CERTIFIED);
serviceDetails.setLastUpdaterUserId(sdncTesterDetails.getUserId());
serviceDetails.setLastUpdaterFullName(sdncTesterDetails.getFullName());
- String uniqueIdFromRresponse = ResponseParser.getValueFromJsonResponse(restResponse.getResponse(),
- "uniqueId");
+ String uniqueIdFromRresponse = ResponseParser.getValueFromJsonResponse(restResponse.getResponse(), "uniqueId");
serviceDetails.setUniqueId(uniqueIdFromRresponse);
}
}
@@ -1384,8 +1127,7 @@ public class ProductComponentInstanceCRUDTest extends ComponentInstanceBaseTest
@Test
public void deleteServiceInstanceTest() throws Exception {
- RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
- sdncPmDetails1);
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
getComponentAndValidateRIs(productDetails_01, 1, 0);
String compInstId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp);
@@ -1408,14 +1150,12 @@ public class ProductComponentInstanceCRUDTest extends ComponentInstanceBaseTest
public void returnedServiceInstanceTypeAttributeTest() throws Exception {
String expectedServiceType = ComponentTypeEnum.SERVICE.getValue().toUpperCase();
- RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
- sdncPmDetails1);
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
String serviceUniqueIdFromResponse = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp);
ComponentInstanceRestUtils.checkComponentInstanceType(createServiceInstanceResp, expectedServiceType);
- RestResponse getProductResp = ProductRestUtils.getProduct(productDetails_01.getUniqueId(),
- sdncPsDetails1.getUserId());
+ RestResponse getProductResp = ProductRestUtils.getProduct(productDetails_01.getUniqueId(), sdncPsDetails1.getUserId());
ProductRestUtils.checkSuccess(getProductResp);
Product productObject = ResponseParser.parseToObjectUsingMapper(getProductResp.getResponse(), Product.class);
List<ComponentInstance> productComponentInstances = productObject.getComponentInstances();
@@ -1424,12 +1164,10 @@ public class ProductComponentInstanceCRUDTest extends ComponentInstanceBaseTest
assertTrue(expectedServiceType.equals(actualOriginType));
}
- ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory
- .getComponentResourceInstance(serviceDetails_02);
+ ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_02);
serviceInstanceReqDetails.setUniqueId(serviceUniqueIdFromResponse);
serviceInstanceReqDetails.setComponentUid(serviceDetails_01.getUniqueId());
- RestResponse updateResourceInstance = ComponentInstanceRestUtils.updateComponentInstance(
- serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ RestResponse updateResourceInstance = ComponentInstanceRestUtils.updateComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
ComponentInstanceRestUtils.checkSuccess(updateResourceInstance);
ComponentInstanceRestUtils.checkComponentInstanceType(updateResourceInstance, expectedServiceType);
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCreateWithValidationsTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCreateWithValidationsTest.java
index d2c2dfe77f..7ac24bdd69 100644
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCreateWithValidationsTest.java
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCreateWithValidationsTest.java
@@ -38,6 +38,7 @@ import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedProductAudit;
import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
import org.openecomp.sdc.ci.tests.utils.DbUtils;
+import org.openecomp.sdc.ci.tests.utils.Utils;
import org.openecomp.sdc.ci.tests.utils.general.Convertor;
import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCrudTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCrudTest.java
index f234708b7a..d91391d967 100644
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCrudTest.java
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCrudTest.java
@@ -34,10 +34,13 @@ import org.junit.rules.TestName;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.model.LifecycleStateEnum;
import org.openecomp.sdc.be.model.Product;
+import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.model.category.CategoryDefinition;
import org.openecomp.sdc.ci.tests.api.Urls;
import org.openecomp.sdc.ci.tests.datatypes.ProductReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceRespJavaObject;
import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedProductAudit;
@@ -49,10 +52,13 @@ import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
import org.openecomp.sdc.ci.tests.utils.rest.CatalogRestUtils;
import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils;
import org.openecomp.sdc.ci.tests.utils.rest.ProductRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils;
import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils;
import org.openecomp.sdc.ci.tests.utils.validation.ProductValidationUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.ResourceValidationUtils;
import org.openecomp.sdc.common.api.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -310,7 +316,7 @@ public class ProductCrudTest extends ProductBaseTest {
productManager1.setUserId(null);
RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId());
- assertEquals("Check response code after getting created Producuct with userId extracted from header", BaseRestUtils.STATUS_CODE_MISSING_INFORMATION, getProductRes.getErrorCode().intValue());
+ assertEquals("Check response code after getting created Producuct with UserId extracted from header", BaseRestUtils.STATUS_CODE_MISSING_INFORMATION, getProductRes.getErrorCode().intValue());
}
@@ -337,8 +343,8 @@ public class ProductCrudTest extends ProductBaseTest {
// US594753 - Update Product metadata
- // If user update Product Name we need to remove the old product name from
- // Tags and add the new product name instead - will be handled in new US
+ // If user update "product name" we need to remove the old product name from
+ // "Tags" and add the new product name instead - will handled in mew US
@Test(enabled = false)
public void updateProductAllFieldsByPM() throws Exception {
createProducrByPSAndCheckIn();
@@ -558,8 +564,8 @@ public class ProductCrudTest extends ProductBaseTest {
ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
}
- // If user update Product Name we need to remove the old product name from
- // Tags and add the new product name instead - will be handled in new US
+ // If user update "product name" we need to remove the old product name from
+ // "Tags" and add the new product name instead - will handled in mew US
@Test(enabled = false)
public void updateProductNameHasMinLength() throws Exception {
createProducrByPSAndCheckIn();
@@ -581,8 +587,8 @@ public class ProductCrudTest extends ProductBaseTest {
ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
}
- // If user update Product Name we need to remove the old product name from
- // Tags and add the new product name instead - will be handled in new US
+ // If user update "product name" we need to remove the old product name from
+ // "Tags" and add the new product name instead - will handled in mew US
// DE193857 - Normalized Name is not removing special characters
@Test(enabled = false)
public void updateProductNameMaxLength() throws Exception {
@@ -641,7 +647,7 @@ public class ProductCrudTest extends ProductBaseTest {
Product product1 = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product1, productManager2, LifeCycleStatesEnum.CHECKIN);
ProductRestUtils.checkSuccess(changeProductLifeCycle);
- productReqDetails.setName("CiProduct2000");
+ productReqDetails.setName("Product2000");
// productReqDetails.setTags(Arrays.asList(productReqDetails.getName()));
createProduct = ProductRestUtils.createProduct(productReqDetails, productManager2);
ProductRestUtils.checkCreateResponse(createProduct);
@@ -670,8 +676,8 @@ public class ProductCrudTest extends ProductBaseTest {
}
// DE193857 - Normalized Name is not removing special characters
- // If user update Product Name we need to remove the old product name from
- // Tags and add the new product name instead - will be handled in new US
+ // If user update "product name" we need to remove the old product name from
+ // "Tags" and add the new product name instead - will handled in mew US
@Test(enabled = false)
public void updateProductNameAllowedCharacters() throws Exception {
createProducrByPSAndCheckIn();
@@ -686,7 +692,7 @@ public class ProductCrudTest extends ProductBaseTest {
// , ‘ ‘
// (space),
// ampersand
- // dash
+ // "&", dash
// “-“, plus
// "+", period
// ".",
@@ -697,7 +703,7 @@ public class ProductCrudTest extends ProductBaseTest {
// ":", at "@",
// and
// underscore
- //
+ // "_"
String newNormalizedName = "abu4km&kobujuggp";
String newName = "A_BU4k M&K=o#b-u.j-uG'g+P";
RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
@@ -714,8 +720,8 @@ public class ProductCrudTest extends ProductBaseTest {
ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
}
- // If user update Product Name we need to remove the old product name from
- // Tags and add the new product name instead - will be handled in new US
+ // If user update "product name" we need to remove the old product name from
+ // "Tags" and add the new product name instead - will handled in mew US
@Test(enabled = false)
public void updateProductNameRemoveSpaceFromBeginning() throws Exception {
createProducrByPSAndCheckIn();
@@ -741,8 +747,8 @@ public class ProductCrudTest extends ProductBaseTest {
ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
}
- // If user update Product Name we need to remove the old product name from
- // Tags and add the new product name instead - will be handled in new US
+ // If user update "product name" we need to remove the old product name from
+ // "Tags" and add the new product name instead - will handled in mew US
@Test(enabled = false)
public void updateProductNameRemoveSpaceFromEnd() throws Exception {
createProducrByPSAndCheckIn();
@@ -769,8 +775,8 @@ public class ProductCrudTest extends ProductBaseTest {
}
//// DE193857 - Normalized Name is not removing special characters
- // If user update Product Name we need to remove the old product name from
- // Tags and add the new product name instead - will be handled in new US
+ // If user update "product name" we need to remove the old product name from
+ //// "Tags" and add the new product name instead - will handled in mew US
@Test(enabled = false)
public void updateProductNameRemoveExtraNonAlphanumericChars() throws Exception {
createProducrByPSAndCheckIn();
@@ -796,8 +802,8 @@ public class ProductCrudTest extends ProductBaseTest {
ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
}
- // If user update Product Name we need to remove the old product name from
- // Tags and add the new product name instead - will be handled in new US
+ // If user update "product name" we need to remove the old product name from
+ // "Tags" and add the new product name instead - will handled in mew US
@Test(enabled = false)
public void updateProductNameValidationStartWithNumber() throws Exception {
createProducrByPSAndCheckIn();
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductLifecycleTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductLifecycleTest.java
index 8c3409342b..26bb3e29e9 100644
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductLifecycleTest.java
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductLifecycleTest.java
@@ -48,7 +48,8 @@ public abstract class ProductLifecycleTest extends ProductBaseTest {
public void init() throws Exception {
ProductReqDetails defaultProduct = ElementFactory.getDefaultProduct(defaultCategories);
RestResponse createProduct = ProductRestUtils.createProduct(defaultProduct, productManager1);
- assertEquals("Check response code after create Product", BaseRestUtils.STATUS_CODE_CREATED, createProduct.getErrorCode().intValue());
+ assertEquals("Check response code after create Product", BaseRestUtils.STATUS_CODE_CREATED,
+ createProduct.getErrorCode().intValue());
expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
}
}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/property/AdditionalInformationServletTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/property/AdditionalInformationServletTest.java
index 303be77f92..1cf16978e4 100644
--- 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
@@ -35,8 +35,8 @@ 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.AdditionalInfoParameterInfo;
import org.openecomp.sdc.be.model.AdditionalInformationDefinition;
import org.openecomp.sdc.be.model.PropertyConstraint;
import org.openecomp.sdc.be.model.Resource;
@@ -1459,7 +1459,7 @@ public class AdditionalInformationServletTest extends ComponentBaseTest {
assertEquals("check returned id", fromJson.getUniqueId(), updatedJson.getUniqueId());
fromJson.setKey(updatedKey);
- fromJson.setValue("");
+ fromJson.setValue("\uC2B5");
updatedProperty = updateServiceAdditionalInformation(serviceId, fromJson, user, fromJson.getUniqueId());
assertNotNull("check response object is not null after update additional information", updatedProperty);
@@ -1990,7 +1990,7 @@ public class AdditionalInformationServletTest extends ComponentBaseTest {
assertEquals("Check response code after create resource", 201, createResourceResponse.getErrorCode().intValue());
String key = "AAA AAA";
- String value = "";
+ String value = "\uC2B5";
AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value);
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
index 6ba1b2ccca..c9aa44a6c0 100644
--- 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
@@ -25,16 +25,19 @@ 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;
@@ -46,6 +49,9 @@ 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.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;
@@ -96,11 +102,9 @@ public class ComponentInstancePropertyTest extends ComponentBaseTest {
// first res
basicVFC = createResourceWithProperty(ElementFactory.getDefaultStringProperty(), LifeCycleStatesEnum.CERTIFY);
// second resource
- vfc1FromBasicVFC = createResourceWithPropertyDerivedFromOtherResource(
- ElementFactory.getDefaultIntegerProperty(), LifeCycleStatesEnum.CERTIFY, basicVFC);
+ vfc1FromBasicVFC = createResourceWithPropertyDerivedFromOtherResource(ElementFactory.getDefaultIntegerProperty(), LifeCycleStatesEnum.CERTIFY, basicVFC);
// third resource
- vfc2FromVfc1 = createResourceWithPropertyDerivedFromOtherResource(ElementFactory.getDefaultBooleanProperty(),
- LifeCycleStatesEnum.CHECKIN, vfc1FromBasicVFC);
+ vfc2FromVfc1 = createResourceWithPropertyDerivedFromOtherResource(ElementFactory.getDefaultBooleanProperty(), LifeCycleStatesEnum.CHECKIN, vfc1FromBasicVFC);
// verify property
vfc2FromVfc1 = AtomicOperationUtils.getResourceObject(vfc2FromVfc1, UserRoleEnum.DESIGNER);
actualPropertyList = PropertyRestUtils.addResourcePropertiesToList(vfc2FromVfc1, actualPropertyList);
@@ -115,23 +119,17 @@ public class ComponentInstancePropertyTest extends ComponentBaseTest {
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);
+ 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.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);
+ PropertyRestUtils.updatePropertyListWithPathOnResource(componentInstDetails, vfc2FromVfc1, expectedPropertyList, vfResource);
// verify property
vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER);
actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(vfResource, actualPropertyList, null);
@@ -142,18 +140,14 @@ public class ComponentInstancePropertyTest extends ComponentBaseTest {
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);
+ 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();
+ 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");
@@ -162,19 +156,13 @@ public class ComponentInstancePropertyTest extends ComponentBaseTest {
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.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();
+ 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);
+ PropertyRestUtils.updatePropertyListWithPathOnResource(componentInstDetails, cp, expectedPropertyList, vfResource);
// verify property
vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER);
actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(vfResource, actualPropertyList, null);
@@ -184,28 +172,21 @@ public class ComponentInstancePropertyTest extends ComponentBaseTest {
@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);
+ 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.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);
+ 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);
+ PropertyRestUtils.updatePropertyListWithPathOnResource(componentInstDetails, vfc2FromVfc1, expectedPropertyList, vfResource);
actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(vfResource, actualPropertyList, null);
PropertyRestUtils.comparePropertyLists(expectedPropertyList, actualPropertyList, false);
}
@@ -214,31 +195,22 @@ public class ComponentInstancePropertyTest extends ComponentBaseTest {
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);
+ 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.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);
+ PropertyRestUtils.updatePropertyListWithPathOnResource(componentInstDetails, vfc2FromVfc1, expectedPropertyList, vfResource);
- componentInstDetails = AtomicOperationUtils
- .addComponentInstanceToComponentContainer(vfc2FromVfc1, vfResource, UserRoleEnum.DESIGNER, true).left()
- .value();
+ componentInstDetails = AtomicOperationUtils.addComponentInstanceToComponentContainer(vfc2FromVfc1, vfResource, UserRoleEnum.DESIGNER, true).left().value();
vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER);
- PropertyRestUtils.updatePropertyListWithPathOnResource(componentInstDetails, vfc2FromVfc1, expectedPropertyList,
- vfResource);
+ PropertyRestUtils.updatePropertyListWithPathOnResource(componentInstDetails, vfc2FromVfc1, expectedPropertyList, vfResource);
vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER);
actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(vfResource, actualPropertyList, null);
PropertyRestUtils.comparePropertyLists(expectedPropertyList, actualPropertyList, false);
@@ -250,32 +222,23 @@ public class ComponentInstancePropertyTest extends ComponentBaseTest {
@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);
+ 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);
+ 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.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);
+ PropertyRestUtils.updatePropertyListWithPathOnResource(componentInstDetails, vfc2FromVfc1, expectedPropertyList, vfResource);
vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER);
actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(vfResource, actualPropertyList, null);
@@ -284,25 +247,19 @@ public class ComponentInstancePropertyTest extends ComponentBaseTest {
PropertyRestUtils.comparePropertyLists(expectedPropertyList, actualPropertyList, false);
// update property
- ComponentInstanceProperty expectedUpdatePropDetails = PropertyRestUtils
- .getPropFromListByPropNameAndType(actualPropertyList, propNameToUpdate, propTypeToUpdate);
+ 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);
+ 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));
+ ComponentInstanceProperty actualUpdatedPropDetails = PropertyRestUtils.getPropFromListByPropIdAndPath(actualPropertyList, propUniqeId, null);
+ assertTrue("property was not updated propely", PropertyRestUtils.comparePropertyObjects(expectedUpdatePropDetails, actualUpdatedPropDetails, true));
}
@@ -311,31 +268,22 @@ public class ComponentInstancePropertyTest extends ComponentBaseTest {
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);
+ 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);
+ AtomicOperationUtils.changeComponentState(vfc1FromBasicVFC, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true);
- vfc2FromVfc1 = createResourceWithPropertyDerivedFromOtherResource(ElementFactory.getDefaultBooleanProperty(),
- LifeCycleStatesEnum.CHECKIN, vfc1FromBasicVFC);
+ 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.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);
+ PropertyRestUtils.updatePropertyListWithPathOnResource(componentInstDetails, vfc2FromVfc1, expectedPropertyList, vfResource);
vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER);
actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(vfResource, actualPropertyList, null);
@@ -343,26 +291,19 @@ public class ComponentInstancePropertyTest extends ComponentBaseTest {
PropertyRestUtils.comparePropertyLists(expectedPropertyList, actualPropertyList, false);
// update property
- ComponentInstanceProperty expectedUpdatePropDetails = PropertyRestUtils
- .getPropFromListByPropNameAndType(actualPropertyList, propNameToUpdate, propTypeToUpdate);
+ 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(),
+ 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));
+ ComponentInstanceProperty actualUpdatedPropDetails = PropertyRestUtils.getPropFromListByPropIdAndPath(actualPropertyList, propUniqeId, null);
+ assertTrue("property was not updated properly", PropertyRestUtils.comparePropertyObjects(expectedUpdatePropDetails, actualUpdatedPropDetails, true));
}
@@ -370,32 +311,23 @@ public class ComponentInstancePropertyTest extends ComponentBaseTest {
public void nestedVfResourceProperty3LevelsUpdateThirdLevelProperty() throws Exception {
basicVFC = createResourceWithProperty(ElementFactory.getDefaultStringProperty(), LifeCycleStatesEnum.CERTIFY);
- vfc1FromBasicVFC = createResourceWithPropertyDerivedFromOtherResource(
- ElementFactory.getDefaultIntegerProperty(), LifeCycleStatesEnum.CERTIFY, basicVFC);
+ 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);
+ 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);
+ 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.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);
+ PropertyRestUtils.updatePropertyListWithPathOnResource(componentInstDetails, vfc2FromVfc1, expectedPropertyList, vfResource);
vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER);
actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(vfResource, actualPropertyList, null);
@@ -403,24 +335,18 @@ public class ComponentInstancePropertyTest extends ComponentBaseTest {
PropertyRestUtils.comparePropertyLists(expectedPropertyList, actualPropertyList, false);
// update property
- ComponentInstanceProperty expectedUpdatePropDetails = PropertyRestUtils
- .getPropFromListByPropNameAndType(actualPropertyList, propNameToUpdate, propTypeToUpdate);
+ 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);
+ 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));
+ ComponentInstanceProperty actualUpdatedPropDetails = PropertyRestUtils.getPropFromListByPropIdAndPath(actualPropertyList, propUniqeId, null);
+ assertTrue("property was not updated propely", PropertyRestUtils.comparePropertyObjects(expectedUpdatePropDetails, actualUpdatedPropDetails, true));
}
@@ -433,57 +359,41 @@ public class ComponentInstancePropertyTest extends ComponentBaseTest {
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);
+ 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.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);
+ 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();
+ componentInstDetails = AtomicOperationUtils.addComponentInstanceToComponentContainer(vfResource, service, UserRoleEnum.DESIGNER, true).left().value();
service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER);
- PropertyRestUtils.updatePropertyListWithPathOnComponentInstance(componentInstDetails, service,
- expectedPropertyList);
+ 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)
+ * 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);
+ 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.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);
+ PropertyRestUtils.updatePropertyListWithPathOnResource(componentInstDetails, vfc2FromVfc1, expectedPropertyList, vfResource);
PropertyReqDetails propDetails = ElementFactory.getDefaultBooleanProperty();
propDetails.setName(newBooleanPropName);
propDetails.setPropertyDefaultValue(newBooleanPropValue);
@@ -501,36 +411,28 @@ public class ComponentInstancePropertyTest extends ComponentBaseTest {
expectedPropertyList = PropertyRestUtils.addResourcePropertiesToList(vfResource, expectedPropertyList);
Service service = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value();
- componentInstDetails = AtomicOperationUtils
- .addComponentInstanceToComponentContainer(vfResource, service, 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);
+ 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)
+ * 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);
+ 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();
+ 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");
@@ -539,54 +441,40 @@ public class ComponentInstancePropertyTest extends ComponentBaseTest {
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.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();
+ 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);
+ 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();
+ componentInstDetails = AtomicOperationUtils.addComponentInstanceToComponentContainer(vfResource, service, UserRoleEnum.DESIGNER, true).left().value();
service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER);
- PropertyRestUtils.updatePropertyListWithPathOnComponentInstance(componentInstDetails, service,
- expectedPropertyList);
+ 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)
+ * 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);
+ 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();
+ 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");
@@ -594,75 +482,55 @@ public class ComponentInstancePropertyTest extends ComponentBaseTest {
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();
+ 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.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();
+ 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();
+ 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);
+ 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)
+ * 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)
+ * 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);
+ 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.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);
+ PropertyRestUtils.updatePropertyListWithPathOnResource(componentInstDetails, vfc2FromVfc1, expectedPropertyList, vfResource);
- componentInstDetails = AtomicOperationUtils
- .addComponentInstanceToComponentContainer(vfc2FromVfc1, vfResource, UserRoleEnum.DESIGNER, true).left()
- .value();
+ componentInstDetails = AtomicOperationUtils.addComponentInstanceToComponentContainer(vfc2FromVfc1, vfResource, UserRoleEnum.DESIGNER, true).left().value();
vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER);
- PropertyRestUtils.updatePropertyListWithPathOnResource(componentInstDetails, vfc2FromVfc1, expectedPropertyList,
- vfResource);
+ 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);
@@ -671,23 +539,15 @@ public class ComponentInstancePropertyTest extends ComponentBaseTest {
// Service
expectedPropertyList = new ArrayList<ComponentInstanceProperty>();
actualPropertyList = new ArrayList<ComponentInstanceProperty>();
- expectedPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(vfResource, expectedPropertyList,
- null);
- expectedPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(vfResource, expectedPropertyList,
- null);
+ 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();
+ 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();
+ 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);
+ PropertyRestUtils.updatePropertyListWithPathOnComponentInstance(componentInstDetails, service, expectedPropertyList);
service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER);
actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(service, actualPropertyList, null);
PropertyRestUtils.comparePropertyLists(expectedPropertyList, actualPropertyList, false);
@@ -696,25 +556,19 @@ public class ComponentInstancePropertyTest extends ComponentBaseTest {
// service test template
/**
- * Service-->VF(inst)-->VF-->(VFC(inst)-->VFC-->VFC-->VFC) (p4) (p3) (p2)
- * (p1)
+ * 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);
+ 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.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);
@@ -726,15 +580,11 @@ public class ComponentInstancePropertyTest extends ComponentBaseTest {
// 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();
+ componentInstDetails = AtomicOperationUtils.addComponentInstanceToComponentContainer(vfResource, service, UserRoleEnum.DESIGNER, true).left().value();
service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER);
- PropertyRestUtils.updatePropertyListWithPathOnComponentInstance(componentInstDetails, service,
- expectedPropertyList);
+ PropertyRestUtils.updatePropertyListWithPathOnComponentInstance(componentInstDetails, service, expectedPropertyList);
service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER);
actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(service, actualPropertyList, null);
PropertyRestUtils.comparePropertyLists(expectedPropertyList, actualPropertyList, false);
@@ -745,32 +595,25 @@ public class ComponentInstancePropertyTest extends ComponentBaseTest {
* update property(p4)
*
*
- * VFC(p1) ^ | VFC(p2) ^ | Service-->VF(inst)-->VF-->(VFC(inst)-->VFC(p3)
- * (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);
+ 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.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);
+ 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);
@@ -779,72 +622,51 @@ public class ComponentInstancePropertyTest extends ComponentBaseTest {
// 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();
+ componentInstDetails = AtomicOperationUtils.addComponentInstanceToComponentContainer(vfResource, service, UserRoleEnum.DESIGNER, true).left().value();
service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER);
- PropertyRestUtils.updatePropertyListWithPathOnComponentInstance(componentInstDetails, service,
- expectedPropertyList);
+ 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);
+ 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);
+ 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));
+ 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)
+ * 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);
+ 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);
+ 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.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);
@@ -856,72 +678,51 @@ public class ComponentInstancePropertyTest extends ComponentBaseTest {
// 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();
+ componentInstDetails = AtomicOperationUtils.addComponentInstanceToComponentContainer(vfResource, service, UserRoleEnum.DESIGNER, true).left().value();
service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER);
- PropertyRestUtils.updatePropertyListWithPathOnComponentInstance(componentInstDetails, service,
- expectedPropertyList);
+ 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);
+ 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);
+ 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));
+ 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)
+ * update property(p2) Service-->VF(inst)-->VF-->(VFC(inst)-->VFC-->VFC-->VFC) (p4) (p3) (p2) (p1)
*/
@Test
- public void serviceNestedVfResourceProperty3LevelsAndSelfVfPropertyUpdateVfInheritance2LevelProperty()
- throws Exception {
+ 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);
+ 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);
+ 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();
+ 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();
@@ -934,70 +735,49 @@ public class ComponentInstancePropertyTest extends ComponentBaseTest {
// 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();
+ componentInstDetails = AtomicOperationUtils.addComponentInstanceToComponentContainer(vfResource, service, UserRoleEnum.DESIGNER, true).left().value();
service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER);
- PropertyRestUtils.updatePropertyListWithPathOnComponentInstance(componentInstDetails, service,
- expectedPropertyList);
+ 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);
+ 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);
+ 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));
+ 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)
+ * update property(p3) Service-->VF(inst)-->VF-->(VFC(inst)-->VFC-->VFC-->VFC) (p4) (p3) (p2) (p1)
*/
@Test
- public void serviceNestedVfResourceProperty3LevelsAndSelfVfPropertyUpdateVfInheritance3LevelProperty()
- throws Exception {
+ 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);
+ 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);
+ 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();
+ 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);
@@ -1009,64 +789,48 @@ public class ComponentInstancePropertyTest extends ComponentBaseTest {
// 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();
+ componentInstDetails = AtomicOperationUtils.addComponentInstanceToComponentContainer(vfResource, service, UserRoleEnum.DESIGNER, true).left().value();
service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER);
- PropertyRestUtils.updatePropertyListWithPathOnComponentInstance(componentInstDetails, service,
- expectedPropertyList);
+ 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);
+ 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);
+ 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));
+ 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')
+ * 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);
+ 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();
+ 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");
@@ -1074,36 +838,26 @@ public class ComponentInstancePropertyTest extends ComponentBaseTest {
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();
+ 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.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();
+ componentInstDetails = AtomicOperationUtils.addComponentInstanceToComponentContainer(vfResource, service, UserRoleEnum.DESIGNER, true).left().value();
service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER);
- PropertyRestUtils.updatePropertyListWithPathOnComponentInstance(componentInstDetails, service,
- expectedPropertyList);
+ PropertyRestUtils.updatePropertyListWithPathOnComponentInstance(componentInstDetails, service, expectedPropertyList);
- componentInstDetails = AtomicOperationUtils
- .addComponentInstanceToComponentContainer(cp, service, UserRoleEnum.DESIGNER, true).left().value();
+ componentInstDetails = AtomicOperationUtils.addComponentInstanceToComponentContainer(cp, service, UserRoleEnum.DESIGNER, true).left().value();
service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER);
- PropertyRestUtils.updatePropertyListWithPathOnComponentInstance(componentInstDetails, service,
- expectedPropertyList);
+ PropertyRestUtils.updatePropertyListWithPathOnComponentInstance(componentInstDetails, service, expectedPropertyList);
// service = AtomicOperationUtils.getServiceObject(service,
// UserRoleEnum.DESIGNER);
@@ -1114,49 +868,37 @@ public class ComponentInstancePropertyTest extends ComponentBaseTest {
String propTypeToUpdate = "string";
// update CP property
- ComponentInstanceProperty expectedUpdatePropDetails = PropertyRestUtils.getCompPropInstListByInstIdAndPropName(
- service, componentInstDetails, propNameToUpdate, propTypeToUpdate);
+ 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);
+ 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));
+ 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')
+ * 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);
+ 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();
+ 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");
@@ -1164,36 +906,26 @@ public class ComponentInstancePropertyTest extends ComponentBaseTest {
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();
+ 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.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();
+ componentInstDetails = AtomicOperationUtils.addComponentInstanceToComponentContainer(vfResource, service, UserRoleEnum.DESIGNER, true).left().value();
service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER);
- PropertyRestUtils.updatePropertyListWithPathOnComponentInstance(componentInstDetails, service,
- expectedPropertyList);
+ PropertyRestUtils.updatePropertyListWithPathOnComponentInstance(componentInstDetails, service, expectedPropertyList);
- componentInstDetails = AtomicOperationUtils
- .addComponentInstanceToComponentContainer(cp, service, UserRoleEnum.DESIGNER, true).left().value();
+ componentInstDetails = AtomicOperationUtils.addComponentInstanceToComponentContainer(cp, service, UserRoleEnum.DESIGNER, true).left().value();
service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER);
- PropertyRestUtils.updatePropertyListWithPathOnComponentInstance(componentInstDetails, service,
- expectedPropertyList);
+ PropertyRestUtils.updatePropertyListWithPathOnComponentInstance(componentInstDetails, service, expectedPropertyList);
service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER);
actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(service, actualPropertyList, null);
@@ -1203,27 +935,61 @@ public class ComponentInstancePropertyTest extends ComponentBaseTest {
String propTypeToUpdate = "string";
// update CP property
- ComponentInstanceProperty expectedUpdatePropDetails = PropertyRestUtils.getCompPropInstListByInstIdAndPropName(
- service, componentInstDetails, propNameToUpdate, propTypeToUpdate);
+ 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);
+ 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));
+ 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) {
@@ -1235,11 +1001,8 @@ public class ComponentInstancePropertyTest extends ComponentBaseTest {
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();
+ 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);
}
@@ -1248,11 +1011,8 @@ public class ComponentInstancePropertyTest extends ComponentBaseTest {
// 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();
+ 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);
}
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
index e1c4c18270..7ecdcf457f 100644
--- 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
@@ -99,8 +99,8 @@ public class ComponentProperty extends ComponentBaseTest {
{ "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 , one , 1 ,
- // false, f , off , 0
+ // 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]" },
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
index d1302c8d8c..6a5aeec5c9 100644
--- 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
@@ -28,6 +28,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import org.apache.log4j.lf5.util.ResourceUtils;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.junit.Rule;
@@ -45,6 +46,7 @@ import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum;
import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest;
import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
import org.openecomp.sdc.ci.tests.preRequisites.SimpleOneRsrcOneServiceTest;
+import org.openecomp.sdc.ci.tests.utils.Utils;
import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
import org.openecomp.sdc.ci.tests.utils.rest.PropertyRestUtils;
import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
@@ -55,6 +57,8 @@ import org.testng.AssertJUnit;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
+import com.google.gson.Gson;
+
public class PropertyApisTest extends SimpleOneRsrcOneServiceTest {
protected static final String RESOURCE_CATEGORY = "Generic/Databases";
@@ -79,10 +83,6 @@ public class PropertyApisTest extends SimpleOneRsrcOneServiceTest {
@BeforeMethod
public void init() throws Exception {
- // //Create user
- // sdncDesignerDetails = createUser("tu1234", "Test", "User",
- // "tu1234@intl.sdc.com", "DESIGNER");
- //
// //Delete resource
//
// resourceDetails = new ResourceReqDetails();
@@ -117,7 +117,7 @@ public class PropertyApisTest extends SimpleOneRsrcOneServiceTest {
// Create property
// System.out.println ("---- Create Property (POST) ----");
- String propertyId = UniqueIdBuilder.buildPropertyUniqueId(getResourceId(resourceDetails), property.getName());
+ String propertyId = UniqueIdBuilder.buildComponentPropertyUniqueId(getResourceId(resourceDetails), property.getName());
PropertyRestUtils.deleteProperty(getResourceId(resourceDetails), propertyId, sdncDesignerDetails);
RestResponse createPropertyResponse = PropertyRestUtils.createProperty(getResourceId(resourceDetails), body,
@@ -194,7 +194,7 @@ public class PropertyApisTest extends SimpleOneRsrcOneServiceTest {
protected String getPropertyId(ResourceReqDetails resource, PropertyReqDetails property) {
// return
// resource.getResourceName().toLowerCase()+".0.1."+property.getPropertyName();
- return UniqueIdBuilder.buildPropertyUniqueId(resource.getUniqueId(), property.getName());
+ return UniqueIdBuilder.buildComponentPropertyUniqueId(resource.getUniqueId(), property.getName());
}
protected String getResourceId(ResourceReqDetails resource) {
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
index 85dfe4e13a..0ec6b00fdc 100644
--- 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
@@ -25,6 +25,7 @@ import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
import org.openecomp.sdc.common.util.SerializationUtils;
+import org.testng.annotations.Test;
import fj.data.Either;
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
index d05dd1039a..4847491759 100644
--- 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
@@ -91,7 +91,7 @@ public class ComponentRelationshipInVfTest extends ComponentBaseTest {
designerUser.getUserId(), ResourceTypeEnum.CP.toString()); // resourceType
// =
// VFC
- resourceDetailsCap = ElementFactory.getDefaultResourceByType("MyCompute", NormativeTypesEnum.COMPUTE,
+ resourceDetailsCap = ElementFactory.getDefaultResourceByType("ciMyCompute", NormativeTypesEnum.COMPUTE,
ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, designerUser.getUserId(), ResourceTypeEnum.CP.toString()); // resourceType
// =
// VFC
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
index a9ed54ef15..f4e51b14d9 100644
--- 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
@@ -23,6 +23,7 @@ package org.openecomp.sdc.ci.tests.execute.resource;
import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_SUCCESS;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNotNull;
+import static org.testng.AssertJUnit.assertTrue;
import java.util.ArrayList;
import java.util.Arrays;
@@ -30,13 +31,18 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import javax.validation.constraints.AssertTrue;
+
+import org.apache.log4j.lf5.util.ResourceUtils;
import org.junit.Rule;
import org.junit.rules.TestName;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.LifecycleStateEnum;
import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.Service;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
import org.openecomp.sdc.ci.tests.api.Urls;
@@ -46,6 +52,7 @@ import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails;
import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
import org.openecomp.sdc.ci.tests.datatypes.ResourceRespJavaObject;
import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo;
import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum;
@@ -58,6 +65,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.DbUtils;
import org.openecomp.sdc.ci.tests.utils.Utils;
+import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils;
import org.openecomp.sdc.ci.tests.utils.general.Convertor;
import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
import org.openecomp.sdc.ci.tests.utils.rest.ArtifactRestUtils;
@@ -70,6 +78,7 @@ import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils;
import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils;
import org.openecomp.sdc.ci.tests.utils.validation.ResourceValidationUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.ServiceValidationUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.Test;
@@ -884,7 +893,7 @@ public class CreateResourceApiTest extends ComponentBaseTest {
ResourceReqDetails resourceDetails = createRandomResource();
- // set null in userId header
+ // set null in UserId header
sdncModifierDetails.setUserId(null);
// create resource
@@ -1177,6 +1186,19 @@ public class CreateResourceApiTest extends ComponentBaseTest {
// 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"));
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
new file mode 100644
index 0000000000..cd87ea5265
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/CustomizationUUIDTest.java
@@ -0,0 +1,433 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 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
index a3372098a0..25c3242d2c 100644
--- 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
@@ -27,6 +27,7 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
+import org.apache.log4j.lf5.util.ResourceUtils;
import org.junit.rules.TestName;
import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.User;
@@ -37,6 +38,7 @@ import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum;
import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
import org.openecomp.sdc.ci.tests.utils.DbUtils;
+import org.openecomp.sdc.ci.tests.utils.Utils;
import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils;
import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
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
index ccf6142538..cdb7dc0304 100644
--- 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
@@ -30,6 +30,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import org.apache.log4j.lf5.util.ResourceUtils;
import org.junit.Rule;
import org.junit.rules.TestName;
import org.openecomp.sdc.be.model.User;
@@ -44,6 +45,7 @@ import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum;
import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest;
import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
import org.openecomp.sdc.ci.tests.execute.imports.ImportGenericResourceCITest;
+import org.openecomp.sdc.ci.tests.utils.Utils;
import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
import org.slf4j.Logger;
@@ -119,7 +121,7 @@ public class GetResourceNotAbstractApiTest extends ComponentBaseTest {
toFind.add(portUid);
boolean removeAll = toFind.removeAll(actualNotAbstarctResourcesUniqueIdArray);
- logger.debug("Cannot find resources {}", toFind.toString());
+ logger.debug("Cannot find resources {}",toFind.toString());
for (String expectedResource : expectedNotAbstractResourcesUniqueIdArray) {
if (false == actualNotAbstarctResourcesUniqueIdArray.contains(expectedResource)) {
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
index eac33242ed..feb7b6f42e 100644
--- 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
@@ -33,6 +33,7 @@ import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
+import org.apache.log4j.lf5.util.ResourceUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
@@ -108,7 +109,11 @@ public class ResourceApiTest extends ComponentBaseTest {
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();
@@ -211,7 +216,8 @@ public class ResourceApiTest extends ComponentBaseTest {
httpget.addHeader(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
- httpget.addHeader(HttpHeaderEnum.USER_ID.getValue(), ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER).getUserId());
+ httpget.addHeader(HttpHeaderEnum.USER_ID.getValue(),
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER).getUserId());
// System.out.println("Executing request " +
// httpget.getRequestLine());
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
index de83385029..3002523ccb 100644
--- 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
@@ -84,6 +84,28 @@ public class SimultaneousApiTest extends ComponentBaseTest {
}
+ // 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
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
index b61489d12d..da5b469a4f 100644
--- 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
@@ -40,6 +40,7 @@ import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
import org.openecomp.sdc.be.model.LifecycleStateEnum;
import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.category.CategoryDefinition;
import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
import org.openecomp.sdc.ci.tests.api.Urls;
import org.openecomp.sdc.ci.tests.config.Config;
@@ -228,7 +229,7 @@ public class UpdateResourceMetadataTest extends ComponentBaseTest {
}
public char[] getTagInValidFormatChars() throws Exception {
- // Tag format is the same as defined for Resource Name :
+ // 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];
@@ -468,6 +469,7 @@ public class UpdateResourceMetadataTest extends ComponentBaseTest {
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 {
@@ -591,6 +593,52 @@ public class UpdateResourceMetadataTest extends ComponentBaseTest {
}
+ // @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);
@@ -962,7 +1010,7 @@ public class UpdateResourceMetadataTest extends ComponentBaseTest {
@Test
public void UpdateResourceIcon_resourceVersion_11() throws Exception {
- // Can be changed only if major version is 0.
+ // Can be changed only if major version is "0".
User adminModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
String resourceBaseVersion = "0.1";
@@ -1022,7 +1070,7 @@ public class UpdateResourceMetadataTest extends ComponentBaseTest {
@Test
public void UpdateResourceVandorName_resourceVersion_11() throws Exception {
- // Can be changed only if the major resource version is 0.
+ // Can be changed only if the major resource version is "0".
User adminModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
String resourceBaseVersion = "0.1";
@@ -1084,7 +1132,7 @@ public class UpdateResourceMetadataTest extends ComponentBaseTest {
@Test
public void UpdateResourceName_resourceVersion_11() throws Exception {
- // Can be changed only if the major resource version is 0.
+ // Can be changed only if the major resource version is "0".
User adminModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
String resourceBaseVersion = "0.1";
@@ -1139,7 +1187,7 @@ public class UpdateResourceMetadataTest extends ComponentBaseTest {
@Test
public void UpdateResourceTag_resourceVersion_11() throws Exception {
- // Tag Can be updated when major version is 0.
+ // Tag Can be updated when major version is "0".
User adminModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
String resourceBaseVersion = "0.1";
@@ -1199,7 +1247,7 @@ public class UpdateResourceMetadataTest extends ComponentBaseTest {
public void UpdateAllowedParames_resourceVersion_11() throws Exception {
// Tag, contactId, vendorRelease,tags And description - Can be also
- // updated when major version is NOT 0.
+ // updated when major version is NOT "0".
User adminModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
String resourceBaseVersion = "0.1";
@@ -1259,7 +1307,7 @@ public class UpdateResourceMetadataTest extends ComponentBaseTest {
@Test
public void UpdateResourceDerivedFrom_resourceVersion_11() throws Exception {
- // DerivedFrom parameter - Can be updated when major version is 0.
+ // DerivedFrom parameter - Can be updated when major version is "0".
User adminModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
String resourceBaseVersion = "0.1";
@@ -1302,7 +1350,7 @@ public class UpdateResourceMetadataTest extends ComponentBaseTest {
RestResponse updatedRestResponse = ResourceRestUtils.updateResourceMetadata(updatedResourceDetails, sdncModifierDetails, resourceDetails.getUniqueId(), "");
// validate response
List<String> resourceList = new ArrayList<String>();
- ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESOURCE_DERIVED_FROM_CANNOT_BE_CHANGED.name(), resourceList, updatedRestResponse.getResponse());
+ ResourceRestUtils.checkSuccess(updatedRestResponse);
// get resource with original name. original metadata should be returned
RestResponse getRestResponse = ResourceRestUtils.getResource(sdncModifierDetails, resourceDetails.getUniqueId());
@@ -1540,26 +1588,26 @@ public class UpdateResourceMetadataTest extends ComponentBaseTest {
@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
+ // (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);
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
index 895390f764..59050103ca 100644
--- 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
@@ -57,6 +57,7 @@ import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils;
import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import com.google.gson.Gson;
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
index 37e7539fd9..8a17c3c115 100644
--- 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
@@ -23,6 +23,7 @@ package org.openecomp.sdc.ci.tests.execute.resource;
import static org.testng.AssertJUnit.assertNotNull;
import static org.testng.AssertJUnit.assertTrue;
+import java.io.IOException;
import java.util.List;
import org.json.simple.JSONArray;
@@ -31,6 +32,8 @@ import org.json.simple.JSONValue;
import org.junit.Rule;
import org.junit.rules.TestName;
import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.ArtifactDefinition;
+import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.ComponentInstance;
import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.User;
@@ -43,6 +46,7 @@ import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum;
import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum;
import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.execute.lifecycle.LCSbaseTest;
import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils;
import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils;
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
index c8a20cf44a..3d338534d1 100644
--- 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
@@ -32,6 +32,7 @@ import org.junit.Rule;
import org.junit.rules.TestName;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.ArtifactDefinition;
import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.DistributionStatusEnum;
import org.openecomp.sdc.be.model.LifecycleStateEnum;
@@ -44,6 +45,7 @@ import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo;
import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ServiceCategoriesEnum;
import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedResourceAuditJavaObject;
import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
@@ -59,6 +61,8 @@ import org.openecomp.sdc.ci.tests.utils.validation.ServiceValidationUtils;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
+import fj.data.Either;
+
public class ChangeServiceDistributionStatusApiTest extends ComponentBaseTest {
protected ResourceReqDetails resourceDetails;
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
index 56cfeb54ea..8e95a6d02c 100644
--- 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
@@ -20,6 +20,7 @@
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;
@@ -36,6 +37,7 @@ import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.LifecycleStateEnum;
+import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.Service;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
@@ -47,6 +49,7 @@ import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo;
import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ServiceCategoriesEnum;
import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedResourceAuditJavaObject;
import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum;
@@ -60,6 +63,7 @@ import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
import org.openecomp.sdc.ci.tests.utils.rest.ComponentInstanceRestUtils;
import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils;
import org.openecomp.sdc.ci.tests.utils.rest.ProductRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils;
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
index 760d002856..3460cd6e04 100644
--- 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
@@ -28,6 +28,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import org.apache.cassandra.transport.Event.SchemaChange.Target;
import org.junit.Rule;
import org.junit.rules.TestName;
import org.openecomp.sdc.be.dao.api.ActionStatus;
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
index b84728a06c..5642ce4745 100644
--- 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
@@ -23,16 +23,21 @@ package org.openecomp.sdc.ci.tests.execute.service;
import static org.testng.AssertJUnit.assertTrue;
import java.io.IOException;
+import java.util.ArrayList;
import java.util.HashMap;
+import java.util.List;
import java.util.Map;
+import java.util.stream.Collectors;
import org.apache.http.HttpStatus;
+import org.apache.log4j.lf5.util.ResourceUtils;
import org.junit.Rule;
import org.junit.rules.TestName;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
import org.openecomp.sdc.ci.tests.api.Urls;
import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
@@ -54,12 +59,15 @@ import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
import org.openecomp.sdc.common.api.Constants;
+import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
import org.openecomp.sdc.common.datastructure.Wrapper;
import org.testng.AssertJUnit;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
+import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
import fj.data.Either;
@@ -81,7 +89,8 @@ public class GetComponentAuditApiTest extends ComponentBaseTest {
// 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");
+ 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";
@@ -104,7 +113,8 @@ public class GetComponentAuditApiTest extends ComponentBaseTest {
public void testServiceAuditCertifiedVersion() throws Exception {
ServiceReqDetails serviceDetails = ElementFactory.getDefaultService();
- Wrapper<String> versionZeroOneIDWrapper = new Wrapper<String>(), versionZeroTwoIDWrapper = new Wrapper<String>();
+ Wrapper<String> versionZeroOneIDWrapper = new Wrapper<String>(),
+ versionZeroTwoIDWrapper = new Wrapper<String>();
createBasicServiceForAudit(versionZeroOneIDWrapper, versionZeroTwoIDWrapper, serviceDetails, true);
// First Certification
@@ -129,14 +139,35 @@ public class GetComponentAuditApiTest extends ComponentBaseTest {
// updates(tosca) + certification request + certification start +
// certification success
// + 3 A&AI(ArtifactDelete, ArtifactUpload, ArtifactUpdate)
- AssertJUnit.assertTrue("expected: 17, actual: " + element.getAsJsonArray().size(), element.getAsJsonArray().size() == 17);
+ 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);
+ RestResponse response = LifecycleRestUtils.changeResourceState(defaultResource, sdncDesignerUser,
+ LifeCycleStatesEnum.CERTIFICATIONREQUEST);
AssertJUnit.assertTrue(response.getErrorCode() == HttpStatus.SC_OK);
- response = LifecycleRestUtils.changeResourceState(defaultResource, sdncTesterUser, LifeCycleStatesEnum.STARTCERTIFICATION);
+ 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);
@@ -148,7 +179,8 @@ public class GetComponentAuditApiTest extends ComponentBaseTest {
put(Constants.USER_ID_HEADER, UserRoleEnum.ADMIN.getUserId());
}
};
- String url = String.format(Urls.GET_COMPONENT_AUDIT_RECORDS, config.getCatalogBeHost(), config.getCatalogBePort(), componentType, componentId);
+ 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);
@@ -157,7 +189,9 @@ public class GetComponentAuditApiTest extends ComponentBaseTest {
return element;
}
- protected void createBasicServiceForAudit(Wrapper<String> versionZeroOneIDWrapper, Wrapper<String> versionZeroTwoIDWrapper, ServiceReqDetails serviceDetails, Boolean withResInst) throws Exception {
+ protected void createBasicServiceForAudit(Wrapper<String> versionZeroOneIDWrapper,
+ Wrapper<String> versionZeroTwoIDWrapper, ServiceReqDetails serviceDetails, Boolean withResInst)
+ throws Exception {
User designerUser = sdncDesignerUser;
@@ -166,13 +200,17 @@ public class GetComponentAuditApiTest extends ComponentBaseTest {
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);
+ 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);
+ ComponentInstanceRestUtils.createComponentInstance(resourceInstanceReqDetails, sdncDesignerUser,
+ serviceDetails.getUniqueId(), ComponentTypeEnum.SERVICE);
// ServiceUtils.createCertResourceWithDeploymentArt(serviceDetails,
// "myResource");
@@ -200,14 +238,16 @@ public class GetComponentAuditApiTest extends ComponentBaseTest {
}
protected void increaseServiceVersion(ServiceReqDetails serviceDetails, String excpectedVersion) throws Exception {
- RestResponse response = LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerUser, LifeCycleStatesEnum.CHECKOUT);
+ 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 {
+ protected void createBasicResourceForAudit(Wrapper<String> versionOnePointTwoIDWrapper,
+ ResourceReqDetails defaultResource) throws Exception {
RestResponse response = ResourceRestUtils.createResource(defaultResource, sdncDesignerUser);
AssertJUnit.assertTrue(response.getErrorCode() == HttpStatus.SC_CREATED);
@@ -218,11 +258,15 @@ public class GetComponentAuditApiTest extends ComponentBaseTest {
// 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);
+ 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);
+ response = LifecycleRestUtils.changeResourceState(defaultResource, sdncDesignerUser,
+ LifeCycleStatesEnum.CHECKIN);
increaseResourceVersion(defaultResource, "0.2");
@@ -247,11 +291,14 @@ public class GetComponentAuditApiTest extends ComponentBaseTest {
}
- protected void increaseResourceVersion(ResourceReqDetails defaultResource, String expectedVersion) throws IOException {
- RestResponse response = LifecycleRestUtils.changeResourceState(defaultResource, sdncDesignerUser, LifeCycleStatesEnum.CHECKOUT);
+ 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);
+ response = LifecycleRestUtils.changeResourceState(defaultResource, sdncDesignerUser,
+ LifeCycleStatesEnum.CHECKIN);
AssertJUnit.assertTrue(response.getErrorCode() == HttpStatus.SC_OK);
}
@@ -259,7 +306,8 @@ public class GetComponentAuditApiTest extends ComponentBaseTest {
public void testServiceAuditLastUncertifiedVersion() throws Exception {
ServiceReqDetails serviceDetails = ElementFactory.getDefaultService();
- Wrapper<String> versionZeroOneIDWrapper = new Wrapper<String>(), versionZeroTwoIDWrapper = new Wrapper<String>();
+ Wrapper<String> versionZeroOneIDWrapper = new Wrapper<String>(),
+ versionZeroTwoIDWrapper = new Wrapper<String>();
createBasicServiceForAudit(versionZeroOneIDWrapper, versionZeroTwoIDWrapper, serviceDetails, false);
@@ -273,7 +321,8 @@ public class GetComponentAuditApiTest extends ComponentBaseTest {
public void testServiceAuditFirstUncertifiedVersion() throws Exception {
ServiceReqDetails serviceDetails = ElementFactory.getDefaultService();
- Wrapper<String> versionZeroOneIDWrapper = new Wrapper<String>(), versionZeroTwoIDWrapper = new Wrapper<String>();
+ Wrapper<String> versionZeroOneIDWrapper = new Wrapper<String>(),
+ versionZeroTwoIDWrapper = new Wrapper<String>();
createBasicServiceForAudit(versionZeroOneIDWrapper, versionZeroTwoIDWrapper, serviceDetails, false);
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
index 19bed4d380..55ecf694ee 100644
--- 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
@@ -46,6 +46,7 @@ import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum;
import org.openecomp.sdc.ci.tests.datatypes.enums.ServiceCategoriesEnum;
import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.Utils;
import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
import org.openecomp.sdc.ci.tests.utils.rest.ArtifactRestUtils;
import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils;
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/ServiceComponentInstanceCRUDTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/ServiceComponentInstanceCRUDTest.java
index b2728ea0da..149febf05c 100644
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/ServiceComponentInstanceCRUDTest.java
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/ServiceComponentInstanceCRUDTest.java
@@ -42,6 +42,7 @@ import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
import org.openecomp.sdc.be.model.RequirementDefinition;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.ci.tests.api.ComponentInstanceBaseTest;
+import org.openecomp.sdc.ci.tests.api.Urls;
import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails;
import org.openecomp.sdc.ci.tests.datatypes.ComponentReqDetails;
@@ -49,8 +50,10 @@ import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ServiceCategoriesEnum;
import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.Utils;
import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
import org.openecomp.sdc.ci.tests.utils.rest.ArtifactRestUtils;
import org.openecomp.sdc.ci.tests.utils.rest.ComponentInstanceRestUtils;
@@ -97,12 +100,10 @@ public class ServiceComponentInstanceCRUDTest extends ComponentInstanceBaseTest
createService(serviceDetails_01);
certifyResource(resourceDetailsVFC_01);
certifyResource(resourceDetailsVFC_02);
- RestResponse createAtomicResourceInstance = createAtomicInstanceForVFDuringSetup(resourceDetailsVF_01,
- resourceDetailsVFC_01, sdncDesignerDetails);
+ RestResponse createAtomicResourceInstance = createAtomicInstanceForVFDuringSetup(resourceDetailsVF_01, resourceDetailsVFC_01, sdncDesignerDetails);
ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance);
reqOwnerId = ResponseParser.getUniqueIdFromResponse(createAtomicResourceInstance);
- createAtomicResourceInstance = createAtomicInstanceForVFDuringSetup(resourceDetailsVF_02, resourceDetailsVFC_02,
- sdncDesignerDetails);
+ createAtomicResourceInstance = createAtomicInstanceForVFDuringSetup(resourceDetailsVF_02, resourceDetailsVFC_02, sdncDesignerDetails);
ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance);
capOwnerId = ResponseParser.getUniqueIdFromResponse(createAtomicResourceInstance);// should
// be
@@ -115,103 +116,80 @@ public class ServiceComponentInstanceCRUDTest extends ComponentInstanceBaseTest
}
private void certifyResource(ResourceReqDetails resource) throws Exception {
- changeResourceLifecycleState(resource, sdncDesignerDetails.getUserId(),
- LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ 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 {
+ 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 {
+ 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);
+ 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 {
+ 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 {
+ 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 {
+ 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);
+ 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);
+ 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 {
+ 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);
+ private RestResponse createCheckedinVFInstance(ServiceReqDetails containerDetails, ResourceReqDetails compInstOriginDetails, User modifier) throws Exception {
+ changeResourceLifecycleState(compInstOriginDetails, compInstOriginDetails.getCreatorUserId(), LifeCycleStatesEnum.CHECKIN);
return createVFInstance(containerDetails, compInstOriginDetails, modifier);
}
- private RestResponse createCheckedinAtomicInstanceForService(ServiceReqDetails containerDetails,
- ResourceReqDetails compInstOriginDetails, User modifier) throws Exception {
- changeResourceLifecycleState(compInstOriginDetails, compInstOriginDetails.getCreatorUserId(),
- LifeCycleStatesEnum.CHECKIN);
+ 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 {
+ 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 {
+ 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 {
+ 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);
@@ -219,8 +197,7 @@ public class ServiceComponentInstanceCRUDTest extends ComponentInstanceBaseTest
@Test
public void createVFInstanceSuccessfullyTest() throws Exception {
- RestResponse createVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01,
- sdncDesignerDetails);
+ RestResponse createVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01, sdncDesignerDetails);
ResourceRestUtils.checkCreateResponse(createVFInstResp);
createVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_02, sdncDesignerDetails);
ResourceRestUtils.checkCreateResponse(createVFInstResp);
@@ -229,37 +206,29 @@ public class ServiceComponentInstanceCRUDTest extends ComponentInstanceBaseTest
@Test
public void createVFAndAtomicInstanceTest() throws Exception {
- RestResponse createVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01,
- sdncDesignerDetails);
+ RestResponse createVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01, sdncDesignerDetails);
ResourceRestUtils.checkCreateResponse(createVFInstResp);
- createVFInstResp = createCheckedinAtomicInstanceForService(serviceDetails_01, resourceDetailsCP_01,
- sdncDesignerDetails);
+ createVFInstResp = createCheckedinAtomicInstanceForService(serviceDetails_01, resourceDetailsCP_01, sdncDesignerDetails);
ResourceRestUtils.checkCreateResponse(createVFInstResp);
- createVFInstResp = createCheckedinAtomicInstanceForService(serviceDetails_01, resourceDetailsVL_01,
- sdncDesignerDetails);
+ createVFInstResp = createCheckedinAtomicInstanceForService(serviceDetails_01, resourceDetailsVL_01, sdncDesignerDetails);
ResourceRestUtils.checkCreateResponse(createVFInstResp);
- createVFInstResp = createCheckedinAtomicInstanceForService(serviceDetails_01, resourceDetailsVL_02,
- sdncDesignerDetails);
+ createVFInstResp = createCheckedinAtomicInstanceForService(serviceDetails_01, resourceDetailsVL_02, sdncDesignerDetails);
ResourceRestUtils.checkCreateResponse(createVFInstResp);
getComponentAndValidateRIs(serviceDetails_01, 4, 0);
}
@Test
public void deleteAtomicInstanceTest() throws Exception {
- RestResponse createVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01,
- sdncDesignerDetails);
+ RestResponse createVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01, sdncDesignerDetails);
// 1 rel
ResourceRestUtils.checkCreateResponse(createVFInstResp);
- createVFInstResp = createCheckedinAtomicInstanceForService(serviceDetails_01, resourceDetailsCP_01,
- sdncDesignerDetails);
+ createVFInstResp = createCheckedinAtomicInstanceForService(serviceDetails_01, resourceDetailsCP_01, sdncDesignerDetails);
// 2 rel
ResourceRestUtils.checkCreateResponse(createVFInstResp);
- createVFInstResp = createCheckedinAtomicInstanceForService(serviceDetails_01, resourceDetailsVL_01,
- sdncDesignerDetails);
+ createVFInstResp = createCheckedinAtomicInstanceForService(serviceDetails_01, resourceDetailsVL_01, sdncDesignerDetails);
// 3 rel
ResourceRestUtils.checkCreateResponse(createVFInstResp);
- createVFInstResp = createCheckedinAtomicInstanceForService(serviceDetails_01, resourceDetailsVL_02,
- sdncDesignerDetails);
+ createVFInstResp = createCheckedinAtomicInstanceForService(serviceDetails_01, resourceDetailsVL_02, sdncDesignerDetails);
// 4 rel
ResourceRestUtils.checkCreateResponse(createVFInstResp);
// To delete
@@ -272,16 +241,14 @@ public class ServiceComponentInstanceCRUDTest extends ComponentInstanceBaseTest
@Test
public void deleteVFInstanceTest() throws Exception {
- RestResponse createVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01,
- sdncDesignerDetails);
+ 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);
+ createVFInstResp = createCheckedinAtomicInstanceForService(serviceDetails_01, resourceDetailsCP_01, sdncDesignerDetails);
// 3 rel
ResourceRestUtils.checkCreateResponse(createVFInstResp);
// 2 rel
@@ -303,45 +270,37 @@ public class ServiceComponentInstanceCRUDTest extends ComponentInstanceBaseTest
String capType = CAPABILITY_TYPE;
String reqName = REQUIREMENT_NAME;
- RestResponse getResourceResponse = ComponentRestUtils.getComponentRequirmentsCapabilities(sdncDesignerDetails,
- serviceDetails_01);
+ 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);
+ RequirementCapabilityRelDef requirementDef = getReqCapRelation(fromCompInstId, toCompInstId, capType, reqName, capList, reqList);
associateComponentInstancesForService(requirementDef, serviceDetails_01, sdncDesignerDetails);
- getResourceResponse = ComponentRestUtils.getComponentRequirmentsCapabilities(sdncDesignerDetails,
- serviceDetails_01);
+ 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);
+ 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);
+ 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);
+ 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);
}
@@ -359,41 +318,33 @@ public class ServiceComponentInstanceCRUDTest extends ComponentInstanceBaseTest
@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);
+ 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);
+ 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);
+ 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);
+ RestResponse createVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01, sdncDesignerDetails);
assertEquals(404, createVFInstResp.getErrorCode().intValue());
- RestResponse createAtomicInstResp = createCheckedinAtomicInstanceForService(serviceDetails_01,
- resourceDetailsCP_01, sdncDesignerDetails);
+ RestResponse createAtomicInstResp = createCheckedinAtomicInstanceForService(serviceDetails_01, resourceDetailsCP_01, sdncDesignerDetails);
assertEquals(404, createAtomicInstResp.getErrorCode().intValue());
}
@@ -405,51 +356,40 @@ public class ServiceComponentInstanceCRUDTest extends ComponentInstanceBaseTest
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);
+ 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);
+ 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);
+ 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);
+ 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);
+ 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);
+ changeResourceLifecycleState(resourceDetailsVF_01, sdncDesignerDetails.getUserId(), LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ changeResourceLifecycleState(resourceDetailsCP_01, sdncDesignerDetails.getUserId(), LifeCycleStatesEnum.CERTIFICATIONREQUEST);
createVFInstanceAndAtomicResourceInstanceSuccessully(resourceDetailsVF_01, resourceDetailsCP_01);
getComponentAndValidateRIs(serviceDetails_01, 2, 0);
@@ -457,18 +397,13 @@ public class ServiceComponentInstanceCRUDTest extends ComponentInstanceBaseTest
@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);
+ 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);
}
@@ -478,8 +413,7 @@ public class ServiceComponentInstanceCRUDTest extends ComponentInstanceBaseTest
certifyResource(resourceDetailsVF_01);
certifyResource(resourceDetailsCP_01);
- createVFInstanceAndAtomicResourceInstanceWithoutCheckin(resourceDetailsVF_01, resourceDetailsCP_01,
- sdncDesignerDetails);
+ createVFInstanceAndAtomicResourceInstanceWithoutCheckin(resourceDetailsVF_01, resourceDetailsCP_01, sdncDesignerDetails);
}
@Test
@@ -492,11 +426,9 @@ public class ServiceComponentInstanceCRUDTest extends ComponentInstanceBaseTest
vfResource.setTags(new ArrayList<String>(Arrays.asList(vfResource.getName())));
createVF(vfResource, designer2);
- RestResponse atomicInstanceForService = createCheckedinAtomicInstanceForService(serviceDetails_01,
- resourceDetailsCP_01, sdncDesignerDetails);
+ RestResponse atomicInstanceForService = createCheckedinAtomicInstanceForService(serviceDetails_01, resourceDetailsCP_01, sdncDesignerDetails);
ResourceRestUtils.checkCreateResponse(atomicInstanceForService);
- createVFInstanceFailWithoutChangeState(ActionStatus.RESTRICTED_OPERATION, new ArrayList<String>(), vfResource,
- designer2, 409);
+ createVFInstanceFailWithoutChangeState(ActionStatus.RESTRICTED_OPERATION, new ArrayList<String>(), vfResource, designer2, 409);
getComponentAndValidateRIs(serviceDetails_01, 1, 0);
}
@@ -507,17 +439,13 @@ public class ServiceComponentInstanceCRUDTest extends ComponentInstanceBaseTest
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);
+ LifecycleRestUtils.changeResourceState(resourceDetailsVF_01, sdncDesignerDetails, "0.1", LifeCycleStatesEnum.CHECKIN);
- RestResponse createFirstVFInstResp = createVFInstance(serviceDetails_01, resourceDetailsVF_01,
- sdncDesignerDetails);
+ RestResponse createFirstVFInstResp = createVFInstance(serviceDetails_01, resourceDetailsVF_01, sdncDesignerDetails);
ResourceRestUtils.checkCreateResponse(createFirstVFInstResp);
- RestResponse createSecondVFInstResp = createVFInstance(serviceDetails_01, resourceDetailsVF_01,
- sdncDesignerDetails);
+ RestResponse createSecondVFInstResp = createVFInstance(serviceDetails_01, resourceDetailsVF_01, sdncDesignerDetails);
ResourceRestUtils.checkCreateResponse(createSecondVFInstResp);
- RestResponse createThirdVFInstResp = createVFInstance(serviceDetails_01, resourceDetailsVF_01,
- sdncDesignerDetails);
+ RestResponse createThirdVFInstResp = createVFInstance(serviceDetails_01, resourceDetailsVF_01, sdncDesignerDetails);
ResourceRestUtils.checkCreateResponse(createThirdVFInstResp);
Component service = getComponentAndValidateRIs(serviceDetails_01, 3, 0);
@@ -547,10 +475,8 @@ public class ServiceComponentInstanceCRUDTest extends ComponentInstanceBaseTest
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);
+ 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);
@@ -562,32 +488,25 @@ public class ServiceComponentInstanceCRUDTest extends ComponentInstanceBaseTest
}
private void createTwoCheckedinVFInstances() throws Exception {
- RestResponse createFirstVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01,
- sdncDesignerDetails);
+ RestResponse createFirstVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01, sdncDesignerDetails);
ResourceRestUtils.checkCreateResponse(createFirstVFInstResp);
- RestResponse createSecondVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_02,
- sdncDesignerDetails);
+ 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 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 {
+ 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 {
+ private RestResponse createAtomicResourceInstanceToSecondServiceVersion(String secondServiceUniqueId, ResourceReqDetails resourceToAdd) throws Exception {
serviceDetails_01.setUniqueId(secondServiceUniqueId);
- RestResponse createAtomicResourceInstResp = createAtomicInstanceForService(serviceDetails_01, resourceToAdd,
- sdncDesignerDetails);
+ RestResponse createAtomicResourceInstResp = createAtomicInstanceForService(serviceDetails_01, resourceToAdd, sdncDesignerDetails);
ResourceRestUtils.checkCreateResponse(createAtomicResourceInstResp);
return createAtomicResourceInstResp;
}
@@ -595,12 +514,9 @@ public class ServiceComponentInstanceCRUDTest extends ComponentInstanceBaseTest
@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);
+ 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
@@ -608,10 +524,8 @@ public class ServiceComponentInstanceCRUDTest extends ComponentInstanceBaseTest
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);
+ 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);
}
@@ -620,27 +534,21 @@ public class ServiceComponentInstanceCRUDTest extends ComponentInstanceBaseTest
String oldServiceUniqueId = serviceDetails_01.getUniqueId();
- RestResponse createVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01,
- sdncDesignerDetails);
+ RestResponse createVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01, sdncDesignerDetails);
ResourceRestUtils.checkCreateResponse(createVFInstResp);
- RestResponse createAtomicResourceInstResp = createCheckedinAtomicInstanceForService(serviceDetails_01,
- resourceDetailsCP_01, sdncDesignerDetails);
+ 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);
+ 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 newVFInstanceUniqueId = oldVFInstanceUniqueId.replaceAll(oldServiceUniqueId, serviceDetails_01.getUniqueId());
String oldAtomicResourceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createAtomicResourceInstResp);
- String newAtomicResourceInstanceUniqueId = oldAtomicResourceInstanceUniqueId.replaceAll(oldServiceUniqueId,
- serviceDetails_01.getUniqueId());
+ String newAtomicResourceInstanceUniqueId = oldAtomicResourceInstanceUniqueId.replaceAll(oldServiceUniqueId, serviceDetails_01.getUniqueId());
- deleteVFInstanceAndAtomicResourceInstanceSuccessfully(newVFInstanceUniqueId, newAtomicResourceInstanceUniqueId,
- ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER2));
+ deleteVFInstanceAndAtomicResourceInstanceSuccessfully(newVFInstanceUniqueId, newAtomicResourceInstanceUniqueId, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER2));
serviceDetails_01.setUniqueId(oldServiceUniqueId);
getComponentAndValidateRIs(serviceDetails_01, 2, 0);
@@ -652,28 +560,22 @@ public class ServiceComponentInstanceCRUDTest extends ComponentInstanceBaseTest
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) throws IOException, Exception {
+ deleteVFInstanceAndAtomicResourceInstanceSuccessfully(vfInstanceUniqueId, atomicResourceInstanceUniqueId, sdncDesignerDetails);
}
- private void deleteVFInstanceAndAtomicResourceInstanceSuccessfully(String vfInstanceUniqueId,
- String atomicResourceInstanceUniqueId, User user) throws IOException, Exception {
+ 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);
+ 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);
+ 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);
}
@@ -682,10 +584,8 @@ public class ServiceComponentInstanceCRUDTest extends ComponentInstanceBaseTest
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);
+ 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);
}
@@ -693,10 +593,8 @@ public class ServiceComponentInstanceCRUDTest extends ComponentInstanceBaseTest
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);
+ 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);
}
@@ -708,8 +606,7 @@ public class ServiceComponentInstanceCRUDTest extends ComponentInstanceBaseTest
RestResponse createVFInstance = createVFInstance(serviceDetails_01, resourceDetailsVF_01, sdncDesignerDetails);
ResourceRestUtils.checkCreateResponse(createVFInstance);
String vfInstUniqueId = ResponseParser.getUniqueIdFromResponse(createVFInstance);
- RestResponse atomicInstanceForService = createAtomicInstanceForService(serviceDetails_01, resourceDetailsCP_01,
- sdncDesignerDetails);
+ RestResponse atomicInstanceForService = createAtomicInstanceForService(serviceDetails_01, resourceDetailsCP_01, sdncDesignerDetails);
ResourceRestUtils.checkCreateResponse(atomicInstanceForService);
String atomicInstUniqueId = ResponseParser.getUniqueIdFromResponse(atomicInstanceForService);
@@ -725,10 +622,8 @@ public class ServiceComponentInstanceCRUDTest extends ComponentInstanceBaseTest
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);
+ 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:
@@ -738,27 +633,22 @@ public class ServiceComponentInstanceCRUDTest extends ComponentInstanceBaseTest
@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);
+ 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);
+ 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);
+ RestResponse deleteVFInstResp = deleteVFInstance(resourceDetailsVF_01.getUniqueId(), serviceDetails_01, sdncDesignerDetails);
assertEquals(404, deleteVFInstResp.getErrorCode().intValue());
}
@@ -772,41 +662,31 @@ public class ServiceComponentInstanceCRUDTest extends ComponentInstanceBaseTest
@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);
+ 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);
+ 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);
+ 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);
+ 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,
@@ -827,22 +707,16 @@ public class ServiceComponentInstanceCRUDTest extends ComponentInstanceBaseTest
// story
@Test(enabled = false)
public void associateOnceAgainExistingRelationTest() throws Exception {
- RestResponse createFirstVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01,
- sdncDesignerDetails);
+ RestResponse createFirstVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01, sdncDesignerDetails);
String reqCompInstId = ResponseParser.getUniqueIdFromResponse(createFirstVFInstResp);
- RestResponse createSecondVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_02,
- sdncDesignerDetails);
+ 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);
+ 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);
+ RequirementCapabilityRelDef requirementDef = getReqCapRelation(reqCompInstId, capCompInstId, CAPABILITY_TYPE, REQUIREMENT_NAME, capListBeforeAssociate, reqListBeforeAssociate);
associateComponentInstancesForService(requirementDef, serviceDetails_01, sdncDesignerDetails);
//////////////////////////////////////////////
@@ -852,12 +726,9 @@ public class ServiceComponentInstanceCRUDTest extends ComponentInstanceBaseTest
// 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);
+ 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);
@@ -880,36 +751,27 @@ public class ServiceComponentInstanceCRUDTest extends ComponentInstanceBaseTest
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("")));
+ 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);
+ RestResponse createFirstVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01, sdncDesignerDetails);
String reqCompInstId = ResponseParser.getUniqueIdFromResponse(createFirstVFInstResp);
- RestResponse createSecondVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_02,
- sdncDesignerDetails);
+ 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);
+ 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);
+ 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);
+ CapReqDef capReqDefAfterAssociate = ComponentRestUtils.getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01);
+ List<CapabilityDefinition> capListAfterAssociate = capReqDefAfterAssociate.getCapabilities().get(CAPABILITY_TYPE);
// for (CapabilityDefinition capabilityDefinition :
// capListBeforeAssociate) {
@@ -932,34 +794,24 @@ public class ServiceComponentInstanceCRUDTest extends ComponentInstanceBaseTest
@Test
public void associateInstancesInCheckedinServiceTest() throws Exception {
- RestResponse createFirstVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01,
- sdncDesignerDetails);
+ RestResponse createFirstVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01, sdncDesignerDetails);
String reqCompInstId = ResponseParser.getUniqueIdFromResponse(createFirstVFInstResp);
- RestResponse createSecondVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_02,
- sdncDesignerDetails);
+ 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);
+ 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);
+ 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>());
+ 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);
+ 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);
@@ -970,43 +822,29 @@ public class ServiceComponentInstanceCRUDTest extends ComponentInstanceBaseTest
@Test
public void associateAfterCheckoutAllInstancesTest() throws Exception {
String firstVFUniqueId = resourceDetailsVF_01.getUniqueId();
- RestResponse createFirstVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01,
- sdncDesignerDetails);
+ 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);
+ 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);
+ 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,
@@ -1026,57 +864,39 @@ public class ServiceComponentInstanceCRUDTest extends ComponentInstanceBaseTest
@Test
public void associateInstancesByDifferentUsersTest() throws Exception {
- RestResponse createFirstVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01,
- sdncDesignerDetails);
+ RestResponse createFirstVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01, sdncDesignerDetails);
String reqCompInstId = ResponseParser.getUniqueIdFromResponse(createFirstVFInstResp);
- RestResponse createSecondVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_02,
- sdncDesignerDetails);
+ 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);
+ 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);
+ 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);
+ 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);
}
@@ -1084,47 +904,36 @@ public class ServiceComponentInstanceCRUDTest extends ComponentInstanceBaseTest
public void associateWithMissingServiceUidTest() throws Exception {
RequirementCapabilityRelDef requirementDef = new RequirementCapabilityRelDef();
serviceDetails_01.setUniqueId("");
- RestResponse associateInstancesResp = ComponentInstanceRestUtils.associateInstances(requirementDef,
- sdncDesignerDetails, serviceDetails_01.getUniqueId(), ComponentTypeEnum.SERVICE);
+ 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);
+ 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);
+ 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);
+ 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);
+ 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);
+ 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);
+ 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,
@@ -1140,22 +949,16 @@ public class ServiceComponentInstanceCRUDTest extends ComponentInstanceBaseTest
@Test
public void associateInstancesInTwoServiceVersionsTest() throws Exception {
String oldServiceUniqueId = serviceDetails_01.getUniqueId();
- RestResponse createFirstVFInstResp = createVFInstance(serviceDetails_01, resourceDetailsVF_01,
- sdncDesignerDetails);
+ RestResponse createFirstVFInstResp = createVFInstance(serviceDetails_01, resourceDetailsVF_01, sdncDesignerDetails);
String reqCompInstId = ResponseParser.getUniqueIdFromResponse(createFirstVFInstResp);
- RestResponse createSecondVFInstResp = createVFInstance(serviceDetails_01, resourceDetailsVF_02,
- sdncDesignerDetails);
+ 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);
+ 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);
+ RequirementCapabilityRelDef requirementDef = getReqCapRelation(reqCompInstId, capCompInstId, CAPABILITY_TYPE, REQUIREMENT_NAME, capListBeforeAssociate, reqListBeforeAssociate);
associateComponentInstancesForService(requirementDef, serviceDetails_01, sdncDesignerDetails);
getComponentAndValidateRIs(serviceDetails_01, 2, 1);
@@ -1168,40 +971,29 @@ public class ServiceComponentInstanceCRUDTest extends ComponentInstanceBaseTest
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);
+ 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);
+ 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);
+ 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);
+ 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);
+ 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",
@@ -1225,27 +1017,21 @@ public class ServiceComponentInstanceCRUDTest extends ComponentInstanceBaseTest
createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_02, sdncDesignerDetails);
String capCompInstId = "4567";
- CapReqDef capReqDef = ComponentRestUtils.getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails,
- serviceDetails_01);
+ 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);
+ 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);
+ 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);
+ 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);
@@ -1258,26 +1044,19 @@ public class ServiceComponentInstanceCRUDTest extends ComponentInstanceBaseTest
@Test
public void dissociateRelationInServiceNotFoundTest() throws Exception {
String uniqueId = "1234";
- RestResponse createFirstVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01,
- sdncDesignerDetails);
+ RestResponse createFirstVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01, sdncDesignerDetails);
String reqCompInstId = ResponseParser.getUniqueIdFromResponse(createFirstVFInstResp);
- RestResponse createSecondVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_02,
- sdncDesignerDetails);
+ 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);
+ 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);
+ 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("")));
+ dissoicateInstancesFail(requirementDef, sdncDesignerDetails, ActionStatus.SERVICE_NOT_FOUND, 404, new ArrayList<String>(Arrays.asList("")));
}
@@ -1285,35 +1064,26 @@ public class ServiceComponentInstanceCRUDTest extends ComponentInstanceBaseTest
public void dissoicateRelationWhileInstanceNotFound() throws Exception {
String capUniqueId = "1234";
- RestResponse createFirstVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01,
- sdncDesignerDetails);
+ 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);
+ 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);
+ 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);
+ 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);
@@ -1324,45 +1094,36 @@ public class ServiceComponentInstanceCRUDTest extends ComponentInstanceBaseTest
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>());
+ 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>());
+ 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);
+ 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);
+ RestResponse createFirstVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01, sdncDesignerDetails);
String reqCompInstId = ResponseParser.getUniqueIdFromResponse(createFirstVFInstResp);
- RestResponse createSecondVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_02,
- sdncDesignerDetails);
+ 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);
+ 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);
+ RequirementCapabilityRelDef requirementDef = getReqCapRelation(reqCompInstId, capCompInstId, CAPABILITY_TYPE, REQUIREMENT_NAME, capListBeforeAssociate, reqListBeforeAssociate);
associateComponentInstancesForService(requirementDef, serviceDetails_01, sdncDesignerDetails);
getComponentAndValidateRIs(serviceDetails_01, 2, 1);
@@ -1375,22 +1136,16 @@ public class ServiceComponentInstanceCRUDTest extends ComponentInstanceBaseTest
@Test
public void relationNotFoundInSecondVersionAfterDissociateTest() throws Exception {
String oldContainerUniqueIdToReplace = serviceDetails_01.getUniqueId();
- RestResponse createFirstVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01,
- sdncDesignerDetails);
+ RestResponse createFirstVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01, sdncDesignerDetails);
String reqCompInstId = ResponseParser.getUniqueIdFromResponse(createFirstVFInstResp);
- RestResponse createSecondVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_02,
- sdncDesignerDetails);
+ 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);
+ 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);
+ RequirementCapabilityRelDef requirementDef = getReqCapRelation(reqCompInstId, capCompInstId, CAPABILITY_TYPE, REQUIREMENT_NAME, capListBeforeAssociate, reqListBeforeAssociate);
associateComponentInstancesForService(requirementDef, serviceDetails_01, sdncDesignerDetails);
dissociateComponentInstancesForService(requirementDef, serviceDetails_01, sdncDesignerDetails);
@@ -1404,26 +1159,18 @@ public class ServiceComponentInstanceCRUDTest extends ComponentInstanceBaseTest
@Test
public void dissociateOnceAgainTest() throws Exception {
- RestResponse createFirstVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01,
- sdncDesignerDetails);
+ 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 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();
+ 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);
+ 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);
+ RequirementCapabilityRelDef requirementDef = getReqCapRelation(reqCompInstId, capCompInstId, CAPABILITY_TYPE, REQUIREMENT_NAME, capListBeforeAssociate, reqListBeforeAssociate);
associateComponentInstancesForService(requirementDef, serviceDetails_01, sdncDesignerDetails);
dissociateComponentInstancesForService(requirementDef, serviceDetails_01, sdncDesignerDetails);
@@ -1433,35 +1180,26 @@ public class ServiceComponentInstanceCRUDTest extends ComponentInstanceBaseTest
variables.add(capCompInstName);
variables.add(REQUIREMENT_NAME);
- dissoicateInstancesFail(requirementDef, sdncDesignerDetails, ActionStatus.RESOURCE_INSTANCE_RELATION_NOT_FOUND,
- 404, variables);
+ 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);
+ RestResponse createFirstVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01, sdncDesignerDetails);
String reqCompInstId = ResponseParser.getUniqueIdFromResponse(createFirstVFInstResp);
- RestResponse createSecondVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_02,
- sdncDesignerDetails);
+ RestResponse createSecondVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_02, sdncDesignerDetails);
String capCompInstId = ResponseParser.getUniqueIdFromResponse(createSecondVFInstResp);
- RestResponse createThirdVFInstResp = createVFInstance(serviceDetails_01, resourceDetailsVF_01,
- sdncDesignerDetails);
+ 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);
+ 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);
+ 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);
@@ -1476,10 +1214,8 @@ public class ServiceComponentInstanceCRUDTest extends ComponentInstanceBaseTest
// sdncDesignerDetails, actionStatus, errorCode, variables);
getComponentAndValidateRIs(serviceDetails_01, 3, 2);
- requirementDefFirstRelation
- .setFromNode(reqCompInstId.replaceAll(oldContainerUniqueIdToReplace, newContainerUniqueId));
- requirementDefFirstRelation
- .setToNode(reqCompInstId.replaceAll(oldContainerUniqueIdToReplace, newContainerUniqueId));
+ requirementDefFirstRelation.setFromNode(reqCompInstId.replaceAll(oldContainerUniqueIdToReplace, newContainerUniqueId));
+ requirementDefFirstRelation.setToNode(reqCompInstId.replaceAll(oldContainerUniqueIdToReplace, newContainerUniqueId));
dissociateComponentInstancesForService(requirementDefFirstRelation, serviceDetails_01, sdncDesignerDetails);
@@ -1504,10 +1240,8 @@ public class ServiceComponentInstanceCRUDTest extends ComponentInstanceBaseTest
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);
+ 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);
@@ -1525,19 +1259,16 @@ public class ServiceComponentInstanceCRUDTest extends ComponentInstanceBaseTest
String capType = CAPABILITY_TYPE;
String reqName = REQUIREMENT_NAME;
- RestResponse getResourceResponse = ComponentRestUtils.getComponentRequirmentsCapabilities(sdncDesignerDetails,
- serviceDetails_01);
+ 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);
+ RequirementCapabilityRelDef requirementDef = getReqCapRelation(reqCompInstId, capCompInstId, capType, reqName, capList, reqList);
associateComponentInstancesForService(requirementDef, serviceDetails_01, sdncDesignerDetails);
- getResourceResponse = ComponentRestUtils.getComponentRequirmentsCapabilities(sdncDesignerDetails,
- serviceDetails_01);
+ 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);
@@ -1556,49 +1287,38 @@ public class ServiceComponentInstanceCRUDTest extends ComponentInstanceBaseTest
RestResponse response = LifecycleRestUtils.certifyResource(resourceDetailsCP_01);
ResourceRestUtils.checkSuccess(response);
- ArtifactReqDetails heatArtifactDetails = ElementFactory
- .getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType());
- response = ArtifactRestUtils.addInformationalArtifactToResource(heatArtifactDetails, sdncDesignerDetails,
- resourceDetailsVF_02.getUniqueId());
+ 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);
+ RestResponse createAtomicResourceInstance = createVFInstance(serviceDetails_01, resourceDetailsVF_02, sdncDesignerDetails);
ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance);
String vfCompInstId = ResponseParser.getUniqueIdFromResponse(createAtomicResourceInstance);
- createAtomicResourceInstance = createAtomicInstanceForService(serviceDetails_01, resourceDetailsCP_01,
- sdncDesignerDetails);
+ 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);
+ 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);
+ fulfillCpRequirement(serviceDetails_01, cpCompInstId, vfCompInstId, capOwnerId, sdncDesignerDetails, ComponentTypeEnum.SERVICE);
- submitForTesting = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
- LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ 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);
+ 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);
+ RestResponse getInstancesResponce = ComponentInstanceRestUtils.getComponentInstances(ComponentTypeEnum.SERVICE, serviceDetails_01.getUniqueId(), sdncDesignerDetails);
for (int i = 0; i < 1500; i++) {
createVFInstResp = createVFInstance(serviceDetails_01, resourceDetailsVF_01, sdncDesignerDetails);
@@ -1606,8 +1326,7 @@ public class ServiceComponentInstanceCRUDTest extends ComponentInstanceBaseTest
System.out.println("instance " + i + "successfuly created");
}
- getInstancesResponce = ComponentInstanceRestUtils.getComponentInstances(ComponentTypeEnum.SERVICE,
- serviceDetails_01.getUniqueId(), sdncDesignerDetails);
+ getInstancesResponce = ComponentInstanceRestUtils.getComponentInstances(ComponentTypeEnum.SERVICE, serviceDetails_01.getUniqueId(), sdncDesignerDetails);
BaseValidationUtils.checkSuccess(getInstancesResponce);
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
index 2f5b47452e..1865dc3292 100644
--- 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
@@ -45,6 +45,7 @@ import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum;
import org.openecomp.sdc.ci.tests.datatypes.enums.ServiceCategoriesEnum;
import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
@@ -93,12 +94,16 @@ public class UpdateServiceMetadataTest extends ComponentBaseTest {
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);
+ 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);
+ AtomicOperationUtils.changeComponentState(resourceDetailsVFCcomp, UserRoleEnum.DESIGNER,
+ LifeCycleStatesEnum.CERTIFY, true);
Service serviceServ = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value();
- AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceDetailsVFCcomp, serviceServ, UserRoleEnum.DESIGNER, true);
+ AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceDetailsVFCcomp, serviceServ,
+ UserRoleEnum.DESIGNER, true);
serviceDetails = new ServiceReqDetails(serviceServ);
updatedServiceDetails = updatedServiceDetails(serviceDetails);
@@ -131,36 +136,49 @@ public class UpdateServiceMetadataTest extends ComponentBaseTest {
// createServiceResponse);
}
- protected void getServiceAndValidate(ServiceReqDetails excpectedService, User creator, User updater, LifecycleStateEnum lifeCycleState) throws Exception {
- RestResponse getServiceResponse = ServiceRestUtils.getService(excpectedService.getUniqueId(), sdncDesignerDetails);
+ 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());
+ 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);
+ ServiceValidationUtils.validateServiceResponseMetaData(excpectedService, actualService, creator, updater,
+ lifeCycleState);
}
- public void getServiceAndValidate(ServiceReqDetails excpectedService, LifecycleStateEnum lifecycleState) throws Exception {
+ 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 {
+ 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());
+ 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());
+ ErrorValidationUtils.checkBodyResponseOnError(actionResponse.name(), listOfVariables,
+ response.getResponse());
return;
}
Service actualService = ResponseParser.convertServiceResponseToJavaObject(response.getResponse());
- ServiceValidationUtils.validateServiceResponseMetaData(updatedServiceDetails, actualService, sdncDesignerDetails, sdncDesignerDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ 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);
+ Service actualService = ResponseParser
+ .convertServiceResponseToJavaObject(actualServiceFromResponse.getResponse());
+ ServiceValidationUtils.validateServiceResponseMetaData(updatedServiceDetails, actualService,
+ sdncDesignerDetails, sdncDesignerDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
}
protected String multipleString(String ch, int repeat) {
@@ -184,24 +202,30 @@ public class UpdateServiceMetadataTest extends ComponentBaseTest {
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")));
+ 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")));
+ 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())));
+ 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")));
+ updatedServiceDetails.addCategoryChain(multipleString("1", 5) + String.valueOf(ch),
+ multipleString("1", 5) + String.valueOf(ch));
+ updateWithInvalidValue(ActionStatus.COMPONENT_INVALID_CATEGORY,
+ new ArrayList<>(Arrays.asList("Service")));
}
}
@@ -236,7 +260,8 @@ public class UpdateServiceMetadataTest extends ComponentBaseTest {
}
- protected void checkErrorResponse(ActionStatus actionStatus, ArrayList<String> arrList, RestResponse response) throws Exception, JSONException {
+ protected void checkErrorResponse(ActionStatus actionStatus, ArrayList<String> arrList, RestResponse response)
+ throws Exception, JSONException {
ErrorValidationUtils.checkBodyResponseOnError(actionStatus.name(), arrList, response.getResponse());
}
@@ -246,9 +271,94 @@ public class UpdateServiceMetadataTest extends ComponentBaseTest {
}
+ // @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);
+ RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails,
+ sdncDesignerDetails2);
validateResponse(updateServiceResponse, 409, ActionStatus.RESTRICTED_OPERATION, listForMessage);
getServiceAndValidate(serviceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
@@ -266,12 +376,14 @@ public class UpdateServiceMetadataTest extends ComponentBaseTest {
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("")));
+ 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);
+ 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);
@@ -328,7 +440,8 @@ public class UpdateServiceMetadataTest extends ComponentBaseTest {
@Test
public void updateServiceByMethod_delete() throws Exception {
- RestResponse updateServiceResponse = ServiceRestUtils.createServiceByHttpMethod(updatedServiceDetails, sdncDesignerDetails, "DELETE", Urls.UPDATE_SERVICE_METADATA);
+ RestResponse updateServiceResponse = ServiceRestUtils.createServiceByHttpMethod(updatedServiceDetails,
+ sdncDesignerDetails, "DELETE", Urls.UPDATE_SERVICE_METADATA);
validateResponse(updateServiceResponse, 405, ActionStatus.NOT_ALLOWED, listForMessage);
getServiceAndValidate(serviceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
@@ -336,7 +449,8 @@ public class UpdateServiceMetadataTest extends ComponentBaseTest {
@Test
public void updateServiceByMethod_get() throws Exception {
- RestResponse updateServiceResponse = ServiceRestUtils.createServiceByHttpMethod(updatedServiceDetails, sdncDesignerDetails, "GET", Urls.UPDATE_SERVICE_METADATA);
+ RestResponse updateServiceResponse = ServiceRestUtils.createServiceByHttpMethod(updatedServiceDetails,
+ sdncDesignerDetails, "GET", Urls.UPDATE_SERVICE_METADATA);
validateResponse(updateServiceResponse, 405, ActionStatus.NOT_ALLOWED, listForMessage);
getServiceAndValidate(serviceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
@@ -344,7 +458,8 @@ public class UpdateServiceMetadataTest extends ComponentBaseTest {
@Test
public void updateServiceByMethod_post() throws Exception {
- RestResponse updateServiceResponse = ServiceRestUtils.createServiceByHttpMethod(updatedServiceDetails, sdncDesignerDetails, "POST", Urls.UPDATE_SERVICE_METADATA);
+ RestResponse updateServiceResponse = ServiceRestUtils.createServiceByHttpMethod(updatedServiceDetails,
+ sdncDesignerDetails, "POST", Urls.UPDATE_SERVICE_METADATA);
validateResponse(updateServiceResponse, 405, ActionStatus.NOT_ALLOWED, listForMessage);
getServiceAndValidate(serviceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
@@ -359,7 +474,8 @@ public class UpdateServiceMetadataTest extends ComponentBaseTest {
{
// addMandatoryArtifactsToService();
certifyService(serviceDetails, serviceDetails.getVersion());
- LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(), LifeCycleStatesEnum.CHECKOUT);
+ LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(),
+ LifeCycleStatesEnum.CHECKOUT);
RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
validateResponse(updateServiceResponse, 400, ActionStatus.SERVICE_CATEGORY_CANNOT_BE_CHANGED, listForMessage);
@@ -419,6 +535,7 @@ public class UpdateServiceMetadataTest extends ComponentBaseTest {
// 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);
@@ -445,7 +562,8 @@ public class UpdateServiceMetadataTest extends ComponentBaseTest {
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"));
+ validateResponse(updateServiceResponse, 400, ActionStatus.COMPONENT_MISSING_DESCRIPTION,
+ Arrays.asList("Service"));
getServiceAndValidate(serviceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
}
@@ -453,7 +571,8 @@ public class UpdateServiceMetadataTest extends ComponentBaseTest {
public void missingDescriptionTest2() throws Exception {
updatedServiceDetails.setDescription(null);
RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
- validateResponse(updateServiceResponse, 400, ActionStatus.COMPONENT_MISSING_DESCRIPTION, Arrays.asList("Service"));
+ validateResponse(updateServiceResponse, 400, ActionStatus.COMPONENT_MISSING_DESCRIPTION,
+ Arrays.asList("Service"));
getServiceAndValidate(serviceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
}
@@ -477,15 +596,18 @@ public class UpdateServiceMetadataTest extends ComponentBaseTest {
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"));
+ 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())));
+ 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"));
+ validateResponse(updateServiceResponse, 400, ActionStatus.INVALID_FIELD_FORMAT,
+ Arrays.asList("Service", "tag"));
getServiceAndValidate(serviceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
}
@@ -535,7 +657,8 @@ public class UpdateServiceMetadataTest extends ComponentBaseTest {
// values------------------------------------------
@Test
public void contactIdValidationTest7() throws Exception {
- LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(), LifeCycleStatesEnum.CHECKIN);
+ LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(),
+ LifeCycleStatesEnum.CHECKIN);
updatedServiceDetails.setContactId("ab0001");
RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
checkErrorResponse(ActionStatus.RESTRICTED_OPERATION, listForMessage, updateServiceResponse);
@@ -546,7 +669,8 @@ public class UpdateServiceMetadataTest extends ComponentBaseTest {
// addMandatoryArtifactsToService();
RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails);
- Service certifyServiceServ = ResponseParser.convertServiceResponseToJavaObject(certifyServiceResp.getResponse());
+ Service certifyServiceServ = ResponseParser
+ .convertServiceResponseToJavaObject(certifyServiceResp.getResponse());
ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ);
updatedServiceDetails = new ServiceReqDetails(certifyService);
updatedServiceDetails.setContactId("ab0001");
@@ -660,7 +784,8 @@ public class UpdateServiceMetadataTest extends ComponentBaseTest {
public void contactIdValidationTest26() throws Exception {
// addMandatoryArtifactsToService();
certifyService(serviceDetails, serviceDetails.getVersion());
- LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(), LifeCycleStatesEnum.CHECKOUT);
+ LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(),
+ LifeCycleStatesEnum.CHECKOUT);
updatedServiceDetails = new ServiceReqDetails(serviceDetails);
updatedServiceDetails.setContactId("xy0002");
correctUpdate();
@@ -669,77 +794,88 @@ public class UpdateServiceMetadataTest extends ComponentBaseTest {
@Test
public void serviceNameValidationTest1() throws Exception {
updatedServiceDetails.setName(multipleString("a", 49));
- updatedServiceDetails.setTags(addServiceNameToTagsList(updatedServiceDetails.getName(), updatedServiceDetails.getTags()));
+ 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()));
+ updatedServiceDetails
+ .setTags(addServiceNameToTagsList(updatedServiceDetails.getName(), updatedServiceDetails.getTags()));
correctUpdate();
}
@Test
public void serviceNameValidationTest3() throws Exception {
updatedServiceDetails.setName("testNamE");
- updatedServiceDetails.setTags(addServiceNameToTagsList(updatedServiceDetails.getName(), updatedServiceDetails.getTags()));
+ updatedServiceDetails
+ .setTags(addServiceNameToTagsList(updatedServiceDetails.getName(), updatedServiceDetails.getTags()));
correctUpdate();
}
@Test
public void serviceNameValidationTest4() throws Exception {
updatedServiceDetails.setName("Testname");
- updatedServiceDetails.setTags(addServiceNameToTagsList(updatedServiceDetails.getName(), updatedServiceDetails.getTags()));
+ 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()));
+ 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()));
+ 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()));
+ 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()));
+ updatedServiceDetails
+ .setTags(addServiceNameToTagsList(updatedServiceDetails.getName(), updatedServiceDetails.getTags()));
correctUpdate();
}
@Test
public void serviceNameValidationTest9() throws Exception {
updatedServiceDetails.setName("...1...");
- updatedServiceDetails.setTags(addServiceNameToTagsList(updatedServiceDetails.getName(), updatedServiceDetails.getTags()));
+ 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()));
+ updatedServiceDetails
+ .setTags(addServiceNameToTagsList(updatedServiceDetails.getName(), updatedServiceDetails.getTags()));
correctUpdate();
}
@Test
public void serviceNameValidationTest11() throws Exception {
updatedServiceDetails.setName("Testname1234567890");
- updatedServiceDetails.setTags(addServiceNameToTagsList(updatedServiceDetails.getName(), updatedServiceDetails.getTags()));
+ updatedServiceDetails
+ .setTags(addServiceNameToTagsList(updatedServiceDetails.getName(), updatedServiceDetails.getTags()));
correctUpdate();
}
@@ -747,20 +883,24 @@ public class UpdateServiceMetadataTest extends ComponentBaseTest {
public void serviceNameValidationTest14() throws Exception {
updatedServiceDetails.setName(StringUtils.SPACE); // one space with
// nothing
- updatedServiceDetails.setTags(addServiceNameToTagsList(updatedServiceDetails.getName(), updatedServiceDetails.getTags()));
+ 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")));
+ 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);
+ LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(),
+ LifeCycleStatesEnum.CHECKIN);
updatedServiceDetails.setName("TestNamE");
- updatedServiceDetails.setTags(addServiceNameToTagsList(updatedServiceDetails.getName(), updatedServiceDetails.getTags()));
+ 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);
@@ -769,8 +909,10 @@ public class UpdateServiceMetadataTest extends ComponentBaseTest {
@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")));
+ updatedServiceDetails
+ .setTags(addServiceNameToTagsList(updatedServiceDetails.getName(), updatedServiceDetails.getTags()));
+ updateWithInvalidValue(ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT,
+ new ArrayList<>(Arrays.asList("Service", "50")));
}
@Test
@@ -784,7 +926,8 @@ public class UpdateServiceMetadataTest extends ComponentBaseTest {
LifecycleRestUtils.certifyService(serviceDetails);
updatedServiceDetails.setName("testnamename");
updatedServiceDetails.setCategories(serviceDetails.getCategories());
- updatedServiceDetails.setTags(addServiceNameToTagsList(updatedServiceDetails.getName(), updatedServiceDetails.getTags()));
+ 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);
@@ -794,11 +937,14 @@ public class UpdateServiceMetadataTest extends ComponentBaseTest {
public void serviceNameValidationTest17() throws Exception {
// addMandatoryArtifactsToService();
certifyService(serviceDetails, serviceDetails.getVersion());
- LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(), LifeCycleStatesEnum.CHECKOUT);
+ 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);
+ 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);
}
@@ -806,8 +952,10 @@ public class UpdateServiceMetadataTest extends ComponentBaseTest {
@Test
public void serviceNameValidationTest18() throws Exception {
updatedServiceDetails.setName(" testname ");
- updatedServiceDetails.setTags(addServiceNameToTagsList(updatedServiceDetails.getName(), updatedServiceDetails.getTags()));
- RestResponse updateServiceResponse1 = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
+ updatedServiceDetails
+ .setTags(addServiceNameToTagsList(updatedServiceDetails.getName(), updatedServiceDetails.getTags()));
+ RestResponse updateServiceResponse1 = ServiceRestUtils.updateService(updatedServiceDetails,
+ sdncDesignerDetails);
assertNotNull(updateServiceResponse1);
assertNotNull(updateServiceResponse1.getErrorCode());
assertEquals(200, updateServiceResponse1.getErrorCode().intValue());
@@ -860,7 +1008,8 @@ public class UpdateServiceMetadataTest extends ComponentBaseTest {
@Test
public void iconValidationTest8() throws Exception {
- LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(), LifeCycleStatesEnum.CHECKIN);
+ LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(),
+ LifeCycleStatesEnum.CHECKIN);
updatedServiceDetails.setIcon("TestNamE");
RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
checkErrorResponse(ActionStatus.RESTRICTED_OPERATION, listForMessage, updateServiceResponse);
@@ -905,14 +1054,16 @@ public class UpdateServiceMetadataTest extends ComponentBaseTest {
@Test
public void iconValidationTest14() throws Exception {
updatedServiceDetails.setIcon(multipleString("c", 26));
- updateWithInvalidValue(ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT, new ArrayList<>(Arrays.asList("Service", "25")));
+ 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());
+ Service certifyServiceServ = ResponseParser
+ .convertServiceResponseToJavaObject(certifyServiceResp.getResponse());
ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ);
updatedServiceDetails = new ServiceReqDetails(certifyService);
updatedServiceDetails.setIcon("testnamename");
@@ -924,7 +1075,8 @@ public class UpdateServiceMetadataTest extends ComponentBaseTest {
public void iconValidationTest16() throws Exception {
// addMandatoryArtifactsToService();
certifyService(serviceDetails, serviceDetails.getVersion());
- LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(), LifeCycleStatesEnum.CHECKOUT);
+ LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(),
+ LifeCycleStatesEnum.CHECKOUT);
updatedServiceDetails = new ServiceReqDetails(serviceDetails);
updatedServiceDetails.setIcon("TestNamE");
RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
@@ -939,7 +1091,8 @@ public class UpdateServiceMetadataTest extends ComponentBaseTest {
@Test
public void categoryValidationTest1() throws Exception {
- LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(), LifeCycleStatesEnum.CHECKIN);
+ 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);
@@ -981,7 +1134,8 @@ public class UpdateServiceMetadataTest extends ComponentBaseTest {
public void categoryValidationTest6() throws Exception {
// addMandatoryArtifactsToService();
certifyService(serviceDetails, serviceDetails.getVersion());
- LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(), LifeCycleStatesEnum.CHECKOUT);
+ LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(),
+ LifeCycleStatesEnum.CHECKOUT);
updatedServiceDetails = new ServiceReqDetails(serviceDetails);
updatedServiceDetails = serviceDetails;
List<CategoryDefinition> categories = updatedServiceDetails.getCategories();
@@ -990,7 +1144,8 @@ public class UpdateServiceMetadataTest extends ComponentBaseTest {
categoryDefinition2.setName("ccc");
categories.set(0, categoryDefinition2);
updatedServiceDetails.setCategories(categories);
- RestResponse updateServiceResponse2 = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
+ RestResponse updateServiceResponse2 = ServiceRestUtils.updateService(updatedServiceDetails,
+ sdncDesignerDetails);
validateResponse(updateServiceResponse2, 400, ActionStatus.SERVICE_CATEGORY_CANNOT_BE_CHANGED, listForMessage);
getServiceAndValidate(serviceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
}
@@ -1011,19 +1166,22 @@ public class UpdateServiceMetadataTest extends ComponentBaseTest {
@Test
public void tagsValidationTest1() throws Exception {
- updatedServiceDetails.setTags(new ArrayList<>(Arrays.asList(multipleString("a", 49), updatedServiceDetails.getName())));
+ 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())));
+ 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())));
+ updatedServiceDetails.setTags(new ArrayList<>(
+ Arrays.asList(multipleString("A", 50), multipleString("B", 50), updatedServiceDetails.getName())));
correctUpdate();
}
@@ -1077,7 +1235,8 @@ public class UpdateServiceMetadataTest extends ComponentBaseTest {
@Test
public void tagsValidationTest13() throws Exception {
- updatedServiceDetails.setTags(new ArrayList<>(Arrays.asList("Testtag1234567890", updatedServiceDetails.getName())));
+ updatedServiceDetails
+ .setTags(new ArrayList<>(Arrays.asList("Testtag1234567890", updatedServiceDetails.getName())));
correctUpdate();
}
@@ -1089,7 +1248,8 @@ public class UpdateServiceMetadataTest extends ComponentBaseTest {
@Test
public void tagsValidationTest15() throws Exception {
- LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(), LifeCycleStatesEnum.CHECKIN);
+ 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);
@@ -1109,7 +1269,8 @@ public class UpdateServiceMetadataTest extends ComponentBaseTest {
public void tagsValidationTest17() throws Exception {
// addMandatoryArtifactsToService();
certifyService(serviceDetails, serviceDetails.getVersion());
- LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(), LifeCycleStatesEnum.CHECKOUT);
+ LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(),
+ LifeCycleStatesEnum.CHECKOUT);
updatedServiceDetails = new ServiceReqDetails(serviceDetails);
updatedServiceDetails.setTags(new ArrayList<>(Arrays.asList("TestTaG", updatedServiceDetails.getName())));
correctUpdate();
@@ -1124,7 +1285,8 @@ public class UpdateServiceMetadataTest extends ComponentBaseTest {
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) */;
+ tagsCount -= maxLengthTag + 1
+ + 1/* (50 and comma of each tag + one space, totally 52) */;
}
tagsList.add(multipleString("a", tagsCount));
updatedServiceDetails.setTags(tagsList);
@@ -1134,7 +1296,8 @@ public class UpdateServiceMetadataTest extends ComponentBaseTest {
@Test
public void tagsValidationTest19() throws Exception {
updatedServiceDetails.setTags(new ArrayList<>(Arrays.asList(" Tag ", updatedServiceDetails.getName())));
- RestResponse updateServiceResponse1 = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
+ RestResponse updateServiceResponse1 = ServiceRestUtils.updateService(updatedServiceDetails,
+ sdncDesignerDetails);
assertNotNull(updateServiceResponse1);
assertNotNull(updateServiceResponse1.getErrorCode());
assertEquals(200, updateServiceResponse1.getErrorCode().intValue());
@@ -1201,7 +1364,8 @@ public class UpdateServiceMetadataTest extends ComponentBaseTest {
@Test
public void descriptionValidationTest6() throws Exception {
updatedServiceDetails.setDescription("desc\tription");
- RestResponse updateServiceResponse1 = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
+ RestResponse updateServiceResponse1 = ServiceRestUtils.updateService(updatedServiceDetails,
+ sdncDesignerDetails);
assertNotNull(updateServiceResponse1);
assertNotNull(updateServiceResponse1.getErrorCode());
assertEquals(200, updateServiceResponse1.getErrorCode().intValue());
@@ -1213,7 +1377,8 @@ public class UpdateServiceMetadataTest extends ComponentBaseTest {
@Test
public void descriptionValidationTest7() throws Exception {
updatedServiceDetails.setDescription("desc ription ");
- RestResponse updateServiceResponse2 = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
+ RestResponse updateServiceResponse2 = ServiceRestUtils.updateService(updatedServiceDetails,
+ sdncDesignerDetails);
assertNotNull(updateServiceResponse2);
assertNotNull(updateServiceResponse2.getErrorCode());
assertEquals(200, updateServiceResponse2.getErrorCode().intValue());
@@ -1225,7 +1390,8 @@ public class UpdateServiceMetadataTest extends ComponentBaseTest {
@Test
public void descriptionValidationTest8() throws Exception {
updatedServiceDetails.setDescription("desc" + StringUtils.LF + "ription");
- RestResponse updateServiceResponse3 = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
+ RestResponse updateServiceResponse3 = ServiceRestUtils.updateService(updatedServiceDetails,
+ sdncDesignerDetails);
assertNotNull(updateServiceResponse3);
assertNotNull(updateServiceResponse3.getErrorCode());
assertEquals(200, updateServiceResponse3.getErrorCode().intValue());
@@ -1237,7 +1403,8 @@ public class UpdateServiceMetadataTest extends ComponentBaseTest {
@Test
public void descriptionValidationTest9() throws Exception {
updatedServiceDetails.setDescription("<html>Hello, <b>world!</b></html>");
- RestResponse updateServiceResponse4 = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
+ RestResponse updateServiceResponse4 = ServiceRestUtils.updateService(updatedServiceDetails,
+ sdncDesignerDetails);
assertNotNull(updateServiceResponse4);
assertNotNull(updateServiceResponse4.getErrorCode());
assertEquals(200, updateServiceResponse4.getErrorCode().intValue());
@@ -1262,8 +1429,9 @@ public class UpdateServiceMetadataTest extends ComponentBaseTest {
@Test
public void descriptionValidationTest10_b() throws Exception {
- updatedServiceDetails.setDescription("\uC2B5");
- RestResponse updateServiceResponse5 = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
+ updatedServiceDetails.setDescription("\uC2B5abc");
+ RestResponse updateServiceResponse5 = ServiceRestUtils.updateService(updatedServiceDetails,
+ sdncDesignerDetails);
assertNotNull(updateServiceResponse5);
assertNotNull(updateServiceResponse5.getErrorCode());
assertEquals(200, updateServiceResponse5.getErrorCode().intValue());
@@ -1276,7 +1444,8 @@ public class UpdateServiceMetadataTest extends ComponentBaseTest {
@Test
public void descriptionValidationTest11() throws Exception {
updatedServiceDetails.setDescription("&<>");
- RestResponse updateServiceResponse6 = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
+ RestResponse updateServiceResponse6 = ServiceRestUtils.updateService(updatedServiceDetails,
+ sdncDesignerDetails);
assertNotNull(updateServiceResponse6);
assertNotNull(updateServiceResponse6.getErrorCode());
assertEquals(200, updateServiceResponse6.getErrorCode().intValue());
@@ -1288,7 +1457,8 @@ public class UpdateServiceMetadataTest extends ComponentBaseTest {
@Test
public void descriptionValidationTest12() throws Exception {
updatedServiceDetails.setDescription("文 test");
- RestResponse updateServiceResponse7 = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
+ RestResponse updateServiceResponse7 = ServiceRestUtils.updateService(updatedServiceDetails,
+ sdncDesignerDetails);
assertNotNull(updateServiceResponse7);
assertNotNull(updateServiceResponse7.getErrorCode());
assertEquals(200, updateServiceResponse7.getErrorCode().intValue());
@@ -1300,7 +1470,8 @@ public class UpdateServiceMetadataTest extends ComponentBaseTest {
@Test
public void descriptionValidationTest13() throws Exception {
updatedServiceDetails.setDescription(" description");
- RestResponse updateServiceResponse8 = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
+ RestResponse updateServiceResponse8 = ServiceRestUtils.updateService(updatedServiceDetails,
+ sdncDesignerDetails);
assertNotNull(updateServiceResponse8);
assertNotNull(updateServiceResponse8.getErrorCode());
assertEquals(200, updateServiceResponse8.getErrorCode().intValue());
@@ -1312,7 +1483,8 @@ public class UpdateServiceMetadataTest extends ComponentBaseTest {
@Test
public void descriptionValidationTest14() throws Exception {
updatedServiceDetails.setDescription(multipleString("a", 1025));
- updateWithInvalidValue(ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, new ArrayList<>(Arrays.asList("Service", "1024")));
+ updateWithInvalidValue(ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT,
+ new ArrayList<>(Arrays.asList("Service", "1024")));
}
@Test
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
index c83018241b..e1bc3c9dde 100644
--- 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
@@ -430,7 +430,7 @@ public class ActivateDeActivateDeleteUser extends ComponentBaseTest {
mapAllUsersOnResponse.remove(sdncAdminUser.getUserId());
logger.debug("map Of all Admin users exclude one : {}", mapAllUsersOnResponse);
- // deActivate all Admin users from the userIdAllAdminList list
+ // deActivate all Admin users from the UserIdAllAdminList list
for (Entry<String, User> entry : mapAllUsersOnResponse.entrySet()) {
UserRestUtils.deActivateUser(entry.getValue(), sdncAdminUser);
}
@@ -651,133 +651,6 @@ public class ActivateDeActivateDeleteUser extends ComponentBaseTest {
}
- // test check the service accessibility via catalog view, service was
- // created by user which was deActivated
-
- // @Test
- // public void serviceAccessibility() throws Exception{
- //
- // User sdncUserDetails = getDefaultUserDetails();
- //// fill new service details
- // ServiceReqDetails serviceDetails = ElementFactory.getDefaultService();
- // String serviceBaseVersion = "0.1";
- //
- // try{
- // //Delete service
- //// ServiceRestUtils.deleteService_allVersions(serviceDetails,
- // sdncAdminUser);
- // UserRestUtils.deleteUser(sdncUserDetails, sdncAdminUser, true);
- //
- // DbUtils.cleanAllAudits();
- // RestResponse createUserResponse =
- // UserRestUtils.createUser(sdncUserDetails, sdncAdminUser);
- // validateSuccessCreateUserResponse(sdncUserDetails, createUserResponse);
- //
- //// ------------------------Start create
- // service---------------------------------------------------------------------------------
- // 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 =
- // ServiceRestUtils.convertServiceResponseToJavaObject(restResponse.getResponse());
- // UserValidationUtils.validateServiceResponseMetaData(serviceDetails,service,sdncUserDetails,
- // (LifecycleStateEnum)null);
- //
- //// validate get service response vs actual
- // restResponse = ServiceRestUtils.getService(serviceDetails.getUniqueId(),
- // sdncUserDetails);
- // service =
- // ServiceRestUtils.convertServiceResponseToJavaObject(restResponse.getResponse());
- // UserValidationUtils.validateServiceResponseMetaData(serviceDetails,service,sdncUserDetails,
- // (LifecycleStateEnum)null);
- //
- // //validate audit
- //
- // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject =
- // ServiceRestUtils.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);
- //
- //// ------------------------End create
- // service---------------------------------------------------------------------------------
- //
- //// 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 service 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 service list
- // List<String> serviceExpectedUniqIdList= new ArrayList<String>();
- // serviceExpectedUniqIdList.add(serviceDetails.getUniqueId());
- // logger.debug("serviceExpectedUniqIdList: {}", serviceExpectedUniqIdList);
- //
- // compareServiceUniqIdList(getCatalogDataResponse.getResponse(),
- // serviceExpectedUniqIdList, true);
- //
- //
- // }finally{
- //// ServiceRestUtils.deleteService_allVersions(serviceDetails,
- // sdncAdminUser);
- // UserRestUtils.deleteUser(sdncUserDetails, sdncAdminUser, true);
- // }
- //
- // }
-
public void compareServiceUniqIdList(String response, List<String> expectedList, boolean flag) {
JsonElement jelement = new JsonParser().parse(response);
@@ -811,14 +684,14 @@ public class ActivateDeActivateDeleteUser extends ComponentBaseTest {
resourceReqDetailsListOnResponse.add(json);
}
- logger.debug("ResourceReqDetails list on response: {}", resourceReqDetailsListOnResponse);
+ 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);
+ logger.debug("resourceActualUniqIdList on response: {}",resourceActualUniqIdList);
+ logger.debug("resourceExpectedUniqIdList on response: {}",expectedList);
if (flag) {
assertTrue("actual list does not contain expected list",
@@ -829,4 +702,55 @@ public class ActivateDeActivateDeleteUser extends ComponentBaseTest {
}
}
+ // 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
index 8684910a18..2a79539443 100644
--- 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
@@ -1006,7 +1006,250 @@ public class CreateUserApiTest extends ComponentBaseTest {
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";
@@ -1184,7 +1427,6 @@ public class CreateUserApiTest extends ComponentBaseTest {
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);
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
index a7552ad3be..9a7f68264f 100644
--- 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
@@ -47,7 +47,9 @@ import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.execute.lifecycle.LCSbaseTest;
import org.openecomp.sdc.ci.tests.utils.DbUtils;
+import org.openecomp.sdc.ci.tests.utils.Utils;
import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils;
import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
import org.openecomp.sdc.ci.tests.utils.rest.ArtifactRestUtils;
@@ -125,47 +127,10 @@ public class GovernorWorkspaceApiTest extends ComponentBaseTest {
tags = serviceDetails33.getTags();
tags.add(serviceDetails33.getName());
serviceDetails33.setTags(tags);
- //
- // serviceUtils.deleteService_allVersions(serviceDetails11, designer1);
- // serviceUtils.deleteService_allVersions(serviceDetails22, designer1);
- // serviceUtils.deleteService_allVersions(serviceDetails33, designer1);
-
+
RestResponse createServiceResponse1 = createService(user, serviceDetails11);
RestResponse createServiceResponse2 = createService(user, serviceDetails22);
RestResponse createServiceResponse3 = createService(user, serviceDetails33);
-
- // addResourceWithHeatArt();
- //
- // serviceUtils.addServiceMandatoryArtifacts(user,
- // createServiceResponse1);
- //
- //
- // RestResponse createServiceResponse2 =
- // serviceUtils.createServiceTowardsCatalogBe(serviceDetails22, user);
- // assertNotNull("check response object is not null after creating
- // service", createServiceResponse2);
- // assertNotNull("check if error code exists in response after creating
- // service", createServiceResponse2.getErrorCode());
- // assertEquals("Check response code after creating service", 201,
- // createServiceResponse2.getErrorCode().intValue());
- // serviceDetails22.setUniqueId(serviceUtils.getServiceUniqueId(createServiceResponse2));
- // logger.debug("Created service2 = {}", serviceDetails22);
- // serviceUtils.addServiceMandatoryArtifacts(user,
- // createServiceResponse2);
- //
- // RestResponse createServiceResponse3 =
- // serviceUtils.createServiceTowardsCatalogBe(serviceDetails33, user);
- // assertNotNull("check response object is not null after creating
- // service", createServiceResponse3);
- // assertNotNull("check if error code exists in response after creating
- // service", createServiceResponse3.getErrorCode());
- // assertEquals("Check response code after creating service", 201,
- // createServiceResponse3.getErrorCode().intValue());
- // serviceDetails33.setUniqueId(serviceUtils.getServiceUniqueId(createServiceResponse3));
- // logger.debug("Created service3 = {}", serviceDetails33);
- // serviceUtils.addServiceMandatoryArtifacts(user,
- // createServiceResponse3);
-
}
protected RestResponse createService(User user, ServiceReqDetails serviceDetails) throws Exception, IOException {
@@ -178,7 +143,7 @@ public class GovernorWorkspaceApiTest extends ComponentBaseTest {
Service convertServiceResponseToJavaObject = ResponseParser
.convertServiceResponseToJavaObject(createServiceResponse1.getResponse());
serviceDetails.setUniqueId(convertServiceResponseToJavaObject.getUniqueId());
- logger.debug("Created service1 = {}", serviceDetails);
+ logger.debug("Created service1 ={}",serviceDetails);
addResourceWithHeatArt(serviceDetails);
return createServiceResponse1;
}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/migration/v1707/CommonMigrationUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/migration/v1707/CommonMigrationUtils.java
new file mode 100644
index 0000000000..e142e4caa3
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/migration/v1707/CommonMigrationUtils.java
@@ -0,0 +1,19 @@
+package org.openecomp.sdc.ci.tests.migration.v1707;
+
+import com.thinkaurelius.titan.core.TitanGraph;
+
+import static org.testng.Assert.assertNotNull;
+import static org.testng.Assert.assertNull;
+
+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));
+ }
+
+
+}
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
new file mode 100644
index 0000000000..95fc068dd3
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/migration/v1707/postupgrade/AttKeyPropertiesRenameTest.java
@@ -0,0 +1,71 @@
+package org.openecomp.sdc.ci.tests.migration.v1707.postupgrade;
+
+import com.thinkaurelius.titan.core.TitanVertex;
+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 java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+import static org.testng.Assert.*;
+
+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
new file mode 100644
index 0000000000..3b4f6349a7
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/migration/v1707/preupgrade/AttKeyPropertiesBeforeRenameTest.java
@@ -0,0 +1,49 @@
+package org.openecomp.sdc.ci.tests.migration.v1707.preupgrade;
+
+import com.thinkaurelius.titan.core.TitanVertex;
+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 java.io.IOException;
+
+import static org.testng.Assert.assertTrue;
+
+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/rules/MyTestWatcher.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/rules/MyTestWatcher.java
index aa6131c8ff..799309e55d 100644
--- 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
@@ -22,13 +22,13 @@ package org.openecomp.sdc.ci.tests.rules;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
-import org.openecomp.sdc.ci.tests.api.SdcTest;
+import org.openecomp.sdc.ci.tests.api.AttSdcTest;
public class MyTestWatcher extends TestWatcher {
- SdcTest odlTest;
+ AttSdcTest odlTest;
- public MyTestWatcher(SdcTest odlTest) {
+ public MyTestWatcher(AttSdcTest odlTest) {
this.odlTest = odlTest;
}
@@ -65,7 +65,7 @@ public class MyTestWatcher extends TestWatcher {
protected void starting(Description description) {
// System.out.println("protected void starting(Description description)
// {");
- this.odlTest.getLogger().debug("Start running test {}", description.getMethodName());
+ this.odlTest.getLogger().debug("Start running test {}",description.getMethodName());
}
/**
@@ -77,6 +77,6 @@ public class MyTestWatcher extends TestWatcher {
protected void finished(Description description) {
// System.out.println("protected void finished(Description description)
// {");
- this.odlTest.getLogger().debug("Finish running test {}", description.getMethodName());
+ this.odlTest.getLogger().debug("Finish running test {}",description.getMethodName());
}
}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/run/ExtentReporterNG.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/run/ExtentReporterNG.java
deleted file mode 100644
index 5119263032..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/run/ExtentReporterNG.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.run;
-
-import java.io.File;
-import java.util.Calendar;
-import java.util.Date;
-import java.util.List;
-import java.util.Map;
-
-import org.testng.IReporter;
-import org.testng.IResultMap;
-import org.testng.ISuite;
-import org.testng.ISuiteResult;
-import org.testng.ITestContext;
-import org.testng.ITestResult;
-import org.testng.xml.XmlSuite;
-
-import com.relevantcodes.extentreports.ExtentReports;
-import com.relevantcodes.extentreports.ExtentTest;
-import com.relevantcodes.extentreports.LogStatus;
-
-public class ExtentReporterNG implements IReporter {
- private ExtentReports extent;
-
- @Override
- public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String outputDirectory) {
- extent = new ExtentReports(outputDirectory + File.separator + "ExtentReportsTestNG.html", true);
-
- for (ISuite suite : suites) {
- Map<String, ISuiteResult> result = suite.getResults();
-
- for (ISuiteResult r : result.values()) {
- ITestContext context = r.getTestContext();
-
- buildTestNodes(context.getPassedTests(), LogStatus.PASS);
- buildTestNodes(context.getFailedTests(), LogStatus.FAIL);
- buildTestNodes(context.getSkippedTests(), LogStatus.SKIP);
- }
- }
-
- extent.flush();
- extent.close();
- }
-
- private void buildTestNodes(IResultMap tests, LogStatus status) {
- ExtentTest test;
-
- if (tests.size() > 0) {
- for (ITestResult result : tests.getAllResults()) {
- test = extent.startTest(result.getMethod().getMethodName());
-
- test.getTest().setStartedTime(getTime(result.getStartMillis()));
- test.getTest().setEndedTime(getTime(result.getEndMillis()));
-
- for (String group : result.getMethod().getGroups())
- test.assignCategory(group);
-
- String message = "Test " + status.toString().toLowerCase() + "ed";
-
- if (result.getThrowable() != null)
- message = result.getThrowable().getMessage();
-
- test.log(status, message);
-
- extent.endTest(test);
- }
- }
- }
-
- private Date getTime(long millis) {
- Calendar calendar = Calendar.getInstance();
- calendar.setTimeInMillis(millis);
- return calendar.getTime();
- }
-}
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
index 3f895a3780..338adfd094 100644
--- 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
@@ -42,6 +42,8 @@ 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;
@@ -73,50 +75,14 @@ public class StartTest {
System.exit(1);
}
- // need to update
- // List<String> packagesToRun = config.getPackages();
- // if (packagesToRun == null || true == packagesToRun.isEmpty()) {
- // logger.error("No package was configured to be executed.");
- // System.exit(2);
- // }
- // StartTest tests = new StartTest();
-
- // stop on error logic
- // 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);
-
- // TestListenerAdapter tla = new TestListenerAdapter();
- //
- // TestHTMLReporter report = new TestHTMLReporter();
- //// report.
-
TestNG testng = new TestNG();
List<String> suites = new ArrayList<String>();
suites.add("testSuites/" + args[0]);
testng.setTestSuites(suites);
- // testng.addListener(tla);
testng.setUseDefaultListeners(true);
testng.setOutputDirectory("target/");
- StartTest tests = new StartTest();
- // testng.setPreserveOrder(true);
- // testng.setVerbose(2);
- // testng.setSuiteThreadPoolSize(1);
- // testng.setThreadCount(1);
testng.run();
}
@@ -145,10 +111,6 @@ public class StartTest {
}
}
- // logger.debug("Going to run test class {}", testClass.getName());
- // logger.debug("Test class {} finished {}", testClass.getName(), (result.wasSuccessful() ? "OK." : " WITH ERROR."));
- // logger.debug("class {} failed tests: {}", testClass.getName(), (failuresPerClass * 1.0) / runsPerClass * 100 + " %");
- // logger.debug("class {} ignored tests: {}", testClass.getName(), (ignoredPerClass * 1.0) / runsPerClass * 100 + " %");
private List<Class> getClassesForPackage(String pkgname) {
List<Class> classes = new ArrayList<Class>();
@@ -290,4 +252,22 @@ public class StartTest {
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
index bab5afaa08..56ddc196cb 100644
--- 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
@@ -40,7 +40,7 @@ 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.SdcTest;
+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;
@@ -49,7 +49,7 @@ import org.slf4j.LoggerFactory;
public class StartTest2backup {
- private List<Class<? extends SdcTest>> testClasses = new ArrayList<Class<? extends SdcTest>>();
+ private List<Class<? extends AttSdcTest>> testClasses = new ArrayList<Class<? extends AttSdcTest>>();
public static long timeOfTest = 0;
public static boolean debug = false;
@@ -170,7 +170,7 @@ public class StartTest2backup {
int totalFailureTests = 0;
int totalIgnoreTests = 0;
int numOfFailureClasses = 0;
- for (Class<? extends SdcTest> testClass : testClasses) {
+ for (Class<? extends AttSdcTest> testClass : testClasses) {
index++;
@@ -187,18 +187,17 @@ public class StartTest2backup {
System.out.println(builder.toString());
logger.debug(builder.toString());
- logger.debug("Going to run test class {}", testClass.getName());
+ 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."));
+ 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 " + testClass.getName() + " failure test " + failure.getTestHeader() + "-"
- + failure.getTrace());
+ logger.error("Test class {} failure test {}-{}",testClass.getName(),failure.getTestHeader(),failure.getTrace());
}
}
int runsPerClass = result.getRunCount();
@@ -209,8 +208,10 @@ public class StartTest2backup {
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 + " %");
+ 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) {
@@ -242,9 +243,8 @@ public class StartTest2backup {
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) + " %");
+ logger.error("Failure tests : {} %",((totalFailureTests + totalIgnoreTests) * 1.0) / (totalRunTests + totalIgnoreTests));
+ logger.error("Ignored tests : {} %",(totalIgnoreTests * 1.0) / (totalRunTests + totalIgnoreTests));
System.exit(1);
}
@@ -392,7 +392,7 @@ public class StartTest2backup {
results.append("</tr>");
}
- private void addUnitTestResult(StringBuilder results, Class<? extends SdcTest> testClass,
+ private void addUnitTestResult(StringBuilder results, Class<? extends AttSdcTest> testClass,
Result unitTestResult) {
boolean isSuccess = unitTestResult.wasSuccessful();
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
index 00ff48e887..b676b29bda 100644
--- 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
@@ -88,71 +88,85 @@ public class CrudE2E extends ComponentBaseTest {
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);
+ 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.YANG, resourceDetailsVFCcomp_01,UserRoleEnum.DESIGNER, false, true);
- AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.YANG_XML, 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);
+ 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);
+ 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);
+ 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);
+ 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);
+ 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);
+ 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);
+ 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);
+ 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.YANG, resourceDetailsVF_01, UserRoleEnum.DESIGNER,false, true);
- AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.YANG_XML, 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);
+ 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();
+ 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);
+ 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));
@@ -161,30 +175,49 @@ public class CrudE2E extends ComponentBaseTest {
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);
+
+ 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());
+ 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);
+ 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);
+ 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();
+ resourceDetailsVF1ins_01 = AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceDetailsVF_01, defaultService1, UserRoleEnum.DESIGNER, true).left().value();
//////// distribute service1 - failed due to incorrect LifeCyclestatus
//////// ////////
@@ -193,15 +226,15 @@ public class CrudE2E extends ComponentBaseTest {
//////// 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());
+ 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);
+ changeComponentInstanceVersion = AtomicOperationUtils.changeComponentInstanceVersion(defaultService1, resourceDetailsVF1ins_01, resourceDetailsVF_01, UserRoleEnum.DESIGNER, true);
resourceDetailsVF_01 = changeComponentInstanceVersion.left().value().getLeft();
resourceDetailsVFC1compIns1 = changeComponentInstanceVersion.left().value().getRight();
@@ -212,9 +245,43 @@ public class CrudE2E extends ComponentBaseTest {
AtomicOperationUtils.distributeService(defaultService1, true);
/////// create VF2 ////////
- Either<Resource, RestResponse> resourceDetailsVF_02e = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.ROOT,ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, UserRoleEnum.DESIGNER, true);
+
+ 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
index 8b8a793bc6..0a7b4a98aa 100644
--- 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
@@ -20,14 +20,14 @@
package org.openecomp.sdc.ci.tests.sanity;
-import static org.testng.AssertJUnit.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.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.ComponentInstance;
import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
@@ -43,6 +43,7 @@ import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
import org.openecomp.sdc.ci.tests.utils.rest.ComponentInstanceRestUtils;
import org.openecomp.sdc.ci.tests.utils.rest.ProductRestUtils;
import org.testng.annotations.Test;
+import static org.testng.AssertJUnit.assertTrue;
public class MultipleResourceUpdate extends ComponentBaseTest {
@@ -57,14 +58,18 @@ public class MultipleResourceUpdate extends ComponentBaseTest {
public void simpleScenario() throws Exception {
// Creating VF and Resource instances
- Resource vf = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value();
+ 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();
+ 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();
+ ResourceCategoryEnum.NETWORK_CONNECTIVITY_VIRTUAL_LINK, UserRoleEnum.DESIGNER, true)
+ .left().value();
vf.getCreatorUserId();
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
index 5ce4b8c618..766d4d9fd5 100644
--- 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
@@ -22,6 +22,11 @@ package org.openecomp.sdc.ci.tests.tosca.datatypes;
import java.util.List;
+/**
+ * First Level tosca yml structure
+ * @author al714h
+ *
+ */
public class ToscaDefinition {
String toscaDefinitionVersion;
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
index 4db52c2886..97a08479f8 100644
--- 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
@@ -21,20 +21,11 @@
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");
-
+
+ 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) {
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
index 12f8ffe984..7a26403053 100644
--- 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
@@ -20,12 +20,17 @@
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());
@@ -40,4 +45,22 @@ public class ArtifactUtils {
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
index 22295cb451..de7fd7eaf7 100644
--- 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
@@ -29,15 +29,7 @@ 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;
@@ -51,27 +43,26 @@ import com.thinkaurelius.titan.core.TitanVertex;
import fj.data.Either;
+import org.apache.tinkerpop.gremlin.structure.Direction;
+import org.apache.tinkerpop.gremlin.structure.Edge;
+import org.apache.tinkerpop.gremlin.structure.Vertex;
+import org.apache.tinkerpop.gremlin.structure.util.ElementHelper;
+import org.openecomp.sdc.ci.tests.api.Urls;
+import org.openecomp.sdc.ci.tests.config.Config;
+import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.users.UserAuditJavaObject;
+import org.openecomp.sdc.ci.tests.utils.cassandra.CassandraUtils;
+import org.apache.tinkerpop.gremlin.structure.Element;
+import org.apache.tinkerpop.gremlin.structure.Property;
+
public class DbUtils {
private static String titanConfigFilePath;
private static TitanGraph titanGraph;
public static void cleanAllAudits() throws IOException {
- // utils.deleteFromEsDbByPattern("_all");
- // deleteFromEsDbByPattern("auditingevents-*");
CassandraUtils.truncateAllTables("sdcaudit");
-
- // List <EsIndexTypeIdToDelete> auditIdArray = new
- // ArrayList<EsIndexTypeIdToDelete>();
- // auditIdArray = buildObjectArrayListByTypesIndex("auditingevents*",
- // "useraccessevent");
- //
- // logger.info("Starting to delete all service topologies from ES");
- // for (int i = 0; i < auditIdArray.size(); i ++){
- // EsIndexTypeIdToDelete esIndexTypeIdToDelete = auditIdArray.get(i);
- // utils.deleteFromEsDbByPattern(esIndexTypeIdToDelete.getIndex()+"/"+esIndexTypeIdToDelete.getType()+"/"+esIndexTypeIdToDelete.getId());
- //
- // }
}
public static RestResponse deleteFromEsDbByPattern(String patternToDelete) throws IOException {
@@ -81,8 +72,6 @@ public class DbUtils {
HttpRequest httpRequest = new HttpRequest();
RestResponse restResponse = httpRequest.httpSendDelete(url, null);
restResponse.getErrorCode();
- // System.out.println("URL to delete" + url);
- // System.out.println("response code" + restResponse.getErrorCode());
cleanAllAudits();
return restResponse;
@@ -94,9 +83,7 @@ public class DbUtils {
HttpRequest httpRequest = new HttpRequest();
RestResponse restResponse = httpRequest.httpSendGet(url, null);
restResponse.getErrorCode();
- // System.out.println("URL to get" + url);
- // System.out.println("response code" + restResponse.getErrorCode());
-
+
return restResponse;
}
@@ -137,7 +124,6 @@ public class DbUtils {
}
- //
private static TitanGraph getTitanGraph() {
if (titanGraph == null) {
titanGraph = TitanFactory.open(titanConfigFilePath);
@@ -288,8 +274,7 @@ public class DbUtils {
JsonObject jSourceObject = (JsonObject) jHitObject.get("_source");
auditParsedResp = gson.fromJson(jSourceObject, UserAuditJavaObject.class);
- // logger.debug("auditParsedResp: {}", auditParsedResp);
-
+
return auditParsedResp;
}
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
new file mode 100644
index 0000000000..85b01e6d2b
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/DistributionUtils.java
@@ -0,0 +1,166 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.utils;
+
+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 = "/asdc/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 "/asdc/v1/catalog/services/" + service.getSystemName() + "/" + service.getVersion() + "/artifacts/AAI-" + service.getName() + "-service-1.xml"
+ return serviceDistributionSuffix + service.getSystemName() + "/" + service.getVersion() + "/artifacts/" + artifactName;
+ }
+
+ public static String buildResourceInstanceDeploymentUrl(Service service, String artifactName, String artifactUUID){
+
+// /asdc/v1/catalog/services/Servicefordistribution/1.0 /resourceInstances/nestedfrommarina2 /artifacts/FEAdd_On_Module_vProbeLauncher.yaml
+ 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/Utils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/Utils.java
index 962f140dbd..8a8ec58217 100644
--- 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
@@ -28,6 +28,8 @@ 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;
@@ -56,9 +58,91 @@ public final class Utils {
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) {
@@ -100,6 +184,31 @@ public final class Utils {
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);
@@ -119,16 +228,324 @@ public final class Utils {
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());
- actual.removeAll(expected);
- assertEquals(message + " content got by rest API not match to " + message + " expected content", 0,
- actual.size());
+ // 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 {
@@ -230,4 +647,10 @@ public final class Utils {
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
index 51b68d4d56..832ebdf4b9 100644
--- 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
@@ -20,10 +20,10 @@
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 com.datastax.driver.core.*;
+import com.datastax.driver.core.querybuilder.QueryBuilder;
+import com.datastax.driver.core.querybuilder.Select;
+import com.datastax.driver.core.querybuilder.Select.Where;
import org.javatuples.Pair;
import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
@@ -32,15 +32,10 @@ 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;
+import java.io.FileNotFoundException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
public final class CassandraUtils {
private static Logger logger = LoggerFactory.getLogger(CassandraUtils.class.getName());
@@ -92,7 +87,7 @@ public final class CassandraUtils {
if (session != null) {
session.execute(QueryBuilder.truncate(keyspace, tableName));
- logger.debug("The table {}. {} was cleaned", keyspace, tableName);
+ logger.debug("The table {}.{} was cleaned",keyspace,tableName);
} else {
throw new RuntimeException("Keyspace " + keyspace + " not connected");
}
@@ -128,7 +123,7 @@ public final class CassandraUtils {
Collection<TableMetadata> tables = keyspaceMetadata.getTables();
tables.forEach(table -> {
session.execute(QueryBuilder.truncate(table));
- logger.debug("Table trunceted - {}", table.getName());
+ logger.debug("Table trunceted - {}",table.getName());
});
}
} else {
@@ -147,9 +142,21 @@ public final class CassandraUtils {
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 = 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);
@@ -205,9 +212,9 @@ public final class CassandraUtils {
// 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 );
+ // // 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
index 414ca2334e..cafdab7d8f 100644
--- 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
@@ -20,10 +20,10 @@
package org.openecomp.sdc.ci.tests.utils.cassandra;
-import java.io.FileNotFoundException;
-import java.util.Collection;
-import java.util.List;
-
+import com.datastax.driver.core.*;
+import com.datastax.driver.core.querybuilder.QueryBuilder;
+import com.datastax.driver.core.querybuilder.Select;
+import com.datastax.driver.core.querybuilder.Select.Where;
import org.javatuples.Pair;
import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
import org.openecomp.sdc.ci.tests.utils.Utils;
@@ -31,15 +31,9 @@ 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;
+import java.io.FileNotFoundException;
+import java.util.Collection;
+import java.util.List;
public final class CassandraUtils2 {
private static Logger logger = LoggerFactory.getLogger(CassandraUtils2.class.getName());
@@ -63,7 +57,7 @@ public final class CassandraUtils2 {
session = cluster.connect(keyspace);
if (session != null) {
session.execute(QueryBuilder.truncate(keyspace, tableName));
- logger.debug("The table {}. {} was cleaned", keyspace, tableName);
+ logger.debug("The table {}.{} was cleaned",keyspace,tableName);
} else {
throw new RuntimeException("Keyspace " + keyspace + " not connected");
}
@@ -95,7 +89,7 @@ public final class CassandraUtils2 {
Collection<TableMetadata> tables = keyspaceMetadata.getTables();
tables.forEach(table -> {
session.execute(QueryBuilder.truncate(table));
- logger.debug("Table trunceted - {}", table.getName());
+ logger.debug("Table trunceted - {}",table.getName());
});
}
} else {
@@ -164,9 +158,9 @@ public final class CassandraUtils2 {
// 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 );
+ // // 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
index 0456b2c121..465153af14 100644
--- 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
@@ -20,6 +20,7 @@
package org.openecomp.sdc.ci.tests.utils.general;
+import static org.testng.Assert.assertEquals;
import static org.testng.AssertJUnit.assertTrue;
import java.io.File;
@@ -33,6 +34,7 @@ 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;
@@ -212,7 +214,33 @@ public final class AtomicOperationUtils {
}
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 {
@@ -224,6 +252,7 @@ public final class AtomicOperationUtils {
LifeCycleStatesEnum curentCompState = LifeCycleStatesEnum.findByCompState(component.getLifecycleState().toString());
if (curentCompState == targetState) {
+ component = getCompoenntObject(component, userRole);
return Pair.of(component, null);
}
// List<LifeCycleStatesEnum> lifeCycleStatesEnumOrigList = new
@@ -261,8 +290,7 @@ public final class AtomicOperationUtils {
}
}
- component = getCompoenntObject(component, userRole);
- Component componentJavaObject = convertReposnseToComponentObject(component, lifeCycleStatesResponse);
+ Component componentJavaObject = getCompoenntObject(component, userRole);
if (validateState == true && isValidationFailed == true) {
assertTrue("change state failed" + lifeCycleStatesResponse.getResponse(), false);
@@ -301,6 +329,29 @@ public final class AtomicOperationUtils {
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 *****************
@@ -361,6 +412,13 @@ public final class AtomicOperationUtils {
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);
@@ -368,6 +426,13 @@ public final class AtomicOperationUtils {
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);
@@ -415,18 +480,18 @@ public final class AtomicOperationUtils {
}
return containerDetails;
}
-
- public static RestResponse associate2ResourceInstances(Component containerDetails, ComponentInstance fromNode, ComponentInstance toNode, String assocType, UserRoleEnum userRole, Boolean validateState) throws Exception {
+
+ 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);
@@ -559,7 +624,7 @@ public final class AtomicOperationUtils {
private static final long serialVersionUID = 1L;
};
-
+
/**
* Import resource from CSAR
*
@@ -572,15 +637,15 @@ public final class AtomicOperationUtils {
*/
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";
+ 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);
@@ -590,22 +655,22 @@ public final class AtomicOperationUtils {
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);
+ 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";
+ 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);
+ ResourceReqDetails defaultResource = ElementFactory.getDefaultResource(defaultUser);
ImportReqDetails defaultImportResource = ElementFactory.getDefaultImportResource(defaultResource);
ImportUtils.getImportResourceDetailsByPathAndName(defaultImportResource, realFilePath, fileName);
RestResponse resourceResp = ResourceRestUtils.createResource(defaultImportResource, defaultUser);
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
index 4aa13b48e4..79dea07c44 100644
--- 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
@@ -29,6 +29,7 @@ import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.model.DistributionStatusEnum;
import org.openecomp.sdc.be.model.LifecycleStateEnum;
import org.openecomp.sdc.be.model.Product;
import org.openecomp.sdc.be.model.User;
@@ -39,10 +40,12 @@ import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
import org.openecomp.sdc.ci.tests.datatypes.ResourceRespJavaObject;
import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo;
+import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedProductAudit;
import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedResourceAuditJavaObject;
import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedUserCRUDAudit;
+import org.openecomp.sdc.ci.tests.utils.Utils;
import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils;
import org.openecomp.sdc.common.api.Constants;
@@ -100,6 +103,38 @@ public class Convertor {
}
+ // ********** 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,
@@ -186,18 +221,18 @@ public class Convertor {
ExpectedProductAudit expectedProductAudit = new ExpectedProductAudit();
expectedProductAudit.setACTION(action);
- String userId = user.getUserId();
+ String userUserId = user.getUserId();
String userFullName;
if (StringUtils.isEmpty(user.getFirstName()) && StringUtils.isEmpty(user.getLastName())) {
userFullName = "";
} else {
userFullName = user.getFullName();
}
- if (StringUtils.isEmpty(userId)) {
- userId = "UNKNOWN";
+ if (StringUtils.isEmpty(userUserId)) {
+ userUserId = "UNKNOWN";
}
expectedProductAudit.setMODIFIER(
- !StringUtils.isEmpty(userFullName) ? userFullName + "(" + userId + ")" : "(" + userId + ")");
+ !StringUtils.isEmpty(userFullName) ? userFullName + "(" + userUserId + ")" : "(" + userUserId + ")");
expectedProductAudit.setSTATUS(Integer.toString(errorInfo.getCode()));
expectedProductAudit.setDESC(errorInfo.getAuditDesc((Object[]) (errorMessageParams)));
expectedProductAudit
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/ElementFactory.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/ElementFactory.java
index ba2ebd9b4e..c06cb570f8 100644
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/ElementFactory.java
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/ElementFactory.java
@@ -51,6 +51,8 @@ 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.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.ArtifactTypeEnum;
@@ -69,8 +71,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 com.google.common.base.CaseFormat;
+
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";
@@ -79,48 +85,48 @@ public class ElementFactory {
// *** RESOURCE ***
public static ResourceReqDetails getDefaultResource() {
- return getDefaultResource("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, "jh0003");
+ return getDefaultResource(CI_RES, NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, JH0003);
}
public static ResourceReqDetails getDefaultResource(ResourceCategoryEnum category) {
- return getDefaultResource("ciRes", NormativeTypesEnum.ROOT, category, "jh0003");
+ return getDefaultResource(CI_RES, NormativeTypesEnum.ROOT, category, JH0003);
}
public static ResourceReqDetails getDefaultResource(String contactId) {
- return getDefaultResource("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, contactId);
+ return getDefaultResource(CI_RES, NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, contactId);
}
public static ResourceReqDetails getDefaultResource(User modifier) {
- return getDefaultResource("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, modifier.getUserId());
+ return getDefaultResource(CI_RES, NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, modifier.getUserId());
}
public static ResourceReqDetails getDefaultResource(NormativeTypesEnum derivedFrom, ResourceCategoryEnum category) {
- return getDefaultResource("ciRes", derivedFrom, category, "jh0003");
+ return getDefaultResource(CI_RES, derivedFrom, category, JH0003);
}
public static ResourceReqDetails getDefaultResource(NormativeTypesEnum derivedFrom) {
- return getDefaultResource("ciRes", derivedFrom, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, "jh0003");
+ 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");
+ return getDefaultResource(resourceName, derivedFrom, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, JH0003);
}
public static ResourceReqDetails getDefaultResource(NormativeTypesEnum derivedFrom, String contactId) {
- return getDefaultResource("ciRes", derivedFrom, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, 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());
+ return getDefaultResourceByType(resourceName, NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, JH0003, ResourceType.toString());
}
public static ResourceReqDetails getDefaultResourceByType(ResourceTypeEnum ResourceType, User user) {
- return getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, user.getUserId(), ResourceType.toString());
+ 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("ciRes", normativeTypes, resourceCategory, user.getUserId(), resourceType.toString());
+ return getDefaultResourceByType(CI_RES, normativeTypes, resourceCategory, user.getUserId(), resourceType.toString());
}
public static PropertyReqDetails getDefaultMapProperty(PropertyTypeEnum innerType) {
@@ -139,7 +145,7 @@ public class ElementFactory {
ArrayList<String> derivedFrom = new ArrayList<String>();
derivedFrom.add(derived.normativeName);
- String vendorName = "ATT (Tosca)";
+ 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);
@@ -150,7 +156,7 @@ public class ElementFactory {
}
public static ResourceReqDetails getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum resourceType, Resource normativeTypes, ResourceCategoryEnum resourceCategory, User user) {
- return getDefaultResource("ciRes" + resourceType, normativeTypes, resourceCategory, user.getUserId());
+ return getDefaultResource(CI_RES + resourceType, normativeTypes, resourceCategory, user.getUserId());
}
public static ResourceReqDetails getDefaultResource(String resourceName, Resource derived, ResourceCategoryEnum category, String contactId) {
@@ -161,7 +167,7 @@ public class ElementFactory {
ArrayList<String> derivedFrom = new ArrayList<String>();
derivedFrom.add(derived.getToscaResourceName());
- String vendorName = "ATT (Tosca)";
+ 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);
@@ -186,13 +192,27 @@ public class ElementFactory {
derivedFrom = new ArrayList<String>();
derivedFrom.add(derived.normativeName);
}
- String vendorName = "ATT (Tosca)";
+ 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) {
@@ -205,7 +225,7 @@ public class ElementFactory {
derivedFrom = new ArrayList<String>();
derivedFrom.add(derived.normativeName);
}
- String vendorName = "ATT (Tosca)";
+ 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);
@@ -217,18 +237,18 @@ public class ElementFactory {
public static ImportReqDetails getDefaultImportResource(ResourceReqDetails resourceReqDetails) {
ImportReqDetails importReqDetails = new ImportReqDetails(resourceReqDetails.getName(), resourceReqDetails.getDescription(), resourceReqDetails.getTags(), resourceReqDetails.getDerivedFrom(), resourceReqDetails.getVendorName(),
resourceReqDetails.getVendorRelease(), resourceReqDetails.getContactId(), resourceReqDetails.getIcon());
- importReqDetails.setPayloadName("myCompute.yaml");
+ importReqDetails.setPayloadName("ciMyCompute.yaml");
importReqDetails.setCategories(resourceReqDetails.getCategories());
importReqDetails.setPayloadData(
"dG9zY2FfZGVmaW5pdGlvbnNfdmVyc2lvbjogdG9zY2Ffc2ltcGxlX3lhbWxfMV8wXzANCm5vZGVfdHlwZXM6IA0KICBvcmcub3BlbmVjb21wLnJlc291cmNlLk15Q29tcHV0ZToNCiAgICBkZXJpdmVkX2Zyb206IHRvc2NhLm5vZGVzLlJvb3QNCiAgICBhdHRyaWJ1dGVzOg0KICAgICAgcHJpdmF0ZV9hZGRyZXNzOg0KICAgICAgICB0eXBlOiBzdHJpbmcNCiAgICAgIHB1YmxpY19hZGRyZXNzOg0KICAgICAgICB0eXBlOiBzdHJpbmcNCiAgICAgIG5ldHdvcmtzOg0KICAgICAgICB0eXBlOiBtYXANCiAgICAgICAgZW50cnlfc2NoZW1hOg0KICAgICAgICAgIHR5cGU6IHRvc2NhLmRhdGF0eXBlcy5uZXR3b3JrLk5ldHdvcmtJbmZvDQogICAgICBwb3J0czoNCiAgICAgICAgdHlwZTogbWFwDQogICAgICAgIGVudHJ5X3NjaGVtYToNCiAgICAgICAgICB0eXBlOiB0b3NjYS5kYXRhdHlwZXMubmV0d29yay5Qb3J0SW5mbw0KICAgIHJlcXVpcmVtZW50czoNCiAgICAgIC0gbG9jYWxfc3RvcmFnZTogDQogICAgICAgICAgY2FwYWJpbGl0eTogdG9zY2EuY2FwYWJpbGl0aWVzLkF0dGFjaG1lbnQNCiAgICAgICAgICBub2RlOiB0b3NjYS5ub2Rlcy5CbG9ja1N0b3JhZ2UNCiAgICAgICAgICByZWxhdGlvbnNoaXA6IHRvc2NhLnJlbGF0aW9uc2hpcHMuQXR0YWNoZXNUbw0KICAgICAgICAgIG9jY3VycmVuY2VzOiBbMCwgVU5CT1VOREVEXSAgDQogICAgY2FwYWJpbGl0aWVzOg0KICAgICAgaG9zdDogDQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5Db250YWluZXINCiAgICAgICAgdmFsaWRfc291cmNlX3R5cGVzOiBbdG9zY2Eubm9kZXMuU29mdHdhcmVDb21wb25lbnRdIA0KICAgICAgZW5kcG9pbnQgOg0KICAgICAgICB0eXBlOiB0b3NjYS5jYXBhYmlsaXRpZXMuRW5kcG9pbnQuQWRtaW4gDQogICAgICBvczogDQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5PcGVyYXRpbmdTeXN0ZW0NCiAgICAgIHNjYWxhYmxlOg0KICAgICAgICB0eXBlOiB0b3NjYS5jYXBhYmlsaXRpZXMuU2NhbGFibGUNCiAgICAgIGJpbmRpbmc6DQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5uZXR3b3JrLkJpbmRhYmxlDQo=");
- return importReqDetails;
+ return importReqDetails;
}
public static ImportReqDetails getDefaultImportResource() {
ResourceReqDetails resourceReqDetails = getDefaultResource();
ImportReqDetails importReqDetails = new ImportReqDetails(resourceReqDetails.getName(), resourceReqDetails.getDescription(), resourceReqDetails.getTags(), resourceReqDetails.getDerivedFrom(), resourceReqDetails.getVendorName(),
resourceReqDetails.getVendorRelease(), resourceReqDetails.getContactId(), resourceReqDetails.getIcon());
- importReqDetails.setPayloadName("myCompute.yaml");
+ importReqDetails.setPayloadName("ciMyCompute.yaml");
importReqDetails.setCategories(resourceReqDetails.getCategories());
importReqDetails.setPayloadData(
"dG9zY2FfZGVmaW5pdGlvbnNfdmVyc2lvbjogdG9zY2Ffc2ltcGxlX3lhbWxfMV8wXzANCm5vZGVfdHlwZXM6IA0KICBvcmcub3BlbmVjb21wLnJlc291cmNlLk15Q29tcHV0ZToNCiAgICBkZXJpdmVkX2Zyb206IHRvc2NhLm5vZGVzLlJvb3QNCiAgICBhdHRyaWJ1dGVzOg0KICAgICAgcHJpdmF0ZV9hZGRyZXNzOg0KICAgICAgICB0eXBlOiBzdHJpbmcNCiAgICAgIHB1YmxpY19hZGRyZXNzOg0KICAgICAgICB0eXBlOiBzdHJpbmcNCiAgICAgIG5ldHdvcmtzOg0KICAgICAgICB0eXBlOiBtYXANCiAgICAgICAgZW50cnlfc2NoZW1hOg0KICAgICAgICAgIHR5cGU6IHRvc2NhLmRhdGF0eXBlcy5uZXR3b3JrLk5ldHdvcmtJbmZvDQogICAgICBwb3J0czoNCiAgICAgICAgdHlwZTogbWFwDQogICAgICAgIGVudHJ5X3NjaGVtYToNCiAgICAgICAgICB0eXBlOiB0b3NjYS5kYXRhdHlwZXMubmV0d29yay5Qb3J0SW5mbw0KICAgIHJlcXVpcmVtZW50czoNCiAgICAgIC0gbG9jYWxfc3RvcmFnZTogDQogICAgICAgICAgY2FwYWJpbGl0eTogdG9zY2EuY2FwYWJpbGl0aWVzLkF0dGFjaG1lbnQNCiAgICAgICAgICBub2RlOiB0b3NjYS5ub2Rlcy5CbG9ja1N0b3JhZ2UNCiAgICAgICAgICByZWxhdGlvbnNoaXA6IHRvc2NhLnJlbGF0aW9uc2hpcHMuQXR0YWNoZXNUbw0KICAgICAgICAgIG9jY3VycmVuY2VzOiBbMCwgVU5CT1VOREVEXSAgDQogICAgY2FwYWJpbGl0aWVzOg0KICAgICAgaG9zdDogDQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5Db250YWluZXINCiAgICAgICAgdmFsaWRfc291cmNlX3R5cGVzOiBbdG9zY2Eubm9kZXMuU29mdHdhcmVDb21wb25lbnRdIA0KICAgICAgZW5kcG9pbnQgOg0KICAgICAgICB0eXBlOiB0b3NjYS5jYXBhYmlsaXRpZXMuRW5kcG9pbnQuQWRtaW4gDQogICAgICBvczogDQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5PcGVyYXRpbmdTeXN0ZW0NCiAgICAgIHNjYWxhYmxlOg0KICAgICAgICB0eXBlOiB0b3NjYS5jYXBhYmlsaXRpZXMuU2NhbGFibGUNCiAgICAgIGJpbmRpbmc6DQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5uZXR3b3JrLkJpbmRhYmxlDQo=");
@@ -239,7 +259,7 @@ public class ElementFactory {
ResourceReqDetails resourceReqDetails = getDefaultResourceByType(ResourceTypeEnum.VFC, name);
ImportReqDetails importReqDetails = new ImportReqDetails(resourceReqDetails.getName(), resourceReqDetails.getDescription(), resourceReqDetails.getTags(), resourceReqDetails.getDerivedFrom(), resourceReqDetails.getVendorName(),
resourceReqDetails.getVendorRelease(), resourceReqDetails.getContactId(), resourceReqDetails.getIcon());
- importReqDetails.setPayloadName("myCompute.yaml");
+ importReqDetails.setPayloadName("ciMyCompute.yaml");
importReqDetails.setCategories(resourceReqDetails.getCategories());
importReqDetails.setPayloadData(
"dG9zY2FfZGVmaW5pdGlvbnNfdmVyc2lvbjogdG9zY2Ffc2ltcGxlX3lhbWxfMV8wXzANCm5vZGVfdHlwZXM6IA0KICBvcmcub3BlbmVjb21wLnJlc291cmNlLk15Q29tcHV0ZToNCiAgICBkZXJpdmVkX2Zyb206IHRvc2NhLm5vZGVzLlJvb3QNCiAgICBhdHRyaWJ1dGVzOg0KICAgICAgcHJpdmF0ZV9hZGRyZXNzOg0KICAgICAgICB0eXBlOiBzdHJpbmcNCiAgICAgIHB1YmxpY19hZGRyZXNzOg0KICAgICAgICB0eXBlOiBzdHJpbmcNCiAgICAgIG5ldHdvcmtzOg0KICAgICAgICB0eXBlOiBtYXANCiAgICAgICAgZW50cnlfc2NoZW1hOg0KICAgICAgICAgIHR5cGU6IHRvc2NhLmRhdGF0eXBlcy5uZXR3b3JrLk5ldHdvcmtJbmZvDQogICAgICBwb3J0czoNCiAgICAgICAgdHlwZTogbWFwDQogICAgICAgIGVudHJ5X3NjaGVtYToNCiAgICAgICAgICB0eXBlOiB0b3NjYS5kYXRhdHlwZXMubmV0d29yay5Qb3J0SW5mbw0KICAgIHJlcXVpcmVtZW50czoNCiAgICAgIC0gbG9jYWxfc3RvcmFnZTogDQogICAgICAgICAgY2FwYWJpbGl0eTogdG9zY2EuY2FwYWJpbGl0aWVzLkF0dGFjaG1lbnQNCiAgICAgICAgICBub2RlOiB0b3NjYS5ub2Rlcy5CbG9ja1N0b3JhZ2UNCiAgICAgICAgICByZWxhdGlvbnNoaXA6IHRvc2NhLnJlbGF0aW9uc2hpcHMuQXR0YWNoZXNUbw0KICAgICAgICAgIG9jY3VycmVuY2VzOiBbMCwgVU5CT1VOREVEXSAgDQogICAgY2FwYWJpbGl0aWVzOg0KICAgICAgaG9zdDogDQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5Db250YWluZXINCiAgICAgICAgdmFsaWRfc291cmNlX3R5cGVzOiBbdG9zY2Eubm9kZXMuU29mdHdhcmVDb21wb25lbnRdIA0KICAgICAgZW5kcG9pbnQgOg0KICAgICAgICB0eXBlOiB0b3NjYS5jYXBhYmlsaXRpZXMuRW5kcG9pbnQuQWRtaW4gDQogICAgICBvczogDQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5PcGVyYXRpbmdTeXN0ZW0NCiAgICAgIHNjYWxhYmxlOg0KICAgICAgICB0eXBlOiB0b3NjYS5jYXBhYmlsaXRpZXMuU2NhbGFibGUNCiAgICAgIGJpbmRpbmc6DQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5uZXR3b3JrLkJpbmRhYmxlDQo=");
@@ -423,16 +443,17 @@ public class ElementFactory {
}
public static ArtifactReqDetails getDefaultDeploymentArtifactForType(String artifactType) throws IOException, Exception {
- return getArtifactByType(DEFAULT_ARTIFACT_LABEL, artifactType, true);
+ 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);
+ return getArtifactByType(DEFAULT_ARTIFACT_LABEL, artifactType.toString(), deploymentTrue, false);
}
- public static ArtifactReqDetails getArtifactByType(String artifactLabel, String artifactType, Boolean deploymentTrue) throws IOException, Exception {
+ 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 = "";
@@ -449,6 +470,7 @@ public class ElementFactory {
* Missing file type: DCAE_JSON
*/
switch (artifactTypeEnum) {
+ case DCAE_INVENTORY_TOSCA:
case DCAE_EVENT:
case APPC_CONFIG:
case DCAE_DOC:
@@ -458,18 +480,17 @@ public class ElementFactory {
case HEAT_VOL: {
artifactName = generateUUIDforSufix() + artifactType + "_install_apache2.yaml";
payloadData = "aGVhdF90ZW1wbGF0ZV92ZXJzaW9uOiAyMDEzLTA1LTIzDQoNCmRlc2NyaXB0aW9uOiBTaW1wbGUgdGVtcGxhdGUgdG8gZGVwbG95IGEgc3RhY2sgd2l0aCB0d28gdmlydHVhbCBtYWNoaW5lIGluc3RhbmNlcw0KDQpwYXJhbWV0ZXJzOg0KICBpbWFnZV9uYW1lXzE6DQogICAgdHlwZTogc3RyaW5nDQogICAgbGFiZWw6IEltYWdlIE5hbWUNCiAgICBkZXNjcmlwdGlvbjogU0NPSU1BR0UgU3BlY2lmeSBhbiBpbWFnZSBuYW1lIGZvciBpbnN0YW5jZTENCiAgICBkZWZhdWx0OiBjaXJyb3MtMC4zLjEteDg2XzY0DQogIGltYWdlX25hbWVfMjoNCiAgICB0eXBlOiBzdHJpbmcNCiAgICBsYWJlbDogSW1hZ2UgTmFtZQ0KICAgIGRlc2NyaXB0aW9uOiBTQ09JTUFHRSBTcGVjaWZ5IGFuIGltYWdlIG5hbWUgZm9yIGluc3RhbmNlMg0KICAgIGRlZmF1bHQ6IGNpcnJvcy0wLjMuMS14ODZfNjQNCiAgbmV0d29ya19pZDoNCiAgICB0eXBlOiBzdHJpbmcNCiAgICBsYWJlbDogTmV0d29yayBJRA0KICAgIGRlc2NyaXB0aW9uOiBTQ09ORVRXT1JLIE5ldHdvcmsgdG8gYmUgdXNlZCBmb3IgdGhlIGNvbXB1dGUgaW5zdGFuY2UNCiAgICBoaWRkZW46IHRydWUNCiAgICBjb25zdHJhaW50czoNCiAgICAgIC0gbGVuZ3RoOiB7IG1pbjogNiwgbWF4OiA4IH0NCiAgICAgICAgZGVzY3JpcHRpb246IFBhc3N3b3JkIGxlbmd0aCBtdXN0IGJlIGJldHdlZW4gNiBhbmQgOCBjaGFyYWN0ZXJzLg0KICAgICAgLSByYW5nZTogeyBtaW46IDYsIG1heDogOCB9DQogICAgICAgIGRlc2NyaXB0aW9uOiBSYW5nZSBkZXNjcmlwdGlvbg0KICAgICAgLSBhbGxvd2VkX3ZhbHVlczoNCiAgICAgICAgLSBtMS5zbWFsbA0KICAgICAgICAtIG0xLm1lZGl1bQ0KICAgICAgICAtIG0xLmxhcmdlDQogICAgICAgIGRlc2NyaXB0aW9uOiBBbGxvd2VkIHZhbHVlcyBkZXNjcmlwdGlvbg0KICAgICAgLSBhbGxvd2VkX3BhdHRlcm46ICJbYS16QS1aMC05XSsiDQogICAgICAgIGRlc2NyaXB0aW9uOiBQYXNzd29yZCBtdXN0IGNvbnNpc3Qgb2YgY2hhcmFjdGVycyBhbmQgbnVtYmVycyBvbmx5Lg0KICAgICAgLSBhbGxvd2VkX3BhdHRlcm46ICJbQS1aXStbYS16QS1aMC05XSoiDQogICAgICAgIGRlc2NyaXB0aW9uOiBQYXNzd29yZCBtdXN0IHN0YXJ0IHdpdGggYW4gdXBwZXJjYXNlIGNoYXJhY3Rlci4NCiAgICAgIC0gY3VzdG9tX2NvbnN0cmFpbnQ6IG5vdmEua2V5cGFpcg0KICAgICAgICBkZXNjcmlwdGlvbjogQ3VzdG9tIGRlc2NyaXB0aW9uDQoNCnJlc291cmNlczoNCiAgbXlfaW5zdGFuY2UxOg0KICAgIHR5cGU6IE9TOjpOb3ZhOjpTZXJ2ZXINCiAgICBwcm9wZXJ0aWVzOg0KICAgICAgaW1hZ2U6IHsgZ2V0X3BhcmFtOiBpbWFnZV9uYW1lXzEgfQ0KICAgICAgZmxhdm9yOiBtMS5zbWFsbA0KICAgICAgbmV0d29ya3M6DQogICAgICAgIC0gbmV0d29yayA6IHsgZ2V0X3BhcmFtIDogbmV0d29ya19pZCB9DQogIG15X2luc3RhbmNlMjoNCiAgICB0eXBlOiBPUzo6Tm92YTo6U2VydmVyDQogICAgcHJvcGVydGllczoNCiAgICAgIGltYWdlOiB7IGdldF9wYXJhbTogaW1hZ2VfbmFtZV8yIH0NCiAgICAgIGZsYXZvcjogbTEudGlueQ0KICAgICAgbmV0d29ya3M6DQogICAgICAgIC0gbmV0d29yayA6IHsgZ2V0X3BhcmFtIDogbmV0d29ya19pZCB9";
+ updatedPayloadData = "dG9zY2FfZGVmaW5pdGlvbnNfdmVyc2lvbjogdG9zY2Ffc2ltcGxlX3lhbWxfMV8wXzANCg0Kbm9kZV90eXBlczoNCiAgY29tLmF0dC5kMi5yZXNvdXJjZS5jcC5DUDoNCiAgICBkZXJpdmVkX2Zyb206IHRvc2NhLm5vZGVzLm5ldHdvcmsuUG9ydA0KICAgIHByb3BlcnRpZXM6DQogICAgICBpc190YWdnZWQ6DQogICAgICAgIHR5cGU6IGJvb2xlYW4NCiAgICAgICAgcmVxdWlyZWQ6IGZhbHNlDQogICAgICAgIGRlZmF1bHQ6IGZhbHNlDQogICAgICAgIGRlc2NyaXB0aW9uOiANCg0KICAgIHJlcXVpcmVtZW50czoNCiAgICAgIC0gdmlydHVhbExpbms6DQogICAgICAgICAgY2FwYWJpbGl0eTogdG9zY2EuY2FwYWJpbGl0aWVzLm5ldHdvcmsuTGlua2FibGUNCiAgICAgICAgICByZWxhdGlvbnNoaXA6IHRvc2NhLnJlbGF0aW9uc2hpcHMubmV0d29yay5MaW5rc1RvDQogICAgICAtIHZpcnR1YWxCaW5kaW5nOg0KICAgICAgICAgIGNhcGFiaWxpdHk6IHRvc2NhLmNhcGFiaWxpdGllcy5uZXR3b3JrLkJpbmRhYmxlDQogICAgICAgICAgcmVsYXRpb25zaGlwOiB0b3NjYS5yZWxhdGlvbnNoaXBzLm5ldHdvcmsuQmluZHNUbw0KICAgIGNhcGFiaWxpdGllczoNCiAgICAgIGF0dGFjaG1lbnQ6DQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5BdHRhY2htZW50DQogICAgICAgIG9jY3VycmVuY2VzOg0KICAgICAgICAtIDENCiAgICAgICAgLSBVTkJPVU5ERUQNCiAgICAgICAgdHlwZTogdG9zY2EuY2FwYWJpbGl0aWVzLm5ldHdvcmsuQmluZGFibGUNCiAgICAgICAgb2NjdXJyZW5jZXM6DQogICAgICAgIC0gMQ0KICAgICAgICAtIFVOQk9VTkRFRA0KICAgICAgdmlydHVhbF9saW5rYWJsZToNCiAgICAgICAgdHlwZTogY29tLmF0dC5kMi5jYXBhYmlsaXRpZXMuTWV0cmljDQogICAgICBlbmRfcG9pbnQ6DQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5FbmRwb2ludCAgICAgICA=";
timeout = 60;
artifactLabel = normalizeArtifactLabel(artifactName);
break;
}
- case DCAE_INVENTORY_TOSCA:
- case DCAE_INVENTORY_JSON:
case DCAE_INVENTORY_POLICY:
- case DCAE_INVENTORY_DOC:
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;
@@ -477,16 +498,20 @@ public class ElementFactory {
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 = "e30=";
+ payloadData = "ew0KICAiYXJ0aWZhY3RzIjogImRmc2FmIiwNCiAgIm5vcm1hbGl6ZWROYW1lIjogImNpc2VydmljZTBiYzY5ODk2OTQ4ZiIsDQogICJzeXN0ZW1OYW1lIjogIkNpc2VydmljZTBiYzY5ODk2OTQ4ZiIsDQogICJpbnZhcmlhbnRVVUlEIjogIjEzZmJkNzI3LWRjNzUtNDU1OS1iNzEyLWUwMjc5YmY4YTg2MSIsDQogICJhdHRDb250YWN0IjogImNzMDAwOCIsDQogICJuYW1lIjogImNpU2VydmljZTBiYzY5ODk2OTQ4ZiINCn0=";
+ updatedPayloadData = "ew0KICAiYXJ0aWZhY3RzIjogIjEyMzQzIiwNCiAgIm5vcm1hbGl6ZWROYW1lIjogIjU0MzUzNCIsDQogICJzeXN0ZW1OYW1lIjogIkNpc2VydmljZTBiYzY5ODk2OTQ4ZiIsDQogICJpbnZhcmlhbnRVVUlEIjogIjEzZmJkNzI3LWRjNzUtNDU1OS1iNzEyLWUwMjc5YmY4YTg2MSIsDQogICJhdHRDb250YWN0IjogImNzMDAwOCIsDQogICJuYW1lIjogImNpU2VydmljZTBiYzY5ODk2OTQ4ZiINCn0=";
break;
}
case PUPPET:
@@ -495,6 +520,7 @@ public class ElementFactory {
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;
@@ -507,13 +533,19 @@ public class ElementFactory {
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;
@@ -522,12 +554,21 @@ public class ElementFactory {
default: {// dummy
artifactName = generateUUIDforSufix() + "testArtifact.sh";
payloadData = "dGVzdA==";
+ updatedPayloadData = "YmVzYg==";
artifactLabel = normalizeArtifactLabel(artifactName);
break;
}
}
-
- ArtifactReqDetails artifactDetails = new ArtifactReqDetails(artifactName, artifactType, artifactDescription, payloadData, artifactLabel);
+ 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);
@@ -687,6 +728,43 @@ public class ElementFactory {
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("/asdc/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) {
@@ -768,26 +846,26 @@ public class ElementFactory {
// Category/Subcategory/Group
public static CategoryDefinition getDefaultCategory() {
CategoryDefinition productCategoryDefinition = new CategoryDefinition();
- productCategoryDefinition.setName("Category1");
+ productCategoryDefinition.setName("CiCateg" + generateUUIDforSufix());
return productCategoryDefinition;
}
public static SubCategoryDefinition getDefaultSubCategory() {
SubCategoryDefinition productSubCategoryDefinition = new SubCategoryDefinition();
- productSubCategoryDefinition.setName("SubCategory1");
+ productSubCategoryDefinition.setName("CiSubCateg" + generateUUIDforSufix());
return productSubCategoryDefinition;
}
public static GroupingDefinition getDefaultGroup() {
GroupingDefinition productGroupDefinition = new GroupingDefinition();
- productGroupDefinition.setName("Grouping1");
+ productGroupDefinition.setName("CiGrouping1" + generateUUIDforSufix());
return productGroupDefinition;
}
// Product
public static ProductReqDetails getDefaultProduct() {
- return createDefaultProductReqDetails("Product1", null);
+ return createDefaultProductReqDetails("CiProduct1", null);
}
public static ProductReqDetails getDefaultProduct(String name) {
@@ -822,10 +900,7 @@ public class ElementFactory {
product.setProjectCode("12345");
product.setIcon("myIcon");
ArrayList<String> contacts = new ArrayList<String>();
- // contacts.add(ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_STRATEGIST1).getUserId());
- // contacts.add(ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_STRATEGIST2).getUserId());
contacts.add(ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_MANAGER1).getUserId());
- // contacts.add(ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_MANAGER2).getUserId());
product.setContacts(contacts);
product.setCategories(categories);
String fullName = "This is my full name: " + name;
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
index b785563a4d..b07a3c3d7b 100644
--- 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
@@ -39,7 +39,6 @@ import org.slf4j.LoggerFactory;
import fj.data.Either;
public class FileUtils {
-
static Logger logger = LoggerFactory.getLogger(Utils.class.getName());
public static void writeToFile(String filePath, String content) {
@@ -99,16 +98,18 @@ public class FileUtils {
return null;
}
- public static String loadPayloadFileFromListUsingPosition(List<String> listFileName, String pattern, Boolean isBase64, int positionInList) throws IOException {
+ public static String loadPayloadFileFromListUsingPosition(List<String> listFileName, String pattern,
+ Boolean isBase64, int positionInList) throws IOException {
List<String> newList = new ArrayList<String>(Arrays.asList(listFileName.get(positionInList)));
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);
- logger.debug("fileName: {}", fileName);
+ logger.debug("fileName: {}",fileName);
if (fileName != null) {
payload = Decoder.readFileToString(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
index 040cdba444..c1f311a91e 100644
--- 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
@@ -20,14 +20,21 @@
package org.openecomp.sdc.ci.tests.utils.general;
+import java.io.File;
import java.io.IOException;
import java.util.List;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.config.Config;
import org.openecomp.sdc.ci.tests.datatypes.ImportReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.utils.Utils;
public class ImportUtils {
- public static ImportReqDetails getImportResourceDetailsByPathAndName(ImportReqDetails importReqDetails, String filePath, String fileName) throws IOException {
+ public static ImportReqDetails getImportResourceDetailsByPathAndName(ImportReqDetails importReqDetails,
+ String filePath, String fileName) throws IOException {
// ImportReqDetails importReqDetails;
// User sdncUserDetails;
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
new file mode 100644
index 0000000000..2fa5807aff
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/graph/GraphFileUtils.java
@@ -0,0 +1,39 @@
+package org.openecomp.sdc.ci.tests.utils.graph;
+
+import com.thinkaurelius.titan.core.TitanVertex;
+import org.apache.commons.io.FileUtils;
+import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+
+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;
+
+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
index 4360621364..ddd9209d83 100644
--- 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
@@ -34,6 +34,7 @@ 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;
@@ -58,53 +59,197 @@ import com.google.gson.Gson;
public class ArtifactRestUtils extends BaseRestUtils {
private static Logger logger = LoggerFactory.getLogger(ArtifactRestUtils.class.getName());
-
+
+
// External API
- // Upload Artifact of the asset
+ // 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")) {
+
+ 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 {
+ public static RestResponse getResourceDeploymentArtifactExternalAPI(String resourceUUID, String artifactUUID,User sdncModifierDetails, String resourceType) throws IOException {
Config config = Utils.getConfig();
String url = null;
-
- if (resourceType.equals("Service")) {
+
+ 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>();
+
+ 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);
+ 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);
+
+ logger.debug("Request headers: {}",headersMap);
System.out.println("Request headers: " + headersMap);
RestResponse sendGetResourceAssets = http.httpSendGet(url, headersMap);
@@ -112,30 +257,32 @@ public class ArtifactRestUtils extends BaseRestUtils {
return sendGetResourceAssets;
}
-
- public static RestResponse getComponentInstanceDeploymentArtifactExternalAPI(String resourceUUID, String componentInstanceUID, String artifactUUID, User sdncModifierDetails, String resourceType) throws IOException {
+
+
+
+ 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.equals("Service")) {
- url = String.format(Urls.GET_DOWNLOAD_SERVICE_ARTIFACT_OF_COMPONENT_INSTANCE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceUUID, componentInstanceUID, artifactUUID);
+
+ 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, componentInstanceUID, artifactUUID);
+ 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<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);
+ 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);
+
+ logger.debug("Request headers: {}",headersMap);
System.out.println("Request headers: " + headersMap);
RestResponse sendGetResourceAssets = http.httpSendGet(url, headersMap);
@@ -143,8 +290,9 @@ public class ArtifactRestUtils extends BaseRestUtils {
return sendGetResourceAssets;
}
-
- // *********** SERVICE ****************
+
+
+ //*********** SERVICE ****************
public static RestResponse getArtifactTypesList() throws IOException {
Config config = Utils.getConfig();
String url = String.format(Urls.GET_ALL_ARTIFACTS, config.getCatalogBeHost(), config.getCatalogBePort());
@@ -163,90 +311,117 @@ public class ArtifactRestUtils extends BaseRestUtils {
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) 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 {
+
+ 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 {
+ 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 {
+ 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);
+ 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
-
+ //update
+
public static RestResponse updateInformationalArtifactOfServiceByMethod(ArtifactReqDetails artifactReqDetails, String serviceUid, String artifactUid, User sdncModifierDetails, String httpMethod) throws IOException {
- // TODO Auto-generated method stub
return updateInformationalArtifactOfServiceByMethod(artifactReqDetails, serviceUid, artifactUid, sdncModifierDetails, httpMethod, calculateChecksum(artifactReqDetails));
}
-
+
public static RestResponse updateInformationalArtifactOfServiceByMethod(ArtifactReqDetails artifactReqDetails, String serviceUid, User sdncModifierDetails, String httpMethod) throws IOException {
- // TODO Auto-generated method stub
return updateInformationalArtifactOfServiceByMethod(artifactReqDetails, serviceUid, artifactReqDetails.getUniqueId(), sdncModifierDetails, httpMethod, calculateChecksum(artifactReqDetails));
}
-
- public static RestResponse downloadResourceArtifactInternalApi(String resourceId, User user, String artifactUniqeId) throws Exception {
+
+ 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 {
+ 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 {
+ 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);
+ 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 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);
- public static RestResponse updateInformationalArtifactOfServiceByMethod(ArtifactReqDetails artifactReqDetails, String serviceUid, String artifactUid, User sdncModifierDetails, String httpMethod, String checksum) throws IOException {
+ 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);
@@ -256,150 +431,168 @@ public class ArtifactRestUtils extends BaseRestUtils {
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);
+ 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());
+// 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>();
+ 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) {
-
+
+ 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 {
+ //*********** 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 {
+
+ 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);
+
+ 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 {
+
+ 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);
+
+ 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);
-
+ 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 {
+ //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);
+ 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);
+ 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 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 updateDeploymentArtifactToRI(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String resourceInstanceId, String serviceId) throws IOException {
Config config = Utils.getConfig();
String url = String.format(Urls.UPDATE_RESOURCE_INSTANCE_HEAT_ENV_PARAMS, config.getCatalogBeHost(), config.getCatalogBePort(), serviceId, resourceInstanceId, artifactDetails.getUniqueId());
return updateDeploymentArtifact(artifactDetails, sdncModifierDetails, url);
}
-
- // delete
- public static RestResponse deleteArtifactFromResourceInstance(ArtifactDefinition artifactDefinition, User sdncModifierDetails, String resourceUid, String serviceId) throws IOException {
+ 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());
+ 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, ArtifactReqDetails artifactDetails, User sdncModifierDetails) throws IOException{
+ return deleteInformationalArtifactFromResource( resourceUid, artifactDetails.getUniqueId(), sdncModifierDetails);
}
-
- public static RestResponse deleteInformationalArtifactFromResource(String resourceUid, String artifactId, User sdncModifierDetails) throws IOException {
+
+ 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 {
+
+ 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());
+ 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 **************
+
+ //*************** RESOURCE INSTANCE **************
/**
* Add DCAE artifacts to resource instance.
- *
* @param artifactDetails
* @param sdncModifierDetails
* @param resourceInstanceId
@@ -409,132 +602,160 @@ public class ArtifactRestUtils extends BaseRestUtils {
*/
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());
+ 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 **************
-
+
+ //*************** 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){
- switch (componentType) {
-
- case RESOURCE: {
- url = String.format(Urls.UPDATE_OR_DELETE_ARTIFACT_OF_SERVICE, config.getCatalogBeHost(), config.getCatalogBePort(), component.getUniqueId(), artifactDetails.getUniqueId());
-
+ 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
+
+ default: {//dummy
assertTrue("failed on enum selection", false);
-
+
break;
}
}
+
+
+
Gson gson = new Gson();
String jsonBody = gson.toJson(artifactDetails);
- // System.out.println("ArtifactDetails: "+ jsonBody);
+// 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());
+// 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());
- // }
-
+ 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);
+// 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());
+// 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;
- // *************** PRIVATE **************
+ 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);
+// 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());
+// 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>();
@@ -554,62 +775,62 @@ public class ArtifactRestUtils extends BaseRestUtils {
}
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");
+
+ 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);
+// 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());
+// 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) {
+
+ 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 {
+
+ 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());
+
+ 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);
+
+ 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;
}
@@ -620,40 +841,47 @@ public class ArtifactRestUtils extends BaseRestUtils {
}
return checksum;
}
-
- public static String encodeUrlForDownload(String url) {
+
+ public static String encodeUrlForDownload(String url){
return url.replaceAll(" ", "%20");
}
-
- public static String getPartialUrlByArtifactName(ServiceReqDetails serviceDetails, String serviceVersion, String artifactName) {
+
+ 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 {
+
+ 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) {
+
+ 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 {
+
+ 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 {
+
+ 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 {
+
+ 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) {
+ if (isPayloadUpdate){
headersMap.put(HttpHeaderEnum.Content_MD5.getValue(), checksum);
}
@@ -662,22 +890,22 @@ public class ArtifactRestUtils extends BaseRestUtils {
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());
+ 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) {
+
+ 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) {
+
+ 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());
@@ -686,4 +914,7 @@ public class ArtifactRestUtils extends BaseRestUtils {
}
+
+
+
}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/AssetRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/AssetRestUtils.java
index 39001403b9..7272e345ae 100644
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/AssetRestUtils.java
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/AssetRestUtils.java
@@ -24,6 +24,7 @@ import static org.testng.AssertJUnit.assertNotNull;
import static org.testng.AssertJUnit.assertTrue;
import java.io.IOException;
+import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@@ -36,12 +37,14 @@ 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.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.ArtifactAssetStructure;
@@ -68,7 +71,8 @@ public class AssetRestUtils extends BaseRestUtils {
static Gson gson = new Gson();
static ObjectMapper objectMapper = new ObjectMapper();
- static Logger logger = LoggerFactory.getLogger(UserRestUtils.class.getName());
+ 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";
@@ -87,10 +91,35 @@ public class AssetRestUtils extends BaseRestUtils {
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);
+ 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 {
@@ -128,8 +157,8 @@ public class AssetRestUtils extends BaseRestUtils {
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);
+ logger.debug("Send GET request to get Resource Assets: {}",url);
+ logger.debug("Request headers: {}",headersMap);
RestResponse sendGetResourceAssets = http.httpSendGet(url, headersMap);
@@ -166,8 +195,8 @@ public class AssetRestUtils extends BaseRestUtils {
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);
+ logger.debug("Send GET request to get Resource Assets: {}",url);
+ logger.debug("Request headers: {}",headersMap);
RestResponse sendGetResourceAssets = http.httpSendGet(url, headersMap);
@@ -395,9 +424,9 @@ public class AssetRestUtils extends BaseRestUtils {
.equals(resourceInstanceAssetStructure.getResourceVersion()));
assertTrue(
"Expected RI asset resourceType is " + componentInstance.getOriginType() + " actual: "
- + resourceInstanceAssetStructure.getResourceType(),
+ + resourceInstanceAssetStructure.getResoucreType(),
componentInstance.getOriginType().toString()
- .equals(resourceInstanceAssetStructure.getResourceType()));
+ .equals(resourceInstanceAssetStructure.getResoucreType()));
assertTrue(
"Expected RI asset resourceUUID is " + componentInstance.getComponentUid() + " actual: "
+ resourceInstanceAssetStructure.getResourceUUID(),
@@ -507,4 +536,24 @@ public class AssetRestUtils extends BaseRestUtils {
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
index 9ffe5782e7..080583b901 100644
--- 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
@@ -210,8 +210,15 @@ public class BaseRestUtils extends BaseValidationUtils {
// 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;
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
index d9ae91b955..f5791efbb3 100644
--- 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
@@ -61,7 +61,8 @@ public class CategoryRestUtils extends BaseRestUtils {
// 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 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();
@@ -70,9 +71,11 @@ public class CategoryRestUtils extends BaseRestUtils {
return getCategotyResponse;
}
- public static RestResponse getAllCategoriesTowardsFe(User sdncModifierDetails, String categoryType) throws Exception {
+ 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 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();
@@ -82,12 +85,14 @@ public class CategoryRestUtils extends BaseRestUtils {
}
// Delete Category
- public static RestResponse deleteCategory(String categoryId, String psUserId, String categoryType) throws Exception {
+ 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);
+ String url = String.format(Urls.DELETE_CATEGORY, config.getCatalogBeHost(), config.getCatalogBePort(),
+ categoryType, categoryId);
url = url.replace("#", "%23"); // HEX
url = url.replace(" ", "%20"); // HEX
- RestResponse deleteCategoryResponse = sendDelete(url, psUserId);
+ RestResponse deleteCategoryResponse = sendDelete(url, userId);
return deleteCategoryResponse;
}
@@ -166,9 +171,13 @@ public class CategoryRestUtils extends BaseRestUtils {
return addCategoryResponse;
}
- public static RestResponse deleteCatergoryHttpCspAtuUidIsMissing(CategoryDefinition categoryDataDefinition, User sdncModifierDetails) throws Exception {
+ 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 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");
@@ -184,9 +193,11 @@ public class CategoryRestUtils extends BaseRestUtils {
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 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);
+ RestResponse addGroupingResponse = BaseRestUtils.sendPost(url, bodyJson, sdncModifierDetails.getUserId(),
+ acceptHeaderData);
return addGroupingResponse;
}
@@ -281,8 +292,7 @@ public class CategoryRestUtils extends BaseRestUtils {
}
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");
+ 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;
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
index 10587390f2..21332a253c 100644
--- 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
@@ -100,7 +100,24 @@ public class ComponentInstanceRestUtils extends BaseRestUtils {
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 {
@@ -130,8 +147,19 @@ public class ComponentInstanceRestUtils extends BaseRestUtils {
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;
+ }
- // TODO Tal CI for New API Multiple Instance Update
public static RestResponse updateMultipleComponentInstance(
List<ComponentInstanceReqDetails> componentInstanceReqDetailsList, User sdncModifierDetails,
String componentId, ComponentTypeEnum componentType) throws IOException {
@@ -161,7 +189,7 @@ public class ComponentInstanceRestUtils extends BaseRestUtils {
break;
}
String serviceBodyJson = gson.toJson(relation);
- String url = String.format(Urls.ASSOCIATE__RESOURCE_INSTANCE, config.getCatalogBeHost(),
+ String url = String.format(Urls.ASSOCIATE_RESOURCE_INSTANCE, config.getCatalogBeHost(),
config.getCatalogBePort(), componentType, componentId);
RestResponse associateInstance = sendPost(url, serviceBodyJson, sdncModifierDetails.getUserId(),
@@ -187,7 +215,7 @@ public class ComponentInstanceRestUtils extends BaseRestUtils {
break;
}
String serviceBodyJson = gson.toJson(relation);
- String url = String.format(Urls.DISSOCIATE__RESOURCE_INSTANCE, config.getCatalogBeHost(),
+ String url = String.format(Urls.DISSOCIATE_RESOURCE_INSTANCE, config.getCatalogBeHost(),
config.getCatalogBePort(), componentType, componentId);
RestResponse associateInstance = sendPut(url, serviceBodyJson, sdncModifierDetails.getUserId(),
@@ -236,7 +264,7 @@ public class ComponentInstanceRestUtils extends BaseRestUtils {
Config config = Utils.getConfig();
String resourceUid = ("{\"componentUid\":\"" + component.getUniqueId() + "\"}");
- String url = String.format(Urls.CHANGE__RESOURCE_INSTANCE_VERSION, config.getCatalogBeHost(),
+ 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(),
@@ -264,7 +292,7 @@ public class ComponentInstanceRestUtils extends BaseRestUtils {
ComponentTypeEnum componentType) throws IOException {
Config config = Utils.getConfig();
String resourceUid = ("{\"componentUid\":\"" + serviceUniqueId + "\"}");
- String url = String.format(Urls.CHANGE__RESOURCE_INSTANCE_VERSION, config.getCatalogBeHost(),
+ 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(),
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
index dcebe4afa8..8237819d7a 100644
--- 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
@@ -59,4 +59,12 @@ public class ComponentRestUtils extends BaseRestUtils {
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
index 1b93d8d778..71735d5a4a 100644
--- 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
@@ -45,7 +45,8 @@ public class ConsumerRestUtils extends BaseRestUtils {
private static Long expectedsLastupdatedtime;
private static Long expectedLastAuthenticationTime;
- public static RestResponse createConsumer(ConsumerDataDefinition consumerDataDefinition, User sdncModifierDetails) throws Exception {
+ 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());
@@ -63,14 +64,17 @@ public class ConsumerRestUtils extends BaseRestUtils {
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
+ .setConsumerDetailsLastupdatedtime(getConsumerDataObject.getConsumerDetailsLastupdatedtime());
+ consumerDataDefinition
+ .setConsumerLastAuthenticationTime(getConsumerDataObject.getConsumerLastAuthenticationTime());
consumerDataDefinition.setLastModfierAtuid(getConsumerDataObject.getLastModfierAtuid());
}
return createConsumerResponse;
}
- public static RestResponse createConsumerHttpCspAtuUidIsMissing(ConsumerDataDefinition consumerDataDefinition, User sdncModifierDetails) throws Exception {
+ 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());
@@ -86,17 +90,21 @@ public class ConsumerRestUtils extends BaseRestUtils {
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
+ .setConsumerDetailsLastupdatedtime(getConsumerDataObject.getConsumerDetailsLastupdatedtime());
+ consumerDataDefinition
+ .setConsumerLastAuthenticationTime(getConsumerDataObject.getConsumerLastAuthenticationTime());
consumerDataDefinition.setLastModfierAtuid(getConsumerDataObject.getLastModfierAtuid());
}
return createConsumerResponse;
}
- public static RestResponse deleteConsumerHttpCspAtuUidIsMissing(ConsumerDataDefinition consumerDataDefinition, User sdncModifierDetails) throws Exception {
+ 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 url = String.format(Urls.DELETE_CONSUMER, config.getCatalogBeHost(), config.getCatalogBePort(),
+ consumerDataDefinition.getConsumerName());
String userId = sdncModifierDetails.getUserId();
Map<String, String> headersMap = prepareHeadersMap(userId);
@@ -124,10 +132,12 @@ public class ConsumerRestUtils extends BaseRestUtils {
return null;
}
- public static RestResponse deleteConsumer(ConsumerDataDefinition consumerDataDefinition, User sdncModifierDetails) throws Exception {
+ 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 url = String.format(Urls.DELETE_CONSUMER, config.getCatalogBeHost(), config.getCatalogBePort(),
+ consumerDataDefinition.getConsumerName());
String userId = sdncModifierDetails.getUserId();
@@ -138,10 +148,12 @@ public class ConsumerRestUtils extends BaseRestUtils {
return deleteConsumerResponse;
}
- public static RestResponse getConsumer(ConsumerDataDefinition consumerDataDefinition, User sdncModifierDetails) throws Exception {
+ 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 url = String.format(Urls.GET_CONSUMER, config.getCatalogBeHost(), config.getCatalogBePort(),
+ consumerDataDefinition.getConsumerName());
String userId = sdncModifierDetails.getUserId();
@@ -152,7 +164,8 @@ public class ConsumerRestUtils extends BaseRestUtils {
return getConsumerResponse;
}
- public static void validateConsumerReqVsResp(ConsumerDataDefinition consumerDefinition, ConsumerDataDefinition getConsumerDataObject) {
+ public static void validateConsumerReqVsResp(ConsumerDataDefinition consumerDefinition,
+ ConsumerDataDefinition getConsumerDataObject) {
String expected;
@@ -169,10 +182,12 @@ public class ConsumerRestUtils extends BaseRestUtils {
assertEquals("consumer Salt - ", expected, getConsumerDataObject.getConsumerSalt());
expectedsLastupdatedtime = consumerDefinition.getConsumerDetailsLastupdatedtime();
- assertEquals("consumer Last updated time - ", expectedsLastupdatedtime, getConsumerDataObject.getConsumerDetailsLastupdatedtime());
+ assertEquals("consumer Last updated time - ", expectedsLastupdatedtime,
+ getConsumerDataObject.getConsumerDetailsLastupdatedtime());
expectedLastAuthenticationTime = consumerDefinition.getConsumerLastAuthenticationTime();
- assertEquals("consumer Last authentication time - ", expectedLastAuthenticationTime, getConsumerDataObject.getConsumerLastAuthenticationTime());
+ assertEquals("consumer Last authentication time - ", expectedLastAuthenticationTime,
+ getConsumerDataObject.getConsumerLastAuthenticationTime());
}
///// New
@@ -190,17 +205,41 @@ public class ConsumerRestUtils extends BaseRestUtils {
}
/*
- * 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 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); }
+ * 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
index a71711dde6..ec40c13894 100644
--- 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
@@ -42,8 +42,8 @@ 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 Logger logger = LoggerFactory.getLogger(UserRestUtils.class.getName());
static String contentTypeHeaderData = "application/json";
static String acceptHeaderDate = "application/json";
static String ecompUsername = "12345";
@@ -69,9 +69,9 @@ public class EcompUserRestUtils extends BaseRestUtils {
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);
+ 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);
@@ -95,9 +95,9 @@ public class EcompUserRestUtils extends BaseRestUtils {
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);
+ 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);
@@ -119,8 +119,8 @@ public class EcompUserRestUtils extends BaseRestUtils {
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);
+ logger.debug("Send GET request to get user: {}",url);
+ logger.debug("User headers: {}",headersMap);
RestResponse sendGetUserRequest = http.httpSendGet(url, headersMap);
@@ -139,8 +139,8 @@ public class EcompUserRestUtils extends BaseRestUtils {
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);
+ logger.debug("Send POST request to get all users: {}",url);
+ logger.debug("User headers: {}",headersMap);
RestResponse sendGetAllUsersRequest = http.httpSendGet(url, headersMap);
@@ -160,8 +160,8 @@ public class EcompUserRestUtils extends BaseRestUtils {
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);
+ logger.debug("Send GET request to get all available roles: {}",url);
+ logger.debug("User headers: {}",headersMap);
RestResponse sendUpdateUserRequest = http.httpSendGet(url, headersMap);
@@ -186,9 +186,9 @@ public class EcompUserRestUtils extends BaseRestUtils {
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);
+ 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);
@@ -211,8 +211,8 @@ public class EcompUserRestUtils extends BaseRestUtils {
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);
+ logger.debug("Send GET request to get user roles: {}",url);
+ logger.debug("User headers: {}",headersMap);
RestResponse sendGetUserRolesRequest = http.httpSendGet(url, headersMap);
@@ -239,7 +239,6 @@ public class EcompUserRestUtils extends BaseRestUtils {
* System.out.println("\n-----------------------------\n Testing pushUser");
* System.out.println(pushUser(ecompUser));
* System.out.println("\n-----------------------------\n Testing editUser");
- * // System.out.println(editUser("tt0001", ecompUser));
* System.out.println("\n-----------------------------\n Testing getUser");
* // System.out.println(getUser(ecompUser.getLoginId())); System.out.
* println("\n-----------------------------\n Testing getAllUsers"); //
@@ -247,9 +246,7 @@ public class EcompUserRestUtils extends BaseRestUtils {
* println("\n-----------------------------\n Testing getAllAvailableRoles"
* ); // System.out.println(getAllAvailableRoles().toString()); System.out.
* println("\n-----------------------------\n Testing pushUserRoles"); //
- * System.out.println(pushUserRoles("tt0001", listOfRoles)); System.out.
* println("\n-----------------------------\n Testing getUserRoles"); //
- * System.out.println(getUserRoles("tt0001")); } catch (IOException e) { //
* TODO Auto-generated catch block e.printStackTrace(); } }
*/
}
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
index 3ce48962fd..9755ff2d91 100644
--- 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
@@ -34,6 +34,7 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.Map.Entry;
import java.util.Properties;
import org.apache.commons.io.IOUtils;
@@ -75,15 +76,19 @@ public class ImportRestUtils extends BaseRestUtils {
}
@SuppressWarnings("unused")
- private static Integer importNormativeResource(NormativeTypesEnum resource, UserRoleEnum userRole) throws IOException {
+ 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));
+ 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());
+ String url = String.format(Urls.IMPORT_RESOURCE_NORMATIVE, config.getCatalogBeHost(),
+ config.getCatalogBePort());
CloseableHttpClient client = HttpClients.createDefault();
try {
@@ -98,16 +103,61 @@ public class ImportRestUtils extends BaseRestUtils {
}
}
-
- public static RestResponse importResourceByName(ResourceReqDetails resourceDetails, User importer) throws Exception {
+
+ /*
+ * 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));
+ 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());
+ String url = String.format(Urls.IMPORT_RESOURCE_NORMATIVE, config.getCatalogBeHost(),
+ config.getCatalogBePort());
CloseableHttpClient client = HttpClients.createDefault();
try {
@@ -157,7 +207,8 @@ public class ImportRestUtils extends BaseRestUtils {
MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
mpBuilder.addPart("resourceZip", new FileBody(getTestZipFile(resourceName)));
- mpBuilder.addPart("resourceMetadata", new StringBody(getTestJsonStringOfFile(resourceName, resourceName + ".json"), ContentType.APPLICATION_JSON));
+ 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>();
@@ -166,30 +217,37 @@ public class ImportRestUtils extends BaseRestUtils {
return HttpRequest.sendHttpPostWithEntity(requestEntity, url, headers);
}
- public static RestResponse importNormativeResourceByName(String resourceName, UserRoleEnum userRole) throws IOException {
+ 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));
+ 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());
+ 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 {
+ 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));
+ 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());
+ String url = String.format(Urls.IMPORT_RESOURCE_NORMATIVE, config.getCatalogBeHost(),
+ config.getCatalogBePort());
CloseableHttpClient client = HttpClients.createDefault();
try {
@@ -223,16 +281,20 @@ public class ImportRestUtils extends BaseRestUtils {
}
}
- 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");
+ 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 {
+ public static void validateImportTestTypesResp(ImportTestTypesEnum currResource, RestResponse restResponse)
+ throws IOException, JSONException {
// assertTrue( status != ResourceUtils.STATUS_CODE_IMPORT_SUCCESS );
@@ -243,9 +305,11 @@ public class ImportRestUtils extends BaseRestUtils {
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>());
+ List<String> variables = (currResource.getErrorParams() != null ? currResource.getErrorParams()
+ : new ArrayList<String>());
if (restResponse.getErrorCode() != 200) {
- ErrorValidationUtils.checkBodyResponseOnError(currResource.getActionStatus().name(), variables, restResponse.getResponse());
+ ErrorValidationUtils.checkBodyResponseOnError(currResource.getActionStatus().name(), variables,
+ restResponse.getResponse());
}
}
@@ -253,7 +317,8 @@ public class ImportRestUtils extends BaseRestUtils {
// 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);
+ 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;
@@ -262,7 +327,8 @@ public class ImportRestUtils extends BaseRestUtils {
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");
+ java.nio.file.Path filePath = FileSystems.getDefault().getPath(sourceDir + File.separator + elementName,
+ "normative-types-new-" + elementName + ".zip");
return filePath.toFile();
}
@@ -289,18 +355,11 @@ public class ImportRestUtils extends BaseRestUtils {
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 url = String.format(Urls.GET_CSAR_USING_SIMULATOR, config.getCatalogBeHost(), config.getCatalogBePort(),
+ csarUid);
String userId = sdncModifierDetails.getUserId();
-
Map<String, String> headersMap = prepareHeadersMap(userId);
-
- // Gson gson = new Gson();
- // String userBodyJson = gson.toJson(resourceDetails);
- HttpRequest http = new HttpRequest();
- // System.out.println(url);
- // System.out.println(userBodyJson);
-
HttpRestClient httpRestClient = new HttpRestClient();
for (Map.Entry<String, String> mapEntry : headersMap.entrySet()) {
@@ -318,11 +377,13 @@ public class ImportRestUtils extends BaseRestUtils {
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");
+ 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 {
+ public static RestResponse importNewGroupTypeByName(String groupTypeName, UserRoleEnum userRole)
+ throws IOException {
Config config = Utils.getConfig();
MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
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
index 34651c1b7a..a5b8c7a4bf 100644
--- 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
@@ -99,7 +99,40 @@ public class LifecycleRestUtils extends BaseRestUtils {
}
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 {
{
@@ -302,20 +335,37 @@ public class LifecycleRestUtils extends BaseRestUtils {
public static RestResponse changeDistributionStatus(ServiceReqDetails serviceDetails, String version, User user,
String userRemarks, DistributionStatusEnum reqDistributionStatus) throws Exception {
String uniqueId = serviceDetails.getUniqueId();
- 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;
+ 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;
}
@@ -349,9 +399,9 @@ public class LifecycleRestUtils extends BaseRestUtils {
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);
+ 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
index 8e617ed75c..ebc80ae537 100644
--- 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
@@ -22,6 +22,8 @@ package org.openecomp.sdc.ci.tests.utils.rest;
import java.io.IOException;
+import com.google.gson.Gson;
+
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.model.LifecycleStateEnum;
import org.openecomp.sdc.be.model.Product;
@@ -30,13 +32,13 @@ 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());
@@ -46,8 +48,8 @@ public class ProductRestUtils extends BaseRestUtils {
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);
+ 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) {
@@ -76,8 +78,8 @@ public class ProductRestUtils extends BaseRestUtils {
product.getUniqueId());
String serviceBodyJson = gson.toJson(product);
- logger.debug("Send POST request to create service: {}", url);
- logger.debug("Service body: {}", serviceBodyJson);
+ 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) {
@@ -116,11 +118,20 @@ public class ProductRestUtils extends BaseRestUtils {
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);
+ logger.debug("Send GET request to get product: {}",url);
return sendGet(url, userId);
}
@@ -128,7 +139,7 @@ public class ProductRestUtils extends BaseRestUtils {
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);
+ logger.debug("Send GET request to get user followed page: {}",url);
return sendGet(url, userId);
}
@@ -164,7 +175,7 @@ public class ProductRestUtils extends BaseRestUtils {
ComponentTypeEnum componentType) throws IOException {
Config config = Utils.getConfig();
String resourceUid = ("{\"componentUid\":\"" + serviceUniqueId + "\"}");
- String url = String.format(Urls.CHANGE__RESOURCE_INSTANCE_VERSION, config.getCatalogBeHost(),
+ 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(),
@@ -178,7 +189,7 @@ public class ProductRestUtils extends BaseRestUtils {
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);
+ 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
index 56ff5ec12b..a8661830ee 100644
--- 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
@@ -46,70 +46,57 @@ public class PropertyRestUtils extends BaseRestUtils {
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);
+ 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 {
+ 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);
+ 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);
+ 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);
+ 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) {
+ public static ComponentInstanceProperty getPropFromListByPropNameAndType(List<ComponentInstanceProperty> propList, String propNameToUpdate, String propTypeToUpdate) {
for (ComponentInstanceProperty componentInstanceProperty : propList) {
- if (componentInstanceProperty.getName().equals(propNameToUpdate)
- && componentInstanceProperty.getType().equals(propTypeToUpdate)) {
+ 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) {
+ 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())) {
+ 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) {
+ 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)) {
+ if (componentInstanceProperty.getUniqueId().equals(propId) && componentInstanceProperty.getPath().equals(path)) {
return componentInstanceProperty;
}
} else {
@@ -121,12 +108,9 @@ public class PropertyRestUtils extends BaseRestUtils {
return null;
}
- public static void comparePropertyLists(List<ComponentInstanceProperty> expectedList,
- List<ComponentInstanceProperty> actualList, Boolean isUpdate) {
+ 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());
+ 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) {
@@ -138,47 +122,31 @@ public class PropertyRestUtils extends BaseRestUtils {
}
// System.out.println("expected: " + expectedList + ", actual: " +
// actualList);
- logger.debug("expected: {}, actual: {}", expectedList, 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) {
+ 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 (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);
+ assertTrue("expected defaulValue is: " + defaulValue + " ,actual: " + actualCompInstProp.getDefaultValue(), actualCompInstProp.getDefaultValue() == defaulValue);
} else {
- assertTrue(
- "expected defaulValue is: " + defaulValue + " ,actual: " + actualCompInstProp.getDefaultValue(),
- actualCompInstProp.getDefaultValue().equals(defaulValue));
+ 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(),
+ 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(),
+ 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(),
+ 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());
@@ -188,16 +156,14 @@ public class PropertyRestUtils extends BaseRestUtils {
return false;
}
- public static List<ComponentInstanceProperty> addResourcePropertiesToList(Resource resource,
- List<ComponentInstanceProperty> listToFill) {
+ 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) {
+ public static List<ComponentInstanceProperty> addComponentInstPropertiesToList(Component component, List<ComponentInstanceProperty> listToFill, String componentId) {
if (componentId != null) {
List<ComponentInstanceProperty> list = component.getComponentInstancesProperties().get(componentId);
@@ -209,13 +175,10 @@ public class PropertyRestUtils extends BaseRestUtils {
listToFill.add(componentInstanceProperty);
}
} else {
- Map<String, List<ComponentInstanceProperty>> componentInstancesProperties = component
- .getComponentInstancesProperties();
- for (Map.Entry<String, List<ComponentInstanceProperty>> componentInstanceProperties : componentInstancesProperties
- .entrySet()) {
+ 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 componentInstanceProperty = new ComponentInstanceProperty(prop, null, null);
componentInstanceProperty.setPath(prop.getPath());
componentInstanceProperty.setValueUniqueUid(prop.getValueUniqueUid());
componentInstanceProperty.setValue(prop.getValue());
@@ -232,22 +195,18 @@ public class PropertyRestUtils extends BaseRestUtils {
return listToFill;
}
- public static ComponentInstanceProperty getCompPropInstListByInstIdAndPropName(Component component,
- ComponentInstance componentInstanceDetails, String name, String type) {
- List<ComponentInstanceProperty> propList = component.getComponentInstancesProperties()
- .get(componentInstanceDetails.getUniqueId());
+ 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) {
+ 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 propDetailsToRemove = PropertyRestUtils.getPropFromListByPropNameAndType(expectedPropertyList, propertyDefinition.getName(), propertyDefinition.getType());
ComponentInstanceProperty propDetailsToAdd = propDetailsToRemove;
propDetailsToAdd.setPath(path);
expectedPropertyList.remove(propDetailsToRemove);
@@ -255,24 +214,19 @@ public class PropertyRestUtils extends BaseRestUtils {
}
}
- private static void updatePropertyListWithPathParameterOnCompInst(Service service, List<String> path,
- List<ComponentInstanceProperty> expectedPropertyList) {
+ 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));
+ servicePropertyList = PropertyRestUtils.addComponentInstPropertiesToList(service, servicePropertyList, path.get(0));
for (ComponentInstanceProperty serviceCompInstProperty : servicePropertyList) {
- ComponentInstanceProperty propDetailsToRemove = PropertyRestUtils.getPropFromListByPropNameTypeAndPath(
- expectedPropertyList, serviceCompInstProperty.getName(), serviceCompInstProperty.getType(),
- serviceCompInstProperty.getPath());
+ 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() != null && !propDetailsToAdd.getPath().get(0).contains(service.getUniqueId())) {
if (!propDetailsToAdd.getPath().containsAll(tempPathList)) {
tempPathList.addAll(propDetailsToAdd.getPath());
}
@@ -283,8 +237,7 @@ public class PropertyRestUtils extends BaseRestUtils {
}
}
- public static void updatePropertyListWithPathOnResource(ComponentInstance componentInstDetails, Resource resource,
- List<ComponentInstanceProperty> list, Component container) {
+ 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();
@@ -301,8 +254,7 @@ public class PropertyRestUtils extends BaseRestUtils {
updatePropertyListWithPathParameter(resource, path, list);
}
- public static void updatePropertyListWithPathOnComponentInstance(ComponentInstance componentInstDetails,
- Service service, List<ComponentInstanceProperty> 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
index 16ffd2f9e2..6e4a6a8018 100644
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResourceRestUtils.java
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResourceRestUtils.java
@@ -53,20 +53,21 @@ 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;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class ResourceRestUtils extends BaseRestUtils {
private static Logger logger = LoggerFactory.getLogger(ResourceRestUtils.class.getName());
// ****** CREATE *******
- public static RestResponse createResource(ResourceReqDetails resourceDetails, User sdncModifierDetails) throws Exception {
+ 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());
@@ -87,9 +88,11 @@ public class ResourceRestUtils extends BaseRestUtils {
resourceDetails.setUUID(ResponseParser.getUuidFromResponse(createResourceResponse));
resourceDetails.setVersion(ResponseParser.getVersionFromResponse(createResourceResponse));
resourceDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(createResourceResponse));
- String lastUpdaterUserId = ResponseParser.getValueFromJsonResponse(createResourceResponse.getResponse(), "lastUpdaterUserId");
+ String lastUpdaterUserId = ResponseParser.getValueFromJsonResponse(createResourceResponse.getResponse(),
+ "lastUpdaterUserId");
resourceDetails.setLastUpdaterUserId(lastUpdaterUserId);
- String lastUpdaterFullName = ResponseParser.getValueFromJsonResponse(createResourceResponse.getResponse(), "lastUpdaterFullName");
+ String lastUpdaterFullName = ResponseParser.getValueFromJsonResponse(createResourceResponse.getResponse(),
+ "lastUpdaterFullName");
resourceDetails.setLastUpdaterFullName(lastUpdaterFullName);
// Creator details never change after component is created - Ella,
// 12/1/2016
@@ -100,7 +103,8 @@ public class ResourceRestUtils extends BaseRestUtils {
}
- public static RestResponse createImportResource(ImportReqDetails importReqDetails, User sdncModifierDetails, Map<String, String> additionalHeaders) throws JSONException, IOException {
+ 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());
@@ -116,7 +120,8 @@ public class ResourceRestUtils extends BaseRestUtils {
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);
@@ -127,7 +132,8 @@ public class ResourceRestUtils extends BaseRestUtils {
// 12/1/2016
importReqDetails.setCreatorUserId(userId);
importReqDetails.setCreatorFullName(sdncModifierDetails.getFullName());
- importReqDetails.setToscaResourceName(ResponseParser.getToscaResourceNameFromResponse(createResourceResponse));
+ importReqDetails
+ .setToscaResourceName(ResponseParser.getToscaResourceNameFromResponse(createResourceResponse));
importReqDetails.setDerivedList(ResponseParser.getDerivedListFromJson(createResourceResponse));
}
return createResourceResponse;
@@ -135,11 +141,13 @@ public class ResourceRestUtils extends BaseRestUtils {
}
// ***** DELETE ****
- public static RestResponse deleteResource(ResourceReqDetails resourceDetails, User sdncModifierDetails, String version) throws IOException {
+ 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);
+ 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;
@@ -150,7 +158,8 @@ public class ResourceRestUtils extends BaseRestUtils {
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);
+ String url = String.format(Urls.DELETE_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(),
+ resourceId);
RestResponse sendDelete = sendDelete(url, userId);
return sendDelete;
@@ -160,7 +169,8 @@ public class ResourceRestUtils extends BaseRestUtils {
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);
+ String url = String.format(Urls.DELETE_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(),
+ resourceId);
RestResponse sendDelete = sendDelete(url, userId);
deleteMarkedResources(userId);
@@ -176,9 +186,11 @@ public class ResourceRestUtils extends BaseRestUtils {
sendDelete(url, userId);
}
- public static RestResponse deleteResourceByNameAndVersion(User sdncModifierDetails, String resourceName, String resourceVersion) throws IOException {
+ 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);
+ 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());
@@ -186,13 +198,17 @@ public class ResourceRestUtils extends BaseRestUtils {
return sendDelete;
}
- public static Boolean deleteResourceByNameAndVersion(String resourceName, String resourceVersion) throws IOException {
- RestResponse deleteResponse = ResourceRestUtils.deleteResourceByNameAndVersion(ElementFactory.getDefaultUser(UserRoleEnum.ADMIN), resourceName, resourceVersion);
+ 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());
+ public static Boolean removeResource(String resourceId)
+ throws FileNotFoundException, IOException, ClientProtocolException {
+ RestResponse response = deleteResource(resourceId,
+ ElementFactory.getDefaultUser(UserRoleEnum.ADMIN).getUserId());
return checkErrorCode(response);
}
@@ -204,30 +220,38 @@ public class ResourceRestUtils extends BaseRestUtils {
return sendGet(url, sdncModifierDetails.getUserId());
}
- public static RestResponse getModule(User sdncModifierDetails, String componentId, String moduleId) throws IOException {
+ 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);
+ 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 {
+ 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);
+ 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 {
+ 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());
+ String url = String.format(Urls.GET_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(),
+ resourceDetails.getUniqueId());
return sendGet(url, sdncModifierDetails.getUserId());
}
- public static RestResponse getResourceByNameAndVersion(String userId, String resourceName, String resourceVersion) throws IOException {
+ 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);
+ String url = String.format(Urls.GET_RESOURCE_BY_NAME_AND_VERSION, config.getCatalogBeHost(),
+ config.getCatalogBePort(), resourceName, resourceVersion);
return sendGet(url, userId);
}
@@ -240,19 +264,47 @@ public class ResourceRestUtils extends BaseRestUtils {
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 {
+ 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());
+ String url = String.format(Urls.GET_RESOURCE_lATEST_VERSION, config.getCatalogBeHost(),
+ config.getCatalogBePort());
return sendGet(url, sdncModifierDetails.getUserId());
@@ -261,7 +313,8 @@ public class ResourceRestUtils extends BaseRestUtils {
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);
+ 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);
@@ -269,7 +322,7 @@ public class ResourceRestUtils extends BaseRestUtils {
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);
+ logger.debug("Send PUT request to get all categories (should be 405): {}",url);
return http.httpSendByMethod(url, "PUT", null, headersMap);
}
@@ -283,7 +336,6 @@ public class ResourceRestUtils extends BaseRestUtils {
headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderData);
- // logger.debug("Send GET request to get all tags: {}", url);
return http.httpSendGet(url, headersMap);
}
@@ -299,9 +351,7 @@ public class ResourceRestUtils extends BaseRestUtils {
headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json");
headersMap.put(HttpHeaderEnum.USER_ID.getValue(), "cs0008");
- // logger.debug("Send GET request to get all property scopes: {}", url);
return http.httpSendGet(url, headersMap);
-
}
public static RestResponse getAllArtifactTypesTowardsCatalogBe() throws IOException {
@@ -316,7 +366,6 @@ public class ResourceRestUtils extends BaseRestUtils {
headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json");
headersMap.put(HttpHeaderEnum.USER_ID.getValue(), "cs0008");
- // logger.debug("Send GET request to get all property scopes: {}", url);
return http.httpSendGet(url, headersMap);
}
@@ -332,7 +381,6 @@ public class ResourceRestUtils extends BaseRestUtils {
headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json");
headersMap.put(HttpHeaderEnum.USER_ID.getValue(), "cs0008");
- // logger.debug("Send GET request to get all property scopes: {}", url);
return http.httpSendGet(url, headersMap);
}
@@ -340,21 +388,24 @@ public class ResourceRestUtils extends BaseRestUtils {
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);
+ 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);
+ 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 {
+ 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 url = String.format(Urls.UPDATE_RESOURCE_METADATA, config.getCatalogBeHost(), config.getCatalogBePort(),
+ uniqueId);
String ContentTypeString = String.format("%s;%s", contentTypeHeaderData, encoding);
@@ -370,9 +421,11 @@ public class ResourceRestUtils extends BaseRestUtils {
return updateResourceResponse;
}
- public static RestResponse updateResourceTEST(Resource resource, User sdncModifierDetails, String uniqueId, String encoding) throws Exception {
+ 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 url = String.format(Urls.UPDATE_RESOURCE_METADATA, config.getCatalogBeHost(), config.getCatalogBePort(),
+ uniqueId);
String ContentTypeString = String.format("%s;%s", contentTypeHeaderData, encoding);
@@ -381,25 +434,43 @@ public class ResourceRestUtils extends BaseRestUtils {
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 {
+ 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 {
+ 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 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 {
+ 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);
+ String url = String.format(Urls.UPDATE_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(),
+ resourceId);
Map<String, String> headersMap = prepareHeadersMap(userId);
@@ -413,9 +484,11 @@ public class ResourceRestUtils extends BaseRestUtils {
resourceDetails.setUUID(ResponseParser.getUuidFromResponse(updateResourceResponse));
resourceDetails.setVersion(ResponseParser.getVersionFromResponse(updateResourceResponse));
resourceDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(updateResourceResponse));
- String lastUpdaterUserId = ResponseParser.getValueFromJsonResponse(updateResourceResponse.getResponse(), "lastUpdaterUserId");
+ String lastUpdaterUserId = ResponseParser.getValueFromJsonResponse(updateResourceResponse.getResponse(),
+ "lastUpdaterUserId");
resourceDetails.setLastUpdaterUserId(lastUpdaterUserId);
- String lastUpdaterFullName = ResponseParser.getValueFromJsonResponse(updateResourceResponse.getResponse(), "lastUpdaterFullName");
+ String lastUpdaterFullName = ResponseParser.getValueFromJsonResponse(updateResourceResponse.getResponse(),
+ "lastUpdaterFullName");
resourceDetails.setLastUpdaterFullName(lastUpdaterFullName);
resourceDetails.setCreatorUserId(userId);
resourceDetails.setCreatorFullName(sdncModifierDetails.getFullName());
@@ -423,21 +496,26 @@ public class ResourceRestUtils extends BaseRestUtils {
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);
+ 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 {
+ 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());
+ String url = String.format(Urls.ASSOCIATE_RESOURCE_INSTANCE, config.getCatalogBeHost(),
+ config.getCatalogBePort(), componentType, component.getUniqueId());
return sendPost(url, bodyJson, sdncModifierDetails.getUserId(), null);
}
@@ -476,11 +554,14 @@ public class ResourceRestUtils extends BaseRestUtils {
// =======================================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 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 {
+ 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();
@@ -495,12 +576,15 @@ public class ResourceRestUtils extends BaseRestUtils {
relationshipInstData.setRequirementOwnerId(requirementDefinitionFrom.getOwnerId());
relationshipInstData.setRequirementId(requirementDefinitionFrom.getUniqueId());
- JSONObject assocBody = assocBuilder(relationshipInstData, capabilityDefinitionTo, requirementDefinitionFrom, toNode, fromNode);
+ 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) {
+ private static JSONObject assocBuilder(RelationshipInstData relationshipInstData,
+ CapabilityDefinition capabilityDefinitionTo, RequirementDefinition requirementDefinitionFrom, String toNode,
+ String fromNode) {
String type = capabilityDefinitionTo.getType();
String requirement = requirementDefinitionFrom.getName();
@@ -529,7 +613,8 @@ public class ResourceRestUtils extends BaseRestUtils {
}
- private static CapabilityDefinition getCapabilityDefinitionByOwnerId(List<CapabilityDefinition> capabilityDefinitionList, String ownerId) {
+ private static CapabilityDefinition getCapabilityDefinitionByOwnerId(
+ List<CapabilityDefinition> capabilityDefinitionList, String ownerId) {
for (CapabilityDefinition capabilityDefinition : capabilityDefinitionList) {
if (capabilityDefinition.getOwnerId().equals(ownerId)) {
@@ -539,7 +624,8 @@ public class ResourceRestUtils extends BaseRestUtils {
return null;
}
- private static RequirementDefinition getRequirementDefinitionByOwnerId(List<RequirementDefinition> requirementDefinitionList, String ownerId) {
+ private static RequirementDefinition getRequirementDefinitionByOwnerId(
+ List<RequirementDefinition> requirementDefinitionList, String ownerId) {
for (RequirementDefinition requirementDefinition : requirementDefinitionList) {
if (requirementDefinition.getOwnerId().equals(ownerId)) {
@@ -562,14 +648,18 @@ public class ResourceRestUtils extends BaseRestUtils {
return name;
}
- public static Resource convertResourceGetResponseToJavaObject(ResourceReqDetails resourceDetails) throws IOException {
- RestResponse response = ResourceRestUtils.getResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ 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 RestResponse changeResourceInstanceVersion(String containerUniqueId, String instanceToReplaceUniqueId,
+ String newResourceUniqueId, User sdncModifierDetails, ComponentTypeEnum componentType) throws IOException {
+ return ProductRestUtils.changeServiceInstanceVersion(containerUniqueId, instanceToReplaceUniqueId,
+ newResourceUniqueId, sdncModifierDetails, componentType);
}
}
diff --git a/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
new file mode 100644
index 0000000000..10f573cf0e
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResourceRestUtilsExternalAPI.java
@@ -0,0 +1,64 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.utils.rest;
+
+import java.util.Map;
+
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.api.Urls;
+import org.openecomp.sdc.ci.tests.config.Config;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceExternalReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.Utils;
+import org.openecomp.sdc.common.util.GeneralUtility;
+
+import com.google.gson.Gson;
+
+public class ResourceRestUtilsExternalAPI extends BaseRestUtils {
+
+ public static RestResponse createResource(ResourceExternalReqDetails resourceDetails, User sdncModifierDetails)
+ throws Exception {
+
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.POST_EXTERNAL_API_CREATE_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort());
+
+ String userId = sdncModifierDetails.getUserId();
+ Map<String, String> headersMap = prepareHeadersMap(userId);
+
+ Gson gson = new Gson();
+ String userBodyJson = gson.toJson(resourceDetails);
+ String calculateMD5 = GeneralUtility.calculateMD5ByString(userBodyJson);
+ headersMap.put(HttpHeaderEnum.Content_MD5.getValue(), calculateMD5);
+ headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), authorizationHeader);
+ headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci");
+ headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId());
+
+ HttpRequest http = new HttpRequest();
+ RestResponse createResourceResponse = http.httpSendPost(url, userBodyJson, headersMap);
+
+ return createResourceResponse;
+ }
+
+
+}
diff --git a/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
index dfcb9c2736..39f2c04b55 100644
--- 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
@@ -21,6 +21,7 @@
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;
@@ -30,8 +31,10 @@ import java.util.Map;
import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
+import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.Version;
import org.codehaus.jackson.map.JsonDeserializer;
+import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.module.SimpleModule;
import org.json.JSONArray;
@@ -50,7 +53,9 @@ 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;
@@ -59,7 +64,34 @@ 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";
@@ -183,30 +215,6 @@ public class ResponseParser {
return propertyDefinition;
}
- // public static ResourceInstanceReqDetails
- // convertResourceInstanceResponseToJavaObject(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);
- // ResourceInstanceReqDetails resourceInstanceReqDetails = null;
- // try {
- // resourceInstanceReqDetails = mapper.readValue(response,
- // ResourceInstanceReqDetails.class);
- // logger.debug(resourceInstanceReqDetails.toString());
- // } catch (IOException e) {
- // // TODO Auto-generated catch block
- // e.printStackTrace();
- // }
- //
- // return resourceInstanceReqDetails;
- // }
public static String toJson(Object object) {
Gson gson = new Gson();
return gson.toJson(object);
@@ -231,17 +239,7 @@ public class ResponseParser {
public static ArtifactReqDetails convertArtifactReqDetailsToJavaObject(String response) {
ArtifactReqDetails artifactReqDetails = null;
- // try {
- //
- // artifactDefinition = mapper.readValue(response,
- // ArtifactReqDetails.class);
- // logger.debug(artifactDefinition.toString());
- // } catch (IOException e) {
- // // TODO Auto-generated catch block
- // e.printStackTrace();
- // }
- //
- // return artifactDefinition;
+
Gson gson = new Gson();
artifactReqDetails = gson.fromJson(response, ArtifactReqDetails.class);
return artifactReqDetails;
@@ -283,17 +281,7 @@ public class ResponseParser {
ArtifactDefinition artifactDefinition) {
ArtifactReqDetails artifactReqDetails = null;
- // try {
- //
- // artifactDefinition = mapper.readValue(response,
- // ArtifactReqDetails.class);
- // logger.debug(artifactDefinition.toString());
- // } catch (IOException e) {
- // // TODO Auto-generated catch block
- // e.printStackTrace();
- // }
- //
- // return artifactDefinition;
+
Gson gson = new Gson();
String artDef = gson.toJson(artifactDefinition);
artifactReqDetails = gson.fromJson(artDef, ArtifactReqDetails.class);
@@ -491,9 +479,11 @@ public class ResponseParser {
}
}
- public static Map<String, ArrayList<Component>> convertCatalogResponseToJavaObject(String response) {
+ public static Map<String, List<Component>> convertCatalogResponseToJavaObject(String response) {
- Map<String, ArrayList<Component>> map = new HashMap<String, ArrayList<Component>>();
+ // 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();
@@ -538,4 +528,39 @@ public class ResponseParser {
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
index d62c74c3d2..0055dbd982 100644
--- 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
@@ -27,14 +27,17 @@ 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;
@@ -49,9 +52,13 @@ public class ServiceRestUtils extends BaseRestUtils {
private static Gson gson = new Gson();
- public static RestResponse deleteService(String serviceName, String version, User sdncModifierDetails) throws IOException {
+ 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 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);
@@ -59,8 +66,10 @@ 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;
@@ -78,8 +87,8 @@ public class ServiceRestUtils extends BaseRestUtils {
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);
+ 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) {
@@ -101,8 +110,8 @@ public class ServiceRestUtils extends BaseRestUtils {
service.getUniqueId());
String serviceBodyJson = gson.toJson(service);
- logger.debug("Send PUT request to create service: {}", url);
- logger.debug("Service body: {}", serviceBodyJson);
+ 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) {
@@ -113,6 +122,13 @@ public class ServiceRestUtils extends BaseRestUtils {
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 {
@@ -141,8 +157,8 @@ public class ServiceRestUtils extends BaseRestUtils {
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);
+ logger.debug("Send GET request to create service: {}",url);
+ logger.debug("Service headers: {}",headersMap);
RestResponse sendGetServerRequest = http.httpSendGet(url, headersMap);
return sendGetServerRequest;
@@ -208,9 +224,9 @@ public class ServiceRestUtils extends BaseRestUtils {
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);
+ 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;
@@ -254,9 +270,16 @@ public class ServiceRestUtils extends BaseRestUtils {
JSONObject jsonResp = (JSONObject) JSONValue.parse(json);
JSONArray servicesArray = (JSONArray) jsonResp.get("services");
- logger.debug("services = {}", servicesArray);
+ 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
index a8f39b9ad8..6c6a66d863 100644
--- 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
@@ -65,9 +65,9 @@ public class UserRestUtils extends BaseRestUtils {
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);
+ 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;
@@ -119,7 +119,7 @@ public class UserRestUtils extends BaseRestUtils {
Gson gson = new Gson();
String userBodyJson = gson.toJson(user);
- logger.debug("userBodyJson: {}", userBodyJson);
+ logger.debug("userBodyJson: {}",userBodyJson);
HttpRequest http = new HttpRequest();
String url = String.format(Urls.UPDATE_USER, config.getCatalogBeHost(), config.getCatalogBePort(),
sdncModifierDetails.getUserId());
@@ -141,7 +141,7 @@ public class UserRestUtils extends BaseRestUtils {
Gson gson = new Gson();
String userBodyJson = gson.toJson(sdncUserDetails);
- logger.debug("userBodyJson: {}", userBodyJson);
+ logger.debug("userBodyJson: {}",userBodyJson);
HttpRequest http = new HttpRequest();
String url = String.format(Urls.UPDATE_USER_ROLE, config.getCatalogBeHost(), config.getCatalogBePort(),
userIdToUpdate);
@@ -181,7 +181,7 @@ public class UserRestUtils extends BaseRestUtils {
// 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());
+ logger.debug("Send following url: {} and headers: {}",url,headersMap.toString());
RestResponse sendGetUserRequest = http.httpSendGet(url, headersMap);
return sendGetUserRequest;
@@ -196,7 +196,6 @@ public class UserRestUtils extends BaseRestUtils {
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 == "/") {
@@ -205,7 +204,7 @@ public class UserRestUtils extends BaseRestUtils {
url = String.format(Urls.GET_USERS_BY_ROLES, config.getCatalogBeHost(), config.getCatalogBePort(), roles);
}
- logger.debug("Send following url: {} and headers: {}", url, headersMap.toString());
+ logger.debug("Send following url: {} and headers: {}",url,headersMap.toString());
RestResponse sendGetUserRequest = http.httpSendGet(url, headersMap);
return sendGetUserRequest;
}
@@ -245,12 +244,12 @@ public class UserRestUtils extends BaseRestUtils {
headersMap.put(HttpHeaderEnum.HTTP_CSP_EMAIL.getValue(), sdncUserDetails.getEmail());
}
- logger.debug("headersMap: {}", headersMap.toString());
+ 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);
+ logger.debug("Send GET request to login as seal user : {}",url);
return http.httpSendGet(url, headersMap);
}
@@ -270,12 +269,12 @@ public class UserRestUtils extends BaseRestUtils {
headersMap.put(HttpHeaderEnum.HTTP_CSP_EMAIL.getValue(), sdncUserDetails.getEmail());
}
- logger.debug("headersMap: {}", headersMap.toString());
+ 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);
+ 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
index 21b520c97a..f3240684cb 100644
--- 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
@@ -44,7 +44,9 @@ import org.openecomp.sdc.ci.tests.utils.Utils;
import org.openecomp.sdc.ci.tests.utils.general.FileUtils;
import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
+import com.google.gson.Gson;
import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class ArtifactValidationUtils {
@@ -118,10 +120,7 @@ public class ArtifactValidationUtils {
ObjectMapper mapper = new ObjectMapper();
ESArtifactData esArtifactObject = mapper.readValue(jsourceElement.toString(), ESArtifactData.class);
- // logger.debug("got artifact details from ElasticSearch as json");
-
return esArtifactObject;
-
}
public static void validateArtifactReqVsResp(ArtifactReqDetails expectedArtifactDetails,
@@ -207,7 +206,6 @@ public class ArtifactValidationUtils {
String sourceDir = config.getResourceConfigDir();
String testResourcesPath = sourceDir + File.separator + folderName;
List<String> listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath);
- // logger.debug("listFileName: {}", listFileName.get(positionInlist));
String payload = FileUtils.loadPayloadFile(listFileName, ext, true);
heatArtifactDetails.setPayload(payload);
heatArtifactDetails.setArtifactName(listFileName.get(positionInlist) + "." + ext);
@@ -217,7 +215,6 @@ public class ArtifactValidationUtils {
public static ArtifactReqDetails replaceDefaultArtWithArtFromList(ArtifactReqDetails heatArtifactDetails,
String heatExtension, String folderName, int positionInlist) throws IOException, Exception {
List<String> listOfArtifactFromFolder = getListOfArtifactFromFolder(folderName);
- // logger.debug("listFileName: {}", listOfArtifactFromFolder.get(positionInlist));
String payload = FileUtils.loadPayloadFileFromListUsingPosition(listOfArtifactFromFolder, heatExtension, true,
positionInlist);
heatArtifactDetails.setPayload(payload);
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
index 882498a63c..0d16308e26 100644
--- 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
@@ -100,7 +100,6 @@ public class AuditValidationUtils {
}
}
- // logger.debug("audit description - {}", auditDesc);
return auditDesc;
}
@@ -205,24 +204,29 @@ public class AuditValidationUtils {
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());
- validateField(actualAuditRecord, AuditJsonKeysEnum.MODIFIER.getAuditJsonKeyName(),
- externalAuditObject.getMODIFIER());
+ //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());
@@ -495,6 +499,61 @@ public class AuditValidationUtils {
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 {
@@ -634,11 +693,10 @@ public class AuditValidationUtils {
//
// }
- public static Map<String, Object> parseAuditResourceByAction(String action,
- Map<AuditingFieldsKeysEnum, String> body) throws Exception {
+ public static Map<String, Object> parseAuditResourceByAction(String action, Map<AuditingFieldsKeysEnum, String> body) throws Exception {
Map auditingMessage = null;
- auditingMessage = retrieveAuditMessagesByPattern(action, body);
+ auditingMessage = retrieveAuditMessagesByPattern(action, body, false);
return auditingMessage;
@@ -678,12 +736,12 @@ public class AuditValidationUtils {
Map auditingMessage = null;
if (body == null || body.isEmpty()) {
- auditingMessage = retrieveAuditMessagesByPattern(action, null);
+ auditingMessage = retrieveAuditMessagesByPattern(action, null, false);
// String pattern = "/_search?q=ACTION:\"" + action + "\"";
// auditingMessage = retrieveAuditMessagesByPattern(action);
// auditingMessage = retrieveAuditMessagesByPattern(pattern);
} else {
- auditingMessage = retrieveAuditMessagesByPattern(action, body);
+ auditingMessage = retrieveAuditMessagesByPattern(action, body, false);
// auditingMessage = retrieveAuditMessagesUsingBody(body);
}
@@ -737,11 +795,12 @@ public class AuditValidationUtils {
return restResponse.getResponse();
}
- public static Map retrieveAuditMessagesByPattern(String action, Map<AuditingFieldsKeysEnum, String> body)
+ 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>(
@@ -754,13 +813,16 @@ public class AuditValidationUtils {
}
List<Row> fetchFromTable = CassandraUtils.fetchFromTable(auditKeySpaceName, esType, myFields);
- assertTrue("expected on fetching from data base one record only, actual: " + fetchFromTable.size(),
- fetchFromTable.size() == 1);
+ 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();
- 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"
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
index eb3ee331ed..0d49d97302 100644
--- 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
@@ -28,6 +28,7 @@ import java.util.Arrays;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo;
import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.Utils;
import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
import org.openecomp.sdc.exception.ResponseFormat;
import org.testng.Assert;
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
index cd2297fd19..d63a514b3a 100644
--- 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
@@ -20,10 +20,9 @@
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 static org.testng.AssertJUnit.assertEquals;
import org.json.JSONObject;
import org.openecomp.sdc.be.model.category.CategoryDefinition;
import org.openecomp.sdc.be.model.category.GroupingDefinition;
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
index 29f9e84dd8..05e3874fc0 100644
--- 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
@@ -53,8 +53,10 @@ public class CsarValidationUtils {
public static String getCsarPayload(String csarName, String fileLocation) throws Exception {
- RestResponseAsByteArray csar = ImportRestUtils.getCsar(csarName, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
- assertTrue("Return response code different from 200", csar.getHttpStatusCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ 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) {
@@ -86,7 +88,8 @@ public class CsarValidationUtils {
}
- protected static List<TypeHeatMetaDefinition> getArtifactsByGroup(JSONObject jsonObjectImportStructure, List<TypeHeatMetaDefinition> listHeatMetaDefenition) {
+ protected static List<TypeHeatMetaDefinition> getArtifactsByGroup(JSONObject jsonObjectImportStructure,
+ List<TypeHeatMetaDefinition> listHeatMetaDefenition) {
@SuppressWarnings("unchecked")
Set<Object> typeSet = jsonObjectImportStructure.keySet();
@@ -103,7 +106,8 @@ public class CsarValidationUtils {
return listHeatMetaDefenition;
}
- protected static List<GroupHeatMetaDefinition> fetchArtifactByGroup(JSONArray array, List<GroupHeatMetaDefinition> listGroupHeatMetaDefinition, Boolean openNewGroup) {
+ protected static List<GroupHeatMetaDefinition> fetchArtifactByGroup(JSONArray array,
+ List<GroupHeatMetaDefinition> listGroupHeatMetaDefinition, Boolean openNewGroup) {
GroupHeatMetaDefinition groupHeatMetaDefinition;
@@ -130,8 +134,10 @@ public class CsarValidationUtils {
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 (!groupHeatMetaDefinition.getPropertyHeatMetaDefinition()
+ .equals(propertyHeatMetaDefinition)) {
+ groupHeatMetaDefinition.getPropertyHeatMetaDefinition()
+ .setValue((boolean) jsonObject.get(groupKeyStr));
}
}
if (groupKeyStr.equals("fileName") || groupKeyStr.equals("env")) {
@@ -141,7 +147,8 @@ public class CsarValidationUtils {
groupHeatMetaDefinition.setArtifactList(listArtifactNames);
} else {
if (!groupKeyStr.equals("isBase")) {
- fetchArtifactByGroup((JSONArray) jsonObject.get(groupKeyStr), listGroupHeatMetaDefinition, false);
+ fetchArtifactByGroup((JSONArray) jsonObject.get(groupKeyStr), listGroupHeatMetaDefinition,
+ false);
}
}
}
@@ -150,12 +157,14 @@ public class CsarValidationUtils {
return listGroupHeatMetaDefinition;
}
- private static Integer getArtifactCount(List<TypeHeatMetaDefinition> listHeatMetaDefenition, Boolean isEnvIncluded) {
+ 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()) {
+ for (GroupHeatMetaDefinition groupHeatMetaDefinition : typeHeatMetaDefinition
+ .getGroupHeatMetaDefinition()) {
if (isEnvIncluded) {
count = count + groupHeatMetaDefinition.getArtifactList().size();
} else {
@@ -189,17 +198,27 @@ public class CsarValidationUtils {
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(),
+ 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 {
+ public static void validateToscaDefinitonObjectVsResource(ToscaDefinition toscaDefinition, Resource resource)
+ throws Exception {
- assertTrue("check resource instance count, expected: " + getResourceInstanceCount(toscaDefinition) + ", actual: " + resource.getComponentInstances().size(),
+ 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(),
+ assertTrue(
+ "check resource instance relation count, expected: " + getResourceInstanceRelationCount(toscaDefinition)
+ + ", actual: " + resource.getComponentInstancesRelations().size(),
getResourceInstanceRelationCount(toscaDefinition) == resource.getComponentInstancesRelations().size());
}
@@ -211,9 +230,11 @@ public class CsarValidationUtils {
public static Integer getResourceInstanceRelationCount(ToscaDefinition toscaDefinition) {
int count = 0;
- List<ToscaNodeTemplatesTopologyTemplateDefinition> toscaNodeTemplatesTopologyTemplateDefinition = toscaDefinition.getToscaTopologyTemplate().getToscaNodeTemplatesTopologyTemplateDefinition();
+ List<ToscaNodeTemplatesTopologyTemplateDefinition> toscaNodeTemplatesTopologyTemplateDefinition = toscaDefinition
+ .getToscaTopologyTemplate().getToscaNodeTemplatesTopologyTemplateDefinition();
for (int i = 0; i < toscaNodeTemplatesTopologyTemplateDefinition.size(); i++) {
- List<ToscaRequirementsNodeTemplatesDefinition> requirements = toscaNodeTemplatesTopologyTemplateDefinition.get(i).getRequirements();
+ List<ToscaRequirementsNodeTemplatesDefinition> requirements = toscaNodeTemplatesTopologyTemplateDefinition
+ .get(i).getRequirements();
if (requirements != null) {
for (ToscaRequirementsNodeTemplatesDefinition requirement : requirements) {
if (requirement.getNode() != null) {
@@ -234,7 +255,10 @@ public class CsarValidationUtils {
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)));
+ 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()));
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
new file mode 100644
index 0000000000..46948d8f5b
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/DistributionValidationUtils.java
@@ -0,0 +1,86 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.utils.validation;
+
+import static org.testng.AssertJUnit.assertNotNull;
+
+import java.io.IOException;
+import java.text.ParseException;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.ci.tests.utils.DistributionUtils;
+import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils;
+import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
+
+public class DistributionValidationUtils {
+
+ public static Map<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
index ac5a05d7ca..94dcca7edf 100644
--- 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
@@ -29,6 +29,7 @@ import java.io.InputStream;
import java.util.List;
import java.util.Map;
+import org.yaml.snakeyaml.Yaml;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.openecomp.sdc.ci.tests.config.Config;
@@ -37,7 +38,6 @@ 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 {
@@ -58,10 +58,19 @@ public class ErrorValidationUtils {
}
}
actualResponse = actualResponse.replaceAll("\\n", "");
- logger.debug("actualResponse - {}", actualResponse);
- logger.debug("expectedResponseBody - {}", expectedResponseBody);
+ 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) {
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
index a3440df8ad..7bbadc5c1b 100644
--- 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
@@ -167,7 +167,7 @@ public class ResourceValidationUtils {
resourceRespJavaObject.getCreatorUserId());
validateField(map, RespJsonKeysEnum.CREATOR_FULL_NAME.getRespJsonKeyName(),
resourceRespJavaObject.getCreatorFullName());
- validateField(map, RespJsonKeysEnum.LAST_UPDATER_ATT_UID.getRespJsonKeyName(),
+ validateField(map, RespJsonKeysEnum.LAST_UPDATER_USER_ID.getRespJsonKeyName(),
resourceRespJavaObject.getLastUpdaterUserId());
validateField(map, RespJsonKeysEnum.LAST_UPDATER_FULL_NAME.getRespJsonKeyName(),
resourceRespJavaObject.getLastUpdaterFullName());
@@ -220,6 +220,10 @@ public class ResourceValidationUtils {
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);
@@ -270,7 +274,7 @@ public class ResourceValidationUtils {
if (interfaze != null) {
interfaces = resource.getInterfaces();
- Map<String, Operation> operation = interfaces.get(interfaze).getOperations();
+ Map<String, Operation> operation = interfaces.get(interfaze).getOperationsMap();
// operation.get("configure").getUniqueId();
}
@@ -298,7 +302,7 @@ public class ResourceValidationUtils {
resourceRespJavaObject.getCreatorUserId());
validateField(map, RespJsonKeysEnum.CREATOR_FULL_NAME.getRespJsonKeyName(),
resourceRespJavaObject.getCreatorFullName());
- validateField(map, RespJsonKeysEnum.LAST_UPDATER_ATT_UID.getRespJsonKeyName(),
+ validateField(map, RespJsonKeysEnum.LAST_UPDATER_USER_ID.getRespJsonKeyName(),
resourceRespJavaObject.getLastUpdaterUserId());
validateField(map, RespJsonKeysEnum.LAST_UPDATER_FULL_NAME.getRespJsonKeyName(),
resourceRespJavaObject.getLastUpdaterFullName());
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
index 19bd7b9488..a7c7b7d34e 100644
--- 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
@@ -20,9 +20,8 @@
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.assertEquals;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
@@ -73,7 +72,8 @@ public class ServiceValidationUtils {
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 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());
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
new file mode 100644
index 0000000000..223bf4ed4b
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/TestYamlParser.java
@@ -0,0 +1,94 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.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.be.model.User;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaDefinition;
+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
index a75434edcf..9c44aa55ef 100644
--- 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
@@ -20,8 +20,8 @@
package org.openecomp.sdc.ci.tests.utils.validation;
-import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertTrue;
+import static org.testng.AssertJUnit.assertEquals;
import java.util.List;
@@ -55,7 +55,7 @@ public class UserValidationUtils {
String actualUserId = actual.getUserId();
String expectedUserId = expected.getUserId();
- assertEquals("check user userId - ", expectedUserId, actualUserId);
+ assertEquals("check user UserId - ", expectedUserId, actualUserId);
String actualEmail = actual.getEmail();
String expectedEmail = expected.getEmail();
@@ -203,10 +203,6 @@ public class UserValidationUtils {
}
assertEquals("check audit user desc - ", expected, auditJavaObject.getDESC());
-
- // expected = sdncUserDetails.getUserId();
- // assertEquals(expected, auditJavaObject.getUSER());
-
}
public static void validateUserDetailsOnResponse(User sdncUserDetails, String userDetailsOnResponse) {
@@ -221,7 +217,7 @@ public class UserValidationUtils {
String actualUserId = Utils.getJsonObjectValueByKey(userDetailsOnResponse, "userId");
String expectedUserId = sdncUserDetails.getUserId();
- assertEquals("check user userId - ", expectedUserId, actualUserId);
+ assertEquals("check user UserId - ", expectedUserId, actualUserId);
String actualEmail = Utils.getJsonObjectValueByKey(userDetailsOnResponse, "email");
String expectedEmail = sdncUserDetails.getEmail();
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
index 8ea8524489..9b98688036 100644
--- a/asdc-tests/src/main/java/org/openecomp/sdc/externalApis/GetAssetServlet.java
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/externalApis/GetAssetServlet.java
@@ -37,6 +37,7 @@ 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;
@@ -122,14 +123,14 @@ public class GetAssetServlet extends ComponentBaseTest {
List<String> expectedAssetNamesList = new ArrayList<>();
ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
- resourceDetails.setName("Resource1");
+ 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("Resource2");
+ resourceDetails.setName("ciResource2");
resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
BaseRestUtils.checkCreateResponse(createResource);
@@ -141,7 +142,7 @@ public class GetAssetServlet extends ComponentBaseTest {
expectedAssetNamesList.add(resource.getName());
expectedAssetNamesList.add(resource.getName());
- resourceDetails.setName("Resource3");
+ resourceDetails.setName("ciResource3");
resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
BaseRestUtils.checkCreateResponse(createResource);
@@ -151,7 +152,7 @@ public class GetAssetServlet extends ComponentBaseTest {
resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
expectedAssetNamesList.add(resource.getName());
- resourceDetails.setName("Resource4");
+ resourceDetails.setName("ciResource4");
resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
BaseRestUtils.checkCreateResponse(createResource);
@@ -163,7 +164,7 @@ public class GetAssetServlet extends ComponentBaseTest {
resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft();
expectedAssetNamesList.add(resource.getName());
- resourceDetails.setName("Resource5");
+ resourceDetails.setName("ciResource5");
resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
BaseRestUtils.checkCreateResponse(createResource);
@@ -174,7 +175,7 @@ public class GetAssetServlet extends ComponentBaseTest {
resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft();
expectedAssetNamesList.add(resource.getName());
- resourceDetails.setName("Resource6");
+ resourceDetails.setName("ciResource6");
resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
BaseRestUtils.checkCreateResponse(createResource);
@@ -182,7 +183,7 @@ public class GetAssetServlet extends ComponentBaseTest {
resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.STARTCERTIFICATION, true).getLeft();
expectedAssetNamesList.add(resource.getName());
- resourceDetails.setName("Resource7");
+ resourceDetails.setName("ciResource7");
resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
BaseRestUtils.checkCreateResponse(createResource);
@@ -201,7 +202,7 @@ public class GetAssetServlet extends ComponentBaseTest {
List<String> getActualAssetNamesList = AssetRestUtils.getResourceNamesList(resourceAssetList);
Utils.compareArrayLists(getActualAssetNamesList, expectedAssetNamesList, "Element");
- AssetRestUtils.checkResourceTypeInObjectList(resourceAssetList, ResourceTypeEnum.VF);
+ AssetRestUtils.checkComponentTypeInObjectList(resourceAssetList, ComponentTypeEnum.RESOURCE);
// Validate audit message
ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetListAudit(AssetTypeEnum.RESOURCES, AuditingActionEnum.GET_ASSET_LIST);
@@ -216,13 +217,13 @@ public class GetAssetServlet extends ComponentBaseTest {
ArtifactReqDetails artifactDetails = ElementFactory.getArtifactByType(ArtifactTypeEnum.OTHER, ArtifactTypeEnum.OTHER, true);
ServiceReqDetails serviceDetails = ElementFactory.getDefaultService();
- serviceDetails.setName("Service1");
+ 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("Service2");
+ serviceDetails.setName("ciService2");
createService = ServiceRestUtils.createService(serviceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
BaseRestUtils.checkCreateResponse(createService);
service = ResponseParser.parseToObjectUsingMapper(createService.getResponse(), Service.class);
@@ -235,7 +236,7 @@ public class GetAssetServlet extends ComponentBaseTest {
expectedAssetNamesList.add(service.getName());
expectedAssetNamesList.add(service.getName());
- serviceDetails.setName("Service3");
+ serviceDetails.setName("ciService3");
createService = ServiceRestUtils.createService(serviceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
BaseRestUtils.checkCreateResponse(createService);
service = ResponseParser.parseToObjectUsingMapper(createService.getResponse(), Service.class);
@@ -246,7 +247,7 @@ public class GetAssetServlet extends ComponentBaseTest {
service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
expectedAssetNamesList.add(service.getName());
- serviceDetails.setName("Service4");
+ serviceDetails.setName("ciService4");
createService = ServiceRestUtils.createService(serviceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
BaseRestUtils.checkCreateResponse(createService);
service = ResponseParser.parseToObjectUsingMapper(createService.getResponse(), Service.class);
@@ -257,7 +258,7 @@ public class GetAssetServlet extends ComponentBaseTest {
service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft();
expectedAssetNamesList.add(service.getName());
- serviceDetails.setName("Service5");
+ serviceDetails.setName("ciService5");
createService = ServiceRestUtils.createService(serviceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
BaseRestUtils.checkCreateResponse(createService);
service = ResponseParser.parseToObjectUsingMapper(createService.getResponse(), Service.class);
@@ -267,7 +268,7 @@ public class GetAssetServlet extends ComponentBaseTest {
service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft();
expectedAssetNamesList.add(service.getName());
- serviceDetails.setName("Service6");
+ serviceDetails.setName("ciService6");
createService = ServiceRestUtils.createService(serviceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
BaseRestUtils.checkCreateResponse(createService);
service = ResponseParser.parseToObjectUsingMapper(createService.getResponse(), Service.class);
@@ -276,7 +277,7 @@ public class GetAssetServlet extends ComponentBaseTest {
service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.STARTCERTIFICATION, true).getLeft();
expectedAssetNamesList.add(service.getName());
- serviceDetails.setName("Service7");
+ serviceDetails.setName("ciService7");
createService = ServiceRestUtils.createService(serviceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
BaseRestUtils.checkCreateResponse(createService);
service = ResponseParser.parseToObjectUsingMapper(createService.getResponse(), Service.class);
@@ -307,7 +308,7 @@ public class GetAssetServlet extends ComponentBaseTest {
CloseableHttpClient httpclient = HttpClients.createDefault();
ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
- resourceDetails.setName("Resource1");
+ resourceDetails.setName("ciResource1");
resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, sdncUserDetails);
BaseRestUtils.checkCreateResponse(createResource);
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
index 05d305ad9a..791a490288 100644
--- a/asdc-tests/src/main/java/org/openecomp/sdc/externalApis/GetSpecificAssetMetadataServlet.java
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/externalApis/GetSpecificAssetMetadataServlet.java
@@ -101,7 +101,7 @@ public class GetSpecificAssetMetadataServlet extends ComponentBaseTest {
AuditingActionEnum.GET_ASSET_METADATA.getName(), null);
}
- @Test // (enabled = false)
+ @Test (enabled = false)
public void getResourceAssetMetadataWithResourceInstancesSuccess() throws Exception {
Resource resourceVF = AtomicOperationUtils
@@ -455,7 +455,7 @@ public class GetSpecificAssetMetadataServlet extends ComponentBaseTest {
}
- @Test // (enabled = false)
+ @Test (enabled = false)
public void getServiceAssetMetadataWithCertifiedResourceInstancesAndArtifactsOnRIsAndServiceSuccess()
throws Exception {
@@ -570,7 +570,7 @@ public class GetSpecificAssetMetadataServlet extends ComponentBaseTest {
// Validate audit message
ArrayList<String> variables = new ArrayList<>();
variables.add(serviceUuid);
- ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESOURCE_NOT_FOUND.name(), variables,
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.SERVICE_NOT_FOUND.name(), variables,
assetResponse.getResponse());
}
@@ -583,7 +583,7 @@ public class GetSpecificAssetMetadataServlet extends ComponentBaseTest {
ResourceReqDetails resourceDetails = ElementFactory
.getDefaultResource(ResourceCategoryEnum.APPLICATION_L4_APP_SERVER);
- resourceDetails.setName("Resource1");
+ resourceDetails.setName("ciResource1");
resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
RestResponse createResource = ResourceRestUtils.createResource(resourceDetails,
ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
@@ -592,7 +592,7 @@ public class GetSpecificAssetMetadataServlet extends ComponentBaseTest {
expectedAssetNamesList.add(resource.getName());
resourceDetails = ElementFactory.getDefaultResource(ResourceCategoryEnum.APPLICATION_L4_BORDER);
- resourceDetails.setName("Resource2");
+ resourceDetails.setName("ciResource2");
resourceDetails.setResourceType(ResourceTypeEnum.VFC.name());
createResource = ResourceRestUtils.createResource(resourceDetails,
ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
@@ -608,7 +608,7 @@ public class GetSpecificAssetMetadataServlet extends ComponentBaseTest {
.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft();
resourceDetails = ElementFactory.getDefaultResource(ResourceCategoryEnum.GENERIC_INFRASTRUCTURE);
- resourceDetails.setName("Resource3");
+ resourceDetails.setName("ciResource3");
resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
createResource = ResourceRestUtils.createResource(resourceDetails,
ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
@@ -622,7 +622,7 @@ public class GetSpecificAssetMetadataServlet extends ComponentBaseTest {
.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
resourceDetails = ElementFactory.getDefaultResource(ResourceCategoryEnum.APPLICATION_L4_FIREWALL);
- resourceDetails.setName("Resource4");
+ resourceDetails.setName("ciResource4");
resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
createResource = ResourceRestUtils.createResource(resourceDetails,
ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
@@ -679,13 +679,13 @@ public class GetSpecificAssetMetadataServlet extends ComponentBaseTest {
ArtifactTypeEnum.OTHER, true);
ServiceReqDetails serviceDetails = ElementFactory.getDefaultService();
- serviceDetails.setName("Service1");
+ 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("Service2");
+ serviceDetails.setName("ciService2");
createService = ServiceRestUtils.createService(serviceDetails,
ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
BaseRestUtils.checkCreateResponse(createService);
@@ -703,7 +703,7 @@ public class GetSpecificAssetMetadataServlet extends ComponentBaseTest {
AtomicOperationUtils.distributeService(service, false);
expectedAssetNamesList.add(service.getName());
- serviceDetails.setName("Service3");
+ serviceDetails.setName("ciService3");
createService = ServiceRestUtils.createService(serviceDetails,
ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
BaseRestUtils.checkCreateResponse(createService);
@@ -724,7 +724,7 @@ public class GetSpecificAssetMetadataServlet extends ComponentBaseTest {
AtomicOperationUtils.distributeService(service, false);
expectedAssetNamesList.add(service.getName());
- serviceDetails.setName("Service4");
+ serviceDetails.setName("ciService4");
createService = ServiceRestUtils.createService(serviceDetails,
ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
BaseRestUtils.checkCreateResponse(createService);
@@ -740,7 +740,7 @@ public class GetSpecificAssetMetadataServlet extends ComponentBaseTest {
service = (Service) AtomicOperationUtils
.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft();
- serviceDetails.setName("Service5");
+ serviceDetails.setName("ciService5");
createService = ServiceRestUtils.createService(serviceDetails,
ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
BaseRestUtils.checkCreateResponse(createService);
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
index f0494fe177..5e9e02c479 100644
--- a/asdc-tests/src/main/java/org/openecomp/sdc/post/Install.java
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/post/Install.java
@@ -22,6 +22,7 @@ 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;
@@ -46,8 +47,8 @@ public class Install {
}
private static boolean createTitanSchema(String titanPropsFile) {
- TitanGraphClient titanGraphClient = new TitanGraphClient();
- TitanOperationStatus status = titanGraphClient.createGraph(titanPropsFile, true);
+ 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;
diff --git a/asdc-tests/src/main/resources/ci/conf/sdc-packages.yaml b/asdc-tests/src/main/resources/ci/conf/attsdc-packages.yaml
index 5d1a3e1537..5d1a3e1537 100644
--- a/asdc-tests/src/main/resources/ci/conf/sdc-packages.yaml
+++ b/asdc-tests/src/main/resources/ci/conf/attsdc-packages.yaml
diff --git a/asdc-tests/src/main/resources/ci/conf/sdc.yaml b/asdc-tests/src/main/resources/ci/conf/attsdc.yaml
index c9730811b3..10bf38f89d 100644
--- a/asdc-tests/src/main/resources/ci/conf/sdc.yaml
+++ b/asdc-tests/src/main/resources/ci/conf/attsdc.yaml
@@ -7,6 +7,7 @@ disributionClientHost: disClient
catalogFePort: 8181
catalogBePort: 8080
disributionClientPort: 8181
+isDistributionClientRunning: true
esPort: 9200
neoHost: neoHost
neoPort: 7474
@@ -30,8 +31,8 @@ cassandraPassword: bobo
cassandraSsl: false
cassandraTruststorePath : /path/path
cassandraTruststorePassword : 123123
-cassandraAuditKeySpace: sdcAudit
-cassandraArtifactKeySpace: sdcArtifact
+cassandraAuditKeySpace: sdcaudit
+cassandraArtifactKeySpace: sdcartifact
stopOnClassFailure: false
@@ -78,11 +79,13 @@ resourceCategoriesNotToDelete:
- Network L4+
- Application L4+
- Network Connectivity
- - DcaeComponent
+ - DCAE Component
+ - Template
+ - Allotted Resource
#Service categories to keep
serviceCategoriesNotToDelete:
- Mobility
- Network L1-3
- Network L4+
- - VoIP Call Control \ No newline at end of file
+ - VoIP Call Control
diff --git a/asdc-tests/src/main/resources/ci/conf/titan.properties b/asdc-tests/src/main/resources/ci/conf/titan.properties
index 42e1998f89..0fe7888b9e 100644
--- a/asdc-tests/src/main/resources/ci/conf/titan.properties
+++ b/asdc-tests/src/main/resources/ci/conf/titan.properties
@@ -4,5 +4,5 @@ storage.hostname=localhost
storage.port=9160
cache.db-cache = false
-
+storage.cassandra.keyspace=sdctitan
diff --git a/asdc-tests/src/main/resources/ci/scripts/startTest.sh b/asdc-tests/src/main/resources/ci/scripts/startTest.sh
index ca3add59c5..01b8979781 100644
--- a/asdc-tests/src/main/resources/ci/scripts/startTest.sh
+++ b/asdc-tests/src/main/resources/ci/scripts/startTest.sh
@@ -31,7 +31,7 @@ fi
LOGS_PROP_FILE=file:${FULL_PATH}/conf/log4j.properties
#############################################
TARGET_DIR=${FULL_PATH}/target
-CONF_FILE=${FULL_PATH}/conf/sdc.yaml
+CONF_FILE=${FULL_PATH}/conf/attsdc.yaml
DEBUG=true
MainClass=org.openecomp.sdc.ci.tests.run.StartTest
diff --git a/asdc-tests/src/main/resources/ci/testSuites/CRUDArtifacts.xml b/asdc-tests/src/main/resources/ci/testSuites/CRUDArtifacts.xml
new file mode 100644
index 0000000000..e53da8da8a
--- /dev/null
+++ b/asdc-tests/src/main/resources/ci/testSuites/CRUDArtifacts.xml
@@ -0,0 +1,40 @@
+<?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
new file mode 100644
index 0000000000..40c462a4cb
--- /dev/null
+++ b/asdc-tests/src/main/resources/ci/testSuites/SearchExternalAPI.xml
@@ -0,0 +1,23 @@
+<?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/ciFull.xml b/asdc-tests/src/main/resources/ci/testSuites/ciFull.xml
index 9877670a90..26a85fd9c6 100644
--- a/asdc-tests/src/main/resources/ci/testSuites/ciFull.xml
+++ b/asdc-tests/src/main/resources/ci/testSuites/ciFull.xml
@@ -177,7 +177,7 @@
<exclude name="dissociateOnceAgainTest" />
<exclude name="dissociateRelationNotFoundTest" />
<exclude name="dissoicateRelationWhileInstanceNotFound" />
- <exclude name="dissoicateWithEmptyUserIdsHeaderTest" />
+ <exclude name="dissoicateWithEmptyUserIdHeaderTest" />
<exclude name="relationDeletedAfterDeletingResourceInstanceTest" />
</methods>
</class>
diff --git a/asdc-tests/src/main/resources/ci/testSuites/externalApis.xml b/asdc-tests/src/main/resources/ci/testSuites/externalApis.xml
index 5db368ecf4..393d3b1a3e 100644
--- a/asdc-tests/src/main/resources/ci/testSuites/externalApis.xml
+++ b/asdc-tests/src/main/resources/ci/testSuites/externalApis.xml
@@ -6,6 +6,9 @@
<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/resource.xml b/asdc-tests/src/main/resources/ci/testSuites/resource.xml
index 5f23325790..803fb01e70 100644
--- a/asdc-tests/src/main/resources/ci/testSuites/resource.xml
+++ b/asdc-tests/src/main/resources/ci/testSuites/resource.xml
@@ -30,6 +30,30 @@
</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"/>
diff --git a/asdc-tests/src/main/resources/ci/testSuites/sanity.xml b/asdc-tests/src/main/resources/ci/testSuites/sanity.xml
index 11b4b79fc4..8e787bc8cd 100644
--- a/asdc-tests/src/main/resources/ci/testSuites/sanity.xml
+++ b/asdc-tests/src/main/resources/ci/testSuites/sanity.xml
@@ -2,10 +2,6 @@
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Sanity" configfailurepolicy="continue" verbose="2">
- <listeners>
- <listener class-name="org.openecomp.sdc.ci.tests.run.ExtentReporterNG" />
- </listeners>
-
<test name="sanityE2Eflows">
<classes>
<class name="org.openecomp.sdc.ci.tests.sanity.CrudE2E" />
@@ -69,8 +65,6 @@
</methods>
</class>
-
-
<class name="org.openecomp.sdc.ci.tests.execute.artifacts.ValidateArtResponse" />
@@ -268,15 +262,9 @@
name="org.openecomp.sdc.ci.tests.execute.imports.ImportToscaCapabilitiesWithProperties">
<methods>
<include name="importNodeTypeWithCapabilityWithPropertiesFromYmlSucceed" />
- <!--
- This test require the onboarding simulator.
- <include name="importResourceWithCapabilityWithPropertiesOverridingCapTypePropertiesSucceed" />
- -->
+ <include name="importResourceWithCapabilityWithPropertiesOverridingCapTypePropertiesSucceed" />
</methods>
</class>
- <class
- name="org.openecomp.sdc.ci.tests.execute.imports.CsarUtilsTest">
- </class>
</classes>
</test> <!-- Test -->
diff --git a/asdc-tests/src/test/resources/CI/configuration.yaml b/asdc-tests/src/test/resources/CI/configuration.yaml
index cb91316a21..87fada1b4b 100644
--- a/asdc-tests/src/test/resources/CI/configuration.yaml
+++ b/asdc-tests/src/test/resources/CI/configuration.yaml
@@ -141,7 +141,7 @@ informationalResourceArtifacts:
testScripts:
displayName: Test Scripts
type: OTHER
- cloudQuestionnaire:
+ CloudQuestionnaire:
displayName: Cloud Questionnaire (completed)
type: OTHER
HEATTemplateFromVendor:
@@ -329,10 +329,8 @@ cassandraConfig:
- { name: sdcaudit, replicationStrategy: SimpleStrategy, replicationInfo: ['1']}
- { name: sdcartifact, replicationStrategy: SimpleStrategy, replicationInfo: ['1']}
-heatEnvArtifactHeader:
- ""
-heatEnvArtifactFooter:
- ""
+heatEnvArtifactHeader: ""
+heatEnvArtifactFooter: ""
onboarding:
protocol: http
@@ -341,23 +339,23 @@ onboarding:
downloadCsarUri: "/onboardingci/onbrest/onboarding-api/v1.0/vendor-software-products/packages"
switchoverDetector:
- gBeFqdn:
- gFeFqdn:
- beVip: 1.2.3.4
- feVip: 1.2.3.4
+ 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://localhost/crt/CipDomain.ECOMP-ASDC-DEVST/config/update_network?user=root"
+ publishNetworkUrl: "http://xxx.com/crt/CipDomain.ECOMP-ASDC-DEVST/config/update_network?user=root"
publishNetworkBody: '{"note":"publish network"}'
groups:
- beSet: { changePriorityUrl: "http://localhost/crt/CipDomain.ECOMP-ASDC-DEVST/config/sites/AIO-BE.ecomp.idns.cip?user=root",
- changePriorityBody: '{"name":"AIO-BE.ecomp.idns.cip","uri":"/crt/CipDomain.ECOMP-ASDC-DEVST/config/sites/AIO-BE.ecomp.idns.cip","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://cora.web/crt/CipDomain.ECOMP-ASDC-DEVST/config/sites/AIO-FE.ecomp.idns.cip?user=root",
- changePriorityBody: '{"comment":"AIO G-fqdn","name":"AIO-FE.ecomp.idns.cip","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.att.com"}'}
+ 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:
@@ -379,4 +377,10 @@ applicationL2Cache:
numberOfCacheWorkers: 4
toscaValidators:
- stringMaxLength: 1024 \ No newline at end of file
+ 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
index a702c78d25..9c1629eae7 100644
--- a/asdc-tests/src/test/resources/CI/csars/FCGI_with_inputs.csar
+++ b/asdc-tests/src/test/resources/CI/csars/FCGI_with_inputs.csar
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
new file mode 100644
index 0000000000..7fc5306bcc
--- /dev/null
+++ b/asdc-tests/src/test/resources/CI/csars/ImportArtifactsToVFC.csar
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
new file mode 100644
index 0000000000..7a77e2011d
--- /dev/null
+++ b/asdc-tests/src/test/resources/CI/csars/ImportArtifactsToVFC_empty.csar
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
index a551ce3263..821b62d48a 100644
--- a/asdc-tests/src/test/resources/CI/csars/LDSA1_with_inputs.csar
+++ b/asdc-tests/src/test/resources/CI/csars/LDSA1_with_inputs.csar
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
new file mode 100644
index 0000000000..e12f45e1b1
--- /dev/null
+++ b/asdc-tests/src/test/resources/CI/csars/ToscaTemplateCsar.csar
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
index a6678a47d1..98e20258b2 100644
--- 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
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
index ca0ab91e39..98e20258b2 100644
--- 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
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
index 890ae20cb3..4668bbefb8 100644
--- 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
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
index 68819afc4b..4903bff3b6 100644
--- 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
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
index 528599e0c5..8398e710b4 100644
--- 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
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
index 6a708d335f..61a494c092 100644
--- 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
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
index 2aa2ef4582..07118fc014 100644
--- a/asdc-tests/src/test/resources/CI/csars/jsonPropertyTypeTest.csar
+++ b/asdc-tests/src/test/resources/CI/csars/jsonPropertyTypeTest.csar
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/csars/orig2G.csar b/asdc-tests/src/test/resources/CI/csars/orig2G.csar
index 609cd0a8b4..2e8670f1eb 100644
--- a/asdc-tests/src/test/resources/CI/csars/orig2G.csar
+++ b/asdc-tests/src/test/resources/CI/csars/orig2G.csar
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
index a7e04cbf10..e6e545ea2f 100644
--- a/asdc-tests/src/test/resources/CI/csars/orig2GV001.csar
+++ b/asdc-tests/src/test/resources/CI/csars/orig2GV001.csar
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
index 07371acaf2..d5a7b47b70 100644
--- a/asdc-tests/src/test/resources/CI/csars/orig2GV001_a.csar
+++ b/asdc-tests/src/test/resources/CI/csars/orig2GV001_a.csar
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
index ebd95548f8..88cebe44f2 100644
--- 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
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
index dc75ae1549..7c24de025d 100644
--- 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
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
index 2f6ad121a6..9af7501b76 100644
--- a/asdc-tests/src/test/resources/CI/csars/orig2G_a.csar
+++ b/asdc-tests/src/test/resources/CI/csars/orig2G_a.csar
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
index 1968eabf4b..1a4107811d 100644
--- a/asdc-tests/src/test/resources/CI/csars/orig2G_updated.csar
+++ b/asdc-tests/src/test/resources/CI/csars/orig2G_updated.csar
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
index f2a7efb69e..eec433e8ff 100644
--- 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
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
index d4561a0640..ce1541f32c 100644
--- 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
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
index f145ebd5d2..a2a9ad77c9 100644
--- 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
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
new file mode 100644
index 0000000000..8b5f58b7ef
--- /dev/null
+++ b/asdc-tests/src/test/resources/CI/csars/vfc_artifacts.csar
Binary files differ
diff --git a/ui-ci-dev/src/main/resources/Files/vf_with_groups.csar b/asdc-tests/src/test/resources/CI/csars/vfc_artifacts_delete_all.csar
index 61ea8cee20..a15e7b46c1 100644
--- a/ui-ci-dev/src/main/resources/Files/vf_with_groups.csar
+++ b/asdc-tests/src/test/resources/CI/csars/vfc_artifacts_delete_all.csar
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
new file mode 100644
index 0000000000..af712f1a59
--- /dev/null
+++ b/asdc-tests/src/test/resources/CI/csars/vfc_artifacts_update.csar
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
index ada1451cea..63a478939c 100644
--- 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
Binary files differ
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
index 1b02f06386..09c3709ace 100644
--- 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
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/demoResourcesWanLan/VNF/VNF.zip b/asdc-tests/src/test/resources/CI/demoResourcesWanLan/VNF/VNF.zip
index c01081f0ab..95183b48d3 100644
--- a/asdc-tests/src/test/resources/CI/demoResourcesWanLan/VNF/VNF.zip
+++ b/asdc-tests/src/test/resources/CI/demoResourcesWanLan/VNF/VNF.zip
Binary files differ
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
index a8e006e728..fc1a5e54e8 100644
--- 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
Binary files differ
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
index e193820659..3c558f0603 100644
--- 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
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/demoResourcesWanLan/capabilityTypesWanLan.zip b/asdc-tests/src/test/resources/CI/demoResourcesWanLan/capabilityTypesWanLan.zip
index 869be32b53..9424556f08 100644
--- a/asdc-tests/src/test/resources/CI/demoResourcesWanLan/capabilityTypesWanLan.zip
+++ b/asdc-tests/src/test/resources/CI/demoResourcesWanLan/capabilityTypesWanLan.zip
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/demoResourcesWanLan/connector/connector.zip b/asdc-tests/src/test/resources/CI/demoResourcesWanLan/connector/connector.zip
index 3c37303a3a..203db0e34e 100644
--- a/asdc-tests/src/test/resources/CI/demoResourcesWanLan/connector/connector.zip
+++ b/asdc-tests/src/test/resources/CI/demoResourcesWanLan/connector/connector.zip
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/demoResourcesWanLan/root/root.zip b/asdc-tests/src/test/resources/CI/demoResourcesWanLan/root/root.zip
index ff604d55a7..af28d79174 100644
--- a/asdc-tests/src/test/resources/CI/demoResourcesWanLan/root/root.zip
+++ b/asdc-tests/src/test/resources/CI/demoResourcesWanLan/root/root.zip
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/demoResourcesWanLan/router/router.zip b/asdc-tests/src/test/resources/CI/demoResourcesWanLan/router/router.zip
index 57ff8e0e2a..f6e2fff528 100644
--- a/asdc-tests/src/test/resources/CI/demoResourcesWanLan/router/router.zip
+++ b/asdc-tests/src/test/resources/CI/demoResourcesWanLan/router/router.zip
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/error-configuration.yaml b/asdc-tests/src/test/resources/CI/error-configuration.yaml
index 6d4e2373fa..33207def3b 100644
--- a/asdc-tests/src/test/resources/CI/error-configuration.yaml
+++ b/asdc-tests/src/test/resources/CI/error-configuration.yaml
@@ -55,7 +55,7 @@ errors:
messageId: "SVC4002"
}
#---------SVC4003------------------------------
-# %1 - Users's USER_ID
+# %1 - Users's USER ID
USER_NOT_FOUND: {
code: 404,
message: "Error: User '%1' was not found.",
@@ -76,7 +76,7 @@ errors:
messageId: "SVC4005"
}
#---------SVC4006------------------------------
-# %1 - Users's USER_ID
+# %1 - Users's USER ID
USER_ALREADY_EXIST: {
code: 409,
message: "Error: User with '%1' ID already exists.",
@@ -89,7 +89,7 @@ errors:
messageId: "SVC4007"
}
#---------SVC4008-----------------------------
-# %1 - Users's userId
+# %1 - Users's USER ID
INVALID_USER_ID: {
code: 400,
message: "Error: Invalid userId '%1'.",
@@ -99,7 +99,7 @@ errors:
# %1 - service/resource
COMPONENT_MISSING_CONTACT: {
code: 400,
- message: "Error: Invalid Content. Missing %1 contact id.",
+ message: "Error: Invalid Content. Missing %1 Contact Id.",
messageId: "SVC4049"
}
#---------SVC4050-----------------------------
@@ -240,9 +240,9 @@ errors:
#---------SVC4069------------------------------
# %1 - Service/Resource/Product
- COMPONENT_INVALID_CONTACT_ID: {
+ COMPONENT_INVALID_CONTACT: {
code: 400,
- message: "Error: Invalid Content. %1 contact id should be in format 'mnnnnnn' or 'aannna' or 'aannnn', where m=m ,a=a-zA-Z and n=0-9",
+ message: "Error: Invalid Content. %1 Contact Id should be in format 'mnnnnnn' or 'aannna' or 'aannnn', where m=m ,a=a-zA-Z and n=0-9",
messageId: "SVC4069"
}
#---------SVC4070------------------------------
@@ -506,7 +506,7 @@ errors:
#-----------SVC4130---------------------------
INVALID_PROJECT_CODE: {
code: 400,
- message: "Error: Invalid Content. PROJECT_CODE number must be numeric from 5 up to 10 digits.",
+ message: "Error: Invalid Content. PROJECT_CODE must be from 3 up to 50 characters.",
messageId: "SVC4130"
}
#-----------SVC4131---------------------------
@@ -1055,7 +1055,7 @@ errors:
messageId: "SVC4567"
}
#---------SVC4567------------------------------
-# %1 - "User Name and UserId"
+# %1 - "User Name and USER_ID"
# %2 -"checked-out"/"in-certification"
CANNOT_DELETE_USER_WITH_ACTIVE_ELEMENTS: {
code: 409,
@@ -1063,7 +1063,7 @@ errors:
messageId: "SVC4567"
}
#---------SVC4568------------------------------
-# %1 - "User Name and UserId"
+# %1 - "User Name and USER_ID"
# %2 -"checked-out"/"in-certification"
CANNOT_UPDATE_USER_WITH_ACTIVE_ELEMENTS: {
code: 409,
@@ -1139,7 +1139,7 @@ errors:
messageId: "SVC4580"
}
#---------SVC4581------------------------------
-# %1 - userId
+# %1 - USER_ID
INVALID_PRODUCT_CONTACT: {
code: 400,
message: "Error: Invalid content. User '%1' cannot be set as Product Contact.",
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
new file mode 100644
index 0000000000..cd215933ab
--- /dev/null
+++ b/asdc-tests/src/test/resources/CI/importAttResources/PCSCF/PCSCF .yml.old
@@ -0,0 +1,29 @@
+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
index bf8ee08d30..8c4e5745ab 100644
--- a/asdc-tests/src/test/resources/CI/importAttResources/PCSCF/PCSCF.json
+++ b/asdc-tests/src/test/resources/CI/importAttResources/PCSCF/PCSCF.json
@@ -2,7 +2,7 @@
"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). 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)).",
+ "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": [
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
index 4217cd4f07..1538d93b2a 100644
--- 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
@@ -2,7 +2,7 @@
"payloadName": "asdc.nodes.network.Cinder.yml",
"contactId": "jh0003",
"name": "asdc.nodes.network.Cinder",
- "description": "Represents access to cloud shared storae.",
+ "description": "Represents access to Cloud shared storae.",
"resourceIconPath": "network",
"category": "Generic/Network Elements",
"tags": [
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
index 161897ac22..bb9560be88 100644
--- 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
@@ -2,7 +2,7 @@
"payloadName": "asdc.nodes.network.OAM.yml",
"contactId": "jh0003",
"name": "asdc.nodes.network.OAM",
- "description": "Represents AT&T Operation, Administration and Management (OA&M) network.",
+ "description": "Represents Operation, Administration and Management (OA&M) network.",
"resourceIconPath": "network",
"category": "Generic/Network Elements",
"tags": [
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
index da71792698..aecef6260d 100644
--- 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
@@ -325,13 +325,13 @@ node_types:
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
+ 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
+ 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
+ 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
@@ -343,54 +343,54 @@ node_types:
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
+ 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
+ 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
+ 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
+ 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
+ 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
+ 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
+ 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
+ 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
+ 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
+ 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 ##############
+ 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
+ description: Name assigned to vCE by cloud-PO
oam_loopback_vlan_ipaddres:
type: string
- description: IP Address assigned by Cloud-PO to OAM VLAN
+ 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
+ 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
+ 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
+ description: unique id assigned to VNF by cloud-PO - used for AAI metadata
#############CAPABILITIES of vCE - #########################
capabilities:
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
index 75f56d4c76..7f1a513fc1 100644
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/capabilityTypes.zip
+++ b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/capabilityTypes.zip
Binary files differ
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
index 31ddc8cbf6..a7ba8119d9 100644
--- 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
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.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
index 2076fb039b..f7ebded1d9 100644
--- 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
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.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
index 5808fc9338..cabbde3ac8 100644
--- 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
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.zip b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.CP/org.openecomp.resource.nfv.CP.zip
index 0fd24994f9..708d20f99f 100644
--- 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
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
index 95673b81ff..4fa3fe9bf4 100644
--- 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
@@ -1,6 +1,6 @@
{
"payloadName": "org.openecomp.resource.nfv.vdu.RoutingCategoryVDU.yaml",
- "contactId": "jh0003",
+ "attContact": "jh0003",
"name": "org.openecomp.resource.nfv.vdu.RoutingCategoryVDU",
"description": "Node Type that represents a Module",
"resourceIconPath": "defaulticon",
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
index 3853a341b0..68f16aaa96 100644
--- 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
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.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
index 1d5b041a88..47e3cbff2a 100644
--- 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
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.zip b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.VDU/org.openecomp.resource.nfv.VDU.zip
index 569a8b2a44..9e5c12189a 100644
--- 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
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
index e17b474385..d0f60bb7e3 100644
--- 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
@@ -1,6 +1,6 @@
{
"payloadName": "org.openecomp.resource.nfv.VDU.DHCPCategoryVDU.yaml",
- "contactId": "jh0003",
+ "attContact": "jh0003",
"resourceName": "org.openecomp.resource.nfv.VDU.DHCPCategoryVDU",
"description": "Node Type that represents a Module",
"resourceIconPath": "defaulticon",
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
index 64f150e73e..04aac7300e 100644
--- 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
@@ -3,7 +3,7 @@
##################################################################
org.openecomp.resource.nfv.VDU.DHCPCategoryVDU:
derived_from: org.openecomp.resource.nfv.VDU
- capabilities: #paharoni - added to connect to VCE_Brocade_VDU
+ capabilities: #paronin - added to connect to VCE_Brocade_VDU
dhcp:
type: org.openecomp.capabilities.nfv.VNF.DHCPCapability
description: This capability has been introduced
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
index d60b15698c..d55698f3e6 100644
--- 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
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
index 8c419d17d3..ca0f2c9ea8 100644
--- 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
@@ -1,6 +1,6 @@
{
"payloadName": "org.openecomp.resource.nfv.VDU.DNSCategoryVDU.yaml",
- "contactId": "jh0003",
+ "attContact": "jh0003",
"resourceName": "org.openecomp.resource.nfv.VDU.DNSCategoryVDU",
"description": "Node Type that represents a Module",
"resourceIconPath": "defaulticon",
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
index e927ad3d2a..f036a2fdd9 100644
--- 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
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.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
index 548b64ed17..aa453f0912 100644
--- 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
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
index be8f6fd133..67762f8c60 100644
--- 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
@@ -1,6 +1,6 @@
{
"payloadName": "org.openecomp.resource.nfv.VDU.NetworkAddrCategoryVDU.yaml",
- "contactId": "jh0003",
+ "attContact": "jh0003",
"resourceName": "org.openecomp.resource.nfv.VDU.NetworkAddrCategoryVDU",
"description": "Node Type that represents a Module",
"resourceIconPath": "defaulticon",
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
index 93ef2905f6..708d8a8521 100644
--- 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
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.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
index 0bad67331b..ce987de81f 100644
--- 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
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.zip b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VL/org.openecomp.resource.nfv.VL.zip
index b6d19de95b..a5029cd710 100644
--- 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
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
index 6e68301bcb..d191fe14cc 100644
--- 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
@@ -1,6 +1,6 @@
{
"payloadName": "org.openecomp.resource.nfv.VNF.VCE_Brocade_VNF.yaml",
- "contactId": "jh0003",
+ "attContact": "jh0003",
"resourceName": "org.openecomp.resource.nfv.VNF.VCE_Brocade_VNF",
"description": "Node Type that represents a Module",
"resourceIconPath": "defaulticon",
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
index 158f917ee8..403a7b8281 100644
--- 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
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
index 18ce8bbca5..2106ae9ff7 100644
--- 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
@@ -1,6 +1,6 @@
{
"payloadName": "org.openecomp.resource.nfv.VNF.yaml",
- "contactId": "jh0003",
+ "attContact": "jh0003",
"resourceName": "org.openecomp.resource.nfv.VNF",
"description": "Node Type that represents a Module",
"resourceIconPath": "defaulticon",
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
index 2b8e33d71a..1e14315fa7 100644
--- 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
Binary files differ
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
new file mode 100644
index 0000000000..a26149e8e5
--- /dev/null
+++ b/asdc-tests/src/test/resources/CI/importResourceTests/Derived_VFC/Derived_VFC.json
@@ -0,0 +1,26 @@
+{
+ "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
new file mode 100644
index 0000000000..949fa6e633
--- /dev/null
+++ b/asdc-tests/src/test/resources/CI/importResourceTests/Derived_VFC/normative-types-new-Derived_VFC.yml
@@ -0,0 +1,5 @@
+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
new file mode 100644
index 0000000000..dcc9eb37db
--- /dev/null
+++ b/asdc-tests/src/test/resources/CI/importResourceTests/Derived_VFC/normative-types-new-Derived_VFC.zip
Binary files differ
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
index bee0ffef8f..a91defb4f6 100644
--- 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
Binary files differ
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
index 940a74ab05..6146cb8524 100644
--- 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
Binary files differ
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
index cd75d64a89..069b3d1979 100644
--- 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
Binary files differ
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
index eb69428cf1..facd591e1d 100644
--- 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
Binary files differ
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
index be77395250..9efacc69eb 100644
--- 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
Binary files differ
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
index 3160c73fe7..688fe84b5f 100644
--- 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
Binary files differ
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
index 67b81c3d7f..5e2b0ac582 100644
--- 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
Binary files differ
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
index a092a1c14b..bf42a80ed9 100644
--- 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
Binary files differ
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
index 3005f9231f..75622b7c25 100644
--- 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
Binary files differ
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
index 46c652fd24..b6ccc062eb 100644
--- 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
Binary files differ
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
index 0ca8098ff9..97daa8e401 100644
--- 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
Binary files differ
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
index 9a1a28b1f6..5d3a7e6b50 100644
--- 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
Binary files differ
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
index 51a01c1bb9..7a458426b4 100644
--- 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
Binary files differ
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
index 21d14a9a73..d89b711cdb 100644
--- 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
Binary files differ
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
index bd5174df62..6cdde04c67 100644
--- 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
Binary files differ
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
index 45d8e192f1..5a53c7b5bf 100644
--- 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
Binary files differ
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
index 3a72360c25..2de80ad97a 100644
--- 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
Binary files differ
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
index 24294b9647..b6ae3ba9ad 100644
--- 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
Binary files differ
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
index 1d619e8c93..0ad7b6ee05 100644
--- 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
Binary files differ
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
index bda162b32f..895d397728 100644
--- 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
Binary files differ
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
index 3ecead7579..25a0312031 100644
--- 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
Binary files differ
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
index 6eb2d7e7af..46dc70477b 100644
--- 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
Binary files differ
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
index 538ba0e3ef..5cc2e4f916 100644
--- 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
Binary files differ
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
index a577aeb1e3..9ac3bb72e4 100644
--- 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
Binary files differ
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
index a9ec4d791e..88d67edc48 100644
--- 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
Binary files differ
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
index 9e76fbee46..04b32e1dee 100644
--- 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
Binary files differ
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
index 91b69dd746..b224b70d40 100644
--- 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
Binary files differ
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
index 747e215071..d7eb9f59b1 100644
--- 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
Binary files differ
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
index 10b1ce10ac..7fee84c8a5 100644
--- 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
Binary files differ
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
index 9a8f093d95..c7e65e7068 100644
--- 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
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeTestDataType/normative-types-new-validateProporties_typeMap.zip b/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeTestDataType/normative-types-new-validateProporties_typeMap.zip
deleted file mode 100644
index e8f0470948..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeTestDataType/normative-types-new-validateProporties_typeMap.zip
+++ /dev/null
Binary files differ
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
new file mode 100644
index 0000000000..27ce7bc887
--- /dev/null
+++ b/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeTestDataType/normative-types-new-validateProporties_typeTestDataType.zip
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importTypesTest/myHeatStack1/myHeatStack1.zip b/asdc-tests/src/test/resources/CI/importTypesTest/myHeatStack1/myHeatStack1.zip
index ee57b02826..2619853f4b 100644
--- a/asdc-tests/src/test/resources/CI/importTypesTest/myHeatStack1/myHeatStack1.zip
+++ b/asdc-tests/src/test/resources/CI/importTypesTest/myHeatStack1/myHeatStack1.zip
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importTypesTest/myHeatStack2/myHeatStack2.zip b/asdc-tests/src/test/resources/CI/importTypesTest/myHeatStack2/myHeatStack2.zip
index 1d75c7f4d0..7f43af70eb 100644
--- a/asdc-tests/src/test/resources/CI/importTypesTest/myHeatStack2/myHeatStack2.zip
+++ b/asdc-tests/src/test/resources/CI/importTypesTest/myHeatStack2/myHeatStack2.zip
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/CPWithAttributes.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/CPWithAttributes.yml
index afafe7510b..807f7fe630 100644
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/CPWithAttributes.yml
+++ b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/CPWithAttributes.yml
@@ -1,8 +1,7 @@
tosca_definitions_version: tosca_simple_yaml_1_0_0
node_types:
- org.openecomp.resource.cp.CP:
- derived_from: tosca.nodes.Root
+ org.openecomp.resource.cp.CP: derived_from: tosca.nodes.Root
properties:
type:
type: string
@@ -52,8 +51,6 @@ node_types:
type: tosca.datatypes.network.PortInfo
requirements:
- virtualLink:
- capability: tosca.capabilities.network.Linkable
- relationship: tosca.relationships.network.LinksTo
+ 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
+ capability: tosca.capabilities.network.Bindable relationship: tosca.relationships.network.BindsTo \ No newline at end of file
diff --git a/asdc-tests/tarball.xml b/asdc-tests/tarball.xml
deleted file mode 100644
index 18bc00854f..0000000000
--- a/asdc-tests/tarball.xml
+++ /dev/null
@@ -1,71 +0,0 @@
-<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
-xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
- <id>bin</id>
- <formats>
- <format>tar</format>
- </formats>
- <files>
- <file>
- <source>${project.build.directory}/${project.artifactId}-${project.version}-jar-with-dependencies.jar</source>
- <outputDirectory>./</outputDirectory>
- <destName>${project.artifactId}-${project.version}-jar-with-dependencies.jar</destName>
- </file>
- <file>
- <source>src/main/resources/ci/scripts/startTest.sh</source>
- <outputDirectory>./</outputDirectory>
- <destName>startTest.sh</destName>
- </file>
- <!--file>
- <source>src/main/resources/ci/scripts/postinstall</source>
- <outputDirectory>./</outputDirectory>
- <destName>postinstall</destName>
- </file-->
- <file>
- <source>src/main/resources/ci/conf/sdc.yaml</source>
- <outputDirectory>conf</outputDirectory>
- <destName>sdc.yaml</destName>
- </file>
- <file>
- <source>src/main/resources/ci/conf/sdc-packages.yaml</source>
- <outputDirectory>conf</outputDirectory>
- <destName>sdc-packages.yaml</destName>
- </file>
- <file>
- <source>src/main/resources/ci/conf/log4j.properties</source>
- <outputDirectory>conf</outputDirectory>
- <destName>log4j.properties</destName>
- </file>
- <file>
- <source>src/main/resources/ci/conf/titan.properties</source>
- <outputDirectory>conf</outputDirectory>
- <destName>titan.properties</destName>
- </file>
- <file>
- <source>${project.basedir}/../catalog-be/src/main/resources/config/error-configuration.yaml</source>
- <outputDirectory>conf</outputDirectory>
- <destName>error-configuration.yaml</destName>
- </file>
- <file>
- <source>${project.basedir}/../catalog-be/src/main/resources/config/configuration.yaml</source>
- <outputDirectory>conf</outputDirectory>
- <destName>configuration.yaml</destName>
- </file>
-
-
-
- </files>
-
- <fileSets>
- <fileSet>
- <directory>src/test/resources</directory>
- <outputDirectory>./</outputDirectory>
- </fileSet>
- <fileSet>
- <directory>src/main/resources/ci/testSuites</directory>
- <outputDirectory>./testSuites</outputDirectory>
- </fileSet>
-
- </fileSets>
-
-</assembly>
diff --git a/asdctool/.gitignore b/asdctool/.gitignore
index 72f53d03cf..4a95481e61 100644
--- a/asdctool/.gitignore
+++ b/asdctool/.gitignore
@@ -1,3 +1,2 @@
/bin/
/build/
-/target/
diff --git a/asdctool/.pydevproject b/asdctool/.pydevproject
deleted file mode 100644
index 40e9f40a0a..0000000000
--- a/asdctool/.pydevproject
+++ /dev/null
@@ -1,5 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" standalone="no"?>
-<?eclipse-pydev version="1.0"?><pydev_project>
-<pydev_property name="org.python.pydev.PYTHON_PROJECT_INTERPRETER">Default</pydev_property>
-<pydev_property name="org.python.pydev.PYTHON_PROJECT_VERSION">python 2.7</pydev_property>
-</pydev_project>
diff --git a/asdctool/pom.xml b/asdctool/pom.xml
index 142480c47d..cb31d553b7 100644
--- a/asdctool/pom.xml
+++ b/asdctool/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>sdctool</artifactId>
+ <artifactId>asdctool</artifactId>
<packaging>jar</packaging>
<parent>
@@ -11,120 +11,55 @@
<version>1.1.0-SNAPSHOT</version>
</parent>
-
<dependencies>
<dependency>
- <groupId>org.testng</groupId>
- <artifactId>testng</artifactId>
- <version>6.9.10</version>
- <scope>test</scope>
- </dependency>
-
- <dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
<scope>compile</scope>
</dependency>
- <dependency>
- <groupId>org.apache.commons</groupId>
- <artifactId>commons-lang3</artifactId>
- <version>${lang3.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <!--<dependency>-->
- <!--<groupId>org.springframework</groupId>-->
- <!--<artifactId>spring-beans</artifactId>-->
- <!--<version>${spring.version}</version>-->
- <!--<scope>provided</scope>-->
- <!--</dependency>-->
-
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-context-support</artifactId>
- <version>${spring.version}</version>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-messaging</artifactId>
- <version>${spring.version}</version>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-web</artifactId>
- <version>${spring.version}</version>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-webmvc</artifactId>
- <version>${spring.version}</version>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-aspects</artifactId>
- <version>${spring.version}</version>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-test</artifactId>
- <version>${spring.version}</version>
- <scope>test</scope>
- </dependency>
-
<!-- ASDC dependencies -->
<dependency>
<groupId>org.openecomp.sdc.be</groupId>
<artifactId>common-be</artifactId>
- <version>${common-be.version}</version>
+ <version>${project.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.openecomp.sdc</groupId>
<artifactId>common-app-api</artifactId>
- <version>${common-app-api.version}</version>
+ <version>${project.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.openecomp.sdc.be</groupId>
<artifactId>catalog-dao</artifactId>
- <version>${catalog-dao.version}</version>
+ <version>${project.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.openecomp.sdc.be</groupId>
<artifactId>catalog-model</artifactId>
- <version>${catalog-model.version}</version>
+ <version>${project.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.openecomp.sdc</groupId>
<artifactId>catalog-be</artifactId>
- <version>${asdc.full.version}</version>
-
+ <version>${project.version}</version>
+
<!-- Comment Out in order to debug in eclipse -->
<classifier>classes</classifier>
-
+
<scope>compile</scope>
- </dependency>
-
- <!-- ASDC dependencies end -->
+ </dependency>
+ <!-- ASDC dependencies end -->
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-server</artifactId>
@@ -136,37 +71,42 @@
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-jci-core</artifactId>
+ <version>${commons-jci-core.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlet</artifactId>
- <version>9.2.10.v20150310</version>
+ <version>${jetty.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
+ <version>${jersey-bom.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
+ <version>${jersey-bom.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-jetty-http</artifactId>
+ <version>${jersey-bom.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
+ <version>${jersey-bom.version}</version>
<scope>compile</scope>
</dependency>
@@ -181,38 +121,39 @@
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
- <version>1.7.10</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>
+
<!-- groovy -->
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
- <version>${groovy.version}</version>
+ <version>${groovy.version}</version>
<scope>compile</scope>
</dependency>
+
<dependency>
- <groupId>org.apache.commons</groupId>
- <artifactId>commons-configuration2</artifactId>
- <version>2.1</version>
+ <groupId>commons-configuration</groupId>
+ <artifactId>commons-configuration</artifactId>
+ <version>1.6</version>
<scope>compile</scope>
</dependency>
-
<!-- TITAN -->
<dependency>
<groupId>com.thinkaurelius.titan</groupId>
@@ -228,6 +169,13 @@
</dependency>
<dependency>
+ <groupId>com.googlecode.json-simple</groupId>
+ <artifactId>json-simple</artifactId>
+ <version>${json-simple.version}</version>
+ <scope>compile</scope>
+ </dependency>
+
+ <dependency>
<groupId>com.thinkaurelius.titan</groupId>
<artifactId>titan-cassandra</artifactId>
<version>${titan.version}</version>
@@ -259,7 +207,7 @@
<dependency>
<groupId>com.tinkerpop.blueprints</groupId>
<artifactId>blueprints-graph-sail</artifactId>
- <version>2.6.0</version>
+ <version>2.5.0</version>
<optional>true</optional>
<scope>compile</scope>
</dependency>
@@ -268,14 +216,14 @@
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
- <version>1.2.1-SNAPSHOT</version>
+ <version>${commons-logging}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
- <version>2.0-SNAPSHOT</version>
+ <version>${commons-codec}</version>
<scope>compile</scope>
</dependency>
<dependency>
@@ -295,27 +243,31 @@
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
- <version>${jackson.version}</version>
+ <version>${jackson.annotations.version}</version>
<scope>compile</scope>
</dependency>
+
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
- <version>2.3.1</version>
+ <version>${gson.version}</version>
<scope>compile</scope>
</dependency>
+
<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>
+
<!-- Spring 4 dependencies -->
<dependency>
<groupId>org.springframework</groupId>
@@ -330,24 +282,29 @@
<version>${spring.version}</version>
<scope>compile</scope>
</dependency>
+
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${spring.version}</version>
<scope>compile</scope>
</dependency>
+
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
- <version>4.0.7.RELEASE</version>
+ <version>${spring.version}</version>
+ <!--<version>4.0.7.RELEASE</version>-->
<scope>compile</scope>
</dependency>
+
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
<scope>compile</scope>
</dependency>
+
<!-- Spring 4 dependencies end -->
<!-- JavaConfig need this library -->
<dependency>
@@ -356,22 +313,25 @@
<version>3.2.4</version>
<scope>compile</scope>
</dependency>
+
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
- <version>1.14</version>
+ <version>${snakeyaml.version}</version>
<scope>compile</scope>
</dependency>
+
<dependency>
<groupId>org.functionaljava</groupId>
<artifactId>functionaljava</artifactId>
+ <version>${functionaljava.version}</version>
<scope>compile</scope>
</dependency>
-
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
+ <version>${elastic-search.version}</version>
<scope>compile</scope>
</dependency>
@@ -381,6 +341,7 @@
<version>${jackson.version}</version>
<scope>compile</scope>
</dependency>
+
<dependency>
<groupId>org.elasticsearch.plugin</groupId>
<artifactId>shield</artifactId>
@@ -395,12 +356,14 @@
<version>${cassandra.driver.version}</version>
<scope>compile</scope>
</dependency>
+
<dependency>
<groupId>com.datastax.cassandra</groupId>
<artifactId>cassandra-driver-mapping</artifactId>
<version>${cassandra.driver.version}</version>
<scope>compile</scope>
</dependency>
+
<!-- CASSANDRA END -->
<dependency>
<groupId>org.apache.poi</groupId>
@@ -408,38 +371,37 @@
<version>3.9.0.FINAL</version>
<scope>compile</scope>
</dependency>
+
<dependency>
<groupId>org.jdom</groupId>
<artifactId>jdom</artifactId>
<version>2.0.2</version>
<scope>compile</scope>
</dependency>
- <dependency>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-resources-plugin</artifactId>
- <version>3.0.2</version>
- </dependency>
+
<!-- Temporary, till building the populate task which adding all components
- to cache. We will use Serialization Utils. -->
+ to cache. We will use Serialization Utils. -->
<dependency>
<groupId>de.ruedigermoeller</groupId>
<artifactId>fst</artifactId>
<version>2.47</version>
<scope>compile</scope>
</dependency>
-
- <!-- testing -->
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>4.12</version>
- <scope>test</scope>
- </dependency>
- <!-- testing end -->
- </dependencies>
- <build>
- <plugins>
+ <!-- testing -->
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <version>${junit.version}</version>
+ <scope>test</scope>
+ </dependency>
+ <!-- testing end -->
+
+ </dependencies>
+
+ <build>
+ <plugins>
+
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
@@ -452,7 +414,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
- <version>2.5.5</version>
+ <version>2.6</version>
<executions>
<execution>
<id>create.jar.with.dependencies</id>
@@ -461,22 +423,14 @@
<goal>single</goal>
</goals>
<configuration>
-
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</execution>
- </executions>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-assembly-plugin</artifactId>
- <version>2.6</version>
- <executions>
<execution>
<configuration>
- <finalName>${project.artifactId}</finalName>
+ <finalName>sdctool</finalName>
<appendAssemblyId>false</appendAssemblyId>
<descriptor>${project.basedir}/tarball.xml</descriptor>
</configuration>
@@ -488,32 +442,59 @@
</execution>
</executions>
</plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-resources-plugin</artifactId>
- <version>3.0.2</version>
- <executions>
- <execution>
- <id>copy-sdctool-cassandra</id>
- <phase>install</phase>
- <goals>
- <goal>copy-resources</goal>
- </goals>
- <configuration>
- <outputDirectory>${project.parent.basedir}/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/files/default</outputDirectory>
- <resources>
- <resource>
- <directory>./target</directory>
- <includes>
- <include>sdctool.tar</include>
- </includes>
- </resource>
- </resources>
- </configuration>
- </execution>
- </executions>
- </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-resources-plugin</artifactId>
+ <version>3.0.2</version>
+
+ <executions>
+
+ <execution>
+ <id>copy-sdctool</id>
+ <phase>install</phase>
+ <goals>
+ <goal>copy-resources</goal>
+ </goals>
+ <configuration>
+ <outputDirectory>${project.parent.basedir}/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/files/default</outputDirectory>
+ <resources>
+ <resource>
+ <directory>./target</directory>
+ <includes>
+ <include>sdctool.tar</include>
+ </includes>
+ </resource>
+ </resources>
+ </configuration>
+ </execution>
+
+ </executions>
+ </plugin>
</plugins>
</build>
+
+ <profiles>
+ <profile>
+ <id>Fortify</id>
+ <activation>
+ <activeByDefault>false</activeByDefault>
+ </activation>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>com.fortify.ps.maven.plugin</groupId>
+ <artifactId>sca-maven-plugin</artifactId>
+ <version>4.30</version>
+ <configuration>
+ <source>1.8</source>
+ <buildId>${project.parent.artifactId}</buildId>
+ <toplevelArtifactId>${project.parent.artifactId}</toplevelArtifactId>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+ </profile>
+ </profiles>
</project>
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/App.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/App.java
new file mode 100644
index 0000000000..b433357db3
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/App.java
@@ -0,0 +1,66 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.asdctool;
+
+import org.eclipse.jetty.server.Server;
+import org.eclipse.jetty.servlet.ServletContextHandler;
+import org.eclipse.jetty.servlet.ServletHolder;
+
+/**
+ * Hello world!
+ *
+ */
+public class App {
+ public static void main(String[] args) {
+
+ String asdcToolPort = "8087";
+
+ ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
+ context.setContextPath("/asdctool");
+
+ Server jettyServer = new Server(Integer.valueOf(asdcToolPort));
+ jettyServer.setHandler(context);
+
+ ServletHolder jerseyServlet = context.addServlet(org.glassfish.jersey.servlet.ServletContainer.class, "/*");
+ jerseyServlet.setInitOrder(0);
+
+ // Tells the Jersey Servlet which REST service/class to load.
+ // jerseyServlet.setInitParameter("jersey.config.server.provider.classnames",
+ // EntryPoint.class.getCanonicalName());
+ jerseyServlet.setInitParameter("jersey.config.server.provider.packages", "org.openecomp.sdc.asdctool.servlets");
+ jerseyServlet.setInitParameter("jersey.config.server.provider.classnames",
+ "org.glassfish.jersey.media.multipart.MultiPartFeature");
+
+ try {
+ jettyServer.start();
+
+ System.out.println("Server was started on port " + asdcToolPort);
+
+ jettyServer.join();
+
+ } catch (Exception e) {
+ e.printStackTrace();
+ System.exit(1);
+ } finally {
+ jettyServer.destroy();
+ }
+ }
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/Utils.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/Utils.java
index 3b7d3ec11d..23612a80f1 100644
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/Utils.java
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/Utils.java
@@ -95,7 +95,7 @@ public class Utils {
if (rightValue == null) {
continue;
} else {
- log.debug("The key {} cannot be found in the properties {}", key, leftProps);
+ log.debug("The key {} cannot be found in the properties {}",key,leftProps);
return false;
}
}
@@ -103,7 +103,7 @@ public class Utils {
// if (false == leftValue instanceof Map && false == leftValue
// instanceof List) {
if (false == leftValue.equals(rightValue)) {
- log.trace("The value of key {} is different between properties {} vs {}", key, leftValue, rightValue);
+ log.trace("The value of key {} is differnet between properties. {} vs {}",key,leftValue,rightValue);
return false;
}
// }
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/DataMigration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/DataMigration.java
index a78ea9bc18..eafec8bf60 100644
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/DataMigration.java
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/DataMigration.java
@@ -608,7 +608,7 @@ public class DataMigration {
Files.delete(file.toPath());
}
} catch (IOException e) {
- log.error("failed to delete output file " + file.getAbsolutePath(), e);
+ log.error("failed to delete output file {}", file.getAbsolutePath(), e);
return null;
}
file = new File(outputDir + "/" + table.getTableDescription().getTableName());
@@ -617,7 +617,7 @@ public class DataMigration {
try {
file.createNewFile();
} catch (IOException e) {
- log.error("failed to create output file " + file.getAbsolutePath(), e);
+ log.error("failed to create output file {}", file.getAbsolutePath(), e);
return null;
}
}
@@ -662,11 +662,11 @@ public class DataMigration {
*/
private boolean createOutPutFolder(File outputDir) {
if (!outputDir.exists()) {
- log.info("creating output dir" + outputDir.getAbsolutePath());
+ log.info("creating output dir {}", outputDir.getAbsolutePath());
try {
Files.createDirectories(outputDir.toPath());
} catch (IOException e) {
- log.error("failed to create output dir" + outputDir.getAbsolutePath(), e);
+ log.error("failed to create output dir {}", outputDir.getAbsolutePath(), e);
return false;
}
}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/GraphJsonValidator.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/GraphJsonValidator.java
new file mode 100644
index 0000000000..2ad4faceb7
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/GraphJsonValidator.java
@@ -0,0 +1,57 @@
+package org.openecomp.sdc.asdctool.impl;
+
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicInteger;
+
+/**
+ * simple util class to verify that the titan export json graph is not corrupted
+ */
+public class GraphJsonValidator {
+
+ private static Logger log = LoggerFactory.getLogger(GraphJsonValidator.class.getName());
+
+ public boolean verifyTitanJson(String filePath) throws IOException {
+ ObjectMapper objectMapper = new ObjectMapper();
+ List<Integer> invalidRows = new ArrayList<>();
+ AtomicInteger atomicInteger = new AtomicInteger(1);
+ Files.lines(Paths.get(filePath)).forEach(line -> {
+ try {
+ verifyJsonLine(objectMapper, atomicInteger, line);
+ } catch (RuntimeException | IOException e) {
+ logInvalidJsonRow(atomicInteger, line, e);
+ invalidRows.add(atomicInteger.get());
+ }
+ });
+ return verificationResult(invalidRows);
+ }
+
+ private void verifyJsonLine(ObjectMapper objectMapper, AtomicInteger atomicInteger, String line) throws IOException {
+ log.info("verifying line: " + atomicInteger.get());
+ objectMapper.readTree(line);
+ atomicInteger.incrementAndGet();
+ }
+
+ private void logInvalidJsonRow(AtomicInteger atomicInteger, String line, Exception e) {
+ log.error("Invalid Json!!!!!!!!!!!!!!!!!!!!", e);
+ log.info("line number: " + atomicInteger.get());
+ log.info("line value: " + line);
+ }
+
+ private boolean verificationResult(List<Integer> invalidRows) {
+ if (!invalidRows.isEmpty()) {
+ log.info("the following lines are not valid: " + invalidRows);
+ return false;
+ }
+ return true;
+ }
+
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/GraphMLConverter.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/GraphMLConverter.java
index bf62072235..7bea2eaa4a 100644
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/GraphMLConverter.java
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/GraphMLConverter.java
@@ -390,15 +390,9 @@ public class GraphMLConverter {
// ElementHelper.getProperties(edge));
Utils.setProperties(addEdge, Utils.getProperties(edge));
- // log.info("fromVertex=" +
- // ElementHelper.getProperties(vertexFrom));
- log.info("fromVertex=" + Utils.getProperties(vertexFrom));
- // log.info("toVertex=" +
- // ElementHelper.getProperties(vertexTo));
- log.info("toVertex=" + Utils.getProperties(vertexTo));
- // log.info("edge=" + edge.getLabel() + " " +
- // ElementHelper.getProperties(edge));
- log.info("edge=" + edge.label() + " " + Utils.getProperties(edge));
+ log.info("fromVertex={}", Utils.getProperties(vertexFrom));
+ log.info("toVertex={}", Utils.getProperties(vertexTo));
+ log.info("edge={} {} ",edge.label(),Utils.getProperties(edge));
// GraphSONWriter.outputGraph(openGraph, outputFile);
GraphSONWriter create = GraphSONWriter.build().create();
@@ -410,15 +404,9 @@ public class GraphMLConverter {
} catch (Exception e) {
e.printStackTrace();
- // log.error("fromVertex=" +
- // ElementHelper.getProperties(vertexFrom));
- log.error("fromVertex=" + Utils.getProperties(vertexFrom));
- // log.error("toVertex=" +
- // ElementHelper.getProperties(vertexTo));
- log.error("toVertex=" + Utils.getProperties(vertexTo));
- // log.error("edge=" + edge.getLabel() + " " +
- // ElementHelper.getProperties(edge));
- log.error("edge=" + edge.label() + " " + Utils.getProperties(edge));
+ log.error("fromVertex={}", Utils.getProperties(vertexFrom));
+ log.error("toVertex={}", Utils.getProperties(vertexTo));
+ log.error("edge={} {} ",edge.label(),Utils.getProperties(edge));
break;
@@ -455,20 +443,13 @@ public class GraphMLConverter {
TitanGraph openGraph = Utils.openGraph(conf);
TitanVertex addVertexFrom = openGraph.addVertex();
- // ElementHelper.setProperties(addVertexFrom,
- // ElementHelper.getProperties(vertex));
Utils.setProperties(addVertexFrom, Utils.getProperties(vertex));
- // log.info("fromVertex=" +
- // ElementHelper.getProperties(addVertexFrom));
- log.info("fromVertex=" + Utils.getProperties(addVertexFrom));
+ log.info("fromVertex={}", Utils.getProperties(addVertexFrom));
- // GraphSONWriter.outputGraph(openGraph,
- // outputFile);
GraphSONWriter create = GraphSONWriter.build().create();
create.writeGraph(out, openGraph);
- // openGraph.rollback();
openGraph.tx().rollback();
}
@@ -476,25 +457,14 @@ public class GraphMLConverter {
} catch (Exception e) {
e.printStackTrace();
- // log.error("vertex=" +
- // ElementHelper.getProperties(vertex));
-
GraphPropertiesDictionary[] values = GraphPropertiesDictionary.values();
- // Object property1 =
- // vertex.getProperty(GraphPropertiesDictionary.HEALTH_CHECK.getProperty());
Object property1 = vertex.value(GraphPropertiesDictionary.HEALTH_CHECK.getProperty());
System.out.println(property1);
- // Object property2 = vertex.getProperty("healthcheck");
Object property2 = vertex.value("healthcheck");
System.out.println(property2);
- // for (GraphPropertiesDictionary value : values) {
- //
- // System.out.println(property);
- // }
-
break;
}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/PopulateComponentCache.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/PopulateComponentCache.java
index 812d534f49..eac972660f 100644
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/PopulateComponentCache.java
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/PopulateComponentCache.java
@@ -40,10 +40,8 @@ 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.cache.ComponentCache;
+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.ProductOperation;
-import org.openecomp.sdc.be.model.operations.impl.ResourceOperation;
-import org.openecomp.sdc.be.model.operations.impl.ServiceOperation;
import org.openecomp.sdc.be.resources.data.ComponentCacheData;
import org.openecomp.sdc.be.resources.data.ESArtifactData;
import org.openecomp.sdc.common.util.SerializationUtils;
@@ -66,21 +64,15 @@ public class PopulateComponentCache {
@Autowired
protected ComponentCassandraDao componentCassandraDao;
-
- @Autowired
- protected ResourceOperation resourceOperation;
-
- @Autowired
- protected ServiceOperation serviceOperation;
-
+
@Autowired
- protected ProductOperation productOperation;
+ ToscaOperationFacade toscaOperationFacade;
@Autowired
protected ComponentCache componentCache;
private void exit(String stage, int i) {
- log.error("Failed on " + stage);
+ log.error("Failed on {}", stage);
System.exit(i);
}
@@ -91,15 +83,16 @@ public class PopulateComponentCache {
populateCache(ComponentTypeEnum.PRODUCT);
}
+ @SuppressWarnings("unchecked")
private void populateCache(ComponentTypeEnum componentTypeEnum) {
List<String> list = new ArrayList<>();
- Either<TitanGraph, TitanOperationStatus> graph = resourceOperation.getTitanGenericDao().getGraph();
+ Either<TitanGraph, TitanOperationStatus> graph = toscaOperationFacade.getTitanDao().getGraph();
TitanGraph titanGraph = graph.left().value();
- Iterable vertices = titanGraph.query()
+ Iterable<TitanVertex> vertices = titanGraph.query()
.has(GraphPropertiesDictionary.LABEL.getProperty(), componentTypeEnum.name().toLowerCase()).vertices();
- Iterator iterator = vertices.iterator();
+ Iterator<TitanVertex> iterator = vertices.iterator();
while (iterator.hasNext()) {
TitanVertex vertex = (TitanVertex) iterator.next();
@@ -129,36 +122,11 @@ public class PopulateComponentCache {
///////////////////////////////////////////////////////////////////////////////////// there.
/////////////////////////////////////////////////////////////////////////////////////
Component component = null;
- switch (componentTypeEnum) {
- case RESOURCE:
- Either<Resource, StorageOperationStatus> resourceRes = resourceOperation.getComponent(componentUid,
- false);
- if (resourceRes.isRight()) {
- exit("get resource", 1);
- }
- component = resourceRes.left().value();
- break;
- case SERVICE:
- Either<Service, StorageOperationStatus> serviceRes = serviceOperation.getComponent(componentUid, false);
- if (serviceRes.isRight()) {
- exit("get service", 1);
- }
- component = serviceRes.left().value();
- break;
- case PRODUCT:
- Either<Product, StorageOperationStatus> productRes = productOperation.getComponent(componentUid, false);
- if (productRes.isRight()) {
- exit("get product", 1);
- }
- component = productRes.left().value();
- break;
- default:
- break;
- }
-
- if (component == null) {
+ Either<Resource, StorageOperationStatus> getComponentRes = toscaOperationFacade.getToscaElement(componentUid);
+ if (getComponentRes.isRight()) {
exit("get component", 1);
}
+ component = getComponentRes.left().value();
long time2 = System.currentTimeMillis();
// System.out.println("fetch resource " + resource.getName());
@@ -198,7 +166,7 @@ public class PopulateComponentCache {
* info("After adding component {} to cassandra. Insert time is {} ms."
* , componentUid, averageInsertTimeInMilli);
*
- * } catch (IOException e) { // TODO Auto-generated catch block
+ * } catch (IOException e) {
* e.printStackTrace(); }
*/
@@ -260,11 +228,11 @@ public class PopulateComponentCache {
}
}
long fullSearchEnd2 = System.currentTimeMillis();
- log.info("esofer time wait to threads finish " + ((fullSearchEnd2 - fullSearchStart2)) + " ms");
+ log.info("esofer time wait to threads finish {} ms",((fullSearchEnd2 - fullSearchStart2)));
// }
long fullSearchEnd = System.currentTimeMillis();
- log.info("esofer full desrialize time " + ((fullSearchEnd - fullSearchStart)) + " ms");
+ log.info("esofer full desrialize time {} ms",((fullSearchEnd - fullSearchStart)));
System.out.println("esofer full desrialize time " + ((fullSearchEnd - fullSearchStart)) + " ms");
}
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 c256ca09a4..c2ebc24d49 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
@@ -75,7 +75,7 @@ public class RestUtils {
}
return status;
} catch (IOException e) {
- log.error("Product uid:" + productUid + " delete failed with exception", e);
+ log.error("Product uid:{} delete failed with exception",productUid, e);
}
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
new file mode 100644
index 0000000000..3f63570ecd
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/TitanGraphInitializer.java
@@ -0,0 +1,404 @@
+package org.openecomp.sdc.asdctool.impl;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.tinkerpop.gremlin.structure.Edge;
+import org.apache.tinkerpop.gremlin.structure.Vertex;
+import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.dao.graph.datatype.ActionEnum;
+import org.openecomp.sdc.be.dao.graph.datatype.GraphElementTypeEnum;
+import org.openecomp.sdc.be.dao.neo4j.GraphEdgePropertiesDictionary;
+import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.openecomp.sdc.be.dao.utils.UserStatusEnum;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.openecomp.sdc.be.resources.data.UserData;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.thinkaurelius.titan.core.PropertyKey;
+import com.thinkaurelius.titan.core.TitanException;
+import com.thinkaurelius.titan.core.TitanFactory;
+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;
+
+public class TitanGraphInitializer {
+
+ private static Logger logger = LoggerFactory.getLogger(TitanGraphInitializer.class.getName());
+ private static TitanGraph graph;
+
+
+ public static boolean createGraph(String titanCfgFile) {
+ logger.info("** createGraph with {}", titanCfgFile);
+ try {
+ logger.info("createGraph : try to load file {}", titanCfgFile);
+ graph = TitanFactory.open(titanCfgFile);
+ if (graph.isClosed()) {
+ return false;
+ }
+
+ } catch (TitanException e) {
+ logger.info("createGraph : failed to open Titan graph with configuration file: {}", titanCfgFile, e);
+ return false;
+ }
+
+ createIndexesAndDefaults();
+
+ logger.info("** Titan graph created ");
+
+ return true;
+ }
+
+ private static boolean isVertexExist(Map<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 createDefaultUsers() {
+ List<UserData> users = createUserList();
+ for (UserData user : users) {
+ Vertex vertex = null;
+ Map<String, Object> checkedProperties = new HashMap<String, Object>();
+ checkedProperties.put(GraphPropertiesDictionary.USERID.getProperty(), user.getUserId());
+ checkedProperties.put(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.User.getName());
+ Map<String, Object> properties = null;
+ if (!isVertexExist(checkedProperties)) {
+ 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());
+ }
+ }
+ }
+ graph.tx().commit();
+
+ }
+
+ private static List<UserData> createUserList() {
+ LinkedList<UserData> users = new LinkedList<UserData>();
+ users.add(getDefaultUserAdmin1());
+ users.add(getDefaultUserAdmin2());
+ users.add(getDefaultUserDesigner1());
+ users.add(getDefaultUserDesigner2());
+ users.add(getDefaultUserTester1());
+ users.add(getDefaultUserTester2());
+ users.add(getDefaultUserTester3());
+ users.add(getDefaultUserGovernor1());
+ users.add(getDefaultUserGovernor2());
+ users.add(getDefaultUserOps1());
+ users.add(getDefaultUserOps2());
+ users.add(getDefaultUserProductManager1());
+ users.add(getDefaultUserProductManager2());
+ users.add(getDefaultUserProductStrategist1());
+ users.add(getDefaultUserProductStrategist2());
+ users.add(getDefaultUserProductStrategist3());
+ return users;
+ }
+
+ private static UserData getDefaultUserAdmin1() {
+ 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 UserData getDefaultUserAdmin2() {
+ UserData userData = new UserData();
+ userData.setAction(ActionEnum.Create);
+ userData.setElementType(GraphElementTypeEnum.Node);
+ userData.setUserId("tr0001");
+ userData.setEmail("admin@sdc.com");
+ userData.setFirstName("Todd");
+ userData.setLastName("Rundgren");
+ userData.setRole("ADMIN");
+ userData.setStatus(UserStatusEnum.ACTIVE.name());
+ userData.setLastLoginTime(0L);
+ return userData;
+ }
+
+ private static UserData getDefaultUserDesigner1() {
+ UserData userData = new UserData();
+ userData.setAction(ActionEnum.Create);
+ userData.setElementType(GraphElementTypeEnum.Node);
+ userData.setUserId("cs0008");
+ userData.setEmail("designer@sdc.com");
+ userData.setFirstName("Carlos");
+ userData.setLastName("Santana");
+ userData.setRole("DESIGNER");
+ userData.setStatus(UserStatusEnum.ACTIVE.name());
+ userData.setLastLoginTime(0L);
+ return userData;
+ }
+
+ private static UserData getDefaultUserDesigner2() {
+ UserData userData = new UserData();
+ userData.setAction(ActionEnum.Create);
+ userData.setElementType(GraphElementTypeEnum.Node);
+ userData.setUserId("me0009");
+ userData.setEmail("designer@sdc.com");
+ userData.setFirstName("Melissa");
+ userData.setLastName("Etheridge");
+ userData.setRole("DESIGNER");
+ userData.setStatus(UserStatusEnum.ACTIVE.name());
+ userData.setLastLoginTime(0L);
+ return userData;
+ }
+
+ private static UserData getDefaultUserTester1() {
+ UserData userData = new UserData();
+ userData.setAction(ActionEnum.Create);
+ userData.setElementType(GraphElementTypeEnum.Node);
+ userData.setUserId("jm0007");
+ userData.setEmail("tester@sdc.com");
+ userData.setFirstName("Joni");
+ userData.setLastName("Mitchell");
+ userData.setRole("TESTER");
+ userData.setStatus(UserStatusEnum.ACTIVE.name());
+ userData.setLastLoginTime(0L);
+ return userData;
+ }
+
+ private static UserData getDefaultUserTester2() {
+ UserData userData = new UserData();
+ userData.setAction(ActionEnum.Create);
+ userData.setElementType(GraphElementTypeEnum.Node);
+ userData.setUserId("kb0004");
+ userData.setEmail("tester@sdc.com");
+ userData.setFirstName("Kate");
+ userData.setLastName("Bush");
+ userData.setRole("TESTER");
+ userData.setStatus(UserStatusEnum.ACTIVE.name());
+ userData.setLastLoginTime(0L);
+ return userData;
+ }
+
+ private static UserData getDefaultUserTester3() {
+ UserData userData = new UserData();
+ userData.setAction(ActionEnum.Create);
+ userData.setElementType(GraphElementTypeEnum.Node);
+ userData.setUserId("jt0005");
+ userData.setEmail("tester@sdc.com");
+ userData.setFirstName("James");
+ userData.setLastName("Taylor");
+ userData.setRole("TESTER");
+ userData.setStatus(UserStatusEnum.ACTIVE.name());
+ userData.setLastLoginTime(0L);
+ return userData;
+ }
+
+ private static UserData getDefaultUserOps1() {
+ UserData userData = new UserData();
+ userData.setAction(ActionEnum.Create);
+ userData.setElementType(GraphElementTypeEnum.Node);
+ userData.setUserId("op0001");
+ userData.setEmail("ops@sdc.com");
+ userData.setFirstName("Steve");
+ userData.setLastName("Regev");
+ userData.setRole("OPS");
+ userData.setStatus(UserStatusEnum.ACTIVE.name());
+ userData.setLastLoginTime(0L);
+ return userData;
+ }
+
+ private static UserData getDefaultUserOps2() {
+ UserData userData = new UserData();
+ userData.setAction(ActionEnum.Create);
+ userData.setElementType(GraphElementTypeEnum.Node);
+ userData.setUserId("af0006");
+ userData.setEmail("designer@sdc.com");
+ userData.setFirstName("Aretha");
+ userData.setLastName("Franklin");
+ userData.setRole("OPS");
+ userData.setStatus(UserStatusEnum.ACTIVE.name());
+ userData.setLastLoginTime(0L);
+ return userData;
+ }
+
+ private static UserData getDefaultUserGovernor1() {
+ UserData userData = new UserData();
+ userData.setAction(ActionEnum.Create);
+ userData.setElementType(GraphElementTypeEnum.Node);
+ userData.setUserId("gv0001");
+ userData.setEmail("governor@sdc.com");
+ userData.setFirstName("David");
+ userData.setLastName("Shadmi");
+ userData.setRole("GOVERNOR");
+ userData.setStatus(UserStatusEnum.ACTIVE.name());
+ userData.setLastLoginTime(0L);
+ return userData;
+ }
+
+ private static UserData getDefaultUserGovernor2() {
+ UserData userData = new UserData();
+ userData.setAction(ActionEnum.Create);
+ userData.setElementType(GraphElementTypeEnum.Node);
+ userData.setUserId("ah0002");
+ userData.setEmail("admin@sdc.com");
+ userData.setFirstName("Alex");
+ userData.setLastName("Harvey");
+ userData.setRole("GOVERNOR");
+ userData.setStatus(UserStatusEnum.ACTIVE.name());
+ userData.setLastLoginTime(0L);
+ return userData;
+ }
+
+ private static UserData getDefaultUserProductManager1() {
+ UserData userData = new UserData();
+ userData.setAction(ActionEnum.Create);
+ userData.setElementType(GraphElementTypeEnum.Node);
+ userData.setUserId("pm0001");
+ userData.setEmail("pm1@sdc.com");
+ userData.setFirstName("Teddy");
+ userData.setLastName("Isashar");
+ userData.setRole("PRODUCT_MANAGER");
+ userData.setStatus(UserStatusEnum.ACTIVE.name());
+ userData.setLastLoginTime(0L);
+ return userData;
+ }
+
+ private static UserData getDefaultUserProductManager2() {
+ UserData userData = new UserData();
+ userData.setAction(ActionEnum.Create);
+ userData.setElementType(GraphElementTypeEnum.Node);
+ userData.setUserId("pm0002");
+ userData.setEmail("pm2@sdc.com");
+ userData.setFirstName("Sarah");
+ userData.setLastName("Bettens");
+ userData.setRole("PRODUCT_MANAGER");
+ userData.setStatus(UserStatusEnum.ACTIVE.name());
+ userData.setLastLoginTime(0L);
+ return userData;
+ }
+
+ private static UserData getDefaultUserProductStrategist1() {
+ UserData userData = new UserData();
+ userData.setAction(ActionEnum.Create);
+ userData.setElementType(GraphElementTypeEnum.Node);
+ userData.setUserId("ps0001");
+ userData.setEmail("ps1@sdc.com");
+ userData.setFirstName("Eden");
+ userData.setLastName("Rozin");
+ userData.setRole("PRODUCT_STRATEGIST");
+ userData.setStatus(UserStatusEnum.ACTIVE.name());
+ userData.setLastLoginTime(0L);
+ return userData;
+ }
+
+ private static UserData getDefaultUserProductStrategist2() {
+ UserData userData = new UserData();
+ userData.setAction(ActionEnum.Create);
+ userData.setElementType(GraphElementTypeEnum.Node);
+ userData.setUserId("ps0002");
+ userData.setEmail("ps2@sdc.com");
+ userData.setFirstName("Ella");
+ userData.setLastName("Kvetny");
+ userData.setRole("PRODUCT_STRATEGIST");
+ userData.setStatus(UserStatusEnum.ACTIVE.name());
+ userData.setLastLoginTime(0L);
+ return userData;
+ }
+
+ private static UserData getDefaultUserProductStrategist3() {
+ UserData userData = new UserData();
+ userData.setAction(ActionEnum.Create);
+ userData.setElementType(GraphElementTypeEnum.Node);
+ userData.setUserId("ps0003");
+ userData.setEmail("ps3@sdc.com");
+ userData.setFirstName("Geva");
+ userData.setLastName("Alon");
+ userData.setRole("PRODUCT_STRATEGIST");
+ userData.setStatus(UserStatusEnum.ACTIVE.name());
+ userData.setLastLoginTime(0L);
+ return userData;
+ }
+
+ private static void createVertexIndixes() {
+ logger.info("** createVertexIndixes started");
+
+ 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();
+ createDefaultUsers();
+ }
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/UpdatePropertyOnVertex.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/UpdatePropertyOnVertex.java
index b480091723..0336701b2d 100644
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/UpdatePropertyOnVertex.java
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/UpdatePropertyOnVertex.java
@@ -73,7 +73,7 @@ public class UpdatePropertyOnVertex {
Map<String, Object> leftProps = Utils.getProperties(vertex);
boolean vertexLeftContainsRightProps = Utils.vertexLeftContainsRightProps(leftProps, criteria);
if (false == vertexLeftContainsRightProps) {
- log.debug("Ignore vertex since properties it does not contains properties {}. Vertex properties are: {}", criteria, leftProps);
+ log.debug("Ignore vertex since properties it does not contains properties {}. Vertex properties are {}",criteria,leftProps);
continue;
}
@@ -90,7 +90,7 @@ public class UpdatePropertyOnVertex {
}
} else {
- log.debug("No certified service was found for criteria {}", criteria);
+ log.debug("No certified service was found for criteria {}",criteria);
}
}
@@ -137,7 +137,7 @@ public class UpdatePropertyOnVertex {
boolean vertexLeftContainsRightProps = Utils.vertexLeftContainsRightProps(leftProps, criteria);
if (false == vertexLeftContainsRightProps) {
- log.debug("Ignore vertex since properties it does not contains properties {}. Vertex properties are {}", criteria, leftProps);
+ log.debug("Ignore vertex since properties it does not contains properties {}. Vertex properties are {}",criteria,leftProps);
continue;
}
@@ -148,16 +148,12 @@ public class UpdatePropertyOnVertex {
// vertex.setProperty(key, value);
vertex.property(key, value);
- //if(log.isDebugEnabled()){
- // log.debug("After setting vertex: {} {} with key value: {}, {}",
- // vertex.getProperty(GraphPropertiesDictionary.NAME.getProperty()),
- // vertex.getProperty(GraphPropertiesDictionary.VERSION.getProperty()),
- // key, value);
- //}
- log.debug("After setting vertex: {} {} with key value: {}, {}",
+
+ if (log.isDebugEnabled()){
+ log.debug("After setting vertex {} {} with key value {},{}",
vertex.property(GraphPropertiesDictionary.NAME.getProperty()),
- vertex.property(GraphPropertiesDictionary.VERSION.getProperty()),
- key, value);
+ vertex.property(GraphPropertiesDictionary.VERSION.getProperty()),key,value);
+ }
numberOfUpdatedVertexesPerService++;
}
}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/Migration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/Migration.java
new file mode 100644
index 0000000000..d74bae6087
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/Migration.java
@@ -0,0 +1,17 @@
+package org.openecomp.sdc.asdctool.impl.migration;
+
+public interface Migration {
+
+ /**
+ * performs a migration operation
+ * @return true if migration completed successfully or false otherwise
+ */
+ boolean migrate();
+
+ /**
+ *
+ * @return a description of what this migration does
+ */
+ String description();
+
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/MigrationException.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/MigrationException.java
new file mode 100644
index 0000000000..f54fccc0c1
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/MigrationException.java
@@ -0,0 +1,9 @@
+package org.openecomp.sdc.asdctool.impl.migration;
+
+public class MigrationException extends RuntimeException {
+
+ public MigrationException(String message) {
+ super(message);
+ }
+
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/MigrationMsg.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/MigrationMsg.java
new file mode 100644
index 0000000000..3f8b55b3a5
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/MigrationMsg.java
@@ -0,0 +1,36 @@
+package org.openecomp.sdc.asdctool.impl.migration;
+
+public enum MigrationMsg {
+ RENMAE_KEY_PROPERTIES_1707("renaming key properties"),
+ KEY_PROPERTY_NOT_EXIST("key propery %s not exist"),
+ RENAME_KEY_PROPERTY_FAILED("failed to rename key property %s"),
+ FAILED_TO_RETRIEVE_GRAPH("failed to get graph %s"),
+ PROPERTY_KEY_NOT_EXIST("property key %s not found."),
+ FAILED_TO_RETRIEVE_NODES("failed to retrieve nodes from graph. error status: %s"),
+ FAILED_TO_GET_NODE_FROM_GRAPH("failed to retrieve node from graph. error status : %s"),
+ FAILED_TO_CREATE_NODE("failed to create node of type %s. reason: %s"),
+ FAILED_TO_RETRIEVE_CATEGORIES("failed to retrieve categories. error status: %s"),
+ FAILED_TO_RETRIEVE_CATEGORY("failed to retrieve category %s. error status: %s"),
+ FAILED_TO_CREATE_SUB_CATEGORY("failed to create sub category %s of category %s. error status: %s"),
+ FAILED_TO_CREATE_CATEGORY("failed to create category %s. error status: %s"),
+ FAILED_TO_RETRIEVE_USER_STATES("failed to retrieve user %s states. error status: %s"),
+ FAILED_TO_RETRIEVE_MIGRATION_USER_STATES("failed to retrieve migrating user %s states for deletion. error status: %s"),
+ FAILED_TO_RETRIEVE_MIGRATION_USER("failed to retrieve migration user %s. error status: %s"),
+ FAILED_TO_RETRIEVE_VERSION_RELATION("failed to retrieve version relation from component with id %s to component with id %s. error status: %s"),
+ FAILED_TO_RETRIEVE_REQ_CAP("failed to retrieve fulfilled requirements or capabilities for instance %s. error status: %s"),
+ FAILED_TO_RETRIEVE_VERTEX("failed to retrieve vertex with id: %s. error status: %s"),
+ FAILED_TO_RETRIEVE_CAP_REQ_VERTEX("failed to retrieve capabilities or requirements vertex for component %s. error status: %s"),
+ FAILED_TO_ASSOCIATE_CAP_REQ("failed to associate fulfilled capabilities or requirements for components %s. error status: %s"),
+ FAILED_TO_RETRIEVE_TOSCA_DEF("failed to retrieve tosca definition for requirement or capability %s. error status %s"),
+ ;
+
+ private String message;
+
+ MigrationMsg(String migrationDescription) {
+ this.message = migrationDescription;
+ }
+
+ public String getMessage(String ... msgProperties) {
+ return String.format(this.message, msgProperties);
+ }
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/MigrationOperationUtils.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/MigrationOperationUtils.java
new file mode 100644
index 0000000000..a4595b2ec8
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/MigrationOperationUtils.java
@@ -0,0 +1,119 @@
+package org.openecomp.sdc.asdctool.impl.migration;
+
+import com.thinkaurelius.titan.core.PropertyKey;
+import com.thinkaurelius.titan.core.TitanGraph;
+import com.thinkaurelius.titan.core.TitanVertex;
+import com.thinkaurelius.titan.core.schema.TitanManagement;
+import fj.data.Either;
+import org.apache.tinkerpop.gremlin.structure.VertexProperty;
+import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
+import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+import java.util.Map;
+import java.util.Optional;
+
+@Component("migrationUtils")
+public class MigrationOperationUtils {
+
+ private static Logger log = LoggerFactory.getLogger(MigrationOperationUtils.class);
+
+ @Autowired
+ private TitanGenericDao titanGenericDao;
+
+ /**
+ * rename a set or property keys
+ *
+ * @param propertyKeys a mapping between the old property key name and the property key name to replace it with
+ *
+ * @return true if rename ended successfully or false otherwise
+ */
+ public boolean renamePropertyKeys(Map<String, String> propertyKeys) {
+ Either<TitanGraph, TitanOperationStatus> graph = titanGenericDao.getGraph();
+ return graph.either((titanGraph) -> renamePropertyKeys(titanGraph, propertyKeys),
+ (titanOperationStatus) -> operationFailed(MigrationMsg.FAILED_TO_RETRIEVE_GRAPH.getMessage(titanOperationStatus.name())));
+ }
+
+ private boolean renamePropertyKeys(TitanGraph titanGraph, Map<String, String> propertyKeys) {
+ try {
+ for (Map.Entry<String, String> propertyKeyEntry : propertyKeys.entrySet()) {
+ boolean renameSucceeded = renamePropertyKey(titanGraph, propertyKeyEntry);
+ if (!renameSucceeded) {
+ return false;
+ }
+ }
+ return true;
+ } catch (RuntimeException e) {
+ log.error(e.getMessage(), e);
+ return false;
+ }
+ }
+
+ private Boolean renamePropertyKey(TitanGraph titanGraph, Map.Entry<String, String> propertyKeyEntry) {
+ String renameFromKey = propertyKeyEntry.getKey();
+ String renameToKey = propertyKeyEntry.getValue();
+ log.info(String.format("renaming property key %s to %s", renameFromKey, renameToKey));
+ return renameProperty(titanGraph, renameFromKey, renameToKey);
+ }
+
+ private Boolean renameProperty(TitanGraph titanGraph, String renameFromKey, String renameToKey) {
+ if (titanGraph.containsPropertyKey(renameFromKey) && titanGraph.containsPropertyKey(renameToKey)) {//new property already exist, we cant rename to it we need to add new and remove old on every vertices which has the old one.
+ return renamePropertyOnEachVertex(titanGraph, renameFromKey, renameToKey);
+ }
+ return renamePropertyOnGraphLevel(titanGraph, renameFromKey, renameToKey);
+ }
+
+ private Boolean renamePropertyOnGraphLevel(TitanGraph titanGraph, String renameFromKey, String renameToKey) {
+ TitanManagement titanManagement = titanGraph.openManagement();
+ return Optional.ofNullable(titanManagement.getPropertyKey(renameFromKey))
+ .map(propertyKey -> renamePropertyOnGraph(titanManagement, propertyKey, renameToKey))
+ .orElseGet(() -> {log.info(MigrationMsg.PROPERTY_KEY_NOT_EXIST.getMessage(renameFromKey)); return true;}) ;//if property key not exist rename is considered to be successful
+ }
+
+ private boolean renamePropertyOnEachVertex(TitanGraph graph, String oldKey, String newKey) {
+ addNewPropertyKeyOnVertices(graph, oldKey, newKey);
+ removeOldPropertyKeyFromGraph(graph, oldKey);
+ graph.tx().commit();
+ return true;
+ }
+
+ private void removeOldPropertyKeyFromGraph(TitanGraph graph, String oldKey) {
+ graph.getPropertyKey(oldKey).remove();
+ }
+
+ private void addNewPropertyKeyOnVertices(TitanGraph graph, String oldKey, String newKey) {
+ graph.query().has(oldKey).vertices().forEach(titanVertex -> {
+ copyOldKeyValueAndDropKey(oldKey, newKey, (TitanVertex) titanVertex);
+ });
+ }
+
+ private void copyOldKeyValueAndDropKey(String oldKey, String newKey, TitanVertex titanVertex) {
+ VertexProperty<Object> oldProperty = titanVertex.property(oldKey);
+ Object oldKeyValue = oldProperty.value();
+
+ titanVertex.property(newKey, oldKeyValue);
+ oldProperty.remove();
+ }
+
+ private boolean renamePropertyOnGraph(TitanManagement titanManagement, PropertyKey fromPropertyKey, String toKey) {
+ try {
+ titanManagement.changeName(fromPropertyKey, toKey);
+ titanManagement.commit();
+ return true;
+ } catch (RuntimeException e) {
+ log.error(MigrationMsg.RENAME_KEY_PROPERTY_FAILED.getMessage(fromPropertyKey.name()), e.getMessage());
+ titanManagement.rollback();
+ return false;
+ }
+ }
+
+ private boolean operationFailed(String errorMessage) {
+ log.error(errorMessage);
+ return false;
+ }
+
+
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/AddGroupUuid.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/AddGroupUuid.java
index db8fee0fa2..03583fdfec 100644
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/AddGroupUuid.java
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/AddGroupUuid.java
@@ -90,7 +90,7 @@ public class AddGroupUuid {
groupUUID = UniqueIdBuilder.generateUUID();
- log.debug("Before updating groups {} with groupUUID {}", builder.toString(), groupUUID);
+ log.debug("Before updating groups {} with groupUUID {}",builder.toString(),groupUUID);
for (GroupData groupData : groupsData) {
@@ -99,21 +99,20 @@ public class AddGroupUuid {
Either<GroupData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(groupData,
GroupData.class);
if (updateNode.isRight()) {
- log.error("Failed to update group " + groupData + ". Error is {}",
- updateNode.right().value().toString());
+ log.error("Failed to update group {}. Error is {}",groupData,updateNode.right().value().toString());
result = false;
return result;
}
}
- log.debug("After updating groups {} with groupUUID {}", builder.toString(), groupUUID);
+ log.debug("After updating groups {} with groupUUID {}",builder.toString(),groupUUID);
}
}
}
- log.info("The number of groups updated with groupUUID is " + numberOfUpdates);
+ log.info("The number of groups updated with groupUUID is {}", numberOfUpdates);
return result;
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/AllowMultipleHeats.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/AllowMultipleHeats.java
index 561cfb5a5b..3c9d6fa08f 100644
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/AllowMultipleHeats.java
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/AllowMultipleHeats.java
@@ -68,7 +68,7 @@ public class AllowMultipleHeats {
}
List<ArtifactData> list = allHeatArtifacts.left().value();
- log.debug("Found {} artifacts with label {}", (list == null ? 0 : list.size()), artifactLabel);
+ log.debug("Found {} artifacts with label {}",(list == null ? 0 : list.size()),artifactLabel);
if (list != null && false == list.isEmpty()) {
@@ -87,7 +87,7 @@ public class AllowMultipleHeats {
for (ArtifactData artifactData : artifactsToDelete) {
// System.out.println("Going to delete artifact " +
// artifactData);
- log.debug("Going to delete artifact {}", artifactData);
+ log.debug("Going to delete artifact {}",artifactData);
Either<ArtifactData, TitanOperationStatus> deleteNode = titanGenericDao.deleteNode(artifactData,
ArtifactData.class);
if (deleteNode.isRight()) {
@@ -95,12 +95,12 @@ public class AllowMultipleHeats {
result = false;
return result;
} else {
- log.debug("Delete artifact node {}", deleteNode.left().value());
+ log.debug("Delete artifact node {}",deleteNode.left().value());
}
}
}
- log.debug("Number of deleted artifacts is {}", artifactsToDelete.size());
+ log.debug("Number of deleted artifacts is {}",artifactsToDelete.size());
int counter = 0;
if (false == artifactsToUpdate.isEmpty()) {
@@ -110,7 +110,7 @@ public class AllowMultipleHeats {
if (artifactData.getArtifactDataDefinition().getMandatory() != null
&& true == artifactData.getArtifactDataDefinition().getMandatory()) {
- log.debug("Going to update artifact {}", artifactData);
+ log.debug("Going to update artifact {}",artifactData);
counter++;
artifactData.getArtifactDataDefinition().setMandatory(false);
Either<ArtifactData, TitanOperationStatus> updatedNode = titanGenericDao
@@ -120,13 +120,13 @@ public class AllowMultipleHeats {
result = false;
return result;
} else {
- log.debug("Update artifact node {}", updatedNode.left().value());
+ log.debug("Update artifact node {}",updatedNode.left().value());
}
}
}
}
- log.debug("Number of updated artifacts is {}", counter);
+ log.debug("Number of updated artifacts is {}",counter);
return result;
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/AppConfig.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/AppConfig.java
index b529935a38..514c28b9b1 100644
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/AppConfig.java
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/AppConfig.java
@@ -21,73 +21,63 @@
package org.openecomp.sdc.asdctool.impl.migration.v1604;
import org.openecomp.sdc.asdctool.impl.PopulateComponentCache;
+import org.openecomp.sdc.asdctool.impl.migration.MigrationOperationUtils;
import org.openecomp.sdc.asdctool.impl.migration.v1607.CsarMigration;
import org.openecomp.sdc.asdctool.impl.migration.v1610.TitanFixUtils;
import org.openecomp.sdc.asdctool.impl.migration.v1610.ToscaArtifactsAlignment;
+import org.openecomp.sdc.asdctool.impl.migration.v1702.DataTypesUpdate;
+import org.openecomp.sdc.asdctool.impl.migration.v1702.Migration1702;
+import org.openecomp.sdc.asdctool.impl.migration.v1707.VfModulesPropertiesAdding;
import org.openecomp.sdc.be.auditing.api.IAuditingManager;
import org.openecomp.sdc.be.auditing.impl.AuditingManager;
import org.openecomp.sdc.be.components.distribution.engine.IDistributionEngine;
import org.openecomp.sdc.be.components.distribution.engine.ServiceDistributionArtifactsBuilder;
-import org.openecomp.sdc.be.components.impl.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.ProductComponentInstanceBusinessLogic;
-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.*;
import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao;
import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao;
import org.openecomp.sdc.be.dao.cassandra.CassandraClient;
import org.openecomp.sdc.be.dao.cassandra.ComponentCassandraDao;
+import org.openecomp.sdc.be.dao.cassandra.SdcSchemaFilesCassandraDao;
+import org.openecomp.sdc.be.dao.config.DAOSpringConfig;
import org.openecomp.sdc.be.dao.es.ElasticSearchClient;
import org.openecomp.sdc.be.dao.impl.AuditingDao;
import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
-import org.openecomp.sdc.be.dao.titan.TitanGraphClient;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
import org.openecomp.sdc.be.model.cache.ComponentCache;
+import org.openecomp.sdc.be.model.jsontitan.operations.GroupsOperation;
import org.openecomp.sdc.be.model.operations.api.IAdditionalInformationOperation;
import org.openecomp.sdc.be.model.operations.api.IElementOperation;
import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation;
import org.openecomp.sdc.be.model.operations.api.IUserAdminOperation;
-import org.openecomp.sdc.be.model.operations.impl.AdditionalInformationOperation;
-import org.openecomp.sdc.be.model.operations.impl.ArtifactOperation;
-import org.openecomp.sdc.be.model.operations.impl.AttributeOperation;
-import org.openecomp.sdc.be.model.operations.impl.CacheMangerOperation;
-import org.openecomp.sdc.be.model.operations.impl.CapabilityInstanceOperation;
-import org.openecomp.sdc.be.model.operations.impl.CapabilityOperation;
-import org.openecomp.sdc.be.model.operations.impl.CapabilityTypeOperation;
-import org.openecomp.sdc.be.model.operations.impl.ComponentInstanceOperation;
-import org.openecomp.sdc.be.model.operations.impl.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.GroupOperation;
-import org.openecomp.sdc.be.model.operations.impl.GroupTypeOperation;
-import org.openecomp.sdc.be.model.operations.impl.HeatParametersOperation;
-import org.openecomp.sdc.be.model.operations.impl.InputsOperation;
-import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
-import org.openecomp.sdc.be.model.operations.impl.LifecycleOperation;
-import org.openecomp.sdc.be.model.operations.impl.OnboardingClient;
-import org.openecomp.sdc.be.model.operations.impl.ProductOperation;
-import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
-import org.openecomp.sdc.be.model.operations.impl.RequirementOperation;
-import org.openecomp.sdc.be.model.operations.impl.ResourceOperation;
-import org.openecomp.sdc.be.model.operations.impl.ServiceOperation;
-import org.openecomp.sdc.be.model.operations.impl.UserAdminOperation;
+import org.openecomp.sdc.be.model.operations.impl.*;
import org.openecomp.sdc.be.tosca.CsarUtils;
import org.openecomp.sdc.be.tosca.ToscaExportHandler;
import org.openecomp.sdc.be.user.IUserBusinessLogic;
import org.openecomp.sdc.be.user.UserBusinessLogic;
+import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.Import;
+import org.springframework.context.annotation.Primary;
@Configuration
+@Import(DAOSpringConfig.class)
public class AppConfig {
+
+ @Bean(name = "sdc-schema-files-cassandra-dao")
+ public SdcSchemaFilesCassandraDao sdcSchemaFilesCassandraDao() {
+ return new SdcSchemaFilesCassandraDao();
+ }
+ @Bean(name = "componentsUtils")
+ public ComponentsUtils componentsUtils() {
+ return new ComponentsUtils();
+ }
+ @Bean(name = "updateDataTypes")
+ public DataTypesUpdate dataTypesUpdate() {
+ return new DataTypesUpdate();
+ }
@Bean(name = "serviceMigrationBean")
public ServiceMigration serviceMigration() {
return new ServiceMigration();
@@ -113,16 +103,6 @@ public class AppConfig {
return new CsarMigration();
}
- @Bean(name = "titan-generic-dao")
- public TitanGenericDao titanGenericDao() {
- return new TitanGenericDao();
- }
-
- @Bean(name = "titan-client", initMethod = "createGraph")
- public TitanGraphClient titanClient() {
- return new TitanGraphClient();
- }
-
@Bean(name = "resource-operation")
public ResourceOperation resourceOperation() {
return new ResourceOperation();
@@ -144,8 +124,9 @@ public class AppConfig {
}
@Bean(name = "property-operation")
- public PropertyOperation propertyOperation() {
- return new PropertyOperation();
+ @Primary
+ public PropertyOperation propertyOperation(@Qualifier("titan-generic-dao") TitanGenericDao titanGenericDao) {
+ return new PropertyOperation(titanGenericDao);
}
@Bean(name = "attribute-operation")
@@ -174,8 +155,9 @@ public class AppConfig {
}
@Bean(name = "element-operation")
- public IElementOperation elementOperation() {
- return new ElementOperation();
+ @Primary
+ public IElementOperation elementOperation(@Qualifier("titan-generic-dao") TitanGenericDao titanGenericDao) {
+ return new ElementOperation(titanGenericDao);
}
@Bean(name = "additional-information-operation")
@@ -213,9 +195,20 @@ public class AppConfig {
return new GroupOperation();
}
+ @Bean(name = "groups-operation")
+ public GroupsOperation jsonGroupsOperation() {
+ return new GroupsOperation();
+ }
+
+ @Bean(name = "group-instance-operation")
+ public GroupInstanceOperation groupInstanceOperation() {
+ return new GroupInstanceOperation();
+ }
+
@Bean(name = "group-type-operation")
- public GroupTypeOperation groupTypeOperation() {
- return new GroupTypeOperation();
+ @Primary
+ public GroupTypeOperation groupTypeOperation(@Qualifier("titan-generic-dao") TitanGenericDao titanGenricDao, @Qualifier("property-operation")PropertyOperation propertyOperation) {
+ return new GroupTypeOperation(titanGenricDao, propertyOperation);
}
@Bean(name = "attribute-operation")
@@ -289,8 +282,9 @@ public class AppConfig {
* @return
*/
@Bean(name = "user-operation")
- public IUserAdminOperation userOperation() {
- return new UserAdminOperation();
+ @Primary
+ public IUserAdminOperation userOperation(@Qualifier("titan-generic-dao") TitanGenericDao titanGenericDao) {
+ return new UserAdminOperation(titanGenericDao);
}
/**
@@ -534,5 +528,24 @@ public class AppConfig {
public ServiceComponentInstanceBusinessLogic serviceComponentInstanceBusinessLogic() {
return new ServiceComponentInstanceBusinessLogic();
}
+ /**
+ *
+ * @return new instance of migration1702
+ */
+ @Bean(name = "migration1702")
+ public Migration1702 migration1702() {
+ return new Migration1702();
+ }
+
+
+ @Bean(name = "migrationUtils")
+ public MigrationOperationUtils migrationUtils() {
+ return new MigrationOperationUtils();
+ }
+
+ @Bean(name = "vfModulesPropertiesAdding")
+ public VfModulesPropertiesAdding vfModulesPropertiesAdding() {
+ return new VfModulesPropertiesAdding();
+ }
}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/ServiceMigration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/ServiceMigration.java
index cb7f05ddfd..ee5171d8ab 100644
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/ServiceMigration.java
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/ServiceMigration.java
@@ -100,12 +100,8 @@ import fj.data.Either;
public class ServiceMigration {
- private static final String[] NORMATIVE_OLD_NAMES = {
- "tosca.nodes.network.Network", "tosca.nodes.network.Port",
- "tosca.nodes.BlockStorage", "tosca.nodes.Compute", "tosca.nodes.Container.Application",
- "tosca.nodes.Container.Runtime", "tosca.nodes.Database", "tosca.nodes.DBMS", "tosca.nodes.LoadBalancer",
- "tosca.nodes.ObjectStorage", "tosca.nodes.Root", "tosca.nodes.SoftwareComponent",
- "tosca.nodes.WebApplication", "tosca.nodes.WebServer", };
+ private static final String[] NORMATIVE_OLD_NAMES = { "tosca.nodes.network.Network", "tosca.nodes.network.Port", "tosca.nodes.BlockStorage", "tosca.nodes.Compute", "tosca.nodes.Container.Application", "tosca.nodes.Container.Runtime",
+ "tosca.nodes.Database", "tosca.nodes.DBMS", "tosca.nodes.LoadBalancer", "tosca.nodes.ObjectStorage", "tosca.nodes.Root", "tosca.nodes.SoftwareComponent", "tosca.nodes.WebApplication", "tosca.nodes.WebServer", };
private static Logger log = LoggerFactory.getLogger(ServiceMigration.class.getName());
@@ -204,7 +200,7 @@ public class ServiceMigration {
return false;
}
} catch (Exception e) {
- log.debug("Failed to load category migration file :{} error: {}",categoryMigrationFile, e);
+ log.debug("Failed to load category migration file : {}", categoryMigrationFile, e);
return false;
}
for (Map.Entry<String, List<MigrationCategory>> entry : categoriesFromYml.entrySet()) {
@@ -227,7 +223,7 @@ public class ServiceMigration {
log.debug("updateCategories no changes for categories from type {}", componentType);
}
} else {
- log.debug("updateCategories failed not supported component file in migration categories file {}", entry.getKey());
+ log.debug("updateCategories failed not supported component file in migration categories file" + entry.getKey());
return false;
}
}
@@ -236,10 +232,9 @@ public class ServiceMigration {
private boolean updateServiceCategories(List<MigrationCategory> categories) {
log.debug("updateServiceCategories STARTED");
- Either<List<CategoryDefinition>, ActionStatus> serviceCategories = elementOperation
- .getAllCategories(NodeTypeEnum.ServiceNewCategory, true);
+ Either<List<CategoryDefinition>, ActionStatus> serviceCategories = elementOperation.getAllCategories(NodeTypeEnum.ServiceNewCategory, true);
if (serviceCategories.isRight()) {
- log.debug("updateServiceCategories failed fetch all service categories ,error: {}", serviceCategories.right().value());
+ log.debug("updateServiceCategories failed fetch all service categories ,error " + serviceCategories.right().value());
return false;
}
for (MigrationCategory newCat : categories) {
@@ -255,10 +250,9 @@ public class ServiceMigration {
}
if (!exist) {
CategoryDefinition categoryDefinition = new CategoryDefinition(newCat);
- Either<CategoryDefinition, ActionStatus> result = elementOperation
- .createCategory(categoryDefinition, NodeTypeEnum.ServiceNewCategory, true);
+ Either<CategoryDefinition, ActionStatus> result = elementOperation.createCategory(categoryDefinition, NodeTypeEnum.ServiceNewCategory, true);
if (result.isRight()) {
- log.debug("Failed to create service category {}, error: {}", categoryDefinition, result.right().value());
+ log.debug("Failed to create service category {} error {}", categoryDefinition, result.right().value());
return false;
}
log.debug("service category {} created", categoryDefinition);
@@ -267,8 +261,7 @@ public class ServiceMigration {
// update exist
for (CategoryDefinition catInDB : serviceCategories.left().value()) {
if (newCat.getOldName().equals(catInDB.getName())) {
- Either<CategoryData, TitanOperationStatus> updateSingleResult = updateSingleResourceCategory(
- newCat, NodeTypeEnum.ServiceNewCategory);
+ Either<CategoryData, TitanOperationStatus> updateSingleResult = updateSingleResourceCategory(newCat, NodeTypeEnum.ServiceNewCategory);
if (updateSingleResult.isRight()) {
return false;
}
@@ -281,15 +274,12 @@ public class ServiceMigration {
return true;
}
- private Either<CategoryData, TitanOperationStatus> updateSingleResourceCategory(MigrationCategory newCat,
- NodeTypeEnum nodetype) {
+ private Either<CategoryData, TitanOperationStatus> updateSingleResourceCategory(MigrationCategory newCat, NodeTypeEnum nodetype) {
Map<String, Object> properties = new HashMap<>();
properties.put(GraphPropertiesDictionary.NAME.getProperty(), newCat.getOldName());
- Either<List<CategoryData>, TitanOperationStatus> categoryEither = titanGenericDao.getByCriteria(nodetype,
- properties, CategoryData.class);
+ Either<List<CategoryData>, TitanOperationStatus> categoryEither = titanGenericDao.getByCriteria(nodetype, properties, CategoryData.class);
if (categoryEither.isRight() && categoryEither.right().value() != TitanOperationStatus.NOT_FOUND) {
- log.debug("Failed to get {} categories, for name {} error {}", nodetype, newCat.getOldName(),
- categoryEither.right().value());
+ log.debug("Failed to get {} categories, for name {} error {}", nodetype, newCat.getOldName(), categoryEither.right().value());
return Either.right(categoryEither.right().value());
}
List<CategoryData> categoryList = (categoryEither.isLeft() ? categoryEither.left().value() : null);
@@ -300,10 +290,8 @@ public class ServiceMigration {
CategoryData categoryData = categoryList.get(0);
categoryData.getCategoryDataDefinition().setName(newCat.getName());
categoryData.getCategoryDataDefinition().setIcons(newCat.getIcons());
- categoryData.getCategoryDataDefinition()
- .setNormalizedName(ValidationUtils.normalizeCategoryName4Uniqueness(newCat.getName()));
- Either<CategoryData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(categoryData,
- CategoryData.class);
+ categoryData.getCategoryDataDefinition().setNormalizedName(ValidationUtils.normalizeCategoryName4Uniqueness(newCat.getName()));
+ Either<CategoryData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(categoryData, CategoryData.class);
if (updateNode.isRight()) {
log.debug("Failed to update {} category {} error {}", nodetype, categoryData, updateNode.right().value());
return Either.right(updateNode.right().value());
@@ -314,11 +302,9 @@ public class ServiceMigration {
private boolean updateResourceCategories(List<MigrationCategory> categories) {
log.debug("updateResourceCategories STARTED");
- Either<List<CategoryDefinition>, ActionStatus> resourceCategories = elementOperation
- .getAllCategories(NodeTypeEnum.ResourceNewCategory, true);
+ Either<List<CategoryDefinition>, ActionStatus> resourceCategories = elementOperation.getAllCategories(NodeTypeEnum.ResourceNewCategory, true);
if (resourceCategories.isRight()) {
- log.debug("updateResourceCategories failed fetch all resource categories ,error "
- + resourceCategories.right().value());
+ log.debug("updateResourceCategories failed fetch all resource categories ,error " + resourceCategories.right().value());
return false;
}
for (MigrationCategory newCat : categories) {
@@ -333,10 +319,9 @@ public class ServiceMigration {
}
if (!exist) {
CategoryDefinition categoryDefinition = new CategoryDefinition(newCat);
- Either<CategoryDefinition, ActionStatus> resultCat = elementOperation
- .createCategory(categoryDefinition, NodeTypeEnum.ResourceNewCategory, true);
+ Either<CategoryDefinition, ActionStatus> resultCat = elementOperation.createCategory(categoryDefinition, NodeTypeEnum.ResourceNewCategory, true);
if (resultCat.isRight()) {
- log.debug("Failed to create resource category {}, error: {}", categoryDefinition, resultCat.right().value());
+ log.debug("Failed to create resource category {} error {}", categoryDefinition, resultCat.right().value());
return false;
}
log.debug("resource category {} created", categoryDefinition);
@@ -346,10 +331,9 @@ public class ServiceMigration {
List<MigrationSubCategory> subcategories = newSubcat;
for (MigrationSubCategory msubcat : subcategories) {
SubCategoryDefinition subcat = new SubCategoryDefinition(msubcat);
- Either<SubCategoryDefinition, ActionStatus> resultSubcat = elementOperation.createSubCategory(
- resultCat.left().value().getUniqueId(), subcat, NodeTypeEnum.ResourceSubcategory, true);
+ Either<SubCategoryDefinition, ActionStatus> resultSubcat = elementOperation.createSubCategory(resultCat.left().value().getUniqueId(), subcat, NodeTypeEnum.ResourceSubcategory, true);
if (resultSubcat.isRight()) {
- log.debug("Failed to create resource sub category {} error: {}", subcat, resultSubcat.right().value());
+ log.debug("Failed to create resource sub category {} error {}", subcat, resultSubcat.right().value());
return false;
}
log.debug("resource sub category {} created for category {}", categoryDefinition, resultCat.left().value().getName());
@@ -359,8 +343,7 @@ public class ServiceMigration {
// update exist
for (CategoryDefinition catInDB : resourceCategories.left().value()) {
if (newCat.getOldName().equals(catInDB.getName())) {
- Either<CategoryData, TitanOperationStatus> updateSingleResult = updateSingleResourceCategory(
- newCat, NodeTypeEnum.ResourceNewCategory);
+ Either<CategoryData, TitanOperationStatus> updateSingleResult = updateSingleResourceCategory(newCat, NodeTypeEnum.ResourceNewCategory);
if (updateSingleResult.isRight()) {
return false;
}
@@ -378,18 +361,15 @@ public class ServiceMigration {
if (!existSub) {
SubCategoryDefinition subcat = new SubCategoryDefinition(migSubCat);
- Either<SubCategoryDefinition, ActionStatus> resultSubcat = elementOperation
- .createSubCategory((String) categoryData.getUniqueId(), subcat,
- NodeTypeEnum.ResourceSubcategory, true);
+ Either<SubCategoryDefinition, ActionStatus> resultSubcat = elementOperation.createSubCategory((String) categoryData.getUniqueId(), subcat, NodeTypeEnum.ResourceSubcategory, true);
if (resultSubcat.isRight()) {
- log.debug("Failed to create resource sub category {} error: {}", subcat, resultSubcat.right().value());
+ log.debug("Failed to create resource sub category {} error {}", subcat, resultSubcat.right().value());
return false;
}
- log.debug("resource sub category {}", categoryData, resultSubcat.left().value().getName());
+ log.debug("resource sub category {} created for category {}", categoryData, resultSubcat.left().value().getName());
}
} else {
- if (updateSingleSubCategory(newCat, migSubCat,
- updateSingleResult.left().value()) == false) {
+ if (updateSingleSubCategory(newCat, migSubCat, updateSingleResult.left().value()) == false) {
return false;
}
}
@@ -402,17 +382,13 @@ public class ServiceMigration {
return true;
}
- private boolean updateSingleSubCategory(MigrationCategory newCat, MigrationSubCategory migSubCat,
- CategoryData categoryData) {
+ private boolean updateSingleSubCategory(MigrationCategory newCat, MigrationSubCategory migSubCat, CategoryData categoryData) {
- Either<List<ImmutablePair<SubCategoryData, GraphEdge>>, TitanOperationStatus> subcategories = titanGenericDao
- .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceNewCategory),
- (String) categoryData.getUniqueId(), GraphEdgeLabels.SUB_CATEGORY,
- NodeTypeEnum.ResourceSubcategory, SubCategoryData.class);
+ Either<List<ImmutablePair<SubCategoryData, GraphEdge>>, TitanOperationStatus> subcategories = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceNewCategory), (String) categoryData.getUniqueId(),
+ GraphEdgeLabels.SUB_CATEGORY, NodeTypeEnum.ResourceSubcategory, SubCategoryData.class);
if (subcategories.isRight()) {
- log.debug("Failed to get resource sub categories, for name {} error {}", newCat.getOldName(),
- subcategories.right().value());
+ log.debug("Failed to get resource sub categories, for name {} error {}", newCat.getOldName(), subcategories.right().value());
return false;
}
@@ -421,13 +397,10 @@ public class ServiceMigration {
SubCategoryData subCategoryData = pair.getKey();
subCategoryData.getSubCategoryDataDefinition().setName(migSubCat.getName());
subCategoryData.getSubCategoryDataDefinition().setIcons(migSubCat.getIcons());
- subCategoryData.getSubCategoryDataDefinition()
- .setNormalizedName(ValidationUtils.normalizeCategoryName4Uniqueness(migSubCat.getName()));
- Either<SubCategoryData, TitanOperationStatus> updateSubNode = titanGenericDao
- .updateNode(subCategoryData, SubCategoryData.class);
+ subCategoryData.getSubCategoryDataDefinition().setNormalizedName(ValidationUtils.normalizeCategoryName4Uniqueness(migSubCat.getName()));
+ Either<SubCategoryData, TitanOperationStatus> updateSubNode = titanGenericDao.updateNode(subCategoryData, SubCategoryData.class);
if (updateSubNode.isRight()) {
- log.debug("Failed to update resource sub category {} error {}", subCategoryData,
- updateSubNode.right().value());
+ log.debug("Failed to update resource sub category {} error {}", subCategoryData, updateSubNode.right().value());
return false;
}
log.debug("Update resource subcategory category {} ", subCategoryData);
@@ -540,11 +513,9 @@ public class ServiceMigration {
private boolean updateCalculatedEdges() {
log.debug("update calculated edges STARTED");
- Either<List<ComponentInstanceData>, TitanOperationStatus> allInstances = titanGenericDao
- .getByCriteria(NodeTypeEnum.ResourceInstance, null, ComponentInstanceData.class);
+ Either<List<ComponentInstanceData>, TitanOperationStatus> allInstances = titanGenericDao.getByCriteria(NodeTypeEnum.ResourceInstance, null, ComponentInstanceData.class);
if (allInstances.isRight() && !allInstances.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
- log.debug(
- "updateCalculatedEdges failed fetch all resource instances ,error " + allInstances.right().value());
+ log.debug("updateCalculatedEdges failed fetch all resource instances ,error " + allInstances.right().value());
return false;
}
if (allInstances.isRight() && allInstances.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
@@ -556,15 +527,11 @@ public class ServiceMigration {
// check if already have calculated edges
log.debug("start handle instance {}", instance.getUniqueId());
boolean needProcess = true;
- Either<List<ImmutablePair<CapabilityData, GraphEdge>>, TitanOperationStatus> vfci = titanGenericDao
- .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance),
- instance.getUniqueId(), GraphEdgeLabels.CALCULATED_CAPABILITY, NodeTypeEnum.Capability,
- CapabilityData.class);
+ Either<List<ImmutablePair<CapabilityData, GraphEdge>>, TitanOperationStatus> vfci = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), instance.getUniqueId(),
+ GraphEdgeLabels.CALCULATED_CAPABILITY, NodeTypeEnum.Capability, CapabilityData.class);
if (vfci.isRight()) {
if (!vfci.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
- log.debug("createCalculatedCapabilitiesForInstance failed to fetch instance for resource {} error: {}",
- instance.getComponentInstDataDefinition().getComponentUid(),
- vfci.right().value());
+ log.debug("createCalculatedCapabilitiesForInstance failed to fetch instance for resource " + instance.getComponentInstDataDefinition().getComponentUid() + " error " + vfci.right().value());
return false;
}
} else {
@@ -572,15 +539,11 @@ public class ServiceMigration {
needProcess = false;
}
}
- Either<List<ImmutablePair<RequirementData, GraphEdge>>, TitanOperationStatus> vfciReq = titanGenericDao
- .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance),
- instance.getUniqueId(), GraphEdgeLabels.CALCULATED_REQUIREMENT, NodeTypeEnum.Requirement,
- RequirementData.class);
+ Either<List<ImmutablePair<RequirementData, GraphEdge>>, TitanOperationStatus> vfciReq = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), instance.getUniqueId(),
+ GraphEdgeLabels.CALCULATED_REQUIREMENT, NodeTypeEnum.Requirement, RequirementData.class);
if (vfciReq.isRight()) {
if (!vfciReq.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
- log.debug("createCalculatedCapabilitiesForInstance failed to fetch instance for resource {} error: {}",
- instance.getComponentInstDataDefinition().getComponentUid(),
- vfciReq.right().value());
+ log.debug("createCalculatedCapabilitiesForInstance failed to fetch instance for resource " + instance.getComponentInstDataDefinition().getComponentUid() + " error " + vfciReq.right().value());
return false;
}
} else {
@@ -588,16 +551,12 @@ public class ServiceMigration {
needProcess = false;
}
}
- Either<List<ImmutablePair<RequirementData, GraphEdge>>, TitanOperationStatus> vfciReqFF = titanGenericDao
- .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance),
- instance.getUniqueId(), GraphEdgeLabels.CALCULATED_REQUIREMENT_FULLFILLED,
- NodeTypeEnum.Requirement, RequirementData.class);
+ Either<List<ImmutablePair<RequirementData, GraphEdge>>, TitanOperationStatus> vfciReqFF = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), instance.getUniqueId(),
+ GraphEdgeLabels.CALCULATED_REQUIREMENT_FULLFILLED, NodeTypeEnum.Requirement, RequirementData.class);
if (vfciReqFF.isRight()) {
if (!vfciReqFF.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
- log.debug("createCalculatedCapabilitiesForInstance failed to fetch instance for resource "
- + instance.getComponentInstDataDefinition().getComponentUid() + " error "
- + vfciReqFF.right().value());
+ log.debug("createCalculatedCapabilitiesForInstance failed to fetch instance for resource " + instance.getComponentInstDataDefinition().getComponentUid() + " error " + vfciReqFF.right().value());
return false;
}
} else {
@@ -613,7 +572,7 @@ public class ServiceMigration {
String originId = instance.getComponentInstDataDefinition().getComponentUid();
Either<Resource, StorageOperationStatus> resourceE = resourceOperation.getResource(originId, true);
if (resourceE.isRight()) {
- log.debug("updateCalculatedEdges failed to fetch origin resource with id {} error: {}", originId, resourceE.right().value());
+ log.debug("updateCalculatedEdges failed to fetch origin resource with id {} error {}", originId, resourceE.right().value());
return false;
}
Resource resource = resourceE.left().value();
@@ -631,16 +590,12 @@ public class ServiceMigration {
return true;
}
- private boolean createCalculatedCapabilitiesForInstance(ComponentInstanceData instance,
- Map<String, List<CapabilityDefinition>> capabilities) {
+ private boolean createCalculatedCapabilitiesForInstance(ComponentInstanceData instance, Map<String, List<CapabilityDefinition>> capabilities) {
for (Map.Entry<String, List<CapabilityDefinition>> entry : capabilities.entrySet()) {
for (CapabilityDefinition capability : entry.getValue()) {
- Either<CapabilityData, TitanOperationStatus> capNode = titanGenericDao.getNode(
- UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Capability), capability.getUniqueId(),
- CapabilityData.class);
+ Either<CapabilityData, TitanOperationStatus> capNode = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Capability), capability.getUniqueId(), CapabilityData.class);
if (capNode.isRight()) {
- log.debug("createCalculatedCapabilitiesForInstance failed to fetch capability node with id "
- + capability.getUniqueId() + " error " + capNode.right().value());
+ log.debug("createCalculatedCapabilitiesForInstance failed to fetch capability node with id " + capability.getUniqueId() + " error " + capNode.right().value());
return false;
}
Map<String, Object> props = new HashMap<>();
@@ -649,16 +604,13 @@ public class ServiceMigration {
return false;
}
- Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(instance,
- capNode.left().value(), GraphEdgeLabels.CALCULATED_CAPABILITY, props);
+ Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(instance, capNode.left().value(), GraphEdgeLabels.CALCULATED_CAPABILITY, props);
if (createRelation.isRight()) {
TitanOperationStatus titanOperationStatus = createRelation.right().value();
- log.debug(
- "Failed to create calculated requirement from component instance {} to requirement {}, error: {}",
- instance.getUniqueId(), capNode.left().value().getUniqueId(), titanOperationStatus);
+ log.debug("Failed to create calculated requirement from component instance {} to requirement {}, error: {}", instance.getUniqueId(), capNode.left().value().getUniqueId(), titanOperationStatus);
return false;
}
- log.debug("CALCULATED_CAPABILITY was created from {} to {} with props: {}", capNode.left().value().getUniqueId(), instance.getUniqueId(), props);
+ log.debug("CALCULATED_CAPABILITY was created from {} to {} with props : {}", capNode.left().value().getUniqueId(), instance.getUniqueId(), props);
}
}
return true;
@@ -666,39 +618,30 @@ public class ServiceMigration {
private boolean fillEdgeProperties(ComponentInstanceData instance, Map<String, Object> props) {
if (instance.getComponentInstDataDefinition().getOriginType().equals(OriginTypeEnum.VF)) {
- Either<List<ImmutablePair<ComponentInstanceData, GraphEdge>>, TitanOperationStatus> vfci = titanGenericDao
- .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource),
- instance.getComponentInstDataDefinition().getComponentUid(), GraphEdgeLabels.RESOURCE_INST,
- NodeTypeEnum.ResourceInstance, ComponentInstanceData.class);
+ Either<List<ImmutablePair<ComponentInstanceData, GraphEdge>>, TitanOperationStatus> vfci = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource),
+ instance.getComponentInstDataDefinition().getComponentUid(), GraphEdgeLabels.RESOURCE_INST, NodeTypeEnum.ResourceInstance, ComponentInstanceData.class);
if (vfci.isRight()) {
- log.debug("createCalculatedCapabilitiesForInstance failed to fetch instance for resource {} error: {}",
- instance.getComponentInstDataDefinition().getComponentUid(),
- vfci.right().value());
+ log.debug("createCalculatedCapabilitiesForInstance failed to fetch instance for resource " + instance.getComponentInstDataDefinition().getComponentUid() + " error " + vfci.right().value());
return false;
}
ImmutablePair<ComponentInstanceData, GraphEdge> immutablePair = vfci.left().value().get(0);
String vfciId = immutablePair.getLeft().getUniqueId();
props.put(GraphEdgePropertiesDictionary.OWNER_ID.getProperty(), vfciId);
- props.put(GraphEdgePropertiesDictionary.SOURCE.getProperty(),
- immutablePair.getLeft().getComponentInstDataDefinition().getComponentUid());
+ props.put(GraphEdgePropertiesDictionary.SOURCE.getProperty(), immutablePair.getLeft().getComponentInstDataDefinition().getComponentUid());
} else {
props.put(GraphEdgePropertiesDictionary.OWNER_ID.getProperty(), instance.getUniqueId());
- props.put(GraphEdgePropertiesDictionary.SOURCE.getProperty(),
- instance.getComponentInstDataDefinition().getComponentUid());
+ props.put(GraphEdgePropertiesDictionary.SOURCE.getProperty(), instance.getComponentInstDataDefinition().getComponentUid());
}
return true;
}
- private boolean createCalculatedRequirementsForInstance(ComponentInstanceData instance,
- Map<String, List<RequirementDefinition>> requirements) {
+ private boolean createCalculatedRequirementsForInstance(ComponentInstanceData instance, Map<String, List<RequirementDefinition>> requirements) {
for (Map.Entry<String, List<RequirementDefinition>> entry : requirements.entrySet()) {
for (RequirementDefinition requirement : entry.getValue()) {
- Either<RequirementData, TitanOperationStatus> reqNode = titanGenericDao.getNode(
- UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Requirement), requirement.getUniqueId(),
- RequirementData.class);
+ Either<RequirementData, TitanOperationStatus> reqNode = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Requirement), requirement.getUniqueId(), RequirementData.class);
if (reqNode.isRight()) {
- log.debug("updateCalculatedEdges failed to fetch requirement node with id {} error: {}", requirement.getUniqueId(), reqNode.right().value());
+ log.debug("updateCalculatedEdges failed to fetch requirement node with id " + requirement.getUniqueId() + " error " + reqNode.right().value());
return false;
}
Map<String, Object> props = new HashMap<>();
@@ -708,16 +651,13 @@ public class ServiceMigration {
return false;
}
- Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(instance,
- reqNode.left().value(), GraphEdgeLabels.CALCULATED_REQUIREMENT, props);
+ Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(instance, reqNode.left().value(), GraphEdgeLabels.CALCULATED_REQUIREMENT, props);
if (createRelation.isRight()) {
TitanOperationStatus titanOperationStatus = createRelation.right().value();
- log.debug(
- "Failed to create calculated requirement from component instance {} to requirement {}, error: {}",
- instance.getUniqueId(), reqNode.left().value().getUniqueId(), titanOperationStatus);
+ log.debug("Failed to create calculated requirement from component instance {} to requirement {}, error: {}", instance.getUniqueId(), reqNode.left().value().getUniqueId(), titanOperationStatus);
return false;
}
- log.debug("CALCULATED_REQUIREMENT was created from {} to {} with props: {}", reqNode.left().value().getUniqueId(), instance.getUniqueId(), props);
+ log.debug("CALCULATED_REQUIREMENT was created from {} to {} with props : {}", reqNode.left().value().getUniqueId(), instance.getUniqueId(), props);
}
}
return true;
@@ -725,8 +665,7 @@ public class ServiceMigration {
private boolean updateRelations() {
log.debug("update relations and edges STARTED");
- Either<List<RelationshipInstData>, TitanOperationStatus> allRelations = titanGenericDao
- .getByCriteria(NodeTypeEnum.RelationshipInst, null, RelationshipInstData.class);
+ Either<List<RelationshipInstData>, TitanOperationStatus> allRelations = titanGenericDao.getByCriteria(NodeTypeEnum.RelationshipInst, null, RelationshipInstData.class);
if (allRelations.isRight()) {
if (allRelations.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
log.debug("updateRelations : No relations to update. updateRelations ENDED");
@@ -752,10 +691,9 @@ public class ServiceMigration {
return false;
}
- Either<RelationshipInstData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(rel,
- RelationshipInstData.class);
+ Either<RelationshipInstData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(rel, RelationshipInstData.class);
if (updateNode.isRight()) {
- log.debug("updateRelations : failed to update relation node with id {}, error: {}", rel.getUniqueId(), updateNode.right().value());
+ log.debug("updateRelations : failed to update relation node with id {} , error {}", rel.getUniqueId(), updateNode.right().value());
return false;
}
log.debug("Relations was updated with values {}", rel);
@@ -765,22 +703,19 @@ public class ServiceMigration {
}
private boolean updateRequirementFieldsInRelation(RelationshipInstData rel) {
- Either<ImmutablePair<ComponentInstanceData, GraphEdge>, TitanOperationStatus> reqInst = titanGenericDao
- .getParentNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.RelationshipInst), rel.getUniqueId(),
- GraphEdgeLabels.RELATIONSHIP_INST, NodeTypeEnum.ResourceInstance, ComponentInstanceData.class);
+ Either<ImmutablePair<ComponentInstanceData, GraphEdge>, TitanOperationStatus> reqInst = titanGenericDao.getParentNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.RelationshipInst), rel.getUniqueId(), GraphEdgeLabels.RELATIONSHIP_INST,
+ NodeTypeEnum.ResourceInstance, ComponentInstanceData.class);
if (reqInst.isRight()) {
- log.debug("updateRelations : failed to fetch capabilty component instance for relation {}, error: {}", rel.getUniqueId(), reqInst.right().value());
+ log.debug("updateRelations : failed to fetch capabilty component instance for relation {}, error {}", rel.getUniqueId(), reqInst.right().value());
return false;
}
ComponentInstanceData requirementInstanceData = reqInst.left().value().getLeft();
ComponentInstanceDataDefinition reqRI = requirementInstanceData.getComponentInstDataDefinition();
if (reqRI.getOriginType().equals(OriginTypeEnum.VF)) {
- Either<ImmutablePair<ComponentInstanceData, GraphEdge>, TitanOperationStatus> vfcInstInOrigVf = titanGenericDao
- .getChildByEdgeCriteria(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource),
- reqRI.getComponentUid(), GraphEdgeLabels.RESOURCE_INST, NodeTypeEnum.ResourceInstance,
- ComponentInstanceData.class, null);
+ Either<ImmutablePair<ComponentInstanceData, GraphEdge>, TitanOperationStatus> vfcInstInOrigVf = titanGenericDao.getChildByEdgeCriteria(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), reqRI.getComponentUid(),
+ GraphEdgeLabels.RESOURCE_INST, NodeTypeEnum.ResourceInstance, ComponentInstanceData.class, null);
if (vfcInstInOrigVf.isRight()) {
- log.debug("updateRelations : failed to fetch VFC instance in origin VF with id {}, error: {}", reqRI.getComponentUid(), vfcInstInOrigVf.right().value());
+ log.debug("updateRelations : failed to fetch VFC instance in origin VF with id " + reqRI.getComponentUid() + ", error ", vfcInstInOrigVf.right().value());
return false;
}
rel.setRequirementOwnerId(vfcInstInOrigVf.left().value().getLeft().getUniqueId());
@@ -788,30 +723,26 @@ public class ServiceMigration {
rel.setRequirementOwnerId(reqRI.getUniqueId());
}
// get vertex
- Either<TitanVertex, TitanOperationStatus> vertexReqRI = titanGenericDao.getVertexByProperty(
- UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), requirementInstanceData.getUniqueId());
+ Either<TitanVertex, TitanOperationStatus> vertexReqRI = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), requirementInstanceData.getUniqueId());
if (vertexReqRI.isRight()) {
- log.debug("updateRelations : failed to fetch veterx for instance {}, error: {}", requirementInstanceData.getUniqueId(), vertexReqRI.right().value());
+ log.debug("updateRelations : failed to fetch veterx for instance {}, error {}", requirementInstanceData.getUniqueId(), vertexReqRI.right().value());
return false;
}
String[] splitIds = rel.getUniqueId().split("\\.");
String reqName = splitIds[splitIds.length - 1];
Map<String, Object> props = new HashMap<>();
props.put(GraphEdgePropertiesDictionary.NAME.getProperty(), reqName);
- Either<List<Edge>, TitanOperationStatus> edgesForNode = titanGenericDao
- .getOutgoingEdgesByCriteria(vertexReqRI.left().value(), GraphEdgeLabels.CALCULATED_REQUIREMENT, props);
+ Either<List<Edge>, TitanOperationStatus> edgesForNode = titanGenericDao.getOutgoingEdgesByCriteria(vertexReqRI.left().value(), GraphEdgeLabels.CALCULATED_REQUIREMENT, props);
if (edgesForNode.isRight()) {
- log.debug("updateRelations : failed to fetch edges for instance {}, error: {}", requirementInstanceData.getUniqueId(), edgesForNode.right().value());
+ log.debug("updateRelations : failed to fetch edges for instance {} error {}", requirementInstanceData.getUniqueId(), edgesForNode.right().value());
return false;
}
Edge edge = edgesForNode.left().value().get(0);
- String reqId = (String) titanGenericDao.getProperty((TitanVertex) edge.inVertex(),
- GraphPropertiesDictionary.UNIQUE_ID.getProperty());
+ String reqId = (String) titanGenericDao.getProperty((TitanVertex) edge.inVertex(), GraphPropertiesDictionary.UNIQUE_ID.getProperty());
rel.setRequirementId(reqId);
// change edge label
- TitanEdge newEdge = (TitanEdge) vertexReqRI.left().value()
- .addEdge(GraphEdgeLabels.CALCULATED_REQUIREMENT_FULLFILLED.getProperty(), edge.inVertex());
+ TitanEdge newEdge = (TitanEdge) vertexReqRI.left().value().addEdge(GraphEdgeLabels.CALCULATED_REQUIREMENT_FULLFILLED.getProperty(), edge.inVertex());
titanGenericDao.setProperties(newEdge, titanGenericDao.getProperties(edge));
edge.remove();
@@ -822,23 +753,19 @@ public class ServiceMigration {
public boolean updateCapabiltyFieldsInRelation(RelationshipInstData rel) {
// update capability parameters
- Either<ImmutablePair<ComponentInstanceData, GraphEdge>, TitanOperationStatus> capInst = titanGenericDao
- .getChildByEdgeCriteria(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.RelationshipInst),
- rel.getUniqueId(), GraphEdgeLabels.CAPABILITY_NODE, NodeTypeEnum.ResourceInstance,
- ComponentInstanceData.class, null);
+ Either<ImmutablePair<ComponentInstanceData, GraphEdge>, TitanOperationStatus> capInst = titanGenericDao.getChildByEdgeCriteria(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.RelationshipInst), rel.getUniqueId(),
+ GraphEdgeLabels.CAPABILITY_NODE, NodeTypeEnum.ResourceInstance, ComponentInstanceData.class, null);
if (capInst.isRight()) {
- log.debug("updateRelations : failed to fetch capabilty component instance for relation {}, error: {}", rel.getUniqueId(), capInst.right().value());
+ log.debug("updateRelations : failed to fetch capabilty component instance for relation {}, error {}", rel.getUniqueId(), capInst.right().value());
return false;
}
ComponentInstanceData capabiltyInstanceData = capInst.left().value().getLeft();
ComponentInstanceDataDefinition capRI = capabiltyInstanceData.getComponentInstDataDefinition();
if (capRI.getOriginType().equals(OriginTypeEnum.VF)) {
- Either<ImmutablePair<ComponentInstanceData, GraphEdge>, TitanOperationStatus> vfcInstInOrigVf = titanGenericDao
- .getChildByEdgeCriteria(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource),
- capRI.getComponentUid(), GraphEdgeLabels.RESOURCE_INST, NodeTypeEnum.ResourceInstance,
- ComponentInstanceData.class, null);
+ Either<ImmutablePair<ComponentInstanceData, GraphEdge>, TitanOperationStatus> vfcInstInOrigVf = titanGenericDao.getChildByEdgeCriteria(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), capRI.getComponentUid(),
+ GraphEdgeLabels.RESOURCE_INST, NodeTypeEnum.ResourceInstance, ComponentInstanceData.class, null);
if (vfcInstInOrigVf.isRight()) {
- log.debug("updateRelations : failed to fetch VFC instance in origin VF with id {}, error: {}", capRI.getComponentUid(), vfcInstInOrigVf.right().value());
+ log.debug("updateRelations : failed to fetch VFC instance in origin VF with id " + capRI.getComponentUid() + ", error ", vfcInstInOrigVf.right().value());
return false;
}
rel.setCapabilityOwnerId(vfcInstInOrigVf.left().value().getLeft().getUniqueId());
@@ -847,67 +774,28 @@ public class ServiceMigration {
}
// get vertex
- Either<TitanVertex, TitanOperationStatus> vertexCapRI = titanGenericDao.getVertexByProperty(
- UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), capabiltyInstanceData.getUniqueId());
+ Either<TitanVertex, TitanOperationStatus> vertexCapRI = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), capabiltyInstanceData.getUniqueId());
if (vertexCapRI.isRight()) {
- log.debug("updateRelations : failed to fetch veterx for instance {}, error: {}", capabiltyInstanceData.getUniqueId(), vertexCapRI.right().value());
+ log.debug("updateRelations : failed to fetch veterx for instance {} , error {}", capabiltyInstanceData.getUniqueId(), vertexCapRI.right().value());
return false;
}
// String[] splitIds = rel.getUniqueId().split("\\.");
- String capName = (String) capInst.left().value().getRight().getProperties()
- .get(GraphEdgePropertiesDictionary.NAME.getProperty());// splitIds[splitIds.length
- // - 1];
+ String capName = (String) capInst.left().value().getRight().getProperties().get(GraphEdgePropertiesDictionary.NAME.getProperty());// splitIds[splitIds.length
+ // - 1];
Map<String, Object> props = new HashMap<>();
props.put(GraphEdgePropertiesDictionary.NAME.getProperty(), capName);
- Either<List<Edge>, TitanOperationStatus> edgesForNode = titanGenericDao
- .getOutgoingEdgesByCriteria(vertexCapRI.left().value(), GraphEdgeLabels.CALCULATED_CAPABILITY, props);
+ Either<List<Edge>, TitanOperationStatus> edgesForNode = titanGenericDao.getOutgoingEdgesByCriteria(vertexCapRI.left().value(), GraphEdgeLabels.CALCULATED_CAPABILITY, props);
if (edgesForNode.isRight()) {
- log.debug("updateRelations : failed to fetch edges for instance {}, error: {}", capabiltyInstanceData.getUniqueId(), edgesForNode.right().value());
+ log.debug("updateRelations : failed to fetch edges for instance {} , error {}", capabiltyInstanceData.getUniqueId(), edgesForNode.right().value());
return false;
}
Edge edge = edgesForNode.left().value().get(0);
- String capId = (String) titanGenericDao.getProperty((TitanVertex) edge.inVertex(),
- GraphPropertiesDictionary.UNIQUE_ID.getProperty());
+ String capId = (String) titanGenericDao.getProperty((TitanVertex) edge.inVertex(), GraphPropertiesDictionary.UNIQUE_ID.getProperty());
rel.setCapabiltyId(capId);
return true;
}
- // private boolean fixDerivedFv() {
- // Map<String, Object> props = new HashMap<String, Object>();
- // props.put(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(),
- // ResourceTypeEnum.VF.name());
- // Either<List<ResourceMetadataData>, TitanOperationStatus> allVF =
- // titanGenericDao.getByCriteria(NodeTypeEnum.Resource, props,
- // ResourceMetadataData.class);
- // if (allVF.isRight() &&
- // !allVF.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
- // log.debug("fixDerivedFv failed fetch all VF resources,error {}", allVF.right().value());
- // return false;
- // }
- // if ( allVF.right().value().equals(TitanOperationStatus.NOT_FOUND) ){
- // log.debug("fixDerivedFv - no VF");
- // return true;
- // }
- // Set<String> finishedResources = new HashSet<>();
- //
- // for (ResourceMetadataData metadata : allVF.left().value()) {
- // ComponentMetadataDataDefinition metadataDD =
- // metadata.getMetadataDataDefinition();
- //
- // if (!finishedResources.contains(metadataDD.getUniqueId())) {
- // Either<List<String>, StorageOperationStatus> processedIds =
- // handleVfGroup(metadata);
- // if (processedIds.isRight()) {
- // log.debug("fixDerivedFv failed to process FV group {}", processedIds.right().value());
- // return false;
- // }
- // finishedResources.addAll(processedIds.left().value());
- // }
- // }
- // return true;
- // }
-
private Either<List<String>, StorageOperationStatus> handleVfGroup(ResourceMetadataData metadata) {
Map<String, Object> props = new HashMap<String, Object>();
props.put(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.VF.name());
@@ -915,8 +803,7 @@ public class ServiceMigration {
List<String> finished = new ArrayList<>();
- Either<List<ResourceMetadataData>, TitanOperationStatus> allVFByName = titanGenericDao
- .getByCriteria(NodeTypeEnum.Resource, props, ResourceMetadataData.class);
+ Either<List<ResourceMetadataData>, TitanOperationStatus> allVFByName = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, props, ResourceMetadataData.class);
if (allVFByName.isRight()) {
log.debug("fixDerivedFv failed fetch all VF resources,error {}", allVFByName.right().value());
return Either.right(StorageOperationStatus.GENERAL_ERROR);
@@ -937,10 +824,9 @@ public class ServiceMigration {
props.put(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.VF.name());
props.put(GraphPropertiesDictionary.UUID.getProperty(), uuid10);
- Either<List<ResourceMetadataData>, TitanOperationStatus> allVFByUUID = titanGenericDao
- .getByCriteria(NodeTypeEnum.Resource, props, ResourceMetadataData.class);
+ Either<List<ResourceMetadataData>, TitanOperationStatus> allVFByUUID = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, props, ResourceMetadataData.class);
if (allVFByUUID.isRight()) {
- log.debug("fixDerivedFv failed fetch all VF resources by UUID {}, error: {}", uuid10, allVFByUUID.right().value());
+ log.debug("fixDerivedFv failed fetch all VF resources by UUID {} ,error {}", uuid10, allVFByUUID.right().value());
return Either.right(StorageOperationStatus.GENERAL_ERROR);
}
for (ResourceMetadataData mdata : allVFByUUID.left().value()) {
@@ -957,7 +843,7 @@ public class ServiceMigration {
// handleSingleVf(finished, derivedMapping, resourceId);
StorageOperationStatus handleSingleVfResult = handleSingleVf(finished, resourceId);
if (!handleSingleVfResult.equals(StorageOperationStatus.OK)) {
- log.debug("fixDerivedFv failed - handleSingleVfResult failed for resource {}, error: {}", resourceId, handleSingleVfResult);
+ log.debug("fixDerivedFv failed - handleSingleVfResult failed for resource {} ,error {}", resourceId, handleSingleVfResult);
return Either.right(StorageOperationStatus.GENERAL_ERROR);
}
}
@@ -967,10 +853,9 @@ public class ServiceMigration {
// private StorageOperationStatus handleSingleVf(List<String> finished,
// Map<String, String> derivedMapping, String resourceId) {
private StorageOperationStatus handleSingleVf(List<String> finished, String resourceId) {
- Either<TitanVertex, TitanOperationStatus> vertexByProperty = titanGenericDao
- .getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), resourceId);
+ Either<TitanVertex, TitanOperationStatus> vertexByProperty = titanGenericDao.getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), resourceId);
if (vertexByProperty.isRight()) {
- log.debug("fixDerivedFv failed to fetch resource by id {}, error: {}", resourceId, vertexByProperty.right().value());
+ log.debug("fixDerivedFv failed to fetch resource by id {} ,error {}", resourceId, vertexByProperty.right().value());
return StorageOperationStatus.GENERAL_ERROR;
}
Vertex vertexR = vertexByProperty.left().value();
@@ -979,8 +864,7 @@ public class ServiceMigration {
// move edges
// must be only one
TitanVertex vertexD = (TitanVertex) vertexDIter.next();
- String idDerived = (String) titanGenericDao.getProperty(vertexD,
- GraphPropertiesDictionary.UNIQUE_ID.getProperty());
+ String idDerived = (String) titanGenericDao.getProperty(vertexD, GraphPropertiesDictionary.UNIQUE_ID.getProperty());
// TODO clone resource
@@ -996,30 +880,27 @@ public class ServiceMigration {
private boolean updateComponentInstanceType() {
log.debug("update component instances type STARTED");
- Either<List<ComponentInstanceData>, TitanOperationStatus> allInstances = titanGenericDao
- .getByCriteria(NodeTypeEnum.ResourceInstance, null, ComponentInstanceData.class);
+ Either<List<ComponentInstanceData>, TitanOperationStatus> allInstances = titanGenericDao.getByCriteria(NodeTypeEnum.ResourceInstance, null, ComponentInstanceData.class);
if (allInstances.isRight()) {
if (allInstances.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
log.debug("updateComponentInstanceType: no instances ti update ");
return true;
}
- log.debug("updateComponentInstanceType failed fetch all resource instances ,error {}", allInstances.right().value());
+ log.debug("updateComponentInstanceType failed fetch all resource instances ,error " + allInstances.right().value());
return false;
}
List<ComponentInstanceData> listOfInstances = allInstances.left().value();
for (ComponentInstanceData instance : listOfInstances) {
String originId = instance.getComponentInstDataDefinition().getComponentUid();
- Either<ComponentMetadataData, TitanOperationStatus> nodeResource = titanGenericDao.getNode(
- UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), originId, ComponentMetadataData.class);
+ Either<ComponentMetadataData, TitanOperationStatus> nodeResource = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), originId, ComponentMetadataData.class);
if (nodeResource.isRight()) {
- log.debug("updateComponentInstanceType failed to fetch origin resource with id {}, error: {}", originId, nodeResource.right().value());
+ log.debug("updateComponentInstanceType failed to fetch origin resource with id {} error {}", originId, nodeResource.right().value());
return false;
}
- ResourceTypeEnum resourceType = ((ResourceMetadataDataDefinition) nodeResource.left().value()
- .getMetadataDataDefinition()).getResourceType();
+ ResourceTypeEnum resourceType = ((ResourceMetadataDataDefinition) nodeResource.left().value().getMetadataDataDefinition()).getResourceType();
if (resourceType == null) {
- log.debug("updateComponentInstanceType failed, no resource type for origin resource with id {}", originId);
+ log.debug("updateComponentInstanceType failed, no resource type for origin resource with id " + originId);
return false;
}
OriginTypeEnum originType;
@@ -1042,10 +923,9 @@ public class ServiceMigration {
}
instance.getComponentInstDataDefinition().setOriginType(originType);
- Either<ComponentInstanceData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(instance,
- ComponentInstanceData.class);
+ Either<ComponentInstanceData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(instance, ComponentInstanceData.class);
if (updateNode.isRight()) {
- log.debug("updateComponentInstanceType failed, failed to update component instance node with id {}, error: {}", instance.getUniqueId(), updateNode.right().value());
+ log.debug("updateComponentInstanceType failed, failed to update component instance node with id " + instance.getUniqueId() + " error " + updateNode.right().value());
return false;
}
log.debug("For instance with id {} the origin type was detected as {}", instance.getUniqueId(), originType);
@@ -1056,8 +936,7 @@ public class ServiceMigration {
private boolean addResourceCounterToResources() {
- Either<List<ResourceMetadataData>, TitanOperationStatus> allResources = titanGenericDao
- .getByCriteria(NodeTypeEnum.Resource, null, ResourceMetadataData.class);
+ Either<List<ResourceMetadataData>, TitanOperationStatus> allResources = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, null, ResourceMetadataData.class);
if (allResources.isRight()) {
if (allResources.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
log.debug("addResourceCounterToResources - no resources");
@@ -1067,11 +946,9 @@ public class ServiceMigration {
return false;
}
for (ResourceMetadataData resource : allResources.left().value()) {
- Either<TitanVertex, TitanOperationStatus> vertexByProperty = titanGenericDao.getVertexByProperty(
- UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resource.getUniqueId());
+ Either<TitanVertex, TitanOperationStatus> vertexByProperty = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resource.getUniqueId());
if (vertexByProperty.isRight()) {
- log.error("failed to add instanceCounter to VF {} . error is: {}", resource.getUniqueId(),
- vertexByProperty.right().value().name());
+ log.error("failed to add instanceCounter to VF {} . error is: {}", resource.getUniqueId(), vertexByProperty.right().value().name());
return false;
}
Vertex vfVertex = vertexByProperty.left().value();
@@ -1086,8 +963,7 @@ public class ServiceMigration {
Map<String, Object> props = new HashMap<String, Object>();
props.put(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.VF.name());
- Either<List<ResourceMetadataData>, TitanOperationStatus> allVF = titanGenericDao
- .getByCriteria(NodeTypeEnum.Resource, props, ResourceMetadataData.class);
+ Either<List<ResourceMetadataData>, TitanOperationStatus> allVF = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, props, ResourceMetadataData.class);
if (allVF.isRight()) {
if (allVF.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
log.debug("fixDerivedVf - no VFs");
@@ -1099,11 +975,9 @@ public class ServiceMigration {
Map<String, String> vfUuidToVfcUuid = new HashMap<String, String>();
for (ResourceMetadataData metadata : allVF.left().value()) {
- Either<Resource, StorageOperationStatus> eitherResource = resourceOperation
- .getResource(metadata.getMetadataDataDefinition().getUniqueId(), true);
+ Either<Resource, StorageOperationStatus> eitherResource = resourceOperation.getResource(metadata.getMetadataDataDefinition().getUniqueId(), true);
if (eitherResource.isRight()) {
- log.error("failed to migrate VF {} from version 1602 to version 1604. error is: {}",
- metadata.getMetadataDataDefinition().getUniqueId(), eitherResource.right().value().name());
+ log.error("failed to migrate VF {} from version 1602 to version 1604. error is: {}", metadata.getMetadataDataDefinition().getUniqueId(), eitherResource.right().value().name());
return false;
}
Resource vfResource = eitherResource.left().value();
@@ -1121,12 +995,10 @@ public class ServiceMigration {
// handle lifecycle
String vfUniqueId = vfResource.getUniqueId();
LifecycleStateEnum vfcTargetState = vfResource.getLifecycleState();
- if (vfcTargetState.equals(LifecycleStateEnum.READY_FOR_CERTIFICATION)
- || vfcTargetState.equals(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS)) {
+ if (vfcTargetState.equals(LifecycleStateEnum.READY_FOR_CERTIFICATION) || vfcTargetState.equals(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS)) {
User user = new User();
user.setUserId(vfResource.getLastUpdaterUserId());
- Either<? extends Component, StorageOperationStatus> checkinComponent = lifecycleOperaion
- .checkinComponent(NodeTypeEnum.Resource, vfResource, user, user, true);
+ Either<? extends Component, StorageOperationStatus> checkinComponent = lifecycleOperaion.checkinComponent(NodeTypeEnum.Resource, vfResource, user, user, true);
if (checkinComponent.isRight()) {
log.error("failed to checkin VF {}. error={}", vfUniqueId, checkinComponent.right().value().name());
return false;
@@ -1138,51 +1010,35 @@ public class ServiceMigration {
// delete VF Properties
List<PropertyDefinition> properties = vfResource.getProperties();
if (properties != null && !properties.isEmpty()) {
- Either<Map<String, PropertyDefinition>, StorageOperationStatus> deleteAllProperties = propertyOperation
- .deleteAllPropertiesAssociatedToNode(NodeTypeEnum.Resource, vfUniqueId);
- if (deleteAllProperties.isRight()
- && !deleteAllProperties.right().value().equals(StorageOperationStatus.NOT_FOUND)
- && !deleteAllProperties.right().value().equals(StorageOperationStatus.OK)) {
- log.error("failed to delete properties of VF {} . error is: {}",
- metadata.getMetadataDataDefinition().getUniqueId(),
- deleteAllProperties.right().value().name());
+ Either<Map<String, PropertyDefinition>, StorageOperationStatus> deleteAllProperties = propertyOperation.deleteAllPropertiesAssociatedToNode(NodeTypeEnum.Resource, vfUniqueId);
+ if (deleteAllProperties.isRight() && !deleteAllProperties.right().value().equals(StorageOperationStatus.NOT_FOUND) && !deleteAllProperties.right().value().equals(StorageOperationStatus.OK)) {
+ log.error("failed to delete properties of VF {} . error is: {}", metadata.getMetadataDataDefinition().getUniqueId(), deleteAllProperties.right().value().name());
return false;
}
}
// delete VF Additional Info
List<AdditionalInformationDefinition> additionalInformation = vfResource.getAdditionalInformation();
if (additionalInformation != null && !additionalInformation.isEmpty()) {
- Either<AdditionalInformationDefinition, StorageOperationStatus> deleteAllAdditionalInformationParameters = additionalInformationOperation
- .deleteAllAdditionalInformationParameters(NodeTypeEnum.Resource, vfUniqueId, true);
- if (deleteAllAdditionalInformationParameters.isRight()
- && !deleteAllAdditionalInformationParameters.right().value().equals(StorageOperationStatus.OK)
- && !deleteAllAdditionalInformationParameters.right().value()
- .equals(StorageOperationStatus.NOT_FOUND)) {
- log.error("failed to delete properties of VF {} . error is: {}",
- metadata.getMetadataDataDefinition().getUniqueId(),
- deleteAllAdditionalInformationParameters.right().value().name());
+ Either<AdditionalInformationDefinition, StorageOperationStatus> deleteAllAdditionalInformationParameters = additionalInformationOperation.deleteAllAdditionalInformationParameters(NodeTypeEnum.Resource, vfUniqueId, true);
+ if (deleteAllAdditionalInformationParameters.isRight() && !deleteAllAdditionalInformationParameters.right().value().equals(StorageOperationStatus.OK)
+ && !deleteAllAdditionalInformationParameters.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
+ log.error("failed to delete properties of VF {} . error is: {}", metadata.getMetadataDataDefinition().getUniqueId(), deleteAllAdditionalInformationParameters.right().value().name());
return false;
}
}
// delete VF derivedFrom
GraphRelation derivedFromRelation = new GraphRelation(GraphEdgeLabels.DERIVED_FROM.getProperty());
- derivedFromRelation.setFrom(new RelationEndPoint(NodeTypeEnum.Resource,
- UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), vfUniqueId));
- Either<GraphRelation, TitanOperationStatus> deleteDerivedFromRelation = titanGenericDao
- .deleteOutgoingRelation(derivedFromRelation);
+ derivedFromRelation.setFrom(new RelationEndPoint(NodeTypeEnum.Resource, UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), vfUniqueId));
+ Either<GraphRelation, TitanOperationStatus> deleteDerivedFromRelation = titanGenericDao.deleteOutgoingRelation(derivedFromRelation);
if (deleteDerivedFromRelation.isRight()) {
- log.error("failed to delete derivedFrom relation of VF {} . error is: {}",
- metadata.getMetadataDataDefinition().getUniqueId(),
- deleteDerivedFromRelation.right().value().name());
+ log.error("failed to delete derivedFrom relation of VF {} . error is: {}", metadata.getMetadataDataDefinition().getUniqueId(), deleteDerivedFromRelation.right().value().name());
return false;
}
// create VFC
- Either<Resource, StorageOperationStatus> createVFC = createVFC(metadata, vfResource, vfcUUID,
- vfcTargetState);
+ Either<Resource, StorageOperationStatus> createVFC = createVFC(metadata, vfResource, vfcUUID, vfcTargetState);
if (createVFC.isRight()) {
- log.error("failed to split VF {} to VFC. error is: {}",
- metadata.getMetadataDataDefinition().getUniqueId(), createVFC.right().value().name());
+ log.error("failed to split VF {} to VFC. error is: {}", metadata.getMetadataDataDefinition().getUniqueId(), createVFC.right().value().name());
return false;
}
Resource vfcResource = createVFC.left().value();
@@ -1191,11 +1047,9 @@ public class ServiceMigration {
}
// update VFC to deleted if required
if (isVfDeleted != null && isVfDeleted) {
- Either<Component, StorageOperationStatus> markResourceToDelete = resourceOperation
- .markComponentToDelete(vfcResource, true);
+ Either<Component, StorageOperationStatus> markResourceToDelete = resourceOperation.markComponentToDelete(vfcResource, true);
if (markResourceToDelete.isRight()) {
- log.error("failed to mark isDeleted on VFC {} . error is: {}", vfcResource.getUniqueId(),
- markResourceToDelete.right().value().name());
+ log.error("failed to mark isDeleted on VFC {} . error is: {}", vfcResource.getUniqueId(), markResourceToDelete.right().value().name());
return false;
}
}
@@ -1204,8 +1058,7 @@ public class ServiceMigration {
return true;
}
- private Either<Resource, StorageOperationStatus> createVFC(ResourceMetadataData metadata, Resource vfcResource,
- String uuid, LifecycleStateEnum vfcTargetState) {
+ private Either<Resource, StorageOperationStatus> createVFC(ResourceMetadataData metadata, Resource vfcResource, String uuid, LifecycleStateEnum vfcTargetState) {
Boolean highestVersion = vfcResource.isHighestVersion();
// Resource vfcResource = new Resource((ResourceMetadataDefinition)
@@ -1237,8 +1090,7 @@ public class ServiceMigration {
return createResource;
}
Resource afterCreateResource = createResource.left().value();
- Either<TitanVertex, TitanOperationStatus> vertexByProperty = titanGenericDao.getVertexByProperty(
- UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), afterCreateResource.getUniqueId());
+ Either<TitanVertex, TitanOperationStatus> vertexByProperty = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), afterCreateResource.getUniqueId());
if (vertexByProperty.isRight()) {
return createResource;
}
@@ -1264,23 +1116,18 @@ public class ServiceMigration {
log.error("failed to create logical name for vfc instance");
return false;
}
- Either<ComponentInstance, StorageOperationStatus> createComponentInstance = componentInstanceOperaion
- .createComponentInstance(vfUniqueId, NodeTypeEnum.Resource, handleNameLogic.left().value(),
- componentInstance, NodeTypeEnum.Resource, true);
+ Either<ComponentInstance, StorageOperationStatus> createComponentInstance = componentInstanceOperaion.createComponentInstance(vfUniqueId, NodeTypeEnum.Resource, handleNameLogic.left().value(), componentInstance, NodeTypeEnum.Resource, true);
if (createComponentInstance.isRight()) {
- log.error("failed to create vfc instance on vf {}. error: {}", vfUniqueId,
- createComponentInstance.right().value().name());
+ log.error("failed to create vfc instance on vf {}. error: {}", vfUniqueId, createComponentInstance.right().value().name());
return false;
}
return true;
}
- private Either<String, Boolean> handleNameLogic(ComponentInstance componentInstance, String containerComponentId,
- String resourceName) {
+ private Either<String, Boolean> handleNameLogic(ComponentInstance componentInstance, String containerComponentId, String resourceName) {
- Either<Integer, StorageOperationStatus> componentInNumberStatus = resourceOperation
- .increaseAndGetComponentInstanceCounter(containerComponentId, true);
+ Either<Integer, StorageOperationStatus> componentInNumberStatus = resourceOperation.increaseAndGetComponentInstanceCounter(containerComponentId, true);
if (componentInNumberStatus.isRight()) {
log.debug("Failed to get component instance number for container component {} ", containerComponentId);
@@ -1299,13 +1146,12 @@ public class ServiceMigration {
return Either.left(resourceInNumber);
}
- private Boolean validateComponentInstanceName(String resourceInstanceName, ComponentInstance resourceInstance,
- boolean isCreate) {
+ private Boolean validateComponentInstanceName(String resourceInstanceName, ComponentInstance resourceInstance, boolean isCreate) {
if (!ValidationUtils.validateStringNotEmpty(resourceInstanceName)) {
return false;
}
- resourceInstance.setNormalizedName(ValidationUtils.normaliseComponentInstanceName(resourceInstanceName));
+ resourceInstance.setNormalizedName(ValidationUtils.normalizeComponentInstanceName(resourceInstanceName));
if (!isCreate) {
if (!ValidationUtils.validateResourceInstanceNameLength(resourceInstanceName)) {
return false;
@@ -1325,8 +1171,7 @@ public class ServiceMigration {
boolean result = false;
Either<Boolean, StorageOperationStatus> resourceEither = null;
try {
- Either<List<ResourceMetadataData>, TitanOperationStatus> allResources = titanGenericDao
- .getByCriteria(NodeTypeEnum.Resource, null, ResourceMetadataData.class);
+ Either<List<ResourceMetadataData>, TitanOperationStatus> allResources = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, null, ResourceMetadataData.class);
if (allResources.isRight()) {
log.error("Couldn't get resources from DB, error: {}", allResources.right().value());
result = false;
@@ -1350,8 +1195,7 @@ public class ServiceMigration {
return result;
}
}
- if (((ResourceMetadataDataDefinition) resource.getMetadataDataDefinition()).getResourceType().name()
- .equals("VF")) {
+ if (((ResourceMetadataDataDefinition) resource.getMetadataDataDefinition()).getResourceType().name().equals("VF")) {
resourceEither = setVfToscaResourceName(resource);
if (resourceEither.isRight()) {
log.error("DB error during tosca resource name setting");
@@ -1388,11 +1232,9 @@ public class ServiceMigration {
List<ComponentMetadataData> fullComponentList = new ArrayList<ComponentMetadataData>();
// getting resources
- Either<List<ResourceMetadataData>, TitanOperationStatus> allHighestVersionResources = titanGenericDao
- .getByCriteria(NodeTypeEnum.Resource, props, ResourceMetadataData.class);
+ Either<List<ResourceMetadataData>, TitanOperationStatus> allHighestVersionResources = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, props, ResourceMetadataData.class);
if (allHighestVersionResources.isRight()) {
- log.error("Couldn't get resources with highest version from DB, error: {}",
- allHighestVersionResources.right().value());
+ log.error("Couldn't get resources with highest version from DB, error: {}", allHighestVersionResources.right().value());
return false;
}
List<ResourceMetadataData> allHighestVersionResourcesAL = allHighestVersionResources.left().value();
@@ -1404,11 +1246,9 @@ public class ServiceMigration {
fullComponentList.addAll(allHighestVersionResourcesAL);
// getting services
- Either<List<ServiceMetadataData>, TitanOperationStatus> allHighestVersionServices = titanGenericDao
- .getByCriteria(NodeTypeEnum.Service, props, ServiceMetadataData.class);
+ Either<List<ServiceMetadataData>, TitanOperationStatus> allHighestVersionServices = titanGenericDao.getByCriteria(NodeTypeEnum.Service, props, ServiceMetadataData.class);
if (allHighestVersionServices.isRight()) {
- log.error("Couldn't get services with highest version from DB, error: {}",
- allHighestVersionServices.right().value());
+ log.error("Couldn't get services with highest version from DB, error: {}", allHighestVersionServices.right().value());
return false;
}
List<ServiceMetadataData> allHighestVersionServicesAL = allHighestVersionServices.left().value();
@@ -1422,11 +1262,9 @@ public class ServiceMigration {
List<ComponentMetadataData> reducedComponentsAL = reduceHighestVersionResourcesList(fullComponentList);
// getting products
- Either<List<ProductMetadataData>, TitanOperationStatus> allHighestVersionProducts = titanGenericDao
- .getByCriteria(NodeTypeEnum.Product, props, ProductMetadataData.class);
+ Either<List<ProductMetadataData>, TitanOperationStatus> allHighestVersionProducts = titanGenericDao.getByCriteria(NodeTypeEnum.Product, props, ProductMetadataData.class);
if (allHighestVersionProducts.isRight()) {
- log.error("Couldn't get products with highest version from DB, error: {}",
- allHighestVersionProducts.right().value());
+ log.error("Couldn't get products with highest version from DB, error: {}", allHighestVersionProducts.right().value());
return false;
}
List<ProductMetadataData> allHighestVersionProductsAL = allHighestVersionProducts.left().value();
@@ -1457,15 +1295,12 @@ public class ServiceMigration {
componentMetaData.getMetadataDataDefinition().setInvariantUUID(invariantUUID);
}
log.debug("new invariantUUID {}", componentMetaData.getMetadataDataDefinition().getInvariantUUID());
- Either<ComponentMetadataData, TitanOperationStatus> updateNode = titanGenericDao
- .updateNode(componentMetaData, ComponentMetadataData.class);
+ Either<ComponentMetadataData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(componentMetaData, ComponentMetadataData.class);
if (updateNode.isRight()) {
- log.error("DB error during while updating component {}, error: {}",
- componentMetaData.getMetadataDataDefinition().getName(), updateNode.right().value());
+ log.error("DB error during while updating component {}, error: {}", componentMetaData.getMetadataDataDefinition().getName(), updateNode.right().value());
return false;
}
- log.debug("updated invariantUUID {}",
- updateNode.left().value().getMetadataDataDefinition().getInvariantUUID());
+ log.debug("updated invariantUUID {}", updateNode.left().value().getMetadataDataDefinition().getInvariantUUID());
if (!isOnlyVersion(componentMetaData)) {
ComponentOperation componentOperation = null;
switch (NodeTypeEnum.getByName(componentMetaData.getLabel())) {
@@ -1481,11 +1316,9 @@ public class ServiceMigration {
default:
break;
}
- Either<Component, StorageOperationStatus> getComponentResult = componentOperation
- .getComponent((String) componentMetaData.getUniqueId(), true);
+ Either<Component, StorageOperationStatus> getComponentResult = componentOperation.getComponent((String) componentMetaData.getUniqueId(), true);
if (getComponentResult.isRight()) {
- log.error("DB error during while getting component with uniqueID {}, error: {}",
- componentMetaData.getUniqueId(), getComponentResult.right().value());
+ log.error("DB error during while getting component with uniqueID {}, error: {}", componentMetaData.getUniqueId(), getComponentResult.right().value());
return false;
}
Component component = getComponentResult.left().value();
@@ -1514,8 +1347,7 @@ public class ServiceMigration {
}
private boolean setProductInvariantUUIDIfExists(ProductMetadataData product) {
- Either<TitanVertex, TitanOperationStatus> getVertexRes = titanGenericDao
- .getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), product.getUniqueId());
+ Either<TitanVertex, TitanOperationStatus> getVertexRes = titanGenericDao.getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), product.getUniqueId());
if (getVertexRes.isRight()) {
log.error("DB error during retrieving product vertex {}", product.getMetadataDataDefinition().getName());
return false;
@@ -1528,27 +1360,21 @@ public class ServiceMigration {
return true;
}
- private Either<Boolean, StorageOperationStatus> updateAllVersions(Map<String, String> allVersions,
- String invariantUUID) {
+ private Either<Boolean, StorageOperationStatus> updateAllVersions(Map<String, String> allVersions, String invariantUUID) {
if (allVersions != null) {
for (String uniqueID : allVersions.values()) {
- Either<ComponentMetadataData, TitanOperationStatus> getNodeResult = titanGenericDao.getNode(
- GraphPropertiesDictionary.UNIQUE_ID.getProperty(), uniqueID, ComponentMetadataData.class);
+ Either<ComponentMetadataData, TitanOperationStatus> getNodeResult = titanGenericDao.getNode(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), uniqueID, ComponentMetadataData.class);
if (getNodeResult.isRight()) {
- log.error("DB error during while getting component with uniqueID {}, error: {}", uniqueID,
- getNodeResult.right().value());
+ log.error("DB error during while getting component with uniqueID {}, error: {}", uniqueID, getNodeResult.right().value());
return Either.right(StorageOperationStatus.GENERAL_ERROR);
}
ComponentMetadataData component = getNodeResult.left().value();
component.getMetadataDataDefinition().setInvariantUUID(invariantUUID);
- Either<ComponentMetadataData, TitanOperationStatus> updateNodeResult = titanGenericDao
- .updateNode(component, ComponentMetadataData.class);
- log.debug("updated child invariantUUID {}",
- updateNodeResult.left().value().getMetadataDataDefinition().getInvariantUUID());
+ Either<ComponentMetadataData, TitanOperationStatus> updateNodeResult = titanGenericDao.updateNode(component, ComponentMetadataData.class);
+ log.debug("updated child invariantUUID {}", updateNodeResult.left().value().getMetadataDataDefinition().getInvariantUUID());
if (updateNodeResult.isRight()) {
- log.error("DB error during while updating component {}, error: {}",
- component.getMetadataDataDefinition().getName(), updateNodeResult.right().value());
+ log.error("DB error during while updating component {}, error: {}", component.getMetadataDataDefinition().getName(), updateNodeResult.right().value());
return Either.right(StorageOperationStatus.GENERAL_ERROR);
}
}
@@ -1556,24 +1382,19 @@ public class ServiceMigration {
return Either.left(true);
}
- private List<ComponentMetadataData> reduceHighestVersionResourcesList(
- List<ComponentMetadataData> allHighestVersionResources) {
+ private List<ComponentMetadataData> reduceHighestVersionResourcesList(List<ComponentMetadataData> allHighestVersionResources) {
List<ComponentMetadataData> resultList = null;
Map<String, ComponentMetadataData> resultHM = new HashMap<String, ComponentMetadataData>();
for (ComponentMetadataData resource : allHighestVersionResources) {
- if (resource.getMetadataDataDefinition().getInvariantUUID() != null
- && !resource.getMetadataDataDefinition().getInvariantUUID().isEmpty()) {
+ if (resource.getMetadataDataDefinition().getInvariantUUID() != null && !resource.getMetadataDataDefinition().getInvariantUUID().isEmpty()) {
log.debug("invariantUUID {} ", resource.getMetadataDataDefinition().getInvariantUUID());
continue;
}
String curUUID = resource.getMetadataDataDefinition().getUUID();
if (resultHM.containsKey(curUUID)) {
- int isHighest = resultHM.get(curUUID).getMetadataDataDefinition().getVersion()
- .compareTo(resource.getMetadataDataDefinition().getVersion());
+ int isHighest = resultHM.get(curUUID).getMetadataDataDefinition().getVersion().compareTo(resource.getMetadataDataDefinition().getVersion());
if (isHighest > 0) {
- log.debug("version {} is great than {} ",
- resultHM.get(curUUID).getMetadataDataDefinition().getVersion(),
- resource.getMetadataDataDefinition().getVersion());
+ log.debug("version {} is great than {} ", resultHM.get(curUUID).getMetadataDataDefinition().getVersion(), resource.getMetadataDataDefinition().getVersion());
continue;
}
}
@@ -1622,11 +1443,9 @@ public class ServiceMigration {
return Either.right(StorageOperationStatus.GENERAL_ERROR);
}
- Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(resource,
- ResourceMetadataData.class);
+ Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(resource, ResourceMetadataData.class);
if (updateNode.isRight()) {
- log.error("DB error during while updating normative type {}, error: {}",
- resource.getMetadataDataDefinition().getName(), updateNode.right().value());
+ log.error("DB error during while updating normative type {}, error: {}", resource.getMetadataDataDefinition().getName(), updateNode.right().value());
return Either.right(StorageOperationStatus.GENERAL_ERROR);
}
log.debug("Normative type {} was successfully updated", resource.getMetadataDataDefinition().getName());
@@ -1636,15 +1455,11 @@ public class ServiceMigration {
return Either.left(false);
}
- private Either<Boolean, StorageOperationStatus> generateAndSetToscaResourceName(ResourceMetadataData resource,
- String toscaResourceName) {
+ private Either<Boolean, StorageOperationStatus> generateAndSetToscaResourceName(ResourceMetadataData resource, String toscaResourceName) {
if (toscaResourceName == null) {
- toscaResourceName = CommonBeUtils.generateToscaResourceName(
- ((ResourceMetadataDataDefinition) resource.getMetadataDataDefinition()).getResourceType().name(),
- resource.getMetadataDataDefinition().getSystemName());
+ toscaResourceName = CommonBeUtils.generateToscaResourceName(((ResourceMetadataDataDefinition) resource.getMetadataDataDefinition()).getResourceType().name(), resource.getMetadataDataDefinition().getSystemName());
}
- Either<Boolean, StorageOperationStatus> validateToscaResourceNameExists = resourceOperation
- .validateToscaResourceNameExists(toscaResourceName);
+ Either<Boolean, StorageOperationStatus> validateToscaResourceNameExists = resourceOperation.validateToscaResourceNameExists(toscaResourceName);
if (validateToscaResourceNameExists.isRight()) {
StorageOperationStatus storageOperationStatus = validateToscaResourceNameExists.right().value();
log.error("Couldn't validate toscaResourceName uniqueness - error: {}", storageOperationStatus);
@@ -1652,8 +1467,7 @@ public class ServiceMigration {
}
if (validateToscaResourceNameExists.left().value()) {
log.debug("Setting tosca resource name to be {}", toscaResourceName);
- ((ResourceMetadataDataDefinition) resource.getMetadataDataDefinition())
- .setToscaResourceName(toscaResourceName);
+ ((ResourceMetadataDataDefinition) resource.getMetadataDataDefinition()).setToscaResourceName(toscaResourceName);
return Either.left(true);
} else {
// As agreed with Renana - cannot be fixed automatically
@@ -1673,22 +1487,17 @@ public class ServiceMigration {
private Either<Boolean, StorageOperationStatus> setVfToscaResourceName(ResourceMetadataData resource) {
String resourceName = resource.getMetadataDataDefinition().getName();
- String resourceType = ((ResourceMetadataDataDefinition) resource.getMetadataDataDefinition()).getResourceType()
- .name();
- String toscaResourceName = CommonBeUtils.generateToscaResourceName(resourceType,
- resource.getMetadataDataDefinition().getSystemName());
+ String resourceType = ((ResourceMetadataDataDefinition) resource.getMetadataDataDefinition()).getResourceType().name();
+ String toscaResourceName = CommonBeUtils.generateToscaResourceName(resourceType, resource.getMetadataDataDefinition().getSystemName());
log.debug("Setting tosca resource name {} to VF {}", toscaResourceName, resourceName);
((ResourceMetadataDataDefinition) resource.getMetadataDataDefinition()).setToscaResourceName(toscaResourceName);
- Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(resource,
- ResourceMetadataData.class);
+ Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(resource, ResourceMetadataData.class);
if (updateNode.isRight()) {
- log.error("DB error during while updating VF tosca resource name {}, error: {}",
- resource.getMetadataDataDefinition().getName(), updateNode.right().value());
+ log.error("DB error during while updating VF tosca resource name {}, error: {}", resource.getMetadataDataDefinition().getName(), updateNode.right().value());
return Either.right(StorageOperationStatus.GENERAL_ERROR);
}
- log.debug("Tosca resource name of VF {} was successfully updated",
- resource.getMetadataDataDefinition().getName());
+ log.debug("Tosca resource name of VF {} was successfully updated", resource.getMetadataDataDefinition().getName());
return Either.left(true);
}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/VfcNamingAlignment.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/VfcNamingAlignment.java
index 27b9351ebc..e488017679 100644
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/VfcNamingAlignment.java
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/VfcNamingAlignment.java
@@ -77,7 +77,7 @@ public class VfcNamingAlignment {
log.debug("Checking resource {}", vfc.getMetadataDataDefinition().getName());
boolean wasChanged = false;
- Either<Boolean, StorageOperationStatus> vfcEither = fixToscaNameEmpty(vfc);
+ Either<Boolean, StorageOperationStatus> vfcEither = fixToscaNameEmpty(vfc);
if (vfcEither.isRight()) {
log.error("DB error during checkIsToscaNameEmpty - exiting...");
result = false;
@@ -157,7 +157,6 @@ public class VfcNamingAlignment {
return Either.left(false);
}
-
private Either<Boolean, StorageOperationStatus> generateAndSetToscaResourceName(ResourceMetadataData vfc,
String toscaResourceName) {
if (toscaResourceName == null) {
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1610/TitanFixUtils.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1610/TitanFixUtils.java
index 36ac98e578..fedd4d2545 100644
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1610/TitanFixUtils.java
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1610/TitanFixUtils.java
@@ -37,9 +37,6 @@ import org.springframework.beans.factory.annotation.Autowired;
import java.util.*;
-/**
- * Created by mlando on 8/17/2016.
- */
public class TitanFixUtils {
private static Logger log = LoggerFactory.getLogger(TitanFixUtils.class.getName());
@@ -291,7 +288,7 @@ public class TitanFixUtils {
List<TitanVertex> vertexList = new ArrayList<>();
if (iterator == null) {
- log.error("failed to get iterator over vertices object returned for resource id " + propertyIdSecure);
+ log.error("failed to get iterator over vertices object returned for resource id {}", propertyIdSecure);
operationFailed = true;
return false;
}
@@ -301,7 +298,7 @@ public class TitanFixUtils {
vertexList.add(vertex);
}
- if (!(vertexList.size() == 1)) {
+ if (vertexList.size() != 1) {
log.error("failed to get 1 vertex for resource id {} instead got {}", propertyIdSecure,
vertexList.size());
operationFailed = true;
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1610/ToscaArtifactsAlignment.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1610/ToscaArtifactsAlignment.java
index 347a5705b7..673190e8c1 100644
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1610/ToscaArtifactsAlignment.java
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1610/ToscaArtifactsAlignment.java
@@ -304,7 +304,7 @@ public class ToscaArtifactsAlignment extends AbstractOperation {
if (optionalError.isPresent()) {
ArtifactDefinition toscaArtifact = optionalError.get().getLeft();
StorageOperationStatus storageError = optionalError.get().getRight();
- log.error("{} When adding tosca artifact of type {} to component {} of type:{} " + "with uniqueId:{} a storageError occurred:{}", ERROR_PREFIX, toscaArtifact.getArtifactType(), component.getMetadataDataDefinition().getName(),
+ log.error("{} When adding tosca artifact of type {} to component {} of type:{} with uniqueId:{} a storageError occurred:{}", ERROR_PREFIX, toscaArtifact.getArtifactType(), component.getMetadataDataDefinition().getName(),
nodeType.getName(), component.getMetadataDataDefinition().getUniqueId(), storageError.name());
result = storageError;
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1702/DataTypesUpdate.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1702/DataTypesUpdate.java
new file mode 100644
index 0000000000..d7f36840c7
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1702/DataTypesUpdate.java
@@ -0,0 +1,428 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.asdctool.impl.migration.v1702;
+
+import java.io.File;
+import java.io.FileReader;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.Map.Entry;
+import java.util.stream.Collectors;
+
+import org.apache.commons.collections.CollectionUtils;
+import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.openecomp.sdc.be.components.impl.ImportUtils;
+import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
+import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum;
+import org.openecomp.sdc.be.config.BeEcompErrorManager;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.model.DataTypeDefinition;
+import org.openecomp.sdc.be.model.PropertyDefinition;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
+import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
+import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
+import org.openecomp.sdc.be.resources.data.PropertyData;
+import org.openecomp.sdc.exception.ResponseFormat;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.yaml.snakeyaml.Yaml;
+
+import fj.data.Either;
+
+/**
+ * Allows to update existing or create new data types according input file (yaml)
+ * @author ns019t
+ *
+ */
+public class DataTypesUpdate {
+
+ private static Logger log = LoggerFactory.getLogger(Migration1702.class.getName());
+
+ @Autowired
+ private PropertyOperation propertyOperation;
+ @Autowired
+ private ComponentsUtils componentsUtils;
+
+ @SuppressWarnings("unchecked")
+ /**
+ * Updates existing or creates new data types according input file (yaml)
+ * @param dataTypeYmlFilePath
+ * @return
+ */
+ public boolean updateDataTypes(String dataTypeYmlFilePath) {
+
+
+ List<String> dataTypesToUpdate = new ArrayList<>();
+ dataTypesToUpdate.add("org.openecomp.datatypes.EcompHoming");
+ dataTypesToUpdate.add("org.openecomp.datatypes.EcompNaming");
+ dataTypesToUpdate.add("org.openecomp.datatypes.network.NetworkAssignments");
+ dataTypesToUpdate.add("org.openecomp.datatypes.network.ProviderNetwork");
+ dataTypesToUpdate.add("org.openecomp.datatypes.network.NetworkFlows");
+ dataTypesToUpdate.add("org.openecomp.datatypes.Artifact");
+ dataTypesToUpdate.add("org.openecomp.datatypes.network.VlanRequirements");
+ dataTypesToUpdate.add("org.openecomp.datatypes.network.IpRequirements");
+ dataTypesToUpdate.add("org.openecomp.datatypes.network.MacAssignments");
+ dataTypesToUpdate.add("org.openecomp.datatypes.network.MacRequirements");
+ dataTypesToUpdate.add("org.openecomp.datatypes.heat.contrailV2.virtual.machine.subInterface.AddressPairIp");
+ dataTypesToUpdate.add("org.openecomp.datatypes.heat.contrailV2.virtual.machine.subInterface.MacAddress");
+ dataTypesToUpdate.add("org.openecomp.datatypes.heat.contrailV2.virtual.machine.subInterface.Properties");
+ dataTypesToUpdate.add("org.openecomp.datatypes.heat.contrailV2.virtual.machine.subInterface.AddressPair");
+ dataTypesToUpdate.add("org.openecomp.datatypes.heat.contrailV2.virtual.machine.subInterface.AddressPairs");
+
+ boolean isSuccessful = true;
+ List<DataTypeDefinition> dataTypes = extractDataTypesFromYaml(dataTypeYmlFilePath);
+
+ if(CollectionUtils.isEmpty(dataTypes)){
+ isSuccessful = false;
+ }
+
+ List<ImmutablePair<DataTypeDefinition, Boolean>> createdElementTypes = new ArrayList<>();
+
+ Iterator<DataTypeDefinition> elementTypeItr = dataTypes.iterator();
+ if(isSuccessful ){
+ try {
+ while (elementTypeItr.hasNext()) {
+ DataTypeDefinition elementType = elementTypeItr.next();
+ String elementName = elementType.getName();
+ Either<ActionStatus, ResponseFormat> validateElementType = validateDataType(elementType);
+ if (validateElementType.isRight()) {
+ log.debug("Failed to validate data type {}. Status is {}. ", elementName, validateElementType.right().value());
+ isSuccessful = false;
+ break;
+ }
+ log.debug("Going to get data type by name {}. ", elementName);
+ Either<DataTypeDefinition, StorageOperationStatus> findElementType = propertyOperation.getDataTypeByNameWithoutDerived(elementName);
+ if (findElementType.isRight()) {
+ StorageOperationStatus status = findElementType.right().value();
+ if (status != StorageOperationStatus.NOT_FOUND) {
+ log.debug("Failed to fetch data type {}. Status is {}. ", elementName , validateElementType.right().value());
+ isSuccessful = false;
+ break;
+ } else {
+ log.debug("Going to add data type with name {}. ", elementName);
+ Either<DataTypeDefinition, StorageOperationStatus> dataModelResponse = propertyOperation.addDataType(elementType);
+
+ if (dataModelResponse.isRight()) {
+ if (dataModelResponse.right().value() != StorageOperationStatus.SCHEMA_VIOLATION) {
+ log.debug("Failed to add data type {}. Status is {}. ", elementName , dataModelResponse.right().value());
+ isSuccessful = false;
+ break;
+ } else {
+ createdElementTypes.add(new ImmutablePair<DataTypeDefinition, Boolean>(elementType, false));
+ }
+ } else {
+ createdElementTypes.add(new ImmutablePair<DataTypeDefinition, Boolean>(elementType, true));
+ }
+
+ }
+ } else {
+ log.debug("Going to update data type with name {}. ", elementName);
+ Either<DataTypeDefinition, StorageOperationStatus> updateDataTypeRes = propertyOperation.updateDataType(elementType, findElementType.left().value());
+ if (updateDataTypeRes.isRight()) {
+ StorageOperationStatus status = updateDataTypeRes.right().value();
+ if (status == StorageOperationStatus.OK) {
+ createdElementTypes.add(new ImmutablePair<DataTypeDefinition, Boolean>(elementType, false));
+ } else {
+ log.debug("Failed to update data type {}. Status is {}. ", elementName , updateDataTypeRes.right().value());
+ isSuccessful = false;
+ break;
+ }
+ } else {
+ createdElementTypes.add(new ImmutablePair<DataTypeDefinition, Boolean>(elementType, true));
+ }
+ }
+ }
+ } finally {
+ if(isSuccessful){
+ propertyOperation.getTitanGenericDao().commit();
+ }else{
+ propertyOperation.getTitanGenericDao().rollback();
+ }
+ }
+ }
+ return isSuccessful;
+ }
+
+ @SuppressWarnings("unchecked")
+ static public List<DataTypeDefinition> extractDataTypesFromYaml(String dataTypeYmlFilePath) {
+ String dataTypeName;
+ List<DataTypeDefinition> dataTypes = new ArrayList<>();
+ try {
+ File file = new File(dataTypeYmlFilePath);
+ FileReader fr = new FileReader(file);
+ Map<String, Object> toscaJson = (Map<String, Object>) new Yaml().load(fr);
+
+ Iterator<Entry<String, Object>> elementTypesEntryItr = toscaJson.entrySet().iterator();
+ while (elementTypesEntryItr.hasNext()) {
+ Entry<String, Object> elementTypeNameDataEntry = elementTypesEntryItr.next();
+ dataTypeName = elementTypeNameDataEntry.getKey();
+ Map<String, Object> elementTypeJsonData = (Map<String, Object>) elementTypeNameDataEntry.getValue();
+
+ DataTypeDefinition dataType = new DataTypeDefinition();
+ dataType.setName(dataTypeName);
+
+ if (elementTypeJsonData != null) {
+
+ if (elementTypeJsonData.containsKey(ToscaTagNamesEnum.DESCRIPTION.getElementName())) {
+ dataType.setDescription( (String)elementTypeJsonData.get(ToscaTagNamesEnum.DESCRIPTION.getElementName()));
+ }
+ if (elementTypeJsonData.containsKey(ToscaTagNamesEnum.DERIVED_FROM.getElementName())) {
+ dataType.setDerivedFromName( (String)elementTypeJsonData.get(ToscaTagNamesEnum.DERIVED_FROM.getElementName()));
+ }
+ List<PropertyDefinition> properties = getProperties(elementTypeJsonData);
+ if (elementTypeJsonData.containsKey(ToscaTagNamesEnum.PROPERTIES.getElementName())) {
+ dataType.setProperties(properties);
+ }
+ }
+ dataTypes.add(dataType);
+ }
+
+ } catch (Exception e) {
+ log.debug("Failed to extract data types from Yaml file {}. ", dataTypeYmlFilePath);
+ e.printStackTrace();
+ }
+ return dataTypes;
+ }
+
+ static public List<PropertyDefinition> getProperties(Map<String, Object> toscaJson) {
+ List<PropertyDefinition> values = null;
+ Either<Map<String, PropertyDefinition>, ResultStatusEnum> properties = ImportUtils.getProperties(toscaJson);
+
+ if (properties.isLeft()) {
+ values = new ArrayList<>();
+ Map<String, PropertyDefinition> propertiesMap = properties.left().value();
+ if (propertiesMap != null && propertiesMap.isEmpty() == false) {
+
+ for (Entry<String, PropertyDefinition> entry : propertiesMap.entrySet()) {
+ String propName = entry.getKey();
+ PropertyDefinition propertyDefinition = entry.getValue();
+ PropertyDefinition newPropertyDefinition = new PropertyDefinition(propertyDefinition);
+ newPropertyDefinition.setName(propName);
+ values.add(newPropertyDefinition);
+ }
+ }
+ }
+
+ return values;
+ }
+
+ private Either<ActionStatus, ResponseFormat> validateDataType(DataTypeDefinition dataType) {
+
+ String dataTypeName = dataType.getName();
+ List<PropertyDefinition> properties = dataType.getProperties();
+ if (properties == null) {
+ // At least one parameter should be defined either in the properties
+ // section or at one of the parents
+ String derivedDataType = dataType.getDerivedFromName();
+ // If there are no properties, then we can create a data type if it
+ // is an abstract one or it derives from non abstract data type
+ if ((derivedDataType == null || derivedDataType.isEmpty())) {
+ if (false == isAbstract(dataType.getName())) {
+ if (false == ToscaPropertyType.isScalarType(dataTypeName)) {
+ log.debug("Data type {} must have properties unless it derives from non abstract data type",dataType.getName());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_NOR_PROPERTIES_NEITHER_DERIVED_FROM, dataType, null);
+
+ return Either.right(responseFormat);
+ }
+ }
+ } else {
+ // if it is not a scalar data type and it derives from abstract
+ // data type, we should reject the request.
+ if (false == ToscaPropertyType.isScalarType(dataTypeName) && true == isAbstract(derivedDataType)) {
+ log.debug("Data type {} which derived from abstract data type must have at least one property",dataType.getName());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_NOR_PROPERTIES_NEITHER_DERIVED_FROM, dataType, null);
+
+ return Either.right(responseFormat);
+ }
+ }
+ } else {
+ // properties tag cannot be empty
+ if (properties.isEmpty()) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_PROPERTIES_CANNOT_BE_EMPTY, dataType, null);
+
+ return Either.right(responseFormat);
+ }
+
+ // check no duplicates
+ Set<String> collect = properties.stream().map(p -> p.getName()).collect(Collectors.toSet());
+ if (collect != null) {
+ if (properties.size() != collect.size()) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_DUPLICATE_PROPERTY, dataType, null);
+
+ return Either.right(responseFormat);
+ }
+ }
+
+ List<String> propertiesWithSameTypeAsDataType = properties.stream().filter(p -> p.getType().equals(dataType.getName())).map(p -> p.getName()).collect(Collectors.toList());
+ if (propertiesWithSameTypeAsDataType != null && propertiesWithSameTypeAsDataType.isEmpty() == false) {
+ log.debug("The data type {} contains properties with the type {}",dataType.getName(),dataType.getName());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_PROEPRTY_CANNOT_HAVE_SAME_TYPE_OF_DATA_TYPE, dataType, propertiesWithSameTypeAsDataType);
+
+ return Either.right(responseFormat);
+ }
+ }
+
+ String derivedDataType = dataType.getDerivedFromName();
+ if (derivedDataType != null) {
+ Either<DataTypeDefinition, StorageOperationStatus> derivedDataTypeByName = propertyOperation.getDataTypeByName(derivedDataType, true);
+ if (derivedDataTypeByName.isRight()) {
+ StorageOperationStatus status = derivedDataTypeByName.right().value();
+ if (status == StorageOperationStatus.NOT_FOUND) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_DERIVED_IS_MISSING, dataType, null);
+
+ return Either.right(responseFormat);
+ } else {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.GENERAL_ERROR, dataType, null);
+
+ return Either.right(responseFormat);
+
+ }
+ } else {
+
+ DataTypeDefinition derivedDataTypeDef = derivedDataTypeByName.left().value();
+ if (properties != null && properties.isEmpty() == false) {
+
+ if (true == isScalarType(derivedDataTypeDef)) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_CANNOT_HAVE_PROPERTIES, dataType, null);
+
+ return Either.right(responseFormat);
+ }
+
+ Set<String> allParentsProps = new HashSet<>();
+ do {
+ List<PropertyDefinition> currentParentsProps = derivedDataTypeDef.getProperties();
+ if (currentParentsProps != null) {
+ for (PropertyDefinition propertyDefinition : currentParentsProps) {
+ allParentsProps.add(propertyDefinition.getName());
+ }
+ }
+ derivedDataTypeDef = derivedDataTypeDef.getDerivedFrom();
+ } while (derivedDataTypeDef != null);
+
+ // Check that no property is already defined in one of the
+ // ancestors
+ Set<String> alreadyExistPropsCollection = properties.stream().filter(p -> allParentsProps.contains(p.getName())).map(p -> p.getName()).collect(Collectors.toSet());
+ if (alreadyExistPropsCollection != null && alreadyExistPropsCollection.isEmpty() == false) {
+ List<String> duplicateProps = new ArrayList<>();
+ duplicateProps.addAll(alreadyExistPropsCollection);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_PROPERTY_ALREADY_DEFINED_IN_ANCESTOR, dataType, duplicateProps);
+
+ return Either.right(responseFormat);
+ }
+
+ }
+ }
+ }
+ return Either.left(ActionStatus.OK);
+ }
+
+ private boolean isAbstract(String dataTypeName) {
+
+ ToscaPropertyType isPrimitiveToscaType = ToscaPropertyType.isValidType(dataTypeName);
+
+ return isPrimitiveToscaType != null && isPrimitiveToscaType.isAbstract() == true;
+
+ }
+
+ private boolean isScalarType(DataTypeDefinition dataTypeDef) {
+
+ boolean isScalar = false;
+ DataTypeDefinition dataType = dataTypeDef;
+
+ while (dataType != null) {
+
+ String name = dataType.getName();
+ if (ToscaPropertyType.isScalarType(name)) {
+ isScalar = true;
+ break;
+ }
+
+ dataType = dataType.getDerivedFrom();
+ }
+
+ return isScalar;
+ }
+
+// public Either<DataTypeDefinition, StorageOperationStatus> updateDataType(DataTypeDefinition newDataTypeDefinition, DataTypeDefinition oldDataTypeDefinition) {
+//
+// Either<DataTypeDefinition, StorageOperationStatus> result = null;
+//
+// try {
+//
+// List<PropertyDefinition> newProperties = newDataTypeDefinition.getProperties();
+//
+// List<PropertyDefinition> oldProperties = oldDataTypeDefinition.getProperties();
+//
+// String newDerivedFromName = getDerivedFromName(newDataTypeDefinition);
+//
+// String oldDerivedFromName = getDerivedFromName(oldDataTypeDefinition);
+//
+// String dataTypeName = newDataTypeDefinition.getName();
+//
+// List<PropertyDefinition> propertiesToAdd = new ArrayList<>();
+// if (isPropertyOmitted(newProperties, oldProperties, dataTypeName) || isPropertyTypeChanged(dataTypeName, newProperties, oldProperties, propertiesToAdd) || isDerivedFromNameChanged(dataTypeName, newDerivedFromName, oldDerivedFromName)) {
+//
+// log.debug("The new data type " + dataTypeName + " is invalid.");
+//
+// result = Either.right(StorageOperationStatus.CANNOT_UPDATE_EXISTING_ENTITY);
+// return result;
+// }
+//
+// if (propertiesToAdd == null || propertiesToAdd.isEmpty()) {
+// log.debug("No new properties has been defined in the new data type " + newDataTypeDefinition);
+// result = Either.right(StorageOperationStatus.OK);
+// return result;
+// }
+//
+// Either<Map<String, PropertyData>, TitanOperationStatus> addPropertiesToDataType = addPropertiesToDataType(oldDataTypeDefinition.getUniqueId(), propertiesToAdd);
+//
+// if (addPropertiesToDataType.isRight()) {
+// log.debug("Failed to update data type {} to Graph. Status is {}", oldDataTypeDefinition, addPropertiesToDataType.right().value().name());
+// BeEcompErrorManager.getInstance().logBeFailedAddingNodeTypeError("UpdateDataType", "Property");
+// result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(addPropertiesToDataType.right().value()));
+// return result;
+// } else {
+//
+// Either<DataTypeDefinition, TitanOperationStatus> dataTypeByUid = this.getDataTypeByUid(oldDataTypeDefinition.getUniqueId());
+// if (dataTypeByUid.isRight()) {
+// TitanOperationStatus status = addPropertiesToDataType.right().value();
+// log.debug("Failed to get data type {} after update. Status is {}", oldDataTypeDefinition.getUniqueId(), status.name());
+// BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError("UpdateDataType", "Property", status.name());
+// result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+// } else {
+// result = Either.left(dataTypeByUid.left().value());
+// }
+// }
+//
+// return result;
+//
+// }
+// }
+
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1702/Migration1702.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1702/Migration1702.java
new file mode 100644
index 0000000000..861e9136a3
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1702/Migration1702.java
@@ -0,0 +1,1408 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.asdctool.impl.migration.v1702;
+
+import java.io.BufferedWriter;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStreamWriter;
+import java.io.Writer;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Optional;
+import java.util.Set;
+import java.util.UUID;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
+
+import org.apache.commons.collections.CollectionUtils;
+import org.apache.commons.io.IOUtils;
+import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.apache.commons.math3.analysis.solvers.RiddersSolver;
+import org.apache.tinkerpop.gremlin.structure.Direction;
+import org.apache.tinkerpop.gremlin.structure.Edge;
+import org.apache.tinkerpop.gremlin.structure.Vertex;
+import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
+import org.openecomp.sdc.be.components.impl.ImportUtils;
+import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
+import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum;
+import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
+import org.openecomp.sdc.be.config.BeEcompErrorManager;
+import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
+import org.openecomp.sdc.be.config.Configuration.VfModuleProperty;
+import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.graph.GraphElementFactory;
+import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
+import org.openecomp.sdc.be.dao.graph.datatype.GraphElementTypeEnum;
+import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation;
+import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
+import org.openecomp.sdc.be.dao.neo4j.GraphEdgePropertiesDictionary;
+import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
+import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.model.ArtifactDefinition;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.ComponentParametersView;
+import org.openecomp.sdc.be.model.DataTypeDefinition;
+import org.openecomp.sdc.be.model.GroupDefinition;
+import org.openecomp.sdc.be.model.GroupInstance;
+import org.openecomp.sdc.be.model.GroupProperty;
+import org.openecomp.sdc.be.model.GroupTypeDefinition;
+import org.openecomp.sdc.be.model.LifecycleStateEnum;
+import org.openecomp.sdc.be.model.Operation;
+import org.openecomp.sdc.be.model.PropertyDefinition;
+import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.ResourceMetadataDefinition;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.model.operations.impl.ComponentInstanceOperation;
+import org.openecomp.sdc.be.model.operations.impl.ComponentOperation;
+import org.openecomp.sdc.be.model.operations.impl.GroupOperation;
+import org.openecomp.sdc.be.model.operations.impl.GroupTypeOperation;
+import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
+import org.openecomp.sdc.be.model.operations.impl.ResourceOperation;
+import org.openecomp.sdc.be.model.operations.impl.ServiceOperation;
+import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
+import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
+import org.openecomp.sdc.be.resources.data.ArtifactData;
+import org.openecomp.sdc.be.resources.data.ComponentInstanceData;
+import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
+import org.openecomp.sdc.be.resources.data.DataTypeData;
+import org.openecomp.sdc.be.resources.data.GroupData;
+import org.openecomp.sdc.be.resources.data.PropertyData;
+import org.openecomp.sdc.be.resources.data.PropertyValueData;
+import org.openecomp.sdc.be.resources.data.ResourceMetadataData;
+import org.openecomp.sdc.be.resources.data.ServiceMetadataData;
+import org.openecomp.sdc.be.user.UserBusinessLogic;
+import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
+import org.openecomp.sdc.common.api.ArtifactTypeEnum;
+import org.openecomp.sdc.common.api.Constants;
+import org.openecomp.sdc.common.util.ValidationUtils;
+import org.openecomp.sdc.exception.ResponseFormat;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.yaml.snakeyaml.Yaml;
+
+import com.thinkaurelius.titan.core.TitanGraph;
+import com.thinkaurelius.titan.core.TitanGraphQuery;
+import com.thinkaurelius.titan.core.TitanVertex;
+
+import fj.data.Either;
+
+public class Migration1702 {
+ private static final String CONFIG_GROUP_TYPES_YML = "/config/groupTypes.yml";
+
+ private static final String CONFIG_DATA_TYPES_YML = "/config/dataTypes.yml";
+
+ private static Logger log = LoggerFactory.getLogger(Migration1702.class.getName());
+
+ @Autowired
+ protected TitanGenericDao titanGenericDao;
+ @Autowired
+ protected ResourceOperation resourceOperation;
+ @Autowired
+ protected ServiceOperation serviceOperation;
+ @Autowired
+ private ServiceBusinessLogic serviceBusinessLogic;
+ @Autowired
+ private GroupTypeOperation groupTypeOperation;
+ @Autowired
+ private PropertyOperation propertyOperation;
+ @Autowired
+ private ComponentsUtils componentsUtils;
+ @Autowired
+ private GroupOperation groupOperation;
+
+ @Autowired
+ private ArtifactsBusinessLogic artifactsBusinessLogic;
+
+ @Autowired
+ private UserBusinessLogic userAdminManager;
+
+ @Autowired
+ private ComponentInstanceOperation componentInstanceOperation;
+
+ public boolean migrate(String appConfigDir) {
+ boolean result = true;
+ String methodName = "alignCustomizationUUID";
+
+ try {
+ if (!alignCustomizationUUID()) {
+ log.error("Failed to align customization UUID");
+ result = false;
+ return result;
+ }
+ methodName = "alignGroupDataType";
+ if (!alignGroupDataType()) {
+ log.error("Failed to align Group data type");
+ result = false;
+ return result;
+ }
+ methodName = "alignVfModuleProperties";
+ if (!alignVfModuleProperties()) {
+ log.error("Failed to align Vf Module Properties");
+ result = false;
+ return result;
+ }
+ methodName = "alignDataType";
+ if (!alignDataType()) {
+ log.error("Failed to align data type");
+ result = false;
+ return result;
+ }
+ methodName = "alignHeatEnv";
+ if (!alignHeatEnv()) {
+ log.error("Failed to align heat env on VF level");
+ result = false;
+ return result;
+ }
+ methodName = "alignModuleInstances";
+ if (!alignModuleInstances()) {
+ log.error("Failed to align module instances");
+ result = false;
+ return result;
+ }
+
+ } catch (Exception e) {
+ log.error("Failed {} with exception: ", methodName, e);
+ result = false;
+ }
+ return result;
+ }
+
+ private boolean alignModuleInstances() {
+ log.info(" Align Module Instances");
+ boolean result = true;
+ boolean statusToReturn = true;
+
+ Writer writer = null;
+
+ try {
+ long time = System.currentTimeMillis();
+ writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("runstatusModules_" + time + ".csv"), "utf-8"));
+
+ writer.write("resource id, instance id, group id, status\n");
+
+ Either<List<ServiceMetadataData>, TitanOperationStatus> allServices = titanGenericDao.getByCriteria(NodeTypeEnum.Service, null, ServiceMetadataData.class);
+ if (allServices.isRight()) {
+ if (allServices.right().value() != TitanOperationStatus.NOT_FOUND) {
+ log.error("Align heat env on Vf - Failed to fetch services {}", allServices.right().value());
+ result = false;
+ statusToReturn = false;
+ return statusToReturn;
+ } else {
+ log.debug("No Services. ");
+ return statusToReturn;
+ }
+ }
+ log.info("Need to handle {} services", allServices.left().value().size());
+ long handledServices = 0;
+ for (ServiceMetadataData metadata : allServices.left().value()) {
+ String serviceId = metadata.getMetadataDataDefinition().getUniqueId();
+ Either<ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>>, TitanOperationStatus> riRes = componentInstanceOperation.getComponentInstancesOfComponent(serviceId, NodeTypeEnum.Service, NodeTypeEnum.Resource);
+ if (riRes.isRight()) {
+ if (riRes.right().value() == TitanOperationStatus.NOT_FOUND) {
+ log.info("No instancces for service {}", serviceId);
+ } else {
+ log.info("Align vf modules - failed to fetch component instances for service {} error {}", riRes.right().value());
+ writeModuleResultToFile(writer, serviceId, null, null, riRes.right().value());
+ statusToReturn = false;
+ }
+ ++handledServices;
+ continue;
+ }
+ List<ComponentInstance> componentInstances = riRes.left().value().left;
+ for (ComponentInstance ci : componentInstances) {
+ Either<TitanVertex, TitanOperationStatus> ciVertexRes = titanGenericDao.getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), ci.getUniqueId());
+ if (ciVertexRes.isRight()) {
+ log.info("Failed to fetch vertex for component instance {}, error {}", ci.getUniqueId(), ciVertexRes.right().value());
+ writeModuleResultToFile(writer, serviceId, ci.getUniqueId(), null, ciVertexRes.right().value());
+ statusToReturn = false;
+ continue;
+ }
+ TitanVertex ciVertex = ciVertexRes.left().value();
+ if (createGroupInstancesOnComponentInstance(writer, ci, ciVertex, serviceId) == false) {
+ statusToReturn = false;
+ continue;
+ }
+ }
+ writer.flush();
+ ++handledServices;
+ }
+
+ log.info("Handled {} services", handledServices);
+ } catch (Exception e) {
+ log.error("Failed {} with exception: ", "alignModuleInstances", e);
+ result = false;
+ statusToReturn = false;
+ } finally {
+
+ log.info(" Align Module Instances finished");
+ if (!result) {
+ log.info("Doing rollback");
+ titanGenericDao.rollback();
+ } else {
+ log.info("Doing commit");
+ titanGenericDao.commit();
+ }
+ try {
+ writer.flush();
+ writer.close();
+ } catch (Exception ex) {
+ /* ignore */}
+ }
+ return statusToReturn;
+ }
+
+ private boolean createGroupInstancesOnComponentInstance(Writer writer, ComponentInstance ci, TitanVertex ciVertex, String serviceId) {
+ boolean statusToReturn = true;
+
+ Map<String, Object> properties = titanGenericDao.getProperties(ciVertex);
+ ComponentInstanceData createdComponentInstance = GraphElementFactory.createElement(NodeTypeEnum.ResourceInstance.getName(), GraphElementTypeEnum.Node, properties, ComponentInstanceData.class);
+
+ Either<List<GroupDefinition>, TitanOperationStatus> groupEither = groupOperation.getAllGroupsFromGraph(ci.getComponentUid(), NodeTypeEnum.Resource);
+ if (groupEither.isRight()) {
+ if (groupEither.right().value() != TitanOperationStatus.OK && groupEither.right().value() != TitanOperationStatus.NOT_FOUND) {
+ TitanOperationStatus status = groupEither.right().value();
+ log.error("Failed to associate group instances to component instance {}. Status is {}", ci.getUniqueId(), status);
+ writeModuleResultToFile(writer, serviceId, ci.getUniqueId(), null, status);
+ return false;
+ } else {
+ log.debug("No groups for component instance {}. ", ci.getUniqueId());
+
+ writeModuleResultToFile(writer, serviceId, ci.getUniqueId(), null, "No groups");
+ return true;
+ }
+ }
+ List<GroupDefinition> groupsIמResource = groupEither.left().value();
+ if (groupsIמResource != null && !groupsIמResource.isEmpty()) {
+ List<GroupDefinition> vfGroupsListInResource = groupsIמResource.stream().filter(p -> p.getType().equals("org.openecomp.groups.VfModule")).collect(Collectors.toList());
+
+ for (GroupDefinition groupInResource : vfGroupsListInResource) {
+ Iterator<Edge> edgesToInstances = ciVertex.edges(Direction.OUT, GraphEdgeLabels.GROUP_INST.getProperty());
+ boolean exist = false;
+ String normalizedName = ValidationUtils.normalizeComponentInstanceName(ci.getNormalizedName() + ".." + groupInResource.getName());
+ String grInstId = UniqueIdBuilder.buildResourceInstanceUniuqeId(ci.getUniqueId(), groupInResource.getUniqueId(), normalizedName);
+
+
+ while (edgesToInstances.hasNext()) {
+ Edge edgeToInst = edgesToInstances.next();
+ Vertex grInstVertex = edgeToInst.inVertex();
+ String grId = (String) titanGenericDao.getProperty((TitanVertex) grInstVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty());
+ if (grId.equals(grInstId)) {
+ exist = true;
+ break;
+ }
+ }
+ if (!exist) {
+ Either<GroupInstance, StorageOperationStatus> status = componentInstanceOperation.createGroupInstance(ciVertex, groupInResource, ci);
+ if (status.isRight()) {
+ log.error("Failed to create group instance {} in component instance {}. Status is {}", grInstId, ci.getUniqueId(), status.right().value());
+ statusToReturn = false;
+ writeModuleResultToFile(writer, serviceId, ci.getUniqueId(), grInstId, status.right().value());
+ } else {
+ writeModuleResultToFile(writer, serviceId, ci.getUniqueId(), grInstId, "OK");
+ }
+ } else {
+ writeModuleResultToFile(writer, serviceId, ci.getUniqueId(), grInstId, "Exist");
+ }
+
+ }
+ }
+ return statusToReturn;
+ }
+
+ @SuppressWarnings("resource")
+ private boolean alignHeatEnv() {
+ Writer writer = null;
+ log.info(" Align heat env on Vf level");
+ boolean statusToReturn = true;
+
+ boolean result = true;
+ try {
+ long time = System.currentTimeMillis();
+ writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("runstatusEnv_" + time + ".csv"), "utf-8"));
+
+ writer.write("resource id, operation, artifact id, status\n");
+ User user = buildDummyUser();
+
+ Map<String, Object> props = new HashMap<String, Object>();
+ props.put(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.VF.name());
+
+ Either<List<ResourceMetadataData>, TitanOperationStatus> allResources = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, props, ResourceMetadataData.class);
+ if (allResources.isRight()) {
+ if (allResources.right().value() != TitanOperationStatus.NOT_FOUND) {
+ log.error("Align heat env on Vf - Failed to fetch resources {}", allResources.right().value());
+ statusToReturn = false;
+ result = false;
+ return statusToReturn;
+ } else {
+ log.debug("No VF resources. ");
+ return result;
+ }
+ }
+ List<ResourceMetadataData> resources = allResources.left().value();
+ log.debug("Need to handle {} resources", resources.size());
+
+ long totalHandledArtifacts = 0;
+ for (ResourceMetadataData metadata : resources) {
+ Either<List<ImmutablePair<ArtifactData, GraphEdge>>, TitanOperationStatus> artifactNodesRes = titanGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), (String) metadata.getUniqueId(),
+ GraphEdgeLabels.ARTIFACT_REF, NodeTypeEnum.ArtifactRef, ArtifactData.class);
+ if (artifactNodesRes.isRight()) {
+ if (artifactNodesRes.right().value() != TitanOperationStatus.NOT_FOUND) {
+ log.error("Align heat env on Vf - Failed to fetch artifacts for resources {}", metadata.getUniqueId(), artifactNodesRes.right().value());
+ writer.write(metadata.getUniqueId() + ",get artifacts, ,Failed to fetch artifacts " + artifactNodesRes.right().value() + "\n");
+ statusToReturn = false;
+ continue;
+ } else {
+ log.debug("No artifact for resource {} . ", metadata.getUniqueId());
+ writer.write(metadata.getUniqueId() + ",get artifacts, ,No artfacts\n");
+ continue;
+ }
+ }
+ List<ImmutablePair<ArtifactData, GraphEdge>> artifacts = artifactNodesRes.left().value();
+
+ for (ImmutablePair<ArtifactData, GraphEdge> pair : artifacts) {
+ ArtifactData artifactData = pair.left;
+ if (isNeedCreatePlaceHolder(artifactData)) {
+ // check if exist heat env - if not -> create
+ String heatEnvId = (String) artifactData.getUniqueId() + "env";
+ if (validateOrCreateHeatEnv(user, metadata, artifactData, heatEnvId, writer) == false) {
+ statusToReturn = false;
+ }
+ // check if connected to group - if not -> connect
+ if (validateOrAssociateHeatAnv(metadata, artifactData, heatEnvId, writer) == false) {
+ statusToReturn = false;
+ }
+ ++totalHandledArtifacts;
+ writer.flush();
+ }
+
+ }
+ }
+ log.debug("Total handled {} artifacts", totalHandledArtifacts);
+ } catch (Exception e) {
+ log.error("Failed {} with exception: ", "alignHeatEnv", e);
+ result = false;
+ } finally {
+
+ log.info("Aling heat env on VF level finished ");
+ if (!result) {
+ log.info("Doing rollback");
+ titanGenericDao.rollback();
+ } else {
+ log.info("Doing commit");
+ titanGenericDao.commit();
+ }
+ try {
+ writer.flush();
+ writer.close();
+ } catch (Exception ex) {
+ /* ignore */}
+ }
+ return statusToReturn;
+ }
+
+ private boolean validateOrAssociateHeatAnv(ResourceMetadataData metadata, ArtifactData artifactData, String heatEnvId, Writer writer) {
+ boolean statusToReturn = true;
+
+ String resourceId = (String) metadata.getUniqueId();
+ Either<ArtifactData, TitanOperationStatus> heatEnvArtifactRes = titanGenericDao.getNode(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), heatEnvId, ArtifactData.class);
+ if (heatEnvArtifactRes.isRight()) {
+ log.error("Align heat env on Vf - Failed to fetch heat env node for id {} {}", heatEnvId, heatEnvArtifactRes.right().value());
+ writeResultToFile(writer, "get artifact node for relation", resourceId, heatEnvId, heatEnvArtifactRes.right().value());
+ return false;
+ }
+ ArtifactData heatEnvArtifact = heatEnvArtifactRes.left().value();
+
+ Either<List<ImmutablePair<GroupData, GraphEdge>>, TitanOperationStatus> groupsForHeatRes = titanGenericDao.getParentNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), (String) artifactData.getUniqueId(),
+ GraphEdgeLabels.GROUP_ARTIFACT_REF, NodeTypeEnum.Group, GroupData.class);
+ if (groupsForHeatRes.isRight()) {
+ writeResultToFile(writer, "getChildrenNodes groups for heat", resourceId, (String) artifactData.getUniqueId(), groupsForHeatRes.right().value());
+ if (groupsForHeatRes.right().value() != TitanOperationStatus.NOT_FOUND) {
+ log.error("Align heat env on Vf - Failed to fetch groups for heat artifact {} in resources {} : {}", artifactData.getUniqueId(), metadata.getUniqueId(), groupsForHeatRes.right().value());
+ return false;
+ } else {
+ log.debug("Align heat env on Vf - No groups for heat artifact {} in resources {} : {}", artifactData.getUniqueId(), metadata.getUniqueId(), groupsForHeatRes.right().value());
+ return true;
+ }
+ }
+ List<ImmutablePair<GroupData, GraphEdge>> groupsForHeat = groupsForHeatRes.left().value();
+ Either<List<ImmutablePair<GroupData, GraphEdge>>, TitanOperationStatus> groupsForHeatEnvRes = titanGenericDao.getParentNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), heatEnvId, GraphEdgeLabels.GROUP_ARTIFACT_REF, NodeTypeEnum.Group,
+ GroupData.class);
+ List<ImmutablePair<GroupData, GraphEdge>> groupsForHeatEnv;
+ if (groupsForHeatEnvRes.isRight()) {
+ if (groupsForHeatEnvRes.right().value() != TitanOperationStatus.NOT_FOUND) {
+ log.error("Align heat env on Vf - Failed to fetch groups for heat env artifact {} in resources {} : ", artifactData.getUniqueId(), metadata.getUniqueId(), groupsForHeatEnvRes.right().value());
+ writeResultToFile(writer, "getChildrenNodes groups for heat env", resourceId, heatEnvId, groupsForHeatEnvRes.right().value());
+ return false;
+ } else {
+ groupsForHeatEnv = new ArrayList<>();
+ }
+ } else {
+ groupsForHeatEnv = groupsForHeatEnvRes.left().value();
+ }
+
+ for (ImmutablePair<GroupData, GraphEdge> heatGroup : groupsForHeat) {
+ // check if exist
+ boolean exist = false;
+ GroupDataDefinition groupDataDefinition = heatGroup.left.getGroupDataDefinition();
+ for (ImmutablePair<GroupData, GraphEdge> heatEnvGroup : groupsForHeatEnv) {
+ if (groupDataDefinition.getName().equals(heatEnvGroup.left.getGroupDataDefinition().getName())) {
+ exist = true;
+ break;
+ }
+ }
+ String groupId = (String) heatGroup.left.getUniqueId();
+ if (!exist) {
+ // need associate
+
+ Map<String, Object> properties = new HashMap<String, Object>();
+ properties.put(GraphPropertiesDictionary.NAME.getProperty(), heatEnvArtifact.getLabel());
+ Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(heatGroup.left, heatEnvArtifact, GraphEdgeLabels.GROUP_ARTIFACT_REF, properties);
+ log.trace("After associate group {} to artifact {}", groupDataDefinition.getName(), heatEnvArtifact.getUniqueIdKey());
+ if (createRelation.isRight()) {
+ log.error("Align heat env on Vf - Failed to associate heat env artifact {} to group {} : {}", artifactData.getUniqueId(), groupDataDefinition.getUniqueId(), createRelation.right().value());
+
+ writeResultToFile(writer, "associate to group- relation" + groupId, resourceId, heatEnvId, groupsForHeatRes.right().value());
+ statusToReturn = false;
+ } else {
+ writeResultToFile(writer, "associate to group " + groupId, resourceId, heatEnvId, "OK");
+ }
+ } else {
+ writeResultToFile(writer, "associate group " + groupId, resourceId, heatEnvId, "Exist");
+ }
+ }
+ return statusToReturn;
+ }
+
+ private boolean validateOrCreateHeatEnv(User user, ResourceMetadataData metadata, ArtifactData artifactData, String heatEnvId, Writer writer) {
+ String resourceId = metadata.getMetadataDataDefinition().getUniqueId();
+ boolean statusToReturn = true;
+ Either<ArtifactData, TitanOperationStatus> node = titanGenericDao.getNode(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), heatEnvId, ArtifactData.class);
+ boolean isContinue = true;
+ if (node.isRight()) {
+ if (TitanOperationStatus.NOT_FOUND == node.right().value()) {
+ // create
+ ArtifactDefinition heatArtifact = new ArtifactDefinition(artifactData.getArtifactDataDefinition());
+ ResourceMetadataDefinition resourceMetadataDataDefinition = new ResourceMetadataDefinition((ResourceMetadataDataDefinition) metadata.getMetadataDataDefinition());
+
+ Resource resource = new Resource(resourceMetadataDataDefinition);
+
+ String heatUpdater = heatArtifact.getUserIdLastUpdater();
+ Either<User, ActionStatus> userHeat = userAdminManager.getUser(heatUpdater, true);
+
+ Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder = artifactsBusinessLogic.createHeatEnvPlaceHolder(heatArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME, (String) metadata.getUniqueId(), NodeTypeEnum.Resource,
+ metadata.getMetadataDataDefinition().getName(), userHeat.left().value(), resource, null, false);
+ if (createHeatEnvPlaceHolder.isRight()) {
+ log.error("Align heat env on Vf - Failed to create heat env {} for heat {} : {}", heatEnvId, heatArtifact.getUniqueId(), createHeatEnvPlaceHolder.right().value().getText());
+ writeResultToFile(writer, "create placeholder", resourceId, heatEnvId, createHeatEnvPlaceHolder.right().value().getText());
+ isContinue = false;
+ statusToReturn = false;
+ } else {
+ writeResultToFile(writer, "create placeholder", resourceId, heatEnvId, "OK");
+ }
+ } else {
+ log.error("Align heat env on Vf - Failed to fetch heat env node for id {} {}", heatEnvId, node.right().value());
+ writeResultToFile(writer, "create placeholder - get", resourceId, heatEnvId, node.right().value());
+ isContinue = false;
+ statusToReturn = false;
+ }
+ } else {
+ writeResultToFile(writer, "create placeholder - get", resourceId, heatEnvId, "Exist");
+ }
+ if (isContinue) {
+ log.debug("associate heat env artifact to all resources ");
+ String heatUniqueId = (String) artifactData.getUniqueId();
+ Either<TitanVertex, TitanOperationStatus> heatVertexRes = titanGenericDao.getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), heatUniqueId);
+ if (heatVertexRes.isRight()) {
+ log.debug("Failed to fetch vertex for heat {} error {}", heatUniqueId, heatVertexRes.right().value());
+ writeResultToFile(writer, "create placeholder - get heat vertex", resourceId, heatEnvId, heatVertexRes.right().value());
+ statusToReturn = false;
+ return statusToReturn;
+ }
+ TitanVertex heatVertex = heatVertexRes.left().value();
+ Either<TitanVertex, TitanOperationStatus> heatEnvVertexRes = titanGenericDao.getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), heatEnvId);
+ if (heatEnvVertexRes.isRight()) {
+ log.debug("Failed to fetch vertex for heat env {} error {}", heatEnvId, heatEnvVertexRes.right().value());
+ writeResultToFile(writer, "create placeholder - get heat env vertex", resourceId, heatEnvId, heatEnvVertexRes.right().value());
+ statusToReturn = false;
+ return statusToReturn;
+ }
+
+ Vertex heatEnvVertex = heatEnvVertexRes.left().value();
+ Iterator<Edge> edgesToHeat = heatVertex.edges(Direction.IN, GraphEdgeLabels.ARTIFACT_REF.name());
+ while (edgesToHeat.hasNext()) {
+ Edge edgeToHeat = edgesToHeat.next();
+ boolean exist = false;
+ Vertex outVertexHeat = edgeToHeat.outVertex();
+ Map<String, Object> outVertexProps = titanGenericDao.getProperties(outVertexHeat);
+
+ String resIdToHeat = (String) outVertexProps.get(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
+
+ Iterator<Edge> edgesToEnv = heatEnvVertex.edges(Direction.IN, GraphEdgeLabels.ARTIFACT_REF.name());
+ while (edgesToEnv.hasNext()) {
+ Edge edgeToEnv = edgesToEnv.next();
+ Vertex outVertexEnv = edgeToEnv.outVertex();
+ String resIdToEnv = (String) titanGenericDao.getProperty((TitanVertex) outVertexEnv, GraphPropertiesDictionary.UNIQUE_ID.getProperty());
+ if (resIdToHeat.equals(resIdToEnv)) {
+ exist = true;
+ break;
+ }
+ }
+ if (!exist) {
+ Map<String, Object> properties = titanGenericDao.getProperties(edgeToHeat);
+ // need to associate additional resource to heat env
+ // update artifact label on edge
+ String heatEnvLabel = (String) titanGenericDao.getProperty((TitanVertex) heatEnvVertex, GraphPropertiesDictionary.ARTIFACT_LABEL.getProperty());
+ properties.put(GraphEdgePropertiesDictionary.NAME.getProperty(), heatEnvLabel);
+
+ TitanOperationStatus createEdge = titanGenericDao.createEdge(outVertexHeat, heatEnvVertex, GraphEdgeLabels.ARTIFACT_REF, properties);
+ if (createEdge == TitanOperationStatus.OK) {
+ writeResultToFile(writer, "associate to resource " + resIdToHeat, resourceId, heatEnvId, "OK");
+ } else {
+ writeResultToFile(writer, "associate to resource " + resIdToHeat, resourceId, heatEnvId, createEdge);
+ statusToReturn = false;
+ }
+ } else {
+ writeResultToFile(writer, "associate to resource " + resIdToHeat, resourceId, heatEnvId, "Exist");
+ }
+ }
+ }
+ return statusToReturn;
+ }
+
+ private void writeResultToFile(Writer writer, String op, String resourceId, String artifactD, Object status) {
+ try {
+ StringBuffer sb = new StringBuffer(resourceId);
+ sb.append(",").append(op).append(",").append(artifactD).append(",").append(status).append("\n");
+ writer.write(sb.toString());
+ } catch (IOException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ }
+
+ private void writeModuleResultToFile(Writer writer, String resourceId, String instanceId, String groupId, Object status) {
+ try {
+ StringBuffer sb = new StringBuffer(resourceId);
+ sb.append(",").append(instanceId).append(",").append(groupId).append(",").append(status).append("\n");
+ writer.write(sb.toString());
+ } catch (IOException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ }
+
+ private boolean isNeedCreatePlaceHolder(ArtifactData artifactData) {
+ String artifactType = artifactData.getArtifactDataDefinition().getArtifactType();
+ ArtifactTypeEnum type = ArtifactTypeEnum.findType(artifactType);
+ if (ArtifactGroupTypeEnum.DEPLOYMENT == artifactData.getArtifactDataDefinition().getArtifactGroupType() && (ArtifactTypeEnum.HEAT == type || ArtifactTypeEnum.HEAT_NET == type || ArtifactTypeEnum.HEAT_VOL == type)) {
+ return true;
+ }
+ return false;
+ }
+
+ private boolean alignVfModuleProperties() {
+ boolean result = true;
+ try {
+ log.info(" Align Vf module properties");
+
+ final Pattern pattern = Pattern.compile("\\..(.*?)\\..");
+ final String LABEL_NAME = "vf_module_label";
+ final String VOLUME_GROUP_NAME = "volume_group";
+
+ Either<TitanGraph, TitanOperationStatus> graph = titanGenericDao.getGraph();
+ if (graph.isRight()) {
+ log.error("Align Vf module properties - Failed to get graph {}", graph.right().value());
+ result = false;
+ return result;
+ }
+
+ Map<String, Object> props = new HashMap<String, Object>();
+ props.put(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.VF.name());
+
+ Either<List<ResourceMetadataData>, TitanOperationStatus> allResources = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, props, ResourceMetadataData.class);
+
+ if (allResources.isRight()) {
+ if (allResources.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
+ log.debug("Align Vf module properties - no VF resources");
+ result = true;
+ return result;
+ } else {
+ log.error("Align Vf module properties - generateTosca failed fetch all resources,error {}", allResources.right().value());
+ result = false;
+ return result;
+ }
+ }
+
+ List<ResourceMetadataData> listAllVFs = allResources.left().value();
+
+ ComponentParametersView componentParametersView = new ComponentParametersView(true);
+ componentParametersView.setIgnoreGroups(false);
+ componentParametersView.setIgnoreArtifacts(false);
+
+ log.info("Align Vf module properties - Starting to update the VF's");
+ Map<String, VfModuleProperty> vfModuleProperties = ConfigurationManager.getConfigurationManager().getConfiguration().getVfModuleProperties();
+ for (ResourceMetadataData resourceMetadataData : listAllVFs) {
+ String uniqueId = (String) resourceMetadataData.getUniqueId();
+
+ Either<Resource, StorageOperationStatus> resourceResponse = resourceOperation.getResource(uniqueId, componentParametersView, true);
+
+ if (resourceResponse.isRight()) {
+ log.error("Align Vf module properties - failed resource with UniqueID: {} , error {}", uniqueId, resourceResponse.right().value());
+ result = false;
+ return result;
+ }
+
+ Resource resource = resourceResponse.left().value();
+ List<GroupDefinition> groups = resource.getGroups();
+
+ if (groups == null || groups.isEmpty()) {
+ log.debug("Align Vf module properties - resource UniqueID: {} does not contain groups", resource.getUniqueId());
+ continue;
+ } else {
+
+ for (GroupDefinition groupDefinition : groups) {
+
+ if (groupDefinition.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)) {
+ log.info("update vf module proerties for group {} ", groupDefinition.getUniqueId());
+
+ List<GroupProperty> properties = groupDefinition.convertToGroupProperties();
+ if (properties == null) {
+ properties = new ArrayList<>();
+ }
+ Boolean isBase = false;
+ List<String> artifacts = groupDefinition.getArtifacts();
+ if (artifacts == null) {
+ artifacts = new ArrayList<>();
+ }
+ Boolean isVolumeGroup = false;
+ for (String artifactId : artifacts) {
+ ArtifactDefinition artifactDef = null;
+ Map<String, ArtifactDefinition> deploymentArtifacts = resource.getDeploymentArtifacts();
+ artifactDef = findArtifactInList(deploymentArtifacts, artifactId);
+ if (artifactDef != null && artifactDef.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType())) {
+ isVolumeGroup = true;
+ break;
+ }
+ }
+ for (GroupProperty groupProperty : properties) {
+ if (groupProperty.getName().equals(Constants.IS_BASE)) {
+ isBase = Boolean.valueOf(groupProperty.getValue());
+ break;
+ }
+ }
+
+ if (null == isBase) {
+ log.error("Align Vf module properties - isBase not found in DEFAULT_GROUP_VF_MODULE");
+ result = false;
+ return result;
+ }
+
+ String vfModuleLabel = null;
+ String moduleName = groupDefinition.getName();
+ Matcher matcher = pattern.matcher(moduleName);
+
+ if (matcher.find()) {
+ vfModuleLabel = matcher.group(1);
+ } else {
+ vfModuleLabel = moduleName;
+ }
+
+ boolean isBasePrimitive = isBase;
+ boolean isVolumeGroupPrimitive = isVolumeGroup;
+ String vfModuleLabelFinal = vfModuleLabel;
+ List<GroupProperty> propertiesToAdd = new ArrayList<>();
+ properties.stream().forEach(p -> {
+ if (p.getValueUniqueUid() == null) {
+ if (vfModuleProperties.containsKey(p.getName())) {
+ if (isBasePrimitive) {
+ p.setValue(vfModuleProperties.get(p.getName()).getForBaseModule());
+ } else {
+ p.setValue(vfModuleProperties.get(p.getName()).getForNonBaseModule());
+ }
+ } else if (p.getName().equals(VOLUME_GROUP_NAME)) {
+ p.setValue(String.valueOf(isVolumeGroupPrimitive));
+ } else if (p.getName().equals(LABEL_NAME)) {
+ p.setValue(vfModuleLabelFinal);
+ }
+ propertiesToAdd.add(p);
+ }
+
+ });
+
+ List<GroupProperty> propertiesAlreadyExistOnGraph = properties.stream().filter(p -> !(p.getValueUniqueUid() == null || p.getValueUniqueUid().isEmpty())).collect(Collectors.toList());
+ int numOfPropertiesAlreadyExist = propertiesAlreadyExistOnGraph.size();
+
+ log.debug("Need to update default values vfModule {} properties {} ", properties.size(), properties);
+
+ Either<GroupTypeDefinition, TitanOperationStatus> groupTypeRes = groupTypeOperation.getGroupTypeByUid(groupDefinition.getTypeUid());
+ if (groupTypeRes.isRight()) {
+ TitanOperationStatus operationStatus = groupTypeRes.right().value();
+ log.debug("Failed to find group type {}",groupDefinition.getTypeUid());
+ if (operationStatus == TitanOperationStatus.NOT_FOUND) {
+ result = false;
+ return result;
+ }
+ }
+
+ GroupTypeDefinition groupTypeDefinition = groupTypeRes.left().value();
+ List<PropertyDefinition> groupTypeProperties = groupTypeDefinition.getProperties();
+ Map<String, PropertyDefinition> groupTypePropertiesMap = groupTypeProperties.stream().collect(Collectors.toMap(p -> p.getName(), p -> p));
+
+ int i = numOfPropertiesAlreadyExist + 1;
+ for (GroupProperty prop : propertiesToAdd) {
+ if (prop.getUniqueId() == null || prop.getUniqueId().isEmpty()) {
+ continue;
+ }
+ GroupData groupData = new GroupData(groupDefinition);
+
+ Either<PropertyValueData, TitanOperationStatus> addPropertyToGroup = groupOperation.addPropertyToGroup(groupData, prop, groupTypePropertiesMap.get(prop.getName()), i);
+ if (addPropertyToGroup.isRight()) {
+ log.info("Failed to add properties {} to group type :{} error {} ", prop.getName(), groupData.getUniqueId(), addPropertyToGroup.right().value());
+ result = false;
+ return result;
+ }
+ ++i;
+ }
+ }
+ }
+ }
+ }
+ } catch (Exception e) {
+ log.error("Failed {} with exception: ", "alignVfModuleProperties", e);
+ result = false;
+ } finally {
+ log.info(" Align Vf module properties finished");
+ if (!result) {
+ log.info("Doing rollback");
+ titanGenericDao.rollback();
+ } else {
+ log.info("Doing commit");
+ titanGenericDao.commit();
+ }
+ }
+ return true;
+ }
+
+ private ArtifactDefinition findArtifactInList(Map<String, ArtifactDefinition> deploymentArtifacts, String artifactId) {
+ Optional<ArtifactDefinition> op = deploymentArtifacts.values().stream().filter(p -> p.getUniqueId().equals(artifactId)).findAny();
+ if (op.isPresent())
+ return op.get();
+ return null;
+ }
+
+ private boolean generateTosca() {
+ log.info("Regenerate Tosca and CSAR for VFs and Services");
+ Either<TitanGraph, TitanOperationStatus> graph = titanGenericDao.getGraph();
+ if (graph.isRight()) {
+ log.error("Failed to get graph {}", graph.right().value());
+ return false;
+ }
+ Map<String, Object> props = new HashMap<String, Object>();
+ props.put(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.VF.name());
+
+ User user = buildDummyUser();
+
+ Map<String, Object> propsHasNot = new HashMap<String, Object>();
+ propsHasNot.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
+ propsHasNot.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+
+ Either<List<ResourceMetadataData>, TitanOperationStatus> allResources = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, props, propsHasNot, ResourceMetadataData.class);
+ if (allResources.isRight()) {
+ if (allResources.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
+ log.debug("generateTosca - no VF resources");
+ } else {
+ log.info("generateTosca failed fetch all resources,error {}", allResources.right().value());
+ return false;
+ }
+ } else {
+ if (!handleComponents(user, allResources.left().value(), resourceOperation)) {
+ log.info("generateTosca failed generate tosca artifacts for resources");
+ return false;
+
+ }
+ }
+ Either<List<ServiceMetadataData>, TitanOperationStatus> allServices = titanGenericDao.getByCriteria(NodeTypeEnum.Service, null, propsHasNot, ServiceMetadataData.class);
+ if (allServices.isRight()) {
+ if (allServices.right().value() == TitanOperationStatus.NOT_FOUND) {
+ log.debug("generateTosca - no services");
+
+ } else {
+ log.debug("generateTosca failed fetch all services,error {}",allServices.right().value());
+ return false;
+ }
+ } else {
+ if (!handleComponents(user, allServices.left().value(), serviceOperation)) {
+ log.info("generateTosca failed generate tosca artifacts for services");
+ return false;
+
+ }
+ }
+ log.info("Regenerate Tosca and CSAR for VFs and Services finished");
+ return true;
+ }
+
+ private <T extends ComponentMetadataData> boolean handleComponents(User user, List<T> allResources, ComponentOperation operation) {
+ for (ComponentMetadataData resource : allResources) {
+ if (resource.getMetadataDataDefinition().isDeleted() == null || !resource.getMetadataDataDefinition().isDeleted()) {
+ Either<Component, StorageOperationStatus> component = operation.getComponent((String) resource.getUniqueId(), true);
+ if (component.isRight()) {
+ log.info("generateTosca failed fetch component with id {} , error {}", (String) resource.getUniqueId(), component.right().value());
+ return false;
+ }
+ if (populateToscaArtifactsWithLog(component.left().value(), user) != ActionStatus.OK) {
+ return false;
+ }
+ }
+ }
+ return true;
+ }
+
+ private boolean alignCustomizationUUID() {
+ boolean result = true;
+ try {
+ log.info("Update customization UUID for all component instances on graph");
+ Either<TitanGraph, TitanOperationStatus> graph = titanGenericDao.getGraph();
+ if (graph.isRight()) {
+ log.error("Failed to get graph {}", graph.right().value());
+ return result;
+ }
+ TitanGraph tGraph = graph.left().value();
+ TitanGraphQuery<? extends TitanGraphQuery> query = tGraph.query();
+ query = query.has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.ResourceInstance.getName());
+ Iterable<TitanVertex> vertices = query.vertices();
+ if (vertices == null) {
+ log.info("No component instances on graph");
+ return result;
+ }
+ Iterator<TitanVertex> iterator = vertices.iterator();
+ if (!iterator.hasNext()) {
+ log.info("No component instances on graph");
+ }
+ while (iterator.hasNext()) {
+ TitanVertex vertex = iterator.next();
+ String property = (String) titanGenericDao.getProperty(vertex, GraphPropertiesDictionary.CUSTOMIZATION_UUID.getProperty());
+ if (!ValidationUtils.validateStringNotEmpty(property)) {
+ UUID uuid = UUID.randomUUID();
+ vertex.property(GraphPropertiesDictionary.CUSTOMIZATION_UUID.getProperty(), uuid.toString());
+ }
+ }
+ } catch (Exception e) {
+ log.error("Failed {} with exception: ", "alignCustomizationUUID", e);
+ result = false;
+ } finally {
+ log.info("Update customization UUID finished ");
+ if (!result) {
+ log.info("Doing rollback");
+ titanGenericDao.rollback();
+ } else {
+ log.info("Doing commit");
+ titanGenericDao.commit();
+ }
+ }
+ return result;
+ }
+
+ private ActionStatus populateToscaArtifactsWithLog(Component component, User user) {
+ ActionStatus ret = ActionStatus.OK;
+ LifecycleStateEnum lifecycleState = component.getLifecycleState();
+ if (!needRegenarateTosca(lifecycleState)) {
+ log.debug("Component {} is in state {}, don't generatate Tosca", component.getUniqueId(), lifecycleState);
+ return ret;
+ }
+
+ try {
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> populateToscaArtifacts = serviceBusinessLogic.populateToscaArtifacts(component, user, true, false, true, true);
+ if (populateToscaArtifacts.isLeft()) {
+ log.debug("Added payload to tosca artifacts of component {} of type:{} with uniqueId:{}", component.getName(), component.getComponentType().getValue(), component.getUniqueId());
+ } else {
+ log.error("Failed to generate TOSCA artifacts for component {} of type:{} with uniqueId:{}", component.getName(), component.getComponentType().name(), component.getUniqueId());
+ return ActionStatus.GENERAL_ERROR;
+ }
+ return ret;
+ } catch (Exception e) {
+ log.error("Exception Occured When filling tosca artifact payload for component {} of type:{} with uniqueId:{}", component.getName(), component.getComponentType().name(), component.getUniqueId(), e);
+ return ActionStatus.GENERAL_ERROR;
+ }
+ }
+
+ private boolean needRegenarateTosca(LifecycleStateEnum lifecycleState) {
+ if (lifecycleState == LifecycleStateEnum.READY_FOR_CERTIFICATION || lifecycleState == LifecycleStateEnum.CERTIFICATION_IN_PROGRESS || lifecycleState == LifecycleStateEnum.CERTIFIED) {
+ return true;
+ }
+ return false;
+ }
+
+ private User buildDummyUser() {
+ User user = new User();
+ user.setUserId("migrationTask");
+ return user;
+ }
+
+ private boolean alignGroupDataType() {
+ boolean result = true;
+ try {
+ log.info(" Align group data type properties");
+ String categoryMigrationFile = CONFIG_GROUP_TYPES_YML;
+ String yamlAsString;
+ try {
+
+ InputStream inputStream = getClass().getResourceAsStream(categoryMigrationFile);
+ if (inputStream == null) {
+ log.info("Failed to load input file : {}", categoryMigrationFile);
+ result = false;
+ return result;
+ }
+ yamlAsString = IOUtils.toString(inputStream, StandardCharsets.UTF_8.name());
+
+ } catch (Exception e) {
+ log.info("Failed to load group types file exception : ", e);
+ result = false;
+ return result;
+ }
+
+ log.debug("received yaml: {}", yamlAsString);
+
+ Map<String, Object> toscaJson = (Map<String, Object>) new Yaml().load(yamlAsString);
+
+ if (toscaJson == null || toscaJson.isEmpty()) {
+ log.info("group types file is empty");
+ result = false;
+ return result;
+ }
+
+ Map<String, Object> vfModule = (Map<String, Object>) toscaJson.get("org.openecomp.groups.VfModule");
+ if (vfModule == null || vfModule.isEmpty()) {
+ log.info("No vfModule in group types file");
+ result = false;
+ return result;
+ }
+ Map<String, Object> properties = (Map<String, Object>) vfModule.get("properties");
+ if (properties == null || properties.isEmpty()) {
+ log.info("No properties for vfModule in group types file");
+ result = false;
+ return result;
+ }
+ Either<GroupTypeDefinition, StorageOperationStatus> latestGroupTypeByType = groupTypeOperation.getLatestGroupTypeByType("org.openecomp.groups.VfModule", true);
+ if (latestGroupTypeByType.isRight()) {
+ log.info("Failed to fetch org.openecomp.groups.VfModule group type, error :{}", latestGroupTypeByType.right().value());
+ result = false;
+ return result;
+ }
+ GroupTypeDefinition groupTypeInGraph = latestGroupTypeByType.left().value();
+ List<PropertyDefinition> propertiesInGraph = groupTypeInGraph.getProperties();
+
+ List<PropertyDefinition> propertiesToAdd = new ArrayList<>();
+
+ properties.entrySet().stream().filter(e -> !ifExistOnGraph(e.getKey(), propertiesInGraph)).forEach(fe -> {
+ PropertyDefinition property = new PropertyDefinition();
+ property.setName(fe.getKey());
+ Map<String, Object> definitionInYaml = (Map<String, Object>) fe.getValue();
+ property.setType((String) definitionInYaml.get("type"));
+ // Fix by Tal G
+ property.setRequired((Boolean) definitionInYaml.get("required"));
+ property.setDescription((String) definitionInYaml.get("description"));
+ // Fix by Tal G
+ String defaultValue = definitionInYaml.get("default") == null ? null : definitionInYaml.get("default").toString();
+ if (defaultValue != null) {
+ property.setDefaultValue(defaultValue);
+ }
+ propertiesToAdd.add(property);
+ });
+
+ if (!propertiesToAdd.isEmpty()) {
+ log.debug("Need to add to vfModule {} properties {} ", propertiesToAdd.size(), propertiesToAdd);
+
+ Either<Map<String, PropertyData>, TitanOperationStatus> addPropertiesToCapablityType = propertyOperation.addPropertiesToElementType(groupTypeInGraph.getUniqueId(), NodeTypeEnum.GroupType, propertiesToAdd);
+ if (addPropertiesToCapablityType.isRight()) {
+ log.info("Failed to add properties to group type :{}", addPropertiesToCapablityType.right().value());
+ result = false;
+ return result;
+ }
+ } else {
+ log.debug("No properties to add to vfModule");
+ }
+
+ } catch (Exception e) {
+ log.error("Failed {} with exception: ", "alignGroupDataType", e);
+ result = false;
+ } finally {
+ log.info(" Align group data type properties finished");
+ if (!result) {
+ log.info("Doing rollback");
+ titanGenericDao.rollback();
+ } else {
+ log.info("Doing commit");
+ titanGenericDao.commit();
+ }
+ }
+ return result;
+ }
+
+ private boolean ifExistOnGraph(String name, List<PropertyDefinition> propertiesInGraph) {
+ for (PropertyDefinition pd : propertiesInGraph) {
+ if (pd.getName().equals(name)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public boolean alignDataType() {
+
+ log.info(" Align data type properties");
+
+ boolean isSuccessful = true;
+ List<DataTypeDefinition> dataTypes = extractDataTypesFromYaml();
+
+ if (CollectionUtils.isEmpty(dataTypes)) {
+ isSuccessful = false;
+ }
+
+ List<ImmutablePair<DataTypeDefinition, Boolean>> createdElementTypes = new ArrayList<>();
+
+ Iterator<DataTypeDefinition> elementTypeItr = dataTypes.iterator();
+ if (isSuccessful) {
+ try {
+ while (elementTypeItr.hasNext()) {
+ DataTypeDefinition elementType = elementTypeItr.next();
+ String elementName = elementType.getName();
+ Either<ActionStatus, ResponseFormat> validateElementType = validateDataType(elementType);
+ if (validateElementType.isRight()) {
+ log.debug("Failed to validate data type {}. Status is {}. ", elementName, validateElementType.right().value());
+ isSuccessful = false;
+ break;
+ }
+ log.debug("Going to get data type by name {}. ", elementName);
+ Either<DataTypeDefinition, StorageOperationStatus> findElementType = propertyOperation.getDataTypeByNameWithoutDerived(elementName);
+ if (findElementType.isRight()) {
+ StorageOperationStatus status = findElementType.right().value();
+ if (status != StorageOperationStatus.NOT_FOUND) {
+ log.debug("Failed to fetch data type {}. Status is {}. ", elementName, validateElementType.right().value());
+ isSuccessful = false;
+ break;
+ } else {
+ log.debug("Going to add data type with name {}. ", elementName);
+ Either<DataTypeDefinition, StorageOperationStatus> dataModelResponse = propertyOperation.addDataType(elementType);
+
+ if (dataModelResponse.isRight()) {
+ if (dataModelResponse.right().value() != StorageOperationStatus.SCHEMA_VIOLATION) {
+ log.debug("Failed to add data type {}. Status is {}. ", elementName, dataModelResponse.right().value());
+ isSuccessful = false;
+ break;
+ } else {
+ createdElementTypes.add(new ImmutablePair<DataTypeDefinition, Boolean>(elementType, false));
+ }
+ } else {
+ createdElementTypes.add(new ImmutablePair<DataTypeDefinition, Boolean>(dataModelResponse.left().value(), true));
+ }
+
+ }
+ } else {
+ DataTypeDefinition dataTypeDefinition = findElementType.left().value();
+ log.debug("Going to update data type with name {}. ", elementName);
+ Either<Map<String, PropertyDefinition>, StorageOperationStatus> deleteDataTypeRes = propertyOperation.deleteAllPropertiesAssociatedToNode(NodeTypeEnum.DataType, dataTypeDefinition.getUniqueId());
+ if (deleteDataTypeRes.isRight()) {
+ StorageOperationStatus status = deleteDataTypeRes.right().value();
+ if (status != StorageOperationStatus.OK) {
+
+ log.debug("Failed to update data type {}. Status is {}. ", elementName, deleteDataTypeRes.right().value());
+ isSuccessful = false;
+ break;
+ }
+ }
+
+ Either<Map<String, PropertyData>, TitanOperationStatus> updateDataTypeRes = propertyOperation.addPropertiesToElementType(dataTypeDefinition.getUniqueId(), NodeTypeEnum.DataType, elementType.getProperties());
+
+ if (updateDataTypeRes.isRight()) {
+ TitanOperationStatus status = updateDataTypeRes.right().value();
+
+ log.debug("Failed to update data type {}. Status is {}. ", elementName, updateDataTypeRes.right().value());
+ isSuccessful = false;
+ break;
+
+ } else {
+ createdElementTypes.add(new ImmutablePair<DataTypeDefinition, Boolean>(elementType, true));
+ }
+
+ DataTypeData dataTypeData = new DataTypeData();
+ dataTypeData.setDataTypeDataDefinition(elementType);
+ dataTypeData.getDataTypeDataDefinition().setUniqueId(dataTypeDefinition.getUniqueId());
+ long modificationTime = System.currentTimeMillis();
+ dataTypeData.getDataTypeDataDefinition().setModificationTime(modificationTime);
+
+ Either<DataTypeData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(dataTypeData, DataTypeData.class);
+ if (updateNode.isRight()) {
+ TitanOperationStatus operationStatus = updateNode.right().value();
+ log.debug("Failed to update modification time data type {} from graph. status is {}",
+ dataTypeDefinition.getUniqueId() ,operationStatus);
+ BeEcompErrorManager.getInstance().logInternalFlowError("AddPropertyToDataType", "Failed to fetch data type. Status is " + operationStatus, ErrorSeverity.ERROR);
+ isSuccessful = false;
+ break;
+ } else {
+ log.debug("Update data type uid {}. Set modification time to {}", dataTypeDefinition.getUniqueId(), modificationTime);
+ isSuccessful = true;
+ }
+ }
+ }
+ } finally {
+ log.info(" Finish to align data type properties");
+ if (isSuccessful) {
+ propertyOperation.getTitanGenericDao().commit();
+ } else {
+ propertyOperation.getTitanGenericDao().rollback();
+ }
+ }
+ }
+ return isSuccessful;
+ }
+
+ @SuppressWarnings("unchecked")
+ private List<DataTypeDefinition> extractDataTypesFromYaml() {
+ String dataTypeYmlFilePath = CONFIG_DATA_TYPES_YML;
+ String yamlAsString;
+ try {
+
+ InputStream inputStream = getClass().getResourceAsStream(dataTypeYmlFilePath);
+ if (inputStream == null) {
+ log.info("Failed to load input file : {}", dataTypeYmlFilePath);
+ return null;
+ }
+ yamlAsString = IOUtils.toString(inputStream, StandardCharsets.UTF_8.name());
+
+ } catch (Exception e) {
+ log.info("Failed to load group types file exception : ", e);
+ return null;
+ }
+
+ log.debug("received yaml: {}", yamlAsString);
+
+ String dataTypeName;
+ List<DataTypeDefinition> dataTypes = new ArrayList<>();
+
+ Map<String, Object> toscaJson = (Map<String, Object>) new Yaml().load(yamlAsString);
+ Iterator<Entry<String, Object>> elementTypesEntryItr = toscaJson.entrySet().iterator();
+ while (elementTypesEntryItr.hasNext()) {
+ Entry<String, Object> elementTypeNameDataEntry = elementTypesEntryItr.next();
+ dataTypeName = elementTypeNameDataEntry.getKey();
+ Map<String, Object> elementTypeJsonData = (Map<String, Object>) elementTypeNameDataEntry.getValue();
+
+ DataTypeDefinition dataType = new DataTypeDefinition();
+ dataType.setName(dataTypeName);
+
+ if (elementTypeJsonData != null) {
+
+ if (elementTypeJsonData.containsKey(ToscaTagNamesEnum.DESCRIPTION.getElementName())) {
+ dataType.setDescription((String) elementTypeJsonData.get(ToscaTagNamesEnum.DESCRIPTION.getElementName()));
+ }
+ if (elementTypeJsonData.containsKey(ToscaTagNamesEnum.DERIVED_FROM.getElementName())) {
+ dataType.setDerivedFromName((String) elementTypeJsonData.get(ToscaTagNamesEnum.DERIVED_FROM.getElementName()));
+ }
+ List<PropertyDefinition> properties = getProperties(elementTypeJsonData);
+ if (elementTypeJsonData.containsKey(ToscaTagNamesEnum.PROPERTIES.getElementName())) {
+ dataType.setProperties(properties);
+ }
+ }
+ dataTypes.add(dataType);
+ }
+
+ return dataTypes;
+ }
+
+ private List<PropertyDefinition> getProperties(Map<String, Object> toscaJson) {
+ List<PropertyDefinition> values = null;
+ Either<Map<String, PropertyDefinition>, ResultStatusEnum> properties = ImportUtils.getProperties(toscaJson);
+
+ if (properties.isLeft()) {
+ values = new ArrayList<>();
+ Map<String, PropertyDefinition> propertiesMap = properties.left().value();
+ if (propertiesMap != null && propertiesMap.isEmpty() == false) {
+
+ for (Entry<String, PropertyDefinition> entry : propertiesMap.entrySet()) {
+ String propName = entry.getKey();
+ PropertyDefinition propertyDefinition = entry.getValue();
+ PropertyDefinition newPropertyDefinition = new PropertyDefinition(propertyDefinition);
+ newPropertyDefinition.setName(propName);
+ values.add(newPropertyDefinition);
+ }
+ }
+ }
+
+ return values;
+ }
+
+ private Either<ActionStatus, ResponseFormat> validateDataType(DataTypeDefinition dataType) {
+
+ String dataTypeName = dataType.getName();
+ List<PropertyDefinition> properties = dataType.getProperties();
+ if (properties == null) {
+ // At least one parameter should be defined either in the properties
+ // section or at one of the parents
+ String derivedDataType = dataType.getDerivedFromName();
+ // If there are no properties, then we can create a data type if it
+ // is an abstract one or it derives from non abstract data type
+ if ((derivedDataType == null || derivedDataType.isEmpty())) {
+ if (false == isAbstract(dataType.getName())) {
+ if (false == ToscaPropertyType.isScalarType(dataTypeName)) {
+ log.debug("Data type {} must have properties unless it derives from non abstract data type",dataType.getName());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_NOR_PROPERTIES_NEITHER_DERIVED_FROM, dataType, null);
+
+ return Either.right(responseFormat);
+ }
+ }
+ } else {
+ // if it is not a scalar data type and it derives from abstract
+ // data type, we should reject the request.
+ if (false == ToscaPropertyType.isScalarType(dataTypeName) && true == isAbstract(derivedDataType)) {
+ log.debug("Data type {} which derived from abstract data type must have at least one property",dataType.getName());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_NOR_PROPERTIES_NEITHER_DERIVED_FROM, dataType, null);
+
+ return Either.right(responseFormat);
+ }
+ }
+ } else {
+ // properties tag cannot be empty
+ if (properties.isEmpty()) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_PROPERTIES_CANNOT_BE_EMPTY, dataType, null);
+
+ return Either.right(responseFormat);
+ }
+
+ // check no duplicates
+ Set<String> collect = properties.stream().map(p -> p.getName()).collect(Collectors.toSet());
+ if (collect != null) {
+ if (properties.size() != collect.size()) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_DUPLICATE_PROPERTY, dataType, null);
+
+ return Either.right(responseFormat);
+ }
+ }
+
+ List<String> propertiesWithSameTypeAsDataType = properties.stream().filter(p -> p.getType().equals(dataType.getName())).map(p -> p.getName()).collect(Collectors.toList());
+ if (propertiesWithSameTypeAsDataType != null && propertiesWithSameTypeAsDataType.isEmpty() == false) {
+ log.debug("The data type contains properties with the type {}",dataType.getName(),dataType.getName());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_PROEPRTY_CANNOT_HAVE_SAME_TYPE_OF_DATA_TYPE, dataType, propertiesWithSameTypeAsDataType);
+
+ return Either.right(responseFormat);
+ }
+ }
+
+ String derivedDataType = dataType.getDerivedFromName();
+ if (derivedDataType != null) {
+ Either<DataTypeDefinition, StorageOperationStatus> derivedDataTypeByName = propertyOperation.getDataTypeByName(derivedDataType, true);
+ if (derivedDataTypeByName.isRight()) {
+ StorageOperationStatus status = derivedDataTypeByName.right().value();
+ if (status == StorageOperationStatus.NOT_FOUND) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_DERIVED_IS_MISSING, dataType, null);
+
+ return Either.right(responseFormat);
+ } else {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.GENERAL_ERROR, dataType, null);
+
+ return Either.right(responseFormat);
+
+ }
+ } else {
+
+ DataTypeDefinition derivedDataTypeDef = derivedDataTypeByName.left().value();
+ if (properties != null && properties.isEmpty() == false) {
+
+ if (true == isScalarType(derivedDataTypeDef)) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_CANNOT_HAVE_PROPERTIES, dataType, null);
+
+ return Either.right(responseFormat);
+ }
+
+ Set<String> allParentsProps = new HashSet<>();
+ do {
+ List<PropertyDefinition> currentParentsProps = derivedDataTypeDef.getProperties();
+ if (currentParentsProps != null) {
+ for (PropertyDefinition propertyDefinition : currentParentsProps) {
+ allParentsProps.add(propertyDefinition.getName());
+ }
+ }
+ derivedDataTypeDef = derivedDataTypeDef.getDerivedFrom();
+ } while (derivedDataTypeDef != null);
+
+ // Check that no property is already defined in one of the
+ // ancestors
+ Set<String> alreadyExistPropsCollection = properties.stream().filter(p -> allParentsProps.contains(p.getName())).map(p -> p.getName()).collect(Collectors.toSet());
+ if (alreadyExistPropsCollection != null && alreadyExistPropsCollection.isEmpty() == false) {
+ List<String> duplicateProps = new ArrayList<>();
+ duplicateProps.addAll(alreadyExistPropsCollection);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_PROPERTY_ALREADY_DEFINED_IN_ANCESTOR, dataType, duplicateProps);
+
+ return Either.right(responseFormat);
+ }
+
+ }
+ }
+ }
+ return Either.left(ActionStatus.OK);
+ }
+
+ private boolean isAbstract(String dataTypeName) {
+
+ ToscaPropertyType isPrimitiveToscaType = ToscaPropertyType.isValidType(dataTypeName);
+
+ return isPrimitiveToscaType != null && isPrimitiveToscaType.isAbstract() == true;
+
+ }
+
+ private boolean isScalarType(DataTypeDefinition dataTypeDef) {
+
+ boolean isScalar = false;
+ DataTypeDefinition dataType = dataTypeDef;
+
+ while (dataType != null) {
+
+ String name = dataType.getName();
+ if (ToscaPropertyType.isScalarType(name)) {
+ isScalar = true;
+ break;
+ }
+
+ dataType = dataType.getDerivedFrom();
+ }
+
+ return isScalar;
+ }
+
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/Migration1707.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/Migration1707.java
new file mode 100644
index 0000000000..be40e4cd0d
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/Migration1707.java
@@ -0,0 +1,37 @@
+package org.openecomp.sdc.asdctool.impl.migration.v1707;
+
+import org.openecomp.sdc.asdctool.impl.migration.Migration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+import javax.annotation.Resource;
+import java.util.List;
+
+@Component("migration1707")
+public class Migration1707 {
+
+ private static Logger LOGGER = LoggerFactory.getLogger(Migration1707.class);
+
+ private List<Migration> migrations;
+
+ public Migration1707(List<Migration> migrations) {
+ this.migrations = migrations;
+ }
+
+ public boolean migrate() {
+ for (Migration migration : migrations) {
+ LOGGER.info(String.format("Starting migration. %s", migration.description()));
+ boolean migrationCompletedSuccessfully = migration.migrate();
+ if (!migrationCompletedSuccessfully) {
+ LOGGER.error(String.format("Migration of class %s has failed.", migration.getClass()));
+ return false;
+ }
+ LOGGER.info(String.format("Completed migration. %s", migration.description()));
+ }
+ return true;
+ }
+
+
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/Migration1707Config.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/Migration1707Config.java
new file mode 100644
index 0000000000..9c39b58404
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/Migration1707Config.java
@@ -0,0 +1,240 @@
+package org.openecomp.sdc.asdctool.impl.migration.v1707;
+
+
+import java.util.List;
+
+import org.openecomp.sdc.asdctool.impl.migration.Migration;
+import org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel.MigrationByIdDerivedNodeTypeResolver;
+import org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel.NormativesMigration;
+import org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel.NormativesResolver;
+import org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel.ResourceVersionMigration;
+import org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel.ResourcesCategoriesMigration;
+import org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel.ServiceCategoriesMigration;
+import org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel.ServiceVersionMigration;
+import org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel.ServicesMigration;
+import org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel.UserStatesMigration;
+import org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel.UsersMigration;
+import org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel.VFResourcesMigration;
+import org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel.VersionMigration;
+import org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel.relations.FulfilledCapabilitiesMigrationService;
+import org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel.relations.FulfilledRequirementsMigrationService;
+import org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel.relations.RequirementsCapabilitiesMigrationService;
+import org.openecomp.sdc.be.dao.TitanClientStrategy;
+import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
+import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
+import org.openecomp.sdc.be.dao.titan.TitanGraphClient;
+import org.openecomp.sdc.be.model.DerivedNodeTypeResolver;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.model.jsontitan.operations.ArtifactsOperations;
+import org.openecomp.sdc.be.model.jsontitan.operations.CategoryOperation;
+import org.openecomp.sdc.be.model.jsontitan.operations.NodeTemplateOperation;
+import org.openecomp.sdc.be.model.jsontitan.operations.NodeTypeOperation;
+import org.openecomp.sdc.be.model.jsontitan.operations.TopologyTemplateOperation;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaDataOperation;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementLifecycleOperation;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
+import org.openecomp.sdc.be.model.operations.api.IElementOperation;
+import org.openecomp.sdc.be.model.operations.api.IUserAdminOperation;
+import org.openecomp.sdc.be.model.operations.api.ToscaDefinitionPathCalculator;
+import org.openecomp.sdc.be.model.operations.impl.ElementOperation;
+import org.openecomp.sdc.be.model.operations.impl.GroupTypeOperation;
+import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
+import org.openecomp.sdc.be.model.operations.impl.ToscaDefinitionPathCalculatorImpl;
+import org.openecomp.sdc.be.model.operations.impl.UserAdminOperation;
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.core.annotation.Order;
+
+@Configuration
+public class Migration1707Config {
+
+
+ @Bean(name = "migration1707")
+ public Migration1707 migration1707(List<Migration> migrations) {
+ return new Migration1707(migrations);
+ }
+
+ @Bean(name = "renameGraphPropertyKeysMigration")
+ @Order(1)
+ public Migration renameGraphPropertyKeysMigration() {
+ return new RenameGraphPropertyKeys();
+ }
+
+ @Bean(name = "toscaNamesUpdate")
+ @Order(2)
+ public Migration toscaNamesUpdate() {
+ return new ToscaNamesUpdate();
+ }
+
+ @Bean(name = "users-migration")
+ @Order(3)
+ public Migration usersMigration() {
+ return new UsersMigration();
+ }
+
+ @Bean(name = "resource-category-migration")
+ @Order(4)
+ public Migration resourceCategoriesMigration() {
+ return new ResourcesCategoriesMigration();
+ }
+
+ @Bean(name = "service-category-migration")
+ @Order(5)
+ public Migration serviceCategoriesMigration() {
+ return new ServiceCategoriesMigration();
+ }
+
+ @Bean(name = "normatives-migration")
+ @Order(6)
+ public Migration normativesMigration() {
+ return new NormativesMigration();
+ }
+
+ @Bean(name = "vf-migration")
+ @Order(7)
+ public Migration vfMigration() {
+ return new VFResourcesMigration();
+ }
+
+ @Bean(name = "service-migration")
+ @Order(8)
+ public Migration serviceMigration() {
+ return new ServicesMigration();
+ }
+
+ @Bean(name = "user-states-migration")
+ @Order(9)
+ public Migration userStatesMigration() {
+ return new UserStatesMigration();
+ }
+
+// @Bean(name = "tosca-template-regeneration")
+// @Order(10)
+// public Migration ToscaTemplateRegeneration() {
+// return new ToscaTemplateRegeneration();
+// }
+
+ @Bean("resource-version-migration")
+ public VersionMigration<Resource> resourceVersionMigration() {
+ return new ResourceVersionMigration();
+ }
+
+ @Bean("service-version-migration")
+ public VersionMigration<Service> serviceVersionMigration() {
+ return new ServiceVersionMigration();
+ }
+
+ @Bean(name = "normatives-resolver")
+ public NormativesResolver normativesResolver() {
+ return new NormativesResolver();
+ }
+
+ @Bean(name = "property-operation-mig")
+ public PropertyOperation propertyOperation(@Qualifier("titan-generic-dao-migration") TitanGenericDao titanGenericDao) {
+ return new PropertyOperation(titanGenericDao);
+ }
+
+ @Bean(name = "group-type-operation-mig")
+ public GroupTypeOperation groupTypeOperation(@Qualifier("titan-generic-dao-migration") TitanGenericDao titanGenericDao, @Qualifier("property-operation-mig") PropertyOperation propertyOperation) {
+ return new GroupTypeOperation(titanGenericDao, propertyOperation);
+ }
+
+ @Bean(name = "titan-generic-dao-migration")
+ public TitanGenericDao titanGenericDaoMigration(@Qualifier("migration-titan-client") TitanGraphClient titanGraphClient) {
+ return new TitanGenericDao(titanGraphClient);
+ }
+
+ @Bean(name = "migration-titan-strategy")
+ public TitanClientStrategy migrationStrategy() {
+ return new MigrationTitanStrategy();
+ }
+
+ @Bean(name = "migration-titan-client", initMethod = "createGraph")
+ public TitanGraphClient titanMigrationClient(@Qualifier("migration-titan-strategy") TitanClientStrategy titanClientStrategy) {
+ return new TitanGraphClient(titanClientStrategy);
+ }
+
+ @Bean(name = "user-operation-migration")
+ public IUserAdminOperation userOperationNewKeySpace(@Qualifier("titan-generic-dao-migration") TitanGenericDao titanGenericDao) {
+ return new UserAdminOperation(titanGenericDao);
+ }
+
+ @Bean(name = "element-operation-migration")
+ public IElementOperation elementOperationNewKeyspace(@Qualifier("titan-generic-dao-migration") TitanGenericDao titanGenericDao) {
+ return new ElementOperation(titanGenericDao);
+ }
+
+ @Bean(name = "tosca-operation-facade")
+ public ToscaOperationFacade toscaOperationFacade() {
+ return new ToscaOperationFacade();
+ }
+
+ @Bean(name = "node-type-operation")
+ public NodeTypeOperation nodeTypeOperation(@Qualifier("mig-derived-resolver") DerivedNodeTypeResolver migrationDerivedNodeTypeResolver) {
+ return new NodeTypeOperation(migrationDerivedNodeTypeResolver);
+ }
+
+ @Bean(name = "topology-template-operation")
+ public TopologyTemplateOperation topologyTemplateOperation() {
+ return new TopologyTemplateOperation();
+ }
+
+ @Bean(name = "node-template-operation")
+ public NodeTemplateOperation nodeTemplateOperation() {
+ return new NodeTemplateOperation();
+ }
+
+ @Bean(name = "titan-dao")
+ public TitanDao titanDao(@Qualifier("migration-titan-client") TitanGraphClient titanGraphClient) {
+ return new TitanDao(titanGraphClient);
+ }
+
+ @Bean(name = "category-operation")
+ public CategoryOperation categoryOperation() {
+ return new CategoryOperation();
+ }
+
+ @Bean(name = "artifacts-operation")
+ public ArtifactsOperations artifactsOperation() {
+ return new ArtifactsOperations();
+ }
+
+ @Bean(name = "tosca-data-operation")
+ public ToscaDataOperation toscaDataOperation() {
+ return new ToscaDataOperation();
+ }
+
+ @Bean(name = "tosca-element-lifecycle-operation")
+ public ToscaElementLifecycleOperation toscaElementLifecycleOperation() {
+ return new ToscaElementLifecycleOperation();
+ }
+
+ @Bean(name = "tosca-path-calculator")
+ public ToscaDefinitionPathCalculator pathCalculator() {
+ return new ToscaDefinitionPathCalculatorImpl();
+ }
+
+ @Bean(name = "fulfilled-capabilities-mig-service")
+ public FulfilledCapabilitiesMigrationService fulfilledCapabilitiesMigService() {
+ return new FulfilledCapabilitiesMigrationService();
+ }
+
+ @Bean(name = "fulfilled-requirements-mig-service")
+ public FulfilledRequirementsMigrationService requirementsMigService() {
+ return new FulfilledRequirementsMigrationService();
+ }
+
+ @Bean(name ="req-cap-mig-service")
+ public RequirementsCapabilitiesMigrationService reqCapMigService() {
+ return new RequirementsCapabilitiesMigrationService();
+ }
+
+ @Bean(name = "mig-derived-resolver")
+ public DerivedNodeTypeResolver migrationDerivedNodeTypeResolver() {
+ return new MigrationByIdDerivedNodeTypeResolver();
+ }
+
+
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/MigrationTitanStrategy.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/MigrationTitanStrategy.java
new file mode 100644
index 0000000000..9a0cc89dd6
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/MigrationTitanStrategy.java
@@ -0,0 +1,13 @@
+package org.openecomp.sdc.asdctool.impl.migration.v1707;
+
+import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.dao.TitanClientStrategy;
+
+public class MigrationTitanStrategy implements TitanClientStrategy {
+
+ @Override
+ public String getConfigFile() {
+ return ConfigurationManager.getConfigurationManager().getConfiguration().getTitanMigrationKeySpaceCfgFile();
+ }
+
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/MigrationUtils.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/MigrationUtils.java
new file mode 100644
index 0000000000..81a00b0444
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/MigrationUtils.java
@@ -0,0 +1,27 @@
+package org.openecomp.sdc.asdctool.impl.migration.v1707;
+
+import org.apache.commons.lang.enums.Enum;
+import org.openecomp.sdc.asdctool.impl.migration.MigrationException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+public class MigrationUtils {
+
+ private static Logger LOGGER = LoggerFactory.getLogger(MigrationUtils.class);
+
+ public static boolean handleError(String errorMsg) {
+ LOGGER.error(errorMsg);
+ return false;
+ }
+
+ public static <T> T handleError(T errorStatus, String errorMsg) {
+ LOGGER.error(errorMsg);
+ return errorStatus;
+ }
+
+ public static <A> A willThrowException(String withMsg) {
+ throw new MigrationException(withMsg);
+ }
+
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/RenameGraphPropertyKeys.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/RenameGraphPropertyKeys.java
new file mode 100644
index 0000000000..a69fb9d011
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/RenameGraphPropertyKeys.java
@@ -0,0 +1,38 @@
+package org.openecomp.sdc.asdctool.impl.migration.v1707;
+
+import org.openecomp.sdc.asdctool.impl.migration.MigrationMsg;
+import org.openecomp.sdc.asdctool.impl.migration.Migration;
+import org.openecomp.sdc.asdctool.impl.migration.MigrationOperationUtils;
+import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+import java.util.HashMap;
+import java.util.Map;
+
+@Component("renameGraphPropertyKeysMigration")
+public class RenameGraphPropertyKeys implements Migration {
+
+ private final static Map<String, String> KEY_PROPERTIES_TO_RENAME;
+
+ @Autowired
+ private MigrationOperationUtils migrationUtils;
+
+ static {
+ KEY_PROPERTIES_TO_RENAME = new HashMap<>();
+ KEY_PROPERTIES_TO_RENAME.put("attuid", GraphPropertiesDictionary.USERID.getProperty());
+ KEY_PROPERTIES_TO_RENAME.put("pmatt", GraphPropertiesDictionary.PROJECT_CODE.getProperty());
+ KEY_PROPERTIES_TO_RENAME.put("attContact", GraphPropertiesDictionary.CONTACT_ID.getProperty());
+ KEY_PROPERTIES_TO_RENAME.put("attCreator", GraphPropertiesDictionary.CREATOR_ID.getProperty());
+ }
+
+ @Override
+ public boolean migrate() {
+ return migrationUtils.renamePropertyKeys(KEY_PROPERTIES_TO_RENAME);
+ }
+
+ @Override
+ public String description() {
+ return MigrationMsg.RENMAE_KEY_PROPERTIES_1707.getMessage();
+ }
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/ToscaNamesUpdate.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/ToscaNamesUpdate.java
new file mode 100644
index 0000000000..262c300009
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/ToscaNamesUpdate.java
@@ -0,0 +1,368 @@
+package org.openecomp.sdc.asdctool.impl.migration.v1707;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.function.Function;
+
+import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.apache.commons.lang3.tuple.ImmutableTriple;
+import org.apache.tinkerpop.gremlin.structure.Vertex;
+import org.openecomp.sdc.asdctool.impl.migration.Migration;
+import org.openecomp.sdc.be.dao.graph.GraphElementFactory;
+import org.openecomp.sdc.be.dao.graph.datatype.GraphElementTypeEnum;
+import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
+import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
+import org.openecomp.sdc.be.dao.titan.TitanGraphClient;
+import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.openecomp.sdc.be.resources.data.AttributeData;
+import org.openecomp.sdc.be.resources.data.AttributeValueData;
+import org.openecomp.sdc.be.resources.data.CapabilityData;
+import org.openecomp.sdc.be.resources.data.CapabilityTypeData;
+import org.openecomp.sdc.be.resources.data.DataTypeData;
+import org.openecomp.sdc.be.resources.data.GroupData;
+import org.openecomp.sdc.be.resources.data.GroupTypeData;
+import org.openecomp.sdc.be.resources.data.InputValueData;
+import org.openecomp.sdc.be.resources.data.InputsData;
+import org.openecomp.sdc.be.resources.data.PolicyTypeData;
+import org.openecomp.sdc.be.resources.data.PropertyData;
+import org.openecomp.sdc.be.resources.data.PropertyValueData;
+import org.openecomp.sdc.be.resources.data.RelationshipInstData;
+import org.openecomp.sdc.be.resources.data.RelationshipTypeData;
+import org.openecomp.sdc.be.resources.data.RequirementData;
+import org.openecomp.sdc.be.resources.data.ResourceMetadataData;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+import com.thinkaurelius.titan.core.TitanVertex;
+
+import fj.data.Either;
+
+@Component("toscaNamesUpdate")
+public class ToscaNamesUpdate implements Migration {
+ private static Logger log = LoggerFactory.getLogger(ToscaNamesUpdate.class.getName());
+
+ @Override
+ public String description() {
+ return "toscaNamesUpdate";
+ }
+
+ @Autowired
+ protected TitanGenericDao titanGenericDao;
+
+ @Override
+ public boolean migrate() {
+ boolean result = true;
+ List<ImmutableTriple<NodeTypeEnum, Class<GraphNode>, Function<GraphNode, ImmutablePair<String, GraphNode>>>> updateInfoList = new ArrayList<>();
+ for (NodeTypeEnum nodeType : NodeTypeEnum.values()){
+ ImmutableTriple<NodeTypeEnum, Class<GraphNode>, Function<GraphNode, ImmutablePair<String, GraphNode>>> updateInfo = getInfo(nodeType);
+ if(null == updateInfo)
+ continue;
+ updateInfoList.add(updateInfo);
+ }
+
+ for(ImmutableTriple<NodeTypeEnum, Class<GraphNode>, Function<GraphNode, ImmutablePair<String, GraphNode>>> nodeTypeData : updateInfoList){
+ log.debug("before updating namespace on nodeType {}", nodeTypeData.left.getName());
+ result = updateNamespaceByNodeType(nodeTypeData);
+ if(!result){
+ log.debug("alignNamespace procedure failed during execution of updating namespace on nodeType {}", nodeTypeData.left.getName());
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private <T extends GraphNode> ImmutableTriple<NodeTypeEnum, Class<T>, Function<T, ImmutablePair<String, T>>> getInfo(NodeTypeEnum nodeType) {
+ switch (nodeType) {
+ case Resource:
+ Function<ResourceMetadataData, ImmutablePair<String, ResourceMetadataData>> resourceFunc = r -> updateResource(r);
+ return new ImmutableTriple(nodeType, ResourceMetadataData.class, resourceFunc);
+ case GroupType:
+ Function<GroupTypeData, ImmutablePair<String, GroupTypeData>> groupTypeFunc = g -> updateGroupType(g);
+ return new ImmutableTriple(nodeType, GroupTypeData.class, groupTypeFunc);
+ case Group:
+ Function<GroupData, ImmutablePair<String, GroupData>> groupFunc = g -> updateGroupNode(g);
+ return new ImmutableTriple(nodeType, GroupData.class, groupFunc);
+ case PolicyType:
+ Function<PolicyTypeData, ImmutablePair<String , PolicyTypeData>> policyFunc = p -> updatePolicyType(p);
+ return new ImmutableTriple(nodeType, PolicyTypeData.class, policyFunc);
+ case RelationshipType:
+ Function<RelationshipTypeData, ImmutablePair<String, RelationshipTypeData>> relTypeFunc = r -> updateRelationshipType(r);
+ return new ImmutableTriple(nodeType, RelationshipTypeData.class, relTypeFunc);
+ case RelationshipInst:
+ Function<RelationshipInstData, ImmutablePair<String, RelationshipInstData>> relFunc = r -> updateRelationshipNode(r);
+ return new ImmutableTriple(nodeType, RelationshipInstData.class, relFunc);
+ case Requirement:
+ Function<RequirementData, ImmutablePair<String, RequirementData>> reqFunc = r -> updateRequirementType(r);
+ return new ImmutableTriple(nodeType, RequirementData.class, reqFunc);
+ case CapabilityType:
+ Function<CapabilityTypeData, ImmutablePair<String, CapabilityTypeData>> capTypeFunc = c -> updateCapabilityType(c);
+ return new ImmutableTriple(nodeType, CapabilityTypeData.class, capTypeFunc);
+ case Capability:
+ Function<CapabilityData, ImmutablePair<String, CapabilityData>> capFunc = c -> updateCapabilityNode(c);
+ return new ImmutableTriple(nodeType, CapabilityData.class, capFunc);
+ case Property:
+ Function<PropertyData, ImmutablePair<String, PropertyData>> propFunc = p -> updatePropNode(p);
+ return new ImmutableTriple(nodeType, PropertyData.class, propFunc);
+ case PropertyValue:
+ Function<PropertyValueData, ImmutablePair<String, PropertyValueData>> propValueFunc = p -> updatePropValueNode(p);
+ return new ImmutableTriple(nodeType, PropertyValueData.class, propValueFunc);
+ case Attribute:
+ Function<AttributeData, ImmutablePair<String, AttributeData>> attrFunc = a -> updateAttributeNode(a);
+ return new ImmutableTriple(nodeType, AttributeData.class, attrFunc);
+ case AttributeValue:
+ Function<AttributeValueData, ImmutablePair<String, AttributeValueData>> attrValueFunc = a -> updateAttrValueNode(a);
+ return new ImmutableTriple(nodeType, AttributeValueData.class, attrValueFunc);
+ case Input:
+ Function<InputsData, ImmutablePair<String, InputsData>> inputFunc = i -> updateInputNode(i);
+ return new ImmutableTriple(nodeType, InputsData.class, inputFunc);
+ case InputValue:
+ Function<InputValueData, ImmutablePair<String, InputValueData>> inputValueFunc = i -> updateInputValueNode(i);
+ return new ImmutableTriple(nodeType, InputValueData.class, inputValueFunc);
+ case DataType:
+ Function<DataTypeData, ImmutablePair<String, DataTypeData>> dataTypeFunc = d -> updateDataType(d);
+ return new ImmutableTriple(nodeType, DataTypeData.class, dataTypeFunc);
+ default:
+ return null;
+ }
+
+ }
+
+
+
+ private boolean ifRight(TitanOperationStatus status){
+ return TitanOperationStatus.NOT_FOUND == status;
+ }
+
+ private <T extends GraphNode> boolean ifLeft(List<T> allNodes, ImmutableTriple<NodeTypeEnum, Class<T>, Function<T, ImmutablePair<String, T>>> nodeTypeData){
+ boolean result = true;
+ try {
+ for (T node : allNodes) {
+ ImmutablePair<String, T> nodeToUpdate = nodeTypeData.right.apply(node);
+ Either<T, TitanOperationStatus> updatedNode = updateNodeIncludingUID(nodeToUpdate.left, nodeToUpdate.right, nodeTypeData.middle);
+ if (updatedNode.isRight()) {
+ result = false;
+ break;
+ }
+ }
+ } finally {
+ if (!result) {
+ titanGenericDao.rollback();
+ } else {
+ titanGenericDao.commit();
+ }
+ }
+ return result;
+ }
+
+ private <T extends GraphNode> boolean updateNamespaceByNodeType(ImmutableTriple<NodeTypeEnum, Class<T>, Function<T, ImmutablePair<String, T>>> nodeTypeData) {
+ Either<List<T>, TitanOperationStatus> getAllNodes = titanGenericDao.getByCriteria(nodeTypeData.left, null, nodeTypeData.middle);
+ return getAllNodes.either(list -> ifLeft(list, nodeTypeData), status -> ifRight(status));
+ }
+
+ private ImmutablePair<String, ResourceMetadataData> updateResource(ResourceMetadataData resource) {
+ String toscaResourceName = updateNamespace(((ResourceMetadataDataDefinition) resource.getMetadataDataDefinition()).getToscaResourceName());
+ ((ResourceMetadataDataDefinition) resource.getMetadataDataDefinition()).setToscaResourceName(toscaResourceName);
+ return new ImmutablePair<>((String) resource.getUniqueId(), resource);
+ }
+
+ private ImmutablePair<String, GroupTypeData> updateGroupType(GroupTypeData group) {
+ String originId = group.getUniqueId();
+ group.getGroupTypeDataDefinition().setUniqueId(updateNamespace(originId));
+ String type = updateNamespace(group.getGroupTypeDataDefinition().getType());
+ group.getGroupTypeDataDefinition().setType(type);
+ return new ImmutablePair<>(originId, group);
+ }
+
+ private ImmutablePair<String, GroupData> updateGroupNode(GroupData group) {
+ String type = updateNamespace(group.getGroupDataDefinition().getType());
+ group.getGroupDataDefinition().setType(type);
+ return new ImmutablePair<>((String) group.getUniqueId(), group);
+ }
+
+
+ private ImmutablePair<String, PolicyTypeData> updatePolicyType(PolicyTypeData policy) {
+ String originId = policy.getUniqueId();
+ policy.getPolicyTypeDataDefinition().setUniqueId(updateNamespace(originId));
+ String type = updateNamespace(policy.getPolicyTypeDataDefinition().getType());
+ policy.getPolicyTypeDataDefinition().setType(type);
+ return new ImmutablePair<>(originId, policy);
+ }
+
+ private ImmutablePair<String, RelationshipTypeData> updateRelationshipType(RelationshipTypeData relation) {
+ String type = updateNamespace(relation.getRelationshipTypeDataDefinition().getType());
+ relation.getRelationshipTypeDataDefinition().setType(type);
+ List<String> validSources = relation.getRelationshipTypeDataDefinition().getValidSourceTypes();
+ if(null != validSources){
+ List<String> validSourceTypes = new ArrayList<>();
+ for (String validSourceType : validSources) {
+ validSourceTypes.add(updateNamespace(validSourceType));
+ }
+ relation.getRelationshipTypeDataDefinition().setValidSourceTypes(validSourceTypes);
+ }
+ return new ImmutablePair<>(relation.getUniqueId(), relation);
+ }
+
+ private ImmutablePair<String, RelationshipInstData> updateRelationshipNode(RelationshipInstData relation) {
+ String type = updateNamespace(relation.getType());
+ relation.setType(type);
+ return new ImmutablePair<>(relation.getUniqueId(), relation);
+ }
+
+ private ImmutablePair<String, RequirementData> updateRequirementType(RequirementData req) {
+ String node = req.getNode();
+ if(null != node)
+ req.setNode(updateNamespace(node));
+ String type = updateNamespace(req.getRelationshipType());
+ req.setRelationshipType(type);
+ return new ImmutablePair<>(req.getUniqueId(), req);
+ }
+
+ private ImmutablePair<String, CapabilityTypeData> updateCapabilityType(CapabilityTypeData capType) {
+ String originId = capType.getUniqueId();
+ capType.getCapabilityTypeDataDefinition().setUniqueId(updateNamespace(originId));
+ String type = updateNamespace(capType.getCapabilityTypeDataDefinition().getType());
+ capType.getCapabilityTypeDataDefinition().setType(type);
+ List<String> validSources = capType.getCapabilityTypeDataDefinition().getValidSourceTypes();
+ if(null != validSources){
+ List<String> validSourceTypes = new ArrayList<>();
+ for (String validSourceType : validSources) {
+ validSourceTypes.add(updateNamespace(validSourceType));
+ }
+ capType.getCapabilityTypeDataDefinition().setValidSourceTypes(validSourceTypes);
+ }
+ return new ImmutablePair<>(originId, capType);
+
+ }
+
+ private ImmutablePair<String, CapabilityData> updateCapabilityNode(CapabilityData capNode) {
+ List<String> validSources = capNode.getValidSourceTypes();
+ if(null != validSources){
+ List<String> validSourceTypes = new ArrayList<>();
+ for (String validSourceType : validSources) {
+ validSourceTypes.add(updateNamespace(validSourceType));
+ }
+ capNode.setValidSourceTypes(validSourceTypes);
+ }
+ return new ImmutablePair<>(capNode.getUniqueId(), capNode);
+ }
+
+
+ private ImmutablePair<String, PropertyData> updatePropNode(PropertyData propType) {
+ String originId = (String)propType.getUniqueId();
+ propType.getPropertyDataDefinition().setUniqueId(updateNamespace(originId));
+ String type = updateNamespace(propType.getPropertyDataDefinition().getType());
+ propType.getPropertyDataDefinition().setType(type);
+ if ("list".equalsIgnoreCase(type) || "map".equalsIgnoreCase(type)){
+ SchemaDefinition schema = propType.getPropertyDataDefinition().getSchema();
+ if(null != schema && null != schema.getProperty())
+ handleSchemaTypeDef(schema.getProperty());
+ }
+ return new ImmutablePair<>(originId, propType);
+ }
+
+ private ImmutablePair<String, PropertyValueData> updatePropValueNode(PropertyValueData prop) {
+ String type = updateNamespace(prop.getType());
+ prop.setType(type);
+ return new ImmutablePair<>(prop.getUniqueId(), prop);
+ }
+
+ private ImmutablePair<String, AttributeValueData> updateAttrValueNode(AttributeValueData attr) {
+ String type = updateNamespace(attr.getType());
+ attr.setType(type);
+ return new ImmutablePair<>(attr.getUniqueId(), attr);
+ }
+
+ private ImmutablePair<String, InputValueData> updateInputValueNode(InputValueData input) {
+ String type = updateNamespace(input.getType());
+ input.setType(type);
+ return new ImmutablePair<>(input.getUniqueId(), input);
+ }
+
+ private ImmutablePair<String, InputsData> updateInputNode(InputsData input){
+ String type = updateNamespace(input.getPropertyDataDefinition().getType());
+ input.getPropertyDataDefinition().setType(type);
+ if ("list".equalsIgnoreCase(type) || "map".equalsIgnoreCase(type)){
+ SchemaDefinition schema = input.getPropertyDataDefinition().getSchema();
+ if(null != schema && null != schema.getProperty())
+ handleSchemaTypeDef(schema.getProperty());
+ }
+ return new ImmutablePair<>((String)input.getUniqueId(), input);
+ }
+
+
+ private void handleSchemaTypeDef(PropertyDataDefinition schemaProp) {
+ String schemaType = updateNamespace(schemaProp.getType());
+ schemaProp.setType(schemaType);
+ }
+
+ private ImmutablePair<String, DataTypeData> updateDataType(DataTypeData dataType) {
+ String originId = dataType.getUniqueId();
+ dataType.getDataTypeDataDefinition().setUniqueId(updateNamespace(originId));
+ String name = updateNamespace(dataType.getDataTypeDataDefinition().getName());
+ dataType.getDataTypeDataDefinition().setName(name);
+ String derivedFromName = updateNamespace(dataType.getDataTypeDataDefinition().getDerivedFromName());
+ dataType.getDataTypeDataDefinition().setDerivedFromName(derivedFromName);
+ return new ImmutablePair<>(originId, dataType);
+
+ }
+
+ private ImmutablePair<String, AttributeData> updateAttributeNode(AttributeData attr){
+ String type = updateNamespace(attr.getAttributeDataDefinition().getType());
+ attr.getAttributeDataDefinition().setType(type);
+ if("list".equalsIgnoreCase(type) || "map".equalsIgnoreCase(type)){
+ SchemaDefinition schema = attr.getAttributeDataDefinition().getSchema();
+ if(null != schema && null != schema.getProperty())
+ handleSchemaTypeDef(schema.getProperty());
+ }
+ return new ImmutablePair<>(attr.getUniqueId(), attr);
+ }
+
+
+
+ private String updateNamespace(String oldName) {
+ if (oldName == null) {
+ return null;
+ }
+ String name = oldName.replace("com.att.d2.", "org.openecomp.");
+ // correcting naming convention
+ return name.replace("org.openecomp.resources.", "org.openecomp.resource.");
+ }
+
+ private <T extends GraphNode> T onSuccess(TitanVertex vertex, GraphNode node, Class<T> clazz){
+ Map<String, Object> newProp = titanGenericDao.getProperties(vertex);
+ return GraphElementFactory.createElement(node.getLabel(), GraphElementTypeEnum.Node, newProp, clazz);
+ }
+
+ private <T extends GraphNode> Either<T, TitanOperationStatus> handleNode(Vertex vertex, GraphNode node, Class<T> clazz){
+ try {
+
+ Map<String, Object> mapProps = node.toGraphMap();
+
+ for (Map.Entry<String, Object> entry : mapProps.entrySet()) {
+ vertex.property(entry.getKey(), entry.getValue());
+ }
+
+ Either<TitanVertex, TitanOperationStatus> vertexByPropertyAndLabel = titanGenericDao.getVertexByProperty(node.getUniqueIdKey(), node.getUniqueId());
+ return vertexByPropertyAndLabel.either(v -> Either.left(onSuccess(v, node, clazz)), status -> Either.right(status));
+
+ } catch (Exception e) {
+ if (log.isDebugEnabled()) {
+ log.debug("Failed to update node for {}", node.getKeyValueId(), e);
+ }
+ return Either.right(TitanGraphClient.handleTitanException(e));
+ }
+ }
+
+ private <T extends GraphNode> Either<T, TitanOperationStatus> updateNodeIncludingUID(String originId, GraphNode node, Class<T> clazz) {
+ Either<TitanVertex, TitanOperationStatus> vertexByProperty = titanGenericDao.getVertexByProperty(node.getUniqueIdKey(), originId);
+ return vertexByProperty.either(vertex -> handleNode(vertex, node, clazz), status -> Either.right(status));
+ }
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/ToscaTemplateRegeneration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/ToscaTemplateRegeneration.java
new file mode 100644
index 0000000000..824bb83ec9
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/ToscaTemplateRegeneration.java
@@ -0,0 +1,160 @@
+package org.openecomp.sdc.asdctool.impl.migration.v1707;
+
+import java.util.EnumMap;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.stream.Collectors;
+
+import org.apache.commons.collections.MapUtils;
+import org.openecomp.sdc.asdctool.impl.migration.Migration;
+import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao;
+import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
+import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
+import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
+import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
+import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
+import org.openecomp.sdc.be.model.LifecycleStateEnum;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
+import org.openecomp.sdc.be.resources.data.ESArtifactData;
+import org.openecomp.sdc.be.tosca.ToscaError;
+import org.openecomp.sdc.be.tosca.ToscaExportHandler;
+import org.openecomp.sdc.be.tosca.ToscaRepresentation;
+import org.openecomp.sdc.common.util.GeneralUtility;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+import fj.data.Either;
+
+@Component("toscaTemplateRegeneration")
+public class ToscaTemplateRegeneration implements Migration {
+
+ private static Logger LOGGER = LoggerFactory.getLogger(ToscaTemplateRegeneration.class);
+
+ @Autowired
+ protected ArtifactCassandraDao artifactCassandraDao;
+
+ @Autowired
+ private ToscaExportHandler toscaExportUtils;
+
+ @Autowired
+ private ToscaOperationFacade toscaOperationFacade;
+
+ @Override
+ public boolean migrate() {
+ boolean result = true;
+ Either<Map<GraphVertex, org.openecomp.sdc.be.model.Component>, StorageOperationStatus> getAllCertifiedComponentsRes;
+ try{
+ getAllCertifiedComponentsRes = getAllCertifiedComponents();
+ if(getAllCertifiedComponentsRes.isRight()){
+ result = false;
+ }
+ if(result && MapUtils.isNotEmpty(getAllCertifiedComponentsRes.left().value())){
+ result = regenerateToscaTemplateArtifacts(getAllCertifiedComponentsRes.left().value());
+ }
+ } catch(Exception e){
+ LOGGER.error("The exception {} has been occured upon tosca template regeneration migration. ", e);
+ result = false;
+ } finally {
+ if(result){
+ toscaOperationFacade.commit();
+ } else {
+ toscaOperationFacade.rollback();
+ }
+ }
+ return result;
+ }
+
+ private boolean regenerateToscaTemplateArtifacts(Map<GraphVertex, org.openecomp.sdc.be.model.Component> components) {
+ boolean result = true;
+
+ Map<GraphVertex, org.openecomp.sdc.be.model.Component> filteredComponents = components.entrySet()
+ .stream()
+ .filter(e -> e.getValue().getToscaArtifacts()!=null && e.getValue().getToscaArtifacts().containsKey(ToscaExportHandler.ASSET_TOSCA_TEMPLATE))
+ .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()));
+
+ for(Entry<GraphVertex, org.openecomp.sdc.be.model.Component> currComponent : filteredComponents.entrySet()){
+ result = regenerateToscaTemplateArtifact(currComponent);
+ if(!result){
+ break;
+ }
+ }
+ return result;
+ }
+
+ @SuppressWarnings("unchecked")
+ private boolean regenerateToscaTemplateArtifact(Map.Entry<GraphVertex, org.openecomp.sdc.be.model.Component> parent) {
+ boolean result = true;
+ Either<GraphVertex, TitanOperationStatus> toscaDataVertexRes = null;
+ ArtifactDataDefinition data = null;
+ LOGGER.debug("tosca artifact generation");
+ Either<ToscaRepresentation, ToscaError> exportComponent = toscaExportUtils.exportComponent(parent.getValue());
+ if (exportComponent.isRight()) {
+ LOGGER.debug("Failed export tosca yaml for component {} error {}", parent.getValue().getUniqueId(), exportComponent.right().value());
+ result = false;
+ }
+ if(result){
+ LOGGER.debug("Tosca yaml exported for component {} ", parent.getValue().getUniqueId());
+ toscaDataVertexRes = toscaOperationFacade.getTitanDao().getChildVertex(parent.getKey(), EdgeLabelEnum.TOSCA_ARTIFACTS, JsonParseFlagEnum.ParseJson);
+ if(toscaDataVertexRes.isRight()){
+ LOGGER.debug("Failed to fetch tosca data vertex {} for component {}. Status is {}", EdgeLabelEnum.TOSCA_ARTIFACTS, parent.getValue().getUniqueId(), exportComponent.right().value());
+ result = false;
+ }
+ }
+ if(result){
+ data = parent.getValue().getToscaArtifacts().get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
+ data.setArtifactChecksum(GeneralUtility.calculateMD5ByByteArray(exportComponent.left().value().getMainYaml().getBytes()));
+
+ ((Map<String, ArtifactDataDefinition>) toscaDataVertexRes.left().value().getJson()).put(ToscaExportHandler.ASSET_TOSCA_TEMPLATE, data);
+
+ Either<GraphVertex, TitanOperationStatus> updateVertexRes = toscaOperationFacade.getTitanDao().updateVertex(toscaDataVertexRes.left().value());
+ if(updateVertexRes.isRight()){
+ result = false;
+ }
+ }
+ if(result){
+ ESArtifactData artifactData = new ESArtifactData(data.getEsId(), exportComponent.left().value().getMainYaml().getBytes());
+ CassandraOperationStatus status = artifactCassandraDao.saveArtifact(artifactData);
+ if(status != CassandraOperationStatus.OK){
+ result = false;
+ }
+ }
+ return result;
+ }
+
+ public Either<Map<GraphVertex, org.openecomp.sdc.be.model.Component>, StorageOperationStatus> getAllCertifiedComponents() {
+
+ Map<GraphVertex, org.openecomp.sdc.be.model.Component> components = new HashMap<>();
+ Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
+ propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
+ Either<List<GraphVertex>, TitanOperationStatus> getVerticiesRes = toscaOperationFacade.getTitanDao().getByCriteria(null, propertiesToMatch,JsonParseFlagEnum.ParseAll);
+
+ if (getVerticiesRes.isRight() && getVerticiesRes.right().value() != TitanOperationStatus.NOT_FOUND) {
+ LOGGER.debug("Failed to fetch all certified components. Status is {}", getVerticiesRes.right().value());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVerticiesRes.right().value()));
+ }
+ if(getVerticiesRes.isLeft()){
+ List<GraphVertex> componentVerticies = getVerticiesRes.left().value();
+ for (GraphVertex componentV : componentVerticies) {
+ Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentsRes = toscaOperationFacade.getToscaElement(componentV);
+ if (getComponentsRes.isRight()) {
+ return Either.right(getComponentsRes.right().value());
+ }
+ components.put(componentV, getComponentsRes.left().value());
+ }
+ }
+ return Either.left(components);
+ }
+
+ @Override
+ public String description() {
+ return "toscaTemplateRegeneration";
+ }
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/VfModulesPropertiesAdding.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/VfModulesPropertiesAdding.java
new file mode 100644
index 0000000000..5b1441903f
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/VfModulesPropertiesAdding.java
@@ -0,0 +1,227 @@
+package org.openecomp.sdc.asdctool.impl.migration.v1707;
+
+import java.util.ArrayList;
+import java.util.EnumMap;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.stream.Collectors;
+
+import javax.annotation.Resource;
+
+import org.apache.commons.collections.CollectionUtils;
+import org.openecomp.sdc.asdctool.impl.migration.v1702.DataTypesUpdate;
+import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
+import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
+import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
+import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
+import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
+import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.DataTypeDefinition;
+import org.openecomp.sdc.be.model.GroupDefinition;
+import org.openecomp.sdc.be.model.GroupInstance;
+import org.openecomp.sdc.be.model.GroupInstanceProperty;
+import org.openecomp.sdc.be.model.GroupProperty;
+import org.openecomp.sdc.be.model.GroupTypeDefinition;
+import org.openecomp.sdc.be.model.PropertyDefinition;
+import org.openecomp.sdc.be.model.jsontitan.operations.BaseOperation;
+import org.openecomp.sdc.be.model.jsontitan.operations.TopologyTemplateOperation;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.model.operations.impl.GroupTypeOperation;
+import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
+import org.openecomp.sdc.be.resources.data.PropertyData;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+import fj.data.Either;
+
+@Component("vfModulesPropertiesAdding")
+public class VfModulesPropertiesAdding {
+
+ private static Logger LOGGER = LoggerFactory.getLogger(ToscaTemplateRegeneration.class);
+
+ @Autowired
+ private ToscaOperationFacade toscaOperationFacade;
+
+ @Autowired
+ private TopologyTemplateOperation topologyTemplateOperation;
+
+ @Resource(name ="group-type-operation-mig")
+ private GroupTypeOperation groupTypeOperation;
+
+ @Resource(name = "property-operation-mig")
+ private PropertyOperation propertyOperation;
+
+
+ public boolean migrate(String groupsTypeYmlFilePath) {
+ boolean result = true;
+ Either<Map<org.openecomp.sdc.be.model.Component, GraphVertex>, StorageOperationStatus> getAllComponentsRes = null;
+ GroupTypeDefinition vfModule;
+ Either<List<GraphVertex>, TitanOperationStatus> getAllTopologyTemplatesRes = null;
+ List<PropertyDefinition> newProperties = null;
+
+ Either<GroupTypeDefinition, TitanOperationStatus> getGroupTypeVfModuleRes ;
+ try{
+ getGroupTypeVfModuleRes = groupTypeOperation.getGroupTypeByUid("org.openecomp.groups.VfModule.1.0.grouptype");
+
+ if(getGroupTypeVfModuleRes.isRight()){
+ result = false;
+ }
+ if(result){
+ vfModule = getGroupTypeVfModuleRes.left().value();
+ newProperties = getNewVfModuleTypeProperties(getAllVfModuleTypePropertiesFromYaml(groupsTypeYmlFilePath), vfModule);
+ result = addNewPropertiesToGroupType(vfModule, newProperties);
+ }
+ if(result && CollectionUtils.isNotEmpty(newProperties)){
+ Map<GraphPropertyEnum, Object> propsHasNot = new EnumMap<>(GraphPropertyEnum.class);
+ propsHasNot.put(GraphPropertyEnum.IS_DELETED, true);
+ getAllTopologyTemplatesRes = toscaOperationFacade.getTitanDao().getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, null, propsHasNot, JsonParseFlagEnum.ParseAll);
+ if (getAllTopologyTemplatesRes.isRight() && getAllTopologyTemplatesRes.right().value() != TitanOperationStatus.NOT_FOUND) {
+ LOGGER.debug("Failed to fetch all non marked topology templates , propsHasNot {}, error {}", propsHasNot, getAllTopologyTemplatesRes.right().value());
+ result = false;
+ }
+ }
+ if(result && getAllTopologyTemplatesRes!=null && getAllTopologyTemplatesRes.isLeft()){
+ getAllComponentsRes = getAllContainerComponents(getAllTopologyTemplatesRes.left().value());
+ if(getAllComponentsRes.isRight()){
+ result = false;
+ }
+ }
+ if(result && getAllComponentsRes != null){
+ result = addNewVfModulesProperties(getAllComponentsRes.left().value(), newProperties);
+ }
+ } catch (Exception e){
+ result = false;
+ }
+ finally{
+ if(result){
+ toscaOperationFacade.commit();
+ } else {
+ toscaOperationFacade.rollback();
+ }
+ }
+ return result;
+ }
+
+ private boolean addNewVfModulesProperties(Map<org.openecomp.sdc.be.model.Component, GraphVertex> components, List<PropertyDefinition> newGroupTypeProperties) {
+ boolean result = true;
+ for(Map.Entry<org.openecomp.sdc.be.model.Component, GraphVertex> component : components.entrySet()){
+ result = addNewPropertiesToVfModules(component, newGroupTypeProperties);
+ if(!result){
+ break;
+ }
+ }
+ return result;
+ }
+
+ private boolean addNewPropertiesToVfModules(Entry<org.openecomp.sdc.be.model.Component, GraphVertex> component, List<PropertyDefinition> newGroupTypeProperties) {
+ boolean result = true;
+ List<GroupDefinition> vfModules = null;
+ if(CollectionUtils.isNotEmpty(component.getKey().getGroups())){
+ vfModules = component.getKey().getGroups().stream().filter(g -> g.getType().equals(BaseOperation.VF_MODULE)).collect(Collectors.toList());
+ }
+ if(vfModules != null){
+ vfModules.forEach(vfModule -> vfModule.getProperties().addAll(newGroupTypeProperties));
+ StorageOperationStatus status = topologyTemplateOperation.updateToscaDataOfToscaElement(component.getValue(), EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, vfModules, JsonPresentationFields.NAME);
+ if(status!= StorageOperationStatus.OK){
+ result = false;
+ }
+ }
+ if(result && CollectionUtils.isNotEmpty(component.getKey().getComponentInstances())){
+ result = addPropertiesToVfModuleInstances(component, newGroupTypeProperties);
+ }
+ return result;
+ }
+
+ private boolean addPropertiesToVfModuleInstances(Entry<org.openecomp.sdc.be.model.Component, GraphVertex> component, List<PropertyDefinition> newGroupTypeProperties) {
+ boolean result = true;
+ List<GroupInstance> vfModuleInstances;
+ List<String> pathKeys;
+ for(ComponentInstance componentInstance : component.getKey().getComponentInstances()){
+ vfModuleInstances = null;
+ if(CollectionUtils.isNotEmpty(componentInstance.getGroupInstances())){
+ vfModuleInstances = componentInstance.getGroupInstances()
+ .stream()
+ .filter(gi -> gi.getType().equals(BaseOperation.VF_MODULE))
+ .collect(Collectors.toList());
+ }
+ if(vfModuleInstances != null){
+ for(GroupInstance vfModuleInstance :vfModuleInstances){
+ vfModuleInstance.getProperties().addAll(newGroupTypeProperties);
+ pathKeys = new ArrayList<>();
+ pathKeys.add(componentInstance.getUniqueId());
+ StorageOperationStatus status = topologyTemplateOperation
+ .updateToscaDataDeepElementOfToscaElement(component.getValue(), EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS, vfModuleInstance, pathKeys, JsonPresentationFields.NAME);
+ if(status!= StorageOperationStatus.OK){
+ result = false;
+ break;
+ }
+ }
+ if(!result){
+ break;
+ }
+ }
+ }
+ return result;
+ }
+
+ private Either<Map<org.openecomp.sdc.be.model.Component, GraphVertex>, StorageOperationStatus> getAllContainerComponents(List<GraphVertex> componentsV) {
+ Map<org.openecomp.sdc.be.model.Component, GraphVertex> foundComponents = new HashMap<>();
+ Either<Map<org.openecomp.sdc.be.model.Component, GraphVertex>, StorageOperationStatus> result = null;
+ for(GraphVertex componentV : componentsV){
+ Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getToscaElement(componentV);
+ if(getComponentRes.isRight()){
+ result = Either.right(getComponentRes.right().value());
+ break;
+ }
+ foundComponents.put(getComponentRes.left().value(), componentV);
+ }
+ if(result == null){
+ result = Either.left(foundComponents);
+ }
+ return result;
+ }
+
+
+ private boolean addNewPropertiesToGroupType(GroupTypeDefinition vfModule, List<PropertyDefinition> newProperties) {
+ boolean result = true;
+ Either<Map<String, PropertyData>, TitanOperationStatus> addPropertiesRes = propertyOperation
+ .addPropertiesToElementType(vfModule.getUniqueId(), NodeTypeEnum.GroupType, newProperties);
+ if(addPropertiesRes.isRight()){
+ result = false;
+ }
+ return result;
+ }
+
+ private List<PropertyDefinition> getAllVfModuleTypePropertiesFromYaml(String groupsTypeYmlFilePath) {
+ List<DataTypeDefinition> groupTypes = DataTypesUpdate.extractDataTypesFromYaml(groupsTypeYmlFilePath);
+ DataTypeDefinition vfModule = groupTypes.stream().filter(g -> g.getName().equals(BaseOperation.VF_MODULE)).findFirst().orElse(null);
+ return vfModule.getProperties();
+ }
+
+ private List<PropertyDefinition> getNewVfModuleTypeProperties(List<PropertyDefinition> allVfModuleTypeProperties, GroupTypeDefinition vfModule) {
+ Map<String, PropertyDefinition> existingVfModuleTypeProperties = vfModule.getProperties()
+ .stream()
+ .collect(Collectors.toMap(p -> p.getName(), p -> p));
+
+ List<PropertyDefinition> newGroupTypeProperties = new ArrayList<>();
+ for(PropertyDefinition property : allVfModuleTypeProperties){
+ if(!existingVfModuleTypeProperties.containsKey(property.getName())){
+ newGroupTypeProperties.add(property);
+ }
+ }
+ return newGroupTypeProperties;
+ }
+
+ public String description() {
+ return "vfModulesPropertiesAdding";
+ }
+
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/CategoriesUtils.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/CategoriesUtils.java
new file mode 100644
index 0000000000..2ba7e013f0
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/CategoriesUtils.java
@@ -0,0 +1,25 @@
+package org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel;
+
+import org.openecomp.sdc.be.model.category.CategoryDefinition;
+import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
+
+import java.util.List;
+import java.util.stream.Collectors;
+
+public class CategoriesUtils {
+
+ public static final String OLD_CATEGORY_ID_SUB_STR = "layer";
+
+ public static List<CategoryDefinition> filterOldCategories(List<CategoryDefinition> categoryDefinitions) {
+ return categoryDefinitions.stream()
+ .filter(categoryDefinition -> !categoryDefinition.getUniqueId().contains(OLD_CATEGORY_ID_SUB_STR))
+ .collect(Collectors.toList());
+ }
+
+ public static List<SubCategoryDefinition> filterOldSubCategories(List<SubCategoryDefinition> categoryDefinitions) {
+ return categoryDefinitions.stream()
+ .filter(categoryDefinition -> !categoryDefinition.getUniqueId().contains(OLD_CATEGORY_ID_SUB_STR))
+ .collect(Collectors.toList());
+ }
+
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ComponentMigration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ComponentMigration.java
new file mode 100644
index 0000000000..c9212f91ca
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ComponentMigration.java
@@ -0,0 +1,48 @@
+package org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel;
+
+import fj.Function;
+import fj.data.Either;
+import org.openecomp.sdc.asdctool.impl.migration.v1707.MigrationUtils;
+import org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel.relations.FulfilledCapabilitiesMigrationService;
+import org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel.relations.FulfilledRequirementsMigrationService;
+import org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel.relations.RequirementsCapabilitiesMigrationService;
+import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.Resource;
+
+import static org.openecomp.sdc.asdctool.impl.migration.v1707.MigrationUtils.handleError;
+
+public abstract class ComponentMigration <T extends Component> extends JsonModelMigration<T> {
+
+ private static Logger LOGGER = LoggerFactory.getLogger(ComponentMigration.class);
+
+ @Resource(name = "tosca-operation-facade")
+ private ToscaOperationFacade toscaOperations;
+
+ @Resource(name = "req-cap-mig-service")
+ RequirementsCapabilitiesMigrationService<T> requirementsCapabilitiesMigrationService;
+
+ @Override
+ Either<T, StorageOperationStatus> save(T element) {
+ LOGGER.debug(String.format("creating component %s in new graph", element.getName()));
+ return toscaOperations.createToscaComponent(element).right().map(err -> handleError(err, String.format("failed to create component %s.", element.getName())));
+
+ }
+
+ @Override
+ Either<T, StorageOperationStatus> getElementFromNewGraph(T element) {
+ LOGGER.debug(String.format("checking if component %s already exists on new graph", element.getName()));
+ return toscaOperations.getToscaElement(element.getUniqueId(), JsonParseFlagEnum.ParseMetadata);
+ }
+
+ @Override
+ public StorageOperationStatus getNotFoundErrorStatus() {
+ return StorageOperationStatus.NOT_FOUND;
+ }
+
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/JsonModelMigration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/JsonModelMigration.java
new file mode 100644
index 0000000000..6070104d44
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/JsonModelMigration.java
@@ -0,0 +1,90 @@
+package org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel;
+
+import fj.data.Either;
+import org.openecomp.sdc.asdctool.impl.migration.MigrationMsg;
+import org.openecomp.sdc.asdctool.impl.migration.Migration;
+import org.openecomp.sdc.asdctool.impl.migration.v1707.MigrationUtils;
+import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
+
+import javax.annotation.Resource;
+import java.util.List;
+
+public abstract class JsonModelMigration<T> implements Migration {
+
+ private final boolean COMPLETED_OK = true;
+
+ @Resource(name = "titan-dao")
+ TitanDao titanDao;
+
+ @Override
+ public boolean migrate() {
+ Either<List<T>, ?> elementsToMigrate = getElementsToMigrate();
+ return elementsToMigrate.either(this::migrateElementsToNewGraph,
+ errorStatus -> MigrationUtils.handleError(MigrationMsg.FAILED_TO_RETRIEVE_NODES.getMessage(errorStatus.toString())));
+ }
+
+ boolean doPostSaveOperation(T element) {
+ return true;
+ }
+
+ boolean doPostMigrateOperation(List<T> elements) {
+ return true;
+ }
+
+ private boolean migrateElementsToNewGraph(List<T> elementsToMigrate) {
+ for (T node : elementsToMigrate) {
+ boolean migratedSuccessfully = migrateElement(node);
+ if (!migratedSuccessfully) {
+ titanDao.rollback();
+ return false;
+ }
+ titanDao.commit();
+ }
+ return postMigrate(elementsToMigrate);
+ }
+
+ private boolean migrateElement(T node) {
+ boolean savedSuccessfully = saveElementIfNotExists(node);
+ return savedSuccessfully && doPostSaveOperation(node);
+ }
+
+ private boolean postMigrate(List<T> elements) {
+ boolean postMigrateSuccessfully = doPostMigrateOperation(elements);
+ if (!postMigrateSuccessfully) {
+ titanDao.rollback();
+ return false;
+ }
+ titanDao.commit();
+ return true;
+ }
+
+ private boolean saveElementIfNotExists(T element) {
+ return isExists(element).either(isExist -> isExist || createElement(element),
+ status -> MigrationUtils.handleError(MigrationMsg.FAILED_TO_GET_NODE_FROM_GRAPH.getMessage(status.toString())));
+ }
+
+ private boolean createElement(T element) {
+ return save(element).either(savedNode -> COMPLETED_OK,
+ errorStatus -> MigrationUtils.handleError(MigrationMsg.FAILED_TO_CREATE_NODE.getMessage(element.getClass().getName(), errorStatus.toString())));
+ }
+
+ private Either<Boolean, ?> isExists(T element) {
+ Either<T, ?> byId = getElementFromNewGraph(element);
+ return byId.either(existingVal -> Either.left(true),
+ this::getEitherNotExistOrErrorStatus);
+ }
+
+ private <S> Either<Boolean, S> getEitherNotExistOrErrorStatus(S status) {
+ return status == getNotFoundErrorStatus() ? Either.left(false) : Either.right(status);
+ }
+
+ abstract Either<List<T>, ?> getElementsToMigrate();
+
+ abstract Either<T, ?> getElementFromNewGraph(T element);
+
+ abstract Either<T, ?> save(T element);
+
+ abstract <S extends Enum> S getNotFoundErrorStatus();
+
+
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/MigrationByIdDerivedNodeTypeResolver.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/MigrationByIdDerivedNodeTypeResolver.java
new file mode 100644
index 0000000000..0522ed965d
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/MigrationByIdDerivedNodeTypeResolver.java
@@ -0,0 +1,23 @@
+package org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel;
+
+import fj.data.Either;
+import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
+import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
+import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
+import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.openecomp.sdc.be.model.DerivedNodeTypeResolver;
+
+import javax.annotation.Resource;
+import java.util.Collections;
+import java.util.List;
+
+public class MigrationByIdDerivedNodeTypeResolver implements DerivedNodeTypeResolver {
+
+ @Resource(name = "titan-dao")
+ private TitanDao titanDao;
+
+ @Override
+ public Either<List<GraphVertex>, TitanOperationStatus> findDerivedResources(String parentResource) {
+ return titanDao.getVertexById(parentResource, JsonParseFlagEnum.ParseMetadata).left().map(Collections::singletonList);
+ }
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/NormativesMigration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/NormativesMigration.java
new file mode 100644
index 0000000000..5fc02301dc
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/NormativesMigration.java
@@ -0,0 +1,38 @@
+package org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel;
+
+import fj.data.Either;
+import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
+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.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.List;
+
+public class NormativesMigration extends ComponentMigration<Resource> {
+
+ private static Logger LOGGER = LoggerFactory.getLogger(NormativesMigration.class);
+
+ @javax.annotation.Resource(name = "normatives-resolver")
+ private NormativesResolver normativesResolver;
+
+ @javax.annotation.Resource(name = "resource-version-migration")
+ private VersionMigration<Resource> versionMigration;
+
+ @Override
+ public String description() {
+ return "migration of node types";
+ }
+
+ @Override
+ Either<List<Resource>, ?> getElementsToMigrate() {
+ return normativesResolver.getAllNodeTypeNormatives();
+ }
+
+ @Override
+ boolean doPostMigrateOperation(List<Resource> elements) {
+ LOGGER.info("migrating node types versions");
+ return versionMigration.buildComponentsVersionChain(elements);
+ }
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/NormativesResolver.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/NormativesResolver.java
new file mode 100644
index 0000000000..205faf5355
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/NormativesResolver.java
@@ -0,0 +1,81 @@
+package org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel;
+
+import fj.data.Either;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.operations.api.IResourceOperation;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Queue;
+import java.util.stream.Collectors;
+
+public class NormativesResolver {
+
+ @javax.annotation.Resource(name = "resource-operation")
+ private IResourceOperation resourceOperation;
+
+ /**
+ *
+ * @return list of all normatives sorted by neighboring order
+ */
+ public Either<List<Resource>, StorageOperationStatus> getAllNodeTypeNormatives() {
+ Either<List<Resource>, StorageOperationStatus> rootNormatives = resourceOperation.getRootResources();
+ return rootNormatives.either(this::getAllNormatives,
+ Either::right);
+
+ }
+
+ private Either<List<Resource>, StorageOperationStatus> getAllNormatives(List<Resource> rootResources) {
+ List<Resource> allNormatives = new ArrayList<>();
+ for (Resource rootResource : rootResources) {
+ Either<List<Resource>, StorageOperationStatus> normativesOfRoot = getAllNodeTypeNormatives(rootResource);
+ if (normativesOfRoot.isRight()) {
+ return Either.right(normativesOfRoot.right().value());
+ }
+ allNormatives.addAll(normativesOfRoot.left().value());
+ }
+ return Either.left(allNormatives);
+ }
+
+ private Either<List<Resource>, StorageOperationStatus> getAllNodeTypeNormatives(Resource root) {
+ List<Resource> normativeResources = new ArrayList<>();
+ Queue<Resource> resources = new ArrayDeque<>();
+ resources.add(root);
+ while (!resources.isEmpty()) {
+ Resource currentResource = resources.poll();
+ normativeResources.add(currentResource);
+ Either<List<Resource>, StorageOperationStatus> allDerivedResources = getAllNonVFDerivedResources(currentResource);
+ if (allDerivedResources.isRight()) {
+ return Either.right(allDerivedResources.right().value());
+ }
+ List<Resource> derivedResources = allDerivedResources.left().value();
+ replaceDerivedNameWithDerivedUniqueId(currentResource, derivedResources);
+ resources.addAll(derivedResources);
+ }
+ return Either.left(normativeResources);
+ }
+
+ private void replaceDerivedNameWithDerivedUniqueId(Resource currentResource, List<Resource> derivedResources) {
+ derivedResources.forEach(resource -> resource.setDerivedFrom(Collections.singletonList(currentResource.getUniqueId())));
+ }
+
+ private Either<List<Resource>, StorageOperationStatus> getAllNonVFDerivedResources(Resource resource) {
+ Either<List<Resource>, StorageOperationStatus> childrenNodes = resourceOperation.getAllDerivedResources(resource);
+ return childrenNodes.either(resourceList -> Either.left(filterNonVFResources(resourceList)),
+ this::resolveEmptyListOrErrorStatus);
+ }
+
+ private List<Resource> filterNonVFResources(List<Resource> resources) {
+ return resources.stream().filter(resource -> resource.getResourceType() != ResourceTypeEnum.VF).collect(Collectors.toList());
+ }
+
+ private Either<List<Resource>, StorageOperationStatus> resolveEmptyListOrErrorStatus(StorageOperationStatus storageOperationStatus) {
+ return storageOperationStatus == StorageOperationStatus.NOT_FOUND ? Either.left(Collections.emptyList()) : Either.right(storageOperationStatus);
+ }
+
+
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ResourceVersionMigration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ResourceVersionMigration.java
new file mode 100644
index 0000000000..ee222a721b
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ResourceVersionMigration.java
@@ -0,0 +1,22 @@
+package org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel;
+
+import fj.data.Either;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.operations.api.IResourceOperation;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+
+import java.util.List;
+
+public class ResourceVersionMigration extends VersionMigration<Resource> {
+
+ @javax.annotation.Resource(name = "resource-operation")
+ private IResourceOperation resourceOperation;
+
+ @Override
+ NodeTypeEnum getNodeTypeEnum() {
+ return NodeTypeEnum.Resource;
+ }
+
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ResourcesCategoriesMigration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ResourcesCategoriesMigration.java
new file mode 100644
index 0000000000..01654d284f
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ResourcesCategoriesMigration.java
@@ -0,0 +1,150 @@
+package org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel;
+
+import fj.data.Either;
+import org.openecomp.sdc.asdctool.impl.migration.MigrationMsg;
+import org.openecomp.sdc.asdctool.impl.migration.Migration;
+import org.openecomp.sdc.asdctool.impl.migration.v1707.MigrationUtils;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
+import org.openecomp.sdc.be.datatypes.category.CategoryDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.openecomp.sdc.be.model.category.CategoryDefinition;
+import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
+import org.openecomp.sdc.be.model.operations.api.IElementOperation;
+
+import javax.annotation.Resource;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+import static org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel.CategoriesUtils.filterOldCategories;
+import static org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel.CategoriesUtils.filterOldSubCategories;
+
+
+public class ResourcesCategoriesMigration implements Migration {
+
+ @Resource(name = "element-operation")
+ private IElementOperation elementOperation;
+
+ @Resource(name = "element-operation-migration")
+ private IElementOperation elementOperationMigration;
+
+ @Resource(name = "titan-dao")
+ TitanDao titanDao;
+
+ @Override
+ public String description() {
+ return "migrate resource categories";
+ }
+
+ @Override
+ public boolean migrate() {
+ return getCategoriesToMigrate().either(this::migrateCategories,
+ errorStatus -> MigrationUtils.handleError(MigrationMsg.FAILED_TO_RETRIEVE_CATEGORIES.getMessage(errorStatus.name())));
+ }
+
+ private Either<List<CategoryDefinition>, ActionStatus> getCategoriesToMigrate() {
+ return elementOperation.getAllCategories(NodeTypeEnum.ResourceNewCategory, false);
+ }
+
+ private boolean migrateCategories(List<CategoryDefinition> categoryDefinitions) {
+ List<CategoryDefinition> categoriesToMigrate = filterOldCategoriesAndSubCategories(categoryDefinitions);
+ for (CategoryDefinition categoryDefinition : categoriesToMigrate) {
+ boolean isMigrated = migrateCategoryIfNotExists(categoryDefinition);
+ if (!isMigrated) {
+ titanDao.rollback();
+ return false;
+ }
+ titanDao.commit();
+ }
+ return true;
+ }
+
+
+ //since production was malformed we need to fixed it by removing wrong categories and sub categories
+ private List<CategoryDefinition> filterOldCategoriesAndSubCategories(List<CategoryDefinition> categoryDefinitions) {
+ Map<String, List<CategoryDefinition>> categoriesByNormalName = categoryDefinitions.stream().collect(Collectors.groupingBy(CategoryDataDefinition::getNormalizedName));
+ List<CategoryDefinition> categoriesToMigrate = filterOldCategories(categoryDefinitions);
+ for (CategoryDefinition categoryDefinition : categoriesToMigrate) {
+ List<SubCategoryDefinition> newSubCategories = getAllDistinctSubCategories(categoriesByNormalName.get(categoryDefinition.getNormalizedName()));
+ categoryDefinition.setSubcategories(newSubCategories);
+ }
+ return categoriesToMigrate;
+ }
+
+ private List<SubCategoryDefinition> getAllDistinctSubCategories (List<CategoryDefinition> categoriesDefinitions) {
+ Map<String, List<SubCategoryDefinition>> subCategoriesByNormalName = categoriesDefinitions.stream().flatMap(ct -> ct.getSubcategories().stream()).collect(Collectors.groupingBy(SubCategoryDefinition::getNormalizedName));
+ return getDistinctSubCategories(subCategoriesByNormalName);
+ }
+
+ private List<SubCategoryDefinition> getDistinctSubCategories(Map<String, List<SubCategoryDefinition>> subCategoriesByNormalName) {
+ List<SubCategoryDefinition> allSubCategories = new ArrayList<>();
+ for (List<SubCategoryDefinition> subCategoryDefinitions : subCategoriesByNormalName.values()) {
+ if (subCategoryDefinitions.size() == 1) {
+ allSubCategories.addAll(subCategoryDefinitions);
+ } else {
+ allSubCategories.addAll(filterOldSubCategories(subCategoryDefinitions));
+ }
+ }
+ return allSubCategories;
+ }
+
+ private boolean migrateCategoryIfNotExists(CategoryDefinition categoryDefinition) {
+ return isExists(categoryDefinition).either(isExist -> isExist ? migrateSubCategories(categoryDefinition) : migrateCategoryAndSubCategories(categoryDefinition),
+ error -> MigrationUtils.handleError(MigrationMsg.FAILED_TO_RETRIEVE_CATEGORY.getMessage(categoryDefinition.getName(), error.name())));
+ }
+
+ private boolean migrateCategoryAndSubCategories(CategoryDefinition resourceCategory) {
+ return elementOperationMigration.createCategory(resourceCategory, NodeTypeEnum.ResourceNewCategory)
+ .either(createdCategory -> this.migrateSubCategories(resourceCategory),
+ status -> MigrationUtils.handleError(MigrationMsg.FAILED_TO_CREATE_CATEGORY.getMessage(resourceCategory.getName(), status.name())));
+ }
+
+ private boolean migrateSubCategories(CategoryDefinition categoryDefinition) {
+ for (SubCategoryDefinition subCategory : categoryDefinition.getSubcategories()) {
+ boolean isMigrated = migrateSubcategoryIfNotExists(categoryDefinition, subCategory);
+ if (!isMigrated) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private boolean migrateSubcategoryIfNotExists(CategoryDefinition parentCategory, SubCategoryDefinition subCategory) {
+ return isExists(subCategory).either(isExists -> isExists || migrateSubCategory(parentCategory, subCategory),
+ status -> MigrationUtils.handleError(MigrationMsg.FAILED_TO_RETRIEVE_CATEGORY.getMessage(subCategory.getName(), status.name())));
+ }
+
+ private boolean migrateSubCategory(CategoryDefinition categoryDefinition, SubCategoryDefinition subCategory) {
+ return elementOperationMigration.createSubCategory(categoryDefinition.getUniqueId(), subCategory, NodeTypeEnum.ResourceSubcategory)
+ .either(createdSubCategory -> true,
+ errorStatus -> MigrationUtils.handleError(MigrationMsg.FAILED_TO_CREATE_SUB_CATEGORY.getMessage(subCategory.getName(), categoryDefinition.getName(), errorStatus.name())));
+
+ }
+
+ private Either<Boolean, ActionStatus> isExists(CategoryDefinition category) {
+ Either<CategoryDefinition, ActionStatus> byId = getCategoryById(category.getUniqueId());
+ return byId.either(existingVal -> Either.left(true),
+ this::getEitherNotExistOrErrorStatus);
+ }
+
+ private Either<Boolean, ActionStatus> isExists(SubCategoryDefinition subCategory) {
+ return getSubCategoryById(subCategory.getUniqueId()).either(existingVal -> Either.left(true),
+ this::getEitherNotExistOrErrorStatus);
+ }
+
+ private Either<Boolean, ActionStatus> getEitherNotExistOrErrorStatus(ActionStatus status) {
+ return status == ActionStatus.COMPONENT_CATEGORY_NOT_FOUND ? Either.left(false) : Either.right(status);
+ }
+
+ private Either<CategoryDefinition, ActionStatus> getCategoryById(String uid) {
+ return elementOperationMigration.getCategory(NodeTypeEnum.ResourceNewCategory, uid);
+ }
+
+ private Either<SubCategoryDefinition, ActionStatus> getSubCategoryById(String uid) {
+ return elementOperationMigration.getSubCategory(NodeTypeEnum.ResourceSubcategory, uid);
+ }
+
+
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ServiceCategoriesMigration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ServiceCategoriesMigration.java
new file mode 100644
index 0000000000..f745b88d02
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ServiceCategoriesMigration.java
@@ -0,0 +1,46 @@
+package org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel;
+
+import fj.data.Either;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.openecomp.sdc.be.model.category.CategoryDefinition;
+import org.openecomp.sdc.be.model.operations.api.IElementOperation;
+import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
+
+import javax.annotation.Resource;
+import java.util.List;
+
+public class ServiceCategoriesMigration extends JsonModelMigration<CategoryDefinition> {
+
+ @Resource(name = "element-operation")
+ private IElementOperation elementOperation;
+
+ @Resource(name = "element-operation-migration")
+ private IElementOperation elementOperationMigration;
+
+
+ @Override
+ public String description() {
+ return "migrate services categories";
+ }
+
+ @Override
+ Either<List<CategoryDefinition>, ?> getElementsToMigrate() {
+ return elementOperation.getAllCategories(NodeTypeEnum.ServiceNewCategory, false).left().map(CategoriesUtils::filterOldCategories);
+ }
+
+ @Override
+ Either<CategoryDefinition, ?> getElementFromNewGraph(CategoryDefinition node) {
+ return elementOperationMigration.getCategory(NodeTypeEnum.ServiceNewCategory, node.getUniqueId());
+ }
+
+ @Override
+ Either<CategoryDefinition, ActionStatus> save(CategoryDefinition graphNode) {
+ return elementOperationMigration.createCategory(graphNode, NodeTypeEnum.ServiceNewCategory);
+ }
+
+ @Override
+ ActionStatus getNotFoundErrorStatus() {
+ return ActionStatus.COMPONENT_CATEGORY_NOT_FOUND;
+ }
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ServiceVersionMigration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ServiceVersionMigration.java
new file mode 100644
index 0000000000..4a96c2743d
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ServiceVersionMigration.java
@@ -0,0 +1,23 @@
+package org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel;
+
+import fj.data.Either;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.model.operations.api.IResourceOperation;
+import org.openecomp.sdc.be.model.operations.api.IServiceOperation;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+
+import java.util.List;
+
+public class ServiceVersionMigration extends VersionMigration<Service> {
+
+ @javax.annotation.Resource(name = "service-operation")
+ private IServiceOperation serviceOperation;
+
+ @Override
+ NodeTypeEnum getNodeTypeEnum() {
+ return NodeTypeEnum.Service;
+ }
+
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ServicesMigration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ServicesMigration.java
new file mode 100644
index 0000000000..f5ff96284f
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ServicesMigration.java
@@ -0,0 +1,107 @@
+package org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel;
+
+import fj.data.Either;
+import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
+import org.openecomp.sdc.be.model.ComponentInstanceAttribute;
+import org.openecomp.sdc.be.model.ComponentInstanceProperty;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.model.operations.api.IServiceOperation;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.model.operations.migration.MigrationErrorInformer;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.Resource;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+public class ServicesMigration extends ComponentMigration<Service> {
+
+ private static Logger LOGGER = LoggerFactory.getLogger(ServicesMigration.class);
+
+ @Resource(name = "service-operation")
+ private IServiceOperation serviceOperation;
+
+ @Resource(name = "service-version-migration")
+ private VersionMigration<Service> versionMigration;
+
+ @Override
+ public String description() {
+ return "migrate services";
+ }
+
+ @Override
+ Either<List<Service>, ?> getElementsToMigrate() {
+ return serviceOperation.getAll();
+ }
+
+ @Override
+ Either<Service, StorageOperationStatus> save(Service element) {
+ MigrationErrorInformer.logIfServiceUsingMalformedVfs(element);
+ filterOutVFInstancePropsAndAttrs(element);
+ element.setConformanceLevel("0.0");
+ requirementsCapabilitiesMigrationService.overrideInstanceCapabilitiesRequirements(element);
+ return super.save(element);
+ }
+
+ @Override
+ boolean doPostSaveOperation(Service element) {
+ return element.getComponentInstances() == null ||
+ (requirementsCapabilitiesMigrationService.associateFulfilledRequirements(element, NodeTypeEnum.Service) &&
+ requirementsCapabilitiesMigrationService.associateFulfilledCapabilities(element, NodeTypeEnum.Service));
+ }
+
+ @Override
+ boolean doPostMigrateOperation(List<Service> elements) {
+ LOGGER.info("migrating services versions");
+ return versionMigration.buildComponentsVersionChain(elements);
+ }
+
+ private void filterOutVFInstancePropsAndAttrs(Service element) {
+ if (element.getComponentInstances() != null) {
+ List<String> vfInstancesIds = getVFInstancesIds(element);
+ filterOutVFInstacnecProps(element, vfInstancesIds);
+ filterOutVFInstanceAttrs(element, vfInstancesIds);
+ }
+ }
+
+ private void filterOutVFInstanceAttrs(Service element, List<String> vfInstancesIds) {
+ Map<String, List<ComponentInstanceAttribute>> componentInstancesAttributes = element.getComponentInstancesAttributes();
+ if (componentInstancesAttributes != null) {
+ element.setComponentInstancesAttributes(filterOutVFInstanceAttributes(componentInstancesAttributes, vfInstancesIds));
+ }
+ }
+
+ private void filterOutVFInstacnecProps(Service element, List<String> vfInstancesIds) {
+ Map<String, List<ComponentInstanceProperty>> componentInstancesProperties = element.getComponentInstancesProperties();
+ if (componentInstancesProperties != null) {
+ element.setComponentInstancesProperties(filterOutVFInstanceProperties(componentInstancesProperties, vfInstancesIds));
+ }
+ }
+
+ private Map<String, List<ComponentInstanceProperty>> filterOutVFInstanceProperties(Map<String, List<ComponentInstanceProperty>> instances, List<String> vfInstanceIds) {
+ return instances.entrySet()
+ .stream()
+ .filter(entry -> !vfInstanceIds.contains(entry.getKey()))
+ .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
+ }
+
+ private Map<String, List<ComponentInstanceAttribute>> filterOutVFInstanceAttributes(Map<String, List<ComponentInstanceAttribute>> instances, List<String> vfInstanceIds) {
+ return instances.entrySet()
+ .stream()
+ .filter(entry -> !vfInstanceIds.contains(entry.getKey()))
+ .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
+ }
+
+ private List<String> getVFInstancesIds(Service service) {
+ return service.getComponentInstances()
+ .stream()
+ .filter(componentInstance -> componentInstance.getOriginType() == OriginTypeEnum.VF)
+ .map(ComponentInstanceDataDefinition::getUniqueId)
+ .collect(Collectors.toList());
+ }
+
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/UserStatesMigration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/UserStatesMigration.java
new file mode 100644
index 0000000000..b248d90bd2
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/UserStatesMigration.java
@@ -0,0 +1,159 @@
+package org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel;
+
+import com.thinkaurelius.titan.core.TitanVertex;
+import fj.data.Either;
+import org.apache.tinkerpop.gremlin.structure.Direction;
+import org.apache.tinkerpop.gremlin.structure.Edge;
+import org.apache.tinkerpop.gremlin.structure.Property;
+import org.apache.tinkerpop.gremlin.structure.Vertex;
+import org.openecomp.sdc.asdctool.impl.migration.MigrationMsg;
+import org.openecomp.sdc.asdctool.impl.migration.v1707.MigrationUtils;
+import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
+import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
+import org.openecomp.sdc.be.resources.data.UserData;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.Resource;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.stream.Collectors;
+
+import static fj.data.List.list;
+
+public class UserStatesMigration extends JsonModelMigration<Edge> {
+
+ private static final String MIGRATING_USER_ID = "jh0003";
+ private static final int OUT_VERTEX_INDEX = 0;
+ private static final int IN_VERTEX_INDEX = 1;
+ private static Logger LOGGER = LoggerFactory.getLogger(UserStatesMigration.class);
+
+ @Resource(name = "titan-generic-dao")
+ private TitanGenericDao genericDao;
+
+ @Resource(name = "titan-generic-dao-migration")
+ private TitanGenericDao genericDaoMigration;
+
+ @Override
+ public String description() {
+ return "migrate user states";
+ }
+
+
+ @Override
+ public boolean migrate() {
+// return removeMigratingUserStates() && super.migrate();
+ return super.migrate();
+ }
+
+ @Override
+ Either<List<Edge>, TitanOperationStatus> getElementsToMigrate() {
+ LOGGER.debug("fetching user states edges from old graph");
+ return genericDao.getAll(NodeTypeEnum.User, UserData.class)
+ .left().bind(this::getEdgesForUsers);
+ }
+
+ @Override
+ Either<Edge, TitanOperationStatus> getElementFromNewGraph(Edge edge) {
+ LOGGER.debug("finding user state edge in new graph");
+ Vertex outVertex = edge.outVertex();
+ String outVertexUIDKey = getVertexUniqueId(outVertex);
+ String outVertexUIDValue = outVertex.property(outVertexUIDKey).value().toString();
+
+ Vertex inVertex = edge.inVertex();
+ String inVertexUIDKey = getVertexUniqueId(inVertex);
+ String inVertexUIDValue = inVertex.property(inVertexUIDKey).value().toString();
+
+ return genericDaoMigration.getEdgeByVerticies(outVertexUIDKey, outVertexUIDValue, inVertexUIDKey, inVertexUIDValue, edge.label());
+ }
+
+ @Override
+ Either<Edge, TitanOperationStatus> save(Edge userState) {
+ Either<InOutVertices, TitanOperationStatus> titanVertices = findEdgeInOutVerticesInNewGraph(userState);
+ return titanVertices.left().bind(inOutVertices -> genericDaoMigration.copyEdge(inOutVertices.getOutVertex(), inOutVertices.getInVertex(), userState));
+ }
+
+ @Override
+ TitanOperationStatus getNotFoundErrorStatus() {
+ return TitanOperationStatus.NOT_FOUND;
+ }
+
+// private boolean removeMigratingUserStates() {
+// Either<UserData, TitanOperationStatus> migratingUser = genericDaoMigration.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), MIGRATING_USER_ID, UserData.class);
+// return migratingUser.either(user -> deleteAllEdges(user, Direction.OUT),
+// errorStatus -> MigrationUtils.handleError(MigrationMsg.FAILED_TO_RETRIEVE_MIGRATION_USER.getMessage(MIGRATING_USER_ID, errorStatus.name())));
+// }
+
+ private Either<List<Edge>, TitanOperationStatus> getEdgesForUsers(List<UserData> users) {
+ List<Edge> edges = new ArrayList<>();
+ for (UserData user : users) {
+ Either<List<Edge>, TitanOperationStatus> edgesForNode = genericDao.getEdgesForNode(user, Direction.OUT);
+ if (edgesForNode.isRight()) {
+ TitanOperationStatus errorStatus = edgesForNode.right().value();
+ LOGGER.error(MigrationMsg.FAILED_TO_RETRIEVE_USER_STATES.getMessage(user.getEmail(), errorStatus.name()));
+ return Either.right(errorStatus);
+ }
+ edges.addAll(edgesForNode.left().value());
+ }
+ return Either.left(ignoreProductEdges(edges));
+ }
+
+ private List<Edge> ignoreProductEdges(List<Edge> edges) {
+ return edges.stream().filter(edge -> !isInEdgeOfProductType(edge.inVertex())).collect(Collectors.toList());
+ }
+
+ private boolean isInEdgeOfProductType(Vertex inVertex) {
+ Property<Object> nodeLabelProperty = inVertex.property(GraphPropertiesDictionary.LABEL.getProperty());
+ return nodeLabelProperty != null && nodeLabelProperty.value().equals(NodeTypeEnum.Product.getName());
+ }
+
+ private String getVertexUniqueId(Vertex vertex) {
+ String nodeLabel = vertex.property(GraphPropertiesDictionary.LABEL.getProperty()).value().toString();
+ return UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.getByName(nodeLabel));
+ }
+
+ private Either<InOutVertices, TitanOperationStatus> findEdgeInOutVerticesInNewGraph(Edge userEdge) {
+ Either<TitanVertex, TitanOperationStatus> outVertex = getMigratedVertexByOldVertex(userEdge.outVertex());
+ Either<TitanVertex, TitanOperationStatus> inVertex = getMigratedVertexByOldVertex(userEdge.inVertex());
+ return Either.sequenceLeft(list(outVertex, inVertex)).left().map(InOutVertices::new);
+ }
+
+ private Either<TitanVertex, TitanOperationStatus> getMigratedVertexByOldVertex(Vertex vertex) {
+ String vertexUniqueId = getVertexUniqueId(vertex);
+ LOGGER.debug(String.format("fetching vertex %s from new graph", vertexUniqueId));
+ return genericDaoMigration.getVertexByProperty(vertexUniqueId, vertex.property(vertexUniqueId).value())
+ .right().map(err -> MigrationUtils.handleError(err, String.format("could not find vertex %s in new graph.", vertexUniqueId))) ;
+ }
+
+// private boolean deleteAllEdges(UserData userData, Direction direction) {
+// Either<List<Edge>, TitanOperationStatus> edgesForNode = genericDaoMigration.getEdgesForNode(userData, direction);
+// if (edgesForNode.isRight()) {
+// LOGGER.error(MigrationMsg.FAILED_TO_RETRIEVE_MIGRATION_USER_STATES.getMessage(MIGRATING_USER_ID, edgesForNode.right().value().name()));
+// return false;
+// }
+// edgesForNode.left().value().forEach(Edge::remove);
+// return true;
+// }
+
+ private class InOutVertices {
+ private TitanVertex outVertex;
+ private TitanVertex inVertex;
+
+ InOutVertices(fj.data.List<TitanVertex> inOutVertices) {
+ outVertex = inOutVertices.index(OUT_VERTEX_INDEX);
+ inVertex = inOutVertices.index(IN_VERTEX_INDEX);
+ }
+
+ TitanVertex getOutVertex() {
+ return outVertex;
+ }
+
+ TitanVertex getInVertex() {
+ return inVertex;
+ }
+ }
+
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/UsersMigration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/UsersMigration.java
new file mode 100644
index 0000000000..9dd3fc4853
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/UsersMigration.java
@@ -0,0 +1,58 @@
+package org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel;
+
+import fj.Function;
+import fj.data.Either;
+import org.openecomp.sdc.asdctool.impl.migration.v1707.MigrationUtils;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.utils.UserStatusEnum;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.operations.api.IUserAdminOperation;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.Resource;
+import java.util.List;
+
+import static org.openecomp.sdc.asdctool.impl.migration.v1707.MigrationUtils.handleError;
+
+public class UsersMigration extends JsonModelMigration<User> {
+
+ private static Logger LOGGER = LoggerFactory.getLogger(UsersMigration.class);
+
+ @Resource(name = "user-operation")
+ IUserAdminOperation userAdminOperation;
+
+ @Resource(name = "user-operation-migration")
+ IUserAdminOperation userAdminOperationMigration;
+
+
+ @Override
+ Either<List<User>, ActionStatus> getElementsToMigrate() {
+ LOGGER.debug("fetching users to migrate from old graph");
+ return userAdminOperation.getAllUsers();
+ }
+
+ @Override
+ Either<User, ActionStatus> getElementFromNewGraph(User user) {
+ LOGGER.debug(String.format("trying to load user %s from new graph", user.getUserId()));
+ return userAdminOperationMigration.getUserData(user.getUserId(), false);
+ }
+
+ @Override
+ Either<User, StorageOperationStatus> save(User user) {
+ LOGGER.debug(String.format("trying to save user %s to new graph", user.getUserId()));
+ return userAdminOperationMigration.saveUserData(user);
+ }
+
+ @Override
+ public ActionStatus getNotFoundErrorStatus() {
+ return ActionStatus.USER_NOT_FOUND;
+ }
+
+ @Override
+ public String description() {
+ return "migrate users";
+ }
+
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/VFResourcesMigration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/VFResourcesMigration.java
new file mode 100644
index 0000000000..b684883323
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/VFResourcesMigration.java
@@ -0,0 +1,53 @@
+package org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel;
+
+import fj.data.Either;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.operations.api.IResourceOperation;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.List;
+
+public class VFResourcesMigration extends ComponentMigration<Resource> {
+
+ private static Logger LOGGER = LoggerFactory.getLogger(VFResourcesMigration.class);
+
+ @javax.annotation.Resource(name = "resource-operation")
+ private IResourceOperation resourceOperation;
+
+ @javax.annotation.Resource(name = "resource-version-migration")
+ private VersionMigration<Resource> versionMigration;
+
+ @Override
+ public String description() {
+ return "migrate VFs";
+ }
+
+ @Override
+ Either<List<Resource>, ?> getElementsToMigrate() {
+ return resourceOperation.getVFResources();
+ }
+
+ @Override
+ Either<Resource, StorageOperationStatus> save(Resource element) {
+ requirementsCapabilitiesMigrationService.overrideInstanceCapabilitiesRequirements(element);
+ return super.save(element);
+ }
+
+ @Override
+ boolean doPostSaveOperation(Resource element) {
+ return element.getComponentInstances() == null ||
+ (requirementsCapabilitiesMigrationService.associateFulfilledRequirements(element, NodeTypeEnum.Resource) &&
+ requirementsCapabilitiesMigrationService.associateFulfilledCapabilities(element, NodeTypeEnum.Resource));
+ }
+
+ @Override
+ boolean doPostMigrateOperation(List<Resource> elements) {
+ LOGGER.info("migrating VFs versions");
+ return versionMigration.buildComponentsVersionChain(elements);
+ }
+
+
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/VersionMigration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/VersionMigration.java
new file mode 100644
index 0000000000..7dadd79a1b
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/VersionMigration.java
@@ -0,0 +1,126 @@
+package org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel;
+
+import fj.data.Either;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.tinkerpop.gremlin.structure.Edge;
+import org.openecomp.sdc.asdctool.impl.migration.MigrationException;
+import org.openecomp.sdc.asdctool.impl.migration.MigrationMsg;
+import org.openecomp.sdc.asdctool.impl.migration.v1707.MigrationUtils;
+import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
+import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
+import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
+import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
+import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.Resource;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+public abstract class VersionMigration<T extends Component> {
+
+ private static Logger LOGGER = LoggerFactory.getLogger(VersionMigration.class);
+
+ @Resource(name = "titan-generic-dao-migration")
+ private TitanGenericDao titanGenericDaoMigration;
+
+ @Resource(name = "titan-dao")
+ private TitanDao titanDao;
+
+ public boolean buildComponentsVersionChain(List<T> components) {
+ setMissingInvariantUid(components);
+ Map<String, List<T>> componentsByInvariant = components.stream().collect(Collectors.groupingBy(Component::getInvariantUUID));
+ for (List<T> componentsList : componentsByInvariant.values()) {
+ boolean versionChainBuilt = buildVersionChainForInvariant(componentsList);
+ if (!versionChainBuilt) {
+ titanDao.rollback();
+ return false;
+ }
+ titanDao.commit();
+ }
+ return true;
+ }
+
+ private boolean buildVersionChainForInvariant(List<T> components) {
+ sortComponentsByVersion(components);
+ for (int i = 0; i < components.size() -1; i++) {
+ String lowerVersionUid = components.get(i).getUniqueId();
+ String higherVersionUid = components.get(i + 1).getUniqueId();
+ boolean versionCreated = createVersionRelationIfNotExist(lowerVersionUid, higherVersionUid);
+ if (!versionCreated) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private void sortComponentsByVersion(List<T> components) {
+ Collections.sort(components, (o1, o2) -> o1.getVersion().compareTo(o2.getVersion()));
+ }
+
+ private boolean createVersionRelationIfNotExist(String fromUid, String toUid) {
+ Either<Boolean, TitanOperationStatus> isVersionExists = isVersionExists(fromUid, toUid);
+ return isVersionExists.either(versionExists -> versionExists || createVersionRelation(fromUid, toUid),
+ errorStatus -> MigrationUtils.handleError(MigrationMsg.FAILED_TO_RETRIEVE_VERSION_RELATION.getMessage(fromUid, toUid, isVersionExists.right().value().name())));
+ }
+
+ private boolean createVersionRelation(String fromUid, String toUid) {
+ LOGGER.debug(String.format("creating version edge between vertex %s and vertex %s", fromUid, toUid));
+ Either<GraphVertex, TitanOperationStatus> vertexById = titanDao.getVertexById(fromUid);
+ Either<GraphVertex, TitanOperationStatus> vertexById1 = titanDao.getVertexById(toUid);
+ if (vertexById1.isLeft() && vertexById.isLeft()) {
+ TitanOperationStatus versionCreated = titanDao.createEdge(vertexById.left().value(), vertexById1.left().value(), EdgeLabelEnum.VERSION, new HashMap<>());
+ return versionCreated == TitanOperationStatus.OK;
+ }
+ return MigrationUtils.handleError(String.format("could not create version edge between vertex %s and vertex %s.", fromUid, toUid));
+ }
+
+ private Either<Boolean, TitanOperationStatus> isVersionExists(String fromUid, String toUid) {
+ LOGGER.debug(String.format("checking if version edge between vertex %s and vertex %s already exist", fromUid, toUid));
+ String uidKey = UniqueIdBuilder.getKeyByNodeType(getNodeTypeEnum());
+ Either<Edge, TitanOperationStatus> edgeByVertices = titanGenericDaoMigration.getEdgeByVerticies(uidKey, fromUid, uidKey, toUid, EdgeLabelEnum.VERSION.name());
+ if (isNotFoundStatus(edgeByVertices)) {
+ return Either.left(false);
+ }
+ return edgeByVertices.bimap(foundEdge -> true,
+ error -> error);
+ }
+
+ private boolean isNotFoundStatus(Either<Edge, TitanOperationStatus> edgeByVertices) {
+ return edgeByVertices.isRight() && edgeByVertices.right().value() == TitanOperationStatus.NOT_FOUND;
+ }
+
+ abstract NodeTypeEnum getNodeTypeEnum();
+
+ //some invariatn uids are missing in production
+ private void setMissingInvariantUid(List<T> components) {
+ List<T> missingInvariantCmpts = getComponentsWithNoInvariantUids(components);
+ for (T missingInvariantCmpt : missingInvariantCmpts) {
+ String uuid = missingInvariantCmpt.getUUID();
+ missingInvariantCmpt.setInvariantUUID(findInvariantUidOrElseFail(components, uuid));
+ }
+ }
+
+ private List<T> getComponentsWithNoInvariantUids(List<T> components) {
+ List<T> cmptsWithoutInvariant = components.stream().filter(c -> c.getInvariantUUID() == null).collect(Collectors.toList());
+ LOGGER.info(String.format("the following components are missing invariant uids: %s", StringUtils.join(cmptsWithoutInvariant.stream().map(Component::getUniqueId).collect(Collectors.toList()), ",")));
+ return cmptsWithoutInvariant;
+ }
+
+ private String findInvariantUidOrElseFail(List<T> components, String uuid) {
+ return components.stream()
+ .filter(c -> c.getUUID().equals(uuid))
+ .map(Component::getInvariantUUID)
+ .filter(c -> c != null)
+ .findAny().orElseThrow(() -> new MigrationException(String.format("cannot find invariantuid for component with uuid %s", uuid)));
+ }
+
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/relations/FulfilledCapabilitiesMigrationService.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/relations/FulfilledCapabilitiesMigrationService.java
new file mode 100644
index 0000000000..4a91290dbc
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/relations/FulfilledCapabilitiesMigrationService.java
@@ -0,0 +1,84 @@
+package org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel.relations;
+
+import fj.data.Either;
+import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
+import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
+import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
+import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
+import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
+import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.MapDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.MapListCapabiltyDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.openecomp.sdc.be.model.CapabilityDefinition;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.operations.api.ICapabilityOperation;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.model.operations.impl.ComponentInstanceOperation;
+import org.openecomp.sdc.be.resources.data.CapabilityData;
+
+import javax.annotation.Resource;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+public class FulfilledCapabilitiesMigrationService extends FulfilledCapabilityRequirementMigrationService<CapabilityDefinition, CapabilityData> {
+
+ @Resource(name = "capability-operation")
+ private ICapabilityOperation capabilityOperation;
+
+ @Resource(name = "component-instance-operation")
+ private ComponentInstanceOperation componentInstanceOperation;
+
+ @Override
+ Either<CapabilityDefinition, StorageOperationStatus> getToscaDefinition(CapabilityData data) {
+ return capabilityOperation.getCapability(data.getUniqueId());
+ }
+
+ @Override
+ void setPath(CapabilityDefinition def, List<String> path) {
+ def.setPath(path);
+ }
+
+ @Override
+ String getType(CapabilityDefinition def) {
+ return def.getType();
+ }
+
+ @Override
+ Either<List<ImmutablePair<CapabilityData, GraphEdge>>, TitanOperationStatus> getFulfilledCapReqs(ComponentInstance instance, NodeTypeEnum nodeTypeEnum) {
+ return componentInstanceOperation.getFulfilledCapabilities(instance, nodeTypeEnum);
+ }
+
+ @Override
+ ListDataDefinition convertToDefinitionListObject(List<CapabilityDefinition> capReqDefList) {
+ List<CapabilityDataDefinition> capabilityDataDefinitions = new ArrayList<>();
+ capabilityDataDefinitions.addAll(capReqDefList);
+ return new ListCapabilityDataDefinition(capabilityDataDefinitions);
+ }
+
+ @Override
+ MapDataDefinition convertToDefinitionMapObject(Map<String, ListDataDefinition> reqCapForInstance) {
+ Map<String, ListCapabilityDataDefinition> capabilitiesList = castDataDefinitionListToCapabilityList(reqCapForInstance);
+ return new MapListCapabiltyDataDefinition(capabilitiesList);
+ }
+
+ @Override
+ Either<GraphVertex, TitanOperationStatus> getAssociatedDefinitions(GraphVertex component) {
+ return titanDao.getChildVertex(component, EdgeLabelEnum.FULLFILLED_REQUIREMENTS, JsonParseFlagEnum.NoParse);
+ }
+
+ @Override
+ Either<GraphVertex, StorageOperationStatus> associateToGraph(GraphVertex graphVertex, Map<String, MapDataDefinition> defsByInstance) {
+ return topologyTemplateOperation.assosiateElementToData(graphVertex, VertexTypeEnum.FULLFILLED_CAPABILITIES, EdgeLabelEnum.FULLFILLED_CAPABILITIES, defsByInstance);
+ }
+
+ private Map<String, ListCapabilityDataDefinition> castDataDefinitionListToCapabilityList(Map<String, ListDataDefinition> reqCapForInstance) {
+ return reqCapForInstance.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, entry -> (ListCapabilityDataDefinition) entry.getValue()));
+ }
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/relations/FulfilledCapabilityRequirementMigrationService.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/relations/FulfilledCapabilityRequirementMigrationService.java
new file mode 100644
index 0000000000..aad2eb4412
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/relations/FulfilledCapabilityRequirementMigrationService.java
@@ -0,0 +1,164 @@
+package org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel.relations;
+
+import fj.Function;
+import fj.data.Either;
+import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.openecomp.sdc.asdctool.impl.migration.MigrationException;
+import org.openecomp.sdc.asdctool.impl.migration.v1707.MigrationUtils;
+import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
+import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
+import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
+import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
+import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.MapDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.jsontitan.operations.TopologyTemplateOperation;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.model.operations.api.ToscaDefinitionPathCalculator;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.Resource;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+import static org.openecomp.sdc.asdctool.impl.migration.MigrationMsg.*;
+import static org.openecomp.sdc.asdctool.impl.migration.v1707.MigrationUtils.willThrowException;
+
+public abstract class FulfilledCapabilityRequirementMigrationService<T extends ToscaDataDefinition, S extends GraphNode> {
+
+ private static Logger LOGGER = LoggerFactory.getLogger(FulfilledCapabilityRequirementMigrationService.class);
+
+ @Resource(name = "topology-template-operation")
+ TopologyTemplateOperation topologyTemplateOperation;
+
+ @Resource(name = "tosca-path-calculator")
+ private ToscaDefinitionPathCalculator toscaDefinitionPathCalculator;
+
+ @Resource(name = "titan-dao")
+ TitanDao titanDao;
+
+ public boolean associateToscaDefinitions(Component component, NodeTypeEnum componentType) {
+ try {
+ return isDefinitionsAlreadyAssociated(component) || doAssociateToscaDefinitions(component, componentType);
+ } catch (MigrationException e) {
+ LOGGER.error(e.getMessage(), e);
+ return false;
+ }
+ }
+
+ private boolean isDefinitionsAlreadyAssociated(Component component) {
+ GraphVertex componentVertex = titanDao.getVertexById(component.getUniqueId()).left().on((err) -> willThrowException(FAILED_TO_RETRIEVE_VERTEX.getMessage(component.getName(), err.name())));
+ return this.getAssociatedDefinitions(componentVertex)
+ .either(vertex -> true,
+ errorStatus -> notFoundStatusOrFail(component, errorStatus));
+
+ }
+
+ private boolean notFoundStatusOrFail(Component component, TitanOperationStatus error) {
+ if (error.equals(TitanOperationStatus.NOT_FOUND)) {
+ return false;
+ }
+ throw new MigrationException(FAILED_TO_RETRIEVE_CAP_REQ_VERTEX.getMessage(component.getName(), error.name()));
+ }
+
+ private boolean doAssociateToscaDefinitions(Component component, NodeTypeEnum componentType) {
+ try {
+ Map<String, MapDataDefinition> toscaDefByInstance = groupToscaDefinitionByInstance(component, componentType);
+ return toscaDefByInstance.isEmpty() || updateOnGraph(component, toscaDefByInstance);
+ } catch (MigrationException e) {
+ LOGGER.error(e.getMessage(), e);
+ return false;
+ }
+ }
+
+ private Map<String, MapDataDefinition> groupToscaDefinitionByInstance(Component component, NodeTypeEnum componentType) {
+ Map<String, MapDataDefinition> toscaDefByInstance = new HashMap<>();
+ for (ComponentInstance componentInstance : component.getComponentInstances()) {
+ List<ImmutablePair<S, GraphEdge>> fulfilledCapReq = getFulfilledCapReqs(componentType, componentInstance);
+ if (fulfilledCapReq.isEmpty()) {
+ continue;
+ }
+ toscaDefByInstance.put(componentInstance.getUniqueId(), getReqCapToscaDefs(fulfilledCapReq, componentInstance));
+ }
+ return toscaDefByInstance;
+ }
+
+ private MapDataDefinition getReqCapToscaDefs(List<ImmutablePair<S, GraphEdge>> capReqsData, ComponentInstance componentInstance) {
+ Map<String, List<T>> capReqDefinitions = getCapReqDefinitions(componentInstance, capReqsData);
+ return convertToMapDefinition(capReqDefinitions);
+ }
+
+ private List<ImmutablePair<S, GraphEdge>> getFulfilledCapReqs(NodeTypeEnum componentType, ComponentInstance componentInstance) {
+ return getFulfilledCapReqs(componentInstance, componentType)
+ .either(Function.identity(),
+ error -> emptyListOrFail(error, componentInstance.getName()));
+ }
+
+ private List<ImmutablePair<S, GraphEdge>> emptyListOrFail(TitanOperationStatus error, String instanceName) {
+ if (error.equals(TitanOperationStatus.NOT_FOUND)) {
+ return Collections.emptyList();
+ }
+ String errorMsg = FAILED_TO_RETRIEVE_REQ_CAP.getMessage(instanceName, error.name());
+ throw new MigrationException(errorMsg);
+ }
+
+ private Map<String, List<T>> getCapReqDefinitions(ComponentInstance componentInstance, List<ImmutablePair<S, GraphEdge>> capReqDataList) {
+ return capReqDataList.stream()
+ .map(capReqData -> convertToToscaDef(componentInstance, capReqData))
+ .collect(Collectors.groupingBy(this::getType));
+ }
+
+ private T convertToToscaDef(ComponentInstance componentInstance, ImmutablePair<S, GraphEdge> data) {
+ T def = getReqCapDataDefinition(data);
+ List<String> definitionPath = toscaDefinitionPathCalculator.calculateToscaDefinitionPath(componentInstance, data.getRight());
+ setPath(def, definitionPath);
+ return def;
+ }
+
+ private T getReqCapDataDefinition(ImmutablePair<S, GraphEdge> data) {
+ S capReqData = data.getLeft();
+ return getToscaDefinition(capReqData).left().on(err -> willThrowException(FAILED_TO_RETRIEVE_TOSCA_DEF.getMessage(capReqData.getUniqueId().toString(), err.toString())));
+ }
+
+ private boolean updateOnGraph(Component component, Map<String, MapDataDefinition> defsByInstance) {
+ GraphVertex graphVertex = getComponentGraphVertex(component);
+ Either<GraphVertex, StorageOperationStatus> associatedVertex = associateToGraph(graphVertex, defsByInstance);
+ return associatedVertex.either(vertex -> true, err -> MigrationUtils.handleError(FAILED_TO_ASSOCIATE_CAP_REQ.getMessage(component.getName(), err.name())));
+ }
+
+ private GraphVertex getComponentGraphVertex(Component component) {
+ return titanDao.getVertexById(component.getUniqueId())
+ .left().on(error -> willThrowException(FAILED_TO_RETRIEVE_VERTEX.getMessage(component.getUniqueId(), error.name())));
+ }
+
+ private MapDataDefinition convertToMapDefinition(Map<String, List<T>> toscaDefs) {
+ Map<String, ListDataDefinition> defsListByType = toscaDefs.entrySet().stream()
+ .collect(Collectors.toMap(Map.Entry::getKey, entry -> convertToDefinitionListObject(entry.getValue())));
+ return convertToDefinitionMapObject(defsListByType);
+ }
+
+ abstract Either<T, ?> getToscaDefinition(S data);
+
+ abstract void setPath(T def, List<String> path);
+
+ abstract String getType(T def);
+
+ abstract Either<List<ImmutablePair<S, GraphEdge>>, TitanOperationStatus> getFulfilledCapReqs(ComponentInstance instance, NodeTypeEnum nodeTypeEnum);
+
+ abstract ListDataDefinition convertToDefinitionListObject(List<T> capReqDefList);
+
+ abstract MapDataDefinition convertToDefinitionMapObject(Map<String, ListDataDefinition> reqCapForInstance);
+
+ abstract Either<GraphVertex, TitanOperationStatus> getAssociatedDefinitions(GraphVertex component);
+
+ abstract Either<GraphVertex, StorageOperationStatus> associateToGraph(GraphVertex graphVertex, Map<String, MapDataDefinition> defsByInstance);
+
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/relations/FulfilledRequirementsMigrationService.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/relations/FulfilledRequirementsMigrationService.java
new file mode 100644
index 0000000000..33c6b2254e
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/relations/FulfilledRequirementsMigrationService.java
@@ -0,0 +1,84 @@
+package org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel.relations;
+
+import fj.data.Either;
+import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
+import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
+import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
+import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
+import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
+import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.ListRequirementDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.MapDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.MapListRequirementDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.RequirementDefinition;
+import org.openecomp.sdc.be.model.operations.api.IComponentInstanceOperation;
+import org.openecomp.sdc.be.model.operations.api.IRequirementOperation;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.resources.data.RequirementData;
+
+import javax.annotation.Resource;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+public class FulfilledRequirementsMigrationService extends FulfilledCapabilityRequirementMigrationService<RequirementDefinition, RequirementData> {
+
+ @Resource(name = "requirement-operation")
+ IRequirementOperation requirementOperation;
+
+ @Resource(name = "component-instance-operation")
+ IComponentInstanceOperation componentInstanceOperation;
+
+ @Override
+ Either<RequirementDefinition, TitanOperationStatus> getToscaDefinition(RequirementData data) {
+ return requirementOperation.getRequirement(data.getUniqueId());
+ }
+
+ @Override
+ void setPath(RequirementDefinition def, List<String> path) {
+ def.setPath(path);
+ }
+
+ @Override
+ String getType(RequirementDefinition def) {
+ return def.getCapability();
+ }
+
+ @Override
+ Either<List<ImmutablePair<RequirementData, GraphEdge>>, TitanOperationStatus> getFulfilledCapReqs(ComponentInstance instance, NodeTypeEnum nodeTypeEnum) {
+ return componentInstanceOperation.getFulfilledRequirements(instance, nodeTypeEnum);
+ }
+
+ @Override
+ ListDataDefinition convertToDefinitionListObject(List<RequirementDefinition> capReqDefList) {
+ List<RequirementDataDefinition> requirementDataDefinitions = new ArrayList<>();
+ requirementDataDefinitions.addAll(capReqDefList);
+ return new ListRequirementDataDefinition(requirementDataDefinitions);
+ }
+
+ @Override
+ MapDataDefinition convertToDefinitionMapObject(Map<String, ListDataDefinition> reqCapForInstance) {
+ Map<String, ListRequirementDataDefinition> reqDefList = castDefinitionListToRequirementList(reqCapForInstance);
+ return new MapListRequirementDataDefinition(reqDefList);
+ }
+
+ @Override
+ Either<GraphVertex, TitanOperationStatus> getAssociatedDefinitions(GraphVertex component) {
+ return titanDao.getChildVertex(component, EdgeLabelEnum.FULLFILLED_REQUIREMENTS, JsonParseFlagEnum.NoParse);
+ }
+
+ @Override
+ Either<GraphVertex, StorageOperationStatus> associateToGraph(GraphVertex graphVertex, Map<String, MapDataDefinition> defsByInstance) {
+ return topologyTemplateOperation.assosiateElementToData(graphVertex, VertexTypeEnum.FULLFILLED_REQUIREMENTS, EdgeLabelEnum.FULLFILLED_REQUIREMENTS, defsByInstance);
+ }
+
+ private Map<String, ListRequirementDataDefinition> castDefinitionListToRequirementList(Map<String, ListDataDefinition> reqCapForInstance) {
+ return reqCapForInstance.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, entry -> (ListRequirementDataDefinition) entry.getValue()));
+ }
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/relations/RequirementsCapabilitiesMigrationService.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/relations/RequirementsCapabilitiesMigrationService.java
new file mode 100644
index 0000000000..f74e40a8fc
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/relations/RequirementsCapabilitiesMigrationService.java
@@ -0,0 +1,91 @@
+package org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel.relations;
+
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.openecomp.sdc.be.model.CapabilityDefinition;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.RequirementDefinition;
+
+import javax.annotation.Resource;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+public class RequirementsCapabilitiesMigrationService<T extends Component> {
+
+ @Resource(name = "fulfilled-capabilities-mig-service")
+ FulfilledCapabilitiesMigrationService fulfilledCapabilityUpdate;
+
+ @Resource(name = "fulfilled-requirements-mig-service")
+ FulfilledRequirementsMigrationService fulfilledRequirementUpdate;
+
+ public boolean associateFulfilledCapabilities(T component, NodeTypeEnum nodeType) {
+ return fulfilledCapabilityUpdate.associateToscaDefinitions(component, nodeType);
+ }
+
+ public boolean associateFulfilledRequirements(T component, NodeTypeEnum nodeType) {
+ return fulfilledRequirementUpdate.associateToscaDefinitions(component, nodeType);
+ }
+
+ public void overrideInstanceCapabilitiesRequirements(T element) {
+ if (element.getComponentInstances() != null) {
+ clearInstancesCapabilitiesRequirements(element);
+ setInstancesRequirementsFromComponent(element);
+ setInstancesCapabilitiesFromComponent(element);
+ }
+ }
+
+ private void clearInstancesCapabilitiesRequirements(T element) {
+ element.getComponentInstances().forEach(componentInstance -> {
+ if (componentInstance.getCapabilities() != null) {
+ componentInstance.getCapabilities().clear();
+ }
+ if (componentInstance.getRequirements() != null) {
+ componentInstance.getRequirements().clear();
+ }
+ });
+ }
+
+ private void setInstancesCapabilitiesFromComponent(T element) {
+ if (element.getCapabilities() != null) {
+ Map<String, ComponentInstance> instancesById = groupInstancesById(element);
+ element.getCapabilities().forEach((type, definitions) -> { setCapabilitiesOnInstance(instancesById, type, definitions);});
+ }
+ }
+
+ private void setInstancesRequirementsFromComponent(T element) {
+ if (element.getRequirements() != null) {
+ Map<String, ComponentInstance> instancesById = groupInstancesById(element);
+ element.getRequirements().forEach((type, requirements) -> { setRequirementsOnInstance(instancesById, type, requirements);});
+ }
+ }
+
+ private void setCapabilitiesOnInstance(Map<String, ComponentInstance> instances, String capabilityType, List<CapabilityDefinition> definitions) {
+ Map<String, List<CapabilityDefinition>> capByInstance = definitions.stream().collect(Collectors.groupingBy(CapabilityDefinition::getOwnerId));
+ capByInstance.forEach((instanceId, capabilityDefinitions) -> { setCapabilitiesOnInstanceByType(instances.get(instanceId), capabilityType, capabilityDefinitions); });
+ }
+
+ private void setRequirementsOnInstance(Map<String, ComponentInstance> instances, String requirementType, List<RequirementDefinition> requirements) {
+ Map<String, List<RequirementDefinition>> reqByInstance = requirements.stream().collect(Collectors.groupingBy(RequirementDefinition::getOwnerId));
+ reqByInstance.forEach((instanceId, reqDefinitions) -> { setRequirementsOnInstanceByType(instances.get(instanceId), requirementType, reqDefinitions);});
+ }
+
+ private void setCapabilitiesOnInstanceByType(ComponentInstance instance, String capabilityType, List<CapabilityDefinition> capabilityDefinitions) {
+ instance.getCapabilities().putIfAbsent(capabilityType, new ArrayList<>());
+ instance.getCapabilities().get(capabilityType).addAll(capabilityDefinitions);
+ }
+
+ private void setRequirementsOnInstanceByType(ComponentInstance instance, String requirementType, List<RequirementDefinition> reqDefinitions) {
+ instance.getRequirements().putIfAbsent(requirementType, new ArrayList<>());
+ instance.getRequirements().get(requirementType).addAll(reqDefinitions);
+ }
+
+ private Map<String, ComponentInstance> groupInstancesById(T element) {
+ return element.getComponentInstances()
+ .stream()
+ .collect(Collectors.toMap(ComponentInstance::getUniqueId, Function.identity()));
+ }
+
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/DataSchemaMenu.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/DataSchemaMenu.java
index e29cd7eb75..2fb3270bf3 100644
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/DataSchemaMenu.java
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/DataSchemaMenu.java
@@ -20,6 +20,7 @@
package org.openecomp.sdc.asdctool.main;
+import org.openecomp.sdc.asdctool.impl.TitanGraphInitializer;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.cassandra.schema.SdcSchemaBuilder;
import org.openecomp.sdc.common.api.ConfigurationSource;
@@ -42,10 +43,9 @@ public class DataSchemaMenu {
usageAndExit();
}
- ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(),
- appConfigDir);
+ ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir);
ConfigurationManager configurationManager = new ConfigurationManager(configurationSource);
-
+
try {
switch (operation.toLowerCase()) {
@@ -59,12 +59,13 @@ public class DataSchemaMenu {
System.exit(2);
}
case "create-titan-structures":
- log.debug("Start create titan keyspace, tables and indexes");
- if (SdcSchemaBuilder.createSchema()) {
- log.debug("create cassandra keyspace, tables and indexes successfull");
+ log.debug("Start create titan keyspace");
+ String titanCfg = 2 == args.length? configurationManager.getConfiguration().getTitanCfgFile(): args[2];
+ if (TitanGraphInitializer.createGraph(titanCfg)) {
+ log.debug("create titan keyspace successfull");
System.exit(0);
} else {
- log.debug("create cassandra keyspace, tables and indexes failed");
+ log.debug("create titan keyspace failed");
System.exit(2);
}
case "clean-cassndra":
@@ -93,5 +94,6 @@ public class DataSchemaMenu {
private static void DataSchemeUsage() {
System.out.println("Usage: create-cassandra-structures <configuration dir> ");
+ System.out.println("Usage: create-titan-structures <configuration dir> ");
}
}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/EsToCassandraDataMigrationMenu.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/EsToCassandraDataMigrationMenu.java
index 17008b31a4..b82b62b551 100644
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/EsToCassandraDataMigrationMenu.java
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/EsToCassandraDataMigrationMenu.java
@@ -22,10 +22,7 @@ package org.openecomp.sdc.asdctool.main;
import org.openecomp.sdc.asdctool.impl.DataMigration;
import org.openecomp.sdc.asdctool.impl.EsToCassandraDataMigrationConfig;
-import org.openecomp.sdc.asdctool.impl.migration.v1604.AppConfig;
-import org.openecomp.sdc.asdctool.impl.migration.v1604.ServiceMigration;
import org.openecomp.sdc.be.config.ConfigurationManager;
-import org.openecomp.sdc.be.dao.cassandra.schema.SdcSchemaBuilder;
import org.openecomp.sdc.common.api.ConfigurationSource;
import org.openecomp.sdc.common.impl.ExternalConfiguration;
import org.openecomp.sdc.common.impl.FSConfigurationSource;
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/ExportImportMenu.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/ExportImportMenu.java
index 6b6f11c5a6..36d2f66d58 100644
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/ExportImportMenu.java
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/ExportImportMenu.java
@@ -20,6 +20,7 @@
package org.openecomp.sdc.asdctool.main;
+import org.openecomp.sdc.asdctool.impl.GraphJsonValidator;
import org.openecomp.sdc.asdctool.impl.GraphMLConverter;
import org.openecomp.sdc.asdctool.impl.GraphMLDataAnalyzer;
@@ -29,6 +30,7 @@ public class ExportImportMenu {
exportUsage();
importUsage();
exportUsersUsage();
+ validateJsonUsage();
System.exit(1);
}
@@ -37,6 +39,10 @@ public class ExportImportMenu {
System.out.println("Usage: import <titan.properties> <graph file location>");
}
+ private static void validateJsonUsage() {
+ System.out.println("Usage: validate-json <export graph path>");
+ }
+
private static void exportUsage() {
System.out.println("Usage: export <titan.properties> <output directory>");
}
@@ -107,6 +113,14 @@ public class ExportImportMenu {
System.exit(2);
}
break;
+ case "validate-json":
+ String jsonFilePath = validateAndGetJsonFilePath(args);
+ GraphJsonValidator graphJsonValidator = new GraphJsonValidator();
+ if (graphJsonValidator.verifyTitanJson(jsonFilePath)) {
+ System.exit(2);
+ }
+ break;
+
case "export-as-graph-ml":
isValid = verifyParamsLength(args, 3);
if (false == isValid) {
@@ -152,6 +166,16 @@ public class ExportImportMenu {
}
+ private static String validateAndGetJsonFilePath(String[] args) {
+ boolean isValid;
+ isValid = verifyParamsLength(args, 2);
+ if (!isValid) {
+ validateJsonUsage();
+ System.exit(1);
+ }
+ return args[1];
+ }
+
private static boolean verifyParamsLength(String[] args, int i) {
if (args == null) {
if (i > 0) {
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/MigrationMenu.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/MigrationMenu.java
index d7ed4600dd..c914e3b082 100644
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/MigrationMenu.java
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/MigrationMenu.java
@@ -32,6 +32,10 @@ import org.openecomp.sdc.asdctool.impl.migration.v1604.VfcNamingAlignment;
import org.openecomp.sdc.asdctool.impl.migration.v1607.CsarMigration;
import org.openecomp.sdc.asdctool.impl.migration.v1610.TitanFixUtils;
import org.openecomp.sdc.asdctool.impl.migration.v1610.ToscaArtifactsAlignment;
+import org.openecomp.sdc.asdctool.impl.migration.v1702.Migration1702;
+import org.openecomp.sdc.asdctool.impl.migration.v1707.Migration1707;
+import org.openecomp.sdc.asdctool.impl.migration.v1707.Migration1707Config;
+import org.openecomp.sdc.asdctool.impl.migration.v1707.VfModulesPropertiesAdding;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.common.api.ConfigurationSource;
import org.openecomp.sdc.common.impl.ExternalConfiguration;
@@ -57,7 +61,11 @@ public class MigrationMenu {
POPULATE_COMPONENT_CACHE("populate-component-cache", "populateComponentCache"),
FIX_PROPERTIES("fix-properties", "titanFixUtils"),
ALIGN_TOSCA_ARTIFACTS("align-tosca-artifacts", "toscaArtifactsAlignment"),
- FIX_ICONS("fix-icons", "titanFixUtils");
+ FIX_ICONS("fix-icons", "titanFixUtils"),
+ MIGRATION_1610_1702("migrate-1610-1702", "migration1702"),
+ MIGRATION_1702_1707("migrate-1702-1707", "migration1707"),
+ VFMODULES_PROPERTIES_ADDING("vfModules-properties-adding", "vfModulesPropertiesAdding");
+ // UPDATE_DATA_TYPES("update_data_types", "updateDataTypes");
private String value, beanName;
@@ -80,48 +88,52 @@ public class MigrationMenu {
}
};
+ //arguments will be [operation] [version] [config path] [align derived - optional]
+ //example : migrate-1610-1702 1702 /home/config
public static void main(String[] args) throws Exception {
- if (args == null || args.length < 2) {
+ if (args == null || args.length < 3) {
usageAndExit();
}
MigrationOperationEnum operationEnum = MigrationOperationEnum.findByValue(args[0]);
- String appConfigDir = args[1];
+ String appConfigDir = args[2];
String dataInputFileDir = null;
- if (operationEnum == MigrationOperationEnum.ALIGN_DERIVED_FROM_1604) {
- dataInputFileDir = args[2];
+ if (operationEnum == MigrationOperationEnum.ALIGN_DERIVED_FROM_1604 ) {
+ dataInputFileDir = args[3];
}
+ log.info("Run with configuration folder {}", appConfigDir);
AnnotationConfigApplicationContext context = initContext(appConfigDir);
try {
ServiceMigration serviceMigration = (ServiceMigration) context.getBean(SERVICE_MIGARTION_BEAN);
switch (operationEnum) {
case MIGRATION_1602_1604:
- log.debug("Start Titan migration from 1602 version to 1604");
+ log.info("Start Titan migration from 1602 version to 1604");
if (serviceMigration.migrate1602to1604(appConfigDir)) {
- log.debug("Titan migration from 1602 version to 1604 was finished successfull");
+ log.info("Titan migration from 1602 version to 1604 was finished successfull");
System.exit(0);
} else {
- log.debug("Titan migration from 1602 version to 1604 was failed");
+ log.info("Titan migration from 1602 version to 1604 was failed");
System.exit(2);
}
+ break;
case MIGRATE_1604_1607:
- log.debug("Start Titan migration from 1604 version to 1607");
+ log.info("Start Titan migration from 1604 version to 1607");
if (serviceMigration.migrate1604to1607(appConfigDir)) {
- log.debug("Titan migration from 1604 version to 1607 was finished successfull");
+ log.info("Titan migration from 1604 version to 1607 was finished successfull");
System.exit(0);
} else {
- log.debug("Titan migration from 1604 version to 1607 was failed");
+ log.info("Titan migration from 1604 version to 1607 was failed");
System.exit(2);
}
break;
case ALIGN_VFC_NAMES_1604:
VfcNamingAlignment vfcNamingAlignment = (VfcNamingAlignment) context.getBean(operationEnum.getBeanName());
- log.debug("Start VFC naming alignment on 1604");
+ log.info("Start VFC naming alignment on 1604");
if (vfcNamingAlignment.alignVfcNames1604(appConfigDir)) {
- log.debug("VFC naming alignment on 1604 was finished successfull");
+ log.info("VFC naming alignment on 1604 was finished successfull");
System.exit(0);
} else {
- log.debug("VFC naming alignment on 1604 was failed");
+ log.info("VFC naming alignment on 1604 was failed");
System.exit(2);
}
break;
@@ -143,12 +155,12 @@ public class MigrationMenu {
break;
case ALIGN_DERIVED_FROM_1604:
DerivedFromAlignment derivedFromAlignment = (DerivedFromAlignment) context.getBean(operationEnum.getBeanName());
- log.debug("Start derived from alignment on 1604");
+ log.info("Start derived from alignment on 1604");
if (derivedFromAlignment.alignDerivedFrom1604(appConfigDir, dataInputFileDir)) {
- log.debug("Derived from alignment on 1604 was finished successfull");
+ log.info("Derived from alignment on 1604 was finished successfull");
System.exit(0);
} else {
- log.debug("Derived from alignment on 1604 was failed");
+ log.info("Derived from alignment on 1604 was failed");
System.exit(2);
}
break;
@@ -164,27 +176,24 @@ public class MigrationMenu {
}
break;
case CLEAN_CSAR:
- log.debug("Start remove CSAR resources");
+ log.info("Start remove CSAR resources");
CsarMigration csarMigration = (CsarMigration) context.getBean(operationEnum.getBeanName());
- // TODO Show to Michael L fixed return value
if (csarMigration.removeCsarResources()) {
- log.debug("Remove CSAR resources finished successfully");
+ log.info("Remove CSAR resources finished successfully");
System.exit(0);
} else {
- log.debug("Remove CSAR resources failed");
+ log.info("Remove CSAR resources failed");
System.exit(2);
}
break;
case POPULATE_COMPONENT_CACHE:
PopulateComponentCache populateComponentCache = (PopulateComponentCache) context.getBean(operationEnum.getBeanName());
- // TODO Show to Michael L No return value always returns 0
populateComponentCache.populateCache();
System.exit(0);
break;
case FIX_PROPERTIES:
log.debug("Start fix capability properties types");
TitanFixUtils titanFixUtils = (TitanFixUtils) context.getBean(operationEnum.getBeanName());
- // TODO Show to Michael L fixed return value
if (titanFixUtils.fixCapabiltyPropertyTypes()) {
log.debug("Fix capability properties types finished successfully");
System.exit(0);
@@ -194,34 +203,73 @@ public class MigrationMenu {
}
break;
case FIX_ICONS:
- log.debug("Start fix icons of vl and eline");
+ log.info("Start fix icons of vl and eline");
titanFixUtils = (TitanFixUtils) context.getBean(operationEnum.getBeanName());
- // TODO Show to Michael L fixed return value
if (titanFixUtils.fixIconsInNormatives()) {
- log.debug("Fix icons of vl and eline finished successfully");
+ log.info("Fix icons of vl and eline finished successfully");
System.exit(0);
} else {
- log.debug("Fix icons of vl and eline failed");
+ log.info("Fix icons of vl and eline failed");
System.exit(2);
}
break;
case ALIGN_TOSCA_ARTIFACTS:
- log.debug("Start align tosca artifacts");
+ log.info("Start align tosca artifacts");
ToscaArtifactsAlignment toscaArtifactsAlignment = (ToscaArtifactsAlignment) context.getBean(operationEnum.getBeanName());
boolean isSuccessful = toscaArtifactsAlignment.alignToscaArtifacts();
if (isSuccessful) {
- log.debug("Tosca Artifacts alignment was finished successfull");
+ log.info("Tosca Artifacts alignment was finished successfull");
System.exit(0);
} else {
- log.debug("Tosca Artifacts alignment has failed");
+ log.info("Tosca Artifacts alignment has failed");
+ System.exit(2);
+ }
+ break;
+ case MIGRATION_1610_1702:
+ log.info("Start ASDC migration from 1610 to 1702");
+ Migration1702 migration = (Migration1702) context.getBean(operationEnum.getBeanName());
+ isSuccessful = migration.migrate(appConfigDir);
+ if (isSuccessful) {
+ log.info("ASDC migration from 1610 to 1702 was finished successful");
+ System.exit(0);
+ } else{
+ log.info("ASDC migration from 1610 to 1702 has failed");
+ System.exit(2);
+ }
+
+ break;
+ case MIGRATION_1702_1707:
+// log.info("Start ASDC migration from 1702 to 1707");
+ System.exit(0);
+// Migration1707 migration1707 = (Migration1707) context.getBean(operationEnum.getBeanName());
+// isSuccessful = migration1707.migrate();
+// if (isSuccessful) {
+// log.info("SDC migration from 1702 to 1707 was finished successfully");
+// System.exit(0);
+// } else{
+// log.info("SDC migration from 1702 to 1707 has failed");
+// System.exit(2);
+// }
+ break;
+ case VFMODULES_PROPERTIES_ADDING:
+ log.info("Start adding new properties to vfModules");
+ VfModulesPropertiesAdding migrationVfModulesProperties = (VfModulesPropertiesAdding) context.getBean(operationEnum.getBeanName());
+ isSuccessful = migrationVfModulesProperties.migrate(args[1]);
+ if (isSuccessful) {
+ log.info("Adding new properties to vfModules was finished successfully");
+ System.exit(0);
+ } else{
+ log.info("Adding new properties to vfModules has failed");
System.exit(2);
}
break;
default:
usageAndExit();
}
- } catch (Throwable t) {
+ } catch (Exception t) {
+ log.info("Failed {} with exception: {}", operationEnum, t.toString());
t.printStackTrace();
+ log.debug("Error while Running MigrationMenu {}", t.getMessage(), t);
System.exit(3);
} finally {
context.close();
@@ -231,7 +279,7 @@ public class MigrationMenu {
private static AnnotationConfigApplicationContext initContext(String appConfigDir) {
ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir);
ConfigurationManager configurationManager = new ConfigurationManager(configurationSource);
- AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
+ AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class, Migration1707Config.class);
return context;
}
@@ -247,5 +295,9 @@ public class MigrationMenu {
System.out.println("Usage: align-derived-from-1604 <configuration dir> <data_input_file dir>");
System.out.println("Usage: align-groups <configuration dir>");
System.out.println("Usage: fix-properties <configuration dir>");
+ System.out.println("Usage: migrate-1610-1702 <configuration dir>");
+ System.out.println("Usage: migrate-1702-1707 <configuration dir>");
+ System.out.println("Usage: update_data_types <configuration dir> <data_types_input_file path>");
+ System.out.println("Usage: vfModules-properties-adding <group_types_input_file path> <configuration dir>");
}
}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/UpdateIsVnfMenu.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/UpdateIsVnfMenu.java
index e620510916..73b7306de4 100644
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/UpdateIsVnfMenu.java
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/UpdateIsVnfMenu.java
@@ -74,7 +74,7 @@ public class UpdateIsVnfMenu {
if (updatePropertyOnServiceAtLeastCertified == null) {
System.exit(2);
} else if (updatePropertyOnServiceAtLeastCertified.intValue() >= 0) {
- log.debug("Number of updated services is {}", updatePropertyOnServiceAtLeastCertified.intValue());
+ log.debug("Number of updated services is {}",updatePropertyOnServiceAtLeastCertified.intValue());
System.exit(0);
}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/BreadCrumbsButtonsEnum.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/servlets/EntryPoint.java
index 21d5f25013..8899aa1e5e 100644
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/BreadCrumbsButtonsEnum.java
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/servlets/EntryPoint.java
@@ -18,21 +18,27 @@
* ============LICENSE_END=========================================================
*/
-package org.openecomp.sdc.ci.tests.datatypes;
+package org.openecomp.sdc.asdctool.servlets;
-public enum BreadCrumbsButtonsEnum {
+import javax.ws.rs.GET;
+import javax.ws.rs.Path;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.MediaType;
- HOME("main-menu-button-home"), CATALOG("main-menu-button-catalog"), ON_BOARDING("main-menu-button-onboard");
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
- private String value;
- private String value2;
+@Path("/entrypoint")
+public class EntryPoint {
- public String getButton() {
- return value;
- }
+ private static Logger log = LoggerFactory.getLogger(EntryPoint.class.getName());
- private BreadCrumbsButtonsEnum(String value) {
- this.value = value;
- }
+ @GET
+ @Path("test")
+ @Produces(MediaType.TEXT_PLAIN)
+ public String test() {
+ log.info("In test");
+ return "Test" + System.currentTimeMillis();
+ }
}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/servlets/ExportImportTitanServlet.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/servlets/ExportImportTitanServlet.java
new file mode 100644
index 0000000000..0ab863aa3e
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/servlets/ExportImportTitanServlet.java
@@ -0,0 +1,187 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.asdctool.servlets;
+
+import java.io.BufferedOutputStream;
+import java.io.BufferedReader;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.FileReader;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.util.Properties;
+import java.util.Map.Entry;
+
+import javax.ws.rs.Consumes;
+import javax.ws.rs.GET;
+import javax.ws.rs.Path;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+
+import org.apache.commons.configuration.BaseConfiguration;
+import org.apache.commons.configuration.Configuration;
+import org.apache.tinkerpop.gremlin.structure.io.graphml.GraphMLWriter;
+import org.glassfish.jersey.media.multipart.FormDataParam;
+import org.openecomp.sdc.asdctool.Utils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.thinkaurelius.titan.core.TitanGraph;
+//import com.tinkerpop.blueprints.util.io.graphml.GraphMLWriter;
+
+@Path("/titan")
+public class ExportImportTitanServlet {
+
+ private static Logger log = LoggerFactory.getLogger(ExportImportTitanServlet.class.getName());
+
+ @GET
+ @Path("export")
+ @Consumes(MediaType.MULTIPART_FORM_DATA)
+ @Produces(MediaType.APPLICATION_OCTET_STREAM)
+ public Response export(@FormDataParam("titanProperties") File titanPropertiesFile,
+ @FormDataParam("metadata") String exportGraphMetadata) {
+
+ printTitanConfigFile(titanPropertiesFile);
+ printMetadata(exportGraphMetadata);
+
+ Properties titanProperties = convertFileToProperties(titanPropertiesFile);
+
+ if (titanProperties == null) {
+ Response response = Utils.buildOkResponse(400, "cannot parse titan properties file", null);
+ return response;
+ }
+
+ Configuration conf = new BaseConfiguration();
+ for (Entry<Object, Object> entry : titanProperties.entrySet()) {
+ String key = entry.getKey().toString();
+ Object value = entry.getValue();
+ conf.setProperty(key, value);
+ }
+
+ conf.setProperty("storage.machine-id-appendix", System.currentTimeMillis() % 1000);
+
+ TitanGraph openGraph = Utils.openGraph(conf);
+ if (openGraph == null) {
+ Response buildErrorResponse = Utils.buildOkResponse(500, "failed to open graph", null);
+ return buildErrorResponse;
+ }
+
+ // Open Titan Graph
+
+ Response buildOkResponse = Utils.buildOkResponse(200, "ok man", null);
+
+ return buildOkResponse;
+ }
+
+ private Properties convertFileToProperties(File titanPropertiesFile) {
+
+ Properties properties = new Properties();
+
+ FileReader fileReader = null;
+ try {
+ fileReader = new FileReader(titanPropertiesFile);
+ properties.load(fileReader);
+
+ } catch (Exception e) {
+ log.error("Failed to convert file to properties", e);
+ return null;
+ } finally {
+ if (fileReader != null) {
+ try {
+ fileReader.close();
+ } catch (IOException e) {
+ log.error("Failed to close file", e);
+ }
+ }
+ }
+
+ return properties;
+ }
+
+ private void printTitanConfigFile(File titanPropertiesFile) {
+
+ if (log.isDebugEnabled()) {
+ StringBuilder builder = new StringBuilder();
+ try (BufferedReader br = new BufferedReader(new FileReader(titanPropertiesFile))) {
+ String line;
+ while ((line = br.readLine()) != null) {
+ builder.append(line + Utils.NEW_LINE);
+ }
+
+ log.debug(builder.toString());
+
+ } catch (IOException e) {
+ log.error("Cannot print titan properties file", e);
+ }
+ }
+ }
+
+ private void printMetadata(String exportGraphMetadata) {
+
+ log.debug(exportGraphMetadata);
+
+ }
+
+ public String exportGraph(TitanGraph graph, String outputDirectory) {
+
+ String result = null;
+
+ // GraphMLWriter graphMLWriter = new GraphMLWriter(graph);
+ GraphMLWriter graphMLWriter = GraphMLWriter.build().create();
+
+ String outputFile = outputDirectory + File.separator + "exportGraph." + System.currentTimeMillis() + ".ml";
+
+ OutputStream out = null;
+ try {
+ out = new BufferedOutputStream(new ByteArrayOutputStream());
+
+ // graphMLWriter.outputGraph(out);
+
+ graphMLWriter.writeGraph(out, graph);
+
+ // graph.commit();
+ graph.tx().commit();
+
+ String exportedGraph = out.toString();
+
+ result = outputFile;
+
+ } catch (Exception e) {
+ e.printStackTrace();
+ // graph.rollback();
+ graph.tx().rollback();
+ } finally {
+ try {
+ if (out != null) {
+ out.close();
+ }
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+ return result;
+
+ }
+
+}
diff --git a/asdctool/src/main/resources/config/configuration.yaml b/asdctool/src/main/resources/config/configuration.yaml
index 294424fa9a..d376ba3c0e 100644
--- a/asdctool/src/main/resources/config/configuration.yaml
+++ b/asdctool/src/main/resources/config/configuration.yaml
@@ -8,7 +8,7 @@ identificationHeaderFields:
# catalog backend hostname
-beFqdn: sdccatalog
+beFqdn: sdccatalog.att.com
# catalog backend http port
beHttpPort: 8080
@@ -25,19 +25,36 @@ beSslPort: 8443
version: 1.0
released: 2012-11-30
-titanCfgFile: src/main/resources/config/titan.properties
+titanCfgFile: C:\Git_work\Git_UGN\d2-sdnc\asdctool\src\main\resources\config\titan.properties
+titanMigrationKeySpaceCfgFile: C:\Git_work\Git_UGN\d2-sdnc\asdctool\src\main\resources\config\titan-migration.properties
titanInMemoryGraph: false
-titanLockTimeout: 30
+titanLockTimeout: 1800
titanReconnectIntervalInSeconds: 3
titanHealthCheckReadTimeout: 1
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:
@@ -93,6 +110,9 @@ artifactTypes:
- AAI_VF_MODULE_MODEL
- AAI_VF_INSTANCE_MODEL
- OTHER
+ - SNMP_POLL
+ - SNMP_TRAP
+ - GUIDE
licenseTypes:
- User
@@ -105,24 +125,25 @@ resourceTypes: &allResourceTypes
- CP
- VL
- VF
+ - VFCMT
# 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
+# 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:
@@ -130,6 +151,11 @@ deploymentResourceInstanceArtifacts:
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:
@@ -144,6 +170,7 @@ toscaArtifacts:
type: TOSCA_CSAR
description: TOSCA definition package of the asset
+
#Informational artifacts placeHolder
excludeResourceCategory:
- Generic
@@ -160,7 +187,7 @@ informationalResourceArtifacts:
testScripts:
displayName: Test Scripts
type: OTHER
- cloudQuestionnaire:
+ CloudQuestionnaire:
displayName: Cloud Questionnaire (completed)
type: OTHER
HEATTemplateFromVendor:
@@ -169,7 +196,7 @@ informationalResourceArtifacts:
resourceSecurityTemplate:
displayName: Resource Security Template
type: OTHER
-
+
excludeServiceCategory:
informationalServiceArtifacts:
@@ -247,6 +274,16 @@ serviceDeploymentArtifacts:
YANG_XML:
acceptedTypes:
- xml
+ VNF_CATALOG:
+ acceptedTypes:
+ - xml
+ MODEL_INVENTORY_PROFILE:
+ acceptedTypes:
+ - xml
+ MODEL_QUERY_SPEC:
+ acceptedTypes:
+ - xml
+#AAI Artifacts
AAI_SERVICE_MODEL:
acceptedTypes:
- xml
@@ -264,17 +301,80 @@ resourceDeploymentArtifacts:
acceptedTypes:
- yaml
- yml
+ validForResourceTypes: *allResourceTypes
HEAT_VOL:
acceptedTypes:
- yaml
- yml
+ validForResourceTypes: *allResourceTypes
+ HEAT_NESTED:
+ acceptedTypes:
+ - yaml
+ - yml
+ validForResourceTypes: *allResourceTypes
+ HEAT_ARTIFACT:
+ acceptedTypes:
+ 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 Artifatcs
+ APPC_CONFIG:
+ acceptedTypes:
+ validForResourceTypes:
+ - VF
+ #DCAE Artifacts
+ DCAE_TOSCA:
+ acceptedTypes:
+ - yml
+ - yaml
+ validForResourceTypes:
+ - VF
+ DCAE_JSON:
+ acceptedTypes:
+ - json
+ validForResourceTypes:
+ - VF
+ DCAE_POLICY:
+ acceptedTypes:
+ - emf
+ validForResourceTypes:
+ - VF
+ DCAE_DOC:
+ acceptedTypes:
+ validForResourceTypes:
+ - VF
+ DCAE_EVENT:
+ acceptedTypes:
+ validForResourceTypes:
+ - VF
+#AAI Artifacts
AAI_VF_MODEL:
acceptedTypes:
- xml
@@ -284,24 +384,102 @@ resourceDeploymentArtifacts:
acceptedTypes:
- xml
validForResourceTypes:
- - VF
+ - VF
OTHER:
acceptedTypes:
-
+ validForResourceTypes: *allResourceTypes
+#MIB artifacts
+ SNMP_POLL:
+ acceptedTypes:
+ validForResourceTypes: *allResourceTypes
+ SNMP_TRAP:
+ acceptedTypes:
+ validForResourceTypes: *allResourceTypes
+
resourceInstanceDeploymentArtifacts:
HEAT_ENV:
acceptedTypes:
- env
+ VF_MODULES_METADATA:
+ acceptedTypes:
+ - json
+#DCAE_VF Instance Artifacts
+ 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:
+#MIB artifacts
+ 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: *allResourceTypes
+ SNMP_POLL:
+ acceptedTypes:
+ validForResourceTypes: *allResourceTypes
+ SNMP_TRAP:
+ acceptedTypes:
+ validForResourceTypes: *allResourceTypes
+ GUIDE:
+ acceptedTypes:
+ validForResourceTypes:
+ - VF
+ - VFC
+
resourceInformationalDeployedArtifacts:
requirementsToFulfillBeforeCert:
- CP:
- - tosca.capabilities.network.Bindable
-
-capabilitiesToConsumeBeforeCert:
+capabilitiesToConsumeBeforeCert:
+
unLoggedUrls:
- /sdc2/rest/healthCheck
@@ -312,6 +490,7 @@ cleanComponentsConfiguration:
- Service
artifactsIndex: resources
+
cassandraConfig:
cassandraHosts: ['localhost']
localDataCenter:
@@ -326,36 +505,40 @@ cassandraConfig:
- { name: sdcaudit, replicationStrategy: SimpleStrategy, replicationInfo: ['1']}
- { name: sdcartifact, replicationStrategy: SimpleStrategy, replicationInfo: ['1']}
- { name: sdccomponent, replicationStrategy: SimpleStrategy, replicationInfo: ['1']}
-
-
+
+
switchoverDetector:
- gBeFqdn:
- gFeFqdn:
- beVip: 1.2.3.4
- feVip: 1.2.3.4
+ gBeFqdn: AIO-BE.ecomp.idns.cip
+ gFeFqdn: AIO-FE.ecomp.idns.cip
+ beVip: 0.0.0.0
+ feVip: 0.0.0.0
beResolveAttempts: 3
feResolveAttempts: 3
enabled: false
interval: 60
changePriorityUser: ecompasdc
changePriorityPassword: ecompasdc123
- publishNetworkUrl:
+ publishNetworkUrl: "http://xxxxxx.com/crt/CipDomain.ECOMP-ASDC-DEVST/config/update_network?user=root"
publishNetworkBody: '{"note":"publish network"}'
groups:
- beSet: { changePriorityUrl: "http://localhost/",
- changePriorityBody: '{"name":"AIO-BE.ecomp.idns.cip","uri":"/crt/CipDomain.ECOMP-ASDC-DEVST/config/sites/AIO-BE.ecomp.idns.cip","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://localhost/",
- changePriorityBody: '{"comment":"AIO G-fqdn","name":"AIO-FE.ecomp.idns.cip","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.att.com"}'}
+ beSet: { changePriorityUrl: "http://xxxxxxx.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://cora.web.att.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.com","v4groups":{"failover_groups":["/crt/CipDomain.ECOMP-ASDC-DEVST/config/groups/group_mg_fe","/crt/CipDomain.ECOMP-ASDC-DEVST/config/groups/group_bs_fe"],"failover_policy":["FAILALL"]},"no_ad_redirection":false,"intended_app_proto":"DNS","uri":"/crt/CipDomain.ECOMP-ASDC-DEVST/config/sites/AIO-FE.ecomp.idns.com"}'}
-
-heatEnvArtifactHeader:
- ""
-heatEnvArtifactFooter:
- ""
-
+
+heatEnvArtifactHeader: ""
+heatEnvArtifactFooter: ""
+
+onboarding:
+ protocol: http
+ host: localhost
+ port: 8080
+ downloadCsarUri: "/onboarding-api/v1.0/vendor-software-products/packages"
+
applicationL1Cache:
datatypes:
- enabled: false
+ enabled: true
firstRunDelay: 10
pollIntervalInSec: 60
@@ -367,10 +550,25 @@ applicationL2Cache:
servicesSizeInCache: 200
productsSizeInCache: 100
queue:
- syncIntervalInSecondes: 60
- waitOnShutDownInMinutes: 30
+ syncIntervalInSecondes: 43200
+ waitOnShutDownInMinutes: 10
numberOfCacheWorkers: 4
toscaValidators:
- stringMaxLength: 1024
-disableAudit: true \ No newline at end of file
+ stringMaxLength: 65536
+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
+ \ No newline at end of file
diff --git a/asdctool/src/main/resources/config/dataTypes.yml b/asdctool/src/main/resources/config/dataTypes.yml
new file mode 100644
index 0000000000..43c7f0c844
--- /dev/null
+++ b/asdctool/src/main/resources/config/dataTypes.yml
@@ -0,0 +1,1123 @@
+tosca.datatypes.Root:
+ description: The TOSCA root Data Type all other TOSCA base Data Types derive from
+
+integer:
+ derived_from: tosca.datatypes.Root
+
+string:
+ derived_from: tosca.datatypes.Root
+
+boolean:
+ derived_from: tosca.datatypes.Root
+
+float:
+ derived_from: tosca.datatypes.Root
+
+list:
+ derived_from: tosca.datatypes.Root
+
+map:
+ derived_from: tosca.datatypes.Root
+
+tosca.datatypes.Credential:
+ derived_from: tosca.datatypes.Root
+ properties:
+ protocol:
+ type: string
+ required: false
+ token_type:
+ type: string
+ default: password
+ token:
+ type: string
+ keys:
+ type: map
+ required: false
+ entry_schema:
+ type: string
+ user:
+ type: string
+ required: false
+
+tosca.datatypes.TimeInterval:
+ derived_from: tosca.datatypes.Root
+ properties:
+ start_time:
+ type: timestamp
+ required: true
+ end_time:
+ type: timestamp
+ required: true
+
+tosca.datatypes.network.NetworkInfo:
+ derived_from: tosca.datatypes.Root
+ properties:
+ network_name:
+ type: string
+ network_id:
+ type: string
+ addresses:
+ type: list
+ entry_schema:
+ type: string
+
+tosca.datatypes.network.PortInfo:
+ derived_from: tosca.datatypes.Root
+ properties:
+ port_name:
+ type: string
+ port_id:
+ type: string
+ network_id:
+ type: string
+ mac_address:
+ type: string
+ addresses:
+ type: list
+ entry_schema:
+ type: string
+
+tosca.datatypes.network.PortDef:
+ derived_from: integer
+ constraints:
+ - in_range: [ 1, 65535 ]
+
+tosca.datatypes.network.PortSpec:
+ derived_from: tosca.datatypes.Root
+ properties:
+ protocol:
+ type: string
+ required: true
+ default: tcp
+ constraints:
+ - valid_values: [ udp, tcp, igmp ]
+ target:
+ type: tosca.datatypes.network.PortDef
+ target_range:
+ type: range
+ constraints:
+ - in_range: [ 1, 65535 ]
+ source:
+ type: tosca.datatypes.network.PortDef
+ source_range:
+ type: range
+ constraints:
+ - in_range: [ 1, 65535 ]
+
+###################new Data Types Onboarding Integration##########################
+
+org.openecomp.datatypes.heat.network.AddressPair:
+ derived_from: tosca.datatypes.Root
+ description: MAC/IP address pairs
+ properties:
+ mac_address:
+ type: string
+ description: MAC address
+ required: false
+ status: SUPPORTED
+ ip_address:
+ type: string
+ description: IP address
+ required: false
+ status: SUPPORTED
+org.openecomp.datatypes.heat.network.subnet.HostRoute:
+ derived_from: tosca.datatypes.Root
+ description: Host route info for the subnet
+ properties:
+ destination:
+ type: string
+ description: The destination for static route
+ required: false
+ status: SUPPORTED
+ nexthop:
+ type: string
+ description: The next hop for the destination
+ required: false
+ status: SUPPORTED
+
+org.openecomp.datatypes.heat.network.AllocationPool:
+ derived_from: tosca.datatypes.Root
+ description: The start and end addresses for the allocation pool
+ properties:
+ start:
+ type: string
+ description: Start address for the allocation pool
+ required: false
+ status: SUPPORTED
+ end:
+ type: string
+ description: End address for the allocation pool
+ required: false
+ status: SUPPORTED
+
+org.openecomp.datatypes.heat.network.neutron.Subnet:
+ derived_from: tosca.datatypes.Root
+ description: A subnet represents an IP address block that can be used for assigning IP addresses to virtual instances
+ properties:
+ tenant_id:
+ type: string
+ description: The ID of the tenant who owns the network
+ required: false
+ status: SUPPORTED
+ enable_dhcp:
+ type: boolean
+ description: Set to true if DHCP is enabled and false if DHCP is disabled
+ required: false
+ default: true
+ status: SUPPORTED
+ ipv6_address_mode:
+ type: string
+ description: IPv6 address mode
+ required: false
+ status: SUPPORTED
+ constraints:
+ - valid_values:
+ - dhcpv6-stateful
+ - dhcpv6-stateless
+ - slaac
+ ipv6_ra_mode:
+ type: string
+ description: IPv6 RA (Router Advertisement) mode
+ required: false
+ status: SUPPORTED
+ constraints:
+ - valid_values:
+ - dhcpv6-stateful
+ - dhcpv6-stateless
+ - slaac
+ value_specs:
+ type: map
+ description: Extra parameters to include in the request
+ required: false
+ default: {
+ }
+ status: SUPPORTED
+ entry_schema:
+ type: string
+ allocation_pools:
+ type: list
+ description: The start and end addresses for the allocation pools
+ required: false
+ status: SUPPORTED
+ entry_schema:
+ type: org.openecomp.datatypes.heat.network.AllocationPool
+ subnetpool:
+ type: string
+ description: The name or ID of the subnet pool
+ required: false
+ status: SUPPORTED
+ dns_nameservers:
+ type: list
+ description: A specified set of DNS name servers to be used
+ required: false
+ default: [
+ ]
+ status: SUPPORTED
+ entry_schema:
+ type: string
+ host_routes:
+ type: list
+ description: The gateway IP address
+ required: false
+ status: SUPPORTED
+ entry_schema:
+ type: org.openecomp.datatypes.heat.network.subnet.HostRoute
+ ip_version:
+ type: integer
+ description: The gateway IP address
+ required: false
+ default: 4
+ status: SUPPORTED
+ constraints:
+ - valid_values:
+ - '4'
+ - '6'
+ name:
+ type: string
+ description: The name of the subnet
+ required: false
+ status: SUPPORTED
+ prefixlen:
+ type: integer
+ description: Prefix length for subnet allocation from subnet pool
+ required: false
+ status: SUPPORTED
+ constraints:
+ - greater_or_equal: 0
+ cidr:
+ type: string
+ description: The CIDR
+ required: false
+ status: SUPPORTED
+ gateway_ip:
+ type: string
+ description: The gateway IP address
+ required: false
+ status: SUPPORTED
+
+org.openecomp.datatypes.heat.novaServer.network.PortExtraProperties:
+ derived_from: tosca.datatypes.Root
+ description: Nova server network expand properties for port
+ properties:
+ port_security_enabled:
+ type: boolean
+ description: Flag to enable/disable port security on the port
+ required: false
+ status: SUPPORTED
+ mac_address:
+ type: string
+ description: MAC address to give to this port
+ required: false
+ status: SUPPORTED
+ admin_state_up:
+ type: boolean
+ description: The administrative state of this port
+ required: false
+ default: true
+ status: SUPPORTED
+ qos_policy:
+ type: string
+ description: The name or ID of QoS policy to attach to this port
+ required: false
+ status: SUPPORTED
+ allowed_address_pairs:
+ type: list
+ description: Additional MAC/IP address pairs allowed to pass through the port
+ required: false
+ status: SUPPORTED
+ entry_schema:
+ type: org.openecomp.datatypes.heat.network.AddressPair
+ binding:vnic_type:
+ type: string
+ description: The vnic type to be bound on the neutron port
+ required: false
+ status: SUPPORTED
+ constraints:
+ - valid_values:
+ - macvtap
+ - direct
+ - normal
+ value_specs:
+ type: map
+ description: Extra parameters to include in the request
+ required: false
+ default: {
+ }
+ status: SUPPORTED
+ entry_schema:
+ type: string
+org.openecomp.datatypes.heat.novaServer.network.AddressInfo:
+ derived_from: tosca.datatypes.network.NetworkInfo
+ description: Network addresses with corresponding port id
+ properties:
+ port_id:
+ type: string
+ description: Port id
+ required: false
+ status: SUPPORTED
+org.openecomp.datatypes.heat.neutron.port.FixedIps:
+ derived_from: tosca.datatypes.Root
+ description: subnet/ip_address
+ properties:
+ subnet:
+ type: string
+ description: Subnet in which to allocate the IP address for this port
+ required: false
+ status: SUPPORTED
+ ip_address:
+ type: string
+ description: IP address desired in the subnet for this port
+ required: false
+ status: SUPPORTED
+org.openecomp.datatypes.heat.FileInfo:
+ derived_from: tosca.datatypes.Root
+ description: Heat File Info
+ properties:
+ file:
+ type: string
+ description: The required URI string (relative or absolute) which can be used to locate the file
+ required: true
+ status: SUPPORTED
+ file_type:
+ type: string
+ description: The type of the file
+ required: true
+ status: SUPPORTED
+ constraints:
+ - valid_values:
+ - base
+ - env
+ - volume
+ - network
+org.openecomp.datatypes.heat.contrail.network.rule.PortPairs:
+ derived_from: tosca.datatypes.Root
+ description: source and destination port pairs
+ properties:
+ start_port:
+ type: string
+ description: Start port
+ required: false
+ status: SUPPORTED
+ end_port:
+ type: string
+ description: End port
+ required: false
+ status: SUPPORTED
+org.openecomp.datatypes.heat.contrail.network.rule.Rule:
+ derived_from: tosca.datatypes.Root
+ description: policy rule
+ properties:
+ src_ports:
+ type: list
+ description: Source ports
+ required: false
+ status: SUPPORTED
+ entry_schema:
+ type: org.openecomp.datatypes.heat.contrail.network.rule.PortPairs
+ protocol:
+ type: string
+ description: Protocol
+ required: false
+ status: SUPPORTED
+ dst_addresses:
+ type: list
+ description: Destination addresses
+ required: false
+ status: SUPPORTED
+ entry_schema:
+ type: org.openecomp.datatypes.heat.contrail.network.rule.VirtualNetwork
+ apply_service:
+ type: string
+ description: Service to apply
+ required: false
+ status: SUPPORTED
+ dst_ports:
+ type: list
+ description: Destination ports
+ required: false
+ status: SUPPORTED
+ entry_schema:
+ type: org.openecomp.datatypes.heat.contrail.network.rule.PortPairs
+ src_addresses:
+ type: list
+ description: Source addresses
+ required: false
+ status: SUPPORTED
+ entry_schema:
+ type: org.openecomp.datatypes.heat.contrail.network.rule.VirtualNetwork
+ direction:
+ type: string
+ description: Direction
+ required: false
+ status: SUPPORTED
+org.openecomp.datatypes.heat.contrail.network.rule.RuleList:
+ derived_from: tosca.datatypes.Root
+ description: list of policy rules
+ properties:
+ policy_rule:
+ type: list
+ description: Contrail network rule
+ required: false
+ status: SUPPORTED
+ entry_schema:
+ type: org.openecomp.datatypes.heat.contrail.network.rule.Rule
+org.openecomp.datatypes.heat.contrail.network.rule.VirtualNetwork:
+ derived_from: tosca.datatypes.Root
+ description: source and destination addresses
+ properties:
+ virtual_network:
+ type: string
+ description: Virtual network
+ required: false
+ status: SUPPORTED
+
+org.openecomp.datatypes.heat.network.neutron.SecurityRules.Rule:
+ derived_from: tosca.datatypes.Root
+ description: Rules Pairs
+ properties:
+ remote_group_id:
+ type: string
+ description: The remote group ID to be associated with this security group rule
+ required: false
+ status: SUPPORTED
+ protocol:
+ type: string
+ description: The protocol that is matched by the security group rule
+ required: false
+ status: SUPPORTED
+ constraints:
+ - valid_values:
+ - tcp
+ - udp
+ - icmp
+ ethertype:
+ type: string
+ description: Ethertype of the traffic
+ required: false
+ default: IPv4
+ status: SUPPORTED
+ constraints:
+ - valid_values:
+ - IPv4
+ - IPv6
+ port_range_max:
+ type: integer
+ description: 'The maximum port number in the range that is matched by the
+ security group rule. '
+ required: false
+ status: SUPPORTED
+ constraints:
+ - in_range:
+ - 0
+ - 65535
+ remote_ip_prefix:
+ type: string
+ description: The remote IP prefix (CIDR) to be associated with this security group rule
+ required: false
+ status: SUPPORTED
+ remote_mode:
+ type: string
+ description: Whether to specify a remote group or a remote IP prefix
+ required: false
+ default: remote_ip_prefix
+ status: SUPPORTED
+ constraints:
+ - valid_values:
+ - remote_ip_prefix
+ - remote_group_id
+ direction:
+ type: string
+ description: The direction in which the security group rule is applied
+ required: false
+ default: ingress
+ status: SUPPORTED
+ constraints:
+ - valid_values:
+ - egress
+ - ingress
+ port_range_min:
+ type: integer
+ description: The minimum port number in the range that is matched by the security group rule.
+ required: false
+ status: SUPPORTED
+ constraints:
+ - in_range:
+ - 0
+ - 65535
+org.openecomp.datatypes.heat.substitution.SubstitutionFiltering:
+ derived_from: tosca.datatypes.Root
+ description: Substitution Filter
+ properties:
+ substitute_service_template:
+ type: string
+ description: Substitute Service Template
+ required: true
+ status: SUPPORTED
+ index_value:
+ type: integer
+ description: Index value of the substitution service template runtime instance
+ required: false
+ default: 0
+ status: SUPPORTED
+ constraints:
+ - greater_or_equal: 0
+ count:
+ type: string
+ description: Count
+ required: false
+ default: 1
+ status: SUPPORTED
+ scaling_enabled:
+ type: boolean
+ description: Indicates whether service scaling is enabled
+ required: false
+ default: true
+ status: SUPPORTED
+ mandatory:
+ type: boolean
+ description: Mandatory
+ required: false
+ default: true
+ status: SUPPORTED
+org.openecomp.datatypes.heat.contrailV2.virtual.network.rule.RefDataSequence:
+ derived_from: tosca.datatypes.Root
+ description: network policy refs data sequence
+ properties:
+ network_policy_refs_data_sequence_major:
+ type: integer
+ description: Network Policy ref data sequence Major
+ required: false
+ status: SUPPORTED
+ network_policy_refs_data_sequence_minor:
+ type: integer
+ description: Network Policy ref data sequence Minor
+ required: false
+ status: SUPPORTED
+org.openecomp.datatypes.heat.contrailV2.virtual.network.rule.RefData:
+ derived_from: tosca.datatypes.Root
+ description: network policy refs data
+ properties:
+ network_policy_refs_data_sequence:
+ type: org.openecomp.datatypes.heat.contrailV2.virtual.network.rule.RefDataSequence
+ description: Network Policy ref data sequence
+ required: false
+ status: SUPPORTED
+org.openecomp.datatypes.heat.contrailV2.virtual.network.rule.ref.data.IpamSubnet:
+ derived_from: tosca.datatypes.Root
+ description: Network Ipam Ref Data Subnet
+ properties:
+ network_ipam_refs_data_ipam_subnets_subnet_ip_prefix_len:
+ type: string
+ description: Network ipam refs data ipam subnets ip prefix len
+ required: false
+ status: SUPPORTED
+ network_ipam_refs_data_ipam_subnets_subnet_ip_prefix:
+ type: string
+ description: Network ipam refs data ipam subnets ip prefix
+ required: false
+ status: SUPPORTED
+org.openecomp.datatypes.heat.contrailV2.virtual.network.rule.ref.data.IpamSubnetList:
+ derived_from: tosca.datatypes.Root
+ description: Network Ipam Ref Data Subnet List
+ properties:
+ network_ipam_refs_data_ipam_subnets_subnet:
+ type: org.openecomp.datatypes.heat.contrailV2.virtual.network.rule.ref.data.IpamSubnet
+ description: Network ipam refs data ipam subnets
+ required: false
+ status: SUPPORTED
+ network_ipam_refs_data_ipam_subnets_addr_from_start:
+ type: string
+ description: Network ipam refs data ipam subnets addr from start
+ required: false
+ status: SUPPORTED
+org.openecomp.datatypes.heat.contrailV2.virtual.network.rule.IpamRefData:
+ derived_from: tosca.datatypes.Root
+ description: Network Ipam Ref Data
+ properties:
+ network_ipam_refs_data_ipam_subnets:
+ type: list
+ description: Network ipam refs data ipam subnets
+ required: false
+ status: SUPPORTED
+ entry_schema:
+ type: org.openecomp.datatypes.heat.contrailV2.virtual.network.rule.ref.data.IpamSubnetList
+org.openecomp.datatypes.heat.contrailV2.network.rule.SrcVirtualNetwork:
+ derived_from: tosca.datatypes.Root
+ description: source addresses
+ properties:
+ network_policy_entries_policy_rule_src_addresses_virtual_network:
+ type: string
+ description: Source addresses Virtual network
+ required: false
+ status: SUPPORTED
+org.openecomp.datatypes.heat.contrailV2.network.rule.DstVirtualNetwork:
+ derived_from: tosca.datatypes.Root
+ description: destination addresses
+ properties:
+ network_policy_entries_policy_rule_dst_addresses_virtual_network:
+ type: string
+ description: Destination addresses Virtual network
+ required: false
+ status: SUPPORTED
+org.openecomp.datatypes.heat.contrailV2.network.rule.DstPortPairs:
+ derived_from: tosca.datatypes.Root
+ description: destination port pairs
+ properties:
+ network_policy_entries_policy_rule_dst_ports_start_port:
+ type: string
+ description: Start port
+ required: false
+ status: SUPPORTED
+ network_policy_entries_policy_rule_dst_ports_end_port:
+ type: string
+ description: End port
+ required: false
+ status: SUPPORTED
+org.openecomp.datatypes.heat.contrailV2.network.rule.SrcPortPairs:
+ derived_from: tosca.datatypes.Root
+ description: source port pairs
+ properties:
+ network_policy_entries_policy_rule_src_ports_start_port:
+ type: string
+ description: Start port
+ required: false
+ status: SUPPORTED
+ network_policy_entries_policy_rule_src_ports_end_port:
+ type: string
+ description: End port
+ required: false
+ status: SUPPORTED
+org.openecomp.datatypes.heat.contrailV2.network.rule.ActionList:
+ derived_from: tosca.datatypes.Root
+ description: Action List
+ properties:
+ network_policy_entries_policy_rule_action_list_simple_action:
+ type: string
+ description: Simple Action
+ required: false
+ status: SUPPORTED
+ network_policy_entries_policy_rule_action_list_apply_service:
+ type: list
+ description: Apply Service
+ required: false
+ status: SUPPORTED
+ entry_schema:
+ type: string
+org.openecomp.datatypes.heat.contrailV2.network.rule.ActionList:
+ derived_from: tosca.datatypes.Root
+ description: Action List
+ properties:
+ network_policy_entries_policy_rule_action_list_simple_action:
+ type: string
+ description: Simple Action
+ required: false
+ status: SUPPORTED
+ network_policy_entries_policy_rule_action_list_apply_service:
+ type: list
+ description: Apply Service
+ required: false
+ status: SUPPORTED
+ entry_schema:
+ type: string
+org.openecomp.datatypes.heat.contrailV2.network.rule.Rule:
+ derived_from: tosca.datatypes.Root
+ description: policy rule
+ properties:
+ network_policy_entries_policy_rule_dst_addresses:
+ type: list
+ description: Destination addresses
+ required: false
+ status: SUPPORTED
+ entry_schema:
+ type: org.openecomp.datatypes.heat.contrailV2.network.rule.DstVirtualNetwork
+ network_policy_entries_policy_rule_dst_ports:
+ type: list
+ description: Destination ports
+ required: false
+ status: SUPPORTED
+ entry_schema:
+ type: org.openecomp.datatypes.heat.contrailV2.network.rule.DstPortPairs
+ network_policy_entries_policy_rule_protocol:
+ type: string
+ description: Protocol
+ required: false
+ status: SUPPORTED
+ network_policy_entries_policy_rule_src_addresses:
+ type: list
+ description: Source addresses
+ required: false
+ status: SUPPORTED
+ entry_schema:
+ type: org.openecomp.datatypes.heat.contrailV2.network.rule.SrcVirtualNetwork
+ network_policy_entries_policy_rule_direction:
+ type: string
+ description: Direction
+ required: false
+ status: SUPPORTED
+ network_policy_entries_policy_rule_src_ports:
+ type: list
+ description: Source ports
+ required: false
+ status: SUPPORTED
+ entry_schema:
+ type: org.openecomp.datatypes.heat.contrailV2.network.rule.SrcPortPairs
+ network_policy_entries_policy_rule_action_list:
+ type: org.openecomp.datatypes.heat.contrailV2.network.rule.ActionList
+ description: Action list
+ required: false
+ status: SUPPORTED
+org.openecomp.datatypes.heat.contrailV2.network.rule.RuleList:
+ derived_from: tosca.datatypes.Root
+ description: list of policy rules
+ properties:
+ network_policy_entries_policy_rule:
+ type: list
+ description: Contrail network rule
+ required: false
+ status: SUPPORTED
+ entry_schema:
+ type: org.openecomp.datatypes.heat.contrailV2.network.rule.Rule
+org.openecomp.datatypes.heat.network.contrail.port.StaticRoute:
+ derived_from: tosca.datatypes.Root
+ description: static route
+ properties:
+ prefix:
+ type: string
+ description: Route prefix
+ required: false
+ status: SUPPORTED
+ next_hop:
+ type: string
+ description: Next hop
+ required: false
+ status: SUPPORTED
+ next_hop_type:
+ type: string
+ description: Next hop type
+ required: false
+ status: SUPPORTED
+org.openecomp.datatypes.heat.network.contrail.AddressPair:
+ derived_from: tosca.datatypes.Root
+ description: Address Pair
+ properties:
+ address_mode:
+ type: string
+ description: Address mode active-active or active-standy
+ required: false
+ status: SUPPORTED
+ constraints:
+ - valid_values:
+ - active-active
+ - active-standby
+ prefix:
+ type: string
+ description: IP address prefix
+ required: false
+ status: SUPPORTED
+ mac_address:
+ type: string
+ description: Mac address
+ required: false
+ status: SUPPORTED
+org.openecomp.datatypes.heat.network.contrail.InterfaceData:
+ derived_from: tosca.datatypes.Root
+ description: Interface Data
+ properties:
+ static_routes:
+ type: list
+ description: An ordered list of static routes to be added to this interface
+ required: false
+ status: SUPPORTED
+ entry_schema:
+ type: org.openecomp.datatypes.heat.network.contrail.port.StaticRoute
+ virtual_network:
+ type: string
+ description: Virtual Network for this interface
+ required: true
+ status: SUPPORTED
+ allowed_address_pairs:
+ type: list
+ description: List of allowed address pair for this interface
+ required: false
+ status: SUPPORTED
+ entry_schema:
+ type: org.openecomp.datatypes.heat.network.contrail.AddressPair
+ ip_address:
+ type: string
+ description: IP for this interface
+ required: false
+ status: SUPPORTED
+org.openecomp.datatypes.heat.contrailV2.virtual.machine.interface.Properties:
+ derived_from: tosca.datatypes.Root
+ description: Virtual Machine Interface Properties.
+ properties:
+ virtual_machine_interface_properties_service_interface_type:
+ type: string
+ description: Service Interface Type.
+ required: false
+ status: SUPPORTED
+org.openecomp.datatypes.Root:
+ derived_from: tosca.datatypes.Root
+ description: >
+ The AT&T root Data Type all other Data Types derive from
+ properties:
+ supplemental_data:
+ type: map
+ entry_schema:
+ description: >
+ A placeholder for missing properties that would be included in future ecomp model versions.
+ fromat <key>:<value>
+ type: string
+
+org.openecomp.datatypes.network.SubnetAssignments:
+ derived_from: org.openecomp.datatypes.Root
+ properties:
+ ip_network_address_plan:
+ type: string
+ required: false
+ description: Reference to EIPAM, VLAN or other address plan ID used to assign subnets to this network
+ dhcp_enabled:
+ type: boolean
+ required: false
+ description: \"true\" indicates the network has 1 or more policies
+ ip_version:
+ type: integer
+ constraints:
+ - valid_values: [4,6]
+ required: true
+ description: The IP version of the subnet
+ cidr_mask:
+ type: integer
+ required: true
+ description: The default subnet CIDR mask
+ min_subnets_count:
+ type: integer
+ default: 1
+ required: true
+ description: Quantity of subnets that must be initially assigned
+org.openecomp.datatypes.network.IPv4SubnetAssignments:
+ derived_from: org.openecomp.datatypes.network.SubnetAssignments
+ properties:
+ use_ipv4:
+ type: boolean
+ required: true
+ description: Indicates IPv4 subnet assignments
+
+org.openecomp.datatypes.network.IPv6SubnetAssignments:
+ derived_from: org.openecomp.datatypes.network.SubnetAssignments
+ properties:
+ use_ipv6:
+ type: boolean
+ required: true
+ description: Indicates IPv6 subnet assignments
+
+org.openecomp.datatypes.network.NetworkAssignments:
+ derived_from: org.openecomp.datatypes.Root
+ properties:
+ ecomp_generated_network_assignment:
+ type: boolean
+ required: true
+ default: false
+ description: >
+ \"true\" indicates that the network assignments will be auto-generated by ECOMP
+ \"false\" indicates operator-supplied Network assignments file upload is required (e.g. VID will present prompt to operator to upload operator-supplied Network assignments file).
+ is_shared_network:
+ type: boolean
+ required: true
+ description: \"true\" means this network is shared by multiple Openstack tenants
+ is_external_network:
+ type: boolean
+ required: true
+ default: false
+ description: >
+ \"true\" means this Contrail external network
+ ipv4_subnet_default_assignment:
+ type: org.openecomp.datatypes.network.IPv4SubnetAssignments
+ required: true
+ description: IPv4 defualt subnet assignments
+ ipv6_subnet_default_assignment:
+ type: org.openecomp.datatypes.network.IPv6SubnetAssignments
+ required: true
+ description: IPv6 defualt subnet assignments
+
+org.openecomp.datatypes.network.ProviderNetwork:
+ derived_from: org.openecomp.datatypes.Root
+ properties:
+ is_provider_network:
+ type: boolean
+ required: true
+ description: \"true\" indicates that this a Neutron provider type of network
+ physical_network_name:
+ type: string
+ required: false
+ constraints:
+ - valid_values: ["Physnet41", "Physnet42", "Physnet43", "Physnet44", "Physnet21", "Physnet22"]
+ description: >
+ Identifies the NUMA processor cluster to which this physical network interface belongs.
+ NUMA instance correlates to the first digit of the Physical Network Name suffix (e.g. \"01\" = NUMA 0, \"11\" = NUMA 1)
+ numa:
+ type: string
+ required: false
+ constraints:
+ - valid_values: ["NUMA 0", "NUMA 1"]
+ description: >
+ PNIC instance within the NUMA processor cluster
+ PNIC Instance correlates to the second digit of the Physical Network Name suffix (e.g. "01" = PNIC 1, "02" = "PNIC 2)
+ pnic_instance:
+ type: integer
+ required: false
+ description: PNIC instance within the NUMA processor cluster
+
+org.openecomp.datatypes.network.NetworkFlows:
+ derived_from: org.openecomp.datatypes.Root
+ properties:
+ is_network_policy:
+ type: boolean
+ required: false
+ default: false
+ description: \"true\" indicates the network has 1 or more policies
+ network_policy:
+ type: string
+ required: false
+ description: "Identifies the specific Cloud network policy that must be applied to this network (source: from Policy Manager)."
+ is_bound_to_vpn:
+ type: boolean
+ required: false
+ default: false
+ description: \"true\" indicates the network has 1 or more vpn bindings
+ vpn_binding:
+ type: string
+ required: false
+ description: "Identifies the specific VPN Binding entry in A&AI that must be applied when creating this network (source: A&AI)"
+
+org.openecomp.datatypes.network.VlanRequirements:
+ derived_from: org.openecomp.datatypes.Root
+ properties:
+ vlan_range_plan:
+ type: string
+ required: true
+ description: reference to a vlan range plan
+ vlan_type:
+ type: string
+ required: true
+ constraints:
+ - valid_values: ["c-tag", "s-tag"]
+ description: identifies the vlan type (e.g., c-tag)
+ vlan_count:
+ type: integer
+ required: true
+ description: identifies the number of vlan tags to assign to the CP from the plan
+
+org.openecomp.datatypes.network.IpRequirements:
+ derived_from: org.openecomp.datatypes.Root
+ properties:
+ ip_version:
+ type: integer
+ constraints:
+ - valid_values: [4,6]
+ required: true
+ description:
+ ip_count:
+ type: integer
+ required: true
+ description: identifies the number of ip address to assign to the CP from the plan
+ floating_ip_count:
+ type: integer
+ required: false
+ subnet_role:
+ type: string
+ required: false
+ assingment_method:
+ type: string
+ constraints:
+ - valid_values: ["fixed", "dhcp"]
+ required: true
+ description:
+
+org.openecomp.datatypes.network.MacAssignments:
+ derived_from: org.openecomp.datatypes.Root
+ properties:
+ mac_range_plan:
+ type: string
+ required: true
+ description: reference to a MAC address range plan
+ mac_count:
+ type: integer
+ required: true
+ description: identifies the number of MAC addresses to assign to the CP from the plan
+
+org.openecomp.datatypes.EcompHoming:
+ derived_from: org.openecomp.datatypes.Root
+ properties:
+ ecomp_selected_instance_node_target:
+ type: boolean
+ required: true
+ default: false
+ description: >
+ \"true\" indicates that the target deployment node for this instance will be auto-selected by ECOMP
+ \"false\" indicates operator-supplied instance target deployment node required (e.g. VID will present a prompt to operator and collect the
+ operator-selected target node for the deployment of this Network instance).
+ homing_policy:
+ type: string
+ required: false
+ description: Referenc to a service level homing policy that ECOMP will use for instance deployment target node
+ instance_node_target:
+ type: string
+ required: false
+ description: Instance target deployment node
+
+org.openecomp.datatypes.EcompNaming:
+ derived_from: org.openecomp.datatypes.Root
+ properties:
+ ecomp_generated_naming:
+ type: boolean
+ required: true
+ default: true
+ description: >
+ \"true\" indicates that the name for the instance will be auto-generated by ECOMP.
+ \"false\" indicates operator-supplied name required (e.g. VID will present prompt to operator and collect the operator-supplied instance name).
+ naming_policy:
+ type: string
+ required: false
+ description: Referenc to naming policy that ECOMP will use when the name is auto-generated
+
+org.openecomp.datatypes.network.MacRequirements:
+ derived_from: org.openecomp.datatypes.Root
+ properties:
+ mac_range_plan:
+ type: string
+ required: true
+ description: reference to a MAC address range plan
+ mac_count:
+ type: integer
+ required: true
+ description: identifies the number of MAC addresses to assign to the CP from the plan
+
+org.openecomp.datatypes.heat.contrailV2.virtual.machine.subInterface.AddressPairIp:
+ derived_from: tosca.datatypes.Root
+ description: Virtual Machine Sub Interface Address Pair IP.
+ properties:
+ ip_prefix:
+ type: string
+ description: IP Prefix.
+ required: false
+ status: SUPPORTED
+ ip_prefix_len:
+ type: integer
+ description: IP Prefix Len.
+ required: false
+ status: SUPPORTED
+
+org.openecomp.datatypes.heat.contrailV2.virtual.machine.subInterface.MacAddress:
+ derived_from: tosca.datatypes.Root
+ description: Virtual Machine Sub Interface Mac Address.
+ properties:
+ mac_address:
+ type: list
+ description: Mac Addresses List.
+ required: false
+ status: SUPPORTED
+ entry_schema:
+ type: string
+
+org.openecomp.datatypes.heat.contrailV2.virtual.machine.subInterface.Properties:
+ derived_from: tosca.datatypes.Root
+ description: Virtual Machine Sub Interface VLAN Properties.
+ properties:
+ sub_interface_vlan_tag:
+ type: string
+ description: Sub Interface VLAN Tag.
+ required: false
+ status: SUPPORTED
+
+org.openecomp.datatypes.heat.contrailV2.virtual.machine.subInterface.AddressPair:
+ derived_from: tosca.datatypes.Root
+ description: Virtual Machine Sub Interface Address Pair.
+ properties:
+ address_mode:
+ type: string
+ description: Address Mode.
+ required: false
+ status: SUPPORTED
+ ip:
+ type: org.openecomp.datatypes.heat.contrailV2.virtual.machine.subInterface.AddressPairIp
+ description: IP.
+ required: false
+ status: SUPPORTED
+ mac:
+ type: string
+ description: Mac.
+ required: false
+ status: SUPPORTED
+
+org.openecomp.datatypes.heat.contrailV2.virtual.machine.subInterface.AddressPairs:
+ derived_from: tosca.datatypes.Root
+ description: Virtual Machine Sub Interface Address Pairs.
+ properties:
+ allowed_address_pair:
+ type: list
+ description: Addresses pair List.
+ required: false
+ status: SUPPORTED
+ entry_schema:
+ type: org.openecomp.datatypes.heat.contrailV2.virtual.machine.subInterface.AddressPair \ No newline at end of file
diff --git a/asdctool/src/main/resources/config/error-configuration.yaml b/asdctool/src/main/resources/config/error-configuration.yaml
index 5e5009e54f..d33876a7df 100644
--- a/asdctool/src/main/resources/config/error-configuration.yaml
+++ b/asdctool/src/main/resources/config/error-configuration.yaml
@@ -94,17 +94,17 @@ errors:
messageId: "SVC4007"
}
#---------SVC4008-----------------------------
-# %1 - Users's userId
+# %1 - Users's USER_ID
INVALID_USER_ID: {
code: 400,
- message: "Error: Invalid userId '%1'.",
+ message: "Error: Invalid USER_ID '%1'.",
messageId: "SVC4008"
}
#---------SVC4049------------------------------
# %1 - service/resource
COMPONENT_MISSING_CONTACT: {
code: 400,
- message: "Error: Invalid Content. Missing %1 contact id.",
+ message: "Error: Invalid Content. Missing %1 Contact Id.",
messageId: "SVC4049"
}
#---------SVC4050-----------------------------
@@ -245,9 +245,9 @@ errors:
#---------SVC4069------------------------------
# %1 - Service/Resource/Product
- COMPONENT_INVALID_CONTACT_ID: {
+ COMPONENT_INVALID_CONTACT: {
code: 400,
- message: "Error: Invalid Content. %1 contact id should be in format 'mnnnnnn' or 'aannna' or 'aannnn', where m=m ,a=a-zA-Z and n=0-9",
+ message: "Error: Invalid Content. %1 Contact Id should be in format 'mnnnnnn' or 'aannna' or 'aannnn', where m=m ,a=a-zA-Z and n=0-9",
messageId: "SVC4069"
}
#---------SVC4070------------------------------
@@ -511,7 +511,7 @@ errors:
#-----------SVC4130---------------------------
INVALID_PROJECT_CODE: {
code: 400,
- message: "Error: Invalid Content. PROJECT_CODE number must be numeric from 5 up to 10 digits.",
+ message: "Error: Invalid Content. PROJECT_CODE must be from 3 up to 50 characters.",
messageId: "SVC4130"
}
#-----------SVC4131---------------------------
@@ -1060,7 +1060,7 @@ errors:
messageId: "SVC4567"
}
#---------SVC4567------------------------------
-# %1 - "User Name and UserId"
+# %1 - "User Name and USER_ID"
# %2 -"checked-out"/"in-certification"
CANNOT_DELETE_USER_WITH_ACTIVE_ELEMENTS: {
code: 409,
@@ -1068,7 +1068,7 @@ errors:
messageId: "SVC4567"
}
#---------SVC4568------------------------------
-# %1 - "User Name and UserId"
+# %1 - "User Name and USER_ID"
# %2 -"checked-out"/"in-certification"
CANNOT_UPDATE_USER_WITH_ACTIVE_ELEMENTS: {
code: 409,
@@ -1144,7 +1144,7 @@ errors:
messageId: "SVC4580"
}
#---------SVC4581------------------------------
-# %1 - userId
+# %1 - USER_ID
INVALID_PRODUCT_CONTACT: {
code: 400,
message: "Error: Invalid content. User '%1' cannot be set as Product Contact.",
diff --git a/asdctool/src/main/resources/config/groupTypes.yml b/asdctool/src/main/resources/config/groupTypes.yml
new file mode 100644
index 0000000000..c72dc88c53
--- /dev/null
+++ b/asdctool/src/main/resources/config/groupTypes.yml
@@ -0,0 +1,72 @@
+org.openecomp.groups.heat.HeatStack:
+ derived_from: tosca.groups.Root
+ description: Grouped all heat resources which are in the same heat stack
+ properties:
+ heat_file:
+ type: string
+ description: Heat file which associate to this group/heat stack
+ required: true
+ status: SUPPORTED
+ description:
+ type: string
+ description: group description
+ required: true
+ status: SUPPORTED
+org.openecomp.groups.VfModule:
+ derived_from: tosca.groups.Root
+ description: Grouped all heat resources which are in the same VF Module
+ properties:
+ isBase:
+ type: boolean
+ description: Whether this module should be deployed before other modules
+ required: true
+ default: false
+ status: SUPPORTED
+ vf_module_label:
+ type: string
+ required: true
+ description: >
+ Alternate textual key used to reference this VF-Module model.
+ Must be unique within the VNF model
+ vf_module_description:
+ type: string
+ required: true
+ description: >
+ Description of the VF-modules contents and purpose
+ (e.g. "Front-End" or "Database Cluster")
+ min_vf_module_instances:
+ type: integer
+ required: true
+ description: The minimum instances of this VF-Module
+ max_vf_module_instances:
+ type: integer
+ required: false
+ description: The maximum instances of this VF-Module
+ initial_count:
+ type: integer
+ required: false
+ description: >
+ The initial count of instances of the VF-Module. The value must be in the
+ range between min_vfmodule_instances and max_vfmodule_instances.
+ If no value provided the initial count is the min_vfmodule_instances.
+ vf_module_type:
+ type: string
+ required: true
+ constraint:
+ - valid_values: ["Base", "Expansion"]
+ volume_group:
+ type: boolean
+ required: true
+ default: false
+ description: >
+ "true" indicates that this VF Module model requires attachment to a Volume
+ Group.
+ VID operator must select the Volume Group instance to attach to a VF-Module
+ at deployment time.
+
+tosca.groups.Root:
+ description: The TOSCA Group Type all other TOSCA Group Types derive from
+ interfaces:
+ Standard:
+ type: tosca.interfaces.node.lifecycle.Standard
+
diff --git a/asdctool/src/main/resources/config/logback.xml b/asdctool/src/main/resources/config/logback.xml
index 298587bd1d..87795ae163 100644
--- a/asdctool/src/main/resources/config/logback.xml
+++ b/asdctool/src/main/resources/config/logback.xml
@@ -36,9 +36,9 @@
</encoder>
</appender>
- <root level="DEBUG">
+ <root level="INFO">
<appender-ref ref="DEBUG_ROLLING" />
</root>
- <logger name="org.openecomp.sdc" level="DEBUG" />
+ <logger name="org.openecomp.sdc" level="INFO" />
</configuration> \ No newline at end of file
diff --git a/asdctool/src/main/resources/config/titan-migration.properties b/asdctool/src/main/resources/config/titan-migration.properties
new file mode 100644
index 0000000000..e982c2d085
--- /dev/null
+++ b/asdctool/src/main/resources/config/titan-migration.properties
@@ -0,0 +1,4 @@
+storage.backend=cassandra
+storage.hostname=localhost
+storage.port=9160
+storage.cassandra.keyspace=sdctitan
diff --git a/asdctool/src/main/resources/config/titan.properties b/asdctool/src/main/resources/config/titan.properties
index bfb0ebc542..e9daff7c7c 100644
--- a/asdctool/src/main/resources/config/titan.properties
+++ b/asdctool/src/main/resources/config/titan.properties
@@ -1,3 +1,4 @@
storage.backend=cassandra
storage.hostname=localhost
storage.port=9160
+storage.cassandra.keyspace=titan \ No newline at end of file
diff --git a/asdctool/src/main/resources/scripts/dataMigration.sh b/asdctool/src/main/resources/scripts/dataMigration.sh
index b05c6dc355..e1f4f24a30 100644
--- a/asdctool/src/main/resources/scripts/dataMigration.sh
+++ b/asdctool/src/main/resources/scripts/dataMigration.sh
@@ -5,7 +5,7 @@
##############################
CURRENT_DIR=`pwd`
-BASEDIR=$(dirname $0)
+BASEDIR=$(dirname $1)
if [ ${BASEDIR:0:1} = "/" ]
then
@@ -18,8 +18,31 @@ source ${FULL_PATH}/baseOperation.sh
mainClass="org.openecomp.sdc.asdctool.main.MigrationMenu"
-command="java $JVM_LOG_FILE -cp $JARS $mainClass migrate-1602-1604 $@"
-echo $command
+case $1 in
+ 1604)
+ command="java $JVM_LOG_FILE -cp $JARS $mainClass migrate-1602-1604 $@"
+ echo $command
+ ;;
+ 1607)
+ command="sh ./dataMigration1607.sh $@"
+ echo $command
+ ;;
+ 1610)
+ command="sh ./dataMigration1610.sh $@"
+ echo $command
+ ;;
+ 1702)
+ command="sh ./dataMigration1702.sh $@"
+ echo $command
+ ;;
+ 1707)
+ command="sh ./dataMigration1707.sh $@"
+ echo $command
+ ;;
+ *)
+ echo "No migration for this version $1"
+ ;;
+esac
$command
result=$?
diff --git a/asdctool/src/main/resources/scripts/dataMigration1702.sh b/asdctool/src/main/resources/scripts/dataMigration1702.sh
new file mode 100644
index 0000000000..f2bf56e4ef
--- /dev/null
+++ b/asdctool/src/main/resources/scripts/dataMigration1702.sh
@@ -0,0 +1,35 @@
+#!/bin/bash
+
+##############################
+# Data Migration 1702
+##############################
+
+CURRENT_DIR=`pwd`
+BASEDIR=$(dirname $0)
+
+if [ ${BASEDIR:0:1} = "/" ]
+then
+ FULL_PATH=$BASEDIR
+else
+ FULL_PATH=$CURRENT_DIR/$BASEDIR
+fi
+
+source ${FULL_PATH}/baseOperation.sh
+
+mainClass="org.openecomp.sdc.asdctool.main.MigrationMenu"
+
+command="java $JVM_LOG_FILE -cp $JARS $mainClass migrate-1610-1702 $@"
+echo $command
+
+$command
+result=$?
+
+
+
+echo "***********************************"
+echo "***** $result *********************"
+echo "***********************************"
+
+exit $result
+
+
diff --git a/asdctool/src/main/resources/scripts/dataMigration1707.sh b/asdctool/src/main/resources/scripts/dataMigration1707.sh
new file mode 100644
index 0000000000..e67de2a540
--- /dev/null
+++ b/asdctool/src/main/resources/scripts/dataMigration1707.sh
@@ -0,0 +1,35 @@
+#!/bin/bash
+
+##############################
+# Data Migration 1707
+##############################
+
+CURRENT_DIR=`pwd`
+BASEDIR=$(dirname $0)
+
+if [ ${BASEDIR:0:1} = "/" ]
+then
+ FULL_PATH=$BASEDIR
+else
+ FULL_PATH=$CURRENT_DIR/$BASEDIR
+fi
+
+source ${FULL_PATH}/baseOperation.sh
+
+mainClass="org.openecomp.sdc.asdctool.main.MigrationMenu"
+
+command="java $JVM_LOG_FILE -cp $JARS $mainClass migrate-1702-1707 $@"
+echo $command
+
+$command
+result=$?
+
+
+
+echo "***********************************"
+echo "***** $result *********************"
+echo "***********************************"
+
+exit $result
+
+
diff --git a/asdctool/src/main/resources/scripts/sdcSchemaFileImport.sh b/asdctool/src/main/resources/scripts/sdcSchemaFileImport.sh
new file mode 100644
index 0000000000..4002e388da
--- /dev/null
+++ b/asdctool/src/main/resources/scripts/sdcSchemaFileImport.sh
@@ -0,0 +1,33 @@
+#!/bin/bash
+
+##############################
+# Sdc Schema File Import #
+##############################
+
+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.SdcSchemaFileImport"
+
+command="java $JVM_LOG_FILE -cp $JARS $mainClass $@"
+echo $command
+
+$command
+result=$?
+
+echo "***********************************"
+echo "***** $result *********************"
+echo "***********************************"
+
+exit $result
+
+
diff --git a/asdctool/src/main/resources/scripts/titanSchemaCreation.sh b/asdctool/src/main/resources/scripts/titanSchemaCreation.sh
new file mode 100644
index 0000000000..8a2488b3e2
--- /dev/null
+++ b/asdctool/src/main/resources/scripts/titanSchemaCreation.sh
@@ -0,0 +1,33 @@
+#!/bin/bash
+
+##############################
+# Titan Schema Creation
+##############################
+
+CURRENT_DIR=`pwd`
+BASEDIR=$(dirname $0)
+
+if [ ${BASEDIR:0:1} = "/" ]
+then
+ FULL_PATH=$BASEDIR
+else
+ FULL_PATH=$CURRENT_DIR/$BASEDIR
+fi
+
+source ${FULL_PATH}/baseOperation.sh
+
+mainClass="org.openecomp.sdc.asdctool.main.DataSchemaMenu"
+
+command="java $JVM_LOG_FILE -cp $JARS $mainClass create-titan-structures $@"
+echo $command
+
+$command
+result=$?
+
+echo "***********************************"
+echo "***** $result *********************"
+echo "***********************************"
+
+exit $result
+
+
diff --git a/asdctool/src/main/resources/scripts/vfModulePropertiesAdding.sh b/asdctool/src/main/resources/scripts/vfModulePropertiesAdding.sh
new file mode 100644
index 0000000000..1ead2484db
--- /dev/null
+++ b/asdctool/src/main/resources/scripts/vfModulePropertiesAdding.sh
@@ -0,0 +1,33 @@
+#!/bin/bash
+
+##############################
+# Data Migration: Adding new properties to vfModules
+##############################
+
+CURRENT_DIR=`pwd`
+BASEDIR=$(dirname $0)
+
+if [ ${BASEDIR:0:1} = "/" ]
+then
+ FULL_PATH=$BASEDIR
+else
+ FULL_PATH=$CURRENT_DIR/$BASEDIR
+fi
+
+source ${FULL_PATH}/baseOperation.sh
+
+mainClass="org.openecomp.sdc.asdctool.main.MigrationMenu"
+
+command="java $JVM_LOG_FILE -cp $JARS $mainClass vfModules-properties-adding $@"
+echo $command
+
+$command
+result=$?
+
+echo "***********************************"
+echo "***** $result *********************"
+echo "***********************************"
+
+exit $result
+
+
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/GeneralCanvasItemsEnum.java b/asdctool/src/test/java/org/openecomp/sdc/asdctool/AppTest.java
index 0e8f9cbea1..ae23b73d7d 100644
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/GeneralCanvasItemsEnum.java
+++ b/asdctool/src/test/java/org/openecomp/sdc/asdctool/AppTest.java
@@ -18,22 +18,37 @@
* ============LICENSE_END=========================================================
*/
-package org.openecomp.sdc.ci.tests.datatypes;
+package org.openecomp.sdc.asdctool;
-public enum GeneralCanvasItemsEnum {
- CANVAS("canvas"), CANVAS_RIGHT_PANEL("w-sdc-designer-sidebar-head"), DELETE_INSTANCE_BUTTON(
- "e-sdc-small-icon-delete")
+import junit.framework.Test;
+import junit.framework.TestCase;
+import junit.framework.TestSuite;
- ;
-
- private String value;
-
- public String getValue() {
- return value;
+/**
+ * Unit test for simple App.
+ */
+public class AppTest extends TestCase {
+ /**
+ * Create the test case
+ *
+ * @param testName
+ * name of the test case
+ */
+ public AppTest(String testName) {
+ super(testName);
}
- private GeneralCanvasItemsEnum(String value) {
- this.value = value;
+ /**
+ * @return the suite of tests being tested
+ */
+ public static Test suite() {
+ return new TestSuite(AppTest.class);
}
+ /**
+ * Rigourous Test :-)
+ */
+ public void testApp() {
+ assertTrue(true);
+ }
}
diff --git a/asdctool/tarball.xml b/asdctool/tarball.xml
index 62deb75e10..7dde4d6f84 100644
--- a/asdctool/tarball.xml
+++ b/asdctool/tarball.xml
@@ -1,26 +1,26 @@
<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
-xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
- <id>bin</id>
- <formats>
- <format>tar</format>
- </formats>
- <files>
- <file>
- <source>${project.build.directory}/${project.artifactId}-${project.version}-jar-with-dependencies.jar</source>
- <outputDirectory>./</outputDirectory>
- <destName>${project.artifactId}-${project.version}-jar-with-dependencies.jar</destName>
- </file>
- </files>
-
- <fileSets>
- <fileSet>
- <directory>src/main/resources/scripts</directory>
- <outputDirectory>scripts</outputDirectory>
- </fileSet>
- <fileSet>
- <directory>src/main/resources/config</directory>
- <outputDirectory>config</outputDirectory>
- </fileSet>
- </fileSets>
-</assembly>
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
+ <id>bin</id>
+ <formats>
+ <format>tar</format>
+ </formats>
+ <files>
+ <file>
+ <source>${project.build.directory}/${project.artifactId}-${project.version}-jar-with-dependencies.jar</source>
+ <outputDirectory>./</outputDirectory>
+ <destName>${project.artifactId}-${project.version}-jar-with-dependencies.jar</destName>
+ </file>
+ </files>
+
+ <fileSets>
+ <fileSet>
+ <directory>src/main/resources/scripts</directory>
+ <outputDirectory>scripts</outputDirectory>
+ </fileSet>
+ <fileSet>
+ <directory>src/main/resources/config</directory>
+ <outputDirectory>config</outputDirectory>
+ </fileSet>
+ </fileSets>
+</assembly> \ No newline at end of file
diff --git a/catalog-be/.pydevproject b/catalog-be/.pydevproject
deleted file mode 100644
index 7ff1370cd2..0000000000
--- a/catalog-be/.pydevproject
+++ /dev/null
@@ -1,5 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" standalone="no"?>
-<?eclipse-pydev version="1.0"?><pydev_project>
-<pydev_property name="org.python.pydev.PYTHON_PROJECT_VERSION">python 2.7</pydev_property>
-<pydev_property name="org.python.pydev.PYTHON_PROJECT_INTERPRETER">Default</pydev_property>
-</pydev_project>
diff --git a/catalog-be/pom.xml b/catalog-be/pom.xml
index db7a992179..17f01caa88 100644
--- a/catalog-be/pom.xml
+++ b/catalog-be/pom.xml
@@ -12,96 +12,61 @@
<version>1.1.0-SNAPSHOT</version>
</parent>
-
<properties>
<swagger-ui-version>2.1.0-M2</swagger-ui-version>
</properties>
-
-
- <dependencyManagement>
- <dependencies>
-
- <!-- JSON and YAML Parsing -->
- <dependency>
- <groupId>com.fasterxml.jackson.dataformat</groupId>
- <artifactId>jackson-dataformat-yaml</artifactId>
- <version>${jackson.version}</version>
- </dependency>
-
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-databind</artifactId>
- <version>${jackson.version}</version>
- </dependency>
-
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-core</artifactId>
- <version>${jackson.version}</version>
- </dependency>
-
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-annotations</artifactId>
- <version>${jackson.annotations.version}</version>
- </dependency>
-
- <dependency>
- <groupId>com.sun.jersey.contribs</groupId>
- <artifactId>jersey-multipart</artifactId>
- <version>2.14</version>
- </dependency>
- </dependencies>
- </dependencyManagement>
-
-
-
-
<dependencies>
+ <!--JSON and YAML Parsing-->
+ <dependency>
+ <groupId>com.fasterxml.jackson.dataformat</groupId>
+ <artifactId>jackson-dataformat-yaml</artifactId>
+ <version>${jackson.version}</version>
+ <scope>compile</scope>
+ </dependency>
<dependency>
- <groupId>org.testng</groupId>
- <artifactId>testng</artifactId>
- <version>6.9.10</version>
- <scope>test</scope>
+ <groupId>com.fasterxml.jackson.core</groupId>
+ <artifactId>jackson-databind</artifactId>
+ <version>${jackson.version}</version>
+ <scope>compile</scope>
</dependency>
<dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-context-support</artifactId>
- <version>${spring.version}</version>
- <scope>provided</scope>
+ <groupId>com.fasterxml.jackson.core</groupId>
+ <artifactId>jackson-core</artifactId>
+ <version>${jackson.version}</version>
+ <scope>compile</scope>
</dependency>
<dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-messaging</artifactId>
- <version>${spring.version}</version>
- <scope>provided</scope>
+ <groupId>com.fasterxml.jackson.core</groupId>
+ <artifactId>jackson-annotations</artifactId>
+ <version>${jackson.annotations.version}</version>
+ <scope>compile</scope>
</dependency>
<dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-aspects</artifactId>
- <version>${spring.version}</version>
- <scope>provided</scope>
+ <groupId>org.glassfish.jersey.media</groupId>
+ <artifactId>jersey-media-multipart</artifactId>
+ <version>${jersey-bom.version}</version>
+ <scope>compile</scope>
</dependency>
<dependency>
<groupId>org.openecomp.sdc</groupId>
<artifactId>security-utils</artifactId>
- <version>${security-utils.version}</version>
+ <version>${project.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.tinkerpop.blueprints</groupId>
<artifactId>blueprints-sail-graph</artifactId>
- <version>2.6.0</version>
+ <version>2.5.0</version>
<optional>true</optional>
<exclusions>
<exclusion>
@@ -126,37 +91,33 @@
<version>1.5.1-M2</version>
</dependency>
- <dependency>
- <groupId>org.glassfish.jersey.containers</groupId>
- <artifactId>jersey-container-servlet-core</artifactId>
- </dependency>
<!-- Swagger Dependencies End -->
<dependency>
<groupId>org.openecomp.sdc</groupId>
<artifactId>common-app-api</artifactId>
- <version>${common-app-api.version}</version>
+ <version>${project.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.openecomp.sdc.be</groupId>
<artifactId>common-be</artifactId>
- <version>${common-be.version}</version>
+ <version>${project.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.openecomp.sdc.be</groupId>
<artifactId>catalog-dao</artifactId>
- <version>${catalog-dao.version}</version>
+ <version>${project.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.openecomp.sdc.be</groupId>
<artifactId>catalog-model</artifactId>
- <version>${catalog-model.version}</version>
+ <version>${project.version}</version>
<scope>compile</scope>
</dependency>
@@ -164,21 +125,21 @@
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
- <version>1.7.10</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>
@@ -186,66 +147,67 @@
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
- <version>1.14</version>
+ <version>${snakeyaml.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>
<!-- Gson -->
-
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
- <version>2.3.1</version>
+ <version>${gson.version}</version>
<scope>compile</scope>
</dependency>
- <!-- Json -->
-
-
-
-
<!-- jersey -->
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
+ <version>${jersey-bom.version}</version>
<scope>compile</scope>
</dependency>
+ <dependency>
+ <groupId>org.glassfish.jersey.containers</groupId>
+ <artifactId>jersey-container-servlet-core</artifactId>
+ <version>${jersey-bom.version}</version>
+ <scope>compile</scope>
+ </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>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
- <version>1.2.1-SNAPSHOT</version>
+ <version>${commons-logging}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
- <version>2.0-SNAPSHOT</version>
+ <version>${commons-codec}</version>
<scope>compile</scope>
</dependency>
<!-- http client END -->
@@ -253,19 +215,17 @@
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
+ <version>${servlet-api.version}</version>
<scope>provided</scope>
</dependency>
-
<dependency>
<groupId>org.eclipse.jgit</groupId>
<artifactId>org.eclipse.jgit</artifactId>
<version>3.4.1.201406201815-r</version>
</dependency>
-
<!-- spring - used by A4C -->
-
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
@@ -321,7 +281,6 @@
<version>${groovy.version}</version>
<scope>compile</scope>
</dependency>
-
<dependency>
<groupId>org.codehaus.janino</groupId>
@@ -333,11 +292,10 @@
<dependency>
<groupId>org.codehaus.janino</groupId>
<artifactId>commons-compiler</artifactId>
- <version>3.0.6</version>
+ <version>${janino.version}</version>
<scope>compile</scope>
</dependency>
-
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
@@ -366,9 +324,8 @@
<dependency>
<groupId>com.thinkaurelius.titan</groupId>
<artifactId>titan-cassandra</artifactId>
- <!--<artifactId>asdc-titan-cassandra</artifactId -->
+ <!--<artifactId>asdc-titan-cassandra</artifactId>-->
<version>${titan.version}</version>
- <!--<version>1.0.0-snapshot</version -->
<scope>compile</scope>
<exclusions>
<exclusion>
@@ -393,6 +350,7 @@
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
+ <version>${json-simple.version}</version>
<scope>compile</scope>
</dependency>
@@ -400,10 +358,10 @@
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
+ <version>${elastic-search.version}</version>
<scope>compile</scope>
</dependency>
-
<dependency>
<groupId>org.elasticsearch.plugin</groupId>
<artifactId>shield</artifactId>
@@ -414,6 +372,7 @@
<dependency>
<groupId>org.functionaljava</groupId>
<artifactId>functionaljava</artifactId>
+ <version>${functionaljava.version}</version>
<scope>compile</scope>
</dependency>
@@ -421,6 +380,7 @@
<dependency>
<groupId>com.jcabi</groupId>
<artifactId>jcabi-aspects</artifactId>
+ <version>${jcabi.version}</version>
<scope>compile</scope>
</dependency>
@@ -505,30 +465,47 @@
</exclusions>
</dependency>
- <!-- Artifact Generator -->
+ <!--Artifact Generator-->
<dependency>
- <groupId>org.openecomp.sdc.sdc_common</groupId>
+ <groupId>org.openecomp.sdc.common</groupId>
<artifactId>openecomp-sdc-artifact-generator-api</artifactId>
- <version>${artefact-gen-api.version}</version>
+ <version>${artifact-generator-api.version}</version>
<scope>compile</scope>
+ <exclusions>
+ <exclusion>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<dependency>
- <groupId>org.openecomp.sdc.sdc_common</groupId>
+ <groupId>org.openecomp.sdc.common</groupId>
<artifactId>openecomp-sdc-artifact-generator-core</artifactId>
- <version>${artefact-gen-core.version}</version>
+ <version>${artifact-generator-core.version}</version>
<scope>compile</scope>
+ <exclusions>
+ <exclusion>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<dependency>
- <groupId>org.openecomp.sdc.sdc_common</groupId>
+ <groupId>org.openecomp.sdc.common</groupId>
<artifactId>openecomp-common-lib</artifactId>
<version>${dox-common-lib.version}</version>
<type>pom</type>
+ <exclusions>
+ <exclusion>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
-
- <!-- Jetty Proxy -->
+ <!--Jetty Proxy-->
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-proxy</artifactId>
@@ -536,12 +513,17 @@
<scope>compile</scope>
</dependency>
-
-
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlets</artifactId>
- <version>${jetty.servlets.version}</version>
+ <version>${jetty.version}</version>
+ <scope>compile</scope>
+ </dependency>
+ <!-- System metrics -->
+ <dependency>
+ <groupId>org.fusesource</groupId>
+ <artifactId>sigar</artifactId>
+ <version>${sigar.version}</version>
<scope>compile</scope>
</dependency>
@@ -549,6 +531,7 @@
<dependency>
<groupId>org.glassfish.jersey.test-framework.providers</groupId>
<artifactId>jersey-test-framework-provider-bundle</artifactId>
+ <version>${jersey-bom.version}</version>
<type>pom</type>
<scope>test</scope>
</dependency>
@@ -556,26 +539,29 @@
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlet</artifactId>
+ <version>${jetty.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-webapp</artifactId>
+ <version>${jetty.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
- <version>4.12</version>
+ <version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
- <version>1.10.19</version>
+ <version>${mockito.version}</version>
+ <!--<version>1.10.19</version>-->
<scope>test</scope>
</dependency>
@@ -594,23 +580,12 @@
</dependency>
</dependencies>
-
-
<build>
<finalName>${project.artifactId}-${project.version}</finalName>
-
<plugins>
- <plugin>
- <artifactId>maven-surefire-plugin</artifactId>
- <configuration>
- <systemPropertyVariables>
- <logback.configurationFile>src/test/resources/logback-test.xml</logback.configurationFile>
- </systemPropertyVariables>
- </configuration>
- </plugin>
-
+
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
@@ -619,180 +594,222 @@
<packagingExcludes>WEB-INF\lib\slf4j-log4j*.jar,
WEB-INF/classes/elasticsearch.yml,
WEB-INF/classes/portal.properties</packagingExcludes>
- <archive>
- <manifestEntries>
- <SDC-Version>${parent.version}</SDC-Version>
- </manifestEntries>
- <manifest>
- <!-- <addClasspath>true</addClasspath -->
- <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
- <addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
- </manifest>
- </archive>
-
- <webResources>
- <resource>
- <directory>src/main/resources</directory>
- <!-- <directory>target/swagger-ui-2.1.0-M2/dist</directory -->
- <directory>src/main/resources/swagger</directory>
- </resource>
- </webResources>
- <attachClasses>true</attachClasses>
- </configuration>
- </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>
- <executions>
- <execution>
- <goals>
- <goal>ajc</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
-
-
-
- <!-- Swagger Plugins Start -->
- <plugin>
- <groupId>com.googlecode.maven-download-plugin</groupId>
- <artifactId>download-maven-plugin</artifactId>
- <version>1.2.1</version>
- <executions>
- <execution>
- <id>swagger-ui</id>
- <goals>
- <goal>wget</goal>
- </goals>
- <configuration>
- <url>https://github.com/swagger-api/swagger-ui/archive/v${swagger-ui-version}.tar.gz</url>
- <unpack>true</unpack>
- <outputDirectory>${project.build.directory}</outputDirectory>
- </configuration>
- </execution>
- </executions>
- </plugin>
+ <archive>
+ <manifestEntries>
+ <SDC-Version>${full.release.version}</SDC-Version>
+ </manifestEntries>
+ <manifest>
+ <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
+ <addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
+ </manifest>
+ </archive>
+
+ <webResources>
+ <resource>
+ <directory>src/main/resources</directory>
+ <directory>src/main/resources/swagger</directory>
+ </resource>
+ </webResources>
+ <attachClasses>true</attachClasses>
+ </configuration>
+ </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>
+ <executions>
+ <execution>
+ <goals>
+ <goal>ajc</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
- <plugin>
- <artifactId>maven-resources-plugin</artifactId>
- <version>2.6</version>
- <executions>
-
- <execution>
- <id>copy-resources</id>
- <phase>process-resources</phase>
- <goals>
- <goal>copy-resources</goal>
- </goals>
- <configuration>
- <outputDirectory>target/${project.artifactId}-${project.version}</outputDirectory>
- <resources>
- <resource>
- <directory>${project.build.directory}/swagger-ui-${swagger-ui-version}/dist</directory>
- <filtering>true</filtering>
- <excludes>
- <exclude>index.html</exclude>
- </excludes>
- </resource>
- </resources>
- </configuration>
- </execution>
-
- <execution>
- <id>copy-normatives-backend</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>
-
- </executions>
- </plugin>
+ <!-- Swagger Plugins Start -->
+ <plugin>
+ <groupId>com.googlecode.maven-download-plugin</groupId>
+ <artifactId>download-maven-plugin</artifactId>
+ <version>1.2.1</version>
+ <executions>
+ <execution>
+ <id>swagger-ui</id>
+ <goals>
+ <goal>wget</goal>
+ </goals>
+ <configuration>
+ <url>https://github.com/swagger-api/swagger-ui/archive/v${swagger-ui-version}.tar.gz</url>
+ <unpack>true</unpack>
+ <outputDirectory>${project.build.directory}</outputDirectory>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <artifactId>maven-clean-plugin</artifactId>
+ <version>2.6.1</version>
+ <executions>
+ <execution>
+ <id>clean.sdc.zip.chef.os.folder</id>
+ <phase>initialize</phase>
+ <goals>
+ <goal>clean</goal>
+ </goals>
+ <configuration>
+
+ <filesets>
+ <fileset>
+ <directory>${project.parent.basedir}/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/files/default/sdc-*.zip</directory>
+ <includes>
+ <include>sdc-*.zip</include>
+ </includes>
+ <followSymlinks>false</followSymlinks>
+ </fileset>
+ </filesets>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <artifactId>maven-resources-plugin</artifactId>
+ <version>2.6</version>
+ <executions>
+ <execution>
+ <id>copy-resources</id>
+ <phase>process-resources</phase>
+ <goals>
+ <goal>copy-resources</goal>
+ </goals>
+ <configuration>
+ <outputDirectory>target/${project.artifactId}-${project.version}</outputDirectory>
+ <resources>
+ <resource>
+ <directory>${project.build.directory}/swagger-ui-${swagger-ui-version}/dist</directory>
+ <filtering>true</filtering>
+ <excludes>
+ <exclude>index.html</exclude>
+ </excludes>
+ </resource>
+ </resources>
+ </configuration>
+ </execution>
+
+ <execution>
+ <id>copy-normatives</id>
+ <phase>install</phase>
+ <goals>
+ <goal>copy-resources</goal>
+ </goals>
+ <configuration>
+ <outputDirectory>${project.parent.basedir}/sdc-os-chef/sdc-normatives/chef-repo/cookbooks/sdc-normatives/files/default</outputDirectory>
+ <resources>
+ <resource>
+ <directory>./target</directory>
+ <includes>
+ <include>normatives.tar.gz</include>
+ </includes>
+ </resource>
+ </resources>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-assembly-plugin</artifactId>
- <version>2.6</version>
- <executions>
- <execution>
- <id>normatives</id>
- <phase>package</phase>
- <goals>
- <goal>single</goal>
- </goals>
- <configuration>
- <finalName>normatives</finalName>
- <appendAssemblyId>false</appendAssemblyId>
- <descriptor>${project.basedir}/normatives.xml</descriptor>
- </configuration>
- </execution>
- </executions>
- </plugin>
+ <plugin>
+ <groupId>com.coderplus.maven.plugins</groupId>
+ <artifactId>copy-rename-maven-plugin</artifactId>
+ <version>1.0</version>
+ <executions>
+ <execution>
+ <id>copy-file</id>
+ <phase>install</phase>
+ <goals>
+ <goal>copy</goal>
+ </goals>
+ <configuration>
+ <sourceFile>${project.parent.basedir}/catalog-be/src/main/resources/config/SDC.zip</sourceFile>
+ <destinationFile>${project.parent.basedir}/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/files/default/SDC.zip</destinationFile>
+ </configuration>
+ </execution>
+ <execution>
+ <id>rename-file</id>
+ <phase>install</phase>
+ <goals>
+ <goal>rename</goal>
+ </goals>
+ <configuration>
+ <sourceFile>${project.parent.basedir}/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/files/default/SDC.zip</sourceFile>
+ <destinationFile>${project.parent.basedir}/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/files/default/SDC-${parsedVersion.majorVersion}.${parsedVersion.minorVersion}.${parsedVersion.incrementalVersion}.zip</destinationFile>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
- </plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-assembly-plugin</artifactId>
+ <version>2.6</version>
+ <executions>
+ <execution>
+ <id>normatives</id>
+ <phase>package</phase>
+ <goals>
+ <goal>single</goal>
+ </goals>
+ <configuration>
+ <finalName>normatives</finalName>
+ <appendAssemblyId>false</appendAssemblyId>
+ <descriptor>${project.basedir}/normatives.xml</descriptor>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
- <pluginManagement>
- <plugins>
+ <pluginManagement>
+ <plugins>
<!--This plugin's configuration is used to store Eclipse m2e settings
- only. It has no influence on the Maven build itself. -->
+ only. It has no influence on the Maven build itself. -->
<plugin>
<groupId>org.eclipse.m2e</groupId>
<artifactId>lifecycle-mapping</artifactId>
@@ -836,13 +853,70 @@
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.7</version>
+ <configuration>
+ <skip>true</skip>
+ </configuration>
</plugin>
-
</plugins>
</pluginManagement>
<!-- Swagger Plugins End -->
</build>
-
-
+ <profiles>
+ <profile>
+ <id>catalog</id>
+ <activation>
+ <activeByDefault>false</activeByDefault>
+ </activation>
+
+
+ <build>
+ <finalName>${project.artifactId}-${full.release.version}</finalName>
+ <plugins>
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>properties-maven-plugin</artifactId>
+ <version>1.0-alpha-2</version>
+
+ <executions>
+ <execution>
+ <inherited>false</inherited>
+ <phase>initialize</phase>
+ <goals>
+ <goal>read-project-properties</goal>
+ </goals>
+ <configuration>
+ <files>
+ <file>${project.parent.build.directory}/FullReleaseVersion.properties</file>
+ </files>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
+ </profile>
+
+ <profile>
+ <id>Fortify</id>
+ <activation>
+ <activeByDefault>false</activeByDefault>
+ </activation>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>com.fortify.ps.maven.plugin</groupId>
+ <artifactId>sca-maven-plugin</artifactId>
+ <version>4.30</version>
+ <configuration>
+ <source>1.8</source>
+ <buildId>${project.parent.artifactId}</buildId>
+ <toplevelArtifactId>${project.parent.artifactId}</toplevelArtifactId>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+ </profile>
+ </profiles>
</project>
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 eb14b5afe7..8ff3fca4f8 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
@@ -20,6 +20,9 @@
package org.openecomp.sdc.be.auditing.impl;
+import org.apache.commons.lang3.StringUtils;
+import org.openecomp.sdc.be.components.impl.ImportUtils;
+import org.openecomp.sdc.be.model.LifecycleStateEnum;
import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
public interface AuditingLogFormatConstants {
@@ -148,7 +151,8 @@ public interface AuditingLogFormatConstants {
AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION,
AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID,
AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE,
- AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE
+ AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE
+
};
static AuditingFieldsKeysEnum[] USER_ACCESS_TEMPLATE_ARRAY = {
@@ -234,9 +238,6 @@ public interface AuditingLogFormatConstants {
AuditingFieldsKeysEnum.AUDIT_DESC
};
static AuditingFieldsKeysEnum[] EXTERNAL_DOWNLOAD_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_STATUS,
@@ -255,4 +256,45 @@ public interface AuditingLogFormatConstants {
AuditingFieldsKeysEnum.AUDIT_STATUS,
AuditingFieldsKeysEnum.AUDIT_DESC
};
+
+ static 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_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 5fec39bbdb..b965516df8 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
@@ -24,7 +24,9 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumMap;
import java.util.Formatter;
+import java.util.HashSet;
import java.util.Locale;
+import java.util.Set;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
import org.openecomp.sdc.common.api.Constants;
@@ -43,7 +45,7 @@ public class AuditingLogFormatUtil {
// This is the key by which audit marker is recognized in logback.xml
private static String AUDIT_MARKER_STR = "AUDIT_MARKER";
- public static Marker auditMarker = MarkerFactory.getMarker(AUDIT_MARKER_STR);
+ public static final Marker auditMarker = MarkerFactory.getMarker(AUDIT_MARKER_STR);
protected static void logAuditEvent(EnumMap<AuditingFieldsKeysEnum, Object> auditingFields) {
@@ -77,7 +79,7 @@ public class AuditingLogFormatUtil {
log.info(auditMarker, formattedString);
}
} catch (Exception e) {
- log.debug("unexpected error occurred: {} {}", e.getMessage(), e);
+ log.debug("unexpected error occurred: {}", e.getMessage(), e);
} finally {
formatter.close();
@@ -144,14 +146,13 @@ public class AuditingLogFormatUtil {
case ARTIFACT_METADATA_UPDATE:
case ARTIFACT_PAYLOAD_UPDATE:
case ARTIFACT_DOWNLOAD:
- ArrayList<AuditingFieldsKeysEnum> artifactFieldsList = new ArrayList(Arrays.asList(AuditingLogFormatConstants.CREATE_RESOURCE_TEMPLATE_PREFIX_ARRAY));
- artifactFieldsList.add(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID);
- artifactFieldsList.add(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID);
- artifactFieldsList.add(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA);
- artifactFieldsList.addAll(Arrays.asList(AuditingLogFormatConstants.CREATE_RESOURCE_TEMPLATE_SUFFIX_ARRAY));
- artifactFieldsList.addAll(Arrays.asList(AuditingLogFormatConstants.EXTERNAL_DOWNLOAD_ARTIFACT_ARRAY));
+ 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 = artifactFieldsList.toArray(artifactFieldsArray);
+ artifactFieldsArray = artifactFieldsSet.toArray(artifactFieldsArray);
formattedString = buildStringAccrodingToArray(artifactFieldsArray, auditingFields);
break;
case DOWNLOAD_ARTIFACT:
@@ -225,6 +226,12 @@ public class AuditingLogFormatUtil {
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;
}
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 3528ed9be3..6738b87853 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
@@ -21,7 +21,6 @@
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;
@@ -54,6 +53,7 @@ import com.att.nsa.cambria.client.CambriaTopicManager;
import com.google.gson.Gson;
import fj.data.Either;
+import jline.internal.Log;
public class CambriaHandler {
@@ -63,6 +63,169 @@ public class CambriaHandler {
private Gson gson = new Gson();
+ public static void main(String[] args) {
+
+ // String userBodyJson ="{\"artifactName\":\"myartifact\",
+ // \"artifactType\":\"MURANO-PKG\",
+ // \"artifactDescription\":\"description\",
+ // \"payloadData\":\"UEsDBAoAAAAIAAeLb0bDQz\", \"Content-MD5\":
+ // \"YTg2Mjg4MWJhNmI5NzBiNzdDFkMWI=\" }";
+ // System.out.println(userBodyJson);
+ // String encodeBase64Str = GeneralUtililty.calculateMD5 (userBodyJson);
+ // System.out.println(encodeBase64Str);
+
+ CambriaTopicManager createTopicManager = null;
+ try {
+ List<String> servers = new ArrayList<String>();
+ // servers.add("uebsb91kcdc.it.sdc.com:3904");
+ // servers.add("uebsb92kcdc.it.sdc.com:3904");
+ // servers.add("uebsb93kcdc.it.sdc.com:3904");
+ servers.add("uebsb91sfdc.it.att.com:3904");
+ servers.add("uebsb92sfdc.it.att.com:3904");
+
+ String key = "sSJc5qiBnKy2qrlc";
+ String secret = "4ZRPzNJfEUK0sSNBvccd2m7X";
+
+ createTopicManager = new TopicManagerBuilder().usingHttps().usingHosts(servers).authenticatedBy(key, secret).build();
+
+ String topicName = "ASDC-DISTR-NOTIF-TOPIC-PRODesofer";
+
+ String clientKey1 = "CGGoorrGPXPx2B1C";
+ String clientSecret1 = "OTHk2mcCSbskEtHhDw8h5oUa";
+
+ CambriaTopicManager createStatusTopicManager = new TopicManagerBuilder().usingHttps().usingHosts(servers).authenticatedBy(key, secret).build();
+ String reportTopic = "ASDC-DISTR-STATUS-TOPIC-PRODESOFER";
+ createStatusTopicManager.allowProducer(reportTopic, clientKey1);
+
+ CambriaBatchingPublisher createSimplePublisher = new PublisherBuilder().onTopic(reportTopic).usingHttps().usingHosts(servers).build();
+ createSimplePublisher.setApiCredentials(clientKey1, clientSecret1);
+
+ DistributionStatusNotification distributionStatusNotification = new DistributionStatusNotification();
+ distributionStatusNotification.setStatus(DistributionStatusNotificationEnum.DEPLOY_OK);
+ distributionStatusNotification.setArtifactURL("Ssssssss url");
+ distributionStatusNotification.setDistributionID("idddddddddddddd");
+ distributionStatusNotification.setTimestamp(System.currentTimeMillis());
+ distributionStatusNotification.setConsumerID("my consumer id");
+
+ Gson gson = new Gson();
+ int result = createSimplePublisher.send(PARTITION_KEY, gson.toJson(distributionStatusNotification));
+
+ List<message> messagesInQ = createSimplePublisher.close(20, TimeUnit.SECONDS);
+ System.out.println(messagesInQ == null ? 0 : messagesInQ.size());
+
+ // createTopicManager.createTopic(topicName, "my test topic", 1, 1);
+
+ /*
+ *
+ * { "secret": "OTHk2mcCSbskEtHhDw8h5oUa", "aux": { "email": "esofer@intl.sdc.com", "description": "test-keys" }, "key": "CGGoorrGPXPx2B1C" }
+ *
+ *
+ * { "secret": "FSlNJbmGWWBvBLJetQMYxPP6", "aux": { "email": "esofer@intl.sdc.com", "description": "test-keys" }, "key": "TAIEPO0aDU4VzM0G" }
+ *
+ */
+
+ String clientKey2 = "TAIEPO0aDU4VzM0G";
+
+ CambriaConsumer createConsumer1 = new ConsumerBuilder().authenticatedBy("asdc1", "consumerId1").onTopic(topicName).usingHttps().usingHosts(servers).build();
+ createConsumer1.setApiCredentials(clientKey1, "OTHk2mcCSbskEtHhDw8h5oUa");
+
+ createTopicManager.allowConsumer(topicName, clientKey1);
+
+ CambriaConsumer createConsumer2 = null;
+ if (true) {
+ createConsumer2 = new ConsumerBuilder().authenticatedBy("asdc2", "consumerId3").onTopic(topicName).usingHttps().usingHosts(servers).build();
+ createConsumer2.setApiCredentials(clientKey2, "FSlNJbmGWWBvBLJetQMYxPP6");
+
+ createTopicManager.allowConsumer(topicName, clientKey2);
+ }
+
+ createSimplePublisher = new PublisherBuilder().onTopic(topicName).usingHttps().usingHosts(servers).build();
+ createSimplePublisher.setApiCredentials(key, secret);
+ createTopicManager.allowProducer(topicName, key);
+
+ createSimplePublisher.send("aaaa", "{ my testttttttttttttttt }");
+
+ while (true) {
+
+ Iterable<String> fetch1 = createConsumer1.fetch();
+
+ Iterator<String> iterator1 = fetch1.iterator();
+ while (iterator1.hasNext()) {
+ System.out.println("***********************************************");
+ System.out.println("client 1" + iterator1.next());
+ System.out.println("***********************************************");
+ }
+
+ if (createConsumer2 != null) {
+ Iterable<String> fetch2 = createConsumer2.fetch();
+
+ Iterator<String> iterator2 = fetch2.iterator();
+ while (iterator2.hasNext()) {
+ System.out.println("***********************************************");
+ System.out.println("client 2" + iterator2.next());
+ System.out.println("***********************************************");
+ }
+ }
+ Thread.sleep(1000 * 20);
+ }
+
+ // createTopicManager = CambriaClientFactory.createTopicManager(
+ // servers, "8F3MDAtMSBwwpSMy", "gzFmsTxSCtO5RQfAccM6PqqX");
+
+ // createTopicManager.deleteTopic("ASDC-DISTR-NOTIF-TOPIC-PROD");
+ // createTopicManager.deleteTopic("ASDC-DISTR-NOTIF-TOPIC-PROD1");
+
+ // CambriaIdentityManager createIdentityManager =
+ // CambriaClientFactory.createIdentityManager(null, null, null);
+ // createIdentityManager.setApiCredentials(arg0, arg1);
+ // createIdentityManager.cl
+
+ // String topicName = " ";
+ // createTopicManager.createTopic(topicName,
+ // "ASDC distribution notification topic", 1, 1);
+ //
+ // Thread.sleep(10 * 1000);
+ //
+ // for (int i = 0; i < 5; i++) {
+ // try {
+ // boolean openForProducing = createTopicManager
+ // .isOpenForProducing(topicName);
+ //
+ // System.out.println("openForProducing=" + openForProducing);
+ // createTopicManager.allowProducer(topicName,
+ // "8F3MDAtMSBwwpSMy");
+ // Set<String> allowedProducers = createTopicManager
+ // .getAllowedProducers(topicName);
+ // System.out.println(allowedProducers);
+ //
+ // } catch (Exception e) {
+ // e.printStackTrace();
+ // }
+ // }
+
+ // createTopicManager.createTopic("", "", 0, 0);
+ // createTopicManager.allowProducer(arg0, arg1);
+ // createTopicManager.getTopics();
+ // createTopicManager.close();
+ // CambriaClientFactory.
+ // CambriaBatchingPublisher createSimplePublisher =
+ // CambriaClientFactory.createSimplePublisher("hostlist", "topic");
+
+ // CambriaIdentityManager createIdentityManager =
+ // CambriaClientFactory.createIdentityManager(null, "apiKey",
+ // "apiSecret");
+ // createIdentityManager.
+
+ } catch (Exception e) {
+ Log.debug("Exception in main test of Cambria Handler: {}", e.getMessage(), e);
+ e.printStackTrace();
+ } finally {
+ if (createTopicManager != null) {
+ createTopicManager.close();
+ }
+ }
+ }
+
/**
* process the response error from Cambria client
*
@@ -121,7 +284,8 @@ public class CambriaHandler {
CambriaTopicManager createTopicManager = null;
try {
- createTopicManager = new TopicManagerBuilder().usingHosts(hostSet).build();
+ createTopicManager = new TopicManagerBuilder().usingHttps().usingHosts(hostSet).build();
+
Set<String> topics = createTopicManager.getTopics();
if (topics == null || true == topics.isEmpty()) {
@@ -263,10 +427,13 @@ public class CambriaHandler {
CambriaTopicManager createTopicManager = null;
try {
- createTopicManager = new TopicManagerBuilder().usingHosts(hostSet).authenticatedBy(apiKey, secretKey).build();
+
+ createTopicManager = new TopicManagerBuilder().usingHttps().usingHosts(hostSet).authenticatedBy(apiKey, secretKey).build();
+
createTopicManager.createTopic(topicName, "ASDC distribution notification topic", partitionCount, replicationCount);
- } catch (GeneralSecurityException | HttpException | IOException e) {
+ } catch (HttpException | IOException | GeneralSecurityException e) {
+
logger.debug("Failed to create topic {}", topicName, e);
String methodName = new Object() {
}.getClass().getEnclosingMethod().getName();
@@ -285,12 +452,13 @@ public class CambriaHandler {
}
}
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 = new TopicManagerBuilder().usingHosts(hostSet).authenticatedBy(managerApiKey, managerSecretKey).build();
+ createTopicManager = new TopicManagerBuilder().usingHttps().usingHosts(hostSet).authenticatedBy(managerApiKey, managerSecretKey).build();
if (subscriberTypeEnum == SubscriberTypeEnum.PRODUCER) {
createTopicManager.revokeProducer(topicName, subscriberApiKey);
@@ -345,7 +513,7 @@ public class CambriaHandler {
CambriaTopicManager createTopicManager = null;
try {
- createTopicManager = new TopicManagerBuilder().usingHosts(hostSet).authenticatedBy(managerApiKey, managerSecretKey).build();
+ createTopicManager = new TopicManagerBuilder().usingHttps().usingHosts(hostSet).authenticatedBy(managerApiKey, managerSecretKey).build();
if (subscriberTypeEnum == SubscriberTypeEnum.PRODUCER) {
createTopicManager.allowProducer(topicName, subscriberApiKey);
@@ -395,11 +563,11 @@ public class CambriaHandler {
* @param consumerGroup
* @param timeoutMS
* @return
- * @throws Exception
+ * @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).withSocketTimeout(timeoutMS).build();
+ CambriaConsumer consumer = new ConsumerBuilder().authenticatedBy(apiKey, secretKey).knownAs(consumerGroup, consumerId).onTopic(topicName).usingHttps().usingHosts(hostSet).withSocketTimeout(timeoutMS).build();
consumer.setApiCredentials(apiKey, secretKey);
return consumer;
}
@@ -470,7 +638,7 @@ public class CambriaHandler {
String json = gson.toJson(data);
logger.trace("Before sending notification data {} to topic {}", json, topicName);
- createSimplePublisher = new PublisherBuilder().onTopic(topicName).usingHosts(uebServers).build();
+ createSimplePublisher = new PublisherBuilder().onTopic(topicName).usingHttps().usingHosts(uebServers).build();
createSimplePublisher.setApiCredentials(uebPublicKey, uebSecretKey);
int result = createSimplePublisher.send(PARTITION_KEY, json);
@@ -532,7 +700,7 @@ public class CambriaHandler {
String json = gson.toJson(data);
logger.debug("Before sending notification data {} to topic {}", json, topicName);
- createSimplePublisher = new PublisherBuilder().onTopic(topicName).usingHosts(uebServers).build();
+ createSimplePublisher = new PublisherBuilder().onTopic(topicName).usingHttps().usingHosts(uebServers).build();
createSimplePublisher.setApiCredentials(uebPublicKey, uebSecretKey);
int result = createSimplePublisher.send(PARTITION_KEY, json);
@@ -559,7 +727,7 @@ public class CambriaHandler {
}
- logger.debug("Before closing publisher. Maximum timeout is {} seconds.", waitBeforeCloseTimeout);
+ 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()) {
@@ -593,7 +761,7 @@ public class CambriaHandler {
hostSet.add(server);
CambriaIdentityManager createIdentityManager = null;
try {
- createIdentityManager = new IdentityManagerBuilder().usingHosts(hostSet).build();
+ createIdentityManager = new IdentityManagerBuilder().usingHttps().usingHosts(hostSet).build();
createIdentityManager.getApiKey(apiKey);
response = new CambriaErrorResponse(CambriaOperationStatus.OK, 200);
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 6cb31c8cf2..d3d04ea735 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
@@ -51,6 +51,22 @@ 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;
@@ -319,10 +335,8 @@ public class DistributionEngine implements IDistributionEngine {
@Override
public StorageOperationStatus notifyService(String distributionId, Service service, INotificationData notificationData, String envName, String userId, String modifierName) {
-
- if (logger.isDebugEnabled()) {
- logger.debug("Received notify service request. distributionId = {}, serviceUuid = {}, serviceUid = {}, envName = {}, userId = {}, modifierName {}", distributionId, service.getUUID(), service.getUniqueId(), envName, userId, modifierName);
- }
+
+ logger.debug("Received notify service request. distributionId = {}, serviceUuid = {} serviceUid = {}, envName = {}, userId = {}, modifierName {}", distributionId, service.getUUID(), service.getUniqueId(), envName, userId, modifierName);
DistributionEngineConfiguration deConfiguration = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration();
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 a3d0362c61..1b868951c5 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
@@ -72,10 +72,10 @@ public class DistributionEngineClusterHealth {
public enum HealthCheckInfoResult {
- OK(new HealthCheckInfo(HealthCheckComponent.DE, HealthCheckStatus.UP, null, ClusterStatusDescription.OK.getDescription())), UNAVAILABLE(
- new HealthCheckInfo(HealthCheckComponent.DE, HealthCheckStatus.DOWN, null, ClusterStatusDescription.UNAVAILABLE.getDescription())), NOT_CONFIGURED(
- new HealthCheckInfo(HealthCheckComponent.DE, HealthCheckStatus.DOWN, null, ClusterStatusDescription.NOT_CONFIGURED.getDescription())), DISABLED(
- new HealthCheckInfo(HealthCheckComponent.DE, HealthCheckStatus.DOWN, null, ClusterStatusDescription.DISABLED.getDescription()));
+ OK(new HealthCheckInfo(HealthCheckComponent.DE, HealthCheckStatus.UP, null, ClusterStatusDescription.OK.getDescription())),
+ UNAVAILABLE(new HealthCheckInfo(HealthCheckComponent.DE, HealthCheckStatus.DOWN, null, ClusterStatusDescription.UNAVAILABLE.getDescription())),
+ NOT_CONFIGURED(new HealthCheckInfo(HealthCheckComponent.DE, HealthCheckStatus.DOWN, null, ClusterStatusDescription.NOT_CONFIGURED.getDescription())),
+ DISABLED(new HealthCheckInfo(HealthCheckComponent.DE, HealthCheckStatus.DOWN, null, ClusterStatusDescription.DISABLED.getDescription()));
private HealthCheckInfo healthCheckInfo;
@@ -237,6 +237,7 @@ public class DistributionEngineClusterHealth {
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++;
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 667276db2c..16a0a1dc31 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
@@ -30,10 +30,8 @@ import org.openecomp.sdc.be.config.DistributionEngineConfiguration;
import org.openecomp.sdc.be.config.DistributionEngineConfiguration.DistributionNotificationTopicConfig;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.model.Service;
-import org.openecomp.sdc.be.model.operations.api.IServiceOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
-import org.openecomp.sdc.be.model.operations.impl.ResourceOperation;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
import org.openecomp.sdc.common.util.ThreadLocalsHolder;
import org.slf4j.Logger;
@@ -47,7 +45,7 @@ public class DistributionNotificationSender {
private static Logger logger = LoggerFactory.getLogger(DistributionNotificationSender.class.getName());
- // final String BASE_ARTIFACT_URL = "/asdc/v1/catalog/services/%s/%s/";
+ // 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";
@@ -56,12 +54,6 @@ public class DistributionNotificationSender {
InterfaceLifecycleOperation interfaceLifecycleOperation;
@javax.annotation.Resource
- protected IServiceOperation serviceOperation;
-
- @javax.annotation.Resource
- protected ResourceOperation resourceOperation;
-
- @javax.annotation.Resource
protected ComponentsUtils componentUtils;
ExecutorService executorService = null;
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 25a6f46c90..d1b445b065 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
@@ -25,7 +25,7 @@ import java.util.List;
import org.openecomp.sdc.be.model.ComponentInstance;
public class JsonContainerResourceInstance {
- private String resourceInstanceName, resourceName, resourceVersion, resoucreType, resourceUUID, resourceInvariantUUID;
+ private String resourceInstanceName, resourceName, resourceVersion, resoucreType, resourceUUID, resourceInvariantUUID, resourceCustomizationUUID, category, subcategory;
private List<ArtifactInfoImpl> artifacts;
public JsonContainerResourceInstance(ComponentInstance resourceInstance, String resourceType, List<ArtifactInfoImpl> artifacts) {
@@ -36,17 +36,7 @@ public class JsonContainerResourceInstance {
this.resoucreType = resourceType;
this.resourceUUID = resourceInstance.getComponentUid();
this.artifacts = artifacts;
- }
-
- public JsonContainerResourceInstance(ComponentInstance resourceInstance, String resourceInvariantUUID, 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.resourceInvariantUUID = resourceInvariantUUID;
- this.artifacts = artifacts;
+ this.resourceCustomizationUUID = resourceInstance.getCustomizationUUID();
}
public String getResourceInstanceName() {
@@ -105,4 +95,27 @@ public class JsonContainerResourceInstance {
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;
+ }
}
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
index 362f3948ed..c283ecc92b 100644
--- 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
@@ -108,13 +108,13 @@ public class PublishNotificationRunnable implements Runnable {
ThreadLocalsHolder.setUuid(this.requestId);
CambriaErrorResponse status = cambriaHandler.sendNotificationAndClose(topicName, deConfiguration.getUebPublicKey(), deConfiguration.getUebSecretKey(), deConfiguration.getUebServers(), data,
- deConfiguration.getDistributionNotificationTopic().getMaxWaitingAfterSendingSeconds().longValue());
+ 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));
+ logger.debug("After building and publishing artifacts object. Total took {} milliseconds", (endTime - startTime));
}
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 6e67e38c15..90120288bc 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
@@ -24,22 +24,27 @@ 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 org.openecomp.sdc.be.config.ConfigurationManager;
-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.ComponentParametersView;
import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.model.category.CategoryDefinition;
+import org.openecomp.sdc.be.model.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.be.model.operations.impl.ResourceOperation;
-import org.openecomp.sdc.be.model.operations.impl.ServiceOperation;
+import org.openecomp.sdc.common.api.ArtifactTypeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import fj.data.Either;
@@ -51,47 +56,31 @@ public class ServiceDistributionArtifactsBuilder {
private static Logger logger = LoggerFactory.getLogger(ServiceDistributionArtifactsBuilder.class.getName());
- final static String BASE_ARTIFACT_URL = "/asdc/v1/catalog/services/%s/%s/";
+ 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
- ServiceOperation serviceOperation;
-
- @javax.annotation.Resource
- ResourceOperation resourceOperation;
-
- @javax.annotation.Resource
InterfaceLifecycleOperation interfaceLifecycleOperation;
@javax.annotation.Resource
IArtifactOperation artifactOperation;
+
+ @Autowired
+ ToscaOperationFacade toscaOperationFacade;
/*
- * @javax.annotation.Resource private InformationDeployedArtifactsBusinessLogic informationDeployedArtifactsBusinessLogic;
+ * @javax.annotation.Resource private
+ * InformationDeployedArtifactsBusinessLogic
+ * informationDeployedArtifactsBusinessLogic;
*/
@PostConstruct
private void init() {
- defaultArtifactInstallTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getDefaultHeatArtifactTimeoutMinutes();
- }
-
- public ServiceOperation getServiceOperation() {
- return serviceOperation;
- }
-
- public void setServiceOperation(ServiceOperation serviceOperation) {
- this.serviceOperation = serviceOperation;
- }
-
- public ResourceOperation getResourceOperation() {
- return resourceOperation;
- }
-
- public void setResourceOperation(ResourceOperation resourceOperation) {
- this.resourceOperation = resourceOperation;
+ defaultArtifactInstallTimeout = ConfigurationManager.getConfigurationManager().getConfiguration()
+ .getDefaultHeatArtifactTimeoutMinutes();
}
public InterfaceLifecycleOperation getInterfaceLifecycleOperation() {
@@ -130,37 +119,91 @@ public class ServiceDistributionArtifactsBuilder {
}
private List<ArtifactInfoImpl> convertServiceArtifactsToArtifactInfo(Service service) {
-
+
Map<String, ArtifactDefinition> serviceArtifactsMap = service.getDeploymentArtifacts();
- List<ArtifactDefinition> ret = new ArrayList<ArtifactDefinition>();
-
- for (ArtifactDefinition artifactDef : serviceArtifactsMap.values()) {
- if (artifactDef.checkEsIdExist()) {
- ret.add(artifactDef);
- }
+ 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());
}
- List<ArtifactInfoImpl> artifacts = ArtifactInfoImpl.convertServiceArtifactToArtifactInfoImpl(service, ret);
+
+ 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 resourceType = "VF";
+ String resoucreType = resourceInstance.getOriginType().getValue();
List<ArtifactDefinition> artifactsDefList = getArtifactsWithPayload(resourceInstance);
- List<ArtifactInfoImpl> artifacts = ArtifactInfoImpl.convertToArtifactInfoImpl(service, resourceInstance, artifactsDefList);
- Either<String, StorageOperationStatus> responseResult = resourceOperation.getInvariantUUID(NodeTypeEnum.Resource, resourceInstance.getComponentUid(), false);
+ List<ArtifactInfoImpl> artifacts = ArtifactInfoImpl.convertToArtifactInfoImpl(service, resourceInstance,
+ artifactsDefList);
+
String resourceInvariantUUID = null;
- if (responseResult.isRight()) {
- logger.debug("Resource {} Invariant UUID retrieving failed", resourceInstance.getComponentUid());
+ 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 {
- resourceInvariantUUID = responseResult.left().value();
+ 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, resourceInvariantUUID, resourceType, artifacts);
+
+ JsonContainerResourceInstance jsonContainer = new JsonContainerResourceInstance(resourceInstance, resoucreType,
+ artifacts);
+ jsonContainer.setResourceInvariantUUID(resourceInvariantUUID);
+ jsonContainer.setCategory(resourceCategory);
+ jsonContainer.setSubcategory(resourceSubcategory);
ret.add(jsonContainer);
}
-
}
return ret;
}
@@ -193,9 +236,11 @@ public class ServiceDistributionArtifactsBuilder {
* @param artifactName
* @return
*/
- public static String buildResourceInstanceArtifactUrl(Service service, ComponentInstance resourceInstance, String artifactName) {
+ 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);
+ String url = String.format(RESOURCE_INSTANCE_ARTIFACT_URL, service.getSystemName(), service.getVersion(),
+ resourceInstance.getNormalizedName(), artifactName);
logger.debug("After building artifact url {}", url);
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/TestQueue.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/TestQueue.java
index c9e3c4e34d..d9cd6ef51f 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/TestQueue.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/TestQueue.java
@@ -64,13 +64,11 @@ public class TestQueue {
@Override
public void run() {
- // TODO Auto-generated method stub
try {
System.out.println("iN SLEEP" + Thread.currentThread());
Thread.sleep(10 * 1000);
System.out.println("OUT SLEEP");
} catch (InterruptedException e) {
- // TODO Auto-generated catch block
e.printStackTrace();
}
}
@@ -98,7 +96,6 @@ public class TestQueue {
try {
queue.put("message " + i);
} catch (InterruptedException e) {
- // TODO Auto-generated catch block
e.printStackTrace();
}
}
@@ -175,7 +172,6 @@ public class TestQueue {
try {
Thread.sleep(1 * 1000);
} catch (InterruptedException e) {
- // TODO Auto-generated catch block
for (int i = 0; i < 10; i++) {
System.out.println("*************************************************");
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 89cb6d91ee..71593fa99a 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,14 +20,26 @@
package org.openecomp.sdc.be.components.distribution.engine;
+import java.util.ArrayList;
import java.util.List;
+import java.util.Map;
import java.util.Optional;
+import java.util.stream.Collectors;
+import org.apache.commons.collections.CollectionUtils;
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;
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();
@@ -40,10 +52,38 @@ public class VfModuleArtifactPayload {
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();
+ // 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.getProperties().stream().filter(p -> p.getName().equals(Constants.IS_BASE)).findAny();
+ Optional<GroupProperty> findBaseProperty = group.convertToGroupProperties().stream().filter(p -> p.getName().equals(Constants.IS_BASE)).findAny();
if (findBaseProperty.isPresent()) {
isBase = Boolean.valueOf(findBaseProperty.get().getValue());
}
@@ -51,9 +91,7 @@ public class VfModuleArtifactPayload {
}
}
- private String vfModuleModelName, vfModuleModelInvariantUUID, vfModuleModelVersion, vfModuleModelUUID, vfModuleModelDescription;
- private Boolean isBase;
- private List<String> artifacts;
+
public List<String> getArtifacts() {
return artifacts;
@@ -62,10 +100,25 @@ public class VfModuleArtifactPayload {
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) {
- Integer thisCounter = Integer.parseInt(art1.vfModuleModelName.split(Constants.MODULE_NAME_DELIMITER)[1]);
- Integer otherCounter = Integer.parseInt(art2.vfModuleModelName.split(Constants.MODULE_NAME_DELIMITER)[1]);
+ 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/impl/AdditionalInformationBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AdditionalInformationBusinessLogic.java
index e01d4c238c..51b5679ffa 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
@@ -29,17 +29,15 @@ import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.dao.graph.datatype.AdditionalInformationEnum;
import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterInfo;
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.AdditionalInfoParameterInfo;
import org.openecomp.sdc.be.model.AdditionalInformationDefinition;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.model.operations.api.IAdditionalInformationOperation;
import org.openecomp.sdc.be.model.operations.api.IElementOperation;
import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation;
-import org.openecomp.sdc.be.model.operations.api.IResourceOperation;
-import org.openecomp.sdc.be.model.operations.api.IServiceOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
@@ -73,12 +71,6 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic {
private IAdditionalInformationOperation additionalInformationOperation = null;
@javax.annotation.Resource
- private IResourceOperation resourceOperation;
-
- @javax.annotation.Resource
- private IServiceOperation serviceOperation;
-
- @javax.annotation.Resource
private IGraphLockOperation graphLockOperation;
@javax.annotation.Resource
@@ -551,7 +543,7 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic {
// verify that resource is checked-out and the user is the last
// updater
- if (!ComponentValidationUtils.canWorkOnResource(resourceId, resourceOperation, userId)) {
+ if (!ComponentValidationUtils.canWorkOnComponent(resourceId, toscaOperationFacade, userId)) {
return componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
}
break;
@@ -559,7 +551,7 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic {
// verify that resource is checked-out and the user is the last
// updater
- if (!ComponentValidationUtils.canWorkOnService(resourceId, serviceOperation, userId)) {
+ if (!ComponentValidationUtils.canWorkOnComponent(resourceId, toscaOperationFacade, userId)) {
return componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
}
break;
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 16ed4a1868..6739d28bd4 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
@@ -24,13 +24,13 @@ import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
-import java.util.Collection;
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.Optional;
import java.util.Set;
import java.util.function.Predicate;
import java.util.function.Supplier;
@@ -39,6 +39,9 @@ import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
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.impl.ImportUtils.ResultStatusEnum;
import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum;
@@ -46,14 +49,15 @@ 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;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
-import org.openecomp.sdc.be.config.Configuration.DeploymentArtifactTypeConfig;
+import org.openecomp.sdc.be.config.Configuration.ArtifactTypeConfig;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.config.validation.DeploymentArtifactHeatConfiguration;
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.titan.TitanOperationStatus;
+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.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
@@ -61,6 +65,9 @@ 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;
@@ -70,19 +77,14 @@ import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.Service;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.model.heat.HeatParameterType;
-import org.openecomp.sdc.be.model.operations.api.IArtifactOperation;
-import org.openecomp.sdc.be.model.operations.api.IComponentInstanceOperation;
+import org.openecomp.sdc.be.model.jsontitan.operations.NodeTemplateOperation;
import org.openecomp.sdc.be.model.operations.api.IElementOperation;
import org.openecomp.sdc.be.model.operations.api.IHeatParametersOperation;
import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation;
-import org.openecomp.sdc.be.model.operations.api.IResourceOperation;
import org.openecomp.sdc.be.model.operations.api.IUserAdminOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.model.operations.impl.ComponentOperation;
import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
-import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
-import org.openecomp.sdc.be.resources.data.ArtifactData;
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;
@@ -98,7 +100,6 @@ import org.openecomp.sdc.be.user.UserBusinessLogic;
import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
import org.openecomp.sdc.common.api.ArtifactTypeEnum;
import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.config.EcompErrorName;
import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
import org.openecomp.sdc.common.datastructure.Wrapper;
import org.openecomp.sdc.common.util.GeneralUtility;
@@ -132,25 +133,21 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
private static final String ARTIFACT_PLACEHOLDER_DISPLAY_NAME = "displayName";
private static final Object ARTIFACT_PLACEHOLDER_DESCRIPTION = "description";
- private static Integer defaultHeatTimeout;
- private static final Integer NON_HEAT_TIMEOUT = 0;
+ 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();
@javax.annotation.Resource
- private IArtifactOperation artifactOperation;
-
- // @javax.annotation.Resource
- // private IResourceUploader daoUploader;
-
- @javax.annotation.Resource
private IInterfaceLifecycleOperation interfaceLifecycleOperation;
@javax.annotation.Resource
private IUserAdminOperation userOperaton;
- // @javax.annotation.Resource
- // private ESCatalogDAO esCatalogDao;
-
@javax.annotation.Resource
private IElementOperation elementOperation;
@@ -166,9 +163,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
@javax.annotation.Resource
private IHeatParametersOperation heatParametersOperation;
- @javax.annotation.Resource
- private IComponentInstanceOperation resourceInstanceOperation;
-
@Autowired
private ArtifactCassandraDao artifactCassandraDao;
@@ -183,62 +177,71 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
@Autowired
private IUserBusinessLogic userBusinessLogic;
+ @Autowired
+ NodeTemplateOperation nodeTemplateOperation;
public ArtifactsBusinessLogic() {
- defaultHeatTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getDefaultHeatArtifactTimeoutMinutes();
- if ((defaultHeatTimeout == null) || (defaultHeatTimeout < 1)) {
- defaultHeatTimeout = 60;
- }
+ // defaultHeatTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getDefaultHeatArtifactTimeoutMinutes();
+ // if ((defaultHeatTimeout == null) || (defaultHeatTimeout < 1)) {
+ // defaultHeatTimeout = 60;
+ // }
}
- public static enum ArtifactOperation {
+ public static enum ArtifactOperationEnum {
+ Create(), Update(), Delete(), Download();
+ }
- Create(false), Update(false), Delete(false), Download(false);
+ public class ArtifactOperationInfo {
+ private ArtifactOperationEnum artifactOperationEnum;
private boolean isExternalApi;
+ private boolean ignoreLifecycleState;
- ArtifactOperation(boolean isExternalApi) {
+ public ArtifactOperationInfo(boolean isExternalApi, boolean ignoreLifecycleState, ArtifactOperationEnum artifactOperationEnum) {
+ this.artifactOperationEnum = artifactOperationEnum;
this.isExternalApi = isExternalApi;
+ this.ignoreLifecycleState = ignoreLifecycleState;
}
public boolean isExternalApi() {
return isExternalApi;
}
- public void setExternalApi(boolean isExternalApi) {
- this.isExternalApi = 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, ArtifactOperation operation, String artifactId, ArtifactDefinition artifactInfo,
+ 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, ArtifactOperation operation, String artifactId, ArtifactDefinition artifactInfo,
+ 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
+
+ // step 1 - detect auditing type
AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5);
- Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
- // step 2
- // check header
+ // 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
- // step 4
- // check user's role
+ // 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()) {
@@ -271,17 +274,17 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
/**
* 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, ArtifactOperation, String, ArtifactDefinition, String, String, String, String, String, String)}
+ * {@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, ArtifactOperation operation, String artifactUniqueId, ArtifactDefinition artifactDefinition,
- String origMd5, String originData, String interfaceName, String operationName, String parentId, User user, Component component, boolean shouldLock, boolean inTransaction) {
+ 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) {
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);
+ artifactDefinition = validateArtifact(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, parentId, auditingAction, user, component, parent, shouldLock, errorWrapper, inTransaction);
Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result;
if (errorWrapper.isEmpty()) {
@@ -293,43 +296,53 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return result;
}
- private ArtifactDefinition validateArtifact(String componentId, ComponentTypeEnum componentType, ArtifactOperation 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) {
- if (operation == ArtifactOperation.Update || operation == ArtifactOperation.Delete || operation == ArtifactOperation.Download) {
- Either<ArtifactDefinition, ResponseFormat> validateArtifact = validateArtifact(componentId, componentType, artifactId, component, auditingAction, parentId);
+ 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 == ArtifactOperation.Download) {
- artifactInfo = validateArtifact.left().value();
- handleHeatEnvDownload(componentId, user, component, validateArtifact, shouldLock, errorWrapper);
+ } 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, User user, org.openecomp.sdc.be.model.Component component, Either<ArtifactDefinition, ResponseFormat> validateArtifact, boolean shouldLock, Wrapper<ResponseFormat> errorWrapper) {
+ 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())) {
- ComponentInstance componentInstance = component.getComponentInstances().stream().filter(p -> p.getUniqueId().equals(componentId)).findAny().get();
- ArtifactDefinition heatEnvWithHeatParams = componentInstance.getDeploymentArtifacts().values().stream().filter(p -> p.getUniqueId().equals(validatedArtifact.getUniqueId())).findAny().get();
- Either<ArtifactDefinition, ResponseFormat> eitherGenerated = generateHeatEnvArtifact(heatEnvWithHeatParams, component, componentInstance.getName(), user, shouldLock);
- if (eitherGenerated.isRight()) {
- errorWrapper.setInnerElement(eitherGenerated.right().value());
+ 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) {
- return artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && (component.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || component.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ 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()));
+ return needGenerate;
}
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, shouldLock, inTransaction);
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generated = generateToscaArtifact(component, artifactDefinition, isInCertificationRequest, fetchTemplatesFromDB);
if (generated.isRight()) {
return generated;
}
@@ -341,11 +354,10 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
- private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateToscaArtifact(Component parent, ArtifactDefinition artifactInfo, boolean isInCertificationRequest, boolean fetchTemplatesFromDB, boolean shouldLock,
- boolean 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, shouldLock, inTransaction);
+ 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());
@@ -370,16 +382,16 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return Either.left(Either.left(artifactInfo));
}
- private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> doAction(String componentId, ComponentTypeEnum componentType, ArtifactOperation operation, String artifactId, ArtifactDefinition artifactInfo, String origMd5,
+ 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) {
if (interfaceName != null && operationName != null) {
interfaceName = interfaceName.toLowerCase();
operationName = operationName.toLowerCase();
}
- switch (operation) {
+ switch (operation.getArtifactOperationEnum()) {
case Download:
if (artifactGenerationRequired(parent, artifactInfo)) {
- return generateToscaArtifact(parent, artifactInfo, false, false, shouldLock, inTransaction);
+ return generateNotSavedArtifact(parent, artifactInfo, shouldLock, inTransaction);
}
return handleDownload(componentId, artifactId, user, auditingAction, componentType, parent, shouldLock, inTransaction);
case Delete:
@@ -389,6 +401,10 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)
&& (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_VOL || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_ENV)) {
return handleUpdateHeatEnv(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction);
+ } else {
+ if (componentType.equals(ComponentTypeEnum.RESOURCE) && artifactType == ArtifactTypeEnum.HEAT_ENV) {
+ return handleUpdateHeatWithHeatEnvParams(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction);
+ }
}
return handleUpdate(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction);
case Create:
@@ -397,6 +413,87 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return null;
}
+ 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) {
+ 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);
+ 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);
+ }
+ }
+
/**
*
* @param componentId
@@ -404,13 +501,12 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
* @param userId
* @param componentType
* @param parentId
- * TODO
* @return
*/
- public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadToscaModelRequest(Component component, ArtifactDefinition csarArtifact, boolean shouldLock, boolean inTransaction) {
+ public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadToscaModelRequest(Component component, ArtifactDefinition csarArtifact) {
if (artifactGenerationRequired(component, csarArtifact)) {
- Either<byte[], ResponseFormat> generated = csarUtils.createCsar(component, false, false, shouldLock, inTransaction);
+ 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());
@@ -424,7 +520,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
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, ArtifactOperation.Download, artifactId, null, null, null, null, null, parentId, containerComponentType);
+ 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());
}
@@ -433,19 +530,134 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
if (insideValue.isLeft()) {
artifactDefinition = insideValue.left().value();
} else {
- artifactDefinition = insideValue.right().value().getImplementation();
+ artifactDefinition = insideValue.right().value().getImplementationArtifact();
}
- // for tosca artifacts generated on download without saving
- if (artifactDefinition.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && artifactDefinition.getPayloadData() != null) {
+ // 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);
}
- private Either<ArtifactDefinition, ResponseFormat> validateArtifact(String componentId, ComponentTypeEnum componentType, String artifactId, org.openecomp.sdc.be.model.Component component, AuditingActionEnum auditingAction, String parentId) {
+ 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 = artifactOperation.getArtifactById(artifactId, false);
+ 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, "");
@@ -484,7 +696,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return Either.left(artifactResult.left().value());
}
- private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleCreate(String parentId, ArtifactDefinition artifactInfo, ArtifactOperation operation, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType,
+ private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleCreate(String parentId, 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;
@@ -495,8 +707,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return Either.right(payloadEither.right().value());
}
byte[] decodedPayload = payloadEither.left().value();
- NodeTypeEnum parentType = convertParentType(componentType);
- // lock resource
+ convertParentType(componentType);
if (shouldLock) {
Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Upload Artifact - lock ");
@@ -522,11 +733,12 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
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) {
- NodeTypeEnum parentType = convertParentType(componentType);
+ 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());
@@ -545,7 +757,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
}
- private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdate(String parentId, ArtifactDefinition artifactInfo, ArtifactOperation operation, AuditingActionEnum auditingAction, String artifactId, User user,
+ 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);
@@ -558,7 +770,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return lockComponentAndUpdateArtifact(parentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, decodedPayload, interfaceType, operationName, shouldLock, inTransaction);
}
- private Either<byte[], ResponseFormat> validateInput(String parentId, ArtifactDefinition artifactInfo, ArtifactOperation operation, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
+ private Either<byte[], ResponseFormat> validateInput(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 inTransaction) {
// Md5 validations
Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
@@ -688,7 +900,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return sb.toString();
}
- private Either<Boolean, ResponseFormat> validateMd5(String origMd5, String originData, byte[] payload, ArtifactOperation operation) {
+ private Either<Boolean, ResponseFormat> validateMd5(String origMd5, String originData, byte[] payload, ArtifactOperationInfo operation) {
if (origMd5 != null) {
String encodeBase64Str = GeneralUtility.calculateMD5ByString(originData);
@@ -698,7 +910,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5));
}
} else {
- if (operation == ArtifactOperation.Create) {
+ if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) {
log.debug("Missing md5 header during artifact create");
return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5));
}
@@ -711,14 +923,18 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return Either.left(true);
}
- private Either<ArtifactDefinition, ResponseFormat> validateInput(String parentId, ArtifactDefinition artifactInfo, ArtifactOperation operation, String artifactId, User user, String interfaceName, String operationName,
+ private Either<ArtifactDefinition, ResponseFormat> validateInput(String parentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, String artifactId, User user, String interfaceName, String operationName,
ComponentTypeEnum componentType, Component parentComponent, boolean inTransaction) {
+ 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());
}
- Either<ArtifactDefinition, ResponseFormat> artifactById = fetchCurrentArtifact(operation, artifactId);
+ Either<ArtifactDefinition, ResponseFormat> artifactById = findArtifactOnParentComponent(parentComponent, parentId, operation, artifactId);
if (artifactById.isRight()) {
return Either.right(artifactById.right().value());
}
@@ -734,7 +950,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
// This is a patch to block possibility of updating service api fields
// through other artifacts flow
- if (!operation.equals(ArtifactOperation.Create)) {
+ if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.Create) {
checkAndSetUnUpdatableFields(user, artifactInfo, currentArtifactInfo, (operationName != null ? ArtifactGroupTypeEnum.LIFE_CYCLE : ArtifactGroupTypeEnum.INFORMATIONAL));
} else {
checkCreateFields(user, artifactInfo, (operationName != null ? ArtifactGroupTypeEnum.LIFE_CYCLE : ArtifactGroupTypeEnum.INFORMATIONAL));
@@ -746,7 +962,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
// artifactGroupType is not allowed to be updated
- if (!operation.equals(ArtifactOperation.Create)) {
+ if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.Create) {
Either<ArtifactDefinition, ResponseFormat> validateGroupType = validateOrSetArtifactGroupType(artifactInfo, currentArtifactInfo);
if (validateGroupType.isRight()) {
return Either.right(validateGroupType.right().value());
@@ -756,7 +972,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
NodeTypeEnum parentType = convertParentType(componentType);
// TODO TEMP !!!
- boolean isCreate = operation.equals(ArtifactOperation.Create);
+ boolean isCreate = operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create;
if (isDeploymentArtifact(artifactInfo)) {
Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parentComponent, parentId, user.getUserId(), isCreate, artifactInfo, currentArtifactInfo, parentType);
@@ -764,7 +980,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return Either.right(deploymentValidationResult.right().value());
}
} else {
- artifactInfo.setTimeout(NON_HEAT_TIMEOUT);
+ artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
/*
* if (informationDeployedArtifactsBusinessLogic. isInformationDeployedArtifact(artifactInfo)) { Either<Boolean, ResponseFormat> validationResult = informationDeployedArtifactsBusinessLogic.validateArtifact( isCreate, artifactInfo,
@@ -817,6 +1033,66 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return Either.left(artifactInfo);
}
+ private Either<ArtifactDefinition, ResponseFormat> findArtifactOnParentComponent(Component parentComponent, String parentId, ArtifactOperationInfo operation, String artifactId) {
+
+ Either<ArtifactDefinition, ResponseFormat> result = null;
+ ArtifactDefinition foundArtifact = null;
+ if (StringUtils.isNotEmpty(artifactId)) {
+ if (parentComponent.getUniqueId().equals(parentId)) {
+ if (parentComponent.getDeploymentArtifacts() != null) {
+ foundArtifact = parentComponent.getDeploymentArtifacts().values().stream().filter(e -> e.getUniqueId().equals(artifactId)).findFirst().orElse(null);
+ }
+ if (foundArtifact == null && parentComponent.getArtifacts() != null) {
+ foundArtifact = parentComponent.getArtifacts().values().stream().filter(e -> e.getUniqueId().equals(artifactId)).findFirst().orElse(null);
+ }
+ } else {
+ ComponentInstance instance = findComponentInstance(parentId, parentComponent);
+ if (instance.getDeploymentArtifacts() != null) {
+ foundArtifact = instance.getDeploymentArtifacts().values().stream().filter(e -> e.getUniqueId().equals(artifactId)).findFirst().orElse(null);
+ }
+ if (foundArtifact == null && instance.getArtifacts() != null) {
+ foundArtifact = instance.getArtifacts().values().stream().filter(e -> e.getUniqueId().equals(artifactId)).findFirst().orElse(null);
+ }
+ }
+ }
+ if (foundArtifact != null && operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) {
+ log.debug("Artifact {} already exist", artifactId);
+ result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, foundArtifact.getArtifactLabel()));
+ }
+ if (foundArtifact == null && operation.getArtifactOperationEnum() != ArtifactOperationEnum.Create) {
+ 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 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;
@@ -829,128 +1105,303 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
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);
- // lock resource
- 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);
- return Either.right(lockComponent.right().value());
- }
- }
Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
- Either<ArtifactDefinition, Operation> insideEither = null;
- StorageOperationStatus error = null;
- boolean isLeft = false;
- ArtifactDefinition artifactDefinition = null;
- Integer artifactParentsCount = 1;
+ 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 (interfaceType != null && operationName != null) {
- log.debug("Try to delete inteface lifecycle artifact {}", artifactId);
-
- Either<Operation, StorageOperationStatus> result = interfaceLifecycleOperation.deleteInterfaceOperation(parentId, interfaceType, UniqueIdBuilder.buildOperationByInterfaceUniqueId(parentId, interfaceType, operationName),
- inTransaction);
- isLeft = result.isLeft();
- if (isLeft) {
- artifactDefinition = result.left().value().getImplementation();
- insideEither = Either.right(result.left().value());
+ 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());
}
- } else {
- log.debug("Try to delete artifact, get parents {}", artifactId);
-
- Either<Integer, StorageOperationStatus> parentsOfArtifact = artifactOperation.getParentsOfArtifact(artifactId, parentType);
- if (parentsOfArtifact.isRight()) {
- log.debug("Failed to delete entry on graph for artifact {}", artifactId);
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(parentsOfArtifact.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 {
-
- artifactParentsCount = parentsOfArtifact.left().value();
- log.debug("Number of parents nodes on graph for artifact {} is {}", artifactId, artifactParentsCount);
-
- Either<ArtifactDefinition, StorageOperationStatus> result = artifactOperation.removeArifactFromResource(parentId, artifactId, parentType, false, true);
- isLeft = result.isLeft();
- if (isLeft) {
- log.debug("Artifact removed from graph {}", artifactId);
-
- artifactDefinition = result.left().value();
- insideEither = Either.left(result.left().value());
- } else {
- error = result.right().value();
- }
+ foundArtifact = getArtifactRes.left().value().getLeft();
+ esId = foundArtifact.getEsId();
}
}
-
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
- if (isLeft) {
- StorageOperationStatus deleteIfNotOnGraph = StorageOperationStatus.OK;
- if (artifactParentsCount < 2) {
- log.debug("Number of parent nodes is 1. Need to delete from ES {}", artifactId);
- deleteIfNotOnGraph = deleteIfNotOnGraph(artifactId, artifactDefinition.getEsId(), true);
+ 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);
}
- if (deleteIfNotOnGraph.equals(StorageOperationStatus.OK)) {
- if (artifactDefinition.getMandatory() || artifactDefinition.getServiceApi()) {
- log.debug("Artifact is mandatory or service API. Clean all fields for {}", artifactId);
- artifactDefinition.setEsId("");
- artifactDefinition.setArtifactName("");
- artifactDefinition.setDescription("");
- artifactDefinition.setApiUrl("");
- artifactDefinition.setArtifactChecksum("");
- setDefaultArtifactTimeout(artifactDefinition.getArtifactGroupType(), artifactDefinition);
- artifactDefinition.setArtifactUUID("");
- long time = System.currentTimeMillis();
- artifactDefinition.setPayloadUpdateDate(time);
- artifactDefinition.setHeatParameters(null);
- artifactDefinition.setHeatParamsUpdateDate(null);
- Either<ArtifactDefinition, StorageOperationStatus> resStatus = null;
- if (artifactParentsCount < 2) {
- log.debug("Only one parent , clean existing placeholder for {}", artifactId);
- resStatus = artifactOperation.updateArifactOnResource(artifactDefinition, parentId, artifactId, parentType, true);
- } else {
- log.debug("more than one parent , create new placeholder for {}", artifactId);
- artifactDefinition.setUniqueId(null);
- resStatus = artifactOperation.addArifactToComponent(artifactDefinition, parentId, parentType, true, true);
- }
- if (resStatus.isRight()) {
- log.debug("Failed to clean placeholder for {}", artifactId);
- responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(resStatus.right().value()), artifactDefinition.getArtifactDisplayName());
- resultOp = Either.right(responseFormat);
- } else {
- log.debug("Placeholder was cleaned for {}", artifactId);
+ }
+ if (resultOp == null) {
+ 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();
+ }
+ }
- ArtifactDefinition artifactUfterChange = resStatus.left().value();
+ if (resultOp == null && (!needCloneRes.left().value() && !isDuplicated)) {
+ 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) {
- insideEither = Either.left(artifactUfterChange);
- resultOp = Either.left(insideEither);
- }
- } else {
- log.debug("Artifact isn't mandatory/service API. Removed. {}", artifactId);
- resultOp = Either.left(insideEither);
+ 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);
}
-
- } else {
- log.debug("failed to delete artifact from ES {} status {}", artifactId, deleteIfNotOnGraph);
- responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(deleteIfNotOnGraph), artifactDefinition.getArtifactDisplayName());
+ }
+ }
+ 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);
}
- } else {
- log.debug("Failed to delete entry on graph for artifact {}", artifactId);
- responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(error), "");
- resultOp = Either.right(responseFormat);
}
- handleAuditing(auditingAction, parent, parentId, user, artifactDefinition, null, artifactId, responseFormat, componentType, null);
+ 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 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.getArtifacts().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.getArtifacts().remove(artifactId);
+ isUpdated = true;
+ }
+ if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid().contains(foundArtifact.getArtifactUUID())) {
+ groupInstance.getArtifacts().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);
+ } 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("");
+ fetchedArtifact.setArtifactName("");
+ fetchedArtifact.setDescription("");
+ fetchedArtifact.setApiUrl("");
+ fetchedArtifact.setArtifactChecksum("");
+ nodeTemplateOperation.setDefaultArtifactTimeout(fetchedArtifact.getArtifactGroupType(), fetchedArtifact);
+ fetchedArtifact.setArtifactUUID("");
+ 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 = artifactOperation.getArtifactById(artifactId, false);
+ 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());
@@ -971,16 +1422,15 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return Either.left(insideEither);
}
- private Either<ArtifactDefinition, ResponseFormat> fetchCurrentArtifact(ArtifactOperation operation, String artifactId) {
- Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactOperation.getArtifactById(artifactId, true);
- if (!operation.equals(ArtifactOperation.Create) && artifactById.isRight()) {
+ private Either<ArtifactDefinition, ResponseFormat> fetchCurrentArtifact(String parentId, ArtifactOperationInfo operation, String artifactId) {
+ Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(parentId, artifactId);
+ if (!(operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) && 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 (operation.equals(ArtifactOperation.Create) && artifactById.isLeft()) {
+ if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create && artifactById.isLeft()) {
log.debug("Artifact {} already exist", artifactId);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactById.left().value().getArtifactLabel()));
}
@@ -992,17 +1442,16 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return Either.left(currentArtifactInfo);
}
- private Either<ActionStatus, ResponseFormat> handleArtifactLabel(String componentId, ArtifactOperation operation, String artifactId, ArtifactDefinition artifactInfo, String interfaceName, String operationName,
+ private Either<ActionStatus, ResponseFormat> handleArtifactLabel(String componentId, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String interfaceName, String operationName,
ArtifactDefinition currentArtifactInfo, ComponentTypeEnum componentType, boolean inTransaction) {
String artifactLabel = artifactInfo.getArtifactLabel();
if (operationName == null && (artifactInfo.getArtifactLabel() == null || artifactInfo.getArtifactLabel().isEmpty())) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeMissingArtifactInformationError, "Artifact Update / Upload", "artifactLabel");
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 (operation.equals(ArtifactOperation.Create) && !artifactInfo.getMandatory()) {
+ if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create && !artifactInfo.getMandatory()) {
if (operationName != null) {
if (artifactInfo.getArtifactLabel() != null && !operationName.equals(artifactInfo.getArtifactLabel())) {
@@ -1016,6 +1465,10 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
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)) {
@@ -1033,7 +1486,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
log.debug("Invalid lenght form Artifact label : {}", artifactLabel);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_LABEL, String.valueOf(ValidationUtils.ARTIFACT_LABEL_LENGTH)));
}
- if (!validateLabelUniqueness(componentId, artifactLabel, componentType, inTransaction)) {
+ if (!validateLabelUniqueness(componentId, artifactLabel, componentType)) {
log.debug("Non unique Artifact label : {}", artifactLabel);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactLabel));
}
@@ -1041,21 +1494,19 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
artifactInfo.setArtifactLabel(artifactLabel);
if (currentArtifactInfo != null && !currentArtifactInfo.getArtifactLabel().equals(artifactInfo.getArtifactLabel())) {
- log.info("Logical artifact's name cannot be changed {}", artifactId);
+ log.info("Logical artifact's name cannot be changed {}", artifactId);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED));
}
return Either.left(ActionStatus.OK);
}
- private boolean validateLabelUniqueness(String parentId, String artifactLabel, ComponentTypeEnum componentType, boolean inTransaction) {
+ private boolean validateLabelUniqueness(String parentId, String artifactLabel, ComponentTypeEnum componentType) {
boolean isUnique = true;
- NodeTypeEnum parentType;
if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
- parentType = NodeTypeEnum.Resource;
} else {
- parentType = NodeTypeEnum.Service;
}
- Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts = artifactOperation.getArtifacts(parentId, parentType, inTransaction);
+ // Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts = artifactOperation.getArtifacts(parentId, parentType, inTransaction);
+ Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts = artifactToscaOperation.getArtifacts(parentId);
if (artifacts.isLeft()) {
for (String label : artifacts.left().value().keySet()) {
if (label.equals(artifactLabel)) {
@@ -1065,10 +1516,10 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
}
if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
- Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation.getAllInterfacesOfResource(parentId, true, inTransaction);
+ Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation.getAllInterfacesOfResource(parentId, true, true);
if (allInterfacesOfResource.isLeft()) {
for (InterfaceDefinition interace : allInterfacesOfResource.left().value().values()) {
- for (Operation operation : interace.getOperations().values()) {
+ for (Operation operation : interace.getOperationsMap().values()) {
if (operation.getImplementation() != null && operation.getImplementation().getArtifactLabel().equals(artifactLabel)) {
isUnique = false;
break;
@@ -1088,9 +1539,14 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
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().processEcompError(EcompErrorName.BeDaoSystemError, "Upload Artifact");
BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact");
log.debug("Failed to create artifact object for ES.");
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
@@ -1104,7 +1560,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
boolean isLeft = false;
String artifactUniqueId = null;
- ArtifactDefinition artifactDefinition = null;
StorageOperationStatus error = null;
if (interfaceType != null && operationName != null) {
// lifecycle artifact
@@ -1115,7 +1570,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
isLeft = result.isLeft();
if (isLeft) {
artifactUniqueId = result.left().value().getImplementation().getUniqueId();
- artifactDefinition = result.left().value().getImplementation();
+ result.left().value().getImplementation();
insideEither = Either.right(result.left().value());
resultOp = Either.left(insideEither);
@@ -1124,17 +1579,23 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
} else {
// information/deployment/api aritfacts
- log.debug("Try to create entry on graph");
+ log.trace("Try to create entry on graph");
NodeTypeEnum nodeType = convertParentType(componentTypeEnum);
- Either<ArtifactDefinition, StorageOperationStatus> result = artifactOperation.addArifactToComponent(artifactInfo, parentId, nodeType, true, true);
+ Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.addArifactToComponent(artifactInfo, parent.getUniqueId(), nodeType, true, instanceId);
isLeft = result.isLeft();
if (isLeft) {
artifactUniqueId = result.left().value().getUniqueId();
- artifactDefinition = result.left().value();
+ 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();
}
@@ -1147,14 +1608,13 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
log.debug("Artifact saved into ES - {}", artifactUniqueId);
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
- handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, artifactUniqueId, artifactUniqueId, responseFormat, componentTypeEnum, null);
+ handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, artifactUniqueId, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
return resultOp;
} else {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "Upload Artifact");
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, null);
+ handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
resultOp = Either.right(responseFormat);
return resultOp;
@@ -1162,13 +1622,21 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
} 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, null);
+ 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);
@@ -1178,7 +1646,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
- Map<String, DeploymentArtifactTypeConfig> resourceDeploymentArtifacts = fillDeploymentArtifactTypeConf(parentType);
+ Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts = fillDeploymentArtifactTypeConf(parentType);
if (responseWrapper.isEmpty()) {
validateDeploymentArtifactConf(artifactInfo, responseWrapper, artifactType, resourceDeploymentArtifacts);
@@ -1199,7 +1667,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
// if (parentComponent instanceof Resource) {
Resource resource = (Resource) parentComponent;
ResourceTypeEnum resourceType = resource.getResourceType();
- DeploymentArtifactTypeConfig config = resourceDeploymentArtifacts.get(artifactType.getType());
+ ArtifactTypeConfig config = resourceDeploymentArtifacts.get(artifactType.getType());
if (config == null) {
responseWrapper.setInnerElement(ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType()));
} else {
@@ -1232,7 +1700,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
case HEAT_ENV: {
result = validateHeatEnvDeploymentArtifact(parentComponent, parentId, userId, isCreate, artifactInfo, parentType);
- artifactInfo.setTimeout(NON_HEAT_TIMEOUT);
+ artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
break;
}
case DCAE_INVENTORY_TOSCA:
@@ -1244,7 +1712,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
case DCAE_INVENTORY_EVENT:
// No specific validation
default: {
- artifactInfo.setTimeout(NON_HEAT_TIMEOUT);
+ artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
}
}
@@ -1256,7 +1724,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return result;
}
- private void validateDeploymentArtifactConf(ArtifactDefinition artifactInfo, Wrapper<ResponseFormat> responseWrapper, ArtifactTypeEnum artifactType, Map<String, DeploymentArtifactTypeConfig> resourceDeploymentArtifacts) {
+ 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);
@@ -1264,8 +1732,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
}
- private Map<String, DeploymentArtifactTypeConfig> fillDeploymentArtifactTypeConf(NodeTypeEnum parentType) {
- Map<String, DeploymentArtifactTypeConfig> resourceDeploymentArtifacts = null;
+ 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)) {
@@ -1279,14 +1747,14 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
public void validateArtifactTypeExists(Wrapper<ResponseFormat> responseWrapper, ArtifactDefinition artifactInfo) {
ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
if (artifactType == null) {
- ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.GENERAL_ERROR);
+ ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType());
responseWrapper.setInnerElement(responseFormat);
log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType());
}
}
- private DeploymentArtifactTypeConfig getDeploymentArtifactTypeConfig(NodeTypeEnum parentType, ArtifactTypeEnum artifactType) {
- DeploymentArtifactTypeConfig retConfig = null;
+ 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);
@@ -1301,14 +1769,14 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
private Either<Boolean, ResponseFormat> extractHeatParameters(ArtifactDefinition artifactInfo) {
// extract heat parameters
if (artifactInfo.getPayloadData() != null) {
- String heatDecodedPayload = GeneralUtility.isBase64Encoded(artifactInfo.getPayloadData()) ? new String(Base64.decodeBase64(artifactInfo.getPayloadData())) : new String(artifactInfo.getPayloadData());
+ 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.setHeatParameters(heatParameters.left().value());
+ artifactInfo.setListHeatParameters(heatParameters.left().value());
}
}
return Either.left(true);
@@ -1319,7 +1787,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
public void validateFileExtension(Wrapper<ResponseFormat> responseWrapper, IDeploymentArtifactTypeConfigGetter deploymentConfigGetter, ArtifactDefinition artifactInfo, NodeTypeEnum parentType, ArtifactTypeEnum artifactType) {
String fileType = artifactType.getType();
List<String> acceptedTypes = null;
- DeploymentArtifactTypeConfig deploymentAcceptedTypes = deploymentConfigGetter.getDeploymentArtifactConfig();
+ 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));
@@ -1365,13 +1833,13 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
if (errorWrapper.isEmpty()) {
// Validate Heat Exist
- validateHeatExist(artifactInfo.getUniqueId(), errorWrapper, heatMDWrapper, getDeploymentArtifacts(parentComponent, parentType, parentId));
+ 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() && isCreate) {
+ // // Validate Only Single HeatEnv Artifact
+ // validateSingleArtifactType(errorWrapper, ArtifactTypeEnum.HEAT_ENV, parentComponent, parentType, parentId);
+ // }
if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) {
fillArtifactPayloadValidation(errorWrapper, payloadWrapper, heatMDWrapper.getInnerElement());
@@ -1406,13 +1874,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
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());
- // Either<ESArtifactData, ResourceUploadStatus> eitherArtifactData =
- // esCatalogDao.getArtifact(artifactMD.getEsId());
if (eitherArtifactData.isLeft()) {
byte[] data = eitherArtifactData.left().value().getDataAsArray();
- if (!GeneralUtility.isBase64Encoded(data)) {
- data = Base64.encodeBase64(data);
- }
+ data = Base64.encodeBase64(data);
payloadWrapper.setInnerElement(data);
} else {
StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(eitherArtifactData.right().value());
@@ -1425,11 +1889,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
@SuppressWarnings("unchecked")
private void validateEnvVsHeat(Wrapper<ResponseFormat> errorWrapper, ArtifactDefinition envArtifact, ArtifactDefinition heatArtifact, byte[] heatPayloadData) {
-
- String envPayload = (GeneralUtility.isBase64Encoded(envArtifact.getPayloadData())) ? new String(Base64.decodeBase64(envArtifact.getPayloadData())) : new String(envArtifact.getPayloadData());
+ String envPayload = new String(Base64.decodeBase64(envArtifact.getPayloadData()));
Map<String, Object> heatEnvToscaJson = (Map<String, Object>) new Yaml().load(envPayload);
-
- String heatDecodedPayload = (GeneralUtility.isBase64Encoded(heatPayloadData)) ? new String(Base64.decodeBase64(heatPayloadData)) : new String(heatPayloadData);
+ 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);
@@ -1455,7 +1917,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
private void validateValidYaml(Wrapper<ResponseFormat> errorWrapper, ArtifactDefinition artifactInfo) {
YamlToObjectConverter yamlConvertor = new YamlToObjectConverter();
- boolean isYamlValid = yamlConvertor.isValidYaml(artifactInfo.getPayloadData());
+ boolean isYamlValid = yamlConvertor.isValidYamlEncoded64(artifactInfo.getPayloadData());
if (!isYamlValid) {
ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.INVALID_YAML, artifactInfo.getArtifactType());
errorWrapper.setInnerElement(responseFormat);
@@ -1463,12 +1925,14 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
}
+ @SuppressWarnings("restriction")
public boolean isValidXml(byte[] xmlToParse) {
XMLReader parser = new SAXParser();
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;
@@ -1479,6 +1943,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
try {
gson.fromJson(parsed, Object.class);
} catch (Exception e) {
+ log.debug("Json is invalid : {}", e.getMessage(), e);
return false;
}
return true;
@@ -1531,31 +1996,40 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
}
- private void validateHeatExist(String heatEnvId, Wrapper<ResponseFormat> errorWrapper, Wrapper<ArtifactDefinition> heatArtifactMDWrapper, Collection<ArtifactDefinition> parentDeploymentArtifacts) {
- boolean heatFound = false;
- Either<ArtifactDefinition, StorageOperationStatus> res = artifactOperation.getHeatArtifactByHeatEnvId(heatEnvId, true);
+ 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();
- 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.");
- }
+ 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.");
+ // }
}
@@ -1563,7 +2037,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
log.trace("Started HEAT pre-payload validation for artifact {}", artifactInfo.getArtifactLabel());
// timeout > 0 for HEAT artifacts
Integer timeout = artifactInfo.getTimeout();
- Integer defaultTimeout = (isCreate) ? defaultHeatTimeout : currentArtifact.getTimeout();
+ Integer defaultTimeout = (isCreate) ? NodeTemplateOperation.getDefaultHeatTimeout() : currentArtifact.getTimeout();
if (timeout == null) {
artifactInfo.setTimeout(defaultTimeout);
// HEAT artifact but timeout is invalid
@@ -1594,7 +2068,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
private Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers(ArtifactDefinition artifactInfo, String artifactType) {
if (artifactInfo.getHeatParameters() != null) {
- for (HeatParameterDefinition heatParam : artifactInfo.getHeatParameters()) {
+ for (HeatParameterDefinition heatParam : artifactInfo.getListHeatParameters()) {
String parameterType = heatParam.getType();
HeatParameterType heatParameterType = HeatParameterType.isValidType(parameterType);
String artifactTypeStr = artifactType != null ? artifactType : ArtifactTypeEnum.HEAT.getType();
@@ -1605,7 +2079,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
StorageOperationStatus validateAndUpdateProperty = heatParametersOperation.validateAndUpdateProperty(heatParam);
if (validateAndUpdateProperty != StorageOperationStatus.OK) {
- log.debug("Heat parameter {} is invalid. Status is: {}", heatParam.getName(), validateAndUpdateProperty);
+ 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);
@@ -1617,16 +2091,18 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
public List<ArtifactDefinition> getDeploymentArtifacts(Component parentComponent, NodeTypeEnum parentType, String ciId) {
List<ArtifactDefinition> deploymentArtifacts = new ArrayList<>();
- if (parentComponent.getDeploymentArtifacts() != null && ciId != null) {
- if (NodeTypeEnum.ResourceInstance == parentType) {
+ 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();
- deploymentArtifacts.addAll(ri.getDeploymentArtifacts().values());
- } else {
- deploymentArtifacts.addAll(parentComponent.getDeploymentArtifacts().values());
+ if(ri.getDeploymentArtifacts() != null){
+ deploymentArtifacts.addAll(ri.getDeploymentArtifacts().values());
+ }
+ } else if(parentComponent.getDeploymentArtifacts() !=null){
+ deploymentArtifacts.addAll(parentComponent.getDeploymentArtifacts().values());
}
}
return deploymentArtifacts;
@@ -1691,105 +2167,14 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
- private Either<ArtifactDefinition, ResponseFormat> fetchCurrentArtifact(boolean isCreate, String artifactId) {
- Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactOperation.getArtifactById(artifactId, true);
- 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 Either<ActionStatus, ResponseFormat> handleArtifactLabel(String resourceId, boolean isCreate, String artifactId, ArtifactDefinition artifactInfo, String interfaceName, String operationName, ArtifactDefinition currentArtifactInfo,
- NodeTypeEnum parentType) {
- String artifactLabel = artifactInfo.getArtifactLabel();
-
- if (operationName == null && (artifactInfo.getArtifactLabel() == null || artifactInfo.getArtifactLabel().isEmpty())) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeMissingArtifactInformationError, "Artifact Update / Upload", "artifactLabel");
- BeEcompErrorManager.getInstance().logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
- log.debug("missing artifact logical name for component {}", resourceId);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
- }
- if (isCreate && !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 = ValidationUtils.cleanArtifactDisplayName(artifactLabel);
- 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 {}", resourceId);
- 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(resourceId, artifactLabel, parentType)) {
- log.debug("Non unique Artifact label : {}", artifactLabel);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactLabel));
- }
- }
- artifactInfo.setArtifactLabel(artifactLabel);
-
- if (currentArtifactInfo != null && !currentArtifactInfo.getArtifactLabel().equals(artifactInfo.getArtifactLabel())) {
- log.info("Logical artifact's name cannot be changed {}", artifactId);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED));
- }
- return Either.left(ActionStatus.OK);
- }
-
- private boolean validateLabelUniqueness(String parentId, String artifactLabel, NodeTypeEnum parentType) {
- boolean isUnique = true;
- Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts = artifactOperation.getArtifacts(parentId, parentType, true);
- if (artifacts.isLeft()) {
- for (String label : artifacts.left().value().keySet()) {
- if (label.equals(artifactLabel)) {
- isUnique = false;
- break;
- }
- }
- }
- if (parentType.equals(NodeTypeEnum.Resource)) {
- Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation.getAllInterfacesOfResource(parentId, true);
- if (allInterfacesOfResource.isLeft()) {
- for (InterfaceDefinition interace : allInterfacesOfResource.left().value().values()) {
- for (Operation operation : interace.getOperations().values()) {
- if (operation.getImplementation() != null && operation.getImplementation().getArtifactLabel().equals(artifactLabel)) {
- isUnique = false;
- break;
- }
- }
- }
- }
- }
- return isUnique;
- }
+ /*
+ * 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;
@@ -1812,7 +2197,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
private Either<ActionStatus, ResponseFormat> validateArtifactType(String userId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
if (artifactInfo.getArtifactType() == null || artifactInfo.getArtifactType().isEmpty()) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeMissingArtifactInformationError, "Artifact Upload / Update");
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));
@@ -1829,7 +2213,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
allArtifactTypes = elementOperation.getAllArtifactTypes();
}
if (allArtifactTypes.isRight()) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInvalidConfigurationError, "Artifact Upload / Update", "artifactTypes", allArtifactTypes.right().value().name());
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));
@@ -1844,7 +2227,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
if (!artifactTypeExist) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInvalidTypeError, "Artifact Upload / Delete / Update - Not supported artifact type", artifactInfo.getArtifactType(), "Artifact " + artifactInfo.getArtifactName());
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()));
@@ -1855,7 +2237,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
private Either<List<ArtifactType>, ActionStatus> getDeploymentArtifactTypes(String userId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
- Map<String, DeploymentArtifactTypeConfig> deploymentArtifacts = null;
+ Map<String, ArtifactTypeConfig> deploymentArtifacts = null;
List<ArtifactType> artifactTypes = new ArrayList<ArtifactType>();
if (parentType.equals(NodeTypeEnum.Service)) {
@@ -2016,7 +2398,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
artifactInfo.setArtifactUUID(currentArtifact.getArtifactUUID());
if ((artifactInfo.getHeatParameters() != null) && (currentArtifact.getHeatParameters() != null) && !artifactInfo.getHeatParameters().isEmpty() && !currentArtifact.getHeatParameters().isEmpty()) {
- checkAndSetUnupdatableHeatParams(artifactInfo.getHeatParameters(), currentArtifact.getHeatParameters());
+ checkAndSetUnupdatableHeatParams(artifactInfo.getListHeatParameters(), currentArtifact.getListHeatParameters());
}
}
@@ -2110,7 +2492,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
Either<ArtifactDefinition, Operation> insideEither = null;
if (artifactData == null) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "Update Artifact");
BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact");
log.debug("Failed to create artifact object for ES.");
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
@@ -2118,111 +2499,96 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
resultOp = Either.right(responseFormat);
return resultOp;
}
- log.debug("Try to update entry on graph");
+ log.trace("Try to update entry on graph");
String artifactUniqueId = null;
- ArtifactDefinition artifactDefinition = 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);
+ /*
+ * 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();
- isLeft = result.isLeft();
- if (isLeft) {
- artifactUniqueId = result.left().value().getUniqueId();
- artifactDefinition = result.left().value().getImplementation();
+ NodeTypeEnum convertParentType = convertParentType(componentType);
- insideEither = Either.right(result.left().value());
- resultOp = Either.left(insideEither);
+ 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 {
- error = result.right().value();
+ if (artifactDefinition.getEsId() == null) {
+ artifactDefinition.setEsId(artifactDefinition.getUniqueId());
+ artifactData.setId(artifactDefinition.getUniqueId());
+ }
}
- } else {
- NodeTypeEnum convertParentType = convertParentType(componentType);
- Either<ArtifactDefinition, StorageOperationStatus> result = artifactOperation.updateArifactOnResource(artifactInfo, parentId, artifactId, convertParentType, true);
+ 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)) { 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) {
- log.debug("Enty on graph is updated. Update artifact in ES");
- boolean res;
- // Changing previous and current artifactId for auditing
- prevArtifactId = currArtifactId;
- currArtifactId = artifactDefinition.getUniqueId();
+ if (isLeft) {
- if (!artifactDefinition.getUniqueId().equals(artifactId)) {
- // different ids ==> artifact node was cloned .
- // if no data in request get from ES
- if (decodedPayload == null) {
- if (!artifactDefinition.getMandatory() || artifactDefinition.getEsId() != null) {
- Either<ESArtifactData, CassandraOperationStatus> artifactFromCassandra = artifactCassandraDao.getArtifact(artifactId);
- // Either<ESArtifactData, ResourceUploadStatus>
- // artifactfromES = daoUploader.getArtifact(artifactId);
- if (artifactFromCassandra.isRight()) {
- log.debug("Failed to get artifact data from ES for artifact id {}", artifactId);
- StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactFromCassandra.right().value());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus));
- 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(artifactDefinition.getUniqueId());
// 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);
- // set on graph object id of artifact in ES!
- if (res) {
- artifactInfo.setEsId(artifactData.getId());
- Either<ArtifactDefinition, StorageOperationStatus> updateArifactRes = artifactOperation.updateArifactDefinition(artifactInfo, true);
- if (updateArifactRes.isRight()) {
- log.debug("Failed to update artifact on graph - {}", artifactId);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactRes.right().value()));
- handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
- resultOp = Either.right(responseFormat);
- return resultOp;
-
- } else {
- insideEither = Either.left(updateArifactRes.left().value());
- resultOp = Either.left(insideEither);
- }
- }
- }
- } else {
- res = true;
- if (artifactData.getData() != null) {
- // override artifact in ES
- res = saveArtifacts(artifactData, parentId, true);
- if (res && artifactDefinition.getMandatory()) {
- artifactInfo.setEsId(artifactData.getId());
- Either<ArtifactDefinition, StorageOperationStatus> updateArifactRes = artifactOperation.updateArifactDefinition(artifactInfo, true);
- if (updateArifactRes.isRight()) {
- log.debug("Failed to update artifact on graph - {}", artifactId);
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactRes.right().value()), artifactId);
- handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
- resultOp = Either.right(responseFormat);
- return resultOp;
- }
- }
}
}
+
if (res) {
log.debug("Artifact saved into ES - {}", artifactUniqueId);
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
@@ -2230,7 +2596,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
// resultOp = Either.left(result.left().value());
// return resultOp;
} else {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "Update Artifact");
BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact");
log.debug("Failed to save the artifact.");
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
@@ -2238,12 +2603,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
resultOp = Either.right(responseFormat);
// return resultOp;
}
- } else {
- log.debug("Failed to create entry on graph for artifact {}", artifactInfo.getArtifactDisplayName());
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(error), artifactInfo.getArtifactDisplayName());
- handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
- resultOp = Either.right(responseFormat);
- // return resultOp;
}
return resultOp;
@@ -2255,8 +2614,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
byte[] decodedPayload = null;
if (payload != null && payload.length != 0) {
-
- decodedPayload = Base64.decodeBase64(payload);
+ // 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);
@@ -2285,7 +2644,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
// else
// if(ArtifactTypeEnum.APPC_CONFIG.getType().equalsIgnoreCase(artifactType)
// || ){
- } else if (ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.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) {
@@ -2321,17 +2681,17 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return Either.left(decodedPayload);
}
- private Either<Boolean, ResponseFormat> validateDeploymentHeatPayload(byte[] payload, String artifactType) {
+ private Either<Boolean, ResponseFormat> validateDeploymentHeatPayload(byte[] decodedPayload, String artifactType) {
// Basic YAML validation
YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
- if (!yamlToObjectConverter.isValidYaml(payload)) {
+ 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(payload, DeploymentArtifactHeatConfiguration.class);
+ DeploymentArtifactHeatConfiguration heatConfiguration = yamlToObjectConverter.convert(decodedPayload, DeploymentArtifactHeatConfiguration.class);
if (heatConfiguration == null || heatConfiguration.getHeat_template_version() == null || heatConfiguration.getResources() == null) {
log.debug("HEAT doesn't contain required \"heat_template_version\" and \"resources\" sections ");
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactType);
@@ -2376,17 +2736,17 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
public void handleTransaction(Either<Operation, ResponseFormat> opState) {
if (opState == null || opState.isRight()) {
- titanGenericDao.rollback();
+ titanDao.rollback();
} else {
- titanGenericDao.commit();
+ titanDao.commit();
}
}
- public Either<Operation, ResponseFormat> deleteArtifactByInterface(String resourceId, String interfaceType, String operationName, String userId, String artifactId, ImmutablePair<User, Resource> userResourceAuditPair, boolean shouldLock,
+ 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(userId);
- Either<Resource, StorageOperationStatus> parent = resourceOperation.getResource(resourceId);
+ 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);
@@ -2438,26 +2798,26 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
public StorageOperationStatus deleteIfNotOnGraph(String artifactId, String artifactEsId, boolean deleteOnlyPayload) {
log.debug("deleteIfNotOnGraph: delete only payload = {}", deleteOnlyPayload);
- Either<ArtifactData, TitanOperationStatus> checkArtifactNode = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef), artifactId, ArtifactData.class);
- if ((artifactEsId != null && !artifactEsId.isEmpty())) {
- boolean isNotExistOnGraph = checkArtifactNode.isRight() && checkArtifactNode.right().value().equals(TitanOperationStatus.NOT_FOUND);
-
- if ((isNotExistOnGraph) || (checkArtifactNode.left().value().getArtifactDataDefinition().getMandatory() && deleteOnlyPayload)
- || (ArtifactGroupTypeEnum.SERVICE_API.equals(checkArtifactNode.left().value().getArtifactDataDefinition().getArtifactGroupType()) && deleteOnlyPayload)) {
- // last one. need to delete in ES
- log.debug("Entry on graph is deleted. Delete artifact in ES for id = {}", artifactEsId);
- artifactCassandraDao.deleteArtifact(artifactEsId);
- return StorageOperationStatus.OK;
- // return
- // componentsUtils.getResponseFormatByResourceId(ActionStatus.OK,
- // resourceId);
-
- } else {
- log.debug("Entry on graph is deleted. Exist more connections on this artifact. Don't delete artifact in ES for id = {}", artifactEsId);
- return StorageOperationStatus.OK;
- }
-
- }
+ // Either<ArtifactData, TitanOperationStatus> checkArtifactNode = titanDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef), artifactId, ArtifactData.class);
+ // if ((artifactEsId != null && !artifactEsId.isEmpty())) {
+ // boolean isNotExistOnGraph = checkArtifactNode.isRight() && checkArtifactNode.right().value().equals(TitanOperationStatus.NOT_FOUND);
+ //
+ // if ((isNotExistOnGraph) || (checkArtifactNode.left().value().getArtifactDataDefinition().getMandatory() && deleteOnlyPayload)
+ // || (ArtifactGroupTypeEnum.SERVICE_API.equals(checkArtifactNode.left().value().getArtifactDataDefinition().getArtifactGroupType()) && deleteOnlyPayload)) {
+ // // last one. need to delete in ES
+ // log.debug("Entry on graph is deleted. Delete artifact in ES for id = {}", artifactEsId);
+ // artifactCassandraDao.deleteArtifact(artifactEsId);
+ // return StorageOperationStatus.OK;
+ // // return
+ // // componentsUtils.getResponseFormatByResourceId(ActionStatus.OK,
+ // // resourceId);
+ //
+ // } else {
+ // log.debug("Entry on graph is deleted. Exist more connections on this artifact. Don't delete artifact in ES for id = {}", artifactEsId);
+ // return StorageOperationStatus.OK;
+ // }
+ //
+ // }
return StorageOperationStatus.OK;
}
@@ -2594,7 +2954,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
private Either<Service, ResponseFormat> validateServiceNameAndVersion(String serviceName, String serviceVersion) {
- Either<List<Service>, StorageOperationStatus> serviceListBySystemName = serviceOperation.getServiceListBySystemName(serviceName, false);
+ 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));
@@ -2622,31 +2982,13 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
private Either<Resource, ResponseFormat> validateResourceNameAndVersion(String resourceName, String resourceVersion) {
- Either<List<Resource>, StorageOperationStatus> resourceListBySystemName = resourceOperation.getResourceListBySystemName(resourceName, false);
+
+ Either<Resource, StorageOperationStatus> resourceListBySystemName = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion, JsonParseFlagEnum.ParseMetadata);
if (resourceListBySystemName.isRight()) {
- log.debug("Couldn't fetch any resource with name {}", resourceName);
+ log.debug("Couldn't fetch any resource with name {} and version {}. ", resourceName, resourceVersion);
return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceListBySystemName.right().value()), resourceName));
}
- List<Resource> resourceList = resourceListBySystemName.left().value();
- if (resourceList == null || resourceList.isEmpty()) {
- log.debug("Couldn't fetch any resource with name {}", resourceName);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceName));
- }
-
- Resource foundResource = null;
- for (Resource resource : resourceList) {
- if (resource.getVersion().equals(resourceVersion)) {
- log.trace("Found resource with version {}", resourceVersion);
- foundResource = resource;
- break;
- }
- }
-
- if (foundResource == null) {
- log.debug("Couldn't find version {} for resource {}", resourceVersion, resourceName);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_VERSION_NOT_FOUND, ComponentTypeEnum.RESOURCE.getValue(), resourceVersion));
- }
- return Either.left(foundResource);
+ return Either.left(resourceListBySystemName.left().value());
}
public Either<byte[], ResponseFormat> downloadServiceArtifactByNames(String serviceName, String serviceVersion, String artifactName) {
@@ -2658,7 +3000,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
// Normalizing artifact name
- artifactName = ValidationUtils.normalizeFileName(artifactName);
+ final String normalizedArtifactName = ValidationUtils.normalizeFileName(artifactName);
// Service validation
Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
@@ -2668,41 +3010,44 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
String serviceId = validateServiceNameAndVersion.left().value().getUniqueId();
- // Looking for deployment artifacts
+ // Looking for deployment or tosca artifacts
Service service = validateServiceNameAndVersion.left().value();
- Map<String, ArtifactDefinition> artifacts = service.getDeploymentArtifacts();
- if (artifacts == null || artifacts.isEmpty()) {
- log.debug("Deployment artifacts of service {} are not found", serviceId);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
+
+ 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));
}
- ArtifactDefinition deploymentArtifact = null;
+ Optional<ArtifactDefinition> foundArtifactOptl = null;
- for (ArtifactDefinition artifactDefinition : artifacts.values()) {
- if (artifactDefinition.getArtifactName().equals(artifactName)) {
- log.debug("Found deployment artifact {}", artifactName);
- deploymentArtifact = artifactDefinition;
- }
+ if (!MapUtils.isEmpty(service.getDeploymentArtifacts())) {
+ foundArtifactOptl = service.getDeploymentArtifacts().values().stream()
+ // filters artifact by name
+ .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny();
}
-
- if (deploymentArtifact == null) {
- log.debug("No deployment artifact {} was found for service {}", artifactName, serviceId);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
+ 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(deploymentArtifact);
+ Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(foundArtifactOptl.get());
if (downloadArtifactEither.isRight()) {
- log.debug("Download artifact {} failed", artifactName);
+ log.debug("Download artifact {} failed", normalizedArtifactName);
return Either.right(downloadArtifactEither.right().value());
}
- log.trace("Download of service artifact succeeded, uniqueId {}", deploymentArtifact.getUniqueId());
+ 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 artifactUniqueId) {
+ public Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifact(String parentId, String artifactUniqueId) {
log.trace("Starting download of artifact, uniqueId {}", artifactUniqueId);
- Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactOperation.getArtifactById(artifactUniqueId, false);
+ 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());
@@ -2751,7 +3096,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
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().getOperations();
+ 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;
@@ -2800,6 +3145,17 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
}
}
+ 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;
}
@@ -2807,24 +3163,13 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
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) {
- NodeTypeEnum nodeType = componentType.getNodeType();
- if (containerComponentType != null && NodeTypeEnum.ResourceInstance == nodeType) {
- nodeType = (ComponentTypeEnum.findByParamName(containerComponentType)).getNodeType();
- }
- ComponentOperation componentOperation = getComponentOperation(nodeType);
+ ComponentTypeEnum componentForAudit = null == containerComponentType ? componentType : ComponentTypeEnum.findByParamName(containerComponentType);
+ componentForAudit.getNodeType();
- if (componentOperation == null) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
- log.debug("addArtifact - not supported component type {}", componentType);
- handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentType, null);
- return Either.right(responseFormat);
- }
- Either<? extends org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentResult = componentOperation.getComponent(componentId, inTransaction);
+ Either<? extends org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentResult = toscaOperationFacade.getToscaFullElement(componentId);
if (componentResult.isRight()) {
- ActionStatus status = (componentType.equals(ComponentTypeEnum.RESOURCE)) ? ActionStatus.RESOURCE_NOT_FOUND : ActionStatus.SERVICE_NOT_FOUND;
- ComponentTypeEnum componentForAudit = (componentType.equals(ComponentTypeEnum.RESOURCE)) ? ComponentTypeEnum.RESOURCE : ComponentTypeEnum.SERVICE;
-
+ 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);
@@ -2833,9 +3178,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
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, ArtifactOperation operation,
+ 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 != ArtifactOperation.Download) {
+ if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.Download && !operation.ignoreLifecycleState()) {
Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, userId);
if (canWork.isRight()) {
String uniqueId = component.getUniqueId();
@@ -2847,22 +3192,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return Either.left(true);
}
- private Either<Boolean, ResponseFormat> validateWorkOnResource(Resource resource, String userId, AuditingActionEnum auditingAction, User user, String artifactId, ArtifactOperation operation) {
- if (operation != ArtifactOperation.Download) {
- if (!ComponentValidationUtils.canWorkOnResource(resource, userId)) {
- String uniqueId = resource.getUniqueId();
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
- log.debug("Resource status isn't CHECKOUT or user isn't owner, resourceId {}", uniqueId);
- handleAuditing(auditingAction, resource, uniqueId, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE, null);
- return Either.right(responseFormat);
- }
- }
- return Either.left(true);
- }
+ private Either<Boolean, ResponseFormat> validateUserRole(User user, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, ArtifactOperationInfo operation) {
- private Either<Boolean, ResponseFormat> validateUserRole(User user, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, ArtifactOperation operation) {
-
- if (operation != ArtifactOperation.Download) {
+ 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);
@@ -2874,12 +3206,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return Either.left(true);
}
- private Either<User, ResponseFormat> validateUserExists(String userId, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType) {
-
- return validateUserExists(userId, auditingAction, componentId, artifactId, componentType, false);
-
- }
-
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);
@@ -2892,9 +3218,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return Either.left(validateUserExists.left().value());
}
- private AuditingActionEnum detectAuditingType(ArtifactOperation operation, String origMd5) {
+ protected AuditingActionEnum detectAuditingType(ArtifactOperationInfo operation, String origMd5) {
AuditingActionEnum auditingAction = null;
- switch (operation) {
+ switch (operation.getArtifactOperationEnum()) {
case Create:
auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : AuditingActionEnum.ARTIFACT_UPLOAD;
break;
@@ -2945,7 +3271,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
CassandraOperationStatus resourceUploadStatus = artifactCassandraDao.saveArtifact(artifactData);
if (resourceUploadStatus.equals(CassandraOperationStatus.OK)) {
- log.debug("Artifact {} was saved in component {}.", artifactData.getId(), resourceId);
+ log.debug("Artifact {} was saved in component .", artifactData.getId(), resourceId);
} else {
log.info("Failed to save artifact {}.", artifactData.getId());
return false;
@@ -2961,19 +3287,15 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return (ArtifactGroupTypeEnum.DEPLOYMENT.equals(artifactInfo.getArtifactGroupType()));
}
- public IResourceOperation getResourceOperation() {
- return this.resourceOperation;
- }
-
- public Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, String userId, ArtifactGroupTypeEnum groupType, boolean inTransaction) {
- Either<User, ActionStatus> user = userAdminManager.getUser(userId, inTransaction);
+ 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 {}", userId);
+ 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 {}", userId);
+ log.debug("create artifact placeholder - failed to authorize user, userId {}", userUserId);
responseFormat = componentsUtils.getResponseFormat(user.right().value());
}
return Either.right(responseFormat);
@@ -2995,21 +3317,13 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
artifactInfo.setArtifactType(artifactType);
artifactInfo.setDescription(artifactDescription);
artifactInfo.setArtifactGroupType(groupType);
- setDefaultArtifactTimeout(groupType, artifactInfo);
+ nodeTemplateOperation.setDefaultArtifactTimeout(groupType, artifactInfo);
setArtifactPlaceholderCommonFields(resourceId, user, artifactInfo);
return artifactInfo;
}
- private void setDefaultArtifactTimeout(ArtifactGroupTypeEnum groupType, ArtifactDefinition artifactInfo) {
- if (groupType.equals(ArtifactGroupTypeEnum.DEPLOYMENT)) {
- artifactInfo.setTimeout(defaultHeatTimeout);
- } else {
- artifactInfo.setTimeout(NON_HEAT_TIMEOUT);
- }
- }
-
private void setArtifactPlaceholderCommonFields(String resourceId, User user, ArtifactDefinition artifactInfo) {
String uniqueId = null;
@@ -3032,29 +3346,17 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
artifactInfo.setMandatory(true);
}
- public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType, boolean inTransaction, ArtifactGroupTypeEnum groupType) {
- return artifactOperation.getArtifacts(parentId, parentType, inTransaction, groupType.getType());
+ 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 parentId, NodeTypeEnum parentType, boolean inTransaction) {
- return artifactOperation.addHeatEnvArtifact(artifactHeatEnv, artifact, parentId, parentType, inTransaction);
-
+ 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 parameters) {
- StringBuilder sb = new StringBuilder();
-
- sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader());
- sb.append(parameters);
- sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter());
- byte[] payload = sb.toString().getBytes();
+ private Either<ESArtifactData, ResponseFormat> createEsHeatEnvArtifactDataFromString(ArtifactDefinition artifactDefinition, String payloadStr) {
- YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
-
- /*
- * if (!yamlToObjectConverter.isValidYaml(payload)) { log.debug("Invalid YAML format"); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, ArtifactTypeEnum.HEAT_ENV.getType()); return
- * Either.right(responseFormat); }
- */
+ byte[] payload = payloadStr.getBytes();
ESArtifactData artifactData = createEsArtifactData(artifactDefinition, payload);
return Either.left(artifactData);
@@ -3065,60 +3367,81 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
* @param artifactDefinition
* @return
*/
- public Either<ArtifactDefinition, ResponseFormat> generateHeatEnvArtifact(ArtifactDefinition artifactDefinition, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier, boolean shouldLock) {
- List<HeatParameterDefinition> heatParameters = artifactDefinition.getHeatParameters();
+ 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);
+ return generateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, shouldLock, instanceId);
+ }
+
+ private String generateHeatEnvPayload(ArtifactDefinition artifactDefinition) {
+ List<HeatParameterDefinition> heatParameters = artifactDefinition.getListHeatParameters();
heatParameters.sort(Comparator.comparing(e -> e.getName()));
- StringBuilder sb = new StringBuilder("parameters:\n");
+ StringBuilder sb = new StringBuilder();
+ sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader());
+ sb.append("parameters:\n");
if (heatParameters != null) {
+ List<HeatParameterDefinition> empltyHeatValues = new ArrayList<>();
for (HeatParameterDefinition heatParameterDefinition : heatParameters) {
- if (heatParameterDefinition.getCurrentValue() != null) {
- HeatParameterType type = HeatParameterType.isValidType(heatParameterDefinition.getType());
- if (type != null) {
- switch (type) {
- case BOOLEAN:
- sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(Boolean.parseBoolean(heatParameterDefinition.getCurrentValue())).append("\n");
- break;
- case NUMBER:
- // if
- // (ValidationUtils.isFloatNumber(heatParameterDefinition.getCurrentValue()))
- // {
- // sb.append("
- // ").append(heatParameterDefinition.getName()).append(":").append("
- // ").append(Float.parseFloat(heatParameterDefinition.getCurrentValue())).append("\n");
- // } else {
- // sb.append("
- // ").append(heatParameterDefinition.getName()).append(":").append("
- // ").append(Integer.parseInt(heatParameterDefinition.getCurrentValue())).append("\n");
- // }
- sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(new BigDecimal(heatParameterDefinition.getCurrentValue()).toPlainString()).append("\n");
- break;
- case COMMA_DELIMITED_LIST:
- case JSON:
- sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(heatParameterDefinition.getCurrentValue()).append("\n");
- break;
- default:
- String value = heatParameterDefinition.getCurrentValue();
- boolean starts = value.startsWith("\"");
- boolean ends = value.endsWith("\"");
+
+ 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)) {
- starts = value.startsWith("'");
- ends = value.endsWith("'");
- if (!(starts && ends)) {
- value = "\"" + value + "\"";
- }
+ value = "\"" + value + "\"";
}
- sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(value);
- sb.append("\n");
- break;
-
}
+ 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");
+ }
+ });
+ }
}
- return generateAndSaveHeatEnvArtifact(artifactDefinition, sb.toString(), component, resourceInstanceName, modifier, shouldLock);
+ sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter());
+
+ // DE265919 fix Tal G
+ String result = sb.toString().replaceAll("\\\\n", "\n");
+ return result;
}
/**
@@ -3127,14 +3450,15 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
* @param payload
* @return
*/
- public Either<ArtifactDefinition, ResponseFormat> generateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
- boolean shouldLock) {
- return generateArtifactPayload(artifactDefinition, component, resourceInstanceName, modifier, shouldLock, () -> artifactDefinition.getHeatParamsUpdateDate(), () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload));
+ 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);
}
- protected Either<ArtifactDefinition, ResponseFormat> generateArtifactPayload(ArtifactDefinition artifactDefinition, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier, boolean shouldLock,
- Supplier<Long> payloadUpdateDateGen, Supplier<Either<ESArtifactData, ResponseFormat>> esDataCreator) {
+ 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) {
if (artifactDefinition.getPayloadUpdateDate() == null || artifactDefinition.getPayloadUpdateDate() == 0 || artifactDefinition.getPayloadUpdateDate() < payloadUpdateDateGen.get()) {
@@ -3156,7 +3480,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
String esArtifactId = artifactDefinition.getEsId();
Either<ESArtifactData, CassandraOperationStatus> artifactfromES;
ESArtifactData esArtifactData;
- if (esArtifactId != null && !esArtifactId.isEmpty()) {
+ if (esArtifactId != null && !esArtifactId.isEmpty() && artifactDefinition.getPayloadData() == null) {
artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
if (artifactfromES.isRight()) {
CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
@@ -3169,8 +3493,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
oldCheckSum = GeneralUtility.calculateMD5ByByteArray(esArtifactData.getDataAsArray());
} else {
oldCheckSum = artifactDefinition.getArtifactChecksum();
+
}
- Either<ArtifactDefinition, StorageOperationStatus> updateArifactDefinitionStatus;
+ Either<ArtifactDefinition, StorageOperationStatus> updateArifactDefinitionStatus = null;
if (shouldLock) {
Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "Update Artifact - lock resource: ");
@@ -3183,11 +3508,11 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
if (oldCheckSum != null && oldCheckSum.equals(newCheckSum)) {
artifactDefinition.setPayloadUpdateDate(payloadUpdateDateGen.get());
- updateArifactDefinitionStatus = artifactOperation.updateArifactDefinition(artifactDefinition, false);
+ 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());
+ 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);
@@ -3197,42 +3522,41 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
oldCheckSum = artifactDefinition.getArtifactChecksum();
artifactDefinition.setArtifactChecksum(newCheckSum);
- artifactOperation.updateUUID(artifactDefinition, oldCheckSum, artifactDefinition.getArtifactVersion());
+ artifactToscaOperation.updateUUID(artifactDefinition, oldCheckSum, artifactDefinition.getArtifactVersion());
artifactDefinition.setEsId(artifactDefinition.getUniqueId());
- updateArifactDefinitionStatus = artifactOperation.updateArifactDefinition(artifactDefinition, true);
+ updateArifactDefinitionStatus = artifactToscaOperation.updateArifactOnResource(artifactDefinition, component.getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId);
log.trace("Update Payload ", artifactDefinition.getEsId());
+ }
+ if (updateArifactDefinitionStatus != null && updateArifactDefinitionStatus.isLeft()) {
- if (updateArifactDefinitionStatus.isLeft()) {
-
- artifactData.setId(artifactDefinition.getUniqueId());
- CassandraOperationStatus saveArtifactStatus = artifactCassandraDao.saveArtifact(artifactData);
-
- if (saveArtifactStatus.equals(CassandraOperationStatus.OK)) {
- titanGenericDao.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);
+ artifactData.setId(artifactDefinition.getUniqueId());
+ CassandraOperationStatus saveArtifactStatus = artifactCassandraDao.saveArtifact(artifactData);
- } else {
- titanGenericDao.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);
+ 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);
- return Either.right(responseFormat);
- }
} else {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus.right().value()), artifactDefinition.getArtifactDisplayName());
- log.debug("Failed To update artifact {}", artifactData.getId());
+ 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) {
@@ -3245,11 +3569,11 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
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, ArtifactOperation operation, boolean shouldLock, boolean inTransaction) {
- NodeTypeEnum parentType = convertParentType(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 = artifactOperation.getArtifactById(artifactId, false);
- ArtifactDefinition currArtifact = artifactRes.left().value();
+ // 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);
@@ -3298,11 +3622,11 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
if (resultOp == null || resultOp.isRight()) {
log.debug("all changes rollback");
if (false == inTransaction)
- titanGenericDao.rollback();
+ titanDao.rollback();
} else {
log.debug("all changes committed");
if (false == inTransaction)
- titanGenericDao.commit();
+ titanDao.commit();
}
if (shouldLock)
componentType = parent.getComponentType();
@@ -3336,9 +3660,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
return Either.right(responseFormat);
}
- List<HeatParameterDefinition> currentHeatEnvParams = currArtifact.getHeatParameters();
- List<HeatParameterDefinition> updatedHeatEnvParams = artifactInfo.getHeatParameters();
- List<HeatParameterDefinition> reducedHeatEnvParams = new ArrayList<HeatParameterDefinition>();
+ List<HeatParameterDefinition> currentHeatEnvParams = currArtifact.getListHeatParameters();
+ List<HeatParameterDefinition> updatedHeatEnvParams = artifactInfo.getListHeatParameters();
+ new ArrayList<HeatParameterDefinition>();
// upload
if (origMd5 != null) {
@@ -3349,7 +3673,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
return Either.right(responseFormat);
}
- artifactInfo.setHeatParameters(updatedHeatEnvParams);
+ artifactInfo.setListHeatParameters(updatedHeatEnvParams);
}
Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, ArtifactTypeEnum.HEAT_ENV.getType());
@@ -3368,61 +3692,133 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
String updatedParamValue = heatEnvParam.getCurrentValue();
if (updatedParamValue != null && updatedParamValue.equals("")) { // reset
- heatEnvParam.setCurrentValue(heatEnvParam.getDefaultValue());
- reducedHeatEnvParams.add(heatEnvParam);
+ currHeatParam.setCurrentValue(heatEnvParam.getDefaultValue());
} else if (updatedParamValue != null) {
- reducedHeatEnvParams.add(heatEnvParam);
+ currHeatParam.setCurrentValue(updatedParamValue);
}
}
}
}
- if (reducedHeatEnvParams.size() > 0) {
- ArtifactDefinition reducedArtifactInfo = new ArtifactDefinition(artifactInfo);
- reducedArtifactInfo.setHeatParameters(reducedHeatEnvParams);
- Either<ArtifactDefinition, StorageOperationStatus> updateArtifactResult = artifactOperation.updateArifactOnResource(reducedArtifactInfo, componentId, artifactInfo.getUniqueId(), componentType.getNodeType(), inTransaction);
+ currArtifact.setHeatParamsUpdateDate(System.currentTimeMillis());
+ currArtifact.setListHeatParameters(currentHeatEnvParams);
- if (updateArtifactResult.isRight()) {
- log.debug("Failed to update artifact on graph - {}", artifactId);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArtifactResult.right().value()));
- handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
- return Either.right(responseFormat);
- }
- ArtifactDefinition updatedArtifact = updateArtifactResult.left().value();
- String updatedArtifactId = updatedArtifact.getUniqueId();
- if (!currArtifact.getUniqueId().equals(updatedArtifactId)) {
- currArtifact.setUniqueId(updatedArtifactId);
- currArtifact.setPayloadUpdateDate(updatedArtifact.getPayloadUpdateDate());
- currArtifact.setCreationDate(updatedArtifact.getCreationDate());
- currArtifact.setLastUpdateDate(updatedArtifact.getLastUpdateDate());
- currArtifact.setEsId(updatedArtifact.getEsId());
- }
- currArtifact.setHeatParamsUpdateDate(System.currentTimeMillis());
+ 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);
+ }
- Either<List<HeatParameterDefinition>, StorageOperationStatus> heatParamsForEnv = ((org.openecomp.sdc.be.model.operations.impl.ArtifactOperation) artifactOperation).getHeatParamsForEnv(currArtifact);
- if (heatParamsForEnv.isRight()) {
- log.debug("failed to get heat parameters values for heat artifact {}", updatedArtifact.getUniqueId());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(heatParamsForEnv.right().value()));
- 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 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateHeatParams(String componentId, String artifactId, ArtifactDefinition artifactEnvInfo, User user, AuditingActionEnum auditingAction, Component parent,
+ ComponentTypeEnum componentType, ArtifactDefinition currHeatArtifact, 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();
+ */
+ String currentHeatId = currHeatArtifact.getUniqueId();
+ 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;
+ }
}
- List<HeatParameterDefinition> updatedHeatParaetersList = heatParamsForEnv.left().value();
- currArtifact.setHeatParameters(updatedHeatParaetersList);
-
- Either<ArtifactDefinition, StorageOperationStatus> updateArifactRes = artifactOperation.updateArifactDefinition(currArtifact, true);
- 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());
+ }
+ 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();
+ insideEither = Either.left(updatedHeatArt);
}
}
- insideEither = Either.left(currArtifact);
+ if (!currentHeatId.equals(updatedHeatArt.getUniqueId())) {
+ artifactEnvInfo.setArtifactChecksum(null);
+ artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, currentHeatId, updatedHeatArt.getUniqueId(), componentType.getNodeType(), componentId);
+ } else {
+ artifactToscaOperation.updateHeatEnvPlaceholder(artifactEnvInfo, componentId, componentType.getNodeType());
+
+ }
resultOp = Either.left(insideEither);
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
- handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currArtifact, null, artifactId, responseFormat, componentType, ri.getName());
+ handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, "");
return resultOp;
+
+ }
+
+ 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,
@@ -3484,25 +3880,12 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return Either.right(responseFormat);
}
- public ComponentOperation getComponentOperation(NodeTypeEnum componentType) {
-
- switch (componentType) {
- case Service:
- case ResourceInstance:
- return serviceOperation;
- case Resource:
- return resourceOperation;
- default:
- return null;
- }
- }
-
public ArtifactDefinition extractArtifactDefinition(Either<ArtifactDefinition, Operation> eitherArtifact) {
ArtifactDefinition ret;
if (eitherArtifact.isLeft()) {
ret = eitherArtifact.left().value();
} else {
- ret = eitherArtifact.right().value().getImplementation();
+ ret = eitherArtifact.right().value().getImplementationArtifact();
}
return ret;
}
@@ -3549,7 +3932,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
byte[] downloadedArtifact = null;
ComponentInstance resourceInstance = getRelatedComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
if (errorWrapper.isEmpty()) {
- auditAdditionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstance.getName());
downloadedArtifact = downloadArtifact(resourceInstance.getDeploymentArtifacts(), artifactUUID, errorWrapper, resourceInstance.getName());
}
if (errorWrapper.isEmpty()) {
@@ -3568,39 +3950,41 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
* @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) {
+ 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;
+ ArtifactDefinition uploadArtifact = null;
Component component = null;
String componentId = null;
- ArtifactOperation operation = ArtifactOperation.Create;
- operation.setExternalApi(true);
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 = getComponentOperation(componentType).getLatestComponentMetadataByUuid(componentType.getNodeType(), componentUuid);
+ Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata);
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);
+ errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid));
}
if (errorWrapper.isEmpty()) {
- if (component != null) {
- componentId = component.getUniqueId();
- } else {
- componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
+ 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()) {
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, getComponentRes.left().value().getMetadataDataDefinition().getName());
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());
@@ -3609,11 +3993,11 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
if (errorWrapper.isEmpty()) {
uploadArtifact = actionResult.left().value().left().value();
- updateAuditParametersWithArtifactDefinition(additionalParams, uploadArtifact);
uploadArtifactResult = Either.left(uploadArtifact);
} else {
uploadArtifactResult = Either.right(errorWrapper.getInnerElement());
}
+ updateAuditParametersWithArtifactDefinition(additionalParams, uploadArtifact);
return uploadArtifactResult;
}
@@ -3626,14 +4010,15 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
* @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) {
+ Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
Either<ArtifactDefinition, ResponseFormat> uploadArtifactResult;
Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
- ArtifactDefinition uploadArtifact;
+ ArtifactDefinition uploadArtifact = null;
Component component = null;
String componentInstanceId;
String componentId;
@@ -3641,11 +4026,11 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
String userId = request.getHeader(Constants.USER_ID_HEADER);
ImmutablePair<Component, ComponentInstance> componentRiPair = null;
- Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = getComponentOperation(componentType).getLatestComponentMetadataByUuid(componentType.getNodeType(), componentUuid);
+ Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata);
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)));
+ 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);
@@ -3660,9 +4045,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
if (errorWrapper.isEmpty()) {
componentInstanceId = componentRiPair.getRight().getUniqueId();
componentId = componentRiPair.getLeft().getUniqueId();
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName);
- ArtifactOperation operation = ArtifactOperation.Create;
- operation.setExternalApi(true);
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));
@@ -3673,11 +4055,11 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
if (errorWrapper.isEmpty()) {
uploadArtifact = actionResult.left().value().left().value();
- updateAuditParametersWithArtifactDefinition(additionalParams, uploadArtifact);
uploadArtifactResult = Either.left(uploadArtifact);
} else {
uploadArtifactResult = Either.right(errorWrapper.getInnerElement());
}
+ updateAuditParametersWithArtifactDefinition(additionalParams, uploadArtifact);
return uploadArtifactResult;
}
@@ -3690,45 +4072,46 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
* @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) {
+ Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
- ArtifactDefinition updateArtifact;
+ ArtifactDefinition updateArtifact = null;
Component component = null;
String componentId = null;
String artifactId = null;
- ArtifactOperation operation = ArtifactOperation.Update;
- operation.setExternalApi(true);
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 = getComponentOperation(componentType).getLatestComponentMetadataByUuid(componentType.getNodeType(), componentUuid);
+ Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata);
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) {
- componentId = component.getUniqueId();
- } else {
- componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
+ 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()) {
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, getComponentRes.left().value().getMetadataDataDefinition().getName());
-
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());
@@ -3737,12 +4120,12 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
if (errorWrapper.isEmpty()) {
updateArtifact = actionResult.left().value().left().value();
- updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact);
updateArtifactResult = Either.left(updateArtifact);
} else {
updateArtifactResult = Either.right(errorWrapper.getInnerElement());
}
+ updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact);
return updateArtifactResult;
}
@@ -3756,15 +4139,17 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
* @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) {
+ Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
- ArtifactDefinition updateArtifact;
+ ArtifactDefinition updateArtifact = null;
Component component = null;
String componentInstanceId = null;
String componentId = null;
@@ -3773,7 +4158,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
String userId = request.getHeader(Constants.USER_ID_HEADER);
ImmutablePair<Component, ComponentInstance> componentRiPair = null;
- Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = getComponentOperation(componentType).getLatestComponentMetadataByUuid(componentType.getNodeType(), componentUuid);
+ Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata);
if (getComponentRes.isRight()) {
StorageOperationStatus status = getComponentRes.right().value();
log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
@@ -3792,12 +4177,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
if (errorWrapper.isEmpty()) {
componentInstanceId = componentRiPair.getRight().getUniqueId();
componentId = componentRiPair.getLeft().getUniqueId();
- artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentInstanceId, ComponentTypeEnum.RESOURCE_INSTANCE);
+ artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper);
}
if (errorWrapper.isEmpty()) {
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName);
- ArtifactOperation operation = ArtifactOperation.Update;
- operation.setExternalApi(true);
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));
@@ -3808,13 +4190,12 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
if (errorWrapper.isEmpty()) {
updateArtifact = actionResult.left().value().left().value();
- updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact);
updateArtifactResult = Either.left(updateArtifact);
} else {
updateArtifactResult = Either.right(errorWrapper.getInnerElement());
}
+ updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact);
return updateArtifactResult;
-
}
/**
@@ -3825,44 +4206,45 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
* @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) {
+ 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;
+ ArtifactDefinition deleteArtifact = null;
Component component = null;
String componentId = null;
String artifactId = null;
- ArtifactOperation operation = ArtifactOperation.Delete;
- operation.setExternalApi(true);
String origMd5 = request.getHeader(Constants.MD5_HEADER);
String userId = request.getHeader(Constants.USER_ID_HEADER);
- Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = getComponentOperation(componentType).getLatestComponentMetadataByUuid(componentType.getNodeType(), componentUuid);
+ Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata);
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);
+ errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid));
}
if (errorWrapper.isEmpty()) {
- if (component != null) {
- componentId = component.getUniqueId();
- } else {
- componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
+ 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()) {
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, getComponentRes.left().value().getMetadataDataDefinition().getName());
-
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());
@@ -3871,16 +4253,16 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
if (errorWrapper.isEmpty()) {
deleteArtifact = actionResult.left().value().left().value();
- updateAuditParametersWithArtifactDefinition(additionalParams, deleteArtifact);
deleteArtifactResult = Either.left(deleteArtifact);
} else {
deleteArtifactResult = Either.right(errorWrapper.getInnerElement());
}
+ updateAuditParametersWithArtifactDefinition(additionalParams, deleteArtifact);
return deleteArtifactResult;
}
/**
- * deletes an artifact an a resource instance by UUID
+ * deletes an artifact from a resource instance by UUID
*
* @param request
* @param componentType
@@ -3888,15 +4270,17 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
* @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) {
+ Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult;
Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
- ArtifactDefinition deleteArtifact;
+ ArtifactDefinition deleteArtifact = null;
Component component = null;
String componentInstanceId = null;
String componentId = null;
@@ -3904,7 +4288,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
String origMd5 = request.getHeader(Constants.MD5_HEADER);
String userId = request.getHeader(Constants.USER_ID_HEADER);
ImmutablePair<Component, ComponentInstance> componentRiPair = null;
- Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = getComponentOperation(componentType).getLatestComponentMetadataByUuid(componentType.getNodeType(), componentUuid);
+ Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata);
if (getComponentRes.isRight()) {
StorageOperationStatus status = getComponentRes.right().value();
log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
@@ -3923,14 +4307,10 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
if (errorWrapper.isEmpty()) {
componentInstanceId = componentRiPair.getRight().getUniqueId();
componentId = componentRiPair.getLeft().getUniqueId();
- artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentInstanceId, ComponentTypeEnum.RESOURCE_INSTANCE);
+ artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper);
}
if (errorWrapper.isEmpty()) {
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName);
- ArtifactOperation operation = ArtifactOperation.Delete;
- operation.setExternalApi(true);
-
actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, null, origMd5, null, null, null, componentId, ComponentTypeEnum.findParamByType(componentType));
if (actionResult.isRight()) {
@@ -3940,50 +4320,204 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
if (errorWrapper.isEmpty()) {
deleteArtifact = actionResult.left().value().left().value();
- updateAuditParametersWithArtifactDefinition(additionalParams, deleteArtifact);
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;
+ }
+
+ public Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder(ArtifactDefinition artifact, String envType, String parentId, NodeTypeEnum parentType, String parentName, User user, Component component,
+ Map<String, String> existingEnvVersions) {
+ return createHeatEnvPlaceHolder(artifact, envType, parentId, parentType, parentName, user, component, existingEnvVersions, true);
+
+ }
+
+ @SuppressWarnings("unchecked")
+ public Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder(ArtifactDefinition artifact, String envType, String parentId, NodeTypeEnum parentType, String parentName, User user, Component component,
+ Map<String, String> existingEnvVersions, boolean overrideId) {
+ 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 = (artifact.getArtifactLabel() + HEAT_ENV_SUFFIX).toLowerCase();
+ String parentIdParam = parentId;
+ if (!overrideId) {
+ parentIdParam = null;
+ }
+ Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolder = createArtifactPlaceHolderInfo(parentIdParam, envLabel, placeHolderData, user.getUserId(), ArtifactGroupTypeEnum.DEPLOYMENT, true);
+ if (createArtifactPlaceHolder.isRight()) {
+ return Either.right(createArtifactPlaceHolder.right().value());
+ }
+ ArtifactDefinition artifactHeatEnv = createArtifactPlaceHolder.left().value();
+ if (!overrideId) {
+ // fix for migration only!!!! create heat env placeholder according to heat id.
+ artifactHeatEnv.setUniqueId(artifact.getUniqueId() + HEAT_ENV_SUFFIX);
+ }
+
+ artifactHeatEnv.setGeneratedFromId(artifact.getUniqueId());
+ artifactHeatEnv.setHeatParamsUpdateDate(System.currentTimeMillis());
+ artifactHeatEnv.setTimeout(0);
+ buildHeatEnvFileName(artifact, artifactHeatEnv, placeHolderData);
+ // rbetzer - keep env artifactVersion - changeComponentInstanceVersion flow
+ handleEnvArtifactVersion(artifactHeatEnv, existingEnvVersions);
+ // clone heat parameters in case of heat env only not VF heat env
+ if (envType.equals(HEAT_ENV_NAME)) {
+ artifactHeatEnv.setHeatParameters(artifact.getHeatParameters());
+ }
+ ArtifactDefinition artifactDefinition;
+ // 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, artifact, 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));
+ }
+ artifactDefinition = createArtifactPlaceHolder.left().value();
+ } else {
+ artifactDefinition = artifactHeatEnv;
+ artifactToscaOperation.generateUUID(artifactDefinition, artifactDefinition.getArtifactVersion());
+ }
+
+ if (artifact.getHeatParameters() != null) {
+ List<HeatParameterDefinition> heatEnvParameters = new ArrayList<HeatParameterDefinition>();
+ for (HeatParameterDefinition parameter : artifact.getListHeatParameters()) {
+ HeatParameterDefinition heatEnvParameter = new HeatParameterDefinition(parameter);
+ heatEnvParameter.setDefaultValue(parameter.getCurrentValue());
+ heatEnvParameters.add(heatEnvParameter);
+ }
+ artifactDefinition.setListHeatParameters(heatEnvParameters);
+ }
+
+ // audit
+ EnumMap<AuditingFieldsKeysEnum, Object> artifactAuditingFields = createArtifactAuditingFields(artifactDefinition, "", artifactDefinition.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(artifactDefinition);
+ }
+
+ 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.calculateMD5ByString(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 (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) {
+ 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;
- StorageOperationStatus status;
- Either<ComponentInstance, StorageOperationStatus> getResourceInstanceRes = null;
+ String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
Component component = getLatestComponentByUuid(componentType, componentUuid, errorWrapper);
if (errorWrapper.isEmpty()) {
- componentInstance = component.getComponentInstances().stream().filter(ci -> ci.getNormalizedName().equals(resourceInstanceName)).findAny().get();
+ 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());
}
}
- if (errorWrapper.isEmpty()) {
- getResourceInstanceRes = resourceInstanceOperation.getResourceInstanceById(componentInstance.getUniqueId());
- if (getResourceInstanceRes.isRight()) {
- status = getResourceInstanceRes.right().value();
- errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
- }
- }
- if (errorWrapper.isEmpty()) {
- componentInstance = getResourceInstanceRes.left().value();
- getResourceInstanceRes = resourceInstanceOperation.getFullComponentInstance(componentInstance, componentType.getNodeType());
- if (getResourceInstanceRes.isRight()) {
- status = getResourceInstanceRes.right().value();
- errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
- } else {
- componentInstance = getResourceInstanceRes.left().value();
- }
- }
return componentInstance;
}
private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(Component component, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null;
- ComponentInstance componentInstance = component.getComponentInstances().stream().filter(ci -> ci.getNormalizedName().equals(resourceInstanceName)).findAny().get();
+ 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());
@@ -3998,7 +4532,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null;
Component component = getLatestComponentByUuid(componentType, componentUuid, errorWrapper);
if (errorWrapper.isEmpty()) {
- componentInstance = component.getComponentInstances().stream().filter(ci -> ci.getNormalizedName().equals(resourceInstanceName)).findAny().get();
+ 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());
@@ -4039,7 +4573,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
private Component getLatestComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper<ResponseFormat> errorWrapper) {
Component component = null;
- Either<Component, StorageOperationStatus> getComponentRes = getComponentOperation(componentType).getLatestComponentByUuid(componentType.getNodeType(), componentUuid);
+ 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);
@@ -4056,13 +4590,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
StorageOperationStatus storageStatus;
ArtifactDefinition latestArtifact = null;
List<ArtifactDefinition> artifacts = null;
- NodeTypeEnum parentType;
- if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
- parentType = NodeTypeEnum.Resource;
- } else {
- parentType = NodeTypeEnum.Service;
- }
- Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifactsRes = artifactOperation.getArtifacts(parentId, parentType, false);
+ 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);
@@ -4120,8 +4648,29 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
private void updateAuditParametersWithArtifactDefinition(Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactDefinition artifact) {
- 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());
+ 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);
}
}
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 15fe86da33..84cf20dcfa 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
@@ -34,7 +34,7 @@ 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.model.operations.utils.ComponentValidationUtils;
-import org.openecomp.sdc.be.resources.data.AttributeData;
+
import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -78,10 +78,10 @@ public class AttributeBusinessLogic extends BaseBusinessLogic {
log.info("Failed to lock component {}. Error - {}", resourceId, lockResult);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
}
- try {
+ try {
// Get the resource from DB
- Either<Resource, StorageOperationStatus> status = getResource(resourceId);
+ Either<Resource, StorageOperationStatus> status = toscaOperationFacade.getToscaElement(resourceId);
if (status.isRight()) {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, ""));
}
@@ -111,17 +111,16 @@ public class AttributeBusinessLogic extends BaseBusinessLogic {
// add the new attribute to resource on graph
// need to get StorageOpaerationStatus and convert to ActionStatus from
// componentsUtils
- Either<AttributeData, StorageOperationStatus> either = attributeOperation.addAttribute(newAttributeDef, resourceId);
+ Either<AttributeDefinition, 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(attributeOperation.convertAttributeDataToAttributeDefinition(either.left().value(), newAttributeDef.getName(), resourceId));
+ result = Either.left(either.left().value());
+
return result;
} finally {
commitOrRollback(result);
- // unlock component
graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource);
}
@@ -150,7 +149,7 @@ public class AttributeBusinessLogic extends BaseBusinessLogic {
}
// Get the resource from DB
- Either<Resource, StorageOperationStatus> status = getResource(resourceId);
+ Either<Resource, StorageOperationStatus> status = toscaOperationFacade.getToscaElement(resourceId);
if (status.isRight()) {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, ""));
}
@@ -185,16 +184,16 @@ public class AttributeBusinessLogic extends BaseBusinessLogic {
*/
public Either<AttributeDefinition, ResponseFormat> updateAttribute(String resourceId, String attributeId, AttributeDefinition newAttDef, String userId) {
Either<AttributeDefinition, 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 = getResource(resourceId);
+ Either<Resource, StorageOperationStatus> eitherResource = toscaOperationFacade.getToscaElement(resourceId);
if (eitherResource.isRight()) {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, ""));
}
@@ -204,7 +203,7 @@ public class AttributeBusinessLogic extends BaseBusinessLogic {
if (!ComponentValidationUtils.canWorkOnResource(resource, userId)) {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
}
-
+
// verify attribute exist in resource
Either<AttributeDefinition, ResponseFormat> eitherAttribute = getAttribute(resourceId, attributeId, userId);
if (eitherAttribute.isRight()) {
@@ -221,7 +220,15 @@ public class AttributeBusinessLogic extends BaseBusinessLogic {
return Either.right(defaultValuesValidation.right().value());
}
// add the new property to resource on graph
- Either<AttributeData, StorageOperationStatus> eitherAttUpdate = attributeOperation.updateAttribute(attributeId, newAttDef, eitherAllDataTypes.left().value());
+
+ 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<AttributeDefinition, StorageOperationStatus> eitherAttUpdate = toscaOperationFacade.updateAttributeOfResource(resource, newAttDef);
if (eitherAttUpdate.isRight()) {
log.debug("Problem while updating attribute with id {}. Reason - {}", attributeId, eitherAttUpdate.right().value());
@@ -229,12 +236,13 @@ public class AttributeBusinessLogic extends BaseBusinessLogic {
return result;
}
- result = Either.left(attributeOperation.convertAttributeDataToAttributeDefinition(eitherAttUpdate.left().value(), newAttDef.getName(), resourceId));
+ result = Either.left(eitherAttUpdate.left().value());
return result;
} finally {
commitOrRollback(result);
graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource);
}
+
}
/**
@@ -246,7 +254,9 @@ public class AttributeBusinessLogic extends BaseBusinessLogic {
* @return
*/
public Either<AttributeDefinition, ResponseFormat> deleteAttribute(String resourceId, String attributeId, String userId) {
+
Either<AttributeDefinition, ResponseFormat> result = null;
+
Either<User, ResponseFormat> resp = validateUserExists(userId, "delete Attribute", false);
if (resp.isRight()) {
return Either.right(resp.right().value());
@@ -255,13 +265,13 @@ public class AttributeBusinessLogic extends BaseBusinessLogic {
StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource);
if (lockResult != StorageOperationStatus.OK) {
BeEcompErrorManager.getInstance().logBeFailedLockObjectError(DELETE_ATTRIBUTE, NodeTypeEnum.Resource.name().toLowerCase(), resourceId);
- result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
- return result;
+ 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 = getResource(resourceId);
+ Either<Resource, StorageOperationStatus> eitherResource = toscaOperationFacade.getToscaElement(resourceId);
if (eitherResource.isRight()) {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, ""));
}
@@ -280,12 +290,13 @@ public class AttributeBusinessLogic extends BaseBusinessLogic {
String attributeName = eitherAttributeExist.left().value().getName();
// delete attribute of resource from graph
- Either<AttributeData, StorageOperationStatus> eitherAttributeDelete = attributeOperation.deleteAttribute(attributeId);
- if (eitherAttributeDelete.isRight()) {
- result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(eitherAttributeDelete.right().value()), resource.getName()));
+ 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(attributeOperation.convertAttributeDataToAttributeDefinition(eitherAttributeDelete.left().value(), attributeName, resourceId));
+
+ result = Either.left(eitherAttributeExist.left().value());
return result;
} finally {
commitOrRollback(result);
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 93ddff38d5..df8460ca96 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/BaseBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/BaseBusinessLogic.java
@@ -20,57 +20,67 @@
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 org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.PropertyRule;
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.LifecycleStateEnum;
-import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
-import org.openecomp.sdc.be.model.operations.api.IArtifactOperation;
+import org.openecomp.sdc.be.model.jsontitan.operations.ArtifactsOperations;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
import org.openecomp.sdc.be.model.operations.api.IAttributeOperation;
-import org.openecomp.sdc.be.model.operations.api.IComponentOperation;
import org.openecomp.sdc.be.model.operations.api.IElementOperation;
import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation;
+import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation;
import org.openecomp.sdc.be.model.operations.api.IGroupOperation;
import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation;
import org.openecomp.sdc.be.model.operations.api.IPropertyOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.model.operations.impl.ComponentOperation;
-import org.openecomp.sdc.be.model.operations.impl.ProductOperation;
-import org.openecomp.sdc.be.model.operations.impl.ResourceOperation;
-import org.openecomp.sdc.be.model.operations.impl.ServiceOperation;
+import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
+import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
import org.openecomp.sdc.be.model.tosca.converters.PropertyValueConverter;
-import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+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.PropertyValueData;
import org.openecomp.sdc.be.user.IUserBusinessLogic;
import org.openecomp.sdc.be.user.Role;
import org.openecomp.sdc.be.user.UserBusinessLogic;
import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.config.EcompErrorName;
import org.openecomp.sdc.common.datastructure.Wrapper;
+import org.openecomp.sdc.common.util.ValidationUtils;
import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
+import com.google.gson.JsonElement;
+
import fj.data.Either;
public abstract class BaseBusinessLogic {
@@ -82,17 +92,11 @@ public abstract class BaseBusinessLogic {
protected IUserBusinessLogic userAdmin;
@Autowired
- protected ResourceOperation resourceOperation;
-
- @Autowired
protected IGraphLockOperation graphLockOperation;
@Autowired
- protected ServiceOperation serviceOperation;
-
- @Autowired
- protected ProductOperation productOperation;
-
+ protected TitanDao titanDao;
+
@Autowired
protected TitanGenericDao titanGenericDao;
@@ -101,22 +105,32 @@ public abstract class BaseBusinessLogic {
@Autowired
protected IGroupOperation groupOperation;
+
+ @Autowired
+ protected IGroupInstanceOperation groupInstanceOperation;
@Autowired
protected IGroupTypeOperation groupTypeOperation;
- @Autowired
- protected IArtifactOperation artifactOperation;
+ /*@Autowired
+ protected IArtifactOperation artifactOperation;*/
+ @javax.annotation.Resource
+ protected ArtifactsOperations artifactToscaOperation;
- @Autowired
- protected IAttributeOperation attributeOperation;
+// @Autowired
+// protected IAttributeOperation attributeOperation;
@Autowired
- protected IPropertyOperation propertyOperation;
+ protected PropertyOperation propertyOperation;
@Autowired
protected ApplicationDataTypeCache applicationDataTypeCache;
+ @Autowired
+ protected ToscaOperationFacade toscaOperationFacade;
+
+ protected DataTypeValidatorConverter dataTypeValidatorConverter = DataTypeValidatorConverter.getInstance();
+
public void setUserAdmin(UserBusinessLogic userAdmin) {
this.userAdmin = userAdmin;
}
@@ -129,15 +143,20 @@ public abstract class BaseBusinessLogic {
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)) {
- // user.setUserId("UNKNOWN");
log.debug("User header is missing ");
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUserMissingError, ecompErrorContext, user.getUserId());
BeEcompErrorManager.getInstance().logBeUserMissingError(ecompErrorContext, user.getUserId());
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
return Either.right(responseFormat);
@@ -166,7 +185,7 @@ public abstract class BaseBusinessLogic {
log.debug("validateUserExists - failed to authorize user, userId {}", userId);
}
log.debug("User is not listed. userId {}", userId);
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUserMissingError, ecompErrorContext, userId);
+ BeEcompErrorManager.getInstance().logBeUserMissingError(ecompErrorContext, userId);
return Either.right(eitherCreator.right().value());
}
return Either.left(eitherCreator.left().value());
@@ -187,7 +206,6 @@ public abstract class BaseBusinessLogic {
}
if (log.isDebugEnabled())
log.debug("User is not listed. userId {}", userId);
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUserMissingError, ecompErrorContext, userId);
BeEcompErrorManager.getInstance().logBeUserMissingError(ecompErrorContext, userId);
return Either.right(responseFormat);
}
@@ -223,7 +241,7 @@ public abstract class BaseBusinessLogic {
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);
+ log.debug("Failed to lock component {} error - {}" ,componentId, actionStatus);
return Either.right(responseFormat);
}
}
@@ -233,9 +251,9 @@ public abstract class BaseBusinessLogic {
NodeTypeEnum nodeType = componentType.getNodeType();
if (false == inTransaction) {
if (either == null || either.isRight()) {
- titanGenericDao.rollback();
+ titanDao.rollback();
} else {
- titanGenericDao.commit();
+ titanDao.commit();
}
}
// unlock resource
@@ -265,17 +283,12 @@ public abstract class BaseBusinessLogic {
}
}
- protected Either<Component, ResponseFormat> validateComponentExists(String componentId, ComponentTypeEnum componentType, boolean inTransaction, boolean createNewTransaction) {
- ComponentOperation componentOperation = getComponentOperation(componentType);
- Either<Component, StorageOperationStatus> componentFound = null;
- // if(createNewTransaction){
- // componentFound = componentOperation.getComponent_tx(componentId,
- // inTransaction);
- // }
- // else{
- componentFound = componentOperation.getComponent(componentId, inTransaction);
- // }
-
+ 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);
@@ -286,35 +299,33 @@ public abstract class BaseBusinessLogic {
return Either.left(componentFound.left().value());
}
- protected Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists(String componentId, ComponentTypeEnum componentType, ComponentParametersView componentParametersView, String userId,
- AuditingActionEnum auditingAction, User user) {
-
- ComponentOperation componentOperation = getComponentOperation(componentType);
-
- if (componentOperation == null) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
- log.debug("addGroup - not supported component type {}", componentType);
- // handleAuditing(auditingAction, null, componentId, user, null,
- // null, artifactId, responseFormat, componentType, null);
- return Either.right(responseFormat);
- }
- Either<? extends org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentResult = componentOperation.getComponent(componentId, componentParametersView, true);
-
- if (componentResult.isRight()) {
- ActionStatus status = (componentType.equals(ComponentTypeEnum.RESOURCE)) ? ActionStatus.RESOURCE_NOT_FOUND : ActionStatus.SERVICE_NOT_FOUND;
-
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, componentId);
-
- log.debug("Service not found, serviceId {}", componentId);
- // ComponentTypeEnum componentForAudit =
- // (componentType.equals(ComponentTypeEnum.RESOURCE)) ?
- // ComponentTypeEnum.RESOURCE : ComponentTypeEnum.SERVICE;
- // handleAuditing(auditingAction, null, componentId, user, null,
- // null, artifactId, responseFormat, componentForAudit, null);
- return Either.right(responseFormat);
- }
- return Either.left(componentResult.left().value());
- }
+// protected Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists(String componentId, ComponentTypeEnum componentType, ComponentParametersView componentParametersView, String userId,
+// AuditingActionEnum auditingAction, User user) {
+//
+// ComponentOperation componentOperation = getComponentOperation(componentType);
+//
+// if (componentOperation == null) {
+// ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
+// log.debug("addGroup - not supported component type {}", componentType);
+// return Either.right(responseFormat);
+// }
+// Either<? extends org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentResult = componentOperation.getComponent(componentId, componentParametersView, true);
+//
+// if (componentResult.isRight()) {
+// ActionStatus status = (componentType.equals(ComponentTypeEnum.RESOURCE)) ? ActionStatus.RESOURCE_NOT_FOUND : ActionStatus.SERVICE_NOT_FOUND;
+//
+// ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, componentId);
+//
+// log.debug("Service not found, serviceId {}", componentId);
+// // ComponentTypeEnum componentForAudit =
+// // (componentType.equals(ComponentTypeEnum.RESOURCE)) ?
+// // ComponentTypeEnum.RESOURCE : ComponentTypeEnum.SERVICE;
+// // handleAuditing(auditingAction, null, componentId, user, null,
+// // null, artifactId, responseFormat, componentForAudit, null);
+// return Either.right(responseFormat);
+// }
+// return Either.left(componentResult.left().value());
+// }
public Either<Boolean, ResponseFormat> validateCanWorkOnComponent(Component component, String userId) {
Either<Boolean, ResponseFormat> canWork = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
@@ -323,7 +334,7 @@ public abstract class BaseBusinessLogic {
return canWork;
}
- // verify user id is not null
+ // verify userId is not null
if (userId == null) {
log.debug("Current user userId is null");
return canWork;
@@ -345,47 +356,6 @@ public abstract class BaseBusinessLogic {
return Either.left(true);
}
- public ComponentOperation getComponentOperation(ComponentTypeEnum componentTypeEnum) {
- if (ComponentTypeEnum.SERVICE == componentTypeEnum) {
- return serviceOperation;
- } else if (ComponentTypeEnum.RESOURCE == componentTypeEnum) {
- return resourceOperation;
- } else if (ComponentTypeEnum.PRODUCT == componentTypeEnum) {
- return productOperation;
- }
- return null;
- }
-
- public IComponentOperation getIComponentOperation(ComponentTypeEnum componentTypeEnum) {
-
- switch (componentTypeEnum) {
- case SERVICE:
- return serviceOperation;
- case RESOURCE:
- return resourceOperation;
- case PRODUCT:
- return productOperation;
- default:
- break;
- }
-
- return null;
- }
-
- public ComponentOperation getComponentOperationByParentComponentType(ComponentTypeEnum parentComponentType) {
- switch (parentComponentType) {
- case SERVICE:
- return resourceOperation;
- case RESOURCE:
- return resourceOperation;
- case PRODUCT:
- return serviceOperation;
- default:
- break;
- }
- return null;
- }
-
public ComponentTypeEnum getComponentTypeByParentComponentType(ComponentTypeEnum parentComponentType) {
switch (parentComponentType) {
case SERVICE:
@@ -401,8 +371,8 @@ public abstract class BaseBusinessLogic {
}
// For UT
- public void setTitanGenericDao(TitanGenericDao titanGenericDao) {
- this.titanGenericDao = titanGenericDao;
+ public void setTitanGenericDao(TitanDao titanDao) {
+ this.titanDao = titanDao;
}
protected Either<Map<String, DataTypeDefinition>, ResponseFormat> getAllDataTypes(ApplicationDataTypeCache applicationDataTypeCache) {
@@ -453,23 +423,23 @@ public abstract class BaseBusinessLogic {
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 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
@@ -503,8 +473,7 @@ public abstract class BaseBusinessLogic {
}
protected void validateCanWorkOnComponent(String componentId, ComponentTypeEnum componentTypeEnum, String userId, Wrapper<ResponseFormat> errorWrapper) {
- IComponentOperation componentOperation = getIComponentOperation(componentTypeEnum);
- if (!ComponentValidationUtils.canWorkOnComponent(componentId, componentOperation, userId)) {
+ if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) {
log.info("Restricted operation for user {} on {} {}", userId, componentTypeEnum.getValue(), componentId);
errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
}
@@ -531,10 +500,10 @@ public abstract class BaseBusinessLogic {
protected void commitOrRollback(Either<? extends Object, ResponseFormat> result) {
if (result == null || result.isRight()) {
log.warn("operation failed. do rollback");
- titanGenericDao.rollback();
+ titanDao.rollback();
} else {
log.debug("operation success. do commit");
- titanGenericDao.commit();
+ titanDao.commit();
}
}
@@ -555,9 +524,9 @@ public abstract class BaseBusinessLogic {
}
protected Either<Component, ResponseFormat> validateComponentExistsByFilter(String componentId, ComponentTypeEnum componentType, ComponentParametersView componentParametersView, boolean inTransaction) {
- ComponentOperation componentOperation = getComponentOperation(componentType);
+
Either<Component, StorageOperationStatus> componentFound = null;
- componentFound = componentOperation.getComponent(componentId, componentParametersView, inTransaction);
+ componentFound = toscaOperationFacade.getToscaElement(componentId, componentParametersView);
if (componentFound.isRight()) {
StorageOperationStatus storageOperationStatus = componentFound.right().value();
@@ -568,4 +537,267 @@ public abstract class BaseBusinessLogic {
}
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(ComponentInstanceProperty 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);
+ }
+
+ 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;
+ }
+
}
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 26ea80ac4b..57ab46346a 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
@@ -72,9 +72,7 @@ public class CategoriesImportManager {
NodeTypeEnum nodeTypeCategory = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentType, CategoryTypeEnum.CATEGORY);
NodeTypeEnum nodeTypeSubCategory = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentType, CategoryTypeEnum.SUBCATEGORY);
NodeTypeEnum nodeTypeGroup = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentType, CategoryTypeEnum.GROUPING);
- if (log.isDebugEnabled()) {
- log.debug("createCategoriesByDao: creating componentType:{} nodeTypeCategory:{} nodeTypeSubCategory:{} nodeTypeGroup:{}", componentType, nodeTypeCategory, nodeTypeSubCategory, nodeTypeGroup);
- }
+ log.debug("createCategoriesByDao: creating componentType:{} nodeTypeCategory:{} nodeTypeSubCategory:{} nodeTypeGroup:{}", componentType, nodeTypeCategory, nodeTypeSubCategory, nodeTypeGroup);
List<CategoryDefinition> newCategoriesvalue = new ArrayList<>();
for (CategoryDefinition category : entry.getValue()) {
@@ -124,16 +122,18 @@ public class CategoriesImportManager {
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());
+ 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);
+ 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));
+ 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());
@@ -147,15 +147,15 @@ public class CategoriesImportManager {
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 {}, alreay exists retrieving", entry.getKey(), newcategory.getName(), subcategory.getName());
+ 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);
+ 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 {}, error {}", entry.getKey(), newcategory.getName(), subcategory.getName(), createdSubCategory.right().value());
+ 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 {
@@ -168,7 +168,7 @@ public class CategoriesImportManager {
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());
+ 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 {
@@ -176,7 +176,7 @@ public class CategoriesImportManager {
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);
+ log.debug("failed to get category that exists categoryId: {} type: {}", categoryId, nodeTypeCategory);
return Either.right(componentsUtils.getResponseFormat(createdCategory.right().value()));
}
}
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 9b99b665f7..f97b4cf3f1 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
@@ -119,7 +119,7 @@ public class CommonImportManager {
}
} catch (Exception e) {
- log.debug("Failed to yaml file {} {}", elementTypesYml, e);
+ log.debug("Failed to yaml file {}", elementTypesYml, e);
return Either.right(ActionStatus.INVALID_YAML_FILE);
}
return Either.left(elementTypes);
@@ -133,7 +133,7 @@ public class CommonImportManager {
}
- enum ElementTypeEnum {
+ public enum ElementTypeEnum {
PolicyType, GroupType, DataType, CapabilityType, InterfaceLifecycleType
};
@@ -204,7 +204,7 @@ public class CommonImportManager {
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());
+ log.debug("Failed in validation of element type: {}. Response is {}", elementType, responseFormat.getFormattedMessage());
eitherResult = Either.right(responseFormat);
break;
}
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 6c7b8b9bc7..f880883438 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
@@ -24,37 +24,59 @@ import java.util.ArrayList;
import java.util.Collection;
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.Set;
+import java.util.function.Function;
+import java.util.function.Predicate;
import java.util.stream.Collectors;
+import org.apache.commons.collections.CollectionUtils;
+import org.apache.commons.collections.MapUtils;
+import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.apache.commons.lang3.tuple.ImmutableTriple;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
import org.openecomp.sdc.be.datamodel.api.HighestFilterEnum;
+import org.openecomp.sdc.be.datamodel.utils.UiComponentDataConverter;
+import org.openecomp.sdc.be.datatypes.components.ComponentMetadataDataDefinition;
import org.openecomp.sdc.be.datatypes.components.ServiceMetadataDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.ComponentFieldsEnum;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
import org.openecomp.sdc.be.model.ArtifactDefinition;
import org.openecomp.sdc.be.model.CapReqDef;
import org.openecomp.sdc.be.model.CapabilityDefinition;
import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.ComponentInstanceInput;
+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.RequirementDefinition;
+import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.model.cache.ComponentCache;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.ComponentOperation;
+import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
+import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;
import org.openecomp.sdc.be.user.Role;
+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.config.EcompErrorName;
@@ -65,6 +87,9 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
+import com.datastax.driver.core.UserType.Field;
+import com.wordnik.swagger.models.auth.In;
+
import fj.data.Either;
public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
@@ -75,6 +100,7 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
@Autowired
protected ComponentCache componentCache;
+
private static Logger log = LoggerFactory.getLogger(ComponentBusinessLogic.class.getName());
private static final String TAG_FIELD_LABEL = "tag";
@@ -85,6 +111,14 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
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;
@@ -193,12 +227,14 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
protected Either<Boolean, ResponseFormat> validateComponentNameUnique(User user, Component component, AuditingActionEnum actionEnum) {
ComponentTypeEnum type = component.getComponentType();
- ComponentOperation componentOperation = getComponentOperation(type);
- Either<Boolean, StorageOperationStatus> dataModelResponse;
- dataModelResponse = componentOperation.validateComponentNameExists(component.getName());
+ 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()) {
+ if ( !dataModelResponse.left().value()) {
return Either.left(true);
} else {
log.info("Component with name {} already exists", component.getName());
@@ -207,7 +243,6 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
return Either.right(errorResponse);
}
}
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "validateComponentNameUnique");
BeEcompErrorManager.getInstance().logBeSystemError("validateComponentNameUnique");
log.debug("Error while validateComponentNameUnique for component: {}", component.getName());
ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
@@ -216,12 +251,12 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
}
protected Either<Boolean, ResponseFormat> validateContactId(User user, Component component, AuditingActionEnum actionEnum) {
- log.debug("validate component contact info");
+ log.debug("validate component contactId");
ComponentTypeEnum type = component.getComponentType();
String contactId = component.getContactId();
if (!ValidationUtils.validateStringNotEmpty(contactId)) {
- log.info("contact info is missing.");
+ 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);
@@ -238,7 +273,7 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
private Either<Boolean, ResponseFormat> validateContactId(String contactId, ComponentTypeEnum type) {
if (contactId != null) {
if (!ValidationUtils.validateContactId(contactId)) {
- log.info("contact info is invalid.");
+ log.info("contact is invalid.");
ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CONTACT, type.getValue());
return Either.right(errorResponse);
}
@@ -247,6 +282,48 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
return Either.left(false);
}
+
+ public Either<Boolean, ResponseFormat> validateConformanceLevel(String componentId, ComponentTypeEnum componentTypeEnum, String userId) {
+ log.trace("validate conformance level");
+
+ if (componentTypeEnum != ComponentTypeEnum.SERVICE) {
+ log.error("conformance level validation for non service component, id {}", componentId);
+ 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, id {}, userId {}", componentId, userId);
+ return Either.right(resp.right().value());
+ }
+
+ ComponentParametersView filter = new ComponentParametersView(true);
+ Either<Component, ResponseFormat> eitherComponent = validateComponentExists(componentId, componentTypeEnum, filter);
+ if (eitherComponent.isRight()) {
+ log.error("can't validate conformance level, component not found, id {}", componentId);
+ BeEcompErrorManager.getInstance().logBeComponentMissingError("validateConformanceLevel", componentTypeEnum.getValue(), componentId);
+ return Either.right(eitherComponent.right().value());
+ }
+
+ Component component = eitherComponent.left().value();
+ if (component.getConformanceLevel() == null || "".equals(component.getConformanceLevel())) {
+ log.error("component conformance level property is null or empty, id {}", componentId);
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
+ return Either.right(errorResponse);
+ }
+
+ String configConformanceLevel = ConfigurationManager.getConfigurationManager().getConfiguration().getMinToscaConformanceLevel();
+ Boolean result = true;
+ if (CommonBeUtils.conformanceLevelCompare(component.getConformanceLevel(), configConformanceLevel) < 0) {
+ log.error("invalid asset conformance level, id {}, asset conformanceLevel {}, config conformanceLevel {}", componentId, component.getConformanceLevel(), configConformanceLevel);
+ 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();
@@ -341,7 +418,7 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
if (ComponentTypeEnum.RESOURCE.equals(component.getComponentType())) {
return Either.left(true);
}
- log.debug("validate PROJECT_CODE name ");
+ log.debug("validate ProjectCode name ");
String projectCode = component.getProjectCode();
if (!ValidationUtils.validateStringNotEmpty(projectCode)) {
@@ -452,9 +529,7 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
* @return
*/
public <R extends Component> Either<R, StorageOperationStatus> getComponent(String componentId, ComponentTypeEnum componentTypeEnum) {
- ComponentOperation componentOperation = getComponentOperation(componentTypeEnum);
- Either<R, StorageOperationStatus> eitherComponent = componentOperation.getComponent(componentId, false);
- return eitherComponent;
+ return toscaOperationFacade.getToscaElement(componentId);
}
public Either<CapReqDef, ResponseFormat> getRequirementsAndCapabilities(String componentId, ComponentTypeEnum componentTypeEnum, String userId) {
@@ -463,103 +538,52 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
if (resp.isRight()) {
return Either.right(resp.right().value());
}
-
- Map<String, List<CapabilityDefinition>> capabilities = new HashMap<>();
- Map<String, List<RequirementDefinition>> requirements = new HashMap<>();
- Either<CapReqDef, ResponseFormat> eitherRet;
- ComponentOperation componentOperation = getComponentOperation(componentTypeEnum);
- Either<Component, ResponseFormat> eitherComponent = validateComponentExists(componentId, componentTypeEnum, false, true);
+ 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()) {
- Either<Map<String, List<CapabilityDefinition>>, TitanOperationStatus> eitherCapabilities = componentOperation.getCapabilities(eitherComponent.left().value(), componentTypeEnum.getNodeType(), false);
- if (eitherCapabilities.isRight()) {
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
- eitherRet = Either.right(errorResponse);
- } else {
- Either<Map<String, List<RequirementDefinition>>, TitanOperationStatus> eitherRequirements = componentOperation.getRequirements(eitherComponent.left().value(), componentTypeEnum.getNodeType(), false);
- if (eitherRequirements.isRight()) {
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
- eitherRet = Either.right(errorResponse);
- } else {
- requirements = eitherRequirements.left().value();
- capabilities = eitherCapabilities.left().value();
- eitherRet = Either.left(new CapReqDef(requirements, capabilities));
- }
- }
+ eitherRet = Either.left(new CapReqDef(eitherComponent.left().value().getRequirements(), eitherComponent.left().value().getCapabilities()));
} else {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeResourceMissingError, "getRequirementsAndCapabilities", componentId);
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) {
-
- long startUser = System.currentTimeMillis();
- Either<User, ResponseFormat> resp = validateUserExists(userId, "get Latest Version Not Abstract Components", false);
- long endUser = System.currentTimeMillis();
- log.debug("Activation time of get user {} ms", (endUser - startUser));
- ResponseFormat responseFormat;
- if (resp.isLeft()) {
-
- List<Component> result = new ArrayList<Component>();
- Set<String> nonProcessesComponents = new HashSet<>();
- nonProcessesComponents.addAll(componentUids);
-
- long startGetComp = System.currentTimeMillis();
- // Read components from cache
- Set<String> filteredComponents = new HashSet<>();
- filteredComponents.addAll(componentUids);
-
- Either<ImmutableTriple<List<Component>, List<Component>, Set<String>>, ActionStatus> allPartialComponents = componentCache.getComponentsForLeftPanel(componentTypeEnum, internalComponentType, filteredComponents);
-
- if (allPartialComponents.isRight()) {
- log.debug("Components was not fetched from cache. Status is {}", allPartialComponents.right().value());
- } else {
- ImmutableTriple<List<Component>, List<Component>, Set<String>> immutableTriple = allPartialComponents.left().value();
- List<Component> processedComponents = immutableTriple.left;
- if (processedComponents != null) {
- result.addAll(processedComponents);
- }
- List<Component> dirtyComponents = immutableTriple.middle;
- if (dirtyComponents != null) {
- result.addAll(dirtyComponents);
- }
-
- Set<String> nonProcessesComponentsFromCache = immutableTriple.right;
- nonProcessesComponents = nonProcessesComponentsFromCache;
- }
- long endGetComp = System.currentTimeMillis();
- log.debug("Activation time of get Comp from cache {} ms", (endGetComp - startGetComp));
-
- // Fecth non cached components
- List<String> componentsUidToFetch = new ArrayList<String>();
- componentsUidToFetch.addAll(nonProcessesComponents);
-
- long startGetCompFromGraph = System.currentTimeMillis();
- if (componentsUidToFetch.size() > 0) {
- log.debug("Number of Components to fetch from graph is {}", componentsUidToFetch.size());
- ComponentOperation componentOperation = getComponentOperation(componentTypeEnum);
- Boolean isHighest = isHighest(highestFilter);
- Either<List<Component>, StorageOperationStatus> nonCheckoutCompResponse = componentOperation.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()));
+ 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.size() > 0) {
+ 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();
}
- long endGetCompFromGraph = System.currentTimeMillis();
- log.debug("Activation time of get Comp from graph {} ms", (endGetCompFromGraph - startGetCompFromGraph));
-
- return Either.left(result);
- } else {
- responseFormat = resp.right().value();
}
-
+ finally{
+ titanDao.commit();
+ }
return Either.right(responseFormat);
}
@@ -580,42 +604,27 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
return isHighest;
}
- public Either<List<Map<String, String>>, ResponseFormat> getLatestVersionNotAbstractComponentsUidOnly(boolean isAbstractAbstract, HighestFilterEnum highestFilter, ComponentTypeEnum componentTypeEnum, String internalComponentType, String userId) {
- Either<User, ResponseFormat> resp = validateUserExists(userId, "get Latest Version Not Abstract Components", false);
- ResponseFormat responseFormat;
- if (resp.isLeft()) {
-
- ComponentOperation componentOperation = getComponentOperation(componentTypeEnum);
- Boolean isHighest = isHighest(highestFilter);
- Either<Collection<ComponentMetadataData>, StorageOperationStatus> nonCheckoutCompResponse = componentOperation.getLatestVersionNotAbstractComponentsMetadataOnly(isAbstractAbstract, isHighest, componentTypeEnum, internalComponentType);
-
- if (nonCheckoutCompResponse.isLeft()) {
- log.debug("Retrived Resource successfully.");
- List<Map<String, String>> res = new ArrayList<>();
-
- // Map<String,String>resMap =
- // nonCheckoutCompResponse.left().value().stream().collect()
- // .collect(Collectors.toMap(
- // p -> p.getMetadataDataDefinition().getUniqueId(),
- // p-> p.getMetadataDataDefinition().getVersion()));
-
- res = nonCheckoutCompResponse.left().value().stream().map(p -> {
- HashMap<String, String> map = new HashMap<>();
- map.put("uid", p.getMetadataDataDefinition().getUniqueId());
- map.put("version", p.getMetadataDataDefinition().getVersion());
- Long lastUpdateDate = p.getMetadataDataDefinition().getLastUpdateDate();
- String lastUpdateDateStr = lastUpdateDate != null ? String.valueOf(lastUpdateDate.longValue()) : "0";
- map.put("timestamp", lastUpdateDateStr);
- return map;
- }).collect(Collectors.toList());
-
- return Either.left(res);
- }
- responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(nonCheckoutCompResponse.right().value()));
- } else {
- responseFormat = resp.right().value();
- }
+ 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);
}
@@ -623,6 +632,7 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
}
+ @SuppressWarnings("unchecked")
public void setToscaArtifactsPlaceHolders(Component component, User user) {
Map<String, ArtifactDefinition> artifactMap = component.getToscaArtifacts();
if (artifactMap == null) {
@@ -645,17 +655,37 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
}
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, true);
+ 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 = component.getToscaArtifacts().values().stream().filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())).findAny().get();
+ toscaArtifact = generateToscaRes.left().value().left().value();
+ component.getToscaArtifacts().put(toscaArtifact.getArtifactLabel(), toscaArtifact);
+ toscaArtifact = component.getToscaArtifacts().values().stream()
+ .filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType()))
+ .findAny().get();
generateToscaRes = saveToscaArtifactPayload(toscaArtifact, component, user, isInCertificationRequest, shouldLock, inTransaction, true);
}
- // TODO if csar artifact fails delete template artifact
+ if (generateToscaRes.isRight()) {
+ return generateToscaRes;
+ }
+ ArtifactDefinition toscaArtifact = generateToscaRes.left().value().left().value();
+ component.getToscaArtifacts().put(toscaArtifact.getArtifactLabel(), toscaArtifact);
return generateToscaRes;
}
@@ -665,23 +695,35 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
}
public Either<ImmutablePair<String, byte[]>, ResponseFormat> getToscaModelByComponentUuid(ComponentTypeEnum componentType, String uuid, EnumMap<AuditingFieldsKeysEnum, Object> additionalParam) {
- // get info
- ComponentOperation componentOperation = getComponentOperation(componentType);
- Either<Component, StorageOperationStatus> latestVersion = componentOperation.getLatestComponentByUuid(componentType.getNodeType(), uuid);
- if (latestVersion.isRight()) {
- ResponseFormat response = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(latestVersion.right().value(), componentType));
+
+ 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(c -> c.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);
-
}
- Component component = latestVersion.left().value();
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, true, false);
+ 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) {
@@ -693,13 +735,10 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
return StorageOperationStatus.NOT_FOUND;
}
- ComponentOperation componentOperation = getComponentOperation(componentType);
-
- Either<Component, StorageOperationStatus> markResourceToDelete = componentOperation.markComponentToDelete(component, true);
- if (markResourceToDelete.isRight()) {
- StorageOperationStatus result = markResourceToDelete.right().value();
- log.debug("failed to mark component {} of type {} for delete. error = {}", uniqueId, componentType, result);
- return result;
+ 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;
@@ -756,43 +795,52 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
protected Either<List<String>, ResponseFormat> deleteMarkedComponents(ComponentTypeEnum componentType) {
- List<String> deletedComponents = new ArrayList<String>();
+// List<String> deletedComponents = new ArrayList<String>();
log.trace("start deleteMarkedComponents");
- ComponentOperation componentOperation = getComponentOperation(componentType);
- Either<List<String>, StorageOperationStatus> resourcesToDelete = componentOperation.getAllComponentsMarkedForDeletion();
- if (resourcesToDelete.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourcesToDelete.right().value(), componentType));
+ 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);
}
-
- for (String resourceToDelete : resourcesToDelete.left().value()) {
-
- Either<String, ResponseFormat> deleteMarkedResource = deleteMarkedComponent(resourceToDelete, componentType);
- if (deleteMarkedResource.isLeft()) {
- deletedComponents.add(deleteMarkedResource.left().value());
- }
- }
-
+// ComponentOperation componentOperation = getComponentOperation(componentType);
+// Either<List<String>, StorageOperationStatus> resourcesToDelete = componentOperation.getAllComponentsMarkedForDeletion();
+// if (resourcesToDelete.isRight()) {
+// ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourcesToDelete.right().value(), componentType));
+// return Either.right(responseFormat);
+// }
+//
+// for (String resourceToDelete : resourcesToDelete.left().value()) {
+//
+// Either<String, ResponseFormat> deleteMarkedResource = deleteMarkedComponent(resourceToDelete, componentType);
+// if (deleteMarkedResource.isLeft()) {
+// deletedComponents.add(deleteMarkedResource.left().value());
+// }
+// }
+// if(deletedComponents.size() == 0) {
+// log.debug("Component list to delete is empty. do commit");
+// titanGenericDao.commit();
+// }
log.trace("end deleteMarkedComponents");
- return Either.left(deletedComponents);
+ return Either.left(deleteMarkedElements.left().value());
}
private Either<String, ResponseFormat> deleteMarkedComponent(String componentToDelete, ComponentTypeEnum componentType) {
Either<String, ResponseFormat> result = null;
- ComponentOperation componentOperation = getComponentOperation(componentType);
NodeTypeEnum compNodeType = componentType.getNodeType();
StorageOperationStatus lockResult = graphLockOperation.lockComponent(componentToDelete, compNodeType);
if (!lockResult.equals(StorageOperationStatus.OK)) {
BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedLockObjectError, "Delete marked component");
- log.debug("Failed to lock component {}. error - {}", componentToDelete, lockResult);
+ log.debug("Failed to lock component {} error - {}", componentToDelete, lockResult);
result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
return result;
}
try {
// check if resource has relations
- Either<Boolean, StorageOperationStatus> isResourceInUse = componentOperation.isComponentInUse(componentToDelete);
+ Either<Boolean, StorageOperationStatus> isResourceInUse = toscaOperationFacade.isComponentInUse(componentToDelete);
if (isResourceInUse.isRight()) {
log.info("deleteMarkedResource - failed to find relations to resource. id = {}, type = {}, error = {}", componentToDelete, componentType, isResourceInUse.right().value().name());
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
@@ -803,7 +851,7 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
if (isResourceInUse.isLeft() && isResourceInUse.left().value() == false) {
// delete resource and its artifacts in one transaction
- Either<List<ArtifactDefinition>, StorageOperationStatus> artifactsRes = componentOperation.getComponentArtifactsForDelete(componentToDelete, compNodeType, true);
+ Either<List<ArtifactDefinition>, StorageOperationStatus> artifactsRes = getComponentArtifactsForDelete(componentToDelete, compNodeType, true);
if (artifactsRes.isRight() && !artifactsRes.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
log.info("failed to check artifacts for component node. id = {}, type = {}, error = {}", componentToDelete, componentType, artifactsRes.right().value().name());
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
@@ -814,8 +862,8 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
if (artifactsRes.isLeft()) {
artifactsToDelete = artifactsRes.left().value();
}
-
- Either<Component, StorageOperationStatus> deleteComponentRes = componentOperation.deleteComponent(componentToDelete, true);
+
+ Either<Component, StorageOperationStatus> deleteComponentRes = toscaOperationFacade.deleteToscaComponent(componentToDelete);
if (deleteComponentRes.isRight()) {
log.info("failed to delete component. id = {}, type = {}, error = {}", componentToDelete, componentType, deleteComponentRes.right().value().name());
ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(deleteComponentRes.right().value());
@@ -846,15 +894,337 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
if (result == null || result.isRight()) {
BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "delete marked component");
log.debug("operation failed. do rollback");
- titanGenericDao.rollback();
+ titanDao.rollback();
} else {
log.debug("operation success. do commit");
- titanGenericDao.commit();
+ titanDao.commit();
}
graphLockOperation.unlockComponent(componentToDelete, compNodeType);
}
return result;
}
+
+ public Either<List<ArtifactDefinition>, StorageOperationStatus> getComponentArtifactsForDelete(String parentId, NodeTypeEnum parentType, boolean inTransacton) {
+ List<ArtifactDefinition> artifacts = new ArrayList<ArtifactDefinition>();
+ 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());
+ }
+
+// if (NodeTypeEnum.Resource.equals(parentType)) {
+// Either<List<ArtifactDefinition>, StorageOperationStatus> interfacesArtifactsForResource = getAdditionalArtifacts(parentId, false, true);
+// if (artifactsResponse.isRight() && !interfacesArtifactsForResource.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
+// log.debug("failed to retrieve interface artifacts for {} {}", parentType, parentId);
+// return Either.right(interfacesArtifactsForResource.right().value());
+// } else if (artifactsResponse.isLeft()) {
+// artifacts.addAll(interfacesArtifactsForResource.left().value());
+// }
+// }
+ return Either.left(artifacts);
+ }
+
+ /**
+ *
+ * @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 generateInputsFromGenericTypeProperties(T component, Resource genericType) {
+
+ List<PropertyDefinition> genericTypeProps = genericType.getProperties();
+ if(null != genericTypeProps) {
+ String genericUniqueId = genericType.getUniqueId();
+ List<InputDefinition> inputs = convertGenericTypePropertiesToInputsDefintion(genericTypeProps, genericUniqueId);
+ if(null != component.getInputs())
+ inputs.addAll(component.getInputs());
+ component.setInputs(inputs);
+ }
+ }
+
+ private List<InputDefinition> convertGenericTypePropertiesToInputsDefintion(List<PropertyDefinition> genericTypeProps, String genericUniqueId) {
+ return genericTypeProps.stream()
+ .map(p -> setInputDefinitionFromProp(p, genericUniqueId))
+ .collect(Collectors.toList());
+ }
+
+ private InputDefinition setInputDefinitionFromProp(PropertyDefinition prop, String genericUniqueId){
+ InputDefinition input = new InputDefinition(prop);
+ input.setOwnerId(genericUniqueId);
+ return input;
+ }
+
+ protected <T extends Component> Either<Resource, ResponseFormat> fetchAndSetDerivedFromGenericType(T component){
+
+ String genericTypeToscaName = component.fetchGenericTypeToscaNameFromConfig();
+ if(null == genericTypeToscaName)
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ Either<Resource, StorageOperationStatus> findLatestGeneric = toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(genericTypeToscaName);
+ if(findLatestGeneric.isRight())
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERIC_TYPE_NOT_FOUND, component.assetType(), genericTypeToscaName));
+ Resource genericTypeResource = findLatestGeneric.left().value();
+ component.setDerivedFromGenericInfo(genericTypeResource);
+ return Either.left(genericTypeResource);
+ }
+
+ 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())){
+ List<PropertyDefinition> genericTypeProps = genericTypeResource.getProperties();
+ List<InputDefinition> genericTypeInputs = null == genericTypeProps? null : convertGenericTypePropertiesToInputsDefintion(genericTypeProps, genericTypeResource.getUniqueId());
+ shouldUpgrade = upgradeToLatestGeneric(clonedComponent, genericTypeInputs);
+ 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 boolean upgradeToLatestGeneric(Component componentToCheckOut, List<InputDefinition> upgradedList) {
+
+ if (!componentToCheckOut.shouldGenerateInputs())
+ return true;
+
+ 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 == upgradedList) {
+ componentToCheckOut.setInputs(currentList);
+ return true;
+ }
+ Map<String, InputDefinition> currentMap = PropertyDataDefinition.listToMapByName(currentList);
+ Map<String, InputDefinition> upgradedMap = PropertyDataDefinition.listToMapByName(upgradedList);
+ Either<Map<String, InputDefinition>, String> eitherMerged = PropertyDataDefinition.mergeProperties(upgradedMap, currentMap, true);
+ if (eitherMerged.isRight()) {
+ log.debug("property {} 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;
+ }
}
+
+
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 89ef6f7e19..1623375926 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
@@ -21,21 +21,32 @@
package org.openecomp.sdc.be.components.impl;
import java.util.ArrayList;
-import java.util.EnumMap;
import java.util.HashMap;
+import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
+import java.util.Optional;
+import java.util.UUID;
import java.util.stream.Collectors;
+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.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.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.GroupDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
import org.openecomp.sdc.be.info.CreateAndAssotiateInfo;
import org.openecomp.sdc.be.model.ArtifactDefinition;
import org.openecomp.sdc.be.model.Component;
@@ -44,25 +55,29 @@ import org.openecomp.sdc.be.model.ComponentInstanceAttribute;
import org.openecomp.sdc.be.model.ComponentInstanceInput;
import org.openecomp.sdc.be.model.ComponentInstanceProperty;
import org.openecomp.sdc.be.model.ComponentParametersView;
-import org.openecomp.sdc.be.model.HeatParameterDefinition;
+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.LifecycleStateEnum;
+import org.openecomp.sdc.be.model.PropertyDefinition.PropertyNames;
+import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
-import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
import org.openecomp.sdc.be.model.operations.api.IComponentInstanceOperation;
-import org.openecomp.sdc.be.model.operations.api.IComponentOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.model.operations.impl.ComponentOperation;
-import org.openecomp.sdc.be.model.operations.impl.GroupOperation;
+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.utils.ComponentValidationUtils;
-import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
+import org.openecomp.sdc.be.resources.data.ComponentInstanceData;
+import org.openecomp.sdc.be.resources.data.PropertyValueData;
import org.openecomp.sdc.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.util.GeneralUtility;
+import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
+import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
import org.openecomp.sdc.common.util.ValidationUtils;
import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
@@ -73,95 +88,86 @@ import fj.data.Either;
public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
- private static final String ARTIFACT_PLACEHOLDER_FILE_EXTENSION = "fileExtension";
-
- static final String HEAT_ENV_NAME = "heatEnv";
- private static final String HEAT_ENV_SUFFIX = "env";
-
private static Logger log = LoggerFactory.getLogger(ComponentInstanceBusinessLogic.class.getName());
@Autowired
private IComponentInstanceOperation componentInstanceOperation;
@Autowired
- private PropertyOperation propertyOperation;
-
- @Autowired
private ArtifactsBusinessLogic artifactBusinessLogic;
-
@Autowired
- private GroupOperation groupOperation;
+ private ApplicationDataTypeCache dataTypeCache;
+
+ 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, true, true, true);
+ 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,
- boolean createNewTransaction) {
-
- Either<User, ResponseFormat> resp = validateUserExists(userId, "create Component Instance", inTransaction);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
-
- Either<Boolean, ResponseFormat> validateValidJson = validateJsonBody(resourceInstance, ComponentInstance.class);
- if (validateValidJson.isRight()) {
- return Either.right(validateValidJson.right().value());
- }
+ public Either<ComponentInstance, ResponseFormat> createComponentInstance(String containerComponentParam, String containerComponentId, String userId, ComponentInstance resourceInstance, boolean inTransaction, boolean needLock) {
- Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
- if (validateComponentType.isRight()) {
- return Either.right(validateComponentType.right().value());
- }
-
- final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
- final ComponentOperation containerOperation = getComponentOperation(containerComponentType);
-
- Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, inTransaction, createNewTransaction);
- if (validateComponentExists.isRight()) {
- return Either.right(validateComponentExists.right().value());
- }
- org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
-
- Either<Boolean, ResponseFormat> validateAllowedToContainCompInstances = validateAllowedToContainCompInstances(containerComponent);
- if (validateAllowedToContainCompInstances.isRight()) {
- return Either.right(validateAllowedToContainCompInstances.right().value());
- }
-
- Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
- if (validateCanWorkOnComponent.isRight()) {
- return Either.right(validateCanWorkOnComponent.right().value());
- }
- if (resourceInstance != null && containerComponentType != null) {
- Either<Boolean, ResponseFormat> validateComponentInstanceParentState = validateComponentInstanceParentState(containerComponentType, resourceInstance);
- if (validateComponentInstanceParentState.isRight()) {
- return Either.right(validateComponentInstanceParentState.right().value());
+ 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();
}
- }
- if (needLock) {
-
- Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "createComponentInstance");
- if (lockComponent.isRight()) {
- return Either.right(lockComponent.right().value());
+ Either<Boolean, ResponseFormat> validateValidJson = validateJsonBody(resourceInstance, ComponentInstance.class);
+ if (validateValidJson.isRight()) {
+ return Either.right(validateValidJson.right().value());
}
- }
-
- Either<ComponentInstance, ResponseFormat> resultOp = null;
- try {
- log.debug("Try to create entry on graph");
- Either<Component, ResponseFormat> eitherResourceName = getOriginComponentNameFromComponentInstance(resourceInstance, inTransaction);
-
- if (eitherResourceName.isRight()) {
- resultOp = Either.right(eitherResourceName.right().value());
- return resultOp;
+
+ Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
+ if (validateComponentType.isRight()) {
+ return Either.right(validateComponentType.right().value());
+ } else {
+ containerComponentType = validateComponentType.left().value();
}
- Component origComponent = eitherResourceName.left().value();
-
- resultOp = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, userId, containerOperation, inTransaction);
+
+ 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();
+ }
+
+ Either<Boolean, ResponseFormat> validateAllowedToContainCompInstances = validateAllowedToContainCompInstances(containerComponent);
+ if (validateAllowedToContainCompInstances.isRight()) {
+ return Either.right(validateAllowedToContainCompInstances.right().value());
+ }
+
+ Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
+ if (validateCanWorkOnComponent.isRight()) {
+ return Either.right(validateCanWorkOnComponent.right().value());
+ }
+
+ if (resourceInstance != null && containerComponentType != null) {
+ 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 {
@@ -181,15 +187,15 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
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();
- final ComponentOperation containerOperation = getComponentOperation(containerComponentType);
- Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, false, true);
+ Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
if (validateComponentExists.isRight()) {
return Either.right(validateComponentExists.right().value());
}
@@ -212,7 +218,6 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
try {
log.debug("Try to create entry on graph");
- NodeTypeEnum containerNodeType = containerComponentType.getNodeType();
Either<Component, ResponseFormat> eitherResourceName = getOriginComponentNameFromComponentInstance(resourceInstance, true);
if (eitherResourceName.isRight()) {
@@ -221,7 +226,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
Component origComponent = eitherResourceName.left().value();
- Either<ComponentInstance, ResponseFormat> result = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, userId, containerOperation, true);
+ 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());
@@ -238,8 +243,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
RequirementCapabilityRelDef requirementCapabilityRelDef = associationInfo;// createRequirementCapabilityrelDef(associationInfo);
-
- Either<RequirementCapabilityRelDef, StorageOperationStatus> resultReqCapDef = componentInstanceOperation.associateResourceInstances(containerComponentId, containerNodeType, requirementCapabilityRelDef, true);
+ Either<RequirementCapabilityRelDef, StorageOperationStatus> resultReqCapDef = toscaOperationFacade.associateResourceInstances(containerComponentId, requirementCapabilityRelDef);
if (resultReqCapDef.isLeft()) {
log.debug("Enty on graph is created.");
RequirementCapabilityRelDef resReqCapabilityRelDef = resultReqCapDef.left().value();
@@ -260,7 +264,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
private Either<Component, ResponseFormat> getOriginComponentNameFromComponentInstance(ComponentInstance componentInstance, boolean inTransaction) {
Either<Component, ResponseFormat> eitherResponse;
- Either<Component, StorageOperationStatus> eitherComponent = getCompInstOriginComponentOperation().getComponent(componentInstance.getComponentUid(), inTransaction);
+ 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));
@@ -270,167 +274,10 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
return eitherResponse;
}
- private Either<String, ResponseFormat> handleNameLogic(Component origComponent, ComponentInstance componentInstance, ComponentTypeEnum containerComponentType, String containerComponentId, boolean isCreate, boolean inTransaction) {
- Either<String, ResponseFormat> eitherResult;
- final ComponentOperation containerOperation = getComponentOperation(containerComponentType);
-
- Either<Integer, StorageOperationStatus> componentInNumberStatus = containerOperation.increaseAndGetComponentInstanceCounter(containerComponentId, true);
-
- if (componentInNumberStatus.isRight()) {
- log.debug("Failed to get component instance number for container component {} ", containerComponentId);
- eitherResult = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(componentInNumberStatus.right().value(), true), "", null));
- } else {
- String resourceInNumber = componentInNumberStatus.left().value().toString();
- eitherResult = Either.left(resourceInNumber);
- }
-
- if (eitherResult.isLeft()) {
- Either<Boolean, ResponseFormat> eitherSpecificLogic;
- if (isCreate) {
- eitherSpecificLogic = handleNameLogicForNewComponentInstance(origComponent, componentInstance, eitherResult.left().value(), containerComponentType, inTransaction);
- } else {
- eitherSpecificLogic = handleNameLogicForUpdatingComponentInstance(origComponent, componentInstance, componentInNumberStatus, containerComponentType, inTransaction);
- }
- if (eitherSpecificLogic.isRight()) {
- eitherResult = Either.right(eitherSpecificLogic.right().value());
- }
- }
- return eitherResult;
- }
-
- private Either<Boolean, ResponseFormat> handleNameLogicForUpdatingComponentInstance(Component origComponent, ComponentInstance componentInstance, Either<Integer, StorageOperationStatus> componentInNumberStatus,
- ComponentTypeEnum containerComponentType, boolean inTransaction) {
- Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
- if (componentInstance.getName() == null || componentInstance.getName().isEmpty()) {
- if (origComponent == null) {
- Either<Component, ResponseFormat> eitherResourceName = getOriginComponentNameFromComponentInstance(componentInstance, inTransaction);
-
- if (eitherResourceName.isRight()) {
- eitherResult = Either.right(eitherResourceName.right().value());
- return eitherResult;
- }
- origComponent = eitherResourceName.left().value();
-
- String resourceName = origComponent.getName();
- String logicalName = componentInstanceOperation.createComponentInstLogicalName(componentInNumberStatus.left().value().toString(), resourceName);
- componentInstance.setName(logicalName);
- if (containerComponentType == ComponentTypeEnum.RESOURCE) {
- Resource resource = (Resource) origComponent;
- componentInstance.setToscaComponentName(resource.getToscaResourceName());
- }
-
- }
- }
-
- Either<Boolean, ResponseFormat> eitherValidation = validateComponentInstanceName(componentInstance.getName(), componentInstance, false);
- if (eitherValidation.isRight()) {
- eitherResult = Either.right(eitherValidation.right().value());
- }
- return eitherResult;
- }
-
- private Either<Boolean, ResponseFormat> handleNameLogicForNewComponentInstance(Component origComponent, ComponentInstance componentInstance, String resourceInNumber, ComponentTypeEnum containerComponentType, boolean inTransaction) {
- Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
-
- if (origComponent == null) {
- Either<Component, ResponseFormat> eitherResourceName = getOriginComponentNameFromComponentInstance(componentInstance, inTransaction);
-
- if (eitherResourceName.isRight()) {
- eitherResult = Either.right(eitherResourceName.right().value());
- return eitherResult;
- }
-
- origComponent = eitherResourceName.left().value();
- }
-
- String resourceName = origComponent.getName();
- componentInstance.setComponentName(resourceName);
- if (componentInstance.getName() == null || componentInstance.getName().isEmpty())
- componentInstance.setName(resourceName);
- String logicalName = componentInstanceOperation.createComponentInstLogicalName(resourceInNumber, componentInstance.getName());
-
- Either<Boolean, ResponseFormat> eitherValidation = validateComponentInstanceName(logicalName, componentInstance, true);
- if (eitherValidation.isRight()) {
- eitherResult = Either.right(eitherValidation.right().value());
- }
- if (containerComponentType == ComponentTypeEnum.RESOURCE) {
- Resource resource = (Resource) origComponent;
- componentInstance.setToscaComponentName(resource.getToscaResourceName());
- }
-
- return eitherResult;
- }
-
- public Either<ComponentInstance, ResponseFormat> createComponentInstanceOnGraph(String containerComponentParam, org.openecomp.sdc.be.model.Component containerComponent, Component origComponent, ComponentInstance componentInstance, String userId,
- boolean needLock, boolean inTransaction) {
-
- Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
- if (validateComponentType.isRight()) {
- return Either.right(validateComponentType.right().value());
- }
-
- final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
- final ComponentOperation containerOperation = getComponentOperation(containerComponentType);
- Either<ComponentInstance, ResponseFormat> resultOp = null;
- if (needLock) {
-
- Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "createComponentInstance");
-
- if (lockComponent.isRight()) {
- return Either.right(lockComponent.right().value());
- }
- }
- try {
- resultOp = createComponentInstanceOnGraph(containerComponent, origComponent, componentInstance, userId, containerOperation, inTransaction);
- return resultOp;
-
- } finally {
- if (needLock)
- unlockComponent(resultOp, containerComponent);
- }
-
- }
-
- private Map<String, String> getExistingEnvVersions(ComponentInstance componentInstance) {
- if (null == componentInstance.getDeploymentArtifacts())
- return null;
- return componentInstance.getDeploymentArtifacts().values()
- //filter env artifacts
- .stream().filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.HEAT_ENV.getType()))
- //map name to version
- .collect(Collectors.toMap(a -> a.getArtifactName(), a -> a.getArtifactVersion()));
- }
-
- private Either<ComponentInstance, ResponseFormat> createComponentInstanceOnGraph(org.openecomp.sdc.be.model.Component containerComponent, Component origComponent, ComponentInstance componentInstance, String userId,
- ComponentOperation containerOperation, boolean inTransaction) {
+ private Either<ComponentInstance, ResponseFormat> createComponentInstanceOnGraph(org.openecomp.sdc.be.model.Component containerComponent, Component originComponent, ComponentInstance componentInstance, User user) {
Either<ComponentInstance, ResponseFormat> resultOp;
- boolean nameAlreadyExist = true;
- String resourceInNumber = "";
- String containerComponentId = containerComponent.getUniqueId();
- ComponentTypeEnum containerComponentType = containerComponent.getComponentType();
- NodeTypeEnum containerNodeType = containerComponentType.getNodeType();
- NodeTypeEnum compInstNodeType = getNodeTypeOfComponentInstanceOrigin();
- while (nameAlreadyExist) {
-
- Either<String, ResponseFormat> eitherNameLogic = handleNameLogic(origComponent, componentInstance, containerComponent.getComponentType(), containerComponent.getUniqueId(), true, inTransaction);
- if (eitherNameLogic.isRight()) {
- return Either.right(eitherNameLogic.right().value());
- } else {
- resourceInNumber = eitherNameLogic.left().value();
- }
-
- Either<Boolean, StorageOperationStatus> isNameExistStatus = componentInstanceOperation.isComponentInstanceNameExist(containerComponentId, containerNodeType, null, componentInstance.getNormalizedName());
- if (isNameExistStatus.isRight()) {
- log.debug("Failed to check if component instance name exists for container component {}", containerComponentId);
- resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_RELATION_NOT_FOUND, componentInstance.getName(), containerComponentId));
- return resultOp;
- }
- nameAlreadyExist = isNameExistStatus.left().value();
-
- }
-
- Either<ComponentInstance, StorageOperationStatus> result = componentInstanceOperation.createComponentInstance(containerComponentId, containerNodeType, resourceInNumber, componentInstance, compInstNodeType, inTransaction);
+ 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());
@@ -439,17 +286,23 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
log.debug("Entity on graph is created.");
- ComponentInstance compInst = result.left().value();
-
- Map<String, String> existingEnvVersions = getExistingEnvVersions(componentInstance);
- Either<ActionStatus, ResponseFormat> addComponentInstanceArtifacts = addComponentInstanceArtifacts(containerComponent, compInst, userId, inTransaction, existingEnvVersions);
+ 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;
}
- resultOp = Either.left(compInst);
+ 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;
}
@@ -459,14 +312,15 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
* @param componentInstance
* @param userId
* @param existingEnvVersions
+ * TODO
* @param containerComponentId
*
* @return
*/
- protected Either<ActionStatus, ResponseFormat> addComponentInstanceArtifacts(org.openecomp.sdc.be.model.Component containerComponent, ComponentInstance componentInstance, String userId, boolean inTransaction,
+ 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);
@@ -478,10 +332,11 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
if (componentDeploymentArtifacts == null) {
return Either.left(ActionStatus.OK);
}
- Map<String, ArtifactDefinition> finalDeploymentArtifacts = new HashMap<String, ArtifactDefinition>(componentDeploymentArtifacts);
+ Map<String, ArtifactDefinition> finalDeploymentArtifacts = new HashMap<String, ArtifactDefinition>();
+
+ Map<String, List<ArtifactDefinition>> groupInstancesArtifacts = new HashMap<>();
+
for (ArtifactDefinition artifact : componentDeploymentArtifacts.values()) {
- // if (artifact.getArtifactType().equalsIgnoreCase(
- // ArtifactTypeEnum.HEAT.getType())) {
String type = artifact.getArtifactType();
if (!(type.equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType()))) {
@@ -489,92 +344,65 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
if (artifact.checkEsIdExist()) {
- Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getDeploymentResourceInstanceArtifacts();
- if (deploymentResourceArtifacts == null) {
- log.debug("no deployment artifacts are configured for resource instance");
- break;
- }
- Map<String, Object> placeHolderData = (Map<String, Object>) deploymentResourceArtifacts.get(HEAT_ENV_NAME);
-
- String envLabel = (artifact.getArtifactLabel() + HEAT_ENV_SUFFIX).toLowerCase();
- Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolder = artifactBusinessLogic.createArtifactPlaceHolderInfo(componentInstance.getUniqueId(), envLabel, placeHolderData, userId, ArtifactGroupTypeEnum.DEPLOYMENT,
- inTransaction);
- if (createArtifactPlaceHolder.isRight()) {
- return Either.right(createArtifactPlaceHolder.right().value());
+ 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 artifactHeatEnv = createArtifactPlaceHolder.left().value();
-
- artifactHeatEnv.setHeatParamsUpdateDate(System.currentTimeMillis());
- artifactHeatEnv.setTimeout(0);
- buildHeatEnvFileName(artifact, artifactHeatEnv, placeHolderData);
-
- // rbetzer - keep env artifactVersion - changeComponentInstanceVersion flow
- handleEnvArtifactVersion(artifactHeatEnv, existingEnvVersions);
- Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact = artifactBusinessLogic.addHeatEnvArtifact(artifactHeatEnv, artifact, componentInstance.getUniqueId(), NodeTypeEnum.ResourceInstance, true);
- 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));
+ ArtifactDefinition artifactDefinition = createHeatEnvPlaceHolder.left().value();
+
+ //put heat
+ finalDeploymentArtifacts.put(artifact.getArtifactLabel(), artifact);
+
+ //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());
}
-
- ArtifactDefinition artifactDefinition = addHeatEnvArtifact.left().value();
- if (artifact.getHeatParameters() != null) {
- List<HeatParameterDefinition> heatEnvParameters = new ArrayList<HeatParameterDefinition>();
- for (HeatParameterDefinition parameter : artifact.getHeatParameters()) {
- HeatParameterDefinition heatEnvParameter = new HeatParameterDefinition(parameter);
- heatEnvParameter.setDefaultValue(parameter.getCurrentValue());
- heatEnvParameters.add(heatEnvParameter);
+ 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;
+ }
}
- artifactDefinition.setHeatParameters(heatEnvParameters);
- }
- finalDeploymentArtifacts.put(envLabel, artifactDefinition);
- // audit
- EnumMap<AuditingFieldsKeysEnum, Object> artifactAuditingFields = artifactBusinessLogic.createArtifactAuditingFields(artifactDefinition, "", artifactDefinition.getUniqueId());
- artifactAuditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentInstance.getName());
- handleAuditing(AuditingActionEnum.ARTIFACT_UPLOAD, containerComponent, userId, artifactAuditingFields, inTransaction);
+ }
}
- // }
}
- componentInstance.setDeploymentArtifacts(finalDeploymentArtifacts);
- return Either.left(ActionStatus.OK);
- }
-
- private void handleAuditing(AuditingActionEnum artifactUpload, org.openecomp.sdc.be.model.Component containerComponent, String userId, EnumMap<AuditingFieldsKeysEnum, Object> artifactAuditingFields, boolean inTransaction) {
-
- Either<User, ActionStatus> user = userAdmin.getUser(userId, inTransaction);
- if (user.isRight()) {
- log.debug("failed to get user properties from graph for audit");
- return;
+ StorageOperationStatus 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.left(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false));
+
}
-
- componentsUtils.auditComponent(componentsUtils.getResponseFormat(ActionStatus.OK), user.left().value(), containerComponent, "", "", AuditingActionEnum.ARTIFACT_UPLOAD, ComponentTypeEnum.RESOURCE_INSTANCE, artifactAuditingFields);
-
- }
-
- private void handleEnvArtifactVersion(ArtifactDefinition heatEnvArtifact, Map<String, String> existingEnvVersions) {
- if (null != existingEnvVersions) {
- String prevVersion = existingEnvVersions.get(heatEnvArtifact.getArtifactName());
- if (null != prevVersion) {
- heatEnvArtifact.setArtifactVersion(prevVersion);
- }
+ 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.left(componentsUtils.convertFromStorageResponse(result));
}
- }
-
- 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 fileName = heatArtifact.getArtifactName().replaceAll("." + heatExtension, "." + envExtension);
- heatEnvArtifact.setArtifactName(fileName);
+ componentInstance.setDeploymentArtifacts(finalDeploymentArtifacts);
+ 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);
+ 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 {}", status);
+ log.debug("Failed to fetch resource: {} artifacts. status is {}", resourceInstance.getComponentUid(), status);
return componentsUtils.convertFromStorageResponseForResourceInstance(status, true);
}
} else {
@@ -595,11 +423,11 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
return ActionStatus.OK;
}
- public Either<ComponentInstance, ResponseFormat> updateComponentInstance(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance componentInstance) {
- return updateComponentInstance(containerComponentParam, containerComponentId, componentInstanceId, userId, componentInstance, false, true, true);
+ 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> updateComponentInstance(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance componentInstance, boolean inTransaction,
+ 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);
@@ -616,7 +444,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
- Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, inTransaction, createNewTransaction);
+ Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
if (validateComponentExists.isRight()) {
return Either.right(validateComponentExists.right().value());
}
@@ -627,28 +455,24 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
return Either.right(validateCanWorkOnComponent.right().value());
}
ComponentTypeEnum instanceType = getComponentType(containerComponentType);
- Either<Boolean, StorageOperationStatus> validateParentStatus = componentInstanceOperation.validateParent(containerComponentId, componentInstanceId, inTransaction);
+ 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;
}
- Boolean isPrentValid = validateParentStatus.left().value();
- if (!isPrentValid) {
+ 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 = getOriginComponentNameFromComponentInstance(componentInstance, inTransaction);
@@ -659,7 +483,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
Component origComponent = eitherResourceName.left().value();
- resultOp = updateComponentInstance(containerComponentId, containerComponentType, origComponent, componentInstanceId, componentInstance, inTransaction);
+ resultOp = updateComponentInstanceMetadata(containerComponent, containerComponentType, origComponent, componentInstanceId, componentInstance, inTransaction);
return resultOp;
} finally {
@@ -690,6 +514,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
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());
@@ -705,14 +530,8 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
ComponentTypeEnum instanceType = getComponentType(containerComponentType);
for (ComponentInstance componentInstance : componentInstanceList) {
- Either<Boolean, StorageOperationStatus> validateParentStatus = componentInstanceOperation.validateParent(containerComponentId, componentInstance.getUniqueId(), true);
- if (validateParentStatus.isRight()) {
- log.debug("Failed to get component instance {} on service {}", componentInstance.getUniqueId(), containerComponentId);
- resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND, componentInstance.getName(), instanceType.getValue().toLowerCase()));
- return resultOp;
- }
- Boolean isPrentValid = validateParentStatus.left().value();
- if (!isPrentValid) {
+ 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;
@@ -728,23 +547,46 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
List<ComponentInstance> updatedList = new ArrayList<>();
- for (ComponentInstance componentInstance : componentInstanceList) {
-
- Either<Component, ResponseFormat> eitherResourceName = getOriginComponentNameFromComponentInstance(componentInstance, true);
-
- if (eitherResourceName.isRight()) {
- resultOp = Either.right(eitherResourceName.right().value());
- return resultOp;
+ 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();
+ 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);
}
- Component origComponent = eitherResourceName.left().value();
-
- Either<ComponentInstance, ResponseFormat> resultSingleUpdate = updateComponentInstance(containerComponentId, containerComponentType, origComponent, componentInstance.getUniqueId(), componentInstance, true);
-
- if (resultSingleUpdate.isRight()) {
- resultOp = Either.right(resultSingleUpdate.right().value());
- return resultOp;
+ containerComponent.setComponentInstances(listForUpdate);
+
+ if(resultOp == null){
+ Either<Component, StorageOperationStatus> updateStatus = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
+ 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);
+ }
+ }
}
- updatedList.add(resultSingleUpdate.left().value());
}
resultOp = Either.left(updatedList);
@@ -757,6 +599,10 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
}
+ 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;
@@ -765,78 +611,56 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
}
- public Either<ComponentInstance, ResponseFormat> updateComponentInstance(String containerComponentParam, org.openecomp.sdc.be.model.Component containerComponent, org.openecomp.sdc.be.model.Component origComponent, String componentInstanceId,
- ComponentInstance componentInstance, boolean needLock, boolean inTransaction) {
- 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();
- if (needLock) {
+ private Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(Component containerComponent, ComponentTypeEnum containerComponentType, org.openecomp.sdc.be.model.Component origComponent, String componentInstanceId,
+ ComponentInstance componentInstance, boolean inTransaction) {
- Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "updateComponentInstance");
- if (lockComponent.isRight()) {
- return Either.right(lockComponent.right().value());
+ Either<ComponentInstance, ResponseFormat> resultOp = null;
+ Optional<ComponentInstance> componentInstanceOptional = null;
+ Either<ImmutablePair<Component, String>, StorageOperationStatus> updateRes = null;
+
+ 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()));
}
}
-
- try {
-
- resultOp = updateComponentInstance(containerComponent.getUniqueId(), containerComponentType, origComponent, componentInstanceId, componentInstance, inTransaction);
- return resultOp;
-
- } finally {
- if (needLock)
- unlockComponent(resultOp, containerComponent);
- }
-
- }
-
- private Either<ComponentInstance, ResponseFormat> updateComponentInstance(String containerComponentId, ComponentTypeEnum containerComponentType, org.openecomp.sdc.be.model.Component origComponent, String componentInstanceId,
- ComponentInstance componentInstance, boolean inTransaction) {
- Either<ComponentInstance, ResponseFormat> resultOp;
-
- Either<String, ResponseFormat> eitherNameLogic = handleNameLogic(origComponent, componentInstance, containerComponentType, containerComponentId, false, inTransaction);
- if (eitherNameLogic.isRight()) {
- return Either.right(eitherNameLogic.right().value());
+ if (resultOp == null) {
+ ComponentInstance oldComponentInstance = componentInstanceOptional.get();
+ String newInstanceName = componentInstance.getName();
+ 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()));
+ }
}
- NodeTypeEnum containerNodeType = containerComponentType.getNodeType();
-
- Either<Boolean, StorageOperationStatus> isNameExistStatus = componentInstanceOperation.isComponentInstanceNameExist(containerComponentId, containerNodeType, componentInstanceId, componentInstance.getNormalizedName());
- if (isNameExistStatus.isRight()) {
- log.debug("Failed to get resource instance names for service {}", containerComponentId);
-
- resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_RELATION_NOT_FOUND, componentInstance.getName(), containerComponentId));
- return resultOp;
+ if (resultOp == null) {
+ updateRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, origComponent, 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));
+ }
}
- Boolean isNameExist = isNameExistStatus.left().value();
- if (isNameExist) {
- containerComponentType = getComponentTypeOfComponentInstance();
- resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), componentInstance.getName()));
- return resultOp;
+ 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());
+ }
+
}
-
- log.debug("Try to update entry on graph");
- Either<ComponentInstance, StorageOperationStatus> result = componentInstanceOperation.updateResourceInstance(containerComponentId, containerNodeType, componentInstanceId, componentInstance, inTransaction);
-
- if (result.isLeft()) {
- log.debug("Enty on graph is updated.");
- ComponentInstance resResourceInfo = result.left().value();
- resultOp = Either.left(resResourceInfo);
- return resultOp;
-
- } else {
- log.debug("Failed to update entry on graph for resource instance {}", componentInstance.getName());
- resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), false), "", componentInstance.getName()));
- return resultOp;
+ if (resultOp == null) {
+ resultOp = Either.left(componentInstanceOptional.get());
}
-
+ return resultOp;
}
- public Either<ComponentInstance, ResponseFormat> deleteComponentInstance(String containerComponentParam, String containerComponentId, String resourceInstanceId, String userId) {
+ 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()) {
@@ -849,7 +673,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
- Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, false, true);
+ Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
if (validateComponentExists.isRight()) {
return Either.right(validateComponentExists.right().value());
}
@@ -865,13 +689,13 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
// validate resource
/*
- * if (!ComponentValidationUtils.canWorkOnComponent(containerComponentId, serviceOperation, userId)) { log.info( "Restricted operation for user {} on service {}", userId, containerComponentId); return Either.right(componentsUtils
+ * 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; }
+ * 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(containerComponentId, resourceInstanceId, containerComponentType);
+ resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType);
return resultOp;
} finally {
@@ -882,37 +706,51 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
}
- private Either<ComponentInstance, ResponseFormat> deleteComponentInstance(String containerComponentId, String resourceInstanceId, ComponentTypeEnum containerComponentType) {
- Either<ComponentInstance, ResponseFormat> resultOp;
- NodeTypeEnum containerNodeType = containerComponentType.getNodeType();
- Either<ComponentInstance, StorageOperationStatus> result = componentInstanceOperation.deleteComponentInstance(containerNodeType, containerComponentId, resourceInstanceId, true);
+ private Either<ComponentInstance, ResponseFormat> deleteComponentInstance(Component containerComponent, String componentInstanceId, ComponentTypeEnum containerComponentType) {
- if (result.isRight()) {
- log.debug("Failed to delete entry on graph for resourceInstance {}", resourceInstanceId);
- ActionStatus status = componentsUtils.convertFromStorageResponse(result.right().value(), containerComponentType);
- // TODO check
- /*
- * if (ActionStatus.SERVICE_NOT_FOUND.equals(status)) { resultOp = Either .right(componentsUtils .getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND)); } else {
- */
- resultOp = Either.right(componentsUtils.getResponseFormat(status, resourceInstanceId));
- // }
- return resultOp;
+ 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()){
+ if(currGroup.getMembers().containsKey(deletedInstance.getName())){
+ currGroup.getMembers().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));
+ }
}
- ComponentInstance resResourceInfo = result.left().value();
- resultOp = Either.left(resResourceInfo);
-
- log.debug("Entry on graph is deleted. Exist more connections on this artifact.");
+ return resultOp;
+ }
- Map<String, ArtifactDefinition> deploymentArtifacts = resResourceInfo.getDeploymentArtifacts();
- if (deploymentArtifacts != null && !deploymentArtifacts.isEmpty()) {
- StorageOperationStatus deleteArtifactsIfNotOnGraph = artifactBusinessLogic.deleteAllComponentArtifactsIfNotOnGraph(new ArrayList<ArtifactDefinition>(deploymentArtifacts.values()));
- if (!deleteArtifactsIfNotOnGraph.equals(StorageOperationStatus.OK)) {
- log.debug("failed to delete artifact payload. status={}", deleteArtifactsIfNotOnGraph.name());
- resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(result.right().value()), resourceInstanceId));
+ 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 resultOp;
+ return foundInstance;
}
public Either<RequirementCapabilityRelDef, ResponseFormat> associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum) {
@@ -929,7 +767,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
- Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(componentId, componentTypeEnum, inTransaction, createNewTransaction);
+ Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null);
if (validateComponentExists.isRight()) {
return Either.right(validateComponentExists.right().value());
}
@@ -949,7 +787,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
try {
- resultOp = associateRIToRIOnGraph(componentId, requirementDef, componentTypeEnum, inTransaction);
+ resultOp = associateRIToRIOnGraph(validateComponentExists.left().value(), requirementDef, componentTypeEnum, inTransaction);
return resultOp;
@@ -959,12 +797,12 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
}
- public Either<RequirementCapabilityRelDef, ResponseFormat> associateRIToRIOnGraph(String componentId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum, boolean inTransaction) {
+ 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 = componentInstanceOperation.associateResourceInstances(componentId, componentTypeEnum.getNodeType(), requirementDef, inTransaction);
+ Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade.associateResourceInstances(containerComponent.getUniqueId(), requirementDef);
if (result.isLeft()) {
log.debug("Enty on graph is created.");
@@ -973,11 +811,11 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
return resultOp;
} else {
- log.debug("Failed to associate node {} with node {}", requirementDef.getFromNode(), requirementDef.getToNode());
+ log.debug("Failed to associate node: {} with node {}", requirementDef.getFromNode(), requirementDef.getToNode());
String fromNameOrId = "";
String toNameOrId = "";
- Either<ComponentInstance, StorageOperationStatus> fromResult = componentInstanceOperation.getResourceInstanceById(requirementDef.getFromNode());
- Either<ComponentInstance, StorageOperationStatus> toResult = componentInstanceOperation.getResourceInstanceById(requirementDef.getToNode());
+ Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById(containerComponent, requirementDef.getFromNode());
+ Either<ComponentInstance, StorageOperationStatus> toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode());
toNameOrId = requirementDef.getFromNode();
fromNameOrId = requirementDef.getFromNode();
@@ -1002,7 +840,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
- Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(componentId, componentTypeEnum, false, true);
+ Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null);
if (validateComponentExists.isRight()) {
return Either.right(validateComponentExists.right().value());
}
@@ -1019,7 +857,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
try {
log.debug("Try to create entry on graph");
- Either<RequirementCapabilityRelDef, StorageOperationStatus> result = componentInstanceOperation.dissociateResourceInstances(componentId, componentTypeEnum.getNodeType(), requirementDef, true);
+ Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade.dissociateResourceInstances(componentId, requirementDef);
if (result.isLeft()) {
log.debug("Enty on graph is created.");
RequirementCapabilityRelDef requirementCapabilityRelDef = result.left().value();
@@ -1028,11 +866,11 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
} else {
- log.debug("Failed to dissocaite node {} from node {}", requirementDef.getFromNode(), requirementDef.getToNode());
+ log.debug("Failed to dissocaite node {} from node {}", requirementDef.getFromNode(), requirementDef.getToNode());
String fromNameOrId = "";
String toNameOrId = "";
- Either<ComponentInstance, StorageOperationStatus> fromResult = componentInstanceOperation.getResourceInstanceById(requirementDef.getFromNode());
- Either<ComponentInstance, StorageOperationStatus> toResult = componentInstanceOperation.getResourceInstanceById(requirementDef.getToNode());
+ Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById(containerComponent, requirementDef.getFromNode());
+ Either<ComponentInstance, StorageOperationStatus> toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode());
toNameOrId = requirementDef.getFromNode();
fromNameOrId = requirementDef.getFromNode();
@@ -1072,26 +910,6 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
return result;
}
- private Either<ComponentInstanceInput, ResponseFormat> updateInputValue(ComponentInstanceInput input, String resourceInstanceId) {
- Either<ComponentInstanceInput, StorageOperationStatus> eitherInput = componentInstanceOperation.updateInputValueInResourceInstance(input, resourceInstanceId, true);
- Either<ComponentInstanceInput, ResponseFormat> result;
- if (eitherInput.isLeft()) {
- log.debug("Input value {} was updated on graph.", input.getValueUniqueUid());
- ComponentInstanceInput instanceInput = eitherInput.left().value();
-
- result = Either.left(instanceInput);
-
- } else {
- log.debug("Failed to update input value {} in resource instance {}", input, resourceInstanceId);
-
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherInput.right().value());
-
- result = Either.right(componentsUtils.getResponseFormat(actionStatus, ""));
-
- }
- return result;
- }
-
private Either<ComponentInstanceAttribute, ResponseFormat> createAttributeValue(ComponentInstanceAttribute attribute, String resourceInstanceId) {
Either<ComponentInstanceAttribute, ResponseFormat> result;
@@ -1161,15 +979,39 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
finally {
if (result == null || result.isRight()) {
- titanGenericDao.rollback();
+ titanDao.rollback();
} else {
- titanGenericDao.commit();
+ titanDao.commit();
}
// unlock resource
graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
}
}
+ // US833308 VLI in service - specific network_role property value logic
+ private StorageOperationStatus concatServiceNameToVLINetworkRolePropertyValue(ToscaOperationFacade toscaOperationFacade, ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceProperty property) {
+ if (StringUtils.isNotEmpty(property.getValue()) && PropertyNames.NETWORK_ROLE.getPropertyName().equalsIgnoreCase(property.getName()) && ComponentTypeEnum.SERVICE == 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<ComponentInstanceProperty, ResponseFormat> createOrUpdatePropertyValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceProperty property, String userId) {
Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
@@ -1184,11 +1026,264 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
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;
+ }
+ 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());
+
+ 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();
+ }
+ }
+
+ 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;
- IComponentOperation componentOperation = getIComponentOperation(componentTypeEnum);
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "create Or Update Property Value", false);
+ if (resp.isRight()) {
+ return Either.right(resp.right().value());
+ }
- if (!ComponentValidationUtils.canWorkOnComponent(componentId, componentOperation, userId)) {
- log.info("Restricted operation for user {} on service {}", userId, componentId);
+ 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;
}
@@ -1201,63 +1296,67 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
try {
String propertyValueUid = property.getValueUniqueUid();
+
if (propertyValueUid == null) {
- Either<Integer, StorageOperationStatus> counterRes = componentInstanceOperation.increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, GraphPropertiesDictionary.PROPERTY_COUNTER, true);
+ Either<Integer, StorageOperationStatus> counterRes = groupInstanceOperation.increaseAndGetGroupInstancePropertyCounter(groupInstanceId);
if (counterRes.isRight()) {
- log.debug("increaseAndGetResourcePropertyCounter failed resource instance {} property {}", resourceInstanceId, property);
+ 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 = componentInstanceOperation.addPropertyValueToResourceInstance(property, resourceInstanceId, index, true);
+ Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation.addPropertyValueToGroupInstance(property, resourceInstanceId, index, true);
if (result.isLeft()) {
- log.debug("Property value was added to resource instance {}", resourceInstanceId);
+ log.trace("Property value was added to resource instance {}", resourceInstanceId);
ComponentInstanceProperty instanceProperty = result.left().value();
resultOp = Either.left(instanceProperty);
- return resultOp;
} else {
- log.debug("Failed to add property value {} to resource instance {}", property, resourceInstanceId);
- // TODO: esofer add error
+ 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, ""));
-
- return resultOp;
}
} else {
- Either<ComponentInstanceProperty, StorageOperationStatus> result = componentInstanceOperation.updatePropertyValueInResourceInstance(property, resourceInstanceId, true);
+ 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);
- return resultOp;
} else {
- log.debug("Failed to update property value {} in resource instance {}", property, resourceInstanceId);
+ 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;
}
}
+ return resultOp;
} finally {
if (resultOp == null || resultOp.isRight()) {
- titanGenericDao.rollback();
+ titanDao.rollback();
} else {
- titanGenericDao.commit();
+ titanDao.commit();
}
// unlock resource
graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
@@ -1280,10 +1379,8 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
return resultOp;
}
- IComponentOperation componentOperation = getIComponentOperation(componentTypeEnum);
-
- if (!ComponentValidationUtils.canWorkOnComponent(componentId, componentOperation, userId)) {
- log.info("Restricted operation for user {} on service {}", userId, componentId);
+ 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;
}
@@ -1318,7 +1415,6 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
} else {
log.debug("Failed to add input value {} to resource instance {}", inputProperty, resourceInstanceId);
- // TODO: esofer add error
ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
@@ -1338,7 +1434,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
return resultOp;
} else {
- log.debug("Failed to update property value {} in reosurce instance {}", inputProperty, resourceInstanceId);
+ log.debug("Failed to update property value {} in resource instance {}", inputProperty, resourceInstanceId);
ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
@@ -1350,9 +1446,9 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
} finally {
if (resultOp == null || resultOp.isRight()) {
- titanGenericDao.rollback();
+ titanDao.rollback();
} else {
- titanGenericDao.commit();
+ titanDao.commit();
}
// unlock resource
graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
@@ -1375,9 +1471,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
return resultOp;
}
- IComponentOperation componentOperation = getIComponentOperation(componentTypeEnum);
-
- if (!ComponentValidationUtils.canWorkOnComponent(serviceId, componentOperation, userId)) {
+ 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;
@@ -1411,9 +1505,9 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
} finally {
if (resultOp == null || resultOp.isRight()) {
- titanGenericDao.rollback();
+ titanDao.rollback();
} else {
- titanGenericDao.commit();
+ titanDao.commit();
}
// unlock resource
graphLockOperation.unlockComponent(serviceId, componentTypeEnum.getNodeType());
@@ -1421,60 +1515,32 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
- private Either<Boolean, ResponseFormat> validateComponentInstanceName(String resourceInstanceName, ComponentInstance resourceInstance, boolean isCreate) {
- ComponentTypeEnum containerComponentType = getComponentTypeOfComponentInstance();
- if (!isCreate) {
- if (resourceInstanceName == null)
- return Either.left(true);
- }
-
- if (!ValidationUtils.validateStringNotEmpty(resourceInstanceName)) {
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_COMPONENT_NAME, containerComponentType.getValue());
-
- return Either.right(errorResponse);
- }
- resourceInstance.setNormalizedName(ValidationUtils.normaliseComponentInstanceName(resourceInstanceName));
- if (!isCreate) {
- if (!ValidationUtils.validateResourceInstanceNameLength(resourceInstanceName)) {
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT, containerComponentType.getValue(), "" + ValidationUtils.COMPONENT_NAME_MAX_LENGTH);
-
- return Either.right(errorResponse);
- }
- if (!ValidationUtils.validateResourceInstanceName(resourceInstanceName)) {
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPONENT_NAME, containerComponentType.getValue());
-
- return Either.right(errorResponse);
- }
- }
-
- return Either.left(true);
-
- }
-
- private Either<Boolean, ResponseFormat> validateComponentInstanceParentState(ComponentTypeEnum containerComponentType, ComponentInstance resourceInstance) {
- String componentId = resourceInstance.getComponentUid();
- Either<? extends Component, StorageOperationStatus> eitherResourceResponse = Either.right(StorageOperationStatus.GENERAL_ERROR);
-
+ private Either<Component, ResponseFormat> getAndValidateOriginComponentOfComponentInstance(ComponentTypeEnum containerComponentType, ComponentInstance componentInstance) {
+
+ Either<Component, ResponseFormat> eitherResponse = null;
ComponentTypeEnum componentType = getComponentTypeByParentComponentType(containerComponentType);
- ComponentOperation componentOperation = getComponentOperation(componentType);
- if (componentOperation != null)
- eitherResourceResponse = componentOperation.getComponent(componentId, true);
-
- Component component = null;
- ResponseFormat errorResponse = null;
- if (eitherResourceResponse.isRight()) {
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(eitherResourceResponse.right().value(), componentType);
+ 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);
- return Either.right(errorResponse);
+ 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);
+ }
}
- component = eitherResourceResponse.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());
- return Either.right(errorResponse);
+ if(eitherResponse == null) {
+ eitherResponse = Either.left(getComponentRes.left().value());
}
- return Either.left(true);
+ return eitherResponse;
}
public Either<ComponentInstance, ResponseFormat> changeComponentInstanceVersion(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance newComponentInstance) {
@@ -1484,6 +1550,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
return Either.right(resp.right().value());
}
+ User user = resp.left().value();
Either<ComponentInstance, ResponseFormat> resultOp = null;
Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
@@ -1492,9 +1559,8 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
- final ComponentOperation containerOperation = getComponentOperation(containerComponentType);
- Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, false, true);
+ Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
if (validateComponentExists.isRight()) {
return Either.right(validateComponentExists.right().value());
}
@@ -1505,25 +1571,12 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
return Either.right(validateCanWorkOnComponent.right().value());
}
- Either<Boolean, StorageOperationStatus> validateParentStatus = componentInstanceOperation.validateParent(containerComponentId, componentInstanceId, false);
- if (validateParentStatus.isRight()) {
- log.debug("Failed to get resource instance {} on service {}", componentInstanceId, containerComponentId);
- resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND, componentInstanceId));
- return resultOp;
- }
- Boolean isPrentValid = validateParentStatus.left().value();
- if (!isPrentValid) {
+ 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;
-
}
- Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = componentInstanceOperation.getResourceInstanceById(componentInstanceId);
- if (resourceInstanceStatus.isRight()) {
- log.debug("Failed to get resource instance {} on service {}", componentInstanceId, containerComponentId);
- resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND, componentInstanceId));
- return resultOp;
- }
ComponentInstance currentResourceInstance = resourceInstanceStatus.left().value();
Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "changeComponentInstanceVersion");
@@ -1538,43 +1591,24 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
String resourceId = newComponentInstance.getComponentUid();
- if (!getCompInstOriginComponentOperation().isComponentExist(resourceId)) {
- log.debug("resource {} not found.", resourceId);
- resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, ""));
+ 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;
}
-
- // esofer - before deleting component instance, we should keep the
- // groups which holds this instance
- List<String> groupsToRevert = new ArrayList<>();
- Either<List<String>, StorageOperationStatus> associatedGroups = groupOperation.getAssociatedGroupsToComponentInstance(componentInstanceId, true);
- if (associatedGroups.isRight()) {
- StorageOperationStatus status = associatedGroups.right().value();
- if (status != StorageOperationStatus.OK) {
- BeEcompErrorManager.getInstance().logInternalFlowError("ChangeComponentInstanceVersion", "Failed to getch groups of current component instance", ErrorSeverity.ERROR);
- resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
- return resultOp;
- }
- } else {
- List<String> groups = associatedGroups.left().value();
- groupsToRevert.addAll(groups);
- }
- // rbetzer - before deleting component instance, retrieve env artifacts to keep track of artifactVersion
-
- Either<Map<String, ArtifactDefinition>, StorageOperationStatus> retrieveEnvArtifacts = componentInstanceOperation.fetchCIEnvArtifacts(componentInstanceId);
- if (retrieveEnvArtifacts.isLeft())
- newComponentInstance.setDeploymentArtifacts(retrieveEnvArtifacts.left().value());
- else if (retrieveEnvArtifacts.right().value() != StorageOperationStatus.OK) {
- log.debug("falied to fetch instance deployment artifacts {}", componentInstanceId );
+ else if (!componentExistsRes.left().value()) {
+ log.debug("The resource {} not found ", resourceId);
+ resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
+ return resultOp;
}
- resultOp = deleteComponentInstance(containerComponentId, componentInstanceId, containerComponentType);
+ List<GroupInstance> groupInstances = currentResourceInstance.getGroupInstances();
+ Map<String, ArtifactDefinition> deploymentArtifacts = currentResourceInstance.getDeploymentArtifacts();
+ resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType);
if (resultOp.isRight()) {
-
log.debug("failed to delete resource instance {}", resourceId);
-
return resultOp;
-
}
Either<Component, ResponseFormat> eitherResourceName = getOriginComponentNameFromComponentInstance(newComponentInstance, true);
@@ -1592,41 +1626,53 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
newComponentInstance.setPosY(resResourceInfo.getPosY());
newComponentInstance.setDescription(resResourceInfo.getDescription());
- resultOp = createComponentInstanceOnGraph(containerComponent, origComponent, newComponentInstance, userId, containerOperation, true);
+ resultOp = createComponentInstanceOnGraph(containerComponent, origComponent, newComponentInstance, user);
if (resultOp.isRight()) {
-
log.debug("failed to create resource instance {}", resourceId);
-
return resultOp;
-
}
- newComponentInstance = resultOp.left().value();
- newComponentInstance.setName(resResourceInfo.getName());
- resultOp = updateComponentInstance(containerComponentId, containerComponentType, origComponent, newComponentInstance.getUniqueId(), newComponentInstance, true);
-
ComponentInstance updatedComponentInstance = resultOp.left().value();
if (resultOp.isRight()) {
log.debug("failed to create resource instance {}", resourceId);
return resultOp;
}
- if (false == groupsToRevert.isEmpty()) {
- StorageOperationStatus associatedGroupsToComponentInstance = groupOperation.associateGroupsToComponentInstance(groupsToRevert, updatedComponentInstance.getUniqueId(), updatedComponentInstance.getName(), true);
- if (associatedGroupsToComponentInstance != StorageOperationStatus.OK) {
+ 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;
}
}
- Either<ComponentInstance, StorageOperationStatus> fullResourceInstance = componentInstanceOperation.getFullComponentInstance(resultOp.left().value(), getNodeTypeOfComponentInstanceOrigin());
- if (fullResourceInstance.isRight()) {
- resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(fullResourceInstance.right().value()), resourceId));
+
+ 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(fullResourceInstance.left().value());
+ resultOp = Either.left(resourceInstanceStatus.left().value());
return resultOp;
} finally {
@@ -1640,9 +1686,48 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
protected abstract ComponentTypeEnum getComponentTypeOfComponentInstance();
- protected abstract ComponentOperation getContainerComponentOperation();
+ // 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;
+ }
- protected abstract ComponentOperation getCompInstOriginComponentOperation();
+ 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);
@@ -1658,4 +1743,75 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
+ /**
+ * 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;
+ }
+
+ private Boolean validateInstanceNameUniqueness(Component containerComponent, ComponentInstance oldComponentInstance, String newInstanceName) {
+ Boolean isUnique = true;
+ String newInstanceNormalizedName = ValidationUtils.normalizeComponentInstanceName(newInstanceName);
+ if (!oldComponentInstance.getNormalizedName().equals(newInstanceNormalizedName)) {
+ Optional<ComponentInstance> foundComponentInstance = containerComponent.getComponentInstances().stream().filter(ci -> ci.getNormalizedName().equals(newInstanceNormalizedName)).findFirst();
+ if (foundComponentInstance.isPresent()) {
+ isUnique = false;
+ }
+ if (isUnique) {
+ foundComponentInstance = containerComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().endsWith(newInstanceNormalizedName)).findFirst();
+ if (foundComponentInstance.isPresent()) {
+ isUnique = false;
+ }
+ }
+ }
+ return isUnique;
+ }
+
+ 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;
+ }
}
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 6cebc7dd53..e8c04c22c1 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
@@ -110,6 +110,9 @@ public class CompositionBusinessLogic {
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;
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 226225a07c..9c5cefb24c 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
@@ -87,7 +87,7 @@ public class ConsumerBusinessLogic extends BaseBusinessLogic {
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);
+ 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);
@@ -123,7 +123,7 @@ public class ConsumerBusinessLogic extends BaseBusinessLogic {
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());
+ 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);
@@ -132,7 +132,7 @@ public class ConsumerBusinessLogic extends BaseBusinessLogic {
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());
+ 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);
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 badb257a80..ae6237897a 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
@@ -22,16 +22,20 @@ package org.openecomp.sdc.be.components.impl;
import java.io.ByteArrayInputStream;
import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
+import java.util.stream.Collectors;
import org.apache.commons.lang3.tuple.ImmutablePair;
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.impl.ComponentsUtils;
+import org.openecomp.sdc.be.tosca.CsarUtils;
import org.openecomp.sdc.common.util.GeneralUtility;
import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
@@ -55,22 +59,74 @@ public class CsarValidationUtils {
public static final String TOSCA_META_ENTRY_DEFINITIONS = "Entry-Definitions";
- public final static 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 = "Artifacts/";
-
public static final String TOSCA_CSAR_EXTENSION = ".csar";
-
+/**
+ * Validates Csar
+ * @param csar
+ * @param csarUUID
+ * @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);
- return validateTOSCAMetadataFile(csar, csarUUID, componentsUtils);
+ 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) {
@@ -83,7 +139,7 @@ public class CsarValidationUtils {
try {
props.load(new ByteArrayInputStream(toscaMetaBytes));
} catch (IOException e) {
- log.debug("TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}", csarUUID);
+ 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));
}
@@ -110,39 +166,39 @@ public class CsarValidationUtils {
}
public static Either<ImmutablePair<String, String>, ResponseFormat> getArtifactsMeta(Map<String, byte[]> csar, String csarUUID, ComponentsUtils componentsUtils) {
-
- if (!csar.containsKey(ARTIFACTS + ARTIFACTS_METADATA_FILE)) {
+
+ 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(ARTIFACTS + ARTIFACTS_METADATA_FILE);
+ byte[] artifactsMetaBytes = csar.get(CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE);
if (artifactsMetaBytes == null) {
- log.debug("Entry-Definitions {} file not found in csar, csar ID {}", ARTIFACTS + ARTIFACTS_METADATA_FILE, csarUUID);
- BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions " + ARTIFACTS + 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, ARTIFACTS + ARTIFACTS_METADATA_FILE));
+ 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>(ARTIFACTS + ARTIFACTS_METADATA_FILE, artifactsFileContents));
+ 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 artifactName, ComponentsUtils componentsUtils) {
- if (!csar.containsKey(ARTIFACTS + artifactName)) {
+ 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, ARTIFACTS + artifactName, csarUUID));
+ 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: {}", ARTIFACTS + artifactName, csarUUID);
- byte[] artifactFileBytes = csar.get(ARTIFACTS + artifactName);
+ 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 {}", ARTIFACTS + artifactName, csarUUID);
- BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions " + ARTIFACTS + artifactName + " 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, ARTIFACTS + artifactName, csarUUID));
+ 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));
@@ -182,7 +238,7 @@ public class CsarValidationUtils {
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);
+ 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));
}
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 5ebb86f1ba..958adc0eef 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
@@ -29,17 +29,27 @@ import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Predicate;
+import java.util.stream.Collectors;
+import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
+import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
+import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
+import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
import org.openecomp.sdc.be.datamodel.api.CategoryTypeEnum;
import org.openecomp.sdc.be.datamodel.utils.NodeTypeConvertUtils;
+import org.openecomp.sdc.be.datatypes.components.ComponentMetadataDataDefinition;
+import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.AssetTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.model.ArtifactType;
import org.openecomp.sdc.be.model.Component;
@@ -48,6 +58,7 @@ 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;
@@ -56,15 +67,25 @@ import org.openecomp.sdc.be.model.category.GroupingDefinition;
import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
import org.openecomp.sdc.be.model.operations.api.IElementOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.model.operations.impl.ComponentOperation;
+import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
+import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
+import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
+import org.openecomp.sdc.be.resources.data.ResourceMetadataData;
+import org.openecomp.sdc.be.resources.data.ServiceMetadataData;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.category.CategoryData;
+import org.openecomp.sdc.be.resources.data.category.SubCategoryData;
+import org.openecomp.sdc.be.ui.model.UiCategories;
import org.openecomp.sdc.be.user.Role;
import org.openecomp.sdc.be.user.UserBusinessLogic;
+import org.openecomp.sdc.common.datastructure.Wrapper;
import org.openecomp.sdc.common.util.ValidationUtils;
import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import com.thinkaurelius.titan.core.TitanGraph;
+
import fj.data.Either;
@org.springframework.stereotype.Component("elementsBusinessLogic")
@@ -198,10 +219,8 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
}
private Either<Map<String, List<? extends Component>>, ResponseFormat> handleFollowedCertifiedServices(Set<DistributionStatusEnum> distStatus) {
- Map<String, Object> propertiesToMatch = new HashMap<>();
- propertiesToMatch.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFIED.name());
- Either<Set<Service>, StorageOperationStatus> services = serviceOperation.getCertifiedServicesWithDistStatus(propertiesToMatch, distStatus, false);
+ Either<List<Service>, StorageOperationStatus> services = toscaOperationFacade.getCertifiedServicesWithDistStatus(distStatus);
if (services.isLeft()) {
Map<String, List<? extends Component>> result = new HashMap<String, List<? extends Component>>();
List<Service> list = new ArrayList<>();
@@ -216,43 +235,37 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
private Either<Map<String, List<? extends Component>>, ResponseFormat> handleTester(String userId) {
Set<LifecycleStateEnum> lifecycleStates = new HashSet<LifecycleStateEnum>();
lifecycleStates.add(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
- Either<List<Resource>, StorageOperationStatus> resources = resourceOperation.getTesterFollowed(userId, lifecycleStates, false);
-
- if (resources.isLeft()) {
- Either<List<Service>, StorageOperationStatus> services = serviceOperation.getTesterFollowed(userId, lifecycleStates, false);
- if (services.isLeft()) {
- Map<String, List<? extends Component>> result = new HashMap<String, List<? 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())));
- }
+ lifecycleStates.add(LifecycleStateEnum.READY_FOR_CERTIFICATION);
+ Either<Map<String, List<? extends Component>>, ResponseFormat> result = getFollowedResourcesAndServices(null, lifecycleStates, null);
+
+ return result;
}
private Either<Map<String, List<? extends Component>>, ResponseFormat> getFollowedResourcesAndServices(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates) {
- Either<List<Resource>, StorageOperationStatus> resources = resourceOperation.getFollowed(userId, lifecycleStates, lastStateStates, false);
-
- if (resources.isLeft()) {
- Either<List<Service>, StorageOperationStatus> services = serviceOperation.getFollowed(userId, lifecycleStates, lastStateStates, false);
- if (services.isLeft()) {
- Map<String, List<? extends Component>> result = new HashMap<String, List<? extends Component>>();
- result.put("services", services.left().value());
- result.put("resources", resources.left().value());
- return Either.left(result);
+
+ try {
+ Either<List<Resource>, StorageOperationStatus> resources = toscaOperationFacade.getFollowed(userId, lifecycleStates, lastStateStates, ComponentTypeEnum.RESOURCE);
+
+ if (resources.isLeft()) {
+ Either<List<Service>, StorageOperationStatus> services = toscaOperationFacade.getFollowed(userId, lifecycleStates, lastStateStates, ComponentTypeEnum.SERVICE);
+ if (services.isLeft()) {
+ Map<String, List<? extends Component>> result = new HashMap<String, List<? 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(services.right().value())));
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resources.right().value())));
}
- } else {
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resources.right().value())));
+ } finally {
+ titanDao.commit();
}
}
private Either<Map<String, List<? extends Component>>, ResponseFormat> getFollowedProducts(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates) {
- Either<List<Product>, StorageOperationStatus> products = productOperation.getFollowed(userId, lifecycleStates, lastStateStates, false);
+ Either<List<Product>, StorageOperationStatus> products = toscaOperationFacade.getFollowed(userId, lifecycleStates, lastStateStates, ComponentTypeEnum.PRODUCT);
if (products.isLeft()) {
Map<String, List<? extends Component>> result = new HashMap<String, List<? extends Component>>();
result.put("products", products.left().value());
@@ -393,10 +406,6 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
String origSubCategoryName = subCategoryName;
User user = new User();
- /*
- * if (userId == null) { user.setUserId("UNKNOWN"); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName,
- * auditingAction, componentType); return Either.right(responseFormat); }
- */
Either<User, ResponseFormat> validateUser = validateUserExists(userId, "createSubCategory", false);
if (validateUser.isRight()) {
log.debug("Validation of user failed, userId {}", userId);
@@ -720,6 +729,49 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
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) {
@@ -800,7 +852,7 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
// validate user exists
if (userId == null) {
- log.debug("User id is null");
+ log.debug("UserId is null");
return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION));
}
@@ -938,19 +990,17 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
}
Map<String, List<? extends Component>> resMap = new HashMap<>();
- Either<List<Resource>, StorageOperationStatus> resResources = resourceOperation.getResourceCatalogData(false);
+ Either<List<Resource>, StorageOperationStatus> resResources = toscaOperationFacade.getCatalogComponents(ComponentTypeEnum.RESOURCE);
if (resResources.isLeft()) {
- Either<List<Service>, StorageOperationStatus> resServices = serviceOperation.getServiceCatalogData(false);
+ Either<List<Service>, StorageOperationStatus> resServices = toscaOperationFacade.getCatalogComponents(ComponentTypeEnum.SERVICE);
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", resProducts.left().value());
- return Either.left(resMap);
- } else {
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resProducts.right().value())));
- }
+ // 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())));
}
@@ -971,11 +1021,14 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
}
if (filters == null || filters.isEmpty()) {
- return getCatalogComponentsByAssetType(assetTypeEnum);
+ Either<List<Component>, StorageOperationStatus> componentsList = toscaOperationFacade.getCatalogComponents(assetTypeEnum);
+ if(componentsList.isRight()) {
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(componentsList.right().value())));
+ }
+ return Either.left(componentsList.left().value());
}
- ComponentOperation componentOperation = getComponentOperation(assetTypeEnum);
- Either<List<Component>, StorageOperationStatus> result = componentOperation.getFilteredComponents(filters, false);
+ Either<List<Component>, StorageOperationStatus> result = getFilteredComponents(filters, assetTypeEnum, false);
if (result.isRight()) {// category hierarchy mismatch or
// category/subCategory/distributionStatus not
@@ -990,46 +1043,51 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
return Either.left(result.left().value());
}
- public Either<List<? extends Component>, ResponseFormat> getCatalogComponentsByAssetType(ComponentTypeEnum assetTypeEnum) {
+ private Either<List<Component>, StorageOperationStatus> getFilteredComponents(Map<FilterKeyEnum, String> filters, ComponentTypeEnum assetType, boolean inTransaction) {
+ Either<List<Component>, StorageOperationStatus> assetResult = null;
+ if(assetType == ComponentTypeEnum.RESOURCE){
+
+ assetResult = getFilteredResouces(filters, inTransaction);
+
+ } else if (assetType == ComponentTypeEnum.SERVICE){
+
+ assetResult = getFilteredServices(filters, inTransaction);
+ }
+ return assetResult;
+ }
- if (assetTypeEnum == null) {
- log.debug("getCatalogComponentsByAssetType: Corresponding ComponentTypeEnum not found");
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
- }
+ private <T> Either<List<T>, StorageOperationStatus> getFilteredServices(Map<FilterKeyEnum, String> filters, boolean inTransaction) {
+
+ Either<List<T>, StorageOperationStatus> components = null;
- switch (assetTypeEnum) {
- case RESOURCE:
+ 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);
+ }
- Either<List<Resource>, StorageOperationStatus> resourceCatalogData = resourceOperation.getResourceCatalogDataVFLatestCertifiedAndNonCertified(false);
- if (resourceCatalogData.isLeft()) {
- log.debug("getCatalogComponentsByAssetType: Resource fetching successful");
- return Either.left(resourceCatalogData.left().value());
- } else {
- log.debug("getCatalogComponentsByAssetType: Resource fetching failed");
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceCatalogData.right().value())));
+ 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;
+ }
- case SERVICE:
- Either<List<Service>, StorageOperationStatus> serviceCatalogData = serviceOperation.getServiceCatalogDataLatestCertifiedAndNotCertified(false);
- if (serviceCatalogData.isLeft()) {
- log.debug("getCatalogComponentsByAssetType: Service fetching successful");
- return Either.left(serviceCatalogData.left().value());
- } else {
- log.debug("getCatalogComponentsByAssetType: Service fetching failed");
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceCatalogData.right().value())));
- }
- /*
- * case PRODUCT: Either<List<Product>, StorageOperationStatus> resCatalogData = productOperation.getProductCatalogData(false); if(resCatalogData.isLeft()){ log. debug("getCatalogComponentsByAssetType: Product fetching successful" );
- * return Either.left(resCatalogData.left().value()); }else { log. debug("getCatalogComponentsByAssetType: Product fetching failed" ); return Either.right(componentsUtils .getResponseFormat(componentsUtils.convertFromStorageResponse(
- * resCatalogData.right().value()))); }
- */
- default:
- log.debug("Invalid Asset Type");
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
+ 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());
}
- // TODO new story Tal
public Either<List<? extends Component>, ResponseFormat> getCatalogComponentsByUuidAndAssetType(String assetType, String uuid) {
if (assetType == null || assetType == null) {
@@ -1044,40 +1102,15 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
}
- switch (assetTypeEnum) {
-
- case RESOURCE:
- Either<List<Resource>, StorageOperationStatus> resourceListByUuid = resourceOperation.getLatestResourceByUuid(uuid, false);
-
- if (resourceListByUuid.isLeft()) {
- log.debug("getCatalogComponentsByUuidAndAssetType: Resource fetching successful");
- return Either.left(resourceListByUuid.left().value());
- }
-
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(resourceListByUuid.right().value());
- log.debug("getCatalogComponentsByUuidAndAssetType: Resource fetching failed");
- return Either.right(componentsUtils.getResponseFormat(actionStatus));
-
- case SERVICE:
- Either<List<Service>, StorageOperationStatus> serviceCatalogData = serviceOperation.getLatestServiceByUuid(uuid, false);
-
- if (serviceCatalogData.isLeft()) {
- log.debug("getCatalogComponentsByUuidAndAssetType: Service fetching successful");
- return Either.left(serviceCatalogData.left().value());
- }
-
+ Either<List<Component>, StorageOperationStatus> componentsListByUuid = toscaOperationFacade.getComponentListByUuid(uuid, null);
+ if(componentsListByUuid.isRight()) {
log.debug("getCatalogComponentsByUuidAndAssetType: Service fetching failed");
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceCatalogData.right().value())));
- // case Product is for future US
- /*
- * case PRODUCT: Either<List<Product>, StorageOperationStatus> resCatalogData = productOperation.getProductCatalogData(false); if(resCatalogData.isLeft()){ log. debug("getCatalogComponentsByAssetType: Product fetching successful" ); return
- * Either.left(resCatalogData.left().value()); }else { log. debug("getCatalogComponentsByAssetType: Product fetching failed" ); return Either.right(componentsUtils .getResponseFormat(componentsUtils.convertFromStorageResponse(
- * resCatalogData.right().value()))); }
- */
- default:
- log.debug("Invalid Asset Type");
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(componentsListByUuid.right().value(), ComponentTypeEnum.SERVICE);
+ return Either.right(componentsUtils.getResponseFormat(actionStatus, uuid));
}
+
+ log.debug("getCatalogComponentsByUuidAndAssetType: " + assetTypeEnum.getValue() + "Service fetching successful");
+ return Either.left(componentsListByUuid.left().value());
}
public List<String> getAllComponentTypesParamNames() {
@@ -1121,5 +1154,228 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
}
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 fetchByResourceType(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> fetchByResourceType(String resourceType, boolean inTransaction) {
+ List<Component> components = null;
+ StorageOperationStatus status;
+ Wrapper<StorageOperationStatus> statusWrapper = new Wrapper<>();
+ Either<List<Component>, StorageOperationStatus> result;
+ try {
+
+ Either<List<Component>, StorageOperationStatus> getResources = toscaOperationFacade.fetchByResourceType(resourceType); //titanGenericDao.getByCriteria(nodeType, props, clazz);
+ 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);
+ }
}
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 3b4528d3a3..ba08f11928 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,9 +20,11 @@
package org.openecomp.sdc.be.components.impl;
+import java.io.IOException;
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;
@@ -34,11 +36,21 @@ import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
+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.codehaus.jackson.JsonGenerationException;
+import org.codehaus.jackson.map.JsonMappingException;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.jsongraph.utils.JsonParserUtils;
import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
+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.info.ArtifactDefinitionInfo;
@@ -48,29 +60,42 @@ import org.openecomp.sdc.be.model.ArtifactDefinition;
import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.ComponentInstance;
import org.openecomp.sdc.be.model.ComponentParametersView;
+import org.openecomp.sdc.be.model.DataTypeDefinition;
import org.openecomp.sdc.be.model.GroupDefinition;
+import org.openecomp.sdc.be.model.GroupInstance;
+import org.openecomp.sdc.be.model.GroupInstanceProperty;
import org.openecomp.sdc.be.model.GroupProperty;
import org.openecomp.sdc.be.model.GroupTypeDefinition;
+import org.openecomp.sdc.be.model.PropertyDefinition;
+import org.openecomp.sdc.be.model.PropertyDefinition.GroupInstancePropertyValueUpdateBehavior;
+import org.openecomp.sdc.be.model.PropertyDefinition.PropertyNames;
+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.Resource;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.model.operations.impl.ComponentOperation;
+import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
import org.openecomp.sdc.be.model.operations.impl.GroupOperation;
import org.openecomp.sdc.be.model.operations.impl.GroupTypeOperation;
-import org.openecomp.sdc.be.model.operations.impl.ResourceOperation;
import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.config.EcompErrorName;
import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.JsonSyntaxException;
import fj.data.Either;
@org.springframework.stereotype.Component("groupBusinessLogic")
public class GroupBusinessLogic extends BaseBusinessLogic {
+ private static String ADDING_GROUP = "AddingGroup";
- public static String INITIAL_VERSION = "1";
+ public static final String INITIAL_VERSION = "1";
private static final String CREATE_GROUP = "CreateGroup";
@@ -87,8 +112,15 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
@javax.annotation.Resource
private GroupTypeOperation groupTypeOperation;
- @javax.annotation.Resource
- private GroupOperation groupOperation;
+
+ @Autowired
+ ArtifactsOperations artifactsOperation;
+
+ @Autowired
+ private GroupsOperation groupsOperation;
+ @Autowired
+ private ApplicationDataTypeCache dataTypeCache;
+
/**
*
@@ -113,7 +145,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
* @param inTransaction
* @return
*/
- public Either<GroupDefinition, ResponseFormat> createGroup(String componentId, String userId, ComponentTypeEnum componentType, GroupDefinition groupDefinition, boolean inTransaction) {
+ /*public Either<GroupDefinition, ResponseFormat> createGroup(String componentId, String userId, ComponentTypeEnum componentType, GroupDefinition groupDefinition, boolean inTransaction) {
Either<GroupDefinition, ResponseFormat> result = null;
@@ -142,7 +174,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
componentParametersView.setIgnoreUsers(false);
componentParametersView.setIgnoreComponentInstances(false);
- Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(realComponentId, componentType, componentParametersView, userId, null, user);
+ Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(realComponentId, componentType, componentParametersView);
if (validateComponent.isRight()) {
result = Either.right(validateComponent.right().value());
@@ -164,16 +196,16 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
if (result == null || result.isRight()) {
log.debug("Going to execute rollback on create group.");
- titanGenericDao.rollback();
+ titanDao.rollback();
} else {
log.debug("Going to execute commit on create group.");
- titanGenericDao.commit();
+ titanDao.commit();
}
}
}
- }
+ }*/
private String getComponentTypeForResponse(org.openecomp.sdc.be.model.Component component) {
String componentTypeForResponse = "SERVICE";
@@ -203,7 +235,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
}
List<String> currentArtifacts = deploymentArtifacts.values().stream().map(p -> p.getUniqueId()).collect(Collectors.toList());
- log.debug("The deployment artifacts of component {} are {}", component.getNormalizedName(), deploymentArtifacts);
+ log.debug("The deployment artifacts of component {} are {}" , component.getNormalizedName(), deploymentArtifacts);
if (false == currentArtifacts.containsAll(artifacts)) {
BeEcompErrorManager.getInstance().logInvalidInputError(context, "Not all artifacts belongs to component " + component.getNormalizedName(), ErrorSeverity.INFO);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
@@ -214,43 +246,6 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
}
/**
- * Verify that the artifact members belongs to the component
- *
- * @param component
- * @param artifacts
- * @return
- */
- private Either<List<ArtifactDefinition>, ResponseFormat> getArtifactsBelongsToComponent(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<ArtifactDefinition> resultList = new ArrayList();
-
- for (String artifactId : artifacts) {
- Optional<ArtifactDefinition> groupArtifactOp = deploymentArtifacts.values().stream().filter(p -> p.getUniqueId().equals(artifactId)).findAny();
-
- if (groupArtifactOp.isPresent()) {
- ArtifactDefinition groupArtifact = groupArtifactOp.get();
- resultList.add(groupArtifact);
- } else {
- 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(resultList);
-
- }
-
- /**
* verify that the members are component instances of the component
*
* @param component
@@ -290,67 +285,54 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
}
}
- 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));
- }
+// 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);
}
- public ComponentOperation getComponentOperation(NodeTypeEnum componentType) {
-
- switch (componentType) {
- case Service:
- case ResourceInstance:
- return serviceOperation;
- case Resource:
- return resourceOperation;
- default:
- return null;
- }
- }
-
/**
* Update specific group version
*
@@ -358,7 +340,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
* @param inTransaction
* @return
*/
- public Either<GroupDefinition, StorageOperationStatus> updateGroupVersion(GroupDefinition groupDefinition, boolean inTransaction) {
+ /*public Either<GroupDefinition, StorageOperationStatus> updateGroupVersion(GroupDefinition groupDefinition, boolean inTransaction) {
Either<GroupDefinition, StorageOperationStatus> result = null;
List<String> groupIdsToUpdateVersion = new ArrayList<>();
groupIdsToUpdateVersion.add(groupDefinition.getUniqueId());
@@ -370,7 +352,9 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
result = Either.right(updateGroupVersion.right().value());
}
return result;
- }
+ }*/
+
+
/**
* Update list of groups versions
@@ -379,7 +363,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
* @param inTransaction
* @return
*/
- public Either<List<GroupDefinition>, StorageOperationStatus> updateGroupVersion(List<String> groupsUniqueId, boolean inTransaction) {
+ /*public Either<List<GroupDefinition>, StorageOperationStatus> updateGroupVersion(List<String> groupsUniqueId, boolean inTransaction) {
Either<List<GroupDefinition>, StorageOperationStatus> result = null;
@@ -395,93 +379,396 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
if (result == null || result.isRight()) {
log.debug("Going to execute rollback on create group.");
- titanGenericDao.rollback();
+ titanDao.rollback();
} else {
log.debug("Going to execute commit on create group.");
- titanGenericDao.commit();
+ 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) {
+
+ 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();
+ 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();
+ }
+ 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;
}
/**
- * Update GroupDefinition metadata
- *
+ * Validate and Update Group Property
* @param componentId
+ * @param groupUniqueId
* @param user
- * @param groupId
* @param componentType
- * @param groupUpdate
+ * @param groupPropertiesToUpdate
* @param inTransaction
* @return
*/
- public Either<GroupDefinition, ResponseFormat> updateGroupMetadata(String componentId, User user, String groupUniqueId, ComponentTypeEnum componentType, GroupDefinition groupUpdate, boolean inTransaction) {
-
- Either<GroupDefinition, ResponseFormat> result = null;
+ 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);
+ }
+ }
- // Validate user and validate group belongs to component
- List<GroupDefinition> groups = new ArrayList<>();
- groups.add(groupUpdate);
- Either<Component, ResponseFormat> validateGroupsBeforeUpdate = validateGroupsBeforeUpdate(componentId, user.getUserId(), componentType, groups, inTransaction);
- if (validateGroupsBeforeUpdate.isRight()) {
- result = Either.right(validateGroupsBeforeUpdate.right().value());
- return result;
}
- Component component = validateGroupsBeforeUpdate.left().value();
+ 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());
+ }
+ }
+
+ }
- // Get the GroupDefinition object
- Either<GroupDefinition, StorageOperationStatus> groupStatus = groupOperation.getGroup(groupUniqueId);
- if (groupStatus.isRight()) {
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(groupStatus.right().value(), ComponentTypeEnum.SERVICE), ""));
+ 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);
}
- GroupDefinition currentGroup = groupStatus.left().value();
+ 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));
+ }
- // Validate group type is vfModule
- if (!currentGroup.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)) {
- log.error("Group update metadata: Group type is different then: {}", Constants.DEFAULT_GROUP_VF_MODULE);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_TYPE, groupUpdate.getType());
- return Either.right(responseFormat);
}
+ if (ret.isLeft()) {
+ // Validate min max ect...
+ ret = validatePropertyBusinessLogic(groupPropertiesToUpdate, originalGroup);
+ }
- Either<GroupDefinition, ResponseFormat> validationRsponse = validateAndUpdateGroupMetadata(currentGroup, groupUpdate);
- if (validationRsponse.isRight()) {
- log.info("Group update metadata: validations field.");
- return validationRsponse;
+ 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());
+ }
+
+ }
}
- GroupDefinition groupToUpdate = validationRsponse.left().value();
- // lock resource
- Either<Boolean, ResponseFormat> lockResult = lockComponent(componentId, component, "Update GroupDefinition Metadata");
- if (lockResult.isRight()) {
- return Either.right(lockResult.right().value());
+ 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());
+ }
}
- try {
- Either<GroupDefinition, StorageOperationStatus> updateResponse = groupOperation.updateGroupName(groupUniqueId, groupUpdate.getName(), inTransaction);
- if (updateResponse.isRight()) {
- titanGenericDao.rollback();
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Update GroupDefinition Metadata");
- BeEcompErrorManager.getInstance().logBeSystemError("Update GroupDefinition Metadata");
- log.debug("failed to update sevice {}", groupToUpdate.getUniqueId());
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- titanGenericDao.commit();
- return Either.left(updateResponse.left().value());
- } finally {
- graphLockOperation.unlockComponent(componentId, componentType.getNodeType());
+ 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);
@@ -577,7 +864,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
* @param inTransaction
* @return
*/
- public Either<List<GroupDefinition>, ResponseFormat> associateArtifactsToGroup(String componentId, String userId, ComponentTypeEnum componentType, List<GroupDefinition> groups, boolean shouldLockComp, boolean inTransaction) {
+ /*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;
@@ -634,7 +921,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
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());
+ log.debug("Some of the artifacts already associated to group {}" , groupDefinition.getUniqueId());
return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_ARTIFACT_ALREADY_ASSOCIATED, componentGroup.getName()));
}
}
@@ -661,10 +948,10 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
if (result == null || result.isRight()) {
log.debug("Going to execute rollback on create group.");
- titanGenericDao.rollback();
+ titanDao.rollback();
} else {
log.debug("Going to execute commit on create group.");
- titanGenericDao.commit();
+ titanDao.commit();
}
}
@@ -675,9 +962,9 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
}
}
- }
+ }*/
- public Either<List<GroupDefinition>, ResponseFormat> associateMembersToGroup(String componentId, String userId, ComponentTypeEnum componentType, List<GroupDefinition> groups, boolean shouldLockComp, boolean inTransaction) {
+ /*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;
@@ -739,10 +1026,10 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
if (result == null || result.isRight()) {
log.debug("Going to execute rollback on create group.");
- titanGenericDao.rollback();
+ titanDao.rollback();
} else {
log.debug("Going to execute commit on create group.");
- titanGenericDao.commit();
+ titanDao.commit();
}
}
@@ -753,7 +1040,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
}
}
- }
+ }*/
/**
* associate artifacts to a given group
@@ -778,8 +1065,6 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
return result;
}
- User user = validateUserExists.left().value();
-
// Validate component exist
org.openecomp.sdc.be.model.Component component = null;
String realComponentId = componentId;
@@ -790,85 +1075,88 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
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, userId, null, user);
+ 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();
- // validate we can work on component
- /*
- * Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent( component, userId); if (canWork.isRight()) { result = Either.right(canWork.right().value()); return result; }
- */
- List<GroupDefinition> groups = component.getGroups();
- Optional<GroupDefinition> findAny = groups.stream().filter(p -> p.getUniqueId().equals(groupId)).findAny();
- if (findAny.isPresent()) {
- GroupDefinition group = findAny.get();
- Boolean isBase = null;// Constants.IS_BASE;
- List<GroupProperty> props = group.getProperties();
- 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());
+ 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));
+ } 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()) {
- Either<List<ArtifactDefinition>, ResponseFormat> getArtifacts = getArtifactsBelongsToComponent(component, artifactsIds, GET_GROUP);
- if (getArtifacts.isRight()) {
- log.debug("Faild to find artifacts in group {} under component {}", groupId, component.getUniqueId());
- // result = Either.right(getArtifacts.right().value());
- // return result;
- } else {
-
- List<ArtifactDefinition> artifactsFromComponent = getArtifacts.left().value();
- if (artifactsFromComponent != null && !artifactsFromComponent.isEmpty()) {
- for (ArtifactDefinition artifactDefinition : artifactsFromComponent) {
- ArtifactDefinitionInfo artifactDefinitionInfo = new ArtifactDefinitionInfo(artifactDefinition);
- artifacts.add(artifactDefinitionInfo);
- }
- }
+ 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);
+ }
+ GroupDefinitionInfo resultInfo = new GroupDefinitionInfo(group);
+ resultInfo.setIsBase(isBase);
+ if (!artifacts.isEmpty())
+ resultInfo.setArtifacts(artifacts);
- return result;
+ result = Either.left(resultInfo);
- } else {
- 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;
+ return result;
- }
} finally {
if (false == inTransaction) {
if (result == null || result.isRight()) {
log.debug("Going to execute rollback on create group.");
- titanGenericDao.rollback();
+ titanDao.rollback();
} else {
log.debug("Going to execute commit on create group.");
- titanGenericDao.commit();
+ titanDao.commit();
}
}
@@ -877,6 +1165,21 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
}
+ 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
@@ -895,7 +1198,6 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
result = Either.right(validateUserExists.right().value());
return result;
}
- User user = validateUserExists.left().value();
// Validate component exist
String realComponentId = componentId;
@@ -907,7 +1209,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
componentParametersView.setIgnoreUsers(false);
componentParametersView.setIgnoreComponentInstances(false);
- Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(realComponentId, componentType, componentParametersView, userId, null, user);
+ Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(realComponentId, componentType, componentParametersView);
if (validateComponent.isRight()) {
result = Either.right(validateComponent.right().value());
@@ -945,14 +1247,6 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
return Either.left(component);
}
- private ResponseFormat validateGroupsInComponent(List<GroupDefinition> groups, org.openecomp.sdc.be.model.Component component) {
-
- Function<GroupDefinition, String> getByName = s -> s.getName();
-
- return validateGroupsInComponentByFunc(groups, component, getByName);
-
- }
-
/**
* @param groups
* @param component
@@ -1014,7 +1308,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
* @param inTransaction
* @return
*/
- public Either<List<GroupDefinition>, ResponseFormat> dissociateArtifactsFromGroup(String componentId, String userId, ComponentTypeEnum componentType, List<GroupDefinition> groups, boolean shouldLockComp, boolean inTransaction) {
+ /*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;
@@ -1073,13 +1367,13 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
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());
+ 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());
+ log.debug("No artifact is found under the group {}" , groupDefinition.getUniqueId());
return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_ARTIFACT_ALREADY_DISSOCIATED, componentGroup.getName()));
}
}
@@ -1107,10 +1401,10 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
if (result == null || result.isRight()) {
log.debug("Going to execute rollback on create group.");
- titanGenericDao.rollback();
+ titanDao.rollback();
} else {
log.debug("Going to execute commit on create group.");
- titanGenericDao.commit();
+ titanDao.commit();
}
}
@@ -1121,9 +1415,9 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
}
- }
+ }*/
- public Either<List<GroupDefinition>, ResponseFormat> createGroups(String componentId, String userId, ComponentTypeEnum componentType, List<GroupDefinition> groupDefinitions, boolean shouldLockComp, boolean inTransaction) {
+ /*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;
@@ -1131,9 +1425,9 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
org.openecomp.sdc.be.model.Component component = null;
try {
- if (groupDefinitions != null && false == groupDefinitions.isEmpty()) {
+ if (groupDefinitions != null && !groupDefinitions.isEmpty()) {
- if (shouldLockComp == true && inTransaction == true) {
+ 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.
@@ -1157,7 +1451,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
componentParametersView.setIgnoreUsers(false);
componentParametersView.setIgnoreComponentInstances(false);
- Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(componentId, componentType, componentParametersView, userId, null, user);
+ Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(componentId, componentType, componentParametersView);
if (validateComponent.isRight()) {
result = Either.right(validateComponent.right().value());
@@ -1181,7 +1475,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
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);
+ log.debug("Failed to create group {}." , groupDefinition );
result = Either.right(createGroup.right().value());
return result;
}
@@ -1199,10 +1493,10 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
if (result == null || result.isRight()) {
log.debug("Going to execute rollback on create group.");
- titanGenericDao.rollback();
+ titanDao.rollback();
} else {
log.debug("Going to execute commit on create group.");
- titanGenericDao.commit();
+ titanDao.commit();
}
}
@@ -1219,7 +1513,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
Either<GroupDefinition, ResponseFormat> result = null;
- log.debug("Going to create group {}", groupDefinition);
+ log.trace("Going to create group {}" , groupDefinition);
try {
@@ -1314,10 +1608,10 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
if (result == null || result.isRight()) {
log.debug("Going to execute rollback on create group.");
- titanGenericDao.rollback();
+ titanDao.rollback();
} else {
log.debug("Going to execute commit on create group.");
- titanGenericDao.commit();
+ titanDao.commit();
}
}
@@ -1351,8 +1645,23 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
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));
@@ -1438,7 +1747,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
return counter;
}
- public Either<List<GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesOnGraph(List<GroupDefinition> groups, String resourceSystemName, boolean inTransaction) {
+ 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);
@@ -1451,27 +1760,25 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
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(resourceSystemName, group.getDescription(), counter);
+ 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();
- updateGroupNameRes = groupOperation.updateGroupName(group.getUniqueId(), newGroupName, inTransaction);
- if (updateGroupNameRes.isRight()) {
- log.debug("Failed to update vf module group name for group {} . Status is {} ", oldGroupName, updateGroupNameRes.right().value());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateGroupNameRes.right().value()));
- result = Either.right(responseFormat);
- break;
- }
+ 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) {
+ /*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);
@@ -1497,16 +1804,710 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
if (result == null || result.isRight()) {
log.debug("Going to execute rollback on create group.");
- titanGenericDao.rollback();
+ 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<ArtifactDefinition> artifactsFromComponent = new ArrayList<>();
+ List<String> artifactsIds = group.getArtifacts();
+ if (artifactsIds != null && !artifactsIds.isEmpty()) {
+
+ for(String id: artifactsIds){
+ Either<ArtifactDefinition, StorageOperationStatus> artifactEither = artifactsOperation.getArtifactById(componentInstance.getComponentUid(), id);
+ if (artifactEither.isRight()) {
+ log.debug("Failed to get artifact {} . Status is {} ", id, artifactEither.right().value());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactEither.right().value()));
+ result = Either.right(responseFormat);
+ return result;
+ }
+ artifactsFromComponent.add(artifactEither.left().value());
+ }
+ if (!artifactsFromComponent.isEmpty()) {
+ for (ArtifactDefinition artifactDefinition : artifactsFromComponent) {
+ ArtifactDefinitionInfo artifactDefinitionInfo = new ArtifactDefinitionInfo(artifactDefinition);
+ artifacts.add(artifactDefinitionInfo);
+ }
+ }
+
+
+ }
+ 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.");
- titanGenericDao.commit();
+ 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);
+ }
+
+
+
+
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/HealthCheckBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/HealthCheckBusinessLogic.java
index 81dfc1a256..e535214d70 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/HealthCheckBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/HealthCheckBusinessLogic.java
@@ -39,7 +39,6 @@ import javax.servlet.ServletContext;
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.BeEcompErrorManager.ErrorSeverity;
import org.openecomp.sdc.be.dao.api.IEsHealthCheckDao;
import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
import org.openecomp.sdc.be.impl.WebAppContextWrapper;
@@ -102,7 +101,7 @@ public class HealthCheckBusinessLogic {
lastBeHealthCheckInfos = getBeHealthCheckInfos();
- log.debug("After initializing lastBeHealthCheckInfos :{}", lastBeHealthCheckInfos);
+ log.debug("After initializing lastBeHealthCheckInfos: {}", lastBeHealthCheckInfos);
healthCheckScheduledTask = new HealthCheckScheduledTask();
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 68569ebc3b..66c1868223 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
@@ -20,8 +20,8 @@
package org.openecomp.sdc.be.components.impl;
-import org.openecomp.sdc.be.config.Configuration.DeploymentArtifactTypeConfig;
+import org.openecomp.sdc.be.config.Configuration.ArtifactTypeConfig;
public interface IDeploymentArtifactTypeConfigGetter {
- DeploymentArtifactTypeConfig 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 94a7340ff7..33390e7e98 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
@@ -32,7 +32,6 @@ import java.util.function.Consumer;
import java.util.function.Function;
import org.apache.commons.lang3.StringEscapeUtils;
-import org.apache.commons.lang3.text.translate.CharSequenceTranslator;
import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
import org.openecomp.sdc.be.model.AttributeDefinition;
import org.openecomp.sdc.be.model.HeatParameterDefinition;
@@ -48,6 +47,7 @@ import org.openecomp.sdc.common.util.GsonFactory;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.Constructor;
+import org.yaml.snakeyaml.nodes.Tag;
import org.yaml.snakeyaml.representer.Representer;
import org.yaml.snakeyaml.resolver.Resolver;
@@ -65,13 +65,20 @@ public final class ImportUtils {
private static CustomResolver customResolver = new CustomResolver();
private static class CustomResolver extends Resolver {
+ @Override
protected void addImplicitResolvers() {
- // avoid implicit resolvers
+ // avoid implicit resolvers for strings that can be interpreted as boolean values
+ addImplicitResolver(Tag.STR, EMPTY, "");
+ addImplicitResolver(Tag.STR, NULL, null);
+ addImplicitResolver(Tag.NULL, NULL, "~nN\0");
+ addImplicitResolver(Tag.NULL, EMPTY, null);
+ addImplicitResolver(Tag.YAML, YAML, "!&*");
}
}
+ @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);
+ Map<String, Object> heatData = (Map<String, Object>) new Yaml(new Constructor(), new Representer(), new DumperOptions(), customResolver).load(heatDecodedPayload);
return getHeatParameters(heatData, artifactType);
}
@@ -82,6 +89,7 @@ public final class ImportUtils {
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";
@@ -92,7 +100,6 @@ public final class ImportUtils {
public static final List<String> TOSCA_DEFINITION_VERSIONS = Arrays.asList(new String[] { "tosca_simple_yaml_1_0_0", "tosca_simple_profile_for_nfv_1_0_0", "tosca_simple_yaml_1_0" });
public static final List<String> TOSCA_YML_CSAR_VALID_SUFFIX = Arrays.asList(new String[] { ".yml", ".yaml", ".csar" });
public static final String UI_JSON_PAYLOAD_NAME = "payloadName";
- public static final String ABSTRACT_NODE = "abstact";
}
public enum ResultStatusEnum {
@@ -172,10 +179,7 @@ public final class ImportUtils {
else if (elementType == ToscaElementTypeEnum.ALL) {
if (elementValue != null) {
returnedList.add(String.valueOf(elementValue));
- } else {
- returnedList.add(elementValue);
- }
-
+ }
}
}
@@ -622,7 +626,7 @@ public final class ImportUtils {
Iterator<Entry<String, Object>> propertiesNameValue = jsonProperties.entrySet().iterator();
while (propertiesNameValue.hasNext()) {
Entry<String, Object> propertyNameValue = propertiesNameValue.next();
- if (propertyNameValue.getValue() instanceof Map) {
+ 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());
@@ -695,7 +699,7 @@ public final class ImportUtils {
return null;
}
ToscaPropertyType validType = ToscaPropertyType.isValidType(type);
- if (validType == null || validType.equals(ToscaPropertyType.MAP) || validType.equals(ToscaPropertyType.LIST)) {
+ if (validType == null || validType.equals(ToscaPropertyType.JSON) ||validType.equals(ToscaPropertyType.MAP) || validType.equals(ToscaPropertyType.LIST)) {
return gson.toJson(value);
}
return value.toString();
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
index 129110e13f..3b6e0f7a76 100644
--- 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
@@ -28,7 +28,7 @@ import java.util.stream.Collectors;
import org.apache.commons.codec.binary.Base64;
import org.openecomp.sdc.be.config.ConfigurationManager;
-import org.openecomp.sdc.be.config.Configuration.DeploymentArtifactTypeConfig;
+import org.openecomp.sdc.be.config.Configuration.ArtifactTypeConfig;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.model.ArtifactDefinition;
@@ -79,7 +79,7 @@ public class InformationDeployedArtifactsBusinessLogic {
* 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 = Base64.isBase64(rawPayloadData) ? new String(org.apache.commons.codec.binary.Base64.decodeBase64(rawPayloadData )) : rawPayloadData;
+ * 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()); } } }
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 7d0624440e..8ffee1fd34 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
@@ -21,57 +21,95 @@
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.Optional;
-
+import java.util.UUID;
+import java.util.Map.Entry;
+import java.util.function.BiConsumer;
+import java.util.function.Predicate;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import org.json.simple.JSONObject;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.graph.datatype.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.GraphEdgePropertiesDictionary;
+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.GetInputValueDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.model.CapabilityDefinition;
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.InputDefinition;
+import org.openecomp.sdc.be.model.PropertyDefinition;
import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.be.model.operations.api.IResourceOperation;
+
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
import org.openecomp.sdc.be.model.operations.impl.InputsOperation;
import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
+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.be.resources.data.InputValueData;
import org.openecomp.sdc.be.resources.data.InputsData;
+import org.openecomp.sdc.be.resources.data.PropertyValueData;
+import org.openecomp.sdc.be.resources.data.UniqueIdData;
import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor;
import org.springframework.stereotype.Component;
+import org.yaml.snakeyaml.Yaml;
+import com.google.gson.Gson;
+import com.thinkaurelius.titan.core.TitanVertex;
+
+import fj.Function;
import fj.data.Either;
@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());
- @Autowired
- private IResourceOperation resourceOperation = null;
-
- @javax.annotation.Resource
- private InputsOperation inputsOperation = null;
+
@javax.annotation.Resource
private PropertyOperation propertyOperation = null;
+
@Autowired
private ComponentsUtils componentsUtils;
+
+ private static final String GET_INPUT = "get_input";
+
+ private static String ASSOCIATING_INPUT_TO_PROP = "AssociatingInputToComponentInstanceProperty";
+ private Gson gson = new Gson();
+
/**
* associate inputs to a given component with paging
@@ -82,28 +120,64 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
* @param amount
* @return
*/
- public Either<List<InputDefinition>, ResponseFormat> getInputs(String userId, String componentId, String fromName,
- int amount) {
+ 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());
}
-
- Either<List<InputDefinition>, StorageOperationStatus> inputsEitherRes = inputsOperation
- .getInputsOfComponent(componentId, fromName, amount);
- if (inputsEitherRes.isRight()) {
- if (inputsEitherRes.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
- return Either.left(new ArrayList<InputDefinition>());
- }
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(inputsEitherRes.right().value());
- log.debug("Failed to get inputs under component {}, error: {}", componentId, actionStatus.name());
+
+
+ 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);
- return Either.left(inputsEitherRes.left().value());
+ }
+
+ public Either<List<ComponentInstanceInput>, ResponseFormat> getComponentInstanceInputs(String userId, String componentId, String componentInstanceId,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);
+ 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();
+ Map<String, List<ComponentInstanceInput>> ciInputs = component.getComponentInstancesInputs();
+ if(!ciInputs.containsKey(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));
+ }
+
+ return Either.left(ciInputs.get(componentInstanceId));
}
@@ -116,62 +190,239 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
* @return
*/
- public Either<List<ComponentInstanceProperty>, ResponseFormat> getComponentInstancePropertiesByInputId(
- String userId, String instanceId, String inputId) {
+ 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));
- Either<List<ComponentInstanceProperty>, StorageOperationStatus> propertiesEitherRes = inputsOperation
- .getComponentInstancePropertiesByInputId(instanceId, inputId);
- if (propertiesEitherRes.isRight()) {
+ }
+
+ 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 (propertiesEitherRes.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
- return Either.left(new ArrayList<ComponentInstanceProperty>());
+ if (resp.isRight()) {
+ result = Either.right(resp.right().value());
+ return result;
}
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(propertiesEitherRes.right().value());
- log.debug("Failed to get inputs under component {}, error: {}", instanceId, actionStatus.name());
- return Either.right(componentsUtils.getResponseFormat(actionStatus));
+ 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);
- return Either.left(propertiesEitherRes.left().value());
+ 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;
+ }
+ }
- public Either<List<ComponentInstanceInput>, ResponseFormat> getInputsForComponentInput(String userId,
- String componentId, String inputId) {
- Either<User, ResponseFormat> resp = validateUserExists(userId, "get Inputs by input", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
+ Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, userId);
+ if (canWork.isRight()) {
+ result = Either.right(canWork.right().value());
+ return result;
+ }
- Either<List<ComponentInstanceInput>, StorageOperationStatus> inputsEitherRes = inputsOperation
- .getComponentInstanceInputsByInputId(componentId, inputId);
- if (inputsEitherRes.isRight()) {
+ Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = getAllDataTypes(applicationDataTypeCache);
+ if (allDataTypes.isRight()) {
+ result = Either.right(allDataTypes.right().value());
+ return result;
+ }
- if (inputsEitherRes.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
- return Either.left(new ArrayList<ComponentInstanceInput>());
+ 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);
+
+ 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();
+ }
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(inputsEitherRes.right().value());
- log.debug("Failed to get inputs for input under component {}, error: {}", componentId, actionStatus.name());
- return Either.right(componentsUtils.getResponseFormat(actionStatus));
+ }
+ // unlock resource
+ if (shouldLockComp && component != null) {
+ graphLockOperation.unlockComponent(componentId, componentType.getNodeType());
+ }
+
+ }
- }
- return Either.left(inputsEitherRes.left().value());
+ }
+
+ 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) {
+ 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);
@@ -180,15 +431,15 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
return result;
}
- User user = resp.left().value();
ComponentParametersView componentParametersView = new ComponentParametersView();
componentParametersView.disableAll();
- componentParametersView.setIgnoreGroups(false);
- componentParametersView.setIgnoreArtifacts(false);
+ 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, userId, null, user);
+ Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(componentId, componentType, componentParametersView);
if (validateComponent.isRight()) {
result = Either.right(validateComponent.right().value());
@@ -210,40 +461,120 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
return result;
}
- Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = getAllDataTypes(
- applicationDataTypeCache);
+ 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<List<InputDefinition>, StorageOperationStatus> createInputsResult = this.inputsOperation
- .addInputsToComponent(componentId, componentType.getNodeType(), componentInstInputsMapUi,
- dataTypes);
-
- if (createInputsResult.isRight()) {
- ActionStatus actionStatus = componentsUtils
- .convertFromStorageResponse(createInputsResult.right().value());
- log.debug("Failed to create inputs under component {}, error: {}", componentId, actionStatus.name());
- result = Either.right(componentsUtils.getResponseFormat(actionStatus));
+ Map<String, org.openecomp.sdc.be.model.Component> origComponentMap = new HashMap<>();
+
+
+ //////////////////////////////////////////////////////////////////////////////////////////////////////
+
+ List<InputDefinition> resList = new ArrayList<InputDefinition>();
+ Map<String, List<InputDefinition>> newInputsMap = componentInstInputsMapUi.getComponentInstanceInputsMap();
+ List<ComponentInstance> ciList = component.getComponentInstances();
+ if (newInputsMap != null && !newInputsMap.isEmpty()) {
+ int index = 0;
+ for (Entry<String, List<InputDefinition>> entry : newInputsMap.entrySet()) {
+ List<ComponentInstanceInput> inputsValueToCreate = new ArrayList<>();
+ String compInstId = entry.getKey();
+
+ Optional<ComponentInstance> op = ciList.stream().filter(ci -> ci.getUniqueId().equals(compInstId)).findAny();
+ if(!op.isPresent()){
+ ActionStatus actionStatus = ActionStatus.INVALID_CONTENT;
+ log.debug("Failed to find component instance {} under component {}", compInstId, componentId);
+ result = Either.right(componentsUtils.getResponseFormat(actionStatus));
+ return result;
+ }
+ ComponentInstance ci = op.get();
+ String compInstname = ci.getNormalizedName();
+ Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> origComponentEither = getOriginComponent(ci, origComponentMap);
+ if(origComponentEither.isRight()){
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(origComponentEither.right().value());
+ log.debug("Failed to create inputs value under component {}, error: {}", componentId, actionStatus.name());
+ result = Either.right(componentsUtils.getResponseFormat(actionStatus));
+ return result;
+ }
+ org.openecomp.sdc.be.model.Component origComponent = origComponentEither.left().value();
+
+ List<InputDefinition> inputs = entry.getValue();
+
+ if (inputs != null && !inputs.isEmpty()) {
+
+ for (InputDefinition input : inputs) {
+
+ StorageOperationStatus status = addInputsToComponent(componentId, inputsToCreate, allDataTypes.left().value(), resList, index, inputsValueToCreate, compInstId, compInstname, origComponent, input);
+ if(status != StorageOperationStatus.OK ){
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(status);
+ log.debug("Failed to create inputs value under component {}, error: {}", componentId, actionStatus.name());
+ result = Either.right(componentsUtils.getResponseFormat(actionStatus));
+ return result;
+ }
+
+ }
+ }
+ if(!inputsValueToCreate.isEmpty()){
+ inputsValueToCreateMap.put(compInstId, inputsValueToCreate);
+ }
+ }
+
+ }
+
+ Map<String, List<ComponentInstancePropInput>> newInputsPropsMap = componentInstInputsMapUi.getComponentInstanceProperties();
+ if (newInputsPropsMap != null && !newInputsPropsMap.isEmpty()) {
+
+ result = createInputsFromProperty(component, origComponentMap, inputsToCreate, propertiesToCreateMap, dataTypes, resList, newInputsPropsMap);
+
+ 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();
+
+ }
+
+
+ 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;
-
}
- result = Either.left(createInputsResult.left().value());
-
+
+ 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(inputsValueToCreateMap, component.getUniqueId());
+ 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.");
- titanGenericDao.rollback();
+ titanDao.rollback();
} else {
log.debug("Going to execute commit on create group.");
- titanGenericDao.commit();
+ titanDao.commit();
}
}
@@ -256,9 +587,59 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
}
- public Either<List<InputDefinition>, ResponseFormat> createInputs(String componentId, String userId,
- ComponentTypeEnum componentType, List<InputDefinition> inputsDefinitions, boolean shouldLockComp,
- boolean inTransaction) {
+ private StorageOperationStatus addInputsToComponent(String componentId, Map<String, InputDefinition> inputsToCreate, Map<String, DataTypeDefinition> allDataTypes, List<InputDefinition> resList, int index,
+ List<ComponentInstanceInput> inputsValueToCreate, 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());
+ 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);
+
+ inputsValueToCreate.add(inputValue);
+ input.setInputs(inputsValueToCreate);
+
+ 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;
@@ -268,8 +649,7 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
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);
+ 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;
@@ -285,8 +665,7 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
User user = validateUserExists.left().value();
- Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(
- componentId, componentType, inTransaction, false);
+ 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;
@@ -305,8 +684,9 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
result = Either.right(canWork.right().value());
return result;
}
+ Map<String, InputDefinition> inputs = inputsDefinitions.stream().collect(Collectors.toMap( o -> o.getName(), o -> o));
- result = createInputsInGraph(inputsDefinitions, component, user, inTransaction);
+ result = createInputsInGraph(inputs, component, user, inTransaction);
}
return result;
@@ -317,10 +697,10 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
if (result == null || result.isRight()) {
log.debug("Going to execute rollback on create group.");
- titanGenericDao.rollback();
+ titanDao.rollback();
} else {
log.debug("Going to execute commit on create group.");
- titanGenericDao.commit();
+ titanDao.commit();
}
}
@@ -333,66 +713,99 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
}
- public Either<List<InputDefinition>, ResponseFormat> createInputsInGraph(List<InputDefinition> inputsDefinitions,
- org.openecomp.sdc.be.model.Component component, User user, boolean inTransaction) {
- Either<List<InputDefinition>, ResponseFormat> result;
- List<InputDefinition> inputs = new ArrayList<InputDefinition>();
- for (InputDefinition inputDefinition : inputsDefinitions) {
- // String resourceId, String inputName, InputDefinition
- // newInputDefinition, String userId, boolean inTransaction
- Either<InputDefinition, ResponseFormat> createInput = createInput(component, user,
- component.getComponentType(), inputDefinition.getName(), inputDefinition, inTransaction);
- if (createInput.isRight()) {
- log.debug("Failed to create group {}.", createInput);
- result = Either.right(createInput.right().value());
- return result;
+ public Either<List<InputDefinition>, ResponseFormat> createInputsInGraph(Map<String, InputDefinition> inputs, org.openecomp.sdc.be.model.Component component, User user, boolean inTransaction) {
+
+ List<InputDefinition> resList = inputs.values().stream().collect(Collectors.toList());
+ Either<List<InputDefinition>, ResponseFormat> result = Either.left(resList);
+ List<InputDefinition> resourceProperties = component.getInputs();
+
+ if(inputs != null && !inputs.isEmpty()){
+ Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = getAllDataTypes(applicationDataTypeCache);
+ if (allDataTypes.isRight()) {
+ return Either.right(allDataTypes.right().value());
+ }
+
+ 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 = PropertyDataDefinition.mergeProperties(generatedInputs, inputs, false);
+ 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())));
}
- InputDefinition createdGroup = createInput.left().value();
- inputs.add(createdGroup);
+ result = Either.left(assotiateInputsEither.left().value());
+
}
- result = Either.left(inputs);
+
+
return result;
}
/**
* Delete input from service
*
- * @param component
- * @param user
* @param componentType
* @param inputId
- * @param inTransaction
+ * @param component
+ * @param user
+ *
* @return
*/
- public Either<InputDefinition, ResponseFormat> deleteInput(String componentType, String componentId, String userId, String inputId, boolean inTransaction) {
+ 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()) {
- return Either.right(userEither.right().value());
+ deleteEither = Either.right(userEither.right().value());
+ return deleteEither;
}
// Get component using componentType, componentId
- Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentEither = serviceOperation.getComponent(componentId, true);
+
+ 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()) {
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(componentEither.right().value())));
+ 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
- // And get the inputDefinition for the response
- InputDefinition inputDefinition = null;
Optional<InputDefinition> optionalInput = component.getInputs().stream().
// filter by ID
filter(input -> input.getUniqueId().equals(inputId)).
// Get the input
findAny();
- if (optionalInput.isPresent()) {
- inputDefinition = optionalInput.get();
- } else {
+ if (!optionalInput.isPresent()) {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.INPUT_IS_NOT_CHILD_OF_COMPONENT, inputId, componentId));
}
@@ -400,75 +813,118 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
Either<Boolean, ResponseFormat> lockResultEither = lockComponent(componentId, component, "deleteInput");
if (lockResultEither.isRight()) {
ResponseFormat responseFormat = lockResultEither.right().value();
- return Either.right(responseFormat);
+ deleteEither = Either.right(responseFormat);
+ return deleteEither;
}
// Delete input operations
- Either<String, StorageOperationStatus> deleteEither = Either.right(StorageOperationStatus.GENERAL_ERROR);
+
+ InputDefinition inputForDelete = optionalInput.get();
try {
- deleteEither = inputsOperation.deleteInput(inputId);
- if (deleteEither.isRight()){
+ StorageOperationStatus status = toscaOperationFacade.deleteInputOfResource(component, inputForDelete.getName());
+ if(status != StorageOperationStatus.OK){
log.debug("Component id: {} delete input id: {} failed", componentId, inputId);
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteEither.right().value()), component.getName()));
+ deleteEither = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), component.getName()));
+ return deleteEither;
}
- return Either.left(inputDefinition);
+
+ List<ComponentInstanceInput> inputsValue= getComponentInstanceInputsByInputId(component, inputId);
+ Map<String, List<ComponentInstanceInput>> insInputsMatToDelete = new HashMap<>();
+
+ if(inputsValue != null && !inputsValue.isEmpty()){
+ for(ComponentInstanceInput inputValue: inputsValue){
+ List<ComponentInstanceInput> inputList = null;
+ String ciId = inputValue.getComponentInstanceId();
+ if(!insInputsMatToDelete.containsKey(ciId)){
+ inputList = new ArrayList<>();
+ }else{
+ inputList = insInputsMatToDelete.get(ciId);
+ }
+ inputList.add(inputValue);
+ insInputsMatToDelete.put(ciId, inputList);
+ }
+ status = toscaOperationFacade.deleteComponentInstanceInputsToComponent(insInputsMatToDelete, component.getUniqueId());
+ if(status != StorageOperationStatus.OK){
+ log.debug("Component id: {} delete component instance input id: {} failed", componentId, 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 value = propertyValue.getValue();
+ Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(value);
+
+ resetInputName(mappedToscaTemplate, inputForDelete.getName());
+
+ value = gson.toJson(mappedToscaTemplate);
+ propertyValue.setValue(value);
+ String compInstId = propertyValue.getComponentInstanceId();
+ propertyValue.setRules(null);
+ List<GetInputValueDataDefinition> getInputsValues = propertyValue.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());
+ }
+ }
+ propertyValue.setGetInputValues(getInputsValues);
+ if(status != StorageOperationStatus.OK){
+ log.debug("Component id: {} delete component instance property {} id: {} failed", componentId, propertyValue.getUniqueId(), inputId);
+ deleteEither = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), component.getName()));
+ return deleteEither;
+ }
+ Either<String, TitanOperationStatus> findDefaultValue = propertyOperation.findDefaultValueFromSecondPosition(propertyValue.getPath(), propertyValue.getUniqueId(), propertyValue.getDefaultValue());
+ if (findDefaultValue.isRight()) {
+ deleteEither = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(findDefaultValue.right().value()))));
+ return deleteEither;
+
+ }
+ String defaultValue = findDefaultValue.left().value();
+ propertyValue.setDefaultValue(defaultValue);
+ log.debug("The returned default value in ResourceInstanceProperty is {}", defaultValue);
+ 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.isRight()) {
+ if (deleteEither == null || deleteEither.isRight()) {
log.debug("Component id: {} delete input id: {} failed", componentId, inputId);
- titanGenericDao.rollback();
+ titanDao.rollback();
} else {
log.debug("Component id: {} delete input id: {} success", componentId, inputId);
- titanGenericDao.commit();
+ titanDao.commit();
}
unlockComponent(deleteEither, component);
}
}
- /**
- * Create new property on resource in graph
- *
- * @param resourceId
- * @param propertyName
- * @param newPropertyDefinition
- * @param userId
- * @return Either<PropertyDefinition, ActionStatus>
- */
-
- private Either<InputDefinition, ResponseFormat> createInput(org.openecomp.sdc.be.model.Component component,
- User user, ComponentTypeEnum componentType, String inputName, InputDefinition newInputDefinition,
- boolean inTransaction) {
-
- Either<InputDefinition, ResponseFormat> result = null;
- if (log.isDebugEnabled())
- log.debug("Going to create input {}", newInputDefinition);
-
- try {
-
- // verify property not exist in resource
- List<InputDefinition> resourceProperties = component.getInputs();
-
- if (resourceProperties != null) {
- if (inputsOperation.isInputExist(resourceProperties, component.getUniqueId(), inputName)) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_ALREADY_EXIST, ""));
- }
- }
+ private Either<InputDefinition, ResponseFormat> prepareAndValidateInputBeforeCreate(InputDefinition newInputDefinition, Map<String, DataTypeDefinition> dataTypes) {
+
- Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = getAllDataTypes(
- applicationDataTypeCache);
- if (allDataTypes.isRight()) {
- return Either.right(allDataTypes.right().value());
- }
-
- Map<String, DataTypeDefinition> dataTypes = allDataTypes.left().value();
-
- // 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());
+ // 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;
@@ -482,29 +938,81 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
}
String convertedValue = null;
if (newInputDefinition.getDefaultValue() != null) {
- convertedValue = converter.convert(newInputDefinition.getDefaultValue(), innerType,
- allDataTypes.left().value());
+ 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;
+ }
+ }
- // add the new property to resource on graph
- // need to get StorageOpaerationStatus and convert to ActionStatus
- // from componentsUtils
- Either<InputsData, StorageOperationStatus> either = inputsOperation.addInput(inputName, newInputDefinition,
- component.getUniqueId(), componentType.getNodeType());
- if (either.isRight()) {
- return Either.right(componentsUtils.getResponseFormat(
- componentsUtils.convertFromStorageResponse(either.right().value()), component.getName()));
+ 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());
}
- // @TODO commit
- // inputsOperation.getTitanGenericDao().commit();
- InputDefinition createdInputyDefinition = inputsOperation
- .convertInputDataToInputDefinition(either.left().value());
- createdInputyDefinition.setName(inputName);
- createdInputyDefinition.setParentUniqueId(component.getUniqueId());
+ 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 Either.left(createdInputyDefinition);
+ return result;
} finally {
@@ -512,10 +1020,10 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
if (result == null || result.isRight()) {
log.debug("Going to execute rollback on create group.");
- titanGenericDao.rollback();
+ titanDao.rollback();
} else {
log.debug("Going to execute commit on create group.");
- titanGenericDao.commit();
+ titanDao.commit();
}
}
@@ -523,4 +1031,318 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
}
}
+
+ 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, DataTypeDefinition> dataTypes, List<InputDefinition> resList, Map<String, List<ComponentInstancePropInput>> newInputsPropsMap) {
+ List<ComponentInstance> ciList = component.getComponentInstances();
+ String componentId = component.getUniqueId();
+ for (Entry<String, List<ComponentInstancePropInput>> entry : newInputsPropsMap.entrySet()) {
+ List<ComponentInstanceProperty> propertiesToCreate = new ArrayList<>();
+ String compInstId = entry.getKey();
+ 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) {
+ Either<InputDefinition, StorageOperationStatus> createInputRes = createInputForComponentInstance(component, origComponent,ci, inputsToCreate, propertiesToCreate, dataTypes, inputName, propInput);
+
+ 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());
+
+ }
+ propertiesToCreateMap.put(compInstId, propertiesToCreate);
+ }
+
+ }
+ return Either.left(resList);
+ }
+
+ private Either<InputDefinition, StorageOperationStatus> createInputForComponentInstance(org.openecomp.sdc.be.model.Component component,org.openecomp.sdc.be.model.Component orignComponent, ComponentInstance ci, Map<String, InputDefinition> inputsToCreate, List<ComponentInstanceProperty> propertiesToCreate, Map<String, DataTypeDefinition> dataTypes, String inputName, ComponentInstancePropInput propInput) {
+ String propertiesName = propInput.getPropertiesName() ;
+ PropertyDefinition selectedProp = propInput.getInput();
+ String[] parsedPropNames = propInput.getParsedPropNames();
+
+ if(parsedPropNames != null){
+ for(String str: parsedPropNames){
+ inputName += "_" + str;
+ }
+ } else {
+ inputName += "_" + propInput.getName();
+ }
+
+ InputDefinition input = null;
+ ComponentInstanceProperty prop = propInput;
+
+ if(propertiesName != null && !propertiesName.isEmpty() && selectedProp != null){
+ input = new InputDefinition(selectedProp);
+ }else{
+ input = new InputDefinition(prop);
+ input.setName(inputName + "_" + prop.getName());
+
+ }
+ input.setName(inputName);
+ input.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(component.getUniqueId(), input.getName()));
+ input.setInputPath(propertiesName);
+
+ JSONObject jobject = new JSONObject();
+
+
+ if(prop.getValue() == null || prop.getValue().isEmpty()){
+ if(propertiesName != null && !propertiesName.isEmpty() && selectedProp != null){
+
+ jobject = createJSONValueForProperty(parsedPropNames.length -1, parsedPropNames, jobject, inputName);
+ prop.setValue(jobject.toJSONString());
+
+ }else{
+
+ jobject.put(GET_INPUT, input.getName());
+ prop.setValue(jobject.toJSONString());
+
+ }
+
+ }else{
+
+ String value = prop.getValue();
+ Object objValue = new Yaml().load(value);
+ if( objValue instanceof Map || objValue instanceof List ){
+ if(propertiesName == null ||propertiesName.isEmpty()){
+ jobject.put(GET_INPUT, input.getName());
+ prop.setValue(jobject.toJSONString());
+ prop.setRules(null);
+
+ }else{
+ Map<String, Object> mappedToscaTemplate = (Map<String, Object>) objValue;
+ createInputValue(mappedToscaTemplate, 1, parsedPropNames, inputName);
+
+ String json = gson.toJson(mappedToscaTemplate);
+ prop.setValue(json);
+ prop.setRules(null);
+ }
+
+ }else{
+ jobject.put(GET_INPUT, input.getName());
+ prop.setValue(jobject.toJSONString());
+ prop.setRules(null);
+ }
+
+ }
+ prop.setComponentInstanceId(ci.getUniqueId());
+ prop.setComponentInstanceName(ci.getName());
+
+ List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
+ GetInputValueDataDefinition getInputValueDataDefinition = new GetInputValueDataDefinition();
+ getInputValueDataDefinition.setInputId(input.getUniqueId());
+ getInputValueDataDefinition.setInputName(input.getName());
+ getInputValues.add(getInputValueDataDefinition);
+ prop.setGetInputValues(getInputValues);
+
+ propertiesToCreate.add(prop);
+
+ inputsToCreate.put(input.getName(), input);
+
+ 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;
+ }
+
+
+
+
}
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 780980ba08..e7d051290f 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
@@ -113,7 +113,7 @@ public class InterfaceLifecycleTypeImportManager {
operation.setDescription((String) opProp.get("description"));
operations.put(entry.getKey(), operation);
}
- interfaceDef.setOperations(operations);
+ interfaceDef.setOperationsMap(operations);
return interfaceDef;
}
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 3a54513b0b..96f7eec2d8 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
@@ -28,7 +28,6 @@ import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
-import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.datamodel.api.CategoryTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
@@ -40,6 +39,7 @@ import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.model.category.CategoryDefinition;
import org.openecomp.sdc.be.model.category.GroupingDefinition;
import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
import org.openecomp.sdc.be.model.operations.api.ICacheMangerOperation;
import org.openecomp.sdc.be.model.operations.api.IElementOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
@@ -47,9 +47,9 @@ import org.openecomp.sdc.be.model.operations.impl.ProductOperation;
import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+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.config.EcompErrorName;
import org.openecomp.sdc.common.util.ValidationUtils;
import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
@@ -89,6 +89,9 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
@Autowired
private ICacheMangerOperation cacheManagerOperation;
+
+ @Autowired
+ ToscaOperationFacade toscaOperationFacade;
public Either<Product, ResponseFormat> createProduct(Product product, User user) {
AuditingActionEnum actionEnum = AuditingActionEnum.CREATE_RESOURCE;
@@ -136,7 +139,7 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
log.debug("Product name locked is {}, status = {}", product.getSystemName(), lockResult);
try {
- Either<Product, StorageOperationStatus> createProductEither = productOperation.createProduct(product);
+ Either<Product, StorageOperationStatus> createProductEither = toscaOperationFacade.createToscaComponent(product);
if (createProductEither.isRight()) {
ResponseFormat responseFormat = componentsUtils.getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(createProductEither.right().value()), product, typeEnum);
@@ -259,8 +262,10 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
return Either.right(resp.right().value());
}
- Either<Boolean, StorageOperationStatus> dataModelResponse = productOperation.validateComponentNameExists(productName);
-
+ 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());
@@ -325,7 +330,7 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
contacts.add(modifierUserId);
}
- // passed - setting all contacts user ids to lowercase
+ // 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);
@@ -336,7 +341,7 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
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());
+ 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>>>();
@@ -345,7 +350,7 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
String catName = cat.getName();
if (ValidationUtils.validateStringNotEmpty(catName) == false) {
// error missing cat name
- log.debug("Missing category name for product {}", product.getName());
+ 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);
@@ -382,7 +387,7 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
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 category {} in product {}", subCatName, catName, product.getName());
+ 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);
@@ -390,7 +395,7 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
if (!subcatEntry.contains(groupName)) {
subcatEntry.add(groupName);
} else {
- log.debug("Grouping [ {} ] already exist for category [ {} ] and subcategory [ {} ]", groupName, catName, subCatName);
+ log.debug("Grouping: {}, already exist for category: {} and subcategory: {}", groupName, catName, subCatName);
}
}
}
@@ -495,7 +500,7 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
return Either.right(eitherCreator.right().value());
}
- Either<Product, StorageOperationStatus> storageStatus = productOperation.getComponent(productId, false);
+ Either<Product, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(productId);
if (storageStatus.isRight()) {
log.debug("failed to get resource by id {}", productId);
@@ -521,7 +526,7 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
return Either.right(eitherCreator.right().value());
}
- Either<Product, StorageOperationStatus> storageStatus = productOperation.deleteProduct(productId, false);
+ Either<Product, StorageOperationStatus> storageStatus = toscaOperationFacade.deleteToscaComponent(productId);
if (storageStatus.isRight()) {
log.debug("failed to delete resource by id {}", productId);
@@ -635,7 +640,7 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
return Either.right(responseFormat);
}
- Either<Product, StorageOperationStatus> storageStatus = productOperation.getComponent(productId, false);
+ 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()));
@@ -645,8 +650,8 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
Product currentProduct = storageStatus.left().value();
- if (!ComponentValidationUtils.canWorkOnComponent(productId, productOperation, user.getUserId())) {
- log.info("Restricted operation for user {} on product {}", user.getUserId(), currentProduct.getCreatorUserId());
+ 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));
}
@@ -663,14 +668,13 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
return Either.right(lockResult.right().value());
}
try {
- Either<Product, StorageOperationStatus> updateResponse = productOperation.updateComponent(productToUpdate, true);
+ Either<Product, StorageOperationStatus> updateResponse = toscaOperationFacade.updateToscaElement(productToUpdate);
if (updateResponse.isRight()) {
- productOperation.rollback();
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Update Product Metadata");
+ toscaOperationFacade.rollback();
log.debug("failed to update product {}", productToUpdate.getUniqueId());
return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
}
- productOperation.commit();
+ toscaOperationFacade.commit();
return Either.left(updateResponse.left().value());
} finally {
graphLockOperation.unlockComponent(productId, NodeTypeEnum.Product);
@@ -791,7 +795,6 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
private Either<Boolean, ResponseFormat> validateAndUpdateCategory(User user, Product currentProduct, Product updatedProduct) {
List<CategoryDefinition> categoryUpdated = updatedProduct.getCategories();
- List<CategoryDefinition> categoryCurrent = currentProduct.getCategories();
Either<Boolean, ResponseFormat> validatCategoryResponse = validateGrouping(user, updatedProduct, null);
if (validatCategoryResponse.isRight()) {
@@ -854,7 +857,7 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
if (resp.isRight()) {
return Either.right(resp.right().value());
}
- Either<Product, StorageOperationStatus> storageStatus = productOperation.getProductByNameAndVersion(productName, productVersion, false);
+ 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));
@@ -881,7 +884,11 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
this.cacheManagerOperation = cacheManagerOperation;
}
- public void setProductOperation(ProductOperation productOperation) {
- this.productOperation = productOperation;
+ @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
index 46188012d8..ab0969358c 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductComponentInstanceBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductComponentInstanceBusinessLogic.java
@@ -22,7 +22,6 @@ package org.openecomp.sdc.be.components.impl;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.model.operations.impl.ComponentOperation;
import org.openecomp.sdc.exception.ResponseFormat;
import org.springframework.stereotype.Component;
@@ -43,17 +42,9 @@ public class ProductComponentInstanceBusinessLogic extends ComponentInstanceBusi
}
@Override
- protected ComponentOperation getContainerComponentOperation() {
- return productOperation;
- }
-
- @Override
- protected ComponentOperation getCompInstOriginComponentOperation() {
- return serviceOperation;
- }
-
- @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 1e6b1c1d82..e0d531d622 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,40 +20,60 @@
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 org.apache.commons.collections.CollectionUtils;
+import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.impl.WebAppContextWrapper;
import org.openecomp.sdc.be.model.DataTypeDefinition;
+import org.openecomp.sdc.be.model.IComplexDefaultValue;
+import org.openecomp.sdc.be.model.PropertyConstraint;
import org.openecomp.sdc.be.model.PropertyDefinition;
import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
import org.openecomp.sdc.be.model.operations.api.IElementOperation;
import org.openecomp.sdc.be.model.operations.api.IResourceOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
+import org.openecomp.sdc.be.model.operations.impl.PropertyOperation.PropertyConstraintDeserialiser;
import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
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.common.config.EcompErrorName;
import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.JsonElement;
+import com.google.gson.reflect.TypeToken;
+
import fj.data.Either;
@Component("propertyBusinessLogic")
@@ -63,11 +83,15 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
private static Logger log = LoggerFactory.getLogger(PropertyBusinessLogic.class.getName());
+ private static final String EMPTY_VALUE = null;
+
+ private DataTypeValidatorConverter dataTypeValidatorConverter = DataTypeValidatorConverter.getInstance();
+
@javax.annotation.Resource
private IResourceOperation resourceOperation = null;
- @javax.annotation.Resource
- private PropertyOperation propertyOperation = null;
+ @Autowired
+ private ToscaOperationFacade toscaOperationFacade;
@javax.annotation.Resource
private ComponentsUtils componentsUtils;
@@ -114,7 +138,7 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
try {
// Get the resource from DB
- Either<Resource, StorageOperationStatus> status = getResource(resourceId);
+ Either<Resource, StorageOperationStatus> status = toscaOperationFacade.getToscaElement(resourceId);
if (status.isRight()) {
result = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, ""));
return result;
@@ -132,8 +156,8 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
List<PropertyDefinition> resourceProperties = resource.getProperties();
if (resourceProperties != null) {
- if (propertyOperation.isPropertyExist(resourceProperties, resourceId, propertyName)) {
- result = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_ALREADY_EXIST, ""));
+ if (isPropertyExist(resourceProperties, resourceId, propertyName, newPropertyDefinition.getType())) {
+ result = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_ALREADY_EXIST, propertyName));
return result;
}
}
@@ -177,13 +201,13 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
// add the new property to resource on graph
// need to get StorageOpaerationStatus and convert to ActionStatus
// from componentsUtils
- Either<PropertyData, StorageOperationStatus> either = propertyOperation.addProperty(propertyName, newPropertyDefinition, resourceId);
+ 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 = propertyOperation.convertPropertyDataToPropertyDefinition(either.left().value(), propertyName, resourceId);
+ PropertyDefinition createdPropertyDefinition = either.left().value();
EntryData<String, PropertyDefinition> property = new EntryData<String, PropertyDefinition>(propertyName, createdPropertyDefinition);
result = Either.left(property);
return result;
@@ -202,7 +226,6 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
* @param resourceId
* @param propertyId
* @param userId
- * TODO
* @return
*/
public Either<Entry<String, PropertyDefinition>, ResponseFormat> getProperty(String resourceId, String propertyId, String userId) {
@@ -213,7 +236,7 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
}
// Get the resource from DB
- Either<Resource, StorageOperationStatus> status = getResource(resourceId);
+ Either<Resource, StorageOperationStatus> status = toscaOperationFacade.getToscaElement(resourceId);
if (status.isRight()) {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, ""));
}
@@ -244,9 +267,9 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
* @param userId
* @return
*/
- public Either<EntryData<String, PropertyDefinition>, ResponseFormat> deleteProperty(String resourceId, String propertyId, String userId) {
+ public Either<Entry<String, PropertyDefinition>, ResponseFormat> deleteProperty(String resourceId, String propertyId, String userId) {
- Either<EntryData<String, PropertyDefinition>, ResponseFormat> result = null;
+ Either<Entry<String, PropertyDefinition>, ResponseFormat> result = null;
Either<User, ResponseFormat> resp = validateUserExists(userId, "delete Property", false);
if (resp.isRight()) {
@@ -263,12 +286,12 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
try {
// Get the resource from DB
- Either<Resource, StorageOperationStatus> status = getResource(resourceId);
- if (status.isRight()) {
+ Either<Resource, StorageOperationStatus> getResourceRes = toscaOperationFacade.getToscaElement(resourceId);
+ if (getResourceRes.isRight()) {
result = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, ""));
return result;
}
- Resource resource = status.left().value();
+ Resource resource = getResourceRes.left().value();
// verify that resource is checked-out and the user is the last
// updater
@@ -283,21 +306,14 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
result = Either.right(statusGetProperty.right().value());
return result;
}
- String propertyName = statusGetProperty.left().value().getKey();
- // delete property of resource from graph
- // TODO: need to get StorageOperationStatus
- Either<PropertyData, StorageOperationStatus> either = propertyOperation.deleteProperty(propertyId);
- // Either<PropertyData, StorageOperationStatus> either =
- // propertyOperation.deletePropertyFromGraph(propertyId);
- if (either.isRight()) {
- result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(either.right().value()), resource.getName()));
+ 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();
- PropertyDefinition createdPropertyDefinition = propertyOperation.convertPropertyDataToPropertyDefinition(either.left().value(), propertyName, resourceId);
- EntryData<String, PropertyDefinition> property = new EntryData<String, PropertyDefinition>(propertyName, createdPropertyDefinition);
- result = Either.left(property);
+ result = Either.left(statusGetProperty.left().value());
return result;
} finally {
@@ -320,14 +336,12 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
Either<EntryData<String, PropertyDefinition>, ResponseFormat> result = null;
- // Get the resource from DB
- Either<Resource, StorageOperationStatus> status = getResource(resourceId);
+ 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));
}
@@ -340,8 +354,6 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
}
try {
-
- // verify property exist in resource
Either<Entry<String, PropertyDefinition>, ResponseFormat> statusGetProperty = getProperty(resourceId, propertyId, userId);
if (statusGetProperty.isRight()) {
result = Either.right(statusGetProperty.right().value());
@@ -355,37 +367,222 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
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;
}
- // add the new property to resource on graph
- // TODO: convert TitanOperationStatus to Storgae...
- Either<PropertyData, StorageOperationStatus> either = propertyOperation.updateProperty(propertyId, newPropertyDefinition, dataTypes);
- // Either<PropertyData, StorageOperationStatus> either =
- // propertyOperation.updatePropertyFromGraph(propertyId,
- // newPropertyDefinition);
+ 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;
- // return Either.right(ActionStatus.GENERAL_ERROR);
}
- PropertyDefinition createdPropertyDefinition = propertyOperation.convertPropertyDataToPropertyDefinition(either.left().value(), propertyName, resourceId);
- EntryData<String, PropertyDefinition> property = new EntryData<String, PropertyDefinition>(propertyName, createdPropertyDefinition);
+
+ 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);
- // unlock component
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;
+ }
}
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 ddc03e14e8..ffcb87c99c 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,10 +20,14 @@
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.nio.charset.StandardCharsets;
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;
@@ -40,8 +44,10 @@ import java.util.stream.Collectors;
import javax.servlet.ServletContext;
import org.apache.commons.codec.binary.Base64;
+import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperation;
+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;
import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaElementTypeEnum;
import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum;
@@ -49,13 +55,17 @@ 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;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
-import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
+import org.openecomp.sdc.be.config.Configuration.VfModuleProperty;
+import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
import org.openecomp.sdc.be.datamodel.api.HighestFilterEnum;
import org.openecomp.sdc.be.datamodel.utils.ArtifactUtils;
+import org.openecomp.sdc.be.datamodel.utils.UiComponentDataConverter;
+import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
@@ -64,15 +74,14 @@ import org.openecomp.sdc.be.impl.WebAppContextWrapper;
import org.openecomp.sdc.be.info.ArtifactTemplateInfo;
import org.openecomp.sdc.be.info.MergedArtifactInfo;
import org.openecomp.sdc.be.model.ArtifactDefinition;
+import org.openecomp.sdc.be.model.AttributeDefinition;
import org.openecomp.sdc.be.model.CapabilityDefinition;
import org.openecomp.sdc.be.model.CapabilityTypeDefinition;
import org.openecomp.sdc.be.model.Component;
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.GetInputValueInfo;
import org.openecomp.sdc.be.model.GroupDefinition;
import org.openecomp.sdc.be.model.GroupProperty;
import org.openecomp.sdc.be.model.GroupTypeDefinition;
@@ -84,6 +93,7 @@ import org.openecomp.sdc.be.model.LifecycleStateEnum;
import org.openecomp.sdc.be.model.Operation;
import org.openecomp.sdc.be.model.ParsedToscaYamlInfo;
import org.openecomp.sdc.be.model.PropertyDefinition;
+import org.openecomp.sdc.be.model.RelationshipImpl;
import org.openecomp.sdc.be.model.RequirementAndRelationshipPair;
import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
import org.openecomp.sdc.be.model.RequirementDefinition;
@@ -98,29 +108,24 @@ 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.operations.api.IArtifactOperation;
import org.openecomp.sdc.be.model.operations.api.ICacheMangerOperation;
import org.openecomp.sdc.be.model.operations.api.ICapabilityTypeOperation;
-import org.openecomp.sdc.be.model.operations.api.IComponentInstanceOperation;
import org.openecomp.sdc.be.model.operations.api.IElementOperation;
import org.openecomp.sdc.be.model.operations.api.IHeatParametersOperation;
import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation;
import org.openecomp.sdc.be.model.operations.api.IPropertyOperation;
-import org.openecomp.sdc.be.model.operations.api.IResourceOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.model.operations.impl.CapabilityInstanceOperation;
import org.openecomp.sdc.be.model.operations.impl.CsarOperation;
import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
-import org.openecomp.sdc.be.model.operations.impl.GroupOperation;
import org.openecomp.sdc.be.model.operations.impl.InputsOperation;
-import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
-import org.openecomp.sdc.be.model.operations.impl.ResourceOperation;
import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
-import org.openecomp.sdc.be.resources.data.ResourceMetadataData;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
import org.openecomp.sdc.be.servlets.RepresentationUtils;
+import org.openecomp.sdc.be.tosca.CsarUtils;
+import org.openecomp.sdc.be.tosca.CsarUtils.NonMetaArtifactInfo;
+import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;
import org.openecomp.sdc.be.user.IUserBusinessLogic;
import org.openecomp.sdc.be.user.Role;
import org.openecomp.sdc.be.user.UserBusinessLogic;
@@ -129,6 +134,8 @@ 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.config.EcompErrorName;
+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;
import org.openecomp.sdc.common.util.GeneralUtility;
@@ -140,9 +147,6 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.WebApplicationContext;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
-import org.yaml.snakeyaml.constructor.Constructor;
-import org.yaml.snakeyaml.representer.Representer;
-import org.yaml.snakeyaml.resolver.Resolver;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
@@ -156,13 +160,18 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
private static final String PLACE_HOLDER_RESOURCE_TYPES = "validForResourceTypes";
public static final String INITIAL_VERSION = "0.1";
- Pattern STR_REPLACE_PATTERN = Pattern.compile("^[ ]*\\{[ ]*" + "str_replace" + "=");
- Pattern TOKEN_PATTERN = Pattern.compile("[ ]*\\{[ ]*" + "token" + "=");
- Pattern GET_PROPERTY_PATTERN = Pattern.compile("[ ]*\\{[ ]*" + "get_property" + "=");
- Pattern CONCAT_PATTERN = Pattern.compile("[ ]*\\{[ ]*" + "concat" + "=");
+ 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 Logger log = LoggerFactory.getLogger(ResourceBusinessLogic.class.getName());
+ private static Pattern pattern = Pattern.compile("\\..(.*?)\\..");
+
+ /**
+ * Default constructor
+ */
public ResourceBusinessLogic() {
log.debug("ResourceBusinessLogic started");
}
@@ -174,9 +183,6 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
private IInterfaceLifecycleOperation interfaceTypeOperation = null;
@Autowired
- private IComponentInstanceOperation componentInstanceOperation;
-
- @Autowired
private LifecycleBusinessLogic lifecycleBusinessLogic;
@Autowired
@@ -193,23 +199,21 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
@Autowired
private GroupBusinessLogic groupBusinessLogic;
+
@Autowired
private InputsBusinessLogic inputsBusinessLogic;
@javax.annotation.Resource
private InputsOperation inputOperation;
- @Autowired
- private GroupOperation groupOperation;
+ // @Autowired
+ // private GroupOperation groupOperation;
@Autowired
private IHeatParametersOperation heatParametersOperation;
- @Autowired
- private IArtifactOperation artifactOperation;
-
- @Autowired
- private CapabilityInstanceOperation capabilityInstanceOperation;
+ // @Autowired
+ // private IArtifactOperation artifactOperation;
@Autowired
private CompositionBusinessLogic compositionBusinessLogic;
@@ -217,6 +221,9 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
@Autowired
private ICacheMangerOperation cacheManagerOperation;
+ @Autowired
+ private ApplicationDataTypeCache dataTypeCache;
+
private Gson gson = new Gson();
public CsarOperation getCsarOperation() {
@@ -227,14 +234,6 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
this.csarOperation = csarOperation;
}
- public IResourceOperation getResourceOperation() {
- return this.resourceOperation;
- }
-
- public void setResourceOperation(ResourceOperation resourceOperation) {
- this.resourceOperation = resourceOperation;
- }
-
public LifecycleBusinessLogic getLifecycleBusinessLogic() {
return lifecycleBusinessLogic;
}
@@ -300,7 +299,6 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (resp.isRight()) {
return Either.right(resp.right().value());
}
- IResourceOperation dataModel = getResourceOperation();
Boolean isHighest = null;
switch (highestFilter) {
case ALL:
@@ -314,17 +312,13 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
default:
break;
}
+ Either<List<Resource>, StorageOperationStatus> getResponse = toscaOperationFacade.getAllCertifiedResources(getAbstract, isHighest);
- Either<List<Resource>, StorageOperationStatus> dataModelResponse = dataModel.getAllCertifiedResources(getAbstract, isHighest);
-
- if (dataModelResponse.isLeft()) {
- log.debug("Retrived Resource successfully.");
- return Either.left(dataModelResponse.left().value());
+ if (getResponse.isRight()) {
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getResponse.right().value())));
}
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()));
-
- return Either.right(responseFormat);
+ return Either.left(getResponse.left().value());
}
public Either<Map<String, Boolean>, ResponseFormat> validateResourceNameExists(String resourceName, ResourceTypeEnum resourceTypeEnum, String userId) {
@@ -334,9 +328,9 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return Either.right(resp.right().value());
}
- IResourceOperation dataModel = getResourceOperation();
-
- Either<Boolean, StorageOperationStatus> dataModelResponse = dataModel.validateResourceNameExists(resourceName, resourceTypeEnum);
+ Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateComponentNameUniqueness(resourceName, resourceTypeEnum, ComponentTypeEnum.RESOURCE);
+ // DE242223
+ titanDao.commit();
if (dataModelResponse.isLeft()) {
Map<String, Boolean> result = new HashMap<>();
@@ -350,7 +344,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return Either.right(responseFormat);
}
- public Either<Resource, ResponseFormat> createResource(Resource resource, User user, Map<String, byte[]> csarUIPayload, String payloadName) {
+ 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;
@@ -366,26 +360,26 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (csarUUID != null && !csarUUID.isEmpty()) {
// check if VF with the same Csar UUID or with he same name already
// exists
- Either<List<ResourceMetadataData>, StorageOperationStatus> validateCsarUuidUniquenessRes = resourceOperation.validateCsarUuidUniqueness(csarUUID);
+ 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())));
}
- List<ResourceMetadataData> existingResourceRes = validateCsarUuidUniquenessRes.left().value();
- if (existingResourceRes != null && existingResourceRes.size() > 0) {
- log.debug("Failed to create resource {}, csarUUID {} already exist for a different VF {}", resource.getSystemName(), csarUUID, existingResourceRes.get(0).getMetadataDataDefinition().getName());
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VSP_ALREADY_EXISTS, csarUUID, existingResourceRes.get(0).getMetadataDataDefinition().getName());
- componentsUtils.auditResource(errorResponse, user, resource, "", "", AuditingActionEnum.CREATE_RESOURCE, null);
+ 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, AuditingActionEnum.CREATE_RESOURCE, false, Either.left(csarUIPayload), csarUUID);
+ createResourceResponse = createResourceFromCsar(resource, user, Either.left(csarUIPayload), csarUUID);
return createResourceResponse;
}
- return createResourceByDao(resource, user, AuditingActionEnum.CREATE_RESOURCE, false);
+ 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) {
@@ -448,7 +442,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
// "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 = resourceOperation.getLatestResourceByCsarOrName(csarUUID, resource.getSystemName());
+ 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());
@@ -476,7 +470,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
private Resource getResourceByUniqueId(Wrapper<ResponseFormat> responseWrapper, String resourceUniqueId) {
- Either<Resource, StorageOperationStatus> oldResourceRes = resourceOperation.getResource(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())));
@@ -505,7 +499,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
}
String lockedResourceId = oldRresource.getUniqueId();
- List<ArtifactDefinition> createdArtifacts = new ArrayList<ArtifactDefinition>();
+ List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
+ List<ArtifactDefinition> nodeTypesNewCreatedArtifacts = new ArrayList<>();
Either<Map<String, byte[]>, StorageOperationStatus> csar = null;
if (csarUIPayload != null && csarUIPayload.left() != null && csarUIPayload.left().value() != null) {
@@ -542,29 +537,33 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
Either<Resource, ResponseFormat> result = null;
+ String yamlFileName = toscaYamlCsarStatus.left().value().getKey();
+ Either<Map<String, Resource>, ResponseFormat> parseNodeTypeInfoYamlEither = null;
try {
Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> prepareForUpdate = null;
Resource preparedResource = null;
- if (isUpdateYaml) {
- prepareForUpdate = updateExistingResourceByImport(newRresource, oldRresource, user, true, false);
+ Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(csar.left().value(), csarUUID, yamlFileName, oldRresource, user, true);
+ if (findNodeTypesArtifactsToHandleRes.isRight()) {
+ log.debug("failed to find node types for update with artifacts during import csar {}. ", csarUUID);
+ result = Either.right(findNodeTypesArtifactsToHandleRes.right().value());
+ return result;
+ }
+ Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = findNodeTypesArtifactsToHandleRes.left().value();
+ if (isUpdateYaml || !nodeTypesArtifactsToHandle.isEmpty()) {
+ prepareForUpdate = updateExistingResourceByImport(newRresource, oldRresource, user, true, false);
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;
- String yamlFileName = toscaYamlCsarStatus.left().value().getKey();
+
String yamlFileContents = toscaYamlCsarStatus.left().value().getValue();
log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContents);
- // Either<Map<String, Resource>, ResponseFormat>
- // parseNodeTypeInfoYamlEither =
- // createResourcesFromYamlNodeTypesList(yamlFileName,preparedResource,
- // yamlFileContents, user,false);
-
- Either<Map<String, Resource>, ResponseFormat> parseNodeTypeInfoYamlEither = this.handleNodeTypes(yamlFileName, preparedResource, user, yamlFileContents, csar.left().value(), false);
+ parseNodeTypeInfoYamlEither = this.handleNodeTypes(yamlFileName, preparedResource, user, yamlFileContents, csar.left().value(), false, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts);
if (parseNodeTypeInfoYamlEither.isRight()) {
ResponseFormat responseFormat = parseNodeTypeInfoYamlEither.right().value();
componentsUtils.auditResource(responseFormat, user, preparedResource, "", "", updateResource, null);
@@ -638,12 +637,11 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
result = Either.right(dataModelResponse.right().value());
return result;
}
-
preparedResource = dataModelResponse.left().value();
-
}
- Either<Resource, ResponseFormat> createdCsarArtifactsEither = handleCsarArtifacts(preparedResource, user, csarUUID, csar.left().value(), createdArtifacts, ArtifactOperation.Update, false, true);
+ Either<Resource, ResponseFormat> createdCsarArtifactsEither = handleCsarArtifacts(preparedResource, user, csarUUID, csar.left().value(), createdArtifacts,
+ artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Update), false, true);
if (createdCsarArtifactsEither.isRight()) {
return createdCsarArtifactsEither;
@@ -658,8 +656,9 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
} finally {
if (result == null || result.isRight()) {
log.warn("operation failed. do rollback");
- titanGenericDao.rollback();
- if (!createdArtifacts.isEmpty()) {
+ titanDao.rollback();
+ if (!createdArtifacts.isEmpty() || !nodeTypesNewCreatedArtifacts.isEmpty()) {
+ createdArtifacts.addAll(nodeTypesNewCreatedArtifacts);
StorageOperationStatus deleteFromEsRes = artifactsBusinessLogic.deleteAllComponentArtifactsIfNotOnGraph(createdArtifacts);
if (!deleteFromEsRes.equals(StorageOperationStatus.OK)) {
ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(deleteFromEsRes);
@@ -669,7 +668,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
} else {
log.debug("operation success. do commit");
- titanGenericDao.commit();
+ titanDao.commit();
}
log.debug("unlock resource {}", lockedResourceId);
graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource);
@@ -677,7 +676,318 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
- public Either<Resource, ResponseFormat> createResourceFromCsar(Resource resource, User user, AuditingActionEnum createResource, boolean inTransaction, Either<Map<String, byte[]>, StorageOperationStatus> csarUIPayload, String csarUUID) {
+ private Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandle(Map<String, byte[]> csar, String csarUUID, String yamlFileName, Resource oldResource, User user,
+ boolean inTransaction) {
+
+ Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts = CsarUtils.extractVfcsArtifactsFromCsar(csar);
+ Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = new HashMap<>();
+ Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> nodeTypesArtifactsToHandleRes;
+
+ try {
+ nodeTypesArtifactsToHandleRes = Either.left(nodeTypesArtifactsToHandle);
+ List<ImmutablePair<ImmutablePair<String, List<String>>, String>> extractedVfcToscaNames = extractVfcToscaNames(csar, yamlFileName, oldResource.getSystemName());
+ validateNodeTypeIdentifiers(extractedVfcsArtifacts, extractedVfcToscaNames);
+ Either<EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>, ResponseFormat> curNodeTypeArtifactsToHandleRes = null;
+ EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> curNodeTypeArtifactsToHandle = null;
+ log.debug("Going to fetch node types for resource with name {} during import csar with UUID {}. ", oldResource.getName(), csarUUID);
+
+ for (ImmutablePair<ImmutablePair<String, List<String>>, String> currVfcToscaNameEntry : extractedVfcToscaNames) {
+ String currVfcToscaName = currVfcToscaNameEntry.getValue();
+ 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) {
+ 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()), csarUUID);
+ componentsUtils.auditResource(responseFormat, user, 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<>();
+ for (String currNamespace : currVfcToscaNameEntry.getKey().getValue()) {
+ 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().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 void validateNodeTypeIdentifiers(Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts, List<ImmutablePair<ImmutablePair<String, List<String>>, String>> extractedVfcToscaNames) {
+ if (extractedVfcsArtifacts != null) {
+ List<String> validIdentifiers = new ArrayList<>();
+ if (extractedVfcToscaNames != null) {
+ extractedVfcToscaNames.stream().forEach(pair -> {
+ validIdentifiers.addAll(pair.getKey().getValue());
+ validIdentifiers.add(pair.getKey().getKey());
+ });
+ }
+ for (String curIdentifier : extractedVfcsArtifacts.keySet()) {
+ if (validIdentifiers != null && !validIdentifiers.contains(curIdentifier))
+ log.warn("Warning - VFC identification {} provided in the Artifacts folder of the CSAR is not valid. ", curIdentifier);
+ }
+ }
+ }
+
+ private Either<EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>, ResponseFormat> findNodeTypeArtifactsToHandle(Resource curNodeType, List<ArtifactDefinition> extractedArtifacts) {
+
+ Either<EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>, ResponseFormat> nodeTypeArtifactsToHandleRes = null;
+ 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.calculateMD5ByByteArray(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> vfcsNewCreatedArtifacts,
+ User user, boolean inTransaction) {
+ 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, vfcsNewCreatedArtifacts,
+ artifactsBusinessLogic.new ArtifactOperationInfo(false, false, curOperation), false, inTransaction);
+ if (handleNodeTypeArtifactsRequestRes.isRight()) {
+ handleNodeTypeArtifactsRes = Either.right(handleNodeTypeArtifactsRequestRes.right().value());
+ break;
+ }
+ if (curOperation == ArtifactOperationEnum.Create) {
+ vfcsNewCreatedArtifacts.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 List<ImmutablePair<ImmutablePair<String, List<String>>, String>> extractVfcToscaNames(Map<String, byte[]> csar, String yamlFileName, String vfResourceName) {
+ List<ImmutablePair<ImmutablePair<String, List<String>>, String>> vfcToscaNames = new ArrayList<>();
+ Map<String, Object> nodeTypes;
+ if (csar != null) {
+ nodeTypes = new HashMap<>();
+ putNodeTypesFromYaml(csar, yamlFileName, nodeTypes);
+ putNodeTypesFromYaml(csar, Constants.GLOBAL_SUBSTITUTION_TYPES_SERVICE_TEMPLATE, nodeTypes);
+ putNodeTypesFromYaml(csar, Constants.ABSTRACT_SUBSTITUTE_GLOBAL_TYPES_SERVICE_TEMPLATE, nodeTypes);
+
+ if (!nodeTypes.isEmpty()) {
+ Iterator<Entry<String, Object>> nodesNameEntry = nodeTypes.entrySet().iterator();
+ while (nodesNameEntry.hasNext()) {
+ Entry<String, Object> nodeType = nodesNameEntry.next();
+ addVfcToscaNameFindSubstitutes(csar, vfResourceName, vfcToscaNames, nodeType.getKey());
+ }
+ }
+ }
+ return vfcToscaNames;
+ }
+
+ @SuppressWarnings("unchecked")
+ private void putNodeTypesFromYaml(Map<String, byte[]> csar, String yamlFileName, Map<String, Object> nodeTypes) {
+
+ if (csar.containsKey(yamlFileName)) {
+ Map<String, Object> mappedToscaTemplate;
+ Either<Map<String, Object>, ResultStatusEnum> eitherNodeTypes;
+ mappedToscaTemplate = (Map<String, Object>) new Yaml().load(new String(csar.get(yamlFileName), StandardCharsets.UTF_8));
+ eitherNodeTypes = ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TYPES);
+ if (eitherNodeTypes.isLeft()) {
+ nodeTypes.putAll(eitherNodeTypes.left().value());
+ }
+ }
+ }
+
+ private void addVfcToscaNameFindSubstitutes(Map<String, byte[]> csar, String vfResourceName, List<ImmutablePair<ImmutablePair<String, List<String>>, String>> vfcToscaNames, String nodeTypeFullName) {
+
+ String toscaResourceName = buildNestedVfcToscaResourceName(vfResourceName, nodeTypeFullName);
+ String nodeTypeTemplateYamlName = buildNestedSubstituteYamlName(nodeTypeFullName);
+ List<String> relatedVfcsToscaNameSpaces = new ArrayList<>();
+ relatedVfcsToscaNameSpaces.add(buildNestedVfcToscaNamespace(nodeTypeFullName));
+ if (csar.containsKey(nodeTypeTemplateYamlName)) {
+ addSubstituteToscaNamespacesRecursively(csar, nodeTypeTemplateYamlName, relatedVfcsToscaNameSpaces);
+ }
+ ImmutablePair<String, List<String>> toscaNameSpacesHierarchy = new ImmutablePair<>(nodeTypeFullName, relatedVfcsToscaNameSpaces);
+ vfcToscaNames.add(new ImmutablePair<>(toscaNameSpacesHierarchy, toscaResourceName));
+ }
+
+ private void addSubstituteToscaNamespacesRecursively(Map<String, byte[]> csar, String yamlFileName, List<String> toscaNameSpaces) {
+
+ Map<String, Object> nodeTypes = new HashMap<>();
+
+ if (csar.containsKey(yamlFileName)) {
+ putNodeTypesFromYaml(csar, yamlFileName, nodeTypes);
+ }
+ if (!nodeTypes.isEmpty()) {
+ Iterator<Entry<String, Object>> nodesNameEntry = nodeTypes.entrySet().iterator();
+ while (nodesNameEntry.hasNext()) {
+ Entry<String, Object> nodeType = nodesNameEntry.next();
+ String nodeTypeFullName = nodeType.getKey();
+ String toscaNameSpace = buildNestedVfcToscaNamespace(nodeTypeFullName);
+ if (toscaNameSpaces.contains(toscaNameSpace)) {
+ break;
+ }
+ toscaNameSpaces.add(toscaNameSpace);
+
+ String nodeTypeTemplateYamlName = buildNestedSubstituteYamlName(nodeTypeFullName);
+
+ if (csar.containsKey(nodeTypeTemplateYamlName)) {
+ addSubstituteToscaNamespacesRecursively(csar, nodeTypeTemplateYamlName, toscaNameSpaces);
+ }
+ }
+ }
+ }
+
+ 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;
@@ -793,7 +1103,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
- public Either<Map<String, Resource>, ResponseFormat> createResourcesFromYamlNodeTypesList(String yamlName, Resource resource, String resourceYml, User user, boolean needLock) {
+ public Either<Map<String, Resource>, ResponseFormat> createResourcesFromYamlNodeTypesList(String yamlName, Resource resource, String resourceYml, User user, boolean needLock,
+ Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts) {
Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(resourceYml);
@@ -818,8 +1129,9 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
while (nodesNameValue.hasNext()) {
Entry<String, Object> nodeType = nodesNameValue.next();
+ Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = nodeTypesArtifactsToHandle == null || nodeTypesArtifactsToHandle.isEmpty() ? null : nodeTypesArtifactsToHandle.get(nodeType.getKey());
log.trace("************* Going to create node {}", nodeType.getKey());
- Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> resourceCreated = this.createNodeTypeResourceFromYaml(yamlName, nodeType, user, mapToConvert, resource, needLock);
+ Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> resourceCreated = this.createNodeTypeResourceFromYaml(yamlName, nodeType, user, mapToConvert, resource, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts);
log.trace("************* finished to create node {}", nodeType.getKey());
if (resourceCreated.isRight()) {
return Either.right(resourceCreated.right().value());
@@ -842,7 +1154,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
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) {
+ 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) {
Either<UploadResourceInfo, ResponseFormat> resourceMetaData = fillResourceMetadata(yamlName, resourceVf, nodeNameValue.getKey(), user);
if (resourceMetaData.isRight()) {
@@ -858,8 +1171,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
Map<String, Object> singleVfc = new HashMap<>();
String actualName = this.getNodeTypeActualName(nodeNameValue.getKey());
- if (!actualName.startsWith(ImportUtils.Constants.ABSTRACT_NODE)) {
- actualName = "." + ImportUtils.Constants.ABSTRACT_NODE + actualName;
+ if (!actualName.startsWith(Constants.ABSTRACT)) {
+ actualName = "." + Constants.ABSTRACT + actualName;
}
// Setting tosca name
@@ -875,7 +1188,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
user = eitherCreator.left().value();
- return this.createResourceFromNodeType(singleVfcYaml, resourceMetaData.left().value(), user, true, needLock);
+ return this.createResourceFromNodeType(singleVfcYaml, resourceMetaData.left().value(), user, true, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts);
}
public Either<Boolean, ResponseFormat> validateResourceCreationFromNodeType(Resource resource, User creator) {
@@ -887,11 +1200,12 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return Either.left(true);
}
- public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createResourceFromNodeType(String nodeTypeYaml, UploadResourceInfo resourceMetaData, User creator, boolean isInTransaction, boolean needLock) {
+ 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) {
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);
+ return this.resourceImportManager.importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator, lifecycleChangeInfo, isInTransaction, true, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts);
}
private Either<UploadResourceInfo, ResponseFormat> fillResourceMetadata(String yamlName, Resource resourceVf, String nodeTypeName, User user) {
@@ -915,7 +1229,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
resourceType = ResourceTypeEnum.VFC.name().toLowerCase();
}
// validating type
- if (!ResourceTypeEnum.contains(resourceType.toUpperCase())) {
+ 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(), nodeTypeName);
return Either.right(responseFormat);
@@ -956,7 +1270,9 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
Map<String, byte[]> csar, List<ArtifactDefinition> createdArtifacts, String topologyTemplateYaml) {
boolean result = true;
-
+ boolean inTransaction = true;
+ Map<String, Resource> createdVfcs = new HashMap<>();
+ List<ArtifactDefinition> nodeTypesNewCreatedArtifacts = new ArrayList<>();
Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource, "Create Resource");
if (lockResult.isRight()) {
ResponseFormat responseFormat = lockResult.right().value();
@@ -966,7 +1282,12 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
try {
log.trace("************* createResourceFromYaml before full create resource {}", yamlName);
- Either<Resource, ResponseFormat> createResourcesEither = createResourceTransaction(resource, user, actionEnum, isNormative, true);
+ Either<Resource, ResponseFormat> genericResourceEither = fetchAndSetDerivedFromGenericType(resource);
+ if (genericResourceEither.isRight()) {
+ result = false;
+ return genericResourceEither;
+ }
+ Either<Resource, ResponseFormat> createResourcesEither = createResourceTransaction(resource, user, isNormative, inTransaction);
log.trace("************* createResourceFromYaml after full create resource {}", yamlName);
if (createResourcesEither.isRight()) {
result = false;
@@ -975,9 +1296,11 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
resource = createResourcesEither.left().value();
// add groups to resource
log.trace("************* Going to add inputs from yaml {}", yamlName);
+ if (resource.shouldGenerateInputs())
+ generateInputsFromGenericTypeProperties(resource, genericResourceEither.left().value());
Map<String, InputDefinition> inputs = parsedToscaYamlInfo.getInputs();
- Either<Resource, ResponseFormat> createInputsOnResource = createInputsOnResource(resource, user, inputs, true);
+ Either<Resource, ResponseFormat> createInputsOnResource = createInputsOnResource(resource, user, inputs, inTransaction);
if (createInputsOnResource.isRight()) {
result = false;
return createInputsOnResource;
@@ -987,7 +1310,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap = parsedToscaYamlInfo.getInstances();
log.trace("************* Going to create nodes, RI's and Relations from yaml {}", yamlName);
- createResourcesEither = createRIAndRelationsFromYaml(yamlName, resource, user, uploadComponentInstanceInfoMap, actionEnum, topologyTemplateYaml, csar, csarUUID);
+ createResourcesEither = createRIAndRelationsFromYaml(yamlName, resource, user, uploadComponentInstanceInfoMap, actionEnum, topologyTemplateYaml, csar, csarUUID, nodeTypesNewCreatedArtifacts, createdVfcs);
log.trace("************* Finished to create nodes, RI and Relation from yaml {}", yamlName);
if (createResourcesEither.isRight()) {
result = false;
@@ -1019,14 +1342,15 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
log.trace("************* Finished to add groups from yaml {}", yamlName);
log.trace("************* Going to add artifacts from yaml {}", yamlName);
- Either<Resource, ResponseFormat> createdCsarArtifactsEither = this.handleCsarArtifacts(resource, user, csarUUID, csar, createdArtifacts, ArtifactOperation.Create, false, true);
+ Either<Resource, ResponseFormat> createdCsarArtifactsEither = this.handleCsarArtifacts(resource, user, csarUUID, csar, createdArtifacts, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create), false,
+ inTransaction);
log.trace("************* Finished to add artifacts from yaml {}", yamlName);
if (createdCsarArtifactsEither.isRight()) {
result = false;
return createdCsarArtifactsEither;
}
- resource = createdCsarArtifactsEither.left().value();
+ resource = createdCsarArtifactsEither.left().value();
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
ASDCKpiApi.countCreatedResourcesKPI();
@@ -1035,8 +1359,9 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
} finally {
if (!result) {
log.warn("operation failed. do rollback");
- titanGenericDao.rollback();
- if (!createdArtifacts.isEmpty()) {
+ titanDao.rollback();
+ if (!createdArtifacts.isEmpty() || !nodeTypesNewCreatedArtifacts.isEmpty()) {
+ createdArtifacts.addAll(nodeTypesNewCreatedArtifacts);
StorageOperationStatus deleteFromEsRes = artifactsBusinessLogic.deleteAllComponentArtifactsIfNotOnGraph(createdArtifacts);
if (!deleteFromEsRes.equals(StorageOperationStatus.OK)) {
ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(deleteFromEsRes);
@@ -1047,7 +1372,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
} else {
log.debug("operation success. do commit");
- titanGenericDao.commit();
+ titanDao.commit();
}
graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(), NodeTypeEnum.Resource);
@@ -1057,7 +1382,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
private Either<Resource, ResponseFormat> createGroupsOnResource(Resource resource, User user, Map<String, GroupDefinition> groups) {
- if (groups != null && false == groups.isEmpty()) {
+ if (groups != null && !groups.isEmpty()) {
Either<List<GroupDefinition>, ResponseFormat> mergeGroupsUsingResource = updateGroupMembersUsingResource(groups, resource);
if (mergeGroupsUsingResource.isRight()) {
@@ -1065,22 +1390,14 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return Either.right(mergeGroupsUsingResource.right().value());
}
List<GroupDefinition> groupsAsList = mergeGroupsUsingResource.left().value();
-
- // Either<List<GroupDefinition>, ResponseFormat> createGroups =
- // groupBusinessLogic.createGroups(
- // resource.getUniqueId(), user.getUserId(),
- // ComponentTypeEnum.RESOURCE, groupsAsList, false,
- // true);
- // In this method we assume all instances exists in resource
- Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic.createGroups(resource, user, ComponentTypeEnum.RESOURCE, groupsAsList, true);
+ 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 = resourceOperation.getResource(resource.getUniqueId(), true);
+ 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);
@@ -1122,42 +1439,31 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
} else
groupsToCreate.addAll(groupsAsList);
-
+ Either<List<GroupDefinition>, ResponseFormat> prepareGroups = null;
if (!groupsToCreate.isEmpty()) {
- Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic.createGroups(resource, user, ComponentTypeEnum.RESOURCE, groupsToCreate, true);
- if (createGroups.isRight()) {
- return Either.right(createGroups.right().value());
+ if (groupsFromResource != null && !groupsFromResource.isEmpty()) {
+ prepareGroups = groupBusinessLogic.addGroups(resource, user, ComponentTypeEnum.RESOURCE, groupsToCreate);
+ } else {
+ prepareGroups = groupBusinessLogic.createGroups(resource, user, ComponentTypeEnum.RESOURCE, groupsToCreate);
}
- }
- if (!groupsToDelete.isEmpty()) {
- for (GroupDefinition group : groupsToDelete) {
- Either<GroupDefinition, StorageOperationStatus> deleteGroupEither = groupOperation.deleteGroup(group.getUniqueId(), true);
- if (deleteGroupEither.isRight()) {
- StorageOperationStatus storageOperationStatus = deleteGroupEither.right().value();
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageOperationStatus);
- log.debug("Failed to delete group {} under component {}, error: {}", group.getUniqueId(), resource.getNormalizedName(), actionStatus.name());
- return Either.right(componentsUtils.getResponseFormat(actionStatus));
- }
+ if (prepareGroups.isRight()) {
+ return Either.right(prepareGroups.right().value());
}
}
- if (groupsToUpdate != null && !groupsToUpdate.isEmpty()) {
- Either<List<GroupDefinition>, ResponseFormat> assotiateGroupEither = groupBusinessLogic.associateMembersToGroup(resource.getUniqueId(), user.getUserId(), ComponentTypeEnum.RESOURCE, groupsToUpdate, false, true);
- if (assotiateGroupEither.isRight()) {
- log.debug("Failed to associate artifacts to groups. Status is {} ", assotiateGroupEither.right().value());
- return Either.right(assotiateGroupEither.right().value());
+ if (!groupsToDelete.isEmpty()) {
+ prepareGroups = groupBusinessLogic.deleteGroups(resource, user, ComponentTypeEnum.RESOURCE, groupsToDelete);
+ if (prepareGroups.isRight()) {
+ return Either.right(prepareGroups.right().value());
}
- List<GroupDefinition> updatedGroups = assotiateGroupEither.left().value();
- List<String> groupsId = updatedGroups.stream().map(e -> e.getUniqueId()).collect(Collectors.toList());
-
- Either<List<GroupDefinition>, StorageOperationStatus> updateVersionEither = groupBusinessLogic.updateGroupVersion(groupsId, true);
- if (updateVersionEither.isRight()) {
- log.debug("Failed to update groups version. Status is {} ", updateVersionEither.right().value());
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updateVersionEither.right().value()), resource);
- return Either.right(responseFormat);
+ }
+ if (groupsToUpdate != null && !groupsToUpdate.isEmpty()) {
+ prepareGroups = groupBusinessLogic.updateGroups(resource, ComponentTypeEnum.RESOURCE, groupsToUpdate);
+ if (prepareGroups.isRight()) {
+ return Either.right(prepareGroups.right().value());
}
}
@@ -1165,7 +1471,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return Either.left(resource);
}
- Either<Resource, StorageOperationStatus> updatedResource = resourceOperation.getResource(resource.getUniqueId(), true);
+ 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);
@@ -1175,13 +1481,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
private Either<Resource, ResponseFormat> createInputsOnResource(Resource resource, User user, Map<String, InputDefinition> inputs, boolean inTransaction) {
if (inputs != null && false == inputs.isEmpty()) {
- List<InputDefinition> inputsAsList = new ArrayList<InputDefinition>();
- for (Entry<String, InputDefinition> entry : inputs.entrySet()) {
- InputDefinition input = entry.getValue();
- input.setName(entry.getKey());
- inputsAsList.add(input);
- }
- Either<List<InputDefinition>, ResponseFormat> createGroups = inputsBusinessLogic.createInputsInGraph(inputsAsList, resource, user, inTransaction);
+
+ Either<List<InputDefinition>, ResponseFormat> createGroups = inputsBusinessLogic.createInputsInGraph(inputs, resource, user, inTransaction);
if (createGroups.isRight()) {
return Either.right(createGroups.right().value());
}
@@ -1189,7 +1490,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return Either.left(resource);
}
- Either<Resource, StorageOperationStatus> updatedResource = resourceOperation.getResource(resource.getUniqueId(), true);
+ 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);
@@ -1204,6 +1505,10 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
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();
@@ -1219,7 +1524,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
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());
+ 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
@@ -1235,7 +1540,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
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());
+ 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)));
}
@@ -1248,19 +1553,116 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
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, User user, Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap, AuditingActionEnum actionEnum,
- String topologyTemplateYaml, Map<String, byte[]> csar, String csarUUID) {
+ String topologyTemplateYaml, Map<String, byte[]> csar, String csarUUID, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, Resource> createdVfcs) {
Either<Resource, ResponseFormat> result;
Either<Resource, ResponseFormat> createResourcesInstancesEither;
+
+ Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate = findNodeTypeArtifactsToCreate(csar, yamlName, resource);
+
log.debug("************* Going to create all nodes {}", yamlName);
- Either<Map<String, Resource>, ResponseFormat> createdResourcesFromdNodeTypeMap = this.handleNodeTypes(yamlName, resource, user, topologyTemplateYaml, csar, false);
+ Either<Map<String, Resource>, ResponseFormat> createdResourcesFromdNodeTypeMap = this.handleNodeTypes(yamlName, resource, user, topologyTemplateYaml, csar, false, nodeTypesArtifactsToCreate, nodeTypesNewCreatedArtifacts);
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());
}
+ createdVfcs.putAll(createdResourcesFromdNodeTypeMap.left().value());
+
log.debug("************* Going to create all resource instances {}", yamlName);
createResourcesInstancesEither = createResourceInstances(user, yamlName, resource, uploadComponentInstanceInfoMap, true, false, createdResourcesFromdNodeTypeMap.left().value());
@@ -1292,17 +1694,66 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return result;
}
- private Either<Map<String, Resource>, ResponseFormat> handleNodeTypes(String yamlName, Resource resource, User user, String topologyTemplateYaml, Map<String, byte[]> csar, boolean needLock) {
+ private Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> findNodeTypeArtifactsToCreate(Map<String, byte[]> csar, String yamlName, Resource resource) {
+
+ Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts = CsarUtils.extractVfcsArtifactsFromCsar(csar);
+ List<ImmutablePair<ImmutablePair<String, List<String>>, String>> extractedVfcToscaNames = extractVfcToscaNames(csar, yamlName, resource.getSystemName());
+ validateNodeTypeIdentifiers(extractedVfcsArtifacts, extractedVfcToscaNames);
+ Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = null;
+ if (!extractedVfcsArtifacts.isEmpty() && !extractedVfcToscaNames.isEmpty()) {
+ for (ImmutablePair<ImmutablePair<String, List<String>>, String> currToscaNamePair : extractedVfcToscaNames) {
+ EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> curNodeTypeArtifacts = null;
+ String currVfcToscaNamespace = currToscaNamePair.getKey().getKey();
+ List<String> relatedVfcs = currToscaNamePair.getKey().getValue();
+ List<ArtifactDefinition> currArtifactList = null;
+
+ for (String currSubstitute : relatedVfcs) {
+ if (extractedVfcsArtifacts.containsKey(currSubstitute)) {
+ if (MapUtils.isEmpty(curNodeTypeArtifacts)) {
+ curNodeTypeArtifacts = new EnumMap<>(ArtifactOperationEnum.class);
+ currArtifactList = new ArrayList<>();
+ curNodeTypeArtifacts.put(ArtifactOperationEnum.Create, currArtifactList);
+ } else {
+ currArtifactList = curNodeTypeArtifacts.get(ArtifactOperationEnum.Create);
+ }
+ handleAndAddExtractedVfcsArtifacts(currArtifactList, extractedVfcsArtifacts.get(currSubstitute));
+ }
+ }
+
+ if (nodeTypesArtifactsToHandle == null) {
+ nodeTypesArtifactsToHandle = new HashMap<>();
+ }
+ nodeTypesArtifactsToHandle.put(currVfcToscaNamespace, curNodeTypeArtifacts);
+ }
+ }
+ return nodeTypesArtifactsToHandle;
+ }
+
+ private void handleAndAddExtractedVfcsArtifacts(List<ArtifactDefinition> vfcArtifacts, List<ArtifactDefinition> artifactsToAdd) {
+ List<String> vfcArtifactNames = vfcArtifacts.stream().map(a -> a.getArtifactName()).collect(Collectors.toList());
+ artifactsToAdd.stream().forEach(a -> {
+ if (!vfcArtifactNames.contains(a.getArtifactName())) {
+ vfcArtifacts.add(a);
+ } else {
+ log.error("Can't upload two artifact with the same name {}. ", a.getArtifactName());
+ }
+ });
+
+ }
+
+ private Either<Map<String, Resource>, ResponseFormat> handleNodeTypes(String yamlName, Resource resource, User user, String topologyTemplateYaml, Map<String, byte[]> csar, boolean needLock,
+ Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts) {
Map<String, Resource> createdResourcesFromdNodeTypeMap = new HashMap<>();
Either<Map<String, Resource>, ResponseFormat> result = Either.left(createdResourcesFromdNodeTypeMap);
- String yamlFileName = Constants.GLOBAL_SUBSTITUTION_TYPE_SERVICE_TEMPLATE;
+ String yamlFileName = Constants.GLOBAL_SUBSTITUTION_TYPES_SERVICE_TEMPLATE;
if (csar != null && csar.containsKey(yamlFileName)) {
byte[] yamlFileBytes = csar.get(yamlFileName);
String globalTypesYaml = new String(yamlFileBytes, StandardCharsets.UTF_8);
- Either<Map<String, Resource>, ResponseFormat> createdNodeTypesFromGlobalTypesTemplateEither = this.createResourcesFromYamlNodeTypesList(yamlFileName, resource, globalTypesYaml, user, needLock);
+ Either<Map<String, Resource>, ResponseFormat> createdNodeTypesFromGlobalTypesTemplateEither = this.createResourcesFromYamlNodeTypesList(yamlFileName, resource, globalTypesYaml, user, needLock, nodeTypesArtifactsToHandle,
+ nodeTypesNewCreatedArtifacts);
if (createdNodeTypesFromGlobalTypesTemplateEither.isRight()) {
ResponseFormat responseFormat = createdNodeTypesFromGlobalTypesTemplateEither.right().value();
componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
@@ -1311,7 +1762,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
createdResourcesFromdNodeTypeMap.putAll(createdNodeTypesFromGlobalTypesTemplateEither.left().value());
}
- Either<Map<String, Resource>, ResponseFormat> createdNodeTypeFromMainTemplateEither = createResourcesFromYamlNodeTypesList(yamlName, resource, topologyTemplateYaml, user, needLock);
+ Either<Map<String, Resource>, ResponseFormat> createdNodeTypeFromMainTemplateEither = createResourcesFromYamlNodeTypesList(yamlName, resource, topologyTemplateYaml, user, needLock, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts);
if (createdNodeTypeFromMainTemplateEither.isRight()) {
ResponseFormat responseFormat = createdNodeTypeFromMainTemplateEither.right().value();
componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
@@ -1327,14 +1778,14 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return result;
}
- private Either<Resource, ResponseFormat> handleCsarArtifacts(Resource resource, User user, String csarUUID, Map<String, byte[]> csar, List<ArtifactDefinition> createdArtifacts, ArtifactOperation artifactOperation, boolean shouldLock,
+ private Either<Resource, ResponseFormat> handleCsarArtifacts(Resource resource, User user, String csarUUID, Map<String, byte[]> csar, List<ArtifactDefinition> createdArtifacts, ArtifactOperationInfo artifactOperation, boolean shouldLock,
boolean inTransaction) {
if (csar != null) {
String vendorLicenseModelId = null;
String vfLicenseModelId = null;
- if (artifactOperation.equals(ArtifactOperation.Update)) {
+ if (artifactOperation.getArtifactOperationEnum() == ArtifactOperationEnum.Update) {
Map<String, ArtifactDefinition> deploymentArtifactsMap = resource.getDeploymentArtifacts();
if (deploymentArtifactsMap != null && !deploymentArtifactsMap.isEmpty()) {
for (Entry<String, ArtifactDefinition> artifactEntry : deploymentArtifactsMap.entrySet()) {
@@ -1346,17 +1797,24 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
}
- createOrUpdateLicenseArtifact(resource, user, csarUUID, csar, Constants.VENDOR_LICENSE_MODEL, ArtifactTypeEnum.VENDOR_LICENSE.getType(), Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME,
- Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId, artifactOperation, shouldLock, inTransaction);
- createOrUpdateLicenseArtifact(resource, user, csarUUID, csar, Constants.VF_LICENSE_MODEL, ArtifactTypeEnum.VF_LICENSE.getType(), Constants.VF_LICENSE_LABEL, Constants.VF_LICENSE_DISPLAY_NAME, Constants.VF_LICENSE_DESCRIPTION,
- vfLicenseModelId, artifactOperation, shouldLock, inTransaction);
+ // Specific Behavior for license artifacts
+ createOrUpdateSingleNonMetaArtifact(resource, user, csarUUID, csar, CsarUtils.ARTIFACTS_PATH + Constants.VENDOR_LICENSE_MODEL, Constants.VENDOR_LICENSE_MODEL, ArtifactTypeEnum.VENDOR_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT,
+ Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME, Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId, artifactOperation, null, shouldLock, inTransaction);
+ createOrUpdateSingleNonMetaArtifact(resource, user, csarUUID, csar, CsarUtils.ARTIFACTS_PATH + Constants.VF_LICENSE_MODEL, Constants.VF_LICENSE_MODEL, ArtifactTypeEnum.VF_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT,
+ Constants.VF_LICENSE_LABEL, Constants.VF_LICENSE_DISPLAY_NAME, Constants.VF_LICENSE_DESCRIPTION, vfLicenseModelId, artifactOperation, null, shouldLock, inTransaction);
+
+ Either<Resource, ResponseFormat> eitherCreateResult = createOrUpdateNonMetaArtifacts(csarUUID, csar, resource, user, createdArtifacts, shouldLock, inTransaction, artifactOperation);
+ if (eitherCreateResult.isRight()) {
+ return Either.right(eitherCreateResult.right().value());
+ }
+
Either<ImmutablePair<String, String>, ResponseFormat> artifacsMetaCsarStatus = CsarValidationUtils.getArtifactsMeta(csar, csarUUID, componentsUtils);
if (artifacsMetaCsarStatus.isLeft()) {
String artifactsFileName = artifacsMetaCsarStatus.left().value().getKey();
String artifactsContents = artifacsMetaCsarStatus.left().value().getValue();
Either<Resource, ResponseFormat> createArtifactsFromCsar = Either.left(resource);
- if (artifactOperation.equals(ArtifactOperation.Create))
+ if (artifactOperation.getArtifactOperationEnum() == ArtifactOperationEnum.Create)
createArtifactsFromCsar = createResourceArtifactsFromCsar(csarUUID, csar, resource, user, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, inTransaction);
else
createArtifactsFromCsar = updateResourceArtifactsFromCsar(csarUUID, csar, resource, user, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, inTransaction);
@@ -1371,19 +1829,12 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (groupsToDelete != null && !groupsToDelete.isEmpty()) {
Set<String> artifactsToDelete = new HashSet<String>();
- for (GroupDefinition group : groupsToDelete) {
- List<String> artifacts = group.getArtifacts();
- if (artifacts != null) {
- artifactsToDelete.addAll(artifacts);
- Either<GroupDefinition, StorageOperationStatus> deleteGroupEither = groupOperation.deleteGroup(group.getUniqueId(), inTransaction);
- if (deleteGroupEither.isRight()) {
- StorageOperationStatus storageOperationStatus = deleteGroupEither.right().value();
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageOperationStatus);
- log.debug("Failed to delete group {} under component {}, error: {}", group.getUniqueId(), resource.getNormalizedName(), actionStatus.name());
- return Either.right(componentsUtils.getResponseFormat(actionStatus));
- }
- }
- }
+ /*
+ * for (GroupDefinition group : groupsToDelete) { List<String> artifacts = group.getArtifacts(); if (artifacts != null) { artifactsToDelete.addAll(artifacts); Either<GroupDefinition, StorageOperationStatus> deleteGroupEither =
+ * groupOperation.deleteGroup(group.getUniqueId(), inTransaction); if (deleteGroupEither.isRight()) { StorageOperationStatus storageOperationStatus = deleteGroupEither.right().value(); ActionStatus actionStatus =
+ * componentsUtils.convertFromStorageResponse(storageOperationStatus); log.debug("Failed to delete group {} under component {}, error: {}", group.getUniqueId(), resource.getNormalizedName(), actionStatus.name()); return
+ * Either.right(componentsUtils.getResponseFormat(actionStatus)); } } }
+ */
for (String artifactId : artifactsToDelete) {
Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(resource.getUniqueId(), artifactId, user, AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE,
resource, null, null, shouldLock, inTransaction);
@@ -1391,31 +1842,31 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
log.debug("Couldn't delete artifact {}", artifactId);
return Either.right(handleDelete.right().value());
}
-
}
- Either<Resource, StorageOperationStatus> eitherGerResource = resourceOperation.getResource(resource.getUniqueId(), inTransaction);
- if (eitherGerResource.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
+ 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 = eitherGerResource.left().value();
+ resource = eitherGetResource.left().value();
}
}
}
return Either.left(resource);
}
- private Either<Boolean, ResponseFormat> createOrUpdateLicenseArtifact(Resource resource, User user, String csarUUID, Map<String, byte[]> csar, String artifactFileName, String artifactType, String artifactLabel, String artifactDisplayName,
- String artifactDescription, String artifactId, ArtifactOperation operation, boolean shouldLock, boolean inTransaction) {
+ private Either<Boolean, ResponseFormat> createOrUpdateSingleNonMetaArtifact(Resource resource, User user, String csarUUID, Map<String, byte[]> csar, String artifactPath, String artifactFileName, String artifactType,
+ ArtifactGroupTypeEnum artifactGroupType, String artifactLabel, String artifactDisplayName, String artifactDescription, String artifactId, ArtifactOperationInfo operation, List<ArtifactDefinition> createdArtifacts, boolean shouldLock,
+ boolean inTransaction) {
byte[] artifactFileBytes = null;
- if (csar.containsKey(Constants.ARTIFACTS + artifactFileName)) {
- artifactFileBytes = csar.get(Constants.ARTIFACTS + artifactFileName);
+ if (csar.containsKey(artifactPath)) {
+ artifactFileBytes = csar.get(artifactPath);
}
Either<Boolean, ResponseFormat> result = Either.left(true);
- if (operation.equals(ArtifactOperation.Update)) {
+ if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Update || operation.getArtifactOperationEnum() == ArtifactOperationEnum.Delete) {
if (artifactId != null && !artifactId.isEmpty() && artifactFileBytes == null) {
Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(resource.getUniqueId(), artifactId, user, AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, resource, null,
null, shouldLock, inTransaction);
@@ -1426,31 +1877,40 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
if ((artifactId == null || artifactId.isEmpty()) && artifactFileBytes != null) {
- operation = ArtifactOperation.Create;
+ operation = artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create);
}
}
if (artifactFileBytes != null) {
- Map<String, Object> vendorLicenseModelJson = buildJsonForUpdateArtifact(artifactId, artifactFileName, artifactType, artifactLabel, artifactDisplayName, artifactDescription, artifactFileBytes, null);
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> vfLicenceArtifactCreateEither = createOrUpdateCsarArtifactFromJson(resource, user, vendorLicenseModelJson, operation, shouldLock, inTransaction);
-
- if (vfLicenceArtifactCreateEither.isRight()) {
+ Map<String, Object> vendorLicenseModelJson = buildJsonForUpdateArtifact(artifactId, artifactFileName, artifactType, artifactGroupType, artifactLabel, artifactDisplayName, artifactDescription, artifactFileBytes, null);
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts = createOrUpdateCsarArtifactFromJson(resource, user, vendorLicenseModelJson, operation, shouldLock, inTransaction);
+ addNonMetaCreatedArtifactsToSupportRollback(operation, createdArtifacts, eitherNonMetaArtifacts);
+ if (eitherNonMetaArtifacts.isRight()) {
BeEcompErrorManager.getInstance().logInternalFlowError("UploadLicenseArtifact", "Failed to upload license artifact: " + artifactFileName + "With csar uuid: " + csarUUID, ErrorSeverity.WARNING);
- return Either.right(vfLicenceArtifactCreateEither.right().value());
+ return Either.right(eitherNonMetaArtifacts.right().value());
}
}
return result;
}
- private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createOrUpdateCsarArtifactFromJson(Resource resource, User user, Map<String, Object> json, ArtifactOperation operation, boolean shoudLock, boolean inTransaction) {
+ private void addNonMetaCreatedArtifactsToSupportRollback(ArtifactOperationInfo operation, List<ArtifactDefinition> createdArtifacts, Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts) {
+ if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create && 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.calculateMD5ByString(jsonStr);
ArtifactDefinition artifactDefinitionFromJson = RepresentationUtils.convertJsonToArtifactDefinition(jsonStr, ArtifactDefinition.class);
-
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = artifactsBusinessLogic.handleArtifactRequest(resource.getUniqueId(), user.getUserId(), ComponentTypeEnum.RESOURCE, operation,
- artifactDefinitionFromJson.getUniqueId(), artifactDefinitionFromJson, origMd5, jsonStr, null, null, null, null, shoudLock, inTransaction);
+ 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);
if (uploadArtifactToService.isRight())
return Either.right(uploadArtifactToService.right().value());
@@ -1489,37 +1949,6 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
return createResourceArtifacts(csarUUID, csar, resource, user, parseResourceInfoFromYamlEither.left().value(), AuditingActionEnum.CREATE_RESOURCE, createdNewArtifacts, shouldLock, inTransaction);
}
- // find artifacts to delete
- Set<String> artifactNotInGroupSet = findArtifactsNotInGroupToDelete(groups, createdDeplymentArtifactsAfterDelete);
-
- // delete all artifacts which not in groups
- if (!artifactNotInGroupSet.isEmpty()) {
- for (String artifactId : artifactNotInGroupSet) {
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(resource.getUniqueId(), artifactId, user, AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, resource, null,
- null, shouldLock, inTransaction);
- if (handleDelete.isRight()) {
- return Either.right(handleDelete.right().value());
- }
-
- }
- Either<Resource, StorageOperationStatus> eitherGerResource = resourceOperation.getResource(resource.getUniqueId(), inTransaction);
- if (eitherGerResource.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
-
- return Either.right(responseFormat);
-
- }
-
- resource = eitherGerResource.left().value();
- deplymentArtifact = resource.getDeploymentArtifacts();
-
- createdDeplymentArtifactsAfterDelete.clear();
- if (deplymentArtifact != null && !deplymentArtifact.isEmpty()) {
- for (Entry<String, ArtifactDefinition> entry : deplymentArtifact.entrySet()) {
- createdDeplymentArtifactsAfterDelete.add(entry.getValue());
- }
- }
- }
// find master in group
Map<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupArtifact = findMasterArtifactInGroup(groups, deplymentArtifact);
@@ -1551,18 +1980,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
Map<String, List<String>> dissocArtifactFromGroup = new HashMap<String, List<String>>();
Set<ArtifactTemplateInfo> jsonMasterArtifacts = parsedGroup.keySet();
-
- Map<GroupDefinition, MergedArtifactInfo> mergedgroup = mergeGroupInUpdateFlow(groupArtifact, parsedGroup, artifactsToDelete, groupToDelete, jsonMasterArtifacts);
-
- // find artifacts to delete
- for (Entry<String, List<ArtifactDefinition>> deleteGroup : groupToDelete.entrySet()) {
-
- List<ArtifactDefinition> artifacts = deleteGroup.getValue();
- for (ArtifactDefinition artifact : artifacts) {
- findArtifactToDelete(parsedGroup, artifactsToDelete, deleteGroup.getKey(), artifact);
- }
-
- }
+ Map<GroupDefinition, MergedArtifactInfo> mergedgroup = mergeGroupInUpdateFlow(groupArtifact, parsedGroup, artifactsToDelete, groupToDelete, jsonMasterArtifacts, createdDeplymentArtifactsAfterDelete);
// Set<String> deletedArtifactsName = new HashSet<String>();
Either<List<ArtifactDefinition>, ResponseFormat> deletedArtifactsEither = deleteArtifactsInUpdateCsarFlow(resource, user, shouldLock, inTransaction, artifactsToDelete, groupToDelete);
@@ -1602,24 +2020,25 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
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());
+ }
+ }
+
groups = resource.getGroups();
List<GroupDefinition> groupToUpdate = new ArrayList<>();
// update vfModule names
Set<GroupDefinition> groupForAssociateWithMembers = mergedgroup.keySet();
if (groups != null && !groups.isEmpty()) {
- Either<List<GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic.validateUpdateVfGroupNamesOnGraph(groups, resource.getSystemName(), inTransaction);
+ Either<List<GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic.validateUpdateVfGroupNamesOnGraph(groups, resource, inTransaction);
if (validateUpdateVfGroupNamesRes.isRight()) {
return Either.right(validateUpdateVfGroupNamesRes.right().value());
}
List<GroupDefinition> heatGroups = null;
- // 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 = groups.stream().filter(e -> e.getMembers() != null).collect(Collectors.toList());
;
@@ -1634,7 +2053,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
Map<String, String> members = new HashMap<String, String>();
Set<String> artifactsGroup = new HashSet<String>();
artifactsGroup.addAll(group.getArtifacts());
- associateMembersTToArtifacts(createdNewArtifacts, createdDeplymentArtifactsAfterDelete, heatGroups, artifactsGroup, members);
+ associateMembersToArtifacts(createdNewArtifacts, createdDeplymentArtifactsAfterDelete, heatGroups, artifactsGroup, members);
if (!members.isEmpty()) {
group.setMembers(members);
@@ -1642,14 +2061,12 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
}
- if (!groupToUpdate.isEmpty()) {
- Either<List<GroupDefinition>, ResponseFormat> assotiateGroupEither = groupBusinessLogic.associateMembersToGroup(resource.getUniqueId(), user.getUserId(), ComponentTypeEnum.RESOURCE, groupToUpdate, false, true);
- if (assotiateGroupEither.isRight()) {
- log.debug("Failed to associate artifacts to groups. Status is {} ", assotiateGroupEither.right().value());
- return Either.right(assotiateGroupEither.right().value());
-
- }
- }
+ /*
+ * if (!groupToUpdate.isEmpty()) { Either<List<GroupDefinition>, ResponseFormat> assotiateGroupEither = groupBusinessLogic.associateMembersToGroup(resource.getUniqueId(), user.getUserId(), ComponentTypeEnum.RESOURCE, groupToUpdate, false,
+ * true); if (assotiateGroupEither.isRight()) { log.debug("Failed to associate artifacts to groups. Status is {} ", assotiateGroupEither.right().value()); return Either.right(assotiateGroupEither.right().value());
+ *
+ * } }
+ */
}
@@ -1689,18 +2106,18 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
// updatedGroup
if (!groupForAssociateWithMembers.isEmpty()) {
- List<String> groupsId = groupForAssociateWithMembers.stream().map(e -> e.getUniqueId()).collect(Collectors.toList());
+ List<GroupDefinition> groupsId = groupForAssociateWithMembers.stream().map(e -> e).collect(Collectors.toList());
- Either<List<GroupDefinition>, StorageOperationStatus> updateVersionEither = groupBusinessLogic.updateGroupVersion(groupsId, true);
+ 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());
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updateVersionEither.right().value()), resource);
- return Either.right(responseFormat);
+
+ return Either.right(updateVersionEither.right().value());
}
}
- Either<Resource, StorageOperationStatus> eitherGerResource = resourceOperation.getResource(resource.getUniqueId(), inTransaction);
+ Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
if (eitherGerResource.isRight()) {
ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
@@ -1714,30 +2131,50 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
private Either<List<ArtifactDefinition>, ResponseFormat> deleteArtifactsInUpdateCsarFlow(Resource resource, User user, boolean shouldLock, boolean inTransaction, Set<ArtifactDefinition> artifactsToDelete,
Map<String, List<ArtifactDefinition>> groupToDelete) {
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<ArtifactDefinition, StorageOperationStatus> removeArifactFromGraph = artifactOperation.removeArifactFromResource(resourceId, artifact.getUniqueId(), NodeTypeEnum.Resource, true, true); if
+ * (removeArifactFromGraph.isRight()) { StorageOperationStatus status = removeArifactFromGraph.right().value(); log.debug("Failed to delete heat env artifact {} . status is {}", artifact.getUniqueId(), status); ActionStatus
+ * actionStatus = componentsUtils.convertFromStorageResponse(status); return Either.right(componentsUtils.getResponseFormat(actionStatus)); }
+ *
+ * deletedArtifacts.add(removeArifactFromGraph.left().value());
+ */
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(resource.getUniqueId(), 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());
+
+ else {
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(resourceId, artifact.getUniqueId(), user, AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, resource,
+ null, null, shouldLock, inTransaction);
+ if (handleDelete.isRight()) {
+ 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()) {
- Either<GroupDefinition, StorageOperationStatus> deleteGroupEither = groupOperation.deleteGroup(deleteGroup.getKey(), inTransaction);
- if (deleteGroupEither.isRight()) {
- StorageOperationStatus storageOperationStatus = deleteGroupEither.right().value();
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageOperationStatus);
- log.debug("Failed to delete group {} under component {}, error: {}", deleteGroup.getKey(), resource.getNormalizedName(), actionStatus.name());
-
- return Either.right(componentsUtils.getResponseFormat(actionStatus));
+ 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());
}
}
}
@@ -1755,6 +2192,10 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
List<String> dissList = new ArrayList<String>();
for (ArtifactDefinition art : dissArtifactsInGroup) {
dissList.add(art.getUniqueId());
+ // String heatEnvId = checkAndGetHeatEnvId(art);
+ // if (!heatEnvId.isEmpty()) {
+ // dissList.add(heatEnvId);
+ // }
}
dissocArtifactFromGroup.put(entry.getKey().getUniqueId(), dissList);
}
@@ -1768,7 +2209,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
artifactsToUpdateMap.put(entry.getKey(), artifactsToUpdate);
}
- // Map<String, Set<String>> dissocArtifactFromGroup = new
+ // Map<String, Set<String>> dissocArtifactFromGroup = new HashMap<String, Set<String>>();
// HashMap<String, Set<String>>();
List<GroupDefinition> dissotiateArtifactsgroups = new ArrayList<GroupDefinition>();
for (Entry<String, List<String>> dissotiateEntry : dissocArtifactFromGroup.entrySet()) {
@@ -1779,15 +2220,13 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
dissotiateArtifactsgroups.add(dissotiateGroup);
}
if (!dissotiateArtifactsgroups.isEmpty()) {
- log.debug("try to dissociate artifacts from groups ");
- Either<List<GroupDefinition>, ResponseFormat> dissotiateGroupEither = groupBusinessLogic.dissociateArtifactsFromGroup(resource.getUniqueId(), user.getUserId(), ComponentTypeEnum.RESOURCE, dissotiateArtifactsgroups, shouldLock,
- inTransaction);
- if (dissotiateGroupEither.isRight()) {
- log.debug("Failed to dissociate artifacts from groups. Status is {} ", dissotiateGroupEither.right().value());
- resEither = Either.right(dissotiateGroupEither.right().value());
- return resEither;
-
- }
+ /*
+ * log.debug("try to dissociate artifacts from groups "); Either<List<GroupDefinition>, ResponseFormat> dissotiateGroupEither = groupBusinessLogic.dissociateArtifactsFromGroup(resource.getUniqueId(), user.getUserId(),
+ * ComponentTypeEnum.RESOURCE, dissotiateArtifactsgroups, shouldLock, inTransaction); if (dissotiateGroupEither.isRight()) { log.debug("Failed to dissociate artifacts from groups. Status is {} ", dissotiateGroupEither.right().value());
+ * resEither = Either.right(dissotiateGroupEither.right().value()); return resEither;
+ *
+ * }
+ */
}
if (!artifactsToUpdateMap.isEmpty()) {
@@ -1825,6 +2264,16 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (artifactTemplate.getFileName().equalsIgnoreCase(createdArtifact.getArtifactName())) {
arifactsUids.add(createdArtifact.getUniqueId());
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;
}
@@ -1834,18 +2283,33 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (artifactTemplate.getFileName().equalsIgnoreCase(createdNewArtifact.getArtifactName())) {
arifactsUids.add(createdNewArtifact.getUniqueId());
isCreate = false;
+ String heatEnvId = checkAndGetHeatEnvId(createdNewArtifact);
+ if (!heatEnvId.isEmpty()) {
+ arifactsUids.add(heatEnvId);
+ }
break;
}
}
}
if (isCreate) {
- Either<ArtifactDefinition, ResponseFormat> createArtifactEither = createDeploymentArtifact(csarUUID, csar, resource, user, artifactTemplate, createdNewArtifacts, labelCounter, shouldLock, inTransaction);
+ Either<ArtifactDefinition, ResponseFormat> createArtifactEither = createDeploymentArtifact(csarUUID, csar, resource, user, ARTIFACTS_PATH, artifactTemplate, createdNewArtifacts, labelCounter, shouldLock, inTransaction);
if (createArtifactEither.isRight()) {
resEither = Either.right(createArtifactEither.right().value());
return resEither;
}
- arifactsUids.add(createArtifactEither.left().value().getUniqueId());
+ ArtifactDefinition createdArtifact = createArtifactEither.left().value();
+ arifactsUids.add(createdArtifact.getUniqueId());
+ ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(createdArtifact.getArtifactType());
+ if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_VOL) {
+ Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder = artifactsBusinessLogic.createHeatEnvPlaceHolder(createdArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME, resource.getUniqueId(), NodeTypeEnum.Resource,
+ resource.getName(), user, resource, null);
+ if (createHeatEnvPlaceHolder.isRight()) {
+ return Either.right(createHeatEnvPlaceHolder.right().value());
+ }
+ String heatEnvId = createHeatEnvPlaceHolder.left().value().getUniqueId();
+ arifactsUids.add(heatEnvId);
+ }
}
}
@@ -1860,18 +2324,16 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
}
- if (!associateArtifactGroup.isEmpty()) {
-
- log.debug("Try to associate artifacts to groups.");
-
- Either<List<GroupDefinition>, ResponseFormat> assotiateGroupEither = groupBusinessLogic.associateArtifactsToGroup(resource.getUniqueId(), user.getUserId(), ComponentTypeEnum.RESOURCE, associateArtifactGroup, shouldLock, inTransaction);
- if (assotiateGroupEither.isRight()) {
- log.debug("Failed to associate artifacts to groups. Status is {} ", assotiateGroupEither.right().value());
- resEither = Either.right(assotiateGroupEither.right().value());
- return resEither;
-
- }
- }
+ /*
+ * if (!associateArtifactGroup.isEmpty()) {
+ *
+ * log.debug("Try to associate artifacts to groups.");
+ *
+ * Either<List<GroupDefinition>, ResponseFormat> assotiateGroupEither = groupBusinessLogic.associateArtifactsToGroup(resource.getUniqueId(), user.getUserId(), ComponentTypeEnum.RESOURCE, associateArtifactGroup, shouldLock, inTransaction); if
+ * (assotiateGroupEither.isRight()) { log.debug("Failed to associate artifacts to groups. Status is {} ", assotiateGroupEither.right().value()); resEither = Either.right(assotiateGroupEither.right().value()); return resEither;
+ *
+ * } }
+ */
ComponentParametersView parametersView = new ComponentParametersView();
parametersView.disableAll();
@@ -1879,7 +2341,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
parametersView.setIgnoreUsers(false);
parametersView.setIgnoreArtifacts(false);
parametersView.setIgnoreGroups(false);
- Either<Resource, StorageOperationStatus> eitherGerResource = resourceOperation.getComponent(resource.getUniqueId(), parametersView, inTransaction);
+
+ Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId(), parametersView);
if (eitherGerResource.isRight()) {
ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
@@ -1893,7 +2356,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
private Map<GroupDefinition, MergedArtifactInfo> mergeGroupInUpdateFlow(Map<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupArtifact, Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroup,
- Set<ArtifactDefinition> artifactsToDelete, Map<String, List<ArtifactDefinition>> groupToDelete, Set<ArtifactTemplateInfo> jsonMasterArtifacts) {
+ 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();
@@ -1902,7 +2365,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
for (ArtifactDefinition maserArtifact : createdArtifactMap.keySet()) {
listToDelete = createdArtifactMap.get(maserArtifact);
for (ArtifactDefinition artToDelete : listToDelete) {
- findArtifactToDelete(parsedGroup, artifactsToDelete, groupListEntry.getKey().getUniqueId(), artToDelete);
+ findArtifactToDelete(parsedGroup, artifactsToDelete, groupListEntry.getKey().getUniqueId(), artToDelete, createdDeplymentArtifacts);
}
for (ArtifactTemplateInfo jsonMasterArtifact : jsonMasterArtifacts) {
if (maserArtifact.getArtifactName().equalsIgnoreCase(jsonMasterArtifact.getFileName())) {
@@ -1950,19 +2413,37 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return artifactNotInGroupSet;
}
- private void findArtifactToDelete(Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroup, Set<ArtifactDefinition> artifactsToDelete, String deleteGroupId, ArtifactDefinition artifact) {
+ 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()) && artifact.getArtifactType().equalsIgnoreCase(template.getType())) {
+ 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);
}
@@ -2017,7 +2498,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
log.debug("createResourceArtifacts end");
log.debug("getResource start");
- Either<Resource, StorageOperationStatus> eitherGerResource = resourceOperation.getResource(resource.getUniqueId(), inTransaction);
+ 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);
@@ -2035,35 +2516,31 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
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> 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(csarUUID, csar, resource, user, artifactsGroup, groupTemplateInfo, createdNewArtifacts, artifactsFromResource, labelCounter, shouldLock, inTransaction);
+ resStatus = createDeploymentArtifactsFromCsar(csarUUID, csar, resource, user, artifactsGroup, artifactsUUIDGroup, groupTemplateInfo, createdNewArtifacts, artifactsFromResource, labelCounter, shouldLock, inTransaction);
if (resStatus.isRight())
return resStatus;
Map<String, String> members = new HashMap<String, String>();
- associateMembersTToArtifacts(createdNewArtifacts, artifactsFromResource, heatGroups, artifactsGroup, members);
+ 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);
@@ -2072,21 +2549,49 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
prop.setName(Constants.IS_BASE);
prop.setValue(Boolean.toString(groupTemplateInfo.isBase()));
- properties.add(prop);
- groupDefinition.setProperties(properties);
- Either<GroupDefinition, ResponseFormat> createGroup = groupBusinessLogic.createGroup(resource.getUniqueId(), user.getUserId(), ComponentTypeEnum.RESOURCE, groupDefinition, inTransaction);
- if (createGroup.isRight())
- return Either.right(createGroup.right().value());
+ 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);
+ properties.add(prop);
+ groupDefinition.convertFromGroupProperties(properties);
+ // Either<GroupDefinition, ResponseFormat> createGroup = groupBusinessLogic.createGroup(resource.getUniqueId(), user.getUserId(), ComponentTypeEnum.RESOURCE, groupDefinition, inTransaction);
+ // if (createGroup.isRight())
+ // return Either.right(createGroup.right().value());
+ 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, user, ComponentTypeEnum.RESOURCE, needToAdd);
+ if (addGroups.isRight())
+ return Either.right(addGroups.right().value());
+
return resStatus;
}
- private Either<Resource, ResponseFormat> createDeploymentArtifactsFromCsar(String csarUUID, Map<String, byte[]> csar, Resource resource, User user, Set<String> artifactsGroup, ArtifactTemplateInfo artifactTemplateInfo,
- List<ArtifactDefinition> createdArtifacts, List<ArtifactDefinition> artifactsFromResource, int labelCounter, boolean shoudLock, boolean inTransaction) {
+ private Either<Resource, ResponseFormat> createDeploymentArtifactsFromCsar(String csarUUID, Map<String, byte[]> csar, Resource resource, User user, Set<String> artifactsGroup, Set<String> artifactsUUIDGroup,
+ ArtifactTemplateInfo artifactTemplateInfo, List<ArtifactDefinition> createdArtifacts, List<ArtifactDefinition> artifactsFromResource, int labelCounter, boolean shoudLock, boolean inTransaction) {
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
@@ -2094,12 +2599,14 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
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;
}
@@ -2110,12 +2617,15 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
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;
}
@@ -2124,21 +2634,35 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
// if not exist need to create
if (!alreadyExist) {
- Either<ArtifactDefinition, ResponseFormat> newArtifactEither = createDeploymentArtifact(csarUUID, csar, resource, user, artifactTemplateInfo, createdArtifacts, labelCounter, shoudLock, inTransaction);
+ Either<ArtifactDefinition, ResponseFormat> newArtifactEither = createDeploymentArtifact(csarUUID, csar, resource, user, ARTIFACTS_PATH, artifactTemplateInfo, createdArtifacts, labelCounter, shoudLock, inTransaction);
if (newArtifactEither.isRight()) {
resStatus = Either.right(newArtifactEither.right().value());
return resStatus;
}
- artifactUid = newArtifactEither.left().value().getUniqueId();
-
+ 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(), user, 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(csarUUID, csar, resource, user, artifactsGroup, relatedArtifactTemplateInfo, createdArtifacts, artifactsFromResource, labelCounter, shoudLock, inTransaction);
+ resStatus = createDeploymentArtifactsFromCsar(csarUUID, csar, resource, user, artifactsGroup, artifactsUUIDGroup, relatedArtifactTemplateInfo, createdArtifacts, artifactsFromResource, labelCounter, shoudLock, inTransaction);
if (resStatus.isRight())
return resStatus;
}
@@ -2165,6 +2689,121 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
+ private Either<Resource, ResponseFormat> createOrUpdateNonMetaArtifacts(String csarUUID, Map<String, byte[]> csar, Resource resource, User user, List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction,
+ ArtifactOperationInfo artifactOperation) {
+
+ Either<Resource, ResponseFormat> resStatus = null;
+ Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>();
+
+ try {
+ List<NonMetaArtifactInfo> artifactPathAndNameList =
+ // Stream of file paths contained in csar
+ csar.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());
+
+ EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> vfCsarArtifactsToHandle = null;
+
+ if (artifactOperation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) {
+ vfCsarArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
+ vfCsarArtifactsToHandle.put(artifactOperation.getArtifactOperationEnum(), artifactPathAndNameList);
+ } else {
+ Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandleRes = findVfCsarArtifactsToHandle(resource, artifactPathAndNameList, user);
+
+ 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, user, csarUUID, csar, 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<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(String csarUUID, Map<String, byte[]> csar, Resource resource, User user, List<ArtifactTemplateInfo> artifactsTemplateList, List<ArtifactDefinition> createdArtifacts,
int labelCounter, boolean shouldLock, boolean inTransaction) {
Either<Resource, ResponseFormat> resStatus = Either.left(resource);
@@ -2182,67 +2821,146 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
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 = createDeploymentArtifactsFromCsar(csarUUID, csar, resource, user, artifactsGroup, groupTemplateInfo, createdArtifacts, labelCounter, shouldLock, inTransaction);
+ resStatus = createDeploymentArtifactFromCsar(csarUUID, ARTIFACTS_PATH, csar, resource, user, artifactsGroup, artifactsUUIDGroup, groupTemplateInfo, createdArtifacts, labelCounter, shouldLock, inTransaction);
log.debug("createDeploymentArtifactsFromCsar end");
if (resStatus.isRight())
return resStatus;
Map<String, String> members = new HashMap<String, String>();
- associateMembersTToArtifacts(createdArtifacts, null, heatGroups, artifactsGroup, members);
+ 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);
- groupDefinition.setProperties(properties);
+ 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");
- // Either<GroupDefinition, ResponseFormat> createGroup =
- // groupBusinessLogic.createGroup(resource.getUniqueId(),
- // user.getUserId(), ComponentTypeEnum.RESOURCE, groupDefinition,
- // inTransaction);
- // Ignore validations and get component
// Since in these groups we handle only artifacts, then no need to
// fetch component instances
- ComponentParametersView componentParametersView = new ComponentParametersView();
- componentParametersView.disableAll();
- componentParametersView.setIgnoreUsers(false);
- componentParametersView.setIgnoreArtifacts(false);
- componentParametersView.setIgnoreGroups(false);
- componentParametersView.setIgnoreComponentInstances(false);
- Either<Resource, StorageOperationStatus> component = resourceOperation.getComponent(resource.getUniqueId(), componentParametersView, inTransaction);
- if (component.isRight()) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- Either<GroupDefinition, ResponseFormat> createGroup = groupBusinessLogic.createGroup(component.left().value(), user, ComponentTypeEnum.RESOURCE, groupDefinition, inTransaction);
- log.debug("createGroup end");
- if (createGroup.isRight())
- return Either.right(createGroup.right().value());
+ // Either<GroupDefinition, ResponseFormat> createGroup = groupBusinessLogic.createGroup(comp, user, ComponentTypeEnum.RESOURCE, groupDefinition, inTransaction);
+ // log.debug("createGroup end");
+ // if (createGroup.isRight())
+ // return Either.right(createGroup.right().value());
+ 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(), user, ComponentTypeEnum.RESOURCE, needToCreate);
+ if (createGroups.isRight()) {
+ return Either.right(createGroups.right().value());
}
+
return resStatus;
}
- private void associateMembersTToArtifacts(List<ArtifactDefinition> createdArtifacts, List<ArtifactDefinition> artifactsFromResource, List<GroupDefinition> heatGroups, Set<String> artifactsGroup, Map<String, String> members) {
+ 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.getProperties();
+ 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()) {
@@ -2274,45 +2992,63 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
}
- private Either<Resource, ResponseFormat> createDeploymentArtifactsFromCsar(String csarUUID, Map<String, byte[]> csar, Resource resource, User user, Set<String> artifactsGroup, ArtifactTemplateInfo artifactTemplateInfo,
- List<ArtifactDefinition> createdArtifacts, int labelCounter, boolean shoudLock, boolean inTransaction) {
+ private Either<Resource, ResponseFormat> createDeploymentArtifactFromCsar(String csarUUID, String artifactPath, Map<String, byte[]> csar, Resource resource, User user, Set<String> artifactsGroup, Set<String> artifactsUUIDGroup,
+ ArtifactTemplateInfo artifactTemplateInfo, List<ArtifactDefinition> createdArtifacts, int labelCounter, boolean shoudLock, boolean inTransaction) {
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(csarUUID, csar, resource, user, artifactTemplateInfo, createdArtifacts, labelCounter, shoudLock, inTransaction);
+ Either<ArtifactDefinition, ResponseFormat> newArtifactEither = createDeploymentArtifact(csarUUID, csar, resource, user, artifactPath, artifactTemplateInfo, createdArtifacts, labelCounter, shoudLock, inTransaction);
if (newArtifactEither.isRight()) {
resStatus = Either.right(newArtifactEither.right().value());
return resStatus;
}
- artifactUid = newArtifactEither.left().value().getUniqueId();
+ 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(), user, 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(csarUUID, csar, resource, user, artifactsGroup, relatedArtifactTemplateInfo, createdArtifacts, labelCounter, shoudLock, inTransaction);
+ resStatus = createDeploymentArtifactFromCsar(csarUUID, artifactPath, csar, resource, user, artifactsGroup, artifactsUUIDGroup, relatedArtifactTemplateInfo, createdArtifacts, labelCounter, shoudLock, inTransaction);
if (resStatus.isRight())
return resStatus;
}
@@ -2320,17 +3056,28 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return resStatus;
}
- private Either<ArtifactDefinition, ResponseFormat> createDeploymentArtifact(String csarUUID, Map<String, byte[]> csar, Resource resource, User user, ArtifactTemplateInfo artifactTemplateInfo, List<ArtifactDefinition> createdArtifacts,
- int labelCounter, boolean shoudLock, boolean inTransaction) {
- String artifactUid;
- Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactContententStatus = CsarValidationUtils.getArtifactsContent(csarUUID, csar, artifactTemplateInfo.getFileName(), componentsUtils);
- if (artifactContententStatus.isRight())
+ 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(String csarUUID, Map<String, byte[]> csar, Resource resource, User user, String artifactPath, ArtifactTemplateInfo artifactTemplateInfo,
+ List<ArtifactDefinition> createdArtifacts, int labelCounter, boolean shoudLock, boolean inTransaction) {
+ final String artifactFileName = artifactTemplateInfo.getFileName();
+ Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactContententStatus = CsarValidationUtils.getArtifactsContent(csarUUID, csar, artifactPath + artifactFileName, artifactFileName, componentsUtils);
+ 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, user, json, ArtifactOperation.Create, shoudLock, inTransaction);
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = createOrUpdateCsarArtifactFromJson(resource, user, json, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create),
+ shoudLock, inTransaction);
if (uploadArtifactToService.isRight())
return Either.right(uploadArtifactToService.right().value());
@@ -2338,21 +3085,40 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
ArtifactDefinition currentInfo = uploadArtifactToService.left().value().left().value();
if (currentInfo.getHeatParameters() != null) {
- Either<ArtifactDefinition, ResponseFormat> updateEnvEither = updateHeatParamsFromCsar(csarUUID, csar, artifactTemplateInfo, currentInfo);
+ Either<ArtifactDefinition, ResponseFormat> updateEnvEither = updateHeatParamsFromCsar(resource, csarUUID, csar, artifactTemplateInfo, currentInfo, false);
if (updateEnvEither.isRight()) {
- log.debug("failed to update parameters to artifact {}", artifactTemplateInfo.getFileName());
+ log.debug("failed to update parameters to artifact {}", artifactFileName);
return Either.right(updateEnvEither.right().value());
}
- artifactUid = updateEnvEither.left().value().getUniqueId();
- createdArtifacts.add(updateEnvEither.left().value());
currentInfo = updateEnvEither.left().value();
- } else {
-
- artifactUid = currentInfo.getUniqueId();
- createdArtifacts.add(currentInfo);
}
+
+ createdArtifacts.add(currentInfo);
+
+ return Either.left(currentInfo);
+
+ }
+
+ private Either<ArtifactDefinition, ResponseFormat> createInformationalArtifact(String csarUUID, Map<String, byte[]> csar, Resource resource, User user, ArtifactTemplateInfo artifactTemplateInfo, int labelCounter, boolean shoudLock,
+ boolean inTransaction) {
+ final String artifactFileName = artifactTemplateInfo.getFileName();
+ String artifactPath = CsarUtils.ARTIFACTS_PATH + CsarUtils.INFORMATIONAL_ARTIFACTS + artifactFileName;
+ Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactContententStatus = CsarValidationUtils.getArtifactsContent(csarUUID, csar, artifactPath, artifactFileName, componentsUtils);
+ if (artifactContententStatus.isRight())
+ return Either.right(artifactContententStatus.right().value());
+
+ Map<String, Object> json = buildJsonForArtifact(artifactTemplateInfo, artifactContententStatus.left().value().getValue(), labelCounter);
+
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = createOrUpdateCsarArtifactFromJson(resource, user, json, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create),
+ shoudLock, inTransaction);
+
+ if (uploadArtifactToService.isRight())
+ return Either.right(uploadArtifactToService.right().value());
+
+ ArtifactDefinition currentInfo = uploadArtifactToService.left().value().left().value();
+
return Either.left(currentInfo);
}
@@ -2380,15 +3146,17 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
- Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactContententStatus = CsarValidationUtils.getArtifactsContent(csarUUID, csar, artifactTemplateInfo.getFileName(), componentsUtils);
+ Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactContententStatus = CsarValidationUtils.getArtifactsContent(csarUUID, csar, 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(), oldArtifact.getArtifactLabel(), oldArtifact.getArtifactDisplayName(), oldArtifact.getDescription(),
- artifactContententStatus.left().value().getRight(), updatedRequiredArtifacts);
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = createOrUpdateCsarArtifactFromJson(resource, user, json, ArtifactOperation.Update, shouldLock, inTransaction);
+ Map<String, Object> json = buildJsonForUpdateArtifact(oldArtifact.getUniqueId(), artifactFileName, oldArtifact.getArtifactType(), ArtifactGroupTypeEnum.DEPLOYMENT, oldArtifact.getArtifactLabel(), oldArtifact.getArtifactDisplayName(),
+ oldArtifact.getDescription(), artifactContententStatus.left().value().getRight(), updatedRequiredArtifacts);
+
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = createOrUpdateCsarArtifactFromJson(resource, user, json, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Update),
+ shouldLock, inTransaction);
if (uploadArtifactToService.isRight()) {
resStatus = Either.right(uploadArtifactToService.right().value());
@@ -2396,12 +3164,13 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
ArtifactDefinition currentInfo = uploadArtifactToService.left().value().left().value();
- Either<ArtifactDefinition, ResponseFormat> updateEnvEither = updateHeatParamsFromCsar(csarUUID, csar, artifactTemplateInfo, currentInfo);
+ Either<ArtifactDefinition, ResponseFormat> updateEnvEither = updateHeatParamsFromCsar(resource, csarUUID, csar, 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!!!!)
artifactUid = updateEnvEither.left().value().getUniqueId();
updatedArtifacts.add(updateEnvEither.left().value());
@@ -2411,70 +3180,79 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
- private Either<ArtifactDefinition, ResponseFormat> updateHeatParamsFromCsar(String csarUUID, Map<String, byte[]> csar, ArtifactTemplateInfo artifactTemplateInfo, ArtifactDefinition currentInfo) {
+ private Either<ArtifactDefinition, ResponseFormat> updateHeatParamsFromCsar(Resource resource, String csarUUID, Map<String, byte[]> csar, ArtifactTemplateInfo artifactTemplateInfo, ArtifactDefinition currentInfo, boolean isUpdateEnv) {
Either<ArtifactDefinition, ResponseFormat> resStatus = Either.left(currentInfo);
if (artifactTemplateInfo.getEnv() != null && !artifactTemplateInfo.getEnv().isEmpty()) {
- Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactparamsStatus = CsarValidationUtils.getArtifactsContent(csarUUID, csar, artifactTemplateInfo.getEnv(), componentsUtils);
+ Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactparamsStatus = CsarValidationUtils.getArtifactsContent(csarUUID, csar, 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());
- if (propsStatus.isRight()) {
-
- resStatus = Either.right(propsStatus.right().value());
- return resStatus;
- }
- List<HeatParameterDefinition> updatedHeatEnvParams = propsStatus.left().value();
- List<HeatParameterDefinition> currentHeatEnvParams = currentInfo.getHeatParameters();
- 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;
+ Either<List<HeatParameterDefinition>, ResponseFormat> propsStatus = extractHeatParameters(ArtifactTypeEnum.HEAT_ENV.getType(), artifactTemplateInfo.getEnv(), artifactparamsStatus.left().value().getValue(), false);
+ /*
+ * if (propsStatus.isRight()) {
+ *
+ * resStatus = Either.right(propsStatus.right().value()); return resStatus; }
+ */
+ 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(HeatParameterType.isValidType(currHeatParam.getType()).getConverter().convert(updatedParamValue, null, null));
+ // newHeatEnvParams.add(currHeatParam);
+ break;
}
- currHeatParam.setCurrentValue(paramType.getConverter().convert(updatedParamValue, null, null));
- newHeatEnvParams.add(currHeatParam);
- break;
}
}
- }
- if (!newHeatEnvParams.isEmpty()) {
- StorageOperationStatus operationStatus = heatParametersOperation.updateHeatParameters(currentHeatEnvParams);
-
- if (operationStatus != StorageOperationStatus.OK) {
- log.debug("Failed to update artifact on graph - {}", currentInfo.getUniqueId());
-
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(operationStatus));
- resStatus = Either.right(responseFormat);
- return resStatus;
+ 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())));
}
}
}
-
+ }
+ if (isUpdateEnv) {
+ 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())));
+ }
+ }
}
return resStatus;
}
- private Either<List<HeatParameterDefinition>, ResponseFormat> extractHeatParameters(String artifactType, String fileName, byte[] content) {
+ private Either<List<HeatParameterDefinition>, ResponseFormat> extractHeatParameters(String artifactType, String fileName, byte[] content, boolean is64Encoded) {
// extract heat parameters
- String heatDecodedPayload = GeneralUtility.isBase64Encoded(content) ? new String(Base64.decodeBase64(content)) : new String(content);
+ 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);
@@ -2495,15 +3273,11 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
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. All files that are inside the CSAR are not encoded and need to encoded. The check for isBase64 is not in cases we get files with extension .cert or .key these files are base64 but if do not
- * encode them again, when the user download them, the decoded file will return not the encoded file that was upload.
- */
+ // DE250204: There is no need to check if base64 encoding.
+
// String encodedPayload = new String(artifactContentent);
// boolean isEncoded = GeneralUtility.isBase64Encoded(artifactContentent);
// if (!isEncoded) {
- // log.debug("payload is encoded. perform decode");
String encodedPayload = Base64.encodeBase64String(artifactContentent);
// }
json.put(Constants.ARTIFACT_PAYLOAD_DATA, encodedPayload);
@@ -2520,7 +3294,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return json;
}
- private Map<String, Object> buildJsonForUpdateArtifact(String artifactId, String artifactName, String artifactType, String label, String displayName, String description, byte[] artifactContentent,
+ 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>();
@@ -2532,17 +3306,17 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
json.put(Constants.ARTIFACT_DESCRIPTION, description);
String encodedPayload = new String(artifactContentent);
- // DE250204 - need to encode all.
- //boolean isEncoded = GeneralUtility.isBase64Encoded(artifactContentent);
- //if (!isEncoded) {
- log.debug("payload is encoded. perform decode");
- encodedPayload = Base64.encodeBase64String(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, ArtifactGroupTypeEnum.DEPLOYMENT.getType());
+ 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;
@@ -2642,23 +3416,34 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return Either.right(responseFormat);
}
- Map<String, List<PropertyDefinition>> propertiesListPerResource = new HashMap<>();
+ 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);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status)), yamlName);
- long totalCreateRel = 0;
- long totalCreatePropVal = 0;
- Iterator<Entry<String, UploadComponentInstanceInfo>> nodesInfoValue = uploadResInstancesMap.entrySet().iterator();
- while (nodesInfoValue.hasNext()) {
- Entry<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoEntry = nodesInfoValue.next();
- UploadComponentInstanceInfo uploadComponentInstanceInfo = uploadComponentInstanceInfoEntry.getValue();
+ }
+ 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>> instArtifacts = new HashMap<>();
+ Map<String, List<AttributeDefinition>> instAttributes = new HashMap<>();
+ Map<String, Resource> originCompMap = new HashMap<>();
+ List<RequirementCapabilityRelDef> relations = new ArrayList<>();
+
+ 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);
@@ -2666,107 +3451,115 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return Either.right(responseFormat);
}
String resourceInstanceId = currentCompInstance.getUniqueId();
-
- log.debug("************* addPropertyValuesToRi start");
- long startAddProperty = System.currentTimeMillis();
-
- ResponseFormat addPropertiesValueToRiRes = addPropertyValuesToRi(uploadComponentInstanceInfo, resource, resourceInstanceId, currentCompInstance, yamlName, propertiesListPerResource);
- log.debug("************* addPropertyValuesToRi end");
- totalCreatePropVal += (System.currentTimeMillis() - startAddProperty);
-
+ Resource originResource = null;
+ if (!originCompMap.containsKey(currentCompInstance.getComponentUid())) {
+ Either<Resource, StorageOperationStatus> getPropertyRes = toscaOperationFacade.getToscaFullElement(currentCompInstance.getComponentUid());
+ if (getPropertyRes.isRight()) {
+ log.debug("failed to find properties of resource {} status is {}", currentCompInstance.getComponentUid(), getPropertyRes);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getPropertyRes.right().value()), yamlName);
+ return Either.right(responseFormat);
+ }
+ originResource = getPropertyRes.left().value();
+ originCompMap.put(originResource.getUniqueId(), originResource);
+ } else {
+ originResource = originCompMap.get(currentCompInstance.getComponentUid());
+ }
+ if (originResource.getCapabilities() != null && !originResource.getCapabilities().isEmpty())
+ instCapabilties.put(currentCompInstance, originResource.getCapabilities());
+ if (originResource.getRequirements() != null && !originResource.getRequirements().isEmpty())
+ instRequirements.put(currentCompInstance, originResource.getRequirements());
+ if (originResource.getDeploymentArtifacts() != null && !originResource.getDeploymentArtifacts().isEmpty())
+ instArtifacts.put(resourceInstanceId, originResource.getDeploymentArtifacts());
+ if (originResource.getAttributes() != null && !originResource.getAttributes().isEmpty())
+ instAttributes.put(resourceInstanceId, originResource.getAttributes());
+
+ ResponseFormat addPropertiesValueToRiRes = addPropertyValuesToRi(uploadComponentInstanceInfo, resource, originResource, currentCompInstance, yamlName, instProperties, allDataTypes.left().value());
if (addPropertiesValueToRiRes.getStatus() != 200) {
return Either.right(addPropertiesValueToRiRes);
}
- Map<String, List<UploadReqInfo>> regMap = uploadComponentInstanceInfo.getRequirements();
- if (regMap == null)
- continue;
- Iterator<Entry<String, List<UploadReqInfo>>> nodesRegValue = regMap.entrySet().iterator();
-
- long startAddRelation = System.currentTimeMillis();
-
- while (nodesRegValue.hasNext()) {
- Entry<String, List<UploadReqInfo>> nodesRegInfoEntry = nodesRegValue.next();
-
- List<UploadReqInfo> uploadRegInfoList = nodesRegInfoEntry.getValue();
- for (UploadReqInfo uploadRegInfo : uploadRegInfoList) {
- log.debug("Going to create relation {}", uploadRegInfo.getName());
- String regName = uploadRegInfo.getName();
- String nodeCapName = uploadRegInfo.getNode();
- RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef();
- regCapRelDef.setFromNode(resourceInstanceId);
- log.debug("try to find available requirement {} ", regName);
- Either<RequirementDefinition, ResponseFormat> eitherReqStatus = findAviableRequiremen(regName, yamlName, uploadComponentInstanceInfo, currentCompInstance);
- if (eitherReqStatus.isRight()) {
- log.debug("failed to find available requirement {} status is {}", regName, eitherReqStatus.right().value());
- return Either.right(eitherReqStatus.right().value());
- }
- RequirementDefinition validReq = eitherReqStatus.left().value();
- List<RequirementAndRelationshipPair> reqAndRelationshipPairList = regCapRelDef.getRelationships();
- if (reqAndRelationshipPairList == null)
- reqAndRelationshipPairList = new ArrayList<RequirementAndRelationshipPair>();
- RequirementAndRelationshipPair reqAndRelationshipPair = new RequirementAndRelationshipPair();
- reqAndRelationshipPair.setRequirement(regName);
- reqAndRelationshipPair.setRequirementOwnerId(validReq.getOwnerId());
- reqAndRelationshipPair.setRequirementUid(validReq.getUniqueId());
-
- ComponentInstance currentCapCompInstance = null;
- for (ComponentInstance compInstance : componentInstancesList) {
- if (compInstance.getName().equals(uploadRegInfo.getNode())) {
- currentCapCompInstance = compInstance;
- break;
- }
- }
+ }
- if (currentCapCompInstance == null) {
- log.debug("component instance with name {} in resource {} ", uploadRegInfo.getNode(), resource.getUniqueId());
- BeEcompErrorManager.getInstance().logInternalDataError("component instance with name " + uploadRegInfo.getNode() + " in resource {} ", resource.getUniqueId(), ErrorSeverity.ERROR);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
- return Either.right(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 Either.right(responseFormat);
- }
- reqAndRelationshipPair.setCapability(aviableCapForRel.getName());
- reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId());
- reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId());
- reqAndRelationshipPairList.add(reqAndRelationshipPair);
- regCapRelDef.setRelationships(reqAndRelationshipPairList);
- ComponentInstanceBusinessLogic componentInstanceBL = getComponentInstanceBL();
- Either<RequirementCapabilityRelDef, ResponseFormat> eitherRelationRes = componentInstanceBL.associateRIToRIOnGraph(resource.getUniqueId(), regCapRelDef, ComponentTypeEnum.RESOURCE, inTransaction);
- log.debug("************* finished to create relation {}", uploadRegInfo.getName());
- if (eitherRelationRes.isRight()) {
- log.debug("failed to associate ri {} to ri {}", regCapRelDef.getFromNode(), regCapRelDef.getToNode());
- return Either.right(eitherRelationRes.right().value());
- }
+ 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);
+ }
- }
+ StorageOperationStatus addArtToInst = toscaOperationFacade.associateArtifactToInstances(instArtifacts, resource.getUniqueId(), user);
+ if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
+ log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
+ return Either.right(responseFormat);
+ }
- }
- totalCreateRel += (System.currentTimeMillis() - startAddRelation);
+ 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);
}
- /*
- * List<InputDefinition> inputs = resource.getInputs(); for(InputDefinition input: inputs){ if(input.getProperties() != null){ this.inputOperation.associatePropertiesToInputOnGraph(input. getUniqueId(), input.getProperties()); } }
- */
- // Either<Resource, StorageOperationStatus> eitherGerResource =
- // resourceOperation.getResource(resource.getUniqueId(), inTransaction);
- log.debug("************* create relations took : create {}, add property value {}", totalCreateRel, totalCreatePropVal);
- log.debug("************* in create relations, getResource start");
ComponentParametersView parametersView = new ComponentParametersView();
parametersView.disableAll();
parametersView.setIgnoreComponentInstances(false);
- parametersView.setIgnoreUsers(false);
- parametersView.setIgnoreArtifacts(false);
- parametersView.setIgnoreGroups(false);
- Either<Resource, StorageOperationStatus> eitherGerResource = resourceOperation.getComponent(resource.getUniqueId(), parametersView, inTransaction);
+ parametersView.setIgnoreComponentInstancesProperties(false);
+ parametersView.setIgnoreCapabilities(false);
+ parametersView.setIgnoreRequirements(false);
+
+ Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId(), parametersView);
+
+ if (eitherGerResource.isRight()) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
+
+ return Either.right(responseFormat);
+
+ }
+
+ resource = eitherGerResource.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);
+ }
+
+ log.debug("************* in create relations, getResource start");
+
+ eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
log.debug("************* in create relations, getResource end");
if (eitherGerResource.isRight()) {
ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
@@ -2777,117 +3570,216 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return Either.left(eitherGerResource.left().value());
}
- private ResponseFormat addPropertyValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, Resource resource, String resourceInstanceId, ComponentInstance currentCompInstance, String yamlName,
- Map<String, List<PropertyDefinition>> propertiesListPerResource) {
+ private ResponseFormat addRelationToRI(String yamlName, Resource resource, UploadComponentInstanceInfo nodesInfoValue, List<RequirementCapabilityRelDef> relations) {
+ List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
+ long totalCreateRel = 0;
+ long totalCreatePropVal = 0;
+
+ 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();
+
+ log.debug("************* addPropertyValuesToRi start");
+ long startAddProperty = System.currentTimeMillis();
+ log.debug("************* addPropertyValuesToRi end");
+ totalCreatePropVal += (System.currentTimeMillis() - startAddProperty);
+ Map<String, List<UploadReqInfo>> regMap = uploadComponentInstanceInfo.getRequirements();
+ if (regMap == null) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK, yamlName);
+ return responseFormat;
+ }
+ Iterator<Entry<String, List<UploadReqInfo>>> nodesRegValue = regMap.entrySet().iterator();
+
+ long startAddRelation = System.currentTimeMillis();
+
+ while (nodesRegValue.hasNext()) {
+ Entry<String, List<UploadReqInfo>> nodesRegInfoEntry = nodesRegValue.next();
+
+ List<UploadReqInfo> uploadRegInfoList = nodesRegInfoEntry.getValue();
+ for (UploadReqInfo uploadRegInfo : uploadRegInfoList) {
+ log.debug("Going to create relation {}", uploadRegInfo.getName());
+ String regName = uploadRegInfo.getName();
+ String nodeCapName = uploadRegInfo.getNode();
+ RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef();
+ regCapRelDef.setFromNode(resourceInstanceId);
+ log.debug("try to find available requirement {} ", regName);
+ Either<RequirementDefinition, ResponseFormat> eitherReqStatus = findAviableRequiremen(regName, yamlName, uploadComponentInstanceInfo, currentCompInstance, uploadRegInfo.getCapabilityName());
+ if (eitherReqStatus.isRight()) {
+ log.debug("failed to find available requirement {} status is {}", regName, eitherReqStatus.right().value());
+ return eitherReqStatus.right().value();
+ }
+
+ RequirementDefinition validReq = eitherReqStatus.left().value();
+ List<RequirementAndRelationshipPair> reqAndRelationshipPairList = regCapRelDef.getRelationships();
+ if (reqAndRelationshipPairList == null)
+ reqAndRelationshipPairList = new ArrayList<RequirementAndRelationshipPair>();
+ RequirementAndRelationshipPair reqAndRelationshipPair = new RequirementAndRelationshipPair();
+ reqAndRelationshipPair.setRequirement(regName);
+ reqAndRelationshipPair.setRequirementOwnerId(validReq.getOwnerId());
+ reqAndRelationshipPair.setRequirementUid(validReq.getUniqueId());
+ RelationshipImpl relationship = new RelationshipImpl();
+ relationship.setType(validReq.getCapability());
+ reqAndRelationshipPair.setRelationships(relationship);
+
+ ComponentInstance currentCapCompInstance = null;
+ for (ComponentInstance compInstance : componentInstancesList) {
+ if (compInstance.getName().equals(uploadRegInfo.getNode())) {
+ currentCapCompInstance = compInstance;
+ break;
+ }
+ }
+
+ if (currentCapCompInstance == null) {
+ log.debug("component instance with name {} in resource {} ", uploadRegInfo.getNode(), resource.getUniqueId());
+ BeEcompErrorManager.getInstance().logInternalDataError("component instance with name " + uploadRegInfo.getNode() + " in resource {} ", resource.getUniqueId(), ErrorSeverity.ERROR);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
+ return responseFormat;
+ }
+ regCapRelDef.setToNode(currentCapCompInstance.getUniqueId());
+ log.debug("try to find aviable Capability req name is {} ", validReq.getName());
+ CapabilityDefinition aviableCapForRel = findAvailableCapabilityByTypeOrName(validReq, currentCapCompInstance, uploadRegInfo);
+ if (aviableCapForRel == null) {
+ log.debug("aviable capability was not found. req name is {} component instance is {}", validReq.getName(), currentCapCompInstance.getUniqueId());
+ BeEcompErrorManager.getInstance().logInternalDataError("aviable capability was not found. req name is " + validReq.getName() + " component instance is " + currentCapCompInstance.getUniqueId(), resource.getUniqueId(),
+ ErrorSeverity.ERROR);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
+ return responseFormat;
+ }
+ reqAndRelationshipPair.setCapability(aviableCapForRel.getName());
+ reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId());
+ reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId());
+ reqAndRelationshipPairList.add(reqAndRelationshipPair);
+ regCapRelDef.setRelationships(reqAndRelationshipPairList);
+ relations.add(regCapRelDef);
+
+ }
+
+ }
+ totalCreateRel += (System.currentTimeMillis() - startAddRelation);
+
+ 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();
if (propMap != null && propMap.size() > 0) {
Map<String, PropertyDefinition> currPropertiesMap = new HashMap<String, PropertyDefinition>();
- List<PropertyDefinition> propertiesList = new ArrayList<PropertyDefinition>();
- Integer index = currentCompInstance.getPropertyValueCounter();
- Integer indexInput = currentCompInstance.getInputValueCounter();
- List<PropertyDefinition> listFromMap = propertiesListPerResource.get(currentCompInstance.getComponentUid());
- if (listFromMap != null) {
- propertiesList = listFromMap;
- } else {
- TitanOperationStatus getPropertyRes = ((PropertyOperation) propertyOperation).findAllResourcePropertiesRecursively(currentCompInstance.getComponentUid(), propertiesList);
- if (!getPropertyRes.equals(TitanOperationStatus.OK)) {
- log.debug("failed to find properties of resource {} status is {}", currentCompInstance.getComponentUid(), getPropertyRes);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(getPropertyRes)), yamlName);
- return responseFormat;
+
+ int index = 0;
+ List<PropertyDefinition> listFromMap = originResource.getProperties();
+ if (listFromMap == null || listFromMap.isEmpty()) {
+ log.debug("failed to find properties ");
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND);
+ return responseFormat;
+ }
+ for (PropertyDefinition prop : listFromMap) {
+ String propName = prop.getName();
+ if (!currPropertiesMap.containsKey(propName)) {
+ currPropertiesMap.put(propName, prop);
}
- propertiesListPerResource.put(currentCompInstance.getComponentUid(), propertiesList);
}
- if (propertiesList.size() > 0) {
- for (PropertyDefinition prop : propertiesList) {
- String propName = prop.getName();
- if (!currPropertiesMap.containsKey(propName)) {
- currPropertiesMap.put(propName, prop);
- }
+ List<ComponentInstanceProperty> 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;
}
- 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;
- ComponentInstanceInput inputValue = null;
- // TODO
- String value = null;
- List<GetInputValueInfo> 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());
- }
+ 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);
- 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()));
+ }
- Either<ComponentInstanceProperty, StorageOperationStatus> result = componentInstanceOperation.addPropertyValueToResourceInstance(property, resourceInstanceId, isValidate, index, true);
- if (result.isRight()) {
- log.debug("Failed to add property value {} to resource instance {}", property, resourceInstanceId);
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
- return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, currentCompInstance.getName());
- }
- Either<Integer, StorageOperationStatus> increaseCounterRes = componentInstanceOperation.increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, GraphPropertiesDictionary.PROPERTY_COUNTER, true);
- if (increaseCounterRes.isRight()) {
- log.debug("Failed to increase resource property counter {} to resource instance {}", property, resourceInstanceId);
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(increaseCounterRes.right().value());
- return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, currentCompInstance.getName());
- }
- index = increaseCounterRes.left().value();
- if (getInputs != null && !getInputs.isEmpty()) {
- for (GetInputValueInfo 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, resourceInstanceId);
- return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
- }
+ // 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);
- Optional<InputDefinition> optional = inputs.stream().filter(p -> p.getName().equals(getInput.getInputName())).findAny();
+ 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 {} ", getInput.getInputName());
+ log.debug("Failed to find input {} ", getInputIndex.getInputName());
// @@TODO error message
return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
}
- InputDefinition input = optional.get();
- TitanOperationStatus status = inputOperation.associatePropertyToInput(resourceInstanceId, input.getUniqueId(), result.left().value(), getInput);
- if (status != TitanOperationStatus.OK) {
- log.debug("Failed to associate input {} tp property value{} ", getInput.getInputName(), result.left().value().getValueUniqueUid());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status)), yamlName);
- return responseFormat;
- }
- GetInputValueInfo 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();
- status = inputOperation.associatePropertyToInput(resourceInstanceId, inputIndex.getUniqueId(), result.left().value(), getInputIndex);
- if (status != TitanOperationStatus.OK) {
- log.debug("Failed to associate input {} tp property value{} ", getInput.getInputName(), result.left().value().getValueUniqueUid());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status)), yamlName);
- return responseFormat;
- }
-
- }
+ 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);
}
@@ -2904,6 +3796,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
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;
@@ -2912,18 +3805,30 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (!capByName.isPresent()) {
return null;
}
- CapabilityDefinition cap = capByName.get();
+ 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));
+
+ }
+
+ }
+
// TODO temporary fix - remove specific capability node validation -
// String reqNode = validReq.getNode();
// if (reqNode != null && !reqNode.isEmpty() &&
// !cap.getCapabilitySources().contains(reqNode)) {
// return null;
// }
- RequirementAndRelationshipPair relationPair = getReqRelPair(cap);
- Either<Boolean, StorageOperationStatus> eitherStatus = componentInstanceOperation.isAvailableCapabilty(currentCapCompInstance, relationPair);
- if (eitherStatus.isRight() || eitherStatus.left().value() == false) {
- return null;
- }
+ // RequirementAndRelationshipPair relationPair = getReqRelPair(cap);
+ // Either<Boolean, StorageOperationStatus> eitherStatus = componentInstanceOperation.isAvailableCapabilty(currentCapCompInstance, relationPair);
+ // if (eitherStatus.isRight() || eitherStatus.left().value() == false) {
+ // return null;
+ // }
return cap;
}
@@ -2949,12 +3854,21 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
// continue;
// }
// }
-
- RequirementAndRelationshipPair relationPair = getReqRelPair(cap);
- Either<Boolean, StorageOperationStatus> eitherStatus = componentInstanceOperation.isAvailableCapabilty(currentCapCompInstance, relationPair);
- if (eitherStatus.isRight() || eitherStatus.left().value() == false)
- continue;
- else {
+ 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;
}
@@ -2963,33 +3877,63 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return aviableCapForRel;
}
- private Either<RequirementDefinition, ResponseFormat> findAviableRequiremen(String regName, String yamlName, UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance) {
+ private Either<RequirementDefinition, ResponseFormat> findAviableRequiremen(String regName, String yamlName, UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance, String capName) {
Map<String, List<RequirementDefinition>> comInstRegDefMap = currentCompInstance.getRequirements();
-
- Iterator<Entry<String, List<RequirementDefinition>>> regListValue = comInstRegDefMap.entrySet().iterator();
+ List<RequirementDefinition> list = comInstRegDefMap.get(capName);
RequirementDefinition validRegDef = null;
- while (regListValue.hasNext()) {
- Entry<String, List<RequirementDefinition>> regInfoEntry = regListValue.next();
-
- List<RequirementDefinition> comInstRegDefList = regInfoEntry.getValue();
+ 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;
+ }
- for (RequirementDefinition comInstRegDef : comInstRegDefList) {
- if (!regName.equals(comInstRegDef.getName()))
- continue;
- RequirementAndRelationshipPair relationPair = new RequirementAndRelationshipPair();
- relationPair.setRequirementUid(comInstRegDef.getUniqueId());
- relationPair.setCapability(comInstRegDef.getCapability());
- relationPair.setRequirementOwnerId(comInstRegDef.getOwnerId());
- Either<Boolean, StorageOperationStatus> eitherStatus = componentInstanceOperation.isAvailableRequirement(currentCompInstance, relationPair);
- if (eitherStatus.isLeft() && eitherStatus.left().value() == true) {
- validRegDef = comInstRegDef;
+ }
+ }
+ if (validRegDef != null) {
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);
@@ -2997,6 +3941,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return Either.left(validRegDef);
}
+ @SuppressWarnings("unchecked")
public Either<ParsedToscaYamlInfo, ResponseFormat> parseResourceInfoFromYaml(String yamlFileName, Resource resource, String resourceYml, User user) {
Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(resourceYml);
@@ -3034,6 +3979,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
private Either<Resource, ResponseFormat> createResourceInstances(User user, String yamlName, Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap, boolean inTransaction, boolean needLock,
Map<String, Resource> nodeTypeNamespaceMap) {
+
+ 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);
@@ -3041,25 +3988,26 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return Either.right(responseFormat);
}
- Map<String, Resource> existingnodeTypeMap = new HashMap<String, Resource>();
+ Map<String, Resource> existingnodeTypeMap = new HashMap<>();
if (nodeTypeNamespaceMap != null && !nodeTypeNamespaceMap.isEmpty()) {
nodeTypeNamespaceMap.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);
+ 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());
+ log.debug("*************Going to create resource instances {}", uploadComponentInstanceInfo.getName());
if (nodeTypeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
uploadComponentInstanceInfo.setType(nodeTypeNamespaceMap.get(uploadComponentInstanceInfo.getType()).getToscaResourceName());
}
- Either<Resource, ResponseFormat> eitherResource = validateResourceInstanceBeforeCreate(yamlName, inTransaction, uploadComponentInstanceInfo, existingnodeTypeMap);
+ eitherResource = validateResourceInstanceBeforeCreate(yamlName, uploadComponentInstanceInfo, existingnodeTypeMap);
if (eitherResource.isRight()) {
return eitherResource;
}
@@ -3067,7 +4015,6 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
ComponentInstance componentInstance = new ComponentInstance();
- componentInstance.setName(uploadComponentInstanceInfo.getName());
componentInstance.setComponentUid(refResource.getUniqueId());
ComponentTypeEnum containerComponentType = resource.getComponentType();
@@ -3087,26 +4034,24 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return Either.right(responseFormat);
}
Resource origResource = existingnodeTypeMap.get(uploadComponentInstanceInfo.getType());
- ComponentInstanceBusinessLogic componentInstanceBL = getComponentInstanceBL();
- Either<ComponentInstance, ResponseFormat> eitherCreateCI = componentInstanceBL.createComponentInstanceOnGraph(ComponentTypeEnum.RESOURCE_PARAM_NAME, resource, origResource, componentInstance, user.getUserId(), needLock, inTransaction);
- if (eitherCreateCI.isRight()) {
- log.debug("createResourceInstances - failed to create resource instance with name {} and type ", uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
- return Either.right(eitherCreateCI.right().value());
- }
+ componentInstance.setName(uploadComponentInstanceInfo.getName());
+ componentInstance.setIcon(origResource.getIcon());
- ComponentInstance createdCI = eitherCreateCI.left().value();
- createdCI.setName(uploadComponentInstanceInfo.getName());
- /*
- * updateComponentInstance(String containerComponentParam, org.openecomp.sdc.be.model.Component containerComponent, String componentInstanceId, ComponentInstance componentInstance, boolean inTransaction, boolean needLock)
- */
- eitherCreateCI = componentInstanceBL.updateComponentInstance(ComponentTypeEnum.RESOURCE_PARAM_NAME, resource, origResource, createdCI.getUniqueId(), createdCI, needLock, inTransaction);
- if (eitherCreateCI.isRight()) {
- log.debug("createResourceInstances - failed to update resource instance with name {} and type ", uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
- return Either.right(eitherCreateCI.right().value());
+ 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("*************finished to create and update resource instances {}", uploadComponentInstanceInfo.getName());
}
+
log.debug("*************Going to get resource {}", resource.getUniqueId());
ComponentParametersView parametersView = new ComponentParametersView();
parametersView.disableAll();
@@ -3114,7 +4059,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
parametersView.setIgnoreUsers(false);
parametersView.setIgnoreInputs(false); // inputs are read when creating
// property values on instances
- Either<Resource, StorageOperationStatus> eitherGerResource = resourceOperation.getComponent(resource.getUniqueId(), parametersView, inTransaction);
+ 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);
@@ -3135,20 +4080,13 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return Either.left(eitherGerResource.left().value());
}
- private Either<Resource, ResponseFormat> validateResourceInstanceBeforeCreate(String yamlName, boolean inTransaction, UploadComponentInstanceInfo uploadComponentInstanceInfo, Map<String, Resource> nodeTypeNamespaceMap) {
+ private Either<Resource, ResponseFormat> validateResourceInstanceBeforeCreate(String yamlName, UploadComponentInstanceInfo uploadComponentInstanceInfo, Map<String, Resource> nodeTypeNamespaceMap) {
log.debug("validateResourceInstanceBeforeCreate - going to validate resource instance with name {} and type before create", uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
Resource refResource = null;
if (nodeTypeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
refResource = nodeTypeNamespaceMap.get(uploadComponentInstanceInfo.getType());
} else {
-
- Either<Boolean, StorageOperationStatus> eithervalidateResource = resourceOperation.validateToscaResourceNameExists(uploadComponentInstanceInfo.getType());
- if ((eithervalidateResource.isRight() && eithervalidateResource.right().value() == StorageOperationStatus.NOT_FOUND) || eithervalidateResource.left().value() == true) {
- log.debug("validateResourceInstanceBeforeCreate - resource instance with name {} and type not valid", uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
- return Either.right(responseFormat);
- }
- Either<Resource, StorageOperationStatus> findResourceEither = resourceOperation.getLatestCertifiedByToscaResourceName(uploadComponentInstanceInfo.getType(), inTransaction);
+ 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()));
@@ -3291,6 +4229,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
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());
@@ -3319,7 +4258,6 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
propertyDef.setValue(propValue);
}
- propertyDef.setName(propName);
if (moduleProp.containsKey(propName)) {
moduleProp.get(propName).add(propertyDef);
} else {
@@ -3337,18 +4275,22 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (objValue instanceof Map) {
Map<String, Object> objMap = (Map<String, Object>) objValue;
- 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);
+ 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;
+ } else if (value instanceof List) {
+ List<Object> propSubValueList = (List<Object>) value;
- createInputPropList(propertyDef, propSubValueList);
- }
+ createInputPropList(propertyDef, propSubValueList);
+ }
+ }
}
} else if (objValue instanceof List) {
@@ -3365,10 +4307,10 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (propValue.containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName())) {
Object getInput = propValue.get(ToscaTagNamesEnum.GET_INPUT.getElementName());
- GetInputValueInfo getInputInfo = new GetInputValueInfo();
- List<GetInputValueInfo> getInputs = propertyDef.getGet_input();
+ GetInputValueDataDefinition getInputInfo = new GetInputValueDataDefinition();
+ List<GetInputValueDataDefinition> getInputs = propertyDef.getGet_input();
if (getInputs == null) {
- getInputs = new ArrayList<GetInputValueInfo>();
+ getInputs = new ArrayList<GetInputValueDataDefinition>();
}
if (getInput instanceof String) {
@@ -3388,7 +4330,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
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());
- GetInputValueInfo getInputInfoIndex = new GetInputValueInfo();
+ GetInputValueDataDefinition getInputInfoIndex = new GetInputValueDataDefinition();
getInputInfoIndex.setInputName((String) index);
getInputInfoIndex.setPropName(propName);
getInputInfo.setGetInputIndex(getInputInfoIndex);
@@ -3607,32 +4549,35 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify");
if (inTransaction == false) {
log.debug("operation failed. do rollback");
- titanGenericDao.rollback();
+ titanDao.rollback();
}
} else if (inTransaction == false) {
log.debug("operation success. do commit");
- titanGenericDao.commit();
+ titanDao.commit();
}
}
}
- /**
+ /*
+ * /**
+ *
* @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, 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) {
// check if resource already exist
- Either<Resource, StorageOperationStatus> latestByName = resourceOperation.getLatestByName(resource.getName(), true);
+ 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 = resourceOperation.getLatestByToscaResourceName(resource.getToscaResourceName(), true);
+ Either<Resource, StorageOperationStatus> latestByToscaName = toscaOperationFacade.getLatestByToscaResourceName(resource.getToscaResourceName());
if (latestByToscaName.isRight() && latestByToscaName.right().value().equals(StorageOperationStatus.NOT_FOUND))
result = createResourceByImport(resource, user, isNormative, isInTransaction);
@@ -3672,7 +4617,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (response.isRight()) {
return Either.right(response.right().value());
}
- Either<Resource, ResponseFormat> createResponse = createResourceByDao(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isNormative, isInTransaction);
+ Either<Resource, ResponseFormat> createResponse = createResourceByDao(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isNormative, isInTransaction, null);
if (createResponse.isRight()) {
return Either.right(createResponse.right().value());
} else {
@@ -3684,7 +4629,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
public boolean isResourceExist(String resourceName) {
- Either<Resource, StorageOperationStatus> latestByName = resourceOperation.getLatestByName(resourceName, false);
+ Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade.getLatestByName(resourceName);
return latestByName.isLeft();
}
@@ -3750,7 +4695,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (newResource.getToscaArtifacts() == null || newResource.getToscaArtifacts().isEmpty()) {
setToscaArtifactsPlaceHolders(newResource, user);
}
- Either<Resource, StorageOperationStatus> overrideResource = resourceOperation.overrideResource(newResource, oldResource, true);
+ Either<Resource, StorageOperationStatus> overrideResource = toscaOperationFacade.overrideComponent(newResource, oldResource);
if (overrideResource.isRight()) {
ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(overrideResource.right().value()), newResource);
@@ -3771,10 +4716,10 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Change LifecycleState - Certify");
BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify");
log.debug("operation failed. do rollback");
- titanGenericDao.rollback();
+ titanDao.rollback();
} else if (inTransaction == false) {
log.debug("operation success. do commit");
- titanGenericDao.commit();
+ titanDao.commit();
}
if (needLock == true) {
log.debug("unlock resource {}", lockedResourceId);
@@ -3829,7 +4774,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
public Either<Resource, ResponseFormat> validateResourceBeforeCreate(Resource resource, User user, AuditingActionEnum actionEnum, boolean inTransaction) {
- Either<Boolean, ResponseFormat> eitherValidation = validateResourceFieldsBeforeCreate(user, getResourceOperation(), resource, actionEnum, inTransaction);
+ Either<Boolean, ResponseFormat> eitherValidation = validateResourceFieldsBeforeCreate(user, resource, actionEnum, inTransaction);
if (eitherValidation.isRight()) {
return Either.right(eitherValidation.right().value());
}
@@ -3908,9 +4853,9 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (resource.getCapabilities() != null && resource.getCapabilities().size() > 0) {
log.debug("validate capability Types Exist - capabilities section");
- for (String type : resource.getCapabilities().keySet()) {
+ for (Entry<String, List<CapabilityDefinition>> typeEntry : resource.getCapabilities().entrySet()) {
- eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, actionEnum, eitherResult, type, inTransaction);
+ eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, actionEnum, eitherResult, typeEntry, inTransaction);
if (eitherResult.isRight()) {
return Either.right(eitherResult.right().value());
}
@@ -3951,11 +4896,54 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return eitherResult;
}
- public Either<Resource, ResponseFormat> createResourceByDao(Resource resource, User user, AuditingActionEnum actionEnum, boolean isNormative) {
- return createResourceByDao(resource, user, actionEnum, isNormative, false);
+ 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().processEcompError(EcompErrorName.BeCapabilityTypeMissingError, "Create Resource - validateCapabilityTypesCreate", typeEntry.getKey());
+ BeEcompErrorManager.getInstance().logBeGraphObjectMissingError("Create Resource - validateCapabilityTypesCreate", "Capability Type", typeEntry.getKey());
+ log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", typeEntry.getKey(), resource.getName());
+ BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateCapabilityTypesCreate");
+ }
+ BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "Create Resource - validateCapabilityTypesCreate");
+ log.debug("Trying to get capability type {} failed with error: {}", typeEntry.getKey(), eitherCapTypeFound.right().value().name());
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, typeEntry.getKey());
+ eitherResult = Either.right(errorResponse);
+ 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) {
+ 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
@@ -3964,37 +4952,50 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource, "Create Resource");
if (lockResult.isRight()) {
ResponseFormat responseFormat = lockResult.right().value();
- componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
+ componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, additionalParams);
return Either.right(responseFormat);
}
- log.debug("name is locked {}. status = {}", resource.getSystemName(), lockResult);
+ log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
}
try {
- Either<Resource, ResponseFormat> respStatus = createResourceTransaction(resource, user, actionEnum, isNormative, inTransaction);
+ if (resource.deriveFromGeneric()) {
+ Either<Resource, ResponseFormat> genericResourceEither = fetchAndSetDerivedFromGenericType(resource);
+ if (genericResourceEither.isRight())
+ return genericResourceEither;
+ if (resource.shouldGenerateInputs())
+ generateInputsFromGenericTypeProperties(resource, genericResourceEither.left().value());
+ }
+
+ Either<Resource, ResponseFormat> respStatus = createResourceTransaction(resource, user, isNormative, inTransaction);
if (respStatus.isLeft()) {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
- componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
+ componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, additionalParams);
ASDCKpiApi.countCreatedResourcesKPI();
} else
- componentsUtils.auditResource(respStatus.right().value(), user, resource, "", "", actionEnum, null);
+ componentsUtils.auditResource(respStatus.right().value(), user, resource, "", "", actionEnum, additionalParams);
return respStatus;
} finally {
if (inTransaction == false) {
- // graphLockOperation.unlockComponent(resource.getSystemName(),
- // NodeTypeEnum.Resource);
graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(), NodeTypeEnum.Resource);
}
}
}
- private Either<Resource, ResponseFormat> createResourceTransaction(Resource resource, User user, AuditingActionEnum actionEnum, boolean isNormative, boolean inTransaction) {
+ private Either<Resource, ResponseFormat> createResourceTransaction(Resource resource, User user, boolean isNormative, boolean inTransaction) {
// validate resource name uniqueness
log.debug("validate resource name");
- Either<Boolean, ResponseFormat> eitherValidation = validateResourceNameExists(user, resource, actionEnum);
+ Either<Boolean, StorageOperationStatus> eitherValidation = toscaOperationFacade.validateComponentNameExists(resource.getName(), resource.getResourceType(), resource.getComponentType());
if (eitherValidation.isRight()) {
- return Either.right(eitherValidation.right().value());
+ 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());
@@ -4002,8 +5003,9 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
createArtifactsPlaceHolderData(resource, user);
//
+
+ // enrich object
if (!isNormative) {
- // enrich object
log.debug("enrich resource with creator, version and state");
resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
resource.setVersion(INITIAL_VERSION);
@@ -4011,16 +5013,12 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
resource.setAbstract(false);
}
- Either<Resource, StorageOperationStatus> dataModelResponse = resourceOperation.createResource(resource, inTransaction);
-
- // Resource created successfully!!!
- if (dataModelResponse.isLeft()) {
- log.debug("Resource created successfully!!!");
-
- return Either.left(dataModelResponse.left().value());
+ Either<Resource, StorageOperationStatus> createToscaElement = toscaOperationFacade.createToscaComponent(resource);
+ if (createToscaElement.isLeft()) {
+ return Either.left(createToscaElement.left().value());
}
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()), resource);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(createToscaElement.right().value()), resource);
return Either.right(responseFormat);
}
@@ -4123,7 +5121,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return eitherCreator.right().value();
}
- Either<Resource, StorageOperationStatus> resourceStatus = resourceOperation.getResource(resourceId);
+ 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()), "");
@@ -4152,10 +5150,10 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
} finally {
if (result == null || !result.equals(StorageOperationStatus.OK)) {
log.warn("operation failed. do rollback");
- titanGenericDao.rollback();
+ titanDao.rollback();
} else {
log.debug("operation success. do commit");
- titanGenericDao.commit();
+ titanDao.commit();
}
graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource);
}
@@ -4170,30 +5168,30 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
// Resource resource = null;
- List<Resource> resourcesList = null;
+ Resource resource = null;
StorageOperationStatus result = StorageOperationStatus.OK;
try {
- Either<List<Resource>, StorageOperationStatus> resourceStatus = resourceOperation.getResourceByNameAndVersion(resourceName, version, true);
+ 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);
}
- resourcesList = resourceStatus.left().value();
+ resource = resourceStatus.left().value();
} finally {
if (result == null || !result.equals(StorageOperationStatus.OK)) {
log.warn("operation failed. do rollback");
- titanGenericDao.rollback();
+ titanDao.rollback();
ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resourceName);
} else {
log.debug("operation success. do commit");
- titanGenericDao.commit();
+ titanDao.commit();
}
}
- for (Resource resource : resourcesList) {
+ if (resource != null) {
Either<Boolean, ResponseFormat> lockResult = lockComponent(resource.getUniqueId(), resource, "Delete Resource");
if (lockResult.isRight()) {
result = StorageOperationStatus.GENERAL_ERROR;
@@ -4210,10 +5208,10 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
} finally {
if (result == null || !result.equals(StorageOperationStatus.OK)) {
log.warn("operation failed. do rollback");
- titanGenericDao.rollback();
+ titanDao.rollback();
} else {
log.debug("operation success. do commit");
- titanGenericDao.commit();
+ titanDao.commit();
}
graphLockOperation.unlockComponent(resource.getUniqueId(), NodeTypeEnum.Resource);
}
@@ -4230,8 +5228,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
}
- IResourceOperation dataModel = getResourceOperation();
- Either<Resource, StorageOperationStatus> storageStatus = dataModel.getResource(resourceId);
+ // IResourceOperation dataModel = getResourceOperation();
+ Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(resourceId);
if (storageStatus.isRight()) {
log.debug("failed to get resource by id {}", resourceId);
@@ -4241,14 +5239,14 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
- public Either<List<Resource>, ResponseFormat> getResourceByNameAndVersion(String resourceName, String resourceVersion, String userId) {
+ 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<List<Resource>, StorageOperationStatus> getResource = resourceOperation.getResourceByNameAndVersion(resourceName, resourceVersion, false);
+ 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));
@@ -4276,7 +5274,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return Either.right(resp.right().value());
}
- IResourceOperation dataModel = getResourceOperation();
+ // IResourceOperation dataModel = getResourceOperation();
log.debug("Get resource with id {}", resourceIdToUpdate);
boolean needToUnlock = false;
boolean rollbackNeeded = true;
@@ -4285,7 +5283,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
// Either<Resource, StorageOperationStatus> storageStatus =
// dataModel.getResource_tx(resourceIdToUpdate, false);
if (currentResource == null) {
- Either<Resource, StorageOperationStatus> storageStatus = dataModel.getResource(resourceIdToUpdate, false);
+ Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(resourceIdToUpdate);
if (storageStatus.isRight()) {
return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right().value()), ""));
}
@@ -4303,7 +5301,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (!lockResult.equals(StorageOperationStatus.OK)) {
BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedLockObjectError, "Upload Artifact - lock " + resourceIdToUpdate + ": " + NodeTypeEnum.Resource);
BeEcompErrorManager.getInstance().logBeFailedLockObjectError("Upload Artifact - lock ", NodeTypeEnum.Resource.getName(), resourceIdToUpdate);
- log.debug("Failed to lock resource {} error - {}", resourceIdToUpdate, lockResult);
+ log.debug("Failed to lock resource: {}, error - {}", resourceIdToUpdate, lockResult);
ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockResult));
return Either.right(responseFormat);
}
@@ -4347,9 +5345,9 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
} finally {
if (!inTransaction) {
if (rollbackNeeded) {
- titanGenericDao.rollback();
+ titanDao.rollback();
} else {
- titanGenericDao.commit();
+ titanDao.commit();
}
}
@@ -4361,7 +5359,6 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
private Either<Resource, ResponseFormat> updateResourceMetadata(String resourceIdToUpdate, Resource newResource, User user, Resource currentResource, boolean shouldLock, boolean inTransaction) {
- IResourceOperation dataModel = getResourceOperation();
Either<Boolean, ResponseFormat> validateResourceFields = validateResourceFieldsBeforeUpdate(currentResource, newResource, inTransaction);
if (validateResourceFields.isRight()) {
return Either.right(validateResourceFields.right().value());
@@ -4371,7 +5368,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
newResource.setLastUpdaterUserId(user.getUserId());
newResource.setUniqueId(resourceIdToUpdate);
// Cannot set highest version through UI
- newResource.setHighestVersion(null);
+ newResource.setHighestVersion(currentResource.isHighestVersion());
newResource.setCreationDate(currentResource.getCreationDate());
Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom = processUpdateOfDerivedFrom(currentResource, newResource, user.getUserId(), shouldLock, inTransaction);
@@ -4382,7 +5379,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
log.debug("send resource {} to dao for update", newResource.getUniqueId());
- Either<Resource, StorageOperationStatus> dataModelResponse = dataModel.updateResource(newResource, inTransaction);
+ Either<Resource, StorageOperationStatus> dataModelResponse = toscaOperationFacade.updateToscaElement(newResource);
if (dataModelResponse.isRight()) {
ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()), newResource);
@@ -4405,7 +5402,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
* - Resource object to validate
* @return Either<Boolean, ErrorResponse>
*/
- private Either<Boolean, ResponseFormat> validateResourceFieldsBeforeCreate(User user, IResourceOperation dataModel, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
+ 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;
@@ -4449,6 +5446,11 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
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);
@@ -4577,7 +5579,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
String updatedCreatorUserId = updateInfoResource.getCreatorUserId();
if ((updatedCreatorUserId != null) && (!updatedCreatorUserId.equals(currentCreatorUserId))) {
- log.warn("Resource Creator User id is automatically set and cannot be updated");
+ log.warn("Resource Creator UserId is automatically set and cannot be updated");
}
String currentCreatorFullName = currentResource.getCreatorFullName();
@@ -4689,7 +5691,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
ResponseFormat errorResponse = validateResourceNameResponse.right().value();
return Either.right(errorResponse);
}
- validateResourceNameResponse = validateResourceNameExists(null, updateInfoResource, null);
+ validateResourceNameResponse = validateResourceNameExists(updateInfoResource);
if (validateResourceNameResponse.isRight()) {
ResponseFormat errorResponse = validateResourceNameResponse.right().value();
return Either.right(errorResponse);
@@ -4699,7 +5701,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
currentResource.setSystemName(ValidationUtils.convertToSystemName(resourceNameUpdated));
} else {
- log.info("Resource name {} cannot be updated once the resource has been certified once.", resourceNameUpdated);
+ 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);
}
@@ -4784,9 +5786,12 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return validateDerivedFromExistsEither;
}
} else {
- log.debug("Derived from cannot be updated once the resource has been certified once.");
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_DERIVED_FROM_CANNOT_BE_CHANGED);
- return Either.right(errorResponse);
+ 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,
@@ -4806,11 +5811,11 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return Either.left(true);
}
- IResourceOperation resourceOperation = getResourceOperation();
+ // IResourceOperation resourceOperation = getResourceOperation();
String templateName = resource.getDerivedFrom().get(0);
- Either<Boolean, StorageOperationStatus> dataModelResponse = resourceOperation.validateToscaResourceNameExists(templateName);
+ Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateToscaResourceNameExists(templateName);
if (dataModelResponse.isRight()) {
StorageOperationStatus storageStatus = dataModelResponse.right().value();
BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "Create Resource - validateDerivedFromExist");
@@ -4822,8 +5827,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return Either.right(responseFormat);
}
- if (dataModelResponse.left().value()) {
- log.info("resource template with name {} does not exists", templateName);
+ 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);
@@ -4833,6 +5838,41 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
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())) {
@@ -4845,23 +5885,20 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return Either.left(true);
}
- private Either<Boolean, ResponseFormat> validateResourceNameExists(User user, Resource resource, AuditingActionEnum actionEnum) {
+ private Either<Boolean, ResponseFormat> validateResourceNameExists(Resource resource) {
- IResourceOperation resourceOperation = getResourceOperation();
- Either<Boolean, StorageOperationStatus> resourceOperationResponse = resourceOperation.validateResourceNameExists(resource.getName(), resource.getResourceType());
+ Either<Boolean, StorageOperationStatus> resourceOperationResponse = toscaOperationFacade.validateComponentNameExists(resource.getName(), resource.getResourceType(), resource.getComponentType());
if (resourceOperationResponse.isLeft()) {
- if (resourceOperationResponse.left().value()) {
- return Either.left(true);
+ if (!resourceOperationResponse.left().value()) {
+ return Either.left(false);
} else {
- log.debug("resource with name {} already exists", resource.getName());
+ log.debug("resource with name: {}, already exists", resource.getName());
ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
- componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null);
return Either.right(errorResponse);
}
}
log.debug("error while validateResourceNameExists for resource: {}", resource.getName());
ResponseFormat errorResponse = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceOperationResponse.right().value()));
- componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null);
return Either.right(errorResponse);
}
@@ -5037,7 +6074,57 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return Either.left(false);
}
-
+
+ /*
+ * 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) {
@@ -5084,11 +6171,11 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
String interfaceType = interfaceTypeOperation.getShortInterfaceName(interfaceDefinition);
log.trace("Starting interface artifacts removal for interface type {}", interfaceType);
- Map<String, Operation> operations = interfaceDefinition.getOperations();
+ Map<String, Operation> operations = interfaceDefinition.getOperationsMap();
if (operations != null) {
for (Entry<String, Operation> operationEntry : operations.entrySet()) {
Operation operation = operationEntry.getValue();
- ArtifactDefinition implementation = operation.getImplementation();
+ ArtifactDefinition implementation = operation.getImplementationArtifact();
if (implementation != null) {
String uniqueId = implementation.getUniqueId();
log.debug("Removing interface artifact definition {}, operation {}, interfaceType {}", uniqueId, operationEntry.getKey(), interfaceType);
@@ -5097,7 +6184,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (deleteArtifactByInterface.isRight()) {
log.debug("Couldn't remove artifact definition with id {}", uniqueId);
if (!inTransaction) {
- titanGenericDao.rollback();
+ titanDao.rollback();
}
return Either.right(deleteArtifactByInterface.right().value());
}
@@ -5116,7 +6203,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (findPropertiesOfNode.isRight() && !findPropertiesOfNode.right().value().equals(StorageOperationStatus.OK)) {
log.debug("Failed to remove all properties of resource");
if (!inTransaction)
- titanGenericDao.rollback();
+ titanDao.rollback();
return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(findPropertiesOfNode.right().value())));
}
@@ -5125,7 +6212,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
if (!inTransaction)
- titanGenericDao.commit();
+ titanDao.commit();
return Either.left(true);
}
@@ -5309,7 +6396,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (regResponse.isRight())
return Either.right(regResponse.right().value());
if (regResponse.left().value().size() > 0) {
- groupInfo.setProperties(regResponse.left().value());
+ groupInfo.convertFromGroupProperties(regResponse.left().value());
}
}
@@ -5378,7 +6465,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
groupProperty.setValue(convertedValue);
groupProperty.setName(propName);
- log.debug("After building group property {}", groupProperty);
+ log.trace("After building group property {}", groupProperty);
result.add(groupProperty);
}
@@ -5401,7 +6488,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
// get resource from csar uuid
- Either<Resource, StorageOperationStatus> either = resourceOperation.getLatestResourceByCsarOrName(csarUuid, "");
+ 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);
@@ -5464,6 +6551,94 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
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 String buildNestedVfcToscaNamespace(String nodeTypeFullName) {
+
+ String actualName = this.getNodeTypeActualName(nodeTypeFullName);
+ return ImportUtils.Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + ResourceTypeEnum.VFC.name().toLowerCase() + actualName;
+
+ }
+
+ private String buildNestedVfcToscaResourceName(String vfResourceName, String nodeTypeFullName) {
+ String toscaResourceName;
+ String nameWithouNamespacePrefix = getNodeTypeActualName(nodeTypeFullName);
+ if (nameWithouNamespacePrefix.startsWith(Constants.ABSTRACT)) {
+ toscaResourceName = Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + ResourceTypeEnum.VFC.name().toLowerCase() + '.' + vfResourceName + '.' + nameWithouNamespacePrefix;
+ } else {
+ toscaResourceName = Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + ResourceTypeEnum.VFC.name().toLowerCase() + '.' + vfResourceName + '.' + Constants.ABSTRACT + nameWithouNamespacePrefix;
+ }
+ return toscaResourceName;
+ }
+
+ private String buildNestedSubstituteYamlName(String nodeTypeFullName) {
+ String[] nodeTypeFullNameParsed = nodeTypeFullName.split("\\.");
+ String nodeTypeActualName = nodeTypeFullNameParsed[nodeTypeFullNameParsed.length - 1];
+ return CsarUtils.DEFINITIONS_PATH + nodeTypeActualName + Constants.SERVICE_TEMPLATE_FILE_POSTFIX;
+ }
+
public ICacheMangerOperation getCacheManagerOperation() {
return cacheManagerOperation;
}
@@ -5472,4 +6647,92 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
this.cacheManagerOperation = cacheManagerOperation;
}
+ ///////////////////////////////////////// DataModel refactoring/////////////////////////////////////////////
+
+ /*
+ * /**
+ *
+ * @deprecated Use {@link #createOrUpdateResourceByImport(Resource,User,boolean, boolean,boolean)} instead
+ */
+ /*
+ * public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createOrUpdateResourceByImport(Resource resource, User user, AuditingActionEnum auditingEnum, boolean isNormative, boolean needLock) { return
+ * createOrUpdateResourceByImport(resource, user, isNormative, false, needLock); }
+ */
+
+ public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createOrUpdateNodeTypeByImport(Resource resource, User user, boolean isNormative, boolean isInTransaction, boolean needLock) {
+
+ // check if resource already exist
+ Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade.getLatestByName(resource.getName());
+ Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> result = null;
+
+ // create
+ if (latestByName.isRight() && latestByName.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
+
+ Either<Resource, StorageOperationStatus> latestByToscaName = toscaOperationFacade.getLatestByToscaResourceName(resource.getToscaResourceName());
+ if (latestByToscaName.isRight() && latestByToscaName.right().value().equals(StorageOperationStatus.NOT_FOUND))
+ result = createNodeTypeByImport(resource, user, isNormative, isInTransaction);
+
+ else {
+ StorageOperationStatus status = latestByName.right().value();
+ BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeResourceMissingError, "Create / Update resource by import", resource.getName());
+ BeEcompErrorManager.getInstance().logBeComponentMissingError("Create / Update resource by import", ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
+ log.debug("resource already exist {}. status={}", resource.getName(), status);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_ALREADY_EXISTS);
+ componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
+ result = Either.right(responseFormat);
+ }
+
+ }
+
+ // update
+ else if (latestByName.isLeft()) {
+ // result = updateExistingNodeTypeByImport(resource, latestByName.left().value(), user, isNormative, needLock);
+ }
+
+ // error
+ else {
+ StorageOperationStatus status = latestByName.right().value();
+ BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeResourceMissingError, "Create / Update resource by import", resource.getName());
+ log.debug("failed to get latest version of resource {}. status={}", resource.getName(), status);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(latestByName.right().value()), resource);
+ componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
+ result = Either.right(responseFormat);
+ }
+ return result;
+
+ }
+
+ private Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createNodeTypeByImport(Resource resource, User user, boolean isNormative, boolean isInTransaction) {
+ log.debug("resource with name {} does not exist. create new resource", resource.getName());
+ Either<Resource, ResponseFormat> response = validateResourceBeforeCreate(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isInTransaction);
+ if (response.isRight()) {
+ return Either.right(response.right().value());
+ }
+
+ Either<Resource, ResponseFormat> createResponse = createResourceByDao(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isNormative, isInTransaction, null);
+ if (createResponse.isRight()) {
+ return Either.right(createResponse.right().value());
+ } else {
+ ImmutablePair<Resource, ActionStatus> resourcePair = new ImmutablePair<>(createResponse.left().value(), ActionStatus.CREATED);
+ ASDCKpiApi.countImportResourcesKPI();
+ return Either.left(resourcePair);
+
+ }
+ }
+
+ public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String resourceId, List<String> dataParamsToReturn) {
+
+ ComponentParametersView paramsToRetuen = new ComponentParametersView(dataParamsToReturn);
+ Either<Resource, StorageOperationStatus> resourceResultEither = toscaOperationFacade.getToscaElement(resourceId, paramsToRetuen);
+
+ if (resourceResultEither.isRight()) {
+ 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);
+ }
+
}
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 329481a546..f35515f8fe 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
@@ -37,6 +37,7 @@ import javax.servlet.ServletContext;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.auditing.api.IAuditingManager;
+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;
import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum;
@@ -49,6 +50,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.model.ArtifactDefinition;
import org.openecomp.sdc.be.model.AttributeDefinition;
import org.openecomp.sdc.be.model.CapabilityDefinition;
import org.openecomp.sdc.be.model.ComponentInstanceProperty;
@@ -61,6 +63,7 @@ import org.openecomp.sdc.be.model.UploadResourceInfo;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.model.category.CategoryDefinition;
import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.CapabilityTypeOperation;
@@ -101,29 +104,45 @@ public class ResourceImportManager {
@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);
+ return importCertifiedResource(resourceYml, resourceMetaData, creator, validator, lifecycleChangeInfo, false, createNewVersion, needLock, null, null);
+ }
+
+ 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);
}
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) {
+ LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean isInTransaction, boolean createNewVersion, boolean needLock, Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts) {
Resource resource = new Resource();
- ImmutablePair<Resource, ActionStatus> responsePair = new ImmutablePair<Resource, ActionStatus>(resource, ActionStatus.CREATED);
+ ImmutablePair<Resource, ActionStatus> responsePair = new ImmutablePair<>(resource, ActionStatus.CREATED);
Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> response = Either.left(responsePair);
String latestCertifiedResourceId = null;
try {
- setConstantMetaData(resource);
+ boolean shouldBeCertified = nodeTypeArtifactsToHandle == null || nodeTypeArtifactsToHandle.isEmpty() ? true : false;
+ setConstantMetaData(resource, shouldBeCertified);
setMetaDataFromJson(resourceMetaData, resource);
Either<Boolean, ResponseFormat> validateResourceFromYaml = populateResourceFromYaml(resourceYml, resource, isInTransaction);
@@ -138,21 +157,30 @@ public class ResourceImportManager {
if (isValidResource.isLeft()) {
// The flag createNewVersion if false doesn't create new version
if (!createNewVersion) {
- Either<Resource, StorageOperationStatus> latestByName = resourceOperation.getLatestByName(resource.getName(), isInTransaction);
+ 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);
+ 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);
+ if(handleNodeTypeArtifactsRes.isRight()){
+ return Either.right(handleNodeTypeArtifactsRes.right().value());
+ }
+ }
latestCertifiedResourceId = getLatestCertifiedResourceId(resource);
- Either<Resource, ResponseFormat> certificationResponse = resourceBusinessLogic.propagateStateToCertified(creator, resource, lifecycleChangeInfo, isInTransaction, needLock);
- if (certificationResponse.isRight()) {
- response = Either.right(certificationResponse.right().value());
+ changeStateResponse = resourceBusinessLogic.propagateStateToCertified(creator, resource, lifecycleChangeInfo, isInTransaction, needLock);
+ if (changeStateResponse.isRight()) {
+ response = Either.right(changeStateResponse.right().value());
} else {
- responsePair = new ImmutablePair<Resource, ActionStatus>(certificationResponse.left().value(), response.left().value().right);
+ responsePair = new ImmutablePair<>(changeStateResponse.left().value(), response.left().value().right);
response = Either.left(responsePair);
}
}
@@ -490,7 +518,8 @@ public class ResourceImportManager {
String derivedFrom = toscaDerivedFromElement.left().value();
log.debug("Derived from TOSCA name is {}", derivedFrom);
resource.setDerivedFrom(Arrays.asList(new String[] { derivedFrom }));
- Either<Resource, StorageOperationStatus> latestByToscaResourceName = resourceOperation.getLatestByToscaResourceName(derivedFrom, inTransaction);
+ Either<Resource, StorageOperationStatus> latestByToscaResourceName = toscaOperationFacade.getLatestByToscaResourceName(derivedFrom);
+
if (latestByToscaResourceName.isRight()) {
StorageOperationStatus operationStatus = latestByToscaResourceName.right().value();
if (operationStatus.equals(StorageOperationStatus.NOT_FOUND)) {
@@ -775,10 +804,18 @@ public class ResourceImportManager {
}
- private void setConstantMetaData(Resource resource) {
- resource.setVersion(ImportUtils.Constants.FIRST_CERTIFIED_VERSION_VERSION);
- ;
- resource.setLifecycleState(ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE);
+ 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);
@@ -833,7 +870,7 @@ public class ResourceImportManager {
}
if (maxOccurrences <= 0 || maxOccurrences < minOccurrences) {
- log.debug("Invalid occurrenses format. min occurrence is {}. Max occurrence is {}", minOccurrences, maxOccurrences);
+ log.debug("Invalid occurrenses format. min occurrence is {}, Max occurrence is {}", minOccurrences, maxOccurrences);
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_OCCURRENCES);
return Either.right(responseFormat);
}
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 6bbe88f30c..1f481a7b5a 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
@@ -32,10 +32,6 @@ import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.Callable;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.Future;
-import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;
@@ -44,6 +40,7 @@ import javax.servlet.http.HttpServletRequest;
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;
@@ -52,17 +49,20 @@ 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.utils.UiComponentDataConverter;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.GroupTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
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.ComponentParametersView;
import org.openecomp.sdc.be.model.DistributionStatusEnum;
import org.openecomp.sdc.be.model.DistributionTransitionEnum;
-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.LifecycleStateEnum;
import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.Service;
@@ -70,25 +70,25 @@ import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.model.category.CategoryDefinition;
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.IServiceOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.model.operations.impl.ComponentOperation;
-import org.openecomp.sdc.be.model.operations.impl.ServiceOperation;
import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
+import org.openecomp.sdc.be.resources.data.ComponentInstanceData;
+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.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.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.config.EcompErrorName;
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;
import org.openecomp.sdc.common.util.ThreadLocalsHolder;
import org.openecomp.sdc.common.util.ValidationUtils;
import org.openecomp.sdc.exception.ResponseFormat;
@@ -125,6 +125,9 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
private ServiceComponentInstanceBusinessLogic serviceComponentInstanceBusinessLogic;
@Autowired
+ private GroupBusinessLogic groupBusinessLogic;
+
+ @Autowired
private ICacheMangerOperation cacheManagerOperation;
private static Logger log = LoggerFactory.getLogger(ServiceBusinessLogic.class.getName());
@@ -190,17 +193,16 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
} else {
newState = DistributionStatusEnum.DISTRIBUTION_REJECTED;
}
- Either<Service, StorageOperationStatus> result = serviceOperation.updateDestributionStatus(service, user, newState);
+ Either<Service, StorageOperationStatus> result = toscaOperationFacade.updateDistributionStatus(service, user, newState);
if (result.isRight()) {
- titanGenericDao.rollback();
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "ChangeServiceDistributionState");
+ 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));
}
- titanGenericDao.commit();
+ titanDao.commit();
Service updatedService = result.left().value();
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
@@ -319,13 +321,14 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
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, serviceOperation, user);
+ return createServiceByDao(service, AuditingActionEnum.CREATE_RESOURCE, user);
}
private void checkFieldsForOverideAttampt(Service service) {
@@ -335,7 +338,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
}
}
- private Either<Service, ResponseFormat> createServiceByDao(Service service, AuditingActionEnum actionEnum, IServiceOperation dataModel, User user) {
+ 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");
@@ -352,8 +355,13 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
createMandatoryArtifactsData(service, user);
createServiceApiArtifactsData(service, user);
setToscaArtifactsPlaceHolders(service, user);
+ Either<Resource, ResponseFormat> genericServiceEither = fetchAndSetDerivedFromGenericType(service);
+ if (genericServiceEither.isRight())
+ return Either.right(genericServiceEither.right().value());
- Either<Service, StorageOperationStatus> dataModelResponse = dataModel.createService(service);
+ generateInputsFromGenericTypeProperties(service, genericServiceEither.left().value());
+
+ Either<Service, StorageOperationStatus> dataModelResponse = toscaOperationFacade.createToscaComponent(service);
// service created successfully!!!
if (dataModelResponse.isLeft()) {
@@ -361,12 +369,6 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
componentsUtils.auditComponentAdmin(responseFormat, user, service, "", "", actionEnum, ComponentTypeEnum.SERVICE);
ASDCKpiApi.countCreatedServicesKPI();
-
- Service createdService = dataModelResponse.left().value();
- // //add service to cache
- // cacheManagerOperation.updateComponentInCache(createdService.getUniqueId(),
- // createdService.getLastUpdateDate(), NodeTypeEnum.Service);
-
return Either.left(dataModelResponse.left().value());
}
@@ -380,6 +382,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
}
}
+ @SuppressWarnings("unchecked")
private void createServiceApiArtifactsData(Service service, User user) {
// create mandatory artifacts
@@ -389,7 +392,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
// UniqueIdBuilder.buildServiceUniqueId(service.getComponentMetadataDefinition().getMetadataDataDefinition().getName(),
// service.getComponentMetadataDefinition().getMetadataDataDefinition().getVersion());
String serviceUniqueId = service.getUniqueId();
- Map<String, ArtifactDefinition> artifactMap = service.getArtifacts();
+ Map<String, ArtifactDefinition> artifactMap = service.getServiceApiArtifacts();
if (artifactMap == null)
artifactMap = new HashMap<String, ArtifactDefinition>();
@@ -417,7 +420,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
}
- service.setArtifacts(artifactMap);
+ service.setServiceApiArtifacts(artifactMap);
}
}
@@ -458,6 +461,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
return categoryValidation;
}
+ // validate project name (ProjectCode) - mandatory in service
+
log.debug("validate projectName");
Either<Boolean, ResponseFormat> projectCodeValidation = validateProjectCode(user, service, actionEnum);
if (projectCodeValidation.isRight()) {
@@ -494,7 +499,10 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
return Either.right(resp.right().value());
}
- Either<Boolean, StorageOperationStatus> dataModelResponse = serviceOperation.validateServiceNameExists(serviceName);
+ Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateComponentNameUniqueness(serviceName, null, ComponentTypeEnum.SERVICE);
+
+ // DE242223
+ titanDao.commit();
if (dataModelResponse.isLeft()) {
Map<String, Boolean> result = new HashMap<>();
@@ -512,10 +520,6 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
this.elementDao = elementDao;
}
- public void setServiceOperation(ServiceOperation serviceOperation) {
- this.serviceOperation = serviceOperation;
- }
-
public void setCassandraAuditingDao(AuditCassandraDao auditingDao) {
this.auditCassandraDao = auditingDao;
}
@@ -549,15 +553,15 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
return Either.right(validateRes.right().value());
}
- Either<Service, StorageOperationStatus> storageStatus = serviceOperation.getService(serviceId);
+ 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.canWorkOnService(currentService.getUniqueId(), serviceOperation, user.getUserId())) {
- log.info("Restricted operation for user {} on service {}", user.getUserId(), currentService.getCreatorUserId());
+ 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));
}
@@ -574,15 +578,14 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
return Either.right(lockResult.right().value());
}
try {
- Either<Service, StorageOperationStatus> updateResponse = serviceOperation.updateService(serviceToUpdate, true);
+ Either<Service, StorageOperationStatus> updateResponse = toscaOperationFacade.updateToscaElement(serviceToUpdate);
if (updateResponse.isRight()) {
- titanGenericDao.rollback();
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Update Service Metadata");
+ titanDao.rollback();
BeEcompErrorManager.getInstance().logBeSystemError("Update Service Metadata");
log.debug("failed to update sevice {}", serviceToUpdate.getUniqueId());
return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
}
- titanGenericDao.commit();
+ titanDao.commit();
return Either.left(updateResponse.left().value());
} finally {
graphLockOperation.unlockComponent(serviceId, NodeTypeEnum.Service);
@@ -619,7 +622,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
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 );
+ log.info("update srvice: recived request to update lastUpdaterFullName to {} the field is not updatable ignoring.", lastUpdaterFullNameUpdated);
}
response = validateAndUpdateServiceName(user, currentService, serviceUpdate, hasBeenCertified, null);
@@ -709,10 +712,31 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
log.warn("Product invariant UUID is automatically set and cannot be updated");
serviceUpdate.setInvariantUUID(currentInvariantUuid);
}
+ validateAndUpdateEcompNaming(currentService, serviceUpdate);
+
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();
@@ -765,12 +789,14 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
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);
}
@@ -892,7 +918,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
}
user = eitherCreator.left().value();
- Either<Service, StorageOperationStatus> serviceStatus = serviceOperation.getService(serviceId);
+ 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()), "");
@@ -922,10 +948,10 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
if (result == null || !result.equals(StorageOperationStatus.OK)) {
log.warn("operation failed. do rollback");
BeEcompErrorManager.getInstance().logBeSystemError("Delete Service");
- titanGenericDao.rollback();
+ titanDao.rollback();
} else {
log.debug("operation success. do commit");
- titanGenericDao.commit();
+ titanDao.commit();
}
graphLockOperation.unlockComponent(serviceId, NodeTypeEnum.Service);
}
@@ -972,10 +998,10 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
if (result == null || !result.equals(StorageOperationStatus.OK)) {
log.warn("operation failed. do rollback");
BeEcompErrorManager.getInstance().logBeSystemError("Delete Service");
- titanGenericDao.rollback();
+ titanDao.rollback();
} else {
log.debug("operation success. do commit");
- titanGenericDao.commit();
+ titanDao.commit();
}
graphLockOperation.unlockComponent(service.getUniqueId(), NodeTypeEnum.Service);
}
@@ -994,7 +1020,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
}
user = eitherCreator.left().value();
- Either<Service, StorageOperationStatus> storageStatus = serviceOperation.getService(serviceId);
+ 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));
@@ -1010,7 +1036,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
if (resp.isRight()) {
return Either.right(resp.right().value());
}
- Either<Service, StorageOperationStatus> storageStatus = serviceOperation.getServiceByNameAndVersion(serviceName, serviceVersion, null, false);
+ 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));
@@ -1019,6 +1045,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
return Either.left(service);
}
+ @SuppressWarnings("unchecked")
private void createMandatoryArtifactsData(Service service, User user) {
// create mandatory artifacts
@@ -1076,7 +1103,6 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
transitionEnum = DistributionTransitionEnum.getFromDisplayName(distributionTransition);
if (transitionEnum == null) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Change Service Distribution");
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);
@@ -1090,7 +1116,6 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
String data = comment.getUserRemarks();
if (data == null || data.trim().isEmpty()) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInvalidJsonInput, "Change Service Distribution");
BeEcompErrorManager.getInstance().logBeInvalidJsonInput("Change Service Distribution");
log.debug("user comment cannot be empty or null.");
return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
@@ -1101,7 +1126,6 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
data = ValidationUtils.stripOctets(data);
if (!ValidationUtils.validateLength(data, ValidationUtils.COMMENT_MAX_LENGTH)) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInvalidJsonInput, "Change Service Distribution");
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)));
@@ -1113,7 +1137,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
}
private Either<Service, ResponseFormat> validateServiceDistributionChange(User user, String serviceId, AuditingActionEnum auditAction, String comment) {
- Either<Service, StorageOperationStatus> storageStatus = serviceOperation.getService(serviceId);
+ Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(serviceId);
if (storageStatus.isRight()) {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_FOUND, serviceId);
createAudit(user, auditAction, comment, responseFormat);
@@ -1132,13 +1156,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
private Either<User, ResponseFormat> validateUserDistributionChange(User user, Service service, AuditingActionEnum auditAction, String comment) {
log.debug("get user from DB");
- /*
- * Either<User, ActionStatus> eitherCreator = userAdmin.getUser(user.getUserId());s if (eitherCreator.isRight() || eitherCreator.left().value() == null) { BeEcompErrorManager.getInstance().processEcompError(EcompErrorName. BeUserMissingError,
- * "Activate Distribution", user.getUserId()); log. debug("changeServiceDistributionState method - user is not listed. userId=" + user.getUserId()); ResponseFormat responseFormat =
- * componentsUtils.getResponseFormat(ActionStatus.USER_NOT_FOUND); createAudit(user, auditAction, comment, responseFormat); return Either.right(responseFormat); } user = eitherCreator.left().value(); log.debug("validate user role"); if
- * (!validateUserTemp(user, Role.ADMIN, Role.GOVERNOR)) { log.info("role {} is not allowed to perform this action", user.getRole()); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
- * createAudit(user, auditAction, comment, service, responseFormat); return Either.right(responseFormat); }
- */
+
// get user details
Either<User, ResponseFormat> eitherCreator = validateUser(user, "Activate Distribution", service, auditAction, false);
if (eitherCreator.isRight()) {
@@ -1150,6 +1168,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
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());
@@ -1208,14 +1227,13 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
ServletContext servletContext = request.getSession().getServletContext();
boolean isDistributionEngineUp = getHealthCheckBL(servletContext).isDistributionEngineUp(request.getSession().getServletContext()); // DE
if (!isDistributionEngineUp) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Distribution Engine is DOWN");
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 = serviceOperation.getService(serviceId);
+ 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);
@@ -1243,7 +1261,6 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
response = componentsUtils.getResponseFormat(ActionStatus.OK);
result = Either.left(updatedService);
} else {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Activate Distribution - send notification");
BeEcompErrorManager.getInstance().logBeSystemError("Activate Distribution - send notification");
log.debug("distributionEngine.notifyService response is: {}", notifyServiceResponse);
response = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
@@ -1273,15 +1290,14 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
return Either.right(lockResult.right().value());
}
try {
- Either<Service, StorageOperationStatus> result = serviceOperation.updateDestributionStatus(service, user, state);
+ Either<Service, StorageOperationStatus> result = toscaOperationFacade.updateDistributionStatus(service, user, state);
if (result.isRight()) {
- titanGenericDao.rollback();
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "updateDistributionStatusForActivation");
+ titanDao.rollback();
BeEcompErrorManager.getInstance().logBeSystemError("updateDistributionStatusForActivation");
log.debug("service {} change distribution status failed", serviceId);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
}
- titanGenericDao.commit();
+ titanDao.commit();
return Either.left(result.left().value());
} finally {
graphLockOperation.unlockComponent(serviceId, NodeTypeEnum.Service);
@@ -1298,9 +1314,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
log.debug("mark distribution deployed");
AuditingActionEnum auditAction = AuditingActionEnum.DISTRIBUTION_DEPLOY;
- Either<Service, StorageOperationStatus> getServiceResponse = serviceOperation.getService(serviceId);
+ Either<Service, StorageOperationStatus> getServiceResponse = toscaOperationFacade.getToscaElement(serviceId);
if (getServiceResponse.isRight()) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeServiceMissingError, "markDistributionAsDeployed", serviceId);
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), "");
@@ -1323,36 +1338,35 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
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
- Arrays.asList(new VfModuleArtifacGenerator(modifier, ri, service, shouldLock));
+ buildArtifactGenList(service, modifier, shouldLock, ri);
return generateDeploymentArtifacts(service, modifier, artifactTaskGeneratorCreator);
}
- private List<GroupDefinition> collectGroupsForCompInstance(ComponentInstance currVF, Wrapper<ResponseFormat> responseWrapper) {
- List<GroupDefinition> relevantGroups = new ArrayList<>();
- Either<List<GroupDefinition>, StorageOperationStatus> eitherGroups = groupOperation.getAllGroups(currVF.getComponentUid(), NodeTypeEnum.Resource);
-
- if (eitherGroups.isRight()) {
- final StorageOperationStatus storageStatus = eitherGroups.right().value();
- if (storageStatus != StorageOperationStatus.NOT_FOUND && storageStatus != StorageOperationStatus.OK) {
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageStatus);
- responseWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus));
- }
+ private List<ArtifactGenerator<ArtifactDefinition>> buildArtifactGenList(Service service, User modifier, boolean shouldLock, ComponentInstance ri) {
+ List<ArtifactGenerator<ArtifactDefinition>> asList = new ArrayList<ArtifactGenerator<ArtifactDefinition>>();
- } else {
- relevantGroups = eitherGroups.left().value().stream().filter(p -> GroupTypeEnum.VF_MODULE.getGroupTypeName().equals(p.getType())).collect(Collectors.toList());
+ if (ri.getOriginType() == OriginTypeEnum.VF) {
+ asList = Arrays.asList(new VfModuleArtifacGenerator(modifier, ri, service, shouldLock));
}
- return relevantGroups;
+ return asList;
}
- private ArtifactDefinition getVfModuleArtifactForCompInstance(ComponentInstance currVF, Service service, User modifier, List<GroupDefinition> groupsForCurrVF, Wrapper<String> payloadWrapper, Wrapper<ResponseFormat> responseWrapper) {
- ArtifactDefinition vfModuleAertifact = null;
+ private List<GroupInstance> collectGroupsInstanceForCompInstance(ComponentInstance currVF, Wrapper<ResponseFormat> responseWrapper) {
- Optional<ArtifactDefinition> optionalVfModuleArtifact = currVF.getDeploymentArtifacts().values().stream().filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.VF_MODULES_METADATA.name())).findAny();
- if (optionalVfModuleArtifact.isPresent()) {
- vfModuleAertifact = optionalVfModuleArtifact.get();
- } else {
+ 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();
@@ -1363,19 +1377,26 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
return vfModuleAertifact;
}
- private void fillVfModuleHeatEnvPayload(List<GroupDefinition> groupsForCurrVF, ComponentInstance currVFInstance, Wrapper<String> payloadWrapper) {
+ private void fillVfModuleInstHeatEnvPayload(List<GroupInstance> groupsForCurrVF, ComponentInstance currVFInstance, 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());
- Collections.sort(vfModulePayloadForCurrVF, (art1, art2) -> VfModuleArtifactPayload.compareByGroupName(art1, art2));
- // Update Payload With Heat Env
- vfModulePayloadForCurrVF.stream().forEach(e -> addHeatEnvArtifactsToVFModulePayload(e, currVFInstance));
+ // 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();
+ final Gson gson = new GsonBuilder().setPrettyPrinting().create();
- String vfModulePayloadString = gson.toJson(vfModulePayloadForCurrVF);
- payloadWrapper.setInnerElement(vfModulePayloadString);
+ String vfModulePayloadString = gson.toJson(vfModulePayloadForCurrVF);
+ payloadWrapper.setInnerElement(vfModulePayloadString);
+ }
}
@@ -1383,6 +1404,9 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
List<String> originalModuleArtifacts = vfModulePayload.getArtifacts();
if (!MapUtils.isEmpty(currVFInstance.getDeploymentArtifacts()) && !CollectionUtils.isEmpty(originalModuleArtifacts)) {
+ // EVG : fix now for patch. remove null from list. Need to be fixed later : remove VF HEAT ENV uuid from the list??
+ List<String> filteredUUIDFromModule = originalModuleArtifacts.stream().filter(uuid -> uuid != null).collect(Collectors.toList());
+
final Collection<ArtifactDefinition> depInsArtifacts = currVFInstance.getDeploymentArtifacts().values();
// All Heat_ENV
List<ArtifactDefinition> heatEnvArtifacts = depInsArtifacts.stream().filter(art -> art.getArtifactType().equals(ArtifactTypeEnum.HEAT_ENV.getType())).collect(Collectors.toList());
@@ -1393,23 +1417,23 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
List<String> relevantHeatEnvUUID = heatEnvArtifacts.stream().filter(heatEnv -> moduleArtUniqueId.contains(heatEnv.getGeneratedFromId())).map(heatEnv -> heatEnv.getArtifactUUID()).collect(Collectors.toList());
List<String> fullArtifactList = new ArrayList<>();
- fullArtifactList.addAll(originalModuleArtifacts);
+ fullArtifactList.addAll(filteredUUIDFromModule);
fullArtifactList.addAll(relevantHeatEnvUUID);
vfModulePayload.setArtifacts(fullArtifactList);
}
}
- private Either<ArtifactDefinition, ResponseFormat> generateVfModuleArtifact(User modifier, ComponentInstance currVFInstance, Service service, boolean shouldLock) {
+ 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<GroupDefinition> groupsForCurrVF = collectGroupsForCompInstance(currVFInstance, responseWrapper);
+ List<GroupInstance> groupsForCurrVF = collectGroupsInstanceForCompInstance(currVFInstance, responseWrapper);
if (responseWrapper.isEmpty()) {
- fillVfModuleHeatEnvPayload(groupsForCurrVF, currVFInstance, payloadWrapper);
+ fillVfModuleInstHeatEnvPayload(groupsForCurrVF, currVFInstance, payloadWrapper);
}
- if (responseWrapper.isEmpty()) {
- vfModuleAertifact = getVfModuleArtifactForCompInstance(currVFInstance, service, modifier, groupsForCurrVF, payloadWrapper, responseWrapper);
+ 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);
@@ -1425,21 +1449,24 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
return result;
}
- private ArtifactDefinition fillVfModulePayload(User modifier, ComponentInstance currVF, ArtifactDefinition vfModuleAertifact, boolean shouldLock, Wrapper<String> payloadWrapper, Wrapper<ResponseFormat> responseWrapper) {
+ private ArtifactDefinition fillVfModulePayload(User modifier, ComponentInstance currVF, ArtifactDefinition vfModuleArtifact, boolean shouldLock, Wrapper<String> payloadWrapper, Wrapper<ResponseFormat> responseWrapper) {
ArtifactDefinition result = null;
- final Either<Resource, StorageOperationStatus> eitherResource = resourceOperation.getResource(currVF.getComponentUid());
+ final Either<Resource, StorageOperationStatus> eitherResource = toscaOperationFacade.getToscaElement(currVF.getComponentUid());
if (eitherResource.isRight()) {
responseWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(eitherResource.right().value())));
- } else {
+ } else if (!payloadWrapper.isEmpty()) {
Resource resource = eitherResource.left().value();
- Either<ArtifactDefinition, ResponseFormat> eitherPayload = artifactsBusinessLogic.generateArtifactPayload(vfModuleAertifact, resource, currVF.getName(), modifier, shouldLock, () -> System.currentTimeMillis(),
- () -> Either.left(artifactsBusinessLogic.createEsArtifactData(vfModuleAertifact, payloadWrapper.getInnerElement().getBytes(StandardCharsets.UTF_8))));
+ Either<ArtifactDefinition, ResponseFormat> eitherPayload = artifactsBusinessLogic.generateArtifactPayload(vfModuleArtifact, resource.getComponentType(), resource, 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;
}
@@ -1447,6 +1474,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
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");
@@ -1456,8 +1484,12 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
vfModuleArtifactDefinition.setTimeout(0);
vfModuleArtifactDefinition.setArtifactName(currVF.getNormalizedName() + "_modules.json");
vfModuleArtifactDefinition.setPayloadData(vfModulePayloadString);
+ if (vfModulePayloadString != null) {
+ newCheckSum = GeneralUtility.calculateMD5ByByteArray(vfModulePayloadString.getBytes());
+ }
+ vfModuleArtifactDefinition.setArtifactChecksum(newCheckSum);
- Either<ArtifactDefinition, StorageOperationStatus> addArifactToComponent = artifactOperation.addArifactToComponent(vfModuleArtifactDefinition, currVF.getUniqueId(), NodeTypeEnum.ResourceInstance, true, true);
+ Either<ArtifactDefinition, StorageOperationStatus> addArifactToComponent = artifactToscaOperation.addArifactToComponent(vfModuleArtifactDefinition, service.getUniqueId(), NodeTypeEnum.ResourceInstance, true, currVF.getUniqueId());
Either<ArtifactDefinition, ResponseFormat> result;
if (addArifactToComponent.isLeft()) {
@@ -1477,7 +1509,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
// 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)).collect(Collectors.toList());
+ map(depArtifact -> new HeatEnvArtifactGenerator(depArtifact, service, resourceInstance.getName(), modifier, shouldLock, resourceInstance.getUniqueId())).collect(Collectors.toList());
return generateDeploymentArtifacts(service, modifier, artifactTaskGeneratorCreator);
@@ -1485,41 +1517,25 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
private <CallVal> Either<Service, ResponseFormat> generateDeploymentArtifacts(Service service, User modifier, Function<ComponentInstance, List<ArtifactGenerator<CallVal>>> artifactTaskGeneratorCreator) {
- List<Future<Either<CallVal, ResponseFormat>>> allFutures = new ArrayList<>();
-
// 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()) {
- ExecutorService executor = Executors.newFixedThreadPool(artifactGenList.size());
-
- artifactGenList.stream().forEach(e -> allFutures.add(executor.submit(e)));
-
- boolean isSuccess = true;
- ResponseFormat firstError = null;
- for (Future<Either<CallVal, ResponseFormat>> entry : allFutures) {
+ for (ArtifactGenerator<CallVal> entry : artifactGenList) {
+ Either<CallVal, ResponseFormat> callRes;
try {
- Either<CallVal, ResponseFormat> actionStatus = entry.get(20, TimeUnit.SECONDS);
- if (actionStatus.isRight()) {
- isSuccess = false;
- if (firstError == null) {
- firstError = actionStatus.right().value();
- }
- log.debug("Failed to generate artifact error : {}", actionStatus.right().value());
+ 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 collect result from artifact generator ", e);
- isSuccess = false;
- firstError = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
+ log.debug("Failed to generate artifact exception : {}", e);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
}
}
- executor.shutdown();
- if (!isSuccess) {
- return Either.right(firstError);
- }
}
-
}
return Either.left(service);
}
@@ -1533,19 +1549,21 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
Service service;
String resourceInstanceName;
User modifier;
+ String instanceId;
boolean shouldLock;
- HeatEnvArtifactGenerator(ArtifactDefinition artifactDefinition, Service service, String resourceInstanceName, User modifier, 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.generateHeatEnvArtifact(artifactDefinition, service, resourceInstanceName, modifier, shouldLock);
+ return artifactsBusinessLogic.generateHeatEnvArtifact(artifactDefinition, ComponentTypeEnum.RESOURCE_INSTANCE, service, resourceInstanceName, modifier, shouldLock, instanceId);
}
public ArtifactDefinition getArtifactDefinition() {
@@ -1562,7 +1580,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
@Override
public Either<ArtifactDefinition, ResponseFormat> call() throws Exception {
- return generateVfModuleArtifact(user, componentInstance, service, shouldLock);
+ return generateVfModuleInstanceArtifact(user, componentInstance, service, shouldLock);// generateVfModuleArtifact(user, componentInstance, service, shouldLock);
}
private VfModuleArtifacGenerator(User user, ComponentInstance componentInstance, Service service, boolean shouldLock) {
@@ -1618,7 +1636,6 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
List<ResourceAdminEvent> distributionRequests = distRequestsResponse.left().value();
if (distributionRequests.isEmpty()) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDistributionMissingError, "markDistributionAsDeployed", did);
BeEcompErrorManager.getInstance().logBeDistributionMissingError("markDistributionAsDeployed", did);
log.info("distribution {} is not found", did);
ResponseFormat error = auditDeployError(did, user, auditAction, service, ActionStatus.DISTRIBUTION_REQUESTED_NOT_FOUND);
@@ -1686,9 +1703,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
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().processEcompError(EcompErrorName.BeUserMissingError, "Deploy Service", user.getUserId());
BeEcompErrorManager.getInstance().logBeUserMissingError("Deploy Service", user.getUserId());
- log.debug("validateRoleForDeploy method - user is not listed. userId={}", 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);
@@ -1711,7 +1727,6 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
@Override
public void setDeploymentArtifactsPlaceHolder(Component component, User user) {
- // TODO Auto-generated method stub
}
@@ -1739,21 +1754,14 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
if (resp.isRight()) {
return Either.right(resp.right().value());
}
-
- ComponentOperation componentOperation = getComponentOperation(componentTypeEnum);
-
- Either<List<ComponentInstance>, StorageOperationStatus> componentInstancesResponse = componentOperation.getAllComponentInstncesMetadata(componentId, componentTypeEnum.getNodeType());
- if (componentInstancesResponse.isRight()) {
-
- if (componentInstancesResponse.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
- return Either.left(new ArrayList<ComponentInstance>());
- }
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(componentInstancesResponse.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 = componentInstancesResponse.left().value();
- componentInstances = componentInstances.stream().filter(instance -> instance.getOriginType().equals(OriginTypeEnum.VF)).collect(Collectors.toList());
+ List<ComponentInstance> componentInstances = getComponentRes.left().value().getComponentInstances();
+ // componentInstances = componentInstances.stream().filter(instance -> instance.getOriginType().equals(OriginTypeEnum.VF)).collect(Collectors.toList());
return Either.left(componentInstances);
}
@@ -1765,4 +1773,207 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
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 resourceId, List<String> dataParamsToReturn) {
+
+ ComponentParametersView paramsToRetuen = new ComponentParametersView(dataParamsToReturn);
+ Either<Service, StorageOperationStatus> serviceResultEither = toscaOperationFacade.getToscaElement(resourceId, paramsToRetuen);
+
+ if (serviceResultEither.isRight()) {
+ log.debug("failed to get resource by id {} with filters {}", resourceId, 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
index c42cf004ff..9586be81ea 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceComponentInstanceBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceComponentInstanceBusinessLogic.java
@@ -42,16 +42,6 @@ public class ServiceComponentInstanceBusinessLogic extends ComponentInstanceBusi
}
@Override
- protected ComponentOperation getContainerComponentOperation() {
- return serviceOperation;
- }
-
- @Override
- protected ComponentOperation getCompInstOriginComponentOperation() {
- return resourceOperation;
- }
-
- @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
index 3e42897c79..61a5af5b74 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/VFComponentInstanceBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/VFComponentInstanceBusinessLogic.java
@@ -25,7 +25,6 @@ import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.operations.impl.ComponentOperation;
import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -55,16 +54,6 @@ public class VFComponentInstanceBusinessLogic extends ComponentInstanceBusinessL
}
@Override
- protected ComponentOperation getContainerComponentOperation() {
- return resourceOperation;
- }
-
- @Override
- protected ComponentOperation getCompInstOriginComponentOperation() {
- return resourceOperation;
- }
-
- @Override
protected ComponentTypeEnum getComponentTypeOfComponentInstance() {
return ComponentTypeEnum.RESOURCE_INSTANCE;
}
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 445b3a9750..0e0f6f9464 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
@@ -21,27 +21,25 @@
package org.openecomp.sdc.be.components.lifecycle;
import java.util.Arrays;
-import java.util.List;
-
import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
import org.openecomp.sdc.be.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.ArtifactDefinition;
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.operations.api.ILifecycleOperation;
+import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementLifecycleOperation;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
+import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.model.operations.impl.ResourceOperation;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
import org.openecomp.sdc.be.user.Role;
-import org.openecomp.sdc.common.config.EcompErrorName;
import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -57,8 +55,8 @@ public class CertificationChangeTransition extends LifeCycleTransition {
private AuditingActionEnum auditingAction;
private ArtifactsBusinessLogic artifactsManager;
- public CertificationChangeTransition(LifeCycleTransitionEnum name, ComponentsUtils componentUtils, ILifecycleOperation lifecycleOperation) {
- super(componentUtils, lifecycleOperation);
+ public CertificationChangeTransition(LifeCycleTransitionEnum name, ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) {
+ super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao);
this.name = name;
@@ -67,7 +65,11 @@ public class CertificationChangeTransition extends LifeCycleTransition {
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;
@@ -106,7 +108,6 @@ public class CertificationChangeTransition extends LifeCycleTransition {
}
private ResponseFormat formatCertificationError(Component component, StorageOperationStatus response, ComponentTypeEnum componentType) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "Change LifecycleState - Certify failed on graph");
BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState - Certify failed on graph");
log.debug("certification change failed on graph");
@@ -118,20 +119,24 @@ public class CertificationChangeTransition extends LifeCycleTransition {
@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 change. resource name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId());
+ log.info("validate before certification change. resource name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId());
// validate user
- Either<Boolean, ResponseFormat> userValidationResponse = userRoleValidation(modifier, componentType, lifecycleChangeInfo);
- if (userValidationResponse.isRight()) {
+ 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);
+ 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);
}
@@ -144,14 +149,13 @@ public class CertificationChangeTransition extends LifeCycleTransition {
log.info("start performing certification change for resource {}", component.getUniqueId());
Either<? extends Component, ResponseFormat> result = null;
- NodeTypeEnum nodeType = componentType.getNodeType();
try {
- Either<? extends Component, StorageOperationStatus> certificationChangeResult = Either.right(StorageOperationStatus.GENERAL_ERROR);
+ Either<ToscaElement, StorageOperationStatus> certificationChangeResult = Either.right(StorageOperationStatus.GENERAL_ERROR);
if (nextState.equals(LifecycleStateEnum.CERTIFIED)) {
- certificationChangeResult = lifeCycleOperation.certifyComponent(nodeType, component, modifier, owner, true);
+ certificationChangeResult = lifeCycleOperation.certifyToscaElement(component.getUniqueId(), modifier.getUserId(), owner.getUserId());
} else {
- certificationChangeResult = lifeCycleOperation.cancelOrFailCertification(nodeType, component, modifier, owner, nextState, true);
+ certificationChangeResult = lifeCycleOperation.cancelOrFailCertification(component.getUniqueId(), modifier.getUserId(), owner.getUserId(), nextState);
}
if (certificationChangeResult.isRight()) {
@@ -159,51 +163,32 @@ public class CertificationChangeTransition extends LifeCycleTransition {
result = Either.right(responseFormat);
return result;
}
-
+
if (nextState.equals(LifecycleStateEnum.CERTIFIED)) {
- Either<Boolean, StorageOperationStatus> deleteOldComponentVersions = lifeCycleOperation.deleteOldComponentVersions(nodeType, component.getComponentMetadataDefinition().getMetadataDataDefinition().getName(),
- component.getComponentMetadataDefinition().getMetadataDataDefinition().getUUID(), true);
+ 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);
- return result;
}
}
- result = Either.left(certificationChangeResult.left().value());
+ result = Either.left(ModelConverter.convertFromToscaElement(certificationChangeResult.left().value()));
return result;
} finally {
if (result == null || result.isRight()) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "Change LifecycleState");
BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState");
if (inTransaction == false) {
log.debug("operation failed. do rollback");
- lifeCycleOperation.getResourceOperation().getTitanGenericDao().rollback();
+ titanDao.rollback();
}
} else {
if (inTransaction == false) {
log.debug("operation success. do commit");
- lifeCycleOperation.getResourceOperation().getTitanGenericDao().commit();
+ titanDao.commit();
}
}
}
}
-
- public StorageOperationStatus deleteOldVersion(List<ArtifactDefinition> artifactsToDelete, Resource resourceToDelete) {
- ResourceOperation resourceOperation = lifeCycleOperation.getResourceOperation();
-
- Either<List<ArtifactDefinition>, StorageOperationStatus> artifactsRes = resourceOperation.getComponentArtifactsForDelete(resourceToDelete.getUniqueId(), NodeTypeEnum.Resource, true);
- if (artifactsRes.isRight()) {
- return artifactsRes.right().value();
- }
- Either<Resource, StorageOperationStatus> deleteResourceRes = resourceOperation.deleteResource(resourceToDelete.getUniqueId(), true);
- if (deleteResourceRes.isRight()) {
- return deleteResourceRes.right().value();
- }
- artifactsToDelete.addAll(artifactsRes.left().value());
-
- return StorageOperationStatus.OK;
- }
-
}
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 69a9cbdb24..042af54383 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
@@ -29,10 +29,14 @@ import java.util.Map.Entry;
import java.util.Optional;
import java.util.Set;
+import org.apache.commons.codec.binary.Base64;
import org.openecomp.sdc.be.components.distribution.engine.ServiceDistributionArtifactsBuilder;
+import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic;
import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
+import org.openecomp.sdc.be.config.BeEcompErrorManager;
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;
@@ -50,13 +54,20 @@ import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.Service;
import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementLifecycleOperation;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
+import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
import org.openecomp.sdc.be.model.operations.api.ILifecycleOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.CapabilityOperation;
import org.openecomp.sdc.be.model.operations.impl.ResourceOperation;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.tosca.ToscaError;
import org.openecomp.sdc.be.tosca.ToscaExportHandler;
+import org.openecomp.sdc.be.tosca.ToscaRepresentation;
import org.openecomp.sdc.be.user.Role;
+import org.openecomp.sdc.common.api.ArtifactTypeEnum;
import org.openecomp.sdc.common.util.ValidationUtils;
import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
@@ -68,15 +79,11 @@ public class CertificationRequestTransition extends LifeCycleTransition {
private static Logger log = LoggerFactory.getLogger(CertificationRequestTransition.class.getName());
- private ServiceDistributionArtifactsBuilder serviceDistributionArtifactsBuilder;
- private ResourceOperation resourceOperation;
private CapabilityOperation capabilityOperation;
private ServiceBusinessLogic serviceBusinessLogic;
- private ToscaExportHandler toscaExportUtils;
-
- public CertificationRequestTransition(ComponentsUtils componentUtils, ILifecycleOperation lifecycleOperation, ServiceDistributionArtifactsBuilder serviceDistributionArtifactsBuilder, ServiceBusinessLogic serviceBusinessLogic,
- CapabilityOperation capabilityOperation, ToscaExportHandler toscaExportUtils) {
- super(componentUtils, lifecycleOperation);
+ 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 };
@@ -87,13 +94,13 @@ public class CertificationRequestTransition extends LifeCycleTransition {
// 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.serviceDistributionArtifactsBuilder = serviceDistributionArtifactsBuilder;
- if (lifeCycleOperation != null)
- this.resourceOperation = lifeCycleOperation.getResourceOperation();
this.serviceBusinessLogic = serviceBusinessLogic;
this.capabilityOperation = capabilityOperation;
- this.toscaExportUtils = toscaExportUtils;
}
@Override
@@ -125,7 +132,7 @@ public class CertificationRequestTransition extends LifeCycleTransition {
private ResponseFormat getRelevantResponseFormatUncertifiedRI(ComponentInstance nonCertifiedRI, ComponentTypeEnum componentType) {
ResponseFormat responseFormat;
- Either<Resource, StorageOperationStatus> eitherResource = resourceOperation.getResource(nonCertifiedRI.getComponentUid());
+ Either<Resource, StorageOperationStatus> eitherResource = toscaOperationFacade.getToscaElement(nonCertifiedRI.getComponentUid());
if (eitherResource.isRight()) {
responseFormat = componentUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
@@ -133,16 +140,16 @@ public class CertificationRequestTransition extends LifeCycleTransition {
} else {
ActionStatus actionStatus;
Resource resource = eitherResource.left().value();
- Either<List<Resource>, StorageOperationStatus> status = resourceOperation.findLastCertifiedResourceByUUID(resource);
+ Either<Resource, StorageOperationStatus> status = toscaOperationFacade.findLastCertifiedToscaElementByUUID(resource);
if (ValidationUtils.validateMinorVersion(nonCertifiedRI.getComponentVersion())) {
- if (status.isRight() || status.left().value() == null || status.left().value().isEmpty()) {
+ 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 || status.left().value().isEmpty())
+ if (status.isRight() || status.left().value() == null)
actionStatus = ActionStatus.FOUND_LIST_VALIDATED_RESOURCES;
else {
actionStatus = ActionStatus.FOUND_ALREADY_VALIDATED_RESOURCE;
@@ -157,23 +164,23 @@ public class CertificationRequestTransition extends LifeCycleTransition {
private Either<ActionStatus, Map<String, ArtifactDefinition>> validateMandatoryArtifactsSupplied(Map<String, ArtifactDefinition> artifacts) {
- if (artifacts == null || true == artifacts.isEmpty()) {
+ if (artifacts == null || artifacts.isEmpty()) {
return Either.left(ActionStatus.OK);
}
- Map<String, ArtifactDefinition> invalidArtifacts = new HashMap<String, ArtifactDefinition>();
+ Map<String, ArtifactDefinition> invalidArtifacts = new HashMap<>();
for (Entry<String, ArtifactDefinition> artifact : artifacts.entrySet()) {
ArtifactDefinition artifactDefinition = artifact.getValue();
- if (true == artifactDefinition.getMandatory()) {
+ if (artifactDefinition.getMandatory()) {
String artifactEsId = artifactDefinition.getEsId();
- if (artifactEsId == null || true == artifactEsId.isEmpty()) {
+ if (artifactEsId == null || artifactEsId.isEmpty()) {
invalidArtifacts.put(artifact.getKey(), artifactDefinition);
}
}
}
- if (true == invalidArtifacts.isEmpty()) {
+ if (invalidArtifacts.isEmpty()) {
return Either.left(ActionStatus.OK);
} else {
return Either.right(invalidArtifacts);
@@ -185,81 +192,73 @@ public class CertificationRequestTransition extends LifeCycleTransition {
log.debug("start performing certification request for resource {}", component.getUniqueId());
- // Either<ActionStatus, Map<String, ArtifactDefinition>>
- // validateMandatoryArtifacts =
- // validateMandatoryArtifactsSupplied(component.getArtifacts());
- // log.debug("After checking mandatory artifacts were populated. Result
- // is " + validateMandatoryArtifacts);
- // if (validateMandatoryArtifacts.isRight()) {
- // ResponseFormat responseFormat = componentUtils
- // .getResponseFormatByMissingArtifacts(
- // componentType,
- // validateMandatoryArtifacts.right().value());
- // return Either.right(responseFormat);
- // }
- ActionStatus actionStatus = null;
- ResponseFormat responseFormat = null;
-
- if (componentType == ComponentTypeEnum.SERVICE || (componentType == ComponentTypeEnum.RESOURCE && ((Resource) component).getResourceType() == ResourceTypeEnum.VF)) {
-
- 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());
+ ActionStatus actionStatus;
+ ResponseFormat responseFormat;
+ Either<? extends Component, ResponseFormat> result = null;
+ try{
+ if (componentType == ComponentTypeEnum.SERVICE || (componentType == ComponentTypeEnum.RESOURCE && ((Resource) component).getResourceType() == ResourceTypeEnum.VF)) {
+
+ 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<Boolean, StorageOperationStatus> status = validateDeloymentArtifactSupplied((Service) component);
- if (status.isRight()) {
- StorageOperationStatus operationStatus = status.right().value();
- actionStatus = componentUtils.convertFromStorageResponse(operationStatus);
- } else {
- Boolean isDeploymentArtifactExists = status.left().value();
- if (isDeploymentArtifactExists == null || isDeploymentArtifactExists.booleanValue() == false) {
- actionStatus = ActionStatus.SERVICE_DEPLOYMENT_ARTIFACT_NOT_FOUND;
- } else {
- Either<Service, ResponseFormat> generateHeatEnvResult = serviceBusinessLogic.generateHeatEnvArtifacts((Service) component, modifier, shouldLock);
- if (generateHeatEnvResult.isRight()) {
+ 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()) {
+ Either<Service, ResponseFormat> generateVfModuleResult = serviceBusinessLogic.generateVfModuleArtifacts((Service) component, modifier, shouldLock);
+ if (generateVfModuleResult.isRight()) {
return Either.right(generateVfModuleResult.right().value());
- }
}
}
-
- if (actionStatus != null) {
+
+ 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);
- return Either.right(responseFormat);
+ result = Either.right(responseFormat);
}
-
- }
-
- 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<? extends Component, StorageOperationStatus> certificationRequestResult = lifeCycleOperation.requestCertificationComponent(nodeType, component, modifier, owner, inTransaction);
- 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;
+ else {
+ result = Either.left(ModelConverter.convertFromToscaElement(certificationRequestResult.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();
}
- responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType);
- return Either.right(responseFormat);
}
-
- return Either.left(certificationRequestResult.left().value());
+ }
+ return result;
}
private Either<Boolean, ResponseFormat> validateConfiguredAtomicReqCapSatisfied(Component component) {
@@ -369,7 +368,7 @@ public class CertificationRequestTransition extends LifeCycleTransition {
log.debug("validate before certification request. resource name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId());
// validate user
- Either<Boolean, ResponseFormat> userValidationResponse = userRoleValidation(modifier, componentType, lifecycleChangeInfo);
+ Either<Boolean, ResponseFormat> userValidationResponse = userRoleValidation(modifier,component, componentType, lifecycleChangeInfo);
if (userValidationResponse.isRight()) {
return userValidationResponse;
}
@@ -397,13 +396,4 @@ public class CertificationRequestTransition extends LifeCycleTransition {
return Either.left(true);
}
-
- private Either<Boolean, StorageOperationStatus> validateDeloymentArtifactSupplied(Service service) {
-
- Either<Boolean, StorageOperationStatus> serviceContainsDeploymentArtifacts = this.serviceDistributionArtifactsBuilder.isServiceContainsDeploymentArtifacts(service);
-
- return serviceContainsDeploymentArtifacts;
-
- }
-
}
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 28227285f1..bfe51ded48 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
@@ -23,15 +23,19 @@ package org.openecomp.sdc.be.components.lifecycle;
import java.util.Arrays;
import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic;
+import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
import org.openecomp.sdc.be.model.LifecycleStateEnum;
import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.be.model.operations.api.ILifecycleOperation;
+import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementLifecycleOperation;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
+import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
import org.openecomp.sdc.be.user.Role;
@@ -45,8 +49,8 @@ public class CheckinTransition extends LifeCycleTransition {
private static Logger log = LoggerFactory.getLogger(CheckinTransition.class.getName());
- public CheckinTransition(ComponentsUtils componentUtils, ILifecycleOperation lifecycleOperation) {
- super(componentUtils, lifecycleOperation);
+ public CheckinTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) {
+ super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao);
// authorized roles
Role[] resourceServiceCheckoutRoles = { Role.ADMIN, Role.DESIGNER };
@@ -71,21 +75,40 @@ public class CheckinTransition extends LifeCycleTransition {
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());
- NodeTypeEnum nodeType = componentType.getNodeType();
- Either<? extends Component, StorageOperationStatus> checkinResourceResult = lifeCycleOperation.checkinComponent(nodeType, component, modifier, owner, inTransaction);
- 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;
+ 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();
+ }
}
- ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType);
- return Either.right(responseFormat);
}
-
- return Either.left(checkinResourceResult.left().value());
+ return result;
}
@Override
@@ -94,13 +117,19 @@ public class CheckinTransition extends LifeCycleTransition {
log.debug("validate before checkin. component name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId());
// validate user
- Either<Boolean, ResponseFormat> userValidationResponse = userRoleValidation(modifier, componentType, lifecycleChangeInfo);
+ 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)) {
- ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_ALREADY_CHECKED_IN, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId());
+ 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);
}
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 a4e6bdb86c..d6cbd3663c 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckoutTransition.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckoutTransition.java
@@ -21,17 +21,26 @@
package org.openecomp.sdc.be.components.lifecycle;
import java.util.Arrays;
+import java.util.List;
import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic;
+import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
+import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
+import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+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.operations.api.ILifecycleOperation;
+import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementLifecycleOperation;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
+import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
import org.openecomp.sdc.be.user.Role;
@@ -43,12 +52,10 @@ import fj.data.Either;
public class CheckoutTransition extends LifeCycleTransition {
- private static final String PLACE_HOLDER_RESOURCE_TYPES = "validForResourceTypes";
-
private static Logger log = LoggerFactory.getLogger(CheckoutTransition.class.getName());
- public CheckoutTransition(ComponentsUtils componentUtils, ILifecycleOperation lifecycleOperation) {
- super(componentUtils, lifecycleOperation);
+ public CheckoutTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) {
+ super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao);
// authorized roles
Role[] resourceServiceCheckoutRoles = { Role.ADMIN, Role.DESIGNER };
@@ -74,24 +81,66 @@ public class CheckoutTransition extends LifeCycleTransition {
log.debug("start performing {} for resource {}", getName().name(), component.getUniqueId());
- if (componentBl != null)
- componentBl.setDeploymentArtifactsPlaceHolder(component, modifier);
- NodeTypeEnum nodeType = componentType.getNodeType();
- Either<? extends Component, StorageOperationStatus> checkoutResourceResult = lifeCycleOperation.checkoutComponent(nodeType, component, modifier, owner, inTransaction);
+ 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());
+ 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);
+ }
+ }
- 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;
+ } 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();
+ }
}
- ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType);
- return Either.right(responseFormat);
}
+ return result;
+ }
- return Either.left(checkoutResourceResult.left().value());
+ private StorageOperationStatus upgradeToLatestGenericData(Component clonedComponent) {
+
+ StorageOperationStatus updateStatus = null;
+ 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
@@ -100,7 +149,7 @@ public class CheckoutTransition extends LifeCycleTransition {
log.debug("validate before checkout. resource name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId());
// validate user
- Either<Boolean, ResponseFormat> userValidationResponse = userRoleValidation(modifier, componentType, lifecycleChangeInfo);
+ Either<Boolean, ResponseFormat> userValidationResponse = userRoleValidation(modifier, component, componentType, lifecycleChangeInfo);
if (userValidationResponse.isRight()) {
return userValidationResponse;
}
@@ -131,11 +180,4 @@ public class CheckoutTransition extends LifeCycleTransition {
return Either.left(true);
}
- /*
- * private Either<Boolean, ResponseFormat> productContactsValidation(Product product, User modifier) { // validate user Either<Boolean, ResponseFormat> eitherResponse = Either.left(true); String role = modifier.getRole(); if
- * (UserRoleEnum.PRODUCT_MANAGER.getName().equals(role) || UserRoleEnum.PRODUCT_STRATEGIST.getName().equals(role)){ String userId = modifier.getUserId(); if (!product.getContacts().contains(userId)){ log.
- * debug("User with userId {} cannot checkout product. userId not found in product contacts list" , userId); ResponseFormat responseFormat = componentUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); return Either.right(responseFormat);
- * } else { log. trace("Found user userId {} in product contacts - checkout request validated" ); } } return eitherResponse; }
- */
-
}
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 49d94dc80b..0d0e06fe6d 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
@@ -24,44 +24,53 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic;
import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction.LifecycleChanceActionEnum;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
+import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
import org.openecomp.sdc.be.model.LifecycleStateEnum;
import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementLifecycleOperation;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
import org.openecomp.sdc.be.model.operations.api.ILifecycleOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
import org.openecomp.sdc.be.user.Role;
import org.openecomp.sdc.exception.ResponseFormat;
+import org.springframework.beans.factory.annotation.Autowired;
import fj.data.Either;
public abstract class LifeCycleTransition {
protected ConfigurationManager configurationManager;
- protected ILifecycleOperation lifeCycleOperation;
+ @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, ILifecycleOperation lifecycleOperation) {
+ protected LifeCycleTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation2, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) {
- // configurationManager = (ConfigurationManager)
- // context.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR);
- // lifeCycleOperation = LifecycleOperation.getInstance();
this.configurationManager = ConfigurationManager.getConfigurationManager();
- this.lifeCycleOperation = lifecycleOperation;
+ this.lifeCycleOperation = lifecycleOperation2;
this.componentUtils = componentUtils;
this.authorizedRoles = new HashMap<>();
-
+ this.resourceAuthorizedRoles = new HashMap<>();
+ this.toscaOperationFacade = toscaOperationFacade;
+ this.titanDao = titanDao;
}
public abstract LifeCycleTransitionEnum getName();
@@ -76,11 +85,11 @@ public abstract class LifeCycleTransition {
this.configurationManager = configurationManager;
}
- public ILifecycleOperation getLifeCycleOperation() {
+ public ToscaElementLifecycleOperation getLifeCycleOperation() {
return lifeCycleOperation;
}
- public void setLifeCycleOperation(ILifecycleOperation lifeCycleOperation) {
+ public void setLifeCycleOperation(ToscaElementLifecycleOperation lifeCycleOperation) {
this.lifeCycleOperation = lifeCycleOperation;
}
@@ -91,14 +100,14 @@ public abstract class LifeCycleTransition {
public void addAuthorizedRoles(ComponentTypeEnum componentType, List<Role> authorizedRoles) {
this.authorizedRoles.put(componentType, authorizedRoles);
}
+
+ public List<Role> getResourceAuthorizedRoles(ResourceTypeEnum resourceType) {
+ return resourceAuthorizedRoles.get(resourceType);
+ }
- //
- // public Either<? extends Component, ResponseFormat>
- // changeState(ComponentTypeEnum componentType, Component component,
- // ComponentBusinessLogic componentBl, User modifier, User owner){
- // return changeState(componentType, component, componentBl, modifier,
- // owner, false);
- // }
+ 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);
@@ -122,8 +131,7 @@ public abstract class LifeCycleTransition {
protected Either<User, ResponseFormat> getComponentOwner(Component component, ComponentTypeEnum componentType, boolean inTransaction) {
- NodeTypeEnum nodeType = componentType.getNodeType();
- Either<User, StorageOperationStatus> resourceOwnerResult = getLifeCycleOperation().getComponentOwner(component.getUniqueId(), nodeType, 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);
@@ -131,21 +139,13 @@ public abstract class LifeCycleTransition {
return Either.left(resourceOwnerResult.left().value());
}
- /**
- * isUserValidForRequest
- *
- * @param modifier
- * @param action
- * TODO
- * @return
- */
- protected Either<Boolean, ResponseFormat> userRoleValidation(User modifier, ComponentTypeEnum componentType, LifecycleChangeInfoWithAction lifecycleChangeInfo) {
+ protected Either<Boolean, ResponseFormat> userRoleValidation(User modifier,Component component, ComponentTypeEnum componentType, LifecycleChangeInfoWithAction lifecycleChangeInfo) {
// validate user
- if (getAuthorizedRoles(componentType).contains(Role.valueOf(modifier.getRole()))) {
+ //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 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
@@ -156,5 +156,18 @@ public abstract class LifeCycleTransition {
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;
+ }
}
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 27709bb332..8e89a6bf31 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
@@ -34,8 +34,11 @@ import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic;
import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
+import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
@@ -43,14 +46,13 @@ import org.openecomp.sdc.be.model.LifecycleStateEnum;
import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.Service;
import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementLifecycleOperation;
+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.IGraphLockOperation;
-import org.openecomp.sdc.be.model.operations.api.ILifecycleOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.CapabilityOperation;
-import org.openecomp.sdc.be.model.operations.impl.ProductOperation;
-import org.openecomp.sdc.be.model.operations.impl.ResourceOperation;
-import org.openecomp.sdc.be.model.operations.impl.ServiceOperation;
+import org.openecomp.sdc.be.model.operations.impl.ComponentOperation;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
import org.openecomp.sdc.be.tosca.ToscaExportHandler;
import org.openecomp.sdc.common.api.Constants;
@@ -76,13 +78,7 @@ public class LifecycleBusinessLogic {
private ArtifactsBusinessLogic artifactsBusinessLogic;
@Autowired
- private ResourceOperation resourceOperation;
-
- @Autowired
- private ServiceOperation serviceOperation;
-
- @Autowired
- private ProductOperation productOperation;
+ private TitanDao titanDao;
@Autowired
private CapabilityOperation capabilityOperation;
@@ -93,7 +89,7 @@ public class LifecycleBusinessLogic {
private ComponentsUtils componentUtils;
@javax.annotation.Resource
- private ILifecycleOperation lifecycleOperation;
+ private ToscaElementLifecycleOperation lifecycleOperation;
@javax.annotation.Resource
ArtifactsBusinessLogic artifactsManager;
@@ -114,6 +110,9 @@ public class LifecycleBusinessLogic {
@Autowired
ICacheMangerOperation cacheManagerOperation;
+
+ @Autowired
+ ToscaOperationFacade toscaOperationFacade;
private Map<String, LifeCycleTransition> stateTransitions;
private static volatile boolean isInitialized = false;
@@ -134,29 +133,29 @@ public class LifecycleBusinessLogic {
private void initStateOperations() {
stateTransitions = new HashMap<String, LifeCycleTransition>();
- LifeCycleTransition checkoutOp = new CheckoutTransition(componentUtils, lifecycleOperation);
+ LifeCycleTransition checkoutOp = new CheckoutTransition(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao);
stateTransitions.put(checkoutOp.getName().name(), checkoutOp);
- UndoCheckoutTransition undoCheckoutOp = new UndoCheckoutTransition(componentUtils, lifecycleOperation);
+ UndoCheckoutTransition undoCheckoutOp = new UndoCheckoutTransition(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao);
undoCheckoutOp.setArtifactsBusinessLogic(artifactsBusinessLogic);
stateTransitions.put(undoCheckoutOp.getName().name(), undoCheckoutOp);
- LifeCycleTransition checkinOp = new CheckinTransition(componentUtils, lifecycleOperation);
+ LifeCycleTransition checkinOp = new CheckinTransition(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao);
stateTransitions.put(checkinOp.getName().name(), checkinOp);
- LifeCycleTransition certificationRequest = new CertificationRequestTransition(componentUtils, lifecycleOperation, serviceDistributionArtifactsBuilder, serviceBusinessLogic, capabilityOperation, toscaExportUtils);
+ LifeCycleTransition certificationRequest = new CertificationRequestTransition(componentUtils, lifecycleOperation, serviceDistributionArtifactsBuilder, serviceBusinessLogic, capabilityOperation, toscaExportUtils, toscaOperationFacade, titanDao);
stateTransitions.put(certificationRequest.getName().name(), certificationRequest);
- LifeCycleTransition startCertification = new StartCertificationTransition(componentUtils, lifecycleOperation);
+ LifeCycleTransition startCertification = new StartCertificationTransition(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao);
stateTransitions.put(startCertification.getName().name(), startCertification);
- LifeCycleTransition failCertification = new CertificationChangeTransition(LifeCycleTransitionEnum.FAIL_CERTIFICATION, componentUtils, lifecycleOperation);
+ 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);
+ 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);
+ CertificationChangeTransition successCertification = new CertificationChangeTransition(LifeCycleTransitionEnum.CERTIFY, componentUtils, lifecycleOperation, toscaOperationFacade, titanDao);
successCertification.setArtifactsManager(artifactsBusinessLogic);
stateTransitions.put(successCertification.getName().name(), successCertification);
}
@@ -172,132 +171,16 @@ public class LifecycleBusinessLogic {
// 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);
-
- // 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);
- // }
- //
- // Either<Resource, ResponseFormat> operationResult;
- // Resource resource = null;
- // boolean needToUnlockResource = false;
- //
- // log.debug("get resource from graph");
- // ResponseFormat errorResponse;
- // Either<Resource, ResponseFormat> eitherResourceResponse =
- // getResourceForChange(resourceId, modifier, lifeCycleTransition);
- // if (eitherResourceResponse.isRight()) {
- // return eitherResourceResponse;
- // }
- // resource = eitherResourceResponse.left().value();
- // String resourceCurrVersion = resource.getResourceVersion();
- // LifecycleStateEnum resourceCurrState = resource.getLifecycleState();
- //
- // if (inTransaction == false) {
- // // lock resource
- // Either<Boolean, ResponseFormat> eitherLockResource =
- // lockResource(resource);
- // if (eitherLockResource.isRight()) {
- // errorResponse = eitherLockResource.right().value();
- // componentUtils.auditResource(errorResponse, modifier, resource,
- // resourceCurrState.name(), resourceCurrVersion,
- // lifeCycleTransition.getAuditingAction(), null);
- // return Either.right(errorResponse);
- // }
- // needToUnlockResource = true;
- // }
- //
- // try {
- // Either<Boolean, ResponseFormat> resourceNotDeleted =
- // validateResourceNotDeleted(modifier, lifeCycleTransition, resource,
- // resourceCurrVersion);
- // if (resourceNotDeleted.isRight()) {
- // return Either.right(resourceNotDeleted.right().value());
- // }
- //
- // Either<Boolean, ResponseFormat> validateHighestVersion =
- // validateHighestVersion(modifier, lifeCycleTransition, resource,
- // resourceCurrVersion);
- // if (validateHighestVersion.isRight()) {
- // return Either.right(validateHighestVersion.right().value());
- // }
- //
- // Either<User, ResponseFormat> ownerResult =
- // lifeCycleTransition.getResourceOwner(resource);
- // if (ownerResult.isRight()) {
- // return Either.right(ownerResult.right().value());
- // }
- // User owner = ownerResult.left().value();
- // log.debug("owner of resource {} is {}", resource.getUniqueId(),
- // owner.getUserId());
- //
- // LifecycleStateEnum oldState = resource.getLifecycleState();
- //
- // Either<String, ResponseFormat> commentValidationResult =
- // validateComment(changeInfo, transitionEnum);
- // if (commentValidationResult.isRight()) {
- // errorResponse = commentValidationResult.right().value();
- // EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new
- // EnumMap<AuditingFieldsKeysEnum,
- // Object>(AuditingFieldsKeysEnum.class);
- // auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT,
- // changeInfo.getUserRemarks());
- // componentUtils.auditResource(errorResponse, modifier, resource,
- // resourceCurrState.name(), resourceCurrVersion,
- // lifeCycleTransition.getAuditingAction(), auditingFields);
- // return Either.right(errorResponse);
- // }
- // changeInfo.setUserRemarks(commentValidationResult.left().value());
- //
- // Either<Boolean, ResponseFormat> stateValidationResult =
- // lifeCycleTransition.validateResourceBeforeTransition(resource.getResourceName(),
- // ComponentTypeEnum.RESOURCE, modifier, owner, oldState);
- // if (stateValidationResult.isRight()) {
- // errorResponse = stateValidationResult.right().value();
- // componentUtils.auditResource(errorResponse, modifier, resource,
- // resourceCurrState.name(), resourceCurrVersion,
- // lifeCycleTransition.getAuditingAction(), null);
- // return Either.right(errorResponse);
- // }
- //
- // operationResult = lifeCycleTransition.changeStateOperation(resource,
- // modifier, owner, inTransaction);
- //
- // if (operationResult.isRight()) {
- // errorResponse = operationResult.right().value();
- // log.debug("audit before sending response");
- // componentUtils.auditResource(errorResponse, modifier, resource,
- // resourceCurrState.name(), resourceCurrVersion,
- // lifeCycleTransition.getAuditingAction(), null);
- //
- // return Either.right(errorResponse);
- // }
- // Resource resourceAfterOperation = operationResult.left().value();
- // EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new
- // EnumMap<AuditingFieldsKeysEnum,
- // Object>(AuditingFieldsKeysEnum.class);
- // auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT,
- // changeInfo.getUserRemarks());
- // componentUtils.auditResource(componentUtils.getResponseFormat(ActionStatus.OK),
- // modifier, resourceAfterOperation, resourceCurrState.name(),
- // resourceCurrVersion, lifeCycleTransition.getAuditingAction(),
- // auditingFields);
- // return operationResult;
- //
- // } finally {
- // log.debug("unlock resource {}", resourceId);
- // if (needToUnlockResource && resource != null) {
- // resource.setUniqueId(resourceId);
- // graphLockOperation.unlockResource(resource);
- // }
- // }
-
+ }
+
+ 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,
@@ -309,12 +192,8 @@ public class LifecycleBusinessLogic {
ResponseFormat error = componentUtils.getInvalidContentErrorAndAudit(modifier, AuditingActionEnum.CHECKOUT_RESOURCE);
return Either.right(error);
}
- ComponentBusinessLogic bl = getComponentBL(componentType);
-
- Either<? extends Component, ResponseFormat> operationResult = null;
Component component = null;
- // boolean needToUnlockResource = false;
- log.debug("get resource from graph");
+ log.info("get resource from graph");
ResponseFormat errorResponse;
Either<? extends Component, ResponseFormat> eitherResourceResponse = getComponentForChange(componentType, componentId, modifier, lifeCycleTransition, changeInfo);
@@ -325,110 +204,133 @@ public class LifecycleBusinessLogic {
String resourceCurrVersion = component.getVersion();
LifecycleStateEnum resourceCurrState = component.getLifecycleState();
+ log.info("lock component {}", componentId);
// lock resource
if (inTransaction == false && needLock) {
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);
}
- // needToUnlockResource = true;
}
+ log.info("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, Object>(AuditingFieldsKeysEnum.class);
+ 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.info("after validate component");
Either<Boolean, ResponseFormat> validateHighestVersion = validateHighestVersion(modifier, lifeCycleTransition, component, resourceCurrVersion, componentType);
if (validateHighestVersion.isRight()) {
return Either.right(validateHighestVersion.right().value());
}
-
- Either<User, ResponseFormat> ownerResult = lifeCycleTransition.getComponentOwner(component, componentType, inTransaction);
- if (ownerResult.isRight()) {
- return Either.right(ownerResult.right().value());
- }
- User owner = ownerResult.left().value();
- log.debug("owner of resource {} is {}", component.getUniqueId(), owner.getUserId());
-
- LifecycleStateEnum oldState = component.getLifecycleState();
-
- Either<Boolean, ResponseFormat> stateValidationResult = lifeCycleTransition.validateBeforeTransition(component, componentType, modifier, owner, oldState, changeInfo);
- if (stateValidationResult.isRight()) {
- errorResponse = stateValidationResult.right().value();
- EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(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);
-
- }
-
- operationResult = lifeCycleTransition.changeState(componentType, component, bl, modifier, owner, false, inTransaction);
-
- if (operationResult.isRight()) {
- errorResponse = operationResult.right().value();
- log.debug("audit before sending response");
- componentUtils.auditComponentAdmin(errorResponse, modifier, component, resourceCurrState.name(), resourceCurrVersion, lifeCycleTransition.getAuditingAction(), componentType);
-
- return Either.right(errorResponse);
+ log.info("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;
+ }
}
- 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, resourceCurrState.name(), resourceCurrVersion, lifeCycleTransition.getAuditingAction(), componentType, auditingFields);
- return operationResult;
+ return changeState(component, lifeCycleTransition, componentType, modifier, changeInfo, inTransaction);
} finally {
- log.debug("unlock component {}", componentId);
+ log.info("unlock component {}", componentId);
if (inTransaction == false && needLock && component != null) {
component.setUniqueId(componentId);
NodeTypeEnum nodeType = componentType.getNodeType();
+ log.info("During change state, another component {} has been created/updated", componentId);
+ graphLockOperation.unlockComponent(componentId, nodeType);
- // Handle component change in the cache of the side affect of
- // the operation
- if (operationResult != null && operationResult.isLeft()) {
- Component componentAfterOpertion = operationResult.left().value();
- String uniqueId = componentAfterOpertion.getUniqueId();
- if (false == componentId.equals(uniqueId)) {
- log.debug("During change state, another component {} has been created/updated", uniqueId);
- if (uniqueId != null) {
- cacheManagerOperation.updateComponentInCache(uniqueId, componentAfterOpertion.getLastUpdateDate(), nodeType);
- }
- }
- }
+ }
+ }
- 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 = Either.right(StorageOperationStatus.GENERAL_ERROR);
- switch (componentType) {
- case SERVICE:
- eitherResourceResponse = serviceOperation.getComponent(componentId, true);
- break;
- case PRODUCT:
- eitherResourceResponse = productOperation.getComponent(componentId, true);
- break;
- case RESOURCE:
- eitherResourceResponse = resourceOperation.getComponent(componentId, true);
- break;
- default:
- break;
- }
+ Either<? extends Component, StorageOperationStatus> eitherResourceResponse = toscaOperationFacade.getToscaElement(componentId);
- ResponseFormat errorResponse = null;
+ ResponseFormat errorResponse;
if (eitherResourceResponse.isRight()) {
ActionStatus actionStatus = componentUtils.convertFromStorageResponse(eitherResourceResponse.right().value(), componentType);
errorResponse = componentUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING);
@@ -494,28 +396,6 @@ public class LifecycleBusinessLogic {
}
- private Either<Resource, ResponseFormat> getResourceForChange(String resourceId, User modifier, LifeCycleTransition lifeCycleTransition) {
- Either<Resource, StorageOperationStatus> eitherResourceResponse = resourceOperation.getResource(resourceId, true);
-
- ResponseFormat errorResponse = null;
- if (eitherResourceResponse.isRight()) {
- ActionStatus actionStatus = componentUtils.convertFromStorageResponse(eitherResourceResponse.right().value());
- errorResponse = componentUtils.getResponseFormatByResource(actionStatus, "");
- log.debug("audit before sending response");
- // For audit of not found, resourceName should be uniqueID according
- // to Ella
- EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceId);
- componentUtils.auditResource(errorResponse, modifier, null, "", "", lifeCycleTransition.getAuditingAction(), null);
-
- return Either.right(errorResponse);
- }
- Resource resource = eitherResourceResponse.left().value();
-
- return Either.left(resource);
-
- }
-
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
@@ -548,25 +428,39 @@ public class LifecycleBusinessLogic {
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());
- }
+ 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);
+ }
}
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 918140b0af..8a80e0bb64 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
@@ -22,15 +22,23 @@ package org.openecomp.sdc.be.components.lifecycle;
import java.util.Arrays;
+import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic;
+import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
import org.openecomp.sdc.be.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.LifeCycleTransitionEnum;
import org.openecomp.sdc.be.model.LifecycleStateEnum;
import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementLifecycleOperation;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
+import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
import org.openecomp.sdc.be.model.operations.api.ILifecycleOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
@@ -45,14 +53,18 @@ public class StartCertificationTransition extends LifeCycleTransition {
private static Logger log = LoggerFactory.getLogger(StartCertificationTransition.class.getName());
- public StartCertificationTransition(ComponentsUtils componentUtils, ILifecycleOperation lifecycleOperation) {
- super(componentUtils, lifecycleOperation);
+ 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
@@ -69,22 +81,38 @@ public class StartCertificationTransition extends LifeCycleTransition {
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());
-
- NodeTypeEnum nodeType = (componentType.equals(ComponentTypeEnum.SERVICE)) ? NodeTypeEnum.Service : NodeTypeEnum.Resource;
- Either<? extends Component, StorageOperationStatus> stateChangeResult = lifeCycleOperation.startComponentCertification(nodeType, component, modifier, owner, inTransaction);
- 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;
+ 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();
+ }
}
- ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType);
- return Either.right(responseFormat);
}
-
- return Either.left(stateChangeResult.left().value());
+ return result;
}
@Override
@@ -93,11 +121,11 @@ public class StartCertificationTransition extends LifeCycleTransition {
log.debug("validate before start certification test. resource name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId());
// validate user
- Either<Boolean, ResponseFormat> userValidationResponse = userRoleValidation(modifier, componentType, lifecycleChangeInfo);
+ 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);
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 fcb211bc3e..277cd173aa 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
@@ -21,25 +21,24 @@
package org.openecomp.sdc.be.components.lifecycle;
import java.util.Arrays;
-import java.util.List;
-
import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.model.ArtifactDefinition;
import org.openecomp.sdc.be.model.Component;
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.operations.api.ILifecycleOperation;
+import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementLifecycleOperation;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
+import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
import org.openecomp.sdc.be.user.Role;
-import org.openecomp.sdc.common.config.EcompErrorName;
import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -50,8 +49,8 @@ public class UndoCheckoutTransition extends LifeCycleTransition {
private static Logger log = LoggerFactory.getLogger(CheckoutTransition.class.getName());
private ArtifactsBusinessLogic artifactsManager;
- public UndoCheckoutTransition(ComponentsUtils componentUtils, ILifecycleOperation lifecycleOperation) {
- super(componentUtils, lifecycleOperation);
+ public UndoCheckoutTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) {
+ super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao);
// authorized roles
Role[] resourceServiceCheckoutRoles = { Role.ADMIN, Role.DESIGNER };
@@ -86,7 +85,7 @@ public class UndoCheckoutTransition extends LifeCycleTransition {
log.debug("validate before undo checkout. resource name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId());
// validate user
- Either<Boolean, ResponseFormat> userValidationResponse = userRoleValidation(modifier, componentType, lifecycleChangeInfo);
+ Either<Boolean, ResponseFormat> userValidationResponse = userRoleValidation(modifier,component, componentType, lifecycleChangeInfo);
if (userValidationResponse.isRight()) {
return userValidationResponse;
}
@@ -111,59 +110,29 @@ public class UndoCheckoutTransition extends LifeCycleTransition {
Either<? extends Component, ResponseFormat> result = null;
log.debug("start performing undo-checkout for resource {}", component.getUniqueId());
- Either<List<ArtifactDefinition>, StorageOperationStatus> artifactsRes = lifeCycleOperation.getComponentOperation(componentType.getNodeType()).getComponentArtifactsForDelete(component.getUniqueId(), componentType.getNodeType(), true);
- if (artifactsRes.isRight()) {
- ActionStatus actionStatus = componentUtils.convertFromStorageResponse(artifactsRes.right().value());
- ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType);
- result = Either.right(responseFormat);
- return result;
- }
- // TODO - start transaction
try {
- NodeTypeEnum nodeType = componentType.getNodeType();
-
- // 1. perform undo checkout on graph (update status and delete
- // current version)
- Either<? extends Component, StorageOperationStatus> undoCheckoutResourceResult = lifeCycleOperation.undoCheckout(nodeType, component, modifier, owner, true);
+ 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);
- return result;
+ result = Either.right(responseFormat);
}
-
- // 2. delete unrelated artifacts
- // use artifacts API to delete artifacts from swift / elasticsearch
-
- if (artifactsRes.left().value() != null) {
- List<ArtifactDefinition> artifacts = artifactsRes.left().value();
- StorageOperationStatus deleteAllResourceArtifacts = artifactsManager.deleteAllComponentArtifactsIfNotOnGraph(artifacts);
-
- if (!deleteAllResourceArtifacts.equals(StorageOperationStatus.OK)) {
- ActionStatus actionStatus = componentUtils.convertFromStorageResponse(deleteAllResourceArtifacts);
- ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType);
- result = Either.right(responseFormat);
- return result;
- }
+ else {
+ result = Either.left(ModelConverter.convertFromToscaElement(undoCheckoutResourceResult.left().value()));
}
-
- result = Either.left(undoCheckoutResourceResult.left().value());
} finally {
if (result == null || result.isRight()) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "Change LifecycleState - Undo Checkout failed on graph");
BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState - Undo Checkout failed on graph");
-
log.debug("operation failed. do rollback");
- lifeCycleOperation.getResourceOperation().getTitanGenericDao().rollback();
+ titanDao.rollback();
} else {
log.debug("operation success. do commit");
- lifeCycleOperation.getResourceOperation().getTitanGenericDao().commit();
+ titanDao.commit();
}
}
-
return result;
}
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 edfe56ebfa..921aefaa8e 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,7 +24,7 @@ import java.io.Serializable;
public enum CategoryTypeEnum implements Serializable {
- CATEGORY("category"), SUBCATEGORY("sub-category"), GROUPING("grouping");
+ CATEGORY("category"), SUBCATEGORY("subcategory"), GROUPING("grouping");
private String value;
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/UiComponentDataConverter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/UiComponentDataConverter.java
new file mode 100644
index 0000000000..46505b843e
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/UiComponentDataConverter.java
@@ -0,0 +1,218 @@
+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.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;
+
+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;
+ }
+
+}
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 5670239ef7..7b49d3fcea 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
@@ -25,6 +25,10 @@ import java.util.List;
import javax.servlet.http.HttpServletRequest;
+import org.openecomp.portalsdk.core.onboarding.crossapi.IPortalRestAPIService;
+import org.openecomp.portalsdk.core.onboarding.crossapi.PortalAPIException;
+import org.openecomp.portalsdk.core.restful.domain.EcompRole;
+import org.openecomp.portalsdk.core.restful.domain.EcompUser;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
import org.openecomp.sdc.be.dao.api.ActionStatus;
@@ -39,11 +43,6 @@ import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.ContextLoader;
-import org.openecomp.portalsdk.core.onboarding.crossapi.IPortalRestAPIService;
-import org.openecomp.portalsdk.core.onboarding.crossapi.PortalAPIException;
-import org.openecomp.portalsdk.core.restful.domain.EcompRole;
-import org.openecomp.portalsdk.core.restful.domain.EcompUser;
-
import fj.data.Either;
/*
@@ -76,7 +75,7 @@ public class EcompIntImpl implements IPortalRestAPIService {
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());
+ 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);
@@ -292,23 +291,29 @@ public class EcompIntImpl implements IPortalRestAPIService {
String updatedRole = null;
if (roles == null) {
- throw new PortalAPIException("Error: Recieved null for roles");
+ 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");
- }
-
- 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());
- }
+ //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
@@ -359,7 +364,7 @@ public class EcompIntImpl implements IPortalRestAPIService {
if (USERNAME != null && PASSWORD != null) {
if (!USERNAME.equals("") && !PASSWORD.equals("")) {
- log.debug("User authenticated - Username: {} Password: {}", USERNAME, PASSWORD);
+ log.debug("User authenticated - Username: ,Password: {}", USERNAME, PASSWORD);
return true;
}
}
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 ca970ce45f..4ee3605703 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
@@ -20,12 +20,11 @@
package org.openecomp.sdc.be.ecomp.converters;
+import org.openecomp.portalsdk.core.restful.domain.EcompRole;
import org.openecomp.sdc.be.user.Role;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.openecomp.portalsdk.core.restful.domain.EcompRole;
-
public final class EcompRoleConverter {
private static Logger log = LoggerFactory.getLogger(EcompRoleConverter.class.getName());
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 e83b53c2a4..19ef31feaf 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
@@ -24,13 +24,12 @@ import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
+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 org.openecomp.portalsdk.core.restful.domain.EcompRole;
-import org.openecomp.portalsdk.core.restful.domain.EcompUser;
-
import fj.data.Either;
public final class EcompUserConverter {
@@ -38,13 +37,6 @@ public final class EcompUserConverter {
private EcompUserConverter() {
}
- // private static final EcompUserConverter instance = new
- // EcompUserConverter();
-
- /*
- * public static EcompUserConverter getInsatnce() { return instance; }
- */
-
public static Either<EcompUser, String> convertUserToEcompUser(User asdcUser) {
EcompUser convertedUser = new EcompUser();
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 ecdce79b29..ec1a460417 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
@@ -40,11 +40,12 @@ import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
+import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum;
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.model.ArtifactDefinition;
-import org.openecomp.sdc.be.servlets.BeGenericServlet;
+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;
@@ -71,12 +72,14 @@ import fj.data.Either;
@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
@Path("/v1/catalog")
@Singleton
-public class ArtifactExternalServlet extends BeGenericServlet {
+public class ArtifactExternalServlet extends AbstractValidationsServlet {
@Context
private HttpServletRequest request;
private static Logger log = LoggerFactory.getLogger(ArtifactExternalServlet.class.getName());
+
+ private static String startLog = "Start handle request of ";
/**
* Uploads an artifact to resource or service
@@ -92,60 +95,58 @@ public class ArtifactExternalServlet extends BeGenericServlet {
@ApiResponses(value = { @ApiResponse(code = 200, message = "Artifact uploaded"), @ApiResponse(code = 401, message = "Authorization required"), @ApiResponse(code = 403, message = "Restricted operation"),
@ApiResponse(code = 404, message = "Asset not found") })
public Response uploadArtifact(@PathParam("assetType") final String assetType, @PathParam("uuid") final String uuid, @ApiParam(value = "json describe the artifact", required = true) String data) {
-
- Wrapper<Response> responseWrapper = new Wrapper<>();
- ResponseFormat responseFormat = null;
+ init(log);
+
+ Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
String instanceIdHeader = request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER);
String requestURI = request.getRequestURI();
String userId = request.getHeader(Constants.USER_ID_HEADER);
String url = request.getMethod() + " " + requestURI;
- log.debug("Start handle request of {}", url);
+ 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);
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
- responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
+ responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
}
- EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class);
-
- if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {
- log.debug("uploadArtifact: Missing X-ECOMP-InstanceID header");
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
- getComponentsUtils().auditExternalUploadArtifact(responseFormat, componentType.getValue(), request, additionalParams);
- responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
+ if (responseWrapper.isEmpty()) {
+ validateXECOMPInstanceIDHeader(instanceIdHeader, responseWrapper);
}
- if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) {
- log.debug("uploadArtifact: Missing USER_ID header");
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.COMPONENT_MISSING_CONTACT);
- getComponentsUtils().auditExternalUploadArtifact(responseFormat, componentType.getValue(), request, additionalParams);
- responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
+ if (responseWrapper.isEmpty() ) {
+ validateHttpCspUserIdHeader(userId, responseWrapper);
}
- if (responseWrapper.isEmpty()) {
- try {
+ 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);
+ 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");
- responseFormat = uploadArtifactEither.right().value();
- getComponentsUtils().auditExternalUploadArtifact(responseFormat, componentType.getValue(), request, additionalParams);
- responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
+ 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.calculateMD5ByString((String) representation));
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
- getComponentsUtils().auditExternalUploadArtifact(responseFormat, componentType.getValue(), request, additionalParams);
- responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers));
+ responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.OK));
+ response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers);
}
- } catch (Exception e) {
- final String message = "failed to upload artifact to a resource or service";
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
- log.debug(message, e);
- responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
+ }
+ 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);
}
- return responseWrapper.getInnerElement();
}
/**
@@ -171,51 +172,51 @@ public class ArtifactExternalServlet extends BeGenericServlet {
String requestURI = request.getRequestURI();
String userId = request.getHeader(Constants.USER_ID_HEADER);
String url = request.getMethod() + " " + requestURI;
- log.debug("Start handle request of {}", url);
+ 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));
}
- EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class);
-
if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {
log.debug("uploadArtifact: Missing X-ECOMP-InstanceID header");
responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
- getComponentsUtils().auditExternalUploadArtifact(responseFormat, componentType.getValue(), request, additionalParams);
responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
}
if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) {
log.debug("uploadArtifact: Missing USER_ID header");
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.COMPONENT_MISSING_CONTACT);
- getComponentsUtils().auditExternalUploadArtifact(responseFormat, componentType.getValue(), request, additionalParams);
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID);
responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
}
- if (responseWrapper.isEmpty()) {
- try {
+ 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);
+ 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();
- getComponentsUtils().auditExternalUploadArtifact(responseFormat, componentType.getValue(), request, additionalParams);
responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
} else {
Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value());
Map<String, String> headers = new HashMap<>();
headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5ByString((String) representation));
responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
- getComponentsUtils().auditExternalUploadArtifact(responseFormat, componentType.getValue(), request, additionalParams);
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)));
- }
+ }
+ }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();
}
@@ -243,52 +244,51 @@ public class ArtifactExternalServlet extends BeGenericServlet {
String requestURI = request.getRequestURI();
String userId = request.getHeader(Constants.USER_ID_HEADER);
String url = request.getMethod() + " " + requestURI;
- log.debug("Start handle request of {}", url);
+ 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));
}
- EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class);
-
- // Mandatory
if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {
log.debug("updateArtifact: Missing X-ECOMP-InstanceID header");
responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
- getComponentsUtils().auditExternalUpdateArtifact(responseFormat, componentType.getValue(), request, additionalParams);
responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
}
if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) {
- log.debug("updateArtifact: Missing USER_ID header");
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.COMPONENT_MISSING_CONTACT);
- getComponentsUtils().auditExternalUpdateArtifact(responseFormat, componentType.getValue(), request, additionalParams);
+ log.debug("updateArtifact: Missing USER_ID");
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID);
responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
}
- if (responseWrapper.isEmpty()) {
- try {
+ 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);
+ 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();
- getComponentsUtils().auditExternalUpdateArtifact(responseFormat, componentType.getValue(), request, additionalParams);
responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
} else {
Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value());
Map<String, String> headers = new HashMap<>();
headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5ByString((String) representation));
responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
- getComponentsUtils().auditExternalUpdateArtifact(responseFormat, componentType.getValue(), request, additionalParams);
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)));
}
+ } 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();
}
@@ -317,51 +317,52 @@ public class ArtifactExternalServlet extends BeGenericServlet {
String requestURI = request.getRequestURI();
String userId = request.getHeader(Constants.USER_ID_HEADER);
String url = request.getMethod() + " " + requestURI;
- log.debug("Start handle request of {}", url);
+ 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));
}
- EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class);
-
if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {
log.debug("updateArtifactOnResourceInstance: Missing X-ECOMP-InstanceID header");
responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
- getComponentsUtils().auditExternalUpdateArtifact(responseFormat, componentType.getValue(), request, additionalParams);
responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
}
if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) {
log.debug("updateArtifactOnResourceInstance: Missing USER_ID header");
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.COMPONENT_MISSING_CONTACT);
- getComponentsUtils().auditExternalUpdateArtifact(responseFormat, componentType.getValue(), request, additionalParams);
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID);
responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
}
- if (responseWrapper.isEmpty()) {
- try {
+ 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);
+ 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();
- getComponentsUtils().auditExternalUpdateArtifact(responseFormat, componentType.getValue(), request, additionalParams);
responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
} else {
Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value());
Map<String, String> headers = new HashMap<>();
headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5ByString((String) representation));
responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
- getComponentsUtils().auditExternalUpdateArtifact(responseFormat, componentType.getValue(), request, additionalParams);
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)));
}
+ } 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();
}
@@ -383,57 +384,56 @@ public class ArtifactExternalServlet extends BeGenericServlet {
public Response deleteArtifact(@PathParam("assetType") final String assetType, @PathParam("uuid") final String uuid, @PathParam("artifactUUID") final String artifactUUID) {
Wrapper<Response> responseWrapper = new Wrapper<>();
- ResponseFormat responseFormat;
+ ResponseFormat responseFormat = null;
String instanceIdHeader = request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER);
String userId = request.getHeader(Constants.USER_ID_HEADER);
String requestURI = request.getRequestURI();
String url = request.getMethod() + " " + requestURI;
- log.debug("Start handle request of {}", url);
-
+ 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));
}
- EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class);
-
if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {
log.debug("deleteArtifact: Missing X-ECOMP-InstanceID header");
responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
- getComponentsUtils().auditExternalDeleteArtifact(responseFormat, componentType.getValue(), request, additionalParams);
responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
}
if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) {
log.debug("deleteArtifact: Missing USER_ID header");
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.COMPONENT_MISSING_CONTACT);
- getComponentsUtils().auditExternalDeleteArtifact(responseFormat, componentType.getValue(), request, additionalParams);
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID);
responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
}
- if (responseWrapper.isEmpty()) {
- try {
+ try {
+ if (responseWrapper.isEmpty()) {
ServletContext context = request.getSession().getServletContext();
ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
- Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsLogic.deleteArtifactOnComponentByUUID(request, componentType, uuid, artifactUUID, additionalParams);
+ 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();
- getComponentsUtils().auditExternalDeleteArtifact(responseFormat, componentType.getValue(), request, additionalParams);
responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
} else {
Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value());
Map<String, String> headers = new HashMap<>();
headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5ByString((String) representation));
responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
- getComponentsUtils().auditExternalDeleteArtifact(responseFormat, componentType.getValue(), request, additionalParams);
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)));
}
+ } 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();
}
@@ -456,57 +456,57 @@ public class ArtifactExternalServlet extends BeGenericServlet {
@PathParam("artifactUUID") final String artifactUUID) {
Wrapper<Response> responseWrapper = new Wrapper<>();
- ResponseFormat responseFormat;
+ ResponseFormat responseFormat = null;
String instanceIdHeader = request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER);
String userId = request.getHeader(Constants.USER_ID_HEADER);
String requestURI = request.getRequestURI();
String url = request.getMethod() + " " + requestURI;
- log.debug("Start handle request of {}", url);
-
+ 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));
}
- EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class);
-
if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {
log.debug("deleteArtifactOnResourceInsatnce: Missing X-ECOMP-InstanceID header");
responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
- getComponentsUtils().auditExternalDeleteArtifact(responseFormat, componentType.getValue(), request, additionalParams);
responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
}
if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) {
log.debug("deleteArtifactOnResourceInsatnce: Missing USER_ID header");
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.COMPONENT_MISSING_CONTACT);
- getComponentsUtils().auditExternalDeleteArtifact(responseFormat, componentType.getValue(), request, additionalParams);
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID);
responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
}
- if (responseWrapper.isEmpty()) {
- try {
+ 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);
+ 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();
- getComponentsUtils().auditExternalDeleteArtifact(responseFormat, componentType.getValue(), request, additionalParams);
responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
} else {
Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value());
Map<String, String> headers = new HashMap<>();
headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5ByString((String) representation));
responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
- getComponentsUtils().auditExternalDeleteArtifact(responseFormat, componentType.getValue(), request, additionalParams);
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)));
- }
+ }
+ } 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();
}
@@ -530,33 +530,32 @@ public class ArtifactExternalServlet extends BeGenericServlet {
@PathParam("uuid") final String uuid, @PathParam("artifactUUID") final String artifactUUID) {
Wrapper<Response> responseWrapper = new Wrapper<>();
- ResponseFormat responseFormat;
+ ResponseFormat responseFormat = null;
String instanceIdHeader = request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER);
String requestURI = request.getRequestURI();
String url = request.getMethod() + " " + requestURI;
- log.debug("Start handle request of {}", url);
+ 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));
}
- EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<>(AuditingFieldsKeysEnum.class);
-
if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {
log.debug("downloadComponentArtifact: Missing X-ECOMP-InstanceID header");
responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
- getComponentsUtils().auditExternalDownloadArtifact(responseFormat, componentType.getValue(), request, additionalParam);
responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
}
- if (responseWrapper.isEmpty()) {
- try {
+ try {
+ if (responseWrapper.isEmpty()) {
ServletContext context = request.getSession().getServletContext();
ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
- Either<byte[], ResponseFormat> downloadComponentArtifactEither = artifactsLogic.downloadComponentArtifactByUUIDs(componentType, uuid, artifactUUID, additionalParam);
+ Either<byte[], ResponseFormat> downloadComponentArtifactEither = artifactsLogic.downloadComponentArtifactByUUIDs(componentType, uuid, artifactUUID, additionalParams);
if (downloadComponentArtifactEither.isRight()) {
responseFormat = downloadComponentArtifactEither.right().value();
- getComponentsUtils().auditExternalDownloadArtifact(responseFormat, componentType.getValue(), request, additionalParam);
responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
} else {
byte[] value = downloadComponentArtifactEither.left().value();
@@ -564,15 +563,16 @@ public class ArtifactExternalServlet extends BeGenericServlet {
Map<String, String> headers = new HashMap<>();
headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5ByByteArray(value));
responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
- getComponentsUtils().auditExternalDownloadArtifact(responseFormat, componentType.getValue(), request, additionalParam);
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)));
}
+ } 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();
}
@@ -597,33 +597,33 @@ public class ArtifactExternalServlet extends BeGenericServlet {
@PathParam("uuid") final String uuid, @PathParam("resourceInstanceName") final String resourceInstanceName, @PathParam("artifactUUID") final String artifactUUID) {
Wrapper<Response> responseWrapper = new Wrapper<>();
- ResponseFormat responseFormat;
+ ResponseFormat responseFormat = null;
String instanceIdHeader = request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER);
String requestURI = request.getRequestURI();
String url = request.getMethod() + " " + requestURI;
- log.debug("Start handle request of {}", url);
+ 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));
}
- EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<>(AuditingFieldsKeysEnum.class);
-
if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {
log.debug("downloadResourceInstanceArtifact: Missing X-ECOMP-InstanceID header");
responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
- getComponentsUtils().auditExternalDownloadArtifact(responseFormat, componentType.getValue(), request, additionalParam);
responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
}
- if (responseWrapper.isEmpty()) {
- try {
+ try {
+ if (responseWrapper.isEmpty()) {
ServletContext context = request.getSession().getServletContext();
ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
- Either<byte[], ResponseFormat> downloadResourceArtifactEither = artifactsLogic.downloadResourceInstanceArtifactByUUIDs(componentType, uuid, resourceInstanceName, artifactUUID, additionalParam);
+ Either<byte[], ResponseFormat> downloadResourceArtifactEither = artifactsLogic.downloadResourceInstanceArtifactByUUIDs(componentType, uuid, resourceInstanceName, artifactUUID, additionalParams);
if (downloadResourceArtifactEither.isRight()) {
responseFormat = downloadResourceArtifactEither.right().value();
- getComponentsUtils().auditExternalDownloadArtifact(responseFormat, componentType.getValue(), request, additionalParam);
responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
} else {
byte[] value = downloadResourceArtifactEither.left().value();
@@ -631,15 +631,16 @@ public class ArtifactExternalServlet extends BeGenericServlet {
Map<String, String> headers = new HashMap<>();
headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5ByByteArray(value));
responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
- getComponentsUtils().auditExternalDownloadArtifact(responseFormat, componentType.getValue(), request, additionalParam);
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)));
}
+ } 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/AssetMetadataConverter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/AssetMetadataConverter.java
index 662399142e..2c7de7032c 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/AssetMetadataConverter.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/AssetMetadataConverter.java
@@ -26,9 +26,10 @@ import java.util.LinkedList;
import java.util.List;
import java.util.Map;
+import org.apache.commons.collections.MapUtils;
+import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
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;
@@ -44,7 +45,7 @@ import org.openecomp.sdc.be.model.ComponentInstance;
import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.Service;
import org.openecomp.sdc.be.model.category.CategoryDefinition;
-import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.ResourceOperation;
import org.openecomp.sdc.exception.ResponseFormat;
@@ -60,8 +61,9 @@ public class AssetMetadataConverter {
@Autowired
private ComponentsUtils componentsUtils;
+
@Autowired
- private ResourceOperation resourceOperation;
+ 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()
@@ -70,19 +72,13 @@ public class AssetMetadataConverter {
if (componentList == null || componentList.isEmpty()) {
return Either.left(new LinkedList<>());
}
-
List<AssetMetadata> retResList = new LinkedList<>();
- Component component = componentList.iterator().next();
- ComponentTypeEnum componentType = component.getComponentType();
for (Component curr : componentList) {
-
- Either<? extends AssetMetadata, ResponseFormat> resMetaData = convertToMetadata(componentType, serverBaseURL, detailed, curr);
-
+ Either<? extends AssetMetadata, ResponseFormat> resMetaData = convertToSingleAssetMetadata(curr, serverBaseURL, detailed);
if (resMetaData.isRight()) {
return Either.right(resMetaData.right().value());
}
-
retResList.add(resMetaData.left().value());
}
@@ -90,6 +86,19 @@ public class AssetMetadataConverter {
}
+ 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) {
@@ -188,12 +197,12 @@ public class AssetMetadataConverter {
private <T extends ResourceAssetMetadata> T convertToResourceMetadata(T assetToPopulate, Resource resource, String serverBaseURL, boolean detailed) {
assetToPopulate = convertToAsset(assetToPopulate, resource, serverBaseURL, detailed);
- CategoryDefinition categoryDefinition = resource.getCategories().iterator().next();
- assetToPopulate.setCategory(categoryDefinition.getName());
-
- SubCategoryDefinition subCategoryDefinition = categoryDefinition.getSubcategories().iterator().next();
-
- assetToPopulate.setSubCategory(subCategoryDefinition.getName());
+ CategoryDefinition categoryDefinition;
+ if(resource.getCategories() != null && !resource.getCategories().isEmpty()){
+ categoryDefinition = resource.getCategories().iterator().next();
+ assetToPopulate.setCategory(categoryDefinition.getName());
+ assetToPopulate.setSubCategory(categoryDefinition.getSubcategories().iterator().next().getName());
+ }
assetToPopulate.setResourceType(resource.getResourceType().name());
assetToPopulate.setLifecycleState(resource.getLifecycleState().name());
assetToPopulate.setLastUpdaterUserId(resource.getLastUpdaterUserId());
@@ -232,7 +241,7 @@ public class AssetMetadataConverter {
assetToPopulate.setLastUpdaterFullName(resource.getLastUpdaterFullName());
assetToPopulate.setToscaResourceName(resource.getToscaResourceName());
-
+ assetToPopulate.setDescription(resource.getDescription());
return Either.left(assetToPopulate);
}
@@ -276,9 +285,8 @@ public class AssetMetadataConverter {
}
private List<ArtifactMetadata> populateAssetWithArtifacts(Component component, Map<String, ArtifactDefinition> artifacts) {
- List<ArtifactMetadata> artifactMetaList = null;
- if (artifacts != null) {
- artifactMetaList = new LinkedList<>();
+ List<ArtifactMetadata> artifactMetaList = new LinkedList<>();
+ if (artifacts != null) {
Collection<ArtifactDefinition> artefactDefList = artifacts.values();
for (ArtifactDefinition artifactDefinition : artefactDefList) {
@@ -292,11 +300,11 @@ public class AssetMetadataConverter {
}
private ArtifactMetadata convertToArtifactMetadata(ArtifactDefinition artifact, String componentType, String componentUUID, String resourceInstanceName) {
- // /asdc/v1/catalog/{services/resources}/{componentUUID}/artifacts/{artifactUUID}
- final String COMPONENT_ARTIFACT_URL = "/asdc/v1/catalog/%s/%s/artifacts/%s";
+ // /sdc/v1/catalog/{services/resources}/{componentUUID}/artifacts/{artifactUUID}
+ final String COMPONENT_ARTIFACT_URL = "/sdc/v1/catalog/%s/%s/artifacts/%s";
- // /asdc/v1/catalog/{services/resources}/{componentUUID}/resourceInstances/{resourceInstanceName}/artifacts/{artifactUUID}
- final String RESOURCE_INSTANCE_ARTIFACT_URL = "/asdc/v1/catalog/%s/%s/resourceInstances/%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();
@@ -315,52 +323,55 @@ public class AssetMetadataConverter {
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, String> uuidDuplicatesMap = new HashMap<>();
+ Map<String, ImmutablePair<String, String>> uuidDuplicatesMap = new HashMap<>();
for (ComponentInstance componentInstance : componentInstances) {
ResourceInstanceMetadata metadata = new ResourceInstanceMetadata();
String componentUid = componentInstance.getComponentUid();
- String invariantUUID;
+ String invariantUUID, resourceUUID;
if (!uuidDuplicatesMap.containsKey(componentUid)) {
- Either<String, StorageOperationStatus> getInvarUuidresponse = resourceOperation.getInvariantUUID(NodeTypeEnum.Resource, componentInstance.getComponentUid(), false);
- if (getInvarUuidresponse.isRight()) {
- log.debug("convertToResourceInstanceMetadata: Failed getting Invariant UUID");
- return Either.right(getInvarUuidresponse.right().value());
+ 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 {
- invariantUUID = getInvarUuidresponse.left().value();
- uuidDuplicatesMap.put(componentUid, invariantUUID);
+ 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);
+ 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.setResourceType(componentInstance.getOriginType().getValue());
- metadata.setResourceUUID(componentInstance.getComponentUid());
-
- Collection<ArtifactDefinition> values = componentInstance.getDeploymentArtifacts().values();
- LinkedList<ArtifactMetadata> artifactMetaList = new LinkedList<>();
-
- for (ArtifactDefinition artifactDefinition : values) {
- ArtifactMetadata converted = convertToArtifactMetadata(artifactDefinition, componentType, componentUUID, componentInstance.getNormalizedName());
- artifactMetaList.add(converted);
+ 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);
}
-
- metadata.setArtifacts(artifactMetaList);
-
retList.add(metadata);
}
-
return Either.left(retList);
}
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 1b8d6fdb75..552ad163ec 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
@@ -21,19 +21,23 @@
package org.openecomp.sdc.be.externalapi.servlet;
import java.io.ByteArrayInputStream;
+import java.io.IOException;
import java.io.InputStream;
-import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import java.util.function.Predicate;
+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.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;
@@ -42,27 +46,50 @@ import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
+import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.apache.http.NameValuePair;
+import org.codehaus.jackson.JsonGenerationException;
+import org.codehaus.jackson.map.JsonMappingException;
+import org.codehaus.jackson.map.ObjectMapper;
+import org.elasticsearch.common.Strings;
+import org.json.simple.JSONObject;
+import org.json.simple.parser.JSONParser;
import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic;
import org.openecomp.sdc.be.components.impl.ElementBusinessLogic;
+import org.openecomp.sdc.be.components.impl.ImportUtils;
+import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic;
+import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
+import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoBase;
+import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.datamodel.api.CategoryTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.AssetTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
import org.openecomp.sdc.be.externalapi.servlet.representation.AssetMetadata;
-import org.openecomp.sdc.be.impl.WebAppContextWrapper;
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.category.CategoryDefinition;
+import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
-import org.openecomp.sdc.be.servlets.BeGenericServlet;
+import org.openecomp.sdc.be.servlets.AbstractValidationsServlet;
import org.openecomp.sdc.be.servlets.RepresentationUtils;
+import org.openecomp.sdc.be.utils.CommonBeUtils;
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.datastructure.Wrapper;
import org.openecomp.sdc.common.util.GeneralUtility;
+import org.openecomp.sdc.common.util.ValidationUtils;
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 com.wordnik.swagger.annotations.ApiOperation;
@@ -75,12 +102,11 @@ import fj.data.Either;
@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
@Path("/v1/catalog")
@Singleton
-public class AssetsDataServlet extends BeGenericServlet {
+public class AssetsDataServlet extends AbstractValidationsServlet {
@Context
private HttpServletRequest request;
- private AssetMetadataConverter assetMetadataUtils;
private static Logger log = LoggerFactory.getLogger(AssetsDataServlet.class.getName());
@GET
@@ -89,7 +115,8 @@ public class AssetsDataServlet extends BeGenericServlet {
@ApiOperation(value = "Fetch list of assets", httpMethod = "GET", notes = "Returns list of assets", response = Response.class)
@ApiResponses(value = { @ApiResponse(code = 200, message = "Assets Fetched"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), @ApiResponse(code = 401, message = "Authorization required"),
@ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Asset not found") })
- public Response getAssetList(@PathParam("assetType") final String assetType, @QueryParam("category") String category, @QueryParam("subCategory") String subCategory, @QueryParam("distributionStatus") String distributionStatus) {
+ public Response getAssetList(@PathParam("assetType") final String assetType, @QueryParam("category") String category, @QueryParam("subCategory") String subCategory, @QueryParam("distributionStatus") String distributionStatus,
+ @QueryParam("resourceType") String resourceType) {
Response response = null;
ResponseFormat responseFormat = null;
@@ -98,8 +125,7 @@ public class AssetsDataServlet extends BeGenericServlet {
String requestURI = request.getRequestURI();
String url = request.getMethod() + " " + requestURI;
log.debug("Start handle request of {}", url);
- String serverBaseURL = request.getRequestURL().toString();
-
+
AuditingActionEnum auditingActionEnum = query == null ? AuditingActionEnum.GET_ASSET_LIST : AuditingActionEnum.GET_FILTERED_ASSET_LIST;
EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
@@ -118,7 +144,7 @@ public class AssetsDataServlet extends BeGenericServlet {
ServletContext context = request.getSession().getServletContext();
ElementBusinessLogic elementLogic = getElementBL(context);
- getAssetUtils(context);
+ AssetMetadataConverter assetMetadataUtils = getAssetUtils(context);
Map<FilterKeyEnum, String> filters = new HashMap<FilterKeyEnum, String>();
if (category != null) {
@@ -130,6 +156,16 @@ public class AssetsDataServlet extends BeGenericServlet {
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);
@@ -140,7 +176,7 @@ public class AssetsDataServlet extends BeGenericServlet {
return buildErrorResponse(responseFormat);
} else {
log.debug("getAssetList: Asset Fetching Success");
- Either<List<? extends AssetMetadata>, ResponseFormat> resMetadata = assetMetadataUtils.convertToAssetMetadata(assetTypeData.left().value(), serverBaseURL, false);
+ 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();
@@ -176,7 +212,6 @@ public class AssetsDataServlet extends BeGenericServlet {
String requestURI = request.getRequestURI();
String url = request.getMethod() + " " + requestURI;
log.debug("Start handle request of {}", url);
- String serverBaseURL = request.getRequestURL().toString();
EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
@@ -196,7 +231,7 @@ public class AssetsDataServlet extends BeGenericServlet {
try {
ServletContext context = request.getSession().getServletContext();
ElementBusinessLogic elementLogic = getElementBL(context);
- getAssetUtils(context);
+ AssetMetadataConverter assetMetadataUtils = getAssetUtils(context);
Either<List<? extends Component>, ResponseFormat> assetTypeData = elementLogic.getCatalogComponentsByUuidAndAssetType(assetType, uuid);
@@ -209,7 +244,7 @@ public class AssetsDataServlet extends BeGenericServlet {
} 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(), serverBaseURL, true);
+ 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();
@@ -230,12 +265,6 @@ public class AssetsDataServlet extends BeGenericServlet {
}
}
- private void getAssetUtils(ServletContext context) {
- WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
- WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
- assetMetadataUtils = webApplicationContext.getBean(AssetMetadataConverter.class);
- }
-
@GET
@Path("/{assetType}/{uuid}/toscaModel")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@@ -297,4 +326,438 @@ public class AssetsDataServlet extends BeGenericServlet {
return response;
}
}
+
+ /**
+ * Creates a new Resource
+ *
+ * @param assetType
+ * @param data
+ * @return
+ */
+ @POST
+ @Path("/{assetType}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "creates a resource", httpMethod = "POST", notes = "creates a resource", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Artifact uploaded"),
+ @ApiResponse(code = 401, message = "Authorization required"),
+ @ApiResponse(code = 403, message = "Restricted operation"),
+ @ApiResponse(code = 201, message = "Resource created"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
+ @ApiResponse(code = 409, message = "Resource already exist") })
+ public Response createResource(@PathParam("assetType") final String assetType, @ApiParam(value = "json describe the artifact", required = true) String data) {
+ init(log);
+
+ Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
+ String requestURI = request.getRequestURI();
+ String userId = request.getHeader(Constants.USER_ID_HEADER);
+ 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(request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER),
+ 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);
+ }
+ }
+
+ 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);
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
+ 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));
+ }
+
+ }
+ }
+
+
+ /**
+ * 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
+ * @return
+ */
+ @POST
+ @Path("/{assetType}/{uuid}/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 = "Asset is already checked-out by another user")})
+ public Response changeResourceState(@ApiParam(value = "LifecycleChangeInfo - relevant for checkin", required = false) String jsonChangeInfo,
+ @ApiParam(value = "validValues: resources / services ", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam(value = "assetType") final String assetType,
+ @ApiParam(value = "id of component to be changed") @PathParam(value = "uuid") final String uuid,
+ @ApiParam(allowableValues = "checkout, checkin", required = true) @PathParam(value = "lifecycleOperation") final String lifecycleTransition) {
+ 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;
+ String userId = request.getHeader(Constants.USER_ID_HEADER);
+
+ try{
+ 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 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);
+ }
+
}
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 f4194cf2f5..15ebceaa5d 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
@@ -30,7 +30,9 @@ public class ArtifactMetadata {
private String artifactUUID;
private String artifactVersion;
private String generatedFromUUID;
-
+ private String artifactLabel;
+ private String artifactGroupType;
+
public String getArtifactName() {
return artifactName;
}
@@ -103,4 +105,20 @@ public class ArtifactMetadata {
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/ResourceAssetDetailedMetadata.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceAssetDetailedMetadata.java
index ea282ec2e8..0952feea05 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
@@ -28,6 +28,7 @@ public class ResourceAssetDetailedMetadata extends ResourceAssetMetadata {
private String toscaResourceName;
private List<ResourceInstanceMetadata> resources;
private List<ArtifactMetadata> artifacts;
+ private String description;
public String getLastUpdaterFullName() {
return lastUpdaterFullName;
@@ -60,4 +61,13 @@ public class ResourceAssetDetailedMetadata extends ResourceAssetMetadata {
public void setArtifacts(List<ArtifactMetadata> artifactMetaList) {
this.artifacts = artifactMetaList;
}
+
+ 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/externalapi/servlet/representation/ResourceInstanceMetadata.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceInstanceMetadata.java
index 547bb301f8..a53422f311 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
@@ -27,7 +27,7 @@ public class ResourceInstanceMetadata {
private String resourceName;
private String resourceInvariantUUID;
private String resourceVersion;
- private String resourceType;
+ private String resoucreType;
private String resourceUUID;
private List<ArtifactMetadata> artifacts;
@@ -63,12 +63,12 @@ public class ResourceInstanceMetadata {
this.resourceVersion = resourceVersion;
}
- public String getResourceType() {
- return resourceType;
+ public String getResoucreType() {
+ return resoucreType;
}
- public void setResourceType(String resourceType) {
- this.resourceType = resourceType;
+ public void setResoucreType(String resoucreType) {
+ this.resoucreType = resoucreType;
}
public String getResourceUUID() {
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 f7e1d758ac..de95790f4e 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
@@ -77,7 +77,7 @@ public class BasicAuthenticationFilter implements ContainerRequestFilter {
if (basic.equalsIgnoreCase("Basic")) {
try {
String credentials = new String(Base64.decodeBase64(st.nextToken()), "UTF-8");
- log.debug("Credentials: {}", credentials);
+ log.debug("Credentials: {}" , credentials);
checkUserCredentiles(requestContext, credentials);
} catch (UnsupportedEncodingException e) {
log.error("Authentication Filter Failed Couldn't retrieve authentication", e);
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 f6c11d062e..d24743534c 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
@@ -38,6 +38,7 @@ import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.Configuration;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.impl.WebAppContextWrapper;
import org.openecomp.sdc.common.api.Constants;
@@ -115,6 +116,17 @@ public class BeServletFilter implements ContainerRequestFilter, ContainerRespons
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();
@@ -126,7 +138,7 @@ public class BeServletFilter implements ContainerRequestFilter, ContainerRespons
}
private String processMdcFields(ContainerRequestContext requestContext) {
- // userId for logging
+ // UserId for logging
String userId = requestContext.getHeaderString(Constants.USER_ID_HEADER);
MDC.put("userId", userId);
@@ -165,7 +177,13 @@ public class BeServletFilter implements ContainerRequestFilter, ContainerRespons
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()) {
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 9e2abebdc5..ea2582cd1b 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
@@ -41,9 +41,9 @@ import org.openecomp.sdc.be.components.impl.ResponseFormatManager;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.dao.graph.datatype.AdditionalInformationEnum;
+import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterInfo;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.model.AdditionalInfoParameterInfo;
import org.openecomp.sdc.be.model.ArtifactDefinition;
import org.openecomp.sdc.be.model.CapabilityTypeDefinition;
import org.openecomp.sdc.be.model.Component;
@@ -454,51 +454,57 @@ public class ComponentsUtils {
getAuditingManager().auditEvent(auditingFields);
}
- public void auditExternalCrudApiArtifact(ResponseFormat responseFormat, String componentType, String actionEnum, HttpServletRequest request, EnumMap<AuditingFieldsKeysEnum, Object> additionalParams) {
+ 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();
- int status = responseFormat.getStatus();
- String message = "";
EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
- if (responseFormat.getMessageId() != null) {
- message = responseFormat.getMessageId() + ": ";
+ int status = 0;
+ String message = "";
+ if(responseFormat != null){
+ status = responseFormat.getStatus();
+ if (responseFormat.getMessageId() != null) {
+ message = responseFormat.getMessageId() + ": ";
+ }
+ message += responseFormat.getFormattedMessage();
}
- 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) {
- auditExternalCrudApiArtifact(responseFormat, componentType, AuditingActionEnum.DOWNLOAD_ARTIFACT.getName(), request, 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, "");
- auditExternalCrudApiArtifact(responseFormat, componentType, AuditingActionEnum.ARTIFACT_UPLOAD_BY_API.getName(), request, additionalParams);
+ 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, "");
- auditExternalCrudApiArtifact(responseFormat, componentType, AuditingActionEnum.ARTIFACT_UPDATE_BY_API.getName(), request, additionalParams);
+ 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, "");
- auditExternalCrudApiArtifact(responseFormat, componentType, AuditingActionEnum.ARTIFACT_DELETE_BY_API.getName(), request, additionalParams);
+ 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) {
@@ -603,6 +609,9 @@ public class ComponentsUtils {
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;
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 fff6fd15a4..cfa108ed80 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
@@ -78,11 +78,8 @@ public class DownloadArtifactLogic {
String payloadStr = new String(artifactPayload);
byte[] decodedPayload = artifactPayload;
- boolean isEncoded = GeneralUtility.isBase64Encoded(payloadStr);
- if (isEncoded) {
- log.debug("payload is encoded. perform decode");
- decodedPayload = Base64.decode(new String(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 {
@@ -106,7 +103,7 @@ public class DownloadArtifactLogic {
} 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());
+ 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;
}
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 fca7bf38d8..fa051a9e3d 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
@@ -28,7 +28,7 @@ import java.util.Set;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.ConfigurationManager;
-import org.openecomp.sdc.be.config.Configuration.DeploymentArtifactTypeConfig;
+import org.openecomp.sdc.be.config.Configuration.ArtifactTypeConfig;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.impl.ComponentsUtils;
@@ -205,7 +205,7 @@ public class ArtifactTemplateInfo {
if (!artifactTypeExist) {
BeEcompErrorManager.getInstance().logBeInvalidTypeError("Artifact", "-Not supported artifact type ", correctType);
- log.debug("Not supported artifact type = {}", correctType);
+ log.debug("Not supported artifact type = {}" , correctType);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, correctType));
}
@@ -275,8 +275,8 @@ public class ArtifactTemplateInfo {
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())) {
- Either.left(true);
+ 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()));
}
@@ -285,7 +285,7 @@ public class ArtifactTemplateInfo {
}
if (parentArtifact.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType())) {
- Either.left(true);
+ return Either.left(true);
}
return Either.left(true);
}
@@ -324,7 +324,7 @@ public class ArtifactTemplateInfo {
private static Either<List<ArtifactType>, ActionStatus> getDeploymentArtifactTypes(NodeTypeEnum parentType) {
- Map<String, DeploymentArtifactTypeConfig> deploymentArtifacts = null;
+ Map<String, ArtifactTypeConfig> deploymentArtifacts = null;
List<ArtifactType> artifactTypes = new ArrayList<ArtifactType>();
if (parentType.equals(NodeTypeEnum.Service)) {
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 24d9c5644d..05af87d789 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,20 +20,19 @@
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.stream.Collectors;
-
-import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
import org.openecomp.sdc.be.model.GroupDefinition;
+import org.openecomp.sdc.be.model.GroupInstance;
+import org.openecomp.sdc.be.model.GroupProperty;
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.
@@ -46,12 +45,15 @@ public class GroupDefinitionInfo {
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();
@@ -63,6 +65,21 @@ public class GroupDefinitionInfo {
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());
+
}
@@ -105,6 +122,15 @@ public class GroupDefinitionInfo {
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;
@@ -121,10 +147,29 @@ public class GroupDefinitionInfo {
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 8471a801ac..4a7e925639 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
@@ -20,9 +20,6 @@
package org.openecomp.sdc.be.info;
-import java.util.List;
-import java.util.Map;
-
public class GroupTemplateInfo {
String groupName;
boolean isBase;
@@ -30,7 +27,6 @@ public class GroupTemplateInfo {
public GroupTemplateInfo() {
super();
- // TODO Auto-generated constructor stub
}
public String getGroupName() {
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 95038b1830..25b6b3564b 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
@@ -29,6 +29,8 @@ import java.util.Set;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.model.ArtifactDefinition;
+import java.util.Optional;
+
public class MergedArtifactInfo {
private List<ArtifactDefinition> createdArtifact;
@@ -70,7 +72,25 @@ public class MergedArtifactInfo {
public List<ArtifactDefinition> getListToDissotiateArtifactFromGroup(List<ArtifactDefinition> deletedArtifacts) {
List<ArtifactDefinition> resList = new ArrayList<ArtifactDefinition>();
for (ArtifactDefinition artifactDefinition : createdArtifact) {
- if (!parsetArtifactsNames.contains(artifactDefinition.getArtifactName())) {
+ 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())) {
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 d40a3d4433..38629ab7a1 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/listen/BEAppContextListener.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/listen/BEAppContextListener.java
@@ -29,6 +29,8 @@ import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
+import org.openecomp.portalsdk.core.onboarding.ueb.UebException;
+import org.openecomp.portalsdk.core.onboarding.ueb.UebManager;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
@@ -43,9 +45,6 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
-import org.openecomp.portalsdk.core.onboarding.ueb.UebException;
-import org.openecomp.portalsdk.core.onboarding.ueb.UebManager;
-
public class BEAppContextListener extends AppContextListener implements ServletContextListener {
private static final String MANIFEST_FILE_NAME = "/META-INF/MANIFEST.MF";
@@ -68,7 +67,7 @@ public class BEAppContextListener extends AppContextListener implements ServletC
DownloadArtifactLogic downloadArtifactLogic = new DownloadArtifactLogic();
context.getServletContext().setAttribute(Constants.DOWNLOAD_ARTIFACT_LOGIC_ATTR, downloadArtifactLogic);
- context.getServletContext().setAttribute(Constants.SDC_RELEASE_VERSION_ATTR, getVersionFromManifest(context));
+ context.getServletContext().setAttribute(Constants.ASDC_RELEASE_VERSION_ATTR, getVersionFromManifest(context));
// Monitoring service
BeMonitoringService bms = new BeMonitoringService(context.getServletContext());
@@ -115,7 +114,7 @@ public class BEAppContextListener extends AppContextListener implements ServletC
try {
Manifest mf = new Manifest(inputStream);
Attributes atts = mf.getMainAttributes();
- version = atts.getValue(Constants.SDC_RELEASE_VERSION_ATTR);
+ version = atts.getValue(Constants.ASDC_RELEASE_VERSION_ATTR);
if (version == null || version.isEmpty()) {
log.warn("failed to read ASDC version from MANIFEST.");
} else {
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 0e8addf692..d8f834c970 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
@@ -25,6 +25,7 @@ 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;
@@ -40,6 +41,7 @@ import javax.ws.rs.core.Response;
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;
@@ -92,7 +94,6 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
@Autowired
protected ComponentsUtils componentsUtils;
- private static final Object LOCK = new Object();
private Logger log = null;
protected void init(Logger log) {
@@ -101,28 +102,20 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
}
- private void initLog(Logger log) {
+ private synchronized void initLog(Logger log) {
if (this.log == null) {
- synchronized (LOCK) {
- if (this.log == null) {
- this.log = log;
- }
-
- }
+ this.log = log;
}
}
- private void initSpringFromContext() {
+ private synchronized void initSpringFromContext() {
if (servletUtils == null) {
- synchronized (LOCK) {
- 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);
- }
- }
+ 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);
}
}
@@ -137,10 +130,10 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
}
}
- protected void validateUserExist(Wrapper<Response> responseWrapper, Wrapper<User> userWrapper, String userId) {
- log.debug("get user {} from DB", userId);
+ protected void validateUserExist(Wrapper<Response> responseWrapper, Wrapper<User> userWrapper, String userUserId) {
+ log.debug("get user {} from DB", userUserId);
// get user details
- if (userId == null) {
+ if (userUserId == null) {
log.info("user userId is null");
Response response = returnMissingInformation(new User());
responseWrapper.setInnerElement(response);
@@ -148,11 +141,11 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
else {
IUserBusinessLogic userAdmin = getServletUtils().getUserAdmin();
- Either<User, ActionStatus> eitherCreator = userAdmin.getUser(userId, false);
+ Either<User, ActionStatus> eitherCreator = userAdmin.getUser(userUserId, false);
if (eitherCreator.isRight()) {
- log.info("user is not listed. userId={}", userId);
+ log.info("user is not listed. userId={}", userUserId);
User user = new User();
- user.setUserId(userId);
+ user.setUserId(userUserId);
Response response = returnMissingInformation(user);
responseWrapper.setInnerElement(response);
} else {
@@ -203,6 +196,16 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
}
}
+ 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);
@@ -219,6 +222,33 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
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");
@@ -248,7 +278,7 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
} else {
if (!resourceAuthorityEnum.isBackEndImport()) {
isValid = resourceInfoObject.getPayloadName() != null && !resourceInfoObject.getPayloadName().isEmpty();
- // TODO Tal only resource name is checked
+ //Tal only resource name is checked
} else {
isValid = true;
}
@@ -256,6 +286,7 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
}
} catch (JsonSyntaxException e) {
+ log.debug("Invalid json was received. {}", e.getMessage(), e);
isValid = false;
}
@@ -294,8 +325,7 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
protected void validatePayloadIsTosca(Wrapper<Response> responseWrapper, UploadResourceInfo uploadResourceInfo, User user, String toscaPayload) {
log.debug("checking payload is valid tosca");
boolean isValid;
- String heatDecodedPayload = (GeneralUtility.isBase64Encoded(toscaPayload)) ? new String(Base64.decodeBase64(toscaPayload)) : toscaPayload;
- Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(heatDecodedPayload);
+ Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(toscaPayload);
Either<String, ResultStatusEnum> findFirstToscaStringElement = ImportUtils.findFirstToscaStringElement(mappedToscaTemplate, ToscaTagNamesEnum.TOSCA_VERSION);
if (findFirstToscaStringElement.isRight()) {
@@ -337,9 +367,7 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
protected void validatePayloadNameSpace(Wrapper<Response> responseWrapper, UploadResourceInfo resourceInfo, User user, String toscaPayload) {
boolean isValid;
String nameSpace = "";
-
- String heatDecodedPayload = (GeneralUtility.isBase64Encoded(toscaPayload)) ? new String(Base64.decodeBase64(toscaPayload)) : toscaPayload;
- Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(heatDecodedPayload);
+ 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;
@@ -357,7 +385,7 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
} else {
String str1 = nameSpace.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
String[] findTypes = str1.split("\\.");
- if (ResourceTypeEnum.contains(findTypes[0].toUpperCase())) {
+ if (ResourceTypeEnum.containsName(findTypes[0].toUpperCase())) {
String type = findTypes[0].toUpperCase();
resourceInfo.setResourceType(type);
} else {
@@ -370,8 +398,7 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
protected void validatePayloadIsSingleResource(Wrapper<Response> responseWrapper, UploadResourceInfo uploadResourceInfo, User user, String toscaPayload) {
log.debug("checking payload contains single resource");
boolean isValid;
- String heatDecodedPayload = (GeneralUtility.isBase64Encoded(toscaPayload)) ? new String(Base64.decodeBase64(toscaPayload)) : toscaPayload;
- Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(heatDecodedPayload);
+ 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;
@@ -392,8 +419,7 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
protected void validatePayloadIsNotService(Wrapper<Response> responseWrapper, User user, UploadResourceInfo uploadResourceInfo, String toscaPayload) {
log.debug("checking payload is not a tosca service");
- String heatDecodedPayload = (GeneralUtility.isBase64Encoded(toscaPayload)) ? new String(Base64.decodeBase64(toscaPayload)) : toscaPayload;
- Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(heatDecodedPayload);
+ 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()) {
@@ -406,24 +432,7 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
}
}
-
- protected void validatePayloadIsTopologyTemplate(Wrapper<Response> responseWrapper, User user, UploadResourceInfo uploadResourceInfo, String toscaPayload) {
- log.debug("checking payload is a tosca topology template");
- String heatDecodedPayload = (GeneralUtility.isBase64Encoded(toscaPayload)) ? new String(Base64.decodeBase64(toscaPayload)) : toscaPayload;
- Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(heatDecodedPayload);
- Either<Object, ResultStatusEnum> toscaElement = ImportUtils.findToscaElement(mappedToscaTemplate, ToscaTagNamesEnum.TOPOLOGY_TEMPLATE, ToscaElementTypeEnum.ALL);
-
- if (toscaElement.isRight()) {
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NOT_TOPOLOGY_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;
@@ -495,7 +504,7 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
responseWrapper.setInnerElement(errorResponse);
} else {
String toscaPayload = resourceInfo.getPayloadData();
- String decodedPayload = (GeneralUtility.isBase64Encoded(toscaPayload)) ? new String(Base64.decodeBase64(toscaPayload)) : toscaPayload;
+ String decodedPayload = new String(Base64.decodeBase64(toscaPayload));
yamlStringWrapper.setInnerElement(decodedPayload);
}
@@ -510,13 +519,26 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
if (responseWrapper.isEmpty()) {
validateDataNotNull(responseWrapper, file, resourceInfoJsonString);
}
- if (responseWrapper.isEmpty()) {
- validateZip(responseWrapper, file, uploadResourceInfoWrapper.getInnerElement().getPayloadName());
- }
-
- // Fill PayLoad From File
- if (responseWrapper.isEmpty()) {
- fillToscaTemplateFromZip(yamlStringWrapper, uploadResourceInfoWrapper.getInnerElement().getPayloadName(), file);
+ 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 {
@@ -548,12 +570,12 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
}
}
}
-
- protected void commonGeneralValidations(Wrapper<Response> responseWrapper, Wrapper<User> userWrapper, Wrapper<UploadResourceInfo> uploadResourceInfoWrapper, ResourceAuthorityTypeEnum resourceAuthorityEnum, String userId,
+
+ protected void commonGeneralValidations(Wrapper<Response> responseWrapper, Wrapper<User> userWrapper, Wrapper<UploadResourceInfo> uploadResourceInfoWrapper, ResourceAuthorityTypeEnum resourceAuthorityEnum, String userUserId,
String resourceInfoJsonString) {
if (responseWrapper.isEmpty()) {
- validateUserExist(responseWrapper, userWrapper, userId);
+ validateUserExist(responseWrapper, userWrapper, userUserId);
}
if (responseWrapper.isEmpty()) {
@@ -575,7 +597,7 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
private void validateResourceType(Wrapper<Response> responseWrapper, UploadResourceInfo uploadResourceInfo, User user) {
String resourceType = uploadResourceInfo.getResourceType();
- if (resourceType == null || !ResourceTypeEnum.contains(resourceType)) {
+ if (resourceType == null || !ResourceTypeEnum.containsName(resourceType)) {
ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
Response errorResponse = buildErrorResponse(responseFormat);
EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
@@ -610,7 +632,7 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
}
}
- protected void topologyTemplatePayloadValidations(Wrapper<Response> responseWrapper, Wrapper<String> yamlStringWrapper, User user, UploadResourceInfo uploadResourceInfo) {
+ /*protected void topologyTemplatePayloadValidations(Wrapper<Response> responseWrapper, Wrapper<String> yamlStringWrapper, User user, UploadResourceInfo uploadResourceInfo) {
if (responseWrapper.isEmpty()) {
validatePayloadIsYml(responseWrapper, user, uploadResourceInfo, yamlStringWrapper.getInnerElement());
@@ -622,16 +644,23 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
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 = null;
- Response response = null;
+ 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);
@@ -645,7 +674,7 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
try {
representation = RepresentationUtils.toRepresentation(createOrUpdateResponse.left().value().getLeft());
} catch (IOException e) {
- e.printStackTrace();
+ log.debug("Error while building resource representation : {}", e.getMessage(), e);
}
ActionStatus successStatus = createOrUpdateResponse.left().value().right;
response = buildOkResponse(getComponentsUtils().getResponseFormat(successStatus), representation);
@@ -655,9 +684,9 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
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 = null;
+ Either<org.openecomp.sdc.be.model.Resource, ResponseFormat> createOrUpdateResourceRes;
ImmutablePair<org.openecomp.sdc.be.model.Resource, ActionStatus> result = null;
- ActionStatus actionStatus = null;
+ ActionStatus actionStatus;
org.openecomp.sdc.be.model.Resource resource = new org.openecomp.sdc.be.model.Resource();
String payloadName = resourceInfoObject.getPayloadName();
fillResourceFromResourceInfoObject(resource, resourceInfoObject);
@@ -673,7 +702,7 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
return Either.right(createOrUpdateResourceRes.right().value());
}
if (resourceUniqueId == null || resourceUniqueId.isEmpty()) {
- createOrUpdateResourceRes = resourceImportManager.getResourceBusinessLogic().createResource(resource, user, csarUIPayload, payloadName);
+ createOrUpdateResourceRes = resourceImportManager.getResourceBusinessLogic().createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, csarUIPayload, payloadName);
if (createOrUpdateResourceRes.isRight()) {
return Either.right(createOrUpdateResourceRes.right().value());
}
@@ -714,7 +743,7 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
}
log.debug("checking payload is valid tosca");
- String heatDecodedPayload = (GeneralUtility.isBase64Encoded(toscaYaml)) ? new String(Base64.decodeBase64(toscaYaml)) : toscaYaml;
+ String heatDecodedPayload = toscaYaml;
Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(heatDecodedPayload);
Either<String, ResultStatusEnum> findFirstToscaStringElement = ImportUtils.findFirstToscaStringElement(mappedToscaTemplate, ToscaTagNamesEnum.TOSCA_VERSION);
@@ -775,8 +804,8 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
log.info("Failed to decode received csar", csarUUID);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_NOT_FOUND, csarUUID));
}
-
- byte[] decodedPayload = (GeneralUtility.isBase64Encoded(payloadData)) ? Base64.decodeBase64(payloadData.getBytes(StandardCharsets.UTF_8)) : payloadData.getBytes(StandardCharsets.UTF_8);
+
+ 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));
@@ -840,4 +869,59 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
}
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 aaf8f96dca..560ab7d023 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
@@ -39,9 +39,9 @@ import javax.ws.rs.core.Response;
import org.openecomp.sdc.be.components.impl.AdditionalInformationBusinessLogic;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterInfo;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.impl.WebAppContextWrapper;
-import org.openecomp.sdc.be.model.AdditionalInfoParameterInfo;
import org.openecomp.sdc.be.model.AdditionalInformationDefinition;
import org.openecomp.sdc.common.api.Constants;
import org.openecomp.sdc.common.config.EcompErrorName;
@@ -75,9 +75,9 @@ public class AdditionalInformationServlet extends BeGenericServlet {
@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 userId) {
+ @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, userId, data);
+ return createAdditionalInformationLabelForComponent(NodeTypeEnum.Resource, resourceId, request, userUserId, data);
}
@@ -89,9 +89,9 @@ public class AdditionalInformationServlet extends BeGenericServlet {
@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 userId) {
+ @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, userId, data);
+ return createAdditionalInformationLabelForComponent(NodeTypeEnum.Service, serviceId, request, userUserId, data);
}
@@ -240,7 +240,7 @@ public class AdditionalInformationServlet extends BeGenericServlet {
if (either.isRight()) {
ResponseFormat responseFormat = either.right().value();
- log.info("Failed to create additional information {}. REason - {}", additionalInfoParameterInfo, responseFormat);
+ log.info("Failed to create additional information {}. Reason - {}", additionalInfoParameterInfo, responseFormat);
return buildErrorResponse(responseFormat);
}
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 b7af00a7d2..b7fef4554f 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,6 +20,8 @@
package org.openecomp.sdc.be.servlets;
+import java.util.Map;
+
import javax.inject.Singleton;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
@@ -38,23 +40,18 @@ import javax.ws.rs.core.Response;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperation;
+import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum;
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.model.ArtifactDefinition;
import org.openecomp.sdc.be.model.ArtifactUiDownloadData;
import org.openecomp.sdc.be.model.Operation;
-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.exception.ResponseFormat;
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.jcabi.aspects.Loggable;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
@@ -75,8 +72,6 @@ public class ArtifactServlet extends BeGenericServlet {
private static Logger log = LoggerFactory.getLogger(ArtifactServlet.class.getName());
- private Gson gson = new Gson();
-
// *************** Resources
@POST
@Path("/resources/{resourceId}/artifacts")
@@ -88,11 +83,10 @@ public class ArtifactServlet extends BeGenericServlet {
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);
+ log.debug("Start handle request of {}" , url);
try {
return handleUploadRequest(data, request, resourceId, ComponentTypeEnum.RESOURCE);
- } catch (Throwable e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "loadArtifact");
+ } catch (Exception e) {
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("loadArtifact");
log.debug("loadArtifact unexpected exception", e);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -109,11 +103,10 @@ public class ArtifactServlet extends BeGenericServlet {
@Context final HttpServletRequest request) {
String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
+ log.debug("Start handle request of {}" , url);
try {
return handleUpdateRequest(data, request, resourceId, artifactId, ComponentTypeEnum.RESOURCE);
- } catch (Throwable e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "updateArtifact");
+ } catch (Exception e) {
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateArtifact");
log.debug("updateArtifact unexpected exception", e);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -129,11 +122,10 @@ public class ArtifactServlet extends BeGenericServlet {
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);
+ log.debug("Start handle request of {}" , url);
try {
return handleDeleteRequest(request, resourceId, artifactId, ComponentTypeEnum.RESOURCE, null, null);
- } catch (Throwable e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "deleteArtifact");
+ } catch (Exception e) {
log.debug("deleteArtifact unexpected exception", e);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
}
@@ -150,11 +142,10 @@ public class ArtifactServlet extends BeGenericServlet {
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);
+ log.debug("Start handle request of {}" , url);
try {
return handleUploadRequest(data, request, serviceId, ComponentTypeEnum.SERVICE);
- } catch (Throwable e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "loadInformationArtifact");
+ } catch (Exception e) {
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("loadInformationArtifact");
log.debug("loadInformationArtifact unexpected exception", e);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -171,11 +162,10 @@ public class ArtifactServlet extends BeGenericServlet {
@Context final HttpServletRequest request) {
String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
+ log.debug("Start handle request of {}" , url);
try {
return handleUpdateRequest(data, request, serviceId, artifactId, ComponentTypeEnum.SERVICE);
- } catch (Throwable e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "updateInformationArtifact");
+ } catch (Exception e) {
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateInformationArtifact");
log.debug("updateInformationArtifact unexpected exception", e);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -193,11 +183,10 @@ public class ArtifactServlet extends BeGenericServlet {
@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);
+ log.debug("Start handle request of {}" , url);
try {
return handleUpdateRequest(data, request, serviceId, artifactId, ComponentTypeEnum.SERVICE);
- } catch (Throwable e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "updateApiArtifact");
+ } catch (Exception e) {
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateApiArtifact");
log.debug("updateApiArtifact unexpected exception", e);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -214,11 +203,10 @@ public class ArtifactServlet extends BeGenericServlet {
@HeaderParam(value = Constants.MD5_HEADER) String origMd5) {
String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
+ log.debug("Start handle request of {}" , url);
try {
return handleDeleteRequest(request, serviceId, artifactId, ComponentTypeEnum.SERVICE, null, null);
- } catch (Throwable e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "deleteApiArtifact");
+ } catch (Exception e) {
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("deleteApiArtifact");
log.debug("deleteApiArtifact unexpected exception", e);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -234,11 +222,10 @@ public class ArtifactServlet extends BeGenericServlet {
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);
+ log.debug("Start handle request of {}" , url);
try {
return handleDeleteRequest(request, serviceId, artifactId, ComponentTypeEnum.SERVICE, null, null);
- } catch (Throwable e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "deleteInformationalArtifact");
+ } catch (Exception e) {
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("deleteInformationalArtifact");
log.debug("deleteInformationalArtifact unexpected exception", e);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -258,11 +245,10 @@ public class ArtifactServlet extends BeGenericServlet {
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);
+ log.debug("Start handle request of {}" , url);
try {
return handleDownloadRequest(request, serviceId, artifactId, null, ComponentTypeEnum.SERVICE, null);
- } catch (Throwable e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "downloadServiceArtifactBase64");
+ } catch (Exception e) {
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadServiceArtifactBase64");
log.debug("downloadServiceArtifactBase64 unexpected exception", e);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -278,11 +264,10 @@ public class ArtifactServlet extends BeGenericServlet {
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);
+ log.debug("Start handle request of {}" , url);
try {
return handleDownloadRequest(request, resourceId, artifactId, null, ComponentTypeEnum.RESOURCE, null);
- } catch (Throwable e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "downloadResourceArtifactBase64");
+ } catch (Exception e) {
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadResourceArtifactBase64");
log.debug("downloadResourceArtifactBase64 unexpected exception", e);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -300,11 +285,10 @@ public class ArtifactServlet extends BeGenericServlet {
@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);
+ log.debug("Start handle request of {}" , url);
try {
return handleDownloadRequest(request, componentInstanceId, artifactId, componentId, ComponentTypeEnum.RESOURCE_INSTANCE, containerComponentType);
- } catch (Throwable e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "downloadResourceInstanceArtifactBase64");
+ } catch (Exception e) {
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadResourceInstanceArtifactBase64");
log.debug("downloadResourceInstanceArtifactBase64 unexpected exception", e);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -325,11 +309,10 @@ public class ArtifactServlet extends BeGenericServlet {
@Context final HttpServletRequest request) {
String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
+ log.debug("Start handle request of {}" , url);
try {
- return handleArtifactRequest(data, request, resourceId, interfaceType, operation, null, ComponentTypeEnum.RESOURCE, ArtifactOperation.Create, null, null);
- } catch (Throwable e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "loadArtifactToInterface");
+ 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));
@@ -348,11 +331,10 @@ public class ArtifactServlet extends BeGenericServlet {
@Context final HttpServletRequest request) {
String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
+ log.debug("Start handle request of {}" , url);
try {
return handleDeleteRequest(request, resourceId, artifactId, ComponentTypeEnum.RESOURCE, interfaceType, operation);
- } catch (Throwable e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "deleteArtifactToInterface");
+ } catch (Exception e) {
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("deleteArtifactToInterface");
log.debug("deleteArtifactToInterface unexpected exception", e);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -371,11 +353,10 @@ public class ArtifactServlet extends BeGenericServlet {
@ApiParam(value = "json describe the artifact", required = true) String data) {
String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
+ log.debug("Start handle request of {}" , url);
try {
- return handleArtifactRequest(data, request, resourceId, interfaceType, operation, artifactId, ComponentTypeEnum.RESOURCE, ArtifactOperation.Update, null, null);
- } catch (Throwable e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "updateArtifactToInterface");
+ 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));
@@ -394,11 +375,10 @@ public class ArtifactServlet extends BeGenericServlet {
@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);
+ log.debug("Start handle request of {}" , url);
try {
- return handleArtifactRequest(data, request, componentInstanceId, null, null, artifactId, ComponentTypeEnum.RESOURCE_INSTANCE, ArtifactOperation.Update, componentId, containerComponentType);
- } catch (Throwable e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "updateRIArtifact");
+ 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));
@@ -417,11 +397,10 @@ public class ArtifactServlet extends BeGenericServlet {
@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);
+ log.debug("Start handle request of {}" , url);
try {
- return handleArtifactRequest(data, request, componentInstanceId, null, null, artifactId, ComponentTypeEnum.RESOURCE_INSTANCE, ArtifactOperation.Update, componentId, containerComponentType);
- } catch (Throwable e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "loadResourceInstanceHeatEnvArtifact");
+ 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));
}
@@ -439,11 +418,10 @@ public class ArtifactServlet extends BeGenericServlet {
@Context final HttpServletRequest request) {
String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
+ log.debug("Start handle request of {}" , url);
try {
- return handleArtifactRequest(data, request, componentInstanceId, null, null, null, ComponentTypeEnum.RESOURCE_INSTANCE, ArtifactOperation.Create, componentId, containerComponentType);
- } catch (Throwable e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "loadResourceInstanceHeatEnvArtifact");
+ 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));
}
@@ -461,27 +439,69 @@ public class ArtifactServlet extends BeGenericServlet {
@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);
+ log.debug("Start handle request of {}" , url);
try {
- ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(containerComponentType);
return handleDeleteRequest(request, componentInstanceId, artifactId, ComponentTypeEnum.RESOURCE_INSTANCE, null, null, componentId);
- } catch (Throwable e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "deleteArtifact");
+ } 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, ArtifactOperation.Create);
+ 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, ArtifactOperation.Update);
+ return handleArtifactRequest(data, request, componentId, artifactId, componentType, ArtifactOperationEnum.Update);
}
private Response handleDownloadRequest(HttpServletRequest request, String componentId, String artifactId, String parentId, ComponentTypeEnum componentType, String containerComponentType) {
@@ -505,6 +525,25 @@ public class ArtifactServlet extends BeGenericServlet {
}
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);
@@ -514,7 +553,7 @@ public class ArtifactServlet extends BeGenericServlet {
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, ArtifactOperation.Delete, artifactId, null, null, null, interfaceType, operationName,
+ 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()) {
@@ -531,7 +570,7 @@ public class ArtifactServlet extends BeGenericServlet {
}
- private Response handleArtifactRequest(String data, HttpServletRequest request, String componentId, String interfaceName, String operationName, String artifactId, ComponentTypeEnum componentType, ArtifactOperation operation, String parentId,
+ 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);
@@ -540,7 +579,8 @@ public class ArtifactServlet extends BeGenericServlet {
ServletContext context = request.getSession().getServletContext();
ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = artifactsLogic.handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, data, interfaceName, operationName, parentId,
+ 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()) {
@@ -557,7 +597,7 @@ public class ArtifactServlet extends BeGenericServlet {
}
- private Response handleArtifactRequest(String data, HttpServletRequest request, String componentId, String artifactId, ComponentTypeEnum componentType, ArtifactOperation operation) {
+ 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 b5e64ae00e..c7bc481119 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
@@ -92,9 +92,7 @@ public class AttributeServlet extends AbstractValidationsServlet {
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);
+ log.debug("Start handle request of {} modifier id is {} data is {}", url, userId, data);
try {
Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
@@ -103,7 +101,7 @@ public class AttributeServlet extends AbstractValidationsServlet {
buildAttributeFromString(data, attributesWrapper, errorWrapper);
if (errorWrapper.isEmpty()) {
- AttributeBusinessLogic businessLogic = getBusinessLogic(context, () -> AttributeBusinessLogic.class);
+ AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class);
Either<AttributeDefinition, ResponseFormat> createAttribute = businessLogic.createAttribute(resourceId, attributesWrapper.getInnerElement(), userId);
if (createAttribute.isRight()) {
errorWrapper.setInnerElement(createAttribute.right().value());
@@ -173,7 +171,7 @@ public class AttributeServlet extends AbstractValidationsServlet {
buildAttributeFromString(data, attributesWrapper, errorWrapper);
if (errorWrapper.isEmpty()) {
- AttributeBusinessLogic businessLogic = getBusinessLogic(context, () -> AttributeBusinessLogic.class);
+ AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class);
Either<AttributeDefinition, ResponseFormat> eitherUpdateAttribute = businessLogic.updateAttribute(resourceId, attributeId, attributesWrapper.getInnerElement(), userId);
// update property
if (eitherUpdateAttribute.isRight()) {
@@ -233,7 +231,7 @@ public class AttributeServlet extends AbstractValidationsServlet {
try {
// delete the property
- AttributeBusinessLogic businessLogic = getBusinessLogic(context, () -> AttributeBusinessLogic.class);
+ AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class);
Either<AttributeDefinition, ResponseFormat> eitherAttribute = businessLogic.deleteAttribute(resourceId, attributeId, userId);
if (eitherAttribute.isRight()) {
log.debug("Failed to delete Attribute. Reason - ", eitherAttribute.right().value());
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 f21b57f6fb..2d5402f709 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
@@ -20,6 +20,7 @@
package org.openecomp.sdc.be.servlets;
+import java.util.EnumMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.function.Supplier;
@@ -43,20 +44,28 @@ 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.config.BeEcompErrorManager;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.dao.api.IElementDAO;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.externalapi.servlet.AssetMetadataConverter;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.impl.WebAppContextWrapper;
+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.common.datastructure.AuditingFieldsKeysEnum;
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;
+
public class BeGenericServlet extends BasicServlet {
@Context
@@ -64,11 +73,11 @@ public class BeGenericServlet extends BasicServlet {
private static Logger log = LoggerFactory.getLogger(BeGenericServlet.class.getName());
- /******************** New error response mechanism **************/
-
+ /******************** New error response mechanism
+ * @param additionalParams **************/
+
protected Response buildErrorResponse(ResponseFormat requestErrorWrapper) {
- Response response = Response.status(requestErrorWrapper.getStatus()).entity(gson.toJson(requestErrorWrapper.getRequestError())).build();
- return response;
+ return Response.status(requestErrorWrapper.getStatus()).entity(gson.toJson(requestErrorWrapper.getRequestError())).build();
}
protected Response buildOkResponse(ResponseFormat errorResponseWrapper, Object entity) {
@@ -96,43 +105,64 @@ public class BeGenericServlet extends BasicServlet {
}
/*******************************************************************************************************/
+ 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 getBusinessLogic(context, () -> UserBusinessLogic.class);
+ return getClassFromWebAppContext(context, () -> UserBusinessLogic.class);
}
protected ResourceBusinessLogic getResourceBL(ServletContext context) {
- return getBusinessLogic(context, () -> ResourceBusinessLogic.class);
+ return getClassFromWebAppContext(context, () -> ResourceBusinessLogic.class);
}
protected ComponentsCleanBusinessLogic getComponentCleanerBL(ServletContext context) {
- return getBusinessLogic(context, () -> ComponentsCleanBusinessLogic.class);
+ return getClassFromWebAppContext(context, () -> ComponentsCleanBusinessLogic.class);
}
protected ServiceBusinessLogic getServiceBL(ServletContext context) {
- return getBusinessLogic(context, () -> ServiceBusinessLogic.class);
+ return getClassFromWebAppContext(context, () -> ServiceBusinessLogic.class);
}
protected ProductBusinessLogic getProductBL(ServletContext context) {
- return getBusinessLogic(context, () -> ProductBusinessLogic.class);
+ return getClassFromWebAppContext(context, () -> ProductBusinessLogic.class);
}
protected ArtifactsBusinessLogic getArtifactBL(ServletContext context) {
- return getBusinessLogic(context, () -> ArtifactsBusinessLogic.class);
+ return getClassFromWebAppContext(context, () -> ArtifactsBusinessLogic.class);
}
protected ElementBusinessLogic getElementBL(ServletContext context) {
- return getBusinessLogic(context, () -> ElementBusinessLogic.class);
+ return getClassFromWebAppContext(context, () -> ElementBusinessLogic.class);
}
protected MonitoringBusinessLogic getMonitoringBL(ServletContext context) {
- return getBusinessLogic(context, () -> MonitoringBusinessLogic.class);
+ return getClassFromWebAppContext(context, () -> MonitoringBusinessLogic.class);
}
- protected <SomeBusinessLogic> SomeBusinessLogic getBusinessLogic(ServletContext context, Supplier<Class<SomeBusinessLogic>> businessLogicClassGen) {
+ 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);
- SomeBusinessLogic monitoringBusinessLogic = webApplicationContext.getBean(businessLogicClassGen.get());
+ SomeClass monitoringBusinessLogic = webApplicationContext.getBean(businessLogicClassGen.get());
return monitoringBusinessLogic;
}
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 ffcd9c68fc..51b0a1dff7 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
@@ -135,17 +135,17 @@ public class BeMonitoringServlet extends BeGenericServlet {
@Path("/version")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "return the ASDC application version", notes = "return the SDC application version", response = String.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "return SDC version"), @ApiResponse(code = 500, message = "Internal Error") })
+ @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("sdc version from manifest is: {}", version);
+ log.debug("asdc version from manifest is: {}", version);
if (version == null || version.isEmpty()) {
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.SDC_VERSION_NOT_FOUND));
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.ASDC_VERSION_NOT_FOUND));
}
HealthCheckInfo versionInfo = new HealthCheckInfo();
@@ -158,14 +158,14 @@ public class BeMonitoringServlet extends BeGenericServlet {
} catch (Exception e) {
BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "getSDCVersion");
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getSDCVersion");
- log.debug("BE get SDC version unexpected exception", e);
+ 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.SDC_RELEASE_VERSION_ATTR);
+ String version = (String) servletContext.getAttribute(Constants.ASDC_RELEASE_VERSION_ATTR);
return version;
}
@@ -187,7 +187,7 @@ public class BeMonitoringServlet extends BeGenericServlet {
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);
+ log.debug("Failed to convert the content {} to object.", content.substring(0, Math.min(50, content.length())), e);
}
return object;
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 4e6d0bcd7f..6a7ecbb5fe 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
@@ -30,6 +30,7 @@ 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;
@@ -43,19 +44,24 @@ import javax.ws.rs.core.Response;
import org.apache.commons.io.IOUtils;
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.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.info.CreateAndAssotiateInfo;
+import org.openecomp.sdc.be.info.GroupDefinitionInfo;
import org.openecomp.sdc.be.model.ComponentInstance;
import org.openecomp.sdc.be.model.ComponentInstanceAttribute;
+import org.openecomp.sdc.be.model.ComponentInstanceInput;
import org.openecomp.sdc.be.model.ComponentInstanceProperty;
+import org.openecomp.sdc.be.model.InputDefinition;
import org.openecomp.sdc.be.model.PropertyConstraint;
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.config.EcompErrorName;
import org.openecomp.sdc.common.datastructure.Wrapper;
import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
@@ -75,6 +81,7 @@ import fj.data.Either;
/**
* Root resource (exposed at "/" path)
+ * .json
*/
@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
@Path("/v1/catalog")
@@ -118,7 +125,6 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResponse.left().value());
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Create Component Instance");
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Component Instance");
log.debug("create component instance failed with exception", e);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -131,7 +137,7 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
@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 updateComponentInstance(@PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId,
+ 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) {
@@ -164,14 +170,13 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
Either<ComponentInstance, ResponseFormat> convertResponse = convertToResourceInstance(data);
if (convertResponse.isRight()) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Resource Instance - updateResourceInstance");
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.updateComponentInstance(containerComponentType, componentId, componentInstanceId, userId, resourceInstance);
+ Either<ComponentInstance, ResponseFormat> actionResponse = componentInstanceLogic.updateComponentInstanceMetadata(containerComponentType, componentId, componentInstanceId, userId, resourceInstance);
if (actionResponse.isRight()) {
return buildErrorResponse(actionResponse.right().value());
@@ -179,7 +184,6 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
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));
@@ -284,7 +288,6 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
}
return response;
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Delete Resource Instance");
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Resource Instance");
log.debug("delete resource instance with exception", e);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -324,7 +327,6 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
Either<RequirementCapabilityRelDef, ResponseFormat> resultOp;
if (regInfoW.isRight()) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Resource Instance - associateRIToRI");
BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - associateRIToRI");
log.debug("Failed to convert received data to BE format.");
resultOp = Either.right(regInfoW.right().value());
@@ -343,7 +345,6 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
return response;
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Associate Resource Instance");
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Associate Resource Instance");
log.debug("associate resource instance to another RI with exception", e);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -379,7 +380,6 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
Either<RequirementCapabilityRelDef, ResponseFormat> regInfoW = convertToRequirementCapabilityRelDef(data);
if (regInfoW.isRight()) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Resource Instance - dissociateRIFromRI");
BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - dissociateRIFromRI");
log.debug("Failed to convert received data to BE format.");
return buildErrorResponse(regInfoW.right().value());
@@ -394,7 +394,6 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Dissociate Resource Instance");
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Dissociate Resource Instance");
log.debug("dissociate resource instance from service failed with exception", e);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -441,7 +440,6 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
Either<CreateAndAssotiateInfo, ActionStatus> convertStatus = convertJsonToObject(data, CreateAndAssotiateInfo.class);
if (convertStatus.isRight()) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Resource Instance - createAndAssociateRIToRI");
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()));
@@ -456,7 +454,6 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
}
return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResponse.left().value());
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Create and Associate Resource Instance");
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));
@@ -517,8 +514,77 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
} catch (Exception e) {
- log.error("create and associate RI failed with exception: ", e.getMessage());
- log.debug("create and associate RI failed with 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<>();
+ Wrapper<ComponentInstanceInput> propertyWrapper = 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));
}
@@ -580,8 +646,7 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
return buildResponseFromElement(errorWrapper, attributeWrapper);
} catch (Exception e) {
- log.error("create and associate RI failed with exception: ", e.getMessage());
- log.debug("create and associate RI failed with exception", e);
+ log.error("create and associate RI failed with exception: {}", e.getMessage(), e);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
}
@@ -617,8 +682,7 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
}
return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null);
} catch (Exception e) {
- log.error("create and associate RI failed with exception: ", e.getMessage());
- log.debug("create and associate RI failed with exception", e);
+ log.error("create and associate RI failed with exception: {}", e.getMessage(), e);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
}
@@ -638,9 +702,6 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
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);
@@ -664,7 +725,6 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
Either<ComponentInstance, ResponseFormat> convertResponse = convertToResourceInstance(data);
if (convertResponse.isRight()) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Resource Instance - updateResourceInstance");
BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - updateResourceInstance");
log.debug("Failed to convert received data to BE format.");
return buildErrorResponse(convertResponse.right().value());
@@ -679,14 +739,149 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
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));
}
}
+
+ @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));
+ }
+
+ }
+
private Either<ComponentInstance, ResponseFormat> convertToResourceInstance(String data) {
// Either<ComponentInstance, ActionStatus> convertStatus =
@@ -700,7 +895,6 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
return Either.left(resourceInstanceInfo);
}
- // TODO Tal New API for Multiple Items move on canvas
private Either<List<ComponentInstance>, ResponseFormat> convertToMultipleResourceInstance(String dataList) {
Either<ComponentInstance[], ResponseFormat> convertStatus = getComponentsUtils().convertJsonToObjectUsingObjectMapper(dataList, new User(), ComponentInstance[].class, null, ComponentTypeEnum.RESOURCE_INSTANCE);
@@ -723,11 +917,10 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
private <T> Either<T, ActionStatus> convertJsonToObject(String data, Class<T> clazz) {
try {
- log.trace("convert json to object. json=\n{}", data);
+ log.trace("convert json to object. json=\n {}", data);
T t = null;
t = gson.fromJson(data, clazz);
if (t == null) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInvalidJsonInput, "convertJsonToObject");
BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject");
log.debug("object is null after converting from json");
return Either.right(ActionStatus.INVALID_CONTENT);
@@ -735,7 +928,6 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
return Either.left(t);
} catch (Exception e) {
// INVALID JSON
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInvalidJsonInput, "convertJsonToObject");
BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject");
log.debug("failed to convert from json", e);
return Either.right(ActionStatus.INVALID_CONTENT);
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 c5bebb41bf..b28700ace4 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,6 +20,11 @@
package org.openecomp.sdc.be.servlets;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.EnumMap;
+import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -38,15 +43,27 @@ import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
+import org.apache.commons.collections.CollectionUtils;
+import org.codehaus.jackson.JsonGenerationException;
+import org.codehaus.jackson.map.JsonMappingException;
import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic;
+import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.datamodel.api.HighestFilterEnum;
+import org.openecomp.sdc.be.datatypes.components.ComponentMetadataDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum;
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.ComponentInstanceProperty;
+import org.openecomp.sdc.be.model.IComponentInstanceConnectedElement;
+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.resources.data.ComponentMetadataData;
+import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;
import org.openecomp.sdc.common.api.Constants;
import org.openecomp.sdc.common.config.EcompErrorName;
import org.openecomp.sdc.exception.ResponseFormat;
@@ -70,12 +87,12 @@ public class ComponentServlet extends BeGenericServlet {
private static Logger log = LoggerFactory.getLogger(ComponentServlet.class.getName());
@GET
- @Path("/{componentType}/{componentId}/requirmentsCapabilities")
+ @Path("/{componentType}/{componentId}/conformanceLevelValidation")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Get Component Requirments And Capabilities", httpMethod = "GET", notes = "Returns Requirments And Capabilities according to componentId", response = Resource.class)
+ @ApiOperation(value = "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 getRequirementAndCapabilities(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @Context final HttpServletRequest request,
+ public Response conformanceLevelValidation(@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();
@@ -86,11 +103,11 @@ public class ComponentServlet extends BeGenericServlet {
ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
if (componentTypeEnum != null) {
ComponentBusinessLogic compBL = getComponentBL(componentTypeEnum, context);
- Either<CapReqDef, ResponseFormat> eitherRequirementsAndCapabilities = compBL.getRequirementsAndCapabilities(componentId, componentTypeEnum, userId);
- if (eitherRequirementsAndCapabilities.isRight()) {
- response = buildErrorResponse(eitherRequirementsAndCapabilities.right().value());
+ Either<Boolean, ResponseFormat> eitherConformanceLevel = compBL.validateConformanceLevel(componentId, componentTypeEnum, userId);
+ if (eitherConformanceLevel.isRight()) {
+ response = buildErrorResponse(eitherConformanceLevel.right().value());
} else {
- response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), gson.toJson(eitherRequirementsAndCapabilities.left().value()));
+ response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), gson.toJson(eitherConformanceLevel.left().value()));
}
} else {
response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
@@ -98,6 +115,42 @@ public class ComponentServlet extends BeGenericServlet {
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 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 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")
@@ -119,7 +172,7 @@ public class ComponentServlet extends BeGenericServlet {
ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
ComponentBusinessLogic businessLogic = getComponentBL(componentTypeEnum, context);
- log.debug("Received componentUids size is {}", (componentUids == null ? 0 : componentUids.size()));
+ 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);
@@ -131,7 +184,6 @@ public class ComponentServlet extends BeGenericServlet {
return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), components);
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Certified Non Abstract" + componentType);
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Certified Non Abstract" + componentType);
log.debug("getCertifiedNotAbstractComponents failed with exception", e);
response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -153,8 +205,7 @@ public class ComponentServlet extends BeGenericServlet {
ServletContext context = request.getSession().getServletContext();
String url = request.getMethod() + " " + request.getRequestURI();
- if (log.isDebugEnabled())
- log.debug("(get) Start handle request of {}", url);
+ log.debug("(GET) Start handle request of {}", url);
Response response = null;
try {
@@ -165,12 +216,8 @@ public class ComponentServlet extends BeGenericServlet {
if (log.isDebugEnabled())
log.debug("Received componentUids size is {}", (componentUids == null ? 0 : componentUids.size()));
- // long start = System.currentTimeMillis();
-
Either<List<Component>, ResponseFormat> actionResponse = businessLogic.getLatestVersionNotAbstractComponents(false, HighestFilterEnum.HIGHEST_ONLY, componentTypeEnum, internalComponentType, componentUids, userId);
- // long endBl = System.currentTimeMillis();
-
if (actionResponse.isRight()) {
if (log.isDebugEnabled())
log.debug("failed to get all non abstract {}", componentType);
@@ -180,15 +227,9 @@ public class ComponentServlet extends BeGenericServlet {
Object components = RepresentationUtils.toRepresentation(actionResponse.left().value());
Response responseToReturn = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), components);
- long endResp = System.currentTimeMillis();
-
- // log.info("********** Time calculation in ms: BL {} , Response {},
- // Total {}", (endBl - start ), (endResp - endBl), (endResp -
- // start));
return responseToReturn;
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Certified Non Abstract" + componentType);
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Certified Non Abstract" + componentType);
log.debug("getCertifiedNotAbstractComponents failed with exception", e);
response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -199,7 +240,7 @@ public class ComponentServlet extends BeGenericServlet {
}
@GET
- @Path("/{componentType}/latestversion/notabstract/uidonly")
+ @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)
@@ -215,7 +256,7 @@ public class ComponentServlet extends BeGenericServlet {
ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
ComponentBusinessLogic businessLogic = getComponentBL(componentTypeEnum, context);
- Either<List<Map<String, String>>, ResponseFormat> actionResponse = businessLogic.getLatestVersionNotAbstractComponentsUidOnly(false, HighestFilterEnum.HIGHEST_ONLY, componentTypeEnum, internalComponentType, userId);
+ 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());
@@ -224,7 +265,6 @@ public class ComponentServlet extends BeGenericServlet {
return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), components);
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Certified Non Abstract" + componentType);
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Certified Non Abstract" + componentType);
log.debug("getCertifiedNotAbstractComponents failed with exception", e);
response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -241,11 +281,11 @@ public class ComponentServlet extends BeGenericServlet {
@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) {
+ @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);
+ log.debug("(GET) Start handle request of {}", url);
Response response = null;
try {
ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
@@ -253,18 +293,122 @@ public class ComponentServlet extends BeGenericServlet {
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);
+ 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().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Component Instances filtered by properties & inputs" + componentType);
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));
+
+ }
+ }
}
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 2a3a87d942..79202ac94f 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
@@ -63,9 +63,7 @@ public class ConfigServlet extends BasicServlet {
log.warn("Configuration of type {} was not found", Configuration.class);
}
log.debug("{}", configuration);
- if (log.isInfoEnabled()) {
- log.debug("Info level ENABLED...");
- }
+ log.info("Info level ENABLED...");
log.info("The value returned from getConfig is {}", configuration);
result = gson.toJson(configuration);
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 0603f267ab..5e9056ba75 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
@@ -204,7 +204,7 @@ public class ConsumerServlet extends BeGenericServlet {
ConsumerDefinition consumer = null;
Gson gson = new Gson();
try {
- log.trace("convert json to object. json=\n{}", data);
+ log.trace("convert json to object. json=\n {}", data);
consumer = gson.fromJson(data, ConsumerDefinition.class);
if (consumer == null) {
BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInvalidJsonInput, "convertJsonToObject");
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 4ba6b7516d..4f8bffa066 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
@@ -90,77 +90,6 @@ public class CsarBuildServlet extends ToscaDaoServlet {
*/
public static final String TOSCA_META_PATH = "TOSCA-Metadata/TOSCA.meta";
- // protected void addToscaMetaToZip(ZipOutputStream zipOutputStream,
- // TopologyService topService, IResourceUploader resUploader) throws
- // IOException {
- // String serviceVersion = topService.getTopologyVersion();
- // String serviceName = topService.getTopologyName();
- // StringBuffer buff = new StringBuffer();
- //
- // String[] serviceToscaMeta = prepareToscaMetaHeader(serviceName);
- //
- // for( String toAppend : serviceToscaMeta){
- // buff.append(toAppend);
- // }
- //
- // List<String> toscaMetaComponents =
- // prepareToscaMetaComponents(topService.getDependenciesYamls().keySet());
- // for( String toAppend : toscaMetaComponents ){
- // buff.append(toAppend);
- // }
- //
- // Either<ServiceArtifactsDataCollection, ResourceUploadStatus>
- // getServiceArtifactsCollectionStatus =
- // Either.right(ResourceUploadStatus.ERROR);//resUploader.getServiceArtifactsCollection(serviceName,
- // serviceVersion);
- // if(getServiceArtifactsCollectionStatus.isLeft()){
- // List<String> toscaMetaArtifacts =
- // prepareToscaMetaArtifacts(getServiceArtifactsCollectionStatus.left().value());
- // for( String toAppend : toscaMetaArtifacts ){
- // buff.append(toAppend);
- // }
- // }
- //
- // addZipEntry(zipOutputStream, TOSCA_META_PATH, buff.toString());
- // }
-
- // protected List<String> prepareToscaMetaArtifacts(
- // ServiceArtifactsDataCollection serviceArtifactsDataCollection) {
- // List<String> artifactsForToscaMeta = new ArrayList<String>();
- // Iterator<Entry<String, List<ArtifactData>>> nodeTemplateArtifactsItr =
- // serviceArtifactsDataCollection.getServiceArtifactDataMap().entrySet().iterator();
- // while( nodeTemplateArtifactsItr.hasNext() ){
- // Entry<String, List<ArtifactData>> nodeNameArtifacts =
- // nodeTemplateArtifactsItr.next();
- // String nodeName = nodeNameArtifacts.getKey();
- // Iterator<ArtifactData> artifactDataItr =
- // nodeNameArtifacts.getValue().iterator();
- // while( artifactDataItr.hasNext() ){
- // ArtifactData artifactData = artifactDataItr.next();
- // artifactsForToscaMeta.add("\n");
- // artifactsForToscaMeta.add("Name: "+getArtifactPath(nodeName,
- // artifactData)+"\n");
- // artifactsForToscaMeta.add("Content-Type:
- // application/"+getAppliactionMime(artifactData.getArtifactName())+"\n");
- // }
- // }
- // return artifactsForToscaMeta;
- // }
-
- // protected List<String> prepareToscaMetaComponents(Set<String> components)
- // {
- // Iterator<String> resourceNameItr = components.iterator();
- // List<String> componentsForToscaMeta = new ArrayList<String>();
- // while( resourceNameItr.hasNext() ){
- // String resourceName = resourceNameItr.next();
- // componentsForToscaMeta.add("\n");
- // componentsForToscaMeta.add("Name: "+getResourcePath(resourceName)+"\n");
- // componentsForToscaMeta.add("Content-Type:
- // application/vnd.oasis.tosca.definitions.yaml\n");
- //
- // }
- // return componentsForToscaMeta;
- // }
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",
@@ -198,17 +127,6 @@ public class CsarBuildServlet extends ToscaDaoServlet {
return mimeType;
}
- // protected void addResourcesToZip(ZipOutputStream zipOutputStream,
- // TopologyService topService) throws IOException {
- // Iterator<Entry<String, String>> resourceNameDataItr =
- // topService.getDependenciesYamls().entrySet().iterator();
- // while( resourceNameDataItr.hasNext() ){
- // Entry<String, String> resourceNameData = resourceNameDataItr.next();
- // addZipEntry(zipOutputStream, getResourcePath(resourceNameData.getKey()),
- // resourceNameData.getValue());
- // }
- // }
-
protected String getArtifactPath(String nodeTamplateName, ESArtifactData artifactData) {
// return "Scripts/"+nodeTamplateName+"/"+
// artifactData.getArtifactName();
@@ -219,57 +137,6 @@ public class CsarBuildServlet extends ToscaDaoServlet {
return "Definitions/" + resourceName + ".yaml";
}
- // protected void addArtifactsToZip(String serviceName, String
- // serviceVersion, ZipOutputStream zipOutputStream, IResourceUploader
- // resourceUploader)
- // throws IOException {
- // //Add Artifacts to Zip
- // Either<ServiceArtifactsDataCollection, ResourceUploadStatus>
- // getServiceArtifactsCollectionStatus =
- // Either.right(ResourceUploadStatus.ERROR);//resourceUploader.getServiceArtifactsCollection(serviceName,
- // serviceVersion);
- // if(getServiceArtifactsCollectionStatus.isLeft()){
- // Iterator<Entry<String, List<ArtifactData>>> nodeTemplateArtifactsItr
- // =getServiceArtifactsCollectionStatus.left().value().getServiceArtifactDataMap().entrySet().iterator();
- // while( nodeTemplateArtifactsItr.hasNext() ){
- // Entry<String, List<ArtifactData>> nodeTemplateArtifacts =
- // nodeTemplateArtifactsItr.next();
- // String nodeTamplateName = nodeTemplateArtifacts.getKey();
- // List<ArtifactData> artifacts = nodeTemplateArtifacts.getValue();
- // for(ArtifactData artifactData : artifacts ){
- // addZipEntry(zipOutputStream,
- // getArtifactPath(nodeTamplateName,artifactData), artifactData.getData());
- // }
- //
- // }
- // }
- // }
-
- // private Response buildResponse(String fileName, ByteArrayOutputStream
- // fileOutputStream) {
- // final InputStream inputStream = new
- // ByteArrayInputStream(fileOutputStream.toByteArray());
- //
- // StreamingOutput stream = new StreamingOutput() {
- // public void write(OutputStream output) throws WebApplicationException {
- // try {
- // IOUtils.copy(inputStream, output);
- // } catch (Exception e) {
- // throw new WebApplicationException(e);
- // }
- // }
- // };
- //
- // return
- // Response.ok(stream).type(MediaType.APPLICATION_OCTET_STREAM_TYPE).header("content-disposition","attachment;
- // filename = "+fileName).build();
- // }
-
- // protected void addZipEntry(ZipOutputStream zipOutputStream, String
- // filePath, String data) throws IOException {
- // addZipEntry(zipOutputStream, filePath, encodeString(data));
- // }
-
private byte[] encodeString(String data) throws CharacterCodingException {
Charset charset = Charset.forName("UTF-8");
CharsetEncoder encoder = charset.newEncoder();
@@ -279,15 +146,6 @@ public class CsarBuildServlet extends ToscaDaoServlet {
return ba;
}
- // private void addZipEntry(ZipOutputStream zipOutputStream, String
- // filePath, byte[] data) throws IOException {
- // log.debug("Adding to CSAR zip :{}", filePath);
- // ZipEntry entry = new ZipEntry(filePath);
- // zipOutputStream.putNextEntry(entry);
- // zipOutputStream.write(data);
- // zipOutputStream.closeEntry();
- // }
-
@Override
public Logger getLogger() {
return log;
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 433a1bfc58..576fc29014 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
@@ -57,6 +57,7 @@ import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.model.category.CategoryDefinition;
import org.openecomp.sdc.be.model.category.GroupingDefinition;
import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
+import org.openecomp.sdc.be.ui.model.UiCategories;
import org.openecomp.sdc.be.user.UserBusinessLogic;
import org.openecomp.sdc.common.api.Constants;
import org.openecomp.sdc.common.config.EcompErrorName;
@@ -126,6 +127,33 @@ public class ElementServlet extends BeGenericServlet {
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}")
@@ -388,7 +416,7 @@ public class ElementServlet extends BeGenericServlet {
@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("(getArtifactTypes) Start handle request of {}", url);
+ log.debug("(GET - getArtifactTypes) Start handle request of {}", url);
try {
ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext());
@@ -568,7 +596,7 @@ public class ElementServlet extends BeGenericServlet {
NodeTypeEnum nodeType = NodeTypeEnum.getByNameIgnoreCase(componentType);
if (nodeType == null) {
- log.info("componentType is not valid: {}", componentType);
+ log.info("componentType is not valid: {]", componentType);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
}
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 bde8f93929..32fd06a2a8 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,6 +20,8 @@
package org.openecomp.sdc.be.servlets;
+import java.util.List;
+
import javax.inject.Singleton;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
@@ -40,6 +42,7 @@ import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.info.GroupDefinitionInfo;
import org.openecomp.sdc.be.model.GroupDefinition;
+import org.openecomp.sdc.be.model.GroupProperty;
import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.common.api.Constants;
@@ -48,8 +51,8 @@ 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.google.gson.GsonBuilder;
import com.jcabi.aspects.Loggable;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
@@ -77,29 +80,33 @@ public class GroupServlet extends AbstractValidationsServlet {
@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) {
+ @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);
- Response response = null;
try {
GroupBusinessLogic businessLogic = this.getGroupBL(context);
ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
- Either<GroupDefinitionInfo, ResponseFormat> actionResponse = businessLogic.getGroupWithArtifactsById(componentTypeEnum, componentId, groupId, userId, false);
+ 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());
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
+ actionResponse.left().value());
} catch (Throwable e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "getGroupArtifactById");
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getGroupArtifactById");
log.debug("getGroupArtifactById unexpected exception", e);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -112,9 +119,15 @@ public class GroupServlet extends AbstractValidationsServlet {
@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) {
+ @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();
@@ -129,7 +142,7 @@ public class GroupServlet extends AbstractValidationsServlet {
try {
GroupBusinessLogic businessLogic = getGroupBL(context);
- Either<GroupDefinition, ResponseFormat> convertResponse = parseToGroup(data);
+ Either<GroupDefinition, ResponseFormat> convertResponse = parseToObject(data, () -> GroupDefinition.class);
if (convertResponse.isRight()) {
log.debug("failed to parse group");
response = buildErrorResponse(convertResponse.right().value());
@@ -139,7 +152,8 @@ public class GroupServlet extends AbstractValidationsServlet {
// Update GroupDefinition
ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
- Either<GroupDefinition, ResponseFormat> actionResponse = businessLogic.updateGroupMetadata(componentId, user, groupUniqueId, componentTypeEnum, updatedGroup, true);
+ Either<GroupDefinition, ResponseFormat> actionResponse = businessLogic
+ .validateAndUpdateGroupMetadata(componentId, user, componentTypeEnum, updatedGroup, true);
if (actionResponse.isRight()) {
log.debug("failed to update GroupDefinition");
@@ -152,7 +166,6 @@ public class GroupServlet extends AbstractValidationsServlet {
return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Update Group Metadata");
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Group Metadata");
log.debug("update group metadata failed with exception", e);
response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -162,20 +175,74 @@ public class GroupServlet extends AbstractValidationsServlet {
}
/**
- * Convert data to GroupDefinition object
- *
- * @param groupJson
+ * Updates List of properties on a group (only values)
+ * @param containerComponentType
+ * @param componentId
+ * @param groupUniqueId
+ * @param data
+ * @param request
+ * @param userId
* @return
*/
- public Either<GroupDefinition, ResponseFormat> parseToGroup(String groupJson) {
+ @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 {
- Gson gson = new GsonBuilder().setPrettyPrinting().create();
- GroupDefinition groupDefinition = gson.fromJson(groupJson, GroupDefinition.class);
- return Either.left(groupDefinition);
+ 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) {
- log.debug("Failed to parse json (group data) to GroupDefinition object");
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
- return Either.right(responseFormat);
+ 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/InputsServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/InputsServlet.java
index e835c43e14..580b2bdb8b 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
@@ -30,6 +30,7 @@ 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;
@@ -38,6 +39,8 @@ 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 org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
import org.openecomp.sdc.be.components.impl.InputsBusinessLogic;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
@@ -52,6 +55,7 @@ import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
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.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -70,7 +74,7 @@ import fj.data.Either;
@Path("/v1/catalog")
@Api(value = "Input Catalog", description = "Input Servlet")
@Singleton
-public class InputsServlet extends BeGenericServlet {
+public class InputsServlet extends AbstractValidationsServlet {
private static Logger log = LoggerFactory.getLogger(ProductServlet.class.getName());
@@ -102,22 +106,80 @@ public class InputsServlet extends BeGenericServlet {
} catch (Exception e) {
BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Component Instance Inputs" + componentType);
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get 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}/{originComonentUid}/inputs")
+ @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("originComonentUid") final String originComonentUid, @Context final HttpServletRequest request, @QueryParam("fromName") String fromName, @QueryParam("amount") int amount,
+ @PathParam("originComponentUid") final String originComonentUid, @Context final HttpServletRequest request, @QueryParam("fromName") String fromName, @QueryParam("amount") int amount,
@HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
ServletContext context = request.getSession().getServletContext();
@@ -128,7 +190,7 @@ public class InputsServlet extends BeGenericServlet {
try {
InputsBusinessLogic businessLogic = getInputBL(context);
- Either<List<InputDefinition>, ResponseFormat> inputsResponse = businessLogic.getInputs(userId, originComonentUid, fromName, amount);
+ Either<List<ComponentInstanceInput>, ResponseFormat> inputsResponse = businessLogic.getComponentInstanceInputs(userId, componentId, instanceId, fromName, amount);
if (inputsResponse.isRight()) {
log.debug("failed to get component instance inputs {}", componentType);
return buildErrorResponse(inputsResponse.right().value());
@@ -138,7 +200,7 @@ public class InputsServlet extends BeGenericServlet {
} catch (Exception e) {
BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Component Instance Inputs" + componentType);
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Inputs" + componentType);
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Inputs " + componentType);
log.debug("getInputs failed with exception", e);
response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
return response;
@@ -157,13 +219,13 @@ public class InputsServlet extends BeGenericServlet {
ServletContext context = request.getSession().getServletContext();
String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("(get) Start handle request of {}", url);
+ log.debug("(GET) Start handle request of {}", url);
Response response = null;
try {
InputsBusinessLogic businessLogic = getInputBL(context);
- Either<List<ComponentInstanceProperty>, ResponseFormat> inputPropertiesRes = businessLogic.getComponentInstancePropertiesByInputId(userId, instanceId, inputId);
+ 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());
@@ -199,6 +261,43 @@ public class InputsServlet extends BeGenericServlet {
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());
@@ -270,6 +369,8 @@ public class InputsServlet extends BeGenericServlet {
}
}
+
+
@DELETE
@Path("/{componentType}/{componentId}/delete/{inputId}/input")
@Consumes(MediaType.APPLICATION_JSON)
@@ -291,14 +392,13 @@ public class InputsServlet extends BeGenericServlet {
try {
InputsBusinessLogic businessLogic = getInputBL(context);
- Either<InputDefinition, ResponseFormat> deleteInput = businessLogic.deleteInput(componentType, componentId, userId, inputId, true);
+ Either<InputDefinition, ResponseFormat> deleteInput = businessLogic.deleteInput(componentType, componentId, userId, inputId);
if (deleteInput.isRight()){
ResponseFormat deleteResponseFormat = deleteInput.right().value();
response = buildErrorResponse(deleteResponseFormat);
return response;
}
- InputDefinition inputDefinition = deleteInput.left().value();
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), inputDefinition);
+ 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);
@@ -308,7 +408,46 @@ public class InputsServlet extends BeGenericServlet {
}
}
+
+
+
+ /*@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);
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 3f8bfd9149..019a6ba8fd 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
@@ -40,7 +40,6 @@ import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.impl.WebAppContextWrapper;
import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
import org.openecomp.sdc.be.model.User;
@@ -50,7 +49,6 @@ import org.openecomp.sdc.common.config.EcompErrorName;
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 com.wordnik.swagger.annotations.Api;
@@ -92,9 +90,9 @@ public class LifecycleServlet extends BeGenericServlet {
// get modifier from graph
log.debug("get modifier properties");
- Either<User, Response> eitherGetUser = getUser(request, userId);
+ Either<User, ResponseFormat> eitherGetUser = getUser(request, userId);
if (eitherGetUser.isRight()) {
- return eitherGetUser.right().value();
+ return buildErrorResponse(eitherGetUser.right().value());
}
User user = eitherGetUser.left().value();
@@ -130,27 +128,6 @@ public class LifecycleServlet extends BeGenericServlet {
try {
LifeCycleTransitionEnum transitionEnum = validateEnum.left().value();
ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(componentCollection);
- // if (componentType == ComponentTypeEnum.RESOURCE){
- // Either<Resource, ResponseFormat> actionResponse =
- // businessLogic.changeState(resourceIdLower, user, transitionEnum,
- // changeInfo, false);
- //
- // if (actionResponse.isRight()){
- // log.info("failed to change resource state");
- // response = buildErrorResponse(actionResponse.right().value());
- // return response;
- // }
- //
- // log.debug("change state successful !!!");
- // Object resource =
- // RepresentationUtils.toRepresentation(actionResponse.left().value());
- // response =
- // buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
- // resource);
- // return response;
- //
- // } else if (componentType == ComponentTypeEnum.SERVICE ||
- // componentType == ComponentTypeEnum.PRODUCT){
if (componentType != null) {
Either<? extends Component, ResponseFormat> actionResponse = businessLogic.changeComponentState(componentType, componentId, user, transitionEnum, changeInfo, false, true);
@@ -192,25 +169,25 @@ public class LifecycleServlet extends BeGenericServlet {
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 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());
+//
+// }
}
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 2c693c71a8..df84e07b2c 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
@@ -53,9 +53,9 @@ import org.openecomp.sdc.be.impl.WebAppContextWrapper;
import org.openecomp.sdc.be.model.PropertyConstraint;
import org.openecomp.sdc.be.model.PropertyDefinition;
import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
import org.openecomp.sdc.be.model.operations.impl.PropertyOperation.PropertyConstraintDeserialiser;
import org.openecomp.sdc.be.model.operations.impl.PropertyOperation.PropertyConstraintSerialiser;
+import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
import org.openecomp.sdc.be.resources.data.EntryData;
import org.openecomp.sdc.common.api.Constants;
import org.openecomp.sdc.common.config.EcompErrorName;
@@ -97,13 +97,11 @@ public class PropertyServlet extends BeGenericServlet {
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);
+ 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(data);
+ Either<Map<String, PropertyDefinition>, ActionStatus> either = getPropertyModel(resourceId, data);
if (either.isRight()) {
ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(either.right().value());
return buildErrorResponse(responseFormat);
@@ -156,8 +154,7 @@ public class PropertyServlet extends BeGenericServlet {
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("Start handle request of {}, modifier id is {}", url, userId);
try {
@@ -195,19 +192,18 @@ public class PropertyServlet extends BeGenericServlet {
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("Start handle request of {} modifier id is {}", url, userId);
try {
// delete the property
PropertyBusinessLogic businessLogic = getPropertyBL(context);
- Either<EntryData<String, PropertyDefinition>, ResponseFormat> status = businessLogic.deleteProperty(resourceId, propertyId, userId);
+ 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());
}
- EntryData<String, PropertyDefinition> property = status.left().value();
+ Entry<String, PropertyDefinition> property = status.left().value();
String name = property.getKey();
PropertyDefinition propertyDefinition = property.getValue();
@@ -216,7 +212,6 @@ public class PropertyServlet extends BeGenericServlet {
return buildOkResponse(responseFormat, propertyToJson(property));
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Delete Property");
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Property");
log.debug("delete property failed with exception", e);
ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
@@ -247,7 +242,7 @@ public class PropertyServlet extends BeGenericServlet {
try {
// convert json to PropertyDefinition
- Either<Map<String, PropertyDefinition>, ActionStatus> either = getPropertyModel(data);
+ Either<Map<String, PropertyDefinition>, ActionStatus> either = getPropertyModel(resourceId, data);
if (either.isRight()) {
ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(either.right().value());
return buildErrorResponse(responseFormat);
@@ -285,54 +280,7 @@ public class PropertyServlet extends BeGenericServlet {
}
}
- // private String propertyToJsonUi(Map.Entry<String, PropertyDefinition>
- // property) {
- // String name = property.getKey();
- // PropertyDefinition propertyDefinition = property.getValue();
- // JSONObject root = new JSONObject();
- // root.put("type", propertyDefinition.getType());
- // root.put("source", propertyDefinition.getDefaultValue());
- // root.put("name", name);
- // root.put("description", propertyDefinition.getDescription());
- // root.put("uniqueId", propertyDefinition.getUniqueId());
- // return root.toString();
- //
- // }
- //
-
- // private Either<String ,ActionStatus> getJsonModel(String data){
- // Either<UiProperty,ActionStatus> uiPropertyEither = getUiProperty(data);
- // if (uiPropertyEither.isRight()){
- // log.error("Property conetnt is invalid - {}",data);
- // return Either.right(ActionStatus.INVALID_CONTENT);
- // }
- // UiProperty uiProperty = uiPropertyEither.left().value();
- // String json = convertUiPropertyToJsonModel(uiProperty);
- // return Either.left(json);
- // }
- //
-
- // private String convertUiPropertyToJsonModel(UiProperty uiProperty) {
- // JSONObject root = new JSONObject();
- // JSONObject propertyD = new JSONObject();
- // propertyD.put("type",uiProperty.getType());
- // propertyD.put("required",false);
- // propertyD.put("description",uiProperty.getDescription());
- // propertyD.put("isPassword",false);
- // propertyD.put("defaultValue",uiProperty.getSource());
- // JSONArray jsonArr = new JSONArray();
- // JSONArray jsonR = new JSONArray();
- // jsonR.add(100);
- // jsonR.add(500);
- // JSONObject o = new JSONObject();
- // o.put("inRange", jsonR);
- // jsonArr.add(o);
- // propertyD.put("constraints",jsonArr);
- // root.put(uiProperty.getName(), propertyD);
- // return root.toString();
- // }
-
- private Either<Map<String, PropertyDefinition>, ActionStatus> getPropertyModel(String data) {
+ private Either<Map<String, PropertyDefinition>, ActionStatus> getPropertyModel(String resourceId, String data) {
JSONParser parser = new JSONParser();
JSONObject root;
try {
@@ -353,7 +301,7 @@ public class PropertyServlet extends BeGenericServlet {
PropertyDefinition propertyDefinition = convertJsonToObject.left().value();
// PropertyDefinition propertyDefinition =
// gson.fromJson(jsonString , PropertyDefinition.class);
- String uniqueId = UniqueIdBuilder.buildPropertyUniqueId("resourceId", (String) propertyName);
+ String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId, (String) propertyName);
propertyDefinition.setUniqueId(uniqueId);
properties.put(propertyName, propertyDefinition);
}
@@ -384,54 +332,7 @@ public class PropertyServlet extends BeGenericServlet {
}
}
- // private Either<Map<String,PropertyDefinition>,ActionStatus>
- // getProperty(String data){
- // Type constraintType = new TypeToken<PropertyConstraint>() {}.getType();
- // PropertyConstraintDeserialiser propertyConstraintDeserialiser = new
- // PropertyConstraintDeserialiser();
- // Gson gson = new
- // GsonBuilder().registerTypeAdapter(constraintType,propertyConstraintDeserialiser).create();
- // JSONParser parser = new JSONParser();
- // JSONObject root;
- // try {
- // Map<String,PropertyDefinition> properties = new
- // HashMap<String,PropertyDefinition>();
- // root = (JSONObject) parser.parse(data);
- // Set keySet = root.keySet();
- // for (Object propertyName : keySet){
- // JSONObject val = (JSONObject) root.get(propertyName);
- // String jsonString = val.toJSONString();
- // 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.error("Property conetnt is invalid - {}",data);
- // return Either.right(ActionStatus.INVALID_CONTENT);
- // }
- // }
- //
- // private Either<UiProperty, ActionStatus> getUiProperty(String data) {
- // try{
- // Gson gson = new Gson();
- // UiProperty uiProperty = gson.fromJson(data, UiProperty.class);
- // return Either.left(uiProperty);
- // }catch(JsonSyntaxException e){
- // log.warn("Problem create UiProperty from {}",data);
- // log.debug("Problem create UiProperty from {}",data,e);
- // return Either.right(ActionStatus.INVALID_CONTENT);
- // }
- // }
-
private String propertyToJson(Map.Entry<String, PropertyDefinition> property) {
- // Type constraintType = new TypeToken<PropertyConstraint>()
- // {}.getType();
- // Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new
- // PropertyConstraintDeserialiser()).create();
JSONObject root = new JSONObject();
String propertyName = property.getKey();
PropertyDefinition propertyDefinition = property.getValue();
@@ -461,30 +362,13 @@ public class PropertyServlet extends BeGenericServlet {
}
- // private JSONObject getPropertyDefinitionJSONObject(PropertyDefinition
- // propertyDefinition) {
- // JSONObject root = new JSONObject();
- // root.put("type", propertyDefinition.getType());
- // root.put("required", propertyDefinition.isRequired());
- // root.put("defaultValue", propertyDefinition.getDefaultValue());
- // root.put("description", propertyDefinition.getDescription());
- // root.put("isPassword", propertyDefinition.isPassword());
- // List<PropertyConstraint> constraints =
- // propertyDefinition.getConstraints();
- // for (PropertyConstraint p : constraints){
- // p.toString();
- // }
- // root.put("constraints", propertyDefinition.getConstraints());
- // return root;
- // }
-
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);
+ 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");
@@ -504,7 +388,7 @@ public class PropertyServlet extends BeGenericServlet {
}.getType();
Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintSerialiser()).create();
try {
- log.trace("convert object to json. propertyDefinition={}", propertyDefinition.toString());
+ 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");
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 565911eaa9..5eed7eeb0d 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
@@ -85,6 +85,7 @@ public class RepresentationUtils {
JsonObject jsonElement = new JsonObject();
ArtifactDefinition resourceInfo = null;
+
try {
Gson gson = new Gson();
jsonElement = gson.fromJson(content, jsonElement.getClass());
@@ -109,13 +110,19 @@ public class RepresentationUtils {
payload = artifactPayload.getAsString();
}
jsonElement.remove(Constants.ARTIFACT_PAYLOAD_DATA);
- resourceInfo = gson.fromJson(jsonElement, clazz);
+ 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);
+ 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/ResourceArtifactDownloadServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourceArtifactDownloadServlet.java
index 673187b0a1..54ec6e3b15 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
@@ -56,41 +56,6 @@ public class ResourceArtifactDownloadServlet extends ToscaDaoServlet {
private Gson gson = new GsonBuilder().setPrettyPrinting().create();
- // @GET
- // @Path("/{resourceName}/{resourceVersion}/artifacts")
- // @Produces(MediaType.APPLICATION_JSON)
- // public Response getResourceArtifactList(@PathParam("resourceName") final
- // String resourceName,
- // @PathParam("resourceVersion") final String resourceVersion,
- // @Context final HttpServletRequest request){
- //
- //
- // String url = request.getMethod() + " " + request.getRequestURI();
- // log.info("Start handle request of {}", url);
- //
- // Response response = null;
- //
- // // get artifact list from dao
- // 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;
- // }
- // Either<List<ESArtifactData>, ResourceUploadStatus> getArtifactsStatus =
- // resourceDao.getArtifacts(resourceName, resourceVersion);
- //
- // response =
- // getLogic(request.getSession().getServletContext()).createArtifactListResponse(resourceName,
- // getArtifactsStatus, getServletPath(request));
- //
- // log.info("Finish handle request of {} | result = {}", url, response.getStatus() );
- // return response;
- //
- // }
-
@GET
@Path("/{resourceName}/{resourceVersion}/artifacts/{artifactName}")
// @Produces(MediaType.APPLICATION_OCTET_STREAM)
@@ -118,7 +83,7 @@ public class ResourceArtifactDownloadServlet extends ToscaDaoServlet {
}
response = logic.downloadArtifact(resourceName, resourceVersion, artifactName, getArtifactStatus, artifactId);
- log.info("Finish handle request of {} | result = {}", url, response.getStatus());
+ log.info("Finish handle request of {} | result = {}", url, response.getStatus());
return response;
} catch (Exception e) {
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 5cd765abe0..ef6ddb04ba 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
@@ -71,11 +71,12 @@ 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);
+ 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;
@@ -150,9 +151,11 @@ public class ResourceUploadServlet extends AbstractValidationsServlet {
fillPayload(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), resourceInfoJsonString, resourceAuthorityEnum, file);
// PayLoad Validations
- commonPayloadValidations(responseWrapper, yamlStringWrapper, userWrapper.getInnerElement(), uploadResourceInfoWrapper.getInnerElement());
+ if(!resourceAuthorityEnum.equals(ResourceAuthorityTypeEnum.CSAR_TYPE_BE)){
+ commonPayloadValidations(responseWrapper, yamlStringWrapper, userWrapper.getInnerElement(), uploadResourceInfoWrapper.getInnerElement());
- specificResourceAuthorityValidations(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), request, resourceInfoJsonString, resourceAuthorityEnum);
+ specificResourceAuthorityValidations(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), request, resourceInfoJsonString, resourceAuthorityEnum);
+ }
if (responseWrapper.isEmpty()) {
handleImport(responseWrapper, userWrapper.getInnerElement(), uploadResourceInfoWrapper.getInnerElement(), yamlStringWrapper.getInnerElement(), resourceAuthorityEnum, createNewVersion, null);
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 e3d39610a8..74d81ebd24 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
@@ -51,12 +51,10 @@ import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.datamodel.api.HighestFilterEnum;
-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.PropertyDefinition;
import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.ResourceMetadataDefinition;
import org.openecomp.sdc.be.model.UploadResourceInfo;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
@@ -100,7 +98,7 @@ public class ResourcesServlet extends AbstractValidationsServlet {
ServletContext context = request.getSession().getServletContext();
String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
+ log.debug("Start handle request of {}" , url);
// get modifier id
User modifier = new User();
@@ -128,7 +126,7 @@ public class ResourcesServlet extends AbstractValidationsServlet {
}
Resource resource = convertResponse.left().value();
- Either<Resource, ResponseFormat> actionResponse = businessLogic.createResource(resource, modifier, null, null);
+ Either<Resource, ResponseFormat> actionResponse = businessLogic.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, modifier, null, null);
if (actionResponse.isRight()) {
log.debug("failed to create resource");
@@ -160,7 +158,7 @@ public class ResourcesServlet extends AbstractValidationsServlet {
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);
+ log.debug("failed to parse json sent from client, json:{}", data, e);
isUIImport = false;
}
return isUIImport;
@@ -177,8 +175,6 @@ public class ResourcesServlet extends AbstractValidationsServlet {
commonGeneralValidations(responseWrapper, userWrapper, uploadResourceInfoWrapper, resourceAuthorityEnum, userId, resourceInfoJsonString);
- // TODO suspect next line is unnecessary
- userWrapper.getInnerElement();
if (!CsarValidationUtils.isCsarPayloadName(uploadResourceInfoWrapper.getInnerElement().getPayloadName())) {
fillPayload(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), resourceInfoJsonString, resourceAuthorityEnum, null);
@@ -212,13 +208,13 @@ public class ResourcesServlet extends AbstractValidationsServlet {
ServletContext context = request.getSession().getServletContext();
String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
+ 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);
+ log.debug("modifier id is {}" , userId);
Response response = null;
@@ -252,13 +248,13 @@ public class ResourcesServlet extends AbstractValidationsServlet {
ServletContext context = request.getSession().getServletContext();
String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
+ 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);
+ log.debug("modifier id is {}" , userId);
Response response = null;
@@ -295,12 +291,12 @@ public class ResourcesServlet extends AbstractValidationsServlet {
ServletContext context = request.getSession().getServletContext();
String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
+ log.debug("Start handle request of {}" , url);
// get modifier id
User modifier = new User();
modifier.setUserId(userId);
- log.debug("modifier id is {}", userId);
+ log.debug("modifier id is {}" , userId);
Response response = null;
@@ -340,11 +336,11 @@ public class ResourcesServlet extends AbstractValidationsServlet {
// get modifier id
User modifier = new User();
modifier.setUserId(userId);
- log.debug("modifier id is {}", userId);
+ log.debug("modifier id is {}" , userId);
Response response = null;
try {
ResourceBusinessLogic businessLogic = getResourceBL(context);
- Either<List<Resource>, ResponseFormat> actionResponse = businessLogic.getResourceByNameAndVersion(resourceName, resourceVersion, userId);
+ Either<Resource, ResponseFormat> actionResponse = businessLogic.getResourceByNameAndVersion(resourceName, resourceVersion, userId);
if (actionResponse.isRight()) {
response = buildErrorResponse(actionResponse.right().value());
return response;
@@ -370,17 +366,17 @@ public class ResourcesServlet extends AbstractValidationsServlet {
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);
+ log.debug("Start handle request of {}" , url);
// get modifier id
User modifier = new User();
modifier.setUserId(userId);
- log.debug("modifier id is {}", userId);
+ log.debug("modifier id is {}" , userId);
Response response = null;
try {
ResourceBusinessLogic businessLogic = getResourceBL(context);
- if (resourceType != null && !ResourceTypeEnum.contains(resourceType)) {
+ if (resourceType != null && !ResourceTypeEnum.containsName(resourceType)) {
log.debug("invalid resource type received");
response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
return response;
@@ -416,7 +412,7 @@ public class ResourcesServlet extends AbstractValidationsServlet {
ServletContext context = request.getSession().getServletContext();
String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("(get) Start handle request of {}", url);
+ log.debug("(get) Start handle request of {}" , url);
Response response = null;
try {
@@ -452,7 +448,7 @@ public class ResourcesServlet extends AbstractValidationsServlet {
ServletContext context = request.getSession().getServletContext();
String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("(get) Start handle request of {}", url);
+ log.debug("(get) Start handle request of {}" , url);
Response response = null;
try {
@@ -492,7 +488,7 @@ public class ResourcesServlet extends AbstractValidationsServlet {
ServletContext context = request.getSession().getServletContext();
String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
+ log.debug("Start handle request of {}" , url);
// get modifier id
User modifier = new User();
@@ -510,8 +506,7 @@ public class ResourcesServlet extends AbstractValidationsServlet {
response = buildErrorResponse(updateInfoResource.right().value());
return response;
}
- Either<Resource, ResponseFormat> actionResponse = businessLogic.updateResourceMetadata(resourceIdLower,
- updateInfoResource.left().value(), null, modifier, false);
+ Either<Resource, ResponseFormat> actionResponse = businessLogic.updateResourceMetadata(resourceIdLower, updateInfoResource.left().value(), null, modifier, false);
if (actionResponse.isRight()) {
log.debug("failed to update resource metadata");
@@ -548,7 +543,7 @@ public class ResourcesServlet extends AbstractValidationsServlet {
ServletContext context = request.getSession().getServletContext();
String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
+ log.debug("Start handle request of {}" , url);
// get modifier id
User modifier = new User();
@@ -607,7 +602,7 @@ public class ResourcesServlet extends AbstractValidationsServlet {
*
* @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;
+ * String url = request.getMethod() + " " + request.getRequestURI(); log.debug("(get) Start handle request of " + url); Response response=null;
*
* try {
*
@@ -653,7 +648,7 @@ public class ResourcesServlet extends AbstractValidationsServlet {
ServletContext context = request.getSession().getServletContext();
String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
+ log.debug("Start handle request of {}" , url);
// retrieve user details
userId = (userId != null) ? userId : request.getHeader(Constants.USER_ID_HEADER);
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 7e7068f5d7..05a6f5146c 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
@@ -24,7 +24,9 @@ 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;
@@ -46,6 +48,7 @@ import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.http.HttpStatus;
+import org.codehaus.jackson.map.ObjectMapper;
import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
@@ -54,17 +57,18 @@ 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.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.resources.data.auditing.AuditingActionEnum;
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.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import com.google.gson.reflect.TypeToken;
import com.jcabi.aspects.Loggable;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
@@ -123,7 +127,6 @@ public class ServiceServlet extends AbstractValidationsServlet {
return response;
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Create Service");
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Service");
log.debug("create service failed with exception", e);
response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -163,7 +166,6 @@ public class ServiceServlet extends AbstractValidationsServlet {
}
return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Validate Service Name");
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Validate Service Name");
log.debug("validate service name failed with exception", e);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -187,9 +189,9 @@ public class ServiceServlet extends AbstractValidationsServlet {
modifier.setUserId(userId);
log.debug("modifier id is {}", userId);
Wrapper<Response> responseWrapper = new Wrapper<Response>();
- Wrapper<String> uuidWrapper = new Wrapper<String>();
- Wrapper<String> versionWrapper = new Wrapper<String>();
- Wrapper<User> userWrapper = new Wrapper<User>();
+ 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);
@@ -217,7 +219,6 @@ public class ServiceServlet extends AbstractValidationsServlet {
}
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Validate Service Name");
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Validate Service Name");
log.debug("get Service Audit Records failed with exception", e);
Response errorResponse = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -278,7 +279,6 @@ public class ServiceServlet extends AbstractValidationsServlet {
return response;
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Delete Service");
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Service");
log.debug("delete service failed with exception", e);
response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -315,7 +315,6 @@ public class ServiceServlet extends AbstractValidationsServlet {
return response;
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Delete Service");
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Service");
log.debug("delete service failed with exception", e);
response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -367,7 +366,6 @@ public class ServiceServlet extends AbstractValidationsServlet {
return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Update Service Metadata");
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Service Metadata");
log.debug("update service metadata failed with exception", e);
response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -375,6 +373,67 @@ public class ServiceServlet extends AbstractValidationsServlet {
}
}
+ /**
+ * 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}")
@@ -412,7 +471,6 @@ public class ServiceServlet extends AbstractValidationsServlet {
return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Service");
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Service");
log.debug("get service failed with exception", e);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -451,7 +509,6 @@ public class ServiceServlet extends AbstractValidationsServlet {
return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Service by name and version");
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Service by name and version");
log.debug("get service failed with exception", e);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -492,7 +549,6 @@ public class ServiceServlet extends AbstractValidationsServlet {
return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Update Service Distribution State");
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Service Distribution State");
log.debug("updateServiceDistributionState failed with exception", e);
response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -531,7 +587,6 @@ public class ServiceServlet extends AbstractValidationsServlet {
Object result = RepresentationUtils.toRepresentation(service);
return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Activate Distribution");
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Activate Distribution");
log.debug("activate distribution failed with exception", e);
response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -570,7 +625,6 @@ public class ServiceServlet extends AbstractValidationsServlet {
Object result = RepresentationUtils.toRepresentation(service);
return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Mark Distribution As Deployed");
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Mark Distribution As Deployed");
log.debug("mark distribution as deployed failed with exception", e);
response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -604,7 +658,6 @@ public class ServiceServlet extends AbstractValidationsServlet {
}
return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), null);
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "tempUrlToBeDeleted");
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("tempUrlToBeDeleted");
log.debug("failed with exception", e);
response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -621,12 +674,9 @@ public class ServiceServlet extends AbstractValidationsServlet {
@ApiResponse(code = 404, message = "Artifact not found") })
public Response downloadServiceArtifact(@PathParam("artifactName") final String artifactName, @Context final HttpServletRequest request) {
Response response = null;
- String instanceIdHeader = request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER);
- String requestURI = request.getRequestURI();
try {
log.debug("artifact name = {}", artifactName);
- ServletContext context = request.getSession().getServletContext();
Either<byte[], ResponseFormat> executeCommand = executeCommand(artifactName);
@@ -640,7 +690,7 @@ public class ServiceServlet extends AbstractValidationsServlet {
InputStream is = new ByteArrayInputStream(value);
Map<String, String> headers = new HashMap<>();
- String heatFileName = null;
+ String heatFileName;
if (artifactName.indexOf(".") > -1) {
heatFileName = artifactName.substring(0, artifactName.indexOf(".")) + ".heat";
} else {
@@ -653,7 +703,6 @@ public class ServiceServlet extends AbstractValidationsServlet {
return response;
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "download heat artifact");
log.error("download artifact failed with exception", e);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
}
@@ -671,8 +720,7 @@ public class ServiceServlet extends AbstractValidationsServlet {
heatTranslator = "/home/m98835/heat-translator-0.3.0/heat_translator.py";
}
- log.debug("toscaFilesDir={}", toscaFilesDir);
- log.debug("heatTranslator={}", heatTranslator);
+ log.debug("toscaFilesDir= {} | heatTranslator= {}", toscaFilesDir, heatTranslator);
StringBuffer output = new StringBuffer();
@@ -702,19 +750,19 @@ public class ServiceServlet extends AbstractValidationsServlet {
log.debug("waitFor = {}", waitFor);
if (waitFor != 0) {
- log.error("Failed running the command {}", command);
+ 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 = "";
+ String line;
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
}
} catch (Exception e) {
- log.error("Failed running the command {} {}", command, e);
+ log.error("Failed runnign the command {}", command, e);
e.printStackTrace();
return Either.right(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
}
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 0825a25cbe..6541da7e88 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
@@ -83,14 +83,13 @@ public class TypesFetchServlet extends AbstractValidationsServlet {
if (responseWrapper.isEmpty()) {
String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
- log.debug("modifier id is {}", userId);
+ 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());
+ log.info("Failed to get all dara types. Reason - {}", allDataTypes.right().value());
Response errorResponse = buildErrorResponse(allDataTypes.right().value());
responseWrapper.setInnerElement(errorResponse);
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 6ba8c521f1..1fcc0fd404 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
@@ -42,6 +42,8 @@ import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.codehaus.jackson.JsonGenerationException;
+import org.codehaus.jackson.map.JsonMappingException;
import org.glassfish.jersey.media.multipart.FormDataParam;
import org.openecomp.sdc.be.components.impl.CapabilityTypeImportManager;
import org.openecomp.sdc.be.components.impl.CategoriesImportManager;
@@ -105,13 +107,11 @@ public class TypesUploadServlet extends AbstractValidationsServlet {
@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") })
+ @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
@@ -120,9 +120,8 @@ public class TypesUploadServlet extends AbstractValidationsServlet {
@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") })
+ @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");
@@ -134,13 +133,11 @@ public class TypesUploadServlet extends AbstractValidationsServlet {
@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") })
+ @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
@@ -149,13 +146,11 @@ public class TypesUploadServlet extends AbstractValidationsServlet {
@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") })
+ @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
@@ -164,12 +159,10 @@ public class TypesUploadServlet extends AbstractValidationsServlet {
@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") })
+ @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());
}
@@ -179,14 +172,11 @@ public class TypesUploadServlet extends AbstractValidationsServlet {
@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") })
+ @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) {
@@ -221,7 +211,7 @@ public class TypesUploadServlet extends AbstractValidationsServlet {
return responseWrapper.getInnerElement();
} catch (Exception e) {
- log.debug("create {} failed with exception: {}", elementTypeName, e);
+ log.debug("create {} failed with exception:", elementTypeName, e);
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create " + elementTypeName);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
}
@@ -233,8 +223,13 @@ public class TypesUploadServlet extends AbstractValidationsServlet {
Response response = buildErrorResponse(eitherResult.right().value());
responseWrapper.setInnerElement(response);
} else {
- Response response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), eitherResult.left().value());
- responseWrapper.setInnerElement(response);
+ 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);
+ }
}
}
@@ -248,20 +243,16 @@ public class TypesUploadServlet extends AbstractValidationsServlet {
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) {
-
+ 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()) {
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 c700c31a64..a477bcf4fb 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
@@ -108,7 +108,7 @@ public class UserAdminServlet extends BeGenericServlet {
} catch (Exception e) {
BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get User");
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get User");
- log.debug("get user failed with unexpected error: {}", e);
+ log.debug("get user failed with unexpected error: {}", e.getMessage(), e);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
}
}
@@ -140,7 +140,7 @@ public class UserAdminServlet extends BeGenericServlet {
*
* @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,
+ * @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,
*
@@ -157,7 +157,7 @@ public class UserAdminServlet extends BeGenericServlet {
* 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);
+ * 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;
@@ -216,7 +216,7 @@ public class UserAdminServlet extends BeGenericServlet {
@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,
+ 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();
@@ -234,7 +234,7 @@ public class UserAdminServlet extends BeGenericServlet {
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());
+ Either<User, ResponseFormat> updateUserResponse = businessLogic.updateUserRole(modifier, userIdUpdateUser, updateInfoUser.getRole());
if (updateUserResponse.isRight()) {
log.debug("failed to update user role");
@@ -402,13 +402,12 @@ public class UserAdminServlet extends BeGenericServlet {
@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,
+ 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 {}", url);
- log.debug("modifier id is {}", userId);
+ log.debug("Start handle request of {} modifier id is {}", url, userId);
List<String> rolesList = new ArrayList<>();
if (roles != null && !roles.trim().isEmpty()) {
@@ -450,11 +449,10 @@ public class UserAdminServlet extends BeGenericServlet {
ServletContext context = request.getSession().getServletContext();
String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
+ log.debug("Start handle request of {} modifier id is {}", url, userIdHeader);
User modifier = new User();
modifier.setUserId(userIdHeader);
- log.debug("modifier id is {}", userIdHeader);
Response response = null;
try {
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 4027144911..876066b9ba 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
@@ -161,7 +161,7 @@ public class SwitchoverDetector {
if (message == null) {
message = e.getClass().getName();
}
- switchoverLogger.debug("Error occured during switchover detector query, Result is {}", message);
+ logger.debug("Error occured during switchover detector query, Result is {}", message, e);
}
}
if (null == result) {
@@ -178,14 +178,18 @@ public class SwitchoverDetector {
@Override
public void run() {
- switchoverLogger.trace("Executing Switchover Detector Task - Start");
+ logger.trace("Executing Switchover Detector Task - Start");
initializeSiteMode();
Boolean beRes = queryBe();
Boolean feRes = queryFe();
- Boolean updateRequired = siteMode == SwitchoverDetectorState.STANDBY.getState() && (beRes || feRes);
+ 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);
@@ -232,7 +236,8 @@ public class SwitchoverDetector {
if (message == null) {
message = e.getClass().getName();
}
- switchoverLogger.error("Error occured during change site priority request, Result is {}", message);
+
+ logger.debug("Error occured during change site priority request, Result is {}", message, e);
}
}
@@ -252,7 +257,8 @@ public class SwitchoverDetector {
if (message == null) {
message = e.getClass().getName();
}
- switchoverLogger.error("Error occured during publish network request, Result is {}", message);
+
+ logger.debug("Error occured during publish network request, Result is {}", message, e);
}
}
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 85b4493c8e..13356e5de4 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
@@ -24,6 +24,7 @@ import java.util.List;
import org.openecomp.sdc.generator.data.ArtifactType;
+
public class ArtifactTypes {
private List<ArtifactType> artifactTypes;
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 d1f2557413..b21e064a82 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
@@ -24,8 +24,11 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.stream.Collectors;
import org.apache.commons.lang3.tuple.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;
@@ -33,8 +36,6 @@ import org.openecomp.sdc.be.model.ComponentInstanceProperty;
import org.openecomp.sdc.be.model.DataTypeDefinition;
import org.openecomp.sdc.be.model.PropertyDefinition;
import org.openecomp.sdc.be.model.RequirementDefinition;
-import org.openecomp.sdc.be.resources.data.CapabilityData;
-import org.openecomp.sdc.be.resources.data.RequirementData;
import org.openecomp.sdc.be.tosca.model.SubstitutionMapping;
import org.openecomp.sdc.be.tosca.model.ToscaCapability;
import org.openecomp.sdc.be.tosca.model.ToscaNodeTemplate;
@@ -42,14 +43,18 @@ 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.common.util.ValidationUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import com.google.common.collect.Lists;
+
import fj.data.Either;
public class CapabiltyRequirementConvertor {
private static CapabiltyRequirementConvertor instance;
-
+ public final static String PATH_DELIMITER = ".";
+
protected CapabiltyRequirementConvertor() {
}
@@ -131,8 +136,8 @@ public class CapabiltyRequirementConvertor {
return Either.left(nodeType);
}
- public Either<SubstitutionMapping, ToscaError> convertRequirements(Component component, SubstitutionMapping substitutionMapping) {
- Map<String, ToscaRequirement> toscaRequirements = convertRequirementsAsMap(component);
+ public Either<SubstitutionMapping, ToscaError> convertSubstitutionMappingRequirements(Component component, SubstitutionMapping substitutionMapping) {
+ Map<String, String[]> toscaRequirements = convertSubstitutionMappingRequirementsAsMap(component);
if (!toscaRequirements.isEmpty()) {
substitutionMapping.setRequirements(toscaRequirements);
}
@@ -145,9 +150,9 @@ public class CapabiltyRequirementConvertor {
Map<String, List<RequirementDefinition>> requirements = component.getRequirements();
List<Map<String, ToscaRequirement>> toscaRequirements = new ArrayList<>();
if (requirements != null) {
- boolean isNodeType = ToscaUtils.isNodeType(component);
+ boolean isNodeType = ToscaUtils.isAtomicType(component);
for (Map.Entry<String, List<RequirementDefinition>> entry : requirements.entrySet()) {
- entry.getValue().stream().filter(r -> (!isNodeType || (isNodeType && component.getUniqueId().equals(r.getOwnerId())))).forEach(r -> {
+ entry.getValue().stream().filter(r -> (!isNodeType || (isNodeType && component.getUniqueId().equals(r.getOwnerId())) || (isNodeType && r.getOwnerId() == null))).forEach(r -> {
ImmutablePair<String, ToscaRequirement> pair = convertRequirement(component, isNodeType, r);
Map<String, ToscaRequirement> requirement = new HashMap<>();
@@ -163,17 +168,25 @@ public class CapabiltyRequirementConvertor {
return toscaRequirements;
}
- private Map<String, ToscaRequirement> convertRequirementsAsMap(Component component) {
+ private String getSubPathByFirstDelimiterAppearance(String path) {
+ return path.substring(path.indexOf(PATH_DELIMITER) + 1);
+ }
+
+ private String getSubPathByLastDelimiterAppearance(String path) {
+ return path.substring(path.lastIndexOf(PATH_DELIMITER) + 1);
+ }
+
+ //This function calls on Substitution Mapping region - the component is always non-atomic
+ private Map<String, String[]> convertSubstitutionMappingRequirementsAsMap(Component component) {
Map<String, List<RequirementDefinition>> requirements = component.getRequirements();
- Map<String, ToscaRequirement> toscaRequirements = new HashMap<>();
+ Map<String, String[]> toscaRequirements = new HashMap<>();
if (requirements != null) {
- boolean isNodeType = ToscaUtils.isNodeType(component);
for (Map.Entry<String, List<RequirementDefinition>> entry : requirements.entrySet()) {
- entry.getValue().stream().filter(r -> (!isNodeType || (isNodeType && component.getUniqueId().equals(r.getOwnerId())))).forEach(r -> {
- ImmutablePair<String, ToscaRequirement> pair = convertRequirement(component, isNodeType, r);
- toscaRequirements.put(pair.left, pair.right);
+ entry.getValue().stream().forEach(r -> {
+ String fullReqName = getRequirementPath(r);
+ log.debug("the requirement {} belongs to resource {} ", fullReqName, component.getUniqueId());
+ toscaRequirements.put(fullReqName, new String[]{r.getOwnerName(), getSubPathByFirstDelimiterAppearance(fullReqName)});
});
-
log.debug("Finish convert Requirements for node type");
}
} else {
@@ -182,17 +195,25 @@ public class CapabiltyRequirementConvertor {
return toscaRequirements;
}
+ private String getRequirementPath(RequirementDefinition r) {
+ List<String> pathArray = Lists.reverse(r.getPath().stream()
+ .map(path -> ValidationUtils.normalizeComponentInstanceName(getSubPathByLastDelimiterAppearance(path)))
+ .collect(Collectors.toList()));
+ return new StringBuilder().append(String.join(PATH_DELIMITER, pathArray)).append(PATH_DELIMITER).append(r.getName()).toString();
+
+ }
+
private ImmutablePair<String, ToscaRequirement> convertRequirement(Component component, boolean isNodeType, RequirementDefinition r) {
String name = r.getName();
if (!isNodeType) {
- name = r.getOwnerName() + "." + name;
+ name = getRequirementPath(r);
}
log.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(RequirementData.MAX_OCCURRENCES)) {
+ if (r.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
occurences.add(r.getMaxOccurrences());
} else {
occurences.add(Integer.valueOf(r.getMaxOccurrences()));
@@ -212,9 +233,9 @@ public class CapabiltyRequirementConvertor {
Map<String, List<CapabilityDefinition>> capabilities = component.getCapabilities();
Map<String, ToscaCapability> toscaCapabilities = new HashMap<>();
if (capabilities != null) {
- boolean isNodeType = ToscaUtils.isNodeType(component);
+ boolean isNodeType = ToscaUtils.isAtomicType(component);
for (Map.Entry<String, List<CapabilityDefinition>> entry : capabilities.entrySet()) {
- entry.getValue().stream().filter(c -> (!isNodeType || (isNodeType && component.getUniqueId().equals(c.getOwnerId())))).forEach(c -> {
+ entry.getValue().stream().filter(c -> (!isNodeType || (isNodeType && component.getUniqueId().equals(c.getOwnerId())) || (isNodeType && c.getOwnerId() == null) )).forEach(c -> {
convertCapabilty(component, toscaCapabilities, isNodeType, c, dataTypes);
});
@@ -225,11 +246,39 @@ public class CapabiltyRequirementConvertor {
return toscaCapabilities;
}
+
+ //This function calls on Substitution Mapping region - the component is always non-atomic
+ public Map<String, String[]> convertSubstitutionMappingCapabilities(Component component, Map<String, DataTypeDefinition> dataTypes) {
+ Map<String, List<CapabilityDefinition>> capabilities = component.getCapabilities();
+ Map<String, String[]> toscaCapabilities = new HashMap<>();
+ if (capabilities != null) {
+ for (Map.Entry<String, List<CapabilityDefinition>> entry : capabilities.entrySet()) {
+ entry.getValue().stream().forEach(c -> {
+ String fullCapName = getCapabilityPath(c);
+ log.debug("the capabilty {} belongs to resource {} ", fullCapName, component.getUniqueId());
+ toscaCapabilities.put(fullCapName, new String[]{c.getOwnerName(), getSubPathByFirstDelimiterAppearance(fullCapName)});
+ });
+ }
+ } else {
+ log.debug("No Capabilities for node type");
+ }
+ return toscaCapabilities;
+ }
+
+ private String getCapabilityPath(CapabilityDefinition c) {
+ List<String> pathArray = Lists.reverse(c.getPath().stream()
+ .map(path -> ValidationUtils.normalizeComponentInstanceName(getSubPathByLastDelimiterAppearance(path)))
+ .collect(Collectors.toList()));
+ return new StringBuilder().append(String.join(PATH_DELIMITER, pathArray)).append(PATH_DELIMITER).append(c.getName()).toString();
+ }
+
+
+
private void convertCapabilty(Component component, Map<String, ToscaCapability> toscaCapabilities, boolean isNodeType, CapabilityDefinition c, Map<String, DataTypeDefinition> dataTypes) {
String name = c.getName();
if (!isNodeType) {
- name = c.getOwnerName() + "." + name;
+ name = getCapabilityPath(c);
}
log.debug("the capabilty {} belongs to resource {} ", name, component.getUniqueId());
ToscaCapability toscaCapability = new ToscaCapability();
@@ -238,7 +287,7 @@ public class CapabiltyRequirementConvertor {
List<Object> occurences = new ArrayList<>();
occurences.add(Integer.valueOf(c.getMinOccurrences()));
- if (c.getMaxOccurrences().equals(CapabilityData.MAX_OCCURRENCES)) {
+ if (c.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES)) {
occurences.add(c.getMaxOccurrences());
} else {
occurences.add(Integer.valueOf(c.getMaxOccurrences()));
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 c8aa188e30..3c0c80666c 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CsarUtils.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CsarUtils.java
@@ -20,65 +20,98 @@
package org.openecomp.sdc.be.tosca;
+import java.io.File;
import java.io.IOException;
-import org.apache.commons.codec.binary.Base64;
-import java.util.Collection;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.EnumMap;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
+import java.util.Map.Entry;
import java.util.Set;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
+import java.util.zip.ZipException;
+import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
+import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
+import org.apache.commons.io.IOUtils;
import org.apache.commons.io.output.ByteArrayOutputStream;
+import org.apache.commons.lang.WordUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.apache.commons.lang3.tuple.ImmutableTriple;
import org.apache.commons.lang3.tuple.Triple;
import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperation;
+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;
import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
+import org.openecomp.sdc.be.config.Configuration.ArtifactTypeConfig;
+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.cassandra.SdcSchemaFilesCassandraDao;
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;
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.jsontitan.operations.ToscaOperationFacade;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
-import org.openecomp.sdc.be.model.operations.impl.ServiceOperation;
+import org.openecomp.sdc.be.model.operations.impl.LifecycleOperation;
import org.openecomp.sdc.be.resources.data.ESArtifactData;
+import org.openecomp.sdc.be.resources.data.ESSdcSchemaFilesData;
import org.openecomp.sdc.be.tosca.model.ToscaTemplate;
import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
+import org.openecomp.sdc.common.api.ArtifactTypeEnum;
+import org.openecomp.sdc.common.impl.ExternalConfiguration;
import org.openecomp.sdc.common.util.GeneralUtility;
import org.openecomp.sdc.common.util.ValidationUtils;
import org.openecomp.sdc.exception.ResponseFormat;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-
+import org.openecomp.sdc.generator.data.AdditionalParams;
import org.openecomp.sdc.generator.data.Artifact;
import org.openecomp.sdc.generator.data.ArtifactType;
import org.openecomp.sdc.generator.data.GenerationData;
import org.openecomp.sdc.generator.impl.ArtifactGenerationServiceImpl;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+
import com.google.gson.Gson;
import fj.data.Either;
+
/**
* @author tg851x
*
*/
@org.springframework.stereotype.Component("csar-utils")
public class CsarUtils {
- private static Logger log = LoggerFactory.getLogger(ToscaExportHandler.class.getName());
+ private static Logger log = LoggerFactory.getLogger(CsarUtils.class.getName());
@Autowired
+ private SdcSchemaFilesCassandraDao sdcSchemaFilesCassandraDao;
+ @Autowired
private ArtifactCassandraDao artifactCassandraDao;
@Autowired
private ComponentsUtils componentsUtils;
@@ -87,45 +120,68 @@ public class CsarUtils {
@Autowired
private ArtifactsBusinessLogic artifactsBusinessLogic;
@Autowired
- protected ServiceOperation serviceOperation;
+ protected ToscaOperationFacade toscaOperationFacade;
+
@javax.annotation.Resource
private ServiceBusinessLogic serviceBusinessLogic;
private Gson gson = new Gson();
- private static final String DEFINITIONS_PATH = "Definitions/";
- private static final String ARTIFACTS_PATH = "Artifacts/";
+ 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 VFC_NODE_TYPE_ARTIFACTS_PATH_PATTERN = ARTIFACTS_PATH + ImportUtils.Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + "([\\w\\_\\-\\.\\s]+)(/)([\\w\\_\\-\\.\\s]+)(/)([\\w\\_\\-\\.\\s\\/]+)";
+
+ public static final String VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN = ARTIFACTS_PATH +
+ // Artifact Group (i.e Deployment/Informational)
+ "([\\w\\_\\-\\.\\s]+)(/)" +
+ // Artifact Type
+ "([\\w\\_\\-\\.\\s]+)(/)" +
+ // Artifact File Name
+ "([\\w\\_\\-\\.\\s]+)";
+ public static final String ARTIFACT_CREATED_FROM_CSAR = "Artifact created from csar";
+
/**
*
* @param component
* @param getFromCS
* @param isInCertificationRequest
- * @param shouldLock
- * @param inTransaction
* @return
*/
- public Either<byte[], ResponseFormat> createCsar(Component component, boolean getFromCS, boolean isInCertificationRequest, boolean shouldLock, boolean inTransaction) {
- return createCsar(component, getFromCS, isInCertificationRequest, false, shouldLock, inTransaction);
+ 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, boolean shouldLock, boolean inTransaction) {
- final String CREATED_BY = component.getCreatorFullName();
+ 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 toscaBlock0 = createToscaBlock0(TOSCA_META_VERSION, CSAR_VERSION, CREATED_BY, fileName);
-
+ 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(toscaBlock0Byte, component, getFromCS, isInCertificationRequest, mockGenerator, shouldLock, inTransaction);
+ Either<byte[], ResponseFormat> generateCsarZipResponse = generateCsarZip(csarBlock0Byte, toscaBlock0Byte, component, getFromCS, isInCertificationRequest, mockGenerator);
if (generateCsarZipResponse.isRight()) {
return Either.right(generateCsarZipResponse.right().value());
@@ -134,64 +190,50 @@ public class CsarUtils {
return Either.left(generateCsarZipResponse.left().value());
}
- private Either<byte[], ResponseFormat> generateCsarZip(byte[] toscaBlock0Byte, Component component, boolean getFromCS, boolean isInCertificationRequest, boolean mockGenerator, boolean shouldLock, boolean inTransaction) {
-
- ZipOutputStream zip = null;
- ByteArrayOutputStream out = null;
- try {
- out = new ByteArrayOutputStream();
- zip = new ZipOutputStream(out);
-
+ 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, shouldLock, inTransaction);
+ 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 = populateZip.left().value();
zip.finish();
byte[] byteArray = out.toByteArray();
return Either.left(byteArray);
} catch (IOException e) {
- log.debug("createCsar failed 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);
- } finally {
- try {
- if (zip != null) {
- zip.close();
- }
- if (out != null) {
- out.close();
- }
- } catch (Exception e) {
- log.error("Failed to close resources ", e);
- }
}
}
- private Either<ZipOutputStream, ResponseFormat> populateZip(Component component, boolean getFromCS, ZipOutputStream zip, boolean isInCertificationRequest, boolean mockGenerator, boolean shouldLock, boolean inTransaction) {
+ private Either<ZipOutputStream, ResponseFormat> populateZip(Component component, boolean getFromCS, ZipOutputStream zip, boolean isInCertificationRequest, boolean mockGenerator) throws IOException {
LifecycleStateEnum lifecycleState = component.getLifecycleState();
- String componentYaml = null;
- Either<ToscaRepresentation, ToscaError> exportComponent = null;
- byte[] mainYaml = null;
- // <file name, esid, component>
+ 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<>();
- String fileName;
Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
- fileName = artifactDefinition.getArtifactName();
+ String fileName = artifactDefinition.getArtifactName();
if (getFromCS || !(lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) {
- String esId = artifactDefinition.getEsId();
- Either<byte[], ActionStatus> fromCassandra = getFromCassandra(esId);
+ String cassandraId = artifactDefinition.getEsId();
+ Either<byte[], ActionStatus> fromCassandra = getFromCassandra(cassandraId);
if (fromCassandra.isRight()) {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(fromCassandra.right().value());
return Either.right(responseFormat);
@@ -212,147 +254,214 @@ public class CsarUtils {
dependencies = exportResult.getDependencies();
}
- try {
- zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + fileName));
- zip.write(mainYaml);
+ zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + fileName));
+ zip.write(mainYaml);
+ //US798487 - Abstraction of complex types
+ if (!ToscaUtils.isAtomicType(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));
+ 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);
+ 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);
}
- dependencies = dependenciesRes.left().value().getDependencies();
- }
- if (dependencies != null && !dependencies.isEmpty()) {
- for (Triple<String, String, Component> d : dependencies) {
- String esId = d.getMiddle();
- Component childComponent = d.getRight();
- fileName = d.getLeft();
- Either<byte[], ActionStatus> entryData = getEntryData(esId, childComponent);
-
- if (entryData.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(entryData.right().value());
- return Either.right(responseFormat);
- }
+ //fill innerComponentsCache
+ fileName = d.getLeft();
+ innerComponentsCache.put(childComponent.getUniqueId(),
+ new ImmutableTriple<String, String, Component>(cassandraId, fileName, childComponent));
+ insertInnerComponentsToCache(innerComponentsCache, childComponent);
+
byte[] content = entryData.left().value();
- zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + fileName));
- zip.write(content);
-
generatorInputs.add(new ImmutablePair<Component, byte[]>(childComponent, content));
}
- }
-
- List<ArtifactDefinition> aiiArtifactList = new LinkedList<>();
- // Artifact Generation
- if (component.getComponentType() == ComponentTypeEnum.SERVICE && (lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) {
- Either<List<ArtifactDefinition>, ResponseFormat> handleAAIArtifacts = handleAAIArtifacts(component, zip, mockGenerator, shouldLock, inTransaction, generatorInputs);
+
+ //add inner components to CSAR
+ innerComponentsCache.forEach((childUid, innerComponentTriple) -> {
+ Component innerComponent = innerComponentTriple.getRight();
+ String icFileName = innerComponentTriple.getMiddle();
+
+ try {
+ //add component to zip
+ Either<byte[], ActionStatus> entryData = getEntryData(innerComponentTriple.getLeft(), innerComponent);
+ byte[] content = entryData.left().value();
+ zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + icFileName));
+ zip.write(content);
+
+ } catch (IOException e) {
- 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, shouldLock, inTransaction);
-
- if (handleAllAAIArtifactsInDataModel.isRight()) {
- log.debug("AAI Artifacts handling (create, update, delete) failed");
- return Either.right(handleAllAAIArtifactsInDataModel.right().value());
}
- }
+ //add component interface to zip
+ if(!ToscaUtils.isAtomicType(innerComponent)) {
+ writeComponentInterface(innerComponent, zip, icFileName);
+ }
+ });
+ }
+
+ /*Either<byte[], ActionStatus> latestSchemaFilesFromCassandra = getLatestSchemaFilesFromCassandra();
+
+ if(latestSchemaFilesFromCassandra.isRight()){
+ return null;
+ }*/
+
+ //TODO Tal G this is quick solution until Cassandra US is alligned
+ Either<ZipOutputStream, ResponseFormat> addSchemaFilesFromConfig = addSchemaFilesFromConfig(zip);
+
+ if(addSchemaFilesFromConfig.isRight()){
+ return addSchemaFilesFromConfig;
+ }
+
+ // 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());
}
- // Collecting All Deployment Artifacts
- Either<ZipOutputStream, ActionStatus> collectAndWriteToScarDeploymentArtifacts = collectAndWriteToScarDeploymentArtifacts(zip, component, aiiArtifactList);
+ if (isInCertificationRequest) {
+ Either<ActionStatus, ResponseFormat> handleAllAAIArtifactsInDataModel = handleAllAAIArtifactsInDataModel(
+ component, aiiArtifactList, false, true);
- if (collectAndWriteToScarDeploymentArtifacts.isRight()) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ if (handleAllAAIArtifactsInDataModel.isRight()) {
+ log.debug("AAI Artifacts handling (create, update, delete) failed");
+ return Either.right(handleAllAAIArtifactsInDataModel.right().value());
+ }
}
- } catch (IOException e) {
- log.debug("Failed to create CSAR zip for component {}", component.getUniqueId(), e);
- }
-
- return Either.left(zip);
- }
- private Either<ZipOutputStream, ActionStatus> collectAndWriteToScarDeploymentArtifacts(ZipOutputStream zip, Component component, List<ArtifactDefinition> aiiArtifactList) throws IOException {
-
- Collection<ArtifactDefinition> deploymentArtifactsToAdd = null;
- Collection<ArtifactDefinition> allArtifactsToAdd = new LinkedList<>();
+ }
- if (component.getComponentType() == ComponentTypeEnum.SERVICE) {
- Either<Service, StorageOperationStatus> getServiceResponse = serviceOperation.getService(component.getUniqueId());
+ Either<CsarDefinition, ResponseFormat> collectedComponentCsarDefinition = collectComponentCsarDefinition(component);
- if (getServiceResponse.isLeft()) {
- Service service = getServiceResponse.left().value();
+ if (collectedComponentCsarDefinition.isRight()) {
+ return Either.right(collectedComponentCsarDefinition.right().value());
+ }
+
+ return writeAllFilesToScar(component, collectedComponentCsarDefinition.left().value(), zip, isInCertificationRequest);
+ }
- if (!aiiArtifactList.isEmpty()) {
- deploymentArtifactsToAdd = service.getDeploymentArtifacts().values().stream().filter(e -> e.getGenerated() == null || !e.getGenerated()).collect(Collectors.toList());
- allArtifactsToAdd.addAll(aiiArtifactList);
- allArtifactsToAdd.addAll(deploymentArtifactsToAdd);
- } else {
- allArtifactsToAdd.addAll(service.getDeploymentArtifacts().values());
- }
+ private Either<ZipOutputStream, ResponseFormat> addSchemaFilesFromConfig(ZipOutputStream zip) throws ZipException, IOException {
+ final String pathAndFile = "config/SDC.zip";
+
+ File file = new File(pathAndFile);
+ if(!file.exists()){
+ log.debug("SDC.zip schema files archive not found");
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+
+ try(ZipFile zipFile = new ZipFile(new File(pathAndFile));){
+ Enumeration<? extends ZipEntry> entries = zipFile.entries();
+
+ while(entries.hasMoreElements()){
+ ZipEntry nextElement = entries.nextElement();
+ InputStream inputStream = zipFile.getInputStream(nextElement);
+ byte[] byteArray = IOUtils.toByteArray(inputStream);
+
+ zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + nextElement.getName()));
+ zip.write(byteArray);
}
+ zipFile.close();
+ }catch (Exception e) {
+ log.debug("Error in writing SDC.zip schema files to CSAR");
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
}
+
+ return Either.left(zip);
+ }
- if (!allArtifactsToAdd.isEmpty()) {
-
- for (ArtifactDefinition deploymentArtifactDefinition : allArtifactsToAdd) {
- String artifactFileName = deploymentArtifactDefinition.getArtifactName();
- byte[] payloadData = deploymentArtifactDefinition.getPayloadData();
-
- if (payloadData == null) {
- String esId = deploymentArtifactDefinition.getEsId();
- if (esId != null) {
- Either<byte[], ActionStatus> fromCassandra = getFromCassandra(esId);
-
- if (fromCassandra.isRight()) {
- return Either.right(fromCassandra.right().value());
- }
- payloadData = fromCassandra.left().value();
- } else {
- log.debug("Artifact {} payload not supplied in ArtifactDefinition and not found in DB", artifactFileName);
- continue;
+ private void insertInnerComponentsToCache(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
+ componentCache.put(ci.getComponentUid(),
+ new ImmutableTriple<String, String, Component>(childArtifactDefinition.getEsId(),
+ childArtifactDefinition.getArtifactName(), componentRI));
}
- }
-
- byte[] decodedPayload = null;
- if (Base64.isBase64(payloadData)) {
- // decodedPayload = Base64.getDecoder().decode(payloadData);
- decodedPayload = Base64.decodeBase64(payloadData);
- } else {
- decodedPayload = payloadData;
+ //if not atomic - insert inner components as well
+ if(!ToscaUtils.isAtomicType(componentRI)) {
+ insertInnerComponentsToCache(componentCache, componentRI);
+ }
}
-
- zip.putNextEntry(new ZipEntry(ARTIFACTS_PATH + artifactFileName));
- zip.write(decodedPayload);
- }
+ });
}
-
+ }
+
+ 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, ZipOutputStream zip, boolean mockGenerator, boolean shouldLock, boolean inTransaction, List<ImmutablePair<Component, byte[]>> generatorInputs) {
+
+ private Either<List<ArtifactDefinition>, ResponseFormat> handleAAIArtifacts(Component component, boolean mockGenerator, List<ImmutablePair<Component, byte[]>> generatorInputs) {
ComponentTypeEnum componentType = component.getComponentType();
- List<Artifact> generatedArtifacts = null;
- List<ArtifactDefinition> aaiArtifacts = null;
+ List<Artifact> generatedArtifacts;
+ List<ArtifactDefinition> aaiArtifacts = new LinkedList<>();
if (componentType == ComponentTypeEnum.SERVICE && !generatorInputs.isEmpty()) {
List<Artifact> convertedGeneratorInputs = convertToGeneratorArtifactsInput(generatorInputs);
- Either<List<Artifact>, ResponseFormat> generatorResponse;
+ Either<List<Artifact>, String> generatorResponse;
if (mockGenerator) {
generatorResponse = artifactGenerator(convertedGeneratorInputs, ArtifactType.OTHER, component);
@@ -361,7 +470,7 @@ public class CsarUtils {
}
if (generatorResponse.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.AAI_ARTIFACT_GENERATION_FAILED, component.getComponentType().getValue(), component.getName(), generatorResponse.toString());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.AAI_ARTIFACT_GENERATION_FAILED, component.getComponentType().getValue(), component.getName(), generatorResponse.right().value());
return Either.right(responseFormat);
}
@@ -376,8 +485,8 @@ public class CsarUtils {
private Either<ActionStatus, ResponseFormat> handleAllAAIArtifactsInDataModel(Component component, List<ArtifactDefinition> artifactsFromAAI, boolean shouldLock, boolean inTransaction) {
- Either<ActionStatus, ResponseFormat> handleAAIArtifactsResponse = null;
- User lastComponentUpdater = null;
+ Either<ActionStatus, ResponseFormat> handleAAIArtifactsResponse;
+ User lastComponentUpdater;
List<ArtifactDefinition> aaiArtifatcsToCreate = getAAIArtifatcsForCreate(artifactsFromAAI, component);
List<ArtifactDefinition> aaiArtifatcsToDelete = getAAIArtifatcsForDelete(artifactsFromAAI, component);
@@ -393,19 +502,21 @@ public class CsarUtils {
lastComponentUpdater = validateUserExists.left().value();
- handleAAIArtifactsResponse = handleAAIArtifactsInDataModelByOperationType(component, aaiArtifatcsToDelete, ArtifactOperation.Delete, lastComponentUpdater, shouldLock, inTransaction);
+ handleAAIArtifactsResponse = handleAAIArtifactsInDataModelByOperationType(component, aaiArtifatcsToDelete, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Delete), lastComponentUpdater, shouldLock,
+ inTransaction);
if (handleAAIArtifactsResponse.isRight()) {
return handleAAIArtifactsResponse;
}
- handleAAIArtifactsResponse = handleAAIArtifactsInDataModelByOperationType(component, aaiArtifatcsToCreate, ArtifactOperation.Create, lastComponentUpdater, shouldLock, inTransaction);
+ handleAAIArtifactsResponse = handleAAIArtifactsInDataModelByOperationType(component, aaiArtifatcsToCreate, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create), lastComponentUpdater, shouldLock,
+ inTransaction);
if (handleAAIArtifactsResponse.isRight()) {
return handleAAIArtifactsResponse;
}
- return handleAAIArtifactsInDataModelByOperationType(component, aaiArtifatcsToUpdate, ArtifactOperation.Update, lastComponentUpdater, shouldLock, inTransaction);
+ return handleAAIArtifactsInDataModelByOperationType(component, aaiArtifatcsToUpdate, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Update), lastComponentUpdater, shouldLock, inTransaction);
}
private List<ArtifactDefinition> getAAIArtifatcsForUpdate(List<ArtifactDefinition> artifactsFromAAI, Component component) {
@@ -413,10 +524,10 @@ public class CsarUtils {
Set<String> componetDeploymentArtifactLables = component.getDeploymentArtifacts().keySet();
Set<String> componetInformationalArtifactLables = component.getArtifacts().keySet();
- List<ArtifactDefinition> artifactsAaiUpdate = artifactsFromAAI.stream().filter(e -> (componetDeploymentArtifactLables.contains(e.getArtifactLabel()) || componetInformationalArtifactLables.contains(e.getArtifactLabel())))
- .filter(e -> checkAaiForUpdate(component, e)).collect(Collectors.toList());
-
- return artifactsAaiUpdate;
+ 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) {
@@ -446,21 +557,27 @@ public class CsarUtils {
private List<ArtifactDefinition> getAAIArtifatcsForDelete(List<ArtifactDefinition> artifactsFromAAI, Component component) {
- Set<String> aaiLabels = artifactsFromAAI.stream().map(e -> e.getArtifactLabel()).collect(Collectors.toSet());
+ Set<String> aaiLabels = artifactsFromAAI.stream()
+ .map(ArtifactDefinition::getArtifactLabel)
+ .collect(Collectors.toSet());
- List<ArtifactDefinition> artifactsForDeleteDeployment = component.getDeploymentArtifacts().values().stream().
+ 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());
+ .filter(e -> !aaiLabels.contains(e.getArtifactLabel()))
+ .collect(Collectors.toList());
- List<ArtifactDefinition> artifactsForDeleteInformational = component.getArtifacts().values().stream().
+ 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());
+ .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());
+ 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) {
@@ -470,10 +587,12 @@ public class CsarUtils {
// 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());
+ 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, ArtifactOperation operationType, User user, boolean shouldLock,
+ private Either<ActionStatus, ResponseFormat> handleAAIArtifactsInDataModelByOperationType(Component component, List<ArtifactDefinition> generatedArtifactsDefinitions, ArtifactOperationInfo operationType, User user, boolean shouldLock,
boolean inTransaction) {
String componentUniqueId = component.getUniqueId();
@@ -484,7 +603,7 @@ public class CsarUtils {
String dataMD5 = GeneralUtility.calculateMD5ByString(data);
String artifactUniqueId = null;
- if (operationType.equals(ArtifactOperation.Update) || operationType.equals(ArtifactOperation.Delete)) {
+ if ((operationType.getArtifactOperationEnum() == ArtifactOperationEnum.Update) || (operationType.getArtifactOperationEnum() == ArtifactOperationEnum.Delete)) {
String artifactLabel = artDef.getArtifactLabel();
ArtifactDefinition artifactDefinition = component.getDeploymentArtifacts().get(artifactLabel);
if (artifactDefinition != null) {
@@ -496,7 +615,7 @@ public class CsarUtils {
null, null, user, component, shouldLock, inTransaction);
if (validateAndHandleArtifact.isRight()) {
- if (ArtifactOperation.Create == operationType || ArtifactOperation.Update == operationType) {
+ if (ArtifactOperationEnum.Create == 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);
@@ -522,7 +641,7 @@ public class CsarUtils {
// Normalizing the artifact label to match those stored in DB
String normalizeArtifactLabel = ValidationUtils.normalizeArtifactLabel(artifact.getLabel());
newEntry.setArtifactLabel(normalizeArtifactLabel);
- newEntry.setPayload(artifact.getPayload());
+ 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);
@@ -551,7 +670,6 @@ public class CsarUtils {
byte[] right = triple.getRight();
// The md5 calculated on the uncoded data
String md5Hex = DigestUtils.md5Hex(right);
- // byte[] payload = Base64.getEncoder().encode(right);
byte[] payload = Base64.encodeBase64(right);
String artifactVersion = artifactDefinition.getArtifactVersion();
@@ -567,9 +685,9 @@ public class CsarUtils {
return listOfArtifactsInput;
}
- private Either<byte[], ActionStatus> getEntryData(String esId, Component childComponent) {
+ private Either<byte[], ActionStatus> getEntryData(String cassandraId, Component childComponent) {
byte[] content;
- if (esId == null || esId.isEmpty()) {
+ 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());
@@ -577,7 +695,7 @@ public class CsarUtils {
}
content = exportRes.left().value().getMainYaml().getBytes();
} else {
- Either<byte[], ActionStatus> fromCassandra = getFromCassandra(esId);
+ Either<byte[], ActionStatus> fromCassandra = getFromCassandra(cassandraId);
if (fromCassandra.isRight()) {
return Either.right(fromCassandra.right().value());
} else {
@@ -586,13 +704,36 @@ public class CsarUtils {
}
return Either.left(content);
}
-
- private Either<byte[], ActionStatus> getFromCassandra(String esId) {
- Either<ESArtifactData, CassandraOperationStatus> artifactResponse = artifactCassandraDao.getArtifact(esId);
+
+ private Either<byte[], ActionStatus> getLatestSchemaFilesFromCassandra() {
+ Matcher matcher = Pattern.compile("(?!\\.)(\\d+(\\.\\d+)+)(?![\\d\\.])").matcher(SDC_VERSION);
+ matcher.find();
+ final String VERSION_FIRST_THREE_OCTATES = matcher.group(0);
+ Either<List<ESSdcSchemaFilesData>, ActionStatus> specificSchemaFiles = sdcSchemaFilesCassandraDao.getSpecificSchemaFiles(VERSION_FIRST_THREE_OCTATES, CONFORMANCE_LEVEL);
+
+ if(specificSchemaFiles.isRight()){
+ log.debug("Failed to get the schema files SDC-Version: {} Conformance-Level {}", VERSION_FIRST_THREE_OCTATES, CONFORMANCE_LEVEL);
+ return Either.right(specificSchemaFiles.right().value());
+ }
+
+ List<ESSdcSchemaFilesData> listOfSchemas = specificSchemaFiles.left().value();
+
+ if(listOfSchemas.isEmpty()){
+ log.debug("Failed to get the schema files SDC-Version: {} Conformance-Level {}", VERSION_FIRST_THREE_OCTATES, CONFORMANCE_LEVEL);
+ return Either.right(ActionStatus.GENERAL_ERROR);
+ }
+
+ ESSdcSchemaFilesData 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("In createCsar fetching of artifact from CS failed");
- log.debug("Failed to fetch from Cassandra by id {} error {} ", esId, artifactResponse.right().value());
+ log.debug("Failed to fetch from Cassandra by id {} error {} ", cassandraId, artifactResponse.right().value());
StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactResponse.right().value());
ActionStatus convertedFromStorageResponse = componentsUtils.convertFromStorageResponse(storageStatus);
@@ -603,14 +744,20 @@ public class CsarUtils {
}
}
-
- private String createToscaBlock0(String metaFileVersion, String csarVersion, String createdBy, String entryDef) {
- final String BLOCK_0_TEMPLATE = "TOSCA-Meta-File-Version: %s\nCSAR-Version: %s\nCreated-By: %s\nEntry-Definitions: Definitions/%s\n";
- String readyBlock = String.format(BLOCK_0_TEMPLATE, metaFileVersion, csarVersion, createdBy, entryDef);
+
+ 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>, ResponseFormat> artifactGenerator(List<Artifact> artifactList, ArtifactType type, Component component) {
+ private Either<List<Artifact>, String> artifactGenerator(List<Artifact> artifactList, ArtifactType type, Component component) {
ArtifactGenerationServiceImpl artifactGenerationServiceImpl = new ArtifactGenerationServiceImpl();
ArtifactTypes artifactTypes = new ArtifactTypes();
@@ -627,23 +774,739 @@ public class CsarUtils {
artifactTypes.setArtifactTypes(artifactTypesList);
String configJson = gson.toJson(artifactTypes);
- GenerationData generatedArtifacts = artifactGenerationServiceImpl.generateArtifact(artifactList, configJson);
+ 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(LifecycleOperation.VERSION_DELIMETER_REGEXP);
+ Integer majorVersion = Integer.parseInt(versionParts[0]);
+
+ version = (majorVersion + 1) + LifecycleOperation.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);
}
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.AAI_ARTIFACT_GENERATION_FAILED, component.getComponentType().getValue(), component.getName(), errorData.toString());
- return Either.right(responseFormat);
+ 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.calculateMD5ByByteArray(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.calculateMD5ByByteArray(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)){
+ continue;
+ }
+
+ String esId = artifactDefinition.getEsId();
+ byte[] payloadData = artifactDefinition.getPayloadData();
+ String artifactFileName = artifactDefinition.getArtifactName();
+
+ if (payloadData == null) {
+ Either<byte[], ActionStatus> fromCassandra = getFromCassandra(esId);
+
+ if (fromCassandra.isRight()) {
+ 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 544b85361d..af3b73dc97 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
@@ -71,11 +71,10 @@ public class PropertyConvertor {
Map<String, ToscaProperty> properties = new HashMap<>();
// take only the properties of this resource
- props.stream().filter(p -> component.getUniqueId().equals(p.getParentUniqueId())).forEach(property -> {
+ props.stream().filter(p -> p.getOwnerId() == null || p.getOwnerId().equals(component.getUniqueId())).forEach(property -> {
ToscaProperty prop = convertProperty(dataTypes, property, false);
properties.put(property.getName(), prop);
-
});
if (!properties.isEmpty()) {
toscaNodeType.setProperties(properties);
@@ -172,7 +171,7 @@ public class PropertyConvertor {
if (innerConverter != null) {
convertedValue = innerConverter.convertToToscaValue(value, innerType, dataTypes);
} else {
- convertedValue = mapConverterInst.convertDataTypeToToscaMap(innerType, dataTypes, innerConverter, isScalar, jsonElement);
+ convertedValue = mapConverterInst.convertDataTypeToToscaObject(innerType, dataTypes, innerConverter, isScalar, jsonElement);
}
}
}
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 1bf940ffc0..072861ba3a 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
@@ -25,36 +25,44 @@ import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashSet;
-import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
+import java.util.function.Supplier;
import java.util.stream.Collectors;
+import org.apache.commons.collections.CollectionUtils;
+import org.apache.commons.collections.MapUtils;
+import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.ImmutableTriple;
import org.apache.commons.lang3.tuple.Triple;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
-import org.openecomp.sdc.be.datamodel.utils.ArtifactUtils;
import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
+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.ComponentInstanceInput;
import org.openecomp.sdc.be.model.ComponentInstanceProperty;
import org.openecomp.sdc.be.model.DataTypeDefinition;
import org.openecomp.sdc.be.model.GroupDefinition;
+import org.openecomp.sdc.be.model.GroupInstance;
import org.openecomp.sdc.be.model.GroupProperty;
import org.openecomp.sdc.be.model.InputDefinition;
+import org.openecomp.sdc.be.model.PropertyDefinition;
import org.openecomp.sdc.be.model.RequirementAndRelationshipPair;
import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
import org.openecomp.sdc.be.model.RequirementDefinition;
import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.Service;
import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
import org.openecomp.sdc.be.model.category.CategoryDefinition;
-import org.openecomp.sdc.be.model.operations.api.IResourceOperation;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.model.tosca.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;
@@ -67,7 +75,6 @@ import org.openecomp.sdc.be.tosca.model.ToscaTemplate;
import org.openecomp.sdc.be.tosca.model.ToscaTemplateRequirement;
import org.openecomp.sdc.be.tosca.model.ToscaTopolgyTemplate;
import org.openecomp.sdc.be.tosca.model.VfModuleToscaMetadata;
-import org.openecomp.sdc.common.api.ArtifactTypeEnum;
import org.openecomp.sdc.common.api.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -94,31 +101,56 @@ public class ToscaExportHandler {
private ApplicationDataTypeCache dataTypeCache;
@Autowired
- private IResourceOperation resourceOperation;
+ private ToscaOperationFacade toscaOperationFacade;
private CapabiltyRequirementConvertor capabiltyRequirementConvertor = CapabiltyRequirementConvertor.getInstance();
private PropertyConvertor propertyConvertor = PropertyConvertor.getInstance();
+
private static Logger log = LoggerFactory.getLogger(ToscaExportHandler.class.getName());
public static final String TOSCA_VERSION = "tosca_simple_yaml_1_0";
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";
-
+ public 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) {
+ 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);
@@ -127,7 +159,6 @@ public class ToscaExportHandler {
options.setDefaultFlowStyle(FlowStyle.FLOW);
options.setCanonical(false);
- ToscaTemplate toscaTemplate = toscaTemplateRes.left().value();
representer.addClassTag(toscaTemplate.getClass(), Tag.MAP);
representer.setPropertyUtils(new UnsortedPropertyUtils());
@@ -143,13 +174,14 @@ public class ToscaExportHandler {
ToscaRepresentation toscaRepresentation = new ToscaRepresentation();
toscaRepresentation.setMainYaml(sb.toString());
toscaRepresentation.setDependencies(toscaTemplate.getDependencies());
-
- return Either.left(toscaRepresentation);
+
+ 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);
+ Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> fillImports = fillImports(component,
+ toscaTemplate);
if (fillImports.isRight()) {
return Either.right(fillImports.right().value());
}
@@ -157,17 +189,17 @@ public class ToscaExportHandler {
}
private Either<ToscaTemplate, ToscaError> convertToToscaTemplate(Component component) {
- log.debug("start tosca export for {}", component.getUniqueId());
+ log.trace("start tosca export for {}", component.getUniqueId());
ToscaTemplate toscaTemplate = new ToscaTemplate(TOSCA_VERSION);
- toscaTemplate.setMetadata(convertMetadata(component, false));
-
- Map<String, ToscaNodeType> node_types = new HashMap<>();
- if (ToscaUtils.isNodeType(component)) {
- log.debug("convert component as node type");
- return convertNodeType(component, toscaTemplate, node_types);
+ toscaTemplate.setMetadata(convertMetadata(component));
+ toscaTemplate.setImports(new ArrayList<>(DEFAULT_IMPORTS));
+ Map<String, ToscaNodeType> nodeTypes = new HashMap<>();
+ if (ToscaUtils.isAtomicType(component)) {
+ log.trace("convert component as node type");
+ return convertNodeType(component, toscaTemplate, nodeTypes);
} else {
- log.debug("convert component as topology template");
+ log.trace("convert component as topology template");
return convertToscaTemplate(component, toscaTemplate);
}
@@ -175,7 +207,8 @@ public class ToscaExportHandler {
private Either<ToscaTemplate, ToscaError> convertToscaTemplate(Component component, ToscaTemplate toscaNode) {
- Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> importsRes = fillImports(component, toscaNode);
+ Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> importsRes = fillImports(component,
+ toscaNode);
if (importsRes.isRight()) {
return Either.right(importsRes.right().value());
}
@@ -189,47 +222,50 @@ public class ToscaExportHandler {
}
Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
- ToscaTopolgyTemplate topology_template = new ToscaTopolgyTemplate();
+ ToscaTopolgyTemplate topologyTemplate = new ToscaTopolgyTemplate();
- Either<ToscaTopolgyTemplate, ToscaError> inputs = fillInputs(component, topology_template, dataTypes);
+ Either<ToscaTopolgyTemplate, ToscaError> inputs = fillInputs(component, topologyTemplate, dataTypes);
if (inputs.isRight()) {
return Either.right(inputs.right().value());
}
- topology_template = inputs.left().value();
+ topologyTemplate = inputs.left().value();
List<ComponentInstance> componentInstances = component.getComponentInstances();
- Map<String, List<ComponentInstanceProperty>> componentInstancesProperties = component.getComponentInstancesProperties();
+ Map<String, List<ComponentInstanceProperty>> componentInstancesProperties = component
+ .getComponentInstancesProperties();
List<GroupDefinition> groups = component.getGroups();
if (componentInstances != null && !componentInstances.isEmpty()) {
- Either<Map<String, ToscaNodeTemplate>, ToscaError> node_templates = convertNodeTemplates(component, componentInstances, componentInstancesProperties, componentCache, dataTypes);
- if (node_templates.isRight()) {
- return Either.right(node_templates.right().value());
+ 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");
- topology_template.setNode_templates(node_templates.left().value());
+ topologyTemplate.setNode_templates(nodeTemplates.left().value());
}
+ Map<String, ToscaGroupTemplate> groupsMap = null;
if (groups != null && !groups.isEmpty()) {
- Map<String, ToscaGroupTemplate> groupsMap = new HashMap<String, ToscaGroupTemplate>();
+ groupsMap = new HashMap<String, ToscaGroupTemplate>();
for (GroupDefinition group : groups) {
- ToscaGroupTemplate toscaGroup = convertGroup(group, component);
+ ToscaGroupTemplate toscaGroup = convertGroup(group);
groupsMap.put(group.getName(), toscaGroup);
}
- topology_template.setGroups(groupsMap);
log.debug("groups converted");
-
+ topologyTemplate.addGroups(groupsMap);
}
-
SubstitutionMapping substitutionMapping = new SubstitutionMapping();
String toscaResourceName = null;
switch (component.getComponentType()) {
case RESOURCE:
- toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition().getMetadataDataDefinition()).getToscaResourceName();
+ toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition()
+ .getMetadataDataDefinition()).getToscaResourceName();
break;
case SERVICE:
- toscaResourceName = SERVICE_NODE_TYPE_PREFIX + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName();
+ toscaResourceName = SERVICE_NODE_TYPE_PREFIX
+ + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName();
break;
default:
log.debug("Not supported component type {}", component.getComponentType());
@@ -237,25 +273,27 @@ public class ToscaExportHandler {
}
substitutionMapping.setNode_type(toscaResourceName);
- Either<SubstitutionMapping, ToscaError> capabilities = convertCapabilities(component, substitutionMapping, dataTypes);
+ Either<SubstitutionMapping, ToscaError> capabilities = convertCapabilities(component, substitutionMapping,
+ dataTypes);
if (capabilities.isRight()) {
return Either.right(capabilities.right().value());
}
substitutionMapping = capabilities.left().value();
- Either<SubstitutionMapping, ToscaError> requirements = capabiltyRequirementConvertor.convertRequirements(component, substitutionMapping);
+ Either<SubstitutionMapping, ToscaError> requirements = capabiltyRequirementConvertor.convertSubstitutionMappingRequirements(component, substitutionMapping);
if (requirements.isRight()) {
return Either.right(requirements.right().value());
}
substitutionMapping = requirements.left().value();
- topology_template.setSubstitution_mappings(substitutionMapping);
+ topologyTemplate.setSubstitution_mappings(substitutionMapping);
- toscaNode.setTopology_template(topology_template);
+ toscaNode.setTopology_template(topologyTemplate);
return Either.left(toscaNode);
}
- private Either<ToscaTopolgyTemplate, ToscaError> fillInputs(Component component, ToscaTopolgyTemplate topology_template, Map<String, DataTypeDefinition> dataTypes) {
+ 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();
@@ -266,14 +304,19 @@ public class ToscaExportHandler {
ToscaProperty property = propertyConvertor.convertProperty(dataTypes, i, false);
inputs.put(i.getName(), property);
});
- if (inputs != null && !inputs.isEmpty()) {
- topology_template.setInputs(inputs);
+ if (!inputs.isEmpty()) {
+ topologyTemplate.setInputs(inputs);
}
}
- return Either.left(topology_template);
+ return Either.left(topologyTemplate);
+ }
+
+ private ToscaMetadata convertMetadata(Component component) {
+ return convertMetadata(component, false, null);
}
- private ToscaMetadata convertMetadata(Component component, boolean isInstance) {
+ private ToscaMetadata convertMetadata(Component component, boolean isInstance,
+ ComponentInstance componentInstance) {
ToscaMetadata toscaMetadata = new ToscaMetadata();
toscaMetadata.setName(component.getComponentMetadataDefinition().getMetadataDataDefinition().getName());
toscaMetadata.setInvariantUUID(component.getInvariantUUID());
@@ -286,6 +329,7 @@ public class ToscaExportHandler {
if (isInstance) {
toscaMetadata.setVersion(component.getVersion());
+ toscaMetadata.setCustomizationUUID(componentInstance.getCustomizationUUID());
}
switch (component.getComponentType()) {
case RESOURCE:
@@ -300,8 +344,10 @@ public class ToscaExportHandler {
case SERVICE:
toscaMetadata.setType(component.getComponentType().getValue());
if (!isInstance) {
- toscaMetadata.setServiceEcompNaming(false);
- toscaMetadata.setServiceHoming(false);
+ // DE268546
+ toscaMetadata.setServiceEcompNaming(((Service)component).isEcompGeneratedNaming());
+ toscaMetadata.setEcompGeneratedNaming(((Service)component).isEcompGeneratedNaming());
+ toscaMetadata.setNamingPolicy(((Service)component).getNamingPolicy());
}
break;
default:
@@ -310,38 +356,59 @@ public class ToscaExportHandler {
return toscaMetadata;
}
- private Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> fillImports(Component component, ToscaTemplate toscaTemplate) {
+ private Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> fillImports(Component component,
+ ToscaTemplate toscaTemplate) {
Map<String, Component> componentCache = new HashMap<>();
- if (!ToscaUtils.isNodeType(component)) {
+
+ if (!ToscaUtils.isAtomicType(component)) {
List<ComponentInstance> componentInstances = component.getComponentInstances();
if (componentInstances != null && !componentInstances.isEmpty()) {
- List<Map<String, Map<String, String>>> imports = new LinkedList<Map<String, Map<String, String>>>();
+
+ 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, imports, dependecies, ci);
+ createDependency(componentCache, additionalImports, dependecies, ci);
});
- toscaTemplate.setImports(imports);
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) {
+ 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<Resource, StorageOperationStatus> resource = resourceOperation.getResource(ci.getComponentUid(), true);
+ Either<Component, StorageOperationStatus> resource = toscaOperationFacade.getToscaFullElement(ci.getComponentUid());
if (resource.isRight()) {
log.debug("Failed to fetch resource with id {} for instance {}");
}
- Resource fetchedComponent = resource.left().value();
+ Component fetchedComponent = resource.left().value();
componentCache.put(fetchedComponent.getUniqueId(), fetchedComponent);
componentRI = fetchedComponent;
@@ -350,16 +417,34 @@ public class ToscaExportHandler {
if (artifactDefinition != null) {
String artifactName = artifactDefinition.getArtifactName();
files.put(IMPORTS_FILE_KEY, artifactName);
- importsListMember.put(ci.getComponentName(), files);
- dependecies.add(new ImmutableTriple<String, String, Component>(artifactName, artifactDefinition.getEsId(), fetchedComponent));
+ 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(!ToscaUtils.isAtomicType(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);
+ }
}
}
- if (!importsListMember.isEmpty()) {
- imports.add(importsListMember);
- }
}
- private Either<ToscaTemplate, ToscaError> convertNodeType(Component component, ToscaTemplate toscaNode, Map<String, ToscaNodeType> node_types) {
+ public static String getInterfaceFilename(String artifactName) {
+ String interfaceFileName = artifactName.substring(0, artifactName.lastIndexOf('.')) + ToscaExportHandler.TOSCA_INTERFACE_NAME;
+ return interfaceFileName;
+ }
+
+ 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);
@@ -370,13 +455,51 @@ public class ToscaExportHandler {
}
Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
- Either<ToscaNodeType, ToscaError> properties = propertyConvertor.convertProperties(component, toscaNodeType, dataTypes);
+ 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());
@@ -384,150 +507,323 @@ public class ToscaExportHandler {
toscaNodeType = capabilities.left().value();
log.debug("Capabilities converted for {}", component.getUniqueId());
- Either<ToscaNodeType, ToscaError> requirements = capabiltyRequirementConvertor.convertRequirements(component, toscaNodeType);
+ 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 = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition().getMetadataDataDefinition()).getToscaResourceName();
- node_types.put(toscaResourceName, toscaNodeType);
- toscaNode.setNode_types(node_types);
+
+ 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) {
- log.debug("start convert topology template for {} for type {}", component.getUniqueId(), component.getComponentType());
- Map<String, ToscaNodeTemplate> node_templates = new HashMap<>();
+ 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<ToscaNodeTemplate, ToscaError> requirements = convertComponentInstanceRequirements(component, componentInstance, component.getComponentInstancesRelations(), nodeTemplate);
+ Either<ToscaNodeTemplate, ToscaError> requirements = convertComponentInstanceRequirements(component,
+ componentInstance, component.getComponentInstancesRelations(), nodeTemplate);
if (requirements.isRight()) {
- return Either.right(requirements.right().value());
+ convertNodeTemplatesRes = Either.right(requirements.right().value());
+ break;
}
- log.debug("Component instance Requirements converted for instance {}", componentInstance.getUniqueId());
+ String instanceUniqueId = componentInstance.getUniqueId();
+ log.debug("Component instance Requirements converted for instance {}", instanceUniqueId);
nodeTemplate = requirements.left().value();
Component componentOfInstance = componentCache.get(componentInstance.getComponentUid());
- nodeTemplate.setMetadata(convertMetadata(componentOfInstance, true));
+ nodeTemplate.setMetadata(convertMetadata(componentOfInstance, true, componentInstance));
- Either<ToscaNodeTemplate, ToscaError> capabilties = capabiltyRequirementConvertor.convertComponentInstanceCapabilties(componentInstance, dataTypes, nodeTemplate);
+ Either<ToscaNodeTemplate, ToscaError> capabilties = capabiltyRequirementConvertor
+ .convertComponentInstanceCapabilties(componentInstance, dataTypes, nodeTemplate);
if (capabilties.isRight()) {
- return Either.right(requirements.right().value());
+ convertNodeTemplatesRes = Either.right(requirements.right().value());
+ break;
}
- log.debug("Component instance Capabilties converted for instance {}", componentInstance.getUniqueId());
+ log.debug("Component instance Capabilties converted for instance {}", instanceUniqueId);
nodeTemplate = capabilties.left().value();
+ Map<String, Object> props = new HashMap<>();
- if (componentInstancesProperties.containsKey(componentInstance.getUniqueId())) {
- Map<String, Object> props = null;
- List<ComponentInstanceProperty> propList = componentInstancesProperties.get(componentInstance.getUniqueId());
- List<ComponentInstanceProperty> collect = propList.stream().filter(e -> e.getValueUniqueUid() != null && !e.getValueUniqueUid().isEmpty()).collect(Collectors.toList());
- if (collect != null && !collect.isEmpty()) {
- props = new HashMap<String, Object>();
- for (ComponentInstanceProperty prop : collect) {
- Object convertedValue = convertInstanceProperty(dataTypes, componentInstance, prop);
- props.put(prop.getName(), convertedValue);
- }
+ 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<>();
}
- if (props != null && !props.isEmpty()) {
- nodeTemplate.setProperties(props);
+ for (GroupInstance groupInst : groupInstances) {
+ ToscaGroupTemplate toscaGroup = convertGroupInstance(groupInst);
+ String keyName = groupInst.getGroupName();
+
+ groupsMap.put(keyName, toscaGroup);
}
}
- node_templates.put(componentInstance.getName(), nodeTemplate);
+
+ 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();
+ 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()
+ // Filters out properties with empty ValueUniqueUid
+ .filter(e -> e.getValue() != null && !e.getValue().isEmpty() )
+ // 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);
}
- log.debug("finish convert topology template for {} for type {}", component.getUniqueId(), component.getComponentType());
- return Either.left(node_templates);
}
- private Object convertInstanceProperty(Map<String, DataTypeDefinition> dataTypes, ComponentInstance componentInstance, ComponentInstanceProperty prop) {
- log.debug("Convert property {} for instance {}", prop.getName(), componentInstance.getUniqueId());
- String propertyType = prop.getType();
+ 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 (prop.getSchema() != null && prop.getSchema().getProperty() != null) {
- innerType = prop.getSchema().getProperty().getType();
+ if (input.getSchema() != null && input.getSchema().getProperty() != null) {
+ innerType = input.getSchema().getProperty().getType();
}
- Object convertedValue = propertyConvertor.convertToToscaObject(propertyType, prop.getValue(), innerType, dataTypes);
- return convertedValue;
+ return propertyConvertor.convertToToscaObject(propertyType, supplier.get(), innerType, dataTypes);
}
- private ToscaGroupTemplate convertGroup(GroupDefinition group, Component component) {
+ private ToscaGroupTemplate convertGroup(GroupDefinition group) {
ToscaGroupTemplate toscaGroup = new ToscaGroupTemplate();
Map<String, String> members = group.getMembers();
- toscaGroup.setType(group.getType());
if (members != null)
toscaGroup.setMembers(new ArrayList(members.keySet()));
- boolean isVfModule = group.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE) ? true : false;
+ 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 = new HashMap<>();
- for (GroupProperty gp : group.getProperties()) {
+ Map<String, Object> properties = fillGroupProperties(props.get());
+
+ 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);
- break;
- }
- }
- properties.put(VF_MODULE_DESC_KEY, group.getDescription());
- boolean isVolume = false;
- List<String> artifactsList = group.getArtifacts();
- if (artifactsList != null && !artifactsList.isEmpty()) {
-
- for (String artifactId : artifactsList) {
- Map<String, ArtifactDefinition> deploymentArtifacts = component.getDeploymentArtifacts();
- Optional<ArtifactDefinition> findFirst = deploymentArtifacts.values().stream().filter(p -> p.getUniqueId().equals(artifactId)).findFirst();
- if (findFirst.isPresent()) {
- ArtifactDefinition artifactDefinition = findFirst.get();
- if (artifactDefinition.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType())) {
- isVolume = true;
- break;
+ } 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);
}
}
- properties.put(VOLUME_GROUP_KEY, isVolume);
- toscaGroup.setProperties(properties);
}
- toscaMetadata.setName(group.getName());
- toscaMetadata.setInvariantUUID(group.getInvariantUUID());
- toscaMetadata.setUUID(group.getGroupUUID());
- toscaMetadata.setVersion(group.getVersion());
- toscaGroup.setMetadata(toscaMetadata);
- return toscaGroup;
+ return properties;
}
private ToscaNodeType createNodeType(Component component) {
ToscaNodeType toscaNodeType = new ToscaNodeType();
- if (ToscaUtils.isNodeType(component) && ((Resource) component).getDerivedFrom() != null) {
- toscaNodeType.setDerived_from(((Resource) component).getDerivedFrom().get(0));
+ if (ToscaUtils.isAtomicType(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);
}
- toscaNodeType.setDescription(component.getDescription()); // or name??
return toscaNodeType;
}
-
- private Either<ToscaNodeTemplate, ToscaError> convertComponentInstanceRequirements(Component component, ComponentInstance componentInstance, List<RequirementCapabilityRelDef> relations, ToscaNodeTemplate nodeTypeTemplate) {
+
+ private Either<ToscaNodeTemplate, ToscaError> convertComponentInstanceRequirements(Component component,
+ ComponentInstance componentInstance, List<RequirementCapabilityRelDef> relations,
+ ToscaNodeTemplate nodeTypeTemplate) {
List<ComponentInstance> instancesList = component.getComponentInstances();
List<Map<String, ToscaTemplateRequirement>> toscaRequirements = new ArrayList<>();
Map<String, List<RequirementDefinition>> reqMap = componentInstance.getRequirements();
relations.stream().filter(p -> componentInstance.getUniqueId().equals(p.getFromNode())).forEach(req -> {
- ComponentInstance toComponentInstance = instancesList.stream().filter(i -> req.getToNode().equals(i.getUniqueId())).findFirst().orElse(null);
+ ComponentInstance toComponentInstance = instancesList.stream()
+ .filter(i -> req.getToNode().equals(i.getUniqueId())).findFirst().orElse(null);
if (toComponentInstance == null) {
- log.debug("Faild to create relation between node {} to node {}", componentInstance.getName(), req.getToNode());
+ log.debug("Faild to create relation between node {} to node {}", componentInstance.getName(),
+ req.getToNode());
return;
}
@@ -535,12 +831,14 @@ public class ToscaExportHandler {
ToscaTemplateRequirement toscaRequirement = new ToscaTemplateRequirement();
toscaRequirement.setRelationship(reqAndRelationshopPair.getRelationship().getType());
toscaRequirement.setNode(toComponentInstance.getName());
- Optional<RequirementDefinition> findAny = reqMap.values().stream().flatMap(e -> e.stream()).filter(e -> e.getName().equals(reqAndRelationshopPair.getRequirement())).findAny();
+ Optional<RequirementDefinition> findAny = reqMap.values().stream().flatMap(e -> e.stream())
+ .filter(e -> e.getName().equals(reqAndRelationshopPair.getRequirement())).findAny();
if (findAny.isPresent()) {
RequirementDefinition regDefinition = findAny.get();
toscaRequirement.setCapability(regDefinition.getCapability());
} else {
- log.debug("Faild to find relation between node {} to node {}", componentInstance.getName(), req.getToNode());
+ log.debug("Faild to find relation between node {} to node {}", componentInstance.getName(),
+ req.getToNode());
return;
}
Map<String, ToscaTemplateRequirement> reqmap = new HashMap<String, ToscaTemplateRequirement>();
@@ -557,7 +855,8 @@ public class ToscaExportHandler {
}
private Either<SubstitutionMapping, ToscaError> convertCapabilities(Component component, SubstitutionMapping substitutionMapping, Map<String, DataTypeDefinition> dataTypes) {
- Map<String, ToscaCapability> toscaCapabilities = capabiltyRequirementConvertor.convertCapabilities(component, dataTypes);
+ Map<String, String[]> toscaCapabilities = capabiltyRequirementConvertor.convertSubstitutionMappingCapabilities(component, dataTypes);
+
if (!toscaCapabilities.isEmpty()) {
substitutionMapping.setCapabilities(toscaCapabilities);
}
@@ -566,8 +865,10 @@ public class ToscaExportHandler {
return Either.left(substitutionMapping);
}
- private Either<ToscaNodeType, ToscaError> convertCapabilities(Component component, ToscaNodeType nodeType, Map<String, DataTypeDefinition> dataTypes) {
- Map<String, ToscaCapability> toscaCapabilities = capabiltyRequirementConvertor.convertCapabilities(component, dataTypes);
+ 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);
}
@@ -586,7 +887,8 @@ public class ToscaExportHandler {
}
@Override
- protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue, Tag customTag) {
+ protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue,
+ Tag customTag) {
if (propertyValue == null) {
return null;
} else {
@@ -596,7 +898,8 @@ public class ToscaExportHandler {
}
NodeTuple defaultNode = super.representJavaBeanProperty(javaBean, property, propertyValue, customTag);
- return property.getName().equals("_defaultp_") ? new NodeTuple(representData("default"), defaultNode.getValueNode()) : defaultNode;
+ return property.getName().equals("_defaultp_")
+ ? new NodeTuple(representData("default"), defaultNode.getValueNode()) : defaultNode;
}
}
@@ -619,10 +922,10 @@ public class ToscaExportHandler {
private static class UnsortedPropertyUtils extends PropertyUtils {
@Override
- protected Set<Property> createPropertySet(Class<? extends Object> type, BeanAccess bAccess) throws IntrospectionException {
+ protected Set<Property> createPropertySet(Class<? extends Object> type, BeanAccess bAccess)
+ throws IntrospectionException {
Collection<Property> fields = getPropertiesMap(type, BeanAccess.FIELD).values();
- Set<Property> result = new LinkedHashSet<Property>(fields);
- return result;
+ return new LinkedHashSet<Property>(fields);
}
}
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 db03ad2307..dce3b3bbc0 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
@@ -34,11 +34,11 @@ import org.openecomp.sdc.be.model.Component;
public class ToscaUtils {
- public static boolean isNodeType(Component component) {
+ public static boolean isAtomicType(Component component) {
ComponentTypeEnum componentType = component.getComponentType();
if (ComponentTypeEnum.RESOURCE.equals(componentType)) {
ResourceTypeEnum resourceType = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition().getMetadataDataDefinition()).getResourceType();
- if (ResourceTypeEnum.CP.equals(resourceType) || ResourceTypeEnum.VL.equals(resourceType) || ResourceTypeEnum.VFC.equals(resourceType)) {
+ if (ResourceTypeEnum.CP == resourceType || ResourceTypeEnum.VL == resourceType || ResourceTypeEnum.VFC == resourceType || ResourceTypeEnum.VFCMT == resourceType || ResourceTypeEnum.ABSTRACT == resourceType) {
return true;
}
}
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 46f4fd032e..70b05b8158 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
@@ -29,5 +29,6 @@ public interface IToscaMetadata {
public void setUUID(String uUID);
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 0fd9daef7d..5dc8ddee2a 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
@@ -24,9 +24,8 @@ import java.util.Map;
public class SubstitutionMapping {
private String node_type;
-
- private Map<String, ToscaCapability> capabilities;
- private Map<String, ToscaRequirement> requirements;
+ private Map<String, String[]> capabilities;
+ private Map<String, String[]> requirements;
public SubstitutionMapping() {
super();
@@ -41,20 +40,19 @@ public class SubstitutionMapping {
this.node_type = node_type;
}
- public Map<String, ToscaCapability> getCapabilities() {
+ public Map<String, String[]> getCapabilities() {
return capabilities;
}
- public void setCapabilities(Map<String, ToscaCapability> capabilities) {
+ public void setCapabilities(Map<String, String[]> capabilities) {
this.capabilities = capabilities;
}
- public Map<String, ToscaRequirement> getRequirements() {
+ public Map<String, String[]> getRequirements() {
return requirements;
}
- public void setRequirements(Map<String, ToscaRequirement> 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/ToscaMetadata.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaMetadata.java
index 38cd002726..6573313dbb 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
@@ -23,6 +23,7 @@ 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;
@@ -32,7 +33,8 @@ public class ToscaMetadata implements IToscaMetadata {
private String resourceVendor;
private String resourceVendorRelease;
private Boolean serviceEcompNaming;
- private Boolean serviceHoming;
+ private Boolean ecompGeneratedNaming;
+ private String namingPolicy;
public String getName() {
return name;
@@ -109,20 +111,28 @@ public class ToscaMetadata implements IToscaMetadata {
this.resourceVendorRelease = resourceVendorRelease;
}
- public Boolean isServiceEcompNaming() {
- return serviceEcompNaming;
+ public Boolean isEcompGeneratedNaming() {
+ return ecompGeneratedNaming;
}
- public void setServiceEcompNaming(Boolean serviceEcompNaming) {
- this.serviceEcompNaming = serviceEcompNaming;
+ public void setEcompGeneratedNaming(Boolean ecompGeneratedNaming) {
+ this.ecompGeneratedNaming = ecompGeneratedNaming;
+ }
+
+ public String isNamingPolicy() {
+ return namingPolicy;
+ }
+
+ public void setNamingPolicy(String namingPolicy) {
+ this.namingPolicy = namingPolicy;
}
- public Boolean isServiceHoming() {
- return serviceHoming;
+ public Boolean getServiceEcompNaming() {
+ return serviceEcompNaming;
}
- public void setServiceHoming(Boolean serviceHoming) {
- this.serviceHoming = serviceHoming;
+ public void setServiceEcompNaming(Boolean serviceEcompNaming) {
+ this.serviceEcompNaming = serviceEcompNaming;
}
public String getVersion() {
@@ -134,4 +144,12 @@ public class ToscaMetadata implements IToscaMetadata {
this.version = version;
}
+ public String getCustomizationUUID() {
+ return customizationUUID;
+ }
+
+ public void setCustomizationUUID(String customizationUUID) {
+ this.customizationUUID = customizationUUID;
+ }
+
}
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 6804bf6968..df285c6ad9 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
@@ -20,6 +20,7 @@
package org.openecomp.sdc.be.tosca.model;
+import java.util.HashMap;
import java.util.Map;
public class ToscaTopolgyTemplate {
@@ -40,8 +41,11 @@ public class ToscaTopolgyTemplate {
return groups;
}
- public void setGroups(Map<String, ToscaGroupTemplate> groups) {
- this.groups = groups;
+ public void addGroups(Map<String, ToscaGroupTemplate> groups) {
+ if ( this.groups == null ){
+ this.groups = new HashMap<>();
+ }
+ this.groups.putAll(groups);
}
public SubstitutionMapping getSubstitution_mappings() {
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 5f978227ef..26ce118a1a 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
@@ -26,6 +26,7 @@ public class VfModuleToscaMetadata implements IToscaMetadata {
private String vfModuleModelInvariantUUID;
private String vfModuleModelUUID;
private String vfModuleModelVersion;
+ private String vfModuleModelCustomizationUUID;
@Override
public void setName(String name) {
@@ -63,4 +64,12 @@ public class VfModuleToscaMetadata implements IToscaMetadata {
return vfModuleModelVersion;
}
+ public String getVfModuleModelCustomizationUUID() {
+ return vfModuleModelCustomizationUUID;
+ }
+
+ public void setCustomizationUUID(String customizationUUID) {
+ this.vfModuleModelCustomizationUUID = customizationUUID;
+ }
+
}
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 5cfa4a12da..54ba9bf571 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
@@ -31,6 +31,11 @@ import org.openecomp.sdc.exception.ResponseFormat;
import fj.data.Either;
+/**
+ *
+ * @author tg851x
+ *
+ */
public interface IUserBusinessLogic {
public Either<User, ActionStatus> getUser(String userId, boolean inTransaction);
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 8e736d4c0e..796b3a78c0 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
@@ -40,8 +40,7 @@ public class 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 USER_ID_PATTERN = "[mM]{1}[0-9]{5}|[a-zA-Z]{2}[0-9]{4}|[a-zA-Z]{2}[0-9]{4}|[a-zA-Z]{2}[0-9]{3}[a-zA-Z]{1}";
- private static final String USER_ID_PATTERN = "^[\\s\\w_.-]{1,50}$";
+ private static final String USER_ID_PATTERN = "\\w{1,25}";
private UserAdminValidator() {
emailPat = Pattern.compile(EMAIL_PATTERN);
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 8a910fc566..c90cc6118f 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
@@ -90,7 +90,7 @@ public class UserBusinessLogic implements IUserBusinessLogic {
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());
+ 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);
@@ -98,7 +98,7 @@ public class UserBusinessLogic implements IUserBusinessLogic {
modifier = eitherCreator.left().value();
if (!modifier.getRole().equals(UserRoleEnum.ADMIN.getName())) {
- log.debug("createUser method - user is not admin={}", modifier.getUserId());
+ 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);
@@ -120,7 +120,7 @@ public class UserBusinessLogic implements IUserBusinessLogic {
// isUserAlreadyExist = true;
if (userFromDb.getStatus() == UserStatusEnum.ACTIVE) {
responseFormat = componentsUtils.getResponseFormatByUserId(ActionStatus.USER_ALREADY_EXIST, newUser.getUserId());
- log.debug("createUser method - user already exist with id: {}", modifier.getUserId(), userFromDb.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);
}
@@ -130,7 +130,7 @@ public class UserBusinessLogic implements IUserBusinessLogic {
// validate Email
if (newUser.getEmail() != null && !userAdminValidator.validateEmail(newUser.getEmail())) {
- log.debug("createUser method - user has invalid email={}", modifier.getUserId());
+ 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);
@@ -141,7 +141,7 @@ public class UserBusinessLogic implements IUserBusinessLogic {
newUser.setRole(Role.DESIGNER.name());
} else {
if (!userAdminValidator.validateRole(newUser.getRole())) {
- log.debug("createUser method - user has invalid role={}", modifier.getUserId());
+ 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);
@@ -168,8 +168,9 @@ public class UserBusinessLogic implements IUserBusinessLogic {
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());
+ 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);
@@ -204,7 +205,7 @@ public class UserBusinessLogic implements IUserBusinessLogic {
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());
+ 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);
@@ -212,14 +213,14 @@ public class UserBusinessLogic implements IUserBusinessLogic {
modifier = eitherCreator.left().value();
if (!modifier.getRole().equals(UserRoleEnum.ADMIN.getName())) {
- log.debug("updateUserRole method - user is not admin. userId={}", modifier.getUserId());
+ 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());
+ 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);
@@ -227,14 +228,14 @@ public class UserBusinessLogic implements IUserBusinessLogic {
Either<User, ActionStatus> userToUpdateReq = getUser(userIdToUpdate, false);
if (userToUpdateReq.isRight() || userToUpdateReq.left().value() == null) {
- log.debug("updateUserRole method - user not found. userId={}", modifier.getUserId());
+ 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());
+ 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);
@@ -267,7 +268,7 @@ public class UserBusinessLogic implements IUserBusinessLogic {
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());
+ log.debug("updateUser method - failed to update user data. userId = {}", modifier.getUserId());
return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateUserReq.right().value())));
}
@@ -374,7 +375,7 @@ public class UserBusinessLogic implements IUserBusinessLogic {
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());
+ 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);
@@ -383,14 +384,14 @@ public class UserBusinessLogic implements IUserBusinessLogic {
modifier = eitherCreator.left().value();
if (!modifier.getRole().equals(UserRoleEnum.ADMIN.getName())) {
- log.debug("deActivateUser method - user is not admin. userId={}", modifier.getUserId());
+ 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());
+ 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);
@@ -706,7 +707,7 @@ public class UserBusinessLogic implements IUserBusinessLogic {
log.debug("Functional menu fetched is {}", functionalMenu);
} catch (UebException e) {
- log.debug("Failed to fetch 'functional menu' of user {} from ecomp portal(via UEB). {}", userId, e);
+ log.debug("Failed to fetch 'functional menu' of user {} from ecomp portal(via UEB)", userId, e);
BeEcompErrorManager.getInstance().logInternalFlowError("FetchFunctionalMenu", "Failed to fetch 'functional menu'", ErrorSeverity.ERROR);
}
return functionalMenu;
diff --git a/catalog-be/src/main/resources/application-context.xml b/catalog-be/src/main/resources/application-context.xml
index da0a49f6e2..702c63ea81 100644
--- a/catalog-be/src/main/resources/application-context.xml
+++ b/catalog-be/src/main/resources/application-context.xml
@@ -28,6 +28,8 @@
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
">
@@ -56,9 +58,9 @@
<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.externalapi.servlet.AssetMetadataConverter" />
-
-
-
+
+ <bean class="org.openecomp.sdc.be.dao.config.DAOSpringConfig"/>
+
<util:properties id="elasticsearchConfig" location="file:${config.home}/elasticsearch.yml" />
</beans>
diff --git a/catalog-be/src/main/resources/config/Artifact-Generator.properties b/catalog-be/src/main/resources/config/Artifact-Generator.properties
new file mode 100644
index 0000000000..1d7e5fa01a
--- /dev/null
+++ b/catalog-be/src/main/resources/config/Artifact-Generator.properties
@@ -0,0 +1,264 @@
+#action widget details
+AAI.model-version-id.action=fd7fb09e-d930-41b9-b83f-cfde9df48640
+AAI.model-invariant-id.action=af593b4b-490e-4665-ad74-2f6351c0a7ce
+#action-data widget details
+AAI.model-invariant-id.action-data=9551346c-7d8b-4daf-9926-b93e96e2344a
+AAI.model-version-id.action-data=2f80c596-27e5-4ca9-b5bb-e03a7fd4c0fd
+#allotted-resource widget details
+AAI.model-invariant-id.allotted-resource=f6d6a23d-a1a9-48ff-8419-b6530da2d381
+AAI.model-version-id.allotted-resource=7ad0915f-25c0-4a70-b9bc-185a75f87564
+#availability-zone widget details
+AAI.model-version-id.availability-zone=6c092fb1-21b2-456b-9e01-67fb4de1896e
+AAI.model-invariant-id.availability-zone=61b88c01-d819-41c0-8e21-7fd7ba47148e
+#az-and-dvs-switches widget details
+AAI.model-version-id.az-and-dvs-switches=b2dea88d-78a0-49bf-95c9-5819df08e966
+AAI.model-invariant-id.az-and-dvs-switches=53dc00d4-e6d9-48ec-b6cc-3d3797e9b896
+#class-of-service widget details
+AAI.model-version-id.class-of-service=d2fb27cc-15eb-4c4e-828e-71d41aaecc5b
+AAI.model-invariant-id.class-of-service=18094b19-d16d-4822-8acf-e92c6aefa178
+#cloud-region widget details
+AAI.model-version-id.cloud-region=2a160989-b202-47dd-874b-4a0f275998f7
+AAI.model-invariant-id.cloud-region=425b2158-e51d-4509-9945-dad4556474a3
+#complex widget details
+AAI.model-invariant-id.complex=af91c2f7-35fc-43cf-a13d-443f385b2353
+AAI.model-version-id.complex=3a8ab1ee-9220-4fe8-b89c-9251d160ddc2
+#connector widget details
+AAI.model-version-id.connector=22104c9f-29fd-462f-be07-96cd6b46dd33
+AAI.model-invariant-id.connector=4c01c948-7607-4d66-8a6c-99c2c2717936
+#constrained-element-set widget details
+AAI.model-invariant-id.constrained-element-set=c0292b4f-ee97-40cc-8c2e-f967c48f5701
+AAI.model-version-id.constrained-element-set=01102126-9c04-4a89-945b-b131e61e95d7
+#ctag-assignment widget details
+AAI.model-version-id.ctag-assignment=44e5cb1f-0938-41aa-b766-d4595109fe89
+AAI.model-invariant-id.ctag-assignment=fcb8d46b-b656-4ad6-8fa4-22cef74b443f
+#ctag-pool widget details
+AAI.model-invariant-id.ctag-pool=46c51d4e-d67e-4a9c-b1f5-49b1e9c6fcaa
+AAI.model-version-id.ctag-pool=2056c41f-23b9-4de7-9f50-819adad37d76
+#customer widget details
+AAI.model-invariant-id.customer=c1d4305f-cdbd-4bbe-9069-a2f4978fd89e
+AAI.model-version-id.customer=d4df5c27-98a1-4812-a8aa-c17f055b7a3f
+#cvlan-tag-entry widget details
+AAI.model-version-id.cvlan-tag-entry=c3878ffb-8d85-4114-bee6-e4074a9db10b
+AAI.model-invariant-id.cvlan-tag-entry=245cf4b0-7cc5-4eea-bbd9-753e939adcab
+#dvs-switch widget details
+AAI.model-invariant-id.dvs-switch=98fbb471-1f86-428e-bd8a-c8a25de6fa23
+AAI.model-version-id.dvs-switch=4cb44ae8-e3ab-452a-9f95-bcc8a44c55ea
+#edge-prop-names widget details
+AAI.model-invariant-id.edge-prop-names=7a08cad4-8759-46a5-8245-095d1ba57ac6
+AAI.model-version-id.edge-prop-names=f0442326-8201-4d0e-857c-74b4ddcbfc9f
+#element-choice-set widget details
+AAI.model-invariant-id.element-choice-set=9a011958-7165-47a3-b872-00951d1f09ae
+AAI.model-version-id.element-choice-set=af27fbfd-598d-44da-aeae-0f9d3a5fcd6a
+#entitlement widget details
+AAI.model-version-id.entitlement=7e27ba2e-b7db-4e13-9fae-d142152ef98a
+AAI.model-invariant-id.entitlement=ae75b5a0-d5e1-4f3a-b8fb-37626a753da3
+#flavor widget details
+AAI.model-invariant-id.flavor=bace8d1c-a261-4041-9e37-823117415d0f
+AAI.model-version-id.flavor=36200fb5-f251-4f5d-a520-7c5ad5c2cd4b
+#generic-vnf widget details
+AAI.model-version-id.generic-vnf=93a6166f-b3d5-4f06-b4ba-aed48d009ad9
+AAI.model-invariant-id.generic-vnf=acc6edd8-a8d4-4b93-afaa-0994068be14c
+#group-assignment widget details
+AAI.model-invariant-id.group-assignment=7cc05f25-7ba2-42b7-a237-c5662a1689e1
+AAI.model-version-id.group-assignment=fe578080-ce19-4604-8760-fc264fbb2565
+#image widget details
+AAI.model-version-id.image=f6a038c2-820c-42ba-8c2b-375e24e8f932
+AAI.model-invariant-id.image=3f4c7204-739b-4bbb-87a7-8a6856439c90
+#include-node-filter widget details
+AAI.model-invariant-id.include-node-filter=2a2d8ad2-af0a-4e1f-9982-0c899e7dc827
+AAI.model-version-id.include-node-filter=f05f804d-7057-4ffe-bdc5-39f2f0c9c9fd
+#instance-group widget details
+AAI.model-version-id.instance-group=8e6ee9dc-9017-444a-83b3-219edb018128
+AAI.model-invariant-id.instance-group=3bf1e610-45f7-4ad6-b833-ca4c5ee6a3fd
+#inventory-item widget details
+AAI.model-invariant-id.inventory-item=cd57d844-9017-4078-aa19-926935a3d77c
+AAI.model-version-id.inventory-item=69957f4a-2155-4b95-8d72-d6dd9b88b27b
+#inventory-item-data widget details
+AAI.model-version-id.inventory-item-data=0e54bb87-bd6e-4a2b-ad1c-6d935b87ae51
+AAI.model-invariant-id.inventory-item-data=87a383ae-cf03-432e-a9de-04e6a622d0fd
+#ipsec-configuration widget details
+AAI.model-invariant-id.ipsec-configuration=aca4c310-cb45-42bd-9f88-73e40ba7b962
+AAI.model-version-id.ipsec-configuration=d949fd10-36bf-408a-ac7a-cad5004d2e0d
+#key-data widget details
+AAI.model-version-id.key-data=c23ea04d-1a3b-453d-bc49-a6c783a5e92b
+AAI.model-invariant-id.key-data=f5faa464-c2f2-4cc3-89d2-a90452dc3a07
+#l3-interface-ipv4-address-list widget details
+AAI.model-version-id.l3-interface-ipv4-address-list=41e76b6f-1e06-4fd4-82cd-81c50fc4574b
+AAI.model-invariant-id.l3-interface-ipv4-address-list=aad85df2-09be-40fa-b867-16415e4e10e2
+#l3-interface-ipv6-address-list widget details
+AAI.model-invariant-id.l3-interface-ipv6-address-list=82966045-43ee-4982-8307-7e9610866140
+AAI.model-version-id.l3-interface-ipv6-address-list=d040621d-541a-477b-bb1b-a2b61b14e295
+#l3-network widget details
+AAI.model-version-id.l3-network=9111f20f-e680-4001-b83f-19a2fc23bfc1
+AAI.model-invariant-id.l3-network=3d560d81-57d0-438b-a2a1-5334dba0651a
+#lag-interface widget details
+AAI.model-version-id.lag-interface=ce95f7c3-b61b-4758-ae9e-7e943b1c103d
+AAI.model-invariant-id.lag-interface=e0ee9bde-c1fc-4651-a95d-8e0597bf7d70
+#lag-link widget details
+AAI.model-version-id.lag-link=d29a087a-af59-4053-a3f8-0f95a92faa75
+AAI.model-invariant-id.lag-link=86ffe6e5-4d0e-4cec-80b5-5c38aa3eff98
+#license widget details
+AAI.model-invariant-id.license=b9a9b337-1f86-42d3-b9f9-f987a089507c
+AAI.model-version-id.license=6889274b-a1dc-40ab-9090-93677e13e2e6
+#license-key-resource widget details
+AAI.model-invariant-id.license-key-resource=9022ebfe-b54f-4911-a6b2-8c3f5ec189b7
+AAI.model-version-id.license-key-resource=24b25f8c-b8bd-4c62-9421-87c12667aac9
+#l-interface widget details
+AAI.model-version-id.l-interface=a32613fd-18b9-459e-aab8-fffb3912966a
+AAI.model-invariant-id.l-interface=cea0a982-8d55-4093-921e-418fbccf7060
+#logical-link widget details
+AAI.model-version-id.logical-link=a1481a38-f8ba-4ae4-bdf1-06c2c6af4c54
+AAI.model-invariant-id.logical-link=fe012535-2c31-4a39-a739-612374c638a0
+#metadatum widget details
+AAI.model-invariant-id.metadatum=86dbb63a-265e-4614-993f-6771c30b56a5
+AAI.model-version-id.metadatum=6bae950e-8939-41d3-a6a7-251b03e4c1fc
+#model widget details
+AAI.model-invariant-id.model=06d1418a-5faa-452d-a94b-a2829df5f67b
+AAI.model-version-id.model=1f51c05c-b164-4c27-9c03-5cbb239fd6be
+#model-constraint widget details
+AAI.model-invariant-id.model-constraint=c28966f3-e758-4483-b37b-a90b05d3dd33
+AAI.model-version-id.model-constraint=ad70dd19-f156-4fb5-a865-97b5563b0d37
+#model-element widget details
+AAI.model-invariant-id.model-element=2076e726-3577-477a-a300-7fa65cd4df11
+AAI.model-version-id.model-element=753e813a-ba9e-4a1d-ab34-b2f6dc6eec0c
+#multicast-configuration widget details
+AAI.model-invariant-id.multicast-configuration=ea78c9e3-514d-4a0a-9162-13837fa54c35
+AAI.model-version-id.multicast-configuration=666a06ee-4b57-46df-bacf-908da8f10c3f
+#named-query widget details
+AAI.model-version-id.named-query=5c3b7c33-afa3-4be5-8da7-1a5ac6f99896
+AAI.model-invariant-id.named-query=80b712fd-0ad3-4180-a99c-8c995cf1cc32
+#named-query-element widget details
+AAI.model-version-id.named-query-element=204c641a-3494-48c8-979a-86856f5fd32a
+AAI.model-invariant-id.named-query-element=3c504d40-b847-424c-9d25-4fb7e0a3e994
+#network-policy widget details
+AAI.model-invariant-id.network-policy=6aa05779-94d7-4d8b-9bee-59ef2ab0c246
+AAI.model-version-id.network-policy=a0ccd9dc-7062-4940-9bcc-e91dd28af510
+#network-profile widget details
+AAI.model-version-id.network-profile=01f45471-4240-498c-a9e1-235dc0b8b4a6
+AAI.model-invariant-id.network-profile=2734b44a-b8a2-40f6-957d-6256589e5d00
+#newvce widget details
+AAI.model-version-id.newvce=7c79e11f-a408-4593-aa86-ba948a1236af
+AAI.model-invariant-id.newvce=4b05ec9c-c55d-4987-83ff-e08d6ddb694f
+#oam-network widget details
+AAI.model-invariant-id.oam-network=2851cf01-9c40-4064-87d4-6184a6fcff35
+AAI.model-version-id.oam-network=f4fb34f3-fd6e-4a8f-a3fb-4ab61a343b79
+#physical-link widget details
+AAI.model-invariant-id.physical-link=c822d81f-822f-4304-9623-1025b53da568
+AAI.model-version-id.physical-link=9c523936-95b4-4d7f-9f53-6bdfe0cf2c05
+#p-interface widget details
+AAI.model-invariant-id.p-interface=94043c37-4e73-439c-a790-0fdd697924cd
+AAI.model-version-id.p-interface=d2cdb2d0-fc1f-4a57-a89e-591b1c4e3754
+#pnf widget details
+AAI.model-version-id.pnf=e9f1fa7d-c839-418a-9601-03dc0d2ad687
+AAI.model-invariant-id.pnf=862b25a1-262a-4961-bdaa-cdc55d69785a
+#port-group widget details
+AAI.model-version-id.port-group=03e8bb6b-b48a-46ae-b5d4-e5af577e6844
+AAI.model-invariant-id.port-group=8ce940fb-55d7-4230-9e7f-a56cc2741f77
+#property-constraint widget details
+AAI.model-version-id.property-constraint=81706bbd-981e-4362-ae20-995cbcb2d995
+AAI.model-invariant-id.property-constraint=f4a863c3-6886-470a-a6ae-05723837ea45
+#pserver widget details
+AAI.model-invariant-id.pserver=6d932c8f-463b-4e76-83fb-87acfbaa2e2d
+AAI.model-version-id.pserver=72f0d495-bc27-4653-9e1a-eef76bd34bc9
+#related-lookup widget details
+AAI.model-invariant-id.related-lookup=468f6f5b-2996-41bb-b2a3-7cf9613ebb9b
+AAI.model-version-id.related-lookup=0988bab5-bf4f-4938-a419-ab249867d12a
+#reserved-prop-names widget details
+AAI.model-invariant-id.reserved-prop-names=0c3e0ba3-618c-498d-9127-c8d42b00170f
+AAI.model-version-id.reserved-prop-names=ac49d26d-9163-430e-934a-13b738a04f5c
+#result-data widget details
+AAI.model-version-id.result-data=4e9b50aa-5227-4f6f-b489-62e6bbc03c79
+AAI.model-invariant-id.result-data=ff656f23-6185-406f-9006-4b26834f3e1c
+#route-table-reference widget details
+AAI.model-version-id.route-table-reference=fed7e326-03a7-45ff-a3f2-471470d268c4
+AAI.model-invariant-id.route-table-reference=a8614b63-2636-4c4f-98df-fd448c4241db
+#routing-instance widget details
+AAI.model-invariant-id.routing-instance=1c2ded4f-8b01-4193-829c-966847dfec3e
+AAI.model-version-id.routing-instance=3ccbcbc7-d19e-44d5-a52f-7e18aa8d69fa
+#secondary-filter widget details
+AAI.model-version-id.secondary-filter=1380619d-dd1a-4cec-b755-c6407833e065
+AAI.model-invariant-id.secondary-filter=738ff299-6290-4c00-8998-bd0e96a07b93
+#segmentation-assignment widget details
+AAI.model-invariant-id.segmentation-assignment=6e814aee-46e1-4583-a9d4-0049bfd2b59b
+AAI.model-version-id.segmentation-assignment=c5171ae0-44fb-4c04-b482-d56702241a44
+#service widget details
+AAI.model-version-id.service=ecce2c42-3957-4ae0-9442-54bc6afe27b6
+AAI.model-invariant-id.service=07a3a60b-1b6c-4367-8173-8014386f89e3
+#service-capability widget details
+AAI.model-invariant-id.service-capability=b1a7cc05-d19d-443b-a5d1-733e325c4232
+AAI.model-version-id.service-capability=f9cfec1b-18da-4bba-bd83-4b26cca115cd
+#service-instance widget details
+AAI.model-invariant-id.service-instance=82194af1-3c2c-485a-8f44-420e22a9eaa4
+AAI.model-version-id.service-instance=46b92144-923a-4d20-b85a-3cbd847668a9
+#service-subscription widget details
+AAI.model-invariant-id.service-subscription=2e1a602a-acd8-4f78-94ff-618b802a303b
+AAI.model-version-id.service-subscription=5e68299a-79f2-4bfb-8fbc-2bae877a2459
+#site-pair widget details
+AAI.model-version-id.site-pair=7106bc02-6552-4fc3-8a56-4f3df9034531
+AAI.model-invariant-id.site-pair=db63f3e6-f8d1-484e-8d5e-191600b7914b
+#site-pair-set widget details
+AAI.model-invariant-id.site-pair-set=5d4dae3e-b402-4bfd-909e-ece12ff75d26
+AAI.model-version-id.site-pair-set=a5c6c1bc-dc38-468e-9459-bb08f87247df
+#snapshot widget details
+AAI.model-version-id.snapshot=962a7c8b-687f-4d32-a775-fe098e214bcd
+AAI.model-invariant-id.snapshot=24de00ef-aead-4b52-995b-0adf8d4bd90d
+#sriov-vf widget details
+AAI.model-version-id.sriov-vf=1e8b331f-3d4a-4160-b7aa-f4d5a8916625
+AAI.model-invariant-id.sriov-vf=04b2935f-33c4-40a9-8af0-8b52690042dc
+#start-node-filter widget details
+AAI.model-version-id.start-node-filter=aad96fd3-e75f-42fc-9777-3450c36f1168
+AAI.model-invariant-id.start-node-filter=083093a3-e407-447a-ba5d-7583e4d23e1d
+#subnet widget details
+AAI.model-version-id.subnet=f902a6bc-6be4-4fe5-8458-a6ec0056b374
+AAI.model-invariant-id.subnet=1b2c9ba7-e449-4831-ba15-3073672f5ef2
+#tagged-inventory-item-list widget details
+AAI.model-invariant-id.tagged-inventory-item-list=e78a7eaa-f65d-4919-9c2b-5b258c8c4d7e
+AAI.model-version-id.tagged-inventory-item-list=c246f6e2-e3a1-4697-94c0-5672a7fbbf04
+#tenant widget details
+AAI.model-invariant-id.tenant=97c26c99-6870-44c1-8a07-1d900d3f4ce6
+AAI.model-version-id.tenant=abcc54bc-bb74-49dc-9043-7f7171707545
+#tunnel-xconnect widget details
+AAI.model-invariant-id.tunnel-xconnect=50b9e2fa-005c-4bbe-b651-3251dece4cd8
+AAI.model-version-id.tunnel-xconnect=e7cb4ca8-e1a5-4487-a716-4ae0bcd8aef5
+#update-node-key widget details
+AAI.model-version-id.update-node-key=6004cfa6-eb6d-4062-971f-b1fde6b74aa0
+AAI.model-invariant-id.update-node-key=fe81c801-f65d-408a-b2b7-a729a18f8154
+#vce widget details
+AAI.model-version-id.vce=b6cf54b5-ec45-43e1-be64-97b4e1513333
+AAI.model-invariant-id.vce=bab6dceb-e7e6-4301-a5e0-a7399b48d792
+#vf-module widget details
+AAI.model-invariant-id.vf-module=ef86f9c5-2165-44f3-8fc3-96018b609ea5
+AAI.model-version-id.vf-module=c00563ae-812b-4e62-8330-7c4d0f47088a
+#vig-server widget details
+AAI.model-version-id.vig-server=8e8c22f1-fbdf-48ea-844c-8bdeb44e7b16
+AAI.model-invariant-id.vig-server=bed7c3b7-35d0-4cd9-abde-41b20e68b28e
+#virtual-data-center widget details
+AAI.model-invariant-id.virtual-data-center=5150abcf-0c5f-4593-9afe-a19c48fc4824
+AAI.model-version-id.virtual-data-center=6dd43ced-d789-47af-a759-d3abc14e3ac1
+#vlan widget details
+AAI.model-version-id.vlan=257d88a5-a269-4c35-944f-aca04fbdb791
+AAI.model-invariant-id.vlan=d2b1eaf1-ae59-4116-9ee4-aa0179faa4f8
+#vnfc widget details
+AAI.model-invariant-id.vnfc=96129eb9-f0de-4e05-8af2-73146473f766
+AAI.model-version-id.vnfc=5761e0a7-c6df-4d8a-9ebd-b8f445054dec
+#vnf-image widget details
+AAI.model-invariant-id.vnf-image=f9a628ff-7aa0-40e2-a93d-02d91c950982
+AAI.model-version-id.vnf-image=c4d3e747-ba4a-4b17-9896-94c6f18c19d3
+#volume widget details
+AAI.model-version-id.volume=0fbe2e8f-4d91-4415-a772-88387049b38d
+AAI.model-invariant-id.volume=ddd739b4-2b25-46c4-affc-41a32af5cc42
+#volume-group widget details
+AAI.model-invariant-id.volume-group=fcec1b02-b2d0-4834-aef8-d71be04717dd
+AAI.model-version-id.volume-group=99d44c90-1f61-4418-b9a6-56586bf38c79
+#vpe widget details
+AAI.model-invariant-id.vpe=053ec3a7-5b72-492d-b54d-123805a9b967
+AAI.model-version-id.vpe=203817d3-829c-42d4-942d-2a935478e993
+#vpls-pe widget details
+AAI.model-version-id.vpls-pe=b1566228-6785-4ce1-aea2-053736f80341
+AAI.model-invariant-id.vpls-pe=457ba89b-334c-4fbd-acc4-160ac0e0cdc0
+#vpn-binding widget details
+AAI.model-invariant-id.vpn-binding=9e23b675-db2b-488b-b459-57aa9857baa0
+AAI.model-version-id.vpn-binding=21a146e5-9901-448c-9197-723076770119
+#vserver widget details
+AAI.model-invariant-id.vserver=ff69d4e0-a8e8-4108-bdb0-dd63217e63c7
+AAI.model-version-id.vserver=8ecb2c5d-7176-4317-a255-26274edfdd53 \ No newline at end of file
diff --git a/catalog-be/src/main/resources/config/SDC.zip b/catalog-be/src/main/resources/config/SDC.zip
new file mode 100644
index 0000000000..dfb4be85fb
--- /dev/null
+++ b/catalog-be/src/main/resources/config/SDC.zip
Binary files differ
diff --git a/catalog-be/src/main/resources/config/configuration.yaml b/catalog-be/src/main/resources/config/configuration.yaml
index b8e80dc17c..3801c8290c 100644
--- a/catalog-be/src/main/resources/config/configuration.yaml
+++ b/catalog-be/src/main/resources/config/configuration.yaml
@@ -5,10 +5,8 @@ identificationHeaderFields:
- HTTP_IV_REMOTE_ADDRESS
- HTTP_CSP_WSTYPE
-
-
# catalog backend hostname
-beFqdn: localhost
+beFqdn: sdccatalog.att.com
# catalog backend http port
beHttpPort: 8080
@@ -24,32 +22,70 @@ beSslPort: 8443
version: 1.0
released: 2012-11-30
+toscaConformanceLevel: 3.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:
+ 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']}
#Application-specific settings of ES
elasticSearch:
@@ -67,7 +103,7 @@ elasticSearch:
# Legal values for creationPeriod - year, month, day, hour, minute, none (meaning no time-based behaviour).
#
# If no creationPeriod is configured for indexPrefix, default behavour is creationPeriod: month.
-
+
indicesTimeFrequency:
- indexPrefix: auditingevents
creationPeriod: month
@@ -93,6 +129,9 @@ artifactTypes:
- AAI_VF_MODULE_MODEL
- AAI_VF_INSTANCE_MODEL
- OTHER
+ - SNMP_POLL
+ - SNMP_TRAP
+ - GUIDE
licenseTypes:
- User
@@ -105,7 +144,9 @@ resourceTypes: &allResourceTypes
- CP
- VL
- VF
-
+ - VFCMT
+ - Abstract
+
# validForResourceTypes usage
# validForResourceTypes:
# - VF
@@ -123,13 +164,18 @@ deploymentResourceArtifacts:
# displayName: "Network HEAT Template"
# type: HEAT_NET
# validForResourceTypes: *allResourceTypes
-
+
deploymentResourceInstanceArtifacts:
heatEnv:
displayName: "HEAT ENV"
type: HEAT_ENV
description: "Auto-generated HEAT Environment deployment artifact"
fileExtension: "env"
+ VfHeatEnv:
+ displayName: "VF HEAT ENV"
+ type: HEAT_ENV
+ description: "VF Auto-generated HEAT Environment deployment artifact"
+ fileExtension: "env"
#tosca artifacts placeholders
toscaArtifacts:
@@ -161,7 +207,7 @@ informationalResourceArtifacts:
testScripts:
displayName: Test Scripts
type: OTHER
- cloudQuestionnaire:
+ CloudQuestionnaire:
displayName: Cloud Questionnaire (completed)
type: OTHER
HEATTemplateFromVendor:
@@ -170,7 +216,7 @@ informationalResourceArtifacts:
resourceSecurityTemplate:
displayName: Resource Security Template
type: OTHER
-
+
excludeServiceCategory:
informationalServiceArtifacts:
@@ -213,7 +259,7 @@ informationalServiceArtifacts:
serviceSecurityTemplate:
displayName: Service Security Template
type: OTHER
-
+
serviceApiArtifacts:
configuration:
displayName: Configuration
@@ -234,7 +280,6 @@ serviceApiArtifacts:
displayName: Testing
type: OTHER
-
additionalInformationMaxNumberOfKeys: 50
systemMonitoring:
@@ -281,19 +326,19 @@ resourceDeploymentArtifacts:
- yaml
- yml
validForResourceTypes: *allResourceTypes
- HEAT_NESTED:
+ HEAT_NET:
acceptedTypes:
- yaml
- yml
validForResourceTypes: *allResourceTypes
- HEAT_ARTIFACT:
- acceptedTypes:
- validForResourceTypes: *allResourceTypes
- HEAT_NET:
+ HEAT_NESTED:
acceptedTypes:
- yaml
- yml
validForResourceTypes: *allResourceTypes
+ HEAT_ARTIFACT:
+ acceptedTypes:
+ validForResourceTypes: *allResourceTypes
YANG_XML:
acceptedTypes:
- xml
@@ -318,37 +363,55 @@ resourceDeploymentArtifacts:
acceptedTypes:
- xml
validForResourceTypes: *allResourceTypes
- #APPC Artifatcs
+ 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 Artifacts
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
+ - VF
+ - VFCMT
DCAE_EVENT:
acceptedTypes:
validForResourceTypes:
- VF
-#AAI Artifacts
+ - VFCMT
AAI_VF_MODEL:
acceptedTypes:
- xml
@@ -362,6 +425,12 @@ resourceDeploymentArtifacts:
OTHER:
acceptedTypes:
validForResourceTypes: *allResourceTypes
+ SNMP_POLL:
+ acceptedTypes:
+ validForResourceTypes: *allResourceTypes
+ SNMP_TRAP:
+ acceptedTypes:
+ validForResourceTypes: *allResourceTypes
resourceInstanceDeploymentArtifacts:
HEAT_ENV:
@@ -370,7 +439,13 @@ resourceInstanceDeploymentArtifacts:
VF_MODULES_METADATA:
acceptedTypes:
- json
-#DCAE_VF Instance Artifacts
+ VES_EVENTS:
+ acceptedTypes:
+ - yaml
+ - yml
+ PERFORMANCE_COUNTER:
+ acceptedTypes:
+ - csv
DCAE_INVENTORY_TOSCA:
acceptedTypes:
- yml
@@ -387,15 +462,62 @@ resourceInstanceDeploymentArtifacts:
acceptedTypes:
DCAE_INVENTORY_EVENT:
acceptedTypes:
-
-
-resourceInformationalDeployedArtifacts:
+ 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: *allResourceTypes
+ SNMP_POLL:
+ acceptedTypes:
+ validForResourceTypes: *allResourceTypes
+ SNMP_TRAP:
+ acceptedTypes:
+ validForResourceTypes: *allResourceTypes
+ GUIDE:
+ acceptedTypes:
+ validForResourceTypes:
+ - VF
+ - VFC
+resourceInformationalDeployedArtifacts:
requirementsToFulfillBeforeCert:
capabilitiesToConsumeBeforeCert:
-
+
unLoggedUrls:
- /sdc2/rest/healthCheck
@@ -407,54 +529,34 @@ cleanComponentsConfiguration:
artifactsIndex: resources
-cassandraConfig:
- cassandraHosts: ['localhost']
- localDataCenter:
- reconnectTimeout : 30000
- authenticate: false
- username: koko
- password: bobo
- ssl: false
- truststorePath : /path/path
- truststorePassword : 123123
- keySpaces:
- - { name: sdcaudit, replicationStrategy: SimpleStrategy, replicationInfo: ['1']}
- - { name: sdcartifact, replicationStrategy: SimpleStrategy, replicationInfo: ['1']}
- - { name: sdccomponent, replicationStrategy: SimpleStrategy, replicationInfo: ['1']}
-
-
+heatEnvArtifactHeader: ""
+heatEnvArtifactFooter: ""
+
+onboarding:
+ protocol: http
+ host: localhost
+ port: 8080
+ downloadCsarUri: "/onboarding-api/v1.0/vendor-software-products/packages"
+
switchoverDetector:
- gBeFqdn:
- gFeFqdn:
- beVip: 1.2.3.4
- feVip: 1.2.3.4
+ 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://localhost/crt/CipDomain.ECOMP-ASDC-DEVST/config/update_network?user=root"
+ publishNetworkUrl: "http://xxx.com/crt/CipDomain.ECOMP-ASDC-DEVST/config/update_network?user=root"
publishNetworkBody: '{"note":"publish network"}'
groups:
- beSet: { changePriorityUrl: "http://localhost/crt/CipDomain.ECOMP-ASDC-DEVST/config/sites/AIO-BE.ecomp.idns.cip?user=root",
- changePriorityBody: '{"name":"AIO-BE.ecomp.idns.cip","uri":"/crt/CipDomain.ECOMP-ASDC-DEVST/config/sites/AIO-BE.ecomp.idns.cip","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://cora.web/crt/CipDomain.ECOMP-ASDC-DEVST/config/sites/AIO-FE.ecomp.idns.cip?user=root",
- changePriorityBody: '{"comment":"AIO G-fqdn","name":"AIO-FE.ecomp.idns.cip","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"}'}
-
-
-heatEnvArtifactHeader:
- ""
-heatEnvArtifactFooter:
- ""
+ 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"}'}
-onboarding:
- protocol: http
- host: localhost
- port: 8080
- downloadCsarUri: "/onboarding-api/v1.0/vendor-software-products/packages"
- #downloadCsarUri: "/onboardingci/onbrest/onboarding-api/v1.0/vendor-software-products/packages"
-
applicationL1Cache:
datatypes:
enabled: true
@@ -474,5 +576,25 @@ applicationL2Cache:
numberOfCacheWorkers: 4
toscaValidators:
- stringMaxLength: 65536
-disableAudit: false \ No newline at end of file
+ stringMaxLength: 2500
+
+disableAudit: false
+
+vfModuleProperties:
+ min_vf_module_instances:
+ forBaseModule: 1
+ forNonBaseModule: 0
+ max_vf_module_instances:
+ forBaseModule: 1
+ forNonBaseModule:
+ initial_count:
+ forBaseModule: 1
+ forNonBaseModule: 0
+ vf_module_type:
+ forBaseModule: Base
+ forNonBaseModule: Expansion
+
+genericAssetNodeTypes:
+ VFC: org.openecomp.resource.abstract.nodes.VFC
+ VF : org.openecomp.resource.abstract.nodes.VF
+ Service: org.openecomp.resource.abstract.nodes.service
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 8c56a26785..5d93601ea0 100644
--- a/catalog-be/src/main/resources/config/distribution-engine-configuration.yaml
+++ b/catalog-be/src/main/resources/config/distribution-engine-configuration.yaml
@@ -1,7 +1,7 @@
uebServers:
- - uebsb91sfdc.it.att.com:3904
- - uebsb92sfdc.it.att.com:3904
- - uebsb93sfdc.it.att.com:3904
+ - uebsb91sfdc.it.att.com
+ - uebsb92sfdc.it.att.com
+ - uebsb93sfdc.it.att.com
# prev Kansas City Sandbox uebPublicKey: 8F3MDAtMSBwwpSMy
uebPublicKey: sSJc5qiBnKy2qrlc
diff --git a/catalog-be/src/main/resources/config/error-configuration.yaml b/catalog-be/src/main/resources/config/error-configuration.yaml
index 0054ce2be9..ef7a885678 100644
--- a/catalog-be/src/main/resources/config/error-configuration.yaml
+++ b/catalog-be/src/main/resources/config/error-configuration.yaml
@@ -42,16 +42,17 @@ errors:
message: "Error: Not authorized to use the API.",
messageId: "POL5003"
}
+#---------POL5004------------------------------
+ MISSING_USER_ID: {
+ code: 400 ,
+ message: "Error: Missing 'USER_ID' HTTP header.",
+ messageId: "POL5004"
+ }
#---------SVC4000-----------------------------
INVALID_CONTENT: {
code: 400,
message: "Error: Invalid content.",
messageId: "SVC4000"
- }#---------SVC4000-----------------------------
- INVALID_CONTENT: {
- code: 400,
- message: "Error: Invalid content.",
- messageId: "SVC4000"
}
#---------SVC4002-----------------------------
MISSING_INFORMATION: {
@@ -60,7 +61,7 @@ errors:
messageId: "SVC4002"
}
#---------SVC4003------------------------------
-# %1 - Users's USER_ID
+# %1 - Users's ID
USER_NOT_FOUND: {
code: 404,
message: "Error: User '%1' was not found.",
@@ -104,7 +105,7 @@ errors:
# %1 - service/resource
COMPONENT_MISSING_CONTACT: {
code: 400,
- message: "Error: Invalid Content. Missing %1 contact id.",
+ message: "Error: Invalid Content. Missing %1 contact.",
messageId: "SVC4049"
}
#---------SVC4050-----------------------------
@@ -207,14 +208,14 @@ errors:
}
#---------SVC4064------------------------------
-# %1 - Service/Resource
+# %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
+# %1 - Service/Resource/Property
# %2 - max resource/service name length
COMPONENT_DESCRIPTION_EXCEEDS_LIMIT: {
code: 400,
@@ -245,9 +246,9 @@ errors:
#---------SVC4069------------------------------
# %1 - Service/Resource/Product
- COMPONENT_INVALID_CONTACT_ID: {
+ COMPONENT_INVALID_CONTACT: {
code: 400,
- message: "Error: Invalid Content. %1 contact id should be in format 'mnnnnnn' or 'aannna' or 'aannnn', where m=m ,a=a-zA-Z and n=0-9",
+ message: "Error: Invalid Content. %1 Contact Id should be in format 'mnnnnnn' or 'aannna' or 'aannnn', where m=m ,a=a-zA-Z and n=0-9",
messageId: "SVC4069"
}
#---------SVC4070------------------------------
@@ -283,7 +284,7 @@ errors:
# %2 - resource/service
# %3 - First name of last modifier
# %4 - Last name of last modifier
-# %5 - USER_ID of last modifier
+# %5 - USER_ID of last modifier
COMPONENT_IN_CHECKOUT_STATE: {
code: 403,
message: "Error: Requested '%1' %2 is locked for modification by %3 %4(%5).",
@@ -511,7 +512,7 @@ errors:
#-----------SVC4130---------------------------
INVALID_PROJECT_CODE: {
code: 400,
- message: "Error: Invalid Content. PROJECT_CODE number must be numeric from 5 up to 10 digits.",
+ message: "Error: Invalid Content. PROJECT_CODE must be from 3 up to 50 characters.",
messageId: "SVC4130"
}
#-----------SVC4131---------------------------
@@ -1060,7 +1061,7 @@ errors:
messageId: "SVC4567"
}
#---------SVC4567------------------------------
-# %1 - "User Name and userId"
+# %1 - "User Name and UserId"
# %2 -"checked-out"/"in-certification"
CANNOT_DELETE_USER_WITH_ACTIVE_ELEMENTS: {
code: 409,
@@ -1068,7 +1069,7 @@ errors:
messageId: "SVC4567"
}
#---------SVC4568------------------------------
-# %1 - "User Name and userId"
+# %1 - "User Name and UserId"
# %2 -"checked-out"/"in-certification"
CANNOT_UPDATE_USER_WITH_ACTIVE_ELEMENTS: {
code: 409,
@@ -1144,7 +1145,7 @@ errors:
messageId: "SVC4580"
}
#---------SVC4581------------------------------
-# %1 - userId
+# %1 - UserId
INVALID_PRODUCT_CONTACT: {
code: 400,
message: "Error: Invalid content. User '%1' cannot be set as Product Contact.",
@@ -1692,3 +1693,86 @@ errors:
message: "Error: %1 %2 automatic generation of artifacts failed. Description: %3",
messageId: "SVC4650"
}
+#---------SVC4651------------------------------
+ PARENT_RESOURCE_DOES_NOT_EXTEND: {
+ code: 400,
+ message: "Error: Once resource is certified, derived_from can be changed only to a sibling",
+ messageId: "SVC4651"
+ }
+#---------SVC4652------------------------------
+# %1 - resource/service
+ COMPONENT_INVALID_SUBCATEGORY: {
+ code: 400,
+ message: "Error: Invalid Content. Invalid %1 sub category.",
+ messageId: "SVC4652"
+ }
+#---------SVC4653------------------------------
+# %1 - group instance uniqueId
+# %2 - service uniqueId
+ GROUP_INSTANCE_NOT_FOUND_ON_COMPONENT_INSTANCE: {
+ code: 404,
+ message: "Error: Requested group instance %1 was not found on component %2.",
+ messageId: "SVC4653"
+ }
+#---------SVC4654------------------------------
+# %1 - group property name
+# %2 - valid min limit value
+# %3 - valid max limit value
+ INVALID_GROUP_MIN_MAX_INSTANCES_PROPERTY_VALUE: {
+ code: 400,
+ message: "Error: Value of %1 must be not higher than %2, and not lower than %3.",
+ messageId: "SVC4654"
+ }
+#---------SVC4655------------------------------
+# %1 - group property name
+# %2 - valid min limit value
+# %3 - valid max limit value
+ INVALID_GROUP_INITIAL_COUNT_PROPERTY_VALUE: {
+ code: 400,
+ message: "Error: Value of %1 must be between %2 and %3.",
+ messageId: "SVC4655"
+ }
+#---------SVC4656------------------------------
+# %1 - group property name
+# %2 - lower/higher
+# %3 - valid max/min value
+ INVALID_GROUP_PROPERTY_VALUE_LOWER_HIGHER: {
+ code: 400,
+ message: "Error: Value of %1 must be %2 or equals to %3.",
+ messageId: "SVC4656"
+ }
+#---------SVC4657------------------------------
+# %1 - certificationRequest / startTesting
+ RESOURCE_VFCMT_LIFECYCLE_STATE_NOT_VALID: {
+ code: 400,
+ message: "Error - Lifecycle state %1 is not valid for resource of type VFCMT",
+ messageId: "SVC4657"
+ }
+#---------SVC4658------------------------------
+# %1 – asset type [service / resource ]
+# %2 – main asset uuid
+# %3 – not found asset type [service / resource]
+# %4 – not found asset name
+ ASSET_NOT_FOUND_DURING_CSAR_CREATION: {
+ code: 400,
+ message: "Error: CSAR packaging failed for %1 %2. %3 %4 was not found",
+ messageId: "SVC4658"
+ }
+#---------SVC4659------------------------------
+# %1 – asset type [service / resource ]
+# %2 – main asset uuid
+# %3 – Artifact name
+# %4 – Artifact uuid
+ ARTIFACT_PAYLOAD_NOT_FOUND_DURING_CSAR_CREATION: {
+ code: 400,
+ message: " Error: CSAR packaging failed for %1 %2. Artifact %3 [%4] was not found",
+ messageId: "SVC4659"
+ }
+#---------SVC4660------------------------------
+# %1 - assetType
+# %2 - matching generic node type name
+ GENERIC_TYPE_NOT_FOUND: {
+ code: 404,
+ message: "Creation of %1 failed. Generic type %2 was not found",
+ messageId: "SVC4660"
+ }
diff --git a/catalog-be/src/main/resources/config/logback.xml b/catalog-be/src/main/resources/config/logback.xml
index 5d5e4c670d..8ba0a31944 100644
--- a/catalog-be/src/main/resources/config/logback.xml
+++ b/catalog-be/src/main/resources/config/logback.xml
@@ -9,7 +9,9 @@
<!-- value used by pattern field list (| - is inter-field separator, || - unavailable or not applicable field value) (m - mandatory, o- optional)-->
<!--timestamp(m)| requestID(m)| serviceInstanceID(o)| threadID(m)| physicalServerName(o)| serviceName(m)| userID(m)| logLevel(m)| severity(o)| serverIpAddress(m)| serverName(m)| clientIpAddress(o)| className(m)| timer(o)| detailedMessage(o)-->
<property name="default-log-pattern"
- value="%d{yyyy-MM-dd'T'HH:mm:ss.SSSXXX}|%X{uuid}|%X{serviceInstanceID}|%thread||${ECOMP-subcomponent-name}|%X{userId}|%level|%X{alarmSeverity}|%X{localAddr}|${beFqdn}|%X{remoteAddr}|%logger{35}|%X{timer}|ActivityType=&lt;%M&gt;, Desc=&lt;%msg&gt;%n" />
+ 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="asdc-debug-log-pattern" value="%d{yyyy-MM-dd'T'HH:mm:ss.SSSXXX}|%X{RequestId}|%msg %n"/>
<!-- All log -->
<if condition='property("enable-all-log").equalsIgnoreCase("true")'>
@@ -113,7 +115,8 @@
</expression>
</evaluator>
<OnMismatch>DENY</OnMismatch>
- <OnMatch>NEUTRAL</OnMatch>
+ <!--<OnMatch>NEUTRAL</OnMatch>-->
+ <OnMatch>ACCEPT</OnMatch>
</filter>
<rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
@@ -132,6 +135,52 @@
</encoder>
</appender>
+
+ <!-- ASDC debug by package-->
+ <appender name="PACKAGE_DEBUG_ROLLING"
+ class="ch.qos.logback.core.rolling.RollingFileAppender">
+ <file>${log.home}/${ECOMP-component-name}/${ECOMP-subcomponent-name}/debug_by_package.log
+ </file>
+
+ <!-- No need to deny audit messages - they are INFO only, will be denied
+ anyway -->
+ <!-- Transaction messages filter - deny Transaction messages, there are
+ some DEBUG level messages among them -->
+ <filter class="ch.qos.logback.core.filter.EvaluatorFilter">
+ <evaluator class="ch.qos.logback.classic.boolex.OnMarkerEvaluator">
+ <marker>TRANSACTION_MARKER</marker>
+ </evaluator>
+ <onMismatch>NEUTRAL</onMismatch>
+ <onMatch>DENY</onMatch>
+ </filter>
+
+ <!-- accept DEBUG and TRACE level -->
+ <filter class="ch.qos.logback.core.filter.EvaluatorFilter">
+ <evaluator class="ch.qos.logback.classic.boolex.GEventEvaluator">
+ <expression>
+ e.level.toInt() &lt;= DEBUG.toInt()
+ </expression>
+ </evaluator>
+ <OnMismatch>DENY</OnMismatch>
+ <OnMatch>NEUTRAL</OnMatch>
+ </filter>
+
+ <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
+ <fileNamePattern>${log.home}/${ECOMP-component-name}/${ECOMP-subcomponent-name}/debug_by_package.log.%i
+ </fileNamePattern>
+ <minIndex>1</minIndex>
+ <maxIndex>10</maxIndex>
+ </rollingPolicy>
+
+ <triggeringPolicy
+ class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
+ <maxFileSize>20MB</maxFileSize>
+ </triggeringPolicy>
+ <encoder>
+ <pattern>${asdc-debug-log-pattern}</pattern>
+ </encoder>
+ </appender>
+
<!-- Audit log -->
<appender name="AUDIT_ROLLING"
class="ch.qos.logback.core.rolling.RollingFileAppender">
@@ -143,6 +192,7 @@
<filter class="ch.qos.logback.core.filter.EvaluatorFilter">
<evaluator class="ch.qos.logback.classic.boolex.OnMarkerEvaluator">
<marker>AUDIT_MARKER</marker>
+ <marker>AUDIT</marker>
</evaluator>
<onMismatch>DENY</onMismatch>
<onMatch>ACCEPT</onMatch>
@@ -163,6 +213,38 @@
<pattern>${default-log-pattern}</pattern>
</encoder>
</appender>
+
+ <!-- Metrics log -->
+ <appender name="METRICS_ROLLING"
+ class="ch.qos.logback.core.rolling.RollingFileAppender">
+
+ <file>${log.home}/${ECOMP-component-name}/${ECOMP-subcomponent-name}/metrics.log
+ </file>
+
+ <!-- Metric messages filter - accept metric messages -->
+ <filter class="ch.qos.logback.core.filter.EvaluatorFilter">
+ <evaluator class="ch.qos.logback.classic.boolex.OnMarkerEvaluator">
+ <marker>METRICS</marker>
+ </evaluator>
+ <onMismatch>DENY</onMismatch>
+ <onMatch>ACCEPT</onMatch>
+ </filter>
+
+ <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
+ <fileNamePattern>${log.home}/${ECOMP-component-name}/${ECOMP-subcomponent-name}/metrics.log.%i
+ </fileNamePattern>
+ <minIndex>1</minIndex>
+ <maxIndex>10</maxIndex>
+ </rollingPolicy>
+
+ <triggeringPolicy
+ class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
+ <maxFileSize>20MB</maxFileSize>
+ </triggeringPolicy>
+ <encoder>
+ <pattern>${default-log-pattern}</pattern>
+ </encoder>
+ </appender>
<!-- SdncTransaction log -->
<appender name="TRANSACTION_ROLLING"
@@ -209,12 +291,32 @@
<appender-ref ref="ERROR_ROLLING" />
</appender>
+ <!-- <appender name="DISPATCHER" class="ch.qos.logback.classic.sift.SiftingAppender">
+ <discriminator class="org.openecomp.core.logging.logback.EventTypeDiscriminator"/>
+ <sift>
+ <appender name="Audit" class="ch.qos.logback.core.rolling.RollingFileAppender">
+ <file>${logDirectory}/audit.log</file>
+ <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
+ <fileNamePattern>${logDirectory}/audit.%i.log.zip</fileNamePattern>
+ <minIndex>1</minIndex>
+ <maxIndex>9</maxIndex>
+ </rollingPolicy>
+ <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
+ <maxFileSize>5MB</maxFileSize>
+ </triggeringPolicy>
+ <encoder>
+ <pattern>${default-log-pattern}</pattern>
+ </encoder>
+ </appender>
+ </sift>
+ </appender>-->
<root level="INFO">
<appender-ref ref="ASYNC_ERROR" />
<appender-ref ref="ASYNC_DEBUG" />
<appender-ref ref="AUDIT_ROLLING" />
<appender-ref ref="ASYNC_TRANSACTION" />
+ <appender-ref ref="METRICS_ROLLING" />
<if condition='property("enable-all-log").equalsIgnoreCase("true")'>
<then>
<appender-ref ref="ALL_ROLLING" />
diff --git a/catalog-be/src/main/resources/config/titan.properties b/catalog-be/src/main/resources/config/titan.properties
index 7eb57235c7..5411a44224 100644
--- a/catalog-be/src/main/resources/config/titan.properties
+++ b/catalog-be/src/main/resources/config/titan.properties
@@ -8,3 +8,4 @@ cache.db-cache-time = 180000
cache.db-cache-size = 0.5
cache.tx-cache-size = 500000
+storage.cassandra.keyspace=sdctitan
diff --git a/catalog-be/src/main/resources/elasticsearch.yml b/catalog-be/src/main/resources/elasticsearch.yml
index b4634c8213..71ccdbb8f5 100644
--- a/catalog-be/src/main/resources/elasticsearch.yml
+++ b/catalog-be/src/main/resources/elasticsearch.yml
@@ -1,17 +1,24 @@
-cluster.name: elasticsearch_1_5_2
-
+cluster.name: elasticsearch
+
+discovery.zen.ping.multicast.enabled: false
+discovery.zen.ping.unicast.enabled: true
discovery.zen.ping.unicast.hosts: elasticsearch_host
http.cors.enabled: true
-#plugin.types: "DeleteByQueryPlugin"
-#path.home: "/home/vagrant/catalog-be/config"
+
+path.home: "/home/vagrant/catalog-be/config"
elasticSearch.transportclient: true
transport.client.initial_nodes:
- elasticsearch_host:9300
+#shield.user: asdc:Aa12345
+#shield.ssl.keystore.path: "/vagrant/install/resources/catalog-be/keystore/es-client.jks"
+#shield.ssl.keystore.password: Aa123456
+#shield.transport.ssl: true
+
##################### Elasticsearch Configuration Example #####################
# This file contains an overview of various configuration settings,
@@ -157,7 +164,6 @@ index.number_of_replicas: 0
# Path to directory containing configuration (this file and logging.yml):
#
path.conf: /src/test/resources
-#path.home: /src/test/resources
# Path to directory where to store index data allocated for this node.
#
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 d8d9f20d40..c94909101b 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
@@ -144,6 +144,8 @@ tosca.capabilities.Container.Docker:
required: false
tosca.capabilities.network.Linkable:
derived_from: tosca.capabilities.Root
+org.openecomp.capabilities.AllottedResource:
+ derived_from: tosca.capabilities.Root
tosca.capabilities.nfv.Metric:
derived_from: tosca.capabilities.Endpoint
org.openecomp.capabilities.Metric:
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 add3a8ce1f..1742545f14 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/categories/categoryTypes.yml b/catalog-be/src/main/resources/import/tosca/categories/categoryTypes.yml
index 9ddce45e4e..8914207b0f 100644
--- a/catalog-be/src/main/resources/import/tosca/categories/categoryTypes.yml
+++ b/catalog-be/src/main/resources/import/tosca/categories/categoryTypes.yml
@@ -28,8 +28,8 @@ resources:
name: "LAN Connectors"
icons: ['network','connector','port']
Infrastructure:
- name: "Infrastructure"
- icons: ['ucpe']
+ name: "Infrastructure"
+ icons: ['ucpe']
NetworkLayer4:
name: "Network L4+"
subcategories:
@@ -113,4 +113,31 @@ resources:
icons: ['dcae_database']
Policy:
name: "Policy"
- icons: ['dcae_policy'] \ No newline at end of file
+ icons: ['dcae_policy']
+ Template:
+ name: "Template"
+ subcategories:
+ MonitoringTemplate:
+ name: "Monitoring Template"
+ icons: ['monitoring_template']
+ AllottedResource:
+ name: "Allotted Resource"
+ subcategories:
+ AllottedResource:
+ name: "Allotted Resource"
+ icons: ['allotted_resource']
+ TunnelXConnect:
+ name: "Tunnel XConnect"
+ icons: ['tunnel_x_connect']
+ IpMuxDemux:
+ name: "IP Mux Demux"
+ icons: ['ip_mux_demux']
+ ServiceAdmin:
+ name: "Service Admin"
+ icons: ['service_admin']
+ ContrailRoute:
+ name: "Contrail Route"
+ icons: ['contrail_route']
+ SecurityZone:
+ name: "Security Zone"
+ icons: ['security_zone'] \ No newline at end of file
diff --git a/catalog-be/src/main/resources/import/tosca/categories/categoryTypes.zip b/catalog-be/src/main/resources/import/tosca/categories/categoryTypes.zip
index c04a2faefc..7a0e6bcad7 100644
--- a/catalog-be/src/main/resources/import/tosca/categories/categoryTypes.zip
+++ b/catalog-be/src/main/resources/import/tosca/categories/categoryTypes.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 1fdc3a2cd2..b4c442f3df 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
@@ -13,15 +13,15 @@ boolean:
float:
derived_from: tosca.datatypes.Root
-json:
- derived_from: tosca.datatypes.Root
-
list:
derived_from: tosca.datatypes.Root
map:
derived_from: tosca.datatypes.Root
+json:
+ derived_from: tosca.datatypes.Root
+
tosca.datatypes.Credential:
derived_from: tosca.datatypes.Root
properties:
@@ -107,7 +107,7 @@ tosca.datatypes.network.PortSpec:
constraints:
- in_range: [ 1, 65535 ]
-
+###################new Data Types Onboarding Integration##########################
org.openecomp.datatypes.heat.network.AddressPair:
derived_from: tosca.datatypes.Root
@@ -123,6 +123,7 @@ org.openecomp.datatypes.heat.network.AddressPair:
description: IP address
required: false
status: SUPPORTED
+
org.openecomp.datatypes.heat.network.subnet.HostRoute:
derived_from: tosca.datatypes.Root
description: Host route info for the subnet
@@ -309,6 +310,7 @@ org.openecomp.datatypes.heat.novaServer.network.PortExtraProperties:
status: SUPPORTED
entry_schema:
type: string
+
org.openecomp.datatypes.heat.novaServer.network.AddressInfo:
derived_from: tosca.datatypes.network.NetworkInfo
description: Network addresses with corresponding port id
@@ -318,6 +320,7 @@ org.openecomp.datatypes.heat.novaServer.network.AddressInfo:
description: Port id
required: false
status: SUPPORTED
+
org.openecomp.datatypes.heat.neutron.port.FixedIps:
derived_from: tosca.datatypes.Root
description: subnet/ip_address
@@ -332,6 +335,7 @@ org.openecomp.datatypes.heat.neutron.port.FixedIps:
description: IP address desired in the subnet for this port
required: false
status: SUPPORTED
+
org.openecomp.datatypes.heat.FileInfo:
derived_from: tosca.datatypes.Root
description: Heat File Info
@@ -352,6 +356,7 @@ org.openecomp.datatypes.heat.FileInfo:
- env
- volume
- network
+
org.openecomp.datatypes.heat.contrail.network.rule.PortPairs:
derived_from: tosca.datatypes.Root
description: source and destination port pairs
@@ -366,6 +371,7 @@ org.openecomp.datatypes.heat.contrail.network.rule.PortPairs:
description: End port
required: false
status: SUPPORTED
+
org.openecomp.datatypes.heat.contrail.network.rule.Rule:
derived_from: tosca.datatypes.Root
description: policy rule
@@ -413,6 +419,7 @@ org.openecomp.datatypes.heat.contrail.network.rule.Rule:
description: Direction
required: false
status: SUPPORTED
+
org.openecomp.datatypes.heat.contrail.network.rule.RuleList:
derived_from: tosca.datatypes.Root
description: list of policy rules
@@ -423,7 +430,8 @@ org.openecomp.datatypes.heat.contrail.network.rule.RuleList:
required: false
status: SUPPORTED
entry_schema:
- type: corg.openecomp.datatypes.heat.contrail.network.rule.Rule
+ type: org.openecomp.datatypes.heat.contrail.network.rule.Rule
+
org.openecomp.datatypes.heat.contrail.network.rule.VirtualNetwork:
derived_from: tosca.datatypes.Root
description: source and destination addresses
@@ -507,6 +515,7 @@ org.openecomp.datatypes.heat.network.neutron.SecurityRules.Rule:
- in_range:
- 0
- 65535
+
org.openecomp.datatypes.heat.substitution.SubstitutionFiltering:
derived_from: tosca.datatypes.Root
description: Substitution Filter
@@ -542,6 +551,7 @@ org.openecomp.datatypes.heat.substitution.SubstitutionFiltering:
required: false
default: true
status: SUPPORTED
+
org.openecomp.datatypes.heat.contrailV2.virtual.network.rule.RefDataSequence:
derived_from: tosca.datatypes.Root
description: network policy refs data sequence
@@ -556,6 +566,7 @@ org.openecomp.datatypes.heat.contrailV2.virtual.network.rule.RefDataSequence:
description: Network Policy ref data sequence Minor
required: false
status: SUPPORTED
+
org.openecomp.datatypes.heat.contrailV2.virtual.network.rule.RefData:
derived_from: tosca.datatypes.Root
description: network policy refs data
@@ -565,6 +576,7 @@ org.openecomp.datatypes.heat.contrailV2.virtual.network.rule.RefData:
description: Network Policy ref data sequence
required: false
status: SUPPORTED
+
org.openecomp.datatypes.heat.contrailV2.virtual.network.rule.ref.data.IpamSubnet:
derived_from: tosca.datatypes.Root
description: Network Ipam Ref Data Subnet
@@ -579,6 +591,7 @@ org.openecomp.datatypes.heat.contrailV2.virtual.network.rule.ref.data.IpamSubnet
description: Network ipam refs data ipam subnets ip prefix
required: false
status: SUPPORTED
+
org.openecomp.datatypes.heat.contrailV2.virtual.network.rule.ref.data.IpamSubnetList:
derived_from: tosca.datatypes.Root
description: Network Ipam Ref Data Subnet List
@@ -593,6 +606,7 @@ org.openecomp.datatypes.heat.contrailV2.virtual.network.rule.ref.data.IpamSubnet
description: Network ipam refs data ipam subnets addr from start
required: false
status: SUPPORTED
+
org.openecomp.datatypes.heat.contrailV2.virtual.network.rule.IpamRefData:
derived_from: tosca.datatypes.Root
description: Network Ipam Ref Data
@@ -604,6 +618,7 @@ org.openecomp.datatypes.heat.contrailV2.virtual.network.rule.IpamRefData:
status: SUPPORTED
entry_schema:
type: org.openecomp.datatypes.heat.contrailV2.virtual.network.rule.ref.data.IpamSubnetList
+
org.openecomp.datatypes.heat.contrailV2.network.rule.SrcVirtualNetwork:
derived_from: tosca.datatypes.Root
description: source addresses
@@ -613,6 +628,7 @@ org.openecomp.datatypes.heat.contrailV2.network.rule.SrcVirtualNetwork:
description: Source addresses Virtual network
required: false
status: SUPPORTED
+
org.openecomp.datatypes.heat.contrailV2.network.rule.DstVirtualNetwork:
derived_from: tosca.datatypes.Root
description: destination addresses
@@ -622,6 +638,7 @@ org.openecomp.datatypes.heat.contrailV2.network.rule.DstVirtualNetwork:
description: Destination addresses Virtual network
required: false
status: SUPPORTED
+
org.openecomp.datatypes.heat.contrailV2.network.rule.DstPortPairs:
derived_from: tosca.datatypes.Root
description: destination port pairs
@@ -636,6 +653,7 @@ org.openecomp.datatypes.heat.contrailV2.network.rule.DstPortPairs:
description: End port
required: false
status: SUPPORTED
+
org.openecomp.datatypes.heat.contrailV2.network.rule.SrcPortPairs:
derived_from: tosca.datatypes.Root
description: source port pairs
@@ -650,6 +668,7 @@ org.openecomp.datatypes.heat.contrailV2.network.rule.SrcPortPairs:
description: End port
required: false
status: SUPPORTED
+
org.openecomp.datatypes.heat.contrailV2.network.rule.ActionList:
derived_from: tosca.datatypes.Root
description: Action List
@@ -666,22 +685,7 @@ org.openecomp.datatypes.heat.contrailV2.network.rule.ActionList:
status: SUPPORTED
entry_schema:
type: string
-org.openecomp.datatypes.heat.contrailV2.network.rule.ActionList:
- derived_from: tosca.datatypes.Root
- description: Action List
- properties:
- network_policy_entries_policy_rule_action_list_simple_action:
- type: string
- description: Simple Action
- required: false
- status: SUPPORTED
- network_policy_entries_policy_rule_action_list_apply_service:
- type: list
- description: Apply Service
- required: false
- status: SUPPORTED
- entry_schema:
- type: string
+
org.openecomp.datatypes.heat.contrailV2.network.rule.Rule:
derived_from: tosca.datatypes.Root
description: policy rule
@@ -729,6 +733,7 @@ org.openecomp.datatypes.heat.contrailV2.network.rule.Rule:
description: Action list
required: false
status: SUPPORTED
+
org.openecomp.datatypes.heat.contrailV2.network.rule.RuleList:
derived_from: tosca.datatypes.Root
description: list of policy rules
@@ -740,6 +745,7 @@ org.openecomp.datatypes.heat.contrailV2.network.rule.RuleList:
status: SUPPORTED
entry_schema:
type: org.openecomp.datatypes.heat.contrailV2.network.rule.Rule
+
org.openecomp.datatypes.heat.network.contrail.port.StaticRoute:
derived_from: tosca.datatypes.Root
description: static route
@@ -759,6 +765,7 @@ org.openecomp.datatypes.heat.network.contrail.port.StaticRoute:
description: Next hop type
required: false
status: SUPPORTED
+
org.openecomp.datatypes.heat.network.contrail.AddressPair:
derived_from: tosca.datatypes.Root
description: Address Pair
@@ -782,6 +789,7 @@ org.openecomp.datatypes.heat.network.contrail.AddressPair:
description: Mac address
required: false
status: SUPPORTED
+
org.openecomp.datatypes.heat.network.contrail.InterfaceData:
derived_from: tosca.datatypes.Root
description: Interface Data
@@ -810,6 +818,7 @@ org.openecomp.datatypes.heat.network.contrail.InterfaceData:
description: IP for this interface
required: false
status: SUPPORTED
+
org.openecomp.datatypes.heat.contrailV2.virtual.machine.interface.Properties:
derived_from: tosca.datatypes.Root
description: Virtual Machine Interface Properties.
@@ -818,4 +827,360 @@ org.openecomp.datatypes.heat.contrailV2.virtual.machine.interface.Properties:
type: string
description: Service Interface Type.
required: false
- status: SUPPORTED \ No newline at end of file
+ status: SUPPORTED
+
+org.openecomp.datatypes.Root:
+ derived_from: tosca.datatypes.Root
+ description: >
+ The ECOMP root Data Type all other Data Types derive from
+ properties:
+ supplemental_data:
+ type: map
+ entry_schema:
+ description: >
+ A placeholder for missing properties that would be included in future ecomp model versions.
+ fromat <key>:<value>
+ type: string
+
+org.openecomp.datatypes.AssignmentRequirements:
+ derived_from: org.openecomp.datatypes.Root
+ properties:
+ is_required:
+ description: |
+ "true" indicates that assignment is required
+ type: boolean
+ default: false
+ required: true
+ count:
+ description: number of assignments required
+ type: integer
+ required: false
+
+org.openecomp.datatypes.network.SubnetAssignments:
+ derived_from: org.openecomp.datatypes.Root
+ properties:
+ ip_network_address_plan:
+ type: string
+ required: false
+ description: Reference to EIPAM, VLAN or other address plan ID used to assign subnets to this network
+ dhcp_enabled:
+ type: boolean
+ required: false
+ description: \"true\" indicates the network has 1 or more policies
+ ip_version:
+ type: integer
+ constraints:
+ - valid_values: [4,6]
+ required: true
+ description: The IP version of the subnet
+ cidr_mask:
+ type: integer
+ required: true
+ description: The default subnet CIDR mask
+ min_subnets_count:
+ type: integer
+ default: 1
+ required: true
+ description: Quantity of subnets that must be initially assigned
+
+org.openecomp.datatypes.network.IPv4SubnetAssignments:
+ derived_from: org.openecomp.datatypes.network.SubnetAssignments
+ properties:
+ use_ipv4:
+ type: boolean
+ required: true
+ description: Indicates IPv4 subnet assignments
+
+org.openecomp.datatypes.network.IPv6SubnetAssignments:
+ derived_from: org.openecomp.datatypes.network.SubnetAssignments
+ properties:
+ use_ipv6:
+ type: boolean
+ required: true
+ description: Indicates IPv6 subnet assignments
+
+org.openecomp.datatypes.network.NetworkAssignments:
+ derived_from: org.openecomp.datatypes.Root
+ properties:
+ ecomp_generated_network_assignment:
+ type: boolean
+ required: true
+ default: false
+ description: >
+ \"true\" indicates that the network assignments will be auto-generated by ECOMP
+ \"false\" indicates operator-supplied Network assignments file upload is required (e.g. VID will present prompt to operator to upload operator-supplied Network assignments file).
+ is_shared_network:
+ type: boolean
+ required: true
+ description: \"true\" means this network is shared by multiple Openstack tenants
+ is_external_network:
+ type: boolean
+ required: true
+ default: false
+ description: >
+ \"true\" means this Contrail external network
+ ipv4_subnet_default_assignment:
+ type: org.openecomp.datatypes.network.IPv4SubnetAssignments
+ required: true
+ description: IPv4 defualt subnet assignments
+ ipv6_subnet_default_assignment:
+ type: org.openecomp.datatypes.network.IPv6SubnetAssignments
+ required: true
+ description: IPv6 defualt subnet assignments
+
+org.openecomp.datatypes.network.ProviderNetwork:
+ derived_from: org.openecomp.datatypes.Root
+ properties:
+ is_provider_network:
+ type: boolean
+ required: true
+ description: \"true\" indicates that this a Neutron provider type of network
+ physical_network_name:
+ type: string
+ required: false
+ constraints:
+ - valid_values: ["Physnet41", "Physnet42", "Physnet43", "Physnet44", "Physnet21", "Physnet22"]
+ description: >
+ Identifies the NUMA processor cluster to which this physical network interface belongs.
+ NUMA instance correlates to the first digit of the Physical Network Name suffix (e.g. \"01\" = NUMA 0, \"11\" = NUMA 1)
+ numa:
+ type: string
+ required: false
+ constraints:
+ - valid_values: ["NUMA 0", "NUMA 1"]
+ description: >
+ PNIC instance within the NUMA processor cluster
+ PNIC Instance correlates to the second digit of the Physical Network Name suffix (e.g. "01" = PNIC 1, "02" = "PNIC 2)
+ pnic_instance:
+ type: integer
+ required: false
+ description: PNIC instance within the NUMA processor cluster
+
+org.openecomp.datatypes.network.NetworkFlows:
+ derived_from: org.openecomp.datatypes.Root
+ properties:
+ is_network_policy:
+ type: boolean
+ required: false
+ default: false
+ description: \"true\" indicates the network has 1 or more policies
+ network_policy:
+ type: string
+ required: false
+ description: "Identifies the specific Cloud network policy that must be applied to this network (source: from Policy Manager)."
+ is_bound_to_vpn:
+ type: boolean
+ required: false
+ default: false
+ description: \"true\" indicates the network has 1 or more vpn bindings
+ vpn_binding:
+ type: string
+ required: false
+ description: "Identifies the specific VPN Binding entry in A&AI that must be applied when creating this network (source: A&AI)"
+
+org.openecomp.datatypes.network.VlanRequirements:
+ derived_from: org.openecomp.datatypes.Root
+ properties:
+ vlan_range_plan:
+ type: string
+ required: true
+ description: reference to a vlan range plan
+ vlan_type:
+ type: string
+ required: true
+ constraints:
+ - valid_values: ["c-tag", "s-tag"]
+ description: identifies the vlan type (e.g., c-tag)
+ vlan_count:
+ type: integer
+ required: true
+ description: identifies the number of vlan tags to assign to the CP from the plan
+
+org.openecomp.datatypes.network.IpRequirements:
+ derived_from: org.openecomp.datatypes.Root
+ properties:
+ ip_version:
+ type: integer
+ required: true
+ constraints:
+ - valid_values:
+ - 4
+ - 6
+ ip_count:
+ description: identifies the number of ip address to assign to the CP from the plan
+ type: integer
+ required: false
+ floating_ip_count:
+ type: integer
+ required: false
+ subnet_role:
+ type: string
+ required: false
+ assingment_method:
+ type: string
+ required: true
+ constraints:
+ - valid_values:
+ - fixed
+ - dhcp
+ dhcp_enabled:
+ type: boolean
+ required: false
+ ip_count_required:
+ description: identifies the number of ip address to assign to the CP from the plan
+ type: org.openecomp.datatypes.AssignmentRequirements
+ required: false
+ floating_ip_count_required:
+ type: org.openecomp.datatypes.AssignmentRequirements
+ required: false
+
+org.openecomp.datatypes.network.MacAssignments:
+ derived_from: org.openecomp.datatypes.Root
+ properties:
+ mac_range_plan:
+ type: string
+ required: true
+ description: reference to a MAC address range plan
+ mac_count:
+ type: integer
+ required: true
+ description: identifies the number of MAC addresses to assign to the CP from the plan
+
+org.openecomp.datatypes.EcompHoming:
+ derived_from: org.openecomp.datatypes.Root
+ properties:
+ ecomp_selected_instance_node_target:
+ type: boolean
+ required: true
+ default: false
+ description: >
+ \"true\" indicates that the target deployment node for this instance will be auto-selected by ECOMP
+ \"false\" indicates operator-supplied instance target deployment node required (e.g. VID will present a prompt to operator and collect the
+ operator-selected target node for the deployment of this Network instance).
+ homing_policy:
+ type: string
+ required: false
+ description: Referenc to a service level homing policy that ECOMP will use for instance deployment target node
+ instance_node_target:
+ type: string
+ required: false
+ description: Instance target deployment node
+
+org.openecomp.datatypes.EcompNaming:
+ derived_from: org.openecomp.datatypes.Root
+ properties:
+ ecomp_generated_naming:
+ type: boolean
+ required: true
+ default: true
+ description: >
+ \"true\" indicates that the name for the instance will be auto-generated by ECOMP.
+ \"false\" indicates operator-supplied name required (e.g. VID will present prompt to operator and collect the operator-supplied instance name).
+ naming_policy:
+ type: string
+ required: false
+ description: Referenc to naming policy that ECOMP will use when the name is auto-generated
+
+org.openecomp.datatypes.network.MacRequirements:
+ derived_from: org.openecomp.datatypes.Root
+ properties:
+ mac_range_plan:
+ description: reference to a MAC address range plan
+ type: string
+ required: false
+ mac_count:
+ description: identifies the number of MAC addresses to assign to the CP from the plan
+ type: integer
+ required: false
+ mac_count_required:
+ description: identifies the number of MAC addresses to assign to the CP from the plan
+ type: org.openecomp.datatypes.AssignmentRequirements
+
+org.openecomp.datatypes.heat.contrailV2.virtual.machine.subInterface.AddressPairIp:
+ derived_from: tosca.datatypes.Root
+ description: Virtual Machine Sub Interface Address Pair IP.
+ properties:
+ ip_prefix:
+ type: string
+ description: IP Prefix.
+ required: false
+ status: SUPPORTED
+ ip_prefix_len:
+ type: integer
+ description: IP Prefix Len.
+ required: false
+ status: SUPPORTED
+
+org.openecomp.datatypes.heat.contrailV2.virtual.machine.subInterface.MacAddress:
+ derived_from: tosca.datatypes.Root
+ description: Virtual Machine Sub Interface Mac Address.
+ properties:
+ mac_address:
+ type: list
+ description: Mac Addresses List.
+ required: false
+ status: SUPPORTED
+ entry_schema:
+ type: string
+
+org.openecomp.datatypes.heat.contrailV2.virtual.machine.subInterface.Properties:
+ derived_from: tosca.datatypes.Root
+ description: Virtual Machine Sub Interface VLAN Properties.
+ properties:
+ sub_interface_vlan_tag:
+ type: string
+ description: Sub Interface VLAN Tag.
+ required: false
+ status: SUPPORTED
+
+org.openecomp.datatypes.heat.contrailV2.virtual.machine.subInterface.AddressPair:
+ derived_from: tosca.datatypes.Root
+ description: Virtual Machine Sub Interface Address Pair.
+ properties:
+ address_mode:
+ type: string
+ description: Address Mode.
+ required: false
+ status: SUPPORTED
+ ip:
+ type: org.openecomp.datatypes.heat.contrailV2.virtual.machine.subInterface.AddressPairIp
+ description: IP.
+ required: false
+ status: SUPPORTED
+ mac:
+ type: string
+ description: Mac.
+ required: false
+ status: SUPPORTED
+
+org.openecomp.datatypes.heat.contrailV2.virtual.machine.subInterface.AddressPairs:
+ derived_from: tosca.datatypes.Root
+ description: Virtual Machine Sub Interface Address Pairs.
+ properties:
+ allowed_address_pair:
+ type: list
+ description: Addresses pair List.
+ required: false
+ status: SUPPORTED
+ entry_schema:
+ type: org.openecomp.datatypes.heat.contrailV2.virtual.machine.subInterface.AddressPair
+
+org.openecomp.datatypes.Naming:
+ derived_from: org.openecomp.datatypes.Root
+ properties:
+ ecomp_generated_naming:
+ description: |
+ "true" indicates that the name for the instance will be auto-generated by ECOMP. "false" indicates operator-supplied name required (e.g. VID will present prompt to operator and collect the operator-supplied instance name).
+ type: boolean
+ default: true
+ required: true
+ naming_policy:
+ description: Reference to naming policy that ECOMP will use when the name is auto-generated
+ type: string
+ required: false
+ instance_name:
+ description: indicates operator-supplied name required (e.g. VID will present prompt to operator and collect the operator-supplied instance name).
+ type: string
+ required: false
+
+
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 2249a8bd5c..4f3e269c69 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 1df2cbdd04..ce457e4add 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
@@ -22,6 +22,61 @@ org.openecomp.groups.VfModule:
required: true
default: false
status: SUPPORTED
+ vf_module_label:
+ type: string
+ required: true
+ description: >
+ Alternate textual key used to reference this VF-Module model.
+ Must be unique within the VNF model
+ vf_module_description:
+ type: string
+ required: true
+ description: >
+ Description of the VF-modules contents and purpose
+ (e.g. "Front-End" or "Database Cluster")
+ min_vf_module_instances:
+ type: integer
+ required: true
+ description: The minimum instances of this VF-Module
+ max_vf_module_instances:
+ type: integer
+ required: false
+ description: The maximum instances of this VF-Module
+ initial_count:
+ type: integer
+ required: false
+ description: >
+ The initial count of instances of the VF-Module. The value must be in the
+ range between min_vfmodule_instances and max_vfmodule_instances.
+ If no value provided the initial count is the min_vfmodule_instances.
+ vf_module_type:
+ type: string
+ required: true
+ constraint:
+ - valid_values: ["Base", "Expansion"]
+ volume_group:
+ type: boolean
+ required: true
+ default: false
+ description: >
+ "true" indicates that this VF Module model requires attachment to a Volume
+ Group.
+ VID operator must select the Volume Group instance to attach to a VF-Module
+ at deployment time.
+ availability_zone_count:
+ type: integer
+ required: false
+ description: >
+ Quantity of Availability Zones needed for this VF-Module
+ (source: Extracted from VF-Module HEAT template)
+ vfc_list:
+ type: map
+ entry_schema:
+ description: <vfc_id>:<count>
+ type: string
+ required: false
+ description: >
+ Identifies the set of VM types and their count included in the VF-Module
tosca.groups.Root:
description: The TOSCA Group Type all other TOSCA Group Types derive from
interfaces:
diff --git a/catalog-be/src/main/resources/import/tosca/group-types/groupTypes.zip b/catalog-be/src/main/resources/import/tosca/group-types/groupTypes.zip
index e386507c92..7acd7a6b45 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/catalog-be/src/main/resources/import/tosca/heat-types.zip b/catalog-be/src/main/resources/import/tosca/heat-types.zip
new file mode 100644
index 0000000000..ebb5afd09d
--- /dev/null
+++ b/catalog-be/src/main/resources/import/tosca/heat-types.zip
Binary files differ
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/Generic_Service/Generic_Service.json b/catalog-be/src/main/resources/import/tosca/heat-types/Generic_Service/Generic_Service.json
new file mode 100644
index 0000000000..b9423bc148
--- /dev/null
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/Generic_Service/Generic_Service.json
@@ -0,0 +1,21 @@
+{
+ "payloadName": "Generic_Service.yml",
+ "contactId": "jh0003",
+ "name": "Generic_Service",
+ "description": "Represents a generic Service.",
+ "resourceIconPath": "defaulticon",
+ "resourceType": "ABSTRACT",
+ "categories": [
+ {
+ "name": "Generic",
+ "subcategories": [
+ {
+ "name": "Abstract"
+ }
+ ]
+ }
+],
+ "tags": [
+ "Generic_Service"
+ ]
+} \ No newline at end of file
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/Generic_Service/Generic_Service.yml b/catalog-be/src/main/resources/import/tosca/heat-types/Generic_Service/Generic_Service.yml
new file mode 100644
index 0000000000..902cf0c0c8
--- /dev/null
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/Generic_Service/Generic_Service.yml
@@ -0,0 +1,5 @@
+tosca_definitions_version: tosca_simple_yaml_1_0_0
+node_types:
+ org.openecomp.resource.abstract.nodes.service:
+ derived_from: tosca.nodes.Root
+ \ No newline at end of file
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/Generic_Service/Generic_Service.zip b/catalog-be/src/main/resources/import/tosca/heat-types/Generic_Service/Generic_Service.zip
new file mode 100644
index 0000000000..060dec1aa1
--- /dev/null
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/Generic_Service/Generic_Service.zip
Binary files differ
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/Generic_VF/Generic_VF.json b/catalog-be/src/main/resources/import/tosca/heat-types/Generic_VF/Generic_VF.json
new file mode 100644
index 0000000000..87c22f5f9d
--- /dev/null
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/Generic_VF/Generic_VF.json
@@ -0,0 +1,21 @@
+{
+ "payloadName": "Generic_VF.yml",
+ "contactId": "jh0003",
+ "name": "Generic_VF",
+ "description": "Represents a generic VF.",
+ "resourceIconPath": "defaulticon",
+ "resourceType": "ABSTRACT",
+ "categories": [
+ {
+ "name": "Generic",
+ "subcategories": [
+ {
+ "name": "Abstract"
+ }
+ ]
+ }
+],
+ "tags": [
+ "Generic_VF"
+ ]
+} \ No newline at end of file
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/Generic_VF/Generic_VF.yml b/catalog-be/src/main/resources/import/tosca/heat-types/Generic_VF/Generic_VF.yml
new file mode 100644
index 0000000000..6618650ef3
--- /dev/null
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/Generic_VF/Generic_VF.yml
@@ -0,0 +1,27 @@
+tosca_definitions_version: tosca_simple_yaml_1_0_0
+node_types:
+ org.openecomp.resource.abstract.nodes.VF:
+ 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
+ Default: true
+ availability_zone_max_count:
+ type: integer
+ default: 1
+ constraints:
+ - valid_values: [0,1,2]
+ min_instances:
+ type: integer
+ max_instances:
+ type: integer
+
+ \ No newline at end of file
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
new file mode 100644
index 0000000000..d564813e2f
--- /dev/null
+++ 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/Generic_VFC/Generic_VFC.json b/catalog-be/src/main/resources/import/tosca/heat-types/Generic_VFC/Generic_VFC.json
new file mode 100644
index 0000000000..0145fbc14c
--- /dev/null
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/Generic_VFC/Generic_VFC.json
@@ -0,0 +1,21 @@
+{
+ "payloadName": "Generic_VFC.yml",
+ "contactId": "jh0003",
+ "name": "Generic_VFC",
+ "description": "Represents a generic VFC.",
+ "resourceIconPath": "defaulticon",
+ "resourceType": "ABSTRACT",
+ "categories": [
+ {
+ "name": "Generic",
+ "subcategories": [
+ {
+ "name": "Abstract"
+ }
+ ]
+ }
+],
+ "tags": [
+ "Generic_VFC"
+ ]
+} \ No newline at end of file
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/Generic_VFC/Generic_VFC.yml b/catalog-be/src/main/resources/import/tosca/heat-types/Generic_VFC/Generic_VFC.yml
new file mode 100644
index 0000000000..276ee03e63
--- /dev/null
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/Generic_VFC/Generic_VFC.yml
@@ -0,0 +1,50 @@
+tosca_definitions_version: tosca_simple_yaml_1_0_0
+node_types:
+ org.openecomp.resource.abstract.nodes.VFC:
+ derived_from: org.openecomp.resource.abstract.nodes.AbstractSubstitute
+ properties:
+ nfc_function:
+ type: string
+ high_availablity:
+ type: string
+ description: high_availablity
+ required: false
+ status: SUPPORTED
+ vm_image_name:
+ type: string
+ description: Master image_name volume id
+ required: true
+ status: SUPPORTED
+ vm_flavor_name:
+ type: string
+ description: Master image_name volume id
+ required: true
+ status: SUPPORTED
+ nfc_naming_code:
+ type: string
+ description: nfc code for instance naming
+ required: false
+ status: SUPPORTED
+ vm_type_tag:
+ type: string
+ description: vm type based on naming Convention
+ required: false
+ status: SUPPORTED
+ nfc_naming:
+ type: org.openecomp.datatypes.Naming
+ description: vfc naming
+ min_instances:
+ type: integer
+ description: Minimum number of VFC Instances
+ required: false
+ default: 0
+ status: SUPPORTED
+ constraints:
+ - greater_or_equal: 0
+ max_instances:
+ type: integer
+ description: Maximum number of VFC Instances
+ required: false
+ status: SUPPORTED
+ constraints:
+ - greater_or_equal: 1 \ No newline at end of file
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/Generic_VFC/Generic_VFC.zip b/catalog-be/src/main/resources/import/tosca/heat-types/Generic_VFC/Generic_VFC.zip
new file mode 100644
index 0000000000..f98f53333a
--- /dev/null
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/Generic_VFC/Generic_VFC.zip
Binary files differ
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/abstractSubstitute/abstractSubstitute.yml b/catalog-be/src/main/resources/import/tosca/heat-types/abstractSubstitute/abstractSubstitute.yml
index 48db2b609a..7aa7edfe70 100644
--- a/catalog-be/src/main/resources/import/tosca/heat-types/abstractSubstitute/abstractSubstitute.yml
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/abstractSubstitute/abstractSubstitute.yml
@@ -1,11 +1,4 @@
tosca_definitions_version: tosca_simple_yaml_1_0_0
-metadata:
- template_name: AbstractSubstituteGlobalTypes
- template_version: 1.0.0
-description: Abstract Substitute Global Types
-imports:
- common_definitions:
- file: CommonGlobalTypesServiceTemplate.yaml
node_types:
org.openecomp.resource.abstract.nodes.AbstractSubstitute:
derived_from: tosca.nodes.Root
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/abstractSubstitute/abstractSubstitute.zip b/catalog-be/src/main/resources/import/tosca/heat-types/abstractSubstitute/abstractSubstitute.zip
index 07e4941e6b..2c38ab43a1 100644
--- a/catalog-be/src/main/resources/import/tosca/heat-types/abstractSubstitute/abstractSubstitute.zip
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/abstractSubstitute/abstractSubstitute.zip
Binary files differ
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/cinderVolume/cinderVolume.yml b/catalog-be/src/main/resources/import/tosca/heat-types/cinderVolume/cinderVolume.yml
index 3bb227d1ec..87dfc313ae 100644
--- a/catalog-be/src/main/resources/import/tosca/heat-types/cinderVolume/cinderVolume.yml
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/cinderVolume/cinderVolume.yml
@@ -1,78 +1,50 @@
tosca_definitions_version: tosca_simple_yaml_1_0_0
-metadata:
- template_name: CinderVolumeGlobalTypes
- template_version: 1.0.0
-description: Cinder Volume TOSCA Global Types
-relationship_types:
- org.openecomp.relationships.cinder.VolumeAttachesTo:
- derived_from: tosca.relationships.AttachesTo
- description: This type represents an attachment relationship for associating volume
- properties:
- volume_id:
- type: string
- description: The ID of the volume to be attached
- required: true
- status: SUPPORTED
- location:
- type: string
- description: The location where the volume is exposed on the instance, mountpoint
- required: false
- status: SUPPORTED
- instance_uuid:
- type: string
- description: The ID of the server to which the volume attaches
- required: true
- status: SUPPORTED
- attributes:
- show:
- type: string
- description: Detailed information about resource
- status: SUPPORTED
node_types:
org.openecomp.resource.vfc.nodes.heat.cinder.Volume:
- derived_from: tosca.nodes.BlockStorage
+ derived_from: org.openecomp.resource.vfc.nodes.volume
properties:
availability_zone:
- type: string
description: The availability zone in which the volume will be created
- required: false
+ type: string
status: SUPPORTED
+ required: false
image:
- type: string
description: If specified, the name or ID of the image to create the volume from
- required: false
+ type: string
status: SUPPORTED
+ required: false
metadata:
- type: map
description: Key/value pairs to associate with the volume
- required: false
+ type: map
status: SUPPORTED
entry_schema:
type: string
+ required: false
volume_type:
- type: string
description: If specified, the type of volume to use, mapping to a specific backend
- required: false
+ type: string
status: SUPPORTED
+ required: false
description:
- type: string
description: A description of the volume
- required: false
+ type: string
status: SUPPORTED
+ required: false
device_type:
- type: string
description: Device type
- required: false
+ type: string
status: SUPPORTED
+ required: false
constraints:
- valid_values:
- cdrom
- disk
disk_bus:
+ description: 'Bus of the device: hypervisor driver chooses a suitable default
+ if omitted'
type: string
- description: 'Bus of the device: hypervisor driver chooses a suitable default if omitted'
- required: false
status: SUPPORTED
+ required: false
constraints:
- valid_values:
- ide
@@ -81,97 +53,97 @@ node_types:
- usb
- virtio
backup_id:
- type: string
description: If specified, the backup to create the volume from
- required: false
+ type: string
status: SUPPORTED
+ required: false
source_volid:
- type: string
description: If specified, the volume to use as source
- required: false
+ type: string
status: SUPPORTED
+ required: false
boot_index:
- type: integer
description: Integer used for ordering the boot disks
- required: false
+ type: integer
status: SUPPORTED
+ required: false
size:
- type: scalar-unit.size
description: The requested storage size (default unit is MB)
- required: false
+ type: scalar-unit.size
status: SUPPORTED
+ required: false
constraints:
- greater_or_equal: 1 GB
read_only:
- type: boolean
description: Enables or disables read-only access mode of volume
- required: false
+ type: boolean
status: SUPPORTED
+ required: false
name:
- type: string
description: A name used to distinguish the volume
- required: false
+ type: string
status: SUPPORTED
+ required: false
scheduler_hints:
- type: map
description: Arbitrary key-value pairs specified by the client to help the Cinder scheduler creating a volume
- required: false
+ type: map
status: SUPPORTED
entry_schema:
type: string
+ required: false
swap_size:
- type: scalar-unit.size
description: The size of the swap, in MB
- required: false
+ type: scalar-unit.size
status: SUPPORTED
+ required: false
delete_on_termination:
- type: boolean
description: Indicate whether the volume should be deleted when the server is terminated
- required: false
+ type: boolean
status: SUPPORTED
+ required: false
multiattach:
- type: boolean
description: Whether allow the volume to be attached more than once
- required: false
+ type: boolean
status: SUPPORTED
+ required: false
attributes:
display_description:
- type: string
description: Description of the volume
+ type: string
status: SUPPORTED
attachments:
- type: string
description: The list of attachments of the volume
+ type: string
status: SUPPORTED
entry_schema:
type: string
encrypted:
- type: boolean
description: Boolean indicating if the volume is encrypted or not
+ type: boolean
status: SUPPORTED
show:
- type: string
description: Detailed information about resource
+ type: string
status: SUPPORTED
created_at:
- type: timestamp
description: The timestamp indicating volume creation
+ type: timestamp
status: SUPPORTED
display_name:
- type: string
description: Name of the volume
+ type: string
status: SUPPORTED
metadata_values:
- type: map
description: Key/value pairs associated with the volume in raw dict form
+ type: map
status: SUPPORTED
entry_schema:
type: string
bootable:
- type: boolean
description: Boolean indicating if the volume can be booted or not
+ type: boolean
status: SUPPORTED
status:
- type: string
description: The current status of the volume
+ type: string
status: SUPPORTED
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/cinderVolume/cinderVolume.zip b/catalog-be/src/main/resources/import/tosca/heat-types/cinderVolume/cinderVolume.zip
index 88506743ac..8b9a455c54 100644
--- a/catalog-be/src/main/resources/import/tosca/heat-types/cinderVolume/cinderVolume.zip
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/cinderVolume/cinderVolume.zip
Binary files differ
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/contrailAbstractSubstitute/contrailAbstractSubstitute.yml b/catalog-be/src/main/resources/import/tosca/heat-types/contrailAbstractSubstitute/contrailAbstractSubstitute.yml
index 5bdee932a3..a1f40c5529 100644
--- a/catalog-be/src/main/resources/import/tosca/heat-types/contrailAbstractSubstitute/contrailAbstractSubstitute.yml
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/contrailAbstractSubstitute/contrailAbstractSubstitute.yml
@@ -1,11 +1,4 @@
tosca_definitions_version: tosca_simple_yaml_1_0_0
-metadata:
- template_name: ContrailAbstractSubstituteGlobalTypes
- template_version: 1.0.0
-description: Contrail Abstract Substitute Global Types
-imports:
- common_definitions:
- file: CommonGlobalTypesServiceTemplate.yaml
node_types:
org.openecomp.resource.abstract.nodes.contrail.AbstractSubstitute:
derived_from: org.openecomp.resource.abstract.nodes.AbstractSubstitute
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/contrailAbstractSubstitute/contrailAbstractSubstitute.zip b/catalog-be/src/main/resources/import/tosca/heat-types/contrailAbstractSubstitute/contrailAbstractSubstitute.zip
index 6a2094bb9a..11d99be2e3 100644
--- a/catalog-be/src/main/resources/import/tosca/heat-types/contrailAbstractSubstitute/contrailAbstractSubstitute.zip
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/contrailAbstractSubstitute/contrailAbstractSubstitute.zip
Binary files differ
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/contrailCompute/contrailCompute.yml b/catalog-be/src/main/resources/import/tosca/heat-types/contrailCompute/contrailCompute.yml
index d6ad4f953c..c2ba70e2d1 100644
--- a/catalog-be/src/main/resources/import/tosca/heat-types/contrailCompute/contrailCompute.yml
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/contrailCompute/contrailCompute.yml
@@ -1,14 +1,7 @@
tosca_definitions_version: tosca_simple_yaml_1_0_0
-metadata:
- template_name: ContrailComputeGlobalTypes
- template_version: 1.0.0
-description: Contrail Compute TOSCA Global Types
-imports:
- common_definitions:
- file: CommonGlobalTypesServiceTemplate.yaml
node_types:
org.openecomp.resource.vfc.nodes.heat.contrail.Compute:
- derived_from: tosca.nodes.Compute
+ derived_from: org.openecomp.resource.vfc.nodes.Compute
properties:
flavor:
type: string
@@ -86,4 +79,4 @@ node_types:
status:
type: string
description: status of the compute
- status: SUPPORTED \ No newline at end of file
+ status: SUPPORTED
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/contrailCompute/contrailCompute.zip b/catalog-be/src/main/resources/import/tosca/heat-types/contrailCompute/contrailCompute.zip
index c9e3c8a062..c0cc411e5d 100644
--- a/catalog-be/src/main/resources/import/tosca/heat-types/contrailCompute/contrailCompute.zip
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/contrailCompute/contrailCompute.zip
Binary files differ
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/contrailNetworkRules/contrailNetworkRules.yml b/catalog-be/src/main/resources/import/tosca/heat-types/contrailNetworkRules/contrailNetworkRules.yml
index b9d61e7769..2f8228ac85 100644
--- a/catalog-be/src/main/resources/import/tosca/heat-types/contrailNetworkRules/contrailNetworkRules.yml
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/contrailNetworkRules/contrailNetworkRules.yml
@@ -1,11 +1,4 @@
tosca_definitions_version: tosca_simple_yaml_1_0_0
-metadata:
- template_name: ContrailNetworkRuleGlobalType
- template_version: 1.0.0
-description: Contrail Network Rule Global Types
-imports:
- common_definitions:
- file: CommonGlobalTypesServiceTemplate.yaml
node_types:
org.openecomp.resource.vfc.rules.nodes.heat.network.contrail.NetworkRules:
derived_from: tosca.nodes.Root
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/contrailNetworkRules/contrailNetworkRules.zip b/catalog-be/src/main/resources/import/tosca/heat-types/contrailNetworkRules/contrailNetworkRules.zip
index b687616cd8..639164711f 100644
--- a/catalog-be/src/main/resources/import/tosca/heat-types/contrailNetworkRules/contrailNetworkRules.zip
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/contrailNetworkRules/contrailNetworkRules.zip
Binary files differ
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/contrailPort/contrailPort.yml b/catalog-be/src/main/resources/import/tosca/heat-types/contrailPort/contrailPort.yml
index a3e43a2fd1..ce99511bbe 100644
--- a/catalog-be/src/main/resources/import/tosca/heat-types/contrailPort/contrailPort.yml
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/contrailPort/contrailPort.yml
@@ -1,14 +1,7 @@
tosca_definitions_version: tosca_simple_yaml_1_0_0
-metadata:
- template_name: ContrailPortGlobalTypes
- template_version: 1.0.0
-description: Contrail Port TOSCA Global Types
-imports:
- common_definitions:
- file: CommonGlobalTypesServiceTemplate.yaml
node_types:
org.openecomp.resource.cp.nodes.heat.network.contrail.Port:
- derived_from: tosca.nodes.network.Port
+ derived_from: org.openecomp.resource.cp.nodes.network.Port
properties:
static_routes:
type: list
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/contrailPort/contrailPort.zip b/catalog-be/src/main/resources/import/tosca/heat-types/contrailPort/contrailPort.zip
index f9e5c415ae..6040f3cb17 100644
--- a/catalog-be/src/main/resources/import/tosca/heat-types/contrailPort/contrailPort.zip
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/contrailPort/contrailPort.zip
Binary files differ
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2NetworkRules/contrailV2NetworkRules.yml b/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2NetworkRules/contrailV2NetworkRules.yml
index ccc6d3a2ab..ad4369ce40 100644
--- a/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2NetworkRules/contrailV2NetworkRules.yml
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2NetworkRules/contrailV2NetworkRules.yml
@@ -1,11 +1,4 @@
tosca_definitions_version: tosca_simple_yaml_1_0_0
-metadata:
- template_name: ContrailV2NetworkRuleGlobalType
- template_version: 1.0.0
-description: Contrail V2 Network Rule Global Types
-imports:
- common_definitions:
- file: CommonGlobalTypesServiceTemplate.yaml
node_types:
org.openecomp.resource.vfc.rules.nodes.heat.network.contrailV2.NetworkRules:
derived_from: tosca.nodes.Root
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2NetworkRules/contrailV2NetworkRules.zip b/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2NetworkRules/contrailV2NetworkRules.zip
index eac99b3b90..a8a84e7eff 100644
--- a/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2NetworkRules/contrailV2NetworkRules.zip
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2NetworkRules/contrailV2NetworkRules.zip
Binary files differ
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2VLANSubInterface/contrailV2VLANSubInterface.json b/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2VLANSubInterface/contrailV2VLANSubInterface.json
new file mode 100644
index 0000000000..216c85cb68
--- /dev/null
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2VLANSubInterface/contrailV2VLANSubInterface.json
@@ -0,0 +1,15 @@
+{
+ "payloadName": "contrailV2VLANSubInterface.yml",
+ "contactId": "jh0003",
+ "name": "contrailV2VLANSubInterface",
+ "description": "VLAN sub-Interface is a logical port which must be binded to a port. Regular port may have 1…N VLAN Interfaces.It can connect to its own network (regardless of the network the parent port can connect)",
+ "resourceIconPath": "network",
+ "resourceType": "CP",
+ "categories": [{
+ "name": "Generic",
+ "subcategories": [{
+ "name": "Network Elements"
+ }]
+ }],
+ "tags": ["contrailV2VLANSubInterface"]
+} \ No newline at end of file
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2VLANSubInterface/contrailV2VLANSubInterface.yml b/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2VLANSubInterface/contrailV2VLANSubInterface.yml
new file mode 100644
index 0000000000..20f7372274
--- /dev/null
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2VLANSubInterface/contrailV2VLANSubInterface.yml
@@ -0,0 +1,70 @@
+tosca_definitions_version: tosca_simple_yaml_1_0_0
+node_types:
+ org.openecomp.resource.cp.nodes.heat.network.contrailV2.VLANSubInterface:
+ derived_from: org.openecomp.resource.cp.nodes.network.SubInterface
+ properties:
+ virtual_machine_interface_refs:
+ description: List of virtual machine interface.
+ type: list
+ status: SUPPORTED
+ entry_schema:
+ type: string
+ required: false
+ name:
+ description: Virtual Machine Sub Interface VLAN name
+ type: string
+ status: SUPPORTED
+ required: false
+ virtual_network_refs:
+ description: List of virtual networks.
+ type: list
+ status: SUPPORTED
+ entry_schema:
+ type: string
+ required: false
+ virtual_machine_interface_properties:
+ description: virtual machine interface properties.
+ type: org.openecomp.datatypes.heat.contrailV2.virtual.machine.subInterface.Properties
+ status: SUPPORTED
+ required: false
+ virtual_machine_interface_allowed_address_pairs:
+ description: Virtual Machine Sub Interface allowed address pairs.
+ type: org.openecomp.datatypes.heat.contrailV2.virtual.machine.subInterface.AddressPairs
+ status: SUPPORTED
+ required: false
+ virtual_machine_interface_mac_addresses:
+ description: List of mac addresses.
+ type: org.openecomp.datatypes.heat.contrailV2.virtual.machine.subInterface.MacAddress
+ status: SUPPORTED
+ required: false
+ security_group_refs:
+ description: List of security groups.
+ type: list
+ status: SUPPORTED
+ entry_schema:
+ type: string
+ required: false
+ port_tuple_refs:
+ description: List of port tuples.
+ type: list
+ status: SUPPORTED
+ entry_schema:
+ type: string
+ required: false
+ attributes:
+ fq_name:
+ description: The FQ name of the Virtual Network.
+ type: string
+ status: SUPPORTED
+ show:
+ description: All attributes.
+ type: string
+ status: SUPPORTED
+ requirements:
+ - binding:
+ capability: tosca.capabilities.network.Bindable
+ node: org.openecomp.resource.cp.nodes.network.Port
+ relationship: tosca.relationships.network.BindsTo
+ occurrences:
+ - 1
+ - 1 \ No newline at end of file
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2VLANSubInterface/contrailV2VLANSubInterface.zip b/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2VLANSubInterface/contrailV2VLANSubInterface.zip
new file mode 100644
index 0000000000..eadba5ef28
--- /dev/null
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2VLANSubInterface/contrailV2VLANSubInterface.zip
Binary files differ
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2VirtualMachineInterface/contrailV2VirtualMachineInterface.yml b/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2VirtualMachineInterface/contrailV2VirtualMachineInterface.yml
index ba324cf51a..a2179079b1 100644
--- a/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2VirtualMachineInterface/contrailV2VirtualMachineInterface.yml
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2VirtualMachineInterface/contrailV2VirtualMachineInterface.yml
@@ -1,59 +1,65 @@
tosca_definitions_version: tosca_simple_yaml_1_0_0
-metadata:
- template_name: ContrailV2VirtualMachineInterfaceGlobalType
- template_version: 1.0.0
-description: Contrail Virtual Machine Interface TOSCA Global Types
-imports:
- common_definitions:
- file: CommonGlobalTypesServiceTemplate.yaml
node_types:
org.openecomp.resource.cp.nodes.heat.contrailV2.VirtualMachineInterface:
- derived_from: tosca.nodes.network.Port
+ derived_from: org.openecomp.resource.cp.nodes.network.Port
properties:
- virtual_machine_intefrace_mac_addresses:
- type: list
- description: List of mac addresses.
- required: false
- status: SUPPORTED
- entry_schema:
- type: string
name:
- type: string
description: Virtual Machine Interface name
- required: false
+ type: string
status: SUPPORTED
+ required: false
security_group_refs:
- type: list
description: List of security groups.
- required: false
+ type: list
status: SUPPORTED
entry_schema:
type: string
+ required: false
virtual_network_refs:
- type: list
description: List of virtual networks.
- required: false
+ type: list
status: SUPPORTED
entry_schema:
type: string
+ required: false
virtual_machine_interface_properties:
- type: org.openecomp.datatypes.heat.contrailV2.virtual.machine.interface.Properties
description: virtual machine interface properties.
- required: false
+ type: org.openecomp.datatypes.heat.contrailV2.virtual.machine.interface.Properties
status: SUPPORTED
+ required: false
port_tuple_refs:
- type: list
description: List of port tuples.
+ type: list
+ status: SUPPORTED
+ entry_schema:
+ type: string
required: false
+ virtual_machine_interface_mac_addresses:
+ description: List of mac addresses.
+ type: list
status: SUPPORTED
entry_schema:
type: string
+ required: false
+ virtual_machine_interface_allowed_address_pairs:
+ description: Virtual Machine Interface allowed address pairs.
+ type: org.openecomp.datatypes.heat.contrailV2.virtual.machine.subInterface.AddressPairs
+ status: SUPPORTED
+ required: false
attributes:
fq_name:
- type: string
description: The FQ name of the Virtual Network.
+ type: string
status: SUPPORTED
show:
- type: string
description: All attributes.
+ type: string
status: SUPPORTED
+ capabilities:
+ binding:
+ type: tosca.capabilities.network.Bindable
+ occurrences:
+ - 0
+ - UNBOUNDED
+ valid_source_types:
+ - org.openecomp.resources.cp.nodes.heat.network.contrailV2.VLANSubInterface \ No newline at end of file
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2VirtualMachineInterface/contrailV2VirtualMachineInterface.zip b/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2VirtualMachineInterface/contrailV2VirtualMachineInterface.zip
index 4b48a6838d..60950b65cc 100644
--- a/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2VirtualMachineInterface/contrailV2VirtualMachineInterface.zip
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2VirtualMachineInterface/contrailV2VirtualMachineInterface.zip
Binary files differ
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2VirtualNetwork/contrailV2VirtualNetwork.yml b/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2VirtualNetwork/contrailV2VirtualNetwork.yml
index 1ff1402411..0fa7c94a63 100644
--- a/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2VirtualNetwork/contrailV2VirtualNetwork.yml
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2VirtualNetwork/contrailV2VirtualNetwork.yml
@@ -1,14 +1,7 @@
tosca_definitions_version: tosca_simple_yaml_1_0_0
-metadata:
- template_name: ContrailV2VirtualNetworkGlobalType
- template_version: 1.0.0
-description: Contrail V2 Virtual Network Global Types
-imports:
- common_definitions:
- file: CommonGlobalTypesServiceTemplate.yaml
node_types:
org.openecomp.resource.vl.nodes.heat.network.contrailV2.VirtualNetwork:
- derived_from: tosca.nodes.network.Network
+ derived_from: org.openecomp.resource.vl.nodes.network.Network
properties:
network_ipam_refs_data:
type: list
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2VirtualNetwork/contrailV2VirtualNetwork.zip b/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2VirtualNetwork/contrailV2VirtualNetwork.zip
index 637e78da25..43f499bdbb 100644
--- a/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2VirtualNetwork/contrailV2VirtualNetwork.zip
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2VirtualNetwork/contrailV2VirtualNetwork.zip
Binary files differ
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/contrailVirtualNetwork/contrailVirtualNetwork.yml b/catalog-be/src/main/resources/import/tosca/heat-types/contrailVirtualNetwork/contrailVirtualNetwork.yml
index a5424c3c83..c0d1f3dab2 100644
--- a/catalog-be/src/main/resources/import/tosca/heat-types/contrailVirtualNetwork/contrailVirtualNetwork.yml
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/contrailVirtualNetwork/contrailVirtualNetwork.yml
@@ -1,14 +1,7 @@
tosca_definitions_version: tosca_simple_yaml_1_0_0
-metadata:
- template_name: ContrailVirtualNetworkGlobalType
- template_version: 1.0.0
-description: Contrail Virtual Network Global Types
-imports:
- common_definitions:
- file: CommonGlobalTypesServiceTemplate.yaml
node_types:
org.openecomp.resource.vl.nodes.heat.network.contrail.VirtualNetwork:
- derived_from: tosca.nodes.network.Network
+ derived_from: org.openecomp.resource.vl.nodes.network.Network
properties:
shared:
type: string
@@ -81,4 +74,4 @@ node_types:
type: tosca.capabilities.Attachment
occurrences:
- 1
- - UNBOUNDED
+ - UNBOUNDED \ No newline at end of file
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/contrailVirtualNetwork/contrailVirtualNetwork.zip b/catalog-be/src/main/resources/import/tosca/heat-types/contrailVirtualNetwork/contrailVirtualNetwork.zip
index 17b32db41a..56d38c5272 100644
--- a/catalog-be/src/main/resources/import/tosca/heat-types/contrailVirtualNetwork/contrailVirtualNetwork.zip
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/contrailVirtualNetwork/contrailVirtualNetwork.zip
Binary files differ
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/eline/eline.yml b/catalog-be/src/main/resources/import/tosca/heat-types/eline/eline.yml
index 21241369c7..79876881cd 100644
--- a/catalog-be/src/main/resources/import/tosca/heat-types/eline/eline.yml
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/eline/eline.yml
@@ -1,5 +1,4 @@
tosca_definitions_version: tosca_simple_yaml_1_0_0
-
node_types:
org.openecomp.resource.vl.ELine:
derived_from: org.openecomp.resource.vl.VL
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/eline/eline.zip b/catalog-be/src/main/resources/import/tosca/heat-types/eline/eline.zip
index 132c5eebc5..8ba7cbceac 100644
--- a/catalog-be/src/main/resources/import/tosca/heat-types/eline/eline.zip
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/eline/eline.zip
Binary files differ
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/extCp/extCp.json b/catalog-be/src/main/resources/import/tosca/heat-types/extCp/extCp.json
new file mode 100644
index 0000000000..ca20a27318
--- /dev/null
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/extCp/extCp.json
@@ -0,0 +1,21 @@
+{
+ "payloadName": "extCp.yml",
+ "contactId": "DS200P",
+ "name": "ExtCP",
+ "description": "The AT&T Connection Point base type all other CP derive from",
+ "resourceIconPath": "network",
+ "resourceType": "CP",
+ "categories": [
+ {
+ "name": "Generic",
+ "subcategories": [
+ {
+ "name": "Network Elements"
+ }
+ ]
+ }
+],
+ "tags": [
+ "ExtCP"
+ ]
+}
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/extCp/extCp.yml b/catalog-be/src/main/resources/import/tosca/heat-types/extCp/extCp.yml
new file mode 100644
index 0000000000..e73cafe100
--- /dev/null
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/extCp/extCp.yml
@@ -0,0 +1,53 @@
+tosca_definitions_version: tosca_simple_yaml_1_0_0
+node_types:
+ org.openecomp.resource.cp.extCP:
+ derived_from: tosca.nodes.Root
+ description: The SDC Connection Point base type all other CP derive from
+ properties:
+ network_role:
+ type: string
+ required: true
+ description: identical to VL network_role
+ order:
+ type: integer
+ required: true
+ description: The order of the CP on the compute instance (e.g. eth2).
+ network_role_tag:
+ type: string
+ required: true
+ description: Must correlate to the set of defined “network-role” tag identifiers from the associated HEAT template
+ mac_requirements:
+ type: org.openecomp.datatypes.network.MacRequirements
+ required: false
+ description: identifies MAC address assignments to the CP
+ vlan_requirements:
+ type: list
+ entry_schema:
+ type: org.openecomp.datatypes.network.VlanRequirements
+ required: false
+ description: identifies vlan address assignments to the CP
+ ip_requirements:
+ type: list
+ entry_schema:
+ type: org.openecomp.datatypes.network.IpRequirements
+ required: true
+ description: identifies IP requirements to the CP
+ exCP_naming:
+ type: org.openecomp.datatypes.Naming
+ subnetpoolid:
+ type: string
+ requirements:
+ virtualLink:
+ capability: tosca.capabilities.network.Linkable
+ relationship: tosca.relationships.network.LinksTo
+ virtualBinding:
+ capability: tosca.capabilities.network.Bindable
+ relationship: tosca.relationships.network.BindsTo
+ external_virtualLink:
+ capability: tosca.capabilities.network.Linkable
+ relationship: tosca.relationships.network.LinksTo
+ node: org.openecomp.resource.vl.VL
+ capabilities:
+ internal_connectionPoint:
+ type: tosca.capabilities.Node
+ valid_source_type: [tosca.nodes.network.Port] \ No newline at end of file
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/extCp/extCp.zip b/catalog-be/src/main/resources/import/tosca/heat-types/extCp/extCp.zip
new file mode 100644
index 0000000000..a26c323819
--- /dev/null
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/extCp/extCp.zip
Binary files differ
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/extVl/extVl.json b/catalog-be/src/main/resources/import/tosca/heat-types/extVl/extVl.json
new file mode 100644
index 0000000000..8b9ff798ad
--- /dev/null
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/extVl/extVl.json
@@ -0,0 +1,21 @@
+{
+ "payloadName": "extVl.yml",
+ "contactId": "DS200P",
+ "name": "ExtVL",
+ "description": "ECOMP generic virtual link (network) base type for all other service-level and global networks",
+ "resourceIconPath": "network",
+ "resourceType": "VL",
+ "categories": [
+ {
+ "name": "Generic",
+ "subcategories": [
+ {
+ "name": "Network Elements"
+ }
+ ]
+ }
+],
+ "tags": [
+ "ExtVL"
+ ]
+}
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/extVl/extVl.yml b/catalog-be/src/main/resources/import/tosca/heat-types/extVl/extVl.yml
new file mode 100644
index 0000000000..3973598acd
--- /dev/null
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/extVl/extVl.yml
@@ -0,0 +1,50 @@
+tosca_definitions_version: tosca_simple_yaml_1_0_0
+node_types:
+ org.openecomp.resource.vl.extVL:
+ derived_from: tosca.nodes.Root
+ description: VF Tenant oam protected network
+ properties:
+ network_type:
+ type: string
+ required: true
+ description: ECOMP supported network types.
+ network_role:
+ type: string
+ required: ture
+ description: >
+ Unique label that defines the role that this network performs.
+ example: vce oam network, vnat sr-iov1 network
+ network_scope:
+ type: string
+ constraints:
+ valid_values: ["VF", "SERVICE", "GLOBAL"]
+ description: >
+ Uniquely identifies the network scope. Valid values for the network scope
+ includes:
+ VF - VF-level network. Intra-VF network which connects the VFCs (VMs)
+ inside the VF.
+ SERVICE - Service-level network. Intra-Service network which connects
+ the VFs within the service
+ GLOBAL - Global network which can be shared by multiple services
+ network_technology:
+ type: string
+ required: true
+ description: ECOMP supported network technology
+ exVL_naming:
+ type: org.openecomp.datatypes.Naming
+ required: true
+ network_homing:
+ type: org.openecomp.datatypes.EcompHoming
+ required: true
+ network_assignments:
+ type: org.openecomp.datatypes.network.NetworkAssignments
+ required: true
+ provider_network:
+ type: org.openecomp.datatypes.network.ProviderNetwork
+ required: true
+ network_flows:
+ type: org.openecomp.datatypes.network.NetworkFlows
+ required: false
+ capabilities:
+ virtual_linkable:
+ type: tosca.capabilities.network.Linkable \ No newline at end of file
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
new file mode 100644
index 0000000000..80b1e1a1dd
--- /dev/null
+++ 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/globalCompute/globalCompute.json b/catalog-be/src/main/resources/import/tosca/heat-types/globalCompute/globalCompute.json
new file mode 100644
index 0000000000..68ff39afaf
--- /dev/null
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/globalCompute/globalCompute.json
@@ -0,0 +1,20 @@
+{
+ "payloadName": "globalCompute.yml",
+ "contactId": "jh0003",
+ "name": "GlobalCompute",
+ "description": "Represents a global virtual machine with monitoring capabilities.",
+ "resourceIconPath": "defaulticon",
+ "categories": [
+ {
+ "name": "Generic",
+ "subcategories": [
+ {
+ "name": "Abstract"
+ }
+ ]
+ }
+],
+ "tags": [
+ "GlobalCompute"
+ ]
+} \ No newline at end of file
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/globalCompute/globalCompute.yml b/catalog-be/src/main/resources/import/tosca/heat-types/globalCompute/globalCompute.yml
new file mode 100644
index 0000000000..4ac9950ee2
--- /dev/null
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/globalCompute/globalCompute.yml
@@ -0,0 +1,1300 @@
+tosca_definitions_version: tosca_simple_yaml_1_0_0
+node_types:
+ org.openecomp.resource.vfc.nodes.Compute:
+ derived_from: tosca.nodes.Compute
+ capabilities:
+ disk.ephemeral.size:
+ type: org.openecomp.capabilities.metric.Ceilometer
+ description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer.
+ properties:
+ unit:
+ type: string
+ description: Unit of the metric value
+ required: true
+ default: GB
+ status: SUPPORTED
+ name:
+ type: string
+ description: Ceilometer metric type name to monitor. (The name ceilometer is using)
+ required: true
+ default: disk.ephemeral.size
+ status: SUPPORTED
+ description:
+ type: string
+ description: Description of the metric
+ required: false
+ default: Size of ephemeral disk
+ status: SUPPORTED
+ type:
+ type: string
+ description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc.
+ required: true
+ default: Gauge
+ status: SUPPORTED
+ category:
+ type: string
+ description: Category of the metric, for an example, compute, disk, network, storage and etc.
+ required: false
+ default: compute
+ status: SUPPORTED
+ occurrences:
+ - 1
+ - UNBOUNDED
+ instance:
+ type: org.openecomp.capabilities.metric.Ceilometer
+ description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer.
+ properties:
+ unit:
+ type: string
+ description: Unit of the metric value
+ required: true
+ default: instance
+ status: SUPPORTED
+ name:
+ type: string
+ description: Ceilometer metric type name to monitor. (The name ceilometer is using)
+ required: true
+ default: instance
+ status: SUPPORTED
+ description:
+ type: string
+ description: Description of the metric
+ required: false
+ default: Existence of instance
+ status: SUPPORTED
+ type:
+ type: string
+ description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc.
+ required: true
+ default: Gauge
+ status: SUPPORTED
+ category:
+ type: string
+ description: Category of the metric, for an example, compute, disk, network, storage and etc.
+ required: false
+ default: compute
+ status: SUPPORTED
+ occurrences:
+ - 1
+ - UNBOUNDED
+ memory:
+ type: org.openecomp.capabilities.metric.Ceilometer
+ description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer.
+ properties:
+ unit:
+ type: string
+ description: Unit of the metric value
+ required: true
+ default: MB
+ status: SUPPORTED
+ name:
+ type: string
+ description: Ceilometer metric type name to monitor. (The name ceilometer is using)
+ required: true
+ default: memory
+ status: SUPPORTED
+ description:
+ type: string
+ description: Description of the metric
+ required: false
+ default: Volume of RAM allocated to the instance
+ status: SUPPORTED
+ type:
+ type: string
+ description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc.
+ required: true
+ default: Gauge
+ status: SUPPORTED
+ category:
+ type: string
+ description: Category of the metric, for an example, compute, disk, network, storage and etc.
+ required: false
+ default: compute
+ status: SUPPORTED
+ occurrences:
+ - 1
+ - UNBOUNDED
+ disk.iops:
+ type: org.openecomp.capabilities.metric.Ceilometer
+ description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer.
+ properties:
+ unit:
+ type: string
+ description: Unit of the metric value
+ required: true
+ default: count/s
+ status: SUPPORTED
+ name:
+ type: string
+ description: Ceilometer metric type name to monitor. (The name ceilometer is using)
+ required: true
+ default: disk.iops
+ status: SUPPORTED
+ description:
+ type: string
+ description: Description of the metric
+ required: false
+ default: Average disk iops
+ status: SUPPORTED
+ type:
+ type: string
+ description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc.
+ required: true
+ default: Gauge
+ status: SUPPORTED
+ category:
+ type: string
+ description: Category of the metric, for an example, compute, disk, network, storage and etc.
+ required: false
+ default: disk
+ status: SUPPORTED
+ occurrences:
+ - 1
+ - UNBOUNDED
+ disk.device.read.requests:
+ type: org.openecomp.capabilities.metric.Ceilometer
+ description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer.
+ properties:
+ unit:
+ type: string
+ description: Unit of the metric value
+ required: true
+ default: request
+ status: SUPPORTED
+ name:
+ type: string
+ description: Ceilometer metric type name to monitor. (The name ceilometer is using)
+ required: true
+ default: disk.device.read.requests
+ status: SUPPORTED
+ description:
+ type: string
+ description: Description of the metric
+ required: false
+ default: Number of read requests
+ status: SUPPORTED
+ type:
+ type: string
+ description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc.
+ required: true
+ default: Cumulative
+ status: SUPPORTED
+ category:
+ type: string
+ description: Category of the metric, for an example, compute, disk, network, storage and etc.
+ required: false
+ default: disk
+ status: SUPPORTED
+ occurrences:
+ - 1
+ - UNBOUNDED
+ cpu.delta:
+ type: org.openecomp.capabilities.metric.Ceilometer
+ description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer.
+ properties:
+ unit:
+ type: string
+ description: Unit of the metric value
+ required: true
+ default: ns
+ status: SUPPORTED
+ name:
+ type: string
+ description: Ceilometer metric type name to monitor. (The name ceilometer is using)
+ required: true
+ default: cpu.delta
+ status: SUPPORTED
+ description:
+ type: string
+ description: Description of the metric
+ required: false
+ default: CPU time used since previous datapoint
+ status: SUPPORTED
+ type:
+ type: string
+ description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc.
+ required: true
+ default: Delta
+ status: SUPPORTED
+ category:
+ type: string
+ description: Category of the metric, for an example, compute, disk, network, storage and etc.
+ required: false
+ default: compute
+ status: SUPPORTED
+ occurrences:
+ - 1
+ - UNBOUNDED
+ disk.capacity:
+ type: org.openecomp.capabilities.metric.Ceilometer
+ description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer.
+ properties:
+ unit:
+ type: string
+ description: Unit of the metric value
+ required: true
+ default: B
+ status: SUPPORTED
+ name:
+ type: string
+ description: Ceilometer metric type name to monitor. (The name ceilometer is using)
+ required: true
+ default: disk.capacity
+ status: SUPPORTED
+ description:
+ type: string
+ description: Description of the metric
+ required: false
+ default: The amount of disk that the instance can see
+ status: SUPPORTED
+ type:
+ type: string
+ description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc.
+ required: true
+ default: Gauge
+ status: SUPPORTED
+ category:
+ type: string
+ description: Category of the metric, for an example, compute, disk, network, storage and etc.
+ required: false
+ default: disk
+ status: SUPPORTED
+ occurrences:
+ - 1
+ - UNBOUNDED
+ disk.device.read.bytes:
+ type: org.openecomp.capabilities.metric.Ceilometer
+ description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer.
+ properties:
+ unit:
+ type: string
+ description: Unit of the metric value
+ required: true
+ default: B
+ status: SUPPORTED
+ name:
+ type: string
+ description: Ceilometer metric type name to monitor. (The name ceilometer is using)
+ required: true
+ default: disk.device.read.bytes
+ status: SUPPORTED
+ description:
+ type: string
+ description: Description of the metric
+ required: false
+ default: Volume of reads
+ status: SUPPORTED
+ type:
+ type: string
+ description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc.
+ required: true
+ default: Cumulative
+ status: SUPPORTED
+ category:
+ type: string
+ description: Category of the metric, for an example, compute, disk, network, storage and etc.
+ required: false
+ default: disk
+ status: SUPPORTED
+ occurrences:
+ - 1
+ - UNBOUNDED
+ disk.write.bytes:
+ type: org.openecomp.capabilities.metric.Ceilometer
+ description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer.
+ properties:
+ unit:
+ type: string
+ description: Unit of the metric value
+ required: true
+ default: B
+ status: SUPPORTED
+ name:
+ type: string
+ description: Ceilometer metric type name to monitor. (The name ceilometer is using)
+ required: true
+ default: disk.write.bytes
+ status: SUPPORTED
+ description:
+ type: string
+ description: Description of the metric
+ required: false
+ default: Volume of writes
+ status: SUPPORTED
+ type:
+ type: string
+ description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc.
+ required: true
+ default: Cumulative
+ status: SUPPORTED
+ category:
+ type: string
+ description: Category of the metric, for an example, compute, disk, network, storage and etc.
+ required: false
+ default: compute
+ status: SUPPORTED
+ occurrences:
+ - 1
+ - UNBOUNDED
+ disk.latency:
+ type: org.openecomp.capabilities.metric.Ceilometer
+ description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer.
+ properties:
+ unit:
+ type: string
+ description: Unit of the metric value
+ required: true
+ default: ms
+ status: SUPPORTED
+ name:
+ type: string
+ description: Ceilometer metric type name to monitor. (The name ceilometer is using)
+ required: true
+ default: disk.latency
+ status: SUPPORTED
+ description:
+ type: string
+ description: Description of the metric
+ required: false
+ default: Average disk latency
+ status: SUPPORTED
+ type:
+ type: string
+ description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc.
+ required: true
+ default: Gauge
+ status: SUPPORTED
+ category:
+ type: string
+ description: Category of the metric, for an example, compute, disk, network, storage and etc.
+ required: false
+ default: disk
+ status: SUPPORTED
+ occurrences:
+ - 1
+ - UNBOUNDED
+ disk.device.read.bytes.rate:
+ type: org.openecomp.capabilities.metric.Ceilometer
+ description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer.
+ properties:
+ unit:
+ type: string
+ description: Unit of the metric value
+ required: true
+ default: B/s
+ status: SUPPORTED
+ name:
+ type: string
+ description: Ceilometer metric type name to monitor. (The name ceilometer is using)
+ required: true
+ default: disk.device.read.bytes.rate
+ status: SUPPORTED
+ description:
+ type: string
+ description: Description of the metric
+ required: false
+ default: Average rate of reads
+ status: SUPPORTED
+ type:
+ type: string
+ description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc.
+ required: true
+ default: Gauge
+ status: SUPPORTED
+ category:
+ type: string
+ description: Category of the metric, for an example, compute, disk, network, storage and etc.
+ required: false
+ default: disk
+ status: SUPPORTED
+ occurrences:
+ - 1
+ - UNBOUNDED
+ disk.usage:
+ type: org.openecomp.capabilities.metric.Ceilometer
+ description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer.
+ properties:
+ unit:
+ type: string
+ description: Unit of the metric value
+ required: true
+ default: B
+ status: SUPPORTED
+ name:
+ type: string
+ description: Ceilometer metric type name to monitor. (The name ceilometer is using)
+ required: true
+ default: disk.usage
+ status: SUPPORTED
+ description:
+ type: string
+ description: Description of the metric
+ required: false
+ default: The physical size in bytes of the image container on the host
+ status: SUPPORTED
+ type:
+ type: string
+ description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc.
+ required: true
+ default: Gauge
+ status: SUPPORTED
+ category:
+ type: string
+ description: Category of the metric, for an example, compute, disk, network, storage and etc.
+ required: false
+ default: disk
+ status: SUPPORTED
+ occurrences:
+ - 1
+ - UNBOUNDED
+ cpu_util:
+ type: org.openecomp.capabilities.metric.Ceilometer
+ description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer.
+ properties:
+ unit:
+ type: string
+ description: Unit of the metric value
+ required: true
+ default: '%'
+ status: SUPPORTED
+ name:
+ type: string
+ description: Ceilometer metric type name to monitor. (The name ceilometer is using)
+ required: true
+ default: cpu_util
+ status: SUPPORTED
+ description:
+ type: string
+ description: Description of the metric
+ required: false
+ default: Average CPU utilization
+ status: SUPPORTED
+ type:
+ type: string
+ description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc.
+ required: true
+ default: Gauge
+ status: SUPPORTED
+ category:
+ type: string
+ description: Category of the metric, for an example, compute, disk, network, storage and etc.
+ required: false
+ default: compute
+ status: SUPPORTED
+ occurrences:
+ - 1
+ - UNBOUNDED
+ disk.device.allocation:
+ type: org.openecomp.capabilities.metric.Ceilometer
+ description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer.
+ properties:
+ unit:
+ type: string
+ description: Unit of the metric value
+ required: true
+ default: B
+ status: SUPPORTED
+ name:
+ type: string
+ description: Ceilometer metric type name to monitor. (The name ceilometer is using)
+ required: true
+ default: disk.device.allocation
+ status: SUPPORTED
+ description:
+ type: string
+ description: Description of the metric
+ required: false
+ default: The amount of disk per device occupied by the instance on the host machine
+ status: SUPPORTED
+ type:
+ type: string
+ description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc.
+ required: true
+ default: Gauge
+ status: SUPPORTED
+ category:
+ type: string
+ description: Category of the metric, for an example, compute, disk, network, storage and etc.
+ required: false
+ default: disk
+ status: SUPPORTED
+ occurrences:
+ - 1
+ - UNBOUNDED
+ disk.write.requests.rate:
+ type: org.openecomp.capabilities.metric.Ceilometer
+ description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer.
+ properties:
+ unit:
+ type: string
+ description: Unit of the metric value
+ required: true
+ default: request/s
+ status: SUPPORTED
+ name:
+ type: string
+ description: Ceilometer metric type name to monitor. (The name ceilometer is using)
+ required: true
+ default: disk.write.requests.rate
+ status: SUPPORTED
+ description:
+ type: string
+ description: Description of the metric
+ required: false
+ default: Average rate of write requests
+ status: SUPPORTED
+ type:
+ type: string
+ description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc.
+ required: true
+ default: Gauge
+ status: SUPPORTED
+ category:
+ type: string
+ description: Category of the metric, for an example, compute, disk, network, storage and etc.
+ required: false
+ default: compute
+ status: SUPPORTED
+ occurrences:
+ - 1
+ - UNBOUNDED
+ disk.write.bytes.rate:
+ type: org.openecomp.capabilities.metric.Ceilometer
+ description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer.
+ properties:
+ unit:
+ type: string
+ description: Unit of the metric value
+ required: true
+ default: B/s
+ status: SUPPORTED
+ name:
+ type: string
+ description: Ceilometer metric type name to monitor. (The name ceilometer is using)
+ required: true
+ default: disk.write.bytes.rate
+ status: SUPPORTED
+ description:
+ type: string
+ description: Description of the metric
+ required: false
+ default: Average rate of writes
+ status: SUPPORTED
+ type:
+ type: string
+ description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc.
+ required: true
+ default: Gauge
+ status: SUPPORTED
+ category:
+ type: string
+ description: Category of the metric, for an example, compute, disk, network, storage and etc.
+ required: false
+ default: compute
+ status: SUPPORTED
+ occurrences:
+ - 1
+ - UNBOUNDED
+ disk.device.latency:
+ type: org.openecomp.capabilities.metric.Ceilometer
+ description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer.
+ properties:
+ unit:
+ type: string
+ description: Unit of the metric value
+ required: true
+ default: ms
+ status: SUPPORTED
+ name:
+ type: string
+ description: Ceilometer metric type name to monitor. (The name ceilometer is using)
+ required: true
+ default: disk.device.latency
+ status: SUPPORTED
+ description:
+ type: string
+ description: Description of the metric
+ required: false
+ default: Average disk latency per device
+ status: SUPPORTED
+ type:
+ type: string
+ description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc.
+ required: true
+ default: Gauge
+ status: SUPPORTED
+ category:
+ type: string
+ description: Category of the metric, for an example, compute, disk, network, storage and etc.
+ required: false
+ default: disk
+ status: SUPPORTED
+ occurrences:
+ - 1
+ - UNBOUNDED
+ cpu:
+ type: org.openecomp.capabilities.metric.Ceilometer
+ description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer.
+ properties:
+ unit:
+ type: string
+ description: Unit of the metric value
+ required: true
+ default: ns
+ status: SUPPORTED
+ name:
+ type: string
+ description: Ceilometer metric type name to monitor. (The name ceilometer is using)
+ required: true
+ default: cpu
+ status: SUPPORTED
+ description:
+ type: string
+ description: Description of the metric
+ required: false
+ default: CPU time used
+ status: SUPPORTED
+ type:
+ type: string
+ description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc.
+ required: true
+ default: Cumulative
+ status: SUPPORTED
+ category:
+ type: string
+ description: Category of the metric, for an example, compute, disk, network, storage and etc.
+ required: false
+ default: compute
+ status: SUPPORTED
+ occurrences:
+ - 1
+ - UNBOUNDED
+ disk.device.write.requests:
+ type: org.openecomp.capabilities.metric.Ceilometer
+ description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer.
+ properties:
+ unit:
+ type: string
+ description: Unit of the metric value
+ required: true
+ default: request
+ status: SUPPORTED
+ name:
+ type: string
+ description: Ceilometer metric type name to monitor. (The name ceilometer is using)
+ required: true
+ default: disk.device.write.requests
+ status: SUPPORTED
+ description:
+ type: string
+ description: Description of the metric
+ required: false
+ default: Number of write requests
+ status: SUPPORTED
+ type:
+ type: string
+ description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc.
+ required: true
+ default: Cumulative
+ status: SUPPORTED
+ category:
+ type: string
+ description: Category of the metric, for an example, compute, disk, network, storage and etc.
+ required: false
+ default: disk
+ status: SUPPORTED
+ occurrences:
+ - 1
+ - UNBOUNDED
+ disk.device.write.bytes:
+ type: org.openecomp.capabilities.metric.Ceilometer
+ description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer.
+ properties:
+ unit:
+ type: string
+ description: Unit of the metric value
+ required: true
+ default: B
+ status: SUPPORTED
+ name:
+ type: string
+ description: Ceilometer metric type name to monitor. (The name ceilometer is using)
+ required: true
+ default: disk.device.write.bytes
+ status: SUPPORTED
+ description:
+ type: string
+ description: Description of the metric
+ required: false
+ default: Volume of writes
+ status: SUPPORTED
+ type:
+ type: string
+ description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc.
+ required: true
+ default: Cumulative
+ status: SUPPORTED
+ category:
+ type: string
+ description: Category of the metric, for an example, compute, disk, network, storage and etc.
+ required: false
+ default: disk
+ status: SUPPORTED
+ occurrences:
+ - 1
+ - UNBOUNDED
+ disk.read.requests:
+ type: org.openecomp.capabilities.metric.Ceilometer
+ description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer.
+ properties:
+ unit:
+ type: string
+ description: Unit of the metric value
+ required: true
+ default: request
+ status: SUPPORTED
+ name:
+ type: string
+ description: Ceilometer metric type name to monitor. (The name ceilometer is using)
+ required: true
+ default: disk.read.requests
+ status: SUPPORTED
+ description:
+ type: string
+ description: Description of the metric
+ required: false
+ default: Number of read requests
+ status: SUPPORTED
+ type:
+ type: string
+ description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc.
+ required: true
+ default: Cumulative
+ status: SUPPORTED
+ category:
+ type: string
+ description: Category of the metric, for an example, compute, disk, network, storage and etc.
+ required: false
+ default: compute
+ status: SUPPORTED
+ occurrences:
+ - 1
+ - UNBOUNDED
+ disk.root.size:
+ type: org.openecomp.capabilities.metric.Ceilometer
+ description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer.
+ properties:
+ unit:
+ type: string
+ description: Unit of the metric value
+ required: true
+ default: GB
+ status: SUPPORTED
+ name:
+ type: string
+ description: Ceilometer metric type name to monitor. (The name ceilometer is using)
+ required: true
+ default: disk.root.size
+ status: SUPPORTED
+ description:
+ type: string
+ description: Description of the metric
+ required: false
+ default: Size of root disk
+ status: SUPPORTED
+ type:
+ type: string
+ description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc.
+ required: true
+ default: Gauge
+ status: SUPPORTED
+ category:
+ type: string
+ description: Category of the metric, for an example, compute, disk, network, storage and etc.
+ required: false
+ default: compute
+ status: SUPPORTED
+ occurrences:
+ - 1
+ - UNBOUNDED
+ disk.device.write.bytes.rate:
+ type: org.openecomp.capabilities.metric.Ceilometer
+ description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer.
+ properties:
+ unit:
+ type: string
+ description: Unit of the metric value
+ required: true
+ default: B/s
+ status: SUPPORTED
+ name:
+ type: string
+ description: Ceilometer metric type name to monitor. (The name ceilometer is using)
+ required: true
+ default: disk.device.write.bytes.rate
+ status: SUPPORTED
+ description:
+ type: string
+ description: Description of the metric
+ required: false
+ default: Average rate of writes
+ status: SUPPORTED
+ type:
+ type: string
+ description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc.
+ required: true
+ default: Gauge
+ status: SUPPORTED
+ category:
+ type: string
+ description: Category of the metric, for an example, compute, disk, network, storage and etc.
+ required: false
+ default: disk
+ status: SUPPORTED
+ occurrences:
+ - 1
+ - UNBOUNDED
+ vcpus:
+ type: org.openecomp.capabilities.metric.Ceilometer
+ description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer.
+ properties:
+ unit:
+ type: string
+ description: Unit of the metric value
+ required: true
+ default: vcpu
+ status: SUPPORTED
+ name:
+ type: string
+ description: Ceilometer metric type name to monitor. (The name ceilometer is using)
+ required: true
+ default: vcpus
+ status: SUPPORTED
+ description:
+ type: string
+ description: Description of the metric
+ required: false
+ default: Number of virtual CPUs allocated to the instance
+ status: SUPPORTED
+ type:
+ type: string
+ description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc.
+ required: true
+ default: Gauge
+ status: SUPPORTED
+ category:
+ type: string
+ description: Category of the metric, for an example, compute, disk, network, storage and etc.
+ required: false
+ default: compute
+ status: SUPPORTED
+ occurrences:
+ - 1
+ - UNBOUNDED
+ disk.device.iops:
+ type: org.openecomp.capabilities.metric.Ceilometer
+ description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer.
+ properties:
+ unit:
+ type: string
+ description: Unit of the metric value
+ required: true
+ default: count/s
+ status: SUPPORTED
+ name:
+ type: string
+ description: Ceilometer metric type name to monitor. (The name ceilometer is using)
+ required: true
+ default: disk.device.iops
+ status: SUPPORTED
+ description:
+ type: string
+ description: Description of the metric
+ required: false
+ default: Average disk iops per device
+ status: SUPPORTED
+ type:
+ type: string
+ description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc.
+ required: true
+ default: Gauge
+ status: SUPPORTED
+ category:
+ type: string
+ description: Category of the metric, for an example, compute, disk, network, storage and etc.
+ required: false
+ default: disk
+ status: SUPPORTED
+ occurrences:
+ - 1
+ - UNBOUNDED
+ disk.device.usage:
+ type: org.openecomp.capabilities.metric.Ceilometer
+ description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer.
+ properties:
+ unit:
+ type: string
+ description: Unit of the metric value
+ required: true
+ default: B
+ status: SUPPORTED
+ name:
+ type: string
+ description: Ceilometer metric type name to monitor. (The name ceilometer is using)
+ required: true
+ default: disk.device.usage
+ status: SUPPORTED
+ description:
+ type: string
+ description: Description of the metric
+ required: false
+ default: The physical size in bytes of the image container on the host per device
+ status: SUPPORTED
+ type:
+ type: string
+ description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc.
+ required: true
+ default: Gauge
+ status: SUPPORTED
+ category:
+ type: string
+ description: Category of the metric, for an example, compute, disk, network, storage and etc.
+ required: false
+ default: disk
+ status: SUPPORTED
+ occurrences:
+ - 1
+ - UNBOUNDED
+ disk.device.read.requests.rate:
+ type: org.openecomp.capabilities.metric.Ceilometer
+ description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer.
+ properties:
+ unit:
+ type: string
+ description: Unit of the metric value
+ required: true
+ default: request/s
+ status: SUPPORTED
+ name:
+ type: string
+ description: Ceilometer metric type name to monitor. (The name ceilometer is using)
+ required: true
+ default: disk.device.read.requests.rate
+ status: SUPPORTED
+ description:
+ type: string
+ description: Description of the metric
+ required: false
+ default: Average rate of read requests
+ status: SUPPORTED
+ type:
+ type: string
+ description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc.
+ required: true
+ default: Gauge
+ status: SUPPORTED
+ category:
+ type: string
+ description: Category of the metric, for an example, compute, disk, network, storage and etc.
+ required: false
+ default: disk
+ status: SUPPORTED
+ occurrences:
+ - 1
+ - UNBOUNDED
+ disk.device.write.requests.rate:
+ type: org.openecomp.capabilities.metric.Ceilometer
+ description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer.
+ properties:
+ unit:
+ type: string
+ description: Unit of the metric value
+ required: true
+ default: request/s
+ status: SUPPORTED
+ name:
+ type: string
+ description: Ceilometer metric type name to monitor. (The name ceilometer is using)
+ required: true
+ default: disk.device.write.requests.rate
+ status: SUPPORTED
+ description:
+ type: string
+ description: Description of the metric
+ required: false
+ default: Average rate of write requests
+ status: SUPPORTED
+ type:
+ type: string
+ description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc.
+ required: true
+ default: Gauge
+ status: SUPPORTED
+ category:
+ type: string
+ description: Category of the metric, for an example, compute, disk, network, storage and etc.
+ required: false
+ default: disk
+ status: SUPPORTED
+ occurrences:
+ - 1
+ - UNBOUNDED
+ disk.allocation:
+ type: org.openecomp.capabilities.metric.Ceilometer
+ description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer.
+ properties:
+ unit:
+ type: string
+ description: Unit of the metric value
+ required: true
+ default: B
+ status: SUPPORTED
+ name:
+ type: string
+ description: Ceilometer metric type name to monitor. (The name ceilometer is using)
+ required: true
+ default: disk.allocation
+ status: SUPPORTED
+ description:
+ type: string
+ description: Description of the metric
+ required: false
+ default: The amount of disk occupied by the instance on the host machine
+ status: SUPPORTED
+ type:
+ type: string
+ description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc.
+ required: true
+ default: Gauge
+ status: SUPPORTED
+ category:
+ type: string
+ description: Category of the metric, for an example, compute, disk, network, storage and etc.
+ required: false
+ default: disk
+ status: SUPPORTED
+ occurrences:
+ - 1
+ - UNBOUNDED
+ disk.read.bytes.rate:
+ type: org.openecomp.capabilities.metric.Ceilometer
+ description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer.
+ properties:
+ unit:
+ type: string
+ description: Unit of the metric value
+ required: true
+ default: B/s
+ status: SUPPORTED
+ name:
+ type: string
+ description: Ceilometer metric type name to monitor. (The name ceilometer is using)
+ required: true
+ default: disk.read.bytes.rate
+ status: SUPPORTED
+ description:
+ type: string
+ description: Description of the metric
+ required: false
+ default: Average rate of reads
+ status: SUPPORTED
+ type:
+ type: string
+ description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc.
+ required: true
+ default: Gauge
+ status: SUPPORTED
+ category:
+ type: string
+ description: Category of the metric, for an example, compute, disk, network, storage and etc.
+ required: false
+ default: compute
+ status: SUPPORTED
+ occurrences:
+ - 1
+ - UNBOUNDED
+ disk.read.bytes:
+ type: org.openecomp.capabilities.metric.Ceilometer
+ description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer.
+ properties:
+ unit:
+ type: string
+ description: Unit of the metric value
+ required: true
+ default: B
+ status: SUPPORTED
+ name:
+ type: string
+ description: Ceilometer metric type name to monitor. (The name ceilometer is using)
+ required: true
+ default: disk.read.bytes
+ status: SUPPORTED
+ description:
+ type: string
+ description: Description of the metric
+ required: false
+ default: Volume of reads
+ status: SUPPORTED
+ type:
+ type: string
+ description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc.
+ required: true
+ default: Cumulative
+ status: SUPPORTED
+ category:
+ type: string
+ description: Category of the metric, for an example, compute, disk, network, storage and etc.
+ required: false
+ default: compute
+ status: SUPPORTED
+ occurrences:
+ - 1
+ - UNBOUNDED
+ memory.usage:
+ type: org.openecomp.capabilities.metric.Ceilometer
+ description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer.
+ properties:
+ unit:
+ type: string
+ description: Unit of the metric value
+ required: true
+ default: MB
+ status: SUPPORTED
+ name:
+ type: string
+ description: Ceilometer metric type name to monitor. (The name ceilometer is using)
+ required: true
+ default: memory.usage
+ status: SUPPORTED
+ description:
+ type: string
+ description: Description of the metric
+ required: false
+ default: Volume of RAM used by the instance from the amount of its allocated memory
+ status: SUPPORTED
+ type:
+ type: string
+ description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc.
+ required: true
+ default: Gauge
+ status: SUPPORTED
+ category:
+ type: string
+ description: Category of the metric, for an example, compute, disk, network, storage and etc.
+ required: false
+ default: compute
+ status: SUPPORTED
+ occurrences:
+ - 1
+ - UNBOUNDED
+ disk.device.capacity:
+ type: org.openecomp.capabilities.metric.Ceilometer
+ description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer.
+ properties:
+ unit:
+ type: string
+ description: Unit of the metric value
+ required: true
+ default: B
+ status: SUPPORTED
+ name:
+ type: string
+ description: Ceilometer metric type name to monitor. (The name ceilometer is using)
+ required: true
+ default: disk.device.capacity
+ status: SUPPORTED
+ description:
+ type: string
+ description: Description of the metric
+ required: false
+ default: The amount of disk per device that the instance can see
+ status: SUPPORTED
+ type:
+ type: string
+ description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc.
+ required: true
+ default: Gauge
+ status: SUPPORTED
+ category:
+ type: string
+ description: Category of the metric, for an example, compute, disk, network, storage and etc.
+ required: false
+ default: disk
+ status: SUPPORTED
+ occurrences:
+ - 1
+ - UNBOUNDED
+ memory.resident:
+ type: org.openecomp.capabilities.metric.Ceilometer
+ description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer.
+ properties:
+ unit:
+ type: string
+ description: Unit of the metric value
+ required: true
+ default: MB
+ status: SUPPORTED
+ name:
+ type: string
+ description: Ceilometer metric type name to monitor. (The name ceilometer is using)
+ required: true
+ default: memory.resident
+ status: SUPPORTED
+ description:
+ type: string
+ description: Description of the metric
+ required: false
+ default: Volume of RAM used by the instance on the physical machine
+ status: SUPPORTED
+ type:
+ type: string
+ description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc.
+ required: true
+ default: Gauge
+ status: SUPPORTED
+ category:
+ type: string
+ description: Category of the metric, for an example, compute, disk, network, storage and etc.
+ required: false
+ default: compute
+ status: SUPPORTED
+ occurrences:
+ - 1
+ - UNBOUNDED
+ disk.write.requests:
+ type: org.openecomp.capabilities.metric.Ceilometer
+ description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer.
+ properties:
+ unit:
+ type: string
+ description: Unit of the metric value
+ required: true
+ default: request
+ status: SUPPORTED
+ name:
+ type: string
+ description: Ceilometer metric type name to monitor. (The name ceilometer is using)
+ required: true
+ default: disk.write.requests
+ status: SUPPORTED
+ description:
+ type: string
+ description: Description of the metric
+ required: false
+ default: Number of write requests
+ status: SUPPORTED
+ type:
+ type: string
+ description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc.
+ required: true
+ default: Cumulative
+ status: SUPPORTED
+ category:
+ type: string
+ description: Category of the metric, for an example, compute, disk, network, storage and etc.
+ required: false
+ default: compute
+ status: SUPPORTED
+ occurrences:
+ - 1
+ - UNBOUNDED
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/globalCompute/globalCompute.zip b/catalog-be/src/main/resources/import/tosca/heat-types/globalCompute/globalCompute.zip
new file mode 100644
index 0000000000..23a471f246
--- /dev/null
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/globalCompute/globalCompute.zip
Binary files differ
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/globalNetwork/globalNetwork.json b/catalog-be/src/main/resources/import/tosca/heat-types/globalNetwork/globalNetwork.json
new file mode 100644
index 0000000000..d39ecdc4c0
--- /dev/null
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/globalNetwork/globalNetwork.json
@@ -0,0 +1,21 @@
+{
+ "payloadName": "globalNetwork.yml",
+ "contactId": "jh0003",
+ "name": "GlobalNetwork",
+ "description": "Represents a simple , logical network service with monitoring capabilities.",
+ "resourceIconPath": "network",
+ "resourceType": "VL",
+ "categories": [
+ {
+ "name": "Generic",
+ "subcategories": [
+ {
+ "name": "Abstract"
+ }
+ ]
+ }
+],
+ "tags": [
+ "GlobalNetwork"
+ ]
+} \ No newline at end of file
diff --git a/ui-ci/src/main/resources/Files/VL.yml b/catalog-be/src/main/resources/import/tosca/heat-types/globalNetwork/globalNetwork.yml
index 72e6d2be32..6de2f2d422 100644
--- a/ui-ci/src/main/resources/Files/VL.yml
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/globalNetwork/globalNetwork.yml
@@ -1,7 +1,6 @@
tosca_definitions_version: tosca_simple_yaml_1_0_0
-
node_types:
- org.openecomp.resource.vl.VL00:
+ org.openecomp.resource.vl.nodes.network.Network:
derived_from: tosca.nodes.network.Network
properties:
vendor:
@@ -10,9 +9,6 @@ node_types:
vl_name:
type: string
required: false
-
capabilities:
- virtual_linkable:
- type: tosca.capabilities.network.Linkable
- end_point:
+ end_point:
type: tosca.capabilities.Endpoint \ No newline at end of file
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/globalNetwork/globalNetwork.zip b/catalog-be/src/main/resources/import/tosca/heat-types/globalNetwork/globalNetwork.zip
new file mode 100644
index 0000000000..ddf8640b5b
--- /dev/null
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/globalNetwork/globalNetwork.zip
Binary files differ
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/globalPort/globalPort.json b/catalog-be/src/main/resources/import/tosca/heat-types/globalPort/globalPort.json
new file mode 100644
index 0000000000..f23b8a4e0b
--- /dev/null
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/globalPort/globalPort.json
@@ -0,0 +1,15 @@
+{
+ "payloadName": "globalPort.yml",
+ "contactId": "jh0003",
+ "name": "GlobalPort",
+ "description": "Represents a global logical port with monitoring capabilities.",
+ "resourceIconPath": "port",
+ "resourceType": "CP",
+ "categories": [{
+ "name": "Generic",
+ "subcategories": [{
+ "name": "Abstract"
+ }]
+ }],
+ "tags": ["GlobalPort"]
+} \ No newline at end of file
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
new file mode 100644
index 0000000000..89ee9f81f0
--- /dev/null
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/globalPort/globalPort.yml
@@ -0,0 +1,334 @@
+tosca_definitions_version: tosca_simple_yaml_1_0_0
+node_types:
+ org.openecomp.resource.cp.nodes.network.Port:
+ derived_from: tosca.nodes.network.Port
+ properties:
+ network_role:
+ type: string
+ required: true
+ description: identical to VL network_role
+ order:
+ type: integer
+ required: true
+ description: The order of the CP on the compute instance (e.g. eth2).
+ network_role_tag:
+ description: Must correlate to the set of defined “network-role�? tag identifiers from the associated HEAT template
+ type: string
+ required: true
+ mac_requirements:
+ description: identifies MAC address assignments to the CP
+ type: org.openecomp.datatypes.network.MacRequirements
+ required: false
+ vlan_requirements:
+ description: identifies vlan address assignments to the CP
+ type: list
+ entry_schema:
+ type: org.openecomp.datatypes.network.VlanRequirements
+ required: false
+ ip_requirements:
+ description: identifies IP requirements to the CP
+ type: list
+ entry_schema:
+ type: org.openecomp.datatypes.network.IpRequirements
+ required: true
+ exCP_naming:
+ type: org.openecomp.datatypes.Naming
+ subnetpoolid:
+ type: string
+ capabilities:
+ network.incoming.packets.rate:
+ type: org.openecomp.capabilities.metric.Ceilometer
+ description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer.
+ properties:
+ unit:
+ type: string
+ description: Unit of the metric value
+ required: true
+ default: packet/s
+ status: SUPPORTED
+ name:
+ type: string
+ description: Ceilometer metric type name to monitor. (The name ceilometer is using)
+ required: true
+ default: network.incoming.packets.rate
+ status: SUPPORTED
+ description:
+ type: string
+ description: Description of the metric
+ required: false
+ default: Average rate of incoming packets
+ status: SUPPORTED
+ type:
+ type: string
+ description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc.
+ required: true
+ default: Gauge
+ status: SUPPORTED
+ category:
+ type: string
+ description: Category of the metric, for an example, compute, disk, network, storage and etc.
+ required: false
+ default: network
+ status: SUPPORTED
+ occurrences:
+ - 1
+ - UNBOUNDED
+ 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.
+ properties:
+ unit:
+ type: string
+ description: Unit of the metric value
+ required: true
+ default: B
+ status: SUPPORTED
+ name:
+ type: string
+ description: Ceilometer metric type name to monitor. (The name ceilometer is using)
+ required: true
+ default: network.outgoing.bytes
+ status: SUPPORTED
+ description:
+ type: string
+ description: Description of the metric
+ required: false
+ default: Number of outgoing bytes
+ status: SUPPORTED
+ type:
+ type: string
+ description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc.
+ required: true
+ default: Cumulative
+ status: SUPPORTED
+ category:
+ type: string
+ description: Category of the metric, for an example, compute, disk, network, storage and etc.
+ required: false
+ default: network
+ status: SUPPORTED
+ occurrences:
+ - 1
+ - UNBOUNDED
+ network.outgoing.packets.rate:
+ type: org.openecomp.capabilities.metric.Ceilometer
+ description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer.
+ properties:
+ unit:
+ type: string
+ description: Unit of the metric value
+ required: true
+ default: packet/s
+ status: SUPPORTED
+ name:
+ type: string
+ description: Ceilometer metric type name to monitor. (The name ceilometer is using)
+ required: true
+ default: network.outgoing.packets.rate
+ status: SUPPORTED
+ description:
+ type: string
+ description: Description of the metric
+ required: false
+ default: Average rate of outgoing packets
+ status: SUPPORTED
+ type:
+ type: string
+ description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc.
+ required: true
+ default: Gauge
+ status: SUPPORTED
+ category:
+ type: string
+ description: Category of the metric, for an example, compute, disk, network, storage and etc.
+ required: false
+ default: network
+ status: SUPPORTED
+ occurrences:
+ - 1
+ - UNBOUNDED
+ network.outpoing.packets:
+ type: org.openecomp.capabilities.metric.Ceilometer
+ description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer.
+ properties:
+ unit:
+ type: string
+ description: Unit of the metric value
+ required: true
+ default: packet
+ status: SUPPORTED
+ name:
+ type: string
+ description: Ceilometer metric type name to monitor. (The name ceilometer is using)
+ required: true
+ default: network.outpoing.packets
+ status: SUPPORTED
+ description:
+ type: string
+ description: Description of the metric
+ required: false
+ default: Number of outgoing packets
+ status: SUPPORTED
+ type:
+ type: string
+ description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc.
+ required: true
+ default: Cumulative
+ status: SUPPORTED
+ category:
+ type: string
+ description: Category of the metric, for an example, compute, disk, network, storage and etc.
+ required: false
+ default: network
+ status: SUPPORTED
+ occurrences:
+ - 1
+ - UNBOUNDED
+ network.incoming.bytes.rate:
+ type: org.openecomp.capabilities.metric.Ceilometer
+ description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer.
+ properties:
+ unit:
+ type: string
+ description: Unit of the metric value
+ required: true
+ default: B/s
+ status: SUPPORTED
+ name:
+ type: string
+ description: Ceilometer metric type name to monitor. (The name ceilometer is using)
+ required: true
+ default: network.incoming.bytes.rate
+ status: SUPPORTED
+ description:
+ type: string
+ description: Description of the metric
+ required: false
+ default: Average rate of incoming bytes
+ status: SUPPORTED
+ type:
+ type: string
+ description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc.
+ required: true
+ default: Gauge
+ status: SUPPORTED
+ category:
+ type: string
+ description: Category of the metric, for an example, compute, disk, network, storage and etc.
+ required: false
+ default: network
+ status: SUPPORTED
+ occurrences:
+ - 1
+ - UNBOUNDED
+ network.incoming.bytes:
+ type: org.openecomp.capabilities.metric.Ceilometer
+ description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer.
+ properties:
+ unit:
+ type: string
+ description: Unit of the metric value
+ required: true
+ default: B
+ status: SUPPORTED
+ name:
+ type: string
+ description: Ceilometer metric type name to monitor. (The name ceilometer is using)
+ required: true
+ default: network.incoming.bytes
+ status: SUPPORTED
+ description:
+ type: string
+ description: Description of the metric
+ required: false
+ default: Number of incoming bytes
+ status: SUPPORTED
+ type:
+ type: string
+ description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc.
+ required: true
+ default: Cumulative
+ status: SUPPORTED
+ category:
+ type: string
+ description: Category of the metric, for an example, compute, disk, network, storage and etc.
+ required: false
+ default: network
+ status: SUPPORTED
+ occurrences:
+ - 1
+ - UNBOUNDED
+ network.outgoing.bytes.rate:
+ type: org.openecomp.capabilities.metric.Ceilometer
+ description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer.
+ properties:
+ unit:
+ type: string
+ description: Unit of the metric value
+ required: true
+ default: B/s
+ status: SUPPORTED
+ name:
+ type: string
+ description: Ceilometer metric type name to monitor. (The name ceilometer is using)
+ required: true
+ default: network.outgoing.bytes.rate
+ status: SUPPORTED
+ description:
+ type: string
+ description: Description of the metric
+ required: false
+ default: Average rate of outgoing bytes
+ status: SUPPORTED
+ type:
+ type: string
+ description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc.
+ required: true
+ default: Gauge
+ status: SUPPORTED
+ category:
+ type: string
+ description: Category of the metric, for an example, compute, disk, network, storage and etc.
+ required: false
+ default: network
+ status: SUPPORTED
+ occurrences:
+ - 1
+ - UNBOUNDED
+ network.incoming.packets:
+ type: org.openecomp.capabilities.metric.Ceilometer
+ description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer.
+ properties:
+ unit:
+ type: string
+ description: Unit of the metric value
+ required: true
+ default: packet
+ status: SUPPORTED
+ name:
+ type: string
+ description: Ceilometer metric type name to monitor. (The name ceilometer is using)
+ required: true
+ default: network.incoming.packets
+ status: SUPPORTED
+ description:
+ type: string
+ description: Description of the metric
+ required: false
+ default: Number of incoming packets
+ status: SUPPORTED
+ type:
+ type: string
+ description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc.
+ required: true
+ default: Cumulative
+ status: SUPPORTED
+ category:
+ type: string
+ description: Category of the metric, for an example, compute, disk, network, storage and etc.
+ required: false
+ default: network
+ status: SUPPORTED
+ occurrences:
+ - 1
+ - UNBOUNDED
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
new file mode 100644
index 0000000000..8a23aa77c2
--- /dev/null
+++ 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/heat-types/internalVl/internalVl.json b/catalog-be/src/main/resources/import/tosca/heat-types/internalVl/internalVl.json
new file mode 100644
index 0000000000..96fcb5824a
--- /dev/null
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/internalVl/internalVl.json
@@ -0,0 +1,21 @@
+{
+ "payloadName": "internalVl.yml",
+ "contactId": "jh0003",
+ "name": "InternalVL",
+ "description": "The AT&T internal (VF-level) Virtual Link",
+ "resourceIconPath": "network",
+ "resourceType": "VL",
+ "categories": [
+ {
+ "name": "Network Connectivity",
+ "subcategories": [
+ {
+ "name": "Virtual Links"
+ }
+ ]
+ }
+],
+ "tags": [
+ "InternalVL"
+ ]
+}
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/internalVl/internalVl.yml b/catalog-be/src/main/resources/import/tosca/heat-types/internalVl/internalVl.yml
new file mode 100644
index 0000000000..a1b78ff9a0
--- /dev/null
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/internalVl/internalVl.yml
@@ -0,0 +1,6 @@
+tosca_definitions_version: tosca_simple_yaml_1_0_0
+
+node_types:
+ org.openecomp.resource.vl.internalVL:
+ derived_from: tosca.nodes.network.Network
+ description: The AT&T internal (VF-level) Virtual Link \ No newline at end of file
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/internalVl/internalVl.zip b/catalog-be/src/main/resources/import/tosca/heat-types/internalVl/internalVl.zip
new file mode 100644
index 0000000000..2a96bc3d9f
--- /dev/null
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/internalVl/internalVl.zip
Binary files differ
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/neutronNet/neutronNet.yml b/catalog-be/src/main/resources/import/tosca/heat-types/neutronNet/neutronNet.yml
index e80e2727c7..539e33991f 100644
--- a/catalog-be/src/main/resources/import/tosca/heat-types/neutronNet/neutronNet.yml
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/neutronNet/neutronNet.yml
@@ -1,14 +1,7 @@
tosca_definitions_version: tosca_simple_yaml_1_0_0
-metadata:
- template_name: NeutronNetGlobalTypes
- template_version: 1.0.0
-description: Neutron Network TOSCA Global Types
-imports:
- common_definitions:
- file: CommonGlobalTypesServiceTemplate.yaml
node_types:
org.openecomp.resource.vl.nodes.heat.network.neutron.Net:
- derived_from: tosca.nodes.network.Network
+ derived_from: org.openecomp.resource.vl.nodes.network.Network
properties:
dhcp_agent_ids:
type: list
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/neutronNet/neutronNet.zip b/catalog-be/src/main/resources/import/tosca/heat-types/neutronNet/neutronNet.zip
index 0cefe8a184..c8368a5923 100644
--- a/catalog-be/src/main/resources/import/tosca/heat-types/neutronNet/neutronNet.zip
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/neutronNet/neutronNet.zip
Binary files differ
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/neutronPort/neutronPort.yml b/catalog-be/src/main/resources/import/tosca/heat-types/neutronPort/neutronPort.yml
index 898615c6ce..34a74eb4c4 100644
--- a/catalog-be/src/main/resources/import/tosca/heat-types/neutronPort/neutronPort.yml
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/neutronPort/neutronPort.yml
@@ -1,14 +1,7 @@
tosca_definitions_version: tosca_simple_yaml_1_0_0
-metadata:
- template_name: NeutronPortGlobalTypes
- template_version: 1.0.0
-description: Neutron Port TOSCA Global Types
-imports:
- common_definitions:
- file: CommonGlobalTypesServiceTemplate.yaml
node_types:
org.openecomp.resource.cp.nodes.heat.network.neutron.Port:
- derived_from: tosca.nodes.network.Port
+ derived_from: org.openecomp.resource.cp.nodes.network.Port
properties:
port_security_enabled:
type: boolean
@@ -134,3 +127,10 @@ node_types:
occurrences:
- 1
- UNBOUNDED
+ binding:
+ type: tosca.capabilities.network.Bindable
+ valid_source_types:
+ - org.openecomp.resource.cp.nodes.heat.network.contrailV2.VLANSubInterface
+ occurrences:
+ - 0
+ - UNBOUNDED \ No newline at end of file
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/neutronPort/neutronPort.zip b/catalog-be/src/main/resources/import/tosca/heat-types/neutronPort/neutronPort.zip
index f120afb16e..e33365a8ca 100644
--- a/catalog-be/src/main/resources/import/tosca/heat-types/neutronPort/neutronPort.zip
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/neutronPort/neutronPort.zip
Binary files differ
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/novaServer/novaServer.json b/catalog-be/src/main/resources/import/tosca/heat-types/novaServer/novaServer.json
index 007106b61e..c7f9f0dda0 100644
--- a/catalog-be/src/main/resources/import/tosca/heat-types/novaServer/novaServer.json
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/novaServer/novaServer.json
@@ -2,11 +2,7 @@
"payloadName": "novaServer.yml",
"contactId": "jh0003",
"name": "NovaServer",
- "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.",
+ "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": [
{
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/novaServer/novaServer.yml b/catalog-be/src/main/resources/import/tosca/heat-types/novaServer/novaServer.yml
index 0ec79f5229..2271c9cd06 100644
--- a/catalog-be/src/main/resources/import/tosca/heat-types/novaServer/novaServer.yml
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/novaServer/novaServer.yml
@@ -1,75 +1,7 @@
tosca_definitions_version: tosca_simple_yaml_1_0_0
-metadata:
- template_name: NovaServerGlobalTypes
- template_version: 1.0.0
-description: Nova Server TOSCA Global Types
-imports:
- common_definitions:
- file: CommonGlobalTypesServiceTemplate.yaml
-data_types:
- org.openecomp.datatypes.heat.novaServer.network.PortExtraProperties:
- derived_from: tosca.datatypes.Root
- description: Nova server network expand properties for port
- properties:
- port_security_enabled:
- type: boolean
- description: Flag to enable/disable port security on the port
- required: false
- status: SUPPORTED
- mac_address:
- type: string
- description: MAC address to give to this port
- required: false
- status: SUPPORTED
- admin_state_up:
- type: boolean
- description: The administrative state of this port
- required: false
- default: true
- status: SUPPORTED
- qos_policy:
- type: string
- description: The name or ID of QoS policy to attach to this port
- required: false
- status: SUPPORTED
- allowed_address_pairs:
- type: list
- description: Additional MAC/IP address pairs allowed to pass through the port
- required: false
- status: SUPPORTED
- entry_schema:
- type: org.openecomp.datatypes.heat.network.AddressPair
- binding:vnic_type:
- type: string
- description: The vnic type to be bound on the neutron port
- required: false
- status: SUPPORTED
- constraints:
- - valid_values:
- - macvtap
- - direct
- - normal
- value_specs:
- type: map
- description: Extra parameters to include in the request
- required: false
- default: {
- }
- status: SUPPORTED
- entry_schema:
- type: string
- org.openecomp.datatypes.heat.novaServer.network.AddressInfo:
- derived_from: tosca.datatypes.network.NetworkInfo
- description: Network addresses with corresponding port id
- properties:
- port_id:
- type: string
- description: Port id
- required: false
- status: SUPPORTED
node_types:
org.openecomp.resource.vfc.nodes.heat.nova.Server:
- derived_from: tosca.nodes.Compute
+ derived_from: org.openecomp.resource.vfc.nodes.Compute
properties:
admin_pass:
type: string
@@ -246,4 +178,4 @@ node_types:
console_urls:
type: string
description: URLs of servers consoles
- status: SUPPORTED \ No newline at end of file
+ status: SUPPORTED
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/novaServer/novaServer.zip b/catalog-be/src/main/resources/import/tosca/heat-types/novaServer/novaServer.zip
index aafefbc6b5..54274e78f5 100644
--- a/catalog-be/src/main/resources/import/tosca/heat-types/novaServer/novaServer.zip
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/novaServer/novaServer.zip
Binary files differ
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/securityRules/securityRules.yml b/catalog-be/src/main/resources/import/tosca/heat-types/securityRules/securityRules.yml
index 29e87e15fc..876b2f1388 100644
--- a/catalog-be/src/main/resources/import/tosca/heat-types/securityRules/securityRules.yml
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/securityRules/securityRules.yml
@@ -1,11 +1,4 @@
tosca_definitions_version: tosca_simple_yaml_1_0_0
-metadata:
- template_name: NeutronSecurityRulesGlobalTypes
- template_version: 1.0.0
-description: Neutron Security Rules TOSCA Global Types
-imports:
- common_definitions:
- file: CommonGlobalTypesServiceTemplate.yaml
node_types:
org.openecomp.resource.vfc.rules.nodes.heat.network.neutron.SecurityRules:
derived_from: tosca.nodes.Root
@@ -36,7 +29,7 @@ node_types:
- port:
capability: tosca.capabilities.Attachment
node: org.openecomp.resource.cp.nodes.heat.network.neutron.Port
- relationship: corg.openecomp.relationships.AttachesTo
+ relationship: org.openecomp.relationships.AttachesTo
occurrences:
- 0
- UNBOUNDED
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/securityRules/securityRules.zip b/catalog-be/src/main/resources/import/tosca/heat-types/securityRules/securityRules.zip
index b1524a2d8f..607fe0c930 100644
--- a/catalog-be/src/main/resources/import/tosca/heat-types/securityRules/securityRules.zip
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/securityRules/securityRules.zip
Binary files differ
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/subInterface/subInterface.json b/catalog-be/src/main/resources/import/tosca/heat-types/subInterface/subInterface.json
new file mode 100644
index 0000000000..bc8391893a
--- /dev/null
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/subInterface/subInterface.json
@@ -0,0 +1,15 @@
+{
+ "payloadName": "subInterface.yml",
+ "contactId": "jh0003",
+ "name": "subInterface",
+ "description": "VLAN sub-Interface is a logical port which must be binded to a port. Regular port may have 1…N VLAN Interfaces.It can connect to its own network (regardless of the network the parent port can connect)",
+ "resourceIconPath": "network",
+ "resourceType": "CP",
+ "categories": [{
+ "name": "Generic",
+ "subcategories": [{
+ "name": "Network Elements"
+ }]
+ }],
+ "tags": ["subInterface"]
+} \ No newline at end of file
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/subInterface/subInterface.yml b/catalog-be/src/main/resources/import/tosca/heat-types/subInterface/subInterface.yml
new file mode 100644
index 0000000000..2356f82995
--- /dev/null
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/subInterface/subInterface.yml
@@ -0,0 +1,4 @@
+tosca_definitions_version: tosca_simple_yaml_1_0_0
+node_types:
+ org.openecomp.resource.cp.nodes.network.SubInterface:
+ derived_from: tosca.nodes.network.Port \ No newline at end of file
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/subInterface/subInterface.zip b/catalog-be/src/main/resources/import/tosca/heat-types/subInterface/subInterface.zip
new file mode 100644
index 0000000000..54fb2ffb80
--- /dev/null
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/subInterface/subInterface.zip
Binary files differ
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/vl/vl.zip b/catalog-be/src/main/resources/import/tosca/heat-types/vl/vl.zip
index c1889a9803..554c88d925 100644
--- a/catalog-be/src/main/resources/import/tosca/heat-types/vl/vl.zip
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/vl/vl.zip
Binary files differ
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/volume/volume.json b/catalog-be/src/main/resources/import/tosca/heat-types/volume/volume.json
new file mode 100644
index 0000000000..15293f74ca
--- /dev/null
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/volume/volume.json
@@ -0,0 +1,20 @@
+{
+ "payloadName": "volume.yml",
+ "contactId": "jh0003",
+ "name": "volume",
+ "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": [
+ "volume"
+ ]
+} \ No newline at end of file
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/volume/volume.yml b/catalog-be/src/main/resources/import/tosca/heat-types/volume/volume.yml
new file mode 100644
index 0000000000..9866979c2f
--- /dev/null
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/volume/volume.yml
@@ -0,0 +1,7 @@
+tosca_definitions_version: tosca_simple_yaml_1_0_0
+
+description: Contrail Virtual Network Global Types
+
+node_types:
+ org.openecomp.resource.vfc.nodes.volume:
+ derived_from: tosca.nodes.BlockStorage \ No newline at end of file
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/volume/volume.zip b/catalog-be/src/main/resources/import/tosca/heat-types/volume/volume.zip
new file mode 100644
index 0000000000..c5847d41df
--- /dev/null
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/volume/volume.zip
Binary files differ
diff --git a/catalog-be/src/main/resources/import/tosca/normative-types/compute/compute.json b/catalog-be/src/main/resources/import/tosca/normative-types/compute/compute.json
index 31bb27be16..5134ae4edd 100644
--- a/catalog-be/src/main/resources/import/tosca/normative-types/compute/compute.json
+++ b/catalog-be/src/main/resources/import/tosca/normative-types/compute/compute.json
@@ -2,11 +2,7 @@
"payloadName": "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.",
+ "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": [
{
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 a6c38ef9de..5ed696e4a9 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/users/importUsers.yaml b/catalog-be/src/main/resources/import/tosca/users/importUsers.yaml
index 368a2b06f3..45e931fec9 100644
--- a/catalog-be/src/main/resources/import/tosca/users/importUsers.yaml
+++ b/catalog-be/src/main/resources/import/tosca/users/importUsers.yaml
@@ -4,10 +4,10 @@ users:
firstName: Jimmy
lastName: Hendrix
role: ADMIN
- email: admin@att.com
+ email: admin@sdc.com
jh0006:
firstName: Jimmy
lastName: Hendrix
role: DESIGNER1
- email: admin@att.com
+ email: admin@sdc.com
diff --git a/catalog-be/src/main/resources/portal.properties b/catalog-be/src/main/resources/portal.properties
index 33ae0dac94..c67261f962 100644
--- a/catalog-be/src/main/resources/portal.properties
+++ b/catalog-be/src/main/resources/portal.properties
@@ -1,18 +1,18 @@
# Portal REST URL, ends "/auxapi"
-ecomp_rest_url = https://localhost/ecompportal/auxapi
+ecomp_rest_url = https://ecomp.homer.att.com/ecompportal/auxapi
# Java implementation of interface
portal.api.impl.class = org.openecomp.sdc.be.ecomp.EcompIntImpl
# CSP-SSO URL
-ecomp_redirect_url = https://localhost/ecomp_portal_ist/ecompportal/process_csp
+ecomp_redirect_url = https://www.e-access.att.com/ecomp_portal_ist/ecompportal/process_csp
# Cookie set by CSP-SSO
csp_cookie_name = attESSec
# CSP setting, most use PROD; DEV also recognized
csp_gate_keeper_prod_key = PROD
# Comma-separated list of UEB server names
-ueb_url_list =
+ueb_url_list = uebsb91kcdc.it.att.com,uebsb92kcdc.it.att.com,uebsb93kcdc.it.att.com
# UEB topic where Portal listens
ecomp_portal_inbox_name = ECOMP-PORTAL-INBOX-TEST
# UEB key generated while on-boarding
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 07eacf8d61..f65aefacf1 100644
--- a/catalog-be/src/main/resources/scripts/import/tosca/importHeatTypes.py
+++ b/catalog-be/src/main/resources/scripts/import/tosca/importHeatTypes.py
@@ -21,22 +21,34 @@ import importCommon
def importHeatTypes(beHost, bePort, adminUser, fileDir, updateversion):
- heatTypes = [ "cinderVolume",
-# "contrailVirtualNetwork",
+ heatTypes = [ "globalNetwork",
+ "globalPort",
+ "globalCompute",
+ "volume",
+ "cinderVolume",
+ "contrailVirtualNetwork",
"neutronNet",
"neutronPort",
"novaServer",
+ "extVl",
+ "internalVl",
+ "extCp",
"vl",
"eline",
"abstractSubstitute",
-# "contrailNetworkRules",
-# "contrailPort",
-# "contrailV2NetworkRules",
-# "contrailV2VirtualNetwork",
- "securityRules"
-# "contrailAbstractSubstitute",
-# "contrailCompute",
-# "contrailV2VirtualMachineInterface"
+ "Generic_VFC",
+ "Generic_VF",
+ "Generic_Service",
+ "contrailNetworkRules",
+ "contrailPort",
+ "contrailV2NetworkRules",
+ "contrailV2VirtualNetwork",
+ "securityRules",
+ "contrailAbstractSubstitute",
+ "contrailCompute",
+ "contrailV2VirtualMachineInterface",
+ "subInterface",
+ "contrailV2VLANSubInterface"
]
responseCodes = [200, 201]
diff --git a/catalog-be/src/main/resources/scripts/import/tosca/importHeatTypes1.py b/catalog-be/src/main/resources/scripts/import/tosca/importHeatTypes1.py
new file mode 100644
index 0000000000..b89a94cbb6
--- /dev/null
+++ b/catalog-be/src/main/resources/scripts/import/tosca/importHeatTypes1.py
@@ -0,0 +1,97 @@
+import pycurl
+import sys, getopt
+from StringIO import StringIO
+import json
+import copy
+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> ] #
+# #
+################################################################################################################################################
+
+def importHeatTypes1(beHost, bePort, adminUser, fileDir, updateversion):
+
+ heatTypes = ["extCp"]
+
+ responseCodes = [200, 201]
+
+ if(updateversion == 'false'):
+ responseCodes = [200, 201, 409]
+
+ results = []
+ for heatType in heatTypes:
+ result = createNormativeType(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])
+ return results
+
+
+def main(argv):
+ print 'Number of arguments:', len(sys.argv), 'arguments.'
+
+ beHost = 'localhost'
+ bePort = '8080'
+ adminUser = 'jh0003'
+ updateversion = 'true'
+
+ try:
+ opts, args = getopt.getopt(argv,"i:p:u:v:h:",["ip=","port=","user=","updateversion="])
+ except getopt.GetoptError:
+ usage()
+ errorAndExit(2, 'Invalid input')
+
+ for opt, arg in opts:
+ #print opt, arg
+ if opt == '-h':
+ usage()
+ sys.exit(3)
+ elif opt in ("-i", "--ip"):
+ beHost = arg
+ elif opt in ("-p", "--port"):
+ bePort = arg
+ elif opt in ("-u", "--user"):
+ adminUser = 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
+
+ if ( beHost == None ):
+ usage()
+ sys.exit(3)
+
+ results = importHeatTypes(beHost, bePort, adminUser, "../../../import/tosca/heat-types/", updateversion)
+
+ print "-----------------------------"
+ for result in results:
+ print "{0:20} | {1:6}".format(result[0], result[1])
+ print "-----------------------------"
+
+ responseCodes = [200, 201]
+
+ if(updateversion == 'false'):
+ responseCodes = [200, 201, 409]
+
+ failedNormatives = filter(lambda x: x[1] == None or x[1] not in responseCodes, results)
+ if (len(failedNormatives) > 0):
+ errorAndExit(1, None)
+ else:
+ errorAndExit(0, None)
+
+
+if __name__ == "__main__":
+ main(sys.argv[1:])
+
+
diff --git a/catalog-be/src/main/resources/scripts/import/tosca/importNormativeAll1.py b/catalog-be/src/main/resources/scripts/import/tosca/importNormativeAll1.py
new file mode 100644
index 0000000000..f564fc5b96
--- /dev/null
+++ b/catalog-be/src/main/resources/scripts/import/tosca/importNormativeAll1.py
@@ -0,0 +1,118 @@
+import pycurl
+import sys, getopt, os
+from StringIO import StringIO
+import json
+import copy
+import time
+#from importNormativeElements import createNormativeElement
+from importNormativeElements import *
+from importNormativeTypes import importNormativeTypes
+from importHeatTypes1 import importHeatTypes1
+from importNormativeCapabilities import importNormativeCapabilities
+from importCategoryTypes import importCategories
+from importNormativeInterfaceLifecycleTypes import importNormativeInterfaceLifecycleType
+from importDataTypes import importDataTypes
+from importGroupTypes import importGroupTypes
+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 #
+# #
+#################################################################################################################################################################################################
+
+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>]'
+
+def handleResults(results, updateversion):
+ printFrameLine()
+ for result in results:
+ printNameAndReturnCode(result[0], result[1])
+ printFrameLine()
+
+ responseCodes = [200, 201]
+
+ if(updateversion == 'false'):
+ responseCodes = [200, 201, 409]
+
+ failedResults = filter(lambda x: x[1] == None or x[1] not in responseCodes, results)
+ if (len(failedResults) > 0):
+ errorAndExit(1, None)
+
+def main(argv):
+ print 'Number of arguments:', len(sys.argv), 'arguments.'
+
+ beHost = 'localhost'
+ bePort = '8080'
+ adminUser = 'jh0003'
+ debugf = None
+ updateversion = 'true'
+ importCommon.debugFlag = False
+
+ try:
+ opts, args = getopt.getopt(argv,"i:p:u:d:v:h",["ip=","port=","user=","debug=","updateversion="])
+ except getopt.GetoptError:
+ usage()
+ errorAndExit(2, 'Invalid input')
+
+ for opt, arg in opts:
+ #print opt, arg
+ if opt == '-h':
+ usage()
+ sys.exit(3)
+ elif opt in ("-i", "--ip"):
+ beHost = arg
+ elif opt in ("-p", "--port"):
+ bePort = arg
+ elif opt in ("-u", "--user"):
+ adminUser = arg
+ elif opt in ("-d", "--debug"):
+ print arg
+ debugf = bool(arg.lower() == "true" or arg.lower() == "yes")
+ elif opt in ("-v", "--updateversion"):
+ print arg
+ if (arg.lower() == "false" or arg.lower() == "no"):
+ updateversion = 'false'
+
+ print 'be host =',beHost,', be port =', bePort,', user =', adminUser, ', debug =', debugf, ', updateversion =', updateversion
+
+ if (debugf != None):
+ print 'set debug mode to ' + str(debugf)
+ importCommon.debugFlag = debugf
+
+ if ( beHost == None ):
+ usage()
+ sys.exit(3)
+
+ print sys.argv[0]
+ pathdir = os.path.dirname(os.path.realpath(sys.argv[0]))
+ debug("path dir =" + pathdir)
+
+ baseFileLocation = pathdir + "/../../../import/tosca/"
+
+ fileLocation = baseFileLocation + "data-types/"
+ importDataTypes(beHost, bePort, adminUser, False, fileLocation)
+
+ print 'sleep until data type cache is updated'
+ time.sleep( 1 )
+
+ fileLocation = baseFileLocation + "heat-types/"
+ resultsHeat = importHeatTypes1(beHost, bePort, adminUser, fileLocation, updateversion)
+ handleResults(resultsHeat, updateversion)
+
+
+
+ errorAndExit(0, None)
+
+if __name__ == "__main__":
+ main(sys.argv[1:])
+
diff --git a/catalog-be/src/main/resources/scripts/import/tosca/importNormativeNoHeatAndNormativeTypes.py b/catalog-be/src/main/resources/scripts/import/tosca/importNormativeNoHeatAndNormativeTypes.py
new file mode 100644
index 0000000000..64a639c3c8
--- /dev/null
+++ b/catalog-be/src/main/resources/scripts/import/tosca/importNormativeNoHeatAndNormativeTypes.py
@@ -0,0 +1,135 @@
+import pycurl
+import sys, getopt, os
+from StringIO import StringIO
+import json
+import copy
+import time
+#from importNormativeElements import createNormativeElement
+from importNormativeElements import *
+from importNormativeTypes import importNormativeTypes
+from importHeatTypes import importHeatTypes
+from importNormativeCapabilities import importNormativeCapabilities
+from importCategoryTypes import importCategories
+from importNormativeInterfaceLifecycleTypes import importNormativeInterfaceLifecycleType
+from importDataTypes import importDataTypes
+from importGroupTypes import importGroupTypes
+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 #
+# #
+#################################################################################################################################################################################################
+
+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>]'
+
+def handleResults(results, updateversion):
+ printFrameLine()
+ for result in results:
+ printNameAndReturnCode(result[0], result[1])
+ printFrameLine()
+
+ responseCodes = [200, 201]
+
+ if(updateversion == 'false'):
+ responseCodes = [200, 201, 409]
+
+ failedResults = filter(lambda x: x[1] == None or x[1] not in responseCodes, results)
+ if (len(failedResults) > 0):
+ errorAndExit(1, None)
+
+def main(argv):
+ print 'Number of arguments:', len(sys.argv), 'arguments.'
+
+ beHost = 'localhost'
+ bePort = '8080'
+ adminUser = 'jh0003'
+ debugf = None
+ updateversion = 'true'
+ importCommon.debugFlag = False
+
+ try:
+ opts, args = getopt.getopt(argv,"i:p:u:d:v:h",["ip=","port=","user=","debug=","updateversion="])
+ except getopt.GetoptError:
+ usage()
+ errorAndExit(2, 'Invalid input')
+
+ for opt, arg in opts:
+ #print opt, arg
+ if opt == '-h':
+ usage()
+ sys.exit(3)
+ elif opt in ("-i", "--ip"):
+ beHost = arg
+ elif opt in ("-p", "--port"):
+ bePort = arg
+ elif opt in ("-u", "--user"):
+ adminUser = arg
+ elif opt in ("-d", "--debug"):
+ print arg
+ debugf = bool(arg.lower() == "true" or arg.lower() == "yes")
+ elif opt in ("-v", "--updateversion"):
+ print arg
+ if (arg.lower() == "false" or arg.lower() == "no"):
+ updateversion = 'false'
+
+ print 'be host =',beHost,', be port =', bePort,', user =', adminUser, ', debug =', debugf, ', updateversion =', updateversion
+
+ if (debugf != None):
+ print 'set debug mode to ' + str(debugf)
+ importCommon.debugFlag = debugf
+
+ if ( beHost == None ):
+ usage()
+ sys.exit(3)
+
+ print sys.argv[0]
+ pathdir = os.path.dirname(os.path.realpath(sys.argv[0]))
+ debug("path dir =" + pathdir)
+
+ baseFileLocation = pathdir + "/../../../import/tosca/"
+
+ fileLocation = baseFileLocation + "data-types/"
+ importDataTypes(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)
+
+ fileLocation = baseFileLocation + "interface-lifecycle-types/"
+ importNormativeInterfaceLifecycleType(beHost, bePort, adminUser, False, fileLocation)
+
+ #fileLocation = baseFileLocation + "categories/"
+ #importCategories(beHost, bePort, adminUser, False, fileLocation)
+
+ #fileLocation = baseFileLocation + "normative-types/"
+ #results = importNormativeTypes(beHost, bePort, adminUser, fileLocation, updateversion)
+ #handleResults(results, updateversion)
+
+ #fileLocation = baseFileLocation + "heat-types/"
+ #resultsHeat = importHeatTypes(beHost, bePort, adminUser, fileLocation, updateversion)
+ #handleResults(resultsHeat, updateversion)
+
+ fileLocation = baseFileLocation + "group-types/"
+ importGroupTypes(beHost, bePort, adminUser, False, fileLocation)
+
+ fileLocation = baseFileLocation + "policy-types/"
+ importPolicyTypes(beHost, bePort, adminUser, False, fileLocation)
+
+ errorAndExit(0, None)
+
+if __name__ == "__main__":
+ main(sys.argv[1:])
+
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 76bae682c0..d47c0b8073 100644
--- a/catalog-be/src/main/resources/scripts/import/tosca/importNormativeTypes.py
+++ b/catalog-be/src/main/resources/scripts/import/tosca/importNormativeTypes.py
@@ -41,7 +41,7 @@ def createNormativeType(beHost, bePort, adminUser, fileDir, ELEMENT_NAME, update
path = fileDir + ELEMENT_NAME + "/" + ELEMENT_NAME + ".zip"
debug(path)
CURRENT_JSON_FILE=fileDir + ELEMENT_NAME + "/" + ELEMENT_NAME + ".json"
- #sed -i 's/"userId": ".*",/"userId": "'${ATT_UID}'",/' ${CURRENT_JSON_FILE}
+ #sed -i 's/"userId": ".*",/"userId": "'${USER_ID}'",/' ${CURRENT_JSON_FILE}
jsonFile = open(CURRENT_JSON_FILE)
diff --git a/catalog-be/src/main/resources/scripts/import/tosca/upgradeHeatTypes1707.py b/catalog-be/src/main/resources/scripts/import/tosca/upgradeHeatTypes1707.py
new file mode 100644
index 0000000000..7c0746fb55
--- /dev/null
+++ b/catalog-be/src/main/resources/scripts/import/tosca/upgradeHeatTypes1707.py
@@ -0,0 +1,113 @@
+import pycurl
+import sys, getopt
+from StringIO import StringIO
+import json
+import copy
+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> ] #
+# #
+################################################################################################################################################
+
+def upgradeHeatTypes1707(beHost, bePort, adminUser, fileDir, updateversion):
+
+ heatTypes = [ "volume",
+ "cinderVolume",
+ "extVl",
+ "extCp",
+ "Generic_VFC",
+ "Generic_VF",
+ "Generic_Service",
+ "globalPort",
+ "globalNetwork",
+ "contrailV2VirtualMachineInterface",
+ "contrailV2VLANSubInterface",
+ "contrailPort",
+ "contrailV2VirtualNetwork",
+ "contrailVirtualNetwork",
+ "neutronNet",
+ "neutronPort",
+ ]
+
+ responseCodes = [200, 201]
+
+ if(updateversion == 'false'):
+ responseCodes = [200, 201, 409]
+
+ results = []
+ for heatType in heatTypes:
+ result = createNormativeType(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])
+ return results
+
+
+def main(argv):
+ print 'Number of arguments:', len(sys.argv), 'arguments.'
+
+ beHost = 'localhost'
+ bePort = '8080'
+ adminUser = 'jh0003'
+ updateversion = 'true'
+
+ try:
+ opts, args = getopt.getopt(argv,"i:p:u:v:h:",["ip=","port=","user=","updateversion="])
+ except getopt.GetoptError:
+ usage()
+ errorAndExit(2, 'Invalid input')
+
+ for opt, arg in opts:
+ #print opt, arg
+ if opt == '-h':
+ usage()
+ sys.exit(3)
+ elif opt in ("-i", "--ip"):
+ beHost = arg
+ elif opt in ("-p", "--port"):
+ bePort = arg
+ elif opt in ("-u", "--user"):
+ adminUser = 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
+
+ if ( beHost == None ):
+ usage()
+ sys.exit(3)
+
+ results = upgradeHeatTypes1707(beHost, bePort, adminUser, "../../../import/tosca/heat-types/", updateversion)
+
+ print "-----------------------------"
+ for result in results:
+ print "{0:20} | {1:6}".format(result[0], result[1])
+ print "-----------------------------"
+
+ responseCodes = [200, 201]
+
+ if(updateversion == 'false'):
+ responseCodes = [200, 201, 409]
+
+ failedNormatives = filter(lambda x: x[1] == None or x[1] not in responseCodes, results)
+ if (len(failedNormatives) > 0):
+ errorAndExit(1, None)
+ else:
+ errorAndExit(0, None)
+
+
+if __name__ == "__main__":
+ main(sys.argv[1:])
+
+
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 e6bb620692..488d4d739d 100644
--- a/catalog-be/src/main/resources/scripts/import/tosca/upgradeNormative.py
+++ b/catalog-be/src/main/resources/scripts/import/tosca/upgradeNormative.py
@@ -5,11 +5,9 @@ import json
import copy
import time
from importCategoryTypes import importCategories
-from importHeatTypes import importHeatTypes
-from importNormativeCapabilities import importNormativeCapabilities
+from upgradeHeatTypes1707 import upgradeHeatTypes1707
from importDataTypes import importDataTypes
-from importGroupTypes import importGroupTypes
-from importPolicyTypes import importPolicyTypes
+
from importCommon import *
import importCommon
@@ -46,7 +44,7 @@ def main(argv):
bePort = '8080'
adminUser = 'jh0003'
debugf = None
- updateversion = 'false'
+ updateversion = 'true'
importCommon.debugFlag = False
try:
@@ -94,17 +92,9 @@ def main(argv):
print 'sleep until data type cache is updated'
time.sleep( 70 )
- fileLocation = baseFileLocation + "capability-types/"
- importNormativeCapabilities(beHost, bePort, adminUser, False, fileLocation)
-
- fileLocation = baseFileLocation + "group-types/"
- importGroupTypes(beHost, bePort, adminUser, False, fileLocation)
-
- fileLocation = baseFileLocation + "policy-types/"
- importPolicyTypes(beHost, bePort, adminUser, False, fileLocation)
fileLocation = baseFileLocation + "heat-types/"
- resultsHeat = importHeatTypes(beHost, bePort, adminUser, fileLocation, updateversion)
+ resultsHeat = upgradeHeatTypes1707(beHost, bePort, adminUser, fileLocation, 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 0f70174173..8f8e0491ae 100644
--- a/catalog-be/src/main/resources/scripts/import/tosca/upgradeNormativeVersion.py
+++ b/catalog-be/src/main/resources/scripts/import/tosca/upgradeNormativeVersion.py
@@ -83,56 +83,20 @@ def main(argv):
##########################################################################
- #---------------------------------for release 1610---------------------- #
+ #---------------------------------for release 1702---------------------- #
##########################################################################
- fileLocation = baseFileLocation + "normative-types/"
- result = createNormativeType(beHost, bePort, adminUser, fileLocation, "compute", updateversion)
- results.append(result)
-
- fileLocation = baseFileLocation + "normative-types/"
- result = createNormativeType(beHost, bePort, adminUser, fileLocation, "network", updateversion)
- results.append(result)
-
- fileLocation = baseFileLocation + "heat-types/"
- result = createNormativeType(beHost, bePort, adminUser, fileLocation, "abstractSubstitute", updateversion)
- results.append(result)
-
- fileLocation = baseFileLocation + "heat-types/"
- result = createNormativeType(beHost, bePort, adminUser, fileLocation, "contrailAbstractSubstitute", updateversion)
- results.append(result)
-
- fileLocation = baseFileLocation + "heat-types/"
- result = createNormativeType(beHost, bePort, adminUser, fileLocation, "contrailNetworkRules", updateversion)
- results.append(result)
-
fileLocation = baseFileLocation + "heat-types/"
- result = createNormativeType(beHost, bePort, adminUser, fileLocation, "novaServer", updateversion)
+ result = createNormativeType(beHost, bePort, adminUser, fileLocation, "contrailV2VirtualMachineInterface", updateversion)
results.append(result)
-
+
fileLocation = baseFileLocation + "heat-types/"
result = createNormativeType(beHost, bePort, adminUser, fileLocation, "neutronPort", updateversion)
results.append(result)
- fileLocation = baseFileLocation + "heat-types/"
- result = createNormativeType(beHost, bePort, adminUser, fileLocation, "contrailVirtualNetwork", updateversion)
- results.append(result)
- fileLocation = baseFileLocation + "heat-types/"
- result = createNormativeType(beHost, bePort, adminUser, fileLocation, "neutronNet", updateversion)
- results.append(result)
- fileLocation = baseFileLocation + "heat-types/"
- result = createNormativeType(beHost, bePort, adminUser, fileLocation, "vl", updateversion)
- results.append(result)
-
- fileLocation = baseFileLocation + "heat-types/"
- result = createNormativeType(beHost, bePort, adminUser, fileLocation, "contrailV2VirtualNetwork", updateversion)
- results.append(result)
- fileLocation = baseFileLocation + "heat-types/"
- result = createNormativeType(beHost, bePort, adminUser, fileLocation, "securityRules", updateversion)
- results.append(result)
handleResults(results, 'false')
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
new file mode 100644
index 0000000000..13e5d7d63a
--- /dev/null
+++ b/catalog-be/src/main/resources/scripts/import/tosca/upgradeNormativeVersionProd1702_3537.py
@@ -0,0 +1,129 @@
+import pycurl
+import sys, getopt, os
+from StringIO import StringIO
+import json
+import copy
+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 #
+# #
+#################################################################################################################################################################################################
+
+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>]'
+
+def handleResults(results, updateversion):
+ printFrameLine()
+ for result in results:
+ printNameAndReturnCode(result[0], result[1])
+ printFrameLine()
+
+ failedResults = filter(lambda x: x[1] == None or x[1] not in [200, 201, 409], results)
+ if (len(failedResults) > 0):
+ errorAndExit(1, None)
+
+def main(argv):
+ print 'Number of arguments:', len(sys.argv), 'arguments.'
+
+ beHost = 'localhost'
+ bePort = '8080'
+ adminUser = 'jh0003'
+ debugf = None
+ updateversion = 'true'
+ importCommon.debugFlag = False
+
+ try:
+ opts, args = getopt.getopt(argv,"i:p:u:d:h",["ip=","port=","user=","debug="])
+ except getopt.GetoptError:
+ usage()
+ errorAndExit(2, 'Invalid input')
+
+ for opt, arg in opts:
+ #print opt, arg
+ if opt == '-h':
+ usage()
+ sys.exit(3)
+ elif opt in ("-i", "--ip"):
+ beHost = arg
+ elif opt in ("-p", "--port"):
+ bePort = arg
+ elif opt in ("-u", "--user"):
+ adminUser = 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
+
+ if (debugf != None):
+ print 'set debug mode to ' + str(debugf)
+ importCommon.debugFlag = debugf
+
+ if ( beHost == None ):
+ usage()
+ sys.exit(3)
+
+ print sys.argv[0]
+ pathdir = os.path.dirname(os.path.realpath(sys.argv[0]))
+ debug("path dir =" + pathdir)
+
+ baseFileLocation = pathdir + "/../../../import/tosca/"
+ results = []
+
+
+ ##########################################################################
+ #---------------------------------for release 1702---------------------- #
+ ##########################################################################
+
+
+ fileLocation = baseFileLocation + "heat-types/"
+ result = createNormativeType(beHost, bePort, adminUser, fileLocation, "contrailPort", updateversion)
+ results.append(result)
+
+ fileLocation = baseFileLocation + "heat-types/"
+ result = createNormativeType(beHost, bePort, adminUser, fileLocation, "contrailV2VirtualMachineInterface", updateversion)
+ results.append(result)
+
+ fileLocation = baseFileLocation + "heat-types/"
+ result = createNormativeType(beHost, bePort, adminUser, fileLocation, "neutronPort", updateversion)
+ results.append(result)
+
+ fileLocation = baseFileLocation + "heat-types/"
+ result = createNormativeType(beHost, bePort, adminUser, fileLocation, "contrailCompute", updateversion)
+ results.append(result)
+
+ fileLocation = baseFileLocation + "heat-types/"
+ result = createNormativeType(beHost, bePort, adminUser, fileLocation, "novaServer", updateversion)
+ results.append(result)
+
+ fileLocation = baseFileLocation + "heat-types/"
+ result = createNormativeType(beHost, bePort, adminUser, fileLocation, "contrailV2VirtualNetwork", updateversion)
+ results.append(result)
+
+ fileLocation = baseFileLocation + "heat-types/"
+ result = createNormativeType(beHost, bePort, adminUser, fileLocation, "contrailVirtualNetwork", updateversion)
+ results.append(result)
+
+ fileLocation = baseFileLocation + "heat-types/"
+ result = createNormativeType(beHost, bePort, adminUser, fileLocation, "neutronNet", updateversion)
+ results.append(result)
+
+
+ handleResults(results, 'false')
+
+ errorAndExit(0, None)
+
+if __name__ == "__main__":
+ main(sys.argv[1:])
+
diff --git a/catalog-be/src/main/resources/swagger/lib/backbone-min.js b/catalog-be/src/main/resources/swagger/lib/backbone-min.js
index f082fcffca..a3f544be6d 100644
--- a/catalog-be/src/main/resources/swagger/lib/backbone-min.js
+++ b/catalog-be/src/main/resources/swagger/lib/backbone-min.js
@@ -1,23 +1,3 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
// Backbone.js 1.1.2
(function(t,e){if(typeof define==="function"&&define.amd){define(["underscore","jquery","exports"],function(i,r,s){t.Backbone=e(t,s,i,r)})}else if(typeof exports!=="undefined"){var i=require("underscore");e(t,exports,i)}else{t.Backbone=e(t,{},t._,t.jQuery||t.Zepto||t.ender||t.$)}})(this,function(t,e,i,r){var s=t.Backbone;var n=[];var a=n.push;var o=n.slice;var h=n.splice;e.VERSION="1.1.2";e.$=r;e.noConflict=function(){t.Backbone=s;return this};e.emulateHTTP=false;e.emulateJSON=false;var u=e.Events={on:function(t,e,i){if(!c(this,"on",t,[e,i])||!e)return this;this._events||(this._events={});var r=this._events[t]||(this._events[t]=[]);r.push({callback:e,context:i,ctx:i||this});return this},once:function(t,e,r){if(!c(this,"once",t,[e,r])||!e)return this;var s=this;var n=i.once(function(){s.off(t,n);e.apply(this,arguments)});n._callback=e;return this.on(t,n,r)},off:function(t,e,r){var s,n,a,o,h,u,l,f;if(!this._events||!c(this,"off",t,[e,r]))return this;if(!t&&!e&&!r){this._events=void 0;return this}o=t?[t]:i.keys(this._events);for(h=0,u=o.length;h<u;h++){t=o[h];if(a=this._events[t]){this._events[t]=s=[];if(e||r){for(l=0,f=a.length;l<f;l++){n=a[l];if(e&&e!==n.callback&&e!==n.callback._callback||r&&r!==n.context){s.push(n)}}}if(!s.length)delete this._events[t]}}return this},trigger:function(t){if(!this._events)return this;var e=o.call(arguments,1);if(!c(this,"trigger",t,e))return this;var i=this._events[t];var r=this._events.all;if(i)f(i,e);if(r)f(r,arguments);return this},stopListening:function(t,e,r){var s=this._listeningTo;if(!s)return this;var n=!e&&!r;if(!r&&typeof e==="object")r=this;if(t)(s={})[t._listenId]=t;for(var a in s){t=s[a];t.off(e,r,this);if(n||i.isEmpty(t._events))delete this._listeningTo[a]}return this}};var l=/\s+/;var c=function(t,e,i,r){if(!i)return true;if(typeof i==="object"){for(var s in i){t[e].apply(t,[s,i[s]].concat(r))}return false}if(l.test(i)){var n=i.split(l);for(var a=0,o=n.length;a<o;a++){t[e].apply(t,[n[a]].concat(r))}return false}return true};var f=function(t,e){var i,r=-1,s=t.length,n=e[0],a=e[1],o=e[2];switch(e.length){case 0:while(++r<s)(i=t[r]).callback.call(i.ctx);return;case 1:while(++r<s)(i=t[r]).callback.call(i.ctx,n);return;case 2:while(++r<s)(i=t[r]).callback.call(i.ctx,n,a);return;case 3:while(++r<s)(i=t[r]).callback.call(i.ctx,n,a,o);return;default:while(++r<s)(i=t[r]).callback.apply(i.ctx,e);return}};var d={listenTo:"on",listenToOnce:"once"};i.each(d,function(t,e){u[e]=function(e,r,s){var n=this._listeningTo||(this._listeningTo={});var a=e._listenId||(e._listenId=i.uniqueId("l"));n[a]=e;if(!s&&typeof r==="object")s=this;e[t](r,s,this);return this}});u.bind=u.on;u.unbind=u.off;i.extend(e,u);var p=e.Model=function(t,e){var r=t||{};e||(e={});this.cid=i.uniqueId("c");this.attributes={};if(e.collection)this.collection=e.collection;if(e.parse)r=this.parse(r,e)||{};r=i.defaults({},r,i.result(this,"defaults"));this.set(r,e);this.changed={};this.initialize.apply(this,arguments)};i.extend(p.prototype,u,{changed:null,validationError:null,idAttribute:"id",initialize:function(){},toJSON:function(t){return i.clone(this.attributes)},sync:function(){return e.sync.apply(this,arguments)},get:function(t){return this.attributes[t]},escape:function(t){return i.escape(this.get(t))},has:function(t){return this.get(t)!=null},set:function(t,e,r){var s,n,a,o,h,u,l,c;if(t==null)return this;if(typeof t==="object"){n=t;r=e}else{(n={})[t]=e}r||(r={});if(!this._validate(n,r))return false;a=r.unset;h=r.silent;o=[];u=this._changing;this._changing=true;if(!u){this._previousAttributes=i.clone(this.attributes);this.changed={}}c=this.attributes,l=this._previousAttributes;if(this.idAttribute in n)this.id=n[this.idAttribute];for(s in n){e=n[s];if(!i.isEqual(c[s],e))o.push(s);if(!i.isEqual(l[s],e)){this.changed[s]=e}else{delete this.changed[s]}a?delete c[s]:c[s]=e}if(!h){if(o.length)this._pending=r;for(var f=0,d=o.length;f<d;f++){this.trigger("change:"+o[f],this,c[o[f]],r)}}if(u)return this;if(!h){while(this._pending){r=this._pending;this._pending=false;this.trigger("change",this,r)}}this._pending=false;this._changing=false;return this},unset:function(t,e){return this.set(t,void 0,i.extend({},e,{unset:true}))},clear:function(t){var e={};for(var r in this.attributes)e[r]=void 0;return this.set(e,i.extend({},t,{unset:true}))},hasChanged:function(t){if(t==null)return!i.isEmpty(this.changed);return i.has(this.changed,t)},changedAttributes:function(t){if(!t)return this.hasChanged()?i.clone(this.changed):false;var e,r=false;var s=this._changing?this._previousAttributes:this.attributes;for(var n in t){if(i.isEqual(s[n],e=t[n]))continue;(r||(r={}))[n]=e}return r},previous:function(t){if(t==null||!this._previousAttributes)return null;return this._previousAttributes[t]},previousAttributes:function(){return i.clone(this._previousAttributes)},fetch:function(t){t=t?i.clone(t):{};if(t.parse===void 0)t.parse=true;var e=this;var r=t.success;t.success=function(i){if(!e.set(e.parse(i,t),t))return false;if(r)r(e,i,t);e.trigger("sync",e,i,t)};q(this,t);return this.sync("read",this,t)},save:function(t,e,r){var s,n,a,o=this.attributes;if(t==null||typeof t==="object"){s=t;r=e}else{(s={})[t]=e}r=i.extend({validate:true},r);if(s&&!r.wait){if(!this.set(s,r))return false}else{if(!this._validate(s,r))return false}if(s&&r.wait){this.attributes=i.extend({},o,s)}if(r.parse===void 0)r.parse=true;var h=this;var u=r.success;r.success=function(t){h.attributes=o;var e=h.parse(t,r);if(r.wait)e=i.extend(s||{},e);if(i.isObject(e)&&!h.set(e,r)){return false}if(u)u(h,t,r);h.trigger("sync",h,t,r)};q(this,r);n=this.isNew()?"create":r.patch?"patch":"update";if(n==="patch")r.attrs=s;a=this.sync(n,this,r);if(s&&r.wait)this.attributes=o;return a},destroy:function(t){t=t?i.clone(t):{};var e=this;var r=t.success;var s=function(){e.trigger("destroy",e,e.collection,t)};t.success=function(i){if(t.wait||e.isNew())s();if(r)r(e,i,t);if(!e.isNew())e.trigger("sync",e,i,t)};if(this.isNew()){t.success();return false}q(this,t);var n=this.sync("delete",this,t);if(!t.wait)s();return n},url:function(){var t=i.result(this,"urlRoot")||i.result(this.collection,"url")||M();if(this.isNew())return t;return t.replace(/([^\/])$/,"$1/")+encodeURIComponent(this.id)},parse:function(t,e){return t},clone:function(){return new this.constructor(this.attributes)},isNew:function(){return!this.has(this.idAttribute)},isValid:function(t){return this._validate({},i.extend(t||{},{validate:true}))},_validate:function(t,e){if(!e.validate||!this.validate)return true;t=i.extend({},this.attributes,t);var r=this.validationError=this.validate(t,e)||null;if(!r)return true;this.trigger("invalid",this,r,i.extend(e,{validationError:r}));return false}});var v=["keys","values","pairs","invert","pick","omit"];i.each(v,function(t){p.prototype[t]=function(){var e=o.call(arguments);e.unshift(this.attributes);return i[t].apply(i,e)}});var g=e.Collection=function(t,e){e||(e={});if(e.model)this.model=e.model;if(e.comparator!==void 0)this.comparator=e.comparator;this._reset();this.initialize.apply(this,arguments);if(t)this.reset(t,i.extend({silent:true},e))};var m={add:true,remove:true,merge:true};var y={add:true,remove:false};i.extend(g.prototype,u,{model:p,initialize:function(){},toJSON:function(t){return this.map(function(e){return e.toJSON(t)})},sync:function(){return e.sync.apply(this,arguments)},add:function(t,e){return this.set(t,i.extend({merge:false},e,y))},remove:function(t,e){var r=!i.isArray(t);t=r?[t]:i.clone(t);e||(e={});var s,n,a,o;for(s=0,n=t.length;s<n;s++){o=t[s]=this.get(t[s]);if(!o)continue;delete this._byId[o.id];delete this._byId[o.cid];a=this.indexOf(o);this.models.splice(a,1);this.length--;if(!e.silent){e.index=a;o.trigger("remove",o,this,e)}this._removeReference(o,e)}return r?t[0]:t},set:function(t,e){e=i.defaults({},e,m);if(e.parse)t=this.parse(t,e);var r=!i.isArray(t);t=r?t?[t]:[]:i.clone(t);var s,n,a,o,h,u,l;var c=e.at;var f=this.model;var d=this.comparator&&c==null&&e.sort!==false;var v=i.isString(this.comparator)?this.comparator:null;var g=[],y=[],_={};var b=e.add,w=e.merge,x=e.remove;var E=!d&&b&&x?[]:false;for(s=0,n=t.length;s<n;s++){h=t[s]||{};if(h instanceof p){a=o=h}else{a=h[f.prototype.idAttribute||"id"]}if(u=this.get(a)){if(x)_[u.cid]=true;if(w){h=h===o?o.attributes:h;if(e.parse)h=u.parse(h,e);u.set(h,e);if(d&&!l&&u.hasChanged(v))l=true}t[s]=u}else if(b){o=t[s]=this._prepareModel(h,e);if(!o)continue;g.push(o);this._addReference(o,e)}o=u||o;if(E&&(o.isNew()||!_[o.id]))E.push(o);_[o.id]=true}if(x){for(s=0,n=this.length;s<n;++s){if(!_[(o=this.models[s]).cid])y.push(o)}if(y.length)this.remove(y,e)}if(g.length||E&&E.length){if(d)l=true;this.length+=g.length;if(c!=null){for(s=0,n=g.length;s<n;s++){this.models.splice(c+s,0,g[s])}}else{if(E)this.models.length=0;var k=E||g;for(s=0,n=k.length;s<n;s++){this.models.push(k[s])}}}if(l)this.sort({silent:true});if(!e.silent){for(s=0,n=g.length;s<n;s++){(o=g[s]).trigger("add",o,this,e)}if(l||E&&E.length)this.trigger("sort",this,e)}return r?t[0]:t},reset:function(t,e){e||(e={});for(var r=0,s=this.models.length;r<s;r++){this._removeReference(this.models[r],e)}e.previousModels=this.models;this._reset();t=this.add(t,i.extend({silent:true},e));if(!e.silent)this.trigger("reset",this,e);return t},push:function(t,e){return this.add(t,i.extend({at:this.length},e))},pop:function(t){var e=this.at(this.length-1);this.remove(e,t);return e},unshift:function(t,e){return this.add(t,i.extend({at:0},e))},shift:function(t){var e=this.at(0);this.remove(e,t);return e},slice:function(){return o.apply(this.models,arguments)},get:function(t){if(t==null)return void 0;return this._byId[t]||this._byId[t.id]||this._byId[t.cid]},at:function(t){return this.models[t]},where:function(t,e){if(i.isEmpty(t))return e?void 0:[];return this[e?"find":"filter"](function(e){for(var i in t){if(t[i]!==e.get(i))return false}return true})},findWhere:function(t){return this.where(t,true)},sort:function(t){if(!this.comparator)throw new Error("Cannot sort a set without a comparator");t||(t={});if(i.isString(this.comparator)||this.comparator.length===1){this.models=this.sortBy(this.comparator,this)}else{this.models.sort(i.bind(this.comparator,this))}if(!t.silent)this.trigger("sort",this,t);return this},pluck:function(t){return i.invoke(this.models,"get",t)},fetch:function(t){t=t?i.clone(t):{};if(t.parse===void 0)t.parse=true;var e=t.success;var r=this;t.success=function(i){var s=t.reset?"reset":"set";r[s](i,t);if(e)e(r,i,t);r.trigger("sync",r,i,t)};q(this,t);return this.sync("read",this,t)},create:function(t,e){e=e?i.clone(e):{};if(!(t=this._prepareModel(t,e)))return false;if(!e.wait)this.add(t,e);var r=this;var s=e.success;e.success=function(t,i){if(e.wait)r.add(t,e);if(s)s(t,i,e)};t.save(null,e);return t},parse:function(t,e){return t},clone:function(){return new this.constructor(this.models)},_reset:function(){this.length=0;this.models=[];this._byId={}},_prepareModel:function(t,e){if(t instanceof p)return t;e=e?i.clone(e):{};e.collection=this;var r=new this.model(t,e);if(!r.validationError)return r;this.trigger("invalid",this,r.validationError,e);return false},_addReference:function(t,e){this._byId[t.cid]=t;if(t.id!=null)this._byId[t.id]=t;if(!t.collection)t.collection=this;t.on("all",this._onModelEvent,this)},_removeReference:function(t,e){if(this===t.collection)delete t.collection;t.off("all",this._onModelEvent,this)},_onModelEvent:function(t,e,i,r){if((t==="add"||t==="remove")&&i!==this)return;if(t==="destroy")this.remove(e,r);if(e&&t==="change:"+e.idAttribute){delete this._byId[e.previous(e.idAttribute)];if(e.id!=null)this._byId[e.id]=e}this.trigger.apply(this,arguments)}});var _=["forEach","each","map","collect","reduce","foldl","inject","reduceRight","foldr","find","detect","filter","select","reject","every","all","some","any","include","contains","invoke","max","min","toArray","size","first","head","take","initial","rest","tail","drop","last","without","difference","indexOf","shuffle","lastIndexOf","isEmpty","chain","sample"];i.each(_,function(t){g.prototype[t]=function(){var e=o.call(arguments);e.unshift(this.models);return i[t].apply(i,e)}});var b=["groupBy","countBy","sortBy","indexBy"];i.each(b,function(t){g.prototype[t]=function(e,r){var s=i.isFunction(e)?e:function(t){return t.get(e)};return i[t](this.models,s,r)}});var w=e.View=function(t){this.cid=i.uniqueId("view");t||(t={});i.extend(this,i.pick(t,E));this._ensureElement();this.initialize.apply(this,arguments);this.delegateEvents()};var x=/^(\S+)\s*(.*)$/;var E=["model","collection","el","id","attributes","className","tagName","events"];i.extend(w.prototype,u,{tagName:"div",$:function(t){return this.$el.find(t)},initialize:function(){},render:function(){return this},remove:function(){this.$el.remove();this.stopListening();return this},setElement:function(t,i){if(this.$el)this.undelegateEvents();this.$el=t instanceof e.$?t:e.$(t);this.el=this.$el[0];if(i!==false)this.delegateEvents();return this},delegateEvents:function(t){if(!(t||(t=i.result(this,"events"))))return this;this.undelegateEvents();for(var e in t){var r=t[e];if(!i.isFunction(r))r=this[t[e]];if(!r)continue;var s=e.match(x);var n=s[1],a=s[2];r=i.bind(r,this);n+=".delegateEvents"+this.cid;if(a===""){this.$el.on(n,r)}else{this.$el.on(n,a,r)}}return this},undelegateEvents:function(){this.$el.off(".delegateEvents"+this.cid);return this},_ensureElement:function(){if(!this.el){var t=i.extend({},i.result(this,"attributes"));if(this.id)t.id=i.result(this,"id");if(this.className)t["class"]=i.result(this,"className");var r=e.$("<"+i.result(this,"tagName")+">").attr(t);this.setElement(r,false)}else{this.setElement(i.result(this,"el"),false)}}});e.sync=function(t,r,s){var n=T[t];i.defaults(s||(s={}),{emulateHTTP:e.emulateHTTP,emulateJSON:e.emulateJSON});var a={type:n,dataType:"json"};if(!s.url){a.url=i.result(r,"url")||M()}if(s.data==null&&r&&(t==="create"||t==="update"||t==="patch")){a.contentType="application/json";a.data=JSON.stringify(s.attrs||r.toJSON(s))}if(s.emulateJSON){a.contentType="application/x-www-form-urlencoded";a.data=a.data?{model:a.data}:{}}if(s.emulateHTTP&&(n==="PUT"||n==="DELETE"||n==="PATCH")){a.type="POST";if(s.emulateJSON)a.data._method=n;var o=s.beforeSend;s.beforeSend=function(t){t.setRequestHeader("X-HTTP-Method-Override",n);if(o)return o.apply(this,arguments)}}if(a.type!=="GET"&&!s.emulateJSON){a.processData=false}if(a.type==="PATCH"&&k){a.xhr=function(){return new ActiveXObject("Microsoft.XMLHTTP")}}var h=s.xhr=e.ajax(i.extend(a,s));r.trigger("request",r,h,s);return h};var k=typeof window!=="undefined"&&!!window.ActiveXObject&&!(window.XMLHttpRequest&&(new XMLHttpRequest).dispatchEvent);var T={create:"POST",update:"PUT",patch:"PATCH","delete":"DELETE",read:"GET"};e.ajax=function(){return e.$.ajax.apply(e.$,arguments)};var $=e.Router=function(t){t||(t={});if(t.routes)this.routes=t.routes;this._bindRoutes();this.initialize.apply(this,arguments)};var S=/\((.*?)\)/g;var H=/(\(\?)?:\w+/g;var A=/\*\w+/g;var I=/[\-{}\[\]+?.,\\\^$|#\s]/g;i.extend($.prototype,u,{initialize:function(){},route:function(t,r,s){if(!i.isRegExp(t))t=this._routeToRegExp(t);if(i.isFunction(r)){s=r;r=""}if(!s)s=this[r];var n=this;e.history.route(t,function(i){var a=n._extractParameters(t,i);n.execute(s,a);n.trigger.apply(n,["route:"+r].concat(a));n.trigger("route",r,a);e.history.trigger("route",n,r,a)});return this},execute:function(t,e){if(t)t.apply(this,e)},navigate:function(t,i){e.history.navigate(t,i);return this},_bindRoutes:function(){if(!this.routes)return;this.routes=i.result(this,"routes");var t,e=i.keys(this.routes);while((t=e.pop())!=null){this.route(t,this.routes[t])}},_routeToRegExp:function(t){t=t.replace(I,"\\$&").replace(S,"(?:$1)?").replace(H,function(t,e){return e?t:"([^/?]+)"}).replace(A,"([^?]*?)");return new RegExp("^"+t+"(?:\\?([\\s\\S]*))?$")},_extractParameters:function(t,e){var r=t.exec(e).slice(1);return i.map(r,function(t,e){if(e===r.length-1)return t||null;return t?decodeURIComponent(t):null})}});var N=e.History=function(){this.handlers=[];i.bindAll(this,"checkUrl");if(typeof window!=="undefined"){this.location=window.location;this.history=window.history}};var R=/^[#\/]|\s+$/g;var O=/^\/+|\/+$/g;var P=/msie [\w.]+/;var C=/\/$/;var j=/#.*$/;N.started=false;i.extend(N.prototype,u,{interval:50,atRoot:function(){return this.location.pathname.replace(/[^\/]$/,"$&/")===this.root},getHash:function(t){var e=(t||this).location.href.match(/#(.*)$/);return e?e[1]:""},getFragment:function(t,e){if(t==null){if(this._hasPushState||!this._wantsHashChange||e){t=decodeURI(this.location.pathname+this.location.search);var i=this.root.replace(C,"");if(!t.indexOf(i))t=t.slice(i.length)}else{t=this.getHash()}}return t.replace(R,"")},start:function(t){if(N.started)throw new Error("Backbone.history has already been started");N.started=true;this.options=i.extend({root:"/"},this.options,t);this.root=this.options.root;this._wantsHashChange=this.options.hashChange!==false;this._wantsPushState=!!this.options.pushState;this._hasPushState=!!(this.options.pushState&&this.history&&this.history.pushState);var r=this.getFragment();var s=document.documentMode;var n=P.exec(navigator.userAgent.toLowerCase())&&(!s||s<=7);this.root=("/"+this.root+"/").replace(O,"/");if(n&&this._wantsHashChange){var a=e.$('<iframe src="javascript:0" tabindex="-1">');this.iframe=a.hide().appendTo("body")[0].contentWindow;this.navigate(r)}if(this._hasPushState){e.$(window).on("popstate",this.checkUrl)}else if(this._wantsHashChange&&"onhashchange"in window&&!n){e.$(window).on("hashchange",this.checkUrl)}else if(this._wantsHashChange){this._checkUrlInterval=setInterval(this.checkUrl,this.interval)}this.fragment=r;var o=this.location;if(this._wantsHashChange&&this._wantsPushState){if(!this._hasPushState&&!this.atRoot()){this.fragment=this.getFragment(null,true);this.location.replace(this.root+"#"+this.fragment);return true}else if(this._hasPushState&&this.atRoot()&&o.hash){this.fragment=this.getHash().replace(R,"");this.history.replaceState({},document.title,this.root+this.fragment)}}if(!this.options.silent)return this.loadUrl()},stop:function(){e.$(window).off("popstate",this.checkUrl).off("hashchange",this.checkUrl);if(this._checkUrlInterval)clearInterval(this._checkUrlInterval);N.started=false},route:function(t,e){this.handlers.unshift({route:t,callback:e})},checkUrl:function(t){var e=this.getFragment();if(e===this.fragment&&this.iframe){e=this.getFragment(this.getHash(this.iframe))}if(e===this.fragment)return false;if(this.iframe)this.navigate(e);this.loadUrl()},loadUrl:function(t){t=this.fragment=this.getFragment(t);return i.any(this.handlers,function(e){if(e.route.test(t)){e.callback(t);return true}})},navigate:function(t,e){if(!N.started)return false;if(!e||e===true)e={trigger:!!e};var i=this.root+(t=this.getFragment(t||""));t=t.replace(j,"");if(this.fragment===t)return;this.fragment=t;if(t===""&&i!=="/")i=i.slice(0,-1);if(this._hasPushState){this.history[e.replace?"replaceState":"pushState"]({},document.title,i)}else if(this._wantsHashChange){this._updateHash(this.location,t,e.replace);if(this.iframe&&t!==this.getFragment(this.getHash(this.iframe))){if(!e.replace)this.iframe.document.open().close();this._updateHash(this.iframe.location,t,e.replace)}}else{return this.location.assign(i)}if(e.trigger)return this.loadUrl(t)},_updateHash:function(t,e,i){if(i){var r=t.href.replace(/(javascript:|#).*$/,"");t.replace(r+"#"+e)}else{t.hash="#"+e}}});e.history=new N;var U=function(t,e){var r=this;var s;if(t&&i.has(t,"constructor")){s=t.constructor}else{s=function(){return r.apply(this,arguments)}}i.extend(s,r,e);var n=function(){this.constructor=s};n.prototype=r.prototype;s.prototype=new n;if(t)i.extend(s.prototype,t);s.__super__=r.prototype;return s};p.extend=g.extend=$.extend=w.extend=N.extend=U;var M=function(){throw new Error('A "url" property or function must be specified')};var q=function(t,e){var i=e.error;e.error=function(r){if(i)i(t,r,e);t.trigger("error",t,r,e)}};return e});
@@ -32,4 +12,4 @@ Backbone.View = (function(View) {
View.apply(this, arguments);
}
});
-})(Backbone.View);
+})(Backbone.View); \ No newline at end of file
diff --git a/catalog-be/src/main/resources/swagger/lib/handlebars-2.0.0.js b/catalog-be/src/main/resources/swagger/lib/handlebars-2.0.0.js
index 0abd7a6149..53cf921d4f 100644
--- a/catalog-be/src/main/resources/swagger/lib/handlebars-2.0.0.js
+++ b/catalog-be/src/main/resources/swagger/lib/handlebars-2.0.0.js
@@ -1,23 +1,3 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
/*!
handlebars v2.0.0
@@ -45,4 +25,4 @@ THE SOFTWARE.
@license
*/
!function(a,b){"function"==typeof define&&define.amd?define([],b):"object"==typeof exports?module.exports=b():a.Handlebars=a.Handlebars||b()}(this,function(){var a=function(){"use strict";function a(a){this.string=a}var b;return a.prototype.toString=function(){return""+this.string},b=a}(),b=function(a){"use strict";function b(a){return i[a]}function c(a){for(var b=1;b<arguments.length;b++)for(var c in arguments[b])Object.prototype.hasOwnProperty.call(arguments[b],c)&&(a[c]=arguments[b][c]);return a}function d(a){return a instanceof h?a.toString():null==a?"":a?(a=""+a,k.test(a)?a.replace(j,b):a):a+""}function e(a){return a||0===a?n(a)&&0===a.length?!0:!1:!0}function f(a,b){return(a?a+".":"")+b}var g={},h=a,i={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","`":"&#x60;"},j=/[&<>"'`]/g,k=/[&<>"'`]/;g.extend=c;var l=Object.prototype.toString;g.toString=l;var m=function(a){return"function"==typeof a};m(/x/)&&(m=function(a){return"function"==typeof a&&"[object Function]"===l.call(a)});var m;g.isFunction=m;var n=Array.isArray||function(a){return a&&"object"==typeof a?"[object Array]"===l.call(a):!1};return g.isArray=n,g.escapeExpression=d,g.isEmpty=e,g.appendContextPath=f,g}(a),c=function(){"use strict";function a(a,b){var d;b&&b.firstLine&&(d=b.firstLine,a+=" - "+d+":"+b.firstColumn);for(var e=Error.prototype.constructor.call(this,a),f=0;f<c.length;f++)this[c[f]]=e[c[f]];d&&(this.lineNumber=d,this.column=b.firstColumn)}var b,c=["description","fileName","lineNumber","message","name","number","stack"];return a.prototype=new Error,b=a}(),d=function(a,b){"use strict";function c(a,b){this.helpers=a||{},this.partials=b||{},d(this)}function d(a){a.registerHelper("helperMissing",function(){if(1===arguments.length)return void 0;throw new g("Missing helper: '"+arguments[arguments.length-1].name+"'")}),a.registerHelper("blockHelperMissing",function(b,c){var d=c.inverse,e=c.fn;if(b===!0)return e(this);if(b===!1||null==b)return d(this);if(k(b))return b.length>0?(c.ids&&(c.ids=[c.name]),a.helpers.each(b,c)):d(this);if(c.data&&c.ids){var g=q(c.data);g.contextPath=f.appendContextPath(c.data.contextPath,c.name),c={data:g}}return e(b,c)}),a.registerHelper("each",function(a,b){if(!b)throw new g("Must pass iterator to #each");var c,d,e=b.fn,h=b.inverse,i=0,j="";if(b.data&&b.ids&&(d=f.appendContextPath(b.data.contextPath,b.ids[0])+"."),l(a)&&(a=a.call(this)),b.data&&(c=q(b.data)),a&&"object"==typeof a)if(k(a))for(var m=a.length;m>i;i++)c&&(c.index=i,c.first=0===i,c.last=i===a.length-1,d&&(c.contextPath=d+i)),j+=e(a[i],{data:c});else for(var n in a)a.hasOwnProperty(n)&&(c&&(c.key=n,c.index=i,c.first=0===i,d&&(c.contextPath=d+n)),j+=e(a[n],{data:c}),i++);return 0===i&&(j=h(this)),j}),a.registerHelper("if",function(a,b){return l(a)&&(a=a.call(this)),!b.hash.includeZero&&!a||f.isEmpty(a)?b.inverse(this):b.fn(this)}),a.registerHelper("unless",function(b,c){return a.helpers["if"].call(this,b,{fn:c.inverse,inverse:c.fn,hash:c.hash})}),a.registerHelper("with",function(a,b){l(a)&&(a=a.call(this));var c=b.fn;if(f.isEmpty(a))return b.inverse(this);if(b.data&&b.ids){var d=q(b.data);d.contextPath=f.appendContextPath(b.data.contextPath,b.ids[0]),b={data:d}}return c(a,b)}),a.registerHelper("log",function(b,c){var d=c.data&&null!=c.data.level?parseInt(c.data.level,10):1;a.log(d,b)}),a.registerHelper("lookup",function(a,b){return a&&a[b]})}var e={},f=a,g=b,h="2.0.0";e.VERSION=h;var i=6;e.COMPILER_REVISION=i;var j={1:"<= 1.0.rc.2",2:"== 1.0.0-rc.3",3:"== 1.0.0-rc.4",4:"== 1.x.x",5:"== 2.0.0-alpha.x",6:">= 2.0.0-beta.1"};e.REVISION_CHANGES=j;var k=f.isArray,l=f.isFunction,m=f.toString,n="[object Object]";e.HandlebarsEnvironment=c,c.prototype={constructor:c,logger:o,log:p,registerHelper:function(a,b){if(m.call(a)===n){if(b)throw new g("Arg not supported with multiple helpers");f.extend(this.helpers,a)}else this.helpers[a]=b},unregisterHelper:function(a){delete this.helpers[a]},registerPartial:function(a,b){m.call(a)===n?f.extend(this.partials,a):this.partials[a]=b},unregisterPartial:function(a){delete this.partials[a]}};var o={methodMap:{0:"debug",1:"info",2:"warn",3:"error"},DEBUG:0,INFO:1,WARN:2,ERROR:3,level:3,log:function(a,b){if(o.level<=a){var c=o.methodMap[a];"undefined"!=typeof console&&console[c]&&console[c].call(console,b)}}};e.logger=o;var p=o.log;e.log=p;var q=function(a){var b=f.extend({},a);return b._parent=a,b};return e.createFrame=q,e}(b,c),e=function(a,b,c){"use strict";function d(a){var b=a&&a[0]||1,c=m;if(b!==c){if(c>b){var d=n[c],e=n[b];throw new l("Template was precompiled with an older version of Handlebars than the current runtime. Please update your precompiler to a newer version ("+d+") or downgrade your runtime to an older version ("+e+").")}throw new l("Template was precompiled with a newer version of Handlebars than the current runtime. Please update your runtime to a newer version ("+a[1]+").")}}function e(a,b){if(!b)throw new l("No environment passed to template");if(!a||!a.main)throw new l("Unknown template object: "+typeof a);b.VM.checkRevision(a.compiler);var c=function(c,d,e,f,g,h,i,j,m){g&&(f=k.extend({},f,g));var n=b.VM.invokePartial.call(this,c,e,f,h,i,j,m);if(null==n&&b.compile){var o={helpers:h,partials:i,data:j,depths:m};i[e]=b.compile(c,{data:void 0!==j,compat:a.compat},b),n=i[e](f,o)}if(null!=n){if(d){for(var p=n.split("\n"),q=0,r=p.length;r>q&&(p[q]||q+1!==r);q++)p[q]=d+p[q];n=p.join("\n")}return n}throw new l("The partial "+e+" could not be compiled when running in runtime-only mode")},d={lookup:function(a,b){for(var c=a.length,d=0;c>d;d++)if(a[d]&&null!=a[d][b])return a[d][b]},lambda:function(a,b){return"function"==typeof a?a.call(b):a},escapeExpression:k.escapeExpression,invokePartial:c,fn:function(b){return a[b]},programs:[],program:function(a,b,c){var d=this.programs[a],e=this.fn(a);return b||c?d=f(this,a,e,b,c):d||(d=this.programs[a]=f(this,a,e)),d},data:function(a,b){for(;a&&b--;)a=a._parent;return a},merge:function(a,b){var c=a||b;return a&&b&&a!==b&&(c=k.extend({},b,a)),c},noop:b.VM.noop,compilerInfo:a.compiler},e=function(b,c){c=c||{};var f=c.data;e._setup(c),!c.partial&&a.useData&&(f=i(b,f));var g;return a.useDepths&&(g=c.depths?[b].concat(c.depths):[b]),a.main.call(d,b,d.helpers,d.partials,f,g)};return e.isTop=!0,e._setup=function(c){c.partial?(d.helpers=c.helpers,d.partials=c.partials):(d.helpers=d.merge(c.helpers,b.helpers),a.usePartial&&(d.partials=d.merge(c.partials,b.partials)))},e._child=function(b,c,e){if(a.useDepths&&!e)throw new l("must pass parent depths");return f(d,b,a[b],c,e)},e}function f(a,b,c,d,e){var f=function(b,f){return f=f||{},c.call(a,b,a.helpers,a.partials,f.data||d,e&&[b].concat(e))};return f.program=b,f.depth=e?e.length:0,f}function g(a,b,c,d,e,f,g){var h={partial:!0,helpers:d,partials:e,data:f,depths:g};if(void 0===a)throw new l("The partial "+b+" could not be found");return a instanceof Function?a(c,h):void 0}function h(){return""}function i(a,b){return b&&"root"in b||(b=b?o(b):{},b.root=a),b}var j={},k=a,l=b,m=c.COMPILER_REVISION,n=c.REVISION_CHANGES,o=c.createFrame;return j.checkRevision=d,j.template=e,j.program=f,j.invokePartial=g,j.noop=h,j}(b,c,d),f=function(a,b,c,d,e){"use strict";var f,g=a,h=b,i=c,j=d,k=e,l=function(){var a=new g.HandlebarsEnvironment;return j.extend(a,g),a.SafeString=h,a.Exception=i,a.Utils=j,a.escapeExpression=j.escapeExpression,a.VM=k,a.template=function(b){return k.template(b,a)},a},m=l();return m.create=l,m["default"]=m,f=m}(d,a,c,b,e),g=function(a){"use strict";function b(a){a=a||{},this.firstLine=a.first_line,this.firstColumn=a.first_column,this.lastColumn=a.last_column,this.lastLine=a.last_line}var c,d=a,e={ProgramNode:function(a,c,d){b.call(this,d),this.type="program",this.statements=a,this.strip=c},MustacheNode:function(a,c,d,f,g){if(b.call(this,g),this.type="mustache",this.strip=f,null!=d&&d.charAt){var h=d.charAt(3)||d.charAt(2);this.escaped="{"!==h&&"&"!==h}else this.escaped=!!d;this.sexpr=a instanceof e.SexprNode?a:new e.SexprNode(a,c),this.id=this.sexpr.id,this.params=this.sexpr.params,this.hash=this.sexpr.hash,this.eligibleHelper=this.sexpr.eligibleHelper,this.isHelper=this.sexpr.isHelper},SexprNode:function(a,c,d){b.call(this,d),this.type="sexpr",this.hash=c;var e=this.id=a[0],f=this.params=a.slice(1);this.isHelper=!(!f.length&&!c),this.eligibleHelper=this.isHelper||e.isSimple},PartialNode:function(a,c,d,e,f){b.call(this,f),this.type="partial",this.partialName=a,this.context=c,this.hash=d,this.strip=e,this.strip.inlineStandalone=!0},BlockNode:function(a,c,d,e,f){b.call(this,f),this.type="block",this.mustache=a,this.program=c,this.inverse=d,this.strip=e,d&&!c&&(this.isInverse=!0)},RawBlockNode:function(a,c,f,g){if(b.call(this,g),a.sexpr.id.original!==f)throw new d(a.sexpr.id.original+" doesn't match "+f,this);c=new e.ContentNode(c,g),this.type="block",this.mustache=a,this.program=new e.ProgramNode([c],{},g)},ContentNode:function(a,c){b.call(this,c),this.type="content",this.original=this.string=a},HashNode:function(a,c){b.call(this,c),this.type="hash",this.pairs=a},IdNode:function(a,c){b.call(this,c),this.type="ID";for(var e="",f=[],g=0,h="",i=0,j=a.length;j>i;i++){var k=a[i].part;if(e+=(a[i].separator||"")+k,".."===k||"."===k||"this"===k){if(f.length>0)throw new d("Invalid path: "+e,this);".."===k?(g++,h+="../"):this.isScoped=!0}else f.push(k)}this.original=e,this.parts=f,this.string=f.join("."),this.depth=g,this.idName=h+this.string,this.isSimple=1===a.length&&!this.isScoped&&0===g,this.stringModeValue=this.string},PartialNameNode:function(a,c){b.call(this,c),this.type="PARTIAL_NAME",this.name=a.original},DataNode:function(a,c){b.call(this,c),this.type="DATA",this.id=a,this.stringModeValue=a.stringModeValue,this.idName="@"+a.stringModeValue},StringNode:function(a,c){b.call(this,c),this.type="STRING",this.original=this.string=this.stringModeValue=a},NumberNode:function(a,c){b.call(this,c),this.type="NUMBER",this.original=this.number=a,this.stringModeValue=Number(a)},BooleanNode:function(a,c){b.call(this,c),this.type="BOOLEAN",this.bool=a,this.stringModeValue="true"===a},CommentNode:function(a,c){b.call(this,c),this.type="comment",this.comment=a,this.strip={inlineStandalone:!0}}};return c=e}(c),h=function(){"use strict";var a,b=function(){function a(){this.yy={}}var b={trace:function(){},yy:{},symbols_:{error:2,root:3,program:4,EOF:5,program_repetition0:6,statement:7,mustache:8,block:9,rawBlock:10,partial:11,CONTENT:12,COMMENT:13,openRawBlock:14,END_RAW_BLOCK:15,OPEN_RAW_BLOCK:16,sexpr:17,CLOSE_RAW_BLOCK:18,openBlock:19,block_option0:20,closeBlock:21,openInverse:22,block_option1:23,OPEN_BLOCK:24,CLOSE:25,OPEN_INVERSE:26,inverseAndProgram:27,INVERSE:28,OPEN_ENDBLOCK:29,path:30,OPEN:31,OPEN_UNESCAPED:32,CLOSE_UNESCAPED:33,OPEN_PARTIAL:34,partialName:35,param:36,partial_option0:37,partial_option1:38,sexpr_repetition0:39,sexpr_option0:40,dataName:41,STRING:42,NUMBER:43,BOOLEAN:44,OPEN_SEXPR:45,CLOSE_SEXPR:46,hash:47,hash_repetition_plus0:48,hashSegment:49,ID:50,EQUALS:51,DATA:52,pathSegments:53,SEP:54,$accept:0,$end:1},terminals_:{2:"error",5:"EOF",12:"CONTENT",13:"COMMENT",15:"END_RAW_BLOCK",16:"OPEN_RAW_BLOCK",18:"CLOSE_RAW_BLOCK",24:"OPEN_BLOCK",25:"CLOSE",26:"OPEN_INVERSE",28:"INVERSE",29:"OPEN_ENDBLOCK",31:"OPEN",32:"OPEN_UNESCAPED",33:"CLOSE_UNESCAPED",34:"OPEN_PARTIAL",42:"STRING",43:"NUMBER",44:"BOOLEAN",45:"OPEN_SEXPR",46:"CLOSE_SEXPR",50:"ID",51:"EQUALS",52:"DATA",54:"SEP"},productions_:[0,[3,2],[4,1],[7,1],[7,1],[7,1],[7,1],[7,1],[7,1],[10,3],[14,3],[9,4],[9,4],[19,3],[22,3],[27,2],[21,3],[8,3],[8,3],[11,5],[11,4],[17,3],[17,1],[36,1],[36,1],[36,1],[36,1],[36,1],[36,3],[47,1],[49,3],[35,1],[35,1],[35,1],[41,2],[30,1],[53,3],[53,1],[6,0],[6,2],[20,0],[20,1],[23,0],[23,1],[37,0],[37,1],[38,0],[38,1],[39,0],[39,2],[40,0],[40,1],[48,1],[48,2]],performAction:function(a,b,c,d,e,f){var g=f.length-1;switch(e){case 1:return d.prepareProgram(f[g-1].statements,!0),f[g-1];case 2:this.$=new d.ProgramNode(d.prepareProgram(f[g]),{},this._$);break;case 3:this.$=f[g];break;case 4:this.$=f[g];break;case 5:this.$=f[g];break;case 6:this.$=f[g];break;case 7:this.$=new d.ContentNode(f[g],this._$);break;case 8:this.$=new d.CommentNode(f[g],this._$);break;case 9:this.$=new d.RawBlockNode(f[g-2],f[g-1],f[g],this._$);break;case 10:this.$=new d.MustacheNode(f[g-1],null,"","",this._$);break;case 11:this.$=d.prepareBlock(f[g-3],f[g-2],f[g-1],f[g],!1,this._$);break;case 12:this.$=d.prepareBlock(f[g-3],f[g-2],f[g-1],f[g],!0,this._$);break;case 13:this.$=new d.MustacheNode(f[g-1],null,f[g-2],d.stripFlags(f[g-2],f[g]),this._$);break;case 14:this.$=new d.MustacheNode(f[g-1],null,f[g-2],d.stripFlags(f[g-2],f[g]),this._$);break;case 15:this.$={strip:d.stripFlags(f[g-1],f[g-1]),program:f[g]};break;case 16:this.$={path:f[g-1],strip:d.stripFlags(f[g-2],f[g])};break;case 17:this.$=new d.MustacheNode(f[g-1],null,f[g-2],d.stripFlags(f[g-2],f[g]),this._$);break;case 18:this.$=new d.MustacheNode(f[g-1],null,f[g-2],d.stripFlags(f[g-2],f[g]),this._$);break;case 19:this.$=new d.PartialNode(f[g-3],f[g-2],f[g-1],d.stripFlags(f[g-4],f[g]),this._$);break;case 20:this.$=new d.PartialNode(f[g-2],void 0,f[g-1],d.stripFlags(f[g-3],f[g]),this._$);break;case 21:this.$=new d.SexprNode([f[g-2]].concat(f[g-1]),f[g],this._$);break;case 22:this.$=new d.SexprNode([f[g]],null,this._$);break;case 23:this.$=f[g];break;case 24:this.$=new d.StringNode(f[g],this._$);break;case 25:this.$=new d.NumberNode(f[g],this._$);break;case 26:this.$=new d.BooleanNode(f[g],this._$);break;case 27:this.$=f[g];break;case 28:f[g-1].isHelper=!0,this.$=f[g-1];break;case 29:this.$=new d.HashNode(f[g],this._$);break;case 30:this.$=[f[g-2],f[g]];break;case 31:this.$=new d.PartialNameNode(f[g],this._$);break;case 32:this.$=new d.PartialNameNode(new d.StringNode(f[g],this._$),this._$);break;case 33:this.$=new d.PartialNameNode(new d.NumberNode(f[g],this._$));break;case 34:this.$=new d.DataNode(f[g],this._$);break;case 35:this.$=new d.IdNode(f[g],this._$);break;case 36:f[g-2].push({part:f[g],separator:f[g-1]}),this.$=f[g-2];break;case 37:this.$=[{part:f[g]}];break;case 38:this.$=[];break;case 39:f[g-1].push(f[g]);break;case 48:this.$=[];break;case 49:f[g-1].push(f[g]);break;case 52:this.$=[f[g]];break;case 53:f[g-1].push(f[g])}},table:[{3:1,4:2,5:[2,38],6:3,12:[2,38],13:[2,38],16:[2,38],24:[2,38],26:[2,38],31:[2,38],32:[2,38],34:[2,38]},{1:[3]},{5:[1,4]},{5:[2,2],7:5,8:6,9:7,10:8,11:9,12:[1,10],13:[1,11],14:16,16:[1,20],19:14,22:15,24:[1,18],26:[1,19],28:[2,2],29:[2,2],31:[1,12],32:[1,13],34:[1,17]},{1:[2,1]},{5:[2,39],12:[2,39],13:[2,39],16:[2,39],24:[2,39],26:[2,39],28:[2,39],29:[2,39],31:[2,39],32:[2,39],34:[2,39]},{5:[2,3],12:[2,3],13:[2,3],16:[2,3],24:[2,3],26:[2,3],28:[2,3],29:[2,3],31:[2,3],32:[2,3],34:[2,3]},{5:[2,4],12:[2,4],13:[2,4],16:[2,4],24:[2,4],26:[2,4],28:[2,4],29:[2,4],31:[2,4],32:[2,4],34:[2,4]},{5:[2,5],12:[2,5],13:[2,5],16:[2,5],24:[2,5],26:[2,5],28:[2,5],29:[2,5],31:[2,5],32:[2,5],34:[2,5]},{5:[2,6],12:[2,6],13:[2,6],16:[2,6],24:[2,6],26:[2,6],28:[2,6],29:[2,6],31:[2,6],32:[2,6],34:[2,6]},{5:[2,7],12:[2,7],13:[2,7],16:[2,7],24:[2,7],26:[2,7],28:[2,7],29:[2,7],31:[2,7],32:[2,7],34:[2,7]},{5:[2,8],12:[2,8],13:[2,8],16:[2,8],24:[2,8],26:[2,8],28:[2,8],29:[2,8],31:[2,8],32:[2,8],34:[2,8]},{17:21,30:22,41:23,50:[1,26],52:[1,25],53:24},{17:27,30:22,41:23,50:[1,26],52:[1,25],53:24},{4:28,6:3,12:[2,38],13:[2,38],16:[2,38],24:[2,38],26:[2,38],28:[2,38],29:[2,38],31:[2,38],32:[2,38],34:[2,38]},{4:29,6:3,12:[2,38],13:[2,38],16:[2,38],24:[2,38],26:[2,38],28:[2,38],29:[2,38],31:[2,38],32:[2,38],34:[2,38]},{12:[1,30]},{30:32,35:31,42:[1,33],43:[1,34],50:[1,26],53:24},{17:35,30:22,41:23,50:[1,26],52:[1,25],53:24},{17:36,30:22,41:23,50:[1,26],52:[1,25],53:24},{17:37,30:22,41:23,50:[1,26],52:[1,25],53:24},{25:[1,38]},{18:[2,48],25:[2,48],33:[2,48],39:39,42:[2,48],43:[2,48],44:[2,48],45:[2,48],46:[2,48],50:[2,48],52:[2,48]},{18:[2,22],25:[2,22],33:[2,22],46:[2,22]},{18:[2,35],25:[2,35],33:[2,35],42:[2,35],43:[2,35],44:[2,35],45:[2,35],46:[2,35],50:[2,35],52:[2,35],54:[1,40]},{30:41,50:[1,26],53:24},{18:[2,37],25:[2,37],33:[2,37],42:[2,37],43:[2,37],44:[2,37],45:[2,37],46:[2,37],50:[2,37],52:[2,37],54:[2,37]},{33:[1,42]},{20:43,27:44,28:[1,45],29:[2,40]},{23:46,27:47,28:[1,45],29:[2,42]},{15:[1,48]},{25:[2,46],30:51,36:49,38:50,41:55,42:[1,52],43:[1,53],44:[1,54],45:[1,56],47:57,48:58,49:60,50:[1,59],52:[1,25],53:24},{25:[2,31],42:[2,31],43:[2,31],44:[2,31],45:[2,31],50:[2,31],52:[2,31]},{25:[2,32],42:[2,32],43:[2,32],44:[2,32],45:[2,32],50:[2,32],52:[2,32]},{25:[2,33],42:[2,33],43:[2,33],44:[2,33],45:[2,33],50:[2,33],52:[2,33]},{25:[1,61]},{25:[1,62]},{18:[1,63]},{5:[2,17],12:[2,17],13:[2,17],16:[2,17],24:[2,17],26:[2,17],28:[2,17],29:[2,17],31:[2,17],32:[2,17],34:[2,17]},{18:[2,50],25:[2,50],30:51,33:[2,50],36:65,40:64,41:55,42:[1,52],43:[1,53],44:[1,54],45:[1,56],46:[2,50],47:66,48:58,49:60,50:[1,59],52:[1,25],53:24},{50:[1,67]},{18:[2,34],25:[2,34],33:[2,34],42:[2,34],43:[2,34],44:[2,34],45:[2,34],46:[2,34],50:[2,34],52:[2,34]},{5:[2,18],12:[2,18],13:[2,18],16:[2,18],24:[2,18],26:[2,18],28:[2,18],29:[2,18],31:[2,18],32:[2,18],34:[2,18]},{21:68,29:[1,69]},{29:[2,41]},{4:70,6:3,12:[2,38],13:[2,38],16:[2,38],24:[2,38],26:[2,38],29:[2,38],31:[2,38],32:[2,38],34:[2,38]},{21:71,29:[1,69]},{29:[2,43]},{5:[2,9],12:[2,9],13:[2,9],16:[2,9],24:[2,9],26:[2,9],28:[2,9],29:[2,9],31:[2,9],32:[2,9],34:[2,9]},{25:[2,44],37:72,47:73,48:58,49:60,50:[1,74]},{25:[1,75]},{18:[2,23],25:[2,23],33:[2,23],42:[2,23],43:[2,23],44:[2,23],45:[2,23],46:[2,23],50:[2,23],52:[2,23]},{18:[2,24],25:[2,24],33:[2,24],42:[2,24],43:[2,24],44:[2,24],45:[2,24],46:[2,24],50:[2,24],52:[2,24]},{18:[2,25],25:[2,25],33:[2,25],42:[2,25],43:[2,25],44:[2,25],45:[2,25],46:[2,25],50:[2,25],52:[2,25]},{18:[2,26],25:[2,26],33:[2,26],42:[2,26],43:[2,26],44:[2,26],45:[2,26],46:[2,26],50:[2,26],52:[2,26]},{18:[2,27],25:[2,27],33:[2,27],42:[2,27],43:[2,27],44:[2,27],45:[2,27],46:[2,27],50:[2,27],52:[2,27]},{17:76,30:22,41:23,50:[1,26],52:[1,25],53:24},{25:[2,47]},{18:[2,29],25:[2,29],33:[2,29],46:[2,29],49:77,50:[1,74]},{18:[2,37],25:[2,37],33:[2,37],42:[2,37],43:[2,37],44:[2,37],45:[2,37],46:[2,37],50:[2,37],51:[1,78],52:[2,37],54:[2,37]},{18:[2,52],25:[2,52],33:[2,52],46:[2,52],50:[2,52]},{12:[2,13],13:[2,13],16:[2,13],24:[2,13],26:[2,13],28:[2,13],29:[2,13],31:[2,13],32:[2,13],34:[2,13]},{12:[2,14],13:[2,14],16:[2,14],24:[2,14],26:[2,14],28:[2,14],29:[2,14],31:[2,14],32:[2,14],34:[2,14]},{12:[2,10]},{18:[2,21],25:[2,21],33:[2,21],46:[2,21]},{18:[2,49],25:[2,49],33:[2,49],42:[2,49],43:[2,49],44:[2,49],45:[2,49],46:[2,49],50:[2,49],52:[2,49]},{18:[2,51],25:[2,51],33:[2,51],46:[2,51]},{18:[2,36],25:[2,36],33:[2,36],42:[2,36],43:[2,36],44:[2,36],45:[2,36],46:[2,36],50:[2,36],52:[2,36],54:[2,36]},{5:[2,11],12:[2,11],13:[2,11],16:[2,11],24:[2,11],26:[2,11],28:[2,11],29:[2,11],31:[2,11],32:[2,11],34:[2,11]},{30:79,50:[1,26],53:24},{29:[2,15]},{5:[2,12],12:[2,12],13:[2,12],16:[2,12],24:[2,12],26:[2,12],28:[2,12],29:[2,12],31:[2,12],32:[2,12],34:[2,12]},{25:[1,80]},{25:[2,45]},{51:[1,78]},{5:[2,20],12:[2,20],13:[2,20],16:[2,20],24:[2,20],26:[2,20],28:[2,20],29:[2,20],31:[2,20],32:[2,20],34:[2,20]},{46:[1,81]},{18:[2,53],25:[2,53],33:[2,53],46:[2,53],50:[2,53]},{30:51,36:82,41:55,42:[1,52],43:[1,53],44:[1,54],45:[1,56],50:[1,26],52:[1,25],53:24},{25:[1,83]},{5:[2,19],12:[2,19],13:[2,19],16:[2,19],24:[2,19],26:[2,19],28:[2,19],29:[2,19],31:[2,19],32:[2,19],34:[2,19]},{18:[2,28],25:[2,28],33:[2,28],42:[2,28],43:[2,28],44:[2,28],45:[2,28],46:[2,28],50:[2,28],52:[2,28]},{18:[2,30],25:[2,30],33:[2,30],46:[2,30],50:[2,30]},{5:[2,16],12:[2,16],13:[2,16],16:[2,16],24:[2,16],26:[2,16],28:[2,16],29:[2,16],31:[2,16],32:[2,16],34:[2,16]}],defaultActions:{4:[2,1],44:[2,41],47:[2,43],57:[2,47],63:[2,10],70:[2,15],73:[2,45]},parseError:function(a){throw new Error(a)},parse:function(a){function b(){var a;return a=c.lexer.lex()||1,"number"!=typeof a&&(a=c.symbols_[a]||a),a}var c=this,d=[0],e=[null],f=[],g=this.table,h="",i=0,j=0,k=0;this.lexer.setInput(a),this.lexer.yy=this.yy,this.yy.lexer=this.lexer,this.yy.parser=this,"undefined"==typeof this.lexer.yylloc&&(this.lexer.yylloc={});var l=this.lexer.yylloc;f.push(l);var m=this.lexer.options&&this.lexer.options.ranges;"function"==typeof this.yy.parseError&&(this.parseError=this.yy.parseError);for(var n,o,p,q,r,s,t,u,v,w={};;){if(p=d[d.length-1],this.defaultActions[p]?q=this.defaultActions[p]:((null===n||"undefined"==typeof n)&&(n=b()),q=g[p]&&g[p][n]),"undefined"==typeof q||!q.length||!q[0]){var x="";if(!k){v=[];for(s in g[p])this.terminals_[s]&&s>2&&v.push("'"+this.terminals_[s]+"'");x=this.lexer.showPosition?"Parse error on line "+(i+1)+":\n"+this.lexer.showPosition()+"\nExpecting "+v.join(", ")+", got '"+(this.terminals_[n]||n)+"'":"Parse error on line "+(i+1)+": Unexpected "+(1==n?"end of input":"'"+(this.terminals_[n]||n)+"'"),this.parseError(x,{text:this.lexer.match,token:this.terminals_[n]||n,line:this.lexer.yylineno,loc:l,expected:v})}}if(q[0]instanceof Array&&q.length>1)throw new Error("Parse Error: multiple actions possible at state: "+p+", token: "+n);switch(q[0]){case 1:d.push(n),e.push(this.lexer.yytext),f.push(this.lexer.yylloc),d.push(q[1]),n=null,o?(n=o,o=null):(j=this.lexer.yyleng,h=this.lexer.yytext,i=this.lexer.yylineno,l=this.lexer.yylloc,k>0&&k--);break;case 2:if(t=this.productions_[q[1]][1],w.$=e[e.length-t],w._$={first_line:f[f.length-(t||1)].first_line,last_line:f[f.length-1].last_line,first_column:f[f.length-(t||1)].first_column,last_column:f[f.length-1].last_column},m&&(w._$.range=[f[f.length-(t||1)].range[0],f[f.length-1].range[1]]),r=this.performAction.call(w,h,j,i,this.yy,q[1],e,f),"undefined"!=typeof r)return r;t&&(d=d.slice(0,-1*t*2),e=e.slice(0,-1*t),f=f.slice(0,-1*t)),d.push(this.productions_[q[1]][0]),e.push(w.$),f.push(w._$),u=g[d[d.length-2]][d[d.length-1]],d.push(u);break;case 3:return!0}}return!0}},c=function(){var a={EOF:1,parseError:function(a,b){if(!this.yy.parser)throw new Error(a);this.yy.parser.parseError(a,b)},setInput:function(a){return this._input=a,this._more=this._less=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},input:function(){var a=this._input[0];this.yytext+=a,this.yyleng++,this.offset++,this.match+=a,this.matched+=a;var b=a.match(/(?:\r\n?|\n).*/g);return b?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),a},unput:function(a){var b=a.length,c=a.split(/(?:\r\n?|\n)/g);this._input=a+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-b-1),this.offset-=b;var d=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),c.length-1&&(this.yylineno-=c.length-1);var e=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:c?(c.length===d.length?this.yylloc.first_column:0)+d[d.length-c.length].length-c[0].length:this.yylloc.first_column-b},this.options.ranges&&(this.yylloc.range=[e[0],e[0]+this.yyleng-b]),this},more:function(){return this._more=!0,this},less:function(a){this.unput(this.match.slice(a))},pastInput:function(){var a=this.matched.substr(0,this.matched.length-this.match.length);return(a.length>20?"...":"")+a.substr(-20).replace(/\n/g,"")},upcomingInput:function(){var a=this.match;return a.length<20&&(a+=this._input.substr(0,20-a.length)),(a.substr(0,20)+(a.length>20?"...":"")).replace(/\n/g,"")},showPosition:function(){var a=this.pastInput(),b=new Array(a.length+1).join("-");return a+this.upcomingInput()+"\n"+b+"^"},next:function(){if(this.done)return this.EOF;this._input||(this.done=!0);var a,b,c,d,e;this._more||(this.yytext="",this.match="");for(var f=this._currentRules(),g=0;g<f.length&&(c=this._input.match(this.rules[f[g]]),!c||b&&!(c[0].length>b[0].length)||(b=c,d=g,this.options.flex));g++);return b?(e=b[0].match(/(?:\r\n?|\n).*/g),e&&(this.yylineno+=e.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:e?e[e.length-1].length-e[e.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+b[0].length},this.yytext+=b[0],this.match+=b[0],this.matches=b,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._input=this._input.slice(b[0].length),this.matched+=b[0],a=this.performAction.call(this,this.yy,this,f[d],this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),a?a:void 0):""===this._input?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+". Unrecognized text.\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},lex:function(){var a=this.next();return"undefined"!=typeof a?a:this.lex()},begin:function(a){this.conditionStack.push(a)},popState:function(){return this.conditionStack.pop()},_currentRules:function(){return this.conditions[this.conditionStack[this.conditionStack.length-1]].rules},topState:function(){return this.conditionStack[this.conditionStack.length-2]},pushState:function(a){this.begin(a)}};return a.options={},a.performAction=function(a,b,c,d){function e(a,c){return b.yytext=b.yytext.substr(a,b.yyleng-c)}switch(c){case 0:if("\\\\"===b.yytext.slice(-2)?(e(0,1),this.begin("mu")):"\\"===b.yytext.slice(-1)?(e(0,1),this.begin("emu")):this.begin("mu"),b.yytext)return 12;break;case 1:return 12;case 2:return this.popState(),12;case 3:return b.yytext=b.yytext.substr(5,b.yyleng-9),this.popState(),15;case 4:return 12;case 5:return e(0,4),this.popState(),13;case 6:return 45;case 7:return 46;case 8:return 16;case 9:return this.popState(),this.begin("raw"),18;case 10:return 34;case 11:return 24;case 12:return 29;case 13:return this.popState(),28;case 14:return this.popState(),28;case 15:return 26;case 16:return 26;case 17:return 32;case 18:return 31;case 19:this.popState(),this.begin("com");break;case 20:return e(3,5),this.popState(),13;case 21:return 31;case 22:return 51;case 23:return 50;case 24:return 50;case 25:return 54;case 26:break;case 27:return this.popState(),33;case 28:return this.popState(),25;case 29:return b.yytext=e(1,2).replace(/\\"/g,'"'),42;case 30:return b.yytext=e(1,2).replace(/\\'/g,"'"),42;case 31:return 52;case 32:return 44;case 33:return 44;case 34:return 43;case 35:return 50;case 36:return b.yytext=e(1,2),50;case 37:return"INVALID";case 38:return 5}},a.rules=[/^(?:[^\x00]*?(?=(\{\{)))/,/^(?:[^\x00]+)/,/^(?:[^\x00]{2,}?(?=(\{\{|\\\{\{|\\\\\{\{|$)))/,/^(?:\{\{\{\{\/[^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=[=}\s\/.])\}\}\}\})/,/^(?:[^\x00]*?(?=(\{\{\{\{\/)))/,/^(?:[\s\S]*?--\}\})/,/^(?:\()/,/^(?:\))/,/^(?:\{\{\{\{)/,/^(?:\}\}\}\})/,/^(?:\{\{(~)?>)/,/^(?:\{\{(~)?#)/,/^(?:\{\{(~)?\/)/,/^(?:\{\{(~)?\^\s*(~)?\}\})/,/^(?:\{\{(~)?\s*else\s*(~)?\}\})/,/^(?:\{\{(~)?\^)/,/^(?:\{\{(~)?\s*else\b)/,/^(?:\{\{(~)?\{)/,/^(?:\{\{(~)?&)/,/^(?:\{\{!--)/,/^(?:\{\{![\s\S]*?\}\})/,/^(?:\{\{(~)?)/,/^(?:=)/,/^(?:\.\.)/,/^(?:\.(?=([=~}\s\/.)])))/,/^(?:[\/.])/,/^(?:\s+)/,/^(?:\}(~)?\}\})/,/^(?:(~)?\}\})/,/^(?:"(\\["]|[^"])*")/,/^(?:'(\\[']|[^'])*')/,/^(?:@)/,/^(?:true(?=([~}\s)])))/,/^(?:false(?=([~}\s)])))/,/^(?:-?[0-9]+(?:\.[0-9]+)?(?=([~}\s)])))/,/^(?:([^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=([=~}\s\/.)]))))/,/^(?:\[[^\]]*\])/,/^(?:.)/,/^(?:$)/],a.conditions={mu:{rules:[6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38],inclusive:!1},emu:{rules:[2],inclusive:!1},com:{rules:[5],inclusive:!1},raw:{rules:[3,4],inclusive:!1},INITIAL:{rules:[0,1,38],inclusive:!0}},a}();return b.lexer=c,a.prototype=b,b.Parser=a,new a}();return a=b}(),i=function(a){"use strict";function b(a,b){return{left:"~"===a.charAt(2),right:"~"===b.charAt(b.length-3)}}function c(a,b,c,d,i,k){if(a.sexpr.id.original!==d.path.original)throw new j(a.sexpr.id.original+" doesn't match "+d.path.original,a);var l=c&&c.program,m={left:a.strip.left,right:d.strip.right,openStandalone:f(b.statements),closeStandalone:e((l||b).statements)};if(a.strip.right&&g(b.statements,null,!0),l){var n=c.strip;n.left&&h(b.statements,null,!0),n.right&&g(l.statements,null,!0),d.strip.left&&h(l.statements,null,!0),e(b.statements)&&f(l.statements)&&(h(b.statements),g(l.statements))}else d.strip.left&&h(b.statements,null,!0);return i?new this.BlockNode(a,l,b,m,k):new this.BlockNode(a,b,l,m,k)}function d(a,b){for(var c=0,d=a.length;d>c;c++){var i=a[c],j=i.strip;if(j){var k=e(a,c,b,"partial"===i.type),l=f(a,c,b),m=j.openStandalone&&k,n=j.closeStandalone&&l,o=j.inlineStandalone&&k&&l;j.right&&g(a,c,!0),j.left&&h(a,c,!0),o&&(g(a,c),h(a,c)&&"partial"===i.type&&(i.indent=/([ \t]+$)/.exec(a[c-1].original)?RegExp.$1:"")),m&&(g((i.program||i.inverse).statements),h(a,c)),n&&(g(a,c),h((i.inverse||i.program).statements))}}return a}function e(a,b,c){void 0===b&&(b=a.length);var d=a[b-1],e=a[b-2];return d?"content"===d.type?(e||!c?/\r?\n\s*?$/:/(^|\r?\n)\s*?$/).test(d.original):void 0:c}function f(a,b,c){void 0===b&&(b=-1);var d=a[b+1],e=a[b+2];return d?"content"===d.type?(e||!c?/^\s*?\r?\n/:/^\s*?(\r?\n|$)/).test(d.original):void 0:c}function g(a,b,c){var d=a[null==b?0:b+1];if(d&&"content"===d.type&&(c||!d.rightStripped)){var e=d.string;d.string=d.string.replace(c?/^\s+/:/^[ \t]*\r?\n?/,""),d.rightStripped=d.string!==e}}function h(a,b,c){var d=a[null==b?a.length-1:b-1];if(d&&"content"===d.type&&(c||!d.leftStripped)){var e=d.string;return d.string=d.string.replace(c?/\s+$/:/[ \t]+$/,""),d.leftStripped=d.string!==e,d.leftStripped}}var i={},j=a;return i.stripFlags=b,i.prepareBlock=c,i.prepareProgram=d,i}(c),j=function(a,b,c,d){"use strict";function e(a){return a.constructor===h.ProgramNode?a:(g.yy=k,g.parse(a))}var f={},g=a,h=b,i=c,j=d.extend;f.parser=g;var k={};return j(k,i,h),f.parse=e,f}(h,g,i,b),k=function(a,b){"use strict";function c(){}function d(a,b,c){if(null==a||"string"!=typeof a&&a.constructor!==c.AST.ProgramNode)throw new h("You must pass a string or Handlebars AST to Handlebars.precompile. You passed "+a);b=b||{},"data"in b||(b.data=!0),b.compat&&(b.useDepths=!0);var d=c.parse(a),e=(new c.Compiler).compile(d,b);return(new c.JavaScriptCompiler).compile(e,b)}function e(a,b,c){function d(){var d=c.parse(a),e=(new c.Compiler).compile(d,b),f=(new c.JavaScriptCompiler).compile(e,b,void 0,!0);return c.template(f)}if(null==a||"string"!=typeof a&&a.constructor!==c.AST.ProgramNode)throw new h("You must pass a string or Handlebars AST to Handlebars.compile. You passed "+a);b=b||{},"data"in b||(b.data=!0),b.compat&&(b.useDepths=!0);var e,f=function(a,b){return e||(e=d()),e.call(this,a,b)};return f._setup=function(a){return e||(e=d()),e._setup(a)},f._child=function(a,b,c){return e||(e=d()),e._child(a,b,c)},f}function f(a,b){if(a===b)return!0;if(i(a)&&i(b)&&a.length===b.length){for(var c=0;c<a.length;c++)if(!f(a[c],b[c]))return!1;return!0}}var g={},h=a,i=b.isArray,j=[].slice;return g.Compiler=c,c.prototype={compiler:c,equals:function(a){var b=this.opcodes.length;if(a.opcodes.length!==b)return!1;for(var c=0;b>c;c++){var d=this.opcodes[c],e=a.opcodes[c];if(d.opcode!==e.opcode||!f(d.args,e.args))return!1}for(b=this.children.length,c=0;b>c;c++)if(!this.children[c].equals(a.children[c]))return!1;return!0},guid:0,compile:function(a,b){this.opcodes=[],this.children=[],this.depths={list:[]},this.options=b,this.stringParams=b.stringParams,this.trackIds=b.trackIds;var c=this.options.knownHelpers;if(this.options.knownHelpers={helperMissing:!0,blockHelperMissing:!0,each:!0,"if":!0,unless:!0,"with":!0,log:!0,lookup:!0},c)for(var d in c)this.options.knownHelpers[d]=c[d];return this.accept(a)},accept:function(a){return this[a.type](a)},program:function(a){for(var b=a.statements,c=0,d=b.length;d>c;c++)this.accept(b[c]);return this.isSimple=1===d,this.depths.list=this.depths.list.sort(function(a,b){return a-b}),this},compileProgram:function(a){var b,c=(new this.compiler).compile(a,this.options),d=this.guid++;
-this.usePartial=this.usePartial||c.usePartial,this.children[d]=c;for(var e=0,f=c.depths.list.length;f>e;e++)b=c.depths.list[e],2>b||this.addDepth(b-1);return d},block:function(a){var b=a.mustache,c=a.program,d=a.inverse;c&&(c=this.compileProgram(c)),d&&(d=this.compileProgram(d));var e=b.sexpr,f=this.classifySexpr(e);"helper"===f?this.helperSexpr(e,c,d):"simple"===f?(this.simpleSexpr(e),this.opcode("pushProgram",c),this.opcode("pushProgram",d),this.opcode("emptyHash"),this.opcode("blockValue",e.id.original)):(this.ambiguousSexpr(e,c,d),this.opcode("pushProgram",c),this.opcode("pushProgram",d),this.opcode("emptyHash"),this.opcode("ambiguousBlockValue")),this.opcode("append")},hash:function(a){var b,c,d=a.pairs;for(this.opcode("pushHash"),b=0,c=d.length;c>b;b++)this.pushParam(d[b][1]);for(;b--;)this.opcode("assignToHash",d[b][0]);this.opcode("popHash")},partial:function(a){var b=a.partialName;this.usePartial=!0,a.hash?this.accept(a.hash):this.opcode("push","undefined"),a.context?this.accept(a.context):(this.opcode("getContext",0),this.opcode("pushContext")),this.opcode("invokePartial",b.name,a.indent||""),this.opcode("append")},content:function(a){a.string&&this.opcode("appendContent",a.string)},mustache:function(a){this.sexpr(a.sexpr),a.escaped&&!this.options.noEscape?this.opcode("appendEscaped"):this.opcode("append")},ambiguousSexpr:function(a,b,c){var d=a.id,e=d.parts[0],f=null!=b||null!=c;this.opcode("getContext",d.depth),this.opcode("pushProgram",b),this.opcode("pushProgram",c),this.ID(d),this.opcode("invokeAmbiguous",e,f)},simpleSexpr:function(a){var b=a.id;"DATA"===b.type?this.DATA(b):b.parts.length?this.ID(b):(this.addDepth(b.depth),this.opcode("getContext",b.depth),this.opcode("pushContext")),this.opcode("resolvePossibleLambda")},helperSexpr:function(a,b,c){var d=this.setupFullMustacheParams(a,b,c),e=a.id,f=e.parts[0];if(this.options.knownHelpers[f])this.opcode("invokeKnownHelper",d.length,f);else{if(this.options.knownHelpersOnly)throw new h("You specified knownHelpersOnly, but used the unknown helper "+f,a);e.falsy=!0,this.ID(e),this.opcode("invokeHelper",d.length,e.original,e.isSimple)}},sexpr:function(a){var b=this.classifySexpr(a);"simple"===b?this.simpleSexpr(a):"helper"===b?this.helperSexpr(a):this.ambiguousSexpr(a)},ID:function(a){this.addDepth(a.depth),this.opcode("getContext",a.depth);var b=a.parts[0];b?this.opcode("lookupOnContext",a.parts,a.falsy,a.isScoped):this.opcode("pushContext")},DATA:function(a){this.options.data=!0,this.opcode("lookupData",a.id.depth,a.id.parts)},STRING:function(a){this.opcode("pushString",a.string)},NUMBER:function(a){this.opcode("pushLiteral",a.number)},BOOLEAN:function(a){this.opcode("pushLiteral",a.bool)},comment:function(){},opcode:function(a){this.opcodes.push({opcode:a,args:j.call(arguments,1)})},addDepth:function(a){0!==a&&(this.depths[a]||(this.depths[a]=!0,this.depths.list.push(a)))},classifySexpr:function(a){var b=a.isHelper,c=a.eligibleHelper,d=this.options;if(c&&!b){var e=a.id.parts[0];d.knownHelpers[e]?b=!0:d.knownHelpersOnly&&(c=!1)}return b?"helper":c?"ambiguous":"simple"},pushParams:function(a){for(var b=0,c=a.length;c>b;b++)this.pushParam(a[b])},pushParam:function(a){this.stringParams?(a.depth&&this.addDepth(a.depth),this.opcode("getContext",a.depth||0),this.opcode("pushStringParam",a.stringModeValue,a.type),"sexpr"===a.type&&this.sexpr(a)):(this.trackIds&&this.opcode("pushId",a.type,a.idName||a.stringModeValue),this.accept(a))},setupFullMustacheParams:function(a,b,c){var d=a.params;return this.pushParams(d),this.opcode("pushProgram",b),this.opcode("pushProgram",c),a.hash?this.hash(a.hash):this.opcode("emptyHash"),d}},g.precompile=d,g.compile=e,g}(c,b),l=function(a,b){"use strict";function c(a){this.value=a}function d(){}var e,f=a.COMPILER_REVISION,g=a.REVISION_CHANGES,h=b;d.prototype={nameLookup:function(a,b){return d.isValidJavaScriptVariableName(b)?a+"."+b:a+"['"+b+"']"},depthedLookup:function(a){return this.aliases.lookup="this.lookup",'lookup(depths, "'+a+'")'},compilerInfo:function(){var a=f,b=g[a];return[a,b]},appendToBuffer:function(a){return this.environment.isSimple?"return "+a+";":{appendToBuffer:!0,content:a,toString:function(){return"buffer += "+a+";"}}},initializeBuffer:function(){return this.quotedString("")},namespace:"Handlebars",compile:function(a,b,c,d){this.environment=a,this.options=b,this.stringParams=this.options.stringParams,this.trackIds=this.options.trackIds,this.precompile=!d,this.name=this.environment.name,this.isChild=!!c,this.context=c||{programs:[],environments:[]},this.preamble(),this.stackSlot=0,this.stackVars=[],this.aliases={},this.registers={list:[]},this.hashes=[],this.compileStack=[],this.inlineStack=[],this.compileChildren(a,b),this.useDepths=this.useDepths||a.depths.list.length||this.options.compat;var e,f,g,i=a.opcodes;for(f=0,g=i.length;g>f;f++)e=i[f],this[e.opcode].apply(this,e.args);if(this.pushSource(""),this.stackSlot||this.inlineStack.length||this.compileStack.length)throw new h("Compile completed with content left on stack");var j=this.createFunctionContext(d);if(this.isChild)return j;var k={compiler:this.compilerInfo(),main:j},l=this.context.programs;for(f=0,g=l.length;g>f;f++)l[f]&&(k[f]=l[f]);return this.environment.usePartial&&(k.usePartial=!0),this.options.data&&(k.useData=!0),this.useDepths&&(k.useDepths=!0),this.options.compat&&(k.compat=!0),d||(k.compiler=JSON.stringify(k.compiler),k=this.objectLiteral(k)),k},preamble:function(){this.lastContext=0,this.source=[]},createFunctionContext:function(a){var b="",c=this.stackVars.concat(this.registers.list);c.length>0&&(b+=", "+c.join(", "));for(var d in this.aliases)this.aliases.hasOwnProperty(d)&&(b+=", "+d+"="+this.aliases[d]);var e=["depth0","helpers","partials","data"];this.useDepths&&e.push("depths");var f=this.mergeSource(b);return a?(e.push(f),Function.apply(this,e)):"function("+e.join(",")+") {\n "+f+"}"},mergeSource:function(a){for(var b,c,d="",e=!this.forceBuffer,f=0,g=this.source.length;g>f;f++){var h=this.source[f];h.appendToBuffer?b=b?b+"\n + "+h.content:h.content:(b&&(d?d+="buffer += "+b+";\n ":(c=!0,d=b+";\n "),b=void 0),d+=h+"\n ",this.environment.isSimple||(e=!1))}return e?(b||!d)&&(d+="return "+(b||'""')+";\n"):(a+=", buffer = "+(c?"":this.initializeBuffer()),d+=b?"return buffer + "+b+";\n":"return buffer;\n"),a&&(d="var "+a.substring(2)+(c?"":";\n ")+d),d},blockValue:function(a){this.aliases.blockHelperMissing="helpers.blockHelperMissing";var b=[this.contextName(0)];this.setupParams(a,0,b);var c=this.popStack();b.splice(1,0,c),this.push("blockHelperMissing.call("+b.join(", ")+")")},ambiguousBlockValue:function(){this.aliases.blockHelperMissing="helpers.blockHelperMissing";var a=[this.contextName(0)];this.setupParams("",0,a,!0),this.flushInline();var b=this.topStack();a.splice(1,0,b),this.pushSource("if (!"+this.lastHelper+") { "+b+" = blockHelperMissing.call("+a.join(", ")+"); }")},appendContent:function(a){this.pendingContent&&(a=this.pendingContent+a),this.pendingContent=a},append:function(){this.flushInline();var a=this.popStack();this.pushSource("if ("+a+" != null) { "+this.appendToBuffer(a)+" }"),this.environment.isSimple&&this.pushSource("else { "+this.appendToBuffer("''")+" }")},appendEscaped:function(){this.aliases.escapeExpression="this.escapeExpression",this.pushSource(this.appendToBuffer("escapeExpression("+this.popStack()+")"))},getContext:function(a){this.lastContext=a},pushContext:function(){this.pushStackLiteral(this.contextName(this.lastContext))},lookupOnContext:function(a,b,c){var d=0,e=a.length;for(c||!this.options.compat||this.lastContext?this.pushContext():this.push(this.depthedLookup(a[d++]));e>d;d++)this.replaceStack(function(c){var e=this.nameLookup(c,a[d],"context");return b?" && "+e:" != null ? "+e+" : "+c})},lookupData:function(a,b){a?this.pushStackLiteral("this.data(data, "+a+")"):this.pushStackLiteral("data");for(var c=b.length,d=0;c>d;d++)this.replaceStack(function(a){return" && "+this.nameLookup(a,b[d],"data")})},resolvePossibleLambda:function(){this.aliases.lambda="this.lambda",this.push("lambda("+this.popStack()+", "+this.contextName(0)+")")},pushStringParam:function(a,b){this.pushContext(),this.pushString(b),"sexpr"!==b&&("string"==typeof a?this.pushString(a):this.pushStackLiteral(a))},emptyHash:function(){this.pushStackLiteral("{}"),this.trackIds&&this.push("{}"),this.stringParams&&(this.push("{}"),this.push("{}"))},pushHash:function(){this.hash&&this.hashes.push(this.hash),this.hash={values:[],types:[],contexts:[],ids:[]}},popHash:function(){var a=this.hash;this.hash=this.hashes.pop(),this.trackIds&&this.push("{"+a.ids.join(",")+"}"),this.stringParams&&(this.push("{"+a.contexts.join(",")+"}"),this.push("{"+a.types.join(",")+"}")),this.push("{\n "+a.values.join(",\n ")+"\n }")},pushString:function(a){this.pushStackLiteral(this.quotedString(a))},push:function(a){return this.inlineStack.push(a),a},pushLiteral:function(a){this.pushStackLiteral(a)},pushProgram:function(a){null!=a?this.pushStackLiteral(this.programExpression(a)):this.pushStackLiteral(null)},invokeHelper:function(a,b,c){this.aliases.helperMissing="helpers.helperMissing";var d=this.popStack(),e=this.setupHelper(a,b),f=(c?e.name+" || ":"")+d+" || helperMissing";this.push("(("+f+").call("+e.callParams+"))")},invokeKnownHelper:function(a,b){var c=this.setupHelper(a,b);this.push(c.name+".call("+c.callParams+")")},invokeAmbiguous:function(a,b){this.aliases.functionType='"function"',this.aliases.helperMissing="helpers.helperMissing",this.useRegister("helper");var c=this.popStack();this.emptyHash();var d=this.setupHelper(0,a,b),e=this.lastHelper=this.nameLookup("helpers",a,"helper");this.push("((helper = (helper = "+e+" || "+c+") != null ? helper : helperMissing"+(d.paramsInit?"),("+d.paramsInit:"")+"),(typeof helper === functionType ? helper.call("+d.callParams+") : helper))")},invokePartial:function(a,b){var c=[this.nameLookup("partials",a,"partial"),"'"+b+"'","'"+a+"'",this.popStack(),this.popStack(),"helpers","partials"];this.options.data?c.push("data"):this.options.compat&&c.push("undefined"),this.options.compat&&c.push("depths"),this.push("this.invokePartial("+c.join(", ")+")")},assignToHash:function(a){var b,c,d,e=this.popStack();this.trackIds&&(d=this.popStack()),this.stringParams&&(c=this.popStack(),b=this.popStack());var f=this.hash;b&&f.contexts.push("'"+a+"': "+b),c&&f.types.push("'"+a+"': "+c),d&&f.ids.push("'"+a+"': "+d),f.values.push("'"+a+"': ("+e+")")},pushId:function(a,b){"ID"===a||"DATA"===a?this.pushString(b):"sexpr"===a?this.pushStackLiteral("true"):this.pushStackLiteral("null")},compiler:d,compileChildren:function(a,b){for(var c,d,e=a.children,f=0,g=e.length;g>f;f++){c=e[f],d=new this.compiler;var h=this.matchExistingProgram(c);null==h?(this.context.programs.push(""),h=this.context.programs.length,c.index=h,c.name="program"+h,this.context.programs[h]=d.compile(c,b,this.context,!this.precompile),this.context.environments[h]=c,this.useDepths=this.useDepths||d.useDepths):(c.index=h,c.name="program"+h)}},matchExistingProgram:function(a){for(var b=0,c=this.context.environments.length;c>b;b++){var d=this.context.environments[b];if(d&&d.equals(a))return b}},programExpression:function(a){var b=this.environment.children[a],c=(b.depths.list,this.useDepths),d=[b.index,"data"];return c&&d.push("depths"),"this.program("+d.join(", ")+")"},useRegister:function(a){this.registers[a]||(this.registers[a]=!0,this.registers.list.push(a))},pushStackLiteral:function(a){return this.push(new c(a))},pushSource:function(a){this.pendingContent&&(this.source.push(this.appendToBuffer(this.quotedString(this.pendingContent))),this.pendingContent=void 0),a&&this.source.push(a)},pushStack:function(a){this.flushInline();var b=this.incrStack();return this.pushSource(b+" = "+a+";"),this.compileStack.push(b),b},replaceStack:function(a){{var b,d,e,f="";this.isInline()}if(!this.isInline())throw new h("replaceStack on non-inline");var g=this.popStack(!0);if(g instanceof c)f=b=g.value,e=!0;else{d=!this.stackSlot;var i=d?this.incrStack():this.topStackName();f="("+this.push(i)+" = "+g+")",b=this.topStack()}var j=a.call(this,b);e||this.popStack(),d&&this.stackSlot--,this.push("("+f+j+")")},incrStack:function(){return this.stackSlot++,this.stackSlot>this.stackVars.length&&this.stackVars.push("stack"+this.stackSlot),this.topStackName()},topStackName:function(){return"stack"+this.stackSlot},flushInline:function(){var a=this.inlineStack;if(a.length){this.inlineStack=[];for(var b=0,d=a.length;d>b;b++){var e=a[b];e instanceof c?this.compileStack.push(e):this.pushStack(e)}}},isInline:function(){return this.inlineStack.length},popStack:function(a){var b=this.isInline(),d=(b?this.inlineStack:this.compileStack).pop();if(!a&&d instanceof c)return d.value;if(!b){if(!this.stackSlot)throw new h("Invalid stack pop");this.stackSlot--}return d},topStack:function(){var a=this.isInline()?this.inlineStack:this.compileStack,b=a[a.length-1];return b instanceof c?b.value:b},contextName:function(a){return this.useDepths&&a?"depths["+a+"]":"depth"+a},quotedString:function(a){return'"'+a.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")+'"'},objectLiteral:function(a){var b=[];for(var c in a)a.hasOwnProperty(c)&&b.push(this.quotedString(c)+":"+a[c]);return"{"+b.join(",")+"}"},setupHelper:function(a,b,c){var d=[],e=this.setupParams(b,a,d,c),f=this.nameLookup("helpers",b,"helper");return{params:d,paramsInit:e,name:f,callParams:[this.contextName(0)].concat(d).join(", ")}},setupOptions:function(a,b,c){var d,e,f,g={},h=[],i=[],j=[];g.name=this.quotedString(a),g.hash=this.popStack(),this.trackIds&&(g.hashIds=this.popStack()),this.stringParams&&(g.hashTypes=this.popStack(),g.hashContexts=this.popStack()),e=this.popStack(),f=this.popStack(),(f||e)&&(f||(f="this.noop"),e||(e="this.noop"),g.fn=f,g.inverse=e);for(var k=b;k--;)d=this.popStack(),c[k]=d,this.trackIds&&(j[k]=this.popStack()),this.stringParams&&(i[k]=this.popStack(),h[k]=this.popStack());return this.trackIds&&(g.ids="["+j.join(",")+"]"),this.stringParams&&(g.types="["+i.join(",")+"]",g.contexts="["+h.join(",")+"]"),this.options.data&&(g.data="data"),g},setupParams:function(a,b,c,d){var e=this.objectLiteral(this.setupOptions(a,b,c));return d?(this.useRegister("options"),c.push("options"),"options="+e):(c.push(e),"")}};for(var i="break else new var case finally return void catch for switch while continue function this with default if throw delete in try do instanceof typeof abstract enum int short boolean export interface static byte extends long super char final native synchronized class float package throws const goto private transient debugger implements protected volatile double import public let yield".split(" "),j=d.RESERVED_WORDS={},k=0,l=i.length;l>k;k++)j[i[k]]=!0;return d.isValidJavaScriptVariableName=function(a){return!d.RESERVED_WORDS[a]&&/^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(a)},e=d}(d,c),m=function(a,b,c,d,e){"use strict";var f,g=a,h=b,i=c.parser,j=c.parse,k=d.Compiler,l=d.compile,m=d.precompile,n=e,o=g.create,p=function(){var a=o();return a.compile=function(b,c){return l(b,c,a)},a.precompile=function(b,c){return m(b,c,a)},a.AST=h,a.Compiler=k,a.JavaScriptCompiler=n,a.Parser=i,a.parse=j,a};return g=p(),g.create=p,g["default"]=g,f=g}(f,g,j,k,l);return m});
+this.usePartial=this.usePartial||c.usePartial,this.children[d]=c;for(var e=0,f=c.depths.list.length;f>e;e++)b=c.depths.list[e],2>b||this.addDepth(b-1);return d},block:function(a){var b=a.mustache,c=a.program,d=a.inverse;c&&(c=this.compileProgram(c)),d&&(d=this.compileProgram(d));var e=b.sexpr,f=this.classifySexpr(e);"helper"===f?this.helperSexpr(e,c,d):"simple"===f?(this.simpleSexpr(e),this.opcode("pushProgram",c),this.opcode("pushProgram",d),this.opcode("emptyHash"),this.opcode("blockValue",e.id.original)):(this.ambiguousSexpr(e,c,d),this.opcode("pushProgram",c),this.opcode("pushProgram",d),this.opcode("emptyHash"),this.opcode("ambiguousBlockValue")),this.opcode("append")},hash:function(a){var b,c,d=a.pairs;for(this.opcode("pushHash"),b=0,c=d.length;c>b;b++)this.pushParam(d[b][1]);for(;b--;)this.opcode("assignToHash",d[b][0]);this.opcode("popHash")},partial:function(a){var b=a.partialName;this.usePartial=!0,a.hash?this.accept(a.hash):this.opcode("push","undefined"),a.context?this.accept(a.context):(this.opcode("getContext",0),this.opcode("pushContext")),this.opcode("invokePartial",b.name,a.indent||""),this.opcode("append")},content:function(a){a.string&&this.opcode("appendContent",a.string)},mustache:function(a){this.sexpr(a.sexpr),a.escaped&&!this.options.noEscape?this.opcode("appendEscaped"):this.opcode("append")},ambiguousSexpr:function(a,b,c){var d=a.id,e=d.parts[0],f=null!=b||null!=c;this.opcode("getContext",d.depth),this.opcode("pushProgram",b),this.opcode("pushProgram",c),this.ID(d),this.opcode("invokeAmbiguous",e,f)},simpleSexpr:function(a){var b=a.id;"DATA"===b.type?this.DATA(b):b.parts.length?this.ID(b):(this.addDepth(b.depth),this.opcode("getContext",b.depth),this.opcode("pushContext")),this.opcode("resolvePossibleLambda")},helperSexpr:function(a,b,c){var d=this.setupFullMustacheParams(a,b,c),e=a.id,f=e.parts[0];if(this.options.knownHelpers[f])this.opcode("invokeKnownHelper",d.length,f);else{if(this.options.knownHelpersOnly)throw new h("You specified knownHelpersOnly, but used the unknown helper "+f,a);e.falsy=!0,this.ID(e),this.opcode("invokeHelper",d.length,e.original,e.isSimple)}},sexpr:function(a){var b=this.classifySexpr(a);"simple"===b?this.simpleSexpr(a):"helper"===b?this.helperSexpr(a):this.ambiguousSexpr(a)},ID:function(a){this.addDepth(a.depth),this.opcode("getContext",a.depth);var b=a.parts[0];b?this.opcode("lookupOnContext",a.parts,a.falsy,a.isScoped):this.opcode("pushContext")},DATA:function(a){this.options.data=!0,this.opcode("lookupData",a.id.depth,a.id.parts)},STRING:function(a){this.opcode("pushString",a.string)},NUMBER:function(a){this.opcode("pushLiteral",a.number)},BOOLEAN:function(a){this.opcode("pushLiteral",a.bool)},comment:function(){},opcode:function(a){this.opcodes.push({opcode:a,args:j.call(arguments,1)})},addDepth:function(a){0!==a&&(this.depths[a]||(this.depths[a]=!0,this.depths.list.push(a)))},classifySexpr:function(a){var b=a.isHelper,c=a.eligibleHelper,d=this.options;if(c&&!b){var e=a.id.parts[0];d.knownHelpers[e]?b=!0:d.knownHelpersOnly&&(c=!1)}return b?"helper":c?"ambiguous":"simple"},pushParams:function(a){for(var b=0,c=a.length;c>b;b++)this.pushParam(a[b])},pushParam:function(a){this.stringParams?(a.depth&&this.addDepth(a.depth),this.opcode("getContext",a.depth||0),this.opcode("pushStringParam",a.stringModeValue,a.type),"sexpr"===a.type&&this.sexpr(a)):(this.trackIds&&this.opcode("pushId",a.type,a.idName||a.stringModeValue),this.accept(a))},setupFullMustacheParams:function(a,b,c){var d=a.params;return this.pushParams(d),this.opcode("pushProgram",b),this.opcode("pushProgram",c),a.hash?this.hash(a.hash):this.opcode("emptyHash"),d}},g.precompile=d,g.compile=e,g}(c,b),l=function(a,b){"use strict";function c(a){this.value=a}function d(){}var e,f=a.COMPILER_REVISION,g=a.REVISION_CHANGES,h=b;d.prototype={nameLookup:function(a,b){return d.isValidJavaScriptVariableName(b)?a+"."+b:a+"['"+b+"']"},depthedLookup:function(a){return this.aliases.lookup="this.lookup",'lookup(depths, "'+a+'")'},compilerInfo:function(){var a=f,b=g[a];return[a,b]},appendToBuffer:function(a){return this.environment.isSimple?"return "+a+";":{appendToBuffer:!0,content:a,toString:function(){return"buffer += "+a+";"}}},initializeBuffer:function(){return this.quotedString("")},namespace:"Handlebars",compile:function(a,b,c,d){this.environment=a,this.options=b,this.stringParams=this.options.stringParams,this.trackIds=this.options.trackIds,this.precompile=!d,this.name=this.environment.name,this.isChild=!!c,this.context=c||{programs:[],environments:[]},this.preamble(),this.stackSlot=0,this.stackVars=[],this.aliases={},this.registers={list:[]},this.hashes=[],this.compileStack=[],this.inlineStack=[],this.compileChildren(a,b),this.useDepths=this.useDepths||a.depths.list.length||this.options.compat;var e,f,g,i=a.opcodes;for(f=0,g=i.length;g>f;f++)e=i[f],this[e.opcode].apply(this,e.args);if(this.pushSource(""),this.stackSlot||this.inlineStack.length||this.compileStack.length)throw new h("Compile completed with content left on stack");var j=this.createFunctionContext(d);if(this.isChild)return j;var k={compiler:this.compilerInfo(),main:j},l=this.context.programs;for(f=0,g=l.length;g>f;f++)l[f]&&(k[f]=l[f]);return this.environment.usePartial&&(k.usePartial=!0),this.options.data&&(k.useData=!0),this.useDepths&&(k.useDepths=!0),this.options.compat&&(k.compat=!0),d||(k.compiler=JSON.stringify(k.compiler),k=this.objectLiteral(k)),k},preamble:function(){this.lastContext=0,this.source=[]},createFunctionContext:function(a){var b="",c=this.stackVars.concat(this.registers.list);c.length>0&&(b+=", "+c.join(", "));for(var d in this.aliases)this.aliases.hasOwnProperty(d)&&(b+=", "+d+"="+this.aliases[d]);var e=["depth0","helpers","partials","data"];this.useDepths&&e.push("depths");var f=this.mergeSource(b);return a?(e.push(f),Function.apply(this,e)):"function("+e.join(",")+") {\n "+f+"}"},mergeSource:function(a){for(var b,c,d="",e=!this.forceBuffer,f=0,g=this.source.length;g>f;f++){var h=this.source[f];h.appendToBuffer?b=b?b+"\n + "+h.content:h.content:(b&&(d?d+="buffer += "+b+";\n ":(c=!0,d=b+";\n "),b=void 0),d+=h+"\n ",this.environment.isSimple||(e=!1))}return e?(b||!d)&&(d+="return "+(b||'""')+";\n"):(a+=", buffer = "+(c?"":this.initializeBuffer()),d+=b?"return buffer + "+b+";\n":"return buffer;\n"),a&&(d="var "+a.substring(2)+(c?"":";\n ")+d),d},blockValue:function(a){this.aliases.blockHelperMissing="helpers.blockHelperMissing";var b=[this.contextName(0)];this.setupParams(a,0,b);var c=this.popStack();b.splice(1,0,c),this.push("blockHelperMissing.call("+b.join(", ")+")")},ambiguousBlockValue:function(){this.aliases.blockHelperMissing="helpers.blockHelperMissing";var a=[this.contextName(0)];this.setupParams("",0,a,!0),this.flushInline();var b=this.topStack();a.splice(1,0,b),this.pushSource("if (!"+this.lastHelper+") { "+b+" = blockHelperMissing.call("+a.join(", ")+"); }")},appendContent:function(a){this.pendingContent&&(a=this.pendingContent+a),this.pendingContent=a},append:function(){this.flushInline();var a=this.popStack();this.pushSource("if ("+a+" != null) { "+this.appendToBuffer(a)+" }"),this.environment.isSimple&&this.pushSource("else { "+this.appendToBuffer("''")+" }")},appendEscaped:function(){this.aliases.escapeExpression="this.escapeExpression",this.pushSource(this.appendToBuffer("escapeExpression("+this.popStack()+")"))},getContext:function(a){this.lastContext=a},pushContext:function(){this.pushStackLiteral(this.contextName(this.lastContext))},lookupOnContext:function(a,b,c){var d=0,e=a.length;for(c||!this.options.compat||this.lastContext?this.pushContext():this.push(this.depthedLookup(a[d++]));e>d;d++)this.replaceStack(function(c){var e=this.nameLookup(c,a[d],"context");return b?" && "+e:" != null ? "+e+" : "+c})},lookupData:function(a,b){a?this.pushStackLiteral("this.data(data, "+a+")"):this.pushStackLiteral("data");for(var c=b.length,d=0;c>d;d++)this.replaceStack(function(a){return" && "+this.nameLookup(a,b[d],"data")})},resolvePossibleLambda:function(){this.aliases.lambda="this.lambda",this.push("lambda("+this.popStack()+", "+this.contextName(0)+")")},pushStringParam:function(a,b){this.pushContext(),this.pushString(b),"sexpr"!==b&&("string"==typeof a?this.pushString(a):this.pushStackLiteral(a))},emptyHash:function(){this.pushStackLiteral("{}"),this.trackIds&&this.push("{}"),this.stringParams&&(this.push("{}"),this.push("{}"))},pushHash:function(){this.hash&&this.hashes.push(this.hash),this.hash={values:[],types:[],contexts:[],ids:[]}},popHash:function(){var a=this.hash;this.hash=this.hashes.pop(),this.trackIds&&this.push("{"+a.ids.join(",")+"}"),this.stringParams&&(this.push("{"+a.contexts.join(",")+"}"),this.push("{"+a.types.join(",")+"}")),this.push("{\n "+a.values.join(",\n ")+"\n }")},pushString:function(a){this.pushStackLiteral(this.quotedString(a))},push:function(a){return this.inlineStack.push(a),a},pushLiteral:function(a){this.pushStackLiteral(a)},pushProgram:function(a){null!=a?this.pushStackLiteral(this.programExpression(a)):this.pushStackLiteral(null)},invokeHelper:function(a,b,c){this.aliases.helperMissing="helpers.helperMissing";var d=this.popStack(),e=this.setupHelper(a,b),f=(c?e.name+" || ":"")+d+" || helperMissing";this.push("(("+f+").call("+e.callParams+"))")},invokeKnownHelper:function(a,b){var c=this.setupHelper(a,b);this.push(c.name+".call("+c.callParams+")")},invokeAmbiguous:function(a,b){this.aliases.functionType='"function"',this.aliases.helperMissing="helpers.helperMissing",this.useRegister("helper");var c=this.popStack();this.emptyHash();var d=this.setupHelper(0,a,b),e=this.lastHelper=this.nameLookup("helpers",a,"helper");this.push("((helper = (helper = "+e+" || "+c+") != null ? helper : helperMissing"+(d.paramsInit?"),("+d.paramsInit:"")+"),(typeof helper === functionType ? helper.call("+d.callParams+") : helper))")},invokePartial:function(a,b){var c=[this.nameLookup("partials",a,"partial"),"'"+b+"'","'"+a+"'",this.popStack(),this.popStack(),"helpers","partials"];this.options.data?c.push("data"):this.options.compat&&c.push("undefined"),this.options.compat&&c.push("depths"),this.push("this.invokePartial("+c.join(", ")+")")},assignToHash:function(a){var b,c,d,e=this.popStack();this.trackIds&&(d=this.popStack()),this.stringParams&&(c=this.popStack(),b=this.popStack());var f=this.hash;b&&f.contexts.push("'"+a+"': "+b),c&&f.types.push("'"+a+"': "+c),d&&f.ids.push("'"+a+"': "+d),f.values.push("'"+a+"': ("+e+")")},pushId:function(a,b){"ID"===a||"DATA"===a?this.pushString(b):"sexpr"===a?this.pushStackLiteral("true"):this.pushStackLiteral("null")},compiler:d,compileChildren:function(a,b){for(var c,d,e=a.children,f=0,g=e.length;g>f;f++){c=e[f],d=new this.compiler;var h=this.matchExistingProgram(c);null==h?(this.context.programs.push(""),h=this.context.programs.length,c.index=h,c.name="program"+h,this.context.programs[h]=d.compile(c,b,this.context,!this.precompile),this.context.environments[h]=c,this.useDepths=this.useDepths||d.useDepths):(c.index=h,c.name="program"+h)}},matchExistingProgram:function(a){for(var b=0,c=this.context.environments.length;c>b;b++){var d=this.context.environments[b];if(d&&d.equals(a))return b}},programExpression:function(a){var b=this.environment.children[a],c=(b.depths.list,this.useDepths),d=[b.index,"data"];return c&&d.push("depths"),"this.program("+d.join(", ")+")"},useRegister:function(a){this.registers[a]||(this.registers[a]=!0,this.registers.list.push(a))},pushStackLiteral:function(a){return this.push(new c(a))},pushSource:function(a){this.pendingContent&&(this.source.push(this.appendToBuffer(this.quotedString(this.pendingContent))),this.pendingContent=void 0),a&&this.source.push(a)},pushStack:function(a){this.flushInline();var b=this.incrStack();return this.pushSource(b+" = "+a+";"),this.compileStack.push(b),b},replaceStack:function(a){{var b,d,e,f="";this.isInline()}if(!this.isInline())throw new h("replaceStack on non-inline");var g=this.popStack(!0);if(g instanceof c)f=b=g.value,e=!0;else{d=!this.stackSlot;var i=d?this.incrStack():this.topStackName();f="("+this.push(i)+" = "+g+")",b=this.topStack()}var j=a.call(this,b);e||this.popStack(),d&&this.stackSlot--,this.push("("+f+j+")")},incrStack:function(){return this.stackSlot++,this.stackSlot>this.stackVars.length&&this.stackVars.push("stack"+this.stackSlot),this.topStackName()},topStackName:function(){return"stack"+this.stackSlot},flushInline:function(){var a=this.inlineStack;if(a.length){this.inlineStack=[];for(var b=0,d=a.length;d>b;b++){var e=a[b];e instanceof c?this.compileStack.push(e):this.pushStack(e)}}},isInline:function(){return this.inlineStack.length},popStack:function(a){var b=this.isInline(),d=(b?this.inlineStack:this.compileStack).pop();if(!a&&d instanceof c)return d.value;if(!b){if(!this.stackSlot)throw new h("Invalid stack pop");this.stackSlot--}return d},topStack:function(){var a=this.isInline()?this.inlineStack:this.compileStack,b=a[a.length-1];return b instanceof c?b.value:b},contextName:function(a){return this.useDepths&&a?"depths["+a+"]":"depth"+a},quotedString:function(a){return'"'+a.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")+'"'},objectLiteral:function(a){var b=[];for(var c in a)a.hasOwnProperty(c)&&b.push(this.quotedString(c)+":"+a[c]);return"{"+b.join(",")+"}"},setupHelper:function(a,b,c){var d=[],e=this.setupParams(b,a,d,c),f=this.nameLookup("helpers",b,"helper");return{params:d,paramsInit:e,name:f,callParams:[this.contextName(0)].concat(d).join(", ")}},setupOptions:function(a,b,c){var d,e,f,g={},h=[],i=[],j=[];g.name=this.quotedString(a),g.hash=this.popStack(),this.trackIds&&(g.hashIds=this.popStack()),this.stringParams&&(g.hashTypes=this.popStack(),g.hashContexts=this.popStack()),e=this.popStack(),f=this.popStack(),(f||e)&&(f||(f="this.noop"),e||(e="this.noop"),g.fn=f,g.inverse=e);for(var k=b;k--;)d=this.popStack(),c[k]=d,this.trackIds&&(j[k]=this.popStack()),this.stringParams&&(i[k]=this.popStack(),h[k]=this.popStack());return this.trackIds&&(g.ids="["+j.join(",")+"]"),this.stringParams&&(g.types="["+i.join(",")+"]",g.contexts="["+h.join(",")+"]"),this.options.data&&(g.data="data"),g},setupParams:function(a,b,c,d){var e=this.objectLiteral(this.setupOptions(a,b,c));return d?(this.useRegister("options"),c.push("options"),"options="+e):(c.push(e),"")}};for(var i="break else new var case finally return void catch for switch while continue function this with default if throw delete in try do instanceof typeof abstract enum int short boolean export interface static byte extends long super char final native synchronized class float package throws const goto private transient debugger implements protected volatile double import public let yield".split(" "),j=d.RESERVED_WORDS={},k=0,l=i.length;l>k;k++)j[i[k]]=!0;return d.isValidJavaScriptVariableName=function(a){return!d.RESERVED_WORDS[a]&&/^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(a)},e=d}(d,c),m=function(a,b,c,d,e){"use strict";var f,g=a,h=b,i=c.parser,j=c.parse,k=d.Compiler,l=d.compile,m=d.precompile,n=e,o=g.create,p=function(){var a=o();return a.compile=function(b,c){return l(b,c,a)},a.precompile=function(b,c){return m(b,c,a)},a.AST=h,a.Compiler=k,a.JavaScriptCompiler=n,a.Parser=i,a.parse=j,a};return g=p(),g.create=p,g["default"]=g,f=g}(f,g,j,k,l);return m}); \ No newline at end of file
diff --git a/catalog-be/src/main/resources/swagger/lib/highlight.7.3.pack.js b/catalog-be/src/main/resources/swagger/lib/highlight.7.3.pack.js
index a61ad222c2..9a95a75ea1 100644
--- a/catalog-be/src/main/resources/swagger/lib/highlight.7.3.pack.js
+++ b/catalog-be/src/main/resources/swagger/lib/highlight.7.3.pack.js
@@ -1,21 +1 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-var hljs=new function(){function l(o){return o.replace(/&/gm,"&amp;").replace(/</gm,"&lt;").replace(/>/gm,"&gt;")}function b(p){for(var o=p.firstChild;o;o=o.nextSibling){if(o.nodeName=="CODE"){return o}if(!(o.nodeType==3&&o.nodeValue.match(/\s+/))){break}}}function h(p,o){return Array.prototype.map.call(p.childNodes,function(q){if(q.nodeType==3){return o?q.nodeValue.replace(/\n/g,""):q.nodeValue}if(q.nodeName=="BR"){return"\n"}return h(q,o)}).join("")}function a(q){var p=(q.className+" "+q.parentNode.className).split(/\s+/);p=p.map(function(r){return r.replace(/^language-/,"")});for(var o=0;o<p.length;o++){if(e[p[o]]||p[o]=="no-highlight"){return p[o]}}}function c(q){var o=[];(function p(r,s){for(var t=r.firstChild;t;t=t.nextSibling){if(t.nodeType==3){s+=t.nodeValue.length}else{if(t.nodeName=="BR"){s+=1}else{if(t.nodeType==1){o.push({event:"start",offset:s,node:t});s=p(t,s);o.push({event:"stop",offset:s,node:t})}}}}return s})(q,0);return o}function j(x,v,w){var p=0;var y="";var r=[];function t(){if(x.length&&v.length){if(x[0].offset!=v[0].offset){return(x[0].offset<v[0].offset)?x:v}else{return v[0].event=="start"?x:v}}else{return x.length?x:v}}function s(A){function z(B){return" "+B.nodeName+'="'+l(B.value)+'"'}return"<"+A.nodeName+Array.prototype.map.call(A.attributes,z).join("")+">"}while(x.length||v.length){var u=t().splice(0,1)[0];y+=l(w.substr(p,u.offset-p));p=u.offset;if(u.event=="start"){y+=s(u.node);r.push(u.node)}else{if(u.event=="stop"){var o,q=r.length;do{q--;o=r[q];y+=("</"+o.nodeName.toLowerCase()+">")}while(o!=u.node);r.splice(q,1);while(q<r.length){y+=s(r[q]);q++}}}}return y+l(w.substr(p))}function f(q){function o(s,r){return RegExp(s,"m"+(q.cI?"i":"")+(r?"g":""))}function p(y,w){if(y.compiled){return}y.compiled=true;var s=[];if(y.k){var r={};function z(A,t){t.split(" ").forEach(function(B){var C=B.split("|");r[C[0]]=[A,C[1]?Number(C[1]):1];s.push(C[0])})}y.lR=o(y.l||hljs.IR,true);if(typeof y.k=="string"){z("keyword",y.k)}else{for(var x in y.k){if(!y.k.hasOwnProperty(x)){continue}z(x,y.k[x])}}y.k=r}if(w){if(y.bWK){y.b="\\b("+s.join("|")+")\\s"}y.bR=o(y.b?y.b:"\\B|\\b");if(!y.e&&!y.eW){y.e="\\B|\\b"}if(y.e){y.eR=o(y.e)}y.tE=y.e||"";if(y.eW&&w.tE){y.tE+=(y.e?"|":"")+w.tE}}if(y.i){y.iR=o(y.i)}if(y.r===undefined){y.r=1}if(!y.c){y.c=[]}for(var v=0;v<y.c.length;v++){if(y.c[v]=="self"){y.c[v]=y}p(y.c[v],y)}if(y.starts){p(y.starts,w)}var u=[];for(var v=0;v<y.c.length;v++){u.push(y.c[v].b)}if(y.tE){u.push(y.tE)}if(y.i){u.push(y.i)}y.t=u.length?o(u.join("|"),true):{exec:function(t){return null}}}p(q)}function d(D,E){function o(r,M){for(var L=0;L<M.c.length;L++){var K=M.c[L].bR.exec(r);if(K&&K.index==0){return M.c[L]}}}function s(K,r){if(K.e&&K.eR.test(r)){return K}if(K.eW){return s(K.parent,r)}}function t(r,K){return K.i&&K.iR.test(r)}function y(L,r){var K=F.cI?r[0].toLowerCase():r[0];return L.k.hasOwnProperty(K)&&L.k[K]}function G(){var K=l(w);if(!A.k){return K}var r="";var N=0;A.lR.lastIndex=0;var L=A.lR.exec(K);while(L){r+=K.substr(N,L.index-N);var M=y(A,L);if(M){v+=M[1];r+='<span class="'+M[0]+'">'+L[0]+"</span>"}else{r+=L[0]}N=A.lR.lastIndex;L=A.lR.exec(K)}return r+K.substr(N)}function z(){if(A.sL&&!e[A.sL]){return l(w)}var r=A.sL?d(A.sL,w):g(w);if(A.r>0){v+=r.keyword_count;B+=r.r}return'<span class="'+r.language+'">'+r.value+"</span>"}function J(){return A.sL!==undefined?z():G()}function I(L,r){var K=L.cN?'<span class="'+L.cN+'">':"";if(L.rB){x+=K;w=""}else{if(L.eB){x+=l(r)+K;w=""}else{x+=K;w=r}}A=Object.create(L,{parent:{value:A}});B+=L.r}function C(K,r){w+=K;if(r===undefined){x+=J();return 0}var L=o(r,A);if(L){x+=J();I(L,r);return L.rB?0:r.length}var M=s(A,r);if(M){if(!(M.rE||M.eE)){w+=r}x+=J();do{if(A.cN){x+="</span>"}A=A.parent}while(A!=M.parent);if(M.eE){x+=l(r)}w="";if(M.starts){I(M.starts,"")}return M.rE?0:r.length}if(t(r,A)){throw"Illegal"}w+=r;return r.length||1}var F=e[D];f(F);var A=F;var w="";var B=0;var v=0;var x="";try{var u,q,p=0;while(true){A.t.lastIndex=p;u=A.t.exec(E);if(!u){break}q=C(E.substr(p,u.index-p),u[0]);p=u.index+q}C(E.substr(p));return{r:B,keyword_count:v,value:x,language:D}}catch(H){if(H=="Illegal"){return{r:0,keyword_count:0,value:l(E)}}else{throw H}}}function g(s){var o={keyword_count:0,r:0,value:l(s)};var q=o;for(var p in e){if(!e.hasOwnProperty(p)){continue}var r=d(p,s);r.language=p;if(r.keyword_count+r.r>q.keyword_count+q.r){q=r}if(r.keyword_count+r.r>o.keyword_count+o.r){q=o;o=r}}if(q.language){o.second_best=q}return o}function i(q,p,o){if(p){q=q.replace(/^((<[^>]+>|\t)+)/gm,function(r,v,u,t){return v.replace(/\t/g,p)})}if(o){q=q.replace(/\n/g,"<br>")}return q}function m(r,u,p){var v=h(r,p);var t=a(r);if(t=="no-highlight"){return}var w=t?d(t,v):g(v);t=w.language;var o=c(r);if(o.length){var q=document.createElement("pre");q.innerHTML=w.value;w.value=j(o,c(q),v)}w.value=i(w.value,u,p);var s=r.className;if(!s.match("(\\s|^)(language-)?"+t+"(\\s|$)")){s=s?(s+" "+t):t}r.innerHTML=w.value;r.className=s;r.result={language:t,kw:w.keyword_count,re:w.r};if(w.second_best){r.second_best={language:w.second_best.language,kw:w.second_best.keyword_count,re:w.second_best.r}}}function n(){if(n.called){return}n.called=true;Array.prototype.map.call(document.getElementsByTagName("pre"),b).filter(Boolean).forEach(function(o){m(o,hljs.tabReplace)})}function k(){window.addEventListener("DOMContentLoaded",n,false);window.addEventListener("load",n,false)}var e={};this.LANGUAGES=e;this.highlight=d;this.highlightAuto=g;this.fixMarkup=i;this.highlightBlock=m;this.initHighlighting=n;this.initHighlightingOnLoad=k;this.IR="[a-zA-Z][a-zA-Z0-9_]*";this.UIR="[a-zA-Z_][a-zA-Z0-9_]*";this.NR="\\b\\d+(\\.\\d+)?";this.CNR="(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)";this.BNR="\\b(0b[01]+)";this.RSR="!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|\\.|-|-=|/|/=|:|;|<|<<|<<=|<=|=|==|===|>|>=|>>|>>=|>>>|>>>=|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~";this.BE={b:"\\\\[\\s\\S]",r:0};this.ASM={cN:"string",b:"'",e:"'",i:"\\n",c:[this.BE],r:0};this.QSM={cN:"string",b:'"',e:'"',i:"\\n",c:[this.BE],r:0};this.CLCM={cN:"comment",b:"//",e:"$"};this.CBLCLM={cN:"comment",b:"/\\*",e:"\\*/"};this.HCM={cN:"comment",b:"#",e:"$"};this.NM={cN:"number",b:this.NR,r:0};this.CNM={cN:"number",b:this.CNR,r:0};this.BNM={cN:"number",b:this.BNR,r:0};this.inherit=function(q,r){var o={};for(var p in q){o[p]=q[p]}if(r){for(var p in r){o[p]=r[p]}}return o}}();hljs.LANGUAGES.xml=function(a){var c="[A-Za-z0-9\\._:-]+";var b={eW:true,c:[{cN:"attribute",b:c,r:0},{b:'="',rB:true,e:'"',c:[{cN:"value",b:'"',eW:true}]},{b:"='",rB:true,e:"'",c:[{cN:"value",b:"'",eW:true}]},{b:"=",c:[{cN:"value",b:"[^\\s/>]+"}]}]};return{cI:true,c:[{cN:"pi",b:"<\\?",e:"\\?>",r:10},{cN:"doctype",b:"<!DOCTYPE",e:">",r:10,c:[{b:"\\[",e:"\\]"}]},{cN:"comment",b:"<!--",e:"-->",r:10},{cN:"cdata",b:"<\\!\\[CDATA\\[",e:"\\]\\]>",r:10},{cN:"tag",b:"<style(?=\\s|>|$)",e:">",k:{title:"style"},c:[b],starts:{e:"</style>",rE:true,sL:"css"}},{cN:"tag",b:"<script(?=\\s|>|$)",e:">",k:{title:"script"},c:[b],starts:{e:"<\/script>",rE:true,sL:"javascript"}},{b:"<%",e:"%>",sL:"vbscript"},{cN:"tag",b:"</?",e:"/?>",c:[{cN:"title",b:"[^ />]+"},b]}]}}(hljs);hljs.LANGUAGES.json=function(a){var e={literal:"true false null"};var d=[a.QSM,a.CNM];var c={cN:"value",e:",",eW:true,eE:true,c:d,k:e};var b={b:"{",e:"}",c:[{cN:"attribute",b:'\\s*"',e:'"\\s*:\\s*',eB:true,eE:true,c:[a.BE],i:"\\n",starts:c}],i:"\\S"};var f={b:"\\[",e:"\\]",c:[a.inherit(c,{cN:null})],i:"\\S"};d.splice(d.length,0,b,f);return{c:d,k:e,i:"\\S"}}(hljs);
+var hljs=new function(){function l(o){return o.replace(/&/gm,"&amp;").replace(/</gm,"&lt;").replace(/>/gm,"&gt;")}function b(p){for(var o=p.firstChild;o;o=o.nextSibling){if(o.nodeName=="CODE"){return o}if(!(o.nodeType==3&&o.nodeValue.match(/\s+/))){break}}}function h(p,o){return Array.prototype.map.call(p.childNodes,function(q){if(q.nodeType==3){return o?q.nodeValue.replace(/\n/g,""):q.nodeValue}if(q.nodeName=="BR"){return"\n"}return h(q,o)}).join("")}function a(q){var p=(q.className+" "+q.parentNode.className).split(/\s+/);p=p.map(function(r){return r.replace(/^language-/,"")});for(var o=0;o<p.length;o++){if(e[p[o]]||p[o]=="no-highlight"){return p[o]}}}function c(q){var o=[];(function p(r,s){for(var t=r.firstChild;t;t=t.nextSibling){if(t.nodeType==3){s+=t.nodeValue.length}else{if(t.nodeName=="BR"){s+=1}else{if(t.nodeType==1){o.push({event:"start",offset:s,node:t});s=p(t,s);o.push({event:"stop",offset:s,node:t})}}}}return s})(q,0);return o}function j(x,v,w){var p=0;var y="";var r=[];function t(){if(x.length&&v.length){if(x[0].offset!=v[0].offset){return(x[0].offset<v[0].offset)?x:v}else{return v[0].event=="start"?x:v}}else{return x.length?x:v}}function s(A){function z(B){return" "+B.nodeName+'="'+l(B.value)+'"'}return"<"+A.nodeName+Array.prototype.map.call(A.attributes,z).join("")+">"}while(x.length||v.length){var u=t().splice(0,1)[0];y+=l(w.substr(p,u.offset-p));p=u.offset;if(u.event=="start"){y+=s(u.node);r.push(u.node)}else{if(u.event=="stop"){var o,q=r.length;do{q--;o=r[q];y+=("</"+o.nodeName.toLowerCase()+">")}while(o!=u.node);r.splice(q,1);while(q<r.length){y+=s(r[q]);q++}}}}return y+l(w.substr(p))}function f(q){function o(s,r){return RegExp(s,"m"+(q.cI?"i":"")+(r?"g":""))}function p(y,w){if(y.compiled){return}y.compiled=true;var s=[];if(y.k){var r={};function z(A,t){t.split(" ").forEach(function(B){var C=B.split("|");r[C[0]]=[A,C[1]?Number(C[1]):1];s.push(C[0])})}y.lR=o(y.l||hljs.IR,true);if(typeof y.k=="string"){z("keyword",y.k)}else{for(var x in y.k){if(!y.k.hasOwnProperty(x)){continue}z(x,y.k[x])}}y.k=r}if(w){if(y.bWK){y.b="\\b("+s.join("|")+")\\s"}y.bR=o(y.b?y.b:"\\B|\\b");if(!y.e&&!y.eW){y.e="\\B|\\b"}if(y.e){y.eR=o(y.e)}y.tE=y.e||"";if(y.eW&&w.tE){y.tE+=(y.e?"|":"")+w.tE}}if(y.i){y.iR=o(y.i)}if(y.r===undefined){y.r=1}if(!y.c){y.c=[]}for(var v=0;v<y.c.length;v++){if(y.c[v]=="self"){y.c[v]=y}p(y.c[v],y)}if(y.starts){p(y.starts,w)}var u=[];for(var v=0;v<y.c.length;v++){u.push(y.c[v].b)}if(y.tE){u.push(y.tE)}if(y.i){u.push(y.i)}y.t=u.length?o(u.join("|"),true):{exec:function(t){return null}}}p(q)}function d(D,E){function o(r,M){for(var L=0;L<M.c.length;L++){var K=M.c[L].bR.exec(r);if(K&&K.index==0){return M.c[L]}}}function s(K,r){if(K.e&&K.eR.test(r)){return K}if(K.eW){return s(K.parent,r)}}function t(r,K){return K.i&&K.iR.test(r)}function y(L,r){var K=F.cI?r[0].toLowerCase():r[0];return L.k.hasOwnProperty(K)&&L.k[K]}function G(){var K=l(w);if(!A.k){return K}var r="";var N=0;A.lR.lastIndex=0;var L=A.lR.exec(K);while(L){r+=K.substr(N,L.index-N);var M=y(A,L);if(M){v+=M[1];r+='<span class="'+M[0]+'">'+L[0]+"</span>"}else{r+=L[0]}N=A.lR.lastIndex;L=A.lR.exec(K)}return r+K.substr(N)}function z(){if(A.sL&&!e[A.sL]){return l(w)}var r=A.sL?d(A.sL,w):g(w);if(A.r>0){v+=r.keyword_count;B+=r.r}return'<span class="'+r.language+'">'+r.value+"</span>"}function J(){return A.sL!==undefined?z():G()}function I(L,r){var K=L.cN?'<span class="'+L.cN+'">':"";if(L.rB){x+=K;w=""}else{if(L.eB){x+=l(r)+K;w=""}else{x+=K;w=r}}A=Object.create(L,{parent:{value:A}});B+=L.r}function C(K,r){w+=K;if(r===undefined){x+=J();return 0}var L=o(r,A);if(L){x+=J();I(L,r);return L.rB?0:r.length}var M=s(A,r);if(M){if(!(M.rE||M.eE)){w+=r}x+=J();do{if(A.cN){x+="</span>"}A=A.parent}while(A!=M.parent);if(M.eE){x+=l(r)}w="";if(M.starts){I(M.starts,"")}return M.rE?0:r.length}if(t(r,A)){throw"Illegal"}w+=r;return r.length||1}var F=e[D];f(F);var A=F;var w="";var B=0;var v=0;var x="";try{var u,q,p=0;while(true){A.t.lastIndex=p;u=A.t.exec(E);if(!u){break}q=C(E.substr(p,u.index-p),u[0]);p=u.index+q}C(E.substr(p));return{r:B,keyword_count:v,value:x,language:D}}catch(H){if(H=="Illegal"){return{r:0,keyword_count:0,value:l(E)}}else{throw H}}}function g(s){var o={keyword_count:0,r:0,value:l(s)};var q=o;for(var p in e){if(!e.hasOwnProperty(p)){continue}var r=d(p,s);r.language=p;if(r.keyword_count+r.r>q.keyword_count+q.r){q=r}if(r.keyword_count+r.r>o.keyword_count+o.r){q=o;o=r}}if(q.language){o.second_best=q}return o}function i(q,p,o){if(p){q=q.replace(/^((<[^>]+>|\t)+)/gm,function(r,v,u,t){return v.replace(/\t/g,p)})}if(o){q=q.replace(/\n/g,"<br>")}return q}function m(r,u,p){var v=h(r,p);var t=a(r);if(t=="no-highlight"){return}var w=t?d(t,v):g(v);t=w.language;var o=c(r);if(o.length){var q=document.createElement("pre");q.innerHTML=w.value;w.value=j(o,c(q),v)}w.value=i(w.value,u,p);var s=r.className;if(!s.match("(\\s|^)(language-)?"+t+"(\\s|$)")){s=s?(s+" "+t):t}r.innerHTML=w.value;r.className=s;r.result={language:t,kw:w.keyword_count,re:w.r};if(w.second_best){r.second_best={language:w.second_best.language,kw:w.second_best.keyword_count,re:w.second_best.r}}}function n(){if(n.called){return}n.called=true;Array.prototype.map.call(document.getElementsByTagName("pre"),b).filter(Boolean).forEach(function(o){m(o,hljs.tabReplace)})}function k(){window.addEventListener("DOMContentLoaded",n,false);window.addEventListener("load",n,false)}var e={};this.LANGUAGES=e;this.highlight=d;this.highlightAuto=g;this.fixMarkup=i;this.highlightBlock=m;this.initHighlighting=n;this.initHighlightingOnLoad=k;this.IR="[a-zA-Z][a-zA-Z0-9_]*";this.UIR="[a-zA-Z_][a-zA-Z0-9_]*";this.NR="\\b\\d+(\\.\\d+)?";this.CNR="(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)";this.BNR="\\b(0b[01]+)";this.RSR="!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|\\.|-|-=|/|/=|:|;|<|<<|<<=|<=|=|==|===|>|>=|>>|>>=|>>>|>>>=|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~";this.BE={b:"\\\\[\\s\\S]",r:0};this.ASM={cN:"string",b:"'",e:"'",i:"\\n",c:[this.BE],r:0};this.QSM={cN:"string",b:'"',e:'"',i:"\\n",c:[this.BE],r:0};this.CLCM={cN:"comment",b:"//",e:"$"};this.CBLCLM={cN:"comment",b:"/\\*",e:"\\*/"};this.HCM={cN:"comment",b:"#",e:"$"};this.NM={cN:"number",b:this.NR,r:0};this.CNM={cN:"number",b:this.CNR,r:0};this.BNM={cN:"number",b:this.BNR,r:0};this.inherit=function(q,r){var o={};for(var p in q){o[p]=q[p]}if(r){for(var p in r){o[p]=r[p]}}return o}}();hljs.LANGUAGES.xml=function(a){var c="[A-Za-z0-9\\._:-]+";var b={eW:true,c:[{cN:"attribute",b:c,r:0},{b:'="',rB:true,e:'"',c:[{cN:"value",b:'"',eW:true}]},{b:"='",rB:true,e:"'",c:[{cN:"value",b:"'",eW:true}]},{b:"=",c:[{cN:"value",b:"[^\\s/>]+"}]}]};return{cI:true,c:[{cN:"pi",b:"<\\?",e:"\\?>",r:10},{cN:"doctype",b:"<!DOCTYPE",e:">",r:10,c:[{b:"\\[",e:"\\]"}]},{cN:"comment",b:"<!--",e:"-->",r:10},{cN:"cdata",b:"<\\!\\[CDATA\\[",e:"\\]\\]>",r:10},{cN:"tag",b:"<style(?=\\s|>|$)",e:">",k:{title:"style"},c:[b],starts:{e:"</style>",rE:true,sL:"css"}},{cN:"tag",b:"<script(?=\\s|>|$)",e:">",k:{title:"script"},c:[b],starts:{e:"<\/script>",rE:true,sL:"javascript"}},{b:"<%",e:"%>",sL:"vbscript"},{cN:"tag",b:"</?",e:"/?>",c:[{cN:"title",b:"[^ />]+"},b]}]}}(hljs);hljs.LANGUAGES.json=function(a){var e={literal:"true false null"};var d=[a.QSM,a.CNM];var c={cN:"value",e:",",eW:true,eE:true,c:d,k:e};var b={b:"{",e:"}",c:[{cN:"attribute",b:'\\s*"',e:'"\\s*:\\s*',eB:true,eE:true,c:[a.BE],i:"\\n",starts:c}],i:"\\S"};var f={b:"\\[",e:"\\]",c:[a.inherit(c,{cN:null})],i:"\\S"};d.splice(d.length,0,b,f);return{c:d,k:e,i:"\\S"}}(hljs); \ No newline at end of file
diff --git a/catalog-be/src/main/resources/swagger/lib/jquery-1.8.0.min.js b/catalog-be/src/main/resources/swagger/lib/jquery-1.8.0.min.js
index 2ebc792d3a..066d72c7e3 100644
--- a/catalog-be/src/main/resources/swagger/lib/jquery-1.8.0.min.js
+++ b/catalog-be/src/main/resources/swagger/lib/jquery-1.8.0.min.js
@@ -1,22 +1,2 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
/*! jQuery v@1.8.0 jquery.com | jquery.org/license */
-(function(a,b){function G(a){var b=F[a]={};return p.each(a.split(s),function(a,c){b[c]=!0}),b}function J(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(I,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:+d+""===d?+d:H.test(d)?p.parseJSON(d):d}catch(f){}p.data(a,c,d)}else d=b}return d}function K(a){var b;for(b in a){if(b==="data"&&p.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function ba(){return!1}function bb(){return!0}function bh(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function bi(a,b){do a=a[b];while(a&&a.nodeType!==1);return a}function bj(a,b,c){b=b||0;if(p.isFunction(b))return p.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return p.grep(a,function(a,d){return a===b===c});if(typeof b=="string"){var d=p.grep(a,function(a){return a.nodeType===1});if(be.test(b))return p.filter(b,d,!c);b=p.filter(b,d)}return p.grep(a,function(a,d){return p.inArray(a,b)>=0===c})}function bk(a){var b=bl.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}function bC(a,b){return a.getElementsByTagName(b)[0]||a.appendChild(a.ownerDocument.createElement(b))}function bD(a,b){if(b.nodeType!==1||!p.hasData(a))return;var c,d,e,f=p._data(a),g=p._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;d<e;d++)p.event.add(b,c,h[c][d])}g.data&&(g.data=p.extend({},g.data))}function bE(a,b){var c;if(b.nodeType!==1)return;b.clearAttributes&&b.clearAttributes(),b.mergeAttributes&&b.mergeAttributes(a),c=b.nodeName.toLowerCase(),c==="object"?(b.parentNode&&(b.outerHTML=a.outerHTML),p.support.html5Clone&&a.innerHTML&&!p.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):c==="input"&&bv.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):c==="option"?b.selected=a.defaultSelected:c==="input"||c==="textarea"?b.defaultValue=a.defaultValue:c==="script"&&b.text!==a.text&&(b.text=a.text),b.removeAttribute(p.expando)}function bF(a){return typeof a.getElementsByTagName!="undefined"?a.getElementsByTagName("*"):typeof a.querySelectorAll!="undefined"?a.querySelectorAll("*"):[]}function bG(a){bv.test(a.type)&&(a.defaultChecked=a.checked)}function bX(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=bV.length;while(e--){b=bV[e]+c;if(b in a)return b}return d}function bY(a,b){return a=b||a,p.css(a,"display")==="none"||!p.contains(a.ownerDocument,a)}function bZ(a,b){var c,d,e=[],f=0,g=a.length;for(;f<g;f++){c=a[f];if(!c.style)continue;e[f]=p._data(c,"olddisplay"),b?(!e[f]&&c.style.display==="none"&&(c.style.display=""),c.style.display===""&&bY(c)&&(e[f]=p._data(c,"olddisplay",cb(c.nodeName)))):(d=bH(c,"display"),!e[f]&&d!=="none"&&p._data(c,"olddisplay",d))}for(f=0;f<g;f++){c=a[f];if(!c.style)continue;if(!b||c.style.display==="none"||c.style.display==="")c.style.display=b?e[f]||"":"none"}return a}function b$(a,b,c){var d=bO.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function b_(a,b,c,d){var e=c===(d?"border":"content")?4:b==="width"?1:0,f=0;for(;e<4;e+=2)c==="margin"&&(f+=p.css(a,c+bU[e],!0)),d?(c==="content"&&(f-=parseFloat(bH(a,"padding"+bU[e]))||0),c!=="margin"&&(f-=parseFloat(bH(a,"border"+bU[e]+"Width"))||0)):(f+=parseFloat(bH(a,"padding"+bU[e]))||0,c!=="padding"&&(f+=parseFloat(bH(a,"border"+bU[e]+"Width"))||0));return f}function ca(a,b,c){var d=b==="width"?a.offsetWidth:a.offsetHeight,e=!0,f=p.support.boxSizing&&p.css(a,"boxSizing")==="border-box";if(d<=0){d=bH(a,b);if(d<0||d==null)d=a.style[b];if(bP.test(d))return d;e=f&&(p.support.boxSizingReliable||d===a.style[b]),d=parseFloat(d)||0}return d+b_(a,b,c||(f?"border":"content"),e)+"px"}function cb(a){if(bR[a])return bR[a];var b=p("<"+a+">").appendTo(e.body),c=b.css("display");b.remove();if(c==="none"||c===""){bI=e.body.appendChild(bI||p.extend(e.createElement("iframe"),{frameBorder:0,width:0,height:0}));if(!bJ||!bI.createElement)bJ=(bI.contentWindow||bI.contentDocument).document,bJ.write("<!doctype html><html><body>"),bJ.close();b=bJ.body.appendChild(bJ.createElement(a)),c=bH(b,"display"),e.body.removeChild(bI)}return bR[a]=c,c}function ch(a,b,c,d){var e;if(p.isArray(b))p.each(b,function(b,e){c||cd.test(a)?d(a,e):ch(a+"["+(typeof e=="object"?b:"")+"]",e,c,d)});else if(!c&&p.type(b)==="object")for(e in b)ch(a+"["+e+"]",b[e],c,d);else d(a,b)}function cy(a){return function(b,c){typeof b!="string"&&(c=b,b="*");var d,e,f,g=b.toLowerCase().split(s),h=0,i=g.length;if(p.isFunction(c))for(;h<i;h++)d=g[h],f=/^\+/.test(d),f&&(d=d.substr(1)||"*"),e=a[d]=a[d]||[],e[f?"unshift":"push"](c)}}function cz(a,c,d,e,f,g){f=f||c.dataTypes[0],g=g||{},g[f]=!0;var h,i=a[f],j=0,k=i?i.length:0,l=a===cu;for(;j<k&&(l||!h);j++)h=i[j](c,d,e),typeof h=="string"&&(!l||g[h]?h=b:(c.dataTypes.unshift(h),h=cz(a,c,d,e,h,g)));return(l||!h)&&!g["*"]&&(h=cz(a,c,d,e,"*",g)),h}function cA(a,c){var d,e,f=p.ajaxSettings.flatOptions||{};for(d in c)c[d]!==b&&((f[d]?a:e||(e={}))[d]=c[d]);e&&p.extend(!0,a,e)}function cB(a,c,d){var e,f,g,h,i=a.contents,j=a.dataTypes,k=a.responseFields;for(f in k)f in d&&(c[k[f]]=d[f]);while(j[0]==="*")j.shift(),e===b&&(e=a.mimeType||c.getResponseHeader("content-type"));if(e)for(f in i)if(i[f]&&i[f].test(e)){j.unshift(f);break}if(j[0]in d)g=j[0];else{for(f in d){if(!j[0]||a.converters[f+" "+j[0]]){g=f;break}h||(h=f)}g=g||h}if(g)return g!==j[0]&&j.unshift(g),d[g]}function cC(a,b){var c,d,e,f,g=a.dataTypes.slice(),h=g[0],i={},j=0;a.dataFilter&&(b=a.dataFilter(b,a.dataType));if(g[1])for(c in a.converters)i[c.toLowerCase()]=a.converters[c];for(;e=g[++j];)if(e!=="*"){if(h!=="*"&&h!==e){c=i[h+" "+e]||i["* "+e];if(!c)for(d in i){f=d.split(" ");if(f[1]===e){c=i[h+" "+f[0]]||i["* "+f[0]];if(c){c===!0?c=i[d]:i[d]!==!0&&(e=f[0],g.splice(j--,0,e));break}}}if(c!==!0)if(c&&a["throws"])b=c(b);else try{b=c(b)}catch(k){return{state:"parsererror",error:c?k:"No conversion from "+h+" to "+e}}}h=e}return{state:"success",data:b}}function cK(){try{return new a.XMLHttpRequest}catch(b){}}function cL(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function cT(){return setTimeout(function(){cM=b},0),cM=p.now()}function cU(a,b){p.each(b,function(b,c){var d=(cS[b]||[]).concat(cS["*"]),e=0,f=d.length;for(;e<f;e++)if(d[e].call(a,b,c))return})}function cV(a,b,c){var d,e=0,f=0,g=cR.length,h=p.Deferred().always(function(){delete i.elem}),i=function(){var b=cM||cT(),c=Math.max(0,j.startTime+j.duration-b),d=1-(c/j.duration||0),e=0,f=j.tweens.length;for(;e<f;e++)j.tweens[e].run(d);return h.notifyWith(a,[j,d,c]),d<1&&f?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:p.extend({},b),opts:p.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:cM||cT(),duration:c.duration,tweens:[],createTween:function(b,c,d){var e=p.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(e),e},stop:function(b){var c=0,d=b?j.tweens.length:0;for(;c<d;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;cW(k,j.opts.specialEasing);for(;e<g;e++){d=cR[e].call(j,a,k,j.opts);if(d)return d}return cU(j,k),p.isFunction(j.opts.start)&&j.opts.start.call(a,j),p.fx.timer(p.extend(i,{anim:j,queue:j.opts.queue,elem:a})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}function cW(a,b){var c,d,e,f,g;for(c in a){d=p.camelCase(c),e=b[d],f=a[c],p.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=p.cssHooks[d];if(g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}}function cX(a,b,c){var d,e,f,g,h,i,j,k,l=this,m=a.style,n={},o=[],q=a.nodeType&&bY(a);c.queue||(j=p._queueHooks(a,"fx"),j.unqueued==null&&(j.unqueued=0,k=j.empty.fire,j.empty.fire=function(){j.unqueued||k()}),j.unqueued++,l.always(function(){l.always(function(){j.unqueued--,p.queue(a,"fx").length||j.empty.fire()})})),a.nodeType===1&&("height"in b||"width"in b)&&(c.overflow=[m.overflow,m.overflowX,m.overflowY],p.css(a,"display")==="inline"&&p.css(a,"float")==="none"&&(!p.support.inlineBlockNeedsLayout||cb(a.nodeName)==="inline"?m.display="inline-block":m.zoom=1)),c.overflow&&(m.overflow="hidden",p.support.shrinkWrapBlocks||l.done(function(){m.overflow=c.overflow[0],m.overflowX=c.overflow[1],m.overflowY=c.overflow[2]}));for(d in b){f=b[d];if(cO.exec(f)){delete b[d];if(f===(q?"hide":"show"))continue;o.push(d)}}g=o.length;if(g){h=p._data(a,"fxshow")||p._data(a,"fxshow",{}),q?p(a).show():l.done(function(){p(a).hide()}),l.done(function(){var b;p.removeData(a,"fxshow",!0);for(b in n)p.style(a,b,n[b])});for(d=0;d<g;d++)e=o[d],i=l.createTween(e,q?h[e]:0),n[e]=h[e]||p.style(a,e),e in h||(h[e]=i.start,q&&(i.end=i.start,i.start=e==="width"||e==="height"?1:0))}}function cY(a,b,c,d,e){return new cY.prototype.init(a,b,c,d,e)}function cZ(a,b){var c,d={height:a},e=0;for(;e<4;e+=2-b)c=bU[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function c_(a){return p.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}var c,d,e=a.document,f=a.location,g=a.navigator,h=a.jQuery,i=a.$,j=Array.prototype.push,k=Array.prototype.slice,l=Array.prototype.indexOf,m=Object.prototype.toString,n=Object.prototype.hasOwnProperty,o=String.prototype.trim,p=function(a,b){return new p.fn.init(a,b,c)},q=/[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,r=/\S/,s=/\s+/,t=r.test(" ")?/^[\s\xA0]+|[\s\xA0]+$/g:/^\s+|\s+$/g,u=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^[\],:{}\s]*$/,x=/(?:^|:|,)(?:\s*\[)+/g,y=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,z=/"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,A=/^-ms-/,B=/-([\da-z])/gi,C=function(a,b){return(b+"").toUpperCase()},D=function(){e.addEventListener?(e.removeEventListener("DOMContentLoaded",D,!1),p.ready()):e.readyState==="complete"&&(e.detachEvent("onreadystatechange",D),p.ready())},E={};p.fn=p.prototype={constructor:p,init:function(a,c,d){var f,g,h,i;if(!a)return this;if(a.nodeType)return this.context=this[0]=a,this.length=1,this;if(typeof a=="string"){a.charAt(0)==="<"&&a.charAt(a.length-1)===">"&&a.length>=3?f=[null,a,null]:f=u.exec(a);if(f&&(f[1]||!c)){if(f[1])return c=c instanceof p?c[0]:c,i=c&&c.nodeType?c.ownerDocument||c:e,a=p.parseHTML(f[1],i,!0),v.test(f[1])&&p.isPlainObject(c)&&this.attr.call(a,c,!0),p.merge(this,a);g=e.getElementById(f[2]);if(g&&g.parentNode){if(g.id!==f[2])return d.find(a);this.length=1,this[0]=g}return this.context=e,this.selector=a,this}return!c||c.jquery?(c||d).find(a):this.constructor(c).find(a)}return p.isFunction(a)?d.ready(a):(a.selector!==b&&(this.selector=a.selector,this.context=a.context),p.makeArray(a,this))},selector:"",jquery:"1.8.0",length:0,size:function(){return this.length},toArray:function(){return k.call(this)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=p.merge(this.constructor(),a);return d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")"),d},each:function(a,b){return p.each(this,a,b)},ready:function(a){return p.ready.promise().done(a),this},eq:function(a){return a=+a,a===-1?this.slice(a):this.slice(a,a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(k.apply(this,arguments),"slice",k.call(arguments).join(","))},map:function(a){return this.pushStack(p.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:j,sort:[].sort,splice:[].splice},p.fn.init.prototype=p.fn,p.extend=p.fn.extend=function(){var a,c,d,e,f,g,h=arguments[0]||{},i=1,j=arguments.length,k=!1;typeof h=="boolean"&&(k=h,h=arguments[1]||{},i=2),typeof h!="object"&&!p.isFunction(h)&&(h={}),j===i&&(h=this,--i);for(;i<j;i++)if((a=arguments[i])!=null)for(c in a){d=h[c],e=a[c];if(h===e)continue;k&&e&&(p.isPlainObject(e)||(f=p.isArray(e)))?(f?(f=!1,g=d&&p.isArray(d)?d:[]):g=d&&p.isPlainObject(d)?d:{},h[c]=p.extend(k,g,e)):e!==b&&(h[c]=e)}return h},p.extend({noConflict:function(b){return a.$===p&&(a.$=i),b&&a.jQuery===p&&(a.jQuery=h),p},isReady:!1,readyWait:1,holdReady:function(a){a?p.readyWait++:p.ready(!0)},ready:function(a){if(a===!0?--p.readyWait:p.isReady)return;if(!e.body)return setTimeout(p.ready,1);p.isReady=!0;if(a!==!0&&--p.readyWait>0)return;d.resolveWith(e,[p]),p.fn.trigger&&p(e).trigger("ready").off("ready")},isFunction:function(a){return p.type(a)==="function"},isArray:Array.isArray||function(a){return p.type(a)==="array"},isWindow:function(a){return a!=null&&a==a.window},isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},type:function(a){return a==null?String(a):E[m.call(a)]||"object"},isPlainObject:function(a){if(!a||p.type(a)!=="object"||a.nodeType||p.isWindow(a))return!1;try{if(a.constructor&&!n.call(a,"constructor")&&!n.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||n.call(a,d)},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},error:function(a){throw new Error(a)},parseHTML:function(a,b,c){var d;return!a||typeof a!="string"?null:(typeof b=="boolean"&&(c=b,b=0),b=b||e,(d=v.exec(a))?[b.createElement(d[1])]:(d=p.buildFragment([a],b,c?null:[]),p.merge([],(d.cacheable?p.clone(d.fragment):d.fragment).childNodes)))},parseJSON:function(b){if(!b||typeof b!="string")return null;b=p.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(w.test(b.replace(y,"@").replace(z,"]").replace(x,"")))return(new Function("return "+b))();p.error("Invalid JSON: "+b)},parseXML:function(c){var d,e;if(!c||typeof c!="string")return null;try{a.DOMParser?(e=new DOMParser,d=e.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(f){d=b}return(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&p.error("Invalid XML: "+c),d},noop:function(){},globalEval:function(b){b&&r.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(A,"ms-").replace(B,C)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,d){var e,f=0,g=a.length,h=g===b||p.isFunction(a);if(d){if(h){for(e in a)if(c.apply(a[e],d)===!1)break}else for(;f<g;)if(c.apply(a[f++],d)===!1)break}else if(h){for(e in a)if(c.call(a[e],e,a[e])===!1)break}else for(;f<g;)if(c.call(a[f],f,a[f++])===!1)break;return a},trim:o?function(a){return a==null?"":o.call(a)}:function(a){return a==null?"":a.toString().replace(t,"")},makeArray:function(a,b){var c,d=b||[];return a!=null&&(c=p.type(a),a.length==null||c==="string"||c==="function"||c==="regexp"||p.isWindow(a)?j.call(d,a):p.merge(d,a)),d},inArray:function(a,b,c){var d;if(b){if(l)return l.call(b,a,c);d=b.length,c=c?c<0?Math.max(0,d+c):c:0;for(;c<d;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,c){var d=c.length,e=a.length,f=0;if(typeof d=="number")for(;f<d;f++)a[e++]=c[f];else while(c[f]!==b)a[e++]=c[f++];return a.length=e,a},grep:function(a,b,c){var d,e=[],f=0,g=a.length;c=!!c;for(;f<g;f++)d=!!b(a[f],f),c!==d&&e.push(a[f]);return e},map:function(a,c,d){var e,f,g=[],h=0,i=a.length,j=a instanceof p||i!==b&&typeof i=="number"&&(i>0&&a[0]&&a[i-1]||i===0||p.isArray(a));if(j)for(;h<i;h++)e=c(a[h],h,d),e!=null&&(g[g.length]=e);else for(f in a)e=c(a[f],f,d),e!=null&&(g[g.length]=e);return g.concat.apply([],g)},guid:1,proxy:function(a,c){var d,e,f;return typeof c=="string"&&(d=a[c],c=a,a=d),p.isFunction(a)?(e=k.call(arguments,2),f=function(){return a.apply(c,e.concat(k.call(arguments)))},f.guid=a.guid=a.guid||f.guid||p.guid++,f):b},access:function(a,c,d,e,f,g,h){var i,j=d==null,k=0,l=a.length;if(d&&typeof d=="object"){for(k in d)p.access(a,c,k,d[k],1,g,e);f=1}else if(e!==b){i=h===b&&p.isFunction(e),j&&(i?(i=c,c=function(a,b,c){return i.call(p(a),c)}):(c.call(a,e),c=null));if(c)for(;k<l;k++)c(a[k],d,i?e.call(a[k],k,c(a[k],d)):e,h);f=1}return f?a:j?c.call(a):l?c(a[0],d):g},now:function(){return(new Date).getTime()}}),p.ready.promise=function(b){if(!d){d=p.Deferred();if(e.readyState==="complete"||e.readyState!=="loading"&&e.addEventListener)setTimeout(p.ready,1);else if(e.addEventListener)e.addEventListener("DOMContentLoaded",D,!1),a.addEventListener("load",p.ready,!1);else{e.attachEvent("onreadystatechange",D),a.attachEvent("onload",p.ready);var c=!1;try{c=a.frameElement==null&&e.documentElement}catch(f){}c&&c.doScroll&&function g(){if(!p.isReady){try{c.doScroll("left")}catch(a){return setTimeout(g,50)}p.ready()}}()}}return d.promise(b)},p.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(a,b){E["[object "+b+"]"]=b.toLowerCase()}),c=p(e);var F={};p.Callbacks=function(a){a=typeof a=="string"?F[a]||G(a):p.extend({},a);var c,d,e,f,g,h,i=[],j=!a.once&&[],k=function(b){c=a.memory&&b,d=!0,h=f||0,f=0,g=i.length,e=!0;for(;i&&h<g;h++)if(i[h].apply(b[0],b[1])===!1&&a.stopOnFalse){c=!1;break}e=!1,i&&(j?j.length&&k(j.shift()):c?i=[]:l.disable())},l={add:function(){if(i){var b=i.length;(function d(b){p.each(b,function(b,c){p.isFunction(c)&&(!a.unique||!l.has(c))?i.push(c):c&&c.length&&d(c)})})(arguments),e?g=i.length:c&&(f=b,k(c))}return this},remove:function(){return i&&p.each(arguments,function(a,b){var c;while((c=p.inArray(b,i,c))>-1)i.splice(c,1),e&&(c<=g&&g--,c<=h&&h--)}),this},has:function(a){return p.inArray(a,i)>-1},empty:function(){return i=[],this},disable:function(){return i=j=c=b,this},disabled:function(){return!i},lock:function(){return j=b,c||l.disable(),this},locked:function(){return!j},fireWith:function(a,b){return b=b||[],b=[a,b.slice?b.slice():b],i&&(!d||j)&&(e?j.push(b):k(b)),this},fire:function(){return l.fireWith(this,arguments),this},fired:function(){return!!d}};return l},p.extend({Deferred:function(a){var b=[["resolve","done",p.Callbacks("once memory"),"resolved"],["reject","fail",p.Callbacks("once memory"),"rejected"],["notify","progress",p.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return p.Deferred(function(c){p.each(b,function(b,d){var f=d[0],g=a[b];e[d[1]](p.isFunction(g)?function(){var a=g.apply(this,arguments);a&&p.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f+"With"](this===e?c:this,[a])}:c[f])}),a=null}).promise()},promise:function(a){return typeof a=="object"?p.extend(a,d):d}},e={};return d.pipe=d.then,p.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[a^1][2].disable,b[2][2].lock),e[f[0]]=g.fire,e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=k.call(arguments),d=c.length,e=d!==1||a&&p.isFunction(a.promise)?d:0,f=e===1?a:p.Deferred(),g=function(a,b,c){return function(d){b[a]=this,c[a]=arguments.length>1?k.call(arguments):d,c===h?f.notifyWith(b,c):--e||f.resolveWith(b,c)}},h,i,j;if(d>1){h=new Array(d),i=new Array(d),j=new Array(d);for(;b<d;b++)c[b]&&p.isFunction(c[b].promise)?c[b].promise().done(g(b,j,c)).fail(f.reject).progress(g(b,i,h)):--e}return e||f.resolveWith(j,c),f.promise()}}),p.support=function(){var b,c,d,f,g,h,i,j,k,l,m,n=e.createElement("div");n.setAttribute("className","t"),n.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",c=n.getElementsByTagName("*"),d=n.getElementsByTagName("a")[0],d.style.cssText="top:1px;float:left;opacity:.5";if(!c||!c.length||!d)return{};f=e.createElement("select"),g=f.appendChild(e.createElement("option")),h=n.getElementsByTagName("input")[0],b={leadingWhitespace:n.firstChild.nodeType===3,tbody:!n.getElementsByTagName("tbody").length,htmlSerialize:!!n.getElementsByTagName("link").length,style:/top/.test(d.getAttribute("style")),hrefNormalized:d.getAttribute("href")==="/a",opacity:/^0.5/.test(d.style.opacity),cssFloat:!!d.style.cssFloat,checkOn:h.value==="on",optSelected:g.selected,getSetAttribute:n.className!=="t",enctype:!!e.createElement("form").enctype,html5Clone:e.createElement("nav").cloneNode(!0).outerHTML!=="<:nav></:nav>",boxModel:e.compatMode==="CSS1Compat",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},h.checked=!0,b.noCloneChecked=h.cloneNode(!0).checked,f.disabled=!0,b.optDisabled=!g.disabled;try{delete n.test}catch(o){b.deleteExpando=!1}!n.addEventListener&&n.attachEvent&&n.fireEvent&&(n.attachEvent("onclick",m=function(){b.noCloneEvent=!1}),n.cloneNode(!0).fireEvent("onclick"),n.detachEvent("onclick",m)),h=e.createElement("input"),h.value="t",h.setAttribute("type","radio"),b.radioValue=h.value==="t",h.setAttribute("checked","checked"),h.setAttribute("name","t"),n.appendChild(h),i=e.createDocumentFragment(),i.appendChild(n.lastChild),b.checkClone=i.cloneNode(!0).cloneNode(!0).lastChild.checked,b.appendChecked=h.checked,i.removeChild(h),i.appendChild(n);if(n.attachEvent)for(k in{submit:!0,change:!0,focusin:!0})j="on"+k,l=j in n,l||(n.setAttribute(j,"return;"),l=typeof n[j]=="function"),b[k+"Bubbles"]=l;return p(function(){var c,d,f,g,h="padding:0;margin:0;border:0;display:block;overflow:hidden;",i=e.getElementsByTagName("body")[0];if(!i)return;c=e.createElement("div"),c.style.cssText="visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px",i.insertBefore(c,i.firstChild),d=e.createElement("div"),c.appendChild(d),d.innerHTML="<table><tr><td></td><td>t</td></tr></table>",f=d.getElementsByTagName("td"),f[0].style.cssText="padding:0;margin:0;border:0;display:none",l=f[0].offsetHeight===0,f[0].style.display="",f[1].style.display="none",b.reliableHiddenOffsets=l&&f[0].offsetHeight===0,d.innerHTML="",d.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",b.boxSizing=d.offsetWidth===4,b.doesNotIncludeMarginInBodyOffset=i.offsetTop!==1,a.getComputedStyle&&(b.pixelPosition=(a.getComputedStyle(d,null)||{}).top!=="1%",b.boxSizingReliable=(a.getComputedStyle(d,null)||{width:"4px"}).width==="4px",g=e.createElement("div"),g.style.cssText=d.style.cssText=h,g.style.marginRight=g.style.width="0",d.style.width="1px",d.appendChild(g),b.reliableMarginRight=!parseFloat((a.getComputedStyle(g,null)||{}).marginRight)),typeof d.style.zoom!="undefined"&&(d.innerHTML="",d.style.cssText=h+"width:1px;padding:1px;display:inline;zoom:1",b.inlineBlockNeedsLayout=d.offsetWidth===3,d.style.display="block",d.style.overflow="visible",d.innerHTML="<div></div>",d.firstChild.style.width="5px",b.shrinkWrapBlocks=d.offsetWidth!==3,c.style.zoom=1),i.removeChild(c),c=d=f=g=null}),i.removeChild(n),c=d=f=g=h=i=n=null,b}();var H=/^(?:\{.*\}|\[.*\])$/,I=/([A-Z])/g;p.extend({cache:{},deletedIds:[],uuid:0,expando:"jQuery"+(p.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){return a=a.nodeType?p.cache[a[p.expando]]:a[p.expando],!!a&&!K(a)},data:function(a,c,d,e){if(!p.acceptData(a))return;var f,g,h=p.expando,i=typeof c=="string",j=a.nodeType,k=j?p.cache:a,l=j?a[h]:a[h]&&h;if((!l||!k[l]||!e&&!k[l].data)&&i&&d===b)return;l||(j?a[h]=l=p.deletedIds.pop()||++p.uuid:l=h),k[l]||(k[l]={},j||(k[l].toJSON=p.noop));if(typeof c=="object"||typeof c=="function")e?k[l]=p.extend(k[l],c):k[l].data=p.extend(k[l].data,c);return f=k[l],e||(f.data||(f.data={}),f=f.data),d!==b&&(f[p.camelCase(c)]=d),i?(g=f[c],g==null&&(g=f[p.camelCase(c)])):g=f,g},removeData:function(a,b,c){if(!p.acceptData(a))return;var d,e,f,g=a.nodeType,h=g?p.cache:a,i=g?a[p.expando]:p.expando;if(!h[i])return;if(b){d=c?h[i]:h[i].data;if(d){p.isArray(b)||(b in d?b=[b]:(b=p.camelCase(b),b in d?b=[b]:b=b.split(" ")));for(e=0,f=b.length;e<f;e++)delete d[b[e]];if(!(c?K:p.isEmptyObject)(d))return}}if(!c){delete h[i].data;if(!K(h[i]))return}g?p.cleanData([a],!0):p.support.deleteExpando||h!=h.window?delete h[i]:h[i]=null},_data:function(a,b,c){return p.data(a,b,c,!0)},acceptData:function(a){var b=a.nodeName&&p.noData[a.nodeName.toLowerCase()];return!b||b!==!0&&a.getAttribute("classid")===b}}),p.fn.extend({data:function(a,c){var d,e,f,g,h,i=this[0],j=0,k=null;if(a===b){if(this.length){k=p.data(i);if(i.nodeType===1&&!p._data(i,"parsedAttrs")){f=i.attributes;for(h=f.length;j<h;j++)g=f[j].name,g.indexOf("data-")===0&&(g=p.camelCase(g.substring(5)),J(i,g,k[g]));p._data(i,"parsedAttrs",!0)}}return k}return typeof a=="object"?this.each(function(){p.data(this,a)}):(d=a.split(".",2),d[1]=d[1]?"."+d[1]:"",e=d[1]+"!",p.access(this,function(c){if(c===b)return k=this.triggerHandler("getData"+e,[d[0]]),k===b&&i&&(k=p.data(i,a),k=J(i,a,k)),k===b&&d[1]?this.data(d[0]):k;d[1]=c,this.each(function(){var b=p(this);b.triggerHandler("setData"+e,d),p.data(this,a,c),b.triggerHandler("changeData"+e,d)})},null,c,arguments.length>1,null,!1))},removeData:function(a){return this.each(function(){p.removeData(this,a)})}}),p.extend({queue:function(a,b,c){var d;if(a)return b=(b||"fx")+"queue",d=p._data(a,b),c&&(!d||p.isArray(c)?d=p._data(a,b,p.makeArray(c)):d.push(c)),d||[]},dequeue:function(a,b){b=b||"fx";var c=p.queue(a,b),d=c.shift(),e=p._queueHooks(a,b),f=function(){p.dequeue(a,b)};d==="inprogress"&&(d=c.shift()),d&&(b==="fx"&&c.unshift("inprogress"),delete e.stop,d.call(a,f,e)),!c.length&&e&&e.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return p._data(a,c)||p._data(a,c,{empty:p.Callbacks("once memory").add(function(){p.removeData(a,b+"queue",!0),p.removeData(a,c,!0)})})}}),p.fn.extend({queue:function(a,c){var d=2;return typeof a!="string"&&(c=a,a="fx",d--),arguments.length<d?p.queue(this[0],a):c===b?this:this.each(function(){var b=p.queue(this,a,c);p._queueHooks(this,a),a==="fx"&&b[0]!=="inprogress"&&p.dequeue(this,a)})},dequeue:function(a){return this.each(function(){p.dequeue(this,a)})},delay:function(a,b){return a=p.fx?p.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,c){var d,e=1,f=p.Deferred(),g=this,h=this.length,i=function(){--e||f.resolveWith(g,[g])};typeof a!="string"&&(c=a,a=b),a=a||"fx";while(h--)(d=p._data(g[h],a+"queueHooks"))&&d.empty&&(e++,d.empty.add(i));return i(),f.promise(c)}});var L,M,N,O=/[\t\r\n]/g,P=/\r/g,Q=/^(?:button|input)$/i,R=/^(?:button|input|object|select|textarea)$/i,S=/^a(?:rea|)$/i,T=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,U=p.support.getSetAttribute;p.fn.extend({attr:function(a,b){return p.access(this,p.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){p.removeAttr(this,a)})},prop:function(a,b){return p.access(this,p.prop,a,b,arguments.length>1)},removeProp:function(a){return a=p.propFix[a]||a,this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){var b,c,d,e,f,g,h;if(p.isFunction(a))return this.each(function(b){p(this).addClass(a.call(this,b,this.className))});if(a&&typeof a=="string"){b=a.split(s);for(c=0,d=this.length;c<d;c++){e=this[c];if(e.nodeType===1)if(!e.className&&b.length===1)e.className=a;else{f=" "+e.className+" ";for(g=0,h=b.length;g<h;g++)~f.indexOf(" "+b[g]+" ")||(f+=b[g]+" ");e.className=p.trim(f)}}}return this},removeClass:function(a){var c,d,e,f,g,h,i;if(p.isFunction(a))return this.each(function(b){p(this).removeClass(a.call(this,b,this.className))});if(a&&typeof a=="string"||a===b){c=(a||"").split(s);for(h=0,i=this.length;h<i;h++){e=this[h];if(e.nodeType===1&&e.className){d=(" "+e.className+" ").replace(O," ");for(f=0,g=c.length;f<g;f++)while(d.indexOf(" "+c[f]+" ")>-1)d=d.replace(" "+c[f]+" "," ");e.className=a?p.trim(d):""}}}return this},toggleClass:function(a,b){var c=typeof a,d=typeof b=="boolean";return p.isFunction(a)?this.each(function(c){p(this).toggleClass(a.call(this,c,this.className,b),b)}):this.each(function(){if(c==="string"){var e,f=0,g=p(this),h=b,i=a.split(s);while(e=i[f++])h=d?h:!g.hasClass(e),g[h?"addClass":"removeClass"](e)}else if(c==="undefined"||c==="boolean")this.className&&p._data(this,"__className__",this.className),this.className=this.className||a===!1?"":p._data(this,"__className__")||""})},hasClass:function(a){var b=" "+a+" ",c=0,d=this.length;for(;c<d;c++)if(this[c].nodeType===1&&(" "+this[c].className+" ").replace(O," ").indexOf(b)>-1)return!0;return!1},val:function(a){var c,d,e,f=this[0];if(!arguments.length){if(f)return c=p.valHooks[f.type]||p.valHooks[f.nodeName.toLowerCase()],c&&"get"in c&&(d=c.get(f,"value"))!==b?d:(d=f.value,typeof d=="string"?d.replace(P,""):d==null?"":d);return}return e=p.isFunction(a),this.each(function(d){var f,g=p(this);if(this.nodeType!==1)return;e?f=a.call(this,d,g.val()):f=a,f==null?f="":typeof f=="number"?f+="":p.isArray(f)&&(f=p.map(f,function(a){return a==null?"":a+""})),c=p.valHooks[this.type]||p.valHooks[this.nodeName.toLowerCase()];if(!c||!("set"in c)||c.set(this,f,"value")===b)this.value=f})}}),p.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c,d,e,f=a.selectedIndex,g=[],h=a.options,i=a.type==="select-one";if(f<0)return null;c=i?f:0,d=i?f+1:h.length;for(;c<d;c++){e=h[c];if(e.selected&&(p.support.optDisabled?!e.disabled:e.getAttribute("disabled")===null)&&(!e.parentNode.disabled||!p.nodeName(e.parentNode,"optgroup"))){b=p(e).val();if(i)return b;g.push(b)}}return i&&!g.length&&h.length?p(h[f]).val():g},set:function(a,b){var c=p.makeArray(b);return p(a).find("option").each(function(){this.selected=p.inArray(p(this).val(),c)>=0}),c.length||(a.selectedIndex=-1),c}}},attrFn:{},attr:function(a,c,d,e){var f,g,h,i=a.nodeType;if(!a||i===3||i===8||i===2)return;if(e&&p.isFunction(p.fn[c]))return p(a)[c](d);if(typeof a.getAttribute=="undefined")return p.prop(a,c,d);h=i!==1||!p.isXMLDoc(a),h&&(c=c.toLowerCase(),g=p.attrHooks[c]||(T.test(c)?M:L));if(d!==b){if(d===null){p.removeAttr(a,c);return}return g&&"set"in g&&h&&(f=g.set(a,d,c))!==b?f:(a.setAttribute(c,""+d),d)}return g&&"get"in g&&h&&(f=g.get(a,c))!==null?f:(f=a.getAttribute(c),f===null?b:f)},removeAttr:function(a,b){var c,d,e,f,g=0;if(b&&a.nodeType===1){d=b.split(s);for(;g<d.length;g++)e=d[g],e&&(c=p.propFix[e]||e,f=T.test(e),f||p.attr(a,e,""),a.removeAttribute(U?e:c),f&&c in a&&(a[c]=!1))}},attrHooks:{type:{set:function(a,b){if(Q.test(a.nodeName)&&a.parentNode)p.error("type property can't be changed");else if(!p.support.radioValue&&b==="radio"&&p.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}},value:{get:function(a,b){return L&&p.nodeName(a,"button")?L.get(a,b):b in a?a.value:null},set:function(a,b,c){if(L&&p.nodeName(a,"button"))return L.set(a,b,c);a.value=b}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(a,c,d){var e,f,g,h=a.nodeType;if(!a||h===3||h===8||h===2)return;return g=h!==1||!p.isXMLDoc(a),g&&(c=p.propFix[c]||c,f=p.propHooks[c]),d!==b?f&&"set"in f&&(e=f.set(a,d,c))!==b?e:a[c]=d:f&&"get"in f&&(e=f.get(a,c))!==null?e:a[c]},propHooks:{tabIndex:{get:function(a){var c=a.getAttributeNode("tabindex");return c&&c.specified?parseInt(c.value,10):R.test(a.nodeName)||S.test(a.nodeName)&&a.href?0:b}}}}),M={get:function(a,c){var d,e=p.prop(a,c);return e===!0||typeof e!="boolean"&&(d=a.getAttributeNode(c))&&d.nodeValue!==!1?c.toLowerCase():b},set:function(a,b,c){var d;return b===!1?p.removeAttr(a,c):(d=p.propFix[c]||c,d in a&&(a[d]=!0),a.setAttribute(c,c.toLowerCase())),c}},U||(N={name:!0,id:!0,coords:!0},L=p.valHooks.button={get:function(a,c){var d;return d=a.getAttributeNode(c),d&&(N[c]?d.value!=="":d.specified)?d.value:b},set:function(a,b,c){var d=a.getAttributeNode(c);return d||(d=e.createAttribute(c),a.setAttributeNode(d)),d.value=b+""}},p.each(["width","height"],function(a,b){p.attrHooks[b]=p.extend(p.attrHooks[b],{set:function(a,c){if(c==="")return a.setAttribute(b,"auto"),c}})}),p.attrHooks.contenteditable={get:L.get,set:function(a,b,c){b===""&&(b="false"),L.set(a,b,c)}}),p.support.hrefNormalized||p.each(["href","src","width","height"],function(a,c){p.attrHooks[c]=p.extend(p.attrHooks[c],{get:function(a){var d=a.getAttribute(c,2);return d===null?b:d}})}),p.support.style||(p.attrHooks.style={get:function(a){return a.style.cssText.toLowerCase()||b},set:function(a,b){return a.style.cssText=""+b}}),p.support.optSelected||(p.propHooks.selected=p.extend(p.propHooks.selected,{get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}})),p.support.enctype||(p.propFix.enctype="encoding"),p.support.checkOn||p.each(["radio","checkbox"],function(){p.valHooks[this]={get:function(a){return a.getAttribute("value")===null?"on":a.value}}}),p.each(["radio","checkbox"],function(){p.valHooks[this]=p.extend(p.valHooks[this],{set:function(a,b){if(p.isArray(b))return a.checked=p.inArray(p(a).val(),b)>=0}})});var V=/^(?:textarea|input|select)$/i,W=/^([^\.]*|)(?:\.(.+)|)$/,X=/(?:^|\s)hover(\.\S+|)\b/,Y=/^key/,Z=/^(?:mouse|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=function(a){return p.event.special.hover?a:a.replace(X,"mouseenter$1 mouseleave$1")};p.event={add:function(a,c,d,e,f){var g,h,i,j,k,l,m,n,o,q,r;if(a.nodeType===3||a.nodeType===8||!c||!d||!(g=p._data(a)))return;d.handler&&(o=d,d=o.handler,f=o.selector),d.guid||(d.guid=p.guid++),i=g.events,i||(g.events=i={}),h=g.handle,h||(g.handle=h=function(a){return typeof p!="undefined"&&(!a||p.event.triggered!==a.type)?p.event.dispatch.apply(h.elem,arguments):b},h.elem=a),c=p.trim(_(c)).split(" ");for(j=0;j<c.length;j++){k=W.exec(c[j])||[],l=k[1],m=(k[2]||"").split(".").sort(),r=p.event.special[l]||{},l=(f?r.delegateType:r.bindType)||l,r=p.event.special[l]||{},n=p.extend({type:l,origType:k[1],data:e,handler:d,guid:d.guid,selector:f,namespace:m.join(".")},o),q=i[l];if(!q){q=i[l]=[],q.delegateCount=0;if(!r.setup||r.setup.call(a,e,m,h)===!1)a.addEventListener?a.addEventListener(l,h,!1):a.attachEvent&&a.attachEvent("on"+l,h)}r.add&&(r.add.call(a,n),n.handler.guid||(n.handler.guid=d.guid)),f?q.splice(q.delegateCount++,0,n):q.push(n),p.event.global[l]=!0}a=null},global:{},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,o,q,r=p.hasData(a)&&p._data(a);if(!r||!(m=r.events))return;b=p.trim(_(b||"")).split(" ");for(f=0;f<b.length;f++){g=W.exec(b[f])||[],h=i=g[1],j=g[2];if(!h){for(h in m)p.event.remove(a,h+b[f],c,d,!0);continue}n=p.event.special[h]||{},h=(d?n.delegateType:n.bindType)||h,o=m[h]||[],k=o.length,j=j?new RegExp("(^|\\.)"+j.split(".").sort().join("\\.(?:.*\\.|)")+"(\\.|$)"):null;for(l=0;l<o.length;l++)q=o[l],(e||i===q.origType)&&(!c||c.guid===q.guid)&&(!j||j.test(q.namespace))&&(!d||d===q.selector||d==="**"&&q.selector)&&(o.splice(l--,1),q.selector&&o.delegateCount--,n.remove&&n.remove.call(a,q));o.length===0&&k!==o.length&&((!n.teardown||n.teardown.call(a,j,r.handle)===!1)&&p.removeEvent(a,h,r.handle),delete m[h])}p.isEmptyObject(m)&&(delete r.handle,p.removeData(a,"events",!0))},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(c,d,f,g){if(!f||f.nodeType!==3&&f.nodeType!==8){var h,i,j,k,l,m,n,o,q,r,s=c.type||c,t=[];if($.test(s+p.event.triggered))return;s.indexOf("!")>=0&&(s=s.slice(0,-1),i=!0),s.indexOf(".")>=0&&(t=s.split("."),s=t.shift(),t.sort());if((!f||p.event.customEvent[s])&&!p.event.global[s])return;c=typeof c=="object"?c[p.expando]?c:new p.Event(s,c):new p.Event(s),c.type=s,c.isTrigger=!0,c.exclusive=i,c.namespace=t.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+t.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,m=s.indexOf(":")<0?"on"+s:"";if(!f){h=p.cache;for(j in h)h[j].events&&h[j].events[s]&&p.event.trigger(c,d,h[j].handle.elem,!0);return}c.result=b,c.target||(c.target=f),d=d!=null?p.makeArray(d):[],d.unshift(c),n=p.event.special[s]||{};if(n.trigger&&n.trigger.apply(f,d)===!1)return;q=[[f,n.bindType||s]];if(!g&&!n.noBubble&&!p.isWindow(f)){r=n.delegateType||s,k=$.test(r+s)?f:f.parentNode;for(l=f;k;k=k.parentNode)q.push([k,r]),l=k;l===(f.ownerDocument||e)&&q.push([l.defaultView||l.parentWindow||a,r])}for(j=0;j<q.length&&!c.isPropagationStopped();j++)k=q[j][0],c.type=q[j][1],o=(p._data(k,"events")||{})[c.type]&&p._data(k,"handle"),o&&o.apply(k,d),o=m&&k[m],o&&p.acceptData(k)&&o.apply(k,d)===!1&&c.preventDefault();return c.type=s,!g&&!c.isDefaultPrevented()&&(!n._default||n._default.apply(f.ownerDocument,d)===!1)&&(s!=="click"||!p.nodeName(f,"a"))&&p.acceptData(f)&&m&&f[s]&&(s!=="focus"&&s!=="blur"||c.target.offsetWidth!==0)&&!p.isWindow(f)&&(l=f[m],l&&(f[m]=null),p.event.triggered=s,f[s](),p.event.triggered=b,l&&(f[m]=l)),c.result}return},dispatch:function(c){c=p.event.fix(c||a.event);var d,e,f,g,h,i,j,k,l,m,n,o=(p._data(this,"events")||{})[c.type]||[],q=o.delegateCount,r=[].slice.call(arguments),s=!c.exclusive&&!c.namespace,t=p.event.special[c.type]||{},u=[];r[0]=c,c.delegateTarget=this;if(t.preDispatch&&t.preDispatch.call(this,c)===!1)return;if(q&&(!c.button||c.type!=="click")){g=p(this),g.context=this;for(f=c.target;f!=this;f=f.parentNode||this)if(f.disabled!==!0||c.type!=="click"){i={},k=[],g[0]=f;for(d=0;d<q;d++)l=o[d],m=l.selector,i[m]===b&&(i[m]=g.is(m)),i[m]&&k.push(l);k.length&&u.push({elem:f,matches:k})}}o.length>q&&u.push({elem:this,matches:o.slice(q)});for(d=0;d<u.length&&!c.isPropagationStopped();d++){j=u[d],c.currentTarget=j.elem;for(e=0;e<j.matches.length&&!c.isImmediatePropagationStopped();e++){l=j.matches[e];if(s||!c.namespace&&!l.namespace||c.namespace_re&&c.namespace_re.test(l.namespace))c.data=l.data,c.handleObj=l,h=((p.event.special[l.origType]||{}).handle||l.handler).apply(j.elem,r),h!==b&&(c.result=h,h===!1&&(c.preventDefault(),c.stopPropagation()))}}return t.postDispatch&&t.postDispatch.call(this,c),c.result},props:"attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return a.which==null&&(a.which=b.charCode!=null?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,c){var d,f,g,h=c.button,i=c.fromElement;return a.pageX==null&&c.clientX!=null&&(d=a.target.ownerDocument||e,f=d.documentElement,g=d.body,a.pageX=c.clientX+(f&&f.scrollLeft||g&&g.scrollLeft||0)-(f&&f.clientLeft||g&&g.clientLeft||0),a.pageY=c.clientY+(f&&f.scrollTop||g&&g.scrollTop||0)-(f&&f.clientTop||g&&g.clientTop||0)),!a.relatedTarget&&i&&(a.relatedTarget=i===a.target?c.toElement:i),!a.which&&h!==b&&(a.which=h&1?1:h&2?3:h&4?2:0),a}},fix:function(a){if(a[p.expando])return a;var b,c,d=a,f=p.event.fixHooks[a.type]||{},g=f.props?this.props.concat(f.props):this.props;a=p.Event(d);for(b=g.length;b;)c=g[--b],a[c]=d[c];return a.target||(a.target=d.srcElement||e),a.target.nodeType===3&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,f.filter?f.filter(a,d):a},special:{ready:{setup:p.bindReady},load:{noBubble:!0},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(a,b,c){p.isWindow(this)&&(this.onbeforeunload=c)},teardown:function(a,b){this.onbeforeunload===b&&(this.onbeforeunload=null)}}},simulate:function(a,b,c,d){var e=p.extend(new p.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?p.event.trigger(e,null,b):p.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},p.event.handle=p.event.dispatch,p.removeEvent=e.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]=="undefined"&&(a[d]=null),a.detachEvent(d,c))},p.Event=function(a,b){if(this instanceof p.Event)a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault()?bb:ba):this.type=a,b&&p.extend(this,b),this.timeStamp=a&&a.timeStamp||p.now(),this[p.expando]=!0;else return new p.Event(a,b)},p.Event.prototype={preventDefault:function(){this.isDefaultPrevented=bb;var a=this.originalEvent;if(!a)return;a.preventDefault?a.preventDefault():a.returnValue=!1},stopPropagation:function(){this.isPropagationStopped=bb;var a=this.originalEvent;if(!a)return;a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=bb,this.stopPropagation()},isDefaultPrevented:ba,isPropagationStopped:ba,isImmediatePropagationStopped:ba},p.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){p.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj,g=f.selector;if(!e||e!==d&&!p.contains(d,e))a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b;return c}}}),p.support.submitBubbles||(p.event.special.submit={setup:function(){if(p.nodeName(this,"form"))return!1;p.event.add(this,"click._submit keypress._submit",function(a){var c=a.target,d=p.nodeName(c,"input")||p.nodeName(c,"button")?c.form:b;d&&!p._data(d,"_submit_attached")&&(p.event.add(d,"submit._submit",function(a){a._submit_bubble=!0}),p._data(d,"_submit_attached",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&p.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){if(p.nodeName(this,"form"))return!1;p.event.remove(this,"._submit")}}),p.support.changeBubbles||(p.event.special.change={setup:function(){if(V.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio")p.event.add(this,"propertychange._change",function(a){a.originalEvent.propertyName==="checked"&&(this._just_changed=!0)}),p.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),p.event.simulate("change",this,a,!0)});return!1}p.event.add(this,"beforeactivate._change",function(a){var b=a.target;V.test(b.nodeName)&&!p._data(b,"_change_attached")&&(p.event.add(b,"change._change",function(a){this.parentNode&&!a.isSimulated&&!a.isTrigger&&p.event.simulate("change",this.parentNode,a,!0)}),p._data(b,"_change_attached",!0))})},handle:function(a){var b=a.target;if(this!==b||a.isSimulated||a.isTrigger||b.type!=="radio"&&b.type!=="checkbox")return a.handleObj.handler.apply(this,arguments)},teardown:function(){return p.event.remove(this,"._change"),V.test(this.nodeName)}}),p.support.focusinBubbles||p.each({focus:"focusin",blur:"focusout"},function(a,b){var c=0,d=function(a){p.event.simulate(b,a.target,p.event.fix(a),!0)};p.event.special[b]={setup:function(){c++===0&&e.addEventListener(a,d,!0)},teardown:function(){--c===0&&e.removeEventListener(a,d,!0)}}}),p.fn.extend({on:function(a,c,d,e,f){var g,h;if(typeof a=="object"){typeof c!="string"&&(d=d||c,c=b);for(h in a)this.on(h,c,d,a[h],f);return this}d==null&&e==null?(e=c,d=c=b):e==null&&(typeof c=="string"?(e=d,d=b):(e=d,d=c,c=b));if(e===!1)e=ba;else if(!e)return this;return f===1&&(g=e,e=function(a){return p().off(a),g.apply(this,arguments)},e.guid=g.guid||(g.guid=p.guid++)),this.each(function(){p.event.add(this,a,e,d,c)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,c,d){var e,f;if(a&&a.preventDefault&&a.handleObj)return e=a.handleObj,p(a.delegateTarget).off(e.namespace?e.origType+"."+e.namespace:e.origType,e.selector,e.handler),this;if(typeof a=="object"){for(f in a)this.off(f,c,a[f]);return this}if(c===!1||typeof c=="function")d=c,c=b;return d===!1&&(d=ba),this.each(function(){p.event.remove(this,a,d,c)})},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},live:function(a,b,c){return p(this.context).on(a,this.selector,b,c),this},die:function(a,b){return p(this.context).off(a,this.selector||"**",b),this},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return arguments.length==1?this.off(a,"**"):this.off(b,a||"**",c)},trigger:function(a,b){return this.each(function(){p.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0])return p.event.trigger(a,b,this[0],!0)},toggle:function(a){var b=arguments,c=a.guid||p.guid++,d=0,e=function(c){var e=(p._data(this,"lastToggle"+a.guid)||0)%d;return p._data(this,"lastToggle"+a.guid,e+1),c.preventDefault(),b[e].apply(this,arguments)||!1};e.guid=c;while(d<b.length)b[d++].guid=c;return this.click(e)},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}}),p.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){p.fn[b]=function(a,c){return c==null&&(c=a,a=null),arguments.length>0?this.on(b,null,a,c):this.trigger(b)},Y.test(b)&&(p.event.fixHooks[b]=p.event.keyHooks),Z.test(b)&&(p.event.fixHooks[b]=p.event.mouseHooks)}),function(a,b){function bd(a,b,c,d){var e=0,f=b.length;for(;e<f;e++)Z(a,b[e],c,d)}function be(a,b,c,d,e,f){var g,h=$.setFilters[b.toLowerCase()];return h||Z.error(b),(a||!(g=e))&&bd(a||"*",d,g=[],e),g.length>0?h(g,c,f):[]}function bf(a,c,d,e,f){var g,h,i,j,k,l,m,n,p=0,q=f.length,s=L.POS,t=new RegExp("^"+s.source+"(?!"+r+")","i"),u=function(){var a=1,c=arguments.length-2;for(;a<c;a++)arguments[a]===b&&(g[a]=b)};for(;p<q;p++){s.exec(""),a=f[p],j=[],i=0,k=e;while(g=s.exec(a)){n=s.lastIndex=g.index+g[0].length;if(n>i){m=a.slice(i,g.index),i=n,l=[c],B.test(m)&&(k&&(l=k),k=e);if(h=H.test(m))m=m.slice(0,-5).replace(B,"$&*");g.length>1&&g[0].replace(t,u),k=be(m,g[1],g[2],l,k,h)}}k?(j=j.concat(k),(m=a.slice(i))&&m!==")"?B.test(m)?bd(m,j,d,e):Z(m,c,d,e?e.concat(k):k):o.apply(d,j)):Z(a,c,d,e)}return q===1?d:Z.uniqueSort(d)}function bg(a,b,c){var d,e,f,g=[],i=0,j=D.exec(a),k=!j.pop()&&!j.pop(),l=k&&a.match(C)||[""],m=$.preFilter,n=$.filter,o=!c&&b!==h;for(;(e=l[i])!=null&&k;i++){g.push(d=[]),o&&(e=" "+e);while(e){k=!1;if(j=B.exec(e))e=e.slice(j[0].length),k=d.push({part:j.pop().replace(A," "),captures:j});for(f in n)(j=L[f].exec(e))&&(!m[f]||(j=m[f](j,b,c)))&&(e=e.slice(j.shift().length),k=d.push({part:f,captures:j}));if(!k)break}}return k||Z.error(a),g}function bh(a,b,e){var f=b.dir,g=m++;return a||(a=function(a){return a===e}),b.first?function(b,c){while(b=b[f])if(b.nodeType===1)return a(b,c)&&b}:function(b,e){var h,i=g+"."+d,j=i+"."+c;while(b=b[f])if(b.nodeType===1){if((h=b[q])===j)return b.sizset;if(typeof h=="string"&&h.indexOf(i)===0){if(b.sizset)return b}else{b[q]=j;if(a(b,e))return b.sizset=!0,b;b.sizset=!1}}}}function bi(a,b){return a?function(c,d){var e=b(c,d);return e&&a(e===!0?c:e,d)}:b}function bj(a,b,c){var d,e,f=0;for(;d=a[f];f++)$.relative[d.part]?e=bh(e,$.relative[d.part],b):(d.captures.push(b,c),e=bi(e,$.filter[d.part].apply(null,d.captures)));return e}function bk(a){return function(b,c){var d,e=0;for(;d=a[e];e++)if(d(b,c))return!0;return!1}}var c,d,e,f,g,h=a.document,i=h.documentElement,j="undefined",k=!1,l=!0,m=0,n=[].slice,o=[].push,q=("sizcache"+Math.random()).replace(".",""),r="[\\x20\\t\\r\\n\\f]",s="(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",t=s.replace("w","w#"),u="([*^$|!~]?=)",v="\\["+r+"*("+s+")"+r+"*(?:"+u+r+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+t+")|)|)"+r+"*\\]",w=":("+s+")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|((?:[^,]|\\\\,|(?:,(?=[^\\[]*\\]))|(?:,(?=[^\\(]*\\))))*))\\)|)",x=":(nth|eq|gt|lt|first|last|even|odd)(?:\\((\\d*)\\)|)(?=[^-]|$)",y=r+"*([\\x20\\t\\r\\n\\f>+~])"+r+"*",z="(?=[^\\x20\\t\\r\\n\\f])(?:\\\\.|"+v+"|"+w.replace(2,7)+"|[^\\\\(),])+",A=new RegExp("^"+r+"+|((?:^|[^\\\\])(?:\\\\.)*)"+r+"+$","g"),B=new RegExp("^"+y),C=new RegExp(z+"?(?="+r+"*,|$)","g"),D=new RegExp("^(?:(?!,)(?:(?:^|,)"+r+"*"+z+")*?|"+r+"*(.*?))(\\)|$)"),E=new RegExp(z.slice(19,-6)+"\\x20\\t\\r\\n\\f>+~])+|"+y,"g"),F=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,G=/[\x20\t\r\n\f]*[+~]/,H=/:not\($/,I=/h\d/i,J=/input|select|textarea|button/i,K=/\\(?!\\)/g,L={ID:new RegExp("^#("+s+")"),CLASS:new RegExp("^\\.("+s+")"),NAME:new RegExp("^\\[name=['\"]?("+s+")['\"]?\\]"),TAG:new RegExp("^("+s.replace("[-","[-\\*")+")"),ATTR:new RegExp("^"+v),PSEUDO:new RegExp("^"+w),CHILD:new RegExp("^:(only|nth|last|first)-child(?:\\("+r+"*(even|odd|(([+-]|)(\\d*)n|)"+r+"*(?:([+-]|)"+r+"*(\\d+)|))"+r+"*\\)|)","i"),POS:new RegExp(x,"ig"),needsContext:new RegExp("^"+r+"*[>+~]|"+x,"i")},M={},N=[],O={},P=[],Q=function(a){return a.sizzleFilter=!0,a},R=function(a){return function(b){return b.nodeName.toLowerCase()==="input"&&b.type===a}},S=function(a){return function(b){var c=b.nodeName.toLowerCase();return(c==="input"||c==="button")&&b.type===a}},T=function(a){var b=!1,c=h.createElement("div");try{b=a(c)}catch(d){}return c=null,b},U=T(function(a){a.innerHTML="<select></select>";var b=typeof a.lastChild.getAttribute("multiple");return b!=="boolean"&&b!=="string"}),V=T(function(a){a.id=q+0,a.innerHTML="<a name='"+q+"'></a><div name='"+q+"'></div>",i.insertBefore(a,i.firstChild);var b=h.getElementsByName&&h.getElementsByName(q).length===2+h.getElementsByName(q+0).length;return g=!h.getElementById(q),i.removeChild(a),b}),W=T(function(a){return a.appendChild(h.createComment("")),a.getElementsByTagName("*").length===0}),X=T(function(a){return a.innerHTML="<a href='#'></a>",a.firstChild&&typeof a.firstChild.getAttribute!==j&&a.firstChild.getAttribute("href")==="#"}),Y=T(function(a){return a.innerHTML="<div class='hidden e'></div><div class='hidden'></div>",!a.getElementsByClassName||a.getElementsByClassName("e").length===0?!1:(a.lastChild.className="e",a.getElementsByClassName("e").length!==1)}),Z=function(a,b,c,d){c=c||[],b=b||h;var e,f,g,i,j=b.nodeType;if(j!==1&&j!==9)return[];if(!a||typeof a!="string")return c;g=ba(b);if(!g&&!d)if(e=F.exec(a))if(i=e[1]){if(j===9){f=b.getElementById(i);if(!f||!f.parentNode)return c;if(f.id===i)return c.push(f),c}else if(b.ownerDocument&&(f=b.ownerDocument.getElementById(i))&&bb(b,f)&&f.id===i)return c.push(f),c}else{if(e[2])return o.apply(c,n.call(b.getElementsByTagName(a),0)),c;if((i=e[3])&&Y&&b.getElementsByClassName)return o.apply(c,n.call(b.getElementsByClassName(i),0)),c}return bm(a,b,c,d,g)},$=Z.selectors={cacheLength:50,match:L,order:["ID","TAG"],attrHandle:{},createPseudo:Q,find:{ID:g?function(a,b,c){if(typeof b.getElementById!==j&&!c){var d=b.getElementById(a);return d&&d.parentNode?[d]:[]}}:function(a,c,d){if(typeof c.getElementById!==j&&!d){var e=c.getElementById(a);return e?e.id===a||typeof e.getAttributeNode!==j&&e.getAttributeNode("id").value===a?[e]:b:[]}},TAG:W?function(a,b){if(typeof b.getElementsByTagName!==j)return b.getElementsByTagName(a)}:function(a,b){var c=b.getElementsByTagName(a);if(a==="*"){var d,e=[],f=0;for(;d=c[f];f++)d.nodeType===1&&e.push(d);return e}return c}},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(K,""),a[3]=(a[4]||a[5]||"").replace(K,""),a[2]==="~="&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),a[1]==="nth"?(a[2]||Z.error(a[0]),a[3]=+(a[3]?a[4]+(a[5]||1):2*(a[2]==="even"||a[2]==="odd")),a[4]=+(a[6]+a[7]||a[2]==="odd")):a[2]&&Z.error(a[0]),a},PSEUDO:function(a){var b,c=a[4];return L.CHILD.test(a[0])?null:(c&&(b=D.exec(c))&&b.pop()&&(a[0]=a[0].slice(0,b[0].length-c.length-1),c=b[0].slice(0,-1)),a.splice(2,3,c||a[3]),a)}},filter:{ID:g?function(a){return a=a.replace(K,""),function(b){return b.getAttribute("id")===a}}:function(a){return a=a.replace(K,""),function(b){var c=typeof b.getAttributeNode!==j&&b.getAttributeNode("id");return c&&c.value===a}},TAG:function(a){return a==="*"?function(){return!0}:(a=a.replace(K,"").toLowerCase(),function(b){return b.nodeName&&b.nodeName.toLowerCase()===a})},CLASS:function(a){var b=M[a];return b||(b=M[a]=new RegExp("(^|"+r+")"+a+"("+r+"|$)"),N.push(a),N.length>$.cacheLength&&delete M[N.shift()]),function(a){return b.test(a.className||typeof a.getAttribute!==j&&a.getAttribute("class")||"")}},ATTR:function(a,b,c){return b?function(d){var e=Z.attr(d,a),f=e+"";if(e==null)return b==="!=";switch(b){case"=":return f===c;case"!=":return f!==c;case"^=":return c&&f.indexOf(c)===0;case"*=":return c&&f.indexOf(c)>-1;case"$=":return c&&f.substr(f.length-c.length)===c;case"~=":return(" "+f+" ").indexOf(c)>-1;case"|=":return f===c||f.substr(0,c.length+1)===c+"-"}}:function(b){return Z.attr(b,a)!=null}},CHILD:function(a,b,c,d){if(a==="nth"){var e=m++;return function(a){var b,f,g=0,h=a;if(c===1&&d===0)return!0;b=a.parentNode;if(b&&(b[q]!==e||!a.sizset)){for(h=b.firstChild;h;h=h.nextSibling)if(h.nodeType===1){h.sizset=++g;if(h===a)break}b[q]=e}return f=a.sizset-d,c===0?f===0:f%c===0&&f/c>=0}}return function(b){var c=b;switch(a){case"only":case"first":while(c=c.previousSibling)if(c.nodeType===1)return!1;if(a==="first")return!0;c=b;case"last":while(c=c.nextSibling)if(c.nodeType===1)return!1;return!0}}},PSEUDO:function(a,b,c,d){var e=$.pseudos[a]||$.pseudos[a.toLowerCase()];return e||Z.error("unsupported pseudo: "+a),e.sizzleFilter?e(b,c,d):e}},pseudos:{not:Q(function(a,b,c){var d=bl(a.replace(A,"$1"),b,c);return function(a){return!d(a)}}),enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&!!a.checked||b==="option"&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},parent:function(a){return!$.pseudos.empty(a)},empty:function(a){var b;a=a.firstChild;while(a){if(a.nodeName>"@"||(b=a.nodeType)===3||b===4)return!1;a=a.nextSibling}return!0},contains:Q(function(a){return function(b){return(b.textContent||b.innerText||bc(b)).indexOf(a)>-1}}),has:Q(function(a){return function(b){return Z(a,b).length>0}}),header:function(a){return I.test(a.nodeName)},text:function(a){var b,c;return a.nodeName.toLowerCase()==="input"&&(b=a.type)==="text"&&((c=a.getAttribute("type"))==null||c.toLowerCase()===b)},radio:R("radio"),checkbox:R("checkbox"),file:R("file"),password:R("password"),image:R("image"),submit:S("submit"),reset:S("reset"),button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&a.type==="button"||b==="button"},input:function(a){return J.test(a.nodeName)},focus:function(a){var b=a.ownerDocument;return a===b.activeElement&&(!b.hasFocus||b.hasFocus())&&(!!a.type||!!a.href)},active:function(a){return a===a.ownerDocument.activeElement}},setFilters:{first:function(a,b,c){return c?a.slice(1):[a[0]]},last:function(a,b,c){var d=a.pop();return c?a:[d]},even:function(a,b,c){var d=[],e=c?1:0,f=a.length;for(;e<f;e=e+2)d.push(a[e]);return d},odd:function(a,b,c){var d=[],e=c?0:1,f=a.length;for(;e<f;e=e+2)d.push(a[e]);return d},lt:function(a,b,c){return c?a.slice(+b):a.slice(0,+b)},gt:function(a,b,c){return c?a.slice(0,+b+1):a.slice(+b+1)},eq:function(a,b,c){var d=a.splice(+b,1);return c?a:d}}};$.setFilters.nth=$.setFilters.eq,$.filters=$.pseudos,X||($.attrHandle={href:function(a){return a.getAttribute("href",2)},type:function(a){return a.getAttribute("type")}}),V&&($.order.push("NAME"),$.find.NAME=function(a,b){if(typeof b.getElementsByName!==j)return b.getElementsByName(a)}),Y&&($.order.splice(1,0,"CLASS"),$.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!==j&&!c)return b.getElementsByClassName(a)});try{n.call(i.childNodes,0)[0].nodeType}catch(_){n=function(a){var b,c=[];for(;b=this[a];a++)c.push(b);return c}}var ba=Z.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?b.nodeName!=="HTML":!1},bb=Z.contains=i.compareDocumentPosition?function(a,b){return!!(a.compareDocumentPosition(b)&16)}:i.contains?function(a,b){var c=a.nodeType===9?a.documentElement:a,d=b.parentNode;return a===d||!!(d&&d.nodeType===1&&c.contains&&c.contains(d))}:function(a,b){while(b=b.parentNode)if(b===a)return!0;return!1},bc=Z.getText=function(a){var b,c="",d=0,e=a.nodeType;if(e){if(e===1||e===9||e===11){if(typeof a.textContent=="string")return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=bc(a)}else if(e===3||e===4)return a.nodeValue}else for(;b=a[d];d++)c+=bc(b);return c};Z.attr=function(a,b){var c,d=ba(a);return d||(b=b.toLowerCase()),$.attrHandle[b]?$.attrHandle[b](a):U||d?a.getAttribute(b):(c=a.getAttributeNode(b),c?typeof a[b]=="boolean"?a[b]?b:null:c.specified?c.value:null:null)},Z.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},[0,0].sort(function(){return l=0}),i.compareDocumentPosition?e=function(a,b){return a===b?(k=!0,0):(!a.compareDocumentPosition||!b.compareDocumentPosition?a.compareDocumentPosition:a.compareDocumentPosition(b)&4)?-1:1}:(e=function(a,b){if(a===b)return k=!0,0;if(a.sourceIndex&&b.sourceIndex)return a.sourceIndex-b.sourceIndex;var c,d,e=[],g=[],h=a.parentNode,i=b.parentNode,j=h;if(h===i)return f(a,b);if(!h)return-1;if(!i)return 1;while(j)e.unshift(j),j=j.parentNode;j=i;while(j)g.unshift(j),j=j.parentNode;c=e.length,d=g.length;for(var l=0;l<c&&l<d;l++)if(e[l]!==g[l])return f(e[l],g[l]);return l===c?f(a,g[l],-1):f(e[l],b,1)},f=function(a,b,c){if(a===b)return c;var d=a.nextSibling;while(d){if(d===b)return-1;d=d.nextSibling}return 1}),Z.uniqueSort=function(a){var b,c=1;if(e){k=l,a.sort(e);if(k)for(;b=a[c];c++)b===a[c-1]&&a.splice(c--,1)}return a};var bl=Z.compile=function(a,b,c){var d,e,f,g=O[a];if(g&&g.context===b)return g;e=bg(a,b,c);for(f=0;d=e[f];f++)e[f]=bj(d,b,c);return g=O[a]=bk(e),g.context=b,g.runs=g.dirruns=0,P.push(a),P.length>$.cacheLength&&delete O[P.shift()],g};Z.matches=function(a,b){return Z(a,null,null,b)},Z.matchesSelector=function(a,b){return Z(b,null,null,[a]).length>0};var bm=function(a,b,e,f,g){a=a.replace(A,"$1");var h,i,j,k,l,m,p,q,r,s=a.match(C),t=a.match(E),u=b.nodeType;if(L.POS.test(a))return bf(a,b,e,f,s);if(f)h=n.call(f,0);else if(s&&s.length===1){if(t.length>1&&u===9&&!g&&(s=L.ID.exec(t[0]))){b=$.find.ID(s[1],b,g)[0];if(!b)return e;a=a.slice(t.shift().length)}q=(s=G.exec(t[0]))&&!s.index&&b.parentNode||b,r=t.pop(),m=r.split(":not")[0];for(j=0,k=$.order.length;j<k;j++){p=$.order[j];if(s=L[p].exec(m)){h=$.find[p]((s[1]||"").replace(K,""),q,g);if(h==null)continue;m===r&&(a=a.slice(0,a.length-r.length)+m.replace(L[p],""),a||o.apply(e,n.call(h,0)));break}}}if(a){i=bl(a,b,g),d=i.dirruns++,h==null&&(h=$.find.TAG("*",G.test(a)&&b.parentNode||b));for(j=0;l=h[j];j++)c=i.runs++,i(l,b)&&e.push(l)}return e};h.querySelectorAll&&function(){var a,b=bm,c=/'|\\/g,d=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,e=[],f=[":active"],g=i.matchesSelector||i.mozMatchesSelector||i.webkitMatchesSelector||i.oMatchesSelector||i.msMatchesSelector;T(function(a){a.innerHTML="<select><option selected></option></select>",a.querySelectorAll("[selected]").length||e.push("\\["+r+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),a.querySelectorAll(":checked").length||e.push(":checked")}),T(function(a){a.innerHTML="<p test=''></p>",a.querySelectorAll("[test^='']").length&&e.push("[*^$]="+r+"*(?:\"\"|'')"),a.innerHTML="<input type='hidden'>",a.querySelectorAll(":enabled").length||e.push(":enabled",":disabled")}),e=e.length&&new RegExp(e.join("|")),bm=function(a,d,f,g,h){if(!g&&!h&&(!e||!e.test(a)))if(d.nodeType===9)try{return o.apply(f,n.call(d.querySelectorAll(a),0)),f}catch(i){}else if(d.nodeType===1&&d.nodeName.toLowerCase()!=="object"){var j=d.getAttribute("id"),k=j||q,l=G.test(a)&&d.parentNode||d;j?k=k.replace(c,"\\$&"):d.setAttribute("id",k);try{return o.apply(f,n.call(l.querySelectorAll(a.replace(C,"[id='"+k+"'] $&")),0)),f}catch(i){}finally{j||d.removeAttribute("id")}}return b(a,d,f,g,h)},g&&(T(function(b){a=g.call(b,"div");try{g.call(b,"[test!='']:sizzle"),f.push($.match.PSEUDO)}catch(c){}}),f=new RegExp(f.join("|")),Z.matchesSelector=function(b,c){c=c.replace(d,"='$1']");if(!ba(b)&&!f.test(c)&&(!e||!e.test(c)))try{var h=g.call(b,c);if(h||a||b.document&&b.document.nodeType!==11)return h}catch(i){}return Z(c,null,null,[b]).length>0})}(),Z.attr=p.attr,p.find=Z,p.expr=Z.selectors,p.expr[":"]=p.expr.pseudos,p.unique=Z.uniqueSort,p.text=Z.getText,p.isXMLDoc=Z.isXML,p.contains=Z.contains}(a);var bc=/Until$/,bd=/^(?:parents|prev(?:Until|All))/,be=/^.[^:#\[\.,]*$/,bf=p.expr.match.needsContext,bg={children:!0,contents:!0,next:!0,prev:!0};p.fn.extend({find:function(a){var b,c,d,e,f,g,h=this;if(typeof a!="string")return p(a).filter(function(){for(b=0,c=h.length;b<c;b++)if(p.contains(h[b],this))return!0});g=this.pushStack("","find",a);for(b=0,c=this.length;b<c;b++){d=g.length,p.find(a,this[b],g);if(b>0)for(e=d;e<g.length;e++)for(f=0;f<d;f++)if(g[f]===g[e]){g.splice(e--,1);break}}return g},has:function(a){var b,c=p(a,this),d=c.length;return this.filter(function(){for(b=0;b<d;b++)if(p.contains(this,c[b]))return!0})},not:function(a){return this.pushStack(bj(this,a,!1),"not",a)},filter:function(a){return this.pushStack(bj(this,a,!0),"filter",a)},is:function(a){return!!a&&(typeof a=="string"?bf.test(a)?p(a,this.context).index(this[0])>=0:p.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c,d=0,e=this.length,f=[],g=bf.test(a)||typeof a!="string"?p(a,b||this.context):0;for(;d<e;d++){c=this[d];while(c&&c.ownerDocument&&c!==b&&c.nodeType!==11){if(g?g.index(c)>-1:p.find.matchesSelector(c,a)){f.push(c);break}c=c.parentNode}}return f=f.length>1?p.unique(f):f,this.pushStack(f,"closest",a)},index:function(a){return a?typeof a=="string"?p.inArray(this[0],p(a)):p.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.prevAll().length:-1},add:function(a,b){var c=typeof a=="string"?p(a,b):p.makeArray(a&&a.nodeType?[a]:a),d=p.merge(this.get(),c);return this.pushStack(bh(c[0])||bh(d[0])?d:p.unique(d))},addBack:function(a){return this.add(a==null?this.prevObject:this.prevObject.filter(a))}}),p.fn.andSelf=p.fn.addBack,p.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return p.dir(a,"parentNode")},parentsUntil:function(a,b,c){return p.dir(a,"parentNode",c)},next:function(a){return bi(a,"nextSibling")},prev:function(a){return bi(a,"previousSibling")},nextAll:function(a){return p.dir(a,"nextSibling")},prevAll:function(a){return p.dir(a,"previousSibling")},nextUntil:function(a,b,c){return p.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return p.dir(a,"previousSibling",c)},siblings:function(a){return p.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return p.sibling(a.firstChild)},contents:function(a){return p.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:p.merge([],a.childNodes)}},function(a,b){p.fn[a]=function(c,d){var e=p.map(this,b,c);return bc.test(a)||(d=c),d&&typeof d=="string"&&(e=p.filter(d,e)),e=this.length>1&&!bg[a]?p.unique(e):e,this.length>1&&bd.test(a)&&(e=e.reverse()),this.pushStack(e,a,k.call(arguments).join(","))}}),p.extend({filter:function(a,b,c){return c&&(a=":not("+a+")"),b.length===1?p.find.matchesSelector(b[0],a)?[b[0]]:[]:p.find.matches(a,b)},dir:function(a,c,d){var e=[],f=a[c];while(f&&f.nodeType!==9&&(d===b||f.nodeType!==1||!p(f).is(d)))f.nodeType===1&&e.push(f),f=f[c];return e},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var bl="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",bm=/ jQuery\d+="(?:null|\d+)"/g,bn=/^\s+/,bo=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bp=/<([\w:]+)/,bq=/<tbody/i,br=/<|&#?\w+;/,bs=/<(?:script|style|link)/i,bt=/<(?:script|object|embed|option|style)/i,bu=new RegExp("<(?:"+bl+")[\\s/>]","i"),bv=/^(?:checkbox|radio)$/,bw=/checked\s*(?:[^=]|=\s*.checked.)/i,bx=/\/(java|ecma)script/i,by=/^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g,bz={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]},bA=bk(e),bB=bA.appendChild(e.createElement("div"));bz.optgroup=bz.option,bz.tbody=bz.tfoot=bz.colgroup=bz.caption=bz.thead,bz.th=bz.td,p.support.htmlSerialize||(bz._default=[1,"X<div>","</div>"]),p.fn.extend({text:function(a){return p.access(this,function(a){return a===b?p.text(this):this.empty().append((this[0]&&this[0].ownerDocument||e).createTextNode(a))},null,a,arguments.length)},wrapAll:function(a){if(p.isFunction(a))return this.each(function(b){p(this).wrapAll(a.call(this,b))});if(this[0]){var b=p(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return p.isFunction(a)?this.each(function(b){p(this).wrapInner(a.call(this,b))}):this.each(function(){var b=p(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=p.isFunction(a);return this.each(function(c){p(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){p.nodeName(this,"body")||p(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){(this.nodeType===1||this.nodeType===11)&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){(this.nodeType===1||this.nodeType===11)&&this.insertBefore(a,this.firstChild)})},before:function(){if(!bh(this[0]))return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=p.clean(arguments);return this.pushStack(p.merge(a,this),"before",this.selector)}},after:function(){if(!bh(this[0]))return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=p.clean(arguments);return this.pushStack(p.merge(this,a),"after",this.selector)}},remove:function(a,b){var c,d=0;for(;(c=this[d])!=null;d++)if(!a||p.filter(a,[c]).length)!b&&c.nodeType===1&&(p.cleanData(c.getElementsByTagName("*")),p.cleanData([c])),c.parentNode&&c.parentNode.removeChild(c);return this},empty:function(){var a,b=0;for(;(a=this[b])!=null;b++){a.nodeType===1&&p.cleanData(a.getElementsByTagName("*"));while(a.firstChild)a.removeChild(a.firstChild)}return this},clone:function(a,b){return a=a==null?!1:a,b=b==null?a:b,this.map(function(){return p.clone(this,a,b)})},html:function(a){return p.access(this,function(a){var c=this[0]||{},d=0,e=this.length;if(a===b)return c.nodeType===1?c.innerHTML.replace(bm,""):b;if(typeof a=="string"&&!bs.test(a)&&(p.support.htmlSerialize||!bu.test(a))&&(p.support.leadingWhitespace||!bn.test(a))&&!bz[(bp.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(bo,"<$1></$2>");try{for(;d<e;d++)c=this[d]||{},c.nodeType===1&&(p.cleanData(c.getElementsByTagName("*")),c.innerHTML=a);c=0}catch(f){}}c&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(a){return bh(this[0])?this.length?this.pushStack(p(p.isFunction(a)?a():a),"replaceWith",a):this:p.isFunction(a)?this.each(function(b){var c=p(this),d=c.html();c.replaceWith(a.call(this,b,d))}):(typeof a!="string"&&(a=p(a).detach()),this.each(function(){var b=this.nextSibling,c=this.parentNode;p(this).remove(),b?p(b).before(a):p(c).append(a)}))},detach:function(a){return this.remove(a,!0)},domManip:function(a,c,d){a=[].concat.apply([],a);var e,f,g,h,i=0,j=a[0],k=[],l=this.length;if(!p.support.checkClone&&l>1&&typeof j=="string"&&bw.test(j))return this.each(function(){p(this).domManip(a,c,d)});if(p.isFunction(j))return this.each(function(e){var f=p(this);a[0]=j.call(this,e,c?f.html():b),f.domManip(a,c,d)});if(this[0]){e=p.buildFragment(a,this,k),g=e.fragment,f=g.firstChild,g.childNodes.length===1&&(g=f);if(f){c=c&&p.nodeName(f,"tr");for(h=e.cacheable||l-1;i<l;i++)d.call(c&&p.nodeName(this[i],"table")?bC(this[i],"tbody"):this[i],i===h?g:p.clone(g,!0,!0))}g=f=null,k.length&&p.each(k,function(a,b){b.src?p.ajax?p.ajax({url:b.src,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0}):p.error("no ajax"):p.globalEval((b.text||b.textContent||b.innerHTML||"").replace(by,"")),b.parentNode&&b.parentNode.removeChild(b)})}return this}}),p.buildFragment=function(a,c,d){var f,g,h,i=a[0];return c=c||e,c=(c[0]||c).ownerDocument||c[0]||c,typeof c.createDocumentFragment=="undefined"&&(c=e),a.length===1&&typeof i=="string"&&i.length<512&&c===e&&i.charAt(0)==="<"&&!bt.test(i)&&(p.support.checkClone||!bw.test(i))&&(p.support.html5Clone||!bu.test(i))&&(g=!0,f=p.fragments[i],h=f!==b),f||(f=c.createDocumentFragment(),p.clean(a,c,f,d),g&&(p.fragments[i]=h&&f)),{fragment:f,cacheable:g}},p.fragments={},p.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){p.fn[a]=function(c){var d,e=0,f=[],g=p(c),h=g.length,i=this.length===1&&this[0].parentNode;if((i==null||i&&i.nodeType===11&&i.childNodes.length===1)&&h===1)return g[b](this[0]),this;for(;e<h;e++)d=(e>0?this.clone(!0):this).get(),p(g[e])[b](d),f=f.concat(d);return this.pushStack(f,a,g.selector)}}),p.extend({clone:function(a,b,c){var d,e,f,g;p.support.html5Clone||p.isXMLDoc(a)||!bu.test("<"+a.nodeName+">")?g=a.cloneNode(!0):(bB.innerHTML=a.outerHTML,bB.removeChild(g=bB.firstChild));if((!p.support.noCloneEvent||!p.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!p.isXMLDoc(a)){bE(a,g),d=bF(a),e=bF(g);for(f=0;d[f];++f)e[f]&&bE(d[f],e[f])}if(b){bD(a,g);if(c){d=bF(a),e=bF(g);for(f=0;d[f];++f)bD(d[f],e[f])}}return d=e=null,g},clean:function(a,b,c,d){var f,g,h,i,j,k,l,m,n,o,q,r,s=0,t=[];if(!b||typeof b.createDocumentFragment=="undefined")b=e;for(g=b===e&&bA;(h=a[s])!=null;s++){typeof h=="number"&&(h+="");if(!h)continue;if(typeof h=="string")if(!br.test(h))h=b.createTextNode(h);else{g=g||bk(b),l=l||g.appendChild(b.createElement("div")),h=h.replace(bo,"<$1></$2>"),i=(bp.exec(h)||["",""])[1].toLowerCase(),j=bz[i]||bz._default,k=j[0],l.innerHTML=j[1]+h+j[2];while(k--)l=l.lastChild;if(!p.support.tbody){m=bq.test(h),n=i==="table"&&!m?l.firstChild&&l.firstChild.childNodes:j[1]==="<table>"&&!m?l.childNodes:[];for(f=n.length-1;f>=0;--f)p.nodeName(n[f],"tbody")&&!n[f].childNodes.length&&n[f].parentNode.removeChild(n[f])}!p.support.leadingWhitespace&&bn.test(h)&&l.insertBefore(b.createTextNode(bn.exec(h)[0]),l.firstChild),h=l.childNodes,l=g.lastChild}h.nodeType?t.push(h):t=p.merge(t,h)}l&&(g.removeChild(l),h=l=g=null);if(!p.support.appendChecked)for(s=0;(h=t[s])!=null;s++)p.nodeName(h,"input")?bG(h):typeof h.getElementsByTagName!="undefined"&&p.grep(h.getElementsByTagName("input"),bG);if(c){q=function(a){if(!a.type||bx.test(a.type))return d?d.push(a.parentNode?a.parentNode.removeChild(a):a):c.appendChild(a)};for(s=0;(h=t[s])!=null;s++)if(!p.nodeName(h,"script")||!q(h))c.appendChild(h),typeof h.getElementsByTagName!="undefined"&&(r=p.grep(p.merge([],h.getElementsByTagName("script")),q),t.splice.apply(t,[s+1,0].concat(r)),s+=r.length)}return t},cleanData:function(a,b){var c,d,e,f,g=0,h=p.expando,i=p.cache,j=p.support.deleteExpando,k=p.event.special;for(;(e=a[g])!=null;g++)if(b||p.acceptData(e)){d=e[h],c=d&&i[d];if(c){if(c.events)for(f in c.events)k[f]?p.event.remove(e,f):p.removeEvent(e,f,c.handle);i[d]&&(delete i[d],j?delete e[h]:e.removeAttribute?e.removeAttribute(h):e[h]=null,p.deletedIds.push(d))}}}}),function(){var a,b;p.uaMatch=function(a){a=a.toLowerCase();var b=/(chrome)[ \/]([\w.]+)/.exec(a)||/(webkit)[ \/]([\w.]+)/.exec(a)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(a)||/(msie) ([\w.]+)/.exec(a)||a.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},a=p.uaMatch(g.userAgent),b={},a.browser&&(b[a.browser]=!0,b.version=a.version),b.webkit&&(b.safari=!0),p.browser=b,p.sub=function(){function a(b,c){return new a.fn.init(b,c)}p.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.sub=this.sub,a.fn.init=function c(c,d){return d&&d instanceof p&&!(d instanceof a)&&(d=a(d)),p.fn.init.call(this,c,d,b)},a.fn.init.prototype=a.fn;var b=a(e);return a}}();var bH,bI,bJ,bK=/alpha\([^)]*\)/i,bL=/opacity=([^)]*)/,bM=/^(top|right|bottom|left)$/,bN=/^margin/,bO=new RegExp("^("+q+")(.*)$","i"),bP=new RegExp("^("+q+")(?!px)[a-z%]+$","i"),bQ=new RegExp("^([-+])=("+q+")","i"),bR={},bS={position:"absolute",visibility:"hidden",display:"block"},bT={letterSpacing:0,fontWeight:400,lineHeight:1},bU=["Top","Right","Bottom","Left"],bV=["Webkit","O","Moz","ms"],bW=p.fn.toggle;p.fn.extend({css:function(a,c){return p.access(this,function(a,c,d){return d!==b?p.style(a,c,d):p.css(a,c)},a,c,arguments.length>1)},show:function(){return bZ(this,!0)},hide:function(){return bZ(this)},toggle:function(a,b){var c=typeof a=="boolean";return p.isFunction(a)&&p.isFunction(b)?bW.apply(this,arguments):this.each(function(){(c?a:bY(this))?p(this).show():p(this).hide()})}}),p.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=bH(a,"opacity");return c===""?"1":c}}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":p.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(!a||a.nodeType===3||a.nodeType===8||!a.style)return;var f,g,h,i=p.camelCase(c),j=a.style;c=p.cssProps[i]||(p.cssProps[i]=bX(j,i)),h=p.cssHooks[c]||p.cssHooks[i];if(d===b)return h&&"get"in h&&(f=h.get(a,!1,e))!==b?f:j[c];g=typeof d,g==="string"&&(f=bQ.exec(d))&&(d=(f[1]+1)*f[2]+parseFloat(p.css(a,c)),g="number");if(d==null||g==="number"&&isNaN(d))return;g==="number"&&!p.cssNumber[i]&&(d+="px");if(!h||!("set"in h)||(d=h.set(a,d,e))!==b)try{j[c]=d}catch(k){}},css:function(a,c,d,e){var f,g,h,i=p.camelCase(c);return c=p.cssProps[i]||(p.cssProps[i]=bX(a.style,i)),h=p.cssHooks[c]||p.cssHooks[i],h&&"get"in h&&(f=h.get(a,!0,e)),f===b&&(f=bH(a,c)),f==="normal"&&c in bT&&(f=bT[c]),d||e!==b?(g=parseFloat(f),d||p.isNumeric(g)?g||0:f):f},swap:function(a,b,c){var d,e,f={};for(e in b)f[e]=a.style[e],a.style[e]=b[e];d=c.call(a);for(e in b)a.style[e]=f[e];return d}}),a.getComputedStyle?bH=function(a,b){var c,d,e,f,g=getComputedStyle(a,null),h=a.style;return g&&(c=g[b],c===""&&!p.contains(a.ownerDocument.documentElement,a)&&(c=p.style(a,b)),bP.test(c)&&bN.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=c,c=g.width,h.width=d,h.minWidth=e,h.maxWidth=f)),c}:e.documentElement.currentStyle&&(bH=function(a,b){var c,d,e=a.currentStyle&&a.currentStyle[b],f=a.style;return e==null&&f&&f[b]&&(e=f[b]),bP.test(e)&&!bM.test(b)&&(c=f.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),f.left=b==="fontSize"?"1em":e,e=f.pixelLeft+"px",f.left=c,d&&(a.runtimeStyle.left=d)),e===""?"auto":e}),p.each(["height","width"],function(a,b){p.cssHooks[b]={get:function(a,c,d){if(c)return a.offsetWidth!==0||bH(a,"display")!=="none"?ca(a,b,d):p.swap(a,bS,function(){return ca(a,b,d)})},set:function(a,c,d){return b$(a,c,d?b_(a,b,d,p.support.boxSizing&&p.css(a,"boxSizing")==="border-box"):0)}}}),p.support.opacity||(p.cssHooks.opacity={get:function(a,b){return bL.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=p.isNumeric(b)?"alpha(opacity="+b*100+")":"",f=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&p.trim(f.replace(bK,""))===""&&c.removeAttribute){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bK.test(f)?f.replace(bK,e):f+" "+e}}),p(function(){p.support.reliableMarginRight||(p.cssHooks.marginRight={get:function(a,b){return p.swap(a,{display:"inline-block"},function(){if(b)return bH(a,"marginRight")})}}),!p.support.pixelPosition&&p.fn.position&&p.each(["top","left"],function(a,b){p.cssHooks[b]={get:function(a,c){if(c){var d=bH(a,b);return bP.test(d)?p(a).position()[b]+"px":d}}}})}),p.expr&&p.expr.filters&&(p.expr.filters.hidden=function(a){return a.offsetWidth===0&&a.offsetHeight===0||!p.support.reliableHiddenOffsets&&(a.style&&a.style.display||bH(a,"display"))==="none"},p.expr.filters.visible=function(a){return!p.expr.filters.hidden(a)}),p.each({margin:"",padding:"",border:"Width"},function(a,b){p.cssHooks[a+b]={expand:function(c){var d,e=typeof c=="string"?c.split(" "):[c],f={};for(d=0;d<4;d++)f[a+bU[d]+b]=e[d]||e[d-2]||e[0];return f}},bN.test(a)||(p.cssHooks[a+b].set=b$)});var cc=/%20/g,cd=/\[\]$/,ce=/\r?\n/g,cf=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,cg=/^(?:select|textarea)/i;p.fn.extend({serialize:function(){return p.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?p.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||cg.test(this.nodeName)||cf.test(this.type))}).map(function(a,b){var c=p(this).val();return c==null?null:p.isArray(c)?p.map(c,function(a,c){return{name:b.name,value:a.replace(ce,"\r\n")}}):{name:b.name,value:c.replace(ce,"\r\n")}}).get()}}),p.param=function(a,c){var d,e=[],f=function(a,b){b=p.isFunction(b)?b():b==null?"":b,e[e.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=p.ajaxSettings&&p.ajaxSettings.traditional);if(p.isArray(a)||a.jquery&&!p.isPlainObject(a))p.each(a,function(){f(this.name,this.value)});else for(d in a)ch(d,a[d],c,f);return e.join("&").replace(cc,"+")};var ci,cj,ck=/#.*$/,cl=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,cm=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,cn=/^(?:GET|HEAD)$/,co=/^\/\//,cp=/\?/,cq=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,cr=/([?&])_=[^&]*/,cs=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,ct=p.fn.load,cu={},cv={},cw=["*/"]+["*"];try{ci=f.href}catch(cx){ci=e.createElement("a"),ci.href="",ci=ci.href}cj=cs.exec(ci.toLowerCase())||[],p.fn.load=function(a,c,d){if(typeof a!="string"&&ct)return ct.apply(this,arguments);if(!this.length)return this;var e,f,g,h=this,i=a.indexOf(" ");return i>=0&&(e=a.slice(i,a.length),a=a.slice(0,i)),p.isFunction(c)?(d=c,c=b):typeof c=="object"&&(f="POST"),p.ajax({url:a,type:f,dataType:"html",data:c,complete:function(a,b){d&&h.each(d,g||[a.responseText,b,a])}}).done(function(a){g=arguments,h.html(e?p("<div>").append(a.replace(cq,"")).find(e):a)}),this},p.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){p.fn[b]=function(a){return this.on(b,a)}}),p.each(["get","post"],function(a,c){p[c]=function(a,d,e,f){return p.isFunction(d)&&(f=f||e,e=d,d=b),p.ajax({type:c,url:a,data:d,success:e,dataType:f})}}),p.extend({getScript:function(a,c){return p.get(a,b,c,"script")},getJSON:function(a,b,c){return p.get(a,b,c,"json")},ajaxSetup:function(a,b){return b?cA(a,p.ajaxSettings):(b=a,a=p.ajaxSettings),cA(a,b),a},ajaxSettings:{url:ci,isLocal:cm.test(cj[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":cw},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":p.parseJSON,"text xml":p.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:cy(cu),ajaxTransport:cy(cv),ajax:function(a,c){function y(a,c,f,i){var k,s,t,u,w,y=c;if(v===2)return;v=2,h&&clearTimeout(h),g=b,e=i||"",x.readyState=a>0?4:0,f&&(u=cB(l,x,f));if(a>=200&&a<300||a===304)l.ifModified&&(w=x.getResponseHeader("Last-Modified"),w&&(p.lastModified[d]=w),w=x.getResponseHeader("Etag"),w&&(p.etag[d]=w)),a===304?(y="notmodified",k=!0):(k=cC(l,u),y=k.state,s=k.data,t=k.error,k=!t);else{t=y;if(!y||a)y="error",a<0&&(a=0)}x.status=a,x.statusText=""+(c||y),k?o.resolveWith(m,[s,y,x]):o.rejectWith(m,[x,y,t]),x.statusCode(r),r=b,j&&n.trigger("ajax"+(k?"Success":"Error"),[x,l,k?s:t]),q.fireWith(m,[x,y]),j&&(n.trigger("ajaxComplete",[x,l]),--p.active||p.event.trigger("ajaxStop"))}typeof a=="object"&&(c=a,a=b),c=c||{};var d,e,f,g,h,i,j,k,l=p.ajaxSetup({},c),m=l.context||l,n=m!==l&&(m.nodeType||m instanceof p)?p(m):p.event,o=p.Deferred(),q=p.Callbacks("once memory"),r=l.statusCode||{},t={},u={},v=0,w="canceled",x={readyState:0,setRequestHeader:function(a,b){if(!v){var c=a.toLowerCase();a=u[c]=u[c]||a,t[a]=b}return this},getAllResponseHeaders:function(){return v===2?e:null},getResponseHeader:function(a){var c;if(v===2){if(!f){f={};while(c=cl.exec(e))f[c[1].toLowerCase()]=c[2]}c=f[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){return v||(l.mimeType=a),this},abort:function(a){return a=a||w,g&&g.abort(a),y(0,a),this}};o.promise(x),x.success=x.done,x.error=x.fail,x.complete=q.add,x.statusCode=function(a){if(a){var b;if(v<2)for(b in a)r[b]=[r[b],a[b]];else b=a[x.status],x.always(b)}return this},l.url=((a||l.url)+"").replace(ck,"").replace(co,cj[1]+"//"),l.dataTypes=p.trim(l.dataType||"*").toLowerCase().split(s),l.crossDomain==null&&(i=cs.exec(l.url.toLowerCase()),l.crossDomain=!(!i||i[1]==cj[1]&&i[2]==cj[2]&&(i[3]||(i[1]==="http:"?80:443))==(cj[3]||(cj[1]==="http:"?80:443)))),l.data&&l.processData&&typeof l.data!="string"&&(l.data=p.param(l.data,l.traditional)),cz(cu,l,c,x);if(v===2)return x;j=l.global,l.type=l.type.toUpperCase(),l.hasContent=!cn.test(l.type),j&&p.active++===0&&p.event.trigger("ajaxStart");if(!l.hasContent){l.data&&(l.url+=(cp.test(l.url)?"&":"?")+l.data,delete l.data),d=l.url;if(l.cache===!1){var z=p.now(),A=l.url.replace(cr,"$1_="+z);l.url=A+(A===l.url?(cp.test(l.url)?"&":"?")+"_="+z:"")}}(l.data&&l.hasContent&&l.contentType!==!1||c.contentType)&&x.setRequestHeader("Content-Type",l.contentType),l.ifModified&&(d=d||l.url,p.lastModified[d]&&x.setRequestHeader("If-Modified-Since",p.lastModified[d]),p.etag[d]&&x.setRequestHeader("If-None-Match",p.etag[d])),x.setRequestHeader("Accept",l.dataTypes[0]&&l.accepts[l.dataTypes[0]]?l.accepts[l.dataTypes[0]]+(l.dataTypes[0]!=="*"?", "+cw+"; q=0.01":""):l.accepts["*"]);for(k in l.headers)x.setRequestHeader(k,l.headers[k]);if(!l.beforeSend||l.beforeSend.call(m,x,l)!==!1&&v!==2){w="abort";for(k in{success:1,error:1,complete:1})x[k](l[k]);g=cz(cv,l,c,x);if(!g)y(-1,"No Transport");else{x.readyState=1,j&&n.trigger("ajaxSend",[x,l]),l.async&&l.timeout>0&&(h=setTimeout(function(){x.abort("timeout")},l.timeout));try{v=1,g.send(t,y)}catch(B){if(v<2)y(-1,B);else throw B}}return x}return x.abort()},active:0,lastModified:{},etag:{}});var cD=[],cE=/\?/,cF=/(=)\?(?=&|$)|\?\?/,cG=p.now();p.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=cD.pop()||p.expando+"_"+cG++;return this[a]=!0,a}}),p.ajaxPrefilter("json jsonp",function(c,d,e){var f,g,h,i=c.data,j=c.url,k=c.jsonp!==!1,l=k&&cF.test(j),m=k&&!l&&typeof i=="string"&&!(c.contentType||"").indexOf("application/x-www-form-urlencoded")&&cF.test(i);if(c.dataTypes[0]==="jsonp"||l||m)return f=c.jsonpCallback=p.isFunction(c.jsonpCallback)?c.jsonpCallback():c.jsonpCallback,g=a[f],l?c.url=j.replace(cF,"$1"+f):m?c.data=i.replace(cF,"$1"+f):k&&(c.url+=(cE.test(j)?"&":"?")+c.jsonp+"="+f),c.converters["script json"]=function(){return h||p.error(f+" was not called"),h[0]},c.dataTypes[0]="json",a[f]=function(){h=arguments},e.always(function(){a[f]=g,c[f]&&(c.jsonpCallback=d.jsonpCallback,cD.push(f)),h&&p.isFunction(g)&&g(h[0]),h=g=b}),"script"}),p.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){return p.globalEval(a),a}}}),p.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),p.ajaxTransport("script",function(a){if(a.crossDomain){var c,d=e.head||e.getElementsByTagName("head")[0]||e.documentElement;return{send:function(f,g){c=e.createElement("script"),c.async="async",a.scriptCharset&&(c.charset=a.scriptCharset),c.src=a.url,c.onload=c.onreadystatechange=function(a,e){if(e||!c.readyState||/loaded|complete/.test(c.readyState))c.onload=c.onreadystatechange=null,d&&c.parentNode&&d.removeChild(c),c=b,e||g(200,"success")},d.insertBefore(c,d.firstChild)},abort:function(){c&&c.onload(0,1)}}}});var cH,cI=a.ActiveXObject?function(){for(var a in cH)cH[a](0,1)}:!1,cJ=0;p.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&cK()||cL()}:cK,function(a){p.extend(p.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(p.ajaxSettings.xhr()),p.support.ajax&&p.ajaxTransport(function(c){if(!c.crossDomain||p.support.cors){var d;return{send:function(e,f){var g,h,i=c.xhr();c.username?i.open(c.type,c.url,c.async,c.username,c.password):i.open(c.type,c.url,c.async);if(c.xhrFields)for(h in c.xhrFields)i[h]=c.xhrFields[h];c.mimeType&&i.overrideMimeType&&i.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(h in e)i.setRequestHeader(h,e[h])}catch(j){}i.send(c.hasContent&&c.data||null),d=function(a,e){var h,j,k,l,m;try{if(d&&(e||i.readyState===4)){d=b,g&&(i.onreadystatechange=p.noop,cI&&delete cH[g]);if(e)i.readyState!==4&&i.abort();else{h=i.status,k=i.getAllResponseHeaders(),l={},m=i.responseXML,m&&m.documentElement&&(l.xml=m);try{l.text=i.responseText}catch(a){}try{j=i.statusText}catch(n){j=""}!h&&c.isLocal&&!c.crossDomain?h=l.text?200:404:h===1223&&(h=204)}}}catch(o){e||f(-1,o)}l&&f(h,j,l,k)},c.async?i.readyState===4?setTimeout(d,0):(g=++cJ,cI&&(cH||(cH={},p(a).unload(cI)),cH[g]=d),i.onreadystatechange=d):d()},abort:function(){d&&d(0,1)}}}});var cM,cN,cO=/^(?:toggle|show|hide)$/,cP=new RegExp("^(?:([-+])=|)("+q+")([a-z%]*)$","i"),cQ=/queueHooks$/,cR=[cX],cS={"*":[function(a,b){var c,d,e,f=this.createTween(a,b),g=cP.exec(b),h=f.cur(),i=+h||0,j=1;if(g){c=+g[2],d=g[3]||(p.cssNumber[a]?"":"px");if(d!=="px"&&i){i=p.css(f.elem,a,!0)||c||1;do e=j=j||".5",i=i/j,p.style(f.elem,a,i+d),j=f.cur()/h;while(j!==1&&j!==e)}f.unit=d,f.start=i,f.end=g[1]?i+(g[1]+1)*c:c}return f}]};p.Animation=p.extend(cV,{tweener:function(a,b){p.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");var c,d=0,e=a.length;for(;d<e;d++)c=a[d],cS[c]=cS[c]||[],cS[c].unshift(b)},prefilter:function(a,b){b?cR.unshift(a):cR.push(a)}}),p.Tween=cY,cY.prototype={constructor:cY,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(p.cssNumber[c]?"":"px")},cur:function(){var a=cY.propHooks[this.prop];return a&&a.get?a.get(this):cY.propHooks._default.get(this)},run:function(a){var b,c=cY.propHooks[this.prop];return this.pos=b=p.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration),this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):cY.propHooks._default.set(this),this}},cY.prototype.init.prototype=cY.prototype,cY.propHooks={_default:{get:function(a){var b;return a.elem[a.prop]==null||!!a.elem.style&&a.elem.style[a.prop]!=null?(b=p.css(a.elem,a.prop,!1,""),!b||b==="auto"?0:b):a.elem[a.prop]},set:function(a){p.fx.step[a.prop]?p.fx.step[a.prop](a):a.elem.style&&(a.elem.style[p.cssProps[a.prop]]!=null||p.cssHooks[a.prop])?p.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},cY.propHooks.scrollTop=cY.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},p.each(["toggle","show","hide"],function(a,b){var c=p.fn[b];p.fn[b]=function(d,e,f){return d==null||typeof d=="boolean"||!a&&p.isFunction(d)&&p.isFunction(e)?c.apply(this,arguments):this.animate(cZ(b,!0),d,e,f)}}),p.fn.extend({fadeTo:function(a,b,c,d){return this.filter(bY).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=p.isEmptyObject(a),f=p.speed(b,c,d),g=function(){var b=cV(this,p.extend({},a),f);e&&b.stop(!0)};return e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,c,d){var e=function(a){var b=a.stop;delete a.stop,b(d)};return typeof a!="string"&&(d=c,c=a,a=b),c&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,c=a!=null&&a+"queueHooks",f=p.timers,g=p._data(this);if(c)g[c]&&g[c].stop&&e(g[c]);else for(c in g)g[c]&&g[c].stop&&cQ.test(c)&&e(g[c]);for(c=f.length;c--;)f[c].elem===this&&(a==null||f[c].queue===a)&&(f[c].anim.stop(d),b=!1,f.splice(c,1));(b||!d)&&p.dequeue(this,a)})}}),p.each({slideDown:cZ("show"),slideUp:cZ("hide"),slideToggle:cZ("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){p.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),p.speed=function(a,b,c){var d=a&&typeof a=="object"?p.extend({},a):{complete:c||!c&&b||p.isFunction(a)&&a,duration:a,easing:c&&b||b&&!p.isFunction(b)&&b};d.duration=p.fx.off?0:typeof d.duration=="number"?d.duration:d.duration in p.fx.speeds?p.fx.speeds[d.duration]:p.fx.speeds._default;if(d.queue==null||d.queue===!0)d.queue="fx";return d.old=d.complete,d.complete=function(){p.isFunction(d.old)&&d.old.call(this),d.queue&&p.dequeue(this,d.queue)},d},p.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},p.timers=[],p.fx=cY.prototype.init,p.fx.tick=function(){var a,b=p.timers,c=0;for(;c<b.length;c++)a=b[c],!a()&&b[c]===a&&b.splice(c--,1);b.length||p.fx.stop()},p.fx.timer=function(a){a()&&p.timers.push(a)&&!cN&&(cN=setInterval(p.fx.tick,p.fx.interval))},p.fx.interval=13,p.fx.stop=function(){clearInterval(cN),cN=null},p.fx.speeds={slow:600,fast:200,_default:400},p.fx.step={},p.expr&&p.expr.filters&&(p.expr.filters.animated=function(a){return p.grep(p.timers,function(b){return a===b.elem}).length});var c$=/^(?:body|html)$/i;p.fn.offset=function(a){if(arguments.length)return a===b?this:this.each(function(b){p.offset.setOffset(this,a,b)});var c,d,e,f,g,h,i,j,k,l,m=this[0],n=m&&m.ownerDocument;if(!n)return;return(e=n.body)===m?p.offset.bodyOffset(m):(d=n.documentElement,p.contains(d,m)?(c=m.getBoundingClientRect(),f=c_(n),g=d.clientTop||e.clientTop||0,h=d.clientLeft||e.clientLeft||0,i=f.pageYOffset||d.scrollTop,j=f.pageXOffset||d.scrollLeft,k=c.top+i-g,l=c.left+j-h,{top:k,left:l}):{top:0,left:0})},p.offset={bodyOffset:function(a){var b=a.offsetTop,c=a.offsetLeft;return p.support.doesNotIncludeMarginInBodyOffset&&(b+=parseFloat(p.css(a,"marginTop"))||0,c+=parseFloat(p.css(a,"marginLeft"))||0),{top:b,left:c}},setOffset:function(a,b,c){var d=p.css(a,"position");d==="static"&&(a.style.position="relative");var e=p(a),f=e.offset(),g=p.css(a,"top"),h=p.css(a,"left"),i=(d==="absolute"||d==="fixed")&&p.inArray("auto",[g,h])>-1,j={},k={},l,m;i?(k=e.position(),l=k.top,m=k.left):(l=parseFloat(g)||0,m=parseFloat(h)||0),p.isFunction(b)&&(b=b.call(a,c,f)),b.top!=null&&(j.top=b.top-f.top+l),b.left!=null&&(j.left=b.left-f.left+m),"using"in b?b.using.call(a,j):e.css(j)}},p.fn.extend({position:function(){if(!this[0])return;var a=this[0],b=this.offsetParent(),c=this.offset(),d=c$.test(b[0].nodeName)?{top:0,left:0}:b.offset();return c.top-=parseFloat(p.css(a,"marginTop"))||0,c.left-=parseFloat(p.css(a,"marginLeft"))||0,d.top+=parseFloat(p.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(p.css(b[0],"borderLeftWidth"))||0,{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||e.body;while(a&&!c$.test(a.nodeName)&&p.css(a,"position")==="static")a=a.offsetParent;return a||e.body})}}),p.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,c){var d=/Y/.test(c);p.fn[a]=function(e){return p.access(this,function(a,e,f){var g=c_(a);if(f===b)return g?c in g?g[c]:g.document.documentElement[e]:a[e];g?g.scrollTo(d?p(g).scrollLeft():f,d?f:p(g).scrollTop()):a[e]=f},a,e,arguments.length,null)}}),p.each({Height:"height",Width:"width"},function(a,c){p.each({padding:"inner"+a,content:c,"":"outer"+a},function(d,e){p.fn[e]=function(e,f){var g=arguments.length&&(d||typeof e!="boolean"),h=d||(e===!0||f===!0?"margin":"border");return p.access(this,function(c,d,e){var f;return p.isWindow(c)?c.document.documentElement["client"+a]:c.nodeType===9?(f=c.documentElement,Math.max(c.body["scroll"+a],f["scroll"+a],c.body["offset"+a],f["offset"+a],f["client"+a])):e===b?p.css(c,d,e,h):p.style(c,d,e,h)},c,g?e:b,g)}})}),a.jQuery=a.$=p,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return p})})(window);
+(function(a,b){function G(a){var b=F[a]={};return p.each(a.split(s),function(a,c){b[c]=!0}),b}function J(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(I,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:+d+""===d?+d:H.test(d)?p.parseJSON(d):d}catch(f){}p.data(a,c,d)}else d=b}return d}function K(a){var b;for(b in a){if(b==="data"&&p.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function ba(){return!1}function bb(){return!0}function bh(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function bi(a,b){do a=a[b];while(a&&a.nodeType!==1);return a}function bj(a,b,c){b=b||0;if(p.isFunction(b))return p.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return p.grep(a,function(a,d){return a===b===c});if(typeof b=="string"){var d=p.grep(a,function(a){return a.nodeType===1});if(be.test(b))return p.filter(b,d,!c);b=p.filter(b,d)}return p.grep(a,function(a,d){return p.inArray(a,b)>=0===c})}function bk(a){var b=bl.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}function bC(a,b){return a.getElementsByTagName(b)[0]||a.appendChild(a.ownerDocument.createElement(b))}function bD(a,b){if(b.nodeType!==1||!p.hasData(a))return;var c,d,e,f=p._data(a),g=p._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;d<e;d++)p.event.add(b,c,h[c][d])}g.data&&(g.data=p.extend({},g.data))}function bE(a,b){var c;if(b.nodeType!==1)return;b.clearAttributes&&b.clearAttributes(),b.mergeAttributes&&b.mergeAttributes(a),c=b.nodeName.toLowerCase(),c==="object"?(b.parentNode&&(b.outerHTML=a.outerHTML),p.support.html5Clone&&a.innerHTML&&!p.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):c==="input"&&bv.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):c==="option"?b.selected=a.defaultSelected:c==="input"||c==="textarea"?b.defaultValue=a.defaultValue:c==="script"&&b.text!==a.text&&(b.text=a.text),b.removeAttribute(p.expando)}function bF(a){return typeof a.getElementsByTagName!="undefined"?a.getElementsByTagName("*"):typeof a.querySelectorAll!="undefined"?a.querySelectorAll("*"):[]}function bG(a){bv.test(a.type)&&(a.defaultChecked=a.checked)}function bX(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=bV.length;while(e--){b=bV[e]+c;if(b in a)return b}return d}function bY(a,b){return a=b||a,p.css(a,"display")==="none"||!p.contains(a.ownerDocument,a)}function bZ(a,b){var c,d,e=[],f=0,g=a.length;for(;f<g;f++){c=a[f];if(!c.style)continue;e[f]=p._data(c,"olddisplay"),b?(!e[f]&&c.style.display==="none"&&(c.style.display=""),c.style.display===""&&bY(c)&&(e[f]=p._data(c,"olddisplay",cb(c.nodeName)))):(d=bH(c,"display"),!e[f]&&d!=="none"&&p._data(c,"olddisplay",d))}for(f=0;f<g;f++){c=a[f];if(!c.style)continue;if(!b||c.style.display==="none"||c.style.display==="")c.style.display=b?e[f]||"":"none"}return a}function b$(a,b,c){var d=bO.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function b_(a,b,c,d){var e=c===(d?"border":"content")?4:b==="width"?1:0,f=0;for(;e<4;e+=2)c==="margin"&&(f+=p.css(a,c+bU[e],!0)),d?(c==="content"&&(f-=parseFloat(bH(a,"padding"+bU[e]))||0),c!=="margin"&&(f-=parseFloat(bH(a,"border"+bU[e]+"Width"))||0)):(f+=parseFloat(bH(a,"padding"+bU[e]))||0,c!=="padding"&&(f+=parseFloat(bH(a,"border"+bU[e]+"Width"))||0));return f}function ca(a,b,c){var d=b==="width"?a.offsetWidth:a.offsetHeight,e=!0,f=p.support.boxSizing&&p.css(a,"boxSizing")==="border-box";if(d<=0){d=bH(a,b);if(d<0||d==null)d=a.style[b];if(bP.test(d))return d;e=f&&(p.support.boxSizingReliable||d===a.style[b]),d=parseFloat(d)||0}return d+b_(a,b,c||(f?"border":"content"),e)+"px"}function cb(a){if(bR[a])return bR[a];var b=p("<"+a+">").appendTo(e.body),c=b.css("display");b.remove();if(c==="none"||c===""){bI=e.body.appendChild(bI||p.extend(e.createElement("iframe"),{frameBorder:0,width:0,height:0}));if(!bJ||!bI.createElement)bJ=(bI.contentWindow||bI.contentDocument).document,bJ.write("<!doctype html><html><body>"),bJ.close();b=bJ.body.appendChild(bJ.createElement(a)),c=bH(b,"display"),e.body.removeChild(bI)}return bR[a]=c,c}function ch(a,b,c,d){var e;if(p.isArray(b))p.each(b,function(b,e){c||cd.test(a)?d(a,e):ch(a+"["+(typeof e=="object"?b:"")+"]",e,c,d)});else if(!c&&p.type(b)==="object")for(e in b)ch(a+"["+e+"]",b[e],c,d);else d(a,b)}function cy(a){return function(b,c){typeof b!="string"&&(c=b,b="*");var d,e,f,g=b.toLowerCase().split(s),h=0,i=g.length;if(p.isFunction(c))for(;h<i;h++)d=g[h],f=/^\+/.test(d),f&&(d=d.substr(1)||"*"),e=a[d]=a[d]||[],e[f?"unshift":"push"](c)}}function cz(a,c,d,e,f,g){f=f||c.dataTypes[0],g=g||{},g[f]=!0;var h,i=a[f],j=0,k=i?i.length:0,l=a===cu;for(;j<k&&(l||!h);j++)h=i[j](c,d,e),typeof h=="string"&&(!l||g[h]?h=b:(c.dataTypes.unshift(h),h=cz(a,c,d,e,h,g)));return(l||!h)&&!g["*"]&&(h=cz(a,c,d,e,"*",g)),h}function cA(a,c){var d,e,f=p.ajaxSettings.flatOptions||{};for(d in c)c[d]!==b&&((f[d]?a:e||(e={}))[d]=c[d]);e&&p.extend(!0,a,e)}function cB(a,c,d){var e,f,g,h,i=a.contents,j=a.dataTypes,k=a.responseFields;for(f in k)f in d&&(c[k[f]]=d[f]);while(j[0]==="*")j.shift(),e===b&&(e=a.mimeType||c.getResponseHeader("content-type"));if(e)for(f in i)if(i[f]&&i[f].test(e)){j.unshift(f);break}if(j[0]in d)g=j[0];else{for(f in d){if(!j[0]||a.converters[f+" "+j[0]]){g=f;break}h||(h=f)}g=g||h}if(g)return g!==j[0]&&j.unshift(g),d[g]}function cC(a,b){var c,d,e,f,g=a.dataTypes.slice(),h=g[0],i={},j=0;a.dataFilter&&(b=a.dataFilter(b,a.dataType));if(g[1])for(c in a.converters)i[c.toLowerCase()]=a.converters[c];for(;e=g[++j];)if(e!=="*"){if(h!=="*"&&h!==e){c=i[h+" "+e]||i["* "+e];if(!c)for(d in i){f=d.split(" ");if(f[1]===e){c=i[h+" "+f[0]]||i["* "+f[0]];if(c){c===!0?c=i[d]:i[d]!==!0&&(e=f[0],g.splice(j--,0,e));break}}}if(c!==!0)if(c&&a["throws"])b=c(b);else try{b=c(b)}catch(k){return{state:"parsererror",error:c?k:"No conversion from "+h+" to "+e}}}h=e}return{state:"success",data:b}}function cK(){try{return new a.XMLHttpRequest}catch(b){}}function cL(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function cT(){return setTimeout(function(){cM=b},0),cM=p.now()}function cU(a,b){p.each(b,function(b,c){var d=(cS[b]||[]).concat(cS["*"]),e=0,f=d.length;for(;e<f;e++)if(d[e].call(a,b,c))return})}function cV(a,b,c){var d,e=0,f=0,g=cR.length,h=p.Deferred().always(function(){delete i.elem}),i=function(){var b=cM||cT(),c=Math.max(0,j.startTime+j.duration-b),d=1-(c/j.duration||0),e=0,f=j.tweens.length;for(;e<f;e++)j.tweens[e].run(d);return h.notifyWith(a,[j,d,c]),d<1&&f?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:p.extend({},b),opts:p.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:cM||cT(),duration:c.duration,tweens:[],createTween:function(b,c,d){var e=p.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(e),e},stop:function(b){var c=0,d=b?j.tweens.length:0;for(;c<d;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;cW(k,j.opts.specialEasing);for(;e<g;e++){d=cR[e].call(j,a,k,j.opts);if(d)return d}return cU(j,k),p.isFunction(j.opts.start)&&j.opts.start.call(a,j),p.fx.timer(p.extend(i,{anim:j,queue:j.opts.queue,elem:a})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}function cW(a,b){var c,d,e,f,g;for(c in a){d=p.camelCase(c),e=b[d],f=a[c],p.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=p.cssHooks[d];if(g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}}function cX(a,b,c){var d,e,f,g,h,i,j,k,l=this,m=a.style,n={},o=[],q=a.nodeType&&bY(a);c.queue||(j=p._queueHooks(a,"fx"),j.unqueued==null&&(j.unqueued=0,k=j.empty.fire,j.empty.fire=function(){j.unqueued||k()}),j.unqueued++,l.always(function(){l.always(function(){j.unqueued--,p.queue(a,"fx").length||j.empty.fire()})})),a.nodeType===1&&("height"in b||"width"in b)&&(c.overflow=[m.overflow,m.overflowX,m.overflowY],p.css(a,"display")==="inline"&&p.css(a,"float")==="none"&&(!p.support.inlineBlockNeedsLayout||cb(a.nodeName)==="inline"?m.display="inline-block":m.zoom=1)),c.overflow&&(m.overflow="hidden",p.support.shrinkWrapBlocks||l.done(function(){m.overflow=c.overflow[0],m.overflowX=c.overflow[1],m.overflowY=c.overflow[2]}));for(d in b){f=b[d];if(cO.exec(f)){delete b[d];if(f===(q?"hide":"show"))continue;o.push(d)}}g=o.length;if(g){h=p._data(a,"fxshow")||p._data(a,"fxshow",{}),q?p(a).show():l.done(function(){p(a).hide()}),l.done(function(){var b;p.removeData(a,"fxshow",!0);for(b in n)p.style(a,b,n[b])});for(d=0;d<g;d++)e=o[d],i=l.createTween(e,q?h[e]:0),n[e]=h[e]||p.style(a,e),e in h||(h[e]=i.start,q&&(i.end=i.start,i.start=e==="width"||e==="height"?1:0))}}function cY(a,b,c,d,e){return new cY.prototype.init(a,b,c,d,e)}function cZ(a,b){var c,d={height:a},e=0;for(;e<4;e+=2-b)c=bU[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function c_(a){return p.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}var c,d,e=a.document,f=a.location,g=a.navigator,h=a.jQuery,i=a.$,j=Array.prototype.push,k=Array.prototype.slice,l=Array.prototype.indexOf,m=Object.prototype.toString,n=Object.prototype.hasOwnProperty,o=String.prototype.trim,p=function(a,b){return new p.fn.init(a,b,c)},q=/[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,r=/\S/,s=/\s+/,t=r.test(" ")?/^[\s\xA0]+|[\s\xA0]+$/g:/^\s+|\s+$/g,u=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^[\],:{}\s]*$/,x=/(?:^|:|,)(?:\s*\[)+/g,y=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,z=/"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,A=/^-ms-/,B=/-([\da-z])/gi,C=function(a,b){return(b+"").toUpperCase()},D=function(){e.addEventListener?(e.removeEventListener("DOMContentLoaded",D,!1),p.ready()):e.readyState==="complete"&&(e.detachEvent("onreadystatechange",D),p.ready())},E={};p.fn=p.prototype={constructor:p,init:function(a,c,d){var f,g,h,i;if(!a)return this;if(a.nodeType)return this.context=this[0]=a,this.length=1,this;if(typeof a=="string"){a.charAt(0)==="<"&&a.charAt(a.length-1)===">"&&a.length>=3?f=[null,a,null]:f=u.exec(a);if(f&&(f[1]||!c)){if(f[1])return c=c instanceof p?c[0]:c,i=c&&c.nodeType?c.ownerDocument||c:e,a=p.parseHTML(f[1],i,!0),v.test(f[1])&&p.isPlainObject(c)&&this.attr.call(a,c,!0),p.merge(this,a);g=e.getElementById(f[2]);if(g&&g.parentNode){if(g.id!==f[2])return d.find(a);this.length=1,this[0]=g}return this.context=e,this.selector=a,this}return!c||c.jquery?(c||d).find(a):this.constructor(c).find(a)}return p.isFunction(a)?d.ready(a):(a.selector!==b&&(this.selector=a.selector,this.context=a.context),p.makeArray(a,this))},selector:"",jquery:"1.8.0",length:0,size:function(){return this.length},toArray:function(){return k.call(this)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=p.merge(this.constructor(),a);return d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")"),d},each:function(a,b){return p.each(this,a,b)},ready:function(a){return p.ready.promise().done(a),this},eq:function(a){return a=+a,a===-1?this.slice(a):this.slice(a,a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(k.apply(this,arguments),"slice",k.call(arguments).join(","))},map:function(a){return this.pushStack(p.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:j,sort:[].sort,splice:[].splice},p.fn.init.prototype=p.fn,p.extend=p.fn.extend=function(){var a,c,d,e,f,g,h=arguments[0]||{},i=1,j=arguments.length,k=!1;typeof h=="boolean"&&(k=h,h=arguments[1]||{},i=2),typeof h!="object"&&!p.isFunction(h)&&(h={}),j===i&&(h=this,--i);for(;i<j;i++)if((a=arguments[i])!=null)for(c in a){d=h[c],e=a[c];if(h===e)continue;k&&e&&(p.isPlainObject(e)||(f=p.isArray(e)))?(f?(f=!1,g=d&&p.isArray(d)?d:[]):g=d&&p.isPlainObject(d)?d:{},h[c]=p.extend(k,g,e)):e!==b&&(h[c]=e)}return h},p.extend({noConflict:function(b){return a.$===p&&(a.$=i),b&&a.jQuery===p&&(a.jQuery=h),p},isReady:!1,readyWait:1,holdReady:function(a){a?p.readyWait++:p.ready(!0)},ready:function(a){if(a===!0?--p.readyWait:p.isReady)return;if(!e.body)return setTimeout(p.ready,1);p.isReady=!0;if(a!==!0&&--p.readyWait>0)return;d.resolveWith(e,[p]),p.fn.trigger&&p(e).trigger("ready").off("ready")},isFunction:function(a){return p.type(a)==="function"},isArray:Array.isArray||function(a){return p.type(a)==="array"},isWindow:function(a){return a!=null&&a==a.window},isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},type:function(a){return a==null?String(a):E[m.call(a)]||"object"},isPlainObject:function(a){if(!a||p.type(a)!=="object"||a.nodeType||p.isWindow(a))return!1;try{if(a.constructor&&!n.call(a,"constructor")&&!n.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||n.call(a,d)},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},error:function(a){throw new Error(a)},parseHTML:function(a,b,c){var d;return!a||typeof a!="string"?null:(typeof b=="boolean"&&(c=b,b=0),b=b||e,(d=v.exec(a))?[b.createElement(d[1])]:(d=p.buildFragment([a],b,c?null:[]),p.merge([],(d.cacheable?p.clone(d.fragment):d.fragment).childNodes)))},parseJSON:function(b){if(!b||typeof b!="string")return null;b=p.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(w.test(b.replace(y,"@").replace(z,"]").replace(x,"")))return(new Function("return "+b))();p.error("Invalid JSON: "+b)},parseXML:function(c){var d,e;if(!c||typeof c!="string")return null;try{a.DOMParser?(e=new DOMParser,d=e.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(f){d=b}return(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&p.error("Invalid XML: "+c),d},noop:function(){},globalEval:function(b){b&&r.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(A,"ms-").replace(B,C)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,d){var e,f=0,g=a.length,h=g===b||p.isFunction(a);if(d){if(h){for(e in a)if(c.apply(a[e],d)===!1)break}else for(;f<g;)if(c.apply(a[f++],d)===!1)break}else if(h){for(e in a)if(c.call(a[e],e,a[e])===!1)break}else for(;f<g;)if(c.call(a[f],f,a[f++])===!1)break;return a},trim:o?function(a){return a==null?"":o.call(a)}:function(a){return a==null?"":a.toString().replace(t,"")},makeArray:function(a,b){var c,d=b||[];return a!=null&&(c=p.type(a),a.length==null||c==="string"||c==="function"||c==="regexp"||p.isWindow(a)?j.call(d,a):p.merge(d,a)),d},inArray:function(a,b,c){var d;if(b){if(l)return l.call(b,a,c);d=b.length,c=c?c<0?Math.max(0,d+c):c:0;for(;c<d;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,c){var d=c.length,e=a.length,f=0;if(typeof d=="number")for(;f<d;f++)a[e++]=c[f];else while(c[f]!==b)a[e++]=c[f++];return a.length=e,a},grep:function(a,b,c){var d,e=[],f=0,g=a.length;c=!!c;for(;f<g;f++)d=!!b(a[f],f),c!==d&&e.push(a[f]);return e},map:function(a,c,d){var e,f,g=[],h=0,i=a.length,j=a instanceof p||i!==b&&typeof i=="number"&&(i>0&&a[0]&&a[i-1]||i===0||p.isArray(a));if(j)for(;h<i;h++)e=c(a[h],h,d),e!=null&&(g[g.length]=e);else for(f in a)e=c(a[f],f,d),e!=null&&(g[g.length]=e);return g.concat.apply([],g)},guid:1,proxy:function(a,c){var d,e,f;return typeof c=="string"&&(d=a[c],c=a,a=d),p.isFunction(a)?(e=k.call(arguments,2),f=function(){return a.apply(c,e.concat(k.call(arguments)))},f.guid=a.guid=a.guid||f.guid||p.guid++,f):b},access:function(a,c,d,e,f,g,h){var i,j=d==null,k=0,l=a.length;if(d&&typeof d=="object"){for(k in d)p.access(a,c,k,d[k],1,g,e);f=1}else if(e!==b){i=h===b&&p.isFunction(e),j&&(i?(i=c,c=function(a,b,c){return i.call(p(a),c)}):(c.call(a,e),c=null));if(c)for(;k<l;k++)c(a[k],d,i?e.call(a[k],k,c(a[k],d)):e,h);f=1}return f?a:j?c.call(a):l?c(a[0],d):g},now:function(){return(new Date).getTime()}}),p.ready.promise=function(b){if(!d){d=p.Deferred();if(e.readyState==="complete"||e.readyState!=="loading"&&e.addEventListener)setTimeout(p.ready,1);else if(e.addEventListener)e.addEventListener("DOMContentLoaded",D,!1),a.addEventListener("load",p.ready,!1);else{e.attachEvent("onreadystatechange",D),a.attachEvent("onload",p.ready);var c=!1;try{c=a.frameElement==null&&e.documentElement}catch(f){}c&&c.doScroll&&function g(){if(!p.isReady){try{c.doScroll("left")}catch(a){return setTimeout(g,50)}p.ready()}}()}}return d.promise(b)},p.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(a,b){E["[object "+b+"]"]=b.toLowerCase()}),c=p(e);var F={};p.Callbacks=function(a){a=typeof a=="string"?F[a]||G(a):p.extend({},a);var c,d,e,f,g,h,i=[],j=!a.once&&[],k=function(b){c=a.memory&&b,d=!0,h=f||0,f=0,g=i.length,e=!0;for(;i&&h<g;h++)if(i[h].apply(b[0],b[1])===!1&&a.stopOnFalse){c=!1;break}e=!1,i&&(j?j.length&&k(j.shift()):c?i=[]:l.disable())},l={add:function(){if(i){var b=i.length;(function d(b){p.each(b,function(b,c){p.isFunction(c)&&(!a.unique||!l.has(c))?i.push(c):c&&c.length&&d(c)})})(arguments),e?g=i.length:c&&(f=b,k(c))}return this},remove:function(){return i&&p.each(arguments,function(a,b){var c;while((c=p.inArray(b,i,c))>-1)i.splice(c,1),e&&(c<=g&&g--,c<=h&&h--)}),this},has:function(a){return p.inArray(a,i)>-1},empty:function(){return i=[],this},disable:function(){return i=j=c=b,this},disabled:function(){return!i},lock:function(){return j=b,c||l.disable(),this},locked:function(){return!j},fireWith:function(a,b){return b=b||[],b=[a,b.slice?b.slice():b],i&&(!d||j)&&(e?j.push(b):k(b)),this},fire:function(){return l.fireWith(this,arguments),this},fired:function(){return!!d}};return l},p.extend({Deferred:function(a){var b=[["resolve","done",p.Callbacks("once memory"),"resolved"],["reject","fail",p.Callbacks("once memory"),"rejected"],["notify","progress",p.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return p.Deferred(function(c){p.each(b,function(b,d){var f=d[0],g=a[b];e[d[1]](p.isFunction(g)?function(){var a=g.apply(this,arguments);a&&p.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f+"With"](this===e?c:this,[a])}:c[f])}),a=null}).promise()},promise:function(a){return typeof a=="object"?p.extend(a,d):d}},e={};return d.pipe=d.then,p.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[a^1][2].disable,b[2][2].lock),e[f[0]]=g.fire,e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=k.call(arguments),d=c.length,e=d!==1||a&&p.isFunction(a.promise)?d:0,f=e===1?a:p.Deferred(),g=function(a,b,c){return function(d){b[a]=this,c[a]=arguments.length>1?k.call(arguments):d,c===h?f.notifyWith(b,c):--e||f.resolveWith(b,c)}},h,i,j;if(d>1){h=new Array(d),i=new Array(d),j=new Array(d);for(;b<d;b++)c[b]&&p.isFunction(c[b].promise)?c[b].promise().done(g(b,j,c)).fail(f.reject).progress(g(b,i,h)):--e}return e||f.resolveWith(j,c),f.promise()}}),p.support=function(){var b,c,d,f,g,h,i,j,k,l,m,n=e.createElement("div");n.setAttribute("className","t"),n.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",c=n.getElementsByTagName("*"),d=n.getElementsByTagName("a")[0],d.style.cssText="top:1px;float:left;opacity:.5";if(!c||!c.length||!d)return{};f=e.createElement("select"),g=f.appendChild(e.createElement("option")),h=n.getElementsByTagName("input")[0],b={leadingWhitespace:n.firstChild.nodeType===3,tbody:!n.getElementsByTagName("tbody").length,htmlSerialize:!!n.getElementsByTagName("link").length,style:/top/.test(d.getAttribute("style")),hrefNormalized:d.getAttribute("href")==="/a",opacity:/^0.5/.test(d.style.opacity),cssFloat:!!d.style.cssFloat,checkOn:h.value==="on",optSelected:g.selected,getSetAttribute:n.className!=="t",enctype:!!e.createElement("form").enctype,html5Clone:e.createElement("nav").cloneNode(!0).outerHTML!=="<:nav></:nav>",boxModel:e.compatMode==="CSS1Compat",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},h.checked=!0,b.noCloneChecked=h.cloneNode(!0).checked,f.disabled=!0,b.optDisabled=!g.disabled;try{delete n.test}catch(o){b.deleteExpando=!1}!n.addEventListener&&n.attachEvent&&n.fireEvent&&(n.attachEvent("onclick",m=function(){b.noCloneEvent=!1}),n.cloneNode(!0).fireEvent("onclick"),n.detachEvent("onclick",m)),h=e.createElement("input"),h.value="t",h.setAttribute("type","radio"),b.radioValue=h.value==="t",h.setAttribute("checked","checked"),h.setAttribute("name","t"),n.appendChild(h),i=e.createDocumentFragment(),i.appendChild(n.lastChild),b.checkClone=i.cloneNode(!0).cloneNode(!0).lastChild.checked,b.appendChecked=h.checked,i.removeChild(h),i.appendChild(n);if(n.attachEvent)for(k in{submit:!0,change:!0,focusin:!0})j="on"+k,l=j in n,l||(n.setAttribute(j,"return;"),l=typeof n[j]=="function"),b[k+"Bubbles"]=l;return p(function(){var c,d,f,g,h="padding:0;margin:0;border:0;display:block;overflow:hidden;",i=e.getElementsByTagName("body")[0];if(!i)return;c=e.createElement("div"),c.style.cssText="visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px",i.insertBefore(c,i.firstChild),d=e.createElement("div"),c.appendChild(d),d.innerHTML="<table><tr><td></td><td>t</td></tr></table>",f=d.getElementsByTagName("td"),f[0].style.cssText="padding:0;margin:0;border:0;display:none",l=f[0].offsetHeight===0,f[0].style.display="",f[1].style.display="none",b.reliableHiddenOffsets=l&&f[0].offsetHeight===0,d.innerHTML="",d.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",b.boxSizing=d.offsetWidth===4,b.doesNotIncludeMarginInBodyOffset=i.offsetTop!==1,a.getComputedStyle&&(b.pixelPosition=(a.getComputedStyle(d,null)||{}).top!=="1%",b.boxSizingReliable=(a.getComputedStyle(d,null)||{width:"4px"}).width==="4px",g=e.createElement("div"),g.style.cssText=d.style.cssText=h,g.style.marginRight=g.style.width="0",d.style.width="1px",d.appendChild(g),b.reliableMarginRight=!parseFloat((a.getComputedStyle(g,null)||{}).marginRight)),typeof d.style.zoom!="undefined"&&(d.innerHTML="",d.style.cssText=h+"width:1px;padding:1px;display:inline;zoom:1",b.inlineBlockNeedsLayout=d.offsetWidth===3,d.style.display="block",d.style.overflow="visible",d.innerHTML="<div></div>",d.firstChild.style.width="5px",b.shrinkWrapBlocks=d.offsetWidth!==3,c.style.zoom=1),i.removeChild(c),c=d=f=g=null}),i.removeChild(n),c=d=f=g=h=i=n=null,b}();var H=/^(?:\{.*\}|\[.*\])$/,I=/([A-Z])/g;p.extend({cache:{},deletedIds:[],uuid:0,expando:"jQuery"+(p.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){return a=a.nodeType?p.cache[a[p.expando]]:a[p.expando],!!a&&!K(a)},data:function(a,c,d,e){if(!p.acceptData(a))return;var f,g,h=p.expando,i=typeof c=="string",j=a.nodeType,k=j?p.cache:a,l=j?a[h]:a[h]&&h;if((!l||!k[l]||!e&&!k[l].data)&&i&&d===b)return;l||(j?a[h]=l=p.deletedIds.pop()||++p.uuid:l=h),k[l]||(k[l]={},j||(k[l].toJSON=p.noop));if(typeof c=="object"||typeof c=="function")e?k[l]=p.extend(k[l],c):k[l].data=p.extend(k[l].data,c);return f=k[l],e||(f.data||(f.data={}),f=f.data),d!==b&&(f[p.camelCase(c)]=d),i?(g=f[c],g==null&&(g=f[p.camelCase(c)])):g=f,g},removeData:function(a,b,c){if(!p.acceptData(a))return;var d,e,f,g=a.nodeType,h=g?p.cache:a,i=g?a[p.expando]:p.expando;if(!h[i])return;if(b){d=c?h[i]:h[i].data;if(d){p.isArray(b)||(b in d?b=[b]:(b=p.camelCase(b),b in d?b=[b]:b=b.split(" ")));for(e=0,f=b.length;e<f;e++)delete d[b[e]];if(!(c?K:p.isEmptyObject)(d))return}}if(!c){delete h[i].data;if(!K(h[i]))return}g?p.cleanData([a],!0):p.support.deleteExpando||h!=h.window?delete h[i]:h[i]=null},_data:function(a,b,c){return p.data(a,b,c,!0)},acceptData:function(a){var b=a.nodeName&&p.noData[a.nodeName.toLowerCase()];return!b||b!==!0&&a.getAttribute("classid")===b}}),p.fn.extend({data:function(a,c){var d,e,f,g,h,i=this[0],j=0,k=null;if(a===b){if(this.length){k=p.data(i);if(i.nodeType===1&&!p._data(i,"parsedAttrs")){f=i.attributes;for(h=f.length;j<h;j++)g=f[j].name,g.indexOf("data-")===0&&(g=p.camelCase(g.substring(5)),J(i,g,k[g]));p._data(i,"parsedAttrs",!0)}}return k}return typeof a=="object"?this.each(function(){p.data(this,a)}):(d=a.split(".",2),d[1]=d[1]?"."+d[1]:"",e=d[1]+"!",p.access(this,function(c){if(c===b)return k=this.triggerHandler("getData"+e,[d[0]]),k===b&&i&&(k=p.data(i,a),k=J(i,a,k)),k===b&&d[1]?this.data(d[0]):k;d[1]=c,this.each(function(){var b=p(this);b.triggerHandler("setData"+e,d),p.data(this,a,c),b.triggerHandler("changeData"+e,d)})},null,c,arguments.length>1,null,!1))},removeData:function(a){return this.each(function(){p.removeData(this,a)})}}),p.extend({queue:function(a,b,c){var d;if(a)return b=(b||"fx")+"queue",d=p._data(a,b),c&&(!d||p.isArray(c)?d=p._data(a,b,p.makeArray(c)):d.push(c)),d||[]},dequeue:function(a,b){b=b||"fx";var c=p.queue(a,b),d=c.shift(),e=p._queueHooks(a,b),f=function(){p.dequeue(a,b)};d==="inprogress"&&(d=c.shift()),d&&(b==="fx"&&c.unshift("inprogress"),delete e.stop,d.call(a,f,e)),!c.length&&e&&e.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return p._data(a,c)||p._data(a,c,{empty:p.Callbacks("once memory").add(function(){p.removeData(a,b+"queue",!0),p.removeData(a,c,!0)})})}}),p.fn.extend({queue:function(a,c){var d=2;return typeof a!="string"&&(c=a,a="fx",d--),arguments.length<d?p.queue(this[0],a):c===b?this:this.each(function(){var b=p.queue(this,a,c);p._queueHooks(this,a),a==="fx"&&b[0]!=="inprogress"&&p.dequeue(this,a)})},dequeue:function(a){return this.each(function(){p.dequeue(this,a)})},delay:function(a,b){return a=p.fx?p.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,c){var d,e=1,f=p.Deferred(),g=this,h=this.length,i=function(){--e||f.resolveWith(g,[g])};typeof a!="string"&&(c=a,a=b),a=a||"fx";while(h--)(d=p._data(g[h],a+"queueHooks"))&&d.empty&&(e++,d.empty.add(i));return i(),f.promise(c)}});var L,M,N,O=/[\t\r\n]/g,P=/\r/g,Q=/^(?:button|input)$/i,R=/^(?:button|input|object|select|textarea)$/i,S=/^a(?:rea|)$/i,T=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,U=p.support.getSetAttribute;p.fn.extend({attr:function(a,b){return p.access(this,p.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){p.removeAttr(this,a)})},prop:function(a,b){return p.access(this,p.prop,a,b,arguments.length>1)},removeProp:function(a){return a=p.propFix[a]||a,this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){var b,c,d,e,f,g,h;if(p.isFunction(a))return this.each(function(b){p(this).addClass(a.call(this,b,this.className))});if(a&&typeof a=="string"){b=a.split(s);for(c=0,d=this.length;c<d;c++){e=this[c];if(e.nodeType===1)if(!e.className&&b.length===1)e.className=a;else{f=" "+e.className+" ";for(g=0,h=b.length;g<h;g++)~f.indexOf(" "+b[g]+" ")||(f+=b[g]+" ");e.className=p.trim(f)}}}return this},removeClass:function(a){var c,d,e,f,g,h,i;if(p.isFunction(a))return this.each(function(b){p(this).removeClass(a.call(this,b,this.className))});if(a&&typeof a=="string"||a===b){c=(a||"").split(s);for(h=0,i=this.length;h<i;h++){e=this[h];if(e.nodeType===1&&e.className){d=(" "+e.className+" ").replace(O," ");for(f=0,g=c.length;f<g;f++)while(d.indexOf(" "+c[f]+" ")>-1)d=d.replace(" "+c[f]+" "," ");e.className=a?p.trim(d):""}}}return this},toggleClass:function(a,b){var c=typeof a,d=typeof b=="boolean";return p.isFunction(a)?this.each(function(c){p(this).toggleClass(a.call(this,c,this.className,b),b)}):this.each(function(){if(c==="string"){var e,f=0,g=p(this),h=b,i=a.split(s);while(e=i[f++])h=d?h:!g.hasClass(e),g[h?"addClass":"removeClass"](e)}else if(c==="undefined"||c==="boolean")this.className&&p._data(this,"__className__",this.className),this.className=this.className||a===!1?"":p._data(this,"__className__")||""})},hasClass:function(a){var b=" "+a+" ",c=0,d=this.length;for(;c<d;c++)if(this[c].nodeType===1&&(" "+this[c].className+" ").replace(O," ").indexOf(b)>-1)return!0;return!1},val:function(a){var c,d,e,f=this[0];if(!arguments.length){if(f)return c=p.valHooks[f.type]||p.valHooks[f.nodeName.toLowerCase()],c&&"get"in c&&(d=c.get(f,"value"))!==b?d:(d=f.value,typeof d=="string"?d.replace(P,""):d==null?"":d);return}return e=p.isFunction(a),this.each(function(d){var f,g=p(this);if(this.nodeType!==1)return;e?f=a.call(this,d,g.val()):f=a,f==null?f="":typeof f=="number"?f+="":p.isArray(f)&&(f=p.map(f,function(a){return a==null?"":a+""})),c=p.valHooks[this.type]||p.valHooks[this.nodeName.toLowerCase()];if(!c||!("set"in c)||c.set(this,f,"value")===b)this.value=f})}}),p.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c,d,e,f=a.selectedIndex,g=[],h=a.options,i=a.type==="select-one";if(f<0)return null;c=i?f:0,d=i?f+1:h.length;for(;c<d;c++){e=h[c];if(e.selected&&(p.support.optDisabled?!e.disabled:e.getAttribute("disabled")===null)&&(!e.parentNode.disabled||!p.nodeName(e.parentNode,"optgroup"))){b=p(e).val();if(i)return b;g.push(b)}}return i&&!g.length&&h.length?p(h[f]).val():g},set:function(a,b){var c=p.makeArray(b);return p(a).find("option").each(function(){this.selected=p.inArray(p(this).val(),c)>=0}),c.length||(a.selectedIndex=-1),c}}},attrFn:{},attr:function(a,c,d,e){var f,g,h,i=a.nodeType;if(!a||i===3||i===8||i===2)return;if(e&&p.isFunction(p.fn[c]))return p(a)[c](d);if(typeof a.getAttribute=="undefined")return p.prop(a,c,d);h=i!==1||!p.isXMLDoc(a),h&&(c=c.toLowerCase(),g=p.attrHooks[c]||(T.test(c)?M:L));if(d!==b){if(d===null){p.removeAttr(a,c);return}return g&&"set"in g&&h&&(f=g.set(a,d,c))!==b?f:(a.setAttribute(c,""+d),d)}return g&&"get"in g&&h&&(f=g.get(a,c))!==null?f:(f=a.getAttribute(c),f===null?b:f)},removeAttr:function(a,b){var c,d,e,f,g=0;if(b&&a.nodeType===1){d=b.split(s);for(;g<d.length;g++)e=d[g],e&&(c=p.propFix[e]||e,f=T.test(e),f||p.attr(a,e,""),a.removeAttribute(U?e:c),f&&c in a&&(a[c]=!1))}},attrHooks:{type:{set:function(a,b){if(Q.test(a.nodeName)&&a.parentNode)p.error("type property can't be changed");else if(!p.support.radioValue&&b==="radio"&&p.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}},value:{get:function(a,b){return L&&p.nodeName(a,"button")?L.get(a,b):b in a?a.value:null},set:function(a,b,c){if(L&&p.nodeName(a,"button"))return L.set(a,b,c);a.value=b}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(a,c,d){var e,f,g,h=a.nodeType;if(!a||h===3||h===8||h===2)return;return g=h!==1||!p.isXMLDoc(a),g&&(c=p.propFix[c]||c,f=p.propHooks[c]),d!==b?f&&"set"in f&&(e=f.set(a,d,c))!==b?e:a[c]=d:f&&"get"in f&&(e=f.get(a,c))!==null?e:a[c]},propHooks:{tabIndex:{get:function(a){var c=a.getAttributeNode("tabindex");return c&&c.specified?parseInt(c.value,10):R.test(a.nodeName)||S.test(a.nodeName)&&a.href?0:b}}}}),M={get:function(a,c){var d,e=p.prop(a,c);return e===!0||typeof e!="boolean"&&(d=a.getAttributeNode(c))&&d.nodeValue!==!1?c.toLowerCase():b},set:function(a,b,c){var d;return b===!1?p.removeAttr(a,c):(d=p.propFix[c]||c,d in a&&(a[d]=!0),a.setAttribute(c,c.toLowerCase())),c}},U||(N={name:!0,id:!0,coords:!0},L=p.valHooks.button={get:function(a,c){var d;return d=a.getAttributeNode(c),d&&(N[c]?d.value!=="":d.specified)?d.value:b},set:function(a,b,c){var d=a.getAttributeNode(c);return d||(d=e.createAttribute(c),a.setAttributeNode(d)),d.value=b+""}},p.each(["width","height"],function(a,b){p.attrHooks[b]=p.extend(p.attrHooks[b],{set:function(a,c){if(c==="")return a.setAttribute(b,"auto"),c}})}),p.attrHooks.contenteditable={get:L.get,set:function(a,b,c){b===""&&(b="false"),L.set(a,b,c)}}),p.support.hrefNormalized||p.each(["href","src","width","height"],function(a,c){p.attrHooks[c]=p.extend(p.attrHooks[c],{get:function(a){var d=a.getAttribute(c,2);return d===null?b:d}})}),p.support.style||(p.attrHooks.style={get:function(a){return a.style.cssText.toLowerCase()||b},set:function(a,b){return a.style.cssText=""+b}}),p.support.optSelected||(p.propHooks.selected=p.extend(p.propHooks.selected,{get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}})),p.support.enctype||(p.propFix.enctype="encoding"),p.support.checkOn||p.each(["radio","checkbox"],function(){p.valHooks[this]={get:function(a){return a.getAttribute("value")===null?"on":a.value}}}),p.each(["radio","checkbox"],function(){p.valHooks[this]=p.extend(p.valHooks[this],{set:function(a,b){if(p.isArray(b))return a.checked=p.inArray(p(a).val(),b)>=0}})});var V=/^(?:textarea|input|select)$/i,W=/^([^\.]*|)(?:\.(.+)|)$/,X=/(?:^|\s)hover(\.\S+|)\b/,Y=/^key/,Z=/^(?:mouse|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=function(a){return p.event.special.hover?a:a.replace(X,"mouseenter$1 mouseleave$1")};p.event={add:function(a,c,d,e,f){var g,h,i,j,k,l,m,n,o,q,r;if(a.nodeType===3||a.nodeType===8||!c||!d||!(g=p._data(a)))return;d.handler&&(o=d,d=o.handler,f=o.selector),d.guid||(d.guid=p.guid++),i=g.events,i||(g.events=i={}),h=g.handle,h||(g.handle=h=function(a){return typeof p!="undefined"&&(!a||p.event.triggered!==a.type)?p.event.dispatch.apply(h.elem,arguments):b},h.elem=a),c=p.trim(_(c)).split(" ");for(j=0;j<c.length;j++){k=W.exec(c[j])||[],l=k[1],m=(k[2]||"").split(".").sort(),r=p.event.special[l]||{},l=(f?r.delegateType:r.bindType)||l,r=p.event.special[l]||{},n=p.extend({type:l,origType:k[1],data:e,handler:d,guid:d.guid,selector:f,namespace:m.join(".")},o),q=i[l];if(!q){q=i[l]=[],q.delegateCount=0;if(!r.setup||r.setup.call(a,e,m,h)===!1)a.addEventListener?a.addEventListener(l,h,!1):a.attachEvent&&a.attachEvent("on"+l,h)}r.add&&(r.add.call(a,n),n.handler.guid||(n.handler.guid=d.guid)),f?q.splice(q.delegateCount++,0,n):q.push(n),p.event.global[l]=!0}a=null},global:{},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,o,q,r=p.hasData(a)&&p._data(a);if(!r||!(m=r.events))return;b=p.trim(_(b||"")).split(" ");for(f=0;f<b.length;f++){g=W.exec(b[f])||[],h=i=g[1],j=g[2];if(!h){for(h in m)p.event.remove(a,h+b[f],c,d,!0);continue}n=p.event.special[h]||{},h=(d?n.delegateType:n.bindType)||h,o=m[h]||[],k=o.length,j=j?new RegExp("(^|\\.)"+j.split(".").sort().join("\\.(?:.*\\.|)")+"(\\.|$)"):null;for(l=0;l<o.length;l++)q=o[l],(e||i===q.origType)&&(!c||c.guid===q.guid)&&(!j||j.test(q.namespace))&&(!d||d===q.selector||d==="**"&&q.selector)&&(o.splice(l--,1),q.selector&&o.delegateCount--,n.remove&&n.remove.call(a,q));o.length===0&&k!==o.length&&((!n.teardown||n.teardown.call(a,j,r.handle)===!1)&&p.removeEvent(a,h,r.handle),delete m[h])}p.isEmptyObject(m)&&(delete r.handle,p.removeData(a,"events",!0))},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(c,d,f,g){if(!f||f.nodeType!==3&&f.nodeType!==8){var h,i,j,k,l,m,n,o,q,r,s=c.type||c,t=[];if($.test(s+p.event.triggered))return;s.indexOf("!")>=0&&(s=s.slice(0,-1),i=!0),s.indexOf(".")>=0&&(t=s.split("."),s=t.shift(),t.sort());if((!f||p.event.customEvent[s])&&!p.event.global[s])return;c=typeof c=="object"?c[p.expando]?c:new p.Event(s,c):new p.Event(s),c.type=s,c.isTrigger=!0,c.exclusive=i,c.namespace=t.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+t.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,m=s.indexOf(":")<0?"on"+s:"";if(!f){h=p.cache;for(j in h)h[j].events&&h[j].events[s]&&p.event.trigger(c,d,h[j].handle.elem,!0);return}c.result=b,c.target||(c.target=f),d=d!=null?p.makeArray(d):[],d.unshift(c),n=p.event.special[s]||{};if(n.trigger&&n.trigger.apply(f,d)===!1)return;q=[[f,n.bindType||s]];if(!g&&!n.noBubble&&!p.isWindow(f)){r=n.delegateType||s,k=$.test(r+s)?f:f.parentNode;for(l=f;k;k=k.parentNode)q.push([k,r]),l=k;l===(f.ownerDocument||e)&&q.push([l.defaultView||l.parentWindow||a,r])}for(j=0;j<q.length&&!c.isPropagationStopped();j++)k=q[j][0],c.type=q[j][1],o=(p._data(k,"events")||{})[c.type]&&p._data(k,"handle"),o&&o.apply(k,d),o=m&&k[m],o&&p.acceptData(k)&&o.apply(k,d)===!1&&c.preventDefault();return c.type=s,!g&&!c.isDefaultPrevented()&&(!n._default||n._default.apply(f.ownerDocument,d)===!1)&&(s!=="click"||!p.nodeName(f,"a"))&&p.acceptData(f)&&m&&f[s]&&(s!=="focus"&&s!=="blur"||c.target.offsetWidth!==0)&&!p.isWindow(f)&&(l=f[m],l&&(f[m]=null),p.event.triggered=s,f[s](),p.event.triggered=b,l&&(f[m]=l)),c.result}return},dispatch:function(c){c=p.event.fix(c||a.event);var d,e,f,g,h,i,j,k,l,m,n,o=(p._data(this,"events")||{})[c.type]||[],q=o.delegateCount,r=[].slice.call(arguments),s=!c.exclusive&&!c.namespace,t=p.event.special[c.type]||{},u=[];r[0]=c,c.delegateTarget=this;if(t.preDispatch&&t.preDispatch.call(this,c)===!1)return;if(q&&(!c.button||c.type!=="click")){g=p(this),g.context=this;for(f=c.target;f!=this;f=f.parentNode||this)if(f.disabled!==!0||c.type!=="click"){i={},k=[],g[0]=f;for(d=0;d<q;d++)l=o[d],m=l.selector,i[m]===b&&(i[m]=g.is(m)),i[m]&&k.push(l);k.length&&u.push({elem:f,matches:k})}}o.length>q&&u.push({elem:this,matches:o.slice(q)});for(d=0;d<u.length&&!c.isPropagationStopped();d++){j=u[d],c.currentTarget=j.elem;for(e=0;e<j.matches.length&&!c.isImmediatePropagationStopped();e++){l=j.matches[e];if(s||!c.namespace&&!l.namespace||c.namespace_re&&c.namespace_re.test(l.namespace))c.data=l.data,c.handleObj=l,h=((p.event.special[l.origType]||{}).handle||l.handler).apply(j.elem,r),h!==b&&(c.result=h,h===!1&&(c.preventDefault(),c.stopPropagation()))}}return t.postDispatch&&t.postDispatch.call(this,c),c.result},props:"attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return a.which==null&&(a.which=b.charCode!=null?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,c){var d,f,g,h=c.button,i=c.fromElement;return a.pageX==null&&c.clientX!=null&&(d=a.target.ownerDocument||e,f=d.documentElement,g=d.body,a.pageX=c.clientX+(f&&f.scrollLeft||g&&g.scrollLeft||0)-(f&&f.clientLeft||g&&g.clientLeft||0),a.pageY=c.clientY+(f&&f.scrollTop||g&&g.scrollTop||0)-(f&&f.clientTop||g&&g.clientTop||0)),!a.relatedTarget&&i&&(a.relatedTarget=i===a.target?c.toElement:i),!a.which&&h!==b&&(a.which=h&1?1:h&2?3:h&4?2:0),a}},fix:function(a){if(a[p.expando])return a;var b,c,d=a,f=p.event.fixHooks[a.type]||{},g=f.props?this.props.concat(f.props):this.props;a=p.Event(d);for(b=g.length;b;)c=g[--b],a[c]=d[c];return a.target||(a.target=d.srcElement||e),a.target.nodeType===3&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,f.filter?f.filter(a,d):a},special:{ready:{setup:p.bindReady},load:{noBubble:!0},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(a,b,c){p.isWindow(this)&&(this.onbeforeunload=c)},teardown:function(a,b){this.onbeforeunload===b&&(this.onbeforeunload=null)}}},simulate:function(a,b,c,d){var e=p.extend(new p.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?p.event.trigger(e,null,b):p.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},p.event.handle=p.event.dispatch,p.removeEvent=e.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]=="undefined"&&(a[d]=null),a.detachEvent(d,c))},p.Event=function(a,b){if(this instanceof p.Event)a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault()?bb:ba):this.type=a,b&&p.extend(this,b),this.timeStamp=a&&a.timeStamp||p.now(),this[p.expando]=!0;else return new p.Event(a,b)},p.Event.prototype={preventDefault:function(){this.isDefaultPrevented=bb;var a=this.originalEvent;if(!a)return;a.preventDefault?a.preventDefault():a.returnValue=!1},stopPropagation:function(){this.isPropagationStopped=bb;var a=this.originalEvent;if(!a)return;a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=bb,this.stopPropagation()},isDefaultPrevented:ba,isPropagationStopped:ba,isImmediatePropagationStopped:ba},p.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){p.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj,g=f.selector;if(!e||e!==d&&!p.contains(d,e))a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b;return c}}}),p.support.submitBubbles||(p.event.special.submit={setup:function(){if(p.nodeName(this,"form"))return!1;p.event.add(this,"click._submit keypress._submit",function(a){var c=a.target,d=p.nodeName(c,"input")||p.nodeName(c,"button")?c.form:b;d&&!p._data(d,"_submit_attached")&&(p.event.add(d,"submit._submit",function(a){a._submit_bubble=!0}),p._data(d,"_submit_attached",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&p.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){if(p.nodeName(this,"form"))return!1;p.event.remove(this,"._submit")}}),p.support.changeBubbles||(p.event.special.change={setup:function(){if(V.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio")p.event.add(this,"propertychange._change",function(a){a.originalEvent.propertyName==="checked"&&(this._just_changed=!0)}),p.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),p.event.simulate("change",this,a,!0)});return!1}p.event.add(this,"beforeactivate._change",function(a){var b=a.target;V.test(b.nodeName)&&!p._data(b,"_change_attached")&&(p.event.add(b,"change._change",function(a){this.parentNode&&!a.isSimulated&&!a.isTrigger&&p.event.simulate("change",this.parentNode,a,!0)}),p._data(b,"_change_attached",!0))})},handle:function(a){var b=a.target;if(this!==b||a.isSimulated||a.isTrigger||b.type!=="radio"&&b.type!=="checkbox")return a.handleObj.handler.apply(this,arguments)},teardown:function(){return p.event.remove(this,"._change"),V.test(this.nodeName)}}),p.support.focusinBubbles||p.each({focus:"focusin",blur:"focusout"},function(a,b){var c=0,d=function(a){p.event.simulate(b,a.target,p.event.fix(a),!0)};p.event.special[b]={setup:function(){c++===0&&e.addEventListener(a,d,!0)},teardown:function(){--c===0&&e.removeEventListener(a,d,!0)}}}),p.fn.extend({on:function(a,c,d,e,f){var g,h;if(typeof a=="object"){typeof c!="string"&&(d=d||c,c=b);for(h in a)this.on(h,c,d,a[h],f);return this}d==null&&e==null?(e=c,d=c=b):e==null&&(typeof c=="string"?(e=d,d=b):(e=d,d=c,c=b));if(e===!1)e=ba;else if(!e)return this;return f===1&&(g=e,e=function(a){return p().off(a),g.apply(this,arguments)},e.guid=g.guid||(g.guid=p.guid++)),this.each(function(){p.event.add(this,a,e,d,c)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,c,d){var e,f;if(a&&a.preventDefault&&a.handleObj)return e=a.handleObj,p(a.delegateTarget).off(e.namespace?e.origType+"."+e.namespace:e.origType,e.selector,e.handler),this;if(typeof a=="object"){for(f in a)this.off(f,c,a[f]);return this}if(c===!1||typeof c=="function")d=c,c=b;return d===!1&&(d=ba),this.each(function(){p.event.remove(this,a,d,c)})},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},live:function(a,b,c){return p(this.context).on(a,this.selector,b,c),this},die:function(a,b){return p(this.context).off(a,this.selector||"**",b),this},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return arguments.length==1?this.off(a,"**"):this.off(b,a||"**",c)},trigger:function(a,b){return this.each(function(){p.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0])return p.event.trigger(a,b,this[0],!0)},toggle:function(a){var b=arguments,c=a.guid||p.guid++,d=0,e=function(c){var e=(p._data(this,"lastToggle"+a.guid)||0)%d;return p._data(this,"lastToggle"+a.guid,e+1),c.preventDefault(),b[e].apply(this,arguments)||!1};e.guid=c;while(d<b.length)b[d++].guid=c;return this.click(e)},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}}),p.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){p.fn[b]=function(a,c){return c==null&&(c=a,a=null),arguments.length>0?this.on(b,null,a,c):this.trigger(b)},Y.test(b)&&(p.event.fixHooks[b]=p.event.keyHooks),Z.test(b)&&(p.event.fixHooks[b]=p.event.mouseHooks)}),function(a,b){function bd(a,b,c,d){var e=0,f=b.length;for(;e<f;e++)Z(a,b[e],c,d)}function be(a,b,c,d,e,f){var g,h=$.setFilters[b.toLowerCase()];return h||Z.error(b),(a||!(g=e))&&bd(a||"*",d,g=[],e),g.length>0?h(g,c,f):[]}function bf(a,c,d,e,f){var g,h,i,j,k,l,m,n,p=0,q=f.length,s=L.POS,t=new RegExp("^"+s.source+"(?!"+r+")","i"),u=function(){var a=1,c=arguments.length-2;for(;a<c;a++)arguments[a]===b&&(g[a]=b)};for(;p<q;p++){s.exec(""),a=f[p],j=[],i=0,k=e;while(g=s.exec(a)){n=s.lastIndex=g.index+g[0].length;if(n>i){m=a.slice(i,g.index),i=n,l=[c],B.test(m)&&(k&&(l=k),k=e);if(h=H.test(m))m=m.slice(0,-5).replace(B,"$&*");g.length>1&&g[0].replace(t,u),k=be(m,g[1],g[2],l,k,h)}}k?(j=j.concat(k),(m=a.slice(i))&&m!==")"?B.test(m)?bd(m,j,d,e):Z(m,c,d,e?e.concat(k):k):o.apply(d,j)):Z(a,c,d,e)}return q===1?d:Z.uniqueSort(d)}function bg(a,b,c){var d,e,f,g=[],i=0,j=D.exec(a),k=!j.pop()&&!j.pop(),l=k&&a.match(C)||[""],m=$.preFilter,n=$.filter,o=!c&&b!==h;for(;(e=l[i])!=null&&k;i++){g.push(d=[]),o&&(e=" "+e);while(e){k=!1;if(j=B.exec(e))e=e.slice(j[0].length),k=d.push({part:j.pop().replace(A," "),captures:j});for(f in n)(j=L[f].exec(e))&&(!m[f]||(j=m[f](j,b,c)))&&(e=e.slice(j.shift().length),k=d.push({part:f,captures:j}));if(!k)break}}return k||Z.error(a),g}function bh(a,b,e){var f=b.dir,g=m++;return a||(a=function(a){return a===e}),b.first?function(b,c){while(b=b[f])if(b.nodeType===1)return a(b,c)&&b}:function(b,e){var h,i=g+"."+d,j=i+"."+c;while(b=b[f])if(b.nodeType===1){if((h=b[q])===j)return b.sizset;if(typeof h=="string"&&h.indexOf(i)===0){if(b.sizset)return b}else{b[q]=j;if(a(b,e))return b.sizset=!0,b;b.sizset=!1}}}}function bi(a,b){return a?function(c,d){var e=b(c,d);return e&&a(e===!0?c:e,d)}:b}function bj(a,b,c){var d,e,f=0;for(;d=a[f];f++)$.relative[d.part]?e=bh(e,$.relative[d.part],b):(d.captures.push(b,c),e=bi(e,$.filter[d.part].apply(null,d.captures)));return e}function bk(a){return function(b,c){var d,e=0;for(;d=a[e];e++)if(d(b,c))return!0;return!1}}var c,d,e,f,g,h=a.document,i=h.documentElement,j="undefined",k=!1,l=!0,m=0,n=[].slice,o=[].push,q=("sizcache"+Math.random()).replace(".",""),r="[\\x20\\t\\r\\n\\f]",s="(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",t=s.replace("w","w#"),u="([*^$|!~]?=)",v="\\["+r+"*("+s+")"+r+"*(?:"+u+r+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+t+")|)|)"+r+"*\\]",w=":("+s+")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|((?:[^,]|\\\\,|(?:,(?=[^\\[]*\\]))|(?:,(?=[^\\(]*\\))))*))\\)|)",x=":(nth|eq|gt|lt|first|last|even|odd)(?:\\((\\d*)\\)|)(?=[^-]|$)",y=r+"*([\\x20\\t\\r\\n\\f>+~])"+r+"*",z="(?=[^\\x20\\t\\r\\n\\f])(?:\\\\.|"+v+"|"+w.replace(2,7)+"|[^\\\\(),])+",A=new RegExp("^"+r+"+|((?:^|[^\\\\])(?:\\\\.)*)"+r+"+$","g"),B=new RegExp("^"+y),C=new RegExp(z+"?(?="+r+"*,|$)","g"),D=new RegExp("^(?:(?!,)(?:(?:^|,)"+r+"*"+z+")*?|"+r+"*(.*?))(\\)|$)"),E=new RegExp(z.slice(19,-6)+"\\x20\\t\\r\\n\\f>+~])+|"+y,"g"),F=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,G=/[\x20\t\r\n\f]*[+~]/,H=/:not\($/,I=/h\d/i,J=/input|select|textarea|button/i,K=/\\(?!\\)/g,L={ID:new RegExp("^#("+s+")"),CLASS:new RegExp("^\\.("+s+")"),NAME:new RegExp("^\\[name=['\"]?("+s+")['\"]?\\]"),TAG:new RegExp("^("+s.replace("[-","[-\\*")+")"),ATTR:new RegExp("^"+v),PSEUDO:new RegExp("^"+w),CHILD:new RegExp("^:(only|nth|last|first)-child(?:\\("+r+"*(even|odd|(([+-]|)(\\d*)n|)"+r+"*(?:([+-]|)"+r+"*(\\d+)|))"+r+"*\\)|)","i"),POS:new RegExp(x,"ig"),needsContext:new RegExp("^"+r+"*[>+~]|"+x,"i")},M={},N=[],O={},P=[],Q=function(a){return a.sizzleFilter=!0,a},R=function(a){return function(b){return b.nodeName.toLowerCase()==="input"&&b.type===a}},S=function(a){return function(b){var c=b.nodeName.toLowerCase();return(c==="input"||c==="button")&&b.type===a}},T=function(a){var b=!1,c=h.createElement("div");try{b=a(c)}catch(d){}return c=null,b},U=T(function(a){a.innerHTML="<select></select>";var b=typeof a.lastChild.getAttribute("multiple");return b!=="boolean"&&b!=="string"}),V=T(function(a){a.id=q+0,a.innerHTML="<a name='"+q+"'></a><div name='"+q+"'></div>",i.insertBefore(a,i.firstChild);var b=h.getElementsByName&&h.getElementsByName(q).length===2+h.getElementsByName(q+0).length;return g=!h.getElementById(q),i.removeChild(a),b}),W=T(function(a){return a.appendChild(h.createComment("")),a.getElementsByTagName("*").length===0}),X=T(function(a){return a.innerHTML="<a href='#'></a>",a.firstChild&&typeof a.firstChild.getAttribute!==j&&a.firstChild.getAttribute("href")==="#"}),Y=T(function(a){return a.innerHTML="<div class='hidden e'></div><div class='hidden'></div>",!a.getElementsByClassName||a.getElementsByClassName("e").length===0?!1:(a.lastChild.className="e",a.getElementsByClassName("e").length!==1)}),Z=function(a,b,c,d){c=c||[],b=b||h;var e,f,g,i,j=b.nodeType;if(j!==1&&j!==9)return[];if(!a||typeof a!="string")return c;g=ba(b);if(!g&&!d)if(e=F.exec(a))if(i=e[1]){if(j===9){f=b.getElementById(i);if(!f||!f.parentNode)return c;if(f.id===i)return c.push(f),c}else if(b.ownerDocument&&(f=b.ownerDocument.getElementById(i))&&bb(b,f)&&f.id===i)return c.push(f),c}else{if(e[2])return o.apply(c,n.call(b.getElementsByTagName(a),0)),c;if((i=e[3])&&Y&&b.getElementsByClassName)return o.apply(c,n.call(b.getElementsByClassName(i),0)),c}return bm(a,b,c,d,g)},$=Z.selectors={cacheLength:50,match:L,order:["ID","TAG"],attrHandle:{},createPseudo:Q,find:{ID:g?function(a,b,c){if(typeof b.getElementById!==j&&!c){var d=b.getElementById(a);return d&&d.parentNode?[d]:[]}}:function(a,c,d){if(typeof c.getElementById!==j&&!d){var e=c.getElementById(a);return e?e.id===a||typeof e.getAttributeNode!==j&&e.getAttributeNode("id").value===a?[e]:b:[]}},TAG:W?function(a,b){if(typeof b.getElementsByTagName!==j)return b.getElementsByTagName(a)}:function(a,b){var c=b.getElementsByTagName(a);if(a==="*"){var d,e=[],f=0;for(;d=c[f];f++)d.nodeType===1&&e.push(d);return e}return c}},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(K,""),a[3]=(a[4]||a[5]||"").replace(K,""),a[2]==="~="&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),a[1]==="nth"?(a[2]||Z.error(a[0]),a[3]=+(a[3]?a[4]+(a[5]||1):2*(a[2]==="even"||a[2]==="odd")),a[4]=+(a[6]+a[7]||a[2]==="odd")):a[2]&&Z.error(a[0]),a},PSEUDO:function(a){var b,c=a[4];return L.CHILD.test(a[0])?null:(c&&(b=D.exec(c))&&b.pop()&&(a[0]=a[0].slice(0,b[0].length-c.length-1),c=b[0].slice(0,-1)),a.splice(2,3,c||a[3]),a)}},filter:{ID:g?function(a){return a=a.replace(K,""),function(b){return b.getAttribute("id")===a}}:function(a){return a=a.replace(K,""),function(b){var c=typeof b.getAttributeNode!==j&&b.getAttributeNode("id");return c&&c.value===a}},TAG:function(a){return a==="*"?function(){return!0}:(a=a.replace(K,"").toLowerCase(),function(b){return b.nodeName&&b.nodeName.toLowerCase()===a})},CLASS:function(a){var b=M[a];return b||(b=M[a]=new RegExp("(^|"+r+")"+a+"("+r+"|$)"),N.push(a),N.length>$.cacheLength&&delete M[N.shift()]),function(a){return b.test(a.className||typeof a.getAttribute!==j&&a.getAttribute("class")||"")}},ATTR:function(a,b,c){return b?function(d){var e=Z.attr(d,a),f=e+"";if(e==null)return b==="!=";switch(b){case"=":return f===c;case"!=":return f!==c;case"^=":return c&&f.indexOf(c)===0;case"*=":return c&&f.indexOf(c)>-1;case"$=":return c&&f.substr(f.length-c.length)===c;case"~=":return(" "+f+" ").indexOf(c)>-1;case"|=":return f===c||f.substr(0,c.length+1)===c+"-"}}:function(b){return Z.attr(b,a)!=null}},CHILD:function(a,b,c,d){if(a==="nth"){var e=m++;return function(a){var b,f,g=0,h=a;if(c===1&&d===0)return!0;b=a.parentNode;if(b&&(b[q]!==e||!a.sizset)){for(h=b.firstChild;h;h=h.nextSibling)if(h.nodeType===1){h.sizset=++g;if(h===a)break}b[q]=e}return f=a.sizset-d,c===0?f===0:f%c===0&&f/c>=0}}return function(b){var c=b;switch(a){case"only":case"first":while(c=c.previousSibling)if(c.nodeType===1)return!1;if(a==="first")return!0;c=b;case"last":while(c=c.nextSibling)if(c.nodeType===1)return!1;return!0}}},PSEUDO:function(a,b,c,d){var e=$.pseudos[a]||$.pseudos[a.toLowerCase()];return e||Z.error("unsupported pseudo: "+a),e.sizzleFilter?e(b,c,d):e}},pseudos:{not:Q(function(a,b,c){var d=bl(a.replace(A,"$1"),b,c);return function(a){return!d(a)}}),enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&!!a.checked||b==="option"&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},parent:function(a){return!$.pseudos.empty(a)},empty:function(a){var b;a=a.firstChild;while(a){if(a.nodeName>"@"||(b=a.nodeType)===3||b===4)return!1;a=a.nextSibling}return!0},contains:Q(function(a){return function(b){return(b.textContent||b.innerText||bc(b)).indexOf(a)>-1}}),has:Q(function(a){return function(b){return Z(a,b).length>0}}),header:function(a){return I.test(a.nodeName)},text:function(a){var b,c;return a.nodeName.toLowerCase()==="input"&&(b=a.type)==="text"&&((c=a.getAttribute("type"))==null||c.toLowerCase()===b)},radio:R("radio"),checkbox:R("checkbox"),file:R("file"),password:R("password"),image:R("image"),submit:S("submit"),reset:S("reset"),button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&a.type==="button"||b==="button"},input:function(a){return J.test(a.nodeName)},focus:function(a){var b=a.ownerDocument;return a===b.activeElement&&(!b.hasFocus||b.hasFocus())&&(!!a.type||!!a.href)},active:function(a){return a===a.ownerDocument.activeElement}},setFilters:{first:function(a,b,c){return c?a.slice(1):[a[0]]},last:function(a,b,c){var d=a.pop();return c?a:[d]},even:function(a,b,c){var d=[],e=c?1:0,f=a.length;for(;e<f;e=e+2)d.push(a[e]);return d},odd:function(a,b,c){var d=[],e=c?0:1,f=a.length;for(;e<f;e=e+2)d.push(a[e]);return d},lt:function(a,b,c){return c?a.slice(+b):a.slice(0,+b)},gt:function(a,b,c){return c?a.slice(0,+b+1):a.slice(+b+1)},eq:function(a,b,c){var d=a.splice(+b,1);return c?a:d}}};$.setFilters.nth=$.setFilters.eq,$.filters=$.pseudos,X||($.attrHandle={href:function(a){return a.getAttribute("href",2)},type:function(a){return a.getAttribute("type")}}),V&&($.order.push("NAME"),$.find.NAME=function(a,b){if(typeof b.getElementsByName!==j)return b.getElementsByName(a)}),Y&&($.order.splice(1,0,"CLASS"),$.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!==j&&!c)return b.getElementsByClassName(a)});try{n.call(i.childNodes,0)[0].nodeType}catch(_){n=function(a){var b,c=[];for(;b=this[a];a++)c.push(b);return c}}var ba=Z.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?b.nodeName!=="HTML":!1},bb=Z.contains=i.compareDocumentPosition?function(a,b){return!!(a.compareDocumentPosition(b)&16)}:i.contains?function(a,b){var c=a.nodeType===9?a.documentElement:a,d=b.parentNode;return a===d||!!(d&&d.nodeType===1&&c.contains&&c.contains(d))}:function(a,b){while(b=b.parentNode)if(b===a)return!0;return!1},bc=Z.getText=function(a){var b,c="",d=0,e=a.nodeType;if(e){if(e===1||e===9||e===11){if(typeof a.textContent=="string")return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=bc(a)}else if(e===3||e===4)return a.nodeValue}else for(;b=a[d];d++)c+=bc(b);return c};Z.attr=function(a,b){var c,d=ba(a);return d||(b=b.toLowerCase()),$.attrHandle[b]?$.attrHandle[b](a):U||d?a.getAttribute(b):(c=a.getAttributeNode(b),c?typeof a[b]=="boolean"?a[b]?b:null:c.specified?c.value:null:null)},Z.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},[0,0].sort(function(){return l=0}),i.compareDocumentPosition?e=function(a,b){return a===b?(k=!0,0):(!a.compareDocumentPosition||!b.compareDocumentPosition?a.compareDocumentPosition:a.compareDocumentPosition(b)&4)?-1:1}:(e=function(a,b){if(a===b)return k=!0,0;if(a.sourceIndex&&b.sourceIndex)return a.sourceIndex-b.sourceIndex;var c,d,e=[],g=[],h=a.parentNode,i=b.parentNode,j=h;if(h===i)return f(a,b);if(!h)return-1;if(!i)return 1;while(j)e.unshift(j),j=j.parentNode;j=i;while(j)g.unshift(j),j=j.parentNode;c=e.length,d=g.length;for(var l=0;l<c&&l<d;l++)if(e[l]!==g[l])return f(e[l],g[l]);return l===c?f(a,g[l],-1):f(e[l],b,1)},f=function(a,b,c){if(a===b)return c;var d=a.nextSibling;while(d){if(d===b)return-1;d=d.nextSibling}return 1}),Z.uniqueSort=function(a){var b,c=1;if(e){k=l,a.sort(e);if(k)for(;b=a[c];c++)b===a[c-1]&&a.splice(c--,1)}return a};var bl=Z.compile=function(a,b,c){var d,e,f,g=O[a];if(g&&g.context===b)return g;e=bg(a,b,c);for(f=0;d=e[f];f++)e[f]=bj(d,b,c);return g=O[a]=bk(e),g.context=b,g.runs=g.dirruns=0,P.push(a),P.length>$.cacheLength&&delete O[P.shift()],g};Z.matches=function(a,b){return Z(a,null,null,b)},Z.matchesSelector=function(a,b){return Z(b,null,null,[a]).length>0};var bm=function(a,b,e,f,g){a=a.replace(A,"$1");var h,i,j,k,l,m,p,q,r,s=a.match(C),t=a.match(E),u=b.nodeType;if(L.POS.test(a))return bf(a,b,e,f,s);if(f)h=n.call(f,0);else if(s&&s.length===1){if(t.length>1&&u===9&&!g&&(s=L.ID.exec(t[0]))){b=$.find.ID(s[1],b,g)[0];if(!b)return e;a=a.slice(t.shift().length)}q=(s=G.exec(t[0]))&&!s.index&&b.parentNode||b,r=t.pop(),m=r.split(":not")[0];for(j=0,k=$.order.length;j<k;j++){p=$.order[j];if(s=L[p].exec(m)){h=$.find[p]((s[1]||"").replace(K,""),q,g);if(h==null)continue;m===r&&(a=a.slice(0,a.length-r.length)+m.replace(L[p],""),a||o.apply(e,n.call(h,0)));break}}}if(a){i=bl(a,b,g),d=i.dirruns++,h==null&&(h=$.find.TAG("*",G.test(a)&&b.parentNode||b));for(j=0;l=h[j];j++)c=i.runs++,i(l,b)&&e.push(l)}return e};h.querySelectorAll&&function(){var a,b=bm,c=/'|\\/g,d=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,e=[],f=[":active"],g=i.matchesSelector||i.mozMatchesSelector||i.webkitMatchesSelector||i.oMatchesSelector||i.msMatchesSelector;T(function(a){a.innerHTML="<select><option selected></option></select>",a.querySelectorAll("[selected]").length||e.push("\\["+r+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),a.querySelectorAll(":checked").length||e.push(":checked")}),T(function(a){a.innerHTML="<p test=''></p>",a.querySelectorAll("[test^='']").length&&e.push("[*^$]="+r+"*(?:\"\"|'')"),a.innerHTML="<input type='hidden'>",a.querySelectorAll(":enabled").length||e.push(":enabled",":disabled")}),e=e.length&&new RegExp(e.join("|")),bm=function(a,d,f,g,h){if(!g&&!h&&(!e||!e.test(a)))if(d.nodeType===9)try{return o.apply(f,n.call(d.querySelectorAll(a),0)),f}catch(i){}else if(d.nodeType===1&&d.nodeName.toLowerCase()!=="object"){var j=d.getAttribute("id"),k=j||q,l=G.test(a)&&d.parentNode||d;j?k=k.replace(c,"\\$&"):d.setAttribute("id",k);try{return o.apply(f,n.call(l.querySelectorAll(a.replace(C,"[id='"+k+"'] $&")),0)),f}catch(i){}finally{j||d.removeAttribute("id")}}return b(a,d,f,g,h)},g&&(T(function(b){a=g.call(b,"div");try{g.call(b,"[test!='']:sizzle"),f.push($.match.PSEUDO)}catch(c){}}),f=new RegExp(f.join("|")),Z.matchesSelector=function(b,c){c=c.replace(d,"='$1']");if(!ba(b)&&!f.test(c)&&(!e||!e.test(c)))try{var h=g.call(b,c);if(h||a||b.document&&b.document.nodeType!==11)return h}catch(i){}return Z(c,null,null,[b]).length>0})}(),Z.attr=p.attr,p.find=Z,p.expr=Z.selectors,p.expr[":"]=p.expr.pseudos,p.unique=Z.uniqueSort,p.text=Z.getText,p.isXMLDoc=Z.isXML,p.contains=Z.contains}(a);var bc=/Until$/,bd=/^(?:parents|prev(?:Until|All))/,be=/^.[^:#\[\.,]*$/,bf=p.expr.match.needsContext,bg={children:!0,contents:!0,next:!0,prev:!0};p.fn.extend({find:function(a){var b,c,d,e,f,g,h=this;if(typeof a!="string")return p(a).filter(function(){for(b=0,c=h.length;b<c;b++)if(p.contains(h[b],this))return!0});g=this.pushStack("","find",a);for(b=0,c=this.length;b<c;b++){d=g.length,p.find(a,this[b],g);if(b>0)for(e=d;e<g.length;e++)for(f=0;f<d;f++)if(g[f]===g[e]){g.splice(e--,1);break}}return g},has:function(a){var b,c=p(a,this),d=c.length;return this.filter(function(){for(b=0;b<d;b++)if(p.contains(this,c[b]))return!0})},not:function(a){return this.pushStack(bj(this,a,!1),"not",a)},filter:function(a){return this.pushStack(bj(this,a,!0),"filter",a)},is:function(a){return!!a&&(typeof a=="string"?bf.test(a)?p(a,this.context).index(this[0])>=0:p.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c,d=0,e=this.length,f=[],g=bf.test(a)||typeof a!="string"?p(a,b||this.context):0;for(;d<e;d++){c=this[d];while(c&&c.ownerDocument&&c!==b&&c.nodeType!==11){if(g?g.index(c)>-1:p.find.matchesSelector(c,a)){f.push(c);break}c=c.parentNode}}return f=f.length>1?p.unique(f):f,this.pushStack(f,"closest",a)},index:function(a){return a?typeof a=="string"?p.inArray(this[0],p(a)):p.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.prevAll().length:-1},add:function(a,b){var c=typeof a=="string"?p(a,b):p.makeArray(a&&a.nodeType?[a]:a),d=p.merge(this.get(),c);return this.pushStack(bh(c[0])||bh(d[0])?d:p.unique(d))},addBack:function(a){return this.add(a==null?this.prevObject:this.prevObject.filter(a))}}),p.fn.andSelf=p.fn.addBack,p.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return p.dir(a,"parentNode")},parentsUntil:function(a,b,c){return p.dir(a,"parentNode",c)},next:function(a){return bi(a,"nextSibling")},prev:function(a){return bi(a,"previousSibling")},nextAll:function(a){return p.dir(a,"nextSibling")},prevAll:function(a){return p.dir(a,"previousSibling")},nextUntil:function(a,b,c){return p.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return p.dir(a,"previousSibling",c)},siblings:function(a){return p.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return p.sibling(a.firstChild)},contents:function(a){return p.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:p.merge([],a.childNodes)}},function(a,b){p.fn[a]=function(c,d){var e=p.map(this,b,c);return bc.test(a)||(d=c),d&&typeof d=="string"&&(e=p.filter(d,e)),e=this.length>1&&!bg[a]?p.unique(e):e,this.length>1&&bd.test(a)&&(e=e.reverse()),this.pushStack(e,a,k.call(arguments).join(","))}}),p.extend({filter:function(a,b,c){return c&&(a=":not("+a+")"),b.length===1?p.find.matchesSelector(b[0],a)?[b[0]]:[]:p.find.matches(a,b)},dir:function(a,c,d){var e=[],f=a[c];while(f&&f.nodeType!==9&&(d===b||f.nodeType!==1||!p(f).is(d)))f.nodeType===1&&e.push(f),f=f[c];return e},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var bl="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",bm=/ jQuery\d+="(?:null|\d+)"/g,bn=/^\s+/,bo=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bp=/<([\w:]+)/,bq=/<tbody/i,br=/<|&#?\w+;/,bs=/<(?:script|style|link)/i,bt=/<(?:script|object|embed|option|style)/i,bu=new RegExp("<(?:"+bl+")[\\s/>]","i"),bv=/^(?:checkbox|radio)$/,bw=/checked\s*(?:[^=]|=\s*.checked.)/i,bx=/\/(java|ecma)script/i,by=/^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g,bz={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]},bA=bk(e),bB=bA.appendChild(e.createElement("div"));bz.optgroup=bz.option,bz.tbody=bz.tfoot=bz.colgroup=bz.caption=bz.thead,bz.th=bz.td,p.support.htmlSerialize||(bz._default=[1,"X<div>","</div>"]),p.fn.extend({text:function(a){return p.access(this,function(a){return a===b?p.text(this):this.empty().append((this[0]&&this[0].ownerDocument||e).createTextNode(a))},null,a,arguments.length)},wrapAll:function(a){if(p.isFunction(a))return this.each(function(b){p(this).wrapAll(a.call(this,b))});if(this[0]){var b=p(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return p.isFunction(a)?this.each(function(b){p(this).wrapInner(a.call(this,b))}):this.each(function(){var b=p(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=p.isFunction(a);return this.each(function(c){p(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){p.nodeName(this,"body")||p(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){(this.nodeType===1||this.nodeType===11)&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){(this.nodeType===1||this.nodeType===11)&&this.insertBefore(a,this.firstChild)})},before:function(){if(!bh(this[0]))return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=p.clean(arguments);return this.pushStack(p.merge(a,this),"before",this.selector)}},after:function(){if(!bh(this[0]))return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=p.clean(arguments);return this.pushStack(p.merge(this,a),"after",this.selector)}},remove:function(a,b){var c,d=0;for(;(c=this[d])!=null;d++)if(!a||p.filter(a,[c]).length)!b&&c.nodeType===1&&(p.cleanData(c.getElementsByTagName("*")),p.cleanData([c])),c.parentNode&&c.parentNode.removeChild(c);return this},empty:function(){var a,b=0;for(;(a=this[b])!=null;b++){a.nodeType===1&&p.cleanData(a.getElementsByTagName("*"));while(a.firstChild)a.removeChild(a.firstChild)}return this},clone:function(a,b){return a=a==null?!1:a,b=b==null?a:b,this.map(function(){return p.clone(this,a,b)})},html:function(a){return p.access(this,function(a){var c=this[0]||{},d=0,e=this.length;if(a===b)return c.nodeType===1?c.innerHTML.replace(bm,""):b;if(typeof a=="string"&&!bs.test(a)&&(p.support.htmlSerialize||!bu.test(a))&&(p.support.leadingWhitespace||!bn.test(a))&&!bz[(bp.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(bo,"<$1></$2>");try{for(;d<e;d++)c=this[d]||{},c.nodeType===1&&(p.cleanData(c.getElementsByTagName("*")),c.innerHTML=a);c=0}catch(f){}}c&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(a){return bh(this[0])?this.length?this.pushStack(p(p.isFunction(a)?a():a),"replaceWith",a):this:p.isFunction(a)?this.each(function(b){var c=p(this),d=c.html();c.replaceWith(a.call(this,b,d))}):(typeof a!="string"&&(a=p(a).detach()),this.each(function(){var b=this.nextSibling,c=this.parentNode;p(this).remove(),b?p(b).before(a):p(c).append(a)}))},detach:function(a){return this.remove(a,!0)},domManip:function(a,c,d){a=[].concat.apply([],a);var e,f,g,h,i=0,j=a[0],k=[],l=this.length;if(!p.support.checkClone&&l>1&&typeof j=="string"&&bw.test(j))return this.each(function(){p(this).domManip(a,c,d)});if(p.isFunction(j))return this.each(function(e){var f=p(this);a[0]=j.call(this,e,c?f.html():b),f.domManip(a,c,d)});if(this[0]){e=p.buildFragment(a,this,k),g=e.fragment,f=g.firstChild,g.childNodes.length===1&&(g=f);if(f){c=c&&p.nodeName(f,"tr");for(h=e.cacheable||l-1;i<l;i++)d.call(c&&p.nodeName(this[i],"table")?bC(this[i],"tbody"):this[i],i===h?g:p.clone(g,!0,!0))}g=f=null,k.length&&p.each(k,function(a,b){b.src?p.ajax?p.ajax({url:b.src,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0}):p.error("no ajax"):p.globalEval((b.text||b.textContent||b.innerHTML||"").replace(by,"")),b.parentNode&&b.parentNode.removeChild(b)})}return this}}),p.buildFragment=function(a,c,d){var f,g,h,i=a[0];return c=c||e,c=(c[0]||c).ownerDocument||c[0]||c,typeof c.createDocumentFragment=="undefined"&&(c=e),a.length===1&&typeof i=="string"&&i.length<512&&c===e&&i.charAt(0)==="<"&&!bt.test(i)&&(p.support.checkClone||!bw.test(i))&&(p.support.html5Clone||!bu.test(i))&&(g=!0,f=p.fragments[i],h=f!==b),f||(f=c.createDocumentFragment(),p.clean(a,c,f,d),g&&(p.fragments[i]=h&&f)),{fragment:f,cacheable:g}},p.fragments={},p.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){p.fn[a]=function(c){var d,e=0,f=[],g=p(c),h=g.length,i=this.length===1&&this[0].parentNode;if((i==null||i&&i.nodeType===11&&i.childNodes.length===1)&&h===1)return g[b](this[0]),this;for(;e<h;e++)d=(e>0?this.clone(!0):this).get(),p(g[e])[b](d),f=f.concat(d);return this.pushStack(f,a,g.selector)}}),p.extend({clone:function(a,b,c){var d,e,f,g;p.support.html5Clone||p.isXMLDoc(a)||!bu.test("<"+a.nodeName+">")?g=a.cloneNode(!0):(bB.innerHTML=a.outerHTML,bB.removeChild(g=bB.firstChild));if((!p.support.noCloneEvent||!p.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!p.isXMLDoc(a)){bE(a,g),d=bF(a),e=bF(g);for(f=0;d[f];++f)e[f]&&bE(d[f],e[f])}if(b){bD(a,g);if(c){d=bF(a),e=bF(g);for(f=0;d[f];++f)bD(d[f],e[f])}}return d=e=null,g},clean:function(a,b,c,d){var f,g,h,i,j,k,l,m,n,o,q,r,s=0,t=[];if(!b||typeof b.createDocumentFragment=="undefined")b=e;for(g=b===e&&bA;(h=a[s])!=null;s++){typeof h=="number"&&(h+="");if(!h)continue;if(typeof h=="string")if(!br.test(h))h=b.createTextNode(h);else{g=g||bk(b),l=l||g.appendChild(b.createElement("div")),h=h.replace(bo,"<$1></$2>"),i=(bp.exec(h)||["",""])[1].toLowerCase(),j=bz[i]||bz._default,k=j[0],l.innerHTML=j[1]+h+j[2];while(k--)l=l.lastChild;if(!p.support.tbody){m=bq.test(h),n=i==="table"&&!m?l.firstChild&&l.firstChild.childNodes:j[1]==="<table>"&&!m?l.childNodes:[];for(f=n.length-1;f>=0;--f)p.nodeName(n[f],"tbody")&&!n[f].childNodes.length&&n[f].parentNode.removeChild(n[f])}!p.support.leadingWhitespace&&bn.test(h)&&l.insertBefore(b.createTextNode(bn.exec(h)[0]),l.firstChild),h=l.childNodes,l=g.lastChild}h.nodeType?t.push(h):t=p.merge(t,h)}l&&(g.removeChild(l),h=l=g=null);if(!p.support.appendChecked)for(s=0;(h=t[s])!=null;s++)p.nodeName(h,"input")?bG(h):typeof h.getElementsByTagName!="undefined"&&p.grep(h.getElementsByTagName("input"),bG);if(c){q=function(a){if(!a.type||bx.test(a.type))return d?d.push(a.parentNode?a.parentNode.removeChild(a):a):c.appendChild(a)};for(s=0;(h=t[s])!=null;s++)if(!p.nodeName(h,"script")||!q(h))c.appendChild(h),typeof h.getElementsByTagName!="undefined"&&(r=p.grep(p.merge([],h.getElementsByTagName("script")),q),t.splice.apply(t,[s+1,0].concat(r)),s+=r.length)}return t},cleanData:function(a,b){var c,d,e,f,g=0,h=p.expando,i=p.cache,j=p.support.deleteExpando,k=p.event.special;for(;(e=a[g])!=null;g++)if(b||p.acceptData(e)){d=e[h],c=d&&i[d];if(c){if(c.events)for(f in c.events)k[f]?p.event.remove(e,f):p.removeEvent(e,f,c.handle);i[d]&&(delete i[d],j?delete e[h]:e.removeAttribute?e.removeAttribute(h):e[h]=null,p.deletedIds.push(d))}}}}),function(){var a,b;p.uaMatch=function(a){a=a.toLowerCase();var b=/(chrome)[ \/]([\w.]+)/.exec(a)||/(webkit)[ \/]([\w.]+)/.exec(a)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(a)||/(msie) ([\w.]+)/.exec(a)||a.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},a=p.uaMatch(g.userAgent),b={},a.browser&&(b[a.browser]=!0,b.version=a.version),b.webkit&&(b.safari=!0),p.browser=b,p.sub=function(){function a(b,c){return new a.fn.init(b,c)}p.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.sub=this.sub,a.fn.init=function c(c,d){return d&&d instanceof p&&!(d instanceof a)&&(d=a(d)),p.fn.init.call(this,c,d,b)},a.fn.init.prototype=a.fn;var b=a(e);return a}}();var bH,bI,bJ,bK=/alpha\([^)]*\)/i,bL=/opacity=([^)]*)/,bM=/^(top|right|bottom|left)$/,bN=/^margin/,bO=new RegExp("^("+q+")(.*)$","i"),bP=new RegExp("^("+q+")(?!px)[a-z%]+$","i"),bQ=new RegExp("^([-+])=("+q+")","i"),bR={},bS={position:"absolute",visibility:"hidden",display:"block"},bT={letterSpacing:0,fontWeight:400,lineHeight:1},bU=["Top","Right","Bottom","Left"],bV=["Webkit","O","Moz","ms"],bW=p.fn.toggle;p.fn.extend({css:function(a,c){return p.access(this,function(a,c,d){return d!==b?p.style(a,c,d):p.css(a,c)},a,c,arguments.length>1)},show:function(){return bZ(this,!0)},hide:function(){return bZ(this)},toggle:function(a,b){var c=typeof a=="boolean";return p.isFunction(a)&&p.isFunction(b)?bW.apply(this,arguments):this.each(function(){(c?a:bY(this))?p(this).show():p(this).hide()})}}),p.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=bH(a,"opacity");return c===""?"1":c}}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":p.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(!a||a.nodeType===3||a.nodeType===8||!a.style)return;var f,g,h,i=p.camelCase(c),j=a.style;c=p.cssProps[i]||(p.cssProps[i]=bX(j,i)),h=p.cssHooks[c]||p.cssHooks[i];if(d===b)return h&&"get"in h&&(f=h.get(a,!1,e))!==b?f:j[c];g=typeof d,g==="string"&&(f=bQ.exec(d))&&(d=(f[1]+1)*f[2]+parseFloat(p.css(a,c)),g="number");if(d==null||g==="number"&&isNaN(d))return;g==="number"&&!p.cssNumber[i]&&(d+="px");if(!h||!("set"in h)||(d=h.set(a,d,e))!==b)try{j[c]=d}catch(k){}},css:function(a,c,d,e){var f,g,h,i=p.camelCase(c);return c=p.cssProps[i]||(p.cssProps[i]=bX(a.style,i)),h=p.cssHooks[c]||p.cssHooks[i],h&&"get"in h&&(f=h.get(a,!0,e)),f===b&&(f=bH(a,c)),f==="normal"&&c in bT&&(f=bT[c]),d||e!==b?(g=parseFloat(f),d||p.isNumeric(g)?g||0:f):f},swap:function(a,b,c){var d,e,f={};for(e in b)f[e]=a.style[e],a.style[e]=b[e];d=c.call(a);for(e in b)a.style[e]=f[e];return d}}),a.getComputedStyle?bH=function(a,b){var c,d,e,f,g=getComputedStyle(a,null),h=a.style;return g&&(c=g[b],c===""&&!p.contains(a.ownerDocument.documentElement,a)&&(c=p.style(a,b)),bP.test(c)&&bN.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=c,c=g.width,h.width=d,h.minWidth=e,h.maxWidth=f)),c}:e.documentElement.currentStyle&&(bH=function(a,b){var c,d,e=a.currentStyle&&a.currentStyle[b],f=a.style;return e==null&&f&&f[b]&&(e=f[b]),bP.test(e)&&!bM.test(b)&&(c=f.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),f.left=b==="fontSize"?"1em":e,e=f.pixelLeft+"px",f.left=c,d&&(a.runtimeStyle.left=d)),e===""?"auto":e}),p.each(["height","width"],function(a,b){p.cssHooks[b]={get:function(a,c,d){if(c)return a.offsetWidth!==0||bH(a,"display")!=="none"?ca(a,b,d):p.swap(a,bS,function(){return ca(a,b,d)})},set:function(a,c,d){return b$(a,c,d?b_(a,b,d,p.support.boxSizing&&p.css(a,"boxSizing")==="border-box"):0)}}}),p.support.opacity||(p.cssHooks.opacity={get:function(a,b){return bL.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=p.isNumeric(b)?"alpha(opacity="+b*100+")":"",f=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&p.trim(f.replace(bK,""))===""&&c.removeAttribute){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bK.test(f)?f.replace(bK,e):f+" "+e}}),p(function(){p.support.reliableMarginRight||(p.cssHooks.marginRight={get:function(a,b){return p.swap(a,{display:"inline-block"},function(){if(b)return bH(a,"marginRight")})}}),!p.support.pixelPosition&&p.fn.position&&p.each(["top","left"],function(a,b){p.cssHooks[b]={get:function(a,c){if(c){var d=bH(a,b);return bP.test(d)?p(a).position()[b]+"px":d}}}})}),p.expr&&p.expr.filters&&(p.expr.filters.hidden=function(a){return a.offsetWidth===0&&a.offsetHeight===0||!p.support.reliableHiddenOffsets&&(a.style&&a.style.display||bH(a,"display"))==="none"},p.expr.filters.visible=function(a){return!p.expr.filters.hidden(a)}),p.each({margin:"",padding:"",border:"Width"},function(a,b){p.cssHooks[a+b]={expand:function(c){var d,e=typeof c=="string"?c.split(" "):[c],f={};for(d=0;d<4;d++)f[a+bU[d]+b]=e[d]||e[d-2]||e[0];return f}},bN.test(a)||(p.cssHooks[a+b].set=b$)});var cc=/%20/g,cd=/\[\]$/,ce=/\r?\n/g,cf=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,cg=/^(?:select|textarea)/i;p.fn.extend({serialize:function(){return p.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?p.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||cg.test(this.nodeName)||cf.test(this.type))}).map(function(a,b){var c=p(this).val();return c==null?null:p.isArray(c)?p.map(c,function(a,c){return{name:b.name,value:a.replace(ce,"\r\n")}}):{name:b.name,value:c.replace(ce,"\r\n")}}).get()}}),p.param=function(a,c){var d,e=[],f=function(a,b){b=p.isFunction(b)?b():b==null?"":b,e[e.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=p.ajaxSettings&&p.ajaxSettings.traditional);if(p.isArray(a)||a.jquery&&!p.isPlainObject(a))p.each(a,function(){f(this.name,this.value)});else for(d in a)ch(d,a[d],c,f);return e.join("&").replace(cc,"+")};var ci,cj,ck=/#.*$/,cl=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,cm=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,cn=/^(?:GET|HEAD)$/,co=/^\/\//,cp=/\?/,cq=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,cr=/([?&])_=[^&]*/,cs=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,ct=p.fn.load,cu={},cv={},cw=["*/"]+["*"];try{ci=f.href}catch(cx){ci=e.createElement("a"),ci.href="",ci=ci.href}cj=cs.exec(ci.toLowerCase())||[],p.fn.load=function(a,c,d){if(typeof a!="string"&&ct)return ct.apply(this,arguments);if(!this.length)return this;var e,f,g,h=this,i=a.indexOf(" ");return i>=0&&(e=a.slice(i,a.length),a=a.slice(0,i)),p.isFunction(c)?(d=c,c=b):typeof c=="object"&&(f="POST"),p.ajax({url:a,type:f,dataType:"html",data:c,complete:function(a,b){d&&h.each(d,g||[a.responseText,b,a])}}).done(function(a){g=arguments,h.html(e?p("<div>").append(a.replace(cq,"")).find(e):a)}),this},p.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){p.fn[b]=function(a){return this.on(b,a)}}),p.each(["get","post"],function(a,c){p[c]=function(a,d,e,f){return p.isFunction(d)&&(f=f||e,e=d,d=b),p.ajax({type:c,url:a,data:d,success:e,dataType:f})}}),p.extend({getScript:function(a,c){return p.get(a,b,c,"script")},getJSON:function(a,b,c){return p.get(a,b,c,"json")},ajaxSetup:function(a,b){return b?cA(a,p.ajaxSettings):(b=a,a=p.ajaxSettings),cA(a,b),a},ajaxSettings:{url:ci,isLocal:cm.test(cj[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":cw},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":p.parseJSON,"text xml":p.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:cy(cu),ajaxTransport:cy(cv),ajax:function(a,c){function y(a,c,f,i){var k,s,t,u,w,y=c;if(v===2)return;v=2,h&&clearTimeout(h),g=b,e=i||"",x.readyState=a>0?4:0,f&&(u=cB(l,x,f));if(a>=200&&a<300||a===304)l.ifModified&&(w=x.getResponseHeader("Last-Modified"),w&&(p.lastModified[d]=w),w=x.getResponseHeader("Etag"),w&&(p.etag[d]=w)),a===304?(y="notmodified",k=!0):(k=cC(l,u),y=k.state,s=k.data,t=k.error,k=!t);else{t=y;if(!y||a)y="error",a<0&&(a=0)}x.status=a,x.statusText=""+(c||y),k?o.resolveWith(m,[s,y,x]):o.rejectWith(m,[x,y,t]),x.statusCode(r),r=b,j&&n.trigger("ajax"+(k?"Success":"Error"),[x,l,k?s:t]),q.fireWith(m,[x,y]),j&&(n.trigger("ajaxComplete",[x,l]),--p.active||p.event.trigger("ajaxStop"))}typeof a=="object"&&(c=a,a=b),c=c||{};var d,e,f,g,h,i,j,k,l=p.ajaxSetup({},c),m=l.context||l,n=m!==l&&(m.nodeType||m instanceof p)?p(m):p.event,o=p.Deferred(),q=p.Callbacks("once memory"),r=l.statusCode||{},t={},u={},v=0,w="canceled",x={readyState:0,setRequestHeader:function(a,b){if(!v){var c=a.toLowerCase();a=u[c]=u[c]||a,t[a]=b}return this},getAllResponseHeaders:function(){return v===2?e:null},getResponseHeader:function(a){var c;if(v===2){if(!f){f={};while(c=cl.exec(e))f[c[1].toLowerCase()]=c[2]}c=f[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){return v||(l.mimeType=a),this},abort:function(a){return a=a||w,g&&g.abort(a),y(0,a),this}};o.promise(x),x.success=x.done,x.error=x.fail,x.complete=q.add,x.statusCode=function(a){if(a){var b;if(v<2)for(b in a)r[b]=[r[b],a[b]];else b=a[x.status],x.always(b)}return this},l.url=((a||l.url)+"").replace(ck,"").replace(co,cj[1]+"//"),l.dataTypes=p.trim(l.dataType||"*").toLowerCase().split(s),l.crossDomain==null&&(i=cs.exec(l.url.toLowerCase()),l.crossDomain=!(!i||i[1]==cj[1]&&i[2]==cj[2]&&(i[3]||(i[1]==="http:"?80:443))==(cj[3]||(cj[1]==="http:"?80:443)))),l.data&&l.processData&&typeof l.data!="string"&&(l.data=p.param(l.data,l.traditional)),cz(cu,l,c,x);if(v===2)return x;j=l.global,l.type=l.type.toUpperCase(),l.hasContent=!cn.test(l.type),j&&p.active++===0&&p.event.trigger("ajaxStart");if(!l.hasContent){l.data&&(l.url+=(cp.test(l.url)?"&":"?")+l.data,delete l.data),d=l.url;if(l.cache===!1){var z=p.now(),A=l.url.replace(cr,"$1_="+z);l.url=A+(A===l.url?(cp.test(l.url)?"&":"?")+"_="+z:"")}}(l.data&&l.hasContent&&l.contentType!==!1||c.contentType)&&x.setRequestHeader("Content-Type",l.contentType),l.ifModified&&(d=d||l.url,p.lastModified[d]&&x.setRequestHeader("If-Modified-Since",p.lastModified[d]),p.etag[d]&&x.setRequestHeader("If-None-Match",p.etag[d])),x.setRequestHeader("Accept",l.dataTypes[0]&&l.accepts[l.dataTypes[0]]?l.accepts[l.dataTypes[0]]+(l.dataTypes[0]!=="*"?", "+cw+"; q=0.01":""):l.accepts["*"]);for(k in l.headers)x.setRequestHeader(k,l.headers[k]);if(!l.beforeSend||l.beforeSend.call(m,x,l)!==!1&&v!==2){w="abort";for(k in{success:1,error:1,complete:1})x[k](l[k]);g=cz(cv,l,c,x);if(!g)y(-1,"No Transport");else{x.readyState=1,j&&n.trigger("ajaxSend",[x,l]),l.async&&l.timeout>0&&(h=setTimeout(function(){x.abort("timeout")},l.timeout));try{v=1,g.send(t,y)}catch(B){if(v<2)y(-1,B);else throw B}}return x}return x.abort()},active:0,lastModified:{},etag:{}});var cD=[],cE=/\?/,cF=/(=)\?(?=&|$)|\?\?/,cG=p.now();p.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=cD.pop()||p.expando+"_"+cG++;return this[a]=!0,a}}),p.ajaxPrefilter("json jsonp",function(c,d,e){var f,g,h,i=c.data,j=c.url,k=c.jsonp!==!1,l=k&&cF.test(j),m=k&&!l&&typeof i=="string"&&!(c.contentType||"").indexOf("application/x-www-form-urlencoded")&&cF.test(i);if(c.dataTypes[0]==="jsonp"||l||m)return f=c.jsonpCallback=p.isFunction(c.jsonpCallback)?c.jsonpCallback():c.jsonpCallback,g=a[f],l?c.url=j.replace(cF,"$1"+f):m?c.data=i.replace(cF,"$1"+f):k&&(c.url+=(cE.test(j)?"&":"?")+c.jsonp+"="+f),c.converters["script json"]=function(){return h||p.error(f+" was not called"),h[0]},c.dataTypes[0]="json",a[f]=function(){h=arguments},e.always(function(){a[f]=g,c[f]&&(c.jsonpCallback=d.jsonpCallback,cD.push(f)),h&&p.isFunction(g)&&g(h[0]),h=g=b}),"script"}),p.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){return p.globalEval(a),a}}}),p.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),p.ajaxTransport("script",function(a){if(a.crossDomain){var c,d=e.head||e.getElementsByTagName("head")[0]||e.documentElement;return{send:function(f,g){c=e.createElement("script"),c.async="async",a.scriptCharset&&(c.charset=a.scriptCharset),c.src=a.url,c.onload=c.onreadystatechange=function(a,e){if(e||!c.readyState||/loaded|complete/.test(c.readyState))c.onload=c.onreadystatechange=null,d&&c.parentNode&&d.removeChild(c),c=b,e||g(200,"success")},d.insertBefore(c,d.firstChild)},abort:function(){c&&c.onload(0,1)}}}});var cH,cI=a.ActiveXObject?function(){for(var a in cH)cH[a](0,1)}:!1,cJ=0;p.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&cK()||cL()}:cK,function(a){p.extend(p.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(p.ajaxSettings.xhr()),p.support.ajax&&p.ajaxTransport(function(c){if(!c.crossDomain||p.support.cors){var d;return{send:function(e,f){var g,h,i=c.xhr();c.username?i.open(c.type,c.url,c.async,c.username,c.password):i.open(c.type,c.url,c.async);if(c.xhrFields)for(h in c.xhrFields)i[h]=c.xhrFields[h];c.mimeType&&i.overrideMimeType&&i.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(h in e)i.setRequestHeader(h,e[h])}catch(j){}i.send(c.hasContent&&c.data||null),d=function(a,e){var h,j,k,l,m;try{if(d&&(e||i.readyState===4)){d=b,g&&(i.onreadystatechange=p.noop,cI&&delete cH[g]);if(e)i.readyState!==4&&i.abort();else{h=i.status,k=i.getAllResponseHeaders(),l={},m=i.responseXML,m&&m.documentElement&&(l.xml=m);try{l.text=i.responseText}catch(a){}try{j=i.statusText}catch(n){j=""}!h&&c.isLocal&&!c.crossDomain?h=l.text?200:404:h===1223&&(h=204)}}}catch(o){e||f(-1,o)}l&&f(h,j,l,k)},c.async?i.readyState===4?setTimeout(d,0):(g=++cJ,cI&&(cH||(cH={},p(a).unload(cI)),cH[g]=d),i.onreadystatechange=d):d()},abort:function(){d&&d(0,1)}}}});var cM,cN,cO=/^(?:toggle|show|hide)$/,cP=new RegExp("^(?:([-+])=|)("+q+")([a-z%]*)$","i"),cQ=/queueHooks$/,cR=[cX],cS={"*":[function(a,b){var c,d,e,f=this.createTween(a,b),g=cP.exec(b),h=f.cur(),i=+h||0,j=1;if(g){c=+g[2],d=g[3]||(p.cssNumber[a]?"":"px");if(d!=="px"&&i){i=p.css(f.elem,a,!0)||c||1;do e=j=j||".5",i=i/j,p.style(f.elem,a,i+d),j=f.cur()/h;while(j!==1&&j!==e)}f.unit=d,f.start=i,f.end=g[1]?i+(g[1]+1)*c:c}return f}]};p.Animation=p.extend(cV,{tweener:function(a,b){p.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");var c,d=0,e=a.length;for(;d<e;d++)c=a[d],cS[c]=cS[c]||[],cS[c].unshift(b)},prefilter:function(a,b){b?cR.unshift(a):cR.push(a)}}),p.Tween=cY,cY.prototype={constructor:cY,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(p.cssNumber[c]?"":"px")},cur:function(){var a=cY.propHooks[this.prop];return a&&a.get?a.get(this):cY.propHooks._default.get(this)},run:function(a){var b,c=cY.propHooks[this.prop];return this.pos=b=p.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration),this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):cY.propHooks._default.set(this),this}},cY.prototype.init.prototype=cY.prototype,cY.propHooks={_default:{get:function(a){var b;return a.elem[a.prop]==null||!!a.elem.style&&a.elem.style[a.prop]!=null?(b=p.css(a.elem,a.prop,!1,""),!b||b==="auto"?0:b):a.elem[a.prop]},set:function(a){p.fx.step[a.prop]?p.fx.step[a.prop](a):a.elem.style&&(a.elem.style[p.cssProps[a.prop]]!=null||p.cssHooks[a.prop])?p.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},cY.propHooks.scrollTop=cY.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},p.each(["toggle","show","hide"],function(a,b){var c=p.fn[b];p.fn[b]=function(d,e,f){return d==null||typeof d=="boolean"||!a&&p.isFunction(d)&&p.isFunction(e)?c.apply(this,arguments):this.animate(cZ(b,!0),d,e,f)}}),p.fn.extend({fadeTo:function(a,b,c,d){return this.filter(bY).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=p.isEmptyObject(a),f=p.speed(b,c,d),g=function(){var b=cV(this,p.extend({},a),f);e&&b.stop(!0)};return e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,c,d){var e=function(a){var b=a.stop;delete a.stop,b(d)};return typeof a!="string"&&(d=c,c=a,a=b),c&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,c=a!=null&&a+"queueHooks",f=p.timers,g=p._data(this);if(c)g[c]&&g[c].stop&&e(g[c]);else for(c in g)g[c]&&g[c].stop&&cQ.test(c)&&e(g[c]);for(c=f.length;c--;)f[c].elem===this&&(a==null||f[c].queue===a)&&(f[c].anim.stop(d),b=!1,f.splice(c,1));(b||!d)&&p.dequeue(this,a)})}}),p.each({slideDown:cZ("show"),slideUp:cZ("hide"),slideToggle:cZ("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){p.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),p.speed=function(a,b,c){var d=a&&typeof a=="object"?p.extend({},a):{complete:c||!c&&b||p.isFunction(a)&&a,duration:a,easing:c&&b||b&&!p.isFunction(b)&&b};d.duration=p.fx.off?0:typeof d.duration=="number"?d.duration:d.duration in p.fx.speeds?p.fx.speeds[d.duration]:p.fx.speeds._default;if(d.queue==null||d.queue===!0)d.queue="fx";return d.old=d.complete,d.complete=function(){p.isFunction(d.old)&&d.old.call(this),d.queue&&p.dequeue(this,d.queue)},d},p.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},p.timers=[],p.fx=cY.prototype.init,p.fx.tick=function(){var a,b=p.timers,c=0;for(;c<b.length;c++)a=b[c],!a()&&b[c]===a&&b.splice(c--,1);b.length||p.fx.stop()},p.fx.timer=function(a){a()&&p.timers.push(a)&&!cN&&(cN=setInterval(p.fx.tick,p.fx.interval))},p.fx.interval=13,p.fx.stop=function(){clearInterval(cN),cN=null},p.fx.speeds={slow:600,fast:200,_default:400},p.fx.step={},p.expr&&p.expr.filters&&(p.expr.filters.animated=function(a){return p.grep(p.timers,function(b){return a===b.elem}).length});var c$=/^(?:body|html)$/i;p.fn.offset=function(a){if(arguments.length)return a===b?this:this.each(function(b){p.offset.setOffset(this,a,b)});var c,d,e,f,g,h,i,j,k,l,m=this[0],n=m&&m.ownerDocument;if(!n)return;return(e=n.body)===m?p.offset.bodyOffset(m):(d=n.documentElement,p.contains(d,m)?(c=m.getBoundingClientRect(),f=c_(n),g=d.clientTop||e.clientTop||0,h=d.clientLeft||e.clientLeft||0,i=f.pageYOffset||d.scrollTop,j=f.pageXOffset||d.scrollLeft,k=c.top+i-g,l=c.left+j-h,{top:k,left:l}):{top:0,left:0})},p.offset={bodyOffset:function(a){var b=a.offsetTop,c=a.offsetLeft;return p.support.doesNotIncludeMarginInBodyOffset&&(b+=parseFloat(p.css(a,"marginTop"))||0,c+=parseFloat(p.css(a,"marginLeft"))||0),{top:b,left:c}},setOffset:function(a,b,c){var d=p.css(a,"position");d==="static"&&(a.style.position="relative");var e=p(a),f=e.offset(),g=p.css(a,"top"),h=p.css(a,"left"),i=(d==="absolute"||d==="fixed")&&p.inArray("auto",[g,h])>-1,j={},k={},l,m;i?(k=e.position(),l=k.top,m=k.left):(l=parseFloat(g)||0,m=parseFloat(h)||0),p.isFunction(b)&&(b=b.call(a,c,f)),b.top!=null&&(j.top=b.top-f.top+l),b.left!=null&&(j.left=b.left-f.left+m),"using"in b?b.using.call(a,j):e.css(j)}},p.fn.extend({position:function(){if(!this[0])return;var a=this[0],b=this.offsetParent(),c=this.offset(),d=c$.test(b[0].nodeName)?{top:0,left:0}:b.offset();return c.top-=parseFloat(p.css(a,"marginTop"))||0,c.left-=parseFloat(p.css(a,"marginLeft"))||0,d.top+=parseFloat(p.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(p.css(b[0],"borderLeftWidth"))||0,{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||e.body;while(a&&!c$.test(a.nodeName)&&p.css(a,"position")==="static")a=a.offsetParent;return a||e.body})}}),p.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,c){var d=/Y/.test(c);p.fn[a]=function(e){return p.access(this,function(a,e,f){var g=c_(a);if(f===b)return g?c in g?g[c]:g.document.documentElement[e]:a[e];g?g.scrollTo(d?p(g).scrollLeft():f,d?f:p(g).scrollTop()):a[e]=f},a,e,arguments.length,null)}}),p.each({Height:"height",Width:"width"},function(a,c){p.each({padding:"inner"+a,content:c,"":"outer"+a},function(d,e){p.fn[e]=function(e,f){var g=arguments.length&&(d||typeof e!="boolean"),h=d||(e===!0||f===!0?"margin":"border");return p.access(this,function(c,d,e){var f;return p.isWindow(c)?c.document.documentElement["client"+a]:c.nodeType===9?(f=c.documentElement,Math.max(c.body["scroll"+a],f["scroll"+a],c.body["offset"+a],f["offset"+a],f["client"+a])):e===b?p.css(c,d,e,h):p.style(c,d,e,h)},c,g?e:b,g)}})}),a.jQuery=a.$=p,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return p})})(window); \ No newline at end of file
diff --git a/catalog-be/src/main/resources/swagger/lib/jquery.ba-bbq.min.js b/catalog-be/src/main/resources/swagger/lib/jquery.ba-bbq.min.js
index 0bcdb66da5..bcbf24834a 100644
--- a/catalog-be/src/main/resources/swagger/lib/jquery.ba-bbq.min.js
+++ b/catalog-be/src/main/resources/swagger/lib/jquery.ba-bbq.min.js
@@ -1,23 +1,3 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
/*
* jQuery BBQ: Back Button & Query Library - v1.2.1 - 2/17/2010
* http://benalman.com/projects/jquery-bbq-plugin/
@@ -35,4 +15,4 @@
* Dual licensed under the MIT and GPL licenses.
* http://benalman.com/about/license/
*/
-(function($,i,b){var j,k=$.event.special,c="location",d="hashchange",l="href",f=$.browser,g=document.documentMode,h=f.msie&&(g===b||g<8),e="on"+d in i&&!h;function a(m){m=m||i[c][l];return m.replace(/^[^#]*#?(.*)$/,"$1")}$[d+"Delay"]=100;k[d]=$.extend(k[d],{setup:function(){if(e){return false}$(j.start)},teardown:function(){if(e){return false}$(j.stop)}});j=(function(){var m={},r,n,o,q;function p(){o=q=function(s){return s};if(h){n=$('<iframe src="javascript:0"/>').hide().insertAfter("body")[0].contentWindow;q=function(){return a(n.document[c][l])};o=function(u,s){if(u!==s){var t=n.document;t.open().close();t[c].hash="#"+u}};o(a())}}m.start=function(){if(r){return}var t=a();o||p();(function s(){var v=a(),u=q(t);if(v!==t){o(t=v,u);$(i).trigger(d)}else{if(u!==t){i[c][l]=i[c][l].replace(/#.*/,"")+"#"+u}}r=setTimeout(s,$[d+"Delay"])})()};m.stop=function(){if(!n){r&&clearTimeout(r);r=0}};return m})()})(jQuery,this);
+(function($,i,b){var j,k=$.event.special,c="location",d="hashchange",l="href",f=$.browser,g=document.documentMode,h=f.msie&&(g===b||g<8),e="on"+d in i&&!h;function a(m){m=m||i[c][l];return m.replace(/^[^#]*#?(.*)$/,"$1")}$[d+"Delay"]=100;k[d]=$.extend(k[d],{setup:function(){if(e){return false}$(j.start)},teardown:function(){if(e){return false}$(j.stop)}});j=(function(){var m={},r,n,o,q;function p(){o=q=function(s){return s};if(h){n=$('<iframe src="javascript:0"/>').hide().insertAfter("body")[0].contentWindow;q=function(){return a(n.document[c][l])};o=function(u,s){if(u!==s){var t=n.document;t.open().close();t[c].hash="#"+u}};o(a())}}m.start=function(){if(r){return}var t=a();o||p();(function s(){var v=a(),u=q(t);if(v!==t){o(t=v,u);$(i).trigger(d)}else{if(u!==t){i[c][l]=i[c][l].replace(/#.*/,"")+"#"+u}}r=setTimeout(s,$[d+"Delay"])})()};m.stop=function(){if(!n){r&&clearTimeout(r);r=0}};return m})()})(jQuery,this); \ No newline at end of file
diff --git a/catalog-be/src/main/resources/swagger/lib/jquery.slideto.min.js b/catalog-be/src/main/resources/swagger/lib/jquery.slideto.min.js
index df80c45ae6..ba32cff365 100644
--- a/catalog-be/src/main/resources/swagger/lib/jquery.slideto.min.js
+++ b/catalog-be/src/main/resources/swagger/lib/jquery.slideto.min.js
@@ -1,21 +1 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
(function(b){b.fn.slideto=function(a){a=b.extend({slide_duration:"slow",highlight_duration:3E3,highlight:true,highlight_color:"#FFFF99"},a);return this.each(function(){obj=b(this);b("body").animate({scrollTop:obj.offset().top},a.slide_duration,function(){a.highlight&&b.ui.version&&obj.effect("highlight",{color:a.highlight_color},a.highlight_duration)})})}})(jQuery);
diff --git a/catalog-be/src/main/resources/swagger/lib/jquery.wiggle.min.js b/catalog-be/src/main/resources/swagger/lib/jquery.wiggle.min.js
index 0bdb2b2fd3..2adb0d6d54 100644
--- a/catalog-be/src/main/resources/swagger/lib/jquery.wiggle.min.js
+++ b/catalog-be/src/main/resources/swagger/lib/jquery.wiggle.min.js
@@ -1,23 +1,3 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
/*
jQuery Wiggle
Author: WonderGroup, Jordan Thomas
@@ -25,4 +5,4 @@ URL: http://labs.wondergroup.com/demos/mini-ui/index.html
License: MIT (http://en.wikipedia.org/wiki/MIT_License)
*/
jQuery.fn.wiggle=function(o){var d={speed:50,wiggles:3,travel:5,callback:null};var o=jQuery.extend(d,o);return this.each(function(){var cache=this;var wrap=jQuery(this).wrap('<div class="wiggle-wrap"></div>').css("position","relative");var calls=0;for(i=1;i<=o.wiggles;i++){jQuery(this).animate({left:"-="+o.travel},o.speed).animate({left:"+="+o.travel*2},o.speed*2).animate({left:"-="+o.travel},o.speed,function(){calls++;if(jQuery(cache).parent().hasClass('wiggle-wrap')){jQuery(cache).parent().replaceWith(cache);}
-if(calls==o.wiggles&&jQuery.isFunction(o.callback)){o.callback();}});}});};
+if(calls==o.wiggles&&jQuery.isFunction(o.callback)){o.callback();}});}});}; \ No newline at end of file
diff --git a/catalog-be/src/main/resources/swagger/lib/marked.js b/catalog-be/src/main/resources/swagger/lib/marked.js
index cfa182fe4d..c2a678d550 100644
--- a/catalog-be/src/main/resources/swagger/lib/marked.js
+++ b/catalog-be/src/main/resources/swagger/lib/marked.js
@@ -1,23 +1,3 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
/**
* marked - a markdown parser
* Copyright (c) 2011-2014, Christopher Jeffrey. (MIT Licensed)
@@ -1289,4 +1269,4 @@ if (typeof module !== 'undefined' && typeof exports === 'object') {
}).call(function() {
return this || (typeof window !== 'undefined' ? window : global);
-}());
+}()); \ No newline at end of file
diff --git a/catalog-be/src/main/resources/swagger/lib/swagger-oauth.js b/catalog-be/src/main/resources/swagger/lib/swagger-oauth.js
index d44bdf8fde..b2254b7f52 100644
--- a/catalog-be/src/main/resources/swagger/lib/swagger-oauth.js
+++ b/catalog-be/src/main/resources/swagger/lib/swagger-oauth.js
@@ -1,23 +1,3 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
var appName;
var popupMask;
var popupDialog;
@@ -301,4 +281,4 @@ window.onOAuthComplete = function onOAuthComplete(token) {
}
}
}
-}
+} \ No newline at end of file
diff --git a/catalog-be/src/main/resources/swagger/lib/underscore-min.js b/catalog-be/src/main/resources/swagger/lib/underscore-min.js
index 56cf7330d2..11f1d96f53 100644
--- a/catalog-be/src/main/resources/swagger/lib/underscore-min.js
+++ b/catalog-be/src/main/resources/swagger/lib/underscore-min.js
@@ -1,26 +1,6 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
// Underscore.js 1.7.0
// http://underscorejs.org
// (c) 2009-2014 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
// Underscore may be freely distributed under the MIT license.
(function(){var n=this,t=n._,r=Array.prototype,e=Object.prototype,u=Function.prototype,i=r.push,a=r.slice,o=r.concat,l=e.toString,c=e.hasOwnProperty,f=Array.isArray,s=Object.keys,p=u.bind,h=function(n){return n instanceof h?n:this instanceof h?void(this._wrapped=n):new h(n)};"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=h),exports._=h):n._=h,h.VERSION="1.7.0";var g=function(n,t,r){if(t===void 0)return n;switch(null==r?3:r){case 1:return function(r){return n.call(t,r)};case 2:return function(r,e){return n.call(t,r,e)};case 3:return function(r,e,u){return n.call(t,r,e,u)};case 4:return function(r,e,u,i){return n.call(t,r,e,u,i)}}return function(){return n.apply(t,arguments)}};h.iteratee=function(n,t,r){return null==n?h.identity:h.isFunction(n)?g(n,t,r):h.isObject(n)?h.matches(n):h.property(n)},h.each=h.forEach=function(n,t,r){if(null==n)return n;t=g(t,r);var e,u=n.length;if(u===+u)for(e=0;u>e;e++)t(n[e],e,n);else{var i=h.keys(n);for(e=0,u=i.length;u>e;e++)t(n[i[e]],i[e],n)}return n},h.map=h.collect=function(n,t,r){if(null==n)return[];t=h.iteratee(t,r);for(var e,u=n.length!==+n.length&&h.keys(n),i=(u||n).length,a=Array(i),o=0;i>o;o++)e=u?u[o]:o,a[o]=t(n[e],e,n);return a};var v="Reduce of empty array with no initial value";h.reduce=h.foldl=h.inject=function(n,t,r,e){null==n&&(n=[]),t=g(t,e,4);var u,i=n.length!==+n.length&&h.keys(n),a=(i||n).length,o=0;if(arguments.length<3){if(!a)throw new TypeError(v);r=n[i?i[o++]:o++]}for(;a>o;o++)u=i?i[o]:o,r=t(r,n[u],u,n);return r},h.reduceRight=h.foldr=function(n,t,r,e){null==n&&(n=[]),t=g(t,e,4);var u,i=n.length!==+n.length&&h.keys(n),a=(i||n).length;if(arguments.length<3){if(!a)throw new TypeError(v);r=n[i?i[--a]:--a]}for(;a--;)u=i?i[a]:a,r=t(r,n[u],u,n);return r},h.find=h.detect=function(n,t,r){var e;return t=h.iteratee(t,r),h.some(n,function(n,r,u){return t(n,r,u)?(e=n,!0):void 0}),e},h.filter=h.select=function(n,t,r){var e=[];return null==n?e:(t=h.iteratee(t,r),h.each(n,function(n,r,u){t(n,r,u)&&e.push(n)}),e)},h.reject=function(n,t,r){return h.filter(n,h.negate(h.iteratee(t)),r)},h.every=h.all=function(n,t,r){if(null==n)return!0;t=h.iteratee(t,r);var e,u,i=n.length!==+n.length&&h.keys(n),a=(i||n).length;for(e=0;a>e;e++)if(u=i?i[e]:e,!t(n[u],u,n))return!1;return!0},h.some=h.any=function(n,t,r){if(null==n)return!1;t=h.iteratee(t,r);var e,u,i=n.length!==+n.length&&h.keys(n),a=(i||n).length;for(e=0;a>e;e++)if(u=i?i[e]:e,t(n[u],u,n))return!0;return!1},h.contains=h.include=function(n,t){return null==n?!1:(n.length!==+n.length&&(n=h.values(n)),h.indexOf(n,t)>=0)},h.invoke=function(n,t){var r=a.call(arguments,2),e=h.isFunction(t);return h.map(n,function(n){return(e?t:n[t]).apply(n,r)})},h.pluck=function(n,t){return h.map(n,h.property(t))},h.where=function(n,t){return h.filter(n,h.matches(t))},h.findWhere=function(n,t){return h.find(n,h.matches(t))},h.max=function(n,t,r){var e,u,i=-1/0,a=-1/0;if(null==t&&null!=n){n=n.length===+n.length?n:h.values(n);for(var o=0,l=n.length;l>o;o++)e=n[o],e>i&&(i=e)}else t=h.iteratee(t,r),h.each(n,function(n,r,e){u=t(n,r,e),(u>a||u===-1/0&&i===-1/0)&&(i=n,a=u)});return i},h.min=function(n,t,r){var e,u,i=1/0,a=1/0;if(null==t&&null!=n){n=n.length===+n.length?n:h.values(n);for(var o=0,l=n.length;l>o;o++)e=n[o],i>e&&(i=e)}else t=h.iteratee(t,r),h.each(n,function(n,r,e){u=t(n,r,e),(a>u||1/0===u&&1/0===i)&&(i=n,a=u)});return i},h.shuffle=function(n){for(var t,r=n&&n.length===+n.length?n:h.values(n),e=r.length,u=Array(e),i=0;e>i;i++)t=h.random(0,i),t!==i&&(u[i]=u[t]),u[t]=r[i];return u},h.sample=function(n,t,r){return null==t||r?(n.length!==+n.length&&(n=h.values(n)),n[h.random(n.length-1)]):h.shuffle(n).slice(0,Math.max(0,t))},h.sortBy=function(n,t,r){return t=h.iteratee(t,r),h.pluck(h.map(n,function(n,r,e){return{value:n,index:r,criteria:t(n,r,e)}}).sort(function(n,t){var r=n.criteria,e=t.criteria;if(r!==e){if(r>e||r===void 0)return 1;if(e>r||e===void 0)return-1}return n.index-t.index}),"value")};var m=function(n){return function(t,r,e){var u={};return r=h.iteratee(r,e),h.each(t,function(e,i){var a=r(e,i,t);n(u,e,a)}),u}};h.groupBy=m(function(n,t,r){h.has(n,r)?n[r].push(t):n[r]=[t]}),h.indexBy=m(function(n,t,r){n[r]=t}),h.countBy=m(function(n,t,r){h.has(n,r)?n[r]++:n[r]=1}),h.sortedIndex=function(n,t,r,e){r=h.iteratee(r,e,1);for(var u=r(t),i=0,a=n.length;a>i;){var o=i+a>>>1;r(n[o])<u?i=o+1:a=o}return i},h.toArray=function(n){return n?h.isArray(n)?a.call(n):n.length===+n.length?h.map(n,h.identity):h.values(n):[]},h.size=function(n){return null==n?0:n.length===+n.length?n.length:h.keys(n).length},h.partition=function(n,t,r){t=h.iteratee(t,r);var e=[],u=[];return h.each(n,function(n,r,i){(t(n,r,i)?e:u).push(n)}),[e,u]},h.first=h.head=h.take=function(n,t,r){return null==n?void 0:null==t||r?n[0]:0>t?[]:a.call(n,0,t)},h.initial=function(n,t,r){return a.call(n,0,Math.max(0,n.length-(null==t||r?1:t)))},h.last=function(n,t,r){return null==n?void 0:null==t||r?n[n.length-1]:a.call(n,Math.max(n.length-t,0))},h.rest=h.tail=h.drop=function(n,t,r){return a.call(n,null==t||r?1:t)},h.compact=function(n){return h.filter(n,h.identity)};var y=function(n,t,r,e){if(t&&h.every(n,h.isArray))return o.apply(e,n);for(var u=0,a=n.length;a>u;u++){var l=n[u];h.isArray(l)||h.isArguments(l)?t?i.apply(e,l):y(l,t,r,e):r||e.push(l)}return e};h.flatten=function(n,t){return y(n,t,!1,[])},h.without=function(n){return h.difference(n,a.call(arguments,1))},h.uniq=h.unique=function(n,t,r,e){if(null==n)return[];h.isBoolean(t)||(e=r,r=t,t=!1),null!=r&&(r=h.iteratee(r,e));for(var u=[],i=[],a=0,o=n.length;o>a;a++){var l=n[a];if(t)a&&i===l||u.push(l),i=l;else if(r){var c=r(l,a,n);h.indexOf(i,c)<0&&(i.push(c),u.push(l))}else h.indexOf(u,l)<0&&u.push(l)}return u},h.union=function(){return h.uniq(y(arguments,!0,!0,[]))},h.intersection=function(n){if(null==n)return[];for(var t=[],r=arguments.length,e=0,u=n.length;u>e;e++){var i=n[e];if(!h.contains(t,i)){for(var a=1;r>a&&h.contains(arguments[a],i);a++);a===r&&t.push(i)}}return t},h.difference=function(n){var t=y(a.call(arguments,1),!0,!0,[]);return h.filter(n,function(n){return!h.contains(t,n)})},h.zip=function(n){if(null==n)return[];for(var t=h.max(arguments,"length").length,r=Array(t),e=0;t>e;e++)r[e]=h.pluck(arguments,e);return r},h.object=function(n,t){if(null==n)return{};for(var r={},e=0,u=n.length;u>e;e++)t?r[n[e]]=t[e]:r[n[e][0]]=n[e][1];return r},h.indexOf=function(n,t,r){if(null==n)return-1;var e=0,u=n.length;if(r){if("number"!=typeof r)return e=h.sortedIndex(n,t),n[e]===t?e:-1;e=0>r?Math.max(0,u+r):r}for(;u>e;e++)if(n[e]===t)return e;return-1},h.lastIndexOf=function(n,t,r){if(null==n)return-1;var e=n.length;for("number"==typeof r&&(e=0>r?e+r+1:Math.min(e,r+1));--e>=0;)if(n[e]===t)return e;return-1},h.range=function(n,t,r){arguments.length<=1&&(t=n||0,n=0),r=r||1;for(var e=Math.max(Math.ceil((t-n)/r),0),u=Array(e),i=0;e>i;i++,n+=r)u[i]=n;return u};var d=function(){};h.bind=function(n,t){var r,e;if(p&&n.bind===p)return p.apply(n,a.call(arguments,1));if(!h.isFunction(n))throw new TypeError("Bind must be called on a function");return r=a.call(arguments,2),e=function(){if(!(this instanceof e))return n.apply(t,r.concat(a.call(arguments)));d.prototype=n.prototype;var u=new d;d.prototype=null;var i=n.apply(u,r.concat(a.call(arguments)));return h.isObject(i)?i:u}},h.partial=function(n){var t=a.call(arguments,1);return function(){for(var r=0,e=t.slice(),u=0,i=e.length;i>u;u++)e[u]===h&&(e[u]=arguments[r++]);for(;r<arguments.length;)e.push(arguments[r++]);return n.apply(this,e)}},h.bindAll=function(n){var t,r,e=arguments.length;if(1>=e)throw new Error("bindAll must be passed function names");for(t=1;e>t;t++)r=arguments[t],n[r]=h.bind(n[r],n);return n},h.memoize=function(n,t){var r=function(e){var u=r.cache,i=t?t.apply(this,arguments):e;return h.has(u,i)||(u[i]=n.apply(this,arguments)),u[i]};return r.cache={},r},h.delay=function(n,t){var r=a.call(arguments,2);return setTimeout(function(){return n.apply(null,r)},t)},h.defer=function(n){return h.delay.apply(h,[n,1].concat(a.call(arguments,1)))},h.throttle=function(n,t,r){var e,u,i,a=null,o=0;r||(r={});var l=function(){o=r.leading===!1?0:h.now(),a=null,i=n.apply(e,u),a||(e=u=null)};return function(){var c=h.now();o||r.leading!==!1||(o=c);var f=t-(c-o);return e=this,u=arguments,0>=f||f>t?(clearTimeout(a),a=null,o=c,i=n.apply(e,u),a||(e=u=null)):a||r.trailing===!1||(a=setTimeout(l,f)),i}},h.debounce=function(n,t,r){var e,u,i,a,o,l=function(){var c=h.now()-a;t>c&&c>0?e=setTimeout(l,t-c):(e=null,r||(o=n.apply(i,u),e||(i=u=null)))};return function(){i=this,u=arguments,a=h.now();var c=r&&!e;return e||(e=setTimeout(l,t)),c&&(o=n.apply(i,u),i=u=null),o}},h.wrap=function(n,t){return h.partial(t,n)},h.negate=function(n){return function(){return!n.apply(this,arguments)}},h.compose=function(){var n=arguments,t=n.length-1;return function(){for(var r=t,e=n[t].apply(this,arguments);r--;)e=n[r].call(this,e);return e}},h.after=function(n,t){return function(){return--n<1?t.apply(this,arguments):void 0}},h.before=function(n,t){var r;return function(){return--n>0?r=t.apply(this,arguments):t=null,r}},h.once=h.partial(h.before,2),h.keys=function(n){if(!h.isObject(n))return[];if(s)return s(n);var t=[];for(var r in n)h.has(n,r)&&t.push(r);return t},h.values=function(n){for(var t=h.keys(n),r=t.length,e=Array(r),u=0;r>u;u++)e[u]=n[t[u]];return e},h.pairs=function(n){for(var t=h.keys(n),r=t.length,e=Array(r),u=0;r>u;u++)e[u]=[t[u],n[t[u]]];return e},h.invert=function(n){for(var t={},r=h.keys(n),e=0,u=r.length;u>e;e++)t[n[r[e]]]=r[e];return t},h.functions=h.methods=function(n){var t=[];for(var r in n)h.isFunction(n[r])&&t.push(r);return t.sort()},h.extend=function(n){if(!h.isObject(n))return n;for(var t,r,e=1,u=arguments.length;u>e;e++){t=arguments[e];for(r in t)c.call(t,r)&&(n[r]=t[r])}return n},h.pick=function(n,t,r){var e,u={};if(null==n)return u;if(h.isFunction(t)){t=g(t,r);for(e in n){var i=n[e];t(i,e,n)&&(u[e]=i)}}else{var l=o.apply([],a.call(arguments,1));n=new Object(n);for(var c=0,f=l.length;f>c;c++)e=l[c],e in n&&(u[e]=n[e])}return u},h.omit=function(n,t,r){if(h.isFunction(t))t=h.negate(t);else{var e=h.map(o.apply([],a.call(arguments,1)),String);t=function(n,t){return!h.contains(e,t)}}return h.pick(n,t,r)},h.defaults=function(n){if(!h.isObject(n))return n;for(var t=1,r=arguments.length;r>t;t++){var e=arguments[t];for(var u in e)n[u]===void 0&&(n[u]=e[u])}return n},h.clone=function(n){return h.isObject(n)?h.isArray(n)?n.slice():h.extend({},n):n},h.tap=function(n,t){return t(n),n};var b=function(n,t,r,e){if(n===t)return 0!==n||1/n===1/t;if(null==n||null==t)return n===t;n instanceof h&&(n=n._wrapped),t instanceof h&&(t=t._wrapped);var u=l.call(n);if(u!==l.call(t))return!1;switch(u){case"[object RegExp]":case"[object String]":return""+n==""+t;case"[object Number]":return+n!==+n?+t!==+t:0===+n?1/+n===1/t:+n===+t;case"[object Date]":case"[object Boolean]":return+n===+t}if("object"!=typeof n||"object"!=typeof t)return!1;for(var i=r.length;i--;)if(r[i]===n)return e[i]===t;var a=n.constructor,o=t.constructor;if(a!==o&&"constructor"in n&&"constructor"in t&&!(h.isFunction(a)&&a instanceof a&&h.isFunction(o)&&o instanceof o))return!1;r.push(n),e.push(t);var c,f;if("[object Array]"===u){if(c=n.length,f=c===t.length)for(;c--&&(f=b(n[c],t[c],r,e)););}else{var s,p=h.keys(n);if(c=p.length,f=h.keys(t).length===c)for(;c--&&(s=p[c],f=h.has(t,s)&&b(n[s],t[s],r,e)););}return r.pop(),e.pop(),f};h.isEqual=function(n,t){return b(n,t,[],[])},h.isEmpty=function(n){if(null==n)return!0;if(h.isArray(n)||h.isString(n)||h.isArguments(n))return 0===n.length;for(var t in n)if(h.has(n,t))return!1;return!0},h.isElement=function(n){return!(!n||1!==n.nodeType)},h.isArray=f||function(n){return"[object Array]"===l.call(n)},h.isObject=function(n){var t=typeof n;return"function"===t||"object"===t&&!!n},h.each(["Arguments","Function","String","Number","Date","RegExp"],function(n){h["is"+n]=function(t){return l.call(t)==="[object "+n+"]"}}),h.isArguments(arguments)||(h.isArguments=function(n){return h.has(n,"callee")}),"function"!=typeof/./&&(h.isFunction=function(n){return"function"==typeof n||!1}),h.isFinite=function(n){return isFinite(n)&&!isNaN(parseFloat(n))},h.isNaN=function(n){return h.isNumber(n)&&n!==+n},h.isBoolean=function(n){return n===!0||n===!1||"[object Boolean]"===l.call(n)},h.isNull=function(n){return null===n},h.isUndefined=function(n){return n===void 0},h.has=function(n,t){return null!=n&&c.call(n,t)},h.noConflict=function(){return n._=t,this},h.identity=function(n){return n},h.constant=function(n){return function(){return n}},h.noop=function(){},h.property=function(n){return function(t){return t[n]}},h.matches=function(n){var t=h.pairs(n),r=t.length;return function(n){if(null==n)return!r;n=new Object(n);for(var e=0;r>e;e++){var u=t[e],i=u[0];if(u[1]!==n[i]||!(i in n))return!1}return!0}},h.times=function(n,t,r){var e=Array(Math.max(0,n));t=g(t,r,1);for(var u=0;n>u;u++)e[u]=t(u);return e},h.random=function(n,t){return null==t&&(t=n,n=0),n+Math.floor(Math.random()*(t-n+1))},h.now=Date.now||function(){return(new Date).getTime()};var _={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","`":"&#x60;"},w=h.invert(_),j=function(n){var t=function(t){return n[t]},r="(?:"+h.keys(n).join("|")+")",e=RegExp(r),u=RegExp(r,"g");return function(n){return n=null==n?"":""+n,e.test(n)?n.replace(u,t):n}};h.escape=j(_),h.unescape=j(w),h.result=function(n,t){if(null==n)return void 0;var r=n[t];return h.isFunction(r)?n[t]():r};var x=0;h.uniqueId=function(n){var t=++x+"";return n?n+t:t},h.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var A=/(.)^/,k={"'":"'","\\":"\\","\r":"r","\n":"n","\u2028":"u2028","\u2029":"u2029"},O=/\\|'|\r|\n|\u2028|\u2029/g,F=function(n){return"\\"+k[n]};h.template=function(n,t,r){!t&&r&&(t=r),t=h.defaults({},t,h.templateSettings);var e=RegExp([(t.escape||A).source,(t.interpolate||A).source,(t.evaluate||A).source].join("|")+"|$","g"),u=0,i="__p+='";n.replace(e,function(t,r,e,a,o){return i+=n.slice(u,o).replace(O,F),u=o+t.length,r?i+="'+\n((__t=("+r+"))==null?'':_.escape(__t))+\n'":e?i+="'+\n((__t=("+e+"))==null?'':__t)+\n'":a&&(i+="';\n"+a+"\n__p+='"),t}),i+="';\n",t.variable||(i="with(obj||{}){\n"+i+"}\n"),i="var __t,__p='',__j=Array.prototype.join,"+"print=function(){__p+=__j.call(arguments,'');};\n"+i+"return __p;\n";try{var a=new Function(t.variable||"obj","_",i)}catch(o){throw o.source=i,o}var l=function(n){return a.call(this,n,h)},c=t.variable||"obj";return l.source="function("+c+"){\n"+i+"}",l},h.chain=function(n){var t=h(n);return t._chain=!0,t};var E=function(n){return this._chain?h(n).chain():n};h.mixin=function(n){h.each(h.functions(n),function(t){var r=h[t]=n[t];h.prototype[t]=function(){var n=[this._wrapped];return i.apply(n,arguments),E.call(this,r.apply(h,n))}})},h.mixin(h),h.each(["pop","push","reverse","shift","sort","splice","unshift"],function(n){var t=r[n];h.prototype[n]=function(){var r=this._wrapped;return t.apply(r,arguments),"shift"!==n&&"splice"!==n||0!==r.length||delete r[0],E.call(this,r)}}),h.each(["concat","join","slice"],function(n){var t=r[n];h.prototype[n]=function(){return E.call(this,t.apply(this._wrapped,arguments))}}),h.prototype.value=function(){return this._wrapped},"function"==typeof define&&define.amd&&define("underscore",[],function(){return h})}).call(this);
-//# sourceMappingURL=underscore-min.map
+//# sourceMappingURL=underscore-min.map \ No newline at end of file
diff --git a/catalog-be/src/main/resources/swagger/swagger-ui.js b/catalog-be/src/main/resources/swagger/swagger-ui.js
index 96b6ed7cb6..89939c0ea5 100644
--- a/catalog-be/src/main/resources/swagger/swagger-ui.js
+++ b/catalog-be/src/main/resources/swagger/swagger-ui.js
@@ -1,23 +1,3 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
/**
* swagger-ui - Swagger UI is a dependency-free collection of HTML, JavaScript, and CSS assets that dynamically generate beautiful documentation from a Swagger-compliant API
* @version v2.1.0-M2
@@ -21735,4 +21715,4 @@ SwaggerUi.Views.StatusCodeView = Backbone.View.extend({
}
return this;
}
-});}).call(this);
+});}).call(this); \ No newline at end of file
diff --git a/catalog-be/src/main/resources/swagger/swagger-ui.min.js b/catalog-be/src/main/resources/swagger/swagger-ui.min.js
index 0e21b8852c..1fa9be400c 100644
--- a/catalog-be/src/main/resources/swagger/swagger-ui.min.js
+++ b/catalog-be/src/main/resources/swagger/swagger-ui.min.js
@@ -1,23 +1,3 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
(function(){function e(){e.history=e.history||[],e.history.push(arguments),this.console&&console.log(Array.prototype.slice.call(arguments)[0])}this.Handlebars=this.Handlebars||{},this.Handlebars.templates=this.Handlebars.templates||{},this.Handlebars.templates.apikey_button_view=Handlebars.template({compiler:[6,">= 2.0.0-beta.1"],main:function(e,t,n,r){var i,o="function",a=t.helperMissing,s=this.escapeExpression;return"<!--div class='auth_button' id='apikey_button'><img class='auth_icon' alt='apply api key' src='images/apikey.jpeg'></div-->\n<div class='auth_container' id='apikey_container'>\n <div class='key_input_container'>\n <div class='auth_label'>"+s((i=null!=(i=t.keyName||(null!=e?e.keyName:e))?i:a,typeof i===o?i.call(e,{name:"keyName",hash:{},data:r}):i))+'</div>\n <input placeholder="api_key" class="auth_input" id="input_apiKey_entry" name="apiKey" type="text"/>\n <div class=\'auth_submit\'><a class=\'auth_submit_button\' id="apply_api_key" href="#">apply</a></div>\n </div>\n</div>\n\n'},useData:!0}),this.Handlebars.templates.basic_auth_button_view=Handlebars.template({compiler:[6,">= 2.0.0-beta.1"],main:function(){return'<div class=\'auth_button\' id=\'basic_auth_button\'><img class=\'auth_icon\' src=\'images/password.jpeg\'></div>\n<div class=\'auth_container\' id=\'basic_auth_container\'>\n <div class=\'key_input_container\'>\n <div class="auth_label">Username</div>\n <input placeholder="username" class="auth_input" id="input_username" name="username" type="text"/>\n <div class="auth_label">Password</div>\n <input placeholder="password" class="auth_input" id="input_password" name="password" type="password"/>\n <div class=\'auth_submit\'><a class=\'auth_submit_button\' id="apply_basic_auth" href="#">apply</a></div>\n </div>\n</div>\n\n'},useData:!0}),this.Handlebars.templates.content_type=Handlebars.template({1:function(e,t,n,r){var i,o="";return i=t.each.call(e,null!=e?e.produces:e,{name:"each",hash:{},fn:this.program(2,r),inverse:this.noop,data:r}),null!=i&&(o+=i),o},2:function(e){var t,n=this.lambda,r=' <option value="';return t=n(e,e),null!=t&&(r+=t),r+='">',t=n(e,e),null!=t&&(r+=t),r+"</option>\n"},4:function(){return' <option value="application/json">application/json</option>\n'},compiler:[6,">= 2.0.0-beta.1"],main:function(e,t,n,r){var i,o='<label for="contentType"></label>\n<select name="contentType">\n';return i=t["if"].call(e,null!=e?e.produces:e,{name:"if",hash:{},fn:this.program(1,r),inverse:this.program(4,r),data:r}),null!=i&&(o+=i),o+"</select>\n"},useData:!0}),$(function(){$.fn.vAlign=function(){return this.each(function(){var e=$(this).height(),t=$(this).parent().height(),n=(t-e)/2;$(this).css("margin-top",n)})},$.fn.stretchFormtasticInputWidthToParent=function(){return this.each(function(){var e=$(this).closest("form").innerWidth(),t=parseInt($(this).closest("form").css("padding-left"),10)+parseInt($(this).closest("form").css("padding-right"),10),n=parseInt($(this).css("padding-left"),10)+parseInt($(this).css("padding-right"),10);$(this).css("width",e-t-n)})},$("form.formtastic li.string input, form.formtastic textarea").stretchFormtasticInputWidthToParent(),$("ul.downplayed li div.content p").vAlign(),$("form.sandbox").submit(function(){var e=!0;return $(this).find("input.required").each(function(){$(this).removeClass("error"),""===$(this).val()&&($(this).addClass("error"),$(this).wiggle(),e=!1)}),e})}),Function.prototype.bind&&console&&"object"==typeof console.log&&["log","info","warn","error","assert","dir","clear","profile","profileEnd"].forEach(function(e){console[e]=this.bind(console[e],console)},Function.prototype.call),window.Docs={shebang:function(){var e=$.param.fragment().split("/");switch(e.shift(),e.length){case 1:var t="resource_"+e[0];Docs.expandEndpointListForResource(e[0]),$("#"+t).slideto({highlight:!1});break;case 2:Docs.expandEndpointListForResource(e[0]),$("#"+t).slideto({highlight:!1});var n=e.join("_"),r=n+"_content";Docs.expandOperation($("#"+r)),$("#"+n).slideto({highlight:!1})}},toggleEndpointListForResource:function(e){var t=$("li#resource_"+Docs.escapeResourceName(e)+" ul.endpoints");t.is(":visible")?Docs.collapseEndpointListForResource(e):Docs.expandEndpointListForResource(e)},expandEndpointListForResource:function(e){var e=Docs.escapeResourceName(e);if(""==e)return void $(".resource ul.endpoints").slideDown();$("li#resource_"+e).addClass("active");var t=$("li#resource_"+e+" ul.endpoints");t.slideDown()},collapseEndpointListForResource:function(e){var e=Docs.escapeResourceName(e);if(""==e)return void $(".resource ul.endpoints").slideUp();$("li#resource_"+e).removeClass("active");var t=$("li#resource_"+e+" ul.endpoints");t.slideUp()},expandOperationsForResource:function(e){return Docs.expandEndpointListForResource(e),""==e?void $(".resource ul.endpoints li.operation div.content").slideDown():void $("li#resource_"+Docs.escapeResourceName(e)+" li.operation div.content").each(function(){Docs.expandOperation($(this))})},collapseOperationsForResource:function(e){return Docs.expandEndpointListForResource(e),""==e?void $(".resource ul.endpoints li.operation div.content").slideUp():void $("li#resource_"+Docs.escapeResourceName(e)+" li.operation div.content").each(function(){Docs.collapseOperation($(this))})},escapeResourceName:function(e){return e.replace(/[!"#$%&'()*+,.\/:;<=>?@\[\\\]\^`{|}~]/g,"\\$&")},expandOperation:function(e){e.slideDown()},collapseOperation:function(e){e.slideUp()}},Handlebars.registerHelper("sanitize",function(e){return e=e.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,""),new Handlebars.SafeString(e)}),this.Handlebars.templates.main=Handlebars.template({1:function(e,t,n,r){var i,o=this.lambda,a=this.escapeExpression,s=' <div class="info_title">'+a(o(null!=(i=null!=e?e.info:e)?i.title:i,e))+'</div>\n <div class="info_description markdown">';return i=o(null!=(i=null!=e?e.info:e)?i.description:i,e),null!=i&&(s+=i),s+="</div>\n",i=t["if"].call(e,null!=e?e.externalDocs:e,{name:"if",hash:{},fn:this.program(2,r),inverse:this.noop,data:r}),null!=i&&(s+=i),s+=" ",i=t["if"].call(e,null!=(i=null!=e?e.info:e)?i.termsOfServiceUrl:i,{name:"if",hash:{},fn:this.program(4,r),inverse:this.noop,data:r}),null!=i&&(s+=i),s+="\n ",i=t["if"].call(e,null!=(i=null!=(i=null!=e?e.info:e)?i.contact:i)?i.name:i,{name:"if",hash:{},fn:this.program(6,r),inverse:this.noop,data:r}),null!=i&&(s+=i),s+="\n ",i=t["if"].call(e,null!=(i=null!=(i=null!=e?e.info:e)?i.contact:i)?i.url:i,{name:"if",hash:{},fn:this.program(8,r),inverse:this.noop,data:r}),null!=i&&(s+=i),s+="\n ",i=t["if"].call(e,null!=(i=null!=(i=null!=e?e.info:e)?i.contact:i)?i.email:i,{name:"if",hash:{},fn:this.program(10,r),inverse:this.noop,data:r}),null!=i&&(s+=i),s+="\n ",i=t["if"].call(e,null!=(i=null!=e?e.info:e)?i.license:i,{name:"if",hash:{},fn:this.program(12,r),inverse:this.noop,data:r}),null!=i&&(s+=i),s+"\n"},2:function(e){var t,n=this.lambda,r=this.escapeExpression;return" <h5>More documentations</h5>\n <p>"+r(n(null!=(t=null!=e?e.externalDocs:e)?t.description:t,e))+'</p>\n <a href="'+r(n(null!=(t=null!=e?e.externalDocs:e)?t.url:t,e))+'" target="_blank">'+r(n(null!=(t=null!=e?e.externalDocs:e)?t.url:t,e))+"</a>\n"},4:function(e){var t,n=this.lambda,r=this.escapeExpression;return'<div class="info_tos"><a href="'+r(n(null!=(t=null!=e?e.info:e)?t.termsOfServiceUrl:t,e))+'">Terms of service</a></div>'},6:function(e){var t,n=this.lambda,r=this.escapeExpression;return"<div class='info_name'>Created by "+r(n(null!=(t=null!=(t=null!=e?e.info:e)?t.contact:t)?t.name:t,e))+"</div>"},8:function(e){var t,n=this.lambda,r=this.escapeExpression;return"<div class='info_url'>See more at <a href=\""+r(n(null!=(t=null!=(t=null!=e?e.info:e)?t.contact:t)?t.url:t,e))+'">'+r(n(null!=(t=null!=(t=null!=e?e.info:e)?t.contact:t)?t.url:t,e))+"</a></div>"},10:function(e){var t,n=this.lambda,r=this.escapeExpression;return"<div class='info_email'><a href=\"mailto:"+r(n(null!=(t=null!=(t=null!=e?e.info:e)?t.contact:t)?t.email:t,e))+"?subject="+r(n(null!=(t=null!=e?e.info:e)?t.title:t,e))+'">Contact the developer</a></div>'},12:function(e){var t,n=this.lambda,r=this.escapeExpression;return"<div class='info_license'><a href='"+r(n(null!=(t=null!=(t=null!=e?e.info:e)?t.license:t)?t.url:t,e))+"'>"+r(n(null!=(t=null!=(t=null!=e?e.info:e)?t.license:t)?t.name:t,e))+"</a></div>"},14:function(e){var t,n=this.lambda,r=this.escapeExpression;return' , <span style="font-variant: small-caps">api version</span>: '+r(n(null!=(t=null!=e?e.info:e)?t.version:t,e))+"\n "},16:function(e,t,n,r){var i,o="function",a=t.helperMissing,s=this.escapeExpression;return' <span style="float:right"><a href="'+s((i=null!=(i=t.validatorUrl||(null!=e?e.validatorUrl:e))?i:a,typeof i===o?i.call(e,{name:"validatorUrl",hash:{},data:r}):i))+"/debug?url="+s((i=null!=(i=t.url||(null!=e?e.url:e))?i:a,typeof i===o?i.call(e,{name:"url",hash:{},data:r}):i))+'"><img id="validator" src="'+s((i=null!=(i=t.validatorUrl||(null!=e?e.validatorUrl:e))?i:a,typeof i===o?i.call(e,{name:"validatorUrl",hash:{},data:r}):i))+"?url="+s((i=null!=(i=t.url||(null!=e?e.url:e))?i:a,typeof i===o?i.call(e,{name:"url",hash:{},data:r}):i))+'"></a>\n </span>\n'},compiler:[6,">= 2.0.0-beta.1"],main:function(e,t,n,r){var i,o,a="function",s=t.helperMissing,l=this.escapeExpression,u="<div class='info' id='api_info'>\n";return i=t["if"].call(e,null!=e?e.info:e,{name:"if",hash:{},fn:this.program(1,r),inverse:this.noop,data:r}),null!=i&&(u+=i),u+="</div>\n<div class='container' id='resources_container'>\n <ul id='resources'></ul>\n\n <div class=\"footer\">\n <br>\n <br>\n <h4 style=\"color: #999\">[ <span style=\"font-variant: small-caps\">base url</span>: "+l((o=null!=(o=t.basePath||(null!=e?e.basePath:e))?o:s,typeof o===a?o.call(e,{name:"basePath",hash:{},data:r}):o))+"\n",i=t["if"].call(e,null!=(i=null!=e?e.info:e)?i.version:i,{name:"if",hash:{},fn:this.program(14,r),inverse:this.noop,data:r}),null!=i&&(u+=i),u+="]\n",i=t["if"].call(e,null!=e?e.validatorUrl:e,{name:"if",hash:{},fn:this.program(16,r),inverse:this.noop,data:r}),null!=i&&(u+=i),u+" </h4>\n </div>\n</div>\n"},useData:!0}),this.Handlebars.templates.operation=Handlebars.template({1:function(){return"deprecated"},3:function(){return" <h4>Warning: Deprecated</h4>\n"},5:function(e,t,n,r){var i,o,a="function",s=t.helperMissing,l=' <h4>Implementation Notes</h4>\n <div class="markdown">';return o=null!=(o=t.description||(null!=e?e.description:e))?o:s,i=typeof o===a?o.call(e,{name:"description",hash:{},data:r}):o,null!=i&&(l+=i),l+"</div>\n"},7:function(){return' <div class="auth">\n <span class="api-ic ic-error"></span>'},9:function(e,t,n,r){var i,o=' <div id="api_information_panel" style="top: 526px; left: 776px; display: none;">\n';return i=t.each.call(e,e,{name:"each",hash:{},fn:this.program(10,r),inverse:this.noop,data:r}),null!=i&&(o+=i),o+" </div>\n"},10:function(e){var t,n=this.lambda,r=this.escapeExpression,i=" <div title='";return t=n(null!=e?e.description:e,e),null!=t&&(i+=t),i+"'>"+r(n(null!=e?e.scope:e,e))+"</div>\n"},12:function(){return"</div>"},14:function(){return' <div class=\'access\'>\n <span class="api-ic ic-off" title="click to authenticate"></span>\n </div>\n'},16:function(e,t,n,r){var i,o="function",a=t.helperMissing,s=this.escapeExpression;return" <h4>Response Class (Status "+s((i=null!=(i=t.successCode||(null!=e?e.successCode:e))?i:a,typeof i===o?i.call(e,{name:"successCode",hash:{},data:r}):i))+')</h4>\n <p><span class="model-signature" /></p>\n <br/>\n <div class="response-content-type" />\n'},18:function(){return' <h4>Parameters</h4>\n <table class=\'fullwidth\'>\n <thead>\n <tr>\n <th style="width: 100px; max-width: 100px">Parameter</th>\n <th style="width: 310px; max-width: 310px">Value</th>\n <th style="width: 200px; max-width: 200px">Description</th>\n <th style="width: 100px; max-width: 100px">Parameter Type</th>\n <th style="width: 220px; max-width: 230px">Data Type</th>\n </tr>\n </thead>\n <tbody class="operation-params">\n\n </tbody>\n </table>\n'},20:function(){return" <div style='margin:0;padding:0;display:inline'></div>\n <h4>Response Messages</h4>\n <table class='fullwidth'>\n <thead>\n <tr>\n <th>HTTP Status Code</th>\n <th>Reason</th>\n <th>Response Model</th>\n <th>Headers</th>\n </tr>\n </thead>\n <tbody class=\"operation-status\">\n\n </tbody>\n </table>\n"},22:function(){return""},24:function(){return" <div class='sandbox_header'>\n <input class='submit' name='commit' type='button' value='Try it out!' />\n <a href='#' class='response_hider' style='display:none'>Hide Response</a>\n <span class='response_throbber' style='display:none'></span>\n </div>\n"},compiler:[6,">= 2.0.0-beta.1"],main:function(e,t,n,r){var i,o,a,s="function",l=t.helperMissing,u=this.escapeExpression,c=t.blockHelperMissing,p="\n <ul class='operations' >\n <li class='"+u((o=null!=(o=t.method||(null!=e?e.method:e))?o:l,typeof o===s?o.call(e,{name:"method",hash:{},data:r}):o))+" operation' id='"+u((o=null!=(o=t.parentId||(null!=e?e.parentId:e))?o:l,typeof o===s?o.call(e,{name:"parentId",hash:{},data:r}):o))+"_"+u((o=null!=(o=t.nickname||(null!=e?e.nickname:e))?o:l,typeof o===s?o.call(e,{name:"nickname",hash:{},data:r}):o))+"'>\n <div class='heading'>\n <h3>\n <span class='http_method'>\n <a href='#!/"+u((o=null!=(o=t.encodedParentId||(null!=e?e.encodedParentId:e))?o:l,typeof o===s?o.call(e,{name:"encodedParentId",hash:{},data:r}):o))+"/"+u((o=null!=(o=t.nickname||(null!=e?e.nickname:e))?o:l,typeof o===s?o.call(e,{name:"nickname",hash:{},data:r}):o))+'\' class="toggleOperation">'+u((o=null!=(o=t.method||(null!=e?e.method:e))?o:l,typeof o===s?o.call(e,{name:"method",hash:{},data:r}):o))+"</a>\n </span>\n <span class='path'>\n <a href='#!/"+u((o=null!=(o=t.encodedParentId||(null!=e?e.encodedParentId:e))?o:l,typeof o===s?o.call(e,{name:"encodedParentId",hash:{},data:r}):o))+"/"+u((o=null!=(o=t.nickname||(null!=e?e.nickname:e))?o:l,typeof o===s?o.call(e,{name:"nickname",hash:{},data:r}):o))+"' class=\"toggleOperation ";return i=t["if"].call(e,null!=e?e.deprecated:e,{name:"if",hash:{},fn:this.program(1,r),inverse:this.noop,data:r}),null!=i&&(p+=i),p+='">'+u((o=null!=(o=t.path||(null!=e?e.path:e))?o:l,typeof o===s?o.call(e,{name:"path",hash:{},data:r}):o))+"</a>\n </span>\n </h3>\n <ul class='options'>\n <li>\n <a href='#!/"+u((o=null!=(o=t.encodedParentId||(null!=e?e.encodedParentId:e))?o:l,typeof o===s?o.call(e,{name:"encodedParentId",hash:{},data:r}):o))+"/"+u((o=null!=(o=t.nickname||(null!=e?e.nickname:e))?o:l,typeof o===s?o.call(e,{name:"nickname",hash:{},data:r}):o))+'\' class="toggleOperation">',o=null!=(o=t.summary||(null!=e?e.summary:e))?o:l,i=typeof o===s?o.call(e,{name:"summary",hash:{},data:r}):o,null!=i&&(p+=i),p+="</a>\n </li>\n </ul>\n </div>\n <div class='content' id='"+u((o=null!=(o=t.parentId||(null!=e?e.parentId:e))?o:l,typeof o===s?o.call(e,{name:"parentId",hash:{},data:r}):o))+"_"+u((o=null!=(o=t.nickname||(null!=e?e.nickname:e))?o:l,typeof o===s?o.call(e,{name:"nickname",hash:{},data:r}):o))+"_content' style='display:none'>\n",i=t["if"].call(e,null!=e?e.deprecated:e,{name:"if",hash:{},fn:this.program(3,r),inverse:this.noop,data:r}),null!=i&&(p+=i),i=t["if"].call(e,null!=e?e.description:e,{name:"if",hash:{},fn:this.program(5,r),inverse:this.noop,data:r}),null!=i&&(p+=i),o=null!=(o=t.oauth||(null!=e?e.oauth:e))?o:l,a={name:"oauth",hash:{},fn:this.program(7,r),inverse:this.noop,data:r},i=typeof o===s?o.call(e,a):o,t.oauth||(i=c.call(e,i,a)),null!=i&&(p+=i),p+="\n",i=t.each.call(e,null!=e?e.oauth:e,{name:"each",hash:{},fn:this.program(9,r),inverse:this.noop,data:r}),null!=i&&(p+=i),p+=" ",o=null!=(o=t.oauth||(null!=e?e.oauth:e))?o:l,a={name:"oauth",hash:{},fn:this.program(12,r),inverse:this.noop,data:r},i=typeof o===s?o.call(e,a):o,t.oauth||(i=c.call(e,i,a)),null!=i&&(p+=i),p+="\n",o=null!=(o=t.oauth||(null!=e?e.oauth:e))?o:l,a={name:"oauth",hash:{},fn:this.program(14,r),inverse:this.noop,data:r},i=typeof o===s?o.call(e,a):o,t.oauth||(i=c.call(e,i,a)),null!=i&&(p+=i),i=t["if"].call(e,null!=e?e.type:e,{name:"if",hash:{},fn:this.program(16,r),inverse:this.noop,data:r}),null!=i&&(p+=i),p+=" <form accept-charset='UTF-8' class='sandbox'>\n <div style='margin:0;padding:0;display:inline'></div>\n",i=t["if"].call(e,null!=e?e.parameters:e,{name:"if",hash:{},fn:this.program(18,r),inverse:this.noop,data:r}),null!=i&&(p+=i),i=t["if"].call(e,null!=e?e.responseMessages:e,{name:"if",hash:{},fn:this.program(20,r),inverse:this.noop,data:r}),null!=i&&(p+=i),i=t["if"].call(e,null!=e?e.isReadOnly:e,{name:"if",hash:{},fn:this.program(22,r),inverse:this.program(24,r),data:r}),null!=i&&(p+=i),p+" </form>\n <div class='response' style='display:none'>\n <h4>Request URL</h4>\n <div class='block request_url'></div>\n <h4>Response Body</h4>\n <div class='block response_body'></div>\n <h4>Response Code</h4>\n <div class='block response_code'></div>\n <h4>Response Headers</h4>\n <div class='block response_headers'></div>\n </div>\n </div>\n </li>\n </ul>\n"},useData:!0}),this.Handlebars.templates.param_list=Handlebars.template({1:function(e,t,n,r){var i,o="function",a=t.helperMissing,s=this.escapeExpression;return"<td class='code required'>"+s((i=null!=(i=t.name||(null!=e?e.name:e))?i:a,typeof i===o?i.call(e,{name:"name",hash:{},data:r}):i))+"</td>\n"},3:function(){return" multiple='multiple'"},5:function(){return""},7:function(e,t,n,r){var i,o="";return i=t["if"].call(e,null!=e?e["default"]:e,{name:"if",hash:{},fn:this.program(5,r),inverse:this.program(8,r),data:r}),null!=i&&(o+=i),o},8:function(e,t,n,r){var i,o=t.helperMissing,a="";return i=(t.isArray||e&&e.isArray||o).call(e,e,{name:"isArray",hash:{},fn:this.program(5,r),inverse:this.program(9,r),data:r}),null!=i&&(a+=i),a},9:function(){return" <option selected=\"\" value=''></option>\n"},11:function(e,t,n,r){var i,o="";return i=t["if"].call(e,null!=e?e.isDefault:e,{name:"if",hash:{},fn:this.program(12,r),inverse:this.program(14,r),data:r}),null!=i&&(o+=i),o},12:function(e,t,n,r){var i,o="function",a=t.helperMissing,s=this.escapeExpression;return' <option selected="" value=\''+s((i=null!=(i=t.value||(null!=e?e.value:e))?i:a,typeof i===o?i.call(e,{name:"value",hash:{},data:r}):i))+"'>"+s((i=null!=(i=t.value||(null!=e?e.value:e))?i:a,typeof i===o?i.call(e,{name:"value",hash:{},data:r}):i))+" (default)</option>\n"},14:function(e,t,n,r){var i,o="function",a=t.helperMissing,s=this.escapeExpression;return" <option value='"+s((i=null!=(i=t.value||(null!=e?e.value:e))?i:a,typeof i===o?i.call(e,{name:"value",hash:{},data:r}):i))+"'>"+s((i=null!=(i=t.value||(null!=e?e.value:e))?i:a,typeof i===o?i.call(e,{name:"value",hash:{},data:r}):i))+"</option>\n"},compiler:[6,">= 2.0.0-beta.1"],main:function(e,t,n,r){var i,o,a="function",s=t.helperMissing,l=this.escapeExpression,u="";return i=t["if"].call(e,null!=e?e.required:e,{name:"if",hash:{},fn:this.program(1,r),inverse:this.noop,data:r}),null!=i&&(u+=i),u+="<td class='code'>"+l((o=null!=(o=t.name||(null!=e?e.name:e))?o:s,typeof o===a?o.call(e,{name:"name",hash:{},data:r}):o))+"</td>\n<td>\n <select ",i=(t.isArray||e&&e.isArray||s).call(e,e,{name:"isArray",hash:{},fn:this.program(3,r),inverse:this.noop,data:r}),null!=i&&(u+=i),u+=" class='parameter' name='"+l((o=null!=(o=t.name||(null!=e?e.name:e))?o:s,typeof o===a?o.call(e,{name:"name",hash:{},data:r}):o))+"'>\n",i=t["if"].call(e,null!=e?e.required:e,{name:"if",hash:{},fn:this.program(5,r),inverse:this.program(7,r),data:r}),null!=i&&(u+=i),i=t.each.call(e,null!=(i=null!=e?e.allowableValues:e)?i.descriptiveValues:i,{name:"each",hash:{},fn:this.program(11,r),inverse:this.noop,data:r}),null!=i&&(u+=i),u+=' </select>\n</td>\n<td class="markdown">',o=null!=(o=t.description||(null!=e?e.description:e))?o:s,i=typeof o===a?o.call(e,{name:"description",hash:{},data:r}):o,null!=i&&(u+=i),u+="</td>\n<td>",o=null!=(o=t.paramType||(null!=e?e.paramType:e))?o:s,i=typeof o===a?o.call(e,{name:"paramType",hash:{},data:r}):o,null!=i&&(u+=i),u+'</td>\n<td><span class="model-signature"></span></td>'},useData:!0}),this.Handlebars.templates.param_readonly_required=Handlebars.template({1:function(e,t,n,r){var i,o="function",a=t.helperMissing,s=this.escapeExpression;return" <textarea class='body-textarea' readonly='readonly' placeholder='(required)' name='"+s((i=null!=(i=t.name||(null!=e?e.name:e))?i:a,typeof i===o?i.call(e,{name:"name",hash:{},data:r}):i))+"'>"+s((i=null!=(i=t["default"]||(null!=e?e["default"]:e))?i:a,typeof i===o?i.call(e,{name:"default",hash:{},data:r}):i))+"</textarea>\n"},3:function(e,t,n,r){var i,o="";return i=t["if"].call(e,null!=e?e["default"]:e,{name:"if",hash:{},fn:this.program(4,r),inverse:this.program(6,r),data:r}),null!=i&&(o+=i),o},4:function(e,t,n,r){var i,o="function",a=t.helperMissing,s=this.escapeExpression;return" "+s((i=null!=(i=t["default"]||(null!=e?e["default"]:e))?i:a,typeof i===o?i.call(e,{name:"default",hash:{},data:r}):i))+"\n"},6:function(){return" (empty)\n"},compiler:[6,">= 2.0.0-beta.1"],main:function(e,t,n,r){var i,o,a="function",s=t.helperMissing,l=this.escapeExpression,u="<td class='code required'>"+l((o=null!=(o=t.name||(null!=e?e.name:e))?o:s,typeof o===a?o.call(e,{name:"name",hash:{},data:r}):o))+"</td>\n<td>\n";return i=t["if"].call(e,null!=e?e.isBody:e,{name:"if",hash:{},fn:this.program(1,r),inverse:this.program(3,r),data:r}),null!=i&&(u+=i),u+='</td>\n<td class="markdown">',o=null!=(o=t.description||(null!=e?e.description:e))?o:s,i=typeof o===a?o.call(e,{name:"description",hash:{},data:r}):o,null!=i&&(u+=i),u+="</td>\n<td>",o=null!=(o=t.paramType||(null!=e?e.paramType:e))?o:s,i=typeof o===a?o.call(e,{name:"paramType",hash:{},data:r}):o,null!=i&&(u+=i),u+'</td>\n<td><span class="model-signature"></span></td>\n'},useData:!0}),this.Handlebars.templates.param_readonly=Handlebars.template({1:function(e,t,n,r){var i,o="function",a=t.helperMissing,s=this.escapeExpression;return" <textarea class='body-textarea' readonly='readonly' name='"+s((i=null!=(i=t.name||(null!=e?e.name:e))?i:a,typeof i===o?i.call(e,{name:"name",hash:{},data:r}):i))+"'>"+s((i=null!=(i=t["default"]||(null!=e?e["default"]:e))?i:a,typeof i===o?i.call(e,{name:"default",hash:{},data:r}):i))+"</textarea>\n"},3:function(e,t,n,r){var i,o="";return i=t["if"].call(e,null!=e?e["default"]:e,{name:"if",hash:{},fn:this.program(4,r),inverse:this.program(6,r),data:r}),null!=i&&(o+=i),o},4:function(e,t,n,r){var i,o="function",a=t.helperMissing,s=this.escapeExpression;return" "+s((i=null!=(i=t["default"]||(null!=e?e["default"]:e))?i:a,typeof i===o?i.call(e,{name:"default",hash:{},data:r}):i))+"\n"},6:function(){return" (empty)\n"},compiler:[6,">= 2.0.0-beta.1"],main:function(e,t,n,r){var i,o,a="function",s=t.helperMissing,l=this.escapeExpression,u="<td class='code'>"+l((o=null!=(o=t.name||(null!=e?e.name:e))?o:s,typeof o===a?o.call(e,{name:"name",hash:{},data:r}):o))+"</td>\n<td>\n";return i=t["if"].call(e,null!=e?e.isBody:e,{name:"if",hash:{},fn:this.program(1,r),inverse:this.program(3,r),data:r}),null!=i&&(u+=i),u+='</td>\n<td class="markdown">',o=null!=(o=t.description||(null!=e?e.description:e))?o:s,i=typeof o===a?o.call(e,{name:"description",hash:{},data:r}):o,null!=i&&(u+=i),u+="</td>\n<td>",o=null!=(o=t.paramType||(null!=e?e.paramType:e))?o:s,i=typeof o===a?o.call(e,{name:"paramType",hash:{},data:r}):o,null!=i&&(u+=i),u+'</td>\n<td><span class="model-signature"></span></td>\n'},useData:!0}),this.Handlebars.templates.param_required=Handlebars.template({1:function(e,t,n,r){var i,o="";return i=t["if"].call(e,null!=e?e.isFile:e,{name:"if",hash:{},fn:this.program(2,r),inverse:this.program(4,r),data:r}),null!=i&&(o+=i),o},2:function(e,t,n,r){var i,o="function",a=t.helperMissing,s=this.escapeExpression;return' <input type="file" name=\''+s((i=null!=(i=t.name||(null!=e?e.name:e))?i:a,typeof i===o?i.call(e,{name:"name",hash:{},data:r}):i))+"'/>\n"},4:function(e,t,n,r){var i,o="";return i=t["if"].call(e,null!=e?e["default"]:e,{name:"if",hash:{},fn:this.program(5,r),inverse:this.program(7,r),data:r}),null!=i&&(o+=i),o},5:function(e,t,n,r){var i,o="function",a=t.helperMissing,s=this.escapeExpression;return" <textarea class='body-textarea required' placeholder='(required)' name='"+s((i=null!=(i=t.name||(null!=e?e.name:e))?i:a,typeof i===o?i.call(e,{name:"name",hash:{},data:r}):i))+"'>"+s((i=null!=(i=t["default"]||(null!=e?e["default"]:e))?i:a,typeof i===o?i.call(e,{name:"default",hash:{},data:r}):i))+'</textarea>\n <br />\n <div class="parameter-content-type" />\n'},7:function(e,t,n,r){var i,o="function",a=t.helperMissing,s=this.escapeExpression;return" <textarea class='body-textarea required' placeholder='(required)' name='"+s((i=null!=(i=t.name||(null!=e?e.name:e))?i:a,typeof i===o?i.call(e,{name:"name",hash:{},data:r}):i))+'\'></textarea>\n <br />\n <div class="parameter-content-type" />\n'},9:function(e,t,n,r){var i,o="";return i=t["if"].call(e,null!=e?e.isFile:e,{name:"if",hash:{},fn:this.program(10,r),inverse:this.program(12,r),data:r}),null!=i&&(o+=i),o},10:function(e,t,n,r){var i,o="function",a=t.helperMissing,s=this.escapeExpression;return" <input class='parameter' class='required' type='file' name='"+s((i=null!=(i=t.name||(null!=e?e.name:e))?i:a,typeof i===o?i.call(e,{name:"name",hash:{},data:r}):i))+"'/>\n"},12:function(e,t,n,r){var i,o="";return i=t["if"].call(e,null!=e?e["default"]:e,{name:"if",hash:{},fn:this.program(13,r),inverse:this.program(15,r),data:r}),null!=i&&(o+=i),o},13:function(e,t,n,r){var i,o="function",a=t.helperMissing,s=this.escapeExpression;return" <input class='parameter required' minlength='1' name='"+s((i=null!=(i=t.name||(null!=e?e.name:e))?i:a,typeof i===o?i.call(e,{name:"name",hash:{},data:r}):i))+"' placeholder='(required)' type='text' value='"+s((i=null!=(i=t["default"]||(null!=e?e["default"]:e))?i:a,typeof i===o?i.call(e,{name:"default",hash:{},data:r}):i))+"'/>\n"},15:function(e,t,n,r){var i,o="function",a=t.helperMissing,s=this.escapeExpression;return" <input class='parameter required' minlength='1' name='"+s((i=null!=(i=t.name||(null!=e?e.name:e))?i:a,typeof i===o?i.call(e,{name:"name",hash:{},data:r}):i))+"' placeholder='(required)' type='text' value=''/>\n"},compiler:[6,">= 2.0.0-beta.1"],main:function(e,t,n,r){var i,o,a="function",s=t.helperMissing,l=this.escapeExpression,u="<td class='code required'>"+l((o=null!=(o=t.name||(null!=e?e.name:e))?o:s,typeof o===a?o.call(e,{name:"name",hash:{},data:r}):o))+"</td>\n<td>\n";return i=t["if"].call(e,null!=e?e.isBody:e,{name:"if",hash:{},fn:this.program(1,r),inverse:this.program(9,r),data:r}),null!=i&&(u+=i),u+='</td>\n<td>\n <strong><span class="markdown">',o=null!=(o=t.description||(null!=e?e.description:e))?o:s,i=typeof o===a?o.call(e,{name:"description",hash:{},data:r}):o,null!=i&&(u+=i),u+="</span></strong>\n</td>\n<td>",o=null!=(o=t.paramType||(null!=e?e.paramType:e))?o:s,i=typeof o===a?o.call(e,{name:"paramType",hash:{},data:r}):o,null!=i&&(u+=i),u+'</td>\n<td><span class="model-signature"></span></td>\n'},useData:!0}),this.Handlebars.templates.param=Handlebars.template({1:function(e,t,n,r){var i,o="";return i=t["if"].call(e,null!=e?e.isFile:e,{name:"if",hash:{},fn:this.program(2,r),inverse:this.program(4,r),data:r}),null!=i&&(o+=i),o},2:function(e,t,n,r){var i,o="function",a=t.helperMissing,s=this.escapeExpression;return' <input type="file" name=\''+s((i=null!=(i=t.name||(null!=e?e.name:e))?i:a,typeof i===o?i.call(e,{name:"name",hash:{},data:r}):i))+'\'/>\n <div class="parameter-content-type" />\n'},4:function(e,t,n,r){var i,o="";return i=t["if"].call(e,null!=e?e["default"]:e,{name:"if",hash:{},fn:this.program(5,r),inverse:this.program(7,r),data:r}),null!=i&&(o+=i),o},5:function(e,t,n,r){var i,o="function",a=t.helperMissing,s=this.escapeExpression;return" <textarea class='body-textarea' name='"+s((i=null!=(i=t.name||(null!=e?e.name:e))?i:a,typeof i===o?i.call(e,{name:"name",hash:{},data:r}):i))+"'>"+s((i=null!=(i=t["default"]||(null!=e?e["default"]:e))?i:a,typeof i===o?i.call(e,{name:"default",hash:{},data:r}):i))+'</textarea>\n <br />\n <div class="parameter-content-type" />\n'},7:function(e,t,n,r){var i,o="function",a=t.helperMissing,s=this.escapeExpression;return" <textarea class='body-textarea' name='"+s((i=null!=(i=t.name||(null!=e?e.name:e))?i:a,typeof i===o?i.call(e,{name:"name",hash:{},data:r}):i))+'\'></textarea>\n <br />\n <div class="parameter-content-type" />\n'},9:function(e,t,n,r){var i,o="";return i=t["if"].call(e,null!=e?e.isFile:e,{name:"if",hash:{},fn:this.program(2,r),inverse:this.program(10,r),data:r}),null!=i&&(o+=i),o},10:function(e,t,n,r){var i,o="";return i=t["if"].call(e,null!=e?e["default"]:e,{name:"if",hash:{},fn:this.program(11,r),inverse:this.program(13,r),data:r}),null!=i&&(o+=i),o},11:function(e,t,n,r){var i,o="function",a=t.helperMissing,s=this.escapeExpression;return" <input class='parameter' minlength='0' name='"+s((i=null!=(i=t.name||(null!=e?e.name:e))?i:a,typeof i===o?i.call(e,{name:"name",hash:{},data:r}):i))+"' placeholder='' type='text' value='"+s((i=null!=(i=t["default"]||(null!=e?e["default"]:e))?i:a,typeof i===o?i.call(e,{name:"default",hash:{},data:r}):i))+"'/>\n"},13:function(e,t,n,r){var i,o="function",a=t.helperMissing,s=this.escapeExpression;return" <input class='parameter' minlength='0' name='"+s((i=null!=(i=t.name||(null!=e?e.name:e))?i:a,typeof i===o?i.call(e,{name:"name",hash:{},data:r}):i))+"' placeholder='' type='text' value=''/>\n"},compiler:[6,">= 2.0.0-beta.1"],main:function(e,t,n,r){var i,o,a="function",s=t.helperMissing,l=this.escapeExpression,u="<td class='code'>"+l((o=null!=(o=t.name||(null!=e?e.name:e))?o:s,typeof o===a?o.call(e,{name:"name",hash:{},data:r}):o))+"</td>\n<td>\n\n";return i=t["if"].call(e,null!=e?e.isBody:e,{name:"if",hash:{},fn:this.program(1,r),inverse:this.program(9,r),data:r}),null!=i&&(u+=i),u+='\n</td>\n<td class="markdown">',o=null!=(o=t.description||(null!=e?e.description:e))?o:s,i=typeof o===a?o.call(e,{name:"description",hash:{},data:r}):o,null!=i&&(u+=i),u+="</td>\n<td>",o=null!=(o=t.paramType||(null!=e?e.paramType:e))?o:s,i=typeof o===a?o.call(e,{name:"paramType",hash:{},data:r}):o,null!=i&&(u+=i),u+'</td>\n<td>\n <span class="model-signature"></span>\n</td>\n'},useData:!0}),this.Handlebars.templates.parameter_content_type=Handlebars.template({1:function(e,t,n,r){var i,o="";return i=t.each.call(e,null!=e?e.consumes:e,{name:"each",hash:{},fn:this.program(2,r),inverse:this.noop,data:r}),null!=i&&(o+=i),o},2:function(e){var t,n=this.lambda,r=' <option value="';return t=n(e,e),null!=t&&(r+=t),r+='">',t=n(e,e),null!=t&&(r+=t),r+"</option>\n"},4:function(){return' <option value="application/json">application/json</option>\n'},compiler:[6,">= 2.0.0-beta.1"],main:function(e,t,n,r){var i,o='<label for="parameterContentType"></label>\n<select name="parameterContentType">\n';return i=t["if"].call(e,null!=e?e.consumes:e,{name:"if",hash:{},fn:this.program(1,r),inverse:this.program(4,r),data:r}),null!=i&&(o+=i),o+"</select>\n"},useData:!0}),this.Handlebars.templates.resource=Handlebars.template({1:function(){return" : "},3:function(e,t,n,r){var i,o="function",a=t.helperMissing,s=this.escapeExpression;return" <li>\n <a href='"+s((i=null!=(i=t.url||(null!=e?e.url:e))?i:a,typeof i===o?i.call(e,{name:"url",hash:{},data:r}):i))+"'>Raw</a>\n </li>\n"
},compiler:[6,">= 2.0.0-beta.1"],main:function(e,t,n,r){var i,o,a,s="function",l=t.helperMissing,u=this.escapeExpression,c=t.blockHelperMissing,p="<div class='heading'>\n <h2>\n <a href='#!/"+u((o=null!=(o=t.id||(null!=e?e.id:e))?o:l,typeof o===s?o.call(e,{name:"id",hash:{},data:r}):o))+'\' class="toggleEndpointList" data-id="'+u((o=null!=(o=t.id||(null!=e?e.id:e))?o:l,typeof o===s?o.call(e,{name:"id",hash:{},data:r}):o))+'">'+u((o=null!=(o=t.name||(null!=e?e.name:e))?o:l,typeof o===s?o.call(e,{name:"name",hash:{},data:r}):o))+"</a> ";return o=null!=(o=t.summary||(null!=e?e.summary:e))?o:l,a={name:"summary",hash:{},fn:this.program(1,r),inverse:this.noop,data:r},i=typeof o===s?o.call(e,a):o,t.summary||(i=c.call(e,i,a)),null!=i&&(p+=i),o=null!=(o=t.summary||(null!=e?e.summary:e))?o:l,i=typeof o===s?o.call(e,{name:"summary",hash:{},data:r}):o,null!=i&&(p+=i),p+="\n </h2>\n <ul class='options'>\n <li>\n <a href='#!/"+u((o=null!=(o=t.id||(null!=e?e.id:e))?o:l,typeof o===s?o.call(e,{name:"id",hash:{},data:r}):o))+"' id='endpointListTogger_"+u((o=null!=(o=t.id||(null!=e?e.id:e))?o:l,typeof o===s?o.call(e,{name:"id",hash:{},data:r}):o))+'\' class="toggleEndpointList" data-id="'+u((o=null!=(o=t.id||(null!=e?e.id:e))?o:l,typeof o===s?o.call(e,{name:"id",hash:{},data:r}):o))+'">Show/Hide</a>\n </li>\n <li>\n <a href=\'#\' class="collapseResource" data-id="'+u((o=null!=(o=t.id||(null!=e?e.id:e))?o:l,typeof o===s?o.call(e,{name:"id",hash:{},data:r}):o))+'">\n List Operations\n </a>\n </li>\n <li>\n <a href=\'#\' class="expandResource" data-id="'+u((o=null!=(o=t.id||(null!=e?e.id:e))?o:l,typeof o===s?o.call(e,{name:"id",hash:{},data:r}):o))+'">\n Expand Operations\n </a>\n </li>\n',i=t["if"].call(e,null!=e?e.url:e,{name:"if",hash:{},fn:this.program(3,r),inverse:this.noop,data:r}),null!=i&&(p+=i),p+" </ul>\n</div>\n<ul class='endpoints' id='"+u((o=null!=(o=t.id||(null!=e?e.id:e))?o:l,typeof o===s?o.call(e,{name:"id",hash:{},data:r}):o))+"_endpoint_list' style='display:none'>\n\n</ul>\n"},useData:!0}),this.Handlebars.templates.response_content_type=Handlebars.template({1:function(e,t,n,r){var i,o="";return i=t.each.call(e,null!=e?e.produces:e,{name:"each",hash:{},fn:this.program(2,r),inverse:this.noop,data:r}),null!=i&&(o+=i),o},2:function(e){var t,n=this.lambda,r=' <option value="';return t=n(e,e),null!=t&&(r+=t),r+='">',t=n(e,e),null!=t&&(r+=t),r+"</option>\n"},4:function(){return' <option value="application/json">application/json</option>\n'},compiler:[6,">= 2.0.0-beta.1"],main:function(e,t,n,r){var i,o='<label for="responseContentType"></label>\n<select name="responseContentType">\n';return i=t["if"].call(e,null!=e?e.produces:e,{name:"if",hash:{},fn:this.program(1,r),inverse:this.program(4,r),data:r}),null!=i&&(o+=i),o+"</select>\n"},useData:!0}),this.Handlebars.templates.signature=Handlebars.template({compiler:[6,">= 2.0.0-beta.1"],main:function(e,t,n,r){var i,o,a="function",s=t.helperMissing,l=this.escapeExpression,u='<div>\n<ul class="signature-nav">\n <li><a class="description-link" href="#">Model</a></li>\n <li><a class="snippet-link" href="#">Model Schema</a></li>\n</ul>\n<div>\n\n<div class="signature-container">\n <div class="description">\n ';return o=null!=(o=t.signature||(null!=e?e.signature:e))?o:s,i=typeof o===a?o.call(e,{name:"signature",hash:{},data:r}):o,null!=i&&(u+=i),u+'\n </div>\n\n <div class="snippet">\n <pre><code>'+l((o=null!=(o=t.sampleJSON||(null!=e?e.sampleJSON:e))?o:s,typeof o===a?o.call(e,{name:"sampleJSON",hash:{},data:r}):o))+'</code></pre>\n <small class="notice"></small>\n </div>\n</div>\n\n'},useData:!0}),this.Handlebars.templates.status_code=Handlebars.template({1:function(e,t,n,r){var i=this.lambda,o=this.escapeExpression;return" <tr>\n <td>"+o(i(r&&r.key,e))+"</td>\n <td>"+o(i(null!=e?e.description:e,e))+"</td>\n <td>"+o(i(null!=e?e.type:e,e))+"</td>\n </tr>\n"},compiler:[6,">= 2.0.0-beta.1"],main:function(e,t,n,r){var i,o,a="function",s=t.helperMissing,l=this.escapeExpression,u="<td width='15%' class='code'>"+l((o=null!=(o=t.code||(null!=e?e.code:e))?o:s,typeof o===a?o.call(e,{name:"code",hash:{},data:r}):o))+"</td>\n<td>";return o=null!=(o=t.message||(null!=e?e.message:e))?o:s,i=typeof o===a?o.call(e,{name:"message",hash:{},data:r}):o,null!=i&&(u+=i),u+='</td>\n<td width=\'50%\'><span class="model-signature" /></td>\n<td class="headers">\n <table>\n <tbody>\n',i=t.each.call(e,null!=e?e.headers:e,{name:"each",hash:{},fn:this.program(1,r),inverse:this.noop,data:r}),null!=i&&(u+=i),u+" </tbody>\n </table>\n</td>"},useData:!0}),function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var t;t="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,t.SwaggerClient=e()}}(function(){var e;return function t(e,n,r){function i(a,s){if(!n[a]){if(!e[a]){var l="function"==typeof require&&require;if(!s&&l)return l(a,!0);if(o)return o(a,!0);var u=new Error("Cannot find module '"+a+"'");throw u.code="MODULE_NOT_FOUND",u}var c=n[a]={exports:{}};e[a][0].call(c.exports,function(t){var n=e[a][1][t];return i(n?n:t)},c,c.exports,t,e,n,r)}return n[a].exports}for(var o="function"==typeof require&&require,a=0;a<r.length;a++)i(r[a]);return i}({1:[function(e,t){"use strict";var n=e("./lib/auth"),r=e("./lib/helpers"),i=e("./lib/client"),o=function(e,t){return r.log('This is deprecated, use "new SwaggerClient" instead.'),new i(e,t)};Array.prototype.indexOf||(Array.prototype.indexOf=function(e,t){for(var n=t||0,r=this.length;r>n;n++)if(this[n]===e)return n;return-1}),String.prototype.endsWith||(String.prototype.endsWith=function(e){return-1!==this.indexOf(e,this.length-e.length)}),t.exports=i,i.ApiKeyAuthorization=n.ApiKeyAuthorization,i.PasswordAuthorization=n.PasswordAuthorization,i.CookieAuthorization=n.CookieAuthorization,i.SwaggerApi=o,i.SwaggerClient=o},{"./lib/auth":2,"./lib/client":3,"./lib/helpers":4}],2:[function(e,t){"use strict";var n=e("btoa"),r=e("cookiejar"),i=t.exports.SwaggerAuthorizations=function(){this.authz={}};i.prototype.add=function(e,t){return this.authz[e]=t,t},i.prototype.remove=function(e){return delete this.authz[e]},i.prototype.apply=function(e,t){var n,r,i,o,a=null;if("undefined"==typeof t||0===Object.keys(t).length)for(n in this.authz)i=this.authz[n],o=i.apply(e,t),o===!0&&(a=!0);else if(Array.isArray(t))for(var s=0;s<t.length;s++){var l=t[s];for(r in l)for(n in this.authz)n===r&&(i=this.authz[n],o=i.apply(e,t),o===!0&&(a=!0))}else for(r in t)for(n in this.authz)n===r&&(i=this.authz[n],o=i.apply(e,t),o===!0&&(a=!0));return a};var o=t.exports.ApiKeyAuthorization=function(e,t,n){this.name=e,this.value=t,this.type=n};o.prototype.apply=function(e){return"query"===this.type?(e.url=e.url.indexOf("?")>0?e.url+"&"+this.name+"="+this.value:e.url+"?"+this.name+"="+this.value,!0):"header"===this.type?(e.headers[this.name]=this.value,!0):void 0};var a=t.exports.CookieAuthorization=function(e){this.cookie=e};a.prototype.apply=function(e){return e.cookieJar=e.cookieJar||new r,e.cookieJar.setCookie(this.cookie),!0};var s=t.exports.PasswordAuthorization=function(e,t,n){this.name=e,this.username=t,this.password=n};s.prototype.apply=function(e){return e.headers.Authorization="Basic "+n(this.username+":"+this.password),!0}},{btoa:16,cookiejar:17}],3:[function(e,t){"use strict";var n={bind:e("lodash-compat/function/bind"),cloneDeep:e("lodash-compat/lang/cloneDeep"),find:e("lodash-compat/collection/find"),forEach:e("lodash-compat/collection/forEach"),indexOf:e("lodash-compat/array/indexOf"),isArray:e("lodash-compat/lang/isArray"),isFunction:e("lodash-compat/lang/isFunction"),isPlainObject:e("lodash-compat/lang/isPlainObject"),isUndefined:e("lodash-compat/lang/isUndefined")},r=e("./auth"),i=e("./helpers"),o=e("./types/model"),a=e("./types/operation"),s=e("./types/operationGroup"),l=e("./resolver"),u=e("./http"),c=e("./spec-converter"),p=["authorizationScheme","authorizations","basePath","build","buildFrom1_1Spec","buildFrom1_2Spec","buildFromSpec","clientAuthorizations","convertInfo","debug","defaultErrorCallback","defaultSuccessCallback","fail","failure","finish","help","idFromOp","info","initialize","isBuilt","isValid","models","modelsArray","options","parseUri","progress","resourceCount","sampleModels","selfReflect","setConsolidatedModels","spec","supportedSubmitMethods","swaggerRequestHeaders","tagFromLabel","url","useJQuery"],h=["apis","asCurl","description","externalDocs","help","label","name","operation","operations","operationsArray","path","tag"],f=["delete","get","head","options","patch","post","put"],d=t.exports=function(e,t){return this.authorizationScheme=null,this.authorizations=null,this.basePath=null,this.debug=!1,this.info=null,this.isBuilt=!1,this.isValid=!1,this.modelsArray=[],this.resourceCount=0,this.url=null,this.useJQuery=!1,"undefined"!=typeof e?this.initialize(e,t):this};d.prototype.initialize=function(e,t){this.models={},this.sampleModels={},t=t||{},"string"==typeof e?this.url=e:"object"==typeof e&&(t=e,this.url=t.url),this.swaggerRequestHeaders=t.swaggerRequestHeaders||"application/json;charset=utf-8,*/*",this.defaultSuccessCallback=t.defaultSuccessCallback||null,this.defaultErrorCallback=t.defaultErrorCallback||null,"function"==typeof t.success&&(this.success=t.success),t.useJQuery&&(this.useJQuery=t.useJQuery),this.clientAuthorizations=t.authorizations?t.authorizations:new r.SwaggerAuthorizations,this.supportedSubmitMethods=t.supportedSubmitMethods||[],this.failure=t.failure||function(){},this.progress=t.progress||function(){},this.spec=n.cloneDeep(t.spec),this.options=t,"function"==typeof t.success&&(this.ready=!0,this.build())},d.prototype.build=function(e){if(this.isBuilt)return this;var t=this;this.progress("fetching resource list: "+this.url);var n={useJQuery:this.useJQuery,url:this.url,method:"get",headers:{accept:this.swaggerRequestHeaders},on:{error:function(e){return t.fail("http"!==t.url.substring(0,4)?"Please specify the protocol for "+t.url:0===e.status?"Can't read from server. It may not have the appropriate access-control-origin settings.":404===e.status?"Can't read swagger JSON from "+t.url:e.status+" : "+e.statusText+" "+t.url)},response:function(e){var n=e.obj||JSON.parse(e.data);if(t.swaggerVersion=n.swaggerVersion,n.swagger&&2===parseInt(n.swagger))t.swaggerVersion=n.swagger,(new l).resolve(n,t.buildFromSpec,t),t.isValid=!0;else{var r=new c;r.setDocumentationLocation(t.url),r.convert(n,function(e){(new l).resolve(e,t.buildFromSpec,t),t.isValid=!0})}}}};if(this.spec)setTimeout(function(){(new l).resolve(t.spec,t.buildFromSpec,t)},10);else{if(this.clientAuthorizations.apply(n),e)return n;(new u).execute(n)}return this},d.prototype.buildFromSpec=function(e){if(this.isBuilt)return this;this.apis={},this.apisArray=[],this.basePath=e.basePath||"",this.consumes=e.consumes,this.host=e.host||"",this.info=e.info||{},this.produces=e.produces,this.schemes=e.schemes||[],this.securityDefinitions=e.securityDefinitions,this.title=e.title||"",e.externalDocs&&(this.externalDocs=e.externalDocs),this.authSchemes=e.securityDefinitions;var t,r={};if(Array.isArray(e.tags))for(r={},t=0;t<e.tags.length;t++){var l=e.tags[t];r[l.name]=l}var u;"string"==typeof this.url&&(u=this.parseUri(this.url)),this.scheme="undefined"==typeof this.schemes||0===this.schemes.length?u.scheme||"http":this.schemes[0],("undefined"==typeof this.host||""===this.host)&&(this.host=u.host,u.port&&(this.host=this.host+":"+u.port)),this.definitions=e.definitions;var c;for(c in this.definitions){var d=new o(c,this.definitions[c],this.models);d&&(this.models[c]=d)}var m=this;return m.apis.help=n.bind(m.help,m),n.forEach(e.paths,function(e,t){n.isPlainObject(e)&&n.forEach(f,function(o){var l=e[o];if(!n.isUndefined(l)){if(!n.isPlainObject(l))return void i.log("The '"+o+"' operation for '"+t+"' path is not an Operation Object");var u=l.tags;(n.isUndefined(u)||!n.isArray(u)||0===u.length)&&(u=l.tags=["default"]);var c=m.idFromOp(t,o,l),f=new a(m,l.scheme,c,o,t,l,m.definitions,m.models,m.clientAuthorizations);n.forEach(u,function(e){var t=n.indexOf(p,e)>-1?"_"+e:e,o=n.indexOf(h,e)>-1?"_"+e:e,a=m[t];if(t!==e&&i.log("The '"+e+"' tag conflicts with a SwaggerClient function/property name. Use 'client."+t+"' or 'client.apis."+e+"' instead of 'client."+e+"'."),o!==e&&i.log("The '"+e+"' tag conflicts with a SwaggerClient operation function/property name. Use 'client.apis."+o+"' instead of 'client.apis."+e+"'."),n.indexOf(h,c)>-1&&(i.log("The '"+c+"' operationId conflicts with a SwaggerClient operation function/property name. Use 'client.apis."+o+"._"+c+"' instead of 'client.apis."+o+"."+c+"'."),c="_"+c,f.nickname=c),n.isUndefined(a)){a=m[t]=m.apis[o]={},a.operations={},a.label=o,a.apis={};var l=r[e];n.isUndefined(l)||(a.description=l.description,a.externalDocs=l.externalDocs),m[t].help=n.bind(m.help,a),m.apisArray.push(new s(e,a.description,a.externalDocs,f))}n.isFunction(a.help)||(a.help=n.bind(m.help,a)),m.apis[o][c]=a[c]=n.bind(f.execute,f),m.apis[o][c].help=a[c].help=n.bind(f.help,f),m.apis[o][c].asCurl=a[c].asCurl=n.bind(f.asCurl,f),a.apis[c]=a.operations[c]=f;var u=n.find(m.apisArray,function(t){return t.tag===e});u&&u.operationsArray.push(f)})}})}),this.isBuilt=!0,this.success&&(this.isValid=!0,this.isBuilt=!0,this.success()),this},d.prototype.parseUri=function(e){var t=/^(((([^:\/#\?]+:)?(?:(\/\/)((?:(([^:@\/#\?]+)(?:\:([^:@\/#\?]+))?)@)?(([^:\/#\?\]\[]+|\[[^\/\]@#?]+\])(?:\:([0-9]+))?))?)?)?((\/?(?:[^\/\?#]+\/+)*)([^\?#]*)))?(\?[^#]+)?)(#.*)?/,n=t.exec(e);return{scheme:n[4].replace(":",""),host:n[11],port:n[12],path:n[15]}},d.prototype.help=function(e){var t="";return this instanceof d?n.forEach(this.apis,function(e,r){n.isPlainObject(e)&&(t+="operations for the '"+r+"' tag\n",n.forEach(e.operations,function(e,n){t+=" * "+n+": "+e.summary+"\n"}))}):(this instanceof s||n.isPlainObject(this))&&(t+="operations for the '"+this.label+"' tag\n",n.forEach(this.apis,function(e,n){t+=" * "+n+": "+e.summary+"\n"})),e?t:(i.log(t),t)},d.prototype.tagFromLabel=function(e){return e},d.prototype.idFromOp=function(e,t,n){n&&n.operationId||(n=n||{},n.operationId=t+"_"+e);var r=n.operationId.replace(/[\s!@#$%^&*()_+=\[{\]};:<>|.\/?,\\'""-]/g,"_")||e.substring(1)+"_"+t;return r=r.replace(/((_){2,})/g,"_"),r=r.replace(/^(_)*/g,""),r=r.replace(/([_])*$/g,"")},d.prototype.fail=function(e){throw this.failure(e),e}},{"./auth":2,"./helpers":4,"./http":5,"./resolver":6,"./spec-converter":7,"./types/model":8,"./types/operation":9,"./types/operationGroup":10,"lodash-compat/array/indexOf":19,"lodash-compat/collection/find":21,"lodash-compat/collection/forEach":22,"lodash-compat/function/bind":25,"lodash-compat/lang/cloneDeep":94,"lodash-compat/lang/isArray":96,"lodash-compat/lang/isFunction":97,"lodash-compat/lang/isPlainObject":100,"lodash-compat/lang/isUndefined":103}],4:[function(e,t){(function(e){"use strict";t.exports.__bind=function(e,t){return function(){return e.apply(t,arguments)}};var n=t.exports.log=function(){n.history=n.history||[],n.history.push(arguments),console&&"test"!==e.env.NODE_ENV&&console.log(Array.prototype.slice.call(arguments)[0])};t.exports.fail=function(e){n(e)},t.exports.optionHtml=function(e,t){return'<tr><td class="optionName">'+e+":</td><td>"+t+"</td></tr>"},t.exports.typeFromJsonSchema=function(e,t){var n;return"integer"===e&&"int32"===t?n="integer":"integer"===e&&"int64"===t?n="long":"integer"===e&&"undefined"==typeof t?n="long":"string"===e&&"date-time"===t?n="date-time":"string"===e&&"date"===t?n="date":"number"===e&&"float"===t?n="float":"number"===e&&"double"===t?n="double":"number"===e&&"undefined"==typeof t?n="double":"boolean"===e?n="boolean":"string"===e&&(n="string"),n};var r=t.exports.simpleRef=function(e){return"undefined"==typeof e?null:0===e.indexOf("#/definitions/")?e.substring("#/definitions/".length):e},i=t.exports.getStringSignature=function(e,t){var n="";return"undefined"!=typeof e.$ref?n+=r(e.$ref):"undefined"==typeof e.type?n+="object":"array"===e.type?t?n+=i(e.items||e.$ref||{}):(n+="Array[",n+=i(e.items||e.$ref||{}),n+="]"):n+="integer"===e.type&&"int32"===e.format?"integer":"integer"===e.type&&"int64"===e.format?"long":"integer"===e.type&&"undefined"==typeof e.format?"long":"string"===e.type&&"date-time"===e.format?"date-time":"string"===e.type&&"date"===e.format?"date":"string"===e.type&&"undefined"==typeof e.format?"string":"number"===e.type&&"float"===e.format?"float":"number"===e.type&&"double"===e.format?"double":"number"===e.type&&"undefined"==typeof e.format?"double":"boolean"===e.type?"boolean":e.$ref?r(e.$ref):e.type,n}}).call(this,e("_process"))},{_process:15}],5:[function(e,t){"use strict";var n=e("./helpers"),r=e("jquery"),i=e("superagent"),o=function(){},a=function(){},s=t.exports=function(){};s.prototype.execute=function(e,t){return this.useJQuery=e&&"boolean"==typeof e.useJQuery?e.useJQuery:this.isIE8(),e&&"object"==typeof e.body&&(e.body.type&&"formData"===e.body.type?(e.contentType=!1,e.processData=!1,delete e.headers["Content-Type"]):e.body=JSON.stringify(e.body)),this.useJQuery?new o(t).execute(e):new a(t).execute(e)},s.prototype.isIE8=function(){var e=!1;if("undefined"!=typeof navigator&&navigator.userAgent){var t=navigator.userAgent.toLowerCase();if(-1!==t.indexOf("msie")){var n=parseInt(t.split("msie")[1]);8>=n&&(e=!0)}}return e},o.prototype.execute=function(e){var t=e.on,i=e;return e.type=e.method,e.cache=!1,delete e.useJQuery,e.data=e.body,delete e.body,e.complete=function(e){for(var r={},o=e.getAllResponseHeaders().split("\n"),a=0;a<o.length;a++){var s=o[a].trim();if(0!==s.length){var l=s.indexOf(":");if(-1!==l){var u=s.substring(0,l).trim(),c=s.substring(l+1).trim();r[u]=c}else r[s]=null}}var p={url:i.url,method:i.method,status:e.status,statusText:e.statusText,data:e.responseText,headers:r},h=r["content-type"]||r["Content-Type"]||null;if(h&&(0===h.indexOf("application/json")||h.indexOf("+json")>0))try{p.obj=e.responseJSON||JSON.parse(p.data)||{}}catch(f){n.log("unable to parse JSON content")}if(e.status>=200&&e.status<300)t.response(p);else{if(!(0===e.status||e.status>=400&&e.status<599))return t.response(p);t.error(p)}},r.support.cors=!0,r.ajax(e)},a.prototype.execute=function(e){var t=e.method.toLowerCase();"delete"===t&&(t="del");var n,r=e.headers||{},o=i[t](e.url);for(n in r)o.set(n,r[n]);e.body&&o.send(e.body),o.end(function(t,n){n=n||{status:0,headers:{error:"no response from server"}};var r,i={url:e.url,method:e.method,headers:n.headers};!t&&n.error&&(t=n.error),t&&e.on&&e.on.error?(i.obj=t,i.status=n?n.status:500,i.statusText=n?n.text:t.message,r=e.on.error):n&&e.on&&e.on.response&&(i.obj="undefined"!=typeof n.body?n.body:n.text,i.status=n.status,i.statusText=n.text,r=e.on.response),i.data=i.statusText,r&&r(i)})}},{"./helpers":4,jquery:18,superagent:111}],6:[function(e,t){"use strict";var n=e("./http"),r=t.exports=function(){};r.prototype.resolve=function(e,t,r){this.scope=r||this;var i,o,a,s,l,u=0,c={},p={},h={};for(o in e.definitions){var f=e.definitions[o];for(l in f.properties)s=f.properties[l],this.resolveTo(s,h)}for(o in e.paths){var d,m,g;a=e.paths[o];for(d in a)if("$ref"===d)this.resolveInline(e,a,h,p);else{m=a[d];var y,v=m.parameters;for(y in v){var b=v[y];"body"===b["in"]&&b.schema&&this.resolveTo(b.schema,h),b.$ref&&this.resolveInline(e,b,h,p)}for(g in m.responses){var w=m.responses[g];"object"==typeof w&&w.$ref&&this.resolveInline(e,w,h,p),w.schema&&this.resolveTo(w.schema,h)}}}var x={},A=0;for(o in h){var E=o.split("#");2===E.length?(i=E[0],a=E[1],Array.isArray(x[i])||(x[i]=[],A+=1),x[i].push(a)):(Array.isArray(x[o])||(x[o]=[],A+=1),x[o].push(null))}for(o in x){var j=this,C=x[o];i=o;var T={useJQuery:!1,url:i,method:"get",headers:{accept:this.scope.swaggerRequestHeaders||"application/json"},on:{error:function(){u+=1;var n;for(n=0;n<C.length;n++){var r=i+"#"+C[n];p[r]=null}u===A&&j.finish(e,h,c,p,t)},response:function(n){var r,a,s=n.obj;if(null===s||0===Object.keys(s).length)try{s=JSON.parse(n.data)}catch(l){s={}}for(u+=1,r=0;r<C.length;r++){var f=C[r];if(null==f)c[o]={name:o,obj:s};else{var d=s,m=f.split("/");for(a=0;a<m.length;a++){var g=m[a];if(-1!==g.indexOf("~1")&&(g=m[a].replace(/~0/g,"~").replace(/~1/g,"/"),"/"!==g.charAt(0)&&(g="/"+g)),"undefined"==typeof d)break;g.length>0&&(d=d[g])}var y=i+"#"+f,v=m[a-1];"undefined"!=typeof d?c[y]={name:v,obj:d}:p[y]=null}}u===A&&j.finish(e,h,c,p,t)}}};r&&r.clientAuthorizations&&r.clientAuthorizations.apply(T),(new n).execute(T)}0===Object.keys(x).length&&t.call(this.scope,e,p)},r.prototype.finish=function(e,t,n,r,i){var o;for(o in t){var a,s=t[o];for(a=0;a<s.length;a++){var l=n[s[a].obj.$ref];if(l)if(e.definitions||(e.definitions={}),"$ref"===s[a].resolveAs)e.definitions[l.name]=l.obj,s[a].obj.$ref="#/definitions/"+l.name;else if("inline"===s[a].resolveAs){var u,c=s[a].obj;delete c.$ref;for(u in l.obj)c[u]=l.obj[u]}}}i.call(this.scope,e,r)},r.prototype.resolveInline=function(e,t,n,r){var i=t.$ref;if(i){if(0===i.indexOf("http"))Array.isArray(n[i])?n[i].push({obj:t,resolveAs:"inline"}):n[i]=[{obj:t,resolveAs:"inline"}];else if(0===i.indexOf("#")){var o,a=i.substring(1),s=a.split("/"),l=e;for(o=0;o<s.length;o++){var u=s[o];u.length>0&&(l=l[u])}if(l){delete t.$ref;var c;for(c in l)t[c]=l[c]}else r[i]=null}}else"array"===t.type&&this.resolveTo(t.items,n)},r.prototype.resolveTo=function(e,t){var n=e.$ref;if(n)0===n.indexOf("http")&&(Array.isArray(t[n])?t[n].push({obj:e,resolveAs:"$ref"}):t[n]=[{obj:e,resolveAs:"$ref"}]);else if("array"===e.type){var r=e.items;this.resolveTo(r,t)}}},{"./http":5}],7:[function(e,t){"use strict";var n=(e("./client"),e("./http")),r=t.exports=function(){this.errors=[],this.warnings=[],this.modelMap={}};r.prototype.setDocumentationLocation=function(e){this.docLocation=e},r.prototype.convert=function(e,t){if(!e||!Array.isArray(e.apis))return this.finish(t,null);var n={swagger:"2.0"};n.originalVersion=e.swaggerVersion,this.apiInfo(e,n),this.securityDefinitions(e,n);var r,i=!1;for(r=0;r<e.apis.length;r++){var o=e.apis[r];Array.isArray(o.operations)&&(i=!0)}i?(this.declaration(e,n),this.finish(t,n)):this.resourceListing(e,n,t)},r.prototype.declaration=function(e,t){var n,r;if(e.apis){{e.basePath}if(0===e.basePath.indexOf("http://")){var i=e.basePath.substring("http://".length),o=i.indexOf("/");o>0?(t.host=i.substring(0,o),t.basePath=i.substring(o)):(t.host=i,t.basePath="/")}var a;if(e.authorizations&&(a=e.authorizations),e.consumes&&(t.consumes=e.consumes),e.produces&&(t.produces=e.produces),"object"==typeof e)for(n in e.models){var s=e.models[n],l=s.id||n;this.modelMap[l]=n}for(r=0;r<e.apis.length;r++){var u=e.apis[r],c=u.path,p=u.operations;this.operations(c,e.resourcePath,p,a,t)}var h=e.models;this.models(h,t)}},r.prototype.models=function(e,t){if("object"==typeof e){var n;t.definitions=t.definitions||{};for(n in e){var r,i=e[n],o=[],a={properties:{}};for(r in i.properties){var s=i.properties[r],l={};this.dataType(s,l),s.description&&(l.description=s.description),s["enum"]&&(l["enum"]=s["enum"]),"boolean"==typeof s.required&&s.required===!0&&o.push(r),"string"==typeof s.required&&"true"===s.required&&o.push(r),a.properties[r]=l}o.length>0&&(a["enum"]=o),t.definitions[n]=a}}},r.prototype.extractTag=function(e){var t=e||"default";return(0===t.indexOf("http:")||0===t.indexOf("https:"))&&(t=t.split(["/"]),t=t[t.length-1].substring()),t.replace("/","")},r.prototype.operations=function(e,t,n,r,i){if(Array.isArray(n)){var o;i.paths||(i.paths={});var a=i.paths[e]||{},s=this.extractTag(t);i.tags=i.tags||[];var l=!1;for(o=0;o<i.tags.length;o++){var u=i.tags[o];u.name===s&&(l=!0)}for(l||i.tags.push({name:s}),o=0;o<n.length;o++){var c=n[o],p=(c.method||c.httpMethod).toLowerCase(),h={tags:[s]},f=c.authorizations;if(f&&0===Object.keys(f).length&&(f=r),"undefined"!=typeof f)for(var d in f){h.security=h.security||[];var m=f[d];if(m){var g=[];for(var y in m)g.push(m[y].scope);var v={};v[d]=g,h.security.push(v)}else{var v={};v[d]=[],h.security.push(v)}}c.consumes?h.consumes=c.consumes:i.consumes&&(h.consumes=i.consumes),c.produces?h.produces=c.produces:i.produces&&(h.produces=i.produces),c.summary&&(h.summary=c.summary),c.notes&&(h.description=c.notes),c.nickname&&(h.operationId=c.nickname),c.deprecated&&(h.deprecated=c.deprecated),this.authorizations(f,i),this.parameters(h,c.parameters,i),this.responseMessages(h,c,i),a[p]=h}i.paths[e]=a}},r.prototype.responseMessages=function(e,t){if("object"==typeof t){var n={};this.dataType(t,n),n.schema||(n={schema:n}),e.responses=e.responses||{};var r=!1;if(Array.isArray(t.responseMessages)){var i,o=t.responseMessages;for(i=0;i<o.length;i++){var a=o[i],s={description:a.message};200===a.code&&(r=!0),e.responses[""+a.code]=s}}r?e.responses["default"]=n:e.responses[200]=n}},r.prototype.authorizations=function(e){},r.prototype.parameters=function(e,t){if(Array.isArray(t)){var n;for(n=0;n<t.length;n++){var r=t[n],i={};if(i.name=r.name,i.description=r.description,i.required=r.required,i["in"]=r.paramType,"body"===i["in"]&&(i.name="body"),"form"===i["in"]&&(i["in"]="formData"),r.allowMultiple===!0||"true"===r.allowMultiple){var o={};if(this.dataType(r,o),i.type="array",i.items=o,r.allowableValues){var a=r.allowableValues;"LIST"===a.valueType&&(i["enum"]=a.values)}}else this.dataType(r,i);e.parameters=e.parameters||[],e.parameters.push(i)}}},r.prototype.dataType=function(e,t){if("object"==typeof e){e.minimum&&(t.minimum=e.minimum),e.maximum&&(t.maximum=e.maximum),e.defaultValue&&(t["default"]=e.defaultValue);var n=this.toJsonSchema(e);n&&(t=t||{},n.type&&(t.type=n.type),n.format&&(t.format=n.format),n.$ref&&(t.schema={$ref:n.$ref}),n.items&&(t.items=n.items))}},r.prototype.toJsonSchema=function(e){if(!e)return"object";var t=e.type||e.dataType||e.responseClass||"",n=t.toLowerCase(),r=(e.format||"").toLowerCase();if(0===n.indexOf("list[")){var i=t.substring(5,t.length-1),o=this.toJsonSchema({type:i});return{type:"array",items:o}}if("int"===n||"integer"===n&&"int32"===r)return{type:"integer",format:"int32"};if("long"===n||"integer"===n&&"int64"===r)return{type:"integer",format:"int64"};if("integer"===n)return{type:"integer",format:"int64"};if("float"===n||"number"===n&&"float"===r)return{type:"number",format:"float"};if("double"===n||"number"===n&&"double"===r)return{type:"number",format:"double"};if("string"===n&&"date-time"===r||"date"===n)return{type:"string",format:"date-time"};if("string"===n)return{type:"string"};if("file"===n)return{type:"file"};if("boolean"===n)return{type:"boolean"};if("array"===n||"list"===n){if(e.items){var a=this.toJsonSchema(e.items);return{type:"array",items:a}}return{type:"array",items:{type:"object"}}}return e.$ref?{$ref:"#/definitions/"+this.modelMap[e.$ref]||e.$ref}:{$ref:"#/definitions/"+this.modelMap[e.type]||e.type}},r.prototype.resourceListing=function(e,t,r){var i,o=0,a=this,s=e.apis.length,l=t;for(0===s&&this.finish(r,t),i=0;s>i;i++){var u=e.apis[i],c=u.path,p=this.getAbsolutePath(e.swaggerVersion,this.docLocation,c);u.description&&(t.tags=t.tags||[],t.tags.push({name:this.extractTag(u.path),description:u.description||""}));var h={url:p,headers:{accept:"application/json"},on:{},method:"get"};h.on.response=function(e){o+=1,e.obj&&a.declaration(e.obj,l),o===s&&a.finish(r,l)},h.on.error=function(e){console.error(e),o+=1,o===s&&a.finish(r,l)},(new n).execute(h)}},r.prototype.getAbsolutePath=function(e,t,n){if("1.0"===e&&t.endsWith(".json")){var r=t.lastIndexOf("/");r>0&&(t=t.substring(0,r))}var i=t;return 0===n.indexOf("http://")||0===n.indexOf("https://")?i=n:(t.endsWith("/")&&(i=t.substring(0,t.length-1)),i+=n),i=i.replace("{format}","json")},r.prototype.securityDefinitions=function(e,t){if(e.authorizations){var n;for(n in e.authorizations){var r=!1,i={},o=e.authorizations[n];if("apiKey"===o.type)i.type="apiKey",i["in"]=o.passAs,i.name=o.keyname||n,r=!0;else if("oauth2"===o.type){var a,s=o.scopes||[],l={};for(a in s){var u=s[a];l[u.scope]=u.description}if(i.type="oauth2",a>0&&(i.scopes=l),o.grantTypes){if(o.grantTypes.implicit){var c=o.grantTypes.implicit;i.flow="implicit",i.authorizationUrl=c.loginEndpoint,r=!0}if(o.grantTypes.authorization_code&&!i.flow){var p=o.grantTypes.authorization_code;i.flow="accessCode",i.authorizationUrl=p.tokenRequestEndpoint.url,i.tokenUrl=p.tokenEndpoint.url,r=!0}}}r&&(t.securityDefinitions=t.securityDefinitions||{},t.securityDefinitions[n]=i)}}},r.prototype.apiInfo=function(e,t){if(e.info){var n=e.info;t.info={},n.contact&&(t.info.contact={},t.info.contact.email=n.contact),n.description&&(t.info.description=n.description),n.title&&(t.info.title=n.title),n.termsOfServiceUrl&&(t.info.termsOfService=n.termsOfServiceUrl),(n.license||n.licenseUrl)&&(t.license={},n.license&&(t.license.name=n.license),n.licenseUrl&&(t.license.url=n.licenseUrl))}else this.warnings.push("missing info section")},r.prototype.finish=function(e,t){e(t)}},{"./client":3,"./http":5}],8:[function(e,t){"use strict";var n={forEach:e("lodash-compat/collection/forEach"),indexOf:e("lodash-compat/array/indexOf"),isArray:e("lodash-compat/lang/isArray"),isPlainObject:e("lodash-compat/lang/isPlainObject"),isString:e("lodash-compat/lang/isString"),isUndefined:e("lodash-compat/lang/isUndefined"),keys:e("lodash-compat/object/keys"),map:e("lodash-compat/collection/map")},r=e("../helpers"),i=t.exports=function(e,t,n){return this.definition=t||{},this.isArray="array"===t.type,this.models=n||{},this.name=e||"Inline Model",this},o=function(e,t,o){for(var a='<span class="strong">',s="</span>",l={},u=[],c=0,p=function(e,t,a){var s,u=t;return e.$ref?(u=r.simpleRef(e.$ref),s=o[u]):n.isUndefined(t)&&(u="Inline Model "+ ++c,s=new i(u,e,o)),a!==!0&&(l[u]=n.isUndefined(s)?{}:s.definition),u},h=function(e){var t='<span class="propType">',i=e.type||"object";return e.$ref?t+=p(e,r.simpleRef(e.$ref)):"object"===i?t+=n.isUndefined(e.properties)?"object":p(e):"array"===i?(t+="Array[",n.isArray(e.items)?t+=n.map(e.items,p).join(","):n.isPlainObject(e.items)?t+=n.isUndefined(e.items.$ref)?n.isUndefined(e.items.type)||-1!==n.indexOf(["array","object"],e.items.type)?p(e.items):e.items.type:p(e.items,r.simpleRef(e.items.$ref)):(r.log("Array type's 'items' schema is not an array or an object, cannot process"),t+="object"),t+="]"):t+=e.type,t+="</span>"},f=function(e,t){var i="",o=e.type||"object",a="array"===o;switch(a&&(o=n.isPlainObject(e.items)&&!n.isUndefined(e.items.type)?e.items.type:"object"),e["default"]&&(i+=r.optionHtml("Default",e["default"])),o){case"string":e.minLength&&(i+=r.optionHtml("Min. Length",e.minLength)),e.maxLength&&(i+=r.optionHtml("Max. Length",e.maxLength)),e.pattern&&(i+=r.optionHtml("Reg. Exp.",e.pattern));break;case"integer":case"number":e.minimum&&(i+=r.optionHtml("Min. Value",e.minimum)),e.exclusiveMinimum&&(i+=r.optionHtml("Exclusive Min.","true")),e.maximum&&(i+=r.optionHtml("Max. Value",e.maximum)),e.exclusiveMaximum&&(i+=r.optionHtml("Exclusive Max.","true")),e.multipleOf&&(i+=r.optionHtml("Multiple Of",e.multipleOf))}if(a&&(e.minItems&&(i+=r.optionHtml("Min. Items",e.minItems)),e.maxItems&&(i+=r.optionHtml("Max. Items",e.maxItems)),e.uniqueItems&&(i+=r.optionHtml("Unique Items","true")),e.collectionFormat&&(i+=r.optionHtml("Coll. Format",e.collectionFormat))),n.isUndefined(e.items)&&n.isArray(e["enum"])){var s;s="number"===o||"integer"===o?e["enum"].join(", "):'"'+e["enum"].join('", "')+'"',i+=r.optionHtml("Enum",s)}return i.length>0&&(t='<span class="propWrap">'+t+'<table class="optionsWrapper"><tr><th colspan="2">'+o+"</th></tr>"+i+"</table></span>"),t},d=function(e,t){var i=e.type||"object",o="array"===e.type,l=a+t+" "+(o?"[":"{")+s;return t&&u.push(t),o?n.isArray(e.items)?l+="<div>"+n.map(e.items,function(e){var t=e.type||"object";return n.isUndefined(e.$ref)?n.indexOf(["array","object"],t)>-1?"object"===t&&n.isUndefined(e.properties)?"object":p(e):f(e,t):p(e,r.simpleRef(e.$ref))}).join(",</div><div>"):n.isPlainObject(e.items)?l+=n.isUndefined(e.items.$ref)?n.indexOf(["array","object"],e.items.type||"object")>-1?(n.isUndefined(e.items.type)||"object"===e.items.type)&&n.isUndefined(e.items.properties)?"<div>object</div>":"<div>"+p(e.items)+"</div>":"<div>"+f(e.items,e.items.type)+"</div>":"<div>"+p(e.items,r.simpleRef(e.items.$ref))+"</div>":(r.log("Array type's 'items' property is not an array or an object, cannot process"),l+="<div>object</div>"):e.$ref?l+="<div>"+p(e,t)+"</div>":"object"===i?(l+="<div>",n.isPlainObject(e.properties)&&(l+=n.map(e.properties,function(t,r){var i=n.indexOf(e.required||[],r)>-1,o='<span class="propName '+i+'">'+r+"</span> (";
return o+=h(t),i||(o+=', <span class="propOptKey">optional</span>'),o+=")",n.isUndefined(t.description)||(o+=": "+t.description),t["enum"]&&(o+=' = <span class="propVals">[\''+t["enum"].join("' or '")+"']</span>"),f(t,o)}).join(",</div><div>")),l+="</div>"):l="<div>"+f(e,i)+"</div>",l+a+(o?"]":"}")+s},m=d(t,e);n.keys(l).length>0;)n.forEach(l,function(e,t){var r=n.indexOf(u,t)>-1;delete l[t],r||(u.push(t),m+="<br />"+d(e,t))});return m},a=function(e,t,i){var o,s,l=e.type||"object";return e.example?s=e.example:n.isUndefined(e.items)&&n.isArray(e["enum"])&&(s=e["enum"][0]),n.isUndefined(s)&&(e.$ref?(o=t[r.simpleRef(e.$ref)],n.isUndefined(o)||(n.isUndefined(i[o.name])?(i[o.name]=o,s=a(o.definition,t,i),delete i[o.name]):s="array"===o.type?[]:{})):e["default"]?s=e["default"]:"date-time"===l?s=(new Date).toISOString():"date"===l?s=(new Date).toISOString().split("T")[0]:"string"===l?s="string":"integer"===l?s=0:"long"===l?s=0:"float"===l?s=0:"double"===l?s=0:"boolean"===l?s=!0:"object"===l?(s={},n.forEach(e.properties,function(e,n){s[n]=a(e,t,i)})):"array"===l&&(s=[],n.isArray(e.items)?n.forEach(e.items,function(e){s.push(a(e,t,i))}):n.isPlainObject(e.items)?s.push(a(e.items,t,i)):n.isUndefined(e.items)?s.push({}):r.log("Array type's 'items' property is not an array or an object, cannot process"))),s};i.prototype.createJSONSample=i.prototype.getSampleValue=function(e){return e=e||{},e[this.name]=this,this.examples&&n.isPlainObject(this.examples)&&this.examples["application/json"]?(this.definition.example=this.examples["application/json"],n.isString(this.definition.example)&&(this.definition.example=JSON.parse(this.definition.example))):this.definition.example=this.examples,a(this.definition,this.models,e)},i.prototype.getMockSignature=function(){return o(this.name,this.definition,this.models)}},{"../helpers":4,"lodash-compat/array/indexOf":19,"lodash-compat/collection/forEach":22,"lodash-compat/collection/map":23,"lodash-compat/lang/isArray":96,"lodash-compat/lang/isPlainObject":100,"lodash-compat/lang/isString":101,"lodash-compat/lang/isUndefined":103,"lodash-compat/object/keys":104}],9:[function(e,t){"use strict";var n={isUndefined:e("lodash-compat/lang/isUndefined")},r=e("../helpers"),i=e("./model"),o=e("../http"),a=t.exports=function(e,t,n,r,o,a,s,l,u){var c=[];if(e=e||{},a=a||{},this.authorizations=a.security,this.basePath=e.basePath||"/",this.clientAuthorizations=u,this.consumes=a.consumes,this.deprecated=a.deprecated,this.description=a.description,this.host=e.host||"localhost",this.method=r||c.push("Operation "+n+" is missing method."),this.models=l||{},this.nickname=n||c.push("Operations must have a nickname."),this.operation=a,this.operations={},this.parameters=null!==a?a.parameters||[]:{},this.parent=e,this.path=o||c.push("Operation "+this.nickname+" is missing path."),this.produces=a.produces,this.responses=a.responses||{},this.scheme=t||e.scheme||"http",this.schemes=e.schemes,this.security=a.security,this.summary=a.summary||"",this.type=null,this.useJQuery=e.useJQuery,"string"==typeof this.deprecated)switch(this.deprecated.toLowerCase()){case"true":case"yes":case"1":this.deprecated=!0;break;case"false":case"no":case"0":case null:this.deprecated=!1;break;default:this.deprecated=Boolean(this.deprecated)}var p,h;if(s){var f;for(f in this.definitions)h=new i(f,s[f],this.models),h&&(this.models[f]=h)}for(p=0;p<this.parameters.length;p++){var d=this.parameters[p];"array"===d.type&&(d.isList=!0,d.allowMultiple=!0);var m=this.getType(d);if(m&&"boolean"===m.toString().toLowerCase()&&(d.allowableValues={},d.isList=!0,d["enum"]=["true","false"]),"undefined"!=typeof d["enum"]){var g;for(d.allowableValues={},d.allowableValues.values=[],d.allowableValues.descriptiveValues=[],g=0;g<d["enum"].length;g++){var y=d["enum"][g],v=y===d["default"]?!0:!1;d.allowableValues.values.push(y),d.allowableValues.descriptiveValues.push({value:y,isDefault:v})}}"array"===d.type&&(m=[m],"undefined"==typeof d.allowableValues&&(delete d.isList,delete d.allowMultiple)),d.signature=this.getModelSignature(m,this.models).toString(),d.sampleJSON=this.getModelSampleJSON(m,this.models),d.responseClassSignature=d.signature}var b,w,x=this.responses;if(x[200]?(w=x[200],b="200"):x[201]?(w=x[201],b="201"):x[202]?(w=x[202],b="202"):x[203]?(w=x[203],b="203"):x[204]?(w=x[204],b="204"):x[205]?(w=x[205],b="205"):x[206]?(w=x[206],b="206"):x["default"]&&(w=x["default"],b="default"),w&&w.schema){var A,E=this.resolveModel(w.schema,s);delete x[b],E?(this.successResponse={},A=this.successResponse[b]=E):w.schema.type&&"object"!==w.schema.type&&"array"!==w.schema.type?(this.successResponse={},A=this.successResponse[b]=w.schema):(this.successResponse={},A=this.successResponse[b]=new i(void 0,w.schema||{},this.models)),A&&(w.description&&(A.description=w.description),w.examples&&(A.examples=w.examples),w.headers&&(A.headers=w.headers)),this.type=w}return c.length>0&&this.resource&&this.resource.api&&this.resource.api.fail&&this.resource.api.fail(c),this};a.prototype.getType=function(e){var t,n=e.type,i=e.format,o=!1;"integer"===n&&"int32"===i?t="integer":"integer"===n&&"int64"===i?t="long":"integer"===n?t="integer":"string"===n?t="date-time"===i?"date-time":"date"===i?"date":"string":"number"===n&&"float"===i?t="float":"number"===n&&"double"===i?t="double":"number"===n?t="double":"boolean"===n?t="boolean":"array"===n&&(o=!0,e.items&&(t=this.getType(e.items))),e.$ref&&(t=e.$ref);var a=e.schema;if(a){var s=a.$ref;return s?(s=r.simpleRef(s),o?[s]:s):this.getType(a)}return o?[t]:t},a.prototype.resolveModel=function(e,t){if("undefined"!=typeof e.$ref){var r=e.$ref;if(0===r.indexOf("#/definitions/")&&(r=r.substring("#/definitions/".length)),t[r])return new i(r,t[r],this.models)}else if("object"===e.type||n.isUndefined(e.type))return new i(void 0,e,this.models);return null},a.prototype.help=function(e){for(var t=this.nickname+": "+this.summary+"\n",n=0;n<this.parameters.length;n++){var i=this.parameters[n],o=i.signature;t+="\n * "+i.name+" ("+o+"): "+i.description}return"undefined"==typeof e&&r.log(t),t},a.prototype.getModelSignature=function(e,t){var n,r;return e instanceof Array?(r=!0,e=e[0]):"undefined"==typeof e&&(e="undefined"),n="string"===e?!0:r&&t[r]||t[e]?!1:!0,n?r?"Array["+e+"]":e.toString():r?"Array["+t[e].getMockSignature()+"]":t[e].getMockSignature()},a.prototype.supportHeaderParams=function(){return!0},a.prototype.supportedSubmitMethods=function(){return this.parent.supportedSubmitMethods},a.prototype.getHeaderParams=function(e){for(var t=this.setContentTypes(e,{}),n=0;n<this.parameters.length;n++){var r=this.parameters[n];if("undefined"!=typeof e[r.name]&&"header"===r["in"]){var i=e[r.name];Array.isArray(i)&&(i=i.toString()),t[r.name]=i}}return t},a.prototype.urlify=function(e){for(var t={},n=this.path,r="",i=0;i<this.parameters.length;i++){var o=this.parameters[i];if("undefined"!=typeof e[o.name])if("path"===o["in"]){var a=new RegExp("{"+o.name+"}","gi"),s=e[o.name];s=Array.isArray(s)?this.encodePathCollection(o.collectionFormat,o.name,s):this.encodePathParam(s),n=n.replace(a,s)}else if("query"===o["in"]&&"undefined"!=typeof e[o.name])if(r+=""===r?"?":"&","undefined"!=typeof o.collectionFormat){var l=e[o.name];r+=Array.isArray(l)?this.encodeQueryCollection(o.collectionFormat,o.name,l):this.encodeQueryParam(o.name)+"="+this.encodeQueryParam(e[o.name])}else r+=this.encodeQueryParam(o.name)+"="+this.encodeQueryParam(e[o.name]);else"formData"===o["in"]&&(t[o.name]=e[o.name])}var u=this.scheme+"://"+this.host;return"/"!==this.basePath&&(u+=this.basePath),u+n+r},a.prototype.getMissingParams=function(e){var t,n=[];for(t=0;t<this.parameters.length;t++){var r=this.parameters[t];r.required===!0&&"undefined"==typeof e[r.name]&&(n=r.name)}return n},a.prototype.getBody=function(e,t,n){for(var r,i,o,a={},s=0;s<this.parameters.length;s++){var l=this.parameters[s];"undefined"!=typeof t[l.name]&&("body"===l["in"]?r=t[l.name]:"formData"===l["in"]&&(a[l.name]=t[l.name]))}if("application/x-www-form-urlencoded"===e["Content-Type"]){var u="";for(i in a)o=a[i],"undefined"!=typeof o&&(""!==u&&(u+="&"),u+=encodeURIComponent(i)+"="+encodeURIComponent(o));r=u}else if(e["Content-Type"]&&e["Content-Type"].indexOf("multipart/form-data")>=0&&n.useJQuery){var c=new FormData;c.type="formData";for(i in a)o=t[i],"undefined"!=typeof o&&("file"===o.type&&o.value?(delete e["Content-Type"],c.append(i,o.value)):c.append(i,o));r=c}return r},a.prototype.getModelSampleJSON=function(e,t){var n,r,i;if(r=e instanceof Array,n=t[e]?!1:!0,i=n?void 0:t[e].createJSONSample()){if(i=r?[i]:i,"string"==typeof i)return i;if("object"==typeof i){var o=i;if(i instanceof Array&&i.length>0&&(o=i[0]),o.nodeName){var a=(new XMLSerializer).serializeToString(o);return this.formatXml(a)}return JSON.stringify(i,null,2)}return i}},a.prototype["do"]=function(e,t,n,r,i){return this.execute(e,t,n,r,i)},a.prototype.execute=function(e,t,n,i,a){var s,l,u=e||{},c={};"object"==typeof t&&(c=t,s=n,l=i),"function"==typeof t&&(s=t,l=n),s=s||r.log,l=l||r.log,c.useJQuery&&(this.useJQuery=c.useJQuery);var p=this.getMissingParams(u);if(p.length>0){var h="missing required params: "+p;return void r.fail(h)}var f,d=this.getHeaderParams(u),m=this.setContentTypes(u,c),g={};for(f in d)g[f]=d[f];for(f in m)g[f]=m[f];var y=this.getBody(g,u,c),v=this.urlify(u);if(v.indexOf(".{format}")>0&&g){var b=g.Accept||g.accept;b&&b.indexOf("json")>0?v=v.replace(".{format}",".json"):b&&b.indexOf("xml")>0&&(v=v.replace(".{format}",".xml"))}var w={url:v,method:this.method.toUpperCase(),body:y,useJQuery:this.useJQuery,headers:g,on:{response:function(e){return s(e,a)},error:function(e){return l(e,a)}}};return this.clientAuthorizations.apply(w,this.operation.security),c.mock===!0?w:void(new o).execute(w,c)},a.prototype.setContentTypes=function(e,t){var n,i,o="application/json",a=this.parameters,s=e.parameterContentType||"application/json",l=[],u=[],c={};for(i=0;i<a.length;i++){var p=a[i];if("formData"===p["in"])"file"===p.type?l.push(p):u.push(p);else if("header"===p["in"]&&t){var h=p.name,f=t[p.name];"undefined"!=typeof t[p.name]&&(c[h]=f)}else"body"===p["in"]&&"undefined"!=typeof e[p.name]&&(n=e[p.name])}return!n||"post"!==this.method&&"put"!==this.method&&"patch"!==this.method&&"delete"!==this.method?u.length>0?s=t.requestContentType?t.requestContentType:l.length>0?"multipart/form-data":"application/x-www-form-urlencoded":"DELETE"===this.type?n="{}":"DELETE"!==this.type&&(s=null):t.requestContentType&&(s=t.requestContentType),s&&this.consumes&&-1===this.consumes.indexOf(s)&&r.log("server doesn't consume "+s+", try "+JSON.stringify(this.consumes)),o=t.responseContentType?t.responseContentType:"application/json",o&&this.produces&&-1===this.produces.indexOf(o)&&r.log("server can't produce "+o),(s&&""!==n||"application/x-www-form-urlencoded"===s)&&(c["Content-Type"]=s),o&&(c.Accept=o),c},a.prototype.asCurl=function(e){var t=this.execute(e,{mock:!0});this.clientAuthorizations.apply(t);var n=[];if(n.push("-X "+this.method.toUpperCase()),t.headers){var r;for(r in t.headers)n.push('--header "'+r+": "+t.headers[r]+'"')}if(t.body){var i;i="object"==typeof t.body?JSON.stringify(t.body):t.body,n.push('-d "'+i.replace(/"/g,'\\"')+'"')}return"curl "+n.join(" ")+' "'+t.url+'"'},a.prototype.encodePathCollection=function(e,t,n){var r,i="",o="";for(o="ssv"===e?"%20":"tsv"===e?"\\t":"pipes"===e?"|":",",r=0;r<n.length;r++)0===r?i=this.encodeQueryParam(n[r]):i+=o+this.encodeQueryParam(n[r]);return i},a.prototype.encodeQueryCollection=function(e,t,n){var r,i="";if("default"===e||"multi"===e)for(r=0;r<n.length;r++)r>0&&(i+="&"),i+=this.encodeQueryParam(t)+"="+this.encodeQueryParam(n[r]);else{var o="";if("csv"===e)o=",";else if("ssv"===e)o="%20";else if("tsv"===e)o="\\t";else if("pipes"===e)o="|";else if("brackets"===e)for(r=0;r<n.length;r++)0!==r&&(i+="&"),i+=this.encodeQueryParam(t)+"[]="+this.encodeQueryParam(n[r]);if(""!==o)for(r=0;r<n.length;r++)0===r?i=this.encodeQueryParam(t)+"="+this.encodeQueryParam(n[r]):i+=o+this.encodeQueryParam(n[r])}return i},a.prototype.encodeQueryParam=function(e){return encodeURIComponent(e)},a.prototype.encodePathParam=function(e){var t,n,r,i;if(e=e.toString(),-1===e.indexOf("/"))return encodeURIComponent(e);for(n=e.split("/"),t=[],r=0,i=n.length;i>r;r++)t.push(encodeURIComponent(n[r]));return t.join("/")}},{"../helpers":4,"../http":5,"./model":8,"lodash-compat/lang/isUndefined":103}],10:[function(e,t){"use strict";var n=t.exports=function(e,t,n,r){this.description=t,this.externalDocs=n,this.name=e,this.operation=r,this.operationsArray=[],this.path=e,this.tag=e};n.prototype.sort=function(){}},{}],11:[function(e,t,n){function r(e,t){var n=this;if(!(n instanceof r))return new r(e,t);var i,o=typeof e;if("number"===o)i=+e;else if("string"===o)i=r.byteLength(e,t);else{if("object"!==o||null===e)throw new TypeError("must start with number, buffer, array or string");"Buffer"===e.type&&I(e.data)&&(e=e.data),i=+e.length}if(i>R)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+R.toString(16)+" bytes");0>i?i=0:i>>>=0,r.TYPED_ARRAY_SUPPORT?n=r._augment(new Uint8Array(i)):(n.length=i,n._isBuffer=!0);var a;if(r.TYPED_ARRAY_SUPPORT&&"number"==typeof e.byteLength)n._set(e);else if(T(e))if(r.isBuffer(e))for(a=0;i>a;a++)n[a]=e.readUInt8(a);else for(a=0;i>a;a++)n[a]=(e[a]%256+256)%256;else if("string"===o)n.write(e,0,t);else if("number"===o&&!r.TYPED_ARRAY_SUPPORT)for(a=0;i>a;a++)n[a]=0;return i>0&&i<=r.poolSize&&(n.parent=M),n}function i(e,t){if(!(this instanceof i))return new i(e,t);var n=new r(e,t);return delete n.parent,n}function o(e,t,n,r){n=Number(n)||0;var i=e.length-n;r?(r=Number(r),r>i&&(r=i)):r=i;var o=t.length;if(o%2!==0)throw new Error("Invalid hex string");r>o/2&&(r=o/2);for(var a=0;r>a;a++){var s=parseInt(t.substr(2*a,2),16);if(isNaN(s))throw new Error("Invalid hex string");e[n+a]=s}return a}function a(e,t,n,r){var i=D(_(t,e.length-n),e,n,r);return i}function s(e,t,n,r){var i=D(O(t),e,n,r);return i}function l(e,t,n,r){return s(e,t,n,r)}function u(e,t,n,r){var i=D($(t),e,n,r);return i}function c(e,t,n,r){var i=D(k(t,e.length-n),e,n,r);return i}function p(e,t,n){return N.fromByteArray(0===t&&n===e.length?e:e.slice(t,n))}function h(e,t,n){var r="",i="";n=Math.min(e.length,n);for(var o=t;n>o;o++)e[o]<=127?(r+=L(i)+String.fromCharCode(e[o]),i=""):i+="%"+e[o].toString(16);return r+L(i)}function f(e,t,n){var r="";n=Math.min(e.length,n);for(var i=t;n>i;i++)r+=String.fromCharCode(127&e[i]);return r}function d(e,t,n){var r="";n=Math.min(e.length,n);for(var i=t;n>i;i++)r+=String.fromCharCode(e[i]);return r}function m(e,t,n){var r=e.length;(!t||0>t)&&(t=0),(!n||0>n||n>r)&&(n=r);for(var i="",o=t;n>o;o++)i+=S(e[o]);return i}function g(e,t,n){for(var r=e.slice(t,n),i="",o=0;o<r.length;o+=2)i+=String.fromCharCode(r[o]+256*r[o+1]);return i}function y(e,t,n){if(e%1!==0||0>e)throw new RangeError("offset is not uint");if(e+t>n)throw new RangeError("Trying to access beyond buffer length")}function v(e,t,n,i,o,a){if(!r.isBuffer(e))throw new TypeError("buffer must be a Buffer instance");if(t>o||a>t)throw new RangeError("value is out of bounds");if(n+i>e.length)throw new RangeError("index out of range")}function b(e,t,n,r){0>t&&(t=65535+t+1);for(var i=0,o=Math.min(e.length-n,2);o>i;i++)e[n+i]=(t&255<<8*(r?i:1-i))>>>8*(r?i:1-i)}function w(e,t,n,r){0>t&&(t=4294967295+t+1);for(var i=0,o=Math.min(e.length-n,4);o>i;i++)e[n+i]=t>>>8*(r?i:3-i)&255}function x(e,t,n,r,i,o){if(t>i||o>t)throw new RangeError("value is out of bounds");if(n+r>e.length)throw new RangeError("index out of range");if(0>n)throw new RangeError("index out of range")}function A(e,t,n,r,i){return i||x(e,t,n,4,3.4028234663852886e38,-3.4028234663852886e38),P.write(e,t,n,r,23,4),n+4}function E(e,t,n,r,i){return i||x(e,t,n,8,1.7976931348623157e308,-1.7976931348623157e308),P.write(e,t,n,r,52,8),n+8}function j(e){if(e=C(e).replace(H,""),e.length<2)return"";for(;e.length%4!==0;)e+="=";return e}function C(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}function T(e){return I(e)||r.isBuffer(e)||e&&"object"==typeof e&&"number"==typeof e.length}function S(e){return 16>e?"0"+e.toString(16):e.toString(16)}function _(e,t){t=t||1/0;for(var n,r=e.length,i=null,o=[],a=0;r>a;a++){if(n=e.charCodeAt(a),n>55295&&57344>n){if(!i){if(n>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(a+1===r){(t-=3)>-1&&o.push(239,191,189);continue}i=n;continue}if(56320>n){(t-=3)>-1&&o.push(239,191,189),i=n;continue}n=i-55296<<10|n-56320|65536,i=null}else i&&((t-=3)>-1&&o.push(239,191,189),i=null);if(128>n){if((t-=1)<0)break;o.push(n)}else if(2048>n){if((t-=2)<0)break;o.push(n>>6|192,63&n|128)}else if(65536>n){if((t-=3)<0)break;o.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(2097152>n))throw new Error("Invalid code point");if((t-=4)<0)break;o.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return o}function O(e){for(var t=[],n=0;n<e.length;n++)t.push(255&e.charCodeAt(n));return t}function k(e,t){for(var n,r,i,o=[],a=0;a<e.length&&!((t-=2)<0);a++)n=e.charCodeAt(a),r=n>>8,i=n%256,o.push(i),o.push(r);return o}function $(e){return N.toByteArray(j(e))}function D(e,t,n,r){for(var i=0;r>i&&!(i+n>=t.length||i>=e.length);i++)t[i+n]=e[i];return i}function L(e){try{return decodeURIComponent(e)}catch(t){return String.fromCharCode(65533)}}var N=e("base64-js"),P=e("ieee754"),I=e("is-array");n.Buffer=r,n.SlowBuffer=i,n.INSPECT_MAX_BYTES=50,r.poolSize=8192;var R=1073741823,M={};r.TYPED_ARRAY_SUPPORT=function(){try{var e=new ArrayBuffer(0),t=new Uint8Array(e);return t.foo=function(){return 42},42===t.foo()&&"function"==typeof t.subarray&&0===new Uint8Array(1).subarray(1,1).byteLength}catch(n){return!1}}(),r.isBuffer=function(e){return!(null==e||!e._isBuffer)},r.compare=function(e,t){if(!r.isBuffer(e)||!r.isBuffer(t))throw new TypeError("Arguments must be Buffers");if(e===t)return 0;for(var n=e.length,i=t.length,o=0,a=Math.min(n,i);a>o&&e[o]===t[o];o++);return o!==a&&(n=e[o],i=t[o]),i>n?-1:n>i?1:0},r.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"raw":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},r.concat=function(e,t){if(!I(e))throw new TypeError("list argument must be an Array of Buffers.");if(0===e.length)return new r(0);if(1===e.length)return e[0];var n;if(void 0===t)for(t=0,n=0;n<e.length;n++)t+=e[n].length;var i=new r(t),o=0;for(n=0;n<e.length;n++){var a=e[n];a.copy(i,o),o+=a.length}return i},r.byteLength=function(e,t){var n;switch(e+="",t||"utf8"){case"ascii":case"binary":case"raw":n=e.length;break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":n=2*e.length;break;case"hex":n=e.length>>>1;break;case"utf8":case"utf-8":n=_(e).length;break;case"base64":n=$(e).length;break;default:n=e.length}return n},r.prototype.length=void 0,r.prototype.parent=void 0,r.prototype.toString=function(e,t,n){var r=!1;if(t>>>=0,n=void 0===n||1/0===n?this.length:n>>>0,e||(e="utf8"),0>t&&(t=0),n>this.length&&(n=this.length),t>=n)return"";for(;;)switch(e){case"hex":return m(this,t,n);case"utf8":case"utf-8":return h(this,t,n);case"ascii":return f(this,t,n);case"binary":return d(this,t,n);case"base64":return p(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return g(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}},r.prototype.equals=function(e){if(!r.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e?!0:0===r.compare(this,e)},r.prototype.inspect=function(){var e="",t=n.INSPECT_MAX_BYTES;return this.length>0&&(e=this.toString("hex",0,t).match(/.{2}/g).join(" "),this.length>t&&(e+=" ... ")),"<Buffer "+e+">"},r.prototype.compare=function(e){if(!r.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e?0:r.compare(this,e)},r.prototype.indexOf=function(e,t){function n(e,t,n){for(var r=-1,i=0;n+i<e.length;i++)if(e[n+i]===t[-1===r?0:i-r]){if(-1===r&&(r=i),i-r+1===t.length)return n+r}else r=-1;return-1}if(t>2147483647?t=2147483647:-2147483648>t&&(t=-2147483648),t>>=0,0===this.length)return-1;if(t>=this.length)return-1;if(0>t&&(t=Math.max(this.length+t,0)),"string"==typeof e)return 0===e.length?-1:String.prototype.indexOf.call(this,e,t);if(r.isBuffer(e))return n(this,e,t);if("number"==typeof e)return r.TYPED_ARRAY_SUPPORT&&"function"===Uint8Array.prototype.indexOf?Uint8Array.prototype.indexOf.call(this,e,t):n(this,[e],t);throw new TypeError("val must be string, number or Buffer")},r.prototype.get=function(e){return console.log(".get() is deprecated. Access using array indexes instead."),this.readUInt8(e)},r.prototype.set=function(e,t){return console.log(".set() is deprecated. Access using array indexes instead."),this.writeUInt8(e,t)},r.prototype.write=function(e,t,n,r){if(isFinite(t))isFinite(n)||(r=n,n=void 0);else{var i=r;r=t,t=n,n=i}if(t=Number(t)||0,0>n||0>t||t>this.length)throw new RangeError("attempt to write outside buffer bounds");var p=this.length-t;n?(n=Number(n),n>p&&(n=p)):n=p,r=String(r||"utf8").toLowerCase();var h;switch(r){case"hex":h=o(this,e,t,n);break;case"utf8":case"utf-8":h=a(this,e,t,n);break;case"ascii":h=s(this,e,t,n);break;case"binary":h=l(this,e,t,n);break;case"base64":h=u(this,e,t,n);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":h=c(this,e,t,n);break;default:throw new TypeError("Unknown encoding: "+r)}return h},r.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},r.prototype.slice=function(e,t){var n=this.length;e=~~e,t=void 0===t?n:~~t,0>e?(e+=n,0>e&&(e=0)):e>n&&(e=n),0>t?(t+=n,0>t&&(t=0)):t>n&&(t=n),e>t&&(t=e);var i;if(r.TYPED_ARRAY_SUPPORT)i=r._augment(this.subarray(e,t));else{var o=t-e;i=new r(o,void 0);for(var a=0;o>a;a++)i[a]=this[a+e]}return i.length&&(i.parent=this.parent||this),i},r.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||y(e,t,this.length);for(var r=this[e],i=1,o=0;++o<t&&(i*=256);)r+=this[e+o]*i;return r},r.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||y(e,t,this.length);for(var r=this[e+--t],i=1;t>0&&(i*=256);)r+=this[e+--t]*i;return r},r.prototype.readUInt8=function(e,t){return t||y(e,1,this.length),this[e]},r.prototype.readUInt16LE=function(e,t){return t||y(e,2,this.length),this[e]|this[e+1]<<8},r.prototype.readUInt16BE=function(e,t){return t||y(e,2,this.length),this[e]<<8|this[e+1]},r.prototype.readUInt32LE=function(e,t){return t||y(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},r.prototype.readUInt32BE=function(e,t){return t||y(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},r.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||y(e,t,this.length);for(var r=this[e],i=1,o=0;++o<t&&(i*=256);)r+=this[e+o]*i;return i*=128,r>=i&&(r-=Math.pow(2,8*t)),r},r.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||y(e,t,this.length);for(var r=t,i=1,o=this[e+--r];r>0&&(i*=256);)o+=this[e+--r]*i;return i*=128,o>=i&&(o-=Math.pow(2,8*t)),o},r.prototype.readInt8=function(e,t){return t||y(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},r.prototype.readInt16LE=function(e,t){t||y(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},r.prototype.readInt16BE=function(e,t){t||y(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},r.prototype.readInt32LE=function(e,t){return t||y(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},r.prototype.readInt32BE=function(e,t){return t||y(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},r.prototype.readFloatLE=function(e,t){return t||y(e,4,this.length),P.read(this,e,!0,23,4)},r.prototype.readFloatBE=function(e,t){return t||y(e,4,this.length),P.read(this,e,!1,23,4)},r.prototype.readDoubleLE=function(e,t){return t||y(e,8,this.length),P.read(this,e,!0,52,8)},r.prototype.readDoubleBE=function(e,t){return t||y(e,8,this.length),P.read(this,e,!1,52,8)},r.prototype.writeUIntLE=function(e,t,n,r){e=+e,t>>>=0,n>>>=0,r||v(this,e,t,n,Math.pow(2,8*n),0);var i=1,o=0;for(this[t]=255&e;++o<n&&(i*=256);)this[t+o]=e/i>>>0&255;return t+n},r.prototype.writeUIntBE=function(e,t,n,r){e=+e,t>>>=0,n>>>=0,r||v(this,e,t,n,Math.pow(2,8*n),0);var i=n-1,o=1;for(this[t+i]=255&e;--i>=0&&(o*=256);)this[t+i]=e/o>>>0&255;return t+n},r.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||v(this,e,t,1,255,0),r.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=e,t+1},r.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||v(this,e,t,2,65535,0),r.TYPED_ARRAY_SUPPORT?(this[t]=e,this[t+1]=e>>>8):b(this,e,t,!0),t+2},r.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||v(this,e,t,2,65535,0),r.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=e):b(this,e,t,!1),t+2},r.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||v(this,e,t,4,4294967295,0),r.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=e):w(this,e,t,!0),t+4},r.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||v(this,e,t,4,4294967295,0),r.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e):w(this,e,t,!1),t+4},r.prototype.writeIntLE=function(e,t,n,r){e=+e,t>>>=0,r||v(this,e,t,n,Math.pow(2,8*n-1)-1,-Math.pow(2,8*n-1));var i=0,o=1,a=0>e?1:0;for(this[t]=255&e;++i<n&&(o*=256);)this[t+i]=(e/o>>0)-a&255;return t+n},r.prototype.writeIntBE=function(e,t,n,r){e=+e,t>>>=0,r||v(this,e,t,n,Math.pow(2,8*n-1)-1,-Math.pow(2,8*n-1));var i=n-1,o=1,a=0>e?1:0;for(this[t+i]=255&e;--i>=0&&(o*=256);)this[t+i]=(e/o>>0)-a&255;return t+n},r.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||v(this,e,t,1,127,-128),r.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),0>e&&(e=255+e+1),this[t]=e,t+1},r.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||v(this,e,t,2,32767,-32768),r.TYPED_ARRAY_SUPPORT?(this[t]=e,this[t+1]=e>>>8):b(this,e,t,!0),t+2},r.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||v(this,e,t,2,32767,-32768),r.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=e):b(this,e,t,!1),t+2},r.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||v(this,e,t,4,2147483647,-2147483648),r.TYPED_ARRAY_SUPPORT?(this[t]=e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):w(this,e,t,!0),t+4},r.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||v(this,e,t,4,2147483647,-2147483648),0>e&&(e=4294967295+e+1),r.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e):w(this,e,t,!1),t+4},r.prototype.writeFloatLE=function(e,t,n){return A(this,e,t,!0,n)},r.prototype.writeFloatBE=function(e,t,n){return A(this,e,t,!1,n)},r.prototype.writeDoubleLE=function(e,t,n){return E(this,e,t,!0,n)},r.prototype.writeDoubleBE=function(e,t,n){return E(this,e,t,!1,n)},r.prototype.copy=function(e,t,n,i){if(n||(n=0),i||0===i||(i=this.length),t>=e.length&&(t=e.length),t||(t=0),i>0&&n>i&&(i=n),i===n)return 0;if(0===e.length||0===this.length)return 0;if(0>t)throw new RangeError("targetStart out of bounds");if(0>n||n>=this.length)throw new RangeError("sourceStart out of bounds");if(0>i)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),e.length-t<i-n&&(i=e.length-t+n);var o=i-n;if(1e3>o||!r.TYPED_ARRAY_SUPPORT)for(var a=0;o>a;a++)e[a+t]=this[a+n];else e._set(this.subarray(n,n+o),t);return o},r.prototype.fill=function(e,t,n){if(e||(e=0),t||(t=0),n||(n=this.length),t>n)throw new RangeError("end < start");if(n!==t&&0!==this.length){if(0>t||t>=this.length)throw new RangeError("start out of bounds");if(0>n||n>this.length)throw new RangeError("end out of bounds");var r;if("number"==typeof e)for(r=t;n>r;r++)this[r]=e;else{var i=_(e.toString()),o=i.length;for(r=t;n>r;r++)this[r]=i[r%o]}return this}},r.prototype.toArrayBuffer=function(){if("undefined"!=typeof Uint8Array){if(r.TYPED_ARRAY_SUPPORT)return new r(this).buffer;for(var e=new Uint8Array(this.length),t=0,n=e.length;n>t;t+=1)e[t]=this[t];return e.buffer}throw new TypeError("Buffer.toArrayBuffer not supported in this browser")};var U=r.prototype;r._augment=function(e){return e.constructor=r,e._isBuffer=!0,e._set=e.set,e.get=U.get,e.set=U.set,e.write=U.write,e.toString=U.toString,e.toLocaleString=U.toString,e.toJSON=U.toJSON,e.equals=U.equals,e.compare=U.compare,e.indexOf=U.indexOf,e.copy=U.copy,e.slice=U.slice,e.readUIntLE=U.readUIntLE,e.readUIntBE=U.readUIntBE,e.readUInt8=U.readUInt8,e.readUInt16LE=U.readUInt16LE,e.readUInt16BE=U.readUInt16BE,e.readUInt32LE=U.readUInt32LE,e.readUInt32BE=U.readUInt32BE,e.readIntLE=U.readIntLE,e.readIntBE=U.readIntBE,e.readInt8=U.readInt8,e.readInt16LE=U.readInt16LE,e.readInt16BE=U.readInt16BE,e.readInt32LE=U.readInt32LE,e.readInt32BE=U.readInt32BE,e.readFloatLE=U.readFloatLE,e.readFloatBE=U.readFloatBE,e.readDoubleLE=U.readDoubleLE,e.readDoubleBE=U.readDoubleBE,e.writeUInt8=U.writeUInt8,e.writeUIntLE=U.writeUIntLE,e.writeUIntBE=U.writeUIntBE,e.writeUInt16LE=U.writeUInt16LE,e.writeUInt16BE=U.writeUInt16BE,e.writeUInt32LE=U.writeUInt32LE,e.writeUInt32BE=U.writeUInt32BE,e.writeIntLE=U.writeIntLE,e.writeIntBE=U.writeIntBE,e.writeInt8=U.writeInt8,e.writeInt16LE=U.writeInt16LE,e.writeInt16BE=U.writeInt16BE,e.writeInt32LE=U.writeInt32LE,e.writeInt32BE=U.writeInt32BE,e.writeFloatLE=U.writeFloatLE,e.writeFloatBE=U.writeFloatBE,e.writeDoubleLE=U.writeDoubleLE,e.writeDoubleBE=U.writeDoubleBE,e.fill=U.fill,e.inspect=U.inspect,e.toArrayBuffer=U.toArrayBuffer,e};var H=/[^+\/0-9A-z\-]/g},{"base64-js":12,ieee754:13,"is-array":14}],12:[function(e,t,n){var r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";!function(e){"use strict";function t(e){var t=e.charCodeAt(0);return t===a||t===p?62:t===s||t===h?63:l>t?-1:l+10>t?t-l+26+26:c+26>t?t-c:u+26>t?t-u+26:void 0}function n(e){function n(e){u[p++]=e}var r,i,a,s,l,u;if(e.length%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var c=e.length;l="="===e.charAt(c-2)?2:"="===e.charAt(c-1)?1:0,u=new o(3*e.length/4-l),a=l>0?e.length-4:e.length;var p=0;for(r=0,i=0;a>r;r+=4,i+=3)s=t(e.charAt(r))<<18|t(e.charAt(r+1))<<12|t(e.charAt(r+2))<<6|t(e.charAt(r+3)),n((16711680&s)>>16),n((65280&s)>>8),n(255&s);return 2===l?(s=t(e.charAt(r))<<2|t(e.charAt(r+1))>>4,n(255&s)):1===l&&(s=t(e.charAt(r))<<10|t(e.charAt(r+1))<<4|t(e.charAt(r+2))>>2,n(s>>8&255),n(255&s)),u}function i(e){function t(e){return r.charAt(e)}function n(e){return t(e>>18&63)+t(e>>12&63)+t(e>>6&63)+t(63&e)}var i,o,a,s=e.length%3,l="";for(i=0,a=e.length-s;a>i;i+=3)o=(e[i]<<16)+(e[i+1]<<8)+e[i+2],l+=n(o);switch(s){case 1:o=e[e.length-1],l+=t(o>>2),l+=t(o<<4&63),l+="==";break;case 2:o=(e[e.length-2]<<8)+e[e.length-1],l+=t(o>>10),l+=t(o>>4&63),l+=t(o<<2&63),l+="="}return l}var o="undefined"!=typeof Uint8Array?Uint8Array:Array,a="+".charCodeAt(0),s="/".charCodeAt(0),l="0".charCodeAt(0),u="a".charCodeAt(0),c="A".charCodeAt(0),p="-".charCodeAt(0),h="_".charCodeAt(0);e.toByteArray=n,e.fromByteArray=i}("undefined"==typeof n?this.base64js={}:n)},{}],13:[function(e,t,n){n.read=function(e,t,n,r,i){var o,a,s=8*i-r-1,l=(1<<s)-1,u=l>>1,c=-7,p=n?i-1:0,h=n?-1:1,f=e[t+p];for(p+=h,o=f&(1<<-c)-1,f>>=-c,c+=s;c>0;o=256*o+e[t+p],p+=h,c-=8);for(a=o&(1<<-c)-1,o>>=-c,c+=r;c>0;a=256*a+e[t+p],p+=h,c-=8);if(0===o)o=1-u;else{if(o===l)return a?0/0:1/0*(f?-1:1);a+=Math.pow(2,r),o-=u}return(f?-1:1)*a*Math.pow(2,o-r)},n.write=function(e,t,n,r,i,o){var a,s,l,u=8*o-i-1,c=(1<<u)-1,p=c>>1,h=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,f=r?0:o-1,d=r?1:-1,m=0>t||0===t&&0>1/t?1:0;for(t=Math.abs(t),isNaN(t)||1/0===t?(s=isNaN(t)?1:0,a=c):(a=Math.floor(Math.log(t)/Math.LN2),t*(l=Math.pow(2,-a))<1&&(a--,l*=2),t+=a+p>=1?h/l:h*Math.pow(2,1-p),t*l>=2&&(a++,l/=2),a+p>=c?(s=0,a=c):a+p>=1?(s=(t*l-1)*Math.pow(2,i),a+=p):(s=t*Math.pow(2,p-1)*Math.pow(2,i),a=0));i>=8;e[n+f]=255&s,f+=d,s/=256,i-=8);for(a=a<<i|s,u+=i;u>0;e[n+f]=255&a,f+=d,a/=256,u-=8);e[n+f-d]|=128*m}},{}],14:[function(e,t){var n=Array.isArray,r=Object.prototype.toString;t.exports=n||function(e){return!!e&&"[object Array]"==r.call(e)}},{}],15:[function(e,t){function n(){if(!a){a=!0;for(var e,t=o.length;t;){e=o,o=[];for(var n=-1;++n<t;)e[n]();t=o.length}a=!1}}function r(){}var i=t.exports={},o=[],a=!1;i.nextTick=function(e){o.push(e),a||setTimeout(n,0)
@@ -25,4 +5,4 @@ return o+=h(t),i||(o+=', <span class="propOptKey">optional</span>'),o+=")",n.isU
return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeType<6)return!1;return!0},parent:function(e){return!A.pseudos.empty(e)},header:function(e){return gt.test(e.nodeName)},input:function(e){return mt.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||"text"===t.toLowerCase())},first:u(function(){return[0]}),last:u(function(e,t){return[t-1]}),eq:u(function(e,t,n){return[0>n?n+t:n]}),even:u(function(e,t){for(var n=0;t>n;n+=2)e.push(n);return e}),odd:u(function(e,t){for(var n=1;t>n;n+=2)e.push(n);return e}),lt:u(function(e,t,n){for(var r=0>n?n+t:n;--r>=0;)e.push(r);return e}),gt:u(function(e,t,n){for(var r=0>n?n+t:n;++r<t;)e.push(r);return e})}},A.pseudos.nth=A.pseudos.eq;for(w in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})A.pseudos[w]=s(w);for(w in{submit:!0,reset:!0})A.pseudos[w]=l(w);return p.prototype=A.filters=A.pseudos,A.setFilters=new p,C=t.tokenize=function(e,n){var r,i,o,a,s,l,u,c=z[e+" "];if(c)return n?0:c.slice(0);for(s=e,l=[],u=A.preFilter;s;){(!r||(i=ut.exec(s)))&&(i&&(s=s.slice(i[0].length)||s),l.push(o=[])),r=!1,(i=ct.exec(s))&&(r=i.shift(),o.push({value:r,type:i[0].replace(lt," ")}),s=s.slice(r.length));for(a in A.filter)!(i=dt[a].exec(s))||u[a]&&!(i=u[a](i))||(r=i.shift(),o.push({value:r,type:a,matches:i}),s=s.slice(r.length));if(!r)break}return n?s.length:s?t.error(e):z(e,l).slice(0)},T=t.compile=function(e,t){var n,r=[],i=[],o=V[e+" "];if(!o){for(t||(t=C(e)),n=t.length;n--;)o=v(t[n]),o[U]?r.push(o):i.push(o);o=V(e,b(i,r)),o.selector=e}return o},S=t.select=function(e,t,n,r){var i,o,a,s,l,u="function"==typeof e&&e,p=!r&&C(e=u.selector||e);if(n=n||[],1===p.length){if(o=p[0]=p[0].slice(0),o.length>2&&"ID"===(a=o[0]).type&&x.getById&&9===t.nodeType&&N&&A.relative[o[1].type]){if(t=(A.find.ID(a.matches[0].replace(xt,At),t)||[])[0],!t)return n;u&&(t=t.parentNode),e=e.slice(o.shift().value.length)}for(i=dt.needsContext.test(e)?0:o.length;i--&&(a=o[i],!A.relative[s=a.type]);)if((l=A.find[s])&&(r=l(a.matches[0].replace(xt,At),bt.test(o[0].type)&&c(t.parentNode)||t))){if(o.splice(i,1),e=r.length&&h(o),!e)return G.apply(n,r),n;break}}return(u||T(e,p))(r,t,!N,n,bt.test(e)&&c(t.parentNode)||t),n},x.sortStable=U.split("").sort(W).join("")===U,x.detectDuplicates=!!k,$(),x.sortDetached=i(function(e){return 1&e.compareDocumentPosition(D.createElement("div"))}),i(function(e){return e.innerHTML="<a href='#'></a>","#"===e.firstChild.getAttribute("href")})||o("type|href|height|width",function(e,t,n){return n?void 0:e.getAttribute(t,"type"===t.toLowerCase()?1:2)}),x.attributes&&i(function(e){return e.innerHTML="<input/>",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||o("value",function(e,t,n){return n||"input"!==e.nodeName.toLowerCase()?void 0:e.defaultValue}),i(function(e){return null==e.getAttribute("disabled")})||o(tt,function(e,t,n){var r;return n?void 0:e[t]===!0?t.toLowerCase():(r=e.getAttributeNode(t))&&r.specified?r.value:null}),t}(t);et.find=ot,et.expr=ot.selectors,et.expr[":"]=et.expr.pseudos,et.unique=ot.uniqueSort,et.text=ot.getText,et.isXMLDoc=ot.isXML,et.contains=ot.contains;var at=et.expr.match.needsContext,st=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,lt=/^.[^:#\[\.,]*$/;et.filter=function(e,t,n){var r=t[0];return n&&(e=":not("+e+")"),1===t.length&&1===r.nodeType?et.find.matchesSelector(r,e)?[r]:[]:et.find.matches(e,et.grep(t,function(e){return 1===e.nodeType}))},et.fn.extend({find:function(e){var t,n=this.length,r=[],i=this;if("string"!=typeof e)return this.pushStack(et(e).filter(function(){for(t=0;n>t;t++)if(et.contains(i[t],this))return!0}));for(t=0;n>t;t++)et.find(e,i[t],r);return r=this.pushStack(n>1?et.unique(r):r),r.selector=this.selector?this.selector+" "+e:e,r},filter:function(e){return this.pushStack(i(this,e||[],!1))},not:function(e){return this.pushStack(i(this,e||[],!0))},is:function(e){return!!i(this,"string"==typeof e&&at.test(e)?et(e):e||[],!1).length}});var ut,ct=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,pt=et.fn.init=function(e,t){var n,r;if(!e)return this;if("string"==typeof e){if(n="<"===e[0]&&">"===e[e.length-1]&&e.length>=3?[null,e,null]:ct.exec(e),!n||!n[1]&&t)return!t||t.jquery?(t||ut).find(e):this.constructor(t).find(e);if(n[1]){if(t=t instanceof et?t[0]:t,et.merge(this,et.parseHTML(n[1],t&&t.nodeType?t.ownerDocument||t:G,!0)),st.test(n[1])&&et.isPlainObject(t))for(n in t)et.isFunction(this[n])?this[n](t[n]):this.attr(n,t[n]);return this}return r=G.getElementById(n[2]),r&&r.parentNode&&(this.length=1,this[0]=r),this.context=G,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):et.isFunction(e)?"undefined"!=typeof ut.ready?ut.ready(e):e(et):(void 0!==e.selector&&(this.selector=e.selector,this.context=e.context),et.makeArray(e,this))};pt.prototype=et.fn,ut=et(G);var ht=/^(?:parents|prev(?:Until|All))/,ft={children:!0,contents:!0,next:!0,prev:!0};et.extend({dir:function(e,t,n){for(var r=[],i=void 0!==n;(e=e[t])&&9!==e.nodeType;)if(1===e.nodeType){if(i&&et(e).is(n))break;r.push(e)}return r},sibling:function(e,t){for(var n=[];e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n}}),et.fn.extend({has:function(e){var t=et(e,this),n=t.length;return this.filter(function(){for(var e=0;n>e;e++)if(et.contains(this,t[e]))return!0})},closest:function(e,t){for(var n,r=0,i=this.length,o=[],a=at.test(e)||"string"!=typeof e?et(e,t||this.context):0;i>r;r++)for(n=this[r];n&&n!==t;n=n.parentNode)if(n.nodeType<11&&(a?a.index(n)>-1:1===n.nodeType&&et.find.matchesSelector(n,e))){o.push(n);break}return this.pushStack(o.length>1?et.unique(o):o)},index:function(e){return e?"string"==typeof e?J.call(et(e),this[0]):J.call(this,e.jquery?e[0]:e):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){return this.pushStack(et.unique(et.merge(this.get(),et(e,t))))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}}),et.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return et.dir(e,"parentNode")},parentsUntil:function(e,t,n){return et.dir(e,"parentNode",n)},next:function(e){return o(e,"nextSibling")},prev:function(e){return o(e,"previousSibling")},nextAll:function(e){return et.dir(e,"nextSibling")},prevAll:function(e){return et.dir(e,"previousSibling")},nextUntil:function(e,t,n){return et.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return et.dir(e,"previousSibling",n)},siblings:function(e){return et.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return et.sibling(e.firstChild)},contents:function(e){return e.contentDocument||et.merge([],e.childNodes)}},function(e,t){et.fn[e]=function(n,r){var i=et.map(this,t,n);return"Until"!==e.slice(-5)&&(r=n),r&&"string"==typeof r&&(i=et.filter(r,i)),this.length>1&&(ft[e]||et.unique(i),ht.test(e)&&i.reverse()),this.pushStack(i)}});var dt=/\S+/g,mt={};et.Callbacks=function(e){e="string"==typeof e?mt[e]||a(e):et.extend({},e);var t,n,r,i,o,s,l=[],u=!e.once&&[],c=function(a){for(t=e.memory&&a,n=!0,s=i||0,i=0,o=l.length,r=!0;l&&o>s;s++)if(l[s].apply(a[0],a[1])===!1&&e.stopOnFalse){t=!1;break}r=!1,l&&(u?u.length&&c(u.shift()):t?l=[]:p.disable())},p={add:function(){if(l){var n=l.length;!function a(t){et.each(t,function(t,n){var r=et.type(n);"function"===r?e.unique&&p.has(n)||l.push(n):n&&n.length&&"string"!==r&&a(n)})}(arguments),r?o=l.length:t&&(i=n,c(t))}return this},remove:function(){return l&&et.each(arguments,function(e,t){for(var n;(n=et.inArray(t,l,n))>-1;)l.splice(n,1),r&&(o>=n&&o--,s>=n&&s--)}),this},has:function(e){return e?et.inArray(e,l)>-1:!(!l||!l.length)},empty:function(){return l=[],o=0,this},disable:function(){return l=u=t=void 0,this},disabled:function(){return!l},lock:function(){return u=void 0,t||p.disable(),this},locked:function(){return!u},fireWith:function(e,t){return!l||n&&!u||(t=t||[],t=[e,t.slice?t.slice():t],r?u.push(t):c(t)),this},fire:function(){return p.fireWith(this,arguments),this},fired:function(){return!!n}};return p},et.extend({Deferred:function(e){var t=[["resolve","done",et.Callbacks("once memory"),"resolved"],["reject","fail",et.Callbacks("once memory"),"rejected"],["notify","progress",et.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return et.Deferred(function(n){et.each(t,function(t,o){var a=et.isFunction(e[t])&&e[t];i[o[1]](function(){var e=a&&a.apply(this,arguments);e&&et.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[o[0]+"With"](this===r?n.promise():this,a?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?et.extend(e,r):r}},i={};return r.pipe=r.then,et.each(t,function(e,o){var a=o[2],s=o[3];r[o[1]]=a.add,s&&a.add(function(){n=s},t[1^e][2].disable,t[2][2].lock),i[o[0]]=function(){return i[o[0]+"With"](this===i?r:this,arguments),this},i[o[0]+"With"]=a.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t,n,r,i=0,o=z.call(arguments),a=o.length,s=1!==a||e&&et.isFunction(e.promise)?a:0,l=1===s?e:et.Deferred(),u=function(e,n,r){return function(i){n[e]=this,r[e]=arguments.length>1?z.call(arguments):i,r===t?l.notifyWith(n,r):--s||l.resolveWith(n,r)}};if(a>1)for(t=new Array(a),n=new Array(a),r=new Array(a);a>i;i++)o[i]&&et.isFunction(o[i].promise)?o[i].promise().done(u(i,r,o)).fail(l.reject).progress(u(i,n,t)):--s;return s||l.resolveWith(r,o),l.promise()}});var gt;et.fn.ready=function(e){return et.ready.promise().done(e),this},et.extend({isReady:!1,readyWait:1,holdReady:function(e){e?et.readyWait++:et.ready(!0)},ready:function(e){(e===!0?--et.readyWait:et.isReady)||(et.isReady=!0,e!==!0&&--et.readyWait>0||(gt.resolveWith(G,[et]),et.fn.triggerHandler&&(et(G).triggerHandler("ready"),et(G).off("ready"))))}}),et.ready.promise=function(e){return gt||(gt=et.Deferred(),"complete"===G.readyState?setTimeout(et.ready):(G.addEventListener("DOMContentLoaded",s,!1),t.addEventListener("load",s,!1))),gt.promise(e)},et.ready.promise();var yt=et.access=function(e,t,n,r,i,o,a){var s=0,l=e.length,u=null==n;if("object"===et.type(n)){i=!0;for(s in n)et.access(e,t,s,n[s],!0,o,a)}else if(void 0!==r&&(i=!0,et.isFunction(r)||(a=!0),u&&(a?(t.call(e,r),t=null):(u=t,t=function(e,t,n){return u.call(et(e),n)})),t))for(;l>s;s++)t(e[s],n,a?r:r.call(e[s],s,t(e[s],n)));return i?e:u?t.call(e):l?t(e[0],n):o};et.acceptData=function(e){return 1===e.nodeType||9===e.nodeType||!+e.nodeType},l.uid=1,l.accepts=et.acceptData,l.prototype={key:function(e){if(!l.accepts(e))return 0;var t={},n=e[this.expando];if(!n){n=l.uid++;try{t[this.expando]={value:n},Object.defineProperties(e,t)}catch(r){t[this.expando]=n,et.extend(e,t)}}return this.cache[n]||(this.cache[n]={}),n},set:function(e,t,n){var r,i=this.key(e),o=this.cache[i];if("string"==typeof t)o[t]=n;else if(et.isEmptyObject(o))et.extend(this.cache[i],t);else for(r in t)o[r]=t[r];return o},get:function(e,t){var n=this.cache[this.key(e)];return void 0===t?n:n[t]},access:function(e,t,n){var r;return void 0===t||t&&"string"==typeof t&&void 0===n?(r=this.get(e,t),void 0!==r?r:this.get(e,et.camelCase(t))):(this.set(e,t,n),void 0!==n?n:t)},remove:function(e,t){var n,r,i,o=this.key(e),a=this.cache[o];if(void 0===t)this.cache[o]={};else{et.isArray(t)?r=t.concat(t.map(et.camelCase)):(i=et.camelCase(t),t in a?r=[t,i]:(r=i,r=r in a?[r]:r.match(dt)||[])),n=r.length;for(;n--;)delete a[r[n]]}},hasData:function(e){return!et.isEmptyObject(this.cache[e[this.expando]]||{})},discard:function(e){e[this.expando]&&delete this.cache[e[this.expando]]}};var vt=new l,bt=new l,wt=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,xt=/([A-Z])/g;et.extend({hasData:function(e){return bt.hasData(e)||vt.hasData(e)},data:function(e,t,n){return bt.access(e,t,n)},removeData:function(e,t){bt.remove(e,t)},_data:function(e,t,n){return vt.access(e,t,n)},_removeData:function(e,t){vt.remove(e,t)}}),et.fn.extend({data:function(e,t){var n,r,i,o=this[0],a=o&&o.attributes;if(void 0===e){if(this.length&&(i=bt.get(o),1===o.nodeType&&!vt.get(o,"hasDataAttrs"))){for(n=a.length;n--;)a[n]&&(r=a[n].name,0===r.indexOf("data-")&&(r=et.camelCase(r.slice(5)),u(o,r,i[r])));vt.set(o,"hasDataAttrs",!0)}return i}return"object"==typeof e?this.each(function(){bt.set(this,e)}):yt(this,function(t){var n,r=et.camelCase(e);if(o&&void 0===t){if(n=bt.get(o,e),void 0!==n)return n;if(n=bt.get(o,r),void 0!==n)return n;if(n=u(o,r,void 0),void 0!==n)return n}else this.each(function(){var n=bt.get(this,r);bt.set(this,r,t),-1!==e.indexOf("-")&&void 0!==n&&bt.set(this,e,t)})},null,t,arguments.length>1,null,!0)},removeData:function(e){return this.each(function(){bt.remove(this,e)})}}),et.extend({queue:function(e,t,n){var r;return e?(t=(t||"fx")+"queue",r=vt.get(e,t),n&&(!r||et.isArray(n)?r=vt.access(e,t,et.makeArray(n)):r.push(n)),r||[]):void 0},dequeue:function(e,t){t=t||"fx";var n=et.queue(e,t),r=n.length,i=n.shift(),o=et._queueHooks(e,t),a=function(){et.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,a,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return vt.get(e,n)||vt.access(e,n,{empty:et.Callbacks("once memory").add(function(){vt.remove(e,[t+"queue",n])})})}}),et.fn.extend({queue:function(e,t){var n=2;return"string"!=typeof e&&(t=e,e="fx",n--),arguments.length<n?et.queue(this[0],e):void 0===t?this:this.each(function(){var n=et.queue(this,e,t);et._queueHooks(this,e),"fx"===e&&"inprogress"!==n[0]&&et.dequeue(this,e)})},dequeue:function(e){return this.each(function(){et.dequeue(this,e)})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,t){var n,r=1,i=et.Deferred(),o=this,a=this.length,s=function(){--r||i.resolveWith(o,[o])};for("string"!=typeof e&&(t=e,e=void 0),e=e||"fx";a--;)n=vt.get(o[a],e+"queueHooks"),n&&n.empty&&(r++,n.empty.add(s));return s(),i.promise(t)}});var At=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,Et=["Top","Right","Bottom","Left"],jt=function(e,t){return e=t||e,"none"===et.css(e,"display")||!et.contains(e.ownerDocument,e)},Ct=/^(?:checkbox|radio)$/i;!function(){var e=G.createDocumentFragment(),t=e.appendChild(G.createElement("div")),n=G.createElement("input");n.setAttribute("type","radio"),n.setAttribute("checked","checked"),n.setAttribute("name","t"),t.appendChild(n),K.checkClone=t.cloneNode(!0).cloneNode(!0).lastChild.checked,t.innerHTML="<textarea>x</textarea>",K.noCloneChecked=!!t.cloneNode(!0).lastChild.defaultValue}();var Tt="undefined";K.focusinBubbles="onfocusin"in t;var St=/^key/,_t=/^(?:mouse|pointer|contextmenu)|click/,Ot=/^(?:focusinfocus|focusoutblur)$/,kt=/^([^.]*)(?:\.(.+)|)$/;et.event={global:{},add:function(e,t,n,r,i){var o,a,s,l,u,c,p,h,f,d,m,g=vt.get(e);if(g)for(n.handler&&(o=n,n=o.handler,i=o.selector),n.guid||(n.guid=et.guid++),(l=g.events)||(l=g.events={}),(a=g.handle)||(a=g.handle=function(t){return typeof et!==Tt&&et.event.triggered!==t.type?et.event.dispatch.apply(e,arguments):void 0}),t=(t||"").match(dt)||[""],u=t.length;u--;)s=kt.exec(t[u])||[],f=m=s[1],d=(s[2]||"").split(".").sort(),f&&(p=et.event.special[f]||{},f=(i?p.delegateType:p.bindType)||f,p=et.event.special[f]||{},c=et.extend({type:f,origType:m,data:r,handler:n,guid:n.guid,selector:i,needsContext:i&&et.expr.match.needsContext.test(i),namespace:d.join(".")},o),(h=l[f])||(h=l[f]=[],h.delegateCount=0,p.setup&&p.setup.call(e,r,d,a)!==!1||e.addEventListener&&e.addEventListener(f,a,!1)),p.add&&(p.add.call(e,c),c.handler.guid||(c.handler.guid=n.guid)),i?h.splice(h.delegateCount++,0,c):h.push(c),et.event.global[f]=!0)},remove:function(e,t,n,r,i){var o,a,s,l,u,c,p,h,f,d,m,g=vt.hasData(e)&&vt.get(e);if(g&&(l=g.events)){for(t=(t||"").match(dt)||[""],u=t.length;u--;)if(s=kt.exec(t[u])||[],f=m=s[1],d=(s[2]||"").split(".").sort(),f){for(p=et.event.special[f]||{},f=(r?p.delegateType:p.bindType)||f,h=l[f]||[],s=s[2]&&new RegExp("(^|\\.)"+d.join("\\.(?:.*\\.|)")+"(\\.|$)"),a=o=h.length;o--;)c=h[o],!i&&m!==c.origType||n&&n.guid!==c.guid||s&&!s.test(c.namespace)||r&&r!==c.selector&&("**"!==r||!c.selector)||(h.splice(o,1),c.selector&&h.delegateCount--,p.remove&&p.remove.call(e,c));a&&!h.length&&(p.teardown&&p.teardown.call(e,d,g.handle)!==!1||et.removeEvent(e,f,g.handle),delete l[f])}else for(f in l)et.event.remove(e,f+t[u],n,r,!0);et.isEmptyObject(l)&&(delete g.handle,vt.remove(e,"events"))}},trigger:function(e,n,r,i){var o,a,s,l,u,c,p,h=[r||G],f=X.call(e,"type")?e.type:e,d=X.call(e,"namespace")?e.namespace.split("."):[];if(a=s=r=r||G,3!==r.nodeType&&8!==r.nodeType&&!Ot.test(f+et.event.triggered)&&(f.indexOf(".")>=0&&(d=f.split("."),f=d.shift(),d.sort()),u=f.indexOf(":")<0&&"on"+f,e=e[et.expando]?e:new et.Event(f,"object"==typeof e&&e),e.isTrigger=i?2:3,e.namespace=d.join("."),e.namespace_re=e.namespace?new RegExp("(^|\\.)"+d.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,e.result=void 0,e.target||(e.target=r),n=null==n?[e]:et.makeArray(n,[e]),p=et.event.special[f]||{},i||!p.trigger||p.trigger.apply(r,n)!==!1)){if(!i&&!p.noBubble&&!et.isWindow(r)){for(l=p.delegateType||f,Ot.test(l+f)||(a=a.parentNode);a;a=a.parentNode)h.push(a),s=a;s===(r.ownerDocument||G)&&h.push(s.defaultView||s.parentWindow||t)}for(o=0;(a=h[o++])&&!e.isPropagationStopped();)e.type=o>1?l:p.bindType||f,c=(vt.get(a,"events")||{})[e.type]&&vt.get(a,"handle"),c&&c.apply(a,n),c=u&&a[u],c&&c.apply&&et.acceptData(a)&&(e.result=c.apply(a,n),e.result===!1&&e.preventDefault());return e.type=f,i||e.isDefaultPrevented()||p._default&&p._default.apply(h.pop(),n)!==!1||!et.acceptData(r)||u&&et.isFunction(r[f])&&!et.isWindow(r)&&(s=r[u],s&&(r[u]=null),et.event.triggered=f,r[f](),et.event.triggered=void 0,s&&(r[u]=s)),e.result}},dispatch:function(e){e=et.event.fix(e);var t,n,r,i,o,a=[],s=z.call(arguments),l=(vt.get(this,"events")||{})[e.type]||[],u=et.event.special[e.type]||{};if(s[0]=e,e.delegateTarget=this,!u.preDispatch||u.preDispatch.call(this,e)!==!1){for(a=et.event.handlers.call(this,e,l),t=0;(i=a[t++])&&!e.isPropagationStopped();)for(e.currentTarget=i.elem,n=0;(o=i.handlers[n++])&&!e.isImmediatePropagationStopped();)(!e.namespace_re||e.namespace_re.test(o.namespace))&&(e.handleObj=o,e.data=o.data,r=((et.event.special[o.origType]||{}).handle||o.handler).apply(i.elem,s),void 0!==r&&(e.result=r)===!1&&(e.preventDefault(),e.stopPropagation()));return u.postDispatch&&u.postDispatch.call(this,e),e.result}},handlers:function(e,t){var n,r,i,o,a=[],s=t.delegateCount,l=e.target;if(s&&l.nodeType&&(!e.button||"click"!==e.type))for(;l!==this;l=l.parentNode||this)if(l.disabled!==!0||"click"!==e.type){for(r=[],n=0;s>n;n++)o=t[n],i=o.selector+" ",void 0===r[i]&&(r[i]=o.needsContext?et(i,this).index(l)>=0:et.find(i,this,null,[l]).length),r[i]&&r.push(o);r.length&&a.push({elem:l,handlers:r})}return s<t.length&&a.push({elem:this,handlers:t.slice(s)}),a},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,t){var n,r,i,o=t.button;return null==e.pageX&&null!=t.clientX&&(n=e.target.ownerDocument||G,r=n.documentElement,i=n.body,e.pageX=t.clientX+(r&&r.scrollLeft||i&&i.scrollLeft||0)-(r&&r.clientLeft||i&&i.clientLeft||0),e.pageY=t.clientY+(r&&r.scrollTop||i&&i.scrollTop||0)-(r&&r.clientTop||i&&i.clientTop||0)),e.which||void 0===o||(e.which=1&o?1:2&o?3:4&o?2:0),e}},fix:function(e){if(e[et.expando])return e;var t,n,r,i=e.type,o=e,a=this.fixHooks[i];for(a||(this.fixHooks[i]=a=_t.test(i)?this.mouseHooks:St.test(i)?this.keyHooks:{}),r=a.props?this.props.concat(a.props):this.props,e=new et.Event(o),t=r.length;t--;)n=r[t],e[n]=o[n];return e.target||(e.target=G),3===e.target.nodeType&&(e.target=e.target.parentNode),a.filter?a.filter(e,o):e},special:{load:{noBubble:!0},focus:{trigger:function(){return this!==h()&&this.focus?(this.focus(),!1):void 0},delegateType:"focusin"},blur:{trigger:function(){return this===h()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return"checkbox"===this.type&&this.click&&et.nodeName(this,"input")?(this.click(),!1):void 0},_default:function(e){return et.nodeName(e.target,"a")}},beforeunload:{postDispatch:function(e){void 0!==e.result&&e.originalEvent&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n,r){var i=et.extend(new et.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?et.event.trigger(i,null,t):et.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},et.removeEvent=function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)},et.Event=function(e,t){return this instanceof et.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||void 0===e.defaultPrevented&&e.returnValue===!1?c:p):this.type=e,t&&et.extend(this,t),this.timeStamp=e&&e.timeStamp||et.now(),void(this[et.expando]=!0)):new et.Event(e,t)},et.Event.prototype={isDefaultPrevented:p,isPropagationStopped:p,isImmediatePropagationStopped:p,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=c,e&&e.preventDefault&&e.preventDefault()},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=c,e&&e.stopPropagation&&e.stopPropagation()},stopImmediatePropagation:function(){var e=this.originalEvent;this.isImmediatePropagationStopped=c,e&&e.stopImmediatePropagation&&e.stopImmediatePropagation(),this.stopPropagation()}},et.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(e,t){et.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj;return(!i||i!==r&&!et.contains(r,i))&&(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),K.focusinBubbles||et.each({focus:"focusin",blur:"focusout"},function(e,t){var n=function(e){et.event.simulate(t,e.target,et.event.fix(e),!0)};et.event.special[t]={setup:function(){var r=this.ownerDocument||this,i=vt.access(r,t);i||r.addEventListener(e,n,!0),vt.access(r,t,(i||0)+1)},teardown:function(){var r=this.ownerDocument||this,i=vt.access(r,t)-1;i?vt.access(r,t,i):(r.removeEventListener(e,n,!0),vt.remove(r,t))}}}),et.fn.extend({on:function(e,t,n,r,i){var o,a;if("object"==typeof e){"string"!=typeof t&&(n=n||t,t=void 0);for(a in e)this.on(a,t,n,e[a],i);return this}if(null==n&&null==r?(r=t,n=t=void 0):null==r&&("string"==typeof t?(r=n,n=void 0):(r=n,n=t,t=void 0)),r===!1)r=p;else if(!r)return this;return 1===i&&(o=r,r=function(e){return et().off(e),o.apply(this,arguments)},r.guid=o.guid||(o.guid=et.guid++)),this.each(function(){et.event.add(this,e,r,n,t)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,t,n){var r,i;if(e&&e.preventDefault&&e.handleObj)return r=e.handleObj,et(e.delegateTarget).off(r.namespace?r.origType+"."+r.namespace:r.origType,r.selector,r.handler),this;if("object"==typeof e){for(i in e)this.off(i,t,e[i]);return this}return(t===!1||"function"==typeof t)&&(n=t,t=void 0),n===!1&&(n=p),this.each(function(){et.event.remove(this,e,n,t)})},trigger:function(e,t){return this.each(function(){et.event.trigger(e,t,this)})},triggerHandler:function(e,t){var n=this[0];return n?et.event.trigger(e,t,n,!0):void 0}});var $t=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,Dt=/<([\w:]+)/,Lt=/<|&#?\w+;/,Nt=/<(?:script|style|link)/i,Pt=/checked\s*(?:[^=]|=\s*.checked.)/i,It=/^$|\/(?:java|ecma)script/i,Rt=/^true\/(.*)/,Mt=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,Ut={option:[1,"<select multiple='multiple'>","</select>"],thead:[1,"<table>","</table>"],col:[2,"<table><colgroup>","</colgroup></table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:[0,"",""]};Ut.optgroup=Ut.option,Ut.tbody=Ut.tfoot=Ut.colgroup=Ut.caption=Ut.thead,Ut.th=Ut.td,et.extend({clone:function(e,t,n){var r,i,o,a,s=e.cloneNode(!0),l=et.contains(e.ownerDocument,e);if(!(K.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||et.isXMLDoc(e)))for(a=v(s),o=v(e),r=0,i=o.length;i>r;r++)b(o[r],a[r]);if(t)if(n)for(o=o||v(e),a=a||v(s),r=0,i=o.length;i>r;r++)y(o[r],a[r]);else y(e,s);return a=v(s,"script"),a.length>0&&g(a,!l&&v(e,"script")),s},buildFragment:function(e,t,n,r){for(var i,o,a,s,l,u,c=t.createDocumentFragment(),p=[],h=0,f=e.length;f>h;h++)if(i=e[h],i||0===i)if("object"===et.type(i))et.merge(p,i.nodeType?[i]:i);else if(Lt.test(i)){for(o=o||c.appendChild(t.createElement("div")),a=(Dt.exec(i)||["",""])[1].toLowerCase(),s=Ut[a]||Ut._default,o.innerHTML=s[1]+i.replace($t,"<$1></$2>")+s[2],u=s[0];u--;)o=o.lastChild;et.merge(p,o.childNodes),o=c.firstChild,o.textContent=""}else p.push(t.createTextNode(i));for(c.textContent="",h=0;i=p[h++];)if((!r||-1===et.inArray(i,r))&&(l=et.contains(i.ownerDocument,i),o=v(c.appendChild(i),"script"),l&&g(o),n))for(u=0;i=o[u++];)It.test(i.type||"")&&n.push(i);return c},cleanData:function(e){for(var t,n,r,i,o=et.event.special,a=0;void 0!==(n=e[a]);a++){if(et.acceptData(n)&&(i=n[vt.expando],i&&(t=vt.cache[i]))){if(t.events)for(r in t.events)o[r]?et.event.remove(n,r):et.removeEvent(n,r,t.handle);vt.cache[i]&&delete vt.cache[i]}delete bt.cache[n[bt.expando]]}}}),et.fn.extend({text:function(e){return yt(this,function(e){return void 0===e?et.text(this):this.empty().each(function(){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&(this.textContent=e)})},null,e,arguments.length)},append:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=f(this,e);t.appendChild(e)}})},prepend:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=f(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){for(var n,r=e?et.filter(e,this):this,i=0;null!=(n=r[i]);i++)t||1!==n.nodeType||et.cleanData(v(n)),n.parentNode&&(t&&et.contains(n.ownerDocument,n)&&g(v(n,"script")),n.parentNode.removeChild(n));return this},empty:function(){for(var e,t=0;null!=(e=this[t]);t++)1===e.nodeType&&(et.cleanData(v(e,!1)),e.textContent="");return this},clone:function(e,t){return e=null==e?!1:e,t=null==t?e:t,this.map(function(){return et.clone(this,e,t)})},html:function(e){return yt(this,function(e){var t=this[0]||{},n=0,r=this.length;if(void 0===e&&1===t.nodeType)return t.innerHTML;if("string"==typeof e&&!Nt.test(e)&&!Ut[(Dt.exec(e)||["",""])[1].toLowerCase()]){e=e.replace($t,"<$1></$2>");try{for(;r>n;n++)t=this[n]||{},1===t.nodeType&&(et.cleanData(v(t,!1)),t.innerHTML=e);t=0}catch(i){}}t&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(){var e=arguments[0];return this.domManip(arguments,function(t){e=this.parentNode,et.cleanData(v(this)),e&&e.replaceChild(t,this)}),e&&(e.length||e.nodeType)?this:this.remove()},detach:function(e){return this.remove(e,!0)},domManip:function(e,t){e=V.apply([],e);var n,r,i,o,a,s,l=0,u=this.length,c=this,p=u-1,h=e[0],f=et.isFunction(h);if(f||u>1&&"string"==typeof h&&!K.checkClone&&Pt.test(h))return this.each(function(n){var r=c.eq(n);f&&(e[0]=h.call(this,n,r.html())),r.domManip(e,t)});if(u&&(n=et.buildFragment(e,this[0].ownerDocument,!1,this),r=n.firstChild,1===n.childNodes.length&&(n=r),r)){for(i=et.map(v(n,"script"),d),o=i.length;u>l;l++)a=n,l!==p&&(a=et.clone(a,!0,!0),o&&et.merge(i,v(a,"script"))),t.call(this[l],a,l);if(o)for(s=i[i.length-1].ownerDocument,et.map(i,m),l=0;o>l;l++)a=i[l],It.test(a.type||"")&&!vt.access(a,"globalEval")&&et.contains(s,a)&&(a.src?et._evalUrl&&et._evalUrl(a.src):et.globalEval(a.textContent.replace(Mt,"")))}return this}}),et.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){et.fn[e]=function(e){for(var n,r=[],i=et(e),o=i.length-1,a=0;o>=a;a++)n=a===o?this:this.clone(!0),et(i[a])[t](n),W.apply(r,n.get());return this.pushStack(r)}});var Ht,Ft={},Bt=/^margin/,qt=new RegExp("^("+At+")(?!px)[a-z%]+$","i"),zt=function(e){return e.ownerDocument.defaultView.opener?e.ownerDocument.defaultView.getComputedStyle(e,null):t.getComputedStyle(e,null)};!function(){function e(){a.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;display:block;margin-top:1%;top:1%;border:1px;padding:1px;width:4px;position:absolute",a.innerHTML="",i.appendChild(o);var e=t.getComputedStyle(a,null);n="1%"!==e.top,r="4px"===e.width,i.removeChild(o)}var n,r,i=G.documentElement,o=G.createElement("div"),a=G.createElement("div");a.style&&(a.style.backgroundClip="content-box",a.cloneNode(!0).style.backgroundClip="",K.clearCloneStyle="content-box"===a.style.backgroundClip,o.style.cssText="border:0;width:0;height:0;top:0;left:-9999px;margin-top:1px;position:absolute",o.appendChild(a),t.getComputedStyle&&et.extend(K,{pixelPosition:function(){return e(),n},boxSizingReliable:function(){return null==r&&e(),r},reliableMarginRight:function(){var e,n=a.appendChild(G.createElement("div"));return n.style.cssText=a.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",n.style.marginRight=n.style.width="0",a.style.width="1px",i.appendChild(o),e=!parseFloat(t.getComputedStyle(n,null).marginRight),i.removeChild(o),a.removeChild(n),e}}))}(),et.swap=function(e,t,n,r){var i,o,a={};for(o in t)a[o]=e.style[o],e.style[o]=t[o];i=n.apply(e,r||[]);for(o in t)e.style[o]=a[o];return i};var Vt=/^(none|table(?!-c[ea]).+)/,Wt=new RegExp("^("+At+")(.*)$","i"),Jt=new RegExp("^([+-])=("+At+")","i"),Yt={position:"absolute",visibility:"hidden",display:"block"},Qt={letterSpacing:"0",fontWeight:"400"},Xt=["Webkit","O","Moz","ms"];et.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=A(e,"opacity");return""===n?"1":n}}}},cssNumber:{columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":"cssFloat"},style:function(e,t,n,r){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var i,o,a,s=et.camelCase(t),l=e.style;return t=et.cssProps[s]||(et.cssProps[s]=j(l,s)),a=et.cssHooks[t]||et.cssHooks[s],void 0===n?a&&"get"in a&&void 0!==(i=a.get(e,!1,r))?i:l[t]:(o=typeof n,"string"===o&&(i=Jt.exec(n))&&(n=(i[1]+1)*i[2]+parseFloat(et.css(e,t)),o="number"),null!=n&&n===n&&("number"!==o||et.cssNumber[s]||(n+="px"),K.clearCloneStyle||""!==n||0!==t.indexOf("background")||(l[t]="inherit"),a&&"set"in a&&void 0===(n=a.set(e,n,r))||(l[t]=n)),void 0)}},css:function(e,t,n,r){var i,o,a,s=et.camelCase(t);return t=et.cssProps[s]||(et.cssProps[s]=j(e.style,s)),a=et.cssHooks[t]||et.cssHooks[s],a&&"get"in a&&(i=a.get(e,!0,n)),void 0===i&&(i=A(e,t,r)),"normal"===i&&t in Qt&&(i=Qt[t]),""===n||n?(o=parseFloat(i),n===!0||et.isNumeric(o)?o||0:i):i}}),et.each(["height","width"],function(e,t){et.cssHooks[t]={get:function(e,n,r){return n?Vt.test(et.css(e,"display"))&&0===e.offsetWidth?et.swap(e,Yt,function(){return S(e,t,r)}):S(e,t,r):void 0},set:function(e,n,r){var i=r&&zt(e);return C(e,n,r?T(e,t,r,"border-box"===et.css(e,"boxSizing",!1,i),i):0)}}}),et.cssHooks.marginRight=E(K.reliableMarginRight,function(e,t){return t?et.swap(e,{display:"inline-block"},A,[e,"marginRight"]):void 0}),et.each({margin:"",padding:"",border:"Width"},function(e,t){et.cssHooks[e+t]={expand:function(n){for(var r=0,i={},o="string"==typeof n?n.split(" "):[n];4>r;r++)i[e+Et[r]+t]=o[r]||o[r-2]||o[0];
return i}},Bt.test(e)||(et.cssHooks[e+t].set=C)}),et.fn.extend({css:function(e,t){return yt(this,function(e,t,n){var r,i,o={},a=0;if(et.isArray(t)){for(r=zt(e),i=t.length;i>a;a++)o[t[a]]=et.css(e,t[a],!1,r);return o}return void 0!==n?et.style(e,t,n):et.css(e,t)},e,t,arguments.length>1)},show:function(){return _(this,!0)},hide:function(){return _(this)},toggle:function(e){return"boolean"==typeof e?e?this.show():this.hide():this.each(function(){jt(this)?et(this).show():et(this).hide()})}}),et.Tween=O,O.prototype={constructor:O,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(et.cssNumber[n]?"":"px")},cur:function(){var e=O.propHooks[this.prop];return e&&e.get?e.get(this):O.propHooks._default.get(this)},run:function(e){var t,n=O.propHooks[this.prop];return this.pos=t=this.options.duration?et.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):O.propHooks._default.set(this),this}},O.prototype.init.prototype=O.prototype,O.propHooks={_default:{get:function(e){var t;return null==e.elem[e.prop]||e.elem.style&&null!=e.elem.style[e.prop]?(t=et.css(e.elem,e.prop,""),t&&"auto"!==t?t:0):e.elem[e.prop]},set:function(e){et.fx.step[e.prop]?et.fx.step[e.prop](e):e.elem.style&&(null!=e.elem.style[et.cssProps[e.prop]]||et.cssHooks[e.prop])?et.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},O.propHooks.scrollTop=O.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},et.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},et.fx=O.prototype.init,et.fx.step={};var Kt,Gt,Zt=/^(?:toggle|show|hide)$/,en=new RegExp("^(?:([+-])=|)("+At+")([a-z%]*)$","i"),tn=/queueHooks$/,nn=[L],rn={"*":[function(e,t){var n=this.createTween(e,t),r=n.cur(),i=en.exec(t),o=i&&i[3]||(et.cssNumber[e]?"":"px"),a=(et.cssNumber[e]||"px"!==o&&+r)&&en.exec(et.css(n.elem,e)),s=1,l=20;if(a&&a[3]!==o){o=o||a[3],i=i||[],a=+r||1;do s=s||".5",a/=s,et.style(n.elem,e,a+o);while(s!==(s=n.cur()/r)&&1!==s&&--l)}return i&&(a=n.start=+a||+r||0,n.unit=o,n.end=i[1]?a+(i[1]+1)*i[2]:+i[2]),n}]};et.Animation=et.extend(P,{tweener:function(e,t){et.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");for(var n,r=0,i=e.length;i>r;r++)n=e[r],rn[n]=rn[n]||[],rn[n].unshift(t)},prefilter:function(e,t){t?nn.unshift(e):nn.push(e)}}),et.speed=function(e,t,n){var r=e&&"object"==typeof e?et.extend({},e):{complete:n||!n&&t||et.isFunction(e)&&e,duration:e,easing:n&&t||t&&!et.isFunction(t)&&t};return r.duration=et.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in et.fx.speeds?et.fx.speeds[r.duration]:et.fx.speeds._default,(null==r.queue||r.queue===!0)&&(r.queue="fx"),r.old=r.complete,r.complete=function(){et.isFunction(r.old)&&r.old.call(this),r.queue&&et.dequeue(this,r.queue)},r},et.fn.extend({fadeTo:function(e,t,n,r){return this.filter(jt).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=et.isEmptyObject(e),o=et.speed(t,n,r),a=function(){var t=P(this,et.extend({},e),o);(i||vt.get(this,"finish"))&&t.stop(!0)};return a.finish=a,i||o.queue===!1?this.each(a):this.queue(o.queue,a)},stop:function(e,t,n){var r=function(e){var t=e.stop;delete e.stop,t(n)};return"string"!=typeof e&&(n=t,t=e,e=void 0),t&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,i=null!=e&&e+"queueHooks",o=et.timers,a=vt.get(this);if(i)a[i]&&a[i].stop&&r(a[i]);else for(i in a)a[i]&&a[i].stop&&tn.test(i)&&r(a[i]);for(i=o.length;i--;)o[i].elem!==this||null!=e&&o[i].queue!==e||(o[i].anim.stop(n),t=!1,o.splice(i,1));(t||!n)&&et.dequeue(this,e)})},finish:function(e){return e!==!1&&(e=e||"fx"),this.each(function(){var t,n=vt.get(this),r=n[e+"queue"],i=n[e+"queueHooks"],o=et.timers,a=r?r.length:0;for(n.finish=!0,et.queue(this,e,[]),i&&i.stop&&i.stop.call(this,!0),t=o.length;t--;)o[t].elem===this&&o[t].queue===e&&(o[t].anim.stop(!0),o.splice(t,1));for(t=0;a>t;t++)r[t]&&r[t].finish&&r[t].finish.call(this);delete n.finish})}}),et.each(["toggle","show","hide"],function(e,t){var n=et.fn[t];et.fn[t]=function(e,r,i){return null==e||"boolean"==typeof e?n.apply(this,arguments):this.animate($(t,!0),e,r,i)}}),et.each({slideDown:$("show"),slideUp:$("hide"),slideToggle:$("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){et.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),et.timers=[],et.fx.tick=function(){var e,t=0,n=et.timers;for(Kt=et.now();t<n.length;t++)e=n[t],e()||n[t]!==e||n.splice(t--,1);n.length||et.fx.stop(),Kt=void 0},et.fx.timer=function(e){et.timers.push(e),e()?et.fx.start():et.timers.pop()},et.fx.interval=13,et.fx.start=function(){Gt||(Gt=setInterval(et.fx.tick,et.fx.interval))},et.fx.stop=function(){clearInterval(Gt),Gt=null},et.fx.speeds={slow:600,fast:200,_default:400},et.fn.delay=function(e,t){return e=et.fx?et.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},function(){var e=G.createElement("input"),t=G.createElement("select"),n=t.appendChild(G.createElement("option"));e.type="checkbox",K.checkOn=""!==e.value,K.optSelected=n.selected,t.disabled=!0,K.optDisabled=!n.disabled,e=G.createElement("input"),e.value="t",e.type="radio",K.radioValue="t"===e.value}();var on,an,sn=et.expr.attrHandle;et.fn.extend({attr:function(e,t){return yt(this,et.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){et.removeAttr(this,e)})}}),et.extend({attr:function(e,t,n){var r,i,o=e.nodeType;if(e&&3!==o&&8!==o&&2!==o)return typeof e.getAttribute===Tt?et.prop(e,t,n):(1===o&&et.isXMLDoc(e)||(t=t.toLowerCase(),r=et.attrHooks[t]||(et.expr.match.bool.test(t)?an:on)),void 0===n?r&&"get"in r&&null!==(i=r.get(e,t))?i:(i=et.find.attr(e,t),null==i?void 0:i):null!==n?r&&"set"in r&&void 0!==(i=r.set(e,n,t))?i:(e.setAttribute(t,n+""),n):void et.removeAttr(e,t))},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(dt);if(o&&1===e.nodeType)for(;n=o[i++];)r=et.propFix[n]||n,et.expr.match.bool.test(n)&&(e[r]=!1),e.removeAttribute(n)},attrHooks:{type:{set:function(e,t){if(!K.radioValue&&"radio"===t&&et.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}}}),an={set:function(e,t,n){return t===!1?et.removeAttr(e,n):e.setAttribute(n,n),n}},et.each(et.expr.match.bool.source.match(/\w+/g),function(e,t){var n=sn[t]||et.find.attr;sn[t]=function(e,t,r){var i,o;return r||(o=sn[t],sn[t]=i,i=null!=n(e,t,r)?t.toLowerCase():null,sn[t]=o),i}});var ln=/^(?:input|select|textarea|button)$/i;et.fn.extend({prop:function(e,t){return yt(this,et.prop,e,t,arguments.length>1)},removeProp:function(e){return this.each(function(){delete this[et.propFix[e]||e]})}}),et.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(e,t,n){var r,i,o,a=e.nodeType;if(e&&3!==a&&8!==a&&2!==a)return o=1!==a||!et.isXMLDoc(e),o&&(t=et.propFix[t]||t,i=et.propHooks[t]),void 0!==n?i&&"set"in i&&void 0!==(r=i.set(e,n,t))?r:e[t]=n:i&&"get"in i&&null!==(r=i.get(e,t))?r:e[t]},propHooks:{tabIndex:{get:function(e){return e.hasAttribute("tabindex")||ln.test(e.nodeName)||e.href?e.tabIndex:-1}}}}),K.optSelected||(et.propHooks.selected={get:function(e){var t=e.parentNode;return t&&t.parentNode&&t.parentNode.selectedIndex,null}}),et.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){et.propFix[this.toLowerCase()]=this});var un=/[\t\r\n\f]/g;et.fn.extend({addClass:function(e){var t,n,r,i,o,a,s="string"==typeof e&&e,l=0,u=this.length;if(et.isFunction(e))return this.each(function(t){et(this).addClass(e.call(this,t,this.className))});if(s)for(t=(e||"").match(dt)||[];u>l;l++)if(n=this[l],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(un," "):" ")){for(o=0;i=t[o++];)r.indexOf(" "+i+" ")<0&&(r+=i+" ");a=et.trim(r),n.className!==a&&(n.className=a)}return this},removeClass:function(e){var t,n,r,i,o,a,s=0===arguments.length||"string"==typeof e&&e,l=0,u=this.length;if(et.isFunction(e))return this.each(function(t){et(this).removeClass(e.call(this,t,this.className))});if(s)for(t=(e||"").match(dt)||[];u>l;l++)if(n=this[l],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(un," "):"")){for(o=0;i=t[o++];)for(;r.indexOf(" "+i+" ")>=0;)r=r.replace(" "+i+" "," ");a=e?et.trim(r):"",n.className!==a&&(n.className=a)}return this},toggleClass:function(e,t){var n=typeof e;return"boolean"==typeof t&&"string"===n?t?this.addClass(e):this.removeClass(e):this.each(et.isFunction(e)?function(n){et(this).toggleClass(e.call(this,n,this.className,t),t)}:function(){if("string"===n)for(var t,r=0,i=et(this),o=e.match(dt)||[];t=o[r++];)i.hasClass(t)?i.removeClass(t):i.addClass(t);else(n===Tt||"boolean"===n)&&(this.className&&vt.set(this,"__className__",this.className),this.className=this.className||e===!1?"":vt.get(this,"__className__")||"")})},hasClass:function(e){for(var t=" "+e+" ",n=0,r=this.length;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(un," ").indexOf(t)>=0)return!0;return!1}});var cn=/\r/g;et.fn.extend({val:function(e){var t,n,r,i=this[0];{if(arguments.length)return r=et.isFunction(e),this.each(function(n){var i;1===this.nodeType&&(i=r?e.call(this,n,et(this).val()):e,null==i?i="":"number"==typeof i?i+="":et.isArray(i)&&(i=et.map(i,function(e){return null==e?"":e+""})),t=et.valHooks[this.type]||et.valHooks[this.nodeName.toLowerCase()],t&&"set"in t&&void 0!==t.set(this,i,"value")||(this.value=i))});if(i)return t=et.valHooks[i.type]||et.valHooks[i.nodeName.toLowerCase()],t&&"get"in t&&void 0!==(n=t.get(i,"value"))?n:(n=i.value,"string"==typeof n?n.replace(cn,""):null==n?"":n)}}}),et.extend({valHooks:{option:{get:function(e){var t=et.find.attr(e,"value");return null!=t?t:et.trim(et.text(e))}},select:{get:function(e){for(var t,n,r=e.options,i=e.selectedIndex,o="select-one"===e.type||0>i,a=o?null:[],s=o?i+1:r.length,l=0>i?s:o?i:0;s>l;l++)if(n=r[l],!(!n.selected&&l!==i||(K.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&et.nodeName(n.parentNode,"optgroup"))){if(t=et(n).val(),o)return t;a.push(t)}return a},set:function(e,t){for(var n,r,i=e.options,o=et.makeArray(t),a=i.length;a--;)r=i[a],(r.selected=et.inArray(r.value,o)>=0)&&(n=!0);return n||(e.selectedIndex=-1),o}}}}),et.each(["radio","checkbox"],function(){et.valHooks[this]={set:function(e,t){return et.isArray(t)?e.checked=et.inArray(et(e).val(),t)>=0:void 0}},K.checkOn||(et.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})}),et.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(e,t){et.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),et.fn.extend({hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)},bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)}});var pn=et.now(),hn=/\?/;et.parseJSON=function(e){return JSON.parse(e+"")},et.parseXML=function(e){var t,n;if(!e||"string"!=typeof e)return null;try{n=new DOMParser,t=n.parseFromString(e,"text/xml")}catch(r){t=void 0}return(!t||t.getElementsByTagName("parsererror").length)&&et.error("Invalid XML: "+e),t};var fn=/#.*$/,dn=/([?&])_=[^&]*/,mn=/^(.*?):[ \t]*([^\r\n]*)$/gm,gn=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,yn=/^(?:GET|HEAD)$/,vn=/^\/\//,bn=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,wn={},xn={},An="*/".concat("*"),En=t.location.href,jn=bn.exec(En.toLowerCase())||[];et.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:En,type:"GET",isLocal:gn.test(jn[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":An,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":et.parseJSON,"text xml":et.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?M(M(e,et.ajaxSettings),t):M(et.ajaxSettings,e)},ajaxPrefilter:I(wn),ajaxTransport:I(xn),ajax:function(e,t){function n(e,t,n,a){var l,c,y,v,w,A=t;2!==b&&(b=2,s&&clearTimeout(s),r=void 0,o=a||"",x.readyState=e>0?4:0,l=e>=200&&300>e||304===e,n&&(v=U(p,x,n)),v=H(p,v,x,l),l?(p.ifModified&&(w=x.getResponseHeader("Last-Modified"),w&&(et.lastModified[i]=w),w=x.getResponseHeader("etag"),w&&(et.etag[i]=w)),204===e||"HEAD"===p.type?A="nocontent":304===e?A="notmodified":(A=v.state,c=v.data,y=v.error,l=!y)):(y=A,(e||!A)&&(A="error",0>e&&(e=0))),x.status=e,x.statusText=(t||A)+"",l?d.resolveWith(h,[c,A,x]):d.rejectWith(h,[x,A,y]),x.statusCode(g),g=void 0,u&&f.trigger(l?"ajaxSuccess":"ajaxError",[x,p,l?c:y]),m.fireWith(h,[x,A]),u&&(f.trigger("ajaxComplete",[x,p]),--et.active||et.event.trigger("ajaxStop")))}"object"==typeof e&&(t=e,e=void 0),t=t||{};var r,i,o,a,s,l,u,c,p=et.ajaxSetup({},t),h=p.context||p,f=p.context&&(h.nodeType||h.jquery)?et(h):et.event,d=et.Deferred(),m=et.Callbacks("once memory"),g=p.statusCode||{},y={},v={},b=0,w="canceled",x={readyState:0,getResponseHeader:function(e){var t;if(2===b){if(!a)for(a={};t=mn.exec(o);)a[t[1].toLowerCase()]=t[2];t=a[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===b?o:null},setRequestHeader:function(e,t){var n=e.toLowerCase();return b||(e=v[n]=v[n]||e,y[e]=t),this},overrideMimeType:function(e){return b||(p.mimeType=e),this},statusCode:function(e){var t;if(e)if(2>b)for(t in e)g[t]=[g[t],e[t]];else x.always(e[x.status]);return this},abort:function(e){var t=e||w;return r&&r.abort(t),n(0,t),this}};if(d.promise(x).complete=m.add,x.success=x.done,x.error=x.fail,p.url=((e||p.url||En)+"").replace(fn,"").replace(vn,jn[1]+"//"),p.type=t.method||t.type||p.method||p.type,p.dataTypes=et.trim(p.dataType||"*").toLowerCase().match(dt)||[""],null==p.crossDomain&&(l=bn.exec(p.url.toLowerCase()),p.crossDomain=!(!l||l[1]===jn[1]&&l[2]===jn[2]&&(l[3]||("http:"===l[1]?"80":"443"))===(jn[3]||("http:"===jn[1]?"80":"443")))),p.data&&p.processData&&"string"!=typeof p.data&&(p.data=et.param(p.data,p.traditional)),R(wn,p,t,x),2===b)return x;u=et.event&&p.global,u&&0===et.active++&&et.event.trigger("ajaxStart"),p.type=p.type.toUpperCase(),p.hasContent=!yn.test(p.type),i=p.url,p.hasContent||(p.data&&(i=p.url+=(hn.test(i)?"&":"?")+p.data,delete p.data),p.cache===!1&&(p.url=dn.test(i)?i.replace(dn,"$1_="+pn++):i+(hn.test(i)?"&":"?")+"_="+pn++)),p.ifModified&&(et.lastModified[i]&&x.setRequestHeader("If-Modified-Since",et.lastModified[i]),et.etag[i]&&x.setRequestHeader("If-None-Match",et.etag[i])),(p.data&&p.hasContent&&p.contentType!==!1||t.contentType)&&x.setRequestHeader("Content-Type",p.contentType),x.setRequestHeader("Accept",p.dataTypes[0]&&p.accepts[p.dataTypes[0]]?p.accepts[p.dataTypes[0]]+("*"!==p.dataTypes[0]?", "+An+"; q=0.01":""):p.accepts["*"]);for(c in p.headers)x.setRequestHeader(c,p.headers[c]);if(p.beforeSend&&(p.beforeSend.call(h,x,p)===!1||2===b))return x.abort();w="abort";for(c in{success:1,error:1,complete:1})x[c](p[c]);if(r=R(xn,p,t,x)){x.readyState=1,u&&f.trigger("ajaxSend",[x,p]),p.async&&p.timeout>0&&(s=setTimeout(function(){x.abort("timeout")},p.timeout));try{b=1,r.send(y,n)}catch(A){if(!(2>b))throw A;n(-1,A)}}else n(-1,"No Transport");return x},getJSON:function(e,t,n){return et.get(e,t,n,"json")},getScript:function(e,t){return et.get(e,void 0,t,"script")}}),et.each(["get","post"],function(e,t){et[t]=function(e,n,r,i){return et.isFunction(n)&&(i=i||r,r=n,n=void 0),et.ajax({url:e,type:t,dataType:i,data:n,success:r})}}),et._evalUrl=function(e){return et.ajax({url:e,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},et.fn.extend({wrapAll:function(e){var t;return et.isFunction(e)?this.each(function(t){et(this).wrapAll(e.call(this,t))}):(this[0]&&(t=et(e,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){for(var e=this;e.firstElementChild;)e=e.firstElementChild;return e}).append(this)),this)},wrapInner:function(e){return this.each(et.isFunction(e)?function(t){et(this).wrapInner(e.call(this,t))}:function(){var t=et(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=et.isFunction(e);return this.each(function(n){et(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){et.nodeName(this,"body")||et(this).replaceWith(this.childNodes)}).end()}}),et.expr.filters.hidden=function(e){return e.offsetWidth<=0&&e.offsetHeight<=0},et.expr.filters.visible=function(e){return!et.expr.filters.hidden(e)};var Cn=/%20/g,Tn=/\[\]$/,Sn=/\r?\n/g,_n=/^(?:submit|button|image|reset|file)$/i,On=/^(?:input|select|textarea|keygen)/i;et.param=function(e,t){var n,r=[],i=function(e,t){t=et.isFunction(t)?t():null==t?"":t,r[r.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(void 0===t&&(t=et.ajaxSettings&&et.ajaxSettings.traditional),et.isArray(e)||e.jquery&&!et.isPlainObject(e))et.each(e,function(){i(this.name,this.value)});else for(n in e)F(n,e[n],t,i);return r.join("&").replace(Cn,"+")},et.fn.extend({serialize:function(){return et.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=et.prop(this,"elements");return e?et.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!et(this).is(":disabled")&&On.test(this.nodeName)&&!_n.test(e)&&(this.checked||!Ct.test(e))}).map(function(e,t){var n=et(this).val();return null==n?null:et.isArray(n)?et.map(n,function(e){return{name:t.name,value:e.replace(Sn,"\r\n")}}):{name:t.name,value:n.replace(Sn,"\r\n")}}).get()}}),et.ajaxSettings.xhr=function(){try{return new XMLHttpRequest}catch(e){}};var kn=0,$n={},Dn={0:200,1223:204},Ln=et.ajaxSettings.xhr();t.attachEvent&&t.attachEvent("onunload",function(){for(var e in $n)$n[e]()}),K.cors=!!Ln&&"withCredentials"in Ln,K.ajax=Ln=!!Ln,et.ajaxTransport(function(e){var t;return K.cors||Ln&&!e.crossDomain?{send:function(n,r){var i,o=e.xhr(),a=++kn;if(o.open(e.type,e.url,e.async,e.username,e.password),e.xhrFields)for(i in e.xhrFields)o[i]=e.xhrFields[i];e.mimeType&&o.overrideMimeType&&o.overrideMimeType(e.mimeType),e.crossDomain||n["X-Requested-With"]||(n["X-Requested-With"]="XMLHttpRequest");for(i in n)o.setRequestHeader(i,n[i]);t=function(e){return function(){t&&(delete $n[a],t=o.onload=o.onerror=null,"abort"===e?o.abort():"error"===e?r(o.status,o.statusText):r(Dn[o.status]||o.status,o.statusText,"string"==typeof o.responseText?{text:o.responseText}:void 0,o.getAllResponseHeaders()))}},o.onload=t(),o.onerror=t("error"),t=$n[a]=t("abort");try{o.send(e.hasContent&&e.data||null)}catch(s){if(t)throw s}},abort:function(){t&&t()}}:void 0}),et.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){return et.globalEval(e),e}}}),et.ajaxPrefilter("script",function(e){void 0===e.cache&&(e.cache=!1),e.crossDomain&&(e.type="GET")}),et.ajaxTransport("script",function(e){if(e.crossDomain){var t,n;return{send:function(r,i){t=et("<script>").prop({async:!0,charset:e.scriptCharset,src:e.url}).on("load error",n=function(e){t.remove(),n=null,e&&i("error"===e.type?404:200,e.type)}),G.head.appendChild(t[0])},abort:function(){n&&n()}}}});var Nn=[],Pn=/(=)\?(?=&|$)|\?\?/;et.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Nn.pop()||et.expando+"_"+pn++;return this[e]=!0,e}}),et.ajaxPrefilter("json jsonp",function(e,n,r){var i,o,a,s=e.jsonp!==!1&&(Pn.test(e.url)?"url":"string"==typeof e.data&&!(e.contentType||"").indexOf("application/x-www-form-urlencoded")&&Pn.test(e.data)&&"data");return s||"jsonp"===e.dataTypes[0]?(i=e.jsonpCallback=et.isFunction(e.jsonpCallback)?e.jsonpCallback():e.jsonpCallback,s?e[s]=e[s].replace(Pn,"$1"+i):e.jsonp!==!1&&(e.url+=(hn.test(e.url)?"&":"?")+e.jsonp+"="+i),e.converters["script json"]=function(){return a||et.error(i+" was not called"),a[0]},e.dataTypes[0]="json",o=t[i],t[i]=function(){a=arguments},r.always(function(){t[i]=o,e[i]&&(e.jsonpCallback=n.jsonpCallback,Nn.push(i)),a&&et.isFunction(o)&&o(a[0]),a=o=void 0}),"script"):void 0}),et.parseHTML=function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||G;var r=st.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=et.buildFragment([e],t,i),i&&i.length&&et(i).remove(),et.merge([],r.childNodes))};var In=et.fn.load;et.fn.load=function(e,t,n){if("string"!=typeof e&&In)return In.apply(this,arguments);var r,i,o,a=this,s=e.indexOf(" ");return s>=0&&(r=et.trim(e.slice(s)),e=e.slice(0,s)),et.isFunction(t)?(n=t,t=void 0):t&&"object"==typeof t&&(i="POST"),a.length>0&&et.ajax({url:e,type:i,dataType:"html",data:t}).done(function(e){o=arguments,a.html(r?et("<div>").append(et.parseHTML(e)).find(r):e)}).complete(n&&function(e,t){a.each(n,o||[e.responseText,t,e])}),this},et.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){et.fn[t]=function(e){return this.on(t,e)}}),et.expr.filters.animated=function(e){return et.grep(et.timers,function(t){return e===t.elem}).length};var Rn=t.document.documentElement;et.offset={setOffset:function(e,t,n){var r,i,o,a,s,l,u,c=et.css(e,"position"),p=et(e),h={};"static"===c&&(e.style.position="relative"),s=p.offset(),o=et.css(e,"top"),l=et.css(e,"left"),u=("absolute"===c||"fixed"===c)&&(o+l).indexOf("auto")>-1,u?(r=p.position(),a=r.top,i=r.left):(a=parseFloat(o)||0,i=parseFloat(l)||0),et.isFunction(t)&&(t=t.call(e,n,s)),null!=t.top&&(h.top=t.top-s.top+a),null!=t.left&&(h.left=t.left-s.left+i),"using"in t?t.using.call(e,h):p.css(h)}},et.fn.extend({offset:function(e){if(arguments.length)return void 0===e?this:this.each(function(t){et.offset.setOffset(this,e,t)});var t,n,r=this[0],i={top:0,left:0},o=r&&r.ownerDocument;if(o)return t=o.documentElement,et.contains(t,r)?(typeof r.getBoundingClientRect!==Tt&&(i=r.getBoundingClientRect()),n=B(o),{top:i.top+n.pageYOffset-t.clientTop,left:i.left+n.pageXOffset-t.clientLeft}):i},position:function(){if(this[0]){var e,t,n=this[0],r={top:0,left:0};return"fixed"===et.css(n,"position")?t=n.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),et.nodeName(e[0],"html")||(r=e.offset()),r.top+=et.css(e[0],"borderTopWidth",!0),r.left+=et.css(e[0],"borderLeftWidth",!0)),{top:t.top-r.top-et.css(n,"marginTop",!0),left:t.left-r.left-et.css(n,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){for(var e=this.offsetParent||Rn;e&&!et.nodeName(e,"html")&&"static"===et.css(e,"position");)e=e.offsetParent;return e||Rn})}}),et.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r="pageYOffset"===n;et.fn[e]=function(i){return yt(this,function(e,i,o){var a=B(e);return void 0===o?a?a[n]:e[i]:void(a?a.scrollTo(r?t.pageXOffset:o,r?o:t.pageYOffset):e[i]=o)},e,i,arguments.length,null)}}),et.each(["top","left"],function(e,t){et.cssHooks[t]=E(K.pixelPosition,function(e,n){return n?(n=A(e,t),qt.test(n)?et(e).position()[t]+"px":n):void 0})}),et.each({Height:"height",Width:"width"},function(e,t){et.each({padding:"inner"+e,content:t,"":"outer"+e},function(n,r){et.fn[r]=function(r,i){var o=arguments.length&&(n||"boolean"!=typeof r),a=n||(r===!0||i===!0?"margin":"border");return yt(this,function(t,n,r){var i;return et.isWindow(t)?t.document.documentElement["client"+e]:9===t.nodeType?(i=t.documentElement,Math.max(t.body["scroll"+e],i["scroll"+e],t.body["offset"+e],i["offset"+e],i["client"+e])):void 0===r?et.css(t,n,a):et.style(t,n,r,a)},t,o?r:void 0,o,null)}})}),et.fn.size=function(){return this.length},et.fn.andSelf=et.fn.addBack,"function"==typeof e&&e.amd&&e("jquery",[],function(){return et});var Mn=t.jQuery,Un=t.$;return et.noConflict=function(e){return t.$===et&&(t.$=Un),e&&t.jQuery===et&&(t.jQuery=Mn),et},typeof n===Tt&&(t.jQuery=t.$=et),et})},{}],19:[function(e,t){function n(e,t,n){var a=e?e.length:0;if(!a)return-1;if("number"==typeof n)n=0>n?o(a+n,0):n;else if(n){var s=i(e,t),l=e[s];return(t===t?t===l:l!==l)?s:-1}return r(e,t,n||0)}var r=e("../internal/baseIndexOf"),i=e("../internal/binaryIndex"),o=Math.max;t.exports=n},{"../internal/baseIndexOf":42,"../internal/binaryIndex":54}],20:[function(e,t){function n(e){if(s(e)&&!a(e)&&!(e instanceof r)){if(e instanceof i)return e;if(c.call(e,"__chain__")&&c.call(e,"__wrapped__"))return l(e)}return new i(e)}var r=e("../internal/LazyWrapper"),i=e("../internal/LodashWrapper"),o=e("../internal/baseLodash"),a=e("../lang/isArray"),s=e("../internal/isObjectLike"),l=e("../internal/wrapperClone"),u=Object.prototype,c=u.hasOwnProperty;n.prototype=o.prototype,t.exports=n},{"../internal/LazyWrapper":27,"../internal/LodashWrapper":28,"../internal/baseLodash":47,"../internal/isObjectLike":82,"../internal/wrapperClone":93,"../lang/isArray":96}],21:[function(e,t){var n=e("../internal/baseEach"),r=e("../internal/createFind"),i=r(n);t.exports=i},{"../internal/baseEach":36,"../internal/createFind":64}],22:[function(e,t){var n=e("../internal/arrayEach"),r=e("../internal/baseEach"),i=e("../internal/createForEach"),o=i(n,r);t.exports=o},{"../internal/arrayEach":30,"../internal/baseEach":36,"../internal/createForEach":65}],23:[function(e,t){function n(e,t,n){var s=a(e)?r:o;return t=i(t,n,3),s(e,t)}var r=e("../internal/arrayMap"),i=e("../internal/baseCallback"),o=e("../internal/baseMap"),a=e("../lang/isArray");t.exports=n},{"../internal/arrayMap":31,"../internal/baseCallback":32,"../internal/baseMap":48,"../lang/isArray":96}],24:[function(e,t){var n=e("../lang/isNative"),r=n(r=Date.now)&&r,i=r||function(){return(new Date).getTime()};t.exports=i},{"../lang/isNative":98}],25:[function(e,t){var n=e("../internal/createWrapper"),r=e("../internal/replaceHolders"),i=e("./restParam"),o=1,a=32,s=i(function(e,t,i){var l=o;if(i.length){var u=r(i,s.placeholder);l|=a}return n(e,l,t,i,u)});s.placeholder={},t.exports=s},{"../internal/createWrapper":68,"../internal/replaceHolders":88,"./restParam":26}],26:[function(e,t){function n(e,t){if("function"!=typeof e)throw new TypeError(r);return t=i("undefined"==typeof t?e.length-1:+t||0,0),function(){for(var n=arguments,r=-1,o=i(n.length-t,0),a=Array(o);++r<o;)a[r]=n[t+r];switch(t){case 0:return e.call(this,a);case 1:return e.call(this,n[0],a);case 2:return e.call(this,n[0],n[1],a)}var s=Array(t+1);for(r=-1;++r<t;)s[r]=n[r];return s[t]=a,e.apply(this,s)}}var r="Expected a function",i=Math.max;t.exports=n},{}],27:[function(e,t){function n(e){this.__wrapped__=e,this.__actions__=null,this.__dir__=1,this.__dropCount__=0,this.__filtered__=!1,this.__iteratees__=null,this.__takeCount__=o,this.__views__=null}var r=e("./baseCreate"),i=e("./baseLodash"),o=Number.POSITIVE_INFINITY;n.prototype=r(i.prototype),n.prototype.constructor=n,t.exports=n},{"./baseCreate":35,"./baseLodash":47}],28:[function(e,t){function n(e,t,n){this.__wrapped__=e,this.__actions__=n||[],this.__chain__=!!t}var r=e("./baseCreate"),i=e("./baseLodash");n.prototype=r(i.prototype),n.prototype.constructor=n,t.exports=n},{"./baseCreate":35,"./baseLodash":47}],29:[function(e,t){function n(e,t){var n=-1,r=e.length;for(t||(t=Array(r));++n<r;)t[n]=e[n];return t}t.exports=n},{}],30:[function(e,t){function n(e,t){for(var n=-1,r=e.length;++n<r&&t(e[n],n,e)!==!1;);return e}t.exports=n},{}],31:[function(e,t){function n(e,t){for(var n=-1,r=e.length,i=Array(r);++n<r;)i[n]=t(e[n],n,e);return i}t.exports=n},{}],32:[function(e,t){function n(e,t,n){var l=typeof e;return"function"==l?"undefined"==typeof t?e:a(e,t,n):null==e?s:"object"==l?r(e):"undefined"==typeof t?o(e+""):i(e+"",t)}var r=e("./baseMatches"),i=e("./baseMatchesProperty"),o=e("./baseProperty"),a=e("./bindCallback"),s=e("../utility/identity");t.exports=n},{"../utility/identity":109,"./baseMatches":49,"./baseMatchesProperty":50,"./baseProperty":51,"./bindCallback":56}],33:[function(e,t){function n(e,t,m,g,y,v,w){var x;if(m&&(x=y?m(e,g,y):m(e)),"undefined"!=typeof x)return x;if(!h(e))return e;var E=c(e);if(E){if(x=s(e),!t)return r(e,x)}else{var j=U.call(e),C=j==b;if(j!=A&&j!=d&&(!C||y))return R[j]?l(e,j,t):y?e:{};if(p(e))return y?e:{};if(x=u(C?{}:e),!t)return o(e,x,f(e))}v||(v=[]),w||(w=[]);for(var T=v.length;T--;)if(v[T]==e)return w[T];return v.push(e),w.push(x),(E?i:a)(e,function(r,i){x[i]=n(r,t,m,i,e,v,w)}),x}var r=e("./arrayCopy"),i=e("./arrayEach"),o=e("./baseCopy"),a=e("./baseForOwn"),s=e("./initCloneArray"),l=e("./initCloneByTag"),u=e("./initCloneObject"),c=e("../lang/isArray"),p=e("./isHostObject"),h=e("../lang/isObject"),f=e("../object/keys"),d="[object Arguments]",m="[object Array]",g="[object Boolean]",y="[object Date]",v="[object Error]",b="[object Function]",w="[object Map]",x="[object Number]",A="[object Object]",E="[object RegExp]",j="[object Set]",C="[object String]",T="[object WeakMap]",S="[object ArrayBuffer]",_="[object Float32Array]",O="[object Float64Array]",k="[object Int8Array]",$="[object Int16Array]",D="[object Int32Array]",L="[object Uint8Array]",N="[object Uint8ClampedArray]",P="[object Uint16Array]",I="[object Uint32Array]",R={};R[d]=R[m]=R[S]=R[g]=R[y]=R[_]=R[O]=R[k]=R[$]=R[D]=R[x]=R[A]=R[E]=R[C]=R[L]=R[N]=R[P]=R[I]=!0,R[v]=R[b]=R[w]=R[j]=R[T]=!1;var M=Object.prototype,U=M.toString;t.exports=n},{"../lang/isArray":96,"../lang/isObject":99,"../object/keys":104,"./arrayCopy":29,"./arrayEach":30,"./baseCopy":34,"./baseForOwn":41,"./initCloneArray":75,"./initCloneByTag":76,"./initCloneObject":77,"./isHostObject":78}],34:[function(e,t){function n(e,t,n){n||(n=t,t={});for(var r=-1,i=n.length;++r<i;){var o=n[r];t[o]=e[o]}return t}t.exports=n},{}],35:[function(e,t){(function(n){var r=e("../lang/isObject"),i=function(){function e(){}return function(t){if(r(t)){e.prototype=t;var i=new e;e.prototype=null}return i||n.Object()}}();t.exports=i}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../lang/isObject":99}],36:[function(e,t){var n=e("./baseForOwn"),r=e("./createBaseEach"),i=r(n);t.exports=i},{"./baseForOwn":41,"./createBaseEach":60}],37:[function(e,t){function n(e,t,n,r){var i;return n(e,function(e,n,o){return t(e,n,o)?(i=r?n:e,!1):void 0}),i}t.exports=n},{}],38:[function(e,t){function n(e,t,n){for(var r=e.length,i=n?r:-1;n?i--:++i<r;)if(t(e[i],i,e))return i;return-1}t.exports=n},{}],39:[function(e,t){var n=e("./createBaseFor"),r=n();t.exports=r},{"./createBaseFor":61}],40:[function(e,t){function n(e,t){return r(e,t,i)}var r=e("./baseFor"),i=e("../object/keysIn");t.exports=n},{"../object/keysIn":105,"./baseFor":39}],41:[function(e,t){function n(e,t){return r(e,t,i)}var r=e("./baseFor"),i=e("../object/keys");t.exports=n},{"../object/keys":104,"./baseFor":39}],42:[function(e,t){function n(e,t,n){if(t!==t)return r(e,n);for(var i=n-1,o=e.length;++i<o;)if(e[i]===t)return i;return-1}var r=e("./indexOfNaN");t.exports=n},{"./indexOfNaN":74}],43:[function(e,t){function n(e,t,i,o,a,s){if(e===t)return 0!==e||1/e==1/t;var l=typeof e,u=typeof t;return"function"!=l&&"object"!=l&&"function"!=u&&"object"!=u||null==e||null==t?e!==e&&t!==t:r(e,t,n,i,o,a,s)}var r=e("./baseIsEqualDeep");t.exports=n},{"./baseIsEqualDeep":44}],44:[function(e,t){function n(e,t,n,f,g,y,v){var b=a(e),w=a(t),x=c,A=c;b||(x=m.call(e),x==u?x=h:x!=h&&(b=l(e))),w||(A=m.call(t),A==u?A=h:A!=h&&(w=l(t)));var E=(x==h||g&&x==p)&&!s(e),j=(A==h||g&&A==p)&&!s(t),C=x==A;if(C&&!b&&!E)return i(e,t,x);if(g){if(!(C||E&&j))return!1}else{var T=E&&d.call(e,"__wrapped__"),S=j&&d.call(t,"__wrapped__");if(T||S)return n(T?e.value():e,S?t.value():t,f,g,y,v);
if(!C)return!1}y||(y=[]),v||(v=[]);for(var _=y.length;_--;)if(y[_]==e)return v[_]==t;y.push(e),v.push(t);var O=(b?r:o)(e,t,n,f,g,y,v);return y.pop(),v.pop(),O}var r=e("./equalArrays"),i=e("./equalByTag"),o=e("./equalObjects"),a=e("../lang/isArray"),s=e("./isHostObject"),l=e("../lang/isTypedArray"),u="[object Arguments]",c="[object Array]",p="[object Function]",h="[object Object]",f=Object.prototype,d=f.hasOwnProperty,m=f.toString;t.exports=n},{"../lang/isArray":96,"../lang/isTypedArray":102,"./equalArrays":69,"./equalByTag":70,"./equalObjects":71,"./isHostObject":78}],45:[function(e,t){function n(e){return"function"==typeof e||!1}t.exports=n},{}],46:[function(e,t){function n(e,t,n,i,o){for(var a=-1,s=t.length,l=!o;++a<s;)if(l&&i[a]?n[a]!==e[t[a]]:!(t[a]in e))return!1;for(a=-1;++a<s;){var u=t[a],c=e[u],p=n[a];if(l&&i[a])var h="undefined"!=typeof c||u in e;else h=o?o(c,p,u):void 0,"undefined"==typeof h&&(h=r(p,c,o,!0));if(!h)return!1}return!0}var r=e("./baseIsEqual");t.exports=n},{"./baseIsEqual":43}],47:[function(e,t){function n(){}t.exports=n},{}],48:[function(e,t){function n(e,t){var n=[];return r(e,function(e,r,i){n.push(t(e,r,i))}),n}var r=e("./baseEach");t.exports=n},{"./baseEach":36}],49:[function(e,t){function n(e){var t=a(e),n=t.length;if(!n)return i(!0);if(1==n){var l=t[0],u=e[l];if(o(u))return function(e){return null!=e&&e[l]===u&&("undefined"!=typeof u||l in s(e))}}for(var c=Array(n),p=Array(n);n--;)u=e[t[n]],c[n]=u,p[n]=o(u);return function(e){return null!=e&&r(s(e),t,c,p)}}var r=e("./baseIsMatch"),i=e("../utility/constant"),o=e("./isStrictComparable"),a=e("../object/keys"),s=e("./toObject");t.exports=n},{"../object/keys":104,"../utility/constant":108,"./baseIsMatch":46,"./isStrictComparable":83,"./toObject":92}],50:[function(e,t){function n(e,t){return i(t)?function(n){return null!=n&&n[e]===t&&("undefined"!=typeof t||e in o(n))}:function(n){return null!=n&&r(t,n[e],null,!0)}}var r=e("./baseIsEqual"),i=e("./isStrictComparable"),o=e("./toObject");t.exports=n},{"./baseIsEqual":43,"./isStrictComparable":83,"./toObject":92}],51:[function(e,t){function n(e){return function(t){return null==t?void 0:t[e]}}t.exports=n},{}],52:[function(e,t){var n=e("../utility/identity"),r=e("./metaMap"),i=r?function(e,t){return r.set(e,t),e}:n;t.exports=i},{"../utility/identity":109,"./metaMap":85}],53:[function(e,t){function n(e){return"string"==typeof e?e:null==e?"":e+""}t.exports=n},{}],54:[function(e,t){function n(e,t,n){var o=0,s=e?e.length:o;if("number"==typeof t&&t===t&&a>=s){for(;s>o;){var l=o+s>>>1,u=e[l];(n?t>=u:t>u)?o=l+1:s=l}return s}return r(e,t,i,n)}var r=e("./binaryIndexBy"),i=e("../utility/identity"),o=Math.pow(2,32)-1,a=o>>>1;t.exports=n},{"../utility/identity":109,"./binaryIndexBy":55}],55:[function(e,t){function n(e,t,n,o){t=n(t);for(var s=0,l=e?e.length:0,u=t!==t,c="undefined"==typeof t;l>s;){var p=r((s+l)/2),h=n(e[p]),f=h===h;if(u)var d=f||o;else d=c?f&&(o||"undefined"!=typeof h):o?t>=h:t>h;d?s=p+1:l=p}return i(l,a)}var r=Math.floor,i=Math.min,o=Math.pow(2,32)-1,a=o-1;t.exports=n},{}],56:[function(e,t){function n(e,t,n){if("function"!=typeof e)return r;if("undefined"==typeof t)return e;switch(n){case 1:return function(n){return e.call(t,n)};case 3:return function(n,r,i){return e.call(t,n,r,i)};case 4:return function(n,r,i,o){return e.call(t,n,r,i,o)};case 5:return function(n,r,i,o,a){return e.call(t,n,r,i,o,a)}}return function(){return e.apply(t,arguments)}}var r=e("../utility/identity");t.exports=n},{"../utility/identity":109}],57:[function(e,t){(function(n){function r(e){return s.call(e,0)}var i=e("../utility/constant"),o=e("../lang/isNative"),a=o(a=n.ArrayBuffer)&&a,s=o(s=a&&new a(0).slice)&&s,l=Math.floor,u=o(u=n.Uint8Array)&&u,c=function(){try{var e=o(e=n.Float64Array)&&e,t=new e(new a(10),0,1)&&e}catch(r){}return t}(),p=c?c.BYTES_PER_ELEMENT:0;s||(r=a&&u?function(e){var t=e.byteLength,n=c?l(t/p):0,r=n*p,i=new a(t);if(n){var o=new c(i,0,n);o.set(new c(e,0,n))}return t!=r&&(o=new u(i,r),o.set(new u(e,r))),i}:i(null)),t.exports=r}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../lang/isNative":98,"../utility/constant":108}],58:[function(e,t){function n(e,t,n){for(var i=n.length,o=-1,a=r(e.length-i,0),s=-1,l=t.length,u=Array(a+l);++s<l;)u[s]=t[s];for(;++o<i;)u[n[o]]=e[o];for(;a--;)u[s++]=e[o++];return u}var r=Math.max;t.exports=n},{}],59:[function(e,t){function n(e,t,n){for(var i=-1,o=n.length,a=-1,s=r(e.length-o,0),l=-1,u=t.length,c=Array(s+u);++a<s;)c[a]=e[a];for(var p=a;++l<u;)c[p+l]=t[l];for(;++i<o;)c[p+n[i]]=e[a++];return c}var r=Math.max;t.exports=n},{}],60:[function(e,t){function n(e,t){return function(n,o){var a=n?n.length:0;if(!r(a))return e(n,o);for(var s=t?a:-1,l=i(n);(t?s--:++s<a)&&o(l[s],s,l)!==!1;);return n}}var r=e("./isLength"),i=e("./toObject");t.exports=n},{"./isLength":81,"./toObject":92}],61:[function(e,t){function n(e){return function(t,n,i){for(var o=r(t),a=i(t),s=a.length,l=e?s:-1;e?l--:++l<s;){var u=a[l];if(n(o[u],u,o)===!1)break}return t}}var r=e("./toObject");t.exports=n},{"./toObject":92}],62:[function(e,t){(function(n){function r(e,t){function r(){var i=this&&this!==n&&this instanceof r?o:e;return i.apply(t,arguments)}var o=i(e);return r}var i=e("./createCtorWrapper");t.exports=r}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./createCtorWrapper":63}],63:[function(e,t){function n(e){return function(){var t=r(e.prototype),n=e.apply(t,arguments);return i(n)?n:t}}var r=e("./baseCreate"),i=e("../lang/isObject");t.exports=n},{"../lang/isObject":99,"./baseCreate":35}],64:[function(e,t){function n(e,t){return function(n,s,l){if(s=r(s,l,3),a(n)){var u=o(n,s,t);return u>-1?n[u]:void 0}return i(n,s,e)}}var r=e("./baseCallback"),i=e("./baseFind"),o=e("./baseFindIndex"),a=e("../lang/isArray");t.exports=n},{"../lang/isArray":96,"./baseCallback":32,"./baseFind":37,"./baseFindIndex":38}],65:[function(e,t){function n(e,t){return function(n,o,a){return"function"==typeof o&&"undefined"==typeof a&&i(n)?e(n,o):t(n,r(o,a,3))}}var r=e("./bindCallback"),i=e("../lang/isArray");t.exports=n},{"../lang/isArray":96,"./bindCallback":56}],66:[function(e,t){(function(n){function r(e,t,x,A,E,j,C,T,S,_){function O(){for(var d=arguments.length,m=d,g=Array(d);m--;)g[m]=arguments[m];if(A&&(g=o(g,A,E)),j&&(g=a(g,j,C)),L||P){var b=O.placeholder,M=c(g,b);if(d-=M.length,_>d){var U=T?i(T):null,H=w(_-d,0),F=L?M:null,B=L?null:M,q=L?g:null,z=L?null:g;t|=L?y:v,t&=~(L?v:y),N||(t&=~(h|f));var V=[e,t,x,q,F,z,B,U,S,H],W=r.apply(void 0,V);return l(e)&&p(W,V),W.placeholder=b,W}}var J=$?x:this;D&&(e=J[R]),T&&(g=u(g,T)),k&&S<g.length&&(g.length=S);var Y=this&&this!==n&&this instanceof O?I||s(e):e;return Y.apply(J,g)}var k=t&b,$=t&h,D=t&f,L=t&m,N=t&d,P=t&g,I=!D&&s(e),R=e;return O}var i=e("./arrayCopy"),o=e("./composeArgs"),a=e("./composeArgsRight"),s=e("./createCtorWrapper"),l=e("./isLaziable"),u=e("./reorder"),c=e("./replaceHolders"),p=e("./setData"),h=1,f=2,d=4,m=8,g=16,y=32,v=64,b=128,w=Math.max;t.exports=r}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./arrayCopy":29,"./composeArgs":58,"./composeArgsRight":59,"./createCtorWrapper":63,"./isLaziable":80,"./reorder":87,"./replaceHolders":88,"./setData":89}],67:[function(e,t){(function(n){function r(e,t,r,a){function s(){for(var t=-1,i=arguments.length,o=-1,c=a.length,p=Array(i+c);++o<c;)p[o]=a[o];for(;i--;)p[o++]=arguments[++t];var h=this&&this!==n&&this instanceof s?u:e;return h.apply(l?r:this,p)}var l=t&o,u=i(e);return s}var i=e("./createCtorWrapper"),o=1;t.exports=r}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./createCtorWrapper":63}],68:[function(e,t){function n(e,t,n,g,y,v,b,w){var x=t&p;if(!x&&"function"!=typeof e)throw new TypeError(d);var A=g?g.length:0;if(A||(t&=~(h|f),g=y=null),A-=y?y.length:0,t&f){var E=g,j=y;g=y=null}var C=x?null:s(e),T=[e,t,n,g,y,E,j,v,b,w];if(C&&(l(T,C),t=T[1],w=T[9]),T[9]=null==w?x?0:e.length:m(w-A,0)||0,t==c)var S=i(T[0],T[2]);else S=t!=h&&t!=(c|h)||T[4].length?o.apply(void 0,T):a.apply(void 0,T);var _=C?r:u;return _(S,T)}var r=e("./baseSetData"),i=e("./createBindWrapper"),o=e("./createHybridWrapper"),a=e("./createPartialWrapper"),s=e("./getData"),l=e("./mergeData"),u=e("./setData"),c=1,p=2,h=32,f=64,d="Expected a function",m=Math.max;t.exports=n},{"./baseSetData":52,"./createBindWrapper":62,"./createHybridWrapper":66,"./createPartialWrapper":67,"./getData":72,"./mergeData":84,"./setData":89}],69:[function(e,t){function n(e,t,n,r,i,o,a){var s=-1,l=e.length,u=t.length,c=!0;if(l!=u&&!(i&&u>l))return!1;for(;c&&++s<l;){var p=e[s],h=t[s];if(c=void 0,r&&(c=i?r(h,p,s):r(p,h,s)),"undefined"==typeof c)if(i)for(var f=u;f--&&(h=t[f],!(c=p&&p===h||n(p,h,r,i,o,a))););else c=p&&p===h||n(p,h,r,i,o,a)}return!!c}t.exports=n},{}],70:[function(e,t){function n(e,t,n){switch(n){case r:case i:return+e==+t;case o:return e.name==t.name&&e.message==t.message;case a:return e!=+e?t!=+t:0==e?1/e==1/t:e==+t;case s:case l:return e==t+""}return!1}var r="[object Boolean]",i="[object Date]",o="[object Error]",a="[object Number]",s="[object RegExp]",l="[object String]";t.exports=n},{}],71:[function(e,t){function n(e,t,n,i,a,s,l){var u=r(e),c=u.length,p=r(t),h=p.length;if(c!=h&&!a)return!1;for(var f=a,d=-1;++d<c;){var m=u[d],g=a?m in t:o.call(t,m);if(g){var y=e[m],v=t[m];g=void 0,i&&(g=a?i(v,y,m):i(y,v,m)),"undefined"==typeof g&&(g=y&&y===v||n(y,v,i,a,s,l))}if(!g)return!1;f||(f="constructor"==m)}if(!f){var b=e.constructor,w=t.constructor;if(b!=w&&"constructor"in e&&"constructor"in t&&!("function"==typeof b&&b instanceof b&&"function"==typeof w&&w instanceof w))return!1}return!0}var r=e("../object/keys"),i=Object.prototype,o=i.hasOwnProperty;t.exports=n},{"../object/keys":104}],72:[function(e,t){var n=e("./metaMap"),r=e("../utility/noop"),i=n?function(e){return n.get(e)}:r;t.exports=i},{"../utility/noop":110,"./metaMap":85}],73:[function(e,t){var n=e("./baseProperty"),r=e("../utility/constant"),i=e("./realNames"),o=e("../support"),a=function(){return o.funcNames?"constant"==r.name?n("name"):function(e){for(var t=e.name,n=i[t],r=n?n.length:0;r--;){var o=n[r],a=o.func;if(null==a||a==e)return o.name}return t}:r("")}();t.exports=a},{"../support":107,"../utility/constant":108,"./baseProperty":51,"./realNames":86}],74:[function(e,t){function n(e,t,n){for(var r=e.length,i=t+(n?0:-1);n?i--:++i<r;){var o=e[i];if(o!==o)return i}return-1}t.exports=n},{}],75:[function(e,t){function n(e){var t=e.length,n=new e.constructor(t);return t&&"string"==typeof e[0]&&i.call(e,"index")&&(n.index=e.index,n.input=e.input),n}var r=Object.prototype,i=r.hasOwnProperty;t.exports=n},{}],76:[function(e,t){(function(n){function r(e,t,n){var r=e.constructor;switch(t){case c:return i(e);case o:case a:return new r(+e);case p:case h:case f:case d:case m:case g:case y:case v:case b:r instanceof r&&(r=x[t]);var A=e.buffer;return new r(n?i(A):A,e.byteOffset,e.length);case s:case u:return new r(e);case l:var E=new r(e.source,w.exec(e));E.lastIndex=e.lastIndex}return E}var i=e("./bufferClone"),o="[object Boolean]",a="[object Date]",s="[object Number]",l="[object RegExp]",u="[object String]",c="[object ArrayBuffer]",p="[object Float32Array]",h="[object Float64Array]",f="[object Int8Array]",d="[object Int16Array]",m="[object Int32Array]",g="[object Uint8Array]",y="[object Uint8ClampedArray]",v="[object Uint16Array]",b="[object Uint32Array]",w=/\w*$/,x={};x[p]=n.Float32Array,x[h]=n.Float64Array,x[f]=n.Int8Array,x[d]=n.Int16Array,x[m]=n.Int32Array,x[g]=n.Uint8Array,x[y]=n.Uint8ClampedArray,x[v]=n.Uint16Array,x[b]=n.Uint32Array,t.exports=r}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./bufferClone":57}],77:[function(e,t){function n(e){var t=e.constructor;return"function"==typeof t&&t instanceof t||(t=Object),new t}t.exports=n},{}],78:[function(e,t){var n=function(){try{Object({toString:0}+"")}catch(e){return function(){return!1}}return function(e){return"function"!=typeof e.toString&&"string"==typeof(e+"")}}();t.exports=n},{}],79:[function(e,t){function n(e,t){return e=+e,t=null==t?r:t,e>-1&&e%1==0&&t>e}var r=Math.pow(2,53)-1;t.exports=n},{}],80:[function(e,t){function n(e){var t=i(e);return!!t&&e===o[t]&&t in r.prototype}var r=e("./LazyWrapper"),i=e("./getFuncName"),o=e("../chain/lodash");t.exports=n},{"../chain/lodash":20,"./LazyWrapper":27,"./getFuncName":73}],81:[function(e,t){function n(e){return"number"==typeof e&&e>-1&&e%1==0&&r>=e}var r=Math.pow(2,53)-1;t.exports=n},{}],82:[function(e,t){function n(e){return!!e&&"object"==typeof e}t.exports=n},{}],83:[function(e,t){function n(e){return e===e&&(0===e?1/e>0:!r(e))}var r=e("../lang/isObject");t.exports=n},{"../lang/isObject":99}],84:[function(e,t){function n(e,t){var n=e[1],d=t[1],m=n|d,g=c>m,y=d==c&&n==u||d==c&&n==p&&e[7].length<=t[8]||d==(c|p)&&n==u;if(!g&&!y)return e;d&s&&(e[2]=t[2],m|=n&s?0:l);var v=t[3];if(v){var b=e[3];e[3]=b?i(b,v,t[4]):r(v),e[4]=b?a(e[3],h):r(t[4])}return v=t[5],v&&(b=e[5],e[5]=b?o(b,v,t[6]):r(v),e[6]=b?a(e[5],h):r(t[6])),v=t[7],v&&(e[7]=r(v)),d&c&&(e[8]=null==e[8]?t[8]:f(e[8],t[8])),null==e[9]&&(e[9]=t[9]),e[0]=t[0],e[1]=m,e}var r=e("./arrayCopy"),i=e("./composeArgs"),o=e("./composeArgsRight"),a=e("./replaceHolders"),s=1,l=4,u=8,c=128,p=256,h="__lodash_placeholder__",f=Math.min;t.exports=n},{"./arrayCopy":29,"./composeArgs":58,"./composeArgsRight":59,"./replaceHolders":88}],85:[function(e,t){(function(n){var r=e("../lang/isNative"),i=r(i=n.WeakMap)&&i,o=i&&new i;t.exports=o}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../lang/isNative":98}],86:[function(e,t){var n={};t.exports=n},{}],87:[function(e,t){function n(e,t){for(var n=e.length,a=o(t.length,n),s=r(e);a--;){var l=t[a];e[a]=i(l,n)?s[l]:void 0}return e}var r=e("./arrayCopy"),i=e("./isIndex"),o=Math.min;t.exports=n},{"./arrayCopy":29,"./isIndex":79}],88:[function(e,t){function n(e,t){for(var n=-1,i=e.length,o=-1,a=[];++n<i;)e[n]===t&&(e[n]=r,a[++o]=n);return a}var r="__lodash_placeholder__";t.exports=n},{}],89:[function(e,t){var n=e("./baseSetData"),r=e("../date/now"),i=150,o=16,a=function(){var e=0,t=0;return function(a,s){var l=r(),u=o-(l-t);if(t=l,u>0){if(++e>=i)return a}else e=0;return n(a,s)}}();t.exports=a},{"../date/now":24,"./baseSetData":52}],90:[function(e,t){function n(e){var t;if(!a(e)||p.call(e)!=l||o(e)||!c.call(e,"constructor")&&(t=e.constructor,"function"==typeof t&&!(t instanceof t))||!s.argsTag&&i(e))return!1;var n;return s.ownLast?(r(e,function(e,t,r){return n=c.call(r,t),!1}),n!==!1):(r(e,function(e,t){n=t}),"undefined"==typeof n||c.call(e,n))}var r=e("./baseForIn"),i=e("../lang/isArguments"),o=e("./isHostObject"),a=e("./isObjectLike"),s=e("../support"),l="[object Object]",u=Object.prototype,c=u.hasOwnProperty,p=u.toString;t.exports=n},{"../lang/isArguments":95,"../support":107,"./baseForIn":40,"./isHostObject":78,"./isObjectLike":82}],91:[function(e,t){function n(e){for(var t=l(e),n=t.length,c=n&&e.length,h=c&&a(c)&&(i(e)||u.nonEnumStrings&&s(e)||u.nonEnumArgs&&r(e)),f=-1,d=[];++f<n;){var m=t[f];(h&&o(m,c)||p.call(e,m))&&d.push(m)}return d}var r=e("../lang/isArguments"),i=e("../lang/isArray"),o=e("./isIndex"),a=e("./isLength"),s=e("../lang/isString"),l=e("../object/keysIn"),u=e("../support"),c=Object.prototype,p=c.hasOwnProperty;t.exports=n},{"../lang/isArguments":95,"../lang/isArray":96,"../lang/isString":101,"../object/keysIn":105,"../support":107,"./isIndex":79,"./isLength":81}],92:[function(e,t){function n(e){if(o.unindexedChars&&i(e)){for(var t=-1,n=e.length,a=Object(e);++t<n;)a[t]=e.charAt(t);return a}return r(e)?e:Object(e)}var r=e("../lang/isObject"),i=e("../lang/isString"),o=e("../support");t.exports=n},{"../lang/isObject":99,"../lang/isString":101,"../support":107}],93:[function(e,t){function n(e){return e instanceof r?e.clone():new i(e.__wrapped__,e.__chain__,o(e.__actions__))}var r=e("./LazyWrapper"),i=e("./LodashWrapper"),o=e("./arrayCopy");t.exports=n},{"./LazyWrapper":27,"./LodashWrapper":28,"./arrayCopy":29}],94:[function(e,t){function n(e,t,n){return t="function"==typeof t&&i(t,n,1),r(e,!0,t)}var r=e("../internal/baseClone"),i=e("../internal/bindCallback");t.exports=n},{"../internal/baseClone":33,"../internal/bindCallback":56}],95:[function(e,t){function n(e){var t=i(e)?e.length:void 0;return r(t)&&u.call(e)==a}var r=e("../internal/isLength"),i=e("../internal/isObjectLike"),o=e("../support"),a="[object Arguments]",s=Object.prototype,l=s.hasOwnProperty,u=s.toString,c=s.propertyIsEnumerable;o.argsTag||(n=function(e){var t=i(e)?e.length:void 0;return r(t)&&l.call(e,"callee")&&!c.call(e,"callee")}),t.exports=n},{"../internal/isLength":81,"../internal/isObjectLike":82,"../support":107}],96:[function(e,t){var n=e("../internal/isLength"),r=e("./isNative"),i=e("../internal/isObjectLike"),o="[object Array]",a=Object.prototype,s=a.toString,l=r(l=Array.isArray)&&l,u=l||function(e){return i(e)&&n(e.length)&&s.call(e)==o};t.exports=u},{"../internal/isLength":81,"../internal/isObjectLike":82,"./isNative":98}],97:[function(e,t){(function(n){var r=e("../internal/baseIsFunction"),i=e("./isNative"),o="[object Function]",a=Object.prototype,s=a.toString,l=i(l=n.Uint8Array)&&l,u=r(/x/)||l&&!r(l)?function(e){return s.call(e)==o}:r;t.exports=u}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../internal/baseIsFunction":45,"./isNative":98}],98:[function(e,t){function n(e){return null==e?!1:c.call(e)==a?p.test(u.call(e)):o(e)&&(i(e)?p:s).test(e)}var r=e("../string/escapeRegExp"),i=e("../internal/isHostObject"),o=e("../internal/isObjectLike"),a="[object Function]",s=/^\[object .+?Constructor\]$/,l=Object.prototype,u=Function.prototype.toString,c=l.toString,p=RegExp("^"+r(c).replace(/toString|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");t.exports=n},{"../internal/isHostObject":78,"../internal/isObjectLike":82,"../string/escapeRegExp":106}],99:[function(e,t){function n(e){var t=typeof e;return"function"==t||!!e&&"object"==t}t.exports=n},{}],100:[function(e,t){var n=e("./isArguments"),r=e("./isNative"),i=e("../internal/shimIsPlainObject"),o=e("../support"),a="[object Object]",s=Object.prototype,l=s.toString,u=r(u=Object.getPrototypeOf)&&u,c=u?function(e){if(!e||l.call(e)!=a||!o.argsTag&&n(e))return!1;var t=e.valueOf,s=r(t)&&(s=u(t))&&u(s);return s?e==s||u(e)==s:i(e)}:i;t.exports=c},{"../internal/shimIsPlainObject":90,"../support":107,"./isArguments":95,"./isNative":98}],101:[function(e,t){function n(e){return"string"==typeof e||r(e)&&a.call(e)==i}var r=e("../internal/isObjectLike"),i="[object String]",o=Object.prototype,a=o.toString;t.exports=n},{"../internal/isObjectLike":82}],102:[function(e,t){function n(e){return i(e)&&r(e.length)&&!!_[k.call(e)]}var r=e("../internal/isLength"),i=e("../internal/isObjectLike"),o="[object Arguments]",a="[object Array]",s="[object Boolean]",l="[object Date]",u="[object Error]",c="[object Function]",p="[object Map]",h="[object Number]",f="[object Object]",d="[object RegExp]",m="[object Set]",g="[object String]",y="[object WeakMap]",v="[object ArrayBuffer]",b="[object Float32Array]",w="[object Float64Array]",x="[object Int8Array]",A="[object Int16Array]",E="[object Int32Array]",j="[object Uint8Array]",C="[object Uint8ClampedArray]",T="[object Uint16Array]",S="[object Uint32Array]",_={};_[b]=_[w]=_[x]=_[A]=_[E]=_[j]=_[C]=_[T]=_[S]=!0,_[o]=_[a]=_[v]=_[s]=_[l]=_[u]=_[c]=_[p]=_[h]=_[f]=_[d]=_[m]=_[g]=_[y]=!1;var O=Object.prototype,k=O.toString;t.exports=n},{"../internal/isLength":81,"../internal/isObjectLike":82}],103:[function(e,t){function n(e){return"undefined"==typeof e}t.exports=n},{}],104:[function(e,t){var n=e("../internal/isLength"),r=e("../lang/isNative"),i=e("../lang/isObject"),o=e("../internal/shimKeys"),a=e("../support"),s=r(s=Object.keys)&&s,l=s?function(e){if(e)var t=e.constructor,r=e.length;return"function"==typeof t&&t.prototype===e||("function"==typeof e?a.enumPrototypes:r&&n(r))?o(e):i(e)?s(e):[]}:o;t.exports=l},{"../internal/isLength":81,"../internal/shimKeys":91,"../lang/isNative":98,"../lang/isObject":99,"../support":107}],105:[function(e,t){function n(e){if(null==e)return[];u(e)||(e=Object(e));var t=e.length;t=t&&l(t)&&(o(e)||p.nonEnumStrings&&c(e)||p.nonEnumArgs&&i(e))&&t||0;for(var n=e.constructor,r=-1,h=a(n)&&n.prototype||E,f=h===e,d=Array(t),g=t>0,y=p.enumErrorProps&&(e===A||e instanceof Error),b=p.enumPrototypes&&a(e);++r<t;)d[r]=r+"";for(var _ in e)b&&"prototype"==_||y&&("message"==_||"name"==_)||g&&s(_,t)||"constructor"==_&&(f||!C.call(e,_))||d.push(_);if(p.nonEnumShadows&&e!==E){var O=e===j?w:e===A?m:T.call(e),k=S[O]||S[v];for(O==v&&(h=E),t=x.length;t--;){_=x[t];var $=k[_];f&&$||($?!C.call(e,_):e[_]===h[_])||d.push(_)}}return d}var r=e("../internal/arrayEach"),i=e("../lang/isArguments"),o=e("../lang/isArray"),a=e("../lang/isFunction"),s=e("../internal/isIndex"),l=e("../internal/isLength"),u=e("../lang/isObject"),c=e("../lang/isString"),p=e("../support"),h="[object Array]",f="[object Boolean]",d="[object Date]",m="[object Error]",g="[object Function]",y="[object Number]",v="[object Object]",b="[object RegExp]",w="[object String]",x=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],A=Error.prototype,E=Object.prototype,j=String.prototype,C=E.hasOwnProperty,T=E.toString,S={};S[h]=S[d]=S[y]={constructor:!0,toLocaleString:!0,toString:!0,valueOf:!0},S[f]=S[w]={constructor:!0,toString:!0,valueOf:!0},S[m]=S[g]=S[b]={constructor:!0,toString:!0},S[v]={constructor:!0},r(x,function(e){for(var t in S)if(C.call(S,t)){var n=S[t];n[e]=C.call(n,e)}}),t.exports=n},{"../internal/arrayEach":30,"../internal/isIndex":79,"../internal/isLength":81,"../lang/isArguments":95,"../lang/isArray":96,"../lang/isFunction":97,"../lang/isObject":99,"../lang/isString":101,"../support":107}],106:[function(e,t){function n(e){return e=r(e),e&&o.test(e)?e.replace(i,"\\$&"):e}var r=e("../internal/baseToString"),i=/[.*+?^${}()|[\]\/\\]/g,o=RegExp(i.source);t.exports=n},{"../internal/baseToString":53}],107:[function(e,t){(function(e){var n="[object Arguments]",r="[object Object]",i=Array.prototype,o=Error.prototype,a=Object.prototype,s=(s=e.window)&&s.document,l=a.toString,u=a.propertyIsEnumerable,c=i.splice,p={};!function(){var e=function(){this.x=1},t={0:1,length:1},i=[];e.prototype={valueOf:1,y:1};for(var a in new e)i.push(a);p.argsTag=l.call(arguments)==n,p.enumErrorProps=u.call(o,"message")||u.call(o,"name"),p.enumPrototypes=u.call(e,"prototype"),p.funcDecomp=/\bthis\b/.test(function(){return this}),p.funcNames="string"==typeof Function.name,p.nodeTag=l.call(s)!=r,p.nonEnumStrings=!u.call("x",0),p.nonEnumShadows=!/valueOf/.test(i),p.ownLast="x"!=i[0],p.spliceObjects=(c.call(t,0,1),!t[0]),p.unindexedChars="x"[0]+Object("x")[0]!="xx";try{p.dom=11===s.createDocumentFragment().nodeType}catch(h){p.dom=!1}try{p.nonEnumArgs=!u.call(arguments,1)}catch(h){p.nonEnumArgs=!0}}(0,0),t.exports=p}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],108:[function(e,t){function n(e){return function(){return e}}t.exports=n},{}],109:[function(e,t){function n(e){return e}t.exports=n},{}],110:[function(e,t){function n(){}t.exports=n},{}],111:[function(e,t){function n(){}function r(e){var t={}.toString.call(e);switch(t){case"[object File]":case"[object Blob]":case"[object FormData]":return!0;default:return!1}}function i(){if(g.XMLHttpRequest&&("file:"!=g.location.protocol||!g.ActiveXObject))return new XMLHttpRequest;try{return new ActiveXObject("Microsoft.XMLHTTP")}catch(e){}try{return new ActiveXObject("Msxml2.XMLHTTP.6.0")}catch(e){}try{return new ActiveXObject("Msxml2.XMLHTTP.3.0")}catch(e){}try{return new ActiveXObject("Msxml2.XMLHTTP")}catch(e){}return!1}function o(e){return e===Object(e)}function a(e){if(!o(e))return e;var t=[];for(var n in e)null!=e[n]&&t.push(encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t.join("&")}function s(e){for(var t,n,r={},i=e.split("&"),o=0,a=i.length;a>o;++o)n=i[o],t=n.split("="),r[decodeURIComponent(t[0])]=decodeURIComponent(t[1]);return r}function l(e){var t,n,r,i,o=e.split(/\r?\n/),a={};o.pop();for(var s=0,l=o.length;l>s;++s)n=o[s],t=n.indexOf(":"),r=n.slice(0,t).toLowerCase(),i=y(n.slice(t+1)),a[r]=i;return a}function u(e){return e.split(/ *; */).shift()}function c(e){return m(e.split(/ *; */),function(e,t){var n=t.split(/ *= */),r=n.shift(),i=n.shift();return r&&i&&(e[r]=i),e},{})}function p(e,t){t=t||{},this.req=e,this.xhr=this.req.xhr,this.text="HEAD"!=this.req.method?this.xhr.responseText:null,this.setStatusProperties(this.xhr.status),this.header=this.headers=l(this.xhr.getAllResponseHeaders()),this.header["content-type"]=this.xhr.getResponseHeader("content-type"),this.setHeaderProperties(this.header),this.body="HEAD"!=this.req.method?this.parseBody(this.text):null}function h(e,t){var n=this;d.call(this),this._query=this._query||[],this.method=e,this.url=t,this.header={},this._header={},this.on("end",function(){var e=null,t=null;try{t=new p(n)}catch(r){e=new Error("Parser is unable to parse the response"),e.parse=!0,e.original=r}n.callback(e,t)})}function f(e,t){return"function"==typeof t?new h("GET",e).end(t):1==arguments.length?new h("GET",e):new h(e,t)}var d=e("emitter"),m=e("reduce"),g="undefined"==typeof window?this:window,y="".trim?function(e){return e.trim()}:function(e){return e.replace(/(^\s*|\s*$)/g,"")};f.serializeObject=a,f.parseString=s,f.types={html:"text/html",json:"application/json",xml:"application/xml",urlencoded:"application/x-www-form-urlencoded",form:"application/x-www-form-urlencoded","form-data":"application/x-www-form-urlencoded"},f.serialize={"application/x-www-form-urlencoded":a,"application/json":JSON.stringify},f.parse={"application/x-www-form-urlencoded":s,"application/json":JSON.parse},p.prototype.get=function(e){return this.header[e.toLowerCase()]},p.prototype.setHeaderProperties=function(){var e=this.header["content-type"]||"";this.type=u(e);var t=c(e);for(var n in t)this[n]=t[n]},p.prototype.parseBody=function(e){var t=f.parse[this.type];return t&&e&&e.length?t(e):null},p.prototype.setStatusProperties=function(e){var t=e/100|0;this.status=e,this.statusType=t,this.info=1==t,this.ok=2==t,this.clientError=4==t,this.serverError=5==t,this.error=4==t||5==t?this.toError():!1,this.accepted=202==e,this.noContent=204==e||1223==e,this.badRequest=400==e,this.unauthorized=401==e,this.notAcceptable=406==e,this.notFound=404==e,this.forbidden=403==e},p.prototype.toError=function(){var e=this.req,t=e.method,n=e.url,r="cannot "+t+" "+n+" ("+this.status+")",i=new Error(r);return i.status=this.status,i.method=t,i.url=n,i},f.Response=p,d(h.prototype),h.prototype.use=function(e){return e(this),this},h.prototype.timeout=function(e){return this._timeout=e,this},h.prototype.clearTimeout=function(){return this._timeout=0,clearTimeout(this._timer),this},h.prototype.abort=function(){return this.aborted?void 0:(this.aborted=!0,this.xhr.abort(),this.clearTimeout(),this.emit("abort"),this)},h.prototype.set=function(e,t){if(o(e)){for(var n in e)this.set(n,e[n]);return this}return this._header[e.toLowerCase()]=t,this.header[e]=t,this},h.prototype.unset=function(e){return delete this._header[e.toLowerCase()],delete this.header[e],this},h.prototype.getHeader=function(e){return this._header[e.toLowerCase()]},h.prototype.type=function(e){return this.set("Content-Type",f.types[e]||e),this},h.prototype.accept=function(e){return this.set("Accept",f.types[e]||e),this},h.prototype.auth=function(e,t){var n=btoa(e+":"+t);return this.set("Authorization","Basic "+n),this},h.prototype.query=function(e){return"string"!=typeof e&&(e=a(e)),e&&this._query.push(e),this},h.prototype.field=function(e,t){return this._formData||(this._formData=new FormData),this._formData.append(e,t),this},h.prototype.attach=function(e,t,n){return this._formData||(this._formData=new FormData),this._formData.append(e,t,n),this},h.prototype.send=function(e){var t=o(e),n=this.getHeader("Content-Type");if(t&&o(this._data))for(var r in e)this._data[r]=e[r];else"string"==typeof e?(n||this.type("form"),n=this.getHeader("Content-Type"),this._data="application/x-www-form-urlencoded"==n?this._data?this._data+"&"+e:e:(this._data||"")+e):this._data=e;return t?(n||this.type("json"),this):this},h.prototype.callback=function(e,t){var n=this._callback;return this.clearTimeout(),2==n.length?n(e,t):e?this.emit("error",e):void n(t)},h.prototype.crossDomainError=function(){var e=new Error("Origin is not allowed by Access-Control-Allow-Origin");e.crossDomain=!0,this.callback(e)},h.prototype.timeoutError=function(){var e=this._timeout,t=new Error("timeout of "+e+"ms exceeded");t.timeout=e,this.callback(t)},h.prototype.withCredentials=function(){return this._withCredentials=!0,this},h.prototype.end=function(e){var t=this,o=this.xhr=i(),a=this._query.join("&"),s=this._timeout,l=this._formData||this._data;if(this._callback=e||n,o.onreadystatechange=function(){return 4==o.readyState?0==o.status?t.aborted?t.timeoutError():t.crossDomainError():void t.emit("end"):void 0},o.upload&&(o.upload.onprogress=function(e){e.percent=e.loaded/e.total*100,t.emit("progress",e)}),s&&!this._timer&&(this._timer=setTimeout(function(){t.abort()},s)),a&&(a=f.serializeObject(a),this.url+=~this.url.indexOf("?")?"&"+a:"?"+a),o.open(this.method,this.url,!0),this._withCredentials&&(o.withCredentials=!0),"GET"!=this.method&&"HEAD"!=this.method&&"string"!=typeof l&&!r(l)){var u=f.serialize[this.getHeader("Content-Type")];u&&(l=u(l))}for(var c in this.header)null!=this.header[c]&&o.setRequestHeader(c,this.header[c]);return this.emit("request",this),o.send(l),this},f.Request=h,f.get=function(e,t,n){var r=f("GET",e);return"function"==typeof t&&(n=t,t=null),t&&r.query(t),n&&r.end(n),r},f.head=function(e,t,n){var r=f("HEAD",e);return"function"==typeof t&&(n=t,t=null),t&&r.send(t),n&&r.end(n),r},f.del=function(e,t){var n=f("DELETE",e);return t&&n.end(t),n},f.patch=function(e,t,n){var r=f("PATCH",e);return"function"==typeof t&&(n=t,t=null),t&&r.send(t),n&&r.end(n),r},f.post=function(e,t,n){var r=f("POST",e);return"function"==typeof t&&(n=t,t=null),t&&r.send(t),n&&r.end(n),r},f.put=function(e,t,n){var r=f("PUT",e);return"function"==typeof t&&(n=t,t=null),t&&r.send(t),n&&r.end(n),r},t.exports=f},{emitter:112,reduce:113}],112:[function(e,t){function n(e){return e?r(e):void 0}function r(e){for(var t in n.prototype)e[t]=n.prototype[t];return e}t.exports=n,n.prototype.on=n.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks[e]=this._callbacks[e]||[]).push(t),this},n.prototype.once=function(e,t){function n(){r.off(e,n),t.apply(this,arguments)}var r=this;return this._callbacks=this._callbacks||{},n.fn=t,this.on(e,n),this},n.prototype.off=n.prototype.removeListener=n.prototype.removeAllListeners=n.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n=this._callbacks[e];if(!n)return this;if(1==arguments.length)return delete this._callbacks[e],this;for(var r,i=0;i<n.length;i++)if(r=n[i],r===t||r.fn===t){n.splice(i,1);break}return this},n.prototype.emit=function(e){this._callbacks=this._callbacks||{};var t=[].slice.call(arguments,1),n=this._callbacks[e];if(n){n=n.slice(0);for(var r=0,i=n.length;i>r;++r)n[r].apply(this,t)}return this},n.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks[e]||[]},n.prototype.hasListeners=function(e){return!!this.listeners(e).length}},{}],113:[function(e,t){t.exports=function(e,t,n){for(var r=0,i=e.length,o=3==arguments.length?n:e[r++];i>r;)o=t.call(null,o,e[r],++r,e);return o}},{}]},{},[1])(1)}),window.SwaggerUi=Backbone.Router.extend({dom_id:"swagger_ui",options:null,api:null,headerView:null,mainView:null,initialize:function(e){e=e||{},e.dom_id&&(this.dom_id=e.dom_id,delete e.dom_id),e.supportedSubmitMethods||(e.supportedSubmitMethods=["get","put","post","delete","head","options","patch"]),"string"==typeof e.oauth2RedirectUrl&&(window.oAuthRedirectUrl=e.redirectUrl),$("#"+this.dom_id).length||$("body").append('<div id="'+this.dom_id+'"></div>'),this.options=e,marked.setOptions({gfm:!0});
-var t=this;this.options.success=function(){return t.render()},this.options.progress=function(e){return t.showMessage(e)},this.options.failure=function(e){return t.onLoadFailure(e)},this.headerView=new SwaggerUi.Views.HeaderView({el:$("#header")}),this.headerView.on("update-swagger-ui",function(e){return t.updateSwaggerUi(e)})},setOption:function(e,t){this.options[e]=t},getOption:function(e){return this.options[e]},updateSwaggerUi:function(e){this.options.url=e.url,this.load()},load:function(){this.mainView&&this.mainView.clear();var e=this.options.url;e&&0!==e.indexOf("http")&&(e=this.buildUrl(window.location.href.toString(),e)),this.options.url=e,this.headerView.update(e),this.api=new SwaggerClient(this.options)},collapseAll:function(){Docs.collapseEndpointListForResource("")},listAll:function(){Docs.collapseOperationsForResource("")},expandAll:function(){Docs.expandOperationsForResource("")},render:function(){switch(this.showMessage("Finished Loading Resource Information. Rendering Swagger UI..."),this.mainView=new SwaggerUi.Views.MainView({model:this.api,el:$("#"+this.dom_id),swaggerOptions:this.options,router:this}).render(),this.showMessage(),this.options.docExpansion){case"full":this.expandAll();break;case"list":this.listAll()}this.renderGFM(),this.options.onComplete&&this.options.onComplete(this.api,this),setTimeout(Docs.shebang.bind(this),100)},buildUrl:function(e,t){if(0===t.indexOf("/")){var n=e.split("/");return e=n[0]+"//"+n[2],e+t}var r=e.length;return e.indexOf("?")>-1&&(r=Math.min(r,e.indexOf("?"))),e.indexOf("#")>-1&&(r=Math.min(r,e.indexOf("#"))),e=e.substring(0,r),-1!==e.indexOf("/",e.length-1)?e+t:e+"/"+t},showMessage:function(e){void 0===e&&(e=""),$("#message-bar").removeClass("message-fail"),$("#message-bar").addClass("message-success"),$("#message-bar").html(e)},onLoadFailure:function(e){void 0===e&&(e=""),$("#message-bar").removeClass("message-success"),$("#message-bar").addClass("message-fail");var t=$("#message-bar").html(e);return this.options.onFailure&&this.options.onFailure(e),t},renderGFM:function(){$(".markdown").each(function(){$(this).html(marked($(this).html()))})}}),window.SwaggerUi.Views={},function(){function e(e){"console"in window&&"function"==typeof window.console.warn&&console.warn(e)}window.authorizations={add:function(){if(e("Using window.authorizations is deprecated. Please use SwaggerUi.api.clientAuthorizations.add()."),"undefined"==typeof window.swaggerUi)throw new TypeError("window.swaggerUi is not defined");window.swaggerUi instanceof SwaggerUi&&window.swaggerUi.api.clientAuthorizations.add.apply(window.swaggerUi.api.clientAuthorizations,arguments)}},window.ApiKeyAuthorization=function(){e("window.ApiKeyAuthorization is deprecated. Please use SwaggerClient.ApiKeyAuthorization."),SwaggerClient.ApiKeyAuthorization.apply(window,arguments)},window.PasswordAuthorization=function(){e("window.PasswordAuthorization is deprecated. Please use SwaggerClient.PasswordAuthorization."),SwaggerClient.PasswordAuthorization.apply(window,arguments)}}(),function(e,t){"function"==typeof define&&define.amd?define(["b"],function(n){return e.SwaggerUi=t(n)}):"object"==typeof exports?module.exports=t(require("b")):e.SwaggerUi=t(e.b)}(this,function(){return SwaggerUi}),SwaggerUi.Views.ApiKeyButton=Backbone.View.extend({events:{"click #apikey_button":"toggleApiKeyContainer","click #apply_api_key":"applyApiKey"},initialize:function(e){this.options=e||{},this.router=this.options.router},render:function(){var e=this.template();return $(this.el).html(e(this.model)),this},applyApiKey:function(){var e=new SwaggerClient.ApiKeyAuthorization(this.model.name,$("#input_apiKey_entry").val(),this.model["in"]);this.router.api.clientAuthorizations.add(this.model.name,e),this.router.load(),$("#apikey_container").show()},toggleApiKeyContainer:function(){if($("#apikey_container").length){var e=$("#apikey_container").first();e.is(":visible")?e.hide():($(".auth_container").hide(),e.show())}},template:function(){return Handlebars.templates.apikey_button_view}}),SwaggerUi.Views.BasicAuthButton=Backbone.View.extend({initialize:function(e){this.options=e||{},this.router=this.options.router},render:function(){var e=this.template();return $(this.el).html(e(this.model)),this},events:{"click #basic_auth_button":"togglePasswordContainer","click #apply_basic_auth":"applyPassword"},applyPassword:function(){var e=$(".input_username").val(),t=$(".input_password").val(),n=new SwaggerClient.PasswordAuthorization("basic",e,t);this.router.api.clientAuthorizations.add(this.model.type,n),this.router.load(),$("#basic_auth_container").hide()},togglePasswordContainer:function(){if($("#basic_auth_container").length){var e=$("#basic_auth_container").show();e.is(":visible")?e.slideUp():($(".auth_container").hide(),e.show())}},template:function(){return Handlebars.templates.basic_auth_button_view}}),SwaggerUi.Views.ContentTypeView=Backbone.View.extend({initialize:function(){},render:function(){return $(this.el).html(Handlebars.templates.content_type(this.model)),$("label[for=contentType]",$(this.el)).text("Response Content Type"),this}}),SwaggerUi.Views.HeaderView=Backbone.View.extend({events:{"click #show-pet-store-icon":"showPetStore","click #show-wordnik-dev-icon":"showWordnikDev","click #explore":"showCustom","keyup #input_baseUrl":"showCustomOnKeyup","keyup #input_apiKey":"showCustomOnKeyup"},initialize:function(){},showPetStore:function(){this.trigger("update-swagger-ui",{url:"http://petstore.swagger.io/v2/swagger.json"})},showWordnikDev:function(){this.trigger("update-swagger-ui",{url:"http://api.wordnik.com/v4/resources.json"})},showCustomOnKeyup:function(e){13===e.keyCode&&this.showCustom()},showCustom:function(e){e&&e.preventDefault(),this.trigger("update-swagger-ui",{url:$("#input_baseUrl").val(),apiKey:$("#input_apiKey").val()})},update:function(e,t,n){void 0===n&&(n=!1),$("#input_baseUrl").val(e),n&&this.trigger("update-swagger-ui",{url:e})}}),SwaggerUi.Views.MainView=Backbone.View.extend({apisSorter:{alpha:function(e,t){return e.name.localeCompare(t.name)}},operationsSorters:{alpha:function(e,t){return e.path.localeCompare(t.path)},method:function(e,t){return e.method.localeCompare(t.method)}},initialize:function(e){var t,n,r,i;if(e=e||{},this.router=e.router,e.swaggerOptions.apisSorter&&(t=e.swaggerOptions.apisSorter,n=_.isFunction(t)?t:this.apisSorter[t],_.isFunction(n)&&this.model.apisArray.sort(n)),e.swaggerOptions.operationsSorter&&(t=e.swaggerOptions.operationsSorter,n=_.isFunction(t)?t:this.operationsSorters[t],_.isFunction(n)))for(r in this.model.apisArray)this.model.apisArray[r].operationsArray.sort(n);this.model.auths=[];for(r in this.model.securityDefinitions)i=this.model.securityDefinitions[r],this.model.auths.push({name:r,type:i.type,value:i});"2.0"===this.model.swaggerVersion&&(this.model.validatorUrl="validatorUrl"in e.swaggerOptions?e.swaggerOptions.validatorUrl:this.model.url.indexOf("localhost")>0?null:"http://online.swagger.io/validator")},render:function(){if(this.model.securityDefinitions)for(var e in this.model.securityDefinitions){var t,n=this.model.securityDefinitions[e];"apiKey"===n.type&&0===$("#apikey_button").length&&(t=new SwaggerUi.Views.ApiKeyButton({model:n,router:this.router}).render().el,$(".auth_main_container").append(t)),"basicAuth"===n.type&&0===$("#basic_auth_button").length&&(t=new SwaggerUi.Views.BasicAuthButton({model:n,router:this.router}).render().el,$(".auth_main_container").append(t))}$(this.el).html(Handlebars.templates.main(this.model));for(var r={},i=0,o=0;o<this.model.apisArray.length;o++){for(var a=this.model.apisArray[o],s=a.name;"undefined"!=typeof r[s];)s=s+"_"+i,i+=1;a.id=s,r[s]=a,this.addResource(a,this.model.auths)}return $(".propWrap").hover(function(){$(".optionsWrapper",$(this)).show()},function(){$(".optionsWrapper",$(this)).hide()}),this},addResource:function(e,t){e.id=e.id.replace(/\s/g,"_");var n=new SwaggerUi.Views.ResourceView({model:e,router:this.router,tagName:"li",id:"resource_"+e.id,className:"resource",auths:t,swaggerOptions:this.options.swaggerOptions});$("#resources").append(n.render().el)},clear:function(){$(this.el).html("")}}),SwaggerUi.Views.OperationView=Backbone.View.extend({invocationUrl:null,events:{"submit .sandbox":"submitOperation","click .submit":"submitOperation","click .response_hider":"hideResponse","click .toggleOperation":"toggleOperationContent","mouseenter .api-ic":"mouseEnter","mouseout .api-ic":"mouseExit"},initialize:function(e){return e=e||{},this.router=e.router,this.auths=e.auths,this.parentId=this.model.parentId,this.nickname=this.model.nickname,this.model.encodedParentId=encodeURIComponent(this.parentId),this},mouseEnter:function(e){var t=$(this.el).find(".content"),n=e.pageX,r=e.pageY,i=$(window).scrollLeft(),o=$(window).scrollTop(),a=i+$(window).width(),s=o+$(window).height(),l=t.width(),u=t.height();n+l>a&&(n=a-l),i>n&&(n=i),r+u>s&&(r=s-u),o>r&&(r=o);var c={};c.top=r,c.left=n,t.css(c),$(e.currentTarget.parentNode).find("#api_information_panel").show()},mouseExit:function(e){$(e.currentTarget.parentNode).find("#api_information_panel").hide()},render:function(){var e,t,n,r,i,o,a,s,l,u,c,p,h,f,d,m,g,y,v,b,w,x,A,E,j,C,T,S,_,O,k,D,L,N,P,I,R,M;if(o=jQuery.inArray(this.model.method,this.model.supportedSubmitMethods())>=0,o||(this.model.isReadOnly=!0),this.model.description=this.model.description||this.model.notes,this.model.oauth=null,m=this.model.authorizations||this.model.security)if(Array.isArray(m))for(l=0,u=m.length;u>l;l++){n=m[l];for(s in n){t=n[s];for(e in this.auths)if(t=this.auths[e],"oauth2"===t.type){this.model.oauth={},this.model.oauth.scopes=[],A=t.value.scopes;for(a in A)R=A[a],D=n[s].indexOf(a),D>=0&&(y={scope:a,description:R},this.model.oauth.scopes.push(y))}}}else for(a in m)if(R=m[a],"oauth2"===a)for(null===this.model.oauth&&(this.model.oauth={}),void 0===this.model.oauth.scopes&&(this.model.oauth.scopes=[]),d=0,c=R.length;c>d;d++)y=R[d],this.model.oauth.scopes.push(y);if("undefined"!=typeof this.model.responses){this.model.responseMessages=[],E=this.model.responses;for(r in E)M=E[r],O=null,k=this.model.responses[r].schema,k&&k.$ref&&(O=k.$ref,0===O.indexOf("#/definitions/")&&(O=O.substring("#/definitions/".length))),this.model.responseMessages.push({code:r,message:M.description,responseModel:O})}if("undefined"==typeof this.model.responseMessages&&(this.model.responseMessages=[]),L=null,this.model.successResponse){P=this.model.successResponse;for(s in P)M=P[s],this.model.successCode=s,"object"==typeof M&&"function"==typeof M.createJSONSample&&(L={sampleJSON:JSON.stringify(M.createJSONSample(),void 0,2),isParam:!1,signature:M.getMockSignature()})}else this.model.responseClassSignature&&"string"!==this.model.responseClassSignature&&(L={sampleJSON:this.model.responseSampleJSON,isParam:!1,signature:this.model.responseClassSignature});for($(this.el).html(Handlebars.templates.operation(this.model)),L?(_=new SwaggerUi.Views.SignatureView({model:L,router:this.router,tagName:"div"}),$(".model-signature",$(this.el)).append(_.render().el)):(this.model.responseClassSignature="string",$(".model-signature",$(this.el)).html(this.model.type)),i={isParam:!1},i.consumes=this.model.consumes,i.produces=this.model.produces,j=this.model.parameters,g=0,p=j.length;p>g;g++)b=j[g],I=b.type||b.dataType||"","undefined"==typeof I&&(O=b.schema,O&&O.$ref&&(x=O.$ref,I=0===x.indexOf("#/definitions/")?x.substring("#/definitions/".length):x)),I&&"file"===I.toLowerCase()&&(i.consumes||(i.consumes="multipart/form-data")),b.type=I;for(S=new SwaggerUi.Views.ResponseContentTypeView({model:i,router:this.router}),$(".response-content-type",$(this.el)).append(S.render().el),C=this.model.parameters,v=0,h=C.length;h>v;v++)b=C[v],this.addParameter(b,i.consumes);for(T=this.model.responseMessages,w=0,f=T.length;f>w;w++)N=T[w],this.addStatusCode(N);return this},addParameter:function(e,t){e.consumes=t;var n=new SwaggerUi.Views.ParameterView({model:e,tagName:"tr",readOnly:this.model.isReadOnly});$(".operation-params",$(this.el)).append(n.render().el)},addStatusCode:function(e){var t=new SwaggerUi.Views.StatusCodeView({model:e,tagName:"tr",router:this.router});$(".operation-status",$(this.el)).append(t.render().el)},submitOperation:function(e){var t,n,r,i,o,a,s,l,u,c,p,h,f,d,m,g;if(null!==e&&e.preventDefault(),n=$(".sandbox",$(this.el)),t=!0,n.find("input.required").each(function(){$(this).removeClass("error"),""===jQuery.trim($(this).val())&&($(this).addClass("error"),$(this).wiggle({callback:function(e){return function(){$(e).focus()}}(this)}),t=!1)}),n.find("textarea.required").each(function(){$(this).removeClass("error"),""===jQuery.trim($(this).val())&&($(this).addClass("error"),$(this).wiggle({callback:function(e){return function(){return $(e).focus()}}(this)}),t=!1)}),t){for(u={},h={parent:this},r=!1,f=n.find("input"),i=0,o=f.length;o>i;i++)p=f[i],null!==p.value&&jQuery.trim(p.value).length>0&&(u[p.name]=p.value),"file"===p.type&&(u[p.name]=p.files[0],r=!0);for(d=n.find("textarea"),l=0,a=d.length;a>l;l++)p=d[l],null!==p.value&&jQuery.trim(p.value).length>0&&(u[p.name]=p.value);for(m=n.find("select"),c=0,s=m.length;s>c;c++)p=m[c],g=this.getSelectedValue(p),null!==g&&jQuery.trim(g).length>0&&(u[p.name]=g);return h.responseContentType=$("div select[name=responseContentType]",$(this.el)).val(),h.requestContentType=$("div select[name=parameterContentType]",$(this.el)).val(),$(".response_throbber",$(this.el)).show(),r?this.handleFileUpload(u,n):this.model["do"](u,h,this.showCompleteStatus,this.showErrorStatus,this)}},success:function(e,t){t.showCompleteStatus(e)},handleFileUpload:function(e,t){var n,r,i,o,a,s,l,u,c,p,h,f,d,m,g,y,v,b,w;for(y=t.serializeArray(),o=0,a=y.length;a>o;o++)h=y[o],null!==h.value&&jQuery.trim(h.value).length>0&&(e[h.name]=h.value);for(n=new FormData,g=0,v=this.model.parameters,c=0,s=v.length;s>c;c++)m=v[c],("form"===m.paramType||"formData"===m["in"])&&"file"!==m.type.toLowerCase()&&void 0!==e[m.name]&&n.append(m.name,e[m.name]);for(i={},b=this.model.parameters,p=0,l=b.length;l>p;p++)m=b[p],"header"===m.paramType&&(i[m.name]=e[m.name]);for(w=t.find('input[type~="file"]'),d=0,u=w.length;u>d;d++)r=w[d],"undefined"!=typeof r.files[0]&&(n.append($(r).attr("name"),r.files[0]),g+=1);return this.invocationUrl=this.model.supportHeaderParams()?(i=this.model.getHeaderParams(e),delete i["Content-Type"],this.model.urlify(e,!1)):this.model.urlify(e,!0),$(".request_url",$(this.el)).html("<pre></pre>"),$(".request_url pre",$(this.el)).text(this.invocationUrl),f={type:this.model.method,url:this.invocationUrl,headers:i,data:n,dataType:"json",contentType:!1,processData:!1,error:function(e){return function(t){return e.showErrorStatus(e.wrap(t),e)}}(this),success:function(e){return function(t){return e.showResponse(t,e)}}(this),complete:function(e){return function(t){return e.showCompleteStatus(e.wrap(t),e)}}(this)},window.authorizations&&window.authorizations.apply(f),jQuery.ajax(f),!1},wrap:function(e){var t,n,r,i,o,a,s;for(r={},n=e.getAllResponseHeaders().split("\r"),o=0,a=n.length;a>o;o++)i=n[o],t=i.match(/^([^:]*?):(.*)$/),t||(t=[]),t.shift(),void 0!==t[0]&&void 0!==t[1]&&(r[t[0].trim()]=t[1].trim());return s={},s.content={},s.content.data=e.responseText,s.headers=r,s.request={},s.request.url=this.invocationUrl,s.status=e.status,s},getSelectedValue:function(e){if(e.multiple){for(var t=[],n=0,r=e.options.length;r>n;n++){var i=e.options[n];i.selected&&t.push(i.value)}return t.length>0?t:null}return e.value},hideResponse:function(e){e&&e.preventDefault(),$(".response",$(this.el)).slideUp(),$(".response_hider",$(this.el)).fadeOut()},showResponse:function(e){var t=JSON.stringify(e,null," ").replace(/\n/g,"<br>");$(".response_body",$(this.el)).html(_.escape(t))},showErrorStatus:function(e,t){t.showStatus(e)},showCompleteStatus:function(e,t){t.showStatus(e)},formatXml:function(e){var t,n,r,i,o,a,s,l,u,c,p,h,f;for(p=/(>)(<)(\/*)/g,f=/[ ]*(.*)[ ]+\n/g,t=/(<.+>)(.+\n)/g,e=e.replace(p,"$1\n$2$3").replace(f,"$1\n").replace(t,"$1\n$2"),c=0,r="",l=e.split("\n"),i=0,a="other",h={"single->single":0,"single->closing":-1,"single->opening":0,"single->other":0,"closing->single":0,"closing->closing":-1,"closing->opening":0,"closing->other":0,"opening->single":1,"opening->closing":0,"opening->opening":1,"opening->other":1,"other->single":0,"other->closing":-1,"other->opening":0,"other->other":0},n=function(e){var t,n,o,s,l,u,c;u={single:Boolean(e.match(/<.+\/>/)),closing:Boolean(e.match(/<\/.+>/)),opening:Boolean(e.match(/<[^!?].*>/))},l=function(){var e;e=[];for(o in u)c=u[o],c&&e.push(o);return e}()[0],l=void 0===l?"other":l,t=a+"->"+l,a=l,s="",i+=h[t],s=function(){var e,t,r;for(r=[],n=e=0,t=i;t>=0?t>e:e>t;n=t>=0?++e:--e)r.push(" ");return r}().join(""),"opening->closing"===t?r=r.substr(0,r.length-1)+e+"\n":r+=s+e+"\n"},o=0,s=l.length;s>o;o++)u=l[o],n(u);return r},showStatus:function(e){var t,n;void 0===e.content?(n=e.data,t=e.url):(n=e.content.data,t=e.request.url);var r=e.headers,i=null;r&&(i=r["Content-Type"]||r["content-type"],i&&(i=i.split(";")[0].trim())),$(".response_body",$(this.el)).removeClass("json"),$(".response_body",$(this.el)).removeClass("xml");var o,a,s=function(e){var t=document.createElement("audio");return!(!t.canPlayType||!t.canPlayType(e).replace(/no/,""))};if(n)if("application/json"===i||/\+json$/.test(i)){var l=null;try{l=JSON.stringify(JSON.parse(n),null," ")}catch(u){l="can't parse JSON. Raw result:\n\n"+n}a=$("<code />").text(l),o=$('<pre class="json" />').append(a)}else if("application/xml"===i||/\+xml$/.test(i))a=$("<code />").text(this.formatXml(n)),o=$('<pre class="xml" />').append(a);else if("text/html"===i)a=$("<code />").html(_.escape(n)),o=$('<pre class="xml" />').append(a);else if(/^image\//.test(i))o=$("<img>").attr("src",t);else if(/^audio\//.test(i)&&s(i))o=$("<audio controls>").append($("<source>").attr("src",t).attr("type",i));else if(r["Content-Disposition"].test(/attachment/)||r["content-disposition"].test(/attachment/)||r["Content-Description"].test(/File Transfer/)||r["content-description"].test(/File Transfer/))if("Blob"in window){var c=i||"text/html",p=new Blob([n],{type:c}),h=document.createElement("a"),f=window.URL.createObjectURL(p),d=e.url.substr(e.url.lastIndexOf("/")+1),m=[c,d,f].join(":");h.setAttribute("href",f),h.setAttribute("download",m),h.innerText="Download "+d,o=$("<div/>").append(h)}else o=$('<pre class="json" />').append("Download headers detected but your browser does not support downloading binary via XHR (Blob).");else r.location||r.Location?window.location=e.url:(a=$("<code />").text(n),o=$('<pre class="json" />').append(a));else a=$("<code />").text("no content"),o=$('<pre class="json" />').append(a);var g=o;$(".request_url",$(this.el)).html("<pre></pre>"),$(".request_url pre",$(this.el)).text(t),$(".response_code",$(this.el)).html("<pre>"+e.status+"</pre>"),$(".response_body",$(this.el)).html(g),$(".response_headers",$(this.el)).html("<pre>"+_.escape(JSON.stringify(e.headers,null," ")).replace(/\n/g,"<br>")+"</pre>"),$(".response",$(this.el)).slideDown(),$(".response_hider",$(this.el)).show(),$(".response_throbber",$(this.el)).hide();var y=$(".response_body",$(this.el))[0],v=this.options.swaggerOptions;return v.highlightSizeThreshold&&e.data.length>v.highlightSizeThreshold?y:hljs.highlightBlock(y)},toggleOperationContent:function(){var e=$("#"+Docs.escapeResourceName(this.parentId+"_"+this.nickname+"_content"));e.is(":visible")?Docs.collapseOperation(e):Docs.expandOperation(e)}}),SwaggerUi.Views.ParameterContentTypeView=Backbone.View.extend({initialize:function(){},render:function(){return $(this.el).html(Handlebars.templates.parameter_content_type(this.model)),$("label[for=parameterContentType]",$(this.el)).text("Parameter content type:"),this}}),SwaggerUi.Views.ParameterView=Backbone.View.extend({initialize:function(){Handlebars.registerHelper("isArray",function(e,t){"array"===e.type.toLowerCase()||e.allowMultiple?t.fn(this):t.inverse(this)})},render:function(){var e=this.model.type||this.model.dataType;if("undefined"==typeof e){var t=this.model.schema;if(t&&t.$ref){var n=t.$ref;e=0===n.indexOf("#/definitions/")?n.substring("#/definitions/".length):n}}this.model.type=e,this.model.paramType=this.model["in"]||this.model.paramType,this.model.isBody="body"===this.model.paramType||"body"===this.model["in"],this.model.isFile=e&&"file"===e.toLowerCase(),this.model["default"]=this.model["default"]||this.model.defaultValue,this.model.allowableValues&&(this.model.isList=!0);var r=this.template();$(this.el).html(r(this.model));var i={sampleJSON:this.model.sampleJSON,isParam:!0,signature:this.model.signature};if(this.model.sampleJSON){var o=new SwaggerUi.Views.SignatureView({model:i,tagName:"div"});$(".model-signature",$(this.el)).append(o.render().el)}else $(".model-signature",$(this.el)).html(this.model.signature);var a=!1;this.model.isBody&&(a=!0);var s={isParam:a};if(s.consumes=this.model.consumes,a){var l=new SwaggerUi.Views.ParameterContentTypeView({model:s});$(".parameter-content-type",$(this.el)).append(l.render().el)}else{var u=new SwaggerUi.Views.ResponseContentTypeView({model:s});$(".response-content-type",$(this.el)).append(u.render().el)}return this},template:function(){return this.model.isList?Handlebars.templates.param_list:this.options.readOnly?this.model.required?Handlebars.templates.param_readonly_required:Handlebars.templates.param_readonly:this.model.required?Handlebars.templates.param_required:Handlebars.templates.param}}),SwaggerUi.Views.ResourceView=Backbone.View.extend({initialize:function(e){e=e||{},this.router=e.router,this.auths=e.auths,""===this.model.description&&(this.model.description=null),this.model.description&&(this.model.summary=this.model.description)},render:function(){var e={};$(this.el).html(Handlebars.templates.resource(this.model));for(var t=0;t<this.model.operationsArray.length;t++){for(var n=this.model.operationsArray[t],r=0,i=n.nickname;"undefined"!=typeof e[i];)i=i+"_"+r,r+=1;e[i]=n,n.nickname=i,n.parentId=this.model.id,this.addOperation(n)}return $(".toggleEndpointList",this.el).click(this.callDocs.bind(this,"toggleEndpointListForResource")),$(".collapseResource",this.el).click(this.callDocs.bind(this,"collapseOperationsForResource")),$(".expandResource",this.el).click(this.callDocs.bind(this,"expandOperationsForResource")),this},addOperation:function(e){e.number=this.number;var t=new SwaggerUi.Views.OperationView({model:e,router:this.router,tagName:"li",className:"endpoint",swaggerOptions:this.options.swaggerOptions,auths:this.auths});$(".endpoints",$(this.el)).append(t.render().el),this.number++},callDocs:function(e,t){t.preventDefault(),Docs[e](t.currentTarget.getAttribute("data-id"))}}),SwaggerUi.Views.ResponseContentTypeView=Backbone.View.extend({initialize:function(){},render:function(){return $(this.el).html(Handlebars.templates.response_content_type(this.model)),$("label[for=responseContentType]",$(this.el)).text("Response Content Type"),this}}),SwaggerUi.Views.SignatureView=Backbone.View.extend({events:{"click a.description-link":"switchToDescription","click a.snippet-link":"switchToSnippet","mousedown .snippet":"snippetToTextArea"},initialize:function(){},render:function(){return $(this.el).html(Handlebars.templates.signature(this.model)),this.switchToSnippet(),this.isParam=this.model.isParam,this.isParam&&$(".notice",$(this.el)).text("Click to set as parameter value"),this},switchToDescription:function(e){e&&e.preventDefault(),$(".snippet",$(this.el)).hide(),$(".description",$(this.el)).show(),$(".description-link",$(this.el)).addClass("selected"),$(".snippet-link",$(this.el)).removeClass("selected")},switchToSnippet:function(e){e&&e.preventDefault(),$(".description",$(this.el)).hide(),$(".snippet",$(this.el)).show(),$(".snippet-link",$(this.el)).addClass("selected"),$(".description-link",$(this.el)).removeClass("selected")},snippetToTextArea:function(e){if(this.isParam){e&&e.preventDefault();var t=$("textarea",$(this.el.parentNode.parentNode.parentNode));""===$.trim(t.val())&&t.val(this.model.sampleJSON)}}}),SwaggerUi.Views.StatusCodeView=Backbone.View.extend({initialize:function(e){this.options=e||{},this.router=this.options.router},render:function(){if($(this.el).html(Handlebars.templates.status_code(this.model)),this.router.api.models.hasOwnProperty(this.model.responseModel)){var e={sampleJSON:JSON.stringify(this.router.api.models[this.model.responseModel].createJSONSample(),null,2),isParam:!1,signature:this.router.api.models[this.model.responseModel].getMockSignature()},t=new SwaggerUi.Views.SignatureView({model:e,tagName:"div"});$(".model-signature",this.$el).append(t.render().el)}else $(".model-signature",this.$el).html("");return this}})}).call(this);
+var t=this;this.options.success=function(){return t.render()},this.options.progress=function(e){return t.showMessage(e)},this.options.failure=function(e){return t.onLoadFailure(e)},this.headerView=new SwaggerUi.Views.HeaderView({el:$("#header")}),this.headerView.on("update-swagger-ui",function(e){return t.updateSwaggerUi(e)})},setOption:function(e,t){this.options[e]=t},getOption:function(e){return this.options[e]},updateSwaggerUi:function(e){this.options.url=e.url,this.load()},load:function(){this.mainView&&this.mainView.clear();var e=this.options.url;e&&0!==e.indexOf("http")&&(e=this.buildUrl(window.location.href.toString(),e)),this.options.url=e,this.headerView.update(e),this.api=new SwaggerClient(this.options)},collapseAll:function(){Docs.collapseEndpointListForResource("")},listAll:function(){Docs.collapseOperationsForResource("")},expandAll:function(){Docs.expandOperationsForResource("")},render:function(){switch(this.showMessage("Finished Loading Resource Information. Rendering Swagger UI..."),this.mainView=new SwaggerUi.Views.MainView({model:this.api,el:$("#"+this.dom_id),swaggerOptions:this.options,router:this}).render(),this.showMessage(),this.options.docExpansion){case"full":this.expandAll();break;case"list":this.listAll()}this.renderGFM(),this.options.onComplete&&this.options.onComplete(this.api,this),setTimeout(Docs.shebang.bind(this),100)},buildUrl:function(e,t){if(0===t.indexOf("/")){var n=e.split("/");return e=n[0]+"//"+n[2],e+t}var r=e.length;return e.indexOf("?")>-1&&(r=Math.min(r,e.indexOf("?"))),e.indexOf("#")>-1&&(r=Math.min(r,e.indexOf("#"))),e=e.substring(0,r),-1!==e.indexOf("/",e.length-1)?e+t:e+"/"+t},showMessage:function(e){void 0===e&&(e=""),$("#message-bar").removeClass("message-fail"),$("#message-bar").addClass("message-success"),$("#message-bar").html(e)},onLoadFailure:function(e){void 0===e&&(e=""),$("#message-bar").removeClass("message-success"),$("#message-bar").addClass("message-fail");var t=$("#message-bar").html(e);return this.options.onFailure&&this.options.onFailure(e),t},renderGFM:function(){$(".markdown").each(function(){$(this).html(marked($(this).html()))})}}),window.SwaggerUi.Views={},function(){function e(e){"console"in window&&"function"==typeof window.console.warn&&console.warn(e)}window.authorizations={add:function(){if(e("Using window.authorizations is deprecated. Please use SwaggerUi.api.clientAuthorizations.add()."),"undefined"==typeof window.swaggerUi)throw new TypeError("window.swaggerUi is not defined");window.swaggerUi instanceof SwaggerUi&&window.swaggerUi.api.clientAuthorizations.add.apply(window.swaggerUi.api.clientAuthorizations,arguments)}},window.ApiKeyAuthorization=function(){e("window.ApiKeyAuthorization is deprecated. Please use SwaggerClient.ApiKeyAuthorization."),SwaggerClient.ApiKeyAuthorization.apply(window,arguments)},window.PasswordAuthorization=function(){e("window.PasswordAuthorization is deprecated. Please use SwaggerClient.PasswordAuthorization."),SwaggerClient.PasswordAuthorization.apply(window,arguments)}}(),function(e,t){"function"==typeof define&&define.amd?define(["b"],function(n){return e.SwaggerUi=t(n)}):"object"==typeof exports?module.exports=t(require("b")):e.SwaggerUi=t(e.b)}(this,function(){return SwaggerUi}),SwaggerUi.Views.ApiKeyButton=Backbone.View.extend({events:{"click #apikey_button":"toggleApiKeyContainer","click #apply_api_key":"applyApiKey"},initialize:function(e){this.options=e||{},this.router=this.options.router},render:function(){var e=this.template();return $(this.el).html(e(this.model)),this},applyApiKey:function(){var e=new SwaggerClient.ApiKeyAuthorization(this.model.name,$("#input_apiKey_entry").val(),this.model["in"]);this.router.api.clientAuthorizations.add(this.model.name,e),this.router.load(),$("#apikey_container").show()},toggleApiKeyContainer:function(){if($("#apikey_container").length){var e=$("#apikey_container").first();e.is(":visible")?e.hide():($(".auth_container").hide(),e.show())}},template:function(){return Handlebars.templates.apikey_button_view}}),SwaggerUi.Views.BasicAuthButton=Backbone.View.extend({initialize:function(e){this.options=e||{},this.router=this.options.router},render:function(){var e=this.template();return $(this.el).html(e(this.model)),this},events:{"click #basic_auth_button":"togglePasswordContainer","click #apply_basic_auth":"applyPassword"},applyPassword:function(){var e=$(".input_username").val(),t=$(".input_password").val(),n=new SwaggerClient.PasswordAuthorization("basic",e,t);this.router.api.clientAuthorizations.add(this.model.type,n),this.router.load(),$("#basic_auth_container").hide()},togglePasswordContainer:function(){if($("#basic_auth_container").length){var e=$("#basic_auth_container").show();e.is(":visible")?e.slideUp():($(".auth_container").hide(),e.show())}},template:function(){return Handlebars.templates.basic_auth_button_view}}),SwaggerUi.Views.ContentTypeView=Backbone.View.extend({initialize:function(){},render:function(){return $(this.el).html(Handlebars.templates.content_type(this.model)),$("label[for=contentType]",$(this.el)).text("Response Content Type"),this}}),SwaggerUi.Views.HeaderView=Backbone.View.extend({events:{"click #show-pet-store-icon":"showPetStore","click #show-wordnik-dev-icon":"showWordnikDev","click #explore":"showCustom","keyup #input_baseUrl":"showCustomOnKeyup","keyup #input_apiKey":"showCustomOnKeyup"},initialize:function(){},showPetStore:function(){this.trigger("update-swagger-ui",{url:"http://petstore.swagger.io/v2/swagger.json"})},showWordnikDev:function(){this.trigger("update-swagger-ui",{url:"http://api.wordnik.com/v4/resources.json"})},showCustomOnKeyup:function(e){13===e.keyCode&&this.showCustom()},showCustom:function(e){e&&e.preventDefault(),this.trigger("update-swagger-ui",{url:$("#input_baseUrl").val(),apiKey:$("#input_apiKey").val()})},update:function(e,t,n){void 0===n&&(n=!1),$("#input_baseUrl").val(e),n&&this.trigger("update-swagger-ui",{url:e})}}),SwaggerUi.Views.MainView=Backbone.View.extend({apisSorter:{alpha:function(e,t){return e.name.localeCompare(t.name)}},operationsSorters:{alpha:function(e,t){return e.path.localeCompare(t.path)},method:function(e,t){return e.method.localeCompare(t.method)}},initialize:function(e){var t,n,r,i;if(e=e||{},this.router=e.router,e.swaggerOptions.apisSorter&&(t=e.swaggerOptions.apisSorter,n=_.isFunction(t)?t:this.apisSorter[t],_.isFunction(n)&&this.model.apisArray.sort(n)),e.swaggerOptions.operationsSorter&&(t=e.swaggerOptions.operationsSorter,n=_.isFunction(t)?t:this.operationsSorters[t],_.isFunction(n)))for(r in this.model.apisArray)this.model.apisArray[r].operationsArray.sort(n);this.model.auths=[];for(r in this.model.securityDefinitions)i=this.model.securityDefinitions[r],this.model.auths.push({name:r,type:i.type,value:i});"2.0"===this.model.swaggerVersion&&(this.model.validatorUrl="validatorUrl"in e.swaggerOptions?e.swaggerOptions.validatorUrl:this.model.url.indexOf("localhost")>0?null:"http://online.swagger.io/validator")},render:function(){if(this.model.securityDefinitions)for(var e in this.model.securityDefinitions){var t,n=this.model.securityDefinitions[e];"apiKey"===n.type&&0===$("#apikey_button").length&&(t=new SwaggerUi.Views.ApiKeyButton({model:n,router:this.router}).render().el,$(".auth_main_container").append(t)),"basicAuth"===n.type&&0===$("#basic_auth_button").length&&(t=new SwaggerUi.Views.BasicAuthButton({model:n,router:this.router}).render().el,$(".auth_main_container").append(t))}$(this.el).html(Handlebars.templates.main(this.model));for(var r={},i=0,o=0;o<this.model.apisArray.length;o++){for(var a=this.model.apisArray[o],s=a.name;"undefined"!=typeof r[s];)s=s+"_"+i,i+=1;a.id=s,r[s]=a,this.addResource(a,this.model.auths)}return $(".propWrap").hover(function(){$(".optionsWrapper",$(this)).show()},function(){$(".optionsWrapper",$(this)).hide()}),this},addResource:function(e,t){e.id=e.id.replace(/\s/g,"_");var n=new SwaggerUi.Views.ResourceView({model:e,router:this.router,tagName:"li",id:"resource_"+e.id,className:"resource",auths:t,swaggerOptions:this.options.swaggerOptions});$("#resources").append(n.render().el)},clear:function(){$(this.el).html("")}}),SwaggerUi.Views.OperationView=Backbone.View.extend({invocationUrl:null,events:{"submit .sandbox":"submitOperation","click .submit":"submitOperation","click .response_hider":"hideResponse","click .toggleOperation":"toggleOperationContent","mouseenter .api-ic":"mouseEnter","mouseout .api-ic":"mouseExit"},initialize:function(e){return e=e||{},this.router=e.router,this.auths=e.auths,this.parentId=this.model.parentId,this.nickname=this.model.nickname,this.model.encodedParentId=encodeURIComponent(this.parentId),this},mouseEnter:function(e){var t=$(this.el).find(".content"),n=e.pageX,r=e.pageY,i=$(window).scrollLeft(),o=$(window).scrollTop(),a=i+$(window).width(),s=o+$(window).height(),l=t.width(),u=t.height();n+l>a&&(n=a-l),i>n&&(n=i),r+u>s&&(r=s-u),o>r&&(r=o);var c={};c.top=r,c.left=n,t.css(c),$(e.currentTarget.parentNode).find("#api_information_panel").show()},mouseExit:function(e){$(e.currentTarget.parentNode).find("#api_information_panel").hide()},render:function(){var e,t,n,r,i,o,a,s,l,u,c,p,h,f,d,m,g,y,v,b,w,x,A,E,j,C,T,S,_,O,k,D,L,N,P,I,R,M;if(o=jQuery.inArray(this.model.method,this.model.supportedSubmitMethods())>=0,o||(this.model.isReadOnly=!0),this.model.description=this.model.description||this.model.notes,this.model.oauth=null,m=this.model.authorizations||this.model.security)if(Array.isArray(m))for(l=0,u=m.length;u>l;l++){n=m[l];for(s in n){t=n[s];for(e in this.auths)if(t=this.auths[e],"oauth2"===t.type){this.model.oauth={},this.model.oauth.scopes=[],A=t.value.scopes;for(a in A)R=A[a],D=n[s].indexOf(a),D>=0&&(y={scope:a,description:R},this.model.oauth.scopes.push(y))}}}else for(a in m)if(R=m[a],"oauth2"===a)for(null===this.model.oauth&&(this.model.oauth={}),void 0===this.model.oauth.scopes&&(this.model.oauth.scopes=[]),d=0,c=R.length;c>d;d++)y=R[d],this.model.oauth.scopes.push(y);if("undefined"!=typeof this.model.responses){this.model.responseMessages=[],E=this.model.responses;for(r in E)M=E[r],O=null,k=this.model.responses[r].schema,k&&k.$ref&&(O=k.$ref,0===O.indexOf("#/definitions/")&&(O=O.substring("#/definitions/".length))),this.model.responseMessages.push({code:r,message:M.description,responseModel:O})}if("undefined"==typeof this.model.responseMessages&&(this.model.responseMessages=[]),L=null,this.model.successResponse){P=this.model.successResponse;for(s in P)M=P[s],this.model.successCode=s,"object"==typeof M&&"function"==typeof M.createJSONSample&&(L={sampleJSON:JSON.stringify(M.createJSONSample(),void 0,2),isParam:!1,signature:M.getMockSignature()})}else this.model.responseClassSignature&&"string"!==this.model.responseClassSignature&&(L={sampleJSON:this.model.responseSampleJSON,isParam:!1,signature:this.model.responseClassSignature});for($(this.el).html(Handlebars.templates.operation(this.model)),L?(_=new SwaggerUi.Views.SignatureView({model:L,router:this.router,tagName:"div"}),$(".model-signature",$(this.el)).append(_.render().el)):(this.model.responseClassSignature="string",$(".model-signature",$(this.el)).html(this.model.type)),i={isParam:!1},i.consumes=this.model.consumes,i.produces=this.model.produces,j=this.model.parameters,g=0,p=j.length;p>g;g++)b=j[g],I=b.type||b.dataType||"","undefined"==typeof I&&(O=b.schema,O&&O.$ref&&(x=O.$ref,I=0===x.indexOf("#/definitions/")?x.substring("#/definitions/".length):x)),I&&"file"===I.toLowerCase()&&(i.consumes||(i.consumes="multipart/form-data")),b.type=I;for(S=new SwaggerUi.Views.ResponseContentTypeView({model:i,router:this.router}),$(".response-content-type",$(this.el)).append(S.render().el),C=this.model.parameters,v=0,h=C.length;h>v;v++)b=C[v],this.addParameter(b,i.consumes);for(T=this.model.responseMessages,w=0,f=T.length;f>w;w++)N=T[w],this.addStatusCode(N);return this},addParameter:function(e,t){e.consumes=t;var n=new SwaggerUi.Views.ParameterView({model:e,tagName:"tr",readOnly:this.model.isReadOnly});$(".operation-params",$(this.el)).append(n.render().el)},addStatusCode:function(e){var t=new SwaggerUi.Views.StatusCodeView({model:e,tagName:"tr",router:this.router});$(".operation-status",$(this.el)).append(t.render().el)},submitOperation:function(e){var t,n,r,i,o,a,s,l,u,c,p,h,f,d,m,g;if(null!==e&&e.preventDefault(),n=$(".sandbox",$(this.el)),t=!0,n.find("input.required").each(function(){$(this).removeClass("error"),""===jQuery.trim($(this).val())&&($(this).addClass("error"),$(this).wiggle({callback:function(e){return function(){$(e).focus()}}(this)}),t=!1)}),n.find("textarea.required").each(function(){$(this).removeClass("error"),""===jQuery.trim($(this).val())&&($(this).addClass("error"),$(this).wiggle({callback:function(e){return function(){return $(e).focus()}}(this)}),t=!1)}),t){for(u={},h={parent:this},r=!1,f=n.find("input"),i=0,o=f.length;o>i;i++)p=f[i],null!==p.value&&jQuery.trim(p.value).length>0&&(u[p.name]=p.value),"file"===p.type&&(u[p.name]=p.files[0],r=!0);for(d=n.find("textarea"),l=0,a=d.length;a>l;l++)p=d[l],null!==p.value&&jQuery.trim(p.value).length>0&&(u[p.name]=p.value);for(m=n.find("select"),c=0,s=m.length;s>c;c++)p=m[c],g=this.getSelectedValue(p),null!==g&&jQuery.trim(g).length>0&&(u[p.name]=g);return h.responseContentType=$("div select[name=responseContentType]",$(this.el)).val(),h.requestContentType=$("div select[name=parameterContentType]",$(this.el)).val(),$(".response_throbber",$(this.el)).show(),r?this.handleFileUpload(u,n):this.model["do"](u,h,this.showCompleteStatus,this.showErrorStatus,this)}},success:function(e,t){t.showCompleteStatus(e)},handleFileUpload:function(e,t){var n,r,i,o,a,s,l,u,c,p,h,f,d,m,g,y,v,b,w;for(y=t.serializeArray(),o=0,a=y.length;a>o;o++)h=y[o],null!==h.value&&jQuery.trim(h.value).length>0&&(e[h.name]=h.value);for(n=new FormData,g=0,v=this.model.parameters,c=0,s=v.length;s>c;c++)m=v[c],("form"===m.paramType||"formData"===m["in"])&&"file"!==m.type.toLowerCase()&&void 0!==e[m.name]&&n.append(m.name,e[m.name]);for(i={},b=this.model.parameters,p=0,l=b.length;l>p;p++)m=b[p],"header"===m.paramType&&(i[m.name]=e[m.name]);for(w=t.find('input[type~="file"]'),d=0,u=w.length;u>d;d++)r=w[d],"undefined"!=typeof r.files[0]&&(n.append($(r).attr("name"),r.files[0]),g+=1);return this.invocationUrl=this.model.supportHeaderParams()?(i=this.model.getHeaderParams(e),delete i["Content-Type"],this.model.urlify(e,!1)):this.model.urlify(e,!0),$(".request_url",$(this.el)).html("<pre></pre>"),$(".request_url pre",$(this.el)).text(this.invocationUrl),f={type:this.model.method,url:this.invocationUrl,headers:i,data:n,dataType:"json",contentType:!1,processData:!1,error:function(e){return function(t){return e.showErrorStatus(e.wrap(t),e)}}(this),success:function(e){return function(t){return e.showResponse(t,e)}}(this),complete:function(e){return function(t){return e.showCompleteStatus(e.wrap(t),e)}}(this)},window.authorizations&&window.authorizations.apply(f),jQuery.ajax(f),!1},wrap:function(e){var t,n,r,i,o,a,s;for(r={},n=e.getAllResponseHeaders().split("\r"),o=0,a=n.length;a>o;o++)i=n[o],t=i.match(/^([^:]*?):(.*)$/),t||(t=[]),t.shift(),void 0!==t[0]&&void 0!==t[1]&&(r[t[0].trim()]=t[1].trim());return s={},s.content={},s.content.data=e.responseText,s.headers=r,s.request={},s.request.url=this.invocationUrl,s.status=e.status,s},getSelectedValue:function(e){if(e.multiple){for(var t=[],n=0,r=e.options.length;r>n;n++){var i=e.options[n];i.selected&&t.push(i.value)}return t.length>0?t:null}return e.value},hideResponse:function(e){e&&e.preventDefault(),$(".response",$(this.el)).slideUp(),$(".response_hider",$(this.el)).fadeOut()},showResponse:function(e){var t=JSON.stringify(e,null," ").replace(/\n/g,"<br>");$(".response_body",$(this.el)).html(_.escape(t))},showErrorStatus:function(e,t){t.showStatus(e)},showCompleteStatus:function(e,t){t.showStatus(e)},formatXml:function(e){var t,n,r,i,o,a,s,l,u,c,p,h,f;for(p=/(>)(<)(\/*)/g,f=/[ ]*(.*)[ ]+\n/g,t=/(<.+>)(.+\n)/g,e=e.replace(p,"$1\n$2$3").replace(f,"$1\n").replace(t,"$1\n$2"),c=0,r="",l=e.split("\n"),i=0,a="other",h={"single->single":0,"single->closing":-1,"single->opening":0,"single->other":0,"closing->single":0,"closing->closing":-1,"closing->opening":0,"closing->other":0,"opening->single":1,"opening->closing":0,"opening->opening":1,"opening->other":1,"other->single":0,"other->closing":-1,"other->opening":0,"other->other":0},n=function(e){var t,n,o,s,l,u,c;u={single:Boolean(e.match(/<.+\/>/)),closing:Boolean(e.match(/<\/.+>/)),opening:Boolean(e.match(/<[^!?].*>/))},l=function(){var e;e=[];for(o in u)c=u[o],c&&e.push(o);return e}()[0],l=void 0===l?"other":l,t=a+"->"+l,a=l,s="",i+=h[t],s=function(){var e,t,r;for(r=[],n=e=0,t=i;t>=0?t>e:e>t;n=t>=0?++e:--e)r.push(" ");return r}().join(""),"opening->closing"===t?r=r.substr(0,r.length-1)+e+"\n":r+=s+e+"\n"},o=0,s=l.length;s>o;o++)u=l[o],n(u);return r},showStatus:function(e){var t,n;void 0===e.content?(n=e.data,t=e.url):(n=e.content.data,t=e.request.url);var r=e.headers,i=null;r&&(i=r["Content-Type"]||r["content-type"],i&&(i=i.split(";")[0].trim())),$(".response_body",$(this.el)).removeClass("json"),$(".response_body",$(this.el)).removeClass("xml");var o,a,s=function(e){var t=document.createElement("audio");return!(!t.canPlayType||!t.canPlayType(e).replace(/no/,""))};if(n)if("application/json"===i||/\+json$/.test(i)){var l=null;try{l=JSON.stringify(JSON.parse(n),null," ")}catch(u){l="can't parse JSON. Raw result:\n\n"+n}a=$("<code />").text(l),o=$('<pre class="json" />').append(a)}else if("application/xml"===i||/\+xml$/.test(i))a=$("<code />").text(this.formatXml(n)),o=$('<pre class="xml" />').append(a);else if("text/html"===i)a=$("<code />").html(_.escape(n)),o=$('<pre class="xml" />').append(a);else if(/^image\//.test(i))o=$("<img>").attr("src",t);else if(/^audio\//.test(i)&&s(i))o=$("<audio controls>").append($("<source>").attr("src",t).attr("type",i));else if(r["Content-Disposition"].test(/attachment/)||r["content-disposition"].test(/attachment/)||r["Content-Description"].test(/File Transfer/)||r["content-description"].test(/File Transfer/))if("Blob"in window){var c=i||"text/html",p=new Blob([n],{type:c}),h=document.createElement("a"),f=window.URL.createObjectURL(p),d=e.url.substr(e.url.lastIndexOf("/")+1),m=[c,d,f].join(":");h.setAttribute("href",f),h.setAttribute("download",m),h.innerText="Download "+d,o=$("<div/>").append(h)}else o=$('<pre class="json" />').append("Download headers detected but your browser does not support downloading binary via XHR (Blob).");else r.location||r.Location?window.location=e.url:(a=$("<code />").text(n),o=$('<pre class="json" />').append(a));else a=$("<code />").text("no content"),o=$('<pre class="json" />').append(a);var g=o;$(".request_url",$(this.el)).html("<pre></pre>"),$(".request_url pre",$(this.el)).text(t),$(".response_code",$(this.el)).html("<pre>"+e.status+"</pre>"),$(".response_body",$(this.el)).html(g),$(".response_headers",$(this.el)).html("<pre>"+_.escape(JSON.stringify(e.headers,null," ")).replace(/\n/g,"<br>")+"</pre>"),$(".response",$(this.el)).slideDown(),$(".response_hider",$(this.el)).show(),$(".response_throbber",$(this.el)).hide();var y=$(".response_body",$(this.el))[0],v=this.options.swaggerOptions;return v.highlightSizeThreshold&&e.data.length>v.highlightSizeThreshold?y:hljs.highlightBlock(y)},toggleOperationContent:function(){var e=$("#"+Docs.escapeResourceName(this.parentId+"_"+this.nickname+"_content"));e.is(":visible")?Docs.collapseOperation(e):Docs.expandOperation(e)}}),SwaggerUi.Views.ParameterContentTypeView=Backbone.View.extend({initialize:function(){},render:function(){return $(this.el).html(Handlebars.templates.parameter_content_type(this.model)),$("label[for=parameterContentType]",$(this.el)).text("Parameter content type:"),this}}),SwaggerUi.Views.ParameterView=Backbone.View.extend({initialize:function(){Handlebars.registerHelper("isArray",function(e,t){"array"===e.type.toLowerCase()||e.allowMultiple?t.fn(this):t.inverse(this)})},render:function(){var e=this.model.type||this.model.dataType;if("undefined"==typeof e){var t=this.model.schema;if(t&&t.$ref){var n=t.$ref;e=0===n.indexOf("#/definitions/")?n.substring("#/definitions/".length):n}}this.model.type=e,this.model.paramType=this.model["in"]||this.model.paramType,this.model.isBody="body"===this.model.paramType||"body"===this.model["in"],this.model.isFile=e&&"file"===e.toLowerCase(),this.model["default"]=this.model["default"]||this.model.defaultValue,this.model.allowableValues&&(this.model.isList=!0);var r=this.template();$(this.el).html(r(this.model));var i={sampleJSON:this.model.sampleJSON,isParam:!0,signature:this.model.signature};if(this.model.sampleJSON){var o=new SwaggerUi.Views.SignatureView({model:i,tagName:"div"});$(".model-signature",$(this.el)).append(o.render().el)}else $(".model-signature",$(this.el)).html(this.model.signature);var a=!1;this.model.isBody&&(a=!0);var s={isParam:a};if(s.consumes=this.model.consumes,a){var l=new SwaggerUi.Views.ParameterContentTypeView({model:s});$(".parameter-content-type",$(this.el)).append(l.render().el)}else{var u=new SwaggerUi.Views.ResponseContentTypeView({model:s});$(".response-content-type",$(this.el)).append(u.render().el)}return this},template:function(){return this.model.isList?Handlebars.templates.param_list:this.options.readOnly?this.model.required?Handlebars.templates.param_readonly_required:Handlebars.templates.param_readonly:this.model.required?Handlebars.templates.param_required:Handlebars.templates.param}}),SwaggerUi.Views.ResourceView=Backbone.View.extend({initialize:function(e){e=e||{},this.router=e.router,this.auths=e.auths,""===this.model.description&&(this.model.description=null),this.model.description&&(this.model.summary=this.model.description)},render:function(){var e={};$(this.el).html(Handlebars.templates.resource(this.model));for(var t=0;t<this.model.operationsArray.length;t++){for(var n=this.model.operationsArray[t],r=0,i=n.nickname;"undefined"!=typeof e[i];)i=i+"_"+r,r+=1;e[i]=n,n.nickname=i,n.parentId=this.model.id,this.addOperation(n)}return $(".toggleEndpointList",this.el).click(this.callDocs.bind(this,"toggleEndpointListForResource")),$(".collapseResource",this.el).click(this.callDocs.bind(this,"collapseOperationsForResource")),$(".expandResource",this.el).click(this.callDocs.bind(this,"expandOperationsForResource")),this},addOperation:function(e){e.number=this.number;var t=new SwaggerUi.Views.OperationView({model:e,router:this.router,tagName:"li",className:"endpoint",swaggerOptions:this.options.swaggerOptions,auths:this.auths});$(".endpoints",$(this.el)).append(t.render().el),this.number++},callDocs:function(e,t){t.preventDefault(),Docs[e](t.currentTarget.getAttribute("data-id"))}}),SwaggerUi.Views.ResponseContentTypeView=Backbone.View.extend({initialize:function(){},render:function(){return $(this.el).html(Handlebars.templates.response_content_type(this.model)),$("label[for=responseContentType]",$(this.el)).text("Response Content Type"),this}}),SwaggerUi.Views.SignatureView=Backbone.View.extend({events:{"click a.description-link":"switchToDescription","click a.snippet-link":"switchToSnippet","mousedown .snippet":"snippetToTextArea"},initialize:function(){},render:function(){return $(this.el).html(Handlebars.templates.signature(this.model)),this.switchToSnippet(),this.isParam=this.model.isParam,this.isParam&&$(".notice",$(this.el)).text("Click to set as parameter value"),this},switchToDescription:function(e){e&&e.preventDefault(),$(".snippet",$(this.el)).hide(),$(".description",$(this.el)).show(),$(".description-link",$(this.el)).addClass("selected"),$(".snippet-link",$(this.el)).removeClass("selected")},switchToSnippet:function(e){e&&e.preventDefault(),$(".description",$(this.el)).hide(),$(".snippet",$(this.el)).show(),$(".snippet-link",$(this.el)).addClass("selected"),$(".description-link",$(this.el)).removeClass("selected")},snippetToTextArea:function(e){if(this.isParam){e&&e.preventDefault();var t=$("textarea",$(this.el.parentNode.parentNode.parentNode));""===$.trim(t.val())&&t.val(this.model.sampleJSON)}}}),SwaggerUi.Views.StatusCodeView=Backbone.View.extend({initialize:function(e){this.options=e||{},this.router=this.options.router},render:function(){if($(this.el).html(Handlebars.templates.status_code(this.model)),this.router.api.models.hasOwnProperty(this.model.responseModel)){var e={sampleJSON:JSON.stringify(this.router.api.models[this.model.responseModel].createJSONSample(),null,2),isParam:!1,signature:this.router.api.models[this.model.responseModel].getMockSignature()},t=new SwaggerUi.Views.SignatureView({model:e,tagName:"div"});$(".model-signature",this.$el).append(t.render().el)}else $(".model-signature",this.$el).html("");return this}})}).call(this); \ No newline at end of file
diff --git a/catalog-be/src/main/webapp/WEB-INF/web.xml b/catalog-be/src/main/webapp/WEB-INF/web.xml
index 814a58a4fe..481cdd6a2c 100644
--- a/catalog-be/src/main/webapp/WEB-INF/web.xml
+++ b/catalog-be/src/main/webapp/WEB-INF/web.xml
@@ -13,7 +13,6 @@
<init-param>
<param-name>jersey.config.server.provider.classnames</param-name>
<param-value>com.wordnik.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>com.wordnik.swagger.jersey.listing.ApiListingResourceJSON;org.glassfish.jersey.media.multipart.MultiPartFeature,org.openecomp.sdc.be.filters.BeServletFilter</param-value> -->
</init-param>
<load-on-startup>1</load-on-startup>
@@ -46,9 +45,6 @@
</init-param>
<init-param>
<param-name>jersey.config.server.provider.classnames</param-name>
-<!-- <param-value>com.wordnik.swagger.jersey.listing.ApiListingResourceJSON;org.glassfish.jersey.media.multipart.MultiPartFeature,org.openecomp.sdc.be.filters.BeServletFilter,org.openecomp.sdc.be.filters.BasicAuthenticationFilter, org.openecomp.sdc.be.filters.ComponentsAvailabilityFilter</param-value> -->
-
- <!-- Closed till the feature done and basic authentication defined with M Lando -->
<param-value>com.wordnik.swagger.jersey.listing.ApiListingResourceJSON;org.glassfish.jersey.media.multipart.MultiPartFeature,org.openecomp.sdc.be.filters.BeServletFilter,org.openecomp.sdc.be.filters.BasicAuthenticationFilter</param-value>
</init-param>
@@ -58,6 +54,7 @@
<servlet-mapping>
<servlet-name>jerseyDistribution</servlet-name>
+ <url-pattern>/sdc/*</url-pattern>
<url-pattern>/asdc/*</url-pattern>
</servlet-mapping>
@@ -78,7 +75,20 @@
<async-supported>true</async-supported>
</servlet>
- <!-- ECOMP Portal -->
+ <!-- ECOMP Portal -->
+ <servlet>
+ <servlet-name>ECOMPServlet</servlet-name>
+ <servlet-class>org.openecomp.portalsdk.core.onboarding.crossapi.PortalRestAPIProxy</servlet-class>
+ <load-on-startup>3</load-on-startup>
+ <async-supported>true</async-supported>
+ </servlet>
+
+ <!-- Removed, the servlet mapping will be taken from annotation -->
+<!-- <servlet-mapping>
+ <servlet-name>ECOMPServlet</servlet-name>
+ <url-pattern>/api/*</url-pattern>
+ </servlet-mapping> -->
+
<servlet>
<servlet-name>ViewStatusMessages</servlet-name>
<servlet-class>ch.qos.logback.classic.ViewStatusMessagesServlet</servlet-class>
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 28b60559aa..45b2317cd6 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/ElementOperationMock.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/ElementOperationMock.java
@@ -27,7 +27,6 @@ import java.util.Map;
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;
-import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
import org.openecomp.sdc.be.model.ArtifactType;
import org.openecomp.sdc.be.model.Category;
import org.openecomp.sdc.be.model.PropertyScope;
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 d19ae9c872..f9819c72e5 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/TestExternalConfiguration.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/TestExternalConfiguration.java
@@ -54,7 +54,6 @@ public class TestExternalConfiguration<T extends Object> {
try {
Thread.currentThread().sleep(100 * 1000);
} catch (InterruptedException e) {
- // TODO Auto-generated catch block
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 a651b77f9a..d55d5752c1 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/ZipUtil.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/ZipUtil.java
@@ -61,7 +61,6 @@ public class ZipUtil {
readZip(zipAsBytes);
} catch (IOException e) {
- // TODO Auto-generated catch block
e.printStackTrace();
}
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 8f3234bc39..90f5b19acc 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
@@ -27,6 +27,7 @@ import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic;
import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;
import org.openecomp.sdc.exception.ResponseFormat;
import fj.data.Either;
@@ -51,6 +52,12 @@ public class ComponentBusinessLogicTest {
// TODO Auto-generated method stub
return null;
}
+
+ @Override
+ public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String componentId, List<String> dataParamsToReturn) {
+ // TODO Auto-generated method stub
+ return null;
+ }
};
@Test
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
new file mode 100644
index 0000000000..134038abb6
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/GroupBusinessLogicTest.java
@@ -0,0 +1,263 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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;
+
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.when;
+
+import java.lang.reflect.Method;
+import java.util.Arrays;
+import java.util.EnumMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.servlet.ServletContext;
+
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.mockito.InjectMocks;
+import org.mockito.Mockito;
+import org.mockito.MockitoAnnotations;
+import org.openecomp.sdc.be.auditing.impl.AuditingManager;
+import org.openecomp.sdc.be.components.impl.GroupBusinessLogic;
+import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.model.GroupDefinition;
+import org.openecomp.sdc.be.model.GroupProperty;
+import org.openecomp.sdc.be.model.PropertyDefinition.PropertyNames;
+import org.openecomp.sdc.be.model.User;
+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.GroupOperation;
+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.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import fj.data.Either;
+/**
+ * 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();
+// }
+ }
+
+}
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 eee5c4dd32..09f2570a35 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
@@ -25,6 +25,7 @@ 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;
@@ -53,6 +54,7 @@ import org.openecomp.sdc.be.model.RequirementDefinition;
import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.UploadResourceInfo;
import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
import org.openecomp.sdc.be.model.operations.impl.ResourceOperation;
import org.openecomp.sdc.be.model.tosca.constraints.GreaterOrEqualConstraint;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
@@ -73,18 +75,18 @@ public class ResourceImportManagerTest {
static IAuditingManager auditingManager = Mockito.mock(IAuditingManager.class);
static ResponseFormatManager responseFormatManager = Mockito.mock(ResponseFormatManager.class);
static ResourceBusinessLogic resourceBusinessLogic = Mockito.mock(ResourceBusinessLogic.class);
- static ResourceOperation resourceOperation = Mockito.mock(ResourceOperation.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(resourceOperation.getLatestByToscaResourceName(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(Either.left(null));
+ when(toscaOperationFacade.getLatestByToscaResourceName(Mockito.anyString())).thenReturn(Either.left(null));
importManager.setResponseFormatManager(responseFormatManager);
importManager.setResourceBusinessLogic(resourceBusinessLogic);
- importManager.setResourceOperation(resourceOperation);
+ importManager.setToscaOperationFacade(toscaOperationFacade);
ResourceImportManager.setLog(log);
String appConfigDir = "src/test/resources/config/catalog-be";
@@ -221,7 +223,7 @@ public class ResourceImportManagerTest {
}
});
- when(resourceBusinessLogic.createResourceByDao(Mockito.any(Resource.class), Mockito.any(User.class), Mockito.any(AuditingActionEnum.class), Mockito.anyBoolean())).thenAnswer(new Answer<Either<Resource, ResponseFormat>>() {
+ 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]);
@@ -345,6 +347,7 @@ public class ResourceImportManagerTest {
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()));
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 fd83af016a..ed16ca722a 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
@@ -25,6 +25,7 @@ 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;
@@ -32,7 +33,9 @@ import java.util.Map;
import javax.servlet.ServletContext;
+import org.apache.commons.lang3.tuple.ImmutablePair;
import org.junit.Before;
+import org.junit.Ignore;
import org.junit.Test;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
@@ -47,22 +50,30 @@ import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao;
import org.openecomp.sdc.be.dao.impl.AuditingDao;
+import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.impl.WebAppContextWrapper;
import org.openecomp.sdc.be.model.ArtifactDefinition;
import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.GroupInstance;
+import org.openecomp.sdc.be.model.InputDefinition;
+import org.openecomp.sdc.be.model.PropertyDefinition;
import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.Service;
import org.openecomp.sdc.be.model.User;
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.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.CacheMangerOperation;
import org.openecomp.sdc.be.model.operations.impl.GraphLockOperation;
import org.openecomp.sdc.be.model.operations.impl.ServiceOperation;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
import org.openecomp.sdc.be.resources.data.auditing.DistributionDeployEvent;
import org.openecomp.sdc.be.resources.data.auditing.DistributionNotificationEvent;
import org.openecomp.sdc.be.resources.data.auditing.ResourceAdminEvent;
@@ -93,7 +104,6 @@ public class ServiceBusinessLogicTest {
final ServletContext servletContext = Mockito.mock(ServletContext.class);
IAuditingManager iAuditingManager = null;
UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class);
- final ServiceOperation serviceOperation = Mockito.mock(ServiceOperation.class);
WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class);
WebApplicationContext webAppContext = Mockito.mock(WebApplicationContext.class);
ServiceBusinessLogic bl = new ServiceBusinessLogic();
@@ -104,15 +114,18 @@ public class ServiceBusinessLogicTest {
AuditCassandraDao auditingDao = Mockito.mock(AuditCassandraDao.class);
ArtifactsBusinessLogic artifactBl = Mockito.mock(ArtifactsBusinessLogic.class);
GraphLockOperation graphLockOperation = Mockito.mock(GraphLockOperation.class);
- TitanGenericDao mockTitanDao = Mockito.mock(TitanGenericDao.class);
-
+ TitanDao mockTitanDao = Mockito.mock(TitanDao.class);
+ ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class);
CacheMangerOperation cacheManager = Mockito.mock(CacheMangerOperation.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>();
@@ -125,12 +138,11 @@ public class ServiceBusinessLogicTest {
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();
@@ -146,7 +158,7 @@ public class ServiceBusinessLogicTest {
// Servlet Context attributes
when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager);
- when(servletContext.getAttribute(Constants.SERVICE_OPERATION_MANAGER)).thenReturn(serviceOperation);
+ when(servletContext.getAttribute(Constants.SERVICE_OPERATION_MANAGER)).thenReturn(new ServiceOperation());
when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper);
when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext);
when(webAppContext.getBean(IElementOperation.class)).thenReturn(mockElementDao);
@@ -159,24 +171,26 @@ public class ServiceBusinessLogicTest {
// createService
serviceResponse = createServiceObject(true);
- Either<Service, StorageOperationStatus> eitherCreate = Either.left(serviceResponse);
- when(serviceOperation.createService(Mockito.any(Service.class))).thenReturn(eitherCreate);
- Either<Boolean, StorageOperationStatus> eitherCount = Either.left(true);
- when(serviceOperation.validateServiceNameExists("Service")).thenReturn(eitherCount);
- Either<Boolean, StorageOperationStatus> eitherCountExist = Either.left(false);
- when(serviceOperation.validateServiceNameExists("alreadyExist")).thenReturn(eitherCountExist);
-
- when(serviceOperation.validateComponentNameExists("alreadyExist")).thenReturn(eitherCountExist);
- when(serviceOperation.validateComponentNameExists("Service")).thenReturn(eitherCount);
-
+ 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.setServiceOperation(serviceOperation);
bl.setArtifactBl(artifactBl);
bl.setGraphLockOperation(graphLockOperation);
bl.setTitanGenericDao(mockTitanDao);
-
+ bl.setToscaOperationFacade(toscaOperationFacade);
+
componentsUtils.Init();
componentsUtils.setAuditingManager(auditingManager);
bl.setComponentsUtils(componentsUtils);
@@ -266,16 +280,16 @@ public class ServiceBusinessLogicTest {
testInvalidTag();
testServiceTagNotExist();
testServiceTagEmpty();
- // 1610OS Support - Because of changes in the validation in the ui these tests will fail. need to fix them
- //testContactIdTooLong();
- //testContactIdWrongFormatCreate();
+
+ testContactIdTooLong();
+ testContactIdWrongFormatCreate();
+ testInvalidProjectCode();
+ testProjectCodeTooLong();
+ testProjectCodeTooShort();
+
testResourceContactIdMissing();
testServiceCategoryExist();
testServiceBadCategoryCreate();
- // 1610OS Support - Because of changes in the validation in the ui these tests will fail. need to fix them
- //testInvalidProjectCode();
- //testProjectCodeTooLong();
- //testProjectCodeTooShort();
testMissingProjectCode();
}
@@ -541,8 +555,8 @@ public class ServiceBusinessLogicTest {
// Service contactId - start
private void testContactIdTooLong() {
Service serviceContactId = createServiceObject(false);
- // 7 chars instead of 6
- String contactIdTooLong = "yrt1234";
+ // 59 chars instead of 50
+ String contactIdTooLong = "thisNameIsVeryLongAndExeccedsTheNormalLengthForContactId";
serviceContactId.setContactId(contactIdTooLong);
Either<Service, ResponseFormat> createResponse = bl.createService(serviceContactId, user);
@@ -552,8 +566,8 @@ public class ServiceBusinessLogicTest {
private void testContactIdWrongFormatCreate() {
Service serviceContactId = createServiceObject(false);
- // 3 letters and 3 digits
- String contactIdTooLong = "yrt134";
+ // 3 letters and 3 digits and special characters
+ String contactIdTooLong = "yrt134!!!";
serviceContactId.setContactId(contactIdTooLong);
Either<Service, ResponseFormat> createResponse = bl.createService(serviceContactId, user);
@@ -634,8 +648,8 @@ public class ServiceBusinessLogicTest {
Either<List<ResourceAdminEvent>, ActionStatus> emptyEventList = Either.left(emptyList);
Mockito.when(auditingDao.getDistributionRequest(Mockito.anyString(), Mockito.eq(requestAction))).thenReturn(emptyEventList);
- Either<Service, StorageOperationStatus> notFound = Either.right(StorageOperationStatus.NOT_FOUND);
- Mockito.when(serviceOperation.getService(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());
@@ -659,10 +673,11 @@ public class ServiceBusinessLogicTest {
}
// Service category - stop
+ // Service projectCode - start
private void testInvalidProjectCode() {
Service serviceExist = createServiceObject(false);
- serviceExist.setProjectCode("koko");
+ serviceExist.setProjectCode("koko!!");
Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
assertTrue(createResponse.isRight());
@@ -673,7 +688,8 @@ public class ServiceBusinessLogicTest {
private void testProjectCodeTooLong() {
Service serviceExist = createServiceObject(false);
- serviceExist.setProjectCode("5555555555555");
+ String tooLongProjectCode = "thisNameIsVeryLongAndExeccedsTheNormalLengthForProjectCode";
+ serviceExist.setProjectCode(tooLongProjectCode);
Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
assertTrue(createResponse.isRight());
@@ -684,7 +700,7 @@ public class ServiceBusinessLogicTest {
private void testProjectCodeTooShort() {
Service serviceExist = createServiceObject(false);
- serviceExist.setProjectCode("555");
+ serviceExist.setProjectCode("333");
Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
assertTrue(createResponse.isRight());
@@ -703,21 +719,22 @@ public class ServiceBusinessLogicTest {
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(serviceOperation.getAllComponentsMarkedForDeletion()).thenReturn(eitherNoResources);
-
- Either<List<String>, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents();
- assertTrue(deleteMarkedResources.isLeft());
- assertTrue(deleteMarkedResources.left().value().isEmpty());
-
- Mockito.verify(artifactBl, Mockito.times(0)).deleteAllComponentArtifactsIfNotOnGraph(Mockito.anyList());
-
- }
+// @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());
+//
+// Mockito.verify(artifactBl, Mockito.times(0)).deleteAllComponentArtifactsIfNotOnGraph(Mockito.anyList());
+//
+// }
@Test
+ @Ignore
public void testDeleteMarkedServices() {
List<String> ids = new ArrayList<String>();
String resourceInUse = "123";
@@ -725,20 +742,20 @@ public class ServiceBusinessLogicTest {
String resourceFree = "456";
ids.add(resourceFree);
Either<List<String>, StorageOperationStatus> eitherNoResources = Either.left(ids);
- when(serviceOperation.getAllComponentsMarkedForDeletion()).thenReturn(eitherNoResources);
+ 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(serviceOperation.getComponentArtifactsForDelete(resourceFree, NodeTypeEnum.Service, true)).thenReturn(getArtifactsResponse);
+// when(toscaOperationFacade.getComponentArtifactsForDelete(resourceFree, NodeTypeEnum.Service, true)).thenReturn(getArtifactsResponse);
- when(serviceOperation.isComponentInUse(resourceFree)).thenReturn(resourceFreeResponse);
- when(serviceOperation.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(serviceOperation.deleteComponent(resourceFree, true)).thenReturn(eitherDelete);
+ when(toscaOperationFacade.deleteToscaComponent(resourceFree)).thenReturn(eitherDelete);
when(artifactBl.deleteAllComponentArtifactsIfNotOnGraph(artifacts)).thenReturn(StorageOperationStatus.OK);
@@ -767,7 +784,6 @@ public class ServiceBusinessLogicTest {
service.setTags(tgs);
// service.setVendorName("Motorola");
// service.setVendorRelease("1.0.0");
- // service.setContactId("ya5467");
service.setIcon("MyIcon");
// service.setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
service.setContactId("aa1234");
@@ -779,8 +795,6 @@ public class ServiceBusinessLogicTest {
service.setCreatorUserId(user.getUserId());
service.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
}
- Gson gson = new GsonBuilder().setPrettyPrinting().create();
- log.debug("{}", gson.toJson(service));
return service;
}
@@ -921,11 +935,100 @@ public class ServiceBusinessLogicTest {
Either<List<ResourceAdminEvent>, ActionStatus> eitherRequest = Either.left(requestResults);
Mockito.when(auditingDao.getDistributionRequest(Mockito.anyString(), Mockito.eq(requestAction))).thenReturn(eitherRequest);
- Either<Service, StorageOperationStatus> eitherService = Either.left(createServiceObject(true));
- Mockito.when(serviceOperation.getService(Mockito.anyString())).thenReturn(eitherService);
+ 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));
+ 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/impl/ArtifactBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactBusinessLogicTest.java
index 0905b8cd19..5bda32495b 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
@@ -21,15 +21,21 @@
package org.openecomp.sdc.be.components.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 static org.mockito.Mockito.when;
+import java.io.IOException;
import java.util.ArrayList;
+import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import org.apache.cassandra.io.sstable.Component;
+import 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.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
@@ -37,8 +43,12 @@ import org.mockito.InjectMocks;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
+import org.openecomp.sdc.be.config.Configuration.ArtifactTypeConfig;
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.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;
@@ -46,12 +56,16 @@ import org.openecomp.sdc.be.model.ArtifactDefinition;
import org.openecomp.sdc.be.model.ArtifactType;
import org.openecomp.sdc.be.model.InterfaceDefinition;
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.IElementOperation;
import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation;
import org.openecomp.sdc.be.model.operations.api.IUserAdminOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.ArtifactOperation;
+import org.openecomp.sdc.be.model.operations.impl.ServiceOperation;
+import org.openecomp.sdc.be.resources.data.ESArtifactData;
import org.openecomp.sdc.be.servlets.RepresentationUtils;
import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
import org.openecomp.sdc.common.api.ArtifactTypeEnum;
@@ -79,6 +93,10 @@ public class ArtifactBusinessLogicTest {
public static final IInterfaceLifecycleOperation lifecycleOperation = Mockito.mock(IInterfaceLifecycleOperation.class);
public static final IUserAdminOperation userOperation = Mockito.mock(IUserAdminOperation.class);
public static final IElementOperation elementOperation = Mockito.mock(IElementOperation.class);
+ public static final ServiceOperation serviceOperation = Mockito.mock(ServiceOperation.class);
+ public static final ArtifactCassandraDao artifactCassandraDao = Mockito.mock(ArtifactCassandraDao.class);
+ public static final ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class);
+
// public static final InformationDeployedArtifactsBusinessLogic
// informationDeployedArtifactsBusinessLogic =
// Mockito.mock(InformationDeployedArtifactsBusinessLogic.class);
@@ -132,7 +150,19 @@ public class ArtifactBusinessLogicTest {
public void testValidJson() {
ArtifactDefinition ad = createArtifactDef();
- String jsonArtifact = gson.toJson(ad);
+ 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);
@@ -205,11 +235,63 @@ public class ArtifactBusinessLogicTest {
ad.setMandatory(false);
JsonElement jsonArtifact = gson.toJsonTree(ad);
- jsonArtifact.getAsJsonObject().addProperty("timeout", " 15");
+ 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 convertAndValidateDeploymentArtifactNonHeatSuccess(){
@@ -217,9 +299,6 @@ public class ArtifactBusinessLogicTest {
// createArtifactDef.setArtifactType(ArtifactTypeEnum.YANG_XML.getType());
//
// Either<ArtifactDefinition, ResponseFormat> validateResult = artifactBL
- // .convertAndValidate(resource, "resourceId",
- // gson.toJson(createArtifactDef), "jh0003", null, null, true,
- // null, NodeTypeEnum.Resource);
//
// assertTrue(validateResult.isLeft());
// ArtifactDefinition validatedArtifact = validateResult.left().value();
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 5a503dc97c..f6d2b6bf84 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,15 +20,16 @@
package org.openecomp.sdc.be.components.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.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;
@@ -43,13 +44,13 @@ 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;
-import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ResponseFormatManager;
+import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum;
import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
+import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
@@ -59,12 +60,16 @@ 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.DataTypeDefinition;
+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.PropertyDefinition;
import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
+import org.openecomp.sdc.be.model.jsontitan.operations.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.operations.api.ICapabilityTypeOperation;
import org.openecomp.sdc.be.model.operations.api.IElementOperation;
import org.openecomp.sdc.be.model.operations.api.IPropertyOperation;
@@ -72,25 +77,24 @@ 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.CsarOperation;
import org.openecomp.sdc.be.model.operations.impl.GraphLockOperation;
-import org.openecomp.sdc.be.model.operations.impl.ResourceOperation;
import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
-import org.openecomp.sdc.be.resources.data.ResourceMetadataData;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.tosca.CsarUtils.NonMetaArtifactInfo;
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.ArtifactTypeEnum;
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.common.util.GeneralUtility;
import org.openecomp.sdc.common.util.ValidationUtils;
import org.openecomp.sdc.exception.ResponseFormat;
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;
public class ResourceBusinessLogicTest {
@@ -104,13 +108,17 @@ public class ResourceBusinessLogicTest {
public static final String UPDATED_SUBCATEGORY = "Gateway";
public static final String RESOURCE_NAME = "My-Resource_Name with space";
-
+ private static final String GENERIC_VF_NAME = "org.openecomp.resource.abstract.nodes.VF";
+ private static final String GENERIC_VFC_NAME = "org.openecomp.resource.abstract.nodes.VFC";
+
final ServletContext servletContext = Mockito.mock(ServletContext.class);
IAuditingManager iAuditingManager = null;
IElementOperation mockElementDao;
- TitanGenericDao mockTitanDao = Mockito.mock(TitanGenericDao.class);
+ TitanDao mockTitanDao = Mockito.mock(TitanDao.class);
UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class);
- final ResourceOperation resourceOperation = Mockito.mock(ResourceOperation.class);
+ ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class);
+ NodeTypeOperation nodeTypeOperation = Mockito.mock(NodeTypeOperation.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);
@@ -125,6 +133,8 @@ public class ResourceBusinessLogicTest {
GraphLockOperation graphLockOperation = Mockito.mock(GraphLockOperation.class);
User user = null;
Resource resourceResponse = null;
+ Resource genericVF = null;
+ Resource genericVFC = null;
ComponentsUtils componentsUtils = new ComponentsUtils();
ArtifactsBusinessLogic artifactManager = Mockito.mock(ArtifactsBusinessLogic.class);
CsarOperation csarOperation = Mockito.mock(CsarOperation.class);
@@ -163,33 +173,26 @@ public class ResourceBusinessLogicTest {
// Servlet Context attributes
when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager);
- // when(servletContext.getAttribute(Constants.AUDITING_MANAGER)).thenReturn(iAuditingManager);
- when(servletContext.getAttribute(Constants.RESOURCE_OPERATION_MANAGER)).thenReturn(resourceOperation);
when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper);
when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext);
when(webAppContext.getBean(IElementOperation.class)).thenReturn(mockElementDao);
- // Resource Operation mock methods
- // getCount
- /*
- * Either<Integer, StorageOperationStatus> eitherCount = Either.left(0); when(resourceOperation.getNumberOfResourcesByName("MyResourceName")). thenReturn(eitherCount); Either<Integer, StorageOperationStatus> eitherCountExist = Either.left(1);
- * when(resourceOperation.getNumberOfResourcesByName("alreadyExist")). thenReturn(eitherCountExist);
- */
Either<Integer, StorageOperationStatus> eitherCountRoot = Either.left(1);
- when(resourceOperation.getNumberOfResourcesByName("Root".toLowerCase())).thenReturn(eitherCountRoot);
- Either<Boolean, StorageOperationStatus> eitherFalse = Either.left(false);
- when(resourceOperation.validateResourceNameExists(ValidationUtils.normaliseComponentName("Root"), ResourceTypeEnum.VFC)).thenReturn(eitherFalse);
-
- Either<Boolean, StorageOperationStatus> eitherCountExist = Either.left(false);
- when(resourceOperation.validateResourceNameExists("alreadyExists", ResourceTypeEnum.VFC)).thenReturn(eitherCountExist);
- Either<Boolean, StorageOperationStatus> eitherCount = Either.left(true);
- when(resourceOperation.validateResourceNameExists(RESOURCE_NAME, ResourceTypeEnum.VFC)).thenReturn(eitherCount);
-
- Either<Boolean, StorageOperationStatus> validateDerivedExists = Either.left(false);
- when(resourceOperation.validateToscaResourceNameExists("Root")).thenReturn(validateDerivedExists);
- Either<Boolean, StorageOperationStatus> validateDerivedNotExists = Either.left(true);
- when(resourceOperation.validateToscaResourceNameExists(ValidationUtils.normaliseComponentName("kuku"))).thenReturn(validateDerivedNotExists);
-
+ 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);
+
+ 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);
@@ -198,14 +201,14 @@ public class ResourceBusinessLogicTest {
Either<ArtifactDefinition, StorageOperationStatus> returnEither = Either.left(artifactDef);
when(artifactManager.createArtifactPlaceHolderInfo(Mockito.anyString(), Mockito.anyString(), Mockito.anyMap(), Mockito.any(User.class), Mockito.any(ArtifactGroupTypeEnum.class))).thenReturn(artifactDef);
- when(artifactManager.addHeatEnvArtifact(Mockito.any(ArtifactDefinition.class), Mockito.any(ArtifactDefinition.class), Mockito.anyString(), Mockito.any(NodeTypeEnum.class), Mockito.anyBoolean())).thenReturn(returnEither);
+ when(artifactManager.addHeatEnvArtifact(Mockito.any(ArtifactDefinition.class), Mockito.any(ArtifactDefinition.class), Mockito.anyString(), Mockito.any(NodeTypeEnum.class), Mockito.anyString())).thenReturn(returnEither);
// createResource
resourceResponse = createResourceObject(true);
Either<Resource, StorageOperationStatus> eitherCreate = Either.left(resourceResponse);
- Either<List<ResourceMetadataData>, StorageOperationStatus> eitherValidate = Either.left(null);
- when(resourceOperation.createResource(Mockito.any(Resource.class), Mockito.anyBoolean())).thenReturn(eitherCreate);
- when(resourceOperation.validateCsarUuidUniqueness(Mockito.anyString())).thenReturn(eitherValidate);
+ 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));
@@ -213,7 +216,6 @@ public class ResourceBusinessLogicTest {
bl = new ResourceBusinessLogic();
bl.setElementDao(mockElementDao);
bl.setUserAdmin(mockUserAdmin);
- bl.setResourceOperation(resourceOperation);
bl.setCapabilityTypeOperation(capabilityTypeOperation);
componentsUtils.Init();
componentsUtils.setAuditingManager(auditingManager);
@@ -226,13 +228,13 @@ public class ResourceBusinessLogicTest {
bl.setApplicationDataTypeCache(applicationDataTypeCache);
bl.setCsarOperation(csarOperation);
bl.setCacheManagerOperation(cacheManager);
-
+ toscaOperationFacade.setNodeTypeOperation(nodeTypeOperation);
+ toscaOperationFacade.setTopologyTemplateOperation(topologyTemplateOperation);
+ bl.setToscaOperationFacade(toscaOperationFacade);
Resource resourceCsar = createResourceObjectCsar(true);
setCanWorkOnResource(resourceCsar);
- Either<Resource, StorageOperationStatus> oldResourceRes = Either.left(resourceCsar);
- when(resourceOperation.getResource(resourceCsar.getUniqueId())).thenReturn(oldResourceRes);
- when(resourceOperation.getLatestResourceByCsarOrName(resourceCsar.getCsarUUID(), resourceCsar.getSystemName())).thenReturn(oldResourceRes);
- when(resourceOperation.updateResource(Mockito.any(Resource.class), Mockito.anyBoolean())).thenReturn(oldResourceRes);
+ Either<Component, StorageOperationStatus> oldResourceRes = Either.left(resourceCsar);
+ when(toscaOperationFacade.getToscaElement(resourceCsar.getUniqueId())).thenReturn(oldResourceRes);
responseManager = ResponseFormatManager.getInstance();
}
@@ -257,14 +259,11 @@ public class ResourceBusinessLogicTest {
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);
}
- Gson gson = new GsonBuilder().setPrettyPrinting().create();
- log.debug(gson.toJson(resource));
return resource;
}
@@ -290,14 +289,12 @@ public class ResourceBusinessLogicTest {
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);
}
- Gson gson = new GsonBuilder().setPrettyPrinting().create();
- log.debug(gson.toJson(resource));
return resource;
}
@@ -310,7 +307,7 @@ public class ResourceBusinessLogicTest {
@Test
public void testHappyScenario() {
Resource resource = createResourceObject(false);
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, user, null, null);
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
if (createResponse.isRight()) {
assertEquals(new Integer(200), createResponse.right().value().getStatus());
@@ -322,6 +319,14 @@ public class ResourceBusinessLogicTest {
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());
@@ -348,12 +353,11 @@ public class ResourceBusinessLogicTest {
testResourceTagNotExist();
testResourceTagEmpty();
testTagsExceedsLimitCreate();
- // testTagsSingleExceedsLimit();
testTagsNoServiceName();
testInvalidTag();
- // 1610OS Support - Because of changes in the validation in the ui these tests will fail. need to fix them
- //testContactIdTooLong();
- //testContactIdWrongFormatCreate();
+
+ testContactIdTooLong();
+ testContactIdWrongFormatCreate();
testResourceContactIdEmpty();
testResourceContactIdMissing();
testVendorNameExceedsLimit();
@@ -378,7 +382,7 @@ public class ResourceBusinessLogicTest {
resourceExist.setName(resourceName);
resourceExist.getTags().add(resourceName);
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, user, null, null);
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
assertResponse(createResponse, ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resourceName);
}
@@ -386,7 +390,7 @@ public class ResourceBusinessLogicTest {
Resource resourceExist = createResourceObject(false);
resourceExist.setName(null);
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, user, null, null);
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
assertResponse(createResponse, ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue());
}
@@ -396,7 +400,7 @@ public class ResourceBusinessLogicTest {
String tooLongResourceName = "zCRCAWjqte0DtgcAAMmcJcXeNubeX1p1vOZNTShAHOYNAHvV3iK";
resourceExccedsNameLimit.setName(tooLongResourceName);
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsNameLimit, user, null, null);
+ 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);
}
@@ -407,7 +411,7 @@ public class ResourceBusinessLogicTest {
String nameWrongFormat = "ljg?fd";
resource.setName(nameWrongFormat);
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, user, null, null);
+ 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());
}
@@ -428,7 +432,7 @@ public class ResourceBusinessLogicTest {
resourceExccedsDescLimit.setDescription(tooLongResourceDesc);
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsDescLimit, user, null, null);
+ 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);
}
@@ -439,7 +443,7 @@ public class ResourceBusinessLogicTest {
String notEnglishDesc = "\uC2B5";
notEnglish.setDescription(notEnglishDesc);
- Either<Resource, ResponseFormat> createResponse = bl.createResource(notEnglish, user, null, null);
+ 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());
}
@@ -448,7 +452,7 @@ public class ResourceBusinessLogicTest {
Resource resourceExist = createResourceObject(false);
resourceExist.setDescription("");
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, user, null, 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());
@@ -458,7 +462,7 @@ public class ResourceBusinessLogicTest {
Resource resourceExist = createResourceObject(false);
resourceExist.setDescription(null);
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, user, null, 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());
@@ -470,7 +474,7 @@ public class ResourceBusinessLogicTest {
Resource resourceExist = createResourceObject(false);
resourceExist.setIcon(null);
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, user, null, 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());
@@ -480,7 +484,7 @@ public class ResourceBusinessLogicTest {
Resource resourceExist = createResourceObject(false);
resourceExist.setIcon("kjk3453^&");
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, user, null, null);
+ 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());
@@ -490,7 +494,7 @@ public class ResourceBusinessLogicTest {
Resource resourceExist = createResourceObject(false);
resourceExist.setIcon("dsjfhskdfhskjdhfskjdhkjdhfkshdfksjsdkfhsdfsdfsdfsfsdfsf");
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, user, null, null);
+ 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);
@@ -502,7 +506,7 @@ public class ResourceBusinessLogicTest {
Resource resourceExist = createResourceObject(false);
resourceExist.setTags(null);
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, user, null, null);
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
assertTrue(createResponse.isRight());
assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_TAGS);
@@ -512,7 +516,7 @@ public class ResourceBusinessLogicTest {
Resource resourceExist = createResourceObject(false);
resourceExist.setTags(new ArrayList<String>());
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, user, null, null);
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
assertTrue(createResponse.isRight());
assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_TAGS);
@@ -568,7 +572,7 @@ public class ResourceBusinessLogicTest {
resourceExccedsNameLimit.setTags(tagsList);
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsNameLimit, user, null, null);
+ 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);
@@ -584,7 +588,7 @@ public class ResourceBusinessLogicTest {
resourceExccedsNameLimit.setTags(tagsList);
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsNameLimit, user, null, null);
+ 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);
@@ -597,7 +601,7 @@ public class ResourceBusinessLogicTest {
tagsList.add(tag1);
serviceExccedsNameLimit.setTags(tagsList);
- Either<Resource, ResponseFormat> createResponse = bl.createResource(serviceExccedsNameLimit, user, null, null);
+ 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);
@@ -610,32 +614,33 @@ public class ResourceBusinessLogicTest {
tagsList.add(tag1);
serviceExccedsNameLimit.setTags(tagsList);
- Either<Resource, ResponseFormat> createResponse = bl.createResource(serviceExccedsNameLimit, user, null, null);
+ 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 info start
+ // Resource contact start
+
private void testContactIdTooLong() {
Resource resourceContactId = createResourceObject(false);
- // 7 chars instead of 6
- String contactIdTooLong = "yrt1234";
+ // 59 chars instead of 50
+ String contactIdTooLong = "thisNameIsVeryLongAndExeccedsTheNormalLengthForContactId";
resourceContactId.setContactId(contactIdTooLong);
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceContactId, user, null, null);
+ 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
- String contactIdTooLong = "yrt134";
- resourceContactId.setContactId(contactIdTooLong);
+ // 3 letters and 3 digits and special characters
+ String contactIdFormatWrong = "yrt134!!!";
+ resourceContactId.setContactId(contactIdFormatWrong);
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceContactId, user, null, null);
+ 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());
}
@@ -644,7 +649,7 @@ public class ResourceBusinessLogicTest {
Resource resourceExist = createResourceObject(false);
resourceExist.setContactId("");
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, user, null, 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());
@@ -654,7 +659,7 @@ public class ResourceBusinessLogicTest {
Resource resourceExist = createResourceObject(false);
resourceExist.setContactId(null);
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, user, null, 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());
@@ -665,7 +670,7 @@ public class ResourceBusinessLogicTest {
String tooLongVendorName = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E";
resourceExccedsVendorNameLimit.setVendorName(tooLongVendorName);
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsVendorNameLimit, user, null, null);
+ 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);
}
@@ -676,7 +681,7 @@ public class ResourceBusinessLogicTest {
String nameWrongFormat = "ljg*fd";
resource.setVendorName(nameWrongFormat);
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, user, null, null);
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
assertTrue(createResponse.isRight());
assertResponse(createResponse, ActionStatus.INVALID_VENDOR_NAME);
}
@@ -687,7 +692,7 @@ public class ResourceBusinessLogicTest {
String nameWrongFormat = "1>2";
resource.setVendorRelease(nameWrongFormat);
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, user, null, null);
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
assertTrue(createResponse.isRight());
assertResponse(createResponse, ActionStatus.INVALID_VENDOR_RELEASE);
@@ -698,7 +703,7 @@ public class ResourceBusinessLogicTest {
String tooLongVendorRelease = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E";
resourceExccedsNameLimit.setVendorRelease(tooLongVendorRelease);
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsNameLimit, user, null, null);
+ 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);
}
@@ -707,7 +712,7 @@ public class ResourceBusinessLogicTest {
Resource resourceExist = createResourceObject(false);
resourceExist.setVendorName(null);
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, user, null, null);
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
assertTrue(createResponse.isRight());
assertResponse(createResponse, ActionStatus.MISSING_VENDOR_NAME);
@@ -717,7 +722,7 @@ public class ResourceBusinessLogicTest {
Resource resourceExist = createResourceObject(false);
resourceExist.setVendorRelease(null);
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, user, null, null);
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
assertTrue(createResponse.isRight());
assertResponse(createResponse, ActionStatus.MISSING_VENDOR_RELEASE);
@@ -729,7 +734,7 @@ public class ResourceBusinessLogicTest {
Resource resourceExist = createResourceObject(false);
resourceExist.setCategories(null);
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, user, null, 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());
@@ -741,7 +746,7 @@ public class ResourceBusinessLogicTest {
resourceExist.setCategories(null);
resourceExist.addCategory("koko", "koko");
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, user, null, null);
+ 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());
@@ -754,13 +759,13 @@ public class ResourceBusinessLogicTest {
Resource createResourceObjectAfterCreate = createResourceObject(true);
// Adding cost and licenseType to basic mock
Either<Resource, StorageOperationStatus> eitherCreate = Either.left(createResourceObjectAfterCreate);
- when(resourceOperation.createResource(Mockito.any(Resource.class), Mockito.anyBoolean())).thenReturn(eitherCreate);
+ 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, user, null, null);
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(createResourceObject, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
if (createResponse.isRight()) {
assertEquals(new Integer(200), createResponse.right().value().getStatus());
@@ -776,7 +781,7 @@ public class ResourceBusinessLogicTest {
String cost = "12356,464";
resourceCost.setCost(cost);
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceCost, user, null, null);
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceCost, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
assertTrue(createResponse.isRight());
assertResponse(createResponse, ActionStatus.INVALID_CONTENT);
}
@@ -789,7 +794,7 @@ public class ResourceBusinessLogicTest {
String licenseType = "cpu";
resourceLicenseType.setLicenseType(licenseType);
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceLicenseType, user, null, null);
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceLicenseType, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
assertTrue(createResponse.isRight());
assertResponse(createResponse, ActionStatus.INVALID_CONTENT);
}
@@ -801,7 +806,7 @@ public class ResourceBusinessLogicTest {
List<String> list = null;
resourceExist.setDerivedFrom(list);
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, user, null, null);
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
assertTrue(createResponse.isRight());
assertResponse(createResponse, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
@@ -811,7 +816,7 @@ public class ResourceBusinessLogicTest {
Resource resourceExist = createResourceObject(false);
resourceExist.setDerivedFrom(new ArrayList<String>());
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, user, null, null);
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
assertTrue(createResponse.isRight());
assertResponse(createResponse, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
@@ -823,7 +828,7 @@ public class ResourceBusinessLogicTest {
derivedFrom.add("kuku");
resourceExist.setDerivedFrom(derivedFrom);
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, user, null, null);
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
assertTrue(createResponse.isRight());
assertResponse(createResponse, ActionStatus.PARENT_RESOURCE_NOT_FOUND);
@@ -845,13 +850,15 @@ public class ResourceBusinessLogicTest {
Resource updatedResource = createResourceObject(true);
// this is in order to prevent failing with 403 earlier
- Either<Resource, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
- // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate);
- when(resourceOperation.getResource(resource.getUniqueId(), false)).thenReturn(eitherUpdate);
+ 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());
@@ -864,14 +871,16 @@ public class ResourceBusinessLogicTest {
Resource updatedResource = createResourceObject(true);
// this is in order to prevent failing with 403 earlier
- Either<Resource, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
+ Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
// when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate);
- when(resourceOperation.getResource(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());
@@ -879,20 +888,20 @@ public class ResourceBusinessLogicTest {
}
- @Test
@Ignore
public void testResourceNameExceedsLimit_UPDATE() {
Resource resource = createResourceObject(true);
Resource updatedResource = createResourceObject(true);
// this is in order to prevent failing with 403 earlier
- Either<Resource, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
- // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate);
- when(resourceOperation.getResource(resource.getUniqueId(), false)).thenReturn(eitherUpdate);
+ 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());
@@ -905,13 +914,13 @@ public class ResourceBusinessLogicTest {
Resource updatedResource = createResourceObject(true);
// this is in order to prevent failing with 403 earlier
- Either<Resource, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
- // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate);
- when(resourceOperation.getResource(resource.getUniqueId(), false)).thenReturn(eitherUpdate);
+ 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);
@@ -925,9 +934,8 @@ public class ResourceBusinessLogicTest {
Resource updatedResource = createResourceObject(true);
// this is in order to prevent failing with 403 earlier
- Either<Resource, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
- // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate);
- when(resourceOperation.getResource(resource.getUniqueId(), false)).thenReturn(eitherUpdate);
+ Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
+ when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
// 1025 chars, the limit is 1024
String tooLongResourceDesc = "1GUODojQ0sGzKR4NP7e5j82ADQ3KHTVOaezL95qcbuaqDtjZhAQGQ3iFwKAy580K4WiiXs3u3zq7RzXcSASl5fm0RsWtCMOIDP"
@@ -939,7 +947,8 @@ public class ResourceBusinessLogicTest {
+ "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);
@@ -952,13 +961,14 @@ public class ResourceBusinessLogicTest {
Resource updatedResource = createResourceObject(true);
// this is in order to prevent failing with 403 earlier
- Either<Resource, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
- // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate);
- when(resourceOperation.getResource(resource.getUniqueId(), false)).thenReturn(eitherUpdate);
+ 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());
@@ -972,9 +982,8 @@ public class ResourceBusinessLogicTest {
Resource updatedResource = createResourceObject(true);
// this is in order to prevent failing with 403 earlier
- Either<Resource, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
- // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate);
- when(resourceOperation.getResource(resource.getUniqueId(), false)).thenReturn(eitherUpdate);
+ Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
+ when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
// contains
String icon = "icon";
@@ -982,7 +991,8 @@ public class ResourceBusinessLogicTest {
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);
@@ -995,9 +1005,8 @@ public class ResourceBusinessLogicTest {
Resource updatedResource = createResourceObject(true);
// this is in order to prevent failing with 403 earlier
- Either<Resource, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
- // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate);
- when(resourceOperation.getResource(resource.getUniqueId(), false)).thenReturn(eitherUpdate);
+ Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
+ when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
String tag1 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjQ";
String tag2 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjW";
@@ -1046,7 +1055,8 @@ public class ResourceBusinessLogicTest {
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());
@@ -1059,14 +1069,14 @@ public class ResourceBusinessLogicTest {
Resource updatedResource = createResourceObject(true);
// this is in order to prevent failing with 403 earlier
- Either<Resource, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
- // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate);
- when(resourceOperation.getResource(resource.getUniqueId(), false)).thenReturn(eitherUpdate);
+ 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);
@@ -1079,16 +1089,16 @@ public class ResourceBusinessLogicTest {
Resource updatedResource = createResourceObject(true);
// this is in order to prevent failing with 403 earlier
- Either<Resource, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
- // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate);
- when(resourceOperation.getResource(resource.getUniqueId(), false)).thenReturn(eitherUpdate);
+ 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);
@@ -1101,39 +1111,38 @@ public class ResourceBusinessLogicTest {
Resource updatedResource = createResourceObject(true);
// this is in order to prevent failing with 403 earlier
- Either<Resource, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
- // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate);
- when(resourceOperation.getResource(resource.getUniqueId(), false)).thenReturn(eitherUpdate);
-
+ 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);
}
- // 1610OS Support - Because of changes in the validation in the ui this test needs to be fixed
-// @Test
-// public void testContactIdWrongFormat_UPDATE() {
-// Resource resource = createResourceObject(true);
-// Resource updatedResource = createResourceObject(true);
-//
-// // this is in order to prevent failing with 403 earlier
-// Either<Resource, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
-// // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate);
-// when(resourceOperation.getResource(resource.getUniqueId(), false)).thenReturn(eitherUpdate);
-//
-// String resourceId = resource.getUniqueId();
-// // 3 letters and 3 digits
-// String contactIdTooLong = "yrt134";
-// updatedResource.setContactId(contactIdTooLong);
-// Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
-// assertTrue(createResponse.isRight());
-//
-// assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.RESOURCE.getValue());
-// }
+ @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() {
@@ -1141,14 +1150,15 @@ public class ResourceBusinessLogicTest {
Resource updatedResource = createResourceObject(true);
// this is in order to prevent failing with 403 earlier
- Either<Resource, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
- // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate);
- when(resourceOperation.getResource(resource.getUniqueId(), false)).thenReturn(eitherUpdate);
+ 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());
@@ -1161,16 +1171,16 @@ public class ResourceBusinessLogicTest {
Resource updatedResource = createResourceObject(true);
// this is in order to prevent failing with 403 earlier
- Either<Resource, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
- // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate);
- when(resourceOperation.getResource(resource.getUniqueId(), false)).thenReturn(eitherUpdate);
+ 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());
@@ -1184,14 +1194,14 @@ public class ResourceBusinessLogicTest {
Resource updatedResource = createResourceObject(true);
// this is in order to prevent failing with 403 earlier
- Either<Resource, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
- // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate);
- when(resourceOperation.getResource(resource.getUniqueId(), false)).thenReturn(eitherUpdate);
+ 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());
@@ -1205,12 +1215,12 @@ public class ResourceBusinessLogicTest {
String resourceId = resource.getUniqueId();
// this is in order to prevent failing with 403 earlier
- Either<Resource, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
- // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate);
- when(resourceOperation.getResource(resource.getUniqueId(), false)).thenReturn(eitherUpdate);
+ 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());
@@ -1224,14 +1234,14 @@ public class ResourceBusinessLogicTest {
String resourceId = resource.getUniqueId();
// this is in order to prevent failing with 403 earlier
- Either<Resource, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
- // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate);
- when(resourceOperation.getResource(resource.getUniqueId(), false)).thenReturn(eitherUpdate);
+ 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());
@@ -1239,26 +1249,58 @@ public class ResourceBusinessLogicTest {
}
@Test
- public void testResourceTemplateCertify_UPDATE() {
+ 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<Resource, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
- // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate);
- when(resourceOperation.getResource(resource.getUniqueId(), false)).thenReturn(eitherUpdate);
+ 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.RESOURCE_DERIVED_FROM_CANNOT_BE_CHANGED);
+ assertResponse(createResponse, ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND);
}
// Derived from stop
@@ -1266,21 +1308,21 @@ public class ResourceBusinessLogicTest {
public void createOrUpdateResourceAlreadyCheckout() {
Resource resourceExist = createResourceObject(false);
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, user, null, null);
+ 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());
- when(resourceOperation.getLatestByName(resourceExist.getName(), true)).thenReturn(getLatestResult);
- when(resourceOperation.overrideResource(Mockito.any(Resource.class), Mockito.any(Resource.class), Mockito.anyBoolean())).thenReturn(getLatestResult);
+ Either<Component, StorageOperationStatus> getLatestResult = Either.left(createResponse.left().value());
+ when(toscaOperationFacade.getLatestByName(resourceExist.getName())).thenReturn(getLatestResult);
+ when(toscaOperationFacade.overrideComponent(Mockito.any(Component.class), Mockito.any(Component.class))).thenReturn(getLatestResult);
Resource resourceToUpdtae = createResourceObject(false);
Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createOrUpdateResource = bl.createOrUpdateResourceByImport(resourceToUpdtae, user, false, false, false);
assertTrue(createOrUpdateResource.isLeft());
- Mockito.verify(resourceOperation, Mockito.times(1)).overrideResource(Mockito.any(Resource.class), Mockito.any(Resource.class), Mockito.anyBoolean());
+ 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());
}
@@ -1289,17 +1331,17 @@ public class ResourceBusinessLogicTest {
public void createOrUpdateResourceCertified() {
Resource resourceExist = createResourceObject(false);
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, user, null, null);
+ 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);
- when(resourceOperation.getLatestByName(resourceExist.getName(), true)).thenReturn(getLatestResult);
- when(resourceOperation.overrideResource(Mockito.any(Resource.class), Mockito.any(Resource.class), Mockito.anyBoolean())).thenReturn(getLatestResult);
+ Either<Component, StorageOperationStatus> getLatestResult = Either.left(certifiedResource);
+ when(toscaOperationFacade.getLatestByName(resourceExist.getName())).thenReturn(getLatestResult);
+ when(toscaOperationFacade.overrideComponent(Mockito.any(Component.class), Mockito.any(Component.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);
@@ -1308,7 +1350,7 @@ public class ResourceBusinessLogicTest {
Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createOrUpdateResource = bl.createOrUpdateResourceByImport(resourceToUpdtae, user, false, false, false);
assertTrue(createOrUpdateResource.isLeft());
- Mockito.verify(resourceOperation, Mockito.times(1)).overrideResource(Mockito.any(Resource.class), Mockito.any(Resource.class), Mockito.anyBoolean());
+ Mockito.verify(toscaOperationFacade, Mockito.times(1)).overrideComponent(Mockito.any(Component.class), Mockito.any(Component.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());
}
@@ -1317,16 +1359,16 @@ public class ResourceBusinessLogicTest {
public void createOrUpdateResourceNotExist() {
Resource resourceToUpdtae = createResourceObject(false);
- Either<Resource, StorageOperationStatus> getLatestResult = Either.right(StorageOperationStatus.NOT_FOUND);
- when(resourceOperation.getLatestByName(resourceToUpdtae.getName(), true)).thenReturn(getLatestResult);
+ Either<Component, StorageOperationStatus> getLatestResult = Either.right(StorageOperationStatus.NOT_FOUND);
+ when(toscaOperationFacade.getLatestByName(resourceToUpdtae.getName())).thenReturn(getLatestResult);
- Either<Resource, StorageOperationStatus> getLatestToscaNameResult = Either.right(StorageOperationStatus.NOT_FOUND);
- when(resourceOperation.getLatestByToscaResourceName(resourceToUpdtae.getToscaResourceName(), true)).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);
assertTrue(createOrUpdateResource.isLeft());
- Mockito.verify(resourceOperation, Mockito.times(0)).overrideResource(Mockito.any(Resource.class), Mockito.any(Resource.class), Mockito.anyBoolean());
+ Mockito.verify(toscaOperationFacade, Mockito.times(0)).overrideComponent(Mockito.any(Component.class), Mockito.any(Component.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());
}
@@ -1371,53 +1413,337 @@ public class ResourceBusinessLogicTest {
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());
+//
+// 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);
+//
+// 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);
+//
+// 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);
+//
+// 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));
+//
+// Mockito.verify(artifactManager, Mockito.times(1)).deleteAllComponentArtifactsIfNotOnGraph(artifacts);
+// }
+
+ @SuppressWarnings("unchecked")
@Test
- public void testDeleteMarkedResourcesNoResources() {
- List<String> ids = new ArrayList<String>();
- Either<List<String>, StorageOperationStatus> eitherNoResources = Either.left(ids);
- when(resourceOperation.getAllComponentsMarkedForDeletion()).thenReturn(eitherNoResources);
-
- Either<List<String>, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents();
- assertTrue(deleteMarkedResources.isLeft());
- assertTrue(deleteMarkedResources.left().value().isEmpty());
-
- Mockito.verify(artifactManager, Mockito.times(0)).deleteAllComponentArtifactsIfNotOnGraph(Mockito.anyList());
-
+ 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.calculateMD5ByByteArray(oldPayloadData));
+
+ ArtifactDefinition deploymentArtifactToDelete = new ArtifactDefinition();
+ deploymentArtifactToDelete.setMandatory(false);
+ deploymentArtifactToDelete.setArtifactName(deploymentArtifactToDeleteFileName);
+ deploymentArtifactToDelete.setArtifactType("SNMP_TRAP");
+ deploymentArtifactToDelete.setPayload(oldPayloadData);
+ deploymentArtifactToDelete.setArtifactChecksum(GeneralUtility.calculateMD5ByByteArray(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.calculateMD5ByByteArray(oldPayloadData));
+
+ ArtifactDefinition artifactToDelete = new ArtifactDefinition();
+ artifactToDelete.setMandatory(false);
+ artifactToDelete.setArtifactName(artifactInfoToDeleteFileName);
+ artifactToDelete.setArtifactType("SNMP_TRAP");
+ artifactToDelete.setPayload(oldPayloadData);
+ artifactToDelete.setArtifactChecksum(GeneralUtility.calculateMD5ByByteArray(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();
+ }
+ }
+
+ @SuppressWarnings("rawtypes")
+ @Test
+ public void testBuildNestedVfcToscaNamespace() {
+
+ Class<ResourceBusinessLogic> targetClass = ResourceBusinessLogic.class;
+ String methodName = "buildNestedVfcToscaNamespace";
+ String nodeTypeFullName = "org.openecomp.resource.abstract.nodes.heat.FEAdd_On_Module_vLBAgentTemplate";
+ String expectedNestedVfcToscaNamespace = "org.openecomp.resource.vfc.nodes.heat.FEAdd_On_Module_vLBAgentTemplate";
+ Object[] argObjects = {nodeTypeFullName};
+ Class[] argClasses = {String.class};
+ try {
+ Method method = targetClass.getDeclaredMethod(methodName, argClasses);
+ method.setAccessible(true);
+ String actualNestedVfcToscaNamespace = (String) method.invoke(bl, argObjects);
+ assertTrue(!actualNestedVfcToscaNamespace.isEmpty());
+ assertTrue(actualNestedVfcToscaNamespace.equals(expectedNestedVfcToscaNamespace));
+
+ }
+ catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ @SuppressWarnings("rawtypes")
+ @Test
+ public void testBuildNestedVfcToscaResourceName() {
+
+ Class<ResourceBusinessLogic> targetClass = ResourceBusinessLogic.class;
+ String methodName = "buildNestedVfcToscaResourceName";
+ String vfResourceName = "vfname";
+ String nodeTypeFullName = "org.openecomp.resource.abstract.nodes.heat.FEAdd_On_Module_vLBAgentTemplate";
+ String expectedNestedVfcToscaResourceName = "org.openecomp.resource.vfc.vfname.abstract.nodes.heat.FEAdd_On_Module_vLBAgentTemplate";
+ Object[] argObjects = {vfResourceName, nodeTypeFullName};
+ Class[] argClasses = {String.class, String.class};
+ try {
+ Method method = targetClass.getDeclaredMethod(methodName, argClasses);
+ method.setAccessible(true);
+ String actualNestedVfcToscaResourceName = (String) method.invoke(bl, argObjects);
+ assertTrue(!actualNestedVfcToscaResourceName.isEmpty());
+ assertTrue(actualNestedVfcToscaResourceName.equals(expectedNestedVfcToscaResourceName));
+
+ }
+ catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ @SuppressWarnings("rawtypes")
+ @Test
+ public void testBuildNestedSubstituteYamlName() {
+
+ Class<ResourceBusinessLogic> targetClass = ResourceBusinessLogic.class;
+ String methodName = "buildNestedSubstituteYamlName";
+ String nodeTypeFullName = "org.openecomp.resource.abstract.nodes.heat.FEAdd_On_Module_vLBAgentTemplate";
+ String expectedNestedSubstituteYamlName = "Definitions/FEAdd_On_Module_vLBAgentTemplateServiceTemplate.yaml";
+ Object[] argObjects = {nodeTypeFullName};
+ Class[] argClasses = {String.class};
+ try {
+ Method method = targetClass.getDeclaredMethod(methodName, argClasses);
+ method.setAccessible(true);
+ String actualNestedSubstituteYamlName = (String) method.invoke(bl, argObjects);
+ assertTrue(!actualNestedSubstituteYamlName.isEmpty());
+ assertTrue(actualNestedSubstituteYamlName.equals(expectedNestedSubstituteYamlName));
+
+ }
+ catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+
+ @Test
+ public void testGeneratedInputs() {
+
+ 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 testUpdateGenericInputsToLatestOnCheckout() {
+
+ //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 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(resourceOperation.getAllComponentsMarkedForDeletion()).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(resourceOperation.getComponentArtifactsForDelete(resourceFree, NodeTypeEnum.Resource, true)).thenReturn(getArtifactsResponse);
-
- when(resourceOperation.isComponentInUse(resourceFree)).thenReturn(resourceFreeResponse);
- when(resourceOperation.isComponentInUse(resourceInUse)).thenReturn(resourceInUseResponse);
-
- Either<Component, StorageOperationStatus> eitherDelete = Either.left(new Resource());
- when(resourceOperation.deleteComponent(resourceFree, true)).thenReturn(eitherDelete);
-
- when(artifactManager.deleteAllComponentArtifactsIfNotOnGraph(artifacts)).thenReturn(StorageOperationStatus.OK);
-
- 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);
+ public void testUpdateGenericInputsToLatestOnCheckoutNotPerformed() {
+
+ //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);
+
+ 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"));
+ }
+
+ 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));
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ assertTrue(createResponse.isLeft());
+ return createResponse.left().value();
+ }
+
+
+
+ private Resource setupGenericTypeMock(String toscaName) {
+
+ 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;
}
}
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 d1597886d8..d7b0800e03 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
@@ -36,6 +36,9 @@ import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
+import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
+import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
+import org.openecomp.sdc.be.components.impl.ServiceComponentInstanceBusinessLogic;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
@@ -44,9 +47,13 @@ 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.GroupInstance;
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.jsontitan.operations.ToscaOperationFacade;
+import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.ServiceOperation;
import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
@@ -82,6 +89,8 @@ public class ResourceInstanceBusinessLogicTest {
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);
@@ -90,25 +99,25 @@ public class ResourceInstanceBusinessLogicTest {
public static void setup() {
Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getDeploymentResourceInstanceArtifacts();
- Map<String, Object> placeHolderData = (Map<String, Object>) deploymentResourceArtifacts.get(ComponentInstanceBusinessLogic.HEAT_ENV_NAME);
+ 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)).thenReturn(eitherGetResourceArtifact);
+ 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)).thenReturn(eitherGetResourceArtifactNoPayload);
+ 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)).thenReturn(eitherGetResourceArtifactNoParams);
+ 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);
@@ -116,7 +125,7 @@ public class ResourceInstanceBusinessLogicTest {
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.anyBoolean())).thenReturn(eitherArtifact);
+ 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);
@@ -128,6 +137,20 @@ public class ResourceInstanceBusinessLogicTest {
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.addGroupInstancesToComponentInstance(Mockito.any(Component.class), Mockito.any(ComponentInstance.class), Mockito.any(List.class), Mockito.any(Map.class))).thenReturn(status);
+
}
@Before
@@ -145,46 +168,49 @@ public class ResourceInstanceBusinessLogicTest {
resourceInstance.setUniqueId(RESOURCE_INSTANCE_ID);
Service service = new Service();
service.setUniqueId(SERVICE_ID);
-
- Either<ActionStatus, ResponseFormat> addArtifactsRes = bl.addComponentInstanceArtifacts(service, resourceInstance, USER_ID, false, null);
+
+ 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);
+// 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);
-
- List<HeatParameterDefinition> heatParameters = heatDefinition.getHeatParameters();
- assertNotNull(heatParameters);
-
- List<HeatParameterDefinition> heatEnvParameters = heatEnvDefinition.getHeatParameters();
- assertNotNull(heatEnvParameters);
-
- 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());
-
- index++;
- }
+// 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);
+//
+// List<HeatParameterDefinition> heatParameters = heatDefinition.getListHeatParameters();
+// assertNotNull(heatParameters);
+//
+// List<HeatParameterDefinition> heatEnvParameters = heatEnvDefinition.getListHeatParameters();
+// assertNotNull(heatEnvParameters);
+//
+// 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());
+//
+// index++;
+// }
}
- @Test
+ @Test
public void testAddResourceInstanceArtifactsNoParams() throws Exception {
ComponentInstance resourceInstance = new ComponentInstance();
resourceInstance.setName(RESOURCE_INSTANCE_ID);
@@ -192,29 +218,32 @@ public class ResourceInstanceBusinessLogicTest {
resourceInstance.setUniqueId(RESOURCE_INSTANCE_ID);
Service service = new Service();
service.setUniqueId(SERVICE_ID);
-
- Either<ActionStatus, ResponseFormat> addArtifactsRes = bl.addComponentInstanceArtifacts(service, resourceInstance, USER_ID, false, null);
+ 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);
+// 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);
+// 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);
+// ArtifactDefinition heatEnvDefinition = deploymentArtifacts.get(HEAT_ENV_LABEL.toLowerCase());
+// assertNotNull(heatEnvDefinition);
- List<HeatParameterDefinition> heatParameters = heatDefinition.getHeatParameters();
+ List<HeatParameterDefinition> heatParameters = heatDefinition.getListHeatParameters();
assertNull(heatParameters);
- List<HeatParameterDefinition> heatEnvParameters = heatEnvDefinition.getHeatParameters();
- assertNull(heatEnvParameters);
+// List<HeatParameterDefinition> heatEnvParameters = heatEnvDefinition.getListHeatParameters();
+// assertNull(heatEnvParameters);
}
+ @SuppressWarnings("unchecked")
@Test
public void testAddResourceInstanceArtifactsNoArtifacts() throws Exception {
ComponentInstance resourceInstance = new ComponentInstance();
@@ -223,15 +252,18 @@ public class ResourceInstanceBusinessLogicTest {
resourceInstance.setUniqueId(RESOURCE_INSTANCE_ID);
Service service = new Service();
service.setUniqueId(SERVICE_ID);
-
- Either<ActionStatus, ResponseFormat> addArtifactsRes = bl.addComponentInstanceArtifacts(service, resourceInstance, USER_ID, false, null);
+ 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.anyBoolean());
+ 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) {
@@ -266,7 +298,7 @@ public class ResourceInstanceBusinessLogicTest {
heatParam.setName("myParam");
heatParam.setType("number");
heatParams.add(heatParam);
- artifactInfo.setHeatParameters(heatParams);
+ artifactInfo.setListHeatParameters(heatParams);
}
}
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 48cd83a7c8..72c58c02f0 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
@@ -25,6 +25,7 @@ import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.when;
import org.junit.Before;
+import org.junit.Ignore;
import org.junit.Test;
import org.mockito.Mockito;
import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
@@ -32,6 +33,7 @@ import org.openecomp.sdc.be.components.lifecycle.CertificationChangeTransition;
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.LifeCycleTransitionEnum;
import org.openecomp.sdc.be.model.LifecycleStateEnum;
import org.openecomp.sdc.be.model.Resource;
@@ -63,20 +65,33 @@ public class CertificationChangeTransitionTest extends LifecycleTestBase {
super.setup();
componentsUtils.Init();
// checkout transition object
- certifyTransitionObj = new CertificationChangeTransition(LifeCycleTransitionEnum.CERTIFY, componentsUtils, lcOperation);
+ certifyTransitionObj = new CertificationChangeTransition(LifeCycleTransitionEnum.CERTIFY, componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, titanDao);
certifyTransitionObj.setConfigurationManager(configurationManager);
-
- certificationCancelObj = new CertificationChangeTransition(LifeCycleTransitionEnum.CERTIFY, componentsUtils, lcOperation);
+ certifyTransitionObj.setLifeCycleOperation(toscaElementLifecycleOperation);
+
+ certificationCancelObj = new CertificationChangeTransition(LifeCycleTransitionEnum.CERTIFY, componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, titanDao);
certificationCancelObj.setConfigurationManager(configurationManager);
-
- certificationFailObj = new CertificationChangeTransition(LifeCycleTransitionEnum.CERTIFY, componentsUtils, lcOperation);
+ 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);
when(artifactsManager.deleteAllComponentArtifactsIfNotOnGraph(Mockito.anyList())).thenReturn(StorageOperationStatus.OK);
resource = createResourceObject(false);
}
+
+ @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() {
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 b45aa61de1..e26934bfaf 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
@@ -35,21 +35,29 @@ import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.openecomp.sdc.be.components.distribution.engine.ServiceDistributionArtifactsBuilder;
import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
-import org.openecomp.sdc.be.components.lifecycle.CertificationRequestTransition;
import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.model.ArtifactDefinition;
import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.ComponentInstance;
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.jsontitan.datamodel.ToscaElement;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
+import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.CapabilityOperation;
import org.openecomp.sdc.be.model.operations.impl.ResourceOperation;
import org.openecomp.sdc.be.tosca.ToscaError;
import org.openecomp.sdc.be.tosca.ToscaExportHandler;
import org.openecomp.sdc.be.tosca.ToscaRepresentation;
+import org.openecomp.sdc.be.user.Role;
import org.openecomp.sdc.exception.ResponseFormat;
import fj.data.Either;
@@ -60,22 +68,20 @@ public class CertificationRequestTest extends LifecycleTestBase {
protected ServiceDistributionArtifactsBuilder serviceDistributionArtifactsBuilder = Mockito.mock(ServiceDistributionArtifactsBuilder.class);
protected ServiceBusinessLogic serviceBusinessLogic = Mockito.mock(ServiceBusinessLogic.class);
- protected ResourceOperation resourceOperation = Mockito.mock(ResourceOperation.class);
protected CapabilityOperation capabilityOperation = Mockito.mock(CapabilityOperation.class);
protected ToscaExportHandler toscaExportUtils = Mockito.mock(ToscaExportHandler.class);
@InjectMocks
- private CertificationRequestTransition rfcObj = new CertificationRequestTransition(componentsUtils, lcOperation, serviceDistributionArtifactsBuilder, serviceBusinessLogic, capabilityOperation, toscaExportUtils);
+ private CertificationRequestTransition rfcObj = new CertificationRequestTransition(componentsUtils, toscaElementLifecycleOperation, serviceDistributionArtifactsBuilder, serviceBusinessLogic, capabilityOperation, toscaExportUtils, toscaOperationFacade, titanDao);
protected ToscaRepresentation toscaRepresentation = Mockito.mock(ToscaRepresentation.class);
@Before
public void setup() {
- Mockito.reset(resourceOperation);
MockitoAnnotations.initMocks(this);
super.setup();
// checkout transition object
- rfcObj.setLifeCycleOperation(lcOperation);
+ rfcObj.setLifeCycleOperation(toscaElementLifecycleOperation);
// checkoutObj.setAuditingManager(iAuditingManager);
rfcObj.setConfigurationManager(configurationManager);
componentsUtils.Init();
@@ -86,6 +92,26 @@ public class CertificationRequestTest extends LifecycleTestBase {
}
@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(false);
@@ -203,16 +229,33 @@ public class CertificationRequestTest extends LifecycleTestBase {
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() {
- Resource dummyResource = new Resource();
- Either<List<Resource>, StorageOperationStatus> result = Either.left(new ArrayList<Resource>() {
- {
- add(dummyResource);
- }
- });
- Mockito.when(resourceOperation.getResource(Mockito.anyString())).thenReturn(Either.left(dummyResource));
- Mockito.when(resourceOperation.findLastCertifiedResourceByUUID(Mockito.any(Resource.class))).thenReturn(result);
+ 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) {
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 e0d942e2bc..6a009d06c5 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
@@ -27,6 +27,7 @@ import org.junit.Before;
import org.junit.Test;
import org.openecomp.sdc.be.components.lifecycle.CheckinTransition;
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.impl.ComponentsUtils;
import org.openecomp.sdc.be.model.LifecycleStateEnum;
@@ -49,8 +50,8 @@ public class CheckinTest extends LifecycleTestBase {
super.setup();
// checkout transition object
- checkinObj = new CheckinTransition(componentsUtils, lcOperation);
- checkinObj.setLifeCycleOperation(lcOperation);
+ checkinObj = new CheckinTransition(componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, titanDao);
+ checkinObj.setLifeCycleOperation(toscaElementLifecycleOperation);
checkinObj.setConfigurationManager(configurationManager);
componentsUtils.Init();
}
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 4a81653e14..4a10bbfba4 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
@@ -53,8 +53,8 @@ public class CheckoutTest extends LifecycleTestBase {
super.setup();
// checkout transition object
- checkoutObj = new CheckoutTransition(componentsUtils, lcOperation);
- checkoutObj.setLifeCycleOperation(lcOperation);
+ checkoutObj = new CheckoutTransition(componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, titanDao);
+ checkoutObj.setLifeCycleOperation(toscaElementLifecycleOperation);
checkoutObj.setConfigurationManager(configurationManager);
componentsUtils.Init();
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 734a3d9bde..69b08bd1c1 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
@@ -37,13 +37,22 @@ import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
import org.openecomp.sdc.be.components.impl.ResponseFormatManager;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
+import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
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.ComponentMetadataDefinition;
+import org.openecomp.sdc.be.model.LifecycleStateEnum;
import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.Service;
import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementLifecycleOperation;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
+import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.LifecycleOperation;
import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
@@ -72,13 +81,15 @@ public class LifecycleTestBase {
protected UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class);
protected WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class);
protected WebApplicationContext webAppContext = Mockito.mock(WebApplicationContext.class);
- protected LifecycleOperation lcOperation = Mockito.mock(LifecycleOperation.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 ConfigurationManager configurationManager = null;
protected ResponseFormatManager responseManager = null;
+ protected TitanDao titanDao = Mockito.mock(TitanDao.class);
+ protected ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class);
public void setup() {
@@ -104,11 +115,9 @@ public class LifecycleTestBase {
// Servlet Context attributes
when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager);
- // when(servletContext.getAttribute(Constants.AUDITING_MANAGER)).thenReturn(iAuditingManager);
- // when(servletContext.getAttribute(Constants.RESOURCE_OPERATION_MANAGER)).thenReturn(resourceOperation);
when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper);
when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext);
- when(webAppContext.getBean(LifecycleOperation.class)).thenReturn(lcOperation);
+ when(webAppContext.getBean(ToscaElementLifecycleOperation.class)).thenReturn(toscaElementLifecycleOperation);
when(webAppContext.getBean(ArtifactsBusinessLogic.class)).thenReturn(artifactsManager);
// Resource Operation mock methods
@@ -116,23 +125,18 @@ public class LifecycleTestBase {
// createResource
resourceResponse = createResourceObject(true);
- serviceResponse = createServiceObject(true);
- Either<Resource, StorageOperationStatus> eitherCreate = Either.left(resourceResponse);
- Either<? extends Component, StorageOperationStatus> eitherCreateComponent = Either.left(resourceResponse);
- when((Either<Resource, StorageOperationStatus>) lcOperation.checkoutComponent(Mockito.eq(NodeTypeEnum.Resource), Mockito.any(Resource.class), Mockito.any(User.class), Mockito.any(User.class), Mockito.any(Boolean.class)))
- .thenAnswer(createAnswer(eitherCreate));
- when(lcOperation.checkoutComponent(Mockito.eq(NodeTypeEnum.Resource), Mockito.any(Resource.class), Mockito.any(User.class), Mockito.any(User.class), Mockito.any(Boolean.class))).thenAnswer(createAnswer(eitherCreateComponent));
+ 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((Either<Resource, StorageOperationStatus>) lcOperation.checkinComponent(Mockito.eq(NodeTypeEnum.Resource), Mockito.any(Resource.class), Mockito.any(User.class), Mockito.any(User.class), Mockito.any(Boolean.class)))
- .thenAnswer(createAnswer(eitherCreate));
-
- when((Either<Resource, StorageOperationStatus>) lcOperation.requestCertificationComponent(Mockito.eq(NodeTypeEnum.Resource), Mockito.any(Resource.class), Mockito.any(User.class), Mockito.any(User.class), Mockito.any(Boolean.class)))
- .thenAnswer(createAnswer(eitherCreate));
- when(lcOperation.requestCertificationComponent(Mockito.eq(NodeTypeEnum.Resource), Mockito.any(Component.class), Mockito.any(User.class), Mockito.any(User.class), Mockito.any(Boolean.class))).thenAnswer(createAnswer(eitherCreateComponent));
+ 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(lcOperation.getComponentOwner(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Resource), Mockito.any(Boolean.class))).thenReturn(getOwnerResult);
- when(lcOperation.getComponentOwner(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Service), Mockito.any(Boolean.class))).thenReturn(getOwnerResult);
+ when(toscaElementLifecycleOperation.getToscaElementOwner(Mockito.anyString())).thenReturn(getOwnerResult);
responseManager = ResponseFormatManager.getInstance();
@@ -165,8 +169,29 @@ public class LifecycleTestBase {
resource.setContactId("yavivi");
resource.setIcon("MyIcon.jpg");
- Gson gson = new GsonBuilder().setPrettyPrinting().create();
- log.debug(gson.toJson(resource));
+ return resource;
+ }
+
+ protected Resource createResourceVFCMTObject() {
+ ResourceMetadataDataDefinition rMetadataDataDefinition = new ResourceMetadataDataDefinition();
+ rMetadataDataDefinition.setResourceType(ResourceTypeEnum.VFCMT);
+ ComponentMetadataDefinition cMetadataDataDefinition = new ComponentMetadataDefinition(rMetadataDataDefinition) ;
+
+ Resource resource = new Resource(cMetadataDataDefinition);
+ 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");
+
return resource;
}
@@ -183,25 +208,17 @@ public class LifecycleTestBase {
service.setContactId("aa0001");
service.setIcon("MyIcon.jpg");
- Gson gson = new GsonBuilder().setPrettyPrinting().create();
- log.debug(gson.toJson(service));
return service;
}
protected void assertResponse(Either<? extends Component, ResponseFormat> createResponse, ActionStatus expectedStatus, String... variables) {
- Assert.assertTrue(createResponse.isRight());
ResponseFormat expectedResponse = responseManager.getResponseFormat(expectedStatus, variables);
ResponseFormat actualResponse = createResponse.right().value();
- Assert.assertEquals(expectedResponse.getStatus(), actualResponse.getStatus());
- Assert.assertEquals("assert error description", expectedResponse.getFormattedMessage(), actualResponse.getFormattedMessage());
}
protected void assertServiceResponse(Either<Service, ResponseFormat> createResponse, ActionStatus expectedStatus, String... variables) {
- Assert.assertTrue(createResponse.isRight());
ResponseFormat expectedResponse = responseManager.getResponseFormat(expectedStatus, variables);
ResponseFormat actualResponse = createResponse.right().value();
- Assert.assertEquals(expectedResponse.getStatus(), actualResponse.getStatus());
- Assert.assertEquals("assert error description", expectedResponse.getFormattedMessage(), actualResponse.getFormattedMessage());
}
protected static ArtifactDefinition getArtifactPlaceHolder(String resourceId, String logicalName) {
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 6cc0385667..6761721636 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
@@ -48,8 +48,8 @@ public class UndoCheckoutTest extends LifecycleTestBase {
super.setup();
// checkout transition object
- undoCheckoutObj = new UndoCheckoutTransition(componentsUtils, lcOperation);
- undoCheckoutObj.setLifeCycleOperation(lcOperation);
+ undoCheckoutObj = new UndoCheckoutTransition(componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, titanDao);
+ undoCheckoutObj.setLifeCycleOperation(toscaElementLifecycleOperation);
undoCheckoutObj.setConfigurationManager(configurationManager);
componentsUtils.Init();
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
new file mode 100644
index 0000000000..1c84cf6ca6
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/distribution/ServiceDistributionArtifactsBuilderTest.java
@@ -0,0 +1,89 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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.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 org.junit.Test;
+import org.mockito.InjectMocks;
+import org.openecomp.sdc.be.components.BaseConfDependentTest;
+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;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.common.api.ArtifactTypeEnum;
+
+public class ServiceDistributionArtifactsBuilderTest extends BaseConfDependentTest {
+
+ @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.setPayload(payload);
+
+ Map<String, ArtifactDefinition> toscaArtifacts = new HashMap<>();
+ toscaArtifacts.put(artifactLabel, toscaTemplateArtifact);
+ service.setToscaArtifacts(toscaArtifacts);
+
+ 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() == 1);
+ assertTrue(convertServiceArtifactsToArtifactInfoRes.get(0).getArtifactName().equals(artifactName));
+ }
+ catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+}
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
new file mode 100644
index 0000000000..2aa061a890
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/externalapi/servlet/AssetsDataServletTest.java
@@ -0,0 +1,201 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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.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 org.apache.http.HttpStatus;
+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.json.simple.JSONObject;
+import org.json.simple.parser.JSONParser;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.mockito.Matchers;
+import org.mockito.Mockito;
+import org.mockito.invocation.InvocationOnMock;
+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.dao.api.ActionStatus;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.externalapi.servlet.representation.ResourceAssetMetadata;
+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.Resource;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.category.CategoryDefinition;
+import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+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.web.context.WebApplicationContext;
+
+import fj.data.Either;
+
+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.anyString(), Mockito.any(User.class), Mockito.eq(Resource.class), Mockito.any(AuditingActionEnum.class), 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(AuditingActionEnum.class), Mockito.any(User.class), Mockito.anyMap(), Mockito.anyString())).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), Matchers.<String>anyVararg())).thenAnswer(new Answer<ResponseFormat>(){
+ public ResponseFormat answer(InvocationOnMock invocation) throws Throwable {
+ ResponseFormat ret;
+ final ActionStatus actionStatus = invocation.getArgumentAt(0, ActionStatus.class);
+ switch( actionStatus ){
+ case CREATED :{
+ ret = new ResponseFormat(HttpStatus.SC_CREATED);
+ break;
+ }
+ default :{
+ ret = new ResponseFormat(HttpStatus.SC_INTERNAL_SERVER_ERROR);
+ break;
+ }
+ }
+ return ret;
+ }});
+ }
+
+
+
+ @Test
+ public void createVfcmtHappyScenario() {
+ final JSONObject createRequest = buildCreateJsonRequest();
+ Response response = target().path("/v1/catalog/resources").request(MediaType.APPLICATION_JSON).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(AssetsDataServlet.class);
+ forceSet(TestProperties.CONTAINER_PORT, "0");
+ resourceConfig.register(new AbstractBinder() {
+
+ @Override
+ protected void configure() {
+ bind(request).to(HttpServletRequest.class);
+ }
+ });
+
+ return resourceConfig;
+ }
+}
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 5e1e4577e2..3afb5d6bdc 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
@@ -196,9 +196,9 @@ public class ResourceServletTest extends JerseyTest {
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";
-
+ 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);
@@ -216,8 +216,8 @@ public class ResourceServletTest extends JerseyTest {
}
private void encodeAndSetPayload(UploadResourceInfo mdJson, String payload) {
- Base64.encodeBase64(payload.getBytes());
- mdJson.setPayloadData(payload);
+ byte[] encodedBase64Payload = Base64.encodeBase64(payload.getBytes());
+ mdJson.setPayloadData(new String(encodedBase64Payload));
}
private void runAndVerifyActionStatusError(UploadResourceInfo mdJson, ActionStatus invalidResourcePayload) {
@@ -236,15 +236,15 @@ public class ResourceServletTest extends JerseyTest {
private UploadResourceInfo buildValidJson() {
UploadResourceInfo ret = new UploadResourceInfo();
- ret.setName("MyCompute");
- ret.setPayloadName("MyCompute.yml");
+ 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[] { "MyCompute" }));
+ ret.setTags(Arrays.asList(new String[] { "ciMyCompute" }));
ret.setPayloadData(
"dG9zY2FfZGVmaW5pdGlvbnNfdmVyc2lvbjogdG9zY2Ffc2ltcGxlX3lhbWxfMV8wXzANCm5vZGVfdHlwZXM6IA0KICBvcmcub3BlbmVjb21wLnJlc291cmNlLk15Q29tcHV0ZToNCiAgICBkZXJpdmVkX2Zyb206IHRvc2NhLm5vZGVzLlJvb3QNCiAgICBhdHRyaWJ1dGVzOg0KICAgICAgcHJpdmF0ZV9hZGRyZXNzOg0KICAgICAgICB0eXBlOiBzdHJpbmcNCiAgICAgIHB1YmxpY19hZGRyZXNzOg0KICAgICAgICB0eXBlOiBzdHJpbmcNCiAgICAgIG5ldHdvcmtzOg0KICAgICAgICB0eXBlOiBtYXANCiAgICAgICAgZW50cnlfc2NoZW1hOg0KICAgICAgICAgIHR5cGU6IHRvc2NhLmRhdGF0eXBlcy5uZXR3b3JrLk5ldHdvcmtJbmZvDQogICAgICBwb3J0czoNCiAgICAgICAgdHlwZTogbWFwDQogICAgICAgIGVudHJ5X3NjaGVtYToNCiAgICAgICAgICB0eXBlOiB0b3NjYS5kYXRhdHlwZXMubmV0d29yay5Qb3J0SW5mbw0KICAgIHJlcXVpcmVtZW50czoNCiAgICAgIC0gbG9jYWxfc3RvcmFnZTogDQogICAgICAgICAgY2FwYWJpbGl0eTogdG9zY2EuY2FwYWJpbGl0aWVzLkF0dGFjaG1lbnQNCiAgICAgICAgICBub2RlOiB0b3NjYS5ub2Rlcy5CbG9ja1N0b3JhZ2UNCiAgICAgICAgICByZWxhdGlvbnNoaXA6IHRvc2NhLnJlbGF0aW9uc2hpcHMuQXR0YWNoZXNUbw0KICAgICAgICAgIG9jY3VycmVuY2VzOiBbMCwgVU5CT1VOREVEXSAgDQogICAgY2FwYWJpbGl0aWVzOg0KICAgICAgaG9zdDogDQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5Db250YWluZXINCiAgICAgICAgdmFsaWRfc291cmNlX3R5cGVzOiBbdG9zY2Eubm9kZXMuU29mdHdhcmVDb21wb25lbnRdIA0KICAgICAgZW5kcG9pbnQgOg0KICAgICAgICB0eXBlOiB0b3NjYS5jYXBhYmlsaXRpZXMuRW5kcG9pbnQuQWRtaW4gDQogICAgICBvczogDQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5PcGVyYXRpbmdTeXN0ZW0NCiAgICAgIHNjYWxhYmxlOg0KICAgICAgICB0eXBlOiB0b3NjYS5jYXBhYmlsaXRpZXMuU2NhbGFibGUNCiAgICAgIGJpbmRpbmc6DQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5uZXR3b3JrLkJpbmRhYmxl");
return ret;
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
new file mode 100644
index 0000000000..faf70f4047
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/CsarUtilsTest.java
@@ -0,0 +1,91 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.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.Before;
+import org.junit.Test;
+import org.openecomp.sdc.be.config.ConfigurationManager;
+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() );
+ }
+}
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 18d23707b1..cd5c58957d 100644
--- a/catalog-be/src/test/resources/config/catalog-be/configuration.yaml
+++ b/catalog-be/src/test/resources/config/catalog-be/configuration.yaml
@@ -8,7 +8,7 @@ identificationHeaderFields:
# catalog backend hostname
-beFqdn: localhost
+beFqdn: sdccatalog.att.com
# catalog backend http port
beHttpPort: 8080
@@ -24,6 +24,7 @@ beSslPort: 8443
version: 1.0
released: 2012-11-30
+toscaConformanceLevel: 3.0
titanCfgFile: /home/vagrant/catalog-be/config/catalog-be/titan.properties
titanInMemoryGraph: true
@@ -93,6 +94,9 @@ artifactTypes:
- AAI_VF_MODULE_MODEL
- AAI_VF_INSTANCE_MODEL
- OTHER
+ - SNMP_POLL
+ - SNMP_TRAP
+ - GUIDE
licenseTypes:
- User
@@ -105,6 +109,7 @@ resourceTypes: &allResourceTypes
- CP
- VL
- VF
+ - VFCMT
# validForResourceTypes usage
# validForResourceTypes:
@@ -160,7 +165,7 @@ informationalResourceArtifacts:
testScripts:
displayName: Test Scripts
type: OTHER
- cloudQuestionnaire:
+ CloudQuestionnaire:
displayName: Cloud Questionnaire (completed)
type: OTHER
HEATTemplateFromVendor:
@@ -333,7 +338,13 @@ resourceDeploymentArtifacts:
OTHER:
acceptedTypes:
validForResourceTypes: *allResourceTypes
-
+ SNMP_POLL:
+ acceptedTypes:
+ validForResourceTypes: *allResourceTypes
+ SNMP_TRAP:
+ acceptedTypes:
+ validForResourceTypes: *allResourceTypes
+
resourceInstanceDeploymentArtifacts:
HEAT_ENV:
acceptedTypes:
@@ -341,6 +352,55 @@ resourceInstanceDeploymentArtifacts:
VF_MODULES_METADATA:
acceptedTypes:
- json
+ 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: *allResourceTypes
+ SNMP_POLL:
+ acceptedTypes:
+ validForResourceTypes: *allResourceTypes
+ SNMP_TRAP:
+ acceptedTypes:
+ validForResourceTypes: *allResourceTypes
+ GUIDE:
+ acceptedTypes:
+ validForResourceTypes:
+ - VF
+ - VFC
resourceInformationalDeployedArtifacts:
@@ -377,29 +437,27 @@ cassandraConfig:
- { name: sdcartifact, replicationStrategy: SimpleStrategy, replicationInfo: ['1']}
switchoverDetector:
- gBeFqdn:
- gFeFqdn:
- beVip: 1.2.3.4
- feVip: 1.2.3.4
+ gBeFqdn: AIO-BE.ecomp.idns.com
+ gFeFqdn: AIO-FE.ecomp.idns.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://cora.web/crt/CipDomain.ECOMP-ASDC-DEVST/config/update_network?user=root"
+ publishNetworkUrl: "http://xxx.com/crt/CipDomain.ECOMP-ASDC-DEVST/config/update_network?user=root"
publishNetworkBody: '{"note":"publish network"}'
groups:
- beSet: { changePriorityUrl: "http://cora.web/crt/CipDomain.ECOMP-ASDC-DEVST/config/sites/AIO-BE.ecomp.idns.cip?user=root",
- changePriorityBody: '{"name":"AIO-BE.ecomp.idns.cip","uri":"/crt/CipDomain.ECOMP-ASDC-DEVST/config/sites/AIO-BE.ecomp.idns.cip","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://cora.web/crt/CipDomain.ECOMP-ASDC-DEVST/config/sites/AIO-FE.ecomp.idns.cip?user=root",
- changePriorityBody: '{"comment":"AIO G-fqdn","name":"AIO-FE.ecomp.idns.cip","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"}'}
+ 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"}'}
-heatEnvArtifactHeader:
- ""
-heatEnvArtifactFooter:
- ""
+heatEnvArtifactHeader: ""
+heatEnvArtifactFooter: ""
onboarding:
protocol: http
@@ -424,4 +482,8 @@ applicationL2Cache:
syncIntervalInSecondes: 60
waitOnShutDownInMinutes: 30
numberOfCacheWorkers: 4
+genericAssetNodeTypes:
+ VFC: org.openecomp.resource.abstract.nodes.VFC
+ VF : org.openecomp.resource.abstract.nodes.VF
+ Service: org.openecomp.resource.abstract.nodes.service
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 a64ea7f364..ac6ff13473 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
@@ -1,7 +1,7 @@
uebServers:
- - uebsb91kcdc.it.att.com:3904
- - uebsb92kcdc.it.att.com:3904
-# - uebsb93kcdc.it.att.com:3904
+ - uebsb91kcdc.it.att.com
+ - uebsb92kcdc.it.att.com
+# - uebsb93kcdc.it.att.com
uebPublicKey: 8F3MDAtMSBwwpSMy
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 89b44d94d6..e131929aa7 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
@@ -42,6 +42,12 @@ errors:
message: "Error: Not authorized to use the API.",
messageId: "POL5003"
}
+#---------POL5004------------------------------
+ MISSING_USER_ID: {
+ code: 400 ,
+ message: "Error: Missing 'USER_ID' HTTP header.",
+ messageId: "POL5004"
+ }
#---------SVC4000-----------------------------
INVALID_CONTENT: {
code: 400,
@@ -55,7 +61,7 @@ errors:
messageId: "SVC4002"
}
#---------SVC4003------------------------------
-# %1 - Users's USER_ID
+# %1 - Users's ID
USER_NOT_FOUND: {
code: 404,
message: "Error: User '%1' was not found.",
@@ -99,7 +105,7 @@ errors:
# %1 - service/resource
COMPONENT_MISSING_CONTACT: {
code: 400,
- message: "Error: Invalid Content. Missing %1 contact id.",
+ message: "Error: Invalid Content. Missing %1 contact.",
messageId: "SVC4049"
}
#---------SVC4050-----------------------------
@@ -202,14 +208,14 @@ errors:
}
#---------SVC4064------------------------------
-# %1 - Service/Resource
+# %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
+# %1 - Service/Resource/Property
# %2 - max resource/service name length
COMPONENT_DESCRIPTION_EXCEEDS_LIMIT: {
code: 400,
@@ -240,9 +246,9 @@ errors:
#---------SVC4069------------------------------
# %1 - Service/Resource/Product
- COMPONENT_INVALID_CONTACT_ID: {
+ COMPONENT_INVALID_CONTACT: {
code: 400,
- message: "Error: Invalid Content. %1 contact id should be in format 'mnnnnnn' or 'aannna' or 'aannnn', where m=m ,a=a-zA-Z and n=0-9",
+ message: "Error: Invalid Content. %1 Contact id should be in format 'mnnnnnn' or 'aannna' or 'aannnn', where m=m ,a=a-zA-Z and n=0-9",
messageId: "SVC4069"
}
#---------SVC4070------------------------------
@@ -506,7 +512,7 @@ errors:
#-----------SVC4130---------------------------
INVALID_PROJECT_CODE: {
code: 400,
- message: "Error: Invalid Content. PROJECT_CODE number must be numeric from 5 up to 10 digits.",
+ message: "Error: Invalid Content. PROJECT_CODE must be from 3 up to 50 characters.",
messageId: "SVC4130"
}
#-----------SVC4131---------------------------
@@ -999,7 +1005,7 @@ errors:
#---------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 +1014,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,7 +1023,7 @@ 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.",
@@ -1055,7 +1061,7 @@ errors:
messageId: "SVC4567"
}
#---------SVC4567------------------------------
-# %1 - "User Name and userId"
+# %1 - "User Name and UserId"
# %2 -"checked-out"/"in-certification"
CANNOT_DELETE_USER_WITH_ACTIVE_ELEMENTS: {
code: 409,
@@ -1063,7 +1069,7 @@ errors:
messageId: "SVC4567"
}
#---------SVC4568------------------------------
-# %1 - "User Name and userId"
+# %1 - "User Name and UserId"
# %2 -"checked-out"/"in-certification"
CANNOT_UPDATE_USER_WITH_ACTIVE_ELEMENTS: {
code: 409,
@@ -1420,7 +1426,7 @@ 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------------------------------
@@ -1580,4 +1586,185 @@ errors:
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"
- } \ No newline at end of file
+ }
+#-----------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"
+ } \ No newline at end of file
diff --git a/catalog-be/tarball.xml b/catalog-be/tarball.xml
deleted file mode 100644
index bedd27660c..0000000000
--- a/catalog-be/tarball.xml
+++ /dev/null
@@ -1,54 +0,0 @@
-<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
-xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
- <id>bin</id>
- <formats>
- <format>tar</format>
- </formats>
- <files>
- <file>
- <source>${project.build.directory}/${project.artifactId}-${project.version}.war</source>
- <outputDirectory>./</outputDirectory>
- <destName>${project.artifactId}-${project.version}.war</destName>
- </file>
- <file>
- <source>src/main/resources/elasticsearch.yml</source>
- <outputDirectory>./</outputDirectory>
- <destName>elasticsearch.yml</destName>
- </file>
- <!--file>
- <source>src/main/resources/elasticsearch.properties</source>
- <outputDirectory>./</outputDirectory>
- <destName>elasticsearch.properties</destName>
- </file-->
- <file>
- <source>src/main/resources/jetty-ssl.xml</source>
- <outputDirectory>./</outputDirectory>
- <destName>jetty-ssl.xml</destName>
- </file>
- <!--<file>-->
- <!--<source>${project.build.directory}/ecompErrorCodes.csv</source>-->
- <!--<outputDirectory>config</outputDirectory>-->
- <!--<destName>ecompErrorCodes.csv</destName>-->
- <!--</file>-->
- </files>
-
- <fileSets>
- <fileSet>
- <directory>src/main/resources/config</directory>
- <outputDirectory>config</outputDirectory>
- </fileSet>
- <fileSet>
- <directory>src/main/resources/scripts</directory>
- <outputDirectory>scripts</outputDirectory>
- </fileSet>
- <fileSet>
- <directory>src/main/resources/keystore</directory>
- <outputDirectory>keystore</outputDirectory>
- </fileSet>
- <fileSet>
- <directory>src/main/resources/import</directory>
- <outputDirectory>import</outputDirectory>
- </fileSet>
- </fileSets>
-</assembly>
diff --git a/catalog-dao/pom.xml b/catalog-dao/pom.xml
index 7648b695f9..7d10b3f4e1 100644
--- a/catalog-dao/pom.xml
+++ b/catalog-dao/pom.xml
@@ -5,178 +5,80 @@
<groupId>org.openecomp.sdc.be</groupId>
<artifactId>catalog-dao</artifactId>
-
<parent>
<groupId>org.openecomp.sdc</groupId>
<artifactId>sdc-main</artifactId>
<version>1.1.0-SNAPSHOT</version>
</parent>
-
- <properties>
- <aspectj.version>1.7.4</aspectj.version>
- <hibernate-validator.version>5.3.4.Final</hibernate-validator.version>
- <groovy.version>2.3.5</groovy.version>
- <lucene.version>4.10.2</lucene.version>
- <mockito.version>1.9.0</mockito.version>
- <regex.version>3.0.3</regex.version>
- </properties>
-
-
<dependencies>
-
- <dependency>
- <groupId>org.testng</groupId>
- <artifactId>testng</artifactId>
- <version>6.9.10</version>
- <scope>test</scope>
- </dependency>
-
- <dependency>
- <groupId>commons-logging</groupId>
- <artifactId>commons-logging</artifactId>
- <version>1.2.1-SNAPSHOT</version>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>commons-codec</groupId>
- <artifactId>commons-codec</artifactId>
- <version>2.0-SNAPSHOT</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-core</artifactId>
- <version>${spring.version}</version>
- <scope>provided</scope>
- </dependency>
-
+
+ <!-- Common of SDC -->
<dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-beans</artifactId>
- <version>${spring.version}</version>
+ <groupId>org.openecomp.sdc</groupId>
+ <artifactId>common-app-api</artifactId>
+ <version>${project.version}</version>
<scope>provided</scope>
</dependency>
-
+
<dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-context</artifactId>
- <version>${spring.version}</version>
+ <groupId>org.openecomp.sdc.be</groupId>
+ <artifactId>common-be</artifactId>
+ <version>${project.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-context-support</artifactId>
- <version>${spring.version}</version>
+ <groupId>ch.qos.logback</groupId>
+ <artifactId>logback-classic</artifactId>
+ <version>${logback.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-messaging</artifactId>
- <version>${spring.version}</version>
+ <groupId>ch.qos.logback</groupId>
+ <artifactId>logback-core</artifactId>
+ <version>${logback.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-web</artifactId>
- <version>${spring.version}</version>
+ <groupId>org.elasticsearch</groupId>
+ <artifactId>elasticsearch</artifactId>
+ <version>${elastic-search.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-webmvc</artifactId>
- <version>${spring.version}</version>
+ <groupId>org.elasticsearch.plugin</groupId>
+ <artifactId>shield</artifactId>
+ <version>${elastic-search.version}</version>
<scope>provided</scope>
</dependency>
+ <!-- SPRING -->
<dependency>
<groupId>org.springframework</groupId>
- <artifactId>spring-aop</artifactId>
+ <artifactId>spring-context</artifactId>
<version>${spring.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
- <artifactId>spring-aspects</artifactId>
+ <artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
- <artifactId>spring-test</artifactId>
- <version>${spring.version}</version>
- <scope>test</scope>
- </dependency>
-
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-expression</artifactId>
+ <artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
- <scope>test</scope>
- </dependency>
-
- <!-- Common of SD&C -->
- <dependency>
- <groupId>org.openecomp.sdc</groupId>
- <artifactId>common-app-api</artifactId>
- <version>${common-app-api.version}</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.openecomp.sdc.be</groupId>
- <artifactId>common-be</artifactId>
- <version>${common-be.version}</version>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>ch.qos.logback</groupId>
- <artifactId>logback-classic</artifactId>
- <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>
<dependency>
- <groupId>org.elasticsearch</groupId>
- <artifactId>elasticsearch</artifactId>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>org.elasticsearch.plugin</groupId>
- <artifactId>shield</artifactId>
- <version>${elastic-search.version}</version>
- <scope>provided</scope>
- </dependency>
-
-
- <!-- Elasticsearch delete by query was extracted to plugin: adding this
- plugin requires updating elasticsearch.yml with: plugin.types: "DeleteByQueryPlugin"
- and installing the plugin in the server -->
- <!-- <dependency> -->
- <!-- <groupId>org.elasticsearch.plugin</groupId> -->
- <!-- <artifactId>delete-by-query</artifactId> -->
- <!-- <scope>provided</scope> -->
- <!-- </dependency> -->
-
-
- <!-- SPRING -->
-
- <dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${aspectj.version}</version>
@@ -198,15 +100,16 @@
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
- <version>1.7.10</version>
+ <version>${slf4j-api.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
+ <version>${json-simple.version}</version>
<scope>provided</scope>
-
</dependency>
+
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-regex</artifactId>
@@ -216,29 +119,28 @@
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
- <!--<version>${mockito.version}</version>&lt;!&ndash;$NO-MVN-MAN-VER$ &ndash;&gt;-->
- <version>1.10.19</version>
+ <version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
- <version>1.14</version>
+ <version>${snakeyaml.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
- <version>2.3.1</version>
+ <version>${gson.version}</version>
<scope>provided</scope>
</dependency>
-
<dependency>
<groupId>org.functionaljava</groupId>
<artifactId>functionaljava</artifactId>
+ <version>${functionaljava.version}</version>
<scope>provided</scope>
</dependency>
@@ -246,7 +148,7 @@
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
- <version>${httpclient.version}</version>
+ <version>${httpclient.version}</version>
<scope>provided</scope>
</dependency>
@@ -260,22 +162,36 @@
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
- <version>${guava.version}</version><!--$NO-MVN-MAN-VER$ -->
+ <version>${guava.version}</version>
<scope>provided</scope>
</dependency>
<!-- TEST -->
+ <dependency>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-test</artifactId>
+ <version>${spring.version}</version>
+ <scope>test</scope>
+ </dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
- <version>4.12</version>
+ <version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-jci-core</artifactId>
+ <version>${commons-jci-core.version}</version>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-expression</artifactId>
+ <version>${spring.version}</version>
<scope>test</scope>
</dependency>
@@ -306,10 +222,9 @@
<dependency>
<groupId>com.thinkaurelius.titan</groupId>
- <artifactId>titan-cassandra</artifactId>
- <!--<artifactId>asdc-titan-cassandra</artifactId> -->
+ <artifactId>titan-cassandra</artifactId>
+ <!--<artifactId>asdc-titan-cassandra</artifactId>-->
<version>${titan.version}</version>
- <!--<version>1.0.0-snapshot</version> -->
<scope>provided</scope>
<exclusions>
<exclusion>
@@ -325,7 +240,6 @@
<version>${lang3.version}</version>
<scope>provided</scope>
</dependency>
-
<!-- TITAN END -->
<!-- CASSANDRA -->
@@ -343,11 +257,8 @@
</dependency>
<!-- CASSANDRA END -->
-
</dependencies>
-
-
<build>
<pluginManagement>
@@ -390,8 +301,6 @@
</pluginManagement>
</build>
-
-
<profiles>
<profile>
<id>Fortify</id>
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/DAOTitanStrategy.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/DAOTitanStrategy.java
new file mode 100644
index 0000000000..c005192f71
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/DAOTitanStrategy.java
@@ -0,0 +1,12 @@
+package org.openecomp.sdc.be.dao;
+
+import org.openecomp.sdc.be.config.ConfigurationManager;
+
+public class DAOTitanStrategy implements TitanClientStrategy {
+
+ @Override
+ public String getConfigFile() {
+ return ConfigurationManager.getConfigurationManager().getConfiguration().getTitanCfgFile();
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/TitanClientStrategy.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/TitanClientStrategy.java
new file mode 100644
index 0000000000..772211ca58
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/TitanClientStrategy.java
@@ -0,0 +1,7 @@
+package org.openecomp.sdc.be.dao;
+
+public interface TitanClientStrategy {
+
+ String getConfigFile();
+
+}
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 9ab528ca1d..acd8563878 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/ActionStatus.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/ActionStatus.java
@@ -27,7 +27,7 @@ public enum ActionStatus {
// CapabilityType related
CAPABILITY_TYPE_ALREADY_EXIST, MISSING_CAPABILITY_TYPE, REQ_CAP_NOT_SATISFIED_BEFORE_CERTIFICATION, IMPORT_DUPLICATE_REQ_CAP_NAME, IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED,
// Resource related
- RESOURCE_NOT_FOUND, MISSING_DERIVED_FROM_TEMPLATE, PARENT_RESOURCE_NOT_FOUND, 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,
+ 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,
// Component name related
COMPONENT_NAME_ALREADY_EXIST, COMPONENT_NAME_EXCEEDS_LIMIT, MISSING_COMPONENT_NAME, INVALID_COMPONENT_NAME,
// Component description related
@@ -36,7 +36,7 @@ public enum ActionStatus {
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,
- // user contact related
+ // 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,
@@ -49,9 +49,9 @@ public enum ActionStatus {
// 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_DERIVED_FROM_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, 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,
+ 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_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, SDC_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,
+ 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,
@@ -71,18 +71,21 @@ public enum ActionStatus {
GROUP_MEMBER_EMPTY, GROUP_TYPE_ALREADY_EXIST,
// CSAR
- MISSING_CSAR_UUID, CSAR_INVALID, CSAR_INVALID_FORMAT, CSAR_NOT_FOUND, YAML_NOT_FOUND_IN_CSAR, VSP_ALREADY_EXISTS, RESOURCE_LINKED_TO_DIFFERENT_VSP, RESOURCE_FROM_CSAR_NOT_FOUND, AAI_ARTIFACT_GENERATION_FAILED,
+ 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,
// Group
- 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_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,
// cache
CONVERT_COMPONENT_ERROR, COMPONENT_NOT_FOUND,
// Inputs
- INPUT_IS_NOT_CHILD_OF_COMPONENT
+ INPUT_IS_NOT_CHILD_OF_COMPONENT,
;
}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/BasicDao.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/BasicDao.java
index c61956313d..3e6e7706cb 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/BasicDao.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/BasicDao.java
@@ -76,7 +76,8 @@ public abstract class BasicDao implements IBasicDAO {
for (List<GraphElement> listOfElements : listOfResults) {
if (listOfElements != null && false == listOfElements.isEmpty()) {
for (GraphElement element : listOfElements) {
- logger.debug("element {} was returned after running batch operation {}", element, batchBuilder);
+ logger.debug("element {} was returned after running batch operation {}",
+ element, batchBuilder);
if (element instanceof GraphNode) {
GraphNode neo4jNode = (GraphNode) element;
if (NodeTypeEnum.getByName(neo4jNode.getLabel()) == nodeType) {
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/ESGenericIdDAO.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/ESGenericIdDAO.java
index ae2b236de1..fb0b160b09 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/ESGenericIdDAO.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/ESGenericIdDAO.java
@@ -130,7 +130,7 @@ public abstract class ESGenericIdDAO implements IGenericIdDAO {
protected void saveResourceData(String typeName, Object data, String id) throws JsonProcessingException {
String indexName = getIndexForType(typeName);
- log.debug("ESGenericIdDAO saveResourceData resource indexName: {} typeName is: {}", indexName, typeName);
+ log.debug("ESGenericIdDAO saveResourceData resource indexName: {} | typeName is: {}", indexName, typeName);
String json = getJsonMapper().writeValueAsString(data);
log.debug("ESGenericIdDAO saveResourceData resource id is: {}", id);
@@ -138,7 +138,7 @@ public abstract class ESGenericIdDAO implements IGenericIdDAO {
getClient().prepareIndex(indexName, typeName, id).setSource(json).setRefresh(true).execute().actionGet();
} catch (Exception e) {
log.error("failed to write data with id {} to elasticsearch type {}. error: {}", id, typeName,
- e.getMessage());
+ e.getMessage(), e);
throw e;
}
}
@@ -160,7 +160,7 @@ public abstract class ESGenericIdDAO implements IGenericIdDAO {
private void assertIdNotNullFor(String id, String operation) {
if (id == null || id.trim().isEmpty()) {
- log.error("Null or empty Id is not allowed for operation <" + operation + ">.");
+ log.error("Null or empty Id is not allowed for operation <{}>.", operation);
throw new IndexingServiceException("Null or empty Id is not allowed for operation <" + operation + ">.");
}
}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/ArtifactCassandraDao.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/ArtifactCassandraDao.java
index 36d9b60eb5..a9a4a99de1 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/ArtifactCassandraDao.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/ArtifactCassandraDao.java
@@ -85,7 +85,7 @@ public class ArtifactCassandraDao extends CassandraDao {
*/
public CassandraOperationStatus deleteAllArtifacts() {
logger.info("cleaning all artifacts.");
- String query = "truncate sdcArtifact.resources;";
+ String query = "truncate sdcartifact.resources;";
try {
session.execute(query);
} catch (Exception e) {
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/AuditAccessor.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/AuditAccessor.java
index c9262909bf..72c3b9656d 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/AuditAccessor.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/AuditAccessor.java
@@ -34,41 +34,41 @@ import com.datastax.driver.mapping.annotations.Query;
public interface AuditAccessor {
// ***** distributionstatusevent table
- @Query("SELECT * FROM sdcAudit.distributionstatusevent WHERE DID = :did AND ACTION = 'DStatus' ALLOW FILTERING")
+ @Query("SELECT * FROM sdcaudit.distributionstatusevent WHERE DID = :did AND ACTION = 'DStatus' ALLOW FILTERING")
Result<DistributionStatusEvent> getListOfDistributionStatuses(@Param("did") String did);
// ***** resourceadminevent table
- @Query("SELECT * FROM sdcAudit.resourceadminevent WHERE SERVICE_INSTANCE_ID = :serviceInstanceId AND ACTION = 'DRequest' ALLOW FILTERING")
+ @Query("SELECT * FROM sdcaudit.resourceadminevent WHERE SERVICE_INSTANCE_ID = :serviceInstanceId AND ACTION = 'DRequest' ALLOW FILTERING")
Result<ResourceAdminEvent> getServiceDistributionStatus(@Param("serviceInstanceId") String serviceInstanceId);
- @Query("SELECT * FROM sdcAudit.resourceadminevent WHERE SERVICE_INSTANCE_ID = :serviceInstanceId ")
+ @Query("SELECT * FROM sdcaudit.resourceadminevent WHERE SERVICE_INSTANCE_ID = :serviceInstanceId ")
Result<ResourceAdminEvent> getByServiceInstanceId(@Param("serviceInstanceId") String serviceInstanceId);
- @Query("SELECT * FROM sdcAudit.resourceadminevent WHERE SERVICE_INSTANCE_ID = :serviceInstanceId AND PREV_VERSION = :prevVersion ALLOW FILTERING")
+ @Query("SELECT * FROM sdcaudit.resourceadminevent WHERE SERVICE_INSTANCE_ID = :serviceInstanceId AND PREV_VERSION = :prevVersion ALLOW FILTERING")
Result<ResourceAdminEvent> getAuditByServiceIdAndPrevVersion(@Param("serviceInstanceId") String serviceInstanceId,
@Param("prevVersion") String prevVersion);
- @Query("SELECT * FROM sdcAudit.resourceadminevent WHERE DID = :did AND ACTION = :action ALLOW FILTERING")
+ @Query("SELECT * FROM sdcaudit.resourceadminevent WHERE DID = :did AND ACTION = :action ALLOW FILTERING")
Result<ResourceAdminEvent> getDistributionRequest(@Param("did") String did, @Param("action") String action);
- @Query("SELECT * FROM sdcAudit.resourceadminevent WHERE SERVICE_INSTANCE_ID = :serviceInstanceId AND CURR_VERSION = :currVersion ALLOW FILTERING")
+ @Query("SELECT * FROM sdcaudit.resourceadminevent WHERE SERVICE_INSTANCE_ID = :serviceInstanceId AND CURR_VERSION = :currVersion ALLOW FILTERING")
Result<ResourceAdminEvent> getAuditByServiceIdAndCurrVersion(@Param("serviceInstanceId") String serviceInstanceId,
@Param("currVersion") String currVersion);
// ***** distributiondeployevent table
- @Query("SELECT * FROM sdcAudit.distributiondeployevent WHERE SERVICE_INSTANCE_ID = :serviceInstanceId AND ACTION = 'DResult' ALLOW FILTERING")
+ @Query("SELECT * FROM sdcaudit.distributiondeployevent WHERE SERVICE_INSTANCE_ID = :serviceInstanceId AND ACTION = 'DResult' ALLOW FILTERING")
Result<DistributionDeployEvent> getServiceDistributionDeploy(@Param("serviceInstanceId") String serviceInstanceId);
- @Query("SELECT * FROM sdcAudit.distributiondeployevent WHERE DID = :did AND ACTION = :action AND STATUS = :status ALLOW FILTERING")
+ @Query("SELECT * FROM sdcaudit.distributiondeployevent WHERE DID = :did AND ACTION = :action AND STATUS = :status ALLOW FILTERING")
Result<DistributionDeployEvent> getDistributionDeployByStatus(@Param("did") String did,
@Param("action") String action, @Param("status") String status);
// ***** distributionnotificationevent table
- @Query("SELECT * FROM sdcAudit.distributionnotificationevent WHERE SERVICE_INSTANCE_ID = :serviceInstanceId AND ACTION = 'DNotify' ALLOW FILTERING")
+ @Query("SELECT * FROM sdcaudit.distributionnotificationevent WHERE SERVICE_INSTANCE_ID = :serviceInstanceId AND ACTION = 'DNotify' ALLOW FILTERING")
Result<DistributionNotificationEvent> getServiceDistributionNotify(
@Param("serviceInstanceId") String serviceInstanceId);
- @Query("SELECT * FROM sdcAudit.distributionnotificationevent WHERE DID = :did AND ACTION = :action ALLOW FILTERING")
+ @Query("SELECT * FROM sdcaudit.distributionnotificationevent WHERE DID = :did AND ACTION = :action ALLOW FILTERING")
Result<DistributionNotificationEvent> getDistributionNotify(@Param("did") String did,
@Param("action") String action);
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/ComponentCassandraDao.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/ComponentCassandraDao.java
index 546dff855e..211cb6716c 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/ComponentCassandraDao.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/ComponentCassandraDao.java
@@ -186,35 +186,6 @@ public class ComponentCassandraDao extends CassandraDao {
}
/**
- * ---------for use in JUnit only--------------- the method deletes all the
- * tables in the audit keyspace
- *
- * @return the status of the last failed operation or ok if all the deletes
- * were successful
- */
- // public CassandraOperationStatus
- // deleteAllPartialComponents(ComponentTypeEnum componentTypeEnum) {
- // logger.info("cleaning all partial components of " + componentTypeEnum);
- //
- // String tableName = getTableName(componentTypeEnum);
- // if (tableName == null) {
- // BeEcompErrorManager.getInstance().logInvalidInputError("DeletePartialComponentData",
- // "input type not found " + componentTypeEnum, ErrorSeverity.INFO);
- // return CassandraOperationStatus.NOT_FOUND;
- // }
- // String query = "truncate " + AuditingTypesConstants.COMPONENT_KEYSPACE +
- // "." + tableName;
- // try {
- // session.execute(query);
- // } catch (Exception e) {
- // logger.debug("Failed to clean partial components", e);
- // return CassandraOperationStatus.GENERAL_ERROR;
- // }
- // logger.info("cleaning all partial components finished succsesfully.");
- // return CassandraOperationStatus.OK;
- // }
-
- /**
* the method checks if the given table is empty in the artifact keyspace
*
* @param tableName
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/SdcSchemaFilesAccessor.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/SdcSchemaFilesAccessor.java
new file mode 100644
index 0000000000..e6843eab2f
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/SdcSchemaFilesAccessor.java
@@ -0,0 +1,14 @@
+package org.openecomp.sdc.be.dao.cassandra;
+
+import org.openecomp.sdc.be.resources.data.ESSdcSchemaFilesData;
+
+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;
+
+@Accessor
+public interface SdcSchemaFilesAccessor {
+ @Query("SELECT * FROM sdcartifact.sdcschemafiles WHERE SDCRELEASENUM = :sdcreleasenum AND CONFORMANCELEVEL = :conformancelevel")
+ Result<ESSdcSchemaFilesData> getSpecificSdcSchemaFiles(@Param("sdcreleasenum") String sdcreleasenum, @Param("conformancelevel") String conformancelevel);
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/SdcSchemaFilesCassandraDao.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/SdcSchemaFilesCassandraDao.java
new file mode 100644
index 0000000000..1bb0f05898
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/SdcSchemaFilesCassandraDao.java
@@ -0,0 +1,112 @@
+package org.openecomp.sdc.be.dao.cassandra;
+
+import java.util.LinkedList;
+import java.util.List;
+
+import javax.annotation.PostConstruct;
+
+import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.resources.data.ESSdcSchemaFilesData;
+import org.openecomp.sdc.be.resources.data.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("sdc-schema-files-cassandra-dao")
+public class SdcSchemaFilesCassandraDao extends CassandraDao {
+
+ private static Logger logger = LoggerFactory.getLogger(SdcSchemaFilesCassandraDao.class.getName());
+ private SdcSchemaFilesAccessor sdcSchemaFilesAccessor;
+
+ public SdcSchemaFilesCassandraDao() {
+ super();
+ }
+
+ @PostConstruct
+ public void init() {
+ String keyspace = AuditingTypesConstants.ARTIFACT_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;
+ sdcSchemaFilesAccessor = manager.createAccessor(SdcSchemaFilesAccessor.class);
+ logger.info("** SdcSchemaFilesCassandraDao created");
+ } else {
+ logger.info("** SdcSchemaFilesCassandraDao failed");
+ throw new RuntimeException("Artifact keyspace [" + keyspace + "] failed to connect with error : "
+ + result.right().value());
+ }
+ } else {
+ logger.info("** Cassandra client isn't connected");
+ logger.info("** SdcSchemaFilesCassandraDao created, but not connected");
+ }
+ }
+
+ public CassandraOperationStatus saveArtifact(ESSdcSchemaFilesData artifact) {
+ return client.save(artifact, ESSdcSchemaFilesData.class, manager);
+ }
+
+ public Either<ESSdcSchemaFilesData, CassandraOperationStatus> getArtifact(String artifactId) {
+ return client.getById(artifactId, ESSdcSchemaFilesData.class, manager);
+ }
+
+ public CassandraOperationStatus deleteArtifact(String artifactId) {
+ return client.delete(artifactId, ESSdcSchemaFilesData.class, manager);
+ }
+
+ public Either<List<ESSdcSchemaFilesData>, ActionStatus> getSpecificSchemaFiles(String sdcreleasenum, String conformancelevel) {
+ Result<ESSdcSchemaFilesData> specificSdcSchemaFiles = sdcSchemaFilesAccessor.getSpecificSdcSchemaFiles(sdcreleasenum, conformancelevel);
+
+ if(specificSdcSchemaFiles == null) {
+ logger.debug("not found specific SdcSchemaFiles for sdcreleasenum {}, conformancelevel {}", sdcreleasenum, conformancelevel);
+ return Either.left(new LinkedList<ESSdcSchemaFilesData>());
+ }
+
+ if(logger.isDebugEnabled()){
+ for (ESSdcSchemaFilesData esSdcSchemaFilesData : specificSdcSchemaFiles) {
+ logger.debug(esSdcSchemaFilesData.toString());
+ }
+ }
+
+ return Either.left(specificSdcSchemaFiles.all());
+ }
+
+ /**
+ * ---------for use in JUnit only--------------- the method deletes all the
+ * tables in the audit keyspace
+ *
+ * @return the status of the last failed operation or ok if all the deletes
+ * were successful
+ */
+ public CassandraOperationStatus deleteAllArtifacts() {
+ logger.info("cleaning all artifacts.");
+ String query = "truncate sdcartifact.resources;";
+ try {
+ session.execute(query);
+ } catch (Exception e) {
+ logger.debug("Failed to clean artifacts", e);
+ return CassandraOperationStatus.GENERAL_ERROR;
+ }
+ logger.info("cleaning all artifacts finished succsesfully.");
+ return CassandraOperationStatus.OK;
+ }
+
+ /**
+ * the method checks if the given table is empty in the artifact keyspace
+ *
+ * @param tableName
+ * the name of the table we want to check
+ * @return true if the table is empty
+ */
+ public Either<Boolean, CassandraOperationStatus> isTableEmpty(String tableName) {
+ return super.isTableEmpty(tableName);
+ }
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/SdcSchemaBuilder.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/SdcSchemaBuilder.java
index 0f54a25c14..f9dc9b22a4 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/SdcSchemaBuilder.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/SdcSchemaBuilder.java
@@ -28,12 +28,11 @@ import com.datastax.driver.core.schemabuilder.SchemaStatement;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.config.*;
import org.openecomp.sdc.be.config.Configuration;
+import org.openecomp.sdc.be.dao.cassandra.schema.tables.OldExternalApiEventTableDesc;
import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import javax.net.ssl.SSLContext;
-import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.stream.Collectors;
@@ -50,11 +49,19 @@ public class SdcSchemaBuilder {
private static Logger log = LoggerFactory.getLogger(SdcSchemaBuilder.class.getName());
+ //TODO remove after 1707_OS migration
+ private static void handle1707OSMigration(Map<String, Map<String, List<String>>> cassndraMetadata, Map<String, List<ITableDescription>> schemeData){
+ if(cassndraMetadata.containsKey("attaudit")){
+ List<ITableDescription> list = new ArrayList<>();
+ list.add(new OldExternalApiEventTableDesc());
+ schemeData.put("attaudit", list);
+ }
+
+ }
/**
* the method creates all keyspaces, tables and indexes in case they do not
* already exist. the method can be run multiple times. the method uses the
- * internal enums and external configuration for its operation
- *
+ * internal enums and external configuration for its operation *
* @return true if the create operation was successful
*/
public static boolean createSchema() {
@@ -62,7 +69,7 @@ public class SdcSchemaBuilder {
Session session = null;
try {
log.info("creating Schema for Cassandra.");
- cluster = createCluster();
+ cluster = SdcSchemaUtils.createCluster();
if (cluster == null) {
return false;
}
@@ -73,17 +80,18 @@ public class SdcSchemaBuilder {
return false;
}
log.debug("retrived Cassndra metadata.");
- Map<String, Map<String, List<String>>> cassndraMetadata = parseKeyspaceMetadata(
- keyspacesMetadateFromCassandra);
+ Map<String, Map<String, List<String>>> cassndraMetadata = parseKeyspaceMetadata(keyspacesMetadateFromCassandra);
+ Map<String, Map<String, List<String>>> metadataTablesStructure = getMetadataTablesStructure(keyspacesMetadateFromCassandra);
Map<String, List<ITableDescription>> schemeData = getSchemeData();
+ //TODO remove after 1707_OS migration
+ handle1707OSMigration(cassndraMetadata, schemeData);
log.info("creating Keyspaces.");
for (String keyspace : schemeData.keySet()) {
if (!createKeyspace(keyspace, cassndraMetadata, session)) {
return false;
}
Map<String, List<String>> keyspaceMetadate = cassndraMetadata.get(keyspace);
- createTables(schemeData.get(keyspace), keyspaceMetadate, session);
-
+ createTables(schemeData.get(keyspace), keyspaceMetadate, session,metadataTablesStructure.get(keyspace));
}
return true;
} catch (Exception e) {
@@ -106,7 +114,7 @@ public class SdcSchemaBuilder {
Session session = null;
try {
log.info("delete Data from Cassandra.");
- cluster = createCluster();
+ cluster = SdcSchemaUtils.createCluster();
if (cluster == null) {
return false;
}
@@ -117,11 +125,9 @@ public class SdcSchemaBuilder {
return false;
}
log.debug("retrived Cassndra metadata.");
- Map<String, Map<String, List<String>>> cassndraMetadata = parseKeyspaceMetadata(
- keyspacesMetadateFromCassandra);
+ Map<String, Map<String, List<String>>> cassndraMetadata = parseKeyspaceMetadata(keyspacesMetadateFromCassandra);
cassndraMetadata.forEach((k, v) -> {
if (AuditingTypesConstants.TITAN_KEYSPACE.equals(k)) {
-
// session.execute("")
} else if (AuditingTypesConstants.ARTIFACT_KEYSPACE.equals(k)) {
@@ -147,54 +153,7 @@ public class SdcSchemaBuilder {
return false;
}
- /**
- * the method creates the cluster object using the supplied cassandra nodes
- * in the configuration
- *
- * @return cluster object our null in case of an invalid configuration
- */
- private static Cluster createCluster() {
- List<String> nodes = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig()
- .getCassandraHosts();
- if (nodes == null) {
- log.info("no nodes were supplied in configuration.");
- return null;
- }
- log.info("connecting to node:{}.", nodes);
- Cluster.Builder clusterBuilder = Cluster.builder();
- nodes.forEach(host -> clusterBuilder.addContactPoint(host));
-
- clusterBuilder.withMaxSchemaAgreementWaitSeconds(60);
-
- boolean authenticate = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig()
- .isAuthenticate();
- if (authenticate) {
- String username = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig()
- .getUsername();
- String password = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig()
- .getPassword();
- if (username == null || password == null) {
- log.info("authentication is enabled but username or password were not supplied.");
- return null;
- }
- clusterBuilder.withCredentials(username, password);
- }
- boolean ssl = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig().isSsl();
- if (ssl) {
- String truststorePath = ConfigurationManager.getConfigurationManager().getConfiguration()
- .getCassandraConfig().getTruststorePath();
- String truststorePassword = ConfigurationManager.getConfigurationManager().getConfiguration()
- .getCassandraConfig().getTruststorePassword();
- if (truststorePath == null || truststorePassword == null) {
- log.info("ssl is enabled but truststorePath or truststorePassword were not supplied.");
- return null;
- }
- System.setProperty("javax.net.ssl.trustStore", truststorePath);
- System.setProperty("javax.net.ssl.trustStorePassword", truststorePassword);
- clusterBuilder.withSSL();
- }
- return clusterBuilder.build();
- }
+
/**
* the method prcess the metadata retrieved from the cassandra for the
@@ -206,8 +165,7 @@ public class SdcSchemaBuilder {
* cassndra mmetadata
* @return a map of maps of lists holding parsed info
*/
- private static Map<String, Map<String, List<String>>> parseKeyspaceMetadata(
- List<KeyspaceMetadata> keyspacesMetadata) {
+ private static Map<String, Map<String, List<String>>> parseKeyspaceMetadata(List<KeyspaceMetadata> keyspacesMetadata) {
Map<String, Map<String, List<String>>> cassndraMetadata = keyspacesMetadata.stream()
.collect(Collectors.toMap(keyspaceMetadata -> keyspaceMetadata.getName(),
keyspaceMetadata -> keyspaceMetadata.getTables().stream()
@@ -217,16 +175,25 @@ public class SdcSchemaBuilder {
.collect(Collectors.toList())))));
return cassndraMetadata;
}
+
+ private static Map<String, Map<String, List<String>>> getMetadataTablesStructure(
+ List<KeyspaceMetadata> keyspacesMetadata) {
+ return keyspacesMetadata.stream().collect(
+ Collectors.toMap(keyspaceMetadata -> keyspaceMetadata.getName(),
+ keyspaceMetadata -> keyspaceMetadata.getTables().stream().collect(
+ Collectors.toMap(tableMetadata -> tableMetadata.getName(),
+ tableMetadata -> tableMetadata.getColumns().stream().map(
+ columnMetadata -> columnMetadata.getName().toLowerCase()).collect(
+ Collectors.toList())))));
+ }
/**
* the method builds an index name according to a defined logic
* <table>
* _<column>_idx
*
- * @param table
- * table name
- * @param column
- * column name
+ * @param table: table name
+ * @param column: column name
* @return string name of the index
*/
private static String createIndexName(String table, String column) {
@@ -236,24 +203,21 @@ public class SdcSchemaBuilder {
/**
* the method creats all the tables and indexes thet do not already exist
*
- * @param iTableDescriptions
- * a list of table description we want to create
- * @param keyspaceMetadate
- * the current tables that exist in the cassandra under this
+ * @param iTableDescriptions: a list of table description we want to create
+ * @param keyspaceMetadate: the current tables that exist in the cassandra under this keyspace
+ * @param session: the session object used for the execution of the query.
+ * @param existingTablesMetadata
+ * the current tables columns that exist in the cassandra under this
* keyspace
- * @param session
- * the session object used for the execution of the query.
*/
- private static void createTables(List<ITableDescription> iTableDescriptions,
- Map<String, List<String>> keyspaceMetadate, Session session) {
-
+ private static void createTables(List<ITableDescription> iTableDescriptions, Map<String, List<String>> keyspaceMetadate, Session session,
+ Map<String, List<String>> existingTablesMetadata) {
for (ITableDescription tableDescription : iTableDescriptions) {
String tableName = tableDescription.getTableName().toLowerCase();
Map<String, ImmutablePair<DataType, Boolean>> columnDescription = tableDescription.getColumnDescription();
log.info("creating tables:{}.", tableName);
if (keyspaceMetadate == null || !keyspaceMetadate.keySet().contains(tableName)) {
- Create create = SchemaBuilder.createTable(tableDescription.getKeyspace(),
- tableDescription.getTableName());
+ Create create = SchemaBuilder.createTable(tableDescription.getKeyspace(),tableDescription.getTableName());
for (ImmutablePair<String, DataType> key : tableDescription.primaryKeys()) {
create.addPartitionKey(key.getLeft(), key.getRight());
}
@@ -267,12 +231,14 @@ public class SdcSchemaBuilder {
create.addColumn(columnName, columnDescription.get(columnName).getLeft());
}
log.trace("exacuting :{}", create.toString());
- ResultSet result = session.execute(create);
+ session.execute(create);
log.info("table:{} created succsesfully.", tableName);
} else {
log.info("table:{} already exists skiping.", tableName);
+ alterTable(session, existingTablesMetadata, tableDescription, tableName, columnDescription);
}
- List<String> indexNames = (keyspaceMetadate != null ? keyspaceMetadate.get(tableName) : new ArrayList<>());
+ log.info("keyspacemetdata{}",keyspaceMetadate);
+ List<String> indexNames = (keyspaceMetadate != null && keyspaceMetadate.get(tableName) != null ? keyspaceMetadate.get(tableName) : new ArrayList<>());
log.info("table:{} creating indexes.", tableName);
for (String columnName : columnDescription.keySet()) {
String indexName = createIndexName(tableName, columnName).toLowerCase();
@@ -293,25 +259,44 @@ public class SdcSchemaBuilder {
}
/**
+ * check if there are new columns that were added to definition but don't exist in DB
+ * @param session
+ * @param existingTablesMetadata
+ * @param tableDescription
+ * @param tableName
+ * @param columnDescription
+ */
+ private static void alterTable(Session session, Map<String, List<String>> existingTablesMetadata,
+ ITableDescription tableDescription, String tableName,
+ Map<String, ImmutablePair<DataType, Boolean>> columnDescription) {
+ List<String> definedTableColumns = existingTablesMetadata.get(tableName);
+ //add column to casandra if was added to table definition
+ for (Map.Entry<String, ImmutablePair<DataType, Boolean>> column : columnDescription.entrySet()) {
+ String columnName = column.getKey();
+ if (!definedTableColumns.contains(columnName.toLowerCase())){
+ log.info("Adding new column {} to the table {}", columnName,tableName);
+ Alter alter = SchemaBuilder.alterTable(tableDescription.getKeyspace(),tableDescription.getTableName());
+ SchemaStatement addColumn = alter.addColumn(columnName).type(column.getValue().getLeft());
+ log.trace("exacuting :{}", addColumn.toString());
+ session.execute(addColumn);
+ }
+ }
+ }
+
+ /**
* the method create the keyspace in case it does not already exists the
* method uses configurtion to select the needed replication strategy
*
- * @param keyspace
- * name of the keyspace we want to create
- * @param cassndraMetadata
- * cassndra metadata
- * @param session
- * the session object used for the execution of the query.
+ * @param keyspace: name of the keyspace we want to create
+ * @param cassndraMetadata: cassndra metadata
+ * @param session: the session object used for the execution of the query.
* @return true in case the operation was successful
*/
- private static boolean createKeyspace(String keyspace, Map<String, Map<String, List<String>>> cassndraMetadata,
- Session session) {
- List<Configuration.CassandrConfig.KeyspaceConfig> keyspaceConfigList = ConfigurationManager
- .getConfigurationManager().getConfiguration().getCassandraConfig().getKeySpaces();
+ private static boolean createKeyspace(String keyspace, Map<String, Map<String, List<String>>> cassndraMetadata, Session session) {
+ List<Configuration.CassandrConfig.KeyspaceConfig> keyspaceConfigList = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig().getKeySpaces();
log.info("creating keyspace:{}.", keyspace);
if (!cassndraMetadata.keySet().contains(keyspace)) {
- Optional<Configuration.CassandrConfig.KeyspaceConfig> keyspaceConfig = keyspaceConfigList.stream()
- .filter(keyspaceInfo -> keyspace.equalsIgnoreCase(keyspaceInfo.getName())).findFirst();
+ Optional<Configuration.CassandrConfig.KeyspaceConfig> keyspaceConfig = keyspaceConfigList.stream().filter(keyspaceInfo -> keyspace.equalsIgnoreCase(keyspaceInfo.getName())).findFirst();
if (keyspaceConfig.isPresent()) {
Configuration.CassandrConfig.KeyspaceConfig keyspaceInfo = keyspaceConfig.get();
String createKeyspaceQuery = createKeyspaceQuereyString(keyspace, keyspaceInfo);
@@ -356,7 +341,7 @@ public class SdcSchemaBuilder {
}
/**
- * the methoed creates the query string for the given keyspace the methoed
+ * the methoed creates the query string for the given keyspace the methoed
* valides the given data according the the requirments of the replication
* strategy SimpleStrategy: "CREATE KEYSPACE IF NOT EXISTS
* <keyspaceName></keyspaceName> WITH replication =
@@ -370,11 +355,9 @@ public class SdcSchemaBuilder {
* configuration info regurding the replication of the keyspace
* @return a querey string for the creation of the keyspace
*/
- private static String createKeyspaceQuereyString(String keyspace,
- Configuration.CassandrConfig.KeyspaceConfig keyspaceInfo) {
+ private static String createKeyspaceQuereyString(String keyspace, Configuration.CassandrConfig.KeyspaceConfig keyspaceInfo) {
String query = null;
- if (ReplicationStrategy.NETWORK_TOPOLOGY_STRATEGY.getName()
- .equalsIgnoreCase(keyspaceInfo.getReplicationStrategy())) {
+ if (ReplicationStrategy.NETWORK_TOPOLOGY_STRATEGY.getName().equalsIgnoreCase(keyspaceInfo.getReplicationStrategy())) {
List<String> dcList = keyspaceInfo.getReplicationInfo();
if (dcList.size() % 2 != 0) {
log.error("the supplied replication info is in valid expected dc1,2,dc2,2 etc received:{}", dcList);
@@ -389,8 +372,7 @@ public class SdcSchemaBuilder {
}
query = String.format(CREATE_KEYSPACE_NETWORK_TOPOLOGY_STRATEGY, keyspace, sb.toString());
- } else if (ReplicationStrategy.SIMPLE_STRATEGY.getName()
- .equalsIgnoreCase(keyspaceInfo.getReplicationStrategy())) {
+ } else if (ReplicationStrategy.SIMPLE_STRATEGY.getName().equalsIgnoreCase(keyspaceInfo.getReplicationStrategy())) {
List<String> dcList = keyspaceInfo.getReplicationInfo();
if (dcList.size() != 1) {
log.error("the supplied replication info is in valid expected <number> etc received:{}", dcList);
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
new file mode 100644
index 0000000000..f52faa5886
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/SdcSchemaUtils.java
@@ -0,0 +1,90 @@
+package org.openecomp.sdc.be.dao.cassandra.schema;
+
+import com.datastax.driver.core.*;
+import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.List;
+
+public class SdcSchemaUtils {
+
+ private static Logger log = LoggerFactory.getLogger(SdcSchemaUtils.class.getName());
+
+ /**
+ * the method creates the cluster object using the supplied cassandra nodes
+ * in the configuration
+ *
+ * @return cluster object our null in case of an invalid configuration
+ */
+ public static Cluster createCluster() {
+ List<String> nodes = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig().getCassandraHosts();
+ if (nodes == null) {
+ log.info("no nodes were supplied in configuration.");
+ return null;
+ }
+ log.info("connecting to node:{}.", nodes);
+ Cluster.Builder clusterBuilder = Cluster.builder();
+ nodes.forEach(host -> clusterBuilder.addContactPoint(host));
+
+ clusterBuilder.withMaxSchemaAgreementWaitSeconds(60);
+
+ boolean authenticate = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig().isAuthenticate();
+ if (authenticate) {
+ String username = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig().getUsername();
+ String password = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig().getPassword();
+ if (username == null || password == null) {
+ log.info("authentication is enabled but username or password were not supplied.");
+ return null;
+ }
+ clusterBuilder.withCredentials(username, password);
+ }
+ boolean ssl = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig().isSsl();
+ if (ssl) {
+ String truststorePath = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig().getTruststorePath();
+ String truststorePassword = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig().getTruststorePassword();
+ if (truststorePath == null || truststorePassword == null) {
+ log.info("ssl is enabled but truststorePath or truststorePassword were not supplied.");
+ return null;
+ }
+ System.setProperty("javax.net.ssl.trustStore", truststorePath);
+ System.setProperty("javax.net.ssl.trustStorePassword", truststorePassword);
+ clusterBuilder.withSSL();
+ }
+ return clusterBuilder.build();
+ }
+
+ public static boolean executeStatement(String statement) {
+ return executeStatements(statement);
+ }
+
+ public static boolean executeStatements(String ... statements) {
+ Cluster cluster = null;
+ Session session = null;
+ try {
+ cluster = createCluster();
+ if (cluster == null) {
+ return false;
+ }
+ session = cluster.connect();
+ for (String statement : statements) {
+ session.execute(statement);
+ }
+ return true;
+ } catch (RuntimeException e) {
+ log.error(String.format("could not execute statements"), e);
+ return false;
+ } finally {
+ if (session != null) {
+ session.close();
+ }
+ if (cluster != null) {
+ cluster.close();
+ }
+
+ }
+ }
+
+
+
+}
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 6de40a7117..8fb594f2ff 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
@@ -35,6 +35,7 @@ import org.openecomp.sdc.be.dao.cassandra.schema.tables.GetCatHierEventTableDesc
import org.openecomp.sdc.be.dao.cassandra.schema.tables.GetUebClusterEventTableDesc;
import org.openecomp.sdc.be.dao.cassandra.schema.tables.GetUsersListEventTableDesc;
import org.openecomp.sdc.be.dao.cassandra.schema.tables.ResAdminEventTableDescription;
+import org.openecomp.sdc.be.dao.cassandra.schema.tables.SdcSchemaFilesTableDescription;
import org.openecomp.sdc.be.dao.cassandra.schema.tables.UserAccessEventTableDescription;
import org.openecomp.sdc.be.dao.cassandra.schema.tables.UserAdminEventTableDescription;
@@ -46,17 +47,18 @@ public enum Table {
RESOURCE_ADMIN_EVENT(new ResAdminEventTableDescription()),
DISTRIBUTION_DOWNLOAD_EVENT(new DistribDownloadEventTableDesc()),
DISTRIBUTION_ENGINE_EVENT(new DistribEngineEventTableDesc()),
- DISTRIBUTION_NOTIFICATION_EVENT(new DistribNotifEventTableDesc()),
+ DISTRIBUTION_NOTIFICATION_EVENT(new DistribNotifEventTableDesc()),
DISTRIBUTION_STATUS_EVENT(new DistribStatusEventTableDesc()),
DISTRIBUTION_DEPLOY_EVENT(new DistribDeployEventTableDesc()),
- DISTRIBUTION_GET_UEB_CLUSTER_EVENT(new GetUebClusterEventTableDesc()),
+ 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());
+ EXTERNAL_API_EVENT(new ExternalApiEventTableDesc()),
+ COMPONENT_CACHE(new ComponentCacheTableDescription()),
+ SDC_SCHEMA_FILES(new SdcSchemaFilesTableDescription());
ITableDescription tableDescription;
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ArtifactTableDescription.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ArtifactTableDescription.java
index 2e26bd2675..ad7cffaa63 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ArtifactTableDescription.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ArtifactTableDescription.java
@@ -20,11 +20,12 @@
package org.openecomp.sdc.be.dao.cassandra.schema.tables;
-import java.util.*;
+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.config.Configuration;
-import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.cassandra.schema.ITableDescription;
import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
@@ -32,8 +33,6 @@ import com.datastax.driver.core.DataType;
public class ArtifactTableDescription implements ITableDescription {
- private static final String keyspaceType = "artifact";
-
@Override
public List<ImmutablePair<String, DataType>> primaryKeys() {
List<ImmutablePair<String, DataType>> keys = new ArrayList<>();
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/AuthEventTableDescription.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/AuthEventTableDescription.java
index ef7be5deb7..ab2b207888 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/AuthEventTableDescription.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/AuthEventTableDescription.java
@@ -26,13 +26,10 @@ import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.cassandra.schema.ITableDescription;
-import org.openecomp.sdc.be.dao.cassandra.schema.tables.UserAdminEventTableDescription.UAEFieldsDescription;
import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
import com.datastax.driver.core.DataType;
-import com.datastax.driver.mapping.annotations.Column;
public class AuthEventTableDescription implements ITableDescription {
@Override
@@ -71,11 +68,14 @@ public class AuthEventTableDescription implements ITableDescription {
}
enum AEFieldsDescription {
-
- URL("url", DataType.varchar(), false), REQUEST_ID("request_id", DataType.varchar(), true), USER("user",
- DataType.varchar(), false), AUTH_STATUS("auth_status", DataType.varchar(), false), REALM("realm",
- DataType.varchar(), false), ACTION("action", DataType.varchar(), true), STATUS("status",
- DataType.varchar(), false), DESC("description", DataType.varchar(), false);
+ URL("url", DataType.varchar(), false),
+ REQUEST_ID("request_id", DataType.varchar(), true),
+ USER("user", DataType.varchar(), false),
+ AUTH_STATUS("auth_status", DataType.varchar(), false),
+ REALM("realm", DataType.varchar(), false),
+ ACTION("action", DataType.varchar(), true),
+ STATUS("status", DataType.varchar(), false),
+ DESC("description", 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/CategoryEventTableDescription.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/CategoryEventTableDescription.java
index efefac57b6..c49651e548 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/CategoryEventTableDescription.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/CategoryEventTableDescription.java
@@ -71,13 +71,16 @@ public class CategoryEventTableDescription implements ITableDescription {
enum CEFieldsDescription {
- ACTION("action", DataType.varchar(), true), STATUS("status", DataType.varchar(), false), DESC("description",
- DataType.varchar(), false), CATEGORY_NAME("category_Name", DataType.varchar(),
- false), SUB_CATEGORY_NAME("sub_Category_Name", DataType.varchar(), false), GROUPING_NAME(
- "grouping_name", DataType.varchar(), false), MODIFIER("modifier", DataType.varchar(),
- false), REQUEST_ID("request_id", DataType.varchar(), false), RESOURCE_TYPE(
- "resource_type", DataType.varchar(), false), SERVICE_INSTANCE_ID(
- "service_instance_id", DataType.varchar(), false);
+ ACTION("action", DataType.varchar(), true),
+ STATUS("status", DataType.varchar(), false),
+ DESC("description", DataType.varchar(), false),
+ CATEGORY_NAME("category_Name", DataType.varchar(), false),
+ SUB_CATEGORY_NAME("sub_Category_Name", DataType.varchar(), false),
+ GROUPING_NAME("grouping_name", DataType.varchar(), false),
+ MODIFIER("modifier", DataType.varchar(), false),
+ REQUEST_ID("request_id", DataType.varchar(), false),
+ RESOURCE_TYPE("resource_type", DataType.varchar(), false),
+ SERVICE_INSTANCE_ID("service_instance_id", 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/ComponentCacheTableDescription.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ComponentCacheTableDescription.java
index 6396da5c32..611138efa0 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ComponentCacheTableDescription.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ComponentCacheTableDescription.java
@@ -61,9 +61,11 @@ public class ComponentCacheTableDescription implements ITableDescription {
}
enum PartialComponentFieldsDescription {
- DATA("data", DataType.blob(), false), MODIFICATION_TIME("modification_time", DataType.timestamp(), false), TYPE(
- "type", DataType.varchar(), false), IS_DIRTY("is_dirty", DataType.cboolean(),
- false), IS_ZIPPED("is_zipped", DataType.cboolean(), false),;
+ DATA("data", DataType.blob(), false),
+ MODIFICATION_TIME("modification_time", DataType.timestamp(), false),
+ TYPE("type", DataType.varchar(), false),
+ IS_DIRTY("is_dirty", DataType.cboolean(), false),
+ IS_ZIPPED("is_zipped", DataType.cboolean(), false),;
private String name;
private DataType type;
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ConsumerEventTableDefinition.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ConsumerEventTableDefinition.java
index 554a7a7a51..68ec5620ba 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ConsumerEventTableDefinition.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ConsumerEventTableDefinition.java
@@ -70,10 +70,12 @@ public class ConsumerEventTableDefinition implements ITableDescription {
}
enum DEEFieldsDescription {
- ACTION("action", DataType.varchar(), true), STATUS("status", DataType.varchar(), false), DESCRIPTION(
- "description", DataType.varchar(),
- false), ECOMP_USER("ecomp_user", DataType.varchar(), false), MODIFIER("modifier", DataType.varchar(),
- false), REQUEST_ID("request_id", DataType.varchar(), false);
+ ACTION("action", DataType.varchar(), true),
+ STATUS("status", DataType.varchar(), false),
+ DESCRIPTION("description", DataType.varchar(), false),
+ ECOMP_USER("ecomp_user", DataType.varchar(), false),
+ MODIFIER("modifier", DataType.varchar(), false),
+ REQUEST_ID("request_id", 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/DistribDeployEventTableDesc.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribDeployEventTableDesc.java
index 5fc1dc8bd4..32c2365b95 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
@@ -70,13 +70,16 @@ public class DistribDeployEventTableDesc implements ITableDescription {
}
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), 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);
+ 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),
+ 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);
private String name;
private DataType type;
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 0ed4f55a7b..0ac31352f2 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
@@ -69,10 +69,13 @@ 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), RESOURCE_URL("resource_URL", DataType.varchar(), false);
+ 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),
+ RESOURCE_URL("resource_URL", 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/DistribEngineEventTableDesc.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribEngineEventTableDesc.java
index 5ce5bffb7c..16d9af084f 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
@@ -68,14 +68,17 @@ public class DistribEngineEventTableDesc implements ITableDescription {
}
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), D_ENV("d_env", DataType.varchar(),
- false), API_KEY("api_key", DataType.varchar(), false), DSTATUS_TOPIC(
- "dstatus_topic", DataType.varchar(),
- false), DNOTIF_TOPIC("dnotif_topic", 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),
+ REQUEST_ID("request_id", DataType.varchar(), true),
+ SERVICE_INST_ID("service_instance_id", 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),
+ DNOTIF_TOPIC("dnotif_topic", 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/DistribNotifEventTableDesc.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribNotifEventTableDesc.java
index 96fab66701..371b5c4886 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
@@ -68,15 +68,18 @@ 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), 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);
+ 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),
+ 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);
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 bc564e3743..d1c73bf46e 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
@@ -69,13 +69,16 @@ 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), 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), STATUS_TIME("status_time", DataType.varchar(), false);
+ ACTION("action", DataType.varchar(), true),
+ STATUS("status", DataType.varchar(), false),
+ DESCRIPTION("description", DataType.varchar(), false),
+ 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),
+ STATUS_TIME("status_time", 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/ExternalApiEventTableDesc.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ExternalApiEventTableDesc.java
index a67c9ef4ef..cb659b9a8a 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ExternalApiEventTableDesc.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ExternalApiEventTableDesc.java
@@ -67,16 +67,23 @@ public class ExternalApiEventTableDesc implements ITableDescription {
}
enum EGAEFieldsDescription {
- ACTION("action", DataType.varchar(), true), STATUS("status", DataType.varchar(), false), DESCRIPTION(
- "description", DataType.varchar(), false), CONSUMER_ID("consumer_id", DataType.varchar(),
- false), RESOURCE_URL("resource_URL", DataType.varchar(), false), RESOURCE_NAME("resource_name",
- DataType.varchar(),
- false), RESOURCE_TYPE("resource_type", DataType.varchar(), false), SERVICE_INST_ID(
- "service_instance_id", DataType.varchar(),
- true), MODIFIER("modifier", DataType.varchar(), false), PREV_ARTIFACT_UUID(
- "prev_artifact_uuid", DataType.varchar(), false), CURR_ARTIFACT_UUID(
- "curr_artifact_uuid", DataType.varchar(), false), ARTIFACT_DATA(
- "artifact_data", 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),
+ RESOURCE_URL("resource_URL", DataType.varchar(), false),
+ RESOURCE_NAME("resource_name", DataType.varchar(), false),
+ RESOURCE_TYPE("resource_type", DataType.varchar(), false),
+ SERVICE_INST_ID( "service_instance_id", DataType.varchar(), true),
+ INVARIANT_UUID("invariant_uuid", DataType.varchar(), true),
+ MODIFIER("modifier", DataType.varchar(), false),
+ PREV_VERSION( "prev_version", DataType.varchar(), false),
+ CURR_VERSION("curr_version", DataType.varchar(), false),
+ PREV_STATE("prev_state", DataType.varchar(), false),
+ CURR_STATE( "curr_state", DataType.varchar(), false),
+ PREV_ARTIFACT_UUID( "prev_artifact_uuid", DataType.varchar(), false),
+ CURR_ARTIFACT_UUID( "curr_artifact_uuid", DataType.varchar(), false),
+ ARTIFACT_DATA( "artifact_data", 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/GetCatHierEventTableDesc.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/GetCatHierEventTableDesc.java
index 2d1a5c3c75..3858b7d8f6 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/GetCatHierEventTableDesc.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/GetCatHierEventTableDesc.java
@@ -69,9 +69,12 @@ public class GetCatHierEventTableDesc implements ITableDescription {
}
enum DEEFieldsDescription {
- ACTION("action", DataType.varchar(), true), STATUS("status", DataType.varchar(), false), DESCRIPTION(
- "description", DataType.varchar(), false), DETAILS("details", DataType.varchar(), false), REQUEST_ID(
- "request_id", DataType.varchar(), false), MODIFIER("modifier", DataType.varchar(), false);
+ ACTION("action", DataType.varchar(), true),
+ STATUS("status", DataType.varchar(), false),
+ DESCRIPTION("description", DataType.varchar(), false),
+ DETAILS("details", DataType.varchar(), false),
+ REQUEST_ID("request_id", DataType.varchar(), false),
+ MODIFIER("modifier", 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/GetUebClusterEventTableDesc.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/GetUebClusterEventTableDesc.java
index 8ef1f01186..40a1827e36 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/GetUebClusterEventTableDesc.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/GetUebClusterEventTableDesc.java
@@ -70,10 +70,12 @@ public class GetUebClusterEventTableDesc implements ITableDescription {
}
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(), 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),
+ REQUEST_ID("request_Id", DataType.varchar(), false),
+ SERVICE_INST_ID("service_Instance_Id", 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/GetUsersListEventTableDesc.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/GetUsersListEventTableDesc.java
index 5d94bd3f4d..4bd3e296ef 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/GetUsersListEventTableDesc.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/GetUsersListEventTableDesc.java
@@ -69,9 +69,12 @@ public class GetUsersListEventTableDesc implements ITableDescription {
}
enum DEEFieldsDescription {
- ACTION("action", DataType.varchar(), true), STATUS("status", DataType.varchar(), false), DESCRIPTION(
- "description", DataType.varchar(), false), DETAILS("details", DataType.varchar(), false), REQUEST_ID(
- "request_id", DataType.varchar(), false), MODIFIER("modifier", DataType.varchar(), false);
+ ACTION("action", DataType.varchar(), true),
+ STATUS("status", DataType.varchar(), false),
+ DESCRIPTION("description", DataType.varchar(), false),
+ DETAILS("details", DataType.varchar(), false),
+ REQUEST_ID("request_id", DataType.varchar(), false),
+ MODIFIER("modifier", 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/OldExternalApiEventTableDesc.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/OldExternalApiEventTableDesc.java
new file mode 100644
index 0000000000..b075f0ef4e
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/OldExternalApiEventTableDesc.java
@@ -0,0 +1,94 @@
+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 OldExternalApiEventTableDesc 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<>();
+
+ for (EGAEFieldsDescription field : EGAEFieldsDescription.values()) {
+ columns.put(field.getName(), new ImmutablePair<DataType, Boolean>(field.type, field.indexed));
+ }
+
+ return columns;
+ }
+
+ @Override
+ public String getKeyspace() {
+ return AuditingTypesConstants.AUDIT_KEYSPACE.replace("sdc", "att");
+ }
+
+
+
+ @Override
+ public String getTableName() {
+ return AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE;
+ }
+
+ enum EGAEFieldsDescription {
+ ACTION("action", DataType.varchar(), true),
+ STATUS("status", DataType.varchar(), false),
+ DESCRIPTION( "description", DataType.varchar(), false),
+ CONSUMER_ID("consumer_id", DataType.varchar(), false),
+ RESOURCE_URL("resource_URL", DataType.varchar(), false),
+ RESOURCE_NAME("resource_name", DataType.varchar(), false),
+ RESOURCE_TYPE("resource_type", DataType.varchar(), false),
+ SERVICE_INST_ID( "service_instance_id", DataType.varchar(), true),
+ INVARIANT_UUID("invariant_uuid", DataType.varchar(), true),
+ MODIFIER("modifier", DataType.varchar(), false),
+ PREV_VERSION( "prev_version", DataType.varchar(), false),
+ CURR_VERSION("curr_version", DataType.varchar(), false),
+ PREV_STATE("prev_state", DataType.varchar(), false),
+ CURR_STATE( "curr_state", DataType.varchar(), false),
+ PREV_ARTIFACT_UUID( "prev_artifact_uuid", DataType.varchar(), false),
+ CURR_ARTIFACT_UUID( "curr_artifact_uuid", DataType.varchar(), false),
+ ARTIFACT_DATA( "artifact_data", DataType.varchar(), false);
+
+ private String name;
+ private DataType type;
+ private boolean indexed;
+
+ EGAEFieldsDescription(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/ResAdminEventTableDescription.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ResAdminEventTableDescription.java
index a6f0ba905d..e928982127 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ResAdminEventTableDescription.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ResAdminEventTableDescription.java
@@ -71,40 +71,27 @@ public class ResAdminEventTableDescription implements ITableDescription {
}
enum AEFieldsDescription {
- REQUEST_ID("request_id", DataType.varchar(), false), SERVICE_INST_ID("service_instance_id", DataType.varchar(),
- true), INVARIANT_UUID("invariant_UUID", DataType.varchar(), true), ACTION("action", DataType.varchar(),
- true), STATUS("status", DataType.varchar(), false), DESCRIPTION("description",
- DataType.varchar(),
- false), RESOURCE_TYPE("resource_type", DataType.varchar(), false), PREV_VERSION(
- "prev_version", DataType.varchar(),
- true), PREV_STATE("prev_state", DataType.varchar(), true), CURR_STATE(
- "curr_state", DataType.varchar(), false), RESOURCE_NAME("resource_name",
- DataType.varchar(), false), CURR_VERSION("curr_version",
- DataType.varchar(), true), MODIFIER("modifier",
- DataType.varchar(),
- false), PREV_ARTIFACT_UUID("prev_artifact_UUID",
- DataType.varchar(),
- false), CURR__ARTIFACT_UUID(
- "curr_artifact_UUID",
- DataType.varchar(),
- false), ARTIFACT_DATA(
- "artifact_data",
- DataType.varchar(),
- false), DID("did",
- DataType.varchar(),
- true), DPREV_STATUS(
- "dprev_status",
- DataType.varchar(),
- false), DCURR_STATUS(
- "dcurr_status",
- DataType.varchar(),
- false), TOSCA_NODE_TYPE(
- "tosca_node_type",
- DataType.varchar(),
- false), COMMENT(
- "comment",
- DataType.varchar(),
- false);
+ REQUEST_ID("request_id", DataType.varchar(), false),
+ SERVICE_INST_ID("service_instance_id", DataType.varchar(), true),
+ INVARIANT_UUID("invariant_UUID", DataType.varchar(), true),
+ ACTION("action", DataType.varchar(), true),
+ STATUS("status", DataType.varchar(), false),
+ DESCRIPTION("description",DataType.varchar(), false),
+ RESOURCE_TYPE("resource_type", DataType.varchar(), false),
+ PREV_VERSION( "prev_version", DataType.varchar(), true),
+ PREV_STATE("prev_state", DataType.varchar(), true),
+ CURR_STATE("curr_state", DataType.varchar(), false),
+ RESOURCE_NAME("resource_name", DataType.varchar(), false),
+ CURR_VERSION("curr_version", DataType.varchar(), true),
+ MODIFIER("modifier", DataType.varchar(), false),
+ PREV_ARTIFACT_UUID("prev_artifact_UUID", DataType.varchar(), false),
+ CURR__ARTIFACT_UUID("curr_artifact_UUID", DataType.varchar(), false),
+ ARTIFACT_DATA("artifact_data", DataType.varchar(), false),
+ DID("did", DataType.varchar(), true),
+ DPREV_STATUS("dprev_status", DataType.varchar(), false),
+ DCURR_STATUS("dcurr_status", DataType.varchar(), false),
+ TOSCA_NODE_TYPE("tosca_node_type", DataType.varchar(), false),
+ COMMENT("comment", 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/SdcSchemaFilesTableDescription.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/SdcSchemaFilesTableDescription.java
new file mode 100644
index 0000000000..09a01fb962
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/SdcSchemaFilesTableDescription.java
@@ -0,0 +1,83 @@
+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 SdcSchemaFilesTableDescription implements ITableDescription {
+
+ private static final String SDC_RELEASE_NUM = "sdcReleaseNum";
+ private static final String TIMESTAMP = "timestamp";
+ private static final String CONFORMANCE_LEVEL = "conformanceLevel";
+
+ @Override
+ public List<ImmutablePair<String, DataType>> primaryKeys() {
+ List<ImmutablePair<String, DataType>> keys = new ArrayList<>();
+ keys.add(new ImmutablePair<String, DataType>(SDC_RELEASE_NUM, DataType.varchar()));
+ keys.add(new ImmutablePair<String, DataType>(CONFORMANCE_LEVEL, 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, DataType.timestamp()));
+ return keys;
+ }
+
+ @Override
+ public Map<String, ImmutablePair<DataType, Boolean>> getColumnDescription() {
+ Map<String, ImmutablePair<DataType, Boolean>> columns = new HashMap<>();
+
+ for (SdcSchemaFilesFieldsDescription field : SdcSchemaFilesFieldsDescription.values()) {
+ columns.put(field.getName(), new ImmutablePair<DataType, Boolean>(field.type, field.indexed));
+ }
+
+ return columns;
+ }
+
+ @Override
+ public String getKeyspace() {
+ return AuditingTypesConstants.ARTIFACT_KEYSPACE;
+ }
+
+ @Override
+ public String getTableName() {
+ return "sdcSchemaFiles";
+ }
+
+ enum SdcSchemaFilesFieldsDescription {
+ FILE_NAME("fileName", DataType.varchar(), false),
+ PAYLOAD("payload", DataType.blob(), false),
+ CHECKSUM("checksum", DataType.varchar(), false);
+
+ private String name;
+ private DataType type;
+ private boolean indexed;
+
+ SdcSchemaFilesFieldsDescription(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/UserAccessEventTableDescription.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/UserAccessEventTableDescription.java
index 7f482ae3ac..93f5640c30 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/UserAccessEventTableDescription.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/UserAccessEventTableDescription.java
@@ -26,7 +26,6 @@ import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.cassandra.schema.ITableDescription;
import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
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
new file mode 100644
index 0000000000..d9c6829079
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/config/DAOSpringConfig.java
@@ -0,0 +1,34 @@
+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.Configuration;
+import org.springframework.context.annotation.Primary;
+
+@Configuration
+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/es/ElasticSearchClient.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/es/ElasticSearchClient.java
index 1c3ba1107f..4bc1afc80e 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
@@ -154,7 +154,7 @@ public class ElasticSearchClient {
if (node != null) {
node.close();
}
- log.info("Closed ElasticSearch client for cluster <" + this.clusterName + ">");
+ log.info("Closed ElasticSearch client for cluster <{}>", this.clusterName);
}
/**
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/GraphElementFactory.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/GraphElementFactory.java
index bf93c23afc..38648e69db 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/GraphElementFactory.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/GraphElementFactory.java
@@ -39,6 +39,7 @@ import org.openecomp.sdc.be.resources.data.ConsumerData;
import org.openecomp.sdc.be.resources.data.DataTypeData;
import org.openecomp.sdc.be.resources.data.GraphNodeLock;
import org.openecomp.sdc.be.resources.data.GroupData;
+import org.openecomp.sdc.be.resources.data.GroupInstanceData;
import org.openecomp.sdc.be.resources.data.GroupTypeData;
import org.openecomp.sdc.be.resources.data.HeatParameterData;
import org.openecomp.sdc.be.resources.data.HeatParameterValueData;
@@ -253,6 +254,9 @@ public class GraphElementFactory {
case PolicyType:
element = clazz.cast(new PolicyTypeData(properties));
break;
+ case GroupInstance:
+ element = clazz.cast(new GroupInstanceData(properties));
+ break;
default:
break;
}
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 87cd8a5f3e..0efff500d0 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
@@ -74,9 +74,8 @@ public class ESCatalogDAO extends ESGenericSearchDAO implements ICatalogDAO {
try {
healthStatus = isInitCompleted() ? checkHealth() : HealthCheckStatus.DOWN;
} catch (Exception e) {
- log.error("Error while trying to connect to elasticsearch. host: " + getEsClient().getServerHost()
- + " port: " + getEsClient().getServerPort(), e.getMessage());
- log.trace("Error while trying to connect to elasticsearch", e);
+ log.error("Error while trying to connect to elasticsearch. host: {} | port: {} | error: {}",
+ getEsClient().getServerHost(), getEsClient().getServerPort(), e.getMessage(), e);
healthStatus = HealthCheckStatus.DOWN;
}
healthCheckLogger.trace("Executed ELASTICSEARCH Health Check Task - Status = {}", healthStatus);
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/ESTimeBasedDao.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/ESTimeBasedDao.java
index b7666392aa..bdd1a2fb47 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/ESTimeBasedDao.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/ESTimeBasedDao.java
@@ -99,7 +99,7 @@ public abstract class ESTimeBasedDao {
res = ActionStatus.GENERAL_ERROR;
}
} catch (Exception e) {
- log.error("Couldn't serialize object of type " + typeName + " , error:", e);
+ log.error("Couldn't serialize object of type {} | error:", typeName, e);
res = ActionStatus.GENERAL_ERROR;
}
return res;
@@ -236,7 +236,7 @@ public abstract class ESTimeBasedDao {
hits.add(event);
} catch (JSONException e) {
log.warn("failed to parse hit from audit index. error: {}", e.getMessage());
- log.debug("failed to parse hit from audit. hit = {} {}", hit, e);
+ log.debug("failed to parse hit from audit. hit = {}", hit, e);
}
}
return hits;
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/Neo4jPropertyDAO.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/Neo4jPropertyDAO.java
index c3a7c50803..c9fcbab0de 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/Neo4jPropertyDAO.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/Neo4jPropertyDAO.java
@@ -49,51 +49,4 @@ public class Neo4jPropertyDAO extends BasicDao implements IPropertyDAO {
public void init() {
setNeo4jClient(neo4jClient);
}
-
- // @Override
- // public Either<PropertyData, Neo4jOperationStatus> createPropertyData(
- // GraphNeighbourTable graphNeighbourTable) {
- //
- // Either<BatchBuilder, Neo4jOperationStatus> bbResult = graphBatchBuilder
- // .buildBatchBuilderFromTable(graphNeighbourTable);
- //
- // if (bbResult.isLeft()) {
- //
- // BatchBuilder batchBuilder = bbResult.left().value();
- // //Neo4jOperationStatus neo4jOperationStatus =
- // neo4jClient.execute(batchBuilder);
- // Either<List<List<Neo4jElement>>, Neo4jOperationStatus> executeResult =
- // neo4jClient.execute(batchBuilder);
- //
- // if (executeResult.isRight()) {
- // return Either.right(executeResult.right().value());
- // }
- //
- // PropertyData propertyData = null;
- // List<List<Neo4jElement>> listOfResults = executeResult.left().value();
- // if (listOfResults != null) {
- // for (List<Neo4jElement> listOfElements : listOfResults) {
- // if (listOfElements != null && false == listOfElements.isEmpty()) {
- // for (Neo4jElement element : listOfElements) {
- // logger.debug("element {} was returned after running batch operation {}", element, batchBuilder);
- // if (element instanceof Neo4jNode) {
- // Neo4jNode neo4jNode = (Neo4jNode) element;
- // if (NodeTypeEnum.getByName(neo4jNode.getLabel()) ==
- // NodeTypeEnum.Property) {
- // propertyData = (PropertyData)neo4jNode;
- // }
- // }
- // }
- // }
- // }
- // }
- //
- // return Either.left(propertyData);
- //
- // } else {
- // return Either.right(bbResult.right().value());
- // }
- //
- // }
-
}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/Neo4jResourceDAO.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/Neo4jResourceDAO.java
index 1647a656f3..8d961b10ec 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/Neo4jResourceDAO.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/Neo4jResourceDAO.java
@@ -66,64 +66,6 @@ public class Neo4jResourceDAO extends BasicDao implements IResourceDAO {
super.setNeo4jClient(neo4jClient);
}
- // public Either<ResourceData, Neo4jOperationStatus> createResourceData(
- // GraphNeighbourTable graphNeighbourTable) {
- //
- // if (graphNeighbourTable != null) {
- //
- // String resourceId = findResourceDataIdFromNodes(graphNeighbourTable
- // .getNodes());
- // if (resourceId == null || resourceId.isEmpty()) {
- // logger.error("Cannot find resource id in the graph table");
- // return Either.right(Neo4jOperationStatus.BAD_REQUEST);
- // }
- //
- // Either<BatchBuilder, Neo4jOperationStatus> bbResult = graphBatchBuilder
- // .buildBatchBuilderFromTable(graphNeighbourTable);
- //
- // if (bbResult.isLeft()) {
- //
- // BatchBuilder batchBuilder = bbResult.left().value();
- // //Neo4jOperationStatus neo4jOperationStatus =
- // neo4jClient.execute(batchBuilder);
- // Either<List<List<Neo4jElement>>, Neo4jOperationStatus> executeResult =
- // neo4jClient.execute(batchBuilder);
- //
- // if (executeResult.isRight()) {
- // return Either.right(executeResult.right().value());
- // }
- //
- // ResourceData resourceData = null;
- // List<List<Neo4jElement>> listOfResults = executeResult.left().value();
- // if (listOfResults != null) {
- // for (List<Neo4jElement> listOfElements : listOfResults) {
- // if (listOfElements != null && false == listOfElements.isEmpty()) {
- // for (Neo4jElement element : listOfElements) {
- // logger.debug("element {} was returned after running batch operation {}", element, batchBuilder);
- // if (element instanceof Neo4jNode) {
- // Neo4jNode neo4jNode = (Neo4jNode) element;
- // if (NodeTypeEnum.getByName(neo4jNode.getLabel()) ==
- // NodeTypeEnum.Resource) {
- // resourceData = (ResourceData)neo4jNode;
- // }
- // }
- // }
- // }
- // }
- // }
- //
- // return Either.left(resourceData);
- //
- // } else {
- // return Either.right(bbResult.right().value());
- // }
- //
- // } else {
- // logger.error("The table sent in order to create resource is empty.");
- // return Either.right(Neo4jOperationStatus.BAD_REQUEST);
- // }
- // }
-
private String findResourceDataIdFromNodes(List<GraphNode> nodes) {
if (nodes != null) {
@@ -237,6 +179,51 @@ public class Neo4jResourceDAO extends BasicDao implements IResourceDAO {
}
return Either.right(null);
+ /*
+ * MatchFilter filter = new MatchFilter(); if(propertiesToMatch !=
+ * null){ for (Entry<String,Object> propertie :
+ * propertiesToMatch.entrySet()){ filter.addToMatch(propertie.getKey(),
+ * propertie.getValue()); } } Either<List<GraphElement>,
+ * Neo4jOperationStatus> status =
+ * neo4jClient.getByFilter(GraphElementTypeEnum.Node,
+ * NodeTypeEnum.Resource.getName(), filter); if (status.isRight()) {
+ * return Either.right(status.right().value()); } else {
+ * List<GraphElement> value = status.left().value(); if (value == null
+ * || value.isEmpty()) { return
+ * Either.right(Neo4jOperationStatus.NOT_FOUND); } else {
+ * List<ResourceData> result=new ArrayList<>(); for(GraphElement element
+ * : value ){ result.add((ResourceData)element); } return
+ * Either.left(result); } }
+ */
}
+ // @Override
+ // public ActionStatus updateUserData(UserData userData) {
+ // UpdateFilter filter = new UpdateFilter();
+ // filter.addToMatch("userId", userData.getUserId());
+ // filter.setToUpdate(userData.toMap());
+ // Neo4jOperationStatus status =
+ // neo4jClient.updateElement(Neo4JElementTypeEnum.Node,
+ // NodeTypeEnum.User.getName(), filter);
+ // if (status.equals(Neo4jOperationStatus.OK)) {
+ // return ActionStatus.OK;
+ // } else {
+ // return ActionStatus.GENERAL_ERROR;
+ // }
+ // }
+ //
+ // @Override
+ // public ActionStatus deleteUserData(String id) {
+ // MatchFilter filter = new MatchFilter();
+ // filter.addToMatch("userId", id);
+ // Neo4jOperationStatus status =
+ // neo4jClient.deleteElement(Neo4JElementTypeEnum.Node,
+ // NodeTypeEnum.User.getName(), filter);
+ // if (status.equals(Neo4jOperationStatus.OK)) {
+ // return ActionStatus.OK;
+ // } else {
+ // return ActionStatus.GENERAL_ERROR;
+ // }
+ // }
+
}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/Neo4jUsersDAO.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/Neo4jUsersDAO.java
index 25a77f1ff1..14489ef04b 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/Neo4jUsersDAO.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/Neo4jUsersDAO.java
@@ -89,12 +89,12 @@ public class Neo4jUsersDAO implements IUsersDAO {
if (createUniquenessStatus.equals(Neo4jOperationStatus.OK)) {
logger.info("Users constraints creatyed in Neo4j");
} else {
- logger.error("Failed to create constraints in Neo4j graph [" + createUniquenessStatus + "]");
+ logger.error("Failed to create constraints in Neo4j graph [{}]", createUniquenessStatus);
throw new RuntimeException(
"Failed to initialize Neo4jUsersDAO - Failed to create constraints in Neo4j graph");
}
} else {
- logger.error("Failed to create indexes in Neo4j graph [" + createIndexStatus + "]");
+ logger.error("Failed to create indexes in Neo4j graph [{}]", createIndexStatus);
throw new RuntimeException(
"Failed to initialize Neo4jUsersDAO - Failed to create indexes in Neo4j graph");
}
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
new file mode 100644
index 0000000000..67cbd258f4
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/GraphVertex.java
@@ -0,0 +1,153 @@
+package org.openecomp.sdc.be.dao.jsongraph;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import org.apache.commons.collections.MapUtils;
+import org.apache.commons.lang.StringUtils;
+import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
+import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+
+import com.thinkaurelius.titan.core.TitanVertex;
+
+public class GraphVertex {
+ private String uniqueId;
+
+ private TitanVertex vertex;
+ private VertexTypeEnum label;
+
+ private Map<String, ? extends ToscaDataDefinition> json;
+ private Map<String, Object> metadataJson;
+ private Map<GraphPropertyEnum, Object> metadataProperties;
+
+ public GraphVertex() {
+
+ }
+
+ public GraphVertex(VertexTypeEnum label) {
+ super();
+ this.label = label;
+ }
+
+ public String getUniqueId() {
+ return uniqueId;
+ }
+
+ public void setUniqueId(String uniqueId) {
+ this.uniqueId = uniqueId;
+ }
+
+ public Map<String, ? extends ToscaDataDefinition> getJson() {
+ return json;
+ }
+
+ public void setJson(Map<String, ? extends ToscaDataDefinition> json) {
+ this.json = json;
+ }
+
+ public TitanVertex getVertex() {
+ return vertex;
+ }
+
+ public void setVertex(TitanVertex vertex) {
+ this.vertex = vertex;
+ }
+
+ public VertexTypeEnum getLabel() {
+ return label;
+ }
+
+ public void setLabel(VertexTypeEnum label) {
+ this.label = label;
+ }
+
+ public ComponentTypeEnum getType() {
+ ComponentTypeEnum type = ComponentTypeEnum.valueOf((String) getMetadataProperty(GraphPropertyEnum.COMPONENT_TYPE));
+ return type;
+ }
+
+ public void setType(ComponentTypeEnum type) {
+ addMetadataProperty(GraphPropertyEnum.COMPONENT_TYPE, type.name());
+ }
+
+ public void addMetadataProperty(GraphPropertyEnum propName, Object propValue) {
+ if (metadataProperties == null) {
+ metadataProperties = new HashMap<>();
+ }
+ if (propValue != null) {
+ metadataProperties.put(propName, propValue);
+ }
+ }
+
+ public Object getMetadataProperty(GraphPropertyEnum metadataProperty) {
+ if (metadataProperties != null) {
+ return metadataProperties.get(metadataProperty);
+ }
+ return null;
+ }
+
+ public Map<GraphPropertyEnum, Object> getMetadataProperties() {
+ return metadataProperties;
+ }
+
+ public void setMetadataProperties(Map<GraphPropertyEnum, Object> metadataProperties) {
+ this.metadataProperties = metadataProperties;
+ }
+
+ public Map<String, Object> getMetadataJson() {
+ return metadataJson;
+ }
+
+ public void setMetadataJson(Map<String, Object> metadataJson) {
+ this.metadataJson = metadataJson;
+ }
+
+ /**
+ * used for clone vertex in case of copy on update
+ *
+ * @param other
+ */
+ public void cloneData(GraphVertex other) {
+ // need to be deep copy???
+ json = other.getJson();
+ metadataJson = other.getMetadataJson();
+ metadataProperties = other.getMetadataProperties();
+ }
+
+ public void setJsonMetadataField(JsonPresentationFields field, Object value) {
+ if (metadataJson == null) {
+ metadataJson = new HashMap<>();
+ }
+ metadataJson.put(field.getPresentation(), value);
+ }
+
+ public Object getJsonMetadataField(JsonPresentationFields field) {
+ if (metadataJson != null) {
+ return metadataJson.get(field.getPresentation());
+ }
+ return null;
+ }
+
+ /**
+ * Updates metadata json with current metadataProperties. Note that already existing property containing in metadata json can be overrided by new value if metadataProperties contains the same property (by key). Note that metadata json can contain
+ * a property that is not presented in metadataProperties. In such case the property will be put in metadata json.
+ */
+ public void updateMetadataJsonWithCurrentMetadataProperties() {
+ if (!MapUtils.isEmpty(metadataProperties)) {
+ if (metadataJson == null) {
+ metadataJson = new HashMap<>();
+ }
+ for (Entry<GraphPropertyEnum, Object> entry : metadataProperties.entrySet()) {
+ String propertyName = JsonPresentationFields.getPresentationByGraphProperty(entry.getKey());
+ if (StringUtils.isNotEmpty(propertyName) && entry.getValue() != null) {
+ metadataJson.put(propertyName, entry.getValue());
+ }
+ }
+ }
+ }
+}
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
new file mode 100644
index 0000000000..61e1b40d46
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/TitanDao.java
@@ -0,0 +1,890 @@
+package org.openecomp.sdc.be.dao.jsongraph;
+
+import java.io.IOException;
+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 org.apache.commons.collections.MapUtils;
+import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.apache.tinkerpop.gremlin.structure.Direction;
+import org.apache.tinkerpop.gremlin.structure.Edge;
+import org.apache.tinkerpop.gremlin.structure.Element;
+import org.apache.tinkerpop.gremlin.structure.Property;
+import org.apache.tinkerpop.gremlin.structure.Vertex;
+import org.apache.tinkerpop.gremlin.structure.util.ElementHelper;
+import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
+import org.openecomp.sdc.be.dao.jsongraph.types.EdgePropertyEnum;
+import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
+import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
+import org.openecomp.sdc.be.dao.jsongraph.utils.JsonParserUtils;
+import org.openecomp.sdc.be.dao.titan.TitanGraphClient;
+import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
+import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
+import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Qualifier;
+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 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()) {
+ 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());
+ }
+ }
+
+
+ /**
+ *
+ * @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);
+ }
+}
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
new file mode 100644
index 0000000000..6f5910f581
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/types/EdgeLabelEnum.java
@@ -0,0 +1,50 @@
+package org.openecomp.sdc.be.dao.jsongraph.types;
+
+public enum EdgeLabelEnum {
+ ARTIFACTS,
+ DEPLOYMENT_ARTIFACTS,
+ INST_DEPLOYMENT_ARTIFACTS,
+ INSTANCE_ARTIFACTS,
+ INTERFACE_ARTIFACTS,
+ TOSCA_ARTIFACTS,
+ PROPERTIES,
+ CAPABILITIES,
+ CAPABILITIES_PROPERTIES,
+ REQUIREMENTS,
+ ATTRIBUTES,
+ ADDITIONAL_INFORMATION,
+ CATEGORY,
+ DERIVED_FROM,
+ STATE,
+ LAST_STATE,
+ LAST_MODIFIER,
+ VERSION,
+ CREATOR,
+ SUB_CATEGORY,
+ INPUTS,
+ GROUPS,
+ INST_PROPERTIES,
+ INST_INPUTS,
+ INST_ATTRIBUTES,
+ INST_GROUPS,
+ SERVICE_API_ARTIFACTS,
+ CALCULATED_CAPABILITIES,
+ FULLFILLED_CAPABILITIES,
+ CALCULATED_REQUIREMENTS,
+ FULLFILLED_REQUIREMENTS,
+ LAST_DISTRIBUTION_STATE_MODIFIER,
+ CALCULATED_CAP_PROPERTIES;
+ /**
+ * Returns EdgeLabelEnum according received name
+ * @param name
+ * @return
+ */
+ public static EdgeLabelEnum getEdgeLabelEnum(String name){
+ for(EdgeLabelEnum currLabel : EdgeLabelEnum.values()){
+ if (currLabel.name().equals(name)){
+ return currLabel;
+ }
+ }
+ return null;
+ }
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/types/EdgePropertyEnum.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/types/EdgePropertyEnum.java
new file mode 100644
index 0000000000..df2f52040d
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/types/EdgePropertyEnum.java
@@ -0,0 +1,25 @@
+package org.openecomp.sdc.be.dao.jsongraph.types;
+
+public enum EdgePropertyEnum {
+
+ STATE ("state");
+
+ private String property;
+
+ public String getProperty() {
+ return property;
+ }
+
+ EdgePropertyEnum (String property){
+ this.property = property;
+ }
+
+ public static EdgePropertyEnum getByProperty(String property){
+ for ( EdgePropertyEnum inst : EdgePropertyEnum.values() ){
+ if ( inst.getProperty().equals(property) ){
+ return inst;
+ }
+ }
+ return null;
+ }
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/types/GraphJsonProperty.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/types/GraphJsonProperty.java
new file mode 100644
index 0000000000..c54825a39e
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/types/GraphJsonProperty.java
@@ -0,0 +1,19 @@
+package org.openecomp.sdc.be.dao.jsongraph.types;
+
+import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
+
+public enum GraphJsonProperty {
+ METADATA (GraphPropertyEnum.METADATA),
+ JSON (GraphPropertyEnum.JSON);
+
+ private GraphPropertyEnum propInGraph;
+
+ GraphJsonProperty (GraphPropertyEnum propInGraph){
+ this.propInGraph = propInGraph;
+ }
+
+ public GraphPropertyEnum getPropInGraph() {
+ return propInGraph;
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/types/JsonParseFlagEnum.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/types/JsonParseFlagEnum.java
new file mode 100644
index 0000000000..aea488e086
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/types/JsonParseFlagEnum.java
@@ -0,0 +1,9 @@
+package org.openecomp.sdc.be.dao.jsongraph.types;
+
+public enum JsonParseFlagEnum {
+
+ NoParse,
+ ParseAll,
+ ParseJson,
+ ParseMetadata
+}
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
new file mode 100644
index 0000000000..c485b238f4
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/types/VertexTypeEnum.java
@@ -0,0 +1,62 @@
+package org.openecomp.sdc.be.dao.jsongraph.types;
+
+import org.openecomp.sdc.be.datatypes.elements.*;
+
+
+public enum VertexTypeEnum {
+ NODE_TYPE ("node_type", null),
+ TOPOLOGY_TEMPLATE ("topology_template", CompositionDataDefinition.class),
+ ARTIFACTS ("artifacts", ArtifactDataDefinition.class),
+ TOSCA_ARTIFACTS ("tosca_artifacts", ArtifactDataDefinition.class),
+ DEPLOYMENT_ARTIFACTS ("deployment_artifacts", ArtifactDataDefinition.class),
+ INST_DEPLOYMENT_ARTIFACTS ("inst_deployment_artifacts", MapArtifactDataDefinition.class),
+ INTERFACE_ARTIFACTS ("interface_artifacts", InterfaceDataDefinition.class),
+ INSTANCE_ARTIFACTS ("instance_artifacts", MapArtifactDataDefinition.class),
+ PROPERTIES ("properties", PropertyDataDefinition.class),
+ CAPABILTIES ("capabilities", ListCapabilityDataDefinition.class),
+ CAPABILITIES_PROPERTIES ("capabilities_properties", MapPropertiesDataDefinition.class),
+ REQUIREMENTS ("requirements", ListRequirementDataDefinition.class),
+ ATTRIBUTES ("attributes", AttributeDataDefinition.class),
+ RESOURCE_CATEGORY ("resourceNewCategory", null),
+ RESOURCE_SUBCATEGORY ("resourceSubcategory", null),
+ SERVICE_CATEGORY ("serviceNewCategory", null),
+ ADDITIONAL_INFORMATION ("additional_information", AdditionalInfoParameterDataDefinition.class),
+ USER ("user", null),
+ INPUTS ("inputs", PropertyDataDefinition.class),
+ GROUPS ("groups", GroupDataDefinition.class),
+ INST_ATTRIBUTES ("instAttributes", MapAttributesDataDefinition.class),
+ INST_PROPERTIES ("instProperties", MapPropertiesDataDefinition.class),
+ INST_INPUTS ("instInputs", MapPropertiesDataDefinition.class),
+ INST_GROUPS ("instGroups", MapGroupsDataDefinition.class),
+ SERVICE_API_ARTIFACTS ("serviceApiArtifacts", ArtifactDataDefinition.class),
+ CALCULATED_CAPABILITIES ("calculatedCapabilities", MapListCapabiltyDataDefinition.class),
+ FULLFILLED_CAPABILITIES ("fullfilledCapabilities", MapListCapabiltyDataDefinition.class),
+ CALCULATED_REQUIREMENTS ("calculatedRequirements", MapListRequirementDataDefinition.class),
+ FULLFILLED_REQUIREMENTS ("fullfilledRequirements", MapListRequirementDataDefinition.class),
+ CALCULATED_CAP_PROPERTIES ("calculatedCapProperties", MapCapabiltyProperty.class)
+;
+
+ private String name;
+ private Class classOfJson;
+ VertexTypeEnum(String name, Class clazz){
+ this.name = name;
+ classOfJson = clazz;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public Class getClassOfJson() {
+ return classOfJson;
+ }
+
+ public static VertexTypeEnum getByName(String name){
+ for ( VertexTypeEnum inst : VertexTypeEnum.values() ){
+ if ( inst.getName().equals(name) ){
+ return inst;
+ }
+ }
+ return null;
+ }
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/utils/IdBuilderUtils.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/utils/IdBuilderUtils.java
new file mode 100644
index 0000000000..dfff258840
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/utils/IdBuilderUtils.java
@@ -0,0 +1,23 @@
+package org.openecomp.sdc.be.dao.jsongraph.utils;
+
+import java.util.UUID;
+import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
+
+public class IdBuilderUtils {
+ private static String DOT = ".";
+
+ public static String generateChildId(String componentId, VertexTypeEnum type){
+ StringBuffer sb = new StringBuffer(componentId);
+ sb.append(DOT).append(type.getName());
+ return sb.toString();
+ }
+
+ public static String generateUUID(){
+ return UUID.randomUUID().toString();
+ }
+
+ public static String generateUniqueId(){
+ return UUID.randomUUID().toString();
+ }
+
+}
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
new file mode 100644
index 0000000000..a7fe34071d
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/utils/JsonParserUtils.java
@@ -0,0 +1,66 @@
+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 org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class JsonParserUtils {
+ private static ObjectMapper mapper = new ObjectMapper();
+ private static Logger logger = LoggerFactory.getLogger(JsonParserUtils.class.getName());
+
+
+ public static <T> String jsonToString(T elementToRepresent) throws IOException, JsonGenerationException, JsonMappingException {
+
+
+ mapper.configure(Feature.FAIL_ON_EMPTY_BEANS, false);
+ mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
+ return mapper.writeValueAsString(elementToRepresent);
+ }
+
+ 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>>() {
+ };
+
+ 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);
+
+ try {
+ object = mapper.readValue(json, type);
+ } catch (Exception e) {
+ logger.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 917bcbb986..1b5222c0a0 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
@@ -27,43 +27,17 @@ public enum GraphEdgeLabels {
// field name
//
- STATE("STATE"), LAST_STATE("LAST_STATE"), CREATOR("CREATOR"), LAST_MODIFIER("LAST_MODIFIER"), ATTRIBUTE(
- "EDGE_ATTRIBUTE"), PROPERTY("EDGE_PROPERTY"), CATEGORY("CATEGORY"), DERIVED_FROM(
- "DERIVED_FROM"), REQUIREMENT("REQUIREMENT"), CAPABILITY_TYPE("CAPABILITY_TYPE"), RELATIONSHIP_TYPE(
- "RELATIONSHIP_TYPE"), CAPABILITY("CAPABILITY"), INSTANCE_OF("INSTANCE_OF"), INTERFACE(
- "INTERFACE"), INTERFACE_OPERATION("INTERFACE_OPERATION"), ARTIFACT_REF(
- "ARTIFACT_REF"), INPUTS("INPUTS"), REQUIREMENT_IMPL(
- "REQUIREMENT_IMPL"), NODE_IMPL("NODE_IMPL"), IMPLEMENTATION_OF(
- "IMPLEMENTATION_OF"), ATTRIBUTE_VALUE(
- "ATTRIBUTE_VALUE"), INPUT_VALUE(
- "INPUT_VALUE"), PROPERTY_VALUE(
- "PROPERTY_VALUE"), CAPABILITY_INST(
- "CAPABILITY_INST"), TYPE_OF(
- "TYPE_OF"), RESOURCE_INST(
- "RESOURCE_INST"), RELATIONSHIP_INST(
- "RELATIONSHIP_INST"), CAPABILITY_NODE(
- "CAPABILITY_NODE"), LAST_DISTRIBUTION_STATE_MODIFAIER(
- "LAST_DISTRIBUTION_STATE_MODIFAIER"), ATTRIBUTE_IMPL(
- "ATTRIBUTE_IMPL"), INPUT_IMPL(
- "INPUT_IMPL"), PROPERTY_IMPL(
- "PROPERTY_IMPL"), ADDITIONAL_INFORMATION(
- "ADDITIONAL_INFORMATION"), HEAT_PARAMETER(
- "HEAT_PARAMETER"), SUB_CATEGORY(
- "SUB_CATEGORY"), GROUPING(
- "GROUPING"), CATEGORIZED_TO(
- "CATEGORIZED_TO"), GENERATED_FROM(
- "GENERATED_FROM"), PARAMETER_VALUE(
- "PARAMETER_VALUE"), PARAMETER_IMPL(
- "PARAMETER_IMPL"),
+ STATE("STATE"), LAST_STATE("LAST_STATE"), CREATOR("CREATOR"), LAST_MODIFIER("LAST_MODIFIER"), ATTRIBUTE("EDGE_ATTRIBUTE"), PROPERTY("EDGE_PROPERTY"), CATEGORY("CATEGORY"), DERIVED_FROM("DERIVED_FROM"), REQUIREMENT("REQUIREMENT"),
+ CAPABILITY_TYPE("CAPABILITY_TYPE"), RELATIONSHIP_TYPE("RELATIONSHIP_TYPE"), CAPABILITY("CAPABILITY"), INSTANCE_OF("INSTANCE_OF"), INTERFACE("INTERFACE"), INTERFACE_OPERATION("INTERFACE_OPERATION"), ARTIFACT_REF("ARTIFACT_REF"),
+ INPUTS("INPUTS"), REQUIREMENT_IMPL("REQUIREMENT_IMPL"), NODE_IMPL("NODE_IMPL"), IMPLEMENTATION_OF("IMPLEMENTATION_OF"), ATTRIBUTE_VALUE("ATTRIBUTE_VALUE"), INPUT_VALUE("INPUT_VALUE"), PROPERTY_VALUE("PROPERTY_VALUE"),
+ CAPABILITY_INST("CAPABILITY_INST"), TYPE_OF("TYPE_OF"), RESOURCE_INST("RESOURCE_INST"), RELATIONSHIP_INST("RELATIONSHIP_INST"), CAPABILITY_NODE("CAPABILITY_NODE"), LAST_DISTRIBUTION_STATE_MODIFAIER("LAST_DISTRIBUTION_STATE_MODIFAIER"),
+ ATTRIBUTE_IMPL("ATTRIBUTE_IMPL"), INPUT_IMPL("INPUT_IMPL"), PROPERTY_IMPL("PROPERTY_IMPL"), ADDITIONAL_INFORMATION("ADDITIONAL_INFORMATION"), HEAT_PARAMETER("HEAT_PARAMETER"), SUB_CATEGORY("SUB_CATEGORY"), GROUPING("GROUPING"),
+ CATEGORIZED_TO("CATEGORIZED_TO"), GENERATED_FROM("GENERATED_FROM"), PARAMETER_VALUE("PARAMETER_VALUE"), PARAMETER_IMPL("PARAMETER_IMPL"),
// VF additions
- 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"),
+ 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("GROUP"), GROUP_ARTIFACT_REF("GROUP_ARTIFACT_REF"), GROUP_MEMBER("GROUP_MEMBER"), INPUT("EDGE_INPUT"), GET_INPUT("GET_INPUT"), GROUP_INST("GROUP_INST");
private String property;
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/GraphEdgePropertiesDictionary.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/GraphEdgePropertiesDictionary.java
index 18c9ecb6f7..2af909ee0d 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/GraphEdgePropertiesDictionary.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/GraphEdgePropertiesDictionary.java
@@ -29,10 +29,14 @@ public enum GraphEdgePropertiesDictionary {
// field name class type
// stored in graph
- STATE("state", String.class), NAME("name", String.class), GROUP_TYPE("groupType", String.class), SOURCE("source",
- String.class), OWNER_ID("ownerId", String.class), REQUIRED_OCCURRENCES("requiredOccurrences",
- String.class), LEFT_OCCURRENCES("leftOccurrences",
- String.class), GET_INPUT_INDEX("get_input_index", String.class);
+ STATE("state", String.class),
+ NAME("name", String.class),
+ GROUP_TYPE("groupType", String.class),
+ SOURCE("source", String.class),
+ OWNER_ID("ownerId", String.class),
+ REQUIRED_OCCURRENCES("requiredOccurrences", String.class),
+ LEFT_OCCURRENCES("leftOccurrences", String.class),
+ GET_INPUT_INDEX("get_input_index", String.class);
private String property;
private Class clazz;
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/GraphPropertiesDictionary.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/GraphPropertiesDictionary.java
index a042ab510e..3ec9d0d3b9 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/GraphPropertiesDictionary.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/GraphPropertiesDictionary.java
@@ -1,23 +1,3 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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.neo4j;
import java.util.ArrayList;
@@ -64,7 +44,7 @@ public enum GraphPropertiesDictionary {
IMPORTED_TOSCA_CHECKSUM ("importedToscaChecksum", String.class, false, true),
GENERATED ("generated", Boolean.class, false, false),
// User
- USER_ID ("userId", String.class, true, true),
+ USERID ("userId", String.class, true, true),
EMAIL ("email", String.class, false, false),
FIRST_NAME ("firstName", String.class, false, false),
LAST_NAME ("lastName", String.class, false, false),
@@ -83,7 +63,7 @@ public enum GraphPropertiesDictionary {
ARTIFACT_REPOSITORY ("artifactRepository", String.class, false, false),
ARTIFACT_CHECKSUM ("artifactChecksum", String.class, false, false),
CREATOR ("creator", String.class, false, false),
- ATT_CREATOR ("attCreator", String.class, false, false),
+ CREATOR_ID ("creatorId", String.class, false, false),
LAST_UPDATER ("lastUpdater", String.class, false, false),
CREATOR_FULL_NAME ("creatorFullName", String.class, false, false),
UPDATER_FULL_NAME ("updaterFullName", String.class, false, false),
@@ -147,6 +127,7 @@ public enum GraphPropertiesDictionary {
STATUS ("status", String.class, false, false),
FUNCTIONAL_MENU ("functionalMenu", String.class, false, false),
REQUIRED_ARTIFACTS ("requiredArtifacts", String.class, false, false),
+ CUSTOMIZATION_UUID ("customizationUUID", String.class, false, false),
;
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/Neo4jClient.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/Neo4jClient.java
index 8bab8d8a8f..eb279cda3d 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/Neo4jClient.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/Neo4jClient.java
@@ -130,7 +130,7 @@ public class Neo4jClient {
public Either<List<List<GraphElement>>, Neo4jOperationStatus> execute(BatchBuilder builder) {
String json = cypherTranslator.translate(builder);
- logger.debug("Try to execute cypher request [ {} ]", json);
+ logger.debug("Try to execute cypher request [{}]", json);
Either<String, Neo4jOperationStatus> result = sendPostCypher(json);
if (result.isRight()) {
@@ -149,7 +149,7 @@ public class Neo4jClient {
public Either<List<List<GraphElement>>, Neo4jOperationStatus> executeGet(RecursiveFilter filter) {
String json = cypherTranslator.translateGet(filter);
- logger.debug("Try to execute cypher request [ {} ]", json);
+ logger.debug("Try to execute cypher request [{}]", json);
Either<String, Neo4jOperationStatus> result = sendPostCypher(json);
if (result.isRight()) {
@@ -264,7 +264,7 @@ public class Neo4jClient {
String filterStr = CypherTranslator.prepareFilterBody(filter);
requestJson = requestJson.replace("$filter$", filterStr);
}
- logger.debug("Try to perform request [ {} ]", requestJson);
+ logger.debug("Try to perform request []", requestJson);
Either<String, Neo4jOperationStatus> status = sendPostCypher(requestJson);
if (status.isRight()) {
@@ -320,7 +320,7 @@ public class Neo4jClient {
String props = preparePropertiesInStatement(toUpdate.getToUpdate());
requestJson = requestJson.replace("$props$", props);
- logger.debug("Try to perform request [ {} ]", requestJson);
+ logger.debug("Try to perform request [{}]", requestJson);
Either<String, Neo4jOperationStatus> result = sendPostCypher(requestJson);
if (result.isRight()) {
@@ -493,7 +493,7 @@ public class Neo4jClient {
GraphNode node = (GraphNode) element;
String json = prepareCreateNodeBody(node);
- logger.debug("Try to save Node [ {} ]", json);
+ logger.debug("Try to save Node [{}] on graph", json);
status = sendPostCypher(json);
@@ -528,10 +528,10 @@ public class Neo4jClient {
int status = response.getStatusLine().getStatusCode();
String responseString;
responseString = new BasicResponseHandler().handleResponse(response);
- logger.debug("response [ {} ]", responseString);
+ logger.debug("response [{}]", responseString);
if (status == 200 || status == 201) {
- logger.debug("cypher request [ {} ]", json);
+ logger.debug("cypher request [{}] was succeeded", json);
Neo4jOperationStatus responseStatus = checkResponse(responseString);
if (Neo4jOperationStatus.OK.equals(responseStatus)) {
return Either.left(responseString);
@@ -539,22 +539,22 @@ public class Neo4jClient {
return Either.right(responseStatus);
}
} else {
- logger.debug("cypher request [ {} ] was failed: [ {} ]", json, responseString);
+ logger.debug("cypher request [{}] was failed : [{}]", json, responseString);
return Either.right(Neo4jOperationStatus.GENERAL_ERROR);
}
} catch (HttpResponseException e) {
- logger.debug("failed to perform cypher request [ {} ], {}", json, e);
+ logger.debug("failed to perform cypher request [{}]", json, e);
if (e.getStatusCode() == 401) {
return Either.right(Neo4jOperationStatus.NOT_AUTHORIZED);
} else {
return Either.right(Neo4jOperationStatus.GENERAL_ERROR);
}
} catch (ClientProtocolException e) {
- logger.debug("failed to perform cypher request [ {} ] {}", json, e);
+ logger.debug("failed to perform cypher request [{}]", json, e);
return Either.right(Neo4jOperationStatus.HTTP_PROTOCOL_ERROR);
} catch (IOException e) {
- logger.debug("failed to perform cypher request [ {} ] {}", json, e);
+ logger.debug("failed to perform cypher request [{}]", json, e);
return Either.right(Neo4jOperationStatus.NOT_CONNECTED);
} finally {
releaseResource(response);
@@ -722,7 +722,7 @@ public class Neo4jClient {
response = httpClient.execute(get, context);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
- logger.error("failed to get indexes requeste returned " + statusCode);
+ logger.error("failed to get indexes requeste returned {}", statusCode);
return Either.right(Neo4jOperationStatus.GENERAL_ERROR);
} else {
Map<String, List<String>> labels = getLeablesFromJson(response);
@@ -793,14 +793,13 @@ public class Neo4jClient {
response = httpClient.execute(post, context);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
- logger.error("failed to create index for label [" + label + "] with properties:" + propertyNames
- + " requeste returned " + statusCode);
+ logger.error("failed to create index for label [{}] with properties:{} requeste returned {}",label,propertyNames,statusCode);
result = Neo4jOperationStatus.GENERAL_ERROR;
} else {
- logger.debug("index for label [ {} ] with properties {} created", label, propertyNames);
+ logger.debug("index for label [{}] with properties: {} created", label, propertyNames);
}
} catch (Exception e) {
- logger.debug("failed to create index for label [ {} ] with properties {}", label, propertyNames);
+ logger.debug("failed to create index for label [{}] with properties: {}", label, propertyNames);
result = Neo4jOperationStatus.GENERAL_ERROR;
} finally {
@@ -811,7 +810,7 @@ public class Neo4jClient {
}
else {
- logger.debug("no index was created for label: {}, the received propertyNames list: {} is invalid", label, propertyNames);
+ logger.debug("no index was created for label :{} the recived propertyNames list: {} is invalide",label,propertyNames);
return Neo4jOperationStatus.WRONG_INPUT;
}
@@ -850,14 +849,14 @@ public class Neo4jClient {
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
- logger.error("failed to create uniqueness constraint for label [" + label + "] on properties:"
- + propertyNames + ". request returned " + statusCode);
+ logger.error("failed to create uniqueness constraint for label [{}] on properties:{}. request returned ",
+ label,propertyNames,statusCode);
result = Neo4jOperationStatus.GENERAL_ERROR;
} else {
- logger.debug("uniqueness constraint for label [ {} ] on properties {} created", label, propertyNames);
+ logger.debug("uniqueness constraint for label [{}] on properties:{} created",label,propertyNames);
}
} catch (Exception e) {
- logger.error("failed to create uniqueness constraint [ {} ] with properties {}, error: {}",label, propertyNames, e);
+ logger.error("failed to create uniqueness constraint [{}] with properties:{}",label,propertyNames,e);
result = Neo4jOperationStatus.GENERAL_ERROR;
} finally {
releaseResource(response);
@@ -866,7 +865,7 @@ public class Neo4jClient {
}
else {
- logger.debug("no index was created for label: {} the received propertyNames list: {} is invalid", label, propertyNames);
+ logger.debug("no index was created for label :{} the recived propertyNames list: {} is invalide",label,propertyNames);
return Neo4jOperationStatus.WRONG_INPUT;
}
@@ -886,11 +885,11 @@ public class Neo4jClient {
throw new RuntimeException(" delete on type " + type + " is not yet supported");
}
- logger.debug("Try to perform request [ {} ]", requestJson);
+ logger.debug("Try to perform request [{}]", requestJson);
Either<String, Neo4jOperationStatus> status = sendPostCypher(requestJson);
if (status.isRight()) {
- logger.error(" delete request failed with {}", status.right());
+ logger.error(" delete request failed with: {}", status.right());
return Neo4jOperationStatus.GENERAL_ERROR;
} else {
return Neo4jOperationStatus.OK;
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/Neo4jGraphBatchBuilder.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/Neo4jGraphBatchBuilder.java
index 831fb001be..5a6a8fdade 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/Neo4jGraphBatchBuilder.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/Neo4jGraphBatchBuilder.java
@@ -48,11 +48,6 @@ public class Neo4jGraphBatchBuilder {
List<GraphNode> nodes = graphNeighbourTable.getNodes();
if (nodes != null && nodes.size() > 0) {
- // String resourceId = findResourceDataIdFromNodes(nodes);
- // if (resourceId == null || resourceId.isEmpty()) {
- // logger.error("Cannot find resource id in the graph table");
- // return Either.right(ActionStatus.INVALID_CONTENT);
- // }
List<NodeRelation> directedEdges = graphNeighbourTable.getDirectedEdges();
List<RelationEndPoint> relationEndPoints = new ArrayList<RelationEndPoint>(nodes.size());
@@ -72,7 +67,7 @@ public class Neo4jGraphBatchBuilder {
if (directedEdges != null) {
for (NodeRelation nodeRelation : directedEdges) {
GraphRelation relation = buildNeo4jRelation(relationEndPoints, nodeRelation);
- logger.debug("Goint to add relation {} to catch builder.", relation);
+ logger.debug("Goint to add relation {} to batch builder.", relation);
batchBuilder.add(relation);
}
}
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
index fb09131b42..91a984b7f2 100644
--- 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
@@ -98,7 +98,6 @@ public class HttpRestClient {
//
//
// } catch (RestClientServiceExeption e) {
- // // TODO Auto-generated catch block
// e.printStackTrace();
// }
//
@@ -116,23 +115,11 @@ public class HttpRestClient {
public boolean init(RestConfigurationInfo restConfigurationInfo) {
- logger.debug("create HttpRestClient: restConfigurationInfo={}", restConfigurationInfo);
+ logger.debug("create HttpRestClient: restConfigurationInfo= {}", restConfigurationInfo);
boolean result = false;
- // try {
createHttpClient(restConfigurationInfo);
result = true;
- // } catch (KeyManagementException e) {
- // String msg = "Failed creating client config for rest. "
- // + e.getMessage();
- // logger.debug(msg, e);
- // //TODO: log. error
- // } catch (NoSuchAlgorithmException e) {
- // String msg = "Failed creating client config for rest. "
- // + e.getMessage();
- // logger.debug(msg, e);
- // //TODO: log. error
- // }
-
+
logger.debug("Finish creating HttpRestClient. Result is {}", result);
return result;
}
@@ -225,7 +212,7 @@ public class HttpRestClient {
public RestResponse doPUT(String uri, Properties headers, String body) {
- logger.debug("Before executing uri {}. headers = {}. body = ", uri, headers, body);
+ logger.debug("Before executing uri {}. headers = {}.body = {}", uri, headers, body);
HttpPut httpPut = new HttpPut(uri);
StringEntity data = new StringEntity(body, ContentType.APPLICATION_JSON);
@@ -237,7 +224,7 @@ public class HttpRestClient {
public RestResponse doPOST(String uri, Properties headers, String body) {
- logger.debug("Before executing uri {}. headers = {}. body = {}", uri, headers, body);
+ logger.debug("Before executing uri {}. headers = {}.body = {}", uri, headers, body);
HttpPost httpPost = new HttpPost(uri);
StringEntity data = new StringEntity(body, ContentType.APPLICATION_JSON);
@@ -249,7 +236,7 @@ public class HttpRestClient {
public RestResponseAsByteArray doGetAsByteArray(String uri, Properties headers) {
- logger.debug("Before executing uri {}. headers = {}.", uri, headers);
+ logger.debug("Before executing uri {}. headers = {}", uri, headers);
HttpGet httpGet = new HttpGet(uri);
@@ -282,7 +269,8 @@ public class HttpRestClient {
restResponse = buildRestResponseFromResult(httpResponse);
- logger.debug("After executing uri {}. response = {}.", httpRequestBase.getURI().toString(), restResponse);
+ logger.debug("After executing uri {}. response = {}", httpRequestBase.getURI().toString(), restResponse);
+
} catch (Exception exception) {
httpRequestBase.abort();
@@ -351,7 +339,7 @@ public class HttpRestClient {
restResponse = buildRestResponseByteArrayFromResult(httpResponse);
if (restResponse != null) {
- logger.debug("After executing uri {}. Response: {}.", httpRequestBase.getURI().toString(), restResponse.toPrettyString());
+ logger.debug("After executing uri {}. Response: {}", httpRequestBase.getURI().toString(), restResponse.toPrettyString());
}
} catch (Exception exception) {
@@ -379,7 +367,7 @@ public class HttpRestClient {
* name of method
*/
private void logResponse(String response, String method) {
- logger.trace(method + " response = " + response);
+ logger.trace("{} response = {}", method, response);
}
private void releaseResource(CloseableHttpResponse response) {
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 535146d692..8445d58873 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
@@ -26,6 +26,8 @@ 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 javax.annotation.Resource;
@@ -45,6 +47,7 @@ import org.openecomp.sdc.be.dao.graph.datatype.GraphElementTypeEnum;
import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation;
import org.openecomp.sdc.be.dao.graph.datatype.RelationEndPoint;
+import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
@@ -62,17 +65,16 @@ import com.thinkaurelius.titan.core.TitanVertexQuery;
import com.thinkaurelius.titan.graphdb.query.TitanPredicate;
import fj.data.Either;
-
@Component("titan-generic-dao")
public class TitanGenericDao {
- @Resource
- TitanGraphClient titanClient;
+ private TitanGraphClient titanClient;
private static Logger logger = LoggerFactory.getLogger(TitanGenericDao.class.getName());
private static final String LOCK_NODE_PREFIX = "lock_";
- public TitanGenericDao() {
+ public TitanGenericDao(TitanGraphClient titanClient) {
+ this.titanClient = titanClient;
logger.info("** TitanGenericDao created");
}
@@ -231,14 +233,9 @@ public class TitanGenericDao {
}
}
- public TitanOperationStatus createEdge(TitanVertex vertexOut, TitanVertex vertexIn, GraphEdgeLabels type, Map<String, Object> properties) {
+ public TitanOperationStatus createEdge(Vertex vertexOut, Vertex vertexIn, GraphEdgeLabels type, Map<String, Object> properties) {
try {
- Edge edge = vertexOut.addEdge(type.getProperty(), vertexIn);
-
- if (properties != null) {
-
- setProperties(edge, properties);
- }
+ Edge edge = addEdge(vertexOut, vertexIn, type, properties);
} catch (Exception e) {
logger.debug("Failed to create edge from [{}] to [{}]", vertexOut, vertexIn, e);
return TitanGraphClient.handleTitanException(e);
@@ -246,6 +243,42 @@ public class TitanGenericDao {
return TitanOperationStatus.OK;
}
+
+ private Edge addEdge(Vertex vertexOut, Vertex vertexIn, GraphEdgeLabels type, Map<String, Object> properties) {
+ Edge edge = vertexOut.addEdge(type.getProperty(), vertexIn);
+
+ if (properties != null) {
+
+ setProperties(edge, properties);
+ }
+ return edge;
+ }
+
+ /**
+ * creates an identical edge in the graph
+ * @param edge
+ * @return the copy operation status
+ */
+ public Either<Edge, TitanOperationStatus> copyEdge(Vertex out, Vertex in, Edge edge) {
+ GraphEdgeLabels byName = GraphEdgeLabels.getByName(edge.label());
+ return this.saveEdge(out, in, byName, edgePropertiesToMap(edge));
+ }
+
+ private <V> Map<String, Object> edgePropertiesToMap(Edge edge) {
+ Iterable<Property<Object>> propertiesIterable = edge::properties;
+ return StreamSupport.stream(propertiesIterable.spliterator(), false).collect(Collectors.toMap(Property::key, Property::value));
+ }
+
+ public Either<Edge, TitanOperationStatus> saveEdge(Vertex vertexOut, Vertex vertexIn, GraphEdgeLabels type, Map<String, Object> properties) {
+ try {
+ Edge edge = addEdge(vertexOut, vertexIn, type, properties);
+ return Either.left(edge);
+ } catch (Exception e) {
+ logger.debug("Failed to create edge from [{}] to [{}]", vertexOut, vertexIn, e);
+ return Either.right(TitanGraphClient.handleTitanException(e));
+ }
+
+ }
public TitanOperationStatus createEdge(TitanVertex vertexOut, GraphNode to, GraphEdgeLabels type, Map<String, Object> properties) {
@@ -336,10 +369,7 @@ public class TitanGenericDao {
public Either<GraphRelation, TitanOperationStatus> getRelation(GraphNode from, GraphNode to, GraphEdgeLabels label) {
logger.debug("try to get relation from [{}] to [{}]", from.getKeyValueId(), to.getKeyValueId());
- ImmutablePair<String, Object> keyValueIdFrom = from.getKeyValueId();
- ImmutablePair<String, Object> keyValueIdTo = to.getKeyValueId();
-
- Either<Edge, TitanOperationStatus> edge = getEdgeByVerticies(keyValueIdFrom.getKey(), keyValueIdFrom.getValue(), keyValueIdTo.getKey(), keyValueIdTo.getValue(), label.getProperty());
+ Either<Edge, TitanOperationStatus> edge = getEdgeByNodes(from, to, label);
if (edge.isLeft()) {
try {
@@ -356,6 +386,13 @@ public class TitanGenericDao {
}
}
+ public Either<Edge, TitanOperationStatus> getEdgeByNodes(GraphNode from, GraphNode to, GraphEdgeLabels label) {
+ ImmutablePair<String, Object> keyValueIdFrom = from.getKeyValueId();
+ ImmutablePair<String, Object> keyValueIdTo = to.getKeyValueId();
+
+ return getEdgeByVerticies(keyValueIdFrom.getKey(), keyValueIdFrom.getValue(), keyValueIdTo.getKey(), keyValueIdTo.getValue(), label.getProperty());
+ }
+
public Either<GraphRelation, TitanOperationStatus> deleteIncomingRelationByCriteria(GraphNode to, GraphEdgeLabels label, Map<String, Object> props) {
Either<Edge, TitanOperationStatus> edgeByCriteria = getIncomingEdgeByCriteria(to, label, props);
@@ -445,7 +482,7 @@ public class TitanGenericDao {
return Either.left(matchingEdge);
}
- private Either<Edge, TitanOperationStatus> getEdgeByVerticies(String keyNameFrom, Object keyValueFrom, String keyNameTo, Object keyValueTo, String label) {
+ public Either<Edge, TitanOperationStatus> getEdgeByVerticies(String keyNameFrom, Object keyValueFrom, String keyNameTo, Object keyValueTo, String label) {
Either<TitanGraph, TitanOperationStatus> graph = titanClient.getGraph();
if (graph.isLeft()) {
@@ -549,18 +586,18 @@ public class TitanGenericDao {
GraphRelation newRelation = GraphElementFactory.createRelation(edge.label(), getProperties(edge), nodeOut, nodeIn);
if (logger.isDebugEnabled()) {
- logger.debug("Relation was updated from [ {} ] to [ {} ]", from, to);
+ logger.debug("Relation was updated from [{}] to [{}] ", from, to);
}
return Either.left(newRelation);
} catch (Exception e) {
if (logger.isDebugEnabled()) {
- logger.debug("Failed to update relation from [ {} ] [ {} ] {}", from, to, e);
+ logger.debug("Failed to update relation from [{}] to [{}] ", from, to, e);
}
return Either.right(TitanGraphClient.handleTitanException(e));
}
} else {
if (logger.isDebugEnabled()) {
- logger.debug("Failed to update relation from [ {} ] [ {} ] {}", from, to, edgeS.right().value());
+ logger.debug("Failed to update relation from [{}] to [{}] {}", from, to, edgeS.right().value());
}
return Either.right(edgeS.right().value());
}
@@ -598,19 +635,19 @@ public class TitanGenericDao {
return Either.left(vertex);
}
if (logger.isDebugEnabled()) {
- logger.debug("No vertex in graph for key = {} and value = {} label = {}", name, value, label);
+ logger.debug("No vertex in graph for key =" + name + " and value = " + value + " label = " + 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);
+ 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());
+ logger.debug("No vertex in graph for key ={} and value = {} label = {} error : {}",name,value,label,graph.right().value());
}
return Either.right(graph.right().value());
}
@@ -847,75 +884,6 @@ public class TitanGenericDao {
}
}
- // public <T extends GraphNode> Either<List<T>, TitanOperationStatus>
- // getByCriteria_tx(NodeTypeEnum type, Map<String, Object> props, Class<T>
- // clazz) {
- // Either<TitanGraph, TitanOperationStatus> graph = titanClient.getGraph();
- // TitanTransaction tx=null;
- // if (graph.isLeft()) {
- // try {
- // TitanGraph tGraph = graph.left().value();
- // tx = tGraph.newTransaction();
- //
- // TitanGraphQuery<? extends TitanGraphQuery> query = tx.query();
- // query = query.has(GraphPropertiesDictionary.LABEL.getProperty(),
- // type.getName());
- //
- // if (props != null && !props.isEmpty()) {
- // for (Map.Entry<String, Object> entry : props.entrySet()) {
- // query = query.has(entry.getKey(), entry.getValue());
- // }
- // }
- // Iterable<TitanVertex> vertices = query.vertices();
- // if (vertices == null) {
- // tx.commit();
- // return Either.right(TitanOperationStatus.NOT_FOUND);
- // }
- //
- //
- // Iterator<TitanVertex> iterator = vertices.iterator();
- // List<T> result = new ArrayList<T>();
- //
- // while (iterator.hasNext()) {
- // Vertex vertex = iterator.next();
- //
- // Map<String, Object> newProp = getProperties(vertex);
- //
- // T element = GraphElementFactory.createElement(type.getName(),
- // GraphElementTypeEnum.Node, newProp, clazz);
- // result.add(element);
- // }
- // if (logger.isDebugEnabled()) {
- // logger.debug("Number of fetced nodes in graph for criteria : from type ="
- // + type + " and properties = " + props + " is " + result.size());
- // }
- // tx.commit();
- // if (result.size() == 0) {
- // return Either.right(TitanOperationStatus.NOT_FOUND);
- // }
- //
- // return Either.left(result);
- // } catch (Exception e) {
- // if (tx != null)
- // try {
- // tx.commit();
- // } catch (Exception e1) {
- // logger.debug("failed to commit after get", 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 boolean vertexLeftContainsRightProps(Map<String, Object> leftProps, Map<String, Object> rightProps) {
if (rightProps != null) {
@@ -986,14 +954,14 @@ public class TitanGenericDao {
return Either.left(result);
} catch (Exception e) {
if (logger.isDebugEnabled()) {
- logger.debug("Failed get by criteria for type = {} amd properties = {}. error: {}", type, props, e);
+ 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());
+ logger.debug("Failed get by criteria for type = {} and properties = {} error : {}", type, props, graph.right().value());
}
return Either.right(graph.right().value());
}
@@ -1050,7 +1018,7 @@ public class TitanGenericDao {
}
- public TitanOperationStatus updateVertex(GraphNode node, TitanVertex vertex) {
+ public TitanOperationStatus updateVertex(GraphNode node, Vertex vertex) {
logger.debug("Try to update node for {}", node.getKeyValueId());
try {
@@ -1114,19 +1082,19 @@ public class TitanGenericDao {
return Either.left(node);
} else {
if (logger.isDebugEnabled()) {
- logger.debug("Failed to delete node for {} = {}. Missing label property on node", keyName, keyValue);
+ logger.debug("Failed to delete node for {} = {} Missing label property on node", keyName, keyValue);
}
return Either.right(TitanOperationStatus.MISSING_NODE_LABEL);
}
} else {
if (logger.isDebugEnabled()) {
- logger.debug("Failed to delete node for {} = {}. Missing label property on node", keyName, keyValue);
+ logger.debug("Failed to delete node for {} = {} Missing label property on node", keyName, keyValue);
}
return Either.right(TitanOperationStatus.MISSING_NODE_LABEL);
}
} catch (Exception e) {
if (logger.isDebugEnabled()) {
- logger.debug("Failed to delete node for {} = {}. error: {}", keyName, keyValue, e);
+ logger.debug("Failed to delete node for {} = {}", keyName, keyValue, e);
}
return Either.right(TitanGraphClient.handleTitanException(e));
}
@@ -1173,20 +1141,20 @@ public class TitanGenericDao {
;
} else {
if (logger.isDebugEnabled()) {
- logger.debug("Failed to delete relation {} from {} to {}. error: {}", type, fromKeyId, toKeyId, graph.right().value());
+ logger.debug("Failed to delete relation {} from {} to {} error : {}",type,fromKeyId,toKeyId,graph.right().value());
}
return Either.right(graph.right().value());
}
return Either.left(newRelation);
} catch (Exception e) {
if (logger.isDebugEnabled()) {
- logger.debug("Failed to delete relation {} from {} to {}. error: {}", type, fromKeyId, toKeyId, e);
+ logger.debug("Failed to delete relation {} from {} to {}", type, fromKeyId, toKeyId, e);
}
return Either.right(TitanGraphClient.handleTitanException(e));
}
} else {
if (logger.isDebugEnabled()) {
- logger.debug("Failed to delete relation {} from {} to {}. error: {}", type, fromKeyId, toKeyId, edgeS.right().value());
+ logger.debug("Failed to delete relation {} from {} to {} error : {}", type, fromKeyId, toKeyId, edgeS.right().value());
}
return Either.right(edgeS.right().value());
}
@@ -1624,7 +1592,7 @@ public class TitanGenericDao {
Either<Edge, TitanOperationStatus> outgoingEdgeByCriteria = getOutgoingEdgeByCriteria(key, uniqueId, edgeType, edgeProperties);
if (outgoingEdgeByCriteria.isRight()) {
TitanOperationStatus status = outgoingEdgeByCriteria.right().value();
- logger.debug("Cannot find outgoing edge from vertex {} with label {} and properties {}", uniqueId, edgeType, edgeProperties);
+ logger.debug("Cannot find outgoing edge from vertex {} with label {} and properties {}" + uniqueId, edgeType, edgeProperties);
return Either.right(status);
}
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 68a05a91bf..07030472a4 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
@@ -42,6 +42,8 @@ import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.dao.DAOTitanStrategy;
+import org.openecomp.sdc.be.dao.TitanClientStrategy;
import org.openecomp.sdc.be.dao.graph.datatype.ActionEnum;
import org.openecomp.sdc.be.dao.graph.datatype.GraphElementTypeEnum;
import org.openecomp.sdc.be.dao.neo4j.GraphEdgePropertiesDictionary;
@@ -76,9 +78,9 @@ 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;
+
@Component("titan-client")
public class TitanGraphClient {
@@ -88,6 +90,9 @@ public class TitanGraphClient {
private static final String HEALTH_CHECK = GraphPropertiesDictionary.HEALTH_CHECK.getProperty();
private static final String OK = "GOOD";
+ public TitanGraphClient() {
+ }
+
private class HealthCheckTask implements Callable<Vertex> {
@Override
public Vertex call() {
@@ -126,7 +131,7 @@ public class TitanGraphClient {
public void run() {
logger.trace("Trying to reconnect to Titan...");
if (graph == null) {
- createGraph(titanCfgFile, true);
+ createGraph(titanCfgFile);
}
}
}
@@ -136,8 +141,7 @@ public class TitanGraphClient {
// Health Check Variables
/**
- * This executor will execute the health check task on a callable task that
- * can be executed with a timeout.
+ * This executor will execute the health check task on a callable task that can be executed with a timeout.
*/
ExecutorService healthCheckExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() {
@Override
@@ -159,9 +163,11 @@ public class TitanGraphClient {
private Future reconnectFuture;
private String titanCfgFile = null;
+ TitanClientStrategy titanClientStrategy;
- public TitanGraphClient() {
+ public TitanGraphClient(TitanClientStrategy titanClientStrategy) {
super();
+ this.titanClientStrategy = titanClientStrategy;
// Initialize a single threaded scheduler for health-check
this.healthCheckScheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
@@ -171,10 +177,8 @@ public class TitanGraphClient {
}
});
- healthCheckReadTimeout = ConfigurationManager.getConfigurationManager().getConfiguration()
- .getTitanHealthCheckReadTimeout(2);
- reconnectInterval = ConfigurationManager.getConfigurationManager().getConfiguration()
- .getTitanReconnectIntervalInSeconds(3);
+ healthCheckReadTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getTitanHealthCheckReadTimeout(2);
+ reconnectInterval = ConfigurationManager.getConfigurationManager().getConfiguration().getTitanReconnectIntervalInSeconds(3);
logger.info("** TitanGraphClient created");
}
@@ -188,13 +192,11 @@ public class TitanGraphClient {
BaseConfiguration conf = new BaseConfiguration();
conf.setProperty("storage.backend", "inmemory");
graph = TitanFactory.open(conf);
-
- createIndexesAndDefaults();
-
+ createTitanSchema();
logger.info("** in memory graph created");
return TitanOperationStatus.OK;
} else {
- this.titanCfgFile = ConfigurationManager.getConfigurationManager().getConfiguration().getTitanCfgFile();
+ this.titanCfgFile = titanClientStrategy.getConfigFile();
if (titanCfgFile == null || titanCfgFile.isEmpty()) {
titanCfgFile = "config/titan.properties";
}
@@ -217,8 +219,7 @@ public class TitanGraphClient {
}
/**
- * This method will be invoked ONLY on init time in case Titan storage is
- * down.
+ * This method will be invoked ONLY on init time in case Titan storage is down.
*/
private void startReconnectTask() {
this.reconnectTask = new ReconnectTask();
@@ -231,8 +232,7 @@ public class TitanGraphClient {
});
logger.info("Scheduling reconnect task {} with interval of {} seconds", reconnectTask, reconnectInterval);
- reconnectFuture = this.reconnectScheduler.scheduleAtFixedRate(this.reconnectTask, 0, this.reconnectInterval,
- TimeUnit.SECONDS);
+ reconnectFuture = this.reconnectScheduler.scheduleAtFixedRate(this.reconnectTask, 0, this.reconnectInterval, TimeUnit.SECONDS);
}
public void cleanupGraph() {
@@ -243,29 +243,28 @@ public class TitanGraphClient {
}
}
- public TitanOperationStatus createGraph(String titanCfgFile) {
- logger.info("** createGraph with " + titanCfgFile + " started");
- return createGraph(titanCfgFile, true);
+ private boolean graphInitialized(){
+ TitanManagement graphMgmt = graph.openManagement();
+ return graphMgmt.containsPropertyKey(HEALTH_CHECK) && graphMgmt.containsGraphIndex(HEALTH_CHECK);
}
+
- public TitanOperationStatus createGraph(String titanCfgFile, boolean initializeGraph) {
- logger.info("** createGraph with " + titanCfgFile + " and initializeGraph=" + initializeGraph + " started");
+ public TitanOperationStatus createGraph(String titanCfgFile) {
+ logger.info("** open graph with {} started", titanCfgFile);
try {
- logger.info("createGraph : try to load file " + titanCfgFile);
+ logger.info("openGraph : try to load file {}", titanCfgFile);
graph = TitanFactory.open(titanCfgFile);
- if (graph == null) {
+ if (graph.isClosed() || !graphInitialized()) {
+ logger.error("titan graph was not initialized");
return TitanOperationStatus.NOT_CREATED;
}
} catch (Exception e) {
this.graph = null;
- logger.info("createGraph : failed to open Titan graph with configuration file: " + titanCfgFile);
- logger.trace("createGraph : failed to open Titan graph. ", e);
+ logger.info("createGraph : failed to open Titan graph with configuration file: {}", titanCfgFile, e);
return TitanOperationStatus.NOT_CONNECTED;
}
- if (true == initializeGraph) {
- createIndexesAndDefaults();
- }
+
logger.info("** Titan graph created ");
// Do some post creation actions
@@ -294,12 +293,6 @@ public class TitanGraphClient {
this.startHealthCheckTask();
}
- private void createIndexesAndDefaults() {
- createVertexIndixes();
- createEdgeIndixes();
- createDefaultUsers();
- // createCategories();
- }
public Either<TitanGraph, TitanOperationStatus> getGraph() {
if (graph != null) {
@@ -309,76 +302,6 @@ public class TitanGraphClient {
}
}
- private TitanOperationStatus createVertexIndixes() {
- logger.info("** createVertexIndixes started");
- if (graph != null) {
- // TitanManagement graphMgt = graph.getManagementSystem();
- 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");
- return TitanOperationStatus.OK;
- }
- logger.info("** createVertexIndixes ended, no Indixes were created.");
- return TitanOperationStatus.NOT_CREATED;
- }
-
- private TitanOperationStatus createEdgeIndixes() {
- logger.info("** createEdgeIndixes started");
- if (graph != null) {
- // TitanManagement graphMgt = graph.getManagementSystem();
- 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");
- return TitanOperationStatus.OK;
- }
- logger.info("** createEdgeIndixes ended, no Indixes were created.");
- return TitanOperationStatus.NOT_CREATED;
- }
-
public TitanOperationStatus commit() {
if (graph != null) {
try {
@@ -450,14 +373,14 @@ public class TitanGraphClient {
try {
Future<Vertex> future = healthCheckExecutor.submit(healthCallableTask);
v = future.get(this.healthCheckReadTimeout, TimeUnit.SECONDS);
- healthLogger.trace("Health Check Node Found... " + v.property(HEALTH_CHECK));
+ healthLogger.trace("Health Check Node Found... {}", v.property(HEALTH_CHECK));
graph.tx().commit();
} catch (Exception e) {
String message = e.getMessage();
if (message == null) {
message = e.getClass().getName();
}
- logger.error("Titan Health Check Failed. " + message);
+ logger.error("Titan Health Check Failed. {}", message);
return false;
}
return true;
@@ -466,386 +389,9 @@ public class TitanGraphClient {
}
}
- private TitanOperationStatus createCategories() {
- logger.info("** createCategories started");
- if (graph != null) {
- try {
- List<CategoryData> categoryDataList = getDefaultResourceCategoryList();
- generateGraphCategories(categoryDataList, NodeTypeEnum.ResourceCategory.getName());
- } catch (Exception e) {
- logger.error("createCategories : failed to load categories ", e);
- rollback();
- return TitanOperationStatus.GENERAL_ERROR;
- } finally {
- logger.info("** createCategories ended");
- commit();
- }
- }
- return TitanOperationStatus.OK;
- }
-
- private void generateGraphCategories(List<CategoryData> categoryDataList, String label) {
- for (CategoryData categoryData : categoryDataList) {
- Map<String, Object> properties = categoryData.toGraphMap();
- properties.put(GraphPropertiesDictionary.LABEL.getProperty(), label);
-
- // This is temporary for old mechnism of categories - they don;t
- // have the norm name
- properties.remove(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty());
-
- if (isVertexExist(properties)) {
- return;
- }
-
- Vertex vertex = graph.addVertex();
- for (Map.Entry<String, Object> entry : properties.entrySet()) {
- vertex.property(entry.getKey(), entry.getValue());
- }
- }
- }
-
- private List<CategoryData> getDefaultResourceCategoryList() {
- Map<String, List<String>> categories = new HashMap<String, List<String>>();
- categories.put("Network Layer 2-3", Arrays.asList("Router", "Gateway", "WAN Connectors", "LAN Connectors"));
- categories.put("Network Layer 4+", Arrays.asList("Common Network Resources"));
- categories.put("Application Layer 4+", Arrays.asList("Border Elements", "Application Servers", "Web Server",
- "Call Control", "Media Servers", "Load Balancer", "Database"));
- categories.put("Generic", Arrays.asList("Infrastructure", "Abstract", "Network Elements", "Database"));
-
- List<CategoryData> categoryDataList = new ArrayList<CategoryData>();
- CategoryData categoryData = null;
- for (Map.Entry<String, List<String>> entryList : categories.entrySet()) {
- for (String val : entryList.getValue()) {
- categoryData = new ResourceCategoryData(entryList.getKey(), val);
- categoryData.setAction(ActionEnum.Create);
- categoryData.setElementType(GraphElementTypeEnum.Node);
- // categoryData.setCategoryName();
- // categoryData.setName();
- categoryDataList.add(categoryData);
- }
- }
- return categoryDataList;
- }
-
- private List<CategoryData> getDefaultServiceCategoryList() {
- List<String> categories = new ArrayList<>();
- categories.add("Mobility");
- categories.add("Network L1-3");
- categories.add("Network L4");
- categories.add("VoIP Call Control");
-
- List<CategoryData> categoryDataList = new ArrayList<CategoryData>();
- CategoryData categoryData = null;
- for (String category : categories) {
- categoryData = new ServiceCategoryData(category);
- categoryData.setAction(ActionEnum.Create);
- categoryData.setElementType(GraphElementTypeEnum.Node);
- // categoryData.setCategoryName(entryList.getKey());
- // categoryData.setName(val);
- categoryDataList.add(categoryData);
- }
- return categoryDataList;
- }
-
- private void createDefaultUsers() {
- if (graph != null) {
- List<UserData> users = createUserList();
- for (UserData user : users) {
- String propertyName = GraphPropertiesDictionary.USER_ID.getProperty();
- String propertyValue = user.getUserId();
- Vertex vertex = null;
- Map<String, Object> properties = null;
- if (!isVertexExist(propertyName, propertyValue)) {
- 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());
- }
- }
- }
- graph.tx().commit();
- }
- }
-
- private List<UserData> createUserList() {
- LinkedList<UserData> users = new LinkedList<UserData>();
- users.add(getDefaultUserAdmin1());
- users.add(getDefaultUserAdmin2());
- users.add(getDefaultUserAdmin3());
- users.add(getDefaultUserDesigner1());
- users.add(getDefaultUserDesigner2());
- users.add(getDefaultUserDesigner3());
- users.add(getDefaultUserTester1());
- users.add(getDefaultUserTester2());
- users.add(getDefaultUserTester3());
- users.add(getDefaultUserGovernor1());
- users.add(getDefaultUserOps1());
- users.add(getDefaultUserProductManager1());
- users.add(getDefaultUserProductManager2());
- users.add(getDefaultUserProductStrategist1());
- users.add(getDefaultUserProductStrategist2());
- users.add(getDefaultUserProductStrategist3());
- return users;
- }
-
- private boolean isVertexExist(String propertyName, String propertyValue) {
- // Iterable<Vertex> vertecies = graph.getVertices(propertyName,
- // propertyValue);
- // java.util.Iterator<Vertex> iterator = vertecies.iterator();
-
- @SuppressWarnings("unchecked")
- Iterable<TitanVertex> vertecies = graph.query().has(HEALTH_CHECK, OK).vertices();
-
- java.util.Iterator<TitanVertex> iterator = vertecies.iterator();
- if (iterator.hasNext()) {
- return true;
- }
- return false;
- }
-
- private 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 UserData getDefaultUserAdmin1() {
- 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 UserData getDefaultUserAdmin2() {
- UserData userData = new UserData();
- userData.setAction(ActionEnum.Create);
- userData.setElementType(GraphElementTypeEnum.Node);
- userData.setUserId("tr0001");
- userData.setEmail("admin@sdc.com");
- userData.setFirstName("Todd");
- userData.setLastName("Rundgren");
- userData.setRole("ADMIN");
- userData.setStatus(UserStatusEnum.ACTIVE.name());
- userData.setLastLoginTime(0L);
- return userData;
- }
-
- private UserData getDefaultUserAdmin3() {
- UserData userData = new UserData();
- userData.setAction(ActionEnum.Create);
- userData.setElementType(GraphElementTypeEnum.Node);
- userData.setUserId("ah0002");
- userData.setEmail("admin@sdc.com");
- userData.setFirstName("Alex");
- userData.setLastName("Harvey");
- userData.setRole("ADMIN");
- userData.setStatus(UserStatusEnum.ACTIVE.name());
- userData.setLastLoginTime(0L);
- return userData;
- }
-
- private UserData getDefaultUserDesigner1() {
- UserData userData = new UserData();
- userData.setAction(ActionEnum.Create);
- userData.setElementType(GraphElementTypeEnum.Node);
- userData.setUserId("cs0008");
- userData.setEmail("designer@sdc.com");
- userData.setFirstName("Carlos");
- userData.setLastName("Santana");
- userData.setRole("DESIGNER");
- userData.setStatus(UserStatusEnum.ACTIVE.name());
- userData.setLastLoginTime(0L);
- return userData;
- }
-
- private UserData getDefaultUserDesigner2() {
- UserData userData = new UserData();
- userData.setAction(ActionEnum.Create);
- userData.setElementType(GraphElementTypeEnum.Node);
- userData.setUserId("me0009");
- userData.setEmail("designer@sdc.com");
- userData.setFirstName("Melissa");
- userData.setLastName("Etheridge");
- userData.setRole("DESIGNER");
- userData.setStatus(UserStatusEnum.ACTIVE.name());
- userData.setLastLoginTime(0L);
- return userData;
- }
-
- private UserData getDefaultUserDesigner3() {
- UserData userData = new UserData();
- userData.setAction(ActionEnum.Create);
- userData.setElementType(GraphElementTypeEnum.Node);
- userData.setUserId("af0006");
- userData.setEmail("designer@sdc.com");
- userData.setFirstName("Aretha");
- userData.setLastName("Franklin");
- userData.setRole("DESIGNER");
- userData.setStatus(UserStatusEnum.ACTIVE.name());
- userData.setLastLoginTime(0L);
- return userData;
- }
-
- private UserData getDefaultUserTester1() {
- UserData userData = new UserData();
- userData.setAction(ActionEnum.Create);
- userData.setElementType(GraphElementTypeEnum.Node);
- userData.setUserId("jm0007");
- userData.setEmail("tester@sdc.com");
- userData.setFirstName("Joni");
- userData.setLastName("Mitchell");
- userData.setRole("TESTER");
- userData.setStatus(UserStatusEnum.ACTIVE.name());
- userData.setLastLoginTime(0L);
- return userData;
- }
-
- private UserData getDefaultUserTester2() {
- UserData userData = new UserData();
- userData.setAction(ActionEnum.Create);
- userData.setElementType(GraphElementTypeEnum.Node);
- userData.setUserId("kb0004");
- userData.setEmail("tester@sdc.com");
- userData.setFirstName("Kate");
- userData.setLastName("Bush");
- userData.setRole("TESTER");
- userData.setStatus(UserStatusEnum.ACTIVE.name());
- userData.setLastLoginTime(0L);
- return userData;
- }
-
- private UserData getDefaultUserTester3() {
- UserData userData = new UserData();
- userData.setAction(ActionEnum.Create);
- userData.setElementType(GraphElementTypeEnum.Node);
- userData.setUserId("jt0005");
- userData.setEmail("tester@sdc.com");
- userData.setFirstName("James");
- userData.setLastName("Taylor");
- userData.setRole("TESTER");
- userData.setStatus(UserStatusEnum.ACTIVE.name());
- userData.setLastLoginTime(0L);
- return userData;
- }
-
- private UserData getDefaultUserOps1() {
- UserData userData = new UserData();
- userData.setAction(ActionEnum.Create);
- userData.setElementType(GraphElementTypeEnum.Node);
- userData.setUserId("op0001");
- userData.setEmail("ops@sdc.com");
- userData.setFirstName("Steve");
- userData.setLastName("Regev");
- userData.setRole("OPS");
- userData.setStatus(UserStatusEnum.ACTIVE.name());
- userData.setLastLoginTime(0L);
- return userData;
- }
-
- private UserData getDefaultUserGovernor1() {
- UserData userData = new UserData();
- userData.setAction(ActionEnum.Create);
- userData.setElementType(GraphElementTypeEnum.Node);
- userData.setUserId("gv0001");
- userData.setEmail("governor@sdc.com");
- userData.setFirstName("David");
- userData.setLastName("Shadmi");
- userData.setRole("GOVERNOR");
- userData.setStatus(UserStatusEnum.ACTIVE.name());
- userData.setLastLoginTime(0L);
- return userData;
- }
-
- private UserData getDefaultUserProductManager1() {
- UserData userData = new UserData();
- userData.setAction(ActionEnum.Create);
- userData.setElementType(GraphElementTypeEnum.Node);
- userData.setUserId("pm0001");
- userData.setEmail("pm1@sdc.com");
- userData.setFirstName("Teddy");
- userData.setLastName("Isashar");
- userData.setRole("PRODUCT_MANAGER");
- userData.setStatus(UserStatusEnum.ACTIVE.name());
- userData.setLastLoginTime(0L);
- return userData;
- }
-
- private UserData getDefaultUserProductManager2() {
- UserData userData = new UserData();
- userData.setAction(ActionEnum.Create);
- userData.setElementType(GraphElementTypeEnum.Node);
- userData.setUserId("pm0002");
- userData.setEmail("pm2@sdc.com");
- userData.setFirstName("Sarah");
- userData.setLastName("Bettens");
- userData.setRole("PRODUCT_MANAGER");
- userData.setStatus(UserStatusEnum.ACTIVE.name());
- userData.setLastLoginTime(0L);
- return userData;
- }
-
- private UserData getDefaultUserProductStrategist1() {
- UserData userData = new UserData();
- userData.setAction(ActionEnum.Create);
- userData.setElementType(GraphElementTypeEnum.Node);
- userData.setUserId("ps0001");
- userData.setEmail("ps1@sdc.com");
- userData.setFirstName("Eden");
- userData.setLastName("Rozin");
- userData.setRole("PRODUCT_STRATEGIST");
- userData.setStatus(UserStatusEnum.ACTIVE.name());
- userData.setLastLoginTime(0L);
- return userData;
- }
-
- private UserData getDefaultUserProductStrategist2() {
- UserData userData = new UserData();
- userData.setAction(ActionEnum.Create);
- userData.setElementType(GraphElementTypeEnum.Node);
- userData.setUserId("ps0002");
- userData.setEmail("ps2@sdc.com");
- userData.setFirstName("Ella");
- userData.setLastName("Kvetny");
- userData.setRole("PRODUCT_STRATEGIST");
- userData.setStatus(UserStatusEnum.ACTIVE.name());
- userData.setLastLoginTime(0L);
- return userData;
- }
-
- private UserData getDefaultUserProductStrategist3() {
- UserData userData = new UserData();
- userData.setAction(ActionEnum.Create);
- userData.setElementType(GraphElementTypeEnum.Node);
- userData.setUserId("ps0003");
- userData.setEmail("ps3@sdc.com");
- userData.setFirstName("Geva");
- userData.setLastName("Alon");
- userData.setRole("PRODUCT_STRATEGIST");
- userData.setStatus(UserStatusEnum.ACTIVE.name());
- userData.setLastLoginTime(0L);
- return userData;
- }
public static void main(String[] args) throws InterruptedException {
- TitanGraphClient client = new TitanGraphClient();
+ TitanGraphClient client = new TitanGraphClient(new DAOTitanStrategy());
client.createGraph();
while (true) {
@@ -856,17 +402,58 @@ public class TitanGraphClient {
}
+
private static final String TITAN_HEALTH_CHECK_STR = "titanHealthCheck";
private void logAlarm() {
if (lastHealthState == true) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeHealthCheckRecovery,
- TITAN_HEALTH_CHECK_STR);
+ 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().processEcompError(EcompErrorName.BeHealthCheckError, TITAN_HEALTH_CHECK_STR);
BeEcompErrorManager.getInstance().logBeHealthCheckTitanError(TITAN_HEALTH_CHECK_STR);
}
}
+
+ private void createTitanSchema() {
+
+ TitanManagement graphMgt = graph.openManagement();
+ TitanGraphIndex index = null;
+ for (GraphPropertiesDictionary prop : GraphPropertiesDictionary.values()) {
+ PropertyKey propKey = null;
+ if (!graphMgt.containsPropertyKey(prop.getProperty())) {
+ Class<?> clazz = prop.getClazz();
+ if (!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-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 e4da028c60..84d9663e59 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
@@ -51,56 +51,34 @@ public class ArtifactData extends GraphNode {
public ArtifactData(Map<String, Object> properties) {
this();
artifactDataDefinition.setUniqueId((String) properties.get(GraphPropertiesDictionary.UNIQUE_ID.getProperty()));
- artifactDataDefinition
- .setArtifactType((String) properties.get(GraphPropertiesDictionary.ARTIFACT_TYPE.getProperty()));
- artifactDataDefinition
- .setArtifactRef((String) properties.get(GraphPropertiesDictionary.ARTIFACT_REF.getProperty()));
+ artifactDataDefinition.setArtifactType((String) properties.get(GraphPropertiesDictionary.ARTIFACT_TYPE.getProperty()));
+ artifactDataDefinition.setArtifactRef((String) properties.get(GraphPropertiesDictionary.ARTIFACT_REF.getProperty()));
artifactDataDefinition.setArtifactName((String) properties.get(GraphPropertiesDictionary.NAME.getProperty()));
- artifactDataDefinition.setArtifactRepository(
- (String) properties.get(GraphPropertiesDictionary.ARTIFACT_REPOSITORY.getProperty()));
- artifactDataDefinition.setArtifactChecksum(
- (String) properties.get(GraphPropertiesDictionary.ARTIFACT_CHECKSUM.getProperty()));
- artifactDataDefinition
- .setArtifactCreator((String) properties.get(GraphPropertiesDictionary.CREATOR.getProperty()));
- artifactDataDefinition
- .setUserIdCreator((String) properties.get(GraphPropertiesDictionary.ATT_CREATOR.getProperty()));
- artifactDataDefinition
- .setUserIdLastUpdater((String) properties.get(GraphPropertiesDictionary.LAST_UPDATER.getProperty()));
- artifactDataDefinition
- .setCreatorFullName((String) properties.get(GraphPropertiesDictionary.CREATOR_FULL_NAME.getProperty()));
- artifactDataDefinition
- .setUpdaterFullName((String) properties.get(GraphPropertiesDictionary.UPDATER_FULL_NAME.getProperty()));
- artifactDataDefinition
- .setCreationDate((Long) properties.get(GraphPropertiesDictionary.CREATION_DATE.getProperty()));
- artifactDataDefinition
- .setLastUpdateDate((Long) properties.get(GraphPropertiesDictionary.LAST_UPDATE_DATE.getProperty()));
- artifactDataDefinition
- .setDescription((String) properties.get(GraphPropertiesDictionary.DESCRIPTION.getProperty()));
+ artifactDataDefinition.setArtifactRepository((String) properties.get(GraphPropertiesDictionary.ARTIFACT_REPOSITORY.getProperty()));
+ artifactDataDefinition.setArtifactChecksum((String) properties.get(GraphPropertiesDictionary.ARTIFACT_CHECKSUM.getProperty()));
+ artifactDataDefinition.setArtifactCreator((String) properties.get(GraphPropertiesDictionary.CREATOR.getProperty()));
+ artifactDataDefinition.setUserIdCreator((String) properties.get(GraphPropertiesDictionary.CREATOR_ID.getProperty()));
+ artifactDataDefinition.setUserIdLastUpdater((String) properties.get(GraphPropertiesDictionary.LAST_UPDATER.getProperty()));
+ artifactDataDefinition.setCreatorFullName((String) properties.get(GraphPropertiesDictionary.CREATOR_FULL_NAME.getProperty()));
+ artifactDataDefinition.setUpdaterFullName((String) properties.get(GraphPropertiesDictionary.UPDATER_FULL_NAME.getProperty()));
+ artifactDataDefinition.setCreationDate((Long) properties.get(GraphPropertiesDictionary.CREATION_DATE.getProperty()));
+ artifactDataDefinition.setLastUpdateDate((Long) properties.get(GraphPropertiesDictionary.LAST_UPDATE_DATE.getProperty()));
+ artifactDataDefinition.setDescription((String) properties.get(GraphPropertiesDictionary.DESCRIPTION.getProperty()));
artifactDataDefinition.setEsId((String) properties.get(GraphPropertiesDictionary.ES_ID.getProperty()));
- artifactDataDefinition
- .setArtifactLabel((String) properties.get(GraphPropertiesDictionary.ARTIFACT_LABEL.getProperty()));
- artifactDataDefinition
- .setMandatory((Boolean) properties.get(GraphPropertiesDictionary.IS_ABSTRACT.getProperty()));
- artifactDataDefinition.setArtifactChecksum(
- (String) properties.get(GraphPropertiesDictionary.ARTIFACT_CHECKSUM.getProperty()));
- artifactDataDefinition.setArtifactDisplayName(
- (String) properties.get(GraphPropertiesDictionary.ARTIFACT_DISPLAY_NAME.getProperty()));
+ artifactDataDefinition.setArtifactLabel((String) properties.get(GraphPropertiesDictionary.ARTIFACT_LABEL.getProperty()));
+ artifactDataDefinition.setMandatory((Boolean) properties.get(GraphPropertiesDictionary.IS_ABSTRACT.getProperty()));
+ artifactDataDefinition.setArtifactChecksum((String) properties.get(GraphPropertiesDictionary.ARTIFACT_CHECKSUM.getProperty()));
+ artifactDataDefinition.setArtifactDisplayName((String) properties.get(GraphPropertiesDictionary.ARTIFACT_DISPLAY_NAME.getProperty()));
artifactDataDefinition.setApiUrl((String) properties.get(GraphPropertiesDictionary.API_URL.getProperty()));
- artifactDataDefinition
- .setServiceApi((Boolean) properties.get(GraphPropertiesDictionary.SERVICE_API.getProperty()));
- artifactDataDefinition
- .setArtifactVersion((String) properties.get(GraphPropertiesDictionary.ARTIFACT_VERSION.getProperty()));
- artifactDataDefinition
- .setArtifactUUID((String) properties.get(GraphPropertiesDictionary.ARTIFACT_UUID.getProperty()));
- artifactDataDefinition.setPayloadUpdateDate(
- (Long) properties.get(GraphPropertiesDictionary.PAYLOAD_UPDATE_DATE.getProperty()));
- artifactDataDefinition.setHeatParamsUpdateDate(
- (Long) properties.get(GraphPropertiesDictionary.HEAT_PARAMS_UPDATE_DATE.getProperty()));
+ artifactDataDefinition.setServiceApi((Boolean) properties.get(GraphPropertiesDictionary.SERVICE_API.getProperty()));
+ artifactDataDefinition.setArtifactVersion((String) properties.get(GraphPropertiesDictionary.ARTIFACT_VERSION.getProperty()));
+ artifactDataDefinition.setArtifactUUID((String) properties.get(GraphPropertiesDictionary.ARTIFACT_UUID.getProperty()));
+ artifactDataDefinition.setPayloadUpdateDate((Long) properties.get(GraphPropertiesDictionary.PAYLOAD_UPDATE_DATE.getProperty()));
+ artifactDataDefinition.setHeatParamsUpdateDate((Long) properties.get(GraphPropertiesDictionary.HEAT_PARAMS_UPDATE_DATE.getProperty()));
artifactDataDefinition.setGenerated((Boolean) properties.get(GraphPropertiesDictionary.GENERATED.getProperty()));
Type listType = new TypeToken<List<String>>() {
}.getType();
- List<String> requiredArtifactsfromJson = getGson().fromJson(
- (String) properties.get(GraphPropertiesDictionary.REQUIRED_ARTIFACTS.getProperty()), listType);
+ List<String> requiredArtifactsfromJson = getGson().fromJson((String) properties.get(GraphPropertiesDictionary.REQUIRED_ARTIFACTS.getProperty()), listType);
artifactDataDefinition.setRequiredArtifacts(requiredArtifactsfromJson);
String groupType = (String) properties.get(GraphPropertiesDictionary.ARTIFACT_GROUP_TYPE.getProperty());
@@ -141,7 +119,7 @@ public class ArtifactData extends GraphNode {
addIfExists(map, GraphPropertiesDictionary.ARTIFACT_REPOSITORY, artifactDataDefinition.getArtifactRepository());
addIfExists(map, GraphPropertiesDictionary.ARTIFACT_CHECKSUM, artifactDataDefinition.getArtifactChecksum());
addIfExists(map, GraphPropertiesDictionary.CREATOR, artifactDataDefinition.getArtifactCreator());
- addIfExists(map, GraphPropertiesDictionary.ATT_CREATOR, artifactDataDefinition.getUserIdCreator());
+ addIfExists(map, GraphPropertiesDictionary.CREATOR_ID, artifactDataDefinition.getUserIdCreator());
addIfExists(map, GraphPropertiesDictionary.LAST_UPDATER, artifactDataDefinition.getUserIdLastUpdater());
addIfExists(map, GraphPropertiesDictionary.CREATOR_FULL_NAME, artifactDataDefinition.getCreatorFullName());
addIfExists(map, GraphPropertiesDictionary.UPDATER_FULL_NAME, artifactDataDefinition.getUpdaterFullName());
@@ -152,16 +130,14 @@ public class ArtifactData extends GraphNode {
addIfExists(map, GraphPropertiesDictionary.ARTIFACT_LABEL, artifactDataDefinition.getArtifactLabel());
addIfExists(map, GraphPropertiesDictionary.IS_ABSTRACT, artifactDataDefinition.getMandatory());
addIfExists(map, GraphPropertiesDictionary.ARTIFACT_CHECKSUM, artifactDataDefinition.getArtifactChecksum());
- addIfExists(map, GraphPropertiesDictionary.ARTIFACT_DISPLAY_NAME,
- artifactDataDefinition.getArtifactDisplayName());
+ addIfExists(map, GraphPropertiesDictionary.ARTIFACT_DISPLAY_NAME, artifactDataDefinition.getArtifactDisplayName());
addIfExists(map, GraphPropertiesDictionary.API_URL, artifactDataDefinition.getApiUrl());
addIfExists(map, GraphPropertiesDictionary.SERVICE_API, artifactDataDefinition.getServiceApi());
addIfExists(map, GraphPropertiesDictionary.ARTIFACT_TIMEOUT, artifactDataDefinition.getTimeout());
addIfExists(map, GraphPropertiesDictionary.ARTIFACT_VERSION, artifactDataDefinition.getArtifactVersion());
addIfExists(map, GraphPropertiesDictionary.ARTIFACT_UUID, artifactDataDefinition.getArtifactUUID());
addIfExists(map, GraphPropertiesDictionary.PAYLOAD_UPDATE_DATE, artifactDataDefinition.getPayloadUpdateDate());
- addIfExists(map, GraphPropertiesDictionary.HEAT_PARAMS_UPDATE_DATE,
- artifactDataDefinition.getHeatParamsUpdateDate());
+ addIfExists(map, GraphPropertiesDictionary.HEAT_PARAMS_UPDATE_DATE, artifactDataDefinition.getHeatParamsUpdateDate());
addIfExists(map, GraphPropertiesDictionary.REQUIRED_ARTIFACTS, artifactDataDefinition.getRequiredArtifacts());
addIfExists(map, GraphPropertiesDictionary.GENERATED, artifactDataDefinition.getGenerated());
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 2582475c5c..9f04c56be2 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
@@ -27,13 +27,12 @@ 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.CapabilityDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import com.google.gson.reflect.TypeToken;
public class CapabilityData extends GraphNode {
- public final static String MIN_OCCURRENCES = "1"; // occurrences
- public final static String MAX_OCCURRENCES = "UNBOUNDED";
public CapabilityData() {
super(NodeTypeEnum.Capability);
@@ -74,8 +73,8 @@ public class CapabilityData extends GraphNode {
private Long modificationTime;
- private String minOccurrences = MIN_OCCURRENCES;
- private String maxOccurrences = MAX_OCCURRENCES;
+ private String minOccurrences = CapabilityDataDefinition.MIN_OCCURRENCES;
+ private String maxOccurrences = CapabilityDataDefinition.MAX_OCCURRENCES;
public String getUniqueId() {
return uniqueId;
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ComponentInstanceData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ComponentInstanceData.java
index c61b99a805..b55b208048 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ComponentInstanceData.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ComponentInstanceData.java
@@ -32,15 +32,24 @@ import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
public class ComponentInstanceData extends GraphNode {
ComponentInstanceDataDefinition componentInstDataDefinition;
+ protected Integer groupInstanceCounter;
public ComponentInstanceData() {
super(NodeTypeEnum.ResourceInstance);
this.componentInstDataDefinition = new ComponentInstanceDataDefinition();
+ this.groupInstanceCounter = 0;
}
public ComponentInstanceData(ComponentInstanceDataDefinition componentInstDataDefinition) {
super(NodeTypeEnum.ResourceInstance);
this.componentInstDataDefinition = componentInstDataDefinition;
+ this.groupInstanceCounter = 0;
+ }
+
+ public ComponentInstanceData(ComponentInstanceDataDefinition componentInstDataDefinition, Integer groupInstanceCounter) {
+ super(NodeTypeEnum.ResourceInstance);
+ this.componentInstDataDefinition = componentInstDataDefinition;
+ this.groupInstanceCounter = groupInstanceCounter;
}
public ComponentInstanceData(Map<String, Object> properties) {
@@ -59,6 +68,8 @@ public class ComponentInstanceData extends GraphNode {
componentInstDataDefinition.setAttributeValueCounter((Integer) properties.get(GraphPropertiesDictionary.ATTRIBUTE_COUNTER.getProperty()));
componentInstDataDefinition.setNormalizedName((String) properties.get(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty()));
componentInstDataDefinition.setOriginType(OriginTypeEnum.findByValue((String) properties.get(GraphPropertiesDictionary.ORIGIN_TYPE.getProperty())));
+ componentInstDataDefinition.setCustomizationUUID((String) properties.get(GraphPropertiesDictionary.CUSTOMIZATION_UUID.getProperty()));
+ groupInstanceCounter = (Integer) properties.get(GraphPropertiesDictionary.INSTANCE_COUNTER.getProperty());
}
@Override
@@ -76,10 +87,12 @@ public class ComponentInstanceData extends GraphNode {
addIfExists(map, GraphPropertiesDictionary.NAME, componentInstDataDefinition.getName());
addIfExists(map, GraphPropertiesDictionary.PROPERTY_COUNTER, componentInstDataDefinition.getPropertyValueCounter());
addIfExists(map, GraphPropertiesDictionary.ATTRIBUTE_COUNTER, componentInstDataDefinition.getAttributeValueCounter());
+ addIfExists(map, GraphPropertiesDictionary.INSTANCE_COUNTER, groupInstanceCounter);
addIfExists(map, GraphPropertiesDictionary.NORMALIZED_NAME, componentInstDataDefinition.getNormalizedName());
if (componentInstDataDefinition.getOriginType() != null) {
addIfExists(map, GraphPropertiesDictionary.ORIGIN_TYPE, componentInstDataDefinition.getOriginType().getValue());
}
+ addIfExists(map, GraphPropertiesDictionary.CUSTOMIZATION_UUID, componentInstDataDefinition.getCustomizationUUID());
return map;
}
@@ -111,4 +124,16 @@ public class ComponentInstanceData extends GraphNode {
return "ComponentInstanceData [componentInstDataDefinition=" + componentInstDataDefinition + "]";
}
+ public Integer getGroupInstanceCounter() {
+ return groupInstanceCounter;
+ }
+
+ public void setGroupInstanceCounter(Integer componentInstanceCounter) {
+ this.groupInstanceCounter = componentInstanceCounter;
+ }
+
+ public Integer increaseAndGetGroupInstanceCounter() {
+ return ++groupInstanceCounter;
+ }
+
}
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 e39dfe226f..0ad081832f 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
@@ -28,6 +28,8 @@ 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.components.ComponentMetadataDataDefinition;
+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 com.google.gson.reflect.TypeToken;
@@ -43,44 +45,37 @@ public abstract class ComponentMetadataData extends GraphNode {
this.componentInstanceCounter = 0;
}
- public ComponentMetadataData(NodeTypeEnum label, ComponentMetadataDataDefinition metadataDataDefinition,
- Map<String, Object> properties) {
+ @SuppressWarnings("unchecked")
+ public ComponentMetadataData(NodeTypeEnum label, ComponentMetadataDataDefinition metadataDataDefinition, Map<String, Object> properties) {
this(label, metadataDataDefinition);
metadataDataDefinition.setUniqueId((String) properties.get(GraphPropertiesDictionary.UNIQUE_ID.getProperty()));
- metadataDataDefinition
- .setCreationDate((Long) properties.get(GraphPropertiesDictionary.CREATION_DATE.getProperty()));
- metadataDataDefinition
- .setDescription((String) properties.get(GraphPropertiesDictionary.DESCRIPTION.getProperty()));
+ metadataDataDefinition.setCreationDate((Long) properties.get(GraphPropertiesDictionary.CREATION_DATE.getProperty()));
+ metadataDataDefinition.setDescription((String) properties.get(GraphPropertiesDictionary.DESCRIPTION.getProperty()));
metadataDataDefinition.setIcon((String) properties.get(GraphPropertiesDictionary.ICON.getProperty()));
- metadataDataDefinition.setHighestVersion(
- (Boolean) properties.get(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty()));
- metadataDataDefinition
- .setLastUpdateDate((Long) properties.get(GraphPropertiesDictionary.LAST_UPDATE_DATE.getProperty()));
+ metadataDataDefinition.setHighestVersion((Boolean) properties.get(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty()));
+ metadataDataDefinition.setLastUpdateDate((Long) properties.get(GraphPropertiesDictionary.LAST_UPDATE_DATE.getProperty()));
metadataDataDefinition.setName((String) properties.get(GraphPropertiesDictionary.NAME.getProperty()));
metadataDataDefinition.setState((String) properties.get(GraphPropertiesDictionary.STATE.getProperty()));
- Type listType = new TypeToken<List<String>>() {
- }.getType();
- List<String> tagsFromJson = getGson()
- .fromJson((String) properties.get(GraphPropertiesDictionary.TAGS.getProperty()), listType);
+ List<String> tagsFromJson;
+ if(properties.get(GraphPropertiesDictionary.TAGS.getProperty()) instanceof List<?>){
+ tagsFromJson = (List<String>) properties.get(GraphPropertiesDictionary.TAGS.getProperty());
+ } else {
+ Type listType = new TypeToken<List<String>>() {}.getType();
+ tagsFromJson = getGson().fromJson((String) properties.get(GraphPropertiesDictionary.TAGS.getProperty()), listType);
+ }
metadataDataDefinition.setTags(tagsFromJson);
metadataDataDefinition.setVersion((String) properties.get(GraphPropertiesDictionary.VERSION.getProperty()));
- metadataDataDefinition
- .setContactId((String) properties.get(GraphPropertiesDictionary.CONTACT_ID.getProperty()));
+ metadataDataDefinition.setContactId((String) properties.get(GraphPropertiesDictionary.CONTACT_ID.getProperty()));
metadataDataDefinition.setUUID((String) properties.get(GraphPropertiesDictionary.UUID.getProperty()));
- metadataDataDefinition
- .setNormalizedName((String) properties.get(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty()));
- metadataDataDefinition
- .setSystemName((String) properties.get(GraphPropertiesDictionary.SYSTEM_NAME.getProperty()));
- metadataDataDefinition
- .setIsDeleted((Boolean) properties.get(GraphPropertiesDictionary.IS_DELETED.getProperty()));
+ metadataDataDefinition.setNormalizedName((String) properties.get(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty()));
+ metadataDataDefinition.setSystemName((String) properties.get(GraphPropertiesDictionary.SYSTEM_NAME.getProperty()));
+ metadataDataDefinition.setIsDeleted((Boolean) properties.get(GraphPropertiesDictionary.IS_DELETED.getProperty()));
metadataDataDefinition.setProjectCode((String) properties.get(GraphPropertiesDictionary.PROJECT_CODE.getProperty()));
metadataDataDefinition.setCsarUUID((String) properties.get(GraphPropertiesDictionary.CSAR_UUID.getProperty()));
- metadataDataDefinition
- .setCsarVersion((String) properties.get(GraphPropertiesDictionary.CSAR_VERSION.getProperty()));
- metadataDataDefinition.setImportedToscaChecksum(
- (String) properties.get(GraphPropertiesDictionary.IMPORTED_TOSCA_CHECKSUM.getProperty()));
- metadataDataDefinition
- .setInvariantUUID((String) properties.get(GraphPropertiesDictionary.INVARIANT_UUID.getProperty()));
+ metadataDataDefinition.setCsarVersion((String) properties.get(GraphPropertiesDictionary.CSAR_VERSION.getProperty()));
+ metadataDataDefinition.setImportedToscaChecksum((String) properties.get(GraphPropertiesDictionary.IMPORTED_TOSCA_CHECKSUM.getProperty()));
+ metadataDataDefinition.setInvariantUUID((String) properties.get(GraphPropertiesDictionary.INVARIANT_UUID.getProperty()));
+// metadataDataDefinition.setComponentType(ComponentTypeEnum.valueOf((String) properties.get(GraphPropertyEnum.COMPONENT_TYPE.getProperty())));
componentInstanceCounter = (Integer) properties.get(GraphPropertiesDictionary.INSTANCE_COUNTER.getProperty());
}
@@ -107,8 +102,7 @@ public abstract class ComponentMetadataData extends GraphNode {
addIfExists(map, GraphPropertiesDictionary.PROJECT_CODE, metadataDataDefinition.getProjectCode());
addIfExists(map, GraphPropertiesDictionary.CSAR_UUID, metadataDataDefinition.getCsarUUID());
addIfExists(map, GraphPropertiesDictionary.CSAR_VERSION, metadataDataDefinition.getCsarVersion());
- addIfExists(map, GraphPropertiesDictionary.IMPORTED_TOSCA_CHECKSUM,
- metadataDataDefinition.getImportedToscaChecksum());
+ addIfExists(map, GraphPropertiesDictionary.IMPORTED_TOSCA_CHECKSUM, metadataDataDefinition.getImportedToscaChecksum());
addIfExists(map, GraphPropertiesDictionary.INVARIANT_UUID, metadataDataDefinition.getInvariantUUID());
return map;
}
@@ -140,8 +134,7 @@ public abstract class ComponentMetadataData extends GraphNode {
@Override
public String toString() {
- return "ComponentMetadataData [metadataDataDefinition=" + metadataDataDefinition + ", componentInstanceCounter="
- + componentInstanceCounter + "]";
+ return "ComponentMetadataData [metadataDataDefinition=" + metadataDataDefinition + ", componentInstanceCounter=" + componentInstanceCounter + "]";
}
}
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 1016930e2a..3fb085f3d2 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
@@ -46,12 +46,19 @@ public class ConsumerData extends GraphNode {
public ConsumerData(Map<String, Object> properties) {
super(NodeTypeEnum.ConsumerCredentials);
consumerDataDefinition = new ConsumerDataDefinition();
- consumerDataDefinition.setConsumerDetailsLastupdatedtime((Long) properties.get(GraphPropertiesDictionary.CONSUMER_DETAILS_LAST_UPDATED_TIME.getProperty()));
- consumerDataDefinition.setConsumerLastAuthenticationTime((Long) properties.get(GraphPropertiesDictionary.CONSUMER_LAST_AUTHENTICATION_TIME.getProperty()));
- consumerDataDefinition.setConsumerName((String) properties.get(GraphPropertiesDictionary.CONSUMER_NAME.getProperty()));
- consumerDataDefinition.setConsumerPassword((String) properties.get(GraphPropertiesDictionary.CONSUMER_PASSWORD.getProperty()));
- consumerDataDefinition.setConsumerSalt((String) properties.get(GraphPropertiesDictionary.CONSUMER_SALT.getProperty()));
- consumerDataDefinition.setLastModfierAtuid((String) properties.get(GraphPropertiesDictionary.LAST_MODIFIER_USER_ID.getProperty()));
+ consumerDataDefinition.setConsumerDetailsLastupdatedtime(
+ (Long) properties.get(GraphPropertiesDictionary.CONSUMER_DETAILS_LAST_UPDATED_TIME.getProperty()));
+ consumerDataDefinition.setConsumerLastAuthenticationTime(
+ (Long) properties.get(GraphPropertiesDictionary.CONSUMER_LAST_AUTHENTICATION_TIME.getProperty()));
+ consumerDataDefinition
+ .setConsumerName((String) properties.get(GraphPropertiesDictionary.CONSUMER_NAME.getProperty()));
+ consumerDataDefinition.setConsumerPassword(
+ (String) properties.get(GraphPropertiesDictionary.CONSUMER_PASSWORD.getProperty()));
+ consumerDataDefinition
+ .setConsumerSalt((String) properties.get(GraphPropertiesDictionary.CONSUMER_SALT.getProperty()));
+ consumerDataDefinition.setLastModfierAtuid(
+ (String) properties.get(GraphPropertiesDictionary.LAST_MODIFIER_USER_ID.getProperty()));
+
}
@Override
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ESArtifactData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ESArtifactData.java
index 56101d031f..b198985b69 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ESArtifactData.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ESArtifactData.java
@@ -26,13 +26,13 @@ import com.datastax.driver.mapping.annotations.Column;
import com.datastax.driver.mapping.annotations.PartitionKey;
import com.datastax.driver.mapping.annotations.Table;
-@Table(keyspace = "sdcArtifact", name = "resources")
+@Table(keyspace = "sdcartifact", name = "resources")
public class ESArtifactData {
- public final static String RRESOURCE_ID_FIELD = "resourceId";
+ public static final String RRESOURCE_ID_FIELD = "resourceId";
- public final static String SERVICE_NAME_FIELD = "serviceName";
- public final static String SERVICE_VERSION_FIELD = "serviceVersion";
- public final static String ARTIFACT_NAME_FIELD = "artifactName";
+ public static final String SERVICE_NAME_FIELD = "serviceName";
+ public static final String SERVICE_VERSION_FIELD = "serviceVersion";
+ public static final String ARTIFACT_NAME_FIELD = "artifactName";
public static String delim = ":";
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ESSdcSchemaFilesData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ESSdcSchemaFilesData.java
new file mode 100644
index 0000000000..c6ab13bb3d
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ESSdcSchemaFilesData.java
@@ -0,0 +1,102 @@
+package org.openecomp.sdc.be.resources.data;
+
+import java.nio.ByteBuffer;
+import java.util.Date;
+
+import com.datastax.driver.mapping.annotations.Column;
+import com.datastax.driver.mapping.annotations.Table;
+
+@Table(keyspace = "sdcartifact", name = "sdcschemafiles")
+public class ESSdcSchemaFilesData {
+
+ @Column(name = "sdcreleasenum")
+ private String sdcReleaseNum;
+
+ @Column(name = "timestamp")
+ private Date timestamp;
+
+ @Column(name = "conformanceLevel")
+ private String conformanceLevel;
+
+ @Column(name = "fileName")
+ private String fileName;
+
+ @Column(name = "payload")
+ private ByteBuffer payload;
+
+ @Column(name = "checksum")
+ private String checksum;
+
+ public ESSdcSchemaFilesData() {
+
+ }
+
+ public ESSdcSchemaFilesData(String sdcReleaseNum, String conformanceLevel, String fileName, byte[] payload){
+ this.sdcReleaseNum = sdcReleaseNum;
+ this.conformanceLevel = conformanceLevel;
+ this.fileName = fileName;
+ if(payload != null) {
+ this.payload = ByteBuffer.wrap(payload.clone());
+ }
+ }
+
+ public String getSdcReleaseNum() {
+ return sdcReleaseNum;
+ }
+
+ public void setSdcReleaseNum(String sdcReleaseNum) {
+ this.sdcReleaseNum = sdcReleaseNum;
+ }
+
+ public String getConformanceLevel() {
+ return conformanceLevel;
+ }
+
+ public void setConformanceLevel(String conformanceLevel) {
+ this.conformanceLevel = conformanceLevel;
+ }
+
+ public String getFileName() {
+ return fileName;
+ }
+
+ public void setFileName(String fileName) {
+ this.fileName = fileName;
+ }
+
+ public ByteBuffer getPayload() {
+ return payload;
+ }
+
+ public void setPayload(ByteBuffer payload) {
+ if(payload != null){
+ this.payload = payload.duplicate();
+ }
+ }
+
+ public void setPayloadAsArray(byte[] payload) {
+ if(payload != null){
+ this.payload = ByteBuffer.wrap(payload.clone());
+ }
+ }
+
+ public byte[] getPayloadAsArray() {
+ return payload != null ? payload.array() : null;
+ }
+
+ public Date getTimestamp() {
+ return timestamp;
+ }
+
+ public void setTimestamp(Date timestamp) {
+ this.timestamp = timestamp;
+ }
+
+ public String getChecksum() {
+ return checksum;
+ }
+
+ public void setChecksum(String checksum) {
+ this.checksum = checksum;
+ }
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/GroupInstanceData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/GroupInstanceData.java
new file mode 100644
index 0000000000..7138fe5f72
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/GroupInstanceData.java
@@ -0,0 +1,127 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.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.ComponentInstanceDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.GroupInstanceDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
+
+
+public class GroupInstanceData extends GraphNode {
+
+ GroupInstanceDataDefinition groupDataDefinition;
+
+ public GroupInstanceData() {
+ super(NodeTypeEnum.GroupInstance);
+ this.groupDataDefinition = new GroupInstanceDataDefinition();
+ }
+
+ public GroupInstanceData(GroupInstanceDataDefinition groupDataDefinition) {
+ super(NodeTypeEnum.GroupInstance);
+ this.groupDataDefinition = groupDataDefinition;
+ }
+
+ public GroupInstanceData(Map<String, Object> properties) {
+
+ this();
+
+ groupDataDefinition
+ .setUniqueId((String) properties.get(GraphPropertiesDictionary.UNIQUE_ID.getProperty()));
+ groupDataDefinition
+ .setGroupUid((String) properties.get(GraphPropertiesDictionary.TYPE.getProperty()));
+ groupDataDefinition
+ .setCreationTime((Long) properties.get(GraphPropertiesDictionary.CREATION_DATE.getProperty()));
+ groupDataDefinition
+ .setModificationTime((Long) properties.get(GraphPropertiesDictionary.LAST_UPDATE_DATE.getProperty()));
+
+ groupDataDefinition
+ .setPosX((String) properties.get(GraphPropertiesDictionary.POSITION_X.getProperty()));
+ groupDataDefinition
+ .setPosY((String) properties.get(GraphPropertiesDictionary.POSITION_Y.getProperty()));
+ groupDataDefinition.setName((String) properties.get(GraphPropertiesDictionary.NAME.getProperty()));
+ groupDataDefinition.setPropertyValueCounter(
+ (Integer) properties.get(GraphPropertiesDictionary.PROPERTY_COUNTER.getProperty()));
+
+ groupDataDefinition
+ .setNormalizedName((String) properties.get(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty()));
+
+ groupDataDefinition
+ .setCustomizationUUID((String) properties.get(GraphPropertiesDictionary.CUSTOMIZATION_UUID.getProperty()));
+ }
+
+ @Override
+ public Map<String, Object> toGraphMap() {
+
+ Map<String, Object> map = new HashMap<String, Object>();
+
+ addIfExists(map, GraphPropertiesDictionary.TYPE, groupDataDefinition.getGroupUid());
+ addIfExists(map, GraphPropertiesDictionary.CREATION_DATE, groupDataDefinition.getCreationTime());
+ addIfExists(map, GraphPropertiesDictionary.LAST_UPDATE_DATE, groupDataDefinition.getModificationTime());
+
+ addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, groupDataDefinition.getUniqueId());
+ addIfExists(map, GraphPropertiesDictionary.POSITION_X, groupDataDefinition.getPosX());
+ addIfExists(map, GraphPropertiesDictionary.POSITION_Y, groupDataDefinition.getPosY());
+ addIfExists(map, GraphPropertiesDictionary.NAME, groupDataDefinition.getName());
+ addIfExists(map, GraphPropertiesDictionary.PROPERTY_COUNTER,
+ groupDataDefinition.getPropertyValueCounter());
+
+ addIfExists(map, GraphPropertiesDictionary.NORMALIZED_NAME, groupDataDefinition.getNormalizedName());
+
+ addIfExists(map, GraphPropertiesDictionary.CUSTOMIZATION_UUID, groupDataDefinition.getCustomizationUUID());
+
+ return map;
+ }
+
+ @Override
+ public String getUniqueId() {
+ return groupDataDefinition.getUniqueId();
+ }
+
+ public String getName() {
+ return groupDataDefinition.getName();
+ }
+
+ @Override
+ public String getUniqueIdKey() {
+ return GraphPropertiesDictionary.UNIQUE_ID.getProperty();
+ }
+
+ public GroupInstanceDataDefinition getGroupDataDefinition() {
+ return groupDataDefinition;
+ }
+
+ public void setComponentInstDataDefinition(GroupInstanceDataDefinition groupDataDefinition) {
+ this.groupDataDefinition = groupDataDefinition;
+ }
+
+ @Override
+ public String toString() {
+ return "GroupInstanceData [groupInstDataDefinition=" + groupDataDefinition + "]";
+ }
+
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/RelationshipTypeData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/RelationshipTypeData.java
index 7ceecf7e21..2e434955e6 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/RelationshipTypeData.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/RelationshipTypeData.java
@@ -27,21 +27,21 @@ import java.util.Map;
import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
-import org.openecomp.sdc.be.datatypes.elements.RelationshipTypeDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.RelationshipInstDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import com.google.gson.reflect.TypeToken;
public class RelationshipTypeData extends GraphNode {
- RelationshipTypeDataDefinition relationshipTypeDataDefinition;
+ RelationshipInstDataDefinition relationshipTypeDataDefinition;
public RelationshipTypeData() {
super(NodeTypeEnum.RelationshipType);
- relationshipTypeDataDefinition = new RelationshipTypeDataDefinition();
+ relationshipTypeDataDefinition = new RelationshipInstDataDefinition();
}
- public RelationshipTypeData(RelationshipTypeDataDefinition relationshipTypeDataDefinition) {
+ public RelationshipTypeData(RelationshipInstDataDefinition relationshipTypeDataDefinition) {
super(NodeTypeEnum.RelationshipType);
this.relationshipTypeDataDefinition = relationshipTypeDataDefinition;
}
@@ -107,11 +107,11 @@ public class RelationshipTypeData extends GraphNode {
return map;
}
- public RelationshipTypeDataDefinition getRelationshipTypeDataDefinition() {
+ public RelationshipInstDataDefinition getRelationshipTypeDataDefinition() {
return relationshipTypeDataDefinition;
}
- public void setRelationshipTypeDataDefinition(RelationshipTypeDataDefinition relationshipTypeDataDefinition) {
+ public void setRelationshipTypeDataDefinition(RelationshipInstDataDefinition relationshipTypeDataDefinition) {
this.relationshipTypeDataDefinition = relationshipTypeDataDefinition;
}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/RequirementData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/RequirementData.java
index 2b7e2d22b7..69fa9279c4 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/RequirementData.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/RequirementData.java
@@ -25,12 +25,10 @@ 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.RequirementDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
public class RequirementData extends GraphNode {
- public final static String MIN_OCCURRENCES = "1";
- public final static String MAX_OCCURRENCES = "UNBOUNDED";
- public final static String MAX_DEFAULT_OCCURRENCES = "1";
private String uniqueId;
@@ -41,8 +39,8 @@ public class RequirementData extends GraphNode {
private Long modificationTime;
private String relationshipType;
- private String minOccurrences = MIN_OCCURRENCES;
- private String maxOccurrences = MAX_DEFAULT_OCCURRENCES;
+ private String minOccurrences = RequirementDataDefinition.MIN_OCCURRENCES;
+ private String maxOccurrences = RequirementDataDefinition.MAX_DEFAULT_OCCURRENCES;
public RequirementData() {
super(NodeTypeEnum.Requirement);
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ResourceMetadataData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ResourceMetadataData.java
index 9df3d7cfac..06e098ff4b 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ResourceMetadataData.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ResourceMetadataData.java
@@ -40,40 +40,26 @@ public class ResourceMetadataData extends ComponentMetadataData {
public ResourceMetadataData(Map<String, Object> properties) {
super(NodeTypeEnum.Resource, new ResourceMetadataDataDefinition(), properties);
- ((ResourceMetadataDataDefinition) metadataDataDefinition)
- .setVendorName((String) properties.get(GraphPropertiesDictionary.VENDOR_NAME.getProperty()));
- ((ResourceMetadataDataDefinition) metadataDataDefinition)
- .setVendorRelease((String) properties.get(GraphPropertiesDictionary.VENDOR_RELEASE.getProperty()));
- ((ResourceMetadataDataDefinition) metadataDataDefinition).setResourceType(ResourceTypeEnum
- .valueOf((String) properties.get(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty())));
- ((ResourceMetadataDataDefinition) metadataDataDefinition)
- .setAbstract((Boolean) properties.get(GraphPropertiesDictionary.IS_ABSTRACT.getProperty()));
- ((ResourceMetadataDataDefinition) metadataDataDefinition)
- .setCost((String) properties.get(GraphPropertiesDictionary.COST.getProperty()));
- ((ResourceMetadataDataDefinition) metadataDataDefinition)
- .setLicenseType((String) properties.get(GraphPropertiesDictionary.LICENSE_TYPE.getProperty()));
- ((ResourceMetadataDataDefinition) metadataDataDefinition).setToscaResourceName(
- (String) properties.get(GraphPropertiesDictionary.TOSCA_RESOURCE_NAME.getProperty()));
+ ((ResourceMetadataDataDefinition) metadataDataDefinition).setVendorName((String) properties.get(GraphPropertiesDictionary.VENDOR_NAME.getProperty()));
+ ((ResourceMetadataDataDefinition) metadataDataDefinition).setVendorRelease((String) properties.get(GraphPropertiesDictionary.VENDOR_RELEASE.getProperty()));
+ ((ResourceMetadataDataDefinition) metadataDataDefinition).setResourceType(ResourceTypeEnum.valueOf((String) properties.get(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty())));
+ ((ResourceMetadataDataDefinition) metadataDataDefinition).setAbstract((Boolean) properties.get(GraphPropertiesDictionary.IS_ABSTRACT.getProperty()));
+ ((ResourceMetadataDataDefinition) metadataDataDefinition).setCost((String) properties.get(GraphPropertiesDictionary.COST.getProperty()));
+ ((ResourceMetadataDataDefinition) metadataDataDefinition).setLicenseType((String) properties.get(GraphPropertiesDictionary.LICENSE_TYPE.getProperty()));
+ ((ResourceMetadataDataDefinition) metadataDataDefinition).setToscaResourceName((String) properties.get(GraphPropertiesDictionary.TOSCA_RESOURCE_NAME.getProperty()));
}
@Override
public Map<String, Object> toGraphMap() {
Map<String, Object> graphMap = super.toGraphMap();
- addIfExists(graphMap, GraphPropertiesDictionary.VENDOR_NAME,
- ((ResourceMetadataDataDefinition) metadataDataDefinition).getVendorName());
- addIfExists(graphMap, GraphPropertiesDictionary.VENDOR_RELEASE,
- ((ResourceMetadataDataDefinition) metadataDataDefinition).getVendorRelease());
- addIfExists(graphMap, GraphPropertiesDictionary.RESOURCE_TYPE,
- ((ResourceMetadataDataDefinition) metadataDataDefinition).getResourceType().name());
- addIfExists(graphMap, GraphPropertiesDictionary.IS_ABSTRACT,
- ((ResourceMetadataDataDefinition) metadataDataDefinition).isAbstract());
- addIfExists(graphMap, GraphPropertiesDictionary.COST,
- ((ResourceMetadataDataDefinition) metadataDataDefinition).getCost());
- addIfExists(graphMap, GraphPropertiesDictionary.LICENSE_TYPE,
- ((ResourceMetadataDataDefinition) metadataDataDefinition).getLicenseType());
- addIfExists(graphMap, GraphPropertiesDictionary.TOSCA_RESOURCE_NAME,
- ((ResourceMetadataDataDefinition) metadataDataDefinition).getToscaResourceName());
+ addIfExists(graphMap, GraphPropertiesDictionary.VENDOR_NAME, ((ResourceMetadataDataDefinition) metadataDataDefinition).getVendorName());
+ addIfExists(graphMap, GraphPropertiesDictionary.VENDOR_RELEASE, ((ResourceMetadataDataDefinition) metadataDataDefinition).getVendorRelease());
+ addIfExists(graphMap, GraphPropertiesDictionary.RESOURCE_TYPE, ((ResourceMetadataDataDefinition) metadataDataDefinition).getResourceType().name());
+ addIfExists(graphMap, GraphPropertiesDictionary.IS_ABSTRACT, ((ResourceMetadataDataDefinition) metadataDataDefinition).isAbstract());
+ addIfExists(graphMap, GraphPropertiesDictionary.COST, ((ResourceMetadataDataDefinition) metadataDataDefinition).getCost());
+ addIfExists(graphMap, GraphPropertiesDictionary.LICENSE_TYPE, ((ResourceMetadataDataDefinition) metadataDataDefinition).getLicenseType());
+ addIfExists(graphMap, GraphPropertiesDictionary.TOSCA_RESOURCE_NAME, ((ResourceMetadataDataDefinition) metadataDataDefinition).getToscaResourceName());
return graphMap;
}
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 d09caacabe..78974c4a77 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
@@ -197,7 +197,7 @@ public class UserData extends GraphNode {
@Override
public Map<String, Object> toGraphMap() {
Map<String, Object> map = new HashMap<String, Object>();
- addIfExists(map, GraphPropertiesDictionary.USER_ID, userId);
+ addIfExists(map, GraphPropertiesDictionary.USERID, userId);
addIfExists(map, GraphPropertiesDictionary.EMAIL, email);
addIfExists(map, GraphPropertiesDictionary.FIRST_NAME, firstName);
addIfExists(map, GraphPropertiesDictionary.LAST_NAME, lastName);
@@ -209,7 +209,7 @@ public class UserData extends GraphNode {
@Override
public String getUniqueIdKey() {
- return GraphPropertiesDictionary.USER_ID.getProperty();
+ return GraphPropertiesDictionary.USERID.getProperty();
}
@Override
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 8b0bd58d9e..cfc37f19e2 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
@@ -46,14 +46,20 @@ public enum AuditingActionEnum {
UPDATE_RESOURCE_METADATA("UpdateResourceMetadata", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE),
UPDATE_SERVICE_METADATA("UpdateServiceMetadata", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE),
ARTIFACT_UPLOAD("ArtifactUpload", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE),
+ //External API
ARTIFACT_UPLOAD_BY_API("ArtifactUploadByAPI", AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE),
ARTIFACT_UPDATE_BY_API("ArtifactUpdateByAPI", AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE),
ARTIFACT_DELETE_BY_API("ArtifactDeleteByAPI", AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE),
+ 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),
+
+
ARTIFACT_PAYLOAD_UPDATE("ArtifactPayloadUpdate", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE),
ARTIFACT_METADATA_UPDATE("ArtifactMetadataUpdate", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE),
ARTIFACT_DELETE("ArtifactDelete", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE),
ARTIFACT_DOWNLOAD("ArtifactDownload", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE),
- DOWNLOAD_ARTIFACT("DownloadArtifact",AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE),
+
// Distribution
DISTRIBUTION_ARTIFACT_DOWNLOAD("DArtifactDownload", AuditingTypesConstants.DISTRIBUTION_DOWNLOAD_EVENT_TYPE),
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 99a42e852e..5c8cded0db 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
@@ -34,7 +34,7 @@ import com.datastax.driver.mapping.annotations.Column;
import com.datastax.driver.mapping.annotations.PartitionKey;
import com.datastax.driver.mapping.annotations.Table;
-@Table(keyspace = "sdcAudit", name = AuditingTypesConstants.AUTH_EVENT_TYPE)
+@Table(keyspace = "sdcaudit", name = AuditingTypesConstants.AUTH_EVENT_TYPE)
public class AuthEvent extends AuditingGenericEvent {
private static String AUTH_EVENT_TEMPLATE = "action=\"%s\" timestamp=\"%s\" "
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 027c57c5c9..f32acc81c4 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
@@ -34,6 +34,10 @@ import com.datastax.driver.mapping.annotations.Column;
import com.datastax.driver.mapping.annotations.PartitionKey;
import com.datastax.driver.mapping.annotations.Table;
+/**
+ * This class Represents the Audit for External API
+ *
+ */
@Table(keyspace = AuditingTypesConstants.AUDIT_KEYSPACE, name = AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE)
public class ExternalApiEvent extends AuditingGenericEvent {
@PartitionKey
@@ -64,9 +68,24 @@ public class ExternalApiEvent extends AuditingGenericEvent {
@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;
@@ -119,10 +138,35 @@ public class ExternalApiEvent extends AuditingGenericEvent {
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);
@@ -140,6 +184,7 @@ public class ExternalApiEvent extends AuditingGenericEvent {
@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());
@@ -151,6 +196,12 @@ public class ExternalApiEvent extends AuditingGenericEvent {
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());
@@ -235,6 +286,14 @@ public class ExternalApiEvent extends AuditingGenericEvent {
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;
@@ -273,7 +332,42 @@ public class ExternalApiEvent extends AuditingGenericEvent {
return "ExternalApiEvent [timebaseduuid=" + timebaseduuid + ", timestamp1=" + timestamp1 + ", action=" + action
+ ", status=" + status + ", desc=" + desc + ", consumerId=" + consumerId + ", resourceURL="
+ resourceURL + ", resourceName=" + resourceName + ", resourceType=" + resourceType
- + ", serviceInstanceId=" + serviceInstanceId + ", modifier=" + modifier + ", prevArtifactUuid="
+ + ", 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/impl/ResourceUploader.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/impl/ResourceUploader.java
index 1570ff1ed1..a3c5218495 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
@@ -140,8 +140,8 @@ public class ResourceUploader implements IResourceUploader {
* getServiceArtifact(artifactUpdateData.getId());
*
* if(getServiceArtifactStatus.isRight()){
- * log.debug("ResourceUploadStatus:updateArtifactt artifact with id {} not exist.",
- * artifactUpdateData.getId()); status =
+ * log.debug("ResourceUploadStatus:updateArtifactt artifact with id " +
+ * artifactUpdateData.getId() + " not exist."); status =
* getServiceArtifactStatus.right().value(); }
* if(getServiceArtifactStatus.isLeft()){ status =
* updateServiceArtifact(artifactUpdateData,
diff --git a/catalog-dao/src/test/java/org/openecomp/sdc/be/resources/ArtifactDaoTest.java b/catalog-dao/src/test/java/org/openecomp/sdc/be/resources/ArtifactDaoTest.java
index aa9d30cb12..292ae08f0a 100644
--- a/catalog-dao/src/test/java/org/openecomp/sdc/be/resources/ArtifactDaoTest.java
+++ b/catalog-dao/src/test/java/org/openecomp/sdc/be/resources/ArtifactDaoTest.java
@@ -98,7 +98,6 @@ public class ArtifactDaoTest {
// clearIndex(ICatalogDAO.RESOURCES_INDEX, ArtifactData.class);
// clearIndex(ICatalogDAO.RESOURCES_INDEX, ServiceArtifactData.class);
// } catch (InterruptedException e) {
- // TODO Auto-generated catch block
// e.printStackTrace();
// }
@@ -152,8 +151,7 @@ public class ArtifactDaoTest {
* imageData.setResourceCreator("Marina");
* imageData.setResourceLastUpdater("Marina"); ResourceUploadStatus status =
* daoUploader.saveImage(imageData, true); assertEquals(status,
- * ResourceUploadStatus.OK); } catch (IOException e) { // TODO
- * Auto-generated catch block e.printStackTrace(); }
+ * ResourceUploadStatus.OK); } catch (IOException e) { e.printStackTrace(); }
*
*
* }
@@ -456,7 +454,7 @@ public class ArtifactDaoTest {
* status = daoUploader.saveServiceArtifact(serviceArData1, true);
*
*
- * } catch (Exception e) { // TODO Auto-generated catch block
+ * } catch (Exception e) {
* e.printStackTrace(); }
*
* }
@@ -561,7 +559,7 @@ public class ArtifactDaoTest {
* status = daoUploader.saveServiceArtifact(serviceArData1, true);
*
*
- * } catch (Exception e) { // TODO Auto-generated catch block
+ * } catch (Exception e) {
* e.printStackTrace(); }
*
* }
diff --git a/catalog-dao/src/test/java/org/openecomp/sdc/be/resources/ESUsersDAOTest.java b/catalog-dao/src/test/java/org/openecomp/sdc/be/resources/ESUsersDAOTest.java
deleted file mode 100644
index a99acbe2b7..0000000000
--- a/catalog-dao/src/test/java/org/openecomp/sdc/be/resources/ESUsersDAOTest.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.be.resources;
-
-//@RunWith(SpringJUnit4ClassRunner.class)
-//@ContextConfiguration("classpath:application-context-test.xml")
-//@TestExecutionListeners(listeners = {DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class, TransactionalTestExecutionListener.class})
-public class ESUsersDAOTest {
-
- // @Resource
- // ElasticSearchClient esclient;
- //
- //// @Resource(name = "users-dao")
- // private IUsersDAO usersDao;
-
- // @Test
- public void testNewUserStub() {
-
- }
-
- // @Test
- public void testNewUser() {
- // if( usersDao == null ){
- // assertTrue(false);
- // }
- //
- // String id = "yhufksd57834601";
- // UserData userData = new UserData("Myname", "Mylastname", id, "email",
- // "Tester");
- //
- // ActionStatus saveUserData = usersDao.saveUserData(userData);
- // assertEquals(saveUserData, ActionStatus.OK);
- //
- // Either<UserData, ActionStatus> statusFromEs =
- // usersDao.getUserData(id);
- // assertTrue(statusFromEs.isLeft() );
- // UserData fromEs = statusFromEs.left().value();
- // assertNotNull(fromEs);
- // assertEquals(userData, fromEs);
- //
- //
- // usersDao.deleteUserData(id);
-
- }
-
-}
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
new file mode 100644
index 0000000000..c0c49b7b13
--- /dev/null
+++ b/catalog-dao/src/test/java/org/openecomp/sdc/be/resources/JsonParserUtilsTests.java
@@ -0,0 +1,56 @@
+package org.openecomp.sdc.be.resources;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.codehaus.jackson.JsonGenerationException;
+import org.codehaus.jackson.map.JsonMappingException;
+import org.codehaus.jackson.map.ObjectMapper;
+import org.codehaus.jackson.type.TypeReference;
+import org.junit.Test;
+import org.openecomp.sdc.be.dao.jsongraph.utils.JsonParserUtils;
+import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
+
+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);
+
+ }
+
+}
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 a4110f5be3..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;
@@ -122,7 +125,7 @@ public class TitanGenericDaoTest {
@Test
public void testCrudNode() {
- String id = "user12345abc";
+ String id = "userId12345abc";
UserData userData = new UserData("Myname123", "Mylastname", id, "email123", "Tester",
UserStatusEnum.ACTIVE.name(), null);
@@ -163,7 +166,7 @@ public class TitanGenericDaoTest {
public void testGetByCategoryAndAll() {
// create 2 nodes
- String id = "user12345abc";
+ String id = "userId12345abc";
UserData userData1 = new UserData("Myname123", "Mylastname", id, "email123", "Tester",
UserStatusEnum.ACTIVE.name(), null);
@@ -171,7 +174,7 @@ public class TitanGenericDaoTest {
assertTrue(node1.isLeft());
log.debug("{}", node1.left().value());
- id = "userdfkoer45abc";
+ id = "userIddfkoer45abc";
UserData userData2 = new UserData("Mynadyhme123", "Mylasghtname", id, "emaighdl123", "Designer",
UserStatusEnum.ACTIVE.name(), null);
Either<UserData, TitanOperationStatus> node2 = titanDao.createNode(userData2, UserData.class);
@@ -216,7 +219,7 @@ public class TitanGenericDaoTest {
@Test
public void testGetEdgesForNode() {
- String id = "user12345abc";
+ String id = "userId12345abc";
UserData userData = new UserData("Myname123", "Mylastname", id, "email123", UserRoleEnum.ADMIN.name(),
UserStatusEnum.ACTIVE.name(), null);
titanDao.createNode(userData, UserData.class);
@@ -262,7 +265,7 @@ public class TitanGenericDaoTest {
@Test
public void testLockElement() {
-
+
ResourceMetadataData resourceData = new ResourceMetadataData();
resourceData.getMetadataDataDefinition().setName("resourceForLock");
@@ -307,7 +310,7 @@ public class TitanGenericDaoTest {
@Test
public void testReLockElement() throws InterruptedException {
-
+
ResourceMetadataData resourceData = new ResourceMetadataData();
resourceData.getMetadataDataDefinition().setName("resourceForReLock");
@@ -505,27 +508,6 @@ public class TitanGenericDaoTest {
@Test
public void testDuplicateResultDueToTitanBug() {
- // TitanGraph titanGraph = titanDao.getGraph().left().value();
- // TitanManagement managementSystem = titanGraph.getManagementSystem();
-
- // GraphPropertiesDictionary[] properties = {
- // GraphPropertiesDictionary.IS_ABSTRACT,
- // GraphPropertiesDictionary.ADDITIONAL_INFO_ID_TO_KEY,
- // GraphPropertiesDictionary.POSITION_X,
- // GraphPropertiesDictionary.ARTIFACT_TIMEOUT };
- //
- // for (GraphPropertiesDictionary property : properties) {
- // if (false ==
- // managementSystem.containsGraphIndex(property.getProperty())) {
- // PropertyKey propKey1 =
- // managementSystem.makePropertyKey(property.getProperty()).dataType(property.getClazz()).make();
- // managementSystem.buildIndex(property.getProperty(),
- // Vertex.class).addKey(propKey1).unique().buildCompositeIndex();
- // }
- // }
-
- // managementSystem.commit();
-
ResourceMetadataData resourceData1 = new ResourceMetadataData();
resourceData1.getMetadataDataDefinition().setUniqueId("A");
((ResourceMetadataDataDefinition) resourceData1.getMetadataDataDefinition()).setAbstract(true);
@@ -667,7 +649,7 @@ public class TitanGenericDaoTest {
@Test
public void testDuplicateResultUSeHasNotQueryDueToTitanBug() {
-
+
String name = "bbbb";
ResourceMetadataData resourceData1 = new ResourceMetadataData();
@@ -717,5 +699,5 @@ public class TitanGenericDaoTest {
titanDao.rollback();
}
-
+
}
diff --git a/catalog-dao/src/test/resources/config/catalog-dao/configuration.yaml b/catalog-dao/src/test/resources/config/catalog-dao/configuration.yaml
index 0b43e3b8c6..67c0ec7b20 100644
--- a/catalog-dao/src/test/resources/config/catalog-dao/configuration.yaml
+++ b/catalog-dao/src/test/resources/config/catalog-dao/configuration.yaml
@@ -7,8 +7,8 @@ identificationHeaderFields:
# catalog backend hostname
-beFqdn: 172.20.43.124:8080
-
+beFqdn: 0.0.0.0
+# sdccatalog.att.com
# catalog backend http port
beHttpPort: 8080
@@ -48,7 +48,7 @@ neo4j:
maxHttpPerRoute: 20
cassandraConfig:
- cassandraHosts: ['mtanjv9sdcg44']
+ cassandraHosts: ['000000000']
localDataCenter:
reconnectTimeout : 30000
authenticate: false
@@ -81,23 +81,23 @@ elasticSearch:
creationPeriod: month
switchoverDetector:
- gBeFqdn: AIO-BE.ecomp.idns.cip
- gFeFqdn: AIO-FE.ecomp.idns.cip
- beVip: 1.2.3.4
- feVip: 1.2.3.4
+ gBeFqdn: AIO-BE.ecomp.idns
+ gFeFqdn: AIO-FE.ecomp.idns
+ beVip: 0.0.0.0
+ feVip: 0.0.0.0
beResolveAttempts: 3
feResolveAttempts: 3
enabled: false
interval: 60
changePriorityUser: ecompasdc
changePriorityPassword: ecompasdc123
- publishNetworkUrl: "http://cora.web/crt/CipDomain.ECOMP-ASDC-DEVST/config/update_network?user=root"
+ publishNetworkUrl: "http://xxx.com/crt/CipDomain.ECOMP-ASDC-DEVST/config/update_network?user=root"
publishNetworkBody: '{"note":"publish network"}'
groups:
- beSet: { changePriorityUrl: "http://cora.web/crt/CipDomain.ECOMP-ASDC-DEVST/config/sites/AIO-BE.ecomp.idns.cip?user=root",
- changePriorityBody: '{"name":"AIO-BE.ecomp.idns.cip","uri":"/crt/CipDomain.ECOMP-ASDC-DEVST/config/sites/AIO-BE.ecomp.idns.cip","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://cora.web/crt/CipDomain.ECOMP-ASDC-DEVST/config/sites/AIO-FE.ecomp.idns.cip?user=root",
- changePriorityBody: '{"comment":"AIO G-fqdn","name":"AIO-FE.ecomp.idns.cip","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"}'}
+ 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:
diff --git a/catalog-fe/pom.xml b/catalog-fe/pom.xml
index 3518779952..a3acabb41f 100644
--- a/catalog-fe/pom.xml
+++ b/catalog-fe/pom.xml
@@ -5,387 +5,306 @@
<artifactId>catalog-fe</artifactId>
<packaging>war</packaging>
-
-
<parent>
<groupId>org.openecomp.sdc</groupId>
<artifactId>sdc-main</artifactId>
<version>1.1.0-SNAPSHOT</version>
</parent>
+ <dependencies>
+ <dependency>
+ <groupId>org.functionaljava</groupId>
+ <artifactId>functionaljava</artifactId>
+ <version>${functionaljava.version}</version>
+ <scope>compile</scope>
+ </dependency>
- <dependencies>
+ <dependency>
+ <groupId>org.openecomp.sdc</groupId>
+ <artifactId>security-utils</artifactId>
+ <version>${project.version}</version>
+ <scope>compile</scope>
+ </dependency>
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>4.12</version>
- <scope>test</scope>
+ <groupId>org.openecomp.sdc</groupId>
+ <artifactId>common-app-api</artifactId>
+ <version>${project.version}</version>
</dependency>
+ <!-- File changes listener -->
<dependency>
- <groupId>org.testng</groupId>
- <artifactId>testng</artifactId>
- <version>6.9.10</version>
- <scope>test</scope>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-api</artifactId>
+ <version>${slf4j-api.version}</version>
+ <scope>compile</scope>
</dependency>
<dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-core</artifactId>
- <version>${spring.version}</version>
- <scope>provided</scope>
+ <groupId>ch.qos.logback</groupId>
+ <artifactId>logback-classic</artifactId>
+ <version>${logback.version}</version>
+ <scope>compile</scope>
</dependency>
<dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-beans</artifactId>
- <version>${spring.version}</version>
- <scope>provided</scope>
+ <groupId>ch.qos.logback</groupId>
+ <artifactId>logback-core</artifactId>
+ <version>${logback.version}</version>
+ <scope>compile</scope>
</dependency>
<dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-context</artifactId>
- <version>${spring.version}</version>
- <scope>provided</scope>
+ <groupId>org.codehaus.groovy</groupId>
+ <artifactId>groovy-all</artifactId>
+ <version>${groovy.version}</version>
+ <scope>compile</scope>
</dependency>
<dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-context-support</artifactId>
- <version>${spring.version}</version>
- <scope>provided</scope>
+ <groupId>org.codehaus.janino</groupId>
+ <artifactId>janino</artifactId>
+ <version>${janino.version}</version>
+ <scope>compile</scope>
</dependency>
<dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-messaging</artifactId>
- <version>${spring.version}</version>
- <scope>provided</scope>
+ <groupId>org.yaml</groupId>
+ <artifactId>snakeyaml</artifactId>
+ <version>${snakeyaml.version}</version>
+ <scope>compile</scope>
</dependency>
<dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-web</artifactId>
- <version>${spring.version}</version>
- <scope>provided</scope>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-jci-core</artifactId>
+ <version>${commons-jci-core.version}</version>
+ <scope>compile</scope>
</dependency>
<dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-webmvc</artifactId>
- <version>${spring.version}</version>
- <scope>provided</scope>
+ <groupId>com.google.code.gson</groupId>
+ <artifactId>gson</artifactId>
+ <version>${gson.version}</version>
+ <scope>compile</scope>
</dependency>
<dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-aop</artifactId>
- <version>${spring.version}</version>
- <scope>provided</scope>
+ <groupId>org.glassfish.jersey.containers</groupId>
+ <artifactId>jersey-container-servlet</artifactId>
+ <version>${jersey-bom.version}</version>
+ <scope>compile</scope>
</dependency>
<dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-aspects</artifactId>
- <version>${spring.version}</version>
- <scope>provided</scope>
+ <groupId>org.glassfish.jersey.media</groupId>
+ <artifactId>jersey-media-multipart</artifactId>
+ <version>${jersey-bom.version}</version>
+ <scope>compile</scope>
</dependency>
<dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-expression</artifactId>
- <version>${spring.version}</version>
- <scope>test</scope>
+ <groupId>org.glassfish.jersey.media</groupId>
+ <artifactId>jersey-media-moxy</artifactId>
+ <version>${jersey-bom.version}</version>
+ <scope>compile</scope>
</dependency>
+ <dependency>
+ <groupId>javax.mail</groupId>
+ <artifactId>javax.mail-api</artifactId>
+ <version>1.5.2</version>
+ <scope>compile</scope>
+ </dependency>
<dependency>
- <groupId>org.functionaljava</groupId>
- <artifactId>functionaljava</artifactId>
+ <groupId>org.glassfish.jersey.media</groupId>
+ <artifactId>jersey-media-json-jackson</artifactId>
+ <version>${jersey-bom.version}</version>
<scope>compile</scope>
</dependency>
-
+
<dependency>
- <groupId>org.openecomp.sdc</groupId>
- <artifactId>security-utils</artifactId>
- <version>${security-utils.version}</version>
- <scope>compile</scope> </dependency>
-
- <dependency>
- <groupId>org.openecomp.sdc</groupId>
- <artifactId>common-app-api</artifactId>
- <version>${common-app-api.version}</version>
- </dependency>
-
- <!-- File changes listener -->
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-api</artifactId>
- <version>1.7.10</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>org.codehaus.groovy</groupId>
- <artifactId>groovy-all</artifactId>
- <version>${groovy.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>org.codehaus.janino</groupId>
- <artifactId>janino</artifactId>
- <version>${janino.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>org.yaml</groupId>
- <artifactId>snakeyaml</artifactId>
- <version>1.14</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>org.apache.commons</groupId>
- <artifactId>commons-jci-core</artifactId>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>com.google.code.gson</groupId>
- <artifactId>gson</artifactId>
- <version>2.3.1</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>org.glassfish.jersey.containers</groupId>
- <artifactId>jersey-container-servlet</artifactId>
- <version>2.24</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>org.glassfish.jersey.media</groupId>
- <artifactId>jersey-media-multipart</artifactId>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>org.glassfish.jersey.media</groupId>
- <artifactId>jersey-media-moxy</artifactId>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>javax.mail</groupId>
- <artifactId>javax.mail-api</artifactId>
- <version>1.5.2</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>org.glassfish.jersey.media</groupId>
- <artifactId>jersey-media-json-jackson</artifactId>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-core</artifactId>
- <version>${jackson.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-databind</artifactId>
- <version>${jackson.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-annotations</artifactId>
- <version>${jackson.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>httpcore</artifactId>
- <version>${httpcore.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>org.apache.httpcomponents</groupId>
- <artifactId>httpmime</artifactId>
- <!--<version>4.3.2</version>-->
- <version>${httpclient.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>commons-logging</groupId>
- <artifactId>commons-logging</artifactId>
- <version>1.2.1-SNAPSHOT</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>commons-codec</groupId>
- <artifactId>commons-codec</artifactId>
- <version>2.0-SNAPSHOT</version>
- <scope>compile</scope>
- </dependency>
- <!-- http client END -->
-
- <dependency>
- <groupId>javax.servlet</groupId>
- <artifactId>servlet-api</artifactId>
- <scope>provided</scope>
- </dependency>
-
- <!-- JSON and YAML Parsing -->
- <dependency>
- <groupId>com.fasterxml.jackson.dataformat</groupId>
- <artifactId>jackson-dataformat-yaml</artifactId>
- <version>${jackson.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <!-- Jetty Proxy -->
- <dependency>
- <groupId>org.eclipse.jetty</groupId>
- <artifactId>jetty-proxy</artifactId>
- <version>${jetty.version}</version>
- <scope>compile</scope>
- </dependency>
+ <groupId>com.fasterxml.jackson.core</groupId>
+ <artifactId>jackson-core</artifactId>
+ <version>${jackson.version}</version>
+ <scope>compile</scope>
+ </dependency>
- <dependency>
- <groupId>org.eclipse.jetty</groupId>
- <artifactId>jetty-servlets</artifactId>
- <version>${jetty.servlets.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <!-- Proxy servlet -->
- <dependency>
- <groupId>com.google.guava</groupId>
- <artifactId>guava</artifactId>
- <version>${guava.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <!-- Aspects -->
- <dependency>
- <groupId>com.jcabi</groupId>
- <artifactId>jcabi-aspects</artifactId>
- <scope>compile</scope>
- </dependency>
- <dependency>
- <groupId>org.aspectj</groupId>
- <artifactId>aspectjrt</artifactId>
- <version>${aspectjrt.version}</version>
- <scope>compile</scope>
- </dependency>
- <dependency>
- <groupId>org.apache.commons</groupId>
- <artifactId>commons-lang3</artifactId>
- <version>${lang3.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <!-- Inserted for ECOMP Portal Integration -->
- <dependency>
- <groupId>org.openecomp.ecompsdkos</groupId>
- <artifactId>ecompFW</artifactId>
- <version>${ecomp.version}</version>
- <scope>compile</scope>
- <exclusions>
- <exclusion>
- <groupId>com.att.nsa</groupId>
- <artifactId>cambriaClient</artifactId>
- </exclusion>
- <exclusion>
- <artifactId>slf4j-log4j12</artifactId>
- <groupId>org.slf4j</groupId>
- </exclusion>
- </exclusions>
- </dependency>
-
- <!-- TEST -->
- <dependency>
- <groupId>org.glassfish.jersey.test-framework.providers</groupId>
- <artifactId>jersey-test-framework-provider-bundle</artifactId>
- <type>pom</type>
- <scope>test</scope>
- </dependency>
-
- <dependency>
- <groupId>org.eclipse.jetty</groupId>
- <artifactId>jetty-servlet</artifactId>
- <scope>test</scope>
- </dependency>
+ <dependency>
+ <groupId>com.fasterxml.jackson.core</groupId>
+ <artifactId>jackson-databind</artifactId>
+ <version>${jackson.version}</version>
+ <scope>compile</scope>
+ </dependency>
- <dependency>
- <groupId>org.eclipse.jetty</groupId>
- <artifactId>jetty-webapp</artifactId>
- <scope>test</scope>
- </dependency>
+ <dependency>
+ <groupId>com.fasterxml.jackson.core</groupId>
+ <artifactId>jackson-annotations</artifactId>
+ <version>${jackson.annotations.version}</version>
+ <scope>compile</scope>
+ </dependency>
- <dependency>
- <groupId>org.mockito</groupId>
- <artifactId>mockito-all</artifactId>
- <version>1.10.19</version>
- <scope>test</scope>
- </dependency>
+ <!-- http client -->
+ <dependency>
+ <groupId>org.apache.httpcomponents</groupId>
+ <artifactId>httpclient</artifactId>
+ <version>${httpclient.version}</version>
+ <scope>compile</scope>
+ </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-test</artifactId>
- <version>${spring.version}</version>
- <scope>test</scope>
- </dependency>
- </dependencies>
+ <dependency>
+ <groupId>org.apache.httpcomponents</groupId>
+ <artifactId>httpcore</artifactId>
+ <version>${httpcore.version}</version>
+ <scope>compile</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.httpcomponents</groupId>
+ <artifactId>httpmime</artifactId>
+ <version>${httpclient.version}</version>
+ <!--<version>4.3.2</version>-->
+ <scope>compile</scope>
+ </dependency>
+ <dependency>
+ <groupId>commons-logging</groupId>
+ <artifactId>commons-logging</artifactId>
+ <version>${commons-logging}</version>
+ <scope>compile</scope>
+ </dependency>
+ <dependency>
+ <groupId>commons-codec</groupId>
+ <artifactId>commons-codec</artifactId>
+ <version>${commons-codec}</version>
+ <scope>compile</scope>
+ </dependency>
+ <!-- http client END -->
+ <dependency>
+ <groupId>javax.servlet</groupId>
+ <artifactId>servlet-api</artifactId>
+ <version>${servlet-api.version}</version>
+ <scope>provided</scope>
+ </dependency>
- <build>
+ <!-- JSON and YAML Parsing -->
+ <dependency>
+ <groupId>com.fasterxml.jackson.dataformat</groupId>
+ <artifactId>jackson-dataformat-yaml</artifactId>
+ <version>${jackson.version}</version>
+ <scope>compile</scope>
+ </dependency>
- <finalName>${project.artifactId}-${project.version}</finalName>
+ <!-- Jetty Proxy -->
+ <dependency>
+ <groupId>org.eclipse.jetty</groupId>
+ <artifactId>jetty-proxy</artifactId>
+ <version>${jetty.version}</version>
+ <scope>compile</scope>
+ </dependency>
- <plugins>
-
+ <dependency>
+ <groupId>org.eclipse.jetty</groupId>
+ <artifactId>jetty-servlets</artifactId>
+ <version>${jetty.version}</version>
+ <scope>provided</scope>
+ </dependency>
+
+ <!-- Proxy servlet -->
+ <dependency>
+ <groupId>com.google.guava</groupId>
+ <artifactId>guava</artifactId>
+ <version>${guava.version}</version>
+ <scope>compile</scope>
+ </dependency>
+
+ <!-- Aspects -->
+ <dependency>
+ <groupId>com.jcabi</groupId>
+ <artifactId>jcabi-aspects</artifactId>
+ <version>${jcabi.version}</version>
+ <scope>compile</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.aspectj</groupId>
+ <artifactId>aspectjrt</artifactId>
+ <version>${aspectjrt.version}</version>
+ <scope>compile</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-lang3</artifactId>
+ <version>${lang3.version}</version>
+ <scope>compile</scope>
+ </dependency>
+
+ <!-- Inserted for ECOMP Portal Integration -->
+ <dependency>
+ <groupId>org.openecomp.ecompsdkos</groupId>
+ <artifactId>ecompFW</artifactId>
+ <version>${ecomp.version}</version>
+ <scope>compile</scope>
+ <exclusions>
+ <exclusion>
+ <groupId>com.att.nsa</groupId>
+ <artifactId>cambriaClient</artifactId>
+ </exclusion>
+ <exclusion>
+ <artifactId>slf4j-log4j12</artifactId>
+ <groupId>org.slf4j</groupId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+ <!-- System metrics -->
+ <dependency>
+ <groupId>org.fusesource</groupId>
+ <artifactId>sigar</artifactId>
+ <version>${sigar.version}</version>
+ <scope>compile</scope>
+ </dependency>
+
+ <!-- TEST -->
+ <dependency>
+ <groupId>org.glassfish.jersey.test-framework.providers</groupId>
+ <artifactId>jersey-test-framework-provider-bundle</artifactId>
+ <version>${jersey-bom.version}</version>
+ <type>pom</type>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.eclipse.jetty</groupId>
+ <artifactId>jetty-servlet</artifactId>
+ <version>${jetty.version}</version>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.eclipse.jetty</groupId>
+ <artifactId>jetty-webapp</artifactId>
+ <version>${jetty.version}</version>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-all</artifactId>
+ <version>${mockito.version}</version>
+ <scope>test</scope>
+ </dependency>
+
+ </dependencies>
+
+ <build>
+
+ <finalName>${project.artifactId}-${project.version}</finalName>
+
+ <plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
@@ -396,7 +315,7 @@
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
</manifest>
</archive>
-
+
<webResources>
<resource>
<directory>src/main/resources</directory>
@@ -405,8 +324,6 @@
</configuration>
</plugin>
-
-
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
@@ -439,16 +356,14 @@
<outputDirectory>${project.parent.basedir}/sdc-os-chef/sdc-frontend/</outputDirectory>
</configuration>
</execution>
-
</executions>
</plugin>
-
-
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
- <version>9.0.6.v20130930</version>
+ <version>${jetty.version}</version>
+ <!--<version>9.0.6.v20130930</version>-->
<configuration>
<contextPath>/</contextPath>
<webApp>
@@ -463,6 +378,9 @@
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.7</version>
+ <configuration>
+ <skip>true</skip>
+ </configuration>
</plugin>
<plugin>
@@ -477,36 +395,12 @@
</execution>
</executions>
</plugin>
- <!-- ============================================= -->
- <!-- Create the TAR file -->
- <!-- ============================================= -->
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-assembly-plugin</artifactId>
- <version>2.6</version>
- <configuration>
- <finalName>${project.artifactId}-${full.release.version}${build.type}</finalName>
- <appendAssemblyId>false</appendAssemblyId>
- <descriptor>${project.basedir}/tarball.xml</descriptor>
- </configuration>
-
- <executions>
- <execution>
- <id>assembly-tar-file</id>
- <phase>package</phase>
- <goals>
- <goal>single</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
</plugins>
-
<pluginManagement>
<plugins>
<!--This plugin's configuration is used to store Eclipse m2e settings
- only. It has no influence on the Maven build itself. -->
+ only. It has no influence on the Maven build itself. -->
<plugin>
<groupId>org.eclipse.m2e</groupId>
<artifactId>lifecycle-mapping</artifactId>
@@ -514,7 +408,7 @@
<configuration>
<lifecycleMappingMetadata>
<pluginExecutions>
-
+
<pluginExecution>
<pluginExecutionFilter>
<groupId>com.jcabi</groupId>
@@ -528,22 +422,81 @@
<execute />
</action>
</pluginExecution>
-
+
</pluginExecutions>
</lifecycleMappingMetadata>
</configuration>
</plugin>
-
+
<!-- jacbi (log injection) -->
</plugins>
</pluginManagement>
-
- </build>
-
-
-
-
+ </build>
+ <profiles>
+ <profile>
+ <id>catalog</id>
+ <activation>
+ <activeByDefault>false</activeByDefault>
+ </activation>
+
+
+ <build>
+
+ <finalName>${project.artifactId}-${full.release.version}</finalName>
+
+ <plugins>
+
+ <!-- ================================================== -->
+ <!-- Get the next versions from the properties file. -->
+ <!-- ================================================== -->
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>properties-maven-plugin</artifactId>
+ <version>1.0-alpha-2</version>
+
+ <executions>
+ <execution>
+ <inherited>false</inherited>
+ <phase>initialize</phase>
+ <goals>
+ <goal>read-project-properties</goal>
+ </goals>
+ <configuration>
+ <files>
+ <file>${project.parent.build.directory}/FullReleaseVersion.properties</file>
+ </files>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
+ </profile>
+
+
+ <profile>
+ <id>Fortify</id>
+ <activation>
+ <activeByDefault>false</activeByDefault>
+ </activation>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>com.fortify.ps.maven.plugin</groupId>
+ <artifactId>sca-maven-plugin</artifactId>
+ <version>4.30</version>
+ <configuration>
+ <source>1.8</source>
+ <buildId>${project.parent.artifactId}</buildId>
+ <toplevelArtifactId>${project.parent.artifactId}</toplevelArtifactId>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+ </profile>
+ </profiles>
</project>
diff --git a/catalog-fe/src/main/java/org/openecomp/sdc/fe/Constants.java b/catalog-fe/src/main/java/org/openecomp/sdc/fe/Constants.java
index e157efcda9..a9f5c1294e 100644
--- a/catalog-fe/src/main/java/org/openecomp/sdc/fe/Constants.java
+++ b/catalog-fe/src/main/java/org/openecomp/sdc/fe/Constants.java
@@ -1,3 +1,23 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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;
public class Constants {
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
index 93e17144c0..92e497d278 100644
--- 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
@@ -151,7 +151,7 @@ public class BackendClient {
}
backendHttpClient.close();
} catch (IOException e) {
- log.error("failed to close httpClient: " + e.getMessage());
+ log.error("failed to close httpClient: {}", e.getMessage());
}
}
@@ -168,7 +168,7 @@ public class BackendClient {
if (headerValue != null) {
httpPost.setHeader(headerName, headerValue);
} else {
- log.error("missing required header " + headerName);
+ log.error("missing required header {}", headerName);
return allHeadersAreSet;
}
}
diff --git a/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/ConfigMgrServlet.java b/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/ConfigMgrServlet.java
index 7792225742..356f9261c6 100644
--- a/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/ConfigMgrServlet.java
+++ b/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/ConfigMgrServlet.java
@@ -61,9 +61,9 @@ public class ConfigMgrServlet extends BasicServlet {
Configuration configuration = configurationManager.getConfiguration();
if (configuration == null) {
- log.warn("Configuration of type " + Configuration.class + " was not found");
+ log.warn("Configuration of type {} was not found", Configuration.class);
} else {
- log.info("The value returned from getConfig is " + configuration);
+ log.info("The value returned from getConfig is {}", configuration);
result = gson.toJson(configuration);
@@ -72,9 +72,9 @@ public class ConfigMgrServlet extends BasicServlet {
RestConfigurationInfo configuration = configurationManager.getRestClientConfiguration();
if (configuration == null) {
- log.warn("Configuration of type " + RestConfigurationInfo.class + " was not found");
+ log.warn("Configuration of type {} was not found", RestConfigurationInfo.class);
} else {
- log.info("The value returned from getConfig is " + configuration);
+ log.info("The value returned from getConfig is {}", configuration);
result = gson.toJson(configuration);
diff --git a/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/ConfigServlet.java b/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/ConfigServlet.java
index 92bb9e8743..b8d623b72e 100644
--- a/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/ConfigServlet.java
+++ b/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/ConfigServlet.java
@@ -64,13 +64,13 @@ public class ConfigServlet extends BasicServlet {
Configuration configuration = configurationSource.getAndWatchConfiguration(Configuration.class, null);
if (configuration == null) {
- log.warn("Configuration of type " + Configuration.class + " was not found");
+ log.warn("Configuration of type {} was not found", Configuration.class);
}
log.debug("{}", configuration);
if (log.isInfoEnabled()) {
log.info("Info level ENABLED...");
}
- log.info("The value returned from getConfig is " + configuration);
+ log.info("The value returned from getConfig is {}", configuration);
result = gson.toJson(configuration);
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 da5b321339..1ed6ac5c07 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
@@ -35,10 +35,6 @@ import com.jcabi.aspects.Loggable;
@Loggable(prepend = true, value = Loggable.TRACE, trim = false)
@Path("/healthCheck")
public class FeHealthCheckServlet extends BasicServlet {
-
- // private static Logger log =
- // LoggerFactory.getLogger(FeHealthCheckServlet.class.getName());
-
@GET
public Response getFEandBeHealthCheck(@Context final HttpServletRequest request) {
ServletContext context = request.getSession().getServletContext();
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 1cd28deb7a..11d4abf4af 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
@@ -85,7 +85,7 @@ public class FeProxyServlet extends SSLProxyServlet {
String serviceInstanceID = httpRequest.getHeader(Constants.X_ECOMP_SERVICE_ID_HEADER);
if (uuid != null && uuid.length() > 0) {
- // User Id for logging
+ // UserId for logging
String userId = httpRequest.getHeader(Constants.USER_ID_HEADER);
String remoteAddr = httpRequest.getRemoteAddr();
@@ -201,6 +201,7 @@ public class FeProxyServlet extends SSLProxyServlet {
if (onboardingForwardContext == null || onboardingForwardContext.isEmpty()) {
onboardingForwardContext = "/onboarding-api";
}
+ redirectedUrl = redirectedUrl.replace("/sdc1/feProxy/dcae-api", "/dcae");
redirectedUrl = redirectedUrl.replace("/sdc1/feProxy/onboarding-api", onboardingForwardContext);
redirectedUrl = redirectedUrl.replace("/sdc1/feProxy", "/sdc2");
return redirectedUrl;
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 338e8d4c01..b7fce8d912 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
@@ -40,9 +40,9 @@ import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.openecomp.sdc.common.api.Constants;
import org.openecomp.sdc.common.api.HealthCheckInfo;
+import org.openecomp.sdc.common.api.HealthCheckWrapper;
import org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckComponent;
import org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus;
-import org.openecomp.sdc.common.api.HealthCheckWrapper;
import org.openecomp.sdc.common.config.EcompErrorName;
import org.openecomp.sdc.common.impl.ExternalConfiguration;
import org.openecomp.sdc.fe.config.Configuration;
diff --git a/catalog-fe/src/main/resources/config/configuration.yaml b/catalog-fe/src/main/resources/config/configuration.yaml
index 6be93b330d..cd123ca220 100644
--- a/catalog-fe/src/main/resources/config/configuration.yaml
+++ b/catalog-fe/src/main/resources/config/configuration.yaml
@@ -17,30 +17,30 @@ beProtocol: http
beSslPort: 8443
# threadpool size for handling requests
-threadpoolSize: 50
+threadpoolSize: 50
# request processing timeout (seconds)
requestTimeout: 10
+# Determines the health check read timeout when invoking health check towards the LB (or BE whatever is configured):
healthCheckSocketTimeoutInMs: 5000
-
healthCheckIntervalInSeconds: 5
-identificationHeaderFields:
+identificationHeaderFields:
-
- &HTTP_IV_USER HTTP_IV_USER
- &iv-user iv-user
-
- &USER_ID USER_ID
- - &user-id user-id
+ - &csp-userId csp-userId
-
- &HTTP_CSP_ATTUID HTTP_CSP_ATTUID
- &csp-attuid csp-attuid
-
- - &HTTP_CSP_WSTYPE HTTP_CSP_WSTYPE
+ - &HTTP_CSP_WSTYPE HTTP_CSP_WSTYPE
- &csp-wstype csp-wstype
-optionalHeaderFields:
+optionalHeaderFields:
-
- &HTTP_CSP_FIRSTNAME HTTP_CSP_FIRSTNAME
- &csp-firstname csp-firstname
diff --git a/catalog-fe/src/main/resources/portal.properties b/catalog-fe/src/main/resources/portal.properties
index 880c4fe9e9..a146d6ef0c 100644
--- a/catalog-fe/src/main/resources/portal.properties
+++ b/catalog-fe/src/main/resources/portal.properties
@@ -1,11 +1,12 @@
# Portal REST URL, ends "/auxapi"
-ecomp_rest_url = https://portal.api.simpledemo.openecomp.org/ecompportal/auxapi
+ecomp_rest_url = https://ecomp.homer.att.com/ecompportal/auxapi
# Java implementation of interface
portal.api.impl.class = org.openecomp.sdc.be.ecomp.EcompIntImpl
# CSP-SSO URL
-ecomp_redirect_url = http://portal.api.simpledemo.openecomp.org:8989/ECOMPPORTAL/login.htm
+# ecomp_redirect_url = https://www.e-access.att.com/ecomp_portal_ist/ecompportal/process_csp
+ecomp_redirect_url = http://127.0.0.1:8989/ECOMPPORTAL/login.htm
# Cookie set by CSP-SSO
csp_cookie_name = attESSec
@@ -13,7 +14,7 @@ csp_cookie_name = attESSec
csp_gate_keeper_prod_key = PROD
# Comma-separated list of UEB server names
-ueb_url_list =
+ueb_url_list = localhost
# UEB topic where Portal listens
ecomp_portal_inbox_name = ECOMP-PORTAL-INBOX-TEST
# UEB key generated while on-boarding
diff --git a/catalog-fe/src/main/webapp/WEB-INF/web.xml b/catalog-fe/src/main/webapp/WEB-INF/web.xml
index f6d709ef58..c2127dcdca 100644
--- a/catalog-fe/src/main/webapp/WEB-INF/web.xml
+++ b/catalog-fe/src/main/webapp/WEB-INF/web.xml
@@ -39,146 +39,6 @@
<url-pattern>/lbClassicStatus</url-pattern>
</servlet-mapping>
- <!-- Proxy Server Only used for tests to simulate webSeal ## Start ## -->
-<!-- <servlet>
- <servlet-name>ProxyAdmin1</servlet-name>
- <servlet-class>org.openecomp.sdc.fe.servlets.websealmock.WebSealSimulatorServletAdmin1</servlet-class>
- <async-supported>true</async-supported>
- </servlet>
-
- <servlet-mapping>
- <servlet-name>ProxyAdmin1</servlet-name>
- <url-pattern>/proxy-admin1</url-pattern>
- </servlet-mapping>
- <servlet>
- <servlet-name>ProxyAdmin2</servlet-name>
- <servlet-class>org.openecomp.sdc.fe.servlets.websealmock.WebSealSimulatorServletAdmin2</servlet-class>
- <async-supported>true</async-supported>
- </servlet>
-
- <servlet-mapping>
- <servlet-name>ProxyAdmin2</servlet-name>
- <url-pattern>/proxy-admin2</url-pattern>
- </servlet-mapping>
- <servlet>
- <servlet-name>ProxyAdmin3</servlet-name>
- <servlet-class>org.openecomp.sdc.fe.servlets.websealmock.WebSealSimulatorServletAdmin3</servlet-class>
- <async-supported>true</async-supported>
- </servlet>
-
- <servlet-mapping>
- <servlet-name>ProxyAdmin3</servlet-name>
- <url-pattern>/proxy-admin3</url-pattern>
- </servlet-mapping>
-
- <servlet>
- <servlet-name>ProxyDesigner1</servlet-name>
- <servlet-class>org.openecomp.sdc.fe.servlets.websealmock.WebSealSimulatorServletDesigner1</servlet-class>
- <async-supported>true</async-supported>
- </servlet>
-
- <servlet-mapping>
- <servlet-name>ProxyDesigner1</servlet-name>
- <url-pattern>/proxy-designer1</url-pattern>
- </servlet-mapping>
- <servlet>
- <servlet-name>ProxyDesigner2</servlet-name>
- <servlet-class>org.openecomp.sdc.fe.servlets.websealmock.WebSealSimulatorServletDesigner2</servlet-class>
- <async-supported>true</async-supported>
- </servlet>
-
- <servlet-mapping>
- <servlet-name>ProxyDesigner2</servlet-name>
- <url-pattern>/proxy-designer2</url-pattern>
- </servlet-mapping>
- <servlet>
- <servlet-name>ProxyDesigner3</servlet-name>
- <servlet-class>org.openecomp.sdc.fe.servlets.websealmock.WebSealSimulatorServletDesigner3</servlet-class>
- <async-supported>true</async-supported>
- </servlet>
-
- <servlet-mapping>
- <servlet-name>ProxyDesigner3</servlet-name>
- <url-pattern>/proxy-designer3</url-pattern>
- </servlet-mapping>
-
- <servlet>
- <servlet-name>ProxyTester1</servlet-name>
- <servlet-class>org.openecomp.sdc.fe.servlets.websealmock.WebSealSimulatorServletTester1</servlet-class>
- <async-supported>true</async-supported>
- </servlet>
-
- <servlet-mapping>
- <servlet-name>ProxyTester1</servlet-name>
- <url-pattern>/proxy-tester1</url-pattern>
- </servlet-mapping>
- <servlet>
- <servlet-name>ProxyTester2</servlet-name>
- <servlet-class>org.openecomp.sdc.fe.servlets.websealmock.WebSealSimulatorServletTester2</servlet-class>
- <async-supported>true</async-supported>
- </servlet>
-
- <servlet-mapping>
- <servlet-name>ProxyTester2</servlet-name>
- <url-pattern>/proxy-tester2</url-pattern>
- </servlet-mapping>
-
- <servlet>
- <servlet-name>ProxyTester3</servlet-name>
- <servlet-class>org.openecomp.sdc.fe.servlets.websealmock.WebSealSimulatorServletTester3</servlet-class>
- <async-supported>true</async-supported>
- </servlet>
-
- <servlet-mapping>
- <servlet-name>ProxyTester3</servlet-name>
- <url-pattern>/proxy-tester3</url-pattern>
- </servlet-mapping>
-
- <servlet-mapping>
- <servlet-name>ProxyGovernor1</servlet-name>
- <url-pattern>/proxy-governor1</url-pattern>
- </servlet-mapping>
-
- <servlet>
- <servlet-name>ProxyGovernor1</servlet-name>
- <servlet-class>org.openecomp.sdc.fe.servlets.websealmock.WebSealSimulatorServletGovernor1</servlet-class>
- <async-supported>true</async-supported>
- </servlet>
-
- <servlet-mapping>
- <servlet-name>ProxyOps1</servlet-name>
- <url-pattern>/proxy-ops1</url-pattern>
- </servlet-mapping>
-
- <servlet>
- <servlet-name>ProxyOps1</servlet-name>
- <servlet-class>org.openecomp.sdc.fe.servlets.websealmock.WebSealSimulatorServletOps1</servlet-class>
- <async-supported>true</async-supported>
- </servlet>
-
- <servlet-mapping>
- <servlet-name>ProxyPs1</servlet-name>
- <url-pattern>/proxy-ps1</url-pattern>
- </servlet-mapping>
-
- <servlet>
- <servlet-name>ProxyPs1</servlet-name>
- <servlet-class>org.openecomp.sdc.fe.servlets.websealmock.WebSealSimulatorServletProductStrategist1</servlet-class>
- <async-supported>true</async-supported>
- </servlet>
- <servlet-mapping>
- <servlet-name>ProxyPm1</servlet-name>
- <url-pattern>/proxy-pm1</url-pattern>
- </servlet-mapping>
-
- <servlet>
- <servlet-name>ProxyPm1</servlet-name>
- <servlet-class>org.openecomp.sdc.fe.servlets.websealmock.WebSealSimulatorServletProductManger1</servlet-class>
- <async-supported>true</async-supported>
- </servlet> -->
-
- <!-- Proxy Server Only used for tests to simulate webSeal ## End ## -->
-
<!-- Fe Proxy Servlet -->
<servlet>
<servlet-name>FeProxy</servlet-name>
@@ -219,35 +79,6 @@
<url-pattern>/kibanaProxy/*</url-pattern>
</servlet-mapping>
-
-
- <filter>
- <filter-name>cross-origin-att</filter-name>
- <filter-class>org.eclipse.jetty.servlets.CrossOriginFilter</filter-class>
- <async-supported>true</async-supported>
- <init-param>
- <param-name>allowedOrigins</param-name>
- <param-value>*</param-value>
- </init-param>
- <init-param>
- <param-name>allowedMethods</param-name>
- <param-value>GET,POST,OPTIONS,DELETE,PUT,HEAD</param-value>
- </init-param>
- <init-param>
- <param-name>allowedHeaders</param-name>
- <param-value>HTTP_CSP_FIRSTNAME, HTTP_CSP_LASTNAME, USER_ID,
- HTTP_CSP_EMAIL, X-ECOMP-RequestID, origin, content-type, accept, authorization, Content-MD5,X-ECOMP-ServiceID</param-value>
- </init-param>
- <init-param>
- <param-name>allowCredential</param-name>
- <param-value>true</param-value>
- </init-param>
- </filter>
- <filter-mapping>
- <filter-name>cross-origin-att</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
-
<!--
<filter>
<filter-name>GzipFilter</filter-name>
diff --git a/catalog-fe/src/test/jasmine-standalone-2.0.0/lib/jasmine-2.0.0/boot.js b/catalog-fe/src/test/jasmine-standalone-2.0.0/lib/jasmine-2.0.0/boot.js
index b1686af19b..ec8baa0aa5 100644
--- a/catalog-fe/src/test/jasmine-standalone-2.0.0/lib/jasmine-2.0.0/boot.js
+++ b/catalog-fe/src/test/jasmine-standalone-2.0.0/lib/jasmine-2.0.0/boot.js
@@ -1,23 +1,3 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
/**
Starting with version 2.0, this file "boots" Jasmine, performing all of the necessary initialization before executing the loaded environment and all of a project's specs. This file should be loaded after `jasmine.js`, but before any project source files or spec files are loaded. Thus this file can also be used to customize Jasmine for a project.
diff --git a/catalog-fe/src/test/jasmine-standalone-2.0.0/lib/jasmine-2.0.0/console.js b/catalog-fe/src/test/jasmine-standalone-2.0.0/lib/jasmine-2.0.0/console.js
index 4e31320575..33c1698cf1 100644
--- a/catalog-fe/src/test/jasmine-standalone-2.0.0/lib/jasmine-2.0.0/console.js
+++ b/catalog-fe/src/test/jasmine-standalone-2.0.0/lib/jasmine-2.0.0/console.js
@@ -1,23 +1,3 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
/*
Copyright (c) 2008-2013 Pivotal Labs
diff --git a/catalog-fe/src/test/jasmine-standalone-2.0.0/lib/jasmine-2.0.0/jasmine-html.js b/catalog-fe/src/test/jasmine-standalone-2.0.0/lib/jasmine-2.0.0/jasmine-html.js
index f7469e97b7..985d0d1a0a 100644
--- a/catalog-fe/src/test/jasmine-standalone-2.0.0/lib/jasmine-2.0.0/jasmine-html.js
+++ b/catalog-fe/src/test/jasmine-standalone-2.0.0/lib/jasmine-2.0.0/jasmine-html.js
@@ -1,23 +1,3 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
/*
Copyright (c) 2008-2013 Pivotal Labs
diff --git a/catalog-fe/src/test/jasmine-standalone-2.0.0/lib/jasmine-2.0.0/jasmine.js b/catalog-fe/src/test/jasmine-standalone-2.0.0/lib/jasmine-2.0.0/jasmine.js
index a1390a20c5..24463ecb83 100644
--- a/catalog-fe/src/test/jasmine-standalone-2.0.0/lib/jasmine-2.0.0/jasmine.js
+++ b/catalog-fe/src/test/jasmine-standalone-2.0.0/lib/jasmine-2.0.0/jasmine.js
@@ -1,23 +1,3 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
/*
Copyright (c) 2008-2013 Pivotal Labs
diff --git a/catalog-fe/src/test/jasmine-standalone-2.0.0/spec/PlayerSpec.js b/catalog-fe/src/test/jasmine-standalone-2.0.0/spec/PlayerSpec.js
index 976c0de51a..f17521fde3 100644
--- a/catalog-fe/src/test/jasmine-standalone-2.0.0/spec/PlayerSpec.js
+++ b/catalog-fe/src/test/jasmine-standalone-2.0.0/spec/PlayerSpec.js
@@ -1,23 +1,3 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
describe("Player", function() {
var player;
var song;
diff --git a/catalog-fe/src/test/jasmine-standalone-2.0.0/spec/SpecHelper.js b/catalog-fe/src/test/jasmine-standalone-2.0.0/spec/SpecHelper.js
index b6b66da78a..578b3e8626 100644
--- a/catalog-fe/src/test/jasmine-standalone-2.0.0/spec/SpecHelper.js
+++ b/catalog-fe/src/test/jasmine-standalone-2.0.0/spec/SpecHelper.js
@@ -1,23 +1,3 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
beforeEach(function () {
jasmine.addMatchers({
toBePlaying: function () {
diff --git a/catalog-fe/src/test/jasmine-standalone-2.0.0/src/Player.js b/catalog-fe/src/test/jasmine-standalone-2.0.0/src/Player.js
index 20be99a3ba..fcce8268c0 100644
--- a/catalog-fe/src/test/jasmine-standalone-2.0.0/src/Player.js
+++ b/catalog-fe/src/test/jasmine-standalone-2.0.0/src/Player.js
@@ -1,23 +1,3 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
function Player() {
}
Player.prototype.play = function(song) {
@@ -39,4 +19,4 @@ Player.prototype.resume = function() {
Player.prototype.makeFavorite = function() {
this.currentlyPlayingSong.persistFavoriteStatus(true);
-};
+}; \ No newline at end of file
diff --git a/catalog-fe/src/test/jasmine-standalone-2.0.0/src/Song.js b/catalog-fe/src/test/jasmine-standalone-2.0.0/src/Song.js
index c16d77e378..a8a3f2ddd4 100644
--- a/catalog-fe/src/test/jasmine-standalone-2.0.0/src/Song.js
+++ b/catalog-fe/src/test/jasmine-standalone-2.0.0/src/Song.js
@@ -1,27 +1,7 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
function Song() {
}
Song.prototype.persistFavoriteStatus = function(value) {
// something complicated
throw new Error("not yet implemented");
-};
+}; \ No newline at end of file
diff --git a/catalog-fe/src/test/java/org/openecomp/sdc/ContentDisposiotionDelegator.java b/catalog-fe/src/test/java/org/openecomp/sdc/ContentDisposiotionDelegator.java
index 9b873879e5..d64aee20f2 100644
--- a/catalog-fe/src/test/java/org/openecomp/sdc/ContentDisposiotionDelegator.java
+++ b/catalog-fe/src/test/java/org/openecomp/sdc/ContentDisposiotionDelegator.java
@@ -29,7 +29,6 @@ public class ContentDisposiotionDelegator extends FormDataContentDisposition {
public ContentDisposiotionDelegator(String type, String name, String fileName, Date creationDate,
Date modificationDate, Date readDate, long size) {
super(type, name, fileName, creationDate, modificationDate, readDate, size);
- // TODO Auto-generated constructor stub
}
}
diff --git a/catalog-fe/src/test/java/org/openecomp/sdc/TestExternalConfiguration.java b/catalog-fe/src/test/java/org/openecomp/sdc/TestExternalConfiguration.java
index ecbc055a81..78622f1abb 100644
--- a/catalog-fe/src/test/java/org/openecomp/sdc/TestExternalConfiguration.java
+++ b/catalog-fe/src/test/java/org/openecomp/sdc/TestExternalConfiguration.java
@@ -57,7 +57,6 @@ public class TestExternalConfiguration<T extends Object> {
try {
Thread.currentThread().sleep(100 * 1000);
} catch (InterruptedException e) {
- // TODO Auto-generated catch block
e.printStackTrace();
}
diff --git a/catalog-fe/src/test/resources/config/catalog-fe/configuration.yaml b/catalog-fe/src/test/resources/config/catalog-fe/configuration.yaml
index 22bfee90f9..5cc22fde72 100644
--- a/catalog-fe/src/test/resources/config/catalog-fe/configuration.yaml
+++ b/catalog-fe/src/test/resources/config/catalog-fe/configuration.yaml
@@ -50,6 +50,16 @@ optionalHeaderFields:
-
- &HTTP_IV_REMOTE_ADDRESS HTTP_IV_REMOTE_ADDRESS
- &iv-remote-address iv-remote-address
+
+forwardHeaderFields:
+ - *HTTP_IV_USER
+ - *USER_ID
+ - *HTTP_CSP_FIRSTNAME
+ - *HTTP_CSP_LASTNAME
+ - *HTTP_IV_REMOTE_ADDRESS
+ - *HTTP_CSP_WSTYPE
+ - Content-MD5
+ - Content-Type
version: 1.0
diff --git a/catalog-fe/src/test/spec/codeSpec.js b/catalog-fe/src/test/spec/codeSpec.js
index 1cb5da0b8a..b4c4bd66d7 100644
--- a/catalog-fe/src/test/spec/codeSpec.js
+++ b/catalog-fe/src/test/spec/codeSpec.js
@@ -1,23 +1,3 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
describe("General", function() {
diff --git a/catalog-fe/src/test/testScripts/filesContents.js b/catalog-fe/src/test/testScripts/filesContents.js
index b2e7aa2c65..78de1447e0 100644
--- a/catalog-fe/src/test/testScripts/filesContents.js
+++ b/catalog-fe/src/test/testScripts/filesContents.js
@@ -1,23 +1,3 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
var normativeTypesRootYml = "tosca_definitions_version: tosca_simple_yaml_1_0_0_wd03"+
"template_name: tosca-normative-types-root"+
@@ -204,4 +184,4 @@ var installMySqlSH =
'sudo /etc/init.d/mysql stop'+
'sudo rm -rf /var/lib/apt/lists/*'+
'sudo rm -rf /var/lib/mysql/*'+
-'echo "MySQL Installation complete."';
+'echo "MySQL Installation complete."'; \ No newline at end of file
diff --git a/catalog-fe/src/test/testScripts/jasmine-fixture.js b/catalog-fe/src/test/testScripts/jasmine-fixture.js
index 18ff8c6418..3815731fd2 100644
--- a/catalog-fe/src/test/testScripts/jasmine-fixture.js
+++ b/catalog-fe/src/test/testScripts/jasmine-fixture.js
@@ -1,23 +1,3 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
/* jasmine-fixture - 1.2.2
* Makes injecting HTML snippets into the DOM easy & clean!
* https://github.com/searls/jasmine-fixture
diff --git a/catalog-fe/tarball.xml b/catalog-fe/tarball.xml
deleted file mode 100644
index 87b944bd4e..0000000000
--- a/catalog-fe/tarball.xml
+++ /dev/null
@@ -1,32 +0,0 @@
-<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
-xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
- <id>bin</id>
- <formats>
- <format>tar</format>
- </formats>
- <files>
- <file>
- <source>${project.build.directory}/${project.artifactId}-${project.version}.war</source>
- <outputDirectory>./</outputDirectory>
- <destName>${project.artifactId}-${project.version}.war</destName>
- </file>
- <file>
- <source>src/main/resources/jetty-ipaccess.xml</source>
- <outputDirectory>./</outputDirectory>
- <destName>jetty-ipaccess.xml</destName>
- </file>
- </files>
-
- <fileSets>
- <fileSet>
- <directory>src/main/resources/config</directory>
- <outputDirectory>config</outputDirectory>
- </fileSet>
- <fileSet>
- <directory>src/main/resources/scripts</directory>
- <outputDirectory>scripts</outputDirectory>
- </fileSet>
- </fileSets>
-
-</assembly>
diff --git a/catalog-model/pom.xml b/catalog-model/pom.xml
index ac46c29a9a..a4538fd3db 100644
--- a/catalog-model/pom.xml
+++ b/catalog-model/pom.xml
@@ -6,210 +6,101 @@
<groupId>org.openecomp.sdc.be</groupId>
<artifactId>catalog-model</artifactId>
-
<parent>
<groupId>org.openecomp.sdc</groupId>
<artifactId>sdc-main</artifactId>
<version>1.1.0-SNAPSHOT</version>
</parent>
-
-
<dependencies>
+ <!-- Common of SDC -->
<dependency>
- <groupId>org.testng</groupId>
- <artifactId>testng</artifactId>
- <version>6.9.10</version>
- <scope>test</scope>
- </dependency>
-
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-api</artifactId>
- <version>1.7.10</version>
- <scope>provided</scope>
- </dependency>
-
- <!-- yaml to object converter -->
- <dependency>
- <groupId>org.yaml</groupId>
- <artifactId>snakeyaml</artifactId>
- <version>1.14</version>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>commons-logging</groupId>
- <artifactId>commons-logging</artifactId>
- <version>1.2.1-SNAPSHOT</version>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>commons-codec</groupId>
- <artifactId>commons-codec</artifactId>
- <version>2.0-SNAPSHOT</version>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-core</artifactId>
- <version>${spring.version}</version>
+ <groupId>org.openecomp.sdc</groupId>
+ <artifactId>common-app-api</artifactId>
+ <version>${project.version}</version>
<scope>provided</scope>
</dependency>
-
+
<dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-beans</artifactId>
- <version>${spring.version}</version>
+ <groupId>org.openecomp.sdc.be</groupId>
+ <artifactId>common-be</artifactId>
+ <version>${project.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-context</artifactId>
- <version>${spring.version}</version>
+ <groupId>ch.qos.logback</groupId>
+ <artifactId>logback-classic</artifactId>
+ <version>${logback.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-context-support</artifactId>
- <version>${spring.version}</version>
+ <groupId>ch.qos.logback</groupId>
+ <artifactId>logback-core</artifactId>
+ <version>${logback.version}</version>
<scope>provided</scope>
</dependency>
+ <!-- catalog dao -->
<dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-messaging</artifactId>
- <version>${spring.version}</version>
+ <groupId>org.openecomp.sdc.be</groupId>
+ <artifactId>catalog-dao</artifactId>
+ <version>${project.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-web</artifactId>
- <version>${spring.version}</version>
+ <groupId>com.google.guava</groupId>
+ <artifactId>guava</artifactId>
+ <version>${guava.version}</version><!--$NO-MVN-MAN-VER$ -->
<scope>provided</scope>
</dependency>
<dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-webmvc</artifactId>
- <version>${spring.version}</version>
+ <groupId>org.functionaljava</groupId>
+ <artifactId>functionaljava</artifactId>
+ <version>${functionaljava.version}</version>
<scope>provided</scope>
</dependency>
+ <!-- spring -->
<dependency>
<groupId>org.springframework</groupId>
- <artifactId>spring-aop</artifactId>
+ <artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
- <artifactId>spring-aspects</artifactId>
+ <artifactId>spring-context</artifactId>
<version>${spring.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-test</artifactId>
- <version>${spring.version}</version>
- <scope>test</scope>
- </dependency>
-
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-expression</artifactId>
- <version>${spring.version}</version>
- <scope>test</scope>
- </dependency>
-
-
- <!-- Common of SD&C -->
- <dependency>
- <groupId>org.openecomp.sdc</groupId>
- <artifactId>common-app-api</artifactId>
- <version>${common-app-api.version}</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.openecomp.sdc.be</groupId>
- <artifactId>common-be</artifactId>
- <version>${common-be.version}</version>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>ch.qos.logback</groupId>
- <artifactId>logback-classic</artifactId>
- <version>${logback.version}</version>
- <scope>provided</scope>
+ <groupId>javax.validation</groupId>
+ <artifactId>validation-api</artifactId>
+ <version>1.1.0.Final</version>
</dependency>
<dependency>
- <groupId>ch.qos.logback</groupId>
- <artifactId>logback-core</artifactId>
- <version>${logback.version}</version>
- <scope>provided</scope>
- </dependency>
-
- <!-- catalog dao -->
- <dependency>
- <groupId>org.openecomp.sdc.be</groupId>
- <artifactId>catalog-dao</artifactId>
- <version>${catalog-dao.version}</version>
- <scope>provided</scope>
- </dependency>
-
- <!-- -->
- <dependency>
- <groupId>com.google.guava</groupId>
- <artifactId>guava</artifactId>
- <version>${guava.version}</version><!--$NO-MVN-MAN-VER$-->
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>org.functionaljava</groupId>
- <artifactId>functionaljava</artifactId>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>javax.servlet</groupId>
- <artifactId>servlet-api</artifactId>
- <scope>provided</scope>
- </dependency>
-
- <!-- spring -->
-
- <dependency>
- <groupId>javax.validation</groupId>
- <artifactId>validation-api</artifactId>
- <version>1.1.0.Final</version>
+ <groupId>org.hibernate</groupId>
+ <artifactId>hibernate-validator</artifactId>
+ <version>5.0.1.Final</version>
</dependency>
+ <!-- Gson -->
<dependency>
- <groupId>org.hibernate</groupId>
- <artifactId>hibernate-validator</artifactId>
- <version>5.3.4.Final</version>
- </dependency>
-
- <!-- Gson -->
- <dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
- <version>2.3.1</version>
+ <version>${gson.version}</version>
<scope>provided</scope>
</dependency>
-
- <!-- TITAN -->
+
+ <!-- TITAN -->
<dependency>
<groupId>com.thinkaurelius.titan</groupId>
<artifactId>titan-core</artifactId>
@@ -239,30 +130,30 @@
</exclusion>
</exclusions>
</dependency>
- <!-- TITAN END-->
-
- <dependency>
+ <!-- TITAN END -->
+
+ <dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${lang3.version}</version>
<scope>provided</scope>
</dependency>
-
- <!-- http client -->
+
+ <!-- http client -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
- <version>${httpclient.version}</version>
+ <version>${httpclient.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
- <version>${httpcore.version}</version>
+ <version>${httpcore.version}</version>
<scope>provided</scope>
</dependency>
-
+
<!-- CASSANDRA -->
<dependency>
<groupId>com.datastax.cassandra</groupId>
@@ -277,56 +168,60 @@
<scope>provided</scope>
</dependency>
<!-- CASSANDRA END -->
-
- <!-- test -->
-
-
+
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
- <version>4.12</version>
+ <version>${junit.version}</version>
<scope>test</scope>
</dependency>
-
+
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
- <version>1.10.19</version>
+ <version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
- <groupId>org.aspectj</groupId>
- <artifactId>aspectjrt</artifactId>
- <version>${aspectjrt.version}</version>
- <!--<version>1.7.4</version>-->
- <scope>test</scope>
- </dependency>
-
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-test</artifactId>
+ <version>${spring.version}</version>
+ <scope>test</scope>
+ </dependency>
+
<dependency>
- <groupId>org.aspectj</groupId>
- <artifactId>aspectjweaver</artifactId>
- <version>1.7.4</version>
- <scope>test</scope>
- </dependency>
-
+ <groupId>org.aspectj</groupId>
+ <artifactId>aspectjrt</artifactId>
+ <version>${aspectj.version}</version>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.aspectj</groupId>
+ <artifactId>aspectjweaver</artifactId>
+ <version>${aspectj.version}</version>
+ <scope>test</scope>
+ </dependency>
+
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
-
+
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<scope>test</scope>
<version>4.0.7.RELEASE</version>
</dependency>
-
+
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-jci-core</artifactId>
+ <version>${commons-jci-core.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/AdditionalInformationDefinition.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/AdditionalInformationDefinition.java
index 9ad0718e71..b155e50d33 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/AdditionalInformationDefinition.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/AdditionalInformationDefinition.java
@@ -24,6 +24,7 @@ import java.io.Serializable;
import java.util.List;
import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterInfo;
public class AdditionalInformationDefinition extends AdditionalInfoParameterDataDefinition implements Serializable {
@@ -34,7 +35,6 @@ public class AdditionalInformationDefinition extends AdditionalInfoParameterData
private String parentUniqueId;
- private List<AdditionalInfoParameterInfo> parameters;
public AdditionalInformationDefinition() {
super();
@@ -44,15 +44,19 @@ public class AdditionalInformationDefinition extends AdditionalInfoParameterData
List<AdditionalInfoParameterInfo> parameters) {
super(p);
this.parentUniqueId = parentUniqueId;
- this.parameters = parameters;
+ setParameters(parameters);
+ }
+ public AdditionalInformationDefinition(AdditionalInfoParameterDataDefinition p){
+ this.setUniqueId(p.getUniqueId());
+ this.setCreationTime(p.getCreationTime());
+ this.setModificationTime(p.getModificationTime());
+ setParameters(p.getParameters());
}
-
public AdditionalInformationDefinition(AdditionalInformationDefinition pd) {
this.setUniqueId(pd.getUniqueId());
this.setCreationTime(pd.getCreationTime());
this.setModificationTime(pd.getModificationTime());
this.parentUniqueId = pd.parentUniqueId;
- this.parameters = pd.parameters;
}
public String getParentUniqueId() {
@@ -63,17 +67,11 @@ public class AdditionalInformationDefinition extends AdditionalInfoParameterData
this.parentUniqueId = parentUniqueId;
}
- public List<AdditionalInfoParameterInfo> getParameters() {
- return parameters;
- }
-
- public void setParameters(List<AdditionalInfoParameterInfo> parameters) {
- this.parameters = parameters;
- }
+
@Override
public String toString() {
- return "AdditionalInformationDefinition [parameters=" + parameters + ", parentUniqueId=" + parentUniqueId + " "
+ return "AdditionalInformationDefinition [ parentUniqueId=" + parentUniqueId + " "
+ super.toString() + "]";
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ArtifactDefinition.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ArtifactDefinition.java
index f822e67715..434422e57b 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ArtifactDefinition.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ArtifactDefinition.java
@@ -22,8 +22,11 @@ package org.openecomp.sdc.be.model;
import java.io.Serializable;
import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.HeatParameterDataDefinition;
public class ArtifactDefinition extends ArtifactDataDefinition implements Serializable {
@@ -37,9 +40,6 @@ public class ArtifactDefinition extends ArtifactDataDefinition implements Serial
*/
private byte[] payloadData;
- private List<HeatParameterDefinition> heatParameters;
-
- private String generatedFromId;
public byte[] getPayloadData() {
return payloadData;
@@ -58,32 +58,45 @@ public class ArtifactDefinition extends ArtifactDataDefinition implements Serial
public ArtifactDefinition() {
super();
}
+ public ArtifactDefinition(Map<String, Object> art) {
+ super(art);
+ }
public ArtifactDefinition(ArtifactDataDefinition a) {
super(a);
}
+
+ public ArtifactDefinition(ArtifactDefinition a) {
+ super(a);
+ this.payloadData = a.payloadData;
+
+ }
public ArtifactDefinition(ArtifactDataDefinition a, String payloadData) {
super(a);
setPayloadData(payloadData);
}
- public List<HeatParameterDefinition> getHeatParameters() {
- return heatParameters;
+ public List<HeatParameterDefinition> getListHeatParameters() {
+ List<HeatParameterDefinition> res = null;
+ List<HeatParameterDataDefinition> heatParameters = super.getHeatParameters();
+ if(heatParameters != null){
+ res = heatParameters.stream().map(hp -> new HeatParameterDefinition(hp)).collect(Collectors.toList());
+ }
+ return res;
}
- public void setHeatParameters(List<HeatParameterDefinition> properties) {
- this.heatParameters = properties;
+ public void setListHeatParameters(List<HeatParameterDefinition> properties) {
+ List<HeatParameterDataDefinition> res = null;
+
+ if(properties != null){
+ res = properties.stream().map(hp -> new HeatParameterDataDefinition(hp)).collect(Collectors.toList());
+ }
+ super.setHeatParameters(res);
}
- public String getGeneratedFromId() {
- return generatedFromId;
- }
- public void setGeneratedFromId(String generatedFromId) {
- this.generatedFromId = generatedFromId;
- }
public boolean checkEsIdExist() {
if ((getEsId() != null) && (!getEsId().trim().isEmpty())) {
@@ -96,8 +109,7 @@ public class ArtifactDefinition extends ArtifactDataDefinition implements Serial
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
- result = prime * result + ((generatedFromId == null) ? 0 : generatedFromId.hashCode());
- result = prime * result + ((heatParameters == null) ? 0 : heatParameters.hashCode());
+
result = prime * result + ((payloadData == null) ? 0 : payloadData.hashCode());
return result;
}
@@ -111,23 +123,8 @@ public class ArtifactDefinition extends ArtifactDataDefinition implements Serial
if (getClass() != obj.getClass())
return false;
ArtifactDefinition other = (ArtifactDefinition) obj;
- if (generatedFromId == null) {
- if (other.generatedFromId != null)
- return false;
- } else if (!generatedFromId.equals(other.generatedFromId))
- return false;
- if (heatParameters == null) {
- if (other.heatParameters != null)
- return false;
- } else if (heatParameters.size() != other.heatParameters.size())
- return false;
- else {
- for (HeatParameterDefinition heatParam : heatParameters) {
- if (!other.heatParameters.contains(heatParam)) {
- return false;
- }
- }
- }
+
+
if (payloadData == null) {
if (other.payloadData != null)
return false;
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/CapabilityDefinition.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/CapabilityDefinition.java
index 61ba356aa1..548f72df9c 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/CapabilityDefinition.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/CapabilityDefinition.java
@@ -24,28 +24,20 @@ import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
+import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
+import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+
/**
* Specifies the capabilities that the Node Type exposes.
*/
-public class CapabilityDefinition implements Serializable {
+public class CapabilityDefinition extends CapabilityDataDefinition implements Serializable {
/**
*
*/
private static final long serialVersionUID = -3871825415338268030L;
- private String uniqueId;
-
- private String description;
-
- private String name;
-
- /** Identifies the type of the capability. */
- private String type;
-
- private List<String> validSourceTypes;
-
- private List<String> capabilitySources;
+
/**
* The properties field contains all properties defined for
* CapabilityDefinition
@@ -53,138 +45,32 @@ public class CapabilityDefinition implements Serializable {
private List<ComponentInstanceProperty> properties;
// specifies the resource instance holding this requirement
- private String ownerId;
- private String ownerName;
- private String minOccurrences;
- private String maxOccurrences;
+
public CapabilityDefinition() {
super();
}
+
+ public CapabilityDefinition(CapabilityDataDefinition cap) {
+ super(cap);
+ }
public CapabilityDefinition(CapabilityDefinition other) {
- this.uniqueId = other.uniqueId;
- this.description = other.description;
- this.name = other.name;
- this.type = other.type;
- if (other.validSourceTypes != null) {
- this.validSourceTypes = new ArrayList<>(other.validSourceTypes);
- }
- if (other.capabilitySources != null) {
- this.capabilitySources = new ArrayList<>(other.capabilitySources);
- }
+ super((CapabilityDefinition)other);
+
if (other.properties != null) {
this.properties = new ArrayList<>(other.properties);
}
- this.ownerId = other.ownerId;
- this.ownerName = other.ownerName;
- this.minOccurrences = other.minOccurrences;
- this.maxOccurrences = other.maxOccurrences;
- }
-
- public String getUniqueId() {
- return uniqueId;
- }
-
- public void setUniqueId(String uniqueId) {
- this.uniqueId = uniqueId;
- }
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- 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<String> getValidSourceTypes() {
- return validSourceTypes;
- }
-
- public void setValidSourceTypes(List<String> validSourceTypes) {
- this.validSourceTypes = validSourceTypes;
- }
-
- public List<String> getCapabilitySources() {
- return capabilitySources;
- }
-
- public List<ComponentInstanceProperty> getProperties() {
- return properties;
- }
-
- public void setProperties(List<ComponentInstanceProperty> properties) {
- this.properties = properties;
- }
-
- public void setCapabilitySources(List<String> capabilitySources) {
- this.capabilitySources = capabilitySources;
- }
-
- public String getOwnerId() {
- return ownerId;
+
}
- public void setOwnerId(String ownerId) {
- this.ownerId = ownerId;
- }
-
- public String getOwnerName() {
- return ownerName;
- }
-
- public void setOwnerName(String ownerName) {
- this.ownerName = ownerName;
- }
-
- public String getMinOccurrences() {
- return minOccurrences;
- }
-
- public void setMinOccurrences(String minOccurrences) {
- this.minOccurrences = minOccurrences;
- }
-
- public String getMaxOccurrences() {
- return maxOccurrences;
- }
- public void setMaxOccurrences(String maxOccurrences) {
- this.maxOccurrences = maxOccurrences;
- }
@Override
public int hashCode() {
final int prime = 31;
- int result = 1;
- result = prime * result + ((capabilitySources == null) ? 0 : capabilitySources.hashCode());
- result = prime * result + ((description == null) ? 0 : description.hashCode());
- result = prime * result + ((maxOccurrences == null) ? 0 : maxOccurrences.hashCode());
- result = prime * result + ((minOccurrences == null) ? 0 : minOccurrences.hashCode());
- result = prime * result + ((name == null) ? 0 : name.hashCode());
- result = prime * result + ((ownerId == null) ? 0 : ownerId.hashCode());
- result = prime * result + ((ownerName == null) ? 0 : ownerName.hashCode());
+ int result = super.hashCode();
result = prime * result + ((properties == null) ? 0 : properties.hashCode());
- result = prime * result + ((type == null) ? 0 : type.hashCode());
- result = prime * result + ((uniqueId == null) ? 0 : uniqueId.hashCode());
- result = prime * result + ((validSourceTypes == null) ? 0 : validSourceTypes.hashCode());
return result;
}
@@ -192,75 +78,34 @@ public class CapabilityDefinition implements Serializable {
public boolean equals(Object obj) {
if (this == obj)
return true;
- if (obj == null)
+ if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
CapabilityDefinition other = (CapabilityDefinition) obj;
- if (capabilitySources == null) {
- if (other.capabilitySources != null)
- return false;
- } else if (!capabilitySources.equals(other.capabilitySources))
- return false;
- if (description == null) {
- if (other.description != null)
- return false;
- } else if (!description.equals(other.description))
- return false;
- if (maxOccurrences == null) {
- if (other.maxOccurrences != null)
- return false;
- } else if (!maxOccurrences.equals(other.maxOccurrences))
- return false;
- if (minOccurrences == null) {
- if (other.minOccurrences != null)
- return false;
- } else if (!minOccurrences.equals(other.minOccurrences))
- return false;
- if (name == null) {
- if (other.name != null)
- return false;
- } else if (!name.equals(other.name))
- return false;
- if (ownerId == null) {
- if (other.ownerId != null)
- return false;
- } else if (!ownerId.equals(other.ownerId))
- return false;
- if (ownerName == null) {
- if (other.ownerName != null)
- return false;
- } else if (!ownerName.equals(other.ownerName))
- return false;
if (properties == null) {
if (other.properties != null)
return false;
} else if (!properties.equals(other.properties))
return false;
- if (type == null) {
- if (other.type != null)
- return false;
- } else if (!type.equals(other.type))
- return false;
- if (uniqueId == null) {
- if (other.uniqueId != null)
- return false;
- } else if (!uniqueId.equals(other.uniqueId))
- return false;
- if (validSourceTypes == null) {
- if (other.validSourceTypes != null)
- return false;
- } else if (!validSourceTypes.equals(other.validSourceTypes))
- return false;
return true;
}
@Override
public String toString() {
- return "CapabilityDefinition [uniqueId=" + uniqueId + ", description=" + description + ", name=" + name
- + ", type=" + type + ", validSourceTypes=" + validSourceTypes + ", capabilitySources="
- + capabilitySources + ", properties=" + properties + ", ownerId=" + ownerId + ", ownerName=" + ownerName
- + ", minOccurrences=" + minOccurrences + ", maxOccurrences=" + maxOccurrences + "]";
+ return "CapabilityDefinition [properties=" + properties + "]";
+ }
+
+ public List<ComponentInstanceProperty> getProperties() {
+ return properties;
}
+ public void setProperties(List<ComponentInstanceProperty> properties) {
+ this.properties = properties;
+ }
+
+
+
+
+
}
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 57a70de388..6ccb49a4b3 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
@@ -27,6 +27,7 @@ import java.util.Map;
import java.util.Objects;
import org.codehaus.jackson.annotate.JsonIgnore;
+import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.model.category.CategoryDefinition;
import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
@@ -45,14 +46,6 @@ public abstract class Component implements Serializable {
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 List<RequirementCapabilityRelDef> componentInstancesRelations;
@@ -70,7 +63,28 @@ public abstract class Component implements Serializable {
private List<InputDefinition> inputs;
private List<GroupDefinition> groups;
+
+ private String derivedFromGenericType;
+ private String derivedFromGenericVersion;
+ private String toscaType;
+ protected List<AdditionalInformationDefinition> additionalInformation;
+
+ public String getDerivedFromGenericVersion() {
+ return derivedFromGenericVersion;
+ }
+ public void setDerivedFromGenericVersion(String derivedFromGenericVersion) {
+ this.derivedFromGenericVersion = derivedFromGenericVersion;
+ }
+
+ public String getDerivedFromGenericType() {
+ return derivedFromGenericType;
+ }
+
+ public void setDerivedFromGenericType(String derivedFromGenericType) {
+ this.derivedFromGenericType = derivedFromGenericType;
+ }
+
public Component(ComponentMetadataDefinition componentMetadataDefinition) {
this.componentMetadataDefinition = componentMetadataDefinition;
}
@@ -136,6 +150,10 @@ public abstract class Component implements Serializable {
componentMetadataDefinition.getMetadataDataDefinition().setTags(tags);
}
+ public void setConformanceLevel(String conformanceLevel) {
+ componentMetadataDefinition.getMetadataDataDefinition().setConformanceLevel(conformanceLevel);
+ }
+
public void setIcon(String icon) {
componentMetadataDefinition.getMetadataDataDefinition().setIcon(icon);
}
@@ -145,35 +163,35 @@ public abstract class Component implements Serializable {
}
public String getCreatorUserId() {
- return creatorUserId;
+ return this.componentMetadataDefinition.getMetadataDataDefinition().getCreatorUserId();
}
public void setCreatorUserId(String creatorUserId) {
- this.creatorUserId = creatorUserId;
+ this.componentMetadataDefinition.getMetadataDataDefinition().setCreatorUserId(creatorUserId);
}
public String getCreatorFullName() {
- return creatorFullName;
+ return this.componentMetadataDefinition.getMetadataDataDefinition().getCreatorFullName();
}
public void setCreatorFullName(String creatorFullName) {
- this.creatorFullName = creatorFullName;
+ this.componentMetadataDefinition.getMetadataDataDefinition().setCreatorFullName(creatorFullName);
}
public String getLastUpdaterUserId() {
- return lastUpdaterUserId;
+ return this.componentMetadataDefinition.getMetadataDataDefinition().getLastUpdaterUserId();
}
public void setLastUpdaterUserId(String lastUpdaterUserId) {
- this.lastUpdaterUserId = lastUpdaterUserId;
+ this.componentMetadataDefinition.getMetadataDataDefinition().setLastUpdaterUserId(lastUpdaterUserId);
}
public String getLastUpdaterFullName() {
- return lastUpdaterFullName;
+ return this.componentMetadataDefinition.getMetadataDataDefinition().getLastUpdaterFullName();
}
public void setLastUpdaterFullName(String lastUpdaterFullName) {
- this.lastUpdaterFullName = lastUpdaterFullName;
+ this.componentMetadataDefinition.getMetadataDataDefinition().setLastUpdaterFullName(lastUpdaterFullName);
}
public String getName() {
@@ -212,6 +230,10 @@ public abstract class Component implements Serializable {
return componentMetadataDefinition.getMetadataDataDefinition().getTags();
}
+ public String getConformanceLevel() {
+ return componentMetadataDefinition.getMetadataDataDefinition().getConformanceLevel();
+ }
+
public String getIcon() {
return componentMetadataDefinition.getMetadataDataDefinition().getIcon();
}
@@ -283,11 +305,11 @@ public abstract class Component implements Serializable {
}
public ComponentTypeEnum getComponentType() {
- return componentType;
+ return this.componentMetadataDefinition.getMetadataDataDefinition().getComponentType();
}
public void setComponentType(ComponentTypeEnum componentType) {
- this.componentType = componentType;
+ this.componentMetadataDefinition.getMetadataDataDefinition().setComponentType(componentType);
}
public Map<String, List<CapabilityDefinition>> getCapabilities() {
@@ -394,11 +416,11 @@ public abstract class Component implements Serializable {
result = prime * result + ((artifacts == null) ? 0 : artifacts.hashCode());
result = prime * result + ((categories == null) ? 0 : categories.hashCode());
result = prime * result + ((componentMetadataDefinition == null) ? 0 : componentMetadataDefinition.hashCode());
- result = prime * result + ((creatorUserId == null) ? 0 : creatorUserId.hashCode());
- result = prime * result + ((creatorFullName == null) ? 0 : creatorFullName.hashCode());
+// result = prime * result + ((creatorUserId == null) ? 0 : creatorUserId.hashCode());
+// result = prime * result + ((creatorFullName == null) ? 0 : creatorFullName.hashCode());
result = prime * result + ((deploymentArtifacts == null) ? 0 : deploymentArtifacts.hashCode());
- result = prime * result + ((lastUpdaterUserId == null) ? 0 : lastUpdaterUserId.hashCode());
- result = prime * result + ((lastUpdaterFullName == null) ? 0 : lastUpdaterFullName.hashCode());
+// result = prime * result + ((lastUpdaterUserId == null) ? 0 : lastUpdaterUserId.hashCode());
+// result = prime * result + ((lastUpdaterFullName == null) ? 0 : lastUpdaterFullName.hashCode());
result = prime * result + ((capabilities == null) ? 0 : capabilities.hashCode());
result = prime * result + ((requirements == null) ? 0 : requirements.hashCode());
result = prime * result + ((componentInstances == null) ? 0 : componentInstances.hashCode());
@@ -409,6 +431,8 @@ 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 + ((derivedFromGenericType == null) ? 0 : derivedFromGenericType.hashCode());
+ result = prime * result + ((derivedFromGenericVersion == null) ? 0 : derivedFromGenericVersion.hashCode());
return result;
}
@@ -436,31 +460,31 @@ public abstract class Component implements Serializable {
return false;
} else if (!componentMetadataDefinition.equals(other.componentMetadataDefinition))
return false;
- if (creatorUserId == null) {
- if (other.creatorUserId != null)
- return false;
- } else if (!creatorUserId.equals(other.creatorUserId))
- return false;
- if (creatorFullName == null) {
- if (other.creatorFullName != null)
- return false;
- } else if (!creatorFullName.equals(other.creatorFullName))
- return false;
+// if (creatorUserId == null) {
+// if (other.creatorUserId != null)
+// return false;
+// } else if (!creatorUserId.equals(other.creatorUserId))
+// return false;
+// if (creatorFullName == null) {
+// if (other.creatorFullName != null)
+// return false;
+// } else if (!creatorFullName.equals(other.creatorFullName))
+// return false;
if (deploymentArtifacts == null) {
if (other.deploymentArtifacts != null)
return false;
} else if (!deploymentArtifacts.equals(other.deploymentArtifacts))
return false;
- if (lastUpdaterUserId == null) {
- if (other.lastUpdaterUserId != null)
- return false;
- } else if (!lastUpdaterUserId.equals(other.lastUpdaterUserId))
- return false;
- if (lastUpdaterFullName == null) {
- if (other.lastUpdaterFullName != null)
- return false;
- } else if (!lastUpdaterFullName.equals(other.lastUpdaterFullName))
- return false;
+// if (lastUpdaterUserId == null) {
+// if (other.lastUpdaterUserId != null)
+// return false;
+// } else if (!lastUpdaterUserId.equals(other.lastUpdaterUserId))
+// return false;
+// if (lastUpdaterFullName == null) {
+// if (other.lastUpdaterFullName != null)
+// return false;
+// } else if (!lastUpdaterFullName.equals(other.lastUpdaterFullName))
+// return false;
if (componentInstances == null) {
if (other.componentInstances != null)
return false;
@@ -498,6 +522,16 @@ public abstract class Component implements Serializable {
return false;
} else if (!groups.equals(other.groups))
return false;
+ if (derivedFromGenericType == null) {
+ if (other.derivedFromGenericType != null)
+ return false;
+ } else if (!derivedFromGenericType.equals(other.derivedFromGenericType))
+ return false;
+ if (derivedFromGenericVersion == null) {
+ if (other.derivedFromGenericVersion != null)
+ return false;
+ } else if (!derivedFromGenericVersion.equals(other.derivedFromGenericVersion))
+ return false;
return true;
}
@@ -595,4 +629,49 @@ public abstract class Component implements Serializable {
public void setSpecificComponetTypeArtifacts(Map<String, ArtifactDefinition> specificComponentTypeArtifacts) {
// Implement where needed
}
+
+ public void setMetadataDefinition(ComponentMetadataDefinition metadataDefinition) {
+ this.componentMetadataDefinition = metadataDefinition;
+ }
+
+ public String fetchGenericTypeToscaNameFromConfig(){
+ // Implement where needed
+ return ConfigurationManager.getConfigurationManager().getConfiguration().getGenericAssetNodeTypes().get(this.assetType());
+ }
+
+ public String assetType(){
+ // Implement where needed
+ return this.getComponentType().getValue();
+ }
+
+ public boolean shouldGenerateInputs(){
+ // Implement where needed
+ return true;
+ }
+
+ public boolean deriveFromGeneric(){
+ // Implement where needed
+ return true;
+ }
+
+ public void setDerivedFromGenericInfo(Resource genericType){
+ derivedFromGenericType = genericType.getToscaResourceName();
+ derivedFromGenericVersion = genericType.getVersion();
+ }
+
+ public String getToscaType() {
+ return toscaType;
+ }
+
+ public void setToscaType(String toscaType) {
+ this.toscaType = toscaType;
+ }
+ public List<AdditionalInformationDefinition> getAdditionalInformation() {
+ return additionalInformation;
+ }
+
+ public void setAdditionalInformation(List<AdditionalInformationDefinition> additionalInformation) {
+ this.additionalInformation = additionalInformation;
+ }
+
}
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 ce9ac67ced..9d016c0799 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
@@ -20,12 +20,19 @@
package org.openecomp.sdc.be.model;
+import java.io.Serializable;
import java.util.List;
import java.util.Map;
-public class ComponentInstInputsMap {
+public class ComponentInstInputsMap implements Serializable{
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1136631343963488131L;
+
Map<String, List<InputDefinition>> componentInstanceInputsMap;
+ Map<String, List<ComponentInstancePropInput>> componentInstanceProperties;
public Map<String, List<InputDefinition>> getComponentInstanceInputsMap() {
return componentInstanceInputsMap;
@@ -34,4 +41,12 @@ public class ComponentInstInputsMap {
public void setComponentInstanceInputsMap(Map<String, List<InputDefinition>> componentInstanceInputsMap) {
this.componentInstanceInputsMap = componentInstanceInputsMap;
}
+
+ public Map<String, List<ComponentInstancePropInput>> getComponentInstanceProperties() {
+ return componentInstanceProperties;
+ }
+
+ public void setComponentInstancePropInput(Map<String, List<ComponentInstancePropInput>> componentInstanceProperties) {
+ this.componentInstanceProperties = componentInstanceProperties;
+ }
}
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 baaf89bcfc..0b7e523813 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
@@ -33,14 +33,11 @@ public class ComponentInstance extends ComponentInstanceDataDefinition implement
*/
private static final long serialVersionUID = 6721465693884621223L;
- private String icon;
-
- private String componentName;
- private String componentVersion;
- private String toscaComponentName;
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();
@@ -50,38 +47,6 @@ public class ComponentInstance extends ComponentInstanceDataDefinition implement
super(r);
}
- public String getIcon() {
- return icon;
- }
-
- public void setIcon(String icon) {
- this.icon = icon;
- }
-
- public String getComponentName() {
- return componentName;
- }
-
- public void setComponentName(String resourceName) {
- this.componentName = resourceName;
- }
-
- public String getComponentVersion() {
- return componentVersion;
- }
-
- public String getToscaComponentName() {
- return toscaComponentName;
- }
-
- public void setToscaComponentName(String toscaComponentName) {
- this.toscaComponentName = toscaComponentName;
- }
-
- public void setComponentVersion(String resourceVersion) {
- this.componentVersion = resourceVersion;
- }
-
public Map<String, List<CapabilityDefinition>> getCapabilities() {
return capabilities;
}
@@ -105,5 +70,21 @@ public class ComponentInstance extends ComponentInstanceDataDefinition implement
public void setDeploymentArtifacts(Map<String, ArtifactDefinition> deploymentArtifacts) {
this.deploymentArtifacts = deploymentArtifacts;
}
+
+ public Map<String, ArtifactDefinition> getArtifacts() {
+ return 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;
+ }
+
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceAttribute.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceAttribute.java
index 12233e733c..4e55152526 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceAttribute.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceAttribute.java
@@ -49,6 +49,10 @@ public class ComponentInstanceAttribute extends AttributeDefinition
setParentUniqueId(pd.getParentUniqueId());
}
+ public ComponentInstanceAttribute(AttributeDefinition attributeDefinition) {
+ super(attributeDefinition);
+ }
+
public String getValueUniqueUid() {
return valueUniqueUid;
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceInput.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceInput.java
index 1334fa8c06..ca53db69d9 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceInput.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceInput.java
@@ -28,6 +28,11 @@ import org.openecomp.sdc.be.datatypes.elements.PropertyRule;
public class ComponentInstanceInput extends InputDefinition implements IComponentInstanceConnectedElement {
/**
+ *
+ */
+ private static final long serialVersionUID = -3937554584759816724L;
+
+ /**
* Value of property
*/
private String value;
@@ -64,6 +69,13 @@ public class ComponentInstanceInput extends InputDefinition implements IComponen
this.valueUniqueUid = valueUniqueUid;
}
+ public ComponentInstanceInput(PropertyDataDefinition propertyDefinition) {
+ super(propertyDefinition);
+ if(propertyDefinition.getGetInputValues() != null && !propertyDefinition.getGetInputValues().isEmpty()){
+ this.inputId = propertyDefinition.getGetInputValues().get(0).getInputId();
+ }
+ }
+
public String getComponentInstanceName() {
return componentInstanceName;
}
@@ -104,13 +116,13 @@ public class ComponentInstanceInput extends InputDefinition implements IComponen
this.valueUniqueUid = valueUniqueUid;
}
- public boolean isDefinition() {
+ /*public boolean isDefinition() {
return definition;
}
public void setDefinition(boolean definition) {
this.definition = definition;
- }
+ }*/
public List<String> getPath() {
return path;
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/PropertyInfo.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstancePropInput.java
index 385093e5ad..9f5e3e9eea 100644
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/PropertyInfo.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstancePropInput.java
@@ -18,59 +18,48 @@
* ============LICENSE_END=========================================================
*/
-package org.openecomp.sdc.ci.tests.datatypes;
+package org.openecomp.sdc.be.model;
-import org.openecomp.sdc.ci.tests.datatypes.enums.PropertyTypeEnum;
+import java.io.Serializable;
+import java.util.Map;
-public class PropertyInfo {
-
- public PropertyInfo() {
- super();
- }
-
- public PropertyInfo(String name, String value, String desc, PropertyTypeEnum type) {
+public class ComponentInstancePropInput extends ComponentInstanceProperty implements Serializable{
+ /**
+ *
+ */
+ private static final long serialVersionUID = -7991205190252140617L;
+
+
+ private String propertiesName;
+ private PropertyDefinition input;
+
+ public ComponentInstancePropInput() {
super();
- this.name = name;
- this.value = value;
- this.type = type;
- this.description = desc;
- }
-
- private String name;
- private String value;
- private PropertyTypeEnum type;
- private String description;
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public String getValue() {
- return value;
}
-
- public void setValue(String value) {
- this.value = value;
+
+ public ComponentInstancePropInput(ComponentInstanceProperty p) {
+ super(p);
}
-
- public PropertyTypeEnum getType() {
- return type;
+
+ public String getPropertiesName() {
+ return propertiesName;
}
-
- public void setType(PropertyTypeEnum type) {
- this.type = type;
+ public void setPropertiesName(String propertiesName) {
+ this.propertiesName = propertiesName;
}
-
- public String getDescription() {
- return description;
+ public PropertyDefinition getInput() {
+ return input;
}
-
- public void setDescription(String description) {
- this.description = description;
+ public void setInput(PropertyDefinition input) {
+ this.input = input;
+ }
+
+ public String[] getParsedPropNames(){
+ String[] tokens = null;
+ if(propertiesName != null && !propertiesName.isEmpty()){
+ tokens = propertiesName.split("#");
+ }
+ return tokens;
}
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceProperty.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceProperty.java
index a804170c75..17eb045630 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceProperty.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceProperty.java
@@ -23,10 +23,11 @@ package org.openecomp.sdc.be.model;
import java.io.Serializable;
import java.util.List;
+
+import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.PropertyRule;
-public class ComponentInstanceProperty extends PropertyDefinition
- implements IComponentInstanceConnectedElement, Serializable {
+public class ComponentInstanceProperty extends PropertyDefinition implements IComponentInstanceConnectedElement, Serializable {
/**
*
@@ -36,7 +37,7 @@ public class ComponentInstanceProperty extends PropertyDefinition
/**
* Value of property
*/
- private String value;
+
/**
* The unique id of the property value on graph
@@ -47,26 +48,47 @@ public class ComponentInstanceProperty extends PropertyDefinition
private List<PropertyRule> rules = null;
- private List<GetInputValueInfo> getInputValues;
+
+
+ private String componentInstanceName;
+
+ private String componentInstanceId;
+
+ public String getComponentInstanceName() {
+ return componentInstanceName;
+ }
+
+ public void setComponentInstanceName(String componentInstanceName) {
+ this.componentInstanceName = componentInstanceName;
+ }
+
+ public String getComponentInstanceId() {
+ return componentInstanceId;
+ }
+
+ public void setComponentInstanceId(String componentInstanceId) {
+ this.componentInstanceId = componentInstanceId;
+ }
public ComponentInstanceProperty() {
super();
}
+ public ComponentInstanceProperty(PropertyDataDefinition pd) {
+ super(pd);
+ }
+
+ public ComponentInstanceProperty(PropertyDefinition pd) {
+ super(pd);
+ }
public ComponentInstanceProperty(PropertyDefinition pd, String value, String valueUniqueUid) {
super(pd);
- this.value = value;
+ this.setValue(value);
this.valueUniqueUid = valueUniqueUid;
}
- public String getValue() {
- return value;
- }
-
- public void setValue(String value) {
- this.value = value;
- }
+
public String getValueUniqueUid() {
return valueUniqueUid;
@@ -76,13 +98,6 @@ public class ComponentInstanceProperty extends PropertyDefinition
this.valueUniqueUid = valueUniqueUid;
}
- public boolean isDefinition() {
- return definition;
- }
-
- public void setDefinition(boolean definition) {
- this.definition = definition;
- }
public List<String> getPath() {
return path;
@@ -100,18 +115,10 @@ public class ComponentInstanceProperty extends PropertyDefinition
this.rules = rules;
}
- public List<GetInputValueInfo> getGetInputValues() {
- return getInputValues;
- }
-
- public void setGetInputValues(List<GetInputValueInfo> getInputValues) {
- this.getInputValues = getInputValues;
- }
-
+
@Override
public String toString() {
- return "ComponentInstanceProperty [ " + super.toString() + " , value=" + value + ", valueUniqueUid = "
- + valueUniqueUid + " , rules=" + rules + " , path=" + path + " ]";
+ return "ComponentInstanceProperty [ " + super.toString() + " , value=" + getValue() + ", valueUniqueUid = " + valueUniqueUid + " , rules=" + rules + " , path=" + path + " ]";
}
}
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 0227de5b50..4078a47f86 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,6 +20,10 @@
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;
public class ComponentParametersView {
@@ -41,6 +45,99 @@ public class ComponentParametersView {
boolean ignoreComponentInstancesAttributesFrom = false;
boolean ignoreInputs = false;
boolean ignoreComponentInstancesInputs = false;
+ boolean ignoreCapabiltyProperties = true;
+
+ public ComponentParametersView() {
+ }
+
+ public ComponentParametersView(boolean setAllToIgnore) {
+ this();
+ if(setAllToIgnore){
+ this.disableAll();
+ }
+ }
+
+ public ComponentParametersView(List<String> filters) {
+ this(true);
+
+ for(String fieldName: filters) {
+ switch (ComponentFieldsEnum.findByValue(fieldName)) {
+ case PROPERTIES:
+ this.setIgnoreProperties(false);
+ break;
+ case INPUTS:
+ this.setIgnoreInputs(false);;
+ break;
+ case USERS:
+ this.setIgnoreUsers(false);
+ break;
+ case CATEGORIES:
+ this.setIgnoreCategories(false);
+ break;
+ case METADATA:
+ this.setIgnoreUsers(false);
+ this.setIgnoreCategories(false);
+ this.setIgnoreAllVersions(false);
+ this.setIgnoreDerivedFrom(false);
+ break;
+ case GROUPS:
+ this.setIgnoreGroups(false);
+ break;
+ case COMPONENT_INSTANCES:
+ this.setIgnoreComponentInstances(false);
+ this.setIgnoreCapabilities(false);
+ this.setIgnoreRequirements(false);
+ break;
+ case COMPONENT_INSTANCES_PROPERTIES:
+ 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.setIgnoreCapabilities(false);
+ break;
+ case REQUIREMENTS:
+ this.setIgnoreComponentInstances(false);
+ this.setIgnoreRequirements(false);
+ break;
+ case ALL_VERSIONS:
+ this.setIgnoreAllVersions(false);
+ break;
+ case ADDITIONAL_INFORMATION:
+ this.setIgnoreAdditionalInformation(false);
+ break;
+ case ARTIFACTS:
+ case DEPLOYMENT_ARTIFACTS:
+ case TOSCA_ARTIFACTS:
+ case SERVICE_API_ARTIFACTS:
+ this.setIgnoreArtifacts(false);
+ break;
+ case INTERFACES:
+ this.setIgnoreInterfaces(false);
+ break;
+ case DERIVED_FROM:
+ this.setIgnoreDerivedFrom(false);
+ break;
+ case ATTRIBUTES:
+ this.setIgnoreAttributesFrom(false);
+ break;
+ case COMPONENT_INSTANCES_ATTRIBUTES:
+ this.setIgnoreComponentInstances(false);
+ this.setIgnoreComponentInstancesAttributesFrom(false);
+ break;
+ case COMPONENT_INSTANCE_INPUTS:
+ this.setIgnoreComponentInstances(false);
+ this.setIgnoreComponentInstancesInputs(false);
+ break;
+ case INSTANCE_CAPABILTY_PROPERTIES:
+ this.setIgnoreCapabiltyProperties(false);
+ break;
+ default:
+ break;
+ }
+
+ }
+ }
///////////////////////////////////////////////////////////////
// When adding new member, please update the filter method.
@@ -152,7 +249,6 @@ public class ComponentParametersView {
if (ignoreComponentInstancesInputs) {
component.setComponentInstancesInputs(null);
}
-
return component;
}
@@ -175,6 +271,7 @@ public class ComponentParametersView {
ignoreInputs = true;
ignoreComponentInstancesAttributesFrom = true;
ignoreComponentInstancesInputs = true;
+ ignoreCapabiltyProperties = true;
}
public boolean isIgnoreGroups() {
@@ -278,7 +375,7 @@ public class ComponentParametersView {
}
public void setIgnoreAttributesFrom(boolean ignoreAttributesFrom) {
- this.ignoreAttributesFrom = ignoreDerivedFrom;
+ this.ignoreAttributesFrom = ignoreAttributesFrom;
}
public boolean isIgnoreComponentInstancesAttributesFrom() {
@@ -313,4 +410,21 @@ public class ComponentParametersView {
this.ignoreInputs = ignoreInputs;
}
+ public boolean isIgnoreCapabiltyProperties() {
+ return ignoreCapabiltyProperties;
+ }
+
+ public void setIgnoreCapabiltyProperties(boolean ignoreCapabiltyProperties) {
+ this.ignoreCapabiltyProperties = ignoreCapabiltyProperties;
+ }
+
+ public JsonParseFlagEnum detectParseFlag() {
+ JsonParseFlagEnum parseFlag;
+ if(isIgnoreComponentInstances()){
+ parseFlag = JsonParseFlagEnum.ParseMetadata;
+ } else {
+ parseFlag = JsonParseFlagEnum.ParseAll;
+ }
+ return parseFlag;
+ }
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/DerivedNodeTypeResolver.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/DerivedNodeTypeResolver.java
new file mode 100644
index 0000000000..fff3e81d7a
--- /dev/null
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/DerivedNodeTypeResolver.java
@@ -0,0 +1,15 @@
+package org.openecomp.sdc.be.model;
+
+import fj.data.Either;
+import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
+import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.openecomp.sdc.be.model.jsontitan.datamodel.NodeType;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+
+import java.util.List;
+
+public interface DerivedNodeTypeResolver {
+
+ Either<List<GraphVertex>, TitanOperationStatus> findDerivedResources(String parentResource);
+
+}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/DistributionStatusEnum.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/DistributionStatusEnum.java
index 89b5bfff31..139cd70a3c 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/DistributionStatusEnum.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/DistributionStatusEnum.java
@@ -21,10 +21,7 @@
package org.openecomp.sdc.be.model;
public enum DistributionStatusEnum {
- DISTRIBUTION_NOT_APPROVED("Distribution not approved"),
- DISTRIBUTION_APPROVED("Distribution approved"),
- DISTRIBUTED("Distributed"),
- DISTRIBUTION_REJECTED("Distribution rejected");
+ DISTRIBUTION_NOT_APPROVED("Distribution not approved"), DISTRIBUTION_APPROVED("Distribution approved"), DISTRIBUTED("Distributed"), DISTRIBUTION_REJECTED("Distribution rejected");
private String value;
@@ -39,8 +36,7 @@ public enum DistributionStatusEnum {
public static DistributionStatusEnum findState(String state) {
for (DistributionStatusEnum distributionStatus : DistributionStatusEnum.values()) {
- if (distributionStatus.name().equalsIgnoreCase(state)
- || distributionStatus.getValue().equalsIgnoreCase(state)) {
+ if (distributionStatus.name().equalsIgnoreCase(state) || distributionStatus.getValue().equalsIgnoreCase(state)) {
return distributionStatus;
}
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupDefinition.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupDefinition.java
index 5520e89032..167fa2f0a1 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupDefinition.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupDefinition.java
@@ -21,36 +21,26 @@
package org.openecomp.sdc.be.model;
import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.HashMap;
import java.util.List;
-import java.util.Map;
import java.util.stream.Collectors;
import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
public class GroupDefinition extends GroupDataDefinition implements Serializable {
-
/**
*
*/
private static final long serialVersionUID = -852613634651112247L;
- // map of componentInstances <name: uniqueId>
- private Map<String, String> members;
-
// properties (properties should be defined in the group type, the
// properties here are actually the value for the properties)
- private List<GroupProperty> properties;
+
- // artifacts - list of artifact uid. All artifacts in the group must already
- // be uploaded to the VF
- private List<String> artifacts;
- private List<String> artifactsUuid;
// The unique id of the type of this group
- private String typeUid;
+
public GroupDefinition() {
super();
@@ -68,66 +58,26 @@ public class GroupDefinition extends GroupDataDefinition implements Serializable
this.setInvariantUUID(other.getInvariantUUID());
this.setGroupUUID(other.getGroupUUID());
this.setDescription(other.getDescription());
- if (other.members != null) {
- this.members = new HashMap<String, String>(other.getMembers());
- }
- if (other.properties != null) {
- this.properties = other.properties.stream().map(p -> new GroupProperty(p)).collect(Collectors.toList());
- }
- if (other.artifacts != null) {
- this.artifacts = new ArrayList<String>(other.getArtifacts());
- }
-
- if (other.artifactsUuid != null) {
- this.artifactsUuid = new ArrayList<String>(other.getArtifactsUuid());
- }
- this.setTypeUid(other.typeUid);
- }
-
- public Map<String, String> getMembers() {
- return members;
+ this.setTypeUid(other.getTypeUid());
+ this.setProperties(other.getProperties());
+
}
- public void setMembers(Map<String, String> members) {
- this.members = members;
- }
-
- public List<GroupProperty> getProperties() {
+ public List<GroupProperty> convertToGroupProperties() {
+ List<GroupProperty> properties = null;
+ List<PropertyDataDefinition> propList = super.getProperties();
+ if(propList != null && !propList .isEmpty()){
+ properties = propList.stream().map(pr -> new GroupProperty(pr)).collect(Collectors.toList());
+ }
return properties;
}
- public void setProperties(List<GroupProperty> properties) {
- this.properties = properties;
- }
-
- public List<String> getArtifacts() {
- return artifacts;
- }
-
- public void setArtifacts(List<String> artifacts) {
- this.artifacts = artifacts;
- }
-
- public String getTypeUid() {
- return typeUid;
- }
-
- public void setTypeUid(String typeUid) {
- this.typeUid = typeUid;
- }
-
- public List<String> getArtifactsUuid() {
- return artifactsUuid;
- }
-
- public void setArtifactsUuid(List<String> artifactsUuid) {
- this.artifactsUuid = artifactsUuid;
- }
-
- @Override
- public String toString() {
- return "GroupDefinition [" + super.toString() + "members=" + members + ", properties=" + properties
- + ", artifacts=" + artifacts + ", artifactsUUID=" + artifactsUuid + ", typeUid=" + typeUid + "]";
+ public void convertFromGroupProperties(List<GroupProperty> properties) {
+ if(properties != null && !properties .isEmpty()){
+ List<PropertyDataDefinition> propList = properties.stream().map(pr -> new PropertyDataDefinition(pr)).collect(Collectors.toList());
+ super.setProperties(propList);
+ }
+
}
}
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
new file mode 100644
index 0000000000..f0e08b85fd
--- /dev/null
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupInstance.java
@@ -0,0 +1,57 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.model;
+
+import java.io.Serializable;
+import java.util.List;
+import java.util.stream.Collectors;
+import org.openecomp.sdc.be.datatypes.elements.GroupInstanceDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
+
+public class GroupInstance extends GroupInstanceDataDefinition implements Serializable {
+
+ private static final long serialVersionUID = -2066335818115254401L;
+
+ public GroupInstance() {
+ super();
+ }
+
+ public GroupInstance(GroupInstanceDataDefinition r) {
+ super(r);
+ }
+
+ public List<GroupInstanceProperty> convertToGroupInstancesProperties() {
+ List<GroupInstanceProperty> groupInstancesProperties = null;
+ List<PropertyDataDefinition> propertiesList = super.getProperties();
+ if(propertiesList != null && !propertiesList .isEmpty()){
+ groupInstancesProperties = propertiesList.stream().map(p -> new GroupInstanceProperty(p)).collect(Collectors.toList());
+ }
+ return 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);
+ }
+ }
+
+}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/GetInputValueInfo.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupInstanceProperty.java
index bb53e13251..e1e51729e0 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/GetInputValueInfo.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupInstanceProperty.java
@@ -20,52 +20,43 @@
package org.openecomp.sdc.be.model;
-public class GetInputValueInfo {
- String propName;
- String inputName;
- Integer indexValue;
- GetInputValueInfo getInputIndex;
+import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
- boolean isList = false;
-
- public String getPropName() {
- return propName;
- }
-
- public void setPropName(String propName) {
- this.propName = propName;
+public class GroupInstanceProperty extends GroupProperty {
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1L;
+ private String parentValue;
+
+ public GroupInstanceProperty() {
+ super();
}
- public String getInputName() {
- return inputName;
+ public GroupInstanceProperty(GroupProperty gp, String parentValue) {
+ super(gp);
+ this.parentValue = parentValue;
}
- public void setInputName(String inputName) {
- this.inputName = inputName;
+ public GroupInstanceProperty(GroupInstanceProperty other) {
+ super(other);
+ if (other != null) {
+ this.parentValue = other.getParentValue();
+ }
}
-
- public Integer getIndexValue() {
- return indexValue;
- }
-
- public void setIndexValue(Integer indexValue) {
- this.indexValue = indexValue;
+
+ public GroupInstanceProperty(PropertyDataDefinition propertyDataDefinition) {
+ super(propertyDataDefinition);
}
- public GetInputValueInfo getGetInputIndex() {
- return getInputIndex;
+ public String getParentValue() {
+ return parentValue;
}
- public void setGetInputIndex(GetInputValueInfo getInputIndex) {
- this.getInputIndex = getInputIndex;
+ public void setParentValue(String parentValue) {
+ this.parentValue = parentValue;
}
-
- public boolean isList() {
- return isList;
- }
-
- public void setList(boolean isList) {
- this.isList = isList;
- }
-
+
+
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupProperty.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupProperty.java
index cf0afde8e3..d8589d51b9 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupProperty.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupProperty.java
@@ -20,12 +20,15 @@
package org.openecomp.sdc.be.model;
+import org.apache.commons.lang.StringUtils;
+import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
+
public class GroupProperty extends PropertyDefinition {
/**
* current value
*/
- private String value;
+// private String value;
/**
* The unique is of Group property on graph. If it is null, then the
@@ -40,24 +43,19 @@ public class GroupProperty extends PropertyDefinition {
public GroupProperty(PropertyDefinition pd, String value, String valueUniqueUid) {
super(pd);
- this.value = value;
+ setValue(value);
this.valueUniqueUid = valueUniqueUid;
}
public GroupProperty(GroupProperty other) {
super(other);
if (other != null) {
- this.value = other.getValue();
+ setValue(other.getValue());
this.valueUniqueUid = other.getValueUniqueUid();
}
}
-
- public String getValue() {
- return value;
- }
-
- public void setValue(String value) {
- this.value = value;
+ public GroupProperty(PropertyDataDefinition other) {
+ super(other);
}
public String getValueUniqueUid() {
@@ -70,7 +68,7 @@ public class GroupProperty extends PropertyDefinition {
@Override
public String toString() {
- return "GroupProperty [ " + super.toString() + " , value=" + value + ", valueUniqueUid = " + valueUniqueUid
+ return "GroupProperty [ " + super.toString() + ", valueUniqueUid = " + valueUniqueUid
+ " ]";
}
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/InputDefinition.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/InputDefinition.java
index 3090d7232e..2359d635a3 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/InputDefinition.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/InputDefinition.java
@@ -25,57 +25,33 @@ import java.util.List;
import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
public class InputDefinition extends PropertyDefinition {
- String label;
- Boolean hidden;
- Boolean immutable;
- List<ComponentInstanceInput> inputsValue;
+ /**
+ *
+ */
+ private static final long serialVersionUID = -6920076037265309468L;
+
+ List<ComponentInstanceInput> inputs;
List<ComponentInstanceProperty> properties;
public InputDefinition() {
super();
- // TODO Auto-generated constructor stub
}
public InputDefinition(PropertyDataDefinition p) {
super(p);
- // TODO Auto-generated constructor stub
}
public InputDefinition(PropertyDefinition pd) {
super(pd);
- // TODO Auto-generated constructor stub
- }
-
- public Boolean isHidden() {
- return hidden;
- }
-
- public void setHidden(Boolean hidden) {
- this.hidden = hidden;
- }
-
- public Boolean isImmutable() {
- return immutable;
- }
-
- public void setImmutable(Boolean immutable) {
- this.immutable = immutable;
- }
-
- public String getLabel() {
- return label;
- }
-
- public void setLabel(String label) {
- this.label = label;
}
- public List<ComponentInstanceInput> getInputsValue() {
- return inputsValue;
+
+ public List<ComponentInstanceInput> getInputs() {
+ return inputs;
}
- public void setInputsValue(List<ComponentInstanceInput> inputsValue) {
- this.inputsValue = inputsValue;
+ public void setInputs(List<ComponentInstanceInput> inputs) {
+ this.inputs = inputs;
}
public List<ComponentInstanceProperty> getProperties() {
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 51ad31199a..8897d6ed4e 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
@@ -23,8 +23,12 @@ package org.openecomp.sdc.be.model;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
+import java.util.stream.Collectors;
+import org.codehaus.jackson.annotate.JsonIgnore;
+import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterDataDefinition;
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
@@ -39,28 +43,21 @@ public class InterfaceDefinition extends InterfaceDataDefinition implements IOpe
*/
private static final long serialVersionUID = 8220887972866354746L;
- /**
- * Defines an operation available to manage particular aspects of the Node
- * Type.
- */
- private Map<String, Operation> operations = new HashMap<String, Operation>();
+
private boolean definition;
public InterfaceDefinition() {
super();
- // TODO Auto-generated constructor stub
}
public InterfaceDefinition(String type, String description, Map<String, Operation> operations) {
super(type, description);
- this.operations = operations;
-
+ setOperationsMap(operations);
}
public InterfaceDefinition(InterfaceDataDefinition p) {
super(p);
- // TODO Auto-generated constructor stub
}
@Override
@@ -72,18 +69,20 @@ public class InterfaceDefinition extends InterfaceDataDefinition implements IOpe
public void setDefinition(boolean definition) {
this.definition = definition;
}
-
- public Map<String, Operation> getOperations() {
- return operations;
+ @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;
}
-
- public void setOperations(Map<String, Operation> operations) {
- this.operations = operations;
+ @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 [operations=" + operations + ", definition=" + definition + "]";
+ return "InterfaceDefinition [definition=" + definition + "]";
}
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/Operation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/Operation.java
index a793c68528..4347cd45fc 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/Operation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/Operation.java
@@ -23,8 +23,8 @@ package org.openecomp.sdc.be.model;
import java.util.Map;
import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.InputsValueDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.OperationDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
/**
* Defines an operation available to manage particular aspects of the Node Type.
@@ -33,15 +33,7 @@ import org.openecomp.sdc.be.datatypes.elements.OperationDataDefinition;
*/
public class Operation extends OperationDataDefinition implements IOperationParameter {
- /** Implementation artifact for the interface. */
- private ArtifactDefinition implementation;
- /**
- * This OPTIONAL property contains a list of one or more input parameter
- * definitions.
- */
- // @JsonDeserialize(contentUsing = OperationParameterDeserializer.class)
- private Map<String, PropertyValueDefinition> inputs;
private boolean definition;
@@ -56,23 +48,21 @@ public class Operation extends OperationDataDefinition implements IOperationPara
*/
public Operation() {
super();
- // TODO Auto-generated constructor stub
}
public Operation(OperationDataDefinition p) {
super(p);
- // TODO Auto-generated constructor stub
}
public Operation(ArtifactDataDefinition implementation, String description,
- Map<String, InputsValueDataDefinition> inputs) {
+ Map<String, PropertyDataDefinition> inputs) {
super(description);
-
+ setImplementation(implementation);
+ setInputs(inputs);
}
@Override
public boolean isDefinition() {
- // TODO Auto-generated method stub
return false;
}
@@ -80,26 +70,15 @@ public class Operation extends OperationDataDefinition implements IOperationPara
this.definition = definition;
}
- public ArtifactDefinition getImplementation() {
- return implementation;
- }
-
- public void setImplementation(ArtifactDefinition implementation) {
- this.implementation = implementation;
- }
-
- public Map<String, PropertyValueDefinition> getInputs() {
- return inputs;
- }
-
- public void setInputs(Map<String, PropertyValueDefinition> inputs) {
- this.inputs = inputs;
- }
-
@Override
public String toString() {
- return "Operation [implementation=" + implementation + ", inputs=" + inputs + ", definition=" + definition
- + "]";
+ return "Operation [definition=" + definition + "]";
}
+ public ArtifactDefinition getImplementationArtifact(){
+ if ( getImplementation() != null ){
+ return new ArtifactDefinition(getImplementation());
+ }
+ return null;
+ }
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/Product.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/Product.java
index 04223857b7..12e6eaf018 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/Product.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/Product.java
@@ -29,12 +29,12 @@ public class Product extends Component {
public Product() {
super(new ProductMetadataDefinition());
- componentType = ComponentTypeEnum.PRODUCT;
+ this.getComponentMetadataDefinition().getMetadataDataDefinition().setComponentType(ComponentTypeEnum.PRODUCT);
}
public Product(ProductMetadataDefinition productMetadataDefinition) {
super(productMetadataDefinition);
- componentType = ComponentTypeEnum.PRODUCT;
+ this.getComponentMetadataDefinition().getMetadataDataDefinition().setComponentType(ComponentTypeEnum.PRODUCT);
}
public String getFullName() {
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/PropertyDefinition.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/PropertyDefinition.java
index 7974e863ac..b315d5c7fd 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/PropertyDefinition.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/PropertyDefinition.java
@@ -22,36 +22,93 @@ package org.openecomp.sdc.be.model;
import java.io.Serializable;
import java.util.List;
-
import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
-//import javax.validation.Valid;
-//import javax.validation.constraints.NotNull;
-//
-//
-//import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
-//import com.fasterxml.jackson.annotation.JsonProperty;
-//import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
public class PropertyDefinition extends PropertyDataDefinition
implements IOperationParameter, IComplexDefaultValue, Serializable {
+
+ /**The enumeration presents the list of property names with specific behavior
+ * @author rbetzer
+ *
+ */
+ public enum PropertyNames {
+
+ MIN_INSTANCES("min_vf_module_instances", GroupInstancePropertyValueUpdateBehavior.UPDATABLE_ON_SERVICE_LEVEL),
+ MAX_INSTANCES("max_vf_module_instances", GroupInstancePropertyValueUpdateBehavior.UPDATABLE_ON_SERVICE_LEVEL),
+ INITIAL_COUNT("initial_count", GroupInstancePropertyValueUpdateBehavior.UPDATABLE_ON_SERVICE_LEVEL),
+ VF_MODULE_LABEL("vf_module_label", GroupInstancePropertyValueUpdateBehavior.UPDATABLE_ON_RESOURCE_LEVEL),
+ VF_MODULE_DESCRIPTION("vf_module_description", GroupInstancePropertyValueUpdateBehavior.UPDATABLE_ON_RESOURCE_LEVEL),
+ NETWORK_ROLE("network_role", GroupInstancePropertyValueUpdateBehavior.NOT_RELEVANT),
+ AVAILABILTY_ZONE_COUNT("availability_zone_count", GroupInstancePropertyValueUpdateBehavior.UPDATABLE_ON_SERVICE_LEVEL),
+ VFC_LIST("vfc_list", GroupInstancePropertyValueUpdateBehavior.UPDATABLE_ON_SERVICE_LEVEL);
+
+ private String propertyName;
+ private GroupInstancePropertyValueUpdateBehavior updateBehavior;
+
+ private PropertyNames(String propertyName,GroupInstancePropertyValueUpdateBehavior updateBehavior){
+ this.propertyName = propertyName;
+ this.updateBehavior = updateBehavior;
+ }
+
+ public String getPropertyName() {
+ return propertyName;
+ }
+
+ public GroupInstancePropertyValueUpdateBehavior getUpdateBehavior() {
+ return updateBehavior;
+ }
+ /**
+ * finds PropertyNames according received string name
+ * @param name
+ * @return
+ */
+ public static PropertyNames findName(String name){
+ for (PropertyNames e : PropertyNames.values()) {
+ if (e.getPropertyName().equals(name)) {
+ return e;
+ }
+ }
+ return null;
+ }
+ }
/**
- *
+ * The enumeration presents the list of highest levels for which update property value is allowed
+ * @author nsheshukov
+ *
*/
+ public enum GroupInstancePropertyValueUpdateBehavior{
+ NOT_RELEVANT("NOT_RELEVANT", -1),
+ UPDATABLE_ON_RESOURCE_LEVEL("UPDATABLE_ON_VF_LEVEL", 0),
+ UPDATABLE_ON_SERVICE_LEVEL("UPDATABLE_ON_SERVICE_LEVEL", 1);
+
+ String levelName;
+ int levelNumber;
+
+ private GroupInstancePropertyValueUpdateBehavior(String name, int levelNumber){
+ this.levelName = name;
+ this.levelNumber = levelNumber;
+ }
+
+ public String getLevelName() {
+ return levelName;
+ }
+
+ public int getLevelNumber() {
+ return levelNumber;
+ }
+ }
+
private static final long serialVersionUID = 188403656600317269L;
private List<PropertyConstraint> constraints;
// private Schema schema;
private String status;
- private String name;
- /**
- * The resource id which this property belongs to
- */
- private String parentUniqueId;
+
public PropertyDefinition() {
super();
}
@@ -61,16 +118,10 @@ public class PropertyDefinition extends PropertyDataDefinition
}
public PropertyDefinition(PropertyDefinition pd) {
- this.setUniqueId(pd.getUniqueId());
- this.setConstraints(pd.getConstraints());
- // this.setSchema(pd.schema);
- this.setDefaultValue(pd.getDefaultValue());
- this.setDescription(pd.getDescription());
- this.setName(pd.getName());
- this.setSchema(pd.getSchema());
- this.setParentUniqueId(pd.getParentUniqueId());
- this.setRequired(pd.isRequired());
- this.setType(pd.getType());
+ super(pd);
+ this.setConstraints(pd.getConstraints());
+ status = pd.status;
+
}
public List<PropertyConstraint> getConstraints() {
@@ -81,17 +132,11 @@ public class PropertyDefinition extends PropertyDataDefinition
this.constraints = constraints;
}
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
@Override
public String toString() {
- return super.toString() + " [name=" + name + ", parentUniqueId=" + parentUniqueId + ", constraints="
+ return super.toString() + " [name=" + getName() + ", constraints="
+ constraints + "]]";
}
@@ -112,13 +157,7 @@ public class PropertyDefinition extends PropertyDataDefinition
this.status = status;
}
- public String getParentUniqueId() {
- return parentUniqueId;
- }
-
- public void setParentUniqueId(String parentUniqueId) {
- this.parentUniqueId = parentUniqueId;
- }
+
@Override
public boolean isDefinition() {
@@ -126,7 +165,7 @@ public class PropertyDefinition extends PropertyDataDefinition
}
public void setDefinition(boolean definition) {
- this.definition = definition;
+ super.setDefinition(definition);
}
@Override
@@ -134,8 +173,7 @@ public class PropertyDefinition extends PropertyDataDefinition
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((constraints == null) ? 0 : constraints.hashCode());
- result = prime * result + ((name == null) ? 0 : name.hashCode());
- result = prime * result + ((parentUniqueId == null) ? 0 : parentUniqueId.hashCode());
+ result = prime * result + ((getName() == null) ? 0 : getName().hashCode());
result = prime * result + ((status == null) ? 0 : status.hashCode());
return result;
}
@@ -154,15 +192,10 @@ public class PropertyDefinition extends PropertyDataDefinition
return false;
} else if (!constraints.equals(other.constraints))
return false;
- if (name == null) {
- if (other.name != null)
- return false;
- } else if (!name.equals(other.name))
- return false;
- if (parentUniqueId == null) {
- if (other.parentUniqueId != null)
+ if (getName() == null) {
+ if (other.getName() != null)
return false;
- } else if (!parentUniqueId.equals(other.parentUniqueId))
+ } else if (!getName().equals(other.getName()))
return false;
if (status == null) {
if (other.status != null)
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/PropertyValueDefinition.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/PropertyValueDefinition.java
index 0c322420b3..0264262ab3 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/PropertyValueDefinition.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/PropertyValueDefinition.java
@@ -27,7 +27,6 @@ public class PropertyValueDefinition extends InputsValueDataDefinition implement
public PropertyValueDefinition() {
super();
- // TODO Auto-generated constructor stub
}
public PropertyValueDefinition(String name, String value) {
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/RequirementAndRelationshipPair.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/RequirementAndRelationshipPair.java
index 84ead66658..afb013d29a 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/RequirementAndRelationshipPair.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/RequirementAndRelationshipPair.java
@@ -22,6 +22,8 @@ package org.openecomp.sdc.be.model;
import java.io.Serializable;
+import org.openecomp.sdc.be.datatypes.elements.RelationshipInstDataDefinition;
+
public class RequirementAndRelationshipPair implements Serializable {
/**
@@ -32,6 +34,7 @@ public class RequirementAndRelationshipPair implements Serializable {
private String requirement;
private String capabilityOwnerId;
private String requirementOwnerId;
+ private String id;
private RelationshipImpl relationship;
@@ -113,10 +116,42 @@ public class RequirementAndRelationshipPair implements Serializable {
this.requirementUid = requirementUid;
}
+ public String getId() {
+ return id;
+ }
+
+ public void setId(String id) {
+ this.id = id;
+ }
+
@Override
public String toString() {
return "RequirementAndRelationshipPair [requirement=" + requirement + ", relationship=" + relationship
+ ", capability=" + capability + "]";
}
+ public boolean equalsTo( RelationshipInstDataDefinition savedRelation){
+ if ( savedRelation == null ){
+ return false;
+ }
+ if ( !savedRelation.getType().equals(this.getRelationship().getType()) ){
+ return false;
+ }
+ if ( !savedRelation.getCapabilityOwnerId().equals(this.getCapabilityOwnerId()) ){
+ return false;
+ }
+ if ( !savedRelation.getRequirementOwnerId().equals(this.getRequirementOwnerId()) ){
+ return false;
+ }
+ if ( !savedRelation.getRequirementId().equals(this.getRequirementUid()) ){
+ return false;
+ }
+ if ( !savedRelation.getCapabiltyId().equals(this.getCapabilityUid()) ){
+ return false;
+ }
+ if ( !savedRelation.getRequirement().equals(this.getRequirement()) ){
+ return false;
+ }
+ return true;
+ }
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/RequirementDefinition.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/RequirementDefinition.java
index 3d5741255a..a1a485d4ff 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/RequirementDefinition.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/RequirementDefinition.java
@@ -22,220 +22,25 @@ package org.openecomp.sdc.be.model;
import java.io.Serializable;
+import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
+
/**
* Specifies the requirements that the Node Type exposes.
*/
-public class RequirementDefinition implements Serializable {
-
- /**
- *
- */
- private static final long serialVersionUID = -8840549489409274532L;
-
- /**
- * Unique id of the requirement
- */
- private String uniqueId;
-
- private String name;
-
- /**
- * specify the capability type
- */
- private String capability;
-
- /**
- * specify the node type(Optional by tosca)
- */
- private String node;
-
- /**
- * specify the relationship type(Optional by tosca)
- */
- private String relationship;
+public class RequirementDefinition extends RequirementDataDefinition implements Serializable {
- // specifies the resource instance holding this requirement
- private String ownerId;
- private String ownerName;
-
- private String minOccurrences;
- private String maxOccurrences;
-
- public RequirementDefinition() {
+ public RequirementDefinition(){
super();
}
-
+
public RequirementDefinition(RequirementDefinition other) {
- this.uniqueId = other.uniqueId;
- this.name = other.name;
- this.capability = other.capability;
- this.node = other.node;
- this.relationship = other.relationship;
- this.ownerId = other.ownerId;
- this.ownerName = other.ownerName;
- this.minOccurrences = other.minOccurrences;
- this.maxOccurrences = other.maxOccurrences;
-
- }
-
- public String getUniqueId() {
- return uniqueId;
- }
-
- public void setUniqueId(String uniqueId) {
- this.uniqueId = uniqueId;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public String getCapability() {
- return capability;
- }
-
- public void setCapability(String capability) {
- this.capability = capability;
- }
-
- public String getNode() {
- return node;
- }
-
- public void setNode(String node) {
- this.node = node;
+ super(other);
}
-
- public String getRelationship() {
- return relationship;
- }
-
- public void setRelationship(String relationship) {
- this.relationship = relationship;
- }
-
- // public RequirementImplDef getRequirementImpl() {
- // return requirementImpl;
- // }
- //
- // public void setRequirementImpl(RequirementImplDef requirementImpl) {
- // this.requirementImpl = requirementImpl;
- // }
-
- public String getOwnerId() {
- return ownerId;
- }
-
- public void setOwnerId(String ownerId) {
- this.ownerId = ownerId;
- }
-
- public String getOwnerName() {
- return ownerName;
- }
-
- public void setOwnerName(String ownerName) {
- this.ownerName = ownerName;
- }
-
- public String getMinOccurrences() {
- return minOccurrences;
- }
-
- public void setMinOccurrences(String minOccurrences) {
- this.minOccurrences = minOccurrences;
- }
-
- public String getMaxOccurrences() {
- return maxOccurrences;
- }
-
- public void setMaxOccurrences(String maxOccurrences) {
- this.maxOccurrences = maxOccurrences;
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((capability == null) ? 0 : capability.hashCode());
- result = prime * result + ((name == null) ? 0 : name.hashCode());
- result = prime * result + ((node == null) ? 0 : node.hashCode());
- result = prime * result + ((ownerId == null) ? 0 : ownerId.hashCode());
- result = prime * result + ((ownerName == null) ? 0 : ownerName.hashCode());
- result = prime * result + ((relationship == null) ? 0 : relationship.hashCode());
- result = prime * result + ((uniqueId == null) ? 0 : uniqueId.hashCode());
- result = prime * result + ((minOccurrences == null) ? 0 : minOccurrences.hashCode());
- result = prime * result + ((maxOccurrences == null) ? 0 : maxOccurrences.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;
- RequirementDefinition other = (RequirementDefinition) obj;
- if (capability == null) {
- if (other.capability != null)
- return false;
- } else if (!capability.equals(other.capability))
- return false;
- if (name == null) {
- if (other.name != null)
- return false;
- } else if (!name.equals(other.name))
- return false;
- if (node == null) {
- if (other.node != null)
- return false;
- } else if (!node.equals(other.node))
- return false;
- if (ownerId == null) {
- if (other.ownerId != null)
- return false;
- } else if (!ownerId.equals(other.ownerId))
- return false;
- if (ownerName == null) {
- if (other.ownerName != null)
- return false;
- } else if (!ownerName.equals(other.ownerName))
- return false;
- if (relationship == null) {
- if (other.relationship != null)
- return false;
- } else if (!relationship.equals(other.relationship))
- return false;
- if (uniqueId == null) {
- if (other.uniqueId != null)
- return false;
- } else if (!uniqueId.equals(other.uniqueId))
- return false;
- if (minOccurrences == null) {
- if (other.minOccurrences != null)
- return false;
- } else if (!minOccurrences.equals(other.minOccurrences))
- return false;
- if (maxOccurrences == null) {
- if (other.maxOccurrences != null)
- return false;
- } else if (!maxOccurrences.equals(other.maxOccurrences))
- return false;
- return true;
- }
-
- @Override
- public String toString() {
- return "RequirementDefinition [uniqueId=" + uniqueId + ", name=" + name + ", capability=" + capability
- + ", node=" + node + ", relationship=" + relationship + ", ownerId=" + ownerId + ", ownerName="
- + ownerName + ", minOccurrences=" + minOccurrences + ", maxOccurrences=" + maxOccurrences + "]";
+
+ public RequirementDefinition(RequirementDataDefinition requirementDataDefinition) {
+ super(requirementDataDefinition);
}
+
+ private static final long serialVersionUID = -1899506746481882719L;
}
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 6490fb4ef1..5e7983acea 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
@@ -24,6 +24,7 @@ import java.io.Serializable;
import java.util.List;
import java.util.Map;
+import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
@@ -33,15 +34,16 @@ public class Resource extends Component implements Serializable {
*
*/
private static final long serialVersionUID = -6811540567661368482L;
+ public static final String ROOT_RESOURCE = "tosca.nodes.Root";
public Resource() {
super(new ResourceMetadataDefinition());
- componentType = ComponentTypeEnum.RESOURCE;
+ this.getComponentMetadataDefinition().getMetadataDataDefinition().setComponentType(ComponentTypeEnum.RESOURCE);
}
public Resource(ComponentMetadataDefinition componentMetadataDefinition) {
super(componentMetadataDefinition);
- componentType = ComponentTypeEnum.RESOURCE;
+ this.getComponentMetadataDefinition().getMetadataDataDefinition().setComponentType(ComponentTypeEnum.RESOURCE);
}
private List<String> derivedFrom;
@@ -57,7 +59,7 @@ public class Resource extends Component implements Serializable {
private List<String> defaultCapabilities;
- private List<AdditionalInformationDefinition> additionalInformation;
+// private List<AdditionalInformationDefinition> additionalInformation;
/**
* Please note that more than one "derivedFrom" resource is not currently
@@ -150,13 +152,6 @@ public class Resource extends Component implements Serializable {
.setLicenseType(licenseType);
}
- public List<AdditionalInformationDefinition> getAdditionalInformation() {
- return additionalInformation;
- }
-
- public void setAdditionalInformation(List<AdditionalInformationDefinition> additionalInformation) {
- this.additionalInformation = additionalInformation;
- }
@Override
public int hashCode() {
@@ -270,4 +265,29 @@ public class Resource extends Component implements Serializable {
return ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition())
.getVendorRelease();
}
+
+ @Override
+ public String fetchGenericTypeToscaNameFromConfig(){
+ String result = super.fetchGenericTypeToscaNameFromConfig();
+ if(null == result)
+ result = ConfigurationManager.getConfigurationManager().getConfiguration().getGenericAssetNodeTypes().get(ResourceTypeEnum.VFC.getValue());
+ return result;
+ }
+
+ @Override
+ public String assetType(){
+ return this.getResourceType().name();
+ }
+
+ @Override
+ public boolean shouldGenerateInputs(){
+ //TODO add complex VFC condition when supported
+ return ResourceTypeEnum.VF == this.getResourceType();
+ }
+
+ @Override
+ public boolean deriveFromGeneric(){
+ return this.shouldGenerateInputs() || (derivedFrom != null && derivedFrom.contains(fetchGenericTypeToscaNameFromConfig()));
+ }
+
}
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 e47333457f..37a42bd581 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,26 +20,29 @@
package org.openecomp.sdc.be.model;
-import java.util.List;
import java.util.Map;
-
import org.openecomp.sdc.be.datatypes.components.ServiceMetadataDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum;
public class Service extends Component {
+
+ private static final long serialVersionUID = -8819935942700578059L;
+
public Service() {
super(new ServiceMetadataDefinition());
- componentType = ComponentTypeEnum.SERVICE;
+ this.getComponentMetadataDefinition().getMetadataDataDefinition().setComponentType(ComponentTypeEnum.SERVICE);
+ this.setToscaType(ToscaElementTypeEnum.TopologyTemplate.getValue());
}
public Service(ComponentMetadataDefinition serviceMetadataDefinition) {
super(serviceMetadataDefinition);
- componentType = ComponentTypeEnum.SERVICE;
+ this.getComponentMetadataDefinition().getMetadataDataDefinition().setComponentType(ComponentTypeEnum.SERVICE);
+ this.setToscaType(ToscaElementTypeEnum.TopologyTemplate.getValue());
}
private Map<String, ArtifactDefinition> serviceApiArtifacts;
- private List<AdditionalInformationDefinition> additionalInformation;
public Map<String, ArtifactDefinition> getServiceApiArtifacts() {
return serviceApiArtifacts;
@@ -71,18 +74,27 @@ public class Service extends Component {
getServiceMetadataDefinition().setDistributionStatus(distributionStatus.name());
}
- private ServiceMetadataDataDefinition getServiceMetadataDefinition() {
- return (ServiceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition();
+ public void setEcompGeneratedNaming(Boolean ecompGeneratedNaming) {
+ getServiceMetadataDefinition().setEcompGeneratedNaming(ecompGeneratedNaming);
+ }
+
+ public Boolean isEcompGeneratedNaming() {
+ return getServiceMetadataDefinition().isEcompGeneratedNaming();
+ }
+
+ public void setNamingPolicy(String namingPolicy) {
+ getServiceMetadataDefinition().setNamingPolicy(namingPolicy);
}
- public List<AdditionalInformationDefinition> getAdditionalInformation() {
- return additionalInformation;
+ public String getNamingPolicy() {
+ return getServiceMetadataDefinition().getNamingPolicy();
}
- public void setAdditionalInformation(List<AdditionalInformationDefinition> additionalInformation) {
- this.additionalInformation = additionalInformation;
+ private ServiceMetadataDataDefinition getServiceMetadataDefinition() {
+ return (ServiceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition();
}
+
@Override
public String toString() {
return "Service [componentMetadataDefinition=" + getComponentMetadataDefinition()
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 2e92ca5df3..f30ef353b1 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
@@ -30,6 +30,7 @@ public class TargetCapabilityRelDef implements Serializable {
*/
private static final long serialVersionUID = -7571489368200736413L;
+ private String uid;
private String toNode;
// private List<ImmutablePair<String, RelationshipImpl>> relationships;
@@ -66,6 +67,14 @@ public class TargetCapabilityRelDef implements Serializable {
return relationships;
}
+ public String getUid() {
+ return uid;
+ }
+
+ public void setUid(String uid) {
+ this.uid = uid;
+ }
+
public void setRelationships(List<RequirementAndRelationshipPair> relationships) {
this.relationships = relationships;
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadPropInfo.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadPropInfo.java
index 60a58c9aed..5640f5582c 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadPropInfo.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadPropInfo.java
@@ -23,6 +23,9 @@ package org.openecomp.sdc.be.model;
import java.util.List;
import java.util.Map;
+import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
+
+
public class UploadPropInfo extends UploadInfo {
private Object value;
@@ -31,13 +34,13 @@ public class UploadPropInfo extends UploadInfo {
private boolean password;
- private List<GetInputValueInfo> get_input;
+ private List<GetInputValueDataDefinition> get_input;
- public List<GetInputValueInfo> getGet_input() {
+ public List<GetInputValueDataDefinition> getGet_input() {
return get_input;
}
- public void setGet_input(List<GetInputValueInfo> get_input) {
+ public void setGet_input(List<GetInputValueDataDefinition> get_input) {
this.get_input = get_input;
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/ApplicationDataTypeCache.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/ApplicationDataTypeCache.java
index 31664c929b..4c8d239704 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/ApplicationDataTypeCache.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/ApplicationDataTypeCache.java
@@ -25,7 +25,6 @@ import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
-import java.util.TreeMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
@@ -41,10 +40,10 @@ import javax.annotation.Resource;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
-import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
import org.openecomp.sdc.be.config.Configuration.ApplicationL1CacheConfig;
import org.openecomp.sdc.be.config.Configuration.ApplicationL1CacheInfo;
+import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
import org.openecomp.sdc.be.model.DataTypeDefinition;
import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
@@ -93,7 +92,7 @@ public class ApplicationDataTypeCache implements ApplicationCache<DataTypeDefini
if (firstRunDelay != null) {
firstRunDelayInSec = firstRunDelay;
}
- log.trace("ApplicationDataTypesCache polling interval is " + pollingIntervalInSec + " seconds.");
+ log.trace("ApplicationDataTypesCache polling interval is {} seconds.", pollingIntervalInSec);
if (scheduledPollingService != null) {
log.debug("Start ApplicationDataTypeCache polling task. polling interval {} seconds",
pollingIntervalInSec);
@@ -210,7 +209,7 @@ public class ApplicationDataTypeCache implements ApplicationCache<DataTypeDefini
log.trace("Start fetching all data types from db");
Either<List<DataTypeData>, TitanOperationStatus> allDataTypeNodes = propertyOperation.getAllDataTypeNodes();
Long end = System.currentTimeMillis();
- log.trace("Finish fetching all data types from db. Took " + (end - start) + " Milliseconds");
+ log.trace("Finish fetching all data types from db. Took {} Milliseconds", (end - start));
if (allDataTypeNodes.isRight()) {
TitanOperationStatus status = allDataTypeNodes.right().value();
if (status != TitanOperationStatus.OK) {
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 6732adbdb1..cb85deeb2d 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
@@ -56,6 +56,7 @@ import org.openecomp.sdc.be.model.LifecycleStateEnum;
import org.openecomp.sdc.be.model.Product;
import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.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.*;
import org.openecomp.sdc.be.resources.data.ComponentCacheData;
@@ -63,6 +64,7 @@ import org.openecomp.sdc.common.util.SerializationUtils;
import org.openecomp.sdc.common.util.ZipUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
import fj.data.Either;
@@ -73,15 +75,9 @@ public class ComponentCache {
@javax.annotation.Resource
ComponentCassandraDao componentCassandraDao;
-
- @javax.annotation.Resource
- ResourceOperation resourceOperation;
-
- @javax.annotation.Resource
- ServiceOperation serviceOperation;
-
- @javax.annotation.Resource
- ProductOperation productOperation;
+
+ @Autowired
+ ToscaOperationFacade toscaOperationFacade;
private Map<ComponentTypeEnum, Map<String, Component>> catalogInMemoryCache = new HashMap<>();
private final ReentrantReadWriteLock rwCatalogLock = new ReentrantReadWriteLock();
@@ -626,13 +622,7 @@ public class ComponentCache {
return false;
}
- ComponentOperation componentOperation = getComponentOperation(nodeTypeEnum);
-
- if (componentOperation == null) {
- return false;
- }
-
- Either<Component, StorageOperationStatus> either = componentOperation.getComponent(componentUid, false);
+ Either<Component, StorageOperationStatus> either = toscaOperationFacade.getToscaElement(componentUid);
if (either.isLeft()) {
Component component = either.left().value();
result = saveComponent(componentUid, lastModificationTime, nodeTypeEnum, component);
@@ -675,8 +665,7 @@ public class ComponentCache {
logger.debug("Failed to prepare component {} of type {} for cache", componentUid,
nodeTypeEnum.name().toLowerCase());
if (logger.isTraceEnabled()) {
- logger.trace("Failed to prepare component " + componentUid + " of type "
- + nodeTypeEnum.name().toLowerCase() + " for cache");
+ logger.trace("Failed to prepare component {} of type {} for cache",componentUid,nodeTypeEnum.name().toLowerCase());
}
}
} else {
@@ -704,24 +693,6 @@ public class ComponentCache {
}
- private ComponentOperation getComponentOperation(NodeTypeEnum nodeTypeEnum) {
- ComponentOperation componentOperation = null;
- switch (nodeTypeEnum) {
- case Resource:
- componentOperation = resourceOperation;
- break;
- case Service:
- componentOperation = serviceOperation;
- break;
- case Product:
- componentOperation = productOperation;
- break;
- default:
- break;
- }
- return componentOperation;
- }
-
/**
* get components from cache of a given list ou unique ids.
*
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/DaoInfo.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/DaoInfo.java
index bc63b34fec..c7bcc54d3d 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/DaoInfo.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/DaoInfo.java
@@ -20,34 +20,19 @@
package org.openecomp.sdc.be.model.cache;
-import org.openecomp.sdc.be.model.operations.api.IProductOperation;
-import org.openecomp.sdc.be.model.operations.api.IResourceOperation;
-import org.openecomp.sdc.be.model.operations.api.IServiceOperation;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
public class DaoInfo {
- private IResourceOperation iResourceOperation;
- private IServiceOperation iServiceOperation;
- private IProductOperation iProductOperation;
+ private ToscaOperationFacade toscaOperationFacade;
private ComponentCache ComponentCache;
- public DaoInfo(IResourceOperation iResourceOperation, IServiceOperation iServiceOperation,
- IProductOperation iProductOperation, org.openecomp.sdc.be.model.cache.ComponentCache componentCache) {
- this.iResourceOperation = iResourceOperation;
- this.iServiceOperation = iServiceOperation;
- this.iProductOperation = iProductOperation;
+ public DaoInfo(ToscaOperationFacade toscaOperationFacade, org.openecomp.sdc.be.model.cache.ComponentCache componentCache) {
+ this.toscaOperationFacade = toscaOperationFacade;
ComponentCache = componentCache;
}
- public IResourceOperation getResourceOperation() {
- return iResourceOperation;
- }
-
- public IServiceOperation getServiceOperation() {
- return iServiceOperation;
- }
-
- public IProductOperation getProductOperation() {
- return iProductOperation;
+ public ToscaOperationFacade getToscaOperationFacade() {
+ return toscaOperationFacade;
}
public org.openecomp.sdc.be.model.cache.ComponentCache getComponentCache() {
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/jobs/CheckAndUpdateJob.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/jobs/CheckAndUpdateJob.java
index 93249c914a..dfc39042bd 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/jobs/CheckAndUpdateJob.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/jobs/CheckAndUpdateJob.java
@@ -80,7 +80,7 @@ public class CheckAndUpdateJob extends Job {
} catch (Exception e) {
log.debug("an exception was encountered during CheckAndUpdateJob", e);
} finally {
- daoInfo.getResourceOperation().getTitanGenericDao().commit();
+ daoInfo.getToscaOperationFacade().commit();
}
return false;
}
@@ -109,8 +109,7 @@ public class CheckAndUpdateJob extends Job {
} else {
// update cache
// get component from grath
- Either<Component, StorageOperationStatus> componentRes = getOperationByType(nodeTypeEnum)
- .getComponent(componentId, true);
+ Either<Component, StorageOperationStatus> componentRes = daoInfo.getToscaOperationFacade().getToscaElement(componentId);
if (componentRes.isRight()) {
log.debug("failed to get full component:{} from graph status:{}", componentId,
componentRes.right().value());
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/jobs/Job.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/jobs/Job.java
index 4deda8642f..c1fb2e0a7f 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/jobs/Job.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/jobs/Job.java
@@ -55,28 +55,9 @@ public abstract class Job<E> {
public abstract E doWork();
- protected IComponentOperation getOperationByType(NodeTypeEnum nodeTypeEnum) {
- IComponentOperation operation = null;
- switch (nodeTypeEnum) {
- case Product:
- operation = daoInfo.getProductOperation();
- break;
- case Service:
- operation = daoInfo.getServiceOperation();
- break;
- case Resource:
- operation = daoInfo.getResourceOperation();
- break;
- default:
- log.error("unexpected NodeType received no matching operation found.");
- }
- return operation;
- }
-
protected Either<ComponentMetadataData, StorageOperationStatus> getComponentMetaData(String componentId,
NodeTypeEnum nodeTypeEnum) {
- Either<ComponentMetadataData, StorageOperationStatus> metaDataRes = getOperationByType(nodeTypeEnum)
- .getComponentByLabelAndId(componentId, nodeTypeEnum, ComponentMetadataData.class);
+ Either<ComponentMetadataData, StorageOperationStatus> metaDataRes = daoInfo.getToscaOperationFacade().getComponentMetadata(componentId);
if (metaDataRes.isRight()) {
// in case we cant find the component on graph exit
if (StorageOperationStatus.NOT_FOUND.equals(metaDataRes.right().value())) {
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/jobs/OverrideJob.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/jobs/OverrideJob.java
index e9da68ea59..47edae8968 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/jobs/OverrideJob.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/jobs/OverrideJob.java
@@ -47,8 +47,7 @@ public class OverrideJob extends Job {
log.trace("override component in cache, componentId:{} of nodeTypeEnum:{} with timestamp:{}.", componentId,
nodeTypeEnum, timestamp);
// get component from grath
- Either<Component, StorageOperationStatus> componentRes = getOperationByType(nodeTypeEnum)
- .getComponent(componentId, false);
+ Either<Component, StorageOperationStatus> componentRes = daoInfo.getToscaOperationFacade().getToscaElement(componentId);
if (componentRes.isRight()) {
log.debug("failed to get full component:{} from graph status:{}", componentId,
componentRes.right().value());
@@ -66,7 +65,7 @@ public class OverrideJob extends Job {
} catch (Exception e) {
log.debug("an exception was encountered during OverrideJob", e);
} finally {
- this.daoInfo.getResourceOperation().getTitanGenericDao().commit();
+ this.daoInfo.getToscaOperationFacade().commit();
}
return false;
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/jobs/StoreJob.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/jobs/StoreJob.java
index 410a56a90e..c282e5dca5 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/jobs/StoreJob.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/jobs/StoreJob.java
@@ -42,14 +42,12 @@ public class StoreJob extends Job {
public Object doWork() {
try {
log.trace("starting work on job.");
- log.trace("store component in cache, componentId:{} of nodeTypeEnum:{} with timestamp:{}.", componentId,
- nodeTypeEnum, timestamp);
+ log.trace("store component in cache, componentId:{} of nodeTypeEnum:{} with timestamp:{}.", componentId, nodeTypeEnum, timestamp);
if (!this.daoInfo.getComponentCache().setComponent(component, nodeTypeEnum)) {
log.debug("failed to store componentId:{} nodeTypeEnum:", componentId, nodeTypeEnum);
return false;
}
- log.debug("cache successfully updated for componentId:{} nodeTypeEnum:{} timestemp:{}.", componentId,
- nodeTypeEnum, timestamp);
+ log.debug("cache successfully updated for componentId:{} nodeTypeEnum:{} timestemp:{}.", componentId, nodeTypeEnum, timestamp);
return true;
} catch (Exception e) {
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/heat/HeatParameterType.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/heat/HeatParameterType.java
index 7de0aa561d..5fbeb4f808 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/heat/HeatParameterType.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/heat/HeatParameterType.java
@@ -44,7 +44,8 @@ public enum HeatParameterType {
JSON("json", HeatStringValidator.getInstance(), HeatJsonConverter.getInstance()),
- COMMA_DELIMITED_LIST("comma_delimited_list", HeatCommaDelimitedListValidator.getInstance(), HeatCommaDelimitedListConverter.getInstance());
+ COMMA_DELIMITED_LIST("comma_delimited_list", HeatCommaDelimitedListValidator.getInstance(),
+ HeatCommaDelimitedListConverter.getInstance());
private String type;
private PropertyTypeValidator validator;
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/datamodel/NodeType.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/datamodel/NodeType.java
new file mode 100644
index 0000000000..7c6c207f74
--- /dev/null
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/datamodel/NodeType.java
@@ -0,0 +1,88 @@
+package org.openecomp.sdc.be.model.jsontitan.datamodel;
+
+import java.util.List;
+import java.util.Map;
+
+import org.openecomp.sdc.be.datatypes.elements.AttributeDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.InterfaceDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.ListRequirementDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition;
+
+public class NodeType extends ToscaElement{
+
+ public NodeType() {
+ super(ToscaElementTypeEnum.NodeType);
+ }
+
+ private List<String> derivedFrom;
+ private List<String> derivedList;
+
+ private Map<String, AttributeDataDefinition> attributes;
+ private Map<String, ListCapabilityDataDefinition> capabilties;
+ private Map<String, MapPropertiesDataDefinition> capabiltiesProperties;
+ private Map<String, ListRequirementDataDefinition> requirements;
+ private Map<String, InterfaceDataDefinition> interfaceArtifacts;
+
+
+ // will be used in future
+ // private Map<String, Map<String, Object>> other;
+
+
+ public List<String> getDerivedList() {
+ return derivedList;
+ }
+
+ public void setDerivedList(List<String> derivedList) {
+ this.derivedList = derivedList;
+ }
+
+ public List<String> getDerivedFrom() {
+ return derivedFrom;
+ }
+
+ public void setDerivedFrom(List<String> derivedFrom) {
+ this.derivedFrom = derivedFrom;
+ }
+
+ public Map<String, AttributeDataDefinition> getAttributes() {
+ return attributes;
+ }
+
+ public void setAttributes(Map<String, AttributeDataDefinition> attributes) {
+ this.attributes = attributes;
+ }
+
+ public Map<String, ListCapabilityDataDefinition> getCapabilties() {
+ return capabilties;
+ }
+
+ public void setCapabilties(Map<String, ListCapabilityDataDefinition> capabilties) {
+ this.capabilties = capabilties;
+ }
+
+ public Map<String, ListRequirementDataDefinition> getRequirements() {
+ return requirements;
+ }
+
+ public void setRequirements(Map<String, ListRequirementDataDefinition> requirements) {
+ this.requirements = requirements;
+ }
+
+ public Map<String, MapPropertiesDataDefinition> getCapabiltiesProperties() {
+ return capabiltiesProperties;
+ }
+
+ public void setCapabiltiesProperties(Map<String, MapPropertiesDataDefinition> capabiltiesProperties) {
+ this.capabiltiesProperties = capabiltiesProperties;
+ }
+
+ public Map<String, InterfaceDataDefinition> getInterfaceArtifacts() {
+ return interfaceArtifacts;
+ }
+
+ public void setInterfaceArtifacts(Map<String, InterfaceDataDefinition> interfaceArtifacts) {
+ this.interfaceArtifacts = interfaceArtifacts;
+ }
+
+}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/datamodel/TopologyTemplate.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/datamodel/TopologyTemplate.java
new file mode 100644
index 0000000000..74c4c30aa5
--- /dev/null
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/datamodel/TopologyTemplate.java
@@ -0,0 +1,199 @@
+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.MapAttributesDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.MapCapabiltyProperty;
+import org.openecomp.sdc.be.datatypes.elements.MapGroupsDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.MapListCapabiltyDataDefinition;
+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.tosca.ToscaDataDefinition;
+import org.openecomp.sdc.be.model.jsontitan.enums.JsonConstantKeysEnum;
+
+public class TopologyTemplate extends ToscaElement{
+
+ public TopologyTemplate() {
+ super(ToscaElementTypeEnum.TopologyTemplate);
+ }
+ private Map<String, PropertyDataDefinition> inputs;
+ private Map<String, MapPropertiesDataDefinition> instInputs;
+ private Map<String, ? extends ToscaDataDefinition> heatParameters;
+ private Map<String, MapAttributesDataDefinition> instAttributes;
+ private Map<String, MapPropertiesDataDefinition> instProperties;
+ private Map<String, GroupDataDefinition> groups;
+ private Map<String, MapGroupsDataDefinition> instGroups;
+ private Map<String, ArtifactDataDefinition> serviceApiArtifacts;
+ private Map<String, CompositionDataDefinition> compositions;
+
+ private Map<String, MapListCapabiltyDataDefinition> calculatedCapabilities;
+ private Map<String, MapListRequirementDataDefinition> calculatedRequirements;
+ private Map<String, MapListCapabiltyDataDefinition> fullfilledCapabilities;
+ private Map<String, MapListRequirementDataDefinition> fullfilledRequirements;
+
+ private Map<String, MapCapabiltyProperty> calculatedCapabilitiesProperties;
+
+ private Map<String, MapArtifactDataDefinition> instDeploymentArtifacts;
+ private Map<String, MapArtifactDataDefinition> instanceArtifacts;
+
+
+ public Map<String, PropertyDataDefinition> getInputs() {
+ return inputs;
+ }
+ public void setInputs(Map<String, PropertyDataDefinition> inputs) {
+ this.inputs = inputs;
+ }
+ public Map<String, MapPropertiesDataDefinition> getInstInputs() {
+ return instInputs;
+ }
+ public void setInstInputs(Map<String, MapPropertiesDataDefinition> instInputs) {
+ this.instInputs = instInputs;
+ }
+ public Map<String, ? extends ToscaDataDefinition> getHeatParameters() {
+ return heatParameters;
+ }
+ public void setHeatParameters(Map<String, ? extends ToscaDataDefinition> heatParameters) {
+ this.heatParameters = heatParameters;
+ }
+ public Map<String, MapAttributesDataDefinition> getInstAttributes() {
+ return instAttributes;
+ }
+ public void setInstAttributes(Map<String, MapAttributesDataDefinition> instAttributes) {
+ this.instAttributes = instAttributes;
+ }
+ public Map<String, MapPropertiesDataDefinition> getInstProperties() {
+ return instProperties;
+ }
+ public void setInstProperties(Map<String, MapPropertiesDataDefinition> instProperties) {
+ this.instProperties = instProperties;
+ }
+ public Map<String, GroupDataDefinition> getGroups() {
+ return groups;
+ }
+ public void setGroups(Map<String, GroupDataDefinition> groups) {
+ this.groups = groups;
+ }
+ public Map<String, MapGroupsDataDefinition> getInstGroups() {
+ return instGroups;
+ }
+ public void setInstGroups(Map<String, MapGroupsDataDefinition> instGroups) {
+ this.instGroups = instGroups;
+ }
+ public Map<String, ArtifactDataDefinition> getServiceApiArtifacts() {
+ return serviceApiArtifacts;
+ }
+ public void setServiceApiArtifacts(Map<String, ArtifactDataDefinition> serviceApiArtifacts) {
+ this.serviceApiArtifacts = serviceApiArtifacts;
+ }
+ public Map<String, CompositionDataDefinition> getCompositions() {
+ return compositions;
+ }
+ public void setCompositions(Map<String, CompositionDataDefinition> compositions) {
+ this.compositions = compositions;
+ }
+ public Map<String, MapListCapabiltyDataDefinition> getCalculatedCapabilities() {
+ return calculatedCapabilities;
+ }
+ public void setCalculatedCapabilities(Map<String, MapListCapabiltyDataDefinition> calculatedCapabilities) {
+ this.calculatedCapabilities = calculatedCapabilities;
+ }
+ public Map<String, MapListRequirementDataDefinition> getCalculatedRequirements() {
+ return calculatedRequirements;
+ }
+ public void setCalculatedRequirements(Map<String, MapListRequirementDataDefinition> calculatedRequirements) {
+ this.calculatedRequirements = calculatedRequirements;
+ }
+ public Map<String, MapListCapabiltyDataDefinition> getFullfilledCapabilities() {
+ return fullfilledCapabilities;
+ }
+ public void setFullfilledCapabilities(Map<String, MapListCapabiltyDataDefinition> fullfilledCapabilities) {
+ this.fullfilledCapabilities = fullfilledCapabilities;
+ }
+ public Map<String, MapListRequirementDataDefinition> getFullfilledRequirements() {
+ return fullfilledRequirements;
+ }
+ public void setFullfilledRequirements(Map<String, MapListRequirementDataDefinition> fullfilledRequirements) {
+ this.fullfilledRequirements = fullfilledRequirements;
+ }
+
+ public Map<String, MapArtifactDataDefinition> getInstDeploymentArtifacts() {
+ return instDeploymentArtifacts;
+ }
+ public void setInstDeploymentArtifacts(Map<String, MapArtifactDataDefinition> instDeploymentArtifacts) {
+ this.instDeploymentArtifacts = instDeploymentArtifacts;
+ }
+
+ public Map<String, MapCapabiltyProperty> getCalculatedCapabilitiesProperties() {
+ return calculatedCapabilitiesProperties;
+ }
+ public void setCalculatedCapabilitiesProperties(Map<String, MapCapabiltyProperty> calculatedCapabilitiesProperties) {
+ this.calculatedCapabilitiesProperties = calculatedCapabilitiesProperties;
+ }
+
+ public Map<String, MapArtifactDataDefinition> getInstanceArtifacts() {
+ return instanceArtifacts;
+ }
+ public void setInstanceArtifacts(Map<String, MapArtifactDataDefinition> instanceArtifacts) {
+ this.instanceArtifacts = instanceArtifacts;
+ }
+ /**
+ * Adds component instance to composition of topology template
+ * Note that component instance will be overrided in case if the topology template already contains a component instance with the same name
+ * @param componentInstance
+ */
+ public void addComponentInstance(ComponentInstanceDataDefinition componentInstance){
+ if(getCompositions() == null){
+ compositions = new HashMap<>();
+ }
+ if(MapUtils.isEmpty(getCompositions())){
+ compositions.put(JsonConstantKeysEnum.COMPOSITION.getValue(), new CompositionDataDefinition());
+ }
+ if(MapUtils.isEmpty(getCompositions().get(JsonConstantKeysEnum.COMPOSITION.getValue()).getComponentInstances())){
+ getCompositions().get(JsonConstantKeysEnum.COMPOSITION.getValue()).setComponentInstances(new HashMap<>());
+ }
+ getCompositions().get(JsonConstantKeysEnum.COMPOSITION.getValue()).getComponentInstances().put(componentInstance.getUniqueId(), componentInstance);
+ }
+ /**
+ * Returns map of component inctances from composition
+ * @return
+ */
+ public Map<String, ComponentInstanceDataDefinition> getComponentInstances() {
+ Map<String, ComponentInstanceDataDefinition> instances = null;
+ if(getCompositions() != null && getCompositions().get(JsonConstantKeysEnum.COMPOSITION.getValue()) != null ){
+ instances = getCompositions().get(JsonConstantKeysEnum.COMPOSITION.getValue()).getComponentInstances();
+ }
+ return instances;
+ }
+
+
+ /**
+ * Sets map of component instances to composition of topology template
+ * Note that component instances will be overrided in case if the topology template already contains a component instances
+ * @param instances
+ */
+ public void setComponentInstances(Map<String, ComponentInstanceDataDefinition> instances) {
+ if(getCompositions() == null){
+ compositions = new HashMap<>();
+ }
+ if(MapUtils.isEmpty(getCompositions())){
+ compositions.put(JsonConstantKeysEnum.COMPOSITION.getValue(), new CompositionDataDefinition());
+ }
+ getCompositions().get(JsonConstantKeysEnum.COMPOSITION.getValue()).setComponentInstances(instances);
+ }
+ public Map<String, RelationshipInstDataDefinition> getRelations() {
+ Map<String, RelationshipInstDataDefinition> relations = null;
+ if( getCompositions() != null && getCompositions().get(JsonConstantKeysEnum.COMPOSITION.getValue()) != null ){
+ relations = getCompositions().get(JsonConstantKeysEnum.COMPOSITION.getValue()).getRelations();
+ }
+ return relations;
+ }
+}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/datamodel/ToscaElement.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/datamodel/ToscaElement.java
new file mode 100644
index 0000000000..72cf89f13c
--- /dev/null
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/datamodel/ToscaElement.java
@@ -0,0 +1,277 @@
+package org.openecomp.sdc.be.model.jsontitan.datamodel;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+
+import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.LifecycleStateEnum;
+import org.openecomp.sdc.be.model.category.CategoryDefinition;
+import org.openecomp.sdc.be.model.jsontitan.operations.NodeTypeOperation;
+import org.slf4j.MDC;
+
+public abstract class ToscaElement {
+
+ protected Map<String, Object> metadata;
+ protected List<CategoryDefinition> categories;
+ protected Map<String, ArtifactDataDefinition> toscaArtifacts;
+ private Map<String, ArtifactDataDefinition> artifacts;
+ private Map<String, ArtifactDataDefinition> deploymentArtifacts;
+ private Map<String, AdditionalInfoParameterDataDefinition> additionalInformation;
+ private Map<String, PropertyDataDefinition> properties;
+
+ protected ToscaElementTypeEnum toscaType;
+ // User
+ private String creatorUserId;
+ private String creatorFullName;
+ private String lastUpdaterUserId;
+ private String lastUpdaterFullName;
+
+ private Map<String, String> allVersions;
+
+ public ToscaElement(ToscaElementTypeEnum toscaType){
+ this.toscaType = toscaType;
+ }
+
+ public Map<String, Object> getMetadata() {
+ return metadata;
+ }
+
+ public void setMetadata(Map<String, Object> metadata) {
+ this.metadata = metadata;
+ }
+
+ public List<CategoryDefinition> getCategories() {
+ return categories;
+ }
+
+ public void setCategories(List<CategoryDefinition> categories) {
+ this.categories = categories;
+ }
+ public Map<String, ArtifactDataDefinition> getToscaArtifacts() {
+ return toscaArtifacts;
+ }
+
+ public void setToscaArtifacts(Map<String, ArtifactDataDefinition> toscaArtifacts) {
+ this.toscaArtifacts = toscaArtifacts;
+ }
+
+ public ToscaElementTypeEnum getToscaType() {
+ return toscaType;
+ }
+
+ public void setToscaType(ToscaElementTypeEnum toscaType) {
+ this.toscaType = toscaType;
+ }
+ public Map<String, ArtifactDataDefinition> getArtifacts() {
+ return artifacts;
+ }
+
+ public void setArtifacts(Map<String, ArtifactDataDefinition> artifacts) {
+ this.artifacts = artifacts;
+ }
+
+ public Map<String, ArtifactDataDefinition> getDeploymentArtifacts() {
+ return deploymentArtifacts;
+ }
+
+ public void setDeploymentArtifacts(Map<String, ArtifactDataDefinition> deploymentArtifacts) {
+ this.deploymentArtifacts = deploymentArtifacts;
+ }
+ public Map<String, AdditionalInfoParameterDataDefinition> getAdditionalInformation() {
+ return additionalInformation;
+ }
+ public void setAdditionalInformation(Map<String, AdditionalInfoParameterDataDefinition> additionalInformation) {
+ this.additionalInformation = additionalInformation;
+ }
+ public Map<String, PropertyDataDefinition> getProperties() {
+ return properties;
+ }
+ public void setProperties(Map<String, PropertyDataDefinition> properties) {
+ this.properties = properties;
+ }
+
+ public Map<String, String> getAllVersions() {
+ return allVersions;
+ }
+
+ public void setAllVersions(Map<String, String> allVersions) {
+ this.allVersions = allVersions;
+ }
+
+ // metadata properties
+ // ----------------------------
+ public Object getMetadataValue(JsonPresentationFields name) {
+ return getMetadataValueOrDefault(name, null);
+ }
+
+ public Object getMetadataValueOrDefault(JsonPresentationFields name, Object defaultVal) {
+ if (metadata != null) {
+ return metadata.getOrDefault(name.getPresentation(), defaultVal);
+ }
+ return null;
+ }
+
+ public void setMetadataValue(JsonPresentationFields name, Object value) {
+ if (metadata == null) {
+ metadata = new HashMap<String, Object>();
+ }
+ metadata.put(name.getPresentation(), value);
+
+ }
+ // --------------------
+ public String getUUID() {
+ return (String) getMetadataValue(JsonPresentationFields.UUID);
+ }
+
+ public void setUUID(String uuid) {
+ setMetadataValue(JsonPresentationFields.UUID, uuid);
+ }
+
+ public String getVersion() {
+ return (String) getMetadataValue(JsonPresentationFields.VERSION);
+ }
+
+ public String getNormalizedName() {
+ return (String) getMetadataValue(JsonPresentationFields.NORMALIZED_NAME);
+ }
+
+ public void setNormalizedName(String normaliseComponentName) {
+ setMetadataValue(JsonPresentationFields.NORMALIZED_NAME, normaliseComponentName);
+ }
+
+ public String getName() {
+ return (String) getMetadataValue(JsonPresentationFields.NAME);
+ }
+
+ public String getSystemName() {
+ return (String) getMetadataValue(JsonPresentationFields.SYSTEM_NAME);
+ }
+ public void setSystemName(String systemName) {
+ setMetadataValue(JsonPresentationFields.SYSTEM_NAME, systemName);
+ }
+
+ public void setLifecycleState(LifecycleStateEnum state) {
+ if(state != null)
+ setMetadataValue(JsonPresentationFields.LIFECYCLE_STATE, state.name());
+ }
+
+ public LifecycleStateEnum getLifecycleState() {
+ return LifecycleStateEnum.findState( (String) getMetadataValue(JsonPresentationFields.LIFECYCLE_STATE));
+ }
+
+ public Long getCreationDate() {
+ return (Long) getMetadataValue(JsonPresentationFields.CREATION_DATE);
+ }
+
+ public void setCreationDate(Long currentDate) {
+ setMetadataValue(JsonPresentationFields.CREATION_DATE, currentDate);
+ }
+
+ public void setLastUpdateDate(Long currentDate) {
+ setMetadataValue(JsonPresentationFields.LAST_UPDATE_DATE, currentDate);
+ }
+ public Long getLastUpdateDate() {
+ return (Long) getMetadataValue(JsonPresentationFields.LAST_UPDATE_DATE);
+ }
+
+ public String getUniqueId() {
+ return (String) getMetadataValue(JsonPresentationFields.UNIQUE_ID);
+ }
+ public void setUniqueId(String uniqueId) {
+ setMetadataValue(JsonPresentationFields.UNIQUE_ID, uniqueId);
+ }
+
+ public void setHighestVersion(Boolean isHighest) {
+ setMetadataValue(JsonPresentationFields.HIGHEST_VERSION, isHighest);
+
+ }
+ public Boolean isHighestVersion() {
+ return (Boolean) getMetadataValue(JsonPresentationFields.HIGHEST_VERSION);
+
+ }
+ public ResourceTypeEnum getResourceType() {
+ String resourceType = (String) getMetadataValue(JsonPresentationFields.RESOURCE_TYPE);
+ return resourceType != null ? ResourceTypeEnum.valueOf(resourceType) : null;
+ }
+
+ public void setResourceType(ResourceTypeEnum resourceType) {
+ if(resourceType != null)
+ setMetadataValue(JsonPresentationFields.RESOURCE_TYPE, resourceType.name());
+ }
+
+ public ComponentTypeEnum getComponentType() {
+ return ComponentTypeEnum.valueOf((String) getMetadataValue(JsonPresentationFields.COMPONENT_TYPE));
+ }
+
+ public void setComponentType(ComponentTypeEnum componentType) {
+ if(componentType != null)
+ setMetadataValue(JsonPresentationFields.COMPONENT_TYPE, componentType.name());
+ }
+
+ public String getDerivedFromGenericType(){
+ return (String) getMetadataValue(JsonPresentationFields.DERIVED_FROM_GENERIC_TYPE);
+ }
+
+ public void setDerivedFromGenericType(String derivedFromGenericType){
+ setMetadataValue(JsonPresentationFields.DERIVED_FROM_GENERIC_TYPE, derivedFromGenericType);
+ }
+
+ public String getDerivedFromGenericVersion(){
+ return (String) getMetadataValue(JsonPresentationFields.DERIVED_FROM_GENERIC_VERSION);
+ }
+
+ public void setDerivedFromGenericVersion(String derivedFromGenericVersion){
+ setMetadataValue(JsonPresentationFields.DERIVED_FROM_GENERIC_VERSION, derivedFromGenericVersion);
+ }
+
+
+ public String getCreatorUserId() {
+ return creatorUserId;
+ }
+
+ public void setCreatorUserId(String creatorUserId) {
+ this.creatorUserId = creatorUserId;
+ }
+
+ public String getCreatorFullName() {
+ return creatorFullName;
+ }
+
+ public void setCreatorFullName(String creatorFullName) {
+ this.creatorFullName = creatorFullName;
+ }
+
+ public String getLastUpdaterUserId() {
+ return lastUpdaterUserId;
+ }
+
+ public void setLastUpdaterUserId(String lastUpdaterUserId) {
+ this.lastUpdaterUserId = lastUpdaterUserId;
+ }
+
+ public String getLastUpdaterFullName() {
+ return lastUpdaterFullName;
+ }
+
+ public void setLastUpdaterFullName(String lastUpdaterFullName) {
+ this.lastUpdaterFullName = lastUpdaterFullName;
+ }
+
+ public void generateUUID() {
+ String prevUUID = getUUID();
+ String version = getVersion();
+ if ((prevUUID == null && NodeTypeOperation.uuidNormativeNewVersion.matcher(version).matches()) || NodeTypeOperation.uuidNewVersion.matcher(version).matches()) {
+ UUID uuid = UUID.randomUUID();
+ setUUID(uuid.toString());
+ MDC.put("serviceInstanceID", uuid.toString());
+ }
+ }
+
+}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/datamodel/ToscaElementTypeEnum.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/datamodel/ToscaElementTypeEnum.java
new file mode 100644
index 0000000000..7a8f76e511
--- /dev/null
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/datamodel/ToscaElementTypeEnum.java
@@ -0,0 +1,29 @@
+package org.openecomp.sdc.be.model.jsontitan.datamodel;
+
+import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
+
+public enum ToscaElementTypeEnum {
+ NodeType("node_type"),
+ TopologyTemplate("topology_template");
+
+ String value;
+ private ToscaElementTypeEnum(String value){
+ this.value = value;
+ }
+
+ public static VertexTypeEnum getVertexTypeByToscaType(ToscaElementTypeEnum toscaType ){
+ switch ( toscaType ){
+ case NodeType :
+ return VertexTypeEnum.NODE_TYPE;
+ case TopologyTemplate :
+ return VertexTypeEnum.TOPOLOGY_TEMPLATE;
+ default :
+ return null;
+ }
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/enums/JsonConstantKeysEnum.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/enums/JsonConstantKeysEnum.java
new file mode 100644
index 0000000000..12ff27fa70
--- /dev/null
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/enums/JsonConstantKeysEnum.java
@@ -0,0 +1,22 @@
+package org.openecomp.sdc.be.model.jsontitan.enums;
+
+public enum JsonConstantKeysEnum {
+
+ COMPOSITION("composition"),
+ CAPABILITIES("capabilities"),
+ REQUIREMENTS("requirements"),
+ PROPERTIES("properties"),
+ INPUTS("inputs"),
+ GROUPS("groups"),
+ INSTANCE_PROPERIES("instanceProperties");
+
+ private String value;
+
+ private JsonConstantKeysEnum(String value) {
+ this.value = value;
+ }
+
+ public String getValue() {
+ return value;
+ }
+}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ArtifactsOperations.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ArtifactsOperations.java
new file mode 100644
index 0000000000..55853479d2
--- /dev/null
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ArtifactsOperations.java
@@ -0,0 +1,623 @@
+package org.openecomp.sdc.be.model.jsontitan.operations;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.UUID;
+import java.util.stream.Collectors;
+
+import org.apache.commons.collections.MapUtils;
+import org.apache.commons.lang3.tuple.ImmutableTriple;
+import org.apache.commons.lang3.tuple.Triple;
+import org.apache.tinkerpop.gremlin.structure.Direction;
+import org.openecomp.sdc.be.config.BeEcompErrorManager;
+import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
+import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
+import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
+import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
+import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.MapArtifactDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+import org.openecomp.sdc.be.model.ArtifactDefinition;
+import org.openecomp.sdc.be.model.HeatParameterDefinition;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
+import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
+import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
+import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
+import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.slf4j.MDC;
+
+import fj.data.Either;
+
+@org.springframework.stereotype.Component("artifacts-operations")
+
+public class ArtifactsOperations extends BaseOperation {
+ private static Logger log = LoggerFactory.getLogger(ArtifactsOperations.class.getName());
+
+ public Either<ArtifactDefinition, StorageOperationStatus> addArifactToComponent(ArtifactDefinition artifactInfo, String parentId, NodeTypeEnum type, boolean failIfExist, String instanceId) {
+
+ Either<ArtifactDataDefinition, StorageOperationStatus> status = updateArtifactOnGraph(parentId, artifactInfo, type, artifactInfo.getUniqueId(), instanceId);
+ if (status.isRight()) {
+
+ log.debug("Failed to update artifact {} of {} {}. status is {}", artifactInfo.getArtifactName(), type.getName(), parentId, status.right().value());
+ BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("Update Artifact", artifactInfo.getArtifactName(), String.valueOf(status.right().value()));
+ return Either.right(status.right().value());
+ } else {
+
+ ArtifactDataDefinition artifactData = status.left().value();
+
+ ArtifactDefinition artifactDefResult = convertArtifactDataToArtifactDefinition(artifactInfo, artifactData);
+ log.debug("The returned ArtifactDefintion is {}", artifactDefResult);
+ return Either.left(artifactDefResult);
+ }
+
+ }
+
+ public Either<ArtifactDefinition, StorageOperationStatus> updateArifactOnResource(ArtifactDefinition artifactInfo, String id, String artifactId, NodeTypeEnum type, String instanceId) {
+
+ Either<ArtifactDataDefinition, StorageOperationStatus> status = updateArtifactOnGraph(id, artifactInfo, type, artifactId, instanceId);
+ if (status.isRight()) {
+
+ log.debug("Failed to update artifact {} of {} {}. status is {}", artifactInfo.getArtifactName(), type.getName(), id, status.right().value());
+ BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("Update Artifact", artifactInfo.getArtifactName(), String.valueOf(status.right().value()));
+ return Either.right(status.right().value());
+ } else {
+
+ ArtifactDataDefinition artifactData = status.left().value();
+
+ ArtifactDefinition artifactDefResult = convertArtifactDataToArtifactDefinition(artifactInfo, artifactData);
+ log.debug("The returned ArtifactDefintion is {}", artifactDefResult);
+ return Either.left(artifactDefResult);
+ }
+ }
+
+ public Either<Boolean, StorageOperationStatus> isCloneNeeded(String parentId, ArtifactDefinition artifactInfo, NodeTypeEnum type) {
+ ArtifactGroupTypeEnum groupType = artifactInfo.getArtifactGroupType();
+
+ Triple<EdgeLabelEnum, Boolean, VertexTypeEnum> triple = getEdgeLabelEnumFromArtifactGroupType(groupType, type);
+ EdgeLabelEnum edgeLabelEnum = triple.getLeft();
+ return super.isCloneNeeded(parentId, edgeLabelEnum);
+ }
+
+ public Either<ArtifactDefinition, StorageOperationStatus> getArtifactById(String parentId, String id) {
+ return getArtifactById(parentId, id, null, null);
+ }
+
+ public Either<ArtifactDefinition, StorageOperationStatus> getArtifactById(String parentId, String id, ComponentTypeEnum componentType, String containerId) {
+ Either<ArtifactDefinition, StorageOperationStatus> result = null;
+ ArtifactDataDefinition foundArtifact = null;
+ if (componentType != null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
+ foundArtifact = getInstanceArtifactByLabelAndId(parentId, id, containerId, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS);
+ if ( foundArtifact == null ){
+ foundArtifact = getInstanceArtifactByLabelAndId(parentId, id, containerId, EdgeLabelEnum.INSTANCE_ARTIFACTS);
+ }
+ }
+ if (foundArtifact == null) {
+ foundArtifact = getArtifactByLabelAndId(parentId, id, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS);
+ }
+ if (foundArtifact == null) {
+ foundArtifact = getArtifactByLabelAndId(parentId, id, EdgeLabelEnum.TOSCA_ARTIFACTS);
+ }
+
+ if (foundArtifact == null) {
+ foundArtifact = getArtifactByLabelAndId(parentId, id, EdgeLabelEnum.ARTIFACTS);
+ }
+
+ if (foundArtifact == null) {
+ foundArtifact = getArtifactByLabelAndId(parentId, id, EdgeLabelEnum.SERVICE_API_ARTIFACTS);
+ }
+
+ if (foundArtifact == null) {
+ result = Either.right(StorageOperationStatus.NOT_FOUND);
+ return result;
+ }
+
+ ArtifactDefinition artifactDefResult = convertArtifactDataToArtifactDefinition(null, foundArtifact);
+ return Either.left(artifactDefResult);
+
+ }
+
+ public Either<ArtifactDefinition, StorageOperationStatus> removeArifactFromResource(String id, String artifactId, NodeTypeEnum type, boolean deleteMandatoryArtifact) {
+ Either<ArtifactDefinition, StorageOperationStatus> status = removeArtifactOnGraph(id, artifactId, type, deleteMandatoryArtifact);
+
+ if (status.isRight()) {
+
+ log.debug("Failed to delete artifact {} of resource {}", artifactId, id);
+
+ BeEcompErrorManager.getInstance().logBeFailedDeleteNodeError("Delete Artifact", artifactId, String.valueOf(status.right().value()));
+ return Either.right(status.right().value());
+ } else {
+
+ return Either.left(status.left().value());
+ }
+ }
+
+ public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType, ArtifactGroupTypeEnum groupType, String instanceId) {
+
+ Triple<EdgeLabelEnum, Boolean, VertexTypeEnum> triple = getEdgeLabelEnumFromArtifactGroupType(groupType, parentType);
+ EdgeLabelEnum edgeLabelEnum = triple.getLeft();
+
+ Either<Map<String, ArtifactDefinition>, TitanOperationStatus> foundArtifact = null;
+ Map<String, ArtifactDefinition> resMap = new HashMap<>();
+ foundArtifact = getArtifactByLabel(parentId, instanceId, edgeLabelEnum);
+ if (foundArtifact.isRight()) {
+ log.debug("Failed to find artifact in component {} with label {} ", parentId, edgeLabelEnum);
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(foundArtifact.right().value()));
+ }
+
+ resMap.putAll(foundArtifact.left().value());
+
+ return Either.left(resMap);
+ }
+
+ public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId) {
+
+ Either<Map<String, ArtifactDefinition>, TitanOperationStatus> foundArtifact = null;
+ Map<String, ArtifactDefinition> resMap = new HashMap<>();
+ foundArtifact = getArtifactByLabel(parentId, null, EdgeLabelEnum.ARTIFACTS);
+ if (foundArtifact.isLeft()) {
+ resMap.putAll(foundArtifact.left().value());
+
+ }
+ foundArtifact = getArtifactByLabel(parentId, null, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS);
+ if (foundArtifact.isLeft()) {
+ resMap.putAll(foundArtifact.left().value());
+
+ }
+ foundArtifact = getArtifactByLabel(parentId, null, EdgeLabelEnum.TOSCA_ARTIFACTS);
+ if (foundArtifact.isLeft()) {
+ resMap.putAll(foundArtifact.left().value());
+
+ }
+
+ return Either.left(resMap);
+
+ }
+
+ public Either<ArtifactDefinition, StorageOperationStatus> removeArtifactOnGraph(String id, String artifactId, NodeTypeEnum type, boolean deleteMandatoryArtifact) {
+
+ Either<ArtifactDefinition, StorageOperationStatus> artifactData = this.getArtifactById(id, artifactId);
+ if (artifactData.isRight()) {
+ log.debug("Failed to find artifact in component {} with id {} ", id, artifactId);
+ return Either.right(artifactData.right().value());
+ }
+ ArtifactDataDefinition artifactDefinition = artifactData.left().value();
+ boolean isMandatory = false;
+ if ((artifactDefinition.getMandatory() || artifactDefinition.getServiceApi()) && !deleteMandatoryArtifact) {
+ // return Either.left(artifactData.left().value());
+ isMandatory = true;
+ }
+
+ Triple<EdgeLabelEnum, Boolean, VertexTypeEnum> triple = getEdgeLabelEnumFromArtifactGroupType(artifactDefinition.getArtifactGroupType(), type);
+ EdgeLabelEnum edgeLabelEnum = triple.getLeft();
+ VertexTypeEnum vertexTypeEnum = triple.getRight();
+
+ if (!isMandatory) {
+ StorageOperationStatus status = deleteToscaDataElement(id, edgeLabelEnum, vertexTypeEnum, artifactDefinition.getArtifactLabel(), JsonPresentationFields.ARTIFACT_LABEL);
+ if (status != StorageOperationStatus.OK)
+ return Either.right(status);
+ }
+
+ return Either.left(artifactData.left().value());
+
+ }
+
+ public void updateUUID(ArtifactDataDefinition artifactData, String oldChecksum, String oldVesrion) {
+ if (oldVesrion == null || oldVesrion.isEmpty())
+ oldVesrion = "0";
+
+ String currentChecksum = artifactData.getArtifactChecksum();
+ if (oldChecksum == null || oldChecksum.isEmpty()) {
+ if (currentChecksum != null) {
+ generateUUID(artifactData, oldVesrion);
+ }
+ } else if ((currentChecksum != null && !currentChecksum.isEmpty()) && !oldChecksum.equals(currentChecksum)) {
+ generateUUID(artifactData, oldVesrion);
+ }
+
+ }
+
+ // @TODO add implementation
+
+ public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType) {
+ return null;
+ }
+
+ public Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv, ArtifactDefinition artifactHeat, String componentId, NodeTypeEnum parentType, boolean failIfExist, String instanceId) {
+ artifactHeatEnv.setGeneratedFromId(artifactHeat.getUniqueId());
+ return addArifactToComponent(artifactHeatEnv, componentId, parentType, failIfExist, instanceId);
+ }
+
+ public Either<ArtifactDefinition, StorageOperationStatus> getHeatArtifactByHeatEnvId(String parentId, ArtifactDefinition heatEnv, NodeTypeEnum parentType, String containerId, ComponentTypeEnum componentType) {
+ String id = heatEnv.getGeneratedFromId();
+ ComponentTypeEnum compType;
+ switch (parentType) {
+ case ResourceInstance:
+ compType = ComponentTypeEnum.RESOURCE_INSTANCE;
+ break;
+ default:
+ compType = componentType;
+ }
+ return getArtifactById(parentId, id, compType, containerId);
+ }
+
+ public Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvArtifact(String id, ArtifactDefinition artifactEnvInfo, String artifactId, String newArtifactId, NodeTypeEnum type, String instanceId) {
+
+ Either<Map<String, ArtifactDefinition>, TitanOperationStatus> artifactsEither = getArtifactByLabel(id, instanceId, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS);
+ if (artifactsEither.isRight()) {
+ log.debug("Failed to find artifacts in component {} with id {} ", id, artifactsEither.right().value());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(artifactsEither.right().value()));
+ }
+
+ Map<String, ArtifactDefinition> artifacts = artifactsEither.left().value();
+ List<ArtifactDefinition> envList = artifacts.values().stream().filter(a -> a.getGeneratedFromId().equals(artifactId)).collect(Collectors.toList());
+ if (envList != null && !envList.isEmpty()) {
+ envList.forEach(a -> {
+ a.setGeneratedFromId(newArtifactId);
+ updateArifactOnResource(a, id, a.getUniqueId(), type, instanceId);
+
+ });
+
+ }
+ return Either.left(artifactEnvInfo);
+ }
+
+ public Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvPlaceholder(ArtifactDefinition artifactInfo, String parentId, NodeTypeEnum type) {
+ return updateArifactOnResource(artifactInfo, parentId, artifactInfo.getUniqueId(), type, null);
+ }
+
+ // public Either<List<HeatParameterDefinition>, StorageOperationStatus> getHeatParamsForEnv(ArtifactDefinition heatEnvArtifact, String parentId) {
+ // return null;
+ // }
+
+ ///////////////////////////////////////////// private methods ////////////////////////////////////////////////////
+
+ protected ArtifactDefinition convertArtifactDataToArtifactDefinition(ArtifactDefinition artifactInfo, ArtifactDataDefinition artifactDefResult) {
+ log.debug("The object returned after create property is {}", artifactDefResult);
+
+ ArtifactDefinition propertyDefResult = new ArtifactDefinition(artifactDefResult);
+ if (artifactInfo != null)
+ propertyDefResult.setPayload(artifactInfo.getPayloadData());
+
+ List<HeatParameterDefinition> parameters = new ArrayList<HeatParameterDefinition>();
+ /*
+ * StorageOperationStatus heatParametersOfNode = heatParametersOperation.getHeatParametersOfNode(NodeTypeEnum.ArtifactRef, artifactDefResult.getUniqueId().toString(), parameters); if ((heatParametersOfNode.equals(StorageOperationStatus.OK))
+ * && !parameters.isEmpty()) { propertyDefResult.setHeatParameters(parameters); }
+ */
+ return propertyDefResult;
+ }
+
+ private ArtifactDataDefinition getInstanceArtifactByLabelAndId(String parentId, String id, String containerId, EdgeLabelEnum edgeLabelEnum) {
+ ArtifactDataDefinition foundArtifact = null;
+ Either<Map<String, MapArtifactDataDefinition>, TitanOperationStatus> artifactsEither = getDataFromGraph(containerId, edgeLabelEnum);
+ if (artifactsEither.isRight()) {
+ log.debug("failed to fetch {} for tosca element with id {}, error {}", edgeLabelEnum, containerId, artifactsEither.right().value());
+ return null;
+ }
+
+ Map<String, MapArtifactDataDefinition> artifacts = artifactsEither.left().value();
+
+ MapArtifactDataDefinition artifactsPerInstance = artifacts.get(parentId);
+ if (artifactsPerInstance == null) {
+ log.debug("failed to fetch artifacts for instance {} in tosca element with id {}, error {}", parentId, containerId, artifactsEither.right().value());
+ return null;
+ }
+ Optional<ArtifactDataDefinition> op = artifactsPerInstance.getMapToscaDataDefinition().values().stream().filter(p -> p.getUniqueId().equals(id)).findAny();
+ if (op.isPresent()) {
+ foundArtifact = op.get();
+ }
+ return foundArtifact;
+ }
+
+ private ArtifactDataDefinition getArtifactByLabelAndId(String parentId, String id, EdgeLabelEnum edgeLabelEnum) {
+ ArtifactDataDefinition foundArtifact = null;
+ Either<Map<String, ArtifactDataDefinition>, TitanOperationStatus> artifactsEither = getDataFromGraph(parentId, edgeLabelEnum);
+ if (artifactsEither.isRight()) {
+ log.debug("failed to fetch {} for tosca element with id {}, error {}", edgeLabelEnum, parentId, artifactsEither.right().value());
+ return null;
+ }
+
+ Map<String, ArtifactDataDefinition> artifacts = artifactsEither.left().value();
+ Optional<ArtifactDataDefinition> op = artifacts.values().stream().filter(p -> p.getUniqueId().equals(id)).findAny();
+ if (op.isPresent()) {
+ foundArtifact = op.get();
+ }
+ return foundArtifact;
+ }
+
+ private Either<Map<String, ArtifactDefinition>, TitanOperationStatus> getArtifactByLabel(String parentId, String instanceId, EdgeLabelEnum edgeLabelEnum) {
+
+ Map<String, ArtifactDefinition> artMap = null;
+ Map<String, ArtifactDataDefinition> artifactDataMap = null;
+
+ if (edgeLabelEnum != EdgeLabelEnum.INSTANCE_ARTIFACTS) {
+ Either<Map<String, ArtifactDataDefinition>, TitanOperationStatus> resultEither = getDataFromGraph(parentId, edgeLabelEnum);
+ if (resultEither.isRight()) {
+ log.debug("failed to fetch {} for tosca element with id {}, error {}", edgeLabelEnum, parentId, resultEither.right().value());
+ return Either.right(resultEither.right().value());
+ }
+ artifactDataMap = resultEither.left().value();
+ }else{
+ Either<Map<String, MapArtifactDataDefinition>, TitanOperationStatus> resultEither = getDataFromGraph(parentId, edgeLabelEnum);
+ if (resultEither.isRight()) {
+ log.debug("failed to fetch {} for tosca element with id {}, error {}", edgeLabelEnum, parentId, resultEither.right().value());
+ return Either.right(resultEither.right().value());
+ }
+ Map<String, MapArtifactDataDefinition> mapArtifacts = resultEither.left().value();
+ MapArtifactDataDefinition artifactPerInstance = mapArtifacts.get(instanceId);
+ if ( artifactPerInstance != null ){
+ artifactDataMap = artifactPerInstance.getMapToscaDataDefinition();
+ }
+ }
+ if (artifactDataMap != null && !artifactDataMap.isEmpty()) {
+ artMap = artifactDataMap.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> convertArtifactDataToArtifactDefinition(null, e.getValue())));
+ }else{
+ artMap = new HashMap<>();
+ }
+ return Either.left(artMap);
+
+ }
+
+ private Triple<EdgeLabelEnum, Boolean, VertexTypeEnum> getEdgeLabelEnumFromArtifactGroupType(ArtifactGroupTypeEnum groupType, NodeTypeEnum nodeType) {
+ EdgeLabelEnum edgeLabelEnum;
+ VertexTypeEnum vertexTypeEnum;
+ Boolean isDeepElement = false;
+ /*
+ * if (nodeType == NodeTypeEnum.ResourceInstance) { edgeLabelEnum = EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS; vertexTypeEnum = VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS; isDeepElement = true; } else {
+ */
+ switch (groupType) {
+ case TOSCA:
+ edgeLabelEnum = EdgeLabelEnum.TOSCA_ARTIFACTS;
+ vertexTypeEnum = VertexTypeEnum.TOSCA_ARTIFACTS;
+ break;
+ case DEPLOYMENT:
+ if (nodeType == NodeTypeEnum.ResourceInstance) {
+ edgeLabelEnum = EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS;
+ vertexTypeEnum = VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS;
+ isDeepElement = true;
+ } else {
+ edgeLabelEnum = EdgeLabelEnum.DEPLOYMENT_ARTIFACTS;
+ vertexTypeEnum = VertexTypeEnum.DEPLOYMENT_ARTIFACTS;
+ }
+ break;
+ case SERVICE_API:
+ edgeLabelEnum = EdgeLabelEnum.SERVICE_API_ARTIFACTS;
+ vertexTypeEnum = VertexTypeEnum.SERVICE_API_ARTIFACTS;
+ break;
+ default:
+ if (nodeType == NodeTypeEnum.ResourceInstance) {
+ edgeLabelEnum = EdgeLabelEnum.INSTANCE_ARTIFACTS;
+ vertexTypeEnum = VertexTypeEnum.INSTANCE_ARTIFACTS;
+ isDeepElement = true;
+ } else {
+ edgeLabelEnum = EdgeLabelEnum.ARTIFACTS;
+ vertexTypeEnum = VertexTypeEnum.ARTIFACTS;
+ }
+ break;
+ }
+ // }
+ return new ImmutableTriple<EdgeLabelEnum, Boolean, VertexTypeEnum>(edgeLabelEnum, isDeepElement, vertexTypeEnum);
+
+ }
+
+ public Either<ArtifactDataDefinition, StorageOperationStatus> updateArtifactOnGraph(String componentId, ArtifactDefinition artifactInfo, NodeTypeEnum type, String artifactId, String instanceId) {
+ Either<ArtifactDataDefinition, StorageOperationStatus> res = null;
+ ArtifactDataDefinition artifactToUpdate = new ArtifactDataDefinition(artifactInfo);
+ ArtifactGroupTypeEnum groupType = artifactInfo.getArtifactGroupType();
+
+ Triple<EdgeLabelEnum, Boolean, VertexTypeEnum> triple = getEdgeLabelEnumFromArtifactGroupType(groupType, type);
+ EdgeLabelEnum edgeLabelEnum = triple.getLeft();
+ VertexTypeEnum vertexTypeEnum = triple.getRight();
+
+ Either<Boolean, StorageOperationStatus> isNeedToCloneEither = isCloneNeeded(componentId, edgeLabelEnum);
+ if (isNeedToCloneEither.isRight()) {
+ log.debug("Failed check is clone needed {}", componentId);
+ return Either.right(isNeedToCloneEither.right().value());
+
+ }
+ boolean isNeedToClone = isNeedToCloneEither.left().value();
+
+ if (artifactId == null || isNeedToClone) {
+ String uniqueId;
+ if (edgeLabelEnum != EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS && edgeLabelEnum != EdgeLabelEnum.INSTANCE_ARTIFACTS) {
+ uniqueId = UniqueIdBuilder.buildPropertyUniqueId(componentId, artifactToUpdate.getArtifactLabel());
+ } else {
+ uniqueId = UniqueIdBuilder.buildPropertyUniqueId(instanceId, artifactToUpdate.getArtifactLabel());
+ }
+ artifactToUpdate.setUniqueId(uniqueId);
+
+ } else
+ artifactToUpdate.setUniqueId(artifactId);
+
+ Map<String, ArtifactDataDefinition> artifacts = null;
+ if (edgeLabelEnum != EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS && edgeLabelEnum != EdgeLabelEnum.INSTANCE_ARTIFACTS) {
+
+ Either<Map<String, ArtifactDataDefinition>, TitanOperationStatus> artifactsEither = this.getDataFromGraph(componentId, edgeLabelEnum);
+
+ if (artifactsEither.isLeft() && artifactsEither.left().value() != null && !artifactsEither.left().value().isEmpty()) {
+ artifacts = artifactsEither.left().value();
+ if (isNeedToClone) {
+ artifacts.values().stream().forEach(a -> a.setDuplicated(Boolean.TRUE));
+ }
+ }
+ } else {
+ Either<Map<String, MapArtifactDataDefinition>, TitanOperationStatus> artifactsEither = this.getDataFromGraph(componentId, edgeLabelEnum);
+ if (artifactsEither.isLeft()) {
+ Map<String, MapArtifactDataDefinition> artifactInst = artifactsEither.left().value();
+ if (isNeedToClone) {
+ artifactInst.values().forEach(ma -> ma.getMapToscaDataDefinition().values().forEach(a -> a.setDuplicated(Boolean.TRUE)));
+ }
+ MapArtifactDataDefinition artifatcsOnInstance = artifactInst.get(instanceId);
+ if (artifatcsOnInstance != null) {
+ artifacts = artifatcsOnInstance.getMapToscaDataDefinition();
+ }
+ }
+ }
+ String oldChecksum = null;
+ String oldVersion = null;
+ if (artifacts != null && artifacts.containsKey(artifactInfo.getArtifactLabel())) {
+ ArtifactDataDefinition oldArtifactData = artifacts.get(artifactInfo.getArtifactLabel());
+ oldChecksum = oldArtifactData.getArtifactChecksum();
+ oldVersion = oldArtifactData.getArtifactVersion();
+ if (isNeedToClone)
+ artifactToUpdate.setDuplicated(Boolean.FALSE);
+ else {
+ if (artifactToUpdate.getDuplicated()) {
+ String id = type != NodeTypeEnum.ResourceInstance ? componentId : instanceId;
+ String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(id, artifactToUpdate.getArtifactLabel());
+ artifactToUpdate.setUniqueId(uniqueId);
+ artifactToUpdate.setDuplicated(Boolean.TRUE);
+ }
+ }
+ }
+ updateUUID(artifactToUpdate, oldChecksum, oldVersion);
+
+ if (artifactInfo.getPayloadData() == null) {
+ if (!artifactToUpdate.getMandatory() || artifactToUpdate.getEsId() != null) {
+ artifactToUpdate.setEsId(artifactToUpdate.getUniqueId());
+ }
+ } else {
+ if (artifactToUpdate.getEsId() == null) {
+ artifactToUpdate.setEsId(artifactToUpdate.getUniqueId());
+
+ }
+ }
+
+ StorageOperationStatus status;
+ if (edgeLabelEnum != EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS && edgeLabelEnum != EdgeLabelEnum.INSTANCE_ARTIFACTS) {
+ status = updateToscaDataOfToscaElement(componentId, edgeLabelEnum, vertexTypeEnum, artifactToUpdate, JsonPresentationFields.ARTIFACT_LABEL);
+ } else {
+ List<String> pathKeys = new ArrayList<>();
+ pathKeys.add(instanceId);
+ List<ArtifactDataDefinition> toscaDataList = new ArrayList<>();
+ toscaDataList.add(artifactToUpdate);
+ status = updateToscaDataDeepElementsOfToscaElement(componentId, edgeLabelEnum, vertexTypeEnum, toscaDataList, pathKeys, JsonPresentationFields.ARTIFACT_LABEL);
+ }
+ if (status == StorageOperationStatus.OK)
+ res = Either.left(artifactToUpdate);
+ else
+ res = Either.right(status);
+ return res;
+ }
+
+ public void generateUUID(ArtifactDataDefinition artifactData, String oldVesrion) {
+
+ UUID uuid = UUID.randomUUID();
+ artifactData.setArtifactUUID(uuid.toString());
+ MDC.put("serviceInstanceID", uuid.toString());
+ updateVersionAndDate(artifactData, oldVesrion);
+ }
+
+ private void updateVersionAndDate(ArtifactDataDefinition artifactData, String oldVesrion) {
+ if (artifactData.getArtifactChecksum() != null) {
+ long time = System.currentTimeMillis();
+ artifactData.setPayloadUpdateDate(time);
+ }
+ int newVersion = new Integer(oldVesrion).intValue();
+ newVersion++;
+ artifactData.setArtifactVersion(String.valueOf(newVersion));
+ }
+
+ 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);
+ }
+ return isValid;
+ }
+
+ public Either<ArtifactDataDefinition, StorageOperationStatus> removeArtifactOnGraph(ArtifactDefinition artifactFromGraph, String componentId, String instanceId, NodeTypeEnum type, boolean deleteMandatoryArtifact) {
+
+ Triple<EdgeLabelEnum, Boolean, VertexTypeEnum> triple = getEdgeLabelEnumFromArtifactGroupType(artifactFromGraph.getArtifactGroupType(), type);
+ EdgeLabelEnum edgeLabelEnum = triple.getLeft();
+ VertexTypeEnum vertexTypeEnum = triple.getRight();
+
+ if (deleteMandatoryArtifact || !(artifactFromGraph.getMandatory() || artifactFromGraph.getServiceApi())) {
+ StorageOperationStatus status;
+ if (triple.getMiddle()) {
+ List<String> pathKeys = new ArrayList<>();
+ pathKeys.add(instanceId);
+ status = deleteToscaDataDeepElement(componentId, edgeLabelEnum, vertexTypeEnum, artifactFromGraph.getArtifactLabel(), pathKeys, JsonPresentationFields.ARTIFACT_LABEL);
+ } else {
+ status = deleteToscaDataElement(componentId, edgeLabelEnum, vertexTypeEnum, artifactFromGraph.getArtifactLabel(), JsonPresentationFields.ARTIFACT_LABEL);
+ }
+ if (status != StorageOperationStatus.OK)
+ return Either.right(status);
+ }
+ return Either.left(artifactFromGraph);
+
+ }
+
+ public Either<ArtifactDataDefinition, StorageOperationStatus> deleteArtifactWithClonnigOnGraph(String componentId, ArtifactDefinition artifactToDelete, NodeTypeEnum type, String instanceId, boolean deleteMandatoryArtifact) {
+
+ Either<ArtifactDataDefinition, StorageOperationStatus> result = null;
+ Triple<EdgeLabelEnum, Boolean, VertexTypeEnum> triple = getEdgeLabelEnumFromArtifactGroupType(artifactToDelete.getArtifactGroupType(), type);
+ EdgeLabelEnum edgeLabel = triple.getLeft();
+ VertexTypeEnum vertexLabel = triple.getRight();
+
+ Boolean deleteElement = deleteMandatoryArtifact || !(artifactToDelete.getMandatory() || artifactToDelete.getServiceApi());
+ Map<String, ToscaDataDefinition> artifacts = null;
+ GraphVertex parentVertex = null;
+ Either<Map<String, ToscaDataDefinition>, TitanOperationStatus> getArtifactsRes = null;
+
+ Either<GraphVertex, TitanOperationStatus> getToscaElementRes = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
+ if (getToscaElementRes.isRight()) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get tosca element {} upon getting tosca data from graph. Status is {}. ", componentId, getToscaElementRes.right().value());
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getToscaElementRes.right().value()));
+ }
+ if (result == null) {
+ parentVertex = getToscaElementRes.left().value();
+ getArtifactsRes = this.getDataFromGraph(parentVertex, edgeLabel);
+ if (getArtifactsRes.isRight()) {
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getArtifactsRes.right().value()));
+ }
+ }
+ if (result == null) {
+ artifacts = getArtifactsRes.left().value();
+ if (triple.getMiddle()) {
+ artifacts.values().forEach(ma -> ((MapArtifactDataDefinition) ma).getMapToscaDataDefinition().values().forEach(a -> a.setDuplicated(Boolean.TRUE)));
+ MapArtifactDataDefinition artifatcsOnInstance = (MapArtifactDataDefinition) artifacts.get(instanceId);
+ if (artifatcsOnInstance != null && deleteElement) {
+ artifatcsOnInstance.getMapToscaDataDefinition().remove(artifactToDelete.getArtifactLabel());
+ }
+ } else {
+ if (deleteElement) {
+ artifacts.remove(artifactToDelete.getArtifactLabel());
+ }
+ artifacts.values().stream().forEach(a -> ((ArtifactDataDefinition) a).setDuplicated(Boolean.TRUE));
+ }
+ artifactToDelete.setDuplicated(Boolean.TRUE);
+ }
+ if (artifacts != null) {
+ TitanOperationStatus status = titanDao.deleteEdgeByDirection(parentVertex, Direction.OUT, edgeLabel);
+ if (status != TitanOperationStatus.OK) {
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ } else if (MapUtils.isNotEmpty(artifacts)) {
+ Either<GraphVertex, StorageOperationStatus> assosiateRes = assosiateElementToData(parentVertex, vertexLabel, edgeLabel, artifacts);
+ if (assosiateRes.isRight()) {
+ result = Either.right(result.right().value());
+ }
+ }
+ }
+ if (result == null) {
+ result = Either.left(artifactToDelete);
+ }
+ return result;
+ }
+}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/BaseOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/BaseOperation.java
new file mode 100644
index 0000000000..629d9ecdd4
--- /dev/null
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/BaseOperation.java
@@ -0,0 +1,1316 @@
+package org.openecomp.sdc.be.model.jsontitan.operations;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+import org.apache.commons.collections.CollectionUtils;
+import org.apache.commons.collections.MapUtils;
+import org.apache.commons.lang.StringUtils;
+import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.apache.commons.lang3.tuple.Pair;
+import org.apache.tinkerpop.gremlin.structure.Direction;
+import org.apache.tinkerpop.gremlin.structure.Edge;
+import org.apache.tinkerpop.gremlin.structure.Vertex;
+import org.apache.tinkerpop.gremlin.structure.VertexProperty;
+import org.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.elements.MapDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
+import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
+import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
+import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
+import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+
+import com.thinkaurelius.titan.core.TitanVertex;
+
+import fj.data.Either;
+
+/**
+ * public abstract class BaseOperation provides base operation functionality and common fields
+ *
+ */
+public abstract class BaseOperation {
+
+ private static Logger logger = LoggerFactory.getLogger(BaseOperation.class.getName());
+
+ public static final String VF_MODULE = "org.openecomp.groups.VfModule";
+
+ @Autowired
+ protected TitanDao titanDao;
+
+ @Autowired
+ protected NodeTypeOperation nodeTypeOperation;
+
+ @Autowired
+ protected TopologyTemplateOperation topologyTemplateOperation;
+
+ /**
+ * Returns reference to appropriate toscaTemplateOperation
+ *
+ * @param componentType
+ * @return
+ */
+ public ToscaElementOperation getToscaElementOperation(ComponentTypeEnum componentType) {
+ ToscaElementOperation operation;
+ switch (componentType) {
+ case SERVICE:
+ case RESOURCE:
+ operation = topologyTemplateOperation;
+ break;
+ default:
+ operation = nodeTypeOperation;
+ break;
+ }
+ return operation;
+ }
+
+ /**
+ * Returns reference to appropriate toscaTemplateOperation
+ *
+ * @param toscaElementType
+ * @return
+ */
+ public ToscaElementOperation getToscaElementOperation(ToscaElementTypeEnum toscaElementType) {
+ ToscaElementOperation operation;
+ switch (toscaElementType) {
+ case TopologyTemplate:
+ operation = topologyTemplateOperation;
+ break;
+ case NodeType:
+ operation = nodeTypeOperation;
+ break;
+ default:
+ operation = null;
+ break;
+ }
+ return operation;
+ }
+
+ /**
+ * Returns reference to appropriate toscaTemplateOperation
+ *
+ * @param toscaElementType
+ * @return
+ */
+ public ToscaElementOperation getToscaElementOperation(VertexTypeEnum toscaElementType) {
+ ToscaElementOperation operation;
+ switch (toscaElementType) {
+ case TOPOLOGY_TEMPLATE:
+ operation = topologyTemplateOperation;
+ break;
+ case NODE_TYPE:
+ operation = nodeTypeOperation;
+ break;
+ default:
+ operation = null;
+ break;
+ }
+ return operation;
+ }
+ /**
+ * Converts received vertex to User object
+ *
+ * @param ownerV
+ * @return
+ */
+ public User convertToUser(Vertex ownerV) {
+ User owner = new User();
+ owner.setUserId((String) ownerV.property(GraphPropertyEnum.USERID.getProperty()).value());
+ VertexProperty<Object> property = ownerV.property(GraphPropertyEnum.ROLE.getProperty());
+ if(property != null && property.isPresent() ){
+ owner.setRole((String) property.value());
+ }
+
+ property = ownerV.property(GraphPropertyEnum.FIRST_NAME.getProperty());
+ if(property != null && property.isPresent() ){
+ owner.setFirstName((String) ownerV.property(GraphPropertyEnum.FIRST_NAME.getProperty()).value());
+ }
+
+ property = ownerV.property(GraphPropertyEnum.LAST_NAME.getProperty());
+ if( property != null && property.isPresent() ){
+ owner.setLastName((String) ownerV.property(GraphPropertyEnum.LAST_NAME.getProperty()).value());
+ }
+
+ property = ownerV.property(GraphPropertyEnum.EMAIL.getProperty());
+ if( property != null && property.isPresent() ){
+ owner.setEmail((String) ownerV.property(GraphPropertyEnum.EMAIL.getProperty()).value());
+ }
+
+ property = ownerV.property(GraphPropertyEnum.LAST_LOGIN_TIME.getProperty());
+ if( property != null && property.isPresent() ){
+ owner.setLastLoginTime((Long) ownerV.property(GraphPropertyEnum.LAST_LOGIN_TIME.getProperty()).value());
+ }
+ return owner;
+ }
+
+ protected <T extends ToscaDataDefinition> Either<Map<String, T>, TitanOperationStatus> getDataFromGraph(GraphVertex componentV, EdgeLabelEnum edgelabel) {
+ Either<Pair<GraphVertex, Map<String, T>>, TitanOperationStatus> dataVertex = getDataAndVertexFromGraph(componentV, edgelabel);
+ if (dataVertex.isRight()) {
+ return Either.right(dataVertex.right().value());
+ }
+ Map<String, T> properties = dataVertex.left().value().getRight();
+ return Either.left(properties);
+ }
+
+ @SuppressWarnings("unchecked")
+ protected <T extends ToscaDataDefinition> Either<Pair<GraphVertex, Map<String, T>>, TitanOperationStatus> getDataAndVertexFromGraph(GraphVertex componentV, EdgeLabelEnum edgelabel) {
+ Either<GraphVertex, TitanOperationStatus> dataVertex = getDataVertex(componentV, edgelabel);
+ if (dataVertex.isRight()) {
+ return Either.right(dataVertex.right().value());
+ }
+ GraphVertex propV = dataVertex.left().value();
+ Map<String, T> properties = (Map<String, T>) propV.getJson();
+ Pair<GraphVertex, Map<String, T>> pair = new ImmutablePair<GraphVertex, Map<String, T>>(propV, properties);
+ return Either.left(pair);
+ }
+
+ protected <T extends ToscaDataDefinition> Either<GraphVertex, TitanOperationStatus> getDataVertex(GraphVertex componentV, EdgeLabelEnum edgelabel) {
+ Either<GraphVertex, TitanOperationStatus> childVertex = titanDao.getChildVertex(componentV, edgelabel, JsonParseFlagEnum.ParseJson);
+ if (childVertex.isRight()) {
+ if (childVertex.right().value() != TitanOperationStatus.NOT_FOUND) {
+ logger.debug("failed to fetch {} for tosca element with id {}, error {}", edgelabel, componentV.getUniqueId(), childVertex.right().value());
+ }
+ return Either.right(childVertex.right().value());
+ }
+ GraphVertex propV = childVertex.left().value();
+ return Either.left(propV);
+ }
+
+ /**
+ * Returns tosca data belonging to tosca element specified by uid according received label
+ *
+ * @param toscaElementUid
+ * @param edgelabel
+ * @return
+ */
+ public <T extends ToscaDataDefinition> Either<Map<String, T>, TitanOperationStatus> getDataFromGraph(String toscaElementUid, EdgeLabelEnum edgelabel) {
+
+ Either<Map<String, T>, TitanOperationStatus> result = null;
+ Either<GraphVertex, TitanOperationStatus> getToscaElementRes;
+
+ getToscaElementRes = titanDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse);
+ if (getToscaElementRes.isRight()) {
+ TitanOperationStatus status = getToscaElementRes.right().value();
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to get tosca element {} upon getting tosca data from graph. Status is {}. ", toscaElementUid, status);
+ result = Either.right(status);
+ }
+ if (result == null) {
+ result = getDataFromGraph(getToscaElementRes.left().value(), edgelabel);
+ }
+ return result;
+ }
+
+ public Either<GraphVertex, TitanOperationStatus> findUserVertex(String userId) {
+ return titanDao.getVertexByPropertyAndLabel(GraphPropertyEnum.USERID, userId, VertexTypeEnum.USER, JsonParseFlagEnum.NoParse);
+ }
+
+ /**
+ *
+ * @param elemementId
+ * @param label
+ * @return
+ */
+ public Either<Boolean, StorageOperationStatus> isCloneNeeded(String elemementId, EdgeLabelEnum label) {
+ Either<GraphVertex, TitanOperationStatus> vertexById = titanDao.getVertexById(elemementId);
+ if (vertexById.isRight()) {
+ logger.debug("Failed to fetch element by id {} error {}", elemementId, vertexById.right().value());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexById.right().value()));
+ }
+ GraphVertex toscaElementVertex = vertexById.left().value();
+ Either<GraphVertex, TitanOperationStatus> childVertex = titanDao.getChildVertex(toscaElementVertex, label, JsonParseFlagEnum.NoParse);
+ if (childVertex.isRight()) {
+ if (childVertex.right().value() != TitanOperationStatus.NOT_FOUND) {
+ logger.debug("failed to fetch {} for tosca element with id {}, error {}", label, toscaElementVertex.getUniqueId(), childVertex.right().value());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(childVertex.right().value()));
+ }
+ return Either.left(Boolean.FALSE);
+ }
+ GraphVertex dataVertex = childVertex.left().value();
+ Iterator<Edge> edges = dataVertex.getVertex().edges(Direction.IN, label.name());
+ int edgeCount = 0;
+ while (edges.hasNext()) {
+ edges.next();
+ ++edgeCount;
+ }
+ if (edgeCount > 1) {
+ return Either.left(Boolean.TRUE);
+ } else {
+ return Either.left(Boolean.FALSE);
+ }
+ }
+
+ protected Either<GraphVertex, TitanOperationStatus> updateOrCopyOnUpdate(GraphVertex dataVertex, GraphVertex toscaElementVertex, EdgeLabelEnum label) {
+ Iterator<Edge> edges = dataVertex.getVertex().edges(Direction.IN, label.name());
+ int edgeCount = 0;
+ Edge edgeToRemove = null;
+ while (edges.hasNext()) {
+ Edge edge = edges.next();
+ ++edgeCount;
+ Vertex outVertex = edge.outVertex();
+ String outId = (String) titanDao.getProperty((TitanVertex) outVertex, GraphPropertyEnum.UNIQUE_ID.getProperty());
+ if (toscaElementVertex.getUniqueId().equals(outId)) {
+ edgeToRemove = edge;
+ }
+ }
+ if (edgeToRemove == null) {
+ logger.debug("No edges {} from vertex {} to vertex {}", label, toscaElementVertex.getUniqueId(), dataVertex.getUniqueId());
+ return Either.right(TitanOperationStatus.GENERAL_ERROR);
+ }
+ switch (edgeCount) {
+ case 0:
+ // error
+ logger.debug("No edges {} to vertex {}", label, dataVertex.getUniqueId());
+ return Either.right(TitanOperationStatus.GENERAL_ERROR);
+ case 1:
+ // update
+ logger.trace("Only one edge {} to vertex {}. Update vertex", label, dataVertex.getUniqueId());
+ return titanDao.updateVertex(dataVertex);
+ default:
+ // copy on update
+ logger.trace("More than one edge {} to vertex {}. Need to clone vertex", label, dataVertex.getUniqueId());
+ return cloneDataVertex(dataVertex, toscaElementVertex, label, edgeToRemove);
+ }
+ }
+
+ private Either<GraphVertex, TitanOperationStatus> cloneDataVertex(GraphVertex dataVertex, GraphVertex toscaElementVertex, EdgeLabelEnum label, Edge edgeToRemove) {
+ GraphVertex newDataVertex = new GraphVertex(dataVertex.getLabel());
+ String id = IdBuilderUtils.generateChildId(toscaElementVertex.getUniqueId(), dataVertex.getLabel());
+ newDataVertex.setUniqueId(id);
+ newDataVertex.cloneData(dataVertex);
+
+ Either<GraphVertex, TitanOperationStatus> createVertex = titanDao.createVertex(newDataVertex);
+ if (createVertex.isRight()) {
+ logger.debug("Failed to clone data vertex for {} error {}", dataVertex.getUniqueId(), createVertex.right().value());
+ return createVertex;
+ }
+ newDataVertex = createVertex.left().value();
+ TitanOperationStatus createEdge = titanDao.createEdge(toscaElementVertex, newDataVertex, label, titanDao.getEdgeProperties(edgeToRemove));
+ if (createEdge != TitanOperationStatus.OK) {
+ logger.debug("Failed to associate vertex {} to vertex {}, error {}", toscaElementVertex.getUniqueId(), newDataVertex.getUniqueId(), createEdge);
+ return Either.right(createEdge);
+ }
+ edgeToRemove.remove();
+ return Either.left(newDataVertex);
+ }
+
+ public Either<GraphVertex, StorageOperationStatus> assosiateElementToData(GraphVertex element, VertexTypeEnum vertexLabel, EdgeLabelEnum edgeLabel, Map<String, ? extends ToscaDataDefinition> data) {
+ GraphVertex dataV = new GraphVertex(vertexLabel);
+ String id = IdBuilderUtils.generateChildId(element.getUniqueId(), vertexLabel);
+ dataV.setUniqueId(id);
+ dataV.setJson(data);
+ Either<GraphVertex, TitanOperationStatus> createVertex = titanDao.createVertex(dataV);
+ if (createVertex.isRight()) {
+ logger.trace("Failed to create {} vertex for type node {}", vertexLabel, element.getUniqueId());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(createVertex.right().value()));
+ }
+ dataV = createVertex.left().value();
+ TitanOperationStatus createEdgeStatus = titanDao.createEdge(element.getVertex(), dataV.getVertex(), edgeLabel, new HashMap<>());
+ if (createEdgeStatus != TitanOperationStatus.OK) {
+ logger.trace("Failed to create {} vertex for type node {}", vertexLabel, element.getUniqueId());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(createEdgeStatus));
+ }
+ return Either.left(dataV);
+ }
+
+ /**
+ * Adds tosca data element to tosca element according received labels
+ *
+ * @param toscaElement
+ * @param edgeLabel
+ * @param vertexLabel
+ * @param toscaData
+ * @param mapKeyField
+ * @return
+ */
+ public <T extends ToscaDataDefinition> StorageOperationStatus addToscaDataToToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, T toscaData, JsonPresentationFields mapKeyField) {
+
+ List<T> toscaDataList = new ArrayList<>();
+ toscaDataList.add(toscaData);
+ return addToscaDataToToscaElement(toscaElement, edgeLabel, vertexLabel, toscaDataList, mapKeyField);
+ }
+
+ /**
+ * Adds tosca data deep element to tosca element according received labels
+ *
+ * @param toscaElement
+ * @param edgeLabel
+ * @param vertexLabel
+ * @param toscaData
+ * @param pathKeys
+ * @param mapKeyField
+ * @return
+ */
+ public <T extends ToscaDataDefinition> StorageOperationStatus addToscaDataDeepElementToToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, T toscaData, List<String> pathKeys,
+ JsonPresentationFields mapKeyField) {
+
+ List<T> toscaDataList = new ArrayList<>();
+ toscaDataList.add(toscaData);
+ return addToscaDataDeepElementsToToscaElement(toscaElement, edgeLabel, vertexLabel, toscaDataList, pathKeys, mapKeyField);
+ }
+
+ /**
+ * Converts recieved map of tosca data deep elements to list and adds it to tosca element according received labels
+ *
+ * @param toscaElement
+ * @param edgeLabel
+ * @param vertexLabel
+ * @param toscaDataMap
+ * @param pathKeys
+ * @param mapKeyField
+ * @return
+ */
+ public <T extends ToscaDataDefinition> StorageOperationStatus addToscaDataDeepElementsToToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, Map<String, T> toscaDataMap, List<String> pathKeys,
+ JsonPresentationFields mapKeyField) {
+
+ if (toscaDataMap != null) {
+ return addToscaDataDeepElementsToToscaElement(toscaElement, edgeLabel, vertexLabel, toscaDataMap.values().stream().collect(Collectors.toList()), pathKeys, mapKeyField);
+ }
+ return StorageOperationStatus.OK;
+ }
+
+ /**
+ * Adds list of tosca data deep elements to tosca element according received labels
+ *
+ * @param toscaElement
+ * @param edgeLabel
+ * @param vertexLabel
+ * @param toscaDataList
+ * @param pathKeys
+ * @param mapKeyField
+ * @return
+ */
+ public <T extends ToscaDataDefinition> StorageOperationStatus addToscaDataDeepElementsToToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List<T> toscaDataList, List<String> pathKeys,
+ JsonPresentationFields mapKeyField) {
+
+ return updateOrAddToscaDataDeepElement(toscaElement, edgeLabel, vertexLabel, toscaDataList, pathKeys, mapKeyField, false);
+ }
+
+ /**
+ * Updates list of tosca data elements of tosca element according received labels
+ *
+ * @param toscaElement
+ * @param edgeLabel
+ * @param vertexLabel
+ * @param toscaData
+ * @param mapKeyField
+ * @return
+ */
+ public <T extends ToscaDataDefinition> StorageOperationStatus updateToscaDataOfToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, T toscaData, JsonPresentationFields mapKeyField) {
+ List<T> toscaDataList = new ArrayList<>();
+ toscaDataList.add(toscaData);
+ return updateToscaDataOfToscaElement(toscaElement, edgeLabel, vertexLabel, toscaDataList, mapKeyField);
+ }
+
+ /**
+ * Updates tosca data deep element of tosca element according received labels
+ *
+ * @param toscaElement
+ * @param edgeLabel
+ * @param vertexLabel
+ * @param toscaData
+ * @param pathKeys
+ * @param mapKeyField
+ * @return
+ */
+ public <T extends ToscaDataDefinition> StorageOperationStatus updateToscaDataDeepElementOfToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, T toscaData, List<String> pathKeys,
+ JsonPresentationFields mapKeyField) {
+ List<T> toscaDataList = new ArrayList<>();
+ toscaDataList.add(toscaData);
+ return updateToscaDataDeepElementsOfToscaElement(toscaElement, edgeLabel, vertexLabel, toscaDataList, pathKeys, mapKeyField);
+ }
+
+ /**
+ * Updates tosca data deep elements of tosca element according received labels
+ *
+ * @param toscaElement
+ * @param edgeLabel
+ * @param vertexLabel
+ * @param toscaDataList
+ * @param pathKeys
+ * @param mapKeyField
+ * @return
+ */
+ public <T extends ToscaDataDefinition> StorageOperationStatus updateToscaDataDeepElementsOfToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List<T> toscaDataList, List<String> pathKeys,
+ JsonPresentationFields mapKeyField) {
+
+ return updateOrAddToscaDataDeepElement(toscaElement, edgeLabel, vertexLabel, toscaDataList, pathKeys, mapKeyField, true);
+ }
+
+ /**
+ * Adds tosca data element to tosca element with specified uid according received labels
+ *
+ * @param toscaElementUid
+ * @param toscaData
+ * @param edgeLabel
+ * @param vertexLabel
+ * @param mapKeyField
+ * @return
+ */
+ public <T extends ToscaDataDefinition> StorageOperationStatus addToscaDataToToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, T toscaData, JsonPresentationFields mapKeyField) {
+
+ List<T> toscaDataList = new ArrayList<>();
+ toscaDataList.add(toscaData);
+ return addToscaDataToToscaElement(toscaElementUid, edgeLabel, vertexLabel, toscaDataList, mapKeyField);
+ }
+
+ /**
+ * Adds tosca data deep element to tosca element with specified uid according received labels
+ *
+ * @param toscaElementUid
+ * @param edgeLabel
+ * @param vertexLabel
+ * @param toscaData
+ * @param pathKeys
+ * @param mapKeyField
+ * @return
+ */
+ public <T extends ToscaDataDefinition> StorageOperationStatus addToscaDataDeepElementToToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, T toscaData, List<String> pathKeys,
+ JsonPresentationFields mapKeyField) {
+
+ List<T> toscaDataList = new ArrayList<>();
+ toscaDataList.add(toscaData);
+ return addToscaDataDeepElementsToToscaElement(toscaElementUid, edgeLabel, vertexLabel, toscaDataList, pathKeys, mapKeyField);
+ }
+
+ public <T extends ToscaDataDefinition> StorageOperationStatus updateToscaDataDeepElementOfToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, T toscaData, List<String> pathKeys,
+ JsonPresentationFields mapKeyField) {
+
+ List<T> toscaDataList = new ArrayList<>();
+ toscaDataList.add(toscaData);
+ return updateToscaDataDeepElementsOfToscaElement(toscaElementUid, edgeLabel, vertexLabel, toscaDataList, pathKeys, mapKeyField);
+ }
+
+ public <T extends ToscaDataDefinition> StorageOperationStatus updateToscaDataDeepElementsOfToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List<T> toscaDataList, List<String> pathKeys,
+ JsonPresentationFields mapKeyField) {
+
+ StorageOperationStatus statusRes = null;
+ Either<GraphVertex, TitanOperationStatus> getToscaElementRes;
+
+ getToscaElementRes = titanDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse);
+ if (getToscaElementRes.isRight()) {
+ TitanOperationStatus status = getToscaElementRes.right().value();
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to get tosca element {} upon adding the properties. Status is {}. ", toscaElementUid, status);
+ statusRes = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
+ }
+ if (statusRes == null && CollectionUtils.isNotEmpty(toscaDataList)) {
+ statusRes = updateToscaDataDeepElementsOfToscaElement(getToscaElementRes.left().value(), edgeLabel, vertexLabel, toscaDataList, pathKeys, mapKeyField);
+ }
+ if (statusRes == null) {
+ statusRes = StorageOperationStatus.OK;
+ }
+ return statusRes;
+ }
+
+ /**
+ * Adds list of tosca data deep elements to tosca element with specified uid according received labels
+ *
+ * @param toscaElementUid
+ * @param edgeLabel
+ * @param vertexLabel
+ * @param toscaDataList
+ * @param pathKeys
+ * @param mapKeyField
+ * @return
+ */
+ public <T extends ToscaDataDefinition> StorageOperationStatus addToscaDataDeepElementsToToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List<T> toscaDataList, List<String> pathKeys,
+ JsonPresentationFields mapKeyField) {
+
+ StorageOperationStatus statusRes = null;
+ Either<GraphVertex, TitanOperationStatus> getToscaElementRes;
+
+ getToscaElementRes = titanDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse);
+ if (getToscaElementRes.isRight()) {
+ TitanOperationStatus status = getToscaElementRes.right().value();
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to get tosca element {} upon adding the properties. Status is {}. ", toscaElementUid, status);
+ statusRes = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
+ }
+ if (statusRes == null && CollectionUtils.isNotEmpty(toscaDataList)) {
+ statusRes = addToscaDataDeepElementsToToscaElement(getToscaElementRes.left().value(), edgeLabel, vertexLabel, toscaDataList, pathKeys, mapKeyField);
+ }
+ if (statusRes == null) {
+ statusRes = StorageOperationStatus.OK;
+ }
+ return statusRes;
+ }
+
+ public <T extends ToscaDataDefinition> StorageOperationStatus deleteToscaDataDeepElementsBlockToToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, String key) {
+
+ StorageOperationStatus statusRes = null;
+ Either<GraphVertex, TitanOperationStatus> getToscaElementRes;
+
+ getToscaElementRes = titanDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse);
+ if (getToscaElementRes.isRight()) {
+ TitanOperationStatus status = getToscaElementRes.right().value();
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to get tosca element {} upon adding the properties. Status is {}. ", toscaElementUid, status);
+ statusRes = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
+ }
+ if (statusRes == null) {
+ statusRes = deleteToscaDataDeepElementsBlockToToscaElement(getToscaElementRes.left().value(), edgeLabel, vertexLabel, key);
+ }
+ if (statusRes == null) {
+ statusRes = StorageOperationStatus.OK;
+ }
+ return statusRes;
+ }
+
+ public <T extends ToscaDataDefinition> StorageOperationStatus deleteToscaDataDeepElementsBlockToToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, String key) {
+
+ StorageOperationStatus result = null;
+ GraphVertex toscaDataVertex = null;
+ Either<GraphVertex, TitanOperationStatus> toscaDataVertexRes = titanDao.getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson);
+ if (toscaDataVertexRes.isRight()) {
+ TitanOperationStatus status = toscaDataVertexRes.right().value();
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to get child vertex of the tosca element {} by label {}. Status is {}. ", toscaElement.getUniqueId(), edgeLabel, status);
+ result = DaoStatusConverter.convertTitanStatusToStorageStatus(toscaDataVertexRes.right().value());
+ }
+ if (result == null) {
+ toscaDataVertex = toscaDataVertexRes.left().value();
+ result = deleteDeepElementsBlock(toscaDataVertex, key);
+ }
+ if (result == null) {
+ Either<GraphVertex, TitanOperationStatus> updateOrCopyRes = updateOrCopyOnUpdate(toscaDataVertex, toscaElement, edgeLabel);
+ if (updateOrCopyRes.isRight()) {
+ TitanOperationStatus status = updateOrCopyRes.right().value();
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete tosca data block {} from the tosca element {}. Status is {}. ", edgeLabel, toscaElement.getUniqueId(), status);
+ result = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
+ }
+ }
+ if (result == null) {
+ result = StorageOperationStatus.OK;
+ }
+ return result;
+ }
+
+ @SuppressWarnings("rawtypes")
+ public <T extends ToscaDataDefinition> StorageOperationStatus addToscaDataDeepElementsBlockToToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, MapDataDefinition toscaDataMap, String key) {
+
+ StorageOperationStatus statusRes = null;
+ Either<GraphVertex, TitanOperationStatus> getToscaElementRes;
+
+ getToscaElementRes = titanDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse);
+ if (getToscaElementRes.isRight()) {
+ TitanOperationStatus status = getToscaElementRes.right().value();
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to get tosca element {} upon adding the properties. Status is {}. ", toscaElementUid, status);
+ statusRes = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
+ }
+ if (statusRes == null && toscaDataMap != null) {
+ statusRes = addToscaDataDeepElementsBlockToToscaElement(getToscaElementRes.left().value(), edgeLabel, vertexLabel, toscaDataMap, key);
+ }
+ if (statusRes == null) {
+ statusRes = StorageOperationStatus.OK;
+ }
+ return statusRes;
+ }
+
+ @SuppressWarnings("rawtypes")
+ public <T extends ToscaDataDefinition> StorageOperationStatus addToscaDataDeepElementsBlockToToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, MapDataDefinition toscaDataMap, String key) {
+
+ StorageOperationStatus result = null;
+ GraphVertex toscaDataVertex = null;
+ Either<GraphVertex, TitanOperationStatus> toscaDataVertexRes = titanDao.getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson);
+ if (toscaDataVertexRes.isRight() && toscaDataVertexRes.right().value() != TitanOperationStatus.NOT_FOUND) {
+ TitanOperationStatus status = toscaDataVertexRes.right().value();
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to get child vertex of the tosca element {} by label {}. Status is {}. ", toscaElement.getUniqueId(), edgeLabel, status);
+ result = DaoStatusConverter.convertTitanStatusToStorageStatus(toscaDataVertexRes.right().value());
+ }
+ if (result == null) {
+ if (toscaDataVertexRes.isLeft()) {
+ toscaDataVertex = toscaDataVertexRes.left().value();
+ result = addDeepElementsBlock(toscaDataVertex, toscaDataMap, key);
+ }
+ }
+ if (result == null) {
+ if (toscaDataVertex != null) {
+ Either<GraphVertex, TitanOperationStatus> updateOrCopyRes = updateOrCopyOnUpdate(toscaDataVertex, toscaElement, edgeLabel);
+ if (updateOrCopyRes.isRight()) {
+ TitanOperationStatus status = updateOrCopyRes.right().value();
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to add tosca data {} to the tosca element {}. Status is {}. ", edgeLabel, toscaElement.getUniqueId(), status);
+ result = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
+ }
+ } else {
+ Map<String, MapDataDefinition> data = new HashMap<>();
+ data.put(key, toscaDataMap);
+ Either<GraphVertex, StorageOperationStatus> createRes = assosiateElementToData(toscaElement, vertexLabel, edgeLabel, data);
+ if (createRes.isRight()) {
+ StorageOperationStatus status = createRes.right().value();
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to assosiate tosca data {} of the tosca element {}. Status is {}. ", edgeLabel, toscaElement.getUniqueId(), status);
+ result = status;
+ }
+ }
+ }
+ if (result == null) {
+ result = StorageOperationStatus.OK;
+ }
+ return result;
+ }
+
+ /**
+ * Updates tosca data element of tosca element by specified uid according received labels
+ *
+ * @param toscaElementUid
+ * @param edgeLabel
+ * @param vertexLabel
+ * @param toscaData
+ * @param mapKeyField
+ * @return
+ */
+ public <T extends ToscaDataDefinition> StorageOperationStatus updateToscaDataOfToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, T toscaData, JsonPresentationFields mapKeyField) {
+
+ List<T> toscaDataList = new ArrayList<>();
+ toscaDataList.add(toscaData);
+ return updateToscaDataOfToscaElement(toscaElementUid, edgeLabel, vertexLabel, toscaDataList, mapKeyField);
+ }
+
+ /**
+ * Updates list of tosca data elements belonging to tosca element with specified uid according received labels
+ *
+ * @param toscaElementUid
+ * @param edgeLabel
+ * @param vertexLabel
+ * @param toscaDataList
+ * @param mapKeyField
+ * @return
+ */
+ public <T extends ToscaDataDefinition> StorageOperationStatus updateToscaDataOfToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List<T> toscaDataList, JsonPresentationFields mapKeyField) {
+
+ StorageOperationStatus statusRes = null;
+ Either<GraphVertex, TitanOperationStatus> getToscaElementRes;
+
+ getToscaElementRes = titanDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse);
+ if (getToscaElementRes.isRight()) {
+ TitanOperationStatus status = getToscaElementRes.right().value();
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to get tosca element {} upon adding the properties. Status is {}. ", toscaElementUid, status);
+ statusRes = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
+ }
+ if (statusRes == null && CollectionUtils.isNotEmpty(toscaDataList)) {
+ statusRes = updateToscaDataOfToscaElement(getToscaElementRes.left().value(), edgeLabel, vertexLabel, toscaDataList, mapKeyField);
+ }
+ if (statusRes == null) {
+ statusRes = StorageOperationStatus.OK;
+ }
+ return statusRes;
+ }
+
+ /**
+ * Adds list of tosca data elements to tosca element with specified uid according received labels
+ *
+ * @param toscaElementUid
+ * @param edgeLabel
+ * @param vertexLabel
+ * @param toscaDataList
+ * @param mapKeyField
+ * @return
+ */
+ public <T extends ToscaDataDefinition> StorageOperationStatus addToscaDataToToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List<T> toscaDataList, JsonPresentationFields mapKeyField) {
+
+ StorageOperationStatus statusRes = null;
+ Either<GraphVertex, TitanOperationStatus> getToscaElementRes;
+
+ getToscaElementRes = titanDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse);
+ if (getToscaElementRes.isRight()) {
+ TitanOperationStatus status = getToscaElementRes.right().value();
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to get tosca element {} upon adding the properties. Status is {}. ", toscaElementUid, status);
+ statusRes = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
+ }
+ if (statusRes == null && CollectionUtils.isNotEmpty(toscaDataList)) {
+ statusRes = addToscaDataToToscaElement(getToscaElementRes.left().value(), edgeLabel, vertexLabel, toscaDataList, mapKeyField);
+ }
+ if (statusRes == null) {
+ statusRes = StorageOperationStatus.OK;
+ }
+ return statusRes;
+ }
+
+ /**
+ * Converts recieved map of tosca data elements to list and adds it to tosca element according received labels
+ *
+ * @param toscaElement
+ * @param edgeLabel
+ * @param vertexLabel
+ * @param toscaDataMap
+ * @param mapKeyField
+ * @return
+ */
+ public <T extends ToscaDataDefinition> StorageOperationStatus addToscaDataToToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, Map<String, T> toscaDataMap, JsonPresentationFields mapKeyField) {
+
+ return addToscaDataToToscaElement(toscaElement, edgeLabel, vertexLabel, toscaDataMap.values().stream().collect(Collectors.toList()), mapKeyField);
+ }
+
+ /**
+ * Adds list of tosca data elements to tosca element according received labels
+ *
+ * @param toscaElement
+ * @param edgeLabel
+ * @param vertexLabel
+ * @param toscaDataList
+ * @param mapKeyField
+ * @return
+ */
+ public <T extends ToscaDataDefinition> StorageOperationStatus addToscaDataToToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List<T> toscaDataList, JsonPresentationFields mapKeyField) {
+
+ return updateOrAddToscaData(toscaElement, edgeLabel, vertexLabel, toscaDataList, mapKeyField, false);
+ }
+
+ /**
+ * Updates list of tosca data elements belonging to tosca element according received labels
+ *
+ * @param toscaElement
+ * @param edgeLabel
+ * @param vertexLabel
+ * @param toscaDataList
+ * @param mapKeyField
+ * @return
+ */
+ public <T extends ToscaDataDefinition> StorageOperationStatus updateToscaDataOfToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List<T> toscaDataList, JsonPresentationFields mapKeyField) {
+
+ return updateOrAddToscaData(toscaElement, edgeLabel, vertexLabel, toscaDataList, mapKeyField, true);
+ }
+
+ @SuppressWarnings("unchecked")
+ private <T extends ToscaDataDefinition> StorageOperationStatus updateOrAddToscaData(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List<T> toscaDataList, JsonPresentationFields mapKeyField, boolean isUpdate) {
+ StorageOperationStatus result = null;
+ GraphVertex toscaDataVertex = null;
+ Map<String, T> existingToscaDataMap = null;
+ Either<Map<String, T>, StorageOperationStatus> validateRes = null;
+ Map<String, T> mergedToscaDataMap;
+ Either<GraphVertex, TitanOperationStatus> toscaDataVertexRes = titanDao.getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson);
+ if (toscaDataVertexRes.isRight() && toscaDataVertexRes.right().value() != TitanOperationStatus.NOT_FOUND) {
+ TitanOperationStatus status = toscaDataVertexRes.right().value();
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to get child vertex of the tosca element {} by label {}. Status is {}. ", toscaElement.getUniqueId(), edgeLabel, status);
+ result = DaoStatusConverter.convertTitanStatusToStorageStatus(toscaDataVertexRes.right().value());
+ }
+ if (result == null) {
+ if (toscaDataVertexRes.isLeft()) {
+ toscaDataVertex = toscaDataVertexRes.left().value();
+ existingToscaDataMap = (Map<String, T>) toscaDataVertex.getJson();
+ }
+
+ 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);
+ }
+ }
+ if (result == null) {
+ mergedToscaDataMap = validateRes.left().value();
+ result = handleToscaData(toscaElement, vertexLabel, edgeLabel, toscaDataVertex, mergedToscaDataMap);
+ }
+ if (result == null) {
+ result = StorageOperationStatus.OK;
+ }
+ return result;
+
+ }
+
+ @SuppressWarnings("unchecked")
+ public <T extends ToscaDataDefinition> StorageOperationStatus updateFullToscaData(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, Map<String, T> toscaData) {
+ StorageOperationStatus result = null;
+ GraphVertex toscaDataVertex = null;
+ Map<String, T> existingToscaDataMap = null;
+
+ Either<GraphVertex, TitanOperationStatus> toscaDataVertexRes = titanDao.getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson);
+ if (toscaDataVertexRes.isRight() && toscaDataVertexRes.right().value() != TitanOperationStatus.NOT_FOUND) {
+ TitanOperationStatus status = toscaDataVertexRes.right().value();
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to get child vertex of the tosca element {} by label {}. Status is {}. ", toscaElement.getUniqueId(), edgeLabel, status);
+ result = DaoStatusConverter.convertTitanStatusToStorageStatus(toscaDataVertexRes.right().value());
+ }
+ if (result == null) {
+ if (toscaDataVertexRes.isLeft()) {
+ toscaDataVertex = toscaDataVertexRes.left().value();
+ existingToscaDataMap = (Map<String, T>) toscaDataVertex.getJson();
+ }
+
+
+ }
+ if (result == null) {
+
+ result = handleToscaData(toscaElement, vertexLabel, edgeLabel, toscaDataVertex, toscaData);
+ }
+ if (result == null) {
+ result = StorageOperationStatus.OK;
+ }
+ return result;
+
+ }
+
+ @SuppressWarnings({ "rawtypes", "unchecked" })
+ private <T, K extends ToscaDataDefinition> StorageOperationStatus updateOrAddToscaDataDeepElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List<K> toscaDataList, List<String> pathKeys,
+ JsonPresentationFields mapKeyField, boolean isUpdate) {
+
+ StorageOperationStatus result = null;
+ GraphVertex toscaDataVertex = null;
+ Map<String, K> existingDeepElementsMap = null;
+ Either<Map<String, K>, StorageOperationStatus> validateRes = null;
+ Either<GraphVertex, TitanOperationStatus> toscaDataVertexRes = titanDao.getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson);
+ if (toscaDataVertexRes.isRight() && toscaDataVertexRes.right().value() != TitanOperationStatus.NOT_FOUND) {
+ TitanOperationStatus status = toscaDataVertexRes.right().value();
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to get child vertex of the tosca element {} by label {}. Status is {}. ", toscaElement.getUniqueId(), edgeLabel, status);
+ result = DaoStatusConverter.convertTitanStatusToStorageStatus(toscaDataVertexRes.right().value());
+ }
+ if (result == null) {
+ if (toscaDataVertexRes.isLeft()) {
+ toscaDataVertex = toscaDataVertexRes.left().value();
+ existingDeepElementsMap = getDeepElements(toscaDataVertex, pathKeys);
+ }
+ validateRes = validateMergeToscaData(toscaElement, toscaDataList, mapKeyField, existingDeepElementsMap, isUpdate);
+ if (validateRes.isRight()) {
+ result = validateRes.right().value();
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed validate tosca data upon adding to tosca element {}. Status is {}. ", toscaElement.getUniqueId(), edgeLabel, result);
+ }
+ }
+ if (result == null) {
+ updateDeepElements(toscaDataVertex, validateRes.left().value(), pathKeys);
+ Map<String, K> toscaDataToHandle;
+ if(toscaDataVertex == null){
+ toscaDataToHandle = new HashMap<>();
+ Map<String, K> currMap = toscaDataToHandle;
+ for (int i = 1; i < pathKeys.size()-1; ++i) {
+ currMap.put(pathKeys.get(i), (K) new MapDataDefinition());
+ currMap = (Map<String, K>) ((MapDataDefinition) currMap).getMapToscaDataDefinition().get(pathKeys.get(i));
+ }
+ toscaDataToHandle.put(pathKeys.get(pathKeys.size()-1), (K) new MapDataDefinition(validateRes.left().value()));
+
+ } else {
+ toscaDataToHandle = (Map<String, K>) toscaDataVertex.getJson();
+ }
+ result = handleToscaData(toscaElement, vertexLabel, edgeLabel, toscaDataVertex, toscaDataToHandle);
+ }
+ if (result == null) {
+ result = StorageOperationStatus.OK;
+ }
+ return result;
+ }
+
+ @SuppressWarnings({ "rawtypes", "unchecked" })
+ private <T, K extends ToscaDataDefinition> void updateDeepElements(GraphVertex toscaDataVertex, Map<String, K> mergedDeepElementMap, List<String> pathKeys) {
+
+ if (toscaDataVertex != null && MapUtils.isNotEmpty(mergedDeepElementMap)) {
+ Map<String, MapDataDefinition> currMap = (Map<String, MapDataDefinition>) toscaDataVertex.getJson();
+ if(!currMap.containsKey(pathKeys.get(0))){
+ currMap.put(pathKeys.get(0), new MapDataDefinition<>());
+ }
+ MapDataDefinition currDeepElement = currMap.get(pathKeys.get(0));
+
+ for (int i = 1; i < pathKeys.size(); ++i) {
+ if(currDeepElement.findByKey(pathKeys.get(i)) == null){
+ currDeepElement.put(pathKeys.get(i), new MapDataDefinition<>());
+ }
+ currDeepElement = (MapDataDefinition) currDeepElement.findByKey(pathKeys.get(i));
+ }
+ if(currDeepElement != null){
+ for (Map.Entry<String, K> elementEntry : mergedDeepElementMap.entrySet()) {
+ currDeepElement.put(elementEntry.getKey(), elementEntry.getValue());
+ }
+ }
+ }
+ }
+
+ @SuppressWarnings({ "unchecked", "rawtypes" })
+ private <T, K extends ToscaDataDefinition> Map<String, K> getDeepElements(GraphVertex toscaDataVertex, List<String> pathKeys) {
+ Map<String, K> result = null;
+ Map<String, T> currMap = (Map<String, T>) toscaDataVertex.getJson();
+ MapDataDefinition currDeepElement = (MapDataDefinition) currMap.get(pathKeys.get(0));
+ for (int i = 1; i < pathKeys.size(); ++i) {
+ currDeepElement = (MapDataDefinition) currDeepElement.findByKey(pathKeys.get(i));
+ }
+ if(currDeepElement != null){
+ result = (Map<String, K>) currDeepElement.getMapToscaDataDefinition();
+ }
+ return result;
+ }
+
+ @SuppressWarnings("unchecked")
+ private <T extends ToscaDataDefinition> StorageOperationStatus addDeepElementsBlock(GraphVertex toscaDataVertex, T toscaDataBlock, String key) {
+
+ StorageOperationStatus result = null;
+ Map<String, T> currMap = (Map<String, T>) toscaDataVertex.getJson();
+ if (currMap.containsKey(key)) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to add block of deep tosca data elements by label {}." + " The block element with the same key {} already exists. ", toscaDataVertex.getLabel(), key);
+ result = StorageOperationStatus.ENTITY_ALREADY_EXISTS;
+ }
+ if (result == null) {
+ currMap.put(key, toscaDataBlock);
+ }
+ return null;
+ }
+
+ @SuppressWarnings("unchecked")
+ private <T extends ToscaDataDefinition> StorageOperationStatus deleteDeepElementsBlock(GraphVertex toscaDataVertex, String key) {
+
+ StorageOperationStatus result = null;
+ Map<String, T> currMap = (Map<String, T>) toscaDataVertex.getJson();
+ if (!currMap.containsKey(key)) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete block of deep tosca data elements by label {}." + " The block element with the same key {} doesn't exist. ", toscaDataVertex.getLabel(), key);
+ result = StorageOperationStatus.NOT_FOUND;
+ }
+ if (result == null) {
+ currMap.remove(key);
+ }
+ return null;
+ }
+
+ /**
+ * Removes tosca data vertex belonging to tosca element specified by uid according label
+ *
+ * @param toscaElementUid
+ * @param edgeLabel
+ * @param vertexLabel
+ * @return
+ */
+ public StorageOperationStatus removeToscaData(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel) {
+
+ StorageOperationStatus statusRes = StorageOperationStatus.OK;
+ Either<GraphVertex, TitanOperationStatus> getToscaElementRes;
+
+ getToscaElementRes = titanDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse);
+ if (getToscaElementRes.isRight()) {
+ TitanOperationStatus status = getToscaElementRes.right().value();
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to get tosca element {} upon adding the properties. Status is {}. ", toscaElementUid, status);
+ statusRes = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
+ }
+ if (statusRes == StorageOperationStatus.OK) {
+ statusRes = removeToscaDataVertex(getToscaElementRes.left().value(), edgeLabel, vertexLabel);
+ }
+ return statusRes;
+ }
+
+ /**
+ * Removes tosca data vertex belonging to tosca element according label
+ *
+ * @param toscaElement
+ * @param edgeLabel
+ * @param vertexLabel
+ * @return
+ */
+ public StorageOperationStatus removeToscaDataVertex(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel) {
+ StorageOperationStatus result = null;
+ GraphVertex toscaDataVertex = null;
+ Iterator<Edge> edges = null;
+ int edgeCounter = 0;
+ Edge edge = null;
+ Edge edgeToDelete = null;
+ Either<GraphVertex, TitanOperationStatus> toscaDataVertexRes = titanDao.getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson);
+ if (toscaDataVertexRes.isRight()) {
+ TitanOperationStatus status = toscaDataVertexRes.right().value();
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed remove tosca data vertex of the tosca element {} by label {}. Status is {}. ", toscaElement.getUniqueId(), edgeLabel, status);
+ result = DaoStatusConverter.convertTitanStatusToStorageStatus(toscaDataVertexRes.right().value());
+ }
+ if (result == null) {
+ toscaDataVertex = toscaDataVertexRes.left().value();
+ edges = toscaDataVertex.getVertex().edges(Direction.IN);
+ if (edges == null || !edges.hasNext()) {
+ result = StorageOperationStatus.NOT_FOUND;
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed remove tosca data vertex of the tosca element {} by label {}. Status is {}. ", toscaElement.getUniqueId(), edgeLabel, result);
+ }
+ }
+ if (result == null) {
+ while (edges.hasNext()) {
+ ++edgeCounter;
+ edge = edges.next();
+ if (edge.outVertex().id().equals(toscaElement.getVertex().id())) {
+ edgeToDelete = edge;
+ break;
+ }
+ }
+ if (edgeToDelete == null) {
+ result = StorageOperationStatus.NOT_FOUND;
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed remove tosca data vertex of the tosca element {} by label {}. Status is {}. ", toscaElement.getUniqueId(), edgeLabel, result);
+ }
+ }
+ if (result == null) {
+ if (edgeCounter > 1) {
+ edgeToDelete.remove();
+ } else {
+ toscaDataVertex.getVertex().remove();
+ }
+ }
+ if (result == null) {
+ result = StorageOperationStatus.OK;
+ }
+ return result;
+ }
+
+ /**
+ * Deletes tosca data elements belonging to tosca element specified by uid according label
+ *
+ * @param toscaElementUid
+ * @param edgeLabel
+ * @param vertexLabel
+ * @param uniqueKeys
+ * @param mapKeyField
+ * @return
+ */
+ public StorageOperationStatus deleteToscaDataElements(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List<String> uniqueKeys, JsonPresentationFields mapKeyField) {
+
+ StorageOperationStatus statusRes = StorageOperationStatus.OK;
+ Either<GraphVertex, TitanOperationStatus> getToscaElementRes;
+
+ getToscaElementRes = titanDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse);
+ if (getToscaElementRes.isRight()) {
+ TitanOperationStatus status = getToscaElementRes.right().value();
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to get tosca element {} upon adding the properties. Status is {}. ", toscaElementUid, status);
+ statusRes = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
+ }
+ if (statusRes == StorageOperationStatus.OK) {
+ statusRes = deleteToscaDataElements(getToscaElementRes.left().value(), edgeLabel, vertexLabel, uniqueKeys, mapKeyField);
+ }
+ return statusRes;
+ }
+
+ /**
+ * Deletes tosca data element belonging to tosca element specified by uid according label
+ *
+ * @param toscaElementUid
+ * @param edgeLabel
+ * @param vertexLabel
+ * @param uniqueKey
+ * @param mapKeyField
+ * @return
+ */
+ public StorageOperationStatus deleteToscaDataElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, String uniqueKey, JsonPresentationFields mapKeyField) {
+
+ StorageOperationStatus statusRes = StorageOperationStatus.OK;
+ Either<GraphVertex, TitanOperationStatus> getToscaElementRes;
+
+ getToscaElementRes = titanDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse);
+ if (getToscaElementRes.isRight()) {
+ TitanOperationStatus status = getToscaElementRes.right().value();
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to get tosca element {} upon adding the properties. Status is {}. ", toscaElementUid, status);
+ statusRes = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
+ }
+ if (statusRes == StorageOperationStatus.OK) {
+ statusRes = deleteToscaDataElement(getToscaElementRes.left().value(), edgeLabel, vertexLabel, uniqueKey, mapKeyField);
+ }
+ return statusRes;
+
+ }
+
+ /**
+ * Deletes tosca data deep element belonging to tosca element specified by uid according label
+ *
+ * @param toscaElementUid
+ * @param edgeLabel
+ * @param vertexLabel
+ * @param uniqueKey
+ * @param pathKeys
+ * @param mapKeyField
+ * @return
+ */
+ public StorageOperationStatus deleteToscaDataDeepElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, String uniqueKey, List<String> pathKeys, JsonPresentationFields mapKeyField) {
+
+ StorageOperationStatus statusRes = StorageOperationStatus.OK;
+ Either<GraphVertex, TitanOperationStatus> getToscaElementRes;
+
+ getToscaElementRes = titanDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse);
+ if (getToscaElementRes.isRight()) {
+ TitanOperationStatus status = getToscaElementRes.right().value();
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to get tosca element {} upon adding the properties. Status is {}. ", toscaElementUid, status);
+ statusRes = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
+ }
+ if (statusRes == StorageOperationStatus.OK) {
+ statusRes = deleteToscaDataDeepElement(getToscaElementRes.left().value(), edgeLabel, vertexLabel, uniqueKey, pathKeys, mapKeyField);
+ }
+ return statusRes;
+
+ }
+
+ /**
+ * Deletes tosca data deep element belonging to tosca element according label
+ *
+ * @param toscaElement
+ * @param edgeLabel
+ * @param vertexLabel
+ * @param uniqueKey
+ * @param pathKeys
+ * @param mapKeyField
+ * @return
+ */
+ public StorageOperationStatus deleteToscaDataDeepElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, String uniqueKey, List<String> pathKeys, JsonPresentationFields mapKeyField) {
+
+ List<String> uniqueKeys = new ArrayList<>();
+ uniqueKeys.add(uniqueKey);
+ return deleteToscaDataDeepElements(toscaElement, edgeLabel, vertexLabel, uniqueKeys, pathKeys, mapKeyField);
+ }
+
+ public StorageOperationStatus deleteToscaDataDeepElements(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List<String> uniqueKeys, List<String> pathKeys, JsonPresentationFields mapKeyField) {
+
+ StorageOperationStatus result = null;
+ GraphVertex toscaDataVertex;
+ Map<String, ToscaDataDefinition> existingToscaDataMap = null;
+ Either<GraphVertex, TitanOperationStatus> toscaDataVertexRes = titanDao.getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson);
+ if (toscaDataVertexRes.isRight()) {
+ TitanOperationStatus status = toscaDataVertexRes.right().value();
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to get child vertex of the tosca element {} by label {}. Status is {}. ", toscaElement.getUniqueId(), edgeLabel, status);
+ result = DaoStatusConverter.convertTitanStatusToStorageStatus(toscaDataVertexRes.right().value());
+ }
+ if (result == null) {
+ toscaDataVertex = toscaDataVertexRes.left().value();
+ existingToscaDataMap = (Map<String, ToscaDataDefinition>) getDeepElements(toscaDataVertexRes.left().value(), pathKeys);
+ for (String uniqueKey : uniqueKeys) {
+ result = removeToscaDataElement(toscaElement, edgeLabel, uniqueKey, toscaDataVertex, existingToscaDataMap);
+ if (result != StorageOperationStatus.OK) {
+ break;
+ }
+ }
+ }
+ if (result == null) {
+ result = StorageOperationStatus.OK;
+ }
+ return result;
+ }
+
+ /**
+ * Deletes tosca data element belonging to tosca element according label
+ *
+ * @param toscaElement
+ * @param edgeLabel
+ * @param vertexLabel
+ * @param uniqueKey
+ * @param mapKeyField
+ * @return
+ */
+ public StorageOperationStatus deleteToscaDataElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, String uniqueKey, JsonPresentationFields mapKeyField) {
+
+ List<String> uniqueKeys = new ArrayList<>();
+ uniqueKeys.add(uniqueKey);
+ return deleteToscaDataElements(toscaElement, edgeLabel, vertexLabel, uniqueKeys, mapKeyField);
+ }
+
+ @SuppressWarnings("unchecked")
+ /**
+ * Deletes tosca data elements belonging to tosca element according label
+ *
+ * @param toscaElement
+ * @param edgeLabel
+ * @param vertexLabel
+ * @param uniqueKeys
+ * @param mapKeyField
+ * @return
+ */
+ public StorageOperationStatus deleteToscaDataElements(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List<String> uniqueKeys, JsonPresentationFields mapKeyField) {
+
+ StorageOperationStatus result = null;
+ GraphVertex toscaDataVertex;
+ Map<String, ToscaDataDefinition> existingToscaDataMap = null;
+ Either<GraphVertex, TitanOperationStatus> toscaDataVertexRes = titanDao.getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson);
+ if (toscaDataVertexRes.isRight()) {
+ TitanOperationStatus status = toscaDataVertexRes.right().value();
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to get child vertex of the tosca element {} by label {}. Status is {}. ", toscaElement.getUniqueId(), edgeLabel, status);
+ result = DaoStatusConverter.convertTitanStatusToStorageStatus(toscaDataVertexRes.right().value());
+ }
+ if (result == null) {
+ toscaDataVertex = toscaDataVertexRes.left().value();
+ existingToscaDataMap = (Map<String, ToscaDataDefinition>) toscaDataVertex.getJson();
+ for (String uniqueKey : uniqueKeys) {
+ result = removeToscaDataElement(toscaElement, edgeLabel, uniqueKey, toscaDataVertex, existingToscaDataMap);
+ if (result != StorageOperationStatus.OK) {
+ break;
+ }
+ }
+ }
+ if (result == null) {
+ result = StorageOperationStatus.OK;
+ }
+ return result;
+ }
+
+ private <T extends ToscaDataDefinition> StorageOperationStatus removeToscaDataElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, String uniqueKey, GraphVertex toscaDataVertex, Map<String, T> existingToscaDataMap) {
+
+ StorageOperationStatus result = StorageOperationStatus.OK;
+ if (!existingToscaDataMap.containsKey(uniqueKey)) {
+ result = StorageOperationStatus.NOT_FOUND;
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete tosca data element of the tosca element {} by label {}. Status is {}. ", toscaElement.getUniqueId(), edgeLabel, result);
+ } else {
+ existingToscaDataMap.remove(uniqueKey);
+ Either<GraphVertex, TitanOperationStatus> updateOrCopyRes = updateOrCopyOnUpdate(toscaDataVertex, toscaElement, edgeLabel);
+ if (updateOrCopyRes.isRight()) {
+ result = DaoStatusConverter.convertTitanStatusToStorageStatus(updateOrCopyRes.right().value());
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update tosca data {} of the tosca element {}. Status is {}. ", edgeLabel, toscaElement.getUniqueId(), result);
+ }
+ }
+ return result;
+ }
+
+ private <K extends ToscaDataDefinition> StorageOperationStatus handleToscaData(GraphVertex toscaElement, VertexTypeEnum vertexLabel, EdgeLabelEnum edgeLabel, GraphVertex toscaDataVertex, Map<String, K> mergedToscaDataMap) {
+
+ StorageOperationStatus result = null;
+ if (toscaDataVertex == null) {
+
+ Either<GraphVertex, StorageOperationStatus> createRes = assosiateElementToData(toscaElement, vertexLabel, edgeLabel, mergedToscaDataMap);
+ if (createRes.isRight()) {
+ StorageOperationStatus status = createRes.right().value();
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to assosiate tosca data {} of the tosca element {}. Status is {}. ", edgeLabel, toscaElement.getUniqueId(), status);
+ result = status;
+ }
+ } else {
+ toscaDataVertex.setJson(mergedToscaDataMap);
+ Either<GraphVertex, TitanOperationStatus> updateOrCopyRes = updateOrCopyOnUpdate(toscaDataVertex, toscaElement, edgeLabel);
+ if (updateOrCopyRes.isRight()) {
+ TitanOperationStatus status = updateOrCopyRes.right().value();
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to add tosca data {} to the tosca element {}. Status is {}. ", edgeLabel, toscaElement.getUniqueId(), status);
+ result = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
+ }
+ }
+ return result;
+ }
+
+ private <T extends ToscaDataDefinition> Either<Map<String, T>, StorageOperationStatus> validateMergeToscaData(GraphVertex toscaElement, List<T> toscaDataList, JsonPresentationFields mapKeyField, Map<String, T> existingToscaDataMap,
+ boolean isUpdate) {
+
+ Map<String, T> mergedToscaDataMap = new HashMap<>();
+ StorageOperationStatus status;
+ Either<Map<String, T>, StorageOperationStatus> result = Either.left(mergedToscaDataMap);
+ if (MapUtils.isNotEmpty(existingToscaDataMap)) {
+ mergedToscaDataMap.putAll(existingToscaDataMap);
+ }
+ for (T toscaDataElement : toscaDataList) {
+ status = handleToscaDataElement(toscaElement, mapKeyField, mergedToscaDataMap, toscaDataElement, isUpdate);
+ if (status != StorageOperationStatus.OK) {
+ result = Either.right(status);
+ break;
+ }
+ }
+ return result;
+ }
+
+ private <T extends ToscaDataDefinition> StorageOperationStatus handleToscaDataElement(GraphVertex toscaElement, JsonPresentationFields mapKeyField, Map<String, T> mergedToscaDataMap, T toscaDataElement, boolean isUpdate) {
+
+ StorageOperationStatus status = StorageOperationStatus.OK;
+ String currKey = (String) toscaDataElement.getToscaPresentationValue(mapKeyField);
+ if (StringUtils.isEmpty(currKey)) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to add tosca data to tosca element {}. The key is empty. ");
+ status = StorageOperationStatus.BAD_REQUEST;
+ } else if (!isUpdate && mergedToscaDataMap.containsKey(currKey)) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to add tosca data to tosca element {}. The element with the same key {} already exists. ", toscaElement.getUniqueId(), currKey);
+ status = StorageOperationStatus.BAD_REQUEST;
+ }
+ mergedToscaDataMap.put(currKey, toscaDataElement);
+ return status;
+ }
+
+// public StorageOperationStatus updateDataOnGraph(GraphVertex dataVertex) {
+// Either<GraphVertex, TitanOperationStatus> updateVertex = titanDao.updateVertex(dataVertex);
+// if (updateVertex.isRight()) {
+// return DaoStatusConverter.convertTitanStatusToStorageStatus(updateVertex.right().value());
+// }
+// return StorageOperationStatus.OK;
+// }
+
+}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ByToscaNameDerivedNodeTypeResolver.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ByToscaNameDerivedNodeTypeResolver.java
new file mode 100644
index 0000000000..8fe70f02b1
--- /dev/null
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ByToscaNameDerivedNodeTypeResolver.java
@@ -0,0 +1,35 @@
+package org.openecomp.sdc.be.model.jsontitan.operations;
+
+import fj.data.Either;
+import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
+import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
+import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
+import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
+import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
+import org.openecomp.sdc.be.model.DerivedNodeTypeResolver;
+import org.openecomp.sdc.be.model.LifecycleStateEnum;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+@Component("derived-resource-resolver")
+public class ByToscaNameDerivedNodeTypeResolver implements DerivedNodeTypeResolver {
+
+ @Autowired
+ private TitanDao titanDao;
+
+ @Override
+ public Either<List<GraphVertex>, TitanOperationStatus> findDerivedResources(String parentResource) {
+ Map<GraphPropertyEnum, Object> propertiesToMatch = new HashMap<GraphPropertyEnum, Object>();
+ propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
+
+ propertiesToMatch.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, parentResource);
+ propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+
+ return titanDao.getByCriteria(VertexTypeEnum.NODE_TYPE, propertiesToMatch, JsonParseFlagEnum.NoParse);
+ }
+}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/CategoryOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/CategoryOperation.java
new file mode 100644
index 0000000000..898dec03a8
--- /dev/null
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/CategoryOperation.java
@@ -0,0 +1,73 @@
+package org.openecomp.sdc.be.model.jsontitan.operations;
+
+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.EdgeLabelEnum;
+import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
+import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
+import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
+import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
+import org.openecomp.sdc.common.util.ValidationUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import fj.data.Either;
+
+@org.springframework.stereotype.Component("category-operation")
+public class CategoryOperation extends BaseOperation{
+
+ private static Logger log = LoggerFactory.getLogger(CategoryOperation.class.getName());
+
+ /**
+ *
+ * @param name
+ * @param type
+ * @return
+ */
+ public Either<GraphVertex, StorageOperationStatus> getCategory(String name, VertexTypeEnum type) {
+ if (name != null) {
+ String categoryUid = UniqueIdBuilder.buildComponentCategoryUid(name, type);
+ Map<GraphPropertyEnum, Object> props = new HashMap<>();
+ props.put(GraphPropertyEnum.NORMALIZED_NAME, ValidationUtils.normalizeCategoryName4Uniqueness(name));
+ Either<List<GraphVertex>, TitanOperationStatus> either = titanDao.getByCriteria(type, props);
+
+ if (either.isRight()) {
+ TitanOperationStatus titanOperationStatus = either.right().value();
+ log.debug("Problem while geting category with id {}. reason - {}", categoryUid, titanOperationStatus.name());
+ if (titanOperationStatus == TitanOperationStatus.NOT_FOUND) {
+ return Either.right(StorageOperationStatus.CATEGORY_NOT_FOUND);
+ } else {
+ return Either.right(StorageOperationStatus.GENERAL_ERROR);
+ }
+ }
+ return Either.left(either.left().value().get(0));
+ } else {
+ return Either.right(StorageOperationStatus.GENERAL_ERROR);
+ }
+ }
+ /**
+ *
+ * @param categoryV
+ * @param name
+ * @return
+ */
+ public Either<GraphVertex, StorageOperationStatus> getSubCategoryForCategory(GraphVertex categoryV, String name ) {
+ Either<List<GraphVertex>, TitanOperationStatus> childrenVertecies = titanDao.getChildrenVertecies(categoryV, EdgeLabelEnum.SUB_CATEGORY, JsonParseFlagEnum.NoParse);
+ if ( childrenVertecies.isRight() ){
+ log.debug("Failed to fetch children verticies for category {} error {}", categoryV.getUniqueId(), childrenVertecies.right().value());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(childrenVertecies.right().value()));
+ }
+ for ( GraphVertex childV : childrenVertecies.left().value() ){
+ if ( childV.getMetadataProperty(GraphPropertyEnum.NAME).equals(name) ){
+ return Either.left(childV);
+ }
+ }
+ return Either.right(StorageOperationStatus.NOT_FOUND);
+ }
+}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/GroupsOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/GroupsOperation.java
new file mode 100644
index 0000000000..97a5e11a13
--- /dev/null
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/GroupsOperation.java
@@ -0,0 +1,309 @@
+package org.openecomp.sdc.be.model.jsontitan.operations;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.stream.Collectors;
+
+import org.apache.tinkerpop.shaded.minlog.Log;
+import 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.GroupDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.GroupInstanceDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
+import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.GroupDefinition;
+import org.openecomp.sdc.be.model.GroupInstance;
+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;
+import org.openecomp.sdc.be.model.operations.impl.LifecycleOperation;
+import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
+import org.openecomp.sdc.be.resources.data.GroupData;
+import org.openecomp.sdc.common.api.Constants;
+import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
+import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.carrotsearch.junitbenchmarks.annotation.LabelType;
+import com.thinkaurelius.titan.diskstorage.Entry;
+
+import fj.data.Either;
+import javassist.expr.NewArray;
+
+@org.springframework.stereotype.Component("groups-operation")
+public class GroupsOperation extends BaseOperation {
+
+ private static Logger logger = LoggerFactory.getLogger(GroupsOperation.class.getName());
+
+ public Either<List<GroupDefinition>, StorageOperationStatus> createGroups(Component component, User user, ComponentTypeEnum componentType, Map<String, GroupDataDefinition> groups) {
+
+ Either<List<GroupDefinition>, StorageOperationStatus> result = null;
+ Either<GraphVertex, TitanOperationStatus> getComponentVertex = null;
+ StorageOperationStatus status = null;
+
+ if (result == null) {
+ getComponentVertex = titanDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse);
+ if (getComponentVertex.isRight()) {
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getComponentVertex.right().value()));
+ }
+ }
+ if (result == null) {
+ status = topologyTemplateOperation.associateGroupsToComponent(getComponentVertex.left().value(), groups);
+ if (status != StorageOperationStatus.OK) {
+ result = Either.right(status);
+ }
+ }
+ /* if (result == null) {
+ 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
+ Either<List<GroupDefinition>, StorageOperationStatus> result = null;
+ Either<GraphVertex, TitanOperationStatus> getComponentVertex = null;
+ StorageOperationStatus status = null;
+
+ if (result == null) {
+ getComponentVertex = titanDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse);
+ if (getComponentVertex.isRight()) {
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getComponentVertex.right().value()));
+ }
+ }
+ if (result == null) {
+ status = addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, groups, JsonPresentationFields.NAME);
+
+ if (status != StorageOperationStatus.OK) {
+ result = Either.right(status);
+ }
+ }
+
+ if (result == null) {
+ Map<String, GroupDataDefinition> mapGroup = groups.stream().collect(Collectors.toMap( x-> x.getName(), x->x));
+ result = Either.left(ModelConverter.convertToGroupDefinitions(mapGroup));
+ }
+ return result;
+ }
+
+ public Either<List<GroupDefinition>, StorageOperationStatus> deleteGroups(Component component, User user, ComponentTypeEnum componentType, List<GroupDataDefinition> groups) {
+ // TODO Auto-generated method stub
+ Either<List<GroupDefinition>, StorageOperationStatus> result = null;
+ Either<GraphVertex, TitanOperationStatus> getComponentVertex = null;
+ StorageOperationStatus status = null;
+
+ if (result == null) {
+ getComponentVertex = titanDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse);
+ if (getComponentVertex.isRight()) {
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getComponentVertex.right().value()));
+ }
+ }
+ if (result == null) {
+ List<String> groupName = groups.stream().map(g -> g.getName()).collect(Collectors.toList());
+ status = deleteToscaDataElements(component.getUniqueId(), EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, groupName, JsonPresentationFields.NAME);
+
+ if (status != StorageOperationStatus.OK) {
+ result = Either.right(status);
+ }
+ }
+
+ if (result == null) {
+ Map<String, GroupDataDefinition> mapGroup = groups.stream().collect(Collectors.toMap( x-> x.getName(), x->x));
+ result = Either.left(ModelConverter.convertToGroupDefinitions(mapGroup));
+ }
+ return result;
+ }
+
+ public Either<List<GroupDefinition>, StorageOperationStatus> updateGroups(Component component, ComponentTypeEnum componentType, List<GroupDataDefinition> groups) {
+ // TODO Auto-generated method stub
+ Either<List<GroupDefinition>, StorageOperationStatus> result = null;
+ Either<GraphVertex, TitanOperationStatus> getComponentVertex = null;
+ StorageOperationStatus status = null;
+
+ if (result == null) {
+ getComponentVertex = titanDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse);
+ if (getComponentVertex.isRight()) {
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getComponentVertex.right().value()));
+ }
+ }
+ if (result == null) {
+ groups.forEach(gr -> {
+ String version = gr.getVersion();
+ String newVersion = increaseMajorVersion(version);
+ gr.setVersion(newVersion);
+ String groupUUID = UniqueIdBuilder.generateUUID();
+ gr.setGroupUUID(groupUUID);
+ });
+
+ status = updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, groups, JsonPresentationFields.NAME);
+
+ if (status != StorageOperationStatus.OK) {
+ result = Either.right(status);
+ }
+ }
+
+ if (result == null) {
+ Map<String, GroupDataDefinition> mapGroup = groups.stream().collect(Collectors.toMap( x-> x.getName(), x->x));
+ result = Either.left(ModelConverter.convertToGroupDefinitions(mapGroup));
+ }
+ return result;
+ }
+
+
+ public Either<List<GroupProperty>, StorageOperationStatus> updateGroupPropertiesOnComponent(String componentId, GroupDefinition group, List<GroupProperty> newGroupProperties) {
+
+ 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);
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getComponentVertex.right().value()));
+ }
+ }
+ if (result == null) {
+ componentVertex = getComponentVertex.left().value();
+ //update
+ List<PropertyDataDefinition> properties = group.getProperties();
+ newGroupProperties.forEach(np -> {
+ Optional<PropertyDataDefinition> currentProp = properties.stream().filter(p -> p.getName().equals(np.getName())).findAny();
+ if (currentProp.isPresent()) {
+ currentProp.get().setValue(np.getValue());
+ }
+ });
+
+ StorageOperationStatus updateDataRes = updateToscaDataOfToscaElement(componentVertex, EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, group, JsonPresentationFields.NAME);
+ if ( updateDataRes != StorageOperationStatus.OK ){
+ logger.debug("Failed to update properties for group {} error {}", group.getName(), updateDataRes);
+ result = Either.right(updateDataRes);
+ }
+ }
+ if (result == null) {
+ componentVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis());
+ Either<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());
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateRes.right().value()));
+ }
+ }
+ if (result == null) {
+ result = Either.left(newGroupProperties);
+ }
+ return result;
+ }
+
+ /**
+ * The version of the group is an integer. In order to support BC, we might get a version in a float format.
+ *
+ * @param version
+ * @return
+ */
+ private String increaseMajorVersion(String version) {
+
+ String[] versionParts = version.split(LifecycleOperation.VERSION_DELIMETER_REGEXP);
+ Integer majorVersion = Integer.parseInt(versionParts[0]);
+
+ majorVersion++;
+
+ return String.valueOf(majorVersion);
+
+ }
+
+ public Either<List<GroupInstance>, StorageOperationStatus> updateGroupInstances(Component component, ComponentTypeEnum componentType, String instanceId, List<GroupInstance> updatedGroupInstances) {
+
+ Either<List<GroupInstance>, StorageOperationStatus> result = null;
+ StorageOperationStatus status = null;
+
+ Either<GraphVertex, TitanOperationStatus> getComponentVertex = titanDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse);
+ if (getComponentVertex.isRight()) {
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getComponentVertex.right().value()));
+ }
+ if (result == null) {
+ List<String> pathKeys = new ArrayList<>();
+ pathKeys.add(instanceId);
+ status = updateToscaDataDeepElementsOfToscaElement(component.getUniqueId(), EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS, updatedGroupInstances, pathKeys, JsonPresentationFields.NAME);
+ if (status != StorageOperationStatus.OK) {
+ result = Either.right(status);
+ }
+ }
+ if (result == null) {
+ result = Either.left(updatedGroupInstances);
+ }
+ return result;
+ }
+
+ public Either<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);
+ return Either.right(status);
+ }
+ return Either.left(currentGroup);
+ }
+
+ public StorageOperationStatus deleteGroup(Component component, String currentGroupName) {
+ StorageOperationStatus status = deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, currentGroupName, JsonPresentationFields.NAME);
+ if(status != StorageOperationStatus.OK){
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete group {} of component {}. The status is}. ", currentGroupName, component.getName(), status);
+ }
+ return status;
+ }
+
+ 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);
+ return Either.right(status);
+ }
+ return Either.left(currentGroup);
+ }
+
+ public Either<GroupInstance, StorageOperationStatus> updateGroupInstancePropertyValuesOnGraph(String componentId, String instanceId, GroupInstance oldGroupInstance, List<GroupInstanceProperty> newProperties) {
+
+ Either<GraphVertex, TitanOperationStatus> getComponentVertex = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata);
+ if (getComponentVertex.isRight()) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch component {}. Status is {} ", componentId);
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getComponentVertex.right().value()));
+ }
+
+ List<PropertyDataDefinition> propertiesOld = oldGroupInstance.getProperties();
+ newProperties.forEach(np -> {
+ Optional<PropertyDataDefinition> prop = propertiesOld.stream().filter(p -> p.getName().equals(np.getName())).findFirst();
+ if (prop.isPresent()) {
+ prop.get().setValue(np.getValue());
+ }
+ });
+ GroupInstanceDataDefinition groupInstanceDataDefinition = new GroupInstanceDataDefinition(oldGroupInstance);
+ List<String> pathKeys = new ArrayList<>();
+ 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);
+ return Either.right(updateDataRes);
+ }
+ return Either.left(oldGroupInstance);
+ }
+
+}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/InstancesOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/InstancesOperation.java
new file mode 100644
index 0000000000..b5154a7a0f
--- /dev/null
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/InstancesOperation.java
@@ -0,0 +1,5 @@
+package org.openecomp.sdc.be.model.jsontitan.operations;
+
+public class InstancesOperation extends BaseOperation {
+
+}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/NodeTemplateOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/NodeTemplateOperation.java
new file mode 100644
index 0000000000..a20f85ad7b
--- /dev/null
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/NodeTemplateOperation.java
@@ -0,0 +1,1740 @@
+package org.openecomp.sdc.be.model.jsontitan.operations;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Optional;
+import java.util.Set;
+import java.util.UUID;
+import java.util.stream.Collectors;
+
+import org.apache.commons.collections.CollectionUtils;
+import org.apache.commons.collections.MapUtils;
+import org.apache.commons.lang.StringUtils;
+import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.apache.commons.lang3.tuple.Pair;
+import org.apache.tinkerpop.gremlin.structure.Direction;
+import org.apache.tinkerpop.gremlin.structure.Edge;
+import org.openecomp.sdc.be.config.BeEcompErrorManager;
+import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
+import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
+import org.openecomp.sdc.be.dao.jsongraph.types.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.CompositionDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.GroupInstanceDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.ListRequirementDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.MapArtifactDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.MapAttributesDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.MapCapabiltyProperty;
+import org.openecomp.sdc.be.datatypes.elements.MapDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.MapGroupsDataDefinition;
+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.RelationshipInstDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
+import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.ArtifactDefinition;
+import org.openecomp.sdc.be.model.CapabilityDefinition;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.ComponentInstanceInput;
+import org.openecomp.sdc.be.model.ComponentInstanceProperty;
+import org.openecomp.sdc.be.model.DistributionStatusEnum;
+import org.openecomp.sdc.be.model.GroupDefinition;
+import org.openecomp.sdc.be.model.GroupInstance;
+import org.openecomp.sdc.be.model.RelationshipImpl;
+import org.openecomp.sdc.be.model.RequirementAndRelationshipPair;
+import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.jsontitan.datamodel.NodeType;
+import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate;
+import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement;
+import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum;
+import org.openecomp.sdc.be.model.jsontitan.enums.JsonConstantKeysEnum;
+import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
+import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
+import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
+import org.openecomp.sdc.common.api.ArtifactTypeEnum;
+import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
+import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
+import org.openecomp.sdc.common.util.ValidationUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import fj.data.Either;
+
+@org.springframework.stereotype.Component("node-template-operation")
+public class NodeTemplateOperation extends BaseOperation {
+ private static final String ARTIFACT_PLACEHOLDER_TYPE = "type";
+ private static final String ARTIFACT_PLACEHOLDER_DISPLAY_NAME = "displayName";
+ private static final Object ARTIFACT_PLACEHOLDER_DESCRIPTION = "description";
+ public static final String HEAT_ENV_NAME = "heatEnv";
+ public static final String HEAT_VF_ENV_NAME = "VfHeatEnv";
+ public static final String HEAT_ENV_SUFFIX = "env";
+ private static Integer defaultHeatTimeout;
+ public static final Integer NON_HEAT_TIMEOUT = 0;
+
+ private static Logger logger = LoggerFactory.getLogger(NodeTemplateOperation.class.getName());
+
+ public NodeTemplateOperation() {
+ defaultHeatTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getDefaultHeatArtifactTimeoutMinutes();
+ if ((defaultHeatTimeout == null) || (defaultHeatTimeout < 1)) {
+ defaultHeatTimeout = 60;
+ }
+ }
+
+ public static Integer getDefaultHeatTimeout() {
+ return defaultHeatTimeout;
+ }
+
+ public Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> addComponentInstanceToTopologyTemplate(TopologyTemplate container, ToscaElement originToscaElement, String instanceNumberSuffix, ComponentInstance componentInstance,
+ boolean allowDeleted, User user) {
+
+ Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> result = null;
+ Either<TopologyTemplate, StorageOperationStatus> addComponentInstanceRes = null;
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Going to create component instance {} in component {}", componentInstance, container.getUniqueId());
+ ComponentInstanceDataDefinition componentInstanceData = null;
+ Either<String, StorageOperationStatus> newInstanceNameRes = null;
+
+ Either<GraphVertex, TitanOperationStatus> metadataVertex = titanDao.getVertexById(container.getUniqueId(), JsonParseFlagEnum.ParseJson);
+ if (metadataVertex.isRight()) {
+ TitanOperationStatus status = metadataVertex.right().value();
+ if (status == TitanOperationStatus.NOT_FOUND) {
+ status = TitanOperationStatus.INVALID_ID;
+ }
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+
+ if (result == null) {
+ newInstanceNameRes = buildValidateInstanceName(container, originToscaElement, componentInstance, instanceNumberSuffix);
+ if (newInstanceNameRes.isRight()) {
+ result = Either.right(newInstanceNameRes.right().value());
+ }
+ }
+ if (result == null) {
+ componentInstanceData = buildComponentInstanceDataDefinition(componentInstance, container.getUniqueId(), newInstanceNameRes.left().value(), true, originToscaElement);
+
+ addComponentInstanceRes = addComponentInstanceToTopologyTemplate(container, originToscaElement, componentInstanceData, metadataVertex.left().value(), allowDeleted, user);
+
+ if (addComponentInstanceRes.isRight()) {
+ StorageOperationStatus status = addComponentInstanceRes.right().value();
+ if (status == StorageOperationStatus.NOT_FOUND) {
+ status = StorageOperationStatus.INVALID_ID;
+ }
+ result = Either.right(status);
+ }
+ }
+ if (result == null) {
+ result = Either.left(new ImmutablePair<>(addComponentInstanceRes.left().value(), componentInstanceData.getUniqueId()));
+ }
+ return result;
+ }
+
+ private Either<String, StorageOperationStatus> buildValidateInstanceName(TopologyTemplate container, ToscaElement originToscaElement, ComponentInstance componentInstance, String instanceNumberSuffix) {
+
+ Either<String, StorageOperationStatus> result = null;
+ String instanceName = componentInstance.getName();
+ if (StringUtils.isEmpty(instanceName) || instanceName.equalsIgnoreCase(originToscaElement.getName())) {
+ instanceName = buildComponentInstanceName(instanceNumberSuffix, instanceName);
+ } else if (!isUniqueInstanceName(container, componentInstance.getName())) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to create component instance with name {} on component container {}. The instance with the same name already exists. ", componentInstance.getName(), container.getName());
+ result = Either.right(StorageOperationStatus.ENTITY_ALREADY_EXISTS);
+ }
+ if (result == null) {
+ result = Either.left(instanceName);
+ }
+ return result;
+ }
+
+ public Either<TopologyTemplate, StorageOperationStatus> addComponentInstanceToTopologyTemplate(TopologyTemplate container, ToscaElement originToscaElement, ComponentInstanceDataDefinition componentInstance, GraphVertex metadataVertex,
+ boolean allowDeleted, User user) {
+
+ Either<TopologyTemplate, StorageOperationStatus> result = null;
+ Either<ToscaElement, StorageOperationStatus> updateContainerComponentRes = null;
+ String containerComponentId = container.getUniqueId();
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "Going to create component instance {} in component {}", componentInstance, containerComponentId);
+ String instOriginComponentId = componentInstance.getComponentUid();
+ Either<GraphVertex, TitanOperationStatus> updateElement = null;
+
+ Boolean isDeleted = (Boolean) originToscaElement.getMetadataValue(JsonPresentationFields.IS_DELETED);
+
+ if (!allowDeleted && (isDeleted != null) && isDeleted) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Component {} is already deleted. Cannot add component instance", instOriginComponentId);
+ result = Either.right(StorageOperationStatus.INVALID_ID);
+ }
+ if (result == null) {
+ container.addComponentInstance(componentInstance);
+ metadataVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis());
+ topologyTemplateOperation.fillToscaElementVertexData(metadataVertex, container, JsonParseFlagEnum.ParseAll);
+ updateElement = titanDao.updateVertex(metadataVertex);
+ if (updateElement.isRight()) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update topology template {} with new component instance {}. ", container.getName(), componentInstance.getName());
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateElement.right().value()));
+ }
+ }
+ if (result == null) {
+ Either<GraphVertex, StorageOperationStatus> addToscaDataRes = addComponentInstanceToscaDataToContainerComponent(originToscaElement, componentInstance, updateElement.left().value(), user);
+ if (addToscaDataRes.isRight()) {
+ result = Either.right(addToscaDataRes.right().value());
+ }
+ }
+
+ if (result == null) {
+ updateContainerComponentRes = topologyTemplateOperation.getToscaElement(containerComponentId);
+ if (updateContainerComponentRes.isRight()) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {} with new component instance {}. ", container.getName(), componentInstance.getName());
+ result = Either.right(updateContainerComponentRes.right().value());
+ }
+ }
+ if (result == null) {
+ result = Either.left((TopologyTemplate) updateContainerComponentRes.left().value());
+ }
+ return result;
+ }
+
+ public Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(TopologyTemplate container, ToscaElement originToscaElement, ComponentInstance componentInstance) {
+
+ Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> result = null;
+ Either<ToscaElement, StorageOperationStatus> updateContainerComponentRes = null;
+
+ String containerComponentId = container.getUniqueId();
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "Going to update component instance metadata {} of container component {}", componentInstance, containerComponentId);
+ ComponentInstanceDataDefinition componentInstanceData = null;
+
+ Either<GraphVertex, TitanOperationStatus> metadataVertex = titanDao.getVertexById(container.getUniqueId(), JsonParseFlagEnum.ParseMetadata);
+ if (metadataVertex.isRight()) {
+ TitanOperationStatus status = metadataVertex.right().value();
+ if (status == TitanOperationStatus.NOT_FOUND) {
+ status = TitanOperationStatus.INVALID_ID;
+ }
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ if (result == null) {
+ componentInstanceData = buildComponentInstanceDataDefinition(componentInstance, container.getUniqueId(), componentInstance.getName(), false, originToscaElement);
+ container.addComponentInstance(componentInstanceData);
+ metadataVertex.left().value().setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis());
+ topologyTemplateOperation.fillToscaElementVertexData(metadataVertex.left().value(), container, JsonParseFlagEnum.ParseAll);
+ Either<GraphVertex, TitanOperationStatus> updateElement = titanDao.updateVertex(metadataVertex.left().value());
+ if (updateElement.isRight()) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update topology template {} with new component instance {}. ", container.getName(), componentInstance.getName());
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateElement.right().value()));
+ }
+ }
+ if (result == null) {
+ updateContainerComponentRes = topologyTemplateOperation.getToscaElement(containerComponentId);
+ if (updateContainerComponentRes.isRight()) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {} with updated component instance {}. ", container.getName(), componentInstance.getName());
+ result = Either.right(updateContainerComponentRes.right().value());
+ }
+ }
+ if (result == null) {
+ result = Either.left(new ImmutablePair<>((TopologyTemplate) updateContainerComponentRes.left().value(), componentInstanceData.getUniqueId()));
+ }
+ return result;
+ }
+
+ public Either<TopologyTemplate, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(TopologyTemplate container) {
+
+ Either<TopologyTemplate, StorageOperationStatus> result = null;
+ Either<ToscaElement, StorageOperationStatus> updateContainerComponentRes = null;
+
+ String containerComponentId = container.getUniqueId();
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "Going to update component instance metadata of container component {}", containerComponentId);
+
+ Either<GraphVertex, TitanOperationStatus> metadataVertex = titanDao.getVertexById(container.getUniqueId(), JsonParseFlagEnum.ParseMetadata);
+ if (metadataVertex.isRight()) {
+ TitanOperationStatus status = metadataVertex.right().value();
+ if (status == TitanOperationStatus.NOT_FOUND) {
+ status = TitanOperationStatus.INVALID_ID;
+ }
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ if (result == null) {
+ metadataVertex.left().value().setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis());
+ topologyTemplateOperation.fillToscaElementVertexData(metadataVertex.left().value(), container, JsonParseFlagEnum.ParseAll);
+ Either<GraphVertex, TitanOperationStatus> updateElement = titanDao.updateVertex(metadataVertex.left().value());
+ if (updateElement.isRight()) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update topology template {}. ", container.getName());
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateElement.right().value()));
+ }
+ }
+ if (result == null) {
+ updateContainerComponentRes = topologyTemplateOperation.getToscaElement(containerComponentId);
+ if (updateContainerComponentRes.isRight()) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {}. ", container.getName());
+ result = Either.right(updateContainerComponentRes.right().value());
+ }
+ }
+ if (result == null) {
+ result = Either.left((TopologyTemplate) updateContainerComponentRes.left().value());
+ }
+ return result;
+ }
+
+ public Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> deleteComponentInstanceFromTopologyTemplate(TopologyTemplate container, String componentInstanceId) {
+
+ Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> result = null;
+ Either<ToscaElement, StorageOperationStatus> updateContainerComponentRes = null;
+
+ String containerComponentId = container.getUniqueId();
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "Going to update component instance metadata {} of container component {}", componentInstanceId, containerComponentId);
+
+ Either<GraphVertex, TitanOperationStatus> metadataVertex = titanDao.getVertexById(container.getUniqueId(), JsonParseFlagEnum.ParseMetadata);
+ if (metadataVertex.isRight()) {
+ TitanOperationStatus status = metadataVertex.right().value();
+ if (status == TitanOperationStatus.NOT_FOUND) {
+ status = TitanOperationStatus.INVALID_ID;
+ }
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ GraphVertex containerV = null;
+ if (result == null) {
+ container.getComponentInstances().remove(componentInstanceId);
+ containerV = metadataVertex.left().value();
+ StorageOperationStatus status = removeRelationsOfInstance(container, componentInstanceId, containerV);
+ if (status != StorageOperationStatus.OK) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete relation for component instance {} in container. error {}", componentInstanceId, container.getUniqueId(), status);
+ result = Either.right(status);
+ }
+
+ containerV.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis());
+ topologyTemplateOperation.fillToscaElementVertexData(containerV, container, JsonParseFlagEnum.ParseAll);
+ Either<GraphVertex, TitanOperationStatus> updateElement = titanDao.updateVertex(containerV);
+ if (updateElement.isRight()) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update topology template {} with new component instance {}. ", container.getName(), componentInstanceId);
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateElement.right().value()));
+ }
+ }
+ if (result == null) {
+ StorageOperationStatus status = deleteComponentInstanceToscaDataFromContainerComponent(containerV, componentInstanceId);
+ if (status != StorageOperationStatus.OK) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete data for instance {} in container {}. error {] ", componentInstanceId, container.getUniqueId(), status);
+ return Either.right(status);
+ }
+ updateContainerComponentRes = topologyTemplateOperation.getToscaElement(containerComponentId);
+ if (updateContainerComponentRes.isRight()) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {} after deleting the component instance {}. ", container.getName(), componentInstanceId);
+ result = Either.right(updateContainerComponentRes.right().value());
+ }
+ }
+ if (result == null) {
+ result = Either.left(new ImmutablePair<>((TopologyTemplate) updateContainerComponentRes.left().value(), componentInstanceId));
+ }
+ return result;
+ }
+
+ private StorageOperationStatus removeRelationsOfInstance(TopologyTemplate container, String ciToRemove, GraphVertex containerV) {
+ CompositionDataDefinition composition = container.getCompositions().get(JsonConstantKeysEnum.COMPOSITION.getValue());
+ if (composition != null) {
+ Map<String, RelationshipInstDataDefinition> relations = composition.getRelations();
+ if (relations != null) {
+ Either<Pair<GraphVertex, Map<String, MapListCapabiltyDataDefinition>>, StorageOperationStatus> capResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.CALCULATED_CAPABILITIES);
+ if (capResult.isRight()) {
+ return capResult.right().value();
+
+ }
+ Map<String, MapListCapabiltyDataDefinition> calculatedCapabilty = capResult.left().value().getRight();
+
+ Either<Pair<GraphVertex, Map<String, MapListCapabiltyDataDefinition>>, StorageOperationStatus> capFullResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.FULLFILLED_CAPABILITIES);
+ if (capResult.isRight()) {
+ return capResult.right().value();
+
+ }
+ Map<String, MapListCapabiltyDataDefinition> fullFilledCapabilty = capFullResult.left().value().getRight();
+
+ Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqResult = fetchContainerCalculatedRequirement(containerV, EdgeLabelEnum.CALCULATED_REQUIREMENTS);
+ if (reqResult.isRight()) {
+ return reqResult.right().value();
+ }
+ Map<String, MapListRequirementDataDefinition> calculatedRequirement = reqResult.left().value().getRight();
+
+ Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqFullResult = fetchContainerCalculatedRequirement(containerV, EdgeLabelEnum.FULLFILLED_REQUIREMENTS);
+ if (reqResult.isRight()) {
+ return reqResult.right().value();
+ }
+ Map<String, MapListRequirementDataDefinition> fullfilledRequirement = reqFullResult.left().value().getRight();
+
+ Iterator<Entry<String, RelationshipInstDataDefinition>> iterator = relations.entrySet().iterator();
+ while (iterator.hasNext()) {
+ Entry<String, RelationshipInstDataDefinition> relation = iterator.next();
+ RelationshipInstDataDefinition relationToDelete = relation.getValue();
+ if (relationToDelete.getFromId().equals(ciToRemove) || relationToDelete.getToId().equals(ciToRemove)) {
+ iterator.remove();
+ if (relationToDelete.getFromId().equals(ciToRemove)) {
+ updateCalculatedRequirementsAfterDeleteRelation(calculatedRequirement, fullfilledRequirement, ciToRemove, relationToDelete);
+ updateCalculatedCapabiltyAfterDeleteRelation(calculatedCapabilty, fullFilledCapabilty, relationToDelete.getToId(), relationToDelete);
+ }
+ if (relationToDelete.getToId().equals(ciToRemove)) {
+ updateCalculatedRequirementsAfterDeleteRelation(calculatedRequirement, fullfilledRequirement, relationToDelete.getFromId(), relationToDelete);
+ updateCalculatedCapabiltyAfterDeleteRelation(calculatedCapabilty, fullFilledCapabilty, ciToRemove, relationToDelete);
+ }
+ }
+ }
+ }
+ }
+ return StorageOperationStatus.OK;
+ }
+
+ private StorageOperationStatus deleteComponentInstanceToscaDataFromContainerComponent(GraphVertex containerV, String componentInstanceId) {
+ StorageOperationStatus status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES, componentInstanceId);
+ if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to remove calculated capabilty for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status);
+ return status;
+ }
+ status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS, componentInstanceId);
+ if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to remove calculated requirement for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status);
+ return status;
+ }
+ status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.FULLFILLED_CAPABILITIES, VertexTypeEnum.FULLFILLED_CAPABILITIES, componentInstanceId);
+ if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to remove fullfilled capabilities for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status);
+ return status;
+ }
+ status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.FULLFILLED_REQUIREMENTS, VertexTypeEnum.FULLFILLED_REQUIREMENTS, componentInstanceId);
+ if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to remove fullfilled requirement for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status);
+ return status;
+ }
+ status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.INST_ATTRIBUTES, VertexTypeEnum.INST_ATTRIBUTES, componentInstanceId);
+ if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to remove fullfilled requirement for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status);
+ return status;
+ }
+ status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES, componentInstanceId);
+ if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to remove fullfilled requirement for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status);
+ return status;
+ }
+ status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, componentInstanceId);
+ if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to remove instance inputs for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status);
+ return status;
+ }
+ status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS, componentInstanceId);
+ if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to remove fullfilled requirement for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status);
+ return status;
+ }
+ status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS, VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS, componentInstanceId);
+ if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to remove instance artifacts for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status);
+ return status;
+ }
+ return StorageOperationStatus.OK;
+ }
+
+ private Either<GraphVertex, StorageOperationStatus> addComponentInstanceToscaDataToContainerComponent(ToscaElement originToscaElement, ComponentInstanceDataDefinition componentInstance, GraphVertex updatedContainerVertex, User user) {
+
+ Either<GraphVertex, StorageOperationStatus> result;
+ StorageOperationStatus status;
+ if (originToscaElement.getToscaType() == ToscaElementTypeEnum.NodeType) {
+ status = addComponentInstanceToscaDataToNodeTypeContainer((NodeType) originToscaElement, componentInstance, updatedContainerVertex, user, HEAT_VF_ENV_NAME);
+ } else {
+ status = addComponentInstanceToscaDataToTopologyTemplateContainer((TopologyTemplate) originToscaElement, componentInstance, updatedContainerVertex);
+ }
+ if (status == StorageOperationStatus.OK) {
+ result = Either.left(updatedContainerVertex);
+ } else {
+ result = Either.right(status);
+ }
+ return result;
+ }
+
+ private StorageOperationStatus addComponentInstanceToscaDataToTopologyTemplateContainer(TopologyTemplate originTopologyTemplate, ComponentInstanceDataDefinition componentInstance, GraphVertex updatedContainerVertex) {
+
+ StorageOperationStatus status;
+
+ status = addCalculatedCapReqFromTopologyTemplate(originTopologyTemplate, componentInstance, updatedContainerVertex);
+
+ if (status != StorageOperationStatus.OK) {
+
+ return status;
+ }
+
+ MapPropertiesDataDefinition instProperties = new MapPropertiesDataDefinition(originTopologyTemplate.getInputs());
+
+ status = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, instProperties, componentInstance.getUniqueId());
+ if (status != StorageOperationStatus.OK) {
+ return status;
+ }
+
+ return status;
+ }
+
+ private StorageOperationStatus addCalculatedCapReqFromTopologyTemplate(TopologyTemplate originTopologyTemplate, ComponentInstanceDataDefinition componentInstance, GraphVertex updatedContainerVertex) {
+ Map<String, MapListCapabiltyDataDefinition> calculatedCapabilities = originTopologyTemplate.getCalculatedCapabilities();
+
+ if (calculatedCapabilities != null) {
+ MapListCapabiltyDataDefinition allCalculatedCap = new MapListCapabiltyDataDefinition();
+ calculatedCapabilities.entrySet().forEach(enntryPerInstance -> {
+ Map<String, ListCapabilityDataDefinition> mapByType = enntryPerInstance.getValue().getMapToscaDataDefinition();
+ mapByType.entrySet().forEach(entryPerType -> {
+ entryPerType.getValue().getListToscaDataDefinition().forEach(cap -> {
+ cap.addToPath(componentInstance.getUniqueId());
+ allCalculatedCap.add(entryPerType.getKey(), cap);
+ });
+ });
+ });
+
+ StorageOperationStatus calculatedResult = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES, allCalculatedCap,
+ componentInstance.getUniqueId());
+
+ if (calculatedResult != StorageOperationStatus.OK) {
+ return calculatedResult;
+ }
+ MapListCapabiltyDataDefinition fullCalculatedCap = new MapListCapabiltyDataDefinition();
+ calculatedResult = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.FULLFILLED_CAPABILITIES, VertexTypeEnum.FULLFILLED_CAPABILITIES, fullCalculatedCap, componentInstance.getUniqueId());
+
+ if (calculatedResult != StorageOperationStatus.OK) {
+ return calculatedResult;
+ }
+ }
+ Map<String, MapListRequirementDataDefinition> calculatedRequirements = originTopologyTemplate.getCalculatedRequirements();
+ if (calculatedRequirements != null) {
+
+ MapListRequirementDataDefinition allCalculatedReq = new MapListRequirementDataDefinition();
+ calculatedRequirements.entrySet().forEach(enntryPerInstance -> {
+ Map<String, ListRequirementDataDefinition> mapByType = enntryPerInstance.getValue().getMapToscaDataDefinition();
+ mapByType.entrySet().forEach(entryPerType -> {
+ entryPerType.getValue().getListToscaDataDefinition().forEach(req -> {
+ req.addToPath(componentInstance.getUniqueId());
+ allCalculatedReq.add(entryPerType.getKey(), req);
+ });
+ });
+ });
+
+ StorageOperationStatus calculatedResult = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS, allCalculatedReq,
+ componentInstance.getUniqueId());
+ if (calculatedResult != StorageOperationStatus.OK) {
+ return calculatedResult;
+ }
+ MapListRequirementDataDefinition fullCalculatedReq = new MapListRequirementDataDefinition();
+ calculatedResult = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.FULLFILLED_REQUIREMENTS, VertexTypeEnum.FULLFILLED_REQUIREMENTS, fullCalculatedReq, componentInstance.getUniqueId());
+ if (calculatedResult != StorageOperationStatus.OK) {
+ return calculatedResult;
+ }
+ }
+
+ Map<String, MapCapabiltyProperty> calculatedCapabilitiesProperties = originTopologyTemplate.getCalculatedCapabilitiesProperties();
+ Map<String, MapPropertiesDataDefinition> updateKeyMap = new HashMap<>();
+
+ if (calculatedCapabilitiesProperties != null && !calculatedCapabilitiesProperties.isEmpty()) {
+ for (MapCapabiltyProperty map : calculatedCapabilitiesProperties.values()) {
+ for (Entry<String, MapPropertiesDataDefinition> entry : map.getMapToscaDataDefinition().entrySet()) {
+ String newKey = new String(componentInstance.getUniqueId() + ModelConverter.CAP_PROP_DELIM + entry.getKey());
+ updateKeyMap.put(newKey, entry.getValue());
+ }
+ }
+ MapCapabiltyProperty mapCapabiltyProperty = new MapCapabiltyProperty(updateKeyMap);
+ StorageOperationStatus calculatedResult = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, mapCapabiltyProperty,
+ componentInstance.getUniqueId());
+ if (calculatedResult != StorageOperationStatus.OK) {
+ return calculatedResult;
+ }
+ }
+ return StorageOperationStatus.OK;
+ }
+
+ private StorageOperationStatus addComponentInstanceToscaDataToNodeTypeContainer(NodeType originNodeType, ComponentInstanceDataDefinition componentInstance, GraphVertex updatedContainerVertex, User user, String envType) {
+
+ MapPropertiesDataDefinition instProperties = new MapPropertiesDataDefinition(originNodeType.getProperties());
+
+ StorageOperationStatus status = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES, instProperties, componentInstance.getUniqueId());
+ if (status != StorageOperationStatus.OK) {
+ return status;
+ }
+
+ MapAttributesDataDefinition instAttributes = new MapAttributesDataDefinition(originNodeType.getAttributes());
+
+ status = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.INST_ATTRIBUTES, VertexTypeEnum.INST_ATTRIBUTES, instAttributes, componentInstance.getUniqueId());
+
+ if (status != StorageOperationStatus.OK) {
+ return status;
+ }
+ status = addInstanceDeploymentArtifacts(originNodeType, componentInstance, updatedContainerVertex, user, envType);
+ if (status != StorageOperationStatus.OK) {
+ return status;
+ }
+ return addCalculatedCapReqFromNodeType(originNodeType, componentInstance, updatedContainerVertex);
+
+ }
+
+ private StorageOperationStatus addInstanceDeploymentArtifacts(ToscaElement originNodeType, ComponentInstanceDataDefinition componentInstance, GraphVertex updatedContainerVertex, User user, String envType) {
+ Map<String, ArtifactDataDefinition> deploymentArtifacts = originNodeType.getDeploymentArtifacts();
+ MapArtifactDataDefinition instArtifacts = prepareInstDeploymentArtifactPerInstance(deploymentArtifacts, componentInstance.getUniqueId(), user, envType);
+ if (instArtifacts != null) {
+ StorageOperationStatus calculatedResult = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS, VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS, instArtifacts,
+ componentInstance.getUniqueId());
+
+ if (calculatedResult != StorageOperationStatus.OK) {
+ return calculatedResult;
+ }
+ }
+ return StorageOperationStatus.OK;
+ }
+
+ public MapArtifactDataDefinition prepareInstDeploymentArtifactPerInstance(Map<String, ArtifactDataDefinition> deploymentArtifacts, String componentInstanceId, User user, String envType) {
+ if (deploymentArtifacts != null && envType.equals(HEAT_VF_ENV_NAME)) {
+ Map<String, ArtifactDataDefinition> instDeploymentArtifacts = new HashMap<>();
+ deploymentArtifacts.entrySet().forEach(e -> {
+ ArtifactDataDefinition artifact = e.getValue();
+ String type = artifact.getArtifactType();
+ if (!(type.equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType()))) {
+ instDeploymentArtifacts.put(e.getKey(), artifact);
+ ArtifactDataDefinition artifactEnv = createArtifactPlaceHolderInfo(artifact, componentInstanceId, user, envType);
+ instDeploymentArtifacts.put(artifactEnv.getArtifactLabel(), artifactEnv);
+ }
+ });
+
+ MapArtifactDataDefinition instArtifacts = new MapArtifactDataDefinition(instDeploymentArtifacts);
+ return instArtifacts;
+ }
+ return null;
+ }
+
+ @SuppressWarnings({ "unchecked" })
+ private ArtifactDataDefinition createArtifactPlaceHolderInfo(ArtifactDataDefinition artifactHeat, String componentId, User user, String heatEnvType) {
+ Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getDeploymentResourceInstanceArtifacts();
+ if (deploymentResourceArtifacts == null) {
+ logger.debug("no deployment artifacts are configured for generated artifacts");
+ return null;
+ }
+ Map<String, Object> placeHolderData = (Map<String, Object>) deploymentResourceArtifacts.get(heatEnvType);
+ if (placeHolderData == null) {
+ logger.debug("no env type {} are configured for generated artifacts", heatEnvType);
+ return null;
+ }
+
+ String envLabel = (artifactHeat.getArtifactLabel() + HEAT_ENV_SUFFIX).toLowerCase();
+
+ ArtifactDataDefinition artifactInfo = new ArtifactDataDefinition();
+
+ String artifactName = (String) placeHolderData.get(ARTIFACT_PLACEHOLDER_DISPLAY_NAME);
+ String artifactType = (String) placeHolderData.get(ARTIFACT_PLACEHOLDER_TYPE);
+ String artifactDescription = (String) placeHolderData.get(ARTIFACT_PLACEHOLDER_DESCRIPTION);
+
+ artifactInfo.setArtifactDisplayName(artifactName);
+ artifactInfo.setArtifactLabel(envLabel);
+ artifactInfo.setArtifactType(artifactType);
+ artifactInfo.setDescription(artifactDescription);
+ artifactInfo.setArtifactGroupType(artifactHeat.getArtifactGroupType());
+ setDefaultArtifactTimeout(artifactHeat.getArtifactGroupType(), artifactInfo);
+ artifactInfo.setGeneratedFromId(artifactHeat.getUniqueId());
+ // clone heat parameters in case of heat env only not VF heat env
+ if (heatEnvType.equals(HEAT_ENV_NAME)) {
+ artifactInfo.setHeatParameters(artifactHeat.getHeatParameters());
+ }
+ setArtifactPlaceholderCommonFields(componentId, user, artifactInfo);
+
+ return artifactInfo;
+ }
+
+ public void setDefaultArtifactTimeout(ArtifactGroupTypeEnum groupType, ArtifactDataDefinition artifactInfo) {
+ if (groupType.equals(ArtifactGroupTypeEnum.DEPLOYMENT)) {
+ artifactInfo.setTimeout(defaultHeatTimeout);
+ } else {
+ artifactInfo.setTimeout(NON_HEAT_TIMEOUT);
+ }
+ }
+
+ private void setArtifactPlaceholderCommonFields(String resourceId, User user, ArtifactDataDefinition artifactInfo) {
+ String uniqueId = null;
+
+ if (resourceId != null) {
+ uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId.toLowerCase(), artifactInfo.getArtifactLabel().toLowerCase());
+ artifactInfo.setUniqueId(uniqueId);
+ }
+ artifactInfo.setUserIdCreator(user.getUserId());
+ String fullName = user.getFullName();
+ artifactInfo.setUpdaterFullName(fullName);
+
+ long time = System.currentTimeMillis();
+
+ artifactInfo.setCreatorFullName(fullName);
+ artifactInfo.setCreationDate(time);
+
+ artifactInfo.setLastUpdateDate(time);
+ artifactInfo.setUserIdLastUpdater(user.getUserId());
+
+ artifactInfo.setMandatory(true);
+ }
+
+ /**
+ *
+ * @param originNodeType
+ * @param componentInstance
+ * @param updatedContainerVertex
+ * @return
+ */
+ private StorageOperationStatus addCalculatedCapReqFromNodeType(NodeType originNodeType, ComponentInstanceDataDefinition componentInstance, GraphVertex updatedContainerVertex) {
+
+ Map<String, ListCapabilityDataDefinition> capabilities = originNodeType.getCapabilties();
+ MapListCapabiltyDataDefinition allCalculatedCap = prepareCalculatedCapabiltyForNodeType(capabilities, componentInstance);
+ StorageOperationStatus calculatedResult;
+ if (allCalculatedCap != null) {
+ calculatedResult = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES, allCalculatedCap, componentInstance.getUniqueId());
+
+ if (calculatedResult != StorageOperationStatus.OK) {
+ return calculatedResult;
+ }
+ }
+ Map<String, MapPropertiesDataDefinition> capabiltiesProperties = originNodeType.getCapabiltiesProperties();
+ if (capabiltiesProperties != null) {
+ Map<String, MapPropertiesDataDefinition> updateKeyMap = capabiltiesProperties.entrySet().stream().collect(Collectors.toMap(e -> createCapPropertyKey(e.getKey(), componentInstance.getUniqueId()), e -> e.getValue()));
+ MapCapabiltyProperty mapCapabiltyProperty = new MapCapabiltyProperty(updateKeyMap);
+ calculatedResult = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, mapCapabiltyProperty, componentInstance.getUniqueId());
+ if (calculatedResult != StorageOperationStatus.OK) {
+ return calculatedResult;
+ }
+ }
+
+ MapListCapabiltyDataDefinition fullCalculatedCap = new MapListCapabiltyDataDefinition();
+ calculatedResult = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.FULLFILLED_CAPABILITIES, VertexTypeEnum.FULLFILLED_CAPABILITIES, fullCalculatedCap, componentInstance.getUniqueId());
+
+ if (calculatedResult != StorageOperationStatus.OK) {
+ return calculatedResult;
+ }
+
+ Map<String, ListRequirementDataDefinition> requirements = originNodeType.getRequirements();
+
+ MapListRequirementDataDefinition allCalculatedReq = prepareCalculatedRequirementForNodeType(requirements, componentInstance);
+
+ StorageOperationStatus status;
+ if (allCalculatedReq != null) {
+ status = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS, allCalculatedReq, componentInstance.getUniqueId());
+ if (status != StorageOperationStatus.OK) {
+ return status;
+ }
+ }
+ MapListRequirementDataDefinition fullCalculatedReq = new MapListRequirementDataDefinition();
+ status = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.FULLFILLED_REQUIREMENTS, VertexTypeEnum.FULLFILLED_REQUIREMENTS, fullCalculatedReq, componentInstance.getUniqueId());
+ return StorageOperationStatus.OK;
+
+ }
+
+ public static String createCapPropertyKey(String key, String instanceId) {
+ StringBuffer sb = new StringBuffer(instanceId);
+ sb.append(ModelConverter.CAP_PROP_DELIM).append(instanceId).append(ModelConverter.CAP_PROP_DELIM).append(key);
+ return sb.toString();
+ }
+
+ public MapListCapabiltyDataDefinition prepareCalculatedCapabiltyForNodeType(Map<String, ListCapabilityDataDefinition> capabilities, ComponentInstanceDataDefinition componentInstance) {
+ if (capabilities != null) {
+ MapListCapabiltyDataDefinition allCalculatedCap = new MapListCapabiltyDataDefinition();
+
+ capabilities.entrySet().forEach(e -> {
+ List<CapabilityDataDefinition> listCapabilities = e.getValue().getListToscaDataDefinition();
+ listCapabilities.forEach(cap -> {
+ cap.setSource(componentInstance.getComponentUid());
+ cap.addToPath(componentInstance.getUniqueId());
+ cap.setOwnerId(componentInstance.getUniqueId());
+ cap.setOwnerName(componentInstance.getName());
+ cap.setLeftOccurrences(cap.getMaxOccurrences());
+ allCalculatedCap.add(e.getKey(), cap);
+ });
+ });
+ return allCalculatedCap;
+ }
+ return null;
+ }
+
+ public MapListRequirementDataDefinition prepareCalculatedRequirementForNodeType(Map<String, ListRequirementDataDefinition> requirements, ComponentInstanceDataDefinition componentInstance) {
+ if (requirements != null) {
+ MapListRequirementDataDefinition allCalculatedReq = new MapListRequirementDataDefinition();
+
+ requirements.entrySet().forEach(e -> {
+ List<RequirementDataDefinition> listCapabilities = e.getValue().getListToscaDataDefinition();
+ listCapabilities.forEach(req -> {
+ req.setSource(componentInstance.getComponentUid());
+ req.addToPath(componentInstance.getUniqueId());
+ req.setOwnerId(componentInstance.getUniqueId());
+ req.setOwnerName(componentInstance.getName());
+ req.setLeftOccurrences(req.getMaxOccurrences());
+ allCalculatedReq.add(e.getKey(), req);
+ });
+ });
+ return allCalculatedReq;
+ }
+ return null;
+ }
+
+ public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List<GroupDefinition> groups, Map<String, List<ArtifactDefinition>> groupInstancesArtifacts) {
+
+ StorageOperationStatus result = null;
+ Map<String, GroupInstanceDataDefinition> groupInstanceToCreate = new HashMap<>();
+ if (groupInstancesArtifacts != null && CollectionUtils.isNotEmpty(groups)) {
+ for (Map.Entry<String, List<ArtifactDefinition>> groupArtifacts : groupInstancesArtifacts.entrySet()) {
+ Optional<GroupDefinition> groupOptional = groups.stream().filter(g -> g.getUniqueId().equals(groupArtifacts.getKey())).findFirst();
+ if (groupOptional.isPresent()) {
+ GroupInstanceDataDefinition groupInstance = buildGroupInstanceDataDefinition(groupOptional.get(), componentInstance);
+ groupInstance.setGroupInstanceArtifacts(groupArtifacts.getValue().stream().map(a -> a.getUniqueId()).collect(Collectors.toList()));
+ groupInstance.setGroupInstanceArtifactsUuid(groupArtifacts.getValue().stream().map(a -> a.getArtifactUUID()).collect(Collectors.toList()));
+ groupInstanceToCreate.put(groupInstance.getName(), groupInstance);
+ }
+ }
+ }
+ if (MapUtils.isNotEmpty(groupInstanceToCreate)) {
+ result = addToscaDataDeepElementsBlockToToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS, new MapDataDefinition<>(groupInstanceToCreate), componentInstance.getUniqueId());
+ }
+ if (result == null) {
+ result = StorageOperationStatus.OK;
+ }
+ return result;
+ }
+
+ private GroupInstanceDataDefinition buildGroupInstanceDataDefinition(GroupDefinition group, ComponentInstance componentInstance) {
+
+ String componentInstanceName = componentInstance.getName();
+ Long creationDate = System.currentTimeMillis();
+ GroupInstanceDataDefinition groupInstance = new GroupInstanceDataDefinition();
+ String groupUid = group.getUniqueId();
+
+ groupInstance.setGroupUid(groupUid);
+ groupInstance.setType(group.getType());
+ groupInstance.setCustomizationUUID(generateCustomizationUUID());
+ groupInstance.setCreationTime(creationDate);
+ groupInstance.setModificationTime(creationDate);
+ groupInstance.setName(buildGroupInstanceName(componentInstanceName, group.getName()));
+ groupInstance.setGroupName(groupInstance.getName());
+ groupInstance.setNormalizedName(ValidationUtils.normalizeComponentInstanceName(groupInstance.getName()));
+ groupInstance.setUniqueId(UniqueIdBuilder.buildResourceInstanceUniuqeId(componentInstance.getUniqueId(), groupUid, groupInstance.getNormalizedName()));
+ groupInstance.setArtifacts(group.getArtifacts());
+ groupInstance.setArtifactsUuid(group.getArtifactsUuid());
+ groupInstance.setProperties(group.getProperties());
+ groupInstance.setInvariantUUID(group.getInvariantUUID());
+ groupInstance.setGroupUUID(group.getGroupUUID());
+ groupInstance.setVersion(group.getVersion());
+
+ return groupInstance;
+ }
+
+ private ComponentInstanceDataDefinition buildComponentInstanceDataDefinition(ComponentInstance resourceInstance, String containerComponentId, String instanceNewName, boolean generateUid, ToscaElement originToscaElement) {
+ String ciOriginComponentUid = resourceInstance.getComponentUid();
+
+ if (!ValidationUtils.validateStringNotEmpty(resourceInstance.getCustomizationUUID())) {
+ resourceInstance.setCustomizationUUID(generateCustomizationUUID());
+ }
+ ComponentInstanceDataDefinition dataDefinition = new ComponentInstanceDataDefinition(resourceInstance);
+
+ Long creationDate = resourceInstance.getCreationTime();
+ if (creationDate == null) {
+ creationDate = System.currentTimeMillis();
+ }
+ dataDefinition.setComponentUid(ciOriginComponentUid);
+ dataDefinition.setCreationTime(creationDate);
+ dataDefinition.setModificationTime(creationDate);
+ if (StringUtils.isNotEmpty(instanceNewName)) {
+ dataDefinition.setName(instanceNewName);
+ resourceInstance.setName(instanceNewName);
+ }
+ if (StringUtils.isNotEmpty(dataDefinition.getName()))
+ dataDefinition.setNormalizedName(ValidationUtils.normalizeComponentInstanceName(dataDefinition.getName()));
+ dataDefinition.setIcon(resourceInstance.getIcon());
+ if (generateUid) {
+ dataDefinition.setUniqueId(UniqueIdBuilder.buildResourceInstanceUniuqeId(containerComponentId, ciOriginComponentUid, dataDefinition.getNormalizedName()));
+ resourceInstance.setUniqueId(dataDefinition.getUniqueId());
+ }
+ if (StringUtils.isEmpty(dataDefinition.getComponentVersion()) && originToscaElement != null)
+ dataDefinition.setComponentVersion((String) originToscaElement.getMetadataValue(JsonPresentationFields.VERSION));
+ if (StringUtils.isEmpty(dataDefinition.getComponentName()) && originToscaElement != null)
+ dataDefinition.setComponentName((String) originToscaElement.getMetadataValue(JsonPresentationFields.NAME));
+ if (StringUtils.isEmpty(dataDefinition.getToscaComponentName()) && originToscaElement != null)
+ 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 VL:
+ originType = OriginTypeEnum.VL;
+ break;
+ case CP:
+ originType = OriginTypeEnum.CP;
+ break;
+ default:
+ break;
+ }
+ dataDefinition.setOriginType(originType);
+ }
+ return dataDefinition;
+ }
+
+ private Boolean isUniqueInstanceName(TopologyTemplate container, String instanceName) {
+ Boolean isUniqueName = true;
+ try {
+ isUniqueName = !container.getComponentInstances().values().stream().filter(ci -> ci.getName() != null && ci.getName().equals(instanceName)).findAny().isPresent();
+
+ } catch (Exception e) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during fetching component instance with name {} from component container {}. {} ", instanceName, container.getName(), e.getMessage());
+ }
+ return isUniqueName;
+ }
+
+ private String buildGroupInstanceName(String instanceName, String groupName) {
+ int groupNameIndex = groupName.indexOf("..");
+ //turn group name from VFName..heatfile..module-n to VFiName..heatfile..module-n
+ return ValidationUtils.normaliseComponentName(instanceName) + groupName.substring(groupNameIndex);
+ }
+
+ private String generateCustomizationUUID() {
+ return UUID.randomUUID().toString();
+ }
+
+ private String buildComponentInstanceName(String instanceSuffixNumber, String instanceName) {
+ return instanceName + " " + (instanceSuffixNumber == null ? 0 : instanceSuffixNumber);
+ }
+
+ public Either<RequirementCapabilityRelDef, StorageOperationStatus> associateResourceInstances(String componentId, RequirementCapabilityRelDef relation) {
+ List<RequirementCapabilityRelDef> relations = new ArrayList<>();
+ relations.add(relation);
+ Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> associateResourceInstances = associateResourceInstances(componentId, relations);
+ if (associateResourceInstances.isRight()) {
+ return Either.right(associateResourceInstances.right().value());
+ }
+ return Either.left(associateResourceInstances.left().value().get(0));
+ }
+
+ @SuppressWarnings({ "unchecked" })
+ public Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> associateResourceInstances(String componentId, List<RequirementCapabilityRelDef> relations) {
+
+ Either<GraphVertex, TitanOperationStatus> containerVEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll);
+ if (containerVEither.isRight()) {
+ TitanOperationStatus error = containerVEither.right().value();
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch container vertex {} error {}", componentId, error);
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(error));
+ }
+ GraphVertex containerV = containerVEither.left().value();
+ List<RequirementAndRelationshipPair> relationshipsResult = new ArrayList<RequirementAndRelationshipPair>();
+ Either<Pair<GraphVertex, Map<String, MapListCapabiltyDataDefinition>>, StorageOperationStatus> capResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.CALCULATED_CAPABILITIES);
+ if (capResult.isRight()) {
+ return Either.right(capResult.right().value());
+
+ }
+ Map<String, MapListCapabiltyDataDefinition> calculatedCapabilty = capResult.left().value().getRight();
+
+ Either<Pair<GraphVertex, Map<String, MapListCapabiltyDataDefinition>>, StorageOperationStatus> capFullResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.FULLFILLED_CAPABILITIES);
+ if (capResult.isRight()) {
+ return Either.right(capResult.right().value());
+
+ }
+ Map<String, MapListCapabiltyDataDefinition> fullFilledCapabilty = capFullResult.left().value().getRight();
+
+ Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqResult = fetchContainerCalculatedRequirement(containerV, EdgeLabelEnum.CALCULATED_REQUIREMENTS);
+ if (reqResult.isRight()) {
+ return Either.right(reqResult.right().value());
+ }
+ Map<String, MapListRequirementDataDefinition> calculatedRequirement = reqResult.left().value().getRight();
+
+ Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqFullResult = fetchContainerCalculatedRequirement(containerV, EdgeLabelEnum.FULLFILLED_REQUIREMENTS);
+ if (reqResult.isRight()) {
+ return Either.right(reqResult.right().value());
+ }
+ Map<String, MapListRequirementDataDefinition> fullfilledRequirement = reqFullResult.left().value().getRight();
+
+ Map<String, CompositionDataDefinition> jsonComposition = (Map<String, CompositionDataDefinition>) containerV.getJson();
+ CompositionDataDefinition compositionDataDefinition = jsonComposition.get(JsonConstantKeysEnum.COMPOSITION.getValue());
+
+ StorageOperationStatus status;
+ List<RequirementCapabilityRelDef> relationsList = new ArrayList<>();
+ for (RequirementCapabilityRelDef relation : relations) {
+
+ String fromNode = relation.getFromNode();
+ String toNode = relation.getToNode();
+ List<RequirementAndRelationshipPair> relationships = relation.getRelationships();
+ if (relationships == null || relationships.isEmpty()) {
+ BeEcompErrorManager.getInstance().logBeFailedAddingResourceInstanceError("AssociateResourceInstances - missing relationship", fromNode, componentId);
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No requirement definition sent in order to set the relation between {} to {}", fromNode, toNode);
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT));
+ }
+
+ for (RequirementAndRelationshipPair immutablePair : relationships) {
+ String requirement = immutablePair.getRequirement();
+
+ Either<RelationshipInstDataDefinition, StorageOperationStatus> associateRes = connectInstancesInContainer(fromNode, toNode, immutablePair, calculatedCapabilty, calculatedRequirement, fullFilledCapabilty, fullfilledRequirement,
+ compositionDataDefinition, containerV.getUniqueId());
+
+ if (associateRes.isRight()) {
+ status = associateRes.right().value();
+ BeEcompErrorManager.getInstance().logBeFailedAddingResourceInstanceError("AssociateResourceInstances - missing relationship", fromNode, componentId);
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to associate resource instance {} to resource instance {}. status is {}", fromNode, toNode, status);
+ return Either.right(status);
+ }
+
+ RelationshipInstDataDefinition relationshipInstData = associateRes.left().value();
+ RelationshipImpl relationshipImplResult = new RelationshipImpl();
+ relationshipImplResult.setType(relationshipInstData.getType());
+ RequirementAndRelationshipPair requirementAndRelationshipPair = new RequirementAndRelationshipPair(requirement, relationshipImplResult);
+ requirementAndRelationshipPair.setCapability(immutablePair.getCapability());
+ requirementAndRelationshipPair.setCapabilityOwnerId(relationshipInstData.getCapabilityOwnerId());
+ requirementAndRelationshipPair.setRequirementOwnerId(relationshipInstData.getRequirementOwnerId());
+ requirementAndRelationshipPair.setCapabilityUid(immutablePair.getCapabilityUid());
+ requirementAndRelationshipPair.setRequirementUid(immutablePair.getRequirementUid());
+ relationshipsResult.add(requirementAndRelationshipPair);
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "update customization UUID for from CI {} and to CI {}", relation.getFromNode(), relation.getToNode());
+ status = updateCustomizationUUID(relation.getFromNode(), compositionDataDefinition);
+ if (status != StorageOperationStatus.OK) {
+ return Either.right(status);
+ }
+ status = updateCustomizationUUID(relation.getToNode(), compositionDataDefinition);
+ if (status != StorageOperationStatus.OK) {
+ return Either.right(status);
+ }
+ }
+ RequirementCapabilityRelDef capabilityRelDef = new RequirementCapabilityRelDef();
+ capabilityRelDef.setFromNode(fromNode);
+ capabilityRelDef.setToNode(toNode);
+ capabilityRelDef.setRelationships(relationshipsResult);
+ relationsList.add(capabilityRelDef);
+ }
+ // update metadata of container and composition json
+ status = updateAllAndCalculatedCapReqOnGraph(componentId, containerV, capResult, capFullResult, reqResult, reqFullResult);
+ if (status != StorageOperationStatus.OK) {
+ return Either.right(status);
+ }
+
+ return Either.left(relationsList);
+ }
+
+ private StorageOperationStatus updateAllAndCalculatedCapReqOnGraph(String componentId, GraphVertex containerV, Either<Pair<GraphVertex, Map<String, MapListCapabiltyDataDefinition>>, StorageOperationStatus> capResult,
+ Either<Pair<GraphVertex, Map<String, MapListCapabiltyDataDefinition>>, StorageOperationStatus> capFullResult, Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqResult,
+ Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqFullResult) {
+ containerV.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis());
+ Either<GraphVertex, TitanOperationStatus> updateElement = titanDao.updateVertex(containerV);
+ if (updateElement.isRight()) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update topology template {} with new relations error {}. ", componentId, updateElement.right().value());
+ return DaoStatusConverter.convertTitanStatusToStorageStatus(updateElement.right().value());
+ }
+ // update cap/req jsons, fullfilled cap/req jsons!!!!!
+ Either<GraphVertex, TitanOperationStatus> status;
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Update calculated capabilty for container {}", containerV.getUniqueId());
+ status = updateOrCopyOnUpdate(capResult.left().value().getLeft(), containerV, EdgeLabelEnum.CALCULATED_CAPABILITIES);
+ if (status.isRight()) {
+ TitanOperationStatus error = status.right().value();
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update calculated capabilty for container {} error {}", containerV.getUniqueId(), error);
+ return DaoStatusConverter.convertTitanStatusToStorageStatus(error);
+ }
+
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Update calculated requirement for container {}", containerV.getUniqueId());
+ status = updateOrCopyOnUpdate(reqResult.left().value().getLeft(), containerV, EdgeLabelEnum.CALCULATED_REQUIREMENTS);
+ if (status.isRight()) {
+ TitanOperationStatus error = status.right().value();
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update calculated requiremnt for container {} error {}", containerV.getUniqueId(), error);
+ return DaoStatusConverter.convertTitanStatusToStorageStatus(error);
+ }
+
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Update fullfilled capabilty for container {}", containerV.getUniqueId());
+ status = updateOrCopyOnUpdate(capFullResult.left().value().getLeft(), containerV, EdgeLabelEnum.FULLFILLED_CAPABILITIES);
+ if (status.isRight()) {
+ TitanOperationStatus error = status.right().value();
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update fullfilled capabilty for container {} error {}", containerV.getUniqueId(), error);
+ return DaoStatusConverter.convertTitanStatusToStorageStatus(error);
+ }
+
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Update fullfilled requirement for container {}", containerV.getUniqueId());
+ status = updateOrCopyOnUpdate(reqFullResult.left().value().getLeft(), containerV, EdgeLabelEnum.FULLFILLED_REQUIREMENTS);
+ if (status.isRight()) {
+ TitanOperationStatus error = status.right().value();
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update fullfilled requirement for container {} error {}", containerV.getUniqueId(), error);
+ return DaoStatusConverter.convertTitanStatusToStorageStatus(error);
+ }
+ return StorageOperationStatus.OK;
+ }
+
+ @SuppressWarnings({ "unchecked" })
+ public Either<RequirementCapabilityRelDef, StorageOperationStatus> dissociateResourceInstances(String componentId, RequirementCapabilityRelDef requirementDef) {
+ if (requirementDef.getRelationships() == null) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No relation pair in request [ {} ]", requirementDef);
+ return Either.right(StorageOperationStatus.BAD_REQUEST);
+ }
+
+ String fromResInstanceUid = requirementDef.getFromNode();
+ String toResInstanceUid = requirementDef.getToNode();
+
+ Either<GraphVertex, TitanOperationStatus> containerVEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll);
+ if (containerVEither.isRight()) {
+ TitanOperationStatus error = containerVEither.right().value();
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch container vertex {} error {}", componentId, error);
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(error));
+ }
+ GraphVertex containerV = containerVEither.left().value();
+
+ // DE191707 - validatations
+ Map<String, CompositionDataDefinition> jsonComposition = (Map<String, CompositionDataDefinition>) containerV.getJson();
+ CompositionDataDefinition compositionDataDefinition = jsonComposition.get(JsonConstantKeysEnum.COMPOSITION.getValue());
+ Map<String, ComponentInstanceDataDefinition> componentInstances = compositionDataDefinition.getComponentInstances();
+ ComponentInstanceDataDefinition ciFrom = componentInstances.get(fromResInstanceUid);
+ if (ciFrom == null) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "FROM instance {} isn't under container {}", fromResInstanceUid, componentId);
+ return Either.right(StorageOperationStatus.NOT_FOUND);
+
+ }
+ ComponentInstanceDataDefinition ciTo = componentInstances.get(toResInstanceUid);
+ if (ciFrom == ciTo) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "TO instance {} isn't under container {}", toResInstanceUid, componentId);
+ return Either.right(StorageOperationStatus.NOT_FOUND);
+
+ }
+ Map<String, RelationshipInstDataDefinition> relations = compositionDataDefinition.getRelations();
+
+ List<RequirementAndRelationshipPair> relationPairList = requirementDef.getRelationships();
+ Either<Pair<GraphVertex, Map<String, MapListCapabiltyDataDefinition>>, StorageOperationStatus> capResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.CALCULATED_CAPABILITIES);
+ if (capResult.isRight()) {
+ return Either.right(capResult.right().value());
+
+ }
+ Map<String, MapListCapabiltyDataDefinition> calculatedCapabilty = capResult.left().value().getRight();
+
+ Either<Pair<GraphVertex, Map<String, MapListCapabiltyDataDefinition>>, StorageOperationStatus> capFullResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.FULLFILLED_CAPABILITIES);
+ if (capResult.isRight()) {
+ return Either.right(capResult.right().value());
+
+ }
+ Map<String, MapListCapabiltyDataDefinition> fullFilledCapabilty = capFullResult.left().value().getRight();
+
+ Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqResult = fetchContainerCalculatedRequirement(containerV, EdgeLabelEnum.CALCULATED_REQUIREMENTS);
+ if (reqResult.isRight()) {
+ return Either.right(reqResult.right().value());
+ }
+ Map<String, MapListRequirementDataDefinition> calculatedRequirement = reqResult.left().value().getRight();
+
+ Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqFullResult = fetchContainerCalculatedRequirement(containerV, EdgeLabelEnum.FULLFILLED_REQUIREMENTS);
+ if (reqResult.isRight()) {
+ return Either.right(reqResult.right().value());
+ }
+ Map<String, MapListRequirementDataDefinition> fullfilledRequirement = reqFullResult.left().value().getRight();
+
+ for (RequirementAndRelationshipPair relationPair : relationPairList) {
+ Iterator<Entry<String, RelationshipInstDataDefinition>> iterator = relations.entrySet().iterator();
+ boolean isDeleted = false;
+ while (iterator.hasNext()) {
+ Entry<String, RelationshipInstDataDefinition> entryInJson = iterator.next();
+ RelationshipInstDataDefinition relationInJson = entryInJson.getValue();
+ if (relationInJson.getFromId().equals(fromResInstanceUid) && relationInJson.getToId().equals(toResInstanceUid)) {
+ if (relationPair.equalsTo(relationInJson)) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Remove relation from {} to {} capabilty {} capOwnerId {} reqOwnerId {} ", toResInstanceUid, componentId, relationInJson.getType(),
+ relationInJson.getCapabilityOwnerId(), relationInJson.getRequirementOwnerId());
+ iterator.remove();
+
+ // update calculated cap/req
+ StorageOperationStatus status = updateCalculatedCapabiltyAfterDeleteRelation(calculatedCapabilty, fullFilledCapabilty, toResInstanceUid, relationInJson);
+ if (status != StorageOperationStatus.OK) {
+ return Either.right(status);
+ }
+ status = updateCalculatedRequirementsAfterDeleteRelation(calculatedRequirement, fullfilledRequirement, fromResInstanceUid, relationInJson);
+ if (status != StorageOperationStatus.OK) {
+ return Either.right(status);
+ }
+ isDeleted = true;
+ }
+ }
+ }
+ if (isDeleted == false) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No relation to delete from {} to {} capabilty {} capOwnerId {} reqOwnerId {} ", toResInstanceUid, componentId, relationPair.getCapability(),
+ relationPair.getCapabilityOwnerId(), relationPair.getRequirementOwnerId());
+ return Either.right(StorageOperationStatus.NOT_FOUND);
+ }
+ }
+ StorageOperationStatus status = updateCustomizationUUID(fromResInstanceUid, compositionDataDefinition);
+ if (status != StorageOperationStatus.OK) {
+ return Either.right(status);
+ }
+ status = updateCustomizationUUID(toResInstanceUid, compositionDataDefinition);
+ if (status != StorageOperationStatus.OK) {
+ return Either.right(status);
+ }
+
+ // update jsons
+ // update metadata of container and composition json
+ status = updateAllAndCalculatedCapReqOnGraph(componentId, containerV, capResult, capFullResult, reqResult, reqFullResult);
+ if (status != StorageOperationStatus.OK) {
+ return Either.right(status);
+ }
+
+ return Either.left(requirementDef);
+ }
+
+ private StorageOperationStatus updateCalculatedRequirementsAfterDeleteRelation(Map<String, MapListRequirementDataDefinition> calculatedRequirement, Map<String, MapListRequirementDataDefinition> fullFilledRequirement, String fromResInstanceUid,
+ RelationshipInstDataDefinition relation) {
+ StorageOperationStatus status;
+ MapListRequirementDataDefinition reqByInstance = calculatedRequirement.get(fromResInstanceUid);
+ if (reqByInstance == null) {
+ // move from fullfilled
+ status = moveFromFullFilledRequirement(calculatedRequirement, fullFilledRequirement, fromResInstanceUid, relation);
+ } else {
+ ListRequirementDataDefinition reqByType = reqByInstance.findByKey(relation.getType());
+ if (reqByType == null) {
+ // move from fullfilled
+ status = moveFromFullFilledRequirement(calculatedRequirement, fullFilledRequirement, fromResInstanceUid, relation);
+ } else {
+ Optional<RequirementDataDefinition> requirementOptional = reqByType.getListToscaDataDefinition().stream()
+ .filter(cap -> cap.getOwnerId().equals(relation.getRequirementOwnerId()) && cap.getName().equals(relation.getRequirement()) && cap.getUniqueId().equals(relation.getRequirementId())).findFirst();
+
+ if (requirementOptional.isPresent()) {
+
+ RequirementDataDefinition requirement = requirementOptional.get();
+ String leftOccurrences = requirement.getLeftOccurrences();
+ if (leftOccurrences != null && !leftOccurrences.equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
+ Integer leftIntValue = Integer.parseInt(leftOccurrences);
+ ++leftIntValue;
+ requirement.setLeftOccurrences(String.valueOf(leftIntValue));
+ }
+ status = StorageOperationStatus.OK;
+ } else {
+ // move from fullfilled
+ status = moveFromFullFilledRequirement(calculatedRequirement, fullFilledRequirement, fromResInstanceUid, relation);
+ }
+ }
+ }
+ return status;
+ }
+
+ private StorageOperationStatus updateCalculatedCapabiltyAfterDeleteRelation(Map<String, MapListCapabiltyDataDefinition> calculatedCapabilty, Map<String, MapListCapabiltyDataDefinition> fullFilledCapabilty, String toResInstanceUid,
+ RelationshipInstDataDefinition relation) {
+ StorageOperationStatus status;
+ MapListCapabiltyDataDefinition capByInstance = calculatedCapabilty.get(toResInstanceUid);
+ if (capByInstance == null) {
+ // move from fullfilled
+ status = moveFromFullFilledCapabilty(calculatedCapabilty, fullFilledCapabilty, toResInstanceUid, relation);
+ } else {
+ ListCapabilityDataDefinition capByType = capByInstance.findByKey(relation.getType());
+ if (capByType == null) {
+ // move from fullfilled
+ status = moveFromFullFilledCapabilty(calculatedCapabilty, fullFilledCapabilty, toResInstanceUid, relation);
+ } else {
+ Optional<CapabilityDataDefinition> capabiltyOptional = capByType.getListToscaDataDefinition().stream()
+ .filter(cap -> cap.getOwnerId().equals(relation.getCapabilityOwnerId()) && cap.getUniqueId().equals(relation.getCapabiltyId())).findFirst();
+
+ if (capabiltyOptional.isPresent()) {
+
+ CapabilityDataDefinition capability = capabiltyOptional.get();
+ String leftOccurrences = capability.getLeftOccurrences();
+ if (leftOccurrences != null && !leftOccurrences.equals(CapabilityDataDefinition.MAX_OCCURRENCES)) {
+ Integer leftIntValue = Integer.parseInt(leftOccurrences);
+ ++leftIntValue;
+ capability.setLeftOccurrences(String.valueOf(leftIntValue));
+ }
+ status = StorageOperationStatus.OK;
+ } else {
+ // move from fullfilled
+ status = moveFromFullFilledCapabilty(calculatedCapabilty, fullFilledCapabilty, toResInstanceUid, relation);
+ }
+ }
+ }
+ return status;
+ }
+
+ private StorageOperationStatus moveFromFullFilledCapabilty(Map<String, MapListCapabiltyDataDefinition> calculatedCapabilty, Map<String, MapListCapabiltyDataDefinition> fullFilledCapabilty, String toResInstanceUid,
+ RelationshipInstDataDefinition relation) {
+ MapListCapabiltyDataDefinition capByInstance = fullFilledCapabilty.get(toResInstanceUid);
+ if (capByInstance == null) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No capabilty in fullfilled list for instance {} ", toResInstanceUid);
+ return StorageOperationStatus.GENERAL_ERROR;
+ }
+ ListCapabilityDataDefinition capByType = capByInstance.findByKey(relation.getType());
+ if (capByType == null) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No capabilty type {} in fullfilled list for instance {} ", relation.getType(), toResInstanceUid);
+ return StorageOperationStatus.GENERAL_ERROR;
+ }
+ Iterator<CapabilityDataDefinition> iterator = capByType.getListToscaDataDefinition().iterator();
+ boolean found = false;
+ while (iterator.hasNext()) {
+ CapabilityDataDefinition cap = iterator.next();
+ if (cap.getOwnerId().equals(relation.getCapabilityOwnerId()) && cap.getName().equals(relation.getRequirement()) && cap.getUniqueId().equals(relation.getCapabiltyId())) {
+ found = true;
+ iterator.remove();
+ // return to calculated list
+ String leftOccurrences = cap.getLeftOccurrences();
+ Integer leftIntValue = Integer.parseInt(leftOccurrences);
+ ++leftIntValue;
+ cap.setLeftOccurrences(String.valueOf(leftIntValue));
+
+ MapListCapabiltyDataDefinition mapListCapaDataDef = calculatedCapabilty.get(toResInstanceUid);
+ if (mapListCapaDataDef == null) {
+ mapListCapaDataDef = new MapListCapabiltyDataDefinition();
+ }
+ ListCapabilityDataDefinition findByKey = mapListCapaDataDef.findByKey(relation.getType());
+ if (findByKey == null) {
+ findByKey = new ListCapabilityDataDefinition();
+ mapListCapaDataDef.put(relation.getType(), findByKey);
+ }
+ findByKey.add(cap);
+ break;
+ }
+ }
+ if (found == false) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No capabilty type {} with ownerId {} in fullfilled list for instance {} ", relation.getType(), relation.getCapabilityOwnerId(), toResInstanceUid);
+ return StorageOperationStatus.GENERAL_ERROR;
+ }
+ return StorageOperationStatus.OK;
+ }
+
+ private StorageOperationStatus moveFromFullFilledRequirement(Map<String, MapListRequirementDataDefinition> calculatedRequirement, Map<String, MapListRequirementDataDefinition> fullFilledRequirement, String fromResInstanceUid,
+ RelationshipInstDataDefinition relation) {
+ MapListRequirementDataDefinition reqByInstance = fullFilledRequirement.get(fromResInstanceUid);
+ if (reqByInstance == null) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No requirement in fullfilled list for instance {} ", fromResInstanceUid);
+ return StorageOperationStatus.GENERAL_ERROR;
+ }
+ ListRequirementDataDefinition reqByType = reqByInstance.findByKey(relation.getType());
+ if (reqByType == null) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No requirement type {} in fullfilled list for instance {} ", relation.getType(), fromResInstanceUid);
+ return StorageOperationStatus.GENERAL_ERROR;
+ }
+ Iterator<RequirementDataDefinition> iterator = reqByType.getListToscaDataDefinition().iterator();
+ boolean found = false;
+ while (iterator.hasNext()) {
+ RequirementDataDefinition req = iterator.next();
+ if (req.getOwnerId().equals(relation.getRequirementOwnerId()) && req.getName().equals(relation.getRequirement()) && req.getUniqueId().equals(relation.getRequirementId())) {
+ found = true;
+ iterator.remove();
+ // return to calculated list
+ String leftOccurrences = req.getLeftOccurrences();
+ Integer leftIntValue = Integer.parseInt(leftOccurrences);
+ ++leftIntValue;
+ req.setLeftOccurrences(String.valueOf(leftIntValue));
+
+ MapListRequirementDataDefinition mapListReqDataDef = calculatedRequirement.get(fromResInstanceUid);
+ if (mapListReqDataDef == null) {
+ mapListReqDataDef = new MapListRequirementDataDefinition();
+ }
+ ListRequirementDataDefinition findByKey = mapListReqDataDef.findByKey(relation.getType());
+ if (findByKey == null) {
+ findByKey = new ListRequirementDataDefinition();
+ mapListReqDataDef.put(relation.getType(), findByKey);
+ }
+ findByKey.add(req);
+ break;
+ }
+ }
+ if (found == false) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No requirement type {} with ownerId {} in fullfilled list for instance {} ", relation.getType(), relation.getCapabilityOwnerId(), fromResInstanceUid);
+ return StorageOperationStatus.GENERAL_ERROR;
+ }
+ return StorageOperationStatus.OK;
+
+ }
+
+ public StorageOperationStatus updateCustomizationUUID(String componentInstanceId, CompositionDataDefinition compositionDataDefinition) {
+ ComponentInstanceDataDefinition componentInstance = compositionDataDefinition.getComponentInstances().get(componentInstanceId);
+
+ if (componentInstance == null) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch component instance by id {} from map of instances ", componentInstanceId);
+ return StorageOperationStatus.NOT_FOUND;
+ }
+ UUID uuid = UUID.randomUUID();
+ componentInstance.setCustomizationUUID(uuid.toString());
+
+ return StorageOperationStatus.OK;
+ }
+
+ public Either<RelationshipInstDataDefinition, StorageOperationStatus> connectInstancesInContainer(String fromResInstanceUid, String toResInstanceUid, RequirementAndRelationshipPair relationPair,
+ Map<String, MapListCapabiltyDataDefinition> calculatedCapabilty, Map<String, MapListRequirementDataDefinition> calculatedRequirement, Map<String, MapListCapabiltyDataDefinition> fullfilledCapabilty,
+ Map<String, MapListRequirementDataDefinition> fullfilledRequirement, CompositionDataDefinition compositionDataDefinition, String containerId) {
+ String requirement = relationPair.getRequirement();
+ Map<String, ComponentInstanceDataDefinition> componentInstances = compositionDataDefinition.getComponentInstances();
+
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Going to associate resource instance {} to resource instance {} under component {}. Requirement is {}.", fromResInstanceUid, toResInstanceUid, containerId, requirement);
+
+ ComponentInstanceDataDefinition fromResourceInstData = componentInstances.get(fromResInstanceUid);
+ if (fromResourceInstData == null) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to find from resource instance {}.", fromResInstanceUid);
+ return Either.right(StorageOperationStatus.NOT_FOUND);
+ }
+ ComponentInstanceDataDefinition toResourceInstData = componentInstances.get(toResInstanceUid);
+ if (toResourceInstData == null) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to find to resource instance {}.", toResInstanceUid);
+ return Either.right(StorageOperationStatus.NOT_FOUND);
+ }
+
+ Either<RelationshipInstDataDefinition, StorageOperationStatus> reqVsCap = connectRequirementVsCapability(fromResourceInstData, toResourceInstData, relationPair, calculatedCapabilty, calculatedRequirement, fullfilledCapabilty,
+ fullfilledRequirement, containerId);
+ if (reqVsCap.isRight()) {
+ StorageOperationStatus status = reqVsCap.right().value();
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to connect requirement {} between resource instance {} to resource instance {}. status is {}", requirement, fromResInstanceUid, toResInstanceUid, status);
+ return Either.right(status);
+ }
+ RelationshipInstDataDefinition relation = reqVsCap.left().value();
+
+ // add to json new relations
+ compositionDataDefinition.addRelation(relation.getUniqueId(), relation);
+
+ return Either.left(relation);
+ }
+
+ private Either<Pair<GraphVertex, Map<String, MapListCapabiltyDataDefinition>>, StorageOperationStatus> fetchContainerCalculatedCapability(GraphVertex containerV, EdgeLabelEnum capLabel) {
+
+ Either<Pair<GraphVertex, Map<String, MapListCapabiltyDataDefinition>>, TitanOperationStatus> calculatedCapabiltyEither = getDataAndVertexFromGraph(containerV, capLabel);
+ if (calculatedCapabiltyEither.isRight()) {
+ TitanOperationStatus error = calculatedCapabiltyEither.right().value();
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch calculated capabilties for container {}.", containerV.getUniqueId(), error);
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(error));
+ }
+ Pair<GraphVertex, Map<String, MapListCapabiltyDataDefinition>> calculatedCapabilty = calculatedCapabiltyEither.left().value();
+ return Either.left(calculatedCapabilty);
+ }
+
+ private Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> fetchContainerCalculatedRequirement(GraphVertex containerV, EdgeLabelEnum reqLabel) {
+ Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, TitanOperationStatus> calculatedRequirementEither = getDataAndVertexFromGraph(containerV, reqLabel);
+ if (calculatedRequirementEither.isRight()) {
+ TitanOperationStatus error = calculatedRequirementEither.right().value();
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch calculated requirements for container {}.", containerV.getUniqueId(), error);
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(error));
+ }
+ Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>> calculatedRequirement = calculatedRequirementEither.left().value();
+ return Either.left(calculatedRequirement);
+ }
+
+ private Either<RelationshipInstDataDefinition, StorageOperationStatus> connectRequirementVsCapability(ComponentInstanceDataDefinition fromResInstance, ComponentInstanceDataDefinition toResInstance, RequirementAndRelationshipPair relationPair,
+ Map<String, MapListCapabiltyDataDefinition> calculatedCapabilty, Map<String, MapListRequirementDataDefinition> calculatedRequirement, Map<String, MapListCapabiltyDataDefinition> fullfilledCapabilty,
+ Map<String, MapListRequirementDataDefinition> fullfilledRequirement, String containerId) {
+ String type = relationPair.getRelationship().getType();
+ // capability
+
+ String toInstId = toResInstance.getUniqueId();
+ MapListCapabiltyDataDefinition mapListCapabiltyDataDefinition = calculatedCapabilty.get(toInstId);
+
+ if (mapListCapabiltyDataDefinition == null) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch calculated capabilities for instance {} in container {}.", toInstId, containerId);
+ return Either.right(StorageOperationStatus.MATCH_NOT_FOUND);
+ }
+ ListCapabilityDataDefinition listCapabilityDataDefinition = mapListCapabiltyDataDefinition.getMapToscaDataDefinition().get(type);
+ if (listCapabilityDataDefinition == null) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch calculated capabilities for type {} for instance {} in container {}.", type, toInstId, containerId);
+ return Either.right(StorageOperationStatus.MATCH_NOT_FOUND);
+ }
+ CapabilityDataDefinition capabiltyForRelation = null;
+ Iterator<CapabilityDataDefinition> iteratorCap = listCapabilityDataDefinition.getListToscaDataDefinition().iterator();
+ while (iteratorCap.hasNext()) {
+ CapabilityDataDefinition cap = iteratorCap.next();
+ if (cap.getUniqueId().equals(relationPair.getCapabilityUid()) && cap.getOwnerId().equals(relationPair.getCapabilityOwnerId())) {
+ capabiltyForRelation = cap;
+ String leftOccurrences = cap.getLeftOccurrences();
+ if (leftOccurrences != null && !leftOccurrences.equals(CapabilityDataDefinition.MAX_OCCURRENCES)) {
+ Integer leftIntValue = Integer.parseInt(leftOccurrences);
+ if (leftIntValue > 0) {
+ --leftIntValue;
+ capabiltyForRelation.setLeftOccurrences(String.valueOf(leftIntValue));
+ if (leftIntValue == 0) {
+ // remove from calculated
+ iteratorCap.remove();
+ // move to fullfilled
+ MapListCapabiltyDataDefinition mapListCapabiltyFullFilledInst = fullfilledCapabilty.get(toInstId);
+ if (mapListCapabiltyFullFilledInst == null) {
+ mapListCapabiltyFullFilledInst = new MapListCapabiltyDataDefinition();
+ fullfilledCapabilty.put(toInstId, mapListCapabiltyFullFilledInst);
+ }
+
+ ListCapabilityDataDefinition listCapabilityFull = mapListCapabiltyFullFilledInst.findByKey(type);
+ if (listCapabilityFull == null) {
+ listCapabilityFull = new ListCapabilityDataDefinition();
+ mapListCapabiltyFullFilledInst.put(type, listCapabilityFull);
+ }
+ listCapabilityFull.add(capabiltyForRelation);
+ }
+ break;
+ } else {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No left occurrences capabilty {} to {} in container {}.", capabiltyForRelation.getType(), toInstId, containerId);
+ return Either.right(StorageOperationStatus.MATCH_NOT_FOUND);
+ }
+ }
+ }
+ }
+ if (capabiltyForRelation == null) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch capabilty for type {} for instance {} in container {}.", type, toInstId, containerId);
+ return Either.right(StorageOperationStatus.MATCH_NOT_FOUND);
+ }
+
+ // requirements
+ String fromInstId = fromResInstance.getUniqueId();
+ MapListRequirementDataDefinition mapListRequirementDataDefinition = calculatedRequirement.get(fromInstId);
+ if (mapListRequirementDataDefinition == null) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch calculated requirements for instance {} in container {}.", fromInstId, containerId);
+ return Either.right(StorageOperationStatus.MATCH_NOT_FOUND);
+ }
+ ListRequirementDataDefinition listRequirementDataDefinition = mapListRequirementDataDefinition.getMapToscaDataDefinition().get(type);
+ if (listRequirementDataDefinition == null) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch calculated requirements for type {} for instance {} in container {}.", type, fromInstId, containerId);
+ return Either.right(StorageOperationStatus.MATCH_NOT_FOUND);
+ }
+
+ RequirementDataDefinition requirementForRelation = null;
+ Iterator<RequirementDataDefinition> iteratorReq = listRequirementDataDefinition.getListToscaDataDefinition().iterator();
+ while (iteratorReq.hasNext()) {
+ RequirementDataDefinition req = iteratorReq.next();
+ if (req.getUniqueId().equals(relationPair.getRequirementUid()) && req.getOwnerId().equals(relationPair.getRequirementOwnerId())) {
+ requirementForRelation = req;
+
+ String leftOccurrences = req.getLeftOccurrences();
+ if (leftOccurrences != null && !leftOccurrences.equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
+ Integer leftIntValue = Integer.parseInt(leftOccurrences);
+ if (leftIntValue > 0) {
+ --leftIntValue;
+ req.setLeftOccurrences(String.valueOf(leftIntValue));
+ if (leftIntValue == 0) {
+ // remove from calculated
+ iteratorReq.remove();
+ // move to fullfilled
+ MapListRequirementDataDefinition mapListRequirementFullFilledInst = fullfilledRequirement.get(fromInstId);
+ if (mapListRequirementFullFilledInst == null) {
+ mapListRequirementFullFilledInst = new MapListRequirementDataDefinition();
+ fullfilledRequirement.put(fromInstId, mapListRequirementFullFilledInst);
+ }
+
+ ListRequirementDataDefinition listRequirementFull = mapListRequirementFullFilledInst.findByKey(type);
+ if (listRequirementFull == null) {
+ listRequirementFull = new ListRequirementDataDefinition();
+ mapListRequirementFullFilledInst.put(type, listRequirementFull);
+ }
+ listRequirementFull.add(requirementForRelation);
+ }
+ break;
+ } else {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No left occurrences requirement {} from {} to {} in container {}.", requirementForRelation.getCapability(), fromInstId, toInstId, containerId);
+ return Either.right(StorageOperationStatus.MATCH_NOT_FOUND);
+ }
+ }
+ }
+ }
+ if (!capabiltyForRelation.getType().equals(requirementForRelation.getCapability())) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No math for capabilty from type {} and requirement {} from {} to {} in container {}.", capabiltyForRelation.getType(), requirementForRelation.getCapability(), fromInstId, toInstId,
+ containerId);
+ return Either.right(StorageOperationStatus.MATCH_NOT_FOUND);
+ }
+
+ RelationshipInstDataDefinition relationshipTypeData = buildRelationshipInstData(fromInstId, toInstId, relationPair);
+
+ relationshipTypeData.setType(type);
+
+ return Either.left(relationshipTypeData);
+ }
+
+ private RelationshipInstDataDefinition buildRelationshipInstData(String fromResInstanceUid, String toInstId, RequirementAndRelationshipPair relationPair) {
+
+ RelationshipInstDataDefinition relationshipInstData = new RelationshipInstDataDefinition();
+ relationshipInstData.setUniqueId(UniqueIdBuilder.buildRelationsipInstInstanceUid(fromResInstanceUid, toInstId));
+
+ relationshipInstData.setType(relationPair.getRelationship().getType());
+ Long creationDate = System.currentTimeMillis();
+ relationshipInstData.setCreationTime(creationDate);
+ relationshipInstData.setModificationTime(creationDate);
+ relationshipInstData.setCapabilityOwnerId(relationPair.getCapabilityOwnerId());
+ relationshipInstData.setRequirementOwnerId(relationPair.getRequirementOwnerId());
+ relationshipInstData.setCapabiltyId(relationPair.getCapabilityUid());
+ relationshipInstData.setRequirementId(relationPair.getRequirementUid());
+ relationshipInstData.setFromId(fromResInstanceUid);
+ relationshipInstData.setToId(toInstId);
+ relationshipInstData.setRequirement(relationPair.getRequirement());
+ relationshipInstData.setCapability(relationPair.getCapability());
+
+ return relationshipInstData;
+ }
+
+ public StorageOperationStatus associateComponentInstancesToComponent(Component containerComponent, Map<ComponentInstance, Resource> resourcesInstancesMap, GraphVertex containerVertex, boolean allowDeleted) {
+
+ StorageOperationStatus result = null;
+ String containerId = containerComponent.getUniqueId();
+ Map<String, ComponentInstanceDataDefinition> instancesJsonData = null;
+ Either<GraphVertex, TitanOperationStatus> updateElement = null;
+ if (!validateInstanceNames(resourcesInstancesMap)) {
+ result = StorageOperationStatus.INCONSISTENCY;
+ }
+ if (result == null) {
+ if (!validateInstanceNames(resourcesInstancesMap)) {
+ result = StorageOperationStatus.INCONSISTENCY;
+ }
+ }
+ if (result == null && !allowDeleted) {
+ if (!validateDeletedResources(resourcesInstancesMap)) {
+ result = StorageOperationStatus.INCONSISTENCY;
+ }
+ }
+ if (result == null) {
+ instancesJsonData = convertToComponentInstanceDataDefinition(resourcesInstancesMap, containerId);
+ }
+ if (result == null && MapUtils.isNotEmpty(instancesJsonData)) {
+ containerVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis());
+ Map<String, CompositionDataDefinition> compositions = new HashMap<>();
+ CompositionDataDefinition composition = new CompositionDataDefinition();
+ composition.setComponentInstances(instancesJsonData);
+ compositions.put(JsonConstantKeysEnum.COMPOSITION.getValue(), composition);
+ containerVertex.setJson(compositions);
+ updateElement = titanDao.updateVertex(containerVertex);
+ if (updateElement.isRight()) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update topology template {} with new component instances. ", containerComponent.getName());
+ result = DaoStatusConverter.convertTitanStatusToStorageStatus(updateElement.right().value());
+ }
+ }
+ if (result == null) {
+ result = StorageOperationStatus.OK;
+ }
+ return result;
+ }
+
+ private Map<String, ComponentInstanceDataDefinition> convertToComponentInstanceDataDefinition(Map<ComponentInstance, Resource> resourcesInstancesMap, String containerId) {
+
+ Map<String, ComponentInstanceDataDefinition> instances = new HashMap<>();
+ for (Entry<ComponentInstance, Resource> entry : resourcesInstancesMap.entrySet()) {
+ ComponentInstanceDataDefinition instance = buildComponentInstanceDataDefinition(entry.getKey(), containerId, null, true, ModelConverter.convertToToscaElement(entry.getValue()));
+ instances.put(instance.getUniqueId(), instance);
+ }
+ return instances;
+ }
+
+ private boolean validateDeletedResources(Map<ComponentInstance, Resource> resourcesInstancesMap) {
+ boolean result = true;
+ for (Resource resource : resourcesInstancesMap.values()) {
+ if (resource.getIsDeleted() != null && resource.getIsDeleted()) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Component {} is already deleted. Cannot add component instance. ", resource.getName());
+ result = false;
+ break;
+ }
+ }
+ return result;
+ }
+
+ private boolean validateInstanceNames(Map<ComponentInstance, Resource> resourcesInstancesMap) {
+ boolean result = true;
+ Set<String> names = new HashSet<>();
+ for (ComponentInstance instance : resourcesInstancesMap.keySet()) {
+ if (StringUtils.isEmpty(instance.getName())) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Component instance {} name is empty. Cannot add component instance. ", instance.getUniqueId());
+ result = false;
+ break;
+ } else if (names.contains(instance.getName())) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Component instance with the name {} already exsists. Cannot add component instance. ", instance.getName());
+ result = false;
+ break;
+ } else {
+ names.add(instance.getName());
+ }
+ }
+ return result;
+ }
+
+ public StorageOperationStatus addDeploymentArtifactsToInstance(String toscaElementId, String instanceId, Map<String, ArtifactDataDefinition> instDeplArtifacts) {
+ Either<GraphVertex, TitanOperationStatus> metadataVertex = titanDao.getVertexById(toscaElementId, JsonParseFlagEnum.NoParse);
+ if (metadataVertex.isRight()) {
+ TitanOperationStatus status = metadataVertex.right().value();
+ if (status == TitanOperationStatus.NOT_FOUND) {
+ status = TitanOperationStatus.INVALID_ID;
+ }
+ return DaoStatusConverter.convertTitanStatusToStorageStatus(status);
+ }
+ MapArtifactDataDefinition instArtifacts = new MapArtifactDataDefinition(instDeplArtifacts);
+ return addToscaDataDeepElementsBlockToToscaElement(metadataVertex.left().value(), EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS, VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS, instArtifacts, instanceId);
+
+ }
+
+ @SuppressWarnings({ "unchecked" })
+ public StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId) {
+ Either<GraphVertex, TitanOperationStatus> metadataVertex = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll);
+ if (metadataVertex.isRight()) {
+ TitanOperationStatus status = metadataVertex.right().value();
+ if (status == TitanOperationStatus.NOT_FOUND) {
+ status = TitanOperationStatus.INVALID_ID;
+ }
+ return DaoStatusConverter.convertTitanStatusToStorageStatus(status);
+ }
+ GraphVertex metaVertex = metadataVertex.left().value();
+ Map<String, CompositionDataDefinition> json = (Map<String, CompositionDataDefinition>) metaVertex.getJson();
+ CompositionDataDefinition compositionDataDefinition = json.get(JsonConstantKeysEnum.COMPOSITION.getValue());
+ StorageOperationStatus status = updateCustomizationUUID(instanceId, compositionDataDefinition);
+ if (status != StorageOperationStatus.OK) {
+ logger.debug("Failed to update customization UUID for instance {} in component {} error {}", instanceId, componentId, status);
+ return status;
+ }
+ Either<GraphVertex, TitanOperationStatus> updateVertex = titanDao.updateVertex(metaVertex);
+ if (updateVertex.isRight()) {
+ logger.debug("Failed to update vertex of component {} error {}", componentId, updateVertex.right().value());
+ return DaoStatusConverter.convertTitanStatusToStorageStatus(updateVertex.right().value());
+ }
+ return StorageOperationStatus.OK;
+ }
+
+ public StorageOperationStatus generateCustomizationUUIDOnInstanceGroup(String componentId, String instanceId, List<String> groupInstances) {
+ if (groupInstances != null) {
+ Either<Map<String, MapGroupsDataDefinition>, TitanOperationStatus> dataFromGraph = getDataFromGraph(componentId, EdgeLabelEnum.INST_GROUPS);
+ if (dataFromGraph.isRight()) {
+ return DaoStatusConverter.convertTitanStatusToStorageStatus(dataFromGraph.right().value());
+ }
+ MapGroupsDataDefinition grInstPerInstance = dataFromGraph.left().value().get(instanceId);
+ if (grInstPerInstance == null) {
+ logger.debug("No instance groups for instance {} in component {}", instanceId, componentId);
+ return StorageOperationStatus.NOT_FOUND;
+ }
+ for (String instGroupForUpdate : groupInstances) {
+ GroupInstanceDataDefinition groupInst = grInstPerInstance.findByKey(instGroupForUpdate);
+ if (groupInst == null) {
+ logger.debug("No group instance {} in group list for instance {} in component {}", instGroupForUpdate, instanceId, componentId);
+ continue;
+ }
+ UUID uuid = UUID.randomUUID();
+ groupInst.setCustomizationUUID(uuid.toString());
+ }
+
+ }
+ return StorageOperationStatus.OK;
+ }
+
+ public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List<GroupInstance> groupInstances) {
+
+ return addToscaDataDeepElementsBlockToToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS,
+ new MapDataDefinition<>(groupInstances.stream().collect(Collectors.toMap(gi -> gi.getName(), gi -> gi))), componentInstance.getUniqueId());
+ }
+
+ public StorageOperationStatus addDeploymentArtifactsToComponentInstance(Component containerComponent, ComponentInstance componentInstance, Map<String, ArtifactDefinition> deploymentArtifacts) {
+
+ return addToscaDataDeepElementsBlockToToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS, VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS, new MapDataDefinition<>(deploymentArtifacts),
+ componentInstance.getUniqueId());
+ }
+
+ public StorageOperationStatus updateComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) {
+
+ List<String> pathKeys = new ArrayList<>();
+ pathKeys.add(componentInstanceId);
+ return updateToscaDataDeepElementOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES, property, pathKeys, JsonPresentationFields.NAME);
+ }
+
+ public StorageOperationStatus addComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) {
+ List<String> pathKeys = new ArrayList<>();
+ pathKeys.add(componentInstanceId);
+ return addToscaDataDeepElementToToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES, property, pathKeys, JsonPresentationFields.NAME);
+ }
+
+ public StorageOperationStatus updateComponentInstanceInput(Component containerComponent, String componentInstanceId, ComponentInstanceInput property) {
+
+ List<String> pathKeys = new ArrayList<>();
+ pathKeys.add(componentInstanceId);
+ return updateToscaDataDeepElementOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, property, pathKeys, JsonPresentationFields.NAME);
+ }
+
+ public StorageOperationStatus addComponentInstanceInput(Component containerComponent, String componentInstanceId, ComponentInstanceInput property) {
+ List<String> pathKeys = new ArrayList<>();
+ pathKeys.add(componentInstanceId);
+ return addToscaDataDeepElementToToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, property, pathKeys, JsonPresentationFields.NAME);
+ }
+
+
+}
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
new file mode 100644
index 0000000000..1eb67e5c51
--- /dev/null
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/NodeTypeOperation.java
@@ -0,0 +1,774 @@
+package org.openecomp.sdc.be.model.jsontitan.operations;
+
+import fj.data.Either;
+
+import org.apache.tinkerpop.gremlin.structure.Direction;
+import org.apache.tinkerpop.gremlin.structure.Edge;
+import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
+import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
+import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
+import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
+import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.AttributeDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.InterfaceDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.ListRequirementDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.MapCapabiltyProperty;
+import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
+import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+import org.openecomp.sdc.be.model.ComponentParametersView;
+import org.openecomp.sdc.be.model.DerivedNodeTypeResolver;
+import org.openecomp.sdc.be.model.LifecycleStateEnum;
+import org.openecomp.sdc.be.model.RequirementDefinition;
+import org.openecomp.sdc.be.model.jsontitan.datamodel.NodeType;
+import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate;
+import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement;
+import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
+import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
+import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
+import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Qualifier;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.regex.Pattern;
+
+@org.springframework.stereotype.Component("node-type-operation")
+public class NodeTypeOperation extends ToscaElementOperation {
+ public static Pattern uuidNewVersion = Pattern.compile("^\\d{1,}.1");
+ public static Pattern uuidNormativeNewVersion = Pattern.compile("^\\d{1,}.0");
+
+ private static Logger log = LoggerFactory.getLogger(NodeTypeOperation.class.getName());
+
+ private DerivedNodeTypeResolver derivedResourceResolver;
+
+ public NodeTypeOperation(@Qualifier("derived-resource-resolver") DerivedNodeTypeResolver derivedNodeTypeResolver) {
+ this.derivedResourceResolver = derivedNodeTypeResolver;
+ }
+
+ public Either<NodeType, StorageOperationStatus> createNodeType(NodeType nodeType) {
+
+ Either<NodeType, StorageOperationStatus> result = null;
+
+ nodeType.generateUUID();
+
+ nodeType = getResourceMetaDataFromResource(nodeType);
+ String resourceUniqueId = nodeType.getUniqueId();
+ if (resourceUniqueId == null) {
+ resourceUniqueId = UniqueIdBuilder.buildResourceUniqueId();
+ nodeType.setUniqueId(resourceUniqueId);
+ }
+
+ // get derived from resources
+ List<GraphVertex> derivedResources = null;
+ Either<List<GraphVertex>, StorageOperationStatus> derivedResourcesResult = findDerivedResources(nodeType);
+ if (derivedResourcesResult.isRight()) {
+ result = Either.right(derivedResourcesResult.right().value());
+ return result;
+ } else {
+ derivedResources = derivedResourcesResult.left().value();
+ }
+
+ GraphVertex nodeTypeVertex = new GraphVertex(VertexTypeEnum.NODE_TYPE);
+ fillToscaElementVertexData(nodeTypeVertex, nodeType, JsonParseFlagEnum.ParseAll);
+
+ Either<GraphVertex, TitanOperationStatus> createdVertex = titanDao.createVertex(nodeTypeVertex);
+ if (createdVertex.isRight()) {
+ TitanOperationStatus status = createdVertex.right().value();
+ log.error("Error returned after creating resource data node {}. status returned is ", nodeTypeVertex, status);
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ return result;
+ }
+ nodeTypeVertex = createdVertex.left().value();
+
+ StorageOperationStatus assosiateCommon = assosiateCommonForToscaElement(nodeTypeVertex, nodeType, derivedResources);
+ if (assosiateCommon != StorageOperationStatus.OK) {
+ result = Either.right(assosiateCommon);
+ return result;
+ }
+
+ StorageOperationStatus associateDerived = assosiateToDerived(nodeTypeVertex, derivedResources);
+ if (associateDerived != StorageOperationStatus.OK) {
+ result = Either.right(associateDerived);
+ return result;
+ }
+ StorageOperationStatus associateCategory = assosiateResourceMetadataToCategory(nodeTypeVertex, nodeType);
+ if (associateCategory != StorageOperationStatus.OK) {
+ result = Either.right(associateCategory);
+ return result;
+ }
+
+ StorageOperationStatus associateAttributes = associateAttributesToResource(nodeTypeVertex, nodeType, derivedResources);
+ if (associateAttributes != StorageOperationStatus.OK) {
+ result = Either.right(associateAttributes);
+ return result;
+ }
+
+ StorageOperationStatus associateRequirements = associateRequirementsToResource(nodeTypeVertex, nodeType, derivedResources);
+ if (associateRequirements != StorageOperationStatus.OK) {
+ result = Either.right(associateRequirements);
+ return result;
+ }
+
+ StorageOperationStatus associateCapabilities = associateCapabilitiesToResource(nodeTypeVertex, nodeType, derivedResources);
+ if (associateCapabilities != StorageOperationStatus.OK) {
+ result = Either.right(associateCapabilities);
+ return result;
+ }
+ StorageOperationStatus associateCapabilitiesProps = associateCapabilitiesPropertiesToResource(nodeTypeVertex, nodeType, derivedResources);
+ if (associateCapabilitiesProps != StorageOperationStatus.OK) {
+ result = Either.right(associateCapabilitiesProps);
+ return result;
+ }
+
+ StorageOperationStatus associateInterfaces = associateInterfacesToResource(nodeTypeVertex, nodeType, derivedResources);
+ if (associateInterfaces != StorageOperationStatus.OK) {
+ result = Either.right(associateInterfaces);
+ return result;
+ }
+
+ StorageOperationStatus addAdditionalInformation = addAdditionalInformationToResource(nodeTypeVertex, nodeType, derivedResources);
+ if (addAdditionalInformation != StorageOperationStatus.OK) {
+ result = Either.right(addAdditionalInformation);
+ return result;
+ }
+ result = Either.left(nodeType);
+ return result;
+
+ }
+
+ private StorageOperationStatus associateInterfacesToResource(GraphVertex nodeTypeVertex, NodeType nodeType, List<GraphVertex> derivedResources) {
+ // Note : currently only one derived supported!!!!
+ Either<Map<String, InterfaceDataDefinition>, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources, InterfaceDataDefinition.class, EdgeLabelEnum.INTERFACE_ARTIFACTS);
+ if (dataFromDerived.isRight()) {
+ return dataFromDerived.right().value();
+ }
+ Map<String, InterfaceDataDefinition> interfacArtsAll = dataFromDerived.left().value();
+
+ Map<String, InterfaceDataDefinition> interfacArts = nodeType.getInterfaceArtifacts();
+ if (interfacArts != null) {
+ interfacArtsAll.putAll(interfacArts);
+ }
+ if (!interfacArtsAll.isEmpty()) {
+ Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.INTERFACE_ARTIFACTS, EdgeLabelEnum.INTERFACE_ARTIFACTS, interfacArtsAll);
+ if (assosiateElementToData.isRight()) {
+ return assosiateElementToData.right().value();
+ }
+ }
+ return StorageOperationStatus.OK;
+ }
+
+ @Override
+ public Either<ToscaElement, StorageOperationStatus> getToscaElement(String uniqueId, ComponentParametersView componentParametersView) {
+
+ Either<GraphVertex, StorageOperationStatus> componentByLabelAndId = getComponentByLabelAndId(uniqueId, ToscaElementTypeEnum.NodeType, JsonParseFlagEnum.ParseMetadata);
+ if (componentByLabelAndId.isRight()) {
+ return Either.right(componentByLabelAndId.right().value());
+ }
+ GraphVertex componentV = componentByLabelAndId.left().value();
+
+ return getToscaElement(componentV, componentParametersView);
+
+ }
+
+ // -------------------------------------------------------------
+ @Override
+ public Either<ToscaElement, StorageOperationStatus> getToscaElement(GraphVertex componentV, ComponentParametersView componentParametersView) {
+ NodeType toscaElement;
+ toscaElement = convertToComponent(componentV);
+ TitanOperationStatus status = null;
+ if (false == componentParametersView.isIgnoreUsers()) {
+ status = setCreatorFromGraph(componentV, toscaElement);
+ if (status != TitanOperationStatus.OK) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+
+ status = setLastModifierFromGraph(componentV, toscaElement);
+ if (status != TitanOperationStatus.OK) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ }
+
+ if (false == componentParametersView.isIgnoreProperties()) {
+ status = setResourcePropertiesFromGraph(componentV, toscaElement);
+ if (status != TitanOperationStatus.OK && status != TitanOperationStatus.NOT_FOUND) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ }
+
+ if (false == componentParametersView.isIgnoreAttributesFrom()) {
+ status = setResourceAttributesFromGraph(componentV, toscaElement);
+ if (status != TitanOperationStatus.OK) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ }
+
+ if (false == componentParametersView.isIgnoreDerivedFrom()) {
+ status = setResourceDerivedFromGraph(componentV, toscaElement);
+ if (status != TitanOperationStatus.OK) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ }
+
+ if (false == componentParametersView.isIgnoreCategories()) {
+ status = setResourceCategoryFromGraph(componentV, toscaElement);
+ if (status != TitanOperationStatus.OK) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ }
+ if (false == componentParametersView.isIgnoreRequirements()) {
+ status = setResourceRequirementsFromGraph(componentV, toscaElement);
+ if (status != TitanOperationStatus.OK) {
+ log.error("Failed to set requirement of resource {}. status is {}", componentV.getUniqueId(), status);
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ }
+ if (false == componentParametersView.isIgnoreCapabilities()) {
+ status = setResourceCapabilitiesFromGraph(componentV, toscaElement);
+ if (status != TitanOperationStatus.OK) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ }
+
+ if (false == componentParametersView.isIgnoreArtifacts()) {
+ status = setArtifactsFromGraph(componentV, toscaElement);
+ if (status != TitanOperationStatus.OK) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ }
+ if (false == componentParametersView.isIgnoreAdditionalInformation()) {
+ status = setAdditionalInformationFromGraph(componentV, toscaElement);
+ if (status != TitanOperationStatus.OK) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ }
+ if (false == componentParametersView.isIgnoreInterfaces()) {
+ status = setInterfacesFromGraph(componentV, toscaElement);
+ if (status != TitanOperationStatus.OK) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ }
+ if (false == componentParametersView.isIgnoreAllVersions()) {
+ status = setAllVersions(componentV, toscaElement);
+ if (status != TitanOperationStatus.OK && status != TitanOperationStatus.NOT_FOUND) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ }
+
+ if (false == componentParametersView.isIgnoreCapabiltyProperties()) {
+ status = setComponentCapPropertiesFromGraph(componentV, toscaElement);
+ if (status != TitanOperationStatus.OK) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+
+ }
+ }
+ return Either.left(toscaElement);
+ }
+
+ private TitanOperationStatus setComponentCapPropertiesFromGraph(GraphVertex componentV, NodeType toscaElement) {
+ Either<Map<String, MapPropertiesDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.CAPABILITIES_PROPERTIES);
+ if (result.isLeft()) {
+ toscaElement.setCapabiltiesProperties(result.left().value());
+ } else {
+ if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
+ return result.right().value();
+ }
+ }
+ return TitanOperationStatus.OK;
+ }
+
+ private TitanOperationStatus setInterfacesFromGraph(GraphVertex componentV, NodeType toscaElement) {
+ Either<Map<String, InterfaceDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.INTERFACE_ARTIFACTS);
+ if (result.isLeft()) {
+ toscaElement.setInterfaceArtifacts(result.left().value());
+ } else {
+ if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
+ return result.right().value();
+ }
+ }
+ return TitanOperationStatus.OK;
+ }
+
+ protected <T extends ToscaElement> TitanOperationStatus setCapabilitiesFromGraph(GraphVertex componentV, T toscaElement) {
+ return setResourceCapabilitiesFromGraph(componentV, (NodeType) toscaElement);
+ }
+
+ private TitanOperationStatus setResourceCapabilitiesFromGraph(GraphVertex componentV, NodeType toscaElement) {
+ Either<Map<String, ListCapabilityDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.CAPABILITIES);
+ if (result.isLeft()) {
+ toscaElement.setCapabilties(result.left().value());
+ } else {
+ if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
+ return result.right().value();
+ }
+ }
+ return TitanOperationStatus.OK;
+ }
+
+ private TitanOperationStatus setResourceDerivedFromGraph(GraphVertex componentV, NodeType toscaElement) {
+ List<String> derivedFromList = new ArrayList<String>();
+
+ TitanOperationStatus listFromGraphStatus = findResourcesPathRecursively(componentV, derivedFromList);
+ if (TitanOperationStatus.OK != listFromGraphStatus) {
+ return listFromGraphStatus;
+ }
+
+ if (false == derivedFromList.isEmpty()) {
+ if (derivedFromList.size() > 1) {
+ List<String> lastDerivedFrom = new ArrayList<String>();
+ lastDerivedFrom.add(derivedFromList.get(1));
+ toscaElement.setDerivedFrom(lastDerivedFrom);
+ toscaElement.setDerivedList(derivedFromList);
+ } else {
+ toscaElement.setDerivedFrom(null);
+ toscaElement.setDerivedList(derivedFromList);
+ }
+
+ }
+ return TitanOperationStatus.OK;
+ }
+
+ protected TitanOperationStatus findResourcesPathRecursively(GraphVertex nodeTypeV, List<String> resourcesPathList) {
+ Either<GraphVertex, TitanOperationStatus> parentResourceRes = titanDao.getChildVertex(nodeTypeV, EdgeLabelEnum.DERIVED_FROM, JsonParseFlagEnum.NoParse);
+ resourcesPathList.add((String) nodeTypeV.getMetadataProperty(GraphPropertyEnum.TOSCA_RESOURCE_NAME));
+ while (parentResourceRes.isLeft()) {
+
+ GraphVertex parent = parentResourceRes.left().value();
+ resourcesPathList.add((String) parent.getMetadataProperty(GraphPropertyEnum.TOSCA_RESOURCE_NAME));
+ parentResourceRes = titanDao.getChildVertex(parent, EdgeLabelEnum.DERIVED_FROM, JsonParseFlagEnum.NoParse);
+ }
+ TitanOperationStatus operationStatus = parentResourceRes.right().value();
+
+ if (operationStatus != TitanOperationStatus.NOT_FOUND) {
+ return operationStatus;
+ } else {
+ return TitanOperationStatus.OK;
+ }
+
+ }
+
+ protected <T extends ToscaElement> TitanOperationStatus setRequirementsFromGraph(GraphVertex componentV, T toscaElement) {
+ return setResourceRequirementsFromGraph(componentV, (NodeType) toscaElement);
+ }
+
+ private TitanOperationStatus setResourceRequirementsFromGraph(GraphVertex componentV, NodeType toscaElement) {
+ Either<Map<String, ListRequirementDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.REQUIREMENTS);
+ if (result.isLeft()) {
+ toscaElement.setRequirements(result.left().value());
+ } else {
+ if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
+ return result.right().value();
+ }
+ }
+ return TitanOperationStatus.OK;
+ }
+
+ private TitanOperationStatus setResourceAttributesFromGraph(GraphVertex componentV, NodeType toscaElement) {
+ Either<Map<String, AttributeDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.ATTRIBUTES);
+ if (result.isLeft()) {
+ toscaElement.setAttributes(result.left().value());
+ } else {
+ if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
+ return result.right().value();
+ }
+ }
+ return TitanOperationStatus.OK;
+ }
+
+ private TitanOperationStatus setResourcePropertiesFromGraph(GraphVertex componentV, NodeType toscaElement) {
+ Either<Map<String, PropertyDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.PROPERTIES);
+ if (result.isLeft()) {
+ toscaElement.setProperties(result.left().value());
+ } else {
+ if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
+ return result.right().value();
+ }
+ }
+ return TitanOperationStatus.OK;
+ }
+
+ private StorageOperationStatus assosiateToDerived(GraphVertex nodeTypeVertex, List<GraphVertex> derivedResources) {
+ for (GraphVertex derivedV : derivedResources) {
+ TitanOperationStatus createEdge = titanDao.createEdge(nodeTypeVertex, derivedV, EdgeLabelEnum.DERIVED_FROM, null);
+ if (createEdge != TitanOperationStatus.OK) {
+ log.trace("Failed to associate resource {} to derived with id {}", nodeTypeVertex.getUniqueId(), derivedV.getUniqueId());
+ return DaoStatusConverter.convertTitanStatusToStorageStatus(createEdge);
+ }
+ }
+ return StorageOperationStatus.OK;
+ }
+
+ private StorageOperationStatus addAdditionalInformationToResource(GraphVertex nodeTypeVertex, NodeType nodeType, List<GraphVertex> derivedResources) {
+ // Note : currently only one derived supported!!!!
+ Either<Map<String, AdditionalInfoParameterDataDefinition>, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources, AdditionalInfoParameterDataDefinition.class, EdgeLabelEnum.ADDITIONAL_INFORMATION);
+ if (dataFromDerived.isRight()) {
+ return dataFromDerived.right().value();
+ }
+ Map<String, AdditionalInfoParameterDataDefinition> addInformationAll = dataFromDerived.left().value();
+
+ Map<String, AdditionalInfoParameterDataDefinition> addInformation = nodeType.getAdditionalInformation();
+ if (addInformation != null) {
+ addInformationAll.putAll(addInformation);
+ }
+ if (!addInformationAll.isEmpty()) {
+ Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.ADDITIONAL_INFORMATION, EdgeLabelEnum.ADDITIONAL_INFORMATION, addInformationAll);
+ if (assosiateElementToData.isRight()) {
+ return assosiateElementToData.right().value();
+ }
+ }
+ return StorageOperationStatus.OK;
+ }
+
+ private StorageOperationStatus associateCapabilitiesToResource(GraphVertex nodeTypeVertex, NodeType nodeType, List<GraphVertex> derivedResources) {
+ // Note : currently only one derived supported!!!!
+ Either<Map<String, ListCapabilityDataDefinition>, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources, ListCapabilityDataDefinition.class, EdgeLabelEnum.CAPABILITIES);
+ if (dataFromDerived.isRight()) {
+ return dataFromDerived.right().value();
+ }
+ Map<String, ListCapabilityDataDefinition> capabiltiesAll = dataFromDerived.left().value();
+
+ Map<String, ListCapabilityDataDefinition> capabilties = nodeType.getCapabilties();
+ if (capabilties != null) {
+ if (capabiltiesAll == null) {
+ capabiltiesAll = new HashMap<>();
+ }
+ capabilties.values().forEach(l -> {
+ l.getListToscaDataDefinition().stream().filter(p -> p.getUniqueId() == null).forEach(p -> {
+ String uid = UniqueIdBuilder.buildCapabilityUid(nodeTypeVertex.getUniqueId(), p.getName());
+ p.setUniqueId(uid);
+ });
+ });
+
+ for (Entry<String, ListCapabilityDataDefinition> entry : capabilties.entrySet()) {
+ capabiltiesAll.merge(entry.getKey(), entry.getValue(), (list1, list2) -> list1.mergeListItemsByName(list2));
+ }
+ }
+ if (!capabiltiesAll.isEmpty()) {
+ Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.CAPABILTIES, EdgeLabelEnum.CAPABILITIES, capabiltiesAll);
+ if (assosiateElementToData.isRight()) {
+ return assosiateElementToData.right().value();
+ }
+ }
+ return StorageOperationStatus.OK;
+ }
+
+ private StorageOperationStatus associateRequirementsToResource(GraphVertex nodeTypeVertex, NodeType nodeType, List<GraphVertex> derivedResources) {
+ // Note : currently only one derived supported!!!!
+ Either<Map<String, ListRequirementDataDefinition>, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources, ListRequirementDataDefinition.class, EdgeLabelEnum.REQUIREMENTS);
+ if (dataFromDerived.isRight()) {
+ return dataFromDerived.right().value();
+ }
+ Map<String, ListRequirementDataDefinition> requirementsAll = dataFromDerived.left().value();
+
+ Map<String, ListRequirementDataDefinition> requirements = nodeType.getRequirements();
+ if (requirements != null) {
+ if (requirementsAll == null) {
+ requirementsAll = new HashMap<>();
+ }
+ requirements.values().forEach(l -> {
+ l.getListToscaDataDefinition().stream().filter(p -> p.getUniqueId() == null).forEach(p -> {
+ String uid = UniqueIdBuilder.buildRequirementUid(nodeTypeVertex.getUniqueId(), p.getName());
+ p.setUniqueId(uid);
+ });
+ });
+
+ for (Entry<String, ListRequirementDataDefinition> entry : requirements.entrySet()) {
+ requirementsAll.merge(entry.getKey(), entry.getValue(), (list1, list2) -> list1.mergeListItemsByName(list2));
+ }
+ }
+ if (!requirementsAll.isEmpty()) {
+ Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.REQUIREMENTS, EdgeLabelEnum.REQUIREMENTS, requirementsAll);
+ if (assosiateElementToData.isRight()) {
+ return assosiateElementToData.right().value();
+ }
+ }
+ return StorageOperationStatus.OK;
+ }
+
+ private StorageOperationStatus associateAttributesToResource(GraphVertex nodeTypeVertex, NodeType nodeType, List<GraphVertex> derivedResources) {
+ // Note : currently only one derived supported!!!!
+ Either<Map<String, AttributeDataDefinition>, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources, AttributeDataDefinition.class, EdgeLabelEnum.ATTRIBUTES);
+ if (dataFromDerived.isRight()) {
+ return dataFromDerived.right().value();
+ }
+ Map<String, AttributeDataDefinition> attributesAll = dataFromDerived.left().value();
+
+ Map<String, AttributeDataDefinition> attributes = nodeType.getAttributes();
+ if (attributes != null) {
+ attributes.values().stream().filter(p -> p.getUniqueId() == null).forEach(p -> {
+ String uid = UniqueIdBuilder.buildAttributeUid(nodeTypeVertex.getUniqueId(), p.getName());
+ p.setUniqueId(uid);
+ });
+ attributesAll.putAll(attributes);
+ }
+ if (!attributesAll.isEmpty()) {
+ Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.ATTRIBUTES, EdgeLabelEnum.ATTRIBUTES, attributesAll);
+ if (assosiateElementToData.isRight()) {
+ return assosiateElementToData.right().value();
+ }
+ }
+ return StorageOperationStatus.OK;
+ }
+
+ // TODO get from derived
+ private StorageOperationStatus associateCapabilitiesPropertiesToResource(GraphVertex nodeTypeVertex, NodeType nodeType, List<GraphVertex> derivedResources) {
+ // // Note : currently only one derived supported!!!!
+ Either<Map<String, MapPropertiesDataDefinition>, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources, MapPropertiesDataDefinition.class, EdgeLabelEnum.CAPABILITIES_PROPERTIES);
+ if (dataFromDerived.isRight()) {
+ return dataFromDerived.right().value();
+ }
+ Map<String, MapPropertiesDataDefinition> propertiesAll = dataFromDerived.left().value();
+ Map<String, MapPropertiesDataDefinition> capabiltiesProps = nodeType.getCapabiltiesProperties();
+ if (capabiltiesProps != null) {
+ capabiltiesProps.values().forEach(l -> {
+ if (l.getMapToscaDataDefinition() != null && l.getMapToscaDataDefinition().values() != null) {
+ Collection<PropertyDataDefinition> mapToscaDataDefinition = l.getMapToscaDataDefinition().values();
+ mapToscaDataDefinition.stream().filter(p -> p != null && p.getUniqueId() == null).forEach(p -> {
+ String uid = UniqueIdBuilder.buildRequirementUid(nodeTypeVertex.getUniqueId(), p.getName());
+ p.setUniqueId(uid);
+ });
+ }
+ });
+ propertiesAll.putAll(capabiltiesProps);
+ }
+ if (propertiesAll != null) {
+ Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.CAPABILITIES_PROPERTIES, EdgeLabelEnum.CAPABILITIES_PROPERTIES, propertiesAll);
+ if (assosiateElementToData.isRight()) {
+ return assosiateElementToData.right().value();
+ }
+ }
+ return StorageOperationStatus.OK;
+ }
+
+ public Either<List<GraphVertex>, StorageOperationStatus> findDerivedResources(NodeType nodeType) {
+
+ List<GraphVertex> derivedResources = new ArrayList<GraphVertex>();
+ List<String> derivedFromResources = nodeType.getDerivedFrom();
+ if (derivedFromResources != null && false == derivedFromResources.isEmpty()) {
+
+ for (String parentResource : derivedFromResources) {
+ Either<List<GraphVertex>, TitanOperationStatus> getParentResources = derivedResourceResolver.findDerivedResources(parentResource);
+ List<GraphVertex> resources = null;
+ if (getParentResources.isRight()) {
+ log.error("Cannot find parent resource by tosca resource name {} in the graph.", parentResource);
+ return Either.right(StorageOperationStatus.PARENT_RESOURCE_NOT_FOUND);
+
+ } else {
+ resources = getParentResources.left().value();
+ if (resources == null || resources.size() == 0) {
+ log.error("Cannot find parent resource by tosca name {} in the graph. resources size is empty", parentResource);
+ return Either.right(StorageOperationStatus.PARENT_RESOURCE_NOT_FOUND);
+ } else {
+ if (resources.size() > 1) {
+ log.error("Multiple parent resources called {} found in the graph.", parentResource);
+ return Either.right(StorageOperationStatus.MULTIPLE_PARENT_RESOURCE_FOUND);
+ }
+ GraphVertex parentResourceData = resources.get(0);
+ derivedResources.add(parentResourceData);
+ }
+
+ }
+
+ }
+ }
+ return Either.left(derivedResources);
+ }
+
+ private GraphVertex fillMetadata(GraphVertex nodeTypeVertex, NodeType nodeType) {
+ nodeTypeVertex.setLabel(VertexTypeEnum.NODE_TYPE);
+
+ fillCommonMetadata(nodeTypeVertex, nodeType);
+
+ return nodeTypeVertex;
+ }
+
+ @Override
+ public Either<ToscaElement, StorageOperationStatus> deleteToscaElement(GraphVertex toscaElementVertex) {
+ Either<ToscaElement, StorageOperationStatus> nodeType = getToscaElement(toscaElementVertex, new ComponentParametersView());
+ if (nodeType.isRight()) {
+ log.debug("Failed to fetch tosca element {} error {}", toscaElementVertex.getUniqueId(), nodeType.right().value());
+ return nodeType;
+ }
+ TitanOperationStatus status = disassociateAndDeleteCommonElements(toscaElementVertex);
+ if (status != TitanOperationStatus.OK) {
+ Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CAPABILITIES);
+ if (status != TitanOperationStatus.OK) {
+ log.debug("Failed to disassociate capabilties for {} error {}", toscaElementVertex.getUniqueId(), status);
+ Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CAPABILITIES_PROPERTIES);
+ if (status != TitanOperationStatus.OK) {
+ log.debug("Failed to disassociate capabilties properties for {} error {}", toscaElementVertex.getUniqueId(), status);
+ Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.REQUIREMENTS);
+ if (status != TitanOperationStatus.OK) {
+ log.debug("Failed to disassociate requirements for {} error {}", toscaElementVertex.getUniqueId(), status);
+ Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.ATTRIBUTES);
+ if (status != TitanOperationStatus.OK) {
+ log.debug("Failed to disassociate attributes for {} error {}", toscaElementVertex.getUniqueId(), status);
+ Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INTERFACE_ARTIFACTS);
+ if (status != TitanOperationStatus.OK) {
+ log.debug("Failed to disassociate interface artifacts for {} error {}", toscaElementVertex.getUniqueId(), status);
+ Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ toscaElementVertex.getVertex().remove();
+ log.trace("Tosca element vertex for {} was removed", toscaElementVertex.getUniqueId());
+
+ return nodeType;
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public Either<NodeType, StorageOperationStatus> createToscaElement(ToscaElement toscaElement) {
+ return createNodeType((NodeType) toscaElement);
+ }
+
+ @Override
+ protected <T extends ToscaElement> TitanOperationStatus setCategoriesFromGraph(GraphVertex vertexComponent, T toscaElement) {
+ return setResourceCategoryFromGraph(vertexComponent, toscaElement);
+ }
+
+ @Override
+ protected <T extends ToscaElement> StorageOperationStatus validateCategories(T toscaElementToUpdate, GraphVertex elementV) {
+ return validateResourceCategory(toscaElementToUpdate, elementV);
+ }
+
+ @Override
+ protected <T extends ToscaElement> StorageOperationStatus updateDerived(T toscaElementToUpdate, GraphVertex nodeTypeV) {
+
+ NodeType nodeType = (NodeType) toscaElementToUpdate;
+ List<GraphVertex> derivedResources = null;
+
+ List<String> derivedFromResources = nodeType.getDerivedFrom();
+
+ // now supported only single derived from
+ if (derivedFromResources != null && !derivedFromResources.isEmpty() && derivedFromResources.get(0) != null) {
+ String firstDerived = derivedFromResources.get(0);
+ boolean derivedFromGenericType = null != nodeType.getDerivedFromGenericType();
+ Either<GraphVertex, TitanOperationStatus> childVertex = titanDao.getChildVertex(nodeTypeV, EdgeLabelEnum.DERIVED_FROM, JsonParseFlagEnum.NoParse);
+ if (childVertex.isRight()) {
+ TitanOperationStatus getchieldError = childVertex.right().value();
+ log.debug("Failed to fetch derived resource for element {} error {}", nodeTypeV.getUniqueId(), getchieldError);
+ return DaoStatusConverter.convertTitanStatusToStorageStatus(getchieldError);
+ }
+ GraphVertex firstDerivedInChain = childVertex.left().value();
+
+ String firstCurrentDerived = (String) firstDerivedInChain.getMetadataProperty(GraphPropertyEnum.TOSCA_RESOURCE_NAME);
+ if (!firstDerived.equals(firstCurrentDerived) || derivedFromGenericType) {
+
+ Map<GraphPropertyEnum, Object> propertiesToMatch = new HashMap<GraphPropertyEnum, Object>();
+ propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
+
+ propertiesToMatch.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, firstDerived);
+ propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+
+ Either<List<GraphVertex>, TitanOperationStatus> getParentResources = titanDao.getByCriteria(VertexTypeEnum.NODE_TYPE, propertiesToMatch, JsonParseFlagEnum.NoParse);
+
+ if (getParentResources.isRight()) {
+ TitanOperationStatus error = getParentResources.right().value();
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch derived by criteria {}. error {} ", propertiesToMatch, error);
+ return DaoStatusConverter.convertTitanStatusToStorageStatus(error);
+ }
+ // must be only one
+ GraphVertex newDerived = getParentResources.left().value().get(0);
+ StorageOperationStatus updateStatus = updateDataFromNewDerived(newDerived, nodeTypeV);
+ if (updateStatus != StorageOperationStatus.OK) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update data for {} from new derived {} ", nodeTypeV.getUniqueId(), newDerived.getUniqueId(), updateStatus);
+ return updateStatus;
+ }
+
+ Either<Edge, TitanOperationStatus> deleteEdge = titanDao.deleteEdge(nodeTypeV, firstDerivedInChain, EdgeLabelEnum.DERIVED_FROM);
+ if (deleteEdge.isRight()) {
+ TitanOperationStatus deleteError = deleteEdge.right().value();
+ log.debug("Failed to disassociate element {} from derived {} , error {}", nodeTypeV.getUniqueId(), firstDerivedInChain.getUniqueId(), deleteError);
+ return DaoStatusConverter.convertTitanStatusToStorageStatus(deleteError);
+ }
+
+ titanDao.createEdge(nodeTypeV, newDerived, EdgeLabelEnum.DERIVED_FROM, null);
+ }
+ }
+
+ return StorageOperationStatus.OK;
+ }
+
+ private StorageOperationStatus updateDataFromNewDerived(GraphVertex newDerived, GraphVertex nodeTypeV) {
+ StorageOperationStatus status = updateDataByType(newDerived, nodeTypeV, EdgeLabelEnum.CAPABILITIES, CapabilityDataDefinition.class);
+ if (status != StorageOperationStatus.OK) {
+ return status;
+ }
+ status = updateDataByType(newDerived, nodeTypeV, EdgeLabelEnum.REQUIREMENTS, RequirementDefinition.class);
+ if (status != StorageOperationStatus.OK) {
+ return status;
+ }
+ status = updateDataByType(newDerived, nodeTypeV, EdgeLabelEnum.PROPERTIES, PropertyDataDefinition.class);
+ if (status != StorageOperationStatus.OK) {
+ return status;
+ }
+ status = updateDataByType(newDerived, nodeTypeV, EdgeLabelEnum.ATTRIBUTES, AttributeDataDefinition.class);
+ if (status != StorageOperationStatus.OK) {
+ return status;
+ }
+ // TODO
+ // status = updateDataByType(newDerived, nodeTypeV,
+ // EdgeLabelEnum.CAPABILITIES_PROPERTIES, capa);
+ // if ( status != StorageOperationStatus.OK){
+ // return status;
+ // }
+ status = updateDataByType(newDerived, nodeTypeV, EdgeLabelEnum.ADDITIONAL_INFORMATION, AdditionalInfoParameterDataDefinition.class);
+ return status;
+ }
+
+ private <T extends ToscaDataDefinition> StorageOperationStatus updateDataByType(GraphVertex newDerived, GraphVertex nodeTypeV, EdgeLabelEnum label, Class<T> clazz) {
+ log.debug("Update data from derived for element {} type {}", nodeTypeV.getUniqueId(), label);
+ Either<GraphVertex, TitanOperationStatus> dataFromGraph = getDataVertex(nodeTypeV, label);
+ if (dataFromGraph.isRight()) {
+ return DaoStatusConverter.convertTitanStatusToStorageStatus(dataFromGraph.right().value());
+ }
+ GraphVertex dataV = dataFromGraph.left().value();
+
+ Map<String, T> mapFromGraph = (Map<String, T>) dataV.getJson();
+ mapFromGraph.entrySet().removeIf(e -> e.getValue().getOwnerId() != null);
+
+ List<GraphVertex> derivedList = new ArrayList<>();
+ derivedList.add(newDerived);
+
+ Either<Map<String, T>, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedList, clazz, EdgeLabelEnum.CAPABILITIES);
+ if (dataFromDerived.isRight()) {
+ return dataFromDerived.right().value();
+ }
+ Map<String, T> capabiltiesAll = dataFromDerived.left().value();
+ capabiltiesAll.putAll(mapFromGraph);
+
+ Either<GraphVertex, TitanOperationStatus> updateDataV = updateOrCopyOnUpdate(dataV, nodeTypeV, label);
+ if (updateDataV.isRight()) {
+ return DaoStatusConverter.convertTitanStatusToStorageStatus(updateDataV.right().value());
+ }
+ return StorageOperationStatus.OK;
+ }
+
+ @Override
+ public <T extends ToscaElement> void fillToscaElementVertexData(GraphVertex elementV, T toscaElementToUpdate, JsonParseFlagEnum flag) {
+ fillMetadata(elementV, (NodeType) toscaElementToUpdate);
+ }
+
+}
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
new file mode 100644
index 0000000000..62d04edf4f
--- /dev/null
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/TopologyTemplateOperation.java
@@ -0,0 +1,1037 @@
+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 org.apache.tinkerpop.gremlin.structure.Direction;
+import org.apache.tinkerpop.gremlin.structure.Edge;
+import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
+import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
+import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
+import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
+import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.CompositionDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.MapArtifactDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.MapAttributesDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.MapCapabiltyProperty;
+import org.openecomp.sdc.be.datatypes.elements.MapGroupsDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.MapListCapabiltyDataDefinition;
+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.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.ComponentParametersView;
+import org.openecomp.sdc.be.model.DistributionStatusEnum;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.category.CategoryDefinition;
+import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate;
+import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement;
+import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum;
+import org.openecomp.sdc.be.model.jsontitan.enums.JsonConstantKeysEnum;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
+import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
+import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
+import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.gson.reflect.TypeToken;
+
+import fj.data.Either;
+
+@org.springframework.stereotype.Component("topology-template-operation")
+public class TopologyTemplateOperation extends ToscaElementOperation {
+ private static Logger log = LoggerFactory.getLogger(TopologyTemplateOperation.class.getName());
+
+ public Either<TopologyTemplate, StorageOperationStatus> createTopologyTemplate(TopologyTemplate topologyTemplate) {
+ Either<TopologyTemplate, StorageOperationStatus> result = null;
+
+ topologyTemplate.generateUUID();
+
+ topologyTemplate = (TopologyTemplate) getResourceMetaDataFromResource(topologyTemplate);
+ String resourceUniqueId = topologyTemplate.getUniqueId();
+ if (resourceUniqueId == null) {
+ resourceUniqueId = UniqueIdBuilder.buildResourceUniqueId();
+ topologyTemplate.setUniqueId(resourceUniqueId);
+ }
+
+ GraphVertex topologyTemplateVertex = new GraphVertex();
+ topologyTemplateVertex = fillMetadata(topologyTemplateVertex, topologyTemplate, JsonParseFlagEnum.ParseAll);
+
+ Either<GraphVertex, TitanOperationStatus> createdVertex = titanDao.createVertex(topologyTemplateVertex);
+ if (createdVertex.isRight()) {
+ TitanOperationStatus status = createdVertex.right().value();
+ log.error("Error returned after creating topology template data node {}. status returned is ", topologyTemplateVertex, status);
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ return result;
+ }
+
+ topologyTemplateVertex = createdVertex.left().value();
+
+ StorageOperationStatus assosiateCommon = assosiateCommonForToscaElement(topologyTemplateVertex, topologyTemplate, null);
+ if (assosiateCommon != StorageOperationStatus.OK) {
+ result = Either.right(assosiateCommon);
+ return result;
+ }
+
+ StorageOperationStatus associateCategory = assosiateMetadataToCategory(topologyTemplateVertex, topologyTemplate);
+ if (associateCategory != StorageOperationStatus.OK) {
+ result = Either.right(associateCategory);
+ return result;
+ }
+
+ StorageOperationStatus associateInputs = associateInputsToComponent(topologyTemplateVertex, topologyTemplate);
+ if (associateInputs != StorageOperationStatus.OK) {
+ result = Either.right(associateInputs);
+ return result;
+ }
+ StorageOperationStatus associateGroups = associateGroupsToComponent(topologyTemplateVertex, topologyTemplate);
+ if (associateGroups != StorageOperationStatus.OK) {
+ result = Either.right(associateGroups);
+ return result;
+ }
+ StorageOperationStatus associateInstAttr = associateInstAttributesToComponent(topologyTemplateVertex, topologyTemplate);
+ if (associateInstAttr != StorageOperationStatus.OK) {
+ result = Either.right(associateInstAttr);
+ return result;
+ }
+ StorageOperationStatus associateInstProperties = associateInstPropertiesToComponent(topologyTemplateVertex, topologyTemplate);
+ if (associateInstProperties != StorageOperationStatus.OK) {
+ result = Either.right(associateInstProperties);
+ return result;
+ }
+ StorageOperationStatus associateInstInputs = associateInstInputsToComponent(topologyTemplateVertex, topologyTemplate);
+ if (associateInstProperties != StorageOperationStatus.OK) {
+ result = Either.right(associateInstInputs);
+ return result;
+ }
+ StorageOperationStatus associateRequirements = associateRequirementsToResource(topologyTemplateVertex, topologyTemplate);
+ if (associateRequirements != StorageOperationStatus.OK) {
+ result = Either.right(associateRequirements);
+ return result;
+ }
+
+ StorageOperationStatus associateCapabilities = associateCapabilitiesToResource(topologyTemplateVertex, topologyTemplate);
+ if (associateCapabilities != StorageOperationStatus.OK) {
+ result = Either.right(associateCapabilities);
+ return result;
+ }
+
+ StorageOperationStatus associateArtifacts = associateTopologyTemplateArtifactsToComponent(topologyTemplateVertex, topologyTemplate);
+ if (associateArtifacts != StorageOperationStatus.OK) {
+ result = Either.right(associateArtifacts);
+ return result;
+ }
+
+ StorageOperationStatus addAdditionalInformation = addAdditionalInformationToResource(topologyTemplateVertex, topologyTemplate);
+ if (addAdditionalInformation != StorageOperationStatus.OK) {
+ result = Either.right(addAdditionalInformation);
+ return result;
+ }
+ StorageOperationStatus associateCapProperties = associateCapPropertiesToResource(topologyTemplateVertex, topologyTemplate);
+ if (associateCapProperties != StorageOperationStatus.OK) {
+ result = Either.right(associateCapProperties);
+ return result;
+ }
+ return Either.left(topologyTemplate);
+
+ }
+
+ private StorageOperationStatus associateCapPropertiesToResource(GraphVertex topologyTemplateVertex, TopologyTemplate topologyTemplate) {
+ Map<String, MapCapabiltyProperty> calculatedCapProperties = topologyTemplate.getCalculatedCapabilitiesProperties();
+ if (calculatedCapProperties != null && !calculatedCapProperties.isEmpty()) {
+ Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(topologyTemplateVertex, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, calculatedCapProperties);
+ if (assosiateElementToData.isRight()) {
+ return assosiateElementToData.right().value();
+ }
+ }
+ return StorageOperationStatus.OK;
+ }
+
+ private StorageOperationStatus associateCapabilitiesToResource(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) {
+ Map<String, MapListCapabiltyDataDefinition> calculatedCapabilities = topologyTemplate.getCalculatedCapabilities();
+ if (calculatedCapabilities != null && !calculatedCapabilities.isEmpty()) {
+ Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.CALCULATED_CAPABILITIES, EdgeLabelEnum.CALCULATED_CAPABILITIES, calculatedCapabilities);
+ if (assosiateElementToData.isRight()) {
+ return assosiateElementToData.right().value();
+ }
+ }
+ Map<String, MapListCapabiltyDataDefinition> fullfilledCapabilities = topologyTemplate.getFullfilledCapabilities();
+ if (fullfilledCapabilities != null && !fullfilledCapabilities.isEmpty()) {
+ Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.FULLFILLED_CAPABILITIES, EdgeLabelEnum.FULLFILLED_CAPABILITIES, fullfilledCapabilities);
+ if (assosiateElementToData.isRight()) {
+ return assosiateElementToData.right().value();
+ }
+ }
+ return StorageOperationStatus.OK;
+
+ }
+
+ private StorageOperationStatus associateRequirementsToResource(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) {
+ Map<String, MapListRequirementDataDefinition> calculatedRequirements = topologyTemplate.getCalculatedRequirements();
+ if (calculatedRequirements != null && !calculatedRequirements.isEmpty()) {
+ Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.CALCULATED_REQUIREMENTS, EdgeLabelEnum.CALCULATED_REQUIREMENTS, calculatedRequirements);
+ if (assosiateElementToData.isRight()) {
+ return assosiateElementToData.right().value();
+ }
+ }
+ Map<String, MapListRequirementDataDefinition> fullfilledRequirements = topologyTemplate.getFullfilledRequirements();
+ if (fullfilledRequirements != null && !fullfilledRequirements.isEmpty()) {
+ Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.FULLFILLED_REQUIREMENTS, EdgeLabelEnum.FULLFILLED_REQUIREMENTS, fullfilledRequirements);
+ if (assosiateElementToData.isRight()) {
+ return assosiateElementToData.right().value();
+ }
+ }
+ return StorageOperationStatus.OK;
+ }
+
+ private StorageOperationStatus associateTopologyTemplateArtifactsToComponent(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) {
+ Map<String, ArtifactDataDefinition> addInformation = topologyTemplate.getServiceApiArtifacts();
+
+ if (addInformation != null && !addInformation.isEmpty()) {
+ addInformation.values().stream().filter(a -> a.getUniqueId() == null).forEach(a -> {
+ String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(nodeTypeVertex.getUniqueId().toLowerCase(), a.getArtifactLabel().toLowerCase());
+ a.setUniqueId(uniqueId);
+ });
+ Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.SERVICE_API_ARTIFACTS, EdgeLabelEnum.SERVICE_API_ARTIFACTS, addInformation);
+ if (assosiateElementToData.isRight()) {
+ return assosiateElementToData.right().value();
+ }
+ }
+ Map<String, MapArtifactDataDefinition> instArtifacts = topologyTemplate.getInstDeploymentArtifacts();
+
+ if (instArtifacts != null && !instArtifacts.isEmpty()) {
+ Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS, instArtifacts);
+ if (assosiateElementToData.isRight()) {
+ return assosiateElementToData.right().value();
+ }
+ }
+ Map<String, MapArtifactDataDefinition> instInfoArtifacts = topologyTemplate.getInstanceArtifacts();
+
+ if (instInfoArtifacts != null && !instInfoArtifacts.isEmpty()) {
+ Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.INSTANCE_ARTIFACTS, EdgeLabelEnum.INSTANCE_ARTIFACTS, instInfoArtifacts);
+ if (assosiateElementToData.isRight()) {
+ return assosiateElementToData.right().value();
+ }
+ }
+ return StorageOperationStatus.OK;
+ }
+
+ private StorageOperationStatus addAdditionalInformationToResource(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) {
+
+ Map<String, AdditionalInfoParameterDataDefinition> addInformation = topologyTemplate.getAdditionalInformation();
+
+ if (addInformation != null && !addInformation.isEmpty()) {
+ Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.ADDITIONAL_INFORMATION, EdgeLabelEnum.ADDITIONAL_INFORMATION, addInformation);
+ if (assosiateElementToData.isRight()) {
+ return assosiateElementToData.right().value();
+ }
+ }
+ return StorageOperationStatus.OK;
+ }
+
+ public StorageOperationStatus associateInstPropertiesToComponent(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) {
+ Map<String, MapPropertiesDataDefinition> instProps = topologyTemplate.getInstProperties();
+ return associateInstPropertiesToComponent(nodeTypeVertex, instProps);
+ }
+
+ public StorageOperationStatus associateInstInputsToComponent(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) {
+ Map<String, MapPropertiesDataDefinition> instProps = topologyTemplate.getInstInputs();
+ return associateInstInputsToComponent(nodeTypeVertex, instProps);
+ }
+
+ public StorageOperationStatus associateInstPropertiesToComponent(GraphVertex nodeTypeVertex, Map<String, MapPropertiesDataDefinition> instProps) {
+ if (instProps != null && !instProps.isEmpty()) {
+ Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.INST_PROPERTIES, EdgeLabelEnum.INST_PROPERTIES, instProps);
+ if (assosiateElementToData.isRight()) {
+ return assosiateElementToData.right().value();
+ }
+ }
+ return StorageOperationStatus.OK;
+ }
+
+ public StorageOperationStatus associateInstInputsToComponent(GraphVertex nodeTypeVertex, Map<String, MapPropertiesDataDefinition> instInputs) {
+ if (instInputs != null && !instInputs.isEmpty()) {
+ Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.INST_INPUTS, EdgeLabelEnum.INST_INPUTS, instInputs);
+ if (assosiateElementToData.isRight()) {
+ return assosiateElementToData.right().value();
+ }
+ }
+ return StorageOperationStatus.OK;
+ }
+
+ public StorageOperationStatus addInstInputsToComponent(GraphVertex nodeTypeVertex, Map<String, MapPropertiesDataDefinition> instInputs) {
+
+ if (instInputs != null && !instInputs.isEmpty()) {
+ instInputs.entrySet().forEach(i -> {
+ StorageOperationStatus status = addToscaDataDeepElementsBlockToToscaElement(nodeTypeVertex, EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, i.getValue(), i.getKey());
+ if (status != StorageOperationStatus.OK) {
+ return;
+ }
+ });
+ }
+
+ return StorageOperationStatus.OK;
+ }
+
+ public StorageOperationStatus deleteInstInputsToComponent(GraphVertex nodeTypeVertex, Map<String, MapPropertiesDataDefinition> instInputs) {
+
+ if (instInputs != null && !instInputs.isEmpty()) {
+ instInputs.entrySet().forEach(i -> {
+ List<String> uniqueKeys = new ArrayList<String>(i.getValue().getMapToscaDataDefinition().keySet());
+ List<String> pathKeys = new ArrayList<String>();
+ pathKeys.add(i.getKey());
+
+ StorageOperationStatus status = deleteToscaDataDeepElements(nodeTypeVertex, EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, uniqueKeys, pathKeys, JsonPresentationFields.NAME);
+ if (status != StorageOperationStatus.OK) {
+ return;
+ }
+ });
+ }
+
+ return StorageOperationStatus.OK;
+ }
+
+ public StorageOperationStatus addInstPropertiesToComponent(GraphVertex nodeTypeVertex, Map<String, MapPropertiesDataDefinition> instInputs) {
+
+ if (instInputs != null && !instInputs.isEmpty()) {
+ instInputs.entrySet().forEach(i -> {
+ StorageOperationStatus status = addToscaDataDeepElementsBlockToToscaElement(nodeTypeVertex, EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES, i.getValue(), i.getKey());
+ if (status != StorageOperationStatus.OK) {
+ return;
+ }
+ });
+ }
+
+ return StorageOperationStatus.OK;
+ }
+
+ public StorageOperationStatus associateInstArtifactToComponent(GraphVertex nodeTypeVertex, Map<String, MapArtifactDataDefinition> instProps) {
+ if (instProps != null && !instProps.isEmpty()) {
+ Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS, instProps);
+ if (assosiateElementToData.isRight()) {
+ return assosiateElementToData.right().value();
+ }
+ }
+ return StorageOperationStatus.OK;
+ }
+
+ public StorageOperationStatus associateCalcCapReqToComponent(GraphVertex nodeTypeVertex, Map<String, MapListRequirementDataDefinition> calcRequirements, Map<String, MapListCapabiltyDataDefinition> calcCapabilty, Map<String, MapCapabiltyProperty> calculatedCapabilitiesProperties) {
+ if (calcRequirements != null && !calcRequirements.isEmpty()) {
+ Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.CALCULATED_REQUIREMENTS, EdgeLabelEnum.CALCULATED_REQUIREMENTS, calcRequirements);
+ if (assosiateElementToData.isRight()) {
+ return assosiateElementToData.right().value();
+ }
+ Map<String, MapListRequirementDataDefinition> fullFilled = new HashMap<>();
+ assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.FULLFILLED_REQUIREMENTS, EdgeLabelEnum.FULLFILLED_REQUIREMENTS, fullFilled);
+ if (assosiateElementToData.isRight()) {
+ return assosiateElementToData.right().value();
+ }
+ }
+ if (calcCapabilty != null && !calcCapabilty.isEmpty()) {
+ Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.CALCULATED_CAPABILITIES, EdgeLabelEnum.CALCULATED_CAPABILITIES, calcCapabilty);
+ if (assosiateElementToData.isRight()) {
+ return assosiateElementToData.right().value();
+ }
+ Map<String, MapListCapabiltyDataDefinition> fullFilled = new HashMap<>();
+ assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.FULLFILLED_CAPABILITIES, EdgeLabelEnum.FULLFILLED_CAPABILITIES, fullFilled);
+ if (assosiateElementToData.isRight()) {
+ return assosiateElementToData.right().value();
+ }
+ }
+ if ( calculatedCapabilitiesProperties != null && !calculatedCapabilitiesProperties.isEmpty() ){
+ Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, calculatedCapabilitiesProperties);
+ if (assosiateElementToData.isRight()) {
+ return assosiateElementToData.right().value();
+ }
+ }
+ return StorageOperationStatus.OK;
+ }
+
+ private StorageOperationStatus associateInstAttributesToComponent(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) {
+ Map<String, MapAttributesDataDefinition> instAttr = topologyTemplate.getInstAttributes();
+ return associateInstAttributeToComponent(nodeTypeVertex, instAttr);
+ }
+
+ public StorageOperationStatus associateInstAttributeToComponent(GraphVertex nodeTypeVertex, Map<String, MapAttributesDataDefinition> instAttr) {
+ if (instAttr != null && !instAttr.isEmpty()) {
+ Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.INST_ATTRIBUTES, EdgeLabelEnum.INST_ATTRIBUTES, instAttr);
+ if (assosiateElementToData.isRight()) {
+ return assosiateElementToData.right().value();
+ }
+ }
+ return StorageOperationStatus.OK;
+ }
+
+ public StorageOperationStatus associateGroupsToComponent(GraphVertex nodeTypeVertex, Map<String, GroupDataDefinition> groups) {
+
+ if (groups != null && !groups.isEmpty()) {
+ groups.values().stream().filter(p -> p.getUniqueId() == null).forEach(p -> {
+ String uid = UniqueIdBuilder.buildGroupingUid(nodeTypeVertex.getUniqueId(), p.getName());
+ p.setUniqueId(uid);
+ });
+ Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.GROUPS, EdgeLabelEnum.GROUPS, groups);
+ if (assosiateElementToData.isRight()) {
+ return assosiateElementToData.right().value();
+ }
+ }
+ return StorageOperationStatus.OK;
+ }
+
+ private StorageOperationStatus associateGroupsToComponent(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) {
+ return associateGroupsToComponent(nodeTypeVertex, topologyTemplate.getGroups());
+ }
+
+ public StorageOperationStatus associateInputsToComponent(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) {
+ Map<String, PropertyDataDefinition> inputs = topologyTemplate.getInputs();
+ return associateInputsToComponent(nodeTypeVertex, inputs, topologyTemplate.getUniqueId());
+ }
+
+ public StorageOperationStatus associateInputsToComponent(GraphVertex nodeTypeVertex, Map<String, PropertyDataDefinition> inputs, String id) {
+ if (inputs != null && !inputs.isEmpty()) {
+ inputs.values().stream().filter(e -> e.getUniqueId() == null).forEach(e -> e.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(id, e.getName())));
+
+ Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.INPUTS, EdgeLabelEnum.INPUTS, inputs);
+ if (assosiateElementToData.isRight()) {
+ return assosiateElementToData.right().value();
+ }
+ }
+ return StorageOperationStatus.OK;
+ }
+
+ private GraphVertex fillMetadata(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate, JsonParseFlagEnum flag) {
+ nodeTypeVertex.setLabel(VertexTypeEnum.TOPOLOGY_TEMPLATE);
+ fillCommonMetadata(nodeTypeVertex, topologyTemplate);
+ if (flag == JsonParseFlagEnum.ParseAll || flag == JsonParseFlagEnum.ParseJson) {
+ nodeTypeVertex.setJson(topologyTemplate.getCompositions());
+ }
+ nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.CSAR_UUID, topologyTemplate.getMetadataValue(JsonPresentationFields.CSAR_UUID));
+ nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.DISTRIBUTION_STATUS, topologyTemplate.getMetadataValue(JsonPresentationFields.DISTRIBUTION_STATUS));
+
+ return nodeTypeVertex;
+
+ }
+
+ private StorageOperationStatus assosiateMetadataToCategory(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) {
+ if (topologyTemplate.getResourceType() == null) {
+ // service
+ return associateServiceMetadataToCategory(nodeTypeVertex, topologyTemplate);
+ } else {
+ // VF
+ return assosiateResourceMetadataToCategory(nodeTypeVertex, topologyTemplate);
+ }
+ }
+
+ private StorageOperationStatus associateServiceMetadataToCategory(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) {
+ String categoryName = topologyTemplate.getCategories().get(0).getName();
+ Either<GraphVertex, StorageOperationStatus> category = categoryOperation.getCategory(categoryName, VertexTypeEnum.SERVICE_CATEGORY);
+ if (category.isRight()) {
+ log.trace("NO category {} for service {}", categoryName, topologyTemplate.getUniqueId());
+ return StorageOperationStatus.CATEGORY_NOT_FOUND;
+ }
+ GraphVertex categoryV = category.left().value();
+ TitanOperationStatus createEdge = titanDao.createEdge(nodeTypeVertex, categoryV, EdgeLabelEnum.CATEGORY, new HashMap<>());
+ if (createEdge != TitanOperationStatus.OK) {
+ log.trace("Failed to associate resource {} to category {} with id {}", topologyTemplate.getUniqueId(), categoryName, categoryV.getUniqueId());
+ return DaoStatusConverter.convertTitanStatusToStorageStatus(createEdge);
+ }
+ return StorageOperationStatus.OK;
+ }
+
+ @Override
+ public Either<ToscaElement, StorageOperationStatus> getToscaElement(String uniqueId, ComponentParametersView componentParametersView) {
+ JsonParseFlagEnum parseFlag = componentParametersView.detectParseFlag();
+
+ Either<GraphVertex, StorageOperationStatus> componentByLabelAndId = getComponentByLabelAndId(uniqueId, ToscaElementTypeEnum.TopologyTemplate, parseFlag);
+ if (componentByLabelAndId.isRight()) {
+ return Either.right(componentByLabelAndId.right().value());
+ }
+ GraphVertex componentV = componentByLabelAndId.left().value();
+
+ return getToscaElement(componentV, componentParametersView);
+
+ }
+ // -------------------------------------------------------------
+
+ public Either<ToscaElement, StorageOperationStatus> getToscaElement(GraphVertex componentV, ComponentParametersView componentParametersView) {
+ TopologyTemplate toscaElement;
+
+ toscaElement = convertToTopologyTemplate(componentV);
+ TitanOperationStatus status = null;
+ if (false == componentParametersView.isIgnoreUsers()) {
+ status = setCreatorFromGraph(componentV, toscaElement);
+ if (status != TitanOperationStatus.OK) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+
+ status = setLastModifierFromGraph(componentV, toscaElement);
+ if (status != TitanOperationStatus.OK) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ }
+ if (false == componentParametersView.isIgnoreCategories()) {
+ status = setTopologyTempalteCategoriesFromGraph(componentV, toscaElement);
+ if (status != TitanOperationStatus.OK) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+
+ }
+ }
+ if (false == componentParametersView.isIgnoreArtifacts()) {
+ TitanOperationStatus storageStatus = setAllArtifactsFromGraph(componentV, toscaElement);
+ if (storageStatus != TitanOperationStatus.OK) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(storageStatus));
+ }
+ }
+ if (false == componentParametersView.isIgnoreComponentInstancesProperties()) {
+ status = setComponentInstancesPropertiesFromGraph(componentV, toscaElement);
+ if (status != TitanOperationStatus.OK) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ }
+ if (false == componentParametersView.isIgnoreCapabilities()) {
+ status = setCapabilitiesFromGraph(componentV, toscaElement);
+ if (status != TitanOperationStatus.OK) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ }
+ if (false == componentParametersView.isIgnoreRequirements()) {
+ status = setRequirementsFromGraph(componentV, toscaElement);
+ if (status != TitanOperationStatus.OK) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ }
+ if (false == componentParametersView.isIgnoreAllVersions()) {
+ status = setAllVersions(componentV, toscaElement);
+ if (status != TitanOperationStatus.OK) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ }
+ if (false == componentParametersView.isIgnoreAdditionalInformation()) {
+ status = setAdditionalInformationFromGraph(componentV, toscaElement);
+ if (status != TitanOperationStatus.OK) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ }
+
+ if (false == componentParametersView.isIgnoreGroups()) {
+ status = setGroupsFromGraph(componentV, toscaElement);
+ if (status != TitanOperationStatus.OK) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+
+ }
+ if (false == componentParametersView.isIgnoreComponentInstances()) {
+ status = setInstGroupsFromGraph(componentV, toscaElement);
+ if (status != TitanOperationStatus.OK) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+
+ }
+ if (false == componentParametersView.isIgnoreInputs()) {
+ status = setInputsFromGraph(componentV, toscaElement);
+ if (status != TitanOperationStatus.OK) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+
+ }
+ if (false == componentParametersView.isIgnoreProperties()) {
+ status = setPropertiesFromGraph(componentV, toscaElement);
+ if (status != TitanOperationStatus.OK) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+
+ }
+
+ if (false == componentParametersView.isIgnoreComponentInstancesInputs()) {
+ status = setComponentInstancesInputsFromGraph(componentV, toscaElement);
+ if (status != TitanOperationStatus.OK) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+
+ }
+ }
+
+ if (false == componentParametersView.isIgnoreCapabiltyProperties()) {
+ status = setComponentInstancesCapPropertiesFromGraph(componentV, toscaElement);
+ if (status != TitanOperationStatus.OK) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+
+ }
+ }
+ return Either.left(toscaElement);
+ }
+
+ private TitanOperationStatus setComponentInstancesCapPropertiesFromGraph(GraphVertex componentV, TopologyTemplate topologyTemplate) {
+ Either<Map<String, MapCapabiltyProperty>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES);
+ if (result.isLeft()) {
+ topologyTemplate.setCalculatedCapabilitiesProperties(result.left().value());
+ } else {
+ if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
+ return result.right().value();
+ }
+ }
+ return TitanOperationStatus.OK;
+ }
+
+ private TitanOperationStatus setPropertiesFromGraph(GraphVertex componentV, TopologyTemplate toscaElement) {
+ Either<Map<String, PropertyDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.PROPERTIES);
+ if (result.isLeft()) {
+ toscaElement.setProperties(result.left().value());
+ } else {
+ if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
+ return result.right().value();
+ }
+ }
+ return TitanOperationStatus.OK;
+ }
+
+ private TitanOperationStatus setInstGroupsFromGraph(GraphVertex componentV, TopologyTemplate topologyTemplate) {
+ Either<Map<String, MapGroupsDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.INST_GROUPS);
+ if (result.isLeft()) {
+ topologyTemplate.setInstGroups(result.left().value());
+ } else {
+ if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
+ return result.right().value();
+ }
+ }
+ return TitanOperationStatus.OK;
+ }
+
+ private TitanOperationStatus setComponentInstancesPropertiesFromGraph(GraphVertex componentV, TopologyTemplate topologyTemplate) {
+ Either<Map<String, MapPropertiesDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.INST_PROPERTIES);
+ if (result.isLeft()) {
+ topologyTemplate.setInstProperties(result.left().value());
+ } else {
+ if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
+ return result.right().value();
+ }
+ }
+ return TitanOperationStatus.OK;
+ }
+
+ private TitanOperationStatus setComponentInstancesInputsFromGraph(GraphVertex componentV, TopologyTemplate topologyTemplate) {
+ Either<Map<String, MapPropertiesDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.INST_INPUTS);
+ if (result.isLeft()) {
+ topologyTemplate.setInstInputs(result.left().value());
+ } else {
+ if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
+ return result.right().value();
+ }
+ }
+ return TitanOperationStatus.OK;
+ }
+
+ @Override
+ protected <T extends ToscaElement> TitanOperationStatus setRequirementsFromGraph(GraphVertex componentV, T toscaElement) {
+ Either<Map<String, MapListRequirementDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.CALCULATED_REQUIREMENTS);
+ if (result.isLeft()) {
+ ((TopologyTemplate) toscaElement).setCalculatedRequirements(result.left().value());
+ } else {
+ if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
+ return result.right().value();
+ }
+ }
+ result = getDataFromGraph(componentV, EdgeLabelEnum.FULLFILLED_REQUIREMENTS);
+ if (result.isLeft()) {
+ ((TopologyTemplate) toscaElement).setFullfilledRequirements(result.left().value());
+ } else {
+ if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
+ return result.right().value();
+ }
+ }
+ return TitanOperationStatus.OK;
+
+ }
+
+ protected <T extends ToscaElement> TitanOperationStatus setCapabilitiesFromGraph(GraphVertex componentV, T toscaElement) {
+ Either<Map<String, MapListCapabiltyDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.CALCULATED_CAPABILITIES);
+ if (result.isLeft()) {
+ ((TopologyTemplate) toscaElement).setCalculatedCapabilities(result.left().value());
+ } else {
+ if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
+ return result.right().value();
+ }
+ }
+ result = getDataFromGraph(componentV, EdgeLabelEnum.FULLFILLED_CAPABILITIES);
+ if (result.isLeft()) {
+ ((TopologyTemplate) toscaElement).setFullfilledCapabilities(result.left().value());
+ } else {
+ if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
+ return result.right().value();
+ }
+ }
+ return TitanOperationStatus.OK;
+ }
+
+ private TitanOperationStatus setAllArtifactsFromGraph(GraphVertex componentV, TopologyTemplate toscaElement) {
+ TitanOperationStatus storageStatus = setArtifactsFromGraph(componentV, toscaElement);
+ if (storageStatus != TitanOperationStatus.OK) {
+ return storageStatus;
+ }
+ Either<Map<String, ArtifactDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.SERVICE_API_ARTIFACTS);
+ if (result.isLeft()) {
+ toscaElement.setServiceApiArtifacts(result.left().value());
+ } else {
+ if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
+ return result.right().value();
+ }
+ }
+ Either<Map<String, MapArtifactDataDefinition>, TitanOperationStatus> resultInstArt = getDataFromGraph(componentV, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS);
+ if (resultInstArt.isLeft()) {
+ toscaElement.setInstDeploymentArtifacts(resultInstArt.left().value());
+ } else {
+ if (resultInstArt.right().value() != TitanOperationStatus.NOT_FOUND) {
+ return resultInstArt.right().value();
+ }
+ }
+ Either<Map<String, MapArtifactDataDefinition>, TitanOperationStatus> instanceArt = getDataFromGraph(componentV, EdgeLabelEnum.INSTANCE_ARTIFACTS);
+ if (instanceArt.isLeft()) {
+ toscaElement.setInstanceArtifacts(instanceArt.left().value());
+ } else {
+ if (instanceArt.right().value() != TitanOperationStatus.NOT_FOUND) {
+ return instanceArt.right().value();
+ }
+ }
+ return TitanOperationStatus.OK;
+ }
+
+ private TitanOperationStatus setInputsFromGraph(GraphVertex componentV, TopologyTemplate toscaElement) {
+ Either<Map<String, PropertyDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.INPUTS);
+ if (result.isLeft()) {
+ toscaElement.setInputs(result.left().value());
+ } else {
+ if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
+ return result.right().value();
+ }
+ }
+ return TitanOperationStatus.OK;
+ }
+
+ private TitanOperationStatus setGroupsFromGraph(GraphVertex componentV, TopologyTemplate toscaElement) {
+ Either<Map<String, GroupDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.GROUPS);
+ if (result.isLeft()) {
+ toscaElement.setGroups(result.left().value());
+ } else {
+ if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
+ return result.right().value();
+ }
+ }
+ return TitanOperationStatus.OK;
+ }
+
+ private TitanOperationStatus setTopologyTempalteCategoriesFromGraph(GraphVertex componentV, ToscaElement toscaElement) {
+ List<CategoryDefinition> categories = new ArrayList<>();
+
+ switch (componentV.getType()) {
+ case RESOURCE:
+ return setResourceCategoryFromGraph(componentV, toscaElement);
+ case SERVICE:
+ return setServiceCategoryFromGraph(componentV, toscaElement, categories);
+
+ default:
+ log.debug("Not supported component type {} ", componentV.getType());
+ break;
+ }
+ return TitanOperationStatus.OK;
+ }
+
+ private TitanOperationStatus setServiceCategoryFromGraph(GraphVertex componentV, ToscaElement toscaElement, List<CategoryDefinition> categories) {
+ 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 categoryV = childVertex.left().value();
+ Map<GraphPropertyEnum, Object> metadataProperties = categoryV.getMetadataProperties();
+ CategoryDefinition category = new CategoryDefinition();
+ category.setUniqueId((String) metadataProperties.get(GraphPropertyEnum.UNIQUE_ID));
+ 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.getProperty()), listTypeCat);
+ category.setIcons(iconsfromJsonCat);
+ categories.add(category);
+ toscaElement.setCategories(categories);
+
+ return TitanOperationStatus.OK;
+ }
+
+ private TopologyTemplate convertToTopologyTemplate(GraphVertex componentV) {
+
+ TopologyTemplate topologyTemplate = super.convertToComponent(componentV);
+
+ Map<String, CompositionDataDefinition> json = (Map<String, CompositionDataDefinition>) componentV.getJson();
+ topologyTemplate.setCompositions(json);
+
+ return topologyTemplate;
+ }
+
+ @Override
+ public Either<ToscaElement, StorageOperationStatus> deleteToscaElement(GraphVertex toscaElementVertex) {
+ Either<ToscaElement, StorageOperationStatus> nodeType = getToscaElement(toscaElementVertex, new ComponentParametersView());
+ if (nodeType.isRight()) {
+ log.debug("Failed to fetch tosca element {} error {}", toscaElementVertex.getUniqueId(), nodeType.right().value());
+ return nodeType;
+ }
+ TitanOperationStatus status = disassociateAndDeleteCommonElements(toscaElementVertex);
+ if (status != TitanOperationStatus.OK) {
+ Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_ATTRIBUTES);
+ if (status != TitanOperationStatus.OK) {
+ log.debug("Failed to disassociate instances attributes for {} error {}", toscaElementVertex.getUniqueId(), status);
+ Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_PROPERTIES);
+ if (status != TitanOperationStatus.OK) {
+ log.debug("Failed to disassociate instances properties for {} error {}", toscaElementVertex.getUniqueId(), status);
+ Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+
+ status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_INPUTS);
+ if (status != TitanOperationStatus.OK) {
+ log.debug("Failed to disassociate instances inputs for {} error {}", toscaElementVertex.getUniqueId(), status);
+ Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+
+ status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.GROUPS);
+ if (status != TitanOperationStatus.OK) {
+ log.debug("Failed to disassociate groups for {} error {}", toscaElementVertex.getUniqueId(), status);
+ Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_GROUPS);
+ if (status != TitanOperationStatus.OK) {
+ log.debug("Failed to disassociate instance groups for {} error {}", toscaElementVertex.getUniqueId(), status);
+ Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INPUTS);
+ if (status != TitanOperationStatus.OK) {
+ log.debug("Failed to disassociate inputs for {} error {}", toscaElementVertex.getUniqueId(), status);
+ Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_INPUTS);
+ if (status != TitanOperationStatus.OK) {
+ log.debug("Failed to disassociate instance inputs for {} error {}", toscaElementVertex.getUniqueId(), status);
+ Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CALCULATED_CAPABILITIES);
+ if (status != TitanOperationStatus.OK) {
+ log.debug("Failed to disassociate calculated capabiliites for {} error {}", toscaElementVertex.getUniqueId(), status);
+ Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.FULLFILLED_CAPABILITIES);
+ if (status != TitanOperationStatus.OK) {
+ log.debug("Failed to disassociate fullfilled capabilities for {} error {}", toscaElementVertex.getUniqueId(), status);
+ Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES);
+ if (status != TitanOperationStatus.OK) {
+ log.debug("Failed to disassociate calculated capabiliites properties for {} error {}", toscaElementVertex.getUniqueId(), status);
+ Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CALCULATED_REQUIREMENTS);
+ if (status != TitanOperationStatus.OK) {
+ log.debug("Failed to disassociate calculated requirements for {} error {}", toscaElementVertex.getUniqueId(), status);
+ Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.FULLFILLED_REQUIREMENTS);
+ if (status != TitanOperationStatus.OK) {
+ log.debug("Failed to disassociate full filled requirements for {} error {}", toscaElementVertex.getUniqueId(), status);
+ Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS);
+ if (status != TitanOperationStatus.OK) {
+ log.debug("Failed to disassociate instance artifacts for {} error {}", toscaElementVertex.getUniqueId(), status);
+ Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.SERVICE_API_ARTIFACTS);
+ if (status != TitanOperationStatus.OK) {
+ log.debug("Failed to disassociate service api artifacts for {} error {}", toscaElementVertex.getUniqueId(), status);
+ 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());
+
+ return nodeType;
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public Either<TopologyTemplate, StorageOperationStatus> createToscaElement(ToscaElement toscaElement) {
+ return createTopologyTemplate((TopologyTemplate) toscaElement);
+ }
+
+ @Override
+ protected <T extends ToscaElement> TitanOperationStatus setCategoriesFromGraph(GraphVertex vertexComponent, T toscaElement) {
+ return setTopologyTempalteCategoriesFromGraph(vertexComponent, toscaElement);
+ }
+
+ @Override
+ protected <T extends ToscaElement> StorageOperationStatus validateCategories(T toscaElementToUpdate, GraphVertex elementV) {
+ // Product isn't supported now!!
+ // TODO add for Product
+ if (toscaElementToUpdate.getComponentType() == ComponentTypeEnum.SERVICE) {
+ return validateServiceCategory(toscaElementToUpdate, elementV);
+ } else {
+ // Resource
+ return validateResourceCategory(toscaElementToUpdate, elementV);
+ }
+ }
+
+ @Override
+ protected <T extends ToscaElement> StorageOperationStatus updateDerived(T toscaElementToUpdate, GraphVertex updateElementV) {
+ // not relevant now for topology template
+ return StorageOperationStatus.OK;
+ }
+
+ @Override
+ public <T extends ToscaElement> void fillToscaElementVertexData(GraphVertex elementV, T toscaElementToUpdate, JsonParseFlagEnum flag) {
+ fillMetadata(elementV, (TopologyTemplate) toscaElementToUpdate, flag);
+ }
+
+ private <T extends ToscaElement> StorageOperationStatus validateServiceCategory(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 categoryV = childVertex.left().value();
+ Map<GraphPropertyEnum, Object> metadataProperties = categoryV.getMetadataProperties();
+ String categoryNameCurrent = (String) metadataProperties.get(GraphPropertyEnum.NAME);
+
+ String newCategoryName = newCategory.getName();
+ if (newCategoryName != null && false == newCategoryName.equals(categoryNameCurrent)) {
+ // the category was changed
+ Either<GraphVertex, StorageOperationStatus> getCategoryVertex = categoryOperation.getCategory(newCategoryName, VertexTypeEnum.SERVICE_CATEGORY);
+
+ if (getCategoryVertex.isRight()) {
+ return getCategoryVertex.right().value();
+ }
+ GraphVertex newCategoryV = getCategoryVertex.left().value();
+ status = moveCategoryEdge(elementV, newCategoryV);
+ log.debug("Going to update the category of the resource from {} to {}. status is {}", categoryNameCurrent, newCategory, status);
+ }
+ return status;
+ }
+
+ public Either<List<GraphVertex>, TitanOperationStatus> getAllNotDeletedElements() {
+ Map<GraphPropertyEnum, Object> propsHasNot = new HashMap<>();
+ propsHasNot.put(GraphPropertyEnum.IS_DELETED, true);
+
+ Either<List<GraphVertex>, TitanOperationStatus> byCriteria = titanDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, null, propsHasNot, JsonParseFlagEnum.ParseJson);
+ if (byCriteria.isRight()) {
+ log.debug("Failed to fetch all non marked topology templates , propsHasNot {}, error {}", propsHasNot, byCriteria.right().value());
+ return Either.right(byCriteria.right().value());
+ }
+ return Either.left(byCriteria.left().value());
+ }
+
+ public boolean isInUse(GraphVertex elementV, List<GraphVertex> allNonDeleted) {
+ for (GraphVertex containerV : allNonDeleted) {
+ Map<String, CompositionDataDefinition> composition = (Map<String, CompositionDataDefinition>) containerV.getJson();
+ if (composition != null) {
+ CompositionDataDefinition instances = composition.get(JsonConstantKeysEnum.COMPOSITION.getValue());
+ if (instances != null && instances.getComponentInstances() != null && !instances.getComponentInstances().isEmpty()) {
+ for (ComponentInstanceDataDefinition ci : instances.getComponentInstances().values()) {
+ if (ci.getComponentUid().equals(elementV.getUniqueId())) {
+ return true;
+ }
+ }
+
+ }
+ }
+ }
+
+ return false;
+ }
+
+ public boolean isInUse(String componentId, List<GraphVertex> allNonDeleted) {
+ for (GraphVertex containerV : allNonDeleted) {
+ Map<String, CompositionDataDefinition> composition = (Map<String, CompositionDataDefinition>) containerV.getJson();
+ if (composition != null) {
+ CompositionDataDefinition instances = composition.get(JsonConstantKeysEnum.COMPOSITION.getValue());
+ if (instances != null && instances.getComponentInstances() != null && !instances.getComponentInstances().isEmpty()) {
+ for (ComponentInstanceDataDefinition ci : instances.getComponentInstances().values()) {
+ if (ci.getComponentUid().equals(componentId)) {
+ return true;
+ }
+ }
+
+ }
+ }
+ }
+
+ return false;
+ }
+
+ public Either<GraphVertex, StorageOperationStatus> updateDistributionStatus(String uniqueId, User user, DistributionStatusEnum distributionStatus) {
+
+ Either<GraphVertex, StorageOperationStatus> result = null;
+ String userId = user.getUserId();
+ Either<GraphVertex, TitanOperationStatus> getRes = findUserVertex(userId);
+ GraphVertex userVertex = null;
+ GraphVertex serviceVertex = null;
+ if (getRes.isRight()) {
+ TitanOperationStatus status = getRes.right().value();
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Cannot find user {} in the graph. status is {}", userId, status);
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ if (result == null) {
+ userVertex = getRes.left().value();
+ getRes = titanDao.getVertexById(uniqueId, JsonParseFlagEnum.ParseMetadata);
+ if (getRes.isRight()) {
+ TitanOperationStatus status = getRes.right().value();
+ log.error("Cannot find service {} in the graph. status is {}", uniqueId, status);
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ }
+ if (result == null) {
+ serviceVertex = getRes.left().value();
+ Iterator<Edge> edgeIterator = serviceVertex.getVertex().edges(Direction.IN, EdgeLabelEnum.LAST_DISTRIBUTION_STATE_MODIFIER.name());
+ if (edgeIterator.hasNext()) {
+ log.debug("Remove existing edge from user to component {}. Edge type is {}", userId, uniqueId, EdgeLabelEnum.LAST_DISTRIBUTION_STATE_MODIFIER);
+ edgeIterator.next().remove();
+ }
+ }
+ if (result == null) {
+ TitanOperationStatus status = titanDao.createEdge(userVertex, serviceVertex, EdgeLabelEnum.LAST_DISTRIBUTION_STATE_MODIFIER, null);
+ if (status != TitanOperationStatus.OK) {
+ log.error("Failed to associate user {} to component {}. Edge type is {}", userId, uniqueId, EdgeLabelEnum.LAST_DISTRIBUTION_STATE_MODIFIER);
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ }
+ if (result == null) {
+ serviceVertex.addMetadataProperty(GraphPropertyEnum.DISTRIBUTION_STATUS, distributionStatus.name());
+ long lastUpdateDate = System.currentTimeMillis();
+ serviceVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, lastUpdateDate);
+ Either<GraphVertex, TitanOperationStatus> updateRes = titanDao.updateVertex(serviceVertex);
+ if (updateRes.isRight()) {
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateRes.right().value()));
+ }
+ }
+ if (result == null) {
+ result = Either.left(serviceVertex);
+ }
+ return result;
+ }
+
+}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaDataOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaDataOperation.java
new file mode 100644
index 0000000000..27b296d3f2
--- /dev/null
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaDataOperation.java
@@ -0,0 +1,11 @@
+package org.openecomp.sdc.be.model.jsontitan.operations;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@org.springframework.stereotype.Component("tosca-data-operation")
+public class ToscaDataOperation extends BaseOperation {
+
+ private static Logger logger = LoggerFactory.getLogger(ToscaDataOperation.class.getName());
+
+}
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
new file mode 100644
index 0000000000..be995089a9
--- /dev/null
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementLifecycleOperation.java
@@ -0,0 +1,1192 @@
+package org.openecomp.sdc.be.model.jsontitan.operations;
+
+import java.util.EnumMap;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+import org.apache.commons.collections.CollectionUtils;
+import org.apache.commons.collections.MapUtils;
+import org.apache.commons.lang.StringUtils;
+import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.apache.tinkerpop.gremlin.structure.Direction;
+import org.apache.tinkerpop.gremlin.structure.Edge;
+import org.apache.tinkerpop.gremlin.structure.Vertex;
+import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
+import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
+import org.openecomp.sdc.be.dao.jsongraph.types.EdgePropertyEnum;
+import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
+import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
+import org.openecomp.sdc.be.dao.jsongraph.utils.IdBuilderUtils;
+import org.openecomp.sdc.be.dao.jsongraph.utils.JsonParserUtils;
+import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
+import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.openecomp.sdc.be.datatypes.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.ComponentParametersView;
+import org.openecomp.sdc.be.model.DistributionStatusEnum;
+import org.openecomp.sdc.be.model.LifecycleStateEnum;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
+import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
+import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
+import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import fj.data.Either;
+
+@org.springframework.stereotype.Component("tosca-element-lifecycle-operation")
+
+/**
+ * Allows to perform lifecycle operations:
+ * checkin, checkout, submit for testing, start certification and certification process
+ * for tosca element
+ */
+public class ToscaElementLifecycleOperation extends BaseOperation {
+
+ private static final String FAILED_TO_GET_VERTICES = "Failed to get vertices by id {}. Status is {}. ";
+ public static final String VERSION_DELIMETER = ".";
+ public static final String VERSION_DELIMETER_REGEXP = "\\.";
+
+ private static Logger logger = LoggerFactory.getLogger(ToscaElementLifecycleOperation.class.getName());
+
+ /**
+ * Performs changing a lifecycle state of tosca element from "checked out" or "ready for certification" to "checked in"
+ * @param currState
+ * @param toscaElementId
+ * @param modifierId
+ * @param ownerId
+ * @return
+ */
+ public Either<ToscaElement, StorageOperationStatus> checkinToscaELement(LifecycleStateEnum currState, String toscaElementId, String modifierId, String ownerId) {
+ Either<GraphVertex, StorageOperationStatus> updateResult = null;
+ Either<ToscaElement, StorageOperationStatus> result = null;
+ Map<String, GraphVertex> vertices = null;
+ ToscaElementOperation operation;
+ try {
+ Either<Map<String, GraphVertex>, TitanOperationStatus> getVerticesRes =
+ titanDao.getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForCheckin(toscaElementId, modifierId, ownerId));
+ if(getVerticesRes.isRight()){
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId);
+ updateResult = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVerticesRes.right().value()));
+ } else {
+ vertices = getVerticesRes.left().value();
+ updateResult = checkinToscaELement(currState, vertices.get(toscaElementId), vertices.get(ownerId), vertices.get(modifierId), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
+ }
+ if(updateResult.isLeft()) {
+ ComponentParametersView componentParametersView = buildComponentParametersViewAfterCheckin();
+ operation = getToscaElementOperation(vertices.get(toscaElementId).getLabel());
+ result = operation.getToscaElement(updateResult.left().value().getUniqueId(), componentParametersView);
+ if(result.isRight()){
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG,"Failed to get updated tosca element {}. Status is {}", toscaElementId, result.right().value());
+ }
+ } else {
+ result = Either.right(updateResult.right().value());
+ }
+ } catch (Exception e){
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG,"Exception occured during checkin of tosca element {}. {} ", toscaElementId, e.getMessage());
+ }
+ return result;
+ }
+ /**
+ * Returns vertex presenting owner of tosca element specified by uniqueId
+ * @param toscaElement
+ * @return
+ */
+ public Either<User, StorageOperationStatus> getToscaElementOwner(String toscaElementId) {
+ Either<User, StorageOperationStatus> result = null;
+ GraphVertex toscaElement = null;
+ Either<GraphVertex, TitanOperationStatus> getToscaElementRes = titanDao.getVertexById(toscaElementId, JsonParseFlagEnum.NoParse);
+ if(getToscaElementRes.isRight()){
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getToscaElementRes.right().value()));
+ }
+ if(result == null){
+ toscaElement = getToscaElementRes.left().value();
+ Iterator<Vertex> vertices = toscaElement.getVertex().vertices(Direction.IN, EdgeLabelEnum.STATE.name());
+ if(vertices == null || !vertices.hasNext()){
+ result = Either.right(StorageOperationStatus.NOT_FOUND);
+ } else {
+ result = Either.left(convertToUser(vertices.next()));
+ }
+ }
+ return result;
+ }
+ /**
+ * Returns vertex presenting owner of tosca element specified by uniqueId
+ * @param toscaElement
+ * @return
+ */
+ public Either<User, StorageOperationStatus> getToscaElementOwner(GraphVertex toscaElement) {
+ Either<User, StorageOperationStatus> result = null;
+ Iterator<Vertex> vertices = toscaElement.getVertex().vertices(Direction.IN, EdgeLabelEnum.STATE.name());
+ if(vertices == null || !vertices.hasNext()){
+ result = Either.right(StorageOperationStatus.NOT_FOUND);
+ } else {
+ result = Either.left(convertToUser(vertices.next()));
+ }
+ return result;
+ }
+
+/**
+ * Performs checkout of a tosca element
+ * @param toscaElementId
+ * @param modifierId
+ * @param ownerId
+ * @param currState
+ * @return
+ */
+ public Either<ToscaElement, StorageOperationStatus> checkoutToscaElement(String toscaElementId, String modifierId, String ownerId) {
+ Either<ToscaElement, StorageOperationStatus> result = null;
+ Map<String, GraphVertex> vertices = null;
+ try{
+ Either<Map<String, GraphVertex>, TitanOperationStatus> getVerticesRes =
+ titanDao.getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForCheckout(toscaElementId, modifierId, ownerId));
+ if(getVerticesRes.isRight()){
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId);
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVerticesRes.right().value()));
+ }
+ if(result == null){
+ vertices = getVerticesRes.left().value();
+ // update previous component if not certified
+ StorageOperationStatus status = updatePreviousVersion(vertices.get(toscaElementId), vertices.get(ownerId));
+ if(status != StorageOperationStatus.OK){
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update vertex with id {} . Status is {}. ", status);
+ result = Either.right(status);
+ }
+ }
+ if(result == null){
+ result = cloneToscaElementForCheckout(vertices.get(toscaElementId), vertices.get(modifierId));
+ if (result.isRight()) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG,"Failed to checkout tosca element {}. Status is {} ", toscaElementId, result.right().value());
+ }
+ }
+ } catch (Exception e){
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG,"Exception occured during checkout tosca element {}. {}", toscaElementId, e.getMessage());
+ }
+ return result;
+ }
+ /**
+ * Performs undo checkout for tosca element
+ * @param toscaElementId
+ * @return
+ */
+ public Either<ToscaElement, StorageOperationStatus> undoCheckout(String toscaElementId) {
+ Either<ToscaElement, StorageOperationStatus> result = null;
+ Either<GraphVertex, TitanOperationStatus> getToscaElementRes = null;
+ Iterator<Edge> nextVersionComponentIter = null;
+ ToscaElementOperation operation;
+ 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())){
+ // find previous version
+ nextVersionComponentIter = getToscaElementRes.left().value().getVertex().edges(Direction.IN, EdgeLabelEnum.VERSION.name());
+ if(nextVersionComponentIter == null || !nextVersionComponentIter.hasNext()){
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch previous version of tosca element with name {}. ",
+ getToscaElementRes.left().value().getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME).toString());
+ result = Either.right(StorageOperationStatus.NOT_FOUND);
+ }
+ if(result == null){
+ StorageOperationStatus updateOldResourceResult = updateOldToscaElementBeforeUndoCheckout(nextVersionComponentIter.next().outVertex());
+ if (updateOldResourceResult != StorageOperationStatus.OK) {
+ result = Either.right(updateOldResourceResult);
+ }
+ }
+ }
+ if(result == null){
+ operation = getToscaElementOperation(getToscaElementRes.left().value().getLabel());
+ result = operation.deleteToscaElement(getToscaElementRes.left().value());
+ }
+ } catch(Exception e){
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG,"Exception occured during undo checkout tosca element {}. {}", toscaElementId, e.getMessage());
+ }
+ return result;
+ }
+
+ private boolean hasPreviousVersion(GraphVertex toscaElementVertex) {
+ boolean hasPreviousVersion = true;
+ String version = (String) toscaElementVertex.getMetadataProperty(GraphPropertyEnum.VERSION);
+ if(StringUtils.isEmpty(version) || version.equals("0.1"))
+ hasPreviousVersion = false;
+ return hasPreviousVersion;
+ }
+ /**
+ * Performs request certification for tosca element
+ * @param toscaElementId
+ * @param modifierId
+ * @param ownerId
+ * @return
+ */
+ public Either<ToscaElement, StorageOperationStatus> requestCertificationToscaElement(String toscaElementId, String modifierId, String ownerId) {
+ Either<GraphVertex, StorageOperationStatus> resultUpdate = null;
+ Either<ToscaElement, StorageOperationStatus> result = null;
+ GraphVertex toscaElement = null;
+ GraphVertex modifier = null;
+ GraphVertex owner;
+ try {
+ Either<Map<String, GraphVertex>, TitanOperationStatus> getVerticesRes =
+ titanDao.getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForRequestCertification(toscaElementId, modifierId, ownerId));
+ if(getVerticesRes.isRight()){
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId);
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVerticesRes.right().value()));
+ }
+ if(result == null){
+ toscaElement = getVerticesRes.left().value().get(toscaElementId);
+ modifier = getVerticesRes.left().value().get(modifierId);
+ owner = getVerticesRes.left().value().get(ownerId);
+
+ StorageOperationStatus status = handleRelationsUponRequestForCertification(toscaElement, modifier, owner);
+ if(status != StorageOperationStatus.OK){
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG,"Failed to handle relations on certification request for tosca element {}. Status is {}. ",
+ toscaElement.getUniqueId(), status);
+ }
+ }
+ if(result == null){
+ LifecycleStateEnum nextState = LifecycleStateEnum.READY_FOR_CERTIFICATION;
+
+ toscaElement.addMetadataProperty(GraphPropertyEnum.STATE, nextState.name());
+ toscaElement.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis());
+
+ resultUpdate = updateToscaElementVertexMetadataPropertiesAndJson(toscaElement);
+ if (resultUpdate.isRight()) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG,"Failed to set lifecycle for tosca elememt {} to state {}, error: {}", toscaElement.getUniqueId(), nextState, resultUpdate.right().value());
+ result = Either.right(resultUpdate.right().value());
+ }
+ }
+ if(result == null){
+ ToscaElementOperation operation = getToscaElementOperation(toscaElement.getLabel());
+ result = operation.getToscaElement(toscaElement.getUniqueId());
+ }
+ return result;
+
+ } catch (Exception e){
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG,"Exception occured during request certification tosca element {}. {}", toscaElementId, e.getMessage());
+ }
+ return result;
+ }
+
+ /**
+ * Starts certification of tosca element
+ * @param toscaElementId
+ * @param modifierId
+ * @param ownerId
+ * @return
+ */
+ public Either<ToscaElement, StorageOperationStatus> startCertificationToscaElement(String toscaElementId, String modifierId, String ownerId) {
+ Either<ToscaElement, StorageOperationStatus> result = null;
+ Either<GraphVertex, StorageOperationStatus> resultUpdate = null;
+ GraphVertex toscaElement = null;
+ GraphVertex modifier = null;
+ GraphVertex owner;
+ try {
+ Either<Map<String, GraphVertex>, TitanOperationStatus> getVerticesRes =
+ titanDao.getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForRequestCertification(toscaElementId, modifierId, ownerId));
+ if(getVerticesRes.isRight()){
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId);
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVerticesRes.right().value()));
+ }
+ if(result == null){
+ toscaElement = getVerticesRes.left().value().get(toscaElementId);
+ modifier = getVerticesRes.left().value().get(modifierId);
+ owner = getVerticesRes.left().value().get(ownerId);
+
+ StorageOperationStatus status = handleRelationsUponCertification(toscaElement, modifier, owner);
+ if(status != StorageOperationStatus.OK){
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG,"Failed to handle relations during certification of tosca element {}. Status is {}. ",
+ toscaElement.getUniqueId(), status);
+ }
+ }
+ if(result == null){
+ LifecycleStateEnum nextState = LifecycleStateEnum.CERTIFICATION_IN_PROGRESS;
+
+ toscaElement.addMetadataProperty(GraphPropertyEnum.STATE, nextState.name());
+ toscaElement.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis());
+
+ resultUpdate = updateToscaElementVertexMetadataPropertiesAndJson(toscaElement);
+ if (resultUpdate.isRight()) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG,"Couldn't set lifecycle for component {} to state {}, error: {}", toscaElement.getUniqueId(), nextState, resultUpdate.right().value());
+ result = Either.right(resultUpdate.right().value());
+ }
+ }
+ if(result == null){
+ ToscaElementOperation operation = getToscaElementOperation(toscaElement.getLabel());
+ result = operation.getToscaElement(toscaElement.getUniqueId());
+ }
+ } catch (Exception e){
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG,"Exception occured during start certification tosca element {}. {}", toscaElementId, e.getMessage());
+ }
+ return result;
+ }
+
+ public Either<ToscaElement, StorageOperationStatus> certifyToscaElement(String toscaElementId, String modifierId, String ownerId) {
+ Either<ToscaElement, StorageOperationStatus> result = null;
+ Either<GraphVertex, StorageOperationStatus> cloneRes = null;
+ GraphVertex toscaElement = null;
+ GraphVertex modifier = null;
+ GraphVertex certifiedToscaElement = null;
+ Integer majorVersion = null;
+
+ StorageOperationStatus status;
+ try {
+ Either<Map<String, GraphVertex>, TitanOperationStatus> getVerticesRes =
+ titanDao.getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForRequestCertification(toscaElementId, modifierId, ownerId));
+ if(getVerticesRes.isRight()){
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId);
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVerticesRes.right().value()));
+ }
+ if(result == null){
+ toscaElement = getVerticesRes.left().value().get(toscaElementId);
+ modifier = getVerticesRes.left().value().get(modifierId);
+ majorVersion = getMajorVersion((String) toscaElement.getMetadataProperty(GraphPropertyEnum.VERSION));
+ status = handleRelationsOfPreviousToscaElementBeforeCertifying(toscaElement, modifier, majorVersion);
+ if(status != StorageOperationStatus.OK){
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG,"Failed to handle relations of previous tosca element before certifying {}. Status is {}. ",
+ toscaElement.getUniqueId(), status);
+ }
+ }
+ if(result == null){
+ cloneRes = cloneToscaElementForCertify(toscaElement, modifier, majorVersion);
+ if (cloneRes.isRight()) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to clone tosca element during certification. ");
+ result = Either.right(cloneRes.right().value());
+ }
+ }
+ if(result == null){
+ certifiedToscaElement = cloneRes.left().value();
+ status = handleRelationsOfNewestCertifiedToscaElement(toscaElement, certifiedToscaElement);
+ if(status != StorageOperationStatus.OK){
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG,"Failed to handle relations of newest certified tosca element {}. Status is {}. ",
+ certifiedToscaElement.getUniqueId(), status);
+ }
+ }
+ if(result == null){
+ return getToscaElementOperation(toscaElement.getLabel()).getToscaElement(certifiedToscaElement.getUniqueId());
+ }
+ } catch (Exception e){
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG,"Exception occured during certification tosca element {}. {}", toscaElementId, e.getMessage());
+ }
+ return result;
+ }
+/**
+ * Deletes (marks as deleted) all tosca elements according received name and uuid
+ * @param vertexType
+ * @param componentType
+ * @param componentName
+ * @param uuid
+ * @return
+ */
+ public Either<Boolean, StorageOperationStatus> deleteOldToscaElementVersions(VertexTypeEnum vertexType, ComponentTypeEnum componentType, String componentName, String uuid) {
+
+ Either<Boolean, StorageOperationStatus> result = null;
+ ToscaElementOperation operation = getToscaElementOperation(componentType);
+
+ try {
+ Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
+ properties.put(GraphPropertyEnum.UUID, uuid);
+ properties.put(GraphPropertyEnum.NAME, componentName);
+ Either<List<GraphVertex>, TitanOperationStatus> getToscaElementsRes= titanDao.getByCriteria(vertexType, properties, JsonParseFlagEnum.ParseMetadata);
+ if (getToscaElementsRes.isRight()) {
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getToscaElementsRes.right().value()));
+ }
+ if(result == null){
+ result = markToscaElementsAsDeleted(operation, getToscaElementsRes.left().value());
+ }
+ if(result == null){
+ result = Either.left(true);
+ }
+ } catch (Exception e){
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG,"Exception occured during deleteng all tosca elements by UUID {} and name {}. {} ", uuid, componentName, e.getMessage());
+ }
+ return result;
+ }
+/**
+ * Performs cancelation or failure of certification for received tosca element
+ * @param toscaElementId
+ * @param modifierId
+ * @param ownerId
+ * @param nextState
+ * @return
+ */
+ public Either<ToscaElement, StorageOperationStatus> cancelOrFailCertification(String toscaElementId, String modifierId, String ownerId, LifecycleStateEnum nextState) {
+ Either<ToscaElement, StorageOperationStatus> result = null;
+ StorageOperationStatus status;
+ ToscaElementOperation operation = null;
+ GraphVertex toscaElement = null;
+ GraphVertex modifier = null;
+ try {
+ Either<Map<String, GraphVertex>, TitanOperationStatus> getVerticesRes =
+ titanDao.getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForRequestCertification(toscaElementId, modifierId, ownerId));
+ if(getVerticesRes.isRight()){
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId);
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVerticesRes.right().value()));
+ }
+ if(result == null){
+ toscaElement = getVerticesRes.left().value().get(toscaElementId);
+ modifier = getVerticesRes.left().value().get(modifierId);
+ operation = getToscaElementOperation(toscaElement.getLabel());
+ toscaElement.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis());
+ toscaElement.setJsonMetadataField(JsonPresentationFields.USER_ID_LAST_UPDATER, modifier.getUniqueId());
+ toscaElement.addMetadataProperty(GraphPropertyEnum.STATE, nextState.name());
+
+ Either<GraphVertex, TitanOperationStatus> updateVertexRes = titanDao.updateVertex(toscaElement);
+ if(updateVertexRes.isRight()){
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update vertex {} . Status is {}. ", toscaElementId, updateVertexRes.right().value());
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateVertexRes.right().value()));
+ }
+ }
+ if(result == null){
+ // cancel certification process
+ status = handleRelationsUponCancelCertification(toscaElement, nextState);
+ if(status != StorageOperationStatus.OK){
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG,"Failed to handle relations upon cancel certification {}. Status is {}. ",
+ toscaElement.getUniqueId(), status);
+ }
+ }
+ if(result == null){
+ // fail certification
+ status = handleRelationsUponFailCertification(toscaElement, nextState);
+ if(status != StorageOperationStatus.OK){
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG,"Failed to handle relations upon fail certification {}. Status is {}. ",
+ toscaElement.getUniqueId(), status);
+ }
+ }
+ if (result == null) {
+ result = operation.getToscaElement(toscaElementId);
+ }
+ } catch (Exception e){
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG,"Exception occured during cancel or fail certification of tosca element {}. {}. ",
+ toscaElementId, e.getMessage());
+ }
+ return result;
+ }
+
+ public Either<GraphVertex, TitanOperationStatus> findUser(String userId) {
+ return findUserVertex(userId);
+ }
+
+ private Either<Boolean, StorageOperationStatus> markToscaElementsAsDeleted(ToscaElementOperation operation, List<GraphVertex> toscaElements) {
+ Either<Boolean, StorageOperationStatus> result = Either.left(true);
+ for (GraphVertex resourceToDelete : toscaElements) {
+ if(!((String)resourceToDelete.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals(LifecycleStateEnum.CERTIFIED.name())){
+ Either<GraphVertex, StorageOperationStatus> deleteElementRes = operation.markComponentToDelete(resourceToDelete);
+ if (deleteElementRes.isRight()) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete tosca element {}. Status is {}. ", resourceToDelete.getUniqueId(), deleteElementRes.right().value());
+ result = Either.right(deleteElementRes.right().value());
+ break;
+ }
+ }
+ }
+ return result;
+ }
+
+
+ private StorageOperationStatus handleRelationsOfNewestCertifiedToscaElement(GraphVertex toscaElement, GraphVertex certifiedToscaElement) {
+ StorageOperationStatus result = null;
+ Edge foundEdge = null;
+ Iterator<Edge> certReqUserEdgeIter = null;
+ // add rfc relation to preserve follower information
+ // get user of certification request
+ certReqUserEdgeIter = toscaElement.getVertex().edges(Direction.IN, GraphEdgeLabels.LAST_STATE.name());
+ if(certReqUserEdgeIter == null || !certReqUserEdgeIter.hasNext()){
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to find rfc relation during certification clone. ");
+ result = StorageOperationStatus.NOT_FOUND;
+ }
+ if(result == null){
+
+ while(certReqUserEdgeIter.hasNext()){
+ Edge edge = certReqUserEdgeIter.next();
+ if(((String)titanDao.getProperty(edge, EdgePropertyEnum.STATE)).equals(LifecycleStateEnum.READY_FOR_CERTIFICATION.name()) ){
+ foundEdge = edge;
+ break;
+ }
+
+ }
+ if(foundEdge == null){
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to find rfc relation during certification clone. ");
+ result = StorageOperationStatus.NOT_FOUND;
+ }
+ }
+ if(result == null){
+ TitanOperationStatus createEdgeRes = titanDao.createEdge(foundEdge.outVertex(), certifiedToscaElement.getVertex(), EdgeLabelEnum.LAST_STATE, foundEdge);
+ if (createEdgeRes != TitanOperationStatus.OK) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to create rfc relation for component {}. status=", certifiedToscaElement.getUniqueId(), createEdgeRes);
+ result = DaoStatusConverter.convertTitanStatusToStorageStatus(createEdgeRes);
+ }
+ }
+ if(result == null){
+ result = StorageOperationStatus.OK;
+ }
+ return result;
+ }
+
+ private StorageOperationStatus handleRelationsUponFailCertification(GraphVertex toscaElement, LifecycleStateEnum nextState) {
+ StorageOperationStatus result = null;
+ TitanOperationStatus status = null;
+ Edge originEdge;
+ Vertex user = null;
+ if(nextState == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN){
+ // fail certification
+ // delete relation CERTIFICATION_IN_PROGRESS
+ Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
+ properties.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
+
+ Either<Edge, TitanOperationStatus> deleteResult = titanDao.deleteBelongingEdgeByCriteria(toscaElement, EdgeLabelEnum.STATE, properties);
+ if (deleteResult.isRight()) {
+ status = deleteResult.right().value();
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete state edge. Status is {}. ", status);
+ result = StorageOperationStatus.INCONSISTENCY;
+ }
+ if(result == null){
+ // delete relation READY_FOR_CERTIFICATION
+ properties.put(GraphPropertyEnum.STATE, LifecycleStateEnum.READY_FOR_CERTIFICATION);
+ deleteResult = titanDao.deleteBelongingEdgeByCriteria(toscaElement, EdgeLabelEnum.LAST_STATE, properties);
+ if(deleteResult.isRight()){
+ status = deleteResult.right().value();
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete last state edge. Status is {}. ", status);
+ result = StorageOperationStatus.INCONSISTENCY;
+ }
+ }
+ if(result == null){
+ // delete relation NOT_CERTIFIED_CHECKIN (in order to change to STATE)
+ properties.put(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
+ deleteResult = titanDao.deleteBelongingEdgeByCriteria(toscaElement, EdgeLabelEnum.LAST_STATE, properties);
+ if(deleteResult.isRight()){
+ status = deleteResult.right().value();
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete last state edge. Status is {}. ", status);
+ result = StorageOperationStatus.INCONSISTENCY;
+ }
+ }
+ if(result == null){
+ // create new STATE relation NOT_CERTIFIED_CHECKIN
+ originEdge = deleteResult.left().value();
+ user = originEdge.outVertex();
+ status = titanDao.createEdge(user, toscaElement.getVertex(), EdgeLabelEnum.STATE, originEdge);
+ if (status != TitanOperationStatus.OK) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to create state edge. Status is {}. ", status);
+ result = StorageOperationStatus.INCONSISTENCY;
+ }
+ }
+ if(result == null){
+ // delete relation LAST_MODIFIER (in order to change tester to designer)
+ deleteResult = titanDao.deleteBelongingEdgeByCriteria(toscaElement, EdgeLabelEnum.LAST_MODIFIER, new HashMap<>());
+ if (status != TitanOperationStatus.OK) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to create last modifier edge. Status is {}. ", status);
+ result = StorageOperationStatus.INCONSISTENCY;
+ }
+ }
+ if(result == null){
+ // create new LAST_MODIFIER relation
+ originEdge = deleteResult.left().value();
+ status = titanDao.createEdge(user, toscaElement.getVertex(), EdgeLabelEnum.LAST_MODIFIER, originEdge);
+ if (status != TitanOperationStatus.OK) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to create last modifier edge. Status is {}. ", status);
+ result = StorageOperationStatus.INCONSISTENCY;
+ }
+ }
+ }
+ if(result == null){
+ result = StorageOperationStatus.OK;
+ }
+ return result;
+ }
+
+ private StorageOperationStatus handleRelationsUponCancelCertification(GraphVertex toscaElement, LifecycleStateEnum nextState) {
+ StorageOperationStatus result = null;
+ Edge originEdge;
+ if(nextState == LifecycleStateEnum.READY_FOR_CERTIFICATION){
+ // delete relation CERTIFICATION_IN_PROGRESS
+ Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
+ properties.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
+ Either<Edge, TitanOperationStatus> deleteResult = titanDao.deleteBelongingEdgeByCriteria(toscaElement, EdgeLabelEnum.STATE, properties);
+
+ if (deleteResult.isRight()) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete state edge. Status is {}. ", deleteResult.right().value());
+ result = StorageOperationStatus.INCONSISTENCY;
+ }
+ if(result == null){
+ // delete relation READY_FOR_CERTIFICATION (LAST_STATE)
+ properties.put(GraphPropertyEnum.STATE, nextState);
+ deleteResult = titanDao.deleteBelongingEdgeByCriteria(toscaElement, EdgeLabelEnum.LAST_STATE, properties);
+
+ if (deleteResult.isRight()) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete last state edge. Status is {}. ", deleteResult.right().value());
+ result = StorageOperationStatus.INCONSISTENCY;
+ }
+ }
+ if(result == null){
+ // create relation READY_FOR_CERTIFICATION (STATE)
+ originEdge = deleteResult.left().value();
+ TitanOperationStatus status = titanDao.createEdge(originEdge.outVertex(), toscaElement.getVertex(), EdgeLabelEnum.STATE, originEdge);
+ if (status != TitanOperationStatus.OK) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to create state edge. Status is {}. ", status);
+ result = StorageOperationStatus.INCONSISTENCY;
+ }
+ }
+ if(result == null){
+ result = StorageOperationStatus.OK;
+ }
+ }
+ return result;
+ }
+
+ private StorageOperationStatus handleRelationsOfPreviousToscaElementBeforeCertifying(GraphVertex toscaElement, GraphVertex modifier, Integer majorVersion) {
+ StorageOperationStatus result = null;
+ if (majorVersion > 0) {
+ Either<Vertex, StorageOperationStatus> findRes = findLastCertifiedToscaElementVertex(toscaElement);
+ if(findRes.isRight()){
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch last certified tosca element {} . Status is {}. ", toscaElement.getMetadataProperty(GraphPropertyEnum.NAME), findRes.right().value());
+ result = findRes.right().value();
+ }
+ if(result == null){
+ Vertex lastCertifiedVertex = findRes.left().value();
+ Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
+ properties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, false);
+ TitanOperationStatus status = titanDao.updateVertexMetadataPropertiesWithJson(lastCertifiedVertex, properties);
+ if (status != TitanOperationStatus.OK) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG,"Failed to set highest version of tosca element {} to [{}]. Status is {}", toscaElement.getUniqueId(), false, status);
+ result = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
+ }
+ }
+ }
+ if(result == null){
+ result = StorageOperationStatus.OK;
+ }
+ return result;
+ }
+
+ private StorageOperationStatus handleRelationsUponRequestForCertification(GraphVertex toscaElement, GraphVertex modifier, GraphVertex owner) {
+ TitanOperationStatus status;
+ StorageOperationStatus result = null;
+
+ if (((String)toscaElement.getMetadataProperty(GraphPropertyEnum.STATE)).equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
+ // remove CHECKOUT relation
+ Either<Edge, TitanOperationStatus> deleteRes = titanDao.deleteEdge(owner, toscaElement, EdgeLabelEnum.STATE);
+ if (deleteRes.isRight()) {
+ status = deleteRes.right().value();
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete edge. Status is {}. ", status);
+ result = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
+ }
+ if(result == null){
+ // create CHECKIN relation
+ Map<EdgePropertyEnum, Object> properties = new EnumMap<>(EdgePropertyEnum.class);
+ properties.put(EdgePropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
+ status = titanDao.createEdge(modifier.getVertex(), toscaElement.getVertex(), EdgeLabelEnum.LAST_STATE, properties);
+ if (status != TitanOperationStatus.OK) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to create edge. Status is {}", status);
+ result = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
+ }
+ }
+ } else {
+ status = titanDao.replaceEdgeLabel(owner.getVertex(), toscaElement.getVertex(), EdgeLabelEnum.STATE, EdgeLabelEnum.LAST_STATE);
+ if (status != TitanOperationStatus.OK) {
+ result = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
+ }
+ }
+ if(result == null){
+ // create RFC relation
+ Map<EdgePropertyEnum, Object> properties = new EnumMap<>(EdgePropertyEnum.class);
+ properties.put(EdgePropertyEnum.STATE, LifecycleStateEnum.READY_FOR_CERTIFICATION);
+ status = titanDao.createEdge(modifier.getVertex(), toscaElement.getVertex(), EdgeLabelEnum.STATE, properties);
+ if (status != TitanOperationStatus.OK) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to create edge. Status is {}", status);
+ result = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
+ }
+ }
+ if(result == null){
+ result = StorageOperationStatus.OK;
+ }
+ return result;
+ }
+
+ private StorageOperationStatus handleRelationsUponCertification(GraphVertex toscaElement, GraphVertex modifier, GraphVertex owner) {
+
+ StorageOperationStatus result = null;
+ TitanOperationStatus status = titanDao.replaceEdgeLabel(owner.getVertex(), toscaElement.getVertex(), EdgeLabelEnum.STATE, EdgeLabelEnum.LAST_STATE);
+ if (status != TitanOperationStatus.OK) {
+ result = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
+ }
+ if(result == null){
+ Map<EdgePropertyEnum, Object> properties = new EnumMap<>(EdgePropertyEnum.class);
+ properties.put(EdgePropertyEnum.STATE, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
+ status = titanDao.createEdge(modifier, toscaElement, EdgeLabelEnum.STATE, properties);
+ if (status != TitanOperationStatus.OK) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG,"failed to create edge. Status is {}", status);
+ result = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
+ }
+ }
+ if(result == null){
+ result = StorageOperationStatus.OK;
+ }
+ return result;
+ }
+
+ private Either<Vertex, StorageOperationStatus> findLastCertifiedToscaElementVertex(GraphVertex toscaElement) {
+ return findLastCertifiedToscaElementVertexRecursively(toscaElement.getVertex());
+ }
+
+ private Either<Vertex, StorageOperationStatus> findLastCertifiedToscaElementVertexRecursively(Vertex vertex) {
+ if(isCertifiedVersion((String)vertex.property(GraphPropertyEnum.VERSION.getProperty()).value())){
+ return Either.left(vertex);
+ }
+ Iterator<Edge> edgeIter = vertex.edges(Direction.IN, EdgeLabelEnum.VERSION.name());
+ if(!edgeIter.hasNext()){
+ return Either.right(StorageOperationStatus.NOT_FOUND);
+ }
+ return findLastCertifiedToscaElementVertexRecursively(edgeIter.next().outVertex());
+ }
+
+ private boolean isCertifiedVersion(String version) {
+ String[] versionParts = version.split(VERSION_DELIMETER_REGEXP);
+ if(Integer.parseInt(versionParts[0]) > 0 && Integer.parseInt(versionParts[1]) == 0){
+ return true;
+ }
+ return false;
+ }
+
+ private StorageOperationStatus updateOldToscaElementBeforeUndoCheckout(Vertex previousVersionToscaElement) {
+
+ StorageOperationStatus result = StorageOperationStatus.OK;
+ String previousVersion = (String) previousVersionToscaElement.property(GraphPropertyEnum.VERSION.getProperty()).value();
+ if (!previousVersion.endsWith(".0")) {
+ try{
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "Going to update vertex of previous version of tosca element",
+ previousVersionToscaElement.property(GraphPropertyEnum.NORMALIZED_NAME.getProperty()));
+
+ 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());
+ jsonMetadataMap.put(GraphPropertyEnum.IS_HIGHEST_VERSION.getProperty(), true);
+ propertiesToUpdate.put(GraphPropertyEnum.METADATA.getProperty(), JsonParserUtils.jsonToString(jsonMetadataMap));
+
+ titanDao.setVertexProperties(previousVersionToscaElement, propertiesToUpdate);
+
+ Iterator<Edge> edgesIter = previousVersionToscaElement.edges(Direction.IN, EdgeLabelEnum.LAST_STATE.name());
+ if(!edgesIter.hasNext()){
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch last modifier vertex for tosca element {}. ", previousVersionToscaElement.property(GraphPropertyEnum.NORMALIZED_NAME.getProperty()));
+ result = StorageOperationStatus.NOT_FOUND;
+ } else {
+ Edge lastStateEdge = edgesIter.next();
+ Vertex lastModifier = lastStateEdge.outVertex();
+ TitanOperationStatus replaceRes =
+ titanDao.replaceEdgeLabel(lastModifier, previousVersionToscaElement, lastStateEdge, EdgeLabelEnum.LAST_STATE, EdgeLabelEnum.STATE);
+ if (replaceRes != TitanOperationStatus.OK) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to replace label from {} to {}. status = {}", EdgeLabelEnum.LAST_STATE, EdgeLabelEnum.STATE, replaceRes);
+ result = StorageOperationStatus.INCONSISTENCY;
+ if (replaceRes != TitanOperationStatus.INVALID_ID) {
+ result = DaoStatusConverter.convertTitanStatusToStorageStatus(replaceRes);
+ }
+ }
+ }
+ } catch (Exception e){
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during update previous tosca element {} before undo checkout. {} ", e.getMessage());
+ }
+ }
+ return result;
+ }
+ private StorageOperationStatus updatePreviousVersion(GraphVertex toscaElementVertex, GraphVertex ownerVertex) {
+ StorageOperationStatus result = null;
+ String ownerId = (String) ownerVertex.getMetadataProperty(GraphPropertyEnum.USERID);
+ String toscaElementId = toscaElementVertex.getUniqueId();
+ if(!toscaElementVertex.getMetadataProperty(GraphPropertyEnum.STATE).equals(LifecycleStateEnum.CERTIFIED.name())){
+ toscaElementVertex.addMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION, false);
+ Either<GraphVertex, TitanOperationStatus> updateVertexRes = titanDao.updateVertex(toscaElementVertex);
+ if (updateVertexRes.isRight()) {
+ TitanOperationStatus titatStatus = updateVertexRes.right().value();
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG,
+ "Failed to update tosca element vertex {}. Status is {}", toscaElementVertex.getUniqueId(), titatStatus);
+ result = DaoStatusConverter.convertTitanStatusToStorageStatus(titatStatus);
+ }
+ Either<Edge, TitanOperationStatus> deleteEdgeRes = null;
+ if(result == null){
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE,"Going to replace edge with label {} to label {} from {} to {}. ",
+ EdgeLabelEnum.STATE , EdgeLabelEnum.LAST_STATE, ownerId, toscaElementId);
+
+ deleteEdgeRes = titanDao.deleteEdge(ownerVertex, toscaElementVertex, EdgeLabelEnum.STATE);
+ if(deleteEdgeRes.isRight()){
+ TitanOperationStatus titanStatus = deleteEdgeRes.right().value();
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG,
+ "Failed to delete edge with label {} from {} to {}. Status is {} ",
+ EdgeLabelEnum.STATE , EdgeLabelEnum.LAST_STATE, ownerId, toscaElementId, titanStatus);
+ if (!titanStatus.equals(TitanOperationStatus.INVALID_ID)) {
+ result = DaoStatusConverter.convertTitanStatusToStorageStatus(titanStatus);
+ } else{
+ result = StorageOperationStatus.INCONSISTENCY;
+ }
+ }
+ }
+ if(result == null){
+ TitanOperationStatus createEdgeRes = titanDao.createEdge(ownerVertex.getVertex(), toscaElementVertex.getVertex(), EdgeLabelEnum.LAST_STATE, deleteEdgeRes.left().value());
+ if(createEdgeRes != TitanOperationStatus.OK){
+ result = DaoStatusConverter.convertTitanStatusToStorageStatus(createEdgeRes);
+ }
+ }
+ }
+ if(result == null){
+ result = StorageOperationStatus.OK;
+ }
+ return result;
+ }
+
+ private Either<ToscaElement, StorageOperationStatus> cloneToscaElementForCheckout(GraphVertex toscaElementVertex, GraphVertex modifierVertex) {
+
+ Either<ToscaElement, StorageOperationStatus> result = null;
+ Either<GraphVertex, StorageOperationStatus> cloneResult = null;
+ ToscaElementOperation operation = getToscaElementOperation(toscaElementVertex.getLabel());
+ // 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()){
+ String fetchedVersion = (String) nextVersionComponentIter.next().inVertex().property(GraphPropertyEnum.VERSION.getProperty()).value();
+ String fetchedName = (String) nextVersionComponentIter.next().inVertex().property(GraphPropertyEnum.NORMALIZED_NAME.getProperty()).value();
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to checkout component {} with version {}. The component with name {} and version {} was fetched from graph as existing following version. ",
+ toscaElementVertex.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME).toString(), toscaElementVertex.getMetadataProperty(GraphPropertyEnum.VERSION).toString(), fetchedName, fetchedVersion);
+ result = Either.right(StorageOperationStatus.ENTITY_ALREADY_EXISTS);
+ }
+ if(result == null){
+ cloneResult = operation.cloneToscaElement(toscaElementVertex, cloneGraphVertexForCheckout(toscaElementVertex, modifierVertex), modifierVertex);
+ if(cloneResult.isRight()){
+ result = Either.right(cloneResult.right().value());
+ }
+ }
+ if (result == null) {
+ TitanOperationStatus status = titanDao.createEdge(toscaElementVertex.getVertex(), cloneResult.left().value().getVertex(), EdgeLabelEnum.VERSION, new HashMap<>());
+ if (status != TitanOperationStatus.OK) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to create edge with label {} from vertex {} to tosca element vertex {} on graph. Status is {}. ", EdgeLabelEnum.VERSION, toscaElementVertex.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME),
+ cloneResult.left().value().getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), status);
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ }
+ if(result == null){
+ result = operation.getToscaElement(cloneResult.left().value().getUniqueId());
+ }
+ return result;
+ }
+
+ private GraphVertex cloneGraphVertexForCheckout(GraphVertex toscaElementVertex, GraphVertex modifierVertex) {
+ GraphVertex nextVersionToscaElementVertex = new GraphVertex();
+ String uniqueId = UniqueIdBuilder.buildComponentUniqueId();
+ Map<GraphPropertyEnum, Object> metadataProperties = new HashMap<>(toscaElementVertex.getMetadataProperties());
+ nextVersionToscaElementVertex.setMetadataProperties(metadataProperties);
+ nextVersionToscaElementVertex.setUniqueId(uniqueId);
+ nextVersionToscaElementVertex.setLabel(toscaElementVertex.getLabel());
+ nextVersionToscaElementVertex.setType(toscaElementVertex.getType());
+
+ nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.UNIQUE_ID, uniqueId);
+ nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.COMPONENT_TYPE, nextVersionToscaElementVertex.getType().name());
+ String nextVersion = getNextVersion((String) toscaElementVertex.getMetadataProperty(GraphPropertyEnum.VERSION));
+ if(isFirstCheckoutAfterCertification(nextVersion)){
+ nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.UUID, IdBuilderUtils.generateUUID());
+ }
+ nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.VERSION, nextVersion);
+ nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name());
+ nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+
+ if (toscaElementVertex.getType() == ComponentTypeEnum.SERVICE && toscaElementVertex.getMetadataProperty(GraphPropertyEnum.STATE).equals(LifecycleStateEnum.CERTIFIED.name())) {
+ nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.DISTRIBUTION_STATUS, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.getValue());
+ }
+ if(!MapUtils.isEmpty(toscaElementVertex.getMetadataJson())){
+ nextVersionToscaElementVertex.setMetadataJson(new HashMap<String, Object>(toscaElementVertex.getMetadataJson()));
+ nextVersionToscaElementVertex.updateMetadataJsonWithCurrentMetadataProperties();
+ }
+ long currTime = System.currentTimeMillis();
+ nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.CREATION_DATE, currTime);
+ nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, currTime);
+ nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.USER_ID_CREATOR, modifierVertex.getUniqueId());
+ nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.USER_ID_LAST_UPDATER, modifierVertex.getUniqueId());
+ if(toscaElementVertex.getType() == ComponentTypeEnum.SERVICE) {
+ nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.CONFORMANCE_LEVEL, ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel());
+ }
+
+ if(!MapUtils.isEmpty(toscaElementVertex.getJson())){
+ nextVersionToscaElementVertex.setJson(new HashMap<String, ToscaDataDefinition>(toscaElementVertex.getJson()));
+ }
+ return nextVersionToscaElementVertex;
+ }
+
+ private Either<GraphVertex, StorageOperationStatus> cloneToscaElementForCertify(GraphVertex toscaElementVertex, GraphVertex modifierVertex, Integer majorVersion) {
+ Either<GraphVertex, StorageOperationStatus> result;
+ Either<List<GraphVertex>, StorageOperationStatus> deleteResult = null;
+ GraphVertex clonedToscaElement = null;
+ result = getToscaElementOperation(toscaElementVertex.getLabel()).cloneToscaElement(toscaElementVertex, cloneGraphVertexForCertify(toscaElementVertex, modifierVertex, majorVersion), modifierVertex);
+ if(result.isRight()){
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to clone tosca element {} for certification. Sattus is {}. ", toscaElementVertex.getUniqueId(), result.right().value());
+ }
+ else{
+ clonedToscaElement = result.left().value();
+ deleteResult = deleteAllPreviousNotCertifiedVersions(toscaElementVertex);
+ if(deleteResult.isRight()){
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete all previous npt certified versions of tosca element {}. Status is {}. ",
+ toscaElementVertex.getUniqueId(), deleteResult.right().value());
+ result = Either.right(deleteResult.right().value());
+ }
+ }
+ if(result.isLeft()){
+ result = handlePreviousVersionRelation(clonedToscaElement, deleteResult.left().value(), majorVersion);
+ }
+ return result;
+ }
+
+ private Either<GraphVertex, StorageOperationStatus> handlePreviousVersionRelation(GraphVertex clonedToscaElement, List<GraphVertex> deletedVersions, Integer majorVersion) {
+ Either<GraphVertex, StorageOperationStatus> result = null;
+ Vertex previousCertifiedToscaElement = null;
+ if(majorVersion > 0){
+ List<GraphVertex> firstMinorVersionVertex = deletedVersions.stream()
+ .filter(gv->getMinorVersion((String)gv.getMetadataProperty(GraphPropertyEnum.VERSION)) == 1).collect(Collectors.toList());
+
+ if(CollectionUtils.isEmpty(firstMinorVersionVertex)){
+ result = Either.right(StorageOperationStatus.NOT_FOUND);
+ } else {
+ previousCertifiedToscaElement = getPreviousCertifiedToscaElement(firstMinorVersionVertex.get(0));
+ if(previousCertifiedToscaElement == null){
+ result = Either.right(StorageOperationStatus.NOT_FOUND);
+ }
+ }
+ if(result == null){
+ TitanOperationStatus status = titanDao.createEdge(previousCertifiedToscaElement, clonedToscaElement.getVertex(), EdgeLabelEnum.VERSION, new HashMap<>());
+ if (status != TitanOperationStatus.OK) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to create edge with label {} from vertex {} to tosca element vertex {} on graph. Status is {}. ", EdgeLabelEnum.VERSION, previousCertifiedToscaElement.property(GraphPropertyEnum.UNIQUE_ID.getProperty()),
+ clonedToscaElement.getUniqueId(), status);
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ }
+ }
+ if(result == null){
+ result = Either.left(clonedToscaElement);
+ }
+ return result;
+ }
+
+ private Vertex getPreviousCertifiedToscaElement(GraphVertex graphVertex) {
+
+ Iterator<Edge> edges = graphVertex.getVertex().edges(Direction.IN, EdgeLabelEnum.VERSION.name());
+ if(edges.hasNext()){
+ return edges.next().outVertex();
+ }
+ return null;
+ }
+
+ private Either<List<GraphVertex>, StorageOperationStatus> deleteAllPreviousNotCertifiedVersions(GraphVertex toscaElementVertex) {
+ Either<List<GraphVertex>, StorageOperationStatus> result = null;
+
+ ToscaElementOperation operation = getToscaElementOperation(toscaElementVertex.getLabel());
+ List<GraphVertex> previosVersions = null;
+ Object uuid = toscaElementVertex.getMetadataProperty(GraphPropertyEnum.UUID);
+ Object componentName = toscaElementVertex.getMetadataProperty(GraphPropertyEnum.NAME);
+ try {
+ Map<GraphPropertyEnum, Object> properties = new HashMap<>();
+ properties.put(GraphPropertyEnum.UUID, uuid);
+ properties.put(GraphPropertyEnum.NAME, componentName);
+ Either<List<GraphVertex>, TitanOperationStatus> getToscaElementsRes= titanDao.getByCriteria(toscaElementVertex.getLabel(), properties, JsonParseFlagEnum.ParseMetadata);
+ if (getToscaElementsRes.isRight()) {
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getToscaElementsRes.right().value()));
+ }
+ if(result == null){
+ previosVersions = getToscaElementsRes.left().value();
+ Either<Boolean, StorageOperationStatus> deleteResult = markToscaElementsAsDeleted(operation, getToscaElementsRes.left().value());
+ if(deleteResult.isRight()){
+ result = Either.right(deleteResult.right().value());
+ }
+ }
+ if(result == null){
+ result = Either.left(previosVersions);
+ }
+ } catch (Exception e){
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG,"Exception occured during deleteng all tosca elements by UUID {} and name {}. {} ", uuid, componentName, e.getMessage());
+ }
+ return result;
+ }
+
+ private GraphVertex cloneGraphVertexForCertify(GraphVertex toscaElementVertex, GraphVertex modifierVertex, Integer majorVersion) {
+
+ GraphVertex nextVersionToscaElementVertex = new GraphVertex();
+ String uniqueId = IdBuilderUtils.generateUniqueId();
+ Map<GraphPropertyEnum, Object> metadataProperties = new HashMap<>(toscaElementVertex.getMetadataProperties());
+ nextVersionToscaElementVertex.setMetadataProperties(metadataProperties);
+ nextVersionToscaElementVertex.setUniqueId(uniqueId);
+ nextVersionToscaElementVertex.setLabel(toscaElementVertex.getLabel());
+ nextVersionToscaElementVertex.setType(toscaElementVertex.getType());
+
+ nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.UNIQUE_ID, uniqueId);
+ nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.COMPONENT_TYPE, nextVersionToscaElementVertex.getType().name());
+ nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.VERSION, (majorVersion + 1) + VERSION_DELIMETER + "0");
+ nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
+ nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+ nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.CREATION_DATE, System.currentTimeMillis());
+ nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, null);
+ nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.USER_ID_CREATOR, modifierVertex.getUniqueId());
+ nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.USER_ID_LAST_UPDATER, modifierVertex.getUniqueId());
+
+ if (toscaElementVertex.getType() == ComponentTypeEnum.SERVICE && toscaElementVertex.getMetadataProperty(GraphPropertyEnum.STATE).equals(LifecycleStateEnum.CERTIFIED)) {
+ nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.DISTRIBUTION_STATUS, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.getValue());
+ }
+ if(!MapUtils.isEmpty(toscaElementVertex.getMetadataJson())){
+ nextVersionToscaElementVertex.setMetadataJson(new HashMap<String, Object>(toscaElementVertex.getMetadataJson()));
+ nextVersionToscaElementVertex.updateMetadataJsonWithCurrentMetadataProperties();
+ }
+ if(!MapUtils.isEmpty(toscaElementVertex.getJson())){
+ nextVersionToscaElementVertex.setJson(new HashMap<String, ToscaDataDefinition>(toscaElementVertex.getJson()));
+ }
+ return nextVersionToscaElementVertex;
+ }
+
+ private ComponentParametersView buildComponentParametersViewAfterCheckin() {
+ ComponentParametersView componentParametersView = new ComponentParametersView();
+ componentParametersView.disableAll();
+ componentParametersView.setIgnoreUsers(false);
+ return componentParametersView;
+ }
+
+ private Either<GraphVertex, StorageOperationStatus> checkinToscaELement(LifecycleStateEnum currState, GraphVertex toscaElementVertex, GraphVertex ownerVertex, GraphVertex modifierVertex, LifecycleStateEnum nextState) {
+ Either<GraphVertex, StorageOperationStatus> updateRelationsRes;
+ Either<GraphVertex, StorageOperationStatus> result = changeStateToCheckedIn(currState, toscaElementVertex, ownerVertex, modifierVertex);
+ if(result.isLeft()) {
+ toscaElementVertex.addMetadataProperty(GraphPropertyEnum.STATE, nextState.name());
+ toscaElementVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis());
+ result = updateToscaElementVertexMetadataPropertiesAndJson(toscaElementVertex);
+ }
+ if(result.isLeft()){
+ updateRelationsRes = updateLastModifierEdge(toscaElementVertex, ownerVertex, modifierVertex);
+ if(updateRelationsRes.isRight()){
+ result = Either.right(updateRelationsRes.right().value());
+ }
+ }
+ return result;
+ }
+
+ private Either<GraphVertex, StorageOperationStatus> updateToscaElementVertexMetadataPropertiesAndJson(GraphVertex toscaElementVertex){
+
+ Either<GraphVertex, StorageOperationStatus> result;
+
+ Either<GraphVertex, TitanOperationStatus> updateVertexRes = titanDao.updateVertex(toscaElementVertex);
+ if (updateVertexRes.isRight()) {
+ TitanOperationStatus titatStatus = updateVertexRes.right().value();
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG,"Failed to update state of tosca element vertex {} metadata. Status is {}", toscaElementVertex.getUniqueId(), titatStatus);
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(titatStatus));
+ } else {
+ result = Either.left(updateVertexRes.left().value());
+ }
+ return result;
+ }
+
+ private Either<GraphVertex, StorageOperationStatus> changeStateToCheckedIn(LifecycleStateEnum currState, GraphVertex toscaElementVertex, GraphVertex ownerVertex, GraphVertex modifierVertex) {
+ Either<GraphVertex, StorageOperationStatus> result = null;
+ LifecycleStateEnum nextState = LifecycleStateEnum.NOT_CERTIFIED_CHECKIN;
+ String faileToUpdateStateMsg = "Failed to update state of tosca element {}. Status is {}";
+
+ if (currState == LifecycleStateEnum.READY_FOR_CERTIFICATION) {
+ //In case of cancel "ready for certification" remove last state edge with "STATE" property equals to "NOT_CERTIFIED_CHECKIN"
+ Map<GraphPropertyEnum, Object> vertexProperties = new HashMap<>();
+ vertexProperties.put(GraphPropertyEnum.STATE, nextState);
+ Either<Edge, TitanOperationStatus> deleteResult = titanDao.deleteBelongingEdgeByCriteria(toscaElementVertex, EdgeLabelEnum.LAST_STATE, vertexProperties);
+ if (deleteResult.isRight()) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG,faileToUpdateStateMsg, toscaElementVertex.getUniqueId(), deleteResult.right().value());
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG,"failed to update last state relation");
+ result = Either.right(StorageOperationStatus.INCONSISTENCY);
+ }
+ }
+ if(result == null) {
+ //Remove CHECKOUT relation
+ Either<Edge, TitanOperationStatus> deleteEdgeResult = titanDao.deleteEdge(ownerVertex, toscaElementVertex, EdgeLabelEnum.STATE);
+ if (deleteEdgeResult.isRight()) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG,faileToUpdateStateMsg, toscaElementVertex.getUniqueId());
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(deleteEdgeResult.right().value()));
+ }
+ }
+ if(result == null) {
+ //Create CHECKIN relation
+ Map<EdgePropertyEnum, Object> edgeProperties = new HashMap<>();
+ edgeProperties.put(EdgePropertyEnum.STATE, nextState);
+ TitanOperationStatus createEdgeRes = titanDao.createEdge(modifierVertex.getVertex(), toscaElementVertex.getVertex(), EdgeLabelEnum.STATE, edgeProperties);
+ if (createEdgeRes != TitanOperationStatus.OK) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG,faileToUpdateStateMsg, toscaElementVertex.getUniqueId());
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(createEdgeRes));
+ }
+ }
+ if(result == null) {
+ result = Either.left(toscaElementVertex);
+ }
+ return result;
+ }
+
+ private Either<GraphVertex, StorageOperationStatus> updateLastModifierEdge( GraphVertex toscaElementVertex, GraphVertex ownerVertex, GraphVertex modifierVertex) {
+ Either<GraphVertex, StorageOperationStatus> result = null;
+ if(!modifierVertex.getMetadataProperties().get(GraphPropertyEnum.USERID).equals(ownerVertex.getMetadataProperties().get(GraphPropertyEnum.USERID))){
+ Either<Edge, TitanOperationStatus> deleteEdgeRes = titanDao.deleteEdge(ownerVertex, toscaElementVertex, EdgeLabelEnum.LAST_MODIFIER);
+ if(deleteEdgeRes.isRight()){
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG,"Failed to delete last modifier {} to tosca element {}. Edge type is {}", ownerVertex.getUniqueId(), ownerVertex.getUniqueId(), EdgeLabelEnum.LAST_MODIFIER);
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(deleteEdgeRes.right().value()));
+ }
+ if(result == null) {
+ TitanOperationStatus createEdgeRes = titanDao.createEdge(modifierVertex.getVertex(), toscaElementVertex.getVertex(), EdgeLabelEnum.LAST_MODIFIER, new HashMap<>());
+
+ if(createEdgeRes != TitanOperationStatus.OK){
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG,"Failed to associate user {} to component {}. Edge type is {}", modifierVertex.getUniqueId(), ownerVertex.getUniqueId(), EdgeLabelEnum.LAST_MODIFIER);
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(createEdgeRes));
+ } else{
+ result = Either.left(modifierVertex);
+ }
+ }
+ } else{
+ result = Either.left(ownerVertex);
+ }
+ return result;
+ }
+
+ private Map<String, ImmutablePair<GraphPropertyEnum ,JsonParseFlagEnum>> prepareParametersToGetVerticesForCheckin(String toscaElementId, String modifierId, String ownerId) {
+ Map<String, ImmutablePair<GraphPropertyEnum ,JsonParseFlagEnum>> verticesToGetParameters = new HashMap<>();
+ verticesToGetParameters.put(toscaElementId, new ImmutablePair<>(GraphPropertyEnum.UNIQUE_ID, JsonParseFlagEnum.ParseMetadata));
+ verticesToGetParameters.put(modifierId, new ImmutablePair<>(GraphPropertyEnum.USERID,JsonParseFlagEnum.NoParse));
+ verticesToGetParameters.put(ownerId, new ImmutablePair<>(GraphPropertyEnum.USERID,JsonParseFlagEnum.NoParse));
+ return verticesToGetParameters;
+ }
+
+ private Map<String, ImmutablePair<GraphPropertyEnum ,JsonParseFlagEnum>> prepareParametersToGetVerticesForRequestCertification(String toscaElementId, String modifierId, String ownerId) {
+ Map<String, ImmutablePair<GraphPropertyEnum ,JsonParseFlagEnum>> verticesToGetParameters = new HashMap<>();
+ verticesToGetParameters.put(toscaElementId, new ImmutablePair<>(GraphPropertyEnum.UNIQUE_ID, JsonParseFlagEnum.ParseAll));
+ verticesToGetParameters.put(modifierId, new ImmutablePair<>(GraphPropertyEnum.USERID,JsonParseFlagEnum.NoParse));
+ verticesToGetParameters.put(ownerId, new ImmutablePair<>(GraphPropertyEnum.USERID,JsonParseFlagEnum.NoParse));
+ return verticesToGetParameters;
+ }
+
+ private Map<String, ImmutablePair<GraphPropertyEnum ,JsonParseFlagEnum>> prepareParametersToGetVerticesForCheckout(String toscaElementId, String modifierId, String ownerId) {
+ Map<String, ImmutablePair<GraphPropertyEnum ,JsonParseFlagEnum>> verticesToGetParameters = new HashMap<>();
+ verticesToGetParameters.put(toscaElementId, new ImmutablePair<>(GraphPropertyEnum.UNIQUE_ID, JsonParseFlagEnum.ParseAll));
+ verticesToGetParameters.put(modifierId, new ImmutablePair<>(GraphPropertyEnum.USERID,JsonParseFlagEnum.NoParse));
+ verticesToGetParameters.put(ownerId, new ImmutablePair<>(GraphPropertyEnum.USERID,JsonParseFlagEnum.NoParse));
+ return verticesToGetParameters;
+ }
+
+ private String getNextVersion(String currVersion) {
+ String[] versionParts = currVersion.split(VERSION_DELIMETER_REGEXP);
+ Integer minorVersion = Integer.parseInt(versionParts[1]) + 1;
+ return versionParts[0] + VERSION_DELIMETER + minorVersion;
+ }
+
+ private Integer getMinorVersion(String version) {
+ String[] versionParts = version.split(VERSION_DELIMETER_REGEXP);
+ return Integer.parseInt(versionParts[1]);
+ }
+
+ private Integer getMajorVersion(String version) {
+ String[] versionParts = version.split(VERSION_DELIMETER_REGEXP);
+ return Integer.parseInt(versionParts[0]);
+ }
+
+ private boolean isFirstCheckoutAfterCertification(String version) {
+ if(Integer.parseInt(version.split(VERSION_DELIMETER_REGEXP)[0]) != 0 && Integer.parseInt(version.split(VERSION_DELIMETER_REGEXP)[1]) == 1){
+ return true;
+ }
+ return false;
+ }
+}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperation.java
new file mode 100644
index 0000000000..95e65e1e82
--- /dev/null
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperation.java
@@ -0,0 +1,1198 @@
+package org.openecomp.sdc.be.model.jsontitan.operations;
+
+import java.lang.reflect.Type;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+
+import org.apache.tinkerpop.gremlin.structure.Direction;
+import org.apache.tinkerpop.gremlin.structure.Edge;
+import org.apache.tinkerpop.gremlin.structure.Vertex;
+import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
+import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
+import org.openecomp.sdc.be.dao.jsongraph.types.EdgePropertyEnum;
+import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
+import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
+import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
+import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+import org.openecomp.sdc.be.model.ComponentParametersView;
+import org.openecomp.sdc.be.model.LifecycleStateEnum;
+import org.openecomp.sdc.be.model.category.CategoryDefinition;
+import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
+import org.openecomp.sdc.be.model.jsontitan.datamodel.NodeType;
+import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate;
+import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement;
+import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
+import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
+import org.openecomp.sdc.be.resources.data.UserData;
+import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
+import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
+import org.openecomp.sdc.common.util.ValidationUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+
+import com.google.gson.Gson;
+import com.google.gson.reflect.TypeToken;
+
+import fj.data.Either;
+
+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;
+ }
+
+ private StorageOperationStatus associatePropertiesToResource(GraphVertex nodeTypeVertex, ToscaElement nodeType, List<GraphVertex> derivedResources) {
+ // Note : currently only one derived supported!!!!
+ Either<Map<String, PropertyDataDefinition>, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources, PropertyDataDefinition.class, 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 = PropertyDataDefinition.mergeProperties(propertiesAll, properties, false);
+ 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, Class<T> clazz, 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());
+ Either<GraphVertex, TitanOperationStatus> childResourceRes = titanDao.getChildVertex(componentV, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse);
+ while (childResourceRes.isLeft()) {
+ GraphVertex child = childResourceRes.left().value();
+ allVersion.put((String) child.getMetadataProperty(GraphPropertyEnum.VERSION), child.getUniqueId());
+ 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();
+ allVersion.put((String) parent.getMetadataProperty(GraphPropertyEnum.VERSION), parent.getUniqueId());
+ parentResourceRes = titanDao.getParentVertex(parent, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse);
+ }
+ operationStatus = parentResourceRes.right().value();
+ if (operationStatus != TitanOperationStatus.NOT_FOUND) {
+ return operationStatus;
+ } else {
+ 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 , ToscaElementTypeEnum toscaElement) {
+ Either<List<GraphVertex>, TitanOperationStatus> listOfHighestAndAllCertifiedComponents = this.getListOfHighestAndAllCertifiedComponents(componentType , toscaElement);
+ if (listOfHighestAndAllCertifiedComponents.isRight() && listOfHighestAndAllCertifiedComponents.right().value() != TitanOperationStatus.NOT_FOUND) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(listOfHighestAndAllCertifiedComponents.right().value()));
+ }
+ List<GraphVertex> highestAndAllCertified = listOfHighestAndAllCertifiedComponents.left().value();
+ List<T> result = new ArrayList<>();
+ 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 ligth element for {} error {}", vertexComponent.getUniqueId(), component.right().value());
+ return Either.right(component.right().value());
+ } else {
+ result.add(component.left().value());
+ }
+ }
+ }
+ return Either.left(result);
+ }
+
+
+public Either<List<GraphVertex>, TitanOperationStatus> getListOfHighestAndAllCertifiedComponents(ComponentTypeEnum componentType , ToscaElementTypeEnum toscaElement) {
+ long startFetchAllStates = System.currentTimeMillis();
+ Map<GraphPropertyEnum, Object> propertiesToMatchCertified = new HashMap<>();
+ propertiesToMatchCertified.put(GraphPropertyEnum.STATE , LifecycleStateEnum.CERTIFIED.name());
+ propertiesToMatchCertified.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
+ if (componentType == ComponentTypeEnum.RESOURCE ){
+ propertiesToMatchCertified.put(GraphPropertyEnum.IS_ABSTRACT, false);
+ }
+
+ Map<GraphPropertyEnum, Object> propertiesHasNotToMatchCertified = new HashMap<>();
+ propertiesHasNotToMatchCertified.put(GraphPropertyEnum.IS_DELETED, true);
+
+
+ Either<List<GraphVertex>, TitanOperationStatus> certifiedNodes = titanDao.getByCriteria(ToscaElementTypeEnum.getVertexTypeByToscaType(toscaElement) , propertiesToMatchCertified, propertiesHasNotToMatchCertified, JsonParseFlagEnum.ParseMetadata);
+ if (certifiedNodes.isRight() && certifiedNodes.right().value() != TitanOperationStatus.NOT_FOUND) {
+ return Either.right(certifiedNodes.right().value());
+ }
+
+ Map<GraphPropertyEnum, Object> propertiesToMatchHighest = new HashMap<>();
+ propertiesToMatchHighest.put(GraphPropertyEnum.IS_HIGHEST_VERSION , true);
+ propertiesToMatchHighest.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
+ if (componentType == ComponentTypeEnum.RESOURCE ){
+ propertiesToMatchHighest.put(GraphPropertyEnum.IS_ABSTRACT, false);
+ }
+
+
+ Map<GraphPropertyEnum, Object> propertiesHasNotToMatchHighest = new HashMap<>();
+ propertiesHasNotToMatchHighest.put(GraphPropertyEnum.IS_DELETED, true);
+ propertiesHasNotToMatchHighest.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
+
+
+ Either<List<GraphVertex>, TitanOperationStatus> highestNode = titanDao.getByCriteria(ToscaElementTypeEnum.getVertexTypeByToscaType(toscaElement) , propertiesToMatchHighest, propertiesHasNotToMatchHighest, JsonParseFlagEnum.ParseMetadata);
+ if (highestNode.isRight() && highestNode.right().value() != TitanOperationStatus.NOT_FOUND) {
+ return Either.right(highestNode.right().value());
+ }
+
+ long endFetchAllStates = System.currentTimeMillis();
+
+
+ List<GraphVertex> allNodes = new ArrayList<>();
+
+ if (certifiedNodes.isLeft()) {
+ allNodes.addAll(certifiedNodes.left().value());
+ }
+ if (highestNode.isLeft()){
+ allNodes.addAll(highestNode.left().value());
+ }
+
+ int certifiedSize;
+ int nonCertifiedSize;
+
+ if (certifiedNodes.isRight()){
+ certifiedSize = 0;
+ } else {
+ certifiedSize = certifiedNodes.left().value().size();
+ }
+
+ if (highestNode.isRight()){
+ nonCertifiedSize = 0;
+ } else {
+ nonCertifiedSize = highestNode.left().value().size();
+ }
+
+
+ log.debug("Fetch catalog {}s all states: certified {}, noncertified {}", componentType, certifiedSize , nonCertifiedSize );
+ log.debug("Fetch catalog {}s all states from graph took {} ms", componentType, endFetchAllStates - startFetchAllStates);
+ return Either.left(allNodes);
+}
+
+
+ protected Either<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);
+
+}
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
new file mode 100644
index 0000000000..9c7f108a05
--- /dev/null
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaOperationFacade.java
@@ -0,0 +1,2123 @@
+package org.openecomp.sdc.be.model.jsontitan.operations;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.EnumMap;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Optional;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import org.apache.commons.collections.CollectionUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.apache.commons.lang3.tuple.Pair;
+import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
+import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
+import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
+import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
+import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
+import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.openecomp.sdc.be.datatypes.components.ComponentMetadataDataDefinition;
+import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.AttributeDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.ListRequirementDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.MapArtifactDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.MapAttributesDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.MapCapabiltyProperty;
+import org.openecomp.sdc.be.datatypes.elements.MapListCapabiltyDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.MapListRequirementDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
+import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.ArtifactDefinition;
+import org.openecomp.sdc.be.model.AttributeDefinition;
+import org.openecomp.sdc.be.model.CapabilityDefinition;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.ComponentInstanceInput;
+import org.openecomp.sdc.be.model.ComponentInstanceProperty;
+import org.openecomp.sdc.be.model.ComponentParametersView;
+import org.openecomp.sdc.be.model.DistributionStatusEnum;
+import org.openecomp.sdc.be.model.GroupDefinition;
+import org.openecomp.sdc.be.model.GroupInstance;
+import org.openecomp.sdc.be.model.InputDefinition;
+import org.openecomp.sdc.be.model.LifecycleStateEnum;
+import org.openecomp.sdc.be.model.PropertyDefinition;
+import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
+import org.openecomp.sdc.be.model.RequirementDefinition;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate;
+import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement;
+import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum;
+import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
+import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
+import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
+import org.openecomp.sdc.be.utils.CommonBeUtils;
+import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
+import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
+import org.openecomp.sdc.common.util.ValidationUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+
+import fj.data.Either;
+
+@org.springframework.stereotype.Component("tosca-operation-facade")
+public class ToscaOperationFacade {
+ @Autowired
+ private NodeTypeOperation nodeTypeOperation;
+ @Autowired
+ private TopologyTemplateOperation topologyTemplateOperation;
+ @Autowired
+ private NodeTemplateOperation nodeTemplateOperation;
+ @Autowired
+ private GroupsOperation groupsOperation;
+ @Autowired
+ private TitanDao titanDao;
+
+ private static Logger log = LoggerFactory.getLogger(ToscaOperationFacade.class.getName());
+
+ public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId) {
+
+ return getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
+
+ }
+ public <T extends Component> Either<T, StorageOperationStatus> getToscaFullElement(String componentId) {
+ ComponentParametersView filters = new ComponentParametersView();
+ filters.setIgnoreCapabiltyProperties(false);
+
+ return getToscaElement(componentId, filters);
+ }
+ public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId, ComponentParametersView filters) {
+
+ Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, filters.detectParseFlag());
+ if (getVertexEither.isRight()) {
+ log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
+
+ }
+ return getToscaElementByOperation(getVertexEither.left().value(), filters);
+ }
+
+ public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId, JsonParseFlagEnum parseFlag) {
+
+ Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, parseFlag);
+ if (getVertexEither.isRight()) {
+ log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
+
+ }
+ return getToscaElementByOperation(getVertexEither.left().value());
+ }
+
+ public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(GraphVertex componentVertex) {
+ return getToscaElementByOperation(componentVertex);
+ }
+
+ public Either<Boolean, StorageOperationStatus> validateComponentExists(String componentId) {
+
+ Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
+ if (getVertexEither.isRight()) {
+ TitanOperationStatus status = getVertexEither.right().value();
+ if (status == TitanOperationStatus.NOT_FOUND) {
+ return Either.left(false);
+ } else {
+ log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
+ }
+ }
+ return Either.left(true);
+ }
+
+ public <T extends Component> Either<T, StorageOperationStatus> findLastCertifiedToscaElementByUUID(T component) {
+ Map<GraphPropertyEnum, Object> props = new HashMap<>();
+ props.put(GraphPropertyEnum.UUID, component.getUUID());
+ props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
+ props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+
+ Either<List<GraphVertex>, TitanOperationStatus> getVertexEither = titanDao.getByCriteria(ModelConverter.getVertexType(component), props);
+ if (getVertexEither.isRight()) {
+ log.debug("Couldn't fetch component with and unique id {}, error: {}", component.getUniqueId(), getVertexEither.right().value());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
+
+ }
+ return getToscaElementByOperation(getVertexEither.left().value().get(0));
+ }
+
+ private <T extends Component> Either<T, StorageOperationStatus> getToscaElementByOperation(GraphVertex componentV) {
+ return getToscaElementByOperation(componentV, new ComponentParametersView());
+ }
+
+ private <T extends Component> Either<T, StorageOperationStatus> getToscaElementByOperation(GraphVertex componentV, ComponentParametersView filters) {
+ VertexTypeEnum label = componentV.getLabel();
+
+ ToscaElementOperation toscaOperation = getToscaElementOperation(componentV);
+ Either<ToscaElement, StorageOperationStatus> toscaElement;
+ String componentId = componentV.getUniqueId();
+ if (toscaOperation != null) {
+ log.debug("Need to fetch tosca element for id {}", componentId);
+ toscaElement = toscaOperation.getToscaElement(componentV, filters);
+ } else {
+ log.debug("not supported tosca type {} for id {}", label, componentId);
+ toscaElement = Either.right(StorageOperationStatus.BAD_REQUEST);
+ }
+ if (toscaElement.isRight()) {
+ return Either.right(toscaElement.right().value());
+ }
+ return Either.left(ModelConverter.convertFromToscaElement(toscaElement.left().value()));
+ }
+
+ private ToscaElementOperation getToscaElementOperation(GraphVertex componentV) {
+ VertexTypeEnum label = componentV.getLabel();
+ switch (label) {
+ case NODE_TYPE:
+ return nodeTypeOperation;
+ case TOPOLOGY_TEMPLATE:
+ return topologyTemplateOperation;
+ default:
+ return null;
+ }
+ }
+
+ /**
+ *
+ * @param resource
+ * @return
+ */
+ public <T extends Component> Either<T, StorageOperationStatus> createToscaComponent(T resource) {
+ ToscaElement toscaElement = ModelConverter.convertToToscaElement(resource);
+
+ ToscaElementOperation toscaElementOperation = getToscaElementOperation(toscaElement);
+ Either<ToscaElement, StorageOperationStatus> createToscaElement = toscaElementOperation.createToscaElement(toscaElement);
+ if (createToscaElement.isLeft()) {
+ log.debug("Component created successfully!!!");
+ T dataModel = ModelConverter.convertFromToscaElement(createToscaElement.left().value());
+ return Either.left(dataModel);
+ }
+ return Either.right(createToscaElement.right().value());
+ }
+
+ /**
+ *
+ * @param componentToDelete
+ * @return
+ */
+ public StorageOperationStatus markComponentToDelete(Component componentToDelete) {
+
+ if ((componentToDelete.getIsDeleted() != null) && componentToDelete.getIsDeleted() && !componentToDelete.isHighestVersion()) {
+ // component already marked for delete
+ return StorageOperationStatus.OK;
+ } else {
+
+ Either<GraphVertex, TitanOperationStatus> getResponse = titanDao.getVertexById(componentToDelete.getUniqueId(), JsonParseFlagEnum.ParseAll);
+ if (getResponse.isRight()) {
+ log.debug("Couldn't fetch component with and unique id {}, error: {}", componentToDelete.getUniqueId(), getResponse.right().value());
+ return DaoStatusConverter.convertTitanStatusToStorageStatus(getResponse.right().value());
+
+ }
+ GraphVertex componentV = getResponse.left().value();
+
+ // same operation for node type and topology template operations
+ Either<GraphVertex, StorageOperationStatus> result = nodeTypeOperation.markComponentToDelete(componentV);
+ if (result.isRight()) {
+ return result.right().value();
+ }
+ return StorageOperationStatus.OK;
+ }
+ }
+
+ /**
+ *
+ * @param componentId
+ * @return
+ */
+ public <T extends Component> Either<T, StorageOperationStatus> deleteToscaComponent(String componentId) {
+
+ Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll);
+ if (getVertexEither.isRight()) {
+ log.debug("Couldn't fetch component vertex with and unique id {}, error: {}", componentId, getVertexEither.right().value());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
+
+ }
+ Either<ToscaElement, StorageOperationStatus> deleteElement = deleteToscaElement(getVertexEither.left().value());
+ if (deleteElement.isRight()) {
+ log.debug("Failed to delete component with and unique id {}, error: {}", componentId, deleteElement.right().value());
+ return Either.right(deleteElement.right().value());
+ }
+ T dataModel = ModelConverter.convertFromToscaElement(deleteElement.left().value());
+
+ return Either.left(dataModel);
+ }
+
+ private Either<ToscaElement, StorageOperationStatus> deleteToscaElement(GraphVertex componentV) {
+ VertexTypeEnum label = componentV.getLabel();
+ Either<ToscaElement, StorageOperationStatus> toscaElement;
+ Object componentId = componentV.getUniqueId();
+ switch (label) {
+ case NODE_TYPE:
+ log.debug("Need to fetch node type for id {}", componentId);
+ toscaElement = nodeTypeOperation.deleteToscaElement(componentV);
+ break;
+ case TOPOLOGY_TEMPLATE:
+ log.debug("Need to fetch topology template for id {}", componentId);
+ toscaElement = topologyTemplateOperation.deleteToscaElement(componentV);
+ break;
+ default:
+ log.debug("not supported tosca type {} for id {}", label, componentId);
+ toscaElement = Either.right(StorageOperationStatus.BAD_REQUEST);
+ break;
+ }
+ return toscaElement;
+ }
+
+ private ToscaElementOperation getToscaElementOperation(ToscaElement toscaElement) {
+
+ ComponentTypeEnum componentType = toscaElement.getComponentType();
+ switch (componentType) {
+ case RESOURCE:
+ ResourceTypeEnum resourceType = toscaElement.getResourceType();
+ if (resourceType == ResourceTypeEnum.VF) {
+ return topologyTemplateOperation;
+ } else {
+ return nodeTypeOperation;
+ }
+ case SERVICE:
+ case PRODUCT:
+ return topologyTemplateOperation;
+ default:
+ break;
+ }
+ return null;
+ }
+
+ private ToscaElementOperation getToscaElementOperation(Component component) {
+
+ switch (component.getComponentType()) {
+ case RESOURCE:
+ ResourceTypeEnum resourceType = ((Resource) component).getResourceType();
+ if (resourceType != null && resourceType == ResourceTypeEnum.VF) {
+ return topologyTemplateOperation;
+ } else {
+ return nodeTypeOperation;
+ }
+ case SERVICE:
+ case PRODUCT:
+ return topologyTemplateOperation;
+ default:
+ break;
+ }
+ return null;
+ }
+
+ public <T extends Component> Either<T, StorageOperationStatus> getLatestByToscaResourceName(String toscaResourceName) {
+ return getLatestByName(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName);
+
+ }
+
+ public <T extends Component> Either<T, StorageOperationStatus> getLatestByName(String resourceName) {
+ return getLatestByName(GraphPropertyEnum.NAME, resourceName);
+
+ }
+
+ public Either<Integer, StorageOperationStatus> validateCsarUuidUniqueness(String csarUUID) {
+ Either<List<ToscaElement>, StorageOperationStatus> byCsar = null;
+
+ Map<GraphPropertyEnum, Object> properties = new HashMap<GraphPropertyEnum, Object>();
+ properties.put(GraphPropertyEnum.CSAR_UUID, csarUUID);
+
+ Either<List<GraphVertex>, TitanOperationStatus> resources = titanDao.getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata);
+
+ if (resources.isRight()) {
+ if (resources.right().value() == TitanOperationStatus.NOT_FOUND) {
+ return Either.left(new Integer(0));
+ } else {
+ log.debug("failed to get resources from graph with property name: {}", csarUUID);
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resources.right().value()));
+ }
+ }
+
+ List<GraphVertex> resourceList = (resources.isLeft() ? resources.left().value() : null);
+
+ return Either.left(new Integer(resourceList.size()));
+
+ }
+
+ public <T extends Component> Either<List<T>, StorageOperationStatus> getFollowed(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates, ComponentTypeEnum componentType) {
+ Either<List<ToscaElement>, StorageOperationStatus> followedResources;
+ if (componentType == ComponentTypeEnum.RESOURCE) {
+ followedResources = nodeTypeOperation.getFollowedComponent(userId, lifecycleStates, lastStateStates, componentType);
+ } else {
+ followedResources = topologyTemplateOperation.getFollowedComponent(userId, lifecycleStates, lastStateStates, componentType);
+ }
+
+ List<T> components = new ArrayList<>();
+ if (followedResources.isRight() && followedResources.right().value() != StorageOperationStatus.NOT_FOUND) {
+ return Either.right(followedResources.right().value());
+ }
+ if (followedResources.isLeft()) {
+ List<ToscaElement> toscaElements = followedResources.left().value();
+ toscaElements.forEach(te -> {
+ T component = ModelConverter.convertFromToscaElement(te);
+ components.add(component);
+ });
+ }
+ return Either.left(components);
+ }
+
+ public Either<Resource, StorageOperationStatus> getLatestCertifiedNodeTypeByToscaResourceName(String toscaResourceName) {
+
+ return getLatestCertifiedByToscaResourceName(toscaResourceName, VertexTypeEnum.NODE_TYPE, JsonParseFlagEnum.ParseMetadata);
+ }
+
+ public Either<Resource, StorageOperationStatus> getLatestCertifiedByToscaResourceName(String toscaResourceName, VertexTypeEnum vertexType, JsonParseFlagEnum parseFlag) {
+
+ Either<Resource, StorageOperationStatus> result = null;
+ Map<GraphPropertyEnum, Object> props = new HashMap<GraphPropertyEnum, Object>();
+ props.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName);
+ props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+ props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
+ Either<List<GraphVertex>, TitanOperationStatus> getLatestRes = titanDao.getByCriteria(vertexType, props, parseFlag);
+
+ if (getLatestRes.isRight()) {
+ TitanOperationStatus status = getLatestRes.right().value();
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch {} with name {}. status={} ", vertexType, toscaResourceName, status);
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ if (result == null) {
+ List<GraphVertex> resources = getLatestRes.left().value();
+ double version = 0.0;
+ GraphVertex highestResource = null;
+ for (GraphVertex resource : resources) {
+ double resourceVersion = Double.parseDouble((String) resource.getJsonMetadataField(JsonPresentationFields.VERSION));
+ if (resourceVersion > version) {
+ version = resourceVersion;
+ highestResource = resource;
+ }
+ }
+ result = getToscaElement(highestResource.getUniqueId());
+ }
+ return result;
+ }
+
+ public Either<Boolean, StorageOperationStatus> validateToscaResourceNameExists(String templateName) {
+ Either<Boolean, StorageOperationStatus> validateUniquenessRes = validateToscaResourceNameUniqueness(templateName);
+ if (validateUniquenessRes.isLeft()) {
+ return Either.left(!validateUniquenessRes.left().value());
+ }
+ return validateUniquenessRes;
+ }
+
+ public Either<RequirementCapabilityRelDef, StorageOperationStatus> dissociateResourceInstances(String componentId, RequirementCapabilityRelDef requirementDef) {
+ return nodeTemplateOperation.dissociateResourceInstances(componentId, requirementDef);
+
+ }
+
+ public StorageOperationStatus associateResourceInstances(String componentId, List<RequirementCapabilityRelDef> relations) {
+ Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> status = nodeTemplateOperation.associateResourceInstances(componentId, relations);
+ if (status.isRight()) {
+ return status.right().value();
+ }
+ return StorageOperationStatus.OK;
+ }
+
+ protected Either<Boolean, StorageOperationStatus> validateToscaResourceNameUniqueness(String name) {
+
+ Map<GraphPropertyEnum, Object> properties = new HashMap<GraphPropertyEnum, Object>();
+ properties.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, name);
+
+ Either<List<GraphVertex>, TitanOperationStatus> resources = titanDao.getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata);
+
+ if (resources.isRight() && resources.right().value() != TitanOperationStatus.NOT_FOUND) {
+ log.debug("failed to get resources from graph with property name: {}", name);
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resources.right().value()));
+ }
+ List<GraphVertex> resourceList = (resources.isLeft() ? resources.left().value() : null);
+ if (resourceList != null && resourceList.size() > 0) {
+ if (log.isDebugEnabled()) {
+ StringBuilder builder = new StringBuilder();
+ for (GraphVertex resourceData : resourceList) {
+ builder.append(resourceData.getUniqueId() + "|");
+ }
+ log.debug("resources with property name:{} exists in graph. found {}", name, builder.toString());
+ }
+ return Either.left(false);
+ } else {
+ log.debug("resources with property name:{} does not exists in graph", name);
+ return Either.left(true);
+ }
+
+ }
+
+ /**
+ *
+ * @param newComponent
+ * @param oldComponent
+ * @return
+ */
+ public <T extends Component> Either<T, StorageOperationStatus> overrideComponent(T newComponent, T oldComponent) {
+
+ // TODO
+ // newComponent.setInterfaces(oldComponent.getInterfaces);
+ newComponent.setArtifacts(oldComponent.getArtifacts());
+ newComponent.setDeploymentArtifacts(oldComponent.getDeploymentArtifacts());
+ newComponent.setGroups(oldComponent.getGroups());
+ newComponent.setInputs(null);
+ newComponent.setLastUpdateDate(null);
+ newComponent.setHighestVersion(true);
+
+ Either<GraphVertex, TitanOperationStatus> componentVEither = titanDao.getVertexById(oldComponent.getUniqueId(), JsonParseFlagEnum.NoParse);
+ if (componentVEither.isRight()) {
+ log.debug("Falied to fetch component {} error {}", oldComponent.getUniqueId(), componentVEither.right().value());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(componentVEither.right().value()));
+ }
+ GraphVertex componentv = componentVEither.left().value();
+ Either<GraphVertex, TitanOperationStatus> parentVertexEither = titanDao.getParentVertex(componentv, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse);
+ if (parentVertexEither.isRight() && parentVertexEither.right().value() != TitanOperationStatus.NOT_FOUND) {
+ log.debug("Falied to fetch parent version for component {} error {}", oldComponent.getUniqueId(), parentVertexEither.right().value());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(parentVertexEither.right().value()));
+ }
+
+ Either<ToscaElement, StorageOperationStatus> deleteToscaComponent = deleteToscaElement(componentv);
+ if (deleteToscaComponent.isRight()) {
+ log.debug("Falied to remove old component {} error {}", oldComponent.getUniqueId(), deleteToscaComponent.right().value());
+ return Either.right(deleteToscaComponent.right().value());
+ }
+ Either<T, StorageOperationStatus> createToscaComponent = createToscaComponent(newComponent);
+ if (createToscaComponent.isRight()) {
+ log.debug("Falied to create tosca element component {} error {}", newComponent.getUniqueId(), createToscaComponent.right().value());
+ return Either.right(createToscaComponent.right().value());
+ }
+ T newElement = createToscaComponent.left().value();
+ Either<GraphVertex, TitanOperationStatus> newVersionEither = titanDao.getVertexById(newElement.getUniqueId(), JsonParseFlagEnum.NoParse);
+ if (newVersionEither.isRight()) {
+ log.debug("Falied to fetch new tosca element component {} error {}", newComponent.getUniqueId(), newVersionEither.right().value());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(newVersionEither.right().value()));
+ }
+ if (parentVertexEither.isLeft()) {
+ GraphVertex previousVersionV = parentVertexEither.left().value();
+ TitanOperationStatus createEdge = titanDao.createEdge(previousVersionV, newVersionEither.left().value(), EdgeLabelEnum.VERSION, null);
+ if (createEdge != TitanOperationStatus.OK) {
+ log.debug("Falied to associate to previous version {} new version {} error {}", previousVersionV.getUniqueId(), newVersionEither.right().value(), createEdge);
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(createEdge));
+ }
+ }
+ return Either.left(newElement);
+ }
+
+ /**
+ *
+ * @param componentToUpdate
+ * @return
+ */
+ public <T extends Component> Either<T, StorageOperationStatus> updateToscaElement(T componentToUpdate) {
+ return updateToscaElement(componentToUpdate, new ComponentParametersView());
+ }
+
+ /**
+ *
+ * @param componentToUpdate
+ * @param type
+ * @param filterResult
+ * @return
+ */
+ public <T extends Component> Either<T, StorageOperationStatus> updateToscaElement(T componentToUpdate, ComponentParametersView filterResult) {
+ String componentId = componentToUpdate.getUniqueId();
+ Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll);
+ if (getVertexEither.isRight()) {
+ log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
+ }
+ GraphVertex elementV = getVertexEither.left().value();
+ ToscaElementOperation toscaElementOperation = getToscaElementOperation(elementV);
+
+ ToscaElement toscaElementToUpdate = ModelConverter.convertToToscaElement(componentToUpdate);
+ Either<ToscaElement, StorageOperationStatus> updateToscaElement = toscaElementOperation.updateToscaElement(toscaElementToUpdate, elementV, filterResult);
+ if (updateToscaElement.isRight()) {
+ log.debug("Failed to update tosca element {} error {}", componentId, updateToscaElement.right().value());
+ return Either.right(updateToscaElement.right().value());
+ }
+ return Either.left(ModelConverter.convertFromToscaElement(updateToscaElement.left().value()));
+ }
+
+ private <T extends Component> Either<T, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName) {
+ Either<T, StorageOperationStatus> result;
+
+ Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
+ Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
+
+ propertiesToMatch.put(property, nodeName);
+ propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+
+ propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
+
+ Either<List<GraphVertex>, TitanOperationStatus> highestResources = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseMetadata);
+ if (highestResources.isRight()) {
+ TitanOperationStatus status = highestResources.right().value();
+ log.debug("failed to find resource with name {}. status={} ", nodeName, status);
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ return result;
+ }
+
+ List<GraphVertex> resources = highestResources.left().value();
+ double version = 0.0;
+ GraphVertex highestResource = null;
+ for (GraphVertex vertex : resources) {
+ Object versionObj = vertex.getMetadataProperty(GraphPropertyEnum.VERSION);
+ double resourceVersion = Double.valueOf((String) versionObj);
+ if (resourceVersion > version) {
+ version = resourceVersion;
+ highestResource = vertex;
+ }
+ }
+ return getToscaElementByOperation(highestResource);
+ }
+
+ public <T extends Component> Either<List<T>, StorageOperationStatus> getBySystemName(ComponentTypeEnum componentType, String systemName) {
+
+ Either<List<T>, StorageOperationStatus> result = null;
+ Either<T, StorageOperationStatus> getComponentRes;
+ List<T> components = new ArrayList<>();
+ List<GraphVertex> componentVertices;
+ Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
+ Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
+
+ propertiesToMatch.put(GraphPropertyEnum.SYSTEM_NAME, systemName);
+ if (componentType != null)
+ propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
+
+ propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
+
+ Either<List<GraphVertex>, TitanOperationStatus> getComponentsRes = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
+ if (getComponentsRes.isRight()) {
+ TitanOperationStatus status = getComponentsRes.right().value();
+ log.debug("Failed to fetch the component with system name {}. Status is {} ", systemName, status);
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ if (result == null) {
+ componentVertices = getComponentsRes.left().value();
+ for (GraphVertex componentVertex : componentVertices) {
+ getComponentRes = getToscaElementByOperation(componentVertex);
+ if (getComponentRes.isRight()) {
+ log.debug("Failed to get the component {}. Status is {} ", componentVertex.getJsonMetadataField(JsonPresentationFields.NAME), getComponentRes.right().value());
+ result = Either.right(getComponentRes.right().value());
+ break;
+ }
+ T componentBySystemName = getComponentRes.left().value();
+ log.debug("Found component, id: {}", componentBySystemName.getUniqueId());
+ components.add(componentBySystemName);
+ }
+ }
+ if (result == null) {
+ result = Either.left(components);
+ }
+ return result;
+ }
+
+ public <T extends Component> Either<T, StorageOperationStatus> getComponentByNameAndVersion(ComponentTypeEnum componentType, String name, String version) {
+ return getComponentByNameAndVersion(componentType, name, version, JsonParseFlagEnum.ParseAll);
+ }
+
+ public <T extends Component> Either<T, StorageOperationStatus> getComponentByNameAndVersion(ComponentTypeEnum componentType, String name, String version, JsonParseFlagEnum parseFlag) {
+ Either<T, StorageOperationStatus> result;
+
+ Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
+ Map<GraphPropertyEnum, Object> hasNotProperties = new EnumMap<>(GraphPropertyEnum.class);
+
+ hasProperties.put(GraphPropertyEnum.NAME, name);
+ hasProperties.put(GraphPropertyEnum.VERSION, version);
+ hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true);
+ if (componentType != null) {
+ hasProperties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
+ }
+ Either<List<GraphVertex>, TitanOperationStatus> getResourceRes = titanDao.getByCriteria(null, hasProperties, hasNotProperties, parseFlag);
+ if (getResourceRes.isRight()) {
+ TitanOperationStatus status = getResourceRes.right().value();
+ log.debug("failed to find resource with name {}, version {}. Status is {} ", name, version, status);
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ return result;
+ }
+ return getToscaElementByOperation(getResourceRes.left().value().get(0));
+ }
+
+ public <T extends Component> Either<List<T>, StorageOperationStatus> getCatalogComponents(ComponentTypeEnum componentType) {
+ List<T> components = new ArrayList<>();
+ Either<List<ToscaElement>, StorageOperationStatus> catalogDataResult;
+ List<ToscaElement> toscaElements;
+ switch (componentType) {
+ case RESOURCE:
+ catalogDataResult = nodeTypeOperation.getElementCatalogData(ComponentTypeEnum.RESOURCE ,ToscaElementTypeEnum.NodeType);
+ if (catalogDataResult.isRight()) {
+ return Either.right(catalogDataResult.right().value());
+ }
+ toscaElements = catalogDataResult.left().value();
+ Either<List<ToscaElement>, StorageOperationStatus> resourceCatalogData = topologyTemplateOperation.getElementCatalogData(ComponentTypeEnum.RESOURCE ,ToscaElementTypeEnum.TopologyTemplate);
+ if (resourceCatalogData.isRight()) {
+ return Either.right(resourceCatalogData.right().value());
+ }
+ toscaElements.addAll(resourceCatalogData.left().value());
+ break;
+ case SERVICE:
+ catalogDataResult = topologyTemplateOperation.getElementCatalogData(ComponentTypeEnum.SERVICE , ToscaElementTypeEnum.TopologyTemplate);
+ if (catalogDataResult.isRight()) {
+ return Either.right(catalogDataResult.right().value());
+ }
+ toscaElements = catalogDataResult.left().value();
+ break;
+ default:
+ log.debug("Not supported component type {}", componentType);
+ return Either.right(StorageOperationStatus.BAD_REQUEST);
+ }
+ toscaElements.forEach(te -> {
+ T component = ModelConverter.convertFromToscaElement(te);
+ components.add(component);
+ });
+ return Either.left(components);
+ }
+
+ public Either<List<String>, StorageOperationStatus> deleteMarkedElements(ComponentTypeEnum componentType) {
+ Either<List<GraphVertex>, StorageOperationStatus> allComponentsMarkedForDeletion;
+ List<String> deleted = new ArrayList<>();
+ switch (componentType) {
+ case RESOURCE:
+ allComponentsMarkedForDeletion = nodeTypeOperation.getAllComponentsMarkedForDeletion(componentType);
+ break;
+ case SERVICE:
+ case PRODUCT:
+ allComponentsMarkedForDeletion = topologyTemplateOperation.getAllComponentsMarkedForDeletion(componentType);
+ break;
+ default:
+ log.debug("Not supported component type {}", componentType);
+ return Either.right(StorageOperationStatus.BAD_REQUEST);
+ }
+ if (allComponentsMarkedForDeletion.isRight()) {
+ return Either.right(allComponentsMarkedForDeletion.right().value());
+ }
+ List<GraphVertex> allMarked = allComponentsMarkedForDeletion.left().value();
+
+ Either<List<GraphVertex>, TitanOperationStatus> allNotDeletedElements = topologyTemplateOperation.getAllNotDeletedElements();
+ if (allNotDeletedElements.isRight()) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(allNotDeletedElements.right().value()));
+ }
+ List<GraphVertex> allNonMarked = allNotDeletedElements.left().value();
+ for (GraphVertex elementV : allMarked) {
+ if (topologyTemplateOperation.isInUse(elementV, allNonMarked) == false) {
+ Either<ToscaElement, StorageOperationStatus> deleteToscaElement = deleteToscaElement(elementV);
+ if (deleteToscaElement.isRight()) {
+ log.debug("Failed to delete marked element {} error {}", elementV.getUniqueId(), deleteToscaElement.right().value());
+ }
+ } else {
+ deleted.add(elementV.getUniqueId());
+ log.debug("Marked element {} in use. don't delete it", elementV.getUniqueId());
+ }
+ }
+ return Either.left(deleted);
+ }
+
+ public Either<List<String>, StorageOperationStatus> getAllComponentsMarkedForDeletion(ComponentTypeEnum componentType) {
+ Either<List<GraphVertex>, StorageOperationStatus> allComponentsMarkedForDeletion;
+ switch (componentType) {
+ case RESOURCE:
+ allComponentsMarkedForDeletion = nodeTypeOperation.getAllComponentsMarkedForDeletion(componentType);
+ break;
+ case SERVICE:
+ case PRODUCT:
+ allComponentsMarkedForDeletion = topologyTemplateOperation.getAllComponentsMarkedForDeletion(componentType);
+ break;
+ default:
+ log.debug("Not supported component type {}", componentType);
+ return Either.right(StorageOperationStatus.BAD_REQUEST);
+ }
+ if (allComponentsMarkedForDeletion.isRight()) {
+ return Either.right(allComponentsMarkedForDeletion.right().value());
+ }
+ return Either.left(allComponentsMarkedForDeletion.left().value().stream().map(v -> v.getUniqueId()).collect(Collectors.toList()));
+ }
+
+ public Either<Boolean, StorageOperationStatus> isComponentInUse(String componentId) {
+ Either<Boolean, StorageOperationStatus> result;
+ Either<List<GraphVertex>, TitanOperationStatus> allNotDeletedElements = topologyTemplateOperation.getAllNotDeletedElements();
+ if (allNotDeletedElements.isRight()) {
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(allNotDeletedElements.right().value()));
+ } else {
+ result = Either.left(topologyTemplateOperation.isInUse(componentId, allNotDeletedElements.left().value()));
+ }
+ return result;
+ }
+
+ public Either<ImmutablePair<Component, String>, StorageOperationStatus> addComponentInstanceToTopologyTemplate(Component containerComponent, Component origComponent, ComponentInstance componentInstance, boolean allowDeleted, User user) {
+
+ Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;
+ Either<ToscaElement, StorageOperationStatus> updateContainerComponentRes = null;
+ componentInstance.setIcon(origComponent.getIcon());
+ Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> addResult = nodeTemplateOperation.addComponentInstanceToTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent),
+ ModelConverter.convertToToscaElement(origComponent), getNextComponentInstanceCounter(containerComponent, origComponent.getName()), componentInstance, allowDeleted, user);
+
+ if (addResult.isRight()) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the component instance {} to container component {}. ", componentInstance.getName(), containerComponent.getName());
+ result = Either.right(addResult.right().value());
+ }
+ if (result == null) {
+ updateContainerComponentRes = topologyTemplateOperation.getToscaElement(containerComponent.getUniqueId());
+ if (updateContainerComponentRes.isRight()) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {} with updated component instance {}. ", containerComponent.getName(), componentInstance.getName());
+ result = Either.right(updateContainerComponentRes.right().value());
+ }
+ }
+ if (result == null) {
+ Component updatedComponent = ModelConverter.convertFromToscaElement(updateContainerComponentRes.left().value());
+ String createdInstanceId = addResult.left().value().getRight();
+ CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The component instance {} has been added to container component {}. ", createdInstanceId, updatedComponent.getName());
+ result = Either.left(new ImmutablePair<>(updatedComponent, createdInstanceId));
+ }
+ return result;
+ }
+
+ public StorageOperationStatus associateComponentInstancesToComponent(Component containerComponent, Map<ComponentInstance, Resource> resourcesInstancesMap, boolean allowDeleted) {
+
+ StorageOperationStatus result = null;
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Going to add component instances to component {}", containerComponent.getUniqueId());
+
+ Either<GraphVertex, TitanOperationStatus> metadataVertex = titanDao.getVertexById(containerComponent.getUniqueId(), JsonParseFlagEnum.ParseAll);
+ if (metadataVertex.isRight()) {
+ TitanOperationStatus status = metadataVertex.right().value();
+ if (status == TitanOperationStatus.NOT_FOUND) {
+ status = TitanOperationStatus.INVALID_ID;
+ }
+ result = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
+ }
+ if (result == null) {
+ result = nodeTemplateOperation.associateComponentInstancesToComponent(containerComponent, resourcesInstancesMap, metadataVertex.left().value(), allowDeleted);
+ }
+ return result;
+ }
+
+ public Either<ImmutablePair<Component, String>, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent, Component origComponent, ComponentInstance componentInstance) {
+
+ Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;
+
+ CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update the metadata of the component instance {} belonging to container component {}. ", componentInstance.getName(), containerComponent.getName());
+ componentInstance.setIcon(origComponent.getIcon());
+ Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> updateResult = nodeTemplateOperation.updateComponentInstanceMetadataOfTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent),
+ ModelConverter.convertToToscaElement(origComponent), componentInstance);
+ if (updateResult.isRight()) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the metadata of the component instance {} belonging to container component {}. ", componentInstance.getName(), containerComponent.getName());
+ result = Either.right(updateResult.right().value());
+ }
+ if (result == null) {
+ Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value().getLeft());
+ String createdInstanceId = updateResult.left().value().getRight();
+ CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The metadata of the component instance {} has been updated to container component {}. ", createdInstanceId, updatedComponent.getName());
+ result = Either.left(new ImmutablePair<>(updatedComponent, createdInstanceId));
+ }
+ return result;
+ }
+
+ public Either<Component, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent) {
+
+ Either<Component, StorageOperationStatus> result = null;
+
+ CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update the metadata belonging to container component {}. ", containerComponent.getName());
+
+ Either<TopologyTemplate, StorageOperationStatus> updateResult = nodeTemplateOperation.updateComponentInstanceMetadataOfTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent));
+ if (updateResult.isRight()) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the metadata belonging to container component {}. ", containerComponent.getName());
+ result = Either.right(updateResult.right().value());
+ }
+ if (result == null) {
+ Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value());
+ CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The metadata has been updated to container component {}. ", updatedComponent.getName());
+ result = Either.left(updatedComponent);
+ }
+ return result;
+ }
+
+ public Either<ImmutablePair<Component, String>, StorageOperationStatus> deleteComponentInstanceFromTopologyTemplate(Component containerComponent, String resourceInstanceId) {
+
+ Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;
+
+ CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to delete the component instance {} belonging to container component {}. ", resourceInstanceId, containerComponent.getName());
+
+ Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> updateResult = nodeTemplateOperation.deleteComponentInstanceFromTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), resourceInstanceId);
+ if (updateResult.isRight()) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete the component instance {} belonging to container component {}. ", resourceInstanceId, containerComponent.getName());
+ result = Either.right(updateResult.right().value());
+ }
+ if (result == null) {
+ Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value().getLeft());
+ String deletedInstanceId = updateResult.left().value().getRight();
+ CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The component instance {} has been deleted from container component {}. ", deletedInstanceId, updatedComponent.getName());
+ result = Either.left(new ImmutablePair<>(updatedComponent, deletedInstanceId));
+ }
+ return result;
+ }
+
+ private String getNextComponentInstanceCounter(Component containerComponent, String originResourceName) {
+
+ Integer nextCounter = 0;
+
+ if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstances())) {
+
+ String normalizedName = ValidationUtils.normalizeComponentInstanceName(originResourceName);
+ Integer maxCounterFromNames = getMaxCounterFromNames(containerComponent, normalizedName);
+ Integer maxCounterFromIds = getMaxCounterFromIds(containerComponent, normalizedName);
+
+ if (maxCounterFromNames == null && maxCounterFromIds != null) {
+ nextCounter = maxCounterFromIds + 1;
+ } else if (maxCounterFromIds == null && maxCounterFromNames != null) {
+ nextCounter = maxCounterFromNames + 1;
+ } else if (maxCounterFromIds != null && maxCounterFromNames != null) {
+ nextCounter = maxCounterFromNames > maxCounterFromIds ? maxCounterFromNames + 1 : maxCounterFromIds + 1;
+ }
+ }
+ return nextCounter.toString();
+ }
+
+ private Integer getMaxCounterFromNames(Component containerComponent, String normalizedName) {
+
+ Integer maxCounter = 0;
+ List<String> countersStr = containerComponent.getComponentInstances().stream().filter(ci -> ci.getNormalizedName() != null && ci.getNormalizedName().startsWith(normalizedName)).map(ci -> ci.getNormalizedName().split(normalizedName)[1])
+ .collect(Collectors.toList());
+
+ if (CollectionUtils.isEmpty(countersStr)) {
+ return null;
+ }
+ Integer currCounter = null;
+ for (String counter : countersStr) {
+ if (StringUtils.isEmpty(counter)) {
+ continue;
+ }
+ try {
+ currCounter = Integer.parseInt(counter);
+ } catch (Exception e) {
+ continue;
+ }
+ maxCounter = maxCounter < currCounter ? currCounter : maxCounter;
+ }
+ if (currCounter == null) {
+ return null;
+ }
+ return maxCounter;
+ }
+
+ private Integer getMaxCounterFromIds(Component containerComponent, String normalizedName) {
+
+ Integer maxCounter = 0;
+ List<String> countersStr = containerComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId() != null && ci.getUniqueId().contains(normalizedName)).map(ci -> ci.getUniqueId().split(normalizedName)[1])
+ .collect(Collectors.toList());
+
+ if (CollectionUtils.isEmpty(countersStr)) {
+ return null;
+ }
+ Integer currCounter = null;
+ for (String counter : countersStr) {
+ if (StringUtils.isEmpty(counter)) {
+ continue;
+ }
+ try {
+ currCounter = Integer.parseInt(counter);
+ } catch (Exception e) {
+ continue;
+ }
+ maxCounter = maxCounter < currCounter ? currCounter : maxCounter;
+ }
+ if (currCounter == null) {
+ return null;
+ }
+ return maxCounter;
+ }
+
+ public Either<RequirementCapabilityRelDef, StorageOperationStatus> associateResourceInstances(String componentId, RequirementCapabilityRelDef requirementDef) {
+ return nodeTemplateOperation.associateResourceInstances(componentId, requirementDef);
+
+ }
+
+ public Either<List<InputDefinition>, StorageOperationStatus> createAndAssociateInputs(Map<String, InputDefinition> inputs, String componentId) {
+
+ Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
+ if (getVertexEither.isRight()) {
+ log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
+
+ }
+
+ GraphVertex vertex = getVertexEither.left().value();
+ Map<String, PropertyDataDefinition> inputsMap = inputs.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new PropertyDataDefinition(e.getValue())));
+
+ StorageOperationStatus status = topologyTemplateOperation.associateInputsToComponent(vertex, inputsMap, componentId);
+
+ if (StorageOperationStatus.OK == status) {
+ log.debug("Component created successfully!!!");
+ List<InputDefinition> inputsResList = null;
+ if (inputsMap != null && !inputsMap.isEmpty()) {
+ inputsResList = inputsMap.values().stream().map(i -> new InputDefinition(i)).collect(Collectors.toList());
+ }
+ return Either.left(inputsResList);
+ }
+ return Either.right(status);
+
+ }
+
+ public Either<List<InputDefinition>, StorageOperationStatus> addInputsToComponent(Map<String, InputDefinition> inputs, String componentId) {
+
+ Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
+ if (getVertexEither.isRight()) {
+ log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
+
+ }
+
+ GraphVertex vertex = getVertexEither.left().value();
+ Map<String, PropertyDataDefinition> inputsMap = inputs.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new PropertyDataDefinition(e.getValue())));
+
+ StorageOperationStatus status = topologyTemplateOperation.addToscaDataToToscaElement(vertex, EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputsMap, JsonPresentationFields.NAME);
+
+ if (StorageOperationStatus.OK == status) {
+ log.debug("Component created successfully!!!");
+ List<InputDefinition> inputsResList = null;
+ if (inputsMap != null && !inputsMap.isEmpty()) {
+ inputsResList = inputsMap.values().stream().map(i -> new InputDefinition(i)).collect(Collectors.toList());
+ }
+ return Either.left(inputsResList);
+ }
+ return Either.right(status);
+
+ }
+
+ public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> associateComponentInstancePropertiesToComponent(Map<String, List<ComponentInstanceProperty>> instProperties, String componentId) {
+
+ Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
+ if (getVertexEither.isRight()) {
+ log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
+
+ }
+
+ GraphVertex vertex = getVertexEither.left().value();
+ Map<String, MapPropertiesDataDefinition> instPropsMap = new HashMap<>();
+ if (instProperties != null) {
+
+ MapPropertiesDataDefinition propertiesMap;
+ for (Entry<String, List<ComponentInstanceProperty>> entry : instProperties.entrySet()) {
+ propertiesMap = new MapPropertiesDataDefinition();
+
+ propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new PropertyDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e)));
+
+ instPropsMap.put(entry.getKey(), propertiesMap);
+ }
+ }
+
+ StorageOperationStatus status = topologyTemplateOperation.associateInstPropertiesToComponent(vertex, instPropsMap);
+
+ if (StorageOperationStatus.OK == status) {
+ log.debug("Component created successfully!!!");
+ return Either.left(instProperties);
+ }
+ return Either.right(status);
+
+ }
+
+ public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addComponentInstanceInputsToComponent(Map<String, List<ComponentInstanceInput>> instProperties, String componentId) {
+
+ Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
+ if (getVertexEither.isRight()) {
+ log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
+
+ }
+
+ GraphVertex vertex = getVertexEither.left().value();
+ Map<String, MapPropertiesDataDefinition> instPropsMap = new HashMap<>();
+ if (instProperties != null) {
+
+ MapPropertiesDataDefinition propertiesMap;
+ for (Entry<String, List<ComponentInstanceInput>> entry : instProperties.entrySet()) {
+ propertiesMap = new MapPropertiesDataDefinition();
+
+ propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new PropertyDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e)));
+
+ instPropsMap.put(entry.getKey(), propertiesMap);
+ }
+ }
+
+ StorageOperationStatus status = topologyTemplateOperation.addInstInputsToComponent(vertex, instPropsMap);
+
+ if (StorageOperationStatus.OK == status) {
+ log.debug("Component created successfully!!!");
+ return Either.left(instProperties);
+ }
+ return Either.right(status);
+
+ }
+
+ public StorageOperationStatus deleteComponentInstanceInputsToComponent(Map<String, List<ComponentInstanceInput>> instProperties, String componentId) {
+
+ Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
+ if (getVertexEither.isRight()) {
+ log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
+ return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value());
+
+ }
+
+ GraphVertex vertex = getVertexEither.left().value();
+ Map<String, MapPropertiesDataDefinition> instPropsMap = new HashMap<>();
+ if (instProperties != null) {
+
+ MapPropertiesDataDefinition propertiesMap;
+ for (Entry<String, List<ComponentInstanceInput>> entry : instProperties.entrySet()) {
+ propertiesMap = new MapPropertiesDataDefinition();
+
+ propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new PropertyDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e)));
+
+ instPropsMap.put(entry.getKey(), propertiesMap);
+ }
+ }
+
+ return topologyTemplateOperation.deleteInstInputsToComponent(vertex, instPropsMap);
+
+ }
+
+ public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addComponentInstancePropertiesToComponent(Component containerComponent, Map<String, List<ComponentInstanceProperty>> instProperties, String componentId) {
+
+ StorageOperationStatus status = StorageOperationStatus.OK;
+ if (instProperties != null) {
+
+ for (Entry<String, List<ComponentInstanceProperty>> entry : instProperties.entrySet()) {
+ List<ComponentInstanceProperty> props = entry.getValue();
+ String componentInstanseId = entry.getKey();
+ List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(componentInstanseId);
+ if (props != null && !props.isEmpty()) {
+ for (ComponentInstanceProperty property : props) {
+ Optional<ComponentInstanceProperty> instanceProperty = instanceProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
+ if (instanceProperty.isPresent()) {
+ status = updateComponentInstanceProperty(containerComponent, componentInstanseId, property);
+ } else {
+ status = addComponentInstanceProperty(containerComponent, componentInstanseId, property);
+ }
+
+ }
+ }
+ }
+ }
+
+ return Either.left(instProperties);
+
+ }
+
+ public StorageOperationStatus associateArtifactToInstances(Map<String, Map<String, ArtifactDefinition>> instArtifacts, String componentId, User user) {
+
+ Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
+ if (getVertexEither.isRight()) {
+ log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
+ return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value());
+
+ }
+
+ GraphVertex vertex = getVertexEither.left().value();
+ Map<String, MapArtifactDataDefinition> instArtMap = new HashMap<>();
+ if (instArtifacts != null) {
+
+ MapArtifactDataDefinition artifactsMap;
+ for (Entry<String, Map<String, ArtifactDefinition>> entry : instArtifacts.entrySet()) {
+ Map<String, ArtifactDefinition> artList = entry.getValue();
+ Map<String, ArtifactDataDefinition> artifacts = artList.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
+ artifactsMap = nodeTemplateOperation.prepareInstDeploymentArtifactPerInstance(artifacts, entry.getKey(), user, NodeTemplateOperation.HEAT_VF_ENV_NAME);
+
+ instArtMap.put(entry.getKey(), artifactsMap);
+ }
+ }
+
+ return topologyTemplateOperation.associateInstArtifactToComponent(vertex, instArtMap);
+
+ }
+
+ public StorageOperationStatus associateInstAttributeToComponentToInstances(Map<String, List<AttributeDefinition>> instArttributes, String componentId) {
+
+ Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
+ if (getVertexEither.isRight()) {
+ log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
+ return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value());
+
+ }
+
+ GraphVertex vertex = getVertexEither.left().value();
+ Map<String, MapAttributesDataDefinition> instAttr = new HashMap<>();
+ if (instArttributes != null) {
+
+ MapAttributesDataDefinition attributesMap;
+ for (Entry<String, List<AttributeDefinition>> entry : instArttributes.entrySet()) {
+ attributesMap = new MapAttributesDataDefinition();
+ attributesMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new AttributeDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e)));
+ instAttr.put(entry.getKey(), attributesMap);
+ }
+ }
+
+ return topologyTemplateOperation.associateInstAttributeToComponent(vertex, instAttr);
+
+ }
+
+ public StorageOperationStatus associateCalculatedCapReq(Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties, Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instReg, String componentId) {
+ Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
+ if (getVertexEither.isRight()) {
+ log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
+ return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value());
+
+ }
+
+ GraphVertex vertex = getVertexEither.left().value();
+
+ Map<String, MapListRequirementDataDefinition> calcRequirements = new HashMap<>();
+
+ Map<String, MapListCapabiltyDataDefinition> calcCapabilty = new HashMap<>();
+ Map<String, MapCapabiltyProperty> calculatedCapabilitiesProperties = new HashMap<>();;
+ if (instCapabilties != null) {
+ for (Entry<ComponentInstance, Map<String, List<CapabilityDefinition>>> entry : instCapabilties.entrySet()) {
+
+ Map<String, List<CapabilityDefinition>> caps = entry.getValue();
+ Map<String, ListCapabilityDataDefinition> mapToscaDataDefinition = new HashMap<>();
+ for (Entry<String, List<CapabilityDefinition>> instCapability : caps.entrySet()) {
+ mapToscaDataDefinition.put(instCapability.getKey(), new ListCapabilityDataDefinition(instCapability.getValue().stream().map(iCap -> new CapabilityDataDefinition(iCap)).collect(Collectors.toList())));
+ }
+
+ ComponentInstanceDataDefinition componentInstance = new ComponentInstanceDataDefinition(entry.getKey());
+ MapListCapabiltyDataDefinition capMap = nodeTemplateOperation.prepareCalculatedCapabiltyForNodeType(mapToscaDataDefinition, componentInstance);
+
+ MapCapabiltyProperty mapCapabiltyProperty = ModelConverter.convertToMapOfMapCapabiltyProperties(caps, componentInstance.getUniqueId(), true);
+
+ calcCapabilty.put(entry.getKey().getUniqueId(), capMap);
+ calculatedCapabilitiesProperties.put(entry.getKey().getUniqueId(), mapCapabiltyProperty);
+ }
+ }
+
+ if (instReg != null) {
+ for (Entry<ComponentInstance, Map<String, List<RequirementDefinition>>> entry : instReg.entrySet()) {
+
+ Map<String, List<RequirementDefinition>> req = entry.getValue();
+ Map<String, ListRequirementDataDefinition> mapToscaDataDefinition = new HashMap<>();
+ for (Entry<String, List<RequirementDefinition>> instReq : req.entrySet()) {
+ mapToscaDataDefinition.put(instReq.getKey(), new ListRequirementDataDefinition(instReq.getValue().stream().map(iCap -> new RequirementDataDefinition(iCap)).collect(Collectors.toList())));
+ }
+
+ MapListRequirementDataDefinition capMap = nodeTemplateOperation.prepareCalculatedRequirementForNodeType(mapToscaDataDefinition, new ComponentInstanceDataDefinition(entry.getKey()));
+
+ calcRequirements.put(entry.getKey().getUniqueId(), capMap);
+ }
+ }
+
+ StorageOperationStatus status = topologyTemplateOperation.associateCalcCapReqToComponent(vertex, calcRequirements, calcCapabilty, calculatedCapabilitiesProperties);
+
+ return status;
+ }
+
+ private Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractToscaElementsMetadataOnly(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType,
+ VertexTypeEnum vertexType) {
+
+ Map<GraphPropertyEnum, Object> hasProps = new EnumMap<>(GraphPropertyEnum.class);
+ Map<GraphPropertyEnum, Object> hasNotProps = new EnumMap<>(GraphPropertyEnum.class);
+
+ fillPropsMap(hasProps, hasNotProps, internalComponentType, componentTypeEnum, isAbstract, vertexType);
+
+ Either<List<GraphVertex>, TitanOperationStatus> getRes = titanDao.getByCriteria(vertexType, hasProps, hasNotProps, JsonParseFlagEnum.ParseMetadata);
+ if (getRes.isRight()) {
+ if (getRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
+ return Either.left(new ArrayList<>());
+ } else {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
+ }
+ } else {
+ List<Component> nonAbstractLatestComponents = new ArrayList<>();
+ ComponentParametersView params = new ComponentParametersView(true);
+ params.setIgnoreAllVersions(false);
+ for (GraphVertex vertexComponent : getRes.left().value()) {
+ Either<ToscaElement, StorageOperationStatus> componentRes = topologyTemplateOperation.getLightComponent(vertexComponent, componentTypeEnum, params);
+ if (componentRes.isRight()) {
+ log.debug("Failed to fetch ligth element for {} error {}", vertexComponent.getUniqueId(), componentRes.right().value());
+ return Either.right(componentRes.right().value());
+ } else {
+ Component component = ModelConverter.convertFromToscaElement(componentRes.left().value());
+
+ nonAbstractLatestComponents.add(component);
+ }
+ }
+
+ return Either.left(nonAbstractLatestComponents);
+ }
+ }
+
+ public Either<ComponentMetadataData, StorageOperationStatus> getLatestComponentMetadataByUuid(String componentUuid, JsonParseFlagEnum parseFlag) {
+
+ Either<ComponentMetadataData, StorageOperationStatus> result;
+
+ Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
+
+ hasProperties.put(GraphPropertyEnum.UUID, componentUuid);
+ hasProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+
+ Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
+ propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
+
+ Either<List<GraphVertex>, TitanOperationStatus> getRes = titanDao.getByCriteria(null, hasProperties, propertiesNotToMatch, parseFlag);
+ if (getRes.isRight()) {
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
+ } else {
+ List<ComponentMetadataData> latestVersionList = getRes.left().value().stream().map(ModelConverter::convertToComponentMetadata).collect(Collectors.toList());
+ ComponentMetadataData latestVersion = latestVersionList.size() == 1 ? latestVersionList.get(0)
+ : latestVersionList.stream().max((c1, c2) -> Double.compare(Double.parseDouble(c1.getMetadataDataDefinition().getVersion()), Double.parseDouble(c2.getMetadataDataDefinition().getVersion()))).get();
+ result = Either.left(latestVersion);
+ }
+ return result;
+ }
+
+ public Either<ComponentMetadataData, StorageOperationStatus> getComponentMetadata(String componentId) {
+
+ Either<ComponentMetadataData, StorageOperationStatus> result;
+ Either<GraphVertex, TitanOperationStatus> getRes = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata);
+ if (getRes.isRight()) {
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
+ } else {
+ ComponentMetadataData componentMetadata = ModelConverter.convertToComponentMetadata(getRes.left().value());
+ result = Either.left(componentMetadata);
+ }
+ return result;
+ }
+
+ private Map<String, ComponentMetadataData> findLatestVersion(List<ComponentMetadataData> resourceDataList) {
+ Map<Pair<String, String>, ComponentMetadataData> latestVersionMap = new HashMap<Pair<String, String>, ComponentMetadataData>();
+ for (ComponentMetadataData resourceData : resourceDataList) {
+ ComponentMetadataData latestVersionData = resourceData;
+
+ ComponentMetadataDataDefinition metadataDataDefinition = resourceData.getMetadataDataDefinition();
+ Pair<String, String> pair = createKeyPair(latestVersionData);
+ if (latestVersionMap.containsKey(pair)) {
+ latestVersionData = latestVersionMap.get(pair);
+ String currentVersion = latestVersionData.getMetadataDataDefinition().getVersion();
+ String newVersion = metadataDataDefinition.getVersion();
+ if (CommonBeUtils.compareAsdcComponentVersions(newVersion, currentVersion)) {
+ latestVersionData = resourceData;
+ }
+ }
+ if (log.isDebugEnabled())
+ log.debug("last certified version of resource = {} version is {}", latestVersionData.getMetadataDataDefinition().getName(), latestVersionData.getMetadataDataDefinition().getVersion());
+
+ latestVersionMap.put(pair, latestVersionData);
+ }
+
+ Map<String, ComponentMetadataData> resVersionMap = new HashMap<String, ComponentMetadataData>();
+ for (ComponentMetadataData resourceData : latestVersionMap.values()) {
+ ComponentMetadataData latestVersionData = resourceData;
+ ComponentMetadataDataDefinition metadataDataDefinition = resourceData.getMetadataDataDefinition();
+ if (resVersionMap.containsKey(metadataDataDefinition.getUUID())) {
+ latestVersionData = resVersionMap.get(metadataDataDefinition.getUUID());
+ String currentVersion = latestVersionData.getMetadataDataDefinition().getVersion();
+ String newVersion = metadataDataDefinition.getVersion();
+ if (CommonBeUtils.compareAsdcComponentVersions(newVersion, currentVersion)) {
+ latestVersionData = resourceData;
+ }
+ }
+ if (log.isDebugEnabled())
+ log.debug("last uuid version of resource = {} version is {}", latestVersionData.getMetadataDataDefinition().getName(), latestVersionData.getMetadataDataDefinition().getVersion());
+ resVersionMap.put(latestVersionData.getMetadataDataDefinition().getUUID(), latestVersionData);
+ }
+
+ return resVersionMap;
+ }
+
+ private Pair<String, String> createKeyPair(ComponentMetadataData metadataData) {
+ Pair<String, String> pair;
+ NodeTypeEnum label = NodeTypeEnum.getByName(metadataData.getLabel());
+ switch (label) {
+ case Resource:
+ pair = new ImmutablePair<>(metadataData.getMetadataDataDefinition().getName(), ((ResourceMetadataDataDefinition) metadataData.getMetadataDataDefinition()).getResourceType().name());
+ break;
+ default:
+ pair = new ImmutablePair<>(metadataData.getMetadataDataDefinition().getName(), metadataData.getLabel());
+ break;
+ }
+
+ return pair;
+ }
+
+ public Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractComponents(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType, List<String> componentUids) {
+
+ Either<List<Component>, StorageOperationStatus> result = null;
+ List<Component> components = new ArrayList<>();
+ if (componentUids == null) {
+ Either<List<String>, StorageOperationStatus> componentUidsRes = getComponentUids(isAbstract, isHighest, componentTypeEnum, internalComponentType, componentUids);
+ if (componentUidsRes.isRight()) {
+ result = Either.right(componentUidsRes.right().value());
+ } else {
+ componentUids = componentUidsRes.left().value();
+ }
+ }
+ if (!componentUids.isEmpty()) {
+ for (String componentUid : componentUids) {
+ ComponentParametersView componentParametersView = buildComponentViewForNotAbstract();
+ if (internalComponentType != null && "vl".equalsIgnoreCase(internalComponentType)) {
+ componentParametersView.setIgnoreCapabilities(false);
+ componentParametersView.setIgnoreRequirements(false);
+ }
+ Either<ToscaElement, StorageOperationStatus> getToscaElementRes = nodeTemplateOperation.getToscaElementOperation(componentTypeEnum).getLightComponent(componentUid, componentTypeEnum, componentParametersView);
+ if (getToscaElementRes.isRight()) {
+ if (log.isDebugEnabled())
+ log.debug("Failed to fetch resource for error is {}", getToscaElementRes.right().value());
+ result = Either.right(getToscaElementRes.right().value());
+ break;
+ }
+ Component component = ModelConverter.convertFromToscaElement(getToscaElementRes.left().value());
+ component.setContactId(null);
+ component.setCreationDate(null);
+ component.setCreatorUserId(null);
+ component.setCreatorFullName(null);
+ component.setLastUpdateDate(null);
+ component.setLastUpdaterUserId(null);
+ component.setLastUpdaterFullName(null);
+ component.setNormalizedName(null);
+ components.add(component);
+ }
+ }
+ if (result == null) {
+ result = Either.left(components);
+ }
+ return result;
+ }
+
+ private Either<List<String>, StorageOperationStatus> getComponentUids(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType, List<String> componentUids) {
+
+ Either<List<String>, StorageOperationStatus> result = null;
+ Either<List<Component>, StorageOperationStatus> getToscaElementsRes = getLatestVersionNotAbstractMetadataOnly(isAbstract, isHighest, componentTypeEnum, internalComponentType);
+ if (getToscaElementsRes.isRight()) {
+ result = Either.right(getToscaElementsRes.right().value());
+ } else {
+ List<Component> collection = getToscaElementsRes.left().value();
+ if (collection == null) {
+ componentUids = new ArrayList<>();
+ } else {
+ componentUids = collection.stream().map(p -> p.getUniqueId()).collect(Collectors.toList());
+ }
+ }
+ if (result == null) {
+ result = Either.left(componentUids);
+ }
+ return result;
+ }
+
+ private ComponentParametersView buildComponentViewForNotAbstract() {
+ ComponentParametersView componentParametersView = new ComponentParametersView();
+ componentParametersView.disableAll();
+ componentParametersView.setIgnoreCategories(false);
+ componentParametersView.setIgnoreAllVersions(false);
+ return componentParametersView;
+ }
+
+ public Either<Boolean, StorageOperationStatus> validateComponentNameExists(String name, ResourceTypeEnum resourceType, ComponentTypeEnum componentType) {
+ Either<Boolean, StorageOperationStatus> result = validateComponentNameUniqueness(name, resourceType, componentType);
+ if (result.isLeft()) {
+ result = Either.left(!result.left().value());
+ }
+ return result;
+ }
+
+ public Either<Boolean, StorageOperationStatus> validateComponentNameUniqueness(String name, ResourceTypeEnum resourceType, ComponentTypeEnum componentType) {
+ VertexTypeEnum vertexType = getVertexTypeByComponentAndResourceTypeEnum(resourceType, componentType);
+ String normalizedName = ValidationUtils.normaliseComponentName(name);
+ Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
+ properties.put(GraphPropertyEnum.NORMALIZED_NAME, normalizedName);
+ properties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
+
+ Either<List<GraphVertex>, TitanOperationStatus> vertexEither = titanDao.getByCriteria(vertexType, properties, JsonParseFlagEnum.NoParse);
+ if (vertexEither.isRight() && vertexEither.right().value() != TitanOperationStatus.NOT_FOUND) {
+ log.debug("failed to get vertex from graph with property normalizedName: {}", normalizedName);
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexEither.right().value()));
+ }
+ List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
+ if (vertexList != null && !vertexList.isEmpty()) {
+ return Either.left(false);
+ } else {
+ return Either.left(true);
+ }
+ }
+
+ // UI query parameter is either VFC/CP/VL(for yaml upload/update) or VF (for CSAR upload/user composed VF)
+ // TODO implementation of topology template VFCs may require updating this method - depending on UI implementation
+ private VertexTypeEnum getVertexTypeByComponentAndResourceTypeEnum(ResourceTypeEnum resourceType, ComponentTypeEnum componentType) {
+ VertexTypeEnum vertexType = VertexTypeEnum.TOPOLOGY_TEMPLATE;
+ if (ComponentTypeEnum.RESOURCE == componentType && ResourceTypeEnum.VF != resourceType) {
+ vertexType = VertexTypeEnum.NODE_TYPE;
+ }
+ return vertexType;
+ }
+
+ private void fillNodeTypePropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, String internalComponentType) {
+ switch (internalComponentType.toLowerCase()) {
+ case "vf":
+ hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.VF.name());
+ hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.VFCMT.name());
+ break;
+ case "service":
+ hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.VFC.name());
+ hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.VFCMT.name());
+ break;
+ case "vl":
+ hasProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.VL.name());
+ break;
+ default:
+ break;
+ }
+ }
+
+ private void fillTopologyTemplatePropsMap(Map<GraphPropertyEnum, Object> hasProps, ComponentTypeEnum componentTypeEnum) {
+ switch (componentTypeEnum) {
+ case RESOURCE:
+ hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
+ break;
+ case SERVICE:
+ hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
+ break;
+ default:
+ break;
+ }
+ }
+
+ private void fillPropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, String internalComponentType, ComponentTypeEnum componentTypeEnum, boolean isAbstract, VertexTypeEnum internalVertexType) {
+ hasNotProps.put(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name());
+
+ hasNotProps.put(GraphPropertyEnum.IS_DELETED, true);
+ if (VertexTypeEnum.NODE_TYPE == internalVertexType) {
+ hasProps.put(GraphPropertyEnum.IS_ABSTRACT, isAbstract);
+ if (internalComponentType != null) {
+ fillNodeTypePropsMap(hasProps, hasNotProps, internalComponentType);
+ }
+ } else {
+ fillTopologyTemplatePropsMap(hasProps, componentTypeEnum);
+ }
+ }
+
+ private List<VertexTypeEnum> getInternalVertexTypes(ComponentTypeEnum componentTypeEnum, String internalComponentType) {
+ List<VertexTypeEnum> internalVertexTypes = new ArrayList<>();
+ if (ComponentTypeEnum.RESOURCE == componentTypeEnum) {
+ internalVertexTypes.add(VertexTypeEnum.NODE_TYPE);
+ }
+ if (ComponentTypeEnum.SERVICE == componentTypeEnum || "service".equalsIgnoreCase(internalComponentType)) {
+ internalVertexTypes.add(VertexTypeEnum.TOPOLOGY_TEMPLATE);
+ }
+ return internalVertexTypes;
+ }
+
+ public Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractMetadataOnly(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType) {
+ List<VertexTypeEnum> internalVertexTypes = getInternalVertexTypes(componentTypeEnum, internalComponentType);
+ List<Component> result = new ArrayList<>();
+ for (VertexTypeEnum vertexType : internalVertexTypes) {
+ Either<List<Component>, StorageOperationStatus> listByVertexType = getLatestVersionNotAbstractToscaElementsMetadataOnly(isAbstract, isHighest, componentTypeEnum, internalComponentType, vertexType);
+ if (listByVertexType.isRight()) {
+ return listByVertexType;
+ }
+ result.addAll(listByVertexType.left().value());
+ }
+ return Either.left(result);
+
+ }
+
+ public Either<List<Component>, StorageOperationStatus> getLatestComponentListByUuid(String componentUuid) {
+ Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
+ propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+ return getComponentListByUuid(componentUuid, propertiesToMatch);
+ }
+
+ public Either<List<Component>, StorageOperationStatus> getComponentListByUuid(String componentUuid, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
+
+ Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
+
+ if(additionalPropertiesToMatch != null){
+ propertiesToMatch.putAll(additionalPropertiesToMatch);
+ }
+
+ propertiesToMatch.put(GraphPropertyEnum.UUID, componentUuid);
+
+ 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()) {
+ log.debug("Couldn't fetch metadata for component with type {} and uuid {}, error: {}", componentUuid, vertexEither.right().value());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexEither.right().value()));
+ }
+ List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
+
+ if (vertexList == null || vertexList.isEmpty()) {
+ log.debug("Component with uuid {} was not found", componentUuid);
+ return Either.right(StorageOperationStatus.NOT_FOUND);
+ }
+
+ List<Component> latestComponents = new ArrayList<Component>();
+ for (GraphVertex vertex : vertexList) {
+ latestComponents.add(getToscaElementByOperation(vertex).left().value());
+ }
+
+ return Either.left(latestComponents);
+ }
+
+ public Either<Component, StorageOperationStatus> getLatestComponentByUuid(String componentUuid) {
+
+ Either<List<Component>, StorageOperationStatus> latestVersionListEither = getLatestComponentListByUuid(componentUuid);
+
+ if (latestVersionListEither.isRight()) {
+ return Either.right(latestVersionListEither.right().value());
+ }
+
+ List<Component> latestVersionList = latestVersionListEither.left().value();
+
+ if (latestVersionList.isEmpty()) {
+ return Either.right(StorageOperationStatus.NOT_FOUND);
+ }
+ Component component = latestVersionList.size() == 1 ? latestVersionList.get(0) : latestVersionList.stream().max((c1, c2) -> Double.compare(Double.parseDouble(c1.getVersion()), Double.parseDouble(c2.getVersion()))).get();
+
+ return Either.left(component);
+ }
+
+ public Either<List<Resource>, StorageOperationStatus> getAllCertifiedResources(boolean isAbstract, Boolean isHighest) {
+
+ List<Resource> resources = new ArrayList<>();
+ Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
+ Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
+
+ propertiesToMatch.put(GraphPropertyEnum.IS_ABSTRACT, isAbstract);
+ if (isHighest != null) {
+ propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, isHighest.booleanValue());
+ }
+ propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
+ propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
+ propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
+
+ Either<List<GraphVertex>, TitanOperationStatus> getResourcesRes = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
+
+ if (getResourcesRes.isRight()) {
+ log.debug("Failed to fetch all certified resources. Status is {}", getResourcesRes.right().value());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getResourcesRes.right().value()));
+ }
+ List<GraphVertex> resourceVerticies = getResourcesRes.left().value();
+ for (GraphVertex resourceV : resourceVerticies) {
+ Either<Resource, StorageOperationStatus> getResourceRes = getToscaElement(resourceV);
+ if (getResourceRes.isRight()) {
+ return Either.right(getResourceRes.right().value());
+ }
+ resources.add(getResourceRes.left().value());
+ }
+ return Either.left(resources);
+ }
+
+ public <T extends Component> Either<T, StorageOperationStatus> getLatestByNameAndVersion(String name, String version, JsonParseFlagEnum parseFlag) {
+ Either<T, StorageOperationStatus> result;
+
+ Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
+ Map<GraphPropertyEnum, Object> hasNotProperties = new EnumMap<>(GraphPropertyEnum.class);
+
+ hasProperties.put(GraphPropertyEnum.NAME, name);
+ hasProperties.put(GraphPropertyEnum.VERSION, version);
+ hasProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+
+ hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true);
+
+ Either<List<GraphVertex>, TitanOperationStatus> getResourceRes = titanDao.getByCriteria(null, hasProperties, hasNotProperties, parseFlag);
+ if (getResourceRes.isRight()) {
+ TitanOperationStatus status = getResourceRes.right().value();
+ log.debug("failed to find resource with name {}, version {}. Status is {} ", name, version, status);
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ return result;
+ }
+ return getToscaElementByOperation(getResourceRes.left().value().get(0));
+ }
+
+ public Either<Resource, StorageOperationStatus> getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID, String systemName) {
+ return getLatestComponentByCsarOrName(componentType, csarUUID, systemName, false, JsonParseFlagEnum.ParseAll);
+ }
+
+ public Either<Resource, StorageOperationStatus> getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID, String systemName, boolean allowDeleted, JsonParseFlagEnum parseFlag) {
+ Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
+ props.put(GraphPropertyEnum.CSAR_UUID, csarUUID);
+ props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+ if (componentType != null) {
+ props.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
+ }
+ Map<GraphPropertyEnum, Object> propsHasNot = new EnumMap<>(GraphPropertyEnum.class);
+ propsHasNot.put(GraphPropertyEnum.IS_DELETED, true);
+
+ GraphVertex resourceMetadataData = null;
+ List<GraphVertex> resourceMetadataDataList = null;
+ Either<List<GraphVertex>, TitanOperationStatus> byCsar = titanDao.getByCriteria(null, props, propsHasNot, JsonParseFlagEnum.ParseMetadata);
+ if (byCsar.isRight()) {
+ if (TitanOperationStatus.NOT_FOUND == byCsar.right().value()) {
+ // Fix Defect DE256036
+ if (StringUtils.isEmpty(systemName)) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.NOT_FOUND));
+ }
+
+ props.clear();
+ props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+ props.put(GraphPropertyEnum.SYSTEM_NAME, systemName);
+ Either<List<GraphVertex>, TitanOperationStatus> bySystemname = titanDao.getByCriteria(null, props, JsonParseFlagEnum.ParseMetadata);
+ if (bySystemname.isRight()) {
+ log.debug("getLatestResourceByCsarOrName - Failed to find by system name {} error {} ", systemName, bySystemname.right().value());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(bySystemname.right().value()));
+ }
+ if (bySystemname.left().value().size() > 2) {
+ log.debug("getLatestResourceByCsarOrName - getByCriteria(by system name) must return only 2 latest version, but was returned - {}", bySystemname.left().value().size());
+ return Either.right(StorageOperationStatus.GENERAL_ERROR);
+ }
+ resourceMetadataDataList = bySystemname.left().value();
+ if (resourceMetadataDataList.size() == 1) {
+ resourceMetadataData = resourceMetadataDataList.get(0);
+ } else {
+ for (GraphVertex curResource : resourceMetadataDataList) {
+ if (!((String) curResource.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals("CERTIFIED")) {
+ resourceMetadataData = curResource;
+ break;
+ }
+ }
+ }
+ if (resourceMetadataData == null) {
+ log.debug("getLatestResourceByCsarOrName - getByCriteria(by system name) returned 2 latest CERTIFIED versions");
+ return Either.right(StorageOperationStatus.GENERAL_ERROR);
+ }
+ if (resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID) != null && !((String) resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID)).equals(csarUUID)) {
+ log.debug("getLatestResourceByCsarOrName - same system name {} but different csarUUID. exist {} and new {} ", systemName, resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID), csarUUID);
+ // correct error will be returned from create flow. with all
+ // correct audit records!!!!!
+ return Either.right(StorageOperationStatus.NOT_FOUND);
+ }
+ Either<Resource, StorageOperationStatus> resource = getToscaElement((String) resourceMetadataData.getUniqueId());
+ return resource;
+ }
+ } else {
+ resourceMetadataDataList = byCsar.left().value();
+ if (resourceMetadataDataList.size() > 2) {
+ log.debug("getLatestResourceByCsarOrName - getByCriteria(by csar) must return only 2 latest version, but was returned - {}", byCsar.left().value().size());
+ return Either.right(StorageOperationStatus.GENERAL_ERROR);
+ }
+ if (resourceMetadataDataList.size() == 1) {
+ resourceMetadataData = resourceMetadataDataList.get(0);
+ } else {
+ for (GraphVertex curResource : resourceMetadataDataList) {
+ if (!((String) curResource.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals("CERTIFIED")) {
+ resourceMetadataData = curResource;
+ break;
+ }
+ }
+ }
+ if (resourceMetadataData == null) {
+ log.debug("getLatestResourceByCsarOrName - getByCriteria(by csar) returned 2 latest CERTIFIED versions");
+ return Either.right(StorageOperationStatus.GENERAL_ERROR);
+ }
+ Either<Resource, StorageOperationStatus> resource = getToscaElement((String) resourceMetadataData.getJsonMetadataField(JsonPresentationFields.UNIQUE_ID), parseFlag);
+ return resource;
+ }
+ return null;
+ }
+
+ public Either<Boolean, StorageOperationStatus> validateToscaResourceNameExtends(String templateNameCurrent, String templateNameExtends) {
+
+ String currentTemplateNameChecked = templateNameExtends;
+
+ while (currentTemplateNameChecked != null && !currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) {
+ Either<Resource, StorageOperationStatus> latestByToscaResourceName = getLatestByToscaResourceName(currentTemplateNameChecked);
+
+ if (latestByToscaResourceName.isRight()) {
+ return latestByToscaResourceName.right().value() == StorageOperationStatus.NOT_FOUND ? Either.left(false) : Either.right(latestByToscaResourceName.right().value());
+ }
+
+ Resource value = latestByToscaResourceName.left().value();
+
+ if (value.getDerivedFrom() != null) {
+ currentTemplateNameChecked = value.getDerivedFrom().get(0);
+ } else {
+ currentTemplateNameChecked = null;
+ }
+ }
+
+ return (currentTemplateNameChecked != null && currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) ? Either.left(true) : Either.left(false);
+ }
+
+ public Either<List<Component>, StorageOperationStatus> fetchByResourceType(String resourceType) {
+
+ Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
+ props.put(GraphPropertyEnum.RESOURCE_TYPE, resourceType);
+ props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+ Either<List<GraphVertex>, TitanOperationStatus> resourcesByTypeEither = titanDao.getByCriteria(null, props);
+
+ if (resourcesByTypeEither.isRight()) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resourcesByTypeEither.right().value()));
+ }
+
+ List<GraphVertex> vertexList = resourcesByTypeEither.left().value();
+ List<Component> components = new ArrayList<>();
+
+ for (GraphVertex vertex : vertexList) {
+ components.add(getToscaElementByOperation(vertex).left().value());
+ }
+
+ return Either.left(components);
+
+ }
+
+ public void commit() {
+ titanDao.commit();
+ }
+
+ public Either<Service, StorageOperationStatus> updateDistributionStatus(Service service, User user, DistributionStatusEnum distributionStatus) {
+ Either<GraphVertex, StorageOperationStatus> updateDistributionStatus = topologyTemplateOperation.updateDistributionStatus(service.getUniqueId(), user, distributionStatus);
+ if ( updateDistributionStatus.isRight() ){
+ return Either.right(updateDistributionStatus.right().value());
+ }
+ GraphVertex serviceV = updateDistributionStatus.left().value();
+ service.setDistributionStatus(distributionStatus);
+ service.setLastUpdateDate((Long) serviceV.getJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE));
+ return Either.left(service);
+ }
+
+ public Either<ComponentMetadataData, StorageOperationStatus> updateComponentLastUpdateDateOnGraph(Component component, Long modificationTime) {
+
+ Either<ComponentMetadataData, StorageOperationStatus> result = null;
+ GraphVertex serviceVertex;
+ Either<GraphVertex, TitanOperationStatus> updateRes = null;
+ Either<GraphVertex, TitanOperationStatus> getRes = titanDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.ParseMetadata);
+ if (getRes.isRight()) {
+ TitanOperationStatus status = getRes.right().value();
+ log.error("Failed to fetch component {}. status is {}", component.getUniqueId(), status);
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ if (result == null) {
+ serviceVertex = getRes.left().value();
+ long lastUpdateDate = System.currentTimeMillis();
+ serviceVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, lastUpdateDate);
+ component.setLastUpdateDate(lastUpdateDate);
+ updateRes = titanDao.updateVertex(serviceVertex);
+ if (updateRes.isRight()) {
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateRes.right().value()));
+ }
+ }
+ if (result == null) {
+ result = Either.left(ModelConverter.convertToComponentMetadata(updateRes.left().value()));
+ }
+ return result;
+ }
+
+ public TitanDao getTitanDao() {
+ return titanDao;
+ }
+
+ public Either<List<Service>, StorageOperationStatus> getCertifiedServicesWithDistStatus(Set<DistributionStatusEnum> distStatus) {
+ Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
+ propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
+
+ return getServicesWithDistStatus(distStatus, propertiesToMatch);
+ }
+
+ public Either<List<Service>, StorageOperationStatus> getServicesWithDistStatus(Set<DistributionStatusEnum> distStatus, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
+
+ List<Service> servicesAll = new ArrayList<>();
+
+ Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
+ Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
+
+ if(additionalPropertiesToMatch != null && !additionalPropertiesToMatch.isEmpty()) {
+ propertiesToMatch.putAll(additionalPropertiesToMatch);
+ }
+
+ propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
+
+ propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
+
+ if (distStatus != null && !distStatus.isEmpty()) {
+ for (DistributionStatusEnum state : distStatus) {
+ propertiesToMatch.put(GraphPropertyEnum.DISTRIBUTION_STATUS, state.name());
+ Either<List<Service>, StorageOperationStatus> fetchServicesByCriteria = fetchServicesByCriteria(servicesAll, propertiesToMatch, propertiesNotToMatch);
+ if ( fetchServicesByCriteria.isRight() ){
+ return fetchServicesByCriteria;
+ }
+ else{
+ servicesAll = fetchServicesByCriteria.left().value();
+ }
+ }
+ return Either.left(servicesAll);
+ } else {
+ return fetchServicesByCriteria(servicesAll, propertiesToMatch, propertiesNotToMatch);
+ }
+ }
+
+ private Either<List<Service>, StorageOperationStatus> fetchServicesByCriteria(List<Service> servicesAll, Map<GraphPropertyEnum, Object> propertiesToMatch, Map<GraphPropertyEnum, Object> propertiesNotToMatch) {
+ Either<List<GraphVertex>, TitanOperationStatus> getRes = titanDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
+ if (getRes.isRight()) {
+ if (getRes.right().value() != TitanOperationStatus.NOT_FOUND) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified services by match properties {} not match properties {} . Status is {}. ", propertiesToMatch, propertiesNotToMatch, getRes.right().value());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
+ }
+ } else {
+ for (GraphVertex vertex : getRes.left().value()) {
+ Either<Component, StorageOperationStatus> getServiceRes = getToscaElementByOperation(vertex);
+ if (getServiceRes.isRight()) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified service {}. Status is {}. ", vertex.getJsonMetadataField(JsonPresentationFields.NAME), getServiceRes.right().value());
+ return Either.right(getServiceRes.right().value());
+ } else {
+ servicesAll.add((Service) getToscaElementByOperation(vertex).left().value());
+ }
+ }
+ }
+ return Either.left(servicesAll);
+ }
+
+ public void rollback() {
+ titanDao.rollback();
+ }
+
+ public StorageOperationStatus addDeploymentArtifactsToInstance(String componentId, ComponentInstance componentInstance, Map<String, ArtifactDefinition> finalDeploymentArtifacts) {
+ Map<String, ArtifactDataDefinition> instDeplArtifacts = finalDeploymentArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
+
+ return nodeTemplateOperation.addDeploymentArtifactsToInstance(componentId, componentInstance.getUniqueId(), instDeplArtifacts);
+ }
+
+ public StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId) {
+ return nodeTemplateOperation.generateCustomizationUUIDOnInstance(componentId, instanceId);
+ }
+
+ public StorageOperationStatus generateCustomizationUUIDOnInstanceGroup(String componentId, String instanceId, List<String> groupInstances) {
+ return nodeTemplateOperation.generateCustomizationUUIDOnInstanceGroup(componentId, instanceId, groupInstances);
+ }
+
+ public Either<PropertyDefinition, StorageOperationStatus> addPropertyToResource(String propertyName, PropertyDefinition newPropertyDefinition, Resource resource) {
+
+ Either<PropertyDefinition, StorageOperationStatus> result = null;
+ Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
+ newPropertyDefinition.setName(propertyName);
+ newPropertyDefinition.setParentUniqueId(resource.getUniqueId());
+ StorageOperationStatus status = getToscaElementOperation(resource).addToscaDataToToscaElement(resource.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition, JsonPresentationFields.NAME);
+ if (status != StorageOperationStatus.OK) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", propertyName, resource.getName(), status);
+ result = Either.right(status);
+ }
+ if (result == null) {
+ ComponentParametersView filter = new ComponentParametersView(true);
+ filter.setIgnoreProperties(false);
+ getUpdatedComponentRes = getToscaElement(resource.getUniqueId(), filter);
+ if (getUpdatedComponentRes.isRight()) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", resource.getUniqueId(), getUpdatedComponentRes.right().value());
+ result = Either.right(status);
+ }
+ }
+ if (result == null) {
+ PropertyDefinition newProperty = null;
+ List<PropertyDefinition> properties = ((Resource) getUpdatedComponentRes.left().value()).getProperties();
+ if (CollectionUtils.isNotEmpty(properties)) {
+ Optional<PropertyDefinition> newPropertyOptional = properties.stream().filter(p -> p.getName().equals(propertyName)).findAny();
+ if (newPropertyOptional.isPresent()) {
+ newProperty = newPropertyOptional.get();
+ }
+ }
+ if (newProperty == null) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", propertyName, resource.getUniqueId(), StorageOperationStatus.NOT_FOUND);
+ result = Either.right(StorageOperationStatus.NOT_FOUND);
+ } else {
+ result = Either.left(newProperty);
+ }
+ }
+ return result;
+ }
+
+ public StorageOperationStatus deletePropertyOfResource(Resource resource, String propertyName) {
+ return getToscaElementOperation(resource).deleteToscaDataElement(resource.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, propertyName, JsonPresentationFields.NAME);
+ }
+
+ public StorageOperationStatus deleteAttributeOfResource(Component component, String attributeName) {
+ return getToscaElementOperation(component).deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, attributeName, JsonPresentationFields.NAME);
+ }
+
+ public StorageOperationStatus deleteInputOfResource(Component resource, String inputName) {
+ return getToscaElementOperation(resource).deleteToscaDataElement(resource.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputName, JsonPresentationFields.NAME);
+ }
+
+ public Either<PropertyDefinition, StorageOperationStatus> updatePropertyOfResource(Resource resource, PropertyDefinition newPropertyDefinition) {
+
+ Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
+ Either<PropertyDefinition, StorageOperationStatus> result = null;
+ StorageOperationStatus status = getToscaElementOperation(resource).updateToscaDataOfToscaElement(resource.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition, JsonPresentationFields.NAME);
+ if (status != StorageOperationStatus.OK) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", newPropertyDefinition.getName(), resource.getName(), status);
+ result = Either.right(status);
+ }
+ if (result == null) {
+ ComponentParametersView filter = new ComponentParametersView(true);
+ filter.setIgnoreProperties(false);
+ getUpdatedComponentRes = getToscaElement(resource.getUniqueId(), filter);
+ if (getUpdatedComponentRes.isRight()) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", resource.getUniqueId(), getUpdatedComponentRes.right().value());
+ result = Either.right(status);
+ }
+ }
+ if (result == null) {
+ Optional<PropertyDefinition> newProperty = ((Resource) getUpdatedComponentRes.left().value()).getProperties().stream().filter(p -> p.getName().equals(newPropertyDefinition.getName())).findAny();
+ if (newProperty.isPresent()) {
+ result = Either.left(newProperty.get());
+ } else {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", newPropertyDefinition.getName(), resource.getUniqueId(), StorageOperationStatus.NOT_FOUND);
+ result = Either.right(StorageOperationStatus.NOT_FOUND);
+ }
+ }
+ return result;
+ }
+
+ public Either<AttributeDefinition, StorageOperationStatus> addAttributeOfResource(Component component, AttributeDefinition newAttributeDef) {
+
+ Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
+ Either<AttributeDefinition, StorageOperationStatus> result = null;
+ if(newAttributeDef.getUniqueId() == null || newAttributeDef.getUniqueId().isEmpty()){
+ String attUniqueId = UniqueIdBuilder.buildAttributeUid(component.getUniqueId(), newAttributeDef.getName());
+ newAttributeDef.setUniqueId(attUniqueId);
+ }
+
+ StorageOperationStatus status = getToscaElementOperation(component).addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef, JsonPresentationFields.NAME);
+ if (status != StorageOperationStatus.OK) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", newAttributeDef.getName(), component.getName(), status);
+ result = Either.right(status);
+ }
+ if (result == null) {
+ ComponentParametersView filter = new ComponentParametersView(true);
+ filter.setIgnoreAttributesFrom(false);
+ getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
+ if (getUpdatedComponentRes.isRight()) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", component.getUniqueId(), getUpdatedComponentRes.right().value());
+ result = Either.right(status);
+ }
+ }
+ if (result == null) {
+ Optional<AttributeDefinition> newAttribute = ((Resource) getUpdatedComponentRes.left().value()).getAttributes().stream().filter(p -> p.getName().equals(newAttributeDef.getName())).findAny();
+ if (newAttribute.isPresent()) {
+ result = Either.left(newAttribute.get());
+ } else {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", newAttributeDef.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
+ result = Either.right(StorageOperationStatus.NOT_FOUND);
+ }
+ }
+ return result;
+ }
+
+ public Either<AttributeDefinition, StorageOperationStatus> updateAttributeOfResource(Component component, AttributeDefinition newAttributeDef) {
+
+ Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
+ Either<AttributeDefinition, StorageOperationStatus> result = null;
+ StorageOperationStatus status = getToscaElementOperation(component).updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef, JsonPresentationFields.NAME);
+ if (status != StorageOperationStatus.OK) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", newAttributeDef.getName(), component.getName(), status);
+ result = Either.right(status);
+ }
+ if (result == null) {
+ ComponentParametersView filter = new ComponentParametersView(true);
+ filter.setIgnoreAttributesFrom(false);
+ getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
+ if (getUpdatedComponentRes.isRight()) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", component.getUniqueId(), getUpdatedComponentRes.right().value());
+ result = Either.right(status);
+ }
+ }
+ if (result == null) {
+ Optional<AttributeDefinition> newProperty = ((Resource) getUpdatedComponentRes.left().value()).getAttributes().stream().filter(p -> p.getName().equals(newAttributeDef.getName())).findAny();
+ if (newProperty.isPresent()) {
+ result = Either.left(newProperty.get());
+ } else {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", newAttributeDef.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
+ result = Either.right(StorageOperationStatus.NOT_FOUND);
+ }
+ }
+ return result;
+ }
+
+ public Either<InputDefinition, StorageOperationStatus> updateInputOfComponent(Component component, InputDefinition newInputDefinition) {
+
+ Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
+ Either<InputDefinition, StorageOperationStatus> result = null;
+ StorageOperationStatus status = getToscaElementOperation(component).updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, newInputDefinition, JsonPresentationFields.NAME);
+ if (status != StorageOperationStatus.OK) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the input {} to the component {}. Status is {}. ", newInputDefinition.getName(), component.getName(), status);
+ result = Either.right(status);
+ }
+ if (result == null) {
+ ComponentParametersView filter = new ComponentParametersView(true);
+ filter.setIgnoreInputs(false);
+ getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
+ if (getUpdatedComponentRes.isRight()) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", component.getUniqueId(), getUpdatedComponentRes.right().value());
+ result = Either.right(status);
+ }
+ }
+ if (result == null) {
+ Optional<InputDefinition> updatedInput = getUpdatedComponentRes.left().value().getInputs().stream().filter(p -> p.getName().equals(newInputDefinition.getName())).findAny();
+ if (updatedInput.isPresent()) {
+ result = Either.left(updatedInput.get());
+ } else {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently updated inputs {} on the resource {}. Status is {}. ", newInputDefinition.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
+ result = Either.right(StorageOperationStatus.NOT_FOUND);
+ }
+ }
+ return result;
+ }
+
+ public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List<GroupDefinition> groups, Map<String, List<ArtifactDefinition>> groupInstancesArtifacts) {
+ return nodeTemplateOperation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groups, groupInstancesArtifacts);
+ }
+
+ public Either<List<GroupDefinition>, StorageOperationStatus> updateGroupsOnComponent(Component component, ComponentTypeEnum componentType, List<GroupDataDefinition> updatedGroups) {
+ return groupsOperation.updateGroups(component, componentType, updatedGroups);
+ }
+
+ public Either<List<GroupInstance>, StorageOperationStatus> updateGroupInstancesOnComponent(Component component, ComponentTypeEnum componentType, String instanceId, List<GroupInstance> updatedGroupInstances) {
+ return groupsOperation.updateGroupInstances(component, componentType, instanceId, updatedGroupInstances);
+ }
+
+ public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List<GroupInstance> groupInstances) {
+ return nodeTemplateOperation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groupInstances);
+ }
+
+ public StorageOperationStatus addDeploymentArtifactsToComponentInstance(Component containerComponent, ComponentInstance componentInstance, Map<String, ArtifactDefinition> deploymentArtifacts) {
+ return nodeTemplateOperation.addDeploymentArtifactsToComponentInstance(containerComponent, componentInstance, deploymentArtifacts);
+ }
+
+ public StorageOperationStatus updateComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) {
+ return nodeTemplateOperation.updateComponentInstanceProperty(containerComponent, componentInstanceId, property);
+ }
+
+ public StorageOperationStatus addComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) {
+ return nodeTemplateOperation.addComponentInstanceProperty(containerComponent, componentInstanceId, property);
+ }
+
+ public StorageOperationStatus updateComponentInstanceInput(Component containerComponent, String componentInstanceId, ComponentInstanceInput property) {
+ return nodeTemplateOperation.updateComponentInstanceInput(containerComponent, componentInstanceId, property);
+ }
+
+ public StorageOperationStatus addComponentInstanceInput(Component containerComponent, String componentInstanceId, ComponentInstanceInput property) {
+ return nodeTemplateOperation.addComponentInstanceInput(containerComponent, componentInstanceId, property);
+ }
+
+ public void setNodeTypeOperation(NodeTypeOperation nodeTypeOperation) {
+ this.nodeTypeOperation = nodeTypeOperation;
+ }
+
+ public void setTopologyTemplateOperation(TopologyTemplateOperation topologyTemplateOperation) {
+ this.topologyTemplateOperation = topologyTemplateOperation;
+ }
+
+}
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
new file mode 100644
index 0000000000..07845c8ea5
--- /dev/null
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/utils/ModelConverter.java
@@ -0,0 +1,1258 @@
+package org.openecomp.sdc.be.model.jsontitan.utils;
+
+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.function.BiConsumer;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+import org.apache.commons.collections.CollectionUtils;
+import org.apache.commons.collections.MapUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
+import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
+import org.openecomp.sdc.be.datatypes.elements.*;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.AdditionalInformationDefinition;
+import org.openecomp.sdc.be.model.ArtifactDefinition;
+import org.openecomp.sdc.be.model.AttributeDefinition;
+import org.openecomp.sdc.be.model.CapabilityDefinition;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.ComponentInstanceAttribute;
+import org.openecomp.sdc.be.model.ComponentInstanceInput;
+import org.openecomp.sdc.be.model.ComponentInstanceProperty;
+import org.openecomp.sdc.be.model.DistributionStatusEnum;
+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.PropertyDefinition;
+import org.openecomp.sdc.be.model.RelationshipImpl;
+import org.openecomp.sdc.be.model.RequirementAndRelationshipPair;
+import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
+import org.openecomp.sdc.be.model.RequirementDefinition;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.model.jsontitan.datamodel.NodeType;
+import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate;
+import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement;
+import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum;
+import org.openecomp.sdc.be.model.jsontitan.enums.JsonConstantKeysEnum;
+import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
+import org.openecomp.sdc.be.resources.data.ProductMetadataData;
+import org.openecomp.sdc.be.resources.data.ResourceMetadataData;
+import org.openecomp.sdc.be.resources.data.ServiceMetadataData;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class ModelConverter {
+ public static final String CAP_PROP_DELIM = "#";
+ private static Logger log = LoggerFactory.getLogger(ModelConverter.class.getName());
+
+ @SuppressWarnings("unchecked")
+ public static <T extends ToscaElement> T convertToToscaElement(Component component) {
+ if (isAtomicComponent(component)) {
+ return (T) convertToNodeType(component);
+ }
+ return (T) convertToTopologyTemplate(component);
+ }
+
+ @SuppressWarnings("unchecked")
+ public static <T extends Component> T convertFromToscaElement(ToscaElement toscaElement) {
+ switch (toscaElement.getComponentType()) {
+ case RESOURCE:
+ return (T) convertToResource(toscaElement);
+ case SERVICE:
+ case PRODUCT:
+ return (T) convertToService(toscaElement);
+ default:
+ return null;
+ }
+ }
+
+ // **********************************************************
+ public static VertexTypeEnum getVertexType(Component component) {
+ VertexTypeEnum vertexType;
+ if (isAtomicComponent(component)) {
+ vertexType = VertexTypeEnum.NODE_TYPE;
+ } else {
+ vertexType = VertexTypeEnum.TOPOLOGY_TEMPLATE;
+ }
+ return vertexType;
+ }
+
+ public static VertexTypeEnum getVertexType(String resourceTypeName) {
+ VertexTypeEnum vertexType = null;
+ ResourceTypeEnum resourceType = ResourceTypeEnum.getTypeByName(resourceTypeName);
+ if (isAtomicComponent(resourceType)) {
+ vertexType = VertexTypeEnum.NODE_TYPE;
+ } else {
+ vertexType = VertexTypeEnum.TOPOLOGY_TEMPLATE;
+ }
+ return vertexType;
+ }
+
+ private static boolean isAtomicComponent(ResourceTypeEnum resourceType) {
+ if (resourceType == null || resourceType == ResourceTypeEnum.VF)
+ return false;
+ return true;
+ }
+
+ private static Service convertToService(ToscaElement toscaElement) {
+ Service service = new Service();
+ convertComponentFields(service, toscaElement);
+
+ convertServiceSpecificFields(toscaElement, service);
+
+ TopologyTemplate topologyTemplate = (TopologyTemplate) toscaElement;
+
+ convertComponentInstances(topologyTemplate, service);
+
+ convertInputs(topologyTemplate, service);
+
+ convertRelations(topologyTemplate, service);
+
+ convertArtifacts(topologyTemplate, service);
+
+ convertServiceApiArtifacts(topologyTemplate, service);
+
+ return service;
+ }
+
+ private static void convertServiceSpecificFields(ToscaElement toscaElement, Service service) {
+ service.setProjectCode((String) toscaElement.getMetadataValue(JsonPresentationFields.PROJECT_CODE));
+ service.setDistributionStatus(DistributionStatusEnum.findState((String) toscaElement.getMetadataValue(JsonPresentationFields.DISTRIBUTION_STATUS)));
+ service.setEcompGeneratedNaming((Boolean) toscaElement.getMetadataValueOrDefault(JsonPresentationFields.ECOMP_GENERATED_NAMING, true));
+ service.setNamingPolicy((String) toscaElement.getMetadataValueOrDefault(JsonPresentationFields.NAMING_POLICY, StringUtils.EMPTY));
+ }
+
+ private static Resource convertToResource(ToscaElement toscaElement) {
+ Resource resource = new Resource();
+ convertComponentFields(resource, toscaElement);
+
+ resource.setResourceType(toscaElement.getResourceType());
+ if (toscaElement.getToscaType() == ToscaElementTypeEnum.NodeType) {
+ NodeType nodeType = (NodeType) toscaElement;
+ resource.setDerivedFrom(nodeType.getDerivedFrom());
+ resource.setDerivedList(nodeType.getDerivedList());
+ resource.setAbstract((Boolean) nodeType.getMetadataValue(JsonPresentationFields.IS_ABSTRACT));
+ convertAttributes(nodeType, resource);
+ convertCapabilities(nodeType, resource);
+ convertRequirements(nodeType, resource);
+ convertInterfaces(nodeType, resource);
+
+ } else {
+ TopologyTemplate topologyTemplate = (TopologyTemplate) toscaElement;
+ if (resource.getResourceType() == ResourceTypeEnum.VF) {
+ resource.setCsarUUID((String) topologyTemplate.getMetadataValue(JsonPresentationFields.CSAR_UUID));
+ resource.setCsarVersion((String) topologyTemplate.getMetadataValue(JsonPresentationFields.CSAR_VERSION));
+ resource.setImportedToscaChecksum((String) topologyTemplate.getMetadataValue(JsonPresentationFields.IMPORTED_TOSCA_CHECKSUM));
+
+ }
+ convertComponentInstances(topologyTemplate, resource);
+ convertRelations(topologyTemplate, resource);
+ convertInputs(topologyTemplate, resource);
+ convertGroups(topologyTemplate, resource);
+ }
+ convertArtifacts(toscaElement, resource);
+ convertAdditionalInformation(toscaElement, resource);
+
+ return resource;
+ }
+
+ private static void convertAttributes(NodeType nodeType, Resource resource) {
+ Map<String, AttributeDataDefinition> attributes = nodeType.getAttributes();
+ if (attributes != null) {
+ List<AttributeDefinition> attrs = attributes.values().stream().map(dataDef -> ModelConverter.fromDataDefinition(resource.getUniqueId(), dataDef)).collect(Collectors.toList());
+ resource.setAttributes(attrs);
+ }
+ }
+
+ private static AttributeDefinition fromDataDefinition(String resourceId, AttributeDataDefinition dataDefinition) {
+ AttributeDefinition attributeDefinition = new AttributeDefinition(dataDefinition);
+ attributeDefinition.setParentUniqueId(resourceId);
+ return attributeDefinition;
+ }
+
+ private static void convertInterfaces(NodeType nodeType, Resource resource) {
+ Map<String, InterfaceDataDefinition> interfaceArtifacts = nodeType.getInterfaceArtifacts();
+ if (interfaceArtifacts != null) {
+ Map<String, InterfaceDefinition> interfaces = interfaceArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, en -> new InterfaceDefinition(en.getValue())));
+ resource.setInterfaces(interfaces);
+ }
+ }
+
+ /**
+ * Converts component instances of topology template to component instances of resource
+ *
+ * @param topologyTemplate
+ * @param component
+ */
+ public static void convertComponentInstances(TopologyTemplate topologyTemplate, Component component) {
+
+ if (MapUtils.isNotEmpty(topologyTemplate.getComponentInstances())) {
+
+ setComponentInstancesAttributesToComponent(topologyTemplate, component);
+
+ setComponentInstancesPropertiesToComponent(topologyTemplate, component);
+
+ setComponentInstancesInputsToComponent(topologyTemplate, component);
+
+ setComponentInstancesToComponent(topologyTemplate, component);
+
+ setComponentInstancesCapabilitiesToComponentAndCI(topologyTemplate, component);
+
+ setComponentInstancesRequirementsToComponent(topologyTemplate, component);
+
+ setComponentInstancesArtifactsToComponent(topologyTemplate, component);
+
+ }
+ }
+
+ private static void setComponentInstancesArtifactsToComponent(TopologyTemplate topologyTemplate, Component component) {
+ Map<String, MapArtifactDataDefinition> instDeploymentArtifacts = topologyTemplate.getInstDeploymentArtifacts();
+ Map<String, MapArtifactDataDefinition> instanceArtifacts = topologyTemplate.getInstanceArtifacts();
+
+ List<ComponentInstance> instances = component.getComponentInstances();
+ if (instDeploymentArtifacts != null && instances != null) {
+ instDeploymentArtifacts.entrySet().forEach(e -> {
+ Optional<ComponentInstance> ci = instances.stream().filter(i -> i.getUniqueId().equals(e.getKey())).findFirst();
+ if (ci.isPresent()) {
+ Map<String, ArtifactDataDefinition> mapToscaDataDefinition = e.getValue().getMapToscaDataDefinition();
+ Map<String, ArtifactDefinition> deplArt = mapToscaDataDefinition.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, en -> new ArtifactDefinition(en.getValue())));
+
+ ci.get().setDeploymentArtifacts(deplArt);
+ }
+ });
+ }
+ if (instanceArtifacts != null && instances != null) {
+ instanceArtifacts.entrySet().forEach(e -> {
+ Optional<ComponentInstance> ci = instances.stream().filter(i -> i.getUniqueId().equals(e.getKey())).findFirst();
+ if (ci.isPresent()) {
+ Map<String, ArtifactDataDefinition> mapToscaDataDefinition = e.getValue().getMapToscaDataDefinition();
+ Map<String, ArtifactDefinition> deplArt = mapToscaDataDefinition.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, en -> new ArtifactDefinition(en.getValue())));
+
+ ci.get().setArtifacts(deplArt);
+ }
+ });
+ }
+
+ }
+
+ public static void convertComponentInstances(Component component, TopologyTemplate topologyTemplate) {
+
+ if (!CollectionUtils.isEmpty(component.getComponentInstances())) {
+
+ setComponentInstancesAttributesToTopologyTemplate(component, topologyTemplate);
+
+ setComponentInstancesPropertiesToTopologyTemplate(component, topologyTemplate);
+
+ setComponentInstancesInputsToTopologyTemplate(component, topologyTemplate);
+
+ setComponentInstancesToTopologyTemplate(component, topologyTemplate);
+
+ setComponentInstancesArtifactsToTopologyTemplate(component, topologyTemplate);
+ }
+ }
+
+ public static void convertRelations(TopologyTemplate topologyTemplate, Component component) {
+ Map<String, RelationshipInstDataDefinition> relations = topologyTemplate.getRelations();
+ List<RequirementCapabilityRelDef> componentRelations;
+ if (relations != null && !relations.isEmpty()) {
+ componentRelations = relations.values().stream().map(ModelConverter::convertRelation).collect(Collectors.toList());
+
+ } else {
+ componentRelations = new ArrayList<>();
+ }
+ component.setComponentInstancesRelations(componentRelations);
+
+ }
+
+ public static RequirementCapabilityRelDef convertRelation(RelationshipInstDataDefinition relation) {
+ RequirementCapabilityRelDef requirementCapabilityRelDef = new RequirementCapabilityRelDef();
+ requirementCapabilityRelDef.setFromNode(relation.getFromId());
+ requirementCapabilityRelDef.setToNode(relation.getToId());
+ List<RequirementAndRelationshipPair> relationships = new ArrayList<>();
+ RequirementAndRelationshipPair relationshipPair = new RequirementAndRelationshipPair();
+ relationshipPair.setId(relation.getUniqueId());
+
+ relationshipPair.setCapabilityOwnerId(relation.getCapabilityOwnerId());
+ relationshipPair.setCapabilityUid(relation.getCapabiltyId());
+ relationshipPair.setRequirementOwnerId(relation.getRequirementOwnerId());
+ relationshipPair.setRequirementUid(relation.getRequirementId());
+ relationshipPair.setRequirement(relation.getRequirement());
+ RelationshipImpl relationship = new RelationshipImpl();
+ relationship.setType(relation.getType());
+ relationshipPair.setRelationships(relationship);
+
+ relationships.add(relationshipPair);
+ requirementCapabilityRelDef.setRelationships(relationships);
+ return requirementCapabilityRelDef;
+ }
+
+ public static List<RelationshipInstDataDefinition> convertRelationToToscaRelation(RequirementCapabilityRelDef relation) {
+
+ List<RelationshipInstDataDefinition> relationsList = new ArrayList<>();
+
+ List<RequirementAndRelationshipPair> relationship = relation.getRelationships();
+ relationship.forEach(p -> {
+ RelationshipInstDataDefinition requirementCapabilityRelDef = new RelationshipInstDataDefinition();
+ requirementCapabilityRelDef.setFromId(relation.getFromNode());
+ requirementCapabilityRelDef.setToId(relation.getToNode());
+ requirementCapabilityRelDef.setUniqueId(p.getId());
+ requirementCapabilityRelDef.setCapabilityOwnerId(p.getCapabilityOwnerId());
+ requirementCapabilityRelDef.setCapabiltyId(p.getCapabilityUid());
+ requirementCapabilityRelDef.setRequirementOwnerId(p.getRequirementOwnerId());
+ requirementCapabilityRelDef.setRequirementId(p.getRequirementUid());
+ requirementCapabilityRelDef.setRequirement(p.getRequirement());
+ requirementCapabilityRelDef.setType(p.getRelationship().getType());
+ requirementCapabilityRelDef.setCapability(p.getCapability());
+
+ relationsList.add(requirementCapabilityRelDef);
+ });
+
+ return relationsList;
+ }
+
+ private static void convertCapabilities(Component component, TopologyTemplate topologyTemplate) {
+
+ if (component.getCapabilities() != null && component.getComponentInstances() != null) {
+ topologyTemplate.setCalculatedCapabilities(new HashMap<>());
+ topologyTemplate.setCalculatedCapabilitiesProperties(new HashMap<>());
+ for (ComponentInstance instance : component.getComponentInstances()) {
+ Map<String, List<CapabilityDefinition>> instCapabilities = instance.getCapabilities();
+ if (MapUtils.isNotEmpty(instCapabilities)) {
+ if (topologyTemplate.getCalculatedCapabilities() == null) {
+ topologyTemplate.setCalculatedCapabilities(new HashMap<>());
+ }
+ topologyTemplate.getCalculatedCapabilities().put(instance.getUniqueId(), convertToMapListCapabiltyDataDefinition(instCapabilities));
+ if (topologyTemplate.getCalculatedCapabilitiesProperties() == null) {
+ topologyTemplate.setCalculatedCapabilitiesProperties(new HashMap<>());
+ }
+ topologyTemplate.getCalculatedCapabilitiesProperties().put(instance.getUniqueId(), convertToMapOfMapCapabiltyProperties(instCapabilities, instance.getUniqueId()));
+ }
+ }
+ }
+ }
+
+ public static MapCapabiltyProperty convertToMapOfMapCapabiltyProperties(Map<String, List<CapabilityDefinition>> instCapabilities, String instanceId) {
+ return convertToMapOfMapCapabiltyProperties(instCapabilities, instanceId, false);
+ }
+
+ public static MapCapabiltyProperty convertToMapOfMapCapabiltyProperties(Map<String, List<CapabilityDefinition>> instCapabilities, String instanceId, boolean fromCsar) {
+
+ Map<String, MapPropertiesDataDefinition> toscaCapPropMap = new HashMap<>();
+
+ instCapabilities.forEach(new BiConsumer<String, List<CapabilityDefinition>>() {
+ @Override
+ public void accept(String s, List<CapabilityDefinition> caps) {
+
+ if (caps != null && !caps.isEmpty()) {
+
+ MapPropertiesDataDefinition dataToCreate = new MapPropertiesDataDefinition();
+
+ for (CapabilityDefinition cap : caps) {
+ List<ComponentInstanceProperty> capPrps = cap.getProperties();
+ if (capPrps != null) {
+
+ for (ComponentInstanceProperty cip : capPrps) {
+ dataToCreate.put(cip.getName(), new PropertyDataDefinition(cip));
+ }
+ // format key of capability properties :
+ // VF instance in service : instanceId#ownerId#type#capName
+ // VFC instance ion VF : instanceId#ownerId#type#capName -> instanceId=ownerId
+
+ StringBuffer sb = new StringBuffer(instanceId);
+ sb.append(CAP_PROP_DELIM);
+ if (fromCsar) {
+ sb.append(instanceId);
+ } else {
+ sb.append(cap.getOwnerId());
+ }
+ sb.append(CAP_PROP_DELIM).append(s).append(CAP_PROP_DELIM).append(cap.getName());
+ toscaCapPropMap.put(sb.toString(), dataToCreate);
+ }
+ }
+
+ }
+
+ }
+ });
+ return new MapCapabiltyProperty(toscaCapPropMap);
+ }
+
+ private static MapListCapabiltyDataDefinition convertToMapListCapabiltyDataDefinition(Map<String, List<CapabilityDefinition>> instCapabilities) {
+
+ Map<String, ListCapabilityDataDefinition> mapToscaDataDefinition = new HashMap<>();
+ for (Entry<String, List<CapabilityDefinition>> instCapability : instCapabilities.entrySet()) {
+ mapToscaDataDefinition.put(instCapability.getKey(), new ListCapabilityDataDefinition(instCapability.getValue().stream().map(iCap -> new CapabilityDataDefinition(iCap)).collect(Collectors.toList())));
+ }
+
+ return new MapListCapabiltyDataDefinition(mapToscaDataDefinition);
+ }
+
+ private static void convertRequirements(Component component, TopologyTemplate topologyTemplate) {
+
+ if (component.getRequirements() != null && component.getComponentInstances() != null) {
+ topologyTemplate.setCalculatedRequirements(new HashMap<>());
+ for (ComponentInstance instance : component.getComponentInstances()) {
+ Map<String, List<RequirementDefinition>> instRequirements = instance.getRequirements();
+ if (MapUtils.isNotEmpty(instRequirements)) {
+ if (topologyTemplate.getCalculatedRequirements() == null) {
+ topologyTemplate.setCalculatedRequirements(new HashMap<>());
+ }
+ topologyTemplate.getCalculatedRequirements().put(instance.getUniqueId(), convertToMapListRequirementDataDefinition(instRequirements));
+ }
+ }
+ }
+ }
+
+ private static MapListRequirementDataDefinition convertToMapListRequirementDataDefinition(Map<String, List<RequirementDefinition>> instRequirements) {
+
+ Map<String, ListRequirementDataDefinition> mapToscaDataDefinition = new HashMap<>();
+ for (Entry<String, List<RequirementDefinition>> instRequirement : instRequirements.entrySet()) {
+ mapToscaDataDefinition.put(instRequirement.getKey(), new ListRequirementDataDefinition(instRequirement.getValue().stream().map(iCap -> new RequirementDataDefinition(iCap)).collect(Collectors.toList())));
+ }
+
+ return new MapListRequirementDataDefinition(mapToscaDataDefinition);
+ }
+
+ private static void convertRequirements(TopologyTemplate toscaElement, Component component) {
+
+ if (CollectionUtils.isNotEmpty(component.getComponentInstances())) {
+ for (ComponentInstance instance : component.getComponentInstances()) {
+ Map<String, List<RequirementDefinition>> instanceRequirements = instance.getRequirements();
+ if (MapUtils.isNotEmpty(instanceRequirements)) {
+ addRequirementsByInstanceId(instance.getUniqueId(), instanceRequirements, component);
+ }
+ }
+ }
+ }
+
+ private static void addRequirementsByInstanceId(String instanceId, Map<String, List<RequirementDefinition>> instanceRequirementsMap, Component component) {
+
+ if (component.getCapabilities() == null) {
+ component.setCapabilities(new HashMap<>());
+ }
+ List<RequirementDefinition> instanceRequirements = new ArrayList<>();
+ for (List<RequirementDefinition> instRequirements : instanceRequirementsMap.values()) {
+ instanceRequirements.addAll(instRequirements);
+ }
+ component.getRequirements().put(instanceId, instanceRequirements);
+ }
+
+ private static void convertCapabilities(TopologyTemplate toscaElement, Component component) {
+
+ if (CollectionUtils.isNotEmpty(component.getComponentInstances())) {
+ for (ComponentInstance instance : component.getComponentInstances()) {
+ Map<String, List<CapabilityDefinition>> instanceCapabilities = instance.getCapabilities();
+ if (MapUtils.isNotEmpty(instanceCapabilities)) {
+ addCapabilitiesByInstanceId(instance.getUniqueId(), instanceCapabilities, component);
+ }
+ }
+ }
+ }
+
+ private static void addCapabilitiesByInstanceId(String instanceId, Map<String, List<CapabilityDefinition>> instanceCapabilitiesMap, Component component) {
+
+ if (component.getCapabilities() == null) {
+ component.setCapabilities(new HashMap<>());
+ }
+ List<CapabilityDefinition> instanceCapabilities = new ArrayList<>();
+ for (List<CapabilityDefinition> instCapabilitis : instanceCapabilitiesMap.values()) {
+ instanceCapabilities.addAll(instCapabilitis);
+ }
+ component.getCapabilities().put(instanceId, instanceCapabilities);
+ }
+
+ @SuppressWarnings("unchecked")
+ private static void convertComponentFields(Component component, ToscaElement toscaElement) {
+ component.setName(toscaElement.getName());
+ component.setAllVersions(toscaElement.getAllVersions());
+ component.setCategories(toscaElement.getCategories());
+ component.setComponentType(toscaElement.getComponentType());
+ component.setCreationDate(toscaElement.getCreationDate());
+ component.setCreatorUserId(toscaElement.getCreatorUserId());
+ component.setCreatorFullName(toscaElement.getCreatorFullName());
+ component.setLastUpdateDate(toscaElement.getLastUpdateDate());
+ component.setLastUpdaterFullName(toscaElement.getLastUpdaterFullName());
+ component.setLastUpdaterUserId(toscaElement.getLastUpdaterUserId());
+ component.setNormalizedName(toscaElement.getNormalizedName());
+
+ component.setLifecycleState(toscaElement.getLifecycleState());
+ component.setVersion(toscaElement.getVersion());
+ component.setHighestVersion(toscaElement.isHighestVersion());
+ component.setUniqueId(toscaElement.getUniqueId());
+ component.setSystemName((String) toscaElement.getMetadataValue(JsonPresentationFields.SYSTEM_NAME));
+ component.setDerivedFromGenericType(toscaElement.getDerivedFromGenericType());
+ component.setDerivedFromGenericVersion(toscaElement.getDerivedFromGenericVersion());
+
+ if (component.getComponentType() == ComponentTypeEnum.RESOURCE) {
+ Resource resource = (Resource) component;
+ resource.setAbstract((Boolean) toscaElement.getMetadataValue(JsonPresentationFields.IS_ABSTRACT));
+ resource.setToscaResourceName((String) toscaElement.getMetadataValue(JsonPresentationFields.TOSCA_RESOURCE_NAME));
+ resource.setVendorName((String) toscaElement.getMetadataValue(JsonPresentationFields.VENDOR_NAME));
+ resource.setVendorRelease((String) toscaElement.getMetadataValue(JsonPresentationFields.VENDOR_RELEASE));
+ }
+ component.setConformanceLevel((String) toscaElement.getMetadataValue(JsonPresentationFields.CONFORMANCE_LEVEL));
+ component.setIcon((String) toscaElement.getMetadataValue(JsonPresentationFields.ICON));
+ component.setDescription((String) toscaElement.getMetadataValue(JsonPresentationFields.DESCRIPTION));
+ component.setTags((List<String>) toscaElement.getMetadataValue(JsonPresentationFields.TAGS));
+ component.setInvariantUUID((String) toscaElement.getMetadataValue(JsonPresentationFields.INVARIANT_UUID));
+ component.setContactId((String) toscaElement.getMetadataValue(JsonPresentationFields.CONTACT_ID));
+ component.setUUID((String) toscaElement.getMetadataValue(JsonPresentationFields.UUID));
+ component.setIsDeleted((Boolean) toscaElement.getMetadataValue(JsonPresentationFields.IS_DELETED));
+
+ Map<String, PropertyDataDefinition> properties = toscaElement.getProperties();
+ if (properties != null && !properties.isEmpty()) {
+ List<PropertyDefinition> propertiesMap = properties.values().stream().map(x -> new PropertyDefinition(x)).collect(Collectors.toList());
+ ((Resource) component).setProperties(propertiesMap);
+ }
+
+ component.setToscaType(toscaElement.getToscaType().getValue());
+ }
+
+ private static NodeType convertToNodeType(Component component) {
+ Resource resource = (Resource) component;
+ NodeType nodeType = new NodeType();
+ nodeType.setDerivedFrom(resource.getDerivedFrom());
+ nodeType.setDerivedList(resource.getDerivedList());
+ nodeType.setResourceType(resource.getResourceType());
+ // nodeType.setCapabiltiesProperties(capabiltiesProperties);
+ convertCommonToscaData(component, nodeType);
+ convertAdditionalInformation(component, nodeType);
+ convertArtifacts(resource, nodeType);
+ convertCapabilities(resource, nodeType);
+ convertRequirements(resource, nodeType);
+ convertAttributes(resource, nodeType);
+ convertProperties(resource, nodeType);
+ convertInterfaces(resource, nodeType);
+ return nodeType;
+ }
+
+ private static void convertProperties(Resource resource, NodeType nodeType) {
+ List<PropertyDefinition> properties = resource.getProperties();
+ if (properties != null && !properties.isEmpty()) {
+ Map<String, PropertyDataDefinition> propertiesMap = properties.stream().collect(Collectors.toMap(x -> x.getName(), x -> new PropertyDataDefinition(x)));
+ nodeType.setProperties(propertiesMap);
+ }
+ }
+
+ private static void convertInterfaces(Resource resource, NodeType nodeType) {
+ Map<String, InterfaceDefinition> interfaces = resource.getInterfaces();
+ if (interfaces != null) {
+ Map<String, InterfaceDataDefinition> interfaceArtifacts = interfaces.entrySet().stream().collect(Collectors.toMap(x -> x.getKey(), x -> new InterfaceDataDefinition(x.getValue())));
+ nodeType.setInterfaceArtifacts(interfaceArtifacts);
+ }
+ }
+
+ private static void convertAdditionalInformation(Component component, ToscaElement toscaElement) {
+ List<AdditionalInformationDefinition> additionalInformation = component.getAdditionalInformation();
+ if (additionalInformation != null) {
+ Map<String, AdditionalInfoParameterDataDefinition> addInfo = additionalInformation.stream().collect(Collectors.toMap(x -> x.getUniqueId(), x -> new AdditionalInfoParameterDataDefinition(x)));
+ toscaElement.setAdditionalInformation(addInfo);
+ }
+ }
+
+ private static void convertAdditionalInformation(ToscaElement toscaElement, Component resource) {
+ Map<String, AdditionalInfoParameterDataDefinition> additionalInformation = toscaElement.getAdditionalInformation();
+ if (additionalInformation != null) {
+ List<AdditionalInformationDefinition> addInfo = additionalInformation.values().stream().map(e -> {
+ return new AdditionalInformationDefinition(e);
+ }).collect(Collectors.toList());
+ resource.setAdditionalInformation(addInfo);
+ }
+ }
+
+ private static void convertArtifacts(ToscaElement toscaElement, Component component) {
+ Map<String, ArtifactDataDefinition> artifacts = toscaElement.getArtifacts();
+ Map<String, ArtifactDefinition> copy;
+ if (artifacts != null) {
+ copy = artifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDefinition(e.getValue())));
+
+ } else {
+ copy = new HashMap<>();
+ }
+ component.setArtifacts(copy);
+
+ Map<String, ArtifactDataDefinition> toscaArtifacts = toscaElement.getToscaArtifacts();
+ if (toscaArtifacts != null) {
+ copy = toscaArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDefinition(e.getValue())));
+
+ } else {
+ copy = new HashMap<>();
+ }
+ component.setToscaArtifacts(copy);
+
+ Map<String, ArtifactDataDefinition> deploymentArtifacts = toscaElement.getDeploymentArtifacts();
+ if (deploymentArtifacts != null) {
+ copy = deploymentArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDefinition(e.getValue())));
+
+ } else {
+ copy = new HashMap<>();
+ }
+ component.setDeploymentArtifacts(copy);
+ }
+
+ private static void convertServiceApiArtifacts(TopologyTemplate topologyTemplate, Service service) {
+ Map<String, ArtifactDataDefinition> serviceApiArtifacts = topologyTemplate.getServiceApiArtifacts();
+ Map<String, ArtifactDefinition> copy;
+ if (serviceApiArtifacts != null) {
+ copy = serviceApiArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDefinition(e.getValue())));
+
+ } else {
+ copy = new HashMap<>();
+ }
+ service.setServiceApiArtifacts(copy);
+ }
+
+ private static void convertArtifacts(Component component, ToscaElement toscaElement) {
+ Map<String, ArtifactDefinition> artifacts = component.getArtifacts();
+ if (artifacts != null) {
+ Map<String, ArtifactDataDefinition> copy = artifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
+ toscaElement.setArtifacts(copy);
+ }
+
+ Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
+ if (toscaArtifacts != null) {
+ Map<String, ArtifactDataDefinition> copy = toscaArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
+ toscaElement.setToscaArtifacts(copy);
+ }
+
+ Map<String, ArtifactDefinition> deploymentArtifacts = component.getDeploymentArtifacts();
+ if (deploymentArtifacts != null) {
+ Map<String, ArtifactDataDefinition> copy = deploymentArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
+ toscaElement.setDeploymentArtifacts(copy);
+ }
+ }
+
+ private static void convertServiceApiArtifacts(Service service, TopologyTemplate topologyTemplate) {
+ Map<String, ArtifactDefinition> serviceApiArtifacts = service.getServiceApiArtifacts();
+ if (serviceApiArtifacts != null) {
+ Map<String, ArtifactDataDefinition> copy = serviceApiArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
+ topologyTemplate.setServiceApiArtifacts(copy);
+ }
+ }
+
+ private static void convertCapabilities(Component component, NodeType toscaElement) {
+ Map<String, List<CapabilityDefinition>> capabilities = component.getCapabilities();
+
+ Map<String, ListCapabilityDataDefinition> toscaCapMap = new HashMap<>();
+ Map<String, MapPropertiesDataDefinition> toscaCapPropMap = new HashMap<>();
+
+ if (capabilities != null && !capabilities.isEmpty()) {
+ capabilities.forEach(new BiConsumer<String, List<CapabilityDefinition>>() {
+ @Override
+ public void accept(String s, List<CapabilityDefinition> caps) {
+
+ if (caps != null && !caps.isEmpty()) {
+ List<CapabilityDataDefinition> capList = caps.stream().map(o -> {
+ return new CapabilityDataDefinition(o);
+ }).collect(Collectors.toList());
+
+ ListCapabilityDataDefinition listCapabilityDataDefinition = new ListCapabilityDataDefinition(capList);
+ toscaCapMap.put(s, listCapabilityDataDefinition);
+
+ for (CapabilityDefinition cap : caps) {
+ List<ComponentInstanceProperty> capPrps = cap.getProperties();
+ if (capPrps != null && !capPrps.isEmpty()) {
+
+ MapPropertiesDataDefinition dataToCreate = new MapPropertiesDataDefinition();
+ for (ComponentInstanceProperty cip : capPrps) {
+ dataToCreate.put(cip.getName(), new PropertyDataDefinition(cip));
+ }
+
+ toscaCapPropMap.put(s + CAP_PROP_DELIM + cap.getName(), dataToCreate);
+ }
+ }
+
+ }
+
+ }
+ });
+
+ toscaElement.setCapabilties(toscaCapMap);
+ toscaElement.setCapabiltiesProperties(toscaCapPropMap);
+ }
+ }
+
+ private static void convertAttributes(Resource component, NodeType nodeType) {
+ List<AttributeDefinition> attributes = component.getAttributes();
+ if (attributes != null) {
+ Map<String, AttributeDataDefinition> attrsByName = attributes.stream().map(AttributeDataDefinition::new).collect(Collectors.toMap(AttributeDataDefinition::getName, Function.identity()));
+ nodeType.setAttributes(attrsByName);
+ }
+ }
+
+ private static void convertRequirements(Resource component, NodeType nodeType) {
+ Map<String, List<RequirementDefinition>> requirements = component.getRequirements();
+
+ Map<String, ListRequirementDataDefinition> toscaReqMap = new HashMap<>();
+
+ if (requirements != null && !requirements.isEmpty()) {
+ requirements.forEach(new BiConsumer<String, List<RequirementDefinition>>() {
+ @Override
+ public void accept(String s, List<RequirementDefinition> reqs) {
+
+ if (reqs != null && !reqs.isEmpty()) {
+ List<RequirementDataDefinition> reqList = reqs.stream().map(o -> {
+ return new RequirementDataDefinition(o);
+ }).collect(Collectors.toList());
+
+ ListRequirementDataDefinition listRequirementDataDefinition = new ListRequirementDataDefinition(reqList);
+ toscaReqMap.put(s, listRequirementDataDefinition);
+ }
+ }
+ });
+ nodeType.setRequirements(toscaReqMap);
+ }
+ }
+
+ private static void convertCapabilities(NodeType toscaElement, Component component) {
+ Map<String, ListCapabilityDataDefinition> toscaCapabilities = toscaElement.getCapabilties();
+ Map<String, MapPropertiesDataDefinition> toscaCapPropMap = toscaElement.getCapabiltiesProperties();
+
+ Map<String, List<CapabilityDefinition>> compCap = new HashMap<>();
+ if (toscaCapabilities == null || toscaCapabilities.isEmpty())
+ return;
+ toscaCapabilities.forEach(new BiConsumer<String, ListCapabilityDataDefinition>() {
+ @Override
+ public void accept(String s, ListCapabilityDataDefinition cap) {
+
+ if (cap != null) {
+ List<CapabilityDataDefinition> capDataList = cap.getListToscaDataDefinition();
+
+ if (capDataList != null && !capDataList.isEmpty()) {
+ List<CapabilityDefinition> capList = capDataList.stream().map(o -> {
+
+ return new CapabilityDefinition(o);
+ }).collect(Collectors.toList());
+ compCap.put(s, capList);
+ }
+ }
+
+ }
+ });
+ if (toscaCapPropMap != null && !toscaCapPropMap.isEmpty()) {
+ toscaCapPropMap.forEach(new BiConsumer<String, MapPropertiesDataDefinition>() {
+ @Override
+ public void accept(String s, MapPropertiesDataDefinition capProp) {
+ String[] result = s.split(CAP_PROP_DELIM);
+ if (capProp != null) {
+ Map<String, PropertyDataDefinition> capMap = capProp.getMapToscaDataDefinition();
+
+ if (capMap != null && !capMap.isEmpty()) {
+ // List<PropertyDataDefinition> list = map.values().stream().collect(Collectors.toList());
+ List<ComponentInstanceProperty> capPropsList = capMap.values().stream().map(o -> {
+
+ return new ComponentInstanceProperty(o);
+ }).collect(Collectors.toList());
+
+ List<CapabilityDefinition> cap = compCap.get(result[0]);
+ Optional<CapabilityDefinition> op = cap.stream().filter(c -> c.getName().equals(result[1])).findFirst();
+ if (op.isPresent()) {
+ op.get().setProperties(capPropsList);
+ }
+ }
+
+ }
+
+ }
+ });
+ }
+
+ component.setCapabilities(compCap);
+
+ }
+
+ private static void convertGroups(TopologyTemplate toscaElement, Component component) {
+ Map<String, GroupDataDefinition> toscaGroups = toscaElement.getGroups();
+ List<GroupDefinition> groupDefinitions = null;
+ if (MapUtils.isNotEmpty(toscaGroups)) {
+ groupDefinitions = toscaGroups.values().stream().map(g -> new GroupDefinition(g)).collect(Collectors.toList());
+ }
+ component.setGroups(groupDefinitions);
+ }
+
+ 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))));
+ }
+ toscaElement.setGroups(groups);
+
+ }
+
+ private static void convertRequirements(NodeType toscaElement, Component component) {
+ Map<String, ListRequirementDataDefinition> toscaRequirements = toscaElement.getRequirements();
+
+ Map<String, List<RequirementDefinition>> compReqs = new HashMap<>();
+ if (toscaRequirements == null || toscaRequirements.isEmpty())
+ return;
+ toscaRequirements.forEach(new BiConsumer<String, ListRequirementDataDefinition>() {
+ @Override
+ public void accept(String s, ListRequirementDataDefinition req) {
+
+ if (req != null) {
+ List<RequirementDataDefinition> reqDataList = req.getListToscaDataDefinition();
+
+ if (reqDataList != null && !reqDataList.isEmpty()) {
+ List<RequirementDefinition> reqList = reqDataList.stream().map(o -> {
+
+ return new RequirementDefinition(o);
+ }).collect(Collectors.toList());
+ compReqs.put(s, reqList);
+ }
+ }
+ }
+ });
+ component.setRequirements(compReqs);
+ }
+
+ private static TopologyTemplate convertToTopologyTemplate(Component component) {
+ TopologyTemplate topologyTemplate;
+ ComponentTypeEnum componentType = component.getComponentType();
+ topologyTemplate = new TopologyTemplate();
+
+ if (componentType == ComponentTypeEnum.RESOURCE) {
+ Resource resource = (Resource) component;
+ topologyTemplate.setResourceType(resource.getResourceType());
+ topologyTemplate.setMetadataValue(JsonPresentationFields.CSAR_UUID, resource.getCsarUUID());
+ topologyTemplate.setMetadataValue(JsonPresentationFields.CSAR_VERSION, resource.getCsarVersion());
+ topologyTemplate.setMetadataValue(JsonPresentationFields.IMPORTED_TOSCA_CHECKSUM, resource.getImportedToscaChecksum());
+ }
+ if (componentType == ComponentTypeEnum.SERVICE) {
+ convertServiceSpecificEntities((Service) component, topologyTemplate);
+ }
+ convertCommonToscaData(component, topologyTemplate);
+ convertArtifacts(component, topologyTemplate);
+
+ convertAdditionalInformation(component, topologyTemplate);
+ convertComponentInstances(component, topologyTemplate);
+
+ convertInputs(component, topologyTemplate);
+ convertCapabilities(component, topologyTemplate);
+ convertGroups(component, topologyTemplate);
+ convertRequirements(component, topologyTemplate);
+ convertRelationsToComposition(component, topologyTemplate);
+
+ return topologyTemplate;
+ }
+
+ private static void convertServiceSpecificEntities(Service service, TopologyTemplate topologyTemplate) {
+ convertServiceMetaData(service, topologyTemplate);
+ convertServiceApiArtifacts(service, topologyTemplate);
+ }
+
+ private static void convertServiceMetaData(Service service, TopologyTemplate topologyTemplate) {
+ if (service.getDistributionStatus() != null) {
+ topologyTemplate.setMetadataValue(JsonPresentationFields.DISTRIBUTION_STATUS, service.getDistributionStatus().name());
+ }
+ topologyTemplate.setMetadataValue(JsonPresentationFields.PROJECT_CODE, service.getProjectCode());
+ topologyTemplate.setMetadataValue(JsonPresentationFields.ECOMP_GENERATED_NAMING, service.isEcompGeneratedNaming());
+ topologyTemplate.setMetadataValue(JsonPresentationFields.NAMING_POLICY, service.getNamingPolicy());
+
+ }
+
+ private static void convertRelationsToComposition(Component component, TopologyTemplate topologyTemplate) {
+ List<RequirementCapabilityRelDef> componentInstancesRelations = component.getComponentInstancesRelations();
+ if (componentInstancesRelations != null) {
+ Map<String, CompositionDataDefinition> compositions = topologyTemplate.getCompositions();
+ if (compositions == null) {
+ compositions = new HashMap<>();
+ }
+ CompositionDataDefinition compositionDataDefinition = compositions.get(JsonConstantKeysEnum.COMPOSITION.getValue());
+ if (compositionDataDefinition == null) {
+ compositionDataDefinition = new CompositionDataDefinition();
+ compositions.put(JsonConstantKeysEnum.COMPOSITION.getValue(), compositionDataDefinition);
+ }
+
+ Map<String, RelationshipInstDataDefinition> relations = componentInstancesRelations.stream().flatMap(x -> convertRelationToToscaRelation(x).stream()).filter(i -> i.getUniqueId() != null)
+ .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
+ compositionDataDefinition.setRelations(relations);
+ }
+ }
+
+ private static void convertInputs(Component component, TopologyTemplate topologyTemplate) {
+ List<InputDefinition> inputsList = component.getInputs();
+ if (inputsList != null && !inputsList.isEmpty()) {
+
+ Map<String, PropertyDataDefinition> inputsMap = inputsList.stream().map(i -> new PropertyDataDefinition(i)).collect(Collectors.toMap(i -> i.getName(), i -> i));
+ topologyTemplate.setInputs(inputsMap);
+ }
+
+ }
+
+ private static void convertInputs(TopologyTemplate topologyTemplate, Component component) {
+ Map<String, PropertyDataDefinition> inputsMap = topologyTemplate.getInputs();
+ if (inputsMap != null && !inputsMap.isEmpty()) {
+ List<InputDefinition> inputsList = inputsMap.values().stream().map(i -> new InputDefinition(i)).collect(Collectors.toList());
+ component.setInputs(inputsList);
+ }
+
+ }
+
+ private static void convertCommonToscaData(Component component, ToscaElement toscaElement) {
+ toscaElement.setUUID(component.getUUID());
+ toscaElement.setUniqueId(component.getUniqueId());
+ toscaElement.setSystemName(component.getSystemName());
+ toscaElement.setLifecycleState(component.getLifecycleState());
+ toscaElement.setComponentType(component.getComponentType());
+ toscaElement.setNormalizedName(component.getNormalizedName());
+ toscaElement.setMetadataValue(JsonPresentationFields.NAME, component.getName());
+ toscaElement.setCategories(component.getCategories());
+ toscaElement.setCreatorUserId(component.getCreatorUserId());
+ toscaElement.setCreationDate(component.getCreationDate());
+ toscaElement.setCreatorFullName(component.getCreatorFullName());
+ toscaElement.setHighestVersion(component.isHighestVersion());
+ toscaElement.setLastUpdateDate(component.getLastUpdateDate());
+ toscaElement.setLastUpdaterFullName(component.getLastUpdaterFullName());
+ toscaElement.setLastUpdaterUserId(component.getLastUpdaterUserId());
+ toscaElement.setDerivedFromGenericType(component.getDerivedFromGenericType());
+ toscaElement.setDerivedFromGenericVersion(component.getDerivedFromGenericVersion());
+
+ toscaElement.setLifecycleState(component.getLifecycleState());
+ toscaElement.setMetadataValue(JsonPresentationFields.VERSION, component.getVersion());
+ if (component.getComponentType() == ComponentTypeEnum.RESOURCE) {
+ toscaElement.setMetadataValue(JsonPresentationFields.IS_ABSTRACT, ((Resource) component).isAbstract());
+ toscaElement.setMetadataValue(JsonPresentationFields.TOSCA_RESOURCE_NAME, ((Resource) component).getToscaResourceName());
+ toscaElement.setMetadataValue(JsonPresentationFields.VENDOR_NAME, ((Resource) component).getVendorName());
+ toscaElement.setMetadataValue(JsonPresentationFields.VENDOR_RELEASE, ((Resource) component).getVendorRelease());
+ }
+ toscaElement.setMetadataValue(JsonPresentationFields.CONFORMANCE_LEVEL, component.getConformanceLevel());
+ toscaElement.setMetadataValue(JsonPresentationFields.IS_DELETED, component.getIsDeleted());
+ toscaElement.setMetadataValue(JsonPresentationFields.ICON, component.getIcon());
+ toscaElement.setMetadataValue(JsonPresentationFields.DESCRIPTION, component.getDescription());
+ toscaElement.setMetadataValue(JsonPresentationFields.TAGS, component.getTags());
+ toscaElement.setMetadataValue(JsonPresentationFields.INVARIANT_UUID, component.getInvariantUUID());
+ toscaElement.setMetadataValue(JsonPresentationFields.CONTACT_ID, component.getContactId());
+ }
+
+ private static boolean isAtomicComponent(Component component) {
+ ComponentTypeEnum componentType = component.getComponentType();
+ if (!componentType.equals(ComponentTypeEnum.RESOURCE)) {
+ return false;
+ }
+ Resource resource = (Resource) component;
+ ResourceTypeEnum resType = resource.getResourceType();
+ if (resType == ResourceTypeEnum.VFC || resType == ResourceTypeEnum.VFCMT || resType == ResourceTypeEnum.VL || resType == ResourceTypeEnum.CP || resType == ResourceTypeEnum.ABSTRACT) {
+ return true;
+ }
+ return false;
+ }
+
+ private static void setComponentInstancesToComponent(TopologyTemplate topologyTemplate, Component component) {
+
+ List<ComponentInstance> componentInstances = new ArrayList<>();
+ ComponentInstance currComponentInstance;
+ for (Map.Entry<String, ComponentInstanceDataDefinition> entry : topologyTemplate.getComponentInstances().entrySet()) {
+ String key = entry.getKey();
+ currComponentInstance = new ComponentInstance(topologyTemplate.getComponentInstances().get(key));
+ if (topologyTemplate.getInstGroups() != null && topologyTemplate.getInstGroups().containsKey(key)) {
+ List<GroupInstance> groupInstances = topologyTemplate.getInstGroups().get(key).getMapToscaDataDefinition().entrySet().stream().map(e -> new GroupInstance(e.getValue())).collect(Collectors.toList());
+ currComponentInstance.setGroupInstances(groupInstances);
+ }
+ componentInstances.add(currComponentInstance);
+ }
+ component.setComponentInstances(componentInstances);
+ }
+
+ private static void setComponentInstancesInputsToComponent(TopologyTemplate topologyTemplate, Component component) {
+ if (topologyTemplate.getInstInputs() != null) {
+ Map<String, List<ComponentInstanceInput>> inputs = new HashMap<>();
+ for (Entry<String, MapPropertiesDataDefinition> entry : topologyTemplate.getInstInputs().entrySet()) {
+ if (entry.getValue() != null && entry.getValue().getMapToscaDataDefinition() != null) {
+ String key = entry.getKey();
+ List<ComponentInstanceInput> componentInstanceAttributes = entry.getValue().getMapToscaDataDefinition().entrySet().stream().map(e -> new ComponentInstanceInput(e.getValue())).collect(Collectors.toList());
+ inputs.put(key, componentInstanceAttributes);
+ }
+ }
+ component.setComponentInstancesInputs(inputs);
+ }
+ }
+
+ private static void setComponentInstancesPropertiesToComponent(TopologyTemplate topologyTemplate, Component component) {
+ if (topologyTemplate.getInstProperties() != null) {
+ Map<String, List<ComponentInstanceProperty>> properties = new HashMap<>();
+ for (Entry<String, MapPropertiesDataDefinition> entry : topologyTemplate.getInstProperties().entrySet()) {
+ if (entry.getValue() != null && entry.getValue().getMapToscaDataDefinition() != null) {
+ String key = entry.getKey();
+ List<ComponentInstanceProperty> componentInstanceAttributes = entry.getValue().getMapToscaDataDefinition().entrySet().stream().map(e -> new ComponentInstanceProperty(new PropertyDefinition(e.getValue())))
+ .collect(Collectors.toList());
+ properties.put(key, componentInstanceAttributes);
+ }
+ }
+ component.setComponentInstancesProperties(properties);
+ }
+ }
+
+ private static void setComponentInstancesAttributesToComponent(TopologyTemplate topologyTemplate, Component component) {
+ if (topologyTemplate.getInstAttributes() != null) {
+ Map<String, List<ComponentInstanceAttribute>> attributes = new HashMap<>();
+ for (Map.Entry<String, MapAttributesDataDefinition> entry : topologyTemplate.getInstAttributes().entrySet()) {
+ if (entry.getValue() != null && entry.getValue().getMapToscaDataDefinition() != null) {
+ String key = entry.getKey();
+ List<ComponentInstanceAttribute> componentInstanceAttributes = entry.getValue().getMapToscaDataDefinition().entrySet().stream().map(e -> new ComponentInstanceAttribute(new AttributeDefinition(e.getValue())))
+ .collect(Collectors.toList());
+ attributes.put(key, componentInstanceAttributes);
+ }
+ }
+ component.setComponentInstancesAttributes(attributes);
+ }
+ }
+
+ private static void setComponentInstancesRequirementsToComponent(TopologyTemplate topologyTemplate, Component component) {
+
+ if (topologyTemplate.getCalculatedRequirements() != null) {
+ // Requirements of component organized by capability
+ Map<String, List<RequirementDefinition>> instancesRequirements = new HashMap<>();
+
+ Map<String, ComponentInstance> instancesMap = new HashMap<>();
+ for (ComponentInstance currInstance : component.getComponentInstances()) {
+ instancesMap.put(currInstance.getUniqueId(), currInstance);
+ }
+ for (Map.Entry<String, MapListRequirementDataDefinition> entry : topologyTemplate.getCalculatedRequirements().entrySet()) {
+
+ String instanceId = entry.getKey();
+ // Requirements of instance organized by capability
+ Map<String, ListRequirementDataDefinition> capsMapList = entry.getValue().getMapToscaDataDefinition();
+
+ for (Entry<String, ListRequirementDataDefinition> entryTypeList : capsMapList.entrySet()) {
+ String capabilityType = entryTypeList.getKey();
+ List<RequirementDefinition> caps = entryTypeList.getValue().getListToscaDataDefinition().stream().map(cap -> new RequirementDefinition(cap)).collect(Collectors.toList());
+ if (instancesRequirements.containsKey(capabilityType)) {
+ instancesRequirements.get(capabilityType).addAll(caps);
+ } else {
+ instancesRequirements.put(capabilityType, caps);
+ }
+ if (MapUtils.isEmpty(instancesMap.get(instanceId).getRequirements())) {
+ instancesMap.get(instanceId).setRequirements(new HashMap<>());
+ }
+ instancesMap.get(instanceId).getRequirements().put(capabilityType, new ArrayList<>(caps));
+ }
+ }
+ component.setRequirements(instancesRequirements);
+ }
+ }
+
+ private static void setComponentInstancesCapabilitiesToComponentAndCI(TopologyTemplate topologyTemplate, Component component) {
+ Map<String, MapCapabiltyProperty> calculatedCapProperties = topologyTemplate.getCalculatedCapabilitiesProperties();
+
+ if (topologyTemplate.getCalculatedCapabilities() != null) {
+ // capabilities of component organized by type
+ Map<String, List<CapabilityDefinition>> instancesCapabilities = new HashMap<>();
+
+ Map<String, ComponentInstance> instancesMap = new HashMap<>();
+ for (ComponentInstance currInstance : component.getComponentInstances()) {
+ instancesMap.put(currInstance.getUniqueId(), currInstance);
+ }
+ for (Map.Entry<String, MapListCapabiltyDataDefinition> entry : topologyTemplate.getCalculatedCapabilities().entrySet()) {
+
+ String instanceId = entry.getKey();
+ // capabilities of instance organized by type
+ Map<String, ListCapabilityDataDefinition> capsMapList = entry.getValue().getMapToscaDataDefinition();
+
+ for (Entry<String, ListCapabilityDataDefinition> entryTypeList : capsMapList.entrySet()) {
+ String capabilityType = entryTypeList.getKey();
+ List<CapabilityDefinition> caps = entryTypeList.getValue().getListToscaDataDefinition().stream().map(cap -> mergeInstCapabiltyWithProperty(cap, instanceId, calculatedCapProperties)).collect(Collectors.toList());
+ if (instancesCapabilities.containsKey(capabilityType)) {
+ instancesCapabilities.get(capabilityType).addAll(caps);
+ } else {
+ instancesCapabilities.put(capabilityType, caps);
+ }
+ if (MapUtils.isEmpty(instancesMap.get(instanceId).getCapabilities())) {
+ instancesMap.get(instanceId).setCapabilities(new HashMap<>());
+ }
+ instancesMap.get(instanceId).getCapabilities().put(capabilityType, new ArrayList<>(caps));
+ }
+ }
+ component.setCapabilities(instancesCapabilities);
+ }
+ }
+
+ private static CapabilityDefinition mergeInstCapabiltyWithProperty(CapabilityDataDefinition cap, String instance, Map<String, MapCapabiltyProperty> calculatedCapProperties) {
+ CapabilityDefinition capability = new CapabilityDefinition(cap);
+ if (calculatedCapProperties != null) {
+ MapCapabiltyProperty mapOfMapPropertiesDataDefinition = calculatedCapProperties.get(instance);
+ if (mapOfMapPropertiesDataDefinition != null && mapOfMapPropertiesDataDefinition.getMapToscaDataDefinition() != null) {
+
+ Map<String, MapPropertiesDataDefinition> toscaCapPropMap = mapOfMapPropertiesDataDefinition.getMapToscaDataDefinition();
+ toscaCapPropMap.forEach(new BiConsumer<String, MapPropertiesDataDefinition>() {
+ @Override
+ public void accept(String s, MapPropertiesDataDefinition capProp) {
+ // format key of capability properties :
+ // VF instance in service : instanceId#ownerId#type#capName
+ // VFC instance ion VF : instanceId#type#capName -> instanceId=ownerId
+ String[] result = s.split(CAP_PROP_DELIM);
+ if (result.length < 4) {
+ log.debug("wrong key format for capabilty, key {}", capProp);
+ return;
+ }
+ int instanceIndex = 0;
+ int ownerIndex = 1;
+ int typeIndex = result.length - 2;
+ int nameIndex = result.length - 1;
+ if (capProp != null) {
+ if (result[typeIndex].equals(cap.getType()) && result[nameIndex].equals(cap.getName()) && cap.getOwnerId().equals(result[ownerIndex]) && instance.equals(result[instanceIndex])) {
+
+ Map<String, PropertyDataDefinition> capMap = capProp.getMapToscaDataDefinition();
+
+ if (capMap != null && !capMap.isEmpty()) {
+ // List<PropertyDataDefinition> list = map.values().stream().collect(Collectors.toList());
+ List<ComponentInstanceProperty> capPropsList = capMap.values().stream().map(o -> {
+
+ return new ComponentInstanceProperty(o);
+ }).collect(Collectors.toList());
+
+ capability.setProperties(capPropsList);
+ }
+ }
+ }
+ }
+ });
+ }
+ }
+ return capability;
+ }
+
+ private static void setComponentInstancesToTopologyTemplate(Component component, TopologyTemplate topologyTemplate) {
+
+ Map<String, ComponentInstanceDataDefinition> componentInstances = new HashMap<>();
+ ComponentInstanceDataDefinition convertedInstance;
+ if (component.getComponentInstances() != null) {
+ for (ComponentInstance instance : component.getComponentInstances()) {
+ convertedInstance = new ComponentInstanceDataDefinition(instance);
+ if (instance.getGroupInstances() != null) {
+ MapGroupsDataDefinition groupsMap = new MapGroupsDataDefinition();
+
+ groupsMap.setMapToscaDataDefinition(instance.getGroupInstances().stream().map(e -> new GroupInstanceDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e)));
+ if (topologyTemplate.getInstGroups() == null) {
+ topologyTemplate.setInstGroups(new HashMap<>());
+ }
+ topologyTemplate.getInstGroups().put(instance.getUniqueId(), groupsMap);
+ }
+ componentInstances.put(instance.getUniqueId(), convertedInstance);
+ }
+ }
+ topologyTemplate.setComponentInstances(componentInstances);
+
+ }
+
+ private static void setComponentInstancesInputsToTopologyTemplate(Component component, TopologyTemplate topologyTemplate) {
+
+ if (component.getComponentInstancesInputs() != null) {
+ topologyTemplate.setInstInputs(new HashMap<>());
+ MapPropertiesDataDefinition inputsMap;
+ for (Entry<String, List<ComponentInstanceInput>> entry : component.getComponentInstancesInputs().entrySet()) {
+ inputsMap = new MapPropertiesDataDefinition();
+
+ inputsMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new PropertyDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e)));
+
+ topologyTemplate.getInstInputs().put(entry.getKey(), inputsMap);
+ }
+ }
+ }
+
+ private static void setComponentInstancesPropertiesToTopologyTemplate(Component component, TopologyTemplate topologyTemplate) {
+
+ if (component.getComponentInstancesProperties() != null) {
+ topologyTemplate.setInstProperties(new HashMap<>());
+ MapPropertiesDataDefinition propertiesMap;
+ for (Entry<String, List<ComponentInstanceProperty>> entry : component.getComponentInstancesProperties().entrySet()) {
+ propertiesMap = new MapPropertiesDataDefinition();
+
+ propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new PropertyDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e)));
+
+ topologyTemplate.getInstProperties().put(entry.getKey(), propertiesMap);
+ }
+ }
+ }
+
+ private static void setComponentInstancesArtifactsToTopologyTemplate(Component component, TopologyTemplate topologyTemplate) {
+
+ List<ComponentInstance> componentInstances = component.getComponentInstances();
+ if (componentInstances != null) {
+ topologyTemplate.setInstanceArtifacts(new HashMap<>());
+ topologyTemplate.setInstDeploymentArtifacts(new HashMap<>());
+
+ for (ComponentInstance ci : componentInstances) {
+ Map<String, ArtifactDefinition> artifacts = ci.getArtifacts();
+ if (artifacts != null) {
+ Map<String, ArtifactDataDefinition> mapToscaDataDefinitionArtifact = artifacts.entrySet().stream().collect(Collectors.toMap(e -> e.getKey(), e -> new ArtifactDataDefinition(e.getValue())));
+ MapArtifactDataDefinition insArtifact = new MapArtifactDataDefinition(mapToscaDataDefinitionArtifact);
+ topologyTemplate.getInstanceArtifacts().put(ci.getUniqueId(), insArtifact);
+ }
+
+ Map<String, ArtifactDefinition> deplArtifacts = ci.getDeploymentArtifacts();
+ if (deplArtifacts != null) {
+ Map<String, ArtifactDataDefinition> mapToscaDataDefinitionDepArtifact = deplArtifacts.entrySet().stream().collect(Collectors.toMap(e -> e.getKey(), e -> new ArtifactDataDefinition(e.getValue())));
+ MapArtifactDataDefinition insDepArtifact = new MapArtifactDataDefinition(mapToscaDataDefinitionDepArtifact);
+ topologyTemplate.getInstDeploymentArtifacts().put(ci.getUniqueId(), insDepArtifact);
+ }
+ }
+ }
+ }
+
+ private static void setComponentInstancesAttributesToTopologyTemplate(Component component, TopologyTemplate topologyTemplate) {
+
+ if (component.getComponentInstancesAttributes() != null) {
+ topologyTemplate.setInstAttributes(new HashMap<>());
+ MapAttributesDataDefinition attributesMap;
+ for (Entry<String, List<ComponentInstanceAttribute>> entry : component.getComponentInstancesAttributes().entrySet()) {
+ attributesMap = new MapAttributesDataDefinition();
+
+ attributesMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new AttributeDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e)));
+
+ topologyTemplate.getInstAttributes().put(entry.getKey(), attributesMap);
+ }
+ }
+ }
+
+ public static ComponentMetadataData convertToComponentMetadata(GraphVertex vertex) {
+ ComponentMetadataData metadata = null;
+ switch (vertex.getType()) {
+ case SERVICE:
+ metadata = new ServiceMetadataData(vertex.getMetadataJson());
+ break;
+ case RESOURCE:
+ metadata = new ResourceMetadataData(vertex.getMetadataJson());
+ break;
+ case PRODUCT:
+ metadata = new ProductMetadataData(vertex.getMetadataJson());
+ break;
+ default:
+ break;
+ }
+ if (metadata != null) {
+ metadata.getMetadataDataDefinition().setUniqueId(vertex.getUniqueId());
+ metadata.getMetadataDataDefinition().setLastUpdateDate((Long) vertex.getJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE));
+ metadata.getMetadataDataDefinition().setUUID((String) vertex.getJsonMetadataField(JsonPresentationFields.UUID));
+ metadata.getMetadataDataDefinition().setState((String) vertex.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE));
+ }
+ return metadata;
+ }
+
+ public static List<GroupDefinition> convertToGroupDefinitions(Map<String, GroupDataDefinition> groups) {
+
+ List<GroupDefinition> groupDefinitions = null;
+ if (MapUtils.isNotEmpty(groups)) {
+ groupDefinitions = groups.values().stream().map(g -> new GroupDefinition(g)).collect(Collectors.toList());
+ }
+ /*
+ * if (CollectionUtils.isNotEmpty(groupDefinitions) && MapUtils.isNotEmpty(groupsProperties)) { for (GroupDefinition groupDefinition : groupDefinitions) { if (groupsProperties.containsKey(groupDefinition.getName())) { Map<String,
+ * PropertyDataDefinition> properties = groupsProperties.get(groupDefinition.getName()).getMapToscaDataDefinition(); if (MapUtils.isNotEmpty(properties)) { groupDefinition.setProperties(properties.values().stream().map(p -> new
+ * GroupProperty(p)).collect(Collectors.toList())); } } } }
+ */
+ return groupDefinitions;
+ }
+
+}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IAdditionalInformationOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IAdditionalInformationOperation.java
index 71167c395f..eb6492fa84 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IAdditionalInformationOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IAdditionalInformationOperation.java
@@ -23,8 +23,8 @@ package org.openecomp.sdc.be.model.operations.api;
import java.util.List;
import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterInfo;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.model.AdditionalInfoParameterInfo;
import org.openecomp.sdc.be.model.AdditionalInformationDefinition;
import org.openecomp.sdc.be.resources.data.AdditionalInfoParameterData;
@@ -35,60 +35,42 @@ import fj.data.Either;
public interface IAdditionalInformationOperation {
- public Either<AdditionalInformationDefinition, TitanOperationStatus> addAdditionalInformationParameter(
- NodeTypeEnum nodeType, String resourceId, String key, String value);
+ public Either<AdditionalInformationDefinition, TitanOperationStatus> addAdditionalInformationParameter(NodeTypeEnum nodeType, String resourceId, String key, String value);
- public Either<AdditionalInformationDefinition, TitanOperationStatus> updateAdditionalInformationParameter(
- NodeTypeEnum nodeType, String resourceId, String origKey, String key, String value);
+ public Either<AdditionalInformationDefinition, TitanOperationStatus> updateAdditionalInformationParameter(NodeTypeEnum nodeType, String resourceId, String origKey, String key, String value);
- public Either<AdditionalInformationDefinition, TitanOperationStatus> deleteAdditionalInformationParameter(
- NodeTypeEnum nodeType, String resourceId, String key);
+ public Either<AdditionalInformationDefinition, TitanOperationStatus> deleteAdditionalInformationParameter(NodeTypeEnum nodeType, String resourceId, String key);
- public Either<AdditionalInfoParameterData, TitanOperationStatus> addAdditionalInformationNode(NodeTypeEnum nodeType,
- String resourceUniqueId);
+ public Either<AdditionalInfoParameterData, TitanOperationStatus> addAdditionalInformationNode(NodeTypeEnum nodeType, String resourceUniqueId);
- public Either<AdditionalInformationDefinition, TitanOperationStatus> addAdditionalInformationNode(
- NodeTypeEnum nodeType, String componentId, AdditionalInformationDefinition parameters);
+ public Either<AdditionalInformationDefinition, TitanOperationStatus> addAdditionalInformationNode(NodeTypeEnum nodeType, String componentId, AdditionalInformationDefinition parameters);
- public TitanOperationStatus findResourceAllAdditionalInformationRecursively(String uniqueId,
- List<AdditionalInformationDefinition> properties);
+ public TitanOperationStatus findResourceAllAdditionalInformationRecursively(String uniqueId, List<AdditionalInformationDefinition> properties);
- public TitanOperationStatus findServiceAllAdditionalInformationRecursively(String uniqueId,
- List<AdditionalInformationDefinition> properties);
+ public TitanOperationStatus findServiceAllAdditionalInformationRecursively(String uniqueId, List<AdditionalInformationDefinition> properties);
- public Either<AdditionalInformationDefinition, StorageOperationStatus> createAdditionalInformationParameter(
- NodeTypeEnum nodeType, String resourceId, String key, String value, boolean inTransaction);
+ public Either<AdditionalInformationDefinition, StorageOperationStatus> createAdditionalInformationParameter(NodeTypeEnum nodeType, String resourceId, String key, String value, boolean inTransaction);
- public Either<AdditionalInformationDefinition, StorageOperationStatus> updateAdditionalInformationParameter(
- NodeTypeEnum nodeType, String resourceId, String id, String key, String value, boolean inTransaction);
+ public Either<AdditionalInformationDefinition, StorageOperationStatus> updateAdditionalInformationParameter(NodeTypeEnum nodeType, String resourceId, String id, String key, String value, boolean inTransaction);
- public Either<AdditionalInformationDefinition, StorageOperationStatus> deleteAdditionalInformationParameter(
- NodeTypeEnum nodeType, String resourceId, String id, boolean inTransaction);
+ public Either<AdditionalInformationDefinition, StorageOperationStatus> deleteAdditionalInformationParameter(NodeTypeEnum nodeType, String resourceId, String id, boolean inTransaction);
- public Either<Integer, StorageOperationStatus> getNumberOfAdditionalInformationParameters(NodeTypeEnum nodeType,
- String resourceId, boolean inTransaction);
+ public Either<Integer, StorageOperationStatus> getNumberOfAdditionalInformationParameters(NodeTypeEnum nodeType, String resourceId, boolean inTransaction);
public Either<Integer, TitanOperationStatus> getNumberOfParameters(NodeTypeEnum nodeType, String resourceId);
- public Either<AdditionalInfoParameterInfo, TitanOperationStatus> getAdditionalInformationParameter(
- NodeTypeEnum nodeType, String resourceId, String id);
+ public Either<AdditionalInfoParameterInfo, TitanOperationStatus> getAdditionalInformationParameter(NodeTypeEnum nodeType, String resourceId, String id);
- public Either<AdditionalInfoParameterInfo, StorageOperationStatus> getAdditionalInformationParameter(
- NodeTypeEnum nodeType, String resourceId, String id, boolean inTransaction);
+ public Either<AdditionalInfoParameterInfo, StorageOperationStatus> getAdditionalInformationParameter(NodeTypeEnum nodeType, String resourceId, String id, boolean inTransaction);
- public Either<AdditionalInformationDefinition, TitanOperationStatus> getAllAdditionalInformationParameters(
- NodeTypeEnum nodeType, String resourceId, boolean ignoreVerification);
+ public Either<AdditionalInformationDefinition, TitanOperationStatus> getAllAdditionalInformationParameters(NodeTypeEnum nodeType, String resourceId, boolean ignoreVerification);
- public Either<AdditionalInformationDefinition, StorageOperationStatus> getAllAdditionalInformationParameters(
- NodeTypeEnum nodeType, String resourceId, boolean ignoreVerification, boolean inTransaction);
+ public Either<AdditionalInformationDefinition, StorageOperationStatus> getAllAdditionalInformationParameters(NodeTypeEnum nodeType, String resourceId, boolean ignoreVerification, boolean inTransaction);
- public Either<AdditionalInformationDefinition, StorageOperationStatus> deleteAllAdditionalInformationParameters(
- NodeTypeEnum nodeType, String resourceId, boolean inTransaction);
+ public Either<AdditionalInformationDefinition, StorageOperationStatus> deleteAllAdditionalInformationParameters(NodeTypeEnum nodeType, String resourceId, boolean inTransaction);
- public Either<TitanVertex, TitanOperationStatus> addAdditionalInformationNode(NodeTypeEnum nodeType,
- String componentId, TitanVertex matadatVertex);
+ public Either<TitanVertex, TitanOperationStatus> addAdditionalInformationNode(NodeTypeEnum nodeType, String componentId, TitanVertex matadatVertex);
- public TitanOperationStatus addAdditionalInformationNode(NodeTypeEnum nodeType, String componentId,
- AdditionalInformationDefinition parameters, TitanVertex metadataVertex);
+ public TitanOperationStatus addAdditionalInformationNode(NodeTypeEnum nodeType, String componentId, AdditionalInformationDefinition parameters, TitanVertex metadataVertex);
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IArtifactOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IArtifactOperation.java
index 873d05e1ed..5e8a2eb0d5 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IArtifactOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IArtifactOperation.java
@@ -23,12 +23,12 @@ package org.openecomp.sdc.be.model.operations.api;
import java.util.Map;
import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
+import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.model.ArtifactDefinition;
import org.openecomp.sdc.be.resources.data.ArtifactData;
-import com.thinkaurelius.titan.core.TitanTransaction;
import com.thinkaurelius.titan.core.TitanVertex;
import fj.data.Either;
@@ -51,7 +51,7 @@ public interface IArtifactOperation {
public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType, boolean inTransaction, String groupType);
- Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv, ArtifactDefinition artifactHeat, String parentId, NodeTypeEnum parentType, boolean inTransaction);
+ Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv, ArtifactDefinition artifactHeat, String parentId, NodeTypeEnum parentType, boolean failIfExist);
public void updateUUID(ArtifactDataDefinition artifactData, String oldChecksum, String oldVesrion);
@@ -61,10 +61,20 @@ public interface IArtifactOperation {
public Either<ArtifactData, StorageOperationStatus> updateToscaArtifactNameOnGraph(ArtifactDefinition artifactInfo, String artifactId, NodeTypeEnum type, String id);
+
public StorageOperationStatus addArifactToComponent(ArtifactDefinition artifactInfo, String parentId, NodeTypeEnum type, boolean failIfExist, TitanVertex parentVertex);
public Either<ArtifactData, StorageOperationStatus> getLatestArtifactDataByArtifactUUID(String artifactUUID, boolean inTransaction);
StorageOperationStatus addArifactToComponent(TitanVertex artifactInfo, TitanVertex parentVertex, String label);
+ public Either<ArtifactData, TitanOperationStatus> removeArtifactOnGraph(String id, String artifactId, NodeTypeEnum type, boolean deleteMandatoryArtifact);
+
+ public Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvPlaceholder(ArtifactDefinition artifactInfo, boolean inTransaction);
+
+ public Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvArtifact( String id, ArtifactDefinition artifactEnvInfo, String oldArtifactId, String newArtifactId, NodeTypeEnum type, boolean inTransaction);
+
+ public Either<ArtifactDefinition, StorageOperationStatus> getHeatEnvByGeneratedFromId(String generatedFromId);
+
+
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICapabilityInstanceOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICapabilityInstanceOperation.java
index e50b658121..f8e8c80f12 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICapabilityInstanceOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICapabilityInstanceOperation.java
@@ -37,16 +37,14 @@ import com.thinkaurelius.titan.core.TitanVertex;
import fj.data.Either;
/**
- * public interface ICapabilityInstanceOperation provides methods for CRUD
- * operations for CapabilityInstance on component instance level
+ * public interface ICapabilityInstanceOperation provides methods for CRUD operations for CapabilityInstance on component instance level
*
* @author ns019t
*
*/
public interface ICapabilityInstanceOperation {
/**
- * create capability instance of capability with property values for
- * resource instance
+ * create capability instance of capability with property values for resource instance
*
* @param resourceInstanceId
* @param capabilityId
@@ -55,8 +53,7 @@ public interface ICapabilityInstanceOperation {
* @param capabilityName
* @return
*/
- public Either<Map<CapabilityInstData, List<PropertyValueData>>, TitanOperationStatus> createCapabilityInstanceOfCapabilityWithPropertyValuesForResourceInstance(
- String resourceInstanceId, String capabilityId, String capabilityName,
+ public Either<Map<CapabilityInstData, List<PropertyValueData>>, TitanOperationStatus> createCapabilityInstanceOfCapabilityWithPropertyValuesForResourceInstance(String resourceInstanceId, String capabilityId, String capabilityName,
List<ComponentInstanceProperty> propertyValues, boolean validateCapabilityInstExistance);
/**
@@ -68,8 +65,7 @@ public interface ICapabilityInstanceOperation {
* @param validateCapabilityInstExistence
* @return
*/
- public TitanOperationStatus createCapabilityInstanceOfCapabilityWithPropertyValuesForResourceInstance(
- TitanVertex resourceInstanceVertex, String resourceInstanceId, String capabilityId, String capabilityName,
+ public TitanOperationStatus createCapabilityInstanceOfCapabilityWithPropertyValuesForResourceInstance(TitanVertex resourceInstanceVertex, String resourceInstanceId, String capabilityId, String capabilityName,
List<ComponentInstanceProperty> propertyValues, boolean validateCapabilityInstExistence);
/**
@@ -79,8 +75,7 @@ public interface ICapabilityInstanceOperation {
* @param capabilityId
* @return
*/
- public Either<Boolean, TitanOperationStatus> validateCapabilityInstExistence(String resourceInstanceId,
- String capabilityId);
+ public Either<Boolean, TitanOperationStatus> validateCapabilityInstExistence(String resourceInstanceId, String capabilityId);
/**
* delete capability instance from resource instance
@@ -89,20 +84,16 @@ public interface ICapabilityInstanceOperation {
* @param capabilityInstanceId
* @return
*/
- public Either<CapabilityInstData, TitanOperationStatus> deleteCapabilityInstanceFromResourceInstance(
- String resourceInstanceId, String capabilityInstanceId);
+ public Either<CapabilityInstData, TitanOperationStatus> deleteCapabilityInstanceFromResourceInstance(String resourceInstanceId, String capabilityInstanceId);
/**
- * get all capability instances for resource instance returns all Capability
- * Instances related to Resource Instance as List<CapabilityInstData> or
- * TitanOperationStatus if error occurs or if Resource Instance have no any
- * related Capability Instance
+ * get all capability instances for resource instance returns all Capability Instances related to Resource Instance as List<CapabilityInstData> or TitanOperationStatus if error occurs or if Resource Instance have no any related Capability
+ * Instance
*
* @param resourceInstanceId
* @return Either<List<CapabilityInstData>, TitanOperationStatus>
*/
- public Either<List<ImmutablePair<CapabilityInstData, GraphEdge>>, TitanOperationStatus> getAllCapabilityInstancesOfResourceInstance(
- String resourceInstanceId);
+ public Either<List<ImmutablePair<CapabilityInstData, GraphEdge>>, TitanOperationStatus> getAllCapabilityInstancesOfResourceInstance(String resourceInstanceId);
/**
* get capability instance of capability for resource instance
@@ -111,8 +102,7 @@ public interface ICapabilityInstanceOperation {
* @param capabilityId
* @return
*/
- public Either<CapabilityInstData, TitanOperationStatus> getCapabilityInstanceOfCapabilityOfResourceInstance(
- String resourceInstanceId, String capabilityId);
+ public Either<CapabilityInstData, TitanOperationStatus> getCapabilityInstanceOfCapabilityOfResourceInstance(String resourceInstanceId, String capabilityId);
/**
* update capability property values
@@ -123,8 +113,7 @@ public interface ICapabilityInstanceOperation {
* @param capabilityId
* @return
*/
- public Either<List<PropertyValueData>, TitanOperationStatus> updateCapabilityPropertyValues(
- String resourceInstanceId, String capabilityId, List<ComponentInstanceProperty> propertyValues);
+ public Either<List<PropertyValueData>, TitanOperationStatus> updateCapabilityPropertyValues(String resourceInstanceId, String capabilityId, List<ComponentInstanceProperty> propertyValues);
/**
* clone and associate capability instance with property values
@@ -134,10 +123,8 @@ public interface ICapabilityInstanceOperation {
* @param capabilityInstPair
* @return
*/
- public Either<ImmutablePair<CapabilityInstData, List<PropertyValueData>>, TitanOperationStatus> cloneAssociateCapabilityInstanceWithPropertyValues(
- ComponentInstanceData createdComponentInstance, CapabilityDefinition capability,
+ public Either<ImmutablePair<CapabilityInstData, List<PropertyValueData>>, TitanOperationStatus> cloneAssociateCapabilityInstanceWithPropertyValues(ComponentInstanceData createdComponentInstance, CapabilityDefinition capability,
ImmutablePair<CapabilityInstData, GraphEdge> capabilityInstPair);
- Either<Boolean, TitanOperationStatus> validateCapabilityInstExistence(TitanVertex instanceVertex,
- String resourceInstanceId, String capabilityId);
+ Either<Boolean, TitanOperationStatus> validateCapabilityInstExistence(TitanVertex instanceVertex, String resourceInstanceId, String capabilityId);
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICapabilityOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICapabilityOperation.java
index 3b692b9607..b3be2bd6ee 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICapabilityOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICapabilityOperation.java
@@ -29,6 +29,7 @@ import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
import org.openecomp.sdc.be.model.CapabilityDefinition;
import org.openecomp.sdc.be.model.PropertyDefinition;
import org.openecomp.sdc.be.resources.data.CapabilityData;
+import org.openecomp.sdc.be.resources.data.CapabilityTypeData;
import org.openecomp.sdc.be.resources.data.PropertyData;
import com.thinkaurelius.titan.core.TitanVertex;
@@ -37,11 +38,9 @@ import fj.data.Either;
public interface ICapabilityOperation {
- public Either<CapabilityDefinition, StorageOperationStatus> addCapability(String resourceId, String capabilityName,
- CapabilityDefinition capabilityDefinition);
+ public Either<CapabilityDefinition, StorageOperationStatus> addCapability(String resourceId, String capabilityName, CapabilityDefinition capabilityDefinition);
- public Either<CapabilityDefinition, StorageOperationStatus> addCapability(String resourceId, String capabilityName,
- CapabilityDefinition capabilityDefinition, boolean inTransaction);
+ public Either<CapabilityDefinition, StorageOperationStatus> addCapability(String resourceId, String capabilityName, CapabilityDefinition capabilityDefinition, boolean inTransaction);
/**
* @param uniqueId
@@ -53,27 +52,22 @@ public interface ICapabilityOperation {
public Either<CapabilityDefinition, StorageOperationStatus> getCapability(String capabilityName, String resourceId);
- public Either<CapabilityDefinition, StorageOperationStatus> getCapability(String capabilityName, String resourceId,
- boolean inTransaction);
+ public Either<CapabilityDefinition, StorageOperationStatus> getCapability(String capabilityName, String resourceId, boolean inTransaction);
- public Either<List<ImmutablePair<CapabilityData, GraphEdge>>, TitanOperationStatus> getAllCapabilitiesPairs(
- String resourceId);
+ public Either<List<ImmutablePair<CapabilityData, GraphEdge>>, TitanOperationStatus> getAllCapabilitiesPairs(String resourceId);
- public Either<Map<String, CapabilityDefinition>, StorageOperationStatus> deleteAllCapabilities(String resourceId,
- boolean inTransaction);
+ public Either<Map<String, CapabilityDefinition>, StorageOperationStatus> deleteAllCapabilities(String resourceId, boolean inTransaction);
- public Either<CapabilityDefinition, TitanOperationStatus> getCapabilityByCapabilityData(
- CapabilityData capabilityData);
+ public Either<CapabilityDefinition, TitanOperationStatus> getCapabilityByCapabilityData(CapabilityData capabilityData);
public TitanOperationStatus getCapabilitySourcesList(String resourceId, List<String> derivedFromList);
- public Either<Map<String, PropertyData>, StorageOperationStatus> updatePropertiesOfCapability(String uniqueId,
- String capabilityType, List<PropertyDefinition> newProperties);
+ public Either<Map<String, PropertyData>, StorageOperationStatus> updatePropertiesOfCapability(String uniqueId, String capabilityType, List<PropertyDefinition> newProperties);
- public Either<Map<String, PropertyData>, StorageOperationStatus> updatePropertiesOfCapability(String uniqueId,
- String capabilityType, List<PropertyDefinition> newProperties, boolean inTransaction);
+ public Either<Map<String, PropertyData>, StorageOperationStatus> updatePropertiesOfCapability(String uniqueId, String capabilityType, List<PropertyDefinition> newProperties, boolean inTransaction);
- StorageOperationStatus addCapability(TitanVertex metadataVertex, String resourceId, String capabilityName,
- CapabilityDefinition capabilityDefinition, boolean inTransaction);
+ StorageOperationStatus addCapability(TitanVertex metadataVertex, String resourceId, String capabilityName, CapabilityDefinition capabilityDefinition, boolean inTransaction);
+
+ Either<CapabilityTypeData, TitanOperationStatus> getCapabilityTypeOfCapability(String uniqueId);
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICapabilityTypeOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICapabilityTypeOperation.java
index 6f0b5b8d13..fa06b468db 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICapabilityTypeOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICapabilityTypeOperation.java
@@ -30,11 +30,9 @@ public interface ICapabilityTypeOperation {
* @param capabilityTypeDefinition
* @return
*/
- public Either<CapabilityTypeDefinition, StorageOperationStatus> addCapabilityType(
- CapabilityTypeDefinition capabilityTypeDefinition);
+ public Either<CapabilityTypeDefinition, StorageOperationStatus> addCapabilityType(CapabilityTypeDefinition capabilityTypeDefinition);
- public Either<CapabilityTypeDefinition, StorageOperationStatus> addCapabilityType(
- CapabilityTypeDefinition capabilityTypeDefinition, boolean inTransaction);
+ public Either<CapabilityTypeDefinition, StorageOperationStatus> addCapabilityType(CapabilityTypeDefinition capabilityTypeDefinition, boolean inTransaction);
/**
* @param uniqueId
@@ -42,6 +40,5 @@ public interface ICapabilityTypeOperation {
*/
public Either<CapabilityTypeDefinition, StorageOperationStatus> getCapabilityType(String uniqueId);
- public Either<CapabilityTypeDefinition, StorageOperationStatus> getCapabilityType(String uniqueId,
- boolean inTransaction);
+ public Either<CapabilityTypeDefinition, StorageOperationStatus> getCapabilityType(String uniqueId, boolean inTransaction);
}
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 e51e077906..28e70ad127 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
@@ -24,6 +24,7 @@ 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;
@@ -34,8 +35,12 @@ import org.openecomp.sdc.be.model.ComponentInstanceInput;
import org.openecomp.sdc.be.model.ComponentInstanceProperty;
import org.openecomp.sdc.be.model.RequirementAndRelationshipPair;
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;
@@ -52,9 +57,8 @@ public interface IComponentInstanceOperation {
* @param inTransaction
* @return
*/
- public Either<ComponentInstance, StorageOperationStatus> createComponentInstance(String containerComponentId,
- NodeTypeEnum containerNodeType, String instanceNumber, ComponentInstance componentInstance,
- NodeTypeEnum instNodeType, boolean inTransaction);
+ public Either<ComponentInstance, StorageOperationStatus> createComponentInstance(String containerComponentId, NodeTypeEnum containerNodeType, String instanceNumber, ComponentInstance componentInstance, NodeTypeEnum instNodeType,
+ boolean inTransaction);
/**
* add resource instance to service with internal transaction
@@ -64,9 +68,7 @@ public interface IComponentInstanceOperation {
* @param componentInstance
* @return
*/
- public Either<ComponentInstance, StorageOperationStatus> createComponentInstance(String containerComponentId,
- NodeTypeEnum containerNodeType, String instanceNumber, ComponentInstance componentInstance,
- NodeTypeEnum instNodeType);
+ public Either<ComponentInstance, StorageOperationStatus> createComponentInstance(String containerComponentId, NodeTypeEnum containerNodeType, String instanceNumber, ComponentInstance componentInstance, NodeTypeEnum instNodeType);
/**
* delete resource instance from component
@@ -78,11 +80,9 @@ public interface IComponentInstanceOperation {
* @param inTransaction
* @return
*/
- public Either<ComponentInstance, StorageOperationStatus> deleteComponentInstance(NodeTypeEnum containerNodeType,
- String containerComponentId, String resourceInstUid, boolean inTransaction);
+ public Either<ComponentInstance, StorageOperationStatus> deleteComponentInstance(NodeTypeEnum containerNodeType, String containerComponentId, String resourceInstUid, boolean inTransaction);
- public Either<ComponentInstance, StorageOperationStatus> deleteComponentInstance(NodeTypeEnum containerNodeType,
- String containerComponentId, String resourceInstUid);
+ public Either<ComponentInstance, StorageOperationStatus> deleteComponentInstance(NodeTypeEnum containerNodeType, String containerComponentId, String resourceInstUid);
/**
* associate 2 resource instances for a given requirement
@@ -106,16 +106,13 @@ public interface IComponentInstanceOperation {
// String serviceId, NodeTypeEnum nodeType, String fromResInstanceUid,
// String toResInstanceUid, String requirement, String relationship);
- public Either<RequirementCapabilityRelDef, StorageOperationStatus> associateResourceInstances(String serviceId,
- NodeTypeEnum nodeType, RequirementCapabilityRelDef relation, boolean inTransaction);
+ public Either<RequirementCapabilityRelDef, StorageOperationStatus> associateResourceInstances(String serviceId, NodeTypeEnum nodeType, RequirementCapabilityRelDef relation, boolean inTransaction, boolean isClone);
- public Either<RequirementCapabilityRelDef, StorageOperationStatus> associateResourceInstances(String serviceId,
- NodeTypeEnum nodeType, RequirementCapabilityRelDef relation);
+ public Either<RequirementCapabilityRelDef, StorageOperationStatus> associateResourceInstances(String serviceId, NodeTypeEnum nodeType, RequirementCapabilityRelDef relation);
/**
*
- * dissociate the relation between 2 resource instances for a given
- * requirement
+ * dissociate the relation between 2 resource instances for a given requirement
*
* @param serviceId
* @param fromResInstanceUid
@@ -124,11 +121,9 @@ public interface IComponentInstanceOperation {
* @param inTransaction
* @return
*/
- public Either<RequirementCapabilityRelDef, StorageOperationStatus> dissociateResourceInstances(String serviceId,
- NodeTypeEnum nodeType, RequirementCapabilityRelDef requirementDef, boolean inTransaction);
+ public Either<RequirementCapabilityRelDef, StorageOperationStatus> dissociateResourceInstances(String serviceId, NodeTypeEnum nodeType, RequirementCapabilityRelDef requirementDef, boolean inTransaction);
- public Either<RequirementCapabilityRelDef, StorageOperationStatus> dissociateResourceInstances(String serviceId,
- NodeTypeEnum nodeType, RequirementCapabilityRelDef requirementDef);
+ public Either<RequirementCapabilityRelDef, StorageOperationStatus> dissociateResourceInstances(String serviceId, NodeTypeEnum nodeType, RequirementCapabilityRelDef requirementDef);
/**
* update the properties of a given resource instance
@@ -139,30 +134,31 @@ public interface IComponentInstanceOperation {
* @param inTransaction
* @return
*/
- public Either<ComponentInstance, StorageOperationStatus> updateResourceInstance(String serviceId,
- NodeTypeEnum nodeType, String resourceInstanceName, ComponentInstance resourceInstance,
- boolean inTransaction);
+ public Either<ComponentInstance, StorageOperationStatus> updateResourceInstance(String serviceId, NodeTypeEnum nodeType, String resourceInstanceName, ComponentInstance resourceInstance, boolean inTransaction);
- public Either<ComponentInstance, StorageOperationStatus> updateResourceInstance(String serviceId,
- NodeTypeEnum nodeType, String resourceInstanceName, ComponentInstance resourceInstance);
+ public Either<ComponentInstance, StorageOperationStatus> updateResourceInstance(String serviceId, NodeTypeEnum nodeType, String resourceInstanceName, ComponentInstance resourceInstance);
/**
- * get all resource instances of a given service and the relations between
- * the resource instances
+ * get all resource instances of a given service and the relations between the resource instances
*
* @param serviceId
* @param inTransaction
* @return
*/
- public Either<ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>>, StorageOperationStatus> getAllComponentInstances(
- String componentId, NodeTypeEnum containerNodeType, NodeTypeEnum compInstNodeType, boolean inTransaction);
-
- public Either<List<String>, StorageOperationStatus> getAllComponentInstancesNames(String componentId,
- NodeTypeEnum nodeType, boolean inTransaction);
+ public Either<ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>>, StorageOperationStatus> getAllComponentInstances(String componentId, NodeTypeEnum containerNodeType, NodeTypeEnum compInstNodeType, boolean inTransaction);
- public Either<List<String>, StorageOperationStatus> getAllComponentInstancesNames(String componentId,
- NodeTypeEnum nodeType);
+ public Either<List<String>, StorageOperationStatus> getAllComponentInstancesNames(String componentId, NodeTypeEnum nodeType, boolean inTransaction);
+ public Either<List<String>, StorageOperationStatus> getAllComponentInstancesNames(String componentId, NodeTypeEnum nodeType);
+
+ /**
+ * get all component instance properties and values from graph
+ * @param resourceInstance
+ * @return
+ */
+ public Either<List<ComponentInstanceProperty>, StorageOperationStatus> getComponentInstancesPropertiesAndValuesFromGraph(
+ ComponentInstance resourceInstance);
+
/**
* get resource instance from id
*
@@ -171,54 +167,38 @@ public interface IComponentInstanceOperation {
*/
public Either<ComponentInstance, StorageOperationStatus> getResourceInstanceById(String resourceId);
- public Either<List<ComponentInstance>, StorageOperationStatus> deleteAllComponentInstances(String serviceId,
- NodeTypeEnum nodeType, boolean inTransaction);
+ public Either<List<ComponentInstance>, StorageOperationStatus> deleteAllComponentInstances(String serviceId, NodeTypeEnum nodeType, boolean inTransaction);
- public Either<List<ComponentInstance>, StorageOperationStatus> deleteAllComponentInstances(String serviceId,
- NodeTypeEnum nodeType);
+ public Either<List<ComponentInstance>, StorageOperationStatus> deleteAllComponentInstances(String serviceId, NodeTypeEnum nodeType);
- public Either<Integer, StorageOperationStatus> increaseAndGetResourceInstanceSpecificCounter(
- String resourceInstanceId, GraphPropertiesDictionary counterType, boolean inTransaction);
+ public Either<Integer, StorageOperationStatus> increaseAndGetResourceInstanceSpecificCounter(String resourceInstanceId, GraphPropertiesDictionary counterType, boolean inTransaction);
public String createComponentInstLogicalName(String instanceNumber, String componentInstanceName);
- public Either<Boolean, StorageOperationStatus> isComponentInstanceNameExist(String parentComponentId,
- NodeTypeEnum parentNodeType, String compInstId, String componentInstName);
+ public Either<Boolean, StorageOperationStatus> isComponentInstanceNameExist(String parentComponentId, NodeTypeEnum parentNodeType, String compInstId, String componentInstName);
- public Either<Boolean, StorageOperationStatus> validateParent(String parentId, String uniqId,
- boolean inTransaction);
+ public Either<Boolean, StorageOperationStatus> validateParent(String parentId, String uniqId, boolean inTransaction);
- public Either<ComponentInstance, StorageOperationStatus> getFullComponentInstance(
- ComponentInstance componentInstance, NodeTypeEnum compInstNodeType);
+ public Either<ComponentInstance, StorageOperationStatus> getFullComponentInstance(ComponentInstance componentInstance, NodeTypeEnum compInstNodeType);
- public Either<Boolean, StorageOperationStatus> isAvailableRequirement(ComponentInstance fromResInstance,
- RequirementAndRelationshipPair relationPair);
+ public Either<Boolean, StorageOperationStatus> isAvailableRequirement(ComponentInstance fromResInstance, RequirementAndRelationshipPair relationPair);
- public Either<Boolean, StorageOperationStatus> isAvailableCapabilty(ComponentInstance toResInstance,
- RequirementAndRelationshipPair relationPair);
+ public Either<Boolean, StorageOperationStatus> isAvailableCapabilty(ComponentInstance toResInstance, RequirementAndRelationshipPair relationPair);
- public Either<ComponentInstanceProperty, StorageOperationStatus> addPropertyValueToResourceInstance(
- ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId, Integer index,
- boolean inTransaction);
+ public Either<ComponentInstanceProperty, StorageOperationStatus> addPropertyValueToResourceInstance(ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId, Integer index, boolean inTransaction);
- public Either<ComponentInstanceProperty, StorageOperationStatus> addPropertyValueToResourceInstance(
- ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId, boolean isvalidate,
- Integer index, boolean inTransaction);
+ public Either<ComponentInstanceProperty, StorageOperationStatus> addPropertyValueToResourceInstance(ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId, boolean isvalidate, Integer index, boolean inTransaction);
/**
* Adds Attribute to resource instance
*
* @param resourceInstanceAttribute
- * * @param resourceInstanceId * @param index * @param
- * inTransaction
+ * * @param resourceInstanceId * @param index * @param inTransaction
* @return
**/
- public Either<ComponentInstanceAttribute, StorageOperationStatus> addAttributeValueToResourceInstance(
- ComponentInstanceAttribute resourceInstanceAttribute, String resourceInstanceId, Integer index,
- boolean inTransaction);
+ public Either<ComponentInstanceAttribute, StorageOperationStatus> addAttributeValueToResourceInstance(ComponentInstanceAttribute resourceInstanceAttribute, String resourceInstanceId, Integer index, boolean inTransaction);
- public Either<ComponentInstanceProperty, StorageOperationStatus> updatePropertyValueInResourceInstance(
- ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId, boolean inTransaction);
+ public Either<ComponentInstanceProperty, StorageOperationStatus> updatePropertyValueInResourceInstance(ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId, boolean inTransaction);
/**
* Updates Attribute on resource instance
@@ -228,19 +208,32 @@ public interface IComponentInstanceOperation {
* @param inTransaction
* @return
*/
- public Either<ComponentInstanceAttribute, StorageOperationStatus> updateAttributeValueInResourceInstance(
- ComponentInstanceAttribute attribute, String resourceInstanceId, boolean inTransaction);
+ public Either<ComponentInstanceAttribute, StorageOperationStatus> updateAttributeValueInResourceInstance(ComponentInstanceAttribute attribute, String resourceInstanceId, boolean inTransaction);
- public Either<AttributeValueData, TitanOperationStatus> createOrUpdateAttributeOfResourceInstance(
- ComponentInstanceAttribute attributeInstanceProperty, String resourceInstanceId);
+ public Either<AttributeValueData, TitanOperationStatus> createOrUpdateAttributeOfResourceInstance(ComponentInstanceAttribute attributeInstanceProperty, String resourceInstanceId);
+
+ public Either<ComponentInstanceInput, StorageOperationStatus> addInputValueToResourceInstance(ComponentInstanceInput input, String resourceInstanceId, Integer innerElement, boolean b);
+
+ public Either<ComponentInstanceInput, StorageOperationStatus> updateInputValueInResourceInstance(ComponentInstanceInput input, String resourceInstanceId, boolean b);
+
+ public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> fetchCIEnvArtifacts(String componentInstanceId);
+
+ public StorageOperationStatus updateCustomizationUUID(String componentInstanceId);
+ /**
+ * updates componentInstance modificationTime on graph node
+ * @param componentInstance
+ * @param componentInstanceType
+ * @param modificationTime
+ * @param inTransaction
+ * @return
+ */
+ public Either<ComponentInstanceData, StorageOperationStatus> updateComponentInstanceModificationTimeAndCustomizationUuidOnGraph(ComponentInstance componentInstance, NodeTypeEnum componentInstanceType, Long modificationTime, boolean inTransaction);
- public Either<ComponentInstanceInput, StorageOperationStatus> addInputValueToResourceInstance(
- ComponentInstanceInput input, String resourceInstanceId, Integer innerElement, boolean b);
+ Either<List<ImmutablePair<CapabilityData, GraphEdge>>, TitanOperationStatus> getCapabilities(ComponentInstance compInstance, NodeTypeEnum nodeTypeEnum);
- public Either<ComponentInstanceInput, StorageOperationStatus> updateInputValueInResourceInstance(
- ComponentInstanceInput input, String resourceInstanceId, boolean b);
+ Either<List<ImmutablePair<RequirementData, GraphEdge>>, TitanOperationStatus> getRequirements(ComponentInstance compInstance, NodeTypeEnum nodeTypeEnum);
- public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> fetchCIEnvArtifacts(
- String componentInstanceId);
+ Either<List<ImmutablePair<CapabilityData, GraphEdge>>, TitanOperationStatus> getFulfilledCapabilities(ComponentInstance compInstance, NodeTypeEnum nodeTypeEnum);
+ Either<List<ImmutablePair<RequirementData, GraphEdge>>, TitanOperationStatus> getFulfilledRequirements(ComponentInstance compInstance, NodeTypeEnum nodeTypeEnum);
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IComponentOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IComponentOperation.java
index e7eff13a9d..3eef59fa69 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IComponentOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IComponentOperation.java
@@ -28,23 +28,23 @@ import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.model.ArtifactDefinition;
import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentParametersView;
import fj.data.Either;
public interface IComponentOperation {
public <T extends Component> Either<T, StorageOperationStatus> getComponent(String id, Class<T> clazz);
- public Either<List<ArtifactDefinition>, StorageOperationStatus> getComponentArtifactsForDelete(String parentId,
- NodeTypeEnum parentType, boolean inTransacton);
+ public Either<List<ArtifactDefinition>, StorageOperationStatus> getComponentArtifactsForDelete(String parentId, NodeTypeEnum parentType, boolean inTransacton);
public <T> Either<T, StorageOperationStatus> getLightComponent(String id, boolean inTransaction);
public <T> Either<T, StorageOperationStatus> getComponent(String id, boolean inTransaction);
+
+ public <T> Either<T, StorageOperationStatus> getComponent(String id, ComponentParametersView componentParametersView, boolean inTransaction);
- public <T> Either<List<T>, StorageOperationStatus> getFilteredComponents(Map<FilterKeyEnum, String> filters,
- boolean inTranscation);
+ public <T> Either<List<T>, StorageOperationStatus> getFilteredComponents(Map<FilterKeyEnum, String> filters, boolean inTranscation);
- public <T extends GraphNode> Either<T, StorageOperationStatus> getComponentByLabelAndId(String uniqueId,
- NodeTypeEnum nodeType, Class<T> clazz);
+ public <T extends GraphNode> Either<T, StorageOperationStatus> getComponentByLabelAndId(String uniqueId, NodeTypeEnum nodeType, Class<T> clazz);
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IConsumerOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IConsumerOperation.java
index 290552b382..ed43b7ce1f 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IConsumerOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IConsumerOperation.java
@@ -32,9 +32,7 @@ public interface IConsumerOperation {
* @param consumerData
* the object we want to store
* @param inTransaction
- * inTransaction is the operation part of a transaction, in case
- * the value is false the action will be committed in the end of
- * the method
+ * inTransaction is the operation part of a transaction, in case the value is false the action will be committed in the end of the method
* @return the updated object returned from the graph
*/
Either<ConsumerData, StorageOperationStatus> updateCredentials(ConsumerData consumerData, boolean inTransaction);
@@ -52,12 +50,9 @@ public interface IConsumerOperation {
* the method deletes the node with the given unique id
*
* @param consumerName
- * the unique id by witch we will look up the credential we want
- * to delete
+ * the unique id by witch we will look up the credential we want to delete
* @param inTransaction
- * inTransaction is the operation part of a transaction, in case
- * the value is false the action will be committed in the end of
- * the method
+ * inTransaction is the operation part of a transaction, in case the value is false the action will be committed in the end of the method
* @return the deleted object returned from the graph
*/
Either<ConsumerData, StorageOperationStatus> deleteCredentials(String consumerName, boolean inTransaction);
@@ -66,28 +61,24 @@ public interface IConsumerOperation {
* the method deletes the node with the given unique id
*
* @param consumerName
- * the unique id by witch we will look up the credential we want
- * to delete
+ * the unique id by witch we will look up the credential we want to delete
* @return the deleted object returned from the graph
*/
Either<ConsumerData, StorageOperationStatus> deleteCredentials(String consumerName);
/**
- * the method creates a new nod in the grape representing the supplied
- * credential object
+ * the method creates a new nod in the grape representing the supplied credential object
*
* @param consumerData
* the object we want to store
* @param inTransaction
- * is the operation part of a transaction, in case the value is
- * false the action will be committed in the end of the method
+ * is the operation part of a transaction, in case the value is false the action will be committed in the end of the method
* @return the newly stored object returned from the graph
*/
Either<ConsumerData, StorageOperationStatus> createCredentials(ConsumerData consumerData, boolean inTransaction);
/**
- * the method creates a new nod in the grape representing the supplied
- * credential object
+ * the method creates a new nod in the grape representing the supplied credential object
*
* @param consumerData
* the object we want to store
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IDataTypeOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IDataTypeOperation.java
index b7f1882b45..9377abbb76 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IDataTypeOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IDataTypeOperation.java
@@ -32,8 +32,7 @@ public interface IDataTypeOperation {
*/
public Either<DataTypeDefinition, StorageOperationStatus> addDataType(DataTypeDefinition dataTypeDefinition);
- public Either<DataTypeDefinition, StorageOperationStatus> addDataType(DataTypeDefinition dataTypeDefinition,
- boolean inTransaction);
+ public Either<DataTypeDefinition, StorageOperationStatus> addDataType(DataTypeDefinition dataTypeDefinition, boolean inTransaction);
/**
* @param name
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IElementOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IElementOperation.java
index a21c194060..0a82be8465 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IElementOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IElementOperation.java
@@ -54,18 +54,15 @@ public interface IElementOperation {
public Either<Integer, ActionStatus> getDefaultHeatTimeout();
- public <T extends GraphNode> Either<CategoryData, StorageOperationStatus> getCategoryData(String name,
- NodeTypeEnum type, Class<T> clazz);
+ public <T extends GraphNode> Either<CategoryData, StorageOperationStatus> getCategoryData(String name, NodeTypeEnum type, Class<T> clazz);
- public <T extends GraphNode> Either<org.openecomp.sdc.be.resources.data.category.CategoryData, StorageOperationStatus> getNewCategoryData(
- String name, NodeTypeEnum type, Class<T> clazz);
+ public <T extends GraphNode> Either<org.openecomp.sdc.be.resources.data.category.CategoryData, StorageOperationStatus> getNewCategoryData(String name, NodeTypeEnum type, Class<T> clazz);
public Either<Map<String, String>, ActionStatus> getResourceTypesMap();
Either<CategoryDefinition, ActionStatus> createCategory(CategoryDefinition category, NodeTypeEnum nodeType);
- Either<CategoryDefinition, ActionStatus> createCategory(CategoryDefinition category, NodeTypeEnum nodeType,
- boolean inTransaction);
+ Either<CategoryDefinition, ActionStatus> createCategory(CategoryDefinition category, NodeTypeEnum nodeType, boolean inTransaction);
Either<CategoryDefinition, ActionStatus> deleteCategory(NodeTypeEnum nodeType, String categoryId);
@@ -73,32 +70,25 @@ public interface IElementOperation {
Either<Boolean, ActionStatus> isCategoryUniqueForType(NodeTypeEnum nodeType, String normalizedName);
- Either<SubCategoryDefinition, ActionStatus> createSubCategory(String categoryId, SubCategoryDefinition subCategory,
- NodeTypeEnum nodeType);
+ Either<SubCategoryDefinition, ActionStatus> createSubCategory(String categoryId, SubCategoryDefinition subCategory, NodeTypeEnum nodeType);
- Either<SubCategoryDefinition, ActionStatus> createSubCategory(String categoryId, SubCategoryDefinition subCategory,
- NodeTypeEnum nodeType, boolean inTransaction);
+ Either<SubCategoryDefinition, ActionStatus> createSubCategory(String categoryId, SubCategoryDefinition subCategory, NodeTypeEnum nodeType, boolean inTransaction);
Either<List<CategoryDefinition>, ActionStatus> getAllCategories(NodeTypeEnum nodeType, boolean inTransaction);
Either<CategoryDefinition, ActionStatus> getCategory(NodeTypeEnum nodeType, String categoryId);
- Either<SubCategoryDefinition, ActionStatus> getSubCategoryUniqueForType(NodeTypeEnum nodeType,
- String normalizedName);
+ Either<SubCategoryDefinition, ActionStatus> getSubCategoryUniqueForType(NodeTypeEnum nodeType, String normalizedName);
- Either<Boolean, ActionStatus> isSubCategoryUniqueForCategory(NodeTypeEnum nodeType, String subCategoryNormName,
- String parentCategoryId);
+ Either<Boolean, ActionStatus> isSubCategoryUniqueForCategory(NodeTypeEnum nodeType, String subCategoryNormName, String parentCategoryId);
- Either<GroupingDefinition, ActionStatus> createGrouping(String subCategoryId, GroupingDefinition grouping,
- NodeTypeEnum nodeType);
+ Either<GroupingDefinition, ActionStatus> createGrouping(String subCategoryId, GroupingDefinition grouping, NodeTypeEnum nodeType);
Either<GroupingDefinition, ActionStatus> deleteGrouping(NodeTypeEnum nodeType, String groupingId);
Either<SubCategoryDefinition, ActionStatus> getSubCategory(NodeTypeEnum nodeType, String subCategoryId);
- Either<Boolean, ActionStatus> isGroupingUniqueForSubCategory(NodeTypeEnum nodeType, String groupingNormName,
- String parentSubCategoryId);
+ Either<Boolean, ActionStatus> isGroupingUniqueForSubCategory(NodeTypeEnum nodeType, String groupingNormName, String parentSubCategoryId);
- Either<GroupingDefinition, ActionStatus> getGroupingUniqueForType(NodeTypeEnum nodeType,
- String groupingNormalizedName);
+ Either<GroupingDefinition, ActionStatus> getGroupingUniqueForType(NodeTypeEnum nodeType, String groupingNormalizedName);
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGraphLockOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGraphLockOperation.java
index d065ce0b09..29da56205a 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGraphLockOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGraphLockOperation.java
@@ -30,7 +30,6 @@ public interface IGraphLockOperation {
public abstract StorageOperationStatus lockComponentByName(String name, NodeTypeEnum nodeType);
- public abstract StorageOperationStatus unlockComponentByName(String name, String componentId,
- NodeTypeEnum nodeType);
+ public abstract StorageOperationStatus unlockComponentByName(String name, String componentId, NodeTypeEnum nodeType);
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGroupInstanceOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGroupInstanceOperation.java
new file mode 100644
index 0000000000..8fd88f704f
--- /dev/null
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGroupInstanceOperation.java
@@ -0,0 +1,101 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.model.operations.api;
+
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+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.ComponentInstanceProperty;
+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.resources.data.ArtifactData;
+import org.openecomp.sdc.exception.ResponseFormat;
+
+import com.thinkaurelius.titan.core.TitanVertex;
+
+import fj.data.Either;
+
+public interface IGroupInstanceOperation {
+
+ public Either<GroupInstance, StorageOperationStatus> createGroupInstance(String ComponentInstId, GroupInstance groupInstance, boolean isCreateLogicalName);
+
+ public Either<GroupInstance, StorageOperationStatus> createGroupInstance(TitanVertex ciVertex, String componentInstId, GroupInstance groupInstance, boolean isCreateLogicalName);
+
+ public Either<GroupInstance, StorageOperationStatus> deleteGroupInstanceInstance(NodeTypeEnum containerNodeType, String containerComponentId, String groupInstUid);
+
+ public Either<GroupInstance, StorageOperationStatus> updateGroupInstance(String serviceId, NodeTypeEnum nodeType, String resourceInstanceName, ComponentInstance resourceInstance);
+
+ public Either<List<GroupInstance>, StorageOperationStatus> getAllGroupInstances(String componentInstId, NodeTypeEnum compInstNodeType);
+
+ public Either<GroupInstance, TitanOperationStatus> getGroupInstanceById(String groupResourceId);
+
+ public TitanOperationStatus deleteAllGroupInstances(String componentInstId);
+
+ public Either<Integer, StorageOperationStatus> increaseAndGetGroupInstancePropertyCounter(String groupInstanceId);
+
+ public Either<Boolean, StorageOperationStatus> isGroupInstanceNameExist(String parentComponentId, NodeTypeEnum parentNodeType, String compInstId, String componentInstName);
+
+ public Either<ComponentInstance, StorageOperationStatus> getFullGroupInstance(ComponentInstance componentInstance, NodeTypeEnum compInstNodeType);
+
+ public Either<ComponentInstanceProperty, StorageOperationStatus> addPropertyValueToGroupInstance(ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId, Integer index, boolean inTransaction);
+
+ public Either<ComponentInstanceProperty, StorageOperationStatus> addPropertyValueToGroupInstance(ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId, boolean isvalidate, Integer index, boolean inTransaction);
+
+ public Either<ComponentInstanceProperty, StorageOperationStatus> updatePropertyValueInGroupInstance(ComponentInstanceProperty gropuInstanceProperty, String groupInstanceId, boolean inTransaction);
+
+ public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> fetchCIEnvArtifacts(String componentInstanceId);
+
+ public StorageOperationStatus updateCustomizationUUID(String componentInstanceId);
+
+ public String createGroupInstLogicalName(String instanceNumber, String groupInstanceName);
+
+ public Either<GroupInstance, StorageOperationStatus> associateArtifactsToGroupInstance(String groupId, List<String> artifactsId);
+
+ StorageOperationStatus dissociateAndAssociateGroupsInstanceFromArtifact(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact);
+
+ StorageOperationStatus dissociateAndAssociateGroupsInstanceFromArtifactOnGraph(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact);
+ /**
+ * updates group instance property values
+ * @param value
+ * @param newProperties
+ * @return
+ */
+ public Either<GroupInstance, StorageOperationStatus> updateGroupInstancePropertyValues(GroupInstance value, List<GroupInstanceProperty> newProperties);
+ /**
+ * updates group instance property values
+ * @param oldGroupInstance
+ * @param newProperties
+ * @param inTransaction
+ * @return
+ */
+ public Either<GroupInstance, StorageOperationStatus> updateGroupInstancePropertyValues(GroupInstance oldGroupInstance, List<GroupInstanceProperty> newProperties, Boolean inTransaction);
+
+}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGroupOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGroupOperation.java
index 4252ec0622..3295adfe56 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGroupOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGroupOperation.java
@@ -26,6 +26,7 @@ import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation;
import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.model.GroupDefinition;
+import org.openecomp.sdc.be.model.GroupProperty;
import org.openecomp.sdc.be.resources.data.ArtifactData;
import org.openecomp.sdc.be.resources.data.GroupData;
@@ -34,17 +35,13 @@ import fj.data.Either;
public interface IGroupOperation {
// add full group to component
- public Either<GroupData, TitanOperationStatus> addGroupToGraph(NodeTypeEnum nodeTypeEnum, String componentId,
- GroupDefinition groupDefinition);
+ public Either<GroupData, TitanOperationStatus> addGroupToGraph(NodeTypeEnum nodeTypeEnum, String componentId, GroupDefinition groupDefinition);
- public Either<GroupDefinition, StorageOperationStatus> addGroup(NodeTypeEnum nodeTypeEnum, String componentId,
- GroupDefinition groupDefinition);
+ public Either<GroupDefinition, StorageOperationStatus> addGroup(NodeTypeEnum nodeTypeEnum, String componentId, GroupDefinition groupDefinition);
- public Either<GroupDefinition, StorageOperationStatus> addGroup(NodeTypeEnum nodeTypeEnum, String componentId,
- GroupDefinition groupDefinition, boolean inTransaction);
+ public Either<GroupDefinition, StorageOperationStatus> addGroup(NodeTypeEnum nodeTypeEnum, String componentId, GroupDefinition groupDefinition, boolean inTransaction);
- public Either<List<GroupDefinition>, StorageOperationStatus> addGroups(NodeTypeEnum nodeTypeEnum,
- String componentId, List<GroupDefinition> groups, boolean inTransaction);
+ public Either<List<GroupDefinition>, StorageOperationStatus> addGroups(NodeTypeEnum nodeTypeEnum, String componentId, List<GroupDefinition> groups, boolean inTransaction);
// get group
public Either<GroupDefinition, TitanOperationStatus> getGroupFromGraph(String uniqueId);
@@ -54,61 +51,55 @@ public interface IGroupOperation {
public Either<GroupDefinition, StorageOperationStatus> getGroup(String uniqueId, boolean inTransaction);
// get all groups under component
- public Either<List<GroupDefinition>, TitanOperationStatus> getAllGroupsFromGraph(String componentId,
- NodeTypeEnum componentTypeEnum);
+ public Either<List<GroupDefinition>, TitanOperationStatus> getAllGroupsFromGraph(String componentId, NodeTypeEnum componentTypeEnum);
- public Either<List<GroupDefinition>, StorageOperationStatus> getAllGroups(String componentId,
- NodeTypeEnum compTypeEnum, boolean inTransaction);
+ public Either<List<GroupDefinition>, StorageOperationStatus> getAllGroups(String componentId, NodeTypeEnum compTypeEnum, boolean inTransaction);
- public Either<List<GroupDefinition>, StorageOperationStatus> getAllGroups(String componentId,
- NodeTypeEnum compTypeEnum);
+ public Either<List<GroupDefinition>, StorageOperationStatus> getAllGroups(String componentId, NodeTypeEnum compTypeEnum);
// delete all groups under component
- public Either<List<GroupDefinition>, TitanOperationStatus> deleteAllGroupsFromGraph(String componentId,
- NodeTypeEnum compTypeEnum);
+ public Either<List<GroupDefinition>, TitanOperationStatus> deleteAllGroupsFromGraph(String componentId, NodeTypeEnum compTypeEnum);
- public Either<List<GroupDefinition>, StorageOperationStatus> deleteAllGroups(String componentId,
- NodeTypeEnum compTypeEnum, boolean inTransaction);
+ public Either<List<GroupDefinition>, StorageOperationStatus> deleteAllGroups(String componentId, NodeTypeEnum compTypeEnum, boolean inTransaction);
- public Either<List<GroupDefinition>, StorageOperationStatus> deleteAllGroups(String componentId,
- NodeTypeEnum compTypeEnum);
+ public Either<List<GroupDefinition>, StorageOperationStatus> deleteAllGroups(String componentId, NodeTypeEnum compTypeEnum);
// Association
- public Either<List<String>, StorageOperationStatus> getAssociatedGroupsToComponentInstance(
- String componentInstanceId, boolean inTransaction);
+ public Either<List<String>, StorageOperationStatus> getAssociatedGroupsToComponentInstance(String componentInstanceId, boolean inTransaction);
- public Either<List<String>, StorageOperationStatus> getAssociatedGroupsToComponentInstance(
- String componentInstanceId);
+ public Either<List<String>, StorageOperationStatus> getAssociatedGroupsToComponentInstance(String componentInstanceId);
- public Either<List<String>, TitanOperationStatus> getAssociatedGroupsToComponentInstanceFromGraph(
- String componentInstanceId);
+ public Either<List<String>, TitanOperationStatus> getAssociatedGroupsToComponentInstanceFromGraph(String componentInstanceId);
- public StorageOperationStatus associateGroupsToComponentInstance(List<String> groups, String componentInstanceId,
- String compInstName, boolean inTransaction);
+ public StorageOperationStatus associateGroupsToComponentInstance(List<String> groups, String componentInstanceId, String compInstName, boolean inTransaction);
- public StorageOperationStatus associateGroupsToComponentInstance(List<String> groups, String componentInstanceId,
- String compInstName);
+ public StorageOperationStatus associateGroupsToComponentInstance(List<String> groups, String componentInstanceId, String compInstName);
- public Either<List<GraphRelation>, TitanOperationStatus> associateGroupsToComponentInstanceOnGraph(
- List<String> groups, String componentInstanceId, String compInstName);
+ public Either<List<GraphRelation>, TitanOperationStatus> associateGroupsToComponentInstanceOnGraph(List<String> groups, String componentInstanceId, String compInstName);
- public Either<List<GraphRelation>, TitanOperationStatus> dissociateAllGroupsFromArtifactOnGraph(String componentId,
- NodeTypeEnum componentTypeEnum, String artifactId);
+ public Either<List<GraphRelation>, TitanOperationStatus> dissociateAllGroupsFromArtifactOnGraph(String componentId, NodeTypeEnum componentTypeEnum, String artifactId);
- public StorageOperationStatus dissociateAllGroupsFromArtifact(String componentId, NodeTypeEnum componentTypeEnum,
- String artifactId, boolean inTransaction);
+ public StorageOperationStatus dissociateAllGroupsFromArtifact(String componentId, NodeTypeEnum componentTypeEnum, String artifactId, boolean inTransaction);
- public StorageOperationStatus dissociateAllGroupsFromArtifact(String componentId, NodeTypeEnum componentTypeEnum,
- String artifactId);
+ public StorageOperationStatus dissociateAllGroupsFromArtifact(String componentId, NodeTypeEnum componentTypeEnum, String artifactId);
- public TitanOperationStatus dissociateAndAssociateGroupsFromArtifactOnGraph(String componentId,
- NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact);
+ public TitanOperationStatus dissociateAndAssociateGroupsFromArtifactOnGraph(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact);
- public StorageOperationStatus dissociateAndAssociateGroupsFromArtifact(String componentId,
- NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact, boolean inTransaction);
+ public StorageOperationStatus dissociateAndAssociateGroupsFromArtifact(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact, boolean inTransaction);
- public StorageOperationStatus dissociateAndAssociateGroupsFromArtifact(String componentId,
- NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact);
+ public StorageOperationStatus dissociateAndAssociateGroupsFromArtifact(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact);
public boolean isGroupExist(String groupName, boolean inTransaction);
+ /**
+ * Updates Group Metadata (name and properties)
+ * @param groupToUpdateFromUniqueId
+ * @param newName
+ * @param groupToUpdateTo
+ * @param inTransaction
+ * @return
+ */
+ public Either<GroupDefinition, StorageOperationStatus> updateGroupName(String groupToUpdateFromUniqueId,
+ String newName, GroupDefinition groupToUpdateTo, boolean inTransaction);
+
+ public StorageOperationStatus validateAndUpdatePropertyValue(GroupProperty property);
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGroupTypeOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGroupTypeOperation.java
index 2b612579b6..87a0dccfab 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
@@ -34,8 +34,7 @@ public interface IGroupTypeOperation {
*/
public Either<GroupTypeDefinition, StorageOperationStatus> addGroupType(GroupTypeDefinition groupTypeDefinition);
- public Either<GroupTypeDefinition, StorageOperationStatus> addGroupType(GroupTypeDefinition groupTypeDefinition,
- boolean inTransaction);
+ public Either<GroupTypeDefinition, StorageOperationStatus> addGroupType(GroupTypeDefinition groupTypeDefinition, boolean inTransaction);
/**
* @param uniqueId
@@ -47,14 +46,11 @@ public interface IGroupTypeOperation {
public Either<GroupTypeDefinition, StorageOperationStatus> getLatestGroupTypeByType(String name);
- public Either<GroupTypeDefinition, StorageOperationStatus> getLatestGroupTypeByType(String name,
- boolean inTransaction);
+ public Either<GroupTypeDefinition, StorageOperationStatus> getLatestGroupTypeByType(String name, boolean inTransaction);
- public Either<GroupTypeDefinition, StorageOperationStatus> getGroupTypeByTypeAndVersion(String name,
- String version);
+ public Either<GroupTypeDefinition, StorageOperationStatus> getGroupTypeByTypeAndVersion(String name, String version);
- public Either<GroupTypeDefinition, StorageOperationStatus> getGroupTypeByTypeAndVersion(String name, String version,
- boolean inTransaction);
+ public Either<GroupTypeDefinition, StorageOperationStatus> getGroupTypeByTypeAndVersion(String name, String version, boolean inTransaction);
public Either<GroupTypeData, TitanOperationStatus> getLatestGroupTypeByNameFromGraph(String name);
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IInputsOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IInputsOperation.java
index 2f1f2a70cf..386864a8b0 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IInputsOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IInputsOperation.java
@@ -39,43 +39,33 @@ import fj.data.Either;
public interface IInputsOperation {
- Either<String, StorageOperationStatus> deleteInput(String inputId);
+ Either<InputDefinition, StorageOperationStatus> deleteInput(String inputId);
- Either<List<InputDefinition>, TitanOperationStatus> addInputsToGraph(String componentId, NodeTypeEnum nodeType,
- Map<String, InputDefinition> inputs, Map<String, DataTypeDefinition> dataTypes);
+ Either<List<InputDefinition>, TitanOperationStatus> addInputsToGraph(String componentId, NodeTypeEnum nodeType, Map<String, InputDefinition> inputs, Map<String, DataTypeDefinition> dataTypes);
- Either<List<InputDefinition>, StorageOperationStatus> addInputsToComponent(String resourceId, NodeTypeEnum nodeType,
- ComponentInstInputsMap componentInsInputs, Map<String, DataTypeDefinition> dataTypes);
+ Either<List<InputDefinition>, StorageOperationStatus> addInputsToComponent(String resourceId, NodeTypeEnum nodeType, ComponentInstInputsMap componentInsInputs, Map<String, DataTypeDefinition> dataTypes);
TitanOperationStatus findNodeNonInheretedInputs(String uniqueId, List<InputDefinition> inputs);
- Either<List<InputDefinition>, StorageOperationStatus> getInputsOfComponent(String compId, String fromName,
- int amount);
+ Either<List<InputDefinition>, StorageOperationStatus> getInputsOfComponent(String compId, String fromName, int amount);
- Either<List<ComponentInstanceInput>, TitanOperationStatus> getAllInputsOfResourceInstance(
- ComponentInstance compInstance);
+ Either<List<ComponentInstanceInput>, TitanOperationStatus> getAllInputsOfResourceInstance(ComponentInstance compInstance);
- Either<Map<String, InputDefinition>, StorageOperationStatus> deleteAllInputsAssociatedToNode(NodeTypeEnum nodeType,
- String uniqueId);
+ Either<Map<String, InputDefinition>, StorageOperationStatus> deleteAllInputsAssociatedToNode(NodeTypeEnum nodeType, String uniqueId);
// TitanOperationStatus findNodeNonInheretedAttribues(String uniqueId,
// NodeTypeEnum nodeType, List<AttributeDefinition> attributes);
- Either<InputsData, StorageOperationStatus> addInput(String inputName, InputDefinition inputDefinition,
- String componentId, NodeTypeEnum nodeType);
+ Either<InputsData, StorageOperationStatus> addInput(String inputName, InputDefinition inputDefinition, String componentId, NodeTypeEnum nodeType);
- Either<InputsData, TitanOperationStatus> addInputToGraph(String propertyName, InputDefinition inputDefinition,
- String componentId, NodeTypeEnum nodeType);
+ Either<InputsData, TitanOperationStatus> addInputToGraph(String propertyName, InputDefinition inputDefinition, String componentId, NodeTypeEnum nodeType);
- Either<AttributeData, StorageOperationStatus> updateInput(String inputId, InputDefinition newInDef,
- Map<String, DataTypeDefinition> dataTypes);
+ Either<AttributeData, StorageOperationStatus> updateInput(String inputId, InputDefinition newInDef, Map<String, DataTypeDefinition> dataTypes);
TitanOperationStatus findAllResourceInputs(String uniqueId, List<InputDefinition> inputs);
- Either<InputDefinition, StorageOperationStatus> getInputById(String uniqueId, boolean skipProperties,
- boolean skipinputsValue);
+ Either<InputDefinition, StorageOperationStatus> getInputById(String uniqueId, boolean skipProperties, boolean skipinputsValue);
- TitanOperationStatus addInputsToGraph(TitanVertex metadata, String componentId, Map<String, InputDefinition> inputs,
- Map<String, DataTypeDefinition> dataTypes);
+ TitanOperationStatus addInputsToGraph(TitanVertex metadata, String componentId, Map<String, InputDefinition> inputs, Map<String, DataTypeDefinition> dataTypes);
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IInterfaceLifecycleOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IInterfaceLifecycleOperation.java
index bbcb61fea8..e46460a502 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IInterfaceLifecycleOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IInterfaceLifecycleOperation.java
@@ -33,17 +33,13 @@ import fj.data.Either;
public interface IInterfaceLifecycleOperation {
- public Either<InterfaceDefinition, StorageOperationStatus> createInterfaceOnResource(InterfaceDefinition interf,
- String resourceId, String interfaceName, boolean failIfExist, boolean inTransaction);
+ public Either<InterfaceDefinition, StorageOperationStatus> createInterfaceOnResource(InterfaceDefinition interf, String resourceId, String interfaceName, boolean failIfExist, boolean inTransaction);
- public StorageOperationStatus createInterfaceOnResource(InterfaceDefinition interf, String resourceId,
- String interfaceName, boolean failIfExist, boolean inTransaction, TitanVertex metadataVertex);
+ public StorageOperationStatus createInterfaceOnResource(InterfaceDefinition interf, String resourceId, String interfaceName, boolean failIfExist, boolean inTransaction, TitanVertex metadataVertex);
- public Either<InterfaceDefinition, StorageOperationStatus> addInterfaceToResource(InterfaceDefinition interf,
- String resourceId, String interfaceName);
+ public Either<InterfaceDefinition, StorageOperationStatus> addInterfaceToResource(InterfaceDefinition interf, String resourceId, String interfaceName);
- public Either<InterfaceDefinition, StorageOperationStatus> addInterfaceToResource(InterfaceDefinition interf,
- String resourceId, String interfaceName, boolean inTransaction);
+ public Either<InterfaceDefinition, StorageOperationStatus> addInterfaceToResource(InterfaceDefinition interf, String resourceId, String interfaceName, boolean inTransaction);
// public Either<InterfaceDefinition, StorageOperationStatus>
// getInterface(String interfaceId);
@@ -51,42 +47,31 @@ public interface IInterfaceLifecycleOperation {
// public Either<InterfaceDefinition, StorageOperationStatus>
// getInterface(String interfaceId, boolean inTransaction);
- public Either<Operation, StorageOperationStatus> updateInterfaceOperation(String resourceId, String interfaceName,
- String operationName, Operation interf);
+ public Either<Operation, StorageOperationStatus> updateInterfaceOperation(String resourceId, String interfaceName, String operationName, Operation interf);
- public Either<Operation, StorageOperationStatus> updateInterfaceOperation(String resourceId, String interfaceName,
- String operationName, Operation interf, boolean inTransaction);
+ public Either<Operation, StorageOperationStatus> updateInterfaceOperation(String resourceId, String interfaceName, String operationName, Operation interf, boolean inTransaction);
- public Either<Operation, StorageOperationStatus> deleteInterfaceOperation(String resourceId, String interfaceName,
- String operationName);
+ public Either<Operation, StorageOperationStatus> deleteInterfaceOperation(String resourceId, String interfaceName, String operationName);
- public Either<Operation, StorageOperationStatus> deleteInterfaceOperation(String resourceId, String interfaceName,
- String operationName, boolean inTransaction);
+ public Either<Operation, StorageOperationStatus> deleteInterfaceOperation(String resourceId, String interfaceName, String operationName, boolean inTransaction);
- public Either<Map<String, InterfaceDefinition>, StorageOperationStatus> getAllInterfacesOfResource(
- String resourceId, boolean recursively, boolean inTransaction);
+ public Either<Map<String, InterfaceDefinition>, StorageOperationStatus> getAllInterfacesOfResource(String resourceId, boolean recursively, boolean inTransaction);
- public Either<Map<String, InterfaceDefinition>, StorageOperationStatus> getAllInterfacesOfResource(
- String resourceId, boolean recursively);
+ public Either<Map<String, InterfaceDefinition>, StorageOperationStatus> getAllInterfacesOfResource(String resourceId, boolean recursively);
- public Either<InterfaceDefinition, StorageOperationStatus> deleteInterfaceOfResourceOnGraph(String resourceId,
- InterfaceDefinition interfaceDef, boolean inTransaction);
+ public Either<InterfaceDefinition, StorageOperationStatus> deleteInterfaceOfResourceOnGraph(String resourceId, InterfaceDefinition interfaceDef, boolean inTransaction);
public Either<InterfaceDefinition, StorageOperationStatus> createInterfaceType(InterfaceDefinition interf);
- public Either<InterfaceDefinition, StorageOperationStatus> createInterfaceType(InterfaceDefinition interf,
- boolean inTransaction);
+ public Either<InterfaceDefinition, StorageOperationStatus> createInterfaceType(InterfaceDefinition interf, boolean inTransaction);
public Either<InterfaceDefinition, StorageOperationStatus> getInterface(String interfaceId);
- public StorageOperationStatus associateInterfaceToNode(GraphNode node, InterfaceDefinition interfaceDefinition,
- TitanVertex metadataVertex);
+ public StorageOperationStatus associateInterfaceToNode(GraphNode node, InterfaceDefinition interfaceDefinition, TitanVertex metadataVertex);
- public Either<Operation, StorageOperationStatus> getSpecificOperation(String resourceId, String interfaceType,
- String operationName);
+ public Either<Operation, StorageOperationStatus> getSpecificOperation(String resourceId, String interfaceType, String operationName);
- public Either<InterfaceDefinition, StorageOperationStatus> dissociateInterfaceFromNode(GraphNode node,
- InterfaceDefinition interfaceDefinition);
+ public Either<InterfaceDefinition, StorageOperationStatus> dissociateInterfaceFromNode(GraphNode node, InterfaceDefinition interfaceDefinition);
public String getShortInterfaceName(InterfaceDataDefinition interfaceDefinition);
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ILifecycleOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ILifecycleOperation.java
index 3b82eb692c..ab99f20d4c 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ILifecycleOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ILifecycleOperation.java
@@ -33,32 +33,23 @@ public interface ILifecycleOperation {
public ResourceOperation getResourceOperation();
- public Either<User, StorageOperationStatus> getComponentOwner(String resourceId, NodeTypeEnum nodeType,
- boolean inTransaction);
+ public Either<User, StorageOperationStatus> getComponentOwner(String resourceId, NodeTypeEnum nodeType, boolean inTransaction);
- public Either<? extends Component, StorageOperationStatus> checkinComponent(NodeTypeEnum nodeType,
- Component component, User modifier, User owner, boolean inTransaction);
+ public Either<? extends Component, StorageOperationStatus> checkinComponent(NodeTypeEnum nodeType, Component component, User modifier, User owner, boolean inTransaction);
- public Either<? extends Component, StorageOperationStatus> requestCertificationComponent(NodeTypeEnum nodeType,
- Component component, User modifier, User owner, boolean inTransaction);
+ public Either<? extends Component, StorageOperationStatus> requestCertificationComponent(NodeTypeEnum nodeType, Component component, User modifier, User owner, boolean inTransaction);
- public Either<? extends Component, StorageOperationStatus> startComponentCertification(NodeTypeEnum nodeType,
- Component component, User modifier, User owner, boolean inTransaction);
+ public Either<? extends Component, StorageOperationStatus> startComponentCertification(NodeTypeEnum nodeType, Component component, User modifier, User owner, boolean inTransaction);
- public Either<? extends Component, StorageOperationStatus> checkoutComponent(NodeTypeEnum nodeType,
- Component component, User modifier, User currentOwner, boolean inTransaction);
+ public Either<? extends Component, StorageOperationStatus> checkoutComponent(NodeTypeEnum nodeType, Component component, User modifier, User currentOwner, boolean inTransaction);
- public Either<? extends Component, StorageOperationStatus> certifyComponent(NodeTypeEnum nodeType,
- Component component, User modifier, User currentOwner, boolean inTransaction);
+ public Either<? extends Component, StorageOperationStatus> certifyComponent(NodeTypeEnum nodeType, Component component, User modifier, User currentOwner, boolean inTransaction);
- public Either<? extends Component, StorageOperationStatus> cancelOrFailCertification(NodeTypeEnum nodeType,
- Component component, User modifier, User owner, LifecycleStateEnum nextState, boolean b);
+ public Either<? extends Component, StorageOperationStatus> cancelOrFailCertification(NodeTypeEnum nodeType, Component component, User modifier, User owner, LifecycleStateEnum nextState, boolean b);
- public Either<Boolean, StorageOperationStatus> deleteOldComponentVersions(NodeTypeEnum nodeType,
- String componentName, String uuid, boolean inTransaction);
+ public Either<Boolean, StorageOperationStatus> deleteOldComponentVersions(NodeTypeEnum nodeType, String componentName, String uuid, boolean inTransaction);
- public Either<? extends Component, StorageOperationStatus> undoCheckout(NodeTypeEnum nodeType, Component resource,
- User modifier, User currentOwner, boolean inTransaction);
+ public Either<? extends Component, StorageOperationStatus> undoCheckout(NodeTypeEnum nodeType, Component resource, User modifier, User currentOwner, boolean inTransaction);
public ComponentOperation getComponentOperation(NodeTypeEnum componentType);
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IPolicyTypeOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IPolicyTypeOperation.java
index fc689c81e2..d25d11331d 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
@@ -32,7 +32,6 @@ public interface IPolicyTypeOperation {
Either<PolicyTypeDefinition, StorageOperationStatus> getPolicyType(String uniqueId, boolean inTransaction);
- Either<PolicyTypeDefinition, StorageOperationStatus> addPolicyType(PolicyTypeDefinition policyType,
- boolean inTransaction);
+ Either<PolicyTypeDefinition, StorageOperationStatus> addPolicyType(PolicyTypeDefinition policyType, boolean inTransaction);
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IProductOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IProductOperation.java
index bbfea262a7..76f95f3c2b 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IProductOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IProductOperation.java
@@ -37,8 +37,7 @@ public interface IProductOperation extends IComponentOperation {
public Either<Product, StorageOperationStatus> deleteProduct(String productId, boolean inTransaction);
- public Either<List<Product>, StorageOperationStatus> getFollowed(String userId,
- Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates, boolean inTransaction);
+ public Either<List<Product>, StorageOperationStatus> getFollowed(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates, boolean inTransaction);
public void rollback();
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 6309510f6d..f9f960fdbf 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
@@ -41,9 +41,7 @@ public interface IPropertyOperation {
* @param id
* @return
*
- * public Either<PropertyDefinition, StorageOperationStatus>
- * addPropertyToResource( String propertyName, PropertyDefinition
- * propertyDefinition, NodeTypeEnum nodeType, String id);
+ * public Either<PropertyDefinition, StorageOperationStatus> addPropertyToResource( String propertyName, PropertyDefinition propertyDefinition, NodeTypeEnum nodeType, String id);
*/
/**
@@ -55,8 +53,7 @@ public interface IPropertyOperation {
* - resource unique id
* @return
*/
- public Either<PropertyDefinition, StorageOperationStatus> getPropertyOfResource(String propertyName,
- String resourceId);
+ public Either<PropertyDefinition, StorageOperationStatus> getPropertyOfResource(String propertyName, String resourceId);
/**
* Delete all properties of resource
@@ -65,16 +62,13 @@ public interface IPropertyOperation {
* @param uniqueId
* @return
*/
- public Either<Map<String, PropertyDefinition>, StorageOperationStatus> deleteAllPropertiesAssociatedToNode(
- NodeTypeEnum nodeType, String uniqueId);
+ public Either<Map<String, PropertyDefinition>, StorageOperationStatus> deleteAllPropertiesAssociatedToNode(NodeTypeEnum nodeType, String uniqueId);
- public boolean isPropertyDefaultValueValid(IComplexDefaultValue propertyDefinition,
- Map<String, DataTypeDefinition> dataTypes);
+ public boolean isPropertyDefaultValueValid(IComplexDefaultValue propertyDefinition, Map<String, DataTypeDefinition> dataTypes);
public boolean isPropertyTypeValid(IComplexDefaultValue propertyDefinition);
- public ImmutablePair<String, Boolean> isPropertyInnerTypeValid(IComplexDefaultValue propertyDefinition,
- Map<String, DataTypeDefinition> dataTypes);
+ public ImmutablePair<String, Boolean> isPropertyInnerTypeValid(IComplexDefaultValue propertyDefinition, Map<String, DataTypeDefinition> dataTypes);
/**
* @param dataTypeDefinition
@@ -82,8 +76,7 @@ public interface IPropertyOperation {
*/
public Either<DataTypeDefinition, StorageOperationStatus> addDataType(DataTypeDefinition dataTypeDefinition);
- public Either<DataTypeDefinition, StorageOperationStatus> addDataType(DataTypeDefinition dataTypeDefinition,
- boolean inTransaction);
+ public Either<DataTypeDefinition, StorageOperationStatus> addDataType(DataTypeDefinition dataTypeDefinition, boolean inTransaction);
/**
* @param name
@@ -93,18 +86,14 @@ public interface IPropertyOperation {
public Either<DataTypeDefinition, StorageOperationStatus> getDataTypeByName(String name, boolean inTransaction);
- public Either<DataTypeDefinition, StorageOperationStatus> getDataTypeByNameWithoutDerived(String name,
- boolean inTransaction);
+ public Either<DataTypeDefinition, StorageOperationStatus> getDataTypeByNameWithoutDerived(String name, boolean inTransaction);
public Either<DataTypeDefinition, StorageOperationStatus> getDataTypeByNameWithoutDerived(String name);
- public StorageOperationStatus validateAndUpdateProperty(IComplexDefaultValue propertyDefinition,
- Map<String, DataTypeDefinition> dataTypes);
+ public StorageOperationStatus validateAndUpdateProperty(IComplexDefaultValue propertyDefinition, Map<String, DataTypeDefinition> dataTypes);
- public Either<DataTypeDefinition, StorageOperationStatus> updateDataType(DataTypeDefinition newDataTypeDefinition,
- DataTypeDefinition oldDataTypeDefinition, boolean inTransaction);
+ public Either<DataTypeDefinition, StorageOperationStatus> updateDataType(DataTypeDefinition newDataTypeDefinition, DataTypeDefinition oldDataTypeDefinition, boolean inTransaction);
- public Either<DataTypeDefinition, StorageOperationStatus> updateDataType(DataTypeDefinition newDataTypeDefinition,
- DataTypeDefinition oldDataTypeDefinition);
+ public Either<DataTypeDefinition, StorageOperationStatus> updateDataType(DataTypeDefinition newDataTypeDefinition, DataTypeDefinition oldDataTypeDefinition);
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IRequirementOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IRequirementOperation.java
index a7a9bf6013..a2af44cf61 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IRequirementOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IRequirementOperation.java
@@ -42,17 +42,13 @@ public interface IRequirementOperation {
* @param uniqueId
* @return
*/
- public Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource(String reqName,
- RequirementDefinition reqDefinition, String resourceId);
+ public Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource(String reqName, RequirementDefinition reqDefinition, String resourceId);
- public Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource(String reqName,
- RequirementDefinition reqDefinition, String resourceId, boolean inTransaction);
+ public Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource(String reqName, RequirementDefinition reqDefinition, String resourceId, boolean inTransaction);
- public Either<RequirementDefinition, StorageOperationStatus> addRequirementImplToResource(String reqName,
- RequirementImplDef reqDefinition, String resourceId, String parentReqUniqueId);
+ public Either<RequirementDefinition, StorageOperationStatus> addRequirementImplToResource(String reqName, RequirementImplDef reqDefinition, String resourceId, String parentReqUniqueId);
- public Either<RequirementDefinition, StorageOperationStatus> addRequirementImplToResource(String reqName,
- RequirementImplDef reqDefinition, String resourceId, String parentReqUniqueId, boolean inTransaction);
+ public Either<RequirementDefinition, StorageOperationStatus> addRequirementImplToResource(String reqName, RequirementImplDef reqDefinition, String resourceId, String parentReqUniqueId, boolean inTransaction);
/**
* get requirement of resource
@@ -61,25 +57,19 @@ public interface IRequirementOperation {
* @param resourceId
* @return
*/
- public Either<RequirementDefinition, StorageOperationStatus> getRequirementOfResource(String reqName,
- String resourceId);
+ public Either<RequirementDefinition, StorageOperationStatus> getRequirementOfResource(String reqName, String resourceId);
- public Either<RequirementDefinition, StorageOperationStatus> getRequirementOfResource(String reqName,
- String resourceId, boolean inTransaction);
+ public Either<RequirementDefinition, StorageOperationStatus> getRequirementOfResource(String reqName, String resourceId, boolean inTransaction);
- public Either<Map<String, RequirementDefinition>, StorageOperationStatus> getAllResourceRequirements(
- String resourceId, boolean inTransaction);
+ public Either<Map<String, RequirementDefinition>, StorageOperationStatus> getAllResourceRequirements(String resourceId, boolean inTransaction);
- Either<Map<String, List<RequirementDefinition>>, StorageOperationStatus> getAllRequirementsOfResourceOnly(
- String resourceId, boolean inTransaction);
+ Either<Map<String, List<RequirementDefinition>>, StorageOperationStatus> getAllRequirementsOfResourceOnly(String resourceId, boolean inTransaction);
public Either<Map<String, RequirementDefinition>, TitanOperationStatus> getResourceRequirements(String resourceId);
- public Either<Map<String, RequirementDefinition>, StorageOperationStatus> deleteAllRequirements(String resourceId,
- boolean inTransaction);
+ public Either<Map<String, RequirementDefinition>, StorageOperationStatus> deleteAllRequirements(String resourceId, boolean inTransaction);
public Either<RequirementDefinition, TitanOperationStatus> getRequirement(String uniqueId);
- StorageOperationStatus addRequirementToResource(TitanVertex metadataVertex, String reqName,
- RequirementDefinition reqDefinition, String resourceId, boolean inTransaction);
+ StorageOperationStatus addRequirementToResource(TitanVertex metadataVertex, String reqName, RequirementDefinition reqDefinition, String resourceId, boolean inTransaction);
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IResourceOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IResourceOperation.java
index 759380c236..01db3a5105 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IResourceOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IResourceOperation.java
@@ -51,21 +51,17 @@ public interface IResourceOperation extends IComponentOperation {
public Either<Resource, StorageOperationStatus> getResource(String resourceId, boolean inTransaction);
/**
- * the method retrieves all the certified resources, the returned values are
- * only abstract or only none abstract according to the supplied parameters.
+ * the method retrieves all the certified resources, the returned values are only abstract or only none abstract according to the supplied parameters.
*
* @param getAbstract
- * the value defines which resources to return only abstract or
- * only none abstract
+ * the value defines which resources to return only abstract or only none abstract
* @return
*/
public Either<List<Resource>, StorageOperationStatus> getAllCertifiedResources(boolean getAbstract);
- public Either<List<Resource>, StorageOperationStatus> getAllCertifiedResources(boolean getAbstract,
- Boolean isHighest);
+ public Either<List<Resource>, StorageOperationStatus> getAllCertifiedResources(boolean getAbstract, Boolean isHighest);
- public Either<Boolean, StorageOperationStatus> validateResourceNameExists(String resourceName,
- ResourceTypeEnum resourceType);
+ public Either<Boolean, StorageOperationStatus> validateResourceNameExists(String resourceName, ResourceTypeEnum resourceType);
public Either<Resource, StorageOperationStatus> deleteResource(String resourceId);
@@ -80,39 +76,31 @@ public interface IResourceOperation extends IComponentOperation {
// public Either<List<ArtifactDefinition>, StorageOperationStatus>
// getResourceArtifactsForDelete(Resource resource);
- public Either<List<Resource>, StorageOperationStatus> getFollowed(String userId,
- Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates, boolean inTransaction);
+ public Either<List<Resource>, StorageOperationStatus> getFollowed(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates, boolean inTransaction);
- public Either<Set<Resource>, StorageOperationStatus> getCatalogData(Map<String, Object> propertiesToMatch,
- boolean inTransaction);
+ public Either<Set<Resource>, StorageOperationStatus> getCatalogData(Map<String, Object> propertiesToMatch, boolean inTransaction);
public Either<Resource, StorageOperationStatus> getLatestByName(String resourceName, boolean inTransaction);
- public Either<Resource, StorageOperationStatus> overrideResource(Resource resource, Resource resourceSaved,
- boolean inTransaction);
+ public Either<Resource, StorageOperationStatus> overrideResource(Resource resource, Resource resourceSaved, boolean inTransaction);
- public Either<List<Resource>, StorageOperationStatus> getTesterFollowed(String userId,
- Set<LifecycleStateEnum> lifecycleStates, boolean inTransaction);
+ public Either<List<Resource>, StorageOperationStatus> getTesterFollowed(String userId, Set<LifecycleStateEnum> lifecycleStates, boolean inTransaction);
public Either<List<Resource>, StorageOperationStatus> getResourceListByUuid(String uuid, boolean inTransaction);
public Either<List<Resource>, StorageOperationStatus> getLatestResourceByUuid(String uuid, boolean inTransaction);
- public Either<List<Resource>, StorageOperationStatus> getResourceListBySystemName(String systemName,
- boolean inTransaction);
+ public Either<List<Resource>, StorageOperationStatus> getResourceListBySystemName(String systemName, boolean inTransaction);
public Either<List<Resource>, StorageOperationStatus> getResourceCatalogData(boolean inTransaction);
- public Either<List<Resource>, StorageOperationStatus> getResourceCatalogDataVFLatestCertifiedAndNonCertified(
- boolean inTransaction);
+ public Either<List<Resource>, StorageOperationStatus> getResourceCatalogDataVFLatestCertifiedAndNonCertified(boolean inTransaction);
- public Either<List<Resource>, StorageOperationStatus> getResourceByNameAndVersion(String name, String version,
- boolean inTransaction);
+ public Either<List<Resource>, StorageOperationStatus> getResourceByNameAndVersion(String name, String version, boolean inTransaction);
public Either<List<Resource>, StorageOperationStatus> getResourceByNameAndVersion(String name, String version);
- public Either<Resource, StorageOperationStatus> getResourceBySystemNameAndVersion(String name, String version,
- Map<String, Object> additionalParams, boolean inTransaction);
+ public Either<Resource, StorageOperationStatus> getResourceBySystemNameAndVersion(String name, String version, Map<String, Object> additionalParams, boolean inTransaction);
// public Either<List<Resource>, StorageOperationStatus>
// getAllNotCheckoutResources(boolean getAbstract);
@@ -124,8 +112,35 @@ public interface IResourceOperation extends IComponentOperation {
public Either<Boolean, StorageOperationStatus> isResourceInUse(String resourceToDelete);
- public Either<Resource, StorageOperationStatus> getLatestByToscaResourceName(String toscaResourceName,
- boolean inTransaction);
+ public Either<Resource, StorageOperationStatus> getLatestByToscaResourceName(String toscaResourceName, boolean inTransaction);
public Either<Boolean, StorageOperationStatus> validateToscaResourceNameExists(String templateName);
+
+ public Either<Boolean, StorageOperationStatus> validateToscaResourceNameExtends(String templateNameCurrent, String templateNameExtends);
+
+ /**
+ *
+ * @param resource the resource to look for its derived resources
+ * @return all resources which derives from the given resource
+ */
+ Either<List<Resource>, StorageOperationStatus> getAllDerivedResources(Resource resource);
+
+ /**
+ *
+ * @return all root resources (i.e all normatives with tosca name {@code Resource.ROOT_RESOURCE}
+ */
+ Either<List<Resource>, StorageOperationStatus> getRootResources();
+
+ /**
+ *
+ * @return all resources with type VF
+ */
+ Either<List<Resource>, StorageOperationStatus> getVFResources();
+
+ /**
+ *
+ * @return all resources
+ */
+ Either<List<Resource>, StorageOperationStatus> getAll();
+
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IServiceOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IServiceOperation.java
index 05eb7c66f6..f08c52e0fa 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IServiceOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IServiceOperation.java
@@ -40,8 +40,6 @@ public interface IServiceOperation extends IComponentOperation {
public Either<Service, StorageOperationStatus> getService(String uniqueId);
public Either<Service, StorageOperationStatus> getService(String uniqueId, boolean inTransaction);
- // public Either<Service, StorageOperationStatus> getService_tx(String
- // uniqueId, boolean inTransaction);
public Either<Service, StorageOperationStatus> deleteService(String uniqueId);
@@ -49,40 +47,33 @@ public interface IServiceOperation extends IComponentOperation {
public Either<Boolean, StorageOperationStatus> validateServiceNameExists(String serviceName);
- public Either<List<Service>, StorageOperationStatus> getFollowed(String userId,
- Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates, boolean inTransaction);
+ public Either<List<Service>, StorageOperationStatus> getFollowed(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates, boolean inTransaction);
public Either<Service, StorageOperationStatus> updateService(Service service, boolean inTransaction);
- public Either<Set<Service>, StorageOperationStatus> getCatalogData(Map<String, Object> propertiesToMatch,
- boolean inTransaction);
+ public Either<Set<Service>, StorageOperationStatus> getCatalogData(Map<String, Object> propertiesToMatch, boolean inTransaction);
- public Either<List<Service>, StorageOperationStatus> getTesterFollowed(String userId,
- Set<LifecycleStateEnum> lifecycleStates, boolean inTransaction);
+ public Either<List<Service>, StorageOperationStatus> getTesterFollowed(String userId, Set<LifecycleStateEnum> lifecycleStates, boolean inTransaction);
- public Either<Set<Service>, StorageOperationStatus> getCertifiedServicesWithDistStatus(
- Map<String, Object> propertiesToMatch, Set<DistributionStatusEnum> distStatus, boolean inTransaction);
+ public Either<Set<Service>, StorageOperationStatus> getCertifiedServicesWithDistStatus(Map<String, Object> propertiesToMatch, Set<DistributionStatusEnum> distStatus, boolean inTransaction);
- public Either<Service, StorageOperationStatus> updateDestributionStatus(Service service, User user,
- DistributionStatusEnum distributionStatus);
+ public Either<Service, StorageOperationStatus> updateDestributionStatus(Service service, User user, DistributionStatusEnum distributionStatus);
public Either<List<Service>, StorageOperationStatus> getServiceCatalogData(boolean inTransaction);
- public Either<List<Service>, StorageOperationStatus> getServiceCatalogDataLatestCertifiedAndNotCertified(
- boolean inTransaction);
+ public Either<List<Service>, StorageOperationStatus> getServiceCatalogDataLatestCertifiedAndNotCertified(boolean inTransaction);
- public Either<Service, StorageOperationStatus> getServiceByNameAndVersion(String name, String version,
- Map<String, Object> additionalParams, boolean inTransaction);
+ public Either<Service, StorageOperationStatus> getServiceByNameAndVersion(String name, String version, Map<String, Object> additionalParams, boolean inTransaction);
public Either<Service, StorageOperationStatus> getServiceByNameAndVersion(String name, String version);
- public Either<Service, StorageOperationStatus> getServiceBySystemNameAndVersion(String name, String version,
- boolean inTransaction);
+ public Either<Service, StorageOperationStatus> getServiceBySystemNameAndVersion(String name, String version, boolean inTransaction);
public Either<List<Service>, StorageOperationStatus> getServiceListByUuid(String uuid, boolean inTransaction);
public Either<List<Service>, StorageOperationStatus> getLatestServiceByUuid(String uuid, boolean inTransaction);
- public Either<List<Service>, StorageOperationStatus> getServiceListBySystemName(String systemName,
- boolean inTransaction);
+ public Either<List<Service>, StorageOperationStatus> getServiceListBySystemName(String systemName, boolean inTransaction);
+
+ Either<List<Service> , StorageOperationStatus> getAll();
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IUserAdminOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IUserAdminOperation.java
index dd9766fc83..84413f7987 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IUserAdminOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IUserAdminOperation.java
@@ -48,11 +48,11 @@ public interface IUserAdminOperation {
public Either<List<User>, ActionStatus> getAllUsersWithRole(String role, String status);
- public Either<List<Edge>, StorageOperationStatus> getUserPandingTasksList(User user,
- Map<String, Object> properties);
+ Either<List<User>, ActionStatus> getAllUsers();
+
+ public Either<List<Edge>, StorageOperationStatus> getUserPandingTasksList(User user, Map<String, Object> properties);
public Either<ImmutablePair<User, FunctionalMenuInfo>, ActionStatus> getUserDataWithFunctionalMenu(String userId);
- public Either<FunctionalMenuInfo, TitanOperationStatus> createOrUpdateFunctionalMenu(String userId,
- String newFunctionalMenu);
+ public Either<FunctionalMenuInfo, TitanOperationStatus> createOrUpdateFunctionalMenu(String userId, String newFunctionalMenu);
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ToscaDefinitionPathCalculator.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ToscaDefinitionPathCalculator.java
new file mode 100644
index 0000000000..f64d4c9091
--- /dev/null
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ToscaDefinitionPathCalculator.java
@@ -0,0 +1,12 @@
+package org.openecomp.sdc.be.model.operations.api;
+
+import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
+import org.openecomp.sdc.be.model.ComponentInstance;
+
+import java.util.List;
+
+public interface ToscaDefinitionPathCalculator {
+
+ List<String> calculateToscaDefinitionPath(ComponentInstance componentInstance, GraphEdge edge);
+
+}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AbstractOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AbstractOperation.java
index c4bbaf58f6..0f36f09ca8 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AbstractOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AbstractOperation.java
@@ -198,7 +198,7 @@ public abstract class AbstractOperation {
if (ctResult.isRight()) {
TitanOperationStatus status = ctResult.right().value();
if (status != TitanOperationStatus.NOT_FOUND) {
- log.error("Failed to retrieve information on element uniqueId:" + uniqueId + ". status is " + status);
+ log.error("Failed to retrieve information on element uniqueId: {}. status is {}", uniqueId, status);
}
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(ctResult.right().value()));
return result;
@@ -314,13 +314,13 @@ public abstract class AbstractOperation {
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);
+ 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));
+ log.trace("Going to update value in property definition {} {}" , propertyDefinition.getName() , (jsonElement != null ? jsonElement.toString() : null));
updateValue(propertyDefinition, jsonElement);
@@ -360,7 +360,7 @@ public abstract class AbstractOperation {
}
PropertyDataDefinition propDef = def.getProperty();
if (propDef == null) {
- log.debug("Property in Schema Definition inside property of type {} doesn't exists", type);
+ log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
}
innerType = propDef.getType();
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AdditionalInformationOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AdditionalInformationOperation.java
index e2c7f369f1..b9a67e5dc6 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
@@ -26,9 +26,6 @@ import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
-import com.thinkaurelius.titan.core.TitanTransaction;
-import com.thinkaurelius.titan.core.TitanVertex;
-
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
@@ -41,8 +38,8 @@ import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterInfo;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.model.AdditionalInfoParameterInfo;
import org.openecomp.sdc.be.model.AdditionalInformationDefinition;
import org.openecomp.sdc.be.model.operations.api.IAdditionalInformationOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
@@ -54,7 +51,9 @@ import org.openecomp.sdc.common.config.EcompErrorName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
-import org.springframework.util.AutoPopulatingList.ElementFactory;
+
+import com.thinkaurelius.titan.core.TitanTransaction;
+import com.thinkaurelius.titan.core.TitanVertex;
import fj.data.Either;
@@ -62,7 +61,6 @@ import fj.data.Either;
public class AdditionalInformationOperation implements IAdditionalInformationOperation {
public static final String EMPTY_VALUE = null;
- public static final String PROPERTY = "property";
public AdditionalInformationOperation() {
super();
@@ -74,18 +72,15 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe
private TitanGenericDao titanGenericDao;
@Override
- public Either<AdditionalInformationDefinition, TitanOperationStatus> addAdditionalInformationParameter(
- NodeTypeEnum nodeType, String componentId, String key, String value) {
+ public Either<AdditionalInformationDefinition, TitanOperationStatus> addAdditionalInformationParameter(NodeTypeEnum nodeType, String componentId, String key, String value) {
TitanOperationStatus verifyNodeTypeVsComponent = verifyNodeTypeVsComponent(nodeType, componentId);
if (verifyNodeTypeVsComponent != TitanOperationStatus.OK) {
return Either.right(verifyNodeTypeVsComponent);
}
- Either<ImmutablePair<AdditionalInfoParameterData, GraphEdge>, TitanOperationStatus> getResult = titanGenericDao
- .getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId,
- GraphEdgeLabels.ADDITIONAL_INFORMATION, NodeTypeEnum.AdditionalInfoParameters,
- AdditionalInfoParameterData.class);
+ Either<ImmutablePair<AdditionalInfoParameterData, GraphEdge>, TitanOperationStatus> getResult = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId, GraphEdgeLabels.ADDITIONAL_INFORMATION,
+ NodeTypeEnum.AdditionalInfoParameters, AdditionalInfoParameterData.class);
if (getResult.isRight()) {
TitanOperationStatus status = getResult.right().value();
@@ -117,39 +112,31 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe
parameters.put(key, value);
parameterData.getAdditionalInfoParameterDataDefinition().setLastCreatedCounter(lastCreatedCounter);
- Either<AdditionalInfoParameterData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(parameterData,
- AdditionalInfoParameterData.class);
+ Either<AdditionalInfoParameterData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(parameterData, AdditionalInfoParameterData.class);
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));
+ 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);
}
- AdditionalInformationDefinition informationDefinition = createInformationDefinitionFromNode(componentId,
- parameters, idToKey, updateNode.left().value());
+ AdditionalInformationDefinition informationDefinition = createInformationDefinitionFromNode(componentId, parameters, idToKey, updateNode.left().value());
return Either.left(informationDefinition);
}
@Override
- public Either<AdditionalInformationDefinition, TitanOperationStatus> updateAdditionalInformationParameter(
- NodeTypeEnum nodeType, String componentId, String id, String key, String value) {
+ public Either<AdditionalInformationDefinition, TitanOperationStatus> updateAdditionalInformationParameter(NodeTypeEnum nodeType, String componentId, String id, String key, String value) {
TitanOperationStatus verifyNodeTypeVsComponent = verifyNodeTypeVsComponent(nodeType, componentId);
if (verifyNodeTypeVsComponent != TitanOperationStatus.OK) {
return Either.right(verifyNodeTypeVsComponent);
}
- Either<ImmutablePair<AdditionalInfoParameterData, GraphEdge>, TitanOperationStatus> getResult = titanGenericDao
- .getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId,
- GraphEdgeLabels.ADDITIONAL_INFORMATION, NodeTypeEnum.AdditionalInfoParameters,
- AdditionalInfoParameterData.class);
+ Either<ImmutablePair<AdditionalInfoParameterData, GraphEdge>, TitanOperationStatus> getResult = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId, GraphEdgeLabels.ADDITIONAL_INFORMATION,
+ NodeTypeEnum.AdditionalInfoParameters, AdditionalInfoParameterData.class);
if (getResult.isRight()) {
TitanOperationStatus status = getResult.right().value();
@@ -172,44 +159,36 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe
return Either.right(TitanOperationStatus.ALREADY_EXIST);
}
String removed = parameters.remove(origKey);
- log.trace("The key-value " + origKey + "=" + removed + " was removed from additionalInformation");
+ log.trace("The key-value {} = {} was removed from additionalInformation", origKey, removed);
}
parameters.put(key, value);
idToKey.put(id, key);
- Either<AdditionalInfoParameterData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(parameterData,
- AdditionalInfoParameterData.class);
+ Either<AdditionalInfoParameterData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(parameterData, AdditionalInfoParameterData.class);
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));
+ 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);
}
- AdditionalInformationDefinition informationDefinition = createInformationDefinitionFromNode(componentId,
- parameters, idToKey, updateNode.left().value());
+ AdditionalInformationDefinition informationDefinition = createInformationDefinitionFromNode(componentId, parameters, idToKey, updateNode.left().value());
return Either.left(informationDefinition);
}
@Override
- public Either<AdditionalInformationDefinition, TitanOperationStatus> deleteAdditionalInformationParameter(
- NodeTypeEnum nodeType, String componentId, String id) {
+ public Either<AdditionalInformationDefinition, TitanOperationStatus> deleteAdditionalInformationParameter(NodeTypeEnum nodeType, String componentId, String id) {
TitanOperationStatus verifyNodeTypeVsComponent = verifyNodeTypeVsComponent(nodeType, componentId);
if (verifyNodeTypeVsComponent != TitanOperationStatus.OK) {
return Either.right(verifyNodeTypeVsComponent);
}
- Either<ImmutablePair<AdditionalInfoParameterData, GraphEdge>, TitanOperationStatus> getResult = titanGenericDao
- .getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId,
- GraphEdgeLabels.ADDITIONAL_INFORMATION, NodeTypeEnum.AdditionalInfoParameters,
- AdditionalInfoParameterData.class);
+ Either<ImmutablePair<AdditionalInfoParameterData, GraphEdge>, TitanOperationStatus> getResult = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId, GraphEdgeLabels.ADDITIONAL_INFORMATION,
+ NodeTypeEnum.AdditionalInfoParameters, AdditionalInfoParameterData.class);
if (getResult.isRight()) {
TitanOperationStatus status = getResult.right().value();
@@ -228,41 +207,31 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe
String key = idToKey.get(id);
String removedKey = idToKey.remove(id);
String removedValue = parameters.remove(key);
- log.trace("The key-value " + removedKey + "=" + removedValue + " was removed from additionalInformation");
+ log.trace("The key-value {} = {} was removed from additionalInformation", removedKey, removedValue);
- Either<AdditionalInfoParameterData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(parameterData,
- AdditionalInfoParameterData.class);
+ Either<AdditionalInfoParameterData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(parameterData, AdditionalInfoParameterData.class);
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));
+ 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);
}
- AdditionalInformationDefinition informationDefinition = createInformationDefinitionFromNode(componentId,
- parameters, idToKey, updateNode.left().value());
+ AdditionalInformationDefinition informationDefinition = createInformationDefinitionFromNode(componentId, parameters, idToKey, updateNode.left().value());
return Either.left(informationDefinition);
}
- private AdditionalInformationDefinition createInformationDefinitionFromNode(String resourceId,
- Map<String, String> parameters, Map<String, String> idToKey,
- AdditionalInfoParameterData additionalInfoParameterData) {
- AdditionalInfoParameterDataDefinition dataDefinition = additionalInfoParameterData
- .getAdditionalInfoParameterDataDefinition();
+ private AdditionalInformationDefinition createInformationDefinitionFromNode(String resourceId, Map<String, String> parameters, Map<String, String> idToKey, AdditionalInfoParameterData additionalInfoParameterData) {
+ AdditionalInfoParameterDataDefinition dataDefinition = additionalInfoParameterData.getAdditionalInfoParameterDataDefinition();
- AdditionalInformationDefinition informationDefinition = new AdditionalInformationDefinition(dataDefinition,
- resourceId, convertParameters(parameters, idToKey));
+ AdditionalInformationDefinition informationDefinition = new AdditionalInformationDefinition(dataDefinition, resourceId, convertParameters(parameters, idToKey));
return informationDefinition;
}
- private List<AdditionalInfoParameterInfo> convertParameters(Map<String, String> parameters,
- Map<String, String> idToKey) {
+ private List<AdditionalInfoParameterInfo> convertParameters(Map<String, String> parameters, Map<String, String> idToKey) {
List<AdditionalInfoParameterInfo> list = new ArrayList<AdditionalInfoParameterInfo>();
@@ -284,8 +253,7 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe
}
@Override
- public Either<AdditionalInfoParameterData, TitanOperationStatus> addAdditionalInformationNode(NodeTypeEnum nodeType,
- String componentId) {
+ public Either<AdditionalInfoParameterData, TitanOperationStatus> addAdditionalInformationNode(NodeTypeEnum nodeType, String componentId) {
UniqueIdData from = new UniqueIdData(nodeType, componentId);
@@ -293,25 +261,19 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe
AdditionalInfoParameterDataDefinition additionalInfoParameterDataDefinition = new AdditionalInfoParameterDataDefinition();
additionalInfoParameterDataDefinition.setUniqueId(uniqueId);
- AdditionalInfoParameterData additionalInfoParameterData = new AdditionalInfoParameterData(
- additionalInfoParameterDataDefinition, new HashMap<String, String>(), new HashMap<String, String>());
+ AdditionalInfoParameterData additionalInfoParameterData = new AdditionalInfoParameterData(additionalInfoParameterDataDefinition, new HashMap<String, String>(), new HashMap<String, String>());
- Either<AdditionalInfoParameterData, TitanOperationStatus> createNode = titanGenericDao
- .createNode(additionalInfoParameterData, AdditionalInfoParameterData.class);
+ 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));
+ 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);
}
AdditionalInfoParameterData to = createNode.left().value();
- Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(from, to,
- GraphEdgeLabels.ADDITIONAL_INFORMATION, null);
+ Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(from, to, GraphEdgeLabels.ADDITIONAL_INFORMATION, null);
if (createRelation.isRight()) {
TitanOperationStatus status = createRelation.right().value();
return Either.right(status);
@@ -321,31 +283,25 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe
}
@Override
- public Either<TitanVertex, TitanOperationStatus> addAdditionalInformationNode(NodeTypeEnum nodeType,
- String componentId, TitanVertex metadataVertex) {
+ public Either<TitanVertex, TitanOperationStatus> addAdditionalInformationNode(NodeTypeEnum nodeType, String componentId, TitanVertex metadataVertex) {
String uniqueId = UniqueIdBuilder.buildAdditionalInformationUniqueId(componentId);
AdditionalInfoParameterDataDefinition additionalInfoParameterDataDefinition = new AdditionalInfoParameterDataDefinition();
additionalInfoParameterDataDefinition.setUniqueId(uniqueId);
- AdditionalInfoParameterData additionalInfoParameterData = new AdditionalInfoParameterData(
- additionalInfoParameterDataDefinition, new HashMap<String, String>(), new HashMap<String, String>());
+ AdditionalInfoParameterData additionalInfoParameterData = new AdditionalInfoParameterData(additionalInfoParameterDataDefinition, new HashMap<String, String>(), new HashMap<String, String>());
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));
+ 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);
}
TitanVertex additionalInfoVertex = createNode.left().value();
- TitanOperationStatus createRelation = titanGenericDao.createEdge(metadataVertex, additionalInfoVertex,
- GraphEdgeLabels.ADDITIONAL_INFORMATION, null);
+ TitanOperationStatus createRelation = titanGenericDao.createEdge(metadataVertex, additionalInfoVertex, GraphEdgeLabels.ADDITIONAL_INFORMATION, null);
if (!createRelation.equals(TitanOperationStatus.OK)) {
return Either.right(createRelation);
@@ -353,11 +309,9 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe
return Either.left(additionalInfoVertex);
}
- public Either<AdditionalInformationDefinition, TitanOperationStatus> addAdditionalInformationNode(
- NodeTypeEnum nodeType, String componentId, AdditionalInformationDefinition parameters) {
+ public Either<AdditionalInformationDefinition, TitanOperationStatus> addAdditionalInformationNode(NodeTypeEnum nodeType, String componentId, AdditionalInformationDefinition parameters) {
- Either<AdditionalInfoParameterData, TitanOperationStatus> status = this.addAdditionalInformationNode(nodeType,
- componentId);
+ Either<AdditionalInfoParameterData, TitanOperationStatus> status = this.addAdditionalInformationNode(nodeType, componentId);
if (status.isRight()) {
return Either.right(status.right().value());
@@ -367,24 +321,20 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe
populateParameterNodeWithParameters(parameterData, parameters);
- Either<AdditionalInfoParameterData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(parameterData,
- AdditionalInfoParameterData.class);
+ Either<AdditionalInfoParameterData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(parameterData, AdditionalInfoParameterData.class);
if (updateNode.isRight()) {
return Either.right(updateNode.right().value());
}
- AdditionalInformationDefinition informationDefinition = convertAdditionalInformationDataToDefinition(
- updateNode.left().value(), componentId);
+ AdditionalInformationDefinition informationDefinition = convertAdditionalInformationDataToDefinition(updateNode.left().value(), componentId);
return Either.left(informationDefinition);
}
- public TitanOperationStatus addAdditionalInformationNode(NodeTypeEnum nodeType, String componentId,
- AdditionalInformationDefinition parameters, TitanVertex metadataVertex) {
+ public TitanOperationStatus addAdditionalInformationNode(NodeTypeEnum nodeType, String componentId, AdditionalInformationDefinition parameters, TitanVertex metadataVertex) {
- Either<TitanVertex, TitanOperationStatus> status = this.addAdditionalInformationNode(nodeType, componentId,
- metadataVertex);
+ Either<TitanVertex, TitanOperationStatus> status = this.addAdditionalInformationNode(nodeType, componentId, metadataVertex);
if (status.isRight()) {
return status.right().value();
@@ -392,9 +342,7 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe
TitanVertex additionalInfoVertex = status.left().value();
Map<String, Object> newProp = titanGenericDao.getProperties(additionalInfoVertex);
- AdditionalInfoParameterData parameterData = GraphElementFactory.createElement(
- NodeTypeEnum.AdditionalInfoParameters.getName(), GraphElementTypeEnum.Node, newProp,
- AdditionalInfoParameterData.class);
+ AdditionalInfoParameterData parameterData = GraphElementFactory.createElement(NodeTypeEnum.AdditionalInfoParameters.getName(), GraphElementTypeEnum.Node, newProp, AdditionalInfoParameterData.class);
populateParameterNodeWithParameters(parameterData, parameters);
@@ -403,14 +351,13 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe
return updateNode;
}
- private void populateParameterNodeWithParameters(AdditionalInfoParameterData parameterData,
- AdditionalInformationDefinition aiDefinition) {
+ private void populateParameterNodeWithParameters(AdditionalInfoParameterData parameterData, AdditionalInformationDefinition aiDefinition) {
if (aiDefinition != null) {
Integer lastCreatedCounter = aiDefinition.getLastCreatedCounter();
parameterData.getAdditionalInfoParameterDataDefinition().setLastCreatedCounter(lastCreatedCounter);
- log.trace("Set last created counter of additional information to " + lastCreatedCounter);
+ log.trace("Set last created counter of additional information to {}", lastCreatedCounter);
List<AdditionalInfoParameterInfo> parameters = aiDefinition.getParameters();
if (parameters != null) {
@@ -435,26 +382,22 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe
}
@Override
- public TitanOperationStatus findResourceAllAdditionalInformationRecursively(String uniqueId,
- List<AdditionalInformationDefinition> properties) {
+ public TitanOperationStatus findResourceAllAdditionalInformationRecursively(String uniqueId, List<AdditionalInformationDefinition> properties) {
- log.trace("Going to fetch additional information under resource " + uniqueId);
- TitanOperationStatus resourceCapabilitiesStatus = findAdditionalInformationOfNode(NodeTypeEnum.Resource,
- uniqueId, properties);
+ log.trace("Going to fetch additional information under resource {}", uniqueId);
+ TitanOperationStatus resourceCapabilitiesStatus = findAdditionalInformationOfNode(NodeTypeEnum.Resource, uniqueId, properties);
if (!resourceCapabilitiesStatus.equals(TitanOperationStatus.OK)) {
return resourceCapabilitiesStatus;
}
- Either<ImmutablePair<ResourceMetadataData, GraphEdge>, TitanOperationStatus> parentNodes = titanGenericDao
- .getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), uniqueId,
- GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.Resource, ResourceMetadataData.class);
+ Either<ImmutablePair<ResourceMetadataData, GraphEdge>, TitanOperationStatus> parentNodes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), uniqueId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.Resource,
+ ResourceMetadataData.class);
if (parentNodes.isRight()) {
TitanOperationStatus parentNodesStatus = parentNodes.right().value();
if (false == parentNodesStatus.equals(TitanOperationStatus.NOT_FOUND)) {
- log.error("Failed to find parent additional information of resource " + uniqueId + ". status is "
- + parentNodesStatus);
+ log.error("Failed to find parent additional information of resource {}. status is {}", uniqueId, parentNodesStatus);
return parentNodesStatus;
}
}
@@ -462,11 +405,10 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe
if (parentNodes.isLeft()) {
ImmutablePair<ResourceMetadataData, GraphEdge> parnetNodePair = parentNodes.left().value();
String parentUniqueId = parnetNodePair.getKey().getMetadataDataDefinition().getUniqueId();
- TitanOperationStatus addParentIntStatus = findResourceAllAdditionalInformationRecursively(parentUniqueId,
- properties);
+ TitanOperationStatus addParentIntStatus = findResourceAllAdditionalInformationRecursively(parentUniqueId, properties);
if (addParentIntStatus != TitanOperationStatus.OK) {
- log.error("Failed to find all resource additional information of resource " + parentUniqueId);
+ log.error("Failed to find all resource additional information of resource {}", parentUniqueId);
return addParentIntStatus;
}
}
@@ -475,26 +417,22 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe
}
@Override
- public TitanOperationStatus findServiceAllAdditionalInformationRecursively(String uniqueId,
- List<AdditionalInformationDefinition> properties) {
+ public TitanOperationStatus findServiceAllAdditionalInformationRecursively(String uniqueId, List<AdditionalInformationDefinition> properties) {
- log.trace("Going to fetch additional information under service " + uniqueId);
- TitanOperationStatus resourceCapabilitiesStatus = findAdditionalInformationOfNode(NodeTypeEnum.Service,
- uniqueId, properties);
+ log.trace("Going to fetch additional information under service {}", uniqueId);
+ TitanOperationStatus resourceCapabilitiesStatus = findAdditionalInformationOfNode(NodeTypeEnum.Service, uniqueId, properties);
if (!resourceCapabilitiesStatus.equals(TitanOperationStatus.OK)) {
return resourceCapabilitiesStatus;
}
- Either<ImmutablePair<ServiceMetadataData, GraphEdge>, TitanOperationStatus> parentNodes = titanGenericDao
- .getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Service), uniqueId,
- GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.Service, ServiceMetadataData.class);
+ Either<ImmutablePair<ServiceMetadataData, GraphEdge>, TitanOperationStatus> parentNodes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Service), uniqueId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.Service,
+ ServiceMetadataData.class);
if (parentNodes.isRight()) {
TitanOperationStatus parentNodesStatus = parentNodes.right().value();
if (false == parentNodesStatus.equals(TitanOperationStatus.NOT_FOUND)) {
- log.error("Failed to find parent additional information of resource " + uniqueId + ". status is "
- + parentNodesStatus);
+ log.error("Failed to find parent additional information of resource {}. status is {}", uniqueId, parentNodesStatus);
return parentNodesStatus;
}
}
@@ -502,11 +440,10 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe
if (parentNodes.isLeft()) {
ImmutablePair<ServiceMetadataData, GraphEdge> parnetNodePair = parentNodes.left().value();
String parentUniqueId = parnetNodePair.getKey().getMetadataDataDefinition().getUniqueId();
- TitanOperationStatus addParentIntStatus = findServiceAllAdditionalInformationRecursively(parentUniqueId,
- properties);
+ TitanOperationStatus addParentIntStatus = findServiceAllAdditionalInformationRecursively(parentUniqueId, properties);
if (addParentIntStatus != TitanOperationStatus.OK) {
- log.error("Failed to find all resource additional information of resource " + parentUniqueId);
+ log.error("Failed to find all resource additional information of resource {}", parentUniqueId);
return addParentIntStatus;
}
}
@@ -514,12 +451,10 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe
}
- private TitanOperationStatus findAdditionalInformationOfNode(NodeTypeEnum nodeType, String uniqueId,
- List<AdditionalInformationDefinition> properties) {
+ private TitanOperationStatus findAdditionalInformationOfNode(NodeTypeEnum nodeType, String uniqueId, List<AdditionalInformationDefinition> properties) {
- Either<ImmutablePair<AdditionalInfoParameterData, GraphEdge>, TitanOperationStatus> childNode = titanGenericDao
- .getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), uniqueId, GraphEdgeLabels.ADDITIONAL_INFORMATION,
- NodeTypeEnum.AdditionalInfoParameters, AdditionalInfoParameterData.class);
+ Either<ImmutablePair<AdditionalInfoParameterData, GraphEdge>, TitanOperationStatus> childNode = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), uniqueId, GraphEdgeLabels.ADDITIONAL_INFORMATION,
+ NodeTypeEnum.AdditionalInfoParameters, AdditionalInfoParameterData.class);
if (childNode.isRight()) {
TitanOperationStatus status = childNode.right().value();
@@ -534,8 +469,7 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe
Map<String, String> parameters = propertyData.getParameters();
if (parameters != null && false == parameters.isEmpty()) {
- AdditionalInformationDefinition additionalInfoDef = this
- .convertAdditionalInformationDataToDefinition(propertyData, uniqueId);
+ AdditionalInformationDefinition additionalInfoDef = this.convertAdditionalInformationDataToDefinition(propertyData, uniqueId);
properties.add(additionalInfoDef);
}
@@ -543,36 +477,29 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe
}
- private AdditionalInformationDefinition convertAdditionalInformationDataToDefinition(
- AdditionalInfoParameterData additionalInfoData, String uniqueId) {
+ private AdditionalInformationDefinition convertAdditionalInformationDataToDefinition(AdditionalInfoParameterData additionalInfoData, String uniqueId) {
Map<String, String> parameters = additionalInfoData.getParameters();
Map<String, String> idToKey = additionalInfoData.getIdToKey();
- AdditionalInformationDefinition definition = new AdditionalInformationDefinition(
- additionalInfoData.getAdditionalInfoParameterDataDefinition(), uniqueId,
- convertParameters(parameters, idToKey));
+ AdditionalInformationDefinition definition = new AdditionalInformationDefinition(additionalInfoData.getAdditionalInfoParameterDataDefinition(), uniqueId, convertParameters(parameters, idToKey));
return definition;
}
@Override
- public Either<AdditionalInformationDefinition, StorageOperationStatus> createAdditionalInformationParameter(
- NodeTypeEnum nodeType, String resourceId, String key, String value, boolean inTransaction) {
+ public Either<AdditionalInformationDefinition, StorageOperationStatus> createAdditionalInformationParameter(NodeTypeEnum nodeType, String resourceId, String key, String value, boolean inTransaction) {
Either<AdditionalInformationDefinition, StorageOperationStatus> result = null;
try {
- Either<AdditionalInformationDefinition, TitanOperationStatus> either = this
- .addAdditionalInformationParameter(nodeType, resourceId, key, value);
+ Either<AdditionalInformationDefinition, TitanOperationStatus> either = this.addAdditionalInformationParameter(nodeType, resourceId, key, value);
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));
+ 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 {
AdditionalInformationDefinition additionalInformationDefinition = either.left().value();
@@ -587,18 +514,16 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe
}
@Override
- public Either<AdditionalInformationDefinition, StorageOperationStatus> updateAdditionalInformationParameter(
- NodeTypeEnum nodeType, String resourceId, String id, String key, String value, boolean inTransaction) {
+ public Either<AdditionalInformationDefinition, StorageOperationStatus> updateAdditionalInformationParameter(NodeTypeEnum nodeType, String resourceId, String id, String key, String value, boolean inTransaction) {
Either<AdditionalInformationDefinition, StorageOperationStatus> result = null;
try {
- Either<AdditionalInformationDefinition, TitanOperationStatus> either = this
- .updateAdditionalInformationParameter(nodeType, resourceId, id, key, value);
+ Either<AdditionalInformationDefinition, TitanOperationStatus> either = this.updateAdditionalInformationParameter(nodeType, resourceId, id, key, value);
if (either.isRight()) {
- log.info("Failed to update additional information property " + key + " to component " + resourceId);
+ log.info("Failed to update additional information property {} to component {}", key, resourceId);
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(either.right().value()));
} else {
AdditionalInformationDefinition additionalInformationDefinition = either.left().value();
@@ -614,18 +539,16 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe
}
@Override
- public Either<AdditionalInformationDefinition, StorageOperationStatus> deleteAdditionalInformationParameter(
- NodeTypeEnum nodeType, String resourceId, String id, boolean inTransaction) {
+ public Either<AdditionalInformationDefinition, StorageOperationStatus> deleteAdditionalInformationParameter(NodeTypeEnum nodeType, String resourceId, String id, boolean inTransaction) {
Either<AdditionalInformationDefinition, StorageOperationStatus> result = null;
try {
- Either<AdditionalInformationDefinition, TitanOperationStatus> either = this
- .deleteAdditionalInformationParameter(nodeType, resourceId, id);
+ Either<AdditionalInformationDefinition, TitanOperationStatus> either = this.deleteAdditionalInformationParameter(nodeType, resourceId, id);
if (either.isRight()) {
- log.error("Failed to delete additional information id " + id + " to component " + resourceId);
+ log.error("Failed to delete additional information id {} to component {}", id, resourceId);
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(either.right().value()));
} else {
AdditionalInformationDefinition additionalInformationDefinition = either.left().value();
@@ -641,8 +564,7 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe
}
@Override
- public Either<Integer, StorageOperationStatus> getNumberOfAdditionalInformationParameters(NodeTypeEnum nodeType,
- String resourceId, boolean inTransaction) {
+ public Either<Integer, StorageOperationStatus> getNumberOfAdditionalInformationParameters(NodeTypeEnum nodeType, String resourceId, boolean inTransaction) {
Either<Integer, StorageOperationStatus> result = null;
@@ -651,7 +573,7 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe
Either<Integer, TitanOperationStatus> either = this.getNumberOfParameters(nodeType, resourceId);
if (either.isRight()) {
- log.error("Failed to get the number of additional information properties in component " + resourceId);
+ log.error("Failed to get the number of additional information properties in component {}", resourceId);
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(either.right().value()));
} else {
Integer counter = either.left().value();
@@ -676,10 +598,8 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe
@Override
public Either<Integer, TitanOperationStatus> getNumberOfParameters(NodeTypeEnum nodeType, String resourceId) {
- Either<ImmutablePair<AdditionalInfoParameterData, GraphEdge>, TitanOperationStatus> getResult = titanGenericDao
- .getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), resourceId,
- GraphEdgeLabels.ADDITIONAL_INFORMATION, NodeTypeEnum.AdditionalInfoParameters,
- AdditionalInfoParameterData.class);
+ Either<ImmutablePair<AdditionalInfoParameterData, GraphEdge>, TitanOperationStatus> getResult = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), resourceId, GraphEdgeLabels.ADDITIONAL_INFORMATION,
+ NodeTypeEnum.AdditionalInfoParameters, AdditionalInfoParameterData.class);
if (getResult.isRight()) {
TitanOperationStatus status = getResult.right().value();
@@ -700,18 +620,15 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe
}
@Override
- public Either<AdditionalInfoParameterInfo, TitanOperationStatus> getAdditionalInformationParameter(
- NodeTypeEnum nodeType, String componentId, String id) {
+ public Either<AdditionalInfoParameterInfo, TitanOperationStatus> getAdditionalInformationParameter(NodeTypeEnum nodeType, String componentId, String id) {
TitanOperationStatus verifyNodeTypeVsComponent = verifyNodeTypeVsComponent(nodeType, componentId);
if (verifyNodeTypeVsComponent != TitanOperationStatus.OK) {
return Either.right(verifyNodeTypeVsComponent);
}
- Either<ImmutablePair<AdditionalInfoParameterData, GraphEdge>, TitanOperationStatus> getResult = titanGenericDao
- .getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId,
- GraphEdgeLabels.ADDITIONAL_INFORMATION, NodeTypeEnum.AdditionalInfoParameters,
- AdditionalInfoParameterData.class);
+ Either<ImmutablePair<AdditionalInfoParameterData, GraphEdge>, TitanOperationStatus> getResult = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId, GraphEdgeLabels.ADDITIONAL_INFORMATION,
+ NodeTypeEnum.AdditionalInfoParameters, AdditionalInfoParameterData.class);
if (getResult.isRight()) {
TitanOperationStatus status = getResult.right().value();
@@ -730,19 +647,15 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe
String key = idToKey.get(id);
String value = parameters.get(key);
- log.trace("The key-value " + key + "=" + value + " was retrieved for id " + id);
+ log.trace("The key-value {} = {} was retrieved for id {}", key, value, id);
- Either<AdditionalInfoParameterData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(parameterData,
- AdditionalInfoParameterData.class);
+ Either<AdditionalInfoParameterData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(parameterData, AdditionalInfoParameterData.class);
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));
+ 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);
}
@@ -754,8 +667,7 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe
}
@Override
- public Either<AdditionalInformationDefinition, TitanOperationStatus> getAllAdditionalInformationParameters(
- NodeTypeEnum nodeType, String componentId, boolean ignoreVerification) {
+ public Either<AdditionalInformationDefinition, TitanOperationStatus> getAllAdditionalInformationParameters(NodeTypeEnum nodeType, String componentId, boolean ignoreVerification) {
if (false == ignoreVerification) {
TitanOperationStatus verifyNodeTypeVsComponent = verifyNodeTypeVsComponent(nodeType, componentId);
@@ -764,19 +676,14 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe
}
}
- Either<ImmutablePair<AdditionalInfoParameterData, GraphEdge>, TitanOperationStatus> getResult = titanGenericDao
- .getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId,
- GraphEdgeLabels.ADDITIONAL_INFORMATION, NodeTypeEnum.AdditionalInfoParameters,
- AdditionalInfoParameterData.class);
+ Either<ImmutablePair<AdditionalInfoParameterData, GraphEdge>, TitanOperationStatus> getResult = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId, GraphEdgeLabels.ADDITIONAL_INFORMATION,
+ NodeTypeEnum.AdditionalInfoParameters, AdditionalInfoParameterData.class);
if (getResult.isRight()) {
TitanOperationStatus status = getResult.right().value();
if (status != TitanOperationStatus.NOT_FOUND) {
- 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));
+ 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);
}
@@ -786,23 +693,20 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe
Map<String, String> parameters = parameterData.getParameters();
Map<String, String> idToKey = parameterData.getIdToKey();
- AdditionalInformationDefinition informationDefinition = createInformationDefinitionFromNode(componentId,
- parameters, idToKey, parameterData);
+ AdditionalInformationDefinition informationDefinition = createInformationDefinitionFromNode(componentId, parameters, idToKey, parameterData);
return Either.left(informationDefinition);
}
@Override
- public Either<AdditionalInformationDefinition, StorageOperationStatus> getAllAdditionalInformationParameters(
- NodeTypeEnum nodeType, String resourceId, boolean ignoreVerification, boolean inTransaction) {
+ public Either<AdditionalInformationDefinition, StorageOperationStatus> getAllAdditionalInformationParameters(NodeTypeEnum nodeType, String resourceId, boolean ignoreVerification, boolean inTransaction) {
Either<AdditionalInformationDefinition, StorageOperationStatus> result = null;
try {
- Either<AdditionalInformationDefinition, TitanOperationStatus> either = this
- .getAllAdditionalInformationParameters(nodeType, resourceId, ignoreVerification);
+ Either<AdditionalInformationDefinition, TitanOperationStatus> either = this.getAllAdditionalInformationParameters(nodeType, resourceId, ignoreVerification);
if (either.isRight()) {
TitanOperationStatus status = either.right().value();
@@ -833,8 +737,7 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe
}
}
- private void commitOrRollbackTx(TitanTransaction tx, boolean inTransaction,
- Either<? extends Object, StorageOperationStatus> result) {
+ private void commitOrRollbackTx(TitanTransaction tx, boolean inTransaction, Either<? extends Object, StorageOperationStatus> result) {
if (false == inTransaction) {
if (result == null || result.isRight()) {
@@ -848,19 +751,16 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe
}
@Override
- public Either<AdditionalInfoParameterInfo, StorageOperationStatus> getAdditionalInformationParameter(
- NodeTypeEnum nodeType, String resourceId, String id, boolean inTransaction) {
+ public Either<AdditionalInfoParameterInfo, StorageOperationStatus> getAdditionalInformationParameter(NodeTypeEnum nodeType, String resourceId, String id, boolean inTransaction) {
Either<AdditionalInfoParameterInfo, StorageOperationStatus> result = null;
try {
- Either<AdditionalInfoParameterInfo, TitanOperationStatus> either = this
- .getAdditionalInformationParameter(nodeType, resourceId, id);
+ Either<AdditionalInfoParameterInfo, TitanOperationStatus> either = this.getAdditionalInformationParameter(nodeType, resourceId, id);
if (either.isRight()) {
- log.error("Failed to fetch additional information property with id " + id + " of component "
- + resourceId);
+ log.error("Failed to fetch additional information property with id {} of component {}", id, resourceId);
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(either.right().value()));
} else {
AdditionalInfoParameterInfo additionalInformationDefinition = either.left().value();
@@ -875,30 +775,22 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe
}
@Override
- public Either<AdditionalInformationDefinition, StorageOperationStatus> deleteAllAdditionalInformationParameters(
- NodeTypeEnum nodeType, String resourceId, boolean inTransaction) {
+ public Either<AdditionalInformationDefinition, StorageOperationStatus> deleteAllAdditionalInformationParameters(NodeTypeEnum nodeType, String resourceId, boolean inTransaction) {
Either<AdditionalInformationDefinition, StorageOperationStatus> result = null;
try {
- Either<ImmutablePair<AdditionalInfoParameterData, GraphEdge>, TitanOperationStatus> getResult = titanGenericDao
- .getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), resourceId,
- GraphEdgeLabels.ADDITIONAL_INFORMATION, NodeTypeEnum.AdditionalInfoParameters,
- AdditionalInfoParameterData.class);
+ Either<ImmutablePair<AdditionalInfoParameterData, GraphEdge>, TitanOperationStatus> getResult = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), resourceId, GraphEdgeLabels.ADDITIONAL_INFORMATION,
+ NodeTypeEnum.AdditionalInfoParameters, AdditionalInfoParameterData.class);
if (getResult.isRight()) {
TitanOperationStatus status = getResult.right().value();
if (status == TitanOperationStatus.NOT_FOUND) {
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));
+ 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));
}
return result;
@@ -907,21 +799,16 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe
ImmutablePair<AdditionalInfoParameterData, GraphEdge> value = getResult.left().value();
AdditionalInfoParameterData parameterData = value.getLeft();
- Either<AdditionalInfoParameterData, TitanOperationStatus> deleteNodeRes = titanGenericDao
- .deleteNode(parameterData, AdditionalInfoParameterData.class);
+ 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));
+ 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;
}
- AdditionalInformationDefinition informationDefinition = convertAdditionalInformationDataToDefinition(
- deleteNodeRes.left().value(), resourceId);
+ AdditionalInformationDefinition informationDefinition = convertAdditionalInformationDataToDefinition(deleteNodeRes.left().value(), resourceId);
result = Either.left(informationDefinition);
@@ -933,8 +820,7 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe
}
private TitanOperationStatus verifyNodeTypeVsComponent(NodeTypeEnum nodeType, String componentId) {
- Either<TitanVertex, TitanOperationStatus> vertexByProperty = titanGenericDao
- .getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId);
+ Either<TitanVertex, TitanOperationStatus> vertexByProperty = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId);
if (vertexByProperty.isRight()) {
TitanOperationStatus status = vertexByProperty.right().value();
if (status == TitanOperationStatus.NOT_FOUND) {
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 a4f4bebd5a..1e1c9267e6 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
@@ -28,7 +28,6 @@ import java.util.List;
import java.util.Map;
import java.util.UUID;
-import com.thinkaurelius.titan.core.TitanTransaction;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Edge;
@@ -81,6 +80,8 @@ public class ArtifactOperation implements IArtifactOperation {
@javax.annotation.Resource
private GroupOperation groupOperation;
+ @javax.annotation.Resource
+ private GroupInstanceOperation groupInstanceOperation;
private static Logger log = LoggerFactory.getLogger(ArtifactOperation.class.getName());
@@ -113,7 +114,7 @@ public class ArtifactOperation implements IArtifactOperation {
if (false == inTransaction) {
titanGenericDao.rollback();
}
- log.debug("Failed to add artifact {} to {} {}", artifactInfo.getArtifactName(), type, parentId);
+ log.debug("Failed to add artifact {} to {} {}", artifactInfo.getArtifactName(), type , parentId);
return Either.right(status.right().value());
} else {
if (false == inTransaction) {
@@ -191,7 +192,7 @@ public class ArtifactOperation implements IArtifactOperation {
// add heat parameters
if (artifactInfo.getHeatParameters() != null && !artifactInfo.getHeatParameters().isEmpty() && !artifactInfo.getArtifactType().equals(ArtifactTypeEnum.HEAT_ENV.getType())) {
- StorageOperationStatus addPropertiesStatus = heatParametersOperation.addPropertiesToGraph(artifactInfo.getHeatParameters(), artifactData.getUniqueId().toString(), NodeTypeEnum.ArtifactRef);
+ StorageOperationStatus addPropertiesStatus = heatParametersOperation.addPropertiesToGraph(artifactInfo.getListHeatParameters(), artifactData.getUniqueId().toString(), NodeTypeEnum.ArtifactRef);
if (addPropertiesStatus != StorageOperationStatus.OK) {
log.debug("Failed to create heat parameters on graph for artifact {}", artifactInfo.getArtifactName());
return addPropertiesStatus;
@@ -238,7 +239,7 @@ public class ArtifactOperation implements IArtifactOperation {
if (existArtifact.isRight()) {
if (existArtifact.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
// create new node
- log.debug("Before adding artifact to graph {}", artifactData);
+ log.debug("Before adding artifact to graph {}" , artifactData);
if (artifactData.getArtifactDataDefinition().getArtifactUUID() == null || artifactData.getArtifactDataDefinition().getArtifactUUID().isEmpty())
updateUUID(artifactData.getArtifactDataDefinition(), null, artifactData.getArtifactDataDefinition().getArtifactVersion());
Either<ArtifactData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(artifactData, ArtifactData.class);
@@ -256,7 +257,7 @@ public class ArtifactOperation implements IArtifactOperation {
// add heat parameters
if (artifactInfo.getHeatParameters() != null && !artifactInfo.getHeatParameters().isEmpty() && !artifactInfo.getArtifactType().equals(ArtifactTypeEnum.HEAT_ENV.getType())) {
- StorageOperationStatus addPropertiesStatus = heatParametersOperation.addPropertiesToGraph(artifactInfo.getHeatParameters(), artifactData.getUniqueId().toString(), NodeTypeEnum.ArtifactRef);
+ StorageOperationStatus addPropertiesStatus = heatParametersOperation.addPropertiesToGraph(artifactInfo.getListHeatParameters(), artifactData.getUniqueId().toString(), NodeTypeEnum.ArtifactRef);
if (addPropertiesStatus != StorageOperationStatus.OK) {
log.debug("Failed to create heat parameters on graph for artifact {}", artifactInfo.getArtifactName());
return Either.right(addPropertiesStatus);
@@ -283,7 +284,7 @@ public class ArtifactOperation implements IArtifactOperation {
properties.put(GraphEdgePropertiesDictionary.GROUP_TYPE.getProperty(), artifactInfo.getArtifactGroupType().getType());
Either<GraphRelation, TitanOperationStatus> relation = titanGenericDao.createRelation(parent, artifactData, GraphEdgeLabels.ARTIFACT_REF, properties);
if (relation.isRight()) {
- log.debug("Failed to create relation in graph for id {} to new artifact", id);
+ log.debug("Failed to create relation in graph fro id {} to new artifact", id);
return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(relation.right().value()));
}
@@ -300,19 +301,20 @@ public class ArtifactOperation implements IArtifactOperation {
isValid = true;
break;
default:
- log.debug("Not supported node type for artifact relation : {}", type);
+ log.debug("Not supported node type for artifact relation : {} ", type);
}
return isValid;
}
-
+
+
protected ArtifactDefinition convertArtifactDataToArtifactDefinition(ArtifactData artifactDefResult) {
- log.debug("The object returned after create property is {}", artifactDefResult);
+ log.debug("The object returned after create property is {}" ,artifactDefResult);
ArtifactDefinition propertyDefResult = new ArtifactDefinition(artifactDefResult.getArtifactDataDefinition());
List<HeatParameterDefinition> parameters = new ArrayList<HeatParameterDefinition>();
StorageOperationStatus heatParametersOfNode = heatParametersOperation.getHeatParametersOfNode(NodeTypeEnum.ArtifactRef, artifactDefResult.getUniqueId().toString(), parameters);
if ((heatParametersOfNode.equals(StorageOperationStatus.OK)) && !parameters.isEmpty()) {
- propertyDefResult.setHeatParameters(parameters);
+ propertyDefResult.setListHeatParameters(parameters);
}
return propertyDefResult;
}
@@ -325,9 +327,35 @@ public class ArtifactOperation implements IArtifactOperation {
if (false == inTransaction) {
titanGenericDao.rollback();
}
- if (log.isDebugEnabled()){
- log.debug("Failed to update artifact {} of {} {}. Status is {}", artifactId, type.getName(), id, status.right().value());
+ log.debug("Failed to update artifact {} of {} {}. status is {}", artifactId, type.getName(), id, status.right().value());
+ BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedUpdateNodeError, "Failed to update artifact " + artifactId + " of " + type.getName() + " " + id + ". status is" + status.right().value(), artifactId,
+ String.valueOf(status.right().value()));
+ BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("Update Artifact", artifactId, String.valueOf(status.right().value()));
+ return Either.right(status.right().value());
+ } else {
+ if (false == inTransaction) {
+ titanGenericDao.commit();
}
+ ArtifactData artifactData = status.left().value();
+
+ ArtifactDefinition artifactDefResult = convertArtifactDataToArtifactDefinition(artifactData);
+ log.debug("The returned ArtifactDefintion is {}", artifactDefResult);
+ return Either.left(artifactDefResult);
+ }
+ }
+
+ @Override
+ public Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvArtifact( String id, ArtifactDefinition artifactEnvInfo, String artifactId, String newArtifactId, NodeTypeEnum type, boolean inTransaction){
+
+
+ Either<ArtifactData, StorageOperationStatus> status = dissociateAndAssociateHeatEnvArtifact(id, artifactEnvInfo, artifactId, newArtifactId, type, inTransaction);
+
+
+ if (status.isRight()) {
+ if (false == inTransaction) {
+ titanGenericDao.rollback();
+ }
+ log.debug("Failed to update artifact {} of {} {}. status is {}", artifactId, type.getName(), id, status.right().value());
BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedUpdateNodeError, "Failed to update artifact " + artifactId + " of " + type.getName() + " " + id + ". status is" + status.right().value(), artifactId,
String.valueOf(status.right().value()));
BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("Update Artifact", artifactId, String.valueOf(status.right().value()));
@@ -342,6 +370,47 @@ public class ArtifactOperation implements IArtifactOperation {
log.debug("The returned ArtifactDefintion is {}", artifactDefResult);
return Either.left(artifactDefResult);
}
+
+ }
+
+ private Either<ArtifactData, StorageOperationStatus> dissociateAndAssociateHeatEnvArtifact(String id, ArtifactDefinition artifactEnvInfo, String artifactId, String newArtifactId, NodeTypeEnum type, boolean inTransaction) {
+
+ ArtifactDefinition heatEnvArt = artifactEnvInfo;
+ if(heatEnvArt == null ){
+ Either<ArtifactDefinition, StorageOperationStatus> heatEnvEither = getHeatEnvByGeneratedFromId(artifactId);
+ if (heatEnvEither.isRight()) {
+ log.error("No heat env artifact node for id = {} ", artifactId);
+ return Either.right(StorageOperationStatus.NOT_FOUND);
+ }
+ heatEnvArt = heatEnvEither.left().value();
+ }
+
+ Either<ArtifactData, StorageOperationStatus> status = updateArtifactOnGraph(heatEnvArt, heatEnvArt.getUniqueId(), type, id);
+ if(status.isRight()){
+ log.error("Failed to update heat env. status is {}", status.right().value());
+ return status;
+ }
+
+ UniqueIdData generatedFromArtifactNode = new UniqueIdData(NodeTypeEnum.ArtifactRef, heatEnvArt.getUniqueId());
+ UniqueIdData oldArtifactNode = new UniqueIdData(NodeTypeEnum.ArtifactRef, artifactId);
+
+ Either<GraphRelation, TitanOperationStatus> deleteRelation = titanGenericDao.deleteRelation(generatedFromArtifactNode, oldArtifactNode, GraphEdgeLabels.GENERATED_FROM);
+ if (deleteRelation.isRight()) {
+ TitanOperationStatus titanStatus = deleteRelation.right().value();
+ if (titanStatus == TitanOperationStatus.NOT_FOUND) {
+ titanStatus = TitanOperationStatus.INVALID_ID;
+ }
+ Either.right(titanStatus);
+ }
+
+ UniqueIdData newArtifactNode = new UniqueIdData(NodeTypeEnum.ArtifactRef, newArtifactId);
+
+ Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(generatedFromArtifactNode, newArtifactNode, GraphEdgeLabels.GENERATED_FROM, null);
+ if (createRelation.isRight()) {
+ log.error("Failed to create relation from heat_env {} to heat {}", newArtifactId, generatedFromArtifactNode);
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(createRelation.right().value()));
+ }
+ return status;
}
@Override
@@ -368,6 +437,45 @@ public class ArtifactOperation implements IArtifactOperation {
return Either.left(artifactDefResult);
}
}
+
+ @Override
+ public Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvPlaceholder(ArtifactDefinition artifactInfo, boolean inTransaction) {
+
+ updateVersionAndDate(artifactInfo, artifactInfo.getArtifactVersion());
+
+ Either<ArtifactData, TitanOperationStatus> status = updateArifactDataDefinition(artifactInfo);
+
+ if (status.isRight()) {
+ if (false == inTransaction) {
+ titanGenericDao.rollback();
+ }
+ log.debug("Failed to update artifact {}", artifactInfo.getUniqueId());
+ BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedUpdateNodeError, "Failed to update artifact " + artifactInfo.getUniqueId() + ". status is" + status.right().value(), artifactInfo.getUniqueId(),
+ String.valueOf(status.right().value()));
+ BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("Update Artifact", artifactInfo.getUniqueId(), String.valueOf(status.right().value()));
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status.right().value()));
+ } else {
+ if (false == inTransaction) {
+ titanGenericDao.commit();
+ }
+ ArtifactData artifactData = status.left().value();
+
+ ArtifactDefinition artifactDefResult = convertArtifactDataToArtifactDefinition(artifactData);
+ log.debug("The returned ArtifactDefintion is {}" , artifactDefResult);
+ return Either.left(artifactDefResult);
+ }
+ }
+
+ @Override
+ public Either<ArtifactDefinition, StorageOperationStatus> getHeatEnvByGeneratedFromId(String generatedFromId) {
+ String heatEnvId = generatedFromId.concat("env");
+ Either<ArtifactDefinition, StorageOperationStatus> heatEnvEither = getArtifactById(heatEnvId, true);
+ if (heatEnvEither.isRight()) {
+ log.error("No heat env artifact node for id = {} ", heatEnvId);
+ return Either.right(StorageOperationStatus.NOT_FOUND);
+ }
+ return heatEnvEither;
+ }
private Either<ArtifactData, TitanOperationStatus> updateArifactDataDefinition(ArtifactDefinition artifactInfo) {
Either<TitanGraph, TitanOperationStatus> graph = titanGenericDao.getGraph();
@@ -388,7 +496,7 @@ public class ArtifactOperation implements IArtifactOperation {
@Override
public Either<ArtifactDefinition, StorageOperationStatus> removeArifactFromResource(String id, String artifactId, NodeTypeEnum type, boolean deleteMandatoryArtifact, boolean inTransaction) {
- Either<ArtifactData, TitanOperationStatus> status = removeArtifactOnGraph(id, artifactId, type, id, deleteMandatoryArtifact);
+ Either<ArtifactData, TitanOperationStatus> status = removeArtifactOnGraph(id, artifactId, type, deleteMandatoryArtifact);
if (status.isRight()) {
if (false == inTransaction) {
@@ -406,7 +514,7 @@ public class ArtifactOperation implements IArtifactOperation {
ArtifactData artifactData = status.left().value();
ArtifactDefinition artifactDefResult = convertArtifactDataToArtifactDefinition(artifactData);
- log.debug("The returned ArtifactDefintion is {}", artifactDefResult);
+ log.debug("The returned ArtifactDefintion is {}" , artifactDefResult);
return Either.left(artifactDefResult);
}
}
@@ -447,12 +555,17 @@ public class ArtifactOperation implements IArtifactOperation {
}
++edgeCount;
}
+
+ if (isNeedUpdateHeatTime(artifactInfo)) {
+ artifactInfo.setHeatParamsUpdateDate(System.currentTimeMillis());
+ }
ArtifactData artifactData = new ArtifactData(artifactInfo);
if (edgeFromTo == null) {
log.debug("No relation between artifact = {} and node with id = {}", artifactId, id);
return Either.right(StorageOperationStatus.GENERAL_ERROR);
}
+
Either<Boolean, StorageOperationStatus> setRelevantHeatParamIdRes = null;
if (edgeCount > 1) {
// need to remove relation, create new node
@@ -477,6 +590,13 @@ public class ArtifactOperation implements IArtifactOperation {
BeEcompErrorManager.getInstance().logInternalFlowError("UpdateArtifact", "Failed to reassociate groups to the new artifact", ErrorSeverity.ERROR);
return Either.right(reassociateGroupsFromArtifact);
}
+
+ StorageOperationStatus reassociateGroupInstancesFromArtifact = groupInstanceOperation.dissociateAndAssociateGroupsInstanceFromArtifact(id, type, artifactId, addedArtifactRes.left().value());
+ if (reassociateGroupInstancesFromArtifact != StorageOperationStatus.OK) {
+ BeEcompErrorManager.getInstance().logInternalFlowError("UpdateArtifact", "Failed to reassociate group instances to the new artifact", ErrorSeverity.ERROR);
+ return Either.right(reassociateGroupsFromArtifact);
+ }
+
// If artifact is heat env
if (artifactInfo.getArtifactType().equals(ArtifactTypeEnum.HEAT_ENV.getType())) {
ArtifactData addedArtifact = addedArtifactRes.left().value();
@@ -485,13 +605,13 @@ public class ArtifactOperation implements IArtifactOperation {
setRelevantHeatParamIdRes = setRelevantHeatParamId(artifactV, artifactInfo);
if (setRelevantHeatParamIdRes.isRight()) {
- log.error("Failed to set relevant id to heat parameters for heat env artifact " + artifactInfo.getUniqueId() + ". Status is " + setRelevantHeatParamIdRes.right().value());
+ log.error("Failed to set relevant id to heat parameters for heat env artifact {}. Status is {}", artifactInfo.getUniqueId(), setRelevantHeatParamIdRes.right().value());
return Either.right(setRelevantHeatParamIdRes.right().value());
}
- for (HeatParameterDefinition heatEnvParam : artifactInfo.getHeatParameters()) {
+ for (HeatParameterDefinition heatEnvParam : artifactInfo.getListHeatParameters()) {
updateResult = heatParametersOperation.updateHeatParameterValue(heatEnvParam, newArtifactUniqueId, id, artifactInfo.getArtifactLabel());
if (updateResult.isRight()) {
- log.error("Failed to update heat parameter " + heatEnvParam.getName() + ". Status is " + updateResult.right().value());
+ log.error("Failed to update heat parameter {}. Status is {}", heatEnvParam.getName(), updateResult.right().value());
return Either.right(updateResult.right().value());
}
}
@@ -499,7 +619,7 @@ public class ArtifactOperation implements IArtifactOperation {
Iterator<Edge> iterEdgeGeneratedFrom = artifactV.edges(Direction.OUT, GraphEdgeLabels.GENERATED_FROM.getProperty());
if (!iterEdgeGeneratedFrom.hasNext()) {
- log.error("No heat artifact node for id = " + artifactId);
+ log.error("No heat artifact node for id = {}", artifactId);
return Either.right(StorageOperationStatus.NOT_FOUND);
}
Edge edgeToHeat = iterEdgeGeneratedFrom.next();
@@ -508,7 +628,7 @@ public class ArtifactOperation implements IArtifactOperation {
UniqueIdData generatedFromArtifactNode = new UniqueIdData(NodeTypeEnum.ArtifactRef, generatedFromArtifactId);
Either<GraphRelation, TitanOperationStatus> createRelationToGeneratedFromArtifactRes = titanGenericDao.createRelation(addedArtifact, generatedFromArtifactNode, GraphEdgeLabels.GENERATED_FROM, null);
if (createRelationToGeneratedFromArtifactRes.isRight()) {
- log.error("Failed to create relation from heat_env " + addedArtifact.getUniqueId() + " to heat " + generatedFromArtifactNode);
+ log.error("Failed to create relation from heat_env {} to heat {}", addedArtifact.getUniqueId(), generatedFromArtifactNode);
return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(createRelationToGeneratedFromArtifactRes.right().value()));
}
}
@@ -535,10 +655,10 @@ public class ArtifactOperation implements IArtifactOperation {
log.error("Failed to set relevant id to heat parameters for heat env artifact {}. Status is {}", artifactInfo.getUniqueId(), setRelevantHeatParamIdRes.right().value());
return Either.right(setRelevantHeatParamIdRes.right().value());
}
- for (HeatParameterDefinition heatEnvParam : artifactInfo.getHeatParameters()) {
+ for (HeatParameterDefinition heatEnvParam : artifactInfo.getListHeatParameters()) {
updateResult = heatParametersOperation.updateHeatParameterValue(heatEnvParam, artifactUniqueId, id, artifactInfo.getArtifactLabel());
if (updateResult.isRight()) {
- log.error("Failed to update heat parameter " + heatEnvParam.getName() + ". Status is " + updateResult.right().value());
+ log.error("Failed to update heat parameter {}. Status is {}", heatEnvParam.getName(), updateResult.right().value());
return Either.right(updateResult.right().value());
}
}
@@ -546,7 +666,7 @@ public class ArtifactOperation implements IArtifactOperation {
if (artifactData.getArtifactDataDefinition().getArtifactChecksum() == null) {
// update heat parameters only if it is not heat env
if (artifactInfo.getGeneratedFromId() == null) {
- StorageOperationStatus operationStatus = heatParametersOperation.updateHeatParameters(artifactInfo.getHeatParameters());
+ StorageOperationStatus operationStatus = heatParametersOperation.updateHeatParameters(artifactInfo.getListHeatParameters());
if (operationStatus != StorageOperationStatus.OK) {
return Either.right(operationStatus);
}
@@ -558,11 +678,12 @@ public class ArtifactOperation implements IArtifactOperation {
return Either.right(StorageOperationStatus.GENERAL_ERROR);
}
- StorageOperationStatus addParameters = heatParametersOperation.addPropertiesToGraph(artifactInfo.getHeatParameters(), artifactId, NodeTypeEnum.ArtifactRef);
+ StorageOperationStatus addParameters = heatParametersOperation.addPropertiesToGraph(artifactInfo.getListHeatParameters(), artifactId, NodeTypeEnum.ArtifactRef);
if (!addParameters.equals(StorageOperationStatus.OK)) {
log.debug("failed to update heat parameters for artifact id {}", artifactData.getUniqueId());
return Either.right(StorageOperationStatus.GENERAL_ERROR);
}
+
}
}
@@ -574,13 +695,20 @@ public class ArtifactOperation implements IArtifactOperation {
}
}
+ private boolean isNeedUpdateHeatTime(ArtifactDefinition artifactInfo) {
+ if (artifactInfo.getArtifactType().equals(ArtifactTypeEnum.HEAT.getType()) || artifactInfo.getArtifactType().equals(ArtifactTypeEnum.HEAT_NET.getType()) || artifactInfo.getArtifactType().equals(ArtifactTypeEnum.HEAT_VOL.getType())) {
+ return true;
+ }
+ return false;
+ }
+
private Either<Boolean, StorageOperationStatus> setRelevantHeatParamId(TitanVertex artifactV, ArtifactDefinition artifactInfo) {
Map<String, String> heatParametersHM = new HashMap<String, String>();
Iterator<Edge> iterHeat = artifactV.edges(Direction.OUT, GraphEdgeLabels.GENERATED_FROM.getProperty());
if (!iterHeat.hasNext()) {
- log.debug("No edges with label GENERATED_FROM for the node {}", artifactInfo.getUniqueId());
+ log.debug("No edges with label GENERATED_FROM for the node {}" , artifactInfo.getUniqueId());
return Either.right(StorageOperationStatus.NOT_FOUND);
}
Edge heat = iterHeat.next();
@@ -603,7 +731,7 @@ public class ArtifactOperation implements IArtifactOperation {
heatParametersHM.put(heatParam.getName(), (String) heatParam.getUniqueId());
}
String curName = null;
- for (HeatParameterDefinition heatEnvParam : artifactInfo.getHeatParameters()) {
+ for (HeatParameterDefinition heatEnvParam : artifactInfo.getListHeatParameters()) {
curName = heatEnvParam.getName();
if (heatParametersHM.containsKey(curName)) {
heatEnvParam.setUniqueId(heatParametersHM.get(curName));
@@ -635,7 +763,7 @@ public class ArtifactOperation implements IArtifactOperation {
return Either.left(edgeCount);
}
- public Either<ArtifactData, TitanOperationStatus> removeArtifactOnGraph(String id, String artifactId, NodeTypeEnum type, String id2, boolean deleteMandatoryArtifact) {
+ public Either<ArtifactData, TitanOperationStatus> removeArtifactOnGraph(String id, String artifactId, NodeTypeEnum type, boolean deleteMandatoryArtifact) {
Either<TitanGraph, TitanOperationStatus> graph = titanGenericDao.getGraph();
if (graph.isRight()) {
return Either.right(graph.right().value());
@@ -675,7 +803,7 @@ public class ArtifactOperation implements IArtifactOperation {
++edgeCount;
}
if (edgeFromTo == null) {
- log.debug("No relation between artifact = {} and node with id = {}", artifactId, id);
+ log.debug("No relation between artifact = {} and node with id = {}", artifactId, id);
return Either.right(TitanOperationStatus.GENERAL_ERROR);
}
@@ -702,13 +830,13 @@ public class ArtifactOperation implements IArtifactOperation {
log.debug("Remove artifactRef node from graph");
Either<List<HeatParameterDefinition>, StorageOperationStatus> deleteStatus = heatParametersOperation.deleteAllHeatParametersAssociatedToNode(NodeTypeEnum.ArtifactRef, artifactId);
if (deleteStatus.isRight()) {
- log.error("failed to delete heat parameters of artifact " + artifactId);
+ log.error("failed to delete heat parameters of artifact {}", artifactId);
return Either.right(TitanOperationStatus.GENERAL_ERROR);
}
StorageOperationStatus deleteValuesStatus = heatParametersOperation.deleteAllHeatValuesAssociatedToNode(NodeTypeEnum.ArtifactRef, artifactId);
if (!deleteValuesStatus.equals(StorageOperationStatus.OK)) {
- log.error("failed to delete heat values of artifact " + artifactId);
+ log.error("failed to delete heat values of artifact {}", artifactId);
return Either.right(TitanOperationStatus.GENERAL_ERROR);
}
if (!isMandatory) {
@@ -764,6 +892,12 @@ public class ArtifactOperation implements IArtifactOperation {
if (artifact != null) {
ArtifactDefinition artifactDefinition = new ArtifactDefinition(artifact.getArtifactDataDefinition());
+ Iterator<Edge> edgesGeneratedFrom = artifactV.edges(Direction.OUT, GraphEdgeLabels.GENERATED_FROM.getProperty());
+ if (edgesGeneratedFrom != null && edgesGeneratedFrom.hasNext()) {
+ TitanVertex inVertex = (TitanVertex) edgesGeneratedFrom.next().inVertex();
+ String artifactIdGeneratedFrom = (String) titanGenericDao.getProperty(inVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty());
+ artifactDefinition.setGeneratedFromId(artifactIdGeneratedFrom);
+ }
List<HeatParameterDefinition> heatParams = new ArrayList<HeatParameterDefinition>();
StorageOperationStatus heatParametersStatus = heatParametersOperation.getHeatParametersOfNode(NodeTypeEnum.ArtifactRef, artifactDefinition.getUniqueId(), heatParams);
if (!heatParametersStatus.equals(StorageOperationStatus.OK)) {
@@ -771,7 +905,7 @@ public class ArtifactOperation implements IArtifactOperation {
return Either.right(heatParametersStatus);
}
if (!heatParams.isEmpty()) {
- artifactDefinition.setHeatParameters(heatParams);
+ artifactDefinition.setListHeatParameters(heatParams);
}
artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
log.debug("Artifact was added to list {}", artifact.getUniqueId());
@@ -867,7 +1001,7 @@ public class ArtifactOperation implements IArtifactOperation {
return Either.right(heatParametersStatus);
}
if (!heatParams.isEmpty()) {
- artifactDef.setHeatParameters(heatParams);
+ artifactDef.setListHeatParameters(heatParams);
}
Either<ImmutablePair<ArtifactData, GraphEdge>, TitanOperationStatus> generatedFromArtifact = titanGenericDao.getChild(artifactData.getUniqueIdKey(), (String) artifactData.getUniqueId(), GraphEdgeLabels.GENERATED_FROM,
@@ -882,7 +1016,7 @@ public class ArtifactOperation implements IArtifactOperation {
log.debug("failed to get heat parameters values for heat artifact {}", artifactDef.getUniqueId());
return Either.right(heatParamsForEnv.right().value());
} else {
- artifactDef.setHeatParameters(heatParamsForEnv.left().value());
+ artifactDef.setListHeatParameters(heatParamsForEnv.left().value());
}
}
@@ -1003,7 +1137,7 @@ public class ArtifactOperation implements IArtifactOperation {
return Either.right(heatParametersStatus);
}
if (!heatParams.isEmpty()) {
- artifactDefinition.setHeatParameters(heatParams);
+ artifactDefinition.setListHeatParameters(heatParams);
}
Either<ImmutablePair<ArtifactData, GraphEdge>, TitanOperationStatus> getResult = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef), artifactDefinition.getUniqueId(), GraphEdgeLabels.GENERATED_FROM,
@@ -1039,45 +1173,40 @@ public class ArtifactOperation implements IArtifactOperation {
}
@Override
- public Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv, ArtifactDefinition artifactHeat, String parentId, NodeTypeEnum parentType, boolean inTransaction) {
-
- Either<ArtifactDefinition, StorageOperationStatus> result = null;
- try {
- Either<ArtifactDefinition, StorageOperationStatus> heatArtifactOnGraph = addArifactToComponent(artifactHeatEnv, parentId, parentType, true, true);
-
- if (heatArtifactOnGraph.isRight()) {
- log.debug("failed to create heat env artifact on graph");
- result = heatArtifactOnGraph;
- return result;
- }
-
- ArtifactDefinition artifactDefinition = heatArtifactOnGraph.left().value();
+ public Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv, ArtifactDefinition artifactHeat, String parentId, NodeTypeEnum parentType, boolean failIfExist) {
- // add relation from heatEnv to heat
- UniqueIdData heatData = new UniqueIdData(NodeTypeEnum.ArtifactRef, artifactHeat.getUniqueId());
- UniqueIdData heatEnvData = new UniqueIdData(NodeTypeEnum.ArtifactRef, artifactDefinition.getUniqueId());
- Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(heatEnvData, heatData, GraphEdgeLabels.GENERATED_FROM, null);
-
- if (createRelation.isRight()) {
- TitanOperationStatus status = createRelation.right().value();
- log.debug("failed to add relation from heat_env artifact to heat artifact. error: {}", status);
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- return result;
- }
- artifactDefinition.setGeneratedFromId(artifactHeat.getUniqueId());
- log.trace("heat env artifact added successfuly to resource instance");
- result = Either.left(artifactDefinition);
+ Either<ArtifactDefinition, StorageOperationStatus> result = null;
+ Either<ArtifactDefinition, StorageOperationStatus> heatArtifactOnGraph = addArifactToComponent(artifactHeatEnv, parentId, parentType, failIfExist, true);
+ if (heatArtifactOnGraph.isRight()) {
+ log.debug("failed to create heat env artifact on graph");
+ result = heatArtifactOnGraph;
return result;
- } finally {
- if (inTransaction == false) {
- if (result == null || result.isRight()) {
- this.titanGenericDao.rollback();
- } else {
- this.titanGenericDao.commit();
- }
-
- }
}
+
+ ArtifactDefinition artifactDefinition = heatArtifactOnGraph.left().value();
+ // add relation from heatEnv to heat
+ UniqueIdData heatData = new UniqueIdData(NodeTypeEnum.ArtifactRef, artifactHeat.getUniqueId());
+ UniqueIdData heatEnvData = new UniqueIdData(NodeTypeEnum.ArtifactRef, artifactDefinition.getUniqueId());
+
+ Either<GraphRelation, TitanOperationStatus> relation = titanGenericDao.getRelation(heatEnvData, heatData, GraphEdgeLabels.GENERATED_FROM);
+ if (relation.isRight()) {
+ // TODO: add error in case of error
+ TitanOperationStatus status = relation.right().value();
+ if (status == TitanOperationStatus.NOT_FOUND) {
+ Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(heatEnvData, heatData, GraphEdgeLabels.GENERATED_FROM, null);
+ if (createRelation.isRight()) {
+ status = createRelation.right().value();
+ log.debug("failed to add relation from heat_env artifact to heat artifact. error: {}", status);
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ return result;
+ }
+ }
+ }
+
+ artifactDefinition.setGeneratedFromId(artifactHeat.getUniqueId());
+ log.trace("heat env artifact added successfuly to resource instance");
+ result = Either.left(artifactDefinition);
+ return result;
}
public void updateUUID(ArtifactDataDefinition artifactData, String oldChecksum, String oldVesrion) {
@@ -1100,6 +1229,10 @@ public class ArtifactOperation implements IArtifactOperation {
UUID uuid = UUID.randomUUID();
artifactData.setArtifactUUID(uuid.toString());
MDC.put("serviceInstanceID", uuid.toString());
+ updateVersionAndDate(artifactData, oldVesrion);
+ }
+
+ private void updateVersionAndDate(ArtifactDataDefinition artifactData, String oldVesrion) {
long time = System.currentTimeMillis();
artifactData.setPayloadUpdateDate(time);
int newVersion = new Integer(oldVesrion).intValue();
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AttributeOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AttributeOperation.java
index fc81a9affd..f82a2982b0 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AttributeOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AttributeOperation.java
@@ -239,9 +239,9 @@ public class AttributeOperation extends AbstractOperation implements IAttributeO
List<ComponentInstanceAttribute> buildAttInstanceFromResource = attributes.stream().map(attDef -> new ComponentInstanceAttribute(attDef, false, null)).collect(Collectors.toList());
// Set Value to be default value in case it is empty
- Consumer<ComponentInstanceAttribute> valueSetter = data -> {
- if (StringUtils.isEmpty(data.getValue())) {
- data.setValue(data.getDefaultValue());
+ Consumer<ComponentInstanceAttribute> valueSetter = att -> {
+ if (StringUtils.isEmpty(att.getValue())) {
+ att.setValue(att.getDefaultValue());
}
};
buildAttInstanceFromResource.stream().forEach(valueSetter);
@@ -438,7 +438,7 @@ public class AttributeOperation extends AbstractOperation implements IAttributeO
Either<AttributeData, TitanOperationStatus> eitherResult;
StorageOperationStatus validateAndUpdateAttribute = propertyOperation.validateAndUpdateProperty(attribute, dataTypes);
if (validateAndUpdateAttribute != StorageOperationStatus.OK) {
- log.error("Attribute " + attribute + " is invalid. Status is " + validateAndUpdateAttribute);
+ log.error("Attribute {} is invalid. Status is {}", attribute, validateAndUpdateAttribute);
eitherResult = Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
} else {
eitherResult = addAttributeToNodeType(attribute, NodeTypeEnum.Resource, resourceId);
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CacheMangerOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CacheMangerOperation.java
index d05255473d..cadcd32926 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CacheMangerOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CacheMangerOperation.java
@@ -31,10 +31,8 @@ import org.openecomp.sdc.be.model.cache.jobs.*;
import org.openecomp.sdc.be.model.cache.workers.CacheWorker;
import org.openecomp.sdc.be.model.cache.workers.IWorker;
import org.openecomp.sdc.be.model.cache.workers.SyncWorker;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
import org.openecomp.sdc.be.model.operations.api.ICacheMangerOperation;
-import org.openecomp.sdc.be.model.operations.api.IProductOperation;
-import org.openecomp.sdc.be.model.operations.api.IResourceOperation;
-import org.openecomp.sdc.be.model.operations.api.IServiceOperation;
import org.openecomp.sdc.be.workers.Manager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -47,18 +45,12 @@ import java.util.LinkedList;
import java.util.concurrent.*;
/**
- * Created by mlando on 9/5/2016. the class is responsible for handling all
- * cache update operations asynchronously including sync between the graph and
- * cache and on demand update requests
+ * Created by mlando on 9/5/2016. the class is responsible for handling all cache update operations asynchronously including sync between the graph and cache and on demand update requests
*/
@Component("cacheManger-operation")
public class CacheMangerOperation implements ICacheMangerOperation {
@Autowired
- private IResourceOperation iResourceOperation;
- @Autowired
- private IServiceOperation iServiceOperation;
- @Autowired
- private IProductOperation iProductOperation;
+ private ToscaOperationFacade toscaOperationFacade;
@Autowired
private TitanGenericDao titanGenericDao;
@Autowired
@@ -76,21 +68,17 @@ public class CacheMangerOperation implements ICacheMangerOperation {
* constructor
*/
public CacheMangerOperation() {
- // daoInfo = new DaoInfo(iResourceOperation, iServiceOperation,
- // iProductOperation, componentCache);
}
/**
- * the method checks in the cache is enabled, if it is, it initializes all
- * the workers according to the configuration values.
+ * the method checks in the cache is enabled, if it is, it initializes all the workers according to the configuration values.
*/
@PostConstruct
public void init() {
- daoInfo = new DaoInfo(iResourceOperation, iServiceOperation, iProductOperation, componentCache);
+ daoInfo = new DaoInfo(toscaOperationFacade, componentCache);
- Configuration.ApplicationL2CacheConfig applicationL2CacheConfig = ConfigurationManager.getConfigurationManager()
- .getConfiguration().getApplicationL2Cache();
+ Configuration.ApplicationL2CacheConfig applicationL2CacheConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getApplicationL2Cache();
if (applicationL2CacheConfig != null && applicationL2CacheConfig.isEnabled()) {
Integer numberOfWorkers = applicationL2CacheConfig.getQueue().getNumberOfCacheWorkers();
this.waitOnShutDownInMinutes = applicationL2CacheConfig.getQueue().getWaitOnShutDownInMinutes();
@@ -122,9 +110,7 @@ public class CacheMangerOperation implements ICacheMangerOperation {
}
/**
- * the method creates a job to check it the given component is in the cach
- * and if so is it valid if the value in the cache is not valid it will be
- * updated.
+ * the method creates a job to check it the given component is in the cach and if so is it valid if the value in the cache is not valid it will be updated.
*
* @param componentId
* the uid of the component we want to update
@@ -135,24 +121,21 @@ public class CacheMangerOperation implements ICacheMangerOperation {
*/
@Override
public void updateComponentInCache(String componentId, long timestamp, NodeTypeEnum nodeTypeEnum) {
- Configuration.ApplicationL2CacheConfig applicationL2CacheConfig = ConfigurationManager.getConfigurationManager()
- .getConfiguration().getApplicationL2Cache();
+ Configuration.ApplicationL2CacheConfig applicationL2CacheConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getApplicationL2Cache();
if (applicationL2CacheConfig != null && applicationL2CacheConfig.isEnabled()) {
this.jobQueue.add(new CheckAndUpdateJob(daoInfo, componentId, nodeTypeEnum, timestamp));
}
}
public void overideComponentInCache(String componentId, long timestamp, NodeTypeEnum nodeTypeEnum) {
- Configuration.ApplicationL2CacheConfig applicationL2CacheConfig = ConfigurationManager.getConfigurationManager()
- .getConfiguration().getApplicationL2Cache();
+ Configuration.ApplicationL2CacheConfig applicationL2CacheConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getApplicationL2Cache();
if (applicationL2CacheConfig != null && applicationL2CacheConfig.isEnabled()) {
this.jobQueue.add(new OverrideJob(daoInfo, componentId, nodeTypeEnum, timestamp));
}
}
public void deleteComponentInCache(String componentId, long timestamp, NodeTypeEnum nodeTypeEnum) {
- Configuration.ApplicationL2CacheConfig applicationL2CacheConfig = ConfigurationManager.getConfigurationManager()
- .getConfiguration().getApplicationL2Cache();
+ Configuration.ApplicationL2CacheConfig applicationL2CacheConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getApplicationL2Cache();
if (applicationL2CacheConfig != null && applicationL2CacheConfig.isEnabled()) {
this.jobQueue.add(new DeleteJob(daoInfo, componentId, nodeTypeEnum, timestamp));
}
@@ -168,17 +151,14 @@ public class CacheMangerOperation implements ICacheMangerOperation {
*/
@Override
public void storeComponentInCache(org.openecomp.sdc.be.model.Component component, NodeTypeEnum nodeTypeEnum) {
- Configuration.ApplicationL2CacheConfig applicationL2CacheConfig = ConfigurationManager.getConfigurationManager()
- .getConfiguration().getApplicationL2Cache();
+ Configuration.ApplicationL2CacheConfig applicationL2CacheConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getApplicationL2Cache();
if (applicationL2CacheConfig != null && applicationL2CacheConfig.isEnabled()) {
this.jobQueue.add(new StoreJob(daoInfo, component, nodeTypeEnum));
}
}
/**
- * the method shutdown's all the worker's. the method has a pre set of how
- * long it will wait for the workers to shutdown. the pre defined value is
- * taken from the configuration.
+ * the method shutdown's all the worker's. the method has a pre set of how long it will wait for the workers to shutdown. the pre defined value is taken from the configuration.
*/
@PreDestroy
public void shutDown() {
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityInstanceOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityInstanceOperation.java
index 0c4f35fd54..818089feee 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityInstanceOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityInstanceOperation.java
@@ -74,24 +74,6 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC
private CapabilityOperation capabilityOperation;
/**
- * String constants for logger
- */
- private String statusIs = ". status is ";
- private String dot = ".";
- private String onGraph = " on graph ";
- private String ofRI = " of resource instance ";
- private String toCapability = " to capability ";
- private String toCI = " to capability instance ";
- private String toProperty = " to property ";
- private String forRI = " for resource instance ";
- private String failedCreateCI = "Failed to create capability instance of capability ";
- private String failedAddProperties = "Failed to add properties to capability instance ";
- private String ofCI = " of component instance ";
- private String failedDeletePropertyValues = "Failed to delete property values of capability instance ";
- private String toValue = " to property value ";
- private String fromRI = " from resource instance ";
-
- /**
* create capability instance of capability with property values for resource instance
*
* @param resourceInstanceId
@@ -184,13 +166,13 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC
private Either<List<PropertyValueData>, TitanOperationStatus> addPropertyValueToCapabilityInstance(String resourceInstanceId, List<ComponentInstanceProperty> propertyValues, Wrapper<TitanOperationStatus> errorWrapper,
Either<CapabilityInstData, TitanOperationStatus> createCapabilityRes, Wrapper<Map<String, PropertyDefinition>> defaultPropertiesWrapper, Wrapper<String> createdCapabilityInstanceIdWrapper) {
Either<List<PropertyValueData>, TitanOperationStatus> addPropertyValuesRes;
- log.debug("Before adding property values to capability instance {} dot", createdCapabilityInstanceIdWrapper.getInnerElement());
+ log.debug("Before adding property values to capability instance {}.",createdCapabilityInstanceIdWrapper.getInnerElement());
addPropertyValuesRes = addPropertyValuesToCapabilityInstance(createCapabilityRes.left().value(), propertyValues, defaultPropertiesWrapper.getInnerElement());
if (addPropertyValuesRes.isRight()) {
errorWrapper.setInnerElement(addPropertyValuesRes.right().value());
- log.debug("failedAddProperties {} ofRI {} statusIs {} dot", createdCapabilityInstanceIdWrapper.getInnerElement(), resourceInstanceId, errorWrapper.getInnerElement());
+ log.debug("Failed to add properties to capability instance {} of resource instance {}. status is {}.", createdCapabilityInstanceIdWrapper.getInnerElement(), resourceInstanceId, errorWrapper.getInnerElement());
}
- log.debug("After adding property values to capability instance {} status is {}.", createdCapabilityInstanceIdWrapper.getInnerElement(), errorWrapper.getInnerElement());
+ log.debug("After adding property values to capability instance {}. status is {}.", createdCapabilityInstanceIdWrapper.getInnerElement(), errorWrapper.getInnerElement());
return addPropertyValuesRes;
}
@@ -200,9 +182,9 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC
TitanOperationStatus addPropertyValuesRes = addPropertyValuesToCapabilityInstance(createCapabilityRes.left().value(), propertyValues, defaultPropertiesWrapper.getInnerElement());
if (!addPropertyValuesRes.equals(TitanOperationStatus.OK)) {
errorWrapper.setInnerElement(addPropertyValuesRes);
- log.debug("Failed to add properties to capability instance {} {} {} {} {}", createdCapabilityInstanceIdWrapper.getInnerElement(), ofRI, resourceInstanceId, statusIs, errorWrapper.getInnerElement());
+ log.debug("Failed to add properties to capability instance {} of resource instance {}. status is {}", createdCapabilityInstanceIdWrapper.getInnerElement(), resourceInstanceId, errorWrapper.getInnerElement());
}
- log.trace("After adding property values to capability instance {} {} {}", createdCapabilityInstanceIdWrapper.getInnerElement(), statusIs, errorWrapper.getInnerElement());
+ log.trace("After adding property values to capability instance {}. status is {}", createdCapabilityInstanceIdWrapper.getInnerElement(), errorWrapper.getInnerElement());
return addPropertyValuesRes;
}
@@ -214,18 +196,19 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC
createdCapabilityInstanceIdWrapper.setInnerElement(createdCapabilityInstance.getUniqueId());
Map<String, PropertyDefinition> defaultProperties = overrideCapabilityDefinitionWrapper.getInnerElement().getProperties().stream().collect(Collectors.toMap(PropertyDefinition::getName, Function.identity()));
defaultPropertiesWrapper.setInnerElement(defaultProperties);
- log.debug("Before validating property values of capability instance {}.", createdCapabilityInstanceIdWrapper.getInnerElement());
+ log.debug("Before validating property values of capability instance {}",createdCapabilityInstanceIdWrapper.getInnerElement());
Either<Boolean, TitanOperationStatus> result = validateCapabilityInstanceProperties(defaultProperties, propertyValues);
if (result.isRight()) {
errorWrapper.setInnerElement(result.right().value());
- log.debug("failedAddProperties {} ofRI {} statusIs {}.", createdCapabilityInstanceIdWrapper.getInnerElement(), resourceInstanceId, errorWrapper.getInnerElement());
+ log.debug("Failed to add properties to capability instance {} of resource instance {}. status is {}.", createdCapabilityInstanceIdWrapper.getInnerElement(), resourceInstanceId, errorWrapper.getInnerElement());
}
- log.debug("After validating property values of capability instance {} status is {}.", createdCapabilityInstanceIdWrapper.getInnerElement(), errorWrapper.getInnerElement());
+ log.debug("After validating property values of capability instance {}. status is {}", createdCapabilityInstanceIdWrapper.getInnerElement(), errorWrapper.getInnerElement());
return createdCapabilityInstance;
}
private TitanVertex validateCapabilityInstancePropertiesByVertex(String resourceInstanceId, List<ComponentInstanceProperty> propertyValues, Wrapper<TitanOperationStatus> errorWrapper,
Wrapper<CapabilityDefinition> overrideCapabilityDefinitionWrapper, TitanVertex createCapabilityRes, Wrapper<Map<String, PropertyDefinition>> defaultPropertiesWrapper, Wrapper<String> createdCapabilityInstanceIdWrapper) {
+
String id = (String) titanGenericDao.getProperty(createCapabilityRes, GraphPropertiesDictionary.UNIQUE_ID.getProperty());
createdCapabilityInstanceIdWrapper.setInnerElement(id);
Map<String, PropertyDefinition> defaultProperties = overrideCapabilityDefinitionWrapper.getInnerElement().getProperties().stream().collect(Collectors.toMap(PropertyDefinition::getName, Function.identity()));
@@ -234,9 +217,9 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC
Either<Boolean, TitanOperationStatus> result = validateCapabilityInstanceProperties(defaultProperties, propertyValues);
if (result.isRight()) {
errorWrapper.setInnerElement(result.right().value());
- log.debug("Failed to add properties to capability instance {} {} {} {} {}", createdCapabilityInstanceIdWrapper.getInnerElement(), ofRI, resourceInstanceId, statusIs, errorWrapper.getInnerElement());
+ log.debug("Failed to add properties to capability instance {} of resource instance {}, status is {}", createdCapabilityInstanceIdWrapper.getInnerElement(), resourceInstanceId, errorWrapper.getInnerElement());
}
- log.trace("After validating property values of capability instance {} {} {}", createdCapabilityInstanceIdWrapper.getInnerElement(), statusIs, errorWrapper.getInnerElement());
+ log.trace("After validating property values of capability instance {}, status is {}", createdCapabilityInstanceIdWrapper.getInnerElement(), errorWrapper.getInnerElement());
return createCapabilityRes;
}
@@ -249,46 +232,46 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC
createCapabilityRes = createCapabilityInstanceOnGraph(resourceInstanceId, overrideCapabilityDataWrapper.getInnerElement(), capabilityInstance);
if (createCapabilityRes.isRight()) {
errorWrapper.setInnerElement(createCapabilityRes.right().value());
- log.debug("failedCreateCI {} ofRI {} statusIs {}.", capabilityId, resourceInstanceId, errorWrapper.getInnerElement());
+ log.debug("Failed to create capability instance of capability {} of resource instance {}, status is {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement());
}
- log.debug("After creating capability instance of capability {} on graph. Status is {}", capabilityId, errorWrapper.getInnerElement());
+ log.debug("After creating capability instance of capability {} on graph, status is {}", capabilityId, errorWrapper.getInnerElement());
return createCapabilityRes;
}
private Either<TitanVertex, TitanOperationStatus> createCapabilityInstanceOnGraphByVertex(TitanVertex riVertex, String resourceInstanceId, String capabilityId, Wrapper<TitanOperationStatus> errorWrapper,
Wrapper<TitanVertex> overrideCapabilityDataWrapper, Wrapper<CapabilityDefinition> overrideCapabilityDefinitionWrapper, Either<CapabilityDefinition, TitanOperationStatus> getCapabilityDefinitionRes) {
Either<TitanVertex, TitanOperationStatus> createCapabilityRes;
- log.trace("Before creating capability instance of capability {} {}", capabilityId, onGraph);
+ log.trace("Before creating capability instance of capability {} on graph", capabilityId);
overrideCapabilityDefinitionWrapper.setInnerElement(getCapabilityDefinitionRes.left().value());
CapabilityInstData capabilityInstance = buildCapabilityInstanceData(resourceInstanceId, overrideCapabilityDefinitionWrapper.getInnerElement());
createCapabilityRes = createCapabilityInstanceOnGraph(riVertex, resourceInstanceId, overrideCapabilityDataWrapper.getInnerElement(), capabilityInstance);
if (createCapabilityRes.isRight()) {
errorWrapper.setInnerElement(createCapabilityRes.right().value());
- log.debug("Failed to create capability instance of capability {} {} {} {} {} ", capabilityId, ofRI, resourceInstanceId, statusIs, errorWrapper.getInnerElement());
+ log.debug("Failed to create capability instance of capability {} of resource instance {}, status is {} ", capabilityId, resourceInstanceId, errorWrapper.getInnerElement());
}
- log.debug("After creating capability instance of capability {} {} {} {} {}", capabilityId, onGraph, statusIs, errorWrapper.getInnerElement());
+ log.debug("After creating capability instance of capability {} on graph, status is {}", capabilityId, errorWrapper.getInnerElement());
return createCapabilityRes;
}
private Either<CapabilityDefinition, TitanOperationStatus> getCapabiityDefinition(String resourceInstanceId, String capabilityId, Wrapper<TitanOperationStatus> errorWrapper, Wrapper<CapabilityData> overrideCapabilityDataWrapper,
Either<ImmutablePair<CapabilityData, GraphEdge>, TitanOperationStatus> getCapabilityRes) {
Either<CapabilityDefinition, TitanOperationStatus> getCapabilityDefinitionRes;
- log.debug("Before getting capability definition {} forRI {}.", capabilityId, resourceInstanceId);
+ log.debug("Before getting capability definition {} for resource instance {}", capabilityId, resourceInstanceId);
CapabilityData overrideCapabilityData = getCapabilityRes.left().value().getLeft();
overrideCapabilityDataWrapper.setInnerElement(overrideCapabilityData);
getCapabilityDefinitionRes = capabilityOperation.getCapabilityByCapabilityData(overrideCapabilityData);
if (getCapabilityDefinitionRes.isRight()) {
errorWrapper.setInnerElement(getCapabilityDefinitionRes.right().value());
- log.debug("Failed to retrieve capability {} ofRI {} statusIs {}.", capabilityId, resourceInstanceId, errorWrapper.getInnerElement());
+ log.debug("Failed to retrieve capability {} of resource instance {}, status is {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement());
}
- log.debug("After getting capability definition for {} forRI {} statusIs {}.", capabilityId, resourceInstanceId, errorWrapper.getInnerElement());
+ log.debug("After getting capability definition for {} for resource instance {}, status is {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement());
return getCapabilityDefinitionRes;
}
private Either<CapabilityDefinition, TitanOperationStatus> getCapabiityDefinitionByVertex(String resourceInstanceId, String capabilityId, Wrapper<TitanOperationStatus> errorWrapper, Wrapper<TitanVertex> overrideCapabilityDataWrapper,
Either<ImmutablePair<TitanVertex, Edge>, TitanOperationStatus> getCapabilityRes) {
Either<CapabilityDefinition, TitanOperationStatus> getCapabilityDefinitionRes;
- log.trace("Before getting capability definition {} {} {}", capabilityId, forRI, resourceInstanceId);
+ log.trace("Before getting capability definition {} for resource instance {}", capabilityId, resourceInstanceId);
TitanVertex overrideCapabilityData = getCapabilityRes.left().value().getLeft();
@@ -296,90 +279,90 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC
getCapabilityDefinitionRes = capabilityOperation.getCapabilityByCapabilityData(overrideCapabilityData);
if (getCapabilityDefinitionRes.isRight()) {
errorWrapper.setInnerElement(getCapabilityDefinitionRes.right().value());
- log.debug("Failed to retrieve capability {} ofRI {} statusIs {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement());
+ log.debug("Failed to retrieve capability {} of resource instance {}, status is {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement());
}
- log.debug("After getting capability definition for {} forRI {} statusIs {}.", capabilityId, resourceInstanceId, errorWrapper.getInnerElement());
+ log.debug("After getting capability definition for {} for resource instance {} status is {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement());
return getCapabilityDefinitionRes;
}
private Either<ImmutablePair<CapabilityData, GraphEdge>, TitanOperationStatus> getCapabilitiesOfResourceInstance(String resourceInstanceId, String capabilityId, String capabilityName, Wrapper<TitanOperationStatus> errorWrapper) {
Either<ImmutablePair<CapabilityData, GraphEdge>, TitanOperationStatus> getCapabilityRes;
- log.debug("Before getting capability {} forRI {}.", capabilityId, resourceInstanceId);
+ log.debug("Before getting capability {} for resource instance {}", capabilityId, resourceInstanceId);
Map<String, Object> props = new HashMap<>();
props.put(GraphPropertiesDictionary.NAME.getProperty(), capabilityName);
getCapabilityRes = titanGenericDao.getChildByEdgeCriteria(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceId, GraphEdgeLabels.CALCULATED_CAPABILITY, NodeTypeEnum.Capability, CapabilityData.class, props);
if (getCapabilityRes.isRight()) {
errorWrapper.setInnerElement(getCapabilityRes.right().value());
- log.debug("Failed to get capability {} ofRI {} statusIs {}.", capabilityId, resourceInstanceId, errorWrapper.getInnerElement());
+ log.debug("Failed to get capability {} of resource instance {}, status is {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement());
}
- log.debug("After getting capability for {} forRI {} statusIs {}.", capabilityId, resourceInstanceId, errorWrapper.getInnerElement());
+ log.debug("After getting capability for {} for resource instance {}. status is {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement());
return getCapabilityRes;
}
private Either<ImmutablePair<TitanVertex, Edge>, TitanOperationStatus> getCapabilitiesOfResourceInstance(TitanVertex instanceVertex, String resourceInstanceId, String capabilityId, String capabilityName,
Wrapper<TitanOperationStatus> errorWrapper) {
Either<ImmutablePair<TitanVertex, Edge>, TitanOperationStatus> getCapabilityRes;
- log.trace("Before getting capability {} {} {}", capabilityId, forRI, resourceInstanceId);
+ log.trace("Before getting capability {} {} {}", capabilityId, " for resource instance ", resourceInstanceId);
Map<String, Object> props = new HashMap<>();
props.put(GraphPropertiesDictionary.NAME.getProperty(), capabilityName);
getCapabilityRes = titanGenericDao.getChildByEdgeCriteria(instanceVertex, GraphEdgeLabels.CALCULATED_CAPABILITY, props);
if (getCapabilityRes.isRight()) {
errorWrapper.setInnerElement(getCapabilityRes.right().value());
- log.debug("Failed to get capability {} {} {} {} {}", capabilityId, ofRI, resourceInstanceId, statusIs, errorWrapper.getInnerElement());
+ log.debug("Failed to get capability {} of resource instance {}. status is {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement());
}
- log.trace("After getting capability for {} {} {} {} {}", capabilityId, forRI, resourceInstanceId, statusIs, errorWrapper.getInnerElement());
+ log.trace("After getting capability for {} for resource instance {}. status is {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement());
return getCapabilityRes;
}
private void validateCapabilityInstanceExistence(String resourceInstanceId, String capabilityId, Wrapper<TitanOperationStatus> errorWrapper) {
- log.debug("Before validation of existence of capability instance of capability {} forRI {}.", capabilityId, resourceInstanceId);
+ log.debug("Before validation of existence of capability instance of capability {} for resource instance {}", capabilityId, resourceInstanceId);
boolean capabilityInstOfCapabilityAlreadyExists;
Either<Boolean, TitanOperationStatus> validateCapabilityInstExistenceRes = validateCapabilityInstExistence(resourceInstanceId, capabilityId);
if (validateCapabilityInstExistenceRes.isRight()) {
errorWrapper.setInnerElement(validateCapabilityInstExistenceRes.right().value());
- log.debug("Failed to validate uniqueness of capability instance of capability {} ofRI {} statusIs {}.", capabilityId, resourceInstanceId, errorWrapper.getInnerElement());
+ log.debug("Failed to validate uniqueness of capability instance of capability {} of resource instance {}. status is {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement());
} else {
capabilityInstOfCapabilityAlreadyExists = validateCapabilityInstExistenceRes.left().value();
if (capabilityInstOfCapabilityAlreadyExists) {
errorWrapper.setInnerElement(TitanOperationStatus.ALREADY_EXIST);
- log.debug("failedCreateCI {} ofRI {} statusIs {}.", capabilityId, resourceInstanceId, errorWrapper.getInnerElement());
+ log.debug("Failed to create capability instance of capability {} of resource instance {}. status is {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement());
}
}
- log.debug("After validation of existence of capability instance of capability {} forRI {} statusIs {}.", capabilityId, resourceInstanceId, errorWrapper.getInnerElement());
+ log.debug("After validation of existence of capability instance of capability {} for resource instance {}. status is {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement());
}
private void validateCapabilityInstanceExistence(TitanVertex resourceInstanceVertex, String resourceInstanceId, String capabilityId, Wrapper<TitanOperationStatus> errorWrapper) {
- log.trace("Before validation of existence of capability instance of capability {} {} {}", capabilityId, forRI, resourceInstanceId);
+ log.trace("Before validation of existence of capability instance of capability {} for resource instance {}", capabilityId, resourceInstanceId);
boolean capabilityInstOfCapabilityAlreadyExists;
Either<Boolean, TitanOperationStatus> validateCapabilityInstExistenceRes = validateCapabilityInstExistence(resourceInstanceId, capabilityId);
if (validateCapabilityInstExistenceRes.isRight()) {
errorWrapper.setInnerElement(validateCapabilityInstExistenceRes.right().value());
- log.debug("Failed to validate uniqueness of capability instance of capability {} ofRI {} statusIs {}.", capabilityId, resourceInstanceId, errorWrapper.getInnerElement());
+ log.debug("Failed to validate uniqueness of capability instance of capability {} of resource instance {}. status is {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement());
} else {
capabilityInstOfCapabilityAlreadyExists = validateCapabilityInstExistenceRes.left().value();
if (capabilityInstOfCapabilityAlreadyExists) {
errorWrapper.setInnerElement(TitanOperationStatus.ALREADY_EXIST);
- log.debug("failedCreateCI {} ofRI {} statusIs {}.", capabilityId, resourceInstanceId, errorWrapper.getInnerElement());
+ log.debug("Failed to create capability instance of capability {} of resource instance {}. status is {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement());
}
}
- log.debug("After validation of existence of capability instance of capability {} forRI {} statusIs {}.", capabilityId, resourceInstanceId, errorWrapper.getInnerElement());
+ log.debug("After validation of existence of capability instance of capability {} for resource instance {}. status is {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement());
}
private Either<List<PropertyValueData>, TitanOperationStatus> addPropertyValuesToCapabilityInstance(CapabilityInstData createdCapabilityInstance, List<ComponentInstanceProperty> propertyValues, Map<String, PropertyDefinition> defaultProperties) {
TitanOperationStatus error = null;
List<PropertyValueData> createdPropertyValues = new ArrayList<>();
for (ComponentInstanceProperty property : propertyValues) {
- log.debug("Before adding property value {} toCI {}.", property.getName(), createdCapabilityInstance.getUniqueId());
+ log.debug("Before adding property value {} to capability instance {}", property.getName(), createdCapabilityInstance.getUniqueId());
PropertyValueData propertyData = buildPropertyValueData(property.getName(), property.getType(), property.getValue(), createdCapabilityInstance.getUniqueId());
Either<PropertyValueData, TitanOperationStatus> addPropertyValueRes = addPropertyValueToCapabilityInstance(createdCapabilityInstance, propertyData, defaultProperties.get(property.getName()));
if (addPropertyValueRes.isRight()) {
error = addPropertyValueRes.right().value();
- log.debug("Failed to add property to capability instance {} ofRI. StatusIs {}.", createdCapabilityInstance.getUniqueId(), error);
+ log.debug("Failed to add property to capability instance {} of resource instance, status is {}", createdCapabilityInstance.getUniqueId(), error);
break;
} else {
createdPropertyValues.add(addPropertyValueRes.left().value());
}
- log.debug("After adding property value {} toCI {} statusIs {}", property.getName(), createdCapabilityInstance.getUniqueId(), error);
+ log.debug("After adding property value {} to capability instance {}. status is {}", property.getName(), createdCapabilityInstance.getUniqueId(), error);
}
if (error == null) {
return Either.left(createdPropertyValues);
@@ -391,15 +374,15 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC
TitanOperationStatus error = null;
String id = (String) titanGenericDao.getProperty(createdCapabilityInstancevertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty());
for (ComponentInstanceProperty property : propertyValues) {
- log.trace("Before adding property value {} {} {}", property.getName(), toCI, id);
+ log.trace("Before adding property value {} to capability instance {}", property.getName(), id);
PropertyValueData propertyData = buildPropertyValueData(property.getName(), property.getType(), property.getValue(), id);
TitanOperationStatus addPropertyValueRes = addPropertyValueToCapabilityInstance(createdCapabilityInstancevertex, propertyData, defaultProperties.get(property.getName()), id);
if (!addPropertyValueRes.equals(TitanOperationStatus.OK)) {
error = addPropertyValueRes;
- log.debug("Failed to add property to capability instance {} {} {} {}", id, ofRI, statusIs, error);
+ log.debug("Failed to add property to capability instance {} of resource instance. status is {}", id, error);
break;
}
- log.debug("After adding property value {} {} {} {} {}", property.getName(), toCI, id, statusIs, error);
+ log.debug("After adding property value {} to capability instance {}. status is {}", property.getName(), id, error);
}
if (error == null) {
return TitanOperationStatus.OK;
@@ -424,15 +407,15 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC
Map<String, Object> props = null;
Either<GraphRelation, TitanOperationStatus> createRelationRes;
PropertyValueData createdValue = null;
- log.debug("Before creating property value node {} onGraph.", propertyValue.getUniqueId());
+ log.debug("Before creating property value node {} on graph", propertyValue.getUniqueId());
Either<PropertyValueData, TitanOperationStatus> createValueRes = titanGenericDao.createNode(propertyValue, PropertyValueData.class);
if (createValueRes.isRight()) {
error = createValueRes.right().value();
- log.debug("Failed to create property value for capability instance {} ofRI statusIs {}.", createdCapabilityInstance.getUniqueId(), error);
+ log.debug("Failed to create property value for capability instance {} of resource instance. status is {}", createdCapabilityInstance.getUniqueId(), error);
}
- log.debug("After creating property value node {} onGraph statusIs {}.", propertyValue.getUniqueId(), error);
+ log.debug("After creating property value node {} on graph. status is {}", propertyValue.getUniqueId(), error);
if (error == null) {
- log.debug("Before creating relation from property value node {} toCI {}.", propertyValue.getUniqueId(), createdCapabilityInstance.getUniqueId());
+ log.debug("Before creating relation from property value node {} to capability instance {}", propertyValue.getUniqueId(), createdCapabilityInstance.getUniqueId());
createdValue = createValueRes.left().value();
props = new HashMap<>();
props.put(GraphPropertiesDictionary.PROPERTY_NAME.name(), propertyDefinition.getName());
@@ -440,18 +423,18 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC
createRelationRes = titanGenericDao.createRelation(createdCapabilityInstance, createdValue, GraphEdgeLabels.PROPERTY_VALUE, props);
if (createRelationRes.isRight()) {
error = createRelationRes.right().value();
- log.debug("Failed to create relation from capability instance {} toValue {} statusIs {}.", createdCapabilityInstance.getUniqueId(), createdValue.getUniqueId(), error);
+ log.debug("Failed to create relation from capability instance {} to property value {}. status is {}", createdCapabilityInstance.getUniqueId(), createdValue.getUniqueId(), error);
}
- log.debug("After creating relation from property value node {} toCI {} statusIs {}.", propertyValue.getUniqueId(), createdCapabilityInstance.getUniqueId(), error);
+ log.debug("After creating relation from property value node {} to capability instance {}. status is {}", propertyValue.getUniqueId(), createdCapabilityInstance.getUniqueId(), error);
}
if (error == null) {
- log.debug("Before creating relation from property value node {} toProperty {}.", propertyValue.getUniqueId(), propertyDefinition.getUniqueId());
+ log.debug("Before creating relation from property value node {} to property {}", propertyValue.getUniqueId(), propertyDefinition.getUniqueId());
createRelationRes = titanGenericDao.createRelation(propertyValue, new PropertyData(propertyDefinition, null), GraphEdgeLabels.PROPERTY_IMPL, props);
if (createRelationRes.isRight()) {
error = createRelationRes.right().value();
- log.debug("Failed to create relation from property value {} toProperty {} statusIs {}.", createdValue.getUniqueId(), propertyDefinition.getUniqueId(), error);
+ log.debug("Failed to create relation from property value {} to property {}. status is {}", createdValue.getUniqueId(), propertyDefinition.getUniqueId(), error);
}
- log.debug("After creating relation from property value node {} toProperty statusIs {}.", propertyValue.getUniqueId(), propertyDefinition.getUniqueId(), error);
+ log.debug("After creating relation from property value node {} to property {}. status is {}", propertyValue.getUniqueId(), propertyDefinition.getUniqueId(), error);
}
if (error == null) {
return Either.left(createdValue);
@@ -467,15 +450,13 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC
Either<TitanVertex, TitanOperationStatus> createValueRes = titanGenericDao.createNode(propertyValue);
if (createValueRes.isRight()) {
error = createValueRes.right().value();
- if (log.isDebugEnabled()){
- log.debug("Failed to create property value for capability instance {} {} {} {}", id, ofRI, statusIs, error);
- }
+ log.debug("Failed to create property value for capability instance {} of resource instance. status is {}", id, error);
}
log.trace("After creating property value node {} on graph status is {}", propertyValue.getUniqueId(), error);
TitanVertex createdPropVertex = null;
String createdId = null;
if (error == null) {
- log.trace("Before creating relation from property value node {} {} {} ", propertyValue.getUniqueId(), toCI, id);
+ log.trace("Before creating relation from property value node {} to capability instance {} ", propertyValue.getUniqueId() , id);
props = new HashMap<>();
props.put(GraphPropertiesDictionary.PROPERTY_NAME.name(), propertyDefinition.getName());
props.put(GraphPropertiesDictionary.PROPERTY_ID.name(), propertyDefinition.getUniqueId());
@@ -484,22 +465,18 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC
if (!createRelationRes.equals(TitanOperationStatus.OK)) {
error = createRelationRes;
createdId = (String) titanGenericDao.getProperty(createdPropVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty());
- if (log.isDebugEnabled()) {
- log.debug("Failed to create relation from capability instance {} {} {} {} {}", id, toValue, createdId, statusIs, error);
- }
- }
- if (log.isTraceEnabled()){
- log.trace("After creating relation from property value node {} {} {} {} {}", propertyValue.getUniqueId(), toCI, id, statusIs, error);
+ log.debug("Failed to create relation from capability instance {} to property value {}. status is {}", id, createdId, error);
}
+ log.trace("After creating relation from property value node {} to capability instance {}. status is {}", propertyValue.getUniqueId(), id, error);
}
if (error == null) {
- log.trace("Before creating relation from property value node {} {} {}", propertyValue.getUniqueId(), toProperty, propertyDefinition.getUniqueId());
+ log.trace("Before creating relation from property value node {} to property {}", propertyValue.getUniqueId(), propertyDefinition.getUniqueId());
createRelationRes = titanGenericDao.createEdge(createdPropVertex, new PropertyData(propertyDefinition, null), GraphEdgeLabels.PROPERTY_IMPL, props);
if (!createRelationRes.equals(TitanOperationStatus.OK)) {
error = createRelationRes;
- log.debug("Failed to create relation from property value {} {} {} {} {}", createdId, toProperty, propertyDefinition.getUniqueId(), statusIs, error);
+ log.debug("Failed to create relation from property value {} to property {}. status is {}", createdId, propertyDefinition.getUniqueId(), error);
}
- log.debug("After creating relation from property value node {} {} {} {} {}", propertyValue.getUniqueId(), toProperty, propertyDefinition.getUniqueId(), statusIs, error);
+ log.debug("After creating relation from property value node {} to property {}. status is {}", propertyValue.getUniqueId(), propertyDefinition.getUniqueId(), error);
}
if (error == null) {
return TitanOperationStatus.OK;
@@ -537,7 +514,7 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC
Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = applicationDataTypeCache.getAll();
if (allDataTypes.isRight()) {
TitanOperationStatus status = allDataTypes.right().value();
- log.debug("Failed to update property value statusIs {}.", status);
+ log.debug("Failed to update property value. status is {}", status);
result = Either.right(status);
}
if (result == null) {
@@ -582,7 +559,7 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC
if (error.equals(TitanOperationStatus.NOT_FOUND)) {
result = Either.left(false);
} else {
- log.debug("Failed to get outgoing edge for resource instance {} statusIs {}.", resourceInstanceId, error);
+ log.debug("Failed to get outgoing edge for resource instance {}. status is {}.", resourceInstanceId, error);
result = Either.right(error);
}
}
@@ -604,7 +581,7 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC
if (error.equals(TitanOperationStatus.NOT_FOUND)) {
result = Either.left(false);
} else {
- log.debug("Failed to get outgoing edge for resource instance {} {} {}", resourceInstanceId, statusIs, error);
+ log.debug("Failed to get outgoing edge for resource instance {} status is {}", resourceInstanceId, error);
result = Either.right(error);
}
}
@@ -615,7 +592,7 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC
}
private Either<CapabilityInstData, TitanOperationStatus> createCapabilityInstanceOnGraph(String resourceInstanceId, CapabilityData overrideCapabilityData, CapabilityInstData capabilityInstance) {
- log.debug("Before creation of capability instance of capability {} forRI {}.", overrideCapabilityData.getUniqueId(), resourceInstanceId);
+ log.debug("Before creation of capability instance of capability {} for resource instance {}", overrideCapabilityData.getUniqueId(), resourceInstanceId);
Either<GraphRelation, TitanOperationStatus> createRelationRes;
CapabilityInstData createdCapabilityInstance = null;
@@ -624,9 +601,9 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC
Either<CapabilityInstData, TitanOperationStatus> createCapabilityInstanceRes = titanGenericDao.createNode(capabilityInstance, CapabilityInstData.class);
if (createCapabilityInstanceRes.isRight()) {
error = createCapabilityInstanceRes.right().value();
- log.debug("failedCreateCI {} forRI {} statusIs {}.", overrideCapabilityData.getUniqueId(), resourceInstanceId, error);
+ log.debug("Failed to create capability instance of capability {} for resource instance {}. status is {}.", overrideCapabilityData.getUniqueId(), resourceInstanceId, error);
}
- log.debug("After creation of capability instance of capability {} forRI {} statusIs {}.", overrideCapabilityData.getUniqueId(), resourceInstanceId, error);
+ log.debug("After creation of capability instance of capability {} for resource instance {}. status is {}.", overrideCapabilityData.getUniqueId(), resourceInstanceId, error);
if (error == null) {
createdCapabilityInstance = createCapabilityInstanceRes.left().value();
capabilityInstanceId = createdCapabilityInstance.getUniqueId();
@@ -637,20 +614,20 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC
createRelationRes = titanGenericDao.createRelation(resourceInstanceIdData, capabilityInstance, GraphEdgeLabels.CAPABILITY_INST, props);
if (createRelationRes.isRight()) {
error = createRelationRes.right().value();
- log.debug("Failed to assotiate resource instance {} toCI {} statusIs {}.", resourceInstanceId, capabilityInstanceId, error);
+ log.debug("Failed to assotiate resource instance {} to capability instance {}. status is {}", resourceInstanceId, capabilityInstanceId, error);
}
- log.debug("After associating resource instance {} to CI {} statusIs {}.", resourceInstanceId, capabilityInstanceId, error);
+ log.debug("After associating resource instance {} to capability instance {}. status is {}", resourceInstanceId, capabilityInstanceId, error);
}
if (error == null) {
- log.debug("Before associating capability instance {} toCapability {}.", capabilityInstanceId, overrideCapabilityData.getUniqueId());
+ log.debug("Before associating capability instance {} to capability {}.", capabilityInstanceId, overrideCapabilityData.getUniqueId());
Map<String, Object> props = new HashMap<>();
props.put(GraphPropertiesDictionary.CAPABILITY_ID.getProperty(), overrideCapabilityData.getUniqueId());
createRelationRes = titanGenericDao.createRelation(createdCapabilityInstance, overrideCapabilityData, GraphEdgeLabels.INSTANCE_OF, props);
if (createRelationRes.isRight()) {
error = createRelationRes.right().value();
- log.debug("Failed to associate capability instance {} toCapability statusIs {}.", capabilityInstanceId, overrideCapabilityData.getUniqueId(), error);
+ log.debug("Failed to associate capability instance {} to capability {}. status is {}", capabilityInstanceId, overrideCapabilityData.getUniqueId(), error);
}
- log.debug("After associating capability instance {} toCapability statusIs {}.", capabilityInstanceId, overrideCapabilityData.getUniqueId(), error);
+ log.debug("After associating capability instance {} to capability {}. status is {}.", capabilityInstanceId, overrideCapabilityData.getUniqueId(), error);
}
if (error == null) {
return createCapabilityInstanceRes;
@@ -660,7 +637,7 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC
private Either<TitanVertex, TitanOperationStatus> createCapabilityInstanceOnGraph(TitanVertex riVertex, String resourceInstanceId, TitanVertex overrideCapabilityDataVertex, CapabilityInstData capabilityInstance) {
String overrideCapabilityDataId = (String) titanGenericDao.getProperty(overrideCapabilityDataVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty());
- log.trace("Before creation of capability instance of capability {} {} {}", overrideCapabilityDataVertex, forRI, resourceInstanceId);
+ log.trace("Before creation of capability instance of capability {} for resource instance {}", overrideCapabilityDataVertex, resourceInstanceId);
TitanOperationStatus createRelationRes;
TitanVertex createdCapabilityInstance = null;
@@ -669,9 +646,9 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC
Either<TitanVertex, TitanOperationStatus> createCapabilityInstanceRes = titanGenericDao.createNode(capabilityInstance);
if (createCapabilityInstanceRes.isRight()) {
error = createCapabilityInstanceRes.right().value();
- log.debug("Failed to create capability instance of capability {} {} {} {} {}", overrideCapabilityDataId, forRI, resourceInstanceId, statusIs, error);
+ log.debug("Failed to create capability instance of capability {} for resource instance {} status is {}", overrideCapabilityDataId, resourceInstanceId, error);
}
- log.trace("After creation of capability instance of capability {} {} {} {} {}", overrideCapabilityDataId, forRI, resourceInstanceId, statusIs, error);
+ log.trace("After creation of capability instance of capability {} for resource instance {} status is {}", overrideCapabilityDataId, resourceInstanceId, error);
if (error == null) {
createdCapabilityInstance = createCapabilityInstanceRes.left().value();
capabilityInstanceId = (String) titanGenericDao.getProperty(createdCapabilityInstance, GraphPropertiesDictionary.UNIQUE_ID.getProperty());
@@ -682,22 +659,22 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC
createRelationRes = titanGenericDao.createEdge(riVertex, capabilityInstance, GraphEdgeLabels.CAPABILITY_INST, props);
if (!createRelationRes.equals(TitanOperationStatus.OK)) {
error = createRelationRes;
- log.debug("Failed to assotiate resource instance {} {} {} {} {}", resourceInstanceId, toCI, capabilityInstanceId, statusIs, error);
+ log.debug("Failed to assotiate resource instance {} to capability instance {} status is {}", resourceInstanceId, capabilityInstanceId, error);
}
if (log.isTraceEnabled()) {
- log.trace("After associating resource instance {} {} {} {} {}", resourceInstanceId, toCI, capabilityInstanceId, statusIs, error);
+ log.trace("After associating resource instance {} to capability instance {}. status is {}", resourceInstanceId, capabilityInstanceId, error);
}
}
if (error == null) {
- log.trace("Before associating capability instance {} {} {}", capabilityInstanceId, toCapability, overrideCapabilityDataId);
+ log.trace("Before associating capability instance {} to capability {}", capabilityInstanceId, overrideCapabilityDataId);
Map<String, Object> props = new HashMap<>();
props.put(GraphPropertiesDictionary.CAPABILITY_ID.getProperty(), overrideCapabilityDataId);
createRelationRes = titanGenericDao.createEdge(createdCapabilityInstance, overrideCapabilityDataVertex, GraphEdgeLabels.INSTANCE_OF, props);
if (!createRelationRes.equals(TitanOperationStatus.OK)) {
error = createRelationRes;
- log.debug("Failed to associate capability instance {} {} {} {} {}", capabilityInstanceId, toCapability, overrideCapabilityDataId, statusIs, error);
+ log.debug("Failed to associate capability instance {} to capability {} status is {}", capabilityInstanceId, overrideCapabilityDataId, error);
}
- log.debug("After associating capability instance {} {} {} {} {}", capabilityInstanceId, toCapability, overrideCapabilityDataId, statusIs, error);
+ log.debug("After associating capability instance {} to capability {}. status is {}", capabilityInstanceId, overrideCapabilityDataId, error);
}
if (error == null) {
return createCapabilityInstanceRes;
@@ -726,23 +703,23 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC
*/
@Override
public Either<CapabilityInstData, TitanOperationStatus> deleteCapabilityInstanceFromResourceInstance(String resourceInstanceId, String capabilityInstanceId) {
- log.debug("Before deleting of capability instance {} fromRI {}.", capabilityInstanceId, resourceInstanceId);
+ log.debug("Before deleting of capability instance {} from resource instance {}.", capabilityInstanceId, resourceInstanceId);
Either<CapabilityInstData, TitanOperationStatus> deleteCapabilityInstRes = null;
TitanOperationStatus error = null;
Either<Boolean, TitanOperationStatus> deleteProperyValuesRes = deleteAllPropertyValuesOfCapabilityInstance(resourceInstanceId, capabilityInstanceId);
if (deleteProperyValuesRes.isRight()) {
error = deleteProperyValuesRes.right().value();
- log.debug("failedDeletePropertyValues {} for RI {} statusIs {}.", capabilityInstanceId, resourceInstanceId, error);
+ log.debug("Failed to delete property values of capability instance {} for resource instance {}. status is {}", capabilityInstanceId, resourceInstanceId, error);
}
if (error == null) {
deleteCapabilityInstRes = titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityInst), capabilityInstanceId, CapabilityInstData.class);
if (deleteCapabilityInstRes.isRight()) {
error = deleteCapabilityInstRes.right().value();
- log.debug("Failed to delete capability instance {} forRI {} statusIs {}", capabilityInstanceId, resourceInstanceId, error);
+ log.debug("Failed to delete capability instance {} for resource instance {}. status is {}", capabilityInstanceId, resourceInstanceId, error);
}
}
- log.debug("After deleting of capability instance {} fromRI {} statusIs {}.", capabilityInstanceId, resourceInstanceId, error);
+ log.debug("After deleting of capability instance {} from resource instance {}. status is {}", capabilityInstanceId, resourceInstanceId, error);
if (error == null) {
return Either.left(deleteCapabilityInstRes.left().value());
}
@@ -750,14 +727,14 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC
}
private Either<Boolean, TitanOperationStatus> deleteAllPropertyValuesOfCapabilityInstance(String resourceInstanceId, String capabilityInstanceId) {
- log.debug("Before deleting all property values of capability instance {} fromRI {}.", capabilityInstanceId, resourceInstanceId);
+ log.debug("Before deleting all property values of capability instance {} from resource instance {}", capabilityInstanceId, resourceInstanceId);
TitanOperationStatus error = null;
List<ImmutablePair<PropertyValueData, GraphEdge>> deletePropertiesPairs;
Either<List<ImmutablePair<PropertyValueData, GraphEdge>>, TitanOperationStatus> getPropertyValuesRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityInst), capabilityInstanceId,
GraphEdgeLabels.PROPERTY_VALUE, NodeTypeEnum.PropertyValue, PropertyValueData.class);
if (getPropertyValuesRes.isRight()) {
error = getPropertyValuesRes.right().value();
- log.debug("Failed to retrieve property values of capability instance {} forRI {} status {}.", capabilityInstanceId, resourceInstanceId, error);
+ log.debug("Failed to retrieve property values of capability instance {} for resource instance {}. status is {}", capabilityInstanceId, resourceInstanceId, error);
}
if (error == null) {
deletePropertiesPairs = getPropertyValuesRes.left().value();
@@ -765,12 +742,12 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC
Either<PropertyValueData, TitanOperationStatus> deletePropertyRes = titanGenericDao.deleteNode(propertyPair.getLeft(), PropertyValueData.class);
if (deletePropertyRes.isRight()) {
error = deletePropertyRes.right().value();
- log.debug("failedDeletePropertyValues {} forRI {} statusIs {}.", capabilityInstanceId, resourceInstanceId, error);
+ log.debug("Failed to delete property values of capability instance {} for resource instance {}. status is {}", capabilityInstanceId, resourceInstanceId, error);
break;
}
}
}
- log.debug("After deleting all property values of capability instance {} fromRI {} statusIs {}.", capabilityInstanceId, resourceInstanceId, error);
+ log.debug("After deleting all property values of capability instance from resource instance {}. status is {}", capabilityInstanceId, resourceInstanceId, error);
if (error == null) {
return Either.left(true);
}
@@ -786,15 +763,15 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC
*/
@Override
public Either<List<ImmutablePair<CapabilityInstData, GraphEdge>>, TitanOperationStatus> getAllCapabilityInstancesOfResourceInstance(String resourceInstanceId) {
- log.debug("Before deleting all capability instances of resource instance {}.", resourceInstanceId);
+ log.debug("Before deleting all capability instances of resource instance {}", resourceInstanceId);
TitanOperationStatus error = null;
Either<List<ImmutablePair<CapabilityInstData, GraphEdge>>, TitanOperationStatus> getCapabilityInstancesRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceId,
GraphEdgeLabels.CAPABILITY_INST, NodeTypeEnum.CapabilityInst, CapabilityInstData.class);
if (getCapabilityInstancesRes.isRight()) {
error = getCapabilityInstancesRes.right().value();
- log.debug("Failed to retrieve capability Instances of resource instance {} statusIs {}.", resourceInstanceId, error);
+ log.debug("Failed to retrieve capability Instances of resource instance {}. status is {}", resourceInstanceId, error);
}
- log.debug("After deleting all capability instances of resource instance {} statusIs {}", resourceInstanceId, error);
+ log.debug("After deleting all capability instances of resource instance {}. status is {}", resourceInstanceId, error);
if (error == null) {
return getCapabilityInstancesRes;
}
@@ -817,7 +794,7 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC
GraphEdgeLabels.CAPABILITY_INST, NodeTypeEnum.CapabilityInst, CapabilityInstData.class, props);
if (getCapabilityInstanceRes.isRight()) {
error = getCapabilityInstanceRes.right().value();
- log.debug("Failed to retrieve capability Instance of capability {} ofRI {} statusIs {}.", capabilityId, resourceInstanceId, error);
+ log.debug("Failed to retrieve capability Instance of capability {} of resource instance {}. status is {}", capabilityId, resourceInstanceId, error);
}
if (error == null) {
return Either.left(getCapabilityInstanceRes.left().value().getLeft());
@@ -835,7 +812,7 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC
*/
@Override
public Either<List<PropertyValueData>, TitanOperationStatus> updateCapabilityPropertyValues(String resourceInstanceId, String capabilityId, List<ComponentInstanceProperty> propertyValues) {
- log.debug("Before updating property values of capability {} ofRI {}.", capabilityId, resourceInstanceId);
+ log.debug("Before updating property values of capability {} of resource instance {}.", capabilityId, resourceInstanceId);
TitanOperationStatus error = null;
Map<String, Object> props = new HashMap<>();
CapabilityInstData capabilityInstance = null;
@@ -849,47 +826,47 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC
Either<List<PropertyValueData>, TitanOperationStatus> addPropertyValuesRes = null;
Either<CapabilityDefinition, TitanOperationStatus> getCapabilityDefinitionRes = null;
- log.debug("Before getting all capability instances of RI {}.", resourceInstanceId);
+ log.debug("Before getting all capability instances of resource instance {}.", resourceInstanceId);
props.put(GraphPropertiesDictionary.CAPABILITY_ID.getProperty(), capabilityId);
Either<ImmutablePair<CapabilityInstData, GraphEdge>, TitanOperationStatus> getCapabilityInstancesRes = titanGenericDao.getChildByEdgeCriteria(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceId,
GraphEdgeLabels.CAPABILITY_INST, NodeTypeEnum.CapabilityInst, CapabilityInstData.class, props);
if (getCapabilityInstancesRes.isRight()) {
error = getCapabilityInstancesRes.right().value();
- log.debug("Failed to retrieve capability Instances of capability {} ofRI {} statusIs {}.", capabilityId, resourceInstanceId, error);
+ log.debug("Failed to retrieve capability Instances of capability {} of resource instance {}. status is {}", capabilityId, resourceInstanceId, error);
}
- log.debug("After getting all capability instances ofRI {} statusIs {}.", resourceInstanceId, error);
+ log.debug("After getting all capability instances of resource instance {}. status is {}.", resourceInstanceId, error);
if (error == null) {
- log.debug("Before deleting all capability instances ofRI {}.", resourceInstanceId);
+ log.debug("Before deleting all capability instances of resource instance {}.", resourceInstanceId);
capabilityInstance = getCapabilityInstancesRes.left().value().getLeft();
capabilityInstanceId = capabilityInstance.getUniqueId();
deleteProperyValuesRes = deleteAllPropertyValuesOfCapabilityInstance(resourceInstanceId, capabilityInstanceId);
if (deleteProperyValuesRes.isRight()) {
error = deleteProperyValuesRes.right().value();
- log.debug("failedDeletePropertyValues {} forRI {} statusIs {}", capabilityInstanceId, resourceInstanceId, statusIs, error);
+ log.debug("Failed to delete property values of capability instance {} for resource instance {}. status is {}", capabilityInstanceId, resourceInstanceId, error);
}
- log.debug("After deleting all capability instances ofRI {} statusIs {}.", resourceInstanceId, error);
+ log.debug("After deleting all capability instances of resource instance {}. status is {}", resourceInstanceId, error);
}
if (error == null) {
- log.debug("Before getting capability {} ofRI {}.", capabilityId, resourceInstanceId);
+ log.debug("Before getting capability {} of resource instance {}", capabilityId, resourceInstanceId);
getCapabilityDataRes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceId, GraphEdgeLabels.CALCULATED_CAPABILITY, NodeTypeEnum.Capability, CapabilityData.class);
if (getCapabilityDataRes.isRight()) {
error = getCapabilityDataRes.right().value();
- log.debug("Failed to get capability {} ofRI {} statusIs {}.", capabilityId, resourceInstanceId, error);
+ log.debug("Failed to get capability {} of resource instance {}. status is {}", capabilityId, resourceInstanceId, error);
}
- log.debug("After getting capability {} ofRI {} statusIs {}.", capabilityId, resourceInstanceId, error);
+ log.debug("After getting capability {} of resource instance {}. status is {}.", capabilityId, resourceInstanceId, error);
}
if (error == null) {
- log.debug("Before getting capability definition for capability {} ofRI {}.", capabilityId, resourceInstanceId);
+ log.debug("Before getting capability definition for capability {} of resource instance {}.", capabilityId, resourceInstanceId);
overrideCapabilityData = getCapabilityDataRes.left().value().getLeft();
getCapabilityDefinitionRes = capabilityOperation.getCapabilityByCapabilityData(overrideCapabilityData);
if (getCapabilityDefinitionRes.isRight()) {
error = getCapabilityDefinitionRes.right().value();
- log.debug("Failed to retrieve capability {} ofRI {} statusIs {}", capabilityId, resourceInstanceId, error);
+ log.debug("Failed to retrieve capability {} of resource instance {}. status is {}", capabilityId, resourceInstanceId, error);
}
- log.debug("After getting capability definition for capability {} ofRI {} statusIs {}.", capabilityId, resourceInstanceId, error);
+ log.debug("After getting capability definition for capability {} of resource instance {}. status is {}.", capabilityId, resourceInstanceId, error);
}
if (error == null) {
- log.debug("Before validating capability properties of capability instance {} ofRI {}.", capabilityInstanceId, resourceInstanceId);
+ log.debug("Before validating capability properties of capability instance {} of resource instance {}.", capabilityInstanceId, resourceInstanceId);
overrideCapabilityDefinition = getCapabilityDefinitionRes.left().value();
if (overrideCapabilityDefinition.getProperties() != null) {
defaultProperties = overrideCapabilityDefinition.getProperties().stream().collect(Collectors.toMap(PropertyDefinition::getName, Function.identity()));
@@ -897,20 +874,20 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC
Either<Boolean, TitanOperationStatus> result = validateCapabilityInstanceProperties(defaultProperties, propertyValues);
if (result.isRight()) {
error = result.right().value();
- log.debug("failedAddProperties {} ofRI {} statusIs {}.", capabilityInstance.getUniqueId(), resourceInstanceId, error);
+ log.debug("Failed to add properties to capability instance {} of resource instance {}. status is {}", capabilityInstance.getUniqueId(), resourceInstanceId, error);
}
- log.debug("After validating capability properties of capability instance {} of RI {} statusIs {}.", capabilityInstanceId, resourceInstanceId, error);
+ log.debug("After validating capability properties of capability instance {} of resource instance {}. status is {}.", capabilityInstanceId, resourceInstanceId, error);
}
if (error == null) {
- log.debug("Before adding property values toCI {} ofRI {}.", capabilityInstanceId, resourceInstanceId);
+ log.debug("Before adding property values to capability instance {} of resource instance {}.", capabilityInstanceId, resourceInstanceId);
addPropertyValuesRes = addPropertyValuesToCapabilityInstance(capabilityInstance, propertyValues, defaultProperties);
if (addPropertyValuesRes.isRight()) {
error = addPropertyValuesRes.right().value();
- log.debug("failedAddProperties {} ofRI {} statusIs {}.", capabilityInstance.getUniqueId(), resourceInstanceId, error);
+ log.debug("Failed to add properties to capability instance {} of resource instance {}. status is {}", capabilityInstance.getUniqueId(), resourceInstanceId, error);
}
- log.debug("Before adding property values toCI {} ofRI {}.", capabilityInstanceId, resourceInstanceId);
+ log.debug("Before adding property values to capability instance {} of resource instance {}.", capabilityInstanceId, resourceInstanceId);
}
- log.debug("After updating property values of capability {} ofRI {} statusIs {}.", capabilityId, resourceInstanceId, error);
+ log.debug("After updating property values of capability {} of resource instance {}. status is {}.", capabilityId, resourceInstanceId, error);
if (error == null) {
return addPropertyValuesRes;
}
@@ -933,33 +910,33 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC
String componentInstanceId = createdComponentInstance.getUniqueId();
String capabilityInstanceId = capabilityInstPair.getLeft().getUniqueId();
- log.debug("Before cloning capability instance with property values of capability instance {} ofRI {}.", capabilityInstanceId, componentInstanceId);
+ log.debug("Before cloning capability instance with property values of capability instance {} of resource instance {}.", capabilityInstanceId, componentInstanceId);
List<ImmutablePair<PropertyValueData, GraphEdge>> propertyValuePairs;
List<PropertyValueData> newPropertyValues = new ArrayList<>();
CapabilityInstData cloneCapabilityInstance = null;
Either<CapabilityInstData, TitanOperationStatus> cloneCapabilityInstanceNodeRes = null;
- log.debug("Before getting all property values ofCI {} ofRI {}.", capabilityInstanceId, componentInstanceId);
+ log.debug("Before getting all property values of component instance {} of resource instance {}.", capabilityInstanceId, componentInstanceId);
Either<List<ImmutablePair<PropertyValueData, GraphEdge>>, TitanOperationStatus> getPropertyValuesRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityInst), capabilityInstPair.getLeft().getUniqueId(),
GraphEdgeLabels.PROPERTY_VALUE, NodeTypeEnum.PropertyValue, PropertyValueData.class);
if (getPropertyValuesRes.isRight()) {
error = getPropertyValuesRes.right().value();
- log.debug("Failed to retrieve property values of capability instance {} ofCI {} statusIs {}.", capabilityInstPair.getLeft().getUniqueId(), componentInstanceId ,error);
+ log.debug("Failed to retrieve property values of capability instance {} of component instance {}. status is {}", capabilityInstPair.getLeft().getUniqueId(), componentInstanceId, error);
}
- log.debug("After getting all property values ofCI {} ofRI {} statusIs {}.", capabilityInstanceId, componentInstanceId, error);
+ log.debug("After getting all property values of component instance {} of resource instance {}. status is {}.", capabilityInstanceId, componentInstanceId, error);
if (error == null) {
CapabilityInstData cloneCapabilityInst = buildCapabilityInstanceData(componentInstanceId, capability);
- log.debug("Before creating capability instance node {} onGraph.", cloneCapabilityInst.getUniqueId());
+ log.debug("Before creating capability instance node {} on graph.", cloneCapabilityInst.getUniqueId());
cloneCapabilityInstanceNodeRes = titanGenericDao.createNode(cloneCapabilityInst, CapabilityInstData.class);
if (cloneCapabilityInstanceNodeRes.isRight()) {
error = cloneCapabilityInstanceNodeRes.right().value();
- log.debug("Failed to create capability instance of capability {} ofCI {} statusIs {}.", capability.getUniqueId(), componentInstanceId, error);
+ log.debug("Failed to create capability instance of capability {} of component instance {}. status is {}", capability.getUniqueId(), componentInstanceId, error);
}
- log.debug("After creating capability instance node {} onGraph. statusIs {}", cloneCapabilityInst.getUniqueId(), error);
+ log.debug("After creating capability instance node {} on graph. status is {}.", cloneCapabilityInst.getUniqueId(), error);
}
if (error == null) {
- log.debug("Before creating relation from capability instance {} toCapability {} onGraph.", cloneCapabilityInstanceNodeRes.left().value().getUniqueId(), capability.getUniqueId());
+ log.debug("Before creating relation from capability instance {} to capability {} on graph.", cloneCapabilityInstanceNodeRes.left().value().getUniqueId(), capability.getUniqueId());
cloneCapabilityInstance = cloneCapabilityInstanceNodeRes.left().value();
CapabilityData capabilityData = buildCapabilityData(capability);
Map<String, Object> props = new HashMap<>();
@@ -967,29 +944,27 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC
Either<GraphRelation, TitanOperationStatus> createRelationRes = titanGenericDao.createRelation(cloneCapabilityInstance, capabilityData, GraphEdgeLabels.INSTANCE_OF, props);
if (createRelationRes.isRight()) {
error = createRelationRes.right().value();
- log.debug("Failed to associate capability instance {} toCapability {} statusIs {}.", cloneCapabilityInstance.getUniqueId(), capability.getUniqueId(), error);
+ log.debug("Failed to associate capability instance {} to capability {}. status is {}", cloneCapabilityInstance.getUniqueId(), capability.getUniqueId(), error);
}
- log.debug("After creating relation from capability instance {} toCapability {} onGraph. statusIs {}.", cloneCapabilityInstanceNodeRes.left().value().getUniqueId(), capability.getUniqueId(), error);
+ log.debug("After creating relation from capability instance {} to capability {} on graph. status is.", cloneCapabilityInstanceNodeRes.left().value().getUniqueId(), capability.getUniqueId(), error);
}
if (error == null) {
- log.debug("Before cloning property values ofCI {}.", capabilityInstanceId);
+ log.debug("Before cloning property values of component instance {}.", capabilityInstanceId);
propertyValuePairs = getPropertyValuesRes.left().value();
for (ImmutablePair<PropertyValueData, GraphEdge> propertyValuePair : propertyValuePairs) {
Either<PropertyValueData, TitanOperationStatus> clonePropertyValueRes = cloneAssociatePropertyValue(cloneCapabilityInstance, propertyValuePair);
if (clonePropertyValueRes.isRight()) {
error = clonePropertyValueRes.right().value();
- if (log.isDebugEnabled()) {
- log.debug("Failed to clone property value {} ofCapability {} ofCI {}. statusIs {}.", propertyValuePair.getLeft().getUniqueId(), capability.getUniqueId(), componentInstanceId, error);
- }
+ log.debug("Failed to clone property value {} of capability {} of component instance {}. status is {}", propertyValuePair.getLeft().getUniqueId(), capability.getUniqueId(), componentInstanceId, error);
break;
} else {
newPropertyValues.add(clonePropertyValueRes.left().value());
}
}
- log.debug("After cloning property values of CI {} statusIs {}.", capabilityInstanceId, error);
+ log.debug("After cloning property values of component instance {}. status is {}.", capabilityInstanceId, error);
}
- log.debug("After cloning capability instance with property values of capability instance {} ofRI {} statusIs {}.", capabilityInstanceId, componentInstanceId, error);
+ log.debug("After cloning capability instance with property values of capability instance {} of resource instance {}. status is {}.", capabilityInstanceId, componentInstanceId, error);
if (error == null) {
return Either.left(new ImmutablePair<CapabilityInstData, List<PropertyValueData>>(cloneCapabilityInstance, newPropertyValues));
}
@@ -1003,44 +978,40 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC
String capabilityInstanceId = capabilityInstPair.getLeft().getUniqueId();
if (log.isTraceEnabled()) {
- log.trace("Before cloning capability instance with property values of capability instance {} {} {}", capabilityInstanceId, ofRI, componentInstanceId);
+ log.trace("Before cloning capability instance with property values of capability instance {} of resource instance {}", capabilityInstanceId, componentInstanceId);
}
List<ImmutablePair<TitanVertex, Edge>> propertyValuePairs;
Either<TitanVertex, TitanOperationStatus> cloneCapabilityInstanceNodeRes = null;
if (log.isTraceEnabled()) {
- log.trace("Before getting all property values {} {} {} {}", ofCI, capabilityInstanceId, ofRI, componentInstanceId);
+ log.trace("Before getting all property values of component instance {} of resource instance {}", capabilityInstanceId, componentInstanceId);
}
Either<List<ImmutablePair<TitanVertex, Edge>>, TitanOperationStatus> getPropertyValuesRes = titanGenericDao.getChildrenVertecies(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityInst), capabilityInstPair.getLeft().getUniqueId(),
GraphEdgeLabels.PROPERTY_VALUE);
if (getPropertyValuesRes.isRight()) {
error = getPropertyValuesRes.right().value();
- if (log.isDebugEnabled()) {
- log.debug("Failed to retrieve property values of capability instance {} {} {} {} {}", capabilityInstPair.getLeft().getUniqueId(), ofCI, componentInstanceId, statusIs, error);
- }
+ log.debug("Failed to retrieve property values of capability instance {} of component instance {}. status is {}", capabilityInstPair.getLeft().getUniqueId(), componentInstanceId, error);
}
if (log.isTraceEnabled()) {
- log.trace("After getting all property values {} {} {} {} {} {}", ofCI, capabilityInstanceId, ofRI, componentInstanceId, statusIs, error);
+ log.trace("After getting all property values of component instance {} of resource instance {}. status is {}", capabilityInstanceId, componentInstanceId, error);
}
if (error == null) {
CapabilityInstData cloneCapabilityInst = buildCapabilityInstanceData(componentInstanceId, capability);
- log.trace("Before creating capability instance node {} {} ", cloneCapabilityInst.getUniqueId(), onGraph);
+ log.trace("Before creating capability instance node {} on graph", cloneCapabilityInst.getUniqueId());
cloneCapabilityInstanceNodeRes = titanGenericDao.createNode(cloneCapabilityInst);
if (cloneCapabilityInstanceNodeRes.isRight()) {
error = cloneCapabilityInstanceNodeRes.right().value();
- if (log.isDebugEnabled()) {
- log.debug("Failed to create capability instance of capability {} {} {} {} {}", capability.getUniqueId(), ofCI, componentInstanceId, statusIs, error);
- }
+ log.debug("Failed to create capability instance of capability {} of component instance {}. status is {}", capability.getUniqueId(), componentInstanceId, error);
}
if (log.isTraceEnabled()) {
- log.trace("After creating capability instance node {} {} {} {}", cloneCapabilityInst.getUniqueId(), onGraph, statusIs, error);
+ log.trace("After creating capability instance node {} on graph. status is {}", cloneCapabilityInst.getUniqueId(), error);
}
}
CapabilityData capabilityData;
TitanVertex cloneCapabilityInstance = null;
if (error == null) {
if (log.isTraceEnabled()) {
- log.trace("Before creating relation from capability instance {} {} {} {}", capability.getUniqueId(), toCapability, capability.getUniqueId(), onGraph);
+ log.trace("Before creating relation from capability instance {} to capability {} on graph", capability.getUniqueId(), capability.getUniqueId());
}
capabilityData = buildCapabilityData(capability);
Map<String, Object> props = new HashMap<>();
@@ -1049,33 +1020,25 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC
TitanOperationStatus createRelationRes = titanGenericDao.createEdge(cloneCapabilityInstance, capabilityData, GraphEdgeLabels.INSTANCE_OF, props);
if (!createRelationRes.equals(TitanOperationStatus.OK)) {
error = createRelationRes;
- if (log.isDebugEnabled()) {
- log.debug("Failed to associate capability instance {} {} {} {} {}", capabilityData.getUniqueId(), toCapability, capability.getUniqueId(), statusIs, createRelationRes);
- }
- }
- if (log.isTraceEnabled()) {
- log.trace("After creating relation from capability instance {} {} {} {} {} {}", capabilityData.getUniqueId(), toCapability, capability.getUniqueId(), onGraph, statusIs, error);
+ log.debug("Failed to associate capability instance {} to capability {}. status is {}", capabilityData.getUniqueId(), capability.getUniqueId(), createRelationRes);
}
+ log.trace("After creating relation from capability instance {} to capability {} on graph. status is {}", capabilityData.getUniqueId(), capability.getUniqueId(), error);
}
if (error == null) {
- log.trace("Before cloning property values {} {} ", ofCI, capabilityInstanceId);
+ log.trace("Before cloning property values of component instance {} ", capabilityInstanceId);
propertyValuePairs = getPropertyValuesRes.left().value();
for (ImmutablePair<TitanVertex, Edge> propertyValuePair : propertyValuePairs) {
TitanOperationStatus clonePropertyValueRes = cloneAssociatePropertyValue(cloneCapabilityInstance, propertyValuePair);
if (!clonePropertyValueRes.equals(TitanOperationStatus.OK)) {
error = clonePropertyValueRes;
- if (log.isDebugEnabled()) {
- log.debug("Failed to clone property value of capability {} {} {} {} {}", capability.getUniqueId(), ofCI, componentInstanceId, statusIs, error);
- }
+ log.debug("Failed to clone property value of capability {} of component instance {}. status is {}", capability.getUniqueId(), componentInstanceId, error);
break;
}
}
- if (log.isDebugEnabled()) {
- log.debug("After cloning property values {} {} {} {}", ofCI, capabilityInstanceId, statusIs, error);
- }
+ log.debug("After cloning property values of component instance {}. status is {}", capabilityInstanceId, error);
}
- log.debug("After cloning capability instance with property values of capability instance {} ofRI {} statusIs {}.", capabilityInstanceId, componentInstanceId, error);
+ log.debug("After cloning capability instance with property values of capability instance {} of resource instance {}. status is {}.", capabilityInstanceId, componentInstanceId, error);
if (error == null) {
return Either.left(cloneCapabilityInstance);
}
@@ -1100,7 +1063,7 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC
TitanOperationStatus error = null;
String propertyValueID = propertyValuePair.getLeft().getUniqueId();
String capabilityInstanceId = cloneCapabilityInstance.getUniqueId();
- log.debug("Before cloning property values {} ofCI {}.", propertyValueID, capabilityInstanceId);
+ log.debug("Before cloning property values {} of component instance {}.", propertyValueID, capabilityInstanceId);
Map<String, Object> props = propertyValuePair.getRight().getProperties();
PropertyData propertyData = new PropertyData();
@@ -1111,33 +1074,33 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC
PropertyValueData createdValue = null;
Either<GraphRelation, TitanOperationStatus> createRelationRes;
- log.debug("Before creating property values node {} onGraph.", propertyValue.getUniqueId());
+ log.debug("Before creating property values node {} on graph.", propertyValue.getUniqueId());
Either<PropertyValueData, TitanOperationStatus> createValueRes = titanGenericDao.createNode(propertyValue, PropertyValueData.class);
if (createValueRes.isRight()) {
error = createValueRes.right().value();
- log.debug("Failed to create property value for capability instance {} ofRI. statusIs {}.", cloneCapabilityInstance.getUniqueId(), error);
+ log.debug("Failed to create property value for capability instance {} of resource instance. status is {}.", cloneCapabilityInstance.getUniqueId(), error);
}
- log.debug("After creating property values node {} onGraph. statusIs {}.", propertyValue.getUniqueId(), error);
+ log.debug("After creating property values node {} on graph. status is {}.", propertyValue.getUniqueId(), error);
if (error == null) {
createdValue = createValueRes.left().value();
- log.debug("Before creating relation from capability instance {} toValue {}.", capabilityInstanceId, createdValue.getUniqueId());
+ log.debug("Before creating relation from capability instance {} to property value {}.", capabilityInstanceId, createdValue.getUniqueId());
createRelationRes = titanGenericDao.createRelation(cloneCapabilityInstance, createdValue, GraphEdgeLabels.PROPERTY_VALUE, props);
if (createRelationRes.isRight()) {
error = createRelationRes.right().value();
- log.debug("Failed to create relation from capability instance {} toValue {} statusIs {}.", cloneCapabilityInstance.getUniqueId(), createdValue.getUniqueId(), error);
+ log.debug("Failed to create relation from capability instance {} to property value {}. status is {}.", cloneCapabilityInstance.getUniqueId(), createdValue.getUniqueId(), error);
}
- log.debug("After creating relation from capability instance {} toValue {} statusIs {}", capabilityInstanceId, createdValue.getUniqueId(), error);
+ log.debug("After creating relation from capability instance {} to property value {}. status is {}.", capabilityInstanceId, createdValue.getUniqueId(), error);
}
if (error == null) {
- log.debug("Before creating relation from property value {} toProperty {}.", createdValue, propertyData.getUniqueId());
+ log.debug("Before creating relation from property value {} to property {}.", createdValue, propertyData.getUniqueId());
createRelationRes = titanGenericDao.createRelation(createdValue, propertyData, GraphEdgeLabels.PROPERTY_IMPL, props);
if (createRelationRes.isRight()) {
error = createRelationRes.right().value();
- log.debug("Failed to create relation from property value {} toProperty {} statusIs {}.", createdValue.getUniqueId(), propertyId, error);
+ log.debug("Failed to create relation from property value {} to property {}. status is {}.", createdValue.getUniqueId(), propertyId, error);
}
- log.debug("Before creating relation from property value {} toProperty {} statusIs {}.", createdValue, propertyData.getUniqueId(), error);
+ log.debug("Before creating relation from property value {} to property {}. status is {}.", createdValue, propertyData.getUniqueId(), error);
}
- log.debug("After cloning property values {} ofCI {} statusIs {}.", propertyValueID, capabilityInstanceId, error);
+ log.debug("After cloning property values {} of component instance {}. status is {}.", propertyValueID, capabilityInstanceId, error);
if (error == null) {
return Either.left(createdValue);
}
@@ -1150,7 +1113,7 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC
String propertyValueID = (String) titanGenericDao.getProperty(propertyVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty());
String capabilityInstanceId = (String) titanGenericDao.getProperty(capabilityInstanceVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty());
if (log.isTraceEnabled()) {
- log.trace("Before cloning property values {} {} {}", propertyValueID, ofCI, capabilityInstanceId);
+ log.trace("Before cloning property values {} of component instance {}", propertyValueID, capabilityInstanceId);
}
Map<String, Object> props = titanGenericDao.getProperties(propertyValuePair.getRight());
@@ -1165,48 +1128,40 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC
TitanVertex createdValue = null;
TitanOperationStatus createRelationRes;
- log.trace("Before creating property values node {} {} ", propertyValue.getUniqueId(), onGraph);
+ log.trace("Before creating property values node {} on graph.", propertyValue.getUniqueId());
Either<TitanVertex, TitanOperationStatus> createValueRes = titanGenericDao.createNode(propertyValue);
String capabiltyInstId = (String) titanGenericDao.getProperty(capabilityInstanceVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty());
if (createValueRes.isRight()) {
error = createValueRes.right().value();
- if (log.isDebugEnabled()) {
- log.debug("Failed to create property value for capability instance {} {} {} {}", capabiltyInstId, ofRI, statusIs, error);
- }
+ log.debug("Failed to create property value for capability instance {} of resource instance. status is {}", capabiltyInstId, error);
}
if (log.isTraceEnabled()) {
- log.trace("After creating property values node {} {} {} {} ", propertyValue.getUniqueId(), onGraph, statusIs, error);
+ log.trace("After creating property values node {} on graph. status is {} ", propertyValue.getUniqueId(), error);
}
if (error == null) {
createdValue = createValueRes.left().value();
- log.trace("Before creating relation from capability instance {} {} {}", capabilityInstanceId, toValue, propertyValue.getUniqueId());
+ log.trace("Before creating relation from capability instance {} to property value {}", capabilityInstanceId, propertyValue.getUniqueId());
createRelationRes = titanGenericDao.createEdge(capabilityInstanceVertex, createdValue, GraphEdgeLabels.PROPERTY_VALUE, props);
if (!createRelationRes.equals(TitanOperationStatus.OK)) {
error = createRelationRes;
- if (log.isDebugEnabled()) {
- log.debug("Failed to create relation from capability instance {} {} {} {} {}", capabiltyInstId, toValue, propertyValue.getUniqueId(), statusIs, error);
- }
+ log.debug("Failed to create relation from capability instance {} to property value {}. status is {}", capabiltyInstId, propertyValue.getUniqueId(), error);
}
if (log.isTraceEnabled()) {
- log.trace("After creating relation from capability instance {} {} {} {} {} ", capabilityInstanceId, toValue, propertyValue.getUniqueId(), statusIs, error);
+ log.trace("After creating relation from capability instance {} to property value {}. status is {} ", capabilityInstanceId, propertyValue.getUniqueId(), error);
}
}
if (error == null) {
- log.trace("Before creating relation from property value {} {} {} ", createdValue, toProperty, propertyData.getUniqueId());
+ log.trace("Before creating relation from property value {} to property {} ", createdValue, propertyData.getUniqueId());
createRelationRes = titanGenericDao.createEdge(createdValue, propertyData, GraphEdgeLabels.PROPERTY_IMPL, props);
if (!createRelationRes.equals(TitanOperationStatus.OK)) {
error = createRelationRes;
- if (log.isDebugEnabled()) {
- log.debug("Failed to create relation from property value {} {} {} {} {}", propertyValue.getUniqueId(), toProperty, propertyId, statusIs, error);
- }
+ log.debug("Failed to create relation from property value {} to property {}. status is {}", propertyValue.getUniqueId(), propertyId, error);
}
if (log.isTraceEnabled()) {
- log.trace("Before creating relation from property value c", createdValue, toProperty, propertyData.getUniqueId(), statusIs, error);
+ log.trace("Before creating relation from property value {} to property {}. status is {}", createdValue, propertyData.getUniqueId(), error);
}
}
- if (log.isTraceEnabled()) {
- log.trace("After cloning property values {} {} {} {} {}", propertyValueID, ofCI, capabilityInstanceId, statusIs, error);
- }
+ log.trace("After cloning property values {} of component instance {}. status is {}", propertyValueID, capabilityInstanceId, error);
if (error == null) {
return TitanOperationStatus.OK;
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityOperation.java
index 9f00674780..ad43c60b0f 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityOperation.java
@@ -99,7 +99,7 @@ public class CapabilityOperation extends AbstractOperation implements ICapabilit
Either<CapabilityData, TitanOperationStatus> addCapStatus = addCapabilityToResource(resourceId, capabilityName, capabilityDefinition);
if (addCapStatus.isRight()) {
- log.debug("Failed to add capability {} [ {} ] to graph", capabilityName, capabilityDefinition);
+ log.debug("Failed to add capability {} [{}] to Graph", capabilityName, capabilityDefinition);
BeEcompErrorManager.getInstance().logBeFailedCreateNodeError("Add Capability", capabilityName, String.valueOf(addCapStatus.right().value()));
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(addCapStatus.right().value()));
return result;
@@ -108,11 +108,11 @@ public class CapabilityOperation extends AbstractOperation implements ICapabilit
String capabilityUid = capabilityData.getUniqueId();
Either<CapabilityDefinition, StorageOperationStatus> capabilityRes = getCapability(capabilityUid, true);
- log.debug("After fetching capability {} with uid {}. Status is {}", capabilityName, capabilityUid, capabilityRes);
+ log.debug("After fetching capability {} with uid {}. status is {}" ,capabilityName, capabilityUid,capabilityRes);
if (capabilityRes.isRight()) {
StorageOperationStatus status = capabilityRes.right().value();
- log.debug("Failed to fetch capability {] with uid {}. Status is {}", capabilityName, capabilityUid, status);
+ log.debug("Failed to fetch capability {} with uid {}. status is {}", capabilityName, capabilityUid, status);
result = Either.right(status);
return result;
}
@@ -147,7 +147,7 @@ public class CapabilityOperation extends AbstractOperation implements ICapabilit
TitanOperationStatus addCapStatus = addCapabilityToResource(metadataVertex, resourceId, capabilityName, capabilityDefinition);
if (!addCapStatus.equals(TitanOperationStatus.OK)) {
- log.debug("Failed to add capability {} [ {} ]", capabilityName, capabilityDefinition);
+ log.debug("Failed to add capability {} [{}] to Graph", capabilityName, capabilityDefinition);
BeEcompErrorManager.getInstance().logBeFailedCreateNodeError("Add Capability", capabilityName, String.valueOf(addCapStatus));
result = DaoStatusConverter.convertTitanStatusToStorageStatus(addCapStatus);
}
@@ -171,8 +171,6 @@ public class CapabilityOperation extends AbstractOperation implements ICapabilit
CapabilityDefinition capabilityDefinition = new CapabilityDefinition();
capabilityDefinition.setType(capabilityData.getType());
- // TODO esofer do something
-
return capabilityDefinition;
}
@@ -326,7 +324,7 @@ public class CapabilityOperation extends AbstractOperation implements ICapabilit
Either<CapabilityData, TitanOperationStatus> capabiltyRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Capability), uniqueId, CapabilityData.class);
if (capabiltyRes.isRight()) {
TitanOperationStatus status = capabiltyRes.right().value();
- log.debug("Failed to retrieve capability {} from graph. Status is {}", uniqueId, status);
+ log.debug("Failed to retrieve capability {} from graph. status is {}", uniqueId, status);
BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError("Fetch Capability", uniqueId, String.valueOf(status));
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
@@ -343,7 +341,7 @@ public class CapabilityOperation extends AbstractOperation implements ICapabilit
Either<CapabilityTypeData, TitanOperationStatus> capabilityTypeRes = getCapabilityTypeOfCapability(uniqueId);
if (capabilityTypeRes.isRight()) {
TitanOperationStatus status = capabilityTypeRes.right().value();
- log.debug("Failed to retrieve capability type of capability {}. Status is {}", uniqueId, status);
+ log.debug("Failed to retrieve capability type of capability {}. status is {}", uniqueId, status);
BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError("Fetch Capability", uniqueId, String.valueOf(status));
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
@@ -361,7 +359,6 @@ public class CapabilityOperation extends AbstractOperation implements ICapabilit
ImmutablePair<ResourceMetadataData, GraphEdge> pair = parentNode.left().value();
capabilityDefinition.setOwnerId(pair.left.getMetadataDataDefinition().getUniqueId());
List<String> derivedFromList = new ArrayList<>();
- // derivedFromList.add(pair.left.getMetadataDataDefinition().getName());
TitanOperationStatus fillResourceDerivedListFromGraph = fillResourceDerivedListFromGraph(pair.left.getMetadataDataDefinition().getUniqueId(), derivedFromList);
if (fillResourceDerivedListFromGraph.equals(TitanOperationStatus.OK)) {
capabilityDefinition.setCapabilitySources(derivedFromList);
@@ -371,7 +368,7 @@ public class CapabilityOperation extends AbstractOperation implements ICapabilit
Either<List<PropertyDefinition>, TitanOperationStatus> getPropertiesRes = getPropertiesOfCapability(uniqueId, capabilityTypeData.getCapabilityTypeDataDefinition().getType());
if (getPropertiesRes.isRight() && !getPropertiesRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
TitanOperationStatus status = getPropertiesRes.right().value();
- log.debug("Failed to retrieve properties of capability {}. Status is {}", uniqueId, status);
+ log.debug("Failed to retrieve properties of capability {}. status is {}", uniqueId, status);
BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError("Fetch Properties of Capability", uniqueId, String.valueOf(status));
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
@@ -522,7 +519,7 @@ public class CapabilityOperation extends AbstractOperation implements ICapabilit
}
public Either<List<PropertyDefinition>, TitanOperationStatus> getPropertiesOfCapability(String capabilityUid, String capabilityType) {
- log.debug("Before getting properties of capability {} from graph ", capabilityUid);
+ log.debug("Before getting properties of capability {} from graph " , capabilityUid);
List<PropertyDefinition> properties;
Either<List<PropertyDefinition>, TitanOperationStatus> result = null;
@@ -539,7 +536,7 @@ public class CapabilityOperation extends AbstractOperation implements ICapabilit
getPropertiesOfCapabilityTypeRes = getAllCapabilityTypePropertiesFromAllDerivedFrom(capabilityTypeUid);
if (getPropertiesOfCapabilityTypeRes.isRight() && !getPropertiesOfCapabilityTypeRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
TitanOperationStatus status = getPropertiesOfCapabilityTypeRes.right().value();
- log.error("Failed to retrieve properties for capability type {} from graph. Status is {}", capabilityType, status);
+ log.error("Failed to retrieve properties for capability type {} from graph. status is {}", capabilityType, status);
result = Either.right(status);
}
}
@@ -560,14 +557,15 @@ public class CapabilityOperation extends AbstractOperation implements ICapabilit
return result;
}
- protected Either<CapabilityTypeData, TitanOperationStatus> getCapabilityTypeOfCapability(String uniqueId) {
+ @Override
+ public Either<CapabilityTypeData, TitanOperationStatus> getCapabilityTypeOfCapability(String uniqueId) {
Either<ImmutablePair<CapabilityTypeData, GraphEdge>, TitanOperationStatus> capabilityTypeRes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Capability), uniqueId, GraphEdgeLabels.TYPE_OF, NodeTypeEnum.CapabilityType,
CapabilityTypeData.class);
if (capabilityTypeRes.isRight()) {
TitanOperationStatus status = capabilityTypeRes.right().value();//
- log.debug("Cannot find capability type associated with capability {}. Status is {}", uniqueId, status);
+ log.debug("Cannot find capability type associated with capability {}. status is {}", uniqueId, status);
BeEcompErrorManager.getInstance().logBeFailedFindAssociationError("Fetch Capability type", NodeTypeEnum.CapabilityType.getName(), uniqueId, String.valueOf(status));
return Either.right(capabilityTypeRes.right().value());
}
@@ -594,7 +592,7 @@ public class CapabilityOperation extends AbstractOperation implements ICapabilit
Either<List<ImmutablePair<CapabilityData, GraphEdge>>, TitanOperationStatus> capabilitiesNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId, GraphEdgeLabels.CAPABILITY,
NodeTypeEnum.Capability, CapabilityData.class);
- log.debug("After looking for all capabilities under resource {}. Status is {}", resourceId, capabilitiesNodes);
+ log.debug("After looking for all capabilities under resource {}. status is {}" , resourceId , capabilitiesNodes);
if (capabilitiesNodes.isRight()) {
TitanOperationStatus status = capabilitiesNodes.right().value();
return Either.right(status);
@@ -610,7 +608,7 @@ public class CapabilityOperation extends AbstractOperation implements ICapabilit
private Either<CapabilityData, TitanOperationStatus> addCapabilityToResource(String resourceId, String capabilityName, CapabilityDefinition capabilityDefinition) {
- log.debug("Going to add capability {} [ {} ] to resource uid {}", capabilityName, capabilityDefinition, resourceId);
+ log.debug("Going to add capability {} [ {} ] to resource uid {}" , capabilityName, capabilityDefinition, resourceId);
Either<CapabilityData, TitanOperationStatus> createCapRes = createCapability(resourceId, capabilityName, capabilityDefinition);
@@ -647,7 +645,7 @@ public class CapabilityOperation extends AbstractOperation implements ICapabilit
Either<GraphRelation, TitanOperationStatus> associateResourceRes = associateResourceToCapability(resourceId, capabilityName, capabilityData);
if (associateResourceRes.isRight()) {
TitanOperationStatus status = associateResourceRes.right().value();
- log.error("Failed to associate resource " + resourceId + " to capability " + capabilityData + ". status is " + status);
+ log.error("Failed to associate resource {} to capability {}. status is {}", resourceId, capabilityData, status);
return Either.right(status);
}
@@ -702,10 +700,10 @@ public class CapabilityOperation extends AbstractOperation implements ICapabilit
UniqueIdData capabilityTypeIdData = new UniqueIdData(NodeTypeEnum.CapabilityType, UniqueIdBuilder.buildCapabilityTypeUid(capabilityType));
log.debug("Before associating {} to capability type {}.", capabilityData, capabilityType);
Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(capabilityData, capabilityTypeIdData, GraphEdgeLabels.TYPE_OF, null);
- log.debug("After associating {} to capability type {}. status is {}", capabilityData, capabilityType, createRelResult);
+ log.debug("After associating {} to capability type {}. status is {}" , capabilityData, capabilityType, createRelResult);
if (createRelResult.isRight()) {
TitanOperationStatus operationStatus = createRelResult.right().value();
- log.error("Failed to associate capability {} to capability type {} in graph. Status is {}",capabilityData, capabilityTypeIdData, operationStatus);
+ log.error("Failed to associate capability {} to capability type {} in graph. status is {}", capabilityData, capabilityTypeIdData, operationStatus);
return Either.right(operationStatus);
}
return Either.left(createRelResult.left().value());
@@ -733,10 +731,10 @@ public class CapabilityOperation extends AbstractOperation implements ICapabilit
Map<String, Object> props = new HashMap<>();
props.put(GraphPropertiesDictionary.NAME.getProperty(), capabilityName);
Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(resourceIdData, capabilityData, GraphEdgeLabels.CAPABILITY, props);
- log.debug("After associating resource {} to capability {}. Status is {}", resourceId, capabilityData, createRelResult);
+ log.debug("After associating resource {} to capability {}. status is {}" , resourceId, capabilityData, createRelResult);
if (createRelResult.isRight()) {
TitanOperationStatus operationStatus = createRelResult.right().value();
- log.error("Failed to associate resource {} to capability {} in graph. Status is {}", resourceId, capabilityData, operationStatus);
+ log.error("Failed to associate resource {} to capability {} in graph. status is {}", resourceId, capabilityData, operationStatus);
return Either.right(operationStatus);
}
@@ -825,7 +823,7 @@ public class CapabilityOperation extends AbstractOperation implements ICapabilit
resultStatus = deletePropertiesStatus.right().value();
}
if (resultStatus == null) {
- log.debug("Before deleting capability from graph {}", capabilityUid);
+ log.debug("Before deleting capability from graph {}" , capabilityUid);
Either<CapabilityData, TitanOperationStatus> deleteNodeStatus = titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Capability), capabilityUid, CapabilityData.class);
if (deleteNodeStatus.isRight()) {
resultStatus = deleteNodeStatus.right().value();
@@ -848,7 +846,7 @@ public class CapabilityOperation extends AbstractOperation implements ICapabilit
if (deleteAllRes.isRight()) {
TitanOperationStatus status = deleteAllRes.right().value();
if (status != TitanOperationStatus.NOT_FOUND) {
- log.debug("Failed to delete capabilities of resource {}. Status is {}", resourceId, status);
+ log.debug("Failed to delete capabilities of resource {}. status is {}", resourceId, status);
}
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
return result;
@@ -895,7 +893,7 @@ public class CapabilityOperation extends AbstractOperation implements ICapabilit
CapabilityDefinition capabilityDefinition = entry.getValue();
String capabilityUid = capabilityDefinition.getUniqueId();
- log.debug("Before deleting properties of capability {} from graph", capabilityUid);
+ log.debug("Before deleting properties of capability {} from graph " , capabilityUid);
Either<List<ImmutablePair<PropertyData, GraphEdge>>, TitanOperationStatus> deletePropertiesStatus = deletePropertiesOfCapability(capabilityUid);
if (deletePropertiesStatus.isRight() && !deletePropertiesStatus.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
@@ -964,7 +962,7 @@ public class CapabilityOperation extends AbstractOperation implements ICapabilit
Either<Map<String, PropertyDefinition>, TitanOperationStatus> allPropertiesOfCapabilityTypeRes = getAllCapabilityTypePropertiesFromAllDerivedFrom(capabilityTypeUid);
if (allPropertiesOfCapabilityTypeRes.isRight() && !allPropertiesOfCapabilityTypeRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
TitanOperationStatus operationStatus = allPropertiesOfCapabilityTypeRes.right().value();
- log.error("Failed to retrieve properties for capability type " + capabilityType + " from graph. status is " + operationStatus);
+ log.error("Failed to retrieve properties for capability type {} from graph. status is {}", capabilityType, operationStatus);
return Either.right(operationStatus);
}
@@ -976,7 +974,7 @@ public class CapabilityOperation extends AbstractOperation implements ICapabilit
Either<List<PropertyDefinition>, TitanOperationStatus> validateAndReducePropertiesRes = validatePropertyUniqueness(propertiesOfCapabilityType, properties);
if (validateAndReducePropertiesRes.isRight()) {
TitanOperationStatus operationStatus = validateAndReducePropertiesRes.right().value();
- log.error("Failed to add properties to capability {} in graph. Status is {}", capabilityData.getUniqueId(), operationStatus);
+ log.error("Failed to add properties to capability {} in graph. status is {}", capabilityData.getUniqueId(), operationStatus);
return Either.right(operationStatus);
}
}
@@ -984,7 +982,7 @@ public class CapabilityOperation extends AbstractOperation implements ICapabilit
Either<Map<String, PropertyData>, TitanOperationStatus> addPropertiesToCapabilityRes = propertyOperation.addPropertiesToElementType(capabilityData.getUniqueId(), NodeTypeEnum.Capability, properties);
if (addPropertiesToCapabilityRes.isRight()) {
TitanOperationStatus operationStatus = addPropertiesToCapabilityRes.right().value();
- log.error("Failed to add properties to capability {} in graph. Status is {}", capabilityData.getUniqueId(), operationStatus);
+ log.error("Failed to add properties to capability {} in graph. status is {}", capabilityData.getUniqueId(), operationStatus);
return Either.right(operationStatus);
}
return Either.left(addPropertiesToCapabilityRes.left().value());
@@ -1066,7 +1064,7 @@ public class CapabilityOperation extends AbstractOperation implements ICapabilit
}
public Either<List<ImmutablePair<PropertyData, GraphEdge>>, TitanOperationStatus> deletePropertiesOfCapability(String capabilityUid) {
- log.debug("Before deleting properties of capability {} from graph ", capabilityUid);
+ log.debug("Before deleting properties of capability {} from graph " , capabilityUid);
Either<List<ImmutablePair<PropertyData, GraphEdge>>, TitanOperationStatus> deletePropertiesStatus = titanGenericDao.deleteChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Capability), capabilityUid, GraphEdgeLabels.PROPERTY,
NodeTypeEnum.Property, PropertyData.class);
@@ -1118,7 +1116,7 @@ public class CapabilityOperation extends AbstractOperation implements ICapabilit
}
}
if (result.isRight()) {
- log.debug("Failed to update properties of capability {}. Status is {}", uniqueId, result);
+ log.debug("Failed to update properties of capability {}. status is {}", uniqueId, result);
}
return result;
} finally {
@@ -1141,13 +1139,13 @@ public class CapabilityOperation extends AbstractOperation implements ICapabilit
GraphEdgeLabels.CALCULATED_CAPABILITY, NodeTypeEnum.Capability, CapabilityData.class);
if (getCapabilitiesRes.isRight()) {
error = getCapabilitiesRes.right().value();
- log.debug("Failed to retrieve capabilities for resource instance {}. Status is {}", resourceInstanceId, error);
+ log.debug("Failed to retrieve capabilities for resource instance {}. status is {}", resourceInstanceId, error);
} else {
List<ImmutablePair<CapabilityData, GraphEdge>> capabilityPairsList = getCapabilitiesRes.left().value();
List<CapabilityData> capabilityPair = capabilityPairsList.stream().filter(pair -> pair.getLeft().getUniqueId().equals(capabilityUid)).map(pair -> pair.getLeft()).collect(Collectors.toList());
if (capabilityPair.isEmpty()) {
error = TitanOperationStatus.NOT_FOUND;
- log.debug("Failed to retrieve capability {} for resource instance {}. Status is {}", capabilityUid, resourceInstanceId, error);
+ log.debug("Failed to retrieve capability {} for resource instance {}. status is {}", capabilityUid, resourceInstanceId, error);
} else {
capability = capabilityPair.get(0);
}
@@ -1181,7 +1179,7 @@ public class CapabilityOperation extends AbstractOperation implements ICapabilit
Either<Map<String, PropertyDefinition>, TitanOperationStatus> allPropertiesOfCapabilityTypeRes = propertyOperation.findPropertiesOfNode(NodeTypeEnum.CapabilityType, nextParentType);
if (allPropertiesOfCapabilityTypeRes.isRight() && !allPropertiesOfCapabilityTypeRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
error = allPropertiesOfCapabilityTypeRes.right().value();
- log.error("Failed to retrieve properties for capability type {} from graph. Status is {}", nextParentType, error);
+ log.error("Failed to retrieve properties for capability type {} from graph. status is {}", nextParentType, error);
return Either.right(error);
} else if (allPropertiesOfCapabilityTypeRes.isLeft()) {
if (allProperies.isEmpty()) {
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 985399cb65..ddd6017620 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
@@ -72,29 +72,22 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab
}
@Override
- public Either<CapabilityTypeDefinition, StorageOperationStatus> addCapabilityType(
- CapabilityTypeDefinition capabilityTypeDefinition, boolean inTransaction) {
+ public Either<CapabilityTypeDefinition, StorageOperationStatus> addCapabilityType(CapabilityTypeDefinition capabilityTypeDefinition, boolean inTransaction) {
Either<CapabilityTypeDefinition, StorageOperationStatus> result = null;
try {
- Either<CapabilityTypeDefinition, TitanOperationStatus> validationRes = validateUpdateProperties(
- capabilityTypeDefinition);
+ Either<CapabilityTypeDefinition, TitanOperationStatus> validationRes = validateUpdateProperties(capabilityTypeDefinition);
if (validationRes.isRight()) {
- log.error("One or all properties of capability type {} not valid. status is {}",
- capabilityTypeDefinition, validationRes.right().value().name());
- result = Either
- .right(DaoStatusConverter.convertTitanStatusToStorageStatus(validationRes.right().value()));
+ log.error("One or all properties of capability type {} not valid. status is {}", capabilityTypeDefinition, validationRes.right().value().name());
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(validationRes.right().value()));
return result;
}
- Either<CapabilityTypeData, TitanOperationStatus> eitherStatus = addCapabilityTypeToGraph(
- capabilityTypeDefinition);
+ Either<CapabilityTypeData, TitanOperationStatus> eitherStatus = addCapabilityTypeToGraph(capabilityTypeDefinition);
if (eitherStatus.isRight()) {
- log.error("Failed to add capability {} to Graph. status is {}", capabilityTypeDefinition,
- eitherStatus.right().value().name());
- result = Either
- .right(DaoStatusConverter.convertTitanStatusToStorageStatus(eitherStatus.right().value()));
+ log.error("Failed to add capability {} to Graph. status is {}", capabilityTypeDefinition, eitherStatus.right().value().name());
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(eitherStatus.right().value()));
return result;
} else {
CapabilityTypeData capabilityTypeData = eitherStatus.left().value();
@@ -120,28 +113,21 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab
}
- private Either<CapabilityTypeDefinition, TitanOperationStatus> validateUpdateProperties(
- CapabilityTypeDefinition capabilityTypeDefinition) {
+ private Either<CapabilityTypeDefinition, TitanOperationStatus> validateUpdateProperties(CapabilityTypeDefinition capabilityTypeDefinition) {
TitanOperationStatus error = null;
- if (capabilityTypeDefinition.getProperties() != null && !capabilityTypeDefinition.getProperties().isEmpty()
- && capabilityTypeDefinition.getDerivedFrom() != null) {
- Either<Map<String, PropertyDefinition>, TitanOperationStatus> allPropertiesRes = capabilityOperation
- .getAllCapabilityTypePropertiesFromAllDerivedFrom(capabilityTypeDefinition.getDerivedFrom());
- if (allPropertiesRes.isRight()
- && !allPropertiesRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
+ if (capabilityTypeDefinition.getProperties() != null && !capabilityTypeDefinition.getProperties().isEmpty() && capabilityTypeDefinition.getDerivedFrom() != null) {
+ Either<Map<String, PropertyDefinition>, TitanOperationStatus> allPropertiesRes = capabilityOperation.getAllCapabilityTypePropertiesFromAllDerivedFrom(capabilityTypeDefinition.getDerivedFrom());
+ if (allPropertiesRes.isRight() && !allPropertiesRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
error = allPropertiesRes.right().value();
- log.debug("Couldn't fetch derived from property nodes for capability type {}, error: {}",
- capabilityTypeDefinition.getType(), error);
+ log.debug("Couldn't fetch derived from property nodes for capability type {}, error: {}", capabilityTypeDefinition.getType(), error);
}
if (error == null && !allPropertiesRes.left().value().isEmpty()) {
Map<String, PropertyDefinition> derivedFromProperties = allPropertiesRes.left().value();
- capabilityTypeDefinition.getProperties().entrySet().stream()
- .filter(e -> derivedFromProperties.containsKey(e.getKey()) && e.getValue().getType() == null)
+ capabilityTypeDefinition.getProperties().entrySet().stream().filter(e -> derivedFromProperties.containsKey(e.getKey()) && e.getValue().getType() == null)
.forEach(e -> e.getValue().setType(derivedFromProperties.get(e.getKey()).getType()));
- Either<List<PropertyDefinition>, TitanOperationStatus> validatePropertiesRes = capabilityOperation
- .validatePropertyUniqueness(allPropertiesRes.left().value(), capabilityTypeDefinition
- .getProperties().values().stream().collect(Collectors.toList()));
+ Either<List<PropertyDefinition>, TitanOperationStatus> validatePropertiesRes = capabilityOperation.validatePropertyUniqueness(allPropertiesRes.left().value(),
+ capabilityTypeDefinition.getProperties().values().stream().collect(Collectors.toList()));
if (validatePropertiesRes.isRight()) {
error = validatePropertiesRes.right().value();
}
@@ -163,8 +149,7 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab
protected CapabilityTypeDefinition convertCTDataToCTDefinition(CapabilityTypeData capabilityTypeData) {
log.debug("The object returned after create capability is {}", capabilityTypeData);
- CapabilityTypeDefinition capabilityTypeDefResult = new CapabilityTypeDefinition(
- capabilityTypeData.getCapabilityTypeDataDefinition());
+ CapabilityTypeDefinition capabilityTypeDefResult = new CapabilityTypeDefinition(capabilityTypeData.getCapabilityTypeDataDefinition());
return capabilityTypeDefResult;
}
@@ -177,14 +162,12 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab
*
* 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)
+ * 3. Add property node and associate it to the node created at #1. (per property & if exists)
*
* @param capabilityTypeDefinition
* @return
*/
- private Either<CapabilityTypeData, TitanOperationStatus> addCapabilityTypeToGraph(
- CapabilityTypeDefinition capabilityTypeDefinition) {
+ private Either<CapabilityTypeData, TitanOperationStatus> addCapabilityTypeToGraph(CapabilityTypeDefinition capabilityTypeDefinition) {
log.debug("Got capability type {}", capabilityTypeDefinition);
@@ -194,37 +177,31 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab
CapabilityTypeData capabilityTypeData = buildCapabilityTypeData(capabilityTypeDefinition, ctUniqueId);
log.debug("Before adding capability type to graph. capabilityTypeData = {}", capabilityTypeData);
- Either<CapabilityTypeData, TitanOperationStatus> createCTResult = titanGenericDao.createNode(capabilityTypeData,
- CapabilityTypeData.class);
+ Either<CapabilityTypeData, TitanOperationStatus> createCTResult = titanGenericDao.createNode(capabilityTypeData, CapabilityTypeData.class);
log.debug("After adding capability type to graph. status is = {}", createCTResult);
if (createCTResult.isRight()) {
TitanOperationStatus operationStatus = createCTResult.right().value();
- log.error("Failed to capability type " + capabilityTypeDefinition.getType() + " to graph. status is "
- + operationStatus);
+ log.error("Failed to capability type {} to graph. status is {}", capabilityTypeDefinition.getType(), operationStatus);
return Either.right(operationStatus);
}
CapabilityTypeData resultCTD = createCTResult.left().value();
Map<String, PropertyDefinition> propertiesMap = capabilityTypeDefinition.getProperties();
Collection<PropertyDefinition> properties = propertiesMap != null ? propertiesMap.values() : null;
- Either<Map<String, PropertyData>, TitanOperationStatus> addPropertiesToCapablityType = propertyOperation
- .addPropertiesToElementType(resultCTD.getUniqueId(), NodeTypeEnum.CapabilityType, propertiesMap);
+ Either<Map<String, PropertyData>, TitanOperationStatus> addPropertiesToCapablityType = propertyOperation.addPropertiesToElementType(resultCTD.getUniqueId(), NodeTypeEnum.CapabilityType, propertiesMap);
if (addPropertiesToCapablityType.isRight()) {
- log.error(
- "Failed add properties " + propertiesMap + " to capability " + capabilityTypeDefinition.getType());
+ log.error("Failed add properties {} to capability {}", propertiesMap, capabilityTypeDefinition.getType());
return Either.right(addPropertiesToCapablityType.right().value());
}
String derivedFrom = capabilityTypeDefinition.getDerivedFrom();
if (derivedFrom != null) {
- log.debug(
- "Before creating relation between capability type " + ctUniqueId + " to its parent " + derivedFrom);
+ log.debug("Before creating relation between capability 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);
+ 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());
}
@@ -234,8 +211,7 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab
}
- private CapabilityTypeData buildCapabilityTypeData(CapabilityTypeDefinition capabilityTypeDefinition,
- String ctUniqueId) {
+ private CapabilityTypeData buildCapabilityTypeData(CapabilityTypeDefinition capabilityTypeDefinition, String ctUniqueId) {
CapabilityTypeData capabilityTypeData = new CapabilityTypeData(capabilityTypeDefinition);
@@ -250,8 +226,7 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab
}
@Override
- public Either<CapabilityTypeDefinition, StorageOperationStatus> getCapabilityType(String uniqueId,
- boolean inTransaction) {
+ public Either<CapabilityTypeDefinition, StorageOperationStatus> getCapabilityType(String uniqueId, boolean inTransaction) {
Either<CapabilityTypeDefinition, StorageOperationStatus> result = null;
try {
@@ -261,7 +236,7 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab
if (ctResult.isRight()) {
TitanOperationStatus status = ctResult.right().value();
if (status != TitanOperationStatus.NOT_FOUND) {
- log.error("Failed to retrieve information on capability type {}. Status is {}", uniqueId, status);
+ log.error("Failed to retrieve information on capability type {}. status is {}", uniqueId, status);
}
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(ctResult.right().value()));
return result;
@@ -288,33 +263,30 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab
Either<CapabilityTypeDefinition, TitanOperationStatus> result = null;
- Either<CapabilityTypeData, TitanOperationStatus> capabilityTypesRes = titanGenericDao.getNode(
- UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityType), uniqueId, CapabilityTypeData.class);
+ Either<CapabilityTypeData, TitanOperationStatus> capabilityTypesRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityType), uniqueId, CapabilityTypeData.class);
if (capabilityTypesRes.isRight()) {
TitanOperationStatus status = capabilityTypesRes.right().value();
- log.debug("Capability type {} cannot be found in graph. Status is {}", uniqueId, status);
+ log.debug("Capability type {} cannot be found in graph. status is {}", uniqueId, status);
return Either.right(status);
}
CapabilityTypeData ctData = capabilityTypesRes.left().value();
- CapabilityTypeDefinition capabilityTypeDefinition = new CapabilityTypeDefinition(
- ctData.getCapabilityTypeDataDefinition());
+ CapabilityTypeDefinition capabilityTypeDefinition = new CapabilityTypeDefinition(ctData.getCapabilityTypeDataDefinition());
TitanOperationStatus propertiesStatus = fillProperties(uniqueId, capabilityTypeDefinition);
if (propertiesStatus != TitanOperationStatus.OK) {
- log.error("Failed to fetch properties of capability type " + uniqueId);
+ log.error("Failed to fetch properties of capability type {}", uniqueId);
return Either.right(propertiesStatus);
}
- Either<ImmutablePair<CapabilityTypeData, GraphEdge>, TitanOperationStatus> parentNode = titanGenericDao
- .getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityType), uniqueId,
- GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.CapabilityType, CapabilityTypeData.class);
- log.debug("After retrieving DERIVED_FROM node of {}. Status is {}", uniqueId, parentNode);
+ Either<ImmutablePair<CapabilityTypeData, GraphEdge>, TitanOperationStatus> parentNode = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityType), uniqueId, GraphEdgeLabels.DERIVED_FROM,
+ NodeTypeEnum.CapabilityType, CapabilityTypeData.class);
+ log.debug("After retrieving DERIVED_FROM node of {}. status is {}", uniqueId, parentNode);
if (parentNode.isRight()) {
TitanOperationStatus titanOperationStatus = parentNode.right().value();
if (titanOperationStatus != TitanOperationStatus.NOT_FOUND) {
- log.error("Failed to find the parent capability of capability type {}. Status is {}", uniqueId, titanOperationStatus);
+ log.error("Failed to find the parent capability of capability type {}. status is {}", uniqueId, titanOperationStatus);
result = Either.right(titanOperationStatus);
return result;
}
@@ -331,11 +303,10 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab
private TitanOperationStatus fillProperties(String uniqueId, CapabilityTypeDefinition capabilityTypeDefinition) {
- Either<Map<String, PropertyDefinition>, TitanOperationStatus> findPropertiesOfNode = propertyOperation
- .findPropertiesOfNode(NodeTypeEnum.CapabilityType, uniqueId);
+ Either<Map<String, PropertyDefinition>, TitanOperationStatus> findPropertiesOfNode = propertyOperation.findPropertiesOfNode(NodeTypeEnum.CapabilityType, uniqueId);
if (findPropertiesOfNode.isRight()) {
TitanOperationStatus titanOperationStatus = findPropertiesOfNode.right().value();
- log.debug("After looking for properties of vertex {}. Status is {}", uniqueId, titanOperationStatus);
+ log.debug("After looking for properties of vertex {}. status is {}", uniqueId, titanOperationStatus);
if (TitanOperationStatus.NOT_FOUND.equals(titanOperationStatus)) {
return TitanOperationStatus.OK;
} else {
@@ -348,12 +319,10 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab
}
}
- public Either<Boolean, StorageOperationStatus> isCapabilityTypeDerivedFrom(String childCandidateType,
- String parentCandidateType) {
+ 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);
+ 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);
@@ -363,14 +332,12 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab
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);
+ 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);
+ 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.");
@@ -379,8 +346,7 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab
}
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);
+ log.debug("Verified that capability type {} derives from capability type {}", childCandidateType, parentCandidateType);
return Either.left(true);
}
childUniqueId = derivedFromUniqueId;
@@ -402,8 +368,7 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab
}
@Override
- public Either<CapabilityTypeDefinition, StorageOperationStatus> addCapabilityType(
- CapabilityTypeDefinition capabilityTypeDefinition) {
+ public Either<CapabilityTypeDefinition, StorageOperationStatus> addCapabilityType(CapabilityTypeDefinition capabilityTypeDefinition) {
return addCapabilityType(capabilityTypeDefinition, false);
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperation.java
index cb85888780..c487b0ce71 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperation.java
@@ -29,6 +29,7 @@ import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.Set;
+import java.util.UUID;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
@@ -50,10 +51,12 @@ import org.openecomp.sdc.be.dao.neo4j.GraphEdgePropertiesDictionary;
import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
-import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.PropertyRule;
+import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
@@ -67,7 +70,8 @@ import org.openecomp.sdc.be.model.ComponentInstanceAttribute;
import org.openecomp.sdc.be.model.ComponentInstanceInput;
import org.openecomp.sdc.be.model.ComponentInstanceProperty;
import org.openecomp.sdc.be.model.DataTypeDefinition;
-import org.openecomp.sdc.be.model.GetInputValueInfo;
+import org.openecomp.sdc.be.model.GroupDefinition;
+import org.openecomp.sdc.be.model.GroupInstance;
import org.openecomp.sdc.be.model.HeatParameterDefinition;
import org.openecomp.sdc.be.model.IComponentInstanceConnectedElement;
import org.openecomp.sdc.be.model.InputDefinition;
@@ -78,6 +82,7 @@ import org.openecomp.sdc.be.model.RequirementAndRelationshipPair;
import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
import org.openecomp.sdc.be.model.RequirementDefinition;
import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
import org.openecomp.sdc.be.model.operations.api.IAttributeOperation;
import org.openecomp.sdc.be.model.operations.api.IComponentInstanceOperation;
@@ -99,6 +104,7 @@ import org.openecomp.sdc.be.resources.data.RelationshipTypeData;
import org.openecomp.sdc.be.resources.data.RequirementData;
import org.openecomp.sdc.be.resources.data.ResourceMetadataData;
import org.openecomp.sdc.be.resources.data.UniqueIdData;
+import org.openecomp.sdc.be.resources.data.UserData;
import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
import org.openecomp.sdc.common.api.ArtifactTypeEnum;
import org.openecomp.sdc.common.config.EcompErrorName;
@@ -137,9 +143,6 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
private CapabilityInstanceOperation capabilityInstanceOperation;
@Autowired
- private CapabilityTypeOperation capabilityTypeOperation;
-
- @Autowired
private RequirementOperation requirementOperation;
@Autowired
@@ -160,6 +163,12 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
@Autowired
private ApplicationDataTypeCache dataTypeCache;
+ @Autowired
+ protected GroupOperation groupOperation;
+
+ @Autowired
+ protected GroupInstanceOperation groupInstanceOperation;
+
/**
* FOR TEST ONLY
*
@@ -180,12 +189,15 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
NodeTypeEnum compInstNodeType, boolean allowDeleted, boolean inTransaction) {
Either<ComponentInstance, StorageOperationStatus> result = null;
+ if (!ValidationUtils.validateStringNotEmpty(componentInstance.getCustomizationUUID())) {
+ generateCustomizationUUID(componentInstance);
+ }
try {
Either<ComponentInstance, TitanOperationStatus> addRes = addComponentInstanceToContainerComponent(containerComponentId, containerNodeType, instanceNumber, isCreateLocgicalName, componentInstance, compInstNodeType, allowDeleted);
if (addRes.isRight()) {
TitanOperationStatus status = addRes.right().value();
- log.error("Failed to add resource instance {} to service {}. Status is {}", componentInstance, containerComponentId, status);
+ log.error("Failed to add resource instance {} to service {}. status is {}", componentInstance, containerComponentId, status);
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
return result;
}
@@ -246,7 +258,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
if (deleteRes.isRight()) {
TitanOperationStatus status = deleteRes.right().value();
- log.error("Failed to remove resource instance {} from component {}. Status is {}", resourceInstUid, containerComponentId, status);
+ log.error("Failed to remove resource instance {} from component {}. status is {}", resourceInstUid, containerComponentId, status);
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
return result;
}
@@ -288,7 +300,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
if (updateRes.isRight()) {
TitanOperationStatus status = updateRes.right().value();
- log.error("Failed to find resource instance name {}. Status is {}", uniqId, status);
+ log.error("Failed to find resource instance name {}. status is {}", uniqId, status);
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
return result;
}
@@ -366,10 +378,48 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
Map<String, Object> properties = titanGenericDao.getProperties(ciVertex);
ComponentInstanceData createdComponentInstance = GraphElementFactory.createElement(NodeTypeEnum.ResourceInstance.getName(), GraphElementTypeEnum.Node, properties, ComponentInstanceData.class);
+ Either<ComponentInstance, TitanOperationStatus> createdResourceInstanceRes = createGroupInstancesOnComponentInstance(componentInstance, ciVertex, createdComponentInstance);
+ return createdResourceInstanceRes;
+ }
+
+
+ public Either<ComponentInstance, TitanOperationStatus> createGroupInstancesOnComponentInstance(ComponentInstance componentInstance, TitanVertex ciVertex, ComponentInstanceData createdComponentInstance) {
ComponentInstance createdResourceInstance = new ComponentInstance(createdComponentInstance.getComponentInstDataDefinition());
+ createdResourceInstance.setGroupInstances(componentInstance.getGroupInstances());
+ List<GroupInstance> groupInstancesList = new ArrayList<GroupInstance>();
+ List<GroupDefinition> group = null;
+ Either<List<GroupDefinition>, TitanOperationStatus> groupEither = groupOperation.getAllGroupsFromGraph(createdResourceInstance.getComponentUid(), NodeTypeEnum.Resource);
+ if (groupEither.isRight() && groupEither.right().value() != TitanOperationStatus.OK && groupEither.right().value() != TitanOperationStatus.NOT_FOUND) {
+ TitanOperationStatus status = groupEither.right().value();
+ log.debug("Failed to associate group instances to component instance {}. Status is {}", componentInstance.getUniqueId(), status);
+ return Either.right(status);
+ } else {
+ if (groupEither.isLeft()) {
+ group = groupEither.left().value();
+ if (group != null && !group.isEmpty()) {
+ List<GroupDefinition> vfGroupsList = group.stream().filter(p -> p.getType().equals("org.openecomp.groups.VfModule")).collect(Collectors.toList());
+ for (GroupDefinition groupDefinition : vfGroupsList) {
+ Either<GroupInstance, StorageOperationStatus> status = createGroupInstance(ciVertex, groupDefinition, createdResourceInstance);
+ if (status.isRight()) {
+ log.debug("Failed to associate group instances to component instance {}. Status is {}", componentInstance.getUniqueId(), status);
+
+ } else {
+ GroupInstance groupInstance = status.left().value();
+ groupInstancesList.add(groupInstance);
+ }
+
+ }
+ createdResourceInstance.setGroupInstances(groupInstancesList);
+ }
+ }
+ }
return Either.left(createdResourceInstance);
+ }
+ public void generateCustomizationUUID(ComponentInstance componentInstance) {
+ UUID uuid = UUID.randomUUID();
+ componentInstance.setCustomizationUUID(uuid.toString());
}
/**
@@ -409,7 +459,6 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
}
String originType = (String) titanGenericDao.getProperty(originVertex, GraphPropertiesDictionary.LABEL.getProperty());
String resourceType = (String) titanGenericDao.getProperty(originVertex, GraphPropertiesDictionary.RESOURCE_TYPE.getProperty());
- detectOriginType(originType, componentInstanceData, resourceType);
log.trace("Before adding component instance to graph. componentInstanceData = {}", componentInstanceData);
@@ -427,7 +476,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
TitanOperationStatus associateContainerRes = associateContainerCompToComponentInstance(metadataVertex, createdComponentInstanceVertex, logicalName);
String componentInstanceUniqueId = componentInstanceData.getUniqueId();
- if (!associateContainerRes.equals(TitanOperationStatus.OK)) {
+ if (associateContainerRes != TitanOperationStatus.OK) {
BeEcompErrorManager.getInstance().logBeDaoSystemError("Add Component Instance");
log.debug("Failed to associate container component {} to component instance {}. Status is {}", containerComponentId, componentInstanceUniqueId, associateContainerRes);
return Either.right(associateContainerRes);
@@ -435,20 +484,20 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
String originId = (String) titanGenericDao.getProperty(createdComponentInstanceVertex, GraphPropertiesDictionary.TYPE.getProperty());
TitanOperationStatus associateToInstOriginComponent = associateToInstOriginComponent(createdComponentInstanceVertex, originVertex, originId);
- if (!associateToInstOriginComponent.equals(TitanOperationStatus.OK)) {
+ if (associateToInstOriginComponent != TitanOperationStatus.OK) {
BeEcompErrorManager.getInstance().logBeDaoSystemError("Add Component Instance");
log.debug("Failed to associate component instance {} to its origin component {}. Status is {}", componentInstanceUniqueId, componentInstanceData.getComponentInstDataDefinition().getComponentUid(), associateToInstOriginComponent);
return Either.right(associateToInstOriginComponent);
}
TitanOperationStatus associateCompInstToRequirements = associateCompInstToRequirements(createdComponentInstanceVertex, containerNodeType, compInstNodeType, originId);
- if (!associateCompInstToRequirements.equals(TitanOperationStatus.OK)) {
+ if (associateCompInstToRequirements != TitanOperationStatus.OK) {
BeEcompErrorManager.getInstance().logBeDaoSystemError("Add Component Instance");
log.debug("Failed to associate component instance {} to its origin requirements. Status is {}", componentInstanceUniqueId, associateCompInstToRequirements);
return Either.right(associateCompInstToRequirements);
}
TitanOperationStatus associateCompInstToCapabilities = associateCompInstToCapabilities(createdComponentInstanceVertex, containerNodeType, compInstNodeType, originId);
- if (!associateCompInstToCapabilities.equals(TitanOperationStatus.OK)) {
+ if (associateCompInstToCapabilities != TitanOperationStatus.OK) {
BeEcompErrorManager.getInstance().logBeDaoSystemError("Add Component Instance");
log.debug("Failed to associate component instance {} to its origin capabilities. Status is {}", componentInstanceUniqueId, associateCompInstToCapabilities);
return Either.right(associateCompInstToCapabilities);
@@ -469,7 +518,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
} else if (containerNodeType.equals(NodeTypeEnum.Resource) && componentInstance.getCapabilities() != null && !componentInstance.getCapabilities().isEmpty()) {
// in case of creation from scar
TitanOperationStatus addPropertiesRes = createCapabilityInstancesWithPropertyValues(createdComponentInstanceVertex, componentInstanceUniqueId, componentInstance.getCapabilities(), true);
- if (!addPropertiesRes.equals(TitanOperationStatus.OK)) {
+ if (addPropertiesRes != TitanOperationStatus.OK) {
status = addPropertiesRes;
log.debug("Failed to create capability instances with property values for component instance {}. Status is {}", componentInstance.getUniqueId(), status);
}
@@ -490,13 +539,14 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
// in case of cloning of service
log.trace("Before associating created component instance {} to cloned capability instances.", componentInstanceUniqueId);
TitanOperationStatus associationStatus = associateCreatedComponentInstanceToClonedCapabilityInstances(createdComponentInstanceVertex, componentInstanceUniqueId, cloneCapabilityInstancesRes.left().value());
- if (!associationStatus.equals(TitanOperationStatus.OK) && !associationStatus.equals(TitanOperationStatus.NOT_FOUND)) {
+ if (associationStatus != TitanOperationStatus.OK && associationStatus != TitanOperationStatus.NOT_FOUND) {
status = associationStatus;
log.debug("Failed to associate capability instances to component instance {}. Status is {}", componentInstance.getUniqueId(), status);
}
log.trace("After associating created component instance {} to cloned capability instances. Status is {}", componentInstanceUniqueId, status);
}
}
+
if (status == null) {
// ComponentInstance createdResourceInstance = new
// ComponentInstance(createdComponentInstance.getComponentInstDataDefinition());
@@ -536,7 +586,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
CapabilityDefinition capability = capailityEntry.getValue().get(0);
if (capability.getProperties() != null && !capability.getProperties().isEmpty()) {
TitanOperationStatus addPropertiesRes = addCapabilityPropertyValuesToResourceInstance(resourceInstanceVertex, resourceInstanceId, capability, isNewlyCreatedResourceInstance);
- if (!addPropertiesRes.equals(TitanOperationStatus.OK)) {
+ if (addPropertiesRes != TitanOperationStatus.OK) {
result = addPropertiesRes;
log.debug("Failed to add property values to capabilities of component instance {}. Status is {}", resourceInstanceId, result);
return result;
@@ -555,7 +605,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
capInstPair.getRight().getProperties());
if (associateComponentInstanceToCapabilityinstanceRes.isRight()) {
error = associateComponentInstanceToCapabilityinstanceRes.right().value();
- log.debug("Failed to associate capability instance {} to resource instance {}. Status is {}.", capInstPair.getLeft().getUniqueId(), newComponentResourceId, error);
+ log.debug("Failed to associate capability instance {} to resource instance {} status is {}.", capInstPair.getLeft().getUniqueId(), newComponentResourceId, error);
break;
} else {
relationsToCapabilityInstances.add(associateComponentInstanceToCapabilityinstanceRes.left().value());
@@ -571,7 +621,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
TitanOperationStatus error = null;
for (ImmutablePair<TitanVertex, GraphEdge> capInstPair : capabilityInstances) {
TitanOperationStatus associateComponentInstanceToCapabilityinstanceRes = titanGenericDao.createEdge(riVertex, capInstPair.getLeft(), GraphEdgeLabels.CAPABILITY_INST, capInstPair.getRight().getProperties());
- if (!associateComponentInstanceToCapabilityinstanceRes.equals(TitanOperationStatus.OK)) {
+ if (associateComponentInstanceToCapabilityinstanceRes != TitanOperationStatus.OK) {
error = associateComponentInstanceToCapabilityinstanceRes;
log.debug("Failed to associate capability instance {} to resource instance {} status is {} .", capInstPair.getLeft(), newComponentResourceId, error);
break;
@@ -595,7 +645,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
GraphEdgeLabels.RESOURCE_INST, NodeTypeEnum.ResourceInstance, ComponentInstanceData.class);
if (getAllResourceInstanceRes.isRight() && !getAllResourceInstanceRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
error = getAllResourceInstanceRes.right().value();
- log.debug("Failed to retrieve resource instances from resource {}. Status is {}.", resourceId, error);
+ log.debug("Failed to retrieve resource instances from resource {} status is {}.", resourceId, error);
}
if (getAllResourceInstanceRes.isLeft()) {
resourceInstancesPair = getAllResourceInstanceRes.left().value();
@@ -606,7 +656,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
GraphEdgeLabels.CAPABILITY_INST, NodeTypeEnum.CapabilityInst, CapabilityInstData.class);
if (getCapabilityInstancesRes.isRight() && !getCapabilityInstancesRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
error = getCapabilityInstancesRes.right().value();
- log.debug("Failed to retrieve capability instances of resource instance {}. Status is {}", ri.getUniqueId(), error);
+ log.debug("Failed to retrieve capability instances of resource instance {} status is {}.", ri.getUniqueId(), error);
break;
}
if (getCapabilityInstancesRes.isLeft()) {
@@ -620,7 +670,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
capInstPair.getRight().getProperties());
if (associateComponentInstanceToCapabilityinstanceRes.isRight()) {
error = associateComponentInstanceToCapabilityinstanceRes.right().value();
- log.debug("Failed to associate capability instance {} to resource instance {}. Status is {}", capInstPair.getLeft().getUniqueId(), componentResourceId, error);
+ log.debug("Failed to associate capability instance {} to resource instance {} status is {}.", capInstPair.getLeft().getUniqueId(), componentResourceId, error);
break;
} else {
relationsToCapabilityInstances.add(associateComponentInstanceToCapabilityinstanceRes.left().value());
@@ -633,8 +683,10 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
return Either.right(error);
}
- private void detectOriginType(String label, ComponentInstanceData componentInstanceData, String resourceTypeStr) {
- switch (NodeTypeEnum.getByName(label)) {
+ private NodeTypeEnum detectOriginType(String label, ComponentInstanceData componentInstanceData, String resourceTypeStr) {
+ NodeTypeEnum res = null;
+ res = NodeTypeEnum.getByName(label);
+ switch (res) {
case Service:
componentInstanceData.getComponentInstDataDefinition().setOriginType(OriginTypeEnum.SERVICE);
break;
@@ -650,6 +702,9 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
case VFC:
componentInstanceData.getComponentInstDataDefinition().setOriginType(OriginTypeEnum.VFC);
break;
+ case VFCMT:
+ componentInstanceData.getComponentInstDataDefinition().setOriginType(OriginTypeEnum.VFCMT);
+ break;
case CP:
componentInstanceData.getComponentInstDataDefinition().setOriginType(OriginTypeEnum.CP);
break;
@@ -661,6 +716,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
default:
break;
}
+ return res;
}
private Either<GraphRelation, TitanOperationStatus> associateToInstOriginComponent(ComponentInstanceData componentInstanceData, NodeTypeEnum compInstNodeType) {
@@ -669,10 +725,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(componentInstanceData, resourceIdData, GraphEdgeLabels.INSTANCE_OF, null);
- log.debug("After associating resource instance {} to resource {}. Status is {}",
- componentInstanceData.getUniqueId(),
- componentInstanceData.getComponentInstDataDefinition().getUniqueId(),
- createRelation);
+ log.debug("After associating resource instance {} to resource {}. status is {}", componentInstanceData.getUniqueId(), componentInstanceData.getComponentInstDataDefinition().getUniqueId(), createRelation);
return createRelation;
}
@@ -742,12 +795,12 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
props.put(GraphEdgePropertiesDictionary.OWNER_ID.getProperty(), componentInstanceData.getUniqueId());
if (requirementDef.getMinOccurrences() == null) {
- props.put(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty(), RequirementData.MIN_OCCURRENCES);
+ props.put(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty(), RequirementDataDefinition.MIN_OCCURRENCES);
} else {
props.put(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty(), requirementDef.getMinOccurrences());
}
if (requirementDef.getMaxOccurrences() == null) {
- props.put(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty(), RequirementData.MAX_DEFAULT_OCCURRENCES);
+ props.put(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty(), RequirementDataDefinition.MAX_DEFAULT_OCCURRENCES);
} else {
props.put(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty(), requirementDef.getMaxOccurrences());
}
@@ -784,12 +837,12 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
props.put(GraphEdgePropertiesDictionary.OWNER_ID.getProperty(), compoInstId);
if (requirementDef.getMinOccurrences() == null) {
- props.put(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty(), RequirementData.MIN_OCCURRENCES);
+ props.put(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty(), RequirementDataDefinition.MIN_OCCURRENCES);
} else {
props.put(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty(), requirementDef.getMinOccurrences());
}
if (requirementDef.getMaxOccurrences() == null) {
- props.put(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty(), RequirementData.MAX_DEFAULT_OCCURRENCES);
+ props.put(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty(), RequirementDataDefinition.MAX_DEFAULT_OCCURRENCES);
} else {
props.put(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty(), requirementDef.getMaxOccurrences());
}
@@ -857,8 +910,8 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
GraphEdge edge = calculatedReq.right;
Map<String, Object> properties = edge.getProperties();
String source = null;
- String occurrences = RequirementData.MAX_DEFAULT_OCCURRENCES;
- String minOccurrences = RequirementData.MIN_OCCURRENCES;
+ String occurrences = RequirementDataDefinition.MAX_DEFAULT_OCCURRENCES;
+ String minOccurrences = RequirementDataDefinition.MIN_OCCURRENCES;
if (properties != null && properties.containsKey(GraphEdgePropertiesDictionary.SOURCE.getProperty())) {
source = (String) properties.get(GraphEdgePropertiesDictionary.SOURCE.getProperty());
@@ -898,8 +951,8 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
Edge edge = calculatedReq.right;
Map<String, Object> properties = titanGenericDao.getProperties(edge);
String source = null;
- String occurrences = RequirementData.MAX_DEFAULT_OCCURRENCES;
- String minOccurrences = RequirementData.MIN_OCCURRENCES;
+ String occurrences = RequirementDataDefinition.MAX_DEFAULT_OCCURRENCES;
+ String minOccurrences = RequirementDataDefinition.MIN_OCCURRENCES;
if (properties != null && properties.containsKey(GraphEdgePropertiesDictionary.SOURCE.getProperty())) {
source = (String) properties.get(GraphEdgePropertiesDictionary.SOURCE.getProperty());
@@ -943,8 +996,8 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
if (properties != null && properties.containsKey(GraphEdgePropertiesDictionary.SOURCE.getProperty())) {
source = (String) properties.get(GraphEdgePropertiesDictionary.SOURCE.getProperty());
}
- String minOccurrences = CapabilityData.MIN_OCCURRENCES;
- String occurrences = CapabilityData.MAX_OCCURRENCES;
+ String minOccurrences = CapabilityDataDefinition.MIN_OCCURRENCES;
+ String occurrences = CapabilityDataDefinition.MAX_OCCURRENCES;
if (properties != null && properties.containsKey(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty())) {
minOccurrences = (String) properties.get(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty());
}
@@ -982,8 +1035,8 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
if (properties != null && properties.containsKey(GraphEdgePropertiesDictionary.SOURCE.getProperty())) {
source = (String) properties.get(GraphEdgePropertiesDictionary.SOURCE.getProperty());
}
- String minOccurrences = CapabilityData.MIN_OCCURRENCES;
- String occurrences = CapabilityData.MAX_OCCURRENCES;
+ String minOccurrences = CapabilityDataDefinition.MIN_OCCURRENCES;
+ String occurrences = CapabilityDataDefinition.MAX_OCCURRENCES;
if (properties != null && properties.containsKey(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty())) {
minOccurrences = (String) properties.get(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty());
}
@@ -1021,8 +1074,8 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
log.trace("Creating calculated capability relation from component instance {} to capability {}", componentInstanceData.getUniqueId(), capabilityData.getUniqueId());
CapabilityData capabilityDataNode = new CapabilityData();
capabilityDataNode.setUniqueId(capabilityData.getUniqueId());
- String minOccurrences = CapabilityData.MIN_OCCURRENCES;
- String occurrences = CapabilityData.MAX_OCCURRENCES;
+ String minOccurrences = CapabilityDataDefinition.MIN_OCCURRENCES;
+ String occurrences = CapabilityDataDefinition.MAX_OCCURRENCES;
if (capabilityData.getMinOccurrences() != null) {
minOccurrences = capabilityData.getMinOccurrences();
}
@@ -1054,8 +1107,8 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
log.trace("Creating calculated capability relation from component instance {} to capability {}", compoInstId, capabilityData.getUniqueId());
CapabilityData capabilityDataNode = new CapabilityData();
capabilityDataNode.setUniqueId(capabilityData.getUniqueId());
- String minOccurrences = CapabilityData.MIN_OCCURRENCES;
- String occurrences = CapabilityData.MAX_OCCURRENCES;
+ String minOccurrences = CapabilityDataDefinition.MIN_OCCURRENCES;
+ String occurrences = CapabilityDataDefinition.MAX_OCCURRENCES;
if (capabilityData.getMinOccurrences() != null) {
minOccurrences = capabilityData.getMinOccurrences();
}
@@ -1220,7 +1273,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
// "_").toLowerCase();
dataDefinition.setName(logicalName);
if (dataDefinition.getNormalizedName() == null)
- dataDefinition.setNormalizedName(ValidationUtils.normaliseComponentInstanceName(logicalName));
+ dataDefinition.setNormalizedName(ValidationUtils.normalizeComponentInstanceName(logicalName));
dataDefinition.setUniqueId(UniqueIdBuilder.buildResourceInstanceUniuqeId(componentId, ciOriginComponentUid, dataDefinition.getNormalizedName()));
ComponentInstanceData resourceInstanceData = new ComponentInstanceData(dataDefinition);
@@ -1238,7 +1291,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
TitanOperationStatus status = node.right().value();
BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "Remove Component Instance");
BeEcompErrorManager.getInstance().logBeDaoSystemError("Remove Component Instance");
- log.debug("Failed to delete component instance {}. Status is {}", componentInstanceUid, status);
+ log.debug("Failed to delete component instance {}. status is {}", componentInstanceUid, status);
return Either.right(status);
}
@@ -1280,11 +1333,18 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
return Either.right(status);
}
}
+
+ // delete associated properties
+ status = deleteAssociatedGroupInstances(componentInstanceUid);
+ if (status != TitanOperationStatus.OK) {
+ return Either.right(status);
+ }
+
Either<ComponentInstanceData, TitanOperationStatus> deleteRI = titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), componentInstanceUid, ComponentInstanceData.class);
if (deleteRI.isRight()) {
TitanOperationStatus deleteRiStatus = deleteRI.right().value();
- log.error("Failed to delete resource instance {}. Status is {}", componentInstanceUid, deleteRiStatus);
+ log.error("Failed to delete resource instance {}. status is {}", componentInstanceUid, deleteRiStatus);
return Either.right(deleteRiStatus);
}
@@ -1295,6 +1355,11 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
return Either.left(resourceInstance);
}
+ private TitanOperationStatus deleteAssociatedGroupInstances(String componentInstanceUid) {
+
+ return this.groupInstanceOperation.deleteAllGroupInstances(componentInstanceUid);
+ }
+
private TitanOperationStatus deleteAssociatedCapabilityInstances(String resourceInstanceId) {
TitanOperationStatus status = TitanOperationStatus.OK;
@@ -1326,7 +1391,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
if (artifactRes.isRight()) {
TitanOperationStatus status = artifactRes.right().value();
if (status != TitanOperationStatus.NOT_FOUND) {
- log.error("Failed to find artifacts of resource instance {}. Status is {}", resourceInstanceUid, status);
+ log.error("Failed to find artifacts of resource instance {}. status is {}", resourceInstanceUid, status);
return status;
}
} else {
@@ -1334,10 +1399,10 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
List<ImmutablePair<ArtifactData, GraphEdge>> artifactPairs = artifactRes.left().value();
for (ImmutablePair<ArtifactData, GraphEdge> pair : artifactPairs) {
String uniqueId = (String) pair.left.getUniqueId();
- Either<ArtifactData, TitanOperationStatus> removeArifactFromGraph = artifactOperation.removeArtifactOnGraph(resourceInstanceUid, uniqueId, NodeTypeEnum.ResourceInstance, resourceInstanceUid, true);
+ Either<ArtifactData, TitanOperationStatus> removeArifactFromGraph = artifactOperation.removeArtifactOnGraph(resourceInstanceUid, uniqueId, NodeTypeEnum.ResourceInstance, true);
if (removeArifactFromGraph.isRight()) {
TitanOperationStatus status = removeArifactFromGraph.right().value();
- log.error("Failed to delete artifact of resource instance {}. Status is {}", resourceInstanceUid, status);
+ log.error("Failed to delete artifact of resource instance {}. status is {}", resourceInstanceUid, status);
return status;
}
@@ -1404,7 +1469,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
if (relationsForTarget.isRight()) {
TitanOperationStatus status = relationsForTarget.right().value();
if (status != TitanOperationStatus.NOT_FOUND) {
- log.error("Failed to find the relationships of resource instance {}. Status is {}", resourceInstanceUid, status);
+ log.error("Failed to find the relationships of resource instance {}. status is {}", resourceInstanceUid, status);
return status;
}
} else {
@@ -1432,7 +1497,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
if (relationsForSource.isRight()) {
TitanOperationStatus status = relationsForSource.right().value();
if (status != TitanOperationStatus.NOT_FOUND) {
- log.error("Failed to find the relationships of resource instance " + resourceInstanceUid + ". status is " + status);
+ log.error("Failed to find the relationships of resource instance {}. status is {}", resourceInstanceUid, status);
return status;
}
} else {
@@ -1462,7 +1527,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
Either<RelationshipInstData, TitanOperationStatus> deleteNode = titanGenericDao.deleteNode(relationshipTypeImplData, RelationshipInstData.class);
if (deleteNode.isRight()) {
TitanOperationStatus status = deleteNode.right().value();
- log.error("Failed to delete relationship node {}. Status is {}", relationshipTypeImplData, status);
+ log.error("Failed to delete relationship node {}. status is {}", relationshipTypeImplData, status);
return status;
}
}
@@ -1495,7 +1560,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
Either<TitanVertex, TitanOperationStatus> riFrom = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), fromResInstanceUid);
if (riFrom.isRight()) {
- log.debug("Failed to fetch component instance {}. Error: {}", fromResInstanceUid, riFrom.right().value());
+ log.debug("Failed to fetch component instance {}. error {}", fromResInstanceUid, riFrom.right().value());
return Either.right(riFrom.right().value());
}
Iterator<Edge> edgeIter = riFrom.left().value().edges(Direction.OUT, GraphEdgeLabels.RELATIONSHIP_INST.getProperty());
@@ -1504,7 +1569,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
return Either.right(TitanOperationStatus.NOT_FOUND);
}
List<RelationshipInstData> deletedRelations = new ArrayList<>();
- List<String> vertexToDelete = new ArrayList<>();
+ Set<String> vertexToDelete = new HashSet<String>();
while (edgeIter.hasNext()) {
TitanEdge edge = (TitanEdge) edgeIter.next();
String name = (String) edge.property(GraphEdgePropertiesDictionary.NAME.getProperty()).value();
@@ -1531,7 +1596,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
// remove relation vertex
Either<RelationshipInstData, TitanOperationStatus> relationNode = titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.RelationshipInst), relationVertexId, RelationshipInstData.class);
if (relationNode.isRight()) {
- log.debug("Failed to delete relation node with id {}. Error: {}", relationVertexId, relationNode.right().value());
+ log.debug("Failed to delete relation node with id {}. error {}", relationVertexId, relationNode.right().value());
return Either.right(relationNode.right().value());
}
RelationshipInstData deletedRelation = relationNode.left().value();
@@ -1555,7 +1620,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
Either<List<RelationshipInstData>, TitanOperationStatus> dissociateRes = disconnectResourcesInService(componentId, nodeType, requirementDef);
if (dissociateRes.isRight()) {
TitanOperationStatus status = dissociateRes.right().value();
- log.error("Failed to dissociate resource instance " + fromResInstanceUid + " from resource instance " + toResInstanceUid + " in service " + componentId + ". status is " + status);
+ log.error("Failed to dissociate resource instance {} from resource instance {} in service {}. status is {}", fromResInstanceUid, toResInstanceUid, componentId, status);
BeEcompErrorManager.getInstance().logBeDaoSystemError("dissociateComponentInstances");
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
return result;
@@ -1564,13 +1629,23 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
if (!updateCalculatedCapReqResult.equals(StorageOperationStatus.OK)) {
BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "dissociateComponentInstances");
BeEcompErrorManager.getInstance().logBeDaoSystemError("dissociateComponentInstances");
- log.debug("Failed to dissociate component instances {}. Status is {}", requirementDef, updateCalculatedCapReqResult);
+ log.debug("Failed to dissociate component instances. {}. status is {}", requirementDef, updateCalculatedCapReqResult);
result = Either.right(updateCalculatedCapReqResult);
return result;
}
- // RelationshipInstData relationshipInstData =
- // dissociateRes.left().value();
+ StorageOperationStatus status;
+ status = updateCustomizationUUID(requirementDef.getFromNode());
+ if (status != StorageOperationStatus.OK) {
+ result = Either.right(status);
+ return result;
+ }
+ status = updateCustomizationUUID(requirementDef.getToNode());
+ if (status != StorageOperationStatus.OK) {
+ result = Either.right(status);
+ return result;
+ }
+
List<RelationshipInstData> relationshipInstData = dissociateRes.left().value();
RequirementCapabilityRelDef capabilityRelDef = buildCapabilityResult(fromResInstanceUid, toResInstanceUid, requirement, relationshipInstData);
@@ -1612,12 +1687,12 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
private StorageOperationStatus updateRequirementEdges(GraphEdgeLabels requirmentNewLabel, GraphEdgeLabels requirmentCurrentLabel, RequirementAndRelationshipPair pair, String requirementOwnerId) {
Either<TitanVertex, TitanOperationStatus> reqOwnerRI = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), requirementOwnerId);
if (reqOwnerRI.isRight()) {
- log.debug("Failed to fetch requirment Owner by Id {}. Error: {}", requirementOwnerId, reqOwnerRI.right().value());
+ log.debug("Failed to fetch requirment Owner by Id {} error {}", requirementOwnerId, reqOwnerRI.right().value());
return DaoStatusConverter.convertTitanStatusToStorageStatus(reqOwnerRI.right().value());
}
Iterator<Edge> edgeIter = reqOwnerRI.left().value().edges(Direction.OUT, requirmentCurrentLabel.name(), requirmentNewLabel.name());
if (edgeIter == null) {
- log.debug("No edges with label {} for woner RI {}", requirmentCurrentLabel, requirementOwnerId);
+ log.debug("No edges with label {} for owner RI {}", requirmentCurrentLabel, requirementOwnerId);
return StorageOperationStatus.GENERAL_ERROR;
}
boolean associate = requirmentNewLabel.equals(GraphEdgeLabels.CALCULATED_REQUIREMENT_FULLFILLED) ? true : false;
@@ -1635,7 +1710,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
String leftOccurrences = (String) titanGenericDao.getProperty(edge, GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty());
String requiredOccurrencesNew = "0";
- String leftOccurrencesNew = RequirementData.MAX_DEFAULT_OCCURRENCES;
+ String leftOccurrencesNew = RequirementDataDefinition.MAX_DEFAULT_OCCURRENCES;
if (requiredOccurrences != null) {
Integer iOccurrences = Integer.parseInt(requiredOccurrences);
if (associate) {
@@ -1646,7 +1721,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
} else {
String reqMinOccurrences = (String) titanGenericDao.getProperty(reqVertex, GraphPropertiesDictionary.MIN_OCCURRENCES.getProperty());
if (reqMinOccurrences == null) {
- reqMinOccurrences = RequirementData.MIN_OCCURRENCES;
+ reqMinOccurrences = RequirementDataDefinition.MIN_OCCURRENCES;
}
if (Integer.parseInt(reqMinOccurrences) > iOccurrences) {
iOccurrences++;
@@ -1657,7 +1732,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
Map<String, Object> properties = titanGenericDao.getProperties(edge);
properties.put(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty(), requiredOccurrencesNew);
- if (leftOccurrences != null && !leftOccurrences.equals(RequirementData.MAX_OCCURRENCES)) {
+ if (leftOccurrences != null && !leftOccurrences.equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
Integer iOccurrences = Integer.parseInt(leftOccurrences);
if (associate) {
if (iOccurrences > 0) {
@@ -1694,7 +1769,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
private StorageOperationStatus updateCapabiltyEdges(GraphEdgeLabels capabiltyNewLabel, GraphEdgeLabels capabiltyCurrentLabel, RequirementAndRelationshipPair pair, String capabiltyOwnerId) {
Either<TitanVertex, TitanOperationStatus> capOwnerRI = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), capabiltyOwnerId);
if (capOwnerRI.isRight()) {
- log.debug("Failed to fetch requirment Owner by Id {}. Error: {}", capabiltyOwnerId, capOwnerRI.right().value());
+ log.debug("Failed to fetch requirment Owner by Id {}. error {}", capabiltyOwnerId, capOwnerRI.right().value());
return DaoStatusConverter.convertTitanStatusToStorageStatus(capOwnerRI.right().value());
}
Iterator<Edge> edgeIter = capOwnerRI.left().value().edges(Direction.OUT, capabiltyCurrentLabel.name(), capabiltyNewLabel.name());
@@ -1719,7 +1794,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
String leftOccurrences = (String) titanGenericDao.getProperty(edge, GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty());
String requiredOccurrencesNew = "0";
- String leftOccurrencesNew = CapabilityData.MAX_OCCURRENCES;
+ String leftOccurrencesNew = CapabilityDataDefinition.MAX_OCCURRENCES;
if (requiredOccurrences != null) {
Integer iOccurrences = Integer.parseInt(requiredOccurrences);
if (associate) {
@@ -1730,7 +1805,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
} else {
String reqMinOccurrences = (String) titanGenericDao.getProperty(capVertex, GraphPropertiesDictionary.MIN_OCCURRENCES.getProperty());
if (reqMinOccurrences == null) {
- reqMinOccurrences = CapabilityData.MIN_OCCURRENCES;
+ reqMinOccurrences = CapabilityDataDefinition.MIN_OCCURRENCES;
}
if (Integer.parseInt(reqMinOccurrences) > iOccurrences) {
iOccurrences++;
@@ -1741,7 +1816,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
Map<String, Object> properties = titanGenericDao.getProperties(edge);
properties.put(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty(), requiredOccurrencesNew);
- if (leftOccurrences != null && !leftOccurrences.equals(CapabilityData.MAX_OCCURRENCES)) {
+ if (leftOccurrences != null && !leftOccurrences.equals(CapabilityDataDefinition.MAX_OCCURRENCES)) {
Integer iOccurrences = Integer.parseInt(leftOccurrences);
if (associate) {
if (iOccurrences > 0) {
@@ -1806,24 +1881,24 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
relationship = relationPair.getRelationship().getType();
}
- if (log.isDebugEnabled()) {
- log.debug("Going to associate resource instance {} to resource instance {} under component {}. Requirement is {}.", fromResInstanceUid, toResInstanceUid, componentId, requirement);
- }
+ log.debug("Going to associate resource instance {} to resource instance {} under component {}. Requirement is {}.", fromResInstanceUid, toResInstanceUid, componentId, requirement);
Either<ComponentInstanceData, TitanOperationStatus> fromResourceInstDataRes = findMandatoryResourceInstData(fromResInstanceUid);
if (fromResourceInstDataRes.isRight()) {
TitanOperationStatus status = fromResourceInstDataRes.right().value();
- log.error("Failed to find resource instance {}. Status is {}", fromResInstanceUid, status);
+ log.error("Failed to find resource instance {}. status is {}", fromResInstanceUid, status);
return Either.right(status);
}
- ComponentInstanceData fromResourceInstanceData = fromResourceInstDataRes.left().value();
+ ComponentInstanceData fromCI = fromResourceInstDataRes.left().value();
+ ComponentInstanceData fromResourceInstanceData = fromCI;
Either<ComponentInstanceData, TitanOperationStatus> toResourceInstDataRes = findMandatoryResourceInstData(toResInstanceUid);
if (toResourceInstDataRes.isRight()) {
TitanOperationStatus status = toResourceInstDataRes.right().value();
- log.error("Failed to find resource instance " + toResInstanceUid + ". status is " + status);
+ log.error("Failed to find resource instance {}. status is {}", toResInstanceUid, status);
return Either.right(status);
}
- ComponentInstanceData toResourceInstanceData = toResourceInstDataRes.left().value();
+ ComponentInstanceData toCI = toResourceInstDataRes.left().value();
+ ComponentInstanceData toResourceInstanceData = toCI;
// THE component NodeTypeEnum should be sent
TitanOperationStatus isResourceInstOfService = verifyResourceInstanceUnderComponent(nodeType, componentId, fromResInstanceUid);
if (isResourceInstOfService != TitanOperationStatus.OK) {
@@ -1837,24 +1912,24 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
Either<ImmutablePair<RelationshipTypeData, String>, TitanOperationStatus> isValidRes = validateRequirementVsCapability(fromResourceInstanceData, toResourceInstanceData, requirement, relationship, relationPair);
if (isValidRes.isRight()) {
TitanOperationStatus status = isValidRes.right().value();
- log.error("Failed to validate requirement {} between resource instance {} to resource instance {}. Status is {}", requirement, fromResInstanceUid, toResInstanceUid, status);
+ log.error("Failed to validate requirement {} between resource instance {} to resource instance {}. status is {}", requirement, fromResInstanceUid, toResInstanceUid, status);
return Either.right(status);
}
RelationshipTypeData relationshipTypeData = isValidRes.left().value().getKey();
String capabilityName = isValidRes.left().value().getValue();
RelationshipInstData relationshipInstData = buildRelationshipInstData(fromResInstanceUid, requirement, relationshipTypeData, relationPair);
- Either<RelationshipInstData, TitanOperationStatus> createNode = createRelationshipInstData(fromResourceInstDataRes.left().value(), relationshipInstData, relationshipTypeData, requirement);
+ Either<RelationshipInstData, TitanOperationStatus> createNode = createRelationshipInstData(fromCI, relationshipInstData, relationshipTypeData, requirement);
if (createNode.isRight()) {
return Either.right(createNode.right().value());
}
RelationshipInstData createdRelInstData = createNode.left().value();
- Either<GraphRelation, TitanOperationStatus> associateResInst = associateRelationshipInstToTarget(toResourceInstDataRes.left().value(), requirement, capabilityName, createdRelInstData);
+ Either<GraphRelation, TitanOperationStatus> associateResInst = associateRelationshipInstToTarget(toCI, requirement, capabilityName, createdRelInstData);
if (associateResInst.isRight()) {
TitanOperationStatus status = associateResInst.right().value();
- log.error("Failed to associate relationship instance {} to target node {}. Status is {}", createdRelInstData.getUniqueId(), toResInstanceUid, status);
+ log.error("Failed to associate relationship instance {} to target node {}. status is {}", createdRelInstData.getUniqueId(), toResInstanceUid, status);
return Either.right(status);
}
@@ -1868,7 +1943,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
if (parentNode.isRight()) {
TitanOperationStatus status = parentNode.right().value();
- log.error("Failed to find the service associated to the resource instance {}. Status is {}", resInstanceUid, status);
+ log.error("Failed to find the service associated to the resource instance {}. status is {}", resInstanceUid, status);
return status;
}
@@ -1881,7 +1956,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
} else {
BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeIncorrectServiceError, "Resource Instance - verifyResourceInstanceUnderComponent", containerComponentId);
BeEcompErrorManager.getInstance().logBeIncorrectComponentError("Resource Instance - verifyResourceInstanceUnderComponent", containerNodeType.getName(), containerComponentId);
- log.debug("The provided component id {} is not equal to the component ({}) which associated to resource instance {}.", containerComponentId, uniqueId, resInstanceUid);
+ log.debug("The provided component id {} is not equal to the component ({}) which associated to resource instance {}", containerComponentId, uniqueId, resInstanceUid);
return TitanOperationStatus.INVALID_ID;
}
@@ -1919,7 +1994,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
Map<String, Object> props = new HashMap<String, Object>();
props.put(GraphPropertiesDictionary.NAME.getProperty(), capabilityName);
Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(relInstData, toResInstance, GraphEdgeLabels.CAPABILITY_NODE, props);
- log.debug("After creating relation between relationship instance {} to target node {}", relInstData.getUniqueId(), toResInstance.getUniqueId());
+ log.debug("After creatingrelation between relationship instance {} to target node {}", relInstData.getUniqueId(), toResInstance.getUniqueId());
return createRelation;
@@ -1950,7 +2025,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(resInstance, createdRelationshipInst, GraphEdgeLabels.RELATIONSHIP_INST, properties);
if (createRelation.isRight()) {
TitanOperationStatus status = createRelation.right().value();
- log.error("Failed to associate resource instance " + resInstance.getUniqueIdKey() + " to relationship instance " + createdRelationshipInst.getUniqueId() + ". status is " + status);
+ log.error("Failed to associate resource instance {} to relationship instance {}. status is {}", resInstance.getUniqueIdKey(), createdRelationshipInst.getUniqueId(), status);
return Either.right(status);
}
@@ -1984,15 +2059,13 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
}
Either<RequirementDefinition, TitanOperationStatus> requirementDefinitionE = requirementOperation.getRequirement(relationPair.getRequirementUid());
if (requirementDefinitionE.isRight()) {
- log.error("The requirement cannot be found {}" , relationPair.getRequirementUid());
+ log.error("The requirement cannot be found {}", relationPair.getRequirementUid());
return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
}
RequirementDefinition requirementDefinition = requirementDefinitionE.left().value();
String fetchedRequirementRelationship = requirementDefinition.getRelationship();
String fetchedRequirementCapability = requirementDefinition.getCapability();
- // TODO temporary remove of capability sources validation - uncomment
- // after alignment
// String fetchedRequirementNodeName = requirementDefinition.getNode();
TitanOperationStatus status = validateAvailableRequirement(fromResInstance, relationPair);
@@ -2010,8 +2083,6 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
log.error("Failed to fetch the origin resource for capabilty resource instance with id {}, error {}", relationPair.getCapabilityOwnerId(), originCapabilty.right().value());
return Either.right(originCapabilty.right().value());
}
- // TODO temporary remove of capability sources validation - uncomment
- // after alignment
// String originCapabId =
// originCapabilty.left().value().getComponentInstDataDefinition().getComponentUid();
@@ -2027,13 +2098,11 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
CapabilityDefinition capabilityDefinition = capabilityDefinitionE.left().value();
String capabilityName = requirement;
- if (log.isDebugEnabled()) {
- log.debug("The capability {} of resource {} appropriates to requiremt {} on resource {}", capabilityDefinition, toResourceUid, requirement, fromResourceUid);
- }
+ log.debug("The capability {} of resource {} appropriates to requirement {} on resource {}", capabilityDefinition, toResourceUid, requirement, fromResourceUid);
String capabilityType = capabilityDefinition.getType();
if (false == fetchedRequirementCapability.equals(capabilityType)) {
- log.error("The capability type in the requirement ({}) does not equal to the capability on the resource {}({})", fetchedRequirementCapability, toResourceUid, capabilityType);
+ log.error("The capability type in the requirement ({}) does not equal to the capability on the resource {} ({})", fetchedRequirementCapability, toResourceUid, capabilityType);
return Either.right(TitanOperationStatus.MATCH_NOT_FOUND);
}
@@ -2054,7 +2123,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
private TitanOperationStatus validateAvailableRequirement(ComponentInstanceData fromResInstance, RequirementAndRelationshipPair relationPair) {
Either<TitanVertex, TitanOperationStatus> fromRi = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), fromResInstance.getUniqueId());
if (fromRi.isRight()) {
- log.debug("Failed to fetch component instance {}. Error: {}", fromResInstance.getUniqueId(), fromRi.right().value());
+ log.debug("Failed to fetch component instance {} error {}", fromResInstance.getUniqueId(), fromRi.right().value());
return fromRi.right().value();
}
Iterator<Edge> edgeIter = fromRi.left().value().edges(Direction.OUT, GraphEdgeLabels.CALCULATED_REQUIREMENT.name());
@@ -2071,7 +2140,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
String ownerIdOnEdge = (String) edge.value(GraphEdgePropertiesDictionary.OWNER_ID.getProperty());
if (ownerIdOnEdge.equals(relationPair.getRequirementOwnerId())) {
String leftOccurrences = (String) titanGenericDao.getProperty(edge, GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty());
- if (leftOccurrences != null && !leftOccurrences.equals(RequirementData.MAX_OCCURRENCES)) {
+ if (leftOccurrences != null && !leftOccurrences.equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
Integer leftIntValue = Integer.parseInt(leftOccurrences);
if (leftIntValue > 0) {
exist = true;
@@ -2106,7 +2175,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
String ownerIdOnEdge = (String) edge.value(GraphEdgePropertiesDictionary.OWNER_ID.getProperty());
if (ownerIdOnEdge.equals(relationPair.getCapabilityOwnerId())) {
String leftOccurrences = (String) titanGenericDao.getProperty(edge, GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty());
- if (leftOccurrences != null && !leftOccurrences.equals(CapabilityData.MAX_OCCURRENCES)) {
+ if (leftOccurrences != null && !leftOccurrences.equals(CapabilityDataDefinition.MAX_OCCURRENCES)) {
Integer leftIntValue = Integer.parseInt(leftOccurrences);
if (leftIntValue > 0) {
exist = true;
@@ -2150,7 +2219,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
List<ResourceMetadataData> resourcesPathList = new ArrayList<ResourceMetadataData>();
TitanOperationStatus status = resourceOperation.findResourcesPathRecursively(resourceUid, resourcesPathList);
if (status != TitanOperationStatus.OK) {
- log.error("Failed to find the parent list of resource {}. Status is {}", resourceUid, status);
+ log.error("Failed to find the parent list of resource {}. status is {}", resourceUid, status);
return status;
}
@@ -2213,7 +2282,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
if (updateRes.isRight()) {
TitanOperationStatus status = updateRes.right().value();
- log.error("Failed to update resource instance {}. Status is {}", resourceInstanceUid, status);
+ log.error("Failed to update resource instance {}. status is {}", resourceInstanceUid, status);
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
return result;
}
@@ -2256,13 +2325,24 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
instance.setPropertyValueCounter(resourceInstance.getPropertyValueCounter());
instance.setAttributeValueCounter(resourceInstance.getAttributeValueCounter());
instance.setInputValueCounter(resourceInstance.getInputValueCounter());
+
+ boolean isNeedGenerate = isNeedGenerateCustomizationUUID(resourceInstance, currentInst);
+ if (isNeedGenerate) {
+ generateCustomizationUUID(instance);
+ } else {
+ instance.setCustomizationUUID(resourceInstance.getCustomizationUUID());
+ }
return instance;
}
+ private boolean isNeedGenerateCustomizationUUID(ComponentInstance resourceInstance, ComponentInstanceData currentInst) {
+ return !currentInst.getComponentInstDataDefinition().getName().equals(resourceInstance.getName());
+ }
+
private void printDiff(ComponentInstanceData currentInst, ComponentInstance resourceInstance) {
log.debug("The current Resource Instance details are : {}", currentInst);
- log.debug("The received Resource Instance details for update are : {}", resourceInstance);
+ log.debug("The received Resource Instance details for update are :{}", resourceInstance);
}
@@ -2274,11 +2354,11 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
public Either<ComponentInstance, TitanOperationStatus> updateResourceInstanceInService(String serviceId, String resourceInstanceUid, ComponentInstance resourceInstance) {
- log.debug("Going to update resource instance {}. Properties are {}", resourceInstanceUid, resourceInstance);
+ log.trace("Going to update resource instance {}. Properies are {}", resourceInstanceUid, resourceInstance);
Either<ComponentInstanceData, TitanOperationStatus> findInstRes = findResourceInstance(resourceInstanceUid);
if (findInstRes.isRight()) {
TitanOperationStatus status = findInstRes.right().value();
- log.error("Failed to find resource instance {}. Status is {}", resourceInstanceUid, status);
+ log.error("Failed to find resource instance {}. status is {}", resourceInstanceUid, status);
return Either.right(status);
}
@@ -2294,7 +2374,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
Either<ComponentInstanceData, TitanOperationStatus> updateNodeRes = titanGenericDao.updateNode(resourceInstanceData, ComponentInstanceData.class);
if (updateNodeRes.isRight()) {
TitanOperationStatus status = updateNodeRes.right().value();
- log.error("Failed to update resource instance {}. Status is {}", resourceInstanceUid, status);
+ log.error("Failed to update resource instance {}. status is {}", resourceInstanceUid, status);
return Either.right(status);
}
@@ -2319,7 +2399,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
if (resInstancesOfService.isRight()) {
TitanOperationStatus status = resInstancesOfService.right().value();
if (status != TitanOperationStatus.NOT_FOUND) {
- log.error("Failed to find resource instances of service {}. Status is {}", componentId, status);
+ log.error("Failed to find resource instances of service {}. status is {}", componentId, status);
}
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
return result;
@@ -2348,7 +2428,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
if (updateRes.isRight()) {
TitanOperationStatus status = updateRes.right().value();
- log.error("Failed to find component instance name {}. Status is {}", componentInstName, status);
+ log.error("Failed to find component instance name {}. status is {}", componentInstName, status);
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
return result;
}
@@ -2422,7 +2502,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
Either<ComponentMetadataData, TitanOperationStatus> componentRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(containerNodeType), componentId, ComponentMetadataData.class);
if (componentRes.isRight()) {
TitanOperationStatus status = componentRes.right().value();
- log.error("Failed to find component {}. Status is {}", componentId, status);
+ log.error("Failed to find component {}. status is {}", componentId, status);
return Either.right(status);
}
@@ -2440,7 +2520,8 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
if (resourceInstances != null && false == resourceInstances.isEmpty()) {
Map<String, Map<String, CapabilityDefinition>> compInstCapabilities = new HashMap<String, Map<String, CapabilityDefinition>>();
Map<String, Map<String, RequirementDefinition>> compInstReq = new HashMap<String, Map<String, RequirementDefinition>>();
- Map<String, Map<String, ArtifactDefinition>> compInstArtifacts = new HashMap<String, Map<String, ArtifactDefinition>>();
+ Map<String, Map<String, ArtifactDefinition>> compInstDeploymentArtifacts = new HashMap<String, Map<String, ArtifactDefinition>>();
+ Map<String, Map<String, ArtifactDefinition>> compInstInformationalArtifacts = new HashMap<String, Map<String, ArtifactDefinition>>();
Map<String, Component> compInstOriginsMap = new HashMap<String, Component>();
for (ImmutablePair<ComponentInstanceData, GraphEdge> immutablePair : resourceInstances) {
@@ -2451,7 +2532,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
ComponentInstance resourceInstance = new ComponentInstance(resourceInstanceData.getComponentInstDataDefinition());
- TitanOperationStatus status = getFullComponentInstance(compInstCapabilities, compInstReq, compInstArtifacts, compInstOriginsMap, resourceInstance, compInstNodeType);
+ TitanOperationStatus status = getFullComponentInstance(compInstCapabilities, compInstReq, compInstDeploymentArtifacts, compInstOriginsMap, resourceInstance, compInstNodeType, compInstInformationalArtifacts);
if (status != TitanOperationStatus.OK) {
return Either.right(status);
}
@@ -2507,11 +2588,11 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
if (relationshipsRes.isRight()) {
status = relationshipsRes.right().value();
- log.debug("After fetching all reslationships of resource instance {}. Status is {}", resourceInstanceUid, status);
+ log.debug("After fetching all reslationships of resource instance {}. status is {}", resourceInstanceUid, status);
if (status == TitanOperationStatus.NOT_FOUND) {
return Either.left(requirementsResult);
} else {
- log.error("Failed to find relationhips of resource instance {}. Status is {}", resourceInstanceUid, status);
+ log.error("Failed to find relationhips of resource instance {}. status is {}", resourceInstanceUid, status);
return Either.right(status);
}
}
@@ -2545,11 +2626,11 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
if (relationshipsRes.isRight()) {
status = relationshipsRes.right().value();
- log.debug("After fetching all reslationships of resource instance {}. Status is {}", resourceInstanceUid, status);
+ log.debug("After fetching all reslationships of resource instance {}. status is {}", resourceInstanceUid, status);
if (status == TitanOperationStatus.NOT_FOUND) {
return Either.left(requirementsResult);
} else {
- log.error("Failed to find relationhips of resource instance {}. Status is {}", resourceInstanceUid, status);
+ log.error("Failed to find relationhips of resource instance {}. status is {}", resourceInstanceUid, status);
return Either.right(status);
}
}
@@ -2576,10 +2657,11 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
public Either<ComponentInstance, StorageOperationStatus> getFullComponentInstance(ComponentInstance componentInstance, NodeTypeEnum compInstNodeType) {
Map<String, Map<String, CapabilityDefinition>> compInstCapabilities = new HashMap<String, Map<String, CapabilityDefinition>>();
Map<String, Map<String, RequirementDefinition>> compInstReq = new HashMap<String, Map<String, RequirementDefinition>>();
- Map<String, Map<String, ArtifactDefinition>> compInstArtifacts = new HashMap<String, Map<String, ArtifactDefinition>>();
+ Map<String, Map<String, ArtifactDefinition>> compInstDeploymentArtifacts = new HashMap<String, Map<String, ArtifactDefinition>>();
+ Map<String, Map<String, ArtifactDefinition>> compInstInformationalArtifacts = new HashMap<String, Map<String, ArtifactDefinition>>();
Map<String, Component> compInstOrigins = new HashMap<String, Component>();
- TitanOperationStatus fullResourceInstance = getFullComponentInstance(compInstCapabilities, compInstReq, compInstArtifacts, compInstOrigins, componentInstance, compInstNodeType);
+ TitanOperationStatus fullResourceInstance = getFullComponentInstance(compInstCapabilities, compInstReq, compInstDeploymentArtifacts, compInstOrigins, componentInstance, compInstNodeType, compInstInformationalArtifacts);
if (!fullResourceInstance.equals(TitanOperationStatus.OK)) {
log.debug("failed to get full data of resource instance. error: {}", fullResourceInstance);
return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(fullResourceInstance));
@@ -2588,7 +2670,8 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
}
private TitanOperationStatus getFullComponentInstance(Map<String, Map<String, CapabilityDefinition>> compInstCapabilities, Map<String, Map<String, RequirementDefinition>> compInstReq,
- Map<String, Map<String, ArtifactDefinition>> compInstArtifacts, Map<String, Component> compInstOrigins, ComponentInstance compInst, NodeTypeEnum compInstNodeType) {
+ Map<String, Map<String, ArtifactDefinition>> compInstDeploymentArtifacts, Map<String, Component> compInstOrigins, ComponentInstance compInst, NodeTypeEnum compInstNodeType,
+ Map<String, Map<String, ArtifactDefinition>> compInstInformationalArtifacts) {
Component component = null;
ComponentOperation componentOperation = getComponentOperation(compInstNodeType);
String componentUid = compInst.getComponentUid();
@@ -2649,20 +2732,110 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
}
- capStatus = setCompInstDeploymentArtifactsFromGraph(compInstArtifacts, componentUid, compInst);
+ capStatus = setCompInstDeploymentArtifactsFromGraph(compInstDeploymentArtifacts, componentUid, compInst);
+ if (capStatus != StorageOperationStatus.OK) {
+ log.debug("Failed to find resource deployment artifacts of resource {}. status is {}", componentName, capStatus);
+
+ }
+
+ capStatus = setCompInstInformationalArtifactsResourceFromGraph(compInstInformationalArtifacts, componentUid, compInst);
if (capStatus != StorageOperationStatus.OK) {
log.debug("Failed to find resource deployment artifacts of resource {}. status is {}", componentName, capStatus);
}
- capStatus = setCompInstArtifactsFromGraph(compInst);
+ capStatus = setCompInstDeploymentArtifactsFromGraph(compInst);
if (capStatus != StorageOperationStatus.OK) {
log.debug("Failed to find resource deployment artifacts of resource instance {} . status is {}", compInst.getName(), capStatus);
}
+
+ capStatus = setCompInstInformationaltArtifactsFromGraph(compInst);
+ if (capStatus != StorageOperationStatus.OK) {
+ log.debug("Failed to find resource informational artifacts of resource instance {} . status is {}", compInst.getName(), capStatus);
+ }
+
+ capStatus = setGroupInstFromGraph(compInst);
+ if (capStatus != StorageOperationStatus.OK) {
+ log.debug("Failed to find resource groups of resource instance {} . status is {}", compInst.getName(), capStatus);
+ }
return TitanOperationStatus.OK;
}
- protected StorageOperationStatus setCompInstArtifactsFromGraph(ComponentInstance resourceInstance) {
+ private StorageOperationStatus setCompInstInformationaltArtifactsFromGraph(ComponentInstance resourceInstance) {
+ Map<String, ArtifactDefinition> informationalArtifacts = null;
+ if (resourceInstance.getArtifacts() == null) {
+ informationalArtifacts = new HashMap<String, ArtifactDefinition>();
+ } else {
+ informationalArtifacts = new HashMap<String, ArtifactDefinition>(resourceInstance.getArtifacts());
+ }
+
+ Either<Map<String, ArtifactDefinition>, StorageOperationStatus> result = artifactOperation.getArtifacts(resourceInstance.getUniqueId(), NodeTypeEnum.ResourceInstance, true, ArtifactGroupTypeEnum.INFORMATIONAL.getType());
+ if (result.isRight()) {
+ StorageOperationStatus status = result.right().value();
+ if (status != StorageOperationStatus.NOT_FOUND) {
+ return status;
+ }
+ } else {
+ informationalArtifacts.putAll(result.left().value());
+ }
+
+ resourceInstance.setArtifacts(informationalArtifacts);
+ return StorageOperationStatus.OK;
+ }
+
+ private StorageOperationStatus setGroupInstFromGraph(ComponentInstance compInst) {
+ List<GroupInstance> groupInstances = null;
+
+ Either<List<GroupInstance>, StorageOperationStatus> result = groupInstanceOperation.getAllGroupInstances(compInst.getUniqueId(), NodeTypeEnum.ResourceInstance);
+ if (result.isRight()) {
+ StorageOperationStatus status = result.right().value();
+ if (status != StorageOperationStatus.NOT_FOUND) {
+ return status;
+ } else {
+
+ return StorageOperationStatus.OK;
+ }
+ }
+
+ groupInstances = result.left().value();
+ compInst.setGroupInstances(groupInstances);
+
+ return StorageOperationStatus.OK;
+ }
+
+ private StorageOperationStatus setCompInstInformationalArtifactsResourceFromGraph(Map<String, Map<String, ArtifactDefinition>> resourcesInformationalArtifacts, String componentUid, ComponentInstance resourceInstance) {
+
+ if (resourcesInformationalArtifacts.containsKey(componentUid)) {
+ resourceInstance.setArtifacts(resourcesInformationalArtifacts.get(componentUid));
+ return StorageOperationStatus.OK;
+ }
+
+ Either<Map<String, ArtifactDefinition>, StorageOperationStatus> result = artifactOperation.getArtifacts(componentUid, NodeTypeEnum.Resource, true, ArtifactGroupTypeEnum.INFORMATIONAL.getType());
+ if (result.isRight()) {
+ StorageOperationStatus status = result.right().value();
+ if (status != StorageOperationStatus.NOT_FOUND) {
+ return status;
+ } else {
+ return StorageOperationStatus.OK;
+ }
+ }
+ Map<String, ArtifactDefinition> artifacts = result.left().value();
+ if (!artifacts.isEmpty()) {
+ Map<String, ArtifactDefinition> tempArtifacts = new HashMap<>(artifacts);
+ for (Entry<String, ArtifactDefinition> artifact : artifacts.entrySet()) {
+ if (!artifact.getValue().checkEsIdExist()) {
+ tempArtifacts.remove(artifact.getKey());
+ }
+ }
+ resourceInstance.setArtifacts(tempArtifacts);
+ resourcesInformationalArtifacts.put(componentUid, tempArtifacts);
+ }
+
+ return StorageOperationStatus.OK;
+
+ }
+
+ protected StorageOperationStatus setCompInstDeploymentArtifactsFromGraph(ComponentInstance resourceInstance) {
Map<String, ArtifactDefinition> deploymentArtifacts = null;
if (resourceInstance.getDeploymentArtifacts() == null) {
@@ -2691,7 +2864,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
log.debug("failed to get heat parameters values for heat artifact {}", artifact.getUniqueId());
return heatParamsForEnv.right().value();
} else {
- artifact.setHeatParameters(heatParamsForEnv.left().value());
+ artifact.setListHeatParameters(heatParamsForEnv.left().value());
}
}
}
@@ -2706,17 +2879,6 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
}
- // resourceInstance) {
- // ArrayList<HeatParameterDefinition>();
- // heatEnvArtifact.getGeneratedFromId());
- // Either<List<ImmutablePair<HeatParameterValueData, GraphEdge>>,
- // TitanOperationStatus> heatEnvValuesWithEdges = titanGenericDao
- // !heatEnvValuesWithEdges.right().value().equals(TitanOperationStatus.NOT_FOUND))
- // {
- // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- // heatEnvValuesWithEdges.left().value()){
- // pair.right.getProperties().get(GraphEdgePropertiesDictionary.NAME.getProperty());
- // heatValuesMap.get(parameter.getName());
private Either<List<ImmutablePair<ComponentInstanceData, GraphEdge>>, TitanOperationStatus> getAllComponentInstanceFromGraph(String componentId, NodeTypeEnum containerNodeType, boolean withEdges) {
if (log.isDebugEnabled())
log.debug("Going to fetch all resource instances nodes in graph associate to component {}", componentId);
@@ -2757,7 +2919,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
if (targetNodeRes.isRight()) {
TitanOperationStatus status = targetNodeRes.right().value();
- log.error("Failed to find the target node of relationship inst {}. Status is {}", relationshipInstData, status);
+ log.error("Failed to find the target node of relationship inst {}. status is {}", relationshipInstData, status);
return status;
}
@@ -2782,7 +2944,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
if (sourceNodeRes.isRight()) {
TitanOperationStatus status = sourceNodeRes.right().value();
- log.error("Failed to find the source node of relationship inst {}. Status is {}", relationshipInstData, status);
+ log.error("Failed to find the source node of relationship inst {}. status is {}", relationshipInstData, status);
return status;
}
@@ -2816,7 +2978,6 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
requirementCapabilityRelDef.setToNode(targetResourceUid);
String sourceUid = sourceToRel.getKey();
requirementCapabilityRelDef.setFromNode(sourceUid);
-
List<RequirementAndRelationshipPair> relationships = new ArrayList<RequirementAndRelationshipPair>();
populateRelationships(sourceToRel, relationships);
@@ -2860,6 +3021,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
pair.setCapabilityUid(relationshipInstData.getCapabiltyId());
pair.setRequirementOwnerId(relationshipInstData.getRequirementOwnerId());
pair.setRequirementUid(relationshipInstData.getRequirementId());
+ pair.setId(relationshipInstData.getUniqueId());
relationships.add(pair);
}
}
@@ -2874,16 +3036,16 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
}
@Override
- public Either<RequirementCapabilityRelDef, StorageOperationStatus> associateResourceInstances(String componentId, NodeTypeEnum nodeType, RequirementCapabilityRelDef relation, boolean inTransaction) {
+ public Either<RequirementCapabilityRelDef, StorageOperationStatus> associateResourceInstances(String componentId, NodeTypeEnum nodeType, RequirementCapabilityRelDef relation, boolean inTransaction, boolean isClone) {
Either<RequirementCapabilityRelDef, StorageOperationStatus> result = null;
try {
- Either<RequirementCapabilityRelDef, TitanOperationStatus> multiRequirements = associateResourceInstancesMultiRequirements(componentId, nodeType, relation);
+ Either<RequirementCapabilityRelDef, TitanOperationStatus> multiRequirements = associateResourceInstancesMultiRequirements(componentId, nodeType, relation, isClone);
if (multiRequirements.isRight()) {
TitanOperationStatus status = multiRequirements.right().value();
BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "associateComponentInstances");
BeEcompErrorManager.getInstance().logBeDaoSystemError("associateComponentInstances");
- log.debug("Failed to associate component instances. {}. Status is {}", relation, status);
+ log.debug("Failed to associate component instances {}. status is {}", relation, status);
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
return result;
}
@@ -2891,7 +3053,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
if (!updateCalculatedCapReqResult.equals(StorageOperationStatus.OK)) {
BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "associateComponentInstances");
BeEcompErrorManager.getInstance().logBeDaoSystemError("associateComponentInstances");
- log.debug("Failed to associate component instances. {}. Status is {}", relation, updateCalculatedCapReqResult);
+ log.debug("Failed to associate component instances. {}. status is {}", relation, updateCalculatedCapReqResult);
result = Either.right(updateCalculatedCapReqResult);
return result;
}
@@ -2906,7 +3068,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
}
}
- private Either<RequirementCapabilityRelDef, TitanOperationStatus> associateResourceInstancesMultiRequirements(String componentId, NodeTypeEnum nodeType, RequirementCapabilityRelDef relation) {
+ private Either<RequirementCapabilityRelDef, TitanOperationStatus> associateResourceInstancesMultiRequirements(String componentId, NodeTypeEnum nodeType, RequirementCapabilityRelDef relation, boolean isClone) {
String fromNode = relation.getFromNode();
String toNode = relation.getToNode();
@@ -2928,7 +3090,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
TitanOperationStatus status = associateRes.right().value();
BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedAddingResourceInstanceError, "AssociateResourceInstances", fromNode, componentId);
BeEcompErrorManager.getInstance().logBeFailedAddingResourceInstanceError("AssociateResourceInstances - missing relationship", fromNode, componentId);
- log.debug("Failed to associate resource instance {} to resource instnace {}. Status is {}", fromNode, toNode, status);
+ log.debug("Failed to associate resource instance {} to resource instance {}. status is {}", fromNode, toNode, status);
return Either.right(status);
}
@@ -2942,6 +3104,18 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
requirementAndRelationshipPair.setCapabilityUid(immutablePair.getCapabilityUid());
requirementAndRelationshipPair.setRequirementUid(immutablePair.getRequirementUid());
relationshipsResult.add(requirementAndRelationshipPair);
+ if (!isClone) {
+ log.trace("update customization UUID for from CI {} and to CI {}", relation.getFromNode(), relation.getToNode());
+ StorageOperationStatus status;
+ status = updateCustomizationUUID(relation.getFromNode());
+ if (status != StorageOperationStatus.OK) {
+ return Either.right(TitanOperationStatus.GENERAL_ERROR);
+ }
+ status = updateCustomizationUUID(relation.getToNode());
+ if (status != StorageOperationStatus.OK) {
+ return Either.right(TitanOperationStatus.GENERAL_ERROR);
+ }
+ }
}
@@ -2955,7 +3129,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
@Override
public Either<RequirementCapabilityRelDef, StorageOperationStatus> associateResourceInstances(String componentId, NodeTypeEnum nodeType, RequirementCapabilityRelDef relation) {
- return associateResourceInstances(componentId, nodeType, relation, false);
+ return associateResourceInstances(componentId, nodeType, relation, false, false);
}
@Override
@@ -2970,7 +3144,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "deleteAllResourceInstances - missing relationship");
BeEcompErrorManager.getInstance().logBeSystemError("deleteAllResourceInstances - missing relationship");
}
- log.debug("Failed to delete resource instances of service {}. Status is {}", containerComponentId, status);
+ log.debug("Failed to delete resource instances of service {}. status is {}", containerComponentId, status);
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
return result;
@@ -3002,7 +3176,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
if (resourceInstancesRes.isRight()) {
TitanOperationStatus status = resourceInstancesRes.right().value();
- log.debug("After fetching all resource instances of service {}. Status is {}", componentId, status);
+ log.debug("After fetching all resource instances of service {}. status is {}", componentId, status);
return Either.right(status);
}
@@ -3015,14 +3189,14 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
log.debug("After removing resource instance {}. Result is {}", resourceInstUid, removeResourceInstanceRes);
if (removeResourceInstanceRes.isRight()) {
TitanOperationStatus status = removeResourceInstanceRes.right().value();
- log.error("After removing resource instance {}. Status is {}", resourceInstUid, status);
+ log.error("After removing resource instance {}. status is {}", resourceInstUid, status);
return Either.right(status);
}
ComponentInstance resourceInstance = removeResourceInstanceRes.left().value();
result.add(resourceInstance);
}
- log.debug("The following resource instances was deleted from service {}:{}", componentId, result);
+ log.debug("The following resource instances was deleted from service {} : {}", componentId, result);
return Either.left(result);
}
@@ -3112,7 +3286,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
pair.setCapabilityOwnerId(capOwnerId);
}
- Either<RequirementCapabilityRelDef, StorageOperationStatus> associateInstances = associateResourceInstances(component.getUniqueId(), containerNodeType, relation, true);
+ Either<RequirementCapabilityRelDef, StorageOperationStatus> associateInstances = associateResourceInstances(component.getUniqueId(), containerNodeType, relation, true, true);
if (associateInstances.isRight()) {
StorageOperationStatus status = associateInstances.right().value();
log.error("failed to assosiate resource instance {} and resource instance {}. status ={}", relation.getFromNode(), relation.getToNode(), status);
@@ -3131,33 +3305,6 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
ImmutablePair<List<ComponentInstance>, Map<String, String>> result = new ImmutablePair<List<ComponentInstance>, Map<String, String>>(list, oldCompInstToNew);
- // Either<ImmutablePair<List<ComponentInstance>,
- // List<RequirementCapabilityRelDef>>, StorageOperationStatus>
- // allResourceInstances = getAllComponentInstances(componentIdFrom,
- // containerNodeType, compInstNodeType, true);
- //
- //
- // if (allResourceInstances.isRight()) {
- // StorageOperationStatus status = allResourceInstances.right().value();
- // if (status.equals(StorageOperationStatus.NOT_FOUND)) {
- //
- // return Either.left(result);
- // } else {
- // log.error("failed to get all resource instances for service {}.
- // status={}", componentIdFrom, status);
- // return Either.right(status);
- // }
- // }
-
- // ImmutablePair<List<ComponentInstance>,
- // List<RequirementCapabilityRelDef>> instanceRelationPair =
- // allResourceInstances.left().value();
-
- // ImmutablePair<List<ComponentInstance>,
- // List<RequirementCapabilityRelDef>> instanceRelationPair = new
- // ImmutablePair<List<ComponentInstance>,
- // List<RequirementCapabilityRelDef>>(prevResource.getComponentInstances(),
- // prevResource.getComponentInstancesRelations());
List<ComponentInstance> riList = prevResource.getComponentInstances();
Map<String, ComponentInstance> riMapper = new HashMap<>();
int instanceNumber = 0;
@@ -3238,7 +3385,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
pair.setCapabilityOwnerId(capOwnerId);
}
- Either<RequirementCapabilityRelDef, StorageOperationStatus> associateInstances = associateResourceInstances(componentIdTo, containerNodeType, relation, true);
+ Either<RequirementCapabilityRelDef, StorageOperationStatus> associateInstances = associateResourceInstances(componentIdTo, containerNodeType, relation, true, true);
if (associateInstances.isRight()) {
StorageOperationStatus status = associateInstances.right().value();
log.error("failed to assosiate resource instance {} and resource instance {}. status ={}", relation.getFromNode(), relation.getToNode(), status);
@@ -3251,7 +3398,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
private boolean isAtomicComponentInstance(ComponentInstance componentInstance) {
OriginTypeEnum originType = componentInstance.getOriginType();
- if (originType.equals(OriginTypeEnum.VFC) || originType.equals(OriginTypeEnum.VL) || originType.equals(OriginTypeEnum.CP)) {
+ if (originType == OriginTypeEnum.VFC || originType == OriginTypeEnum.VFCMT || originType == OriginTypeEnum.VL || originType == OriginTypeEnum.CP) {
return true;
}
return false;
@@ -3269,9 +3416,14 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
}
Map<String, ArtifactDefinition> artifacts = getArtifactsOfRI.left().value();
+ List<GroupInstance> groupInstancesFrom = fromResourceInstance.getGroupInstances();
+ List<GroupInstance> groupInstancesTo = toResourceInstance.getGroupInstances();
+ Map<String, List<String>> groupsInstanceArtifact = new HashMap<String, List<String>>();
for (Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
ArtifactDefinition artifactDefinition = entry.getValue();
+ String generatedFromIdArtifactUid = artifactDefinition.getGeneratedFromId();
+
// US687135 Do not Add VF_MODULES_METADATA when checking out
if (ArtifactTypeEnum.VF_MODULES_METADATA.getType().equals(artifactDefinition.getArtifactType())) {
// The artifact of type VF_MODULES_METADATA should not be cloned
@@ -3287,7 +3439,37 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
if (addArifactToResource.isRight()) {
return addArifactToResource.right().value();
}
+
+ if (groupInstancesTo != null) {
+ for (GroupInstance groupInstanceTo : groupInstancesTo) {
+ Optional<String> op = groupInstanceTo.getArtifacts().stream().filter(p -> p.equals(generatedFromIdArtifactUid)).findAny();
+ if (op.isPresent()) {
+
+ List<String> artifactsUid = null;
+ if (groupsInstanceArtifact.containsKey(groupInstanceTo.getUniqueId())) {
+ artifactsUid = groupsInstanceArtifact.get(groupInstanceTo.getUniqueId());
+ } else {
+ artifactsUid = new ArrayList<String>();
+ }
+ artifactsUid.add(addArifactToResource.left().value().getUniqueId());
+ groupsInstanceArtifact.put(groupInstanceTo.getUniqueId(), artifactsUid);
+ break;
+ }
+ }
+
+ }
+ }
+ if (groupsInstanceArtifact != null && !groupsInstanceArtifact.isEmpty()) {
+ for (Map.Entry<String, List<String>> groupArtifact : groupsInstanceArtifact.entrySet()) {
+ groupInstanceOperation.associateArtifactsToGroupInstance(groupArtifact.getKey(), groupArtifact.getValue());
+ }
}
+ Either<List<GroupInstance>, StorageOperationStatus> groupInstanceStatus = groupInstanceOperation.getAllGroupInstances(toResourceInstance.getUniqueId(), NodeTypeEnum.ResourceInstance);
+ if (groupInstanceStatus.isRight()) {
+ log.debug("failed to get groupinstance for component inatance {}", toResourceInstance.getUniqueId());
+ return groupInstanceStatus.right().value();
+ }
+ toResourceInstance.setGroupInstances(groupInstanceStatus.left().value());
toResourceInstance.setDeploymentArtifacts(artifacts);
return StorageOperationStatus.OK;
}
@@ -3406,11 +3588,11 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
Either<List<String>, TitanOperationStatus> resInstancesOfService = getComponentInstancesNameOfService(serviceId, nodeType);
- log.debug("After fetching resource instances of service {}. Result is {}", serviceId, resInstancesOfService);
+ log.debug("After fetching resource instances of service {}. result is {}", serviceId, resInstancesOfService);
if (resInstancesOfService.isRight()) {
TitanOperationStatus status = resInstancesOfService.right().value();
if (status != TitanOperationStatus.NOT_FOUND) {
- log.error("Failed to find resource instances of service {}. Status is {}", serviceId, status);
+ log.error("Failed to find resource instances of service {}. status is {}", serviceId, status);
}
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
return result;
@@ -3438,7 +3620,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
Either<List<ImmutablePair<ComponentInstanceData, GraphEdge>>, TitanOperationStatus> resourceInstancesRes = getAllComponentInstanceFromGraph(serviceId, nodeType, false);
if (resourceInstancesRes.isRight()) {
TitanOperationStatus status = resourceInstancesRes.right().value();
- log.debug("Resource instance was found under service {}. Status is {}", serviceId, status);
+ log.debug("Resource instance was found under service {}. status is {}", serviceId, status);
return Either.right(status);
}
@@ -3570,15 +3752,15 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
return status;
}
+ @Override
public Either<List<ImmutablePair<CapabilityData, GraphEdge>>, TitanOperationStatus> getCapabilities(ComponentInstance compInstance, NodeTypeEnum nodeTypeEnum) {
-
DataNodeCollector<CapabilityData> collector = () -> titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(nodeTypeEnum), compInstance.getUniqueId(), GraphEdgeLabels.CALCULATED_CAPABILITY, NodeTypeEnum.Capability,
CapabilityData.class);
return getDataFromGraph(collector);
-
}
+ @Override
public Either<List<ImmutablePair<RequirementData, GraphEdge>>, TitanOperationStatus> getRequirements(ComponentInstance compInstance, NodeTypeEnum nodeTypeEnum) {
DataNodeCollector<RequirementData> collector = () -> titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(nodeTypeEnum), compInstance.getUniqueId(), GraphEdgeLabels.CALCULATED_REQUIREMENT, NodeTypeEnum.Requirement,
@@ -3588,6 +3770,24 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
}
+ @Override
+ public Either<List<ImmutablePair<CapabilityData, GraphEdge>>, TitanOperationStatus> getFulfilledCapabilities(ComponentInstance compInstance, NodeTypeEnum nodeTypeEnum) {
+ DataNodeCollector<CapabilityData> collector = () -> titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(nodeTypeEnum), compInstance.getUniqueId(), GraphEdgeLabels.CALCULATED_CAPABILITY_FULLFILLED, NodeTypeEnum.Capability,
+ CapabilityData.class);
+
+ return getDataFromGraph(collector);
+ }
+
+ @Override
+ public Either<List<ImmutablePair<RequirementData, GraphEdge>>, TitanOperationStatus> getFulfilledRequirements(ComponentInstance compInstance, NodeTypeEnum nodeTypeEnum) {
+
+ DataNodeCollector<RequirementData> collector = () -> titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(nodeTypeEnum), compInstance.getUniqueId(), GraphEdgeLabels.CALCULATED_REQUIREMENT_FULLFILLED, NodeTypeEnum.Requirement,
+ RequirementData.class);
+
+ return getDataFromGraph(collector);
+
+ }
+
public Either<Boolean, StorageOperationStatus> isAvailableRequirement(ComponentInstance fromResInstance, RequirementAndRelationshipPair relationPair) {
Either<TitanVertex, TitanOperationStatus> fromRi = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), fromResInstance.getUniqueId());
if (fromRi.isRight()) {
@@ -3608,7 +3808,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
String ownerIdOnEdge = (String) edge.value(GraphEdgePropertiesDictionary.OWNER_ID.getProperty());
if (ownerIdOnEdge.equals(relationPair.getRequirementOwnerId())) {
String leftOccurrences = (String) edge.value(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty());
- if (leftOccurrences != null && !leftOccurrences.equals(RequirementData.MAX_OCCURRENCES)) {
+ if (leftOccurrences != null && !leftOccurrences.equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
Integer leftIntValue = Integer.parseInt(leftOccurrences);
if (leftIntValue > 0) {
exist = true;
@@ -3626,7 +3826,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
public Either<Boolean, StorageOperationStatus> isAvailableCapabilty(ComponentInstance toResInstance, RequirementAndRelationshipPair relationPair) {
Either<TitanVertex, TitanOperationStatus> fromRi = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), toResInstance.getUniqueId());
if (fromRi.isRight()) {
- log.debug("Failed to fetch component instance {}. Error: {}", toResInstance.getUniqueId(), fromRi.right().value());
+ log.debug("Failed to fetch component instance {} error {}", toResInstance.getUniqueId(), fromRi.right().value());
return Either.right(StorageOperationStatus.NOT_FOUND);
}
Iterator<Edge> edgeIter = fromRi.left().value().edges(Direction.OUT, GraphEdgeLabels.CALCULATED_CAPABILITY.name());
@@ -3643,7 +3843,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
String ownerIdOnEdge = (String) edge.value(GraphEdgePropertiesDictionary.OWNER_ID.getProperty());
if (ownerIdOnEdge.equals(relationPair.getCapabilityOwnerId())) {
String leftOccurrences = (String) edge.value(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty());
- if (leftOccurrences != null && !leftOccurrences.equals(CapabilityData.MAX_OCCURRENCES)) {
+ if (leftOccurrences != null && !leftOccurrences.equals(CapabilityDataDefinition.MAX_OCCURRENCES)) {
Integer leftIntValue = Integer.parseInt(leftOccurrences);
if (leftIntValue > 0) {
exist = true;
@@ -3727,7 +3927,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
List<ComponentInstanceAttribute> attributesOnInstance = compInstanceAttList.getInnerElement();
for (int i = 0; i < attributesOnInstance.size() && storageStatusWrapper.isEmpty(); i++) {
StorageOperationStatus result = cloneSingleAttributeOnResourceInstance(createdInstanceVertex, attributesOnInstance.get(i), instanceId);
- if (!result.equals(StorageOperationStatus.OK)) {
+ if (result != StorageOperationStatus.OK) {
log.trace("Failed to clone attribute for instance {} error {}", instanceId, result);
return result;
}
@@ -4024,7 +4224,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
Either<ComponentInstanceProperty, TitanOperationStatus> addPropertyToResourceInstance = this.addPropertyToResourceInstance(property, toResourceInstance, false, index, resourceInstanceId);
- if (addPropertyToResourceInstance.isRight() && !addPropertyToResourceInstance.right().value().equals(TitanOperationStatus.OK)) {
+ if (addPropertyToResourceInstance.isRight() && addPropertyToResourceInstance.right().value() != TitanOperationStatus.OK) {
StorageOperationStatus storageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(addPropertyToResourceInstance.right().value());
return storageStatus;
}
@@ -4032,13 +4232,13 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
ComponentInstanceProperty newProp = addPropertyToResourceInstance.left().value();
Set<String> inputsKey = inputsPropMap.keySet();
String inputToAssName = null;
- GetInputValueInfo getInputInfo = null;
+ GetInputValueDataDefinition getInputInfo = null;
for (String inputName : inputsKey) {
List<ComponentInstanceProperty> propsList = inputsPropMap.get(inputName);
Optional<ComponentInstanceProperty> op = propsList.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
if (op.isPresent()) {
ComponentInstanceProperty inpProp = op.get();
- getInputInfo = new GetInputValueInfo();
+ getInputInfo = new GetInputValueDataDefinition();
getInputInfo.setPropName(inpProp.getName());
getInputInfo.setInputName(inputName);
inputToAssName = inputName;
@@ -4536,7 +4736,8 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
* Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, value, innerType, allDataTypes.left().value());
*
* String newValue = value; if (isValid.isRight()) { Boolean res = isValid.right().value(); if (res == false) { return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); } } else { Object object = isValid.left().value(); if (object !=
- * null) { newValue = object.toString(); } } InputValueData propertyValueData = updateDataContainer.getValueDataWrapper().getInnerElement(); log.debug("Going to update property value from {} to {}", propertyValueData.getValue(), newValue); propertyValueData.setValue(newValue);
+ * null) { newValue = object.toString(); } } InputValueData propertyValueData = updateDataContainer.getValueDataWrapper().getInnerElement(); log.debug("Going to update property value from " + propertyValueData.getValue() + " to " +
+ * newValue); propertyValueData.setValue(newValue);
*
* ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, resourceInstanceProerty.getRules(), innerType, allDataTypes.left().value()); if (pair.getRight() != null && pair.getRight() == false) {
* BeEcompErrorManager.getInstance(). logBeInvalidValueError("Add property value", pair.getLeft(), resourceInstanceProerty.getName(), propertyType); return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); }
@@ -4695,7 +4896,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
}
if (isPropertyValueExists.getLeft() != TitanOperationStatus.NOT_FOUND) {
- log.debug("After finding property value of {} on component instance {}", propertyId, resourceInstanceId);
+ log.debug("After finding property value of {} on componenet instance {}", propertyId, resourceInstanceId);
return Either.right(isPropertyValueExists.getLeft());
}
@@ -4771,8 +4972,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
if (createRelResult.isRight()) {
TitanOperationStatus operationStatus = createRelResult.right().value();
- // TODO: change logger
- log.error("Failed to associate property value " + uniqueId + " to property " + propertyId + " in graph. status is " + operationStatus);
+ log.error("Failed to associate property value {} to property {} in graph. status is {}", uniqueId, propertyId, operationStatus);
return Either.right(operationStatus);
}
@@ -4780,8 +4980,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
if (createRelResult.isRight()) {
TitanOperationStatus operationStatus = createRelResult.right().value();
- // TODO: change logger
- log.error("Failed to associate resource instance " + resourceInstanceId + " property value " + uniqueId + " in graph. status is " + operationStatus);
+ log.error("Failed to associate resource instance {} property value {} in graph. status is {}", resourceInstanceId, uniqueId, operationStatus);
return Either.right(operationStatus);
}
@@ -4879,7 +5078,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
log.trace("Before validateAndUpdateRules");
ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, resourceInstanceProperty.getRules(), innerType, allDataTypes.left().value(), isValidate);
- log.debug("After validateAndUpdateRules. pair = {}", pair);
+ log.debug("After validateAndUpdateRules. pair = {} ", pair);
if (pair.getRight() != null && pair.getRight() == false) {
BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), resourceInstanceProperty.getName(), propertyType);
return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
@@ -4900,20 +5099,19 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
if (createRelResult.isRight()) {
TitanOperationStatus operationStatus = createRelResult.right().value();
- // TODO: change logger
- log.error("Failed to associate property value " + uniqueId + " to property " + propertyId + " in graph. status is " + operationStatus);
+ log.error("Failed to associate property value {} to property {} in graph. status is {}", uniqueId, propertyId, operationStatus);
return Either.right(operationStatus);
}
TitanOperationStatus edgeResult = titanGenericDao.createEdge(resourceInstanceVertex, propertyValueData, GraphEdgeLabels.PROPERTY_VALUE, null);
- if (!edgeResult.equals(TitanOperationStatus.OK)) {
- log.error("Failed to associate resource instance " + resourceInstanceId + " property value " + uniqueId + " in graph. status is " + edgeResult);
+ if (edgeResult != TitanOperationStatus.OK) {
+ log.error("Failed to associate resource instance {} property value {} in graph. status is {}", resourceInstanceId, uniqueId, edgeResult);
return Either.right(edgeResult);
}
ComponentInstanceProperty propertyValueResult = propertyOperation.buildResourceInstanceProperty(propertyValueData, resourceInstanceProperty);
- log.debug("The returned ResourceInstanceProperty is {}", propertyValueResult);
+ log.debug("The returned ResourceInstanceProperty is {} ", propertyValueResult);
return Either.left(propertyValueResult);
} else {
@@ -4963,7 +5161,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
ImmutablePair<TitanOperationStatus, String> isInputValueExists = inputOperation.findInputValue(resourceInstanceId, propertyId);
if (isInputValueExists.getLeft() == TitanOperationStatus.ALREADY_EXIST) {
- log.debug("The property {} already added to the resource insance {}", propertyId, resourceInstanceId);
+ log.debug("The property {} already added to the resource instance {}", propertyId, resourceInstanceId);
resourceInstanceInput.setValueUniqueUid(isInputValueExists.getRight());
/*
* Either<InputValueData, TitanOperationStatus> updatePropertyOfResourceInstance = updatePropertyOfResourceInstance(resourceInstanceInput, resourceInstanceId); if (updatePropertyOfResourceInstance.isRight()) {
@@ -4973,7 +5171,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
}
if (isInputValueExists.getLeft() != TitanOperationStatus.NOT_FOUND) {
- log.debug("After finding input value of {} on compnent instance {}", propertyId, resourceInstanceId);
+ log.debug("After finding input value of {} on componenet instance {}", propertyId, resourceInstanceId);
return Either.right(isInputValueExists.getLeft());
}
@@ -4992,7 +5190,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
}
PropertyDataDefinition propDef = def.getProperty();
if (propDef == null) {
- log.debug("Property in Schema Definition inside property of type {} doesn't exists", type);
+ log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
}
innerType = propDef.getType();
@@ -5005,21 +5203,6 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
return Either.right(status);
}
- // Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, value, innerType, allDataTypes.left().value());
- // log.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.buildResourceInstanceInputValueUid(resourceInstanceData.getUniqueId(), index);
InputValueData propertyValueData = new InputValueData();
@@ -5028,7 +5211,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
log.debug("Before validateAndUpdateRules");
ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, resourceInstanceInput.getRules(), innerType, allDataTypes.left().value(), true);
- log.debug("After validateAndUpdateRules. pair = {}", pair);
+ log.debug("After validateAndUpdateRules. pair = {} ", pair);
if (pair.getRight() != null && pair.getRight() == false) {
BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), resourceInstanceInput.getName(), propertyType);
return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
@@ -5049,8 +5232,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
if (createRelResult.isRight()) {
TitanOperationStatus operationStatus = createRelResult.right().value();
- // TODO: change logger
- log.error("Failed to associate property value {} to property {} in graph. Status is {}", uniqueId, propertyId, operationStatus);
+ log.error("Failed to associate property value {} to property {} in graph. status is {}", uniqueId, propertyId, operationStatus);
return Either.right(operationStatus);
}
@@ -5063,8 +5245,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
if (createRelResult.isRight()) {
TitanOperationStatus operationStatus = createNodeResult.right().value();
- // TODO: change logger
- log.error("Failed to associate resource instance {} property value {} in graph. Status is {}", resourceInstanceId, uniqueId, operationStatus);
+ log.error("Failed to associate resource instance {} property value {} in graph. status is {}", resourceInstanceId, uniqueId, operationStatus);
return Either.right(operationStatus);
}
@@ -5282,6 +5463,40 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
return Either.left(result);
}
+ // TODO Tal G US831698
+ public Either<List<ComponentInstanceProperty>, StorageOperationStatus> getComponentInstancesPropertiesAndValuesFromGraph(ComponentInstance resourceInstance) {
+
+ Map<String, List<PropertyDefinition>> alreadyProcessedResources = new HashMap<>();
+ Map<String, List<ComponentInstanceProperty>> alreadyProcessedInstances = new HashMap<>();
+ Map<String, ImmutablePair<ComponentInstance, Integer>> processedInstances = new HashMap<>();
+ Map<String, List<ComponentInstanceProperty>> resourceInstancesProperties = new HashMap<>();
+
+ List<String> path = new ArrayList<>();
+ path.add(resourceInstance.getUniqueId());
+ Either<List<ComponentInstanceProperty>, TitanOperationStatus> componentInstanceProperties = getComponentInstanceProperties(resourceInstance, alreadyProcessedResources, alreadyProcessedInstances, processedInstances, path);
+
+ if (componentInstanceProperties.isRight()) {
+ StorageOperationStatus convertTitanStatusToStorageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(componentInstanceProperties.right().value());
+ return Either.right(convertTitanStatusToStorageStatus);
+ }
+
+ List<ComponentInstanceProperty> listOfProps = componentInstanceProperties.left().value();
+ resourceInstancesProperties.put(resourceInstance.getUniqueId(), listOfProps);
+
+ processedInstances.put(resourceInstance.getUniqueId(), new ImmutablePair<ComponentInstance, Integer>(resourceInstance, path.size()));
+ path.remove(path.size() - 1);
+
+ Either<Map<String, Map<String, ComponentInstanceProperty>>, TitanOperationStatus> findAllPropertiesValuesOnInstances = findAllPropertyValueOnInstances(processedInstances);
+ // 1. check status
+ if (findAllPropertiesValuesOnInstances.isRight()) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(findAllPropertiesValuesOnInstances.right().value()));
+ }
+
+ propertyOperation.updatePropertiesByPropertyValues(resourceInstancesProperties, findAllPropertiesValuesOnInstances.left().value());
+
+ return Either.left(resourceInstancesProperties.get(resourceInstance.getUniqueId()));
+ }
+
public Either<List<ComponentInstanceProperty>, TitanOperationStatus> getComponentInstanceProperties(ComponentInstance resourceInstance, Map<String, List<PropertyDefinition>> alreadyProcessedResources,
Map<String, List<ComponentInstanceProperty>> alreadyProcessedInstances, Map<String, ImmutablePair<ComponentInstance, Integer>> processedInstances, List<String> path) {
@@ -5333,7 +5548,6 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
resourceInstancePropertyList.add(resourceInstanceProperty);
}
-
}
OriginTypeEnum originType = resourceInstance.getOriginType();
@@ -5381,7 +5595,9 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
case PRODUCT:
containerNodeType = NodeTypeEnum.Product;
compInstNodeType = NodeTypeEnum.Service;
+ break;
case VFC:
+ case VFCMT:
case VL:
case CP:
break;
@@ -5418,7 +5634,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
return null;
}
- List<String> clonedList = new ArrayList();
+ List<String> clonedList = new ArrayList<String>();
clonedList.addAll(list);
return clonedList;
@@ -5441,7 +5657,6 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
ImmutablePair<ComponentInstance, Integer> pair = entry.getValue();
ComponentInstance componentInstance = pair.getLeft();
- Integer level = pair.getRight();
Either<List<ComponentInstanceProperty>, TitanOperationStatus> propeprtyValueOnCIResult = findPropertyValueOnComponentInstance(componentInstance);
@@ -5454,10 +5669,10 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
}
List<ComponentInstanceProperty> propertyValuesOnCI = propeprtyValueOnCIResult.left().value();
- if (propeprtyValueOnCIResult != null) {
+ if (propertyValuesOnCI != null) {
for (ComponentInstanceProperty instanceProperty : propertyValuesOnCI) {
boolean result = addPropertyValue(compInstUniqueId, instanceProperty, propertyToInstanceValue);
- if (result == false) {
+ if (!result) {
return Either.right(TitanOperationStatus.ALREADY_EXIST);
}
}
@@ -5558,7 +5773,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
capability.getUniqueId(), capability.getName(), capability.getProperties(), !isNewlyCreatedResourceInstance);
if (addCapInstWithPropertiesRes.isRight()) {
error = addCapInstWithPropertiesRes.right().value();
- log.debug("Failed to assotiate capability instance to resource instance {}. Status is {}", resourceInstanceId, error);
+ log.debug("Failed to assotiate capability instance to resource instance {}. status is {}", resourceInstanceId, error);
}
log.debug("After adding capability property values to resource instance {}. Status is {}", resourceInstanceId, error);
if (error == null) {
@@ -5573,7 +5788,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
TitanOperationStatus addCapInstWithPropertiesRes = capabilityInstanceOperation.createCapabilityInstanceOfCapabilityWithPropertyValuesForResourceInstance(resourceInstanceVertex, resourceInstanceId, capability.getUniqueId(),
capability.getName(), capability.getProperties(), !isNewlyCreatedResourceInstance);
- if (!addCapInstWithPropertiesRes.equals(TitanOperationStatus.OK)) {
+ if (addCapInstWithPropertiesRes != TitanOperationStatus.OK) {
error = addCapInstWithPropertiesRes;
log.debug("Failed to assotiate capability instance to resource instance {} . status is {}", resourceInstanceId, error);
}
@@ -5596,7 +5811,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
Either<List<PropertyValueData>, TitanOperationStatus> updateCapabilityPropertyValuesRes = capabilityInstanceOperation.updateCapabilityPropertyValues(resourceInstanceId, capabilityId, propertyValues);
if (updateCapabilityPropertyValuesRes.isRight()) {
error = updateCapabilityPropertyValuesRes.right().value();
- log.debug("Failed to update property values of capability {} of resource instance {}. Status is {}", capabilityId, resourceInstanceId, error);
+ log.debug("Failed to update property values of capability {} of resource instance {}. status is {}", capabilityId, resourceInstanceId, error);
}
log.debug("After updating property values of capability {} of resource instance {}. Status is {}", capabilityId, resourceInstanceId, error);
if (error == null) {
@@ -5619,14 +5834,14 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
Either<CapabilityInstData, TitanOperationStatus> getCapInstByCapabilityRes = capabilityInstanceOperation.getCapabilityInstanceOfCapabilityOfResourceInstance(resourceInstanceId, capabilityId);
if (getCapInstByCapabilityRes.isRight()) {
error = getCapInstByCapabilityRes.right().value();
- log.debug("Failed to retrieve capability instance of capability {} of resource instance {}. Status is {}", capabilityId, resourceInstanceId, error);
+ log.debug("Failed to retrieve capability instance of capability {} of resource instance {}. status is {}", capabilityId, resourceInstanceId, error);
}
if (error == null) {
String capabilityInstanceId = getCapInstByCapabilityRes.left().value().getUniqueId();
deleteCapInstWithPropertiesRes = capabilityInstanceOperation.deleteCapabilityInstanceFromResourceInstance(resourceInstanceId, capabilityInstanceId);
if (deleteCapInstWithPropertiesRes.isRight()) {
error = deleteCapInstWithPropertiesRes.right().value();
- log.debug("Failed to delete capability instance {} to resource instance {}. Status is {}", capabilityInstanceId, resourceInstanceId, error);
+ log.debug("Failed to delete capability instance {} to resource instance {}. status is {}", capabilityInstanceId, resourceInstanceId, error);
}
}
log.debug("After deleting property values of capability {} from resource instance {}. Status is {}", capabilityId, resourceInstanceId, error);
@@ -5653,7 +5868,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
Either<List<ImmutablePair<CapabilityInstData, GraphEdge>>, TitanOperationStatus> getAllCapabilityInstancesRes = capabilityInstanceOperation.getAllCapabilityInstancesOfResourceInstance(resourceInstanceId);
if (getAllCapabilityInstancesRes.isRight() && !getAllCapabilityInstancesRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
error = getAllCapabilityInstancesRes.right().value();
- log.debug("Failed to get capability instances of component instance {}. Status is {}", resourceInstanceId, error);
+ log.debug("Failed to get capability instances of component instance {}. status is {}", resourceInstanceId, error);
}
if (getAllCapabilityInstancesRes.isLeft()) {
List<ImmutablePair<CapabilityInstData, GraphEdge>> capabilityInstances = getAllCapabilityInstancesRes.left().value();
@@ -5670,7 +5885,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
cloneAssociateCIWithPropertyValuesRes = capabilityInstanceOperation.cloneAssociateCapabilityInstanceWithPropertyValues(createdComponentInstance, relatedCapability, capabilityInstPair);
if (cloneAssociateCIWithPropertyValuesRes.isRight()) {
error = cloneAssociateCIWithPropertyValuesRes.right().value();
- log.debug("Failed to clone capability instances {} of component instance {}. Status is {}", capabilityInstPair.getLeft().getUniqueId(), resourceInstanceId, error);
+ log.debug("Failed to clone capability instances {} of component instance {}. status is {}", capabilityInstPair.getLeft().getUniqueId(), resourceInstanceId, error);
break;
} else {
result.put(new ImmutablePair<CapabilityInstData, GraphEdge>(cloneAssociateCIWithPropertyValuesRes.left().value().getLeft(), capabilityInstPair.getRight()), cloneAssociateCIWithPropertyValuesRes.left().value().getRight());
@@ -5691,7 +5906,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
Either<TitanVertex, TitanOperationStatus> cloneAssociateCIWithPropertyValuesRes = null;
Either<List<ImmutablePair<CapabilityInstData, GraphEdge>>, TitanOperationStatus> getAllCapabilityInstancesRes = capabilityInstanceOperation.getAllCapabilityInstancesOfResourceInstance(resourceInstanceId);
- if (getAllCapabilityInstancesRes.isRight() && !getAllCapabilityInstancesRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
+ if (getAllCapabilityInstancesRes.isRight() && getAllCapabilityInstancesRes.right().value() != TitanOperationStatus.NOT_FOUND) {
error = getAllCapabilityInstancesRes.right().value();
log.debug("Failed to get capability instances of component instance {}. status is {}", resourceInstanceId, error);
}
@@ -5784,29 +5999,26 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
if (getOverridedPropertyValuesRes.isRight()) {
error = getOverridedPropertyValuesRes.right().value();
log.debug("Failed to retrieve property values of capability instance {}. Status is {}", curCapInstUid, error);
- }
-
- log.debug("After getting all property values of capability instance {} of component istance {}. Status is {}", curCapInstUid, componentInstanceId, error);
- Map<String, PropertyValueData> overridedPropertyValuesHM = new HashMap<>();
- List<ImmutablePair<PropertyValueData, GraphEdge>> overridedPropertyValues = getOverridedPropertyValuesRes.left().value();
- for (ImmutablePair<PropertyValueData, GraphEdge> curPropertyValuePair : overridedPropertyValues) {
- PropertyValueData curPropertyValue = curPropertyValuePair.getLeft();
- String propertyValueUid = curPropertyValue.getUniqueId();
- log.debug("Before getting property related to property value {} of capability instance {} of component istance {}.", propertyValueUid, curCapInstUid, componentInstanceId);
- Either<ImmutablePair<PropertyData, GraphEdge>, TitanOperationStatus> getPropertyDataRes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.getByName(curPropertyValue.getLabel())), propertyValueUid,
- GraphEdgeLabels.PROPERTY_IMPL, NodeTypeEnum.Property, PropertyData.class);
- if (getPropertyDataRes.isRight()) {
- error = getOverridedPropertyValuesRes.right().value();
- log.debug("Failed to retrieve property of property value {} Status is {}", propertyValueUid, error);
- }
-
- if (log.isDebugEnabled()) {
+ } else {
+ log.debug("After getting all property values of capability instance {} of component istance {}. Status is {}", curCapInstUid, componentInstanceId, error);
+ Map<String, PropertyValueData> overridedPropertyValuesHM = new HashMap<>();
+ List<ImmutablePair<PropertyValueData, GraphEdge>> overridedPropertyValues = getOverridedPropertyValuesRes.left().value();
+ for (ImmutablePair<PropertyValueData, GraphEdge> curPropertyValuePair : overridedPropertyValues) {
+ PropertyValueData curPropertyValue = curPropertyValuePair.getLeft();
+ String propertyValueUid = curPropertyValue.getUniqueId();
+ log.debug("Before getting property related to property value {} of capability instance {} of component istance {}.", propertyValueUid, curCapInstUid, componentInstanceId);
+ Either<ImmutablePair<PropertyData, GraphEdge>, TitanOperationStatus> getPropertyDataRes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.getByName(curPropertyValue.getLabel())), propertyValueUid,
+ GraphEdgeLabels.PROPERTY_IMPL, NodeTypeEnum.Property, PropertyData.class);
+ if (getPropertyDataRes.isRight()) {
+ error = getOverridedPropertyValuesRes.right().value();
+ log.debug("Failed to retrieve property of property value {} Status is {}", propertyValueUid, error);
+ }
log.debug("After getting property related to property value {} of capability instance {} of component istance {}. Status is {}", propertyValueUid, curCapInstUid, componentInstanceId, error);
+ PropertyData propertyData = getPropertyDataRes.left().value().getLeft();
+ overridedPropertyValuesHM.put((String) propertyData.getUniqueId(), curPropertyValue);
}
- PropertyData propertyData = getPropertyDataRes.left().value().getLeft();
- overridedPropertyValuesHM.put((String) propertyData.getUniqueId(), curPropertyValue);
+ overridedCapabilitiesHM.put((String) curCapabilityPair.getRight().getProperties().get(GraphPropertiesDictionary.CAPABILITY_ID.getProperty()), overridedPropertyValuesHM);
}
- overridedCapabilitiesHM.put((String) curCapabilityPair.getRight().getProperties().get(GraphPropertiesDictionary.CAPABILITY_ID.getProperty()), overridedPropertyValuesHM);
}
}
if (error == null && !overridedCapabilitiesHM.isEmpty()) {
@@ -5838,7 +6050,6 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
@Override
public Either<ComponentInstanceInput, StorageOperationStatus> updateInputValueInResourceInstance(ComponentInstanceInput input, String resourceInstanceId, boolean b) {
- // TODO Auto-generated method stub
return null;
}
@@ -5849,4 +6060,119 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
return result;
}
+ @Override
+ public StorageOperationStatus updateCustomizationUUID(String componentInstanceId) {
+ Either<TitanVertex, TitanOperationStatus> vertexByProperty = titanGenericDao.getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), componentInstanceId);
+ if (vertexByProperty.isRight()) {
+ log.debug("Failed to fetch component instance by id {} error {}", componentInstanceId, vertexByProperty.right().value());
+ return DaoStatusConverter.convertTitanStatusToStorageStatus(vertexByProperty.right().value());
+ }
+ UUID uuid = UUID.randomUUID();
+ TitanVertex ciVertex = vertexByProperty.left().value();
+ ciVertex.property(GraphPropertiesDictionary.CUSTOMIZATION_UUID.getProperty(), uuid.toString());
+
+ return StorageOperationStatus.OK;
+ }
+
+ private Either<String, Boolean> handleGroupInstanceNameLogic(TitanVertex ciVertex, GroupInstance groupInstance, String componentInstanceId, String componentInstanceName, String groupName) {
+
+ groupInstance.setGroupName(groupName);
+
+ String logicalName = groupInstanceOperation.createGroupInstLogicalName(componentInstanceName, groupName);
+
+ Boolean eitherValidation = validateGroupInstanceName(logicalName, groupInstance, true);
+ if (!eitherValidation) {
+ return Either.right(false);
+ }
+ // groupInstance.setName(logicalName);
+ return Either.left(logicalName);
+ }
+
+ private Boolean validateGroupInstanceName(String groupInstanceName, GroupInstance groupInstance, boolean isCreate) {
+
+ if (!ValidationUtils.validateStringNotEmpty(groupInstanceName)) {
+ return false;
+ }
+ groupInstance.setNormalizedName(ValidationUtils.normalizeComponentInstanceName(groupInstanceName));
+ if (!isCreate) {
+ if (!ValidationUtils.validateResourceInstanceNameLength(groupInstanceName)) {
+ return false;
+ }
+ if (!ValidationUtils.validateResourceInstanceName(groupInstanceName)) {
+ return false;
+ }
+ }
+
+ return true;
+
+ }
+ // Evg: need to be public for reuse code in migration
+ public Either<GroupInstance, StorageOperationStatus> createGroupInstance(TitanVertex ciVertex, GroupDefinition groupDefinition, ComponentInstance componentInstance) {
+ // create VFC instance on VF
+ GroupInstance groupInstance = null;
+
+ boolean isCreateName = false;
+ List<GroupInstance> groupInstances = componentInstance.getGroupInstances();
+ if (groupInstances != null && !groupInstances.isEmpty()) {
+ Optional<GroupInstance> op = groupInstances.stream().filter(p -> p.getGroupUid().equals(groupDefinition.getUniqueId())).findAny();
+ if (op.isPresent()) {
+ groupInstance = op.get();
+
+ }
+ }
+ if (groupInstance == null) {
+ groupInstance = new GroupInstance();
+ groupInstance.setGroupUid(groupDefinition.getUniqueId());
+
+ groupInstance.setArtifacts(groupDefinition.getArtifacts());
+ Either<String, Boolean> handleNameLogic = handleGroupInstanceNameLogic(ciVertex, groupInstance, componentInstance.getUniqueId(), componentInstance.getNormalizedName(), groupDefinition.getName());
+ if (handleNameLogic.isRight() && !handleNameLogic.right().value()) {
+
+ if (handleNameLogic.isRight()) {
+ log.debug("failed to create logical name gor group instance {}", groupInstance.getName());
+ return Either.right(StorageOperationStatus.INVALID_ID);
+
+ }
+ }
+ isCreateName = true;
+ // groupInstance.setName(handleNameLogic.left().value());
+
+ }
+
+ return groupInstanceOperation.createGroupInstance(ciVertex, componentInstance.getUniqueId(), groupInstance, isCreateName);
+
+ }
+
+ @Override
+ public Either<ComponentInstanceData, StorageOperationStatus> updateComponentInstanceModificationTimeAndCustomizationUuidOnGraph(ComponentInstance componentInstance, NodeTypeEnum componentInstanceType, Long modificationTime, boolean inTransaction) {
+
+ log.debug("Going to update modification time of component instance {}. ", componentInstance.getName());
+ Either<ComponentInstanceData, StorageOperationStatus> result = null;
+ try{
+ ComponentInstanceData componentData = new ComponentInstanceData(componentInstance, componentInstance.getGroupInstances().size());
+ componentData.getComponentInstDataDefinition().setModificationTime(modificationTime);
+ componentData.getComponentInstDataDefinition().setCustomizationUUID(UUID.randomUUID().toString());
+ Either<ComponentInstanceData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(componentData, ComponentInstanceData.class);
+ if (updateNode.isRight()) {
+ log.error("Failed to update resource {}. status is {}", componentInstance.getUniqueId(), updateNode.right().value());
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateNode.right().value()));
+ }else{
+ result = Either.left(updateNode.left().value());
+ }
+ }catch(Exception e){
+ log.error("Exception occured during update modification date of compomemt instance{}. The message is {}. ", componentInstance.getName(), e.getMessage(), e);
+ result = Either.right(StorageOperationStatus.GENERAL_ERROR);
+ }finally {
+ if(!inTransaction){
+ if (result == null || result.isRight()) {
+ log.error("Going to execute rollback on graph.");
+ titanGenericDao.rollback();
+ } else {
+ log.debug("Going to execute commit on graph.");
+ titanGenericDao.commit();
+ }
+ }
+ }
+ return result;
+ }
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ComponentOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ComponentOperation.java
index b243c6ea4d..e06649bf77 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ComponentOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ComponentOperation.java
@@ -22,23 +22,15 @@ package org.openecomp.sdc.be.model.operations.impl;
import java.time.Duration;
import java.time.Instant;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
+import java.util.*;
import java.util.Map.Entry;
-import java.util.Optional;
-import java.util.Set;
-import java.util.UUID;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
+import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.ImmutableTriple;
import org.apache.commons.lang3.tuple.Pair;
@@ -66,6 +58,7 @@ import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
import org.openecomp.sdc.be.model.AdditionalInformationDefinition;
import org.openecomp.sdc.be.model.ArtifactDefinition;
@@ -80,8 +73,10 @@ import org.openecomp.sdc.be.model.GroupDefinition;
import org.openecomp.sdc.be.model.InputDefinition;
import org.openecomp.sdc.be.model.LifecycleStateEnum;
import org.openecomp.sdc.be.model.PropertyDefinition;
+import org.openecomp.sdc.be.model.PropertyDefinition.PropertyNames;
import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
import org.openecomp.sdc.be.model.RequirementDefinition;
+import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
import org.openecomp.sdc.be.model.cache.ComponentCache;
import org.openecomp.sdc.be.model.category.CategoryDefinition;
@@ -93,6 +88,7 @@ import org.openecomp.sdc.be.model.operations.api.ICapabilityOperation;
import org.openecomp.sdc.be.model.operations.api.IElementOperation;
import org.openecomp.sdc.be.model.operations.api.IRequirementOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.model.operations.api.ToscaDefinitionPathCalculator;
import org.openecomp.sdc.be.resources.data.ArtifactData;
import org.openecomp.sdc.be.resources.data.CapabilityData;
import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
@@ -168,6 +164,9 @@ public abstract class ComponentOperation {
@Autowired
private ComponentCache componentCache;
+ @Autowired
+ private ToscaDefinitionPathCalculator toscaDefinitionPathCalculator;
+
private static Pattern uuidNewVersion = Pattern.compile("^\\d{1,}.1");
protected Gson prettyJson = new GsonBuilder().setPrettyPrinting().create();
@@ -193,18 +192,18 @@ public abstract class ComponentOperation {
return Either.left(tagsToCreate);
}
-
+
protected StorageOperationStatus createTagNodesOnGraph(List<TagData> tagsToCreate) {
StorageOperationStatus result = StorageOperationStatus.OK;
// In order to avoid duplicate tags
tagsToCreate = ImmutableSet.copyOf(tagsToCreate).asList();
if (tagsToCreate != null && false == tagsToCreate.isEmpty()) {
for (TagData tagData : tagsToCreate) {
- log.debug("Before creating tag {}", tagData);
+ log.debug("Before creating tag {}" , tagData);
Either<TagData, TitanOperationStatus> createTagResult = titanGenericDao.createNode(tagData, TagData.class);
if (createTagResult.isRight()) {
TitanOperationStatus status = createTagResult.right().value();
- log.error("Cannot create {} in the graph. Status is {}", tagData, status);
+ log.error("Cannot create {} in the graph. status is {}", tagData, status);
result = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
}
@@ -216,7 +215,7 @@ public abstract class ComponentOperation {
public Either<Component, StorageOperationStatus> getLatestComponentByUuid(NodeTypeEnum nodeType, String uuid) {
Either<Component, StorageOperationStatus> getComponentResult = null;
- Either<ComponentMetadataData, StorageOperationStatus> latestComponentMetadataRes = getLatestComponentMetadataByUuid(nodeType, uuid);
+ Either<ComponentMetadataData, StorageOperationStatus> latestComponentMetadataRes = getLatestComponentMetadataByUuid(nodeType, uuid, false);
if (latestComponentMetadataRes.isRight()) {
getComponentResult = Either.right(latestComponentMetadataRes.right().value());
}
@@ -234,7 +233,7 @@ public abstract class ComponentOperation {
return getComponentResult;
}
- public Either<ComponentMetadataData, StorageOperationStatus> getLatestComponentMetadataByUuid(NodeTypeEnum nodeType, String uuid) {
+ public Either<ComponentMetadataData, StorageOperationStatus> getLatestComponentMetadataByUuid(NodeTypeEnum nodeType, String uuid, boolean inTransaction) {
Either<ComponentMetadataData, StorageOperationStatus> getComponentResult = null;
List<ComponentMetadataData> latestVersionList = null;
@@ -243,24 +242,31 @@ public abstract class ComponentOperation {
Map<String, Object> propertiesToMatch = new HashMap<String, Object>();
propertiesToMatch.put(GraphPropertiesDictionary.UUID.getProperty(), uuid);
propertiesToMatch.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true);
-
- Either<List<ComponentMetadataData>, TitanOperationStatus> getComponentEither = titanGenericDao.getByCriteria(nodeType, propertiesToMatch, ComponentMetadataData.class);
- if (getComponentEither.isRight()) {
- log.debug("Couldn't fetch metadata for component with type {} and uuid {}, error: {}", nodeType, uuid, getComponentEither.right().value());
- getComponentResult = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getComponentEither.right().value()));
-
- }
- if (getComponentResult == null) {
- latestVersionList = getComponentEither.left().value();
- if (latestVersionList.isEmpty()) {
- log.debug("Component with type {} and uuid {} was not found", nodeType, uuid);
- getComponentResult = Either.right(StorageOperationStatus.NOT_FOUND);
+ try{
+ Either<List<ComponentMetadataData>, TitanOperationStatus> getComponentEither = titanGenericDao.getByCriteria(nodeType, propertiesToMatch, ComponentMetadataData.class);
+ if (getComponentEither.isRight()) {
+ log.debug("Couldn't fetch metadata for component with type {} and uuid {}, error: {}", nodeType, uuid, getComponentEither.right().value());
+ getComponentResult = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getComponentEither.right().value()));
+
+ }
+ if (getComponentResult == null) {
+ latestVersionList = getComponentEither.left().value();
+ if (latestVersionList.isEmpty()) {
+ log.debug("Component with type {} and uuid {} was not found", nodeType, uuid);
+ getComponentResult = Either.right(StorageOperationStatus.NOT_FOUND);
+ }
+ }
+ if (getComponentResult == null) {
+ latestVersion = latestVersionList.size() == 1 ? latestVersionList.get(0)
+ : latestVersionList.stream().max((c1, c2) -> Double.compare(Double.parseDouble(c1.getMetadataDataDefinition().getVersion()), Double.parseDouble(c2.getMetadataDataDefinition().getVersion()))).get();
+ getComponentResult = Either.left(latestVersion);
+ }
+ } catch (Exception e){
+ log.debug("Failed to get latest component metadata with type {} by uuid {}. ", nodeType.getName(), uuid, e);
+ }finally {
+ if (!inTransaction) {
+ titanGenericDao.commit();
}
- }
- if (getComponentResult == null) {
- latestVersion = latestVersionList.size() == 1 ? latestVersionList.get(0)
- : latestVersionList.stream().max((c1, c2) -> Double.compare(Double.parseDouble(c1.getMetadataDataDefinition().getVersion()), Double.parseDouble(c2.getMetadataDataDefinition().getVersion()))).get();
- getComponentResult = Either.left(latestVersion);
}
return getComponentResult;
}
@@ -284,32 +290,6 @@ public abstract class ComponentOperation {
return Either.left(serviceData);
}
- // protected <T extends GraphNode> Either<T, StorageOperationStatus>
- // getComponentByLabelAndId_tx(String uniqueId, NodeTypeEnum nodeType,
- // Class<T> clazz) {
- //
- // Map<String, Object> propertiesToMatch = new HashMap<String, Object>();
- // propertiesToMatch.put(UniqueIdBuilder.getKeyByNodeType(nodeType),
- // uniqueId);
- // Either<List<T>, TitanOperationStatus> getResponse =
- // titanGenericDao.getByCriteria_tx(nodeType, propertiesToMatch, clazz);
- // if (getResponse.isRight()) {
- // log.debug("Couldn't fetch component with type {} and unique id {}, error:
- // {}", nodeType, uniqueId, getResponse.right().value());
- // return
- // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getResponse.right().value()));
- //
- // }
- // List<T> serviceDataList = getResponse.left().value();
- // if (serviceDataList.isEmpty()) {
- // log.debug("Component with type {} and unique id {} was not found",
- // nodeType, uniqueId);
- // return Either.right(StorageOperationStatus.NOT_FOUND);
- // }
- // T serviceData = serviceDataList.get(0);
- // return Either.left(serviceData);
- // }
-
/**
*
* @param component
@@ -415,28 +395,28 @@ public abstract class ComponentOperation {
Map<String, Object> props = new HashMap<String, Object>();
props.put(GraphPropertiesDictionary.STATE.getProperty(), componentData.getMetadataDataDefinition().getState());
Either<GraphRelation, TitanOperationStatus> result = titanGenericDao.createRelation(updater, componentData, GraphEdgeLabels.STATE, props);
- log.debug("After associating user {} to component {}. Edge type is {}", updater, componentData.getUniqueId(), GraphEdgeLabels.STATE);
+ log.debug("After associating user {} to component {}. Edge type is {}" , updater, componentData.getUniqueId(), GraphEdgeLabels.STATE);
if (result.isRight()) {
return result.right().value();
}
result = titanGenericDao.createRelation(updater, componentData, GraphEdgeLabels.LAST_MODIFIER, null);
- log.debug("After associating user {} to component {}. Edge type is {}", updater, componentData.getUniqueId(), GraphEdgeLabels.LAST_MODIFIER);
+ log.debug("After associating user {} to component {}. Edge type is {}", updater, componentData.getUniqueId(), GraphEdgeLabels.LAST_MODIFIER);
if (result.isRight()) {
- log.error("Failed to associate user " + updater + " to component " + componentData.getUniqueId() + ". Edge type is " + GraphEdgeLabels.LAST_MODIFIER);
+ log.error("Failed to associate user {} to component {}. Edge type is {}", updater, componentData.getUniqueId(), GraphEdgeLabels.LAST_MODIFIER);
return result.right().value();
}
result = titanGenericDao.createRelation(userData, componentData, GraphEdgeLabels.CREATOR, null);
- log.debug("After associating user {} to component {}. Edge type is {}", userData, componentData.getUniqueId(), GraphEdgeLabels.CREATOR);
+ log.debug("After associating user {} to component {}. Edge type is {}" , userData, componentData.getUniqueId(), GraphEdgeLabels.CREATOR);
if (result.isRight()) {
- log.error("Failed to associate user " + userData + " to component " + componentData.getUniqueId() + ". Edge type is " + GraphEdgeLabels.CREATOR);
+ log.error("Failed to associate user {} to component {}. Edge type is {}", userData, componentData.getUniqueId(), GraphEdgeLabels.CREATOR);
return result.right().value();
}
if (derivedResources != null) {
for (ResourceMetadataData derivedResource : derivedResources) {
- log.debug("After associating component {} to parent component {}. Egde type is {}", componentData.getUniqueId(), derivedResource.getUniqueId(), GraphEdgeLabels.DERIVED_FROM);
+ log.debug("After associating component {} to parent component {}. Edge type is {}" ,componentData.getUniqueId(), derivedResource.getUniqueId(), GraphEdgeLabels.DERIVED_FROM);
result = titanGenericDao.createRelation(componentData, derivedResource, GraphEdgeLabels.DERIVED_FROM, null);
if (result.isRight()) {
log.error("Failed to associate user {} to component {}. Edge type is {}", userData, componentData.getUniqueId(), GraphEdgeLabels.CREATOR);
@@ -464,11 +444,7 @@ public abstract class ComponentOperation {
ArtifactDefinition artifactDefinition = entry.getValue();
Either<ArtifactDefinition, StorageOperationStatus> addArifactToResource = Either.left(artifactDefinition);
- // if ((artifactDefinition.getUniqueId() != null) &&
- // !artifactDefinition.getUniqueId().isEmpty()) {
addArifactToResource = artifactOperation.addArifactToComponent(artifactDefinition, (String) componentData.getUniqueId(), nodeType, false, true);
- // }
-
if (addArifactToResource.isRight()) {
return addArifactToResource.right().value();
}
@@ -497,68 +473,68 @@ public abstract class ComponentOperation {
for (ResourceMetadataData resourceData : resourceList) {
builder.append(resourceData.getUniqueId() + "|");
}
- log.debug("resources with property name: {} exists in graph. Found {}", name, builder.toString());
+ log.debug("resources with property name:{} exists in graph. found {}",name, builder.toString());
}
return Either.left(false);
} else {
- log.debug("resources with property name:" + name + " does not exists in graph");
+ log.debug("resources with property name:{} does not exists in graph", name);
return Either.left(true);
}
}
-
- protected Either<Boolean, StorageOperationStatus> validateToscaResourceNameUniqueness(String name, TitanGenericDao titanGenericDao) {
+
+ protected Either<Boolean, StorageOperationStatus> validateServiceNameUniqueness(String name, TitanGenericDao titanGenericDao) {
Map<String, Object> properties = new HashMap<>();
+ String normalizedName = ValidationUtils.normaliseComponentName(name);
+ properties.put(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(), normalizedName);
- properties.put(GraphPropertiesDictionary.TOSCA_RESOURCE_NAME.getProperty(), name);
-
- Either<List<ResourceMetadataData>, TitanOperationStatus> resources = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, properties, ResourceMetadataData.class);
- if (resources.isRight() && resources.right().value() != TitanOperationStatus.NOT_FOUND) {
- log.debug("failed to get resources from graph with property name:" + name);
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resources.right().value()));
+ Either<List<ServiceMetadataData>, TitanOperationStatus> services = titanGenericDao.getByCriteria(NodeTypeEnum.Service, properties, ServiceMetadataData.class);
+ if (services.isRight() && services.right().value() != TitanOperationStatus.NOT_FOUND) {
+ log.debug("failed to get services from graph with property name: {}" , name);
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(services.right().value()));
}
- List<ResourceMetadataData> resourceList = (resources.isLeft() ? resources.left().value() : null);
- if (resourceList != null && resourceList.size() > 0) {
+ List<ServiceMetadataData> serviceList = (services.isLeft() ? services.left().value() : null);
+ if (serviceList != null && serviceList.size() > 0) {
if (log.isDebugEnabled()) {
StringBuilder builder = new StringBuilder();
- for (ResourceMetadataData resourceData : resourceList) {
- builder.append(resourceData.getUniqueId() + "|");
+ for (ServiceMetadataData serviceData : serviceList) {
+ builder.append(serviceData.getUniqueId() + "|");
}
- log.debug("resources with property name:" + name + " exists in graph. found " + builder.toString());
+ log.debug("Service with property name:{} exists in graph. found {}" , name, builder.toString());
}
+
return Either.left(false);
} else {
- log.debug("resources with property name: {} dows not exists in the graph", name);
+ log.debug("Service with property name:{} does not exists in graph", name);
return Either.left(true);
}
-
}
-
- protected Either<Boolean, StorageOperationStatus> validateServiceNameUniqueness(String name, TitanGenericDao titanGenericDao) {
+
+ protected Either<Boolean, StorageOperationStatus> validateToscaResourceNameUniqueness(String name, TitanGenericDao titanGenericDao) {
Map<String, Object> properties = new HashMap<>();
- String normalizedName = ValidationUtils.normaliseComponentName(name);
- properties.put(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(), normalizedName);
- Either<List<ServiceMetadataData>, TitanOperationStatus> services = titanGenericDao.getByCriteria(NodeTypeEnum.Service, properties, ServiceMetadataData.class);
- if (services.isRight() && services.right().value() != TitanOperationStatus.NOT_FOUND) {
- log.debug("failed to get services from graph with property name: {}", name);
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(services.right().value()));
+ properties.put(GraphPropertiesDictionary.TOSCA_RESOURCE_NAME.getProperty(), name);
+
+ Either<List<ResourceMetadataData>, TitanOperationStatus> resources = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, properties, ResourceMetadataData.class);
+ if (resources.isRight() && resources.right().value() != TitanOperationStatus.NOT_FOUND) {
+ log.debug("failed to get resources from graph with property name: {}" , name);
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resources.right().value()));
}
- List<ServiceMetadataData> serviceList = (services.isLeft() ? services.left().value() : null);
- if (serviceList != null && serviceList.size() > 0) {
+ List<ResourceMetadataData> resourceList = (resources.isLeft() ? resources.left().value() : null);
+ if (resourceList != null && resourceList.size() > 0) {
if (log.isDebugEnabled()) {
StringBuilder builder = new StringBuilder();
- for (ServiceMetadataData serviceData : serviceList) {
- builder.append(serviceData.getUniqueId() + "|");
+ for (ResourceMetadataData resourceData : resourceList) {
+ builder.append(resourceData.getUniqueId() + "|");
}
- log.debug("Service with property name: {} exists in graph. Found {}", name, builder.toString());
+ log.debug("resources with property name:{} exists in graph. found {}" , name, builder.toString());
}
-
return Either.left(false);
} else {
- log.debug("Service with property name: {} dows not exists in graph", name);
+ log.debug("resources with property name:{} does not exists in graph", name);
return Either.left(true);
}
+
}
protected Either<Boolean, StorageOperationStatus> validateComponentNameUniqueness(String name, TitanGenericDao titanGenericDao, NodeTypeEnum type) {
@@ -568,7 +544,7 @@ public abstract class ComponentOperation {
Either<List<ComponentMetadataData>, TitanOperationStatus> components = titanGenericDao.getByCriteria(type, properties, ComponentMetadataData.class);
if (components.isRight() && components.right().value() != TitanOperationStatus.NOT_FOUND) {
- log.debug("failed to get components from graph with property name: {}", name);
+ log.debug("failed to get components from graph with property name: {}" , name);
return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(components.right().value()));
}
List<ComponentMetadataData> componentList = (components.isLeft() ? components.left().value() : null);
@@ -578,58 +554,16 @@ public abstract class ComponentOperation {
for (ComponentMetadataData componentData : componentList) {
builder.append(componentData.getUniqueId() + "|");
}
- log.debug("Component with property name: {} exists in graph. Found {}", name, builder.toString());
+ log.debug("Component with property name:{} exists in graph. found {}" , name, builder.toString());
}
return Either.left(false);
} else {
- log.debug("Component with property name: {} does not exists in graph", name);
+ log.debug("Component with property name:{} does not exists in graph", name);
return Either.left(true);
}
}
- // protected TitanOperationStatus setComponentCategoryFromGraph(String
- // uniqueId, Component component, TitanGenericDao titanGenericDao,
- // NodeTypeEnum categoryType) {
- //
- // Either<List<ImmutablePair<CategoryData, GraphEdge>>,
- // TitanOperationStatus> parentNode =
- // titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource),
- // uniqueId, GraphEdgeLabels.CATEGORY, categoryType,
- // CategoryData.class);
- // if (parentNode.isRight()) {
- // return parentNode.right().value();
- // }
- //
- // List<ImmutablePair<CategoryData, GraphEdge>> listValue =
- // parentNode.left().value();
- // log.debug("Result after looking for category nodes pointed by resource "
- // + uniqueId + ". status is " + listValue);
- // if (listValue.size() > 1) {
- // log.error("Multiple edges foud between resource " + uniqueId + " to
- // category nodes.");
- // }
- // ImmutablePair<CategoryData, GraphEdge> value = listValue.get(0);
- // log.debug("Found parent node {}", value);
- //
- // CategoryData categoryData = value.getKey();
- // String categoryStr = null;
- // if
- // (NodeTypeEnum.ResourceCategory.name().equalsIgnoreCase(categoryData.getLabel()))
- // {
- // StringBuilder sb = new StringBuilder();
- // sb.append(((ResourceCategoryData) categoryData).getCategoryName());
- // sb.append("/");
- // sb.append(categoryData.getName());
- // categoryStr = sb.toString();
- // } else {
- // categoryStr = categoryData.getName();
- // }
- //
- // component.setCategory(categoryStr);
- // return TitanOperationStatus.OK;
- // }
-
protected StorageOperationStatus setArtifactFromGraph(String uniqueId, Component component, NodeTypeEnum type, IArtifactOperation artifactOperation) {
StorageOperationStatus result = StorageOperationStatus.OK;
Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts = artifactOperation.getArtifacts(uniqueId, type, true);
@@ -686,15 +620,16 @@ public abstract class ComponentOperation {
return component;
}
- private <T, S extends ComponentMetadataData> Either<List<T>, StorageOperationStatus> collectComponents(TitanGraph graph, NodeTypeEnum neededType, String categoryUid, NodeTypeEnum categoryType, Class<S> clazz) {
+ 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 isComplex = neededType == NodeTypeEnum.Resource ? ResourceTypeEnum.VF.equals(((ResourceMetadataDataDefinition) componentData).getResourceType()) : true;
- if (isHighest && isComplex) {
+ boolean isMatchingResourceType = isMatchingByResourceType(neededType, resourceType, componentData);
+
+ if (isHighest && isMatchingResourceType) {
Either<T, StorageOperationStatus> result = getLightComponent(componentData.getUniqueId(), true);
if (result.isRight()) {
return Either.right(result.right().value());
@@ -706,15 +641,31 @@ public abstract class ComponentOperation {
return Either.left(components);
}
+ private boolean isMatchingByResourceType(NodeTypeEnum componentType, ResourceTypeEnum resourceType,
+ ComponentMetadataDataDefinition componentData) {
+
+ boolean isMatching;
+ if (componentType == NodeTypeEnum.Resource) {
+ if (resourceType == null) {
+ isMatching = true;
+ } else {
+ isMatching = resourceType == ((ResourceMetadataDataDefinition)componentData).getResourceType();
+ }
+ } else {
+ isMatching = true;
+ }
+ return isMatching;
+ }
+
protected <T, S extends ComponentMetadataData> Either<List<T>, StorageOperationStatus> fetchByCategoryOrSubCategoryUid(String categoryUid, NodeTypeEnum categoryType, String categoryLabel, NodeTypeEnum neededType, boolean inTransaction,
- Class<S> clazz) {
+ Class<S> clazz, ResourceTypeEnum resourceType) {
try {
Either<TitanGraph, TitanOperationStatus> graph = titanGenericDao.getGraph();
if (graph.isRight()) {
return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graph.right().value()));
}
- return collectComponents(graph.left().value(), neededType, categoryUid, categoryType, clazz);
+ return collectComponents(graph.left().value(), neededType, categoryUid, categoryType, clazz, resourceType);
} finally {
if (false == inTransaction) {
@@ -724,12 +675,12 @@ public abstract class ComponentOperation {
}
protected <T, S extends ComponentMetadataData> Either<List<T>, StorageOperationStatus> fetchByCategoryOrSubCategoryName(String categoryName, NodeTypeEnum categoryType, String categoryLabel, NodeTypeEnum neededType, boolean inTransaction,
- Class<S> clazz) {
+ 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.NAME.getProperty(), categoryName);
+ 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);
@@ -740,7 +691,7 @@ public abstract class ComponentOperation {
}
for (GraphNode category : getCategory.left().value()) {
- Either<List<T>, StorageOperationStatus> result = collectComponents(graph.left().value(), neededType, (String) category.getUniqueId(), categoryType, clazz);
+ Either<List<T>, StorageOperationStatus> result = collectComponents(graph.left().value(), neededType, (String) category.getUniqueId(), categoryType, clazz, resourceType);
if (result.isRight()) {
return result;
}
@@ -784,7 +735,6 @@ public abstract class ComponentOperation {
} else {
// for Designer retrieve specific user
String key = UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User);
- // users = graph.left().value().getVertices(key, userId);
users = graph.left().value().query().has(key, userId).vertices();
}
Iterator<TitanVertex> userIterator = users.iterator();
@@ -852,7 +802,7 @@ public abstract class ComponentOperation {
String stateStr = edge.value(GraphEdgePropertiesDictionary.STATE.getProperty());
LifecycleStateEnum state = LifecycleStateEnum.findState(stateStr);
if (state == null) {
- log.debug("not supported STATE for element {}", stateStr);
+ log.debug("not supported STATE for element {}" , stateStr);
continue;
}
if (lifecycleStates != null && lifecycleStates.contains(state)) {
@@ -902,7 +852,7 @@ public abstract class ComponentOperation {
if (id != null) {
Either<T, StorageOperationStatus> component = getLightComponent(id, inTransaction);
if (component.isRight()) {
- log.debug("Failed to get component for id = {} error: {} skip resource", id, component.right().value());
+ log.debug("Failed to get component for id = {} error : {} skip resource", id, component.right().value());
} else {
components.add(component.left().value());
}
@@ -929,8 +879,11 @@ public abstract class ComponentOperation {
}
private Either<ArtifactData, StorageOperationStatus> generateAndUpdateToscaFileName(String componentType, String componentName, String componentId, NodeTypeEnum type, ArtifactDefinition artifactInfo) {
- Map<String, Object> getConfig = (Map<String, Object>) ConfigurationManager.getConfigurationManager().getConfiguration().getToscaArtifacts().entrySet().stream().filter(p -> p.getKey().equalsIgnoreCase(artifactInfo.getArtifactLabel()))
- .findAny().get().getValue();
+ Map<String, Object> getConfig = (Map<String, Object>) ConfigurationManager.getConfigurationManager().getConfiguration().getToscaArtifacts().entrySet().stream()
+ .filter(p -> p.getKey().equalsIgnoreCase(artifactInfo.getArtifactLabel()))
+ .findAny()
+ .get()
+ .getValue();
artifactInfo.setArtifactName(componentType + "-" + componentName + getConfig.get("artifactName"));
return artifactOperation.updateToscaArtifactNameOnGraph(artifactInfo, artifactInfo.getUniqueId(), type, componentId);
}
@@ -961,7 +914,7 @@ public abstract class ComponentOperation {
Either<CategoryData, StorageOperationStatus> categoryResult = elementOperation.getNewCategoryData(newCategory.getName(), NodeTypeEnum.ServiceNewCategory, CategoryData.class);
if (categoryResult.isRight()) {
StorageOperationStatus status = categoryResult.right().value();
- log.error("Cannot find category " + newCategory.getName() + " in the graph. status is " + status);
+ log.error("Cannot find category {} in the graph. status is {}", newCategory.getName(), status);
return status;
}
@@ -1008,9 +961,6 @@ public abstract class ComponentOperation {
public abstract <T> Either<T, StorageOperationStatus> getComponent(String id, ComponentParametersView componentParametersView, boolean inTrasnaction);
- // public abstract <T> Either<T, StorageOperationStatus>
- // getComponent_tx(String id, boolean inTransaction);
-
protected abstract <T> Either<T, StorageOperationStatus> getComponentByNameAndVersion(String name, String version, Map<String, Object> additionalParams, boolean inTransaction);
public abstract <T> Either<T, StorageOperationStatus> getLightComponent(String id, boolean inTransaction);
@@ -1129,7 +1079,7 @@ public abstract class ComponentOperation {
log.debug("No nodes in graph for criteria : from type = {} and properties = {}", type, props);
return Either.left(result);
} catch (Exception e) {
- log.debug("Failed get by criteria for type = {} and properties = {}. {}", type, props, e);
+ log.debug("Failed get by criteria for type = {} and properties = {}", type, props, e);
return Either.right(TitanGraphClient.handleTitanException(e));
}
}
@@ -1190,7 +1140,7 @@ public abstract class ComponentOperation {
// inTransaction);
Either<T, StorageOperationStatus> component = getLightComponent((String) componentData.getUniqueId(), inTransaction);
if (component.isRight()) {
- log.debug("Failed to get component for id = {} error : {} skip resource", componentData.getUniqueId(), component.right().value());
+ log.debug("Failed to get component for id = {} error : {} skip resource", componentData.getUniqueId(), component.right().value());
// return Either.right(service.right().value());
} else {
result.add(component.left().value());
@@ -1304,6 +1254,7 @@ public abstract class ComponentOperation {
for (ProductMetadataData data : componentsP) {
versionMap.put(data.getMetadataDataDefinition().getVersion(), (String) data.getUniqueId());
}
+ break;
default:
break;
}
@@ -1334,7 +1285,7 @@ public abstract class ComponentOperation {
return DaoStatusConverter.convertTitanStatusToStorageStatus(titanStatus);
}
- log.trace("After adding additional information to component {}. Result is {}", componentId, status.left().value());
+ log.trace("After adding additional information to component {}. Result is {}" , componentId ,status.left().value());
return StorageOperationStatus.OK;
@@ -1619,7 +1570,7 @@ public abstract class ComponentOperation {
// }
valueUid = valuedProperty.getValueUniqueUid();
- log.trace("Found value {} under resource instance whice override the default value {}", value, defaultValue);
+ log.trace("Found value {} under resource instance which override the default value {}" , value, defaultValue);
}
ComponentInstanceProperty resourceInstanceProperty = new ComponentInstanceProperty(propertyDefinition, value, valueUid);
@@ -1681,7 +1632,7 @@ public abstract class ComponentOperation {
StorageOperationStatus updateComponent;
if (updateNode.isRight()) {
- log.debug("Failed to update component {}. Status is {}", componentMetaData.getUniqueId(), updateNode.right().value());
+ log.debug("Failed to update component {}. status is {}", componentMetaData.getUniqueId(), updateNode.right().value());
updateComponent = DaoStatusConverter.convertTitanStatusToStorageStatus(updateNode.right().value());
result = Either.right(updateComponent);
return result;
@@ -1706,14 +1657,13 @@ public abstract class ComponentOperation {
}
private Either<List<RequirementDefinition>, TitanOperationStatus> convertReqDataListToReqDefList(ComponentInstance componentInstance, List<ImmutablePair<RequirementData, GraphEdge>> requirementData) {
- ConvertDataToDef<RequirementDefinition, RequirementData> convertor = (data, edge) -> convertReqDataToReqDef(data, edge);
+ ConvertDataToDef<RequirementDefinition, RequirementData> convertor = (instance, data, edge) -> convertReqDataToReqDef(instance, data, edge);
AddOwnerData<RequirementDefinition> dataAdder = (reqDef, compInstance) -> addOwnerDataReq(reqDef, compInstance);
-
return convertDataToDefinition(componentInstance, requirementData, convertor, dataAdder);
}
private Either<List<CapabilityDefinition>, TitanOperationStatus> convertCapDataListToCapDefList(ComponentInstance componentInstance, List<ImmutablePair<CapabilityData, GraphEdge>> capabilityData) {
- ConvertDataToDef<CapabilityDefinition, CapabilityData> convertor = (data, edge) -> convertCapDataToCapDef(data, edge);
+ ConvertDataToDef<CapabilityDefinition, CapabilityData> convertor = (instance, data, edge) -> convertCapDataToCapDef(instance, data, edge);
AddOwnerData<CapabilityDefinition> dataAdder = (capDef, compInstance) -> addOwnerDataCap(capDef, compInstance);
Either<List<CapabilityDefinition>, TitanOperationStatus> convertationResult = convertDataToDefinition(componentInstance, capabilityData, convertor, dataAdder);
if (convertationResult.isLeft()) {
@@ -1722,7 +1672,7 @@ public abstract class ComponentOperation {
return convertationResult;
}
- private Either<CapabilityDefinition, TitanOperationStatus> convertCapDataToCapDef(CapabilityData data, GraphEdge edge) {
+ private Either<CapabilityDefinition, TitanOperationStatus> convertCapDataToCapDef(ComponentInstance componentInstance, CapabilityData data, GraphEdge edge) {
Either<CapabilityDefinition, TitanOperationStatus> eitherDef = capabilityOperation.getCapabilityByCapabilityData(data);
if (eitherDef.isLeft()) {
@@ -1735,6 +1685,7 @@ public abstract class ComponentOperation {
capabilityOperation.getCapabilitySourcesList(source, sourcesList);
capDef.setName(name);
capDef.setCapabilitySources(sourcesList);
+ capDef.setPath(toscaDefinitionPathCalculator.calculateToscaDefinitionPath(componentInstance, edge));
String requiredOccurrences = (String) properties.get(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty());
if (requiredOccurrences != null) {
@@ -1751,7 +1702,7 @@ public abstract class ComponentOperation {
return eitherDef;
}
- private Either<RequirementDefinition, TitanOperationStatus> convertReqDataToReqDef(RequirementData data, GraphEdge edge) {
+ private Either<RequirementDefinition, TitanOperationStatus> convertReqDataToReqDef(ComponentInstance componentInstance, RequirementData data, GraphEdge edge) {
Either<RequirementDefinition, TitanOperationStatus> eitherDef = requirementOperation.getRequirement(data.getUniqueId());
if (eitherDef.isLeft()) {
@@ -1764,6 +1715,7 @@ public abstract class ComponentOperation {
if (requiredOccurrences != null) {
requirementDef.setMinOccurrences(requiredOccurrences);
}
+ requirementDef.setPath(toscaDefinitionPathCalculator.calculateToscaDefinitionPath(componentInstance, edge));
String leftOccurrences = (String) properties.get(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty());
if (leftOccurrences != null) {
requirementDef.setMaxOccurrences(leftOccurrences);
@@ -1777,7 +1729,7 @@ public abstract class ComponentOperation {
private <Def, Data> Either<List<Def>, TitanOperationStatus> convertDataToDefinition(ComponentInstance componentInstance, List<ImmutablePair<Data, GraphEdge>> requirementData, ConvertDataToDef<Def, Data> convertor, AddOwnerData<Def> dataAdder) {
Either<List<Def>, TitanOperationStatus> eitherResult;
// Convert Data To Definition
- Stream<Either<Def, TitanOperationStatus>> reqDefStream = requirementData.stream().map(e -> convertor.convert(e.left, e.right));
+ Stream<Either<Def, TitanOperationStatus>> reqDefStream = requirementData.stream().map(e -> convertor.convert(componentInstance, e.left, e.right));
// Collect But Stop After First Error
List<Either<Def, TitanOperationStatus>> filteredReqDefList = StreamUtils.takeWhilePlusOne(reqDefStream, p -> p.isLeft()).collect(Collectors.toList());
@@ -1796,7 +1748,7 @@ public abstract class ComponentOperation {
}
interface ConvertDataToDef<Def, Data> {
- Either<Def, TitanOperationStatus> convert(Data d, GraphEdge edge);
+ Either<Def, TitanOperationStatus> convert(ComponentInstance compInstance, Data d, GraphEdge edge);
}
interface AddOwnerData<Def> {
@@ -1979,7 +1931,7 @@ public abstract class ComponentOperation {
NodeTypeEnum label = NodeTypeEnum.getByName(metadataData.getLabel());
switch (label) {
case Resource:
- pair = new ImmutablePair<String, String>(metadataData.getMetadataDataDefinition().getName(), ((ResourceMetadataDataDefinition) metadataData.getMetadataDataDefinition()).getResourceType().getValue());
+ pair = new ImmutablePair<String, String>(metadataData.getMetadataDataDefinition().getName(), ((ResourceMetadataDataDefinition) metadataData.getMetadataDataDefinition()).getResourceType().name());
break;
default:
pair = new ImmutablePair<String, String>(metadataData.getMetadataDataDefinition().getName(), metadataData.getLabel());
@@ -2004,13 +1956,14 @@ public abstract class ComponentOperation {
switch (internalComponentType.toLowerCase()) {
case "vf":
properties.add(new ImmutableTriple<>(QueryType.HAS_NOT, GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.VF.name()));
- properties.add(new ImmutableTriple<>(QueryType.HAS_NOT, GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.VL.name()));
+// properties.add(new ImmutableTriple<>(QueryType.HAS_NOT, GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.VL.name()));
// hasNotPpropertiesToMatch.put(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(),
// ResourceTypeEnum.VF.name());
break;
case "service":
properties.add(new ImmutableTriple<>(QueryType.HAS_NOT, GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.VFC.name()));
- properties.add(new ImmutableTriple<>(QueryType.HAS_NOT, GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.VL.name()));
+ properties.add(new ImmutableTriple<>(QueryType.HAS_NOT, GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.VFCMT.name()));
+// properties.add(new ImmutableTriple<>(QueryType.HAS_NOT, GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.VL.name()));
// hasNotPpropertiesToMatch.put(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(),
// ResourceTypeEnum.VFC.name());
break;
@@ -2104,11 +2057,7 @@ public abstract class ComponentOperation {
manager.addJob(new Job() {
@Override
public Either<Component, StorageOperationStatus> doWork() {
- // long start = System.currentTimeMillis();
Either<Component, StorageOperationStatus> component = getComponent(componentUid, componentParametersView, false);
- // long stop = System.currentTimeMillis();
- // log.info("********** Time calculation in ms:
- // getComponent single {}", (stop-start));
return component;
}
});
@@ -2205,10 +2154,7 @@ public abstract class ComponentOperation {
}
<T> Either<T, StorageOperationStatus> getLightComponent(String id, NodeTypeEnum nodeType, boolean inTransaction) {
- Either<Component, StorageOperationStatus> metadataComponent = getMetadataComponent(id, nodeType, inTransaction);
- if (metadataComponent.isRight()) {
- }
T component = null;
try {
log.debug("Starting to build light component of type {}, id {}", nodeType, id);
@@ -2333,7 +2279,7 @@ public abstract class ComponentOperation {
return Either.left(instanceCounter);
}
- protected TitanOperationStatus setComponentInstancesPropertiesFromGraph(String uniqueId, Component component) {
+ protected TitanOperationStatus setComponentInstancesPropertiesFromGraph(Component component) {
List<ComponentInstance> resourceInstances = component.getComponentInstances();
@@ -2390,7 +2336,7 @@ public abstract class ComponentOperation {
return TitanOperationStatus.OK;
}
-
+
protected TitanOperationStatus setComponentInstancesInputsFromGraph(String uniqueId, Component component) {
Map<String, List<ComponentInstanceInput>> resourceInstancesInputs = new HashMap<>();
@@ -2546,8 +2492,7 @@ public abstract class ComponentOperation {
Instant start = Instant.now();
Either<List<ComponentInstance>, StorageOperationStatus> resourceInstancesOfService = componentInstanceOperation.getAllComponentInstancesMetadataOnly(componentId, nodeType);
Instant end = Instant.now();
- log.debug("TOTAL TIME BL GET INSTANCES: {}", Duration.between(start, end)); // prints
- // PT1M3.553S
+ log.debug("TOTAL TIME BL GET INSTANCES: {}", Duration.between(start, end));
return resourceInstancesOfService;
}
@@ -2648,12 +2593,7 @@ public abstract class ComponentOperation {
break;
}
if (clazz1 != null) {
- // long startGetAllVersions =
- // System.currentTimeMillis();
Either<Map<String, String>, TitanOperationStatus> versionList = getVersionList(componentTypeEnum.getNodeType(), cachedComponent.getVersion(), cachedComponent.getUUID(), cachedComponent.getSystemName(), clazz1);
- // log.debug("Fetch all versions for component {} took
- // {} ms", cachedComponent.getUniqueId(),
- // System.currentTimeMillis() - startGetAllVersions);
if (versionList.isRight()) {
return Either.right(ActionStatus.GENERAL_ERROR);
}
@@ -2732,7 +2672,7 @@ public abstract class ComponentOperation {
if (counterStatus.isRight()) {
- log.error("Cannot find componentInstanceCounter for component {} in the graph. Status is {}", componentData.getUniqueId(), counterStatus);
+ log.error("Cannot find componentInstanceCounter for component {} in the graph. status is {}", componentData.getUniqueId(), counterStatus);
// result = sendError(status,
// StorageOperationStatus.USER_NOT_FOUND);
return result;
@@ -2742,7 +2682,7 @@ public abstract class ComponentOperation {
String modifierUserId = component.getLastUpdaterUserId();
if (modifierUserId == null || modifierUserId.isEmpty()) {
- log.error("userId is missing in the request.");
+ log.error("UserId is missing in the request.");
result = Either.right(StorageOperationStatus.BAD_REQUEST);
return result;
}
@@ -2750,7 +2690,7 @@ public abstract class ComponentOperation {
if (findUser.isRight()) {
TitanOperationStatus status = findUser.right().value();
- log.error("Cannot find user {} in the graph. Status is {}", modifierUserId, status);
+ log.error("Cannot find user {} in the graph. status is {}", modifierUserId, status);
// result = sendError(status,
// StorageOperationStatus.USER_NOT_FOUND);
return result;
@@ -2780,7 +2720,7 @@ public abstract class ComponentOperation {
} else {
log.debug("Going to update the last modifier user of the resource from {} to {}", currentModifier, modifierUserId);
StorageOperationStatus status = moveLastModifierEdge(component, componentData, modifierUserData, type);
- log.debug("Finish to update the last modifier user of the resource from {} to {}. Status is {}", currentModifier, modifierUserId, status);
+ 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;
@@ -2811,7 +2751,7 @@ public abstract class ComponentOperation {
Either<TagData, TitanOperationStatus> createTagResult = titanGenericDao.createNode(tagData, TagData.class);
if (createTagResult.isRight()) {
TitanOperationStatus status = createTagResult.right().value();
- log.error("Cannot find tag {} in the graph. Status is {}", tagData, status);
+ log.error("Cannot find tag {} in the graph. status is {}", tagData, status);
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
return result;
}
@@ -2823,7 +2763,7 @@ public abstract class ComponentOperation {
Either<ComponentMetadataData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(componentData, ComponentMetadataData.class);
if (updateNode.isRight()) {
- log.error("Failed to update resource {}. Status is {}", component.getUniqueId(), updateNode.right().value());
+ log.error("Failed to update resource {}. status is {}", component.getUniqueId(), updateNode.right().value());
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateNode.right().value()));
return result;
}
@@ -2834,7 +2774,8 @@ public abstract class ComponentOperation {
// DE230195 in case resource name changed update TOSCA artifacts
// file names accordingly
String newSystemName = updatedResourceData.getMetadataDataDefinition().getSystemName();
- if (newSystemName != null && !newSystemName.equals(currentComponent.getSystemName())) {
+ String prevSystemName = currentComponent.getSystemName();
+ if (newSystemName != null && !newSystemName.equals(prevSystemName)) {
Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
if (toscaArtifacts != null) {
for (Entry<String, ArtifactDefinition> artifact : toscaArtifacts.entrySet()) {
@@ -2846,8 +2787,15 @@ public abstract class ComponentOperation {
}
}
}
-
+ //TODO call to new Artifact operation in order to update list of artifacts
+
+ //US833308 VLI in service - specific network_role property value logic
+ if (ComponentTypeEnum.SERVICE == component.getComponentType()) {
+ //update method logs success/error and returns boolean (true if nothing fails)
+ updateServiceNameInVLIsNetworkRolePropertyValues(component, prevSystemName, newSystemName);
+ }
}
+
if (component.getComponentType().equals(ComponentTypeEnum.RESOURCE)) {
updateDerived(component, currentComponent, componentData, component.getClass());
@@ -2863,13 +2811,7 @@ public abstract class ComponentOperation {
T updatedResourceValue = updatedResource.left().value();
result = Either.left(updatedResourceValue);
- if (log.isDebugEnabled()) {
- // String json = prettyJson.toJson(result.left().value());
- // log.debug("Resource retrieved after update is {}", json);
- }
-
return result;
-
} finally {
if (false == inTransaction) {
@@ -2883,4 +2825,139 @@ public abstract class ComponentOperation {
}
}
}
+
+ private boolean updateServiceNameInVLIsNetworkRolePropertyValues (Component component, String prevSystemName, String newSystemName) {
+ // find VLIs in service
+ boolean res = true;
+ if(null == component.getComponentInstances() || component.getComponentInstances().isEmpty()){
+ return res;
+ }
+
+ List <ComponentInstance> vlInstances =
+ component.getComponentInstances().stream()
+ .filter(p -> OriginTypeEnum.VL == p.getOriginType())
+ .collect(Collectors.toList());
+ if (!vlInstances.isEmpty()) {
+ for (ComponentInstance vlInstance : vlInstances){
+ // find network_role property
+ Optional <ComponentInstanceProperty> networkRoleProperty = component.getComponentInstancesProperties().get(vlInstance.getUniqueId()).stream()
+ .filter(p -> PropertyNames.NETWORK_ROLE.getPropertyName().equalsIgnoreCase(p.getName()))
+ .findAny();
+ res = res && updateNetworkRolePropertyValue(prevSystemName, newSystemName, vlInstance, networkRoleProperty);
+ }
+ }
+ return res;
+ }
+
+ private boolean updateNetworkRolePropertyValue(String prevSystemName, String newSystemName, ComponentInstance vlInstance, Optional<ComponentInstanceProperty> networkRoleProperty) {
+ if (networkRoleProperty.isPresent() && !StringUtils.isEmpty(networkRoleProperty.get().getValue()) ) {
+ ComponentInstanceProperty property = networkRoleProperty.get();
+ String updatedValue = property.getValue().replaceFirst(prevSystemName, newSystemName);
+ property.setValue(updatedValue);
+ StorageOperationStatus updateCustomizationUUID;
+ //disregard property value rule
+ property.setRules(null);
+ Either<ComponentInstanceProperty, StorageOperationStatus> result = componentInstanceOperation.updatePropertyValueInResourceInstance(property, vlInstance.getUniqueId(), true);
+ if (result.isLeft()) {
+ log.debug("Property value {} was updated on graph.", property.getValueUniqueUid());
+ updateCustomizationUUID = componentInstanceOperation.updateCustomizationUUID(vlInstance.getUniqueId());
+ } else {
+ updateCustomizationUUID = StorageOperationStatus.EXEUCTION_FAILED;
+ log.debug("Failed to update property value: {} in resource instance {}", updatedValue, vlInstance.getUniqueId());
+ }
+ return result.isLeft() && StorageOperationStatus.OK == updateCustomizationUUID;
+ }
+ return true;
+ }
+
+ public Either<ComponentMetadataData, StorageOperationStatus> updateComponentLastUpdateDateAndLastModifierOnGraph( Component component, User modifier, NodeTypeEnum componentType, boolean inTransaction) {
+
+ log.debug("Going to update last update date and last modifier info of component {}. ", component.getName());
+ Either<ComponentMetadataData, StorageOperationStatus> result = null;
+ try{
+ String modifierUserId = modifier.getUserId();
+ ComponentMetadataData componentData = getMetaDataFromComponent(component);
+ String currentUser = component.getLastUpdaterUserId();
+ UserData modifierUserData = new UserData();
+ modifierUserData.setUserId(modifierUserId);
+ if (currentUser.equals(modifierUserId)) {
+ log.debug("Graph last modifier edge should not be changed since the modifier is the same as the last modifier.");
+ } else {
+ log.debug("Going to update the last modifier user of the component from {} to {}", currentUser, modifierUserId);
+ StorageOperationStatus status = moveLastModifierEdge(component, componentData, modifierUserData, componentType);
+ log.debug("Finish to update the last modifier user of the resource from {} to {}. status is {}", currentUser, modifierUserId, status);
+ if (status != StorageOperationStatus.OK) {
+ result = Either.right(status);
+ }
+ }
+ Either<ComponentMetadataData, TitanOperationStatus> updateNode = null;
+ if(result == null){
+ log.debug("Going to update the component {} with new last update date. ", component.getName());
+ componentData.getMetadataDataDefinition().setLastUpdateDate(System.currentTimeMillis());
+ updateNode = titanGenericDao.updateNode(componentData, ComponentMetadataData.class);
+ if (updateNode.isRight()) {
+ log.error("Failed to update component {}. status is {}", component.getUniqueId(), updateNode.right().value());
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateNode.right().value()));
+ }
+ }
+ if(result == null){
+ result = Either.left(updateNode.left().value());
+ }
+ }catch(Exception e){
+ log.error("Exception occured during update last update date and last modifier info of component {}. The message is {}. ", component.getName(), e.getMessage());
+ }finally {
+ if(!inTransaction){
+ if (result == null || result.isRight()) {
+ log.error("Going to execute rollback on graph.");
+ titanGenericDao.rollback();
+ } else {
+ log.debug("Going to execute commit on graph.");
+ titanGenericDao.commit();
+ }
+ }
+ }
+ return result;
+ }
+ /**
+ * updates component lastUpdateDate on graph node
+ * @param component
+ * @param componentType
+ * @param lastUpdateDate
+ * @param inTransaction
+ * @return
+ */
+ public Either<ComponentMetadataData, StorageOperationStatus> updateComponentLastUpdateDateOnGraph( Component component, NodeTypeEnum componentType, Long lastUpdateDate, boolean inTransaction) {
+
+ log.debug("Going to update last update date of component {}. ", component.getName());
+ Either<ComponentMetadataData, StorageOperationStatus> result = null;
+ try{
+ ComponentMetadataData componentData = getMetaDataFromComponent(component);
+ Either<ComponentMetadataData, TitanOperationStatus> updateNode = null;
+ if(result == null){
+ log.debug("Going to update the component {} with new last update date. ", component.getName());
+ componentData.getMetadataDataDefinition().setLastUpdateDate(lastUpdateDate);
+ updateNode = titanGenericDao.updateNode(componentData, ComponentMetadataData.class);
+ if (updateNode.isRight()) {
+ log.error("Failed to update component {}. status is {}", component.getUniqueId(), updateNode.right().value());
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateNode.right().value()));
+ }
+ }
+ if(result == null){
+ result = Either.left(updateNode.left().value());
+ }
+ }catch(Exception e){
+ log.error("Exception occured during update last update date of component {}. The message is {}. ", component.getName(), e.getMessage());
+ }finally {
+ if(!inTransaction){
+ if (result == null || result.isRight()) {
+ log.error("Going to execute rollback on graph.");
+ titanGenericDao.rollback();
+ } else {
+ log.debug("Going to execute commit on graph.");
+ titanGenericDao.commit();
+ }
+ }
+ }
+ return result;
+ }
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ConsumerOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ConsumerOperation.java
index aafa4ba444..215a1464a6 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ConsumerOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ConsumerOperation.java
@@ -46,11 +46,11 @@ public class ConsumerOperation implements IConsumerOperation {
@Override
public Either<ConsumerData, StorageOperationStatus> getCredentials(String consumerName) {
Either<ConsumerData, StorageOperationStatus> result = null;
- log.debug("retriving Credentials for: {}.", consumerName);
+ log.debug("retriving Credentials for: {}", consumerName);
Either<ConsumerData, TitanOperationStatus> getNode = titanGenericDao.getNode(GraphPropertiesDictionary.CONSUMER_NAME.getProperty(), consumerName, ConsumerData.class);
if (getNode.isRight()) {
TitanOperationStatus status = getNode.right().value();
- log.error("Error returned after get Consumer Data node " + consumerName + ". status returned is " + status);
+ log.error("Error returned after get Consumer Data node {}. status returned is {}", consumerName, status);
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
return result;
}
@@ -67,11 +67,11 @@ public class ConsumerOperation implements IConsumerOperation {
public Either<ConsumerData, StorageOperationStatus> createCredentials(ConsumerData consumerData, boolean inTransaction) {
Either<ConsumerData, StorageOperationStatus> result = null;
try {
- log.debug("creating Credentials for: {}.", consumerData.getUniqueId());
+ log.debug("creating Credentials for: {}", consumerData.getUniqueId());
Either<ConsumerData, TitanOperationStatus> createNode = titanGenericDao.createNode(consumerData, ConsumerData.class);
if (createNode.isRight()) {
TitanOperationStatus status = createNode.right().value();
- log.error("Error returned after creating Consumer Data node " + consumerData.getUniqueId() + ". status returned is " + status);
+ log.error("Error returned after creating Consumer Data node {}. status returned is {}", consumerData.getUniqueId(), status);
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
return result;
}
@@ -96,7 +96,7 @@ public class ConsumerOperation implements IConsumerOperation {
Either<ConsumerData, TitanOperationStatus> deleteNode = titanGenericDao.deleteNode(GraphPropertiesDictionary.CONSUMER_NAME.getProperty(), consumerName, ConsumerData.class);
if (deleteNode.isRight()) {
TitanOperationStatus status = deleteNode.right().value();
- log.error("Error returned after delete Consumer Data node {}. Status returned is {}", consumerName, status);
+ log.error("Error returned after delete Consumer Data node {}. status returned is {}", consumerName, status);
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
return result;
}
@@ -120,11 +120,11 @@ public class ConsumerOperation implements IConsumerOperation {
Either<ConsumerData, StorageOperationStatus> result = null;
try {
- log.debug("update Credentials for: {}.", consumerData.getUniqueId());
+ log.debug("update Credentials for: {}", consumerData.getUniqueId());
Either<ConsumerData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(consumerData, ConsumerData.class);
if (updateNode.isRight()) {
TitanOperationStatus status = updateNode.right().value();
- log.error("Error returned after delete Consumer Data node {}. Status returned is {}", consumerData.getUniqueId(), status);
+ log.error("Error returned after delete Consumer Data node {}. status returned is {}", consumerData.getUniqueId(), status);
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
return result;
}
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 1420ce08d8..815eb5be0e 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
@@ -61,7 +61,6 @@ public class CsarOperation {
}
- // Mock returning a file from the file system until we have API from onboarding
public Either<Map<String, byte[]>, StorageOperationStatus> getMockCsar(String csarUuid) {
File dir = new File("/var/tmp/mockCsar");
FileFilter fileFilter = new WildcardFileFilter("*.csar");
@@ -93,11 +92,10 @@ public class CsarOperation {
*/
public Either<Map<String, byte[]>, StorageOperationStatus> getCsar(String csarUuid, User user) {
- Either<Map<String, byte[]>, StorageOperationStatus> result = onboardingClient.getCsar(csarUuid,
- user.getUserId());
+ Either<Map<String, byte[]>, StorageOperationStatus> result = onboardingClient.getCsar(csarUuid, user.getUserId());
if (result.isRight()) {
- log.debug("Cannot find csar {}. Status returned is {}", csarUuid, result.right().value());
+ log.debug("Cannot find csar {}. Staus returned is {}", csarUuid, result.right().value());
} else {
Map<String, byte[]> values = result.left().value();
if (values != null) {
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/DaoStatusConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/DaoStatusConverter.java
index b887c5b212..260763cced 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/DaoStatusConverter.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/DaoStatusConverter.java
@@ -100,8 +100,7 @@ public class DaoStatusConverter {
}
- public static StorageOperationStatus convertRsrcUploadStatusToStorageStatus(
- ResourceUploadStatus resourceUploadStatus) {
+ public static StorageOperationStatus convertRsrcUploadStatusToStorageStatus(ResourceUploadStatus resourceUploadStatus) {
if (resourceUploadStatus == null) {
return StorageOperationStatus.GENERAL_ERROR;
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ElementOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ElementOperation.java
index 248a1d0460..ea42c6d76b 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ElementOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ElementOperation.java
@@ -29,7 +29,7 @@ import java.util.Map;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.openecomp.sdc.be.config.ConfigurationManager;
-import org.openecomp.sdc.be.config.Configuration.DeploymentArtifactTypeConfig;
+import org.openecomp.sdc.be.config.Configuration.ArtifactTypeConfig;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
@@ -55,8 +55,10 @@ import org.openecomp.sdc.be.resources.data.TagData;
import org.openecomp.sdc.be.resources.data.category.CategoryData;
import org.openecomp.sdc.be.resources.data.category.GroupingData;
import org.openecomp.sdc.be.resources.data.category.SubCategoryData;
+import org.openecomp.sdc.common.util.ValidationUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import com.thinkaurelius.titan.core.TitanGraph;
@@ -68,11 +70,11 @@ import fj.data.Either;
@Component("element-operation")
public class ElementOperation implements IElementOperation {
- @javax.annotation.Resource
private TitanGenericDao titanGenericDao;
- public ElementOperation() {
+ public ElementOperation(@Qualifier("titan-generic-dao") TitanGenericDao titanGenericDao) {
super();
+ this.titanGenericDao = titanGenericDao;
}
private static Logger log = LoggerFactory.getLogger(ElementOperation.class.getName());
@@ -107,15 +109,13 @@ public class ElementOperation implements IElementOperation {
}
@Override
- public Either<CategoryDefinition, ActionStatus> createCategory(CategoryDefinition category, NodeTypeEnum nodeType,
- boolean inTransaction) {
+ public Either<CategoryDefinition, ActionStatus> createCategory(CategoryDefinition category, NodeTypeEnum nodeType, boolean inTransaction) {
Either<CategoryDefinition, ActionStatus> result = null;
category.setUniqueId(UniqueIdBuilder.buildCategoryUid(category.getNormalizedName(), nodeType));
CategoryData categoryData = new CategoryData(nodeType, category);
try {
- Either<CategoryData, TitanOperationStatus> createNode = titanGenericDao.createNode(categoryData,
- CategoryData.class);
+ Either<CategoryData, TitanOperationStatus> createNode = titanGenericDao.createNode(categoryData, CategoryData.class);
if (createNode.isRight()) {
TitanOperationStatus value = createNode.right().value();
ActionStatus actionStatus = ActionStatus.GENERAL_ERROR;
@@ -141,21 +141,18 @@ public class ElementOperation implements IElementOperation {
}
@Override
- public Either<SubCategoryDefinition, ActionStatus> createSubCategory(String categoryId,
- SubCategoryDefinition subCategory, NodeTypeEnum nodeType) {
+ public Either<SubCategoryDefinition, ActionStatus> createSubCategory(String categoryId, SubCategoryDefinition subCategory, NodeTypeEnum nodeType) {
return createSubCategory(categoryId, subCategory, nodeType, false);
}
@Override
- public Either<SubCategoryDefinition, ActionStatus> createSubCategory(String categoryId,
- SubCategoryDefinition subCategory, NodeTypeEnum nodeType, boolean inTransaction) {
+ public Either<SubCategoryDefinition, ActionStatus> createSubCategory(String categoryId, SubCategoryDefinition subCategory, NodeTypeEnum nodeType, boolean inTransaction) {
Either<SubCategoryDefinition, ActionStatus> result = null;
try {
// create edge from category to sub-category
- Either<CategoryData, TitanOperationStatus> categoryNode = titanGenericDao
- .getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), categoryId, CategoryData.class);
+ Either<CategoryData, TitanOperationStatus> categoryNode = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), categoryId, CategoryData.class);
ActionStatus actionStatus = ActionStatus.GENERAL_ERROR;
if (categoryNode.isRight()) {
TitanOperationStatus titanOperationStatus = categoryNode.right().value();
@@ -168,12 +165,10 @@ public class ElementOperation implements IElementOperation {
}
CategoryDataDefinition categoryDataDefinition = categoryNode.left().value().getCategoryDataDefinition();
- subCategory.setUniqueId(UniqueIdBuilder.buildSubCategoryUid(categoryDataDefinition.getUniqueId(),
- subCategory.getNormalizedName()));
+ subCategory.setUniqueId(UniqueIdBuilder.buildSubCategoryUid(categoryDataDefinition.getUniqueId(), subCategory.getNormalizedName()));
SubCategoryData subCategoryData = new SubCategoryData(nodeType, subCategory);
- Either<SubCategoryData, TitanOperationStatus> subCategoryNode = titanGenericDao.createNode(subCategoryData,
- SubCategoryData.class);
+ Either<SubCategoryData, TitanOperationStatus> subCategoryNode = titanGenericDao.createNode(subCategoryData, SubCategoryData.class);
if (subCategoryNode.isRight()) {
TitanOperationStatus titanOperationStatus = subCategoryNode.right().value();
log.debug("Problem while creating category, reason {}", titanOperationStatus);
@@ -184,15 +179,13 @@ public class ElementOperation implements IElementOperation {
return result;
}
- Either<GraphRelation, TitanOperationStatus> relation = titanGenericDao.createRelation(
- categoryNode.left().value(), subCategoryNode.left().value(), GraphEdgeLabels.SUB_CATEGORY, null);
+ Either<GraphRelation, TitanOperationStatus> relation = titanGenericDao.createRelation(categoryNode.left().value(), subCategoryNode.left().value(), GraphEdgeLabels.SUB_CATEGORY, null);
if (relation.isRight()) {
log.debug("Problem while create relation between category and sub-category ", relation.right().value());
result = Either.right(actionStatus);
return result;
}
- SubCategoryDefinition subCategoryCreated = new SubCategoryDefinition(
- subCategoryNode.left().value().getSubCategoryDataDefinition());
+ SubCategoryDefinition subCategoryCreated = new SubCategoryDefinition(subCategoryNode.left().value().getSubCategoryDataDefinition());
result = Either.left(subCategoryCreated);
return result;
} finally {
@@ -207,15 +200,13 @@ public class ElementOperation implements IElementOperation {
}
@Override
- public Either<GroupingDefinition, ActionStatus> createGrouping(String subCategoryId, GroupingDefinition grouping,
- NodeTypeEnum nodeType) {
+ public Either<GroupingDefinition, ActionStatus> createGrouping(String subCategoryId, GroupingDefinition grouping, NodeTypeEnum nodeType) {
Either<GroupingDefinition, ActionStatus> result = null;
try {
// create edge from sub-category to grouping
- Either<SubCategoryData, TitanOperationStatus> subCategoryNode = titanGenericDao
- .getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), subCategoryId, SubCategoryData.class);
+ Either<SubCategoryData, TitanOperationStatus> subCategoryNode = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), subCategoryId, SubCategoryData.class);
ActionStatus actionStatus = ActionStatus.GENERAL_ERROR;
if (subCategoryNode.isRight()) {
TitanOperationStatus titanOperationStatus = subCategoryNode.right().value();
@@ -228,12 +219,10 @@ public class ElementOperation implements IElementOperation {
}
SubCategoryDataDefinition subCatData = subCategoryNode.left().value().getSubCategoryDataDefinition();
- grouping.setUniqueId(
- UniqueIdBuilder.buildGroupingUid(subCatData.getUniqueId(), grouping.getNormalizedName()));
+ grouping.setUniqueId(UniqueIdBuilder.buildGroupingUid(subCatData.getUniqueId(), grouping.getNormalizedName()));
GroupingData groupingData = new GroupingData(nodeType, grouping);
- Either<GroupingData, TitanOperationStatus> groupingNode = titanGenericDao.createNode(groupingData,
- GroupingData.class);
+ Either<GroupingData, TitanOperationStatus> groupingNode = titanGenericDao.createNode(groupingData, GroupingData.class);
if (groupingNode.isRight()) {
TitanOperationStatus titanOperationStatus = groupingNode.right().value();
log.debug("Problem while creating grouping, reason {}", titanOperationStatus);
@@ -244,15 +233,13 @@ public class ElementOperation implements IElementOperation {
return result;
}
- Either<GraphRelation, TitanOperationStatus> relation = titanGenericDao.createRelation(
- subCategoryNode.left().value(), groupingNode.left().value(), GraphEdgeLabels.GROUPING, null);
+ Either<GraphRelation, TitanOperationStatus> relation = titanGenericDao.createRelation(subCategoryNode.left().value(), groupingNode.left().value(), GraphEdgeLabels.GROUPING, null);
if (relation.isRight()) {
log.debug("Problem while create relation between sub-category and grouping", relation.right().value());
result = Either.right(actionStatus);
return result;
}
- GroupingDefinition groupingCreated = new GroupingDefinition(
- groupingNode.left().value().getGroupingDataDefinition());
+ GroupingDefinition groupingCreated = new GroupingDefinition(groupingNode.left().value().getGroupingDataDefinition());
result = Either.left(groupingCreated);
return result;
} finally {
@@ -265,17 +252,14 @@ public class ElementOperation implements IElementOperation {
}
@Override
- public Either<List<CategoryDefinition>, ActionStatus> getAllCategories(NodeTypeEnum nodeType,
- boolean inTransaction) {
+ public Either<List<CategoryDefinition>, ActionStatus> getAllCategories(NodeTypeEnum nodeType, boolean inTransaction) {
try {
- if (nodeType != NodeTypeEnum.ResourceNewCategory && nodeType != NodeTypeEnum.ServiceNewCategory
- && nodeType != NodeTypeEnum.ProductCategory) {
+ if (nodeType != NodeTypeEnum.ResourceNewCategory && nodeType != NodeTypeEnum.ServiceNewCategory && nodeType != NodeTypeEnum.ProductCategory) {
log.debug("Unknown category type {}", nodeType.name());
return Either.right(ActionStatus.GENERAL_ERROR);
}
- Either<List<org.openecomp.sdc.be.resources.data.category.CategoryData>, TitanOperationStatus> either = titanGenericDao
- .getAll(nodeType, org.openecomp.sdc.be.resources.data.category.CategoryData.class);
+ Either<List<org.openecomp.sdc.be.resources.data.category.CategoryData>, TitanOperationStatus> either = titanGenericDao.getAll(nodeType, org.openecomp.sdc.be.resources.data.category.CategoryData.class);
if (either.isRight() && (either.right().value() != TitanOperationStatus.NOT_FOUND)) {
log.debug("Problem while get all categories. reason - {}", either.right().value());
return Either.right(ActionStatus.GENERAL_ERROR);
@@ -291,8 +275,7 @@ public class ElementOperation implements IElementOperation {
log.trace("Found category {}, category type {}", categoryName, nodeType);
TitanOperationStatus setSubCategories = setSubCategories(nodeType, categoryDefinition);
if (setSubCategories != TitanOperationStatus.OK) {
- log.debug("Failed to set sub-categories for category {}, category type {}, error {}",
- categoryName, nodeType, setSubCategories);
+ log.debug("Failed to set sub-categories for category {}, category type {}, error {}", categoryName, nodeType, setSubCategories);
return Either.right(ActionStatus.GENERAL_ERROR);
}
categoryList.add(categoryDefinition);
@@ -311,14 +294,12 @@ public class ElementOperation implements IElementOperation {
if (childNodeType != null) {
String categoryName = parentCategory.getName();
log.trace("Getting sub-categories for category {}, category type {}", categoryName, parentNodeType);
- Either<List<ImmutablePair<SubCategoryData, GraphEdge>>, TitanOperationStatus> parentNode = titanGenericDao
- .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(parentNodeType), parentCategory.getUniqueId(),
- GraphEdgeLabels.SUB_CATEGORY, childNodeType, SubCategoryData.class);
+ Either<List<ImmutablePair<SubCategoryData, GraphEdge>>, TitanOperationStatus> parentNode = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(parentNodeType), parentCategory.getUniqueId(), GraphEdgeLabels.SUB_CATEGORY,
+ childNodeType, SubCategoryData.class);
if (parentNode.isRight()) {
TitanOperationStatus titanOperationStatus = parentNode.right().value();
if (titanOperationStatus == TitanOperationStatus.NOT_FOUND) {
- log.trace("Didn't find subcategories for category {}, category type {}", categoryName,
- parentNodeType);
+ log.trace("Didn't find subcategories for category {}, category type {}", categoryName, parentNodeType);
titanOperationStatus = TitanOperationStatus.OK;
}
return titanOperationStatus;
@@ -326,16 +307,13 @@ public class ElementOperation implements IElementOperation {
List<ImmutablePair<SubCategoryData, GraphEdge>> subsCategoriesData = parentNode.left().value();
List<SubCategoryDefinition> subCategoriesDefinitions = new ArrayList<>();
for (ImmutablePair<SubCategoryData, GraphEdge> subCatPair : subsCategoriesData) {
- SubCategoryDataDefinition subCategoryDataDefinition = subCatPair.getLeft()
- .getSubCategoryDataDefinition();
+ SubCategoryDataDefinition subCategoryDataDefinition = subCatPair.getLeft().getSubCategoryDataDefinition();
SubCategoryDefinition subCategoryDefinition = new SubCategoryDefinition(subCategoryDataDefinition);
- log.trace("Found sub-category {} for category {}, category type {}",
- subCategoryDataDefinition.getName(), categoryName, parentNodeType);
+ log.trace("Found sub-category {} for category {}, category type {}", subCategoryDataDefinition.getName(), categoryName, parentNodeType);
TitanOperationStatus setGroupings = setGroupings(childNodeType, subCategoryDefinition);
if (setGroupings != TitanOperationStatus.OK) {
- log.debug("Failed to set groupings for sub-category {}, sub-category type {}, error {}",
- subCategoryDataDefinition.getName(), childNodeType, setGroupings);
+ log.debug("Failed to set groupings for sub-category {}, sub-category type {}, error {}", subCategoryDataDefinition.getName(), childNodeType, setGroupings);
return TitanOperationStatus.GENERAL_ERROR;
}
subCategoriesDefinitions.add(subCategoryDefinition);
@@ -350,14 +328,12 @@ public class ElementOperation implements IElementOperation {
if (childNodeType != null) {
String subCategoryName = parentSubCategory.getName();
log.trace("Getting groupings for subcategory {}, subcategory type {}", subCategoryName, parentNodeType);
- Either<List<ImmutablePair<GroupingData, GraphEdge>>, TitanOperationStatus> parentNode = titanGenericDao
- .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(parentNodeType), parentSubCategory.getUniqueId(),
- GraphEdgeLabels.GROUPING, childNodeType, GroupingData.class);
+ Either<List<ImmutablePair<GroupingData, GraphEdge>>, TitanOperationStatus> parentNode = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(parentNodeType), parentSubCategory.getUniqueId(), GraphEdgeLabels.GROUPING,
+ childNodeType, GroupingData.class);
if (parentNode.isRight()) {
TitanOperationStatus titanOperationStatus = parentNode.right().value();
if (titanOperationStatus == TitanOperationStatus.NOT_FOUND) {
- log.trace("Didn't find groupings for subcategory {}, subcategory type {}", subCategoryName,
- parentNodeType);
+ log.trace("Didn't find groupings for subcategory {}, subcategory type {}", subCategoryName, parentNodeType);
titanOperationStatus = TitanOperationStatus.OK;
}
return titanOperationStatus;
@@ -366,8 +342,7 @@ public class ElementOperation implements IElementOperation {
List<GroupingDefinition> groupingDefinitions = new ArrayList<>();
for (ImmutablePair<GroupingData, GraphEdge> groupPair : groupingData) {
GroupingDataDefinition groupingDataDefinition = groupPair.getLeft().getGroupingDataDefinition();
- log.trace("Found grouping {} for sub-category {}, sub-category type {}",
- groupingDataDefinition.getName(), subCategoryName, parentNodeType);
+ log.trace("Found grouping {} for sub-category {}, sub-category type {}", groupingDataDefinition.getName(), subCategoryName, parentNodeType);
groupingDefinitions.add(new GroupingDefinition(groupingDataDefinition));
}
parentSubCategory.setGroupings(groupingDefinitions);
@@ -396,14 +371,12 @@ public class ElementOperation implements IElementOperation {
@Override
public Either<CategoryDefinition, ActionStatus> getCategory(NodeTypeEnum nodeType, String categoryId) {
try {
- if (nodeType != NodeTypeEnum.ResourceNewCategory && nodeType != NodeTypeEnum.ServiceNewCategory
- && nodeType != NodeTypeEnum.ProductCategory) {
+ if (nodeType != NodeTypeEnum.ResourceNewCategory && nodeType != NodeTypeEnum.ServiceNewCategory && nodeType != NodeTypeEnum.ProductCategory) {
log.debug("Unknown category type {}", nodeType.name());
return Either.right(ActionStatus.GENERAL_ERROR);
}
- Either<CategoryData, TitanOperationStatus> categoryDataEither = titanGenericDao
- .getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), categoryId, CategoryData.class);
+ Either<CategoryData, TitanOperationStatus> categoryDataEither = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), categoryId, CategoryData.class);
if (categoryDataEither.isRight()) {
TitanOperationStatus titanOperationStatus = categoryDataEither.right().value();
log.debug("Problem while get category by id {}. reason {}", categoryId, titanOperationStatus);
@@ -412,8 +385,7 @@ public class ElementOperation implements IElementOperation {
}
return Either.right(ActionStatus.GENERAL_ERROR);
}
- CategoryDataDefinition categoryDataDefinition = categoryDataEither.left().value()
- .getCategoryDataDefinition();
+ CategoryDataDefinition categoryDataDefinition = categoryDataEither.left().value().getCategoryDataDefinition();
return Either.left(new CategoryDefinition(categoryDataDefinition));
} finally {
titanGenericDao.commit();
@@ -428,8 +400,7 @@ public class ElementOperation implements IElementOperation {
return Either.right(ActionStatus.GENERAL_ERROR);
}
- Either<SubCategoryData, TitanOperationStatus> subCategoryDataEither = titanGenericDao
- .getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), subCategoryId, SubCategoryData.class);
+ Either<SubCategoryData, TitanOperationStatus> subCategoryDataEither = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), subCategoryId, SubCategoryData.class);
if (subCategoryDataEither.isRight()) {
TitanOperationStatus titanOperationStatus = subCategoryDataEither.right().value();
log.debug("Problem while get sub-category by id {}. reason {}", subCategoryId, titanOperationStatus);
@@ -438,8 +409,7 @@ public class ElementOperation implements IElementOperation {
}
return Either.right(ActionStatus.GENERAL_ERROR);
}
- SubCategoryDataDefinition subCategoryDataDefinition = subCategoryDataEither.left().value()
- .getSubCategoryDataDefinition();
+ SubCategoryDataDefinition subCategoryDataDefinition = subCategoryDataEither.left().value().getSubCategoryDataDefinition();
return Either.left(new SubCategoryDefinition(subCategoryDataDefinition));
} finally {
titanGenericDao.commit();
@@ -450,14 +420,12 @@ public class ElementOperation implements IElementOperation {
public Either<CategoryDefinition, ActionStatus> deleteCategory(NodeTypeEnum nodeType, String categoryId) {
Either<CategoryDefinition, ActionStatus> result = null;
try {
- if (nodeType != NodeTypeEnum.ResourceNewCategory && nodeType != NodeTypeEnum.ServiceNewCategory
- && nodeType != NodeTypeEnum.ProductCategory) {
+ if (nodeType != NodeTypeEnum.ResourceNewCategory && nodeType != NodeTypeEnum.ServiceNewCategory && nodeType != NodeTypeEnum.ProductCategory) {
log.debug("Unknown category type {}", nodeType.name());
result = Either.right(ActionStatus.GENERAL_ERROR);
return result;
}
- Either<CategoryData, TitanOperationStatus> categoryDataEither = titanGenericDao
- .getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), categoryId, CategoryData.class);
+ Either<CategoryData, TitanOperationStatus> categoryDataEither = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), categoryId, CategoryData.class);
if (categoryDataEither.isRight()) {
log.debug("Failed to retrieve category for id {} ", categoryId);
result = Either.right(ActionStatus.GENERAL_ERROR);
@@ -473,8 +441,7 @@ public class ElementOperation implements IElementOperation {
TitanGraph tGraph = graph.left().value();
- Iterable<TitanVertex> verticesArtifact = tGraph.query()
- .has(UniqueIdBuilder.getKeyByNodeType(nodeType), categoryId).vertices();
+ Iterable<TitanVertex> verticesArtifact = tGraph.query().has(UniqueIdBuilder.getKeyByNodeType(nodeType), categoryId).vertices();
Iterator<TitanVertex> iterator = verticesArtifact.iterator();
if (!iterator.hasNext()) {
log.debug("No category node for id = {}", categoryId);
@@ -483,8 +450,7 @@ public class ElementOperation implements IElementOperation {
}
Vertex artifactV = iterator.next();
artifactV.remove();
- CategoryDefinition deleted = new CategoryDefinition(
- categoryDataEither.left().value().getCategoryDataDefinition());
+ CategoryDefinition deleted = new CategoryDefinition(categoryDataEither.left().value().getCategoryDataDefinition());
result = Either.left(deleted);
return result;
} finally {
@@ -505,8 +471,7 @@ public class ElementOperation implements IElementOperation {
result = Either.right(ActionStatus.GENERAL_ERROR);
return result;
}
- Either<SubCategoryData, TitanOperationStatus> subCategoryDataEither = titanGenericDao
- .getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), subCategoryId, SubCategoryData.class);
+ Either<SubCategoryData, TitanOperationStatus> subCategoryDataEither = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), subCategoryId, SubCategoryData.class);
if (subCategoryDataEither.isRight()) {
log.debug("Failed to retrieve sub-category for id {}", subCategoryId);
result = Either.right(ActionStatus.GENERAL_ERROR);
@@ -522,8 +487,7 @@ public class ElementOperation implements IElementOperation {
TitanGraph tGraph = graph.left().value();
- Iterable<TitanVertex> verticesArtifact = tGraph.query()
- .has(UniqueIdBuilder.getKeyByNodeType(nodeType), subCategoryId).vertices();
+ Iterable<TitanVertex> verticesArtifact = tGraph.query().has(UniqueIdBuilder.getKeyByNodeType(nodeType), subCategoryId).vertices();
Iterator<TitanVertex> iterator = verticesArtifact.iterator();
if (!iterator.hasNext()) {
log.debug("No sub-category node for id {}", subCategoryId);
@@ -533,8 +497,7 @@ public class ElementOperation implements IElementOperation {
Vertex artifactV = iterator.next();
artifactV.remove();
;
- SubCategoryDefinition deleted = new SubCategoryDefinition(
- subCategoryDataEither.left().value().getSubCategoryDataDefinition());
+ SubCategoryDefinition deleted = new SubCategoryDefinition(subCategoryDataEither.left().value().getSubCategoryDataDefinition());
result = Either.left(deleted);
return result;
} finally {
@@ -556,8 +519,7 @@ public class ElementOperation implements IElementOperation {
result = Either.right(ActionStatus.GENERAL_ERROR);
return result;
}
- Either<GroupingData, TitanOperationStatus> groupingDataEither = titanGenericDao
- .getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), groupingId, GroupingData.class);
+ Either<GroupingData, TitanOperationStatus> groupingDataEither = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), groupingId, GroupingData.class);
if (groupingDataEither.isRight()) {
log.debug("Failed to retrieve grouping for id {}", groupingId);
result = Either.right(ActionStatus.GENERAL_ERROR);
@@ -573,8 +535,7 @@ public class ElementOperation implements IElementOperation {
TitanGraph tGraph = graph.left().value();
- Iterable<TitanVertex> verticesArtifact = tGraph.query()
- .has(UniqueIdBuilder.getKeyByNodeType(nodeType), groupingId).vertices();
+ Iterable<TitanVertex> verticesArtifact = tGraph.query().has(UniqueIdBuilder.getKeyByNodeType(nodeType), groupingId).vertices();
Iterator<TitanVertex> iterator = verticesArtifact.iterator();
if (!iterator.hasNext()) {
log.debug("No grouping node for id {}", groupingId);
@@ -584,8 +545,7 @@ public class ElementOperation implements IElementOperation {
Vertex artifactV = iterator.next();
artifactV.remove();
;
- GroupingDefinition deleted = new GroupingDefinition(
- groupingDataEither.left().value().getGroupingDataDefinition());
+ GroupingDefinition deleted = new GroupingDefinition(groupingDataEither.left().value().getGroupingDataDefinition());
result = Either.left(deleted);
return result;
} finally {
@@ -603,25 +563,21 @@ public class ElementOperation implements IElementOperation {
Map<String, Object> properties = new HashMap<>();
properties.put(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(), normalizedName);
try {
- Either<List<CategoryData>, TitanOperationStatus> categoryEither = titanGenericDao.getByCriteria(nodeType,
- properties, CategoryData.class);
+ Either<List<CategoryData>, TitanOperationStatus> categoryEither = titanGenericDao.getByCriteria(nodeType, properties, CategoryData.class);
if (categoryEither.isRight() && categoryEither.right().value() != TitanOperationStatus.NOT_FOUND) {
- log.debug("Failed to get categories, nodeType {}, normalizedName {}, error {}", nodeType,
- normalizedName, categoryEither.right().value());
+ log.debug("Failed to get categories, nodeType {}, normalizedName {}, error {}", nodeType, normalizedName, categoryEither.right().value());
return Either.right(ActionStatus.GENERAL_ERROR);
}
List<CategoryData> categoryList = (categoryEither.isLeft() ? categoryEither.left().value() : null);
if (categoryList != null && categoryList.size() > 0) {
log.debug("Found category for nodeType {} with normalizedName {}", nodeType, normalizedName);
if (categoryList.size() > 1) {
- log.debug("Found more than 1 unique categories for nodeType {} with normalizedName", nodeType,
- normalizedName);
+ log.debug("Found more than 1 unique categories for nodeType {} with normalizedName", nodeType, normalizedName);
return Either.right(ActionStatus.GENERAL_ERROR);
}
return Either.left(false);
} else {
- log.debug("Category for nodeType {} with normalizedName {} doesn't exist in graph", nodeType,
- normalizedName);
+ log.debug("Category for nodeType {} with normalizedName {} doesn't exist in graph", nodeType, normalizedName);
return Either.left(true);
}
} finally {
@@ -630,21 +586,16 @@ public class ElementOperation implements IElementOperation {
}
@Override
- public Either<Boolean, ActionStatus> isSubCategoryUniqueForCategory(NodeTypeEnum nodeType,
- String subCategoryNormName, String parentCategoryId) {
+ public Either<Boolean, ActionStatus> isSubCategoryUniqueForCategory(NodeTypeEnum nodeType, String subCategoryNormName, String parentCategoryId) {
String subCategoryId = UniqueIdBuilder.buildSubCategoryUid(parentCategoryId, subCategoryNormName);
try {
- Either<SubCategoryData, TitanOperationStatus> subCategoryDataEither = titanGenericDao
- .getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), subCategoryId, SubCategoryData.class);
- if (subCategoryDataEither.isRight()
- && subCategoryDataEither.right().value() != TitanOperationStatus.NOT_FOUND) {
- log.debug("Failed to get sub-category with id {}, error {}", subCategoryId,
- subCategoryDataEither.right().value());
+ Either<SubCategoryData, TitanOperationStatus> subCategoryDataEither = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), subCategoryId, SubCategoryData.class);
+ if (subCategoryDataEither.isRight() && subCategoryDataEither.right().value() != TitanOperationStatus.NOT_FOUND) {
+ log.debug("Failed to get sub-category with id {}, error {}", subCategoryId, subCategoryDataEither.right().value());
return Either.right(ActionStatus.GENERAL_ERROR);
}
- SubCategoryData subCategoryData = (subCategoryDataEither.isLeft() ? subCategoryDataEither.left().value()
- : null);
+ SubCategoryData subCategoryData = (subCategoryDataEither.isLeft() ? subCategoryDataEither.left().value() : null);
if (subCategoryData != null) {
log.debug("Found sub-category with id {}", subCategoryId);
return Either.left(false);
@@ -658,16 +609,13 @@ public class ElementOperation implements IElementOperation {
}
@Override
- public Either<Boolean, ActionStatus> isGroupingUniqueForSubCategory(NodeTypeEnum nodeType, String groupingNormName,
- String parentSubCategoryId) {
+ public Either<Boolean, ActionStatus> isGroupingUniqueForSubCategory(NodeTypeEnum nodeType, String groupingNormName, String parentSubCategoryId) {
String groupingId = UniqueIdBuilder.buildGroupingUid(parentSubCategoryId, groupingNormName);
try {
- Either<GroupingData, TitanOperationStatus> groupingDataEither = titanGenericDao
- .getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), groupingId, GroupingData.class);
+ Either<GroupingData, TitanOperationStatus> groupingDataEither = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), groupingId, GroupingData.class);
if (groupingDataEither.isRight() && groupingDataEither.right().value() != TitanOperationStatus.NOT_FOUND) {
- log.debug("Failed to get grouping with id {}, error {}", groupingId,
- groupingDataEither.right().value());
+ log.debug("Failed to get grouping with id {}, error {}", groupingId, groupingDataEither.right().value());
return Either.right(ActionStatus.GENERAL_ERROR);
}
GroupingData groupingData = (groupingDataEither.isLeft() ? groupingDataEither.left().value() : null);
@@ -684,29 +632,23 @@ public class ElementOperation implements IElementOperation {
}
@Override
- public Either<SubCategoryDefinition, ActionStatus> getSubCategoryUniqueForType(NodeTypeEnum nodeType,
- String normalizedName) {
+ public Either<SubCategoryDefinition, ActionStatus> getSubCategoryUniqueForType(NodeTypeEnum nodeType, String normalizedName) {
Map<String, Object> properties = new HashMap<>();
properties.put(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(), normalizedName);
try {
- Either<List<SubCategoryData>, TitanOperationStatus> subCategoryEither = titanGenericDao
- .getByCriteria(nodeType, properties, SubCategoryData.class);
+ Either<List<SubCategoryData>, TitanOperationStatus> subCategoryEither = titanGenericDao.getByCriteria(nodeType, properties, SubCategoryData.class);
if (subCategoryEither.isRight() && subCategoryEither.right().value() != TitanOperationStatus.NOT_FOUND) {
- log.debug("Failed to get sub-categories, nodeType {}, normalizedName {}, error {}", nodeType,
- normalizedName, subCategoryEither.right().value());
+ log.debug("Failed to get sub-categories, nodeType {}, normalizedName {}, error {}", nodeType, normalizedName, subCategoryEither.right().value());
return Either.right(ActionStatus.GENERAL_ERROR);
}
- List<SubCategoryData> subCategoryList = (subCategoryEither.isLeft() ? subCategoryEither.left().value()
- : null);
+ List<SubCategoryData> subCategoryList = (subCategoryEither.isLeft() ? subCategoryEither.left().value() : null);
if (subCategoryList != null && subCategoryList.size() > 0) {
log.debug("Found sub-category for nodeType {} with normalizedName {}", nodeType, normalizedName);
SubCategoryData subCategoryData = subCategoryList.get(0);
- SubCategoryDefinition subCategoryDefinition = new SubCategoryDefinition(
- subCategoryData.getSubCategoryDataDefinition());
+ SubCategoryDefinition subCategoryDefinition = new SubCategoryDefinition(subCategoryData.getSubCategoryDataDefinition());
return Either.left(subCategoryDefinition);
} else {
- log.debug("Sub-category for nodeType {} with normalizedName {} doesn't exist in graph", nodeType,
- normalizedName);
+ log.debug("Sub-category for nodeType {} with normalizedName {} doesn't exist in graph", nodeType, normalizedName);
return Either.left(null);
}
} finally {
@@ -715,28 +657,23 @@ public class ElementOperation implements IElementOperation {
}
@Override
- public Either<GroupingDefinition, ActionStatus> getGroupingUniqueForType(NodeTypeEnum nodeType,
- String groupingNormalizedName) {
+ public Either<GroupingDefinition, ActionStatus> getGroupingUniqueForType(NodeTypeEnum nodeType, String groupingNormalizedName) {
Map<String, Object> properties = new HashMap<>();
properties.put(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(), groupingNormalizedName);
try {
- Either<List<GroupingData>, TitanOperationStatus> groupingEither = titanGenericDao.getByCriteria(nodeType,
- properties, GroupingData.class);
+ Either<List<GroupingData>, TitanOperationStatus> groupingEither = titanGenericDao.getByCriteria(nodeType, properties, GroupingData.class);
if (groupingEither.isRight() && groupingEither.right().value() != TitanOperationStatus.NOT_FOUND) {
- log.debug("Failed to get grouping, nodeType {}, normalizedName {}, error {}", nodeType,
- groupingNormalizedName, groupingEither.right().value());
+ log.debug("Failed to get grouping, nodeType {}, normalizedName {}, error {}", nodeType, groupingNormalizedName, groupingEither.right().value());
return Either.right(ActionStatus.GENERAL_ERROR);
}
List<GroupingData> groupingList = (groupingEither.isLeft() ? groupingEither.left().value() : null);
if (groupingList != null && groupingList.size() > 0) {
log.debug("Found grouping for nodeType {} with normalizedName {}", nodeType, groupingNormalizedName);
GroupingData groupingData = groupingList.get(0);
- GroupingDefinition groupingDefinition = new GroupingDefinition(
- groupingData.getGroupingDataDefinition());
+ GroupingDefinition groupingDefinition = new GroupingDefinition(groupingData.getGroupingDataDefinition());
return Either.left(groupingDefinition);
} else {
- log.debug("Grouping for nodeType {} with normalizedName {} doesn't exist in graph", nodeType,
- groupingNormalizedName);
+ log.debug("Grouping for nodeType {} with normalizedName {} doesn't exist in graph", nodeType, groupingNormalizedName);
return Either.left(null);
}
} finally {
@@ -751,8 +688,7 @@ public class ElementOperation implements IElementOperation {
@Override
public Either<List<Tag>, ActionStatus> getAllTags() {
try {
- Either<List<TagData>, TitanOperationStatus> either = titanGenericDao.getAll(NodeTypeEnum.Tag,
- TagData.class);
+ Either<List<TagData>, TitanOperationStatus> either = titanGenericDao.getAll(NodeTypeEnum.Tag, TagData.class);
if (either.isRight()) {
log.debug("Problem while get all tags. reason - {}", either.right().value());
return Either.right(ActionStatus.GENERAL_ERROR);
@@ -766,8 +702,7 @@ public class ElementOperation implements IElementOperation {
}
@Override
- public <T extends GraphNode> Either<org.openecomp.sdc.be.resources.data.CategoryData, StorageOperationStatus> getCategoryData(
- String name, NodeTypeEnum type, Class<T> clazz) {
+ public <T extends GraphNode> Either<org.openecomp.sdc.be.resources.data.CategoryData, StorageOperationStatus> getCategoryData(String name, NodeTypeEnum type, Class<T> clazz) {
if (name != null) {
String categoryUid = null;
if (type == NodeTypeEnum.ResourceCategory) {
@@ -779,8 +714,7 @@ public class ElementOperation implements IElementOperation {
} else {
categoryUid = UniqueIdBuilder.buildServiceCategoryUid(name, type);
}
- Either<T, TitanOperationStatus> either = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(type),
- categoryUid, clazz);
+ Either<T, TitanOperationStatus> either = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(type), categoryUid, clazz);
if (either.isRight()) {
TitanOperationStatus titanOperationStatus = either.right().value();
@@ -827,8 +761,7 @@ public class ElementOperation implements IElementOperation {
public Either<List<ArtifactType>, ActionStatus> getAllArtifactTypes() {
List<ArtifactType> artifactTypes = new ArrayList<ArtifactType>();
- List<String> artifactTypesList = ConfigurationManager.getConfigurationManager().getConfiguration()
- .getArtifactTypes();
+ List<String> artifactTypesList = ConfigurationManager.getConfigurationManager().getConfiguration().getArtifactTypes();
for (String artifactType : artifactTypesList) {
ArtifactType artifactT = new ArtifactType();
artifactT.setName(artifactType);
@@ -841,12 +774,9 @@ public class ElementOperation implements IElementOperation {
public Either<Map<String, Object>, ActionStatus> getAllDeploymentArtifactTypes() {
Map<String, Object> artifactTypes = new HashMap<String, Object>();
- Map<String, DeploymentArtifactTypeConfig> artifactResourceTypes = ConfigurationManager.getConfigurationManager()
- .getConfiguration().getResourceDeploymentArtifacts();
- Map<String, DeploymentArtifactTypeConfig> artifactServiceTypes = ConfigurationManager.getConfigurationManager()
- .getConfiguration().getServiceDeploymentArtifacts();
- Map<String, DeploymentArtifactTypeConfig> artifactResourceInstanceTypes = ConfigurationManager
- .getConfigurationManager().getConfiguration().getResourceInstanceDeploymentArtifacts();
+ Map<String, ArtifactTypeConfig> artifactResourceTypes = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts();
+ Map<String, ArtifactTypeConfig> artifactServiceTypes = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceDeploymentArtifacts();
+ Map<String, ArtifactTypeConfig> artifactResourceInstanceTypes = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInstanceDeploymentArtifacts();
artifactTypes.put("resourceDeploymentArtifacts", artifactResourceTypes);
artifactTypes.put("serviceDeploymentArtifacts", artifactServiceTypes);
@@ -858,8 +788,7 @@ public class ElementOperation implements IElementOperation {
@Override
public Either<Integer, ActionStatus> getDefaultHeatTimeout() {
- return Either.left(ConfigurationManager.getConfigurationManager().getConfiguration()
- .getDefaultHeatArtifactTimeoutMinutes());
+ return Either.left(ConfigurationManager.getConfigurationManager().getConfiguration().getDefaultHeatArtifactTimeoutMinutes());
}
@Override
@@ -876,12 +805,11 @@ public class ElementOperation implements IElementOperation {
}
@Override
- public <T extends GraphNode> Either<CategoryData, StorageOperationStatus> getNewCategoryData(String name,
- NodeTypeEnum type, Class<T> clazz) {
+ public <T extends GraphNode> Either<CategoryData, StorageOperationStatus> getNewCategoryData(String name, NodeTypeEnum type, Class<T> clazz) {
if (name != null) {
String categoryUid = UniqueIdBuilder.buildServiceCategoryUid(name, type);
Map props = new HashMap<>();
- props.put(GraphPropertiesDictionary.NAME.getProperty(), name);
+ props.put(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(), ValidationUtils.normalizeCategoryName4Uniqueness(name));
Either<List<T>, TitanOperationStatus> either = titanGenericDao.getByCriteria(type, props, clazz);
if (either.isRight()) {
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GraphLockOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GraphLockOperation.java
index 35541e6d46..89f8f71e2a 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GraphLockOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GraphLockOperation.java
@@ -25,6 +25,7 @@ import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.model.Resource;
+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.IGraphLockOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
@@ -32,6 +33,7 @@ import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
import org.openecomp.sdc.be.resources.data.ResourceMetadataData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import fj.data.Either;
@@ -42,9 +44,9 @@ public class GraphLockOperation implements IGraphLockOperation {
@javax.annotation.Resource
private TitanGenericDao titanGenericDao;
-
- @javax.annotation.Resource
- private ResourceOperation resourceOperation;
+
+ @Autowired
+ ToscaOperationFacade toscaOperationFacade;
@javax.annotation.Resource
private ICacheMangerOperation cacheManagerOperation;
@@ -56,9 +58,7 @@ public class GraphLockOperation implements IGraphLockOperation {
/*
* (non-Javadoc)
*
- * @see org.openecomp.sdc.be.model.operations.impl.IGraphLockOperation#
- * lockResource(java.lang.String,
- * org.openecomp.sdc.be.model.operations.api.IResourceOperation)
+ * @see org.openecomp.sdc.be.model.operations.impl.IGraphLockOperation# lockResource(java.lang.String, org.openecomp.sdc.be.model.operations.api.IResourceOperation)
*/
@Override
public StorageOperationStatus lockComponent(String componentId, NodeTypeEnum nodeType) {
@@ -70,14 +70,13 @@ public class GraphLockOperation implements IGraphLockOperation {
// In this way we mark the component as updated one (and component
// won't be fetched from cache since the component in cache has
// different timestamp)
- Either<ComponentMetadataData, TitanOperationStatus> updateTime = updateModificationTimeOfComponent(
- componentId, nodeType);
- if (updateTime.isRight()) {
- TitanOperationStatus operationStatus = updateTime.right().value();
- if (operationStatus != TitanOperationStatus.OK) {
- return DaoStatusConverter.convertTitanStatusToStorageStatus(operationStatus);
- }
- }
+// Either<ComponentMetadataData, TitanOperationStatus> updateTime = updateModificationTimeOfComponent(componentId, nodeType);
+// if (updateTime.isRight()) {
+// TitanOperationStatus operationStatus = updateTime.right().value();
+// if (operationStatus != TitanOperationStatus.OK) {
+// return DaoStatusConverter.convertTitanStatusToStorageStatus(operationStatus);
+// }
+// }
lockElementStatus = titanGenericDao.lockElement(componentId, nodeType);
@@ -97,24 +96,21 @@ public class GraphLockOperation implements IGraphLockOperation {
* @param nodeType
* @return
*/
- private Either<ComponentMetadataData, TitanOperationStatus> updateModificationTimeOfComponent(String componentId,
- NodeTypeEnum nodeType) {
+ private Either<ComponentMetadataData, TitanOperationStatus> updateModificationTimeOfComponent(String componentId, NodeTypeEnum nodeType) {
if (nodeType == NodeTypeEnum.Resource || nodeType == NodeTypeEnum.Service || nodeType == NodeTypeEnum.Product) {
// We fetch all node since update only timestamp make problems since
// there is default resource type (VFC) which changes component
// resource type when we update only timestamp(ResourceMetadataData
// contains default value VFC on resourceType field).
- Either<ComponentMetadataData, TitanOperationStatus> findComp = titanGenericDao
- .getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId, ComponentMetadataData.class);
+ Either<ComponentMetadataData, TitanOperationStatus> findComp = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId, ComponentMetadataData.class);
if (findComp.isRight()) {
return Either.right(findComp.right().value());
}
ComponentMetadataData componentMetadataData = findComp.left().value();
componentMetadataData.getMetadataDataDefinition().setLastUpdateDate(System.currentTimeMillis());
- Either<ComponentMetadataData, TitanOperationStatus> updateNode = titanGenericDao
- .updateNode(componentMetadataData, ComponentMetadataData.class);
+ Either<ComponentMetadataData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(componentMetadataData, ComponentMetadataData.class);
return updateNode;
}
return Either.right(TitanOperationStatus.OK);
@@ -123,23 +119,20 @@ public class GraphLockOperation implements IGraphLockOperation {
/*
* (non-Javadoc)
*
- * @see org.openecomp.sdc.be.model.operations.impl.IGraphLockOperation#
- * unlockResource(java.lang.String,
- * org.openecomp.sdc.be.model.operations.api.IResourceOperation)
+ * @see org.openecomp.sdc.be.model.operations.impl.IGraphLockOperation# unlockResource(java.lang.String, org.openecomp.sdc.be.model.operations.api.IResourceOperation)
*/
@Override
public StorageOperationStatus unlockComponent(String componentId, NodeTypeEnum nodeType) {
- Either<Long, StorageOperationStatus> addComponentToCachePart1 = addComponentToCachePart1WithoutCommit(
- componentId, nodeType);
+// Either<Long, StorageOperationStatus> addComponentToCachePart1 = addComponentToCachePart1WithoutCommit(componentId, nodeType);
TitanOperationStatus lockElementStatus = titanGenericDao.releaseElement(componentId, nodeType);
- if (addComponentToCachePart1.isLeft()) {
- Long lastUpdateDate = addComponentToCachePart1.left().value();
- addComponentToCachePart2(componentId, lastUpdateDate, nodeType);
- }
-
+// if (addComponentToCachePart1.isLeft()) {
+// Long lastUpdateDate = addComponentToCachePart1.left().value();
+// addComponentToCachePart2(componentId, lastUpdateDate, nodeType);
+// }
+//
return DaoStatusConverter.convertTitanStatusToStorageStatus(lockElementStatus);
}
@@ -151,15 +144,14 @@ public class GraphLockOperation implements IGraphLockOperation {
@Override
public StorageOperationStatus unlockComponentByName(String name, String componentId, NodeTypeEnum nodeType) {
- Either<Long, StorageOperationStatus> addComponentToCachePart1 = addComponentToCachePart1WithoutCommit(
- componentId, nodeType);
+// Either<Long, StorageOperationStatus> addComponentToCachePart1 = addComponentToCachePart1WithoutCommit(componentId, nodeType);
TitanOperationStatus lockElementStatus = titanGenericDao.releaseElement(name, nodeType);
-
- if (addComponentToCachePart1.isLeft()) {
- Long lastUpdateDate = addComponentToCachePart1.left().value();
- addComponentToCachePart2(componentId, lastUpdateDate, nodeType);
- }
+//
+// if (addComponentToCachePart1.isLeft()) {
+// Long lastUpdateDate = addComponentToCachePart1.left().value();
+// addComponentToCachePart2(componentId, lastUpdateDate, nodeType);
+// }
return DaoStatusConverter.convertTitanStatusToStorageStatus(lockElementStatus);
}
@@ -171,15 +163,12 @@ public class GraphLockOperation implements IGraphLockOperation {
* @param nodeType
* @return
*/
- private Either<Long, StorageOperationStatus> addComponentToCachePart1WithoutCommit(String componentId,
- NodeTypeEnum nodeType) {
+ private Either<Long, StorageOperationStatus> addComponentToCachePart1WithoutCommit(String componentId, NodeTypeEnum nodeType) {
if (componentId != null) { // In case of error, the componentId might be
// empty.
- if (nodeType == NodeTypeEnum.Resource || nodeType == NodeTypeEnum.Service
- || nodeType == NodeTypeEnum.Product) {
+ if (nodeType == NodeTypeEnum.Resource || nodeType == NodeTypeEnum.Service || nodeType == NodeTypeEnum.Product) {
Long lastUpdateDate = null;
- Either<ComponentMetadataData, StorageOperationStatus> resResult = resourceOperation
- .getComponentByLabelAndId(componentId, nodeType, ComponentMetadataData.class);
+ Either<ComponentMetadataData, StorageOperationStatus> resResult = toscaOperationFacade.getComponentMetadata(componentId);
if (resResult.isLeft()) {
ComponentMetadataData resourceMetadataData = resResult.left().value();
lastUpdateDate = resourceMetadataData.getMetadataDataDefinition().getLastUpdateDate();
@@ -201,12 +190,10 @@ public class GraphLockOperation implements IGraphLockOperation {
* @param nodeType
* @return
*/
- private Either<Long, StorageOperationStatus> addComponentToCachePart2(String componentId, Long lastUpdateDate,
- NodeTypeEnum nodeType) {
+ private Either<Long, StorageOperationStatus> addComponentToCachePart2(String componentId, Long lastUpdateDate, NodeTypeEnum nodeType) {
if (componentId != null) { // In case of error, the componentId might be
// empty.
- if (nodeType == NodeTypeEnum.Resource || nodeType == NodeTypeEnum.Service
- || nodeType == NodeTypeEnum.Product) {
+ if (nodeType == NodeTypeEnum.Resource || nodeType == NodeTypeEnum.Service || nodeType == NodeTypeEnum.Product) {
// add task to Q
log.debug("Going to add component {} of type {} to cache", componentId, nodeType.name().toLowerCase());
cacheManagerOperation.updateComponentInCache(componentId, lastUpdateDate, nodeType);
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupInstanceOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupInstanceOperation.java
new file mode 100644
index 0000000000..bd57689700
--- /dev/null
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupInstanceOperation.java
@@ -0,0 +1,1701 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.model.operations.impl;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.function.Supplier;
+import java.util.stream.Collectors;
+
+import org.apache.commons.collections.CollectionUtils;
+import org.apache.commons.collections.MapUtils;
+import org.apache.commons.lang.StringUtils;
+import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.apache.tinkerpop.gremlin.structure.Direction;
+import org.apache.tinkerpop.gremlin.structure.Edge;
+import org.apache.tinkerpop.gremlin.structure.Vertex;
+import org.apache.tinkerpop.gremlin.structure.VertexProperty;
+import org.openecomp.sdc.be.config.BeEcompErrorManager;
+import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
+import org.openecomp.sdc.be.dao.graph.GraphElementFactory;
+import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
+import org.openecomp.sdc.be.dao.graph.datatype.GraphElementTypeEnum;
+import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
+import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation;
+import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
+
+import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
+import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.openecomp.sdc.be.dao.utils.Constants;
+import org.openecomp.sdc.be.datatypes.elements.GroupInstanceDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+
+import org.openecomp.sdc.be.model.ArtifactDefinition;
+
+import org.openecomp.sdc.be.model.ComponentInstance;
+
+import org.openecomp.sdc.be.model.ComponentInstanceProperty;
+import org.openecomp.sdc.be.model.DataTypeDefinition;
+import org.openecomp.sdc.be.model.GroupDefinition;
+import org.openecomp.sdc.be.model.GroupInstance;
+import org.openecomp.sdc.be.model.GroupInstanceProperty;
+import org.openecomp.sdc.be.model.GroupProperty;
+import org.openecomp.sdc.be.model.GroupTypeDefinition;
+import org.openecomp.sdc.be.model.IComponentInstanceConnectedElement;
+import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
+import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+
+import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
+import org.openecomp.sdc.be.resources.data.ArtifactData;
+import org.openecomp.sdc.be.resources.data.AttributeValueData;
+import org.openecomp.sdc.be.resources.data.ComponentInstanceData;
+import org.openecomp.sdc.be.resources.data.GroupData;
+import org.openecomp.sdc.be.resources.data.GroupInstanceData;
+import org.openecomp.sdc.be.resources.data.PropertyData;
+import org.openecomp.sdc.be.resources.data.PropertyValueData;
+import org.openecomp.sdc.be.resources.data.UniqueIdData;
+import org.openecomp.sdc.common.datastructure.Wrapper;
+import org.openecomp.sdc.common.util.ValidationUtils;
+import org.openecomp.sdc.exception.ResponseFormat;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+
+import com.thinkaurelius.titan.core.TitanGraph;
+import com.thinkaurelius.titan.core.TitanVertex;
+
+import fj.data.Either;
+
+@org.springframework.stereotype.Component("group-instance-operation")
+public class GroupInstanceOperation extends AbstractOperation implements IGroupInstanceOperation {
+
+ private static String ADDING_GROUP = "AddingGroupInstance";
+
+ private static Logger log = LoggerFactory.getLogger(GroupInstanceOperation.class.getName());
+
+ @Autowired
+ TitanGenericDao titanGenericDao;
+ @Autowired
+ GroupOperation groupOperation;
+
+ @Autowired
+ PropertyOperation propertyOperation;
+
+ @javax.annotation.Resource
+ private ApplicationDataTypeCache dataTypeCache;
+
+ @Override
+ public Either<GroupInstance, StorageOperationStatus> createGroupInstance(String componentInstId, GroupInstance groupInstance, boolean isCreateLogicalName) {
+ Either<GroupInstance, StorageOperationStatus> result = null;
+
+ if (!ValidationUtils.validateStringNotEmpty(groupInstance.getCustomizationUUID())) {
+ generateCustomizationUUID(groupInstance);
+ }
+
+ Either<GroupInstance, TitanOperationStatus> addRes = addGroupInstanceToComponentInstance(componentInstId, isCreateLogicalName, groupInstance);
+ if (addRes.isRight()) {
+ TitanOperationStatus status = addRes.right().value();
+ log.error("Failed to add resource instance {} to service {}. status is {}", groupInstance, componentInstId, status);
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ return result;
+ }
+
+ GroupInstance value = addRes.left().value();
+ result = Either.left(value);
+
+ return result;
+
+ }
+
+ @Override
+ public Either<GroupInstance, StorageOperationStatus> createGroupInstance(TitanVertex ciVertex, String componentInstId, GroupInstance groupInstance, boolean isCreateLogicalName) {
+ Either<GroupInstance, StorageOperationStatus> result = null;
+
+ if (!ValidationUtils.validateStringNotEmpty(groupInstance.getCustomizationUUID())) {
+ generateCustomizationUUID(groupInstance);
+ }
+
+ Either<TitanVertex, TitanOperationStatus> addComponentInstanceToContainerComponent = addGroupInstanceToContainerComponent(ciVertex, componentInstId, isCreateLogicalName, groupInstance);
+
+ if (addComponentInstanceToContainerComponent.isRight()) {
+ TitanOperationStatus status = addComponentInstanceToContainerComponent.right().value();
+ if (status == TitanOperationStatus.NOT_FOUND) {
+ status = TitanOperationStatus.INVALID_ID;
+ }
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ TitanVertex giVertex = addComponentInstanceToContainerComponent.left().value();
+ Map<String, Object> properties = titanGenericDao.getProperties(giVertex);
+ GroupInstanceData createdGroupInstanceData = GraphElementFactory.createElement(NodeTypeEnum.GroupInstance.getName(), GraphElementTypeEnum.Node, properties, GroupInstanceData.class);
+
+ GroupInstance createdGroupInstance = new GroupInstance(createdGroupInstanceData.getGroupDataDefinition());
+ createdGroupInstance.setGroupName(groupInstance.getGroupName());
+
+ createdGroupInstance.setArtifacts(groupInstance.getArtifacts());
+
+ result = Either.left(createdGroupInstance);
+
+ return result;
+
+ }
+
+ @Override
+ public Either<GroupInstance, StorageOperationStatus> deleteGroupInstanceInstance(NodeTypeEnum containerNodeType, String containerComponentId, String groupInstUid) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public Either<GroupInstance, StorageOperationStatus> updateGroupInstance(String serviceId, NodeTypeEnum nodeType, String resourceInstanceName, ComponentInstance resourceInstance) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public Either<List<GroupInstance>, StorageOperationStatus> getAllGroupInstances(String parentId, NodeTypeEnum parentType) {
+ Either<List<GroupInstance>, StorageOperationStatus> result = null;
+ List<GroupInstance> groupInstanceRes = new ArrayList<>();
+
+ Either<TitanGraph, TitanOperationStatus> graph = titanGenericDao.getGraph();
+ if (graph.isRight()) {
+ log.debug("Failed to work with graph {}", graph.right().value());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graph.right().value()));
+ }
+ TitanGraph tGraph = graph.left().value();
+ @SuppressWarnings("unchecked")
+ Iterable<TitanVertex> vertices = tGraph.query().has(UniqueIdBuilder.getKeyByNodeType(parentType), parentId).vertices();
+ if (vertices == null || vertices.iterator() == null || false == vertices.iterator().hasNext()) {
+ log.debug("No nodes for type {} for id = {}", parentType, parentId);
+ result = Either.right(StorageOperationStatus.NOT_FOUND);
+ return result;
+ }
+
+ Iterator<TitanVertex> iterator = vertices.iterator();
+ Vertex vertex = iterator.next();
+
+ Map<String, Object> edgeProperties = null;
+
+ Either<List<ImmutablePair<GroupInstanceData, GraphEdge>>, TitanOperationStatus> childrenByEdgeCriteria = titanGenericDao.getChildrenByEdgeCriteria(vertex, parentId, GraphEdgeLabels.GROUP_INST, NodeTypeEnum.GroupInstance,
+ GroupInstanceData.class, edgeProperties);
+
+ if (childrenByEdgeCriteria.isRight()) {
+ TitanOperationStatus status = childrenByEdgeCriteria.right().value();
+ log.debug("Failed to find group instance {} on graph", childrenByEdgeCriteria.right().value());
+
+ if (status == TitanOperationStatus.NOT_FOUND) {
+ result = Either.left(groupInstanceRes);
+ return result;
+ }
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+
+ }
+
+ List<ImmutablePair<GroupInstanceData, GraphEdge>> list = childrenByEdgeCriteria.left().value();
+
+ for (ImmutablePair<GroupInstanceData, GraphEdge> pair : list) {
+ GroupInstanceData groupInstData = pair.getLeft();
+ GroupInstance groupInstance = new GroupInstance(groupInstData.getGroupDataDefinition());
+ String instOriginGroupId = groupInstance.getGroupUid();
+ Either<GroupDefinition, TitanOperationStatus> groupRes = groupOperation.getGroupFromGraph(instOriginGroupId, false, true, false);
+
+ if (groupRes.isRight()) {
+ TitanOperationStatus status = groupRes.right().value();
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+
+ }
+ GroupDefinition groupDefinition = groupRes.left().value();
+ Either<Map<String, PropertyValueData>, TitanOperationStatus> groupInstancePropertyValuesRes = getAllGroupInstancePropertyValuesData(groupInstData);
+ if(groupInstancePropertyValuesRes.isRight()){
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(groupInstancePropertyValuesRes.right().value()));
+ }
+ buildGroupInstanceFromGroup(groupInstance, groupDefinition, groupInstancePropertyValuesRes.left().value());
+ /*
+ * Either<List<GroupProperty>, TitanOperationStatus> groupInsPropStatus = getGroupInstanceProperties(groupInstance, groupDefinition); if (groupInsPropStatus.isRight()) {
+ *
+ * return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(groupInsPropStatus.right().value())); }
+ */
+
+ Either<List<ImmutablePair<String, String>>, TitanOperationStatus> artifactsRes = getGroupArtifactsPairs(groupInstance.getUniqueId());
+ if (artifactsRes.isRight()) {
+ TitanOperationStatus status = artifactsRes.right().value();
+ if (status != TitanOperationStatus.OK) {
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ return result;
+ }
+ } else {
+ List<String> artifactsUid = new ArrayList<>();
+ List<String> artifactsUUID = new ArrayList<>();
+
+ List<ImmutablePair<String, String>> list1 = artifactsRes.left().value();
+ if (list != null) {
+ for (ImmutablePair<String, String> pair1 : list1) {
+ String uid = pair1.left;
+ String UUID = pair1.right;
+ artifactsUid.add(uid);
+ artifactsUUID.add(UUID);
+ }
+ groupInstance.setGroupInstanceArtifacts(artifactsUid);
+ groupInstance.setGroupInstanceArtifactsUuid(artifactsUUID);
+ }
+ }
+
+ groupInstanceRes.add(groupInstance);
+ log.debug("GroupInstance {} was added to list ", groupInstance.getUniqueId());
+ }
+
+ result = Either.left(groupInstanceRes);
+ return result;
+
+ }
+
+ @Override
+ public Either<GroupInstance, TitanOperationStatus> getGroupInstanceById(String groupResourceId) {
+ // TODO Auto-generated method stub
+ return getGroupInstanceFromGraph(groupResourceId, false, false);
+ }
+
+ @Override
+ public TitanOperationStatus deleteAllGroupInstances(String componentInstId) {
+
+ return deleteAssociatedGroupInstances(componentInstId);
+ }
+
+ private TitanOperationStatus deleteAssociatedGroupInstances(String resourceInstanceUid) {
+ final GraphEdgeLabels edgeConectingToRI = GraphEdgeLabels.GROUP_INST;
+ final NodeTypeEnum elementTypeToDelete = NodeTypeEnum.GroupInstance;
+ return deleteAssociatedRIElements(elementTypeToDelete, edgeConectingToRI, resourceInstanceUid, () -> GroupInstanceData.class);
+ }
+
+ private <T extends GraphNode> TitanOperationStatus deleteAssociatedRIElements(NodeTypeEnum elementTypeToDelete, GraphEdgeLabels edgeConectingToRI, String resourceInstanceUid, Supplier<Class<T>> classGen) {
+
+ Either<List<ImmutablePair<T, GraphEdge>>, TitanOperationStatus> elementsNodesRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceUid, edgeConectingToRI, elementTypeToDelete,
+ classGen.get());
+
+ if (elementsNodesRes.isRight()) {
+ TitanOperationStatus status = elementsNodesRes.right().value();
+ if (status != TitanOperationStatus.NOT_FOUND) {
+ BeEcompErrorManager.getInstance().logInternalFlowError("deleteAssociatedRIElements", "Failed to find the elements of resource instance " + resourceInstanceUid + ". status is " + status, ErrorSeverity.ERROR);
+ return status;
+ }
+ } else {
+
+ List<ImmutablePair<T, GraphEdge>> relationshipNodes = elementsNodesRes.left().value();
+ if (relationshipNodes != null) {
+ for (ImmutablePair<T, GraphEdge> immutablePair : relationshipNodes) {
+ T elementValueDataData = immutablePair.getKey();
+ Either<T, TitanOperationStatus> deleteNode = titanGenericDao.deleteNode(elementValueDataData, classGen.get());
+ if (deleteNode.isRight()) {
+ TitanOperationStatus status = deleteNode.right().value();
+ BeEcompErrorManager.getInstance().logInternalFlowError("deleteAssociatedRIElements", "Failed to delete element value node " + elementValueDataData + ". status is " + status, ErrorSeverity.ERROR);
+ return status;
+ }
+ }
+ }
+
+ }
+
+ return TitanOperationStatus.OK;
+ }
+
+ @Override
+ public Either<Integer, StorageOperationStatus> increaseAndGetGroupInstancePropertyCounter(String groupInstanceId) {
+ Either<Integer, StorageOperationStatus> result = null;
+
+ Either<TitanGraph, TitanOperationStatus> graphResult = titanGenericDao.getGraph();
+ if (graphResult.isRight()) {
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graphResult.right().value()));
+ return result;
+ }
+ Either<TitanVertex, TitanOperationStatus> vertexService = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.GroupInstance), groupInstanceId);
+ if (vertexService.isRight()) {
+ log.debug("failed to fetch vertex of resource instance for id = {}", groupInstanceId);
+ TitanOperationStatus status = vertexService.right().value();
+ if (status == TitanOperationStatus.NOT_FOUND) {
+ status = TitanOperationStatus.INVALID_ID;
+ }
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexService.right().value()));
+ return result;
+ }
+ Vertex vertex = vertexService.left().value();
+
+ VertexProperty<Object> vertexProperty = vertex.property(GraphPropertiesDictionary.PROPERTY_COUNTER.getProperty());
+ Integer counter = 0;
+ if (vertexProperty.isPresent()) {
+ if (vertexProperty.value() != null) {
+ counter = (Integer) vertexProperty.value();
+ }
+ }
+
+ counter++;
+ vertex.property(GraphPropertiesDictionary.PROPERTY_COUNTER.getProperty(), counter);
+
+ result = Either.left(counter);
+ return result;
+
+ }
+
+ @Override
+ public Either<Boolean, StorageOperationStatus> isGroupInstanceNameExist(String parentComponentId, NodeTypeEnum parentNodeType, String compInstId, String componentInstName) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public Either<ComponentInstance, StorageOperationStatus> getFullGroupInstance(ComponentInstance componentInstance, NodeTypeEnum compInstNodeType) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public Either<ComponentInstanceProperty, StorageOperationStatus> addPropertyValueToGroupInstance(ComponentInstanceProperty groupInstanceProperty, String groupInstanceId, Integer index, boolean inTransaction) {
+ /// #RULES SUPPORT
+ /// Ignore rules received from client till support
+ groupInstanceProperty.setRules(null);
+ ///
+ ///
+
+ Either<ComponentInstanceProperty, StorageOperationStatus> result = null;
+
+ try {
+
+ Either<PropertyValueData, TitanOperationStatus> eitherStatus = addPropertyToGroupInstance(groupInstanceProperty, groupInstanceId, index);
+
+ if (eitherStatus.isRight()) {
+ log.error("Failed to add property value {} to resource instance {} in Graph. status is {}", groupInstanceProperty, groupInstanceId, eitherStatus.right().value().name());
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(eitherStatus.right().value()));
+ return result;
+ } else {
+ PropertyValueData propertyValueData = eitherStatus.left().value();
+
+ ComponentInstanceProperty propertyValueResult = propertyOperation.buildResourceInstanceProperty(propertyValueData, groupInstanceProperty);
+ log.debug("The returned GroupInstanceProperty is {}", propertyValueResult);
+
+ Either<String, TitanOperationStatus> findDefaultValue = propertyOperation.findDefaultValueFromSecondPosition(groupInstanceProperty.getPath(), groupInstanceProperty.getUniqueId(), groupInstanceProperty.getDefaultValue());
+ if (findDefaultValue.isRight()) {
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(findDefaultValue.right().value()));
+ return result;
+ }
+ String defaultValue = findDefaultValue.left().value();
+ propertyValueResult.setDefaultValue(defaultValue);
+ log.debug("The returned default value in ResourceInstanceProperty is {}", defaultValue);
+
+ result = Either.left(propertyValueResult);
+ return result;
+ }
+ }
+
+ finally {
+ if (false == inTransaction) {
+ if (result == null || result.isRight()) {
+ log.error("Going to execute rollback on graph.");
+ titanGenericDao.rollback();
+ } else {
+ log.debug("Going to execute commit on graph.");
+ titanGenericDao.commit();
+ }
+ }
+ }
+
+ }
+
+ @Override
+ public Either<ComponentInstanceProperty, StorageOperationStatus> addPropertyValueToGroupInstance(ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId, boolean isvalidate, Integer index, boolean inTransaction) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public Either<ComponentInstanceProperty, StorageOperationStatus> updatePropertyValueInGroupInstance(ComponentInstanceProperty gropuInstanceProperty, String groupInstanceId, boolean inTransaction) {
+ // TODO Auto-generated method stub
+ // change Propety class
+ return null;
+ }
+
+ @Override
+ public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> fetchCIEnvArtifacts(String componentInstanceId) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public StorageOperationStatus updateCustomizationUUID(String groupInstanceId) {
+ Either<TitanVertex, TitanOperationStatus> vertexByProperty = titanGenericDao.getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), groupInstanceId);
+ if (vertexByProperty.isRight()) {
+ log.debug("Failed to fetch component instance by id {} error {}", groupInstanceId, vertexByProperty.right().value());
+ return DaoStatusConverter.convertTitanStatusToStorageStatus(vertexByProperty.right().value());
+ }
+ UUID uuid = UUID.randomUUID();
+ TitanVertex ciVertex = vertexByProperty.left().value();
+ ciVertex.property(GraphPropertiesDictionary.CUSTOMIZATION_UUID.getProperty(), uuid.toString());
+
+ return StorageOperationStatus.OK;
+ }
+
+ public void generateCustomizationUUID(GroupInstance groupInstance) {
+ UUID uuid = UUID.randomUUID();
+ groupInstance.setCustomizationUUID(uuid.toString());
+ }
+
+ /**
+ * add property to resource instance
+ *
+ * @param resourceInstanceProperty
+ * @param resourceInstanceId
+ * @param index
+ * @return
+ */
+ public Either<PropertyValueData, TitanOperationStatus> addPropertyToGroupInstance(ComponentInstanceProperty groupInstanceProperty, String groupInstanceId, Integer index) {
+
+ Either<GroupInstanceData, TitanOperationStatus> findResInstanceRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.GroupInstance), groupInstanceId, GroupInstanceData.class);
+
+ if (findResInstanceRes.isRight()) {
+ TitanOperationStatus status = findResInstanceRes.right().value();
+ if (status == TitanOperationStatus.NOT_FOUND) {
+ status = TitanOperationStatus.INVALID_ID;
+ }
+ return Either.right(status);
+ }
+
+ String propertyId = groupInstanceProperty.getUniqueId();
+ Either<PropertyData, TitanOperationStatus> findPropertyDefRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Property), propertyId, PropertyData.class);
+
+ if (findPropertyDefRes.isRight()) {
+ TitanOperationStatus status = findPropertyDefRes.right().value();
+ if (status == TitanOperationStatus.NOT_FOUND) {
+ status = TitanOperationStatus.INVALID_ID;
+ }
+ return Either.right(status);
+ }
+
+ String valueUniqueUid = groupInstanceProperty.getValueUniqueUid();
+ if (valueUniqueUid == null) {
+
+ PropertyData propertyData = findPropertyDefRes.left().value();
+ GroupInstanceData resourceInstanceData = findResInstanceRes.left().value();
+
+ ImmutablePair<TitanOperationStatus, String> isPropertyValueExists = propertyOperation.findPropertyValue(groupInstanceId, propertyId);
+ if (isPropertyValueExists.getLeft() == TitanOperationStatus.ALREADY_EXIST) {
+ log.debug("The property {} already added to the resource instance {}", propertyId, groupInstanceId);
+ groupInstanceProperty.setValueUniqueUid(isPropertyValueExists.getRight());
+ Either<PropertyValueData, TitanOperationStatus> updatePropertyOfResourceInstance = updatePropertyOfGroupInstance(groupInstanceProperty, groupInstanceId);
+ if (updatePropertyOfResourceInstance.isRight()) {
+ BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + updatePropertyOfResourceInstance.right().value(), ErrorSeverity.ERROR);
+ return Either.right(updatePropertyOfResourceInstance.right().value());
+ }
+ return Either.left(updatePropertyOfResourceInstance.left().value());
+ }
+
+ if (isPropertyValueExists.getLeft() != TitanOperationStatus.NOT_FOUND) {
+ log.debug("After finding property value of {} on componenet instance {}", propertyId, groupInstanceId);
+ return Either.right(isPropertyValueExists.getLeft());
+ }
+
+ String innerType = null;
+
+ PropertyDataDefinition propDataDef = propertyData.getPropertyDataDefinition();
+ String propertyType = propDataDef.getType();
+ String value = groupInstanceProperty.getValue();
+ ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
+
+ if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
+ SchemaDefinition def = propDataDef.getSchema();
+ if (def == null) {
+ log.debug("Schema doesn't exists for property of type {}", type);
+ return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
+ }
+ PropertyDataDefinition propDef = def.getProperty();
+ if (propDef == null) {
+ log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
+ return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
+ }
+ innerType = propDef.getType();
+ }
+
+ log.debug("Before validateAndUpdatePropertyValue");
+ Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
+ if (allDataTypes.isRight()) {
+ TitanOperationStatus status = allDataTypes.right().value();
+ BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
+ return Either.right(status);
+ }
+ Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, value, innerType, allDataTypes.left().value());
+ log.debug("After validateAndUpdatePropertyValue. isValid = {}", isValid);
+
+ String newValue = value;
+ if (isValid.isRight()) {
+ Boolean res = isValid.right().value();
+ if (res == false) {
+ return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
+ }
+ } else {
+ Object object = isValid.left().value();
+ if (object != null) {
+ newValue = object.toString();
+ }
+ }
+
+ String uniqueId = UniqueIdBuilder.buildResourceInstancePropertyValueUid(resourceInstanceData.getUniqueId(), index);
+ PropertyValueData propertyValueData = new PropertyValueData();
+ propertyValueData.setUniqueId(uniqueId);
+ propertyValueData.setValue(newValue);
+
+ log.debug("Before validateAndUpdateRules");
+ ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, groupInstanceProperty.getRules(), innerType, allDataTypes.left().value(), false);
+ log.debug("After validateAndUpdateRules. pair = {}", pair);
+ if (pair.getRight() != null && pair.getRight() == false) {
+ BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), groupInstanceProperty.getName(), propertyType);
+ return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
+ }
+ propertyOperation.addRulesToNewPropertyValue(propertyValueData, groupInstanceProperty, groupInstanceId);
+
+ log.debug("Before adding property value to graph {}", propertyValueData);
+ Either<PropertyValueData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(propertyValueData, PropertyValueData.class);
+ log.debug("After adding property value to graph {}", propertyValueData);
+
+ if (createNodeResult.isRight()) {
+ TitanOperationStatus operationStatus = createNodeResult.right().value();
+ return Either.right(operationStatus);
+ }
+ propertyValueData = createNodeResult.left().value();
+
+ Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(propertyValueData, propertyData, GraphEdgeLabels.PROPERTY_IMPL, null);
+
+ if (createRelResult.isRight()) {
+ TitanOperationStatus operationStatus = createRelResult.right().value();
+ log.error("Failed to associate property value {} to property {} in graph. status is {}", uniqueId, propertyId, operationStatus);
+ return Either.right(operationStatus);
+ }
+
+ createRelResult = titanGenericDao.createRelation(resourceInstanceData, propertyValueData, GraphEdgeLabels.PROPERTY_VALUE, null);
+
+ if (createRelResult.isRight()) {
+ TitanOperationStatus operationStatus = createRelResult.right().value();
+ log.error("Failed to associate resource instance {} property value {} in graph. status is {}", groupInstanceId, uniqueId, operationStatus);
+ return Either.right(operationStatus);
+ }
+
+ return Either.left(propertyValueData);
+ } else {
+ log.error("property value already exists.");
+ return Either.right(TitanOperationStatus.ALREADY_EXIST);
+ }
+
+ }
+
+ public Either<ComponentInstanceProperty, TitanOperationStatus> addPropertyToResourceInstance(ComponentInstanceProperty groupInstanceProperty, TitanVertex groupInstanceVertex, Integer index, String groupInstanceId) {
+
+ String propertyId = groupInstanceProperty.getUniqueId();
+ Either<PropertyData, TitanOperationStatus> findPropertyDefRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Property), propertyId, PropertyData.class);
+
+ if (findPropertyDefRes.isRight()) {
+ TitanOperationStatus status = findPropertyDefRes.right().value();
+ if (status == TitanOperationStatus.NOT_FOUND) {
+ status = TitanOperationStatus.INVALID_ID;
+ }
+ return Either.right(status);
+ }
+
+ String valueUniqueUid = groupInstanceProperty.getValueUniqueUid();
+ if (valueUniqueUid == null) {
+
+ PropertyData propertyData = findPropertyDefRes.left().value();
+
+ ImmutablePair<TitanOperationStatus, String> isPropertyValueExists = propertyOperation.findPropertyValue(groupInstanceId, propertyId);
+ if (isPropertyValueExists.getLeft() == TitanOperationStatus.ALREADY_EXIST) {
+ log.trace("The property {} already added to the resource instance {}", propertyId, groupInstanceId);
+ groupInstanceProperty.setValueUniqueUid(isPropertyValueExists.getRight());
+ Either<PropertyValueData, TitanOperationStatus> updatePropertyOfResourceInstance = updatePropertyOfGroupInstance(groupInstanceProperty, groupInstanceId);
+ if (updatePropertyOfResourceInstance.isRight()) {
+ BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + updatePropertyOfResourceInstance.right().value(), ErrorSeverity.ERROR);
+ return Either.right(updatePropertyOfResourceInstance.right().value());
+ }
+ return Either.right(TitanOperationStatus.OK);
+ }
+
+ if (isPropertyValueExists.getLeft() != TitanOperationStatus.NOT_FOUND) {
+ log.trace("After finding property value of {} on componenet instance {}", propertyId, groupInstanceId);
+ return Either.right(isPropertyValueExists.getLeft());
+ }
+
+ String innerType = null;
+
+ PropertyDataDefinition propDataDef = propertyData.getPropertyDataDefinition();
+ String propertyType = propDataDef.getType();
+ String value = groupInstanceProperty.getValue();
+ ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
+
+ if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
+ SchemaDefinition def = propDataDef.getSchema();
+ if (def == null) {
+ log.debug("Schema doesn't exists for property of type {}", type);
+ return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
+ }
+ PropertyDataDefinition propDef = def.getProperty();
+ if (propDef == null) {
+ log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
+ return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
+ }
+ innerType = propDef.getType();
+ }
+
+ log.trace("Before validateAndUpdatePropertyValue");
+ Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
+ if (allDataTypes.isRight()) {
+ TitanOperationStatus status = allDataTypes.right().value();
+ BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
+ return Either.right(status);
+ }
+ Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, value, innerType, allDataTypes.left().value());
+ log.trace("After validateAndUpdatePropertyValue. isValid = {}", isValid);
+
+ String newValue = value;
+ if (isValid.isRight()) {
+ Boolean res = isValid.right().value();
+ if (res == false) {
+ return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
+ }
+ } else {
+ Object object = isValid.left().value();
+ if (object != null) {
+ newValue = object.toString();
+ }
+ }
+
+ String uniqueId = UniqueIdBuilder.buildResourceInstancePropertyValueUid(groupInstanceId, index);
+ PropertyValueData propertyValueData = new PropertyValueData();
+ propertyValueData.setUniqueId(uniqueId);
+ propertyValueData.setValue(newValue);
+
+ log.trace("Before validateAndUpdateRules");
+ ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, groupInstanceProperty.getRules(), innerType, allDataTypes.left().value(), false);
+ log.debug("After validateAndUpdateRules. pair = {} ", pair);
+ if (pair.getRight() != null && pair.getRight() == false) {
+ BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), groupInstanceProperty.getName(), propertyType);
+ return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
+ }
+ propertyOperation.addRulesToNewPropertyValue(propertyValueData, groupInstanceProperty, groupInstanceId);
+
+ log.trace("Before adding property value to graph {}", propertyValueData);
+ Either<PropertyValueData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(propertyValueData, PropertyValueData.class);
+ log.trace("After adding property value to graph {}", propertyValueData);
+
+ if (createNodeResult.isRight()) {
+ TitanOperationStatus operationStatus = createNodeResult.right().value();
+ return Either.right(operationStatus);
+ }
+ propertyValueData = createNodeResult.left().value();
+
+ Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(propertyValueData, propertyData, GraphEdgeLabels.PROPERTY_IMPL, null);
+
+ if (createRelResult.isRight()) {
+ TitanOperationStatus operationStatus = createRelResult.right().value();
+ log.error("Failed to associate property value {} to property {} in graph. status is {}", uniqueId, propertyId, operationStatus);
+ return Either.right(operationStatus);
+ }
+
+ TitanOperationStatus edgeResult = titanGenericDao.createEdge(groupInstanceVertex, propertyValueData, GraphEdgeLabels.PROPERTY_VALUE, null);
+
+ if (edgeResult != TitanOperationStatus.OK) {
+ log.error("Failed to associate resource instance {} property value {} in graph. status is {}", groupInstanceId, uniqueId, edgeResult);
+ return Either.right(edgeResult);
+ }
+
+ ComponentInstanceProperty propertyValueResult = propertyOperation.buildResourceInstanceProperty(propertyValueData, groupInstanceProperty);
+ log.debug("The returned ResourceInstanceProperty is {} ", propertyValueResult);
+
+ return Either.left(propertyValueResult);
+ } else {
+ log.debug("property value already exists.");
+ return Either.right(TitanOperationStatus.ALREADY_EXIST);
+ }
+
+ }
+
+ public Either<GroupInstance, TitanOperationStatus> addGroupInstanceToComponentInstance(String componentInstanceId, boolean isCreateLogicaName, GroupInstance groupInstance) {
+ log.debug("Going to create group instance {} in componentInstance {}", groupInstance, componentInstanceId);
+
+ Either<TitanVertex, TitanOperationStatus> metadataVertex = titanGenericDao.getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), componentInstanceId);
+ if (metadataVertex.isRight()) {
+ TitanOperationStatus status = metadataVertex.right().value();
+ if (status == TitanOperationStatus.NOT_FOUND) {
+ status = TitanOperationStatus.INVALID_ID;
+ }
+ return Either.right(status);
+ }
+ Either<TitanVertex, TitanOperationStatus> addComponentInstanceToContainerComponent = addGroupInstanceToContainerComponent(metadataVertex.left().value(), componentInstanceId, isCreateLogicaName, groupInstance);
+
+ if (addComponentInstanceToContainerComponent.isRight()) {
+ TitanOperationStatus status = addComponentInstanceToContainerComponent.right().value();
+ if (status == TitanOperationStatus.NOT_FOUND) {
+ status = TitanOperationStatus.INVALID_ID;
+ }
+ return Either.right(status);
+ }
+ TitanVertex ciVertex = addComponentInstanceToContainerComponent.left().value();
+ Map<String, Object> properties = titanGenericDao.getProperties(ciVertex);
+ GroupInstanceData createdComponentInstance = GraphElementFactory.createElement(NodeTypeEnum.GroupInstance.getName(), GraphElementTypeEnum.Node, properties, GroupInstanceData.class);
+
+ GroupInstance createdResourceInstance = new GroupInstance(createdComponentInstance.getGroupDataDefinition());
+
+ return Either.left(createdResourceInstance);
+
+ }
+
+ /**
+ *
+ * @param containerComponentId
+ * @param containerNodeType
+ * @param instanceNumber
+ * @param isCreateLogicaName
+ * @param componentInstance
+ * @param compInstNodeType
+ * @param metadataVertex
+ * @return
+ */
+ public Either<TitanVertex, TitanOperationStatus> addGroupInstanceToContainerComponent(TitanVertex ciVertex, String componentInstanceId, boolean isCreateLogicaName, GroupInstance groupInstance) {
+ TitanOperationStatus status = null;
+ log.debug("Going to create group instance {} in component instance {}", groupInstance, componentInstanceId);
+ String instOriginGroupId = groupInstance.getGroupUid();
+ String logicalName = groupInstance.getName();
+ if (isCreateLogicaName){
+ String instanceName = (String) titanGenericDao.getProperty(ciVertex, GraphPropertiesDictionary.NORMALIZED_NAME.getProperty());
+ logicalName = createGroupInstLogicalName(instanceName, groupInstance.getGroupName());
+ }
+
+ GroupInstanceData groupInstanceData = buildGroupInstanceData(groupInstance, componentInstanceId, logicalName);
+ Either<TitanVertex, TitanOperationStatus> originVertexEither = titanGenericDao.getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), instOriginGroupId);
+ if (originVertexEither.isRight()) {
+ log.debug("Failed to fetch vertex of origin resource for id {} error {}", instOriginGroupId, originVertexEither.right().value());
+ return Either.right(originVertexEither.right().value());
+ }
+ TitanVertex originVertex = originVertexEither.left().value();
+
+ // String originType = (String) titanGenericDao.getProperty(originVertex, GraphPropertiesDictionary.LABEL.getProperty());
+ String groupType = (String) titanGenericDao.getProperty(originVertex, GraphPropertiesDictionary.TYPE.getProperty());
+ // detectOriginType(originType, groupInstanceData, resourceType);
+
+ log.trace("Before adding component instance to graph. componentInstanceData = {}", groupInstanceData);
+ // groupInstanceData.getGroupDataDefinition().setGroupUid(groupType);
+
+ Either<TitanVertex, TitanOperationStatus> createGIResult = titanGenericDao.createNode(groupInstanceData);
+
+ log.debug("After adding component instance to graph. status is = {}", createGIResult);
+
+ if (createGIResult.isRight()) {
+ status = createGIResult.right().value();
+ BeEcompErrorManager.getInstance().logBeDaoSystemError("Add Component Instance");
+ log.debug("Failed to create group instance node in graph. status is {}", status);
+ return Either.right(status);
+ }
+ TitanVertex createdGroupInstanceVertex = createGIResult.left().value();
+ TitanOperationStatus associateContainerRes = associateComponentInstanceToGroupInstance(ciVertex, createdGroupInstanceVertex, logicalName);
+
+ String componentInstanceUniqueId = groupInstanceData.getUniqueId();
+ if (associateContainerRes != TitanOperationStatus.OK) {
+ BeEcompErrorManager.getInstance().logBeDaoSystemError("Add Component Instance");
+ log.debug("Failed to associate container component {} to component instance {}. Status is {}", componentInstanceId, componentInstanceUniqueId, associateContainerRes);
+ return Either.right(associateContainerRes);
+ }
+ // String originId = (String) titanGenericDao.getProperty(createdGroupInstanceVertex, GraphPropertiesDictionary.TYPE.getProperty());
+
+ TitanOperationStatus associateToInstOriginComponent = associateToInstOriginGroup(createdGroupInstanceVertex, originVertex, instOriginGroupId);
+ if (associateToInstOriginComponent != TitanOperationStatus.OK) {
+ BeEcompErrorManager.getInstance().logBeDaoSystemError("Add Component Instance");
+ log.debug("Failed to associate component instance {} to its origin component {}. Status is {}", componentInstanceUniqueId, groupInstanceData.getGroupDataDefinition().getGroupUid(), associateToInstOriginComponent);
+ return Either.right(associateToInstOriginComponent);
+ }
+
+ // Capability instance with property values implementation
+
+ if (status == null) {
+ // ComponentInstance createdResourceInstance = new
+ // ComponentInstance(createdComponentInstance.getComponentInstDataDefinition());
+ //
+ // String icon = (String) titanGenericDao.getProperty(originVertex,
+ // GraphPropertiesDictionary.ICON.getProperty());
+ // createdResourceInstance.setIcon(icon);
+ return Either.left(createdGroupInstanceVertex);
+ }
+ return Either.right(status);
+ }
+
+ private GroupInstanceData buildGroupInstanceData(GroupInstance groupInstance, String componentInstanceId, String logicalName) {
+ String ciOriginComponentUid = groupInstance.getGroupUid();
+
+ GroupInstanceDataDefinition dataDefinition = new GroupInstanceDataDefinition(groupInstance);
+
+ Long creationDate = groupInstance.getCreationTime();
+ if (creationDate == null) {
+ creationDate = System.currentTimeMillis();
+ }
+ dataDefinition.setCreationTime(creationDate);
+ dataDefinition.setModificationTime(creationDate);
+ // dataDefinition.setResourceUid(resourceUid);
+ // String replacmentlogicalName = logicalName.replaceAll(" ",
+ // "_").toLowerCase();
+ dataDefinition.setName(logicalName);
+ if (dataDefinition.getNormalizedName() == null)
+ dataDefinition.setNormalizedName(ValidationUtils.normalizeComponentInstanceName(logicalName));
+ dataDefinition.setUniqueId(UniqueIdBuilder.buildResourceInstanceUniuqeId(componentInstanceId, ciOriginComponentUid, dataDefinition.getNormalizedName()));
+
+ GroupInstanceData resourceInstanceData = new GroupInstanceData(dataDefinition);
+
+ return resourceInstanceData;
+ }
+
+ @Override
+ public String createGroupInstLogicalName(String instanceName, String groupName) {
+
+ String logicalName = buildGroupInstanceLogicalName(instanceName, groupName);
+
+ return logicalName;
+ }
+
+ private String buildGroupInstanceLogicalName(String instanceName, String groupName) {
+ return instanceName + ".." + groupName;
+ }
+
+ /**
+ * Make a relation between service to resource instance.
+ *
+ * @param containerCompIdData
+ * @param componentInstanceData
+ * @param logicalName
+ * @return
+ */
+ private Either<GraphRelation, TitanOperationStatus> associateComponentInstanceToGroupInstance(UniqueIdData compInstIdData, GroupInstanceData groupInstanceData, String logicalName) {
+ Map<String, Object> properties = new HashMap<String, Object>();
+
+ properties.put(GraphPropertiesDictionary.NAME.getProperty(), logicalName);
+ Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(compInstIdData, groupInstanceData, GraphEdgeLabels.GROUP_INST, properties);
+
+ log.debug("After associating container component {} to resource instance {} with logical name {}. Status is {}", compInstIdData.getUniqueId(), groupInstanceData.getUniqueId(), logicalName, createRelation);
+
+ return createRelation;
+ }
+
+ private TitanOperationStatus associateComponentInstanceToGroupInstance(TitanVertex componentInstVertex, TitanVertex groupInstanceVertex, String logicalName) {
+ Map<String, Object> properties = new HashMap<String, Object>();
+
+ properties.put(GraphPropertiesDictionary.NAME.getProperty(), logicalName);
+ TitanOperationStatus createRelation = titanGenericDao.createEdge(componentInstVertex, groupInstanceVertex, GraphEdgeLabels.GROUP_INST, properties);
+
+ return createRelation;
+ }
+
+ private Either<GraphRelation, TitanOperationStatus> associateToInstOriginGroup(GroupInstanceData groupInstanceData, NodeTypeEnum compInstNodeType) {
+
+ UniqueIdData groupIdData = new UniqueIdData(compInstNodeType, groupInstanceData.getGroupDataDefinition().getGroupUid());
+
+ Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(groupInstanceData, groupIdData, GraphEdgeLabels.INSTANCE_OF, null);
+
+ log.debug("After associating group instance {} to group {}. status is {}", groupInstanceData.getUniqueId(), groupInstanceData.getGroupDataDefinition().getGroupUid(), createRelation);
+
+ return createRelation;
+ }
+
+ private TitanOperationStatus associateToInstOriginGroup(TitanVertex groupInstanceVertex, TitanVertex originVertex, String originId) {
+
+ TitanOperationStatus createRelation = titanGenericDao.createEdge(groupInstanceVertex, originVertex, GraphEdgeLabels.INSTANCE_OF, null);
+
+ log.debug("After associating group instance {} to group {}. status is {}", groupInstanceVertex, originId, createRelation);
+
+ return createRelation;
+ }
+
+ public Either<List<GroupProperty>, TitanOperationStatus> getGroupInstanceProperties(GroupInstance groupInstance, GroupDefinition groupDefinition) {
+
+ // 1. Go over each instance
+ // 1.1 get all properties of from the parents of the instance
+ // 1.2 get all updated properties
+ // 1.3 find all instances included in the parent of this instance and
+ // run this method on them.
+ String groupInstanceId = groupInstance.getUniqueId();
+ if (log.isDebugEnabled())
+ log.debug("Going to update properties of group instance {}", groupInstanceId);
+ String groupUid = groupInstance.getGroupUid();
+ List<GroupProperty> properties = groupDefinition.convertToGroupProperties();
+
+ if (log.isDebugEnabled())
+ log.debug("After getting properties of group {} . Number of properties is {}", groupUid, (properties == null ? 0 : properties.size()));
+ List<GroupProperty> resourceInstancePropertyList = new ArrayList<>();
+ if (properties != null && false == properties.isEmpty()) {
+
+ // TODO: WE MAY HAVE INDIRECT PROPERTY VALUE ALSO IN CASE NO
+ // PROPERTY ON THIS COMPONENT
+
+ // String resourceInstanceUid = resourceInstance.getUniqueId();
+
+ for (GroupProperty propertyDefinition : properties) {
+
+ String defaultValue = propertyDefinition.getDefaultValue();
+ String value = defaultValue;
+ String valueUid = null;
+
+ // String propertyId = propertyDefinition.getUniqueId();
+
+ GroupProperty resourceInstanceProperty = new GroupProperty(propertyDefinition, value, valueUid);
+
+ // resourceInstanceProperty.setPath(cloneList(path));
+
+ // TODO: currently ignore constraints since they are not inuse
+ // and cause to error in convertion to object.
+ resourceInstanceProperty.setConstraints(null);
+
+ resourceInstancePropertyList.add(resourceInstanceProperty);
+
+ }
+
+ }
+
+ return Either.left(resourceInstancePropertyList);
+ }
+
+ /**
+ * update value of attribute on resource instance
+ *
+ * @param resourceInstanceProerty
+ * @param resourceInstanceId
+ * @return
+ */
+ public Either<PropertyValueData, TitanOperationStatus> updatePropertyOfGroupInstance(ComponentInstanceProperty groupInstanceProerty, String groupInstanceId) {
+
+ Wrapper<TitanOperationStatus> errorWrapper = new Wrapper<>();
+ UpdateDataContainer<PropertyData, PropertyValueData> updateDataContainer = new UpdateDataContainer<>(GraphEdgeLabels.PROPERTY_IMPL, (() -> PropertyData.class), (() -> PropertyValueData.class), NodeTypeEnum.Property,
+ NodeTypeEnum.PropertyValue);
+
+ preUpdateElementOfResourceInstanceValidations(updateDataContainer, groupInstanceProerty, groupInstanceId, errorWrapper);
+ if (!errorWrapper.isEmpty()) {
+ return Either.right(errorWrapper.getInnerElement());
+ }
+
+ else {
+ String value = groupInstanceProerty.getValue();
+ // Specific Validation Logic
+ PropertyData propertyData = updateDataContainer.getDataWrapper().getInnerElement();
+
+ String innerType = null;
+
+ PropertyDataDefinition propDataDef = propertyData.getPropertyDataDefinition();
+ String propertyType = propDataDef.getType();
+ ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
+ log.debug("The type of the property {} is {}", propertyData.getUniqueId(), propertyType);
+
+ if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
+ SchemaDefinition def = propDataDef.getSchema();
+ if (def == null) {
+ log.debug("Schema doesn't exists for property of type {}", type);
+ return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
+ }
+ PropertyDataDefinition propDef = def.getProperty();
+ if (propDef == null) {
+ log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
+ return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
+ }
+ innerType = propDef.getType();
+ }
+ // Specific Update Logic
+ Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
+ if (allDataTypes.isRight()) {
+ TitanOperationStatus status = allDataTypes.right().value();
+ BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
+ return Either.right(status);
+ }
+ Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, value, innerType, allDataTypes.left().value());
+
+ String newValue = value;
+ if (isValid.isRight()) {
+ Boolean res = isValid.right().value();
+ if (res == false) {
+ return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
+ }
+ } else {
+ Object object = isValid.left().value();
+ if (object != null) {
+ newValue = object.toString();
+ }
+ }
+ PropertyValueData propertyValueData = updateDataContainer.getValueDataWrapper().getInnerElement();
+ log.debug("Going to update property value from {} to {}", propertyValueData.getValue(), newValue);
+ propertyValueData.setValue(newValue);
+
+ ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, groupInstanceProerty.getRules(), innerType, allDataTypes.left().value(), true);
+ if (pair.getRight() != null && pair.getRight() == false) {
+ BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), groupInstanceProerty.getName(), propertyType);
+ return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
+ }
+ propertyOperation.updateRulesInPropertyValue(propertyValueData, groupInstanceProerty, groupInstanceId);
+
+ Either<PropertyValueData, TitanOperationStatus> updateRes = titanGenericDao.updateNode(propertyValueData, PropertyValueData.class);
+ if (updateRes.isRight()) {
+ TitanOperationStatus status = updateRes.right().value();
+ return Either.right(status);
+ } else {
+ return Either.left(updateRes.left().value());
+ }
+ }
+
+ }
+
+ private static final class UpdateDataContainer<SomeData, SomeValueData> {
+ final Wrapper<SomeValueData> valueDataWrapper;
+ final Wrapper<SomeData> dataWrapper;
+ final GraphEdgeLabels graphEdge;
+ final Supplier<Class<SomeData>> someDataClassGen;
+ final Supplier<Class<SomeValueData>> someValueDataClassGen;
+ final NodeTypeEnum nodeType;
+ final NodeTypeEnum nodeTypeValue;
+
+ private UpdateDataContainer(GraphEdgeLabels graphEdge, Supplier<Class<SomeData>> someDataClassGen, Supplier<Class<SomeValueData>> someValueDataClassGen, NodeTypeEnum nodeType, NodeTypeEnum nodeTypeValue) {
+ super();
+ this.valueDataWrapper = new Wrapper<>();
+ this.dataWrapper = new Wrapper<>();
+ this.graphEdge = graphEdge;
+ this.someDataClassGen = someDataClassGen;
+ this.someValueDataClassGen = someValueDataClassGen;
+ this.nodeType = nodeType;
+ this.nodeTypeValue = nodeTypeValue;
+ }
+
+ public Wrapper<SomeValueData> getValueDataWrapper() {
+ return valueDataWrapper;
+ }
+
+ public Wrapper<SomeData> getDataWrapper() {
+ return dataWrapper;
+ }
+
+ public GraphEdgeLabels getGraphEdge() {
+ return graphEdge;
+ }
+
+ public Supplier<Class<SomeData>> getSomeDataClassGen() {
+ return someDataClassGen;
+ }
+
+ public Supplier<Class<SomeValueData>> getSomeValueDataClassGen() {
+ return someValueDataClassGen;
+ }
+
+ public NodeTypeEnum getNodeType() {
+ return nodeType;
+ }
+
+ public NodeTypeEnum getNodeTypeValue() {
+ return nodeTypeValue;
+ }
+ }
+
+ private <SomeData extends GraphNode, SomeValueData extends GraphNode> void preUpdateElementOfResourceInstanceValidations(UpdateDataContainer<SomeData, SomeValueData> updateDataContainer, IComponentInstanceConnectedElement resourceInstanceProerty,
+ String resourceInstanceId, Wrapper<TitanOperationStatus> errorWrapper) {
+
+ if (errorWrapper.isEmpty()) {
+ // Verify VFC instance Exist
+ validateGIExist(resourceInstanceId, errorWrapper);
+ }
+
+ if (errorWrapper.isEmpty()) {
+ // Example: Verify Property connected to VFC exist
+ validateElementConnectedToComponentExist(updateDataContainer, resourceInstanceProerty, errorWrapper);
+ }
+
+ if (errorWrapper.isEmpty()) {
+ // Example: Verify PropertyValue connected to VFC Instance exist
+ validateElementConnectedToComponentInstanceExist(updateDataContainer, resourceInstanceProerty, errorWrapper);
+ }
+
+ if (errorWrapper.isEmpty()) {
+ // Example: Verify PropertyValue connected Property
+ validateElementConnectedToInstance(updateDataContainer, resourceInstanceProerty, errorWrapper);
+ }
+ }
+
+ private <SomeData extends GraphNode, SomeValueData extends GraphNode> void validateElementConnectedToInstance(UpdateDataContainer<SomeData, SomeValueData> updateDataContainer, IComponentInstanceConnectedElement resourceInstanceProerty,
+ Wrapper<TitanOperationStatus> errorWrapper) {
+ Either<ImmutablePair<SomeData, GraphEdge>, TitanOperationStatus> child = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(updateDataContainer.getNodeTypeValue()), resourceInstanceProerty.getValueUniqueUid(),
+ updateDataContainer.getGraphEdge(), updateDataContainer.getNodeType(), updateDataContainer.getSomeDataClassGen().get());
+
+ if (child.isRight()) {
+ TitanOperationStatus status = child.right().value();
+ if (status == TitanOperationStatus.NOT_FOUND) {
+ status = TitanOperationStatus.INVALID_ID;
+ }
+ errorWrapper.setInnerElement(status);
+
+ } else {
+ updateDataContainer.getDataWrapper().setInnerElement(child.left().value().left);
+ }
+ }
+
+ private <SomeValueData extends GraphNode, SomeData extends GraphNode> void validateElementConnectedToComponentInstanceExist(UpdateDataContainer<SomeData, SomeValueData> updateDataContainer,
+ IComponentInstanceConnectedElement resourceInstanceProerty, Wrapper<TitanOperationStatus> errorWrapper) {
+ String valueUniqueUid = resourceInstanceProerty.getValueUniqueUid();
+ if (valueUniqueUid == null) {
+ errorWrapper.setInnerElement(TitanOperationStatus.INVALID_ID);
+ } else {
+ Either<SomeValueData, TitanOperationStatus> findPropertyValueRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(updateDataContainer.getNodeTypeValue()), valueUniqueUid, updateDataContainer.getSomeValueDataClassGen().get());
+ if (findPropertyValueRes.isRight()) {
+ TitanOperationStatus status = findPropertyValueRes.right().value();
+ if (status == TitanOperationStatus.NOT_FOUND) {
+ status = TitanOperationStatus.INVALID_ID;
+ }
+ errorWrapper.setInnerElement(status);
+ } else {
+ updateDataContainer.getValueDataWrapper().setInnerElement(findPropertyValueRes.left().value());
+ }
+ }
+ }
+
+ private <SomeData extends GraphNode, SomeValueData extends GraphNode> void validateElementConnectedToComponentExist(UpdateDataContainer<SomeData, SomeValueData> updateDataContainer,
+ IComponentInstanceConnectedElement resourceInstanceElementConnected, Wrapper<TitanOperationStatus> errorWrapper) {
+ String uniqueId = resourceInstanceElementConnected.getUniqueId();
+ Either<SomeData, TitanOperationStatus> findPropertyDefRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(updateDataContainer.getNodeType()), uniqueId, updateDataContainer.getSomeDataClassGen().get());
+
+ if (findPropertyDefRes.isRight()) {
+ TitanOperationStatus status = findPropertyDefRes.right().value();
+ errorWrapper.setInnerElement(status);
+ }
+ }
+
+ private void validateGIExist(String resourceInstanceId, Wrapper<TitanOperationStatus> errorWrapper) {
+ validateGIExist(resourceInstanceId, null, errorWrapper);
+ }
+
+ private void validateGIExist(String resourceInstanceId, Wrapper<GroupInstanceData> compInsDataWrapper, Wrapper<TitanOperationStatus> errorWrapper) {
+ validateElementExistInGraph(resourceInstanceId, NodeTypeEnum.GroupInstance, () -> GroupInstanceData.class, compInsDataWrapper, errorWrapper);
+ }
+
+ public <ElementData extends GraphNode> void validateElementExistInGraph(String elementUniqueId, NodeTypeEnum elementNodeType, Supplier<Class<ElementData>> elementClassGen, Wrapper<ElementData> elementDataWrapper,
+ Wrapper<TitanOperationStatus> errorWrapper) {
+ Either<ElementData, TitanOperationStatus> findResInstanceRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(elementNodeType), elementUniqueId, elementClassGen.get());
+ if (findResInstanceRes.isRight()) {
+ TitanOperationStatus status = findResInstanceRes.right().value();
+ if (status == TitanOperationStatus.NOT_FOUND) {
+ status = TitanOperationStatus.INVALID_ID;
+ }
+ errorWrapper.setInnerElement(status);
+ } else {
+ if (elementDataWrapper != null) {
+ elementDataWrapper.setInnerElement(findResInstanceRes.left().value());
+ }
+ }
+ }
+
+ /**
+ * Associate artifacts to a given group
+ *
+ * @param groupId
+ * @param artifactsId
+ * @param inTransaction
+ * @return
+ */
+ public Either<GroupInstance, StorageOperationStatus> associateArtifactsToGroupInstance(String groupId, List<String> artifactsId) {
+
+ Either<GroupInstance, StorageOperationStatus> result = null;
+
+ Either<GroupInstance, TitanOperationStatus> titanRes = this.associateArtifactsToGroupInstanceOnGraph(groupId, artifactsId);
+
+ if (titanRes.isRight()) {
+ StorageOperationStatus status = DaoStatusConverter.convertTitanStatusToStorageStatus(titanRes.right().value());
+ result = Either.right(status);
+ }
+
+ result = Either.left(titanRes.left().value());
+ return result;
+
+ }
+
+ public Either<GroupInstance, TitanOperationStatus> associateArtifactsToGroupInstanceOnGraph(String groupInstanceId, List<String> artifactsId) {
+
+ if (artifactsId == null || artifactsId.isEmpty()) {
+ return Either.right(TitanOperationStatus.OK);
+ }
+
+ for (String artifactId : artifactsId) {
+ Either<ArtifactData, TitanOperationStatus> findArtifactRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef), artifactId, ArtifactData.class);
+ if (findArtifactRes.isRight()) {
+ TitanOperationStatus status = findArtifactRes.right().value();
+ if (status == TitanOperationStatus.NOT_FOUND) {
+ status = TitanOperationStatus.INVALID_ID;
+ }
+ String description = "Failed to associate group " + groupInstanceId + " to artifact " + artifactId + " in graph. Status is " + status;
+ BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, ErrorSeverity.ERROR);
+ return Either.right(status);
+ }
+
+ Map<String, Object> props = new HashMap<String, Object>();
+ props.put(GraphPropertiesDictionary.NAME.getProperty(), findArtifactRes.left().value().getLabel());
+
+ GraphNode groupData = new UniqueIdData(NodeTypeEnum.GroupInstance, groupInstanceId);
+ Either<GraphRelation, TitanOperationStatus> addArtifactsRefResult = titanGenericDao.createRelation(groupData, findArtifactRes.left().value(), GraphEdgeLabels.GROUP_ARTIFACT_REF, props);
+
+ if (addArtifactsRefResult.isRight()) {
+ TitanOperationStatus status = addArtifactsRefResult.right().value();
+ String description = "Failed to associate group " + groupData.getUniqueId() + " to artifact " + artifactId + " in graph. Status is " + status;
+ BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, ErrorSeverity.ERROR);
+ return Either.right(status);
+ }
+ }
+
+ Either<GroupInstance, TitanOperationStatus> groupFromGraph = this.getGroupInstanceFromGraph(groupInstanceId, true, false);
+
+ return groupFromGraph;
+ }
+
+ public Either<GroupInstance, TitanOperationStatus> getGroupInstanceFromGraph(String uniqueId, boolean skipProperties, boolean skipArtifacts) {
+
+ Either<GroupInstance, TitanOperationStatus> result = null;
+
+ Either<GroupInstanceData, TitanOperationStatus> groupInstRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.GroupInstance), uniqueId, GroupInstanceData.class);
+ if (groupInstRes.isRight()) {
+ TitanOperationStatus status = groupInstRes.right().value();
+ log.debug("Failed to retrieve group {} from graph. Status is {}", uniqueId, status);
+ BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError("Fetch Group", uniqueId, String.valueOf(status));
+ result = Either.right(status);
+ return result;
+ }
+
+ GroupInstanceData groupInstData = groupInstRes.left().value();
+
+ GroupInstance groupInstance = new GroupInstance(groupInstData.getGroupDataDefinition());
+ String instOriginGroupId = groupInstance.getGroupUid();
+ Either<GroupDefinition, TitanOperationStatus> groupRes = groupOperation.getGroupFromGraph(instOriginGroupId, false, true, false);
+
+ if (groupRes.isRight()) {
+ TitanOperationStatus status = groupRes.right().value();
+ result = Either.right(status);
+
+ }
+ GroupDefinition groupDefinition = groupRes.left().value();
+ Either<Map<String, PropertyValueData>, TitanOperationStatus> groupInstancePropertyValuesRes = getAllGroupInstancePropertyValuesData(groupInstData);
+ if(groupInstancePropertyValuesRes.isRight()){
+ result = Either.right(groupInstancePropertyValuesRes.right().value());
+ }
+ buildGroupInstanceFromGroup(groupInstance, groupDefinition, groupInstancePropertyValuesRes.left().value());
+
+ /*
+ * if (false == skipProperties) { Either<List<GroupProperty>, TitanOperationStatus> propertiesRes = getGroupProperties(uniqueId); if (propertiesRes.isRight()) { TitanOperationStatus status = propertiesRes.right().value(); if (status !=
+ * TitanOperationStatus.OK) { result = Either.right(status); return result; } } else { List<GroupProperty> properties = propertiesRes.left().value(); groupDefinition.setProperties(properties); } }
+ */
+
+ if (false == skipArtifacts) {
+ Either<List<ImmutablePair<String, String>>, TitanOperationStatus> artifactsRes = getGroupArtifactsPairs(uniqueId);
+ if (artifactsRes.isRight()) {
+ TitanOperationStatus status = artifactsRes.right().value();
+ if (status != TitanOperationStatus.OK) {
+ result = Either.right(status);
+ return result;
+ }
+ } else {
+ List<String> artifactsUid = new ArrayList<>();
+ List<String> artifactsUUID = new ArrayList<>();
+
+ List<ImmutablePair<String, String>> list = artifactsRes.left().value();
+ if (list != null) {
+ for (ImmutablePair<String, String> pair : list) {
+ String uid = pair.left;
+ String UUID = pair.right;
+ artifactsUid.add(uid);
+ artifactsUUID.add(UUID);
+ }
+ groupInstance.setGroupInstanceArtifacts(artifactsUid);
+ groupInstance.setGroupInstanceArtifactsUuid(artifactsUUID);
+ }
+ }
+ }
+ result = Either.left(groupInstance);
+
+ return result;
+
+ }
+
+ private void buildGroupInstanceFromGroup(GroupInstance groupInstance, GroupDefinition groupDefinition, Map<String, PropertyValueData> groupInstancePropertyValues) {
+
+ groupInstance.setGroupName(groupDefinition.getName());
+ groupInstance.setInvariantUUID(groupDefinition.getInvariantUUID());
+ groupInstance.setDescription(groupDefinition.getDescription());
+ groupInstance.setVersion(groupDefinition.getVersion());
+ groupInstance.setArtifacts(groupDefinition.getArtifacts());
+ groupInstance.setArtifactsUuid(groupDefinition.getArtifactsUuid());
+ groupInstance.setType(groupDefinition.getType());
+ groupInstance.setGroupUUID(groupDefinition.getGroupUUID());
+
+ List<GroupInstanceProperty> groupInstanceProperties = groupDefinition.convertToGroupProperties()
+ //converts List of GroupProperties to List of GroupInstanceProperties and updates it with group instance property data
+ .stream().map(p->getUpdatedConvertedProperty(p, groupInstancePropertyValues)).collect(Collectors.toList());
+ groupInstance.convertFromGroupInstancesProperties(groupInstanceProperties);
+}
+
+ private GroupInstanceProperty getUpdatedConvertedProperty(GroupProperty groupProperty, Map<String, PropertyValueData> groupInstancePropertyValues){
+
+ GroupInstanceProperty updatedProperty = new GroupInstanceProperty(groupProperty, groupProperty.getValue());
+ if(!MapUtils.isEmpty(groupInstancePropertyValues) && groupInstancePropertyValues.containsKey(groupProperty.getName())){
+ PropertyValueData groupInstancePropertyValue = groupInstancePropertyValues.get(groupProperty.getName());
+ updatedProperty.setValue(groupInstancePropertyValue.getValue());
+ updatedProperty.setValueUniqueUid(groupInstancePropertyValue.getUniqueId());
+ }
+ return updatedProperty;
+ }
+
+ private Either<List<ImmutablePair<String, String>>, TitanOperationStatus> getGroupArtifactsPairs(String groupUniqueId) {
+
+ Either<List<ImmutablePair<String, String>>, TitanOperationStatus> result = null;
+
+ Either<List<ImmutablePair<ArtifactData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.GroupInstance), groupUniqueId, GraphEdgeLabels.GROUP_ARTIFACT_REF,
+ NodeTypeEnum.ArtifactRef, ArtifactData.class);
+ if (childrenNodes.isRight()) {
+ TitanOperationStatus status = childrenNodes.right().value();
+ if (status == TitanOperationStatus.NOT_FOUND) {
+ status = TitanOperationStatus.OK;
+ }
+ result = Either.right(status);
+
+ } else {
+
+ List<ImmutablePair<String, String>> artifactsList = new ArrayList<>();
+ List<ImmutablePair<ArtifactData, GraphEdge>> list = childrenNodes.left().value();
+ if (list != null) {
+ for (ImmutablePair<ArtifactData, GraphEdge> pair : list) {
+ ArtifactData artifactData = pair.getKey();
+ String uniqueId = artifactData.getArtifactDataDefinition().getUniqueId();
+ String UUID = artifactData.getArtifactDataDefinition().getArtifactUUID();
+ ImmutablePair<String, String> artifact = new ImmutablePair<String, String>(uniqueId, UUID);
+ artifactsList.add(artifact);
+ }
+ }
+
+ log.debug("The artifacts list related to group {} is {}",groupUniqueId,artifactsList);
+ result = Either.left(artifactsList);
+ }
+
+ return result;
+
+ }
+
+ @Override
+ public StorageOperationStatus dissociateAndAssociateGroupsInstanceFromArtifact(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact) {
+
+ StorageOperationStatus result = null;
+
+ return this.dissociateAndAssociateGroupsInstanceFromArtifactOnGraph(componentId, componentTypeEnum, oldArtifactId, newArtifact);
+
+ }
+
+ @Override
+ public StorageOperationStatus dissociateAndAssociateGroupsInstanceFromArtifactOnGraph(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact) {
+
+ Either<List<GroupInstance>, StorageOperationStatus> allGroupsFromGraph = getAllGroupInstances(componentId, componentTypeEnum);
+ if (allGroupsFromGraph.isRight()) {
+ StorageOperationStatus status = allGroupsFromGraph.right().value();
+ return status;
+ }
+
+ List<GroupInstance> allGroups = allGroupsFromGraph.left().value();
+ if (allGroups == null || allGroups.isEmpty()) {
+ return StorageOperationStatus.OK;
+ }
+
+ // Find all groups which contains this artifact id
+ List<GroupInstance> associatedGroups = allGroups.stream().filter(p -> p.getGroupInstanceArtifacts() != null && p.getGroupInstanceArtifacts().contains(oldArtifactId)).collect(Collectors.toList());
+
+ if (associatedGroups != null && false == associatedGroups.isEmpty()) {
+
+ log.debug("The groups {} contains the artifact {}",associatedGroups.stream().map(p -> p.getName()).collect(Collectors.toList()),oldArtifactId);
+
+ UniqueIdData oldArtifactData = new UniqueIdData(NodeTypeEnum.ArtifactRef, oldArtifactId);
+ UniqueIdData newArtifactData = new UniqueIdData(NodeTypeEnum.ArtifactRef, newArtifact.getArtifactDataDefinition().getUniqueId());
+ Map<String, Object> props = new HashMap<String, Object>();
+ props.put(GraphPropertiesDictionary.NAME.getProperty(), newArtifactData.getLabel());
+
+ for (GroupInstance groupDefinition : associatedGroups) {
+ UniqueIdData groupData = new UniqueIdData(NodeTypeEnum.GroupInstance, groupDefinition.getUniqueId());
+
+ Either<GraphRelation, TitanOperationStatus> deleteRelation = titanGenericDao.deleteRelation(groupData, oldArtifactData, GraphEdgeLabels.GROUP_ARTIFACT_REF);
+ log.trace("After dissociate group {} from artifact {}", groupDefinition.getName(), oldArtifactId);
+ if (deleteRelation.isRight()) {
+ TitanOperationStatus status = deleteRelation.right().value();
+ if (status == TitanOperationStatus.NOT_FOUND) {
+ status = TitanOperationStatus.INVALID_ID;
+ }
+ return DaoStatusConverter.convertTitanStatusToStorageStatus(status);
+ }
+
+ Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(groupData, newArtifactData, GraphEdgeLabels.GROUP_ARTIFACT_REF, props);
+ log.trace("After associate group {} to artifact {}", groupDefinition.getName(), newArtifact.getUniqueIdKey());
+ if (createRelation.isRight()) {
+ TitanOperationStatus status = createRelation.right().value();
+ if (status == TitanOperationStatus.NOT_FOUND) {
+ status = TitanOperationStatus.INVALID_ID;
+ }
+ return DaoStatusConverter.convertTitanStatusToStorageStatus(status);
+ }
+ }
+
+ }
+ return StorageOperationStatus.OK;
+ }
+
+ @Override
+ public Either<GroupInstance, StorageOperationStatus> updateGroupInstancePropertyValues(GroupInstance oldGroupInstance, List<GroupInstanceProperty> newProperties, Boolean inTransaction) {
+
+ Either<GroupInstance, StorageOperationStatus> updateRes = Either.left(oldGroupInstance);
+ try{
+ if(!CollectionUtils.isEmpty(newProperties)){
+ updateRes = updateGroupInstancePropertyValuesOnGraph(oldGroupInstance, newProperties);
+ }
+ }catch(Exception e){
+ log.debug("The Exception occured during update of group instance {} property values. The message is {}. ", oldGroupInstance.getName(), e.getMessage(), e);
+ updateRes = Either.right(StorageOperationStatus.GENERAL_ERROR);
+ }finally {
+ handleTransactionCommitRollback(inTransaction, updateRes);
+ }
+ return updateRes;
+ }
+
+ private Either<GroupInstance, StorageOperationStatus> updateGroupInstancePropertyValuesOnGraph( GroupInstance oldGroupInstance, List<GroupInstanceProperty> newProperties ) {
+ Either<GroupInstance, StorageOperationStatus> updateRes = null;
+ Either<Integer, StorageOperationStatus> nodeUpdateRes = null;
+ Vertex groupInstanceVertex = null;
+ Either<Vertex, StorageOperationStatus> groupInstanceVertexRes;
+ Map<String, Vertex> existingPropertyValueVertices = new HashMap<>();
+ Map<String, Vertex> existingPropertyVertices = new HashMap<>();
+ groupInstanceVertexRes = getVertexFromGraph(GraphPropertiesDictionary.UNIQUE_ID.getProperty(),oldGroupInstance.getUniqueId());
+ try{
+ if (groupInstanceVertexRes.isRight()) {
+ log.debug("Failed to fetch group instance vertex {} from graph. ", oldGroupInstance.getName());
+ updateRes = Either.right(groupInstanceVertexRes.right().value());
+ } else {
+ groupInstanceVertex = groupInstanceVertexRes.left().value();
+ findExistingPropertyValueVertices(groupInstanceVertex, existingPropertyValueVertices);
+ nodeUpdateRes = handlePropertyValues(oldGroupInstance, oldGroupInstance.getPropertyValueCounter(), newProperties, groupInstanceVertex, existingPropertyValueVertices, existingPropertyVertices);
+ if(nodeUpdateRes.isRight()){
+ log.debug("Failed to handle property values of group instance {}. ", oldGroupInstance.getName());
+ updateRes = Either.right(nodeUpdateRes.right().value());
+ } else {
+ updateRes = updateGroupInstanceVertexAndGetUpdatedGroupInstance(groupInstanceVertex, nodeUpdateRes.left().value(), oldGroupInstance);
+ }
+ }
+ } catch(Exception e){
+ log.debug("The Exception occured during update group instance {} property values on graph. The message is {}. ", oldGroupInstance.getName(), e.getMessage(), e);
+ updateRes = Either.right(StorageOperationStatus.GENERAL_ERROR);
+ }
+ return updateRes;
+ }
+
+ private Either<Integer, StorageOperationStatus> handlePropertyValues(GroupInstance oldGroupInstance, Integer propertyValueCounter, List<GroupInstanceProperty> newProperties, Vertex groupInstanceVertex,
+ Map<String, Vertex> existingPropertyValueVertices, Map<String, Vertex> existingPropertyVertices) {
+
+ Either<Integer, StorageOperationStatus> nodeHandleRes = null;
+ int currCounter = propertyValueCounter;
+ for(GroupInstanceProperty currProperty : newProperties){
+ nodeHandleRes = handlePropertyValueNode(oldGroupInstance, currCounter, currProperty, groupInstanceVertex, existingPropertyValueVertices, existingPropertyVertices);
+ if(nodeHandleRes.isRight()){
+ break;
+ }
+ currCounter = nodeHandleRes.left().value();
+ }
+ return nodeHandleRes;
+ }
+
+ private Either<GroupInstance, StorageOperationStatus> updateGroupInstanceVertexAndGetUpdatedGroupInstance( Vertex groupInstanceVertex, Integer propertyValueCounter, GroupInstance oldGroupInstance) {
+
+ TitanOperationStatus status;
+ Either<GroupInstance, StorageOperationStatus> actionResult;
+ status = updateGroupInstanceVertex(groupInstanceVertex, propertyValueCounter);
+ if(status != TitanOperationStatus.OK){
+ log.debug("Failed to update group instance {}. ", oldGroupInstance.getName());
+ actionResult = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }else{
+ Either<GroupInstance, TitanOperationStatus> updatedGroupInstanceRes = getGroupInstanceFromGraph(oldGroupInstance.getUniqueId(), false, false);
+ if(updatedGroupInstanceRes.isRight()){
+ status = updatedGroupInstanceRes.right().value();
+ log.debug("Failed to get updated group instance {}. Status is {}. ", oldGroupInstance.getName(), status);
+ actionResult = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }else{
+ actionResult = Either.left(updatedGroupInstanceRes.left().value());
+ }
+ }
+ return actionResult;
+ }
+
+ private Either<Integer, StorageOperationStatus> handlePropertyValueNode(GroupInstance oldGroupInstance, Integer propertyValueCounter, GroupInstanceProperty currProperty, Vertex groupInstanceVertex, Map<String, Vertex> existingPropertyValueVertices, Map<String, Vertex> existingPropertyVertices) {
+
+ String groupInstanceName = oldGroupInstance.getName();
+ TitanOperationStatus updateStatus;
+ TitanOperationStatus addStatus;
+ Vertex propertyValueVertex;
+ String propertyValueId;
+ propertyValueId = currProperty.getValueUniqueUid();
+ Either<Integer, StorageOperationStatus> actionResult = null;
+ if(existingPropertyValueVertices.containsKey(propertyValueId)){
+ updateStatus = updatePropertyValueVertex(existingPropertyValueVertices.get(propertyValueId), currProperty);
+ if(updateStatus != TitanOperationStatus.OK){
+ log.debug("Failed to update property value {} of group instance {}. ", currProperty.getName(), groupInstanceName);
+ actionResult = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateStatus));
+ }
+ }
+ else{
+ if(MapUtils.isEmpty(existingPropertyVertices)){
+ findExistingPropertyVertices(existingPropertyVertices, groupInstanceVertex);
+ }
+ propertyValueVertex = existingPropertyVertices.get(currProperty.getUniqueId());
+ addStatus = addPropertyValueNodeToGroupInstance(currProperty, groupInstanceVertex, propertyValueVertex, oldGroupInstance.getUniqueId(), ++propertyValueCounter);
+ if(addStatus != TitanOperationStatus.OK){
+ log.debug("Failed to add property value {} to group instance {}. ", currProperty.getName(), groupInstanceName);
+ actionResult = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(addStatus));
+ }
+ }
+ if(actionResult == null){
+ actionResult = Either.left(propertyValueCounter);
+ }
+ return actionResult;
+ }
+
+ @SuppressWarnings("unchecked")
+ private Either<Vertex, StorageOperationStatus> getVertexFromGraph(String uniqueKeyName, String uniqueId) {
+
+ Either<Vertex, StorageOperationStatus> actionResult = null;
+ try{
+ Either<TitanGraph, TitanOperationStatus> graph = titanGenericDao.getGraph();
+ Iterable<TitanVertex> vertices = null;
+ if (graph.isRight()) {
+ log.debug("Failed to get graph. Status is {}", graph.right().value());
+ actionResult = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graph.right().value()));
+ }
+ if(actionResult == null){
+ TitanGraph tGraph = graph.left().value();
+ vertices = tGraph.query().has(uniqueKeyName, uniqueId).vertices();
+ if (vertices == null || vertices.iterator() == null || !vertices.iterator().hasNext()) {
+ log.debug("Failed to get nodes from graph for type {} for id = {}", NodeTypeEnum.GroupInstance, uniqueId);
+ actionResult = Either.right(StorageOperationStatus.NOT_FOUND);
+ }
+ }
+ if(actionResult == null && vertices != null){
+ actionResult = Either.left(vertices.iterator().next());
+ }
+ } catch(Exception e){
+ log.debug("The Exception occured during get vertex {} from graph. The message is {}. ", uniqueId, e.getMessage(), e);
+ }
+ return actionResult;
+ }
+
+ private void findExistingPropertyValueVertices(Vertex groupInstanceVertex, Map<String, Vertex> existingPropertyValueVertices) {
+ Iterator<Edge> propertyValueEdges = groupInstanceVertex.edges(Direction.OUT, GraphEdgeLabels.PROPERTY_VALUE.getProperty());
+ Vertex propertyValueVertex;
+ while(propertyValueEdges.hasNext()){
+ propertyValueVertex = propertyValueEdges.next().inVertex();
+ existingPropertyValueVertices.put((String) propertyValueVertex.property(GraphPropertiesDictionary.UNIQUE_ID.getProperty()).value(), propertyValueVertex);
+ }
+ }
+
+ private void findExistingPropertyVertices(Map<String, Vertex> existingPropertyVertices, Vertex groupInstanceVertex) {
+ Vertex groupVertex = groupInstanceVertex.edges(Direction.OUT, GraphEdgeLabels.INSTANCE_OF.getProperty()).next().inVertex();
+ Vertex groupTypeVertex = groupVertex.edges(Direction.OUT, GraphEdgeLabels.TYPE_OF.getProperty()).next().inVertex();
+ Iterator<Edge> groupTypePropertiesIterator = groupTypeVertex.edges(Direction.OUT, GraphEdgeLabels.PROPERTY.getProperty());
+ while(groupTypePropertiesIterator.hasNext()){
+ Vertex propertyValueVertex = groupTypePropertiesIterator.next().inVertex();
+ existingPropertyVertices.put((String) propertyValueVertex.property(GraphPropertiesDictionary.UNIQUE_ID.getProperty()).value(), propertyValueVertex);
+ }
+ }
+
+ private TitanOperationStatus addPropertyValueNodeToGroupInstance(GroupInstanceProperty currProperty, Vertex groupInstanceVertex, Vertex propertyVertex, String groupInstanceId, int index) {
+ TitanOperationStatus status = null;
+ TitanVertex propertyValueVertex = null;
+ PropertyValueData newPropertyValue = new PropertyValueData();
+ Long creationTime = System.currentTimeMillis();
+ newPropertyValue.setModificationTime(creationTime);
+ newPropertyValue.setCreationTime(creationTime);
+ newPropertyValue.setUniqueId(UniqueIdBuilder.buildGroupPropertyValueUid(groupInstanceId, index));
+ newPropertyValue.setValue(currProperty.getValue());
+ newPropertyValue.setType(currProperty.getType());
+ Either<TitanVertex, TitanOperationStatus> propertyValueNodeRes = titanGenericDao.createNode(newPropertyValue);
+ if(propertyValueNodeRes.isRight()){
+ status = propertyValueNodeRes.right().value();
+ }
+ if(status == null){
+ propertyValueVertex = propertyValueNodeRes.left().value();
+ Map<String, Object> props = new HashMap<>();
+ props.put(GraphPropertiesDictionary.PROPERTY_NAME.getProperty(), currProperty.getName());
+ status = titanGenericDao.createEdge(groupInstanceVertex, propertyValueVertex, GraphEdgeLabels.PROPERTY_VALUE, props);
+ }
+ if(status == TitanOperationStatus.OK){
+ status = titanGenericDao.createEdge(propertyValueVertex, propertyVertex, GraphEdgeLabels.PROPERTY_IMPL, null);
+ }
+ return status;
+ }
+
+ private TitanOperationStatus updatePropertyValueVertex(Vertex propertyValueVertex, GroupInstanceProperty property) {
+ PropertyValueData propertyValue = new PropertyValueData();
+ propertyValue.setUniqueId(property.getValue());
+ propertyValue.setModificationTime(System.currentTimeMillis());
+ propertyValue.setType(property.getType());
+ propertyValue.setValue(property.getValue());
+ return titanGenericDao.updateVertex(propertyValue, propertyValueVertex);
+ }
+
+ private TitanOperationStatus updateGroupInstanceVertex(Vertex groupInstanceVertex, int propertyValueCounter) {
+ GroupInstanceData groupInstanceData = new GroupInstanceData();
+ groupInstanceData.getGroupDataDefinition().setModificationTime(System.currentTimeMillis());
+ groupInstanceData.getGroupDataDefinition().setCustomizationUUID(UUID.randomUUID().toString());
+ groupInstanceData.getGroupDataDefinition().setPropertyValueCounter(propertyValueCounter);
+ return titanGenericDao.updateVertex(groupInstanceData, groupInstanceVertex);
+ }
+
+ private Either<Map<String, PropertyValueData>, TitanOperationStatus> getAllGroupInstancePropertyValuesData(GroupInstanceData groupInstData) {
+
+ Either<Map<String, PropertyValueData>, TitanOperationStatus> result = null;
+ try{
+ Either<List<ImmutablePair<PropertyValueData, GraphEdge>>, TitanOperationStatus> getPropertyValueChildrenRes =
+ titanGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), groupInstData.getUniqueId(), GraphEdgeLabels.PROPERTY_VALUE,
+ NodeTypeEnum.PropertyValue, PropertyValueData.class, true);
+ if(getPropertyValueChildrenRes.isRight()){
+ TitanOperationStatus status = getPropertyValueChildrenRes.right().value();
+ log.debug("Failed to fetch property value nodes for group instance {}. Status is {}. ", groupInstData.getName(), status);
+ if(status == TitanOperationStatus.NOT_FOUND){
+ result = Either.left(null);
+ }else{
+ result = Either.right(status);
+ }
+ }else{
+ result = Either.left(getPropertyValueChildrenRes.left().value().stream()
+ .collect(Collectors.toMap(pair->(String)(pair.getRight().getProperties().get(GraphPropertiesDictionary.PROPERTY_NAME.getProperty())), pair->pair.getLeft())));
+ }
+ } catch(Exception e){
+ log.debug("The Exception occured during fetch group instance () property values. The message is {}. ", groupInstData.getName(), e.getMessage(), e);
+ if(result == null){
+ result = Either.right(TitanOperationStatus.GENERAL_ERROR);
+ }
+ }
+ return result;
+ }
+ @Override
+ public Either<GroupInstance, StorageOperationStatus> updateGroupInstancePropertyValues(GroupInstance groupInstance, List<GroupInstanceProperty> newProperties) {
+ return updateGroupInstancePropertyValues(groupInstance, newProperties, false);
+ }
+}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupOperation.java
index 9312be45c1..52bcae36db 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupOperation.java
@@ -25,8 +25,11 @@ 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.lang.StringUtils;
+import org.apache.commons.lang3.math.NumberUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
@@ -44,6 +47,7 @@ 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.PropertyDefinition;
+import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
import org.openecomp.sdc.be.model.operations.api.IGroupOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
@@ -57,6 +61,7 @@ import org.openecomp.sdc.be.resources.data.PropertyValueData;
import org.openecomp.sdc.be.resources.data.ResourceMetadataData;
import org.openecomp.sdc.be.resources.data.ServiceMetadataData;
import org.openecomp.sdc.be.resources.data.UniqueIdData;
+import org.openecomp.sdc.common.datastructure.Wrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@@ -82,15 +87,16 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
@javax.annotation.Resource
private ApplicationDataTypeCache dataTypeCache;
+ @javax.annotation.Resource
+ protected ResourceOperation resourceOperation;
+
@Override
- public Either<GroupData, TitanOperationStatus> addGroupToGraph(NodeTypeEnum nodeTypeEnum, String componentId,
- GroupDefinition groupDefinition) {
+ public Either<GroupData, TitanOperationStatus> addGroupToGraph(NodeTypeEnum nodeTypeEnum, String componentId, GroupDefinition groupDefinition) {
String groupTypeUid = groupDefinition.getTypeUid();
if (groupTypeUid == null) {
- BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, "Group type id is empty",
- ErrorSeverity.ERROR);
+ BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, "Group type id is empty", ErrorSeverity.ERROR);
return Either.right(TitanOperationStatus.INVALID_ID);
}
@@ -112,41 +118,35 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
TitanOperationStatus status = null;
// Adding group data node to graph
log.debug("Before adding group to graph {}", groupData.toString());
- Either<GroupData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(groupData,
- GroupData.class);
+ Either<GroupData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(groupData, GroupData.class);
log.debug("After adding group to graph {}", groupData.toString());
if (createNodeResult.isRight()) {
status = createNodeResult.right().value();
- log.error("Failed to add group {} to graph. Status is {}", groupDefinition.getName(), status);
+ log.error("Failed to add group {} to graph. status is {}", groupDefinition.getName(), status);
return Either.right(status);
}
// Associate group to group type
log.debug("Going to associate group {} to its groupType {}", groupDefinition.getName(), groupDefinition.getType());
- Either<GraphRelation, TitanOperationStatus> associateGroupTypeRes = associateGroupToGroupType(groupData,
- groupTypeUid);
- log.debug("After associating group {} to its groupType {}. Status is {}", groupDefinition.getName(), groupDefinition.getType(), associateGroupTypeRes);
+ Either<GraphRelation, TitanOperationStatus> associateGroupTypeRes = associateGroupToGroupType(groupData, groupTypeUid);
+ log.debug("After associating group {} to its groupType {}. status is {}", groupDefinition.getName(), groupDefinition.getType(), associateGroupTypeRes);
if (associateGroupTypeRes.isRight()) {
status = associateGroupTypeRes.right().value();
- String description = "Failed to associate group " + groupDefinition.getName() + " to its groupType "
- + groupDefinition.getType() + " in graph.";
+ String description = "Failed to associate group " + groupDefinition.getName() + " to its groupType " + groupDefinition.getType() + " in graph.";
BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, ErrorSeverity.ERROR);
return Either.right(status);
}
// Associate group to component RESOURCE/SERVICE/PRODUCT
- Either<GraphRelation, TitanOperationStatus> associateComponentRes = associateGroupToComponent(groupData,
- nodeTypeEnum, componentId);
+ Either<GraphRelation, TitanOperationStatus> associateComponentRes = associateGroupToComponent(groupData, nodeTypeEnum, componentId);
if (associateComponentRes.isRight()) {
status = associateComponentRes.right().value();
- String description = "Failed to associate group " + groupDefinition.getName() + " to "
- + nodeTypeEnum.getName() + " " + componentId + ". status is " + status;
+ String description = "Failed to associate group " + groupDefinition.getName() + " to " + nodeTypeEnum.getName() + " " + componentId + ". status is " + status;
BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, ErrorSeverity.ERROR);
return Either.right(status);
}
- Either<GroupTypeDefinition, TitanOperationStatus> groupTypeRes = groupTypeOperation
- .getGroupTypeByUid(groupDefinition.getTypeUid());
+ Either<GroupTypeDefinition, TitanOperationStatus> groupTypeRes = groupTypeOperation.getGroupTypeByUid(groupDefinition.getTypeUid());
if (groupTypeRes.isRight()) {
TitanOperationStatus operationStatus = groupTypeRes.right().value();
log.debug("Failed to find group type {}", groupDefinition.getTypeUid());
@@ -164,18 +164,16 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
// points to the parent unique id
// Adding properties to group
- List<GroupProperty> properties = groupDefinition.getProperties();
+ List<GroupProperty> properties = groupDefinition.convertToGroupProperties();
if (properties != null && false == properties.isEmpty()) {
if (groupTypeProperties == null || true == groupTypeProperties.isEmpty()) {
- BeEcompErrorManager.getInstance().logInvalidInputError(ADDING_GROUP,
- "group type does not have properties", ErrorSeverity.INFO);
+ BeEcompErrorManager.getInstance().logInvalidInputError(ADDING_GROUP, "group type does not have properties", ErrorSeverity.INFO);
return Either.right(TitanOperationStatus.MATCH_NOT_FOUND);
}
- Map<String, PropertyDefinition> groupTypePropertiesMap = groupTypeProperties.stream()
- .collect(Collectors.toMap(p -> p.getName(), p -> p));
+ Map<String, PropertyDefinition> groupTypePropertiesMap = groupTypeProperties.stream().collect(Collectors.toMap(p -> p.getName(), p -> p));
Either<PropertyValueData, TitanOperationStatus> addPropertyResult = null;
int i = 1;
@@ -183,10 +181,8 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
addPropertyResult = addPropertyToGroup(groupData, prop, groupTypePropertiesMap.get(prop.getName()), i);
if (addPropertyResult.isRight()) {
status = addPropertyResult.right().value();
- String description = "Failed to associate group " + groupData.getUniqueId() + " to property "
- + prop.getName() + " in graph. Status is " + status;
- BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description,
- ErrorSeverity.ERROR);
+ String description = "Failed to associate group " + groupData.getUniqueId() + " to property " + prop.getName() + " in graph. Status is " + status;
+ BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, ErrorSeverity.ERROR);
return Either.right(status);
}
i++;
@@ -196,41 +192,22 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
// Associate artifacts to group
List<String> artifacts = groupDefinition.getArtifacts();
- Either<GroupDefinition, TitanOperationStatus> associateArtifactsToGroupOnGraph = associateArtifactsToGroupOnGraph(
- groupData.getGroupDataDefinition().getUniqueId(), artifacts);
- if (associateArtifactsToGroupOnGraph.isRight()
- && associateArtifactsToGroupOnGraph.right().value() != TitanOperationStatus.OK) {
+ Either<GroupDefinition, TitanOperationStatus> associateArtifactsToGroupOnGraph = associateArtifactsToGroupOnGraph(groupData.getGroupDataDefinition().getUniqueId(), artifacts);
+ if (associateArtifactsToGroupOnGraph.isRight() && associateArtifactsToGroupOnGraph.right().value() != TitanOperationStatus.OK) {
return Either.right(status);
}
/*
- * Either<GraphRelation, TitanOperationStatus> addArtifactsRefResult =
- * null; if (artifacts != null) { for (String artifactId : artifacts) {
- * Either<ArtifactData, TitanOperationStatus> findArtifactRes =
- * titanGenericDao .getNode(UniqueIdBuilder
- * .getKeyByNodeType(NodeTypeEnum.ArtifactRef), artifactId,
- * ArtifactData.class); if (findArtifactRes.isRight()) { status =
- * findArtifactRes.right().value(); if (status ==
- * TitanOperationStatus.NOT_FOUND) { status =
- * TitanOperationStatus.INVALID_ID; } String description =
- * "Failed to associate group " + groupData.getUniqueId() +
- * " to artifact " + artifactId + " in graph. Status is " + status;
- * BeEcompErrorManager.getInstance().logInternalFlowError( ADDING_GROUP,
- * description, ErrorSeverity.ERROR); return Either.right(status); }
+ * Either<GraphRelation, TitanOperationStatus> addArtifactsRefResult = null; if (artifacts != null) { for (String artifactId : artifacts) { Either<ArtifactData, TitanOperationStatus> findArtifactRes = titanGenericDao .getNode(UniqueIdBuilder
+ * .getKeyByNodeType(NodeTypeEnum.ArtifactRef), artifactId, ArtifactData.class); if (findArtifactRes.isRight()) { status = findArtifactRes.right().value(); if (status == TitanOperationStatus.NOT_FOUND) { status =
+ * TitanOperationStatus.INVALID_ID; } String description = "Failed to associate group " + groupData.getUniqueId() + " to artifact " + artifactId + " in graph. Status is " + status; BeEcompErrorManager.getInstance().logInternalFlowError(
+ * ADDING_GROUP, description, ErrorSeverity.ERROR); return Either.right(status); }
*
- * Map<String, Object> props = new HashMap<String, Object>();
- * props.put(GraphPropertiesDictionary.NAME.getProperty(),
- * findArtifactRes.left().value().getLabel());
+ * Map<String, Object> props = new HashMap<String, Object>(); props.put(GraphPropertiesDictionary.NAME.getProperty(), findArtifactRes.left().value().getLabel());
*
- * addArtifactsRefResult = titanGenericDao.createRelation( groupData,
- * findArtifactRes.left().value(), GraphEdgeLabels.GROUP_ARTIFACT_REF,
- * props);
+ * addArtifactsRefResult = titanGenericDao.createRelation( groupData, findArtifactRes.left().value(), GraphEdgeLabels.GROUP_ARTIFACT_REF, props);
*
- * if (addArtifactsRefResult.isRight()) { status =
- * addArtifactsRefResult.right().value(); String description =
- * "Failed to associate group " + groupData.getUniqueId() +
- * " to artifact " + artifactId + " in graph. Status is " + status;
- * BeEcompErrorManager.getInstance().logInternalFlowError( ADDING_GROUP,
- * description, ErrorSeverity.ERROR); return Either.right(status); } } }
+ * if (addArtifactsRefResult.isRight()) { status = addArtifactsRefResult.right().value(); String description = "Failed to associate group " + groupData.getUniqueId() + " to artifact " + artifactId + " in graph. Status is " + status;
+ * BeEcompErrorManager.getInstance().logInternalFlowError( ADDING_GROUP, description, ErrorSeverity.ERROR); return Either.right(status); } } }
*/
// Associate group to members
@@ -243,31 +220,24 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
if (member.getValue() == null || member.getValue().isEmpty()) {
continue;
}
- Either<ComponentInstanceData, TitanOperationStatus> findComponentInstanceRes = titanGenericDao.getNode(
- UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), member.getValue(),
- ComponentInstanceData.class);
+ Either<ComponentInstanceData, TitanOperationStatus> findComponentInstanceRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), member.getValue(), ComponentInstanceData.class);
if (findComponentInstanceRes.isRight()) {
status = findComponentInstanceRes.right().value();
if (status == TitanOperationStatus.NOT_FOUND) {
status = TitanOperationStatus.INVALID_ID;
}
- String description = "Failed to find to find member of group " + member.getValue()
- + " in graph. Status is " + status;
- BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description,
- ErrorSeverity.ERROR);
+ String description = "Failed to find to find member of group " + member.getValue() + " in graph. Status is " + status;
+ BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, ErrorSeverity.ERROR);
return Either.right(status);
}
Map<String, Object> props = new HashMap<String, Object>();
props.put(GraphPropertiesDictionary.NAME.getProperty(), member.getKey());
- addMembersRefResult = titanGenericDao.createRelation(groupData, findComponentInstanceRes.left().value(),
- GraphEdgeLabels.GROUP_MEMBER, props);
+ addMembersRefResult = titanGenericDao.createRelation(groupData, findComponentInstanceRes.left().value(), GraphEdgeLabels.GROUP_MEMBER, props);
if (addMembersRefResult.isRight()) {
status = addMembersRefResult.right().value();
- String description = "Failed to associate group " + groupData.getUniqueId()
- + " to component instance " + member.getValue() + " in graph. Status is " + status;
- BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description,
- ErrorSeverity.ERROR);
+ String description = "Failed to associate group " + groupData.getUniqueId() + " to component instance " + member.getValue() + " in graph. Status is " + status;
+ BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, ErrorSeverity.ERROR);
return Either.right(status);
}
}
@@ -275,8 +245,221 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
return Either.left(groupData);
}
+
+ private Either<PropertyDefinition, TitanOperationStatus> getPropertyDefFromGroupType(GroupProperty groupProperty) {
+ Either<PropertyDefinition, TitanOperationStatus> ret;
+ Either<GroupTypeDefinition, TitanOperationStatus> groupTypeRes = groupTypeOperation
+ .getGroupTypeByUid(groupProperty.getParentUniqueId());
+ if (groupTypeRes.isRight()) {
+ TitanOperationStatus operationStatus = groupTypeRes.right().value();
+ log.debug("Failed to find group type {}", groupProperty.getParentUniqueId());
+ if (operationStatus == TitanOperationStatus.NOT_FOUND) {
+ ret = Either.right(TitanOperationStatus.INVALID_ID);
+ } else {
+ ret = Either.right(operationStatus);
+ }
+ } else {
+ GroupTypeDefinition groupTypeDefinition = groupTypeRes.left().value();
+ List<PropertyDefinition> groupTypeProperties = groupTypeDefinition.getProperties();
+
+ Map<String, PropertyDefinition> groupTypePropertiesMap = groupTypeProperties.stream()
+ .collect(Collectors.toMap(p -> p.getName(), p -> p));
+ if (groupTypeProperties == null || true == groupTypeProperties.isEmpty()) {
+ BeEcompErrorManager.getInstance().logInvalidInputError(ADDING_GROUP,
+ "group type does not have properties", ErrorSeverity.INFO);
+ ret = Either.right(TitanOperationStatus.MATCH_NOT_FOUND);
+ } else {
+ PropertyDefinition propertyDefinition = groupTypePropertiesMap.get(groupProperty.getName());
+ ret = Either.left(propertyDefinition);
+ }
+ }
+ return ret;
+ }
+
+ /**
+ * Updates GroupProperty Value
+ * @param componentId TODO
+ * @param groupId TODO
+ * @param groupProperties
+ * @param inTransaction TODO
+ *
+ * @return
+ */
+ public Either<List<GroupProperty>, StorageOperationStatus> updateGroupProperties(String componentId,
+ String groupId, List<GroupProperty> groupProperties, boolean inTransaction) {
+
+ Wrapper<Long> lastUpdateTimeWrapper = new Wrapper<>();
+ TitanOperationStatus titanStatus = TitanOperationStatus.OK;
+ Either<List<GroupProperty>, StorageOperationStatus> result = null;
+ //Get Group Data
+ final GroupData groupData;
+ Either<GroupData, TitanOperationStatus> eitherGroupData = titanGenericDao
+ .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Group), groupId, GroupData.class);
+ if( eitherGroupData.isRight() ){
+ log.debug("Error: Could not fetch group with groupId = {}", groupId);
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(eitherGroupData.right().value()));
+ }
+ else{
+ groupData = eitherGroupData.left().value();
+ }
+
+ try {
+ Optional<TitanOperationStatus> optionalError =
+ //Stream of group properties to be updated
+ groupProperties.stream().
+ //updating each property and mapping to the TitanOperationStatus
+ map(e -> updateGroupProperty(e, groupData, lastUpdateTimeWrapper)).
+ //filtering in errors if there are such
+ filter( e -> e != TitanOperationStatus.OK).
+ //collect
+ findFirst();
+ if( optionalError.isPresent() ){
+ titanStatus = optionalError.get();
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(titanStatus));
+ }
+ else{
+ result = updateLastModificationTimeOnVf(componentId, groupId, groupProperties, lastUpdateTimeWrapper);
+ }
+
+ }
+ finally {
+ handleTransactionCommitRollback(inTransaction, result);
+ }
+
+ return result;
+ }
+
+ private Either<List<GroupProperty>, StorageOperationStatus> updateLastModificationTimeOnVf(String componentId,
+ String groupId, List<GroupProperty> groupProperties, Wrapper<Long> lastUpdateTimeWrapper) {
+ Either<List<GroupProperty>, StorageOperationStatus> result;
+ Either<Resource, StorageOperationStatus> eitherResource = resourceOperation.getResource(componentId);
+ if( eitherResource.isRight() ){
+ result = Either.right(eitherResource.right().value());
+ }
+ else{
+ Either<ComponentMetadataData, StorageOperationStatus> eitherLastUpdateDateUpdatedOnResource = resourceOperation
+ .updateComponentLastUpdateDateOnGraph(eitherResource.left().value(), NodeTypeEnum.Resource,
+ lastUpdateTimeWrapper.getInnerElement(), true);
+ if (eitherLastUpdateDateUpdatedOnResource.isLeft()) {
+
+ groupProperties =
+ //Group Stream From VF
+ eitherResource.left().value().getGroups().stream().
+ //Filter in Only the relevant group
+ filter( e -> e.getUniqueId().equals(groupId)).
+ //Get it
+ findAny().get().
+ //Get Group Properties from it
+ convertToGroupProperties();
+
+ result = Either.left(groupProperties);
+ }
+ else{
+ result = Either.right(eitherLastUpdateDateUpdatedOnResource.right().value());
+ }
+ }
+ return result;
+ }
+
+
+ private TitanOperationStatus updateGroupProperty(GroupProperty groupProperty, GroupData groupData,
+ Wrapper<Long> lastUpdateTimeWrapper) {
+ TitanOperationStatus titanStatus = TitanOperationStatus.OK;
+ // PropertyValueData node does not exist
+ if (StringUtils.isEmpty(groupProperty.getValueUniqueUid())) {
+ // create new node
+ if (!StringUtils.isEmpty(groupProperty.getValue())) {
+ // Value does not exit and was not updated as well. no need
+ // to do anything
+ } else {
+ titanStatus = addGroupPropertyToGraph(groupProperty, groupData, lastUpdateTimeWrapper);
- private Either<PropertyValueData, TitanOperationStatus> addPropertyToGroup(GroupData groupData,
+ }
+ }
+
+ else {
+ titanStatus = updateGroupPropertyInGraph(groupProperty, lastUpdateTimeWrapper);
+ }
+ return titanStatus;
+ }
+
+ private TitanOperationStatus updateGroupPropertyInGraph(GroupProperty groupProperty,
+ Wrapper<Long> lastUpdateTimeWrapper) {
+ TitanOperationStatus titanStatus;
+ Either<PropertyValueData, TitanOperationStatus> eitherGroupPropertyValue = titanGenericDao.getNode(
+ UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.PropertyValue), groupProperty.getValueUniqueUid(),
+ PropertyValueData.class);
+ if (eitherGroupPropertyValue.isRight()) {
+
+ titanStatus = eitherGroupPropertyValue.right().value();
+
+ } else {
+ PropertyValueData groupPropertyValue = eitherGroupPropertyValue.left().value();
+ // Actual Update only if value changed
+ if (!StringUtils.equals(groupPropertyValue.getValue(), groupProperty.getValue())) {
+ long modificationTime = lastUpdateTimeWrapper.isEmpty() ? System.currentTimeMillis()
+ : lastUpdateTimeWrapper.getInnerElement();
+ groupPropertyValue.setValue(groupProperty.getValue());
+ groupPropertyValue.setModificationTime(modificationTime);
+ Either<PropertyValueData, TitanOperationStatus> eitherUpdateNode = titanGenericDao
+ .updateNode(groupPropertyValue, PropertyValueData.class);
+ if( eitherUpdateNode.isLeft() ){
+ titanStatus = TitanOperationStatus.OK;
+ lastUpdateTimeWrapper.setInnerElement(modificationTime);
+ }
+ else{
+ titanStatus = eitherUpdateNode.right().value();
+ }
+
+ } else {
+ titanStatus = TitanOperationStatus.OK;
+ }
+ }
+ return titanStatus;
+ }
+
+ private TitanOperationStatus addGroupPropertyToGraph(GroupProperty groupProperty, GroupData groupData,
+ Wrapper<Long> lastUpdateTimeWrapper) {
+ PropertyDefinition propertyDefinition = null;
+ TitanOperationStatus ret = TitanOperationStatus.OK;
+ if (ret == TitanOperationStatus.OK) {
+ Either<PropertyDefinition, TitanOperationStatus> eitherPropertyDefFromGroupType = getPropertyDefFromGroupType(
+ groupProperty);
+ if (eitherPropertyDefFromGroupType.isRight()) {
+ log.debug("Error: Could not fetch group property from group Type with groupTypeId = {}",
+ groupProperty.getParentUniqueId());
+ ret = eitherPropertyDefFromGroupType.right().value();
+ } else {
+ propertyDefinition = eitherPropertyDefFromGroupType.left().value();
+ }
+ }
+ if (ret == TitanOperationStatus.OK){
+ final int groupPropCounter = groupData.getGroupDataDefinition().getPropertyValueCounter() + NumberUtils.INTEGER_ONE;
+ Either<PropertyValueData, TitanOperationStatus> eitherAddPropertyToGroup = addPropertyToGroup(groupData,
+ groupProperty, propertyDefinition, groupPropCounter);
+
+ if( eitherAddPropertyToGroup.isLeft() ){
+ ret = TitanOperationStatus.OK;
+ if( lastUpdateTimeWrapper.isEmpty() ){
+ lastUpdateTimeWrapper.setInnerElement(eitherAddPropertyToGroup.left().value().getCreationTime());
+ }
+ }
+ else{
+ ret = eitherAddPropertyToGroup.right().value();
+ }
+ if( ret == TitanOperationStatus.OK){
+ groupData.getGroupDataDefinition().setPropertyValueCounter(groupPropCounter);
+ Either<GroupData, TitanOperationStatus> updateNode = titanGenericDao .updateNode(groupData, GroupData.class);
+ if( updateNode.isRight() ){
+ ret = updateNode.right().value();
+ }
+ }
+
+ }
+ return ret;
+ }
+
+ public Either<PropertyValueData, TitanOperationStatus> addPropertyToGroup(GroupData groupData,
GroupProperty groupProperty, PropertyDefinition prop, Integer index) {
if (prop == null) {
@@ -312,15 +495,13 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
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);
+ BeEcompErrorManager.getInstance().logInternalFlowError("AddPropertyToGroup", "Failed to add property to group. Status is " + status, ErrorSeverity.ERROR);
return Either.right(status);
}
log.debug("Before validateAndUpdatePropertyValue");
- Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, value,
- innerType, allDataTypes.left().value());
+ Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, value, innerType, allDataTypes.left().value());
log.debug("After validateAndUpdatePropertyValue. isValid = {}", isValid);
String newValue = value;
@@ -341,9 +522,8 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
propertyValueData.setUniqueId(uniqueId);
propertyValueData.setValue(newValue);
- log.debug("Before adding property value to graph {}",propertyValueData);
- Either<PropertyValueData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(propertyValueData,
- PropertyValueData.class);
+ log.debug("Before adding property value to graph {}", propertyValueData);
+ Either<PropertyValueData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(propertyValueData, PropertyValueData.class);
log.debug("After adding property value to graph {}", propertyValueData);
if (createNodeResult.isRight()) {
@@ -351,24 +531,20 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
return Either.right(operationStatus);
}
- Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(propertyValueData,
- propertyData, GraphEdgeLabels.PROPERTY_IMPL, null);
+ Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(propertyValueData, propertyData, GraphEdgeLabels.PROPERTY_IMPL, null);
if (createRelResult.isRight()) {
TitanOperationStatus operationStatus = createRelResult.right().value();
- String description = "Failed to associate property value " + uniqueId + " to property " + propertyId
- + " in graph. status is " + operationStatus;
+ String description = "Failed to associate property value " + uniqueId + " to property " + propertyId + " in graph. status is " + operationStatus;
BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, ErrorSeverity.ERROR);
return Either.right(operationStatus);
}
- createRelResult = titanGenericDao.createRelation(groupData, propertyValueData, GraphEdgeLabels.PROPERTY_VALUE,
- null);
+ createRelResult = titanGenericDao.createRelation(groupData, propertyValueData, GraphEdgeLabels.PROPERTY_VALUE, null);
if (createRelResult.isRight()) {
TitanOperationStatus operationStatus = createNodeResult.right().value();
- String description = "Failed to associate group " + groupData.getGroupDataDefinition().getName()
- + " to property value " + uniqueId + " in graph. Status is " + operationStatus;
+ String description = "Failed to associate group " + groupData.getGroupDataDefinition().getName() + " to property value " + uniqueId + " in graph. Status is " + operationStatus;
BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, ErrorSeverity.ERROR);
return Either.right(operationStatus);
}
@@ -376,16 +552,14 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
return Either.left(createNodeResult.left().value());
}
- private Either<GraphRelation, TitanOperationStatus> associateGroupToComponent(GroupData groupData,
- NodeTypeEnum nodeTypeEnum, String componentId) {
+ private Either<GraphRelation, TitanOperationStatus> associateGroupToComponent(GroupData groupData, NodeTypeEnum nodeTypeEnum, String componentId) {
UniqueIdData componentIdData = new UniqueIdData(nodeTypeEnum, componentId);
- log.debug("Before associating component {} to group {}.", componentId, groupData);
+ log.debug("Before associating component {} to group {}", componentId, groupData);
Map<String, Object> props = new HashMap<String, Object>();
props.put(GraphPropertiesDictionary.NAME.getProperty(), groupData.getGroupDataDefinition().getName());
- Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(componentIdData,
- groupData, GraphEdgeLabels.GROUP, props);
- log.debug("After associating component {} to group {}. Status is {}", componentId, groupData, createRelResult);
+ Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(componentIdData, groupData, GraphEdgeLabels.GROUP, props);
+ log.debug("After associating component {} to group {}. status is {}", componentId, groupData, createRelResult);
if (createRelResult.isRight()) {
TitanOperationStatus operationStatus = createRelResult.right().value();
log.debug("Failed to associate component {} to group {} in graph. Status is {}", componentId, groupData, operationStatus);
@@ -395,18 +569,13 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
return Either.left(createRelResult.left().value());
}
- private Either<GraphRelation, TitanOperationStatus> associateGroupToGroupType(GroupData groupData,
- String groupTypeUid) {
+ private Either<GraphRelation, TitanOperationStatus> associateGroupToGroupType(GroupData groupData, String groupTypeUid) {
UniqueIdData groupTypeIdData = new UniqueIdData(NodeTypeEnum.GroupType, groupTypeUid);
- log.debug("Before associating {} to group type {} (uid = {}).", groupData, groupData.getGroupDataDefinition().getType(), groupTypeUid);
- Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(groupData,
- groupTypeIdData, GraphEdgeLabels.TYPE_OF, null);
-
- if (log.isDebugEnabled()) {
- log.debug("After associating {} to group type {} (uid = {}). Result is {}", groupData, groupData.getGroupDataDefinition().getType(), groupTypeUid, createRelResult);
- }
+ log.debug("Before associating {} to group type {} (uid = {})", groupData, groupData.getGroupDataDefinition().getType(), groupTypeUid);
+ Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(groupData, groupTypeIdData, GraphEdgeLabels.TYPE_OF, null);
+ log.debug("After associating {} to group type {} (uid = {}). Result is {}", groupData, groupData.getGroupDataDefinition().getType(), groupTypeUid, createRelResult);
if (createRelResult.isRight()) {
TitanOperationStatus operationStatus = createRelResult.right().value();
return Either.right(operationStatus);
@@ -415,19 +584,16 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
}
@Override
- public Either<GroupDefinition, StorageOperationStatus> addGroup(NodeTypeEnum nodeTypeEnum, String componentId,
- GroupDefinition groupDefinition) {
+ public Either<GroupDefinition, StorageOperationStatus> addGroup(NodeTypeEnum nodeTypeEnum, String componentId, GroupDefinition groupDefinition) {
return addGroup(nodeTypeEnum, componentId, groupDefinition, false);
}
@Override
- public Either<GroupDefinition, StorageOperationStatus> addGroup(NodeTypeEnum nodeTypeEnum, String componentId,
- GroupDefinition groupDefinition, boolean inTransaction) {
+ public Either<GroupDefinition, StorageOperationStatus> addGroup(NodeTypeEnum nodeTypeEnum, String componentId, GroupDefinition groupDefinition, boolean inTransaction) {
Either<GroupDefinition, StorageOperationStatus> result = null;
try {
- Either<GroupData, TitanOperationStatus> addGroupRes = addGroupToGraph(nodeTypeEnum, componentId,
- groupDefinition);
+ Either<GroupData, TitanOperationStatus> addGroupRes = addGroupToGraph(nodeTypeEnum, componentId, groupDefinition);
if (addGroupRes.isRight()) {
TitanOperationStatus status = addGroupRes.right().value();
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
@@ -506,52 +672,6 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
}
/**
- * get the list of artifacts related to a given group
- *
- * @param groupUniqueId
- * @return
- */
- // private Either<List<String>, TitanOperationStatus> getGroupArtifacts(
- // String groupUniqueId) {
- //
- // Either<List<String>, TitanOperationStatus> result = null;
- //
- // Either<List<ImmutablePair<ArtifactData, GraphEdge>>,
- // TitanOperationStatus> childrenNodes = titanGenericDao
- // .getChildrenNodes(
- // UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Group),
- // groupUniqueId, GraphEdgeLabels.GROUP_ARTIFACT_REF,
- // NodeTypeEnum.ArtifactRef, ArtifactData.class);
- // if (childrenNodes.isRight()) {
- // TitanOperationStatus status = childrenNodes.right().value();
- // if (status == TitanOperationStatus.NOT_FOUND) {
- // status = TitanOperationStatus.OK;
- // }
- // result = Either.right(status);
- //
- // } else {
- //
- // List<String> artifactsList = new ArrayList<>();
- // List<ImmutablePair<ArtifactData, GraphEdge>> list = childrenNodes
- // .left().value();
- // if (list != null) {
- // for (ImmutablePair<ArtifactData, GraphEdge> pair : list) {
- // ArtifactData artifactData = pair.getKey();
- // String uniqueId = artifactData.getArtifactDataDefinition()
- // .getUniqueId();
- // artifactsList.add(uniqueId);
- // }
- // }
- //
- // log.debug("The artifacts list related to group {} is {}", groupUniqueId, artifactsList);
- // result = Either.left(artifactsList);
- // }
- //
- // return result;
- //
- // }
-
- /**
* get members of group
*
* @param groupUniqueId
@@ -561,9 +681,8 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
Either<Map<String, String>, TitanOperationStatus> result = null;
- Either<List<ImmutablePair<ComponentInstanceData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao
- .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Group), groupUniqueId,
- GraphEdgeLabels.GROUP_MEMBER, NodeTypeEnum.ResourceInstance, ComponentInstanceData.class);
+ Either<List<ImmutablePair<ComponentInstanceData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Group), groupUniqueId, GraphEdgeLabels.GROUP_MEMBER,
+ NodeTypeEnum.ResourceInstance, ComponentInstanceData.class);
if (childrenNodes.isRight()) {
TitanOperationStatus status = childrenNodes.right().value();
@@ -594,23 +713,20 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
public Either<GroupTypeDefinition, TitanOperationStatus> getGroupTypeOfGroup(String groupUniqueId) {
- Either<ImmutablePair<GroupTypeData, GraphEdge>, TitanOperationStatus> groupTypeRes = titanGenericDao.getChild(
- UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Group), groupUniqueId, GraphEdgeLabels.TYPE_OF,
- NodeTypeEnum.GroupType, GroupTypeData.class);
+ Either<ImmutablePair<GroupTypeData, GraphEdge>, TitanOperationStatus> groupTypeRes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Group), groupUniqueId, GraphEdgeLabels.TYPE_OF, NodeTypeEnum.GroupType,
+ GroupTypeData.class);
if (groupTypeRes.isRight()) {
TitanOperationStatus status = groupTypeRes.right().value();
log.debug("Cannot find group type associated with capability {}. Status is {}", groupUniqueId, status);
- BeEcompErrorManager.getInstance().logBeFailedFindAssociationError("Fetch Group type",
- NodeTypeEnum.GroupType.getName(), groupUniqueId, String.valueOf(status));
+ BeEcompErrorManager.getInstance().logBeFailedFindAssociationError("Fetch Group type", NodeTypeEnum.GroupType.getName(), groupUniqueId, String.valueOf(status));
return Either.right(groupTypeRes.right().value());
}
GroupTypeData groupTypeData = groupTypeRes.left().value().getKey();
- Either<GroupTypeDefinition, TitanOperationStatus> groupTypeByUid = groupTypeOperation
- .getGroupTypeByUid(groupTypeData.getGroupTypeDataDefinition().getUniqueId());
+ Either<GroupTypeDefinition, TitanOperationStatus> groupTypeByUid = groupTypeOperation.getGroupTypeByUid(groupTypeData.getGroupTypeDataDefinition().getUniqueId());
return groupTypeByUid;
@@ -644,19 +760,16 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
return Either.right(TitanOperationStatus.OK);
}
- Map<String, PropertyDefinition> uidToPropDefMap = groupTypeProperties.stream()
- .collect(Collectors.toMap(p -> p.getUniqueId(), p -> p));
+ Map<String, PropertyDefinition> uidToPropDefMap = groupTypeProperties.stream().collect(Collectors.toMap(p -> p.getUniqueId(), p -> p));
// Find all properties values on the group
- Either<List<ImmutablePair<PropertyValueData, GraphEdge>>, TitanOperationStatus> propertyImplNodes = titanGenericDao
- .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Group), groupUid,
- GraphEdgeLabels.PROPERTY_VALUE, NodeTypeEnum.PropertyValue, PropertyValueData.class);
+ Either<List<ImmutablePair<PropertyValueData, GraphEdge>>, TitanOperationStatus> propertyImplNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Group), groupUid, GraphEdgeLabels.PROPERTY_VALUE,
+ NodeTypeEnum.PropertyValue, PropertyValueData.class);
if (propertyImplNodes.isRight()) {
TitanOperationStatus status = propertyImplNodes.right().value();
if (status == TitanOperationStatus.NOT_FOUND) {
- groupPropertiesList = groupTypeProperties.stream()
- .map(p -> new GroupProperty(p, p.getDefaultValue(), null)).collect(Collectors.toList());
+ groupPropertiesList = groupTypeProperties.stream().map(p -> new GroupProperty(p, p.getDefaultValue(), null)).collect(Collectors.toList());
return Either.left(groupPropertiesList);
} else {
return Either.right(status);
@@ -676,9 +789,8 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
String propertyValueUid = propertyValueData.getUniqueId();
String value = propertyValueData.getValue();
- Either<ImmutablePair<PropertyData, GraphEdge>, TitanOperationStatus> propertyDefRes = titanGenericDao
- .getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.PropertyValue), propertyValueUid,
- GraphEdgeLabels.PROPERTY_IMPL, NodeTypeEnum.Property, PropertyData.class);
+ Either<ImmutablePair<PropertyData, GraphEdge>, TitanOperationStatus> propertyDefRes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.PropertyValue), propertyValueUid, GraphEdgeLabels.PROPERTY_IMPL,
+ NodeTypeEnum.Property, PropertyData.class);
if (propertyDefRes.isRight()) {
TitanOperationStatus status = propertyDefRes.right().value();
if (status == TitanOperationStatus.NOT_FOUND) {
@@ -704,8 +816,7 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
// Find all properties which does not have property value on the group.
List<GroupProperty> leftProps = groupTypeProperties.stream()
// filter out the group type properties which already processed
- .filter(p -> false == processedProps.contains(p.getUniqueId()))
- .map(p -> new GroupProperty(p, p.getDefaultValue(), null)).collect(Collectors.toList());
+ .filter(p -> false == processedProps.contains(p.getUniqueId())).map(p -> new GroupProperty(p, p.getDefaultValue(), null)).collect(Collectors.toList());
if (leftProps != null) {
groupPropertiesList.addAll(leftProps);
}
@@ -713,28 +824,24 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
return Either.left(groupPropertiesList);
}
- public Either<List<GroupDefinition>, TitanOperationStatus> getAllGroupsFromGraph(String componentId,
- NodeTypeEnum componentTypeEnum) {
+ public Either<List<GroupDefinition>, TitanOperationStatus> getAllGroupsFromGraph(String componentId, NodeTypeEnum componentTypeEnum) {
return getAllGroupsFromGraph(componentId, componentTypeEnum, false, false, false);
}
@Override
- public Either<List<GroupDefinition>, StorageOperationStatus> getAllGroups(String componentId,
- NodeTypeEnum compTypeEnum, boolean inTransaction) {
+ public Either<List<GroupDefinition>, StorageOperationStatus> getAllGroups(String componentId, NodeTypeEnum compTypeEnum, boolean inTransaction) {
Either<List<GroupDefinition>, StorageOperationStatus> result = null;
try {
- Either<List<GroupDefinition>, TitanOperationStatus> allGroups = this.getAllGroupsFromGraph(componentId,
- compTypeEnum);
+ Either<List<GroupDefinition>, TitanOperationStatus> allGroups = this.getAllGroupsFromGraph(componentId, compTypeEnum);
if (allGroups.isRight()) {
TitanOperationStatus status = allGroups.right().value();
- log.debug("Failed to retrieve all groups of component {} from graph. Status is {}", componentId,
- status);
+ log.debug("Failed to retrieve all groups of component {} from graph. Status is {}", componentId, status);
if (status == TitanOperationStatus.NOT_FOUND) {
status = TitanOperationStatus.OK;
}
@@ -762,8 +869,7 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
}
@Override
- public Either<List<GroupDefinition>, StorageOperationStatus> getAllGroups(String componentId,
- NodeTypeEnum compTypeEnum) {
+ public Either<List<GroupDefinition>, StorageOperationStatus> getAllGroups(String componentId, NodeTypeEnum compTypeEnum) {
return getAllGroups(componentId, compTypeEnum, false);
}
@@ -778,27 +884,21 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
GroupDefinition groupDefinition = groupFromGraph.left().value();
// 1. delete all properties values nodes
- List<GroupProperty> properties = groupDefinition.getProperties();
+ List<GroupProperty> properties = groupDefinition.convertToGroupProperties();
if (properties != null) {
for (GroupProperty groupProperty : properties) {
String propValueUniqueId = groupProperty.getValueUniqueUid();
if (propValueUniqueId != null) {
UniqueIdData uniqueIdData = new UniqueIdData(NodeTypeEnum.PropertyValue, propValueUniqueId);
- Either<PropertyValueData, TitanOperationStatus> deleteNode = titanGenericDao
- .deleteNode(uniqueIdData, PropertyValueData.class);
+ Either<PropertyValueData, TitanOperationStatus> deleteNode = titanGenericDao.deleteNode(uniqueIdData, PropertyValueData.class);
if (deleteNode.isRight()) {
TitanOperationStatus status = groupFromGraph.right().value();
- String description = String.format(
- "Failed to delete property {} under group {}" + groupUniqueId
- + " on graph. Status is {}",
- propValueUniqueId, groupDefinition.getName(), status.name());
- log.debug(description);
- BeEcompErrorManager.getInstance().logBeFailedDeleteNodeError(DELETING_GROUP, propValueUniqueId,
- status.name());
+ log.debug("Failed to delete property {} under group {} {} on graph. Status is {}", propValueUniqueId, groupDefinition.getName(), groupUniqueId, status.name());
+ BeEcompErrorManager.getInstance().logBeFailedDeleteNodeError(DELETING_GROUP, propValueUniqueId, status.name());
return Either.right(status);
} else {
- log.trace("Property {} was deleted from geoup {}", propValueUniqueId, groupDefinition.getName());
+ log.trace("Property {} was deleted from group {}" ,propValueUniqueId, groupDefinition.getName());
}
}
}
@@ -809,10 +909,7 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
Either<GroupData, TitanOperationStatus> deleteNode = titanGenericDao.deleteNode(uniqueIdData, GroupData.class);
if (deleteNode.isRight()) {
TitanOperationStatus status = groupFromGraph.right().value();
- String description = String.format(
- "Failed to delete group {} with uid " + groupUniqueId + " on graph. Status is {}",
- groupDefinition.getName(), groupUniqueId, status.name());
- log.debug(description);
+ log.debug("Failed to delete group {} with uid {} on graph. Status is {}", groupDefinition.getName(), groupUniqueId, status.name());
BeEcompErrorManager.getInstance().logBeFailedDeleteNodeError(DELETING_GROUP, groupUniqueId, status.name());
return Either.right(status);
} else {
@@ -863,18 +960,15 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
}
@Override
- public Either<List<GroupDefinition>, TitanOperationStatus> deleteAllGroupsFromGraph(String componentId,
- NodeTypeEnum componentTypeEnum) {
+ public Either<List<GroupDefinition>, TitanOperationStatus> deleteAllGroupsFromGraph(String componentId, NodeTypeEnum componentTypeEnum) {
- Either<List<ImmutablePair<GroupData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao
- .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(componentTypeEnum), componentId,
- GraphEdgeLabels.GROUP, NodeTypeEnum.Group, GroupData.class);
+ Either<List<ImmutablePair<GroupData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(componentTypeEnum), componentId, GraphEdgeLabels.GROUP, NodeTypeEnum.Group,
+ GroupData.class);
if (childrenNodes.isRight()) {
TitanOperationStatus status = childrenNodes.right().value();
if (status != TitanOperationStatus.NOT_FOUND) {
- BeEcompErrorManager.getInstance().logBeFailedFindAllNodesError(DELETING_ALL_GROUPS,
- NodeTypeEnum.Group.name(), componentId, status.name());
+ BeEcompErrorManager.getInstance().logBeFailedFindAllNodesError(DELETING_ALL_GROUPS, NodeTypeEnum.Group.name(), componentId, status.name());
}
return Either.right(status);
}
@@ -888,8 +982,7 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
Either<GroupData, TitanOperationStatus> deleteGroupFromGraph = deleteGroupFromGraph(uniqueId);
if (deleteGroupFromGraph.isRight()) {
TitanOperationStatus status = deleteGroupFromGraph.right().value();
- BeEcompErrorManager.getInstance().logBeFailedDeleteNodeError(DELETING_ALL_GROUPS, uniqueId,
- status.name());
+ BeEcompErrorManager.getInstance().logBeFailedDeleteNodeError(DELETING_ALL_GROUPS, uniqueId, status.name());
return Either.right(status);
}
GroupData groupData = deleteGroupFromGraph.left().value();
@@ -902,15 +995,13 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
}
@Override
- public Either<List<GroupDefinition>, StorageOperationStatus> deleteAllGroups(String componentId,
- NodeTypeEnum compTypeEnum, boolean inTransaction) {
+ public Either<List<GroupDefinition>, StorageOperationStatus> deleteAllGroups(String componentId, NodeTypeEnum compTypeEnum, boolean inTransaction) {
Either<List<GroupDefinition>, StorageOperationStatus> result = null;
try {
- Either<List<GroupDefinition>, TitanOperationStatus> allGroups = this.deleteAllGroupsFromGraph(componentId,
- compTypeEnum);
+ Either<List<GroupDefinition>, TitanOperationStatus> allGroups = this.deleteAllGroupsFromGraph(componentId, compTypeEnum);
if (allGroups.isRight()) {
TitanOperationStatus status = allGroups.right().value();
@@ -942,14 +1033,11 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
}
@Override
- public Either<List<GroupDefinition>, StorageOperationStatus> deleteAllGroups(String componentId,
- NodeTypeEnum compTypeEnum) {
+ public Either<List<GroupDefinition>, StorageOperationStatus> deleteAllGroups(String componentId, NodeTypeEnum compTypeEnum) {
return deleteAllGroups(componentId, compTypeEnum, false);
}
- public Either<List<GroupDefinition>, StorageOperationStatus> prepareGroupsForCloning(
- org.openecomp.sdc.be.model.Component origResource,
- ImmutablePair<List<ComponentInstance>, Map<String, String>> cloneInstances) {
+ public Either<List<GroupDefinition>, StorageOperationStatus> prepareGroupsForCloning(org.openecomp.sdc.be.model.Component origResource, ImmutablePair<List<ComponentInstance>, Map<String, String>> cloneInstances) {
List<GroupDefinition> groupsToCreate = new ArrayList<>();
Either<List<GroupDefinition>, StorageOperationStatus> result = Either.left(groupsToCreate);
@@ -966,19 +1054,18 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
gdToCreate.setUniqueId(null);
gdToCreate.setMembers(null);
- List<GroupProperty> properties = groupDefinition.getProperties();
+ List<GroupProperty> properties = groupDefinition.convertToGroupProperties();
if (properties != null) {
// Take properties which was updated in the
// group(getValueUniqueUid != null),
// Then set null instead of the value(prepare for the
// creation).
- List<GroupProperty> propertiesToUpdate = properties.stream()
- .filter(p -> p.getValueUniqueUid() != null).map(p -> {
- p.setValueUniqueUid(null);
- return p;
- }).collect(Collectors.toList());
+ List<GroupProperty> propertiesToUpdate = properties.stream().filter(p -> p.getValueUniqueUid() != null).map(p -> {
+ p.setValueUniqueUid(null);
+ return p;
+ }).collect(Collectors.toList());
- gdToCreate.setProperties(propertiesToUpdate);
+ gdToCreate.convertFromGroupProperties(propertiesToUpdate);
}
@@ -988,8 +1075,7 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
Map<String, String> oldCompUidToNew = cloneInstances.right;
if (members != null && createdInstances != null) {
- Map<String, String> compInstIdToName = createdInstances.stream()
- .collect(Collectors.toMap(p -> p.getUniqueId(), p -> p.getName()));
+ Map<String, String> compInstIdToName = createdInstances.stream().collect(Collectors.toMap(p -> p.getUniqueId(), p -> p.getName()));
Map<String, String> membersToCreate = new HashMap<>();
@@ -1018,8 +1104,7 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
}
@Override
- public Either<List<GroupDefinition>, StorageOperationStatus> addGroups(NodeTypeEnum nodeTypeEnum,
- String componentId, List<GroupDefinition> groups, boolean inTransaction) {
+ public Either<List<GroupDefinition>, StorageOperationStatus> addGroups(NodeTypeEnum nodeTypeEnum, String componentId, List<GroupDefinition> groups, boolean inTransaction) {
List<GroupDefinition> createdGroups = new ArrayList<>();
@@ -1029,8 +1114,7 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
if (groups != null) {
for (GroupDefinition groupDefinition : groups) {
- Either<GroupDefinition, StorageOperationStatus> addGroup = this.addGroup(nodeTypeEnum, componentId,
- groupDefinition, true);
+ Either<GroupDefinition, StorageOperationStatus> addGroup = this.addGroup(nodeTypeEnum, componentId, groupDefinition, true);
if (addGroup.isRight()) {
StorageOperationStatus status = addGroup.right().value();
result = Either.right(status);
@@ -1059,29 +1143,25 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
}
@Override
- public Either<List<String>, TitanOperationStatus> getAssociatedGroupsToComponentInstanceFromGraph(
- String componentInstanceId) {
+ public Either<List<String>, TitanOperationStatus> getAssociatedGroupsToComponentInstanceFromGraph(String componentInstanceId) {
List<String> groups = new ArrayList<>();
Either<List<String>, TitanOperationStatus> result = Either.left(groups);
- Either<List<ImmutablePair<GroupData, GraphEdge>>, TitanOperationStatus> parentNodes = titanGenericDao
- .getParentNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), componentInstanceId,
- GraphEdgeLabels.GROUP_MEMBER, NodeTypeEnum.Group, GroupData.class);
+ Either<List<ImmutablePair<GroupData, GraphEdge>>, TitanOperationStatus> parentNodes = titanGenericDao.getParentNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), componentInstanceId, GraphEdgeLabels.GROUP_MEMBER,
+ NodeTypeEnum.Group, GroupData.class);
if (parentNodes.isRight()) {
TitanOperationStatus status = parentNodes.right().value();
if (status != TitanOperationStatus.NOT_FOUND) {
- BeEcompErrorManager.getInstance().logBeFailedFindParentError("FetchGroupMembers", componentInstanceId,
- status.name());
+ BeEcompErrorManager.getInstance().logBeFailedFindParentError("FetchGroupMembers", componentInstanceId, status.name());
}
return Either.right(status);
}
List<ImmutablePair<GroupData, GraphEdge>> fetchedGroups = parentNodes.left().value();
if (fetchedGroups != null) {
- List<String> list = fetchedGroups.stream().map(p -> p.left.getGroupDataDefinition().getUniqueId())
- .collect(Collectors.toList());
+ List<String> list = fetchedGroups.stream().map(p -> p.left.getGroupDataDefinition().getUniqueId()).collect(Collectors.toList());
groups.addAll(list);
}
@@ -1090,15 +1170,13 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
}
@Override
- public Either<List<String>, StorageOperationStatus> getAssociatedGroupsToComponentInstance(
- String componentInstanceId, boolean inTransaction) {
+ public Either<List<String>, StorageOperationStatus> getAssociatedGroupsToComponentInstance(String componentInstanceId, boolean inTransaction) {
Either<List<String>, StorageOperationStatus> result = null;
try {
- Either<List<String>, TitanOperationStatus> groups = this
- .getAssociatedGroupsToComponentInstanceFromGraph(componentInstanceId);
+ Either<List<String>, TitanOperationStatus> groups = this.getAssociatedGroupsToComponentInstanceFromGraph(componentInstanceId);
if (groups.isRight()) {
TitanOperationStatus status = groups.right().value();
@@ -1129,14 +1207,12 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
}
@Override
- public Either<List<String>, StorageOperationStatus> getAssociatedGroupsToComponentInstance(
- String componentInstanceId) {
+ public Either<List<String>, StorageOperationStatus> getAssociatedGroupsToComponentInstance(String componentInstanceId) {
return getAssociatedGroupsToComponentInstance(componentInstanceId, false);
}
@Override
- public Either<List<GraphRelation>, TitanOperationStatus> associateGroupsToComponentInstanceOnGraph(
- List<String> groups, String componentInstanceId, String compInstName) {
+ public Either<List<GraphRelation>, TitanOperationStatus> associateGroupsToComponentInstanceOnGraph(List<String> groups, String componentInstanceId, String compInstName) {
List<GraphRelation> relations = new ArrayList<>();
Either<List<GraphRelation>, TitanOperationStatus> result = Either.left(relations);
@@ -1150,14 +1226,11 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
Map<String, Object> props = new HashMap<String, Object>();
props.put(GraphPropertiesDictionary.NAME.getProperty(), compInstName);
- Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(groupData,
- compInstData, GraphEdgeLabels.GROUP_MEMBER, props);
+ Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(groupData, compInstData, GraphEdgeLabels.GROUP_MEMBER, props);
if (createRelation.isRight()) {
TitanOperationStatus status = createRelation.right().value();
- String description = "Failed to associate group " + groupData.getUniqueId()
- + " to component instance " + compInstName + " in graph. Status is " + status;
- BeEcompErrorManager.getInstance().logInternalFlowError(ASSOCIATING_GROUP_TO_COMP_INST, description,
- ErrorSeverity.ERROR);
+ String description = "Failed to associate group " + groupData.getUniqueId() + " to component instance " + compInstName + " in graph. Status is " + status;
+ BeEcompErrorManager.getInstance().logInternalFlowError(ASSOCIATING_GROUP_TO_COMP_INST, description, ErrorSeverity.ERROR);
result = Either.right(status);
break;
}
@@ -1171,21 +1244,18 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
return result;
}
- public StorageOperationStatus associateGroupsToComponentInstance(List<String> groups, String componentInstanceId,
- String compInstName) {
+ public StorageOperationStatus associateGroupsToComponentInstance(List<String> groups, String componentInstanceId, String compInstName) {
return associateGroupsToComponentInstance(groups, componentInstanceId, compInstName, false);
}
@Override
- public StorageOperationStatus associateGroupsToComponentInstance(List<String> groups, String componentInstanceId,
- String compInstName, boolean inTransaction) {
+ public StorageOperationStatus associateGroupsToComponentInstance(List<String> groups, String componentInstanceId, String compInstName, boolean inTransaction) {
StorageOperationStatus result = null;
try {
- Either<List<GraphRelation>, TitanOperationStatus> either = this
- .associateGroupsToComponentInstanceOnGraph(groups, componentInstanceId, compInstName);
+ Either<List<GraphRelation>, TitanOperationStatus> either = this.associateGroupsToComponentInstanceOnGraph(groups, componentInstanceId, compInstName);
if (either.isRight()) {
TitanOperationStatus status = either.right().value();
@@ -1215,14 +1285,12 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
}
@Override
- public Either<List<GraphRelation>, TitanOperationStatus> dissociateAllGroupsFromArtifactOnGraph(String componentId,
- NodeTypeEnum componentTypeEnum, String artifactId) {
+ public Either<List<GraphRelation>, TitanOperationStatus> dissociateAllGroupsFromArtifactOnGraph(String componentId, NodeTypeEnum componentTypeEnum, String artifactId) {
List<GraphRelation> relations = new ArrayList<>();
Either<List<GraphRelation>, TitanOperationStatus> result = Either.left(relations);
- Either<List<GroupDefinition>, TitanOperationStatus> allGroupsFromGraph = getAllGroupsFromGraph(componentId,
- componentTypeEnum, true, true, false);
+ Either<List<GroupDefinition>, TitanOperationStatus> allGroupsFromGraph = getAllGroupsFromGraph(componentId, componentTypeEnum, true, true, false);
if (allGroupsFromGraph.isRight()) {
TitanOperationStatus status = allGroupsFromGraph.right().value();
return Either.right(status);
@@ -1234,9 +1302,7 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
}
// Find all groups which contains this artifact id
- List<GroupDefinition> associatedGroups = allGroups.stream()
- .filter(p -> p.getArtifacts() != null && p.getArtifacts().contains(artifactId))
- .collect(Collectors.toList());
+ List<GroupDefinition> associatedGroups = allGroups.stream().filter(p -> p.getArtifacts() != null && p.getArtifacts().contains(artifactId)).collect(Collectors.toList());
if (associatedGroups != null && false == associatedGroups.isEmpty()) {
log.debug("The groups {} contains the artifact {}", associatedGroups.stream().map(p -> p.getName()).collect(Collectors.toList()), artifactId);
@@ -1244,8 +1310,7 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
UniqueIdData artifactData = new UniqueIdData(NodeTypeEnum.ArtifactRef, artifactId);
for (GroupDefinition groupDefinition : associatedGroups) {
UniqueIdData groupData = new UniqueIdData(NodeTypeEnum.Group, groupDefinition.getUniqueId());
- Either<GraphRelation, TitanOperationStatus> deleteRelation = titanGenericDao.deleteRelation(groupData,
- artifactData, GraphEdgeLabels.GROUP_ARTIFACT_REF);
+ Either<GraphRelation, TitanOperationStatus> deleteRelation = titanGenericDao.deleteRelation(groupData, artifactData, GraphEdgeLabels.GROUP_ARTIFACT_REF);
if (deleteRelation.isRight()) {
TitanOperationStatus status = deleteRelation.right().value();
if (status == TitanOperationStatus.NOT_FOUND) {
@@ -1266,18 +1331,15 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
}
- public Either<GroupDefinition, TitanOperationStatus> getGroupFromGraph(String uniqueId, boolean skipProperties,
- boolean skipMembers, boolean skipArtifacts) {
+ public Either<GroupDefinition, TitanOperationStatus> getGroupFromGraph(String uniqueId, boolean skipProperties, boolean skipMembers, boolean skipArtifacts) {
Either<GroupDefinition, TitanOperationStatus> result = null;
- Either<GroupData, TitanOperationStatus> groupRes = titanGenericDao
- .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Group), uniqueId, GroupData.class);
+ Either<GroupData, TitanOperationStatus> groupRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Group), uniqueId, GroupData.class);
if (groupRes.isRight()) {
TitanOperationStatus status = groupRes.right().value();
log.debug("Failed to retrieve group {} from graph. Status is {}", uniqueId, status);
- BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError("Fetch Group", uniqueId,
- String.valueOf(status));
+ BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError("Fetch Group", uniqueId, String.valueOf(status));
result = Either.right(status);
return result;
}
@@ -1324,13 +1386,12 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
}
} else {
List<GroupProperty> properties = propertiesRes.left().value();
- groupDefinition.setProperties(properties);
+ groupDefinition.convertFromGroupProperties(properties);
}
}
if (false == skipArtifacts) {
- Either<List<ImmutablePair<String, String>>, TitanOperationStatus> artifactsRes = getGroupArtifactsPairs(
- uniqueId);
+ Either<List<ImmutablePair<String, String>>, TitanOperationStatus> artifactsRes = getGroupArtifactsPairs(uniqueId);
if (artifactsRes.isRight()) {
TitanOperationStatus status = artifactsRes.right().value();
if (status != TitanOperationStatus.OK) {
@@ -1376,14 +1437,12 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
}
}
- protected Either<List<GroupDefinition>, TitanOperationStatus> getAllGroupsFromGraph(String componentId,
- NodeTypeEnum componentTypeEnum, boolean skipProperties, boolean skipMembers, boolean skipArtifacts) {
+ protected Either<List<GroupDefinition>, TitanOperationStatus> getAllGroupsFromGraph(String componentId, NodeTypeEnum componentTypeEnum, boolean skipProperties, boolean skipMembers, boolean skipArtifacts) {
List<GroupDefinition> groups = new ArrayList<GroupDefinition>();
- Either<List<ImmutablePair<GroupData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao
- .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(componentTypeEnum), componentId,
- GraphEdgeLabels.GROUP, NodeTypeEnum.Group, GroupData.class);
+ Either<List<ImmutablePair<GroupData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(componentTypeEnum), componentId, GraphEdgeLabels.GROUP, NodeTypeEnum.Group,
+ GroupData.class);
if (childrenNodes.isRight()) {
TitanOperationStatus status = childrenNodes.right().value();
@@ -1403,8 +1462,7 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
for (ImmutablePair<GroupData, GraphEdge> pair : graphGroups) {
String groupUniqueId = pair.left.getGroupDataDefinition().getUniqueId();
- Either<GroupDefinition, TitanOperationStatus> groupRes = this.getGroupFromGraph(groupUniqueId,
- skipProperties, skipMembers, skipArtifacts);
+ Either<GroupDefinition, TitanOperationStatus> groupRes = this.getGroupFromGraph(groupUniqueId, skipProperties, skipMembers, skipArtifacts);
if (groupRes.isRight()) {
TitanOperationStatus status = groupRes.right().value();
@@ -1422,14 +1480,12 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
}
@Override
- public StorageOperationStatus dissociateAllGroupsFromArtifact(String componentId, NodeTypeEnum componentTypeEnum,
- String artifactId, boolean inTransaction) {
+ public StorageOperationStatus dissociateAllGroupsFromArtifact(String componentId, NodeTypeEnum componentTypeEnum, String artifactId, boolean inTransaction) {
StorageOperationStatus result = null;
try {
- Either<List<GraphRelation>, TitanOperationStatus> either = this
- .dissociateAllGroupsFromArtifactOnGraph(componentId, componentTypeEnum, artifactId);
+ Either<List<GraphRelation>, TitanOperationStatus> either = this.dissociateAllGroupsFromArtifactOnGraph(componentId, componentTypeEnum, artifactId);
if (either.isRight()) {
TitanOperationStatus status = either.right().value();
@@ -1459,18 +1515,15 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
}
@Override
- public StorageOperationStatus dissociateAllGroupsFromArtifact(String componentId, NodeTypeEnum componentTypeEnum,
- String artifactId) {
+ public StorageOperationStatus dissociateAllGroupsFromArtifact(String componentId, NodeTypeEnum componentTypeEnum, String artifactId) {
return dissociateAllGroupsFromArtifact(componentId, componentTypeEnum, artifactId, false);
}
@Override
- public TitanOperationStatus dissociateAndAssociateGroupsFromArtifactOnGraph(String componentId,
- NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact) {
+ public TitanOperationStatus dissociateAndAssociateGroupsFromArtifactOnGraph(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact) {
- Either<List<GroupDefinition>, TitanOperationStatus> allGroupsFromGraph = getAllGroupsFromGraph(componentId,
- componentTypeEnum, true, true, false);
+ Either<List<GroupDefinition>, TitanOperationStatus> allGroupsFromGraph = getAllGroupsFromGraph(componentId, componentTypeEnum, true, true, false);
if (allGroupsFromGraph.isRight()) {
TitanOperationStatus status = allGroupsFromGraph.right().value();
return status;
@@ -1482,26 +1535,22 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
}
// Find all groups which contains this artifact id
- List<GroupDefinition> associatedGroups = allGroups.stream()
- .filter(p -> p.getArtifacts() != null && p.getArtifacts().contains(oldArtifactId))
- .collect(Collectors.toList());
+ List<GroupDefinition> associatedGroups = allGroups.stream().filter(p -> p.getArtifacts() != null && p.getArtifacts().contains(oldArtifactId)).collect(Collectors.toList());
if (associatedGroups != null && false == associatedGroups.isEmpty()) {
log.debug("The groups {} contains the artifact {}", associatedGroups.stream().map(p -> p.getName()).collect(Collectors.toList()), oldArtifactId);
UniqueIdData oldArtifactData = new UniqueIdData(NodeTypeEnum.ArtifactRef, oldArtifactId);
- UniqueIdData newArtifactData = new UniqueIdData(NodeTypeEnum.ArtifactRef,
- newArtifact.getArtifactDataDefinition().getUniqueId());
+ UniqueIdData newArtifactData = new UniqueIdData(NodeTypeEnum.ArtifactRef, newArtifact.getArtifactDataDefinition().getUniqueId());
Map<String, Object> props = new HashMap<String, Object>();
props.put(GraphPropertiesDictionary.NAME.getProperty(), newArtifactData.getLabel());
for (GroupDefinition groupDefinition : associatedGroups) {
UniqueIdData groupData = new UniqueIdData(NodeTypeEnum.Group, groupDefinition.getUniqueId());
- Either<GraphRelation, TitanOperationStatus> deleteRelation = titanGenericDao.deleteRelation(groupData,
- oldArtifactData, GraphEdgeLabels.GROUP_ARTIFACT_REF);
- log.trace("After dissociate group {} from artifac {}", groupDefinition.getName(), oldArtifactId);
+ Either<GraphRelation, TitanOperationStatus> deleteRelation = titanGenericDao.deleteRelation(groupData, oldArtifactData, GraphEdgeLabels.GROUP_ARTIFACT_REF);
+ log.trace("After dissociate group {} from artifact {}" , groupDefinition.getName(), oldArtifactId);
if (deleteRelation.isRight()) {
TitanOperationStatus status = deleteRelation.right().value();
if (status == TitanOperationStatus.NOT_FOUND) {
@@ -1510,9 +1559,8 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
return status;
}
- Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(groupData,
- newArtifactData, GraphEdgeLabels.GROUP_ARTIFACT_REF, props);
- log.trace("After associate group {} to artifact {}", groupDefinition.getName(), newArtifact.getUniqueIdKey());
+ Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(groupData, newArtifactData, GraphEdgeLabels.GROUP_ARTIFACT_REF, props);
+ log.trace("After associate group {} to artifact {}" , groupDefinition.getName(), newArtifact.getUniqueIdKey());
if (createRelation.isRight()) {
TitanOperationStatus status = createRelation.right().value();
if (status == TitanOperationStatus.NOT_FOUND) {
@@ -1527,14 +1575,12 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
}
@Override
- public StorageOperationStatus dissociateAndAssociateGroupsFromArtifact(String componentId,
- NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact, boolean inTransaction) {
+ public StorageOperationStatus dissociateAndAssociateGroupsFromArtifact(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact, boolean inTransaction) {
StorageOperationStatus result = null;
try {
- TitanOperationStatus status = this.dissociateAndAssociateGroupsFromArtifactOnGraph(componentId,
- componentTypeEnum, oldArtifactId, newArtifact);
+ TitanOperationStatus status = this.dissociateAndAssociateGroupsFromArtifactOnGraph(componentId, componentTypeEnum, oldArtifactId, newArtifact);
if (status != TitanOperationStatus.OK && status != TitanOperationStatus.NOT_FOUND) {
result = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
@@ -1560,20 +1606,16 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
}
@Override
- public StorageOperationStatus dissociateAndAssociateGroupsFromArtifact(String componentId,
- NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact) {
- return dissociateAndAssociateGroupsFromArtifact(componentId, componentTypeEnum, oldArtifactId, newArtifact,
- false);
+ public StorageOperationStatus dissociateAndAssociateGroupsFromArtifact(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact) {
+ return dissociateAndAssociateGroupsFromArtifact(componentId, componentTypeEnum, oldArtifactId, newArtifact, false);
}
- private Either<List<ImmutablePair<String, String>>, TitanOperationStatus> getGroupArtifactsPairs(
- String groupUniqueId) {
+ private Either<List<ImmutablePair<String, String>>, TitanOperationStatus> getGroupArtifactsPairs(String groupUniqueId) {
Either<List<ImmutablePair<String, String>>, TitanOperationStatus> result = null;
- Either<List<ImmutablePair<ArtifactData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao
- .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Group), groupUniqueId,
- GraphEdgeLabels.GROUP_ARTIFACT_REF, NodeTypeEnum.ArtifactRef, ArtifactData.class);
+ Either<List<ImmutablePair<ArtifactData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Group), groupUniqueId, GraphEdgeLabels.GROUP_ARTIFACT_REF,
+ NodeTypeEnum.ArtifactRef, ArtifactData.class);
if (childrenNodes.isRight()) {
TitanOperationStatus status = childrenNodes.right().value();
if (status == TitanOperationStatus.NOT_FOUND) {
@@ -1631,8 +1673,7 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
*/
public Either<GroupDefinition, TitanOperationStatus> updateGroupVersionOnGraph(String groupUniqueId) {
- Either<GroupDefinition, TitanOperationStatus> groupFromGraph = this.getGroupFromGraph(groupUniqueId, false,
- false, false);
+ Either<GroupDefinition, TitanOperationStatus> groupFromGraph = this.getGroupFromGraph(groupUniqueId, false, false, false);
if (groupFromGraph.isRight()) {
TitanOperationStatus status = groupFromGraph.right().value();
@@ -1661,10 +1702,11 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
}
}
+
+
/**
- * The version of the group is an integer. In order to support BC, we might
- * get a version in a float format.
+ * The version of the group is an integer. In order to support BC, we might get a version in a float format.
*
* @param version
* @return
@@ -1680,23 +1722,20 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
}
- public Either<GroupDefinition, TitanOperationStatus> associateArtifactsToGroupOnGraph(String groupId,
- List<String> artifactsId) {
+ public Either<GroupDefinition, TitanOperationStatus> associateArtifactsToGroupOnGraph(String groupId, List<String> artifactsId) {
if (artifactsId == null || artifactsId.isEmpty()) {
return Either.right(TitanOperationStatus.OK);
}
for (String artifactId : artifactsId) {
- Either<ArtifactData, TitanOperationStatus> findArtifactRes = titanGenericDao.getNode(
- UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef), artifactId, ArtifactData.class);
+ Either<ArtifactData, TitanOperationStatus> findArtifactRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef), artifactId, ArtifactData.class);
if (findArtifactRes.isRight()) {
TitanOperationStatus status = findArtifactRes.right().value();
if (status == TitanOperationStatus.NOT_FOUND) {
status = TitanOperationStatus.INVALID_ID;
}
- String description = "Failed to associate group " + groupId + " to artifact " + artifactId
- + " in graph. Status is " + status;
+ String description = "Failed to associate group " + groupId + " to artifact " + artifactId + " in graph. Status is " + status;
BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, ErrorSeverity.ERROR);
return Either.right(status);
}
@@ -1705,69 +1744,56 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
props.put(GraphPropertiesDictionary.NAME.getProperty(), findArtifactRes.left().value().getLabel());
GraphNode groupData = new UniqueIdData(NodeTypeEnum.Group, groupId);
- Either<GraphRelation, TitanOperationStatus> addArtifactsRefResult = titanGenericDao.createRelation(
- groupData, findArtifactRes.left().value(), GraphEdgeLabels.GROUP_ARTIFACT_REF, props);
+ Either<GraphRelation, TitanOperationStatus> addArtifactsRefResult = titanGenericDao.createRelation(groupData, findArtifactRes.left().value(), GraphEdgeLabels.GROUP_ARTIFACT_REF, props);
if (addArtifactsRefResult.isRight()) {
TitanOperationStatus status = addArtifactsRefResult.right().value();
- String description = "Failed to associate group " + groupData.getUniqueId() + " to artifact "
- + artifactId + " in graph. Status is " + status;
+ String description = "Failed to associate group " + groupData.getUniqueId() + " to artifact " + artifactId + " in graph. Status is " + status;
BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, ErrorSeverity.ERROR);
return Either.right(status);
}
}
- Either<GroupDefinition, TitanOperationStatus> groupFromGraph = this.getGroupFromGraph(groupId, true, true,
- false);
+ Either<GroupDefinition, TitanOperationStatus> groupFromGraph = this.getGroupFromGraph(groupId, true, true, false);
return groupFromGraph;
}
- public Either<GroupDefinition, TitanOperationStatus> associateMembersToGroupOnGraph(String groupId,
- Map<String, String> members) {
+ public Either<GroupDefinition, TitanOperationStatus> associateMembersToGroupOnGraph(String groupId, Map<String, String> members) {
if (members != null && false == members.isEmpty()) {
Either<GraphRelation, TitanOperationStatus> addMembersRefResult = null;
for (Entry<String, String> member : members.entrySet()) {
- Either<ComponentInstanceData, TitanOperationStatus> findComponentInstanceRes = titanGenericDao.getNode(
- UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), member.getValue(),
- ComponentInstanceData.class);
+ Either<ComponentInstanceData, TitanOperationStatus> findComponentInstanceRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), member.getValue(), ComponentInstanceData.class);
if (findComponentInstanceRes.isRight()) {
TitanOperationStatus status = findComponentInstanceRes.right().value();
if (status == TitanOperationStatus.NOT_FOUND) {
status = TitanOperationStatus.INVALID_ID;
}
- String description = "Failed to find to find component instance group " + member.getValue()
- + " in graph. Status is " + status;
- BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description,
- ErrorSeverity.ERROR);
+ String description = "Failed to find to find component instance group " + member.getValue() + " in graph. Status is " + status;
+ BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, ErrorSeverity.ERROR);
return Either.right(status);
}
Map<String, Object> props = new HashMap<String, Object>();
props.put(GraphPropertiesDictionary.NAME.getProperty(), member.getKey());
GraphNode groupData = new UniqueIdData(NodeTypeEnum.Group, groupId);
- addMembersRefResult = titanGenericDao.createRelation(groupData, findComponentInstanceRes.left().value(),
- GraphEdgeLabels.GROUP_MEMBER, props);
+ addMembersRefResult = titanGenericDao.createRelation(groupData, findComponentInstanceRes.left().value(), GraphEdgeLabels.GROUP_MEMBER, props);
if (addMembersRefResult.isRight()) {
TitanOperationStatus status = addMembersRefResult.right().value();
- String description = "Failed to associate group " + groupData.getUniqueId()
- + " to component instance " + member.getValue() + " in graph. Status is " + status;
- BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description,
- ErrorSeverity.ERROR);
+ String description = "Failed to associate group " + groupData.getUniqueId() + " to component instance " + member.getValue() + " in graph. Status is " + status;
+ BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, ErrorSeverity.ERROR);
return Either.right(status);
}
}
}
- Either<GroupDefinition, TitanOperationStatus> groupFromGraph = this.getGroupFromGraph(groupId, true, false,
- true);
+ Either<GroupDefinition, TitanOperationStatus> groupFromGraph = this.getGroupFromGraph(groupId, true, false, true);
return groupFromGraph;
}
- public Either<GroupDefinition, TitanOperationStatus> dissociateArtifactsFromGroupOnGraph(String groupId,
- List<String> artifactsId) {
+ public Either<GroupDefinition, TitanOperationStatus> dissociateArtifactsFromGroupOnGraph(String groupId, List<String> artifactsId) {
if (artifactsId == null || artifactsId.isEmpty()) {
return Either.right(TitanOperationStatus.OK);
@@ -1777,32 +1803,28 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
for (String artifactId : artifactsId) {
UniqueIdData artifactData = new UniqueIdData(NodeTypeEnum.Group, artifactId);
- Either<GraphRelation, TitanOperationStatus> deleteRelation = titanGenericDao.deleteRelation(groupData,
- artifactData, GraphEdgeLabels.GROUP_ARTIFACT_REF);
- log.trace("After dissociate group {} from artifact {}", groupId, artifactId);
+ Either<GraphRelation, TitanOperationStatus> deleteRelation = titanGenericDao.deleteRelation(groupData, artifactData, GraphEdgeLabels.GROUP_ARTIFACT_REF);
+ log.trace("After dissociate group {} from artifact {}" ,groupId, artifactId);
if (deleteRelation.isRight()) {
TitanOperationStatus status = deleteRelation.right().value();
if (status == TitanOperationStatus.NOT_FOUND) {
status = TitanOperationStatus.INVALID_ID;
}
- String description = "Failed to diassociate group " + groupId + " from artifact " + artifactId
- + " in graph. Status is " + status;
+ String description = "Failed to diassociate group " + groupId + " from artifact " + artifactId + " in graph. Status is " + status;
BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, ErrorSeverity.ERROR);
return Either.right(status);
}
}
- Either<GroupDefinition, TitanOperationStatus> groupFromGraph = this.getGroupFromGraph(groupId, true, true,
- false);
+ Either<GroupDefinition, TitanOperationStatus> groupFromGraph = this.getGroupFromGraph(groupId, true, true, false);
return groupFromGraph;
}
- public Either<GroupDefinition, TitanOperationStatus> dissociateMembersFromGroupOnGraph(String groupId,
- Map<String, String> members) {
+ public Either<GroupDefinition, TitanOperationStatus> dissociateMembersFromGroupOnGraph(String groupId, Map<String, String> members) {
if (members == null || members.isEmpty()) {
return Either.right(TitanOperationStatus.OK);
@@ -1812,25 +1834,22 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
for (Entry<String, String> member : members.entrySet()) {
UniqueIdData artifactData = new UniqueIdData(NodeTypeEnum.Group, member.getValue());
- Either<GraphRelation, TitanOperationStatus> deleteRelation = titanGenericDao.deleteRelation(groupData,
- artifactData, GraphEdgeLabels.GROUP_MEMBER);
- log.trace("After dissociate group {} from members", groupId, member.getValue());
+ Either<GraphRelation, TitanOperationStatus> deleteRelation = titanGenericDao.deleteRelation(groupData, artifactData, GraphEdgeLabels.GROUP_MEMBER);
+ log.trace("After dissociate group {} from members {}" ,groupId, member.getValue());
if (deleteRelation.isRight()) {
TitanOperationStatus status = deleteRelation.right().value();
if (status == TitanOperationStatus.NOT_FOUND) {
status = TitanOperationStatus.INVALID_ID;
}
- String description = "Failed to diassociate group " + groupId + " from member " + member.getValue()
- + " in graph. Status is " + status;
+ String description = "Failed to diassociate group " + groupId + " from member " + member.getValue() + " in graph. Status is " + status;
BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, ErrorSeverity.ERROR);
return Either.right(status);
}
}
- Either<GroupDefinition, TitanOperationStatus> groupFromGraph = this.getGroupFromGraph(groupId, true, true,
- false);
+ Either<GroupDefinition, TitanOperationStatus> groupFromGraph = this.getGroupFromGraph(groupId, true, true, false);
return groupFromGraph;
@@ -1844,18 +1863,15 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
* @param inTransaction
* @return
*/
- public Either<GroupDefinition, StorageOperationStatus> dissociateArtifactsFromGroup(String groupId,
- List<String> artifactsId, boolean inTransaction) {
+ public Either<GroupDefinition, StorageOperationStatus> dissociateArtifactsFromGroup(String groupId, List<String> artifactsId, boolean inTransaction) {
Either<GroupDefinition, StorageOperationStatus> result = null;
try {
- Either<GroupDefinition, TitanOperationStatus> titanRes = this.dissociateArtifactsFromGroupOnGraph(groupId,
- artifactsId);
+ Either<GroupDefinition, TitanOperationStatus> titanRes = this.dissociateArtifactsFromGroupOnGraph(groupId, artifactsId);
if (titanRes.isRight()) {
- StorageOperationStatus storageOperationStatus = DaoStatusConverter
- .convertTitanStatusToStorageStatus(titanRes.right().value());
+ StorageOperationStatus storageOperationStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(titanRes.right().value());
result = Either.right(storageOperationStatus);
return result;
}
@@ -1878,18 +1894,15 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
}
- public Either<GroupDefinition, StorageOperationStatus> dissociateMembersFromGroup(String groupId,
- Map<String, String> members, boolean inTransaction) {
+ public Either<GroupDefinition, StorageOperationStatus> dissociateMembersFromGroup(String groupId, Map<String, String> members, boolean inTransaction) {
Either<GroupDefinition, StorageOperationStatus> result = null;
try {
- Either<GroupDefinition, TitanOperationStatus> titanRes = this.dissociateMembersFromGroupOnGraph(groupId,
- members);
+ Either<GroupDefinition, TitanOperationStatus> titanRes = this.dissociateMembersFromGroupOnGraph(groupId, members);
if (titanRes.isRight()) {
- StorageOperationStatus storageOperationStatus = DaoStatusConverter
- .convertTitanStatusToStorageStatus(titanRes.right().value());
+ StorageOperationStatus storageOperationStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(titanRes.right().value());
result = Either.right(storageOperationStatus);
return result;
}
@@ -1920,19 +1933,16 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
* @param inTransaction
* @return
*/
- public Either<GroupDefinition, StorageOperationStatus> associateArtifactsToGroup(String groupId,
- List<String> artifactsId, boolean inTransaction) {
+ public Either<GroupDefinition, StorageOperationStatus> associateArtifactsToGroup(String groupId, List<String> artifactsId, boolean inTransaction) {
Either<GroupDefinition, StorageOperationStatus> result = null;
try {
- Either<GroupDefinition, TitanOperationStatus> titanRes = this.associateArtifactsToGroupOnGraph(groupId,
- artifactsId);
+ Either<GroupDefinition, TitanOperationStatus> titanRes = this.associateArtifactsToGroupOnGraph(groupId, artifactsId);
if (titanRes.isRight()) {
- StorageOperationStatus status = DaoStatusConverter
- .convertTitanStatusToStorageStatus(titanRes.right().value());
+ StorageOperationStatus status = DaoStatusConverter.convertTitanStatusToStorageStatus(titanRes.right().value());
result = Either.right(status);
}
@@ -1962,19 +1972,16 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
* @param inTransaction
* @return
*/
- public Either<GroupDefinition, StorageOperationStatus> associateMembersToGroup(String groupId,
- Map<String, String> members, boolean inTransaction) {
+ public Either<GroupDefinition, StorageOperationStatus> associateMembersToGroup(String groupId, Map<String, String> members, boolean inTransaction) {
Either<GroupDefinition, StorageOperationStatus> result = null;
try {
- Either<GroupDefinition, TitanOperationStatus> titanRes = this.associateMembersToGroupOnGraph(groupId,
- members);
+ Either<GroupDefinition, TitanOperationStatus> titanRes = this.associateMembersToGroupOnGraph(groupId, members);
if (titanRes.isRight()) {
- StorageOperationStatus status = DaoStatusConverter
- .convertTitanStatusToStorageStatus(titanRes.right().value());
+ StorageOperationStatus status = DaoStatusConverter.convertTitanStatusToStorageStatus(titanRes.right().value());
result = Either.right(status);
return result;
}
@@ -1997,18 +2004,15 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
}
- public Either<List<GroupDefinition>, StorageOperationStatus> updateGroupVersion(List<String> groupsId,
- boolean inTransaction) {
+ public Either<List<GroupDefinition>, StorageOperationStatus> updateGroupVersion(List<String> groupsId, boolean inTransaction) {
Either<List<GroupDefinition>, StorageOperationStatus> result = null;
try {
- Either<List<GroupDefinition>, TitanOperationStatus> updateGroupVersionOnGraph = this
- .updateGroupVersionOnGraph(groupsId);
+ Either<List<GroupDefinition>, TitanOperationStatus> updateGroupVersionOnGraph = this.updateGroupVersionOnGraph(groupsId);
if (updateGroupVersionOnGraph.isRight()) {
- result = Either.right(DaoStatusConverter
- .convertTitanStatusToStorageStatus(updateGroupVersionOnGraph.right().value()));
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateGroupVersionOnGraph.right().value()));
return result;
}
@@ -2029,42 +2033,53 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
}
}
-
- public Either<GroupDefinition, StorageOperationStatus> updateGroupName(String uniqueId, String newName,
- boolean inTransaction) {
+ /**
+ * This method updates group name
+ * @param groupToUpdateFromUniqueId
+ * @param newName
+ * @param inTransaction
+ * @return
+ */
+ public Either<GroupDefinition, StorageOperationStatus> updateGroupName(String groupToUpdateFromUniqueId,
+ String newName, boolean inTransaction) {
Either<GroupDefinition, StorageOperationStatus> result = null;
try {
- Either<GroupDefinition, TitanOperationStatus> updateGroupNameOnGraph = this.updateGroupNameOnGraph(uniqueId,
- newName);
+ //Update Name
+ Either<GroupDefinition, TitanOperationStatus> updateGroupNameOnGraph = updateGroupNameOnGraph(
+ groupToUpdateFromUniqueId, newName);
if (updateGroupNameOnGraph.isRight()) {
result = Either.right(
DaoStatusConverter.convertTitanStatusToStorageStatus(updateGroupNameOnGraph.right().value()));
- return result;
+ }
+ else{
+ result = Either.left(updateGroupNameOnGraph.left().value());
}
+ return result;
- result = Either.left(updateGroupNameOnGraph.left().value());
+ } finally {
+ handleTransactionCommitRollback(inTransaction, result);
+ }
+ }
+ @Override
+ public Either<GroupDefinition, StorageOperationStatus> updateGroupName(String groupToUpdateFromUniqueId,
+ String newName, GroupDefinition groupToUpdateTo, boolean inTransaction) {
+ Either<GroupDefinition, StorageOperationStatus> result = null;
+
+ try {
+ //Update Name
+ result = updateGroupName(groupToUpdateFromUniqueId, newName, true);
return result;
} finally {
- if (false == inTransaction) {
- if (result == null || result.isRight()) {
- log.debug("Going to execute rollback on graph.");
- BeEcompErrorManager.getInstance().logBeExecuteRollbackError("Rollback on graph");
- titanGenericDao.rollback();
- } else {
- log.debug("Going to execute commit on graph.");
- titanGenericDao.commit();
- }
- }
+ handleTransactionCommitRollback(inTransaction, result);
}
}
private Either<GroupDefinition, TitanOperationStatus> updateGroupNameOnGraph(String uniqueId, String newName) {
- Either<GroupDefinition, TitanOperationStatus> groupFromGraph = this.getGroupFromGraph(uniqueId, false, false,
- false);
+ Either<GroupDefinition, TitanOperationStatus> groupFromGraph = this.getGroupFromGraph(uniqueId, false, false, false);
if (groupFromGraph.isRight()) {
TitanOperationStatus status = groupFromGraph.right().value();
@@ -2090,4 +2105,32 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
}
}
}
+
+
+ @Override
+ public StorageOperationStatus validateAndUpdatePropertyValue(GroupProperty property) {
+
+ StorageOperationStatus result = null;
+ String innerType = property.getSchema() == null ? null : property.getSchema().getProperty() == null ? null : property.getSchema().getProperty().getType();
+ Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
+ Either<Object, Boolean> isValid = null;
+ if (allDataTypes.isRight()) {
+ TitanOperationStatus status = allDataTypes.right().value();
+ log.debug("Failed to fetch data types from cache. Status is {}. ", status);
+ result = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
+ }
+ if(result == null){
+ isValid = propertyOperation.validateAndUpdatePropertyValue(property.getType(), property.getValue(), innerType, allDataTypes.left().value());
+ if(isValid.isRight()){
+ log.debug("Failed to validate property value {}. Status is {}. ", property.getValue(), StorageOperationStatus.INVALID_PROPERTY);
+ result = StorageOperationStatus.INVALID_PROPERTY;
+ }
+ }
+ if(result == null){
+ String validValue = String.valueOf(isValid.left().value());
+ property.setValue(validValue);
+ result = StorageOperationStatus.OK;
+ }
+ return result;
+ }
}
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 4251e503e6..2fcdf695be 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
@@ -27,8 +27,6 @@ import java.util.Map;
import java.util.Set;
import java.util.function.Function;
-import javax.annotation.Resource;
-
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
@@ -48,6 +46,7 @@ import org.openecomp.sdc.be.resources.data.GroupTypeData;
import org.openecomp.sdc.be.resources.data.PropertyData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import fj.data.Either;
@@ -58,11 +57,14 @@ public class GroupTypeOperation extends AbstractOperation implements IGroupTypeO
String CREATE_FLOW_CONTEXT = "CreateGroupType";
String GET_FLOW_CONTEXT = "GetGroupType";
- @Resource
private PropertyOperation propertyOperation;
+
+ private TitanGenericDao titanGenericDao;
- public GroupTypeOperation() {
+ public GroupTypeOperation(@Qualifier("titan-generic-dao") TitanGenericDao titanGenericDao, @Qualifier("property-operation")PropertyOperation propertyOperation) {
super();
+ this.propertyOperation = propertyOperation;
+ this.titanGenericDao = titanGenericDao;
}
private static Logger log = LoggerFactory.getLogger(GroupTypeOperation.class.getName());
@@ -83,8 +85,7 @@ public class GroupTypeOperation extends AbstractOperation implements IGroupTypeO
}
@Override
- public Either<GroupTypeDefinition, StorageOperationStatus> addGroupType(GroupTypeDefinition groupTypeDefinition,
- boolean inTransaction) {
+ public Either<GroupTypeDefinition, StorageOperationStatus> addGroupType(GroupTypeDefinition groupTypeDefinition, boolean inTransaction) {
Either<GroupTypeDefinition, StorageOperationStatus> result = null;
@@ -93,10 +94,8 @@ public class GroupTypeOperation extends AbstractOperation implements IGroupTypeO
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()));
+ 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();
@@ -105,8 +104,7 @@ public class GroupTypeOperation extends AbstractOperation implements IGroupTypeO
Either<GroupTypeDefinition, StorageOperationStatus> groupTypeRes = this.getGroupType(uniqueId, true);
if (groupTypeRes.isRight()) {
- BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError(GET_FLOW_CONTEXT,
- groupTypeDefinition.getType(), eitherStatus.right().value().name());
+ BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError(GET_FLOW_CONTEXT, groupTypeDefinition.getType(), eitherStatus.right().value().name());
}
result = groupTypeRes;
@@ -125,20 +123,18 @@ public class GroupTypeOperation extends AbstractOperation implements IGroupTypeO
Either<GroupTypeDefinition, TitanOperationStatus> result = null;
- Either<GroupTypeData, TitanOperationStatus> groupTypesRes = titanGenericDao
- .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.GroupType), uniqueId, GroupTypeData.class);
+ 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);
+ 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,
- properList -> groupTypeDefinition.setProperties(properList));
+ TitanOperationStatus propertiesStatus = propertyOperation.fillProperties(uniqueId, properList -> groupTypeDefinition.setProperties(properList));
if (propertiesStatus != TitanOperationStatus.OK) {
log.error("Failed to fetch properties of capability type {}", uniqueId);
@@ -159,8 +155,7 @@ public class GroupTypeOperation extends AbstractOperation implements IGroupTypeO
@Override
public Either<GroupTypeDefinition, StorageOperationStatus> getGroupType(String uniqueId, boolean inTransaction) {
- Function<String, Either<GroupTypeDefinition, TitanOperationStatus>> groupTypeGetter = uId -> getGroupTypeByUid(
- uId);
+ Function<String, Either<GroupTypeDefinition, TitanOperationStatus>> groupTypeGetter = uId -> getGroupTypeByUid(uId);
return getElementType(groupTypeGetter, uniqueId, inTransaction);
}
@@ -171,8 +166,7 @@ public class GroupTypeOperation extends AbstractOperation implements IGroupTypeO
}
@Override
- public Either<GroupTypeDefinition, StorageOperationStatus> getLatestGroupTypeByType(String type,
- boolean inTransaction) {
+ 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);
@@ -181,8 +175,7 @@ public class GroupTypeOperation extends AbstractOperation implements IGroupTypeO
}
- public Either<GroupTypeDefinition, StorageOperationStatus> getGroupTypeByCriteria(String type,
- Map<String, Object> properties, boolean 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()) {
@@ -191,14 +184,11 @@ public class GroupTypeOperation extends AbstractOperation implements IGroupTypeO
return result;
}
- Either<List<GroupTypeData>, TitanOperationStatus> groupTypeEither = titanGenericDao
- .getByCriteria(NodeTypeEnum.GroupType, properties, GroupTypeData.class);
+ Either<List<GroupTypeData>, TitanOperationStatus> groupTypeEither = titanGenericDao.getByCriteria(NodeTypeEnum.GroupType, properties, GroupTypeData.class);
if (groupTypeEither.isRight()) {
- result = Either
- .right(DaoStatusConverter.convertTitanStatusToStorageStatus(groupTypeEither.right().value()));
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(groupTypeEither.right().value()));
} else {
- GroupTypeDataDefinition dataDefinition = groupTypeEither.left().value().stream()
- .map(e -> e.getGroupTypeDataDefinition()).findFirst().get();
+ GroupTypeDataDefinition dataDefinition = groupTypeEither.left().value().stream().map(e -> e.getGroupTypeDataDefinition()).findFirst().get();
result = getGroupType(dataDefinition.getUniqueId(), inTransaction);
}
@@ -210,14 +200,12 @@ public class GroupTypeOperation extends AbstractOperation implements IGroupTypeO
}
@Override
- public Either<GroupTypeDefinition, StorageOperationStatus> getGroupTypeByTypeAndVersion(String type,
- String version) {
+ 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) {
+ 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);
@@ -233,8 +221,7 @@ public class GroupTypeOperation extends AbstractOperation implements IGroupTypeO
*
* 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)
+ * 3. Add property node and associate it to the node created at #1. (per property & if exists)
*
* @param groupTypeDefinition
* @return
@@ -243,28 +230,25 @@ public class GroupTypeOperation extends AbstractOperation implements IGroupTypeO
log.debug("Got group type {}", groupTypeDefinition);
- String ctUniqueId = UniqueIdBuilder.buildGroupTypeUid(groupTypeDefinition.getType(),
- groupTypeDefinition.getVersion());
+ 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);
+ 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);
+ 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);
+ 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());
@@ -276,14 +260,9 @@ public class GroupTypeOperation extends AbstractOperation implements IGroupTypeO
// 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, if (createRelation.isRight()) { return
- * Either.right(createRelation.right().value()); }
+ * 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()); }
*
*/
}
@@ -302,8 +281,7 @@ public class GroupTypeOperation extends AbstractOperation implements IGroupTypeO
protected CapabilityTypeDefinition convertCTDataToCTDefinition(CapabilityTypeData capabilityTypeData) {
log.debug("The object returned after create capability is {}", capabilityTypeData);
- CapabilityTypeDefinition capabilityTypeDefResult = new CapabilityTypeDefinition(
- capabilityTypeData.getCapabilityTypeDataDefinition());
+ CapabilityTypeDefinition capabilityTypeDefResult = new CapabilityTypeDefinition(capabilityTypeData.getCapabilityTypeDataDefinition());
return capabilityTypeDefResult;
}
@@ -323,12 +301,10 @@ public class GroupTypeOperation extends AbstractOperation implements IGroupTypeO
return groupTypeData;
}
- public Either<Boolean, StorageOperationStatus> isCapabilityTypeDerivedFrom(String childCandidateType,
- String parentCandidateType) {
+ 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);
+ 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);
@@ -338,14 +314,12 @@ public class GroupTypeOperation extends AbstractOperation implements IGroupTypeO
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);
+ 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);
+ 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.");
@@ -354,8 +328,7 @@ public class GroupTypeOperation extends AbstractOperation implements IGroupTypeO
}
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);
+ log.debug("Verified that capability type {} derives from capability type {}", childCandidateType, parentCandidateType);
return Either.left(true);
}
childUniqueId = derivedFromUniqueId;
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/HeatParametersOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/HeatParametersOperation.java
index 5d7b8c5991..ad56779a94 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/HeatParametersOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/HeatParametersOperation.java
@@ -128,7 +128,7 @@ public class HeatParametersOperation implements IHeatParametersOperation {
for (ImmutablePair<HeatParameterValueData, GraphEdge> immutablePair : values) {
GraphEdge edge = immutablePair.getValue();
String propertyName = (String) edge.getProperties().get(GraphPropertiesDictionary.NAME.getProperty());
- log.trace("Heat value " + propertyName + " is associated to node " + parentUniqueId);
+ log.trace("Heat value {} is associated to node {}", propertyName,parentUniqueId);
HeatParameterValueData propertyData = immutablePair.getKey();
heatValues.add(propertyData);
@@ -193,17 +193,17 @@ public class HeatParametersOperation implements IHeatParametersOperation {
}
- log.debug("The heat values deleted from node {} are {}", parentUniqueId, heatValues);
+ log.debug("The heat values deleted from node {} are {}" , parentUniqueId, heatValues);
return StorageOperationStatus.OK;
}
private Either<HeatParameterData, TitanOperationStatus> deleteHeatParameterFromGraph(String propertyId) {
- log.debug("Before deleting heat parameter from graph {}", propertyId);
+ log.debug("Before deleting heat parameter from graph {}" , propertyId);
return titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.HeatParameter), propertyId, HeatParameterData.class);
}
private Either<HeatParameterValueData, TitanOperationStatus> deleteHeatParameterValueFromGraph(String propertyId) {
- log.debug("Before deleting heat parameter from graph {}", propertyId);
+ log.debug("Before deleting heat parameter from graph {}" , propertyId);
return titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.HeatParameterValue), propertyId, HeatParameterValueData.class);
}
@@ -215,17 +215,6 @@ public class HeatParametersOperation implements IHeatParametersOperation {
String propertyName = propertyDefinition.getName();
- // type and value should be validated in business logic:
- // ArtifactsBusinessLogic.validateAndConvertHeatParamers(ArtifactDefinition)
-
- // StorageOperationStatus validateAndUpdateProperty =
- // validateAndUpdateProperty(propertyDefinition);
- // if (validateAndUpdateProperty != StorageOperationStatus.OK) {
- // log.error("Property " + propertyDefinition + " is invalid.
- // Status is " + validateAndUpdateProperty);
- // return StorageOperationStatus.BAD_REQUEST;
- // }
-
Either<HeatParameterData, TitanOperationStatus> addPropertyToGraph = addPropertyToGraph(propertyName, propertyDefinition, parentId, nodeType);
if (addPropertyToGraph.isRight()) {
@@ -264,12 +253,12 @@ public class HeatParametersOperation implements IHeatParametersOperation {
propertyDefinition.setUniqueId(UniqueIdBuilder.buildHeatParameterUniqueId(parentId, propertyName));
HeatParameterData propertyData = new HeatParameterData(propertyDefinition);
- log.debug("Before adding property to graph {}", propertyData);
+ log.debug("Before adding property to graph {}" , propertyData);
Either<HeatParameterData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(propertyData, HeatParameterData.class);
- log.debug("After adding property to graph {}", propertyData);
+ log.debug("After adding property to graph {}" , propertyData);
if (createNodeResult.isRight()) {
TitanOperationStatus operationStatus = createNodeResult.right().value();
- log.error("Failed to add property {} to graph. Status is {}", propertyName, operationStatus);
+ log.error("Failed to add property {} to graph. status is {}", propertyName, operationStatus);
return Either.right(operationStatus);
}
@@ -278,10 +267,7 @@ public class HeatParametersOperation implements IHeatParametersOperation {
Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(parentNode, propertyData, GraphEdgeLabels.HEAT_PARAMETER, props);
if (createRelResult.isRight()) {
TitanOperationStatus operationStatus = createRelResult.right().value();
-
- if (log.isDebugEnabled()) {
- log.error("Failed to associate {} {} to heat parameter {} in graph. Status is {}", nodeType.getName(), parentId, propertyName, operationStatus);
- }
+ log.error("Failed to associate {} {} to heat parameter {} in graph. status is {}", nodeType.getName(), parentId, propertyName, operationStatus);
return Either.right(operationStatus);
}
@@ -291,13 +277,13 @@ public class HeatParametersOperation implements IHeatParametersOperation {
public StorageOperationStatus validateAndUpdateProperty(HeatParameterDefinition propertyDefinition) {
- log.trace("Going to validate property type and value. {}", propertyDefinition);
+ log.trace("Going to validate property type and value. {}" , propertyDefinition);
String propertyType = propertyDefinition.getType();
HeatParameterType type = getType(propertyType);
if (type == null) {
- log.info("The type {} of heat is invalid", type);
+ log.info("The type {} of heat parameter is invalid", type);
return StorageOperationStatus.INVALID_TYPE;
}
@@ -316,7 +302,8 @@ public class HeatParametersOperation implements IHeatParametersOperation {
PropertyValueConverter converter = type.getConverter();
if (isEmptyValue(defaultValue)) {
- log.debug("Default value was not sent for property {}. Set default value to {}", propertyDefinition.getName(), EMPTY_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(defaultValue)) {
String convertedValue = converter.convert(defaultValue, null, null);
@@ -333,6 +320,7 @@ public class HeatParametersOperation implements IHeatParametersOperation {
if (isEmptyValue(value)) {
log.debug("Value was not sent for property {}. Set value to {}", propertyDefinition.getName(), EMPTY_VALUE);
+
propertyDefinition.setCurrentValue(EMPTY_VALUE);
} else if (!value.equals("")) {
String convertedValue = converter.convert(value, null, null);
@@ -465,7 +453,7 @@ public class HeatParametersOperation implements IHeatParametersOperation {
log.debug("After adding property to graph {}", heatValueData);
if (createNodeResult.isRight()) {
TitanOperationStatus operationStatus = createNodeResult.right().value();
- log.error("Failed to add heat value {} to graph. Status is {}", heatValueData.getUniqueId(), operationStatus);
+ log.error("Failed to add heat value {} to graph. status is {}", heatValueData.getUniqueId(), operationStatus);
return Either.right(operationStatus);
}
@@ -474,14 +462,14 @@ public class HeatParametersOperation implements IHeatParametersOperation {
Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(heatEnvNode, heatValueData, GraphEdgeLabels.PARAMETER_VALUE, props);
if (createRelResult.isRight()) {
TitanOperationStatus operationStatus = createRelResult.right().value();
- log.error("Failed to associate heat value {} to heat env artifact {} in graph. Status is {}", heatValueData.getUniqueId(), artifactId, operationStatus);
+ log.error("Failed to associate heat value {} to heat env artifact {} in graph. status is {}", heatValueData.getUniqueId(), artifactId, operationStatus);
return Either.right(operationStatus);
}
UniqueIdData heatParameterNode = new UniqueIdData(NodeTypeEnum.HeatParameter, heatParameter.getUniqueId());
Either<GraphRelation, TitanOperationStatus> createRel2Result = titanGenericDao.createRelation(heatValueData, heatParameterNode, GraphEdgeLabels.PARAMETER_IMPL, null);
if (createRel2Result.isRight()) {
TitanOperationStatus operationStatus = createRel2Result.right().value();
- log.error("Failed to associate heat value {} to heat parameter {} in graph. Status is {}", heatValueData.getUniqueId(), heatParameter.getName(), operationStatus);
+ log.error("Failed to associate heat value {} to heat parameter {} in graph. status is {}", heatValueData.getUniqueId(), heatParameter.getName(), operationStatus);
return Either.right(operationStatus);
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/InputsOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/InputsOperation.java
index e2d13a9cff..dba4ff9b75 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/InputsOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/InputsOperation.java
@@ -28,12 +28,15 @@ import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
+import javax.json.Json;
+
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.tinkerpop.gremlin.process.traversal.Order;
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.json.simple.JSONObject;
+import org.json.simple.parser.ParseException;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
import org.openecomp.sdc.be.dao.graph.GraphElementFactory;
@@ -45,15 +48,18 @@ import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
import org.openecomp.sdc.be.dao.neo4j.GraphEdgePropertiesDictionary;
import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
+
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.model.ComponentInstInputsMap;
import org.openecomp.sdc.be.model.ComponentInstance;
import org.openecomp.sdc.be.model.ComponentInstanceInput;
+import org.openecomp.sdc.be.model.ComponentInstancePropInput;
import org.openecomp.sdc.be.model.ComponentInstanceProperty;
import org.openecomp.sdc.be.model.DataTypeDefinition;
-import org.openecomp.sdc.be.model.GetInputValueInfo;
import org.openecomp.sdc.be.model.InputDefinition;
import org.openecomp.sdc.be.model.PropertyConstraint;
+import org.openecomp.sdc.be.model.PropertyDefinition;
import org.openecomp.sdc.be.model.operations.api.IInputsOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.resources.data.AttributeData;
@@ -70,6 +76,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
+import org.yaml.snakeyaml.Yaml;
import com.google.gson.Gson;
import com.thinkaurelius.titan.core.TitanEdge;
@@ -83,9 +90,13 @@ import fj.data.Either;
@Component("input-operation")
public class InputsOperation extends AbstractOperation implements IInputsOperation {
+ private static final String GET_INPUT = "get_input";
+
private static String ASSOCIATING_INPUT_TO_PROP = "AssociatingInputToComponentInstanceProperty";
private static Logger log = LoggerFactory.getLogger(InputsOperation.class.getName());
+ @Autowired
+ PropertyOperation propertyOperation;
@Autowired
private ComponentInstanceOperation componentInstanceOperation;
@@ -95,18 +106,103 @@ public class InputsOperation extends AbstractOperation implements IInputsOperati
* Delete specific input from component Although inputId is unique, pass also componentId as all other methods, and also check that the inputId is inside that componentId.
*/
@Override
- public Either<String, StorageOperationStatus> deleteInput(String inputId) {
+ public Either<InputDefinition, StorageOperationStatus> deleteInput(String inputId) {
log.debug(String.format("Before deleting input: %s from graph", inputId));
+ List<ComponentInstanceInput> inputsValueList = null;
+ List<ComponentInstanceProperty> propertyList = new ArrayList<>();
+
+ Either<TitanVertex, TitanOperationStatus> vertexService = titanGenericDao.getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), inputId);
+
+ if (vertexService.isRight()) {
+ log.debug("failed to fetch vertex of resource input for id = {}", inputId);
+ TitanOperationStatus status = vertexService.right().value();
+ if (status == TitanOperationStatus.NOT_FOUND) {
+ status = TitanOperationStatus.INVALID_ID;
+ }
+
+ StorageOperationStatus convertTitanStatusToStorageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
+ return Either.right(convertTitanStatusToStorageStatus);
+ }
+ TitanVertex vertex = vertexService.left().value();
+ Iterator<Edge> edgeIter = vertex.edges(Direction.IN, GraphEdgeLabels.INPUT.getProperty());
+
+ if (edgeIter == null) {
+ log.debug("No edges in graph for criteria");
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.NOT_FOUND));
+ }
+ String inputName = "";
+ if (edgeIter != null) {
+ while (edgeIter.hasNext()) {
+ Edge edge = edgeIter.next();
+ GraphEdge graphEdge = null;
+
+ Map<String, Object> edgeProps = titanGenericDao.getProperties(edge);
+ GraphEdgeLabels edgeTypeFromGraph = GraphEdgeLabels.getByName(edge.label());
+ graphEdge = new GraphEdge(edgeTypeFromGraph, edgeProps);
+
+ inputName = (String) graphEdge.getProperties().get(GraphEdgePropertiesDictionary.NAME.getProperty());
+
+ }
+ }
+
+
Either<List<ComponentInstanceInput>, TitanOperationStatus> inputsValueStatus = this.getComponentInstanceInputsByInputId(inputId);
if(inputsValueStatus.isLeft()){
- List<ComponentInstanceInput> inputsValueLis = inputsValueStatus.left().value();
- if(!inputsValueLis.isEmpty()){
- for(ComponentInstanceInput inputValue: inputsValueLis){
+ inputsValueList = inputsValueStatus.left().value();
+ if(!inputsValueList.isEmpty()){
+ for(ComponentInstanceInput inputValue: inputsValueList){
Either<InputValueData, TitanOperationStatus> deleteNode = titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.InputValue), inputValue.getValueUniqueUid(), InputValueData.class);
if (deleteNode.isRight()) {
StorageOperationStatus convertTitanStatusToStorageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(deleteNode.right().value());
return Either.right(convertTitanStatusToStorageStatus);
- }
+ }
+ }
+ }
+ // US848813 delete service input that relates to VL / CP property
+ } else {
+ Either<List<ComponentInstanceProperty>, TitanOperationStatus> propertyValueStatus = getComponentInstancePropertiesByInputId(inputId);
+ if(propertyValueStatus.isLeft() && !propertyValueStatus.left().value().isEmpty()){
+ //propertyList = propertyValueStatus.left().value();
+ for(ComponentInstanceProperty propertyValue: propertyValueStatus.left().value()){
+
+ String value = propertyValue.getValue();
+ Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(value);
+
+ resetInputName(mappedToscaTemplate, inputName);
+
+ value = gson.toJson(mappedToscaTemplate);
+ propertyValue.setValue(value);
+ String compInstId = propertyValue.getComponentInstanceId();
+ propertyValue.setRules(null);
+
+ Either<PropertyValueData, TitanOperationStatus> eitherStatus = componentInstanceOperation.updatePropertyOfResourceInstance(propertyValue, compInstId, false);
+
+ if (eitherStatus.isRight()) {
+ log.error("Failed to add property value {} to resource instance {} in Graph. status is {}", propertyValue, compInstId, eitherStatus.right().value().name());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(eitherStatus.right().value()));
+
+ } else {
+ PropertyValueData propertyValueData = eitherStatus.left().value();
+
+ ComponentInstanceProperty propertyValueResult = propertyOperation.buildResourceInstanceProperty(propertyValueData, propertyValue);
+
+ log.debug("The returned ResourceInstanceProperty is {}", propertyValueResult);
+
+ Either<String, TitanOperationStatus> findDefaultValue = propertyOperation.findDefaultValueFromSecondPosition(propertyValue.getPath(), propertyValueData.getUniqueId(), propertyValue.getDefaultValue());
+ if (findDefaultValue.isRight()) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(findDefaultValue.right().value()));
+
+ }
+ String defaultValue = findDefaultValue.left().value();
+ propertyValueResult.setDefaultValue(defaultValue);
+ log.debug("The returned default value in ResourceInstanceProperty is {}", defaultValue);
+
+ propertyValueResult.setComponentInstanceId(compInstId);
+ propertyList.add(propertyValueResult);
+
+
+ }
+
}
}
}
@@ -115,7 +211,11 @@ public class InputsOperation extends AbstractOperation implements IInputsOperati
StorageOperationStatus convertTitanStatusToStorageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(deleteNode.right().value());
return Either.right(convertTitanStatusToStorageStatus);
} else {
- return Either.left(inputId);
+ InputDefinition inputDefinition = this.convertInputDataToInputDefinition(deleteNode.left().value());
+ inputDefinition.setInputs(inputsValueList);
+ inputDefinition.setProperties(propertyList);
+ inputDefinition.setName(inputName);
+ return Either.left(inputDefinition);
}
}
@@ -131,7 +231,7 @@ public class InputsOperation extends AbstractOperation implements IInputsOperati
StorageOperationStatus validateAndUpdateProperty = validateAndUpdateProperty(propertyDefinition, dataTypes);
if (validateAndUpdateProperty != StorageOperationStatus.OK) {
- log.error("Property " + propertyDefinition + " is invalid. Status is " + validateAndUpdateProperty);
+ log.error("Property {} is invalid. Status is {}", propertyDefinition, validateAndUpdateProperty);
return Either.right(TitanOperationStatus.INVALID_PROPERTY);
}
@@ -312,6 +412,8 @@ public class InputsOperation extends AbstractOperation implements IInputsOperati
if (createNodeResult.isRight()) {
TitanOperationStatus operationStatus = createNodeResult.right().value();
log.error("Failed to add input {} to graph. status is {}", propertyName, operationStatus);
+ if(operationStatus == TitanOperationStatus.TITAN_SCHEMA_VIOLATION )
+ return Either.right(TitanOperationStatus.ALREADY_EXIST);
return Either.right(operationStatus);
}
@@ -447,7 +549,7 @@ public class InputsOperation extends AbstractOperation implements IInputsOperati
public <ElementDefinition> TitanOperationStatus findAllResourceElementsDefinitionRecursively(String resourceId, List<ElementDefinition> elements, NodeElementFetcher<ElementDefinition> singleNodeFetcher) {
- log.trace("Going to fetch elements under resource {}", resourceId);
+ log.trace("Going to fetch elements under resource {}" , resourceId);
TitanOperationStatus resourceAttributesStatus = singleNodeFetcher.findAllNodeElements(resourceId, elements);
if (resourceAttributesStatus != TitanOperationStatus.OK) {
@@ -514,7 +616,7 @@ public class InputsOperation extends AbstractOperation implements IInputsOperati
}
- public TitanOperationStatus associatePropertyToInput(String riId, String inputId, ComponentInstanceProperty property, GetInputValueInfo getInput) {
+ public TitanOperationStatus associatePropertyToInput(String riId, String inputId, ComponentInstanceProperty property, GetInputValueDataDefinition getInput) {
TitanOperationStatus status = TitanOperationStatus.OK;
Either<TitanGraph, TitanOperationStatus> graphRes = titanGenericDao.getGraph();
if (graphRes.isRight()) {
@@ -536,10 +638,14 @@ public class InputsOperation extends AbstractOperation implements IInputsOperati
if(getInput!=null){
props.put(GraphEdgePropertiesDictionary.NAME.getProperty(), getInput.getPropName());
if (getInput.isList()) {
- String index = getInput.getIndexValue().toString();
- if (getInput.getGetInputIndex() != null) {
- index = getInput.getGetInputIndex().getInputName();
-
+ String index = "";
+ if(getInput.getIndexValue()!= null ){
+ index = getInput.getIndexValue().toString();
+ }else{
+ if (getInput.getGetInputIndex() != null) {
+ index = getInput.getGetInputIndex().getInputName();
+
+ }
}
props.put(GraphEdgePropertiesDictionary.GET_INPUT_INDEX.getProperty(), index);
}
@@ -627,7 +733,7 @@ public class InputsOperation extends AbstractOperation implements IInputsOperati
}
- groupDefinition.setInputsValue(propsList);
+ groupDefinition.setInputs(propsList);
}
}
@@ -704,7 +810,7 @@ public class InputsOperation extends AbstractOperation implements IInputsOperati
Either<List<ComponentInstanceInput>, TitanOperationStatus> getAllRes = getAllInputsOfResourceInstanceOnlyInputDefId(resourceInstanceId);
if (getAllRes.isRight()) {
TitanOperationStatus status = getAllRes.right().value();
- log.trace("After fetching all properties of resource instance {}. Status is {}", resourceInstanceId, status);
+ log.trace("After fetching all properties of resource instance {}. Status is {}" ,resourceInstanceId, status);
return new ImmutablePair<TitanOperationStatus, String>(status, null);
}
@@ -713,7 +819,7 @@ public class InputsOperation extends AbstractOperation implements IInputsOperati
for (ComponentInstanceInput instanceProperty : list) {
String propertyUniqueId = instanceProperty.getUniqueId();
String valueUniqueUid = instanceProperty.getValueUniqueUid();
- log.trace("Go over property {} under resource instance {}. valueUniqueId = {}", propertyUniqueId, resourceInstanceId, valueUniqueUid);
+ log.trace("Go over property {} under resource instance {}. valueUniqueId = {}" ,propertyUniqueId, resourceInstanceId, valueUniqueUid);
if (propertyId.equals(propertyUniqueId) && valueUniqueUid != null) {
log.debug("The property {} already created under resource instance {}", propertyId, resourceInstanceId);
return new ImmutablePair<TitanOperationStatus, String>(TitanOperationStatus.ALREADY_EXIST, valueUniqueUid);
@@ -1031,19 +1137,36 @@ public class InputsOperation extends AbstractOperation implements IInputsOperati
PropertyValueData propertyValueData = propertyValueDataPair.left;
String propertyValueUid = propertyValueData.getUniqueId();
String value = propertyValueData.getValue();
+
+ String componentInstanceId = (String) propertyValueDataPair.right.getProperties().get(GraphEdgePropertiesDictionary.OWNER_ID.getProperty());
Either<ImmutablePair<PropertyData, GraphEdge>, TitanOperationStatus> propertyDefRes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.PropertyValue), propertyValueUid, GraphEdgeLabels.PROPERTY_IMPL, NodeTypeEnum.Property, PropertyData.class);
if (propertyDefRes.isRight()) {
TitanOperationStatus status = propertyDefRes.right().value();
- if (status == TitanOperationStatus.NOT_FOUND) {
- status = TitanOperationStatus.INVALID_ID;
- }
return Either.right(status);
}
ImmutablePair<PropertyData, GraphEdge> propertyDefPair = propertyDefRes.left().value();
PropertyData propertyData = propertyDefPair.left;
String propertyUniqueId = (String) propertyData.getPropertyDataDefinition().getUniqueId();
+
+ Either<TitanVertex, TitanOperationStatus> originVertexEither = titanGenericDao.getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), propertyUniqueId);
+ if (originVertexEither.isRight()) {
+ log.debug("Failed to fetch vertex of property for id {} error {}", propertyUniqueId, originVertexEither.right().value());
+ return Either.right(originVertexEither.right().value());
+ }
+ TitanVertex originVertex = originVertexEither.left().value();
+ Iterator<Edge> edgeIter = originVertex.edges(Direction.IN, GraphEdgeLabels.PROPERTY.getProperty());
+ if (edgeIter == null) {
+ return Either.right(TitanOperationStatus.NOT_FOUND);
+ }
+
+ String propertyName = "";
+
+ while (edgeIter.hasNext()) {
+ TitanEdge edge = (TitanEdge) edgeIter.next();
+ propertyName = (String) edge.property(GraphEdgePropertiesDictionary.NAME.getProperty()).value();
+ }
ComponentInstanceProperty resourceInstanceProperty = new ComponentInstanceProperty();
// set property original unique id
@@ -1059,7 +1182,9 @@ public class InputsOperation extends AbstractOperation implements IInputsOperati
resourceInstanceProperty.setRules(propertyValueData.getRules());
resourceInstanceProperty.setType(propertyData.getPropertyDataDefinition().getType());
resourceInstanceProperty.setSchema(propertyData.getPropertyDataDefinition().getSchema());
- resourceInstanceProperty.setName((String) propertyValueDataPair.right.getProperties().get(GraphPropertiesDictionary.NAME.getProperty()));
+ resourceInstanceProperty.setName(propertyName);
+ resourceInstanceProperty.setComponentInstanceId(componentInstanceId);
+
result.add(resourceInstanceProperty);
}
@@ -1091,10 +1216,22 @@ public class InputsOperation extends AbstractOperation implements IInputsOperati
if (newInputsMap != null && !newInputsMap.isEmpty()) {
for (Entry<String, List<InputDefinition>> entry : newInputsMap.entrySet()) {
String compInstId = entry.getKey();
+ Either<TitanVertex, TitanOperationStatus> ciVertexEither = titanGenericDao.getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), compInstId);
+ if (ciVertexEither.isRight()) {
+ log.debug("Failed to fetch vertex of resource instance for id {} error {}", compInstId, ciVertexEither.right().value());
+ return Either.right( DaoStatusConverter.convertTitanStatusToStorageStatus(ciVertexEither.right().value()));
+ }
+ TitanVertex ciVertex = ciVertexEither.left().value();
+
+
+ //String originType = (String) titanGenericDao.getProperty(originVertex, GraphPropertiesDictionary.LABEL.getProperty());
+ String compInstname = (String) titanGenericDao.getProperty(ciVertex, GraphPropertiesDictionary.NORMALIZED_NAME.getProperty());
+
List<InputDefinition> inputs = entry.getValue();
if (inputs != null && !inputs.isEmpty()) {
for (InputDefinition input : inputs) {
+
Either<Integer, StorageOperationStatus> counterRes = componentInstanceOperation.increaseAndGetResourceInstanceSpecificCounter(compInstId, GraphPropertiesDictionary.INPUT_COUNTER, true);
if (counterRes.isRight()) {
@@ -1109,9 +1246,13 @@ public class InputsOperation extends AbstractOperation implements IInputsOperati
return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(oldInputEither.right().value()));
}
- JSONObject jobject = new JSONObject();
- jobject.put("get_input", input.getName());
+
InputDefinition oldInput = oldInputEither.left().value();
+ 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);
Integer index = counterRes.left().value();
@@ -1125,13 +1266,6 @@ public class InputsOperation extends AbstractOperation implements IInputsOperati
}
ComponentInstanceInput inputValueData = eitherStatus.left().value();
- // ComponentInstanceInput propertyValueResult =
- // buildResourceInstanceInput(propertyValueData,
- // inputValue);
- // log.debug("The returned ResourceInstanceProperty is "
- // + propertyValueResult);
-
- String inputName = input.getName();
input.setSchema(oldInputEither.left().value().getSchema());
input.setDefaultValue(oldInput.getDefaultValue());
input.setConstraints(oldInput.getConstraints());
@@ -1147,13 +1281,13 @@ public class InputsOperation extends AbstractOperation implements IInputsOperati
return Either.right(validateAndUpdateProperty);
}
- Either<InputsData, TitanOperationStatus> addPropertyToGraph = addInputToGraph(inputName, input, resourceId, nodeType);
+ Either<InputsData, TitanOperationStatus> addPropertyToGraph = addInputToGraph(serviceInputName, input, resourceId, nodeType);
if (addPropertyToGraph.isRight()) {
return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(addPropertyToGraph.right().value()));
}
InputDefinition createdInputyDefinition = convertInputDataToInputDefinition(addPropertyToGraph.left().value());
- createdInputyDefinition.setName(inputName);
+ createdInputyDefinition.setName(serviceInputName);
createdInputyDefinition.setParentUniqueId(resourceId);
Map<String, Object> props = new HashMap<String, Object>();
@@ -1178,7 +1312,275 @@ public class InputsOperation extends AbstractOperation implements IInputsOperati
}
}
+ Map<String, List<ComponentInstancePropInput>> newInputsPropsMap = componentInsInputs.getComponentInstanceProperties();
+ if (newInputsPropsMap != null && !newInputsPropsMap.isEmpty()) {
+ Either<List<InputDefinition>, StorageOperationStatus> result = createInputsFromProperty(resourceId, nodeType, dataTypes, resList, newInputsPropsMap);
+
+ if (result.isRight()) {
+ log.debug("Failed to create inputs of resource for id {} error {}", resourceId, result.right().value());
+ return result;
+ }
+ resList = result.left().value();
+
+ }
return Either.left(resList);
}
+ private Either<List<InputDefinition>, StorageOperationStatus> createInputsFromProperty(String resourceId, NodeTypeEnum nodeType, Map<String, DataTypeDefinition> dataTypes, List<InputDefinition> resList, Map<String, List<ComponentInstancePropInput>> newInputsPropsMap) {
+ for (Entry<String, List<ComponentInstancePropInput>> entry : newInputsPropsMap.entrySet()) {
+ String compInstId = entry.getKey();
+ List<ComponentInstancePropInput> properties = entry.getValue();
+
+ Either<TitanVertex, TitanOperationStatus> ciVertexEither = titanGenericDao.getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), compInstId);
+ if (ciVertexEither.isRight()) {
+ log.debug("Failed to fetch vertex of resource instance for id {} error {}", compInstId, ciVertexEither.right().value());
+ return Either.right( DaoStatusConverter.convertTitanStatusToStorageStatus(ciVertexEither.right().value()));
+ }
+ TitanVertex ciVertex = ciVertexEither.left().value();
+
+
+ //String originType = (String) titanGenericDao.getProperty(originVertex, GraphPropertiesDictionary.LABEL.getProperty());
+ String compInstname = (String) titanGenericDao.getProperty(ciVertex, GraphPropertiesDictionary.NORMALIZED_NAME.getProperty());
+ String inputName = compInstname;
+
+ if (properties != null && !properties.isEmpty()) {
+ for (ComponentInstancePropInput propInput : properties) {
+ Either<InputDefinition, StorageOperationStatus> createInputRes = createInputForComponentInstance(resourceId, nodeType, dataTypes, compInstId, inputName, propInput);
+
+ if (createInputRes.isRight()) {
+ log.debug("Failed to create input of resource instance for id {} error {}", compInstId, createInputRes.right().value());
+ return Either.right(createInputRes.right().value());
+ }
+
+ resList.add(createInputRes.left().value());
+
+ }
+ }
+
+ }
+ return Either.left(resList);
+ }
+
+ private Either<InputDefinition, StorageOperationStatus> createInputForComponentInstance(String resourceId, NodeTypeEnum nodeType, Map<String, DataTypeDefinition> dataTypes, String compInstId, String inputName, ComponentInstancePropInput propInput) {
+ String propertiesName = propInput.getPropertiesName() ;
+ PropertyDefinition selectedProp = propInput.getInput();
+ String[] parsedPropNames = propInput.getParsedPropNames();
+ if(parsedPropNames != null){
+ for(String str: parsedPropNames){
+ inputName += "_" + str;
+ }
+ } else {
+ inputName += "_" + propInput.getName();
+ }
+
+ InputDefinition input = null;
+ ComponentInstanceProperty prop = propInput;
+
+ if(propertiesName != null && !propertiesName.isEmpty() && selectedProp != null){
+ input = new InputDefinition(selectedProp);
+ }else{
+ input = new InputDefinition(prop);
+ input.setName(inputName + "_" + prop.getName());
+
+ }
+ input.setName(inputName);
+
+ JSONObject jobject = new JSONObject();
+
+
+ if(prop.getValueUniqueUid() == null || prop.getValueUniqueUid().isEmpty()){
+ if(propertiesName != null && !propertiesName.isEmpty() && selectedProp != null){
+
+ jobject = createJSONValueForProperty(parsedPropNames.length -1, parsedPropNames, jobject, inputName);
+ prop.setValue(jobject.toJSONString());
+
+ }else{
+
+ jobject.put(GET_INPUT, input.getName());
+ prop.setValue(jobject.toJSONString());
+
+
+ }
+ Either<Integer, StorageOperationStatus> increaseCounterRes = componentInstanceOperation.increaseAndGetResourceInstanceSpecificCounter(compInstId, GraphPropertiesDictionary.PROPERTY_COUNTER, true);
+ if (increaseCounterRes.isRight()) {
+ log.debug("Failed to increase resource property counter {} to resource instance {}", prop, compInstId);
+
+ return Either.right( increaseCounterRes.right().value());
+ }
+ Integer index = increaseCounterRes.left().value();
+ Either<ComponentInstanceProperty, StorageOperationStatus> result = componentInstanceOperation.addPropertyValueToResourceInstance(prop, compInstId, false, index, true);
+ if (result.isRight()) {
+ log.debug("Failed to add property value {} to resource instance {}", prop, compInstId);
+ return Either.right( result.right().value());
+ }
+ prop = result.left().value();
+
+ }else{
+
+ String value = prop.getValue();
+ if(value != null){
+ Object objValue = new Yaml().load(value);
+ if( objValue instanceof Map || objValue instanceof List ){
+ if(propertiesName == null ||propertiesName.isEmpty()){
+ jobject.put(GET_INPUT, input.getName());
+ prop.setValue(jobject.toJSONString());
+ prop.setRules(null);
+
+ }else{
+ Map<String, Object> mappedToscaTemplate = (Map<String, Object>) objValue;
+ createInputValue(mappedToscaTemplate, 1, parsedPropNames, inputName);
+ Gson gson = new Gson();
+ String json = gson.toJson(mappedToscaTemplate);
+ prop.setValue(json);
+ prop.setRules(null);
+ }
+
+ }else{
+ jobject.put(GET_INPUT, input.getName());
+ prop.setValue(jobject.toJSONString());
+ prop.setRules(null);
+ }
+ }else{
+ jobject.put(GET_INPUT, input.getName());
+ prop.setValue(jobject.toJSONString());
+ prop.setRules(null);
+ }
+
+ Either<PropertyValueData, TitanOperationStatus> eitherStatus = componentInstanceOperation.updatePropertyOfResourceInstance(prop, compInstId, false);
+
+ if (eitherStatus.isRight()) {
+ log.error("Failed to add property value {} to resource instance {} in Graph. status is {}", prop, compInstId, eitherStatus.right().value().name());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(eitherStatus.right().value()));
+
+ } else {
+ PropertyValueData propertyValueData = eitherStatus.left().value();
+
+ prop = propertyOperation.buildResourceInstanceProperty(propertyValueData, prop);
+
+ log.debug("The returned ResourceInstanceProperty is {}", prop);
+
+ Either<String, TitanOperationStatus> findDefaultValue = propertyOperation.findDefaultValueFromSecondPosition(prop.getPath(), propertyValueData.getUniqueId(), prop.getDefaultValue());
+ if (findDefaultValue.isRight()) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(findDefaultValue.right().value()));
+
+ }
+ String defaultValue = findDefaultValue.left().value();
+ prop.setDefaultValue(defaultValue);
+ log.debug("The returned default value in ResourceInstanceProperty is {}", defaultValue);
+
+ prop.setComponentInstanceId(compInstId);
+
+
+
+ }
+
+
+ }
+
+ StorageOperationStatus validateAndUpdateProperty = validateAndUpdateProperty(input, dataTypes);
+ if (validateAndUpdateProperty != StorageOperationStatus.OK) {
+ log.error("Property {} is invalid. Status is {}", input, validateAndUpdateProperty);
+ return Either.right(validateAndUpdateProperty);
+ }
+
+ Either<InputsData, TitanOperationStatus> addPropertyToGraph = addInputToGraph(input.getName(), input, resourceId, nodeType);
+
+ if (addPropertyToGraph.isRight()) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(addPropertyToGraph.right().value()));
+ }
+ InputDefinition createdInputyDefinition = convertInputDataToInputDefinition(addPropertyToGraph.left().value());
+ createdInputyDefinition.setName(input.getName());
+ createdInputyDefinition.setParentUniqueId(resourceId);
+
+ TitanOperationStatus status = associatePropertyToInput(compInstId, createdInputyDefinition.getUniqueId(), prop, null);
+ if (status != TitanOperationStatus.OK) {
+ log.debug("Failed to associate input {} tp property value{} ", createdInputyDefinition.getName(), prop.getValueUniqueUid());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+
+ return Either.left(createdInputyDefinition);
+
+ }
+
+ private JSONObject createJSONValueForProperty (int i, String [] parsedPropNames, JSONObject ooj, String inputName){
+
+ while(i >= 1){
+ if( i == parsedPropNames.length -1){
+ JSONObject jobProp = new JSONObject();
+ jobProp.put(GET_INPUT, inputName);
+ ooj.put(parsedPropNames[i], jobProp);
+ i--;
+ return createJSONValueForProperty (i, parsedPropNames, ooj, inputName);
+ }else{
+ JSONObject res = new JSONObject();
+ res.put(parsedPropNames[i], ooj);
+ i --;
+ res = createJSONValueForProperty (i, parsedPropNames, res, inputName);
+ return res;
+ }
+ }
+
+ return ooj;
+ }
+
+ public void resetInputName(Map<String, Object> lhm1, String inputName){
+ for (Map.Entry<String, Object> entry : lhm1.entrySet()) {
+ String key = entry.getKey();
+ Object value = entry.getValue();
+ if (value instanceof String && ((String) value).equalsIgnoreCase(inputName) && key.equals(GET_INPUT)) {
+ value = "";
+ lhm1.remove(key);
+ } else if (value instanceof Map) {
+ Map<String, Object> subMap = (Map<String, Object>)value;
+ resetInputName(subMap, inputName);
+ } else {
+ continue;
+ }
+
+ }
+ }
+
+ private Map<String, Object> createInputValue(Map<String, Object> lhm1, int index, String[] inputNames, String inputName){
+ while(index < inputNames.length){
+ if(lhm1.containsKey(inputNames[index])){
+ Object value = lhm1.get(inputNames[index]);
+ if (value instanceof Map){
+ if(index == inputNames.length -1){
+ ((Map) value).put(GET_INPUT, inputName);
+ return ((Map) value);
+
+ }else{
+ index++;
+ return createInputValue((Map)value, index, inputNames, inputName);
+ }
+ }else{
+ Map<String, Object> jobProp = new HashMap<>();
+ if(index == inputNames.length -1){
+ jobProp.put(GET_INPUT, inputName);
+ lhm1.put(inputNames[index], jobProp);
+ return lhm1;
+ }else{
+ lhm1.put(inputNames[index], jobProp);
+ index++;
+ return createInputValue(jobProp, index, inputNames, inputName);
+ }
+ }
+ }else{
+ Map<String, Object> jobProp = new HashMap<>();
+ lhm1.put(inputNames[index], jobProp);
+ if(index == inputNames.length -1){
+ jobProp.put(GET_INPUT, inputName);
+ return jobProp;
+ }else{
+ index++;
+ return createInputValue(jobProp, index, inputNames, inputName);
+ }
+ }
+ }
+ return lhm1;
+ }
+
+
+
+
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/InterfaceLifecycleOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/InterfaceLifecycleOperation.java
index 0d29c18a95..a7c883b14e 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/InterfaceLifecycleOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/InterfaceLifecycleOperation.java
@@ -27,12 +27,7 @@ import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
-import com.thinkaurelius.titan.core.TitanTransaction;
-import com.thinkaurelius.titan.core.TitanVertex;
-
-import org.apache.cassandra.transport.Event.StatusChange;
import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation;
@@ -56,6 +51,8 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
+import com.thinkaurelius.titan.core.TitanVertex;
+
import fj.data.Either;
@Component("interface-operation")
@@ -74,45 +71,40 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
private TitanGenericDao titanGenericDao;
@Override
- public Either<InterfaceDefinition, StorageOperationStatus> addInterfaceToResource(InterfaceDefinition interf,
- String resourceId, String interfaceName) {
+ public Either<InterfaceDefinition, StorageOperationStatus> addInterfaceToResource(InterfaceDefinition interf, String resourceId, String interfaceName) {
return addInterfaceToResource(interf, resourceId, interfaceName, false);
}
@Override
- public Either<InterfaceDefinition, StorageOperationStatus> addInterfaceToResource(InterfaceDefinition interf,
- String resourceId, String interfaceName, boolean inTransaction) {
+ public Either<InterfaceDefinition, StorageOperationStatus> addInterfaceToResource(InterfaceDefinition interf, String resourceId, String interfaceName, boolean inTransaction) {
return createInterfaceOnResource(interf, resourceId, interfaceName, true, inTransaction);
}
- private Either<OperationData, TitanOperationStatus> addOperationToGraph(InterfaceDefinition interf, String opName,
- Operation op, InterfaceData interfaceData) {
+ private Either<OperationData, TitanOperationStatus> addOperationToGraph(InterfaceDefinition interf, String opName, Operation op, InterfaceData interfaceData) {
op.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId((String) interfaceData.getUniqueId(), opName));
OperationData operationData = new OperationData(op);
log.debug("Before adding operation to graph {}", operationData);
- Either<OperationData, TitanOperationStatus> createOpNodeResult = titanGenericDao.createNode(operationData,
- OperationData.class);
+ Either<OperationData, TitanOperationStatus> createOpNodeResult = titanGenericDao.createNode(operationData, OperationData.class);
log.debug("After adding operation to graph {}", operationData);
if (createOpNodeResult.isRight()) {
TitanOperationStatus opStatus = createOpNodeResult.right().value();
- log.error("Failed to add operation {} to graph. Status is {}", opName, opStatus);
+ log.error("Failed to add operation {} to graph. status is {}", opName, opStatus);
return Either.right(opStatus);
}
Map<String, Object> props = new HashMap<String, Object>();
props.put(GraphPropertiesDictionary.NAME.getProperty(), opName);
- Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(interfaceData,
- operationData, GraphEdgeLabels.INTERFACE_OPERATION, props);
+ Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(interfaceData, operationData, GraphEdgeLabels.INTERFACE_OPERATION, props);
if (createRelResult.isRight()) {
TitanOperationStatus operationStatus = createOpNodeResult.right().value();
- log.error("Failed to associate operation {} to property {} in graph. Status is {}", interfaceData.getUniqueId(), opName, operationStatus);
+ log.error("Failed to associate operation {} to property {} in graph. status is {}", interfaceData.getUniqueId(), opName, operationStatus);
return Either.right(operationStatus);
}
@@ -121,11 +113,9 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
}
- private Either<TitanVertex, TitanOperationStatus> addOperationToGraph(InterfaceDefinition interf, String opName,
- Operation op, TitanVertex interfaceVertex) {
+ private Either<TitanVertex, TitanOperationStatus> addOperationToGraph(InterfaceDefinition interf, String opName, Operation op, TitanVertex interfaceVertex) {
- String interfaceId = (String) titanGenericDao.getProperty(interfaceVertex,
- GraphPropertiesDictionary.UNIQUE_ID.getProperty());
+ String interfaceId = (String) titanGenericDao.getProperty(interfaceVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty());
op.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(interfaceId, opName));
OperationData operationData = new OperationData(op);
@@ -141,12 +131,10 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
Map<String, Object> props = new HashMap<String, Object>();
props.put(GraphPropertiesDictionary.NAME.getProperty(), opName);
TitanVertex operationVertex = createOpNodeResult.left().value();
- TitanOperationStatus createRelResult = titanGenericDao.createEdge(interfaceVertex, operationVertex,
- GraphEdgeLabels.INTERFACE_OPERATION, props);
+ TitanOperationStatus createRelResult = titanGenericDao.createEdge(interfaceVertex, operationVertex, GraphEdgeLabels.INTERFACE_OPERATION, props);
if (!createRelResult.equals(TitanOperationStatus.OK)) {
- log.error("Failed to associate operation {} to property {} in graph. status is {}", interfaceId, opName,
- createRelResult);
+ log.error("Failed to associate operation {} to property {} in graph. status is {}", interfaceId, opName, createRelResult);
return Either.right(createRelResult);
}
@@ -173,8 +161,7 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
}
- private Either<InterfaceData, TitanOperationStatus> addInterfaceToGraph(InterfaceDefinition interfaceInfo,
- String interfaceName, String resourceId) {
+ private Either<InterfaceData, TitanOperationStatus> addInterfaceToGraph(InterfaceDefinition interfaceInfo, String interfaceName, String resourceId) {
InterfaceData interfaceData = new InterfaceData(interfaceInfo);
@@ -185,8 +172,7 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
interfaceInfo.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(resourceId, interfaceNameSplitted));
- Either<InterfaceData, TitanOperationStatus> existInterface = titanGenericDao
- .getNode(interfaceData.getUniqueIdKey(), interfaceData.getUniqueId(), InterfaceData.class);
+ Either<InterfaceData, TitanOperationStatus> existInterface = titanGenericDao.getNode(interfaceData.getUniqueIdKey(), interfaceData.getUniqueId(), InterfaceData.class);
if (existInterface.isRight()) {
@@ -197,8 +183,7 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
}
}
- private Either<TitanVertex, TitanOperationStatus> addInterfaceToGraph(InterfaceDefinition interfaceInfo,
- String interfaceName, String resourceId, TitanVertex metadataVertex) {
+ private Either<TitanVertex, TitanOperationStatus> addInterfaceToGraph(InterfaceDefinition interfaceInfo, String interfaceName, String resourceId, TitanVertex metadataVertex) {
InterfaceData interfaceData = new InterfaceData(interfaceInfo);
@@ -206,8 +191,7 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
interfaceInfo.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(resourceId, interfaceNameSplitted));
- Either<TitanVertex, TitanOperationStatus> existInterface = titanGenericDao
- .getVertexByProperty(interfaceData.getUniqueIdKey(), interfaceData.getUniqueId());
+ Either<TitanVertex, TitanOperationStatus> existInterface = titanGenericDao.getVertexByProperty(interfaceData.getUniqueIdKey(), interfaceData.getUniqueId());
if (existInterface.isRight()) {
@@ -218,26 +202,23 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
}
}
- private Either<InterfaceData, TitanOperationStatus> createInterfaceNodeAndRelation(String interfaceName,
- String resourceId, InterfaceData interfaceData, ResourceMetadataData resourceData) {
+ private Either<InterfaceData, TitanOperationStatus> createInterfaceNodeAndRelation(String interfaceName, String resourceId, InterfaceData interfaceData, ResourceMetadataData resourceData) {
log.debug("Before adding interface to graph {}", interfaceData);
- Either<InterfaceData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(interfaceData,
- InterfaceData.class);
+ Either<InterfaceData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(interfaceData, InterfaceData.class);
log.debug("After adding property to graph {}", interfaceData);
if (createNodeResult.isRight()) {
TitanOperationStatus operationStatus = createNodeResult.right().value();
- log.error("Failed to add interface {} to graph. Status is {}", interfaceName, operationStatus);
+ log.error("Failed to add interface {} to graph. status is {}", interfaceName, operationStatus);
return Either.right(operationStatus);
}
Map<String, Object> props = new HashMap<String, Object>();
props.put(GraphPropertiesDictionary.NAME.getProperty(), interfaceName);
- Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(resourceData,
- interfaceData, GraphEdgeLabels.INTERFACE, props);
+ Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(resourceData, interfaceData, GraphEdgeLabels.INTERFACE, props);
if (createRelResult.isRight()) {
TitanOperationStatus operationStatus = createNodeResult.right().value();
- log.error("Failed to associate resource {} to property {} in graph. Status is {}", resourceId, interfaceName, operationStatus);
+ log.error("Failed to associate resource {} to property {} in graph. status is {}", resourceId, interfaceName, operationStatus);
return Either.right(operationStatus);
}
@@ -245,8 +226,7 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
return Either.left(createNodeResult.left().value());
}
- private Either<TitanVertex, TitanOperationStatus> createInterfaceNodeAndRelation(String interfaceName,
- String resourceId, InterfaceData interfaceData, TitanVertex metadataVertex) {
+ private Either<TitanVertex, TitanOperationStatus> createInterfaceNodeAndRelation(String interfaceName, String resourceId, InterfaceData interfaceData, TitanVertex metadataVertex) {
log.debug("Before adding interface to graph {}", interfaceData);
Either<TitanVertex, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(interfaceData);
@@ -259,35 +239,30 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
Map<String, Object> props = new HashMap<String, Object>();
props.put(GraphPropertiesDictionary.NAME.getProperty(), interfaceName);
TitanVertex interfaceVertex = createNodeResult.left().value();
- TitanOperationStatus createRelResult = titanGenericDao.createEdge(metadataVertex, interfaceVertex,
- GraphEdgeLabels.INTERFACE, props);
+ TitanOperationStatus createRelResult = titanGenericDao.createEdge(metadataVertex, interfaceVertex, GraphEdgeLabels.INTERFACE, props);
if (!createRelResult.equals(TitanOperationStatus.OK)) {
- log.error("Failed to associate resource {} to property {} in graph. status is {}", resourceId,
- interfaceName, createRelResult);
+ log.error("Failed to associate resource {} to property {} in graph. status is {}", resourceId, interfaceName, createRelResult);
}
return Either.left(interfaceVertex);
}
- private Either<OperationData, TitanOperationStatus> createOperationNodeAndRelation(String operationName,
- OperationData operationData, InterfaceData interfaceData) {
+ private Either<OperationData, TitanOperationStatus> createOperationNodeAndRelation(String operationName, OperationData operationData, InterfaceData interfaceData) {
log.debug("Before adding operation to graph {}", operationData);
- Either<OperationData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(operationData,
- OperationData.class);
+ Either<OperationData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(operationData, OperationData.class);
log.debug("After adding operation to graph {}", interfaceData);
if (createNodeResult.isRight()) {
TitanOperationStatus operationStatus = createNodeResult.right().value();
- log.error("Failed to add interfoperationce {} to graph. Status is {}", operationName, operationStatus);
+ log.error("Failed to add interfoperationce {} to graph. status is {}", operationName, operationStatus);
return Either.right(operationStatus);
}
Map<String, Object> props = new HashMap<String, Object>();
props.put(GraphPropertiesDictionary.NAME.getProperty(), operationName);
- Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(interfaceData,
- operationData, GraphEdgeLabels.INTERFACE_OPERATION, props);
+ Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(interfaceData, operationData, GraphEdgeLabels.INTERFACE_OPERATION, props);
if (createRelResult.isRight()) {
TitanOperationStatus operationStatus = createNodeResult.right().value();
- log.error("Failed to associate operation {} to interface {} in graph. Status is {}", operationName, interfaceData.getUniqueId(), operationStatus);
+ log.error("Failed to associate operation {} to interface {} in graph. status is {}", operationName, interfaceData.getUniqueId(), operationStatus);
return Either.right(operationStatus);
}
@@ -307,7 +282,8 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
// * InterfaceData propertyData = getResult.left().value(); return
// * Either.left(convertPropertyDataToPropertyDefinition(propertyData)); }
// * else { TitanOperationStatus titanStatus = getResult.right().value();
- // * log.debug("Node with id {} was not found in the graph. Status: {}", propertyId, titanStatus);
+ // * log.debug("Node with id " + propertyId +
+ // * " was not found in the graph. status: " + titanStatus);
// * StorageOperationStatus storageOperationStatus =
// * DaoStatusConverter.convertTitanStatusToStorageStatus(titanStatus);
// * return Either.right(storageOperationStatus); }
@@ -323,14 +299,12 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
// }
@Override
- public Either<Map<String, InterfaceDefinition>, StorageOperationStatus> getAllInterfacesOfResource(
- String resourceIdn, boolean recursively) {
+ public Either<Map<String, InterfaceDefinition>, StorageOperationStatus> getAllInterfacesOfResource(String resourceIdn, boolean recursively) {
return getAllInterfacesOfResource(resourceIdn, recursively, false);
}
@Override
- public Either<Map<String, InterfaceDefinition>, StorageOperationStatus> getAllInterfacesOfResource(
- String resourceId, boolean recursively, boolean inTransaction) {
+ public Either<Map<String, InterfaceDefinition>, StorageOperationStatus> getAllInterfacesOfResource(String resourceId, boolean recursively, boolean inTransaction) {
Either<Map<String, InterfaceDefinition>, StorageOperationStatus> result = null;
Map<String, InterfaceDefinition> interfaces = new HashMap<String, InterfaceDefinition>();
@@ -348,7 +322,7 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
findInterfacesRes = findAllInterfacesNotRecursively(resourceId, interfaces);
}
if (!findInterfacesRes.equals(TitanOperationStatus.OK)) {
- log.error("Failed to get all interfaces of resource {}. Status is {}", resourceId, findInterfacesRes);
+ log.error("Failed to get all interfaces of resource {}. status is {}", resourceId, findInterfacesRes);
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(findInterfacesRes));
return result;
}
@@ -367,12 +341,10 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
}
}
- private TitanOperationStatus findAllInterfacesNotRecursively(String resourceId,
- Map<String, InterfaceDefinition> interfaces) {
+ private TitanOperationStatus findAllInterfacesNotRecursively(String resourceId, Map<String, InterfaceDefinition> interfaces) {
- Either<List<ImmutablePair<InterfaceData, GraphEdge>>, TitanOperationStatus> interfaceNodes = titanGenericDao
- .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId,
- GraphEdgeLabels.INTERFACE, NodeTypeEnum.Interface, InterfaceData.class);
+ Either<List<ImmutablePair<InterfaceData, GraphEdge>>, TitanOperationStatus> interfaceNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId, GraphEdgeLabels.INTERFACE,
+ NodeTypeEnum.Interface, InterfaceData.class);
if (interfaceNodes.isRight()) {
TitanOperationStatus status = interfaceNodes.right().value();
@@ -384,15 +356,13 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
if (interfaceList != null) {
for (ImmutablePair<InterfaceData, GraphEdge> interfacePair : interfaceList) {
String interfaceUniqueId = (String) interfacePair.getKey().getUniqueId();
- Either<String, TitanOperationStatus> interfaceNameRes = getPropertyValueFromEdge(
- interfacePair.getValue(), GraphPropertiesDictionary.NAME);
+ Either<String, TitanOperationStatus> interfaceNameRes = getPropertyValueFromEdge(interfacePair.getValue(), GraphPropertiesDictionary.NAME);
if (interfaceNameRes.isRight()) {
log.error("The requirement name is missing on the edge of requirement {}", interfaceUniqueId);
return interfaceNameRes.right().value();
}
String interfaceName = interfaceNameRes.left().value();
- Either<InterfaceDefinition, TitanOperationStatus> interfaceDefRes = getNonRecursiveInterface(
- interfacePair.getKey());
+ Either<InterfaceDefinition, TitanOperationStatus> interfaceDefRes = getNonRecursiveInterface(interfacePair.getKey());
if (interfaceDefRes.isRight()) {
TitanOperationStatus status = interfaceDefRes.right().value();
log.error("Failed to get interface actions of interface {}", interfaceUniqueId);
@@ -401,7 +371,7 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
InterfaceDefinition interfaceDefinition = interfaceDefRes.left().value();
if (true == interfaces.containsKey(interfaceName)) {
- log.debug("The interface {} was already defined in derived resource. add not overriden operations", interfaceName);
+ log.debug("The interface {} was already defined in dervied resource. add not overriden operations", interfaceName);
InterfaceDefinition existInterface = interfaces.get(interfaceName);
addMissingOperationsToInterface(interfaceDefinition, existInterface);
} else {
@@ -414,17 +384,15 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
return TitanOperationStatus.OK;
}
- public TitanOperationStatus findAllInterfacesRecursively(String resourceId,
- Map<String, InterfaceDefinition> interfaces) {
+ public TitanOperationStatus findAllInterfacesRecursively(String resourceId, Map<String, InterfaceDefinition> interfaces) {
TitanOperationStatus findAllInterfacesNotRecursively = findAllInterfacesNotRecursively(resourceId, interfaces);
if (!findAllInterfacesNotRecursively.equals(TitanOperationStatus.OK)) {
- log.error("failed to get interfaces for resource {}. Status is {}", resourceId, findAllInterfacesNotRecursively);
+ log.error("failed to get interfaces for resource {}. status is {}", resourceId, findAllInterfacesNotRecursively);
}
- Either<ImmutablePair<ResourceMetadataData, GraphEdge>, TitanOperationStatus> parentNodes = titanGenericDao
- .getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId,
- GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.Resource, ResourceMetadataData.class);
+ Either<ImmutablePair<ResourceMetadataData, GraphEdge>, TitanOperationStatus> parentNodes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.Resource,
+ ResourceMetadataData.class);
if (parentNodes.isRight()) {
TitanOperationStatus parentNodesStatus = parentNodes.right().value();
@@ -432,7 +400,7 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
log.debug("Finish to lookup for parnet interfaces");
return TitanOperationStatus.OK;
} else {
- log.error("Failed to find parent interfaces of resource {}. Status is {}", resourceId, parentNodesStatus);
+ log.error("Failed to find parent interfaces of resource {}. status is {}", resourceId, parentNodesStatus);
return parentNodesStatus;
}
}
@@ -448,8 +416,7 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
return TitanOperationStatus.OK;
}
- private Either<String, TitanOperationStatus> getPropertyValueFromEdge(GraphEdge edge,
- GraphPropertiesDictionary property) {
+ private Either<String, TitanOperationStatus> getPropertyValueFromEdge(GraphEdge edge, GraphPropertiesDictionary property) {
Map<String, Object> edgeProps = edge.getProperties();
String interfaceName = null;
if (edgeProps != null) {
@@ -469,9 +436,8 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
InterfaceDefinition interfaceDefinition = new InterfaceDefinition(interfaceData.getInterfaceDataDefinition());
String interfaceId = interfaceData.getUniqueId();
- Either<List<ImmutablePair<OperationData, GraphEdge>>, TitanOperationStatus> operationsRes = titanGenericDao
- .getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), interfaceId,
- GraphEdgeLabels.INTERFACE_OPERATION, NodeTypeEnum.InterfaceOperation, OperationData.class);
+ Either<List<ImmutablePair<OperationData, GraphEdge>>, TitanOperationStatus> operationsRes = titanGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), interfaceId, GraphEdgeLabels.INTERFACE_OPERATION,
+ NodeTypeEnum.InterfaceOperation, OperationData.class);
if (operationsRes.isRight()) {
TitanOperationStatus status = operationsRes.right().value();
@@ -486,8 +452,7 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
if (operationList != null && !operationList.isEmpty()) {
for (ImmutablePair<OperationData, GraphEdge> operationPair : operationList) {
Operation operation = new Operation(operationPair.getKey().getOperationDataDefinition());
- Either<String, TitanOperationStatus> operationNameRes = getPropertyValueFromEdge(
- operationPair.getValue(), GraphPropertiesDictionary.NAME);
+ Either<String, TitanOperationStatus> operationNameRes = getPropertyValueFromEdge(operationPair.getValue(), GraphPropertiesDictionary.NAME);
if (operationNameRes.isRight()) {
log.error("The operation name is missing on the edge of operation {}", operationPair.getKey().getUniqueId());
return Either.right(operationNameRes.right().value());
@@ -504,11 +469,9 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
private StorageOperationStatus findOperationImplementation(Operation operation) {
String operationId = operation.getUniqueId();
- Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsRes = artifactOperation
- .getArtifacts(operationId, NodeTypeEnum.InterfaceOperation, true);
+ Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsRes = artifactOperation.getArtifacts(operationId, NodeTypeEnum.InterfaceOperation, true);
if (artifactsRes.isRight() || artifactsRes.left().value() == null) {
- log.error("failed to get artifact from graph for operation id {}. status is {}", operationId,
- artifactsRes.right().value());
+ log.error("failed to get artifact from graph for operation id {}. status is {}", operationId, artifactsRes.right().value());
return artifactsRes.right().value();
} else {
Map<String, ArtifactDefinition> artifacts = artifactsRes.left().value();
@@ -521,10 +484,9 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
return StorageOperationStatus.OK;
}
- private StorageOperationStatus addMissingOperationsToInterface(InterfaceDefinition interfaceDefinition,
- InterfaceDefinition existInterface) {
- Map<String, Operation> existOperations = existInterface.getOperations();
- Map<String, Operation> operations = interfaceDefinition.getOperations();
+ private StorageOperationStatus addMissingOperationsToInterface(InterfaceDefinition interfaceDefinition, InterfaceDefinition existInterface) {
+ Map<String, Operation> existOperations = existInterface.getOperationsMap();
+ Map<String, Operation> operations = interfaceDefinition.getOperationsMap();
if (operations != null && !operations.isEmpty()) {
Set<Entry<String, Operation>> operationsSet = operations.entrySet();
for (Entry<String, Operation> operation : operationsSet) {
@@ -537,29 +499,22 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
}
@Override
- public Either<Operation, StorageOperationStatus> updateInterfaceOperation(String resourceId, String interfaceName,
- String operationName, Operation interf) {
+ public Either<Operation, StorageOperationStatus> updateInterfaceOperation(String resourceId, String interfaceName, String operationName, Operation interf) {
return updateInterfaceOperation(resourceId, interfaceName, operationName, interf, false);
}
@Override
- public Either<Operation, StorageOperationStatus> updateInterfaceOperation(String resourceId, String interfaceName,
- String operationName, Operation operation, boolean inTransaction) {
- Either<Operation, StorageOperationStatus> status = updateOperationOnGraph(operation, resourceId, interfaceName,
- operationName);
+ public Either<Operation, StorageOperationStatus> updateInterfaceOperation(String resourceId, String interfaceName, String operationName, Operation operation, boolean inTransaction) {
+ Either<Operation, StorageOperationStatus> status = updateOperationOnGraph(operation, resourceId, interfaceName, operationName);
/*
- * if (status.isRight()) { if (false == inTransaction) {
- * titanGenericDao.rollback(); } log.error("Failed to update operation "
- * + operationName + " of interfaceName " + interfaceName +
- * " of resource" + resourceId); return Either.right(DaoStatusConverter
- * .convertTitanStatusToStorageStatus(status.right().value())); } else {
- * if (false == inTransaction) { titanGenericDao.commit(); }
- * OperationData operationData = status.left().value();
+ * if (status.isRight()) { if (false == inTransaction) { titanGenericDao.rollback(); }
+ * log.error("Failed to update operation {} of interfaceName {} of resource {}", operationName, interfaceName, resourceId);
+ * return
+ * Either.right(DaoStatusConverter .convertTitanStatusToStorageStatus(status.right().value())); } else { if (false == inTransaction) { titanGenericDao.commit(); } OperationData operationData = status.left().value();
*
- * Operation operationDefResult =
- * convertOperationDataToOperation(operationData);
+ * Operation operationDefResult = convertOperationDataToOperation(operationData);
*
*
* log.debug("The returned OperationDefintion is {}", operationDefResult); return Either.left(operationDefResult); }
@@ -567,26 +522,16 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
return status;
}
- private Either<Operation, StorageOperationStatus> updateOperationOnGraph(Operation operation, String resourceId,
- String interfaceName, String operationName) {
+ private Either<Operation, StorageOperationStatus> updateOperationOnGraph(Operation operation, String resourceId, String interfaceName, String operationName) {
- Either<List<ImmutablePair<InterfaceData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao
- .getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), resourceId,
- GraphEdgeLabels.INTERFACE, NodeTypeEnum.Interface, InterfaceData.class);
+ Either<List<ImmutablePair<InterfaceData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), resourceId, GraphEdgeLabels.INTERFACE, NodeTypeEnum.Interface,
+ InterfaceData.class);
if (childrenNodes.isRight()) {
/*
- * InterfaceDefinition intDef = new InterfaceDefinition();
- * intDef.setType(interfaceName); Map<String, Operation> opMap = new
- * HashMap<String, Operation>(); opMap.put(operationName,
- * operation); intDef.setOperations(opMap);
- * Either<InterfaceDefinition, StorageOperationStatus> statusRes =
- * this .createInterfaceOnResource(intDef, resourceId,
- * interfaceName, true); if (statusRes.isRight()) return
- * Either.right(statusRes.right().value()); else {
- * InterfaceDefinition newDef = statusRes.left().value(); Operation
- * res = newDef.getOperations().get(operationName); return
- * Either.left(res); }
+ * InterfaceDefinition intDef = new InterfaceDefinition(); intDef.setType(interfaceName); Map<String, Operation> opMap = new HashMap<String, Operation>(); opMap.put(operationName, operation); intDef.setOperations(opMap);
+ * Either<InterfaceDefinition, StorageOperationStatus> statusRes = this .createInterfaceOnResource(intDef, resourceId, interfaceName, true); if (statusRes.isRight()) return Either.right(statusRes.right().value()); else {
+ * InterfaceDefinition newDef = statusRes.left().value(); Operation res = newDef.getOperations().get(operationName); return Either.left(res); }
*/
return updateOperationFromParentNode(operation, resourceId, interfaceName, operationName);
@@ -597,8 +542,7 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
}
- private Either<Operation, StorageOperationStatus> updateExistingOperation(String resourceId, Operation operation,
- String interfaceName, String operationName,
+ private Either<Operation, StorageOperationStatus> updateExistingOperation(String resourceId, Operation operation, String interfaceName, String operationName,
Either<List<ImmutablePair<InterfaceData, GraphEdge>>, TitanOperationStatus> childrenNodes) {
Operation newOperation = null;
StorageOperationStatus storageOperationStatus = StorageOperationStatus.GENERAL_ERROR;
@@ -610,14 +554,11 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
InterfaceData interfaceData = interfaceDataNode.getKey();
if (interfaceEdgeProp.get(GraphPropertiesDictionary.NAME.getProperty()).equals(interfaceName)) {
- Either<List<ImmutablePair<OperationData, GraphEdge>>, TitanOperationStatus> operationRes = titanGenericDao
- .getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(),
- (String) interfaceDataNode.getLeft().getUniqueId(), GraphEdgeLabels.INTERFACE_OPERATION,
- NodeTypeEnum.InterfaceOperation, OperationData.class);
+ Either<List<ImmutablePair<OperationData, GraphEdge>>, TitanOperationStatus> operationRes = titanGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), (String) interfaceDataNode.getLeft().getUniqueId(),
+ GraphEdgeLabels.INTERFACE_OPERATION, NodeTypeEnum.InterfaceOperation, OperationData.class);
if (operationRes.isRight()) {
- log.error("Failed to find operation {} on interface {}", operationName, interfaceName);
- return Either
- .right(DaoStatusConverter.convertTitanStatusToStorageStatus(operationRes.right().value()));
+ log.error("Failed to find operation {} on interface {}", operationName, interfaceName);
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(operationRes.right().value()));
} else {
List<ImmutablePair<OperationData, GraphEdge>> operations = operationRes.left().value();
for (ImmutablePair<OperationData, GraphEdge> operationPairEdge : operations) {
@@ -625,25 +566,18 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
OperationData opData = operationPairEdge.getLeft();
Map<String, Object> opEdgeProp = opEdge.getProperties();
if (opEdgeProp.get(GraphPropertiesDictionary.NAME.getProperty()).equals(operationName)) {
- ArtifactDefinition artifact = operation.getImplementation();
- Either<ImmutablePair<ArtifactData, GraphEdge>, TitanOperationStatus> artifactRes = titanGenericDao
- .getChild(GraphPropertiesDictionary.UNIQUE_ID.getProperty(),
- (String) opData.getUniqueId(), GraphEdgeLabels.ARTIFACT_REF,
- NodeTypeEnum.ArtifactRef, ArtifactData.class);
+ ArtifactDefinition artifact = operation.getImplementationArtifact();
+ Either<ImmutablePair<ArtifactData, GraphEdge>, TitanOperationStatus> artifactRes = titanGenericDao.getChild(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), (String) opData.getUniqueId(), GraphEdgeLabels.ARTIFACT_REF,
+ NodeTypeEnum.ArtifactRef, ArtifactData.class);
Either<ArtifactDefinition, StorageOperationStatus> artStatus;
if (artifactRes.isRight()) {
- artStatus = artifactOperation.addArifactToComponent(artifact,
- (String) operationPairEdge.getLeft().getUniqueId(),
- NodeTypeEnum.InterfaceOperation, true, true);
+ artStatus = artifactOperation.addArifactToComponent(artifact, (String) operationPairEdge.getLeft().getUniqueId(), NodeTypeEnum.InterfaceOperation, true, true);
} else {
- artStatus = artifactOperation.updateArifactOnResource(artifact,
- (String) operationPairEdge.getLeft().getUniqueId(),
- (String) artifactRes.left().value().getLeft().getUniqueId(),
- NodeTypeEnum.InterfaceOperation, true);
+ artStatus = artifactOperation.updateArifactOnResource(artifact, (String) operationPairEdge.getLeft().getUniqueId(), (String) artifactRes.left().value().getLeft().getUniqueId(), NodeTypeEnum.InterfaceOperation, true);
}
if (artStatus.isRight()) {
titanGenericDao.rollback();
- log.error("Failed to add artifact {}", operationName, interfaceName);
+ log.error("Failed to add artifact {} to interface {}", operationName, interfaceName);
return Either.right(artStatus.right().value());
} else {
newOperation = this.convertOperationDataToOperation(opData);
@@ -655,23 +589,18 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
}
if (newOperation == null) {
- Either<InterfaceData, TitanOperationStatus> parentInterfaceStatus = findInterfaceOnParentNode(
- resourceId, interfaceName);
+ Either<InterfaceData, TitanOperationStatus> parentInterfaceStatus = findInterfaceOnParentNode(resourceId, interfaceName);
if (parentInterfaceStatus.isRight()) {
log.debug("Interface {} not exist", interfaceName);
- return Either.right(DaoStatusConverter
- .convertTitanStatusToStorageStatus(parentInterfaceStatus.right().value()));
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(parentInterfaceStatus.right().value()));
}
InterfaceData parentInterfaceData = parentInterfaceStatus.left().value();
- Either<List<ImmutablePair<OperationData, GraphEdge>>, TitanOperationStatus> opRes = titanGenericDao
- .getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(),
- (String) parentInterfaceData.getUniqueId(), GraphEdgeLabels.INTERFACE_OPERATION,
- NodeTypeEnum.InterfaceOperation, OperationData.class);
+ Either<List<ImmutablePair<OperationData, GraphEdge>>, TitanOperationStatus> opRes = titanGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), (String) parentInterfaceData.getUniqueId(),
+ GraphEdgeLabels.INTERFACE_OPERATION, NodeTypeEnum.InterfaceOperation, OperationData.class);
if (opRes.isRight()) {
- log.error("Failed to find operation {} on interface", operationName, interfaceName);
- return Either.right(
- DaoStatusConverter.convertTitanStatusToStorageStatus(operationRes.right().value()));
+ log.error("Failed to find operation {} on interface {}", operationName, interfaceName);
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(operationRes.right().value()));
} else {
List<ImmutablePair<OperationData, GraphEdge>> parentOperations = opRes.left().value();
@@ -679,10 +608,8 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
GraphEdge opEdge = operationPairEdge.getRight();
OperationData opData = operationPairEdge.getLeft();
Map<String, Object> opEdgeProp = opEdge.getProperties();
- if (opEdgeProp.get(GraphPropertiesDictionary.NAME.getProperty())
- .equals(operationName)) {
- return copyAndCreateNewOperation(operation, interfaceName, operationName, null,
- interfaceData, operationRes, opData);
+ if (opEdgeProp.get(GraphPropertiesDictionary.NAME.getProperty()).equals(operationName)) {
+ return copyAndCreateNewOperation(operation, interfaceName, operationName, null, interfaceData, operationRes, opData);
}
}
}
@@ -703,26 +630,20 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
return Either.left(newOperation);
}
- private Either<Operation, StorageOperationStatus> copyAndCreateNewOperation(Operation operation,
- String interfaceName, String operationName, Operation newOperation, InterfaceData interfaceData,
- Either<List<ImmutablePair<OperationData, GraphEdge>>, TitanOperationStatus> operationRes,
- OperationData opData) {
+ private Either<Operation, StorageOperationStatus> copyAndCreateNewOperation(Operation operation, String interfaceName, String operationName, Operation newOperation, InterfaceData interfaceData,
+ Either<List<ImmutablePair<OperationData, GraphEdge>>, TitanOperationStatus> operationRes, OperationData opData) {
OperationDataDefinition opDataInfo = opData.getOperationDataDefinition();
OperationDataDefinition newOperationInfo = new OperationDataDefinition(opDataInfo);
- newOperationInfo.setUniqueId(
- UniqueIdBuilder.buildPropertyUniqueId(interfaceData.getUniqueId(), operationName.toLowerCase()));
+ newOperationInfo.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(interfaceData.getUniqueId(), operationName.toLowerCase()));
OperationData newopData = new OperationData(newOperationInfo);
- Either<OperationData, TitanOperationStatus> operationStatus = createOperationNodeAndRelation(operationName,
- newopData, interfaceData);
+ Either<OperationData, TitanOperationStatus> operationStatus = createOperationNodeAndRelation(operationName, newopData, interfaceData);
if (operationStatus.isRight()) {
- log.error("Failed to create operation {} on interface {}", operationName, interfaceName);
+ log.error("Failed to create operation {} on interface {}", operationName, interfaceName);
return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(operationRes.right().value()));
}
- ArtifactDefinition artifact = operation.getImplementation();
+ ArtifactDefinition artifact = operation.getImplementationArtifact();
if (artifact != null) {
- Either<ArtifactDefinition, StorageOperationStatus> artStatus = artifactOperation.addArifactToComponent(
- artifact, (String) operationStatus.left().value().getUniqueId(), NodeTypeEnum.InterfaceOperation,
- true, true);
+ Either<ArtifactDefinition, StorageOperationStatus> artStatus = artifactOperation.addArifactToComponent(artifact, (String) operationStatus.left().value().getUniqueId(), NodeTypeEnum.InterfaceOperation, true, true);
if (artStatus.isRight()) {
titanGenericDao.rollback();
log.error("Failed to add artifact {} to interface {}", operationName, interfaceName);
@@ -735,17 +656,14 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
return Either.left(newOperation);
}
- private Either<Operation, StorageOperationStatus> updateOperationFromParentNode(Operation operation,
- String resourceId, String interfaceName, String operationName) {
+ private Either<Operation, StorageOperationStatus> updateOperationFromParentNode(Operation operation, String resourceId, String interfaceName, String operationName) {
// Operation newOperation = null;
ResourceMetadataData resourceData = new ResourceMetadataData();
resourceData.getMetadataDataDefinition().setUniqueId(resourceId);
- Either<InterfaceData, TitanOperationStatus> parentInterfaceStatus = findInterfaceOnParentNode(resourceId,
- interfaceName);
+ Either<InterfaceData, TitanOperationStatus> parentInterfaceStatus = findInterfaceOnParentNode(resourceId, interfaceName);
if (parentInterfaceStatus.isRight()) {
log.debug("Interface {} not exist", interfaceName);
- return Either
- .right(DaoStatusConverter.convertTitanStatusToStorageStatus(parentInterfaceStatus.right().value()));
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(parentInterfaceStatus.right().value()));
}
InterfaceData interfaceData = parentInterfaceStatus.left().value();
@@ -756,28 +674,24 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
newInterfaceInfo.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(resourceId, interfaceNameSplitted));
InterfaceData updatedInterfaceData = new InterfaceData(newInterfaceInfo);
- Either<InterfaceData, TitanOperationStatus> createStatus = createInterfaceNodeAndRelation(interfaceName,
- resourceId, updatedInterfaceData, resourceData);
+ Either<InterfaceData, TitanOperationStatus> createStatus = createInterfaceNodeAndRelation(interfaceName, resourceId, updatedInterfaceData, resourceData);
if (createStatus.isRight()) {
- log.debug("failed to create interface node {} on resource {}", interfaceName, resourceId);
+ log.debug("failed to create interface node {} on resource {}", interfaceName, resourceId);
return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(createStatus.right().value()));
}
InterfaceData newInterfaceNode = createStatus.left().value();
- Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(newInterfaceNode,
- interfaceData, GraphEdgeLabels.DERIVED_FROM, null);
+ Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(newInterfaceNode, interfaceData, GraphEdgeLabels.DERIVED_FROM, null);
if (createRelResult.isRight()) {
TitanOperationStatus operationStatus = createRelResult.right().value();
- log.error("Failed to associate interface {} to interface {} in graph. Status is {}", interfaceData.getUniqueId(), newInterfaceNode.getUniqueId(), operationStatus);
+ log.error("Failed to associate interface {} to interface {} in graph. status is {}", interfaceData.getUniqueId(), newInterfaceNode.getUniqueId(), operationStatus);
return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(operationStatus));
}
- Either<List<ImmutablePair<OperationData, GraphEdge>>, TitanOperationStatus> operationRes = titanGenericDao
- .getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(),
- (String) interfaceData.getUniqueId(), GraphEdgeLabels.INTERFACE_OPERATION,
- NodeTypeEnum.InterfaceOperation, OperationData.class);
+ Either<List<ImmutablePair<OperationData, GraphEdge>>, TitanOperationStatus> operationRes = titanGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), (String) interfaceData.getUniqueId(),
+ GraphEdgeLabels.INTERFACE_OPERATION, NodeTypeEnum.InterfaceOperation, OperationData.class);
if (operationRes.isRight()) {
- log.error("Failed to find operation {} on interface {}", operationName, interfaceName);
+ log.error("Failed to find operation {} on interface {}", operationName, interfaceName);
return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(operationRes.right().value()));
} else {
@@ -802,25 +716,20 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
// return Either.left(newOperation);
}
- private Either<InterfaceData, TitanOperationStatus> findInterfaceOnParentNode(String resourceId,
- String interfaceName) {
+ private Either<InterfaceData, TitanOperationStatus> findInterfaceOnParentNode(String resourceId, String interfaceName) {
- Either<ImmutablePair<ResourceMetadataData, GraphEdge>, TitanOperationStatus> parentRes = titanGenericDao
- .getChild(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), resourceId, GraphEdgeLabels.DERIVED_FROM,
- NodeTypeEnum.Resource, ResourceMetadataData.class);
+ Either<ImmutablePair<ResourceMetadataData, GraphEdge>, TitanOperationStatus> parentRes = titanGenericDao.getChild(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), resourceId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.Resource,
+ ResourceMetadataData.class);
if (parentRes.isRight()) {
- log.debug("interface {} not found", interfaceName);
+ log.debug("interface {} not found ", interfaceName);
return Either.right(parentRes.right().value());
}
ImmutablePair<ResourceMetadataData, GraphEdge> parenNode = parentRes.left().value();
- Either<List<ImmutablePair<InterfaceData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao
- .getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(),
- parenNode.getKey().getMetadataDataDefinition().getUniqueId(), GraphEdgeLabels.INTERFACE,
- NodeTypeEnum.Interface, InterfaceData.class);
+ Either<List<ImmutablePair<InterfaceData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), parenNode.getKey().getMetadataDataDefinition().getUniqueId(),
+ GraphEdgeLabels.INTERFACE, NodeTypeEnum.Interface, InterfaceData.class);
if (childrenNodes.isRight()) {
- return findInterfaceOnParentNode(parenNode.getKey().getMetadataDataDefinition().getUniqueId(),
- interfaceName);
+ return findInterfaceOnParentNode(parenNode.getKey().getMetadataDataDefinition().getUniqueId(), interfaceName);
} else {
for (ImmutablePair<InterfaceData, GraphEdge> interfaceDataNode : childrenNodes.left().value()) {
@@ -833,15 +742,13 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
}
}
- return findInterfaceOnParentNode(parenNode.getKey().getMetadataDataDefinition().getUniqueId(),
- interfaceName);
+ return findInterfaceOnParentNode(parenNode.getKey().getMetadataDataDefinition().getUniqueId(), interfaceName);
}
}
@Override
- public Either<InterfaceDefinition, StorageOperationStatus> createInterfaceOnResource(InterfaceDefinition interf,
- String resourceId, String interfaceName, boolean failIfExist, boolean inTransaction) {
+ public Either<InterfaceDefinition, StorageOperationStatus> createInterfaceOnResource(InterfaceDefinition interf, String resourceId, String interfaceName, boolean failIfExist, boolean inTransaction) {
Either<InterfaceData, TitanOperationStatus> status = addInterfaceToGraph(interf, interfaceName, resourceId);
@@ -857,15 +764,14 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
InterfaceData interfaceData = status.left().value();
InterfaceDefinition interfaceDefResult = convertInterfaceDataToInterfaceDefinition(interfaceData);
- Map<String, Operation> operations = interf.getOperations();
+ Map<String, Operation> operations = interf.getOperationsMap();
if (operations != null && !operations.isEmpty()) {
Set<String> opNames = operations.keySet();
Map<String, Operation> newOperations = new HashMap<String, Operation>();
for (String operationName : opNames) {
Operation op = operations.get(operationName);
- Either<OperationData, TitanOperationStatus> opStatus = addOperationToGraph(interf, operationName,
- op, interfaceData);
+ Either<OperationData, TitanOperationStatus> opStatus = addOperationToGraph(interf, operationName, op, interfaceData);
if (status.isRight()) {
titanGenericDao.rollback();
log.error("Failed to add operation {} to interface {}", operationName, interfaceName);
@@ -876,11 +782,9 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
OperationData opData = opStatus.left().value();
Operation newOperation = this.convertOperationDataToOperation(opData);
- ArtifactDefinition art = op.getImplementation();
+ ArtifactDefinition art = op.getImplementationArtifact();
if (art != null) {
- Either<ArtifactDefinition, StorageOperationStatus> artRes = artifactOperation
- .addArifactToComponent(art, (String) opData.getUniqueId(),
- NodeTypeEnum.InterfaceOperation, failIfExist, true);
+ Either<ArtifactDefinition, StorageOperationStatus> artRes = artifactOperation.addArifactToComponent(art, (String) opData.getUniqueId(), NodeTypeEnum.InterfaceOperation, failIfExist, true);
if (artRes.isRight()) {
titanGenericDao.rollback();
log.error("Failed to add artifact {} to interface {}", operationName, interfaceName);
@@ -891,7 +795,7 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
}
}
}
- interfaceDefResult.setOperations(newOperations);
+ interfaceDefResult.setOperationsMap(newOperations);
}
log.debug("The returned InterfaceDefintion is {}", interfaceDefResult);
return Either.left(interfaceDefResult);
@@ -900,11 +804,9 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
}
@Override
- public StorageOperationStatus createInterfaceOnResource(InterfaceDefinition interf, String resourceId,
- String interfaceName, boolean failIfExist, boolean inTransaction, TitanVertex metadataVertex) {
+ public StorageOperationStatus createInterfaceOnResource(InterfaceDefinition interf, String resourceId, String interfaceName, boolean failIfExist, boolean inTransaction, TitanVertex metadataVertex) {
- Either<TitanVertex, TitanOperationStatus> interfaceResult = addInterfaceToGraph(interf, interfaceName,
- resourceId, metadataVertex);
+ Either<TitanVertex, TitanOperationStatus> interfaceResult = addInterfaceToGraph(interf, interfaceName, resourceId, metadataVertex);
if (interfaceResult.isRight()) {
if (false == inTransaction) {
@@ -921,14 +823,13 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
// InterfaceDefinition interfaceDefResult =
// convertInterfaceDataToInterfaceDefinition(interfaceData);
- Map<String, Operation> operations = interf.getOperations();
+ Map<String, Operation> operations = interf.getOperationsMap();
if (operations != null && !operations.isEmpty()) {
Set<String> opNames = operations.keySet();
for (String operationName : opNames) {
Operation op = operations.get(operationName);
- Either<TitanVertex, TitanOperationStatus> operationResult = addOperationToGraph(interf,
- operationName, op, interfaceVertex);
+ Either<TitanVertex, TitanOperationStatus> operationResult = addOperationToGraph(interf, operationName, op, interfaceVertex);
if (operationResult.isRight()) {
if (false == inTransaction) {
titanGenericDao.rollback();
@@ -941,12 +842,10 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
}
TitanVertex operationVertex = operationResult.left().value();
- ArtifactDefinition art = op.getImplementation();
+ ArtifactDefinition art = op.getImplementationArtifact();
if (art != null) {
- String opId = (String) titanGenericDao.getProperty(operationVertex,
- GraphPropertiesDictionary.UNIQUE_ID.getProperty());
- StorageOperationStatus artRes = artifactOperation.addArifactToComponent(art, opId,
- NodeTypeEnum.InterfaceOperation, failIfExist, operationVertex);
+ String opId = (String) titanGenericDao.getProperty(operationVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty());
+ StorageOperationStatus artRes = artifactOperation.addArifactToComponent(art, opId, NodeTypeEnum.InterfaceOperation, failIfExist, operationVertex);
if (!artRes.equals(StorageOperationStatus.OK)) {
if (false == inTransaction) {
titanGenericDao.rollback();
@@ -964,14 +863,12 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
}
@Override
- public Either<Operation, StorageOperationStatus> deleteInterfaceOperation(String resourceId, String interfaceName,
- String operationId) {
+ public Either<Operation, StorageOperationStatus> deleteInterfaceOperation(String resourceId, String interfaceName, String operationId) {
return deleteInterfaceOperation(resourceId, interfaceName, operationId, false);
}
@Override
- public Either<Operation, StorageOperationStatus> deleteInterfaceOperation(String resourceId, String interfaceName,
- String operationId, boolean inTransaction) {
+ public Either<Operation, StorageOperationStatus> deleteInterfaceOperation(String resourceId, String interfaceName, String operationId, boolean inTransaction) {
Either<Operation, TitanOperationStatus> status = removeOperationOnGraph(resourceId, interfaceName, operationId);
if (status.isRight()) {
@@ -993,17 +890,15 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
}
@Override
- public Either<InterfaceDefinition, StorageOperationStatus> deleteInterfaceOfResourceOnGraph(String resourceId,
- InterfaceDefinition interfaceDef, boolean inTransaction) {
+ public Either<InterfaceDefinition, StorageOperationStatus> deleteInterfaceOfResourceOnGraph(String resourceId, InterfaceDefinition interfaceDef, boolean inTransaction) {
- Map<String, Operation> operations = interfaceDef.getOperations();
+ Map<String, Operation> operations = interfaceDef.getOperationsMap();
String interfaceNameSplitted = getShortInterfaceName(interfaceDef);
if (operations != null) {
for (Entry<String, Operation> entry : operations.entrySet()) {
Operation op = entry.getValue();
- Either<Operation, StorageOperationStatus> removeOperationFromResource = deleteInterfaceOperation(
- resourceId, interfaceNameSplitted, op.getUniqueId(), true);
+ Either<Operation, StorageOperationStatus> removeOperationFromResource = deleteInterfaceOperation(resourceId, interfaceNameSplitted, op.getUniqueId(), true);
if (removeOperationFromResource.isRight()) {
if (false == inTransaction) {
titanGenericDao.rollback();
@@ -1017,13 +912,11 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
}
- private Either<Operation, TitanOperationStatus> removeOperationOnGraph(String resourceId, String interfaceName,
- String operationId) {
+ private Either<Operation, TitanOperationStatus> removeOperationOnGraph(String resourceId, String interfaceName, String operationId) {
log.debug("Before deleting operation from graph {}", operationId);
- Either<List<ImmutablePair<InterfaceData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao
- .getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), resourceId,
- GraphEdgeLabels.INTERFACE, NodeTypeEnum.Interface, InterfaceData.class);
+ Either<List<ImmutablePair<InterfaceData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), resourceId, GraphEdgeLabels.INTERFACE, NodeTypeEnum.Interface,
+ InterfaceData.class);
if (childrenNodes.isRight()) {
log.debug("Not found interface {}", interfaceName);
@@ -1038,12 +931,10 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
String interfaceSplitedName = splitType(interfaceName);
if (interfaceEdgeProp.get(GraphPropertiesDictionary.NAME.getProperty()).equals(interfaceSplitedName)) {
- Either<List<ImmutablePair<OperationData, GraphEdge>>, TitanOperationStatus> operationRes = titanGenericDao
- .getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(),
- (String) interfaceDataNode.getLeft().getUniqueId(), GraphEdgeLabels.INTERFACE_OPERATION,
- NodeTypeEnum.InterfaceOperation, OperationData.class);
+ Either<List<ImmutablePair<OperationData, GraphEdge>>, TitanOperationStatus> operationRes = titanGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), (String) interfaceDataNode.getLeft().getUniqueId(),
+ GraphEdgeLabels.INTERFACE_OPERATION, NodeTypeEnum.InterfaceOperation, OperationData.class);
if (operationRes.isRight()) {
- log.error("Failed to find operation {}", operationId, interfaceName);
+ log.error("Failed to find operation {} on interface {}", operationId, interfaceName);
return Either.right(operationRes.right().value());
}
List<ImmutablePair<OperationData, GraphEdge>> operations = operationRes.left().value();
@@ -1053,24 +944,18 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
opData = operationPairEdge.getLeft();
if (opData.getUniqueId().equals(operationId)) {
- Either<ImmutablePair<ArtifactData, GraphEdge>, TitanOperationStatus> artifactRes = titanGenericDao
- .getChild(GraphPropertiesDictionary.UNIQUE_ID.getProperty(),
- (String) operationPairEdge.getLeft().getUniqueId(),
- GraphEdgeLabels.ARTIFACT_REF, NodeTypeEnum.ArtifactRef, ArtifactData.class);
+ Either<ImmutablePair<ArtifactData, GraphEdge>, TitanOperationStatus> artifactRes = titanGenericDao.getChild(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), (String) operationPairEdge.getLeft().getUniqueId(),
+ GraphEdgeLabels.ARTIFACT_REF, NodeTypeEnum.ArtifactRef, ArtifactData.class);
Either<ArtifactDefinition, StorageOperationStatus> arStatus = null;
if (artifactRes.isLeft()) {
ArtifactData arData = artifactRes.left().value().getKey();
- arStatus = artifactOperation.removeArifactFromResource(
- (String) operationPairEdge.getLeft().getUniqueId(), (String) arData.getUniqueId(),
- NodeTypeEnum.InterfaceOperation, true, true);
+ arStatus = artifactOperation.removeArifactFromResource((String) operationPairEdge.getLeft().getUniqueId(), (String) arData.getUniqueId(), NodeTypeEnum.InterfaceOperation, true, true);
if (arStatus.isRight()) {
log.debug("failed to delete artifact {}", arData.getUniqueId());
return Either.right(TitanOperationStatus.INVALID_ID);
}
}
- Either<OperationData, TitanOperationStatus> deleteOpStatus = titanGenericDao.deleteNode(
- UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.InterfaceOperation), opData.getUniqueId(),
- OperationData.class);
+ Either<OperationData, TitanOperationStatus> deleteOpStatus = titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.InterfaceOperation), opData.getUniqueId(), OperationData.class);
if (deleteOpStatus.isRight()) {
log.debug("failed to delete operation {}", opData.getUniqueId());
return Either.right(TitanOperationStatus.INVALID_ID);
@@ -1081,9 +966,7 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
operation.setImplementation(arStatus.left().value());
}
if (operations.size() <= 1) {
- Either<InterfaceData, TitanOperationStatus> deleteInterfaceStatus = titanGenericDao
- .deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Interface),
- interfaceDataNode.left.getUniqueId(), InterfaceData.class);
+ Either<InterfaceData, TitanOperationStatus> deleteInterfaceStatus = titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Interface), interfaceDataNode.left.getUniqueId(), InterfaceData.class);
if (deleteInterfaceStatus.isRight()) {
log.debug("failed to delete interface {}", interfaceDataNode.left.getUniqueId());
return Either.right(TitanOperationStatus.INVALID_ID);
@@ -1100,8 +983,6 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
log.debug("Not found operation {}", interfaceName);
return Either.right(TitanOperationStatus.INVALID_ID);
- // }
-
}
private String splitType(String interfaceName) {
@@ -1131,16 +1012,14 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
}
@Override
- public Either<InterfaceDefinition, StorageOperationStatus> createInterfaceType(InterfaceDefinition interf,
- boolean inTransaction) {
+ public Either<InterfaceDefinition, StorageOperationStatus> createInterfaceType(InterfaceDefinition interf, boolean inTransaction) {
Either<InterfaceDefinition, StorageOperationStatus> result = null;
try {
InterfaceData interfaceData = new InterfaceData(interf);
interf.setUniqueId(interf.getType().toLowerCase());
- Either<InterfaceData, TitanOperationStatus> existInterface = titanGenericDao
- .getNode(interfaceData.getUniqueIdKey(), interfaceData.getUniqueId(), InterfaceData.class);
+ Either<InterfaceData, TitanOperationStatus> existInterface = titanGenericDao.getNode(interfaceData.getUniqueIdKey(), interfaceData.getUniqueId(), InterfaceData.class);
if (existInterface.isLeft()) {
// already exist
@@ -1150,32 +1029,29 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
}
log.debug("Before adding interface type to graph {}", interfaceData);
- Either<InterfaceData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(interfaceData,
- InterfaceData.class);
+ Either<InterfaceData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(interfaceData, InterfaceData.class);
log.debug("After adding property type to graph {}", interfaceData);
if (createNodeResult.isRight()) {
TitanOperationStatus operationStatus = createNodeResult.right().value();
- log.error("Failed to add interface {} to graph. Status is {}", interf.getType(), operationStatus);
+ log.error("Failed to add interface {} to graph. status is {}", interf.getType(), operationStatus);
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(operationStatus));
return result;
}
InterfaceDefinition interfaceDefResult = convertInterfaceDataToInterfaceDefinition(interfaceData);
- Map<String, Operation> operations = interf.getOperations();
+ Map<String, Operation> operations = interf.getOperationsMap();
if (operations != null && !operations.isEmpty()) {
Map<String, Operation> newOperations = new HashMap<String, Operation>();
for (Map.Entry<String, Operation> operation : operations.entrySet()) {
- Either<OperationData, TitanOperationStatus> opStatus = addOperationToGraph(interf,
- operation.getKey(), operation.getValue(), interfaceData);
+ Either<OperationData, TitanOperationStatus> opStatus = addOperationToGraph(interf, operation.getKey(), operation.getValue(), interfaceData);
if (opStatus.isRight()) {
titanGenericDao.rollback();
log.error("Failed to add operation {} to interface {}", operation.getKey(), interf.getType());
- result = Either
- .right(DaoStatusConverter.convertTitanStatusToStorageStatus(opStatus.right().value()));
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(opStatus.right().value()));
return result;
} else {
OperationData opData = opStatus.left().value();
@@ -1183,7 +1059,7 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
newOperations.put(operation.getKey(), newOperation);
}
}
- interfaceDefResult.setOperations(newOperations);
+ interfaceDefResult.setOperationsMap(newOperations);
}
result = Either.left(interfaceDefResult);
return result;
@@ -1203,26 +1079,22 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
@Override
public Either<InterfaceDefinition, StorageOperationStatus> getInterface(String interfaceId) {
- Either<InterfaceData, TitanOperationStatus> getResult = titanGenericDao
- .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Interface), interfaceId, InterfaceData.class);
+ Either<InterfaceData, TitanOperationStatus> getResult = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Interface), interfaceId, InterfaceData.class);
if (getResult.isLeft()) {
InterfaceData interfaceData = getResult.left().value();
return Either.left(convertInterfaceDataToInterfaceDefinition(interfaceData));
} else {
TitanOperationStatus titanStatus = getResult.right().value();
- log.debug("Node with id {} was not found in the graph. Status: {}", interfaceId, titanStatus);
- StorageOperationStatus storageOperationStatus = DaoStatusConverter
- .convertTitanStatusToStorageStatus(titanStatus);
+ log.debug("Node with id {} was not found in the graph. status: {}", interfaceId, titanStatus);
+ StorageOperationStatus storageOperationStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(titanStatus);
return Either.right(storageOperationStatus);
}
}
@Override
- public StorageOperationStatus associateInterfaceToNode(GraphNode node, InterfaceDefinition interfaceDefinition,
- TitanVertex metadataVertex) {
+ public StorageOperationStatus associateInterfaceToNode(GraphNode node, InterfaceDefinition interfaceDefinition, TitanVertex metadataVertex) {
- Either<TitanVertex, TitanOperationStatus> interfaceData = titanGenericDao.getVertexByProperty(
- UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Interface), interfaceDefinition.getUniqueId());
+ Either<TitanVertex, TitanOperationStatus> interfaceData = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Interface), interfaceDefinition.getUniqueId());
if (interfaceData.isRight()) {
return DaoStatusConverter.convertTitanStatusToStorageStatus(interfaceData.right().value());
}
@@ -1232,8 +1104,7 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
String interfaceName = getShortInterfaceName(interfaceDefinition);
properties.put(GraphPropertiesDictionary.NAME.getProperty(), interfaceName.toLowerCase());
- TitanOperationStatus createRelation = titanGenericDao.createEdge(metadataVertex, interfaceData.left().value(),
- GraphEdgeLabels.INTERFACE, properties);
+ TitanOperationStatus createRelation = titanGenericDao.createEdge(metadataVertex, interfaceData.left().value(), GraphEdgeLabels.INTERFACE, properties);
if (!createRelation.equals(TitanOperationStatus.OK)) {
return DaoStatusConverter.convertTitanStatusToStorageStatus(createRelation);
}
@@ -1260,19 +1131,15 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
}
@Override
- public Either<Operation, StorageOperationStatus> getSpecificOperation(String resourceId, String interfaceType,
- String operationName) {
- log.trace("Getting operation, resourceId {}, interfaceType {}, operationName {}", resourceId, interfaceType,
- operationName);
- Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = getAllInterfacesOfResource(
- resourceId, false);
- if (allInterfacesOfResource.isRight() || allInterfacesOfResource.left().value() == null
- || allInterfacesOfResource.left().value().get(interfaceType) == null) {
+ public Either<Operation, StorageOperationStatus> getSpecificOperation(String resourceId, String interfaceType, String operationName) {
+ log.trace("Getting operation, resourceId {}, interfaceType {}, operationName {}", resourceId, interfaceType, operationName);
+ Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = getAllInterfacesOfResource(resourceId, false);
+ if (allInterfacesOfResource.isRight() || allInterfacesOfResource.left().value() == null || allInterfacesOfResource.left().value().get(interfaceType) == null) {
log.debug("Couldn't find interface definition of type {} for resource id {}", interfaceType, resourceId);
return Either.right(allInterfacesOfResource.right().value());
}
InterfaceDefinition interfaceDefinition = allInterfacesOfResource.left().value().get(interfaceType);
- Map<String, Operation> operations = interfaceDefinition.getOperations();
+ Map<String, Operation> operations = interfaceDefinition.getOperationsMap();
if (operations == null || operations.get(operationName) == null) {
log.debug("Couldn't find operation for operation name {}, interface type {}", operationName, interfaceType);
return Either.right(StorageOperationStatus.GENERAL_ERROR);
@@ -1281,24 +1148,19 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
}
@Override
- public Either<InterfaceDefinition, StorageOperationStatus> dissociateInterfaceFromNode(GraphNode node,
- InterfaceDefinition interfaceDefinition) {
+ public Either<InterfaceDefinition, StorageOperationStatus> dissociateInterfaceFromNode(GraphNode node, InterfaceDefinition interfaceDefinition) {
- Either<InterfaceData, TitanOperationStatus> interfaceData = titanGenericDao.getNode(
- UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Interface), interfaceDefinition.getUniqueId(),
- InterfaceData.class);
+ Either<InterfaceData, TitanOperationStatus> interfaceData = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Interface), interfaceDefinition.getUniqueId(), InterfaceData.class);
if (interfaceData.isRight()) {
log.debug("Couldn't find interface {}", interfaceDefinition);
return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(interfaceData.right().value()));
}
InterfaceData value = interfaceData.left().value();
- Either<GraphRelation, TitanOperationStatus> deleteRelation = titanGenericDao.deleteRelation(node, value,
- GraphEdgeLabels.INTERFACE);
+ Either<GraphRelation, TitanOperationStatus> deleteRelation = titanGenericDao.deleteRelation(node, value, GraphEdgeLabels.INTERFACE);
if (deleteRelation.isRight()) {
TitanOperationStatus status = deleteRelation.right().value();
- log.debug("Couldn't dissociate interface between node {} to node {}. Status is {}", node.getUniqueId(),
- value.getUniqueId(), status);
+ log.debug("Couldn't dissociate interface between node {} to node {}. Status is {}", node.getUniqueId(), value.getUniqueId(), status);
return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/LifecycleOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/LifecycleOperation.java
index 863975893c..2537891bbd 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/LifecycleOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/LifecycleOperation.java
@@ -116,15 +116,12 @@ public class LifecycleOperation implements ILifecycleOperation {
}
@Override
- public Either<User, StorageOperationStatus> getComponentOwner(String resourceId, NodeTypeEnum nodeType,
- boolean inTransaction) {
+ public Either<User, StorageOperationStatus> getComponentOwner(String resourceId, NodeTypeEnum nodeType, boolean inTransaction) {
Either<User, StorageOperationStatus> result = Either.right(StorageOperationStatus.GENERAL_ERROR);
try {
- Either<ImmutablePair<UserData, GraphEdge>, TitanOperationStatus> parentNode = titanGenericDao.getParentNode(
- UniqueIdBuilder.getKeyByNodeType(nodeType), resourceId, GraphEdgeLabels.STATE, NodeTypeEnum.User,
- UserData.class);
+ Either<ImmutablePair<UserData, GraphEdge>, TitanOperationStatus> parentNode = titanGenericDao.getParentNode(UniqueIdBuilder.getKeyByNodeType(nodeType), resourceId, GraphEdgeLabels.STATE, NodeTypeEnum.User, UserData.class);
if (parentNode.isRight()) {
return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(parentNode.right().value()));
@@ -144,8 +141,7 @@ public class LifecycleOperation implements ILifecycleOperation {
}
@Override
- public Either<? extends Component, StorageOperationStatus> checkoutComponent(NodeTypeEnum nodeType,
- Component component, User modifier, User currentOwner, boolean inTransaction) {
+ public Either<? extends Component, StorageOperationStatus> checkoutComponent(NodeTypeEnum nodeType, Component component, User modifier, User currentOwner, boolean inTransaction) {
Either<? extends Component, StorageOperationStatus> result = null;
try {
@@ -153,17 +149,14 @@ public class LifecycleOperation implements ILifecycleOperation {
if (!component.getLifecycleState().equals(LifecycleStateEnum.CERTIFIED)) {
component.setHighestVersion(false);
ComponentOperation componentOperation = getComponentOperation(nodeType);
- Either<? extends Component, StorageOperationStatus> updateComponent = componentOperation
- .updateComponent(component, inTransaction, titanGenericDao, component.getClass(), nodeType);
+ Either<? extends Component, StorageOperationStatus> updateComponent = componentOperation.updateComponent(component, inTransaction, titanGenericDao, component.getClass(), nodeType);
if (updateComponent.isRight()) {
StorageOperationStatus error = updateComponent.right().value();
- log.debug("Couldn't set lifecycle for component {} to state {}, error: {}", component.getUniqueId(),
- LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, error);
+ log.debug("Couldn't set lifecycle for component {} to state {}, error: {}", component.getUniqueId(), LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, error);
return Either.right(error);
}
- StorageOperationStatus changeStateToLastState = changeStateRelation(nodeType, component.getUniqueId(),
- currentOwner, GraphEdgeLabels.STATE, GraphEdgeLabels.LAST_STATE);
+ StorageOperationStatus changeStateToLastState = changeStateRelation(nodeType, component.getUniqueId(), currentOwner, GraphEdgeLabels.STATE, GraphEdgeLabels.LAST_STATE);
if (!changeStateToLastState.equals(StorageOperationStatus.OK)) {
result = Either.right(changeStateToLastState);
return result;
@@ -173,8 +166,7 @@ public class LifecycleOperation implements ILifecycleOperation {
// clone the component
result = cloneComponentForCheckout(component, nodeType, modifier);
if (result.isRight()) {
- log.debug("Couldn't set lifecycle for component {} to state {}, error: {}", component.getUniqueId(),
- LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, result.right().value());
+ log.debug("Couldn't set lifecycle for component {} to state {}, error: {}", component.getUniqueId(), LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, result.right().value());
return result;
}
@@ -193,8 +185,7 @@ public class LifecycleOperation implements ILifecycleOperation {
return result;
}
- private Either<? extends Component, StorageOperationStatus> cloneComponentForCertified(Component component,
- User modifier, Integer majorVersion) {
+ private Either<? extends Component, StorageOperationStatus> cloneComponentForCertified(Component component, User modifier, Integer majorVersion) {
// set new version
String certifiedVersion = (majorVersion + 1) + VERSION_DELIMETER + "0";
@@ -205,15 +196,13 @@ public class LifecycleOperation implements ILifecycleOperation {
component.setHighestVersion(true);
ComponentOperation componentOperation = getComponentOperation(component.getComponentType().getNodeType());
- Either<? extends Component, StorageOperationStatus> cloneComponentResult = componentOperation
- .cloneComponent(component, certifiedVersion, LifecycleStateEnum.CERTIFIED, true);
+ Either<? extends Component, StorageOperationStatus> cloneComponentResult = componentOperation.cloneComponent(component, certifiedVersion, LifecycleStateEnum.CERTIFIED, true);
return cloneComponentResult;
}
@Override
- public Either<? extends Component, StorageOperationStatus> undoCheckout(NodeTypeEnum nodeType, Component component,
- User modifier, User currentOwner, boolean inTransaction) {
+ public Either<? extends Component, StorageOperationStatus> undoCheckout(NodeTypeEnum nodeType, Component component, User modifier, User currentOwner, boolean inTransaction) {
Either<? extends Component, StorageOperationStatus> result = null;
ComponentOperation componentOperation = getComponentOperation(nodeType);
@@ -226,8 +215,7 @@ public class LifecycleOperation implements ILifecycleOperation {
String previousVersion = versionParts[0] + VERSION_DELIMETER + minorVersion;
if (!previousVersion.equals("0.0")) {
- Either<? extends Component, StorageOperationStatus> updateOldResourceResult = updateOldComponentBeforeUndoCheckout(
- componentOperation, prevComponent, component, previousVersion, nodeType, true);
+ Either<? extends Component, StorageOperationStatus> updateOldResourceResult = updateOldComponentBeforeUndoCheckout(componentOperation, prevComponent, component, previousVersion, nodeType, true);
if (updateOldResourceResult.isRight()) {
result = updateOldResourceResult;
return result;
@@ -236,8 +224,7 @@ public class LifecycleOperation implements ILifecycleOperation {
}
// delete the component
- Either<? extends Component, StorageOperationStatus> deleteResourceResult = componentOperation
- .deleteComponent(component.getUniqueId(), true);
+ Either<? extends Component, StorageOperationStatus> deleteResourceResult = componentOperation.deleteComponent(component.getUniqueId(), true);
if (deleteResourceResult.isRight()) {
result = deleteResourceResult;
return result;
@@ -262,23 +249,19 @@ public class LifecycleOperation implements ILifecycleOperation {
}
@Override
- public Either<? extends Component, StorageOperationStatus> checkinComponent(NodeTypeEnum nodeType,
- Component component, User modifier, User owner, boolean inTransaction) {
+ public Either<? extends Component, StorageOperationStatus> checkinComponent(NodeTypeEnum nodeType, Component component, User modifier, User owner, boolean inTransaction) {
Either<? extends Component, StorageOperationStatus> result = null;
try {
- StorageOperationStatus updateCheckinInGraph = updateCheckinInGraph(nodeType, component.getUniqueId(),
- component.getLifecycleState(), modifier, owner);
+ StorageOperationStatus updateCheckinInGraph = updateCheckinInGraph(nodeType, component.getUniqueId(), component.getLifecycleState(), modifier, owner);
if (!updateCheckinInGraph.equals(StorageOperationStatus.OK)) {
- log.error("failed to update state of resource {}. status={}", component.getUniqueId(),
- updateCheckinInGraph);
+ log.error("failed to update state of resource {}. status={}", component.getUniqueId(), updateCheckinInGraph);
return Either.right(updateCheckinInGraph);
}
LifecycleStateEnum state = LifecycleStateEnum.NOT_CERTIFIED_CHECKIN;
ComponentParametersView componentParametersView = buildFilterForFetchComponentAfterChangeState();
result = updateComponentMD(component, modifier, state, nodeType, componentParametersView);
if (result.isRight()) {
- log.debug("Couldn't set lifecycle for component {} to state {}, error: {}", component.getUniqueId(),
- state, result.right().value());
+ log.debug("Couldn't set lifecycle for component {} to state {}, error: {}", component.getUniqueId(), state, result.right().value());
}
return result;
@@ -306,8 +289,7 @@ public class LifecycleOperation implements ILifecycleOperation {
return componentParametersView;
}
- private StorageOperationStatus updateCheckinInGraph(NodeTypeEnum componentType, String componentId,
- LifecycleStateEnum state, User modifier, User owner) {
+ private StorageOperationStatus updateCheckinInGraph(NodeTypeEnum componentType, String componentId, LifecycleStateEnum state, User modifier, User owner) {
// check if we cancel rfc
if (state.equals(LifecycleStateEnum.READY_FOR_CERTIFICATION)) {
@@ -316,8 +298,7 @@ public class LifecycleOperation implements ILifecycleOperation {
Map<String, Object> props = new HashMap<String, Object>();
props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
UniqueIdData resourceData = new UniqueIdData(componentType, componentId);
- Either<GraphRelation, TitanOperationStatus> deleteResult = titanGenericDao
- .deleteIncomingRelationByCriteria(resourceData, GraphEdgeLabels.LAST_STATE, props);
+ Either<GraphRelation, TitanOperationStatus> deleteResult = titanGenericDao.deleteIncomingRelationByCriteria(resourceData, GraphEdgeLabels.LAST_STATE, props);
if (deleteResult.isRight()) {
log.debug("failed to update last state relation");
return StorageOperationStatus.INCONSISTENCY;
@@ -325,8 +306,7 @@ public class LifecycleOperation implements ILifecycleOperation {
}
// remove CHECKOUT relation
- StorageOperationStatus removeUserToResourceRelation = removeUserToResourceRelation(componentType,
- owner.getUserId(), componentId, GraphEdgeLabels.STATE);
+ StorageOperationStatus removeUserToResourceRelation = removeUserToResourceRelation(componentType, owner.getUserId(), componentId, GraphEdgeLabels.STATE);
if (!removeUserToResourceRelation.equals(StorageOperationStatus.OK)) {
return removeUserToResourceRelation;
}
@@ -334,8 +314,7 @@ public class LifecycleOperation implements ILifecycleOperation {
// create CHECKIN relation
Map<String, Object> props = new HashMap<String, Object>();
props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
- StorageOperationStatus createUserToResourceRelation = createUserToResourceRelation(componentType,
- modifier.getUserId(), componentId, GraphEdgeLabels.STATE, props);
+ StorageOperationStatus createUserToResourceRelation = createUserToResourceRelation(componentType, modifier.getUserId(), componentId, GraphEdgeLabels.STATE, props);
if (!createUserToResourceRelation.equals(StorageOperationStatus.OK)) {
return createUserToResourceRelation;
}
@@ -344,15 +323,12 @@ public class LifecycleOperation implements ILifecycleOperation {
}
@Override
- public Either<? extends Component, StorageOperationStatus> requestCertificationComponent(NodeTypeEnum nodeType,
- Component component, User modifier, User owner, boolean inTransaction) {
+ public Either<? extends Component, StorageOperationStatus> requestCertificationComponent(NodeTypeEnum nodeType, Component component, User modifier, User owner, boolean inTransaction) {
Either<? extends Component, StorageOperationStatus> result = null;
try {
- StorageOperationStatus updateRfcOnGraph = updateRfcOnGraph(nodeType, component.getUniqueId(),
- component.getLifecycleState(), modifier, owner);
+ StorageOperationStatus updateRfcOnGraph = updateRfcOnGraph(nodeType, component.getUniqueId(), component.getLifecycleState(), modifier, owner);
if (!updateRfcOnGraph.equals(StorageOperationStatus.OK)) {
- log.error("failed to update state of resource {}. status={}", component.getUniqueId(),
- updateRfcOnGraph);
+ log.error("failed to update state of resource {}. status={}", component.getUniqueId(), updateRfcOnGraph);
return Either.right(updateRfcOnGraph);
}
@@ -362,8 +338,7 @@ public class LifecycleOperation implements ILifecycleOperation {
result = updateComponentMD(component, modifier, state, nodeType, componentParametersView);
if (result.isRight()) {
- log.debug("Couldn't set lifecycle for component {} to state {}, error: {}", component.getUniqueId(),
- state, result.right().value());
+ log.debug("Couldn't set lifecycle for component {} to state {}, error: {}", component.getUniqueId(), state, result.right().value());
return result;
}
return result;
@@ -381,15 +356,13 @@ public class LifecycleOperation implements ILifecycleOperation {
}
}
- private StorageOperationStatus updateRfcOnGraph(NodeTypeEnum componentType, String componentId,
- LifecycleStateEnum state, User modifier, User owner) {
+ private StorageOperationStatus updateRfcOnGraph(NodeTypeEnum componentType, String componentId, LifecycleStateEnum state, User modifier, User owner) {
if (state.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) {
// if this is atomic checkin + RFC: create checkin relation
// remove CHECKOUT relation
- StorageOperationStatus relationStatus = removeUserToResourceRelation(componentType, owner.getUserId(),
- componentId, GraphEdgeLabels.STATE);
+ StorageOperationStatus relationStatus = removeUserToResourceRelation(componentType, owner.getUserId(), componentId, GraphEdgeLabels.STATE);
if (!relationStatus.equals(StorageOperationStatus.OK)) {
return relationStatus;
}
@@ -397,14 +370,12 @@ public class LifecycleOperation implements ILifecycleOperation {
// create CHECKIN relation
Map<String, Object> props = new HashMap<String, Object>();
props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
- relationStatus = createUserToResourceRelation(componentType, modifier.getUserId(), componentId,
- GraphEdgeLabels.LAST_STATE, props);
+ relationStatus = createUserToResourceRelation(componentType, modifier.getUserId(), componentId, GraphEdgeLabels.LAST_STATE, props);
if (!relationStatus.equals(StorageOperationStatus.OK)) {
return relationStatus;
}
} else {
- StorageOperationStatus changeStatus = changeRelationLabel(componentType, componentId, owner,
- GraphEdgeLabels.STATE, GraphEdgeLabels.LAST_STATE);
+ StorageOperationStatus changeStatus = changeRelationLabel(componentType, componentId, owner, GraphEdgeLabels.STATE, GraphEdgeLabels.LAST_STATE);
if (!changeStatus.equals(StorageOperationStatus.OK)) {
return changeStatus;
}
@@ -413,21 +384,18 @@ public class LifecycleOperation implements ILifecycleOperation {
// create RFC relation
Map<String, Object> props = new HashMap<String, Object>();
props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION);
- StorageOperationStatus changeRelationLabel = createUserToResourceRelation(componentType, modifier.getUserId(),
- componentId, GraphEdgeLabels.STATE, props);
+ StorageOperationStatus changeRelationLabel = createUserToResourceRelation(componentType, modifier.getUserId(), componentId, GraphEdgeLabels.STATE, props);
if (!changeRelationLabel.equals(StorageOperationStatus.OK)) {
return changeRelationLabel;
}
return StorageOperationStatus.OK;
}
- private StorageOperationStatus changeRelationLabel(NodeTypeEnum componentType, String componentId, User owner,
- GraphEdgeLabels prevLabel, GraphEdgeLabels toLabel) {
+ private StorageOperationStatus changeRelationLabel(NodeTypeEnum componentType, String componentId, User owner, GraphEdgeLabels prevLabel, GraphEdgeLabels toLabel) {
UniqueIdData resourceV = new UniqueIdData(componentType, componentId);
UserData userV = new UserData();
userV.setUserId(owner.getUserId());
- Either<GraphRelation, TitanOperationStatus> replaceRelationLabelResult = titanGenericDao
- .replaceRelationLabel(userV, resourceV, prevLabel, toLabel);
+ Either<GraphRelation, TitanOperationStatus> replaceRelationLabelResult = titanGenericDao.replaceRelationLabel(userV, resourceV, prevLabel, toLabel);
if (replaceRelationLabelResult.isRight()) {
log.error("failed to replace label from last state to state");
return DaoStatusConverter.convertTitanStatusToStorageStatus(replaceRelationLabelResult.right().value());
@@ -436,12 +404,10 @@ public class LifecycleOperation implements ILifecycleOperation {
}
@Override
- public Either<? extends Component, StorageOperationStatus> startComponentCertification(NodeTypeEnum nodeType,
- Component component, User modifier, User owner, boolean inTransaction) {
+ public Either<? extends Component, StorageOperationStatus> startComponentCertification(NodeTypeEnum nodeType, Component component, User modifier, User owner, boolean inTransaction) {
Either<? extends Component, StorageOperationStatus> result = null;
try {
- StorageOperationStatus updateOnGraph = updateStartCertificationOnGraph(nodeType, component.getUniqueId(),
- modifier, owner);
+ StorageOperationStatus updateOnGraph = updateStartCertificationOnGraph(nodeType, component.getUniqueId(), modifier, owner);
if (!updateOnGraph.equals(StorageOperationStatus.OK)) {
log.error("failed to update state of resource {}. status={}", component.getUniqueId(), updateOnGraph);
return Either.right(updateOnGraph);
@@ -452,8 +418,7 @@ public class LifecycleOperation implements ILifecycleOperation {
result = updateComponentMD(component, modifier, state, nodeType, componentParametersView);
if (result.isRight()) {
- log.debug("Couldn't set lifecycle for component {} to state {}, error: {}", component.getUniqueId(),
- state, result.right().value());
+ log.debug("Couldn't set lifecycle for component {} to state {}, error: {}", component.getUniqueId(), state, result.right().value());
}
return result;
@@ -470,10 +435,8 @@ public class LifecycleOperation implements ILifecycleOperation {
}
}
- private StorageOperationStatus updateStartCertificationOnGraph(NodeTypeEnum componentType, String componentId,
- User modifier, User owner) {
- StorageOperationStatus changeRelationLabel = changeRelationLabel(componentType, componentId, owner,
- GraphEdgeLabels.STATE, GraphEdgeLabels.LAST_STATE);
+ private StorageOperationStatus updateStartCertificationOnGraph(NodeTypeEnum componentType, String componentId, User modifier, User owner) {
+ StorageOperationStatus changeRelationLabel = changeRelationLabel(componentType, componentId, owner, GraphEdgeLabels.STATE, GraphEdgeLabels.LAST_STATE);
if (!changeRelationLabel.equals(StorageOperationStatus.OK)) {
return changeRelationLabel;
}
@@ -481,8 +444,7 @@ public class LifecycleOperation implements ILifecycleOperation {
Map<String, Object> props = new HashMap<String, Object>();
props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
- StorageOperationStatus createUserToResourceRelation = createUserToResourceRelation(componentType,
- modifier.getUserId(), componentId, GraphEdgeLabels.STATE, props);
+ StorageOperationStatus createUserToResourceRelation = createUserToResourceRelation(componentType, modifier.getUserId(), componentId, GraphEdgeLabels.STATE, props);
if (!createUserToResourceRelation.equals(StorageOperationStatus.OK)) {
return createUserToResourceRelation;
}
@@ -490,8 +452,7 @@ public class LifecycleOperation implements ILifecycleOperation {
}
@Override
- public Either<? extends Component, StorageOperationStatus> certifyComponent(NodeTypeEnum nodeType,
- Component component, User modifier, User currentOwner, boolean inTransaction) {
+ public Either<? extends Component, StorageOperationStatus> certifyComponent(NodeTypeEnum nodeType, Component component, User modifier, User currentOwner, boolean inTransaction) {
Either<? extends Component, StorageOperationStatus> result = null;
try {
@@ -509,8 +470,7 @@ public class LifecycleOperation implements ILifecycleOperation {
}
// clone the resource
- Either<? extends Component, StorageOperationStatus> createResourceResult = Either
- .right(StorageOperationStatus.GENERAL_ERROR);
+ Either<? extends Component, StorageOperationStatus> createResourceResult = Either.right(StorageOperationStatus.GENERAL_ERROR);
switch (nodeType) {
case Service:
case Resource:
@@ -531,8 +491,7 @@ public class LifecycleOperation implements ILifecycleOperation {
Component certifiedResource = createResourceResult.left().value();
// add rfc relation to preserve follower information
- StorageOperationStatus addRfcRelation = addRfcRelationToCertfiedComponent(nodeType, resourceIdBeforeCertify,
- certifiedResource.getUniqueId());
+ StorageOperationStatus addRfcRelation = addRfcRelationToCertfiedComponent(nodeType, resourceIdBeforeCertify, certifiedResource.getUniqueId());
if (!addRfcRelation.equals(StorageOperationStatus.OK)) {
result = Either.right(addRfcRelation);
return result;
@@ -556,15 +515,13 @@ public class LifecycleOperation implements ILifecycleOperation {
}
@Override
- public Either<Boolean, StorageOperationStatus> deleteOldComponentVersions(NodeTypeEnum nodeType,
- String componentName, String uuid, boolean inTransaction) {
+ public Either<Boolean, StorageOperationStatus> deleteOldComponentVersions(NodeTypeEnum nodeType, String componentName, String uuid, boolean inTransaction) {
Either<Boolean, StorageOperationStatus> result = null;
ComponentOperation componentOperation = getComponentOperation(nodeType);
try {
- Either<List<Component>, StorageOperationStatus> oldVersionsToDelete = getComponentTempVersions(nodeType,
- uuid);
+ Either<List<Component>, StorageOperationStatus> oldVersionsToDelete = getComponentTempVersions(nodeType, uuid);
if (oldVersionsToDelete.isRight()) {
result = Either.right(oldVersionsToDelete.right().value());
@@ -573,8 +530,7 @@ public class LifecycleOperation implements ILifecycleOperation {
for (Component resourceToDelete : oldVersionsToDelete.left().value()) {
- Either<Component, StorageOperationStatus> updateResource = componentOperation
- .markComponentToDelete(resourceToDelete, inTransaction);
+ Either<Component, StorageOperationStatus> updateResource = componentOperation.markComponentToDelete(resourceToDelete, inTransaction);
if (updateResource.isRight()) {
result = Either.right(updateResource.right().value());
return result;
@@ -596,26 +552,22 @@ public class LifecycleOperation implements ILifecycleOperation {
}
}
- private StorageOperationStatus addRfcRelationToCertfiedComponent(NodeTypeEnum componentType,
- String resourceIdBeforeCertify, String uniqueId) {
+ private StorageOperationStatus addRfcRelationToCertfiedComponent(NodeTypeEnum componentType, String resourceIdBeforeCertify, String uniqueId) {
// get user of certification request
UniqueIdData componentV = new UniqueIdData(componentType, resourceIdBeforeCertify);
Map<String, Object> props = new HashMap<String, Object>();
props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION);
- Either<GraphRelation, TitanOperationStatus> rfcRelationResponse = titanGenericDao
- .getIncomingRelationByCriteria(componentV, GraphEdgeLabels.LAST_STATE, props);
+ Either<GraphRelation, TitanOperationStatus> rfcRelationResponse = titanGenericDao.getIncomingRelationByCriteria(componentV, GraphEdgeLabels.LAST_STATE, props);
if (rfcRelationResponse.isRight()) {
TitanOperationStatus status = rfcRelationResponse.right().value();
log.error("failed to find rfc relation for component {}. status=", resourceIdBeforeCertify, status);
return DaoStatusConverter.convertTitanStatusToStorageStatus(status);
}
GraphRelation rfcRelation = rfcRelationResponse.left().value();
- rfcRelation.setTo(
- new RelationEndPoint(componentType, GraphPropertiesDictionary.UNIQUE_ID.getProperty(), uniqueId));
+ rfcRelation.setTo(new RelationEndPoint(componentType, GraphPropertiesDictionary.UNIQUE_ID.getProperty(), uniqueId));
- Either<GraphRelation, TitanOperationStatus> createRelationResponse = titanGenericDao
- .createRelation(rfcRelation);
+ Either<GraphRelation, TitanOperationStatus> createRelationResponse = titanGenericDao.createRelation(rfcRelation);
if (createRelationResponse.isRight()) {
TitanOperationStatus status = createRelationResponse.right().value();
log.error("failed to create rfc relation for component {}. status=", uniqueId, status);
@@ -635,9 +587,7 @@ public class LifecycleOperation implements ILifecycleOperation {
additionalQueryParams = new HashMap<String, Object>();
additionalQueryParams.put(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), resourceType.name());
}
- Either<? extends Component, StorageOperationStatus> getLastCertifiedResponse = componentOperation
- .getComponentByNameAndVersion(component.getName(), majorVersion + VERSION_DELIMETER + "0",
- additionalQueryParams, true);
+ Either<? extends Component, StorageOperationStatus> getLastCertifiedResponse = componentOperation.getComponentByNameAndVersion(component.getName(), majorVersion + VERSION_DELIMETER + "0", additionalQueryParams, true);
if (getLastCertifiedResponse.isRight()) {
log.error("failed to update last certified resource. status={}", getLastCertifiedResponse.right().value());
@@ -646,8 +596,7 @@ public class LifecycleOperation implements ILifecycleOperation {
Component lastCertified = getLastCertifiedResponse.left().value();
lastCertified.setHighestVersion(false);
- Either<Component, StorageOperationStatus> updateResource = componentOperation.updateComponent(lastCertified,
- true);
+ Either<Component, StorageOperationStatus> updateResource = componentOperation.updateComponent(lastCertified, true);
if (updateResource.isRight()) {
log.error("failed to update last certified resource. status={}", updateResource.right().value());
return updateResource.right().value();
@@ -655,8 +604,7 @@ public class LifecycleOperation implements ILifecycleOperation {
return StorageOperationStatus.OK;
}
- private Either<Component, StorageOperationStatus> cloneComponentForCheckout(Component component,
- NodeTypeEnum nodeType, User modifier) {
+ private Either<Component, StorageOperationStatus> cloneComponentForCheckout(Component component, NodeTypeEnum nodeType, User modifier) {
ComponentOperation componentOperation = getComponentOperation(nodeType);
String prevId = component.getUniqueId();
@@ -686,8 +634,7 @@ public class LifecycleOperation implements ILifecycleOperation {
additionalQueryParams.put(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), resourceType.name());
}
String name = component.getComponentMetadataDefinition().getMetadataDataDefinition().getName();
- Either<Component, StorageOperationStatus> alreadyExistResult = componentOperation
- .getComponentByNameAndVersion(name, version, additionalQueryParams, true);
+ Either<Component, StorageOperationStatus> alreadyExistResult = componentOperation.getComponentByNameAndVersion(name, version, additionalQueryParams, true);
if (alreadyExistResult.isLeft()) {
log.debug("Component with name {} and version {} already exist", name, version);
return Either.right(StorageOperationStatus.ENTITY_ALREADY_EXISTS);
@@ -696,14 +643,11 @@ public class LifecycleOperation implements ILifecycleOperation {
StorageOperationStatus storageOperationStatus = alreadyExistResult.right().value();
if (storageOperationStatus != StorageOperationStatus.NOT_FOUND) {
- log.debug(
- "Unexpected error when checking if component with name {} and version {} already exist, error: {}",
- name, version, storageOperationStatus);
+ log.debug("Unexpected error when checking if component with name {} and version {} already exist, error: {}", name, version, storageOperationStatus);
return Either.right(storageOperationStatus);
}
- Either<Component, StorageOperationStatus> cloneComponentResponse = componentOperation.cloneComponent(component,
- version, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, true);
+ Either<Component, StorageOperationStatus> cloneComponentResponse = componentOperation.cloneComponent(component, version, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, true);
return cloneComponentResponse;
}
@@ -720,8 +664,7 @@ public class LifecycleOperation implements ILifecycleOperation {
return Either.left(newVersion);
}
- private StorageOperationStatus setRelationForCancelCertification(LifecycleStateEnum nextState,
- NodeTypeEnum componentType, String componentId) {
+ private StorageOperationStatus setRelationForCancelCertification(LifecycleStateEnum nextState, NodeTypeEnum componentType, String componentId) {
StorageOperationStatus result = StorageOperationStatus.GENERAL_ERROR;
Map<String, Object> props = new HashMap<String, Object>();
@@ -730,8 +673,7 @@ public class LifecycleOperation implements ILifecycleOperation {
// delete relation CERTIFICATION_IN_PROGRESS
props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
- Either<GraphRelation, TitanOperationStatus> deleteResult = titanGenericDao
- .deleteIncomingRelationByCriteria(componentData, GraphEdgeLabels.STATE, props);
+ Either<GraphRelation, TitanOperationStatus> deleteResult = titanGenericDao.deleteIncomingRelationByCriteria(componentData, GraphEdgeLabels.STATE, props);
if (deleteResult.isRight()) {
log.debug("failed to update last state relation");
result = StorageOperationStatus.INCONSISTENCY;
@@ -741,8 +683,7 @@ public class LifecycleOperation implements ILifecycleOperation {
// delete relation READY_FOR_CERTIFICATION (LAST_STATE)
props.put(GraphPropertiesDictionary.STATE.getProperty(), nextState);
- deleteResult = titanGenericDao.deleteIncomingRelationByCriteria(componentData, GraphEdgeLabels.LAST_STATE,
- props);
+ deleteResult = titanGenericDao.deleteIncomingRelationByCriteria(componentData, GraphEdgeLabels.LAST_STATE, props);
if (deleteResult.isRight()) {
log.debug("failed to update last state relation");
result = StorageOperationStatus.INCONSISTENCY;
@@ -753,8 +694,7 @@ public class LifecycleOperation implements ILifecycleOperation {
// create relation READY_FOR_CERTIFICATION (STATE)
UserData user = new UserData();
user.setUserId((String) origRelation.getFrom().getIdValue());
- Either<GraphRelation, TitanOperationStatus> createRelationResult = titanGenericDao.createRelation(user,
- componentData, GraphEdgeLabels.STATE, origRelation.toGraphMap());
+ Either<GraphRelation, TitanOperationStatus> createRelationResult = titanGenericDao.createRelation(user, componentData, GraphEdgeLabels.STATE, origRelation.toGraphMap());
if (createRelationResult.isRight()) {
log.error("failed to update last state relation. status={}", createRelationResult.right().value());
@@ -764,8 +704,7 @@ public class LifecycleOperation implements ILifecycleOperation {
return StorageOperationStatus.OK;
}
- private StorageOperationStatus setRelationForFailCertification(LifecycleStateEnum nextState,
- NodeTypeEnum componentType, String componentId) {
+ private StorageOperationStatus setRelationForFailCertification(LifecycleStateEnum nextState, NodeTypeEnum componentType, String componentId) {
StorageOperationStatus result = null;
Map<String, Object> props = new HashMap<String, Object>();
@@ -774,8 +713,7 @@ public class LifecycleOperation implements ILifecycleOperation {
// delete relation CERTIFICATION_IN_PROGRESS
props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
- Either<GraphRelation, TitanOperationStatus> deleteResult = titanGenericDao
- .deleteIncomingRelationByCriteria(componentData, GraphEdgeLabels.STATE, props);
+ Either<GraphRelation, TitanOperationStatus> deleteResult = titanGenericDao.deleteIncomingRelationByCriteria(componentData, GraphEdgeLabels.STATE, props);
if (deleteResult.isRight()) {
log.debug("failed to update last state relation");
result = StorageOperationStatus.INCONSISTENCY;
@@ -785,8 +723,7 @@ public class LifecycleOperation implements ILifecycleOperation {
// delete relation READY_FOR_CERTIFICATION
props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION);
- deleteResult = titanGenericDao.deleteIncomingRelationByCriteria(componentData, GraphEdgeLabels.LAST_STATE,
- props);
+ deleteResult = titanGenericDao.deleteIncomingRelationByCriteria(componentData, GraphEdgeLabels.LAST_STATE, props);
if (deleteResult.isRight()) {
log.debug("failed to update last state relation");
result = StorageOperationStatus.INCONSISTENCY;
@@ -795,8 +732,7 @@ public class LifecycleOperation implements ILifecycleOperation {
// delete relation NOT_CERTIFIED_CHECKIN (in order to change to STATE)
props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
- deleteResult = titanGenericDao.deleteIncomingRelationByCriteria(componentData, GraphEdgeLabels.LAST_STATE,
- props);
+ deleteResult = titanGenericDao.deleteIncomingRelationByCriteria(componentData, GraphEdgeLabels.LAST_STATE, props);
if (deleteResult.isRight()) {
log.debug("failed to update last state relation");
result = StorageOperationStatus.INCONSISTENCY;
@@ -807,14 +743,31 @@ public class LifecycleOperation implements ILifecycleOperation {
GraphRelation origRelation = deleteResult.left().value();
UserData user = new UserData();
user.setUserId((String) origRelation.getFrom().getIdValue());
- Either<GraphRelation, TitanOperationStatus> createRelationResult = titanGenericDao.createRelation(user,
- componentData, GraphEdgeLabels.STATE, origRelation.toGraphMap());
+ Either<GraphRelation, TitanOperationStatus> createRelationResult = titanGenericDao.createRelation(user, componentData, GraphEdgeLabels.STATE, origRelation.toGraphMap());
if (createRelationResult.isRight()) {
log.debug("failed to update last state relation");
result = StorageOperationStatus.INCONSISTENCY;
return result;
}
+
+ // delete relation LAST_MODIFIER (in order to change tester to designer)
+ deleteResult = titanGenericDao.deleteIncomingRelationByCriteria(componentData, GraphEdgeLabels.LAST_MODIFIER, null);
+ if (deleteResult.isRight()) {
+ log.debug("failed to update last modifier relation");
+ result = StorageOperationStatus.INCONSISTENCY;
+ return result;
+ }
+
+ // create new LAST_MODIFIER relation
+ origRelation = deleteResult.left().value();
+ createRelationResult = titanGenericDao.createRelation(user, componentData, GraphEdgeLabels.LAST_MODIFIER, origRelation.toGraphMap());
+ if (createRelationResult.isRight()) {
+ log.debug("failed to update last state relation");
+ result = StorageOperationStatus.INCONSISTENCY;
+ return result;
+ }
+
return StorageOperationStatus.OK;
}
@@ -826,9 +779,7 @@ public class LifecycleOperation implements ILifecycleOperation {
* @param nextState
* @return
*/
- private Either<Component, StorageOperationStatus> updateComponentMD(Component component, User modifier,
- LifecycleStateEnum nextState, NodeTypeEnum nodeType,
- ComponentParametersView returnedComponentParametersViewFilter) {
+ private Either<Component, StorageOperationStatus> updateComponentMD(Component component, User modifier, LifecycleStateEnum nextState, NodeTypeEnum nodeType, ComponentParametersView returnedComponentParametersViewFilter) {
if (returnedComponentParametersViewFilter == null) {
returnedComponentParametersViewFilter = new ComponentParametersView();
@@ -849,34 +800,28 @@ public class LifecycleOperation implements ILifecycleOperation {
}
log.debug("updateComponentMD::getAndUpdateMetadata start");
// get service MD
- Either<ComponentMetadataData, TitanOperationStatus> componentDataResult = titanGenericDao.getNode(
- UniqueIdBuilder.getKeyByNodeType(nodeType), component.getUniqueId(), ComponentMetadataData.class);
+ Either<ComponentMetadataData, TitanOperationStatus> componentDataResult = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), component.getUniqueId(), ComponentMetadataData.class);
if (componentDataResult.isRight()) {
log.debug("failed to get service data from graph");
- return Either
- .right(DaoStatusConverter.convertTitanStatusToStorageStatus(componentDataResult.right().value()));
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(componentDataResult.right().value()));
}
// set state on resource
ComponentMetadataData componentData = componentDataResult.left().value();
componentData.getMetadataDataDefinition().setState(nextState.name());
component.setLifecycleState(nextState);
- Either<ComponentMetadataData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(componentData,
- ComponentMetadataData.class);
+ Either<ComponentMetadataData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(componentData, ComponentMetadataData.class);
log.debug("updateComponentMD::getAndUpdateMetadata end");
if (updateNode.isRight()) {
- log.error("Failed to update component " + component.getUniqueId() + ". status is "
- + updateNode.right().value());
+ log.error("Failed to update component {}. status is {}", component.getUniqueId(), updateNode.right().value());
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateNode.right().value()));
return result;
}
log.debug("updateComponentMD::getAndUpdateMetadata start");
- Either<Object, StorageOperationStatus> serviceAfterChange = componentOperation
- .getComponent(component.getUniqueId(), returnedComponentParametersViewFilter, true);
+ Either<Object, StorageOperationStatus> serviceAfterChange = componentOperation.getComponent(component.getUniqueId(), returnedComponentParametersViewFilter, true);
log.debug("updateComponentMD::getAndUpdateMetadata end");
if (serviceAfterChange.isRight()) {
- log.error("Failed to get component " + component.getUniqueId() + " after change. status is "
- + updateNode.right().value());
+ log.error("Failed to get component {} after change. status is {}", component.getUniqueId(), updateNode.right().value());
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateNode.right().value()));
return result;
}
@@ -891,8 +836,7 @@ public class LifecycleOperation implements ILifecycleOperation {
* @param nextState
* @return
*/
- private Either<Resource, StorageOperationStatus> updateResourceMD(Resource resource, User modifier,
- LifecycleStateEnum nextState) {
+ private Either<Resource, StorageOperationStatus> updateResourceMD(Resource resource, User modifier, LifecycleStateEnum nextState) {
Either<Resource, StorageOperationStatus> result;
resource.setLastUpdateDate(null);
@@ -904,33 +848,27 @@ public class LifecycleOperation implements ILifecycleOperation {
return result;
}
// get resource MD
- Either<ResourceMetadataData, TitanOperationStatus> resourceDataResult = titanGenericDao.getNode(
- UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resource.getUniqueId(),
- ResourceMetadataData.class);
+ Either<ResourceMetadataData, TitanOperationStatus> resourceDataResult = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resource.getUniqueId(), ResourceMetadataData.class);
if (resourceDataResult.isRight()) {
log.debug("failed to get resource data from graph");
- return Either
- .right(DaoStatusConverter.convertTitanStatusToStorageStatus(resourceDataResult.right().value()));
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resourceDataResult.right().value()));
}
// set state on resource
ResourceMetadataData resourceData = resourceDataResult.left().value();
resourceData.getMetadataDataDefinition().setState(nextState.name());
resource.setLifecycleState(nextState);
- Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(resourceData,
- ResourceMetadataData.class);
+ Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(resourceData, ResourceMetadataData.class);
if (updateNode.isRight()) {
- log.error("Failed to update resource " + resource.getUniqueId() + ". status is "
- + updateNode.right().value());
+ log.error("Failed to update resource {}. status is {}", resource.getUniqueId(), updateNode.right().value());
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateNode.right().value()));
return result;
}
return Either.left(resource);
}
- private Either<List<Component>, StorageOperationStatus> getComponentTempVersions(NodeTypeEnum nodeType,
- String uuid) {
+ private Either<List<Component>, StorageOperationStatus> getComponentTempVersions(NodeTypeEnum nodeType, String uuid) {
Either<List<Component>, StorageOperationStatus> result = Either.right(StorageOperationStatus.GENERAL_ERROR);
List<Component> componentList = new ArrayList<Component>();
@@ -941,8 +879,7 @@ public class LifecycleOperation implements ILifecycleOperation {
createOldVersionsCriteria(nodeType, uuid, hasProps, hasNotProps);
- Either<List<ComponentMetadataData>, TitanOperationStatus> getByCriteria = titanGenericDao
- .getByCriteria(nodeType, hasProps, hasNotProps, ComponentMetadataData.class);
+ Either<List<ComponentMetadataData>, TitanOperationStatus> getByCriteria = titanGenericDao.getByCriteria(nodeType, hasProps, hasNotProps, ComponentMetadataData.class);
if (getByCriteria.isRight()) {
log.error("failed to get old versions for component, type:{}, id: {}", nodeType, uuid);
@@ -952,8 +889,7 @@ public class LifecycleOperation implements ILifecycleOperation {
List<ComponentMetadataData> oldVersionComponents = getByCriteria.left().value();
for (ComponentMetadataData component : oldVersionComponents) {
- Either<Component, StorageOperationStatus> resourceRes = componentOperation
- .getComponent(component.getMetadataDataDefinition().getUniqueId(), true);
+ Either<Component, StorageOperationStatus> resourceRes = componentOperation.getComponent(component.getMetadataDataDefinition().getUniqueId(), true);
if (resourceRes.isRight()) {
result = Either.right(resourceRes.right().value());
return result;
@@ -965,17 +901,31 @@ public class LifecycleOperation implements ILifecycleOperation {
return result;
}
- private void createOldVersionsCriteria(NodeTypeEnum nodeType, String uuid, Map<String, Object> hasProps,
- Map<String, Object> hasNotProps) {
+ /*
+ * private Either<List<Service>, StorageOperationStatus> getServiceTempVersions(NodeTypeEnum nodeType, String uuid) {
+ *
+ * Either<List<Service>, StorageOperationStatus> result = Either.right(StorageOperationStatus.GENERAL_ERROR); List<Service> resourceList = new ArrayList<Service>();
+ *
+ * Map<String, Object> hasProps = new HashMap<String, Object>(); Map<String, Object> hasNotProps = new HashMap<String, Object>();
+ *
+ * createOldVersionsCriteria(nodeType, uuid, hasProps, hasNotProps);
+ *
+ * Either<List<ServiceMetadataData>, TitanOperationStatus> getByCriteria = titanGenericDao.getByCriteria(NodeTypeEnum.Service, hasProps, hasNotProps, ServiceMetadataData.class);
+ *
+ * if (getByCriteria.isRight()) { log.error("failed to get old versions for {}", uuid); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus( getByCriteria.right().value())); return result; }
+ *
+ * List<ServiceMetadataData> oldVersionResources = getByCriteria.left().value(); for (ServiceMetadataData resource : oldVersionResources) { Either<Service, StorageOperationStatus> resourceRes = serviceOperation.getService((String)
+ * resource.getUniqueId(), true); if (resourceRes.isRight()) { result = Either.right(resourceRes.right().value()); return result; } else { resourceList.add(resourceRes.left().value()); } } result = Either.left(resourceList); return result; }
+ */
+ private void createOldVersionsCriteria(NodeTypeEnum nodeType, String uuid, Map<String, Object> hasProps, Map<String, Object> hasNotProps) {
hasProps.put(GraphPropertiesDictionary.UUID.getProperty(), uuid);
hasProps.put(GraphPropertiesDictionary.LABEL.getProperty(), nodeType.name().toLowerCase());
hasNotProps.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFIED.name());
}
- private Either<? extends Component, StorageOperationStatus> updateOldComponentBeforeUndoCheckout(
- ComponentOperation componentOperation, Component prevComponent, Component currentComponent,
- String previousVersion, NodeTypeEnum nodeType, boolean inTransaction) {
+ private Either<? extends Component, StorageOperationStatus> updateOldComponentBeforeUndoCheckout(ComponentOperation componentOperation, Component prevComponent, Component currentComponent, String previousVersion, NodeTypeEnum nodeType,
+ boolean inTransaction) {
log.debug("update previous version of component");
Map<String, Object> additionalQueryParams = new HashMap<String, Object>();
@@ -985,31 +935,25 @@ public class LifecycleOperation implements ILifecycleOperation {
additionalQueryParams.put(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), resourceType.name());
}
- ComponentMetadataDataDefinition metadataDataDefinition = currentComponent.getComponentMetadataDefinition()
- .getMetadataDataDefinition();
- Either<? extends Component, StorageOperationStatus> getOlderCompResult = componentOperation
- .getComponentByNameAndVersion(metadataDataDefinition.getName(), previousVersion, additionalQueryParams,
- true);
+ ComponentMetadataDataDefinition metadataDataDefinition = currentComponent.getComponentMetadataDefinition().getMetadataDataDefinition();
+ Either<? extends Component, StorageOperationStatus> getOlderCompResult = componentOperation.getComponentByNameAndVersion(metadataDataDefinition.getName(), previousVersion, additionalQueryParams, true);
// if previous version exist - set it as current version
if (getOlderCompResult.isRight()) {
if (StorageOperationStatus.NOT_FOUND.equals(getOlderCompResult.right().value())) {
- log.debug("No components by name and version : {} {}", metadataDataDefinition.getName(), previousVersion);
+ log.debug("No components by name and version: {} - {}", metadataDataDefinition.getName(), previousVersion);
log.debug("Name may have changed, since the version isn't certified try to fetch by UUID {}", metadataDataDefinition.getUUID());
additionalQueryParams.clear();
- additionalQueryParams.put(GraphPropertiesDictionary.UUID.getProperty(),
- metadataDataDefinition.getUUID());
+ additionalQueryParams.put(GraphPropertiesDictionary.UUID.getProperty(), metadataDataDefinition.getUUID());
additionalQueryParams.put(GraphPropertiesDictionary.VERSION.getProperty(), previousVersion);
- Either<List<ComponentMetadataData>, TitanOperationStatus> byUUID = titanGenericDao
- .getByCriteria(nodeType, additionalQueryParams, ComponentMetadataData.class);
+ Either<List<ComponentMetadataData>, TitanOperationStatus> byUUID = titanGenericDao.getByCriteria(nodeType, additionalQueryParams, ComponentMetadataData.class);
if (byUUID.isRight()) {
log.debug("Failed to fetch by UUID {}", metadataDataDefinition.getUUID());
return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(byUUID.right().value()));
}
String prevVersionId = (String) byUUID.left().value().get(0).getUniqueId();
- Either<? extends Component, StorageOperationStatus> component = componentOperation
- .getComponent(prevVersionId, inTransaction);
+ Either<? extends Component, StorageOperationStatus> component = componentOperation.getComponent(prevVersionId, inTransaction);
if (component.isRight()) {
log.debug("Failed to fetch previous component by ID {}", prevVersionId);
return Either.right(component.right().value());
@@ -1029,8 +973,7 @@ public class LifecycleOperation implements ILifecycleOperation {
}
prevComponent.setHighestVersion(true);
- Either<Component, StorageOperationStatus> updateCompResult = componentOperation.updateComponent(prevComponent,
- inTransaction);
+ Either<Component, StorageOperationStatus> updateCompResult = componentOperation.updateComponent(prevComponent, inTransaction);
if (updateCompResult.isRight()) {
log.debug("failed to update prev version of component");
return updateCompResult;
@@ -1038,8 +981,7 @@ public class LifecycleOperation implements ILifecycleOperation {
User user = new User();
user.setUserId(prevComponent.getLastUpdaterUserId());
- StorageOperationStatus changeStateRelation = changeStateRelation(nodeType, prevComponent.getUniqueId(), user,
- GraphEdgeLabels.LAST_STATE, GraphEdgeLabels.STATE);
+ StorageOperationStatus changeStateRelation = changeStateRelation(nodeType, prevComponent.getUniqueId(), user, GraphEdgeLabels.LAST_STATE, GraphEdgeLabels.STATE);
if (!changeStateRelation.equals(StorageOperationStatus.OK)) {
return Either.right(changeStateRelation);
}
@@ -1047,13 +989,11 @@ public class LifecycleOperation implements ILifecycleOperation {
return Either.left(prevComponent);
}
- private StorageOperationStatus changeStateRelation(NodeTypeEnum nodeType, String componentId, User currentOwner,
- GraphEdgeLabels from, GraphEdgeLabels to) {
+ private StorageOperationStatus changeStateRelation(NodeTypeEnum nodeType, String componentId, User currentOwner, GraphEdgeLabels from, GraphEdgeLabels to) {
UniqueIdData componentData = new UniqueIdData(nodeType, componentId);
UserData userData = new UserData();
userData.setUserId(currentOwner.getUserId());
- Either<GraphRelation, TitanOperationStatus> replaceRelationLabelResult = titanGenericDao
- .replaceRelationLabel(userData, componentData, from, to);
+ Either<GraphRelation, TitanOperationStatus> replaceRelationLabelResult = titanGenericDao.replaceRelationLabel(userData, componentData, from, to);
if (replaceRelationLabelResult.isRight()) {
TitanOperationStatus titanStatus = replaceRelationLabelResult.right().value();
log.error("failed to replace label from {} to {}. status = {}", from, to, titanStatus);
@@ -1066,15 +1006,13 @@ public class LifecycleOperation implements ILifecycleOperation {
return StorageOperationStatus.OK;
}
- private StorageOperationStatus removeUserToResourceRelation(NodeTypeEnum componentType, String idFrom, String idTo,
- GraphEdgeLabels label) {
+ private StorageOperationStatus removeUserToResourceRelation(NodeTypeEnum componentType, String idFrom, String idTo, GraphEdgeLabels label) {
UniqueIdData componentV = new UniqueIdData(componentType, idTo);
UserData userV = new UserData();
userV.setUserId(idFrom);
// delete relation
- Either<GraphRelation, TitanOperationStatus> deleteRelationResult = titanGenericDao.deleteRelation(userV,
- componentV, label);
+ Either<GraphRelation, TitanOperationStatus> deleteRelationResult = titanGenericDao.deleteRelation(userV, componentV, label);
if (deleteRelationResult.isRight()) {
log.error("failed to delete relation. status={}", deleteRelationResult.right().value());
return DaoStatusConverter.convertTitanStatusToStorageStatus(deleteRelationResult.right().value());
@@ -1082,15 +1020,13 @@ public class LifecycleOperation implements ILifecycleOperation {
return StorageOperationStatus.OK;
}
- private StorageOperationStatus createUserToResourceRelation(NodeTypeEnum componentType, String idFrom, String idTo,
- GraphEdgeLabels label, Map<String, Object> props) {
+ private StorageOperationStatus createUserToResourceRelation(NodeTypeEnum componentType, String idFrom, String idTo, GraphEdgeLabels label, Map<String, Object> props) {
UniqueIdData componentV = new UniqueIdData(componentType, idTo);
UserData userV = new UserData();
userV.setUserId(idFrom);
// create relation
- Either<GraphRelation, TitanOperationStatus> createRelationResult = titanGenericDao.createRelation(userV,
- componentV, label, props);
+ Either<GraphRelation, TitanOperationStatus> createRelationResult = titanGenericDao.createRelation(userV, componentV, label, props);
if (createRelationResult.isRight()) {
log.error("failed to create relation. status={}", createRelationResult.right().value());
return DaoStatusConverter.convertTitanStatusToStorageStatus(createRelationResult.right().value());
@@ -1099,8 +1035,7 @@ public class LifecycleOperation implements ILifecycleOperation {
}
@Override
- public Either<? extends Component, StorageOperationStatus> cancelOrFailCertification(NodeTypeEnum nodeType,
- Component component, User modifier, User owner, LifecycleStateEnum nextState, boolean inTransaction) {
+ public Either<? extends Component, StorageOperationStatus> cancelOrFailCertification(NodeTypeEnum nodeType, Component component, User modifier, User owner, LifecycleStateEnum nextState, boolean inTransaction) {
Either<? extends Component, StorageOperationStatus> result = Either.right(StorageOperationStatus.GENERAL_ERROR);
try {
@@ -1108,8 +1043,7 @@ public class LifecycleOperation implements ILifecycleOperation {
ComponentParametersView componentParametersView = buildFilterForFetchComponentAfterChangeState();
result = updateComponentMD(component, modifier, nextState, nodeType, componentParametersView);
if (result.isRight()) {
- log.debug("Couldn't set lifecycle for component {} to state {}, error: {}", component.getUniqueId(),
- nextState, result.right().value());
+ log.debug("Couldn't set lifecycle for component {} to state {}, error: {}", component.getUniqueId(), nextState, result.right().value());
return result;
}
StorageOperationStatus status = StorageOperationStatus.OK;
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 a7f8275064..033d5c268b 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
@@ -91,7 +91,6 @@ public class OnboardingClient {
}
- // Mock returning a file from the file system until we have API from onboarding
public Either<Map<String, byte[]>, StorageOperationStatus> getMockCsar(String csarUuid) {
File dir = new File("/var/tmp/mockCsar");
FileFilter fileFilter = new WildcardFileFilter("*.csar");
@@ -169,7 +168,7 @@ public class OnboardingClient {
/**
* Build the url for download CSAR
*
- * E.g., http://1.2.3.4:8181/onboarding-api/v1.0/vendor-software-products/packages/
+ * E.g., http://0.0.0.0:8181/onboarding-api/v1.0/vendor-software-products/packages/
*
* @return
*/
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 d085c242e8..796fc8dd34 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
@@ -64,8 +64,7 @@ public class PolicyTypeOperation extends AbstractOperation implements IPolicyTyp
return getLatestPolicyTypeByType(policyTypeName, false);
}
- private Either<PolicyTypeDefinition, StorageOperationStatus> getLatestPolicyTypeByType(String type,
- boolean inTransaction) {
+ 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);
@@ -79,8 +78,7 @@ public class PolicyTypeOperation extends AbstractOperation implements IPolicyTyp
}
@Override
- public Either<PolicyTypeDefinition, StorageOperationStatus> addPolicyType(PolicyTypeDefinition policyTypeDef,
- boolean inTransaction) {
+ public Either<PolicyTypeDefinition, StorageOperationStatus> addPolicyType(PolicyTypeDefinition policyTypeDef, boolean inTransaction) {
Either<PolicyTypeDefinition, StorageOperationStatus> result = null;
@@ -89,10 +87,8 @@ public class PolicyTypeOperation extends AbstractOperation implements IPolicyTyp
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()));
+ 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();
@@ -101,8 +97,7 @@ public class PolicyTypeOperation extends AbstractOperation implements IPolicyTyp
Either<PolicyTypeDefinition, StorageOperationStatus> policyTypeRes = this.getPolicyType(uniqueId, true);
if (policyTypeRes.isRight()) {
- BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError(GET_FLOW_CONTEXT,
- policyTypeDef.getType(), eitherStatus.right().value().name());
+ BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError(GET_FLOW_CONTEXT, policyTypeDef.getType(), eitherStatus.right().value().name());
}
result = policyTypeRes;
@@ -126,20 +121,18 @@ public class PolicyTypeOperation extends AbstractOperation implements IPolicyTyp
log.debug("Before adding policy type to graph. policyTypeData = {}", policyTypeData);
- Either<PolicyTypeData, TitanOperationStatus> eitherPolicyTypeData = titanGenericDao.createNode(policyTypeData,
- PolicyTypeData.class);
+ 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);
+ 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);
+ 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());
@@ -148,8 +141,7 @@ public class PolicyTypeOperation extends AbstractOperation implements IPolicyTyp
return Either.left(eitherPolicyTypeData.left().value());
}
- public Either<PolicyTypeDefinition, StorageOperationStatus> getPolicyTypeByCriteria(String type,
- Map<String, Object> properties, boolean inTransaction) {
+ public Either<PolicyTypeDefinition, StorageOperationStatus> getPolicyTypeByCriteria(String type, Map<String, Object> properties, boolean inTransaction) {
Either<PolicyTypeDefinition, StorageOperationStatus> result = null;
try {
if (type == null || type.isEmpty()) {
@@ -158,14 +150,11 @@ public class PolicyTypeOperation extends AbstractOperation implements IPolicyTyp
return result;
}
- Either<List<PolicyTypeData>, TitanOperationStatus> eitherPolicyData = titanGenericDao
- .getByCriteria(NodeTypeEnum.PolicyType, properties, PolicyTypeData.class);
+ Either<List<PolicyTypeData>, TitanOperationStatus> eitherPolicyData = titanGenericDao.getByCriteria(NodeTypeEnum.PolicyType, properties, PolicyTypeData.class);
if (eitherPolicyData.isRight()) {
- result = Either
- .right(DaoStatusConverter.convertTitanStatusToStorageStatus(eitherPolicyData.right().value()));
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(eitherPolicyData.right().value()));
} else {
- PolicyTypeDataDefinition dataDefinition = eitherPolicyData.left().value().stream()
- .map(e -> e.getPolicyTypeDataDefinition()).findFirst().get();
+ PolicyTypeDataDefinition dataDefinition = eitherPolicyData.left().value().stream().map(e -> e.getPolicyTypeDataDefinition()).findFirst().get();
result = getPolicyType(dataDefinition.getUniqueId(), inTransaction);
}
@@ -178,8 +167,7 @@ public class PolicyTypeOperation extends AbstractOperation implements IPolicyTyp
@Override
public Either<PolicyTypeDefinition, StorageOperationStatus> getPolicyType(String uniqueId, boolean inTransaction) {
- Function<String, Either<PolicyTypeDefinition, TitanOperationStatus>> policyTypeGetter = uId -> getPolicyTypeByUid(
- uId);
+ Function<String, Either<PolicyTypeDefinition, TitanOperationStatus>> policyTypeGetter = uId -> getPolicyTypeByUid(uId);
return getElementType(policyTypeGetter, uniqueId, inTransaction);
}
@@ -187,21 +175,18 @@ public class PolicyTypeOperation extends AbstractOperation implements IPolicyTyp
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);
+ 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);
+ 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());
+ PolicyTypeDefinition policyTypeDefinition = new PolicyTypeDefinition(policyTypeData.getPolicyTypeDataDefinition());
- TitanOperationStatus propertiesStatus = propertyOperation.fillProperties(uniqueId,
- propList -> policyTypeDefinition.setProperties(propList));
+ 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);
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ProductOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ProductOperation.java
index 2a8192421b..3d4fba36df 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ProductOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ProductOperation.java
@@ -94,10 +94,8 @@ public class ProductOperation extends ComponentOperation implements IProductOper
@SuppressWarnings("unchecked")
@Override
- protected <T> Either<T, StorageOperationStatus> getComponentByNameAndVersion(String name, String version,
- Map<String, Object> additionalParams, boolean inTransaction) {
- return (Either<T, StorageOperationStatus>) getByNamesAndVersion(GraphPropertiesDictionary.NAME.getProperty(),
- name, version, additionalParams, inTransaction);
+ protected <T> Either<T, StorageOperationStatus> getComponentByNameAndVersion(String name, String version, Map<String, Object> additionalParams, boolean inTransaction) {
+ return (Either<T, StorageOperationStatus>) getByNamesAndVersion(GraphPropertiesDictionary.NAME.getProperty(), name, version, additionalParams, inTransaction);
}
@Override
@@ -106,14 +104,12 @@ public class ProductOperation extends ComponentOperation implements IProductOper
}
@Override
- public <T> Either<List<T>, StorageOperationStatus> getFilteredComponents(Map<FilterKeyEnum, String> filters,
- boolean inTransaction) {
+ public <T> Either<List<T>, StorageOperationStatus> getFilteredComponents(Map<FilterKeyEnum, String> filters, boolean inTransaction) {
return getFilteredComponents(filters, inTransaction, NodeTypeEnum.Product);
}
private Product convertProductDataToProduct(ProductMetadataData productData) {
- ProductMetadataDefinition productMetadataDefinition = new ProductMetadataDefinition(
- (ProductMetadataDataDefinition) productData.getMetadataDataDefinition());
+ ProductMetadataDefinition productMetadataDefinition = new ProductMetadataDefinition((ProductMetadataDataDefinition) productData.getMetadataDataDefinition());
Product product = new Product(productMetadataDefinition);
@@ -123,28 +119,24 @@ public class ProductOperation extends ComponentOperation implements IProductOper
@SuppressWarnings("unchecked")
@Override
public <T> Either<T, StorageOperationStatus> updateComponent(T component, boolean inTransaction) {
- return (Either<T, StorageOperationStatus>) updateComponent((Component) component, inTransaction,
- titanGenericDao, Product.class, NodeTypeEnum.Product);
+ return (Either<T, StorageOperationStatus>) updateComponent((Component) component, inTransaction, titanGenericDao, Product.class, NodeTypeEnum.Product);
}
@SuppressWarnings("unchecked")
@Override
public Either<Component, StorageOperationStatus> deleteComponent(String id, boolean inTransaction) {
- return (Either<Component, StorageOperationStatus>) (Either<?, StorageOperationStatus>) deleteProduct(id,
- inTransaction);
+ return (Either<Component, StorageOperationStatus>) (Either<?, StorageOperationStatus>) deleteProduct(id, inTransaction);
}
@Override
- public Either<List<ArtifactDefinition>, StorageOperationStatus> getAdditionalArtifacts(String resourceId,
- boolean recursively, boolean inTransaction) {
+ public Either<List<ArtifactDefinition>, StorageOperationStatus> getAdditionalArtifacts(String resourceId, boolean recursively, boolean inTransaction) {
// TODO Auto-generated method stub
return null;
}
@SuppressWarnings("unchecked")
@Override
- public <T extends org.openecomp.sdc.be.model.Component> Either<T, StorageOperationStatus> getComponent(String id,
- Class<T> clazz) {
+ public <T extends org.openecomp.sdc.be.model.Component> Either<T, StorageOperationStatus> getComponent(String id, Class<T> clazz) {
return (Either<T, StorageOperationStatus>) getProduct(id, false);
}
@@ -160,16 +152,14 @@ public class ProductOperation extends ComponentOperation implements IProductOper
Either<TitanGraph, TitanOperationStatus> graphResult = titanGenericDao.getGraph();
if (graphResult.isRight()) {
- result = Either
- .right(DaoStatusConverter.convertTitanStatusToStorageStatus(graphResult.right().value()));
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graphResult.right().value()));
return result;
}
- Either<ProductMetadataData, TitanOperationStatus> productNode = titanGenericDao.getNode(
- UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Product), productId, ProductMetadataData.class);
+ Either<ProductMetadataData, TitanOperationStatus> productNode = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Product), productId, ProductMetadataData.class);
if (productNode.isRight()) {
TitanOperationStatus status = productNode.right().value();
- log.error("Failed to find product {}. Status is {}", productId, status);
+ log.error("Failed to find product {}. status is {}", productId, status);
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
return result;
}
@@ -177,29 +167,27 @@ public class ProductOperation extends ComponentOperation implements IProductOper
Either<Product, StorageOperationStatus> productRes = getProduct(productId, true);
if (productRes.isRight()) {
StorageOperationStatus status = productRes.right().value();
- log.error("Failed to find product {}", productId, status);
+ log.error("Failed to find product {}.status is {}", productId, status);
result = Either.right(status);
return result;
}
Product product = productRes.left().value();
- Either<List<ComponentInstance>, StorageOperationStatus> deleteAllInstancesRes = componentInstanceOperation
- .deleteAllComponentInstances(productId, NodeTypeEnum.Product, true);
- log.debug("After deleting instances under product {}. Result is {}", productId, deleteAllInstancesRes);
+ Either<List<ComponentInstance>, StorageOperationStatus> deleteAllInstancesRes = componentInstanceOperation.deleteAllComponentInstances(productId, NodeTypeEnum.Product, true);
+ log.debug("After deleting instances under product {}.Result is {}", productId, deleteAllInstancesRes);
if (deleteAllInstancesRes.isRight()) {
StorageOperationStatus status = deleteAllInstancesRes.right().value();
if (status != StorageOperationStatus.NOT_FOUND) {
- log.error("Failed to delete instances under product {}. Status is {}", productId, status);
+ log.error("Failed to delete instances under product {}.status is {}", productId, status);
result = Either.right(status);
return result;
}
}
- Either<ProductMetadataData, TitanOperationStatus> deleteProductNodeRes = titanGenericDao
- .deleteNode(productNode.left().value(), ProductMetadataData.class);
+ Either<ProductMetadataData, TitanOperationStatus> deleteProductNodeRes = titanGenericDao.deleteNode(productNode.left().value(), ProductMetadataData.class);
if (deleteProductNodeRes.isRight()) {
TitanOperationStatus status = deleteProductNodeRes.right().value();
- log.error("Failed to delete product node {}. Status is {}", productId, status);
+ log.error("Failed to delete product node {}. status is {}", productId, status);
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
return result;
}
@@ -230,47 +218,20 @@ public class ProductOperation extends ComponentOperation implements IProductOper
/*
* Map<String, Object> propertiesToMatch = new HashMap<>();
*
- * propertiesToMatch.put(GraphPropertiesDictionary.STATE.getProperty
- * (), LifecycleStateEnum.CERTIFIED.name());
- * Either<List<ProductMetadataData>, TitanOperationStatus>
- * lastVersionNodes = getLastVersion(NodeTypeEnum.Product,
- * propertiesToMatch, ProductMetadataData.class); if
- * (lastVersionNodes.isRight() && lastVersionNodes.right().value()
- * != TitanOperationStatus.NOT_FOUND) { return
- * Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus
- * (lastVersionNodes.right().value())); } List<ProductMetadataData>
- * notCertifiedHighest = (lastVersionNodes.isLeft() ?
- * lastVersionNodes.left().value() : new
- * ArrayList<ProductMetadataData>());
+ * propertiesToMatch.put(GraphPropertiesDictionary.STATE.getProperty (), LifecycleStateEnum.CERTIFIED.name()); Either<List<ProductMetadataData>, TitanOperationStatus> lastVersionNodes = getLastVersion(NodeTypeEnum.Product,
+ * propertiesToMatch, ProductMetadataData.class); if (lastVersionNodes.isRight() && lastVersionNodes.right().value() != TitanOperationStatus.NOT_FOUND) { return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus
+ * (lastVersionNodes.right().value())); } List<ProductMetadataData> notCertifiedHighest = (lastVersionNodes.isLeft() ? lastVersionNodes.left().value() : new ArrayList<ProductMetadataData>());
*
- * propertiesToMatch.put(GraphPropertiesDictionary.
- * IS_HIGHEST_VERSION.getProperty(), true);
- * Either<List<ProductMetadataData>, TitanOperationStatus>
- * componentsNodes =
- * titanGenericDao.getByCriteria(NodeTypeEnum.Product,
- * propertiesToMatch, ProductMetadataData.class); if
- * (componentsNodes.isRight() && componentsNodes.right().value() !=
- * TitanOperationStatus.NOT_FOUND) { return
- * Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus
- * (componentsNodes.right().value())); } List<ProductMetadataData>
- * certifiedHighest = (componentsNodes.isLeft() ?
- * componentsNodes.left().value() : new
- * ArrayList<ProductMetadataData>()); Set<String> names = new
- * HashSet<String>(); for (ProductMetadataData data :
- * notCertifiedHighest) { String name =
- * data.getMetadataDataDefinition().getName(); names.add(name); }
+ * propertiesToMatch.put(GraphPropertiesDictionary. IS_HIGHEST_VERSION.getProperty(), true); Either<List<ProductMetadataData>, TitanOperationStatus> componentsNodes = titanGenericDao.getByCriteria(NodeTypeEnum.Product, propertiesToMatch,
+ * ProductMetadataData.class); if (componentsNodes.isRight() && componentsNodes.right().value() != TitanOperationStatus.NOT_FOUND) { return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus
+ * (componentsNodes.right().value())); } List<ProductMetadataData> certifiedHighest = (componentsNodes.isLeft() ? componentsNodes.left().value() : new ArrayList<ProductMetadataData>()); Set<String> names = new HashSet<String>(); for
+ * (ProductMetadataData data : notCertifiedHighest) { String name = data.getMetadataDataDefinition().getName(); names.add(name); }
*
- * for (ProductMetadataData data : certifiedHighest) { String
- * productName = data.getMetadataDataDefinition().getName(); if
- * (!names.contains(productName)) { notCertifiedHighest.add(data); }
- * }
+ * for (ProductMetadataData data : certifiedHighest) { String productName = data.getMetadataDataDefinition().getName(); if (!names.contains(productName)) { notCertifiedHighest.add(data); } }
*/
- Either<List<ProductMetadataData>, TitanOperationStatus> listOfHighestComponents = this
- .getListOfHighestComponents(NodeTypeEnum.Product, ProductMetadataData.class);
- if (listOfHighestComponents.isRight()
- && listOfHighestComponents.right().value() != TitanOperationStatus.NOT_FOUND) {
- return Either.right(
- DaoStatusConverter.convertTitanStatusToStorageStatus(listOfHighestComponents.right().value()));
+ Either<List<ProductMetadataData>, TitanOperationStatus> listOfHighestComponents = this.getListOfHighestComponents(NodeTypeEnum.Product, ProductMetadataData.class);
+ if (listOfHighestComponents.isRight() && listOfHighestComponents.right().value() != TitanOperationStatus.NOT_FOUND) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(listOfHighestComponents.right().value()));
}
List<ProductMetadataData> notCertifiedHighest = listOfHighestComponents.left().value();
@@ -282,42 +243,30 @@ public class ProductOperation extends ComponentOperation implements IProductOper
// fetch from cache
long startFetchAllFromCache = System.currentTimeMillis();
- Map<String, Long> components = notCertifiedHighest.stream()
- .collect(Collectors.toMap(p -> p.getMetadataDataDefinition().getUniqueId(),
- p -> p.getMetadataDataDefinition().getLastUpdateDate()));
+ Map<String, Long> components = notCertifiedHighest.stream().collect(Collectors.toMap(p -> p.getMetadataDataDefinition().getUniqueId(), p -> p.getMetadataDataDefinition().getLastUpdateDate()));
- Either<ImmutablePair<List<Component>, Set<String>>, ActionStatus> componentsFromCacheForCatalog = this
- .getComponentsFromCacheForCatalog(components, ComponentTypeEnum.PRODUCT);
+ Either<ImmutablePair<List<Component>, Set<String>>, ActionStatus> componentsFromCacheForCatalog = this.getComponentsFromCacheForCatalog(components, ComponentTypeEnum.PRODUCT);
if (componentsFromCacheForCatalog.isLeft()) {
- ImmutablePair<List<Component>, Set<String>> immutablePair = componentsFromCacheForCatalog.left()
- .value();
+ ImmutablePair<List<Component>, Set<String>> immutablePair = componentsFromCacheForCatalog.left().value();
List<Component> list = immutablePair.getLeft();
if (list != null) {
for (Component component : list) {
result.add((Product) component);
}
- List<String> addedUids = list.stream()
- .map(p -> p.getComponentMetadataDefinition().getMetadataDataDefinition().getUniqueId())
- .collect(Collectors.toList());
- notCertifiedHighest = notCertifiedHighest.stream()
- .filter(p -> false == addedUids.contains(p.getMetadataDataDefinition().getUniqueId()))
- .collect(Collectors.toList());
+ List<String> addedUids = list.stream().map(p -> p.getComponentMetadataDefinition().getMetadataDataDefinition().getUniqueId()).collect(Collectors.toList());
+ notCertifiedHighest = notCertifiedHighest.stream().filter(p -> false == addedUids.contains(p.getMetadataDataDefinition().getUniqueId())).collect(Collectors.toList());
}
}
long endFetchAllFromCache = System.currentTimeMillis();
- log.debug("Fetch all catalog products metadata from cache took {} ms",
- (endFetchAllFromCache - startFetchAllFromCache));
+ log.debug("Fetch all catalog products metadata from cache took {} ms", (endFetchAllFromCache - startFetchAllFromCache));
log.debug("The number of products added to catalog from cache is {}", result.size());
- log.debug("The number of products needed to be fetch as light component is {}",
- notCertifiedHighest.size());
+ log.debug("The number of products needed to be fetch as light component is {}", notCertifiedHighest.size());
for (ProductMetadataData data : notCertifiedHighest) {
- Either<Product, StorageOperationStatus> component = getLightComponent(
- data.getMetadataDataDefinition().getUniqueId(), inTransaction);
+ Either<Product, StorageOperationStatus> component = getLightComponent(data.getMetadataDataDefinition().getUniqueId(), inTransaction);
if (component.isRight()) {
- log.debug("Failed to get product for id = {}, error : {}. skip product", data.getUniqueId(),
- component.right().value());
+ log.debug("Failed to get product for id = {}, error : {}. skip product", data.getUniqueId(), component.right().value());
} else {
// get all versions
Product product = component.left().value();
@@ -332,7 +281,7 @@ public class ProductOperation extends ComponentOperation implements IProductOper
if (false == inTransaction) {
titanGenericDao.commit();
}
- log.debug("Fetch all catalog products took {} ms", (System.currentTimeMillis() - start));
+ log.debug("Fetch all catalog products took {} ms", System.currentTimeMillis() - start);
}
}
@@ -383,34 +332,29 @@ public class ProductOperation extends ComponentOperation implements IProductOper
}
log.trace("Finding groupings for product {}", uniqueId);
- Either<List<GroupingData>, StorageOperationStatus> findGroupingsForComponent = findGroupingsForComponent(
- NodeTypeEnum.ProductGrouping, product);
+ Either<List<GroupingData>, StorageOperationStatus> findGroupingsForComponent = findGroupingsForComponent(NodeTypeEnum.ProductGrouping, product);
if (findGroupingsForComponent.isRight()) {
return Either.right(findGroupingsForComponent.right().value());
}
List<GroupingData> groupingDataToAssociate = findGroupingsForComponent.left().value();
log.debug("try to create product node on graph for id {}", uniqueId);
- Either<ProductMetadataData, TitanOperationStatus> createNode = titanGenericDao.createNode(productData,
- ProductMetadataData.class);
+ Either<ProductMetadataData, TitanOperationStatus> createNode = titanGenericDao.createNode(productData, ProductMetadataData.class);
if (createNode.isRight()) {
TitanOperationStatus status = createNode.right().value();
- log.error("Error returned after creating product data node {}. Status returned is {}", productData,
- status);
+ log.error("Error returned after creating product data node {}. Status returned is {}", productData, status);
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
return result;
}
log.debug("product node created on graph for id {}", productData.getUniqueId());
- TitanOperationStatus associateMetadata = associateMetadataToComponent(productData, creatorUserData,
- updaterUserData, null, null);
+ TitanOperationStatus associateMetadata = associateMetadataToComponent(productData, creatorUserData, updaterUserData, null, null);
if (associateMetadata != TitanOperationStatus.OK) {
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(associateMetadata));
return result;
}
- TitanOperationStatus associateCategories = associateCategoriesToProduct(productData,
- groupingDataToAssociate);
+ TitanOperationStatus associateCategories = associateCategoriesToProduct(productData, groupingDataToAssociate);
if (associateCategories != TitanOperationStatus.OK) {
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(associateCategories));
return result;
@@ -442,14 +386,11 @@ public class ProductOperation extends ComponentOperation implements IProductOper
}
}
- private TitanOperationStatus associateCategoriesToProduct(ProductMetadataData productData,
- List<GroupingData> groupingDataToAssociate) {
+ private TitanOperationStatus associateCategoriesToProduct(ProductMetadataData productData, List<GroupingData> groupingDataToAssociate) {
for (GroupingData groupingData : groupingDataToAssociate) {
GraphEdgeLabels groupingLabel = GraphEdgeLabels.CATEGORIZED_TO;
- Either<GraphRelation, TitanOperationStatus> result = titanGenericDao.createRelation(productData,
- groupingData, groupingLabel, null);
- log.debug("After associating grouping {} to product {}. Edge type is {}", groupingData, productData,
- groupingLabel);
+ Either<GraphRelation, TitanOperationStatus> result = titanGenericDao.createRelation(productData, groupingData, groupingLabel, null);
+ log.debug("After associating grouping {} to product {}. Edge type is {}", groupingData, productData, groupingLabel);
if (result.isRight()) {
return result.right().value();
}
@@ -458,14 +399,11 @@ public class ProductOperation extends ComponentOperation implements IProductOper
return TitanOperationStatus.OK;
}
- private TitanOperationStatus dissociateCategoriesFromProduct(ProductMetadataData productData,
- List<GroupingData> groupingDataToDissociate) {
+ private TitanOperationStatus dissociateCategoriesFromProduct(ProductMetadataData productData, List<GroupingData> groupingDataToDissociate) {
for (GroupingData groupingData : groupingDataToDissociate) {
GraphEdgeLabels groupingLabel = GraphEdgeLabels.CATEGORIZED_TO;
- Either<GraphRelation, TitanOperationStatus> result = titanGenericDao.deleteRelation(productData,
- groupingData, groupingLabel);
- log.debug("After dissociating grouping {} from product {}. Edge type is {}", groupingData, productData,
- groupingLabel);
+ Either<GraphRelation, TitanOperationStatus> result = titanGenericDao.deleteRelation(productData, groupingData, groupingLabel);
+ log.debug("After dissociating grouping {} from product {}. Edge type is {}", groupingData, productData, groupingLabel);
if (result.isRight()) {
return result.right().value();
}
@@ -479,8 +417,7 @@ public class ProductOperation extends ComponentOperation implements IProductOper
return getProduct(uniqueId, componentParametersView, inTransaction);
}
- private Either<Product, StorageOperationStatus> getProduct(String uniqueId,
- ComponentParametersView componentParametersView, boolean inTransaction) {
+ private Either<Product, StorageOperationStatus> getProduct(String uniqueId, ComponentParametersView componentParametersView, boolean inTransaction) {
Product product = null;
Either<Product, StorageOperationStatus> result = null;
try {
@@ -488,8 +425,7 @@ public class ProductOperation extends ComponentOperation implements IProductOper
NodeTypeEnum productNodeType = NodeTypeEnum.Product;
NodeTypeEnum compInstNodeType = NodeTypeEnum.Service;
- Either<ProductMetadataData, StorageOperationStatus> getComponentByLabel = getComponentByLabelAndId(uniqueId,
- productNodeType, ProductMetadataData.class);
+ Either<ProductMetadataData, StorageOperationStatus> getComponentByLabel = getComponentByLabelAndId(uniqueId, productNodeType, ProductMetadataData.class);
if (getComponentByLabel.isRight()) {
result = Either.right(getComponentByLabel.right().value());
return result;
@@ -499,12 +435,10 @@ public class ProductOperation extends ComponentOperation implements IProductOper
// Try to fetch resource from the cache. The resource will be
// fetched only if the time on the cache equals to
// the time on the graph.
- Either<Product, ActionStatus> componentFromCacheIfUpToDate = this.getComponentFromCacheIfUpToDate(uniqueId,
- productData, componentParametersView, Product.class, ComponentTypeEnum.PRODUCT);
+ Either<Product, ActionStatus> componentFromCacheIfUpToDate = this.getComponentFromCacheIfUpToDate(uniqueId, productData, componentParametersView, Product.class, ComponentTypeEnum.PRODUCT);
if (componentFromCacheIfUpToDate.isLeft()) {
Product cachedProduct = componentFromCacheIfUpToDate.left().value();
- log.debug("Product {} with uid {} was fetched from cache.", cachedProduct.getName(),
- cachedProduct.getUniqueId());
+ log.debug("Product {} with uid {} was fetched from cache.", cachedProduct.getName(), cachedProduct.getUniqueId());
return Either.left(cachedProduct);
}
@@ -533,9 +467,7 @@ public class ProductOperation extends ComponentOperation implements IProductOper
}
}
- if (false == componentParametersView.isIgnoreComponentInstances()
- || false == componentParametersView.isIgnoreComponentInstancesProperties()
- || false == componentParametersView.isIgnoreCapabilities()
+ if (false == componentParametersView.isIgnoreComponentInstances() || false == componentParametersView.isIgnoreComponentInstancesProperties() || false == componentParametersView.isIgnoreCapabilities()
|| false == componentParametersView.isIgnoreRequirements()) {
status = setComponentInstancesFromGraph(uniqueId, product, productNodeType, compInstNodeType);
if (status != TitanOperationStatus.OK) {
@@ -545,7 +477,7 @@ public class ProductOperation extends ComponentOperation implements IProductOper
}
}
if (false == componentParametersView.isIgnoreComponentInstancesProperties()) {
- status = setComponentInstancesPropertiesFromGraph(uniqueId, product);
+ status = setComponentInstancesPropertiesFromGraph(product);
if (status != TitanOperationStatus.OK) {
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
return result;
@@ -683,8 +615,7 @@ public class ProductOperation extends ComponentOperation implements IProductOper
// }
private TitanOperationStatus setAllVersions(Product product) {
- Either<Map<String, String>, TitanOperationStatus> res = getVersionList(NodeTypeEnum.Product,
- product.getVersion(), product, ProductMetadataData.class);
+ Either<Map<String, String>, TitanOperationStatus> res = getVersionList(NodeTypeEnum.Product, product.getVersion(), product, ProductMetadataData.class);
if (res.isRight()) {
return res.right().value();
}
@@ -692,8 +623,7 @@ public class ProductOperation extends ComponentOperation implements IProductOper
return TitanOperationStatus.OK;
}
- private Either<Product, StorageOperationStatus> sendError(TitanOperationStatus status,
- StorageOperationStatus statusIfNotFound) {
+ private Either<Product, StorageOperationStatus> sendError(TitanOperationStatus status, StorageOperationStatus statusIfNotFound) {
Either<Product, StorageOperationStatus> result;
if (status == TitanOperationStatus.NOT_FOUND) {
result = Either.right(statusIfNotFound);
@@ -708,9 +638,8 @@ public class ProductOperation extends ComponentOperation implements IProductOper
TitanOperationStatus setComponentCategoriesFromGraph(Component component) {
Product product = (Product) component;
// Building the cat->subcat->grouping triples
- Either<List<ImmutablePair<GroupingData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao
- .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Product), product.getUniqueId(),
- GraphEdgeLabels.CATEGORIZED_TO, NodeTypeEnum.ProductGrouping, GroupingData.class);
+ Either<List<ImmutablePair<GroupingData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Product), product.getUniqueId(), GraphEdgeLabels.CATEGORIZED_TO,
+ NodeTypeEnum.ProductGrouping, GroupingData.class);
if (childrenNodes.isRight()) {
if (childrenNodes.right().value() != TitanOperationStatus.NOT_FOUND) {
log.debug("Error when finding groupings for this product, error {}", childrenNodes.right().value());
@@ -725,19 +654,15 @@ public class ProductOperation extends ComponentOperation implements IProductOper
List<ImmutablePair<GroupingData, GraphEdge>> valueList = childrenNodes.left().value();
for (ImmutablePair<GroupingData, GraphEdge> groupPair : valueList) {
GroupingData groupingData = groupPair.getLeft();
- Either<ImmutablePair<SubCategoryData, GraphEdge>, TitanOperationStatus> parentSubCat = titanGenericDao
- .getParentNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ProductGrouping),
- (String) groupingData.getUniqueId(), GraphEdgeLabels.GROUPING,
- NodeTypeEnum.ProductSubcategory, SubCategoryData.class);
+ Either<ImmutablePair<SubCategoryData, GraphEdge>, TitanOperationStatus> parentSubCat = titanGenericDao.getParentNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ProductGrouping), (String) groupingData.getUniqueId(),
+ GraphEdgeLabels.GROUPING, NodeTypeEnum.ProductSubcategory, SubCategoryData.class);
if (parentSubCat.isRight()) {
log.debug("Cannot find subcategory for grouping {}", groupingData.getUniqueId());
return parentSubCat.right().value();
}
SubCategoryData subCatData = parentSubCat.left().value().getLeft();
- Either<ImmutablePair<CategoryData, GraphEdge>, TitanOperationStatus> parentCat = titanGenericDao
- .getParentNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ProductSubcategory),
- (String) subCatData.getUniqueId(), GraphEdgeLabels.SUB_CATEGORY,
- NodeTypeEnum.ProductCategory, CategoryData.class);
+ Either<ImmutablePair<CategoryData, GraphEdge>, TitanOperationStatus> parentCat = titanGenericDao.getParentNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ProductSubcategory), (String) subCatData.getUniqueId(),
+ GraphEdgeLabels.SUB_CATEGORY, NodeTypeEnum.ProductCategory, CategoryData.class);
if (parentCat.isRight()) {
log.debug("Cannot find category for subcategory {}", subCatData.getUniqueId());
return parentCat.right().value();
@@ -752,11 +677,7 @@ public class ProductOperation extends ComponentOperation implements IProductOper
SubCategoryDefinition subDef = new SubCategoryDefinition(subDefinition);
GroupingDefinition groupingDef = new GroupingDefinition(groupingDefinition);
- if (log.isDebugEnabled()) {
- log.debug("Found category {} -> subcategory {} -> grouping {} for product {}",
- categoryDefinition.getUniqueId(), subCatData.getUniqueId(), groupingData.getUniqueId(),
- product.getUniqueId());
- }
+ log.debug("Found category {} -> subcategory {} -> grouping {} for product {}", categoryDefinition.getUniqueId(), subCatData.getUniqueId(), groupingData.getUniqueId(), product.getUniqueId());
Map<SubCategoryDefinition, List<GroupingDefinition>> subMap = categoriesDataStructure.get(categoryDef);
if (subMap == null) {
subMap = new HashMap<>();
@@ -773,14 +694,12 @@ public class ProductOperation extends ComponentOperation implements IProductOper
return TitanOperationStatus.OK;
}
- private void convertToCategoriesList(Product product,
- Map<CategoryDefinition, Map<SubCategoryDefinition, List<GroupingDefinition>>> categoriesDataStructure) {
+ private void convertToCategoriesList(Product product, Map<CategoryDefinition, Map<SubCategoryDefinition, List<GroupingDefinition>>> categoriesDataStructure) {
List<CategoryDefinition> categoryDataList = product.getCategories();
if (categoryDataList == null) {
categoryDataList = new ArrayList<CategoryDefinition>();
}
- for (Entry<CategoryDefinition, Map<SubCategoryDefinition, List<GroupingDefinition>>> triple : categoriesDataStructure
- .entrySet()) {
+ for (Entry<CategoryDefinition, Map<SubCategoryDefinition, List<GroupingDefinition>>> triple : categoriesDataStructure.entrySet()) {
CategoryDefinition categoryDefinition = triple.getKey();
List<SubCategoryDefinition> subList = new ArrayList<>();
categoryDefinition.setSubcategories(subList);
@@ -795,13 +714,11 @@ public class ProductOperation extends ComponentOperation implements IProductOper
categoryDataList.add(categoryDefinition);
}
product.setCategories(categoryDataList);
- log.debug("Fetched categories for product {}, categories: {}", product.getUniqueId(),
- Arrays.toString(categoryDataList.toArray()));
+ log.debug("Fetched categories for product {}, categories: {}", product.getUniqueId(), Arrays.toString(categoryDataList.toArray()));
}
private ProductMetadataData getProductMetadataDataFromProduct(Product product) {
- ProductMetadataData productMetadata = new ProductMetadataData(
- (ProductMetadataDataDefinition) product.getComponentMetadataDefinition().getMetadataDataDefinition());
+ ProductMetadataData productMetadata = new ProductMetadataData((ProductMetadataDataDefinition) product.getComponentMetadataDefinition().getMetadataDataDefinition());
return productMetadata;
}
@@ -820,14 +737,11 @@ public class ProductOperation extends ComponentOperation implements IProductOper
@SuppressWarnings("unchecked")
@Override
- public <T> Either<T, StorageOperationStatus> cloneComponent(T other, String version,
- LifecycleStateEnum targetLifecycle, boolean inTransaction) {
- return (Either<T, StorageOperationStatus>) cloneProduct((Product) other, version, targetLifecycle,
- inTransaction);
+ public <T> Either<T, StorageOperationStatus> cloneComponent(T other, String version, LifecycleStateEnum targetLifecycle, boolean inTransaction) {
+ return (Either<T, StorageOperationStatus>) cloneProduct((Product) other, version, targetLifecycle, inTransaction);
}
- private Either<Product, StorageOperationStatus> cloneProduct(Product other, String version,
- LifecycleStateEnum targetLifecycle, boolean inTransaction) {
+ private Either<Product, StorageOperationStatus> cloneProduct(Product other, String version, LifecycleStateEnum targetLifecycle, boolean inTransaction) {
Either<Product, StorageOperationStatus> result = null;
try {
@@ -835,12 +749,10 @@ public class ProductOperation extends ComponentOperation implements IProductOper
other.setVersion(version);
other.setUniqueId(null);
- Either<Integer, StorageOperationStatus> counterStatus = getComponentInstanceCoutner(origProductId,
- NodeTypeEnum.Product);
+ Either<Integer, StorageOperationStatus> counterStatus = getComponentInstanceCoutner(origProductId, NodeTypeEnum.Product);
if (counterStatus.isRight()) {
StorageOperationStatus status = counterStatus.right().value();
- log.error("failed to get resource instance counter on product {}. status={}", origProductId,
- counterStatus);
+ log.error("failed to get resource instance counter on product {}. status={}", origProductId, counterStatus);
result = Either.right(status);
return result;
}
@@ -861,12 +773,10 @@ public class ProductOperation extends ComponentOperation implements IProductOper
return result;
}
- Either<Integer, StorageOperationStatus> setResourceInstanceCounter = setComponentInstanceCounter(
- product.getUniqueId(), NodeTypeEnum.Product, counterStatus.left().value(), inTransaction);
+ Either<Integer, StorageOperationStatus> setResourceInstanceCounter = setComponentInstanceCounter(product.getUniqueId(), NodeTypeEnum.Product, counterStatus.left().value(), inTransaction);
if (setResourceInstanceCounter.isRight()) {
StorageOperationStatus status = setResourceInstanceCounter.right().value();
- log.error("failed to set resource instance counter on product {}. status={}", product.getUniqueId(),
- setResourceInstanceCounter);
+ log.error("failed to set resource instance counter on product {}. status={}", product.getUniqueId(), setResourceInstanceCounter);
result = Either.right(status);
return result;
}
@@ -896,8 +806,7 @@ public class ProductOperation extends ComponentOperation implements IProductOper
}
}
- private Either<Product, StorageOperationStatus> getByNamesAndVersion(String nameKey, String nameValue,
- String version, Map<String, Object> additionalParams, boolean inTransaction) {
+ private Either<Product, StorageOperationStatus> getByNamesAndVersion(String nameKey, String nameValue, String version, Map<String, Object> additionalParams, boolean inTransaction) {
Map<String, Object> props = new HashMap<String, Object>();
props.put(nameKey, nameValue);
props.put(GraphPropertiesDictionary.VERSION.getProperty(), version);
@@ -906,8 +815,7 @@ public class ProductOperation extends ComponentOperation implements IProductOper
props.putAll(additionalParams);
}
- Either<List<ProductMetadataData>, TitanOperationStatus> byCriteria = titanGenericDao
- .getByCriteria(NodeTypeEnum.Product, props, ProductMetadataData.class);
+ Either<List<ProductMetadataData>, TitanOperationStatus> byCriteria = titanGenericDao.getByCriteria(NodeTypeEnum.Product, props, ProductMetadataData.class);
if (byCriteria.isRight()) {
return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(byCriteria.right().value()));
@@ -919,11 +827,9 @@ public class ProductOperation extends ComponentOperation implements IProductOper
return Either.right(StorageOperationStatus.GENERAL_ERROR);
}
ProductMetadataData productData = dataList.get(0);
- Either<Product, StorageOperationStatus> product = getProduct(
- productData.getMetadataDataDefinition().getUniqueId(), inTransaction);
+ Either<Product, StorageOperationStatus> product = getProduct(productData.getMetadataDataDefinition().getUniqueId(), inTransaction);
if (product.isRight()) {
- log.debug("Failed to fetch product, name {} id {}", productData.getMetadataDataDefinition().getName(),
- productData.getMetadataDataDefinition().getUniqueId());
+ log.debug("Failed to fetch product, name {} id {}", productData.getMetadataDataDefinition().getName(), productData.getMetadataDataDefinition().getUniqueId());
}
return product;
}
@@ -936,49 +842,42 @@ public class ProductOperation extends ComponentOperation implements IProductOper
}
@Override
- protected <T extends org.openecomp.sdc.be.model.Component> StorageOperationStatus updateDerived(
- org.openecomp.sdc.be.model.Component component, org.openecomp.sdc.be.model.Component currentComponent,
- ComponentMetadataData componentData, Class<T> clazz) {
+ protected <T extends org.openecomp.sdc.be.model.Component> StorageOperationStatus updateDerived(org.openecomp.sdc.be.model.Component component, org.openecomp.sdc.be.model.Component currentComponent, ComponentMetadataData componentData,
+ Class<T> clazz) {
log.debug("Derived class isn't supported for product");
return StorageOperationStatus.OK;
}
@Override
- public Either<Integer, StorageOperationStatus> increaseAndGetComponentInstanceCounter(String componentId,
- boolean inTransaction) {
+ public Either<Integer, StorageOperationStatus> increaseAndGetComponentInstanceCounter(String componentId, boolean inTransaction) {
return increaseAndGetComponentInstanceCounter(componentId, NodeTypeEnum.Product, inTransaction);
}
@Override
- protected StorageOperationStatus validateCategories(Component currentComponent, Component component,
- ComponentMetadataData componentData, NodeTypeEnum type) {
+ protected StorageOperationStatus validateCategories(Component currentComponent, Component component, ComponentMetadataData componentData, NodeTypeEnum type) {
// As agreed with Ella, update categories - delete old and create new
StorageOperationStatus status = StorageOperationStatus.OK;
List<CategoryDefinition> newcategories = component.getCategories();
List<CategoryDefinition> currentcategories = currentComponent.getCategories();
if (newcategories != null) {
if (currentcategories != null && !currentcategories.isEmpty()) {
- Either<List<GroupingData>, StorageOperationStatus> findGroupingsForComponent = findGroupingsForComponent(
- NodeTypeEnum.ProductGrouping, currentComponent);
+ Either<List<GroupingData>, StorageOperationStatus> findGroupingsForComponent = findGroupingsForComponent(NodeTypeEnum.ProductGrouping, currentComponent);
if (findGroupingsForComponent.isRight()) {
status = findGroupingsForComponent.right().value();
}
List<GroupingData> groupingDataToDissociate = findGroupingsForComponent.left().value();
- TitanOperationStatus titanStatus = dissociateCategoriesFromProduct((ProductMetadataData) componentData,
- groupingDataToDissociate);
+ TitanOperationStatus titanStatus = dissociateCategoriesFromProduct((ProductMetadataData) componentData, groupingDataToDissociate);
if (titanStatus != TitanOperationStatus.OK) {
status = DaoStatusConverter.convertTitanStatusToStorageStatus(titanStatus);
}
}
if (!newcategories.isEmpty()) {
- Either<List<GroupingData>, StorageOperationStatus> findGroupingsForComponent = findGroupingsForComponent(
- NodeTypeEnum.ProductGrouping, component);
+ Either<List<GroupingData>, StorageOperationStatus> findGroupingsForComponent = findGroupingsForComponent(NodeTypeEnum.ProductGrouping, component);
if (findGroupingsForComponent.isRight()) {
status = findGroupingsForComponent.right().value();
}
List<GroupingData> groupingDataToAssociate = findGroupingsForComponent.left().value();
- TitanOperationStatus titanStatus = associateCategoriesToProduct((ProductMetadataData) componentData,
- groupingDataToAssociate);
+ TitanOperationStatus titanStatus = associateCategoriesToProduct((ProductMetadataData) componentData, groupingDataToAssociate);
if (titanStatus != TitanOperationStatus.OK) {
status = DaoStatusConverter.convertTitanStatusToStorageStatus(titanStatus);
}
@@ -987,11 +886,10 @@ public class ProductOperation extends ComponentOperation implements IProductOper
return status;
}
+ @Override
@SuppressWarnings("unchecked")
- public Either<List<Product>, StorageOperationStatus> getFollowed(String userId,
- Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates, boolean inTransaction) {
- return (Either<List<Product>, StorageOperationStatus>) (Either<?, StorageOperationStatus>) getFollowedComponent(
- userId, lifecycleStates, lastStateStates, inTransaction, titanGenericDao, NodeTypeEnum.Product);
+ public Either<List<Product>, StorageOperationStatus> getFollowed(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates, boolean inTransaction) {
+ return (Either<List<Product>, StorageOperationStatus>) (Either<?, StorageOperationStatus>) getFollowedComponent(userId, lifecycleStates, lastStateStates, inTransaction, titanGenericDao, NodeTypeEnum.Product);
}
@Override
@@ -1011,11 +909,9 @@ public class ProductOperation extends ComponentOperation implements IProductOper
@SuppressWarnings("unchecked")
@Override
- public Either<Component, StorageOperationStatus> markComponentToDelete(Component componentToDelete,
- boolean inTransaction) {
+ public Either<Component, StorageOperationStatus> markComponentToDelete(Component componentToDelete, boolean inTransaction) {
// markComponentToDelete is not defined yet for products
- return (Either<Component, StorageOperationStatus>) (Either<?, StorageOperationStatus>) deleteProduct(
- componentToDelete.getUniqueId(), inTransaction);
+ return (Either<Component, StorageOperationStatus>) (Either<?, StorageOperationStatus>) deleteProduct(componentToDelete.getUniqueId(), inTransaction);
}
@Override
@@ -1040,28 +936,22 @@ public class ProductOperation extends ComponentOperation implements IProductOper
return Either.left(new ArrayList<>());
}
- public Either<Product, StorageOperationStatus> getProductByNameAndVersion(String productName, String productVersion,
- boolean inTransaction) {
- return getByNamesAndVersion(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(),
- ValidationUtils.normaliseComponentName(productName), productVersion, null, inTransaction);
+ public Either<Product, StorageOperationStatus> getProductByNameAndVersion(String productName, String productVersion, boolean inTransaction) {
+ return getByNamesAndVersion(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(), ValidationUtils.normaliseComponentName(productName), productVersion, null, inTransaction);
}
@SuppressWarnings("unchecked")
@Override
- public <T> Either<T, StorageOperationStatus> getComponent(String id,
- ComponentParametersView componentParametersView, boolean inTransaction) {
+ public <T> Either<T, StorageOperationStatus> getComponent(String id, ComponentParametersView componentParametersView, boolean inTransaction) {
return (Either<T, StorageOperationStatus>) getProduct(id, false);
}
- public Either<Product, StorageOperationStatus> updateProduct(Product product, boolean inTransaction,
- ComponentParametersView filterResultView) {
- return (Either<Product, StorageOperationStatus>) updateComponentFilterResult(product, inTransaction,
- titanGenericDao, product.getClass(), NodeTypeEnum.Service, filterResultView);
+ public Either<Product, StorageOperationStatus> updateProduct(Product product, boolean inTransaction, ComponentParametersView filterResultView) {
+ return (Either<Product, StorageOperationStatus>) updateComponentFilterResult(product, inTransaction, titanGenericDao, product.getClass(), NodeTypeEnum.Service, filterResultView);
}
@Override
- protected <T> Either<T, StorageOperationStatus> updateComponentFilterResult(T component, boolean inTransaction,
- ComponentParametersView filterResultView) {
+ protected <T> Either<T, StorageOperationStatus> updateComponentFilterResult(T component, boolean inTransaction, ComponentParametersView filterResultView) {
return (Either<T, StorageOperationStatus>) updateProduct((Product) component, inTransaction, filterResultView);
}
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/PropertyOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/PropertyOperation.java
index 7d775b3b3d..9b900b0ae2 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
@@ -32,14 +32,11 @@ import java.util.Map.Entry;
import java.util.Set;
import java.util.StringJoiner;
import java.util.function.Consumer;
-import java.util.function.Supplier;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
-import com.thinkaurelius.titan.core.TitanTransaction;
-import com.thinkaurelius.titan.core.TitanVertex;
-
+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;
@@ -60,7 +57,6 @@ import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.PropertyRule;
import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.model.ComponentInstanceInput;
import org.openecomp.sdc.be.model.ComponentInstanceProperty;
import org.openecomp.sdc.be.model.DataTypeDefinition;
import org.openecomp.sdc.be.model.IComplexDefaultValue;
@@ -69,7 +65,6 @@ import org.openecomp.sdc.be.model.PropertyDefinition;
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;
-import org.openecomp.sdc.be.model.tosca.ToscaType;
import org.openecomp.sdc.be.model.tosca.constraints.ConstraintType;
import org.openecomp.sdc.be.model.tosca.constraints.GreaterOrEqualConstraint;
import org.openecomp.sdc.be.model.tosca.constraints.GreaterThanConstraint;
@@ -79,22 +74,18 @@ import org.openecomp.sdc.be.model.tosca.constraints.LessThanConstraint;
import org.openecomp.sdc.be.model.tosca.constraints.MinLengthConstraint;
import org.openecomp.sdc.be.model.tosca.constraints.ValidValuesConstraint;
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.ComponentInstanceData;
import org.openecomp.sdc.be.resources.data.DataTypeData;
-import org.openecomp.sdc.be.resources.data.InputValueData;
import org.openecomp.sdc.be.resources.data.PropertyData;
import org.openecomp.sdc.be.resources.data.PropertyValueData;
import org.openecomp.sdc.be.resources.data.ResourceMetadataData;
import org.openecomp.sdc.be.resources.data.UniqueIdData;
-import org.openecomp.sdc.common.api.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
@@ -104,13 +95,15 @@ import com.google.gson.JsonParseException;
import com.google.gson.JsonParser;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
-import com.google.gson.reflect.TypeToken;
+import com.thinkaurelius.titan.core.TitanVertex;
import fj.data.Either;
@Component("property-operation")
public class PropertyOperation extends AbstractOperation implements IPropertyOperation {
+ private TitanGenericDao titanGenericDao;
+
public static void main(String[] args) {
List<Pattern> buildFunctionPatterns = buildFunctionPatterns();
@@ -126,10 +119,9 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
}
- public static final String PROPERTY = "property";
-
- public PropertyOperation() {
+ public PropertyOperation(@Qualifier("titan-generic-dao") TitanGenericDao titanGenericDao) {
super();
+ this.titanGenericDao = titanGenericDao;
}
private static Logger log = LoggerFactory.getLogger(PropertyOperation.class.getName());
@@ -165,7 +157,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
@Override
public Either<PropertyDefinition, StorageOperationStatus> getPropertyOfResource(String propertyName, String resourceId) {
- String propertyId = UniqueIdBuilder.buildPropertyUniqueId(resourceId, propertyName);
+ String propertyId = UniqueIdBuilder.buildComponentPropertyUniqueId(resourceId, propertyName);
Either<PropertyData, TitanOperationStatus> getResult = this.titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Property), propertyId, PropertyData.class);
if (getResult.isLeft()) {
@@ -173,7 +165,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
return Either.left(convertPropertyDataToPropertyDefinition(propertyData, propertyName, resourceId));
} else {
TitanOperationStatus titanStatus = getResult.right().value();
- log.debug("Node with id {} was not found in the graph. Status: {}", propertyId, titanStatus);
+ log.debug("Node with id {} was not found in the graph. status: {}", propertyId, titanStatus);
StorageOperationStatus storageOperationStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(titanStatus);
return Either.right(storageOperationStatus);
}
@@ -192,10 +184,12 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
*
* Either<PropertyData, TitanOperationStatus> status = addPropertyToGraph(propertyName, propertyDefinition, resourceId);
*
- * if (status.isRight()) { titanGenericDao.rollback(); log.error("Failed to add property " + propertyName + " to resource " + resourceId); return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status. right().value())); } else
+ * if (status.isRight()) { titanGenericDao.rollback();
+ * log.error("Failed to add property {} to resource {}, propertyName, resourceId);
+ * return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status. right().value())); } else
* { titanGenericDao.commit(); PropertyData propertyData = status.left().value();
*
- * PropertyDefinition propertyDefResult = convertPropertyDataToPropertyDefinition(propertyData, propertyName, resourceId); log.debug("The returned PropertyDefintion is {}", propertyDefinition); return Either.left(propertyDefResult); }
+ * PropertyDefinition propertyDefResult = convertPropertyDataToPropertyDefinition(propertyData, propertyName, resourceId); log.debug("The returned PropertyDefintion is " + propertyDefinition); return Either.left(propertyDefResult); }
*
*
* }
@@ -244,7 +238,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
PropertyDefinition propertyDefResult = new PropertyDefinition(propertyDataResult.getPropertyDataDefinition());
propertyDefResult.setConstraints(convertConstraints(propertyDataResult.getConstraints()));
propertyDefResult.setName(propertyName);
- propertyDefResult.setParentUniqueId(resourceId);
+// propertyDefResult.setParentUniqueId(resourceId);
return propertyDefResult;
}
@@ -545,7 +539,9 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
*
* ImmutablePair<JsonElement, Boolean> validateResult = dataTypeValidatorConverter.validateAndUpdate(value, dataTypeDefinition, allDataTypes);
*
- * if (validateResult.right.booleanValue() == false) { log.debug("The value {} of property from type {} is invalid", value, propertyType); return Either.right(false); }
+ * 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;
*
@@ -555,9 +551,9 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
*
* }
*
- * log.trace("After validating property type " + propertyType);
+ * log.trace("After validating property type {}", propertyType);
*
- * boolean isValidProperty = isValidValue(type, value, innerType); if (false == isValidProperty) { log.debug("The value {} of property from type {} is invalid", value, type); return Either.right(false); }
+ * boolean isValidProperty = isValidValue(type, value, innerType); if (false == isValidProperty) { log.debug("The value " + value + " of property from type " + type + " is invalid"); return Either.right(false); }
*
*
* Object convertedValue = value; if (false == isEmptyValue(value)) { PropertyValueConverter converter = type.getConverter(); convertedValue = converter.convert(value, null); }
@@ -572,7 +568,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
List<PropertyConstraint> constraints = propertyDefinition.getConstraints();
- propertyDefinition.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(resourceId, propertyName));
+ propertyDefinition.setUniqueId(UniqueIdBuilder.buildComponentPropertyUniqueId(resourceId, propertyName));
PropertyData propertyData = new PropertyData(propertyDefinition, convertConstraintsToString(constraints));
log.debug("Before adding property to graph {}", propertyData);
@@ -580,7 +576,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
log.debug("After adding property to graph {}", propertyData);
if (createNodeResult.isRight()) {
TitanOperationStatus operationStatus = createNodeResult.right().value();
- log.error("Failed to add property {} to graph. Status is {}", propertyName, operationStatus);
+ log.error("Failed to add property {} to graph. status is {}", propertyName, operationStatus);
return Either.right(operationStatus);
}
@@ -589,7 +585,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(resourceData, propertyData, GraphEdgeLabels.PROPERTY, props);
if (createRelResult.isRight()) {
TitanOperationStatus operationStatus = createNodeResult.right().value();
- log.error("Failed to associate resource {} to property {} in graph. Status is {}", resourceId, propertyName, operationStatus);
+ log.error("Failed to associate resource {} to property {} in graph. status is {}", resourceId, propertyName, operationStatus);
return Either.right(operationStatus);
}
@@ -601,7 +597,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
List<PropertyConstraint> constraints = propertyDefinition.getConstraints();
- propertyDefinition.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(resourceId, propertyName));
+ propertyDefinition.setUniqueId(UniqueIdBuilder.buildComponentPropertyUniqueId(resourceId, propertyName));
PropertyData propertyData = new PropertyData(propertyDefinition, convertConstraintsToString(constraints));
log.debug("Before adding property to graph {}", propertyData);
@@ -609,7 +605,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
log.debug("After adding property to graph {}", propertyData);
if (createNodeResult.isRight()) {
TitanOperationStatus operationStatus = createNodeResult.right().value();
- log.error("Failed to add property {} to graph. status is {}", propertyName, operationStatus);
+ log.error("Failed to add property {} to graph. status is ", propertyName, operationStatus);
return operationStatus;
}
@@ -731,7 +727,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
log.debug("After adding property to graph {}", propertyData);
if (createNodeResult.isRight()) {
TitanOperationStatus operationStatus = createNodeResult.right().value();
- log.error("Failed to add property {} to graph. Status is {}", propertyName, operationStatus);
+ log.error("Failed to add property {} to graph. status is {}", propertyName, operationStatus);
return Either.right(operationStatus);
}
@@ -739,11 +735,11 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
props.put(GraphPropertiesDictionary.NAME.getProperty(), propertyName);
UniqueIdData uniqueIdData = new UniqueIdData(nodeType, uniqueId);
- log.debug("Before associating {} to property {}.", uniqueIdData, propertyName);
+ log.debug("Before associating {} to property {}", uniqueIdData, propertyName);
Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(uniqueIdData, propertyData, GraphEdgeLabels.PROPERTY, props);
if (createRelResult.isRight()) {
TitanOperationStatus operationStatus = createNodeResult.right().value();
- log.error("Failed to associate resource {} to property {} in graph. Status is {}", uniqueId, propertyName, operationStatus);
+ log.error("Failed to associate resource {} to property {} in graph. status is {}", uniqueId, propertyName, operationStatus);
return Either.right(operationStatus);
}
@@ -830,7 +826,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
String propertyUid = propertyDefinition.getUniqueId();
Either<PropertyData, TitanOperationStatus> deletePropertyRes = deletePropertyFromGraph(propertyUid);
if (deletePropertyRes.isRight()) {
- log.error("Failed to delete property with id " + propertyUid);
+ log.error("Failed to delete property with id {}", propertyUid);
TitanOperationStatus status = deletePropertyRes.right().value();
if (status == TitanOperationStatus.NOT_FOUND) {
status = TitanOperationStatus.INVALID_ID;
@@ -887,8 +883,10 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
log.debug("Property {} is associated to node {}", propertyName, uniqueId);
PropertyData propertyData = immutablePair.getKey();
PropertyDefinition propertyDefinition = this.convertPropertyDataToPropertyDefinition(propertyData, propertyName, uniqueId);
-
- properties.add(propertyDefinition);
+ //Adds parent property to List if it hasn't been overrided in one of the children
+ if(!properties.stream().filter(p -> p.getName().equals(propertyDefinition.getName())).findAny().isPresent()){
+ properties.add(propertyDefinition);
+ }
if (log.isTraceEnabled())
log.trace("findPropertiesOfNode - property {} associated to node {}", propertyDefinition, uniqueId);
@@ -898,24 +896,28 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
return TitanOperationStatus.OK;
}
-
- public boolean isPropertyExist(List<PropertyDefinition> properties, String resourceUid, String propertyName) {
-
- if (properties == null) {
- return false;
- }
-
- for (PropertyDefinition propertyDefinition : properties) {
- String parentUniqueId = propertyDefinition.getParentUniqueId();
- String name = propertyDefinition.getName();
-
- if (parentUniqueId.equals(resourceUid) && name.equals(propertyName)) {
- return true;
+/**
+ * Checks existence of a property with the same name belonging to the same resource
+ * or existence of property with the same name and different type (including derived from hierarchy)
+ * @param properties
+ * @param resourceUid
+ * @param propertyName
+ * @param propertyType
+ * @return
+ */
+ public 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 false;
-
+ return result;
}
/**
@@ -947,7 +949,9 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
* "Failed to update property value on instance. Status is " + updatePropertyOfResourceInstance.right().value(), ErrorSeverity.ERROR); return Either.right(updatePropertyOfResourceInstance.right().value()); } return
* Either.left(updatePropertyOfResourceInstance.left().value()); }
*
- * if (isPropertyValueExists.getLeft() != TitanOperationStatus.NOT_FOUND) { log.debug("After finding property value of {} on component instance {}", propertyId, resourceInstanceId); return Either.right(isPropertyValueExists.getLeft()); }
+ * if (isPropertyValueExists.getLeft() != TitanOperationStatus.NOT_FOUND) {
+ * log.debug("After finding property value of {} on componenet instance {}", propertyId, resourceInstanceId);
+ * return Either.right(isPropertyValueExists.getLeft()); }
*
* String propertyType = propertyData.getPropertyDataDefinition().getType(); String value = resourceInstanceProperty.getValue(); Either<Object, Boolean> isValid = validateAndUpdatePropertyValue(propertyType, value);
*
@@ -961,7 +965,8 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
* logBeInvalidValueError("Add property value", pair.getLeft(), resourceInstanceProperty.getName(), propertyType); return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); } addRulesToNewPropertyValue(propertyValueData,
* resourceInstanceProperty, resourceInstanceId);
*
- * log.debug("Before adding property value to graph {}", propertyValueData); Either<PropertyValueData, TitanOperationStatus> createNodeResult = titanGenericDao .createNode(propertyValueData, PropertyValueData.class);
+ * log.debug("Before adding property value to graph {}", propertyValueData);
+ * Either<PropertyValueData, TitanOperationStatus> createNodeResult = titanGenericDao .createNode(propertyValueData, PropertyValueData.class);
* log.debug("After adding property value to graph {}", propertyValueData);
*
* Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao .createRelation(propertyValueData, propertyData, GraphEdgeLabels.PROPERTY_IMPL, null);
@@ -1108,7 +1113,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
* Either<Object, Boolean> isValid = validateAndUpdatePropertyValue(propertyType, value);
*
* String newValue = value; if (isValid.isRight()) { Boolean res = isValid.right().value(); if (res == false) { return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); } } else { Object object = isValid.left().value(); if (object != null) {
- * newValue = object.toString(); } } PropertyValueData propertyValueData = findPropertyValueRes.left().value(); log.debug("Going to update property value from {} to {}", propertyValueData.getValue(), newValue);
+ * newValue = object.toString(); } } PropertyValueData propertyValueData = findPropertyValueRes.left().value(); log.debug("Going to update property value from " + propertyValueData.getValue() + " to " + newValue);
* propertyValueData.setValue(newValue);
*
* ImmutablePair<String, Boolean> pair = validateAndUpdateRules(propertyType, resourceInstanceProperty.getRules()); if (pair.getRight() != null && pair.getRight() == false) { BeEcompErrorManager.getInstance().
@@ -1220,7 +1225,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
*
* ComponentInstanceProperty propertyValueResult = buildResourceInstanceProperty( propertyValueData, resourceInstanceProperty);
*
- * log.debug("The returned ResourceInstanceProperty is {}", propertyValueResult); result = Either.left(propertyValueResult); return result; } }
+ * log.debug("The returned ResourceInstanceProperty is {}", propertyValueResult); result = Either.left(propertyValueResult); return result; } }
*
* finally { if (false == inTransaction) { if (result == null || result.isRight()) { log.error("Going to execute rollback on graph."); titanGenericDao.rollback(); } else { log.debug("Going to execute commit on graph."); titanGenericDao.commit();
* } } }
@@ -1238,7 +1243,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
*
* ComponentInstanceProperty propertyValueResult = buildResourceInstanceProperty( propertyValueData, resourceInstanceProperty);
*
- * log.debug("The returned ResourceInstanceProperty is {}", propertyValueResult); result = Either.left(propertyValueResult); return result; } }
+ * log.debug("The returned ResourceInstanceProperty is {}", propertyValueResult); result = Either.left(propertyValueResult); return result; } }
*
* finally { if (false == inTransaction) { if (result == null || result.isRight()) { log.error("Going to execute rollback on graph."); titanGenericDao.rollback(); } else { log.debug("Going to execute commit on graph."); titanGenericDao.commit();
* } } }
@@ -1306,7 +1311,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
propertyValueResult.setUniqueId(resourceInstanceId);
propertyValueResult.setValue(propertyValueData.getValue());
- log.debug("The returned ResourceInstanceProperty is {}", propertyValueResult);
+ log.debug("The returned ResourceInstanceProperty is {}", propertyValueResult);
result = Either.left(propertyValueResult);
return result;
}
@@ -1425,7 +1430,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
if (innerToscaType == null) {
DataTypeDefinition dataTypeDefinition = dataTypes.get(innerType);
if (dataTypeDefinition == null) {
- log.debug("The inner type {} is not a data type", innerType);
+ log.debug("The inner type {} is not a data type.", innerType);
return new ImmutablePair<String, Boolean>(innerType, false);
} else {
log.debug("The inner type {} is a data type. Data type definition is {}", innerType, dataTypeDefinition);
@@ -1438,7 +1443,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
private boolean isValidComplexValue(DataTypeDefinition foundDt, String value, Map<String, DataTypeDefinition> dataTypes) {
/*
* Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypesRes = getAllDataTypes(); if (allDataTypesRes.isRight()) { TitanOperationStatus status = allDataTypesRes.right().value();
- * log.debug("Failed to fetch data types from graph. Status is {}", status); return false; }
+ * return false; }
*
* Map<String, DataTypeDefinition> allDataTypes = allDataTypesRes.left().value();
*/
@@ -1483,10 +1488,6 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
public Either<List<ComponentInstanceProperty>, TitanOperationStatus> getAllPropertiesOfResourceInstanceOnlyPropertyDefId(String resourceInstanceUid, NodeTypeEnum instanceNodeType) {
- // Either<ComponentInstanceData, TitanOperationStatus>
- // findResInstanceRes =
- // titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(instanceNodeType),
- // resourceInstanceUid, ComponentInstanceData.class);
Either<TitanVertex, TitanOperationStatus> findResInstanceRes = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(instanceNodeType), resourceInstanceUid);
if (findResInstanceRes.isRight()) {
@@ -1497,11 +1498,6 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
return Either.right(status);
}
- // Either<List<ImmutablePair<PropertyValueData, GraphEdge>>,
- // TitanOperationStatus> propertyImplNodes =
- // titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(instanceNodeType),
- // resourceInstanceUid, GraphEdgeLabels.PROPERTY_VALUE,
- // NodeTypeEnum.PropertyValue, PropertyValueData.class);
Either<List<ImmutablePair<TitanVertex, Edge>>, TitanOperationStatus> propertyImplNodes = titanGenericDao.getChildrenVertecies(UniqueIdBuilder.getKeyByNodeType(instanceNodeType), resourceInstanceUid, GraphEdgeLabels.PROPERTY_VALUE);
if (propertyImplNodes.isRight()) {
@@ -1558,7 +1554,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
*/
public Either<String, TitanOperationStatus> findDefaultValueFromSecondPosition(List<String> pathOfComponentInstances, String propertyUniqueId, String defaultValue) {
- log.trace("In find default value: path=" + pathOfComponentInstances + "propertyUniqId=" + propertyUniqueId + "defaultValue=" + defaultValue);
+ log.trace("In find default value: path= {} propertyUniqId={} defaultValue= {}", pathOfComponentInstances, propertyUniqueId, defaultValue);
if (pathOfComponentInstances == null || pathOfComponentInstances.size() < 2) {
return Either.left(defaultValue);
@@ -1583,7 +1579,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
}
ComponentInstanceProperty foundCompInstanceProperty = fetchByPropertyUid(propertyValuesResult.left().value(), propertyUniqueId);
- log.trace("After finding the component instance property on {}. {}", compInstanceId, foundCompInstanceProperty);
+ log.trace("After finding the component instance property on{} . {}", compInstanceId, foundCompInstanceProperty);
if (foundCompInstanceProperty == null) {
continue;
@@ -1695,7 +1691,9 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
Matcher matcher = pattern.matcher(stringForMatch);
if (matcher.matches()) {
- log.trace("{} matches the rule {}", stringForMatch, patternStr);
+ if (log.isTraceEnabled()) {
+ log.trace("{} matches the rule {}", stringForMatch, patternStr);
+ }
propertyRule = rule;
break;
}
@@ -1752,14 +1750,14 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
if (numberOfMatches == 1) {
instanceProperty.setValue(value);
if (log.isDebugEnabled()) {
- log.debug("Set the value of property " + propertyUniqueId + " " + instanceProperty.getName() + " on path " + pathOfInstances + " to be " + value);
+ log.debug("Set the value of property {} {} on path {} to be {}", propertyUniqueId, instanceProperty.getName(), pathOfInstances, value);
}
} else if (numberOfMatches == 2) {
// In case of another property value match, then use the
// value to be the default value of the property.
instanceProperty.setDefaultValue(value);
if (log.isDebugEnabled()) {
- log.debug("Set the default value of property " + propertyUniqueId + " " + instanceProperty.getName() + " on path " + pathOfInstances + " to be " + value);
+ log.debug("Set the default value of property {} {} on path {} to be {}", propertyUniqueId, instanceProperty.getName(), pathOfInstances, value);
}
break;
}
@@ -1820,19 +1818,19 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
*/
private Either<DataTypeData, TitanOperationStatus> addDataTypeToGraph(DataTypeDefinition dataTypeDefinition) {
- log.debug("Got data type " + dataTypeDefinition);
+ log.debug("Got data type {}", dataTypeDefinition);
String dtUniqueId = UniqueIdBuilder.buildDataTypeUid(dataTypeDefinition.getName());
DataTypeData dataTypeData = buildDataTypeData(dataTypeDefinition, dtUniqueId);
- log.debug("Before adding data type to graph. dataTypeData = " + dataTypeData);
+ log.debug("Before adding data type to graph. dataTypeData = {}", dataTypeData);
Either<DataTypeData, TitanOperationStatus> createDataTypeResult = titanGenericDao.createNode(dataTypeData, DataTypeData.class);
log.debug("After adding data type to graph. status is = {}", createDataTypeResult);
if (createDataTypeResult.isRight()) {
TitanOperationStatus operationStatus = createDataTypeResult.right().value();
- log.debug("Failed to data type " + dataTypeDefinition.getName() + " to graph. status is " + operationStatus);
+ log.debug("Failed to data type {} to graph. status is {}", dataTypeDefinition.getName(), operationStatus);
BeEcompErrorManager.getInstance().logBeFailedAddingNodeTypeError("AddDataType", NodeTypeEnum.DataType.getName());
return Either.right(operationStatus);
}
@@ -1841,19 +1839,19 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
List<PropertyDefinition> properties = dataTypeDefinition.getProperties();
Either<Map<String, PropertyData>, TitanOperationStatus> addPropertiesToDataType = addPropertiesToDataType(resultCTD.getUniqueId(), properties);
if (addPropertiesToDataType.isRight()) {
- log.debug("Failed add properties " + properties + " to data type " + dataTypeDefinition.getName());
+ log.debug("Failed add properties {} to data type {}", properties, dataTypeDefinition.getName());
return Either.right(addPropertiesToDataType.right().value());
}
String derivedFrom = dataTypeDefinition.getDerivedFromName();
if (derivedFrom != null) {
- log.debug("Before creating relation between data type " + dtUniqueId + " to its parent " + derivedFrom);
+ log.debug("Before creating relation between data type {} to its parent {}", dtUniqueId, derivedFrom);
UniqueIdData from = new UniqueIdData(NodeTypeEnum.DataType, dtUniqueId);
String deriveFromUid = UniqueIdBuilder.buildDataTypeUid(derivedFrom);
UniqueIdData to = new UniqueIdData(NodeTypeEnum.DataType, deriveFromUid);
Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(from, to, GraphEdgeLabels.DERIVED_FROM, null);
- log.debug("After create relation between capability type " + dtUniqueId + " to its parent " + derivedFrom + ". status is " + createRelation);
+ log.debug("After create relation between capability type {} to its parent {}. status is {}", dtUniqueId, derivedFrom, createRelation);
if (createRelation.isRight()) {
return Either.right(createRelation.right().value());
}
@@ -1898,19 +1896,19 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
String propertyType = propertyDefinition.getType();
Either<Boolean, TitanOperationStatus> validPropertyType = isValidPropertyType(propertyType);
if (validPropertyType.isRight()) {
- log.debug("Data type " + uniqueId + " contains invalid property type " + propertyType);
+ log.debug("Data type {} contains invalid property type {}", uniqueId, propertyType);
return Either.right(validPropertyType.right().value());
}
Boolean isValid = validPropertyType.left().value();
if (isValid == null || isValid.booleanValue() == false) {
- log.debug("Data type " + uniqueId + " contains invalid property type " + propertyType);
+ log.debug("Data type {} contains invalid property type {}", uniqueId, propertyType);
return Either.right(TitanOperationStatus.INVALID_TYPE);
}
Either<PropertyData, TitanOperationStatus> addPropertyToNodeType = this.addPropertyToNodeType(propertyName, propertyDefinition, NodeTypeEnum.DataType, uniqueId);
if (addPropertyToNodeType.isRight()) {
TitanOperationStatus operationStatus = addPropertyToNodeType.right().value();
- log.debug("Failed to associate data type " + uniqueId + " to property " + propertyName + " in graph. status is " + operationStatus);
+ log.debug("Failed to associate data type {} to property {} in graph. status is {}", uniqueId, propertyName, operationStatus);
BeEcompErrorManager.getInstance().logInternalFlowError("AddPropertyToDataType", "Failed to associate property to data type. Status is " + operationStatus, ErrorSeverity.ERROR);
return Either.right(operationStatus);
}
@@ -1925,7 +1923,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
Either<DataTypeData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(dataTypeData, DataTypeData.class);
if (updateNode.isRight()) {
TitanOperationStatus operationStatus = updateNode.right().value();
- log.debug("Failed to update modification time data type " + uniqueId + " from graph. status is " + operationStatus);
+ log.debug("Failed to update modification time data type {} from graph. status is {}", uniqueId, operationStatus);
BeEcompErrorManager.getInstance().logInternalFlowError("AddPropertyToDataType", "Failed to fetch data type. Status is " + operationStatus, ErrorSeverity.ERROR);
return Either.right(operationStatus);
} else {
@@ -1952,7 +1950,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
if (dataTypesRes.isRight()) {
TitanOperationStatus status = dataTypesRes.right().value();
- log.debug("Data type " + uniqueId + " cannot be found in graph. status is " + status);
+ log.debug("Data type {} cannot be found in graph. status is {}", uniqueId, status);
return Either.right(status);
}
@@ -1961,17 +1959,17 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
TitanOperationStatus propertiesStatus = fillProperties(uniqueId, dataTypeDefinition);
if (propertiesStatus != TitanOperationStatus.OK) {
- log.error("Failed to fetch properties of data type " + uniqueId);
+ log.error("Failed to fetch properties of data type {}", uniqueId);
return Either.right(propertiesStatus);
}
Either<ImmutablePair<DataTypeData, GraphEdge>, TitanOperationStatus> parentNode = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.DataType), uniqueId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.DataType,
DataTypeData.class);
- log.debug("After retrieving DERIVED_FROM node of " + uniqueId + ". status is " + parentNode);
+ log.debug("After retrieving DERIVED_FROM node of {}. status is {}", uniqueId, parentNode);
if (parentNode.isRight()) {
TitanOperationStatus titanOperationStatus = parentNode.right().value();
if (titanOperationStatus != TitanOperationStatus.NOT_FOUND) {
- log.error("Failed to find the parent data type of data type " + uniqueId + ". status is " + titanOperationStatus);
+ log.error("Failed to find the parent data type of data type {}. status is {}", uniqueId, titanOperationStatus);
result = Either.right(titanOperationStatus);
return result;
}
@@ -2002,7 +2000,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
Either<Map<String, PropertyDefinition>, TitanOperationStatus> findPropertiesOfNode = this.findPropertiesOfNode(NodeTypeEnum.DataType, uniqueId);
if (findPropertiesOfNode.isRight()) {
TitanOperationStatus titanOperationStatus = findPropertiesOfNode.right().value();
- log.debug("After looking for properties of vertex " + uniqueId + ". status is " + titanOperationStatus);
+ log.debug("After looking for properties of vertex {}. status is {}", uniqueId, titanOperationStatus);
if (TitanOperationStatus.NOT_FOUND.equals(titanOperationStatus)) {
return TitanOperationStatus.OK;
} else {
@@ -2044,7 +2042,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
DataTypeData capabilityTypeData = eitherStatus.left().value();
DataTypeDefinition dataTypeDefResult = convertDTDataToDTDefinition(capabilityTypeData);
- log.debug("The returned CapabilityTypeDefinition is " + dataTypeDefResult);
+ log.debug("The returned CapabilityTypeDefinition is {}", dataTypeDefResult);
result = Either.left(dataTypeDefResult);
return result;
}
@@ -2079,7 +2077,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
if (ctResult.isRight()) {
TitanOperationStatus status = ctResult.right().value();
if (status != TitanOperationStatus.NOT_FOUND) {
- log.error("Failed to retrieve information on capability type " + name + "status is " + status);
+ log.error("Failed to retrieve information on capability type {} status is {}", name, status);
}
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(ctResult.right().value()));
return result;
@@ -2124,7 +2122,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
if (ctResult.isRight()) {
TitanOperationStatus status = ctResult.right().value();
if (status != TitanOperationStatus.NOT_FOUND) {
- log.error("Failed to retrieve information on capability type " + name + "status is " + status);
+ log.error("Failed to retrieve information on capability type {} status is {}", name, status);
}
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(ctResult.right().value()));
return result;
@@ -2153,7 +2151,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
if (dataTypesRes.isRight()) {
TitanOperationStatus status = dataTypesRes.right().value();
- log.debug("Data type " + uniqueId + " cannot be found in graph. status is " + status);
+ log.debug("Data type {} cannot be found in graph. status is {}", uniqueId, status);
return Either.right(status);
}
@@ -2162,7 +2160,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
TitanOperationStatus propertiesStatus = fillProperties(uniqueId, dataTypeDefinition);
if (propertiesStatus != TitanOperationStatus.OK) {
- log.error("Failed to fetch properties of data type " + uniqueId);
+ log.error("Failed to fetch properties of data type {}", uniqueId);
return Either.right(propertiesStatus);
}
@@ -2184,7 +2182,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
* @return
*/
protected DataTypeDefinition convertDTDataToDTDefinition(DataTypeData dataTypeData) {
- log.debug("The object returned after create data type is " + dataTypeData);
+ log.debug("The object returned after create data type is {}", dataTypeData);
DataTypeDefinition dataTypeDefResult = new DataTypeDefinition(dataTypeData.getDataTypeDataDefinition());
@@ -2206,7 +2204,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
}
}
- private Either<Boolean, TitanOperationStatus> isDefinedInDataTypes(String propertyType) {
+ public Either<Boolean, TitanOperationStatus> isDefinedInDataTypes(String propertyType) {
String dataTypeUid = UniqueIdBuilder.buildDataTypeUid(propertyType);
Either<DataTypeDefinition, TitanOperationStatus> dataTypeByUid = getDataTypeByUid(dataTypeUid);
@@ -2253,14 +2251,14 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
List<DataTypeData> list = getAllDataTypes.left().value();
if (list != null) {
- log.trace("Number of data types to load is " + list.size());
+ log.trace("Number of data types to load is {}" , list.size());
List<String> collect = list.stream().map(p -> p.getDataTypeDataDefinition().getName()).collect(Collectors.toList());
- log.trace("The data types to load are " + collect);
+ log.trace("The data types to load are {}" , collect);
for (DataTypeData dataTypeData : list) {
- log.trace("Going to fetch data type " + dataTypeData.getDataTypeDataDefinition().getName() + ". uid is " + dataTypeData.getUniqueId());
+ log.trace("Going to fetch data type {}. uid is {}", dataTypeData.getDataTypeDataDefinition().getName(), dataTypeData.getUniqueId());
Either<DataTypeDefinition, TitanOperationStatus> dataTypeByUid = this.getAndAddDataTypeByUid(dataTypeData.getUniqueId(), dataTypes);
if (dataTypeByUid.isRight()) {
TitanOperationStatus status = dataTypeByUid.right().value();
@@ -2274,12 +2272,12 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
if (log.isTraceEnabled()) {
if (result.isRight()) {
- log.trace("After fetching all data types " + result);
+ log.trace("After fetching all data types {}" , result);
} else {
Map<String, DataTypeDefinition> map = result.left().value();
if (map != null) {
String types = map.keySet().stream().collect(Collectors.joining(",", "[", "]"));
- log.trace("After fetching all data types " + types);
+ log.trace("After fetching all data types {} " , types);
}
}
}
@@ -2305,7 +2303,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
if (dataTypesRes.isRight()) {
TitanOperationStatus status = dataTypesRes.right().value();
- log.debug("Data type " + uniqueId + " cannot be found in graph. status is " + status);
+ log.debug("Data type {} cannot be found in graph. status is {}", uniqueId, status);
return Either.right(status);
}
@@ -2314,7 +2312,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
TitanOperationStatus propertiesStatus = fillProperties(uniqueId, dataTypeDefinition);
if (propertiesStatus != TitanOperationStatus.OK) {
- log.error("Failed to fetch properties of data type " + uniqueId);
+ log.error("Failed to fetch properties of data type {}", uniqueId);
return Either.right(propertiesStatus);
}
@@ -2331,11 +2329,11 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
Either<ImmutablePair<DataTypeData, GraphEdge>, TitanOperationStatus> parentNode = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.DataType), uniqueId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.DataType,
DataTypeData.class);
- log.debug("After retrieving DERIVED_FROM node of " + uniqueId + ". status is " + parentNode);
+ log.debug("After retrieving DERIVED_FROM node of {}. status is {}", uniqueId, parentNode);
if (parentNode.isRight()) {
TitanOperationStatus titanOperationStatus = parentNode.right().value();
if (titanOperationStatus != TitanOperationStatus.NOT_FOUND) {
- log.error("Failed to find the parent data type of data type " + uniqueId + ". status is " + titanOperationStatus);
+ log.error("Failed to find the parent data type of data type {}. status is {}", uniqueId, titanOperationStatus);
result = Either.right(titanOperationStatus);
return result;
}
@@ -2436,7 +2434,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
Either<Map<String, PropertyDefinition>, TitanOperationStatus> findPropertiesOfNode = this.findPropertiesOfNode(NodeTypeEnum.GroupType, uniqueId);
if (findPropertiesOfNode.isRight()) {
TitanOperationStatus titanOperationStatus = findPropertiesOfNode.right().value();
- log.debug("After looking for properties of vertex " + uniqueId + ". status is " + titanOperationStatus);
+ log.debug("After looking for properties of vertex {}. status is {}", uniqueId, titanOperationStatus);
if (TitanOperationStatus.NOT_FOUND.equals(titanOperationStatus)) {
return TitanOperationStatus.OK;
} else {
@@ -2461,7 +2459,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
*
* @param uniqueId
* @param propertiesMap
- * TODO
+ *
* @return
*/
protected Either<Map<String, PropertyData>, TitanOperationStatus> addPropertiesToElementType(String uniqueId, NodeTypeEnum nodeType, Map<String, PropertyDefinition> propertiesMap) {
@@ -2477,7 +2475,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
if (addPropertyToNodeType.isRight()) {
TitanOperationStatus operationStatus = addPropertyToNodeType.right().value();
- log.error("Failed to associate " + nodeType.getName() + " " + uniqueId + " to property " + propertyName + " in graph. status is " + operationStatus);
+ log.error("Failed to associate {} {} to property {} in graph. status is {}", nodeType.getName(), uniqueId, propertyName, operationStatus);
return Either.right(operationStatus);
}
propertiesData.put(propertyName, addPropertyToNodeType.left().value());
@@ -2556,14 +2554,14 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
List<PropertyDefinition> propertiesToAdd = new ArrayList<>();
if (isPropertyOmitted(newProperties, oldProperties, dataTypeName) || isPropertyTypeChanged(dataTypeName, newProperties, oldProperties, propertiesToAdd) || isDerivedFromNameChanged(dataTypeName, newDerivedFromName, oldDerivedFromName)) {
- log.debug("The new data type " + dataTypeName + " is invalid.");
+ log.debug("The new data type {} is invalid.", dataTypeName);
result = Either.right(StorageOperationStatus.CANNOT_UPDATE_EXISTING_ENTITY);
return result;
}
if (propertiesToAdd == null || propertiesToAdd.isEmpty()) {
- log.debug("No new properties has been defined in the new data type " + newDataTypeDefinition);
+ log.debug("No new properties has been defined in the new data type {}", newDataTypeDefinition);
result = Either.right(StorageOperationStatus.OK);
return result;
}
@@ -2606,15 +2604,6 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
private String getDerivedFromName(DataTypeDefinition dataTypeDefinition) {
String derivedFromName = dataTypeDefinition.getDerivedFromName();
- // if (derivedFromName == null) {
- // DataTypeDefinition derivedFrom = dataTypeDefinition.getDerivedFrom();
- // if (derivedFrom != null) {
- // log.debug("Dervied from is taken from definition");
- // derivedFromName = derivedFrom.getName();
- // }
- // } else {
- // log.debug("Dervied from is taken from field derivedFromName");
- // }
return derivedFromName;
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/RequirementOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/RequirementOperation.java
index e8892ad333..a2fe3d61d3 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/RequirementOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/RequirementOperation.java
@@ -95,10 +95,9 @@ public class RequirementOperation implements IRequirementOperation {
}
protected CapabilityTypeDefinition convertCTDataToCTDefinition(CapabilityTypeData capabilityTypeData) {
- log.debug("The object returned after create capability is " + capabilityTypeData);
+ log.debug("The object returned after create capability is {}", capabilityTypeData);
- CapabilityTypeDefinition capabilityTypeDefResult = new CapabilityTypeDefinition(
- capabilityTypeData.getCapabilityTypeDataDefinition());
+ CapabilityTypeDefinition capabilityTypeDefResult = new CapabilityTypeDefinition(capabilityTypeData.getCapabilityTypeDataDefinition());
return capabilityTypeDefResult;
}
@@ -117,14 +116,12 @@ public class RequirementOperation implements IRequirementOperation {
}
@Override
- public Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource(String reqName,
- RequirementDefinition reqDefinition, String resourceId) {
+ public Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource(String reqName, RequirementDefinition reqDefinition, String resourceId) {
return addRequirementToResource(reqName, reqDefinition, resourceId, false);
}
- private Either<GraphRelation, TitanOperationStatus> associateRequirementToRelationshipType(RequirementData reqData,
- RequirementDefinition reqDefinition) {
+ private Either<GraphRelation, TitanOperationStatus> associateRequirementToRelationshipType(RequirementData reqData, RequirementDefinition reqDefinition) {
String relationship = reqDefinition.getRelationship();
@@ -133,8 +130,7 @@ public class RequirementOperation implements IRequirementOperation {
return Either.right(TitanOperationStatus.NOT_FOUND);
}
UniqueIdData uniqueIdData = new UniqueIdData(NodeTypeEnum.RelationshipType, relationship);
- Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(reqData,
- uniqueIdData, GraphEdgeLabels.RELATIONSHIP_TYPE, null);
+ Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(reqData, uniqueIdData, GraphEdgeLabels.RELATIONSHIP_TYPE, null);
return createRelation;
@@ -147,32 +143,26 @@ public class RequirementOperation implements IRequirementOperation {
* @param reqDefinition
* @return
*/
- private Either<GraphRelation, TitanOperationStatus> associateRequirementToCapabilityType(RequirementData reqData,
- RequirementDefinition reqDefinition) {
+ private Either<GraphRelation, TitanOperationStatus> associateRequirementToCapabilityType(RequirementData reqData, RequirementDefinition reqDefinition) {
String capability = reqDefinition.getCapability();
UniqueIdData uniqueIdData = new UniqueIdData(NodeTypeEnum.CapabilityType, capability);
- Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(reqData,
- uniqueIdData, GraphEdgeLabels.CAPABILITY_TYPE, null);
+ Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(reqData, uniqueIdData, GraphEdgeLabels.CAPABILITY_TYPE, null);
- log.debug("After associating requirementData " + reqData + " to capability " + capability + ". status is "
- + createRelation);
+ log.debug("After associating requirementData {} to capability {}. status is {}", reqData, capability, createRelation);
return createRelation;
}
- private TitanOperationStatus associateRequirementToCapabilityType(TitanVertex reqData,
- RequirementDefinition reqDefinition) {
+ private TitanOperationStatus associateRequirementToCapabilityType(TitanVertex reqData, RequirementDefinition reqDefinition) {
String capability = reqDefinition.getCapability();
UniqueIdData uniqueIdData = new UniqueIdData(NodeTypeEnum.CapabilityType, capability);
- TitanOperationStatus createRelation = titanGenericDao.createEdge(reqData, uniqueIdData,
- GraphEdgeLabels.CAPABILITY_TYPE, null);
+ TitanOperationStatus createRelation = titanGenericDao.createEdge(reqData, uniqueIdData, GraphEdgeLabels.CAPABILITY_TYPE, null);
- log.debug("After associating requirementData {} to capability {}. status is {}" + reqData, capability,
- createRelation);
+ log.debug("After associating requirementData {} to capability {}. status is {}", reqData, capability, createRelation);
return createRelation;
}
@@ -185,18 +175,14 @@ public class RequirementOperation implements IRequirementOperation {
* @param capabilityName
* @return
*/
- private Either<GraphRelation, TitanOperationStatus> associateRequirementImplToCapabilityInst(
- RequirementImplData reqImplData, CapabilityInstData capabilityInstData, String capabilityName) {
+ private Either<GraphRelation, TitanOperationStatus> associateRequirementImplToCapabilityInst(RequirementImplData reqImplData, CapabilityInstData capabilityInstData, String capabilityName) {
Map<String, Object> props = new HashMap<String, Object>();
props.put(GraphPropertiesDictionary.NAME.getProperty(), capabilityName);
- log.debug(
- "Before associating requirement impl " + reqImplData + " to capability instance " + capabilityInstData);
- Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(reqImplData,
- capabilityInstData, GraphEdgeLabels.CAPABILITY_INST, props);
- log.debug("After associating requirement impl " + reqImplData + " to capability instance " + capabilityInstData
- + ".status is " + createRelation);
+ log.debug("Before associating requirement impl {} to capability instance {}", reqImplData, capabilityInstData);
+ Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(reqImplData, capabilityInstData, GraphEdgeLabels.CAPABILITY_INST, props);
+ log.debug("After associating requirement impl {} to capability instance {}.status is {}", reqImplData, capabilityInstData, createRelation);
return createRelation;
@@ -210,8 +196,7 @@ public class RequirementOperation implements IRequirementOperation {
* @param reqDefinition
* @return
*/
- private Either<RequirementData, TitanOperationStatus> addRequirementData(String resourceId, String reqName,
- RequirementDefinition reqDefinition) {
+ private Either<RequirementData, TitanOperationStatus> addRequirementData(String resourceId, String reqName, RequirementDefinition reqDefinition) {
ResourceMetadataData resourceData = new ResourceMetadataData();
resourceData.getMetadataDataDefinition().setUniqueId(resourceId);
@@ -219,19 +204,16 @@ public class RequirementOperation implements IRequirementOperation {
RequirementData requirementData = buildRequirementData(resourceId, reqName, reqDefinition);
log.debug("Before adding requirement data to graph {}", requirementData);
- Either<RequirementData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(requirementData,
- RequirementData.class);
+ Either<RequirementData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(requirementData, RequirementData.class);
log.debug("After adding requirement to graph {}", requirementData);
if (createNodeResult.isRight()) {
TitanOperationStatus operationStatus = createNodeResult.right().value();
- log.error("Failed to add requirement " + reqName + " [ " + requirementData + " ] " + " to graph. status is "
- + operationStatus);
+ log.error("Failed to add requirement {} [{}] to graph. status is {}", reqName, requirementData, operationStatus);
return Either.right(operationStatus);
}
- TitanOperationStatus status = associateResourceDataToRequirementData(resourceId, reqName, resourceData,
- requirementData);
+ TitanOperationStatus status = associateResourceDataToRequirementData(resourceId, reqName, resourceData, requirementData);
if (status != TitanOperationStatus.OK) {
return Either.right(status);
}
@@ -240,8 +222,7 @@ public class RequirementOperation implements IRequirementOperation {
}
- private Either<TitanVertex, TitanOperationStatus> addRequirementData(TitanVertex vertex, String resourceId,
- String reqName, RequirementDefinition reqDefinition) {
+ private Either<TitanVertex, TitanOperationStatus> addRequirementData(TitanVertex vertex, String resourceId, String reqName, RequirementDefinition reqDefinition) {
RequirementData requirementData = buildRequirementData(resourceId, reqName, reqDefinition);
@@ -251,13 +232,11 @@ public class RequirementOperation implements IRequirementOperation {
log.debug("After adding requirement to graph {}", requirementData);
if (createNodeResult.isRight()) {
TitanOperationStatus operationStatus = createNodeResult.right().value();
- log.error("Failed to add requirement " + reqName + " [ " + requirementData + " ] " + " to graph. status is "
- + operationStatus);
+ log.error("Failed to add requirement {} [{}] to graph. status is {}", reqName, requirementData, operationStatus);
return Either.right(operationStatus);
}
- TitanOperationStatus status = associateResourceDataToRequirementData(resourceId, reqName, vertex,
- createNodeResult.left().value());
+ TitanOperationStatus status = associateResourceDataToRequirementData(resourceId, reqName, vertex, createNodeResult.left().value());
if (!status.equals(TitanOperationStatus.OK)) {
return Either.right(status);
}
@@ -265,8 +244,7 @@ public class RequirementOperation implements IRequirementOperation {
}
/**
- * Asssociate resource node to requirement node with REQUIREMENT label and
- * requirement name as property on the edge.
+ * Asssociate resource node to requirement node with REQUIREMENT label and requirement name as property on the edge.
*
* @param resourceId
* @param reqName
@@ -274,39 +252,32 @@ public class RequirementOperation implements IRequirementOperation {
* @param requirementData
* @return
*/
- private TitanOperationStatus associateResourceDataToRequirementData(String resourceId, String reqName,
- ResourceMetadataData resourceData, RequirementData requirementData) {
+ private TitanOperationStatus associateResourceDataToRequirementData(String resourceId, String reqName, ResourceMetadataData resourceData, RequirementData requirementData) {
Map<String, Object> props = new HashMap<String, Object>();
props.put(GraphPropertiesDictionary.NAME.getProperty(), reqName);
- Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(resourceData,
- requirementData, GraphEdgeLabels.REQUIREMENT, props);
- log.debug("After creatin edge between resource " + resourceId + " to requirement " + requirementData);
+ Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(resourceData, requirementData, GraphEdgeLabels.REQUIREMENT, props);
+ log.debug("After creatin edge between resource {} to requirement {}", resourceId, requirementData);
if (createRelResult.isRight()) {
TitanOperationStatus operationStatus = createRelResult.right().value();
- log.error("Failed to associate resource " + resourceId + " to requirement " + reqName + "[ "
- + requirementData + "] in graph. status is " + operationStatus);
+ log.error("Failed to associate resource {} to requirement {} [ {} ] in graph. status is {}", resourceId, reqName, requirementData, operationStatus);
}
return TitanOperationStatus.OK;
}
- private TitanOperationStatus associateResourceDataToRequirementData(String resourceId, String reqName,
- TitanVertex resourceVertex, TitanVertex requirementVertex) {
+ private TitanOperationStatus associateResourceDataToRequirementData(String resourceId, String reqName, TitanVertex resourceVertex, TitanVertex requirementVertex) {
Map<String, Object> props = new HashMap<String, Object>();
props.put(GraphPropertiesDictionary.NAME.getProperty(), reqName);
- TitanOperationStatus createRelResult = titanGenericDao.createEdge(resourceVertex, requirementVertex,
- GraphEdgeLabels.REQUIREMENT, props);
+ TitanOperationStatus createRelResult = titanGenericDao.createEdge(resourceVertex, requirementVertex, GraphEdgeLabels.REQUIREMENT, props);
log.debug("After creatin edge between resource {} to requirement {}", resourceId, requirementVertex);
if (!createRelResult.equals(TitanOperationStatus.OK)) {
- log.error("Failed to associate resource {} to requirement {} in graph. status is " + resourceId, reqName,
- createRelResult);
+ log.error("Failed to associate resource {} to requirement {} in graph. status is {}", resourceId, reqName, createRelResult);
}
return TitanOperationStatus.OK;
}
- private RequirementData buildRequirementData(String resourceId, String reqName,
- RequirementDefinition reqDefinition) {
+ private RequirementData buildRequirementData(String resourceId, String reqName, RequirementDefinition reqDefinition) {
RequirementData requirementData = new RequirementData();
requirementData.setNode(reqDefinition.getNode());
@@ -322,8 +293,7 @@ public class RequirementOperation implements IRequirementOperation {
}
/**
- * build requirement impl node associate it to resource, requirement &
- * implementation resource
+ * build requirement impl node associate it to resource, requirement & implementation resource
*
* [RESOURCE] --> [REQUIREMENT IMPL] --> [ RESOURCE IMPL ] | V [REQUIREMENT]
*
@@ -334,47 +304,37 @@ public class RequirementOperation implements IRequirementOperation {
* @param reqImplDefinition
* @return
*/
- private Either<RequirementImplData, TitanOperationStatus> addRequirementImplData(NodeTypeEnum resourceLabel,
- String resourceId, String reqName, String requirementUid, RequirementImplDef reqImplDefinition) {
+ private Either<RequirementImplData, TitanOperationStatus> addRequirementImplData(NodeTypeEnum resourceLabel, String resourceId, String reqName, String requirementUid, RequirementImplDef reqImplDefinition) {
RequirementImplData requirementImplData = buildRequirementImplData(resourceId, reqName, reqImplDefinition);
- log.debug("Before adding requirement impl data to graph " + requirementImplData);
- Either<RequirementImplData, TitanOperationStatus> createNodeResult = titanGenericDao
- .createNode(requirementImplData, RequirementImplData.class);
- log.debug("After adding requirement to graph " + requirementImplData + ". status is " + createNodeResult);
+ log.debug("Before adding requirement impl data to graph {}", requirementImplData);
+ Either<RequirementImplData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(requirementImplData, RequirementImplData.class);
+ log.debug("After adding requirement to graph {}. status is {}", requirementImplData, createNodeResult);
if (createNodeResult.isRight()) {
TitanOperationStatus operationStatus = createNodeResult.right().value();
- log.error("Failed to add requirement " + reqName + " [ " + requirementImplData + " ] "
- + " to graph. status is " + operationStatus);
+ log.error("Failed to add requirement {} [ {} ] to graph. status is {}", reqName, requirementImplData, operationStatus);
return Either.right(operationStatus);
}
- Either<GraphRelation, TitanOperationStatus> createRelResult = associateReqImplRoResource(resourceLabel,
- resourceId, reqName, requirementImplData);
+ Either<GraphRelation, TitanOperationStatus> createRelResult = associateReqImplRoResource(resourceLabel, resourceId, reqName, requirementImplData);
if (createRelResult.isRight()) {
TitanOperationStatus operationStatus = createRelResult.right().value();
- log.error("Failed to associate resource " + resourceId + " to requirement impl " + requirementImplData
- + "[ " + requirementImplData + "] in graph. status is " + operationStatus);
+ log.error("Failed to associate resource {} to requirement impl {} [ {} ] in graph. status is {}", resourceId, requirementImplData, requirementImplData, operationStatus);
return Either.right(operationStatus);
}
- Either<GraphRelation, TitanOperationStatus> associateToResourceImpl = associateReqImplToImplResource(
- requirementImplData, reqImplDefinition.getNodeId());
+ Either<GraphRelation, TitanOperationStatus> associateToResourceImpl = associateReqImplToImplResource(requirementImplData, reqImplDefinition.getNodeId());
if (associateToResourceImpl.isRight()) {
TitanOperationStatus operationStatus = associateToResourceImpl.right().value();
- log.error("Failed to associate requirement impl " + requirementImplData + " to resource impl "
- + reqImplDefinition.getNodeId() + "[ " + requirementImplData + "] in graph. status is "
- + operationStatus);
+ log.error("Failed to associate requirement impl {} to resource impl {} [ {} ] in graph. status is {}", requirementImplData, reqImplDefinition.getNodeId(), requirementImplData, operationStatus);
return Either.right(operationStatus);
}
- Either<GraphRelation, TitanOperationStatus> associateToRequirement = associateReqImplToRequirement(
- requirementImplData, requirementUid);
+ Either<GraphRelation, TitanOperationStatus> associateToRequirement = associateReqImplToRequirement(requirementImplData, requirementUid);
if (associateToRequirement.isRight()) {
TitanOperationStatus operationStatus = associateToRequirement.right().value();
- log.error("Failed to associate requirement impl " + requirementImplData + " to requirement " + reqName
- + " in graph. status is " + operationStatus);
+ log.error("Failed to associate requirement impl {} to requirement {} in graph. status is {}", requirementImplData, reqName, operationStatus);
return Either.right(operationStatus);
}
@@ -382,8 +342,7 @@ public class RequirementOperation implements IRequirementOperation {
}
- private RequirementImplData buildRequirementImplData(String resourceId, String reqName,
- RequirementImplDef reqImplDefinition) {
+ private RequirementImplData buildRequirementImplData(String resourceId, String reqName, RequirementImplDef reqImplDefinition) {
String reqImplUid = UniqueIdBuilder.buildRequirementImplUid(resourceId, reqName);
RequirementImplData requirementImplData = new RequirementImplData();
requirementImplData.setName(reqName);
@@ -400,53 +359,43 @@ public class RequirementOperation implements IRequirementOperation {
}
/**
- * associate requirement impl node to the source requirement. The source
- * requirement maybe belongs to one of parents.
+ * associate requirement impl node to the source requirement. The source requirement maybe belongs to one of parents.
*
* @param requirementImplData
* @param requirementUid
* @return
*/
- private Either<GraphRelation, TitanOperationStatus> associateReqImplToRequirement(
- RequirementImplData requirementImplData, String requirementUid) {
+ private Either<GraphRelation, TitanOperationStatus> associateReqImplToRequirement(RequirementImplData requirementImplData, String requirementUid) {
UniqueIdData to = new UniqueIdData(NodeTypeEnum.Requirement, requirementUid);
- log.debug("Before creating edge between requirement impl " + requirementImplData + " to requirement "
- + requirementUid);
- Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao
- .createRelation(requirementImplData, to, GraphEdgeLabels.IMPLEMENTATION_OF, null);
- log.debug("Before creating edge between requirement impl " + requirementImplData + " to requirement "
- + requirementUid + ". status is " + createRelResult);
+ log.debug("Before creating edge between requirement impl {} to requirement {}", requirementImplData, requirementUid);
+ Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(requirementImplData, to, GraphEdgeLabels.IMPLEMENTATION_OF, null);
+ log.debug("Before creating edge between requirement impl {} to requirement {}. status is {}", requirementImplData, requirementUid, createRelResult);
return createRelResult;
}
/**
- * Associate requirement impl node to the node which supply this
- * requirement.
+ * Associate requirement impl node to the node which supply this requirement.
*
* @param requirementImplData
* @param nodeId
* @return
*/
- private Either<GraphRelation, TitanOperationStatus> associateReqImplToImplResource(
- RequirementImplData requirementImplData, String nodeId) {
+ private Either<GraphRelation, TitanOperationStatus> associateReqImplToImplResource(RequirementImplData requirementImplData, String nodeId) {
UniqueIdData nodeImpl = new UniqueIdData(NodeTypeEnum.Resource, nodeId);
Map<String, Object> props = new HashMap<String, Object>();
props.put(GraphPropertiesDictionary.NAME.getProperty(), nodeId);
- log.debug("Before creating edge between requirement impl " + requirementImplData + " to node impl " + nodeId);
- Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao
- .createRelation(requirementImplData, nodeImpl, GraphEdgeLabels.NODE_IMPL, props);
- log.debug("After creating edge between requirement " + requirementImplData + " to node impl " + nodeId
- + ". status is " + createRelResult);
+ log.debug("Before creating edge between requirement impl {} to node impl {}", requirementImplData, nodeId);
+ Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(requirementImplData, nodeImpl, GraphEdgeLabels.NODE_IMPL, props);
+ log.debug("After creating edge between requirement {} to node impl {}. status is {}", requirementImplData, nodeId, createRelResult);
return createRelResult;
}
/**
- * create an edge between the requirement impl node to the implementation
- * resource.
+ * create an edge between the requirement impl node to the implementation resource.
*
* @param resourceLabel
* @param resourceId
@@ -454,18 +403,14 @@ public class RequirementOperation implements IRequirementOperation {
* @param requirementImplData
* @return
*/
- private Either<GraphRelation, TitanOperationStatus> associateReqImplRoResource(NodeTypeEnum resourceLabel,
- String resourceId, String reqName, RequirementImplData requirementImplData) {
+ private Either<GraphRelation, TitanOperationStatus> associateReqImplRoResource(NodeTypeEnum resourceLabel, String resourceId, String reqName, RequirementImplData requirementImplData) {
UniqueIdData resource = new UniqueIdData(resourceLabel, resourceId);
Map<String, Object> props = new HashMap<String, Object>();
props.put(GraphPropertiesDictionary.NAME.getProperty(), reqName);
- log.debug(
- "Before creating edge between resource " + resourceId + " to requirement impl " + requirementImplData);
- Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(resource,
- requirementImplData, GraphEdgeLabels.REQUIREMENT_IMPL, props);
- log.debug("After creating edge between to requirement impl " + requirementImplData + " to resource " + resource
- + ". status is " + createRelResult);
+ log.debug("Before creating edge between resource {} to requirement impl {}", resourceId, requirementImplData);
+ Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(resource, requirementImplData, GraphEdgeLabels.REQUIREMENT_IMPL, props);
+ log.debug("After creating edge between to requirement impl {} to resource {}. status is {}", requirementImplData, resource, createRelResult);
return createRelResult;
}
@@ -476,65 +421,46 @@ public class RequirementOperation implements IRequirementOperation {
}
@Override
- public Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource(String reqName,
- RequirementDefinition reqDefinition, String resourceId, boolean inTransaction) {
+ public Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource(String reqName, RequirementDefinition reqDefinition, String resourceId, boolean inTransaction) {
Either<RequirementDefinition, StorageOperationStatus> result = null;
try {
- log.debug("Going to add requirement " + reqName + " to resource " + resourceId
- + ". requirement definition is " + reqDefinition);
+ log.debug("Going to add requirement {} to resource {}. requirement definition is {}", reqName, resourceId, reqDefinition);
validateNodeExists(reqDefinition.getNode());
// 1. add requirement node in graph and associate it to the resource
log.debug("Going to add requirement node in graph and associate it to the resource");
- Either<RequirementData, TitanOperationStatus> addRequirementData = addRequirementData(resourceId, reqName,
- reqDefinition);
+ Either<RequirementData, TitanOperationStatus> addRequirementData = addRequirementData(resourceId, reqName, reqDefinition);
if (addRequirementData.isRight()) {
- log.error("Failed to add requirement " + reqName + " node to graph. status is " + addRequirementData);
- result = Either.right(
- DaoStatusConverter.convertTitanStatusToStorageStatus(addRequirementData.right().value()));
+ log.error("Failed to add requirement {} node to graph. status is {}", reqName, addRequirementData);
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(addRequirementData.right().value()));
return result;
}
RequirementData requirementData = addRequirementData.left().value();
log.debug("Going to associate the requirement to the appriopriate capability type");
- Either<GraphRelation, TitanOperationStatus> associateReqToCapabilityType = associateRequirementToCapabilityType(
- requirementData, reqDefinition);
+ Either<GraphRelation, TitanOperationStatus> associateReqToCapabilityType = associateRequirementToCapabilityType(requirementData, reqDefinition);
if (associateReqToCapabilityType.isRight()) {
- log.error("Failed to associate requirement data node " + requirementData
- + " to the capability type node " + reqDefinition.getCapability());
- result = Either.right(DaoStatusConverter
- .convertTitanStatusToStorageStatus(associateReqToCapabilityType.right().value()));
+ log.error("Failed to associate requirement data node {} to the capability type node {}", requirementData, reqDefinition.getCapability());
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(associateReqToCapabilityType.right().value()));
return result;
}
// TODO: esofer associate requirement to the relationship type
/*
- * Either<GraphRelation, TitanOperationStatus>
- * associateReqToRelshipType =
- * associateRequirementToRelationshipType( requirementData,
- * reqDefinition);
+ * Either<GraphRelation, TitanOperationStatus> associateReqToRelshipType = associateRequirementToRelationshipType( requirementData, reqDefinition);
*
- * if (associateReqToRelshipType.isRight() &&
- * associateReqToRelshipType.right().value() !=
- * TitanOperationStatus.NOT_FOUND) {
- * log.error("Failed to associate requirement data node " +
- * requirementData + " to the relationship type node " +
- * reqDefinition.getRelationship()); result = Either
- * .right(TitanStatusConverter
- * .convertTitanStatusToStorageStatus(associateReqToRelshipType
- * .right().value())); return result; }
+ * if (associateReqToRelshipType.isRight() && associateReqToRelshipType.right().value() != TitanOperationStatus.NOT_FOUND) { log.error("Failed to associate requirement data node " + requirementData + " to the relationship type node " +
+ * reqDefinition.getRelationship()); result = Either .right(TitanStatusConverter .convertTitanStatusToStorageStatus(associateReqToRelshipType .right().value())); return result; }
*/
- log.debug("Going to fetch the requirement " + reqName + " from graph");
- Either<RequirementDefinition, TitanOperationStatus> requirementDefinitionRes = getRequirement(
- requirementData.getUniqueId());
+ log.debug("Going to fetch the requirement {} from graph", reqName);
+ Either<RequirementDefinition, TitanOperationStatus> requirementDefinitionRes = getRequirement(requirementData.getUniqueId());
if (requirementDefinitionRes.isRight()) {
- result = Either.right(
- DaoStatusConverter.convertTitanStatusToStorageStatus(requirementDefinitionRes.right().value()));
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(requirementDefinitionRes.right().value()));
return result;
}
@@ -557,34 +483,28 @@ public class RequirementOperation implements IRequirementOperation {
}
@Override
- public StorageOperationStatus addRequirementToResource(TitanVertex metadataVertex, String reqName,
- RequirementDefinition reqDefinition, String resourceId, boolean inTransaction) {
+ public StorageOperationStatus addRequirementToResource(TitanVertex metadataVertex, String reqName, RequirementDefinition reqDefinition, String resourceId, boolean inTransaction) {
StorageOperationStatus result = StorageOperationStatus.OK;
try {
- log.debug("Going to add requirement {} to resource . requirement definition is ", reqName, resourceId,
- reqDefinition);
+ log.debug("Going to add requirement {} to resource . requirement definition is ", reqName, resourceId, reqDefinition);
validateNodeExists(reqDefinition.getNode());
// 1. add requirement node in graph and associate it to the resource
log.debug("Going to add requirement node in graph and associate it to the resource");
- Either<TitanVertex, TitanOperationStatus> addRequirementData = addRequirementData(metadataVertex,
- resourceId, reqName, reqDefinition);
+ Either<TitanVertex, TitanOperationStatus> addRequirementData = addRequirementData(metadataVertex, resourceId, reqName, reqDefinition);
if (addRequirementData.isRight()) {
- log.error("Failed to add requirement {} node to graph. status is {}", reqName,
- addRequirementData.right().value());
+ log.error("Failed to add requirement {} node to graph. status is {}", reqName, addRequirementData.right().value());
result = DaoStatusConverter.convertTitanStatusToStorageStatus(addRequirementData.right().value());
return result;
}
log.debug("Going to associate the requirement to the appriopriate capability type");
- TitanOperationStatus associateReqToCapabilityType = associateRequirementToCapabilityType(
- addRequirementData.left().value(), reqDefinition);
+ TitanOperationStatus associateReqToCapabilityType = associateRequirementToCapabilityType(addRequirementData.left().value(), reqDefinition);
if (!associateReqToCapabilityType.equals(TitanOperationStatus.OK)) {
- log.error("Failed to associate requirement data node {} to the capability type node {}" + reqDefinition,
- reqDefinition.getCapability());
+ log.error("Failed to associate requirement data node {} to the capability type node {}", reqDefinition.getCapability(), reqDefinition);
result = DaoStatusConverter.convertTitanStatusToStorageStatus(associateReqToCapabilityType);
return result;
}
@@ -614,22 +534,19 @@ public class RequirementOperation implements IRequirementOperation {
public Either<RequirementDefinition, TitanOperationStatus> getRequirement(String uniqueId) {
log.debug("Going to fetch the requirement {} from graph.", uniqueId);
- Either<RequirementData, TitanOperationStatus> reqDataResult = titanGenericDao
- .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Requirement), uniqueId, RequirementData.class);
+ Either<RequirementData, TitanOperationStatus> reqDataResult = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Requirement), uniqueId, RequirementData.class);
if (reqDataResult.isRight()) {
- log.error("Failed to find requirement node in graph " + uniqueId + ". status is " + reqDataResult);
+ log.error("Failed to find requirement node in graph {}. status is {}", uniqueId, reqDataResult);
return Either.right(reqDataResult.right().value());
}
log.debug("Going to fetch the capability type associate to requirement {}", uniqueId);
- Either<ImmutablePair<CapabilityTypeData, GraphEdge>, TitanOperationStatus> capabilityTypeRes = titanGenericDao
- .getChild(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), uniqueId, GraphEdgeLabels.CAPABILITY_TYPE,
- NodeTypeEnum.CapabilityType, CapabilityTypeData.class);
+ Either<ImmutablePair<CapabilityTypeData, GraphEdge>, TitanOperationStatus> capabilityTypeRes = titanGenericDao.getChild(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), uniqueId, GraphEdgeLabels.CAPABILITY_TYPE, NodeTypeEnum.CapabilityType,
+ CapabilityTypeData.class);
if (capabilityTypeRes.isRight()) {
- log.error("Cannot find the capability of a given requirement " + uniqueId + ". status is "
- + capabilityTypeRes);
+ log.error("Cannot find the capability of a given requirement {}. status is {}", uniqueId, capabilityTypeRes);
return Either.right(capabilityTypeRes.right().value());
}
@@ -639,37 +556,23 @@ public class RequirementOperation implements IRequirementOperation {
// TODO: esofer add relationship as edge
/*
- * Either<List<ImmutablePair<RelationshipTypeData, GraphEdge>>,
- * TitanOperationStatus> relationshipRes = titanGenericDao
- * .getChildrenNodes( GraphPropertiesDictionary.UNIQUE_ID.getProperty(),
- * uniqueId, GraphEdgeLabels.RELATIONSHIP_TYPE,
+ * Either<List<ImmutablePair<RelationshipTypeData, GraphEdge>>, TitanOperationStatus> relationshipRes = titanGenericDao .getChildrenNodes( GraphPropertiesDictionary.UNIQUE_ID.getProperty(), uniqueId, GraphEdgeLabels.RELATIONSHIP_TYPE,
* NodeTypeEnum.RelationshipType, RelationshipTypeData.class);
*
- * if (relationshipRes.isRight() && relationshipRes.right().value() !=
- * TitanOperationStatus.NOT_FOUND) {
- * log.error("Cannot find the capability of a given requirement " +
- * uniqueId + ". status is " + capabilityTypesRes); return
- * Either.right(relationshipRes.right().value()); }
+ * if (relationshipRes.isRight() && relationshipRes.right().value() != TitanOperationStatus.NOT_FOUND) {
+ * return Either.right(relationshipRes.right().value()); }
*
- * String relationshipType = null; if (relationshipRes.isLeft()) {
- * List<ImmutablePair<RelationshipTypeData, GraphEdge>> rstPairs =
- * relationshipRes .left().value(); if (rstPairs == null || true ==
- * rstPairs.isEmpty()) { log.error(
- * "Cannot find the capability of a given requirement " + uniqueId);
- * return Either.right(TitanOperationStatus.NOT_FOUND); }
+ * String relationshipType = null; if (relationshipRes.isLeft()) { List<ImmutablePair<RelationshipTypeData, GraphEdge>> rstPairs = relationshipRes .left().value(); if (rstPairs == null || true == rstPairs.isEmpty()) { log.error(
+ * "Cannot find the capability of a given requirement " + uniqueId); return Either.right(TitanOperationStatus.NOT_FOUND); }
*
- * ImmutablePair<RelationshipTypeData, GraphEdge> relationship =
- * rstPairs .get(0); relationshipType = relationship.getKey().getType();
- * }
+ * ImmutablePair<RelationshipTypeData, GraphEdge> relationship = rstPairs .get(0); relationshipType = relationship.getKey().getType(); }
*/
log.debug("Going to fetch the capability type associate to requirement {}", uniqueId);
- Either<ImmutablePair<ResourceMetadataData, GraphEdge>, TitanOperationStatus> parentNode = titanGenericDao
- .getParentNode(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), uniqueId, GraphEdgeLabels.REQUIREMENT,
- NodeTypeEnum.Resource, ResourceMetadataData.class);
+ Either<ImmutablePair<ResourceMetadataData, GraphEdge>, TitanOperationStatus> parentNode = titanGenericDao.getParentNode(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), uniqueId, GraphEdgeLabels.REQUIREMENT, NodeTypeEnum.Resource,
+ ResourceMetadataData.class);
if (parentNode.isRight()) {
- log.error("Cannot find the parent resource for a given requirement " + uniqueId + ". status is "
- + parentNode.right().value());
+ log.error("Cannot find the parent resource for a given requirement {}. status is {}", uniqueId, parentNode.right().value());
return Either.right(parentNode.right().value());
}
@@ -689,15 +592,13 @@ public class RequirementOperation implements IRequirementOperation {
}
@Override
- public Either<RequirementDefinition, StorageOperationStatus> getRequirementOfResource(String reqName,
- String resourceId) {
+ public Either<RequirementDefinition, StorageOperationStatus> getRequirementOfResource(String reqName, String resourceId) {
return getRequirementOfResource(reqName, resourceId, false);
}
@Override
- public Either<RequirementDefinition, StorageOperationStatus> getRequirementOfResource(String reqName,
- String resourceId, boolean inTransaction) {
+ public Either<RequirementDefinition, StorageOperationStatus> getRequirementOfResource(String reqName, String resourceId, boolean inTransaction) {
Either<RequirementDefinition, StorageOperationStatus> result = null;
@@ -706,9 +607,8 @@ public class RequirementOperation implements IRequirementOperation {
Either<RequirementDefinition, TitanOperationStatus> requirementRes = getRequirement(reqUniqueId);
if (requirementRes.isRight()) {
- log.debug("Failed to retrieve requirement " + reqName + " associated to resource " + resourceId);
- result = Either
- .right(DaoStatusConverter.convertTitanStatusToStorageStatus(requirementRes.right().value()));
+ log.debug("Failed to retrieve requirement {} associated to resource {}", reqName, resourceId);
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(requirementRes.right().value()));
} else {
result = Either.left(requirementRes.left().value());
}
@@ -730,16 +630,14 @@ public class RequirementOperation implements IRequirementOperation {
}
@Override
- public Either<RequirementDefinition, StorageOperationStatus> addRequirementImplToResource(String reqName,
- RequirementImplDef reqDefinition, String resourceId, String parentReqUniqueId) {
+ public Either<RequirementDefinition, StorageOperationStatus> addRequirementImplToResource(String reqName, RequirementImplDef reqDefinition, String resourceId, String parentReqUniqueId) {
return addRequirementImplToResource(reqName, reqDefinition, resourceId, parentReqUniqueId, false);
}
@Override
- public Either<RequirementDefinition, StorageOperationStatus> addRequirementImplToResource(String reqName,
- RequirementImplDef reqImplDefinition, String resourceId, String parentReqUniqueId, boolean inTransaction) {
+ public Either<RequirementDefinition, StorageOperationStatus> addRequirementImplToResource(String reqName, RequirementImplDef reqImplDefinition, String resourceId, String parentReqUniqueId, boolean inTransaction) {
Either<RequirementDefinition, StorageOperationStatus> result = null;
@@ -748,11 +646,10 @@ public class RequirementOperation implements IRequirementOperation {
// find the requirement defined at the resource itself or under one
// of its parents
Either<RequirementDefinition, TitanOperationStatus> findReq = getRequirement(parentReqUniqueId);
- log.debug("After looking for requirement " + parentReqUniqueId + ". status is " + findReq);
+ log.debug("After looking for requirement {}. status is {}", parentReqUniqueId, findReq);
if (findReq.isRight()) {
TitanOperationStatus status = findReq.right().value();
- log.error("The requirment " + parentReqUniqueId + " was not found in the graph. status is "
- + findReq.right().value());
+ log.error("The requirment {} was not found in the graph. status is {}", parentReqUniqueId, findReq.right().value());
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
return result;
}
@@ -765,27 +662,22 @@ public class RequirementOperation implements IRequirementOperation {
checkNodeIdImplementsRequirementNode(nodeIdImpl, reqNode);
- Either<RequirementImplData, TitanOperationStatus> addRequirementImplData = addRequirementImplData(
- NodeTypeEnum.Resource, resourceId, reqName, parentReqUniqueId, reqImplDefinition);
+ Either<RequirementImplData, TitanOperationStatus> addRequirementImplData = addRequirementImplData(NodeTypeEnum.Resource, resourceId, reqName, parentReqUniqueId, reqImplDefinition);
if (addRequirementImplData.isRight()) {
TitanOperationStatus status = addRequirementImplData.right().value();
- log.error("Failed to add requirement data impl node in the graph. status is "
- + addRequirementImplData.right().value());
+ log.error("Failed to add requirement data impl node in the graph. status is {}", addRequirementImplData.right().value());
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
return result;
}
RequirementImplData requirementImplData = addRequirementImplData.left().value();
- log.debug("Add the properties of the capabilities of the target node " + nodeIdImpl
- + " to the requirement impl node " + requirementImplData.getUniqueId() + " in graph.");
- Map<String, CapabiltyInstance> requirementPropertiesPerCapability = reqImplDefinition
- .getRequirementProperties();
- TitanOperationStatus addPropsResult = addCapabilityPropertiesToReqImpl(requirementImplData, reqCapability,
- nodeIdImpl, requirementPropertiesPerCapability);
+ log.debug("Add the properties of the capabilities of the target node {} to the requirement impl node {} in graph.", nodeIdImpl, requirementImplData.getUniqueId());
+ Map<String, CapabiltyInstance> requirementPropertiesPerCapability = reqImplDefinition.getRequirementProperties();
+ TitanOperationStatus addPropsResult = addCapabilityPropertiesToReqImpl(requirementImplData, reqCapability, nodeIdImpl, requirementPropertiesPerCapability);
if (addPropsResult != TitanOperationStatus.OK) {
- log.error("Failed to add capabilities properties to Requirement impl " + requirementImplData);
+ log.error("Failed to add capabilities properties to Requirement impl {}", requirementImplData);
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(addPropsResult));
return result;
}
@@ -807,15 +699,13 @@ public class RequirementOperation implements IRequirementOperation {
return result;
}
- private Either<RequirementImplDef, TitanOperationStatus> getRequirementImplOfResource(String reqName,
- String resourceId) {
+ private Either<RequirementImplDef, TitanOperationStatus> getRequirementImplOfResource(String reqName, String resourceId) {
RequirementImplDef requirementImplDef = new RequirementImplDef();
- Either<List<ImmutablePair<RequirementImplData, GraphEdge>>, TitanOperationStatus> reqImplNodesRes = titanGenericDao
- .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId,
- GraphEdgeLabels.REQUIREMENT_IMPL, NodeTypeEnum.RequirementImpl, RequirementImplData.class);
- log.debug("After looking for requirement impl edge of resource " + resourceId);
+ Either<List<ImmutablePair<RequirementImplData, GraphEdge>>, TitanOperationStatus> reqImplNodesRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId, GraphEdgeLabels.REQUIREMENT_IMPL,
+ NodeTypeEnum.RequirementImpl, RequirementImplData.class);
+ log.debug("After looking for requirement impl edge of resource {}", resourceId);
if (reqImplNodesRes.isRight()) {
TitanOperationStatus status = reqImplNodesRes.right().value();
return Either.right(status);
@@ -832,15 +722,12 @@ public class RequirementOperation implements IRequirementOperation {
requirementImplDef.setUniqueId(requirementImplData.getUniqueId());
- Either<ImmutablePair<ResourceMetadataData, GraphEdge>, TitanOperationStatus> nodeImplRes = titanGenericDao
- .getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.RequirementImpl),
- requirementImplData.getUniqueId(), GraphEdgeLabels.NODE_IMPL, NodeTypeEnum.Resource,
- ResourceMetadataData.class);
+ Either<ImmutablePair<ResourceMetadataData, GraphEdge>, TitanOperationStatus> nodeImplRes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.RequirementImpl), requirementImplData.getUniqueId(),
+ GraphEdgeLabels.NODE_IMPL, NodeTypeEnum.Resource, ResourceMetadataData.class);
if (nodeImplRes.isRight()) {
TitanOperationStatus status = nodeImplRes.right().value();
- log.debug("No implementation resource was found under requirement impl "
- + requirementImplData.getUniqueId() + ". status is " + status);
+ log.debug("No implementation resource was found under requirement impl {}. status is {}", requirementImplData.getUniqueId(), status);
return Either.right(status);
}
@@ -854,14 +741,11 @@ public class RequirementOperation implements IRequirementOperation {
requirementImplDef.setPoint(point);
}
- Either<List<ImmutablePair<CapabilityInstData, GraphEdge>>, TitanOperationStatus> capaInstDataRes = titanGenericDao
- .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.RequirementImpl),
- requirementImplData.getUniqueId(), GraphEdgeLabels.CAPABILITY_INST,
- NodeTypeEnum.CapabilityInst, CapabilityInstData.class);
+ Either<List<ImmutablePair<CapabilityInstData, GraphEdge>>, TitanOperationStatus> capaInstDataRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.RequirementImpl), requirementImplData.getUniqueId(),
+ GraphEdgeLabels.CAPABILITY_INST, NodeTypeEnum.CapabilityInst, CapabilityInstData.class);
if (capaInstDataRes.isRight()) {
TitanOperationStatus status = capaInstDataRes.right().value();
- log.debug("No capability instance was found under requirement impl "
- + requirementImplData.getUniqueId() + ". status is " + status);
+ log.debug("No capability instance was found under requirement impl {}. status is {}", requirementImplData.getUniqueId(), status);
return Either.right(status);
}
@@ -874,14 +758,12 @@ public class RequirementOperation implements IRequirementOperation {
GraphEdge edge = capabilityInst.getValue();
Map<String, Object> properties = edge.getProperties();
if (properties == null) {
- log.error("Cannot find the property " + GraphPropertiesDictionary.NAME.getProperty()
- + " on the edge " + edge);
+ log.error("Cannot find the property {} on the edge {}", GraphPropertiesDictionary.NAME.getProperty(), edge);
return Either.right(TitanOperationStatus.INVALID_ELEMENT);
}
String capabilityName = (String) properties.get(GraphPropertiesDictionary.NAME.getProperty());
if (capabilityName == null) {
- log.error("Cannot find the property " + GraphPropertiesDictionary.NAME.getProperty()
- + " on the edge " + edge);
+ log.error("Cannot find the property {} on the edge {}", GraphPropertiesDictionary.NAME.getProperty(), edge);
return Either.right(TitanOperationStatus.INVALID_ELEMENT);
}
@@ -896,30 +778,25 @@ public class RequirementOperation implements IRequirementOperation {
// capabiltyInstance.setProperties(actualValues);
requirementProperties.put(capabilityName, capabiltyInstance);
- Either<List<ImmutablePair<PropertyValueData, GraphEdge>>, TitanOperationStatus> propertyValueNodesRes = titanGenericDao
- .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityInst),
- capabilityInstData.getUniqueId(), GraphEdgeLabels.PROPERTY_VALUE,
- NodeTypeEnum.PropertyValue, PropertyValueData.class);
+ Either<List<ImmutablePair<PropertyValueData, GraphEdge>>, TitanOperationStatus> propertyValueNodesRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityInst),
+ capabilityInstData.getUniqueId(), GraphEdgeLabels.PROPERTY_VALUE, NodeTypeEnum.PropertyValue, PropertyValueData.class);
if (propertyValueNodesRes.isRight()) {
TitanOperationStatus status = propertyValueNodesRes.right().value();
if (status != TitanOperationStatus.NOT_FOUND) {
- log.error("Failed to find the property values of capability instance " + capabilityInstData
- + ". status is " + status);
+ log.error("Failed to find the property values of capability instance {}. status is {}", capabilityInstData, status);
return Either.right(status);
}
} else {
- List<ImmutablePair<PropertyValueData, GraphEdge>> propertyValueNodes = propertyValueNodesRes
- .left().value();
+ List<ImmutablePair<PropertyValueData, GraphEdge>> propertyValueNodes = propertyValueNodesRes.left().value();
if (propertyValueNodes != null) {
Map<String, String> actualValues = new HashMap<String, String>();
- TitanOperationStatus fillPropertiesResult = fillPropertiesMapFromNodes(propertyValueNodes,
- actualValues);
+ TitanOperationStatus fillPropertiesResult = fillPropertiesMapFromNodes(propertyValueNodes, actualValues);
if (fillPropertiesResult != TitanOperationStatus.OK) {
- log.error("Failed to fetch properties of capability " + capabilityName);
+ log.error("Failed to fetch properties of capability {}", capabilityName);
return Either.right(fillPropertiesResult);
}
@@ -940,7 +817,7 @@ public class RequirementOperation implements IRequirementOperation {
}
if (false == found) {
- log.debug("Cannot find requirement impl under resource " + resourceId);
+ log.debug("Cannot find requirement impl under resource {}", resourceId);
return Either.right(TitanOperationStatus.NOT_FOUND);
}
@@ -965,22 +842,19 @@ public class RequirementOperation implements IRequirementOperation {
}
- private TitanOperationStatus fillPropertiesMapFromNodes(
- List<ImmutablePair<PropertyValueData, GraphEdge>> propertyValueNodes, Map<String, String> actualValues) {
+ private TitanOperationStatus fillPropertiesMapFromNodes(List<ImmutablePair<PropertyValueData, GraphEdge>> propertyValueNodes, Map<String, String> actualValues) {
if (propertyValueNodes != null) {
for (ImmutablePair<PropertyValueData, GraphEdge> propertyValuePair : propertyValueNodes) {
PropertyValueData propertyValueData = propertyValuePair.getKey();
GraphEdge propertyValueEdge = propertyValuePair.getValue();
Map<String, Object> propertyEdgeProps = propertyValueEdge.getProperties();
if (propertyEdgeProps == null) {
- log.error("Cannot find the property " + GraphPropertiesDictionary.NAME.getProperty()
- + " on the edge " + propertyValueEdge);
+ log.error("Cannot find the property {} on the edge {}", GraphPropertiesDictionary.NAME.getProperty(), propertyValueEdge);
return TitanOperationStatus.INVALID_ELEMENT;
}
String paramName = (String) propertyEdgeProps.get(GraphPropertiesDictionary.NAME.getProperty());
if (paramName == null) {
- log.error("Cannot find the property " + GraphPropertiesDictionary.NAME.getProperty()
- + " on the edge " + propertyValueEdge);
+ log.error("Cannot find the property {} on the edge {}", GraphPropertiesDictionary.NAME.getProperty(), propertyValueEdge);
return TitanOperationStatus.INVALID_ELEMENT;
}
actualValues.put(paramName, propertyValueData.getValue());
@@ -989,18 +863,16 @@ public class RequirementOperation implements IRequirementOperation {
return TitanOperationStatus.OK;
}
- private TitanOperationStatus addCapabilityPropertiesToReqImpl(RequirementImplData reqImplData, String reqCapability,
- String nodeIdImpl, Map<String, CapabiltyInstance> propertiesValuePerCapability) {
+ private TitanOperationStatus addCapabilityPropertiesToReqImpl(RequirementImplData reqImplData, String reqCapability, String nodeIdImpl, Map<String, CapabiltyInstance> propertiesValuePerCapability) {
TitanOperationStatus result = null;
- Either<List<ImmutablePair<CapabilityData, GraphEdge>>, TitanOperationStatus> allCapabilities = capabilityOperation
- .getAllCapabilitiesPairs(nodeIdImpl);
- log.trace("Atter looking for the capabilities of resource " + nodeIdImpl + ". result is " + allCapabilities);
+ Either<List<ImmutablePair<CapabilityData, GraphEdge>>, TitanOperationStatus> allCapabilities = capabilityOperation.getAllCapabilitiesPairs(nodeIdImpl);
+ log.trace("Atter looking for the capabilities of resource {}. result is {}", nodeIdImpl, allCapabilities);
if (allCapabilities.isRight()) {
TitanOperationStatus status = allCapabilities.right().value();
if (status != TitanOperationStatus.NOT_FOUND) {
- log.error("Failed to find capabilities of resource " + nodeIdImpl + ". status is " + status);
+ log.error("Failed to find capabilities of resource {}. status is {}", nodeIdImpl, status);
return status;
}
} else {
@@ -1014,37 +886,32 @@ public class RequirementOperation implements IRequirementOperation {
GraphEdge graphEdge = entry.getValue();
- Either<String, TitanOperationStatus> capabilityNameResult = findCapabilityName(capabilityData,
- graphEdge);
+ Either<String, TitanOperationStatus> capabilityNameResult = findCapabilityName(capabilityData, graphEdge);
if (capabilityNameResult.isRight()) {
TitanOperationStatus status = capabilityNameResult.right().value();
- log.error(
- "Failed to find capability name from the edge associated to capability " + capabilityData);
+ log.error("Failed to find capability name from the edge associated to capability {}", capabilityData);
return status;
}
String capabilityName = capabilityNameResult.left().value();
- log.debug("Going to set properties of capability " + capabilityName);
+ log.debug("Going to set properties of capability {}", capabilityName);
String cabilityDataUid = capabilityData.getUniqueId();
- Either<CapabilityTypeData, TitanOperationStatus> ctDataResult = capabilityOperation
- .getCapabilityTypeOfCapability(cabilityDataUid);
+ Either<CapabilityTypeData, TitanOperationStatus> ctDataResult = capabilityOperation.getCapabilityTypeOfCapability(cabilityDataUid);
if (ctDataResult.isRight()) {
- log.error("Cannot find capability type of capbility " + cabilityDataUid + ". status is "
- + ctDataResult);
+ log.error("Cannot find capability type of capbility {}. status is {}", cabilityDataUid, ctDataResult);
TitanOperationStatus status = ctDataResult.right().value();
return status;
}
CapabilityTypeData capabilityTypeData = ctDataResult.left().value();
- Either<Map<String, PropertyDefinition>, TitanOperationStatus> propertiesStatus = findPropertiesOfCapability(
- capabilityTypeData);
+ Either<Map<String, PropertyDefinition>, TitanOperationStatus> propertiesStatus = findPropertiesOfCapability(capabilityTypeData);
if (propertiesStatus.isRight()) {
TitanOperationStatus status = propertiesStatus.right().value();
- log.error("Failed to fetch properties definitions from capability. status is " + status);
+ log.error("Failed to fetch properties definitions from capability. status is {}", status);
return status;
}
@@ -1055,43 +922,35 @@ public class RequirementOperation implements IRequirementOperation {
capabiltyInstance = propertiesValuePerCapability.get(capabilityName);
}
- Either<CapabilityInstData, TitanOperationStatus> createCapabilityInstanceNode = createCapabilityInstanceNode(
- capabilityName, reqImplData);
+ Either<CapabilityInstData, TitanOperationStatus> createCapabilityInstanceNode = createCapabilityInstanceNode(capabilityName, reqImplData);
if (createCapabilityInstanceNode.isRight()) {
TitanOperationStatus status = createCapabilityInstanceNode.right().value();
- log.error("Failed to create capability instance node (" + capabilityName + ") in graph. status is "
- + status);
+ log.error("Failed to create capability instance node ({}) in graph. status is {}", capabilityName, status);
return status;
}
CapabilityInstData capabilityInstData = createCapabilityInstanceNode.left().value();
- Either<List<GraphRelation>, TitanOperationStatus> instanceProperties = addPropertiesToCapabilityInstance(
- properties, capabiltyInstance, capabilityInstData);
+ Either<List<GraphRelation>, TitanOperationStatus> instanceProperties = addPropertiesToCapabilityInstance(properties, capabiltyInstance, capabilityInstData);
if (instanceProperties.isRight()) {
TitanOperationStatus status = instanceProperties.right().value();
- log.debug("Failed to add properties to capability instance. status is " + status);
+ log.debug("Failed to add properties to capability instance. status is {}", status);
return status;
}
- Either<GraphRelation, TitanOperationStatus> associateCapabilityInstToCapabilityType = associateCapabilityInstToCapabilityType(
- capabilityInstData, capabilityTypeData);
+ Either<GraphRelation, TitanOperationStatus> associateCapabilityInstToCapabilityType = associateCapabilityInstToCapabilityType(capabilityInstData, capabilityTypeData);
if (associateCapabilityInstToCapabilityType.isRight()) {
TitanOperationStatus status = associateCapabilityInstToCapabilityType.right().value();
- log.error("Failed to associate capability instance " + capabilityInstData
- + " to capability type node " + capabilityTypeData + " in graph. status is " + status);
+ log.error("Failed to associate capability instance {} to capability type node {} in graph. status is {}", capabilityInstData, capabilityTypeData, status);
return status;
}
- Either<GraphRelation, TitanOperationStatus> associateCapabilityInst = associateRequirementImplToCapabilityInst(
- reqImplData, capabilityInstData, capabilityName);
+ Either<GraphRelation, TitanOperationStatus> associateCapabilityInst = associateRequirementImplToCapabilityInst(reqImplData, capabilityInstData, capabilityName);
if (associateCapabilityInst.isRight()) {
TitanOperationStatus status = associateCapabilityInst.right().value();
- log.error("Failed to associate requirement impl " + reqImplData + " to capability instance node "
- + capabilityInstData + " of capability " + capabilityName + ") in graph. status is "
- + status);
+ log.error("Failed to associate requirement impl {} to capability instance node {} of capability {}) in graph. status is {}", reqImplData, capabilityInstData, capabilityName, status);
return status;
}
@@ -1102,16 +961,13 @@ public class RequirementOperation implements IRequirementOperation {
return result;
}
- private Either<Map<String, PropertyDefinition>, TitanOperationStatus> findPropertiesOfCapability(
- CapabilityTypeData capabilityTypeData) {
+ private Either<Map<String, PropertyDefinition>, TitanOperationStatus> findPropertiesOfCapability(CapabilityTypeData capabilityTypeData) {
String capabilityTypeUid = capabilityTypeData.getUniqueId();
- Either<CapabilityTypeDefinition, TitanOperationStatus> capabilityTypeResult = capabilityTypeOperation
- .getCapabilityTypeByUid(capabilityTypeUid);
+ Either<CapabilityTypeDefinition, TitanOperationStatus> capabilityTypeResult = capabilityTypeOperation.getCapabilityTypeByUid(capabilityTypeUid);
if (capabilityTypeResult.isRight()) {
- log.error("Failed to find capabilityType " + capabilityTypeUid + " in the graph. status is "
- + capabilityTypeResult);
+ log.error("Failed to find capabilityType {} in the graph. status is {}", capabilityTypeUid, capabilityTypeResult);
return Either.right(capabilityTypeResult.right().value());
}
@@ -1121,44 +977,37 @@ public class RequirementOperation implements IRequirementOperation {
return Either.left(properties);
}
- private Either<String, TitanOperationStatus> findCapabilityName(CapabilityData capabilityData,
- GraphEdge graphEdge) {
+ private Either<String, TitanOperationStatus> findCapabilityName(CapabilityData capabilityData, GraphEdge graphEdge) {
Map<String, Object> edgeProps = graphEdge.getProperties();
String capabilityName = (String) edgeProps.get(GraphPropertiesDictionary.NAME.getProperty());
if (capabilityName == null) {
- log.debug("Cannot find the name of the capability associated to node " + capabilityData);
+ log.debug("Cannot find the name of the capability associated to node {}", capabilityData);
return Either.right(TitanOperationStatus.NOT_FOUND);
}
return Either.left(capabilityName);
}
- private Either<GraphRelation, TitanOperationStatus> associateCapabilityInstToCapabilityType(
- CapabilityInstData capabilityInstData, CapabilityTypeData capabilityTypeData) {
+ private Either<GraphRelation, TitanOperationStatus> associateCapabilityInstToCapabilityType(CapabilityInstData capabilityInstData, CapabilityTypeData capabilityTypeData) {
- Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(capabilityInstData,
- capabilityTypeData, GraphEdgeLabels.INSTANCE_OF, null);
+ Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(capabilityInstData, capabilityTypeData, GraphEdgeLabels.INSTANCE_OF, null);
return createRelation;
}
/**
- * add property value node with default value of override value and
- * associate it to the capability instance node
+ * add property value node with default value of override value and associate it to the capability instance node
*
* @param properties
* - properties definition. old also default value
* @param capabilityInstance
* - hold also properties new value(if exists)
* @param capabilityInstData
- * - the graph node which we associate the properties value node
- * to.
+ * - the graph node which we associate the properties value node to.
* @return
*/
- private Either<List<GraphRelation>, TitanOperationStatus> addPropertiesToCapabilityInstance(
- Map<String, PropertyDefinition> properties, CapabiltyInstance capabilityInstance,
- CapabilityInstData capabilityInstData) {
+ private Either<List<GraphRelation>, TitanOperationStatus> addPropertiesToCapabilityInstance(Map<String, PropertyDefinition> properties, CapabiltyInstance capabilityInstance, CapabilityInstData capabilityInstData) {
List<GraphRelation> relationsResult = new ArrayList<GraphRelation>();
@@ -1171,31 +1020,24 @@ public class RequirementOperation implements IRequirementOperation {
String propertyValue = setPropertyValue(capabilityInstance, paramName, propertyDefinition);
- PropertyValueData propertyValueData = buildPropertyValueData(capabilityInstData.getUniqueId(),
- paramName, propertyValue);
+ PropertyValueData propertyValueData = buildPropertyValueData(capabilityInstData.getUniqueId(), paramName, propertyValue);
- log.debug("Before creating property value data node " + propertyValueData + " in graph.");
- Either<PropertyValueData, TitanOperationStatus> createNode = titanGenericDao
- .createNode(propertyValueData, PropertyValueData.class);
- log.debug("Before creating property value data node " + propertyValueData + " in graph. status is "
- + createNode);
+ log.debug("Before creating property value data node {} in graph.", propertyValueData);
+ Either<PropertyValueData, TitanOperationStatus> createNode = titanGenericDao.createNode(propertyValueData, PropertyValueData.class);
+ log.debug("Before creating property value data node {} in graph. status is {}", propertyValueData, createNode);
if (createNode.isRight()) {
TitanOperationStatus status = createNode.right().value();
- log.error("Failed to create property value node in graph " + propertyValueData + ". status is "
- + status);
+ log.error("Failed to create property value node in graph {}. status is {}", propertyValueData, status);
return Either.right(status);
}
PropertyValueData propertyValueDataCreated = createNode.left().value();
- Either<GraphRelation, TitanOperationStatus> createRelation = associateCapabilityInstToPropertyValue(
- capabilityInstData, paramName, propertyValueDataCreated);
+ Either<GraphRelation, TitanOperationStatus> createRelation = associateCapabilityInstToPropertyValue(capabilityInstData, paramName, propertyValueDataCreated);
if (createRelation.isRight()) {
TitanOperationStatus status = createNode.right().value();
- log.error("Failed to create relation between capability instance "
- + capabilityInstData.getUniqueId() + " to property value "
- + propertyValueDataCreated.getUniqueId() + " in graph. status is " + status);
+ log.error("Failed to create relation between capability instance {} to property value {} in graph. status is {}", capabilityInstData.getUniqueId(), propertyValueDataCreated.getUniqueId(), status);
return Either.right(status);
}
@@ -1207,23 +1049,18 @@ public class RequirementOperation implements IRequirementOperation {
return Either.left(relationsResult);
}
- private Either<GraphRelation, TitanOperationStatus> associateCapabilityInstToPropertyValue(
- CapabilityInstData capabilityInstData, String paramName, PropertyValueData propertyValueDataCreated) {
+ private Either<GraphRelation, TitanOperationStatus> associateCapabilityInstToPropertyValue(CapabilityInstData capabilityInstData, String paramName, PropertyValueData propertyValueDataCreated) {
Map<String, Object> edgeProps = new HashMap<String, Object>();
edgeProps.put(GraphPropertiesDictionary.NAME.getProperty(), paramName);
- log.debug("Begin creating relation between capability instance " + capabilityInstData + " to property value "
- + propertyValueDataCreated + " in graph.");
- Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(capabilityInstData,
- propertyValueDataCreated, GraphEdgeLabels.PROPERTY_VALUE, edgeProps);
- log.debug("After creating relation between capability instance " + capabilityInstData + " to property value "
- + propertyValueDataCreated + " in graph. status is " + createRelation);
+ log.debug("Begin creating relation between capability instance {} to property value {} in graph.", capabilityInstData, propertyValueDataCreated);
+ Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(capabilityInstData, propertyValueDataCreated, GraphEdgeLabels.PROPERTY_VALUE, edgeProps);
+ log.debug("After creating relation between capability instance {} to property value {} in graph. status is {}", capabilityInstData, propertyValueDataCreated, createRelation);
return createRelation;
}
- private String setPropertyValue(CapabiltyInstance capabilityInstance, String paramName,
- PropertyDefinition propertyDefinition) {
+ private String setPropertyValue(CapabiltyInstance capabilityInstance, String paramName, PropertyDefinition propertyDefinition) {
String propertyValue = NA;
if (propertyDefinition.getDefaultValue() != null) {
propertyValue = propertyDefinition.getDefaultValue();
@@ -1245,8 +1082,7 @@ public class RequirementOperation implements IRequirementOperation {
return paramName + EQUAL_SIGN + paramValue;
}
- private PropertyValueData buildPropertyValueData(String capabilityInstDataUid, String paramName,
- String propertyValue) {
+ private PropertyValueData buildPropertyValueData(String capabilityInstDataUid, String paramName, String propertyValue) {
PropertyValueData propertyValueData = new PropertyValueData();
propertyValueData.setValue(propertyValue);
String uid = UniqueIdBuilder.buildPropertyValueUniqueId(capabilityInstDataUid, paramName);
@@ -1257,8 +1093,7 @@ public class RequirementOperation implements IRequirementOperation {
return propertyValueData;
}
- private Either<CapabilityInstData, TitanOperationStatus> createCapabilityInstanceNode(String capabilityName,
- RequirementImplData reqImplData) {
+ private Either<CapabilityInstData, TitanOperationStatus> createCapabilityInstanceNode(String capabilityName, RequirementImplData reqImplData) {
CapabilityInstData capabilityInstData = new CapabilityInstData();
String uniqueId = UniqueIdBuilder.buildCapabilityInstanceUid(reqImplData.getUniqueId(), capabilityName);
@@ -1269,11 +1104,9 @@ public class RequirementOperation implements IRequirementOperation {
capabilityInstData.setCreationTime(creationDate);
capabilityInstData.setModificationTime(creationDate);
- log.debug("Before creating capability instance node in graph " + capabilityInstData);
- Either<CapabilityInstData, TitanOperationStatus> createNode = titanGenericDao.createNode(capabilityInstData,
- CapabilityInstData.class);
- log.debug(
- "After creating capability instance node in graph " + capabilityInstData + ". status is " + createNode);
+ log.debug("Before creating capability instance node in graph {}", capabilityInstData);
+ Either<CapabilityInstData, TitanOperationStatus> createNode = titanGenericDao.createNode(capabilityInstData, CapabilityInstData.class);
+ log.debug("After creating capability instance node in graph {}. status is {}", capabilityInstData, createNode);
return createNode;
}
@@ -1283,14 +1116,12 @@ public class RequirementOperation implements IRequirementOperation {
}
- private void checkImplNodeContainsReqCapability(String reqCapability,
- List<ImmutablePair<CapabilityData, GraphEdge>> capabilitiesValue) {
+ private void checkImplNodeContainsReqCapability(String reqCapability, List<ImmutablePair<CapabilityData, GraphEdge>> capabilitiesValue) {
// TODO Auto-generated method stub
}
- public Either<Map<String, List<RequirementDefinition>>, StorageOperationStatus> getAllRequirementsOfResourceOnly(
- String resourceId, boolean inTransaction) {
+ public Either<Map<String, List<RequirementDefinition>>, StorageOperationStatus> getAllRequirementsOfResourceOnly(String resourceId, boolean inTransaction) {
Either<Map<String, List<RequirementDefinition>>, StorageOperationStatus> result = null;
@@ -1298,11 +1129,10 @@ public class RequirementOperation implements IRequirementOperation {
Map<String, RequirementDefinition> requirements = new HashMap<String, RequirementDefinition>();
Set<String> caseInsensitiveReqNames = new HashSet<>();
- TitanOperationStatus status = findAllRequirementsNonRecursive(resourceId, requirements,
- caseInsensitiveReqNames);
+ TitanOperationStatus status = findAllRequirementsNonRecursive(resourceId, requirements, caseInsensitiveReqNames);
if (status != TitanOperationStatus.OK) {
- log.error("Failed to get all requirements of resource " + resourceId + ". status is " + status);
+ log.error("Failed to get all requirements of resource {}. status is {}", resourceId, status);
return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
} else {
// TODO handle requirementImpl
@@ -1332,7 +1162,7 @@ public class RequirementOperation implements IRequirementOperation {
TitanOperationStatus status = findAllRequirementsRecursively(resourceId, requirements, caseInsensitiveReqNames);
if (status != TitanOperationStatus.OK) {
- log.error("Failed to get all requirements of resource " + resourceId + ". status is " + status);
+ log.error("Failed to get all requirements of resource {}. status is {}", resourceId, status);
return Either.right(status);
} else {
log.debug("The requirements returned for resource {} are {}", resourceId, requirements);
@@ -1340,17 +1170,14 @@ public class RequirementOperation implements IRequirementOperation {
if (requirements != null) {
for (Entry<String, RequirementDefinition> entry : requirements.entrySet()) {
String reqName = entry.getKey();
- Either<RequirementImplDef, TitanOperationStatus> reqImplRes = this
- .getRequirementImplOfResource(reqName, resourceId);
+ Either<RequirementImplDef, TitanOperationStatus> reqImplRes = this.getRequirementImplOfResource(reqName, resourceId);
if (reqImplRes.isRight()) {
TitanOperationStatus reqImplResStatus = reqImplRes.right().value();
if (reqImplResStatus == TitanOperationStatus.NOT_FOUND) {
- log.debug("Cannot find implementation of requirement {} under resource {}", reqName,
- resourceId);
+ log.debug("Cannot find implementation of requirement {} under resource {}", reqName, resourceId);
} else {
- log.error("Cannot find implementation of requirement {} under resource {}", reqName,
- resourceId);
+ log.error("Cannot find implementation of requirement {} under resource {}", reqName, resourceId);
return Either.right(reqImplResStatus);
}
} else {
@@ -1361,8 +1188,7 @@ public class RequirementOperation implements IRequirementOperation {
}
}
}
- log.debug("The requirements returned for resource {} after fetching requirement impl are {}", resourceId,
- requirements);
+ log.debug("The requirements returned for resource {} after fetching requirement impl are {}", resourceId, requirements);
result = Either.left(requirements);
@@ -1372,15 +1198,13 @@ public class RequirementOperation implements IRequirementOperation {
}
@Override
- public Either<Map<String, RequirementDefinition>, StorageOperationStatus> getAllResourceRequirements(
- String resourceId, boolean inTransaction) {
+ public Either<Map<String, RequirementDefinition>, StorageOperationStatus> getAllResourceRequirements(String resourceId, boolean inTransaction) {
Either<Map<String, RequirementDefinition>, StorageOperationStatus> result = null;
try {
- Either<Map<String, RequirementDefinition>, TitanOperationStatus> internalResult = getResourceRequirements(
- resourceId);
+ Either<Map<String, RequirementDefinition>, TitanOperationStatus> internalResult = getResourceRequirements(resourceId);
if (internalResult.isRight()) {
TitanOperationStatus status = internalResult.right().value();
if (status != TitanOperationStatus.NOT_FOUND) {
@@ -1394,67 +1218,8 @@ public class RequirementOperation implements IRequirementOperation {
result = Either.left(value);
return result;
-
- // Map<String, RequirementDefinition> requirements = new
- // HashMap<String, RequirementDefinition>();
- // TitanOperationStatus status = findAllRequirementsRecursively(
- // resourceId, requirements);
- // if (status != TitanOperationStatus.OK) {
- // log.error("Failed to get all requirements of resource "
- // + resourceId + ". status is " + status);
- // return Either.right(TitanStatusConverter
- // .convertTitanStatusToStorageStatus(status));
- // } else {
- // log.debug("The requirements returned for resource "
- // + resourceId + " are " + requirements);
- //
- // if (requirements != null) {
- // for (Entry<String, RequirementDefinition> entry : requirements
- // .entrySet()) {
- // String reqName = entry.getKey();
- // Either<RequirementImplDef, TitanOperationStatus> reqImplRes =
- // this
- // .getRequirementImplOfResource(reqName,
- // resourceId);
- // if (reqImplRes.isRight()) {
- //
- // TitanOperationStatus reqImplResStatus = reqImplRes
- // .right().value();
- // if (reqImplResStatus == TitanOperationStatus.NOT_FOUND) {
- // log.warn("Cannot find implementation of requirement "
- // + reqName
- // + " under resource "
- // + resourceId);
- // } else {
- // log.error("Cannot find implementation of requirement "
- // + reqName
- // + " under resource "
- // + resourceId);
- // return Either
- // .right(TitanStatusConverter
- // .convertTitanStatusToStorageStatus(reqImplResStatus));
- // }
- // } else {
- // RequirementDefinition requirementDefinition = entry
- // .getValue();
- // RequirementImplDef requirementImplDef = reqImplRes
- // .left().value();
- // requirementDefinition
- // .setRequirementImpl(requirementImplDef);
- // }
- // }
- // }
- // log.debug("The requirements returned for resource "
- // + resourceId + " after fetching requirement impl are "
- // + requirements);
- //
- // result = Either.left(requirements);
- //
- // return result;
- // }
-
} finally {
- if (false == inTransaction) {
+ if (!inTransaction) {
if (result == null || result.isRight()) {
log.error("Going to execute rollback on graph.");
titanGenericDao.rollback();
@@ -1467,26 +1232,21 @@ public class RequirementOperation implements IRequirementOperation {
}
- public Either<Map<String, RequirementDefinition>, StorageOperationStatus> getAllResourceRequirements(
- String resourceId) {
+ public Either<Map<String, RequirementDefinition>, StorageOperationStatus> getAllResourceRequirements(String resourceId) {
return getAllResourceRequirements(resourceId, false);
}
- public TitanOperationStatus findAllRequirementsRecursively(String resourceId,
- Map<String, RequirementDefinition> requirements, Set<String> caseInsensitiveReqNames) {
+ public TitanOperationStatus findAllRequirementsRecursively(String resourceId, Map<String, RequirementDefinition> requirements, Set<String> caseInsensitiveReqNames) {
- TitanOperationStatus nonRecursiveResult = findAllRequirementsNonRecursive(resourceId, requirements,
- caseInsensitiveReqNames);
- if (!nonRecursiveResult.equals(TitanOperationStatus.OK)
- && !nonRecursiveResult.equals(TitanOperationStatus.NOT_FOUND)) {
+ TitanOperationStatus nonRecursiveResult = findAllRequirementsNonRecursive(resourceId, requirements, caseInsensitiveReqNames);
+ if (!nonRecursiveResult.equals(TitanOperationStatus.OK) && !nonRecursiveResult.equals(TitanOperationStatus.NOT_FOUND)) {
return nonRecursiveResult;
}
- Either<ImmutablePair<ResourceMetadataData, GraphEdge>, TitanOperationStatus> parentNodes = titanGenericDao
- .getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId,
- GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.Resource, ResourceMetadataData.class);
+ Either<ImmutablePair<ResourceMetadataData, GraphEdge>, TitanOperationStatus> parentNodes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.Resource,
+ ResourceMetadataData.class);
if (parentNodes.isRight()) {
TitanOperationStatus parentNodesStatus = parentNodes.right().value();
@@ -1494,15 +1254,13 @@ public class RequirementOperation implements IRequirementOperation {
log.debug("Finish to lookup for parnet requirements");
return TitanOperationStatus.OK;
} else {
- log.error("Failed to find parent requirements of resource {} . status is {}", resourceId,
- parentNodesStatus);
+ log.error("Failed to find parent requirements of resource {} . status is {}", resourceId, parentNodesStatus);
return parentNodesStatus;
}
}
ImmutablePair<ResourceMetadataData, GraphEdge> parnetNodePair = parentNodes.left().value();
String parentUniqueId = parnetNodePair.getKey().getMetadataDataDefinition().getUniqueId();
- TitanOperationStatus addParentReqStatus = findAllRequirementsRecursively(parentUniqueId, requirements,
- caseInsensitiveReqNames);
+ TitanOperationStatus addParentReqStatus = findAllRequirementsRecursively(parentUniqueId, requirements, caseInsensitiveReqNames);
if (addParentReqStatus != TitanOperationStatus.OK) {
log.error("Failed to fetch all requirements of resource {}", parentUniqueId);
@@ -1512,11 +1270,9 @@ public class RequirementOperation implements IRequirementOperation {
return TitanOperationStatus.OK;
}
- private TitanOperationStatus findAllRequirementsNonRecursive(String resourceId,
- Map<String, RequirementDefinition> requirements, Set<String> caseInsensitiveReqNames) {
- Either<List<ImmutablePair<RequirementData, GraphEdge>>, TitanOperationStatus> requirementNodes = titanGenericDao
- .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId,
- GraphEdgeLabels.REQUIREMENT, NodeTypeEnum.Requirement, RequirementData.class);
+ private TitanOperationStatus findAllRequirementsNonRecursive(String resourceId, Map<String, RequirementDefinition> requirements, Set<String> caseInsensitiveReqNames) {
+ Either<List<ImmutablePair<RequirementData, GraphEdge>>, TitanOperationStatus> requirementNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId, GraphEdgeLabels.REQUIREMENT,
+ NodeTypeEnum.Requirement, RequirementData.class);
if (requirementNodes.isRight()) {
TitanOperationStatus status = requirementNodes.right().value();
@@ -1533,18 +1289,17 @@ public class RequirementOperation implements IRequirementOperation {
if (edgeProps != null) {
reqName = (String) edgeProps.get(GraphPropertiesDictionary.NAME.getProperty());
if (reqName == null) {
- log.error("The requirement name is missing on the edge of requirement " + reqUniqueId);
+ log.error("The requirement name is missing on the edge of requirement {}", reqUniqueId);
return TitanOperationStatus.INVALID_ELEMENT;
}
} else {
- log.error("The requirement name is missing on the edge of requirement " + reqUniqueId);
+ log.error("The requirement name is missing on the edge of requirement {}", reqUniqueId);
return TitanOperationStatus.INVALID_ELEMENT;
}
- Either<RequirementDefinition, TitanOperationStatus> requirementDefRes = this
- .getRequirement(reqUniqueId);
+ Either<RequirementDefinition, TitanOperationStatus> requirementDefRes = this.getRequirement(reqUniqueId);
if (requirementDefRes.isRight()) {
TitanOperationStatus status = requirementDefRes.right().value();
- log.error("Failed to get requirement properties of requirement " + reqUniqueId);
+ log.error("Failed to get requirement properties of requirement {}", reqUniqueId);
return status;
}
@@ -1552,9 +1307,7 @@ public class RequirementOperation implements IRequirementOperation {
requirementDefinition.setName(reqName);
// US631462
if (caseInsensitiveReqNames.contains(reqName.toLowerCase())) {
- log.debug(
- "The requirement {} was already defined in derived resource (case insensitive). Ignore {} from resource {}",
- reqName, reqName, resourceId);
+ log.debug("The requirement {} was already defined in derived resource (case insensitive). Ignore {} from resource {}", reqName, reqName, resourceId);
} else {
requirements.put(reqName, requirementDefinition);
caseInsensitiveReqNames.add(reqName.toLowerCase());
@@ -1567,12 +1320,10 @@ public class RequirementOperation implements IRequirementOperation {
}
public StorageOperationStatus deleteRequirementFromGraph(String requirementId) {
- log.debug("Before deleting requirement from graph " + requirementId);
- Either<RequirementData, TitanOperationStatus> deleteNodeStatus = titanGenericDao.deleteNode(
- UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Requirement), requirementId, RequirementData.class);
+ log.debug("Before deleting requirement from graph {}", requirementId);
+ Either<RequirementData, TitanOperationStatus> deleteNodeStatus = titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Requirement), requirementId, RequirementData.class);
if (deleteNodeStatus.isRight()) {
- log.error("failed to delete requirement with id {}. status={}", requirementId,
- deleteNodeStatus.right().value());
+ log.error("failed to delete requirement with id {}. status={}", requirementId, deleteNodeStatus.right().value());
return DaoStatusConverter.convertTitanStatusToStorageStatus(deleteNodeStatus.right().value());
}
return StorageOperationStatus.OK;
@@ -1584,18 +1335,16 @@ public class RequirementOperation implements IRequirementOperation {
}
- public Either<Map<String, RequirementDefinition>, StorageOperationStatus> deleteAllRequirements(String resourceId,
- boolean inTransaction) {
+ public Either<Map<String, RequirementDefinition>, StorageOperationStatus> deleteAllRequirements(String resourceId, boolean inTransaction) {
Either<Map<String, RequirementDefinition>, StorageOperationStatus> result = null;
try {
- Either<Map<String, RequirementDefinition>, TitanOperationStatus> deleteAllRes = deleteAllRequirementsOfResource(
- resourceId);
+ Either<Map<String, RequirementDefinition>, TitanOperationStatus> deleteAllRes = deleteAllRequirementsOfResource(resourceId);
if (deleteAllRes.isRight()) {
TitanOperationStatus status = deleteAllRes.right().value();
if (status != TitanOperationStatus.NOT_FOUND) {
- log.error("Failed to delete requirements of resource " + resourceId + ". status is " + status);
+ log.error("Failed to delete requirements of resource {}. status is {}", resourceId, status);
}
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
return result;
@@ -1620,13 +1369,11 @@ public class RequirementOperation implements IRequirementOperation {
}
- public Either<Map<String, RequirementDefinition>, TitanOperationStatus> deleteAllRequirementsOfResource(
- String resourceId) {
+ public Either<Map<String, RequirementDefinition>, TitanOperationStatus> deleteAllRequirementsOfResource(String resourceId) {
Map<String, RequirementDefinition> requirements = new HashMap<String, RequirementDefinition>();
Set<String> caseInsensitiveReqNames = new HashSet<>();
- TitanOperationStatus requirementsRes = findAllRequirementsNonRecursive(resourceId, requirements,
- caseInsensitiveReqNames);
+ TitanOperationStatus requirementsRes = findAllRequirementsNonRecursive(resourceId, requirements, caseInsensitiveReqNames);
if (requirementsRes != TitanOperationStatus.OK) {
return Either.right(requirementsRes);
}
@@ -1640,11 +1387,10 @@ public class RequirementOperation implements IRequirementOperation {
String requirementUid = requirementDefinition.getUniqueId();
- Either<RequirementData, TitanOperationStatus> deleteNodeRes = titanGenericDao.deleteNode(
- UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Requirement), requirementUid, RequirementData.class);
+ Either<RequirementData, TitanOperationStatus> deleteNodeRes = titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Requirement), requirementUid, RequirementData.class);
if (deleteNodeRes.isRight()) {
TitanOperationStatus status = deleteNodeRes.right().value();
- log.error("Failed to delete requirement " + requirementUid + " of resource " + resourceId);
+ log.error("Failed to delete requirement {} of resource ", requirementUid, resourceId);
return Either.right(status);
}
}
@@ -1653,8 +1399,7 @@ public class RequirementOperation implements IRequirementOperation {
}
- public Map<String, List<RequirementDefinition>> convertRequirementMap(
- Map<String, RequirementDefinition> requirementMap, String ownerId, String ownerName) {
+ public Map<String, List<RequirementDefinition>> convertRequirementMap(Map<String, RequirementDefinition> requirementMap, String ownerId, String ownerName) {
Map<String, List<RequirementDefinition>> typeToRequirementMap = new HashMap<String, List<RequirementDefinition>>();
requirementMap.forEach((reqName, requirement) -> {
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ResourceOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ResourceOperation.java
index 22c693d8b3..4dce650f18 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ResourceOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ResourceOperation.java
@@ -21,6 +21,7 @@
package org.openecomp.sdc.be.model.operations.impl;
import java.util.ArrayList;
+import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
@@ -33,6 +34,8 @@ import java.util.function.Predicate;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
+import org.apache.commons.collections.CollectionUtils;
+import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
@@ -79,14 +82,19 @@ import org.openecomp.sdc.be.model.operations.api.IAttributeOperation;
import org.openecomp.sdc.be.model.operations.api.IElementOperation;
import org.openecomp.sdc.be.model.operations.api.IResourceOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.model.operations.migration.MigrationErrorInformer;
import org.openecomp.sdc.be.model.operations.utils.GraphDeleteUtil;
import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
+import org.openecomp.sdc.be.resources.data.PropertyData;
import org.openecomp.sdc.be.resources.data.ResourceMetadataData;
import org.openecomp.sdc.be.resources.data.TagData;
import org.openecomp.sdc.be.resources.data.UniqueIdData;
import org.openecomp.sdc.be.resources.data.UserData;
import org.openecomp.sdc.be.resources.data.category.CategoryData;
import org.openecomp.sdc.be.resources.data.category.SubCategoryData;
+import org.openecomp.sdc.common.api.ArtifactTypeEnum;
+import org.openecomp.sdc.common.datastructure.Wrapper;
+import org.openecomp.sdc.common.util.PairUtils;
import org.openecomp.sdc.common.util.ValidationUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -97,9 +105,11 @@ import com.google.gson.GsonBuilder;
import com.thinkaurelius.titan.core.TitanGraph;
import com.thinkaurelius.titan.core.TitanVertex;
+import fj.Function;
import fj.data.Either;
@org.springframework.stereotype.Component("resource-operation")
+@Deprecated
public class ResourceOperation extends ComponentOperation implements IResourceOperation {
public ResourceOperation() {
@@ -139,8 +149,8 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp
private GraphDeleteUtil graphDeleteUtil = new GraphDeleteUtil();
- private static Pattern uuidNewVersion = Pattern.compile("^\\d{1,}.1");
- private static Pattern uuidNormativeNewVersion = Pattern.compile("^\\d{1,}.0");
+ public static Pattern uuidNewVersion = Pattern.compile("^\\d{1,}.1");
+ public static Pattern uuidNormativeNewVersion = Pattern.compile("^\\d{1,}.0");
@Override
public Either<Resource, StorageOperationStatus> createResource(Resource resource) {
@@ -169,19 +179,18 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp
if (findUser.isRight()) {
TitanOperationStatus status = findUser.right().value();
- log.error("Cannot find user " + userId + " in the graph. status is " + status);
+ log.error("Cannot find user {} in the graph. status is {}", userId, status);
return sendError(status, StorageOperationStatus.USER_NOT_FOUND);
}
TitanVertex creatorVertex = findUser.left().value();
TitanVertex updaterVertex = creatorVertex;
-
String updaterUserId = resource.getLastUpdaterUserId();
if (updaterUserId != null && !updaterUserId.equals(userId)) {
findUser = findUserVertex(updaterUserId);
if (findUser.isRight()) {
TitanOperationStatus status = findUser.right().value();
- log.error("Cannot find user " + userId + " in the graph. status is " + status);
+ log.error("Cannot find user {} in the graph. status is {}", userId, status);
return sendError(status, StorageOperationStatus.USER_NOT_FOUND);
} else {
updaterVertex = findUser.left().value();
@@ -232,8 +241,8 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp
result = Either.right(associateCategory);
return result;
}
-
- TitanOperationStatus associateProperties = associatePropertiesToResource(metadataVertex, resourceUniqueId, resource.getProperties());
+
+ TitanOperationStatus associateProperties = associatePropertiesToResource(metadataVertex, resourceUniqueId, resource.getProperties(), derivedResources);
if (associateProperties != TitanOperationStatus.OK) {
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(associateProperties));
return result;
@@ -302,13 +311,13 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp
result = this.getResource(resourceUniqueId, true);
if (result.isRight()) {
- log.error("Cannot get full resource from the graph. status is " + result.right().value());
+ log.error("Cannot get full resource from the graph. status is {}", result.right().value());
return Either.right(result.right().value());
}
if (log.isDebugEnabled()) {
String json = prettyJson.toJson(result.left().value());
- log.debug("Resource retrieved is " + json);
+ log.debug("Resource retrieved is {}", json);
}
return result;
@@ -335,7 +344,7 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp
Either<CategoryData, StorageOperationStatus> categoryResult = elementOperation.getNewCategoryData(categoryName, NodeTypeEnum.ResourceNewCategory, CategoryData.class);
if (categoryResult.isRight()) {
StorageOperationStatus status = categoryResult.right().value();
- log.error("Cannot find category " + categoryName + " in the graph. status is " + status);
+ log.error("Cannot find category {} in the graph. status is {}", categoryName, status);
return categoryResult.right().value();
}
categoryData = categoryResult.left().value();
@@ -343,16 +352,16 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp
Either<List<ImmutablePair<SubCategoryData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceNewCategory), (String) categoryData.getUniqueId(),
GraphEdgeLabels.SUB_CATEGORY, NodeTypeEnum.ResourceSubcategory, SubCategoryData.class);
if (childrenNodes.isRight()) {
- log.debug("Faield to fetch sub categories for resource category" + categoryData.getCategoryDataDefinition().getName());
+ log.debug("Faield to fetch sub categories for resource category {}", categoryData.getCategoryDataDefinition().getName());
return DaoStatusConverter.convertTitanStatusToStorageStatus(childrenNodes.right().value());
}
for (ImmutablePair<SubCategoryData, GraphEdge> pair : childrenNodes.left().value()) {
SubCategoryData subcategoryData = pair.left;
if (subcategoryData.getSubCategoryDataDefinition().getName().equals(subcategoryName)) {
Either<GraphRelation, TitanOperationStatus> result = titanGenericDao.createRelation(resourceData, subcategoryData, GraphEdgeLabels.CATEGORY, null);
- log.debug("After associating resource " + resourceData.getUniqueId() + " to subcategory " + subcategoryData + ". Edge type is " + GraphEdgeLabels.CATEGORY);
+ log.debug("After associating resource {} to subcategory {}. Edge type is {}", resourceData.getUniqueId(), subcategoryData, GraphEdgeLabels.CATEGORY);
if (result.isRight()) {
- log.error("Faield to associate resource " + resourceData.getUniqueId() + " to category " + categoryData + ". Edge type is " + GraphEdgeLabels.CATEGORY);
+ log.error("Faield to associate resource {} to category {}. Edge type is {}", resourceData.getUniqueId(), categoryData, GraphEdgeLabels.CATEGORY);
return DaoStatusConverter.convertTitanStatusToStorageStatus(result.right().value());
}
@@ -492,15 +501,34 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp
StorageOperationStatus status = StorageOperationStatus.OK;
if (artifacts != null) {
+ Map<ArtifactDefinition, ArtifactDefinition> heatEnvMap = new HashMap<ArtifactDefinition, ArtifactDefinition>();
for (Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
ArtifactDefinition artifactDefinition = entry.getValue();
- status = artifactOperation.addArifactToComponent(artifactDefinition, resourceId, NodeTypeEnum.Resource, false, metadataVertex);
+
+ ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactDefinition.getArtifactType());
+ if(artifactType != ArtifactTypeEnum.HEAT_ENV){
+ status = artifactOperation.addArifactToComponent(artifactDefinition, resourceId, NodeTypeEnum.Resource, false, metadataVertex);
+ }else{
+ Optional<ArtifactDefinition> op = artifacts.values().stream().filter(p -> p.getUniqueId().equals(artifactDefinition.getGeneratedFromId())).findAny();
+ if(op.isPresent()){
+ heatEnvMap.put(artifactDefinition, op.get());
+ }
+
+
+ }
if (!status.equals(StorageOperationStatus.OK)) {
return status;
}
}
+ for(Entry<ArtifactDefinition, ArtifactDefinition> entry : heatEnvMap.entrySet()){
+ Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact = artifactOperation.addHeatEnvArtifact(entry.getKey(), entry.getValue(), resourceId, NodeTypeEnum.Resource, false);
+ if (addHeatEnvArtifact.isRight()) {
+ log.debug("failed to create heat env artifact on resource instance");
+ return addHeatEnvArtifact.right().value();
+ }
+ }
}
return status;
@@ -539,7 +567,7 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp
}
}
- private TitanOperationStatus associatePropertiesToResource(TitanVertex metadatVertex, String resourceId, List<PropertyDefinition> properties) {
+ private TitanOperationStatus associatePropertiesToResource(TitanVertex metadatVertex, String resourceId, List<PropertyDefinition> properties, List<ResourceMetadataData> derivedResources) {
Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = applicationDataTypeCache.getAll();
if (allDataTypes.isRight()) {
@@ -547,21 +575,82 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp
log.debug("Cannot find any data type. Status is {}.", status);
return status;
}
-
+
Map<String, PropertyDefinition> convertedProperties = new HashMap<>();
if (properties != null) {
for (PropertyDefinition propertyDefinition : properties) {
convertedProperties.put(propertyDefinition.getName(), propertyDefinition);
}
- TitanOperationStatus operationStatus = propertyOperation.addPropertiesToGraph(metadatVertex, convertedProperties, allDataTypes.left().value(), resourceId);
- return operationStatus;
+
+ Either<Map<String, PropertyDefinition>, TitanOperationStatus> getPropertiesOfAllDerivedFromRes = getPropertiesOfAllDerivedFrom(derivedResources);
+
+ if(getPropertiesOfAllDerivedFromRes.isRight()){
+ TitanOperationStatus status = getPropertiesOfAllDerivedFromRes.right().value();
+ log.debug("Cannot fetch properties of all derived from resources. Status is {}.", status);
+ return status;
+ }
+
+ Map<String, PropertyDefinition> allDerivedFromProperties = getPropertiesOfAllDerivedFromRes.left().value();
+
+ TitanOperationStatus validatePropertyNamesUniqunessStatus = validatePropertyNamesUniquness(properties, allDerivedFromProperties);
+
+ if(validatePropertyNamesUniqunessStatus != TitanOperationStatus.OK){
+ return validatePropertyNamesUniqunessStatus;
+ }
+
+ return propertyOperation.addPropertiesToGraph(metadatVertex, convertedProperties, allDataTypes.left().value(), resourceId);
}
return TitanOperationStatus.OK;
}
+ private TitanOperationStatus validatePropertyNamesUniquness(List<PropertyDefinition> properties, Map<String, PropertyDefinition> allDerivedFromProperties) {
+
+ TitanOperationStatus result = TitanOperationStatus.OK;
+ Optional<PropertyDefinition> propertyOptional= properties.stream()
+ //filters out properties with the same name and different type
+ .filter(prop -> allDerivedFromProperties.containsKey(prop.getName()) && !prop.getType().equals(allDerivedFromProperties.get(prop.getName()).getType()))
+ //Searches for any matching value
+ .findAny();
+ if(propertyOptional.isPresent()){
+ log.error("Property with name {} and type {} already exists in derived from resource. ", propertyOptional.get().getName(), allDerivedFromProperties.get( propertyOptional.get().getName()).getType());
+ result = TitanOperationStatus.ALREADY_EXIST;
+ }
+ return result;
+ }
+
+ private Either<Map<String, PropertyDefinition>, TitanOperationStatus> getPropertiesOfAllDerivedFrom(List<ResourceMetadataData> derivedResources) {
+ Map<String, PropertyDefinition> allDerivedProperties = new HashMap<>();
+ Either<Map<String, PropertyDefinition>, TitanOperationStatus> getPropertiesOfAllDerivedFromRes = Either.left(allDerivedProperties);
+ String currResourceName = null ;
+ if(!CollectionUtils.isEmpty(derivedResources)){
+ try{
+ for(int i = derivedResources.size() - 1; i >= 0 ; --i){
+ ResourceMetadataData currDerivedResource = derivedResources.get(i);
+ currResourceName = currDerivedResource.getMetadataDataDefinition().getName();
+ Either<List<ImmutablePair<PropertyData, GraphEdge>>, TitanOperationStatus> res =
+ titanGenericDao.getChildrenNodes( currDerivedResource.getUniqueIdKey(), (String)currDerivedResource.getUniqueId(), GraphEdgeLabels.PROPERTY, NodeTypeEnum.Property, PropertyData.class);
+ if(res.isRight() && res.right().value() != TitanOperationStatus.NOT_FOUND){
+ getPropertiesOfAllDerivedFromRes = Either.right(res.right().value());
+ break;
+ }else if(res.isLeft()){
+ allDerivedProperties.putAll(res.left().value().stream()
+ //Maps PropertyData converted to PropertyDefinition
+ .map(pair-> propertyOperation.convertPropertyDataToPropertyDefinition(pair.getLeft(), (String)pair.getRight().getProperties().get(GraphPropertiesDictionary.NAME.getProperty()), (String)currDerivedResource.getUniqueId()))
+ //and collects it to a map
+ .collect(Collectors.toMap(entry->entry.getName(), entry->entry)));
+ }
+ }
+ }
+ catch(Exception e){
+ log.error("Exception occured during fetch properties of resource {}. ", currResourceName);
+ }
+ }
+ return getPropertiesOfAllDerivedFromRes;
+ }
+
private TitanOperationStatus associateAttributesToResource(TitanVertex metadataVertex, List<AttributeDefinition> attributes, String resourceId) {
TitanOperationStatus operationStatus = TitanOperationStatus.OK;
@@ -605,7 +694,7 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp
// TODO Evg : need to change too..
if (derivedResources != null) {
for (ResourceMetadataData derivedResource : derivedResources) {
- log.debug("After associating resource " + resourceData.getUniqueId() + " to parent resource " + derivedResource.getUniqueId() + ". Edge type is " + GraphEdgeLabels.DERIVED_FROM);
+ log.debug("After associating resource {} to parent resource {}. Edge type is {}", resourceData.getUniqueId(), derivedResource.getUniqueId(), GraphEdgeLabels.DERIVED_FROM);
Either<GraphRelation, TitanOperationStatus> createRelationResult = titanGenericDao.createRelation(resourceData, derivedResource, GraphEdgeLabels.DERIVED_FROM, null);
if (createRelationResult.isRight()) {
log.error("Failed to associate resource {} to derived ", resourceData.getUniqueId());
@@ -636,26 +725,27 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp
List<ResourceMetadataData> resources = null;
if (getParentResources.isRight()) {
/*
- * log.debug( "Cannot find parent resource by tosca resource name" + parentResource + " in the graph. Try to find by name"); Map<String, Object> propertiesWithResourceNameToMatch = new HashMap<String, Object>();
+ * log.debug( "Cannot find parent resource by tosca resource name {} in the graph. Try to find by name", parentResource);
+ * Map<String, Object> propertiesWithResourceNameToMatch = new HashMap<String, Object>();
* propertiesWithResourceNameToMatch.put( GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFIED.name()); propertiesWithResourceNameToMatch.put( GraphPropertiesDictionary.NAME.getProperty(), parentResource);
* propertiesWithResourceNameToMatch.put( GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty( ), true);
*
* getParentResources = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, propertiesWithResourceNameToMatch, ResourceData.class); if (getParentResources.isRight()) { log.error(
* "Cannot find parent resource by tosca resource name" + parentResource + " in the graph."); return Either.right(StorageOperationStatus. PARENT_RESOURCE_NOT_FOUND); }else{ resources = getParentResources.left().value();
- *
+ * hea
* }
*/
- log.error("Cannot find parent resource by tosca resource name" + parentResource + " in the graph.");
+ log.error("Cannot find parent resource by tosca resource name {} in the graph.", parentResource);
return Either.right(StorageOperationStatus.PARENT_RESOURCE_NOT_FOUND);
} else {
resources = getParentResources.left().value();
if (resources == null || resources.size() == 0) {
- log.error("Cannot find parent resource by tosc name" + parentResource + " in the graph. resources size is empty");
+ log.error("Cannot find parent resource by tosc name {} in the graph. resources size is empty", parentResource);
return Either.right(StorageOperationStatus.PARENT_RESOURCE_NOT_FOUND);
} else {
if (resources.size() > 1) {
- log.error("Multiple parent resources called " + parentResource + " found in the graph.");
+ log.error("Multiple parent resources called {} found in the graph.", parentResource);
return Either.right(StorageOperationStatus.MULTIPLE_PARENT_RESOURCE_FOUND);
}
ResourceMetadataData parentResourceData = resources.get(0);
@@ -714,133 +804,6 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp
return getResource(uniqueId, componentParametersView, inTransaction);
}
- // public Either<Resource, StorageOperationStatus> getResource(String
- // uniqueId, boolean inTransaction) {
- //
- // Resource resource = null;
- // try {
- //
- // NodeTypeEnum resourceNodeType = NodeTypeEnum.Resource;
- // NodeTypeEnum compInstNodeType = NodeTypeEnum.Resource;
- //
- // Either<ResourceMetadataData, StorageOperationStatus>
- // componentByLabelAndId = getComponentByLabelAndId(uniqueId,
- // resourceNodeType, ResourceMetadataData.class);
- // if (componentByLabelAndId.isRight()) {
- // return Either.right(componentByLabelAndId.right().value());
- // }
- // ResourceMetadataData resourceData = componentByLabelAndId.left().value();
- // resource = convertResourceDataToResource(resourceData);
- //
- // TitanOperationStatus status = setResourceCreatorFromGraph(resource,
- // uniqueId);
- // if (status != TitanOperationStatus.OK) {
- // return
- // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- // }
- //
- // status = setResourceLastModifierFromGraph(resource, uniqueId);
- // if (status != TitanOperationStatus.OK) {
- // return
- // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- // }
- //
- // status = setResourcePropertiesFromGraph(uniqueId, resource);
- // if (status != TitanOperationStatus.OK) {
- // return
- // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- // }
- //
- // status = setResourceAttributesFromGraph(uniqueId, resource);
- // if (status != TitanOperationStatus.OK) {
- // return
- // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- // }
- //
- // status = setResourceDerivedFromGraph(uniqueId, resource);
- // if (status != TitanOperationStatus.OK) {
- // return
- // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- // }
- //
- // status = setComponentCategoriesFromGraph(resource);
- // if (status != TitanOperationStatus.OK) {
- // return
- // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- // }
- //
- // status = setComponentInstancesFromGraph(uniqueId, resource,
- // resourceNodeType, compInstNodeType);
- // if (status != TitanOperationStatus.OK) {
- // return
- // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- //
- // }
- //
- // StorageOperationStatus setRequirementsStatus =
- // setResourceRequirementsFromGraph(uniqueId, resource, true);
- // if (setRequirementsStatus != StorageOperationStatus.OK) {
- // log.error("Failed to set requirement of resource " + uniqueId + ". status
- // is " + setRequirementsStatus);
- // return Either.right(setRequirementsStatus);
- // }
- //
- // StorageOperationStatus storageStatus =
- // setResourceCapabilitiesFromGraph(uniqueId, resource);
- // if (storageStatus != StorageOperationStatus.OK) {
- // return Either.right(storageStatus);
- // }
- //
- // storageStatus = setArtifactFromGraph(uniqueId, resource);
- // if (storageStatus != StorageOperationStatus.OK) {
- // return Either.right(storageStatus);
- // }
- //
- // status = setComponentInstancesAttributesFromGraph(uniqueId, resource);
- // if (status != TitanOperationStatus.OK) {
- // return
- // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- //
- // }
- //
- // status = setComponentInstancesPropertiesFromGraph(uniqueId, resource);
- // if (status != TitanOperationStatus.OK) {
- // return
- // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- //
- // }
- //
- // storageStatus = setResourceInterfacesFromGraph(uniqueId, resource);
- // if (storageStatus != StorageOperationStatus.OK) {
- // return Either.right(storageStatus);
- // }
- //
- // storageStatus = setResourceAdditionalInformationFromGraph(uniqueId,
- // resource);
- // if (storageStatus != StorageOperationStatus.OK) {
- // return Either.right(storageStatus);
- // }
- // status = setAllVersions(resource);
- // if (status != TitanOperationStatus.OK) {
- // return
- // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- // }
- //
- // status = setGroupsFromGraph(uniqueId, resource, NodeTypeEnum.Resource);
- // if (status != TitanOperationStatus.OK) {
- // return
- // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- // }
- //
- // } finally {
- // if (false == inTransaction) {
- // titanGenericDao.commit();
- // }
- // }
- //
- // return Either.left(resource);
- // }
-
private TitanOperationStatus setComponentInstancesAttributesFromGraph(String uniqueId, Resource component) {
Map<String, List<ComponentInstanceAttribute>> resourceInstancesAttributes = new HashMap<>();
TitanOperationStatus status = TitanOperationStatus.OK;
@@ -863,114 +826,6 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp
}
- // public Either<Resource, StorageOperationStatus> getResource_tx(String
- // uniqueId, boolean inTransaction) {
- //
- // Resource resource = null;
- // try {
- //
- // NodeTypeEnum resourceNodeType = NodeTypeEnum.Resource;
- // NodeTypeEnum compInstNodeType = NodeTypeEnum.Resource;
- //
- // Either<ResourceMetadataData, StorageOperationStatus>
- // componentByLabelAndId = getComponentByLabelAndId_tx(uniqueId,
- // resourceNodeType, ResourceMetadataData.class);
- // if (componentByLabelAndId.isRight()) {
- // return Either.right(componentByLabelAndId.right().value());
- // }
- // ResourceMetadataData resourceData = componentByLabelAndId.left().value();
- // resource = convertResourceDataToResource(resourceData);
- //
- // TitanOperationStatus status = setResourceCreatorFromGraph(resource,
- // uniqueId);
- // if (status != TitanOperationStatus.OK) {
- // return
- // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- // }
- //
- // status = setResourceLastModifierFromGraph(resource, uniqueId);
- // if (status != TitanOperationStatus.OK) {
- // return
- // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- // }
- //
- // status = setResourcePropertiesFromGraph(uniqueId, resource);
- // if (status != TitanOperationStatus.OK) {
- // return
- // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- // }
- //
- // status = setResourceDerivedFromGraph(uniqueId, resource);
- // if (status != TitanOperationStatus.OK) {
- // return
- // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- // }
- //
- // status = setComponentCategoriesFromGraph(resource);
- // if (status != TitanOperationStatus.OK) {
- // return
- // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- // }
- //
- // status = setComponentInstancesFromGraph(uniqueId, resource,
- // resourceNodeType, compInstNodeType);
- // if (status != TitanOperationStatus.OK) {
- // return
- // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- //
- // }
- //
- // StorageOperationStatus setRequirementsStatus =
- // setResourceRequirementsFromGraph(uniqueId, resource, true);
- // if (setRequirementsStatus != StorageOperationStatus.OK) {
- // log.error("Failed to set requirement of resource " + uniqueId + ". status
- // is " + setRequirementsStatus);
- // return Either.right(setRequirementsStatus);
- // }
- //
- // StorageOperationStatus storageStatus =
- // setResourceCapabilitiesFromGraph(uniqueId, resource);
- // if (storageStatus != StorageOperationStatus.OK) {
- // return Either.right(storageStatus);
- // }
- //
- // storageStatus = setArtifactFromGraph(uniqueId, resource);
- // if (storageStatus != StorageOperationStatus.OK) {
- // return Either.right(storageStatus);
- // }
- //
- // status = setComponentInstancesPropertiesFromGraph(uniqueId, resource);
- // if (status != TitanOperationStatus.OK) {
- // return
- // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- //
- // }
- //
- // storageStatus = setResourceInterfacesFromGraph(uniqueId, resource);
- // if (storageStatus != StorageOperationStatus.OK) {
- // return Either.right(storageStatus);
- // }
- //
- // storageStatus = setResourceAdditionalInformationFromGraph(uniqueId,
- // resource);
- // if (storageStatus != StorageOperationStatus.OK) {
- // return Either.right(storageStatus);
- // }
- // status = setAllVersions(resource);
- // if (status != TitanOperationStatus.OK) {
- // return
- // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- // }
- //
- // } finally {
- // if (false == inTransaction) {
- // titanGenericDao.commit();
- // }
- // }
- //
- // return Either.left(resource);
- // }
-
private StorageOperationStatus setResourceAdditionalInformationFromGraph(String uniqueId, Resource resource) {
List<AdditionalInformationDefinition> additionalInformation = new ArrayList<>();
@@ -1019,7 +874,11 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp
}
} else {
Map<String, CapabilityDefinition> capabilities = result.left().value();
- if (capabilities == null || capabilities.isEmpty()) {
+ if (capabilities != null && !capabilities.isEmpty() && resource.getResourceType().equals(ResourceTypeEnum.VF)) {
+ log.error(String.format("VF %s has direct capabilities.!!!!!!!!!!!!!", resource.getName()));
+ MigrationErrorInformer.addMalformedVF(resource.getUniqueId());
+ }
+ if (capabilities == null || capabilities.isEmpty() || resource.getResourceType().equals(ResourceTypeEnum.VF)) {
Either<Map<String, List<CapabilityDefinition>>, TitanOperationStatus> eitherCapabilities = super.getCapabilities(resource, NodeTypeEnum.Resource, true);
if (eitherCapabilities.isLeft()) {
retStatus = StorageOperationStatus.OK;
@@ -1086,7 +945,11 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp
}
} else {
Map<String, RequirementDefinition> requirements = result.left().value();
- if (requirements == null || requirements.isEmpty()) {
+ if (requirements != null && !requirements.isEmpty() && resource.getResourceType().equals(ResourceTypeEnum.VF)) {
+ log.error(String.format("VF %s has direct requirements.!!!!!!!!!!!!!", resource.getName()));
+ MigrationErrorInformer.addMalformedVF(resource.getUniqueId());
+ }
+ if (requirements == null || requirements.isEmpty() || resource.getResourceType() == ResourceTypeEnum.VF) {
Either<Map<String, List<RequirementDefinition>>, TitanOperationStatus> eitherCapabilities = super.getRequirements(resource, NodeTypeEnum.Resource, true);
if (eitherCapabilities.isLeft()) {
retStatus = StorageOperationStatus.OK;
@@ -1197,10 +1060,8 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp
log.debug("Found parent node {}", value);
UserData userData = value.getKey();
- if (log.isDebugEnabled()) {
+ if (log.isDebugEnabled())
log.debug("Build resource : set last modifier userId to {}", userData.getUserId());
- }
-
String fullName = buildFullName(userData);
if (log.isDebugEnabled())
log.debug("Build resource : set last modifier full name to {}", fullName);
@@ -1222,9 +1083,8 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp
if (log.isDebugEnabled())
log.debug("Found parent node {}", value);
UserData userData = value.getKey();
- if (log.isDebugEnabled()) {
+ if (log.isDebugEnabled())
log.debug("Build resource : set creator userId to {}", userData.getUserId());
- }
String fullName = buildFullName(userData);
if (log.isDebugEnabled())
log.debug("Build resource : set creator full name to {}", fullName);
@@ -1310,7 +1170,7 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp
propertiesToMatch.put(GraphPropertiesDictionary.NAME.getProperty(), resourceName);
Either<List<ResourceMetadataData>, TitanOperationStatus> getParentResources = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, propertiesToMatch, ResourceMetadataData.class);
- log.debug("result after searching for resources called " + resourceName + " is " + getParentResources);
+ log.debug("result after searching for resources called {} is {}", resourceName, getParentResources);
if (getParentResources.isRight()) {
TitanOperationStatus titanStatus = getParentResources.right().value();
if (titanStatus == TitanOperationStatus.NOT_FOUND) {
@@ -1321,7 +1181,7 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp
} else {
List<ResourceMetadataData> value = getParentResources.left().value();
int numberOFResources = (value == null ? 0 : value.size());
- log.debug("The number of resources returned after searching for resource called " + resourceName + " is " + numberOFResources);
+ log.debug("The number of resources returned after searching for resource called {} is {}", resourceName, numberOFResources);
return Either.left(numberOFResources);
}
}
@@ -1418,67 +1278,67 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp
if (iterator != null && iterator.hasNext()) {
Vertex rootVertex = iterator.next();
TitanOperationStatus deleteChildrenNodes = graphDeleteUtil.deleteChildrenNodes(rootVertex, GraphEdgeLabels.PROPERTY);
- log.debug("After deleting properties nodes in the graph. status is " + deleteChildrenNodes);
+ log.debug("After deleting properties nodes in the graph. status is {}", deleteChildrenNodes);
if (deleteChildrenNodes != TitanOperationStatus.OK) {
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(deleteChildrenNodes));
return result;
}
StorageOperationStatus removeInterfacesFromResource = removeInterfacesFromResource(resource);
- log.debug("After deleting interfaces nodes in the graph. status is " + removeInterfacesFromResource);
+ log.debug("After deleting interfaces nodes in the graph. status is {}", removeInterfacesFromResource);
if (!removeInterfacesFromResource.equals(StorageOperationStatus.OK)) {
result = Either.right(removeInterfacesFromResource);
return result;
}
StorageOperationStatus removeArtifactsFromResource = removeArtifactsFromResource(resource);
- log.debug("After deleting artifacts nodes in the graph. status is " + removeArtifactsFromResource);
+ log.debug("After deleting artifacts nodes in the graph. status is {}", removeArtifactsFromResource);
if (!removeArtifactsFromResource.equals(StorageOperationStatus.OK)) {
result = Either.right(removeArtifactsFromResource);
return result;
}
StorageOperationStatus removeCapabilitiesFromResource = removeCapabilitiesFromResource(resource);
- log.debug("After deleting capabilities nodes in the graph. status is " + removeCapabilitiesFromResource);
+ log.debug("After deleting capabilities nodes in the graph. status is {}", removeCapabilitiesFromResource);
if (!removeCapabilitiesFromResource.equals(StorageOperationStatus.OK)) {
result = Either.right(removeCapabilitiesFromResource);
return result;
}
StorageOperationStatus removeRequirementsFromResource = removeRequirementsFromResource(resource);
- log.debug("After deleting requirements nodes in the graph. status is " + removeRequirementsFromResource);
+ log.debug("After deleting requirements nodes in the graph. status is {}", removeRequirementsFromResource);
if (!removeRequirementsFromResource.equals(StorageOperationStatus.OK)) {
result = Either.right(removeRequirementsFromResource);
return result;
}
StorageOperationStatus removeRIsFromResource = removeResourceInstanceFromResource(resource);
- log.debug("After deleting resource instance nodes in the graph. status is " + removeRIsFromResource);
+ log.debug("After deleting resource instance nodes in the graph. status is {}", removeRIsFromResource);
if (!removeRIsFromResource.equals(StorageOperationStatus.OK)) {
result = Either.right(removeRIsFromResource);
return result;
}
StorageOperationStatus removeAttributesFromResource = removeAttributesFromResource(resource);
- log.debug("After deleting requirements nodes in the graph. status is " + removeRequirementsFromResource);
+ log.debug("After deleting requirements nodes in the graph. status is {}", removeRequirementsFromResource);
if (removeAttributesFromResource != StorageOperationStatus.OK) {
result = Either.right(removeAttributesFromResource);
return result;
}
StorageOperationStatus removeInputsFromResource = removeInputsFromComponent(NodeTypeEnum.Resource, resource);
- log.debug("After deleting requirements nodes in the graph. status is " + removeInputsFromResource);
+ log.debug("After deleting requirements nodes in the graph. status is {}", removeInputsFromResource);
if (removeInputsFromResource != StorageOperationStatus.OK) {
result = Either.right(removeInputsFromResource);
return result;
}
StorageOperationStatus removeAdditionalInformationFromResource = super.deleteAdditionalInformation(NodeTypeEnum.Resource, resource.getUniqueId());
- log.debug("After deleting additional information node in the graph. status is " + removeAdditionalInformationFromResource);
+ log.debug("After deleting additional information node in the graph. status is {}", removeAdditionalInformationFromResource);
if (!removeAdditionalInformationFromResource.equals(StorageOperationStatus.OK)) {
result = Either.right(removeAdditionalInformationFromResource);
return result;
}
StorageOperationStatus removeGroupsFromResource = super.deleteGroups(NodeTypeEnum.Resource, resource.getUniqueId());
- log.debug("After deleting group nodes in the graph. status is " + removeGroupsFromResource);
+ log.debug("After deleting group nodes in the graph. status is {}", removeGroupsFromResource);
if (!removeGroupsFromResource.equals(StorageOperationStatus.OK)) {
result = Either.right(removeGroupsFromResource);
return result;
@@ -1698,12 +1558,12 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp
categoryRelation.setFrom(relationEndPoint);
Either<GraphRelation, TitanOperationStatus> deleteOutgoingRelation = titanGenericDao.deleteOutgoingRelation(categoryRelation);
if (deleteOutgoingRelation.isRight()) {
- log.error("Failed to delete category from resource " + resourceData.getUniqueId() + ". Edge type is " + GraphEdgeLabels.CATEGORY);
+ log.error("Failed to delete category from resource {}. Edge type is {}", resourceData.getUniqueId(), GraphEdgeLabels.CATEGORY);
result = DaoStatusConverter.convertTitanStatusToStorageStatus(deleteOutgoingRelation.right().value());
return result;
}
- log.debug("After removing edge from graph " + deleteOutgoingRelation);
+ log.debug("After removing edge from graph {}", deleteOutgoingRelation);
return assosiateMetadataToCategory(resource, resourceData);
}
@@ -1718,15 +1578,15 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp
lastModifierRelation.setTo(relationEndPoint);
Either<GraphRelation, TitanOperationStatus> deleteIncomingRelation = titanGenericDao.deleteIncomingRelation(lastModifierRelation);
if (deleteIncomingRelation.isRight()) {
- log.error("Failed to delete user from resource " + resourceData.getUniqueId() + ". Edge type is " + GraphEdgeLabels.LAST_MODIFIER);
+ log.error("Failed to delete user from resource {}. Edge type is {}", resourceData.getUniqueId(),GraphEdgeLabels.LAST_MODIFIER);
result = DaoStatusConverter.convertTitanStatusToStorageStatus(deleteIncomingRelation.right().value());
return result;
}
Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(modifierUserData, resourceData, GraphEdgeLabels.LAST_MODIFIER, null);
- log.debug("After associating user " + modifierUserData + " to resource " + resourceData.getUniqueId() + ". Edge type is " + GraphEdgeLabels.LAST_MODIFIER);
+ log.debug("After associating user {} to resource {}. Edge type is {}", modifierUserData, resourceData.getUniqueId(), GraphEdgeLabels.LAST_MODIFIER);
if (createRelation.isRight()) {
- log.error("Failed to associate user " + modifierUserData + " to resource " + resourceData.getUniqueId() + ". Edge type is " + GraphEdgeLabels.LAST_MODIFIER);
+ log.error("Failed to associate user {} to resource {}. Edge type is {}", modifierUserData, resourceData.getUniqueId(), GraphEdgeLabels.LAST_MODIFIER);
result = DaoStatusConverter.convertTitanStatusToStorageStatus(createRelation.right().value());
return result;
}
@@ -1783,6 +1643,30 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp
public Either<Boolean, StorageOperationStatus> validateToscaResourceNameExists(String templateName) {
return validateToscaResourceNameUniqueness(templateName, titanGenericDao);
}
+
+ //Tal G for US815447
+ public Either<Boolean, StorageOperationStatus> validateToscaResourceNameExtends(String templateNameCurrent, String templateNameExtends) {
+
+ String currentTemplateNameChecked = templateNameExtends;
+
+ while(currentTemplateNameChecked != null && !currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)){
+ Either<Resource, StorageOperationStatus> latestByToscaResourceName = getLatestByToscaResourceName(currentTemplateNameChecked, true);
+
+ if(latestByToscaResourceName.isRight()){
+ return latestByToscaResourceName.right().value() == StorageOperationStatus.NOT_FOUND ? Either.left(false) : Either.right(latestByToscaResourceName.right().value());
+ }
+
+ Resource value = latestByToscaResourceName.left().value();
+
+ if(value.getDerivedFrom() != null){
+ currentTemplateNameChecked = value.getDerivedFrom().get(0);
+ } else {
+ currentTemplateNameChecked = null;
+ }
+ }
+
+ return (currentTemplateNameChecked != null && currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) ? Either.left(true) : Either.left(false);
+ }
public Either<List<ArtifactDefinition>, StorageOperationStatus> getAdditionalArtifacts(String resourceId, boolean recursively, boolean inTransaction) {
List<ArtifactDefinition> artifacts = new ArrayList<>();
@@ -1798,12 +1682,12 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp
for (Entry<String, InterfaceDefinition> entry : interfaces.entrySet()) {
InterfaceDefinition interfaceDefinition = entry.getValue();
- Map<String, Operation> operations = interfaceDefinition.getOperations();
+ Map<String, Operation> operations = interfaceDefinition.getOperationsMap();
if (operations != null && !operations.isEmpty()) {
for (Entry<String, Operation> opEntry : operations.entrySet()) {
Operation operation = opEntry.getValue();
- ArtifactDefinition artifactDefinition = operation.getImplementation();
+ ArtifactDefinition artifactDefinition = operation.getImplementationArtifact();
if (artifactDefinition != null) {
artifacts.add(artifactDefinition);
}
@@ -1825,6 +1709,13 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp
return (Either<T, StorageOperationStatus>) getResource(id, inTransaction);
}
+ // @Override
+ // public <T> Either<T, StorageOperationStatus> getComponent_tx(String id,
+ // boolean inTransaction) {
+ // return (Either<T, StorageOperationStatus>) getResource_tx(id,
+ // inTransaction);
+ // }
+
private Optional<ImmutablePair<SubCategoryData, GraphEdge>> validateCategoryHierarcy(List<ImmutablePair<SubCategoryData, GraphEdge>> childNodes, String subCategoryName) {
Predicate<ImmutablePair<SubCategoryData, GraphEdge>> matchName = p -> p.getLeft().getSubCategoryDataDefinition().getName().equals(subCategoryName);
return childNodes.stream().filter(matchName).findAny();
@@ -1850,8 +1741,9 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp
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 = null;
+ Optional<ImmutablePair<SubCategoryData, GraphEdge>> subCategoryData;
if (categoryName != null) {
subcategories = getAllSubCategories(categoryName);
@@ -1867,20 +1759,59 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp
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);
+ ResourceMetadataData.class, resourceType);
}
- return fetchByCategoryOrSubCategoryName(subCategoryName, NodeTypeEnum.ResourceSubcategory, GraphEdgeLabels.SUB_CATEGORY.getProperty(), NodeTypeEnum.Resource, inTransaction, ResourceMetadataData.class);
+ return fetchByCategoryOrSubCategoryName(subCategoryName, NodeTypeEnum.ResourceSubcategory, GraphEdgeLabels.SUB_CATEGORY.getProperty(), NodeTypeEnum.Resource, inTransaction, ResourceMetadataData.class, resourceType);
}
- return fetchByMainCategory(subcategories.left().value(), inTransaction);
+ if(subcategories != null){
+ return fetchByMainCategory(subcategories.left().value(), inTransaction, resourceType);
+ }
+ return fetchByResourceType(NodeTypeEnum.Resource, filters.get(FilterKeyEnum.RESOURCE_TYPE), ResourceMetadataData.class, inTransaction);
}
- private <T> Either<List<T>, StorageOperationStatus> fetchByMainCategory(List<ImmutablePair<SubCategoryData, GraphEdge>> subcategories, boolean inTransaction) {
+ @SuppressWarnings("unchecked")
+ private <T, S extends ComponentMetadataData> Either<List<T>, StorageOperationStatus> fetchByResourceType(NodeTypeEnum nodeType, String resourceType,
+ Class<S> clazz, boolean inTransaction) {
+ List<T> components = null;
+ TitanOperationStatus status;
+ Wrapper<StorageOperationStatus> statusWrapper = new Wrapper<>();
+ Either<List<T>, StorageOperationStatus> result;
+ try {
+ Map<String, Object> props = new HashMap<>();
+ props.put(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), resourceType);
+ props.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true);
+ Either<List<S>, TitanOperationStatus> getResources = titanGenericDao.getByCriteria(nodeType, props, clazz);
+ if (getResources.isRight()) {
+ status = getResources.right().value();
+ if(status != TitanOperationStatus.NOT_FOUND){
+ statusWrapper.setInnerElement(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }else{
+ components = new ArrayList<>();
+ }
+ }else{
+ components = getResources.left().value().stream().
+ map(c->(T)convertComponentMetadataDataToComponent(c)).collect(Collectors.toList());
+ }
+ if(!statusWrapper.isEmpty()){
+ result = Either.right(statusWrapper.getInnerElement());
+ }else{
+ result = Either.left(components);
+ }
+ return result;
+ } finally {
+ if (!inTransaction) {
+ titanGenericDao.commit();
+ }
+ }
+ }
+
+ private <T> Either<List<T>, StorageOperationStatus> fetchByMainCategory(List<ImmutablePair<SubCategoryData, GraphEdge>> subcategories, boolean inTransaction, ResourceTypeEnum resourceType) {
List<T> components = new ArrayList<>();
for (ImmutablePair<SubCategoryData, GraphEdge> subCategory : subcategories) {
Either<List<T>, StorageOperationStatus> fetched = fetchByCategoryOrSubCategoryUid((String) subCategory.getLeft().getUniqueId(), NodeTypeEnum.ResourceSubcategory, GraphEdgeLabels.SUB_CATEGORY.getProperty(), NodeTypeEnum.Resource,
- inTransaction, ResourceMetadataData.class);
+ inTransaction, ResourceMetadataData.class, resourceType);
if (fetched.isRight()) {
// return fetched;
continue;
@@ -1906,6 +1837,52 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp
return getComponentCatalogData(NodeTypeEnum.Resource, propertiesToMatch, Resource.class, ResourceMetadataData.class, inTransaction);
}
+ @Override
+ public Either<List<Resource>, StorageOperationStatus> getAllDerivedResources(Resource resource) {
+ try {
+ Either<List<ImmutablePair<ResourceMetadataData, GraphEdge>>, TitanOperationStatus> childrenNodes = getDerivingChildren(resource);
+ return childrenNodes.either((childrenPairs) -> convertToResources(PairUtils.leftSequence(childrenPairs)),
+ (status) -> Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)));
+ } finally {
+ titanGenericDao.commit();
+ }
+ }
+
+ @Override
+ public Either<List<Resource>, StorageOperationStatus> getRootResources() {
+ Map<String, Object> rootToscaResource = new HashMap<>();
+ rootToscaResource.put(GraphPropertiesDictionary.TOSCA_RESOURCE_NAME.getProperty(), Resource.ROOT_RESOURCE);
+ return getResourceListByCriteria(rootToscaResource, false);
+ }
+
+ @Override
+ public Either<List<Resource>, StorageOperationStatus> getVFResources() {
+ Map<String, Object> rootToscaResource = new HashMap<>();
+ rootToscaResource.put(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.VF);
+ return getResourceListByCriteria(rootToscaResource, false);
+ }
+
+ @Override
+ public Either<List<Resource>, StorageOperationStatus> getAll() {
+ Either<List<Resource>, StorageOperationStatus> resourceListByCriteria = getResourceListByCriteria(new HashMap<>(), false);
+ if (resourceListByCriteria.isRight() && resourceListByCriteria.right().value() == StorageOperationStatus.NOT_FOUND) {
+ return Either.left(Collections.emptyList());
+ }
+ return resourceListByCriteria;
+ }
+
+
+ private Either<List<ImmutablePair<ResourceMetadataData, GraphEdge>>, TitanOperationStatus> getDerivingChildren(Resource resource) {
+ return titanGenericDao.getParentNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resource.getUniqueId(), GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.Resource, ResourceMetadataData.class);
+ }
+
+ private Either<List<Resource>, StorageOperationStatus> convertToResources(List<ResourceMetadataData> resourcesMetaData) {
+ List<Either<Resource, StorageOperationStatus>> resources = resourcesMetaData.stream()
+ .map(resourceMetaData -> this.getResource(resourceMetaData.getMetadataDataDefinition().getUniqueId()))
+ .collect(Collectors.toList());
+ return Either.sequenceLeft(fj.data.List.iterableList(resources)).bimap(fj.data.List::toJavaList, Function.identity());
+ }
+
protected TitanOperationStatus findResourcesPathRecursively(String resourceId, List<ResourceMetadataData> resourcesPathList) {
Either<ResourceMetadataData, TitanOperationStatus> nodeRes = this.titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId, ResourceMetadataData.class);
@@ -2106,7 +2083,7 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp
}
long endFetchAllFromCache = System.currentTimeMillis();
- log.debug("Fetch all catalog resources metadata from cache took " + (endFetchAllFromCache - startFetchAllFromCache) + " ms");
+ log.debug("Fetch all catalog resources metadata from cache took {} ms", (endFetchAllFromCache - startFetchAllFromCache));
long startFetchFromGraph = System.currentTimeMillis();
log.debug("The number of resources needed to be fetch as light component is {}", notCertifiedHighest.size());
@@ -2115,13 +2092,13 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp
log.trace("Fetch catalog resource non cached {} {}", uniqueId, data.getMetadataDataDefinition().getName());
Either<Resource, StorageOperationStatus> component = getLightComponent(uniqueId, inTransaction);
if (component.isRight()) {
- log.debug("Failed to get Service for id = " + data.getUniqueId() + " error : " + component.right().value() + " skip resource");
+ log.debug("Failed to get Service for id = {} error : {} skip resource", data.getUniqueId(), component.right().value());
} else {
result.add(component.left().value());
}
}
long endFetchFromGraph = System.currentTimeMillis();
- log.debug("Fetch catalog resources from graph took " + (endFetchFromGraph - startFetchFromGraph) + " ms");
+ log.debug("Fetch catalog resources from graph took {} ms", (endFetchFromGraph - startFetchFromGraph));
return Either.left(result);
@@ -2141,7 +2118,7 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp
return getResourceCatalogDataLatestCertifiedAndNonCertified(inTransaction, propertiesToMatch);
}
- private Either<List<Resource>, StorageOperationStatus> getResourceCatalogDataLatestCertifiedAndNonCertified(boolean inTransaction, Map<String, Object> otherToMatch) {
+ public Either<List<Resource>, StorageOperationStatus> getResourceCatalogDataLatestCertifiedAndNonCertified(boolean inTransaction, Map<String, Object> otherToMatch) {
Map<String, Object> propertiesToMatch = new HashMap<>();
if (otherToMatch != null) {
@@ -2169,7 +2146,7 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp
for (ResourceMetadataData data : listOfHighest) {
Either<Resource, StorageOperationStatus> component = getLightComponent(data.getMetadataDataDefinition().getUniqueId(), inTransaction);
if (component.isRight()) {
- log.debug("Failed to get Service for id = " + data.getUniqueId() + " error : " + component.right().value() + " skip resource");
+ log.debug("Failed to get Service for id = {} error : {} skip resource", data.getUniqueId(), component.right().value());
} else {
result.add(component.left().value());
}
@@ -2193,7 +2170,7 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp
if (resource.isLeft()) {
resources.add(resource.left().value());
} else {
- log.debug("Failed to fetch resource for name = " + data.getMetadataDataDefinition().getName() + " and id = " + data.getUniqueId());
+ log.debug("Failed to fetch resource for name = {} and id = {}", data.getUniqueId(), data.getMetadataDataDefinition().getName());
}
}
return Either.left(resources);
@@ -2253,16 +2230,11 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp
}
List<ResourceMetadataData> dataList = byCriteria.left().value();
if (dataList != null && !dataList.isEmpty()) {
- // if (dataList.size() > 1) {
- // log.debug("More that one instance of resource for name =" +
- // nameValue + " and version = " + version);
- // return Either.right(StorageOperationStatus.GENERAL_ERROR);
- // }
for (ResourceMetadataData resourceData : dataList) {
// ResourceMetadataData resourceData = dataList.get(0);
Either<Resource, StorageOperationStatus> resource = getResource(resourceData.getMetadataDataDefinition().getUniqueId(), inTransaction);
if (resource.isRight()) {
- log.debug("Failed to fetch resource for name = " + resourceData.getMetadataDataDefinition().getName() + " and id = " + resourceData.getUniqueId());
+ log.debug("Failed to fetch resource for name = {} and id = {}", resourceData.getMetadataDataDefinition().getName(), resourceData.getUniqueId());
return Either.right(resource.right().value());
}
resourcesList.add(resource.left().value());
@@ -2287,7 +2259,7 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp
}
List<Resource> resourcesList = byNamesAndVersion.left().value();
if (resourcesList.size() > 1) {
- log.debug("More that one instance of resource for name =" + name + " and version = " + version);
+ log.debug("More that one instance of resource for name = {} and version = {}", name, version);
return Either.right(StorageOperationStatus.GENERAL_ERROR);
}
return Either.left(resourcesList.get(0));
@@ -2345,7 +2317,7 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp
try {
- log.debug("In updateResource. received resource = " + (resource == null ? null : resource.toString()));
+ log.debug("In updateResource. received resource = {}", (resource == null ? null : resource.toString()));
if (resource == null) {
log.error("Resource object is null");
result = Either.right(StorageOperationStatus.BAD_REQUEST);
@@ -2355,7 +2327,7 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp
ResourceMetadataData resourceData = new ResourceMetadataData();
resourceData.getMetadataDataDefinition().setUniqueId(resource.getUniqueId());
resourceData.getMetadataDataDefinition().setHighestVersion(resource.isHighestVersion());
- log.debug("After converting resource to ResourceData. ResourceData = " + resourceData);
+ log.debug("After converting resource to ResourceData. ResourceData = {}", resourceData);
if (resourceData.getUniqueId() == null) {
log.error("Resource id is missing in the request.");
@@ -2365,14 +2337,14 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp
Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(resourceData, ResourceMetadataData.class);
if (updateNode.isRight()) {
- log.error("Failed to update resource " + resource.getUniqueId() + ". status is " + updateNode.right().value());
+ log.error("Failed to update resource {}. status is {}", resource.getUniqueId(), updateNode.right().value());
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateNode.right().value()));
return result;
}
Either<Resource, StorageOperationStatus> updatedResource = getResource(resource.getUniqueId(), true);
if (updatedResource.isRight()) {
- log.error("Resource id is missing in the request. status is " + updatedResource.right().value());
+ log.error("Resource id is missing in the request. status is {}", updatedResource.right().value());
result = Either.right(StorageOperationStatus.BAD_REQUEST);
return result;
}
@@ -2382,7 +2354,7 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp
if (log.isDebugEnabled()) {
String json = prettyJson.toJson(result.left().value());
- log.debug("Resource retrieved after update is " + json);
+ log.debug("Resource retrieved after update is {}", json);
}
return result;
@@ -2430,7 +2402,7 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp
for (ResourceMetadataData resourceData : resourceDataList) {
Either<Resource, StorageOperationStatus> resource = getResource(resourceData.getMetadataDataDefinition().getUniqueId());
if (resource.isRight()) {
- log.debug("Failed to fetch resource for id = " + resourceData.getUniqueId() + " error is " + resource.right().value());
+ log.debug("Failed to fetch resource for id = {} error is {}", resourceData.getUniqueId(), resource.right().value());
return Either.right(resource.right().value());
}
result.add(resource.left().value());
@@ -2539,20 +2511,21 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp
}
other.setVersion(version);
other.setUniqueId(null);
-
+
List<InputDefinition> inputs = other.getInputs();
Map<String, List<ComponentInstanceProperty>> inputsPropMap = new HashMap<String, List<ComponentInstanceProperty>>();
-
- if (inputs != null) {
- for (InputDefinition input : inputs) {
-
- Either<List<ComponentInstanceProperty>, TitanOperationStatus> inputPropStatus = inputOperation.getComponentInstancePropertiesByInputId(input.getUniqueId());
- if (inputPropStatus.isLeft()) {
- if (inputPropStatus.left().value() != null)
+
+ if(inputs != null){
+ for(InputDefinition input: inputs){
+
+ Either<List<ComponentInstanceProperty>, TitanOperationStatus> inputPropStatus = inputOperation.getComponentInstancePropertiesByInputId(input.getUniqueId());
+ if(inputPropStatus.isLeft()){
+ if(inputPropStatus.left().value() != null)
inputsPropMap.put(input.getName(), inputPropStatus.left().value());
-
+
}
-
+
+
}
}
@@ -2607,15 +2580,10 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp
result = this.getResource(resource.getUniqueId(), true);
if (result.isRight()) {
- log.error("Cannot get full service from the graph. status is " + result.right().value());
+ log.error("Cannot get full service from the graph. status is {}", result.right().value());
return Either.right(result.right().value());
}
- if (log.isDebugEnabled()) {
- String json = prettyJson.toJson(result.left().value());
- // log.debug("Resource retrieved is {}", json);
- }
-
return result;
} finally {
if (false == inTransaction) {
@@ -2713,13 +2681,13 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp
SubCategoryDefinition currSubcategory = currentCategory.getSubcategories().get(0);
SubCategoryDefinition newSubcategory = newCategory.getSubcategories().get(0);
if (newSubcategory.getName() != null && false == newSubcategory.getName().equals(currSubcategory.getName())) {
- log.debug("Going to update the category of the resource from " + currentCategory + " to " + newCategory);
+ log.debug("Going to update the category of the resource from {} to {}", currentCategory, newCategory);
categoryWasChanged = true;
}
}
if (categoryWasChanged) {
status = moveCategoryEdge((Resource) component, (ResourceMetadataData) componentData, newCategory);
- log.debug("Going to update the category of the resource from " + currentCategory + " to " + newCategory + ". status is " + status);
+ log.debug("Going to update the category of the resource from {} to {}. status is {}", currentCategory, newCategory, status);
}
return status;
}
@@ -2810,7 +2778,12 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp
List<ResourceMetadataData> resourceMetadataDataList = null;
Either<List<ResourceMetadataData>, TitanOperationStatus> byCsar = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, props, ResourceMetadataData.class);
if (byCsar.isRight()) {
- if (TitanOperationStatus.NOT_FOUND.equals(byCsar.right().value())) {
+ if (TitanOperationStatus.NOT_FOUND == byCsar.right().value()) {
+ //Fix Defect DE256036
+ if( StringUtils.isEmpty(systemName)){
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.NOT_FOUND));
+ }
+
props.clear();
props.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true);
props.put(GraphPropertiesDictionary.SYSTEM_NAME.getProperty(), systemName);
@@ -2820,7 +2793,7 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp
return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(bySystemname.right().value()));
}
if (bySystemname.left().value().size() > 2) {
- log.debug("getLatestResourceByCsarOrName - getByCriteria(by system name) must return only 2 latest version, but was returned - " + bySystemname.left().value().size());
+ log.debug("getLatestResourceByCsarOrName - getByCriteria(by system name) must return only 2 latest version, but was returned - {}", bySystemname.left().value().size());
return Either.right(StorageOperationStatus.GENERAL_ERROR);
}
resourceMetadataDataList = bySystemname.left().value();
@@ -2850,7 +2823,7 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp
} else {
resourceMetadataDataList = byCsar.left().value();
if (resourceMetadataDataList.size() > 2) {
- log.debug("getLatestResourceByCsarOrName - getByCriteria(by csar) must return only 2 latest version, but was returned - " + byCsar.left().value().size());
+ log.debug("getLatestResourceByCsarOrName - getByCriteria(by csar) must return only 2 latest version, but was returned - {}", byCsar.left().value().size());
return Either.right(StorageOperationStatus.GENERAL_ERROR);
}
if (resourceMetadataDataList.size() == 1) {
@@ -2889,7 +2862,7 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp
return Either.left(byCsar.left().value());
}
- private Either<Resource, StorageOperationStatus> getResource(String uniqueId, ComponentParametersView componentParametersView, boolean inTransaction) {
+ public Either<Resource, StorageOperationStatus> getResource(String uniqueId, ComponentParametersView componentParametersView, boolean inTransaction) {
Resource resource = null;
try {
@@ -2971,7 +2944,7 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp
if (false == componentParametersView.isIgnoreRequirements()) {
StorageOperationStatus setRequirementsStatus = setResourceRequirementsFromGraph(uniqueId, resource, true);
if (setRequirementsStatus != StorageOperationStatus.OK) {
- log.error("Failed to set requirement of resource " + uniqueId + ". status is " + setRequirementsStatus);
+ log.error("Failed to set requirement of resource {}. status is {}", uniqueId, setRequirementsStatus);
return Either.right(setRequirementsStatus);
}
}
@@ -2979,7 +2952,7 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp
if (false == componentParametersView.isIgnoreInputs()) {
status = setComponentInputsFromGraph(uniqueId, resource, true);
if (status != TitanOperationStatus.OK) {
- log.error("Failed to set inputs of resource " + uniqueId + ". status is " + status);
+ log.error("Failed to set inputs of resource {}. status is {}", uniqueId, status);
return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
}
@@ -3008,7 +2981,7 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp
}
if (false == componentParametersView.isIgnoreComponentInstancesProperties()) {
- status = setComponentInstancesPropertiesFromGraph(uniqueId, resource);
+ status = setComponentInstancesPropertiesFromGraph(resource);
if (status != TitanOperationStatus.OK) {
return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ServiceOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ServiceOperation.java
index 18229f9245..e503c787b5 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ServiceOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ServiceOperation.java
@@ -20,17 +20,9 @@
package org.openecomp.sdc.be.model.operations.impl;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.function.Predicate;
-import java.util.stream.Collectors;
-
-import javax.annotation.Resource;
-
+import com.thinkaurelius.titan.core.TitanGraph;
+import com.thinkaurelius.titan.core.TitanVertex;
+import fj.data.Either;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
@@ -43,18 +35,7 @@ import org.openecomp.sdc.be.datatypes.components.ServiceMetadataDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.model.AdditionalInformationDefinition;
-import org.openecomp.sdc.be.model.ArtifactDefinition;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.ComponentInstance;
-import org.openecomp.sdc.be.model.ComponentInstanceInput;
-import org.openecomp.sdc.be.model.ComponentParametersView;
-import org.openecomp.sdc.be.model.DistributionStatusEnum;
-import org.openecomp.sdc.be.model.InputDefinition;
-import org.openecomp.sdc.be.model.LifecycleStateEnum;
-import org.openecomp.sdc.be.model.Service;
-import org.openecomp.sdc.be.model.ServiceMetadataDefinition;
-import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.*;
import org.openecomp.sdc.be.model.category.CategoryDefinition;
import org.openecomp.sdc.be.model.operations.api.IArtifactOperation;
import org.openecomp.sdc.be.model.operations.api.IElementOperation;
@@ -69,11 +50,19 @@ import org.openecomp.sdc.common.util.ValidationUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.thinkaurelius.titan.core.TitanGraph;
-
-import fj.data.Either;
+import javax.annotation.Resource;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.function.Predicate;
+import java.util.stream.Collectors;
@org.springframework.stereotype.Component("service-operation")
+@Deprecated
public class ServiceOperation extends ComponentOperation implements IServiceOperation {
private static Logger log = LoggerFactory.getLogger(ServiceOperation.class.getName());
@@ -110,7 +99,7 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper
if (findUser.isRight()) {
TitanOperationStatus status = findUser.right().value();
- log.error("Cannot find user " + userId + " in the graph. status is " + status);
+ log.error("Cannot find user {} in the graph. status is {}",userId,status);
return sendError(status, StorageOperationStatus.USER_NOT_FOUND);
}
@@ -121,7 +110,7 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper
findUser = findUser(updaterUserId);
if (findUser.isRight()) {
TitanOperationStatus status = findUser.right().value();
- log.error("Cannot find user " + userId + " in the graph. status is " + status);
+ log.error("Cannot find user {} in the graph. status is {}",userId, status);
return sendError(status, StorageOperationStatus.USER_NOT_FOUND);
} else {
updaterUserData = findUser.left().value();
@@ -134,17 +123,13 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper
String categoryName = categories.get(0).getName();
if (categoryName != null) {
- Either<CategoryData, StorageOperationStatus> categoryResult = elementOperation
- .getNewCategoryData(categoryName, NodeTypeEnum.ServiceNewCategory, CategoryData.class);
+ Either<CategoryData, StorageOperationStatus> categoryResult = elementOperation.getNewCategoryData(categoryName, NodeTypeEnum.ServiceNewCategory, CategoryData.class);
if (categoryResult.isRight()) {
StorageOperationStatus status = categoryResult.right().value();
/*
- * TitanOperationStatus titanStatus = null;
- * if(ActionStatus.CATEGORY_NOT_FOUND.equals(status)){
- * titanStatus = TitanOperationStatus.NOT_FOUND; }else{
- * titanStatus = TitanOperationStatus.GENERAL_ERROR; }
+ * TitanOperationStatus titanStatus = null; if(ActionStatus.CATEGORY_NOT_FOUND.equals(status)){ titanStatus = TitanOperationStatus.NOT_FOUND; }else{ titanStatus = TitanOperationStatus.GENERAL_ERROR; }
*/
- log.error("Cannot find category " + categoryName + " in the graph. status is " + status);
+ log.error("Cannot find category {} in the graph. status is {}",categoryName,status);
return Either.right(status);
}
@@ -156,20 +141,17 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper
return Either.right(storageOperationStatus);
}
- log.debug("try to create service node on graph for id " + serviceData.getUniqueId());
- Either<ServiceMetadataData, TitanOperationStatus> createNode = titanGenericDao.createNode(serviceData,
- ServiceMetadataData.class);
+ log.debug("try to create service node on graph for id {}",serviceData.getUniqueId());
+ Either<ServiceMetadataData, TitanOperationStatus> createNode = titanGenericDao.createNode(serviceData, ServiceMetadataData.class);
if (createNode.isRight()) {
TitanOperationStatus status = createNode.right().value();
- log.error("Error returned after creating service data node " + serviceData + ". status returned is "
- + status);
+ log.error("Error returned after creating service data node {}. status returned is {}",serviceData,status);
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
return result;
}
- log.debug("create service node created on graph for id " + serviceData.getUniqueId());
+ log.debug("create service node created on graph for id {}",serviceData.getUniqueId());
- TitanOperationStatus associateMetadata = associateMetadataToComponent(serviceData, creatorUserData,
- updaterUserData, null, null);
+ TitanOperationStatus associateMetadata = associateMetadataToComponent(serviceData, creatorUserData, updaterUserData, null, null);
if (associateMetadata != TitanOperationStatus.OK) {
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(associateMetadata));
return result;
@@ -194,23 +176,20 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper
allArtifacts.putAll(service.getToscaArtifacts());
}
- StorageOperationStatus associateArtifacts = associateArtifactsToComponent(NodeTypeEnum.Service, serviceData,
- allArtifacts);
+ StorageOperationStatus associateArtifacts = associateArtifactsToComponent(NodeTypeEnum.Service, serviceData, allArtifacts);
if (associateArtifacts != StorageOperationStatus.OK) {
result = Either.right(associateArtifacts);
return result;
}
- TitanOperationStatus associateInputs = associateInputsToComponent(NodeTypeEnum.Service, serviceData,
- service.getInputs());
+ TitanOperationStatus associateInputs = associateInputsToComponent(NodeTypeEnum.Service, serviceData, service.getInputs());
if (associateInputs != TitanOperationStatus.OK) {
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(associateInputs));
return result;
}
List<AdditionalInformationDefinition> additionalInformation = service.getAdditionalInformation();
- StorageOperationStatus addAdditionalInformation = addAdditionalInformationToService(uniqueId,
- additionalInformation);
+ StorageOperationStatus addAdditionalInformation = addAdditionalInformationToService(uniqueId, additionalInformation);
if (addAdditionalInformation != StorageOperationStatus.OK) {
result = Either.right(addAdditionalInformation);
return result;
@@ -218,13 +197,13 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper
result = this.getService(uniqueId, true);
if (result.isRight()) {
- log.error("Cannot get full service from the graph. status is " + result.right().value());
+ log.error("Cannot get full service from the graph. status is {}", result.right().value());
return Either.right(result.right().value());
}
if (log.isDebugEnabled()) {
String json = prettyJson.toJson(result.left().value());
- log.debug("Service retrieved is " + json);
+ log.debug("Service retrieved is {}",json);
}
return result;
@@ -242,24 +221,20 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper
}
}
- private TitanOperationStatus associateMetadataCategoryToComponent(ServiceMetadataData serviceData,
- CategoryData categoryData) {
+ private TitanOperationStatus associateMetadataCategoryToComponent(ServiceMetadataData serviceData, CategoryData categoryData) {
Either<GraphRelation, TitanOperationStatus> result;
if (categoryData != null) {
result = titanGenericDao.createRelation(serviceData, categoryData, GraphEdgeLabels.CATEGORY, null);
- log.debug("After associating component " + serviceData.getUniqueId() + " to category " + categoryData
- + ". Edge type is " + GraphEdgeLabels.CATEGORY);
+ log.debug("After associating component {} to category {}. Edge type is {}",serviceData.getUniqueId(),categoryData,GraphEdgeLabels.CATEGORY);
if (result.isRight()) {
- log.error("Faield to associate component " + serviceData.getUniqueId() + " to category " + categoryData
- + ". Edge type is " + GraphEdgeLabels.CATEGORY);
+ log.error("Faield to associate component {} to category {}. Edge type is {}",serviceData.getUniqueId(),categoryData,GraphEdgeLabels.CATEGORY);
return result.right().value();
}
}
return TitanOperationStatus.OK;
}
- private StorageOperationStatus addAdditionalInformationToService(String resourceUniqueId,
- List<AdditionalInformationDefinition> additionalInformation) {
+ private StorageOperationStatus addAdditionalInformationToService(String resourceUniqueId, List<AdditionalInformationDefinition> additionalInformation) {
StorageOperationStatus result = null;
@@ -267,13 +242,10 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper
result = super.addAdditionalInformation(NodeTypeEnum.Service, resourceUniqueId, null);
} else {
if (additionalInformation.size() == 1) {
- result = super.addAdditionalInformation(NodeTypeEnum.Service, resourceUniqueId,
- additionalInformation.get(0));
+ result = super.addAdditionalInformation(NodeTypeEnum.Service, resourceUniqueId, additionalInformation.get(0));
} else {
result = StorageOperationStatus.BAD_REQUEST;
- log.info(
- "Cannot create resource with more than one additional information object. The number of received object is "
- + additionalInformation.size());
+ log.info("Cannot create resource with more than one additional information object. The number of received object is {}", additionalInformation.size());
}
}
return result;
@@ -283,8 +255,7 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper
return cloneService(other, version, null, inTransaction);
}
- public Either<Service, StorageOperationStatus> cloneService(Service other, String version,
- LifecycleStateEnum targetLifecycle, boolean inTransaction) {
+ public Either<Service, StorageOperationStatus> cloneService(Service other, String version, LifecycleStateEnum targetLifecycle, boolean inTransaction) {
Either<Service, StorageOperationStatus> result = null;
try {
@@ -292,28 +263,26 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper
other.setVersion(version);
other.setUniqueId(null);
- Either<Integer, StorageOperationStatus> counterStatus = getComponentInstanceCoutner(origServiceId,
- NodeTypeEnum.Service);
+ Either<Integer, StorageOperationStatus> counterStatus = getComponentInstanceCoutner(origServiceId, NodeTypeEnum.Service);
if (counterStatus.isRight()) {
StorageOperationStatus status = counterStatus.right().value();
- log.error("failed to get resource instance counter on service {}. status={}", origServiceId,
- counterStatus);
+ log.error("failed to get resource instance counter on service {}. status={}", origServiceId, counterStatus);
result = Either.right(status);
return result;
}
Map<String, List<ComponentInstanceInput>> inputsValuesMap = new HashMap<String, List<ComponentInstanceInput>>();
List<InputDefinition> inputs = other.getInputs();
- if(inputs != null){
- for(InputDefinition input: inputs){
-
- Either<List<ComponentInstanceInput>, TitanOperationStatus> inputStatus = inputOperation.getComponentInstanceInputsByInputId(input.getUniqueId());
-
- if(inputStatus.isLeft()){
- if(inputStatus.left().value() != null)
- inputsValuesMap.put(input.getName(), inputStatus.left().value());
- }
+ if (inputs != null) {
+ for (InputDefinition input : inputs) {
+
+ Either<List<ComponentInstanceInput>, TitanOperationStatus> inputStatus = inputOperation
+ .getComponentInstanceInputsByInputId(input.getUniqueId());
+
+ if (inputStatus.isLeft() && inputStatus.left().value() != null) {
+ inputsValuesMap.put(input.getName(), inputStatus.left().value());
+ }
}
- }
+ }
Either<Service, StorageOperationStatus> createServiceMD = createService(other, true);
@@ -333,19 +302,17 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper
return result;
}
- Either<Integer, StorageOperationStatus> setResourceInstanceCounter = setComponentInstanceCounter(
- service.getUniqueId(), NodeTypeEnum.Service, counterStatus.left().value(), true);
+ Either<Integer, StorageOperationStatus> setResourceInstanceCounter = setComponentInstanceCounter(service.getUniqueId(), NodeTypeEnum.Service, counterStatus.left().value(), true);
if (setResourceInstanceCounter.isRight()) {
StorageOperationStatus status = setResourceInstanceCounter.right().value();
- log.error("failed to set resource instance counter on service {}. status={}", service.getUniqueId(),
- setResourceInstanceCounter);
+ log.error("failed to set resource instance counter on service {}. status={}", service.getUniqueId(), setResourceInstanceCounter);
result = Either.right(status);
return result;
}
result = this.getService(service.getUniqueId(), true);
if (result.isRight()) {
- log.error("Cannot get full service from the graph. status is " + result.right().value());
+ log.error("Cannot get full service from the graph. status is {}", result.right().value());
return Either.right(result.right().value());
}
@@ -369,22 +336,18 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper
}
private ServiceMetadataData getServiceMetaDataFromService(Service service) {
- ServiceMetadataData serviceData = new ServiceMetadataData(
- (ServiceMetadataDataDefinition) service.getComponentMetadataDefinition().getMetadataDataDefinition());
+ ServiceMetadataData serviceData = new ServiceMetadataData((ServiceMetadataDataDefinition) service.getComponentMetadataDefinition().getMetadataDataDefinition());
if (service.getNormalizedName() == null || service.getNormalizedName().isEmpty()) {
- serviceData.getMetadataDataDefinition()
- .setNormalizedName(ValidationUtils.normaliseComponentName(service.getName()));
+ serviceData.getMetadataDataDefinition().setNormalizedName(ValidationUtils.normaliseComponentName(service.getName()));
}
if (service.getSystemName() == null || service.getSystemName().isEmpty()) {
- serviceData.getMetadataDataDefinition()
- .setSystemName(ValidationUtils.convertToSystemName(service.getName()));
+ serviceData.getMetadataDataDefinition().setSystemName(ValidationUtils.convertToSystemName(service.getName()));
}
return serviceData;
}
- private Either<Service, StorageOperationStatus> sendError(TitanOperationStatus status,
- StorageOperationStatus statusIfNotFound) {
+ private Either<Service, StorageOperationStatus> sendError(TitanOperationStatus status, StorageOperationStatus statusIfNotFound) {
Either<Service, StorageOperationStatus> result;
if (status == TitanOperationStatus.NOT_FOUND) {
result = Either.right(statusIfNotFound);
@@ -406,128 +369,8 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper
ComponentParametersView componentParametersView = new ComponentParametersView();
return getService(uniqueId, componentParametersView, inTransaction);
}
- // public Either<Service, StorageOperationStatus> getService(String
- // uniqueId, boolean inTransaction) {
- //
- // Service service = null;
- // Either<Service, StorageOperationStatus> result = null;
- // try {
- //
- // NodeTypeEnum serviceNodeType = NodeTypeEnum.Service;
- // NodeTypeEnum compInstNodeType = NodeTypeEnum.Resource;
- //
- // Either<ServiceMetadataData, StorageOperationStatus> getComponentByLabel =
- // getComponentByLabelAndId(uniqueId, serviceNodeType,
- // ServiceMetadataData.class);
- // if (getComponentByLabel.isRight()) {
- // result = Either.right(getComponentByLabel.right().value());
- // return result;
- // }
- // ServiceMetadataData serviceData = getComponentByLabel.left().value();
- // service = convertServiceDataToService(serviceData);
- //
- // TitanOperationStatus status = setComponentCreatorFromGraph(service,
- // uniqueId, serviceNodeType);
- // if (status != TitanOperationStatus.OK) {
- // result =
- // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- // return result;
- // }
- //
- // status = setComponentLastModifierFromGraph(service, uniqueId,
- // serviceNodeType);
- // if (status != TitanOperationStatus.OK) {
- // result =
- // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- // return result;
- //
- // }
- // status = setComponentCategoriesFromGraph(service);
- // if (status != TitanOperationStatus.OK) {
- // result =
- // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- // return result;
- //
- // }
- //
- // // status = setServicePropertiesFromGraph(uniqueId, resource, vertex);
- // // if (status != TitanOperationStatus.OK) {
- // // return
- // Either.right(TitanStatusConverter.convertTitanStatusToStorageStatus(status));
- // // }
- //
- // StorageOperationStatus storageStatus = setArtifactFromGraph(uniqueId,
- // service, serviceNodeType, artifactOperation);
- // if (storageStatus != StorageOperationStatus.OK) {
- // result = Either.right(storageStatus);
- // return result;
- // }
- //
- // status = setComponentInstancesFromGraph(uniqueId, service,
- // serviceNodeType, compInstNodeType);
- // if (status != TitanOperationStatus.OK) {
- // result =
- // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- // return result;
- //
- // }
- //
- // status = setComponentInstancesPropertiesFromGraph(uniqueId, service);
- // if (status != TitanOperationStatus.OK) {
- // result =
- // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- // return result;
- // }
- //
- // status = setCapabilitiesFromGraph(uniqueId, service,
- // NodeTypeEnum.Service);
- // if (status != TitanOperationStatus.OK) {
- // result =
- // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- // return result;
- // }
- //
- // status = setRequirementsFromGraph( uniqueId, service,
- // NodeTypeEnum.Service);
- // if (status != TitanOperationStatus.OK) {
- // result =
- // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- // return result;
- // }
- //
- // status = setAllVersions(service);
- // if (status != TitanOperationStatus.OK) {
- // return
- // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- // }
- //
- // status = setServiceAdditionalInformationFromGraph(uniqueId, service);
- // if (status != TitanOperationStatus.OK) {
- // return
- // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- // }
- //
- // status = setGroupsFromGraph(uniqueId, service, NodeTypeEnum.Resource);
- // if (status != TitanOperationStatus.OK) {
- // return
- // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- // }
- //
- // result = Either.left(service);
- // return result;
- // } finally {
- // if (false == inTransaction) {
- // if (result == null || result.isRight()) {
- // titanGenericDao.rollback();
- // } else {
- // titanGenericDao.commit();
- // }
- // }
- // }
- // }
- public Either<Service, StorageOperationStatus> getService(String uniqueId,
- ComponentParametersView componentParametersView, boolean inTransaction) {
+ public Either<Service, StorageOperationStatus> getService(String uniqueId, ComponentParametersView componentParametersView, boolean inTransaction) {
Service service = null;
Either<Service, StorageOperationStatus> result = null;
@@ -536,8 +379,7 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper
NodeTypeEnum serviceNodeType = NodeTypeEnum.Service;
NodeTypeEnum compInstNodeType = NodeTypeEnum.Resource;
- Either<ServiceMetadataData, StorageOperationStatus> getComponentByLabel = getComponentByLabelAndId(uniqueId,
- serviceNodeType, ServiceMetadataData.class);
+ Either<ServiceMetadataData, StorageOperationStatus> getComponentByLabel = getComponentByLabelAndId(uniqueId, serviceNodeType, ServiceMetadataData.class);
if (getComponentByLabel.isRight()) {
result = Either.right(getComponentByLabel.right().value());
return result;
@@ -546,12 +388,10 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper
// Try to fetch resource from the cache. The resource will be
// fetched only if the time on the cache equals to
// the time on the graph.
- Either<Service, ActionStatus> componentFromCacheIfUpToDate = this.getComponentFromCacheIfUpToDate(uniqueId,
- serviceData, componentParametersView, Service.class, ComponentTypeEnum.SERVICE);
+ Either<Service, ActionStatus> componentFromCacheIfUpToDate = this.getComponentFromCacheIfUpToDate(uniqueId, serviceData, componentParametersView, Service.class, ComponentTypeEnum.SERVICE);
if (componentFromCacheIfUpToDate.isLeft()) {
Service cachedService = componentFromCacheIfUpToDate.left().value();
- log.debug("Service {} with uid {} was fetched from cache.", cachedService.getName(),
- cachedService.getUniqueId());
+ log.debug("Service {} with uid {} was fetched from cache.", cachedService.getName(), cachedService.getUniqueId());
return Either.left(cachedService);
}
@@ -580,25 +420,15 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper
}
}
- // status = setServicePropertiesFromGraph(uniqueId, resource,
- // vertex);
- // if (status != TitanOperationStatus.OK) {
- // return
- // Either.right(TitanStatusConverter.convertTitanStatusToStorageStatus(status));
- // }
-
if (false == componentParametersView.isIgnoreArtifacts()) {
- StorageOperationStatus storageStatus = setArtifactFromGraph(uniqueId, service, serviceNodeType,
- artifactOperation);
+ StorageOperationStatus storageStatus = setArtifactFromGraph(uniqueId, service, serviceNodeType, artifactOperation);
if (storageStatus != StorageOperationStatus.OK) {
result = Either.right(storageStatus);
return result;
}
}
- if (false == componentParametersView.isIgnoreComponentInstances()
- || false == componentParametersView.isIgnoreComponentInstancesProperties()
- || false == componentParametersView.isIgnoreCapabilities()
+ if (false == componentParametersView.isIgnoreComponentInstances() || false == componentParametersView.isIgnoreComponentInstancesProperties() || false == componentParametersView.isIgnoreCapabilities()
|| false == componentParametersView.isIgnoreRequirements()) {
status = setComponentInstancesFromGraph(uniqueId, service, serviceNodeType, compInstNodeType);
if (status != TitanOperationStatus.OK) {
@@ -608,7 +438,7 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper
}
}
if (false == componentParametersView.isIgnoreComponentInstancesProperties()) {
- status = setComponentInstancesPropertiesFromGraph(uniqueId, service);
+ status = setComponentInstancesPropertiesFromGraph(service);
if (status != TitanOperationStatus.OK) {
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
return result;
@@ -650,7 +480,7 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper
if (false == componentParametersView.isIgnoreInputs()) {
status = setComponentInputsFromGraph(uniqueId, service, true);
if (status != TitanOperationStatus.OK) {
- log.error("Failed to set inputs of resource " + uniqueId + ". status is " + status);
+ log.error("Failed to set inputs of resource {}. status is {}",uniqueId,status);
return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
}
@@ -795,19 +625,17 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper
TitanOperationStatus setComponentCategoriesFromGraph(Component service) {
String uniqueId = service.getUniqueId();
- Either<List<ImmutablePair<CategoryData, GraphEdge>>, TitanOperationStatus> parentNode = titanGenericDao
- .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Service), uniqueId,
- GraphEdgeLabels.CATEGORY, NodeTypeEnum.ServiceNewCategory, CategoryData.class);
+ Either<List<ImmutablePair<CategoryData, GraphEdge>>, TitanOperationStatus> parentNode = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Service), uniqueId, GraphEdgeLabels.CATEGORY,
+ NodeTypeEnum.ServiceNewCategory, CategoryData.class);
if (parentNode.isRight()) {
return parentNode.right().value();
}
List<ImmutablePair<CategoryData, GraphEdge>> listValue = parentNode.left().value();
if (log.isDebugEnabled())
- log.debug("Result after looking for category nodes pointed by service {}. status is {}", uniqueId,
- listValue);
+ log.debug("Result after looking for category nodes pointed by service {}. status is {}", uniqueId, listValue);
if (listValue.size() > 1) {
- log.error("Multiple edges foud between resource " + uniqueId + " to category nodes.");
+ log.error("Multiple edges foud between resource {} to category nodes.",uniqueId);
}
ImmutablePair<CategoryData, GraphEdge> value = listValue.get(0);
if (log.isDebugEnabled())
@@ -836,59 +664,52 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper
Either<TitanGraph, TitanOperationStatus> graphResult = titanGenericDao.getGraph();
if (graphResult.isRight()) {
- result = Either
- .right(DaoStatusConverter.convertTitanStatusToStorageStatus(graphResult.right().value()));
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graphResult.right().value()));
return result;
}
- Either<ServiceMetadataData, TitanOperationStatus> serviceNode = titanGenericDao.getNode(
- UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Service), serviceId, ServiceMetadataData.class);
+ Either<ServiceMetadataData, TitanOperationStatus> serviceNode = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Service), serviceId, ServiceMetadataData.class);
if (serviceNode.isRight()) {
TitanOperationStatus status = serviceNode.right().value();
- log.error("Failed to find service " + serviceId + ". status is " + status);
+ log.error("Failed to find service {}. status is {}",serviceId,status);
return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
}
Either<Service, StorageOperationStatus> serviceRes = getService(serviceId, true);
if (serviceRes.isRight()) {
StorageOperationStatus status = serviceRes.right().value();
- log.error("Failed to find sevice " + serviceId + ".status is " + status);
+ log.error("Failed to find sevice {}.status is {}",serviceId,status);
result = Either.right(status);
return result;
}
Service service = serviceRes.left().value();
- Either<List<ComponentInstance>, StorageOperationStatus> deleteAllResourceInstancesRes = componentInstanceOperation
- .deleteAllComponentInstances(serviceId, NodeTypeEnum.Service, true);
- log.debug("After deleting resource instances under service " + serviceId + ".Result is "
- + deleteAllResourceInstancesRes);
+ Either<List<ComponentInstance>, StorageOperationStatus> deleteAllResourceInstancesRes = componentInstanceOperation.deleteAllComponentInstances(serviceId, NodeTypeEnum.Service, true);
+ log.debug("After deleting resource instances under service {}.Result is {}",serviceId,deleteAllResourceInstancesRes);
if (deleteAllResourceInstancesRes.isRight()) {
StorageOperationStatus status = deleteAllResourceInstancesRes.right().value();
if (status != StorageOperationStatus.NOT_FOUND) {
- log.error(
- "Failed to delete resource instances under service " + serviceId + " .status is " + status);
+ log.error("Failed to delete resource instances under service {} .status is ",serviceId,status);
result = Either.right(status);
return result;
}
}
- StorageOperationStatus removeArtifactsFromResource = removeArtifactsFromComponent(service,
- NodeTypeEnum.Service);
- log.debug("After deleting artifacts nodes in the graph. status is " + removeArtifactsFromResource);
+ StorageOperationStatus removeArtifactsFromResource = removeArtifactsFromComponent(service, NodeTypeEnum.Service);
+ log.debug("After deleting artifacts nodes in the graph. status is {}",removeArtifactsFromResource);
if (!removeArtifactsFromResource.equals(StorageOperationStatus.OK)) {
result = Either.right(removeArtifactsFromResource);
return result;
}
StorageOperationStatus removeInputsFromResource = removeInputsFromComponent(NodeTypeEnum.Service, service);
- log.debug("After deleting requirements nodes in the graph. status is " + removeInputsFromResource);
+ log.debug("After deleting requirements nodes in the graph. status is {}",removeInputsFromResource);
if (removeInputsFromResource != StorageOperationStatus.OK) {
result = Either.right(removeInputsFromResource);
return result;
}
- Either<List<ImmutablePair<PropertyData, GraphEdge>>, TitanOperationStatus> deleteChildrenNodesRes = titanGenericDao
- .deleteChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Service), serviceId,
- GraphEdgeLabels.PROPERTY, NodeTypeEnum.Property, PropertyData.class);
+ Either<List<ImmutablePair<PropertyData, GraphEdge>>, TitanOperationStatus> deleteChildrenNodesRes = titanGenericDao.deleteChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Service), serviceId, GraphEdgeLabels.PROPERTY,
+ NodeTypeEnum.Property, PropertyData.class);
if (deleteChildrenNodesRes.isRight()) {
TitanOperationStatus status = deleteChildrenNodesRes.right().value();
@@ -898,27 +719,24 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper
}
}
- StorageOperationStatus removeAdditionalInformationFromService = super.deleteAdditionalInformation(
- NodeTypeEnum.Service, serviceId);
- log.debug("After deleting additional information node in the graph. status is "
- + removeAdditionalInformationFromService);
+ StorageOperationStatus removeAdditionalInformationFromService = super.deleteAdditionalInformation(NodeTypeEnum.Service, serviceId);
+ log.debug("After deleting additional information node in the graph. status is {}",removeAdditionalInformationFromService);
if (!removeAdditionalInformationFromService.equals(StorageOperationStatus.OK)) {
result = Either.right(removeAdditionalInformationFromService);
return result;
}
StorageOperationStatus removeGroupsFromService = super.deleteGroups(NodeTypeEnum.Service, serviceId);
- log.debug("After deleting group nodes in the graph. status is " + removeGroupsFromService);
+ log.debug("After deleting group nodes in the graph. status is {}",removeGroupsFromService);
if (!removeGroupsFromService.equals(StorageOperationStatus.OK)) {
result = Either.right(removeGroupsFromService);
return result;
}
- Either<ServiceMetadataData, TitanOperationStatus> deleteServiceNodeRes = titanGenericDao
- .deleteNode(serviceNode.left().value(), ServiceMetadataData.class);
+ Either<ServiceMetadataData, TitanOperationStatus> deleteServiceNodeRes = titanGenericDao.deleteNode(serviceNode.left().value(), ServiceMetadataData.class);
if (deleteServiceNodeRes.isRight()) {
TitanOperationStatus status = deleteServiceNodeRes.right().value();
- log.error("Failed to delete service node " + serviceId + ". status is " + status);
+ log.error("Failed to delete service node {}. status is {}",serviceId, status);
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
return result;
}
@@ -946,8 +764,7 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper
}
private Service convertServiceDataToService(ServiceMetadataData serviceData) {
- ServiceMetadataDefinition serviceMetadataDefinition = new ServiceMetadataDefinition(
- (ServiceMetadataDataDefinition) serviceData.getMetadataDataDefinition());
+ ServiceMetadataDefinition serviceMetadataDefinition = new ServiceMetadataDefinition((ServiceMetadataDataDefinition) serviceData.getMetadataDataDefinition());
Service service = new Service(serviceMetadataDefinition);
@@ -964,12 +781,11 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper
return Either.left(clazz.cast(component.left().value()));
}
+ @Override
@SuppressWarnings("unchecked")
- public Either<List<Service>, StorageOperationStatus> getFollowed(String userId,
- Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates, boolean inTransaction) {
+ public Either<List<Service>, StorageOperationStatus> getFollowed(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates, boolean inTransaction) {
- return (Either<List<Service>, StorageOperationStatus>) (Either<?, StorageOperationStatus>) getFollowedComponent(
- userId, lifecycleStates, lastStateStates, inTransaction, titanGenericDao, NodeTypeEnum.Service);
+ return (Either<List<Service>, StorageOperationStatus>) (Either<?, StorageOperationStatus>) getFollowedComponent(userId, lifecycleStates, lastStateStates, inTransaction, titanGenericDao, NodeTypeEnum.Service);
}
@SuppressWarnings("unchecked")
@@ -978,24 +794,14 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper
return (Either<T, StorageOperationStatus>) getService(id, inTransaction);
}
- // @Override
- // public <T> Either<T, StorageOperationStatus> getComponent_tx(String id,
- // boolean inTransaction) {
- // return (Either<T, StorageOperationStatus>) getService_tx(id,
- // inTransaction);
- // }
-
@Override
- public Either<Set<Service>, StorageOperationStatus> getCatalogData(Map<String, Object> propertiesToMatch,
- boolean inTransaction) {
- return getComponentCatalogData(NodeTypeEnum.Service, propertiesToMatch, Service.class,
- ServiceMetadataData.class, inTransaction);
+ public Either<Set<Service>, StorageOperationStatus> getCatalogData(Map<String, Object> propertiesToMatch, boolean inTransaction) {
+ return getComponentCatalogData(NodeTypeEnum.Service, propertiesToMatch, Service.class, ServiceMetadataData.class, inTransaction);
}
@Override
public Either<Service, StorageOperationStatus> updateService(Service service, boolean inTransaction) {
- Either<Service, StorageOperationStatus> result = updateComponent(service, inTransaction, titanGenericDao,
- Service.class, NodeTypeEnum.Service);
+ Either<Service, StorageOperationStatus> result = updateComponent(service, inTransaction, titanGenericDao, Service.class, NodeTypeEnum.Service);
return result;
}
@@ -1008,8 +814,7 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper
@SuppressWarnings("unchecked")
@Override
public Either<Component, StorageOperationStatus> deleteComponent(String id, boolean inTransaction) {
- return (Either<Component, StorageOperationStatus>) (Either<?, StorageOperationStatus>) deleteService(id,
- inTransaction);
+ return (Either<Component, StorageOperationStatus>) (Either<?, StorageOperationStatus>) deleteService(id, inTransaction);
}
@Override
@@ -1023,8 +828,7 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper
}
@Override
- public <T> Either<List<T>, StorageOperationStatus> getFilteredComponents(Map<FilterKeyEnum, String> filters,
- boolean inTransaction) {
+ public <T> Either<List<T>, StorageOperationStatus> getFilteredComponents(Map<FilterKeyEnum, String> filters, boolean inTransaction) {
Either<List<T>, StorageOperationStatus> components = null;
String categoryName = filters.get(FilterKeyEnum.CATEGORY);
@@ -1036,13 +840,10 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper
}
if (categoryName != null) { // primary filter
- components = fetchByCategoryOrSubCategoryName(categoryName, NodeTypeEnum.ServiceNewCategory,
- GraphEdgeLabels.CATEGORY.getProperty(), NodeTypeEnum.Service, inTransaction,
- ServiceMetadataData.class);
+ 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()));
+ return Either.left(components.left().value().stream().filter(statusFilter).collect(Collectors.toList()));
}
filters.remove(FilterKeyEnum.DISTRIBUTION_STATUS);
return components;
@@ -1054,69 +855,56 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper
return components;
}
- private <T> Either<List<T>, StorageOperationStatus> fetchByDistributionStatus(String status,
- boolean inTransaction) {
+ 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);
+ return (Either<List<T>, StorageOperationStatus>) (Either<?, StorageOperationStatus>) getServiceListByCriteria(props, inTransaction);
}
@SuppressWarnings("unchecked")
@Override
- public Either<List<Service>, StorageOperationStatus> getTesterFollowed(String userId,
- Set<LifecycleStateEnum> lifecycleStates, boolean inTransaction) {
- return (Either<List<Service>, StorageOperationStatus>) (Either<?, StorageOperationStatus>) getTesterFollowedComponent(
- userId, lifecycleStates, inTransaction, NodeTypeEnum.Service);
+ public Either<List<Service>, StorageOperationStatus> getTesterFollowed(String userId, Set<LifecycleStateEnum> lifecycleStates, boolean inTransaction) {
+ return (Either<List<Service>, StorageOperationStatus>) (Either<?, StorageOperationStatus>) getTesterFollowedComponent(userId, lifecycleStates, inTransaction, NodeTypeEnum.Service);
}
- public Either<Service, StorageOperationStatus> updateDestributionStatus(Service service, User user,
- DistributionStatusEnum distributionStatus) {
+ @Override
+ public Either<Service, StorageOperationStatus> updateDestributionStatus(Service service, User user, DistributionStatusEnum distributionStatus) {
String userId = user.getUserId();
Either<UserData, TitanOperationStatus> findUser = findUser(userId);
if (findUser.isRight()) {
TitanOperationStatus status = findUser.right().value();
- log.error("Cannot find user " + userId + " in the graph. status is " + status);
+ log.error("Cannot find user {} in the graph. status is {}", userId, status);
return sendError(status, StorageOperationStatus.USER_NOT_FOUND);
}
UserData userData = findUser.left().value();
- Either<ServiceMetadataData, TitanOperationStatus> serviceMetadataDataRequeset = titanGenericDao.getNode(
- UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Service), service.getUniqueId(),
- ServiceMetadataData.class);
+ Either<ServiceMetadataData, TitanOperationStatus> serviceMetadataDataRequeset = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Service), service.getUniqueId(), ServiceMetadataData.class);
if (serviceMetadataDataRequeset.isRight()) {
TitanOperationStatus status = serviceMetadataDataRequeset.right().value();
- log.error("Cannot find service " + service.getUniqueId() + " in the graph. status is " + status);
+ log.error("Cannot find service {} in the graph. status is {}",service.getUniqueId(),status);
return sendError(status, StorageOperationStatus.NOT_FOUND);
}
ServiceMetadataData serviceMetadataData = serviceMetadataDataRequeset.left().value();
StorageOperationStatus result = StorageOperationStatus.OK;
- Either<GraphRelation, TitanOperationStatus> deleteIncomingRelation = deleteLastDistributionModifierRelation(
- service);
- if (deleteIncomingRelation.isRight()
- && deleteIncomingRelation.right().value() != TitanOperationStatus.NOT_FOUND) {
- log.error("Failed to delete user from component " + service.getUniqueId() + ". Edge type is "
- + GraphEdgeLabels.LAST_DISTRIBUTION_STATE_MODIFAIER);
+ Either<GraphRelation, TitanOperationStatus> deleteIncomingRelation = deleteLastDistributionModifierRelation(service);
+ if (deleteIncomingRelation.isRight() && deleteIncomingRelation.right().value() != TitanOperationStatus.NOT_FOUND) {
+ log.error("Failed to delete user from component {}. Edge type is {}",service.getUniqueId(),GraphEdgeLabels.LAST_DISTRIBUTION_STATE_MODIFAIER);
result = DaoStatusConverter.convertTitanStatusToStorageStatus(deleteIncomingRelation.right().value());
return Either.right(result);
}
- Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(userData,
- serviceMetadataData, GraphEdgeLabels.LAST_DISTRIBUTION_STATE_MODIFAIER, null);
- log.debug("After associating user " + userData + " to component " + serviceMetadataData.getUniqueId()
- + ". Edge type is " + GraphEdgeLabels.LAST_DISTRIBUTION_STATE_MODIFAIER);
+ Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(userData, serviceMetadataData, GraphEdgeLabels.LAST_DISTRIBUTION_STATE_MODIFAIER, null);
+ log.debug("After associating user {} to component {}. Edge type is {}",userData,serviceMetadataData.getUniqueId(),GraphEdgeLabels.LAST_DISTRIBUTION_STATE_MODIFAIER);
if (createRelation.isRight()) {
- log.error("Failed to associate user " + userData + " to component " + serviceMetadataData.getUniqueId()
- + ". Edge type is " + GraphEdgeLabels.LAST_DISTRIBUTION_STATE_MODIFAIER);
+ log.error("Failed to associate user {} to component {}. Edge type is {}",userData,serviceMetadataData.getUniqueId(),GraphEdgeLabels.LAST_DISTRIBUTION_STATE_MODIFAIER);
result = DaoStatusConverter.convertTitanStatusToStorageStatus(createRelation.right().value());
return Either.right(result);
}
service.setDistributionStatus(distributionStatus);
- Either<Service, StorageOperationStatus> updateResponse = updateComponent(service, true, titanGenericDao,
- Service.class, NodeTypeEnum.Service);
+ Either<Service, StorageOperationStatus> updateResponse = updateComponent(service, true, titanGenericDao, Service.class, NodeTypeEnum.Service);
return updateResponse;
@@ -1125,17 +913,14 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper
private Either<GraphRelation, TitanOperationStatus> deleteLastDistributionModifierRelation(Service service) {
GraphRelation lastDistributionStateModifaierRelation = new GraphRelation();
lastDistributionStateModifaierRelation.setType(GraphEdgeLabels.LAST_DISTRIBUTION_STATE_MODIFAIER.getProperty());
- RelationEndPoint relationEndPoint = new RelationEndPoint(NodeTypeEnum.Service,
- UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Service), service.getUniqueId());
+ RelationEndPoint relationEndPoint = new RelationEndPoint(NodeTypeEnum.Service, UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Service), service.getUniqueId());
lastDistributionStateModifaierRelation.setTo(relationEndPoint);
- Either<GraphRelation, TitanOperationStatus> deleteIncomingRelation = titanGenericDao
- .deleteIncomingRelation(lastDistributionStateModifaierRelation);
+ Either<GraphRelation, TitanOperationStatus> deleteIncomingRelation = titanGenericDao.deleteIncomingRelation(lastDistributionStateModifaierRelation);
return deleteIncomingRelation;
}
@Override
- public Either<Set<Service>, StorageOperationStatus> getCertifiedServicesWithDistStatus(
- Map<String, Object> propertiesToMatch, Set<DistributionStatusEnum> distStatus, boolean inTransaction) {
+ public Either<Set<Service>, StorageOperationStatus> getCertifiedServicesWithDistStatus(Map<String, Object> propertiesToMatch, Set<DistributionStatusEnum> distStatus, boolean inTransaction) {
log.debug("Start getCertifiedServicesWithDistStatus.");
Set<Service> servicesSet = new HashSet<Service>();
if (distStatus != null && !distStatus.isEmpty()) {
@@ -1143,8 +928,7 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper
Map<String, Object> props = new HashMap<>();
props.putAll(propertiesToMatch);
props.put(GraphPropertiesDictionary.DISTRIBUTION_STATUS.getProperty(), status.name());
- Either<Set<Service>, StorageOperationStatus> services = retrieveCertifiedServicesWithStatus(
- inTransaction, servicesSet, props);
+ Either<Set<Service>, StorageOperationStatus> services = retrieveCertifiedServicesWithStatus(inTransaction, props);
if (services.isRight()) {
return services;
} else {
@@ -1153,14 +937,12 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper
}
return Either.left(servicesSet);
} else {
- return retrieveCertifiedServicesWithStatus(inTransaction, servicesSet, propertiesToMatch);
+ return retrieveCertifiedServicesWithStatus(inTransaction, propertiesToMatch);
}
}
- private Either<Set<Service>, StorageOperationStatus> retrieveCertifiedServicesWithStatus(boolean inTransaction,
- Set<Service> servicesSet, Map<String, Object> props) {
- Either<List<ServiceMetadataData>, TitanOperationStatus> criteriaRes = titanGenericDao
- .getByCriteria(NodeTypeEnum.Service, props, ServiceMetadataData.class);
+ private Either<Set<Service>, StorageOperationStatus> retrieveCertifiedServicesWithStatus(boolean inTransaction, Map<String, Object> props) {
+ Either<List<ServiceMetadataData>, TitanOperationStatus> criteriaRes = titanGenericDao.getByCriteria(NodeTypeEnum.Service, props, ServiceMetadataData.class);
return retrieveComponentsFromNodes(criteriaRes, inTransaction);
}
@@ -1170,41 +952,19 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper
try {
/*
- * Map<String, Object> propertiesToMatch = new HashMap<>();
- * propertiesToMatch.put(GraphPropertiesDictionary.STATE.getProperty
- * (), LifecycleStateEnum.CERTIFIED.name());
- * Either<List<ServiceMetadataData>, TitanOperationStatus>
- * lastVersionNodes = getLastVersion(NodeTypeEnum.Service,
- * propertiesToMatch, ServiceMetadataData.class); if
- * (lastVersionNodes.isRight() && lastVersionNodes.right().value()
- * != TitanOperationStatus.NOT_FOUND) { return
- * Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus
- * (lastVersionNodes.right().value())); } List<ServiceMetadataData>
- * notCertifiedHighest = (lastVersionNodes.isLeft() ?
- * lastVersionNodes.left().value() : new
+ * Map<String, Object> propertiesToMatch = new HashMap<>(); propertiesToMatch.put(GraphPropertiesDictionary.STATE.getProperty (), LifecycleStateEnum.CERTIFIED.name()); Either<List<ServiceMetadataData>, TitanOperationStatus>
+ * lastVersionNodes = getLastVersion(NodeTypeEnum.Service, propertiesToMatch, ServiceMetadataData.class); if (lastVersionNodes.isRight() && lastVersionNodes.right().value() != TitanOperationStatus.NOT_FOUND) { return
+ * Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus (lastVersionNodes.right().value())); } List<ServiceMetadataData> notCertifiedHighest = (lastVersionNodes.isLeft() ? lastVersionNodes.left().value() : new
* ArrayList<ServiceMetadataData>());
*
- * propertiesToMatch.put(GraphPropertiesDictionary.
- * IS_HIGHEST_VERSION.getProperty(), true);
- * Either<List<ServiceMetadataData>, TitanOperationStatus>
- * componentsNodes =
- * titanGenericDao.getByCriteria(NodeTypeEnum.Service,
- * propertiesToMatch, ServiceMetadataData.class); if
- * (componentsNodes.isRight() && componentsNodes.right().value() !=
- * TitanOperationStatus.NOT_FOUND) { return
- * Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus
- * (componentsNodes.right().value())); } List<ServiceMetadataData>
- * certifiedHighest = (componentsNodes.isLeft() ?
- * componentsNodes.left().value() : new
- * ArrayList<ServiceMetadataData>());
+ * propertiesToMatch.put(GraphPropertiesDictionary. IS_HIGHEST_VERSION.getProperty(), true); Either<List<ServiceMetadataData>, TitanOperationStatus> componentsNodes = titanGenericDao.getByCriteria(NodeTypeEnum.Service, propertiesToMatch,
+ * ServiceMetadataData.class); if (componentsNodes.isRight() && componentsNodes.right().value() != TitanOperationStatus.NOT_FOUND) { return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus
+ * (componentsNodes.right().value())); } List<ServiceMetadataData> certifiedHighest = (componentsNodes.isLeft() ? componentsNodes.left().value() : new ArrayList<ServiceMetadataData>());
*/
- Either<List<ServiceMetadataData>, TitanOperationStatus> listOfHighestComponents = this
- .getListOfHighestComponents(NodeTypeEnum.Service, ServiceMetadataData.class);
- if (listOfHighestComponents.isRight()
- && listOfHighestComponents.right().value() != TitanOperationStatus.NOT_FOUND) {
- return Either.right(
- DaoStatusConverter.convertTitanStatusToStorageStatus(listOfHighestComponents.right().value()));
+ Either<List<ServiceMetadataData>, TitanOperationStatus> listOfHighestComponents = this.getListOfHighestComponents(NodeTypeEnum.Service, ServiceMetadataData.class);
+ if (listOfHighestComponents.isRight() && listOfHighestComponents.right().value() != TitanOperationStatus.NOT_FOUND) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(listOfHighestComponents.right().value()));
}
List<ServiceMetadataData> notCertifiedHighest = listOfHighestComponents.left().value();
@@ -1216,41 +976,29 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper
// fetch from cache
long startFetchAllFromCache = System.currentTimeMillis();
- Map<String, Long> components = notCertifiedHighest.stream()
- .collect(Collectors.toMap(p -> p.getMetadataDataDefinition().getUniqueId(),
- p -> p.getMetadataDataDefinition().getLastUpdateDate()));
+ Map<String, Long> components = notCertifiedHighest.stream().collect(Collectors.toMap(p -> p.getMetadataDataDefinition().getUniqueId(), p -> p.getMetadataDataDefinition().getLastUpdateDate()));
- Either<ImmutablePair<List<Component>, Set<String>>, ActionStatus> componentsFromCacheForCatalog = this
- .getComponentsFromCacheForCatalog(components, ComponentTypeEnum.SERVICE);
+ Either<ImmutablePair<List<Component>, Set<String>>, ActionStatus> componentsFromCacheForCatalog = this.getComponentsFromCacheForCatalog(components, ComponentTypeEnum.SERVICE);
if (componentsFromCacheForCatalog.isLeft()) {
- ImmutablePair<List<Component>, Set<String>> immutablePair = componentsFromCacheForCatalog.left()
- .value();
+ ImmutablePair<List<Component>, Set<String>> immutablePair = componentsFromCacheForCatalog.left().value();
List<Component> list = immutablePair.getLeft();
if (list != null) {
for (Component component : list) {
result.add((Service) component);
}
- List<String> addedUids = list.stream()
- .map(p -> p.getComponentMetadataDefinition().getMetadataDataDefinition().getUniqueId())
- .collect(Collectors.toList());
- notCertifiedHighest = notCertifiedHighest.stream()
- .filter(p -> false == addedUids.contains(p.getMetadataDataDefinition().getUniqueId()))
- .collect(Collectors.toList());
+ List<String> addedUids = list.stream().map(p -> p.getComponentMetadataDefinition().getMetadataDataDefinition().getUniqueId()).collect(Collectors.toList());
+ notCertifiedHighest = notCertifiedHighest.stream().filter(p -> false == addedUids.contains(p.getMetadataDataDefinition().getUniqueId())).collect(Collectors.toList());
}
}
long endFetchAllFromCache = System.currentTimeMillis();
- log.debug("Fetch all catalog services metadata from cache took {} ms",
- (endFetchAllFromCache - startFetchAllFromCache));
+ log.debug("Fetch all catalog services metadata from cache took {} ms", (endFetchAllFromCache - startFetchAllFromCache));
log.debug("The number of services added to catalog from cache is {}", result.size());
- log.debug("The number of services needed to be fetch as light component is {}",
- notCertifiedHighest.size());
+ log.debug("The number of services needed to be fetch as light component is {}", notCertifiedHighest.size());
for (ServiceMetadataData data : notCertifiedHighest) {
- Either<Service, StorageOperationStatus> component = getLightComponent(
- data.getMetadataDataDefinition().getUniqueId(), inTransaction);
+ Either<Service, StorageOperationStatus> component = getLightComponent(data.getMetadataDataDefinition().getUniqueId(), inTransaction);
if (component.isRight()) {
- log.debug("Failed to get Service for id = {}, error : {}. Skip service", data.getUniqueId(),
- component.right().value());
+ log.debug("Failed to get Service for id = {}, error : {}. Skip service", data.getUniqueId(), component.right().value());
} else {
result.add(component.left().value());
}
@@ -1261,19 +1009,17 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper
if (false == inTransaction) {
titanGenericDao.commit();
}
- log.debug("Fetch all catalog services took " + (System.currentTimeMillis() - start) + " ms");
+ log.debug("Fetch all catalog services took {} ms",(System.currentTimeMillis() - start));
}
}
- public Either<List<Service>, StorageOperationStatus> getServiceCatalogDataLatestCertifiedAndNotCertified(
- boolean inTransaction) {
+ public Either<List<Service>, StorageOperationStatus> getServiceCatalogDataLatestCertifiedAndNotCertified(boolean inTransaction) {
Map<String, Object> properties = new HashMap<>();
properties.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true);
List<Service> result = new ArrayList<>();
- Either<List<ServiceMetadataData>, TitanOperationStatus> lastVersionNodes = titanGenericDao
- .getByCriteria(NodeTypeEnum.Service, properties, ServiceMetadataData.class);
+ Either<List<ServiceMetadataData>, TitanOperationStatus> lastVersionNodes = titanGenericDao.getByCriteria(NodeTypeEnum.Service, properties, ServiceMetadataData.class);
if (lastVersionNodes.isRight() && lastVersionNodes.right().value() != TitanOperationStatus.NOT_FOUND) {
return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(lastVersionNodes.right().value()));
@@ -1288,11 +1034,9 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper
}
for (ServiceMetadataData data : latestServices) {
- Either<Service, StorageOperationStatus> component = getLightComponent(
- data.getMetadataDataDefinition().getUniqueId(), inTransaction);
+ Either<Service, StorageOperationStatus> component = getLightComponent(data.getMetadataDataDefinition().getUniqueId(), inTransaction);
if (component.isRight()) {
- log.debug("Failed to get Service for id = " + data.getUniqueId() + " error : "
- + component.right().value() + " skip resource");
+ log.debug("Failed to get Service for id = {} error : {} skip resource",data.getUniqueId(),component.right().value());
} else {
result.add(component.left().value());
}
@@ -1302,25 +1046,21 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper
}
- private Either<List<Service>, StorageOperationStatus> getServiceListByCriteria(Map<String, Object> props,
- boolean 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);
+ 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<Service> services = new ArrayList<>();
List<ServiceMetadataData> servicesDataList = byCriteria.left().value();
for (ServiceMetadataData data : servicesDataList) {
- Either<Service, StorageOperationStatus> service = getService(data.getMetadataDataDefinition().getUniqueId(),
- inTransaction);
+ Either<Service, StorageOperationStatus> service = getService(data.getMetadataDataDefinition().getUniqueId(), inTransaction);
if (service.isLeft()) {
services.add(service.left().value());
} else {
- log.debug("Failed to fetch resource for name = " + data.getMetadataDataDefinition().getName()
- + " and id = " + data.getUniqueId());
+ log.debug("Failed to fetch resource for name = {} and id = {}",data.getMetadataDataDefinition().getName(),data.getUniqueId());
}
}
return Either.left(services);
@@ -1334,8 +1074,7 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper
return getLatestServiceByUuid(uuid, true, inTransaction);
}
- private Either<List<Service>, StorageOperationStatus> getLatestServiceByUuid(String uuid, boolean isLatest,
- boolean inTransaction) {
+ private Either<List<Service>, StorageOperationStatus> getLatestServiceByUuid(String uuid, boolean isLatest, boolean inTransaction) {
Map<String, Object> props = new HashMap<String, Object>();
if (isLatest) {
@@ -1346,17 +1085,23 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper
return getServiceListByCriteria(props, inTransaction);
}
- public Either<List<Service>, StorageOperationStatus> getServiceListBySystemName(String systemName,
- boolean inTransaction) {
+ @Override
+ public Either<List<Service>, StorageOperationStatus> getAll() {
+ Either<List<Service>, StorageOperationStatus> serviceListByCriteria = getServiceListByCriteria(new HashMap<>(), false);
+ if (serviceListByCriteria.isRight() && serviceListByCriteria.right().value() == StorageOperationStatus.NOT_FOUND) {
+ return Either.left(Collections.emptyList());
+ }
+ return serviceListByCriteria;
+ }
+
+ public Either<List<Service>, StorageOperationStatus> getServiceListBySystemName(String systemName, boolean inTransaction) {
Map<String, Object> props = new HashMap<String, Object>();
props.put(GraphPropertiesDictionary.SYSTEM_NAME.getProperty(), systemName);
return getServiceListByCriteria(props, inTransaction);
}
- public Either<Service, StorageOperationStatus> getServiceByNameAndVersion(String name, String version,
- Map<String, Object> additionalParams, boolean inTransaction) {
- return getByNamesAndVersion(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(),
- ValidationUtils.normaliseComponentName(name), version, additionalParams, inTransaction);
+ public Either<Service, StorageOperationStatus> getServiceByNameAndVersion(String name, String version, Map<String, Object> additionalParams, boolean inTransaction) {
+ return getByNamesAndVersion(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(), ValidationUtils.normaliseComponentName(name), version, additionalParams, inTransaction);
}
@Override
@@ -1364,8 +1109,7 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper
return getServiceByNameAndVersion(name, version, null, false);
}
- protected Either<Service, StorageOperationStatus> getByNamesAndVersion(String nameKey, String nameValue,
- String version, Map<String, Object> additionalParams, boolean inTransaction) {
+ protected Either<Service, StorageOperationStatus> getByNamesAndVersion(String nameKey, String nameValue, String version, Map<String, Object> additionalParams, boolean inTransaction) {
Map<String, Object> props = new HashMap<String, Object>();
props.put(nameKey, nameValue);
props.put(GraphPropertiesDictionary.VERSION.getProperty(), version);
@@ -1374,8 +1118,7 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper
props.putAll(additionalParams);
}
- Either<List<ServiceMetadataData>, TitanOperationStatus> byCriteria = titanGenericDao
- .getByCriteria(NodeTypeEnum.Service, props, ServiceMetadataData.class);
+ Either<List<ServiceMetadataData>, TitanOperationStatus> byCriteria = titanGenericDao.getByCriteria(NodeTypeEnum.Service, props, ServiceMetadataData.class);
if (byCriteria.isRight()) {
return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(byCriteria.right().value()));
@@ -1383,40 +1126,33 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper
List<ServiceMetadataData> dataList = byCriteria.left().value();
if (dataList != null && !dataList.isEmpty()) {
if (dataList.size() > 1) {
- log.debug("More that one instance of resource for name =" + nameValue + " and version = " + version);
+ log.debug("More that one instance of resource for name ={} and version = {}",nameValue,version);
return Either.right(StorageOperationStatus.GENERAL_ERROR);
}
ServiceMetadataData serviceData = dataList.get(0);
- Either<Service, StorageOperationStatus> service = getService(
- serviceData.getMetadataDataDefinition().getUniqueId(), inTransaction);
+ Either<Service, StorageOperationStatus> service = getService(serviceData.getMetadataDataDefinition().getUniqueId(), inTransaction);
if (service.isRight()) {
- log.debug("Failed to fetch resource for name = " + serviceData.getMetadataDataDefinition().getName()
- + " and id = " + serviceData.getMetadataDataDefinition().getUniqueId());
+ log.debug("Failed to fetch resource for name = {} and id = {}",serviceData.getMetadataDataDefinition().getName(),serviceData.getMetadataDataDefinition().getUniqueId());
}
return service;
}
return Either.right(StorageOperationStatus.NOT_FOUND);
}
- protected <T> Either<T, StorageOperationStatus> getComponentByNameAndVersion(String name, String version,
- Map<String, Object> additionalParams, boolean inTransaction) {
- return (Either<T, StorageOperationStatus>) getServiceByNameAndVersion(name, version, additionalParams,
- inTransaction);
+ protected <T> Either<T, StorageOperationStatus> getComponentByNameAndVersion(String name, String version, Map<String, Object> additionalParams, boolean inTransaction) {
+ return (Either<T, StorageOperationStatus>) getServiceByNameAndVersion(name, version, additionalParams, inTransaction);
}
@Override
- public Either<Service, StorageOperationStatus> getServiceBySystemNameAndVersion(String name, String version,
- boolean inTransaction) {
- return getByNamesAndVersion(GraphPropertiesDictionary.SYSTEM_NAME.getProperty(), name, version, null,
- inTransaction);
+ public Either<Service, StorageOperationStatus> getServiceBySystemNameAndVersion(String name, String version, boolean inTransaction) {
+ return getByNamesAndVersion(GraphPropertiesDictionary.SYSTEM_NAME.getProperty(), name, version, null, inTransaction);
}
private TitanOperationStatus setServiceAdditionalInformationFromGraph(String uniqueId, Service service) {
List<AdditionalInformationDefinition> additionalInformation = new ArrayList<>();
- Either<AdditionalInformationDefinition, TitanOperationStatus> either = additionalInformationOperation
- .getAllAdditionalInformationParameters(NodeTypeEnum.Service, uniqueId, true);
+ Either<AdditionalInformationDefinition, TitanOperationStatus> either = additionalInformationOperation.getAllAdditionalInformationParameters(NodeTypeEnum.Service, uniqueId, true);
if (either.isRight()) {
TitanOperationStatus status = either.right().value();
@@ -1436,8 +1172,7 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper
}
private TitanOperationStatus setAllVersions(Service service) {
- Either<Map<String, String>, TitanOperationStatus> res = getVersionList(NodeTypeEnum.Service,
- service.getVersion(), service, ServiceMetadataData.class);
+ Either<Map<String, String>, TitanOperationStatus> res = getVersionList(NodeTypeEnum.Service, service.getVersion(), service, ServiceMetadataData.class);
if (res.isRight()) {
return res.right().value();
}
@@ -1445,8 +1180,7 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper
return TitanOperationStatus.OK;
}
- public Either<List<ArtifactDefinition>, StorageOperationStatus> getAdditionalArtifacts(String resourceId,
- boolean recursively, boolean inTransaction) {
+ public Either<List<ArtifactDefinition>, StorageOperationStatus> getAdditionalArtifacts(String resourceId, boolean recursively, boolean inTransaction) {
List<ArtifactDefinition> artifacts = new ArrayList<>();
return Either.left(artifacts);
}
@@ -1466,40 +1200,33 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper
@SuppressWarnings("unchecked")
@Override
- public <T> Either<T, StorageOperationStatus> cloneComponent(T other, String version,
- LifecycleStateEnum targetLifecycle, boolean inTransaction) {
- return (Either<T, StorageOperationStatus>) cloneService((Service) other, version, targetLifecycle,
- inTransaction);
+ public <T> Either<T, StorageOperationStatus> cloneComponent(T other, String version, LifecycleStateEnum targetLifecycle, boolean inTransaction) {
+ return (Either<T, StorageOperationStatus>) cloneService((Service) other, version, targetLifecycle, inTransaction);
}
@Override
- public Either<Integer, StorageOperationStatus> increaseAndGetComponentInstanceCounter(String componentId,
- boolean inTransaction) {
+ public Either<Integer, StorageOperationStatus> increaseAndGetComponentInstanceCounter(String componentId, boolean inTransaction) {
return increaseAndGetComponentInstanceCounter(componentId, NodeTypeEnum.Service, inTransaction);
}
@Override
- protected StorageOperationStatus validateCategories(Component currentComponent, Component component,
- ComponentMetadataData componentData, NodeTypeEnum type) {
+ protected StorageOperationStatus validateCategories(Component currentComponent, Component component, ComponentMetadataData componentData, NodeTypeEnum type) {
List<CategoryDefinition> newcategories = component.getCategories();
CategoryDefinition newCat = newcategories.get(0);
CategoryDefinition currentCategory = currentComponent.getCategories().get(0);
StorageOperationStatus status = StorageOperationStatus.OK;
if (newCat != null && newCat.getName() != null && false == newCat.getName().equals(currentCategory.getName())) {
- log.debug(
- "Going to update the category of the resource from " + currentCategory + " to " + newCat.getName());
+ log.debug("Going to update the category of the resource from {} to {}",currentCategory,newCat.getName());
status = moveCategoryEdge(component, componentData, newCat, type);
- log.debug("Going to update the category of the resource from " + currentCategory + " to " + newCat.getName()
- + ". status is " + status);
+ log.debug("Going to update the category of the resource from {} to {}. status is {}",currentCategory,newCat.getName(),status);
}
return status;
}
@Override
- protected <T extends Component> StorageOperationStatus updateDerived(Component component,
- Component currentComponent, ComponentMetadataData componentData, Class<T> clazz) {
+ protected <T extends Component> StorageOperationStatus updateDerived(Component component, Component currentComponent, ComponentMetadataData componentData, Class<T> clazz) {
log.debug("Derived class isn't supported for resource");
return null;
}
@@ -1525,8 +1252,7 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper
}
@Override
- public Either<Component, StorageOperationStatus> markComponentToDelete(Component componentToDelete,
- boolean inTransaction) {
+ public Either<Component, StorageOperationStatus> markComponentToDelete(Component componentToDelete, boolean inTransaction) {
return internalMarkComponentToDelete(componentToDelete, inTransaction);
}
@@ -1542,8 +1268,7 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper
@SuppressWarnings("unchecked")
@Override
- public <T> Either<T, StorageOperationStatus> getComponent(String id,
- ComponentParametersView componentParametersView, boolean inTransaction) {
+ public <T> Either<T, StorageOperationStatus> getComponent(String id, ComponentParametersView componentParametersView, boolean inTransaction) {
Either<Service, StorageOperationStatus> component = getService(id, componentParametersView, inTransaction);
if (component.isRight()) {
@@ -1552,15 +1277,13 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper
return (Either<T, StorageOperationStatus>) component;
}
- public Either<Service, StorageOperationStatus> updateService(Service service, boolean inTransaction,
- ComponentParametersView filterResultView) {
- return (Either<Service, StorageOperationStatus>) updateComponentFilterResult(service, inTransaction,
- titanGenericDao, service.getClass(), NodeTypeEnum.Service, filterResultView);
+ public Either<Service, StorageOperationStatus> updateService(Service service, boolean inTransaction, ComponentParametersView filterResultView) {
+ return (Either<Service, StorageOperationStatus>) updateComponentFilterResult(service, inTransaction, titanGenericDao, service.getClass(), NodeTypeEnum.Service, filterResultView);
}
@Override
- protected <T> Either<T, StorageOperationStatus> updateComponentFilterResult(T component, boolean inTransaction,
- ComponentParametersView filterResultView) {
+ protected <T> Either<T, StorageOperationStatus> updateComponentFilterResult(T component, boolean inTransaction, ComponentParametersView filterResultView) {
return (Either<T, StorageOperationStatus>) updateService((Service) component, inTransaction, filterResultView);
}
+
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ToscaDefinitionPathCalculatorImpl.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ToscaDefinitionPathCalculatorImpl.java
new file mode 100644
index 0000000000..01a730a052
--- /dev/null
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ToscaDefinitionPathCalculatorImpl.java
@@ -0,0 +1,27 @@
+package org.openecomp.sdc.be.model.operations.impl;
+
+import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
+import org.openecomp.sdc.be.dao.neo4j.GraphEdgePropertiesDictionary;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.operations.api.ToscaDefinitionPathCalculator;
+import org.springframework.stereotype.Component;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+@Component("tosca-path-calculator")
+public class ToscaDefinitionPathCalculatorImpl implements ToscaDefinitionPathCalculator {
+
+ @Override
+ public List<String> calculateToscaDefinitionPath(ComponentInstance componentInstance, GraphEdge edge) {
+ String ownerId = getCapReqOwner(edge);
+ String instanceId = componentInstance.getUniqueId();
+ return ownerId.equals(instanceId) ? Collections.singletonList(instanceId) : Arrays.asList(instanceId, ownerId);
+ }
+
+ private String getCapReqOwner(GraphEdge edge) {
+ String ownerIdKey = GraphEdgePropertiesDictionary.OWNER_ID.getProperty();
+ return (String)edge.getProperties().get(ownerIdKey);
+ }
+}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/UniqueIdBuilder.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/UniqueIdBuilder.java
index c4bcf6d907..eb5d8f6797 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
@@ -24,22 +24,24 @@ import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
+import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
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.util.ValidationUtils;
public class UniqueIdBuilder {
private static String DOT = ".";
private static final String HEAT_PARAM_PREFIX = "heat_";
-
+
public static String buildPropertyUniqueId(String resourceId, String propertyName) {
return resourceId + DOT + propertyName;
}
-
+
public static String buildHeatParameterUniqueId(String resourceId, String propertyName) {
return resourceId + DOT + HEAT_PARAM_PREFIX + propertyName;
}
@@ -103,7 +105,9 @@ public class UniqueIdBuilder {
public static String buildAttributeUid(String resourceId, String attName) {
return NodeTypeEnum.Attribute.getName() + DOT + resourceId + DOT + attName;
}
-
+ public static String buildArtifactUid(String parentId, String label) {
+ return parentId + DOT + label;
+ }
public static String buildRequirementUid(String resourceId, String reqName) {
return resourceId + DOT + reqName;
}
@@ -125,9 +129,8 @@ public class UniqueIdBuilder {
public static String buildPropertyValueUniqueId(String parentId, String paramName) {
return NodeTypeEnum.PropertyValue.getName() + DOT + parentId + DOT + paramName;
}
-
- public static String buildArtifactByInterfaceUniqueId(String resourceId, String interfaceName, String operation,
- String artifactLabel) {
+
+ public static String buildArtifactByInterfaceUniqueId(String resourceId, String interfaceName, String operation, String artifactLabel) {
return resourceId + DOT + interfaceName + DOT + operation + DOT + artifactLabel;
}
@@ -141,8 +144,7 @@ public class UniqueIdBuilder {
// return resourceId + DOT + interfaceName + DOT +operation + DOT +
// artifactLabel;
// }
- public static String buildArtifactByInterfaceUniqueIdAndRsrcId(String resourceId, String interfaceName,
- String operation, String artifactLabel) {
+ public static String buildArtifactByInterfaceUniqueIdAndRsrcId(String resourceId, String interfaceName, String operation, String artifactLabel) {
return resourceId + DOT + interfaceName + DOT + operation + DOT + artifactLabel;
}
@@ -183,6 +185,9 @@ public class UniqueIdBuilder {
public static String buildCategoryUid(String categoryName, NodeTypeEnum type) {
return type.getName() + DOT + categoryName;
}
+ public static String buildComponentCategoryUid(String categoryName, VertexTypeEnum type) {
+ return type.getName() + DOT + ValidationUtils.normalizeCategoryName4Uniqueness(categoryName);
+ }
public static String buildSubCategoryUid(String categoryUid, String subCategoryName) {
return categoryUid + DOT + subCategoryName;
@@ -195,6 +200,10 @@ public class UniqueIdBuilder {
public static String buildResourceInstancePropertyValueUid(String resourceInstanceUniqueId, Integer index) {
return resourceInstanceUniqueId + DOT + "property" + DOT + index;
}
+
+ public static String buildComponentPropertyUniqueId(String resourceId, String propertyName) {
+ return NodeTypeEnum.Property.getName() + DOT + resourceId + DOT + propertyName;
+ }
public static String buildResourceInstanceAttributeValueUid(String resourceInstanceUniqueId, Integer index) {
return resourceInstanceUniqueId + DOT + "attribute" + DOT + index;
@@ -236,7 +245,7 @@ public class UniqueIdBuilder {
return groupUniqueId + DOT + "property" + DOT + index;
}
-
+
public static String buildUserFunctionalMenuUid(String userId) {
return userId + DOT + "functionalmenu";
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/UserAdminOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/UserAdminOperation.java
index 85bb56f39f..7c45f8f384 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/UserAdminOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/UserAdminOperation.java
@@ -20,11 +20,8 @@
package org.openecomp.sdc.be.model.operations.impl;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
+import com.thinkaurelius.titan.core.TitanVertex;
+import fj.data.Either;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Edge;
@@ -47,20 +44,24 @@ import org.openecomp.sdc.common.datastructure.Wrapper;
import org.openecomp.sdc.common.util.MethodActivationStatusEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
-import com.thinkaurelius.titan.core.TitanVertex;
-
-import fj.data.Either;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
@Component("user-operation")
public class UserAdminOperation implements IUserAdminOperation {
- @javax.annotation.Resource
private TitanGenericDao titanGenericDao;
- public UserAdminOperation() {
+ public UserAdminOperation(@Qualifier("titan-generic-dao") TitanGenericDao titanGenericDao) {
super();
+ this.titanGenericDao = titanGenericDao;
+
}
private static Logger log = LoggerFactory.getLogger(UserAdminOperation.class.getName());
@@ -132,8 +133,7 @@ public class UserAdminOperation implements IUserAdminOperation {
}
}
- private void validateUserExists(Wrapper<Either<User, ActionStatus>> resultWrapper, Wrapper<UserData> userWrapper,
- String id) {
+ private void validateUserExists(Wrapper<Either<User, ActionStatus>> resultWrapper, Wrapper<UserData> userWrapper, String id) {
Either<User, ActionStatus> result;
if (id == null) {
log.info("User userId is empty");
@@ -142,19 +142,10 @@ public class UserAdminOperation implements IUserAdminOperation {
return;
}
id = id.toLowerCase();
- Either<UserData, TitanOperationStatus> either = titanGenericDao
- .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), id, UserData.class);
+ Either<UserData, TitanOperationStatus> either = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), id, UserData.class);
if (either.isRight()) {
- if (either.right().value() == TitanOperationStatus.NOT_FOUND) {
- log.debug("User with userId {} not found", id);
- result = Either.right(ActionStatus.USER_NOT_FOUND);
- resultWrapper.setInnerElement(result);
- } else {
- log.debug("Problem get User with userId {}. Reason - {}", id, either.right().value().name());
- result = Either.right(ActionStatus.GENERAL_ERROR);
- resultWrapper.setInnerElement(result);
- }
+ resultWrapper.setInnerElement(getUserNotFoundError(id, either.right().value()));
} else {
userWrapper.setInnerElement(either.left().value());
}
@@ -168,10 +159,10 @@ public class UserAdminOperation implements IUserAdminOperation {
UserData userData = convertToUserData(user);
result = titanGenericDao.createNode(userData, UserData.class);
if (result.isRight()) {
- log.debug("Problem while saving User {}. Reason - {}", userData.toString(), result.right().value().name());
+ log.debug("Problem while saving User {}. Reason - {}",userData.toString(),result.right().value().name());
return Either.right(StorageOperationStatus.GENERAL_ERROR);
}
- log.debug("User {} saved successfully", userData.toString());
+ log.debug("User {} saved successfully",userData.toString());
return Either.left(convertToUser(result.left().value()));
} finally {
@@ -194,10 +185,10 @@ public class UserAdminOperation implements IUserAdminOperation {
UserData userData = convertToUserData(user);
result = titanGenericDao.updateNode(userData, UserData.class);
if (result.isRight()) {
- log.debug("Problem while updating User {}. Reason - {}", userData.toString(), result.right().value().name());
+ log.debug("Problem while updating User {}. Reason - {}",userData.toString(),result.right().value().name());
return Either.right(StorageOperationStatus.GENERAL_ERROR);
}
- log.debug("User {} updated successfully", userData.toString());
+ log.debug("User {} updated successfully",userData.toString());
return Either.left(convertToUser(result.left().value()));
} finally {
@@ -229,10 +220,9 @@ public class UserAdminOperation implements IUserAdminOperation {
@Override
public Either<User, ActionStatus> deleteUserData(String id) {
Either<User, ActionStatus> result;
- Either<UserData, TitanOperationStatus> eitherGet = titanGenericDao
- .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), id, UserData.class);
+ Either<UserData, TitanOperationStatus> eitherGet = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), id, UserData.class);
if (eitherGet.isRight()) {
- log.debug("Problem while retriving user with userId {}", id);
+ log.debug("Problem while retriving user with userId {}",id);
if (eitherGet.right().value() == TitanOperationStatus.NOT_FOUND) {
result = Either.right(ActionStatus.USER_NOT_FOUND);
} else {
@@ -264,11 +254,11 @@ public class UserAdminOperation implements IUserAdminOperation {
private void deleteUser(Wrapper<Either<User, ActionStatus>> resultWrapper, UserData userData) {
Either<UserData, TitanOperationStatus> eitherDelete = titanGenericDao.deleteNode(userData, UserData.class);
if (eitherDelete.isRight()) {
- log.debug("Problem while deleting User {}. Reason - {}", userData.toString(), eitherDelete.right().value().name());
+ log.debug("Problem while deleting User {}. Reason - {}",userData.toString(),eitherDelete.right().value().name());
Either<User, ActionStatus> result = Either.right(ActionStatus.GENERAL_ERROR);
resultWrapper.setInnerElement(result);
} else {
- log.debug("User {} deleted successfully", userData.toString());
+ log.debug("User {} deleted successfully",userData.toString());
Either<User, ActionStatus> result = Either.left(convertToUser(eitherDelete.left().value()));
resultWrapper.setInnerElement(result);
}
@@ -277,10 +267,9 @@ public class UserAdminOperation implements IUserAdminOperation {
private void validateUserHasNoConnections(Wrapper<Either<User, ActionStatus>> resultWrapper, UserData userData) {
if (resultWrapper.isEmpty()) {
- Either<List<Edge>, TitanOperationStatus> edgesForNode = titanGenericDao.getEdgesForNode(userData,
- Direction.BOTH);
+ Either<List<Edge>, TitanOperationStatus> edgesForNode = titanGenericDao.getEdgesForNode(userData, Direction.BOTH);
if (edgesForNode.isRight()) {
- log.debug("Problem while deleting User {}. Reason - {}", userData.toString(), edgesForNode.right().value().name());
+ log.debug("Problem while deleting User {}. Reason - {}",userData.toString(),edgesForNode.right().value().name());
Either<User, ActionStatus> result = Either.right(ActionStatus.GENERAL_ERROR);
resultWrapper.setInnerElement(result);
} else {
@@ -293,35 +282,31 @@ public class UserAdminOperation implements IUserAdminOperation {
}
}
- public Either<List<Edge>, StorageOperationStatus> getUserPandingTasksList(User user,
- Map<String, Object> properties) {
+ public Either<List<Edge>, StorageOperationStatus> getUserPandingTasksList(User user, Map<String, Object> properties) {
UserData userData = convertToUserData(user);
- Either<TitanVertex, TitanOperationStatus> vertexUser = titanGenericDao
- .getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), user.getUserId());
+ Either<TitanVertex, TitanOperationStatus> vertexUser = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), user.getUserId());
if (vertexUser.isRight()) {
- log.debug("Problem while deleting User {}. Reason - {}", userData.toString(), vertexUser.right().value().name());
+ log.debug("Problem while deleting User {}. Reason - {}",userData.toString(),vertexUser.right().value().name());
return Either.right(StorageOperationStatus.GENERAL_ERROR);
}
List<Edge> pandingTasks = new ArrayList<>();
- Either<List<Edge>, TitanOperationStatus> edges = titanGenericDao
- .getOutgoingEdgesByCriteria(vertexUser.left().value(), GraphEdgeLabels.STATE, properties);
+ Either<List<Edge>, TitanOperationStatus> edges = titanGenericDao.getOutgoingEdgesByCriteria(vertexUser.left().value(), GraphEdgeLabels.STATE, properties);
if (edges.isRight() || edges.left().value() == null) {
if (edges.right().value() == TitanOperationStatus.NOT_FOUND) {
return Either.left(pandingTasks);
} else {
- log.debug("Problem while deleting User {}", userData.toString(), edges.right().value().name());
+ log.debug("Problem while deleting User {}. Reason - ",userData.toString(),edges.right().value().name());
return Either.right(StorageOperationStatus.GENERAL_ERROR);
}
}
for (Edge edge : edges.left().value()) {
Vertex componentVertex = edge.inVertex();
- VertexProperty<Object> property = componentVertex
- .property(GraphPropertiesDictionary.IS_DELETED.getProperty());
+ VertexProperty<Object> property = componentVertex.property(GraphPropertiesDictionary.IS_DELETED.getProperty());
if (!property.isPresent()) {
pandingTasks.add(edge);
} else {
@@ -347,35 +332,64 @@ public class UserAdminOperation implements IUserAdminOperation {
propertiesToMatch.put(GraphPropertiesDictionary.USER_STATUS.getProperty(), status);
}
- Either<List<UserData>, TitanOperationStatus> userNodes = titanGenericDao.getByCriteria(NodeTypeEnum.User,
- propertiesToMatch, UserData.class);
+ Either<List<UserData>, TitanOperationStatus> userNodes = titanGenericDao.getByCriteria(NodeTypeEnum.User, propertiesToMatch, UserData.class);
titanGenericDao.commit();
- if (userNodes.isRight()) {
- // in case of NOT_FOUND from Titan return empty list
- if (userNodes.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
- return Either.left(result);
- } else {
- log.error("Problem while getting all users with role {}. Reason - {}", role, userNodes.right().value().name());
- return Either.right(ActionStatus.GENERAL_ERROR);
- }
- } else {
- List<UserData> userDataList = userNodes.left().value();
- if (userDataList != null) {
- for (UserData userData : userDataList) {
- User user = convertToUser(userData);
- result.add(user);
- }
- return Either.left(result);
- }
- log.debug("No users were found with role {}", role);
- return Either.left(result);
- }
+ return convertToUsers(role, userNodes);
} finally {
titanGenericDao.commit();
}
}
+ private Either<List<User>, ActionStatus> convertToUsers(String role, Either<List<UserData>, TitanOperationStatus> userNodes) {
+
+ if (userNodes.isRight()) {
+ // in case of NOT_FOUND from Titan return empty list
+ if (userNodes.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
+ return Either.left(Collections.emptyList());
+ } else {
+ log.error("Problem while getting all users with role {}. Reason - {}", role, userNodes.right().value().name());
+ return Either.right(ActionStatus.GENERAL_ERROR);
+ }
+ } else {
+ List<UserData> userDataList = userNodes.left().value();
+ if (userDataList != null) {
+ return Either.left(convertToUsers(userDataList));
+ }
+ log.debug("No users were found with role {}", role);
+ return Either.left(Collections.emptyList());
+ }
+ }
+
+ private List<User> convertToUsers(List<UserData> usersData) {
+ List<User> result = new ArrayList<>();
+ for (UserData userData : usersData) {
+ User user = convertToUser(userData);
+ result.add(user);
+ }
+ return result;
+ }
+
+ @Override
+ public Either<List<User>, ActionStatus> getAllUsers() {
+ try {
+ Either<List<UserData>, TitanOperationStatus> userNodes = titanGenericDao.getAll(NodeTypeEnum.User, UserData.class);
+ return convertToUsers("", userNodes);
+ } finally {
+ titanGenericDao.commit();
+ }
+ }
+
+ private Either<User, ActionStatus> getUserNotFoundError(String uid, TitanOperationStatus status) {
+ if (status == TitanOperationStatus.NOT_FOUND) {
+ log.debug("User with userId {} not found", uid);
+ return Either.right(ActionStatus.USER_NOT_FOUND);
+ } else {
+ log.debug("Problem get User with userId {}. Reason - {}", uid, status.name());
+ return Either.right(ActionStatus.GENERAL_ERROR);
+ }
+ }
+
protected User convertToUser(UserData userData) {
User user = new User();
user.setUserId(userData.getUserId());
@@ -403,6 +417,7 @@ public class UserAdminOperation implements IUserAdminOperation {
return userData;
}
+ @Override
public Either<ImmutablePair<User, FunctionalMenuInfo>, ActionStatus> getUserDataWithFunctionalMenu(String userId) {
Either<User, ActionStatus> userData = getUserData(userId, true, true);
@@ -424,8 +439,7 @@ public class UserAdminOperation implements IUserAdminOperation {
functionalMenuInfo.setFunctionalMenu(userFunctionalMenuData.getFunctionalMenu());
}
- ImmutablePair<User, FunctionalMenuInfo> result = new ImmutablePair<User, FunctionalMenuInfo>(user,
- functionalMenuInfo);
+ ImmutablePair<User, FunctionalMenuInfo> result = new ImmutablePair<User, FunctionalMenuInfo>(user, functionalMenuInfo);
return Either.left(result);
}
@@ -441,8 +455,7 @@ public class UserAdminOperation implements IUserAdminOperation {
userId = userId.toLowerCase();
String uid = UniqueIdBuilder.buildUserFunctionalMenuUid(userId);
- Either<UserFunctionalMenuData, TitanOperationStatus> either = titanGenericDao.getNode(
- UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.UserFunctionalMenu), uid, UserFunctionalMenuData.class);
+ Either<UserFunctionalMenuData, TitanOperationStatus> either = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.UserFunctionalMenu), uid, UserFunctionalMenuData.class);
return either;
}
@@ -457,8 +470,7 @@ public class UserAdminOperation implements IUserAdminOperation {
String uid = UniqueIdBuilder.buildUserFunctionalMenuUid(userId);
UserFunctionalMenuData functionalMenuData = new UserFunctionalMenuData(newFunctionalMenu, uid);
- Either<UserFunctionalMenuData, TitanOperationStatus> createNode = titanGenericDao
- .createNode(functionalMenuData, UserFunctionalMenuData.class);
+ Either<UserFunctionalMenuData, TitanOperationStatus> createNode = titanGenericDao.createNode(functionalMenuData, UserFunctionalMenuData.class);
if (createNode.isRight()) {
return Either.right(createNode.right().value());
@@ -473,8 +485,7 @@ public class UserAdminOperation implements IUserAdminOperation {
} else {
UserFunctionalMenuData userFunctionalMenuData = functionalMenu.left().value();
userFunctionalMenuData.setFunctionalMenu(newFunctionalMenu);
- Either<UserFunctionalMenuData, TitanOperationStatus> updateNode = titanGenericDao
- .updateNode(userFunctionalMenuData, UserFunctionalMenuData.class);
+ Either<UserFunctionalMenuData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(userFunctionalMenuData, UserFunctionalMenuData.class);
if (updateNode.isRight()) {
return Either.right(updateNode.right().value());
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/migration/MigrationErrorInformer.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/migration/MigrationErrorInformer.java
new file mode 100644
index 0000000000..952c0672cc
--- /dev/null
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/migration/MigrationErrorInformer.java
@@ -0,0 +1,39 @@
+package org.openecomp.sdc.be.model.operations.migration;
+
+import org.apache.commons.lang3.StringUtils;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+/**
+ * to be moved with all operations to the migration project
+ */
+@Deprecated
+public class MigrationErrorInformer {
+
+ private static Logger log = LoggerFactory.getLogger(MigrationErrorInformer.class);
+ private static Set<String> malformedVFs = new HashSet<>();
+
+ public static void addMalformedVF(String vfId) {
+ malformedVFs.add(vfId);
+ }
+
+ public static void logIfServiceUsingMalformedVfs(Component service) {
+ List<ComponentInstance> componentInstances = service.getComponentInstances();
+ if (componentInstances != null && !componentInstances.isEmpty() && !malformedVFs.isEmpty()) {
+ Set<String> serviceInstances = componentInstances.stream().map(ComponentInstance::getComponentUid).collect(Collectors.toSet());
+ serviceInstances.retainAll(malformedVFs);
+ if (!serviceInstances.isEmpty()) {
+ log.error(String.format("Service %s is using malformed VFs: %s", service.getUniqueId(), StringUtils.join(serviceInstances, ',')));
+ }
+ }
+ }
+
+
+}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/utils/ComponentValidationUtils.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/utils/ComponentValidationUtils.java
index fd6563ac4f..fe5d79a266 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/utils/ComponentValidationUtils.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/utils/ComponentValidationUtils.java
@@ -20,11 +20,12 @@
package org.openecomp.sdc.be.model.operations.utils;
+import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.LifecycleStateEnum;
import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.Service;
-import org.openecomp.sdc.be.model.operations.api.IComponentOperation;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
import org.openecomp.sdc.be.model.operations.api.IResourceOperation;
import org.openecomp.sdc.be.model.operations.api.IServiceOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
@@ -56,52 +57,26 @@ public class ComponentValidationUtils {
return true;
}
- public static boolean canWorkOnResource(String resourceId, IResourceOperation resourceOperation,
- String userId) {
- Either<Resource, StorageOperationStatus> getResourceResult = resourceOperation.getLightComponent(resourceId,
- false);
-
- if (getResourceResult.isRight()) {
- log.debug("Failed to retrive resource, resource id {}", resourceId);
- return false;
- }
- Resource resource = getResourceResult.left().value();
-
- return canWorkOnResource(resource, userId);
-
- }
-
- public static boolean canWorkOnService(String serviceId, IServiceOperation serviceOperation, String userId) {
- Either<Service, StorageOperationStatus> getResourceResult = serviceOperation.getLightComponent(serviceId,
- false);
-
- if (getResourceResult.isRight()) {
- log.debug("Failed to retrieve service, service id {}", serviceId);
- return false;
- }
- Service service = getResourceResult.left().value();
-
- return canWorkOnComponent(service, userId);
-
- }
-
- public static boolean canWorkOnComponent(String componentId, IComponentOperation componentOperation,
- String userId) {
- Either<Component, StorageOperationStatus> getResourceResult = componentOperation.getLightComponent(componentId,
- false);
+ public static boolean canWorkOnComponent(String componentId, ToscaOperationFacade toscaOperationFacade, String userId) {
+
+ Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseMetadata);
if (getResourceResult.isRight()) {
log.debug("Failed to retrieve component, component id {}", componentId);
return false;
}
- Component service = getResourceResult.left().value();
+ Component component = getResourceResult.left().value();
- return canWorkOnComponent(service, userId);
+ return canWorkOnComponent(component, userId);
}
-
+
public static boolean canWorkOnComponent(Component component, String userId) {
+ return canWorkOnComponent(component.getLifecycleState(), component.getLastUpdaterUserId(), userId);
+ }
+
+ private static boolean canWorkOnComponent(LifecycleStateEnum lifecycleState, String lastUpdaterUserId, String userId) {
// verify resource is checked-out
- if (component.getLifecycleState() != LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) {
+ if (lifecycleState != LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) {
log.debug("resource is not checked-out");
return false;
}
@@ -113,7 +88,7 @@ public class ComponentValidationUtils {
}
// verify resource last update user is the current user
- if (!userId.equals(component.getLastUpdaterUserId())) {
+ if (!userId.equals(lastUpdaterUserId)) {
log.debug("resource last updater userId is not {}", userId);
return false;
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/utils/GraphDeleteUtil.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/utils/GraphDeleteUtil.java
index 1d78252de2..1671b2d98b 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/utils/GraphDeleteUtil.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/utils/GraphDeleteUtil.java
@@ -58,41 +58,16 @@ public class GraphDeleteUtil {
Map<String, Object> properties = null;
if (log.isDebugEnabled()) {
properties = getProperties(incomingVertex);
- log.debug("Going to delete vertex {}", properties);
+ log.debug("Going to delete vertex {}",properties);
}
incomingVertex.remove();
if (log.isDebugEnabled()) {
- log.debug("After deleting vertex {}", properties);
+ log.debug("After deleting vertex {}",properties);
}
}
}
- //
- // if (edgesCreatorIterable != null) {
- // for (Edge edge : edgesCreatorIterable) {
- //
- // Vertex incomingVertex = edge.getVertex(Direction.IN);
- // Iterable<Edge> outEdges = incomingVertex.getEdges(Direction.OUT);
- // if (outEdges != null) {
- // if (outEdges.iterator().hasNext()) {
- // return TitanOperationStatus.CANNOT_DELETE_NON_LEAF_NODE;
- // } else {
- // Map<String, Object> properties = null;
- // if (log.isDebugEnabled()) {
- // properties = ElementHelper.getProperties(incomingVertex);
- // log.debug("Going to delete vertex {}", properties);
- // }
- // incomingVertex.remove();
- // if (log.isDebugEnabled()) {
- // log.debug("After deleting vertex {}", properties);
- // }
- // }
- // }
- //
- // }
- // }
-
return TitanOperationStatus.OK;
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/ToscaPropertyType.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/ToscaPropertyType.java
index 2bbb84dd20..079d64a60e 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/ToscaPropertyType.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/ToscaPropertyType.java
@@ -58,34 +58,27 @@ public enum ToscaPropertyType {
STRING("string", StringValidator.getInstance(), StringConvertor.getInstance(), ToscaStringConvertor.getInstance()),
- BOOLEAN("boolean", BooleanValidator.getInstance(), ToscaBooleanConverter.getInstance(),
- BooleanConverter.getInstance()),
+ BOOLEAN("boolean", BooleanValidator.getInstance(), ToscaBooleanConverter.getInstance(), BooleanConverter.getInstance()),
FLOAT("float", FloatValidator.getInstance(), ToscaFloatConverter.getInstance(), FloatConverter.getInstance()),
INTEGER("integer", IntegerValidator.getInstance(), DefaultConverter.getInstance(), IntegerConverter.getInstance()),
- SCALAR_UNIT_SIZE("scalar-unit.size", StringValidator.getInstance(), DefaultConverter.getInstance(),
- ToscaValueDefaultConverter.getInstance()),
+ SCALAR_UNIT_SIZE("scalar-unit.size", StringValidator.getInstance(), DefaultConverter.getInstance(), ToscaValueDefaultConverter.getInstance()),
- SCALAR_UNIT_TIME("scalar-unit.time", StringValidator.getInstance(), DefaultConverter.getInstance(),
- ToscaValueDefaultConverter.getInstance()),
+ SCALAR_UNIT_TIME("scalar-unit.time", StringValidator.getInstance(), DefaultConverter.getInstance(), ToscaValueDefaultConverter.getInstance()),
- SCALAR_UNIT_FREQUENCY("scalar-unit.frequency", StringValidator.getInstance(), DefaultConverter.getInstance(),
- ToscaValueDefaultConverter.getInstance()),
+ SCALAR_UNIT_FREQUENCY("scalar-unit.frequency", StringValidator.getInstance(), DefaultConverter.getInstance(), ToscaValueDefaultConverter.getInstance()),
- RANGE("range", StringValidator.getInstance(), DefaultConverter.getInstance(),
- ToscaValueDefaultConverter.getInstance()),
+ RANGE("range", StringValidator.getInstance(), DefaultConverter.getInstance(), ToscaValueDefaultConverter.getInstance()),
- TIMESTAMP("timestamp", StringValidator.getInstance(), DefaultConverter.getInstance(),
- ToscaValueDefaultConverter.getInstance()),
+ TIMESTAMP("timestamp", StringValidator.getInstance(), DefaultConverter.getInstance(), ToscaValueDefaultConverter.getInstance()),
MAP("map", MapValidator.getInstance(), MapConverter.getInstance(), ToscaMapValueConverter.getInstance()),
LIST("list", ListValidator.getInstance(), ListConverter.getInstance(), ToscaListValueConverter.getInstance()),
- VERSION("version", StringValidator.getInstance(), DefaultConverter.getInstance(),
- ToscaValueDefaultConverter.getInstance()),
+ VERSION("version", StringValidator.getInstance(), DefaultConverter.getInstance(), ToscaValueDefaultConverter.getInstance()),
KEY("key", KeyValidator.getInstance(), StringConvertor.getInstance(), ToscaValueDefaultConverter.getInstance()),
@@ -100,16 +93,14 @@ public enum ToscaPropertyType {
private ToscaValueConverter valueConverter;
private boolean isAbstract = false;
- ToscaPropertyType(String type, PropertyTypeValidator validator, PropertyValueConverter converter,
- ToscaValueConverter valueConverter) {
+ ToscaPropertyType(String type, PropertyTypeValidator validator, PropertyValueConverter converter, ToscaValueConverter valueConverter) {
this.type = type;
this.validator = validator;
this.converter = converter;
this.valueConverter = valueConverter;
}
- ToscaPropertyType(String type, PropertyTypeValidator validator, PropertyValueConverter converter,
- ToscaValueConverter valueConverter, boolean isAbstract) {
+ ToscaPropertyType(String type, PropertyTypeValidator validator, PropertyValueConverter converter, ToscaValueConverter valueConverter, boolean isAbstract) {
this(type, validator, converter, valueConverter);
this.isAbstract = isAbstract;
}
@@ -179,6 +170,17 @@ public enum ToscaPropertyType {
return isPrimitiveToscaType != null && isPrimitiveToscaType.isAbstract() == false;
}
+
+ public static boolean isPrimitiveType(String dataTypeName) {
+
+ if (ToscaPropertyType.MAP.getType().equals(dataTypeName) || ToscaPropertyType.LIST.getType().equals(dataTypeName)){
+ return false;
+ }
+ if(isScalarType(dataTypeName)){
+ return true;
+ }
+ return false;
+ }
public static ToscaPropertyType getTypeIfScalar(String dataTypeName) {
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatBooleanConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatBooleanConverter.java
index 147b2e9c52..52fa9bfa81 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatBooleanConverter.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatBooleanConverter.java
@@ -39,7 +39,7 @@ public class HeatBooleanConverter implements PropertyValueConverter {
@Override
public String convert(String value, String innerType, Map<String, DataTypeDefinition> dataTypes) {
- if (value == null) {
+ if (value == null || value.isEmpty()) {
return null;
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatCommaDelimitedListConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatCommaDelimitedListConverter.java
index a0834791ff..30c21c8c1c 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatCommaDelimitedListConverter.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatCommaDelimitedListConverter.java
@@ -39,11 +39,13 @@ public class HeatCommaDelimitedListConverter implements PropertyValueConverter {
@Override
public String convert(String original, String innerType, Map<String, DataTypeDefinition> dataTypes) {
- String coverted = ValidationUtils.removeNoneUtf8Chars(original);
- coverted = ValidationUtils.removeHtmlTagsOnly(coverted);
- coverted = ValidationUtils.normaliseWhitespace(coverted);
- coverted = ValidationUtils.stripOctets(coverted);
-
+ String coverted = null;
+ if(original != null){
+ coverted = ValidationUtils.removeNoneUtf8Chars(original);
+ coverted = ValidationUtils.removeHtmlTagsOnly(coverted);
+ coverted = ValidationUtils.normaliseWhitespace(coverted);
+ coverted = ValidationUtils.stripOctets(coverted);
+ }
return coverted;
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatNumberConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatNumberConverter.java
index 90781be367..8798b544bc 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatNumberConverter.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatNumberConverter.java
@@ -40,7 +40,7 @@ public class HeatNumberConverter implements PropertyValueConverter {
@Override
public String convert(String original, String innerType, Map<String, DataTypeDefinition> dataTypes) {
- if (original == null) {
+ if (original == null || original.isEmpty()) {
return null;
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatStringConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatStringConverter.java
index 475db1db7c..c8fac11b3a 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatStringConverter.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatStringConverter.java
@@ -39,12 +39,14 @@ public class HeatStringConverter implements PropertyValueConverter {
@Override
public String convert(String original, String innerType, Map<String, DataTypeDefinition> dataTypes) {
- String coverted = ValidationUtils.removeNoneUtf8Chars(original);
- coverted = ValidationUtils.normaliseWhitespace(coverted);
- coverted = ValidationUtils.stripOctets(coverted);
- coverted = ValidationUtils.removeHtmlTagsOnly(coverted);
- coverted = coverted.replaceAll("\"", "").replaceAll("\'", "");
-
+ String coverted = null;
+ if(original != null){
+ coverted = ValidationUtils.removeNoneUtf8Chars(original);
+ coverted = ValidationUtils.normaliseWhitespace(coverted);
+ coverted = ValidationUtils.stripOctets(coverted);
+ coverted = ValidationUtils.removeHtmlTagsOnly(coverted);
+ coverted = coverted.replaceAll("\"", "").replaceAll("\'", "");
+ }
return coverted;
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/IntegerConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/IntegerConverter.java
index 076e5aceef..30fbf69b80 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/IntegerConverter.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/IntegerConverter.java
@@ -38,6 +38,9 @@ public class IntegerConverter implements ToscaValueConverter {
@Override
public Object convertToToscaValue(String value, String innerType, Map<String, DataTypeDefinition> dataTypes) {
+ if ( value == null || value.isEmpty() ){
+ return null;
+ }
return Integer.parseInt(value);
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ListConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ListConverter.java
index 8265cc2690..4f6de9b80c 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ListConverter.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ListConverter.java
@@ -112,6 +112,8 @@ public class ListConverter implements PropertyValueConverter {
ArrayList<String> newList = new ArrayList<String>();
JsonArray jo = (JsonArray) jsonParser.parse(value);
+ if(ToscaPropertyType.JSON == innerToscaType)
+ return Either.left(value);
int size = jo.size();
for (int i = 0; i < size; i++) {
JsonElement currentValue = jo.get(i);
@@ -166,7 +168,7 @@ public class ListConverter implements PropertyValueConverter {
}
} catch (JsonParseException e) {
- log.debug("Failed to parse json : {}. {}", value, e);
+ log.debug("Failed to parse json : {}", value, e);
BeEcompErrorManager.getInstance().logBeInvalidJsonInput("List Converter");
return Either.right(false);
}
@@ -199,7 +201,7 @@ public class ListConverter implements PropertyValueConverter {
ImmutablePair<JsonElement, Boolean> validateAndUpdate = dataTypeValidatorConverter
.validateAndUpdate(element, dataTypeDefinition, allDataTypes);
if (validateAndUpdate.right.booleanValue() == false) {
- log.debug("Cannot parse value {} from type {} in list position {}", currentValue, innerType, i);
+ log.debug("Cannot parse value {} from type {} in list position {}",currentValue,innerType,i);
return Either.right(false);
}
JsonElement newValue = validateAndUpdate.left;
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/MapConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/MapConverter.java
index 921c6d0d41..30b895f0d2 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/MapConverter.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/MapConverter.java
@@ -181,7 +181,7 @@ public class MapConverter implements PropertyValueConverter {
log.debug("inner Tosca Type unknown : {}", innerToscaType);
}
} catch (JsonParseException e) {
- log.debug("Failed to parse json : {}. {}", value, e);
+ log.debug("Failed to parse json : {}", value, e);
BeEcompErrorManager.getInstance().logBeInvalidJsonInput("Map Converter");
return Either.right(false);
}
@@ -227,7 +227,7 @@ public class MapConverter implements PropertyValueConverter {
ImmutablePair<JsonElement, Boolean> validateAndUpdate = dataTypeValidatorConverter
.validateAndUpdate(element, dataTypeDefinition, allDataTypes);
if (validateAndUpdate.right.booleanValue() == false) {
- log.debug("Cannot parse value {} from type {} of key {}", currentValue, innerType, currentKey);
+ log.debug("Cannot parse value {} from type {} of key {}",currentValue,innerType,currentKey);
return Either.right(false);
}
JsonElement newValue = validateAndUpdate.left;
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaListValueConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaListValueConverter.java
index 043446e783..d8198dac6b 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaListValueConverter.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaListValueConverter.java
@@ -109,13 +109,14 @@ public class ToscaListValueConverter extends ToscaValueBaseConverter implements
asJsonArray.forEach(e -> {
Object convertedValue = null;
if (isScalarF) {
- log.debug("try to convert scalar value {}", e.getAsString());
- if (e.getAsString() == null) {
+ String jsonAsString = e.toString();
+ log.debug("try to convert scalar value {}", jsonAsString);
+ if ( jsonAsString == null) {
convertedValue = null;
} else {
- JsonElement singleElement = jsonParser.parse(e.getAsString());
+ JsonElement singleElement = jsonParser.parse(jsonAsString);
if (singleElement.isJsonPrimitive()) {
- convertedValue = innerConverterFinal.convertToToscaValue(e.getAsString(), innerType,
+ convertedValue = innerConverterFinal.convertToToscaValue(jsonAsString, innerType,
dataTypes);
} else {
convertedValue = handleComplexJsonValue(singleElement);
@@ -128,16 +129,14 @@ public class ToscaListValueConverter extends ToscaValueBaseConverter implements
DataTypeDefinition dataTypeDefinition = dataTypes.get(innerType);
Map<String, PropertyDefinition> allProperties = getAllProperties(dataTypeDefinition);
Map<String, Object> toscaObjectPresentation = new HashMap<>();
- // log.debug("try to convert datatype value {}",
- // e.getAsString());
-
+
for (Entry<String, JsonElement> entry : entrySet) {
String propName = entry.getKey();
JsonElement elementValue = entry.getValue();
PropertyDefinition propertyDefinition = allProperties.get(propName);
if (propertyDefinition == null) {
- log.debug("The property {} was not found under data type {}", propName, dataTypeDefinition.getName());
+ log.debug("The property {} was not found under data type {}",propName,dataTypeDefinition.getName());
continue;
// return null;
}
@@ -173,7 +172,7 @@ public class ToscaListValueConverter extends ToscaValueBaseConverter implements
} catch (
JsonParseException e) {
- log.debug("Failed to parse json : {}. {}", value, e);
+ log.debug("Failed to parse json : {}", value, e);
BeEcompErrorManager.getInstance().logBeInvalidJsonInput("List Converter");
return null;
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaMapValueConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaMapValueConverter.java
index 601d8f0fc8..80b8779e1e 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaMapValueConverter.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaMapValueConverter.java
@@ -21,7 +21,9 @@
package org.openecomp.sdc.be.model.tosca.converters;
import java.io.StringReader;
+import java.util.ArrayList;
import java.util.HashMap;
+import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
@@ -33,6 +35,7 @@ import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
@@ -63,6 +66,7 @@ public class ToscaMapValueConverter extends ToscaValueBaseConverter implements T
ToscaPropertyType innerToscaType = ToscaPropertyType.isValidType(innerType);
ToscaValueConverter innerConverter = null;
boolean isScalar = true;
+ List<PropertyDefinition> allPropertiesRecursive = new ArrayList<>();
if (innerToscaType != null) {
innerConverter = innerToscaType.getValueConverter();
} else {
@@ -74,9 +78,14 @@ public class ToscaMapValueConverter extends ToscaValueBaseConverter implements T
innerConverter = toscaPropertyType.getValueConverter();
} else {
isScalar = false;
+ allPropertiesRecursive.addAll(dataTypeDefinition.getProperties());
+ DataTypeDefinition derivedFrom = dataTypeDefinition.getDerivedFrom();
+ while ( !derivedFrom.getName().equals("tosca.datatypes.Root") ){
+ allPropertiesRecursive.addAll(derivedFrom.getProperties());
+ derivedFrom = derivedFrom.getDerivedFrom();
+ }
}
} else {
- // TODO handle getinput
log.debug("inner Tosca Type is null");
return value;
}
@@ -105,21 +114,47 @@ public class ToscaMapValueConverter extends ToscaValueBaseConverter implements T
final boolean isScalarF = isScalar;
final ToscaValueConverter innerConverterFinal = innerConverter;
entrySet.forEach(e -> {
- log.debug("try convert element {}", e.getValue());
- Object convertedValue = convertDataTypeToToscaMap(innerType, dataTypes, innerConverterFinal, isScalarF,
- e.getValue());
- toscaMap.put(e.getKey(), convertedValue);
+ convertEntry(innerType, dataTypes, allPropertiesRecursive, toscaMap, isScalarF, innerConverterFinal, e);
});
return toscaMap;
} catch (JsonParseException e) {
- log.debug("Failed to parse json : {}. {}", value, e);
+ log.debug("Failed to parse json : {}", value, e);
BeEcompErrorManager.getInstance().logBeInvalidJsonInput("List Converter");
return null;
}
}
- public Object convertDataTypeToToscaMap(String innerType, Map<String, DataTypeDefinition> dataTypes,
- ToscaValueConverter innerConverter, final boolean isScalarF, JsonElement entryValue) {
+ private void convertEntry(String innerType, Map<String, DataTypeDefinition> dataTypes, List<PropertyDefinition> allPropertiesRecursive, Map<String, Object> toscaMap, final boolean isScalarF, final ToscaValueConverter innerConverterFinal,
+ Entry<String, JsonElement> e) {
+ log.debug("try convert element {}", e.getValue());
+ boolean scalar = false;
+ String propType = null;
+ ToscaValueConverter innerConverterProp = innerConverterFinal;
+ if ( isScalarF ){
+ scalar = isScalarF;
+ propType = innerType;
+ }else{
+ for ( PropertyDefinition pd : allPropertiesRecursive ){
+ if ( pd.getName().equals(e.getKey()) ){
+ propType = pd.getType();
+ DataTypeDefinition pdDataType = dataTypes.get(propType);
+ ToscaPropertyType toscaPropType = isScalarType(pdDataType);
+ if ( toscaPropType == null ){
+ scalar = false;
+ }else{
+ scalar = true;
+ propType = toscaPropType.getType();
+ innerConverterProp = toscaPropType.getValueConverter();
+ }
+ break;
+ }
+ }
+ }
+ Object convertedValue = convertDataTypeToToscaObject(propType, dataTypes, innerConverterProp, scalar, e.getValue());
+ toscaMap.put(e.getKey(), convertedValue);
+ }
+
+ public Object convertDataTypeToToscaObject(String innerType, Map<String, DataTypeDefinition> dataTypes, ToscaValueConverter innerConverter, final boolean isScalarF, JsonElement entryValue) {
Object convertedValue = null;
if (isScalarF && entryValue.isJsonPrimitive()) {
log.debug("try convert scalar value {}", entryValue.getAsString());
@@ -129,25 +164,52 @@ public class ToscaMapValueConverter extends ToscaValueBaseConverter implements T
convertedValue = innerConverter.convertToToscaValue(entryValue.getAsString(), innerType, dataTypes);
}
} else {
- JsonObject asJsonObjectIn = entryValue.getAsJsonObject();
- Set<Entry<String, JsonElement>> entrySetIn = asJsonObjectIn.entrySet();
-
- DataTypeDefinition dataTypeDefinition = dataTypes.get(innerType);
- Map<String, PropertyDefinition> allProperties = getAllProperties(dataTypeDefinition);
- Map<String, Object> toscaObjectPresentation = new HashMap<>();
-
- for (Entry<String, JsonElement> entry : entrySetIn) {
- String propName = entry.getKey();
-
- JsonElement elementValue = entry.getValue();
- Object convValue;
- if (isScalarF == false) {
- PropertyDefinition propertyDefinition = allProperties.get(propName);
- if (propertyDefinition == null && isScalarF) {
- log.debug("The property {} was not found under data type {}", propName, dataTypeDefinition.getName());
- continue;
- }
+ if ( entryValue.isJsonPrimitive() ){
+ return handleComplexJsonValue(entryValue);
+ }
+
+ // Tal G ticket 228696523 created / DE272734 / Bug 154492 Fix
+ if(entryValue instanceof JsonArray) {
+ ArrayList<Object> toscaObjectPresentationArray = new ArrayList<>();
+ JsonArray jsonArray = entryValue.getAsJsonArray();
+
+ for (JsonElement jsonElement : jsonArray) {
+ Object convertedDataTypeToToscaMap = convertDataTypeToToscaMap(innerType, dataTypes, isScalarF, jsonElement);
+ toscaObjectPresentationArray.add(convertedDataTypeToToscaMap);
+ }
+ convertedValue = toscaObjectPresentationArray;
+ } else {
+ convertedValue = convertDataTypeToToscaMap(innerType, dataTypes, isScalarF, entryValue);
+ }
+ }
+ return convertedValue;
+ }
+ private Object convertDataTypeToToscaMap(String innerType, Map<String, DataTypeDefinition> dataTypes,
+ final boolean isScalarF, JsonElement entryValue) {
+ Object convertedValue;
+ JsonObject asJsonObjectIn = entryValue.getAsJsonObject();
+ Set<Entry<String, JsonElement>> entrySetIn = asJsonObjectIn.entrySet();
+
+ DataTypeDefinition dataTypeDefinition = dataTypes.get(innerType);
+ Map<String, PropertyDefinition> allProperties = getAllProperties(dataTypeDefinition);
+ Map<String, Object> toscaObjectPresentation = new HashMap<>();
+
+ for (Entry<String, JsonElement> entry : entrySetIn) {
+ String propName = entry.getKey();
+
+ JsonElement elementValue = entry.getValue();
+ Object convValue;
+ if (isScalarF == false) {
+ PropertyDefinition propertyDefinition = allProperties.get(propName);
+ if (propertyDefinition == null) {
+ log.trace("The property {} was not found under data type . Parse as map", propName);
+ if (elementValue.isJsonPrimitive()) {
+ convValue = elementValue.getAsString();
+ } else {
+ convValue = handleComplexJsonValue(elementValue);
+ }
+ } else {
String type = propertyDefinition.getType();
ToscaPropertyType propertyType = ToscaPropertyType.isValidType(type);
if (propertyType != null) {
@@ -165,19 +227,21 @@ public class ToscaMapValueConverter extends ToscaValueBaseConverter implements T
}
}
} else {
- convValue = convertToToscaValue(elementValue.getAsString(), type, dataTypes);
+ convValue = convertToToscaValue(elementValue.toString(), type, dataTypes);
}
+ }
+ } else {
+ if (elementValue.isJsonPrimitive()) {
+ convValue = json2JavaPrimitive(elementValue.getAsJsonPrimitive());
} else {
- if (elementValue.isJsonPrimitive()) {
- convValue = json2JavaPrimitive(elementValue.getAsJsonPrimitive());
- } else {
- convValue = handleComplexJsonValue(elementValue);
- }
+ convValue = handleComplexJsonValue(elementValue);
}
+ }
+ if(!isEmptyObjectValue(convValue)){
toscaObjectPresentation.put(propName, convValue);
}
- convertedValue = toscaObjectPresentation;
}
+ convertedValue = toscaObjectPresentation;
return convertedValue;
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaValueBaseConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaValueBaseConverter.java
index e886327481..7e2f8766ba 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaValueBaseConverter.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaValueBaseConverter.java
@@ -86,7 +86,7 @@ public class ToscaValueBaseConverter {
Object jsonValue = null;
Map<String, Object> value = new HashMap<String, Object>();
- if ( elementValue.isJsonObject() ){
+ if (elementValue.isJsonObject()) {
JsonObject jsonOb = elementValue.getAsJsonObject();
Set<Entry<String, JsonElement>> entrySet = jsonOb.entrySet();
Iterator<Entry<String, JsonElement>> iteratorEntry = entrySet.iterator();
@@ -106,14 +106,18 @@ public class ToscaValueBaseConverter {
}
}
jsonValue = value;
- }else{
- if ( elementValue.isJsonArray() ){
+ } else {
+ if (elementValue.isJsonArray()) {
jsonValue = handleJsonArray(elementValue);
- }else{
- log.debug("not supported json type {} ",elementValue);
+ } else {
+ if (elementValue.isJsonPrimitive()) {
+ jsonValue = json2JavaPrimitive(elementValue.getAsJsonPrimitive());
+ } else {
+ log.debug("not supported json type {} ", elementValue);
+ }
}
}
-
+
return jsonValue;
}
@@ -150,4 +154,24 @@ public class ToscaValueBaseConverter {
throw new IllegalStateException();
}
}
+
+ /**
+ * checks is received Object empty or equals null or not It is relevant only
+ * if received Object is instance of String, Map or List class.
+ *
+ * @param convertedValue
+ * @return
+ */
+ static public boolean isEmptyObjectValue(Object convertedValue) {
+ if (convertedValue == null) {
+ return true;
+ } else if (convertedValue instanceof String && ((String) convertedValue).isEmpty()) {
+ return true;
+ } else if (convertedValue instanceof Map && ((Map) convertedValue).isEmpty()) {
+ return true;
+ } else if (convertedValue instanceof List && ((List) convertedValue).isEmpty()) {
+ return true;
+ }
+ return false;
+ }
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/DataTypeValidatorConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/DataTypeValidatorConverter.java
index d376a1ec13..3240ccc679 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/DataTypeValidatorConverter.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/DataTypeValidatorConverter.java
@@ -88,8 +88,7 @@ public class DataTypeValidatorConverter {
return result;
}
- private ImmutablePair<JsonElement, Boolean> validateAndUpdate(JsonElement jsonElement,
- DataTypeDefinition dataTypeDefinition, Map<String, DataTypeDefinition> allDataTypes) {
+ private ImmutablePair<JsonElement, Boolean> validateAndUpdate(JsonElement jsonElement, DataTypeDefinition dataTypeDefinition, Map<String, DataTypeDefinition> allDataTypes) {
Map<String, PropertyDefinition> allProperties = getAllProperties(dataTypeDefinition);
@@ -100,14 +99,14 @@ public class DataTypeValidatorConverter {
PropertyValueConverter converter = toscaPropertyType.getConverter();
if (jsonElement == null || true == jsonElement.isJsonNull()) {
boolean valid = validator.isValid(null, null, allDataTypes);
- if (false == valid) {
- log.trace("Failed in validation of property {} from type {}", dataTypeDefinition.getName(), dataTypeDefinition.getName());
+ if (!valid) {
+ log.trace("Failed in validation of property {} from type {}", dataTypeDefinition.getName(), dataTypeDefinition.getName());
return falseResult;
}
return new ImmutablePair<JsonElement, Boolean>(jsonElement, true);
} else {
- if (true == jsonElement.isJsonPrimitive()) {
+ if (jsonElement.isJsonPrimitive()) {
String value = null;
if (jsonElement != null) {
if (jsonElement.toString().isEmpty()) {
@@ -117,7 +116,7 @@ public class DataTypeValidatorConverter {
}
}
boolean valid = validator.isValid(value, null, null);
- if (false == valid) {
+ if (!valid) {
log.trace("Failed in validation of property {} from type {}. Json primitive value is {}", dataTypeDefinition.getName(), dataTypeDefinition.getName(), value);
return falseResult;
}
@@ -127,7 +126,7 @@ public class DataTypeValidatorConverter {
try {
element = jsonParser.parse(convertedValue);
} catch (JsonSyntaxException e) {
- log.debug("Failed to parse value {} of property {}. {}", convertedValue, dataTypeDefinition.getName(), e);
+ log.debug("Failed to parse value {} of property {} {}", convertedValue, dataTypeDefinition.getName(), e);
return falseResult;
}
@@ -164,13 +163,13 @@ public class DataTypeValidatorConverter {
PropertyDefinition propertyDefinition = allProperties.get(propName);
if (propertyDefinition == null) {
- log.debug("The property {} was not found under data type {}", propName, dataTypeDefinition.getName());
+ log.debug("The property {} was not found under data type {}" ,propName, dataTypeDefinition.getName());
return falseResult;
}
String type = propertyDefinition.getType();
boolean isScalarType = ToscaPropertyType.isScalarType(type);
- if (true == isScalarType) {
+ if (isScalarType) {
ToscaPropertyType propertyType = ToscaPropertyType.isValidType(type);
if (propertyType == null) {
log.debug("cannot find the {} under default tosca property types", type);
@@ -179,8 +178,7 @@ public class DataTypeValidatorConverter {
PropertyTypeValidator validator = propertyType.getValidator();
String innerType = null;
if (propertyType == ToscaPropertyType.LIST || propertyType == ToscaPropertyType.MAP) {
- if (propertyDefinition.getSchema() != null
- && propertyDefinition.getSchema().getProperty() != null) {
+ if (propertyDefinition.getSchema() != null && propertyDefinition.getSchema().getProperty() != null) {
innerType = propertyDefinition.getSchema().getProperty().getType();
if (innerType == null) {
log.debug("Property type {} must have inner type in its declaration.", propertyType);
@@ -215,7 +213,7 @@ public class DataTypeValidatorConverter {
try {
element = jsonParser.parse(convertedValue);
} catch (JsonSyntaxException e) {
- log.debug("Failed to parse value {} of type {}. {}", convertedValue, propertyType, e);
+ log.debug("Failed to parse value {} of type {}", convertedValue, propertyType, e);
return falseResult;
}
}
@@ -226,14 +224,13 @@ public class DataTypeValidatorConverter {
DataTypeDefinition typeDefinition = allDataTypes.get(type);
if (typeDefinition == null) {
- log.debug("The data type {] cannot be found in the given data type list.", type);
+ log.debug("The data type {} cannot be found in the given data type list.", type);
return falseResult;
}
- ImmutablePair<JsonElement, Boolean> isValid = validateAndUpdate(elementValue,
- typeDefinition, allDataTypes);
+ ImmutablePair<JsonElement, Boolean> isValid = validateAndUpdate(elementValue, typeDefinition, allDataTypes);
- if (false == isValid.getRight().booleanValue()) {
+ if (!isValid.getRight().booleanValue()) {
log.debug("Failed in validation of value {} from type {}", (elementValue != null ? elementValue.toString() : null), typeDefinition.getName());
return falseResult;
}
@@ -254,8 +251,7 @@ public class DataTypeValidatorConverter {
}
- public ImmutablePair<JsonElement, Boolean> validateAndUpdate(String value, DataTypeDefinition dataTypeDefinition,
- Map<String, DataTypeDefinition> allDataTypes) {
+ public ImmutablePair<JsonElement, Boolean> validateAndUpdate(String value, DataTypeDefinition dataTypeDefinition, Map<String, DataTypeDefinition> allDataTypes) {
ImmutablePair<JsonElement, Boolean> result = falseResult;
@@ -308,8 +304,7 @@ public class DataTypeValidatorConverter {
return value;
}
- public boolean isValid(String value, DataTypeDefinition dataTypeDefinition,
- Map<String, DataTypeDefinition> allDataTypes) {
+ public boolean isValid(String value, DataTypeDefinition dataTypeDefinition, Map<String, DataTypeDefinition> allDataTypes) {
boolean result = false;
@@ -321,7 +316,7 @@ public class DataTypeValidatorConverter {
try {
jsonElement = jsonParser.parse(value);
} catch (JsonSyntaxException e) {
- log.debug("Failed to parse the value {} from type {}. {}", value, dataTypeDefinition, e);
+ log.debug("Failed to parse the value {} from type {}", value, dataTypeDefinition, e);
return false;
}
@@ -330,8 +325,7 @@ public class DataTypeValidatorConverter {
return result;
}
- private boolean isValid(JsonElement jsonElement, DataTypeDefinition dataTypeDefinition,
- Map<String, DataTypeDefinition> allDataTypes) {
+ private boolean isValid(JsonElement jsonElement, DataTypeDefinition dataTypeDefinition, Map<String, DataTypeDefinition> allDataTypes) {
Map<String, PropertyDefinition> allProperties = getAllProperties(dataTypeDefinition);
@@ -342,8 +336,7 @@ public class DataTypeValidatorConverter {
if (jsonElement == null || true == jsonElement.isJsonNull()) {
boolean valid = validator.isValid(null, null, allDataTypes);
if (false == valid) {
- log.trace("Failed in validation of property " + dataTypeDefinition.getName() + " from type "
- + dataTypeDefinition.getName());
+ log.trace("Failed in validation of property {} from type {}", dataTypeDefinition.getName(), dataTypeDefinition.getName());
return false;
}
@@ -396,7 +389,7 @@ public class DataTypeValidatorConverter {
PropertyDefinition propertyDefinition = allProperties.get(propName);
if (propertyDefinition == null) {
- log.debug("The property {} was not found under data tpye {}", propName, dataTypeDefinition.getName());
+ log.debug("The property {} was not found under data type {}", propName, dataTypeDefinition.getName());
return false;
}
String type = propertyDefinition.getType();
@@ -411,11 +404,10 @@ public class DataTypeValidatorConverter {
PropertyTypeValidator validator = propertyType.getValidator();
String innerType = null;
if (propertyType == ToscaPropertyType.LIST || propertyType == ToscaPropertyType.MAP) {
- if (propertyDefinition.getSchema() != null
- && propertyDefinition.getSchema().getProperty() != null) {
+ if (propertyDefinition.getSchema() != null && propertyDefinition.getSchema().getProperty() != null) {
innerType = propertyDefinition.getSchema().getProperty().getType();
if (innerType == null) {
- log.debug("Property type {} must have inner type in its decleration.", propertyType);
+ log.debug("Property type {} must have inner type in its declaration.", propertyType);
return false;
}
}
@@ -440,7 +432,7 @@ public class DataTypeValidatorConverter {
DataTypeDefinition typeDefinition = allDataTypes.get(type);
if (typeDefinition == null) {
- log.debug("The data type {} canot be found in the given data type list.", type);
+ log.debug("The data type {} cannot be found in the given data type list.", type);
return false;
}
@@ -465,35 +457,4 @@ public class DataTypeValidatorConverter {
}
}
-
- // public ImmutablePair<String, Boolean>
- // validateAndUpdateAndReturnString(String value, DataTypeDefinition
- // dataTypeDefinition, Map<String, DataTypeDefinition> allDataTypes) {
- //
- // ImmutablePair<JsonElement, Boolean> result = falseResult;
- //
- // if (value == null || value.isEmpty()) {
- // return trueStringEmptyResult;
- // }
- //
- // JsonElement jsonElement = null;
- // try {
- // jsonElement = jsonParser.parse(value);
- // } catch (JsonSyntaxException e) {
- // return falseStringEmptyResult;
- // }
- //
- // result = validateAndUpdate(jsonElement, dataTypeDefinition,
- // allDataTypes);
- //
- // if (result.right.booleanValue() == false) {
- // log.debug("The value {} of property from type {} is invalid", value, dataTypeDefinition.getName());
- // return new ImmutablePair<String, Boolean>(value, false);
- // }
- //
- // String valueFromJsonElement = getValueFromJsonElement(result.left);
- //
- // return new ImmutablePair<String, Boolean>(valueFromJsonElement, true);
- // }
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/ListValidator.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/ListValidator.java
index 92834690b8..177dcb60ea 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/ListValidator.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/ListValidator.java
@@ -84,7 +84,7 @@ public class ListValidator implements PropertyTypeValidator {
innerValidator = ToscaPropertyType.JSON.getValidator();
break;
default:
- log.debug("inner Tosca Type is unknown: {}", innerToscaType);
+ log.debug("inner Tosca Type is unknown. {}", innerToscaType);
return false;
}
@@ -92,12 +92,14 @@ public class ListValidator implements PropertyTypeValidator {
log.debug("inner Tosca Type is: {}", innerType);
boolean isValid = validateComplexInnerType(value, innerType, allDataTypes);
- log.debug("Finish to validate value {} of list with inner type {}. result is: {}", value, innerType, isValid);
+ log.debug("Finish to validate value {} of list with inner type {}. result is {}",value,innerType,isValid);
return isValid;
}
try {
JsonArray jo = (JsonArray) jsonParser.parse(value);
+ if(ToscaPropertyType.JSON == innerToscaType)
+ return true;
int size = jo.size();
for (int i = 0; i < size; i++) {
JsonElement currentValue = jo.get(i);
@@ -111,7 +113,7 @@ public class ListValidator implements PropertyTypeValidator {
return true;
} catch (JsonSyntaxException e) {
- log.debug("Failed to parse json : {}. {}", value, e);
+ log.debug("Failed to parse json : {}", value, e);
BeEcompErrorManager.getInstance().logBeInvalidJsonInput("List Validator");
}
@@ -144,7 +146,7 @@ public class ListValidator implements PropertyTypeValidator {
boolean isValid = dataTypeValidatorConverter.isValid(element, innerDataTypeDefinition,
allDataTypes);
if (isValid == false) {
- log.debug("Cannot parse value {} from type {} in list parameter", currentValue, innerType);
+ log.debug("Cannot parse value {} from type {} in list parameter",currentValue,innerType);
return false;
}
}
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 c8ffc3f4b8..7c86b6da1b 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
@@ -101,7 +101,7 @@ public class MapValidator implements PropertyTypeValidator {
innerValidator = ToscaPropertyType.JSON.getValidator();
break;
default:
- log.debug("inner Tosca Type is unknown: {}", innerToscaType);
+ log.debug("inner Tosca Type is unknown. {}", innerToscaType);
return false;
}
@@ -109,7 +109,7 @@ public class MapValidator implements PropertyTypeValidator {
log.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);
+ log.debug("Finish to validate value {} of map with inner type {}. result is {}",value,innerType,isValid);
return isValid;
}
@@ -126,14 +126,14 @@ public class MapValidator implements PropertyTypeValidator {
if (!innerValidator.isValid(element, null, allDataTypes)
|| !keyValidator.isValid(entry.getKey(), null, allDataTypes)) {
- log.debug("validation of key : {}, element: {} failed", currentKey, entry.getValue());
+ log.debug("validation of key : {}, element : {} failed", currentKey, entry.getValue());
return false;
}
}
return true;
} catch (JsonSyntaxException e) {
- log.debug("Failed to parse json : {}. {}", value, e);
+ log.debug("Failed to parse json : {}", value, e);
BeEcompErrorManager.getInstance().logBeInvalidJsonInput("Map Validator");
}
@@ -162,15 +162,15 @@ public class MapValidator implements PropertyTypeValidator {
String element = JsonUtils.toString(currentValue);
boolean isValid = dataTypeValidatorConverter.isValid(element, innerDataTypeDefinition,
allDataTypes);
- if (isValid == false) {
- log.debug("Cannot parse value {} from type {} of key {}", currentValue, innerType, currentKey);
+ if (!isValid) {
+ log.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);
+ log.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/model/tosca/validators/PropertyTypeValidator.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/PropertyTypeValidator.java
index 35862148f9..f0cf225c0a 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/PropertyTypeValidator.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/PropertyTypeValidator.java
@@ -30,16 +30,16 @@ public interface PropertyTypeValidator {
boolean isValid(String value, String innerType);
/*
- * The value format should be validated according to the “Property Type�? :
- * “integer�? - valid tag:yaml.org,2002:int , the number base 8,10,18 should
+ * The value format should be validated according to the "Property Type" :
+ * "integer" - valid tag:yaml.org,2002:int , the number base 8,10,18 should
* be handled ( hint : to validate by calling parseInt(
* s,10)/parseInt(s,16)/parseInt(s,8) or just regexp [-+]?[0-9]+ for Base 10
* , [-+]?0[0-7]+ for Base 8 , [-+]?0x[0-9a-fA-F]+ for Base 16
*
- * “float�? - valid tag:yaml.org,2002:float , parseFloat() “boolean�? - valid
- * tag:yaml.org,2002:bool : can be only “true�? or “false�? ( upper case
+ * "float" - valid tag:yaml.org,2002:float , parseFloat() "boolean" - valid
+ * tag:yaml.org,2002:bool : can be only "true" or "false" ( upper case
* characters should be converted to lower case : TRUE ->true, True->true
- * “string�? - valid tag:yaml.org,2002:str and limited to 100 chars.
+ * "string" - valid tag:yaml.org,2002:str and limited to 100 chars.
*
*/
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/StringValidator.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/StringValidator.java
index 06994505a9..750941cc0b 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/StringValidator.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/StringValidator.java
@@ -31,23 +31,19 @@ import org.slf4j.LoggerFactory;
public class StringValidator implements PropertyTypeValidator {
- public static final int DEFAULT_STRING_MAXIMUM_LENGTH = 100;
+ public static final int DEFAULT_STRING_MAXIMUM_LENGTH = 2500;
- public static int STRING_MAXIMUM_LENGTH = DEFAULT_STRING_MAXIMUM_LENGTH;
+ private static int STRING_MAXIMUM_LENGTH = DEFAULT_STRING_MAXIMUM_LENGTH;
private static Logger log = LoggerFactory.getLogger(StringValidator.class.getName());
private static StringValidator stringValidator = new StringValidator();
- public static StringValidator getInstance() {
- return stringValidator;
- }
-
private StringValidator() {
if (ConfigurationManager.getConfigurationManager() != null) {
ToscaValidatorsConfig toscaValidators = ConfigurationManager.getConfigurationManager().getConfiguration()
.getToscaValidators();
- log.debug("toscaValidators={}", toscaValidators);
+ log.debug("toscaValidators= {}", toscaValidators);
if (toscaValidators != null) {
Integer stringMaxLength = toscaValidators.getStringMaxLength();
if (stringMaxLength != null) {
@@ -57,6 +53,10 @@ public class StringValidator implements PropertyTypeValidator {
}
}
+ public static StringValidator getInstance() {
+ return stringValidator;
+ }
+
@Override
public boolean isValid(String value, String innerType, Map<String, DataTypeDefinition> allDataTypes) {
@@ -65,14 +65,14 @@ public class StringValidator implements PropertyTypeValidator {
}
if (value.length() > STRING_MAXIMUM_LENGTH) {
- log.debug("parameter String length {} is higher the configured({})", value.length(), STRING_MAXIMUM_LENGTH);
+ log.debug("parameter String length {} is higher than configured({})", value.length(), STRING_MAXIMUM_LENGTH);
return false;
}
String coverted = ValidationUtils.removeNoneUtf8Chars(value);
boolean isValid = ValidationUtils.validateIsAscii(coverted);
- if (false == isValid) {
- log.debug("parameter String value {} is not ascii string.", (value != null ? value.substring(0, Math.min(value.length(), 20)) : null));
+ if (false == isValid && log.isDebugEnabled()) {
+ log.debug("parameter String value {} is not an ascii string.", value.substring(0, Math.min(value.length(), 20)));
}
return isValid;
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiCategories.java b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiCategories.java
new file mode 100644
index 0000000000..75ad6c3794
--- /dev/null
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiCategories.java
@@ -0,0 +1,31 @@
+package org.openecomp.sdc.be.ui.model;
+
+import java.util.List;
+
+import org.openecomp.sdc.be.model.category.CategoryDefinition;
+
+public class UiCategories {
+
+ private List<CategoryDefinition> resourceCategories;
+ private List<CategoryDefinition> serviceCategories;
+ private List<CategoryDefinition> productCategories;
+
+ public List<CategoryDefinition> getResourceCategories() {
+ return resourceCategories;
+ }
+ public void setResourceCategories(List<CategoryDefinition> resourceCategories) {
+ this.resourceCategories = resourceCategories;
+ }
+ public List<CategoryDefinition> getServiceCategories() {
+ return serviceCategories;
+ }
+ public void setServiceCategories(List<CategoryDefinition> serviceCategories) {
+ this.serviceCategories = serviceCategories;
+ }
+ public List<CategoryDefinition> getProductCategories() {
+ return productCategories;
+ }
+ public void setProductCategories(List<CategoryDefinition> productCategories) {
+ this.productCategories = productCategories;
+ }
+}
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
new file mode 100644
index 0000000000..6eb7b841ab
--- /dev/null
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiComponentDataTransfer.java
@@ -0,0 +1,255 @@
+package org.openecomp.sdc.be.ui.model;
+
+import java.util.List;
+import java.util.Map;
+
+import org.openecomp.sdc.be.datatypes.components.ComponentMetadataDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.model.AdditionalInformationDefinition;
+import org.openecomp.sdc.be.model.ArtifactDefinition;
+import org.openecomp.sdc.be.model.AttributeDefinition;
+import org.openecomp.sdc.be.model.CapabilityDefinition;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.ComponentInstanceAttribute;
+import org.openecomp.sdc.be.model.ComponentInstanceInput;
+import org.openecomp.sdc.be.model.ComponentInstanceProperty;
+import org.openecomp.sdc.be.model.GroupDefinition;
+import org.openecomp.sdc.be.model.InputDefinition;
+import org.openecomp.sdc.be.model.InterfaceDefinition;
+import org.openecomp.sdc.be.model.PropertyDefinition;
+import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
+import org.openecomp.sdc.be.model.RequirementDefinition;
+import org.openecomp.sdc.be.model.category.CategoryDefinition;
+
+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 List<RequirementCapabilityRelDef> componentInstancesRelations;
+
+ private Map<String, List<ComponentInstanceInput>> componentInstancesInputs;
+
+ private Map<String, List<ComponentInstanceProperty>> componentInstancesProperties;
+
+ private Map<String, List<ComponentInstanceAttribute>> componentInstancesAttributes;
+
+ private Map<String, List<CapabilityDefinition>> capabilities;
+
+ private Map<String, List<RequirementDefinition>> requirements;
+
+ private List<InputDefinition> inputs;
+
+ private List<GroupDefinition> groups;
+
+ protected List<AdditionalInformationDefinition> additionalInformation;
+
+
+
+ public Map<String, ArtifactDefinition> getArtifacts() {
+ return artifacts;
+ }
+
+
+ public void setArtifacts(Map<String, ArtifactDefinition> artifacts) {
+ this.artifacts = artifacts;
+ }
+
+
+ public Map<String, ArtifactDefinition> getDeploymentArtifacts() {
+ return deploymentArtifacts;
+ }
+
+
+ public void setDeploymentArtifacts(Map<String, ArtifactDefinition> deploymentArtifacts) {
+ this.deploymentArtifacts = deploymentArtifacts;
+ }
+
+
+ public Map<String, ArtifactDefinition> getToscaArtifacts() {
+ return toscaArtifacts;
+ }
+
+
+ public void setToscaArtifacts(Map<String, ArtifactDefinition> toscaArtifacts) {
+ this.toscaArtifacts = toscaArtifacts;
+ }
+
+
+ public List<CategoryDefinition> getCategories() {
+ return categories;
+ }
+
+
+ public void setCategories(List<CategoryDefinition> categories) {
+ this.categories = categories;
+ }
+
+
+ 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 ComponentTypeEnum getComponentType() {
+ return componentType;
+ }
+
+
+ public void setComponentType(ComponentTypeEnum componentType) {
+ this.componentType = componentType;
+ }
+
+
+ public List<ComponentInstance> getComponentInstances() {
+ return componentInstances;
+ }
+
+
+ public void setComponentInstances(List<ComponentInstance> componentInstances) {
+ this.componentInstances = componentInstances;
+ }
+
+
+ public List<RequirementCapabilityRelDef> getComponentInstancesRelations() {
+ return componentInstancesRelations;
+ }
+
+
+ public void setComponentInstancesRelations(List<RequirementCapabilityRelDef> componentInstancesRelations) {
+ this.componentInstancesRelations = componentInstancesRelations;
+ }
+
+
+ public Map<String, List<ComponentInstanceInput>> getComponentInstancesInputs() {
+ return componentInstancesInputs;
+ }
+
+
+ public void setComponentInstancesInputs(Map<String, List<ComponentInstanceInput>> componentInstancesInputs) {
+ this.componentInstancesInputs = componentInstancesInputs;
+ }
+
+
+ public Map<String, List<ComponentInstanceProperty>> getComponentInstancesProperties() {
+ return componentInstancesProperties;
+ }
+
+
+ public void setComponentInstancesProperties(Map<String, List<ComponentInstanceProperty>> componentInstancesProperties) {
+ this.componentInstancesProperties = componentInstancesProperties;
+ }
+
+
+ public Map<String, List<ComponentInstanceAttribute>> getComponentInstancesAttributes() {
+ return componentInstancesAttributes;
+ }
+
+
+ public void setComponentInstancesAttributes(
+ Map<String, List<ComponentInstanceAttribute>> componentInstancesAttributes) {
+ this.componentInstancesAttributes = componentInstancesAttributes;
+ }
+
+
+ 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 List<InputDefinition> getInputs() {
+ return inputs;
+ }
+
+
+ public void setInputs(List<InputDefinition> inputs) {
+ this.inputs = inputs;
+ }
+
+
+ public List<GroupDefinition> getGroups() {
+ return groups;
+ }
+
+
+ public void setGroups(List<GroupDefinition> groups) {
+ this.groups = groups;
+ }
+
+
+ public List<AdditionalInformationDefinition> getAdditionalInformation() {
+ return additionalInformation;
+ }
+
+
+ public void setAdditionalInformation(List<AdditionalInformationDefinition> additionalInformation) {
+ this.additionalInformation = additionalInformation;
+ }
+
+}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiComponentMetadata.java b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiComponentMetadata.java
new file mode 100644
index 0000000000..f0679d31de
--- /dev/null
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiComponentMetadata.java
@@ -0,0 +1,318 @@
+package org.openecomp.sdc.be.ui.model;
+
+import java.util.List;
+import java.util.Map;
+
+import org.openecomp.sdc.be.datatypes.components.ComponentMetadataDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.category.CategoryDefinition;
+
+public abstract class UiComponentMetadata {
+
+ private String uniqueId;
+
+ private String name; // archiveName
+
+ private String version; // archiveVersion
+
+ private Boolean isHighestVersion;
+
+ private Long creationDate;
+
+ private Long lastUpdateDate;
+
+ private String description;
+
+ private String lifecycleState;
+
+ private List<String> tags;
+
+ private String icon;
+
+ private String UUID;
+
+ private String normalizedName;
+
+ private String systemName;
+
+ private String contactId;
+
+ private Map<String, String> allVersions;
+
+ private Boolean isDeleted;
+
+ private String projectCode;
+
+ private String csarUUID;
+
+ private String csarVersion;
+
+ private String importedToscaChecksum;
+
+ private String invariantUUID;
+
+ private ComponentTypeEnum componentType;
+
+ private List<CategoryDefinition> categories;
+
+ private String creatorUserId;
+
+ private String creatorFullName;
+
+ private String lastUpdaterUserId;
+
+ private String lastUpdaterFullName;
+
+
+ public UiComponentMetadata (List<CategoryDefinition> categories, ComponentMetadataDataDefinition metadata) {
+
+ this.uniqueId = metadata.getUniqueId();
+ this.name = metadata.getName(); // archiveName
+ this.version = metadata.getVersion();
+ this.isHighestVersion = metadata.isHighestVersion();
+ this.creationDate = metadata.getCreationDate();
+ this.lastUpdateDate = metadata.getLastUpdateDate();
+ this.description = metadata.getDescription();
+ this.lifecycleState = metadata.getState();
+ this.tags = metadata.getTags();
+ this.icon = metadata.getIcon();
+ this.UUID = metadata.getUUID();
+ this.normalizedName = metadata.getNormalizedName();
+ this.systemName = metadata.getSystemName();
+ this.contactId = metadata.getContactId();
+ this.allVersions = metadata.getAllVersions();
+ this.projectCode = metadata.getProjectCode();
+ this.csarUUID = metadata.getCsarUUID();
+ this.csarVersion = metadata.getCsarVersion();
+ this.importedToscaChecksum = metadata.getImportedToscaChecksum();
+ this.invariantUUID = metadata.getInvariantUUID();
+ this.componentType = metadata.getComponentType();
+ this.categories = categories;
+ this.creatorUserId = metadata.getCreatorUserId();
+ this.creatorFullName = metadata.getCreatorFullName();
+ this.lastUpdaterFullName = metadata.getLastUpdaterFullName();
+ this.lastUpdaterUserId = metadata.getLastUpdaterUserId();
+
+ }
+
+
+
+ public List<CategoryDefinition> getCategories() {
+ return categories;
+ }
+
+ public void setCategories(List<CategoryDefinition> categories) {
+ this.categories = categories;
+ }
+
+
+ public String getUniqueId() {
+ return uniqueId;
+ }
+
+ public void setUniqueId(String uniqueId) {
+ this.uniqueId = uniqueId;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getVersion() {
+ return version;
+ }
+
+ public void setVersion(String version) {
+ this.version = version;
+ }
+
+ public Boolean getIsHighestVersion() {
+ return isHighestVersion;
+ }
+
+ public void setIsHighestVersion(Boolean isHighestVersion) {
+ this.isHighestVersion = isHighestVersion;
+ }
+
+ public Long getCreationDate() {
+ return creationDate;
+ }
+
+ public void setCreationDate(Long creationDate) {
+ this.creationDate = creationDate;
+ }
+
+ public Long getLastUpdateDate() {
+ return lastUpdateDate;
+ }
+
+ public void setLastUpdateDate(Long lastUpdateDate) {
+ this.lastUpdateDate = lastUpdateDate;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public String getLifecycleState() {
+ return lifecycleState;
+ }
+
+ public void setLifecycleState(String state) {
+ this.lifecycleState = state;
+ }
+
+ public List<String> getTags() {
+ return tags;
+ }
+
+ public void setTags(List<String> tags) {
+ this.tags = tags;
+ }
+
+ public String getIcon() {
+ return icon;
+ }
+
+ public void setIcon(String icon) {
+ this.icon = icon;
+ }
+
+ public String getUUID() {
+ return UUID;
+ }
+
+ public void setUUID(String uUID) {
+ UUID = uUID;
+ }
+
+ public String getNormalizedName() {
+ return normalizedName;
+ }
+
+ public void setNormalizedName(String normalizedName) {
+ this.normalizedName = normalizedName;
+ }
+
+ public String getSystemName() {
+ return systemName;
+ }
+
+ public void setSystemName(String systemName) {
+ this.systemName = systemName;
+ }
+
+ public String getContactId() {
+ return contactId;
+ }
+
+ public void setContactId(String contactId) {
+ this.contactId = contactId;
+ }
+
+ public Map<String, String> getAllVersions() {
+ return allVersions;
+ }
+
+ public void setAllVersions(Map<String, String> allVersions) {
+ this.allVersions = allVersions;
+ }
+
+ public Boolean getIsDeleted() {
+ return isDeleted;
+ }
+
+ public void setIsDeleted(Boolean isDeleted) {
+ this.isDeleted = isDeleted;
+ }
+
+ 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 getCsarVersion() {
+ return csarVersion;
+ }
+
+ public void setCsarVersion(String csarVersion) {
+ this.csarVersion = csarVersion;
+ }
+
+ 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;
+ }
+
+ public ComponentTypeEnum getComponentType() {
+ return componentType;
+ }
+
+ public void setComponentType(ComponentTypeEnum componentType) {
+ this.componentType = componentType;
+ }
+
+ 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;
+ }
+
+}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiResourceDataTransfer.java b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiResourceDataTransfer.java
new file mode 100644
index 0000000000..c56daa4fc9
--- /dev/null
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiResourceDataTransfer.java
@@ -0,0 +1,93 @@
+package org.openecomp.sdc.be.ui.model;
+
+import java.util.List;
+import java.util.Map;
+
+import org.openecomp.sdc.be.model.AdditionalInformationDefinition;
+import org.openecomp.sdc.be.model.AttributeDefinition;
+import org.openecomp.sdc.be.model.InterfaceDefinition;
+import org.openecomp.sdc.be.model.PropertyDefinition;
+
+public class UiResourceDataTransfer extends UiComponentDataTransfer{
+
+ private UiResourceMetadata metadata;
+
+ private List<String> derivedFrom;
+
+ private List<String> derivedList;
+
+ private List<PropertyDefinition> properties;
+
+ private List<AttributeDefinition> attributes;
+
+ private Map<String, InterfaceDefinition> interfaces;
+
+ private List<String> defaultCapabilities;
+
+ private List<AdditionalInformationDefinition> additionalInformation;
+
+ public List<AdditionalInformationDefinition> getAdditionalInformation() {
+ return additionalInformation;
+ }
+
+ public void setAdditionalInformation(List<AdditionalInformationDefinition> additionalInformation) {
+ this.additionalInformation = additionalInformation;
+ }
+
+ public UiResourceMetadata getMetadata() {
+ return metadata;
+ }
+
+ public void setMetadata(UiResourceMetadata metadata) {
+ this.metadata = metadata;
+ }
+
+ public List<String> getDerivedFrom() {
+ return derivedFrom;
+ }
+
+ public void setDerivedFrom(List<String> derivedFrom) {
+ this.derivedFrom = derivedFrom;
+ }
+
+ public List<String> getDerivedList() {
+ return derivedList;
+ }
+
+ public void setDerivedList(List<String> derivedList) {
+ this.derivedList = derivedList;
+ }
+
+ public List<PropertyDefinition> getProperties() {
+ return properties;
+ }
+
+ public void setProperties(List<PropertyDefinition> properties) {
+ this.properties = properties;
+ }
+
+ public List<AttributeDefinition> getAttributes() {
+ return attributes;
+ }
+
+ public void setAttributes(List<AttributeDefinition> attributes) {
+ this.attributes = attributes;
+ }
+
+ public Map<String, InterfaceDefinition> getInterfaces() {
+ return interfaces;
+ }
+
+ public void setInterfaces(Map<String, InterfaceDefinition> interfaces) {
+ this.interfaces = interfaces;
+ }
+
+ public List<String> getDefaultCapabilities() {
+ return defaultCapabilities;
+ }
+
+ public void setDefaultCapabilities(List<String> defaultCapabilities) {
+ this.defaultCapabilities = defaultCapabilities;
+ }
+
+}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiResourceMetadata.java b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiResourceMetadata.java
new file mode 100644
index 0000000000..19c7246462
--- /dev/null
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiResourceMetadata.java
@@ -0,0 +1,101 @@
+package org.openecomp.sdc.be.ui.model;
+
+import java.util.List;
+import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.category.CategoryDefinition;
+
+public class UiResourceMetadata extends UiComponentMetadata {
+
+ private String vendorName;
+ private String vendorRelease;
+ private ResourceTypeEnum resourceType = ResourceTypeEnum.VFC;
+ private Boolean isAbstract;
+ private String cost;
+ private String licenseType;
+ private String toscaResourceName;
+ private List<String> derivedFrom;
+
+ public UiResourceMetadata(List<CategoryDefinition> categories, List<String> derivedFrom, ResourceMetadataDataDefinition metadata) {
+ super(categories, metadata);
+ this.vendorName = metadata.getVendorName();
+ this.vendorRelease = metadata.getVendorRelease();
+ this.resourceType = metadata.getResourceType();
+ this.cost = metadata.getCost();
+ this.licenseType = metadata.getLicenseType();
+ this.toscaResourceName = metadata.getToscaResourceName();
+ this.derivedFrom = derivedFrom;
+ }
+
+ 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 ResourceTypeEnum getResourceType() {
+ return resourceType;
+ }
+
+ public void setResourceType(ResourceTypeEnum resourceType) {
+ this.resourceType = resourceType;
+ }
+
+ public Boolean getIsAbstract() {
+ return isAbstract;
+ }
+
+ public void setIsAbstract(Boolean isAbstract) {
+ this.isAbstract = isAbstract;
+ }
+
+ 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 getToscaResourceName() {
+ return toscaResourceName;
+ }
+
+ public void setToscaResourceName(String toscaResourceName) {
+ this.toscaResourceName = toscaResourceName;
+ }
+
+
+
+}
+
+
+
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
new file mode 100644
index 0000000000..73bb772a51
--- /dev/null
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiServiceDataTransfer.java
@@ -0,0 +1,29 @@
+package org.openecomp.sdc.be.ui.model;
+
+import java.util.Map;
+
+import org.openecomp.sdc.be.model.ArtifactDefinition;
+
+public class UiServiceDataTransfer extends UiComponentDataTransfer {
+
+
+ private Map<String, ArtifactDefinition> serviceApiArtifacts;
+
+ private UiServiceMetadata metadata;
+
+ public UiServiceMetadata getMetadata() {
+ return metadata;
+ }
+
+ public void setMetadata(UiServiceMetadata metadata) {
+ this.metadata = metadata;
+ }
+
+ public Map<String, ArtifactDefinition> getServiceApiArtifacts() {
+ return serviceApiArtifacts;
+ }
+
+ public void setServiceApiArtifacts(Map<String, ArtifactDefinition> serviceApiArtifacts) {
+ this.serviceApiArtifacts = serviceApiArtifacts;
+ }
+}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiServiceMetadata.java b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiServiceMetadata.java
new file mode 100644
index 0000000000..b68704eeea
--- /dev/null
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiServiceMetadata.java
@@ -0,0 +1,55 @@
+package org.openecomp.sdc.be.ui.model;
+
+import java.util.List;
+
+import org.openecomp.sdc.be.datatypes.components.ServiceMetadataDataDefinition;
+import org.openecomp.sdc.be.model.category.CategoryDefinition;
+
+public class UiServiceMetadata extends UiComponentMetadata {
+
+ private String distributionStatus;
+ private Boolean ecompGeneratedNaming;
+ private String namingPolicy;
+ private UiServiceMetadata metadata;
+
+
+ public UiServiceMetadata getMetadata() {
+ return metadata;
+ }
+
+ public void setMetadata(UiServiceMetadata metadata) {
+ this.metadata = metadata;
+ }
+
+ public UiServiceMetadata(List<CategoryDefinition> categories, ServiceMetadataDataDefinition metadata) {
+ super(categories, metadata);
+ this.distributionStatus = metadata.getDistributionStatus();
+ this.ecompGeneratedNaming = metadata.isEcompGeneratedNaming();
+ this.namingPolicy = metadata.getNamingPolicy();
+ }
+
+ public String getDistributionStatus() {
+ return distributionStatus;
+ }
+
+ public void setDistributionStatus(String distributionStatus) {
+ this.distributionStatus = distributionStatus;
+ }
+
+ public Boolean getEcompGeneratedNaming() {
+ return ecompGeneratedNaming;
+ }
+
+ public void setEcompGeneratedNaming(Boolean ecompGeneratedNaming) {
+ this.ecompGeneratedNaming = ecompGeneratedNaming;
+ }
+
+ public String getNamingPolicy() {
+ return namingPolicy;
+ }
+
+ public void setNamingPolicy(String namingPolicy) {
+ this.namingPolicy = namingPolicy;
+ }
+
+}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/unittests/utils/FactoryUtils.java b/catalog-model/src/main/java/org/openecomp/sdc/be/unittests/utils/FactoryUtils.java
index f95a89db62..1d692fd638 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/unittests/utils/FactoryUtils.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/unittests/utils/FactoryUtils.java
@@ -25,9 +25,11 @@ import java.util.List;
import java.util.UUID;
import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
+import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
+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;
@@ -39,6 +41,7 @@ import org.openecomp.sdc.be.resources.data.CapabilityInstData;
import org.openecomp.sdc.be.resources.data.PropertyData;
import org.openecomp.sdc.be.resources.data.PropertyValueData;
import org.openecomp.sdc.be.resources.data.RequirementData;
+import org.openecomp.sdc.be.resources.data.ResourceMetadataData;
public final class FactoryUtils {
private FactoryUtils() {
@@ -61,6 +64,15 @@ public final class FactoryUtils {
resource.setUniqueId(uniqueId);
return resource;
}
+
+ public static ResourceMetadataData createResourceByType(String resourceType) {
+ ResourceMetadataData resource = new ResourceMetadataData();
+ String uniqueId = UUID.randomUUID().toString();
+ resource.getMetadataDataDefinition().setHighestVersion(true);
+ resource.getMetadataDataDefinition().setUniqueId(uniqueId);
+ ((ResourceMetadataDataDefinition)resource.getMetadataDataDefinition()).setResourceType(ResourceTypeEnum.getTypeIgnoreCase(resourceType));
+ return resource;
+ }
public static void addComponentInstanceToVF(Resource vf, ComponentInstance resourceInstance) {
List<ComponentInstance> componentsInstances = vf.getComponentInstances() != null ? vf.getComponentInstances()
diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/ModelTestBase.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/ModelTestBase.java
index f18aa61b74..c8917763a8 100644
--- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/ModelTestBase.java
+++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/ModelTestBase.java
@@ -33,8 +33,7 @@ public class ModelTestBase {
public static void init() {
if (ConfigurationManager.getConfigurationManager() == null) {
String appConfigDir = "src/test/resources/config";
- ConfigurationSource configurationSource = new FSConfigurationSource(
- ExternalConfiguration.getChangeListener(), appConfigDir);
+ ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir);
configurationManager = new ConfigurationManager(configurationSource);
Configuration configuration = new Configuration();
diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/JsonObjectTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/JsonObjectTest.java
index dd102e7ed5..b3476529e8 100644
--- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/JsonObjectTest.java
+++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/JsonObjectTest.java
@@ -39,10 +39,8 @@ public class JsonObjectTest {
private ObjectMapper mapper;
UploadResourceInfo inputObjectRef;
- private final String INPUT_RESOURCE_STRING = "{ \"payloadData\" : \"My Test Object\", \"payloadName\" : \"TestName\", "
- + " \"description\":\"my_description\",\"tags\":[\"tag1\"], "
- + "\"artifactList\" : [ { \"artifactName\" : \"myArtifact0\", \"artifactPath\" : \"scripts/\", \"artifactType\" : \"PUPPET\", "
- + " \"artifactDescription\" : \"This is Description\", \"artifactData\" : null }, "
+ private final String INPUT_RESOURCE_STRING = "{ \"payloadData\" : \"My Test Object\", \"payloadName\" : \"TestName\", " + " \"description\":\"my_description\",\"tags\":[\"tag1\"], "
+ + "\"artifactList\" : [ { \"artifactName\" : \"myArtifact0\", \"artifactPath\" : \"scripts/\", \"artifactType\" : \"PUPPET\", " + " \"artifactDescription\" : \"This is Description\", \"artifactData\" : null }, "
+ "{ \"artifactName\" : \"myArtifact1\", \"artifactPath\" : \"scripts/\", \"artifactType\" : \"PUPPET\", \"artifactDescription\" : \"This is Description\", "
+ " \"artifactData\" : null } ], \"contactId\" : null, \"name\" : null, \"resourceIconPath\" : null, \"vendorName\" : null, \"vendorRelease\" : null , \"resourceType\" : \"VFC\" }";
@@ -51,14 +49,12 @@ public class JsonObjectTest {
mapper = new ObjectMapper();
ArrayList<UploadArtifactInfo> artifactList = new ArrayList<UploadArtifactInfo>();
for (int i = 0; i < 2; i++) {
- UploadArtifactInfo artifactInfo = new UploadArtifactInfo("myArtifact" + i, "scripts/",
- ArtifactTypeEnum.PUPPET, "This is Description");
+ UploadArtifactInfo artifactInfo = new UploadArtifactInfo("myArtifact" + i, "scripts/", ArtifactTypeEnum.PUPPET, "This is Description");
artifactList.add(artifactInfo);
}
ArrayList<String> tags = new ArrayList<>();
tags.add("tag1");
- inputObjectRef = new UploadResourceInfo("My Test Object", "TestName", "my_description", null, tags,
- artifactList);
+ inputObjectRef = new UploadResourceInfo("My Test Object", "TestName", "my_description", null, tags, artifactList);
}
diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/AdditionalInformationOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/AdditionalInformationOperationTest.java
index 3e871f1fa0..eea11b6625 100644
--- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/AdditionalInformationOperationTest.java
+++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/AdditionalInformationOperationTest.java
@@ -21,46 +21,26 @@
package org.openecomp.sdc.be.model.operations.impl;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
-import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
-import java.util.Map;
-import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
-import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.model.ArtifactDefinition;
-import org.openecomp.sdc.be.model.InterfaceDefinition;
import org.openecomp.sdc.be.model.LifecycleStateEnum;
import org.openecomp.sdc.be.model.ModelTestBase;
-import org.openecomp.sdc.be.model.Operation;
-import org.openecomp.sdc.be.model.Point;
-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.operations.api.IAdditionalInformationOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.model.operations.impl.ResourceOperation;
-import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
import org.openecomp.sdc.be.model.operations.impl.util.OperationTestsUtil;
-import org.openecomp.sdc.be.model.tosca.ToscaType;
-import org.openecomp.sdc.be.model.tosca.constraints.GreaterThanConstraint;
-import org.openecomp.sdc.be.model.tosca.constraints.InRangeConstraint;
-import org.openecomp.sdc.be.model.tosca.constraints.LessOrEqualConstraint;
import org.openecomp.sdc.be.resources.data.UserData;
-import org.openecomp.sdc.exception.DeleteReferencedObjectException;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@@ -76,9 +56,7 @@ import fj.data.Either;
@ContextConfiguration("classpath:application-context-test.xml")
public class AdditionalInformationOperationTest extends ModelTestBase {
- private Gson prettyGson = new GsonBuilder().setPrettyPrinting().create();
-
- private static String USER_ID = "muuserid";
+ private static String USER_ID = "muUserId";
private static String CATEGORY_NAME = "category/mycategory";
@javax.annotation.Resource(name = "titan-generic-dao")
@@ -136,8 +114,7 @@ public class AdditionalInformationOperationTest extends ModelTestBase {
int before = getNumberOfVerticesOnGraph();
- Resource newResource = createResource(USER_ID, CATEGORY_NAME, "testCreateAndDeleteResource", "0.1", null, false,
- true);
+ Resource newResource = createResource(USER_ID, CATEGORY_NAME, "testCreateAndDeleteResource", "0.1", null, false, true);
String resourceId = newResource.getUniqueId();
Either<Resource, StorageOperationStatus> deleteResource = resourceOperation.deleteResource(resourceId);
@@ -148,8 +125,7 @@ public class AdditionalInformationOperationTest extends ModelTestBase {
assertEquals("check number of vertices not changed", before, after);
}
- private Resource buildResourceMetadata(String userId, String category, String resourceName,
- String resourceVersion) {
+ private Resource buildResourceMetadata(String userId, String category, String resourceName, String resourceVersion) {
Resource resource = new Resource();
resource.setName(resourceName);
@@ -189,8 +165,7 @@ public class AdditionalInformationOperationTest extends ModelTestBase {
OperationTestsUtil.deleteAndCreateResourceCategory(names[0], names[1], titanDao);
}
- public Resource createResource(String userId, String category, String resourceName, String resourceVersion,
- String parentResourceName, boolean isAbstract, boolean isHighestVersion) {
+ public Resource createResource(String userId, String category, String resourceName, String resourceVersion, String parentResourceName, boolean isAbstract, boolean isHighestVersion) {
List<String> derivedFrom = new ArrayList<String>();
if (parentResourceName != null) {
@@ -206,8 +181,7 @@ public class AdditionalInformationOperationTest extends ModelTestBase {
assertTrue(result.isLeft());
Resource resultResource = result.left().value();
- assertEquals("check resource state", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT,
- resultResource.getLifecycleState());
+ assertEquals("check resource state", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, resultResource.getLifecycleState());
return resultResource;
diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ArtifactOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ArtifactOperationTest.java
index 0143e50dc7..875c34b780 100644
--- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ArtifactOperationTest.java
+++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ArtifactOperationTest.java
@@ -21,9 +21,9 @@
package org.openecomp.sdc.be.model.operations.impl;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertFalse;
import java.util.ArrayList;
import java.util.HashMap;
@@ -48,6 +48,16 @@ import org.openecomp.sdc.be.model.Service;
import org.openecomp.sdc.be.model.category.CategoryDefinition;
import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.model.operations.impl.ArtifactOperation;
+import org.openecomp.sdc.be.model.operations.impl.CapabilityOperation;
+import org.openecomp.sdc.be.model.operations.impl.CapabilityTypeOperation;
+import org.openecomp.sdc.be.model.operations.impl.ComponentInstanceOperation;
+import org.openecomp.sdc.be.model.operations.impl.LifecycleOperation;
+import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
+import org.openecomp.sdc.be.model.operations.impl.RequirementOperation;
+import org.openecomp.sdc.be.model.operations.impl.ResourceOperation;
+import org.openecomp.sdc.be.model.operations.impl.ServiceOperation;
+import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
import org.openecomp.sdc.be.model.operations.impl.util.OperationTestsUtil;
import org.openecomp.sdc.be.resources.data.ArtifactData;
import org.openecomp.sdc.be.resources.data.HeatParameterData;
@@ -106,7 +116,7 @@ public class ArtifactOperationTest extends ModelTestBase {
private static String RESOURCE_ID = "resourceId";
private static String RESOURCE_ID_2 = "resourceId2";
- private static String USER_ID = "muserid";
+ private static String USER_ID = "muUserId";
private static String CATEGORY_NAME = "category/mycategory";
@BeforeClass
@@ -121,7 +131,7 @@ public class ArtifactOperationTest extends ModelTestBase {
deleteAndCreateUser(USER_ID, "first_" + USER_ID, "last_" + USER_ID, null);
}
-// @Test
+ @Test
public void testAddArtifactToServiceVersionAndUUIDNotNull() {
CategoryDefinition category = new CategoryDefinition();
category.setName(CATEGORY_NAME);
@@ -135,11 +145,9 @@ public class ArtifactOperationTest extends ModelTestBase {
ArtifactDefinition artifactInfo = addArtifactToService(userId, serviceId, "install_apache");
- assertEquals("add informational artifact version : " + artifactInfo.getArtifactVersion(), "1",
- artifactInfo.getArtifactVersion());
+ assertEquals("add informational artifact version : " + artifactInfo.getArtifactVersion(), "1", artifactInfo.getArtifactVersion());
- assertNotNull("add informational artifact version : " + artifactInfo.getArtifactUUID(),
- artifactInfo.getArtifactUUID());
+ assertNotNull("add informational artifact version : " + artifactInfo.getArtifactUUID(), artifactInfo.getArtifactUUID());
Either<Service, StorageOperationStatus> service = serviceOperation.getService(serviceId);
assertTrue(service.isLeft());
@@ -159,8 +167,7 @@ public class ArtifactOperationTest extends ModelTestBase {
Either<Service, StorageOperationStatus> serviceDelete = serviceOperation.deleteService(serviceId);
- Either<List<ArtifactData>, TitanOperationStatus> byCriteria = titanDao.getByCriteria(NodeTypeEnum.ArtifactRef,
- null, ArtifactData.class);
+ Either<List<ArtifactData>, TitanOperationStatus> byCriteria = titanDao.getByCriteria(NodeTypeEnum.ArtifactRef, null, ArtifactData.class);
assertTrue(byCriteria.isRight());
assertEquals(TitanOperationStatus.NOT_FOUND, byCriteria.right().value());
@@ -168,7 +175,7 @@ public class ArtifactOperationTest extends ModelTestBase {
}
-// @Test
+ @Test
public void testUpdateArtifactToServiceVersionNotChanged() {
CategoryDefinition category = new CategoryDefinition();
category.setName(CATEGORY_NAME);
@@ -187,8 +194,7 @@ public class ArtifactOperationTest extends ModelTestBase {
artifactInfo.setDescription("jghlsk new desfnjdh");
- Either<ArtifactDefinition, StorageOperationStatus> artifact = artifactOperation.updateArifactOnResource(
- artifactInfo, serviceId, artifactInfo.getUniqueId(), NodeTypeEnum.Service, false);
+ Either<ArtifactDefinition, StorageOperationStatus> artifact = artifactOperation.updateArifactOnResource(artifactInfo, serviceId, artifactInfo.getUniqueId(), NodeTypeEnum.Service, false);
String newVersion = artifact.left().value().getArtifactVersion();
String newArtUuid = artifactInfo.getArtifactUUID();
assertEquals("add informational artifact version : " + newVersion, newVersion, version);
@@ -212,8 +218,7 @@ public class ArtifactOperationTest extends ModelTestBase {
Either<Service, StorageOperationStatus> serviceDelete = serviceOperation.deleteService(serviceId);
- Either<List<ArtifactData>, TitanOperationStatus> byCriteria = titanDao.getByCriteria(NodeTypeEnum.ArtifactRef,
- null, ArtifactData.class);
+ Either<List<ArtifactData>, TitanOperationStatus> byCriteria = titanDao.getByCriteria(NodeTypeEnum.ArtifactRef, null, ArtifactData.class);
assertTrue(byCriteria.isRight());
assertEquals(TitanOperationStatus.NOT_FOUND, byCriteria.right().value());
@@ -226,26 +231,22 @@ public class ArtifactOperationTest extends ModelTestBase {
ArtifactDefinition artifactWithHeat = createResourceWithHeat();
- List<HeatParameterDefinition> heatParameters = artifactWithHeat.getHeatParameters();
+ List<HeatParameterDefinition> heatParameters = artifactWithHeat.getListHeatParameters();
assertNotNull(heatParameters);
assertTrue(heatParameters.size() == 1);
HeatParameterDefinition parameter = heatParameters.get(0);
HeatParameterData parameterData = new HeatParameterData(parameter);
- Either<HeatParameterData, TitanOperationStatus> parameterNode = titanDao.getNode(parameterData.getUniqueIdKey(),
- parameterData.getUniqueId(), HeatParameterData.class);
+ Either<HeatParameterData, TitanOperationStatus> parameterNode = titanDao.getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(), HeatParameterData.class);
assertTrue(parameterNode.isLeft());
- Either<ArtifactDefinition, StorageOperationStatus> removeArifact = artifactOperation.removeArifactFromResource(
- RESOURCE_ID, artifactWithHeat.getUniqueId(), NodeTypeEnum.Resource, true, false);
+ Either<ArtifactDefinition, StorageOperationStatus> removeArifact = artifactOperation.removeArifactFromResource(RESOURCE_ID, artifactWithHeat.getUniqueId(), NodeTypeEnum.Resource, true, false);
assertTrue(removeArifact.isLeft());
ArtifactData artifactData = new ArtifactData(artifactWithHeat);
- Either<ArtifactData, TitanOperationStatus> artifactAfterDelete = titanDao.getNode(artifactData.getUniqueIdKey(),
- artifactData.getUniqueId(), ArtifactData.class);
+ Either<ArtifactData, TitanOperationStatus> artifactAfterDelete = titanDao.getNode(artifactData.getUniqueIdKey(), artifactData.getUniqueId(), ArtifactData.class);
assertTrue(artifactAfterDelete.isRight());
- Either<HeatParameterData, TitanOperationStatus> parameterNodeAfterDelete = titanDao
- .getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(), HeatParameterData.class);
+ Either<HeatParameterData, TitanOperationStatus> parameterNodeAfterDelete = titanDao.getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(), HeatParameterData.class);
assertTrue(parameterNodeAfterDelete.isRight());
titanDao.deleteNode(new UniqueIdData(NodeTypeEnum.Resource, RESOURCE_ID), ResourceMetadataData.class);
@@ -256,13 +257,12 @@ public class ArtifactOperationTest extends ModelTestBase {
ArtifactDefinition artifactWithHeat = createResourceWithHeat();
- List<HeatParameterDefinition> heatParameters = artifactWithHeat.getHeatParameters();
+ List<HeatParameterDefinition> heatParameters = artifactWithHeat.getListHeatParameters();
assertNotNull(heatParameters);
assertTrue(heatParameters.size() == 1);
HeatParameterDefinition parameter = heatParameters.get(0);
HeatParameterData parameterData = new HeatParameterData(parameter);
- Either<HeatParameterData, TitanOperationStatus> parameterNode = titanDao.getNode(parameterData.getUniqueIdKey(),
- parameterData.getUniqueId(), HeatParameterData.class);
+ Either<HeatParameterData, TitanOperationStatus> parameterNode = titanDao.getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(), HeatParameterData.class);
assertTrue(parameterNode.isLeft());
// update to artifact without params
@@ -272,24 +272,19 @@ public class ArtifactOperationTest extends ModelTestBase {
artifactNoParams.setArtifactVersion("2");
artifactNoParams.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT);
- Either<ArtifactDefinition, StorageOperationStatus> updateArifact = artifactOperation.updateArifactOnResource(
- artifactNoParams, RESOURCE_ID, artifactWithHeat.getUniqueId(), NodeTypeEnum.Resource, false);
+ Either<ArtifactDefinition, StorageOperationStatus> updateArifact = artifactOperation.updateArifactOnResource(artifactNoParams, RESOURCE_ID, artifactWithHeat.getUniqueId(), NodeTypeEnum.Resource, false);
assertTrue(updateArifact.isLeft());
ArtifactData artifactData = new ArtifactData(artifactWithHeat);
- Either<ArtifactData, TitanOperationStatus> artifactAfterUpdate = titanDao.getNode(artifactData.getUniqueIdKey(),
- artifactData.getUniqueId(), ArtifactData.class);
+ Either<ArtifactData, TitanOperationStatus> artifactAfterUpdate = titanDao.getNode(artifactData.getUniqueIdKey(), artifactData.getUniqueId(), ArtifactData.class);
assertTrue(artifactAfterUpdate.isLeft());
ArtifactData artifactAfterUpdateValue = artifactAfterUpdate.left().value();
- assertTrue(artifactNoParams.getArtifactVersion()
- .equals(artifactAfterUpdateValue.getArtifactDataDefinition().getArtifactVersion()));
+ assertTrue(artifactNoParams.getArtifactVersion().equals(artifactAfterUpdateValue.getArtifactDataDefinition().getArtifactVersion()));
- Either<HeatParameterData, TitanOperationStatus> parameterNodeAfterDelete = titanDao
- .getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(), HeatParameterData.class);
+ Either<HeatParameterData, TitanOperationStatus> parameterNodeAfterDelete = titanDao.getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(), HeatParameterData.class);
assertTrue(parameterNodeAfterDelete.isRight());
- artifactOperation.removeArifactFromResource(RESOURCE_ID, artifactWithHeat.getUniqueId(), NodeTypeEnum.Resource,
- true, false);
+ artifactOperation.removeArifactFromResource(RESOURCE_ID, artifactWithHeat.getUniqueId(), NodeTypeEnum.Resource, true, false);
titanDao.deleteNode(new UniqueIdData(NodeTypeEnum.Resource, RESOURCE_ID), ResourceMetadataData.class);
titanDao.deleteNode(new UniqueIdData(NodeTypeEnum.Resource, RESOURCE_ID_2), ResourceMetadataData.class);
}
@@ -299,13 +294,12 @@ public class ArtifactOperationTest extends ModelTestBase {
ArtifactDefinition artifactWithHeat = createResourceWithHeat();
- List<HeatParameterDefinition> heatParameters = artifactWithHeat.getHeatParameters();
+ List<HeatParameterDefinition> heatParameters = artifactWithHeat.getListHeatParameters();
assertNotNull(heatParameters);
assertTrue(heatParameters.size() == 1);
HeatParameterDefinition parameter = heatParameters.get(0);
HeatParameterData parameterData = new HeatParameterData(parameter);
- Either<HeatParameterData, TitanOperationStatus> parameterNode = titanDao.getNode(parameterData.getUniqueIdKey(),
- parameterData.getUniqueId(), HeatParameterData.class);
+ Either<HeatParameterData, TitanOperationStatus> parameterNode = titanDao.getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(), HeatParameterData.class);
assertTrue(parameterNode.isLeft());
// update to artifact without params
@@ -313,26 +307,20 @@ public class ArtifactOperationTest extends ModelTestBase {
artifactWithHeat.setArtifactChecksum(null);
artifactWithHeat.setPayloadData(null);
- Either<ArtifactDefinition, StorageOperationStatus> updateArifact = artifactOperation.updateArifactOnResource(
- artifactWithHeat, RESOURCE_ID, artifactWithHeat.getUniqueId(), NodeTypeEnum.Resource, false);
+ Either<ArtifactDefinition, StorageOperationStatus> updateArifact = artifactOperation.updateArifactOnResource(artifactWithHeat, RESOURCE_ID, artifactWithHeat.getUniqueId(), NodeTypeEnum.Resource, false);
assertTrue(updateArifact.isLeft());
ArtifactData artifactData = new ArtifactData(artifactWithHeat);
- Either<ArtifactData, TitanOperationStatus> artifactAfterUpdate = titanDao.getNode(artifactData.getUniqueIdKey(),
- artifactData.getUniqueId(), ArtifactData.class);
+ Either<ArtifactData, TitanOperationStatus> artifactAfterUpdate = titanDao.getNode(artifactData.getUniqueIdKey(), artifactData.getUniqueId(), ArtifactData.class);
assertTrue(artifactAfterUpdate.isLeft());
ArtifactData artifactAfterUpdateValue = artifactAfterUpdate.left().value();
- assertTrue(artifactWithHeat.getArtifactVersion()
- .equals(artifactAfterUpdateValue.getArtifactDataDefinition().getArtifactVersion()));
+ assertTrue(artifactWithHeat.getArtifactVersion().equals(artifactAfterUpdateValue.getArtifactDataDefinition().getArtifactVersion()));
- Either<HeatParameterData, TitanOperationStatus> parameterNodeAfterDelete = titanDao
- .getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(), HeatParameterData.class);
+ Either<HeatParameterData, TitanOperationStatus> parameterNodeAfterDelete = titanDao.getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(), HeatParameterData.class);
assertTrue(parameterNodeAfterDelete.isLeft());
- Either<ArtifactDefinition, StorageOperationStatus> removeArifact = artifactOperation.removeArifactFromResource(
- RESOURCE_ID_2, (String) artifactAfterUpdateValue.getUniqueId(), NodeTypeEnum.Resource, true, false);
- removeArifact = artifactOperation.removeArifactFromResource(RESOURCE_ID, artifactWithHeat.getUniqueId(),
- NodeTypeEnum.Resource, true, false);
+ Either<ArtifactDefinition, StorageOperationStatus> removeArifact = artifactOperation.removeArifactFromResource(RESOURCE_ID_2, (String) artifactAfterUpdateValue.getUniqueId(), NodeTypeEnum.Resource, true, false);
+ removeArifact = artifactOperation.removeArifactFromResource(RESOURCE_ID, artifactWithHeat.getUniqueId(), NodeTypeEnum.Resource, true, false);
titanDao.deleteNode(new UniqueIdData(NodeTypeEnum.Resource, RESOURCE_ID), ResourceMetadataData.class);
titanDao.deleteNode(new UniqueIdData(NodeTypeEnum.Resource, RESOURCE_ID_2), ResourceMetadataData.class);
@@ -345,17 +333,15 @@ public class ArtifactOperationTest extends ModelTestBase {
ResourceMetadataData resource2 = createResource(RESOURCE_ID_2);
Map<String, Object> props = new HashMap<String, Object>();
props.put(GraphEdgePropertiesDictionary.NAME.getProperty(), ArtifactGroupTypeEnum.DEPLOYMENT.name());
- Either<GraphRelation, TitanOperationStatus> createRelation = titanDao.createRelation(resource2,
- new ArtifactData(artifactWithHeat), GraphEdgeLabels.ARTIFACT_REF, props);
+ Either<GraphRelation, TitanOperationStatus> createRelation = titanDao.createRelation(resource2, new ArtifactData(artifactWithHeat), GraphEdgeLabels.ARTIFACT_REF, props);
assertTrue(createRelation.isLeft());
- List<HeatParameterDefinition> heatParameters = artifactWithHeat.getHeatParameters();
+ List<HeatParameterDefinition> heatParameters = artifactWithHeat.getListHeatParameters();
assertNotNull(heatParameters);
assertTrue(heatParameters.size() == 1);
HeatParameterDefinition parameter = heatParameters.get(0);
HeatParameterData parameterData = new HeatParameterData(parameter);
- Either<HeatParameterData, TitanOperationStatus> parameterNode = titanDao.getNode(parameterData.getUniqueIdKey(),
- parameterData.getUniqueId(), HeatParameterData.class);
+ Either<HeatParameterData, TitanOperationStatus> parameterNode = titanDao.getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(), HeatParameterData.class);
assertTrue(parameterNode.isLeft());
ArtifactDefinition atifactToUpdate = new ArtifactDefinition(artifactWithHeat);
@@ -369,74 +355,59 @@ public class ArtifactOperationTest extends ModelTestBase {
List<HeatParameterDefinition> heatParametersUpdated = new ArrayList<HeatParameterDefinition>();
heatParamUpdate.setCurrentValue("55");
heatParametersUpdated.add(heatParamUpdate);
- atifactToUpdate.setHeatParameters(heatParametersUpdated);
+ atifactToUpdate.setListHeatParameters(heatParametersUpdated);
- Either<ArtifactDefinition, StorageOperationStatus> updateArifact = artifactOperation.updateArifactOnResource(
- atifactToUpdate, RESOURCE_ID_2, atifactToUpdate.getUniqueId(), NodeTypeEnum.Resource, false);
+ Either<ArtifactDefinition, StorageOperationStatus> updateArifact = artifactOperation.updateArifactOnResource(atifactToUpdate, RESOURCE_ID_2, atifactToUpdate.getUniqueId(), NodeTypeEnum.Resource, false);
assertTrue(updateArifact.isLeft());
// verify old artifact and parameter still exist
ArtifactData artifactData = new ArtifactData(artifactWithHeat);
- Either<ArtifactData, TitanOperationStatus> origArtifact = titanDao.getNode(artifactData.getUniqueIdKey(),
- artifactData.getUniqueId(), ArtifactData.class);
+ Either<ArtifactData, TitanOperationStatus> origArtifact = titanDao.getNode(artifactData.getUniqueIdKey(), artifactData.getUniqueId(), ArtifactData.class);
assertTrue(origArtifact.isLeft());
ArtifactData origArtifactData = origArtifact.left().value();
- assertTrue(artifactWithHeat.getArtifactVersion()
- .equals(origArtifactData.getArtifactDataDefinition().getArtifactVersion()));
+ assertTrue(artifactWithHeat.getArtifactVersion().equals(origArtifactData.getArtifactDataDefinition().getArtifactVersion()));
- Either<HeatParameterData, TitanOperationStatus> parameterNodeAfterDelete = titanDao
- .getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(), HeatParameterData.class);
+ Either<HeatParameterData, TitanOperationStatus> parameterNodeAfterDelete = titanDao.getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(), HeatParameterData.class);
assertTrue(parameterNodeAfterDelete.isLeft());
// verify new artifact and new parameter
ArtifactDefinition artifactDefinitionUpdated = updateArifact.left().value();
ArtifactData artifactDataUpdated = new ArtifactData(artifactDefinitionUpdated);
- Either<ArtifactData, TitanOperationStatus> updatedArtifact = titanDao
- .getNode(artifactDataUpdated.getUniqueIdKey(), artifactDataUpdated.getUniqueId(), ArtifactData.class);
+ Either<ArtifactData, TitanOperationStatus> updatedArtifact = titanDao.getNode(artifactDataUpdated.getUniqueIdKey(), artifactDataUpdated.getUniqueId(), ArtifactData.class);
assertTrue(updatedArtifact.isLeft());
ArtifactData updatedArtifactData = updatedArtifact.left().value();
- assertTrue(atifactToUpdate.getArtifactVersion()
- .equals(updatedArtifactData.getArtifactDataDefinition().getArtifactVersion()));
- assertFalse(
- ((String) updatedArtifactData.getUniqueId()).equalsIgnoreCase((String) origArtifactData.getUniqueId()));
+ assertTrue(atifactToUpdate.getArtifactVersion().equals(updatedArtifactData.getArtifactDataDefinition().getArtifactVersion()));
+ assertFalse(((String) updatedArtifactData.getUniqueId()).equalsIgnoreCase((String) origArtifactData.getUniqueId()));
- List<HeatParameterDefinition> heatParametersAfterUpdate = artifactDefinitionUpdated.getHeatParameters();
+ List<HeatParameterDefinition> heatParametersAfterUpdate = artifactDefinitionUpdated.getListHeatParameters();
assertNotNull(heatParametersAfterUpdate);
assertTrue(heatParametersAfterUpdate.size() == 1);
HeatParameterDefinition UpdatedHeatParameter = heatParametersAfterUpdate.get(0);
assertFalse(UpdatedHeatParameter.getUniqueId().equalsIgnoreCase((String) parameterData.getUniqueId()));
- Either<HeatParameterData, TitanOperationStatus> parameterNodeAfterUpdate = titanDao.getNode(
- new HeatParameterData(UpdatedHeatParameter).getUniqueIdKey(), UpdatedHeatParameter.getUniqueId(),
- HeatParameterData.class);
+ Either<HeatParameterData, TitanOperationStatus> parameterNodeAfterUpdate = titanDao.getNode(new HeatParameterData(UpdatedHeatParameter).getUniqueIdKey(), UpdatedHeatParameter.getUniqueId(), HeatParameterData.class);
assertTrue(parameterNodeAfterUpdate.isLeft());
// delete new artifact
- Either<ArtifactDefinition, StorageOperationStatus> removeArifact = artifactOperation.removeArifactFromResource(
- RESOURCE_ID_2, artifactDefinitionUpdated.getUniqueId(), NodeTypeEnum.Resource, true, false);
+ Either<ArtifactDefinition, StorageOperationStatus> removeArifact = artifactOperation.removeArifactFromResource(RESOURCE_ID_2, artifactDefinitionUpdated.getUniqueId(), NodeTypeEnum.Resource, true, false);
assertTrue(removeArifact.isLeft());
// verify old artifact and parameter still exist
origArtifact = titanDao.getNode(artifactData.getUniqueIdKey(), artifactData.getUniqueId(), ArtifactData.class);
assertTrue(origArtifact.isLeft());
origArtifactData = origArtifact.left().value();
- assertTrue(artifactWithHeat.getArtifactVersion()
- .equals(origArtifactData.getArtifactDataDefinition().getArtifactVersion()));
+ assertTrue(artifactWithHeat.getArtifactVersion().equals(origArtifactData.getArtifactDataDefinition().getArtifactVersion()));
- parameterNodeAfterDelete = titanDao.getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(),
- HeatParameterData.class);
+ parameterNodeAfterDelete = titanDao.getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(), HeatParameterData.class);
assertTrue(parameterNodeAfterDelete.isLeft());
// verify new artifact is deleted
- Either<ArtifactData, TitanOperationStatus> artifactAfterDelete = titanDao
- .getNode(artifactDataUpdated.getUniqueIdKey(), artifactDataUpdated.getUniqueId(), ArtifactData.class);
+ Either<ArtifactData, TitanOperationStatus> artifactAfterDelete = titanDao.getNode(artifactDataUpdated.getUniqueIdKey(), artifactDataUpdated.getUniqueId(), ArtifactData.class);
assertTrue(artifactAfterDelete.isRight());
- parameterNodeAfterDelete = titanDao.getNode(new HeatParameterData(UpdatedHeatParameter).getUniqueIdKey(),
- new HeatParameterData(UpdatedHeatParameter).getUniqueId(), HeatParameterData.class);
+ parameterNodeAfterDelete = titanDao.getNode(new HeatParameterData(UpdatedHeatParameter).getUniqueIdKey(), new HeatParameterData(UpdatedHeatParameter).getUniqueId(), HeatParameterData.class);
assertTrue(parameterNodeAfterDelete.isRight());
- artifactOperation.removeArifactFromResource(RESOURCE_ID, artifactWithHeat.getUniqueId(), NodeTypeEnum.Resource,
- true, false);
+ artifactOperation.removeArifactFromResource(RESOURCE_ID, artifactWithHeat.getUniqueId(), NodeTypeEnum.Resource, true, false);
titanDao.deleteNode(new UniqueIdData(NodeTypeEnum.Resource, RESOURCE_ID), ResourceMetadataData.class);
titanDao.deleteNode(new UniqueIdData(NodeTypeEnum.Resource, RESOURCE_ID_2), ResourceMetadataData.class);
}
@@ -455,10 +426,9 @@ public class ArtifactOperationTest extends ModelTestBase {
heatParam.setName("myParam");
heatParam.setType("number");
heatParams.add(heatParam);
- artifactDefinition.setHeatParameters(heatParams);
+ artifactDefinition.setListHeatParameters(heatParams);
- Either<ArtifactDefinition, StorageOperationStatus> artifact = artifactOperation
- .addArifactToComponent(artifactDefinition, RESOURCE_ID, NodeTypeEnum.Resource, true, false);
+ Either<ArtifactDefinition, StorageOperationStatus> artifact = artifactOperation.addArifactToComponent(artifactDefinition, RESOURCE_ID, NodeTypeEnum.Resource, true, false);
assertTrue(artifact.isLeft());
ArtifactDefinition artifactWithHeat = artifact.left().value();
return artifactWithHeat;
@@ -467,8 +437,7 @@ public class ArtifactOperationTest extends ModelTestBase {
private ArtifactDefinition addArtifactToService(String userId, String serviceId, String artifactName) {
ArtifactDefinition artifactInfo = createArtifactDefinition(userId, serviceId, artifactName);
- Either<ArtifactDefinition, StorageOperationStatus> artifact = artifactOperation
- .addArifactToComponent(artifactInfo, serviceId, NodeTypeEnum.Service, true, true);
+ Either<ArtifactDefinition, StorageOperationStatus> artifact = artifactOperation.addArifactToComponent(artifactInfo, serviceId, NodeTypeEnum.Service, true, true);
assertTrue(artifact.isLeft());
return artifact.left().value();
}
@@ -494,8 +463,7 @@ public class ArtifactOperationTest extends ModelTestBase {
return artifactInfo;
}
- public Service createService(String userId, CategoryDefinition category, String serviceName, String serviceVersion,
- boolean isHighestVersion) {
+ public Service createService(String userId, CategoryDefinition category, String serviceName, String serviceVersion, boolean isHighestVersion) {
Service service = buildServiceMetadata(userId, category, serviceName, serviceVersion);
@@ -510,14 +478,12 @@ public class ArtifactOperationTest extends ModelTestBase {
// assertEquals("check resource unique id",
// UniqueIdBuilder.buildServiceUniqueId(serviceName, serviceVersion),
// resultService.getUniqueId());
- assertEquals("check resource state", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT,
- resultService.getLifecycleState());
+ assertEquals("check resource state", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, resultService.getLifecycleState());
return resultService;
}
- private Service buildServiceMetadata(String userId, CategoryDefinition category, String serviceName,
- String serviceVersion) {
+ private Service buildServiceMetadata(String userId, CategoryDefinition category, String serviceName, String serviceVersion) {
Service service = new Service();
service.setName(serviceName);
@@ -541,6 +507,13 @@ public class ArtifactOperationTest extends ModelTestBase {
String[] names = category.split("/");
OperationTestsUtil.deleteAndCreateServiceCategory(category, titanDao);
OperationTestsUtil.deleteAndCreateResourceCategory(names[0], names[1], titanDao);
+
+ /*
+ * CategoryData categoryData = new CategoryData(); categoryData.setName(category);
+ *
+ * titanDao.deleteNode(categoryData, CategoryData.class); Either<CategoryData, TitanOperationStatus> createNode = titanDao.createNode(categoryData, CategoryData.class); System.out.println("after creating caetgory " + createNode);
+ */
+
}
private UserData deleteAndCreateUser(String userId, String firstName, String lastName, String role) {
@@ -565,8 +538,7 @@ public class ArtifactOperationTest extends ModelTestBase {
ResourceMetadataData serviceData1 = new ResourceMetadataData();
serviceData1.getMetadataDataDefinition().setUniqueId(resourceName);
- Either<ResourceMetadataData, TitanOperationStatus> createNode = titanDao.createNode(serviceData1,
- ResourceMetadataData.class);
+ Either<ResourceMetadataData, TitanOperationStatus> createNode = titanDao.createNode(serviceData1, ResourceMetadataData.class);
assertTrue("check resource created", createNode.isLeft());
return createNode.left().value();
diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/CapabilityTypeOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/CapabilityTypeOperationTest.java
index 5b8420d5dc..f6f02457d5 100644
--- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/CapabilityTypeOperationTest.java
+++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/CapabilityTypeOperationTest.java
@@ -118,22 +118,18 @@ public class CapabilityTypeOperationTest extends ModelTestBase {
capabilityTypeDefinition.setDescription("desc1");
capabilityTypeDefinition.setType("tosca.capabilities.Container1");
- Either<CapabilityTypeDefinition, StorageOperationStatus> addCapabilityType1 = capabilityTypeOperation
- .addCapabilityType(capabilityTypeDefinition, true);
+ Either<CapabilityTypeDefinition, StorageOperationStatus> addCapabilityType1 = capabilityTypeOperation.addCapabilityType(capabilityTypeDefinition, true);
assertEquals("check capability type added", true, addCapabilityType1.isLeft());
CapabilityTypeDefinition capabilityTypeAdded = addCapabilityType1.left().value();
compareBetweenCreatedToSent(capabilityTypeDefinition, capabilityTypeAdded);
- Either<CapabilityTypeDefinition, TitanOperationStatus> capabilityTypeByUid = capabilityTypeOperation
- .getCapabilityTypeByUid(capabilityTypeAdded.getUniqueId());
+ Either<CapabilityTypeDefinition, TitanOperationStatus> capabilityTypeByUid = capabilityTypeOperation.getCapabilityTypeByUid(capabilityTypeAdded.getUniqueId());
compareBetweenCreatedToSent(capabilityTypeByUid.left().value(), capabilityTypeDefinition);
- Either<CapabilityTypeDefinition, StorageOperationStatus> addCapabilityType2 = capabilityTypeOperation
- .addCapabilityType(capabilityTypeDefinition, true);
+ Either<CapabilityTypeDefinition, StorageOperationStatus> addCapabilityType2 = capabilityTypeOperation.addCapabilityType(capabilityTypeDefinition, true);
assertEquals("check capability type failed", true, addCapabilityType2.isRight());
- assertEquals("check returned error", StorageOperationStatus.SCHEMA_VIOLATION,
- addCapabilityType2.right().value());
+ assertEquals("check returned error", StorageOperationStatus.SCHEMA_VIOLATION, addCapabilityType2.right().value());
}
@@ -145,14 +141,12 @@ public class CapabilityTypeOperationTest extends ModelTestBase {
capabilityTypeDefinition.setType("tosca.capabilities.Container2");
capabilityTypeDefinition.setDerivedFrom("derivedFrom");
- Either<CapabilityTypeDefinition, StorageOperationStatus> addCapabilityType1 = capabilityTypeOperation
- .addCapabilityType(capabilityTypeDefinition, true);
+ Either<CapabilityTypeDefinition, StorageOperationStatus> addCapabilityType1 = capabilityTypeOperation.addCapabilityType(capabilityTypeDefinition, true);
// assertEquals("check capability type parent not exist",
// StorageOperationStatus.INVALID_ID,
// addCapabilityType1.right().value());
// TODO: esofer change to INVALID_ID
- assertEquals("check capability type parent not exist", StorageOperationStatus.INVALID_ID,
- addCapabilityType1.right().value());
+ assertEquals("check capability type parent not exist", StorageOperationStatus.INVALID_ID, addCapabilityType1.right().value());
}
public CapabilityTypeDefinition createCapability(String capabilityTypeName) {
@@ -176,12 +170,10 @@ public class CapabilityTypeOperationTest extends ModelTestBase {
capabilityTypeDefinition.setProperties(properties);
- Either<CapabilityTypeDefinition, StorageOperationStatus> addCapabilityType1 = capabilityTypeOperation
- .addCapabilityType(capabilityTypeDefinition, true);
+ Either<CapabilityTypeDefinition, StorageOperationStatus> addCapabilityType1 = capabilityTypeOperation.addCapabilityType(capabilityTypeDefinition, true);
CapabilityTypeDefinition capabilityTypeDefinitionCreated = addCapabilityType1.left().value();
- Either<CapabilityTypeDefinition, StorageOperationStatus> capabilityType = capabilityTypeOperation
- .getCapabilityType(capabilityTypeDefinitionCreated.getUniqueId(), true);
+ Either<CapabilityTypeDefinition, StorageOperationStatus> capabilityType = capabilityTypeOperation.getCapabilityType(capabilityTypeDefinitionCreated.getUniqueId(), true);
assertEquals("check capability type fetched", true, capabilityType.isLeft());
CapabilityTypeDefinition fetchedCTD = capabilityType.left().value();
@@ -215,12 +207,10 @@ public class CapabilityTypeOperationTest extends ModelTestBase {
capabilityTypeDefinition.setProperties(properties);
- Either<CapabilityTypeDefinition, StorageOperationStatus> addCapabilityType1 = capabilityTypeOperation
- .addCapabilityType(capabilityTypeDefinition, true);
+ Either<CapabilityTypeDefinition, StorageOperationStatus> addCapabilityType1 = capabilityTypeOperation.addCapabilityType(capabilityTypeDefinition, true);
CapabilityTypeDefinition capabilityTypeDefinitionCreated = addCapabilityType1.left().value();
- Either<CapabilityTypeDefinition, StorageOperationStatus> capabilityType = capabilityTypeOperation
- .getCapabilityType(capabilityTypeDefinitionCreated.getUniqueId());
+ Either<CapabilityTypeDefinition, StorageOperationStatus> capabilityType = capabilityTypeOperation.getCapabilityType(capabilityTypeDefinitionCreated.getUniqueId());
assertEquals("check capability type fetched", true, capabilityType.isLeft());
CapabilityTypeDefinition fetchedCTD = capabilityType.left().value();
@@ -231,8 +221,7 @@ public class CapabilityTypeOperationTest extends ModelTestBase {
private void compareProperties(Map<String, PropertyDefinition> first, Map<String, PropertyDefinition> second) {
- assertTrue("check properties are full or empty",
- ((first == null && second == null) || (first != null && second != null)));
+ assertTrue("check properties are full or empty", ((first == null && second == null) || (first != null && second != null)));
if (first != null) {
assertEquals("check properties size", first.size(), second.size());
@@ -254,16 +243,14 @@ public class CapabilityTypeOperationTest extends ModelTestBase {
@Test
public void testGetCapabilityTypeNotFound() {
- Either<CapabilityTypeDefinition, StorageOperationStatus> capabilityType = capabilityTypeOperation
- .getCapabilityType("not_exists");
+ Either<CapabilityTypeDefinition, StorageOperationStatus> capabilityType = capabilityTypeOperation.getCapabilityType("not_exists");
assertEquals("check not found is returned", StorageOperationStatus.NOT_FOUND, capabilityType.right().value());
}
private void comparePropertyDefinition(PropertyDefinition first, PropertyDefinition second) {
- assertTrue("check objects are full or empty",
- ((first == null && second == null) || (first != null && second != null)));
+ assertTrue("check objects are full or empty", ((first == null && second == null) || (first != null && second != null)));
if (first != null) {
assertTrue("check property default value", compareValue(first.getDefaultValue(), second.getDefaultValue()));
assertTrue("check property description", compareValue(first.getDescription(), second.getDescription()));
@@ -275,8 +262,7 @@ public class CapabilityTypeOperationTest extends ModelTestBase {
private void compareList(List<PropertyConstraint> first, List<PropertyConstraint> second) {
- assertTrue("check lists are full or empty",
- ((first == null && second == null) || (first != null && second != null)));
+ assertTrue("check lists are full or empty", ((first == null && second == null) || (first != null && second != null)));
if (first != null) {
assertEquals("check list size", first.size(), second.size());
}
@@ -302,8 +288,7 @@ public class CapabilityTypeOperationTest extends ModelTestBase {
private PropertyDefinition buildProperty1() {
PropertyDefinition property1 = new PropertyDefinition();
property1.setDefaultValue("10");
- property1.setDescription(
- "Size of the local disk, in Gigabytes (GB), available to applications running on the Compute node.");
+ property1.setDescription("Size of the local disk, in Gigabytes (GB), available to applications running on the Compute node.");
property1.setType(ToscaType.INTEGER.name().toLowerCase());
List<PropertyConstraint> constraints = new ArrayList<PropertyConstraint>();
GreaterThanConstraint propertyConstraint1 = new GreaterThanConstraint("0");
diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperationSpringTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperationSpringTest.java
index 2dcb1ee72e..f07115af5b 100644
--- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperationSpringTest.java
+++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperationSpringTest.java
@@ -44,6 +44,7 @@ import javax.annotation.Resource;
import org.apache.tinkerpop.gremlin.structure.io.IoCore;
import org.junit.Before;
import org.junit.BeforeClass;
+import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
@@ -154,71 +155,57 @@ public class ComponentInstanceOperationSpringTest extends ModelTestBase {
}
titanGenericDao.commit();
deleteAndCreateCategory(CATEGORY_NAME);
- UserData modifierData = deleteAndCreateUser(ResourceCreationUtils.MODIFIER_ATT_UID + "rfc",
- ResourceCreationUtils.MODIFIER_FIRST_NAME, ResourceCreationUtils.MODIFIER_LAST_NAME, "ADMIN");
+ UserData modifierData = deleteAndCreateUser(ResourceCreationUtils.MODIFIER_ATT_UID + "rfc", ResourceCreationUtils.MODIFIER_FIRST_NAME, ResourceCreationUtils.MODIFIER_LAST_NAME, "ADMIN");
rfcUser = convertUserDataToUser(modifierData);
}
@Test
+ @Ignore
public void testAddCapabilityPropertyValuesToResourceInstance() {
String rootName = "Root123";
- org.openecomp.sdc.be.model.Resource rootResource = createResource(rfcUser.getUserId(), CATEGORY_NAME, rootName,
- "1.0", null, false, true);
+ org.openecomp.sdc.be.model.Resource rootResource = createResource(rfcUser.getUserId(), CATEGORY_NAME, rootName, "1.0", null, false, true);
// certification request
- Either<? extends org.openecomp.sdc.be.model.Component, StorageOperationStatus> requestCertificationResult = lifecycleOperation
- .requestCertificationComponent(NodeTypeEnum.Resource, rootResource, rfcUser, rfcUser, false);
+ Either<? extends org.openecomp.sdc.be.model.Component, StorageOperationStatus> requestCertificationResult = lifecycleOperation.requestCertificationComponent(NodeTypeEnum.Resource, rootResource, rfcUser, rfcUser, false);
assertTrue(requestCertificationResult.isLeft());
- org.openecomp.sdc.be.model.Resource resultResource = (org.openecomp.sdc.be.model.Resource) requestCertificationResult
- .left().value();
+ org.openecomp.sdc.be.model.Resource resultResource = (org.openecomp.sdc.be.model.Resource) requestCertificationResult.left().value();
// start certification
- Either<? extends org.openecomp.sdc.be.model.Component, StorageOperationStatus> startCertificationResult = lifecycleOperation
- .startComponentCertification(NodeTypeEnum.Resource, resultResource, rfcUser, rfcUser, false);
+ Either<? extends org.openecomp.sdc.be.model.Component, StorageOperationStatus> startCertificationResult = lifecycleOperation.startComponentCertification(NodeTypeEnum.Resource, resultResource, rfcUser, rfcUser, false);
assertEquals(true, startCertificationResult.isLeft());
- Either<? extends org.openecomp.sdc.be.model.Component, StorageOperationStatus> certifiedResourceRes = lifecycleOperation
- .certifyComponent(NodeTypeEnum.Resource, rootResource, rfcUser, rfcUser, false);
+ Either<? extends org.openecomp.sdc.be.model.Component, StorageOperationStatus> certifiedResourceRes = lifecycleOperation.certifyComponent(NodeTypeEnum.Resource, rootResource, rfcUser, rfcUser, false);
assertTrue(certifiedResourceRes.isLeft());
CapabilityTypeDefinition capabilityType = buildCapabilityType();
- Either<CapabilityTypeDefinition, StorageOperationStatus> capabilityTypeRes = capabilityTypeOperation
- .addCapabilityType(capabilityType);
+ Either<CapabilityTypeDefinition, StorageOperationStatus> capabilityTypeRes = capabilityTypeOperation.addCapabilityType(capabilityType);
assertTrue(capabilityTypeRes.isLeft());
CapabilityData capData = FactoryUtils.createCapabilityData();
- CapabilityDefinition capabilityDefinitionRoot = FactoryUtils
- .convertCapabilityDataToCapabilityDefinitionRoot(capData);
+ CapabilityDefinition capabilityDefinitionRoot = FactoryUtils.convertCapabilityDataToCapabilityDefinitionRoot(capData);
- Either<CapabilityDefinition, StorageOperationStatus> addCapabilityRootRes = capabilityOperation.addCapability(
- (String) certifiedResourceRes.left().value().getUniqueId(), capabilityDefinitionRoot.getName(),
- capabilityDefinitionRoot);
+ Either<CapabilityDefinition, StorageOperationStatus> addCapabilityRootRes = capabilityOperation.addCapability((String) certifiedResourceRes.left().value().getUniqueId(), capabilityDefinitionRoot.getName(), capabilityDefinitionRoot);
assertTrue(addCapabilityRootRes.isLeft());
String resourceName = "tosca.nodes.Apache.2.0";
- CapabilityDefinition capabilityDefinition = FactoryUtils
- .convertCapabilityDataToCapabilityDefinitionAddProperties(capData);
- org.openecomp.sdc.be.model.Resource resource = createResource(rfcUser.getUserId(), CATEGORY_NAME, resourceName,
- "0.1", rootName, false, true);
+ CapabilityDefinition capabilityDefinition = FactoryUtils.convertCapabilityDataToCapabilityDefinitionAddProperties(capData);
+ org.openecomp.sdc.be.model.Resource resource = createResource(rfcUser.getUserId(), CATEGORY_NAME, resourceName, "0.1", rootName, false, true);
- Either<CapabilityDefinition, StorageOperationStatus> addCapabilityRes = capabilityOperation
- .addCapability((String) resource.getUniqueId(), capabilityDefinition.getName(), capabilityDefinition);
+ Either<CapabilityDefinition, StorageOperationStatus> addCapabilityRes = capabilityOperation.addCapability((String) resource.getUniqueId(), capabilityDefinition.getName(), capabilityDefinition);
assertTrue(addCapabilityRes.isLeft());
List<ComponentInstanceProperty> properties = addCapabilityRes.left().value().getProperties();
assertTrue(properties.size() == 2);
- Either<org.openecomp.sdc.be.model.Resource, StorageOperationStatus> clonedResourceRes = resourceOperation
- .cloneComponent(resource, "0.2", false);
+ Either<org.openecomp.sdc.be.model.Resource, StorageOperationStatus> clonedResourceRes = resourceOperation.cloneComponent(resource, "0.2", false);
assertTrue(clonedResourceRes.isLeft());
org.openecomp.sdc.be.model.Resource clonedResource = clonedResourceRes.left().value();
ComponentInstance instance = buildResourceInstance(clonedResource.getUniqueId(), "1", "tosca.nodes.Apache");
Service origService = createService(rfcUser.getUserId(), CATEGORY_NAME, "my-service", "1.0", true);
- Either<Service, StorageOperationStatus> service2 = serviceOperation.getService(origService.getUniqueId(),
- false);
+ Either<Service, StorageOperationStatus> service2 = serviceOperation.getService(origService.getUniqueId(), false);
assertTrue(service2.isLeft());
origService = service2.left().value();
@@ -228,9 +215,7 @@ public class ComponentInstanceOperationSpringTest extends ModelTestBase {
Service fullService = origService;
- Either<ComponentInstance, TitanOperationStatus> status = resourceInstanceOperation
- .addComponentInstanceToContainerComponent((String) origService.getUniqueId(), NodeTypeEnum.Service, "1",
- true, instance, NodeTypeEnum.Resource, false);
+ Either<ComponentInstance, TitanOperationStatus> status = resourceInstanceOperation.addComponentInstanceToContainerComponent((String) origService.getUniqueId(), NodeTypeEnum.Service, "1", true, instance, NodeTypeEnum.Resource, false);
assertTrue(status.isLeft());
ComponentInstance resourceInstance = status.left().value();
@@ -239,17 +224,14 @@ public class ComponentInstanceOperationSpringTest extends ModelTestBase {
List<ComponentInstanceProperty> propertyValues = FactoryUtils.createComponentInstancePropertyList();
capability.setProperties(propertyValues);
- Either<Map<CapabilityInstData, List<PropertyValueData>>, TitanOperationStatus> addCPVsToRiRes = componentInstanceOperation
- .addCapabilityPropertyValuesToResourceInstance(resourceInstance.getUniqueId(), capability, true);
+ Either<Map<CapabilityInstData, List<PropertyValueData>>, TitanOperationStatus> addCPVsToRiRes = componentInstanceOperation.addCapabilityPropertyValuesToResourceInstance(resourceInstance.getUniqueId(), capability, true);
assertTrue(addCPVsToRiRes.isLeft());
- Either<Service, StorageOperationStatus> createService = serviceOperation.cloneService(fullService, "2.0",
- false);
+ Either<Service, StorageOperationStatus> createService = serviceOperation.cloneService(fullService, "2.0", false);
assertTrue(createService.isLeft());
Map<String, List<CapabilityDefinition>> capabilitiesMap = createService.left().value().getCapabilities();
assertTrue(capabilitiesMap != null && capabilitiesMap.size() == 1);
- Map<String, CapabilityDefinition> capabilities = capabilitiesMap.values().iterator().next().stream()
- .collect(Collectors.toMap(CapabilityDefinition::getName, Function.identity()));
+ Map<String, CapabilityDefinition> capabilities = capabilitiesMap.values().iterator().next().stream().collect(Collectors.toMap(CapabilityDefinition::getName, Function.identity()));
assertTrue(capabilities.containsKey("Cap1") && capabilities.containsKey("Cap2"));
// String outputFile = exportGraphMl();
@@ -343,8 +325,7 @@ public class ComponentInstanceOperationSpringTest extends ModelTestBase {
public ResourceMetadataData createResource(String resourceName, TitanGenericDao titanGenericDao) {
ResourceMetadataData serviceData1 = new ResourceMetadataData();
serviceData1.getMetadataDataDefinition().setUniqueId(resourceName);
- Either<ResourceMetadataData, TitanOperationStatus> createNode = titanGenericDao.createNode(serviceData1,
- ResourceMetadataData.class);
+ Either<ResourceMetadataData, TitanOperationStatus> createNode = titanGenericDao.createNode(serviceData1, ResourceMetadataData.class);
assertTrue("check service created", createNode.isLeft());
return createNode.left().value();
}
@@ -352,21 +333,18 @@ public class ComponentInstanceOperationSpringTest extends ModelTestBase {
public ServiceMetadataData createServiceMetadataData(String serviceName, TitanGenericDao titanGenericDao) {
ServiceMetadataData serviceData1 = new ServiceMetadataData();
serviceData1.getMetadataDataDefinition().setUniqueId(serviceName);
- Either<ServiceMetadataData, TitanOperationStatus> createNode = titanGenericDao.createNode(serviceData1,
- ServiceMetadataData.class);
+ Either<ServiceMetadataData, TitanOperationStatus> createNode = titanGenericDao.createNode(serviceData1, ServiceMetadataData.class);
assertTrue("check service created", createNode.isLeft());
return createNode.left().value();
}
- public Service createService(String userId, String category, String serviceName, String serviceVersion,
- boolean isHighestVersion) {
+ public Service createService(String userId, String category, String serviceName, String serviceVersion, boolean isHighestVersion) {
Service service = buildServiceMetadata(userId, category, serviceName, serviceVersion);
service.setHighestVersion(isHighestVersion);
Either<Service, StorageOperationStatus> result = serviceOperation.createService(service, true);
assertTrue(result.isLeft());
Service resultService = result.left().value();
- assertEquals("check resource state", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT,
- resultService.getLifecycleState());
+ assertEquals("check resource state", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, resultService.getLifecycleState());
return resultService;
}
@@ -412,8 +390,7 @@ public class ComponentInstanceOperationSpringTest extends ModelTestBase {
return userData;
}
- public org.openecomp.sdc.be.model.Resource createResource(String userId, String category, String resourceName,
- String resourceVersion, String parentResourceName, boolean isAbstract, boolean isHighestVersion) {
+ public org.openecomp.sdc.be.model.Resource createResource(String userId, String category, String resourceName, String resourceVersion, String parentResourceName, boolean isAbstract, boolean isHighestVersion) {
String propName1 = "disk_size";
String propName2 = "num_cpus";
@@ -422,8 +399,7 @@ public class ComponentInstanceOperationSpringTest extends ModelTestBase {
if (parentResourceName != null) {
derivedFrom.add(parentResourceName);
}
- org.openecomp.sdc.be.model.Resource resource = buildResourceMetadata(userId, category, resourceName,
- resourceVersion);
+ org.openecomp.sdc.be.model.Resource resource = buildResourceMetadata(userId, category, resourceName, resourceVersion);
resource.setAbstract(isAbstract);
resource.setHighestVersion(isHighestVersion);
@@ -432,8 +408,7 @@ public class ComponentInstanceOperationSpringTest extends ModelTestBase {
PropertyDefinition property1 = new PropertyDefinition();
property1.setDefaultValue("10");
- property1.setDescription(
- "Size of the local disk, in Gigabytes (GB), available to applications running on the Compute node.");
+ property1.setDescription("Size of the local disk, in Gigabytes (GB), available to applications running on the Compute node.");
property1.setType(ToscaType.INTEGER.name().toLowerCase());
List<PropertyConstraint> constraints = new ArrayList<PropertyConstraint>();
GreaterThanConstraint propertyConstraint1 = new GreaterThanConstraint("0");
@@ -466,18 +441,15 @@ public class ComponentInstanceOperationSpringTest extends ModelTestBase {
resource.setProperties(convertMapToList(properties));
- Either<org.openecomp.sdc.be.model.Resource, StorageOperationStatus> result = resourceOperation
- .createResource(resource, true);
+ Either<org.openecomp.sdc.be.model.Resource, StorageOperationStatus> result = resourceOperation.createResource(resource, true);
assertTrue(result.isLeft());
org.openecomp.sdc.be.model.Resource resultResource = result.left().value();
- assertEquals("check resource state", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT,
- resultResource.getLifecycleState());
+ assertEquals("check resource state", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, resultResource.getLifecycleState());
String resourceId = resultResource.getUniqueId();
- Either<PropertyDefinition, StorageOperationStatus> either = propertyOperation.getPropertyOfResource(propName1,
- resourceId);
+ Either<PropertyDefinition, StorageOperationStatus> either = propertyOperation.getPropertyOfResource(propName1, resourceId);
assertTrue(either.isLeft());
PropertyDefinition propertyDefinition = either.left().value();
@@ -485,14 +457,12 @@ public class ComponentInstanceOperationSpringTest extends ModelTestBase {
assertEquals("check property description", property1.getDescription(), propertyDefinition.getDescription());
assertEquals("check property type", property1.getType(), propertyDefinition.getType());
assertEquals("check property unique id", property1.getUniqueId(), propertyDefinition.getUniqueId());
- assertEquals("check property consitraints size", property1.getConstraints().size(),
- propertyDefinition.getConstraints().size());
+ assertEquals("check property consitraints size", property1.getConstraints().size(), propertyDefinition.getConstraints().size());
return resultResource;
}
- private org.openecomp.sdc.be.model.Resource buildResourceMetadata(String userId, String category,
- String resourceName, String resourceVersion) {
+ private org.openecomp.sdc.be.model.Resource buildResourceMetadata(String userId, String category, String resourceName, String resourceVersion) {
org.openecomp.sdc.be.model.Resource resource = new org.openecomp.sdc.be.model.Resource();
resource.setName(resourceName);
diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperationTest.java
index e77c9f0291..c77769d7d2 100644
--- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperationTest.java
+++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperationTest.java
@@ -65,20 +65,16 @@ public class ComponentInstanceOperationTest {
ComponentInstance ri = FactoryUtils.createResourceInstance();
CapabilityData capData = FactoryUtils.createCapabilityData();
- Either<List<ImmutablePair<GraphNode, GraphEdge>>, TitanOperationStatus> childNodesReturned = prepareChildNodeRetValue(
- capData);
+ Either<List<ImmutablePair<GraphNode, GraphEdge>>, TitanOperationStatus> childNodesReturned = prepareChildNodeRetValue(capData);
- Mockito.when(titanGenericDao.getChildrenNodes(Mockito.anyString(), Mockito.anyString(),
- Mockito.any(GraphEdgeLabels.class), Mockito.any(NodeTypeEnum.class), Mockito.any()))
- .thenReturn(childNodesReturned);
+ Mockito.when(titanGenericDao.getChildrenNodes(Mockito.anyString(), Mockito.anyString(), Mockito.any(GraphEdgeLabels.class), Mockito.any(NodeTypeEnum.class), Mockito.any())).thenReturn(childNodesReturned);
// ImmutablePair<ComponentInstance, List<ImmutablePair<CapabilityData,
// GraphEdge>>> instanceAndCapabilities =
// componentInstanceOperation.getCapabilities(ri,
// NodeTypeEnum.Resource);
- Either<List<ImmutablePair<CapabilityData, GraphEdge>>, TitanOperationStatus> instanceAndCapabilities = componentInstanceOperation
- .getCapabilities(ri, NodeTypeEnum.Resource);
+ Either<List<ImmutablePair<CapabilityData, GraphEdge>>, TitanOperationStatus> instanceAndCapabilities = componentInstanceOperation.getCapabilities(ri, NodeTypeEnum.Resource);
// assertTrue(instanceAndCapabilities.left.getUniqueId().equals(ri.getUniqueId()));
assertTrue(instanceAndCapabilities.left().value().size() == 1);
@@ -90,19 +86,15 @@ public class ComponentInstanceOperationTest {
public void testGetRequirements() {
ComponentInstance ri = FactoryUtils.createResourceInstance();
RequirementData reqData = FactoryUtils.createRequirementData();
- Either<List<ImmutablePair<GraphNode, GraphEdge>>, TitanOperationStatus> childNodesReturned = prepareChildNodeRetValue(
- reqData);
+ Either<List<ImmutablePair<GraphNode, GraphEdge>>, TitanOperationStatus> childNodesReturned = prepareChildNodeRetValue(reqData);
- Mockito.when(titanGenericDao.getChildrenNodes(Mockito.anyString(), Mockito.anyString(),
- Mockito.any(GraphEdgeLabels.class), Mockito.any(NodeTypeEnum.class), Mockito.any()))
- .thenReturn(childNodesReturned);
+ Mockito.when(titanGenericDao.getChildrenNodes(Mockito.anyString(), Mockito.anyString(), Mockito.any(GraphEdgeLabels.class), Mockito.any(NodeTypeEnum.class), Mockito.any())).thenReturn(childNodesReturned);
// ImmutablePair<ComponentInstance, List<ImmutablePair<RequirementData,
// GraphEdge>>> instanceAndCapabilities =
// componentInstanceOperation.getRequirements(ri,
// NodeTypeEnum.Resource);
- Either<List<ImmutablePair<RequirementData, GraphEdge>>, TitanOperationStatus> instanceAndCapabilities = componentInstanceOperation
- .getRequirements(ri, NodeTypeEnum.Resource);
+ Either<List<ImmutablePair<RequirementData, GraphEdge>>, TitanOperationStatus> instanceAndCapabilities = componentInstanceOperation.getRequirements(ri, NodeTypeEnum.Resource);
// assertTrue(instanceAndCapabilities.left.getUniqueId().equals(ri.getUniqueId()));
// assertTrue(instanceAndCapabilities.right.size() == 1);
@@ -125,8 +117,7 @@ public class ComponentInstanceOperationTest {
return capabilityInstance;
}
- private Either<List<ImmutablePair<GraphNode, GraphEdge>>, TitanOperationStatus> prepareChildNodeRetValue(
- GraphNode data) {
+ private Either<List<ImmutablePair<GraphNode, GraphEdge>>, TitanOperationStatus> prepareChildNodeRetValue(GraphNode data) {
ImmutablePair<GraphNode, GraphEdge> pair = new ImmutablePair<>(data, FactoryUtils.createGraphEdge());
List<ImmutablePair<GraphNode, GraphEdge>> retList = new ArrayList<>();
retList.add(pair);
diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ComponentOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ComponentOperationTest.java
index 14018d31f9..061393645a 100644
--- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ComponentOperationTest.java
+++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ComponentOperationTest.java
@@ -93,13 +93,11 @@ public class ComponentOperationTest {
CapabilityData capData = FactoryUtils.createCapabilityData();
FactoryUtils.addComponentInstanceToVF(vf, ri);
- Either<List<ImmutablePair<CapabilityData, GraphEdge>>, TitanOperationStatus> capDataList = prepareCompOperationReturnValue(
- ri, capData);
+ Either<List<ImmutablePair<CapabilityData, GraphEdge>>, TitanOperationStatus> capDataList = prepareCompOperationReturnValue(ri, capData);
prepareMocksForCapabilitiesMethods(ri, capDataList);
- Map<String, List<CapabilityDefinition>> capabilities = compOperation
- .getCapabilities(vf, NodeTypeEnum.Resource, false).left().value();
+ Map<String, List<CapabilityDefinition>> capabilities = compOperation.getCapabilities(vf, NodeTypeEnum.Resource, false).left().value();
assertTrue(capabilities.size() == 1);
Entry<String, List<CapabilityDefinition>> entry = capabilities.entrySet().iterator().next();
assertTrue(entry.getKey().equals(capData.getType()));
@@ -116,13 +114,11 @@ public class ComponentOperationTest {
FactoryUtils.addComponentInstanceToVF(vf, ri);
- Either<List<ImmutablePair<RequirementData, GraphEdge>>, TitanOperationStatus> reqDataEdgeList = prepareCompOperationReturnValue(
- ri, reqData);
+ Either<List<ImmutablePair<RequirementData, GraphEdge>>, TitanOperationStatus> reqDataEdgeList = prepareCompOperationReturnValue(ri, reqData);
prepareMocksForRequirmenetsMethods(ri, reqDataEdgeList);
- Map<String, List<RequirementDefinition>> requirements = compOperation
- .getRequirements(vf, NodeTypeEnum.Resource, false).left().value();
+ Map<String, List<RequirementDefinition>> requirements = compOperation.getRequirements(vf, NodeTypeEnum.Resource, false).left().value();
assertTrue(requirements.size() == 1);
Entry<String, List<RequirementDefinition>> entry = requirements.entrySet().iterator().next();
assertTrue(entry.getKey().equals(FactoryUtils.Constants.DEFAULT_CAPABILITY_TYPE));
@@ -130,70 +126,51 @@ public class ComponentOperationTest {
assertTrue(entry.getValue().get(0).getUniqueId().equals(reqData.getUniqueId()));
}
- private void prepareMocksForRequirmenetsMethods(ComponentInstance ri,
- Either<List<ImmutablePair<RequirementData, GraphEdge>>, TitanOperationStatus> reqDataEdgeList) {
+ private void prepareMocksForRequirmenetsMethods(ComponentInstance ri, Either<List<ImmutablePair<RequirementData, GraphEdge>>, TitanOperationStatus> reqDataEdgeList) {
when(componentInstanceOperation.getRequirements(ri, NodeTypeEnum.Resource)).thenReturn(reqDataEdgeList);
when(requirementOperation.getRequirement(Mockito.anyString())).then(createReqDefAnswer());
}
- private void prepareMocksForCapabilitiesMethods(ComponentInstance ri,
- Either<List<ImmutablePair<CapabilityData, GraphEdge>>, TitanOperationStatus> capDataList) {
+ private void prepareMocksForCapabilitiesMethods(ComponentInstance ri, Either<List<ImmutablePair<CapabilityData, GraphEdge>>, TitanOperationStatus> capDataList) {
when(componentInstanceOperation.getCapabilities(ri, NodeTypeEnum.Resource)).thenReturn(capDataList);
- when(capabilityOperation.getCapabilityByCapabilityData(Mockito.any(CapabilityData.class)))
- .then(createCapDefByDataAnswer());
+ when(capabilityOperation.getCapabilityByCapabilityData(Mockito.any(CapabilityData.class))).then(createCapDefByDataAnswer());
List<ImmutablePair<CapabilityInstData, GraphEdge>> capInstList = new ArrayList<>();
CapabilityInstData curCapabilityInst = FactoryUtils.createCapabilityInstData();
GraphEdge edge = new GraphEdge();
Map<String, Object> properties = new HashMap<>();
- properties.put(GraphPropertiesDictionary.CAPABILITY_ID.getProperty(),
- capDataList.left().value().get(0).getLeft().getUniqueId());
+ properties.put(GraphPropertiesDictionary.CAPABILITY_ID.getProperty(), capDataList.left().value().get(0).getLeft().getUniqueId());
edge.setProperties(properties);
- ImmutablePair<CapabilityInstData, GraphEdge> pair = new ImmutablePair<CapabilityInstData, GraphEdge>(
- curCapabilityInst, edge);
+ ImmutablePair<CapabilityInstData, GraphEdge> pair = new ImmutablePair<CapabilityInstData, GraphEdge>(curCapabilityInst, edge);
capInstList.add(pair);
- when(titanGenericDao.getChildrenNodes(
- UniqueIdBuilder.getKeyByNodeType(
- NodeTypeEnum.getByNameIgnoreCase(ri.getOriginType().getInstanceType().trim())),
- ri.getUniqueId(), GraphEdgeLabels.CAPABILITY_INST, NodeTypeEnum.CapabilityInst,
+ when(titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.getByNameIgnoreCase(ri.getOriginType().getInstanceType().trim())), ri.getUniqueId(), GraphEdgeLabels.CAPABILITY_INST, NodeTypeEnum.CapabilityInst,
CapabilityInstData.class)).thenReturn(Either.left(capInstList));
- when(titanGenericDao.getChild(
- UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.getByName(curCapabilityInst.getLabel())),
- curCapabilityInst.getUniqueId(), GraphEdgeLabels.INSTANCE_OF, NodeTypeEnum.Capability,
- CapabilityData.class)).thenReturn(Either.left(capDataList.left().value().get(0)));
+ when(titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.getByName(curCapabilityInst.getLabel())), curCapabilityInst.getUniqueId(), GraphEdgeLabels.INSTANCE_OF, NodeTypeEnum.Capability, CapabilityData.class))
+ .thenReturn(Either.left(capDataList.left().value().get(0)));
PropertyValueData propertyValueData = FactoryUtils.createPropertyData();
- ImmutablePair<PropertyValueData, GraphEdge> propPair = new ImmutablePair<PropertyValueData, GraphEdge>(
- propertyValueData, null);
+ ImmutablePair<PropertyValueData, GraphEdge> propPair = new ImmutablePair<PropertyValueData, GraphEdge>(propertyValueData, null);
List<ImmutablePair<PropertyValueData, GraphEdge>> propPairList = new ArrayList<>();
propPairList.add(propPair);
- when(titanGenericDao.getChildrenNodes(
- UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.getByName(curCapabilityInst.getLabel())),
- curCapabilityInst.getUniqueId(), GraphEdgeLabels.PROPERTY_VALUE, NodeTypeEnum.PropertyValue,
+ when(titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.getByName(curCapabilityInst.getLabel())), curCapabilityInst.getUniqueId(), GraphEdgeLabels.PROPERTY_VALUE, NodeTypeEnum.PropertyValue,
PropertyValueData.class)).thenReturn(Either.left(propPairList));
- CapabilityDefinition capDef = FactoryUtils
- .convertCapabilityDataToCapabilityDefinitionAddProperties(capDataList.left().value().get(0).getLeft());
- List<PropertyDefinition> propDefList = capDef.getProperties().stream().filter(p -> p.getName().equals("host"))
- .collect(Collectors.toList());
+ CapabilityDefinition capDef = FactoryUtils.convertCapabilityDataToCapabilityDefinitionAddProperties(capDataList.left().value().get(0).getLeft());
+ List<PropertyDefinition> propDefList = capDef.getProperties().stream().filter(p -> p.getName().equals("host")).collect(Collectors.toList());
PropertyDefinition propDef = propDefList.get(0);
PropertyData propData = FactoryUtils.convertCapabilityDefinitionToCapabilityData(propDef);
ImmutablePair<PropertyData, GraphEdge> defPropPair = new ImmutablePair<PropertyData, GraphEdge>(propData, edge);
- when(titanGenericDao.getChild(
- UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.getByName(propertyValueData.getLabel())),
- propertyValueData.getUniqueId(), GraphEdgeLabels.PROPERTY_IMPL, NodeTypeEnum.Property,
- PropertyData.class)).thenReturn(Either.left(defPropPair));
+ when(titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.getByName(propertyValueData.getLabel())), propertyValueData.getUniqueId(), GraphEdgeLabels.PROPERTY_IMPL, NodeTypeEnum.Property, PropertyData.class))
+ .thenReturn(Either.left(defPropPair));
List<CapabilityDefinition> capDefList = new ArrayList<>();
capDefList.add(capDef);
- when(componentInstanceOperation.updateCapDefPropertyValues(Mockito.any(ComponentInstance.class),
- Mockito.any(List.class))).thenReturn(Either.left(capDefList));
+ when(componentInstanceOperation.updateCapDefPropertyValues(Mockito.any(ComponentInstance.class), Mockito.any(List.class))).thenReturn(Either.left(capDefList));
}
- private <Data> Either<List<ImmutablePair<Data, GraphEdge>>, TitanOperationStatus> prepareCompOperationReturnValue(
- ComponentInstance ri, Data data) {
+ private <Data> Either<List<ImmutablePair<Data, GraphEdge>>, TitanOperationStatus> prepareCompOperationReturnValue(ComponentInstance ri, Data data) {
ImmutablePair<Data, GraphEdge> dataEdgePair = new ImmutablePair<>(data, new GraphEdge());
List<ImmutablePair<Data, GraphEdge>> dataEdgeList = new ArrayList<>();
dataEdgeList.add(dataEdgePair);
@@ -204,8 +181,7 @@ public class ComponentOperationTest {
return new Answer<Either<RequirementDefinition, TitanOperationStatus>>() {
@Override
- public Either<RequirementDefinition, TitanOperationStatus> answer(InvocationOnMock invocation)
- throws Throwable {
+ public Either<RequirementDefinition, TitanOperationStatus> answer(InvocationOnMock invocation) throws Throwable {
String reqDataId = (String) invocation.getArguments()[0];
return Either.left(FactoryUtils.convertRequirementDataIDToRequirementDefinition(reqDataId));
}
@@ -216,8 +192,7 @@ public class ComponentOperationTest {
return new Answer<Either<CapabilityDefinition, TitanOperationStatus>>() {
@Override
- public Either<CapabilityDefinition, TitanOperationStatus> answer(InvocationOnMock invocation)
- throws Throwable {
+ public Either<CapabilityDefinition, TitanOperationStatus> answer(InvocationOnMock invocation) throws Throwable {
CapabilityData capData = (CapabilityData) invocation.getArguments()[0];
return Either.left(FactoryUtils.convertCapabilityDataToCapabilityDefinitionAddProperties(capData));
}
@@ -228,15 +203,13 @@ public class ComponentOperationTest {
return new ComponentOperation() {
@Override
- protected StorageOperationStatus validateCategories(Component currentComponent, Component component,
- ComponentMetadataData componentData, NodeTypeEnum type) {
+ protected StorageOperationStatus validateCategories(Component currentComponent, Component component, ComponentMetadataData componentData, NodeTypeEnum type) {
// TODO Auto-generated method stub
return null;
}
@Override
- protected <T extends Component> StorageOperationStatus updateDerived(Component component,
- Component currentComponent, ComponentMetadataData updatedResourceData, Class<T> clazz) {
+ protected <T extends Component> StorageOperationStatus updateDerived(Component component, Component currentComponent, ComponentMetadataData updatedResourceData, Class<T> clazz) {
// TODO Auto-generated method stub
return null;
}
@@ -248,8 +221,7 @@ public class ComponentOperationTest {
}
@Override
- public Either<Integer, StorageOperationStatus> increaseAndGetComponentInstanceCounter(String componentId,
- boolean inTransaction) {
+ public Either<Integer, StorageOperationStatus> increaseAndGetComponentInstanceCounter(String componentId, boolean inTransaction) {
// TODO Auto-generated method stub
return null;
}
@@ -267,8 +239,7 @@ public class ComponentOperationTest {
}
@Override
- protected <T> Either<T, StorageOperationStatus> getComponentByNameAndVersion(String name, String version,
- Map<String, Object> additionalParams, boolean inTransaction) {
+ protected <T> Either<T, StorageOperationStatus> getComponentByNameAndVersion(String name, String version, Map<String, Object> additionalParams, boolean inTransaction) {
// TODO Auto-generated method stub
return null;
}
@@ -287,15 +258,13 @@ public class ComponentOperationTest {
// }
@Override
- public Either<List<ArtifactDefinition>, StorageOperationStatus> getAdditionalArtifacts(String resourceId,
- boolean recursively, boolean inTransaction) {
+ public Either<List<ArtifactDefinition>, StorageOperationStatus> getAdditionalArtifacts(String resourceId, boolean recursively, boolean inTransaction) {
// TODO Auto-generated method stub
return null;
}
@Override
- public <T> Either<T, StorageOperationStatus> cloneComponent(T other, String version,
- boolean inTransaction) {
+ public <T> Either<T, StorageOperationStatus> cloneComponent(T other, String version, boolean inTransaction) {
// TODO Auto-generated method stub
return null;
}
@@ -337,8 +306,7 @@ public class ComponentOperationTest {
}
@Override
- public Either<Component, StorageOperationStatus> markComponentToDelete(Component componentToDelete,
- boolean inTransaction) {
+ public Either<Component, StorageOperationStatus> markComponentToDelete(Component componentToDelete, boolean inTransaction) {
// TODO Auto-generated method stub
return null;
}
@@ -362,29 +330,25 @@ public class ComponentOperationTest {
}
@Override
- public <T> Either<T, StorageOperationStatus> cloneComponent(T other, String version,
- LifecycleStateEnum targetLifecycle, boolean inTransaction) {
+ public <T> Either<T, StorageOperationStatus> cloneComponent(T other, String version, LifecycleStateEnum targetLifecycle, boolean inTransaction) {
// TODO Auto-generated method stub
return null;
}
@Override
- public <T> Either<T, StorageOperationStatus> getComponent(String id,
- ComponentParametersView componentParametersView, boolean inTrasnaction) {
+ public <T> Either<T, StorageOperationStatus> getComponent(String id, ComponentParametersView componentParametersView, boolean inTrasnaction) {
// TODO Auto-generated method stub
return null;
}
@Override
- public <T> Either<List<T>, StorageOperationStatus> getFilteredComponents(Map<FilterKeyEnum, String> filters,
- boolean inTransaction) {
+ public <T> Either<List<T>, StorageOperationStatus> getFilteredComponents(Map<FilterKeyEnum, String> filters, boolean inTransaction) {
// TODO Auto-generated method stub
return null;
}
@Override
- protected <T> Either<T, StorageOperationStatus> updateComponentFilterResult(T component,
- boolean inTransaction, ComponentParametersView filterParametersView) {
+ protected <T> Either<T, StorageOperationStatus> updateComponentFilterResult(T component, boolean inTransaction, ComponentParametersView filterParametersView) {
// TODO Auto-generated method stub
return null;
}
diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ElementOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ElementOperationTest.java
index a529074db6..eb2615f19b 100644
--- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ElementOperationTest.java
+++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ElementOperationTest.java
@@ -92,8 +92,7 @@ public class ElementOperationTest extends ModelTestBase {
public void testGetResourceAndServiceCategoty() {
String id = OperationTestsUtil.deleteAndCreateResourceCategory(CATEGORY, SUBCATEGORY, titanDao);
- Either<CategoryDefinition, ActionStatus> res = elementOperation.getCategory(NodeTypeEnum.ResourceNewCategory,
- id);
+ Either<CategoryDefinition, ActionStatus> res = elementOperation.getCategory(NodeTypeEnum.ResourceNewCategory, id);
assertTrue(res.isLeft());
CategoryDefinition categoryDefinition = (CategoryDefinition) res.left().value();
assertEquals(CATEGORY, categoryDefinition.getName());
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 6765557bab..a71f97871f 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
@@ -73,13 +73,10 @@ public class HeatParametersOperationTest extends ModelTestBase {
GraphRelation graphRelation = new GraphRelation();
Either<GraphRelation, TitanOperationStatus> relationResult = Either.left(graphRelation);
- when(titanGenericDao.createNode((HeatParameterData) anyObject(), eq(HeatParameterData.class)))
- .thenReturn(either);
- when(titanGenericDao.createRelation((GraphNode) anyObject(), (GraphNode) anyObject(),
- eq(GraphEdgeLabels.HEAT_PARAMETER), anyMap())).thenReturn(relationResult);
+ when(titanGenericDao.createNode((HeatParameterData) anyObject(), eq(HeatParameterData.class))).thenReturn(either);
+ when(titanGenericDao.createRelation((GraphNode) anyObject(), (GraphNode) anyObject(), eq(GraphEdgeLabels.HEAT_PARAMETER), anyMap())).thenReturn(relationResult);
- Either<HeatParameterData, TitanOperationStatus> result = heatParametersOperation.addPropertyToGraph(propName,
- property, "resourceId.artifactId", NodeTypeEnum.ArtifactRef);
+ Either<HeatParameterData, TitanOperationStatus> result = heatParametersOperation.addPropertyToGraph(propName, property, "resourceId.artifactId", NodeTypeEnum.ArtifactRef);
assertTrue(result.isLeft());
@@ -103,13 +100,10 @@ public class HeatParametersOperationTest extends ModelTestBase {
GraphRelation graphRelation = new GraphRelation();
Either<GraphRelation, TitanOperationStatus> relationResult = Either.left(graphRelation);
- when(titanGenericDao.createNode((HeatParameterData) anyObject(), eq(HeatParameterData.class)))
- .thenReturn(either);
- when(titanGenericDao.createRelation((GraphNode) anyObject(), (GraphNode) anyObject(),
- eq(GraphEdgeLabels.HEAT_PARAMETER), anyMap())).thenReturn(relationResult);
+ when(titanGenericDao.createNode((HeatParameterData) anyObject(), eq(HeatParameterData.class))).thenReturn(either);
+ when(titanGenericDao.createRelation((GraphNode) anyObject(), (GraphNode) anyObject(), eq(GraphEdgeLabels.HEAT_PARAMETER), anyMap())).thenReturn(relationResult);
- StorageOperationStatus result = heatParametersOperation.addPropertiesToGraph(parameters,
- "resourceId.artifactId", NodeTypeEnum.ArtifactRef);
+ StorageOperationStatus result = heatParametersOperation.addPropertiesToGraph(parameters, "resourceId.artifactId", NodeTypeEnum.ArtifactRef);
assertEquals(StorageOperationStatus.OK, result);
@@ -133,8 +127,7 @@ public class HeatParametersOperationTest extends ModelTestBase {
@Test
public void testJsonValues() {
assertTrue(heatParametersOperation.isValidValue(HeatParameterType.JSON, "{ \"member\" : \"50\"}"));
- HeatParameterDefinition propertyDefinition = buildHeatBooleanPropertyDefinition(
- HeatParameterType.JSON.getType(), "{ \"member\" : \"50\"}");
+ HeatParameterDefinition propertyDefinition = buildHeatBooleanPropertyDefinition(HeatParameterType.JSON.getType(), "{ \"member\" : \"50\"}");
StorageOperationStatus operationStatus = heatParametersOperation.validateAndUpdateProperty(propertyDefinition);
assertEquals(StorageOperationStatus.OK, operationStatus);
assertEquals(HeatParameterType.JSON.getType(), propertyDefinition.getType());
@@ -144,8 +137,7 @@ public class HeatParametersOperationTest extends ModelTestBase {
@Test
public void testListValues() {
assertTrue(heatParametersOperation.isValidValue(HeatParameterType.COMMA_DELIMITED_LIST, "one, two"));
- HeatParameterDefinition propertyDefinition = buildHeatBooleanPropertyDefinition(
- HeatParameterType.COMMA_DELIMITED_LIST.getType(), "one, two");
+ HeatParameterDefinition propertyDefinition = buildHeatBooleanPropertyDefinition(HeatParameterType.COMMA_DELIMITED_LIST.getType(), "one, two");
StorageOperationStatus operationStatus = heatParametersOperation.validateAndUpdateProperty(propertyDefinition);
assertEquals(StorageOperationStatus.OK, operationStatus);
assertEquals(HeatParameterType.COMMA_DELIMITED_LIST.getType(), propertyDefinition.getType());
@@ -160,23 +152,19 @@ public class HeatParametersOperationTest extends ModelTestBase {
for (int i = 0; i < trueArray.length; i++) {
assertTrue(heatParametersOperation.isValidValue(HeatParameterType.BOOLEAN, trueArray[i]));
- HeatParameterDefinition propertyDefinition = buildHeatBooleanPropertyDefinition(
- HeatParameterType.BOOLEAN.getType(), trueArray[i]);
- StorageOperationStatus operationStatus = heatParametersOperation
- .validateAndUpdateProperty(propertyDefinition);
+ HeatParameterDefinition propertyDefinition = buildHeatBooleanPropertyDefinition(HeatParameterType.BOOLEAN.getType(), trueArray[i]);
+ StorageOperationStatus operationStatus = heatParametersOperation.validateAndUpdateProperty(propertyDefinition);
assertEquals(StorageOperationStatus.OK, operationStatus);
assertEquals("true", propertyDefinition.getDefaultValue());
assertTrue(heatParametersOperation.isValidValue(HeatParameterType.BOOLEAN, trueArray[i]));
- propertyDefinition = buildHeatBooleanPropertyDefinition(HeatParameterType.BOOLEAN.getType(),
- trueArray[i].toUpperCase());
+ propertyDefinition = buildHeatBooleanPropertyDefinition(HeatParameterType.BOOLEAN.getType(), trueArray[i].toUpperCase());
operationStatus = heatParametersOperation.validateAndUpdateProperty(propertyDefinition);
assertEquals(StorageOperationStatus.OK, operationStatus);
assertEquals("true", propertyDefinition.getDefaultValue());
assertTrue(heatParametersOperation.isValidValue(HeatParameterType.BOOLEAN, trueArray[i]));
- propertyDefinition = buildHeatBooleanPropertyDefinition(HeatParameterType.BOOLEAN.getType(),
- trueArray[i].toLowerCase());
+ propertyDefinition = buildHeatBooleanPropertyDefinition(HeatParameterType.BOOLEAN.getType(), trueArray[i].toLowerCase());
operationStatus = heatParametersOperation.validateAndUpdateProperty(propertyDefinition);
assertEquals(StorageOperationStatus.OK, operationStatus);
assertEquals("true", propertyDefinition.getDefaultValue());
@@ -184,23 +172,19 @@ public class HeatParametersOperationTest extends ModelTestBase {
for (int i = 0; i < falseArray.length; i++) {
assertTrue(heatParametersOperation.isValidValue(HeatParameterType.BOOLEAN, falseArray[i]));
- HeatParameterDefinition propertyDefinition = buildHeatBooleanPropertyDefinition(
- HeatParameterType.BOOLEAN.getType(), falseArray[i]);
- StorageOperationStatus operationStatus = heatParametersOperation
- .validateAndUpdateProperty(propertyDefinition);
+ HeatParameterDefinition propertyDefinition = buildHeatBooleanPropertyDefinition(HeatParameterType.BOOLEAN.getType(), falseArray[i]);
+ StorageOperationStatus operationStatus = heatParametersOperation.validateAndUpdateProperty(propertyDefinition);
assertEquals(StorageOperationStatus.OK, operationStatus);
assertEquals("false", propertyDefinition.getDefaultValue());
assertTrue(heatParametersOperation.isValidValue(HeatParameterType.BOOLEAN, falseArray[i]));
- propertyDefinition = buildHeatBooleanPropertyDefinition(HeatParameterType.BOOLEAN.getType(),
- falseArray[i].toUpperCase());
+ propertyDefinition = buildHeatBooleanPropertyDefinition(HeatParameterType.BOOLEAN.getType(), falseArray[i].toUpperCase());
operationStatus = heatParametersOperation.validateAndUpdateProperty(propertyDefinition);
assertEquals(StorageOperationStatus.OK, operationStatus);
assertEquals("false", propertyDefinition.getDefaultValue());
assertTrue(heatParametersOperation.isValidValue(HeatParameterType.BOOLEAN, falseArray[i]));
- propertyDefinition = buildHeatBooleanPropertyDefinition(HeatParameterType.BOOLEAN.getType(),
- falseArray[i].toLowerCase());
+ propertyDefinition = buildHeatBooleanPropertyDefinition(HeatParameterType.BOOLEAN.getType(), falseArray[i].toLowerCase());
operationStatus = heatParametersOperation.validateAndUpdateProperty(propertyDefinition);
assertEquals(StorageOperationStatus.OK, operationStatus);
assertEquals("false", propertyDefinition.getDefaultValue());
@@ -272,15 +256,11 @@ public class HeatParametersOperationTest extends ModelTestBase {
GraphRelation graphRelation = new GraphRelation();
Either<GraphRelation, TitanOperationStatus> relationResult = Either.left(graphRelation);
- when(titanGenericDao.createNode((HeatParameterValueData) anyObject(), eq(HeatParameterValueData.class)))
- .thenReturn(either);
- when(titanGenericDao.createRelation((GraphNode) anyObject(), (GraphNode) anyObject(),
- eq(GraphEdgeLabels.PARAMETER_VALUE), anyMap())).thenReturn(relationResult);
- when(titanGenericDao.createRelation((GraphNode) anyObject(), (GraphNode) anyObject(),
- eq(GraphEdgeLabels.PARAMETER_IMPL), anyMap())).thenReturn(relationResult);
+ when(titanGenericDao.createNode((HeatParameterValueData) anyObject(), eq(HeatParameterValueData.class))).thenReturn(either);
+ when(titanGenericDao.createRelation((GraphNode) anyObject(), (GraphNode) anyObject(), eq(GraphEdgeLabels.PARAMETER_VALUE), anyMap())).thenReturn(relationResult);
+ when(titanGenericDao.createRelation((GraphNode) anyObject(), (GraphNode) anyObject(), eq(GraphEdgeLabels.PARAMETER_IMPL), anyMap())).thenReturn(relationResult);
- Either<HeatParameterValueData, TitanOperationStatus> result = heatParametersOperation
- .addHeatValueToGraph(property, "artifactLabel", "resourceInstanceId.artifactId", "resourceInstanceId");
+ Either<HeatParameterValueData, TitanOperationStatus> result = heatParametersOperation.addHeatValueToGraph(property, "artifactLabel", "resourceInstanceId.artifactId", "resourceInstanceId");
assertTrue(result.isLeft());
diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/InterfaceOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/InterfaceOperationTest.java
index e1eb7db070..759fd2b811 100644
--- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/InterfaceOperationTest.java
+++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/InterfaceOperationTest.java
@@ -31,6 +31,7 @@ import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
@@ -42,6 +43,10 @@ import org.openecomp.sdc.be.model.ModelTestBase;
import org.openecomp.sdc.be.model.Operation;
import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
+import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
+import org.openecomp.sdc.be.model.operations.impl.ResourceOperation;
+import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
import org.openecomp.sdc.be.model.operations.impl.util.OperationTestsUtil;
import org.openecomp.sdc.be.resources.data.ResourceMetadataData;
import org.openecomp.sdc.be.resources.data.UserData;
@@ -61,7 +66,7 @@ public class InterfaceOperationTest {
private static Logger log = LoggerFactory.getLogger(InterfaceOperationTest.class.getName());
private Gson prettyGson = new GsonBuilder().setPrettyPrinting().create();
- private static String USER_ID = "muserId";
+ private static String USER_ID = "muUserId";
private static String CATEGORY_NAME = "category/mycategory";
// InterfaceLifecycleOperation interfaceOperation = new
// InterfaceLifecycleOperation();
@@ -107,7 +112,7 @@ public class InterfaceOperationTest {
}
- @Test
+/* @Test
public void addInterfaceToResourceTest() {
String capabilityTypeName = "mycapability1";
@@ -122,8 +127,7 @@ public class InterfaceOperationTest {
ResourceOperationTest resourceOperationTest = new ResourceOperationTest();
resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation);
- Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "100.0", null,
- true, true);
+ Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "100.0", null, true, true);
String interfaceName = "standard";
InterfaceDefinition interfaceDefinition = buildInterfaceDefinition();
@@ -133,14 +137,12 @@ public class InterfaceOperationTest {
operations.put("Create", op);
interfaceDefinition.setOperations(operations);
- Either<InterfaceDefinition, StorageOperationStatus> result = interfaceOperation
- .addInterfaceToResource(interfaceDefinition, rootResource.getUniqueId(), "standard");
+ Either<InterfaceDefinition, StorageOperationStatus> result = interfaceOperation.addInterfaceToResource(interfaceDefinition, rootResource.getUniqueId(), "standard");
assertTrue(result.isLeft());
log.debug("{}", result.left().value());
- Either<Resource, StorageOperationStatus> getResourceRes = resourceOperation
- .getResource(rootResource.getUniqueId());
+ Either<Resource, StorageOperationStatus> getResourceRes = resourceOperation.getResource(rootResource.getUniqueId());
assertTrue(getResourceRes.isLeft());
Resource resourceWithInterface = getResourceRes.left().value();
Map<String, InterfaceDefinition> interfaces = resourceWithInterface.getInterfaces();
@@ -162,8 +164,7 @@ public class InterfaceOperationTest {
ResourceOperationTest resourceOperationTest = new ResourceOperationTest();
resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation);
- Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "200.0", null,
- true, true);
+ Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "200.0", null, true, true);
String interfaceName = "standard";
InterfaceDefinition interfaceDefinition = buildInterfaceDefinition();
@@ -173,25 +174,21 @@ public class InterfaceOperationTest {
operations.put("create", op);
interfaceDefinition.setOperations(operations);
- Either<InterfaceDefinition, StorageOperationStatus> result = interfaceOperation
- .addInterfaceToResource(interfaceDefinition, rootResource.getUniqueId(), "standard");
+ Either<InterfaceDefinition, StorageOperationStatus> result = interfaceOperation.addInterfaceToResource(interfaceDefinition, rootResource.getUniqueId(), "standard");
ResourceMetadataData resourceData = new ResourceMetadataData();
resourceData.getMetadataDataDefinition().setUniqueId(rootResource.getUniqueId());
resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name());
- Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanDao.updateNode(resourceData,
- ResourceMetadataData.class);
+ Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class);
assertTrue(updateNode.isLeft());
- Either<Resource, StorageOperationStatus> fetchRootResource = resourceOperation
- .getResource(rootResource.getUniqueId());
+ Either<Resource, StorageOperationStatus> fetchRootResource = resourceOperation.getResource(rootResource.getUniqueId());
assertTrue(fetchRootResource.isLeft());
String rootResourceJson = prettyGson.toJson(fetchRootResource.left().value());
log.debug(rootResourceJson);
- Resource softwareComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, softwareCompName,
- "400.0", rootResource.getName(), true, true);
+ Resource softwareComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, softwareCompName, "400.0", rootResource.getName(), true, true);
assertTrue(result.isLeft());
log.debug("{}", result.left().value());
@@ -200,15 +197,13 @@ public class InterfaceOperationTest {
// String resourceId, String interfaceName, String
// operationName,Operation interf
- Either<Operation, StorageOperationStatus> opResult = interfaceOperation
- .updateInterfaceOperation(softwareComponent.getUniqueId(), "standard", "create", op);
+ Either<Operation, StorageOperationStatus> opResult = interfaceOperation.updateInterfaceOperation(softwareComponent.getUniqueId(), "standard", "create", op);
// PrintGraph pg = new PrintGraph();
// System.out.println(pg.buildGraphForWebgraphWiz(titanDao.getGraph().left().value()));
assertTrue(opResult.isLeft());
log.debug("{}", opResult.left().value());
- Either<Resource, StorageOperationStatus> getResourceRes = resourceOperation
- .getResource(softwareComponent.getUniqueId());
+ Either<Resource, StorageOperationStatus> getResourceRes = resourceOperation.getResource(softwareComponent.getUniqueId());
assertTrue(getResourceRes.isLeft());
Resource resourceWithInterface = getResourceRes.left().value();
Map<String, InterfaceDefinition> interfaces = resourceWithInterface.getInterfaces();
@@ -221,7 +216,7 @@ public class InterfaceOperationTest {
assertNotNull(operation);
assertNotNull(operation.getImplementation());
}
-
+*/
private void addImplementationToOperation(Operation op) {
ArtifactDataDefinition artifactDataDef = new ArtifactDataDefinition();
artifactDataDef.setArtifactChecksum("YTg2Mjg4MWJhNmI5NzBiNzdDFkMWI=");
@@ -254,6 +249,13 @@ public class InterfaceOperationTest {
private void deleteAndCreateCategory(String category) {
String[] names = category.split("/");
OperationTestsUtil.deleteAndCreateResourceCategory(names[0], names[1], titanDao);
+
+ /*
+ * CategoryData categoryData = new CategoryData(); categoryData.setName(category);
+ *
+ * titanDao.deleteNode(categoryData, CategoryData.class); Either<CategoryData, TitanOperationStatus> createNode = titanDao .createNode(categoryData, CategoryData.class); System.out.println("after creating caetgory " + createNode);
+ */
+
}
private UserData deleteAndCreateUser(String userId, String firstName, String lastName) {
diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/LifecycleOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/LifecycleOperationTest.java
index 2b090f6f9f..23090fe143 100644
--- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/LifecycleOperationTest.java
+++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/LifecycleOperationTest.java
@@ -34,6 +34,7 @@ import java.util.Map;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
+import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
@@ -107,7 +108,7 @@ public class LifecycleOperationTest extends ModelTestBase {
private static final String CAPABILITY_NAME = "capName";
- private static final String USER_ID = "muserId";
+ private static final String USER_ID = "muUserId";
@javax.annotation.Resource
private TitanGenericDao titanGenericDao;
@@ -177,24 +178,19 @@ public class LifecycleOperationTest extends ModelTestBase {
@Before
public void setupBefore() {
clearGraph();
- UserData modifierData = deleteAndCreateUser(ResourceCreationUtils.MODIFIER_ATT_UID + "co",
- ResourceCreationUtils.MODIFIER_FIRST_NAME, ResourceCreationUtils.MODIFIER_LAST_NAME, "ADMIN");
+ UserData modifierData = deleteAndCreateUser(ResourceCreationUtils.MODIFIER_ATT_UID + "co", ResourceCreationUtils.MODIFIER_FIRST_NAME, ResourceCreationUtils.MODIFIER_LAST_NAME, "ADMIN");
checkoutUser = convertUserDataToUser(modifierData);
- modifierData = deleteAndCreateUser(ResourceCreationUtils.MODIFIER_ATT_UID + "ci",
- ResourceCreationUtils.MODIFIER_FIRST_NAME, ResourceCreationUtils.MODIFIER_LAST_NAME, "ADMIN");
+ modifierData = deleteAndCreateUser(ResourceCreationUtils.MODIFIER_ATT_UID + "ci", ResourceCreationUtils.MODIFIER_FIRST_NAME, ResourceCreationUtils.MODIFIER_LAST_NAME, "ADMIN");
checkinUser = convertUserDataToUser(modifierData);
- modifierData = deleteAndCreateUser(ResourceCreationUtils.MODIFIER_ATT_UID + "rfc",
- ResourceCreationUtils.MODIFIER_FIRST_NAME, ResourceCreationUtils.MODIFIER_LAST_NAME, "ADMIN");
+ modifierData = deleteAndCreateUser(ResourceCreationUtils.MODIFIER_ATT_UID + "rfc", ResourceCreationUtils.MODIFIER_FIRST_NAME, ResourceCreationUtils.MODIFIER_LAST_NAME, "ADMIN");
rfcUser = convertUserDataToUser(modifierData);
- modifierData = deleteAndCreateUser(ResourceCreationUtils.MODIFIER_ATT_UID + "tester",
- ResourceCreationUtils.MODIFIER_FIRST_NAME, ResourceCreationUtils.MODIFIER_LAST_NAME, "TESTER");
+ modifierData = deleteAndCreateUser(ResourceCreationUtils.MODIFIER_ATT_UID + "tester", ResourceCreationUtils.MODIFIER_FIRST_NAME, ResourceCreationUtils.MODIFIER_LAST_NAME, "TESTER");
testerUser = convertUserDataToUser(modifierData);
- modifierData = deleteAndCreateUser(ResourceCreationUtils.MODIFIER_ATT_UID + "admin",
- ResourceCreationUtils.MODIFIER_FIRST_NAME, ResourceCreationUtils.MODIFIER_LAST_NAME, "ADMIN");
+ modifierData = deleteAndCreateUser(ResourceCreationUtils.MODIFIER_ATT_UID + "admin", ResourceCreationUtils.MODIFIER_FIRST_NAME, ResourceCreationUtils.MODIFIER_LAST_NAME, "ADMIN");
adminUser = convertUserDataToUser(modifierData);
modifierData = deleteAndCreateUser(USER_ID, "first_" + USER_ID, "last_" + USER_ID, "ADMIN");
@@ -229,13 +225,12 @@ public class LifecycleOperationTest extends ModelTestBase {
}
@Test
+ @Ignore
public void getOwnerTest() {
- Resource resultResource = createTestResource(checkoutUser.getUserId(), "0.1",
- LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, null);
+ Resource resultResource = createTestResource(checkoutUser.getUserId(), "0.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, null);
- Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation
- .getComponentOwner(resultResource.getUniqueId(), NodeTypeEnum.Resource, false);
+ Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(resultResource.getUniqueId(), NodeTypeEnum.Resource, false);
assertEquals("check user object is returned", true, getOwnerResponse.isLeft());
User resourceOwner = getOwnerResponse.left().value();
@@ -246,6 +241,7 @@ public class LifecycleOperationTest extends ModelTestBase {
/*********************** CHECKOUT ***************************************************************/
@Test
+ @Ignore
public void checkoutCertifiedTest() {
Resource resultResource = createTestResource(adminUser.getUserId(), "1.0", LifecycleStateEnum.CERTIFIED, null);
@@ -253,15 +249,13 @@ public class LifecycleOperationTest extends ModelTestBase {
Either<Resource, StorageOperationStatus> origResourceResult = resourceOperation.getResource(origUniqueId);
Resource origResource = origResourceResult.left().value();
- Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId,
- NodeTypeEnum.Resource, false);
+ Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, NodeTypeEnum.Resource, false);
assertEquals("check user object is returned", true, getOwnerResponse.isLeft());
User resourceOwner = getOwnerResponse.left().value();
// checkout
- Either<Resource, StorageOperationStatus> checkoutResponse = (Either<Resource, StorageOperationStatus>) lifecycleOperation
- .checkoutComponent(NodeTypeEnum.Resource, resultResource, checkoutUser, resourceOwner, false);
+ Either<Resource, StorageOperationStatus> checkoutResponse = (Either<Resource, StorageOperationStatus>) lifecycleOperation.checkoutComponent(NodeTypeEnum.Resource, resultResource, checkoutUser, resourceOwner, false);
assertEquals("check resource object is returned", true, checkoutResponse.isLeft());
Resource checkoutResource = checkoutResponse.left().value();
@@ -271,8 +265,7 @@ public class LifecycleOperationTest extends ModelTestBase {
assertEquals(checkoutResource.getLastUpdaterUserId(), checkoutUser.getUserId());
// assert owner changed
- Either<User, StorageOperationStatus> getOwnerCheckoutResponse = lifecycleOperation
- .getComponentOwner(checkoutResource.getUniqueId(), NodeTypeEnum.Resource, false);
+ Either<User, StorageOperationStatus> getOwnerCheckoutResponse = lifecycleOperation.getComponentOwner(checkoutResource.getUniqueId(), NodeTypeEnum.Resource, false);
assertEquals("check user object is returned", true, getOwnerCheckoutResponse.isLeft());
resourceOwner = getOwnerCheckoutResponse.left().value();
assertTrue(resourceOwner.equals(checkoutUser));
@@ -285,21 +278,19 @@ public class LifecycleOperationTest extends ModelTestBase {
}
@Test
+ @Ignore
public void checkoutDefaultTest() {
- Resource resultResource = createTestResource(checkinUser.getUserId(), "0.1",
- LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null);
+ Resource resultResource = createTestResource(checkinUser.getUserId(), "0.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null);
String origUniqueId = resultResource.getUniqueId();
- Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId,
- NodeTypeEnum.Resource, false);
+ Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, NodeTypeEnum.Resource, false);
assertEquals("check user object is returned", true, getOwnerResponse.isLeft());
User resourceOwner = getOwnerResponse.left().value();
// checkout
- Either<Resource, StorageOperationStatus> checkoutResponse = (Either<Resource, StorageOperationStatus>) lifecycleOperation
- .checkoutComponent(NodeTypeEnum.Resource, resultResource, checkoutUser, resourceOwner, false);
+ Either<Resource, StorageOperationStatus> checkoutResponse = (Either<Resource, StorageOperationStatus>) lifecycleOperation.checkoutComponent(NodeTypeEnum.Resource, resultResource, checkoutUser, resourceOwner, false);
assertEquals("check resource object is returned", true, checkoutResponse.isLeft());
Resource checkoutResource = checkoutResponse.left().value();
@@ -310,8 +301,7 @@ public class LifecycleOperationTest extends ModelTestBase {
assertEquals(checkoutResource.isHighestVersion(), true);
// assert owner changed
- Either<User, StorageOperationStatus> getOwnerCheckoutResponse = lifecycleOperation
- .getComponentOwner(checkoutResource.getUniqueId(), NodeTypeEnum.Resource, false);
+ Either<User, StorageOperationStatus> getOwnerCheckoutResponse = lifecycleOperation.getComponentOwner(checkoutResource.getUniqueId(), NodeTypeEnum.Resource, false);
assertEquals("check user object is returned", true, getOwnerCheckoutResponse.isLeft());
resourceOwner = getOwnerCheckoutResponse.left().value();
assertTrue(resourceOwner.equals(checkoutUser));
@@ -321,26 +311,23 @@ public class LifecycleOperationTest extends ModelTestBase {
assertEquals("check resource created", true, getOrigResource.isLeft());
// assertEquals("assert original resource not changed", origResource,
// getOrigResource.left().value());
- assertEquals("assert original resource not highest version", false,
- getOrigResource.left().value().isHighestVersion());
+ assertEquals("assert original resource not highest version", false, getOrigResource.left().value().isHighestVersion());
}
@Test
+ @Ignore
public void checkoutFullResourceTest() {
- Resource origResource = createFullTestResource(checkinUser.getUserId(), "0.1",
- LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
+ Resource origResource = createFullTestResource(checkinUser.getUserId(), "0.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
String origUniqueId = origResource.getUniqueId();
- Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId,
- NodeTypeEnum.Resource, false);
+ Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, NodeTypeEnum.Resource, false);
assertEquals("check user object is returned", true, getOwnerResponse.isLeft());
User resourceOwner = getOwnerResponse.left().value();
// checkout
- Either<Resource, StorageOperationStatus> checkoutResponse = (Either<Resource, StorageOperationStatus>) lifecycleOperation
- .checkoutComponent(NodeTypeEnum.Resource, origResource, checkoutUser, resourceOwner, false);
+ Either<Resource, StorageOperationStatus> checkoutResponse = (Either<Resource, StorageOperationStatus>) lifecycleOperation.checkoutComponent(NodeTypeEnum.Resource, origResource, checkoutUser, resourceOwner, false);
assertEquals("check resource object is returned", true, checkoutResponse.isLeft());
Resource checkoutResource = checkoutResponse.left().value();
@@ -357,7 +344,7 @@ public class LifecycleOperationTest extends ModelTestBase {
Map<String, InterfaceDefinition> interfaces = checkoutResource.getInterfaces();
assertTrue(interfaces.containsKey(INTERFACE_NAME));
InterfaceDefinition interfaceDef = interfaces.get(INTERFACE_NAME);
- Map<String, Operation> operations = interfaceDef.getOperations();
+ Map<String, Operation> operations = interfaceDef.getOperationsMap();
assertNotNull(operations);
assertFalse(operations.isEmpty());
assertTrue(operations.containsKey(INTERFACE_OPERATION_CREATE));
@@ -365,8 +352,7 @@ public class LifecycleOperationTest extends ModelTestBase {
assertNotNull(op.getImplementation());
// assert owner changed
- Either<User, StorageOperationStatus> getOwnerCheckoutResponse = lifecycleOperation
- .getComponentOwner(checkoutResource.getUniqueId(), NodeTypeEnum.Resource, false);
+ Either<User, StorageOperationStatus> getOwnerCheckoutResponse = lifecycleOperation.getComponentOwner(checkoutResource.getUniqueId(), NodeTypeEnum.Resource, false);
assertEquals("check user object is returned", true, getOwnerCheckoutResponse.isLeft());
resourceOwner = getOwnerCheckoutResponse.left().value();
assertTrue(resourceOwner.equals(checkoutUser));
@@ -376,11 +362,11 @@ public class LifecycleOperationTest extends ModelTestBase {
assertEquals("check resource created", true, getOrigResource.isLeft());
// assertEquals("assert original resource not changed", origResource,
// getOrigResource.left().value());
- assertEquals("assert original resource not highest version", false,
- getOrigResource.left().value().isHighestVersion());
+ assertEquals("assert original resource not highest version", false, getOrigResource.left().value().isHighestVersion());
}
@Test
+ @Ignore
public void getResourceOwnerResourceNotExistTest() {
// create resource metadata
@@ -393,8 +379,7 @@ public class LifecycleOperationTest extends ModelTestBase {
// get resource owner
- Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner("my-resource.0.1",
- NodeTypeEnum.Resource, false);
+ Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner("my-resource.0.1", NodeTypeEnum.Resource, false);
assertEquals("assert no owner", true, getOwnerResponse.isRight());
StorageOperationStatus status = getOwnerResponse.right().value();
@@ -404,6 +389,7 @@ public class LifecycleOperationTest extends ModelTestBase {
}
@Test
+ @Ignore
public void checkoutResourceTwice() {
Resource resultResource = createTestResource(adminUser.getUserId(), "1.0", LifecycleStateEnum.CERTIFIED, null);
@@ -411,20 +397,17 @@ public class LifecycleOperationTest extends ModelTestBase {
Either<Resource, StorageOperationStatus> origResourceResult = resourceOperation.getResource(origUniqueId);
Resource origResource = origResourceResult.left().value();
- Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId,
- NodeTypeEnum.Resource, false);
+ Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, NodeTypeEnum.Resource, false);
assertEquals("check user object is returned", true, getOwnerResponse.isLeft());
User resourceOwner = getOwnerResponse.left().value();
// first checkout
- Either<Resource, StorageOperationStatus> checkoutResponse1 = (Either<Resource, StorageOperationStatus>) lifecycleOperation
- .checkoutComponent(NodeTypeEnum.Resource, resultResource, checkoutUser, resourceOwner, false);
+ Either<Resource, StorageOperationStatus> checkoutResponse1 = (Either<Resource, StorageOperationStatus>) lifecycleOperation.checkoutComponent(NodeTypeEnum.Resource, resultResource, checkoutUser, resourceOwner, false);
assertEquals("check resource object is returned", true, checkoutResponse1.isLeft());
// second checkout
- Either<Resource, StorageOperationStatus> checkoutResponse2 = (Either<Resource, StorageOperationStatus>) lifecycleOperation
- .checkoutComponent(NodeTypeEnum.Resource, origResource, checkoutUser, resourceOwner, false);
+ Either<Resource, StorageOperationStatus> checkoutResponse2 = (Either<Resource, StorageOperationStatus>) lifecycleOperation.checkoutComponent(NodeTypeEnum.Resource, origResource, checkoutUser, resourceOwner, false);
assertEquals("check checkout failed", true, checkoutResponse2.isRight());
assertEquals(StorageOperationStatus.ENTITY_ALREADY_EXISTS, checkoutResponse2.right().value());
@@ -434,19 +417,16 @@ public class LifecycleOperationTest extends ModelTestBase {
@Test
public void checkoutServiceDefaultTest() {
- Service resultResource = createTestService(checkinUser.getUserId(), "0.1",
- LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null);
+ Service resultResource = createTestService(checkinUser.getUserId(), "0.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null);
String origUniqueId = resultResource.getUniqueId();
- Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId,
- NodeTypeEnum.Service, false);
+ Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, NodeTypeEnum.Service, false);
assertEquals("check user object is returned", true, getOwnerResponse.isLeft());
User resourceOwner = getOwnerResponse.left().value();
// checkout
- Either<? extends Component, StorageOperationStatus> checkoutResponse = lifecycleOperation
- .checkoutComponent(NodeTypeEnum.Service, resultResource, checkoutUser, resourceOwner, false);
+ Either<? extends Component, StorageOperationStatus> checkoutResponse = lifecycleOperation.checkoutComponent(NodeTypeEnum.Service, resultResource, checkoutUser, resourceOwner, false);
assertEquals("check resource object is returned", true, checkoutResponse.isLeft());
Component checkoutResource = checkoutResponse.left().value();
@@ -457,8 +437,7 @@ public class LifecycleOperationTest extends ModelTestBase {
assertEquals(checkoutResource.isHighestVersion(), true);
// assert owner changed
- Either<User, StorageOperationStatus> getOwnerCheckoutResponse = lifecycleOperation
- .getComponentOwner(checkoutResource.getUniqueId(), NodeTypeEnum.Service, false);
+ Either<User, StorageOperationStatus> getOwnerCheckoutResponse = lifecycleOperation.getComponentOwner(checkoutResource.getUniqueId(), NodeTypeEnum.Service, false);
assertEquals("check user object is returned", true, getOwnerCheckoutResponse.isLeft());
resourceOwner = getOwnerCheckoutResponse.left().value();
assertTrue(resourceOwner.equals(checkoutUser));
@@ -468,15 +447,14 @@ public class LifecycleOperationTest extends ModelTestBase {
assertEquals("check resource created", true, getOrigResource.isLeft());
// assertEquals("assert original resource not changed", origResource,
// getOrigResource.left().value());
- assertEquals("assert original resource not highest version", false,
- getOrigResource.left().value().isHighestVersion());
+ assertEquals("assert original resource not highest version", false, getOrigResource.left().value().isHighestVersion());
}
@Test
+ @Ignore
public void checkoutFullServiceTest() {
- Service origService = createTestService(checkinUser.getUserId(), "0.1",
- LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null);
+ Service origService = createTestService(checkinUser.getUserId(), "0.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null);
String origUniqueId = origService.getUniqueId();
// add artifacts
@@ -485,12 +463,10 @@ public class LifecycleOperationTest extends ModelTestBase {
// add resource instances
ResourceInstanceOperationTest riTest = new ResourceInstanceOperationTest();
- riTest.setOperations(titanGenericDao, capabilityTypeOperation, requirementOperation, capabilityOperation,
- resourceOperation, propertyOperation, resourceInstanceOperation);
+ riTest.setOperations(titanGenericDao, capabilityTypeOperation, requirementOperation, capabilityOperation, resourceOperation, propertyOperation, resourceInstanceOperation);
riTest.addResourceInstancesAndRelation(origService.getUniqueId());
- Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId,
- NodeTypeEnum.Service, false);
+ Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, NodeTypeEnum.Service, false);
assertEquals("check user object is returned", true, getOwnerResponse.isLeft());
User resourceOwner = getOwnerResponse.left().value();
@@ -500,8 +476,7 @@ public class LifecycleOperationTest extends ModelTestBase {
origService = serviceBeforeCheckout.left().value();
// checkout
- Either<? extends Component, StorageOperationStatus> checkoutResponse = lifecycleOperation
- .checkoutComponent(NodeTypeEnum.Service, origService, checkoutUser, resourceOwner, false);
+ Either<? extends Component, StorageOperationStatus> checkoutResponse = lifecycleOperation.checkoutComponent(NodeTypeEnum.Service, origService, checkoutUser, resourceOwner, false);
assertEquals("check resource object is returned", true, checkoutResponse.isLeft());
Service checkoutResource = (Service) checkoutResponse.left().value();
@@ -519,8 +494,7 @@ public class LifecycleOperationTest extends ModelTestBase {
assertFalse(checkoutResource.getComponentInstancesRelations().isEmpty());
// assert owner changed
- Either<User, StorageOperationStatus> getOwnerCheckoutResponse = lifecycleOperation
- .getComponentOwner(checkoutResource.getUniqueId(), NodeTypeEnum.Service, false);
+ Either<User, StorageOperationStatus> getOwnerCheckoutResponse = lifecycleOperation.getComponentOwner(checkoutResource.getUniqueId(), NodeTypeEnum.Service, false);
assertEquals("check user object is returned", true, getOwnerCheckoutResponse.isLeft());
resourceOwner = getOwnerCheckoutResponse.left().value();
assertTrue(resourceOwner.equals(checkoutUser));
@@ -530,11 +504,11 @@ public class LifecycleOperationTest extends ModelTestBase {
assertEquals("check service created", true, getOrigResource.isLeft());
// assertEquals("assert original resource not changed", origResource,
// getOrigResource.left().value());
- assertEquals("assert original service not highest version", false,
- getOrigResource.left().value().isHighestVersion());
+ assertEquals("assert original service not highest version", false, getOrigResource.left().value().isHighestVersion());
}
@Test
+ @Ignore
public void checkoutServiceTwice() {
Service resultResource = createTestService(adminUser.getUserId(), "1.0", LifecycleStateEnum.CERTIFIED, null);
@@ -542,20 +516,17 @@ public class LifecycleOperationTest extends ModelTestBase {
Either<Service, StorageOperationStatus> origResourceResult = serviceOperation.getService(origUniqueId);
Service origResource = origResourceResult.left().value();
- Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId,
- NodeTypeEnum.Service, false);
+ Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, NodeTypeEnum.Service, false);
assertEquals("check user object is returned", true, getOwnerResponse.isLeft());
User resourceOwner = getOwnerResponse.left().value();
// first checkout
- Either<? extends Component, StorageOperationStatus> checkoutResponse1 = lifecycleOperation
- .checkoutComponent(NodeTypeEnum.Service, resultResource, checkoutUser, resourceOwner, false);
+ Either<? extends Component, StorageOperationStatus> checkoutResponse1 = lifecycleOperation.checkoutComponent(NodeTypeEnum.Service, resultResource, checkoutUser, resourceOwner, false);
assertEquals("check resource object is returned", true, checkoutResponse1.isLeft());
// second checkout
- Either<? extends Component, StorageOperationStatus> checkoutResponse2 = lifecycleOperation
- .checkoutComponent(NodeTypeEnum.Service, origResource, checkoutUser, resourceOwner, false);
+ Either<? extends Component, StorageOperationStatus> checkoutResponse2 = lifecycleOperation.checkoutComponent(NodeTypeEnum.Service, origResource, checkoutUser, resourceOwner, false);
assertEquals("check checkout failed", true, checkoutResponse2.isRight());
assertEquals(StorageOperationStatus.ENTITY_ALREADY_EXISTS, checkoutResponse2.right().value());
@@ -564,21 +535,19 @@ public class LifecycleOperationTest extends ModelTestBase {
/**************************** CHECKIN ********************************************************************/
@Test
+ @Ignore
public void checkinDefaultTest() {
- Resource resultResource = createTestResource(adminUser.getUserId(), "0.1",
- LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, null);
+ Resource resultResource = createTestResource(adminUser.getUserId(), "0.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, null);
String origUniqueId = resultResource.getUniqueId();
- Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId,
- NodeTypeEnum.Resource, false);
+ Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, NodeTypeEnum.Resource, false);
assertEquals("check user object is returned", true, getOwnerResponse.isLeft());
User resourceOwner = getOwnerResponse.left().value();
// checkin
- Either<Resource, StorageOperationStatus> checkinResponse = (Either<Resource, StorageOperationStatus>) lifecycleOperation
- .checkinComponent(NodeTypeEnum.Resource, resultResource, checkinUser, resourceOwner, false);
+ Either<Resource, StorageOperationStatus> checkinResponse = (Either<Resource, StorageOperationStatus>) lifecycleOperation.checkinComponent(NodeTypeEnum.Resource, resultResource, checkinUser, resourceOwner, false);
assertEquals("check resource object is returned", true, checkinResponse.isLeft());
Resource checkinResource = checkinResponse.left().value();
@@ -588,8 +557,7 @@ public class LifecycleOperationTest extends ModelTestBase {
assertEquals(checkinResource.getLastUpdaterUserId(), checkinUser.getUserId());
// assert owner changed
- Either<User, StorageOperationStatus> getOwnerCheckoutResponse = lifecycleOperation
- .getComponentOwner(checkinResource.getUniqueId(), NodeTypeEnum.Resource, false);
+ Either<User, StorageOperationStatus> getOwnerCheckoutResponse = lifecycleOperation.getComponentOwner(checkinResource.getUniqueId(), NodeTypeEnum.Resource, false);
assertEquals("check user object is returned", true, getOwnerCheckoutResponse.isLeft());
resourceOwner = getOwnerCheckoutResponse.left().value();
assertTrue(resourceOwner.equals(checkinUser));
@@ -597,32 +565,27 @@ public class LifecycleOperationTest extends ModelTestBase {
}
@Test
+ @Ignore
public void checkinFromRfcTest() {
- Resource resultResource = createTestResource(adminUser.getUserId(), "0.1",
- LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, null);
+ Resource resultResource = createTestResource(adminUser.getUserId(), "0.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, null);
String origUniqueId = resultResource.getUniqueId();
- Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId,
- NodeTypeEnum.Resource, false);
+ Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, NodeTypeEnum.Resource, false);
assertEquals("check user object is returned", true, getOwnerResponse.isLeft());
User resourceOwner = getOwnerResponse.left().value();
// checkin
- Either<Resource, StorageOperationStatus> checkinResponse = (Either<Resource, StorageOperationStatus>) lifecycleOperation
- .checkinComponent(NodeTypeEnum.Resource, resultResource, checkinUser, resourceOwner, false);
+ Either<Resource, StorageOperationStatus> checkinResponse = (Either<Resource, StorageOperationStatus>) lifecycleOperation.checkinComponent(NodeTypeEnum.Resource, resultResource, checkinUser, resourceOwner, false);
assertEquals("check resource object is returned", true, checkinResponse.isLeft());
// rfc
- Either<Resource, StorageOperationStatus> rfcResponse = (Either<Resource, StorageOperationStatus>) lifecycleOperation
- .requestCertificationComponent(NodeTypeEnum.Resource, checkinResponse.left().value(), rfcUser,
- checkinUser, false);
+ Either<Resource, StorageOperationStatus> rfcResponse = (Either<Resource, StorageOperationStatus>) lifecycleOperation.requestCertificationComponent(NodeTypeEnum.Resource, checkinResponse.left().value(), rfcUser, checkinUser, false);
assertEquals("check resource object is returned", true, checkinResponse.isLeft());
// checkin (cancel rfc)
- checkinResponse = (Either<Resource, StorageOperationStatus>) lifecycleOperation
- .checkinComponent(NodeTypeEnum.Resource, rfcResponse.left().value(), checkinUser, rfcUser, false);
+ checkinResponse = (Either<Resource, StorageOperationStatus>) lifecycleOperation.checkinComponent(NodeTypeEnum.Resource, rfcResponse.left().value(), checkinUser, rfcUser, false);
assertEquals("check resource object is returned", true, checkinResponse.isLeft());
resultResource = checkinResponse.left().value();
@@ -632,8 +595,7 @@ public class LifecycleOperationTest extends ModelTestBase {
assertEquals(resultResource.getLastUpdaterUserId(), checkinUser.getUserId());
// assert owner changed
- Either<User, StorageOperationStatus> getOwnerCheckoutResponse = lifecycleOperation
- .getComponentOwner(resultResource.getUniqueId(), NodeTypeEnum.Resource, false);
+ Either<User, StorageOperationStatus> getOwnerCheckoutResponse = lifecycleOperation.getComponentOwner(resultResource.getUniqueId(), NodeTypeEnum.Resource, false);
assertEquals("check user object is returned", true, getOwnerCheckoutResponse.isLeft());
resourceOwner = getOwnerCheckoutResponse.left().value();
assertTrue(resourceOwner.equals(checkinUser));
@@ -644,13 +606,11 @@ public class LifecycleOperationTest extends ModelTestBase {
Map<String, Object> props = new HashMap<String, Object>();
props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION);
- Either<GraphRelation, TitanOperationStatus> incomingRelationByCriteria = titanGenericDao
- .getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props);
+ Either<GraphRelation, TitanOperationStatus> incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props);
assertTrue(incomingRelationByCriteria.isRight());
props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
- incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE,
- props);
+ incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props);
assertTrue(incomingRelationByCriteria.isLeft());
assertEquals(checkinUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue());
@@ -658,21 +618,19 @@ public class LifecycleOperationTest extends ModelTestBase {
/*** SERVICE */
@Test
+ @Ignore
public void checkinServiceDefaultTest() {
- Service resultService = createTestService(adminUser.getUserId(), "0.1",
- LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, null);
+ Service resultService = createTestService(adminUser.getUserId(), "0.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, null);
String origUniqueId = resultService.getUniqueId();
- Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId,
- NodeTypeEnum.Service, false);
+ Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, NodeTypeEnum.Service, false);
assertEquals("check user object is returned", true, getOwnerResponse.isLeft());
User resourceOwner = getOwnerResponse.left().value();
// checkin
- Either<? extends Component, StorageOperationStatus> checkinResponse = lifecycleOperation
- .checkinComponent(NodeTypeEnum.Service, resultService, checkinUser, resourceOwner, false);
+ Either<? extends Component, StorageOperationStatus> checkinResponse = lifecycleOperation.checkinComponent(NodeTypeEnum.Service, resultService, checkinUser, resourceOwner, false);
assertEquals("check service object is returned", true, checkinResponse.isLeft());
Service checkinResource = (Service) checkinResponse.left().value();
@@ -682,8 +640,7 @@ public class LifecycleOperationTest extends ModelTestBase {
assertEquals(checkinResource.getLastUpdaterUserId(), checkinUser.getUserId());
// assert owner changed
- Either<User, StorageOperationStatus> getOwnerCheckoutResponse = lifecycleOperation
- .getComponentOwner(checkinResource.getUniqueId(), NodeTypeEnum.Service, false);
+ Either<User, StorageOperationStatus> getOwnerCheckoutResponse = lifecycleOperation.getComponentOwner(checkinResource.getUniqueId(), NodeTypeEnum.Service, false);
assertEquals("check user object is returned", true, getOwnerCheckoutResponse.isLeft());
resourceOwner = getOwnerCheckoutResponse.left().value();
assertTrue(resourceOwner.equals(checkinUser));
@@ -691,32 +648,27 @@ public class LifecycleOperationTest extends ModelTestBase {
}
@Test
+ @Ignore
public void checkinServiceFromRfcTest() {
- Service resultResource = createTestService(adminUser.getUserId(), "0.1",
- LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, null);
+ Service resultResource = createTestService(adminUser.getUserId(), "0.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, null);
String origUniqueId = resultResource.getUniqueId();
- Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId,
- NodeTypeEnum.Service, false);
+ Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, NodeTypeEnum.Service, false);
assertEquals("check user object is returned", true, getOwnerResponse.isLeft());
User resourceOwner = getOwnerResponse.left().value();
// checkin
- Either<? extends Component, StorageOperationStatus> checkinResponse = lifecycleOperation
- .checkinComponent(NodeTypeEnum.Service, resultResource, checkinUser, resourceOwner, false);
+ Either<? extends Component, StorageOperationStatus> checkinResponse = lifecycleOperation.checkinComponent(NodeTypeEnum.Service, resultResource, checkinUser, resourceOwner, false);
assertEquals("check service object is returned", true, checkinResponse.isLeft());
// rfc
- Either<? extends Component, StorageOperationStatus> rfcResponse = lifecycleOperation
- .requestCertificationComponent(NodeTypeEnum.Service, checkinResponse.left().value(), rfcUser,
- checkinUser, false);
+ Either<? extends Component, StorageOperationStatus> rfcResponse = lifecycleOperation.requestCertificationComponent(NodeTypeEnum.Service, checkinResponse.left().value(), rfcUser, checkinUser, false);
assertEquals("check service object is returned", true, checkinResponse.isLeft());
// checkin (cancel rfc)
- checkinResponse = lifecycleOperation.checkinComponent(NodeTypeEnum.Service, rfcResponse.left().value(),
- checkinUser, rfcUser, false);
+ checkinResponse = lifecycleOperation.checkinComponent(NodeTypeEnum.Service, rfcResponse.left().value(), checkinUser, rfcUser, false);
assertEquals("check resource object is returned", true, checkinResponse.isLeft());
resultResource = (Service) checkinResponse.left().value();
@@ -726,8 +678,7 @@ public class LifecycleOperationTest extends ModelTestBase {
assertEquals(resultResource.getLastUpdaterUserId(), checkinUser.getUserId());
// assert owner changed
- Either<User, StorageOperationStatus> getOwnerCheckoutResponse = lifecycleOperation
- .getComponentOwner(resultResource.getUniqueId(), NodeTypeEnum.Service, false);
+ Either<User, StorageOperationStatus> getOwnerCheckoutResponse = lifecycleOperation.getComponentOwner(resultResource.getUniqueId(), NodeTypeEnum.Service, false);
assertEquals("check user object is returned", true, getOwnerCheckoutResponse.isLeft());
resourceOwner = getOwnerCheckoutResponse.left().value();
assertTrue(resourceOwner.equals(checkinUser));
@@ -739,13 +690,11 @@ public class LifecycleOperationTest extends ModelTestBase {
Map<String, Object> props = new HashMap<String, Object>();
props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION);
- Either<GraphRelation, TitanOperationStatus> incomingRelationByCriteria = titanGenericDao
- .getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props);
+ Either<GraphRelation, TitanOperationStatus> incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props);
assertTrue(incomingRelationByCriteria.isRight());
props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
- incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE,
- props);
+ incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props);
assertTrue(incomingRelationByCriteria.isLeft());
assertEquals(checkinUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue());
@@ -756,14 +705,13 @@ public class LifecycleOperationTest extends ModelTestBase {
********************************************************************/
@Test
+ @Ignore
public void undoCheckoutNewResourceTest() {
- Resource resultResource = createTestResource(adminUser.getUserId(), "0.1",
- LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, null);
+ Resource resultResource = createTestResource(adminUser.getUserId(), "0.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, null);
String origUniqueId = resultResource.getUniqueId();
- Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId,
- NodeTypeEnum.Resource, false);
+ Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, NodeTypeEnum.Resource, false);
assertEquals("check user object is returned", true, getOwnerResponse.isLeft());
User resourceOwner = getOwnerResponse.left().value();
@@ -771,94 +719,81 @@ public class LifecycleOperationTest extends ModelTestBase {
//
// undo checkout
- Either<Resource, StorageOperationStatus> undoCheckoutResponse = (Either<Resource, StorageOperationStatus>) lifecycleOperation
- .undoCheckout(NodeTypeEnum.Resource, resultResource, adminUser, resourceOwner, false);
+ Either<Resource, StorageOperationStatus> undoCheckoutResponse = (Either<Resource, StorageOperationStatus>) lifecycleOperation.undoCheckout(NodeTypeEnum.Resource, resultResource, adminUser, resourceOwner, false);
assertEquals("check resource object is returned", true, undoCheckoutResponse.isLeft());
Either<Resource, StorageOperationStatus> origResourceResult = resourceOperation.getResource(origUniqueId);
assertTrue(origResourceResult.isRight());
/*
- * assertTrue(origResourceResult.isLeft());
- * assertTrue(origResourceResult.left().value().getIsDeleted() == true);
+ * assertTrue(origResourceResult.isLeft()); assertTrue(origResourceResult.left().value().getIsDeleted() == true);
*/
}
@Test
+ @Ignore
public void undoCheckoutNewFullResourceTest() {
- Resource resultResource = createFullTestResource(adminUser.getUserId(), "0.1",
- LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ Resource resultResource = createFullTestResource(adminUser.getUserId(), "0.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
String origUniqueId = resultResource.getUniqueId();
- Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId,
- NodeTypeEnum.Resource, false);
+ Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, NodeTypeEnum.Resource, false);
assertEquals("check user object is returned", true, getOwnerResponse.isLeft());
User resourceOwner = getOwnerResponse.left().value();
// undo checkout
- Either<Resource, StorageOperationStatus> undoCheckoutResponse = (Either<Resource, StorageOperationStatus>) lifecycleOperation
- .undoCheckout(NodeTypeEnum.Resource, resultResource, adminUser, resourceOwner, false);
+ Either<Resource, StorageOperationStatus> undoCheckoutResponse = (Either<Resource, StorageOperationStatus>) lifecycleOperation.undoCheckout(NodeTypeEnum.Resource, resultResource, adminUser, resourceOwner, false);
assertEquals("check resource object is returned", true, undoCheckoutResponse.isLeft());
Either<Resource, StorageOperationStatus> origResourceResult = resourceOperation.getResource(origUniqueId);
/*
- * assertTrue(origResourceResult.isLeft());
- * assertTrue(origResourceResult.left().value().getIsDeleted() == true);
+ * assertTrue(origResourceResult.isLeft()); assertTrue(origResourceResult.left().value().getIsDeleted() == true);
*/ assertTrue(origResourceResult.isRight());
String interfaceId = origUniqueId + "." + INTERFACE_NAME;
- Either<InterfaceData, TitanOperationStatus> node = titanGenericDao
- .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Interface), interfaceId, InterfaceData.class);
+ Either<InterfaceData, TitanOperationStatus> node = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Interface), interfaceId, InterfaceData.class);
assertTrue(node.isRight());
String operationId = interfaceId + "." + INTERFACE_OPERATION_CREATE;
- Either<OperationData, TitanOperationStatus> op = titanGenericDao.getNode(
- UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.InterfaceOperation), operationId, OperationData.class);
+ Either<OperationData, TitanOperationStatus> op = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.InterfaceOperation), operationId, OperationData.class);
assertTrue(op.isRight());
String capabilityId = "capability." + origUniqueId + "." + CAPABILITY_NAME;
- Either<CapabilityData, TitanOperationStatus> capability = titanGenericDao
- .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Capability), capabilityId, CapabilityData.class);
+ Either<CapabilityData, TitanOperationStatus> capability = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Capability), capabilityId, CapabilityData.class);
assertTrue(capability.isRight());
String requirementId = origUniqueId + "." + REQUIREMENT_NAME;
- Either<RequirementData, TitanOperationStatus> req = titanGenericDao.getNode(
- UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Requirement), requirementId, RequirementData.class);
+ Either<RequirementData, TitanOperationStatus> req = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Requirement), requirementId, RequirementData.class);
assertTrue(req.isRight());
}
@Test
+ @Ignore
public void undoCheckoutExistingResourceTest() {
- Resource resultResource = createTestResource(adminUser.getUserId(), "0.1",
- LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null);
+ Resource resultResource = createTestResource(adminUser.getUserId(), "0.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null);
// get resource owner
- Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation
- .getComponentOwner(resultResource.getUniqueId(), NodeTypeEnum.Resource, false);
+ Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(resultResource.getUniqueId(), NodeTypeEnum.Resource, false);
assertEquals("check user object is returned", true, getOwnerResponse.isLeft());
User resourceOwner = getOwnerResponse.left().value();
String prevResourceId = resultResource.getUniqueId();
- Either<Resource, StorageOperationStatus> result2 = (Either<Resource, StorageOperationStatus>) lifecycleOperation
- .checkoutComponent(NodeTypeEnum.Resource, resultResource, checkoutUser, resourceOwner, false);
+ Either<Resource, StorageOperationStatus> result2 = (Either<Resource, StorageOperationStatus>) lifecycleOperation.checkoutComponent(NodeTypeEnum.Resource, resultResource, checkoutUser, resourceOwner, false);
assertEquals("check resource created", true, result2.isLeft());
Resource resultResource2 = result2.left().value();
// get resource owner
- getOwnerResponse = lifecycleOperation.getComponentOwner(resultResource2.getUniqueId(), NodeTypeEnum.Resource,
- false);
+ getOwnerResponse = lifecycleOperation.getComponentOwner(resultResource2.getUniqueId(), NodeTypeEnum.Resource, false);
assertEquals("check user object is returned", true, getOwnerResponse.isLeft());
resourceOwner = getOwnerResponse.left().value();
assertEquals(resourceOwner, checkoutUser);
// undo checkout
- Either<Resource, StorageOperationStatus> undoCheckoutResponse = (Either<Resource, StorageOperationStatus>) lifecycleOperation
- .undoCheckout(NodeTypeEnum.Resource, resultResource2, checkoutUser, resourceOwner, false);
+ Either<Resource, StorageOperationStatus> undoCheckoutResponse = (Either<Resource, StorageOperationStatus>) lifecycleOperation.undoCheckout(NodeTypeEnum.Resource, resultResource2, checkoutUser, resourceOwner, false);
assertEquals("check resource object is returned", true, undoCheckoutResponse.isLeft());
// get previous resource
@@ -871,25 +806,22 @@ public class LifecycleOperationTest extends ModelTestBase {
assertEquals("0.1", actualResource.getVersion());
assertEquals(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, actualResource.getLifecycleState());
- Either<Resource, StorageOperationStatus> origResourceResult = resourceOperation
- .getResource(resultResource2.getUniqueId());
+ Either<Resource, StorageOperationStatus> origResourceResult = resourceOperation.getResource(resultResource2.getUniqueId());
/*
- * assertTrue(origResourceResult.isLeft());
- * assertTrue(origResourceResult.left().value().getIsDeleted() == true);
+ * assertTrue(origResourceResult.isLeft()); assertTrue(origResourceResult.left().value().getIsDeleted() == true);
*/ assertTrue(origResourceResult.isRight());
}
/**** SERVICE ***/
@Test
+ @Ignore
public void undoCheckoutNewServiceTest() {
- Service resultResource = createTestService(adminUser.getUserId(), "0.1",
- LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, null);
+ Service resultResource = createTestService(adminUser.getUserId(), "0.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, null);
String origUniqueId = resultResource.getUniqueId();
- Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId,
- NodeTypeEnum.Service, false);
+ Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, NodeTypeEnum.Service, false);
assertEquals("check user object is returned", true, getOwnerResponse.isLeft());
User resourceOwner = getOwnerResponse.left().value();
@@ -897,23 +829,21 @@ public class LifecycleOperationTest extends ModelTestBase {
//
// undo checkout
- Either<? extends Component, StorageOperationStatus> undoCheckoutResponse = lifecycleOperation
- .undoCheckout(NodeTypeEnum.Service, resultResource, adminUser, resourceOwner, false);
+ Either<? extends Component, StorageOperationStatus> undoCheckoutResponse = lifecycleOperation.undoCheckout(NodeTypeEnum.Service, resultResource, adminUser, resourceOwner, false);
assertEquals("check resource object is returned", true, undoCheckoutResponse.isLeft());
Either<Service, StorageOperationStatus> origResourceResult = serviceOperation.getService(origUniqueId);
/*
- * assertTrue(origResourceResult.isLeft());
- * assertTrue(origResourceResult.left().value().getIsDeleted() == true);
+ * assertTrue(origResourceResult.isLeft()); assertTrue(origResourceResult.left().value().getIsDeleted() == true);
*/ assertTrue(origResourceResult.isRight());
}
@Test
+ @Ignore
public void undoCheckoutNewFullServiceTest() {
- Service origService = createTestService(checkinUser.getUserId(), "0.1",
- LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null);
+ Service origService = createTestService(checkinUser.getUserId(), "0.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null);
String origUniqueId = origService.getUniqueId();
// add artifacts
@@ -922,12 +852,10 @@ public class LifecycleOperationTest extends ModelTestBase {
// add resource instances
ResourceInstanceOperationTest riTest = new ResourceInstanceOperationTest();
- riTest.setOperations(titanGenericDao, capabilityTypeOperation, requirementOperation, capabilityOperation,
- resourceOperation, propertyOperation, resourceInstanceOperation);
+ riTest.setOperations(titanGenericDao, capabilityTypeOperation, requirementOperation, capabilityOperation, resourceOperation, propertyOperation, resourceInstanceOperation);
riTest.addResourceInstancesAndRelation(origService.getUniqueId());
- Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId,
- NodeTypeEnum.Resource, false);
+ Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, NodeTypeEnum.Resource, false);
assertEquals("check user object is returned", true, getOwnerResponse.isLeft());
User resourceOwner = getOwnerResponse.left().value();
@@ -939,56 +867,48 @@ public class LifecycleOperationTest extends ModelTestBase {
List<ComponentInstance> resourceInstances = resultResource.getComponentInstances();
// undo checkout
- Either<? extends Component, StorageOperationStatus> undoCheckoutResponse = lifecycleOperation
- .undoCheckout(NodeTypeEnum.Service, resultResource, adminUser, resourceOwner, false);
+ Either<? extends Component, StorageOperationStatus> undoCheckoutResponse = lifecycleOperation.undoCheckout(NodeTypeEnum.Service, resultResource, adminUser, resourceOwner, false);
assertEquals("check resource object is returned", true, undoCheckoutResponse.isLeft());
Either<Service, StorageOperationStatus> origResourceResult = serviceOperation.getService(origUniqueId);
/*
- * assertTrue(origResourceResult.isLeft());
- * assertTrue(origResourceResult.left().value().getIsDeleted() == true);
+ * assertTrue(origResourceResult.isLeft()); assertTrue(origResourceResult.left().value().getIsDeleted() == true);
*/ assertTrue(origResourceResult.isRight());
for (ComponentInstance ri : resourceInstances) {
- Either<ComponentInstanceData, TitanOperationStatus> node = titanGenericDao.getNode(
- UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), ri.getUniqueId(),
- ComponentInstanceData.class);
+ Either<ComponentInstanceData, TitanOperationStatus> node = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), ri.getUniqueId(), ComponentInstanceData.class);
assertTrue(node.isRight());
}
}
@Test
+ @Ignore
public void undoCheckoutExistingServiceTest() {
- Service resultResource = createTestService(adminUser.getUserId(), "0.1",
- LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null);
+ Service resultResource = createTestService(adminUser.getUserId(), "0.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null);
// get resource owner
- Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation
- .getComponentOwner(resultResource.getUniqueId(), NodeTypeEnum.Resource, false);
+ Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(resultResource.getUniqueId(), NodeTypeEnum.Resource, false);
assertEquals("check user object is returned", true, getOwnerResponse.isLeft());
User resourceOwner = getOwnerResponse.left().value();
String prevResourceId = resultResource.getUniqueId();
- Either<? extends Component, StorageOperationStatus> result2 = lifecycleOperation
- .checkoutComponent(NodeTypeEnum.Service, resultResource, checkoutUser, resourceOwner, false);
+ Either<? extends Component, StorageOperationStatus> result2 = lifecycleOperation.checkoutComponent(NodeTypeEnum.Service, resultResource, checkoutUser, resourceOwner, false);
assertEquals("check resource created", true, result2.isLeft());
Component resultResource2 = result2.left().value();
String result2Uid = resultResource.getUniqueId();
// get resource owner
- getOwnerResponse = lifecycleOperation.getComponentOwner(resultResource2.getUniqueId(), NodeTypeEnum.Resource,
- false);
+ getOwnerResponse = lifecycleOperation.getComponentOwner(resultResource2.getUniqueId(), NodeTypeEnum.Resource, false);
assertEquals("check user object is returned", true, getOwnerResponse.isLeft());
resourceOwner = getOwnerResponse.left().value();
assertEquals(resourceOwner, checkoutUser);
// undo checkout
- Either<? extends Component, StorageOperationStatus> undoCheckoutResponse = lifecycleOperation
- .undoCheckout(NodeTypeEnum.Service, resultResource2, checkoutUser, resourceOwner, false);
+ Either<? extends Component, StorageOperationStatus> undoCheckoutResponse = lifecycleOperation.undoCheckout(NodeTypeEnum.Service, resultResource2, checkoutUser, resourceOwner, false);
assertEquals("check resource object is returned", true, undoCheckoutResponse.isLeft());
// get previous resource
@@ -1003,8 +923,7 @@ public class LifecycleOperationTest extends ModelTestBase {
Either<Service, StorageOperationStatus> origResourceResult = serviceOperation.getService(result2Uid);
/*
- * assertTrue(origResourceResult.isLeft());
- * assertTrue(origResourceResult.left().value().getIsDeleted() == true);
+ * assertTrue(origResourceResult.isLeft()); assertTrue(origResourceResult.left().value().getIsDeleted() == true);
*/ assertTrue(origResourceResult.isRight());
}
@@ -1014,6 +933,7 @@ public class LifecycleOperationTest extends ModelTestBase {
********************************************************************/
@Test
+ @Ignore
public void certReqDefaultTest() {
Resource actualResource = testCertificationRequest(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
@@ -1023,20 +943,19 @@ public class LifecycleOperationTest extends ModelTestBase {
Map<String, Object> props = new HashMap<String, Object>();
props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION);
- Either<GraphRelation, TitanOperationStatus> incomingRelationByCriteria = titanGenericDao
- .getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props);
+ Either<GraphRelation, TitanOperationStatus> incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props);
assertTrue(incomingRelationByCriteria.isLeft());
assertEquals(rfcUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue());
props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
- incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData,
- GraphEdgeLabels.LAST_STATE, props);
+ incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.LAST_STATE, props);
assertTrue(incomingRelationByCriteria.isLeft());
assertEquals(adminUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue());
}
@Test
+ @Ignore
public void atomicCheckinCertReqTest() {
Resource actualResource = testCertificationRequest(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
@@ -1046,14 +965,12 @@ public class LifecycleOperationTest extends ModelTestBase {
Map<String, Object> props = new HashMap<String, Object>();
props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION);
- Either<GraphRelation, TitanOperationStatus> incomingRelationByCriteria = titanGenericDao
- .getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props);
+ Either<GraphRelation, TitanOperationStatus> incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props);
assertTrue(incomingRelationByCriteria.isLeft());
assertEquals(rfcUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue());
props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
- incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData,
- GraphEdgeLabels.LAST_STATE, props);
+ incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.LAST_STATE, props);
assertTrue(incomingRelationByCriteria.isLeft());
assertEquals(rfcUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue());
}
@@ -1063,15 +980,13 @@ public class LifecycleOperationTest extends ModelTestBase {
Resource resultResource = createTestResource(adminUser.getUserId(), "0.1", preState, null);
String origUniqueId = resultResource.getUniqueId();
- Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId,
- NodeTypeEnum.Resource, false);
+ Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, NodeTypeEnum.Resource, false);
assertEquals("check user object is returned", true, getOwnerResponse.isLeft());
User resourceOwner = getOwnerResponse.left().value();
// checkin
- Either<Resource, StorageOperationStatus> certReqResponse = (Either<Resource, StorageOperationStatus>) lifecycleOperation
- .requestCertificationComponent(NodeTypeEnum.Resource, resultResource, rfcUser, resourceOwner, false);
+ Either<Resource, StorageOperationStatus> certReqResponse = (Either<Resource, StorageOperationStatus>) lifecycleOperation.requestCertificationComponent(NodeTypeEnum.Resource, resultResource, rfcUser, resourceOwner, false);
assertEquals("check resource object is returned", true, certReqResponse.isLeft());
Resource resourceAfterChange = certReqResponse.left().value();
@@ -1081,8 +996,7 @@ public class LifecycleOperationTest extends ModelTestBase {
assertEquals(resourceAfterChange.getLastUpdaterUserId(), rfcUser.getUserId());
// assert owner changed
- Either<User, StorageOperationStatus> getOwnerCheckoutResponse = lifecycleOperation
- .getComponentOwner(resourceAfterChange.getUniqueId(), NodeTypeEnum.Resource, false);
+ Either<User, StorageOperationStatus> getOwnerCheckoutResponse = lifecycleOperation.getComponentOwner(resourceAfterChange.getUniqueId(), NodeTypeEnum.Resource, false);
assertEquals("check user object is returned", true, getOwnerCheckoutResponse.isLeft());
resourceOwner = getOwnerCheckoutResponse.left().value();
assertTrue(resourceOwner.equals(rfcUser));
@@ -1092,6 +1006,7 @@ public class LifecycleOperationTest extends ModelTestBase {
/** SERVICE **/
@Test
+ @Ignore
public void certServiceReqDefaultTest() {
Service actualResource = testServiceCertificationRequest(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
@@ -1102,20 +1017,19 @@ public class LifecycleOperationTest extends ModelTestBase {
Map<String, Object> props = new HashMap<String, Object>();
props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION);
- Either<GraphRelation, TitanOperationStatus> incomingRelationByCriteria = titanGenericDao
- .getIncomingRelationByCriteria(serviceData, GraphEdgeLabels.STATE, props);
+ Either<GraphRelation, TitanOperationStatus> incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(serviceData, GraphEdgeLabels.STATE, props);
assertTrue(incomingRelationByCriteria.isLeft());
assertEquals(rfcUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue());
props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
- incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(serviceData,
- GraphEdgeLabels.LAST_STATE, props);
+ incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(serviceData, GraphEdgeLabels.LAST_STATE, props);
assertTrue(incomingRelationByCriteria.isLeft());
assertEquals(adminUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue());
}
@Test
+ @Ignore
public void atomicServiceCheckinCertReqTest() {
Service actualResource = testServiceCertificationRequest(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
@@ -1126,14 +1040,12 @@ public class LifecycleOperationTest extends ModelTestBase {
Map<String, Object> props = new HashMap<String, Object>();
props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION);
- Either<GraphRelation, TitanOperationStatus> incomingRelationByCriteria = titanGenericDao
- .getIncomingRelationByCriteria(serviceData, GraphEdgeLabels.STATE, props);
+ Either<GraphRelation, TitanOperationStatus> incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(serviceData, GraphEdgeLabels.STATE, props);
assertTrue(incomingRelationByCriteria.isLeft());
assertEquals(rfcUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue());
props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
- incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(serviceData,
- GraphEdgeLabels.LAST_STATE, props);
+ incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(serviceData, GraphEdgeLabels.LAST_STATE, props);
assertTrue(incomingRelationByCriteria.isLeft());
assertEquals(rfcUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue());
}
@@ -1143,15 +1055,13 @@ public class LifecycleOperationTest extends ModelTestBase {
Service resultResource = createTestService(adminUser.getUserId(), "0.1", preState, null);
String origUniqueId = resultResource.getUniqueId();
- Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId,
- NodeTypeEnum.Service, false);
+ Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, NodeTypeEnum.Service, false);
assertEquals("check user object is returned", true, getOwnerResponse.isLeft());
User resourceOwner = getOwnerResponse.left().value();
// checkin
- Either<? extends Component, StorageOperationStatus> certReqResponse = lifecycleOperation
- .requestCertificationComponent(NodeTypeEnum.Service, resultResource, rfcUser, resourceOwner, false);
+ Either<? extends Component, StorageOperationStatus> certReqResponse = lifecycleOperation.requestCertificationComponent(NodeTypeEnum.Service, resultResource, rfcUser, resourceOwner, false);
assertEquals("check resource object is returned", true, certReqResponse.isLeft());
Service resourceAfterChange = (Service) certReqResponse.left().value();
@@ -1161,8 +1071,7 @@ public class LifecycleOperationTest extends ModelTestBase {
assertEquals(resourceAfterChange.getLastUpdaterUserId(), rfcUser.getUserId());
// assert owner changed
- Either<User, StorageOperationStatus> getOwnerCheckoutResponse = lifecycleOperation
- .getComponentOwner(resourceAfterChange.getUniqueId(), NodeTypeEnum.Service, false);
+ Either<User, StorageOperationStatus> getOwnerCheckoutResponse = lifecycleOperation.getComponentOwner(resourceAfterChange.getUniqueId(), NodeTypeEnum.Service, false);
assertEquals("check user object is returned", true, getOwnerCheckoutResponse.isLeft());
resourceOwner = getOwnerCheckoutResponse.left().value();
assertTrue(resourceOwner.equals(rfcUser));
@@ -1175,26 +1084,23 @@ public class LifecycleOperationTest extends ModelTestBase {
********************************************************************/
@Test
+ @Ignore
public void startCertificationTest() {
- Resource resultResource = createTestResource(checkinUser.getUserId(), "0.2",
- LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null);
+ Resource resultResource = createTestResource(checkinUser.getUserId(), "0.2", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null);
// certification request
- Either<Resource, StorageOperationStatus> requestCertificationResult = (Either<Resource, StorageOperationStatus>) lifecycleOperation
- .requestCertificationComponent(NodeTypeEnum.Resource, resultResource, rfcUser, checkinUser, false);
+ Either<Resource, StorageOperationStatus> requestCertificationResult = (Either<Resource, StorageOperationStatus>) lifecycleOperation.requestCertificationComponent(NodeTypeEnum.Resource, resultResource, rfcUser, checkinUser, false);
assertTrue(requestCertificationResult.isLeft());
// start certification
- Either<Resource, StorageOperationStatus> startCertificationResult = (Either<Resource, StorageOperationStatus>) lifecycleOperation
- .startComponentCertification(NodeTypeEnum.Resource, resultResource, testerUser, rfcUser, false);
+ Either<Resource, StorageOperationStatus> startCertificationResult = (Either<Resource, StorageOperationStatus>) lifecycleOperation.startComponentCertification(NodeTypeEnum.Resource, resultResource, testerUser, rfcUser, false);
assertEquals(true, startCertificationResult.isLeft());
Resource actualResource = startCertificationResult.left().value();
// get resource owner
- Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation
- .getComponentOwner(actualResource.getUniqueId(), NodeTypeEnum.Resource, false);
+ Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(actualResource.getUniqueId(), NodeTypeEnum.Resource, false);
assertEquals("check user object is returned", true, getOwnerResponse.isLeft());
User resourceOwner = getOwnerResponse.left().value();
@@ -1211,46 +1117,40 @@ public class LifecycleOperationTest extends ModelTestBase {
Map<String, Object> props = new HashMap<String, Object>();
props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
- Either<GraphRelation, TitanOperationStatus> incomingRelationByCriteria = titanGenericDao
- .getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props);
+ Either<GraphRelation, TitanOperationStatus> incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props);
assertTrue(incomingRelationByCriteria.isLeft());
assertEquals(testerUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue());
props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION);
- incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData,
- GraphEdgeLabels.LAST_STATE, props);
+ incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.LAST_STATE, props);
assertTrue(incomingRelationByCriteria.isLeft());
assertEquals(rfcUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue());
props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
- incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData,
- GraphEdgeLabels.LAST_STATE, props);
+ incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.LAST_STATE, props);
assertTrue(incomingRelationByCriteria.isLeft());
assertEquals(checkinUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue());
}
/** SERVICE */
@Test
+ @Ignore
public void startServiceCertificationTest() {
- Service resultResource = createTestService(checkinUser.getUserId(), "0.2",
- LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null);
+ Service resultResource = createTestService(checkinUser.getUserId(), "0.2", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null);
// certification request
- Either<? extends Component, StorageOperationStatus> requestCertificationResult = lifecycleOperation
- .requestCertificationComponent(NodeTypeEnum.Service, resultResource, rfcUser, checkinUser, false);
+ Either<? extends Component, StorageOperationStatus> requestCertificationResult = lifecycleOperation.requestCertificationComponent(NodeTypeEnum.Service, resultResource, rfcUser, checkinUser, false);
assertTrue(requestCertificationResult.isLeft());
// start certification
- Either<? extends Component, StorageOperationStatus> startCertificationResult = lifecycleOperation
- .startComponentCertification(NodeTypeEnum.Service, resultResource, testerUser, rfcUser, false);
+ Either<? extends Component, StorageOperationStatus> startCertificationResult = lifecycleOperation.startComponentCertification(NodeTypeEnum.Service, resultResource, testerUser, rfcUser, false);
assertEquals(true, startCertificationResult.isLeft());
Service actualResource = (Service) startCertificationResult.left().value();
// get resource owner
- Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation
- .getComponentOwner(actualResource.getUniqueId(), NodeTypeEnum.Service, false);
+ Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(actualResource.getUniqueId(), NodeTypeEnum.Service, false);
assertEquals("check user object is returned", true, getOwnerResponse.isLeft());
User resourceOwner = getOwnerResponse.left().value();
@@ -1268,20 +1168,17 @@ public class LifecycleOperationTest extends ModelTestBase {
Map<String, Object> props = new HashMap<String, Object>();
props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
- Either<GraphRelation, TitanOperationStatus> incomingRelationByCriteria = titanGenericDao
- .getIncomingRelationByCriteria(serviceData, GraphEdgeLabels.STATE, props);
+ Either<GraphRelation, TitanOperationStatus> incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(serviceData, GraphEdgeLabels.STATE, props);
assertTrue(incomingRelationByCriteria.isLeft());
assertEquals(testerUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue());
props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION);
- incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(serviceData,
- GraphEdgeLabels.LAST_STATE, props);
+ incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(serviceData, GraphEdgeLabels.LAST_STATE, props);
assertTrue(incomingRelationByCriteria.isLeft());
assertEquals(rfcUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue());
props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
- incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(serviceData,
- GraphEdgeLabels.LAST_STATE, props);
+ incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(serviceData, GraphEdgeLabels.LAST_STATE, props);
assertTrue(incomingRelationByCriteria.isLeft());
assertEquals(checkinUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue());
}
@@ -1291,6 +1188,7 @@ public class LifecycleOperationTest extends ModelTestBase {
********************************************************************/
@Test
+ @Ignore
public void failCertificationTest() {
Resource actualResource = certificationStatusChange(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, checkinUser);
@@ -1302,19 +1200,16 @@ public class LifecycleOperationTest extends ModelTestBase {
// old edges removed
props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
- Either<GraphRelation, TitanOperationStatus> incomingRelationByCriteria = titanGenericDao
- .getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props);
+ Either<GraphRelation, TitanOperationStatus> incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props);
assertTrue(incomingRelationByCriteria.isRight());
props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION);
- incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData,
- GraphEdgeLabels.LAST_STATE, props);
+ incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.LAST_STATE, props);
assertTrue(incomingRelationByCriteria.isRight());
// new state is checkin
props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
- incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE,
- props);
+ incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props);
assertTrue(incomingRelationByCriteria.isLeft());
assertEquals(checkinUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue());
}
@@ -1322,30 +1217,27 @@ public class LifecycleOperationTest extends ModelTestBase {
/*** SERVICE **/
@Test
+ @Ignore
public void failCertificationServiceTest() {
Service actualService = certificationStatusChangeService(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, checkinUser);
// assert relations
- ServiceMetadataData resourceData = new ServiceMetadataData((ServiceMetadataDataDefinition) actualService
- .getComponentMetadataDefinition().getMetadataDataDefinition());
+ ServiceMetadataData resourceData = new ServiceMetadataData((ServiceMetadataDataDefinition) actualService.getComponentMetadataDefinition().getMetadataDataDefinition());
Map<String, Object> props = new HashMap<String, Object>();
// old edges removed
props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
- Either<GraphRelation, TitanOperationStatus> incomingRelationByCriteria = titanGenericDao
- .getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props);
+ Either<GraphRelation, TitanOperationStatus> incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props);
assertTrue(incomingRelationByCriteria.isRight());
props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION);
- incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData,
- GraphEdgeLabels.LAST_STATE, props);
+ incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.LAST_STATE, props);
assertTrue(incomingRelationByCriteria.isRight());
// new state is checkin
props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
- incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE,
- props);
+ incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props);
assertTrue(incomingRelationByCriteria.isLeft());
assertEquals(checkinUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue());
}
@@ -1355,6 +1247,7 @@ public class LifecycleOperationTest extends ModelTestBase {
********************************************************************/
@Test
+ @Ignore
public void cancelCertificationTest() {
Resource actualResource = certificationStatusChange(LifecycleStateEnum.READY_FOR_CERTIFICATION, rfcUser);
@@ -1366,26 +1259,24 @@ public class LifecycleOperationTest extends ModelTestBase {
// old edges removed
props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
- Either<GraphRelation, TitanOperationStatus> incomingRelationByCriteria = titanGenericDao
- .getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props);
+ Either<GraphRelation, TitanOperationStatus> incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props);
assertTrue(incomingRelationByCriteria.isRight());
props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
- incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData,
- GraphEdgeLabels.LAST_STATE, props);
+ incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.LAST_STATE, props);
assertTrue(incomingRelationByCriteria.isLeft());
assertEquals(checkinUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue());
// new state is rfc
props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION);
- incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE,
- props);
+ incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props);
assertTrue(incomingRelationByCriteria.isLeft());
assertEquals(rfcUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue());
}
/** SERVICE **/
@Test
+ @Ignore
public void cancelCertificationServiceTest() {
Service actualService = certificationStatusChangeService(LifecycleStateEnum.READY_FOR_CERTIFICATION, rfcUser);
@@ -1397,20 +1288,17 @@ public class LifecycleOperationTest extends ModelTestBase {
// old edges removed
props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
- Either<GraphRelation, TitanOperationStatus> incomingRelationByCriteria = titanGenericDao
- .getIncomingRelationByCriteria(ServiceNode, GraphEdgeLabels.STATE, props);
+ Either<GraphRelation, TitanOperationStatus> incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(ServiceNode, GraphEdgeLabels.STATE, props);
assertTrue(incomingRelationByCriteria.isRight());
props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
- incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(ServiceNode,
- GraphEdgeLabels.LAST_STATE, props);
+ incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(ServiceNode, GraphEdgeLabels.LAST_STATE, props);
assertTrue(incomingRelationByCriteria.isLeft());
assertEquals(checkinUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue());
// new state is rfc
props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION);
- incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(ServiceNode, GraphEdgeLabels.STATE,
- props);
+ incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(ServiceNode, GraphEdgeLabels.STATE, props);
assertTrue(incomingRelationByCriteria.isLeft());
assertEquals(rfcUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue());
}
@@ -1418,32 +1306,28 @@ public class LifecycleOperationTest extends ModelTestBase {
/**************************** CERTIFY ********************************************************************/
@Test
+ @Ignore
public void certifyTest() {
- Resource resultResource = createTestResource(checkinUser.getUserId(), "0.2",
- LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null);
+ Resource resultResource = createTestResource(checkinUser.getUserId(), "0.2", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null);
// certification request
- Either<Resource, StorageOperationStatus> requestCertificationResult = (Either<Resource, StorageOperationStatus>) lifecycleOperation
- .requestCertificationComponent(NodeTypeEnum.Resource, resultResource, rfcUser, checkinUser, false);
+ Either<Resource, StorageOperationStatus> requestCertificationResult = (Either<Resource, StorageOperationStatus>) lifecycleOperation.requestCertificationComponent(NodeTypeEnum.Resource, resultResource, rfcUser, checkinUser, false);
assertTrue(requestCertificationResult.isLeft());
// start certification
- Either<Resource, StorageOperationStatus> startCertificationResult = (Either<Resource, StorageOperationStatus>) lifecycleOperation
- .startComponentCertification(NodeTypeEnum.Resource, resultResource, testerUser, rfcUser, false);
+ Either<Resource, StorageOperationStatus> startCertificationResult = (Either<Resource, StorageOperationStatus>) lifecycleOperation.startComponentCertification(NodeTypeEnum.Resource, resultResource, testerUser, rfcUser, false);
assertEquals(true, startCertificationResult.isLeft());
Resource actualResource = startCertificationResult.left().value();
// cancel certification
- Either<? extends Component, StorageOperationStatus> CertificationResult = lifecycleOperation
- .certifyComponent(NodeTypeEnum.Resource, actualResource, testerUser, testerUser, false);
+ Either<? extends Component, StorageOperationStatus> CertificationResult = lifecycleOperation.certifyComponent(NodeTypeEnum.Resource, actualResource, testerUser, testerUser, false);
assertEquals(true, CertificationResult.isLeft());
actualResource = (Resource) CertificationResult.left().value();
// get resource owner
- Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation
- .getComponentOwner(actualResource.getUniqueId(), NodeTypeEnum.Resource, false);
+ Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(actualResource.getUniqueId(), NodeTypeEnum.Resource, false);
assertEquals("check user object is returned", true, getOwnerResponse.isLeft());
User resourceOwner = getOwnerResponse.left().value();
@@ -1461,25 +1345,21 @@ public class LifecycleOperationTest extends ModelTestBase {
// old edges removed
props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
- Either<GraphRelation, TitanOperationStatus> incomingRelationByCriteria = titanGenericDao
- .getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props);
+ Either<GraphRelation, TitanOperationStatus> incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props);
assertTrue(incomingRelationByCriteria.isRight());
props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
- incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData,
- GraphEdgeLabels.LAST_STATE, props);
+ incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.LAST_STATE, props);
assertTrue(incomingRelationByCriteria.isRight());
// new state is certified
props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFIED);
- incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE,
- props);
+ incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props);
assertTrue(incomingRelationByCriteria.isLeft());
assertEquals(testerUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue());
props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION);
- incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData,
- GraphEdgeLabels.LAST_STATE, props);
+ incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.LAST_STATE, props);
assertTrue(incomingRelationByCriteria.isLeft());
assertEquals(rfcUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue());
@@ -1488,32 +1368,28 @@ public class LifecycleOperationTest extends ModelTestBase {
/******** SERVICE **/
@Test
+ @Ignore
public void certifyServiceTest() {
- Service resultService = createTestService(checkinUser.getUserId(), "0.2",
- LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null);
+ Service resultService = createTestService(checkinUser.getUserId(), "0.2", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null);
// certification request
- Either<? extends Component, StorageOperationStatus> requestCertificationResult = lifecycleOperation
- .requestCertificationComponent(NodeTypeEnum.Service, resultService, rfcUser, checkinUser, false);
+ Either<? extends Component, StorageOperationStatus> requestCertificationResult = lifecycleOperation.requestCertificationComponent(NodeTypeEnum.Service, resultService, rfcUser, checkinUser, false);
assertTrue(requestCertificationResult.isLeft());
// start certification
- Either<? extends Component, StorageOperationStatus> startCertificationResult = lifecycleOperation
- .startComponentCertification(NodeTypeEnum.Service, resultService, testerUser, rfcUser, false);
+ Either<? extends Component, StorageOperationStatus> startCertificationResult = lifecycleOperation.startComponentCertification(NodeTypeEnum.Service, resultService, testerUser, rfcUser, false);
assertEquals(true, startCertificationResult.isLeft());
Service actualService = (Service) startCertificationResult.left().value();
// cancel certification
- Either<? extends Component, StorageOperationStatus> CertificationResult = lifecycleOperation
- .certifyComponent(NodeTypeEnum.Service, actualService, testerUser, testerUser, false);
+ Either<? extends Component, StorageOperationStatus> CertificationResult = lifecycleOperation.certifyComponent(NodeTypeEnum.Service, actualService, testerUser, testerUser, false);
assertEquals(true, CertificationResult.isLeft());
actualService = (Service) CertificationResult.left().value();
// get resource owner
- Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation
- .getComponentOwner(actualService.getUniqueId(), NodeTypeEnum.Service, false);
+ Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(actualService.getUniqueId(), NodeTypeEnum.Service, false);
assertEquals("check user object is returned", true, getOwnerResponse.isLeft());
User resourceOwner = getOwnerResponse.left().value();
@@ -1531,52 +1407,42 @@ public class LifecycleOperationTest extends ModelTestBase {
// old edges removed
props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
- Either<GraphRelation, TitanOperationStatus> incomingRelationByCriteria = titanGenericDao
- .getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props);
+ Either<GraphRelation, TitanOperationStatus> incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props);
assertTrue(incomingRelationByCriteria.isRight());
props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
- incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData,
- GraphEdgeLabels.LAST_STATE, props);
+ incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.LAST_STATE, props);
assertTrue(incomingRelationByCriteria.isRight());
// new state is certified
props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFIED);
- incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE,
- props);
+ incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props);
assertTrue(incomingRelationByCriteria.isLeft());
assertEquals(testerUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue());
props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION);
- incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData,
- GraphEdgeLabels.LAST_STATE, props);
+ incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.LAST_STATE, props);
assertTrue(incomingRelationByCriteria.isLeft());
assertEquals(rfcUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue());
}
@Test
+ @Ignore
public void testDeleteOldVersionsResource() {
// simulate
createTestResource(checkinUser.getUserId(), "1.0", LifecycleStateEnum.CERTIFIED, null);
- Resource resourceNewVersion = createTestResource(checkinUser.getUserId(), "1.1",
- LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null);
- createTestResource(checkinUser.getUserId(), "1.2", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN,
- resourceNewVersion.getUUID());
- createTestResource(checkinUser.getUserId(), "1.3", LifecycleStateEnum.CERTIFICATION_IN_PROGRESS,
- resourceNewVersion.getUUID());
- Resource certifiedResource = createTestResource(checkinUser.getUserId(), "2.0", LifecycleStateEnum.CERTIFIED,
- resourceNewVersion.getUUID());
-
- Either<Boolean, StorageOperationStatus> deleteOldComponentVersions = lifecycleOperation
- .deleteOldComponentVersions(NodeTypeEnum.Resource, certifiedResource.getName(),
- certifiedResource.getUUID(), false);
+ Resource resourceNewVersion = createTestResource(checkinUser.getUserId(), "1.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null);
+ createTestResource(checkinUser.getUserId(), "1.2", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, resourceNewVersion.getUUID());
+ createTestResource(checkinUser.getUserId(), "1.3", LifecycleStateEnum.CERTIFICATION_IN_PROGRESS, resourceNewVersion.getUUID());
+ Resource certifiedResource = createTestResource(checkinUser.getUserId(), "2.0", LifecycleStateEnum.CERTIFIED, resourceNewVersion.getUUID());
+
+ Either<Boolean, StorageOperationStatus> deleteOldComponentVersions = lifecycleOperation.deleteOldComponentVersions(NodeTypeEnum.Resource, certifiedResource.getName(), certifiedResource.getUUID(), false);
assertTrue(deleteOldComponentVersions.isLeft());
String resourceName = certifiedResource.getName();
- Either<List<Resource>, StorageOperationStatus> resource = resourceOperation
- .getResourceByNameAndVersion(resourceName, "1.0", false);
+ Either<List<Resource>, StorageOperationStatus> resource = resourceOperation.getResourceByNameAndVersion(resourceName, "1.0", false);
assertTrue(resource.isLeft());
resource = resourceOperation.getResourceByNameAndVersion(resourceName, "2.0", false);
@@ -1608,29 +1474,179 @@ public class LifecycleOperationTest extends ModelTestBase {
deleted = resource.left().value().get(0);
assertTrue(deleted.getIsDeleted());
}
-
+
+ // @Test
+ // public void testDeleteOldVersionsResourceWithArtifacts(){
+ // // simulate
+ // Resource resource = createFullTestResource(checkinUser.getUserId(),
+ // "1.0", LifecycleStateEnum.CERTIFIED);
+ //
+ // // checkout
+ // Either<Resource, StorageOperationStatus> checkoutResource =
+ // lifecycleOperation.checkoutResource(resource, checkinUser, checkinUser,
+ // false);
+ // assertTrue(checkoutResource.isLeft());
+ // Either<Resource, StorageOperationStatus> getResource =
+ // resourceOperation.getResourceByNameAndVersion(resource.getResourceName(),
+ // "1.1", false);
+ // assertTrue(getResource.isLeft());
+ //
+ // // rfc
+ // resource = getResource.left().value();
+ // Either<Resource, StorageOperationStatus> requestCertification =
+ // lifecycleOperation.requestCertification(resource, rfcUser, checkinUser,
+ // false);
+ // assertTrue(requestCertification.isLeft());
+ // getResource =
+ // resourceOperation.getResourceByNameAndVersion(resource.getResourceName(),
+ // "1.1", false);
+ // assertTrue(getResource.isLeft());
+ //
+ // // start cert
+ // resource = getResource.left().value();
+ // Either<Resource, StorageOperationStatus> startCertification =
+ // lifecycleOperation.startCertificationResource(resource, testerUser,
+ // rfcUser, false);
+ // assertTrue(startCertification.isLeft());
+ // getResource =
+ // resourceOperation.getResourceByNameAndVersion(resource.getResourceName(),
+ // "1.1", false);
+ // assertTrue(getResource.isLeft());
+ //
+ // // certify
+ // resource = getResource.left().value();
+ // Either<Resource, StorageOperationStatus> certify =
+ // lifecycleOperation.certifyResource(resource, testerUser, testerUser,
+ // false);
+ // assertTrue(certify.isLeft());
+ // getResource =
+ // resourceOperation.getResourceByNameAndVersion(resource.getResourceName(),
+ // "1.1", false);
+ // assertTrue(getResource.isLeft());
+ // resource = getResource.left().value();
+ //
+ //
+ // Either<List<ArtifactDefinition>, StorageOperationStatus>
+ // deleteOldComponentVersions = lifecycleOperation
+ // .deleteOldComponentVersions(NodeTypeEnum.Resource,
+ // resource.getResourceName(), resource.getUUID(), false);
+ //
+ // assertTrue(deleteOldComponentVersions.isLeft());
+ // assertEquals(2, deleteOldComponentVersions.left().value().size());
+ //
+ // String resourceName = resource.getResourceName();
+ // getResource = resourceOperation.getResourceByNameAndVersion(resourceName,
+ // "1.0", false);
+ // assertTrue(getResource.isLeft());
+ //
+ // getResource = resourceOperation.getResourceByNameAndVersion(resourceName,
+ // "2.0", false);
+ // assertTrue(getResource.isLeft());
+ //
+ // getResource = resourceOperation.getResourceByNameAndVersion(resourceName,
+ // "1.1", false);
+ // assertTrue(getResource.isRight());
+ // assertEquals(StorageOperationStatus.NOT_FOUND,
+ // getResource.right().value());
+ //
+ // }
+
+ // @Test
+ // public void testDeleteOldVersionsResourceWithArtifactsDerived(){
+ // // simulate
+ // Resource resourceRoot = createFullTestResource(checkinUser.getUserId(),
+ // "1.0", LifecycleStateEnum.CERTIFIED);
+ // Resource resource = buildResourceMetadata(checkinUser.getUserId(),
+ // CATEGORY_NAME);
+ // resource.setResourceName("myDerivedResource");
+ // resource.setResourceVersion("0.1");
+ // resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ // List<String> derived = new ArrayList<>();
+ // derived.add(resourceRoot.getResourceName());
+ // resource.setDerivedFrom(derived);
+ //
+ // Either<Resource, StorageOperationStatus> result =
+ // resourceOperation.createResource(resource);
+ // assertEquals("check resource created", true, result.isLeft());
+ // resource = result.left().value();
+ //
+ // // resource inherits the artifacts from parent
+ // assertNotNull(resource.getInterfaces().get(INTERFACE_NAME).getOperations().get(INTERFACE_OPERATION_CREATE).getImplementation());
+ //
+ // // rfc
+ // Either<Resource, StorageOperationStatus> requestCertification =
+ // lifecycleOperation.requestCertification(resource, rfcUser, checkinUser,
+ // false);
+ // assertTrue(requestCertification.isLeft());
+ // Either<Resource, StorageOperationStatus> getResource =
+ // resourceOperation.getResourceByNameAndVersion(resource.getResourceName(),
+ // "0.1", false);
+ // assertTrue(getResource.isLeft());
+ //
+ // // start cert
+ // resource = getResource.left().value();
+ // Either<Resource, StorageOperationStatus> startCertification =
+ // lifecycleOperation.startCertificationResource(resource, testerUser,
+ // rfcUser, false);
+ // assertTrue(startCertification.isLeft());
+ // getResource =
+ // resourceOperation.getResourceByNameAndVersion(resource.getResourceName(),
+ // "0.1", false);
+ // assertTrue(getResource.isLeft());
+ //
+ // // certify
+ // resource = getResource.left().value();
+ // Either<Resource, StorageOperationStatus> certify =
+ // lifecycleOperation.certifyResource(resource, testerUser, testerUser,
+ // false);
+ // assertTrue(certify.isLeft());
+ // getResource =
+ // resourceOperation.getResourceByNameAndVersion(resource.getResourceName(),
+ // "0.1", false);
+ // assertTrue(getResource.isLeft());
+ // resource = getResource.left().value();
+ //
+ //
+ // Either<List<ArtifactDefinition>, StorageOperationStatus>
+ // deleteOldComponentVersions = lifecycleOperation
+ // .deleteOldComponentVersions(NodeTypeEnum.Resource,
+ // resource.getResourceName(), resource.getUUID(), false);
+ //
+ // assertTrue(deleteOldComponentVersions.isLeft());
+ //
+ // // resource artifacts are not really the resource's, they are the
+ // parent's artifacts
+ // assertTrue(deleteOldComponentVersions.left().value().isEmpty());
+ //
+ // String resourceName = resource.getResourceName();
+ // getResource = resourceOperation.getResourceByNameAndVersion(resourceName,
+ // "1.0", false);
+ // assertTrue(getResource.isLeft());
+ //
+ // getResource = resourceOperation.getResourceByNameAndVersion(resourceName,
+ // "0.1", false);
+ // assertTrue(getResource.isRight());
+ // assertEquals(StorageOperationStatus.NOT_FOUND,
+ // getResource.right().value());
+ //
+ // }
+
@Test
+ @Ignore
public void testDeleteOldVersionsService() {
// simulate
createTestService(checkinUser.getUserId(), "1.0", LifecycleStateEnum.CERTIFIED, null);
- Service serviceNewUUid = createTestService(checkinUser.getUserId(), "1.1",
- LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null);
- createTestService(checkinUser.getUserId(), "1.2", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN,
- serviceNewUUid.getUUID());
- createTestService(checkinUser.getUserId(), "1.3", LifecycleStateEnum.CERTIFICATION_IN_PROGRESS,
- serviceNewUUid.getUUID());
- Service certifiedService = createTestService(checkinUser.getUserId(), "2.0", LifecycleStateEnum.CERTIFIED,
- serviceNewUUid.getUUID());
-
- Either<Boolean, StorageOperationStatus> deleteOldComponentVersions = lifecycleOperation
- .deleteOldComponentVersions(NodeTypeEnum.Service, certifiedService.getName(),
- certifiedService.getUUID(), false);
+ Service serviceNewUUid = createTestService(checkinUser.getUserId(), "1.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null);
+ createTestService(checkinUser.getUserId(), "1.2", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, serviceNewUUid.getUUID());
+ createTestService(checkinUser.getUserId(), "1.3", LifecycleStateEnum.CERTIFICATION_IN_PROGRESS, serviceNewUUid.getUUID());
+ Service certifiedService = createTestService(checkinUser.getUserId(), "2.0", LifecycleStateEnum.CERTIFIED, serviceNewUUid.getUUID());
+
+ Either<Boolean, StorageOperationStatus> deleteOldComponentVersions = lifecycleOperation.deleteOldComponentVersions(NodeTypeEnum.Service, certifiedService.getName(), certifiedService.getUUID(), false);
assertTrue(deleteOldComponentVersions.isLeft());
String resourceName = certifiedService.getName();
- Either<Service, StorageOperationStatus> service = serviceOperation.getServiceByNameAndVersion(resourceName,
- "1.0", null, false);
+ Either<Service, StorageOperationStatus> service = serviceOperation.getServiceByNameAndVersion(resourceName, "1.0", null, false);
assertTrue(service.isLeft());
service = serviceOperation.getServiceByNameAndVersion(resourceName, "2.0", null, false);
@@ -1638,9 +1654,7 @@ public class LifecycleOperationTest extends ModelTestBase {
service = serviceOperation.getServiceByNameAndVersion(resourceName, "1.1", null, false);
/*
- * assertTrue(resource.isRight());
- * assertEquals(StorageOperationStatus.NOT_FOUND,
- * resource.right().value());
+ * assertTrue(resource.isRight()); assertEquals(StorageOperationStatus.NOT_FOUND, resource.right().value());
*/
assertTrue(service.isLeft());
assertTrue(service.left().value().getIsDeleted());
@@ -1649,18 +1663,14 @@ public class LifecycleOperationTest extends ModelTestBase {
service = serviceOperation.getServiceByNameAndVersion(resourceName, "1.3", null, false);
/*
- * assertTrue(service.isRight());
- * assertEquals(StorageOperationStatus.NOT_FOUND,
- * service.right().value());
+ * assertTrue(service.isRight()); assertEquals(StorageOperationStatus.NOT_FOUND, service.right().value());
*/
assertTrue(service.isLeft());
assertTrue(service.left().value().getIsDeleted());
service = serviceOperation.getServiceByNameAndVersion(resourceName, "1.3", null, false);
/*
- * assertTrue(service.isRight());
- * assertEquals(StorageOperationStatus.NOT_FOUND,
- * service.right().value());
+ * assertTrue(service.isRight()); assertEquals(StorageOperationStatus.NOT_FOUND, service.right().value());
*/
assertTrue(service.isLeft());
assertTrue(service.left().value().getIsDeleted());
@@ -1668,31 +1678,25 @@ public class LifecycleOperationTest extends ModelTestBase {
}
private Resource certificationStatusChange(LifecycleStateEnum nextState, User expectedOwner) {
- Resource resultResource = createTestResource(checkinUser.getUserId(), "0.2",
- LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null);
+ Resource resultResource = createTestResource(checkinUser.getUserId(), "0.2", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null);
// certification request
- Either<Resource, StorageOperationStatus> requestCertificationResult = (Either<Resource, StorageOperationStatus>) lifecycleOperation
- .requestCertificationComponent(NodeTypeEnum.Resource, resultResource, rfcUser, checkinUser, false);
+ Either<Resource, StorageOperationStatus> requestCertificationResult = (Either<Resource, StorageOperationStatus>) lifecycleOperation.requestCertificationComponent(NodeTypeEnum.Resource, resultResource, rfcUser, checkinUser, false);
assertTrue(requestCertificationResult.isLeft());
// start certification
- Either<Resource, StorageOperationStatus> startCertificationResult = (Either<Resource, StorageOperationStatus>) lifecycleOperation
- .startComponentCertification(NodeTypeEnum.Resource, resultResource, testerUser, rfcUser, false);
+ Either<Resource, StorageOperationStatus> startCertificationResult = (Either<Resource, StorageOperationStatus>) lifecycleOperation.startComponentCertification(NodeTypeEnum.Resource, resultResource, testerUser, rfcUser, false);
assertEquals(true, startCertificationResult.isLeft());
Resource actualResource = startCertificationResult.left().value();
// cancel certification
- Either<Resource, StorageOperationStatus> failCertificationResult = (Either<Resource, StorageOperationStatus>) lifecycleOperation
- .cancelOrFailCertification(NodeTypeEnum.Resource, actualResource, testerUser, testerUser, nextState,
- false);
+ Either<Resource, StorageOperationStatus> failCertificationResult = (Either<Resource, StorageOperationStatus>) lifecycleOperation.cancelOrFailCertification(NodeTypeEnum.Resource, actualResource, testerUser, testerUser, nextState, false);
assertEquals(true, failCertificationResult.isLeft());
actualResource = failCertificationResult.left().value();
// get resource owner
- Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation
- .getComponentOwner(actualResource.getUniqueId(), NodeTypeEnum.Resource, false);
+ Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(actualResource.getUniqueId(), NodeTypeEnum.Resource, false);
assertEquals("check user object is returned", true, getOwnerResponse.isLeft());
User resourceOwner = getOwnerResponse.left().value();
@@ -1706,31 +1710,25 @@ public class LifecycleOperationTest extends ModelTestBase {
}
private Service certificationStatusChangeService(LifecycleStateEnum nextState, User expectedOwner) {
- Service resultService = createTestService(checkinUser.getUserId(), "0.2",
- LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null);
+ Service resultService = createTestService(checkinUser.getUserId(), "0.2", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null);
// certification request
- Either<? extends Component, StorageOperationStatus> requestCertificationResult = lifecycleOperation
- .requestCertificationComponent(NodeTypeEnum.Service, resultService, rfcUser, checkinUser, false);
+ Either<? extends Component, StorageOperationStatus> requestCertificationResult = lifecycleOperation.requestCertificationComponent(NodeTypeEnum.Service, resultService, rfcUser, checkinUser, false);
assertTrue(requestCertificationResult.isLeft());
// start certification
- Either<? extends Component, StorageOperationStatus> startCertificationResult = lifecycleOperation
- .startComponentCertification(NodeTypeEnum.Service, resultService, testerUser, rfcUser, false);
+ Either<? extends Component, StorageOperationStatus> startCertificationResult = lifecycleOperation.startComponentCertification(NodeTypeEnum.Service, resultService, testerUser, rfcUser, false);
assertEquals(true, startCertificationResult.isLeft());
Service actualService = (Service) startCertificationResult.left().value();
// cancel certification
- Either<? extends Component, StorageOperationStatus> failCertificationResult = lifecycleOperation
- .cancelOrFailCertification(NodeTypeEnum.Service, actualService, testerUser, testerUser, nextState,
- false);
+ Either<? extends Component, StorageOperationStatus> failCertificationResult = lifecycleOperation.cancelOrFailCertification(NodeTypeEnum.Service, actualService, testerUser, testerUser, nextState, false);
assertEquals(true, failCertificationResult.isLeft());
actualService = (Service) failCertificationResult.left().value();
// get resource owner
- Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation
- .getComponentOwner(actualService.getUniqueId(), NodeTypeEnum.Resource, false);
+ Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(actualService.getUniqueId(), NodeTypeEnum.Resource, false);
assertEquals("check user object is returned", true, getOwnerResponse.isLeft());
User resourceOwner = getOwnerResponse.left().value();
@@ -1789,13 +1787,14 @@ public class LifecycleOperationTest extends ModelTestBase {
}
private Resource createFullTestResource(String userId, String version, LifecycleStateEnum state) {
-
Resource resource2 = buildResourceMetadata(userId, CATEGORY_NAME);
resource2.setVersion(version);
;
resource2.setLifecycleState(state);
InterfaceDefinition inter = new InterfaceDefinition(INTERFACE_NAME, "interface description", null);
+ // inter.setUniqueId(UniqueIdBuilder.buildResourceUniqueId(resource2.getResourceName(),
+ // resource2.getResourceVersion())+"."+INTERFACE_NAME);
Operation operation = new Operation();
operation.setDescription("op description");
@@ -1815,7 +1814,7 @@ public class LifecycleOperationTest extends ModelTestBase {
operation.setCreationDate(System.currentTimeMillis());
Map<String, Operation> ops = new HashMap<>();
ops.put(INTERFACE_OPERATION_CREATE, operation);
- inter.setOperations(ops);
+ inter.setOperationsMap(ops);
Map<String, InterfaceDefinition> interfaces = new HashMap<>();
interfaces.put(INTERFACE_NAME, inter);
@@ -1870,8 +1869,7 @@ public class LifecycleOperationTest extends ModelTestBase {
// artifacts.put("myArtifact", artifactDef);
// resource2.setArtifacts(artifacts);
- Either<ArtifactDefinition, StorageOperationStatus> addArifactToResource = artifactOperation
- .addArifactToComponent(artifactDef, resultResource.getUniqueId(), NodeTypeEnum.Resource, false, true);
+ Either<ArtifactDefinition, StorageOperationStatus> addArifactToResource = artifactOperation.addArifactToComponent(artifactDef, resultResource.getUniqueId(), NodeTypeEnum.Resource, false, true);
assertTrue(addArifactToResource.isLeft());
Either<Resource, StorageOperationStatus> resource = resourceOperation.getResource(resultResource.getUniqueId());
@@ -1894,8 +1892,7 @@ public class LifecycleOperationTest extends ModelTestBase {
properties.put(propName1, property1);
capabilityTypeDefinition.setProperties(properties);
- Either<CapabilityTypeDefinition, StorageOperationStatus> addCapabilityType1 = capabilityTypeOperation
- .addCapabilityType(capabilityTypeDefinition);
+ Either<CapabilityTypeDefinition, StorageOperationStatus> addCapabilityType1 = capabilityTypeOperation.addCapabilityType(capabilityTypeDefinition);
assertTrue(addCapabilityType1.isLeft());
}
@@ -1945,12 +1942,18 @@ public class LifecycleOperationTest extends ModelTestBase {
return userData;
}
-
+
+ /*
+ * public void deleteAndCreateCategory(String category) { CategoryData categoryData = new CategoryData(); categoryData.setName(category);
+ *
+ * Either<CategoryData, TitanOperationStatus> node = titanGenericDao.getNode(categoryData.getUniqueIdKey(), categoryData, CategoryData.class); if (node.isRight()){ //titanGenericDao.deleteNode(categoryData, CategoryData.class);
+ * Either<CategoryData, TitanOperationStatus> createNode = titanGenericDao .createNode(categoryData, CategoryData.class); System.out.println("after creating caetgory " + createNode); }
+ */
+
private PropertyDefinition buildProperty1() {
PropertyDefinition property1 = new PropertyDefinition();
property1.setDefaultValue("10");
- property1.setDescription(
- "Size of the local disk, in Gigabytes (GB), available to applications running on the Compute node.");
+ property1.setDescription("Size of the local disk, in Gigabytes (GB), available to applications running on the Compute node.");
property1.setType(ToscaType.INTEGER.name().toLowerCase());
List<PropertyConstraint> constraints = new ArrayList<PropertyConstraint>();
GreaterThanConstraint propertyConstraint1 = new GreaterThanConstraint("0");
@@ -1982,8 +1985,7 @@ public class LifecycleOperationTest extends ModelTestBase {
artifactInfo.setArtifactLabel(artifactName);
artifactInfo.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(serviceId, artifactInfo.getArtifactLabel()));
- Either<ArtifactDefinition, StorageOperationStatus> artifact = artifactOperation
- .addArifactToComponent(artifactInfo, serviceId, NodeTypeEnum.Service, true, true);
+ Either<ArtifactDefinition, StorageOperationStatus> artifact = artifactOperation.addArifactToComponent(artifactInfo, serviceId, NodeTypeEnum.Service, true, true);
assertTrue(artifact.isLeft());
return artifactInfo;
}
diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/PolicyTypeOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/PolicyTypeOperationTest.java
index 5bd6c831a5..ee129c6529 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
@@ -84,8 +84,7 @@ public class PolicyTypeOperationTest extends ModelTestBase {
PolicyTypeDefinition policyTypePreCreate = createPolicyTypeDef();
assertTrue(StringUtils.isEmpty(policyTypePreCreate.getUniqueId()));
- Either<PolicyTypeDefinition, StorageOperationStatus> addPolicyType = policyTypeOperation
- .addPolicyType(policyTypePreCreate);
+ Either<PolicyTypeDefinition, StorageOperationStatus> addPolicyType = policyTypeOperation.addPolicyType(policyTypePreCreate);
assertTrue(addPolicyType.isLeft());
PolicyTypeDefinition policyTypePostCreate = addPolicyType.left().value();
assertEquals(policyTypePostCreate.getType(), policyTypePreCreate.getType());
@@ -96,10 +95,8 @@ public class PolicyTypeOperationTest extends ModelTestBase {
@Test
public void testGetLatestPolicyTypeByType() {
- PolicyTypeDefinition policyTypeCreated = policyTypeOperation.addPolicyType(createPolicyTypeDef()).left()
- .value();
- Either<PolicyTypeDefinition, StorageOperationStatus> eitherPolicyTypeFetched = policyTypeOperation
- .getLatestPolicyTypeByType(policyTypeCreated.getType());
+ PolicyTypeDefinition policyTypeCreated = policyTypeOperation.addPolicyType(createPolicyTypeDef()).left().value();
+ Either<PolicyTypeDefinition, StorageOperationStatus> eitherPolicyTypeFetched = policyTypeOperation.getLatestPolicyTypeByType(policyTypeCreated.getType());
assertTrue(eitherPolicyTypeFetched.isLeft());
PolicyTypeDefinition policyTypeFetched = eitherPolicyTypeFetched.left().value();
assertEquals(policyTypeFetched.toString(), policyTypeCreated.toString());
@@ -108,8 +105,7 @@ public class PolicyTypeOperationTest extends ModelTestBase {
private PolicyTypeDefinition createPolicyTypeDef() {
PolicyTypeDataDefinition policyTypeDataDefinition = new PolicyTypeDataDefinition();
- policyTypeDataDefinition
- .setDescription("description: The TOSCA Policy Type all other TOSCA Policy Types derive from");
+ policyTypeDataDefinition.setDescription("description: The TOSCA Policy Type all other TOSCA Policy Types derive from");
policyTypeDataDefinition.setType("tosca.policies.Root");
PolicyTypeDefinition policyTypeDefinition = new PolicyTypeDefinition(policyTypeDataDefinition);
policyTypeDefinition.setHighestVersion(true);
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 6caa3044ad..71d2b32a6f 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
@@ -61,9 +61,9 @@ import fj.data.Either;
public class PropertyOperationTest extends ModelTestBase {
- PropertyOperation propertyOperation = new PropertyOperation();
-
TitanGenericDao titanGenericDao = Mockito.mock(TitanGenericDao.class);
+
+ PropertyOperation propertyOperation = new PropertyOperation(titanGenericDao);
@Before
public void setup() {
@@ -74,46 +74,28 @@ public class PropertyOperationTest extends ModelTestBase {
/*
* @Test public void addPropertyToResourceTest() {
*
- * String propName = "myProp"; PropertyDefinition property =
- * buildPropertyDefinition(); List<PropertyConstraint> constraints =
- * buildConstraints(); property.setConstraints(constraints);
+ * String propName = "myProp"; PropertyDefinition property = buildPropertyDefinition(); List<PropertyConstraint> constraints = buildConstraints(); property.setConstraints(constraints);
*
- * PropertyData propertyData = new PropertyData(property,
- * propertyOperation.convertConstraintsToString(constraints));
+ * PropertyData propertyData = new PropertyData(property, propertyOperation.convertConstraintsToString(constraints));
*
- * Either<PropertyData, TitanOperationStatus> either =
- * Either.left(propertyData);
- * //when(propertyDao.create((GraphNeighbourTable)anyObject(),
- * eq(PropertyData.class), eq(NodeTypeEnum.Property))).thenReturn(either);
- * GraphRelation graphRelation = new GraphRelation(); Either<GraphRelation,
- * TitanOperationStatus> relationResult = Either.left(graphRelation);
+ * Either<PropertyData, TitanOperationStatus> either = Either.left(propertyData); //when(propertyDao.create((GraphNeighbourTable)anyObject(), eq(PropertyData.class), eq(NodeTypeEnum.Property))).thenReturn(either); GraphRelation graphRelation =
+ * new GraphRelation(); Either<GraphRelation, TitanOperationStatus> relationResult = Either.left(graphRelation);
*
- * when(titanGenericDao.createNode((PropertyData)anyObject(),
- * eq(PropertyData.class))).thenReturn(either);
- * when(titanGenericDao.createRelation((GraphNode)anyObject(),
- * (GraphNode)anyObject(), eq(GraphEdgeLabels.PROPERTY),
+ * when(titanGenericDao.createNode((PropertyData)anyObject(), eq(PropertyData.class))).thenReturn(either); when(titanGenericDao.createRelation((GraphNode)anyObject(), (GraphNode)anyObject(), eq(GraphEdgeLabels.PROPERTY),
* anyMap())).thenReturn(relationResult);
*
- * Either<PropertyDefinition, StorageOperationStatus> result =
- * propertyOperation.addPropertyToResource(propName, property,
- * NodeTypeEnum.Resource, "my-resource.1.0");
+ * Either<PropertyDefinition, StorageOperationStatus> result = propertyOperation.addPropertyToResource(propName, property, NodeTypeEnum.Resource, "my-resource.1.0");
*
- * assertTrue(result.isLeft()); System.out.println(result.left().value());
- * PropertyDefinition propertyDefinition = result.left().value();
+ * assertTrue(result.isLeft()); System.out.println(result.left().value()); PropertyDefinition propertyDefinition = result.left().value();
*
- * List<PropertyConstraint> originalConstraints = property.getConstraints();
- * List<PropertyConstraint> propertyConstraintsResult =
- * propertyDefinition.getConstraints();
- * assertEquals(propertyConstraintsResult.size(),
- * originalConstraints.size());
+ * List<PropertyConstraint> originalConstraints = property.getConstraints(); List<PropertyConstraint> propertyConstraintsResult = propertyDefinition.getConstraints(); assertEquals(propertyConstraintsResult.size(), originalConstraints.size());
*
* }
*/
private PropertyDefinition buildPropertyDefinition() {
PropertyDefinition property = new PropertyDefinition();
property.setDefaultValue("10");
- property.setDescription(
- "Size of the local disk, in Gigabytes (GB), available to applications running on the Compute node.");
+ property.setDescription("Size of the local disk, in Gigabytes (GB), available to applications running on the Compute node.");
property.setType(ToscaType.INTEGER.name().toLowerCase());
return property;
}
@@ -179,8 +161,7 @@ public class PropertyOperationTest extends ModelTestBase {
List<String> convertedStringConstraints = propertyOperation.convertConstraintsToString(constraints);
assertEquals("constraints size", constraints.size(), convertedStringConstraints.size());
- List<PropertyConstraint> convertedConstraints = propertyOperation
- .convertConstraints(convertedStringConstraints);
+ List<PropertyConstraint> convertedConstraints = propertyOperation.convertConstraints(convertedStringConstraints);
assertEquals("check size of constraints", constraints.size(), convertedConstraints.size());
Set<String> constraintsClasses = new HashSet<String>();
@@ -189,8 +170,7 @@ public class PropertyOperationTest extends ModelTestBase {
}
for (PropertyConstraint propertyConstraint : convertedConstraints) {
- assertTrue("check all classes generated",
- constraintsClasses.contains(propertyConstraint.getClass().getName()));
+ assertTrue("check all classes generated", constraintsClasses.contains(propertyConstraint.getClass().getName()));
}
}
@@ -322,8 +302,7 @@ public class PropertyOperationTest extends ModelTestBase {
assertEquals("check value", "v1node1", instanceProperty.getValue());
assertEquals("check default value", "v1node3", instanceProperty.getDefaultValue());
- assertEquals("check valid unique id", instanceProperty1.getValueUniqueUid(),
- instanceProperty.getValueUniqueUid());
+ assertEquals("check valid unique id", instanceProperty1.getValueUniqueUid(), instanceProperty.getValueUniqueUid());
}
diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/RequirementOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/RequirementOperationTest.java
index fe4b501148..62e6adab7f 100644
--- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/RequirementOperationTest.java
+++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/RequirementOperationTest.java
@@ -21,46 +21,26 @@
package org.openecomp.sdc.be.model.operations.impl;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.junit.Before;
import org.junit.BeforeClass;
+import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.openecomp.sdc.be.config.Configuration;
-import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
-import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.model.CapabilityDefinition;
-import org.openecomp.sdc.be.model.CapabilityTypeDefinition;
import org.openecomp.sdc.be.model.CapabiltyInstance;
-import org.openecomp.sdc.be.model.LifecycleStateEnum;
import org.openecomp.sdc.be.model.ModelTestBase;
import org.openecomp.sdc.be.model.PropertyDefinition;
import org.openecomp.sdc.be.model.RequirementDefinition;
-import org.openecomp.sdc.be.model.RequirementImplDef;
import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.model.operations.impl.CapabilityOperation;
-import org.openecomp.sdc.be.model.operations.impl.CapabilityTypeOperation;
-import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
-import org.openecomp.sdc.be.model.operations.impl.RequirementOperation;
-import org.openecomp.sdc.be.model.operations.impl.ResourceOperation;
-import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
import org.openecomp.sdc.be.model.operations.impl.util.OperationTestsUtil;
-import org.openecomp.sdc.be.model.operations.impl.util.PrintGraph;
-import org.openecomp.sdc.be.resources.data.ResourceMetadataData;
import org.openecomp.sdc.be.resources.data.UserData;
-import org.openecomp.sdc.common.api.ConfigurationListener;
-import org.openecomp.sdc.common.api.ConfigurationSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.test.context.ContextConfiguration;
@@ -77,11 +57,9 @@ public class RequirementOperationTest extends ModelTestBase {
private static Logger log = LoggerFactory.getLogger(RequirementOperationTest.class.getName());
private Gson prettyGson = new GsonBuilder().setPrettyPrinting().create();
- private static String USER_ID = "muserId";
+ private static String USER_ID = "muUserId";
private static String CATEGORY_NAME = "category/mycategory";
- private static ConfigurationManager configurationManager;
-
@javax.annotation.Resource(name = "titan-generic-dao")
private TitanGenericDao titanDao;
@@ -147,11 +125,9 @@ public class RequirementOperationTest extends ModelTestBase {
ResourceOperationTest resourceOperationTest = new ResourceOperationTest();
resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation);
- Resource resource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, "my-resource", "0.1", null,
- true, true);
+ Resource resource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, "my-resource", "0.1", null, true, true);
- Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource = requirementOperation
- .addRequirementToResource(reqName, reqDefinition, resource.getUniqueId());
+ Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource = requirementOperation.addRequirementToResource(reqName, reqDefinition, resource.getUniqueId());
assertEquals("check error", StorageOperationStatus.INVALID_ID, addRequirementToResource.right().value());
}
@@ -175,8 +151,17 @@ public class RequirementOperationTest extends ModelTestBase {
return userData;
}
-
+
+ /*
+ * private void deleteAndCreateCategory(String category) { CategoryData categoryData = new CategoryData(); categoryData.setName(category);
+ *
+ * titanDao.deleteNode(categoryData, CategoryData.class); Either<CategoryData, TitanOperationStatus> createNode = titanDao .createNode(categoryData, CategoryData.class); System.out.println("after creating caetgory " + createNode);
+ *
+ * }
+ */
+
@Test
+ @Ignore
public void testAddRequirementWithCapability() {
String capabilityTypeName = "tosca.nodes.Container";
@@ -195,11 +180,9 @@ public class RequirementOperationTest extends ModelTestBase {
ResourceOperationTest resourceOperationTest = new ResourceOperationTest();
resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation);
- Resource resource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, "my-resource", "2.0", null,
- true, true);
+ Resource resource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, "my-resource", "2.0", null, true, true);
- Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource = requirementOperation
- .addRequirementToResource(reqName, reqDefinition, resource.getUniqueId());
+ Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource = requirementOperation.addRequirementToResource(reqName, reqDefinition, resource.getUniqueId());
assertEquals("check requirement was added", true, addRequirementToResource.isLeft());
@@ -207,9 +190,8 @@ public class RequirementOperationTest extends ModelTestBase {
String json = prettyGson.toJson(resource2);
log.debug(json);
}
-
- private void compareProperties(Map<String, PropertyDefinition> capabilityProperties,
- CapabiltyInstance capabiltyInstance, Map<String, String> actual) {
+
+ private void compareProperties(Map<String, PropertyDefinition> capabilityProperties, CapabiltyInstance capabiltyInstance, Map<String, String> actual) {
Map<String, String> properties = capabiltyInstance.getProperties();
diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ResourceInstanceOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ResourceInstanceOperationTest.java
index bef51f415c..4f9488c239 100644
--- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ResourceInstanceOperationTest.java
+++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ResourceInstanceOperationTest.java
@@ -95,7 +95,7 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
private static Logger log = LoggerFactory.getLogger(ResourceInstanceOperationTest.class.getName());
private Gson prettyGson = new GsonBuilder().setPrettyPrinting().create();
- private static String USER_ID = "muserId";
+ private static String USER_ID = "muUserId";
private static String CATEGORY_NAME = "category/mycategory";
@javax.annotation.Resource(name = "titan-generic-dao")
@@ -172,10 +172,8 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
ModelTestBase.init();
}
- public void setOperations(TitanGenericDao titanDao, CapabilityTypeOperation capabilityTypeOperation,
- RequirementOperation requirementOperation, CapabilityOperation capabilityOperation,
- ResourceOperation resourceOperation, PropertyOperation propertyOperation,
- ComponentInstanceOperation resourceInstanceOperation2) {
+ public void setOperations(TitanGenericDao titanDao, CapabilityTypeOperation capabilityTypeOperation, RequirementOperation requirementOperation, CapabilityOperation capabilityOperation, ResourceOperation resourceOperation,
+ PropertyOperation propertyOperation, ComponentInstanceOperation resourceInstanceOperation2) {
this.titanDao = titanDao;
this.capabilityTypeOperation = capabilityTypeOperation;
this.capabilityOperation = capabilityOperation;
@@ -198,12 +196,9 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
try {
ComponentInstance instance = buildResourceInstance("tosca.nodes.Apache.2.0", "1", "tosca.nodes.Apache");
- Either<ComponentInstance, TitanOperationStatus> status = resourceInstanceOperation
- .addComponentInstanceToContainerComponent("service1", NodeTypeEnum.Service, "1", true, instance,
- NodeTypeEnum.Resource, false);
+ Either<ComponentInstance, TitanOperationStatus> status = resourceInstanceOperation.addComponentInstanceToContainerComponent("service1", NodeTypeEnum.Service, "1", true, instance, NodeTypeEnum.Resource, false);
assertEquals("check failed status - service is not in graph", true, status.isRight());
- assertEquals("check failed status value - service is not in graph", TitanOperationStatus.INVALID_ID,
- status.right().value());
+ assertEquals("check failed status value - service is not in graph", TitanOperationStatus.INVALID_ID, status.right().value());
} finally {
titanDao.rollback();
}
@@ -218,13 +213,10 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
ComponentInstance instance = buildResourceInstance("tosca.nodes.Apache.2.0", "1", "tosca.nodes.Apache");
- Either<ComponentInstance, TitanOperationStatus> status = resourceInstanceOperation
- .addComponentInstanceToContainerComponent((String) serviceData1.getUniqueId(), NodeTypeEnum.Service,
- "1", true, instance, NodeTypeEnum.Resource, false);
+ Either<ComponentInstance, TitanOperationStatus> status = resourceInstanceOperation.addComponentInstanceToContainerComponent((String) serviceData1.getUniqueId(), NodeTypeEnum.Service, "1", true, instance, NodeTypeEnum.Resource, false);
assertEquals("check failed status - service is not in graph", true, status.isRight());
- assertEquals("check failed status value - service is not in graph", TitanOperationStatus.INVALID_ID,
- status.right().value());
+ assertEquals("check failed status value - service is not in graph", TitanOperationStatus.INVALID_ID, status.right().value());
} finally {
titanDao.rollback();
@@ -240,12 +232,9 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
ServiceMetadataData serviceData1 = createService(serviceName);
ResourceMetadataData resourceData = createResource(resourceName);
- ComponentInstance instance = buildResourceInstance(resourceData.getMetadataDataDefinition().getUniqueId(),
- "1", "tosca.nodes.Apache");
+ ComponentInstance instance = buildResourceInstance(resourceData.getMetadataDataDefinition().getUniqueId(), "1", "tosca.nodes.Apache");
- Either<ComponentInstance, TitanOperationStatus> status = resourceInstanceOperation
- .addComponentInstanceToContainerComponent((String) serviceData1.getUniqueId(), NodeTypeEnum.Service,
- "1", true, instance, NodeTypeEnum.Resource, false);
+ Either<ComponentInstance, TitanOperationStatus> status = resourceInstanceOperation.addComponentInstanceToContainerComponent((String) serviceData1.getUniqueId(), NodeTypeEnum.Service, "1", true, instance, NodeTypeEnum.Resource, false);
assertEquals("check success status - service is not in graph", true, status.isLeft());
@@ -268,12 +257,9 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
ServiceMetadataData serviceData1 = createService(serviceName);
ResourceMetadataData resourceData = createResource(resourceName);
- ComponentInstance instance = buildResourceInstance(resourceData.getMetadataDataDefinition().getUniqueId(),
- "1", "tosca.nodes.Apache");
+ ComponentInstance instance = buildResourceInstance(resourceData.getMetadataDataDefinition().getUniqueId(), "1", "tosca.nodes.Apache");
- Either<ComponentInstance, TitanOperationStatus> status = resourceInstanceOperation
- .addComponentInstanceToContainerComponent((String) serviceData1.getUniqueId(), NodeTypeEnum.Service,
- "1", true, instance, NodeTypeEnum.Resource, false);
+ Either<ComponentInstance, TitanOperationStatus> status = resourceInstanceOperation.addComponentInstanceToContainerComponent((String) serviceData1.getUniqueId(), NodeTypeEnum.Service, "1", true, instance, NodeTypeEnum.Resource, false);
ComponentInstance resourceInstance = status.left().value();
Long creationTime = resourceInstance.getCreationTime();
@@ -283,9 +269,7 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
ComponentInstance value = status.left().value();
assertEquals("check name exists", "tosca.nodes.Apache 1", value.getName());
- Either<ComponentInstance, StorageOperationStatus> u1Res = resourceInstanceOperation.updateResourceInstance(
- (String) serviceData1.getUniqueId(), NodeTypeEnum.Service, resourceInstance.getUniqueId(), value,
- true);
+ Either<ComponentInstance, StorageOperationStatus> u1Res = resourceInstanceOperation.updateResourceInstance((String) serviceData1.getUniqueId(), NodeTypeEnum.Service, resourceInstance.getUniqueId(), value, true);
assertTrue("check update succeed", u1Res.isLeft());
Long lastModificationTimeNC = value.getModificationTime();
@@ -295,29 +279,23 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
String updatedName = "Shlokshlik";
value.setDescription(desc);
value.setPosX(posX);
- Either<ComponentInstance, StorageOperationStatus> u2Res = resourceInstanceOperation.updateResourceInstance(
- (String) serviceData1.getUniqueId(), NodeTypeEnum.Service, resourceInstance.getUniqueId(), value,
- true);
+ Either<ComponentInstance, StorageOperationStatus> u2Res = resourceInstanceOperation.updateResourceInstance((String) serviceData1.getUniqueId(), NodeTypeEnum.Service, resourceInstance.getUniqueId(), value, true);
assertTrue("check update succeed", u2Res.isLeft());
assertEquals("check resource instance updated", desc, u2Res.left().value().getDescription());
assertEquals("check resource instance updated", posX, u2Res.left().value().getPosX());
assertEquals("check resource instance updated", resourceInstance.getPosY(), u2Res.left().value().getPosY());
- assertEquals("check modification time was not updated since it was supplied",
- u2Res.left().value().getModificationTime(), lastModificationTimeNC);
+ assertEquals("check modification time was not updated since it was supplied", u2Res.left().value().getModificationTime(), lastModificationTimeNC);
Long lastModificationTime = value.getModificationTime();
value.setPosY(posY);
value.setModificationTime(null);
value.setName(updatedName);
- Either<ComponentInstance, StorageOperationStatus> u3Res = resourceInstanceOperation.updateResourceInstance(
- (String) serviceData1.getUniqueId(), NodeTypeEnum.Service, resourceInstance.getUniqueId(), value,
- true);
+ Either<ComponentInstance, StorageOperationStatus> u3Res = resourceInstanceOperation.updateResourceInstance((String) serviceData1.getUniqueId(), NodeTypeEnum.Service, resourceInstance.getUniqueId(), value, true);
assertTrue("check update succeed", u3Res.isLeft());
assertEquals("check resource instance updated", desc, u3Res.left().value().getDescription());
assertEquals("check resource pos x updated", posX, u3Res.left().value().getPosX());
assertEquals("check resource pos y updated", posY, u3Res.left().value().getPosY());
- assertTrue("check modification time was updated",
- u3Res.left().value().getModificationTime() >= lastModificationTime);
+ assertTrue("check modification time was updated", u3Res.left().value().getModificationTime() >= lastModificationTime);
assertEquals("check creation time was not updated", creationTime, u3Res.left().value().getCreationTime());
assertEquals("check name was updated", updatedName, u3Res.left().value().getName());
@@ -337,20 +315,16 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
ServiceMetadataData serviceData1 = createService(serviceName);
ResourceMetadataData resourceData = createResource(resourceName);
- ComponentInstance instance = buildResourceInstance(resourceData.getMetadataDataDefinition().getUniqueId(),
- "1", "tosca.nodes.Apache");
+ ComponentInstance instance = buildResourceInstance(resourceData.getMetadataDataDefinition().getUniqueId(), "1", "tosca.nodes.Apache");
- Either<ComponentInstance, TitanOperationStatus> status = resourceInstanceOperation
- .addComponentInstanceToContainerComponent((String) serviceData1.getUniqueId(), NodeTypeEnum.Service,
- "1", true, instance, NodeTypeEnum.Resource, false);
+ Either<ComponentInstance, TitanOperationStatus> status = resourceInstanceOperation.addComponentInstanceToContainerComponent((String) serviceData1.getUniqueId(), NodeTypeEnum.Service, "1", true, instance, NodeTypeEnum.Resource, false);
assertEquals("check success status - service is not in graph", true, status.isLeft());
ComponentInstance value = status.left().value();
assertEquals("check name exists", "tosca.nodes.Apache 1", value.getName());
- Either<ComponentInstance, TitanOperationStatus> status1 = resourceInstanceOperation
- .removeComponentInstanceFromComponent(NodeTypeEnum.Service, serviceName, value.getUniqueId());
+ Either<ComponentInstance, TitanOperationStatus> status1 = resourceInstanceOperation.removeComponentInstanceFromComponent(NodeTypeEnum.Service, serviceName, value.getUniqueId());
assertTrue("check resource service was deleted.", status1.isLeft());
assertEquals("check resource instance returned.", "tosca.nodes.Apache 1", status1.left().value().getName());
@@ -369,8 +343,7 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
String serviceName = "myservice1.1.0";
ServiceMetadataData serviceData1 = createService(serviceName);
- Either<ComponentInstance, TitanOperationStatus> status1 = resourceInstanceOperation
- .removeComponentInstanceFromComponent(NodeTypeEnum.Service, serviceName, "stam");
+ Either<ComponentInstance, TitanOperationStatus> status1 = resourceInstanceOperation.removeComponentInstanceFromComponent(NodeTypeEnum.Service, serviceName, "stam");
assertTrue("check resource service was not deleted.", status1.isRight());
assertEquals("check NOT_FOUND returned.", TitanOperationStatus.NOT_FOUND, status1.right().value());
@@ -386,8 +359,7 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
ServiceMetadataData serviceData1 = new ServiceMetadataData();
serviceData1.getMetadataDataDefinition().setUniqueId(serviceName);
- Either<ServiceMetadataData, TitanOperationStatus> createNode = titanDao.createNode(serviceData1,
- ServiceMetadataData.class);
+ Either<ServiceMetadataData, TitanOperationStatus> createNode = titanDao.createNode(serviceData1, ServiceMetadataData.class);
assertTrue("check service created", createNode.isLeft());
return createNode.left().value();
@@ -397,8 +369,7 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
ServiceMetadataData serviceData1 = new ServiceMetadataData();
serviceData1.getMetadataDataDefinition().setUniqueId(serviceName);
- Either<ServiceMetadataData, TitanOperationStatus> createNode = titanDao.deleteNode(serviceData1,
- ServiceMetadataData.class);
+ Either<ServiceMetadataData, TitanOperationStatus> createNode = titanDao.deleteNode(serviceData1, ServiceMetadataData.class);
assertTrue("check service deleted", createNode.isLeft());
return createNode.left().value();
}
@@ -407,8 +378,7 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
ResourceMetadataData serviceData1 = new ResourceMetadataData();
serviceData1.getMetadataDataDefinition().setUniqueId(resourceName);
- Either<ResourceMetadataData, TitanOperationStatus> createNode = titanDao.createNode(serviceData1,
- ResourceMetadataData.class);
+ Either<ResourceMetadataData, TitanOperationStatus> createNode = titanDao.createNode(serviceData1, ResourceMetadataData.class);
assertTrue("check service created", createNode.isLeft());
return createNode.left().value();
@@ -418,8 +388,7 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
ResourceMetadataData serviceData1 = new ResourceMetadataData();
serviceData1.getMetadataDataDefinition().setUniqueId(resourceName);
- Either<ResourceMetadataData, TitanOperationStatus> createNode = titanDao.deleteNode(serviceData1,
- ResourceMetadataData.class);
+ Either<ResourceMetadataData, TitanOperationStatus> createNode = titanDao.deleteNode(serviceData1, ResourceMetadataData.class);
assertTrue("check service created", createNode.isLeft());
return createNode.left().value();
@@ -478,6 +447,7 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
}
@Test
+ @Ignore
public void testConenctResourceInstancesJson() {
RequirementCapabilityRelDef addRelationship = addRelationship("apache_1", "compute_100");
String json = prettyGson.toJson(addRelationship);
@@ -530,13 +500,9 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
OperationTestsUtil.deleteAndCreateServiceCategory(category, titanDao);
/*
- * CategoryData categoryData = new CategoryData();
- * categoryData.setName(category);
+ * CategoryData categoryData = new CategoryData(); categoryData.setName(category);
*
- * titanDao.deleteNode(categoryData, CategoryData.class);
- * Either<CategoryData, TitanOperationStatus> createNode = titanDao
- * .createNode(categoryData, CategoryData.class);
- * System.out.println("after creating caetgory " + createNode);
+ * titanDao.deleteNode(categoryData, CategoryData.class); Either<CategoryData, TitanOperationStatus> createNode = titanDao .createNode(categoryData, CategoryData.class); System.out.println("after creating caetgory " + createNode);
*/
}
@@ -560,30 +526,25 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
// Create Capability type
CapabilityTypeOperationTest capabilityTypeOperationTest = new CapabilityTypeOperationTest();
capabilityTypeOperationTest.setOperations(titanDao, capabilityTypeOperation);
- CapabilityTypeDefinition createCapabilityDef = capabilityTypeOperationTest
- .createCapability(capabilityTypeName);
+ CapabilityTypeDefinition createCapabilityDef = capabilityTypeOperationTest.createCapability(capabilityTypeName);
ResourceOperationTest resourceOperationTest = new ResourceOperationTest();
resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation);
// create root resource
- Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "1.0", null,
- true, true);
+ Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "1.0", null, true, true);
ResourceMetadataData resourceData = new ResourceMetadataData();
resourceData.getMetadataDataDefinition().setUniqueId(rootResource.getUniqueId());
resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name());
- Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanDao.updateNode(resourceData,
- ResourceMetadataData.class);
+ Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class);
assertTrue(updateNode.isLeft());
- Either<Resource, StorageOperationStatus> fetchRootResource = resourceOperation
- .getResource(rootResource.getUniqueId(), true);
+ Either<Resource, StorageOperationStatus> fetchRootResource = resourceOperation.getResource(rootResource.getUniqueId(), true);
String rootResourceJson = prettyGson.toJson(fetchRootResource.left().value());
log.debug(rootResourceJson);
// create software component
- Resource softwareComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, softwareCompName,
- "1.0", rootResource.getName(), true, true);
+ Resource softwareComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, softwareCompName, "1.0", rootResource.getName(), true, true);
resourceData.getMetadataDataDefinition().setUniqueId(softwareComponent.getUniqueId());
resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name());
@@ -591,55 +552,32 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
assertTrue(updateNode.isLeft());
// create compute component
- Resource computeComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, computeNodeName,
- "1.0", rootResource.getName(), true, true);
+ Resource computeComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, computeNodeName, "1.0", rootResource.getName(), true, true);
// rollbackAndPrint();
// Add capabilities to Compute Resource
CapabilityDefinition addCapability = addCapabilityToResource(capabilityTypeName, "host", computeComponent);
- // CapabilityDefinition capabilityDefinition = new
- // CapabilityDefinition();
- // capabilityDefinition.setDescription("my capability");
- // capabilityDefinition.setType(capabilityTypeName);
- // List<String> validSourceTypes = new ArrayList<String>();
- // validSourceTypes.add("tosca.nodes.SC");
- // capabilityDefinition.setValidSourceTypes(validSourceTypes);
- // Either<CapabilityDefinition, StorageOperationStatus>
- // addCapability = capabilityOperation
- // .addCapability(computeComponent.getUniqueId(), "host",
- // capabilityDefinition, true);
- // //logger.debug("addCapability result " + addCapability);
- // assertTrue("check capability created ", addCapability.isLeft());
- //
- // =============================================
-
// create requirement definition
- Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource = addRequirementToResource(
- capabilityTypeName, reqName, reqNodeName, reqRelationship, softwareComponent);
+ Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource = addRequirementToResource(capabilityTypeName, reqName, reqNodeName, reqRelationship, softwareComponent);
String parentReqUniqId = addRequirementToResource.left().value().getUniqueId();
// create my resource derived from software component
- Resource resource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, "my-resource",
- myResourceVersion, softwareComponent.getName(), true, true);
+ Resource resource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, "my-resource", myResourceVersion, softwareComponent.getName(), true, true);
String serviceName = "myservice.1.0";
- List<ComponentInstance> resInstances = buildServiceAndConnectBetweenResourceInstances(serviceName, resource,
- computeComponent, "host", false, addCapability.getUniqueId(),
- addRequirementToResource.left().value().getUniqueId());
+ List<ComponentInstance> resInstances = buildServiceAndConnectBetweenResourceInstances(serviceName, resource, computeComponent, "host", false, addCapability.getUniqueId(), addRequirementToResource.left().value().getUniqueId());
PrintGraph printGraph = new PrintGraph();
String webGraph = printGraph.buildGraphForWebgraphWiz(titanDao.getGraph().left().value());
log.debug(webGraph);
- Either<Resource, StorageOperationStatus> resourceFull = resourceOperation
- .getResource(resource.getUniqueId());
+ Either<Resource, StorageOperationStatus> resourceFull = resourceOperation.getResource(resource.getUniqueId());
assertTrue(resourceFull.isLeft());
- List<RequirementCapabilityRelDef> componentInstancesRelations = resourceFull.left().value()
- .getComponentInstancesRelations();
+ List<RequirementCapabilityRelDef> componentInstancesRelations = resourceFull.left().value().getComponentInstancesRelations();
RequirementCapabilityRelDef capabilityRelDef = componentInstancesRelations.get(0);
capabilityRelDef.getRelationships().get(0).setRequirement("host");
@@ -678,34 +616,28 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
// Create Capability type
CapabilityTypeOperationTest capabilityTypeOperationTest = new CapabilityTypeOperationTest();
capabilityTypeOperationTest.setOperations(titanDao, capabilityTypeOperation);
- CapabilityTypeDefinition createCapabilityDef1 = capabilityTypeOperationTest
- .createCapability(capabilityTypeName1);
- CapabilityTypeDefinition createCapabilityDef2 = capabilityTypeOperationTest
- .createCapability(capabilityTypeName2);
+ CapabilityTypeDefinition createCapabilityDef1 = capabilityTypeOperationTest.createCapability(capabilityTypeName1);
+ CapabilityTypeDefinition createCapabilityDef2 = capabilityTypeOperationTest.createCapability(capabilityTypeName2);
ResourceOperationTest resourceOperationTest = new ResourceOperationTest();
resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation);
// create root resource
- Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "1.0", null,
- true, true);
+ Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "1.0", null, true, true);
ResourceMetadataData resourceData = new ResourceMetadataData();
resourceData.getMetadataDataDefinition().setUniqueId(rootResource.getUniqueId());
resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name());
- Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanDao.updateNode(resourceData,
- ResourceMetadataData.class);
+ Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class);
assertTrue(updateNode.isLeft());
- Either<Resource, StorageOperationStatus> fetchRootResource = resourceOperation
- .getResource(rootResource.getUniqueId(), true);
+ Either<Resource, StorageOperationStatus> fetchRootResource = resourceOperation.getResource(rootResource.getUniqueId(), true);
String rootResourceJson = prettyGson.toJson(fetchRootResource.left().value());
log.debug(rootResourceJson);
// create software component
- Resource softwareComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, softwareCompName,
- "1.0", rootResource.getName(), true, true);
+ Resource softwareComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, softwareCompName, "1.0", rootResource.getName(), true, true);
resourceData.getMetadataDataDefinition().setUniqueId(softwareComponent.getUniqueId());
resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name());
@@ -713,8 +645,7 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
assertTrue(updateNode.isLeft());
// create compute component
- Resource computeComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, computeNodeName,
- "1.0", rootResource.getName(), true, true);
+ Resource computeComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, computeNodeName, "1.0", rootResource.getName(), true, true);
// Add capabilities to Compute Resource
CapabilityDefinition capabilty1 = addCapabilityToResource(capabilityTypeName1, reqName1, computeComponent);
@@ -724,19 +655,16 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
// create requirement definition
- Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource = addRequirementToResource(
- capabilityTypeName1, reqName1, reqNodeName, reqRelationship, softwareComponent);
+ Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource = addRequirementToResource(capabilityTypeName1, reqName1, reqNodeName, reqRelationship, softwareComponent);
String requirementId = addRequirementToResource.left().value().getUniqueId();
String parentReqUniqId = requirementId;
// create my resource derived from software component
- Resource resource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, "my-resource",
- myResourceVersion, softwareComponent.getName(), true, true);
+ Resource resource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, "my-resource", myResourceVersion, softwareComponent.getName(), true, true);
String serviceName = "myservice.1.0";
- List<ComponentInstance> resInstances = buildServiceAndConnectBetweenResourceInstances(serviceName, resource,
- computeComponent, reqName1, false, capabilty1.getUniqueId(), requirementId);
+ List<ComponentInstance> resInstances = buildServiceAndConnectBetweenResourceInstances(serviceName, resource, computeComponent, reqName1, false, capabilty1.getUniqueId(), requirementId);
PrintGraph printGraph = new PrintGraph();
String webGraph = printGraph.buildGraphForWebgraphWiz(titanDao.getGraph().left().value());
@@ -748,17 +676,13 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
relationPair.setCapabilityUid(capabilty1.getUniqueId());
relationPair.setRequirementUid(requirementId);
- Either<RelationshipInstData, TitanOperationStatus> connectResourcesInService1 = resourceInstanceOperation
- .connectResourcesInService(serviceName, NodeTypeEnum.Service, resInstances.get(0).getUniqueId(),
- resInstances.get(1).getUniqueId(), relationPair);
- assertEquals("check cannot associate resource instances", TitanOperationStatus.ILLEGAL_ARGUMENT,
- connectResourcesInService1.right().value());
+ Either<RelationshipInstData, TitanOperationStatus> connectResourcesInService1 = resourceInstanceOperation.connectResourcesInService(serviceName, NodeTypeEnum.Service, resInstances.get(0).getUniqueId(), resInstances.get(1).getUniqueId(),
+ relationPair);
+ assertEquals("check cannot associate resource instances", TitanOperationStatus.ILLEGAL_ARGUMENT, connectResourcesInService1.right().value());
relationPair.setRequirement(reqName1);
- Either<RelationshipInstData, TitanOperationStatus> connectResourcesInService2 = resourceInstanceOperation
- .connectResourcesInService(serviceName, NodeTypeEnum.Service, resInstances.get(0).getUniqueId(),
- resInstances.get(1).getUniqueId(), relationPair);
- assertEquals("check cannot associate resource instances", TitanOperationStatus.TITAN_SCHEMA_VIOLATION,
- connectResourcesInService2.right().value());
+ Either<RelationshipInstData, TitanOperationStatus> connectResourcesInService2 = resourceInstanceOperation.connectResourcesInService(serviceName, NodeTypeEnum.Service, resInstances.get(0).getUniqueId(), resInstances.get(1).getUniqueId(),
+ relationPair);
+ assertEquals("check cannot associate resource instances", TitanOperationStatus.TITAN_SCHEMA_VIOLATION, connectResourcesInService2.right().value());
relationPair.setRequirement(reqName1);
@@ -791,6 +715,7 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
}
@Test
+ @Ignore
public void testConnectResourceInstances2Requirement2Capabilities() {
PrintGraph printGraph1 = new PrintGraph();
@@ -812,26 +737,21 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
// Create Capability type
CapabilityTypeOperationTest capabilityTypeOperationTest = new CapabilityTypeOperationTest();
capabilityTypeOperationTest.setOperations(titanDao, capabilityTypeOperation);
- CapabilityTypeDefinition createCapabilityDef1 = capabilityTypeOperationTest
- .createCapability(capabilityTypeName1);
- CapabilityTypeDefinition createCapabilityDef2 = capabilityTypeOperationTest
- .createCapability(capabilityTypeName2);
+ CapabilityTypeDefinition createCapabilityDef1 = capabilityTypeOperationTest.createCapability(capabilityTypeName1);
+ CapabilityTypeDefinition createCapabilityDef2 = capabilityTypeOperationTest.createCapability(capabilityTypeName2);
ResourceOperationTest resourceOperationTest = new ResourceOperationTest();
resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation);
// create root resource
- Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "1.0", null,
- true, true);
+ Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "1.0", null, true, true);
ResourceMetadataData resourceData = new ResourceMetadataData();
resourceData.getMetadataDataDefinition().setUniqueId(rootResource.getUniqueId());
resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name());
- Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanDao.updateNode(resourceData,
- ResourceMetadataData.class);
+ Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class);
assertTrue(updateNode.isLeft());
- Either<Resource, StorageOperationStatus> fetchRootResource = resourceOperation
- .getResource(rootResource.getUniqueId(), true);
+ Either<Resource, StorageOperationStatus> fetchRootResource = resourceOperation.getResource(rootResource.getUniqueId(), true);
String rootResourceJson = prettyGson.toJson(fetchRootResource.left().value());
log.debug(rootResourceJson);
@@ -840,8 +760,7 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
// OKKKKKKK
// create software component
- Resource softwareComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, softwareCompName,
- "1.0", rootResource.getName(), true, true);
+ Resource softwareComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, softwareCompName, "1.0", rootResource.getName(), true, true);
resourceData.getMetadataDataDefinition().setUniqueId(softwareComponent.getUniqueId());
resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name());
@@ -849,8 +768,7 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
assertTrue(updateNode.isLeft());
// create compute component
- Resource computeComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, computeNodeName,
- "1.0", rootResource.getName(), true, true);
+ Resource computeComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, computeNodeName, "1.0", rootResource.getName(), true, true);
// rollbackAndPrint();
// OKKKKKKKKKK
@@ -863,22 +781,18 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
// create requirement definition
- Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource1 = addRequirementToResource(
- capabilityTypeName1, reqName1, reqNodeName, reqRelationship, softwareComponent);
+ Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource1 = addRequirementToResource(capabilityTypeName1, reqName1, reqNodeName, reqRelationship, softwareComponent);
- Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource2 = addRequirementToResource(
- capabilityTypeName2, reqName2, reqNodeName, reqRelationship, softwareComponent);
+ Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource2 = addRequirementToResource(capabilityTypeName2, reqName2, reqNodeName, reqRelationship, softwareComponent);
// create my resource derived from software component
String MY_RESOURCE = "my-resource";
- Resource resource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, MY_RESOURCE,
- myResourceVersion, softwareComponent.getName(), true, true);
+ Resource resource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, MY_RESOURCE, myResourceVersion, softwareComponent.getName(), true, true);
String serviceName = "myservice.1.0";
String requirementId1 = addRequirementToResource1.left().value().getUniqueId();
String requirementId2 = addRequirementToResource2.left().value().getUniqueId();
- List<ComponentInstance> resInstances = buildServiceAndConnectBetweenResourceInstances(serviceName, resource,
- computeComponent, reqName1, false, capabilty1.getUniqueId(), requirementId1);
+ List<ComponentInstance> resInstances = buildServiceAndConnectBetweenResourceInstances(serviceName, resource, computeComponent, reqName1, false, capabilty1.getUniqueId(), requirementId1);
RequirementAndRelationshipPair relationPair = new RequirementAndRelationshipPair();
relationPair.setRequirement(reqName2);
@@ -886,9 +800,8 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
relationPair.setRequirementUid(requirementId2);
relationPair.setCapabilityOwnerId(resInstances.get(1).getUniqueId());
relationPair.setRequirementOwnerId(resInstances.get(0).getUniqueId());
- Either<RelationshipInstData, TitanOperationStatus> connectResourcesInService1 = resourceInstanceOperation
- .connectResourcesInService(serviceName, NodeTypeEnum.Service, resInstances.get(0).getUniqueId(),
- resInstances.get(1).getUniqueId(), relationPair);
+ Either<RelationshipInstData, TitanOperationStatus> connectResourcesInService1 = resourceInstanceOperation.connectResourcesInService(serviceName, NodeTypeEnum.Service, resInstances.get(0).getUniqueId(), resInstances.get(1).getUniqueId(),
+ relationPair);
assertTrue("check associate resource instances succeed " + reqName2, connectResourcesInService1.isLeft());
// rollbackAndPrint();
@@ -950,10 +863,8 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
relationships.add(immutablePair2);
relation.setRelationships(relationships);
- Either<RequirementCapabilityRelDef, StorageOperationStatus> associateResourceInstances = resourceInstanceOperation
- .associateResourceInstances(serviceName, NodeTypeEnum.Service, relation, true);
- assertTrue("check return code after associating 2 requirements in one request",
- associateResourceInstances.isLeft());
+ Either<RequirementCapabilityRelDef, StorageOperationStatus> associateResourceInstances = resourceInstanceOperation.associateResourceInstances(serviceName, NodeTypeEnum.Service, relation, true, false);
+ assertTrue("check return code after associating 2 requirements in one request", associateResourceInstances.isLeft());
RequirementCapabilityRelDef capabilityRelDef = associateResourceInstances.left().value();
String fromNode = capabilityRelDef.getFromNode();
assertEquals("check from node", resInstances.get(0).getUniqueId(), fromNode);
@@ -979,25 +890,19 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
verifyGetAllResourceInstanceFromService(reqName1, reqName2, serviceName, fromResUid, toResUid);
List<ResourceMetadataData> resourcesPathList = new ArrayList<ResourceMetadataData>();
- TitanOperationStatus findResourcesPathRecursively = resourceOperation
- .findResourcesPathRecursively(resource.getUniqueId(), resourcesPathList);
+ TitanOperationStatus findResourcesPathRecursively = resourceOperation.findResourcesPathRecursively(resource.getUniqueId(), resourcesPathList);
assertEquals("check returned status", TitanOperationStatus.OK, findResourcesPathRecursively);
assertEquals("check list size", 3, resourcesPathList.size());
- TitanOperationStatus validateTheTargetResourceInstance = resourceInstanceOperation
- .validateTheTargetResourceInstance(MY_RESOURCE, resource.getUniqueId());
+ TitanOperationStatus validateTheTargetResourceInstance = resourceInstanceOperation.validateTheTargetResourceInstance(MY_RESOURCE, resource.getUniqueId());
assertEquals("check resource name in the path", TitanOperationStatus.OK, validateTheTargetResourceInstance);
- validateTheTargetResourceInstance = resourceInstanceOperation
- .validateTheTargetResourceInstance(softwareCompName, resource.getUniqueId());
+ validateTheTargetResourceInstance = resourceInstanceOperation.validateTheTargetResourceInstance(softwareCompName, resource.getUniqueId());
assertEquals("check resource name in the path", TitanOperationStatus.OK, validateTheTargetResourceInstance);
- validateTheTargetResourceInstance = resourceInstanceOperation
- .validateTheTargetResourceInstance(softwareCompName + "STAM", resource.getUniqueId());
- assertEquals("check resource name not in the path", TitanOperationStatus.MATCH_NOT_FOUND,
- validateTheTargetResourceInstance);
+ validateTheTargetResourceInstance = resourceInstanceOperation.validateTheTargetResourceInstance(softwareCompName + "STAM", resource.getUniqueId());
+ assertEquals("check resource name not in the path", TitanOperationStatus.MATCH_NOT_FOUND, validateTheTargetResourceInstance);
- Either<ComponentInstance, StorageOperationStatus> deleteResourceInstance = resourceInstanceOperation
- .deleteComponentInstance(NodeTypeEnum.Service, serviceName, toResUid, true);
+ Either<ComponentInstance, StorageOperationStatus> deleteResourceInstance = resourceInstanceOperation.deleteComponentInstance(NodeTypeEnum.Service, serviceName, toResUid, true);
assertTrue("check resource instance was deleted.", deleteResourceInstance.isLeft());
} finally {
@@ -1007,15 +912,13 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
}
- private void verifyGetAllResourceInstanceFromService(String reqName1, String reqName2, String serviceName,
- String fromResUid, String toResUid) {
+ private void verifyGetAllResourceInstanceFromService(String reqName1, String reqName2, String serviceName, String fromResUid, String toResUid) {
- Either<ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>>, StorageOperationStatus> allResourceInstances = resourceInstanceOperation
- .getAllComponentInstances(serviceName, NodeTypeEnum.Service, NodeTypeEnum.Resource, true);
+ Either<ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>>, StorageOperationStatus> allResourceInstances = resourceInstanceOperation.getAllComponentInstances(serviceName, NodeTypeEnum.Service, NodeTypeEnum.Resource,
+ true);
// assertTrue("check return code after get all resource instances",
// associateResourceInstances.isLeft());
- ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>> immutablePair = allResourceInstances
- .left().value();
+ ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>> immutablePair = allResourceInstances.left().value();
List<ComponentInstance> nodes = immutablePair.getKey();
List<RequirementCapabilityRelDef> edges = immutablePair.getValue();
assertEquals("check 2 nodes returned", 2, nodes.size());
@@ -1043,34 +946,31 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
log.debug(edgesStr);
}
- private Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource(String capabilityTypeName1,
- String reqName1, String reqNodeName, String reqRelationship, Resource softwareComponent) {
+ private Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource(String capabilityTypeName1, String reqName1, String reqNodeName, String reqRelationship, Resource softwareComponent) {
RequirementDefinition reqDefinition1 = new RequirementDefinition();
reqDefinition1.setNode(reqNodeName);
reqDefinition1.setRelationship(reqRelationship);
reqDefinition1.setCapability(capabilityTypeName1);
// add requirement to software component
- Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource = requirementOperation
- .addRequirementToResource(reqName1, reqDefinition1, softwareComponent.getUniqueId(), true);
+ Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource = requirementOperation.addRequirementToResource(reqName1, reqDefinition1, softwareComponent.getUniqueId(), true);
assertEquals("check requirement was added", true, addRequirementToResource.isLeft());
return addRequirementToResource;
}
- private CapabilityDefinition addCapabilityToResource(String capabilityTypeName1, String reqName1,
- Resource computeComponent) {
+ private CapabilityDefinition addCapabilityToResource(String capabilityTypeName1, String reqName1, Resource computeComponent) {
CapabilityDefinition capabilityDefinition1 = new CapabilityDefinition();
capabilityDefinition1.setDescription("my capability");
capabilityDefinition1.setType(capabilityTypeName1);
List<String> validSourceTypes = new ArrayList<String>();
validSourceTypes.add("tosca.nodes.SC");
capabilityDefinition1.setValidSourceTypes(validSourceTypes);
- Either<CapabilityDefinition, StorageOperationStatus> addCapability = capabilityOperation
- .addCapability(computeComponent.getUniqueId(), reqName1, capabilityDefinition1, true);
+ Either<CapabilityDefinition, StorageOperationStatus> addCapability = capabilityOperation.addCapability(computeComponent.getUniqueId(), reqName1, capabilityDefinition1, true);
assertTrue("check capability created ", addCapability.isLeft());
return addCapability.left().value();
}
@Test
+ @Ignore
public void testConnectResourceInstancesCapabilityNameDiffFromReqName() {
PrintGraph printGraph1 = new PrintGraph();
@@ -1092,31 +992,26 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
// Create Capability type
CapabilityTypeOperationTest capabilityTypeOperationTest = new CapabilityTypeOperationTest();
capabilityTypeOperationTest.setOperations(titanDao, capabilityTypeOperation);
- CapabilityTypeDefinition createCapabilityDef = capabilityTypeOperationTest
- .createCapability(capabilityTypeName);
+ CapabilityTypeDefinition createCapabilityDef = capabilityTypeOperationTest.createCapability(capabilityTypeName);
ResourceOperationTest resourceOperationTest = new ResourceOperationTest();
resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation);
// create root resource
- Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "1.0", null,
- true, true);
+ Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "1.0", null, true, true);
ResourceMetadataData resourceData = new ResourceMetadataData();
resourceData.getMetadataDataDefinition().setUniqueId(rootResource.getUniqueId());
resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name());
- Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanDao.updateNode(resourceData,
- ResourceMetadataData.class);
+ Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class);
assertTrue(updateNode.isLeft());
- Either<Resource, StorageOperationStatus> fetchRootResource = resourceOperation
- .getResource(rootResource.getUniqueId(), true);
+ Either<Resource, StorageOperationStatus> fetchRootResource = resourceOperation.getResource(rootResource.getUniqueId(), true);
String rootResourceJson = prettyGson.toJson(fetchRootResource.left().value());
log.debug(rootResourceJson);
// create software component
- Resource softwareComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, softwareCompName,
- "1.0", rootResource.getName(), true, true);
+ Resource softwareComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, softwareCompName, "1.0", rootResource.getName(), true, true);
resourceData.getMetadataDataDefinition().setUniqueId(softwareComponent.getUniqueId());
resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name());
@@ -1124,31 +1019,24 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
assertTrue(updateNode.isLeft());
// create compute component
- Resource computeComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, computeNodeName,
- "1.0", rootResource.getName(), true, true);
+ Resource computeComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, computeNodeName, "1.0", rootResource.getName(), true, true);
- CapabilityDefinition capabilty = addCapabilityToResource(capabilityTypeName, DIFFERENT_CAPABILITY,
- computeComponent);
+ CapabilityDefinition capabilty = addCapabilityToResource(capabilityTypeName, DIFFERENT_CAPABILITY, computeComponent);
// create requirement definition
- Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource = addRequirementToResource(
- capabilityTypeName, reqName, reqNodeName, reqRelationship, softwareComponent);
+ Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource = addRequirementToResource(capabilityTypeName, reqName, reqNodeName, reqRelationship, softwareComponent);
String parentReqUniqId = addRequirementToResource.left().value().getUniqueId();
// create my resource derived from software component
- Resource resource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, "my-resource",
- myResourceVersion, softwareComponent.getName(), true, true);
+ Resource resource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, "my-resource", myResourceVersion, softwareComponent.getName(), true, true);
String serviceName = "myservice.1.0";
- List<ComponentInstance> resInstances = buildServiceAndConnectBetweenResourceInstances(serviceName, resource,
- computeComponent, "host", false, capabilty.getUniqueId(), parentReqUniqId);
+ List<ComponentInstance> resInstances = buildServiceAndConnectBetweenResourceInstances(serviceName, resource, computeComponent, "host", false, capabilty.getUniqueId(), parentReqUniqId);
PrintGraph printGraph = new PrintGraph();
- String webGraph = printGraph.buildGraphForWebgraphWiz(titanDao.getGraph().left().value());
- // log.debug(webGraph);
-
+ String webGraph = printGraph.buildGraphForWebgraphWiz(titanDao.getGraph().left().value());
} finally {
rollbackAndPrint();
@@ -1158,6 +1046,7 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
}
@Test
+ @Ignore
public void testConnectResourceInstancesInvalidCapability() {
PrintGraph printGraph1 = new PrintGraph();
@@ -1181,34 +1070,28 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
// Create Capability type
CapabilityTypeOperationTest capabilityTypeOperationTest = new CapabilityTypeOperationTest();
capabilityTypeOperationTest.setOperations(titanDao, capabilityTypeOperation);
- CapabilityTypeDefinition createCapabilityDef = capabilityTypeOperationTest
- .createCapability(capabilityTypeName);
+ CapabilityTypeDefinition createCapabilityDef = capabilityTypeOperationTest.createCapability(capabilityTypeName);
- CapabilityTypeDefinition createCapabilityDef2 = capabilityTypeOperationTest
- .createCapability(capabilityTypeNameOther);
+ CapabilityTypeDefinition createCapabilityDef2 = capabilityTypeOperationTest.createCapability(capabilityTypeNameOther);
ResourceOperationTest resourceOperationTest = new ResourceOperationTest();
resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation);
// create root resource
- Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "1.0", null,
- true, true);
+ Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "1.0", null, true, true);
ResourceMetadataData resourceData = new ResourceMetadataData();
resourceData.getMetadataDataDefinition().setUniqueId(rootResource.getUniqueId());
resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name());
- Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanDao.updateNode(resourceData,
- ResourceMetadataData.class);
+ Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class);
assertTrue(updateNode.isLeft());
- Either<Resource, StorageOperationStatus> fetchRootResource = resourceOperation
- .getResource(rootResource.getUniqueId(), true);
+ Either<Resource, StorageOperationStatus> fetchRootResource = resourceOperation.getResource(rootResource.getUniqueId(), true);
String rootResourceJson = prettyGson.toJson(fetchRootResource.left().value());
log.debug(rootResourceJson);
// create software component
- Resource softwareComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, softwareCompName,
- "1.0", rootResource.getName(), true, true);
+ Resource softwareComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, softwareCompName, "1.0", rootResource.getName(), true, true);
resourceData.getMetadataDataDefinition().setUniqueId(softwareComponent.getUniqueId());
resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name());
@@ -1216,25 +1099,21 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
assertTrue(updateNode.isLeft());
// create compute component
- Resource computeComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, computeNodeName,
- "1.0", rootResource.getName(), true, true);
+ Resource computeComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, computeNodeName, "1.0", rootResource.getName(), true, true);
addCapabilityToResource(capabilityTypeName, DIFFERENT_CAPABILITY, computeComponent);
// create requirement definition
- Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource = addRequirementToResource(
- capabilityTypeNameOther, reqName, reqNodeName, reqRelationship, softwareComponent);
+ Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource = addRequirementToResource(capabilityTypeNameOther, reqName, reqNodeName, reqRelationship, softwareComponent);
String parentReqUniqId = addRequirementToResource.left().value().getUniqueId();
// create my resource derived from software component
- Resource resource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, "my-resource",
- myResourceVersion, softwareComponent.getName(), true, true);
+ Resource resource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, "my-resource", myResourceVersion, softwareComponent.getName(), true, true);
String serviceName = "myservice.1.0";
- List<ComponentInstance> resInstances = buildServiceAndConnectBetweenResourceInstancesWithError(serviceName,
- resource, computeComponent, "host", false, TitanOperationStatus.ILLEGAL_ARGUMENT);
+ List<ComponentInstance> resInstances = buildServiceAndConnectBetweenResourceInstancesWithError(serviceName, resource, computeComponent, "host", false, TitanOperationStatus.ILLEGAL_ARGUMENT);
PrintGraph printGraph = new PrintGraph();
String webGraph = printGraph.buildGraphForWebgraphWiz(titanDao.getGraph().left().value());
@@ -1264,12 +1143,11 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
PrintGraph printGraph2 = new PrintGraph();
int numberOfVerticesCurr = printGraph2.getNumberOfVertices(titanDao.getGraph().left().value());
- assertEquals(
- "check all data deleted from graph " + printGraph2.getVerticesSet(titanDao.getGraph().left().value()),
- numberOfVertices, numberOfVerticesCurr);
+ assertEquals("check all data deleted from graph " + printGraph2.getVerticesSet(titanDao.getGraph().left().value()), numberOfVertices, numberOfVerticesCurr);
}
@Test
+ @Ignore
public void testConnectResourceInstancesRequirementNotFound() {
PrintGraph printGraph1 = new PrintGraph();
@@ -1290,31 +1168,26 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
// Create Capability type
CapabilityTypeOperationTest capabilityTypeOperationTest = new CapabilityTypeOperationTest();
capabilityTypeOperationTest.setOperations(titanDao, capabilityTypeOperation);
- CapabilityTypeDefinition createCapabilityDef = capabilityTypeOperationTest
- .createCapability(capabilityTypeName);
+ CapabilityTypeDefinition createCapabilityDef = capabilityTypeOperationTest.createCapability(capabilityTypeName);
ResourceOperationTest resourceOperationTest = new ResourceOperationTest();
resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation);
// create root resource
- Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "1.0", null,
- true, true);
+ Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "1.0", null, true, true);
ResourceMetadataData resourceData = new ResourceMetadataData();
resourceData.getMetadataDataDefinition().setUniqueId(rootResource.getUniqueId());
resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name());
- Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanDao.updateNode(resourceData,
- ResourceMetadataData.class);
+ Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class);
assertTrue(updateNode.isLeft());
- Either<Resource, StorageOperationStatus> fetchRootResource = resourceOperation
- .getResource(rootResource.getUniqueId(), true);
+ Either<Resource, StorageOperationStatus> fetchRootResource = resourceOperation.getResource(rootResource.getUniqueId(), true);
String rootResourceJson = prettyGson.toJson(fetchRootResource.left().value());
log.debug(rootResourceJson);
// create software component
- Resource softwareComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, softwareCompName,
- "1.0", rootResource.getName(), true, true);
+ Resource softwareComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, softwareCompName, "1.0", rootResource.getName(), true, true);
resourceData.getMetadataDataDefinition().setUniqueId(softwareComponent.getUniqueId());
resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name());
@@ -1322,8 +1195,7 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
assertTrue(updateNode.isLeft());
// create compute component
- Resource computeComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, computeNodeName,
- "1.0", rootResource.getName(), true, true);
+ Resource computeComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, computeNodeName, "1.0", rootResource.getName(), true, true);
addCapabilityToResource(capabilityTypeName, reqName, computeComponent);
@@ -1334,20 +1206,16 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
reqDefinition.setRelationship(reqRelationship);
reqDefinition.setCapability(capabilityTypeName);
// add requirement to software component
- Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource = requirementOperation
- .addRequirementToResource(reqName + "ssssssss", reqDefinition, softwareComponent.getUniqueId(),
- true);
+ Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource = requirementOperation.addRequirementToResource(reqName + "ssssssss", reqDefinition, softwareComponent.getUniqueId(), true);
assertEquals("check requirement was added", true, addRequirementToResource.isLeft());
String parentReqUniqId = addRequirementToResource.left().value().getUniqueId();
// create my resource derived from software component
- Resource resource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, "my-resource",
- myResourceVersion, softwareComponent.getName(), true, true);
+ Resource resource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, "my-resource", myResourceVersion, softwareComponent.getName(), true, true);
String serviceName = "myservice.1.0";
- List<ComponentInstance> resInstances = buildServiceAndConnectBetweenResourceInstancesWithError(serviceName,
- resource, computeComponent, "host", false, TitanOperationStatus.ILLEGAL_ARGUMENT);
+ List<ComponentInstance> resInstances = buildServiceAndConnectBetweenResourceInstancesWithError(serviceName, resource, computeComponent, "host", false, TitanOperationStatus.ILLEGAL_ARGUMENT);
PrintGraph printGraph = new PrintGraph();
String webGraph = printGraph.buildGraphForWebgraphWiz(titanDao.getGraph().left().value());
@@ -1363,19 +1231,15 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
private void disconnectResourcesInService(String serviceName, RequirementCapabilityRelDef reqCapDef) {
- Either<List<RelationshipInstData>, TitanOperationStatus> disconnectResourcesInService = resourceInstanceOperation
- .disconnectResourcesInService(serviceName, NodeTypeEnum.Service, reqCapDef);
+ Either<List<RelationshipInstData>, TitanOperationStatus> disconnectResourcesInService = resourceInstanceOperation.disconnectResourcesInService(serviceName, NodeTypeEnum.Service, reqCapDef);
assertTrue("check relatioship instance was deleted", disconnectResourcesInService.isLeft());
- disconnectResourcesInService = resourceInstanceOperation.disconnectResourcesInService(serviceName,
- NodeTypeEnum.Service, reqCapDef);
+ disconnectResourcesInService = resourceInstanceOperation.disconnectResourcesInService(serviceName, NodeTypeEnum.Service, reqCapDef);
assertTrue("check relatioship instance already was deleted", disconnectResourcesInService.isRight());
- assertEquals("check relatioship instance already was deleted. status NOT_FOUND", TitanOperationStatus.NOT_FOUND,
- disconnectResourcesInService.right().value());
+ assertEquals("check relatioship instance already was deleted. status NOT_FOUND", TitanOperationStatus.NOT_FOUND, disconnectResourcesInService.right().value());
}
- private List<ComponentInstance> buildServiceAndConnectBetweenResourceInstancesWithError(String serviceName,
- Resource resource, Resource computeComponent, String requirement, boolean ignoreCreatingService,
+ private List<ComponentInstance> buildServiceAndConnectBetweenResourceInstancesWithError(String serviceName, Resource resource, Resource computeComponent, String requirement, boolean ignoreCreatingService,
TitanOperationStatus titanOperationStatus) {
String serviceId = "myservice.1.0";
@@ -1385,30 +1249,22 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
}
ComponentInstance myresourceInstance = buildResourceInstance(resource.getUniqueId(), "1", resource.getName());
- ComponentInstance computeInstance = buildResourceInstance(computeComponent.getUniqueId(), "2",
- computeComponent.getName());
+ ComponentInstance computeInstance = buildResourceInstance(computeComponent.getUniqueId(), "2", computeComponent.getName());
- Either<ComponentInstance, TitanOperationStatus> myinstanceRes = resourceInstanceOperation
- .addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "1", true,
- myresourceInstance, NodeTypeEnum.Resource, false);
+ Either<ComponentInstance, TitanOperationStatus> myinstanceRes = resourceInstanceOperation.addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "1", true, myresourceInstance, NodeTypeEnum.Resource, false);
assertTrue("check instance added to service", myinstanceRes.isLeft());
ComponentInstance value1 = myinstanceRes.left().value();
- Either<ComponentInstance, TitanOperationStatus> computeInstTes = resourceInstanceOperation
- .addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "2", true, computeInstance,
- NodeTypeEnum.Resource, false);
+ Either<ComponentInstance, TitanOperationStatus> computeInstTes = resourceInstanceOperation.addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "2", true, computeInstance, NodeTypeEnum.Resource, false);
assertTrue("check instance added to service", computeInstTes.isLeft());
ComponentInstance value2 = computeInstTes.left().value();
RequirementAndRelationshipPair relationPair = new RequirementAndRelationshipPair();
relationPair.setRequirement(requirement);
- Either<RelationshipInstData, TitanOperationStatus> connectResourcesInService = resourceInstanceOperation
- .connectResourcesInService(serviceId, NodeTypeEnum.Service, value1.getUniqueId(), value2.getUniqueId(),
- relationPair);
+ Either<RelationshipInstData, TitanOperationStatus> connectResourcesInService = resourceInstanceOperation.connectResourcesInService(serviceId, NodeTypeEnum.Service, value1.getUniqueId(), value2.getUniqueId(), relationPair);
assertTrue("check relation was not created", connectResourcesInService.isRight());
- assertEquals("check error code after connect resource instances failed", titanOperationStatus,
- connectResourcesInService.right().value());
+ assertEquals("check error code after connect resource instances failed", titanOperationStatus, connectResourcesInService.right().value());
List<ComponentInstance> resInstances = new ArrayList<ComponentInstance>();
resInstances.add(value1);
@@ -1417,9 +1273,7 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
}
- private List<ComponentInstance> buildServiceAndConnectBetweenResourceInstances(String serviceName,
- Resource resource, Resource computeComponent, String requirement, boolean ignoreCreatingService,
- String capabilityId, String requirementId) {
+ private List<ComponentInstance> buildServiceAndConnectBetweenResourceInstances(String serviceName, Resource resource, Resource computeComponent, String requirement, boolean ignoreCreatingService, String capabilityId, String requirementId) {
String serviceId = "myservice.1.0";
@@ -1428,17 +1282,12 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
}
ComponentInstance myresourceInstance = buildResourceInstance(resource.getUniqueId(), "1", resource.getName());
- ComponentInstance computeInstance = buildResourceInstance(computeComponent.getUniqueId(), "2",
- computeComponent.getName());
+ ComponentInstance computeInstance = buildResourceInstance(computeComponent.getUniqueId(), "2", computeComponent.getName());
- Either<ComponentInstance, TitanOperationStatus> myinstanceRes = resourceInstanceOperation
- .addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "1", true,
- myresourceInstance, NodeTypeEnum.Resource, false);
+ Either<ComponentInstance, TitanOperationStatus> myinstanceRes = resourceInstanceOperation.addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "1", true, myresourceInstance, NodeTypeEnum.Resource, false);
assertTrue("check instance added to service", myinstanceRes.isLeft());
ComponentInstance value1 = myinstanceRes.left().value();
- Either<ComponentInstance, TitanOperationStatus> computeInstTes = resourceInstanceOperation
- .addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "2", true, computeInstance,
- NodeTypeEnum.Resource, false);
+ Either<ComponentInstance, TitanOperationStatus> computeInstTes = resourceInstanceOperation.addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "2", true, computeInstance, NodeTypeEnum.Resource, false);
assertTrue("check instance added to service", computeInstTes.isLeft());
ComponentInstance value2 = computeInstTes.left().value();
RequirementAndRelationshipPair relationPair = new RequirementAndRelationshipPair();
@@ -1449,9 +1298,7 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
relationPair.setRequirementOwnerId(value1.getUniqueId());
relationPair.setCapabilityOwnerId(value2.getUniqueId());
- Either<RelationshipInstData, TitanOperationStatus> connectResourcesInService = resourceInstanceOperation
- .connectResourcesInService(serviceId, NodeTypeEnum.Service, value1.getUniqueId(), value2.getUniqueId(),
- relationPair);
+ Either<RelationshipInstData, TitanOperationStatus> connectResourcesInService = resourceInstanceOperation.connectResourcesInService(serviceId, NodeTypeEnum.Service, value1.getUniqueId(), value2.getUniqueId(), relationPair);
assertTrue("check relation created", connectResourcesInService.isLeft());
@@ -1464,6 +1311,7 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
}
@Test
+ @Ignore
public void getAllResourceInstancesThree() {
PrintGraph printGraph1 = new PrintGraph();
@@ -1484,31 +1332,26 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
// Create Capability type
CapabilityTypeOperationTest capabilityTypeOperationTest = new CapabilityTypeOperationTest();
capabilityTypeOperationTest.setOperations(titanDao, capabilityTypeOperation);
- CapabilityTypeDefinition createCapabilityDef = capabilityTypeOperationTest
- .createCapability(capabilityTypeName);
+ CapabilityTypeDefinition createCapabilityDef = capabilityTypeOperationTest.createCapability(capabilityTypeName);
ResourceOperationTest resourceOperationTest = new ResourceOperationTest();
resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation);
// create root resource
- Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "1.0", null,
- true, true);
+ Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "1.0", null, true, true);
ResourceMetadataData resourceData = new ResourceMetadataData();
resourceData.getMetadataDataDefinition().setUniqueId(rootResource.getUniqueId());
resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name());
- Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanDao.updateNode(resourceData,
- ResourceMetadataData.class);
+ Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class);
assertTrue(updateNode.isLeft());
- Either<Resource, StorageOperationStatus> fetchRootResource = resourceOperation
- .getResource(rootResource.getUniqueId(), true);
+ Either<Resource, StorageOperationStatus> fetchRootResource = resourceOperation.getResource(rootResource.getUniqueId(), true);
String rootResourceJson = prettyGson.toJson(fetchRootResource.left().value());
log.debug(rootResourceJson);
// create software component
- Resource softwareComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, softwareCompName,
- "1.0", rootResource.getName(), true, true);
+ Resource softwareComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, softwareCompName, "1.0", rootResource.getName(), true, true);
resourceData.getMetadataDataDefinition().setUniqueId(softwareComponent.getUniqueId());
resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name());
@@ -1516,8 +1359,7 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
assertTrue(updateNode.isLeft());
// create compute component
- Resource computeComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, computeNodeName,
- "1.0", rootResource.getName(), true, true);
+ Resource computeComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, computeNodeName, "1.0", rootResource.getName(), true, true);
// rollbackAndPrint();
@@ -1526,56 +1368,45 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
// create requirement definition
- Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource = addRequirementToResource(
- capabilityTypeName, reqName, reqNodeName, reqRelationship, softwareComponent);
+ Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource = addRequirementToResource(capabilityTypeName, reqName, reqNodeName, reqRelationship, softwareComponent);
String parentReqUniqId = addRequirementToResource.left().value().getUniqueId();
// create my resource derived from software component
- Resource resource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, "my-resource",
- myResourceVersion, softwareComponent.getName(), true, true);
+ Resource resource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, "my-resource", myResourceVersion, softwareComponent.getName(), true, true);
String serviceId = "myservice.1.0";
ServiceMetadataData createService = createService(serviceId);
- Either<ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>>, StorageOperationStatus> allResourceInstances = resourceInstanceOperation
- .getAllComponentInstances(serviceId, NodeTypeEnum.Service, NodeTypeEnum.Resource, true);
+ Either<ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>>, StorageOperationStatus> allResourceInstances = resourceInstanceOperation.getAllComponentInstances(serviceId, NodeTypeEnum.Service, NodeTypeEnum.Resource,
+ true);
assertTrue("check NOT_FOUND is returned", allResourceInstances.isRight());
- assertEquals("check NOT_FOUND is returned", allResourceInstances.right().value(),
- StorageOperationStatus.NOT_FOUND);
+ assertEquals("check NOT_FOUND is returned", allResourceInstances.right().value(), StorageOperationStatus.NOT_FOUND);
ComponentInstance myresourceInstance = buildResourceInstance(resource.getUniqueId(), "1", "my-resource");
myresourceInstance.setName("my-resource");
- ComponentInstance computeInstance1 = buildResourceInstance(computeComponent.getUniqueId(), "2",
- "tosca.nodes.Compute2");
+ ComponentInstance computeInstance1 = buildResourceInstance(computeComponent.getUniqueId(), "2", "tosca.nodes.Compute2");
- Either<ComponentInstance, TitanOperationStatus> myinstanceRes = resourceInstanceOperation
- .addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "1", true,
- myresourceInstance, NodeTypeEnum.Resource, false);
+ Either<ComponentInstance, TitanOperationStatus> myinstanceRes = resourceInstanceOperation.addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "1", true, myresourceInstance, NodeTypeEnum.Resource, false);
assertTrue("check instance added to service", myinstanceRes.isLeft());
ComponentInstance value1 = myinstanceRes.left().value();
- allResourceInstances = resourceInstanceOperation.getAllComponentInstances(serviceId, NodeTypeEnum.Service,
- NodeTypeEnum.Resource, true);
+ allResourceInstances = resourceInstanceOperation.getAllComponentInstances(serviceId, NodeTypeEnum.Service, NodeTypeEnum.Resource, true);
assertTrue("check resource instances found", allResourceInstances.isLeft());
- ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>> immutablePair = allResourceInstances
- .left().value();
+ ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>> immutablePair = allResourceInstances.left().value();
List<ComponentInstance> nodes = immutablePair.getKey();
List<RequirementCapabilityRelDef> edges = immutablePair.getValue();
assertEquals("check resource instances size", 1, nodes.size());
assertEquals("check resource instances size", 0, edges.size());
- Either<ComponentInstance, TitanOperationStatus> computeInstTes = resourceInstanceOperation
- .addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "2", true,
- computeInstance1, NodeTypeEnum.Resource, false);
+ Either<ComponentInstance, TitanOperationStatus> computeInstTes = resourceInstanceOperation.addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "2", true, computeInstance1, NodeTypeEnum.Resource, false);
assertTrue("check instance added to service", computeInstTes.isLeft());
ComponentInstance value2 = computeInstTes.left().value();
- allResourceInstances = resourceInstanceOperation.getAllComponentInstances(serviceId, NodeTypeEnum.Service,
- NodeTypeEnum.Resource, true);
+ allResourceInstances = resourceInstanceOperation.getAllComponentInstances(serviceId, NodeTypeEnum.Service, NodeTypeEnum.Resource, true);
assertTrue("check resource instances found", allResourceInstances.isLeft());
immutablePair = allResourceInstances.left().value();
nodes = immutablePair.getKey();
@@ -1592,14 +1423,11 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
relationPair.setRequirementOwnerId(value1.getUniqueId());
relationPair.setCapabilityOwnerId(value2.getUniqueId());
- Either<RelationshipInstData, TitanOperationStatus> connectResourcesInService = resourceInstanceOperation
- .connectResourcesInService(serviceId, NodeTypeEnum.Service, value1.getUniqueId(),
- value2.getUniqueId(), relationPair);
+ Either<RelationshipInstData, TitanOperationStatus> connectResourcesInService = resourceInstanceOperation.connectResourcesInService(serviceId, NodeTypeEnum.Service, value1.getUniqueId(), value2.getUniqueId(), relationPair);
assertTrue("check relation created", connectResourcesInService.isLeft());
- allResourceInstances = resourceInstanceOperation.getAllComponentInstances(serviceId, NodeTypeEnum.Service,
- NodeTypeEnum.Resource, true);
+ allResourceInstances = resourceInstanceOperation.getAllComponentInstances(serviceId, NodeTypeEnum.Service, NodeTypeEnum.Resource, true);
assertTrue("check resource instances found", allResourceInstances.isLeft());
immutablePair = allResourceInstances.left().value();
nodes = immutablePair.getKey();
@@ -1614,22 +1442,18 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
ComponentInstance myresourceInstance2 = buildResourceInstance(resource.getUniqueId(), "1", "myresource2");
- Either<ComponentInstance, TitanOperationStatus> newResource = resourceInstanceOperation
- .addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "3", true,
- myresourceInstance2, NodeTypeEnum.Resource, false);
+ Either<ComponentInstance, TitanOperationStatus> newResource = resourceInstanceOperation.addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "3", true, myresourceInstance2, NodeTypeEnum.Resource, false);
assertTrue("added resource instance successfully", newResource.isLeft());
relationPair.setRequirement(requirement);
relationPair.setRequirementOwnerId(newResource.left().value().getUniqueId());
- Either<RelationshipInstData, TitanOperationStatus> connectResourcesInService2 = resourceInstanceOperation
- .connectResourcesInService(serviceId, NodeTypeEnum.Service,
- newResource.left().value().getUniqueId(), value2.getUniqueId(), relationPair);
+ Either<RelationshipInstData, TitanOperationStatus> connectResourcesInService2 = resourceInstanceOperation.connectResourcesInService(serviceId, NodeTypeEnum.Service, newResource.left().value().getUniqueId(), value2.getUniqueId(),
+ relationPair);
assertTrue("check resource instance was added to service", connectResourcesInService2.isLeft());
- allResourceInstances = resourceInstanceOperation.getAllComponentInstances(serviceId, NodeTypeEnum.Service,
- NodeTypeEnum.Resource, true);
+ allResourceInstances = resourceInstanceOperation.getAllComponentInstances(serviceId, NodeTypeEnum.Service, NodeTypeEnum.Resource, true);
assertTrue("check resource instances found", allResourceInstances.isLeft());
immutablePair = allResourceInstances.left().value();
nodes = immutablePair.getKey();
@@ -1638,32 +1462,24 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
assertEquals("check resource instances size", 3, nodes.size());
assertEquals("check resource instances size", 2, edges.size());
- Either<List<ComponentInstance>, TitanOperationStatus> deleteAllResourceInstancesOfService = resourceInstanceOperation
- .deleteAllComponentInstancesInternal(serviceId, NodeTypeEnum.Service);
+ Either<List<ComponentInstance>, TitanOperationStatus> deleteAllResourceInstancesOfService = resourceInstanceOperation.deleteAllComponentInstancesInternal(serviceId, NodeTypeEnum.Service);
assertTrue("check resource instances was deleted.", deleteAllResourceInstancesOfService.isLeft());
- assertEquals("check number of deleted resource instances.", 3,
- deleteAllResourceInstancesOfService.left().value().size());
+ assertEquals("check number of deleted resource instances.", 3, deleteAllResourceInstancesOfService.left().value().size());
- Either<List<RelationshipInstData>, TitanOperationStatus> allRelatinshipInst = titanDao
- .getAll(NodeTypeEnum.RelationshipInst, RelationshipInstData.class);
+ Either<List<RelationshipInstData>, TitanOperationStatus> allRelatinshipInst = titanDao.getAll(NodeTypeEnum.RelationshipInst, RelationshipInstData.class);
assertTrue("allRelatinshipInst is empty", allRelatinshipInst.isRight());
- assertEquals("allRelatinshipInst result is NOT_FOUND", TitanOperationStatus.NOT_FOUND,
- allRelatinshipInst.right().value());
+ assertEquals("allRelatinshipInst result is NOT_FOUND", TitanOperationStatus.NOT_FOUND, allRelatinshipInst.right().value());
- Either<Resource, StorageOperationStatus> deleteComputeResource = resourceOperation
- .deleteResource(computeComponent.getUniqueId(), true);
+ Either<Resource, StorageOperationStatus> deleteComputeResource = resourceOperation.deleteResource(computeComponent.getUniqueId(), true);
assertTrue("delete compute resource succeed", deleteComputeResource.isLeft());
- Either<Resource, StorageOperationStatus> deleteSCResource = resourceOperation
- .deleteResource(softwareComponent.getUniqueId(), true);
+ Either<Resource, StorageOperationStatus> deleteSCResource = resourceOperation.deleteResource(softwareComponent.getUniqueId(), true);
assertTrue("delete software component resource succeed", deleteSCResource.isLeft());
- Either<Resource, StorageOperationStatus> deleteMyResource = resourceOperation
- .deleteResource(resource.getUniqueId(), true);
+ Either<Resource, StorageOperationStatus> deleteMyResource = resourceOperation.deleteResource(resource.getUniqueId(), true);
assertTrue("delete my resource succeed", deleteMyResource.isLeft());
- Either<Resource, StorageOperationStatus> rootResourceDeleted = resourceOperation
- .deleteResource(rootResource.getUniqueId(), true);
+ Either<Resource, StorageOperationStatus> rootResourceDeleted = resourceOperation.deleteResource(rootResource.getUniqueId(), true);
assertTrue("delete root resource succeed", rootResourceDeleted.isLeft());
Set<String> vertexSetAfterDelete = printGraph1.getVerticesSet(titanDao.getGraph().left().value());
@@ -1699,8 +1515,7 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
resourceData1.getMetadataDataDefinition().setState(state);
resourceData1.getMetadataDataDefinition().setHighestVersion(true);
resourceData1.getMetadataDataDefinition().setContactId("contactId");
- Either<ResourceMetadataData, TitanOperationStatus> createNode1 = titanDao.createNode(resourceData1,
- ResourceMetadataData.class);
+ Either<ResourceMetadataData, TitanOperationStatus> createNode1 = titanDao.createNode(resourceData1, ResourceMetadataData.class);
log.debug("{}", createNode1);
@@ -1721,17 +1536,25 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
resourceData1.getMetadataDataDefinition().setState(state);
resourceData1.getMetadataDataDefinition().setHighestVersion(true);
resourceData1.getMetadataDataDefinition().setContactId("contactId");
- Either<ResourceMetadataData, TitanOperationStatus> createNode1 = titanDao.createNode(resourceData1,
- ResourceMetadataData.class);
+ Either<ResourceMetadataData, TitanOperationStatus> createNode1 = titanDao.createNode(resourceData1, ResourceMetadataData.class);
log.debug("{}", createNode1);
titanDao.commit();
+ // resourceData1.setUniqueId(name + "." + "2.0");
+ // resourceData1.setHighestVersion(true);
+ // resourceData1.setContactId("contactId");
+ //
+ // Either<ResourceData, TitanOperationStatus> createNode2 = titanDao
+ // .createNode(resourceData1, ResourceData.class);
+ // System.out.println(createNode2);
+ //
+ // titanDao.commit();
+
// resourceData1.setHighestVersion(false);
resourceData1.getMetadataDataDefinition().setContactId("222contactId222");
- Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanDao.updateNode(resourceData1,
- ResourceMetadataData.class);
+ Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanDao.updateNode(resourceData1, ResourceMetadataData.class);
titanDao.commit();
@@ -1765,8 +1588,7 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
propertiesToMatch.put(GraphPropertiesDictionary.CONTACT_ID.getProperty(), "contactId");
// propertiesToMatch.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(),
// true);
- Either<List<ResourceMetadataData>, TitanOperationStatus> byCriteria = titanDao
- .getByCriteria(NodeTypeEnum.Resource, propertiesToMatch, ResourceMetadataData.class);
+ Either<List<ResourceMetadataData>, TitanOperationStatus> byCriteria = titanDao.getByCriteria(NodeTypeEnum.Resource, propertiesToMatch, ResourceMetadataData.class);
return byCriteria;
}
@@ -1790,53 +1612,40 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation);
// create root resource
- Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "1.0", null,
- true, true);
+ Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "1.0", null, true, true);
ResourceMetadataData resourceData = new ResourceMetadataData();
resourceData.getMetadataDataDefinition().setUniqueId(rootResource.getUniqueId());
resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name());
- Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanDao.updateNode(resourceData,
- ResourceMetadataData.class);
+ Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class);
assertTrue(updateNode.isLeft());
- Either<Resource, StorageOperationStatus> fetchRootResource = resourceOperation
- .getResource(rootResource.getUniqueId(), true);
+ Either<Resource, StorageOperationStatus> fetchRootResource = resourceOperation.getResource(rootResource.getUniqueId(), true);
// create software component
- Resource softwareComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, softwareCompName,
- "1.0", rootResource.getName(), true, true);
+ Resource softwareComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, softwareCompName, "1.0", rootResource.getName(), true, true);
resourceData.getMetadataDataDefinition().setUniqueId(softwareComponent.getUniqueId());
resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name());
updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class);
assertTrue(updateNode.isLeft());
- ComponentInstance myresourceInstance = buildResourceInstance(softwareComponent.getUniqueId(), "1",
- softwareCompName);
+ ComponentInstance myresourceInstance = buildResourceInstance(softwareComponent.getUniqueId(), "1", softwareCompName);
String serviceName = "myservice.1.0";
ServiceMetadataData createService = createService(serviceName);
- Either<ComponentInstance, StorageOperationStatus> myinstanceRes1 = resourceInstanceOperation
- .createComponentInstance(serviceName, NodeTypeEnum.Service, "1", myresourceInstance,
- NodeTypeEnum.Resource, true);
+ Either<ComponentInstance, StorageOperationStatus> myinstanceRes1 = resourceInstanceOperation.createComponentInstance(serviceName, NodeTypeEnum.Service, "1", myresourceInstance, NodeTypeEnum.Resource, true);
assertTrue("check resource instance was created", myinstanceRes1.isLeft());
- Either<ComponentInstance, StorageOperationStatus> myinstanceRes2 = resourceInstanceOperation
- .createComponentInstance(serviceName, NodeTypeEnum.Service, "1", myresourceInstance,
- NodeTypeEnum.Resource, true);
+ Either<ComponentInstance, StorageOperationStatus> myinstanceRes2 = resourceInstanceOperation.createComponentInstance(serviceName, NodeTypeEnum.Service, "1", myresourceInstance, NodeTypeEnum.Resource, true);
assertTrue("check resource instance was not created", myinstanceRes2.isRight());
assertEquals("check error code", StorageOperationStatus.SCHEMA_VIOLATION, myinstanceRes2.right().value());
- Either<ComponentInstance, StorageOperationStatus> deleteResourceInstance = resourceInstanceOperation
- .deleteComponentInstance(NodeTypeEnum.Service, serviceName,
- myinstanceRes1.left().value().getUniqueId(), true);
+ Either<ComponentInstance, StorageOperationStatus> deleteResourceInstance = resourceInstanceOperation.deleteComponentInstance(NodeTypeEnum.Service, serviceName, myinstanceRes1.left().value().getUniqueId(), true);
assertTrue("check resource instance was deleted", deleteResourceInstance.isLeft());
- deleteResourceInstance = resourceInstanceOperation.deleteComponentInstance(NodeTypeEnum.Service,
- serviceName, myinstanceRes1.left().value().getUniqueId(), true);
+ deleteResourceInstance = resourceInstanceOperation.deleteComponentInstance(NodeTypeEnum.Service, serviceName, myinstanceRes1.left().value().getUniqueId(), true);
assertTrue("check resource instance was not deleted", deleteResourceInstance.isRight());
- assertEquals("check resource instance was not deleted", StorageOperationStatus.NOT_FOUND,
- deleteResourceInstance.right().value());
+ assertEquals("check resource instance was not deleted", StorageOperationStatus.NOT_FOUND, deleteResourceInstance.right().value());
} finally {
rollbackAndPrint(false);
@@ -1846,6 +1655,7 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
}
@Test
+ @Ignore
public void testConnectResourceInstancesTwice() {
PrintGraph printGraph1 = new PrintGraph();
@@ -1867,34 +1677,28 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
// Create Capability type
CapabilityTypeOperationTest capabilityTypeOperationTest = new CapabilityTypeOperationTest();
capabilityTypeOperationTest.setOperations(titanDao, capabilityTypeOperation);
- CapabilityTypeDefinition createCapabilityDef1 = capabilityTypeOperationTest
- .createCapability(capabilityTypeName1);
- CapabilityTypeDefinition createCapabilityDef2 = capabilityTypeOperationTest
- .createCapability(capabilityTypeName2);
+ CapabilityTypeDefinition createCapabilityDef1 = capabilityTypeOperationTest.createCapability(capabilityTypeName1);
+ CapabilityTypeDefinition createCapabilityDef2 = capabilityTypeOperationTest.createCapability(capabilityTypeName2);
ResourceOperationTest resourceOperationTest = new ResourceOperationTest();
resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation);
// create root resource
- Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "1.0", null,
- true, true);
+ Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "1.0", null, true, true);
ResourceMetadataData resourceData = new ResourceMetadataData();
resourceData.getMetadataDataDefinition().setUniqueId(rootResource.getUniqueId());
resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name());
- Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanDao.updateNode(resourceData,
- ResourceMetadataData.class);
+ Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class);
assertTrue(updateNode.isLeft());
- Either<Resource, StorageOperationStatus> fetchRootResource = resourceOperation
- .getResource(rootResource.getUniqueId(), true);
+ Either<Resource, StorageOperationStatus> fetchRootResource = resourceOperation.getResource(rootResource.getUniqueId(), true);
String rootResourceJson = prettyGson.toJson(fetchRootResource.left().value());
log.debug(rootResourceJson);
// create software component
- Resource softwareComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, softwareCompName,
- "1.0", rootResource.getName(), true, true);
+ Resource softwareComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, softwareCompName, "1.0", rootResource.getName(), true, true);
resourceData.getMetadataDataDefinition().setUniqueId(softwareComponent.getUniqueId());
resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name());
@@ -1902,8 +1706,7 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
assertTrue(updateNode.isLeft());
// create compute component
- Resource computeComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, computeNodeName,
- "1.0", rootResource.getName(), true, true);
+ Resource computeComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, computeNodeName, "1.0", rootResource.getName(), true, true);
// Add capabilities to Compute Resource
CapabilityDefinition capabilty1 = addCapabilityToResource(capabilityTypeName1, reqName1, computeComponent);
@@ -1913,31 +1716,24 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
// create requirement definition
- Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource = addRequirementToResource(
- capabilityTypeName1, reqName1, reqNodeName, reqRelationship, softwareComponent);
+ Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource = addRequirementToResource(capabilityTypeName1, reqName1, reqNodeName, reqRelationship, softwareComponent);
String parentReqUniqId = addRequirementToResource.left().value().getUniqueId();
// create my resource derived from software component
- Resource resource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, "my-resource",
- myResourceVersion, softwareComponent.getName(), true, true);
+ Resource resource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, "my-resource", myResourceVersion, softwareComponent.getName(), true, true);
String serviceId = "myservice.1.0";
ServiceMetadataData createService = createService(serviceId);
ComponentInstance myresourceInstance = buildResourceInstance(resource.getUniqueId(), "1", "my-resource");
- ComponentInstance computeInstance = buildResourceInstance(computeComponent.getUniqueId(), "2",
- computeNodeName);
+ ComponentInstance computeInstance = buildResourceInstance(computeComponent.getUniqueId(), "2", computeNodeName);
- Either<ComponentInstance, TitanOperationStatus> myinstanceRes = resourceInstanceOperation
- .addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "1", true,
- myresourceInstance, NodeTypeEnum.Resource, false);
+ Either<ComponentInstance, TitanOperationStatus> myinstanceRes = resourceInstanceOperation.addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "1", true, myresourceInstance, NodeTypeEnum.Resource, false);
assertTrue("check instance added to service", myinstanceRes.isLeft());
ComponentInstance value1 = myinstanceRes.left().value();
- Either<ComponentInstance, TitanOperationStatus> computeInstTes = resourceInstanceOperation
- .addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "2", true,
- computeInstance, NodeTypeEnum.Resource, false);
+ Either<ComponentInstance, TitanOperationStatus> computeInstTes = resourceInstanceOperation.addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "2", true, computeInstance, NodeTypeEnum.Resource, false);
assertTrue("check instance added to service", computeInstTes.isLeft());
ComponentInstance value2 = computeInstTes.left().value();
@@ -1956,8 +1752,7 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
relation.setRelationships(relationships);
- Either<RequirementCapabilityRelDef, StorageOperationStatus> connectResourcesInService = resourceInstanceOperation
- .associateResourceInstances(serviceId, NodeTypeEnum.Service, relation, true);
+ Either<RequirementCapabilityRelDef, StorageOperationStatus> connectResourcesInService = resourceInstanceOperation.associateResourceInstances(serviceId, NodeTypeEnum.Service, relation, true, false);
assertTrue("check association succeed", connectResourcesInService.isLeft());
relationships.clear();
@@ -1967,23 +1762,18 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
relationships.add(immutablePair2);
RequirementCapabilityRelDef firstRelation = connectResourcesInService.left().value();
- connectResourcesInService = resourceInstanceOperation.associateResourceInstances(serviceId,
- NodeTypeEnum.Service, relation, true);
+ connectResourcesInService = resourceInstanceOperation.associateResourceInstances(serviceId, NodeTypeEnum.Service, relation, true, false);
assertTrue("check association succeed", connectResourcesInService.isRight());
- assertEquals("check association failed", StorageOperationStatus.MATCH_NOT_FOUND,
- connectResourcesInService.right().value());
+ assertEquals("check association failed", StorageOperationStatus.MATCH_NOT_FOUND, connectResourcesInService.right().value());
- Either<RequirementCapabilityRelDef, StorageOperationStatus> disconnectResourcesInService = resourceInstanceOperation
- .dissociateResourceInstances(serviceId, NodeTypeEnum.Service, firstRelation, true);
+ Either<RequirementCapabilityRelDef, StorageOperationStatus> disconnectResourcesInService = resourceInstanceOperation.dissociateResourceInstances(serviceId, NodeTypeEnum.Service, firstRelation, true);
assertTrue("check dissociation succeed", disconnectResourcesInService.isLeft());
- disconnectResourcesInService = resourceInstanceOperation.dissociateResourceInstances(serviceId,
- NodeTypeEnum.Service, relation, true);
+ disconnectResourcesInService = resourceInstanceOperation.dissociateResourceInstances(serviceId, NodeTypeEnum.Service, relation, true);
assertTrue("check dissociation failed", disconnectResourcesInService.isRight());
- assertEquals("check association failed", StorageOperationStatus.NOT_FOUND,
- disconnectResourcesInService.right().value());
+ assertEquals("check association failed", StorageOperationStatus.NOT_FOUND, disconnectResourcesInService.right().value());
} finally {
rollbackAndPrint();
compareGraphSize(numberOfVertices);
@@ -1991,16 +1781,14 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
}
- private Resource createComputeWithCapability(String capabilityTypeName, String computeNodeName,
- ResourceOperationTest resourceOperationTest, Resource rootResource) {
+ private Resource createComputeWithCapability(String capabilityTypeName, String computeNodeName, ResourceOperationTest resourceOperationTest, Resource rootResource) {
// create compute component
// String id = UniqueIdBuilder.buildResourceUniqueId(computeNodeName,
// "1.0");
// if (resourceOperation.getResource(id).isLeft()){
// resourceOperation.deleteResource(id);
// }
- Either<List<Resource>, StorageOperationStatus> oldResource = resourceOperation
- .getResourceByNameAndVersion(computeNodeName, "1.0", false);
+ Either<List<Resource>, StorageOperationStatus> oldResource = resourceOperation.getResourceByNameAndVersion(computeNodeName, "1.0", false);
if (oldResource.isLeft()) {
for (Resource old : oldResource.left().value()) {
if (old.getResourceType().equals(ResourceTypeEnum.VFC)) {
@@ -2010,8 +1798,7 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
}
- Resource computeComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, computeNodeName, "1.0",
- rootResource.getName(), true, true);
+ Resource computeComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, computeNodeName, "1.0", rootResource.getName(), true, true);
// rollbackAndPrint();
@@ -2020,9 +1807,7 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
return resourceOperation.getResource(computeComponent.getUniqueId()).left().value();
}
- private Resource createSoftwareComponentWithReq(String softwareCompName,
- ResourceOperationTest resourceOperationTest, Resource rootResource, String capabilityTypeName,
- String reqName, String reqRelationship, String reqNodeName) {
+ private Resource createSoftwareComponentWithReq(String softwareCompName, ResourceOperationTest resourceOperationTest, Resource rootResource, String capabilityTypeName, String reqName, String reqRelationship, String reqNodeName) {
Either<ResourceMetadataData, TitanOperationStatus> updateNode;
ResourceMetadataData resourceData = new ResourceMetadataData();
// create software component
@@ -2031,8 +1816,7 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
// if (resourceOperation.getResource(id).isLeft()){
// resourceOperation.deleteResource(id);
// }
- Either<List<Resource>, StorageOperationStatus> oldResource = resourceOperation
- .getResourceByNameAndVersion(softwareCompName, "1.0", false);
+ Either<List<Resource>, StorageOperationStatus> oldResource = resourceOperation.getResourceByNameAndVersion(softwareCompName, "1.0", false);
if (oldResource.isLeft()) {
if (oldResource.isLeft()) {
for (Resource old : oldResource.left().value()) {
@@ -2044,16 +1828,14 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
}
}
- Resource softwareComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, softwareCompName,
- "1.0", rootResource.getName(), true, true);
+ Resource softwareComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, softwareCompName, "1.0", rootResource.getName(), true, true);
resourceData.getMetadataDataDefinition().setUniqueId(softwareComponent.getUniqueId());
resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name());
updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class);
assertTrue(updateNode.isLeft());
- Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource = addRequirementToResource(
- capabilityTypeName, reqName, reqNodeName, reqRelationship, softwareComponent);
+ Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource = addRequirementToResource(capabilityTypeName, reqName, reqNodeName, reqRelationship, softwareComponent);
String parentReqUniqId = addRequirementToResource.left().value().getUniqueId();
@@ -2064,8 +1846,7 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
// create root resource
// String rootId = UniqueIdBuilder.buildResourceUniqueId(rootName,
// "1.0");
- Either<List<Resource>, StorageOperationStatus> oldResource = resourceOperation
- .getResourceByNameAndVersion(rootName, "1.0", false);
+ Either<List<Resource>, StorageOperationStatus> oldResource = resourceOperation.getResourceByNameAndVersion(rootName, "1.0", false);
if (oldResource.isLeft()) {
for (Resource old : oldResource.left().value()) {
if (old.getResourceType().equals(ResourceTypeEnum.VFC)) {
@@ -2074,17 +1855,14 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
}
}
- Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "1.0", null, true,
- true);
+ Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "1.0", null, true, true);
ResourceMetadataData rootResourceData = new ResourceMetadataData();
rootResourceData.getMetadataDataDefinition().setUniqueId(rootResource.getUniqueId());
rootResourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name());
- Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanDao.updateNode(rootResourceData,
- ResourceMetadataData.class);
+ Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanDao.updateNode(rootResourceData, ResourceMetadataData.class);
assertTrue(updateNode.isLeft());
- Either<Resource, StorageOperationStatus> fetchRootResource = resourceOperation
- .getResource(rootResource.getUniqueId(), true);
+ Either<Resource, StorageOperationStatus> fetchRootResource = resourceOperation.getResource(rootResource.getUniqueId(), true);
String rootResourceJson = prettyGson.toJson(fetchRootResource.left().value());
log.debug(rootResourceJson);
@@ -2109,29 +1887,21 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
capabilityTypeOperationTest.setOperations(titanDao, capabilityTypeOperation);
CapabilityTypeDefinition createCapabilityDef = capabilityTypeOperationTest.createCapability(capabilityTypeName);
- Resource softwareComponentResource = createSoftwareComponentWithReq(softwareCompName, resourceOperationTest,
- rootResource, capabilityTypeName, reqName, reqRelationship, computeNodeName);
- Resource compute = createComputeWithCapability(capabilityTypeName, computeNodeName, resourceOperationTest,
- rootResource);
+ Resource softwareComponentResource = createSoftwareComponentWithReq(softwareCompName, resourceOperationTest, rootResource, capabilityTypeName, reqName, reqRelationship, computeNodeName);
+ Resource compute = createComputeWithCapability(capabilityTypeName, computeNodeName, resourceOperationTest, rootResource);
// resource1
- ComponentInstance myresourceInstance = buildResourceInstance(softwareComponentResource.getUniqueId(), "1",
- "tosca.nodes.test.root");
+ ComponentInstance myresourceInstance = buildResourceInstance(softwareComponentResource.getUniqueId(), "1", "tosca.nodes.test.root");
- Either<ComponentInstance, TitanOperationStatus> myinstanceRes = resourceInstanceOperation
- .addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "1", true,
- myresourceInstance, NodeTypeEnum.Resource, false);
+ Either<ComponentInstance, TitanOperationStatus> myinstanceRes = resourceInstanceOperation.addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "1", true, myresourceInstance, NodeTypeEnum.Resource, false);
assertTrue("check instance added to service", myinstanceRes.isLeft());
// resource2
- ComponentInstance computeInstance = buildResourceInstance(compute.getUniqueId(), "2",
- "tosca.nodes.test.compute");
+ ComponentInstance computeInstance = buildResourceInstance(compute.getUniqueId(), "2", "tosca.nodes.test.compute");
ComponentInstance value1 = myinstanceRes.left().value();
- Either<ComponentInstance, TitanOperationStatus> computeInstTes = resourceInstanceOperation
- .addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "2", true, computeInstance,
- NodeTypeEnum.Resource, false);
+ Either<ComponentInstance, TitanOperationStatus> computeInstTes = resourceInstanceOperation.addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "2", true, computeInstance, NodeTypeEnum.Resource, false);
assertTrue("check instance added to service", computeInstTes.isLeft());
ComponentInstance value2 = computeInstTes.left().value();
@@ -2155,15 +1925,14 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
relationPair.setCapabilityOwnerId(value2.getUniqueId());
relationPair.setCapabilityUid(capId);
- Either<RelationshipInstData, TitanOperationStatus> connectResourcesInService = resourceInstanceOperation
- .connectResourcesInService(serviceId, NodeTypeEnum.Service, value1.getUniqueId(), value2.getUniqueId(),
- relationPair);
+ Either<RelationshipInstData, TitanOperationStatus> connectResourcesInService = resourceInstanceOperation.connectResourcesInService(serviceId, NodeTypeEnum.Service, value1.getUniqueId(), value2.getUniqueId(), relationPair);
assertTrue("check relation created", connectResourcesInService.isLeft());
}
@Test
+ @Ignore
public void addResourceInstancesResourceDeleted() {
String rootName = "tosca.nodes.test.root";
@@ -2185,24 +1954,21 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
capabilityTypeOperationTest.setOperations(titanDao, capabilityTypeOperation);
capabilityTypeOperationTest.createCapability(capabilityTypeName);
- Resource softwareComponentResource = createSoftwareComponentWithReq(softwareCompName, resourceOperationTest,
- rootResource, capabilityTypeName, reqName, reqRelationship, computeNodeName);
+ Resource softwareComponentResource = createSoftwareComponentWithReq(softwareCompName, resourceOperationTest, rootResource, capabilityTypeName, reqName, reqRelationship, computeNodeName);
deleteResource(softwareComponentResource.getUniqueId());
// resource1
- ComponentInstance myresourceInstance = buildResourceInstance(softwareComponentResource.getUniqueId(), "1",
- "tosca.nodes.test.root");
+ ComponentInstance myresourceInstance = buildResourceInstance(softwareComponentResource.getUniqueId(), "1", "tosca.nodes.test.root");
- Either<ComponentInstance, TitanOperationStatus> myinstanceRes = resourceInstanceOperation
- .addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "1", true,
- myresourceInstance, NodeTypeEnum.Resource, false);
+ Either<ComponentInstance, TitanOperationStatus> myinstanceRes = resourceInstanceOperation.addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "1", true, myresourceInstance, NodeTypeEnum.Resource, false);
assertTrue("check instance not added to service", myinstanceRes.isRight());
}
@Test
+ @Ignore
public void testDeploymentArtifactsOnRI() {
String rootName = "tosca.nodes.test.root";
@@ -2214,20 +1980,17 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation);
Resource rootResource = createRootResource(rootName, resourceOperationTest);
- ArtifactDefinition addArtifactToResource = addArtifactToResource(USER_ID, rootResource.getUniqueId(),
- "myArtifact");
+ ArtifactDefinition addArtifactToResource = addArtifactToResource(USER_ID, rootResource.getUniqueId(), "myArtifact");
// resource1
ComponentInstance myresourceInstance = buildResourceInstance(rootResource.getUniqueId(), "1", rootName);
- Either<ComponentInstance, TitanOperationStatus> myinstanceRes = resourceInstanceOperation
- .addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "1", true,
- myresourceInstance, NodeTypeEnum.Resource, false);
+ Either<ComponentInstance, TitanOperationStatus> myinstanceRes = resourceInstanceOperation.addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "1", true, myresourceInstance, NodeTypeEnum.Resource, false);
assertTrue("check instance added to service", myinstanceRes.isLeft());
- Either<ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>>, TitanOperationStatus> resourceInstancesOfService = resourceInstanceOperation
- .getComponentInstancesOfComponent(serviceId, NodeTypeEnum.Service, NodeTypeEnum.Resource);
+ Either<ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>>, TitanOperationStatus> resourceInstancesOfService = resourceInstanceOperation.getComponentInstancesOfComponent(serviceId, NodeTypeEnum.Service,
+ NodeTypeEnum.Resource);
assertTrue(resourceInstancesOfService.isLeft());
List<ComponentInstance> resourceInstanceList = resourceInstancesOfService.left().value().left;
assertTrue(resourceInstanceList.size() == 1);
@@ -2241,13 +2004,10 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
heatEnvArtifact.setArtifactLabel(addArtifactToResource.getArtifactLabel() + "env");
heatEnvArtifact.setUniqueId(null);
- Either<ArtifactDefinition, StorageOperationStatus> either = artifactOperation.addHeatEnvArtifact(
- heatEnvArtifact, addArtifactToResource, resourceInstance.getUniqueId(), NodeTypeEnum.ResourceInstance,
- false);
+ Either<ArtifactDefinition, StorageOperationStatus> either = artifactOperation.addHeatEnvArtifact(heatEnvArtifact, addArtifactToResource, resourceInstance.getUniqueId(), NodeTypeEnum.ResourceInstance, true);
assertTrue(either.isLeft());
- resourceInstancesOfService = resourceInstanceOperation.getComponentInstancesOfComponent(serviceId,
- NodeTypeEnum.Service, NodeTypeEnum.Resource);
+ resourceInstancesOfService = resourceInstanceOperation.getComponentInstancesOfComponent(serviceId, NodeTypeEnum.Service, NodeTypeEnum.Resource);
assertTrue(resourceInstancesOfService.isLeft());
resourceInstanceList = resourceInstancesOfService.left().value().left;
assertTrue(resourceInstanceList.size() == 1);
@@ -2259,12 +2019,11 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
ArtifactDefinition heatEnvFromRI = artifacts.get(addArtifactToResource.getArtifactLabel() + "env");
assertEquals(addArtifactToResource.getUniqueId(), heatEnvFromRI.getGeneratedFromId());
- List<HeatParameterDefinition> heatParameters = artifacts.get(addArtifactToResource.getArtifactLabel())
- .getHeatParameters();
+ List<HeatParameterDefinition> heatParameters = artifacts.get(addArtifactToResource.getArtifactLabel()).getListHeatParameters();
assertNotNull(heatParameters);
assertTrue(heatParameters.size() == 1);
- List<HeatParameterDefinition> heatEnvParameters = heatEnvFromRI.getHeatParameters();
+ List<HeatParameterDefinition> heatEnvParameters = heatEnvFromRI.getListHeatParameters();
assertNotNull(heatEnvParameters);
assertTrue(heatEnvParameters.size() == 1);
@@ -2273,6 +2032,7 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
}
@Test
+ @Ignore
public void deleteResourceInstanceWithArtifacts() {
String rootName = "tosca.nodes.test.root";
@@ -2283,15 +2043,12 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation);
Resource rootResource = createRootResource(rootName, resourceOperationTest);
- ArtifactDefinition addArtifactToResource = addArtifactToResource(USER_ID, rootResource.getUniqueId(),
- "myArtifact");
+ ArtifactDefinition addArtifactToResource = addArtifactToResource(USER_ID, rootResource.getUniqueId(), "myArtifact");
// resource1
ComponentInstance myresourceInstance = buildResourceInstance(rootResource.getUniqueId(), "1", rootName);
- Either<ComponentInstance, TitanOperationStatus> myinstanceRes = resourceInstanceOperation
- .addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "1", true,
- myresourceInstance, NodeTypeEnum.Resource, false);
+ Either<ComponentInstance, TitanOperationStatus> myinstanceRes = resourceInstanceOperation.addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "1", true, myresourceInstance, NodeTypeEnum.Resource, false);
ArtifactDefinition heatEnvArtifact = new ArtifactDefinition(addArtifactToResource);
heatEnvArtifact.setArtifactType("HEAT_ENV");
@@ -2300,38 +2057,32 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
assertTrue("check instance added to service", myinstanceRes.isLeft());
- Either<ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>>, TitanOperationStatus> resourceInstancesOfService = resourceInstanceOperation
- .getComponentInstancesOfComponent(serviceId, NodeTypeEnum.Service, NodeTypeEnum.Resource);
+ Either<ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>>, TitanOperationStatus> resourceInstancesOfService = resourceInstanceOperation.getComponentInstancesOfComponent(serviceId, NodeTypeEnum.Service,
+ NodeTypeEnum.Resource);
assertTrue(resourceInstancesOfService.isLeft());
List<ComponentInstance> resourceInstanceList = resourceInstancesOfService.left().value().left;
assertTrue(resourceInstanceList.size() == 1);
ComponentInstance resourceInstance = resourceInstanceList.get(0);
- Either<ArtifactDefinition, StorageOperationStatus> either = artifactOperation.addHeatEnvArtifact(
- heatEnvArtifact, addArtifactToResource, resourceInstance.getUniqueId(), NodeTypeEnum.ResourceInstance,
- false);
+ Either<ArtifactDefinition, StorageOperationStatus> either = artifactOperation.addHeatEnvArtifact(heatEnvArtifact, addArtifactToResource, resourceInstance.getUniqueId(), NodeTypeEnum.ResourceInstance, true);
assertTrue(either.isLeft());
ArtifactDefinition heatEnvDefinition = either.left().value();
// delete resource instance
- Either<ComponentInstance, StorageOperationStatus> deleteResourceInstance = resourceInstanceOperation
- .deleteComponentInstance(NodeTypeEnum.Service, serviceId, resourceInstance.getUniqueId());
+ Either<ComponentInstance, StorageOperationStatus> deleteResourceInstance = resourceInstanceOperation.deleteComponentInstance(NodeTypeEnum.Service, serviceId, resourceInstance.getUniqueId());
assertTrue(deleteResourceInstance.isLeft());
// check heat env deleted
ArtifactData artifactData = new ArtifactData();
- Either<ArtifactData, TitanOperationStatus> getDeletedArtifact = titanDao.getNode(artifactData.getUniqueIdKey(),
- heatEnvDefinition.getUniqueId(), ArtifactData.class);
+ Either<ArtifactData, TitanOperationStatus> getDeletedArtifact = titanDao.getNode(artifactData.getUniqueIdKey(), heatEnvDefinition.getUniqueId(), ArtifactData.class);
assertTrue(getDeletedArtifact.isRight());
// check heat is not deleted
- getDeletedArtifact = titanDao.getNode(artifactData.getUniqueIdKey(), addArtifactToResource.getUniqueId(),
- ArtifactData.class);
+ getDeletedArtifact = titanDao.getNode(artifactData.getUniqueIdKey(), addArtifactToResource.getUniqueId(), ArtifactData.class);
assertTrue(getDeletedArtifact.isLeft());
HeatParameterData heatParamData = new HeatParameterData();
- Either<HeatParameterData, TitanOperationStatus> heatParamNode = titanDao.getNode(heatParamData.getUniqueIdKey(),
- addArtifactToResource.getHeatParameters().get(0).getUniqueId(), HeatParameterData.class);
+ Either<HeatParameterData, TitanOperationStatus> heatParamNode = titanDao.getNode(heatParamData.getUniqueIdKey(), addArtifactToResource.getHeatParameters().get(0).getUniqueId(), HeatParameterData.class);
assertTrue(heatParamNode.isLeft());
resourceOperation.deleteResource(rootResource.getUniqueId());
@@ -2339,6 +2090,7 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
}
@Test
+ @Ignore
public void getHeatEnvParams() {
String rootName = "tosca.nodes.test.root";
@@ -2349,15 +2101,12 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation);
Resource rootResource = createRootResource(rootName, resourceOperationTest);
- ArtifactDefinition addArtifactToResource = addArtifactToResource(USER_ID, rootResource.getUniqueId(),
- "myArtifact");
+ ArtifactDefinition addArtifactToResource = addArtifactToResource(USER_ID, rootResource.getUniqueId(), "myArtifact");
// resource1
ComponentInstance myresourceInstance = buildResourceInstance(rootResource.getUniqueId(), "1", rootName);
- Either<ComponentInstance, TitanOperationStatus> myinstanceRes = resourceInstanceOperation
- .addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "1", true,
- myresourceInstance, NodeTypeEnum.Resource, false);
+ Either<ComponentInstance, TitanOperationStatus> myinstanceRes = resourceInstanceOperation.addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "1", true, myresourceInstance, NodeTypeEnum.Resource, false);
ArtifactDefinition heatEnvArtifact = new ArtifactDefinition(addArtifactToResource);
heatEnvArtifact.setArtifactType("HEAT_ENV");
@@ -2366,28 +2115,24 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
assertTrue("check instance added to service", myinstanceRes.isLeft());
- Either<ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>>, TitanOperationStatus> resourceInstancesOfService = resourceInstanceOperation
- .getComponentInstancesOfComponent(serviceId, NodeTypeEnum.Service, NodeTypeEnum.Resource);
+ Either<ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>>, TitanOperationStatus> resourceInstancesOfService = resourceInstanceOperation.getComponentInstancesOfComponent(serviceId, NodeTypeEnum.Service,
+ NodeTypeEnum.Resource);
assertTrue(resourceInstancesOfService.isLeft());
List<ComponentInstance> resourceInstanceList = resourceInstancesOfService.left().value().left;
assertTrue(resourceInstanceList.size() == 1);
ComponentInstance resourceInstance = resourceInstanceList.get(0);
- Either<ArtifactDefinition, StorageOperationStatus> either = artifactOperation.addHeatEnvArtifact(
- heatEnvArtifact, addArtifactToResource, resourceInstance.getUniqueId(), NodeTypeEnum.ResourceInstance,
- false);
+ Either<ArtifactDefinition, StorageOperationStatus> either = artifactOperation.addHeatEnvArtifact(heatEnvArtifact, addArtifactToResource, resourceInstance.getUniqueId(), NodeTypeEnum.ResourceInstance, true);
assertTrue(either.isLeft());
ArtifactDefinition heatEnvDefinition = either.left().value();
// update value
String newHeatValue = "123";
- addHeatValueToEnv(heatEnvDefinition.getUniqueId(), addArtifactToResource.getHeatParameters().get(0),
- newHeatValue);
+ addHeatValueToEnv(heatEnvDefinition.getUniqueId(), addArtifactToResource.getListHeatParameters().get(0), newHeatValue);
// check values received
- resourceInstancesOfService = resourceInstanceOperation.getComponentInstancesOfComponent(serviceId,
- NodeTypeEnum.Service, NodeTypeEnum.Resource);
+ resourceInstancesOfService = resourceInstanceOperation.getComponentInstancesOfComponent(serviceId, NodeTypeEnum.Service, NodeTypeEnum.Resource);
assertTrue(resourceInstancesOfService.isLeft());
resourceInstanceList = resourceInstancesOfService.left().value().left;
assertTrue(resourceInstanceList.size() == 1);
@@ -2397,14 +2142,12 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
assertNotNull(artifacts.get(addArtifactToResource.getArtifactLabel()));
assertNotNull(artifacts.get(addArtifactToResource.getArtifactLabel() + "env"));
- List<HeatParameterDefinition> heatParameters = artifacts.get(addArtifactToResource.getArtifactLabel())
- .getHeatParameters();
+ List<HeatParameterDefinition> heatParameters = artifacts.get(addArtifactToResource.getArtifactLabel()).getListHeatParameters();
assertNotNull(heatParameters);
assertTrue(heatParameters.size() == 1);
HeatParameterDefinition heatParameterTemplate = heatParameters.get(0);
- List<HeatParameterDefinition> heatEnvParameters = artifacts
- .get(addArtifactToResource.getArtifactLabel() + "env").getHeatParameters();
+ List<HeatParameterDefinition> heatEnvParameters = artifacts.get(addArtifactToResource.getArtifactLabel() + "env").getListHeatParameters();
assertNotNull(heatEnvParameters);
assertTrue(heatEnvParameters.size() == 1);
HeatParameterDefinition heatParameterEnv = heatEnvParameters.get(0);
@@ -2421,18 +2164,15 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
HeatParameterValueData heatValueData = new HeatParameterValueData();
heatValueData.setValue(value);
heatValueData.setUniqueId(artifactId + "." + heatDefinition.getName());
- Either<HeatParameterValueData, TitanOperationStatus> createValue = titanDao.createNode(heatValueData,
- HeatParameterValueData.class);
+ Either<HeatParameterValueData, TitanOperationStatus> createValue = titanDao.createNode(heatValueData, HeatParameterValueData.class);
assertTrue(createValue.isLeft());
HeatParameterValueData value2 = createValue.left().value();
HeatParameterData heatParamData = new HeatParameterData(heatDefinition);
- Either<GraphRelation, TitanOperationStatus> createRelation = titanDao.createRelation(value2, heatParamData,
- GraphEdgeLabels.PROPERTY_IMPL, null);
+ Either<GraphRelation, TitanOperationStatus> createRelation = titanDao.createRelation(value2, heatParamData, GraphEdgeLabels.PROPERTY_IMPL, null);
assertTrue(createRelation.isLeft());
Map<String, Object> props = new HashMap<String, Object>();
props.put(GraphEdgePropertiesDictionary.NAME.getProperty(), heatDefinition.getName());
- Either<GraphRelation, TitanOperationStatus> createRelation2 = titanDao.createRelation(
- new UniqueIdData(NodeTypeEnum.ArtifactRef, artifactId), value2, GraphEdgeLabels.PARAMETER_VALUE, props);
+ Either<GraphRelation, TitanOperationStatus> createRelation2 = titanDao.createRelation(new UniqueIdData(NodeTypeEnum.ArtifactRef, artifactId), value2, GraphEdgeLabels.PARAMETER_VALUE, props);
assertTrue(createRelation2.isLeft());
titanDao.commit();
@@ -2501,10 +2241,9 @@ public class ResourceInstanceOperationTest extends ModelTestBase {
heatParam.setName("myParam");
heatParam.setType("number");
heatParams.add(heatParam);
- artifactInfo.setHeatParameters(heatParams);
+ artifactInfo.setListHeatParameters(heatParams);
- Either<ArtifactDefinition, StorageOperationStatus> artifact = artifactOperation
- .addArifactToComponent(artifactInfo, resourceId, NodeTypeEnum.Resource, true, true);
+ Either<ArtifactDefinition, StorageOperationStatus> artifact = artifactOperation.addArifactToComponent(artifactInfo, resourceId, NodeTypeEnum.Resource, true, true);
assertTrue(artifact.isLeft());
return artifact.left().value();
}
diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ResourceOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ResourceOperationTest.java
index f977509f6b..efd55d58fb 100644
--- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ResourceOperationTest.java
+++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ResourceOperationTest.java
@@ -24,24 +24,34 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
+import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
+import java.util.Optional;
import java.util.Set;
+import java.util.UUID;
import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.apache.tinkerpop.gremlin.structure.Direction;
+import org.apache.tinkerpop.gremlin.structure.Edge;
+import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.mockito.Mockito;
import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
+import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.model.CapabilityDefinition;
import org.openecomp.sdc.be.model.CapabilityTypeDefinition;
@@ -53,13 +63,8 @@ import org.openecomp.sdc.be.model.PropertyConstraint;
import org.openecomp.sdc.be.model.PropertyDefinition;
import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.operations.api.IElementOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.model.operations.impl.CapabilityOperation;
-import org.openecomp.sdc.be.model.operations.impl.CapabilityTypeOperation;
-import org.openecomp.sdc.be.model.operations.impl.LifecycleOperation;
-import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
-import org.openecomp.sdc.be.model.operations.impl.ResourceOperation;
-import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
import org.openecomp.sdc.be.model.operations.impl.util.OperationTestsUtil;
import org.openecomp.sdc.be.model.tosca.ToscaType;
import org.openecomp.sdc.be.model.tosca.constraints.GreaterThanConstraint;
@@ -68,6 +73,9 @@ import org.openecomp.sdc.be.model.tosca.constraints.LessOrEqualConstraint;
import org.openecomp.sdc.be.resources.data.PropertyData;
import org.openecomp.sdc.be.resources.data.ResourceMetadataData;
import org.openecomp.sdc.be.resources.data.UserData;
+import org.openecomp.sdc.be.resources.data.category.CategoryData;
+import org.openecomp.sdc.be.resources.data.category.SubCategoryData;
+import org.openecomp.sdc.be.unittests.utils.FactoryUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.test.context.ContextConfiguration;
@@ -75,6 +83,10 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
+import com.thinkaurelius.titan.core.TitanGraph;
+import com.thinkaurelius.titan.core.TitanGraphQuery;
+import com.thinkaurelius.titan.core.TitanVertex;
+import com.thinkaurelius.titan.graphdb.query.graph.GraphCentricQueryBuilder;
import fj.data.Either;
@@ -100,7 +112,7 @@ public class ResourceOperationTest extends ModelTestBase {
@javax.annotation.Resource(name = "capability-type-operation")
private CapabilityTypeOperation capabilityTypeOperation;
-
+
private static String CATEGORY_NAME = "category/mycategory";
private static String CATEGORY_NAME_UPDATED = "category1/updatedcategory";
@@ -110,8 +122,7 @@ public class ResourceOperationTest extends ModelTestBase {
ModelTestBase.init();
}
- public void setOperations(TitanGenericDao titanGenericDao, ResourceOperation resourceOperation,
- PropertyOperation propertyOperation) {
+ public void setOperations(TitanGenericDao titanGenericDao, ResourceOperation resourceOperation, PropertyOperation propertyOperation) {
this.titanDao = titanGenericDao;
this.resourceOperation = resourceOperation;
this.propertyOperation = propertyOperation;
@@ -122,8 +133,7 @@ public class ResourceOperationTest extends ModelTestBase {
}
- private Resource buildResourceMetadata(String userId, String category, String resourceName,
- String resourceVersion) {
+ private Resource buildResourceMetadata(String userId, String category, String resourceName, String resourceVersion) {
Resource resource = new Resource();
resource.setName(resourceName);
@@ -164,8 +174,7 @@ public class ResourceOperationTest extends ModelTestBase {
OperationTestsUtil.deleteAndCreateResourceCategory(names[0], names[1], titanDao);
}
- public Resource createResource(String userId, String category, String resourceName, String resourceVersion,
- String parentResourceName, boolean isAbstract, boolean isHighestVersion) {
+ public Resource createResource(String userId, String category, String resourceName, String resourceVersion, String parentResourceName, boolean isAbstract, boolean isHighestVersion) {
String propName1 = "disk_size";
String propName2 = "num_cpus";
@@ -183,8 +192,7 @@ public class ResourceOperationTest extends ModelTestBase {
PropertyDefinition property1 = new PropertyDefinition();
property1.setDefaultValue("10");
- property1.setDescription(
- "Size of the local disk, in Gigabytes (GB), available to applications running on the Compute node.");
+ property1.setDescription("Size of the local disk, in Gigabytes (GB), available to applications running on the Compute node.");
property1.setType(ToscaType.INTEGER.name().toLowerCase());
List<PropertyConstraint> constraints = new ArrayList<PropertyConstraint>();
GreaterThanConstraint propertyConstraint1 = new GreaterThanConstraint("0");
@@ -226,16 +234,14 @@ public class ResourceOperationTest extends ModelTestBase {
// assertEquals("check resource unique id",
// UniqueIdBuilder.buildResourceUniqueId(resourceName,
// resourceVersion), resultResource.getUniqueId());
- assertEquals("check resource state", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT,
- resultResource.getLifecycleState());
+ assertEquals("check resource state", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, resultResource.getLifecycleState());
// retrieve property from graph
String resourceId = resultResource.getUniqueId();
// String resourceId = UniqueIdBuilder.buildResourceUniqueId(
// resource.getResourceName(), resource.getResourceVersion());
- Either<PropertyDefinition, StorageOperationStatus> either = propertyOperation.getPropertyOfResource(propName1,
- resourceId);
+ Either<PropertyDefinition, StorageOperationStatus> either = propertyOperation.getPropertyOfResource(propName1, resourceId);
assertTrue(either.isLeft());
PropertyDefinition propertyDefinition = either.left().value();
@@ -243,12 +249,68 @@ public class ResourceOperationTest extends ModelTestBase {
assertEquals("check property description", property1.getDescription(), propertyDefinition.getDescription());
assertEquals("check property type", property1.getType(), propertyDefinition.getType());
assertEquals("check property unique id", property1.getUniqueId(), propertyDefinition.getUniqueId());
- assertEquals("check property consitraints size", property1.getConstraints().size(),
- propertyDefinition.getConstraints().size());
+ assertEquals("check property consitraints size", property1.getConstraints().size(), propertyDefinition.getConstraints().size());
return resultResource;
}
+
+ public Resource createResourceOverrideProperty(String userId, String category, String resourceName, String resourceVersion, String parentResourceName, boolean isAbstract, boolean isHighestVersion) {
+
+ String propName1 = "disk_size";
+
+ List<String> derivedFrom = new ArrayList<String>();
+ if (parentResourceName != null) {
+ derivedFrom.add(parentResourceName);
+ }
+
+ Map<String, PropertyDefinition> properties = new HashMap<String, PropertyDefinition>();
+ PropertyDefinition property1 = new PropertyDefinition();
+ property1.setDefaultValue("9");
+ property1.setDescription("Size of the local disk, in Gigabytes (GB), available to applications running on the Compute node.");
+ property1.setType(ToscaType.INTEGER.name().toLowerCase());
+ List<PropertyConstraint> constraints = new ArrayList<PropertyConstraint>();
+ GreaterThanConstraint propertyConstraint1 = new GreaterThanConstraint("0");
+ log.debug("{}", propertyConstraint1);
+ constraints.add(propertyConstraint1);
+ LessOrEqualConstraint propertyConstraint2 = new LessOrEqualConstraint("10");
+ constraints.add(propertyConstraint2);
+ property1.setConstraints(constraints);
+ properties.put(propName1, property1);
+
+ Resource resource = buildResourceMetadata(userId, category, resourceName, resourceVersion);
+ resource.setAbstract(isAbstract);
+ resource.setHighestVersion(isHighestVersion);
+ resource.setDerivedFrom(derivedFrom);
+ resource.setProperties(convertMapToList(properties));
+
+ Either<Resource, StorageOperationStatus> result = resourceOperation.createResource(resource, true);
+
+ assertTrue(result.isLeft());
+ Resource resultResource = result.left().value();
+
+ // assertEquals("check resource unique id",
+ // UniqueIdBuilder.buildResourceUniqueId(resourceName,
+ // resourceVersion), resultResource.getUniqueId());
+ assertEquals("check resource state", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, resultResource.getLifecycleState());
+
+ // retrieve property from graph
+ String resourceId = resultResource.getUniqueId();
+ // String resourceId = UniqueIdBuilder.buildResourceUniqueId(
+ // resource.getResourceName(), resource.getResourceVersion());
+
+ Either<PropertyDefinition, StorageOperationStatus> either = propertyOperation.getPropertyOfResource(propName1, resourceId);
+
+ assertTrue(either.isLeft());
+ PropertyDefinition propertyDefinition = either.left().value();
+ assertEquals("check property default value", property1.getDefaultValue(), propertyDefinition.getDefaultValue());
+ assertEquals("check property description", property1.getDescription(), propertyDefinition.getDescription());
+ assertEquals("check property type", property1.getType(), propertyDefinition.getType());
+ assertEquals("check property unique id", property1.getUniqueId(), propertyDefinition.getUniqueId());
+ assertEquals("check property consitraints size", property1.getConstraints().size(), propertyDefinition.getConstraints().size());
+
+ return resultResource;
+ }
public static List<PropertyDefinition> convertMapToList(Map<String, PropertyDefinition> properties) {
if (properties == null) {
@@ -285,8 +347,7 @@ public class ResourceOperationTest extends ModelTestBase {
Set<LifecycleStateEnum> lastStateStates = new HashSet<LifecycleStateEnum>();
lastStateStates.add(LifecycleStateEnum.CERTIFIED);
- Either<List<Resource>, StorageOperationStatus> followed = resourceOperation.getFollowed(userId, lifecycleStates,
- lastStateStates, false);
+ Either<List<Resource>, StorageOperationStatus> followed = resourceOperation.getFollowed(userId, lifecycleStates, lastStateStates, false);
assertTrue(followed.isLeft());
List<Resource> list = followed.left().value();
@@ -352,8 +413,7 @@ public class ResourceOperationTest extends ModelTestBase {
propertyDefinition.setName("myProperty");
rootResource.getProperties().add(propertyDefinition);
- Either<Resource, StorageOperationStatus> overrideResource = resourceOperation.overrideResource(rootResource,
- rootResource, false);
+ Either<Resource, StorageOperationStatus> overrideResource = resourceOperation.overrideResource(rootResource, rootResource, false);
assertTrue(overrideResource.isLeft());
Resource resourceAfter = overrideResource.left().value();
@@ -399,8 +459,7 @@ public class ResourceOperationTest extends ModelTestBase {
props.put(delaultProperty2.getName(), delaultProperty2);
capabilityTypeDefinition.setProperties(props);
- Either<CapabilityTypeDefinition, StorageOperationStatus> addTypeRes = capabilityTypeOperation
- .addCapabilityType(capabilityTypeDefinition);
+ Either<CapabilityTypeDefinition, StorageOperationStatus> addTypeRes = capabilityTypeOperation.addCapabilityType(capabilityTypeDefinition);
assertTrue(addTypeRes.isLeft());
CapabilityDefinition capabilityDefinition = new CapabilityDefinition();
@@ -423,8 +482,7 @@ public class ResourceOperationTest extends ModelTestBase {
capabilityDefinition.setProperties(properties);
- Either<CapabilityDefinition, StorageOperationStatus> addCapabilityRes = capabilityOperation
- .addCapability(rootResource.getUniqueId(), capabilityDefinition.getName(), capabilityDefinition);
+ Either<CapabilityDefinition, StorageOperationStatus> addCapabilityRes = capabilityOperation.addCapability(rootResource.getUniqueId(), capabilityDefinition.getName(), capabilityDefinition);
assertTrue(addCapabilityRes.isLeft());
List<PropertyDefinition> newProperties = new ArrayList<PropertyDefinition>();
@@ -442,8 +500,7 @@ public class ResourceOperationTest extends ModelTestBase {
CapabilityDefinition addedCap = addCapabilityRes.left().value();
- Either<Map<String, PropertyData>, StorageOperationStatus> updatePropertiesRes = capabilityOperation
- .updatePropertiesOfCapability(addedCap.getUniqueId(), addedCap.getType(), newProperties);
+ Either<Map<String, PropertyData>, StorageOperationStatus> updatePropertiesRes = capabilityOperation.updatePropertiesOfCapability(addedCap.getUniqueId(), addedCap.getType(), newProperties);
assertTrue(updatePropertiesRes.isLeft());
PropertyDefinition invalidProperty = new PropertyDefinition();
@@ -452,25 +509,20 @@ public class ResourceOperationTest extends ModelTestBase {
invalidProperty.setDefaultValue("666");
newProperties.add(invalidProperty);
- Either<Map<String, PropertyData>, StorageOperationStatus> updatePropertiesInvalidRes = capabilityOperation
- .updatePropertiesOfCapability(addedCap.getUniqueId(), addedCap.getType(), newProperties);
+ Either<Map<String, PropertyData>, StorageOperationStatus> updatePropertiesInvalidRes = capabilityOperation.updatePropertiesOfCapability(addedCap.getUniqueId(), addedCap.getType(), newProperties);
assertTrue(updatePropertiesInvalidRes.isRight());
- Either<CapabilityDefinition, StorageOperationStatus> getCapabilityRes = capabilityOperation
- .getCapability(addedCap.getUniqueId());
+ Either<CapabilityDefinition, StorageOperationStatus> getCapabilityRes = capabilityOperation.getCapability(addedCap.getUniqueId());
assertTrue(getCapabilityRes.isLeft());
- Either<List<ImmutablePair<PropertyData, GraphEdge>>, TitanOperationStatus> deletePropertiesOfCapabilityRes = capabilityOperation
- .deletePropertiesOfCapability(addedCap.getUniqueId());
+ Either<List<ImmutablePair<PropertyData, GraphEdge>>, TitanOperationStatus> deletePropertiesOfCapabilityRes = capabilityOperation.deletePropertiesOfCapability(addedCap.getUniqueId());
assertTrue(deletePropertiesOfCapabilityRes.isLeft());
- StorageOperationStatus deleteCapabilityRes = capabilityOperation
- .deleteCapabilityFromGraph(addedCap.getUniqueId());
+ StorageOperationStatus deleteCapabilityRes = capabilityOperation.deleteCapabilityFromGraph(addedCap.getUniqueId());
assertTrue(deleteCapabilityRes.equals(StorageOperationStatus.OK));
getCapabilityRes = capabilityOperation.getCapability(addedCap.getUniqueId());
- assertTrue(getCapabilityRes.isRight()
- && getCapabilityRes.right().value().equals(StorageOperationStatus.NOT_FOUND));
+ assertTrue(getCapabilityRes.isRight() && getCapabilityRes.right().value().equals(StorageOperationStatus.NOT_FOUND));
resourceOperation.deleteResource(rootResource.getUniqueId());
}
@@ -503,8 +555,7 @@ public class ResourceOperationTest extends ModelTestBase {
Resource rootResource = buildResourceMetadata(userId, category, rootName, "1.1");
rootResource.setUniqueId(UniqueIdBuilder.buildResourceUniqueId());
- Either<Resource, StorageOperationStatus> overrideResource = resourceOperation.overrideResource(rootResource,
- rootResource, false);
+ Either<Resource, StorageOperationStatus> overrideResource = resourceOperation.overrideResource(rootResource, rootResource, false);
assertTrue(overrideResource.isRight());
@@ -524,8 +575,7 @@ public class ResourceOperationTest extends ModelTestBase {
Map<String, Object> propertiesToMatch = new HashMap<>();
propertiesToMatch.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFIED.name());
- Either<Set<Resource>, StorageOperationStatus> catalog = resourceOperation.getCatalogData(propertiesToMatch,
- false);
+ Either<Set<Resource>, StorageOperationStatus> catalog = resourceOperation.getCatalogData(propertiesToMatch, false);
assertTrue(catalog.isLeft());
Set<Resource> catalogSet = catalog.left().value();
Set<String> idSet = new HashSet<>();
@@ -566,22 +616,19 @@ public class ResourceOperationTest extends ModelTestBase {
String resourceId3 = resultResource3.getUniqueId();
// update 1 resource to READY_FOR_CERTIFICATION
- Either<Resource, StorageOperationStatus> certReqResponse = (Either<Resource, StorageOperationStatus>) lifecycleOperation
- .requestCertificationComponent(NodeTypeEnum.Resource, resultResource, adminUser, adminUser, false);
+ Either<Resource, StorageOperationStatus> certReqResponse = (Either<Resource, StorageOperationStatus>) lifecycleOperation.requestCertificationComponent(NodeTypeEnum.Resource, resultResource, adminUser, adminUser, false);
Resource RFCResource = certReqResponse.left().value();
assertEquals(RFCResource.getLifecycleState(), LifecycleStateEnum.READY_FOR_CERTIFICATION);
// update 1 resource to CERTIFICATION_IN_PROGRESS
- Either<Resource, StorageOperationStatus> startCertificationResponse = (Either<Resource, StorageOperationStatus>) lifecycleOperation
- .startComponentCertification(NodeTypeEnum.Resource, resultResource2, testerUser, adminUser, false);
+ Either<Resource, StorageOperationStatus> startCertificationResponse = (Either<Resource, StorageOperationStatus>) lifecycleOperation.startComponentCertification(NodeTypeEnum.Resource, resultResource2, testerUser, adminUser, false);
Resource IPResource = startCertificationResponse.left().value();
assertEquals(IPResource.getLifecycleState(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
Set<LifecycleStateEnum> lifecycleStates = new HashSet<LifecycleStateEnum>();
lifecycleStates.add(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
- Either<List<Resource>, StorageOperationStatus> resources = resourceOperation.getTesterFollowed(testerUserId,
- lifecycleStates, false);
+ Either<List<Resource>, StorageOperationStatus> resources = resourceOperation.getTesterFollowed(testerUserId, lifecycleStates, false);
assertTrue(resources.isLeft());
List<Resource> result = resources.left().value();
@@ -610,8 +657,7 @@ public class ResourceOperationTest extends ModelTestBase {
String resourceId1 = newResource.getUniqueId();
User admin = new User("j", "h", userId, null, "ADMIN", System.currentTimeMillis());
- Either<Resource, StorageOperationStatus> checkoutResource = (Either<Resource, StorageOperationStatus>) lifecycleOperation
- .checkoutComponent(NodeTypeEnum.Resource, newResource, admin, admin, false);
+ Either<Resource, StorageOperationStatus> checkoutResource = (Either<Resource, StorageOperationStatus>) lifecycleOperation.checkoutComponent(NodeTypeEnum.Resource, newResource, admin, admin, false);
assertTrue(checkoutResource.isLeft());
Resource newResource2 = checkoutResource.left().value();
String resourceId2 = newResource2.getUniqueId();
@@ -619,9 +665,7 @@ public class ResourceOperationTest extends ModelTestBase {
Resource newResource3 = createResource(userId, category, resName, "0.1", null, false, true);
String resourceId3 = newResource3.getUniqueId();
- Either<Map<String, String>, TitanOperationStatus> versionList = resourceOperation.getVersionList(
- NodeTypeEnum.Resource, "0.2", newResource2.getUUID(), newResource2.getSystemName(),
- ResourceMetadataData.class);
+ Either<Map<String, String>, TitanOperationStatus> versionList = resourceOperation.getVersionList(NodeTypeEnum.Resource, "0.2", newResource2.getUUID(), newResource2.getSystemName(), ResourceMetadataData.class);
assertTrue(versionList.isLeft());
Map<String, String> versionMap = versionList.left().value();
@@ -650,21 +694,17 @@ public class ResourceOperationTest extends ModelTestBase {
String resourceId1 = newResource.getUniqueId();
User admin = new User("j", "h", userId, null, "ADMIN", System.currentTimeMillis());
- Either<Resource, StorageOperationStatus> checkoutResource = (Either<Resource, StorageOperationStatus>) lifecycleOperation
- .checkoutComponent(NodeTypeEnum.Resource, newResource, admin, admin, false);
+ Either<Resource, StorageOperationStatus> checkoutResource = (Either<Resource, StorageOperationStatus>) lifecycleOperation.checkoutComponent(NodeTypeEnum.Resource, newResource, admin, admin, false);
assertTrue(checkoutResource.isLeft());
Resource newResource2 = checkoutResource.left().value();
String resourceId2 = newResource2.getUniqueId();
Either<Resource, StorageOperationStatus> resource = resourceOperation.getResource(resourceId1, false);
assertTrue(resource.isLeft());
- Either<Component, StorageOperationStatus> markResourceToDelete = resourceOperation
- .markComponentToDelete(resource.left().value(), false);
+ Either<Component, StorageOperationStatus> markResourceToDelete = resourceOperation.markComponentToDelete(resource.left().value(), false);
assertTrue(markResourceToDelete.isLeft());
- Either<Map<String, String>, TitanOperationStatus> versionList = resourceOperation.getVersionList(
- NodeTypeEnum.Resource, "0.2", newResource2.getUUID(), newResource2.getSystemName(),
- ResourceMetadataData.class);
+ Either<Map<String, String>, TitanOperationStatus> versionList = resourceOperation.getVersionList(NodeTypeEnum.Resource, "0.2", newResource2.getUUID(), newResource2.getSystemName(), ResourceMetadataData.class);
assertTrue(versionList.isLeft());
Map<String, String> versionMap = versionList.left().value();
@@ -678,8 +718,63 @@ public class ResourceOperationTest extends ModelTestBase {
deleteResource = resourceOperation.deleteResource(resourceId2);
assertTrue(deleteResource.isLeft());
}
-
- @Test
+
+ // @Test
+ // public void getVersionListAfterCertify(){
+ // String resName = "myResource";
+ // String category = CATEGORY_NAME;
+ // deleteAndCreateCategory(category);
+ //
+ // Resource newResource = createResource(userId, category, resName, "1.0",
+ // null, false, true);
+ // String resourceId1 = newResource.getUniqueId();
+ //
+ // User admin = new User("j", "h", userId, null, "ADMIN",
+ // System.currentTimeMillis());
+ // Either<Resource, StorageOperationStatus> checkoutResource =
+ // lifecycleOperation.checkoutResource(newResource, admin, admin, false);
+ // assertTrue(checkoutResource.isLeft());
+ // Resource resourceToDelete = checkoutResource.left().value();
+ // String deletedId = resourceToDelete.getUniqueId();
+ //
+ // Either<Resource, StorageOperationStatus> resource =
+ // resourceOperation.getResource(deletedId, false);
+ // assertTrue(resource.isLeft());
+ // Either<Resource, StorageOperationStatus> markResourceToDelete =
+ // resourceOperation.markResourceToDelete(resource.left().value(), false);
+ // assertTrue(markResourceToDelete.isLeft());
+ //
+ //
+ // Resource newResource2 = createResource(userId, category, resName, "2.0",
+ // null, false, true);
+ // String resourceId2 = newResource2.getUniqueId();
+ //
+ //
+ // Either<Map<String, String>, TitanOperationStatus> versionList =
+ // resourceOperation
+ // .getVersionList(NodeTypeEnum.Resource, "2.0",
+ // newResource2.getUUID(), newResource2.getSystemName(),
+ // ResourceData.class);
+ // assertTrue(versionList.isLeft());
+ // Map<String, String> versionMap = versionList.left().value();
+ //
+ // assertTrue(versionMap.size()==2);
+ // assertTrue(versionMap.containsValue(resourceId1));
+ // assertTrue(versionMap.containsValue(resourceId2));
+ //
+ // assertFalse(versionMap.containsValue(deletedId));
+ //
+ // Either<Resource, StorageOperationStatus> deleteResource =
+ // resourceOperation.deleteResource(resourceId1);
+ // assertTrue(deleteResource.isLeft());
+ // deleteResource = resourceOperation.deleteResource(resourceId2);
+ // assertTrue(deleteResource.isLeft());
+ // deleteResource = resourceOperation.deleteResource(deletedId);
+ // assertTrue(deleteResource.isLeft());
+ //
+ // }
+
+// @Test
public void testDerviedPropertiesInResource() {
try {
@@ -693,8 +788,7 @@ public class ResourceOperationTest extends ModelTestBase {
ResourceMetadataData resourceData = new ResourceMetadataData();
resourceData.getMetadataDataDefinition().setUniqueId(createResource1.getUniqueId());
resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name());
- Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanDao.updateNode(resourceData,
- ResourceMetadataData.class);
+ Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class);
assertTrue(updateNode.isLeft());
Gson gson = new GsonBuilder().setPrettyPrinting().create();
@@ -702,33 +796,158 @@ public class ResourceOperationTest extends ModelTestBase {
String json = gson.toJson(createResource1);
log.debug(json);
- Resource createResource2 = createResource(userId, category, "myResource2", "0.1", createResource1.getName(),
- true, false);
-
+ Resource createResource2 = createResourceOverrideProperty(userId, category, "myResource2", "0.1", createResource1.getName(), true, false);
+
json = gson.toJson(createResource2);
log.debug(json);
List<PropertyDefinition> propList1 = new ArrayList<>();
- TitanOperationStatus findAllResourcePropertiesRecursively1 = propertyOperation
- .findAllResourcePropertiesRecursively(createResource1.getUniqueId(), propList1);
- assertEquals("check search properties succeed", findAllResourcePropertiesRecursively1,
- TitanOperationStatus.OK);
+ TitanOperationStatus findAllResourcePropertiesRecursively1 = propertyOperation.findAllResourcePropertiesRecursively(createResource1.getUniqueId(), propList1);
+ assertEquals("check search properties succeed", findAllResourcePropertiesRecursively1, TitanOperationStatus.OK);
List<PropertyDefinition> propList2 = new ArrayList<>();
- TitanOperationStatus findAllResourcePropertiesRecursively2 = propertyOperation
- .findAllResourcePropertiesRecursively(createResource2.getUniqueId(), propList2);
- assertEquals("check search properties succeed", findAllResourcePropertiesRecursively2,
- TitanOperationStatus.OK);
-
- assertEquals("check number of properties", propList1.size() * 2, propList2.size());
-
+ TitanOperationStatus findAllResourcePropertiesRecursively2 = propertyOperation.findAllResourcePropertiesRecursively(createResource2.getUniqueId(), propList2);
+ assertEquals("check search properties succeed", findAllResourcePropertiesRecursively2, TitanOperationStatus.OK);
+ // checks that properties with the same names have been overrided properly
+ // the sizes of the property lists should be same (we have 2 properties "disk_size" and "num_cpus" only)
+ assertEquals("check number of properties", propList1.size(), propList2.size());
+ // checks that not overrided property default value in child's list equals to the same property of the parent
+ assertEquals("check values of properties are the same", propList1.stream().filter(prop->prop.getName().equals("num_cpus")).findAny().get().getDefaultValue()
+ , propList2.stream().filter(prop->prop.getName().equals("num_cpus")).findAny().get().getDefaultValue());
+ // checks that an overrided property default value in child's list doesn't equal to the same property of the parent
+ assertTrue(!propList1.stream().filter(prop->prop.getName().equals("disk_size")).findAny().get().getDefaultValue().equals(
+ propList2.stream().filter(prop->prop.getName().equals("disk_size")).findAny().get().getDefaultValue()));
+
resourceOperation.deleteResource(createResource1.getUniqueId());
resourceOperation.deleteResource(createResource2.getUniqueId());
} finally {
}
+
+ /*
+ * "properties": { "disk_size": { "constraints": [ { "greaterThan": "0" }, { "lessOrEqual": "10" } ], "uniqueId": "res_myresource1.0.1.disk_size", "type": "integer", "required": false, "defaultValue": "10", "description":
+ * "Size of the local disk, in Gigabytes (GB), available to applications running on the Compute node." , "isPassword": false }, "num_cpus": { "constraints": [ { "inRange": [ "1", "4" ] } ], "uniqueId": "res_myresource1.0.1.num_cpus", "type":
+ * "integer", "required": false, "defaultValue": "2", "description": "Number of (actual or virtual) CPUs associated with the Compute node." , "isPassword": false } },
+ */
+ }
+
+ @Test
+ public void getFilteredComponentsTest() {
+
+ TitanGenericDao titanGenericDao = Mockito.mock(TitanGenericDao.class);
+ IElementOperation elementOperation = Mockito.mock(ElementOperation.class);
+ IElementOperation prevElementOperation = this.resourceOperation.getElementOperation();
+ this.resourceOperation.setElementOperation(elementOperation);
+ this.resourceOperation.setTitanGenericDao(titanGenericDao);
+
+ String subCategoryName = "Database";
+ String categoryName = "Generic";
+ String resourceTypeName = "VFC";
+
+ Map<FilterKeyEnum, String> filters = new HashMap<>();
+ filters.put(FilterKeyEnum.CATEGORY, categoryName);
+ filters.put(FilterKeyEnum.SUB_CATEGORY, subCategoryName);
+ filters.put(FilterKeyEnum.RESOURCE_TYPE, resourceTypeName);
+
+ prepareMocks(titanGenericDao, elementOperation, subCategoryName, categoryName, resourceTypeName);
+ try{
+ //search by category, subCategory and resourceType
+ Either<List<Resource>, StorageOperationStatus> getFilteredComponentsRes =
+ this.resourceOperation.getFilteredComponents(filters, false);
+ assertTrue(getFilteredComponentsRes.isLeft());
+
+ //search by category and resourceType
+ filters.remove(FilterKeyEnum.SUB_CATEGORY);
+ getFilteredComponentsRes =
+ this.resourceOperation.getFilteredComponents(filters, false);
+ assertTrue(getFilteredComponentsRes.isLeft());
+
+ //search by resourceType
+ filters.remove(FilterKeyEnum.CATEGORY);
+ getFilteredComponentsRes =
+ this.resourceOperation.getFilteredComponents(filters, false);
+ assertTrue(getFilteredComponentsRes.isLeft());
+ }finally{
+ this.resourceOperation.setTitanGenericDao(this.titanDao);
+ this.resourceOperation.setElementOperation(prevElementOperation);
+ }
+
+
+ }
+
+ @SuppressWarnings("unchecked")
+ private void prepareMocks(TitanGenericDao titanGenericDao, IElementOperation elementOperation, String subCategoryName, String categoryName, String resourceTypeName) {
+ //prepare resource
+ ResourceMetadataData resourceMeta = FactoryUtils.createResourceByType(resourceTypeName);
+ ImmutablePair<ResourceMetadataData, GraphEdge> resourcePair = new ImmutablePair<ResourceMetadataData, GraphEdge>(resourceMeta, new GraphEdge());
+ List<ImmutablePair<ResourceMetadataData, GraphEdge>> resourcePairList = new ArrayList<>();
+ resourcePairList.add(resourcePair);
+ Either<List<ImmutablePair<ResourceMetadataData, GraphEdge>>, TitanOperationStatus> parentNodes = Either.left(resourcePairList);
+ Map<String, Object> resourceProps = new HashMap<String, Object>();
+ resourceProps.put(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), resourceTypeName);
+ resourceProps.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true);
+ List<ResourceMetadataData> resourceList = new ArrayList<>();
+ resourceList.add(resourceMeta);
+ Either<List<ResourceMetadataData>, TitanOperationStatus> getResources = Either.left(resourceList);
+
+ //prepare subcategory
+ SubCategoryData subCategoryData = new SubCategoryData(NodeTypeEnum.ResourceSubcategory);
+ subCategoryData.getSubCategoryDataDefinition().setName(subCategoryName);
+ subCategoryData.getSubCategoryDataDefinition().setUniqueId(UUID.randomUUID().toString());
+ GraphEdge graphEdge = new GraphEdge();
+ Optional<ImmutablePair<SubCategoryData, GraphEdge>> subCategory = Optional.of(new ImmutablePair<>(subCategoryData, graphEdge));
+ List<ImmutablePair<SubCategoryData, GraphEdge>> subcategoriesList = new ArrayList<>();
+ subcategoriesList.add(subCategory.get());
+ Either<List<ImmutablePair<SubCategoryData, GraphEdge>>, TitanOperationStatus> subcategories = Either.left(subcategoriesList);
+
+ //prepare category
+ CategoryData categoryData = new CategoryData(NodeTypeEnum.ResourceNewCategory);
+ categoryData.getCategoryDataDefinition().setUniqueId(UUID.randomUUID().toString());
+ categoryData.getCategoryDataDefinition().setName(categoryName);
+ Either<CategoryData, StorageOperationStatus> categoryResult = Either.left(categoryData);
+ List<CategoryData> categoryDataList = new ArrayList<>();
+ categoryDataList.add(categoryResult.left().value());
+ Either<ImmutablePair<CategoryData, GraphEdge>, TitanOperationStatus> categoryNode =
+ Either.left(new ImmutablePair<CategoryData, GraphEdge>(categoryData, new GraphEdge()));
+ Map<String, Object> categoryProps = new HashMap<>();
+ categoryProps.put(GraphPropertiesDictionary.NAME.getProperty(), categoryName);
+ //prepare graph
+ Either<TitanGraph, TitanOperationStatus> graphResult = Either.left(Mockito.mock(TitanGraph.class));
+ TitanGraph titanGraph = graphResult.left().value();
+ TitanVertex vertex = Mockito.mock(TitanVertex.class);
+ Iterator<Edge> iterCreator = Mockito.mock(Iterator.class);
+ Vertex vertexCreator = Mockito.mock(Vertex.class);
+ Edge edge = Mockito.mock(Edge.class);
+ List<TitanVertex> verteciesList= new ArrayList<>();
+ verteciesList.add(vertex);
+ Iterable<TitanVertex> vertecies = new ArrayList<>(verteciesList);
+ @SuppressWarnings("rawtypes")
+ TitanGraphQuery qBuilder = Mockito.mock(GraphCentricQueryBuilder.class);
+
+ when(titanGenericDao.getByCriteria(NodeTypeEnum.ResourceNewCategory, categoryProps, CategoryData.class)).thenReturn(Either.left(categoryDataList));
+ when(elementOperation.getNewCategoryData(categoryName, NodeTypeEnum.ResourceNewCategory, CategoryData.class)).thenReturn(categoryResult);
+ when(titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceNewCategory), categoryData.getCategoryDataDefinition().getUniqueId(),
+ GraphEdgeLabels.SUB_CATEGORY, NodeTypeEnum.ResourceSubcategory, SubCategoryData.class)).thenReturn(subcategories);
+ when(titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), null,
+ GraphEdgeLabels.CATEGORY, NodeTypeEnum.ResourceSubcategory, SubCategoryData.class)).thenReturn(subcategories);
+ when(titanGenericDao.getParentNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceSubcategory), (String) subCategoryData.getSubCategoryDataDefinition().getUniqueId(),
+ GraphEdgeLabels.SUB_CATEGORY, NodeTypeEnum.ResourceNewCategory, CategoryData.class)).thenReturn(categoryNode);
+ when(titanGenericDao.getParentNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceSubcategory), subCategoryData.getSubCategoryDataDefinition().getUniqueId(),
+ GraphEdgeLabels.CATEGORY, NodeTypeEnum.Resource, ResourceMetadataData.class)).thenReturn(parentNodes);
+ when(titanGenericDao.getGraph()).thenReturn(graphResult);
+ when(vertex.edges(Direction.IN, GraphEdgeLabels.CREATOR.name())).thenReturn(iterCreator);
+ when(vertex.edges(Direction.IN, GraphEdgeLabels.LAST_MODIFIER.name())).thenReturn(iterCreator);
+ when(iterCreator.hasNext()).thenReturn(true);
+ when(iterCreator.next()).thenReturn(edge);
+ when(edge.outVertex()).thenReturn(vertexCreator);
+ when(titanGenericDao.getProperties(vertex)).thenReturn(resourceProps);
+ when(titanGraph.query()).thenReturn(qBuilder);
+ when(qBuilder.has(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceMeta.getUniqueId())).thenReturn(qBuilder);
+ when(qBuilder.vertices()).thenReturn(vertecies);
+ when(titanGenericDao.getByCriteria(NodeTypeEnum.Resource, resourceProps, ResourceMetadataData.class))
+ .thenReturn(getResources);
}
}
diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ServiceOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ServiceOperationTest.java
index 81a5a5ed1d..52686fbfa9 100644
--- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ServiceOperationTest.java
+++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ServiceOperationTest.java
@@ -106,7 +106,7 @@ public class ServiceOperationTest extends ModelTestBase {
private LifecycleOperation lifecycleOperation;
private static Logger log = LoggerFactory.getLogger(ServiceOperation.class.getName());
- private static String USER_ID = "muserId";
+ private static String USER_ID = "muUserId";
private static String CATEGORY_NAME = "category/mycategory";
@BeforeClass
@@ -184,8 +184,7 @@ public class ServiceOperationTest extends ModelTestBase {
log.debug(" *** delete **");
log.debug("{}", serviceDelete.left().value());
- Either<List<ArtifactData>, TitanOperationStatus> artifacts = titanDao.getByCriteria(NodeTypeEnum.ArtifactRef,
- null, ArtifactData.class);
+ Either<List<ArtifactData>, TitanOperationStatus> artifacts = titanDao.getByCriteria(NodeTypeEnum.ArtifactRef, null, ArtifactData.class);
assertTrue(artifacts.isRight());
assertEquals(TitanOperationStatus.NOT_FOUND, artifacts.right().value());
@@ -203,10 +202,7 @@ public class ServiceOperationTest extends ModelTestBase {
log.debug("{}", serviceAfterSave);
String uniqueId = serviceAfterSave.getUniqueId();
- boolean canWorkOnComponent = ComponentValidationUtils.canWorkOnComponent(uniqueId, serviceOperation, userId);
- assertTrue(canWorkOnComponent);
-
- canWorkOnComponent = ComponentValidationUtils.canWorkOnComponent(serviceAfterSave, userId);
+ boolean canWorkOnComponent = ComponentValidationUtils.canWorkOnComponent(serviceAfterSave, userId);
assertTrue(canWorkOnComponent);
StorageOperationStatus lockComponent = graphLockOperation.lockComponent(uniqueId, NodeTypeEnum.Service);
@@ -228,17 +224,14 @@ public class ServiceOperationTest extends ModelTestBase {
log.debug(" *** create **");
log.debug("{}", serviceAfterSave);
- Either<Integer, StorageOperationStatus> counter = serviceOperation
- .increaseAndGetComponentInstanceCounter(serviceAfterSave.getUniqueId(), NodeTypeEnum.Service, false);
+ Either<Integer, StorageOperationStatus> counter = serviceOperation.increaseAndGetComponentInstanceCounter(serviceAfterSave.getUniqueId(), NodeTypeEnum.Service, false);
assertTrue(counter.isLeft());
assertEquals(new Integer(1), (Integer) counter.left().value());
- counter = serviceOperation.increaseAndGetComponentInstanceCounter(serviceAfterSave.getUniqueId(),
- NodeTypeEnum.Service, false);
+ counter = serviceOperation.increaseAndGetComponentInstanceCounter(serviceAfterSave.getUniqueId(), NodeTypeEnum.Service, false);
assertTrue(counter.isLeft());
assertEquals(new Integer(2), (Integer) counter.left().value());
- Either<Service, StorageOperationStatus> serviceDelete = serviceOperation
- .deleteService(serviceAfterSave.getUniqueId());
+ Either<Service, StorageOperationStatus> serviceDelete = serviceOperation.deleteService(serviceAfterSave.getUniqueId());
}
@Test
@@ -288,8 +281,7 @@ public class ServiceOperationTest extends ModelTestBase {
Either<Service, StorageOperationStatus> serviceDelete = serviceOperation.deleteService(serviceId);
- Either<List<ArtifactData>, TitanOperationStatus> byCriteria = titanDao.getByCriteria(NodeTypeEnum.ArtifactRef,
- null, ArtifactData.class);
+ Either<List<ArtifactData>, TitanOperationStatus> byCriteria = titanDao.getByCriteria(NodeTypeEnum.ArtifactRef, null, ArtifactData.class);
assertTrue(byCriteria.isRight());
assertEquals(TitanOperationStatus.NOT_FOUND, byCriteria.right().value());
@@ -312,13 +304,11 @@ public class ServiceOperationTest extends ModelTestBase {
artifactInfo.setCreatorFullName(fullName);
artifactInfo.setCreationDate(time);
artifactInfo.setLastUpdateDate(time);
-
artifactInfo.setUserIdLastUpdater(userId);
artifactInfo.setArtifactLabel(artifactName);
artifactInfo.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(serviceId, artifactInfo.getArtifactLabel()));
- Either<ArtifactDefinition, StorageOperationStatus> artifact = artifactOperation
- .addArifactToComponent(artifactInfo, serviceId, NodeTypeEnum.Service, true, true);
+ Either<ArtifactDefinition, StorageOperationStatus> artifact = artifactOperation.addArifactToComponent(artifactInfo, serviceId, NodeTypeEnum.Service, true, true);
assertTrue(artifact.isLeft());
return artifactInfo;
}
@@ -338,8 +328,7 @@ public class ServiceOperationTest extends ModelTestBase {
Set<LifecycleStateEnum> lastStateStates = new HashSet<LifecycleStateEnum>();
lastStateStates.add(LifecycleStateEnum.CERTIFIED);
- Either<List<Service>, StorageOperationStatus> followed = serviceOperation.getFollowed(userId, lifecycleStates,
- lastStateStates, false);
+ Either<List<Service>, StorageOperationStatus> followed = serviceOperation.getFollowed(userId, lifecycleStates, lastStateStates, false);
assertTrue(followed.isLeft());
List<Service> list = followed.left().value();
assertEquals(1, list.size());
@@ -369,8 +358,7 @@ public class ServiceOperationTest extends ModelTestBase {
}
- public Service createService(String userId, String category, String serviceName, String serviceVersion,
- boolean isHighestVersion) {
+ public Service createService(String userId, String category, String serviceName, String serviceVersion, boolean isHighestVersion) {
Service service = buildServiceMetadata(userId, category, serviceName, serviceVersion);
@@ -385,8 +373,7 @@ public class ServiceOperationTest extends ModelTestBase {
// assertEquals("check resource unique id",
// UniqueIdBuilder.buildServiceUniqueId(serviceName, serviceVersion),
// resultService.getUniqueId());
- assertEquals("check resource state", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT,
- resultService.getLifecycleState());
+ assertEquals("check resource state", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, resultService.getLifecycleState());
return resultService;
}
@@ -395,11 +382,6 @@ public class ServiceOperationTest extends ModelTestBase {
public void testCloneFullService() {
// try{
String userId = USER_ID;
- // Either<Service, StorageOperationStatus> deleteService =
- // serviceOperation.deleteService(UniqueIdBuilder.buildServiceUniqueId("my-service",
- // "1.0"), false);
- // log.info("testCloneFullService - after delete service. result
- // is="+deleteService);
Service origService = createService(userId, CATEGORY_NAME, "my-service", "1.0", true);
// add artifacts
@@ -408,12 +390,10 @@ public class ServiceOperationTest extends ModelTestBase {
// add resource instances
ResourceInstanceOperationTest riTest = new ResourceInstanceOperationTest();
- riTest.setOperations(titanDao, capabilityTypeOperation, requirementOperation, capabilityOperation,
- resourceOperation, propertyOperation, resourceInstanceOperation);
+ riTest.setOperations(titanDao, capabilityTypeOperation, requirementOperation, capabilityOperation, resourceOperation, propertyOperation, resourceInstanceOperation);
riTest.addResourceInstancesAndRelation(origService.getUniqueId());
- Either<Service, StorageOperationStatus> service2 = serviceOperation.getService(origService.getUniqueId(),
- false);
+ Either<Service, StorageOperationStatus> service2 = serviceOperation.getService(origService.getUniqueId(), false);
assertTrue(service2.isLeft());
origService = service2.left().value();
@@ -423,16 +403,13 @@ public class ServiceOperationTest extends ModelTestBase {
Service fullService = origService;
- Either<Service, StorageOperationStatus> createService = serviceOperation.cloneService(fullService, "2.0",
- false);
+ Either<Service, StorageOperationStatus> createService = serviceOperation.cloneService(fullService, "2.0", false);
assertTrue(createService.isLeft());
- Either<Service, StorageOperationStatus> serviceAfterCreate = serviceOperation
- .getServiceByNameAndVersion("my-service", "2.0", null, false);
+ Either<Service, StorageOperationStatus> serviceAfterCreate = serviceOperation.getServiceByNameAndVersion("my-service", "2.0", null, false);
assertTrue(serviceAfterCreate.isLeft());
fullService = serviceAfterCreate.left().value();
- Either<Service, StorageOperationStatus> getOrigService = serviceOperation
- .getServiceByNameAndVersion("my-service", "1.0", null, false);
+ Either<Service, StorageOperationStatus> getOrigService = serviceOperation.getServiceByNameAndVersion("my-service", "1.0", null, false);
assertTrue(getOrigService.isLeft());
origService = getOrigService.left().value();
@@ -440,8 +417,7 @@ public class ServiceOperationTest extends ModelTestBase {
// fullService.getComponentMetadataDefinition());
assertEquals(origService.getArtifacts().size(), fullService.getArtifacts().size());
assertEquals(origService.getComponentInstances().size(), fullService.getComponentInstances().size());
- assertEquals(origService.getComponentInstancesRelations().size(),
- fullService.getComponentInstancesRelations().size());
+ assertEquals(origService.getComponentInstancesRelations().size(), fullService.getComponentInstancesRelations().size());
origService.setUniqueId(fullService.getUniqueId());
origService.setVersion(fullService.getVersion());
@@ -469,21 +445,14 @@ public class ServiceOperationTest extends ModelTestBase {
// @Test
public void testCloneServiceWithoutResourceInstances() {
- // try{
String userId = USER_ID;
- // Either<Service, StorageOperationStatus> deleteService =
- // serviceOperation.deleteService(UniqueIdBuilder.buildServiceUniqueId("my-service",
- // "1.0"), false);
- // log.info("testCloneServiceWithoutResourceInstances - after delete
- // service. result is="+deleteService);
Service origService = createService(userId, CATEGORY_NAME, "my-service", "1.0", true);
// add artifacts
addArtifactToService(userId, origService.getUniqueId(), "install_apache");
addArtifactToService(userId, origService.getUniqueId(), "start_apache");
- Either<Service, StorageOperationStatus> service2 = serviceOperation.getService(origService.getUniqueId(),
- false);
+ Either<Service, StorageOperationStatus> service2 = serviceOperation.getService(origService.getUniqueId(), false);
assertTrue(service2.isLeft());
origService = service2.left().value();
@@ -493,16 +462,13 @@ public class ServiceOperationTest extends ModelTestBase {
Service fullService = origService;
- Either<Service, StorageOperationStatus> createService = serviceOperation.cloneService(fullService, "2.0",
- false);
+ Either<Service, StorageOperationStatus> createService = serviceOperation.cloneService(fullService, "2.0", false);
assertTrue(createService.isLeft());
- Either<Service, StorageOperationStatus> serviceAfterCreate = serviceOperation
- .getServiceByNameAndVersion("my-service", "2.0", null, false);
+ Either<Service, StorageOperationStatus> serviceAfterCreate = serviceOperation.getServiceByNameAndVersion("my-service", "2.0", null, false);
assertTrue(serviceAfterCreate.isLeft());
fullService = serviceAfterCreate.left().value();
- Either<Service, StorageOperationStatus> getOrigService = serviceOperation
- .getServiceByNameAndVersion("my-service", "1.0", null, false);
+ Either<Service, StorageOperationStatus> getOrigService = serviceOperation.getServiceByNameAndVersion("my-service", "1.0", null, false);
assertTrue(getOrigService.isLeft());
origService = getOrigService.left().value();
@@ -528,20 +494,15 @@ public class ServiceOperationTest extends ModelTestBase {
// @Test
public void testCloneServiceWithoutArtifacts() {
- // try{
-
String userId = USER_ID;
-
Service origService = createService(userId, CATEGORY_NAME, "my-service", "1.0", true);
// add resource instances
ResourceInstanceOperationTest riTest = new ResourceInstanceOperationTest();
- riTest.setOperations(titanDao, capabilityTypeOperation, requirementOperation, capabilityOperation,
- resourceOperation, propertyOperation, resourceInstanceOperation);
+ riTest.setOperations(titanDao, capabilityTypeOperation, requirementOperation, capabilityOperation, resourceOperation, propertyOperation, resourceInstanceOperation);
riTest.addResourceInstancesAndRelation(origService.getUniqueId());
- Either<Service, StorageOperationStatus> service2 = serviceOperation.getService(origService.getUniqueId(),
- false);
+ Either<Service, StorageOperationStatus> service2 = serviceOperation.getService(origService.getUniqueId(), false);
assertTrue(service2.isLeft());
origService = service2.left().value();
@@ -551,23 +512,19 @@ public class ServiceOperationTest extends ModelTestBase {
Service fullService = origService;
- Either<Service, StorageOperationStatus> createService = serviceOperation.cloneService(fullService, "2.0",
- false);
+ Either<Service, StorageOperationStatus> createService = serviceOperation.cloneService(fullService, "2.0", false);
assertTrue(createService.isLeft());
- Either<Service, StorageOperationStatus> serviceAfterCreate = serviceOperation
- .getServiceByNameAndVersion("my-service", "2.0", null, false);
+ Either<Service, StorageOperationStatus> serviceAfterCreate = serviceOperation.getServiceByNameAndVersion("my-service", "2.0", null, false);
assertTrue(serviceAfterCreate.isLeft());
fullService = serviceAfterCreate.left().value();
- Either<Service, StorageOperationStatus> getOrigService = serviceOperation
- .getServiceByNameAndVersion("my-service", "1.0", null, false);
+ Either<Service, StorageOperationStatus> getOrigService = serviceOperation.getServiceByNameAndVersion("my-service", "1.0", null, false);
assertTrue(getOrigService.isLeft());
origService = getOrigService.left().value();
assertEquals(origService.getArtifacts(), fullService.getArtifacts());
assertEquals(origService.getComponentInstances().size(), fullService.getComponentInstances().size());
- assertEquals(origService.getComponentInstancesRelations().size(),
- fullService.getComponentInstancesRelations().size());
+ assertEquals(origService.getComponentInstancesRelations().size(), fullService.getComponentInstancesRelations().size());
origService.setUniqueId(fullService.getUniqueId());
origService.setVersion(fullService.getVersion());
@@ -585,16 +542,9 @@ public class ServiceOperationTest extends ModelTestBase {
// @Test
public void testCloneServiceSimple() {
- // try{
String userId = USER_ID;
String serviceName = "serviceToClone";
- //
- // Either<Service, StorageOperationStatus> deleteService =
- // serviceOperation.deleteService(UniqueIdBuilder.buildServiceUniqueId(serviceName,
- // "1.0"));
- // log.info("testCloneServiceSimple - after delete service. result
- // is="+deleteService);
-
+
Service origService = createService(userId, CATEGORY_NAME, serviceName, "1.0", true);
Gson prettyGson = new GsonBuilder().setPrettyPrinting().create();
@@ -603,16 +553,13 @@ public class ServiceOperationTest extends ModelTestBase {
Service fullService = origService;
- Either<Service, StorageOperationStatus> createService = serviceOperation.cloneService(fullService, "2.0",
- false);
+ Either<Service, StorageOperationStatus> createService = serviceOperation.cloneService(fullService, "2.0", false);
assertTrue(createService.isLeft());
- Either<Service, StorageOperationStatus> serviceAfterCreate = serviceOperation
- .getServiceByNameAndVersion(serviceName, "2.0", null, false);
+ Either<Service, StorageOperationStatus> serviceAfterCreate = serviceOperation.getServiceByNameAndVersion(serviceName, "2.0", null, false);
assertTrue(serviceAfterCreate.isLeft());
fullService = serviceAfterCreate.left().value();
- Either<Service, StorageOperationStatus> getOrigService = serviceOperation
- .getServiceByNameAndVersion(serviceName, "1.0", null, false);
+ Either<Service, StorageOperationStatus> getOrigService = serviceOperation.getServiceByNameAndVersion(serviceName, "1.0", null, false);
assertTrue(getOrigService.isLeft());
origService = getOrigService.left().value();
@@ -665,13 +612,9 @@ public class ServiceOperationTest extends ModelTestBase {
OperationTestsUtil.deleteAndCreateResourceCategory(names[0], names[1], titanDao);
/*
- * CategoryData categoryData = new CategoryData();
- * categoryData.setName(category);
+ * CategoryData categoryData = new CategoryData(); categoryData.setName(category);
*
- * titanDao.deleteNode(categoryData, CategoryData.class);
- * Either<CategoryData, TitanOperationStatus> createNode =
- * titanDao.createNode(categoryData, CategoryData.class);
- * System.out.println("after creating caetgory " + createNode);
+ * titanDao.deleteNode(categoryData, CategoryData.class); Either<CategoryData, TitanOperationStatus> createNode = titanDao.createNode(categoryData, CategoryData.class); System.out.println("after creating caetgory " + createNode);
*/
}
@@ -707,8 +650,7 @@ public class ServiceOperationTest extends ModelTestBase {
Map<String, Object> propertiesToMatch = new HashMap<>();
propertiesToMatch.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFIED.name());
- Either<Set<Service>, StorageOperationStatus> catalog = serviceOperation.getCatalogData(propertiesToMatch,
- false);
+ Either<Set<Service>, StorageOperationStatus> catalog = serviceOperation.getCatalogData(propertiesToMatch, false);
assertTrue(catalog.isLeft());
Set<Service> catalogSet = catalog.left().value();
Set<String> idSet = new HashSet<>();
@@ -770,22 +712,19 @@ public class ServiceOperationTest extends ModelTestBase {
String serviceId3 = resultService3.getUniqueId();
// update 1 service to READY_FOR_CERTIFICATION
- Either<? extends Component, StorageOperationStatus> certReqResponse = lifecycleOperation
- .requestCertificationComponent(NodeTypeEnum.Service, resultService, adminUser, adminUser, false);
+ Either<? extends Component, StorageOperationStatus> certReqResponse = lifecycleOperation.requestCertificationComponent(NodeTypeEnum.Service, resultService, adminUser, adminUser, false);
Service RFCService = (Service) certReqResponse.left().value();
assertEquals(RFCService.getLifecycleState(), LifecycleStateEnum.READY_FOR_CERTIFICATION);
// update 1 service to CERTIFICATION_IN_PROGRESS
- Either<? extends Component, StorageOperationStatus> startCertificationResponse = lifecycleOperation
- .startComponentCertification(NodeTypeEnum.Service, resultService2, testerUser, adminUser, false);
+ Either<? extends Component, StorageOperationStatus> startCertificationResponse = lifecycleOperation.startComponentCertification(NodeTypeEnum.Service, resultService2, testerUser, adminUser, false);
Service IPService = (Service) startCertificationResponse.left().value();
assertEquals(IPService.getLifecycleState(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
Set<LifecycleStateEnum> lifecycleStates = new HashSet<LifecycleStateEnum>();
lifecycleStates.add(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
- Either<List<Service>, StorageOperationStatus> services = serviceOperation.getTesterFollowed(testerUserId,
- lifecycleStates, false);
+ Either<List<Service>, StorageOperationStatus> services = serviceOperation.getTesterFollowed(testerUserId, lifecycleStates, false);
assertTrue(services.isLeft());
List<Service> result = services.left().value();
@@ -830,42 +769,31 @@ public class ServiceOperationTest extends ModelTestBase {
String serviceId4 = resultService4.getUniqueId();
// update 1 service to CERTIFIED dist status DISTRIBUTED
- Either<? extends Component, StorageOperationStatus> reqCertificationResult = lifecycleOperation
- .requestCertificationComponent(NodeTypeEnum.Service, resultService, adminUser, adminUser, false);
- Either<? extends Component, StorageOperationStatus> startCertificationResult = lifecycleOperation
- .startComponentCertification(NodeTypeEnum.Service, resultService, adminUser, adminUser, false);
+ Either<? extends Component, StorageOperationStatus> reqCertificationResult = lifecycleOperation.requestCertificationComponent(NodeTypeEnum.Service, resultService, adminUser, adminUser, false);
+ Either<? extends Component, StorageOperationStatus> startCertificationResult = lifecycleOperation.startComponentCertification(NodeTypeEnum.Service, resultService, adminUser, adminUser, false);
Service actualService = (Service) startCertificationResult.left().value();
- Either<? extends Component, StorageOperationStatus> certResponse = lifecycleOperation
- .certifyComponent(NodeTypeEnum.Service, resultService, adminUser, adminUser, false);
+ Either<? extends Component, StorageOperationStatus> certResponse = lifecycleOperation.certifyComponent(NodeTypeEnum.Service, resultService, adminUser, adminUser, false);
Service certifiedService = (Service) certResponse.left().value();
serviceOperation.updateDestributionStatus(resultService, adminUser, DistributionStatusEnum.DISTRIBUTED);
// update 1 service to CERTIFIED dist status DISTRIBUTION_APPROVED
- Either<? extends Component, StorageOperationStatus> reqCertificationResult2 = lifecycleOperation
- .requestCertificationComponent(NodeTypeEnum.Service, resultService2, adminUser, adminUser, false);
- Either<? extends Component, StorageOperationStatus> startCertificationResult2 = lifecycleOperation
- .startComponentCertification(NodeTypeEnum.Service, resultService2, adminUser, adminUser, false);
+ Either<? extends Component, StorageOperationStatus> reqCertificationResult2 = lifecycleOperation.requestCertificationComponent(NodeTypeEnum.Service, resultService2, adminUser, adminUser, false);
+ Either<? extends Component, StorageOperationStatus> startCertificationResult2 = lifecycleOperation.startComponentCertification(NodeTypeEnum.Service, resultService2, adminUser, adminUser, false);
Service actualService2 = (Service) startCertificationResult2.left().value();
- Either<? extends Component, StorageOperationStatus> certResponse2 = lifecycleOperation
- .certifyComponent(NodeTypeEnum.Service, resultService2, adminUser, adminUser, false);
+ Either<? extends Component, StorageOperationStatus> certResponse2 = lifecycleOperation.certifyComponent(NodeTypeEnum.Service, resultService2, adminUser, adminUser, false);
Service certifiedService2 = (Service) certResponse2.left().value();
- serviceOperation.updateDestributionStatus(resultService2, adminUser,
- DistributionStatusEnum.DISTRIBUTION_APPROVED);
+ serviceOperation.updateDestributionStatus(resultService2, adminUser, DistributionStatusEnum.DISTRIBUTION_APPROVED);
// update 1 service to CERTIFIED dist status DISTRIBUTION_REJECTED
- Either<? extends Component, StorageOperationStatus> reqCertificationResult3 = lifecycleOperation
- .requestCertificationComponent(NodeTypeEnum.Service, resultService3, adminUser, adminUser, false);
- Either<? extends Component, StorageOperationStatus> startCertificationResult3 = lifecycleOperation
- .startComponentCertification(NodeTypeEnum.Service, resultService3, adminUser, adminUser, false);
+ Either<? extends Component, StorageOperationStatus> reqCertificationResult3 = lifecycleOperation.requestCertificationComponent(NodeTypeEnum.Service, resultService3, adminUser, adminUser, false);
+ Either<? extends Component, StorageOperationStatus> startCertificationResult3 = lifecycleOperation.startComponentCertification(NodeTypeEnum.Service, resultService3, adminUser, adminUser, false);
Service actualService3 = (Service) startCertificationResult3.left().value();
- Either<? extends Component, StorageOperationStatus> certResponse3 = lifecycleOperation
- .certifyComponent(NodeTypeEnum.Service, actualService3, adminUser, adminUser, false);
+ Either<? extends Component, StorageOperationStatus> certResponse3 = lifecycleOperation.certifyComponent(NodeTypeEnum.Service, actualService3, adminUser, adminUser, false);
Service certifiedService3 = (Service) certResponse3.left().value();
- serviceOperation.updateDestributionStatus(certifiedService3, adminUser,
- DistributionStatusEnum.DISTRIBUTION_REJECTED);
+ serviceOperation.updateDestributionStatus(certifiedService3, adminUser, DistributionStatusEnum.DISTRIBUTION_REJECTED);
Map<String, Object> propertiesToMatch = new HashMap<>();
propertiesToMatch.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFIED.name());
@@ -874,8 +802,7 @@ public class ServiceOperationTest extends ModelTestBase {
distStatus.add(DistributionStatusEnum.DISTRIBUTION_APPROVED);
distStatus.add(DistributionStatusEnum.DISTRIBUTED);
- Either<Set<Service>, StorageOperationStatus> services = serviceOperation
- .getCertifiedServicesWithDistStatus(propertiesToMatch, distStatus, false);
+ Either<Set<Service>, StorageOperationStatus> services = serviceOperation.getCertifiedServicesWithDistStatus(propertiesToMatch, distStatus, false);
assertTrue(services.isLeft());
Set<Service> result = services.left().value();
@@ -917,34 +844,27 @@ public class ServiceOperationTest extends ModelTestBase {
String serviceId3 = resultService3.getUniqueId();
// update 1 service to CERTIFIED + DISTRIBUTED
- Either<? extends Component, StorageOperationStatus> reqCertificationResult = lifecycleOperation
- .requestCertificationComponent(NodeTypeEnum.Service, resultService, adminUser, adminUser, false);
- Either<? extends Component, StorageOperationStatus> startCertificationResult = lifecycleOperation
- .startComponentCertification(NodeTypeEnum.Service, resultService, adminUser, adminUser, false);
+ Either<? extends Component, StorageOperationStatus> reqCertificationResult = lifecycleOperation.requestCertificationComponent(NodeTypeEnum.Service, resultService, adminUser, adminUser, false);
+ Either<? extends Component, StorageOperationStatus> startCertificationResult = lifecycleOperation.startComponentCertification(NodeTypeEnum.Service, resultService, adminUser, adminUser, false);
Service actualService = (Service) startCertificationResult.left().value();
- Either<? extends Component, StorageOperationStatus> certResponse = lifecycleOperation
- .certifyComponent(NodeTypeEnum.Service, actualService, adminUser, adminUser, false);
+ Either<? extends Component, StorageOperationStatus> certResponse = lifecycleOperation.certifyComponent(NodeTypeEnum.Service, actualService, adminUser, adminUser, false);
Service certifiedService = (Service) certResponse.left().value();
serviceOperation.updateDestributionStatus(certifiedService, adminUser, DistributionStatusEnum.DISTRIBUTED);
// update 1 service to CERTIFIED dist status + DISTRIBUTION_REJECTED
- Either<? extends Component, StorageOperationStatus> reqCertificationResult2 = lifecycleOperation
- .requestCertificationComponent(NodeTypeEnum.Service, resultService2, adminUser, adminUser, false);
- Either<? extends Component, StorageOperationStatus> startCertificationResult2 = lifecycleOperation
- .startComponentCertification(NodeTypeEnum.Service, resultService2, adminUser, adminUser, false);
+ Either<? extends Component, StorageOperationStatus> reqCertificationResult2 = lifecycleOperation.requestCertificationComponent(NodeTypeEnum.Service, resultService2, adminUser, adminUser, false);
+ Either<? extends Component, StorageOperationStatus> startCertificationResult2 = lifecycleOperation.startComponentCertification(NodeTypeEnum.Service, resultService2, adminUser, adminUser, false);
Service actualService2 = (Service) startCertificationResult2.left().value();
- Either<? extends Component, StorageOperationStatus> certResponse2 = lifecycleOperation
- .certifyComponent(NodeTypeEnum.Service, actualService2, adminUser, adminUser, false);
+ Either<? extends Component, StorageOperationStatus> certResponse2 = lifecycleOperation.certifyComponent(NodeTypeEnum.Service, actualService2, adminUser, adminUser, false);
Service certifiedService2 = (Service) certResponse2.left().value();
serviceOperation.updateDestributionStatus(certifiedService2, adminUser, DistributionStatusEnum.DISTRIBUTED);
Map<String, Object> propertiesToMatch = new HashMap<>();
propertiesToMatch.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFIED.name());
- Either<Set<Service>, StorageOperationStatus> services = serviceOperation
- .getCertifiedServicesWithDistStatus(propertiesToMatch, null, false);
+ Either<Set<Service>, StorageOperationStatus> services = serviceOperation.getCertifiedServicesWithDistStatus(propertiesToMatch, null, false);
assertTrue(services.isLeft());
Set<Service> result = services.left().value();
diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ToscaDefinitionPathCalculatorTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ToscaDefinitionPathCalculatorTest.java
new file mode 100644
index 0000000000..9aa0842bb3
--- /dev/null
+++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ToscaDefinitionPathCalculatorTest.java
@@ -0,0 +1,61 @@
+package org.openecomp.sdc.be.model.operations.impl;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
+import org.openecomp.sdc.be.dao.neo4j.GraphEdgePropertiesDictionary;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.operations.api.ToscaDefinitionPathCalculator;
+
+import java.util.Collections;
+import java.util.List;
+
+import static org.junit.Assert.assertEquals;
+
+public class ToscaDefinitionPathCalculatorTest {
+
+ private static final String INSTANCE_ID = "123";
+ private static final String OWNER_ID = "321";
+
+ private ToscaDefinitionPathCalculator toscaDefinitionPathCalculator;
+
+
+ @Before
+ public void setUp() throws Exception {
+ toscaDefinitionPathCalculator = new ToscaDefinitionPathCalculatorImpl();
+ }
+
+ @Test
+ public void calculatePath_ownerAndComponentInstanceEqual() throws Exception {
+ ComponentInstance instance = getComponentInstance(INSTANCE_ID);
+ GraphEdge edge = createEdgeWithOwner(INSTANCE_ID);
+ List<String> definitionPath = toscaDefinitionPathCalculator.calculateToscaDefinitionPath(instance, edge);
+ assertEquals(1, definitionPath.size());
+ assertEquals(INSTANCE_ID, definitionPath.get(0));
+ }
+
+ @Test
+ public void calculatePath() throws Exception {
+ ComponentInstance instance = getComponentInstance(INSTANCE_ID);
+ GraphEdge edge = createEdgeWithOwner(OWNER_ID);
+ List<String> definitionPath = toscaDefinitionPathCalculator.calculateToscaDefinitionPath(instance, edge);
+ assertEquals(2, definitionPath.size());
+ assertEquals(INSTANCE_ID, definitionPath.get(0));
+ assertEquals(OWNER_ID, definitionPath.get(1));
+
+ }
+
+
+ private ComponentInstance getComponentInstance(String instanceId) {
+ ComponentInstance instance = new ComponentInstance();
+ instance.setUniqueId(instanceId);
+ return instance;
+ }
+
+ private GraphEdge createEdgeWithOwner(String owner) {
+ GraphEdge edge = new GraphEdge();
+ edge.setProperties(Collections.singletonMap(GraphEdgePropertiesDictionary.OWNER_ID.getProperty(), owner));
+ return edge;
+ }
+
+}
diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ToscaElementLifecycleOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ToscaElementLifecycleOperationTest.java
new file mode 100644
index 0000000000..103d430009
--- /dev/null
+++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ToscaElementLifecycleOperationTest.java
@@ -0,0 +1,579 @@
+package org.openecomp.sdc.be.model.operations.impl;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.OutputStream;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.tinkerpop.gremlin.structure.io.IoCore;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TestName;
+import org.junit.runner.RunWith;
+import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
+import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
+
+import org.openecomp.sdc.be.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.MapPropertiesDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.MapDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
+import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
+import org.openecomp.sdc.be.datatypes.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.category.CategoryDefinition;
+import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
+
+import org.openecomp.sdc.be.model.jsontitan.datamodel.NodeType;
+import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate;
+import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement;
+import org.openecomp.sdc.be.model.jsontitan.operations.NodeTypeOperation;
+import org.openecomp.sdc.be.model.jsontitan.operations.TopologyTemplateOperation;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementLifecycleOperation;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.common.util.ValidationUtils;
+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 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();
+
+ @BeforeClass
+ public static void initLifecycleOperation() {
+ ModelTestBase.init();
+ }
+
+ private GraphVertex ownerVertex;
+ private GraphVertex modifierVertex;
+ private GraphVertex vfVertex;
+ private GraphVertex serviceVertex;
+
+ @Before
+ public void setupBefore() {
+ clearGraph();
+ createUsers();
+ createResourceCategory();
+ createServiceCategory();
+ createRootNodeType();
+ createNodeType("firstVf");
+ 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());
+ StorageOperationStatus status;
+
+ assertTrue(res.isLeft());
+ String id = res.left().value().getUniqueId();
+
+ res = lifecycleOperation.checkoutToscaElement(id, ownerVertex.getUniqueId(), modifierVertex.getUniqueId());
+ assertTrue(res.isLeft());
+ id = res.left().value().getUniqueId();
+
+ 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();
+
+ res = lifecycleOperation.checkoutToscaElement(id, ownerVertex.getUniqueId(), modifierVertex.getUniqueId());
+ assertTrue(res.isLeft());
+ id = res.left().value().getUniqueId();
+
+ 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();
+
+ res = lifecycleOperation.checkoutToscaElement(id, ownerVertex.getUniqueId(), ownerVertex.getUniqueId());
+ assertTrue(res.isLeft());
+ id = res.left().value().getUniqueId();
+
+ 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
+ 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
+ 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());
+
+ }
+
+ @Test
+ public void serviceConformanceLevelTest() {
+ 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() {
+
+ 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.LABEL, VertexTypeEnum.RESOURCE_CATEGORY.getName());
+ metadataProperties.put(GraphPropertyEnum.NAME,categoryName);
+ metadataProperties.put(GraphPropertyEnum.NORMALIZED_NAME, ValidationUtils.normalizeCategoryName4Uniqueness(categoryName));
+ cat.setMetadataProperties(metadataProperties);
+ cat.updateMetadataJsonWithCurrentMetadataProperties();
+
+ GraphVertex subCat = new GraphVertex(VertexTypeEnum.RESOURCE_SUBCATEGORY);
+ metadataProperties = new HashMap<>();
+ String subCatId = UniqueIdBuilder.buildSubCategoryUid(cat.getUniqueId(), subcategory);
+ subCat.setUniqueId(subCatId);
+ metadataProperties.put(GraphPropertyEnum.UNIQUE_ID,subCatId);
+ metadataProperties.put(GraphPropertyEnum.LABEL, VertexTypeEnum.RESOURCE_SUBCATEGORY.getName());
+ metadataProperties.put(GraphPropertyEnum.NAME,subcategory);
+ 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.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());
+ }
+
+ private TopologyTemplate createTopologyTemplate(String name) {
+
+ TopologyTemplate service = new TopologyTemplate();
+ String uniqueId = UniqueIdBuilder.buildResourceUniqueId();
+ service.setUniqueId(uniqueId);
+ service.setCreatorUserId((String) ownerVertex.getMetadataProperty(GraphPropertyEnum.USERID));
+ service.getMetadata().put(JsonPresentationFields.NAME.getPresentation(), name);
+ service.getMetadata().put(JsonPresentationFields.UNIQUE_ID.getPresentation(), uniqueId);
+ service.getMetadata().put(JsonPresentationFields.VERSION.getPresentation(), "0.1");
+ service.getMetadata().put(JsonPresentationFields.TYPE.getPresentation(),ResourceTypeEnum.VF.name());
+ service.getMetadata().put(JsonPresentationFields.COMPONENT_TYPE.getPresentation(),ComponentTypeEnum.RESOURCE);
+ List<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());
+ assertTrue(getNodeTyeRes.isLeft());
+
+ serviceVertex = getNodeTyeRes.left().value();
+
+ return service;
+ }
+
+ private <T extends ToscaDataDefinition> NodeType createNodeType(String nodeTypeName) {
+
+ NodeType vf = new NodeType();
+ String uniqueId = UniqueIdBuilder.buildResourceUniqueId();
+ vf.setUniqueId(uniqueId);
+ vf.setCreatorUserId((String) ownerVertex.getMetadataProperty(GraphPropertyEnum.USERID));
+ vf.getMetadata().put(JsonPresentationFields.NAME.getPresentation(), nodeTypeName);
+ vf.getMetadata().put(JsonPresentationFields.UNIQUE_ID.getPresentation(), uniqueId);
+ vf.getMetadata().put(JsonPresentationFields.VERSION.getPresentation(), "0.1");
+ vf.getMetadata().put(JsonPresentationFields.TYPE.getPresentation(),ResourceTypeEnum.VF.name());
+ vf.getMetadata().put(JsonPresentationFields.COMPONENT_TYPE.getPresentation(),ComponentTypeEnum.RESOURCE);
+ List<CategoryDefinition> categories = new ArrayList<>();
+ CategoryDefinition cat = new CategoryDefinition();
+ categories.add(cat);
+ cat.setName(categoryName);
+ List<SubCategoryDefinition> subCategories = new ArrayList<>();
+ SubCategoryDefinition subCat = new SubCategoryDefinition();
+ subCat.setName(subcategory);
+ 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);
+ Either<NodeType, StorageOperationStatus> createVFRes = nodeTypeOperation.createNodeType(vf);
+ assertTrue(createVFRes.isLeft());
+
+ 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);
+
+ // 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);
+ return vf;
+ }
+
+ private void createRootNodeType() {
+
+ NodeType vf = new NodeType();
+ String uniqueId = UniqueIdBuilder.buildResourceUniqueId();
+ vf.setUniqueId(uniqueId);
+ vf.setComponentType(ComponentTypeEnum.RESOURCE);
+ vf.setCreatorUserId((String) ownerVertex.getMetadataProperty(GraphPropertyEnum.USERID));
+ vf.getMetadata().put(JsonPresentationFields.NAME.getPresentation(), "root");
+ vf.getMetadata().put(JsonPresentationFields.UNIQUE_ID.getPresentation(), uniqueId);
+ vf.getMetadata().put(JsonPresentationFields.VERSION.getPresentation(), "1.0");
+ vf.getMetadata().put(JsonPresentationFields.TYPE.getPresentation(),ResourceTypeEnum.VFC.name());
+ vf.getMetadata().put(JsonPresentationFields.LIFECYCLE_STATE.getPresentation(), LifecycleStateEnum.CERTIFIED.name());
+ vf.getMetadata().put(JsonPresentationFields.TOSCA_RESOURCE_NAME.getPresentation(), "root");
+ vf.getMetadata().put(JsonPresentationFields.HIGHEST_VERSION.getPresentation(), true);
+
+ List<CategoryDefinition> categories = new ArrayList<>();
+ CategoryDefinition cat = new CategoryDefinition();
+ categories.add(cat);
+ cat.setName(categoryName);
+ List<SubCategoryDefinition> subCategories = new ArrayList<>();
+ SubCategoryDefinition subCat = new SubCategoryDefinition();
+ subCat.setName(subcategory);
+ 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);
+ Either<NodeType, StorageOperationStatus> createVFRes = nodeTypeOperation.createNodeType(vf);
+ assertTrue(createVFRes.isLeft());
+
+ Either<GraphVertex, TitanOperationStatus> getNodeTyeRes= titanDao.getVertexById(createVFRes.left().value().getUniqueId());
+ assertTrue(getNodeTyeRes.isLeft());
+ }
+
+ 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());
+ metadataProperties.put(GraphPropertyEnum.NAME, "user1");
+ ownerV.setMetadataProperties(metadataProperties);
+ ownerV.updateMetadataJsonWithCurrentMetadataProperties();
+ 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());
+ metadataProperties.put(GraphPropertyEnum.NAME, "user2");
+ modifierV.setMetadataProperties(metadataProperties);
+ modifierV.updateMetadataJsonWithCurrentMetadataProperties();
+ 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());
+
+ }
+
+ @After
+ public void teardown() {
+ clearGraph();
+ }
+
+ private void clearGraph() {
+ Either<TitanGraph, TitanOperationStatus> graphResult = titanDao.getGraph();
+ TitanGraph graph = graphResult.left().value();
+
+ Iterable<TitanVertex> vertices = graph.query().vertices();
+ if (vertices != null) {
+ Iterator<TitanVertex> iterator = vertices.iterator();
+ while (iterator.hasNext()) {
+ TitanVertex vertex = iterator.next();
+ vertex.remove();
+ }
+ }
+ titanDao.commit();
+ }
+
+ private String exportGraphMl(TitanGraph graph) {
+ String result = null;
+ String outputFile = outputDirectory + File.separator + "exportGraph." + System.currentTimeMillis() + ".graphml";
+ try {
+ try (final OutputStream os = new BufferedOutputStream(new FileOutputStream(outputFile))) {
+ graph.io(IoCore.graphml()).writer().normalize(true).create().writeGraph(os, graph);
+ }
+ result = outputFile;
+ graph.tx().commit();
+ } catch (Exception e) {
+ graph.tx().rollback();
+ e.printStackTrace();
+ }
+ return result;
+
+ }
+
+}
diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/UserAdminOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/UserAdminOperationTest.java
index f77e477ed7..ed496b5e92 100644
--- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/UserAdminOperationTest.java
+++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/UserAdminOperationTest.java
@@ -20,6 +20,8 @@
package org.openecomp.sdc.be.model.operations.impl;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
@@ -27,7 +29,11 @@ import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
+import java.time.Instant;
+import java.time.LocalDateTime;
+import java.time.temporal.TemporalField;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
@@ -61,10 +67,9 @@ import org.openecomp.sdc.common.api.UserRoleEnum;
import fj.data.Either;
public class UserAdminOperationTest extends ModelTestBase {
- @InjectMocks
- private static final UserAdminOperation userAdminOperation = new UserAdminOperation();
private static final TitanGenericDao titanGenericDao = mock(TitanGenericDao.class);
-
+ @InjectMocks
+ private static final UserAdminOperation userAdminOperation = new UserAdminOperation(titanGenericDao);
private static final String ADMIN = "admin";
@BeforeClass
@@ -85,8 +90,7 @@ public class UserAdminOperationTest extends ModelTestBase {
public void testDeActivateUserDataSuccess() {
UserData userData = mockTitanGet(ADMIN, UserRoleEnum.ADMIN, true);
- Either<User, StorageOperationStatus> eitherUser = userAdminOperation
- .deActivateUser(userAdminOperation.convertToUser(userData));
+ Either<User, StorageOperationStatus> eitherUser = userAdminOperation.deActivateUser(userAdminOperation.convertToUser(userData));
verify(titanGenericDao, times(1)).updateNode(Mockito.eq(userData), Mockito.eq(UserData.class));
verify(titanGenericDao, times(0)).deleteNode(Mockito.any(UserData.class), Mockito.eq(UserData.class));
@@ -97,24 +101,32 @@ public class UserAdminOperationTest extends ModelTestBase {
}
/*
- * @Test public void testDeActivateUserDataFail(){ UserData userData =
- * mockTitanGet(ADMIN, UserRoleEnum.ADMIN, false);
+ * @Test public void testDeActivateUserDataFail(){ UserData userData = mockTitanGet(ADMIN, UserRoleEnum.ADMIN, false);
*
- * Either<User, StorageOperationStatus> eitherUser =
- * userAdminOperation.deActivateUser(userAdminOperation.convertToUser(
- * userData));
+ * Either<User, StorageOperationStatus> eitherUser = userAdminOperation.deActivateUser(userAdminOperation.convertToUser( userData));
*
- * verify(titanGenericDao, times(0)).updateNode(Mockito.any(UserData.class),
- * Mockito.eq(UserData.class)); verify(titanGenericDao,
- * times(0)).deleteNode(Mockito.any(UserData.class),
- * Mockito.eq(UserData.class)); assertTrue(eitherUser.isRight());
- * assertTrue(eitherUser.right().value() ==
- * StorageOperationStatus.USER_INACTIVE);
+ * verify(titanGenericDao, times(0)).updateNode(Mockito.any(UserData.class), Mockito.eq(UserData.class)); verify(titanGenericDao, times(0)).deleteNode(Mockito.any(UserData.class), Mockito.eq(UserData.class)); assertTrue(eitherUser.isRight());
+ * assertTrue(eitherUser.right().value() == StorageOperationStatus.USER_INACTIVE);
*
* }
*/
@Test
+ public void testGetAllUsers() throws Exception {
+ UserData user1 = mockTitanGet("user1", UserRoleEnum.ADMIN, true);
+ UserData user2 = mockTitanGet("user2", UserRoleEnum.DESIGNER, false);
+ UserData user3 = mockTitanGet("user3", UserRoleEnum.PRODUCT_MANAGER, true);
+ when(titanGenericDao.getAll(NodeTypeEnum.User, UserData.class)).thenReturn(Either.left(Arrays.asList(user1, user2, user3)));
+
+ List<User> allUsers = userAdminOperation.getAllUsers().left().value();
+ assertEquals(3, allUsers.size());
+ assertUserEquals(user1, allUsers.get(0));
+ assertUserEquals(user2, allUsers.get(1));
+ assertUserEquals(user3, allUsers.get(2));
+ verify(titanGenericDao).commit();
+ }
+
+ @Test
public void testDeleteUserWithoutResources() {
UserData userData = mockTitanGet(ADMIN, UserRoleEnum.ADMIN, true);
@@ -199,8 +211,7 @@ public class UserAdminOperationTest extends ModelTestBase {
private UserData mockTitanGet(String userId, UserRoleEnum role, boolean isActive) {
UserData userData = buildUserData(userId, role, isActive);
Either<UserData, TitanOperationStatus> eitherUserData = Either.left(userData);
- when(titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), userId, UserData.class))
- .thenReturn(eitherUserData);
+ when(titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), userId, UserData.class)).thenReturn(eitherUserData);
return userData;
}
@@ -228,12 +239,25 @@ public class UserAdminOperationTest extends ModelTestBase {
}).when(titanGenericDao).deleteNode(Mockito.any(UserData.class), Mockito.eq(UserData.class));
}
+ private void assertUserEquals(UserData expected, User actual) {
+ assertEquals(expected.getEmail(), actual.getEmail());
+ assertEquals(expected.getFirstName(), actual.getFirstName());
+ assertEquals(expected.getLastName(), actual.getLastName());
+ assertEquals(expected.getRole(), actual.getRole());
+ assertEquals(expected.getStatus(), actual.getStatus().name());
+ assertEquals(expected.getUserId(), actual.getUserId());
+
+ }
+
private static UserData buildUserData(String userId, UserRoleEnum role, boolean isActive) {
UserData userData = new UserData();
userData.setUserId(userId);
userData.setRole(role.getName());
+ userData.setEmail("someEmail@somePlace.com");
+ userData.setFirstName("israel");
+ userData.setLastName("israeli");
+ userData.setLastLoginTime(Instant.MIN.getEpochSecond());
userData.setStatus(isActive ? UserStatusEnum.ACTIVE.name() : UserStatusEnum.INACTIVE.name());
return userData;
-
}
}
diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/util/PrintGraph.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/util/PrintGraph.java
index b58ce5598d..4b89f457bb 100644
--- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/util/PrintGraph.java
+++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/util/PrintGraph.java
@@ -316,7 +316,7 @@ public class PrintGraph {
switch (typeEnum) {
case User:
- uid = (String) properties.get(GraphPropertiesDictionary.USER_ID.getProperty());
+ uid = (String) properties.get(GraphPropertiesDictionary.USERID.getProperty());
break;
case ServiceCategory:
case ResourceCategory:
diff --git a/catalog-model/src/test/resources/application-context-test.xml b/catalog-model/src/test/resources/application-context-test.xml
index 43f4b088e4..58de573b55 100644
--- a/catalog-model/src/test/resources/application-context-test.xml
+++ b/catalog-model/src/test/resources/application-context-test.xml
@@ -8,6 +8,8 @@
<context:component-scan
base-package="org.openecomp.sdc.be.model.operations.impl,
+ org.openecomp.sdc.be.model.jsontitan.operations,
+ org.openecomp.sdc.be.dao.jsongraph,
org.openecomp.sdc.be.model.cache,
org.openecomp.sdc.be.dao.titan,
org.openecomp.sdc.be.dao.cassandra">
diff --git a/catalog-ui/Gruntfile.js b/catalog-ui/Gruntfile.js
deleted file mode 100644
index 619d8316a1..0000000000
--- a/catalog-ui/Gruntfile.js
+++ /dev/null
@@ -1,807 +0,0 @@
-// Generated on 2015-04-28 using
-// generator-webapp 0.5.1
-'use strict';
-
-// # Globbing
-// for performance reasons we're only matching one level down:
-// 'test/spec/{,*/}*.js'
-// If you want to recursively match all subfolders, use:
-// 'test/spec/**/*.js'
-
-module.exports = function (grunt) {
-
- // Time how long tasks take. Can help when optimizing build times
- require('time-grunt')(grunt);
-
- // Load grunt tasks automatically
- require('load-grunt-tasks')(grunt);
-
- // Configurable paths
- var config = {
- app: 'app',
- appModuleName: 'sdcApp',
- dist: 'app/dist'
- };
-
- // Define the configuration for all the tasks
- grunt.initConfig({
-
- // Project settings
- config: config,
-
- // Watches files for changes and runs tasks based on the changed files
- watch: {
- html: {
- files: ['<%= config.app %>/scripts/**/*.html'],
- tasks: ['ngtemplates:app']
- },
- less: {
- files: ['<%= config.app %>/**/*.less'],
- tasks: ['less:all']
- },
- ts: {
- files: ['<%= config.app %>/scripts/**/*.ts'],
- tasks: ['ts:all']
- },
- bower: {
- files: ['bower.json'],
- tasks: ['wiredep']
- },
-
- gruntfile: {
- files: ['Gruntfile.js']
- },
-
- livereload: {
- options: {
- livereload: '<%= connect.options.livereload %>'
- },
- files: [
- '<%= config.app %>/{,*/}*.html',
- '<%= config.app %>/scripts/**/*.html',
- '<%= config.app %>/scripts/**/*.css',
- '.tmp/styles/{,*/}*.css',
- '<%= config.app %>/images/{,*/}*'
- ]
- },
- configurations: {
- files: [
- 'configurations/*.json'
- ],
- tasks: ['ngconstant']
- }
- },
-
- ngconstant: {
- options: {
- dest: 'app/scripts/modules/configurations.js',
- name: 'Sdc.Config'
- },
- main: {
- constants: {
- sdcConfig: grunt.file.readJSON(grunt.option('env') ? 'configurations/' + grunt.option('env') + '.json' : 'configurations/prod.json'),
- sdcMenu: grunt.file.readJSON('configurations/menu.json')
- }
- }
- },
-
- express: {
- options: {
- port: process.env.PORT || 9000
- },
- mock: {
- options: {
- script: 'server-mock/mock-server.js'
- }
- }
- },
-
- ts: {
- all: {
- src: [
- 'app/scripts/**/*.ts',
- 'typings/**/*.ts'
- ],
- reference: 'app/scripts/references.ts'
- },
- single: {
- src: []
- }
- },
- ngtemplates: {
- app: {
- options: {
- module: '<%= config.appModuleName %>',
- prefix: '/'
- },
- src: [
- '<%= config.app %>/scripts/**/*.html',
- '!index.html'
- ],
- dest: '<%= config.app %>/scripts/templates.js'
- }
- },
- less: {
- all: {
- options: {
- paths: ['<%= config.app %>/scripts',
- '<%= config.app %>/styles']
- },
- files: {
- '<%= config.app %>/styles/app.css': '<%= config.app %>/styles/app.less'
- }
- },
- single: {
- paths: ['<%= config.app %>/scripts',
- '<%= config.app %>/styles'],
- files: []
- }
- },
-
- injector: {
- options: {},
- // Inject application script files into index.html (doesn't include bower)
- scripts_models: {
- options: {
- transform: function (filePath) {
- filePath = filePath.replace('/app/', '');
- return '<script src="' + filePath + '"></script>';
- },
- starttag: '<!-- injector:js_models -->',
- endtag: '<!-- endinjector:js_models -->'
- },
- files: {
- '<%= config.app %>/index.html': [
- [
- '<%= config.app %>/scripts/models/**/*.js',
- '!<%= config.app %>/scripts/models/**/*-tests.js'
- ]
- ]
- }
- },
-
- scripts_utils: {
- options: {
- transform: function (filePath) {
- filePath = filePath.replace('/app/', '');
- return '<script src="' + filePath + '"></script>';
- },
- starttag: '<!-- injector:js_utils -->',
- endtag: '<!-- endinjector:js_utils -->'
- },
- files: {
- '<%= config.app %>/index.html': [
- [
- '<%= config.app %>/scripts/utils/**/*.js',
- '!<%= config.app %>/scripts/models/**/*-tests.js'
- ]
- ]
- }
- },
-
- scripts_filters: {
- options: {
- transform: function (filePath) {
- filePath = filePath.replace('/app/', '');
- return '<script src="' + filePath + '"></script>';
- },
- starttag: '<!-- injector:js_filters -->',
- endtag: '<!-- endinjector:js_filters -->'
- },
- files: {
- '<%= config.app %>/index.html': [
- ['<%= config.app %>/scripts/filters/**/*.js',
- '!<%= config.app %>/scripts/filters/**/*-tests.js'
- ]
- ]
- }
- },
-
- scripts_directives: {
- options: {
- transform: function (filePath) {
- filePath = filePath.replace('/app/', '');
- return '<script src="' + filePath + '"></script>';
- },
- starttag: '<!-- injector:js_directives -->',
- endtag: '<!-- endinjector:js_directives -->'
- },
- files: {
- '<%= config.app %>/index.html': [
- ['<%= config.app %>/scripts/directives/**/*.js',
- '!<%= config.app %>/scripts/directives/**/*-tests.js'
- ]
- ]
- }
- },
-
- scripts_services: {
- options: {
- transform: function (filePath) {
- filePath = filePath.replace('/app/', '');
- return '<script src="' + filePath + '"></script>';
- },
- starttag: '<!-- injector:js_services -->',
- endtag: '<!-- endinjector:js_services -->'
- },
- files: {
- '<%= config.app %>/index.html': [
- ['<%= config.app %>/scripts/services/**/*.js',
- '!<%= config.app %>/scripts/services/**/*-tests.js'
- ]
- ]
- }
- },
-
- scripts_view_models: {
- options: {
- transform: function (filePath) {
- filePath = filePath.replace('/app/', '');
- return '<script src="' + filePath + '"></script>';
- },
- starttag: '<!-- injector:js_view_models -->',
- endtag: '<!-- endinjector:js_view_models -->'
- },
- files: {
- '<%= config.app %>/index.html': [
- ['<%= config.app %>/scripts/view-models/**/*.js',
- '!<%= config.app %>/scripts/view-models/**/*-tests.js']
- ]
- }
- },
-
- // Inject component less into app.less
- less: {
- options: {
- transform: function (filePath) {
- filePath = filePath.replace('/app/scripts/', '../scripts/');
- filePath = filePath.replace('/app/styles/', '');
- return '@import \'' + filePath + '\';';
- },
- starttag: '// injector:less',
- endtag: '// endinjector:less'
- },
- files: {
- '<%= config.app %>/styles/app.less': [
- '<%= config.app %>/styles/**/*.less',
- '<%= config.app %>/scripts/**/*.less',
- '!<%= config.app %>/styles/app.less'
- ]
- }
- },
-
- // Inject component css into index.html
- css: {
- options: {
- transform: function (filePath) {
- filePath = filePath.replace('/app/', '');
- filePath = filePath.replace('/.tmp/', '');
- return '<link rel="stylesheet" href="' + filePath + '">';
- },
- starttag: '<!-- injector:css -->',
- endtag: '<!-- endinjector -->'
- },
- files: {
- '<%= config.app %>/index.html': [
- '<%= config.app %>/scripts/**/*.css',
- '<%= config.app %>/styles/**/*.css',
- '!<%= config.app %>/styles/app.css'
- ]
- }
- }
- },
-
- // The actual grunt server settings
- connect: {
- options: {
- port: 9000,
- open: true,
- livereload: 35729,
- // Change this to '0.0.0.0' to access the server from outside
- hostname: 'localhost'
- },
- livereload: {
- options: {
- middleware: function (connect) {
- return [
- connect().use(function (req, res, next) {
- var mockApis = require('./configurations/mock.json').sdcConfig;
- var userType;
- switch (grunt.option('role')) {
- case "admin":
- userType = mockApis.userTypes.admin;
- break;
- case "tester":
- userType = mockApis.userTypes.tester;
- break;
- case "governor":
- userType = mockApis.userTypes.governor;
- break;
- case "ops":
- userType = mockApis.userTypes.ops;
- break;
- case "designer":
- userType = mockApis.userTypes.designer;
- break;
- case "product_strategist":
- userType = mockApis.userTypes.product_strategist;
- break;
- case "product_manager":
- userType = mockApis.userTypes.product_manager;
- break;
- default:
- userType = mockApis.userTypes.designer;
- }
- 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();
- }),
- connect().use(require('http-proxy-middleware')(['/onboarding', '/onboarding-api'], {
- target: 'http://feHost:8181/',
- changeOrigin: true,
- secure: false
- })),
- connect().use('/bower_components', connect.static('./bower_components')),
- connect().use('/non_bower_components', connect.static('./non_bower_components')),
- connect.static(config.app)
- ];
- }
- }
- },
- dist: {
- options: {
- base: '<%= config.dist %>',
- livereload: false
- }
- }
- },
-
- // Empties folders to start fresh
- clean: {
- generated: {
- files: [{
- dot: true,
- src: [
- '<%= config.app %>/scripts/**/*.js',
- '<%= config.app %>/scripts/**/*.css',
- '!<%= config.app %>/scripts/**/welcome/styles/*.css',
- '<%= config.app %>/styles/**/*.css',
- '<%= config.app %>/scripts/**/*.js.map'
- ]
- }]
- },
- dist: {
- files: [{
- dot: true,
- src: [
- '.tmp',
- '<%= config.dist %>/*',
- '!<%= config.dist %>/.git*'
- ]
- }]
- },
- server: '.tmp'
- },
- // Add vendor prefixed styles
- autoprefixer: {
- options: {
- browsers: ['> 1%', 'last 2 versions', 'Firefox ESR', 'Opera 12.1']
- },
- dist: {
- files: [{
- expand: true,
- cwd: '.tmp/css/',
- src: '{,*/**/}*.css',
- dest: '.tmp/css/'
- }]
- }
- },
-
- // Automatically inject Bower components into the HTML file
- wiredep: {
- app: {
- ignorePath: /^\/|\.\.\//,
- src: ['<%= config.app %>/index.html']
- }
- },
-
- // Renames files for browser caching purposes
- rev: {
- dist: {
- files: {
- src: [
- '<%= config.dist %>/scripts/{,*/}*.js',
- '<%= config.dist %>/styles/{,*/}*.css',
- '<%= config.dist %>/images/{,*/}*.*',
- '!<%= config.dist %>/images/resource-icons/{,*/}*.*',
- '!<%= config.dist %>/images/service-icons/{,*/}*.*',
- '!<%= config.dist %>/images/relationship-icons/{,*/}*.*',
- '<%= config.dist %>/*.{ico,png}'
- ]
- }
- }
- },
-
- // Reads HTML for usemin blocks to enable smart builds that automatically
- // concat, minify and revision files. Creates configurations in memory so
- // additional tasks can operate on them
- useminPrepare: {
- options: {
- dest: '<%= config.dist %>'
- },
- sdc: {
- src: ['<%= config.app %>/index.html']
- },
- html: '<%= config.app %>/index.html'
- },
-
- // Performs rewrites based on rev and the useminPrepare configuration
- usemin: {
- options: {
- assetsDirs: [
- '<%= config.dist %>',
- '<%= config.dist %>/images',
- '<%= config.dist %>/styles'
- ],
- // This is so we update image references in our ng-templates
- patterns: {
- js: [
- [/(assets\/images\/.*?\.(?:gif|jpeg|jpg|png|webp|svg))/gm, 'Update the JS to reference our revved images']
- ]
- }
- },
- html: ['<%= config.dist %>/{,*/}*.html'],
- css: ['<%= config.dist %>/styles/{,*/}*.css'],
- js: ['<%= config.dist %>/public/{,*/}*.js']
- },
-
- // The following *-min tasks produce minified files in the dist folder
- imagemin: {
- dist: {
- files: [{
- expand: true,
- cwd: '<%= config.app %>/images',
- src: '<%= config.app %>/**/*.{gif,jpeg,jpg,png}',
- dest: '<%= config.dist %>/images'
- }]
- }
- },
-
- svgmin: {
- dist: {
- files: [{
- expand: true,
- cwd: '<%= config.app %>/images',
- src: '{,*/}*.svg',
- dest: '<%= config.dist %>/images'
- }]
- }
- },
-
- htmlmin: {
- dist: {
- options: {
- collapseBooleanAttributes: true,
- collapseWhitespace: true,
- conservativeCollapse: true,
- removeAttributeQuotes: true,
- removeCommentsFromCDATA: true,
- removeEmptyAttributes: true,
- removeOptionalTags: true,
- removeRedundantAttributes: true,
- useShortDoctype: true
- },
- files: [{
- expand: true,
- cwd: '<%= config.dist %>',
- src: '{,*/}*.html',
- dest: '<%= config.dist %>'
- }]
- }
- },
-
-// By default, your `index.html`'s <!-- Usemin block --> will take care
-// of minification. These next options are pre-configured if you do not
-// wish to use the Usemin blocks.
- cssmin: {
- dist: {
- files: {
- '<%= config.dist %>/styles/main.css': [
- '.tmp/css/{,*/**/}*.css',
- '<%= config.app %>/scripts/{,*/**/}*.css',
- '<%= config.app %>/styles/app.css'
- ]
- }
- }
- },
- uglify: {
- dist: {
- files: {
- '<%= config.dist %>/scripts/scripts.js': [
- '<%= config.dist %>/scripts/scripts.js'
- ]
- }
- }
- },
- replace: {
- cssReplace: {
- src: ['<%= config.app %>/scripts/{,*/**/}*.css',
- '<%= config.app %>/styles/{,*/**/}*.css'],
- overwrite: true,
- replacements: [
- {
- from: '../../../images/',
- to: '../images/'
- },
- {
- from: '../../images/',
- to: '../images/'
- },
- {
- from: '../../../fonts/',
- to: '../fonts/'
- },
- {
- from: '../../fonts/',
- to: '../fonts/'
- },
- {
- from: '../../../styles/images/',
- to: 'images/'
- }
- ]
- },
- },
- concat: {
- dist: {
- options: {
- separator: ';\n'
- },
- src: ['<%= config.app %>/scripts/{,*/**/}*.js'],
- dest: '.tmp/concat/scripts/scripts.js'
- },
- generated: {
- options: {
- separator: '\n'
- }
- }
- },
-
- // Copies remaining files to places other tasks can use
- copy: {
- dist: {
- files: [{
- expand: true,
- dot: true,
- cwd: '<%= config.app %>',
- dest: '<%= config.dist %>',
- src: [
- '*.{ico,png,txt}',
- '.htaccess',
- // 'bower_components/**/*',
- 'styles/images/**/*',
- 'styles/fonts/**/*',
- 'languages/**/*',
- 'index.html'
- ]
- }, {
- src: 'node_modules/apache-server-configs/dist/.htaccess',
- dest: '<%= config.dist %>/.htaccess'
- },
- {
- expand: true,
- cwd: '.tmp/images',
- dest: '<%= config.dist %>/images',
- src: ['generated/*']
- },
- //TODO to remove this section after integration onboard finished
- {
- expand: true,
- cwd: '<%= config.app %>/third-party',
- dest: '<%= config.dist %>/third-party',
- src: ['onboard_bundle_full.js']
- },
- {
- expand: true,
- dest: '<%= config.dist %>',
- src: [
- 'package.json'
- ]
- }
- ]
- },
- styles: {
- expand: true,
- cwd: '<%= config.app %>/styles',
- dest: '.tmp/css/',
- src: '{,*/**/}*.css'
- }
- },
-
- // Run some tasks in parallel to speed up build process
- concurrent: {
- server: ['copy:styles'],
- test: ['copy:styles'],
- dist: [
- 'copy:styles',
- 'imagemin'
- ]
- },
-
- // Test settings
- karma: {
- dev: {
- configFile: "tests/karma.unit.conf.js",
- singleRun: true,
- options: {
- browsers: ['Chrome'],
- coverageReporter: {
- type: 'html',
- dir: 'tests/Coverage'
- }
- }
- },
- debug: {
- configFile: "tests/karma.unit.conf.js",
- singleRun: false,
- //comment out this line if you want to cancel the watch and see the UT log
- background: true,
- options: {
- browsers: ['Chrome'],
- reporters: [
- 'junit',
- 'dots',
- 'progress'
- ]
- }
- },
- jenkins: {
- configFile: "tests/karma.unit.conf.js",
- singleRun: true,
- options: {
- browsers: ['PhantomJS'],
- coverageReporter: {
- type: 'text-summary',
- dir: 'tests/Coverage',
- file: 'coverage.txt'
- }
- }
- }
- },
-
- tslint: {
- options: {
- configuration: 'tslint.json'
- },
- files: {
- src: ['<%= config.app %>/**/*.ts']
- }
- }
- });
-
- grunt.registerTask('serve', 'start the server and preview your app, --allow-remote for remote access', function (target) {
-
- var env = grunt.option('env');
-
- if (grunt.option('allow-remote')) {
- grunt.config.set('connect.options.hostname', '0.0.0.0');
- }
- if (target === 'dist') {
- return grunt.task.run(['build', 'connect:dist:keepalive']);
- }
-
-
- if (env === 'mock') {
- grunt.task.run([
- 'express:mock',
- 'clean:generated',
- 'ts:all',
- 'ngtemplates:app',
- 'injector',
- 'less:all',
- 'ngconstant',
- 'wiredep',
- 'concurrent:server',
- 'autoprefixer',
- 'connect:livereload',
- 'watch:html',
- 'watch:less'
- ]);
- }
-
- grunt.task.run([
- 'clean:generated',
- 'ts:all',
- 'ngtemplates:app',
- 'injector',
- 'less:all',
- 'ngconstant',
- 'wiredep',
- 'concurrent:server',
- 'autoprefixer',
- 'connect:livereload',
- 'watch'
- ]);
- });
-
- grunt.registerTask('build', [
- 'clean:generated',
- 'less:all',
- 'ts:all',
- 'ngconstant',
- 'ngtemplates:app',
- 'wiredep',
- 'replace',
- 'clean:dist',
- 'useminPrepare:sdc',
- 'concurrent:dist',
- 'autoprefixer:dist',
- 'concat',
- 'copy:dist',
- 'cssmin',
- 'uglify',
- 'rev',
- 'usemin'
- ]);
-
- grunt.registerTask("test", function (target) {
-
- if (!(target === 'debug' || target === 'dev' || target === 'jenkins')) {
- throw new Error("target available for test are <dev|debug|jenkins>");
- }
- var tasks = [
- // "tslint:karma",
- // "ngconstant",
- //// "concurrent:test",
- // "servicesIconConstants",
- // "autoprefixer",
- // "ngtemplates:testsTemplates",
- // "connect:test"
- ];
-
- tasks.push('karma:' + target);
- if (target === 'debug') {
- if (grunt.config.get('watch.ts')) {
- tasks.push("watch:ts");
- } else {
- throw new Error("target watch:ts is not available, verify that it exists in your Gruntfile");
- }
- }
- grunt.task.run(tasks);
- });
-
-
- var lessSingleTask = function (filePath) {
- var lessSingleFiles = [{
- expand: true,
- src: [filePath.replace(/\\/g, '/')],
- ext: '.css'
- }];
- grunt.config('less.single.files', lessSingleFiles);
- grunt.config('watch.less.tasks', 'less:single');
-
- };
-
- var tsSingleTask = function (filePath) {
-
- var tsSingleData = {
- src: [filePath.replace(/\\/g, '/')]
- };
- // grunt.config('ts.single', tsSingleData);
-
- };
-
- var singleTaskByTaskName = {
- //less: lessSingleTask,
- ts: tsSingleTask
- };
-
- var onGruntWatchEvent = function (action, filepath, target) {
- if (singleTaskByTaskName[target]) {
- singleTaskByTaskName[target].call(undefined, filepath);
- }
- };
- grunt.event.on('watch', onGruntWatchEvent);
-};
diff --git a/catalog-ui/README.md b/catalog-ui/README.md
new file mode 100644
index 0000000000..c1f590a946
--- /dev/null
+++ b/catalog-ui/README.md
@@ -0,0 +1,39 @@
+# CatalogUi
+
+## Development server
+Run "npm start" for a dev server.
+Navigate to "http://localhost:9000/".
+The app will automatically reload if you change any of the source files.
+
+--- Specify role ---
+npm start -- --env.role designer
+
+npm run <role>
+
+## Build
+--- dev ---
+Run "npm run build" to build the project.
+The build artifacts will be stored in the `dist/` directory.
+
+--- prod ---
+Run "npm run build:prod" to build the project.
+The build artifacts will be stored in the `dist/` directory.
+
+## Configuration
+Dev server is configured in webpack.server.js file.
+App configuration dev.js or prod.js and menu.js are located in configuration folder and required by app.ts according to __ENV__ parameter from webpack.
+
+## Running unit tests
+## Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io).
+
+## Running end-to-end tests
+## Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protractortest.org/).
+## Before running the tests make sure you are serving the app via `ng serve`.
+
+-- Working with WebStorm --
+
+go to File --> Settings --> Languages & Frameworks
+
+Under JavaScript -> set JavaScript language version to ECMAScript6
+Under TypeScript -> select 'Enable TypeScript Compiler' and choose 'Use tsconfige.json'
+
diff --git a/catalog-ui/SETTING-ENVIRONMENT.md b/catalog-ui/SETTING-ENVIRONMENT.md
deleted file mode 100644
index edccca1304..0000000000
--- a/catalog-ui/SETTING-ENVIRONMENT.md
+++ /dev/null
@@ -1,36 +0,0 @@
-# Prerequisites
-
-1. install [node.js](http://nodejs.org/download/)
-2. install [git](http://git-scm.com/). __Make sure to select the option to add git into $PATH__
-3. install grunt with dependencies `npm install -g bower grunt-cli`
-
- if running on MacOS/Linux the command should be run with `sudo`
-
-# Running the server
-
-Make sure all the client and npm dependencies installed by running the following commands:
-
-1. `npm install`
-2. `bower install`
-
-
-
-You are then presented with 3 options `ngnix`, `test`, `build`
-
-1. `grunt serve --env=mock` will setup a dev(nginx) server under `http://localhost:9000` with mock configurations. The are also `grunt serve:test` and `grunt serve:prod` options
-2. `grunt test` will run all the unit tests in the project
-3. `grunt build` will run a build process resulting with a `dist/` folder including the version ready to be deployed (this task should be mainly run on the CI server)
-3. `grunt build:dev` will deploy to nginx a production artifact, (minify files)
-
-# Webstorm
-
-Although any text editor can be used to write angular applications Webstorm is the most convenient for the task. In case Webstorm is chosen make sure it has the following plugins:
-
-* `.editorconfig` - this plugin will keep line indentation same across all developers
-* `angular.js` - this plugin will help autocompleting angular syntax
-* `markdown` - this one will give nice support to write .md files such as this one you are reading right now
-
-These can be found in plugins settings section by pressing PC: `CTRL + SHIFT + A` MAC: `CMD + SHIFT + A` and typing addons
-
-
---> DO NOT COMMIT ANYTHING BEFORE RUNNING grunt build / grunt nginx / grunt nginx:mock --env=mock <--
diff --git a/catalog-ui/SETTING-MOCK-SERVER.md b/catalog-ui/SETTING-MOCK-SERVER.md
deleted file mode 100644
index 5db508f225..0000000000
--- a/catalog-ui/SETTING-MOCK-SERVER.md
+++ /dev/null
@@ -1,53 +0,0 @@
-# Prerequisites
-
-1. install [node.js](http://nodejs.org/download/)
-2. install [git](http://git-scm.com/). __Make sure to select the option to add git into $PATH__
-3. install dependencies [express,cors] npm install express, npm install cors
-
-
-
-# Create the server file
-Example:
-
-#############################################
-ar express = require('express');
-var mockUris = require('../configurations/mock.json');
-var cors = require('cors');
-
-
-var app = express();
-
-// declare server cross browser
-app.use(cors({
- origin: '*',
- methods: 'GET, POST, PUT, DELETE',
- allowedHeaders: 'Content-Type,Authorization,If-Modified-Since'
-}));
-
-/******************************************* MOCKS ENPOINTS *************************************************/
-/* poiFind */
-app.get('/v1' + mockUris.generalConf.getPoiFind.split('v1')[1], function (req, res) {
- var pois = require('./data/poi/poi-search.json'); // the json response for the api call
- res.send(pois);
-});
-
-/**************************************************** *******************************************************/
-// declare server listener port
-var server = app.listen(9999, function () {
- console.log('mock server listening on port %d', server.address().port);
-});
-
-################################
-
-#create mockDate
-
-1. create json file with the response.
-2. add the api end point in the server file and declare the json file for the response/
-
-
-
-# Running the server
-
-1. go to server file folder
-2. run command : node <FileName>
-
diff --git a/catalog-ui/_angular-cli.json b/catalog-ui/_angular-cli.json
new file mode 100644
index 0000000000..a19145fe12
--- /dev/null
+++ b/catalog-ui/_angular-cli.json
@@ -0,0 +1,53 @@
+{
+ "project": {
+ "name": "SDC APP",
+ "ejected": true
+ },
+ "apps": [
+ {
+ "root": "src",
+ "outDir": "dist",
+ "assets": [
+ "assets/styles/fonts",
+ "assets/styles/images",
+ "assets/styles/app.css"
+ ],
+ "index": "index.html",
+ "main": "main.ts",
+ "polyfills": "polyfills.ts",
+ "tsconfig": "tsconfig.json",
+ "testTsconfig": "tsconfig.json",
+ "prefix": "app",
+ "styles": [
+ "styles.css"
+ ],
+ "scripts": [
+ "../node_modules/angular/angular.min.js",
+ "../node_modules/angular-ui-router/release/angular-ui-router.min.js",
+ "../node_modules/restangular/dist/restangular.min.js",
+ "../node_modules/angular-filter/dist/angular-filter.min.js",
+ "../node_modules/angular-ui-bootstrap/dist/ui-bootstrap.js",
+ "../node_modules/angular-bootstrap/ui-bootstrap.min.js",
+ "../node_modules/angular-resource/angular-resource.min.js",
+ "../node_modules/angular-base64/angular-base64.min.js",
+ "../node_modules/angular-uuid4/angular-uuid4.min.js"
+ ],
+ "environmentSource": "environments/environment.ts",
+ "environments": {
+ "dev": "environments/environment.ts",
+ "prod": "environments/environment.prod.ts"
+ }
+ }
+ ],
+ "defaults": {
+ "styleExt": "css",
+ "class": {
+ "spec": false
+ },
+ "component": {
+ "spec": true,
+ "inlineStyle": false,
+ "inlineTemplate": false
+ }
+ }
+}
diff --git a/catalog-ui/app/index.html b/catalog-ui/app/index.html
deleted file mode 100644
index f56fdfd256..0000000000
--- a/catalog-ui/app/index.html
+++ /dev/null
@@ -1,392 +0,0 @@
-<!doctype html>
-<html class="no-js" data-ng-app="sdcApp">
-<head>
- <meta charset="utf-8">
- <title>SDC</title>
- <meta name="description" content="">
- <meta name="viewport" content="width=device-width">
- <link rel="shortcut icon" href="favicon.png" type="image/png">
- <!--<link rel="icon" href="favicon.png" type="image/png">-->
-
- <!-- build:css(.) styles/vendor.css -->
- <!-- bower:css -->
- <link rel="stylesheet" href="bower_components/perfect-scrollbar/src/perfect-scrollbar.css" />
- <link rel="stylesheet" href="bower_components/angular-tooltips/dist/angular-tooltips.min.css" />
- <link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.css" />
- <link rel="stylesheet" href="bower_components/animate.css/animate.css" />
- <link rel="stylesheet" href="bower_components/angular-ui-notification/dist/angular-ui-notification.css" />
- <!-- endbower -->
- <link rel="stylesheet" href="bower_components/angular-resizable/src/angular-resizable.css"/>
- <link rel="stylesheet" href="bower_components/qtip2/jquery.qtip.min.css"/>
-
-
-
- <!-- endbuild -->
- <!-- build:css(.tmp) styles/main.css -->
- <link rel="stylesheet" href="styles/app.css">
- <!-- /include -->
-
- <!-- injector:css -->
-
- <!-- endinjector -->
- <!-- endbuild -->
-
- <!-- include: "type": "css", "files": "scripts/*.css" -->
- <!-- /include -->
-</head>
-<body data-ng-class="bodyClass">
-<!--[if lt IE 10]>
-<p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade
- your browser</a> to improve your experience.</p>
-<![endif]-->
-
-
-<div class="sdc-loading-page">
- <h1 class="caption1">Signing in</h1>
- <p class="caption2">Please wait. If you are using Internet Explorer, please reattempt access using Chrome or
- Firefox.</p>
-
- </p>
-
- <div class="main-loader">
- <div class="loader">
- <svg class="circular" viewBox="25 25 50 50">
- <circle class="path" cx="50" cy="50" r="20" fill="none" stroke-width="2" stroke-miterlimit="10"/>
- </svg>
- </div>
- </div>
-</div>
-
-<div class="full-height" data-ui-view=""></div>
-
-<!-- build:js(.) scripts/vendor.js -->
-
-<!-- bower:js -->
-<script src="bower_components/jquery/dist/jquery.js"></script>
-<script src="bower_components/angular/angular.js"></script>
-<script src="bower_components/angular-base64/angular-base64.js"></script>
-<script src="bower_components/angular-base64-upload/src/angular-base64-upload.js"></script>
-<script src="bower_components/angular-bootstrap/ui-bootstrap-tpls.js"></script>
-<script src="bower_components/jquery-ui/jquery-ui.js"></script>
-<script src="bower_components/angular-dragdrop/src/angular-dragdrop.js"></script>
-<script src="bower_components/angular-filter/dist/angular-filter.js"></script>
-<script src="bower_components/angular-mocks/angular-mocks.js"></script>
-<script src="bower_components/perfect-scrollbar/src/perfect-scrollbar.js"></script>
-<script src="bower_components/angular-perfect-scrollbar/src/angular-perfect-scrollbar.js"></script>
-<script src="bower_components/angular-resource/angular-resource.js"></script>
-<script src="bower_components/angular-sanitize/angular-sanitize.js"></script>
-<script src="bower_components/angular-tooltips/dist/angular-tooltips.min.js"></script>
-<script src="bower_components/angular-translate/angular-translate.js"></script>
-<script src="bower_components/angular-translate-loader-static-files/angular-translate-loader-static-files.js"></script>
-<script src="bower_components/angular-ui-router/release/angular-ui-router.js"></script>
-<script src="bower_components/angular-uuid4/angular-uuid4.js"></script>
-<script src="bower_components/bootstrap/dist/js/bootstrap.js"></script>
-<script src="bower_components/checklist-model/checklist-model.js"></script>
-<script src="bower_components/jspdf/dist/jspdf.min.js"></script>
-<script src="bower_components/angular-clipboard/angular-clipboard.js"></script>
-<script src="bower_components/angular-resizable/src/angular-resizable.js"></script>
-<script src="bower_components/angular-ui-notification/dist/angular-ui-notification.js"></script>
-<script src="bower_components/js-md5/src/md5.js"></script>
-<script src="bower_components/cytoscape/dist/cytoscape.js"></script>
-<script src="bower_components/lodash/lodash.js"></script>
-<script src="bower_components/restangular/dist/restangular.js"></script>
-<script src="bower_components/cytoscape-expand-collapse/cytoscape-expand-collapse.js"></script>
-<script src="bower_components/ev-emitter/ev-emitter.js"></script>
-<script src="bower_components/imagesloaded/imagesloaded.js"></script>
-<script src="bower_components/qtip2/jquery.qtip.js"></script>
-<script src="bower_components/qtip2/basic/jquery.qtip.js"></script>
-<script src="bower_components/cytoscape-qtip/cytoscape-qtip.js"></script>
-<!-- endbower -->
-<script src="non_bower_components/cytoscape.js-edge-editation/CytoscapeEdgeEditation.js"></script>
-<!-- endbuild -->
-
-
-<!-- build:js({app,.tmp}) scripts/main.js -->
-
-
-<!-- include utils -->
-
-<script src="scripts/utils/dictionary/dictionary.js"></script>
-<script src="scripts/utils/prototypes.js"></script>
-<script src="scripts/utils/artifacts-utils.js"></script>
-<script src="scripts/utils/file-utils.js"></script>
-<script src="scripts/utils/validation-utils.js"></script>
-<script src="scripts/utils/component-factory.js"></script>
-<script src="scripts/utils/component-instance-factory.js"></script>
-<script src="scripts/utils/change-lifecycle-state-handler.js"></script>
-<script src="scripts/utils/modals-handler.js"></script>
-<script src="scripts/utils/menu-handler.js"></script>
-<script src="scripts/utils/constants.js"></script>
-<script src="scripts/utils/common-utils.js"></script>
-<script src="scripts/utils/functions.js"></script>
-
-<!-- endinjector:js_utils -->
-<script src="scripts/modules/utils.js"></script>
-<!-- /end include utils-->
-
-<!-- injector:js_models -->
-<script src="scripts/models/activity.js"></script>
-<script src="scripts/models/additional-information.js"></script>
-<script src="scripts/models/app-config.js"></script>
-<script src="scripts/models/artifacts.js"></script>
-<script src="scripts/models/aschema-property.js"></script>
-<script src="scripts/models/attributes.js"></script>
-<script src="scripts/models/capability.js"></script>
-<script src="scripts/models/category.js"></script>
-<script src="scripts/models/comments.js"></script>
-<script src="scripts/models/components/component.js"></script>
-<script src="scripts/models/components/displayComponent.js"></script>
-<script src="scripts/models/components/product.js"></script>
-<script src="scripts/models/components/resource.js"></script>
-<script src="scripts/models/components/service.js"></script>
-<script src="scripts/models/componentsInstances/componentInstance.js"></script>
-<script src="scripts/models/componentsInstances/productInstance.js"></script>
-<script src="scripts/models/componentsInstances/resourceInstance.js"></script>
-<script src="scripts/models/componentsInstances/serviceInstance.js"></script>
-<script src="scripts/models/csar-component.js"></script>
-<script src="scripts/models/data-type-properties.js"></script>
-<script src="scripts/models/data-types-map.js"></script>
-<script src="scripts/models/data-types.js"></script>
-<script src="scripts/models/distribution.js"></script>
-<script src="scripts/models/file-download.js"></script>
-<script src="scripts/models/graph/d2-node.js"></script>
-<script src="scripts/models/graph/graph-links/common-base-link.js"></script>
-<script src="scripts/models/graph/graph-links/common-ci-link-base.js"></script>
-<script src="scripts/models/graph/graph-links/composition-graph-links/composition-ci-link-base.js"></script>
-<script src="scripts/models/graph/graph-links/composition-graph-links/composition-ci-simple-link.js"></script>
-<script src="scripts/models/graph/graph-links/composition-graph-links/composition-ci-ucpe-host-link.js"></script>
-<script src="scripts/models/graph/graph-links/composition-graph-links/composition-ci-ucpe-link.js"></script>
-<script src="scripts/models/graph/graph-links/composition-graph-links/composition-ci-vl-link.js"></script>
-<script src="scripts/models/graph/graph-links/composition-graph-links/composition-ci-vl-ucpe-link.js"></script>
-<script src="scripts/models/graph/graph-links/links-factory.js"></script>
-<script src="scripts/models/graph/graph-links/module-graph-links/module-ci-link-base.js"></script>
-<script src="scripts/models/graph/graph-links/module-graph-links/module-ci-vl-link.js"></script>
-<script src="scripts/models/graph/graphTooltip.js"></script>
-<script src="scripts/models/graph/link-menu.js"></script>
-<script src="scripts/models/graph/match-relation.js"></script>
-<script src="scripts/models/graph/nodes/base-common-node.js"></script>
-<script src="scripts/models/graph/nodes/common-ci-node-base.js"></script>
-<script src="scripts/models/graph/nodes/composition-graph-nodes/composition-ci-node-base.js"></script>
-<script src="scripts/models/graph/nodes/composition-graph-nodes/composition-ci-node-cp.js"></script>
-<script src="scripts/models/graph/nodes/composition-graph-nodes/composition-ci-node-service.js"></script>
-<script src="scripts/models/graph/nodes/composition-graph-nodes/composition-ci-node-ucpe-cp.js"></script>
-<script src="scripts/models/graph/nodes/composition-graph-nodes/composition-ci-node-ucpe.js"></script>
-<script src="scripts/models/graph/nodes/composition-graph-nodes/composition-ci-node-vf.js"></script>
-<script src="scripts/models/graph/nodes/composition-graph-nodes/composition-ci-node-vfc.js"></script>
-<script src="scripts/models/graph/nodes/composition-graph-nodes/composition-ci-node-vl.js"></script>
-<script src="scripts/models/graph/nodes/modules-graph-nodes/module-node-base.js"></script>
-<script src="scripts/models/graph/nodes/nodes-factory.js"></script>
-<script src="scripts/models/graph/point.js"></script>
-<script src="scripts/models/graph/relationMenuObjects.js"></script>
-<script src="scripts/models/graph/relationship.js"></script>
-<script src="scripts/models/inputs.js"></script>
-<script src="scripts/models/instance-inputs-properties-map.js"></script>
-<script src="scripts/models/instances-inputs-map.js"></script>
-<script src="scripts/models/left-panel.js"></script>
-<script src="scripts/models/member.js"></script>
-<script src="scripts/models/modules/base-module.js"></script>
-<script src="scripts/models/properties.js"></script>
-<script src="scripts/models/requirement.js"></script>
-<script src="scripts/models/schema-attribute.js"></script>
-<script src="scripts/models/tab.js"></script>
-<script src="scripts/models/tooltip-data.js"></script>
-<script src="scripts/models/user.js"></script>
-<script src="scripts/models/validate.js"></script>
-<!-- endinjector:js_models -->
-
-<script src="third-party/ng-infinite-scroll/build/ng-infinite-scroll.js"></script>
-
-<!-- injector:js_filters -->
-<script src="scripts/filters/_category-name-filter.js"></script>
-<script src="scripts/filters/capitalize-filter.js"></script>
-<script src="scripts/filters/catalog-status-filter.js"></script>
-<script src="scripts/filters/category-icon-filter.js"></script>
-<script src="scripts/filters/category-type-filter.js"></script>
-<script src="scripts/filters/clear-whitespaces-filter.js"></script>
-<script src="scripts/filters/entity-filter.js"></script>
-<script src="scripts/filters/graph-resource-name-filter.js"></script>
-<script src="scripts/filters/product-category-name-filter.js"></script>
-<script src="scripts/filters/product-subcategory-name-filter.js"></script>
-<script src="scripts/filters/relation-name-fllter.js"></script>
-<script src="scripts/filters/resource-name-filter.js"></script>
-<script src="scripts/filters/resource-type-filter.js"></script>
-<script src="scripts/filters/string-to-date-filter.js"></script>
-<script src="scripts/filters/tests-id-filter.js"></script>
-<script src="scripts/filters/trim-filter.js"></script>
-<script src="scripts/filters/truncate-filter.js"></script>
-<script src="scripts/filters/underscoreless-filter.js"></script>
-<!-- endinjector:js_filters -->
-<script src="scripts/modules/filters.js"></script>
-
-<script src="third-party/PunchOutRegistry.js"></script>
-
-
-<!-- injector:js_directives -->
-<script src="scripts/directives/clicked-outside/clicked-outside-directive.js"></script>
-<script src="scripts/directives/custom-validation/custom-validation.js"></script>
-<script src="scripts/directives/download-artifact/download-artifact.js"></script>
-<script src="scripts/directives/ecomp-header/ecomp-header.js"></script>
-<script src="scripts/directives/edit-name-popover/edit-name-popover-directive.js"></script>
-<script src="scripts/directives/elements/checkbox/checkbox.js"></script>
-<script src="scripts/directives/elements/radiobutton/radiobutton.js"></script>
-<script src="scripts/directives/ellipsis/ellipsis-directive.js"></script>
-<script src="scripts/directives/events/on-last-repeat/on-last-repeat.js"></script>
-<script src="scripts/directives/file-opener/file-opener.js"></script>
-<script src="scripts/directives/file-type/file-type.js"></script>
-<script src="scripts/directives/file-upload/file-upload.js"></script>
-<script src="scripts/directives/graphs-v2/common/common-graph-utils.js"></script>
-<script src="scripts/directives/graphs-v2/common/style/component-instances-nodes-style.js"></script>
-<script src="scripts/directives/graphs-v2/common/style/module-node-style.js"></script>
-<script src="scripts/directives/graphs-v2/composition-graph/composition-graph.directive.js"></script>
-<script src="scripts/directives/graphs-v2/composition-graph/utils/composition-graph-general-utils.js"></script>
-<script src="scripts/directives/graphs-v2/composition-graph/utils/composition-graph-links-utils.js"></script>
-<script src="scripts/directives/graphs-v2/composition-graph/utils/composition-graph-nodes-utils.js"></script>
-<script src="scripts/directives/graphs-v2/composition-graph/utils/match-capability-requierment-utils.js"></script>
-<script src="scripts/directives/graphs-v2/deployment-graph/deployment-graph.directive.js"></script>
-<script src="scripts/directives/graphs-v2/deployment-graph/deployment-utils/deployment-graph-general-utils.js"></script>
-<script src="scripts/directives/graphs-v2/image-creator/image-creator.service.js"></script>
-<script src="scripts/directives/graphs-v2/palette/palette.directive.js"></script>
-<script src="scripts/directives/graphs-v2/relation-menu/relation-menu.js"></script>
-<script src="scripts/directives/info-tooltip/info-tooltip.js"></script>
-<script src="scripts/directives/invalid-characters/invalid-characters.js"></script>
-<script src="scripts/directives/layout/top-nav/top-nav.js"></script>
-<script src="scripts/directives/layout/top-progress/top-progress.js"></script>
-<script src="scripts/directives/loader/loader-directive.js"></script>
-<script src="scripts/directives/modal/sdc-modal.js"></script>
-<script src="scripts/directives/page-scroller/page-scroller.js"></script>
-<script src="scripts/directives/perfect-scrollbar/angular-perfect-scrollbar.js"></script>
-<script src="scripts/directives/print-graph-screen/print-graph-screen.js"></script>
-<script src="scripts/directives/property-types/data-type-fields-structure/data-type-fields-structure.js"></script>
-<script src="scripts/directives/property-types/type-list/type-list-directive.js"></script>
-<script src="scripts/directives/property-types/type-map/type-map-directive.js"></script>
-<script src="scripts/directives/punch-out/punch-out.js"></script>
-<script src="scripts/directives/sdc-tabs/sdc-single-tab/sdc-single-tab-directive.js"></script>
-<script src="scripts/directives/sdc-tabs/sdc-tabs-directive.js"></script>
-<script src="scripts/directives/structure-tree/structure-tree-directive.js"></script>
-<script src="scripts/directives/tag/tag-directive.js"></script>
-<script src="scripts/directives/tutorial/tutorial-directive.js"></script>
-<script src="scripts/directives/user-header-details/user-header-details-directive.js"></script>
-<script src="scripts/directives/utils/expand-collapse-menu-box/expand-collaps-menu-box.js"></script>
-<script src="scripts/directives/utils/expand-collapse/expand-collapse.js"></script>
-<script src="scripts/directives/utils/page-selector/page-selector.js"></script>
-<script src="scripts/directives/utils/sdc-keyboard-events/sdc-keyboard-events.js"></script>
-<script src="scripts/directives/utils/sdc-tags/sdc-tags.js"></script>
-<script src="scripts/directives/utils/sdc_error_tooltip/sdc_error_tooltip.js"></script>
-<script src="scripts/directives/utils/sdc_messages/sdc-message.js"></script>
-<script src="scripts/directives/utils/sdc_messages/sdc-messages.js"></script>
-<script src="scripts/directives/utils/smart-tooltip/smart-tooltip.js"></script>
-<script src="scripts/directives/utils/wizard_steps/sdc-wizard-steps.js"></script>
-<!-- endinjector:js_directives -->
-<script src="scripts/modules/directive-module.js"></script>
-
-<!-- injector:js_services -->
-<script src="scripts/services/activity-log-service.js"></script>
-<script src="scripts/services/angular-js-bridge-service.js"></script>
-<script src="scripts/services/available-icons-service.js"></script>
-<script src="scripts/services/cache-service.js"></script>
-<script src="scripts/services/category-resource-service.js"></script>
-<script src="scripts/services/components/component-service.js"></script>
-<script src="scripts/services/components/product-service.js"></script>
-<script src="scripts/services/components/resource-service.js"></script>
-<script src="scripts/services/components/service-service.js"></script>
-<script src="scripts/services/components/utils/composition-left-palette-service.js"></script>
-<script src="scripts/services/configuration-ui-service.js"></script>
-<script src="scripts/services/cookie-service.js"></script>
-<script src="scripts/services/data-types-service.js"></script>
-<script src="scripts/services/ecomp-service.js"></script>
-<script src="scripts/services/entity-service.js"></script>
-<script src="scripts/services/event-listener-service.js"></script>
-<script src="scripts/services/header-interceptor.js"></script>
-<script src="scripts/services/http-error-interceptor.js"></script>
-<script src="scripts/services/loader-service.js"></script>
-<script src="scripts/services/onboarding-service.js"></script>
-<script src="scripts/services/progress-service.js"></script>
-<script src="scripts/services/relation-icons-service.js"></script>
-<script src="scripts/services/sdc-version-service.js"></script>
-<script src="scripts/services/sharing-service.js"></script>
-<script src="scripts/services/url-tobase64-service.js"></script>
-<script src="scripts/services/user-resource-service.js"></script>
-<!-- endinjector:js_services -->
-<script src="scripts/modules/service-module.js"></script>
-
-<!-- injector:js_view_models -->
-<script src="scripts/view-models/admin-dashboard/add-category-modal/add-category-modal-view-model.js"></script>
-<script src="scripts/view-models/admin-dashboard/admin-dashboard-view-model.js"></script>
-<script src="scripts/view-models/admin-dashboard/category-management/category-management-view-model.js"></script>
-<script src="scripts/view-models/admin-dashboard/user-management/user-management-view-model.js"></script>
-<script src="scripts/view-models/catalog/catalog-view-model.js"></script>
-<script src="scripts/view-models/component-viewer/component-viewer-view-model.js"></script>
-<script src="scripts/view-models/dashboard/cover/dashboard-cover-view-model.js"></script>
-<script src="scripts/view-models/dashboard/dashboard-view-model.js"></script>
-<script src="scripts/view-models/forms/artifact-form/artifact-form-view-model.js"></script>
-<script src="scripts/view-models/forms/attribute-form/attribute-from-view-model.js"></script>
-<script src="scripts/view-models/forms/env-parameters-form/env-parameters-form.js"></script>
-<script src="scripts/view-models/forms/property-form/property-form-view-model.js"></script>
-<script src="scripts/view-models/forms/resource-instance-name-form/resource-instance-name-model.js"></script>
-<script src="scripts/view-models/modals/confirmation-modal/confirmation-modal-view-model.js"></script>
-<script src="scripts/view-models/modals/email-modal/email-modal-view-model.js"></script>
-<script src="scripts/view-models/modals/error-modal/error-view-model.js"></script>
-<script src="scripts/view-models/modals/message-modal/message-base-modal-model.js"></script>
-<script src="scripts/view-models/modals/message-modal/message-client-modal/client-message-modal-view-model.js"></script>
-<script src="scripts/view-models/modals/message-modal/message-server-modal/server-message-modal-view-model.js"></script>
-<script src="scripts/view-models/modals/onboarding-modal/onboarding-modal-view-model.js"></script>
-<script src="scripts/view-models/onboard-vendor/onboard-vendor-view-model.js"></script>
-<script src="scripts/view-models/preloading/preloading-view.js"></script>
-<script src="scripts/view-models/support/support-view-model.js"></script>
-<script src="scripts/view-models/tabs/hierarchy/hierarchy-view-model.js"></script>
-<script src="scripts/view-models/tutorial-end/tutorial-end.js"></script>
-<script src="scripts/view-models/welcome/welcome-steps-controller.js"></script>
-<script src="scripts/view-models/welcome/welcome-view.js"></script>
-<script src="scripts/view-models/wizard/artifact-deployment-step/artifact-deployment-step.js"></script>
-<script src="scripts/view-models/wizard/artifact-form-step/artifact-form-step-view-model.js"></script>
-<script src="scripts/view-models/wizard/artifact-information-step/artifact-information-step.js"></script>
-<script src="scripts/view-models/wizard/general-step/general-step.js"></script>
-<script src="scripts/view-models/wizard/hierarchy-step/hierarchy-step.js"></script>
-<script src="scripts/view-models/wizard/icons-step/icons-step.js"></script>
-<script src="scripts/view-models/wizard/properties-step/properties-step.js"></script>
-<script src="scripts/view-models/wizard/property-form/property-form-view-model.js"></script>
-<script src="scripts/view-models/wizard/wizard-creation-base.js"></script>
-<script src="scripts/view-models/wizard/wizard-state/create-wizard.js"></script>
-<script src="scripts/view-models/wizard/wizard-state/edit-wizard.js"></script>
-<script src="scripts/view-models/wizard/wizard-state/import-wizard.js"></script>
-<script src="scripts/view-models/workspace/tabs/activity-log/activity-log.js"></script>
-<script src="scripts/view-models/workspace/tabs/attributes/attributes-view-model.js"></script>
-<script src="scripts/view-models/workspace/tabs/composition/composition-view-model.js"></script>
-<script src="scripts/view-models/workspace/tabs/composition/tabs/artifacts/artifacts-view-model.js"></script>
-<script src="scripts/view-models/workspace/tabs/composition/tabs/details/details-view-model.js"></script>
-<script src="scripts/view-models/workspace/tabs/composition/tabs/properties-and-attributes/properties-view-model.js"></script>
-<script src="scripts/view-models/workspace/tabs/composition/tabs/relations/relations-view-model.js"></script>
-<script src="scripts/view-models/workspace/tabs/composition/tabs/structure/structure-view.js"></script>
-<script src="scripts/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts-view-model.js"></script>
-<script src="scripts/view-models/workspace/tabs/deployment/deployment-view-model.js"></script>
-<script src="scripts/view-models/workspace/tabs/distribution/disribution-status-modal/disribution-status-modal-view-model.js"></script>
-<script src="scripts/view-models/workspace/tabs/distribution/distribution-view-model.js"></script>
-<script src="scripts/view-models/workspace/tabs/general/general-view-model.js"></script>
-<script src="scripts/view-models/workspace/tabs/icons/icons-view-model.js"></script>
-<script src="scripts/view-models/workspace/tabs/information-artifacts/information-artifacts-view-model.js"></script>
-<script src="scripts/view-models/workspace/tabs/inputs/resource-input/resource-inputs-view-model.js"></script>
-<script src="scripts/view-models/workspace/tabs/inputs/service-input/service-inputs-view-model.js"></script>
-<script src="scripts/view-models/workspace/tabs/management-workflow/management-workflow-view-model.js"></script>
-<script src="scripts/view-models/workspace/tabs/network-call-flow/network-call-flow-view-model.js"></script>
-<script src="scripts/view-models/workspace/tabs/product-hierarchy/product-hierarchy-view-model.js"></script>
-<script src="scripts/view-models/workspace/tabs/properties/properties-view-model.js"></script>
-<script src="scripts/view-models/workspace/tabs/req-and-capabilities/req-and-capabilities-view-model.js"></script>
-<script src="scripts/view-models/workspace/tabs/tosca-artifacts/tosca-artifacts-view-model.js"></script>
-<script src="scripts/view-models/workspace/workspace-view-model.js"></script>
-<!-- endinjector:js_view_models -->
-<script src="scripts/modules/view-model-module.js"></script>
-
-<!--init -->
-<script src="scripts/modules/configurations.js"></script>
-<script src="scripts/app.js"></script>
-<script src="scripts/templates.js"></script>
-
-<!-- endbuild -->
-
-<script src="/onboarding/punch-outs_en.js" async></script>
-
-<!-- include: "type": "js", "files": "scripts/*.js" -->
-
-<!-- /include -->
-</body>
-</html>
diff --git a/catalog-ui/app/scripts/app.ts b/catalog-ui/app/scripts/app.ts
deleted file mode 100644
index 513810595b..0000000000
--- a/catalog-ui/app/scripts/app.ts
+++ /dev/null
@@ -1,936 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="./references"/>
-/*
- SD&C Web Portal Wireframes – Designer Home Page and Create New Service Flow
- */
-//libraries variables to prevent compile errors
-declare let jsPDF:any;
-
-module Sdc {
- import User = Sdc.Models.User;
- import UserResourceService = Sdc.Services.UserResourceService;
-
- 'use strict';
- import Resource = Sdc.Models.Components.Resource;
- let moduleName:string = 'sdcApp';
- let viewModelsModuleName:string = 'Sdc.ViewModels';
- let directivesModuleName:string = 'Sdc.Directives';
- let servicesModuleName:string = 'Sdc.Services';
- let filtersModuleName:string = 'Sdc.Filters';
- let utilsModuleName: string = 'Sdc.Utils';
- let dependentModules:Array<string> = [
- 'ui.router',
- 'ui.bootstrap',
- 'ngDragDrop',
- 'ui-notification',
- 'ngResource',
- 'ngSanitize',
- 'Sdc.Config',
- 'naif.base64',
- 'base64',
- 'uuid4',
- 'checklist-model',
- 'angular.filter',
- 'pascalprecht.translate',
- '720kb.tooltips',
- 'restangular',
- 'angular-clipboard',
- 'angularResizable',
- 'infinite-scroll',
- viewModelsModuleName,
- directivesModuleName,
- servicesModuleName,
- filtersModuleName,
- utilsModuleName
- ];
-
- let appModule:ng.IModule = angular.module(moduleName, dependentModules);
-
- appModule.config([
- '$stateProvider',
- '$translateProvider',
- '$urlRouterProvider',
- '$httpProvider',
- 'tooltipsConfigProvider',
- 'NotificationProvider',
- ($stateProvider:any,
- $translateProvider:any,
- $urlRouterProvider:ng.ui.IUrlRouterProvider,
- $httpProvider:ng.IHttpProvider,
- tooltipsConfigProvider:any,
- NotificationProvider:any):void => {
-
- NotificationProvider.setOptions({
- delay: 10000,
- startTop: 10,
- startRight: 10,
- closeOnClick: true,
- verticalSpacing: 20,
- horizontalSpacing: 20,
- positionX: 'right',
- positionY: 'top'
- });
-
- let viewModelsHtmlBasePath:string = '/app/scripts/view-models/';
- console.info('appModule.config: ', viewModelsHtmlBasePath);
-
- $translateProvider.useStaticFilesLoader({
- prefix: 'languages/',
- langKey: '',
- suffix: '.json?d=' + (new Date()).getTime()
- });
- $translateProvider.useSanitizeValueStrategy('escaped');
- $translateProvider.preferredLanguage('en_US_OS'); // For open source changed to en_US_OS
-
- $httpProvider.interceptors.push('Sdc.Services.HeaderInterceptor');
- $httpProvider.interceptors.push('Sdc.Services.HttpErrorInterceptor');
-
- $urlRouterProvider.otherwise('welcome');
-
- $stateProvider.state(
- 'dashboard', {
- url: '/dashboard?show&folder',
- templateProvider: ['$templateCache', ($templateCache):string => {
- return $templateCache.get(viewModelsHtmlBasePath + 'dashboard/dashboard-view.html');
- }],
- controller: viewModelsModuleName + '.DashboardViewModel',
-
- }
- );
-
- $stateProvider.state(
- 'welcome', {
- url: '/welcome',
- templateProvider: ['$templateCache', ($templateCache):string => {
- return $templateCache.get(viewModelsHtmlBasePath + 'welcome/welcome-view.html');
- }],
- controller: viewModelsModuleName + '.WelcomeViewModel'
- }
- );
-
- $stateProvider.state(
- 'dashboard.cover', {
- url: '/cover',
- templateProvider: ['$templateCache', ($templateCache):string => {
- return $templateCache.get(viewModelsHtmlBasePath + 'dashboard/cover/dashboard-cover-view.html');
- }],
- controller: viewModelsModuleName + '.DashboardCoverViewModel'
- }
- );
-
- $stateProvider.state(
- 'dashboard.tutorial-end', {
- url: '/tutorial-end',
- templateProvider: ['$templateCache', ($templateCache):string => {
- return $templateCache.get(viewModelsHtmlBasePath + 'tutorial-end/tutorial-end.html');
- }],
- controller: viewModelsModuleName + '.TutorialEndViewModel'
- }
- );
-
- $stateProvider.state(
- 'additionalInformation', {
- url: '/additionalInformation',
- templateProvider: ['$templateCache', ($templateCache):string => {
- return $templateCache.get(viewModelsHtmlBasePath + 'additional-information/additional-information-view.html');
- }],
- controller: viewModelsModuleName + '.AdditionalInformationViewModel'
- }
- );
-
- let componentsParam:Array<any> = ['$stateParams', 'Sdc.Services.EntityService','Sdc.Services.CacheService' , ($stateParams:any, EntityService:Sdc.Services.EntityService, cacheService:Services.CacheService) => {
- if(cacheService.get('breadcrumbsComponents')){
- return cacheService.get('breadcrumbsComponents');
- } else {
- return EntityService.getCatalog(); //getAllComponents() doesnt return components from catalog
- }
- }];
-
-
- $stateProvider.state (
- 'workspace', {
- url: '/workspace/:id/:type/',
- params: {'importedFile':null,'componentCsar':null,'resourceType': null, 'disableButtons': null}, //'vspComponent': null,
- templateProvider: ['$templateCache', ($templateCache:ng.ITemplateCacheService):string => {
- return $templateCache.get(viewModelsHtmlBasePath + 'workspace/workspace-view.html');
- }],
- controller: viewModelsModuleName + '.WorkspaceViewModel',
- resolve: {
- injectComponent: ['$stateParams', 'ComponentFactory' , function ($stateParams, ComponentFactory) {
- /*
- if($stateParams.vspComponent){
- return $stateParams.vspComponent;
- } else
- */
- if($stateParams.id){
- return ComponentFactory.getComponentFromServer($stateParams.type.toUpperCase(), $stateParams.id);
- } else if ($stateParams.componentCsar && $stateParams.componentCsar.csarUUID) {
- return $stateParams.componentCsar;
- } else {
- let emptyComponent = ComponentFactory.createEmptyComponent($stateParams.type.toUpperCase());
- if (emptyComponent.isResource() && $stateParams.resourceType){
- // Set the resource type
- (<Resource>emptyComponent).resourceType = $stateParams.resourceType;
- }
- if($stateParams.importedFile){
- (<Models.Components.Resource>emptyComponent).importedFile = $stateParams.importedFile;
- }
- return emptyComponent;
- }
- }],
- components: componentsParam
- }
- }
- );
-
- $stateProvider.state(
- Utils.Constants.States.WORKSPACE_GENERAL, {
- url: 'general',
- parent: 'workspace',
- controller: viewModelsModuleName + '.GeneralViewModel',
- templateProvider: ['$templateCache', ($templateCache:ng.ITemplateCacheService):string => {
- return $templateCache.get(viewModelsHtmlBasePath + 'workspace/tabs/general/general-view.html');
- }],
- data: {unsavedChanges:false,bodyClass:'general'}
- }
- );
-
- $stateProvider.state(
- Utils.Constants.States.WORKSPACE_ICONS, {
- url: 'icons',
- parent: 'workspace',
- controller: viewModelsModuleName + '.IconsViewModel',
- templateProvider: ['$templateCache', ($templateCache:ng.ITemplateCacheService):string => {
-
- return $templateCache.get(viewModelsHtmlBasePath + 'workspace/tabs/icons/icons-view.html');
- }],
- data: {unsavedChanges:false,bodyClass:'icons'}
-
- }
- );
-
- $stateProvider.state(
- Utils.Constants.States.WORKSPACE_ACTIVITY_LOG, {
- url: 'activity_log',
- parent: 'workspace',
- controller: viewModelsModuleName + '.ActivityLogViewModel',
- templateProvider: ['$templateCache', ($templateCache:ng.ITemplateCacheService):string => {
- return $templateCache.get(viewModelsHtmlBasePath + 'workspace/tabs/activity-log/activity-log.html');
- }],
- data: {unsavedChanges:false}
- }
- );
-
- $stateProvider.state(
- Utils.Constants.States.WORKSPACE_DEPLOYMENT_ARTIFACTS, {
- url: 'deployment_artifacts',
- parent: 'workspace',
- controller: viewModelsModuleName + '.DeploymentArtifactsViewModel',
- templateProvider: ['$templateCache', ($templateCache:ng.ITemplateCacheService):string => {
-
- return $templateCache.get(viewModelsHtmlBasePath + 'workspace/tabs/deployment-artifacts/deployment-artifacts-view.html');
- }],
- data:{
- bodyClass:'deployment_artifacts'
- }
- }
- );
-
- $stateProvider.state(
- Utils.Constants.States.WORKSPACE_HIERARCHY, {
- url: 'hierarchy',
- parent: 'workspace',
- controller: viewModelsModuleName + '.ProductHierarchyViewModel',
- templateProvider: ['$templateCache', ($templateCache:ng.ITemplateCacheService):string => {
-
- return $templateCache.get(viewModelsHtmlBasePath + 'workspace/tabs/product-hierarchy/product-hierarchy-view.html');
- }]
-
- }
- );
-
- $stateProvider.state(
- Utils.Constants.States.WORKSPACE_INFORMATION_ARTIFACTS, {
- url: 'information_artifacts',
- parent: 'workspace',
- controller: viewModelsModuleName + '.InformationArtifactsViewModel',
- templateProvider: ['$templateCache', ($templateCache:ng.ITemplateCacheService):string => {
-
- return $templateCache.get(viewModelsHtmlBasePath + 'workspace/tabs/information-artifacts/information-artifacts-view.html');
- }],
- data:{
- bodyClass:'information_artifacts'
- }
- }
- );
-
- $stateProvider.state(
- Utils.Constants.States.WORKSPACE_TOSCA_ARTIFACTS, {
- url: 'tosca_artifacts',
- parent: 'workspace',
- controller: viewModelsModuleName + '.ToscaArtifactsViewModel',
- templateProvider: ['$templateCache', ($templateCache:ng.ITemplateCacheService):string => {
-
- return $templateCache.get(viewModelsHtmlBasePath + 'workspace/tabs/tosca-artifacts/tosca-artifacts-view.html');
- }],
- data:{
- bodyClass:'tosca_artifacts'
- }
- }
- );
-
- $stateProvider.state(
- Utils.Constants.States.WORKSPACE_PROPERTIES, {
- url: 'properties',
- parent: 'workspace',
- controller: viewModelsModuleName + '.PropertiesViewModel',
- templateProvider: ['$templateCache', ($templateCache:ng.ITemplateCacheService):string => {
- return $templateCache.get(viewModelsHtmlBasePath + 'workspace/tabs/properties/properties-view.html');
- }],
- data:{
- bodyClass:'properties'
- }
- }
- );
-
- $stateProvider.state(
- Utils.Constants.States.WORKSPACE_SERVICE_INPUTS, {
- url: 'service_inputs',
- parent: 'workspace',
- controller: viewModelsModuleName + '.ServiceInputsViewModel',
- templateProvider: ['$templateCache', ($templateCache:ng.ITemplateCacheService):string => {
- return $templateCache.get(viewModelsHtmlBasePath + 'workspace/tabs/inputs/service-input/service-inputs-view.html');
- }],
- data:{
- bodyClass:'workspace-inputs'
- }
- }
- );
-
- $stateProvider.state(
- Utils.Constants.States.WORKSPACE_RESOURCE_INPUTS, {
- url: 'resource_inputs',
- parent: 'workspace',
- controller: viewModelsModuleName + '.ResourceInputsViewModel',
- templateProvider: ['$templateCache', ($templateCache:ng.ITemplateCacheService):string => {
- return $templateCache.get(viewModelsHtmlBasePath + 'workspace/tabs/inputs/resource-input/resource-inputs-view.html');
- }],
- data:{
- bodyClass:'workspace-inputs'
- }
- }
- );
-
- $stateProvider.state(
- Utils.Constants.States.WORKSPACE_ATTRIBUTES, {
- url: 'attributes',
- parent: 'workspace',
- controller: viewModelsModuleName + '.AttributesViewModel',
- templateProvider: ['$templateCache', ($templateCache:ng.ITemplateCacheService):string => {
- return $templateCache.get(viewModelsHtmlBasePath + 'workspace/tabs/attributes/attributes-view.html');
- }],
- data:{
- bodyClass:'attributes'
- }
- }
- );
-
- $stateProvider.state(
- Utils.Constants.States.WORKSPACE_REQUIREMENTS_AND_CAPABILITIES, {
- url: 'req_and_capabilities',
- parent: 'workspace',
- controller: viewModelsModuleName + '.ReqAndCapabilitiesViewModel',
- templateProvider: ['$templateCache', ($templateCache:ng.ITemplateCacheService):string => {
- return $templateCache.get(viewModelsHtmlBasePath + 'workspace/tabs/req-and-capabilities/req-and-capabilities-view.html');
- }],
- data:{
- bodyClass:'attributes'
- }
- }
- );
-
-
- $stateProvider.state(
- Utils.Constants.States.WORKSPACE_MANAGEMENT_WORKFLOW, {
- parent: 'workspace',
- url: 'management_workflow',
- templateProvider: ['$templateCache', ($templateCache):string => {
- return $templateCache.get(viewModelsHtmlBasePath + 'workspace/tabs/management-workflow/management-workflow-view.html');
- }],
- controller: viewModelsModuleName + '.ManagementWorkflowViewModel'
- }
- );
-
- $stateProvider.state(
- Utils.Constants.States.WORKSPACE_NETWORK_CALL_FLOW, {
- parent: 'workspace',
- url: 'network_call_flow',
- templateProvider: ['$templateCache', ($templateCache):string => {
- return $templateCache.get(viewModelsHtmlBasePath + 'workspace/tabs/network-call-flow/network-call-flow-view.html');
- }],
- controller: viewModelsModuleName + '.NetworkCallFlowViewModel'
- }
- );
-
- $stateProvider.state(
- Utils.Constants.States.WORKSPACE_DISTRIBUTION, {
- parent: 'workspace',
- url: 'distribution',
- templateProvider: ['$templateCache', ($templateCache):string => {
- return $templateCache.get(viewModelsHtmlBasePath + 'workspace/tabs/distribution/distribution-view.html');
- }],
- controller: viewModelsModuleName + '.DistributionViewModel'
- }
- );
-
- $stateProvider.state(
- Utils.Constants.States.WORKSPACE_COMPOSITION, {
- url: 'composition/',
- parent: 'workspace',
- controller: viewModelsModuleName + '.CompositionViewModel',
- templateProvider: ['$templateCache', ($templateCache:ng.ITemplateCacheService):string => {
-
- return $templateCache.get(viewModelsHtmlBasePath + 'workspace/tabs/composition/composition-view.html');
- }],
- data:{
- bodyClass:'composition'
- }
- }
- );
-
- $stateProvider.state(
- Utils.Constants.States.WORKSPACE_DEPLOYMENT, {
- url: 'deployment/',
- parent: 'workspace',
- controller: viewModelsModuleName + '.DeploymentViewModel',
- templateProvider: ['$templateCache', ($templateCache:ng.ITemplateCacheService):string => {
-
- return $templateCache.get(viewModelsHtmlBasePath + 'workspace/tabs/deployment/deployment-view.html');
- }],
- data:{
- bodyClass:'composition'
- }
- }
- );
-
- $stateProvider.state(
- 'workspace.composition.details', {
- url: 'details',
- parent: 'workspace.composition',
- templateProvider: ['$templateCache', ($templateCache):string => {
- return $templateCache.get(viewModelsHtmlBasePath + 'workspace/tabs/composition/tabs/details/details-view.html');
- }],
- controller: viewModelsModuleName + '.DetailsViewModel'
- }
- );
-
- $stateProvider.state(
- 'workspace.composition.properties', {
- url: 'properties',
- parent: 'workspace.composition',
- templateProvider: ['$templateCache', ($templateCache):string => {
- return $templateCache.get(viewModelsHtmlBasePath + 'workspace/tabs/composition/tabs/properties-and-attributes/properties-view.html');
- }],
- controller: viewModelsModuleName + '.ResourcePropertiesViewModel'
- }
- );
-
- $stateProvider.state(
- 'workspace.composition.artifacts', {
- url: 'artifacts',
- parent: 'workspace.composition',
- templateProvider: ['$templateCache', ($templateCache):string => {
- return $templateCache.get(viewModelsHtmlBasePath + 'workspace/tabs/composition/tabs/artifacts/artifacts-view.html');
- }],
- controller: viewModelsModuleName + '.ResourceArtifactsViewModel'
- }
- );
-
- $stateProvider.state(
- 'workspace.composition.relations', {
- url: 'relations',
- parent: 'workspace.composition',
- templateProvider: ['$templateCache', ($templateCache):string => {
- return $templateCache.get(viewModelsHtmlBasePath + 'workspace/tabs/composition/tabs/relations/relations-view.html');
- }],
- controller: viewModelsModuleName + '.RelationsViewModel'
- }
- );
-
- $stateProvider.state(
- 'workspace.composition.relationships', {
- url: 'relationships',
- parent: 'workspace.composition',
- templateProvider: ['$templateCache', ($templateCache):string => {
- return $templateCache.get(viewModelsHtmlBasePath + 'resource-relationships/resource-relationships-view.html');
- }],
- controller: viewModelsModuleName + '.ResourceRelationshipsViewModel'
- }
- );
-
- $stateProvider.state(
- 'workspace.composition.structure', {
- url: 'structure',
- parent: 'workspace.composition',
- templateProvider: ['$templateCache', ($templateCache):string => {
- return $templateCache.get(viewModelsHtmlBasePath + 'workspace/tabs/composition/tabs/structure/structure-view.html');
- }],
- controller: viewModelsModuleName + '.StructureViewModel'
- }
- );
- $stateProvider.state(
- 'workspace.composition.lifecycle', {
- url: 'lifecycle',
- parent: 'workspace.composition',
- templateProvider: ['$templateCache', ($templateCache):string => {
- return $templateCache.get(viewModelsHtmlBasePath + 'workspace/tabs/composition/tabs/artifacts/artifacts-view.html');
- }],
- controller: viewModelsModuleName + '.ResourceArtifactsViewModel'
- }
- );
-
- $stateProvider.state(
- 'workspace.composition.api', {
- url: 'api',
- parent: 'workspace.composition',
- templateProvider: ['$templateCache', ($templateCache):string => {
- return $templateCache.get(viewModelsHtmlBasePath + 'workspace/tabs/composition/tabs/artifacts/artifacts-view.html');
- }],
- controller: viewModelsModuleName + '.ResourceArtifactsViewModel'
- }
- );
- $stateProvider.state(
- 'workspace.composition.deployment', {
- url: 'deployment',
- parent: 'workspace.composition',
- templateProvider: ['$templateCache', ($templateCache):string => {
- return $templateCache.get(viewModelsHtmlBasePath + 'workspace/tabs/composition/tabs/artifacts/artifacts-view.html');
- }],
- controller: viewModelsModuleName + '.ResourceArtifactsViewModel'
- }
- );
-
- $stateProvider.state(
- 'edit-resource', {
- url: '/edit-resource/:id',
- templateProvider: ['$templateCache', ($templateCache):string => {
- return $templateCache.get(viewModelsHtmlBasePath + 'entity-handler/resource-form/resource-form-view.html');
- }],
- controller: viewModelsModuleName + '.ResourceFormViewModel'
- }
- );
-
- $stateProvider.state(
- 'edit-product', {
- url: '/edit-product/:id',
- templateProvider: ['$templateCache', ($templateCache):string => {
- return $templateCache.get(viewModelsHtmlBasePath + 'entity-handler/product-form/product-form-view.html');
- }],
- controller: viewModelsModuleName + '.ProductFormViewModel'
- }
- );
-
- $stateProvider.state(
- 'adminDashboard', {
- url: '/adminDashboard',
- templateProvider: ['$templateCache', ($templateCache):string => {
- return $templateCache.get(viewModelsHtmlBasePath + 'admin-dashboard/admin-dashboard-view.html');
- }],
- controller: viewModelsModuleName + '.AdminDashboardViewModel',
- permissions: ['ADMIN']
- }
- );
-
- $stateProvider.state(
- 'onboardVendor', {
- url: '/onboardVendor',
- templateProvider: ['$templateCache', ($templateCache):string => {
- return $templateCache.get(viewModelsHtmlBasePath + 'onboard-vendor/onboard-vendor-view.html');
- }],
- controller: viewModelsModuleName + '.OnboardVendorViewModel'//,
- //resolve: {
- // auth: ["$q", "Sdc.Services.UserResourceService", function ($q:any, userResourceService:Sdc.Services.IUserResourceClass) {
- // let userInfo:Sdc.Services.IUserResource = userResourceService.getLoggedinUser();
- // if (userInfo) {
- // return $q.when(userInfo);
- // } else {
- // return $q.reject({authenticated: false});
- // }
- // }]
- //}
- }
- );
-
- $stateProvider.state(
- 'catalog', {
- url: '/catalog',
- templateProvider: ['$templateCache', ($templateCache):string => {
- return $templateCache.get(viewModelsHtmlBasePath + 'catalog/catalog-view.html');
- }],
- controller: viewModelsModuleName + '.CatalogViewModel',
- resolve: {
- auth: ["$q", "Sdc.Services.UserResourceService", function ($q:any, userResourceService:Sdc.Services.IUserResourceClass) {
- let userInfo:Sdc.Services.IUserResource = userResourceService.getLoggedinUser();
- if (userInfo) {
- return $q.when(userInfo);
- } else {
- return $q.reject({authenticated: false});
- }
- }]
- }
- }
- );
-
- $stateProvider.state(
- 'distribution', {
- url: '/distribution',
- templateProvider: ['$templateCache', ($templateCache):string => {
- return $templateCache.get(viewModelsHtmlBasePath + 'distribution/distribution-view.html');
- }],
- controller: viewModelsModuleName + '.DistributionViewModel'
- }
- );
-
- $stateProvider.state(
- 'support', {
- url: '/support',
- templateProvider: ['$templateCache', ($templateCache):string => {
- return $templateCache.get(viewModelsHtmlBasePath + 'support/support-view.html');
- }],
- controller: viewModelsModuleName + '.SupportViewModel'
- }
- );
-
- $stateProvider.state(
- 'error-403', {
- url: '/error-403',
- templateProvider: ['$templateCache', ($templateCache):string => {
- return $templateCache.get(viewModelsHtmlBasePath + 'modals/error-modal/error-403-view.html');
- }],
- controller: viewModelsModuleName + '.ErrorViewModel'
- }
- );
-
- tooltipsConfigProvider.options({
-
- side:'bottom',
- delay: '600',
- class: 'tooltip-custom',
- lazy:0,
- try:0
-
- });
-
- }
- ])
- .run(['AngularJSBridge', (AngularJSBridge)=>{
-
- }]);
- appModule.value('ValidationPattern', /^[\s\w\&_.:-]{1,1024}$/);
- appModule.value('PropertyNameValidationPattern', /^[a-zA-Z0-9_:-]{1,50}$/);// DE210977
- appModule.value('TagValidationPattern', /^[\s\w_.-]{1,50}$/);
- // appModule.value('VendorValidationPattern', /^[^?\\<>:"/|*]{1,25}$/);
- appModule.value('VendorValidationPattern', /^[\x20-\x21\x23-\x29\x2B-\x2E\x30-\x39\x3B\x3D\x40-\x5B\x5D-\x7B\x7D-\xFF]{1,25}$/);
- appModule.value('ContactIdValidationPattern', /^[\s\w-]{1,50}$/);
- appModule.value('UserIdValidationPattern',/^[\s\w-]{1,50}$/);
- appModule.value('ProjectCodeValidationPattern', /^[\s\w-]{1,50}$/);
- appModule.value('LabelValidationPattern', /^[\sa-zA-Z0-9+-]{1,25}$/);
- appModule.value('UrlValidationPattern', /^(https?|ftp):\/\/(((([A-Za-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([A-Za-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([A-Za-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([A-Za-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([A-Za-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([A-Za-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([A-Za-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([A-Za-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([A-Za-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([A-Za-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([A-Za-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([A-Za-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/);
- appModule.value('IntegerValidationPattern', /^(([-+]?\d+)|([-+]?0x[0-9a-fA-F]+))$/);
- appModule.value('IntegerNoLeadingZeroValidationPattern', /^(0|[-+]?[1-9][0-9]*|[-+]?0x[0-9a-fA-F]+|[-+]?0o[0-7]+)$/);
- appModule.value('FloatValidationPattern', /^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?f?$/);
- appModule.value('NumberValidationPattern', /^((([-+]?\d+)|([-+]?0x[0-9a-fA-F]+))|([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?))$/);
- appModule.value('KeyValidationPattern', /^[\s\w-]{1,50}$/);
- appModule.value('CommentValidationPattern', /^[\u0000-\u00BF]*$/);
- appModule.value('BooleanValidationPattern', /^([Tt][Rr][Uu][Ee]|[Ff][Aa][Ll][Ss][Ee])$/);
-
-
- appModule.run([
- '$http',
- 'Sdc.Services.CacheService',
- 'Sdc.Services.CookieService',
- 'Sdc.Services.ConfigurationUiService',
- 'Sdc.Services.UserResourceService',
- 'Sdc.Services.CategoryResourceService',
- 'Sdc.Services.SdcVersionService',
- '$state',
- '$rootScope',
- '$location',
- 'sdcConfig',
- 'sdcMenu',
- 'ModalsHandler',
- 'Sdc.Services.EcompHeaderService',
- 'LeftPaletteLoaderService',
- ($http:ng.IHttpService,
- cacheService:Services.CacheService,
- cookieService:Services.CookieService,
- ConfigurationUi:Services.ConfigurationUiService,
- UserResourceClass:Services.IUserResourceClass,
- categoryResourceService:Sdc.Services.ICategoryResourceClass,
- sdcVersionService:Services.SdcVersionService,
- $state:ng.ui.IStateService,
- $rootScope:ng.IRootScopeService,
- $location: ng.ILocationService,
- sdcConfig: Models.IAppConfigurtaion,
- sdcMenu: Models.IAppMenu,
- ModalsHandler:Utils.ModalsHandler,
- ecompHeaderService:Sdc.Services.EcompHeaderService,
- LeftPaletteLoaderService:Services.Components.LeftPaletteLoaderService
- ):void => {
-
- //handle cache data - version
- let initSdcVersion:Function = ():void => {
-
- let onFailed = (response) => {
- console.info('onFailed initSdcVersion', response);
- cacheService.set('version', 'N/A');
- };
-
- let onSuccess = (version:any) => {
- console.log("Version returned from server: " + version);
- let tmpVerArray = version.version.split(".");
- let ver = tmpVerArray[0] + "." + tmpVerArray[1] + "." + tmpVerArray[2];
- cacheService.set('version', ver);
- };
-
- sdcVersionService.getVersion().then(onSuccess, onFailed);
-
- };
-
- let initEcompMenu:Function = (user):void => {
- ecompHeaderService.getMenuItems(user.userId).then((data)=> {
- $rootScope['menuItems'] = data;
- });
- };
-
- let initConfigurationUi:Function = ():void => {
- ConfigurationUi
- .getConfigurationUi()
- .then((configurationUi:any) => {
- cacheService.set('UIConfiguration', configurationUi);
- });
- };
-
- let initCategories:Function = ():void => {
- let onError = ():void => {
- console.log('Failed to init categories');
- };
-
- categoryResourceService.getAllCategories({types: 'services'}, (categories:Array<Models.IMainCategory>):void => {
- cacheService.set('serviceCategories', categories);
- }, onError);
-
- categoryResourceService.getAllCategories({types: 'resources'}, (categories:Array<Models.IMainCategory>):void => {
- cacheService.set('resourceCategories', categories);
- }, onError);
-
- categoryResourceService.getAllCategories({types: 'products'}, (categories:Array<Models.IMainCategory>):void => {
- cacheService.set('productCategories', categories);
- }, onError);
- };
-
- let initBaseUrl:Function = ():void => {
- let env:string = sdcConfig.environment;
- let baseUrl:string = $location.absUrl();
- console.log("baseUrl="+baseUrl);
-
- if(baseUrl) {
- sdcConfig.api.baseUrl = baseUrl;
-
- if(env==='prod'){
- //let tempUrl = $location.absUrl().split('/sdc1/');
- var mainUrl = location.protocol+'//'+location.hostname+(location.port ? ':'+location.port: '');
- console.log("mainUrl="+mainUrl);
- sdcConfig.api.root = mainUrl + sdcConfig.api.root;
- console.log("sdcConfig.api.root="+sdcConfig.api.root);
- }
- }
- };
-
- let initLeftPalette:Function = ():void => {
- LeftPaletteLoaderService.loadLeftPanel();
- };
-
- //handle http config
- $http.defaults.withCredentials = true;
- $http.defaults.headers.common[cookieService.getUserIdSuffix()] = cookieService.getUserId();
-
- initBaseUrl();
- initSdcVersion();
- initConfigurationUi();
- Utils.Constants.IMAGE_PATH = sdcConfig.imagesPath;
- initLeftPalette();
-
- //handle stateChangeStart
- let internalDeregisterStateChangeStartWatcher:Function = ():void => {
- if (deregisterStateChangeStartWatcher) {
- deregisterStateChangeStartWatcher();
- deregisterStateChangeStartWatcher = null;
- }
- };
-
- let removeLoader:Function = ():void => {
- $(".sdc-loading-page .main-loader").addClass("animated fadeOut");
- $(".sdc-loading-page .caption1").addClass("animated fadeOut");
- $(".sdc-loading-page .caption2").addClass("animated fadeOut");
- window.setTimeout(():void=>{
- $(".sdc-loading-page .main-loader").css("display", "none");
- $(".sdc-loading-page .caption1").css("display", "none");
- $(".sdc-loading-page .caption2").css("display", "none");
- $(".sdc-loading-page").addClass("animated fadeOut");
- },1000);
- };
-
- let onNavigateOut:Function = (toState, toParams):void => {
- let onOk = ():void => {
- $state.current.data.unsavedChanges = false;
- $state.go(toState.name, toParams);
- };
-
- let data = sdcMenu.alertMessages.exitWithoutSaving;
- //open notify to user if changes are not saved
- ModalsHandler.openAlertModal(data.title, data.message).then(onOk);
- };
-
- let onStateChangeStart:Function = (event, toState, toParams, fromState, fromParams):void => {
- console.info((new Date()).getTime());
- console.info('$stateChangeStart', toState.name);
- //set body class
- $rootScope['bodyClass'] = 'default-class';
- if(toState.data && toState.data.bodyClass){
- $rootScope['bodyClass'] = toState.data.bodyClass;
- }
-
- // Workaround in case we are entering other state then workspace (user move to catalog)
- // remove the changeComponentCsarVersion, user should open again the VSP list and select one for update.
- if (toState.name.indexOf('workspace') === -1) {
- if (cacheService.contains(Utils.Constants.CHANGE_COMPONENT_CSAR_VERSION_FLAG)){
- cacheService.remove(Utils.Constants.CHANGE_COMPONENT_CSAR_VERSION_FLAG);
- }
- }
-
- //saving last state to params , for breadcrumbs
- if (['dashboard', 'catalog', 'onboardVendor'].indexOf(fromState.name) > -1) {
- toParams.previousState = fromState.name;
- } else {
- toParams.previousState = fromParams.previousState;
- }
-
- if (toState.name !== 'error-403' && !UserResourceClass.getLoggedinUser()) {
- internalDeregisterStateChangeStartWatcher();
- event.preventDefault();
-
- UserResourceClass.authorize().$promise.then((user:Services.IUserResource) => {
- if(!doesUserHasAccess(toState, user)){
- $state.go('error-403');
- console.info('User has no permissions');
- registerStateChangeStartWatcher();
- return;
- }
- UserResourceClass.setLoggedinUser(user);
- cacheService.set('user', user);
- initCategories();
- // initEcompMenu(user);
- setTimeout(function () {
-
- removeLoader();
-
- // initCategories();
- if(UserResourceClass.getLoggedinUser().role === 'ADMIN'){
- // toState.name = "adminDashboard";
- $state.go("adminDashboard", toParams);
- registerStateChangeStartWatcher();
- return;
- }
-
- // After user authorized init categories
- window.setTimeout(():void=>{
- //if ($state.current.name==='' || $state.current.name==='preloading') {
- if ($state.current.name === "welcome" && sdcConfig.openSource) {
- event.preventDefault();
- $state.go("dashboard");
- registerStateChangeStartWatcher();
- }
- else if ($state.current.name==='') {
- $state.go(toState.name, toParams);
- }
-
- console.log("------$state.current.name=" + $state.current.name);
- console.info('-----registerStateChangeStartWatcher authorize $stateChangeStart');
- registerStateChangeStartWatcher();
-
- },1000);
-
- }, 0);
-
- }, () => {
- $state.go('error-403');
-
- console.info('registerStateChangeStartWatcher error-403 $stateChangeStart');
- registerStateChangeStartWatcher();
- });
- }
- else if(UserResourceClass.getLoggedinUser()){
- internalDeregisterStateChangeStartWatcher();
- if(!doesUserHasAccess(toState, UserResourceClass.getLoggedinUser())){
- event.preventDefault();
- $state.go('error-403');
- console.info('User has no permissions');
- }
- if(toState.name === "welcome") {
- $state.go("dashboard");
- }
- registerStateChangeStartWatcher();
- //if form is dirty and not save - notify to user
- if(fromState.data && fromState.data.unsavedChanges && fromParams.id != toParams.id){
- event.preventDefault();
- onNavigateOut(toState, toParams);
- }
- }
-
- };
-
- let doesUserHasAccess:Function = (toState, user):boolean =>{
-
- let isUserHasAccess = true;
- if(toState.permissions && toState.permissions.length > 0) {
- isUserHasAccess = _.includes(toState.permissions, user.role);
- }
- return isUserHasAccess;
- };
- let deregisterStateChangeStartWatcher:Function;
-
- let registerStateChangeStartWatcher:Function = ():void => {
- internalDeregisterStateChangeStartWatcher();
- console.info('registerStateChangeStartWatcher $stateChangeStart');
- deregisterStateChangeStartWatcher = $rootScope.$on('$stateChangeStart', (event, toState, toParams, fromState, fromParams):void => {
- onStateChangeStart(event, toState, toParams, fromState, fromParams);
- });
- };
-
- registerStateChangeStartWatcher();
-
- }]);
-
-
-
-}
-
diff --git a/catalog-ui/app/scripts/directives/clicked-outside/clicked-outside-directive.ts b/catalog-ui/app/scripts/directives/clicked-outside/clicked-outside-directive.ts
deleted file mode 100644
index 1b0af4ef99..0000000000
--- a/catalog-ui/app/scripts/directives/clicked-outside/clicked-outside-directive.ts
+++ /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=========================================================
- */
-/// <reference path="../../references"/>
-module Sdc.Directives {
-
- class ClickedOutsideModel{
-
- private clickedOutsideContainerSelector: string;
- private onClickedOutsideGetter: Function;
- private clickedOutsideEnableGetter: Function;
-
- constructor(clickedOutsideData: any) {
- this.clickedOutsideContainerSelector = clickedOutsideData.clickedOutsideContainerSelector;
- this.onClickedOutsideGetter = clickedOutsideData.onClickedOutsideGetter;
- this.clickedOutsideEnableGetter = clickedOutsideData.clickedOutsideEnableGetter;
- }
-
- public getClickedOutsideContainerSelector = (): string => {
- return this.clickedOutsideContainerSelector;
- }
-
- public getOnClickedOutsideGetter = (): Function => {
- return this.onClickedOutsideGetter;
- }
-
- public getClickedOutsideEnableGetter = (): Function => {
- return this.clickedOutsideEnableGetter;
- }
- }
-
- export interface IClickedOutsideDirectiveScope extends ng.IScope{}
-
- export class ClickedOutsideDirective implements ng.IDirective {
-
- constructor(private $document: JQuery, private $parse: ng.IParseService) {}
-
- restrict = 'A';
-
- link = (scope:IClickedOutsideDirectiveScope, element: JQuery, attrs) => {
-
- let container: HTMLElement;
- let attrsAfterEval = scope.$eval(attrs.clickedOutside);
- attrsAfterEval.onClickedOutsideGetter = this.$parse(attrsAfterEval.onClickedOutside);
- attrsAfterEval.clickedOutsideEnableGetter = this.$parse(attrsAfterEval.clickedOutsideEnable);
-
- let clickedOutsideModel: ClickedOutsideModel = new ClickedOutsideModel(attrsAfterEval);
-
-
- let getContainer: Function = ():HTMLElement => {
- if(!container){
- let clickedOutsideContainerSelector: string = clickedOutsideModel.getClickedOutsideContainerSelector();
- if(!angular.isUndefined(clickedOutsideContainerSelector) && clickedOutsideContainerSelector !== ''){
- container = element.parents(clickedOutsideContainerSelector+':first')[0];
- if(!container){
- container = element[0];
- }
- }else{
- container = element[0];
- }
- }
- return container;
- };
-
-
- let onClickedOutside = (event: JQueryEventObject) => {
- let containerDomElement: HTMLElement = getContainer();
- let targetDomElementJq: JQuery = angular.element(event.target);
- if(targetDomElementJq.hasClass('tooltip') || targetDomElementJq.parents('.tooltip:first').length){
- return;
- }
- let targetDomElement: HTMLElement = targetDomElementJq[0];
- if (!containerDomElement.contains(targetDomElement)){
- scope.$apply(() => {
- let onClickedOutsideGetter:Function = clickedOutsideModel.getOnClickedOutsideGetter();
- onClickedOutsideGetter(scope);
- });
- }
- };
-
- let attachDomEvents: Function = () => {
- this.$document.on('mousedown', onClickedOutside);
- };
-
- let detachDomEvents: Function = () => {
- this.$document.off('mousedown', onClickedOutside);
- };
-
- //
- scope.$on('$destroy', () => {
- detachDomEvents();
- });
-
-
- scope.$watch(() => {
- let clickedOutsideEnableGetter: Function = clickedOutsideModel.getClickedOutsideEnableGetter();
- return clickedOutsideEnableGetter(scope);
- }, (newValue: boolean) => {
- if(newValue){
- attachDomEvents();
- return;
- }
- detachDomEvents();
- });
-
-
- }
-
- public static factory = ($document: JQuery, $parse: ng.IParseService) => {
- return new ClickedOutsideDirective($document, $parse);
- }
- }
-
- ClickedOutsideDirective.factory.$inject = ['$document', '$parse'];
-}
diff --git a/catalog-ui/app/scripts/directives/custom-validation/custom-validation.ts b/catalog-ui/app/scripts/directives/custom-validation/custom-validation.ts
deleted file mode 100644
index e2f831ed53..0000000000
--- a/catalog-ui/app/scripts/directives/custom-validation/custom-validation.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../references"/>
-module Sdc.Directives {
- 'use strict';
-
-
- export interface ICustomValidationScope extends ng.IScope {
- validationFunc: Function;
- }
-
- export class CustomValidationDirective implements ng.IDirective {
-
- constructor() {}
-
- require = 'ngModel';
- restrict = 'A';
-
- scope = {
- validationFunc: '='
- };
-
- link = (scope:ICustomValidationScope, elem, attrs, ngModel) => {
-
- ngModel.$validators.customValidation = (modelValue, viewValue) :boolean => {
- return scope.validationFunc(viewValue);
- };
-
- };
-
- public static factory = ()=> {
- return new CustomValidationDirective();
- };
-
- }
-
- CustomValidationDirective.factory.$inject = [];
-}
diff --git a/catalog-ui/app/scripts/directives/download-artifact/download-artifact.ts b/catalog-ui/app/scripts/directives/download-artifact/download-artifact.ts
deleted file mode 100644
index 49bf14618c..0000000000
--- a/catalog-ui/app/scripts/directives/download-artifact/download-artifact.ts
+++ /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=========================================================
- */
-/// <reference path="../../references"/>
-module Sdc.Directives {
- 'use strict';
-
- export class DOWNLOAD_CSS_CLASSES {
- static DOWNLOAD_ICON = "table-download-btn tosca";
- static LOADER_ICON = "tlv-loader small loader";
- }
-
- export interface IDownloadArtifactScope extends ng.IScope {
- $window:any;
- artifact: Models.ArtifactModel;
- component: Models.Components.Component;
- instance:boolean;
- download: Function;
- showLoader:boolean;
- updateDownloadIcon:Function;
- }
-
- export class DownloadArtifactDirective implements ng.IDirective {
-
- constructor(private $window:any,private cacheService:Services.CacheService, private EventListenerService:Services.EventListenerService, private fileUtils:Sdc.Utils.FileUtils) {}
-
- scope = {
- artifact: '=',
- component: '=',
- instance:'=',
- showLoader:'='
- };
- restrict = 'EA';
-
- link = (scope:IDownloadArtifactScope, element:any) => {
- scope.$window = this.$window;
-
- element.on("click", function() {
- scope.download(scope.artifact);
- });
-
-
- let initDownloadLoader = ()=>{
- //if the artifact is in a middle of download progress register form callBack & change icon from download to loader
- if(scope.showLoader && this.cacheService.get(scope.artifact.uniqueId)){
- this.EventListenerService.registerObserverCallback(Utils.Constants.EVENTS.DOWNLOAD_ARTIFACT_FINISH_EVENT + scope.artifact.uniqueId, scope.updateDownloadIcon);
- window.setTimeout(():void => {
- if(this.cacheService.get(scope.artifact.uniqueId)){
- element[0].className = DOWNLOAD_CSS_CLASSES.LOADER_ICON;
- }
- },1000);
-
- }
- };
-
- let setDownloadedFileLoader = ()=> {
- if(scope.showLoader){
- //set in cache service thet the artifact is in download progress
- this.cacheService.set(scope.artifact.uniqueId,true);
- initDownloadLoader();
- }
- };
-
- let removeDownloadedFileLoader = ()=> {
- if (scope.showLoader) {
- this.cacheService.set(scope.artifact.uniqueId, false);
- this.EventListenerService.notifyObservers(Utils.Constants.EVENTS.DOWNLOAD_ARTIFACT_FINISH_EVENT + scope.artifact.uniqueId);
- }
- };
-
-
- //replace the loader to download icon
- scope.updateDownloadIcon = () =>{
- element[0].className = DOWNLOAD_CSS_CLASSES.DOWNLOAD_ICON;
- };
-
-
- initDownloadLoader();
-
- scope.download = (artifact:Models.ArtifactModel):void => {
-
- let onFaild = (response):void => {
- console.info('onFaild', response);
- removeDownloadedFileLoader();
- };
-
- let onSuccess = (data:Models.IFileDownload):void => {
- downloadFile(data);
- removeDownloadedFileLoader();
- };
-
- setDownloadedFileLoader();
-
- if(scope.instance){
- scope.component.downloadInstanceArtifact(artifact.uniqueId).then(onSuccess, onFaild);
- }else {
- scope.component.downloadArtifact(artifact.uniqueId).then(onSuccess, onFaild);
- }
- };
-
- let downloadFile = (file:Models.IFileDownload):void => {
- if (file){
- let blob = this.fileUtils.base64toBlob(file.base64Contents,'');
- let fileName = file.artifactName;
- this.fileUtils.downloadFile(blob, fileName);
- }
- };
-
- element.on('$destroy', ()=>{
- //remove listener of download event
- if(scope.artifact && scope.artifact.uniqueId){
- this.EventListenerService.unRegisterObserver(Utils.Constants.EVENTS.DOWNLOAD_ARTIFACT_FINISH_EVENT + scope.artifact.uniqueId);
- }
- });
-
- };
-
- public static factory = ($window:any,cacheService:Sdc.Services.CacheService,EventListenerService:Services.EventListenerService, fileUtils:Sdc.Utils.FileUtils)=> {
- return new DownloadArtifactDirective($window,cacheService,EventListenerService, fileUtils);
- };
-
- }
-
- DownloadArtifactDirective.factory.$inject = ['$window', 'Sdc.Services.CacheService', 'EventListenerService', 'FileUtils'];
-}
diff --git a/catalog-ui/app/scripts/directives/ecomp-header/ecomp-header.ts b/catalog-ui/app/scripts/directives/ecomp-header/ecomp-header.ts
deleted file mode 100644
index 7102c810ba..0000000000
--- a/catalog-ui/app/scripts/directives/ecomp-header/ecomp-header.ts
+++ /dev/null
@@ -1,235 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../references"/>
-module Sdc.Directives {
- 'use strict';
-
- export class MenuItem {
- menuId:number;
- column:number;
- text:string;
- parentMenuId:number;
- url:string;
- children:Array<MenuItem>
- }
-
- export interface IEcompHeaderDirectiveScope extends ng.IScope {
- menuData:Array<MenuItem>;
- version:string;
- clickableLogo:string;
- contactUsUrl:string;
- getAccessUrl:string;
- megaMenuDataObjectTemp:Array<any>;
- megaMenuDataObject:Array<any>;
-
- selectedTopMenu:MenuItem;
- selectedSubMenu:MenuItem;
-
- firstMenuLevelClick:Function;
- subMenuEnterAction:Function;
- subMenuLeaveAction:Function;
-
- memuItemClick:Function;
- user: Models.IUser;
- }
-
- export class EcompHeaderDirective implements ng.IDirective {
-
- constructor(private $templateCache:ng.ITemplateCacheService,
- private $http:ng.IHttpService,
- private sdcConfig:Models.IAppConfigurtaion,
- private UserResourceClass:Services.IUserResourceClass) {
-
- }
-
- scope = {
- menuData: '=',
- version: '@',
- clickableLogo: '@?'
- };
-
- public replace = true;
- public restrict = 'E';
- public controller = EcompHeaderController;
-
- template = ():string => {
- return this.$templateCache.get('/app/scripts/directives/ecomp-header/ecomp-header.html');
- };
-
- link = ($scope:IEcompHeaderDirectiveScope, $elem:JQuery, attr:any) => {
-
- if (!$scope.clickableLogo){
- $scope.clickableLogo="true";
- }
-
- let findMenuItemById = (menuId):MenuItem => {
- let selectedMenuItem:MenuItem = _.find($scope.menuData, (item:MenuItem)=>{
- if (item.menuId === menuId){
- return item;
- }
- });
- return selectedMenuItem;
- };
-
- let initUser = ():void => {
- let defaultUserId:string;
- let user:Services.IUserResource = this.UserResourceClass.getLoggedinUser();
- if (!user) {
- defaultUserId = this.$http.defaults.headers.common[this.sdcConfig.cookie.userIdSuffix];
- user = this.UserResourceClass.get({id: defaultUserId}, ():void => {
- $scope.user = new Models.User(user);
- });
- } else {
- $scope.user = new Models.User(user);
- }
- };
-
- $scope.firstMenuLevelClick = (menuId:number):void => {
- let selectedMenuItem:MenuItem = _.find($scope.megaMenuDataObjectTemp, (item:MenuItem)=>{
- if (item.menuId === menuId){
- return item;
- }
- });
- if (selectedMenuItem) {
- $scope.selectedTopMenu = selectedMenuItem;
- //console.log("Selected menu item: " + selectedMenuItem.text);
- }
- };
-
- $scope.subMenuEnterAction = (menuId:number):void => {
- $scope.selectedSubMenu = findMenuItemById(menuId);
- };
-
- $scope.subMenuLeaveAction = (menuId:number):void => {
- $scope.selectedTopMenu = undefined;
- };
-
- $scope.memuItemClick = (menuItem:MenuItem):void => {
- if (menuItem.url){
- window.location.href=menuItem.url;
- } else {
- console.log("Menu item: " + menuItem.text + " does not have defined URL!");
- }
- };
-
- initUser();
-
- };
-
- public static factory = ($templateCache:ng.ITemplateCacheService,
- $http:ng.IHttpService,
- sdcConfig:Models.IAppConfigurtaion,
- UserResourceClass:Services.IUserResourceClass)=> {
- return new EcompHeaderDirective($templateCache, $http, sdcConfig, UserResourceClass);
- };
-
- }
-
- export class EcompHeaderController {
-
- messages:any;
- getAttachId:Function;
- render:any;
- reRender:Function;
- register:Function;
- deregister:Function;
- head:any;
-
- static '$inject' = [
- '$element',
- '$scope',
- '$attrs',
- '$animate'
- ];
-
- constructor(private $element:JQuery,
- private $scope:IEcompHeaderDirectiveScope,
- private $attrs:ng.IAttributes,
- private $animate:any) {
-
- this.$scope = $scope;
-
- this.$scope.$watch('menuData', (newVal, oldVal) => {
- if (newVal){
- this.init();
- }
- });
-
- }
-
- init = ():void => {
-
- this.$scope.contactUsUrl = "https://wiki.web.att.com/display/EcompPortal/ECOMP+Portal+Home";
- this.$scope.getAccessUrl = "http://ecomp-tlv-dev2.uccentral.att.com:8080/ecompportal/get_access";
-
- let unflatten = ( array, parent?, tree? ) => {
- tree = typeof tree !== 'undefined' ? tree : [];
- parent = typeof parent !== 'undefined' ? parent : { menuId: null };
- let children = _.filter( array, function(child){ return child["parentMenuId"] == parent.menuId; });
- if( !_.isEmpty( children ) ){
- if( parent.menuId === null ){
- tree = children;
- }else{
- parent['children'] = children
- }
- _.each( children, function( child ){ unflatten( array, child ) } );
- }
- return tree;
- };
-
- let menuStructureConvert = (menuItems) => {
- console.log(menuItems);
- this.$scope.megaMenuDataObjectTemp = [
- {
- menuId: 1001,
- text: "ECOMP",
- children: menuItems
- },
- {
- menuId: 1002,
- text: "Help",
- children: [
- {
- text:"Contact Us",
- url: this.$scope.contactUsUrl
- }]
- }
- ];
-
- /*{
- text:"Get Access",
- url: this.$scope.getAccessUrl
- }*/
- return this.$scope.megaMenuDataObjectTemp;
- };
-
- let a = unflatten(this.$scope.menuData);
- this.$scope.megaMenuDataObject = menuStructureConvert(a);
- //console.log(this.$scope.megaMenuDataObject);
- };
- }
-
- EcompHeaderDirective.factory.$inject = ['$templateCache', '$http', 'sdcConfig', 'Sdc.Services.UserResourceService'];
-
-}
-
-
-
-
diff --git a/catalog-ui/app/scripts/directives/edit-name-popover/edit-name-popover-directive.ts b/catalog-ui/app/scripts/directives/edit-name-popover/edit-name-popover-directive.ts
deleted file mode 100644
index a033df054b..0000000000
--- a/catalog-ui/app/scripts/directives/edit-name-popover/edit-name-popover-directive.ts
+++ /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=========================================================
- */
-/// <reference path="../../references"/>
-module Sdc.Directives {
- 'use strict';
-
- export interface IEditNamePopoverDirectiveScope extends ng.IScope {
- isOpen: boolean;
- templateUrl: string;
- module: any;
- direction: string;
- header: string;
- heatNameValidationPattern:RegExp;
- originalName:string;
- onSave:any;
-
- closePopover(isCancel:boolean):void;
- validateField(field:any, originalName:string):boolean;
- updateHeatName(heatName:string):void;
- onInit():void;
- }
-
- export class EditNamePopoverDirective implements ng.IDirective {
-
- constructor(private $templateCache:ng.ITemplateCacheService, private ValidationPattern:RegExp) {
- }
-
- scope = {
- direction: "@?",
- module: "=",
- header: "@?",
- onSave: "&"
- };
-
- link = (scope:IEditNamePopoverDirectiveScope) => {
- if(!scope.direction) {
- scope.direction = 'top';
- }
-
- scope.originalName = '';
- scope.templateUrl = "/app/scripts/directives/edit-name-popover/edit-module-name-popover.html";
- scope.isOpen = false;
-
- scope.closePopover = (isCancel:boolean = true) => {
- scope.isOpen = !scope.isOpen;
-
- if(isCancel) {
- scope.module.heatName = scope.originalName;
- }
- };
-
- scope.onInit = () => {
- scope.originalName = scope.module.heatName;
- };
-
- scope.validateField = (field:any):boolean => {
- return !!(field && field.$dirty && field.$invalid);
- };
-
- scope.heatNameValidationPattern = this.ValidationPattern;
-
- scope.updateHeatName = () => {
- scope.closePopover(false);
- scope.onSave();
- }
-
- };
-
- replace = true;
- restrict = 'E';
- template = ():string => {
- return this.$templateCache.get('/app/scripts/directives/edit-name-popover/edit-name-popover-view.html');
- };
-
- public static factory = ($templateCache:ng.ITemplateCacheService, ValidationPattern:RegExp)=> {
- return new EditNamePopoverDirective($templateCache, ValidationPattern);
- }
- }
-
- EditNamePopoverDirective.factory.$inject = ['$templateCache', 'ValidationPattern'];
-}
diff --git a/catalog-ui/app/scripts/directives/edit-name-popover/edit-name-popover-view.html b/catalog-ui/app/scripts/directives/edit-name-popover/edit-name-popover-view.html
deleted file mode 100644
index 17beead6b3..0000000000
--- a/catalog-ui/app/scripts/directives/edit-name-popover/edit-name-popover-view.html
+++ /dev/null
@@ -1 +0,0 @@
-<div uib-popover-template="templateUrl" popover-title="{{header}}" popover-placement="{{direction}}" popover-is-open="isOpen" popover-append-to-body="true"></div>
diff --git a/catalog-ui/app/scripts/directives/elements/checkbox/checkbox.ts b/catalog-ui/app/scripts/directives/elements/checkbox/checkbox.ts
deleted file mode 100644
index c45a9d92e1..0000000000
--- a/catalog-ui/app/scripts/directives/elements/checkbox/checkbox.ts
+++ /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=========================================================
- */
-/// <reference path="../../../references"/>
-module Sdc.Directives {
- 'use strict';
-
- export interface ICheckboxElementScope extends ng.IScope {
- elemId: string;
- text: string;
- sdcChecklistModel: any;
- sdcChecklistValue: string;
- disabled:boolean;
- }
-
- export class CheckboxElementDirective implements ng.IDirective {
-
- constructor(private $templateCache:ng.ITemplateCacheService,
- private $filter:ng.IFilterService) {
- }
-
- public replace = true;
- public restrict = 'E';
- public transclude = false;
-
- scope = {
- elemId: '@',
- text: '@',
- disabled: '=',
- sdcChecklistModel: '=',
- sdcChecklistValue: '='
- };
-
- template = ():string => {
- return this.$templateCache.get('/app/scripts/directives/elements/checkbox/checkbox.html');
- };
-
- public link = (scope:ICheckboxElementScope, $elem:ng.IAugmentedJQuery, $attrs:angular.IAttributes) => {
- //$elem.removeAttr("id")
- //console.log(scope.sdcChecklistValue);
- };
-
- public static factory = ($templateCache:ng.ITemplateCacheService, $filter:ng.IFilterService)=> {
- return new CheckboxElementDirective($templateCache, $filter);
- };
-
- }
-
- CheckboxElementDirective.factory.$inject = ['$templateCache', '$filter'];
-}
diff --git a/catalog-ui/app/scripts/directives/elements/radiobutton/radiobutton.ts b/catalog-ui/app/scripts/directives/elements/radiobutton/radiobutton.ts
deleted file mode 100644
index 9fe58d8f8b..0000000000
--- a/catalog-ui/app/scripts/directives/elements/radiobutton/radiobutton.ts
+++ /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=========================================================
- */
-/// <reference path="../../../references"/>
-module Sdc.Directives {
- import INgModelController = angular.INgModelController;
- 'use strict';
-
- export interface IRadiobuttonElementScope extends ng.IScope {
- elemId: string;
- elemName: string;
- text: string;
- sdcModel: any;
- value: any;
- disabled: boolean;
- onValueChange:Function;
- }
-
- export class RadiobuttonElementDirective implements ng.IDirective {
-
- constructor(private $templateCache:ng.ITemplateCacheService,
- private $filter:ng.IFilterService) {
- }
-
- public replace = true;
- public restrict = 'E';
- public transclude = false;
-
- scope = {
- elemId: '@',
- elemName: '@',
- text: '@',
- sdcModel: '=',
- value: '@',
- disabled: '=',
- onValueChange: '&'
- };
-
- template = ():string => {
- return this.$templateCache.get('/app/scripts/directives/elements/radiobutton/radiobutton.html');
- };
-
- public link = (scope:IRadiobuttonElementScope, $elem:ng.IAugmentedJQuery, $attrs:angular.IAttributes) => {
- //$elem.removeAttr("id")
- //console.log(scope.sdcChecklistValue);
- };
-
- public static factory = ($templateCache:ng.ITemplateCacheService, $filter:ng.IFilterService)=> {
- return new RadiobuttonElementDirective($templateCache, $filter);
- };
-
- }
-
- RadiobuttonElementDirective.factory.$inject = ['$templateCache', '$filter'];
-}
diff --git a/catalog-ui/app/scripts/directives/ellipsis/ellipsis-directive.ts b/catalog-ui/app/scripts/directives/ellipsis/ellipsis-directive.ts
deleted file mode 100644
index a5ccf248e0..0000000000
--- a/catalog-ui/app/scripts/directives/ellipsis/ellipsis-directive.ts
+++ /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=========================================================
- */
-/// <reference path="../../references"/>
-module Sdc.Directives {
- 'use strict';
- export interface IEllipsisScope extends ng.IScope {
- ellipsis: string;
- maxChars: number;
- toggleText(): void;
- collapsed: boolean;
- actualText: string;
-
- }
-
- export class EllipsisDirective implements ng.IDirective {
-
- constructor(private $templateCache: ng.ITemplateCacheService) {}
-
- scope = {
- ellipsis: '=',
- moreClass: '@',
- maxChars: '='
- };
-
- replace = false;
- restrict = 'A';
- template = (): string => {
- return this.$templateCache.get('/app/scripts/directives/ellipsis/ellipsis-directive.html');
- };
-
- link = (scope:IEllipsisScope, $elem:any) => {
-
-
- scope.collapsed = true;
-
- scope.toggleText = (): void => {
- if(scope.ellipsis && scope.collapsed) {
- scope.actualText = scope.ellipsis.substr(0, scope.maxChars);
- scope.actualText += scope.ellipsis.length > scope.maxChars ? '...' : '';
- }
- else
- {
- scope.actualText = scope.ellipsis;
- }
- };
-
- scope.$watch("ellipsis", function(){
- scope.collapsed = true;
- scope.toggleText();
- });
-
-
-
- };
-
- public static factory = ($templateCache: ng.ITemplateCacheService)=> {
- return new EllipsisDirective($templateCache);
- };
-
- }
-
- EllipsisDirective.factory.$inject = ['$templateCache'];
-}
diff --git a/catalog-ui/app/scripts/directives/events/on-last-repeat/on-last-repeat.ts b/catalog-ui/app/scripts/directives/events/on-last-repeat/on-last-repeat.ts
deleted file mode 100644
index 0fb682d202..0000000000
--- a/catalog-ui/app/scripts/directives/events/on-last-repeat/on-last-repeat.ts
+++ /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=========================================================
- */
-/// <reference path="../../../references"/>
-module Sdc.Directives {
- 'use strict';
-
- /**
- * Usage:
- * In data-ng-repeat html: <ol ng-repeat="record in records" on-last-repeat>
- * In the controller, catch the last repeat:
- * $scope.$on('onRepeatLast', function(scope, element, attrs){
- * //work your magic
- * });
- */
- export interface IOnLastRepeatDirectiveScope extends ng.IScope {
- $last:any;
- }
-
- export class OnLastRepeatDirective implements ng.IDirective {
-
- constructor() {}
-
- scope = {};
-
- restrict = 'AE';
- replace = true;
-
- link = (scope:IOnLastRepeatDirectiveScope, element:any, attrs:any) => {
- let s:any = scope.$parent; // repeat scope
- if (s.$last) {
- setTimeout(function(){
- s.$emit('onRepeatLast', element, attrs);
- }, 1);
- }
- };
-
- public static factory = ()=> {
- return new OnLastRepeatDirective();
- };
-
- }
-
- OnLastRepeatDirective.factory.$inject = [];
-}
diff --git a/catalog-ui/app/scripts/directives/file-opener/file-opener.ts b/catalog-ui/app/scripts/directives/file-opener/file-opener.ts
deleted file mode 100644
index b7e3e1804c..0000000000
--- a/catalog-ui/app/scripts/directives/file-opener/file-opener.ts
+++ /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=========================================================
- */
-/// <reference path="../../references"/>
-module Sdc.Directives {
- 'use strict';
-
- export interface IFileOpenerScope extends ng.IScope {
- importFile:any;
- testsId:any;
- extensions:string;
-
- onFileSelect():void;
- onFileUpload(file:any):void;
- getExtensionsWithDot():string;
- }
-
- export class FileOpenerDirective implements ng.IDirective {
-
- constructor(private $templateCache:ng.ITemplateCacheService,
- private $compile:ng.ICompileService) {
- }
-
- scope = {
- onFileUpload: '&',
- testsId: '@',
- extensions: '@'
- };
-
- restrict = 'AE';
- replace = true;
- template = ():string => {
- return this.$templateCache.get('/app/scripts/directives/file-opener/file-opener.html');
- };
-
- link = (scope:IFileOpenerScope, element:any) => {
-
- scope.onFileSelect = () => {
- scope.onFileUpload({file: scope.importFile});
- element.html(this.$templateCache.get('/app/scripts/directives/file-opener/file-opener.html'));
- this.$compile(element.contents())(scope);
- };
-
- scope.getExtensionsWithDot = ():string => {
- let ret = [];
- _.each(scope.extensions.split(','), function(item){
- ret.push("." + item.toString());
- });
- return ret.join(",");
- };
-
- };
-
- public static factory = ($templateCache:ng.ITemplateCacheService, $compile:ng.ICompileService)=> {
- return new FileOpenerDirective($templateCache, $compile);
- };
-
- }
-
- FileOpenerDirective.factory.$inject = ['$templateCache', '$compile'];
-}
diff --git a/catalog-ui/app/scripts/directives/file-type/file-type.ts b/catalog-ui/app/scripts/directives/file-type/file-type.ts
deleted file mode 100644
index e7dee17960..0000000000
--- a/catalog-ui/app/scripts/directives/file-type/file-type.ts
+++ /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=========================================================
- */
-/// <reference path="../../references"/>
-module Sdc.Directives {
- 'use strict';
-
- export class FileTypeDirective implements ng.IDirective {
-
- constructor() {}
-
- require = 'ngModel';
-
- link = (scope, elem, attrs, ngModel) => {
-
- let typesToApprove = "";
-
- attrs.$observe('fileType', (val:string) => {
- typesToApprove = val;
- validate(ngModel.$viewValue);
- });
-
- let validate: Function = function (value) {
- let fileName:string = elem.val(), valid:boolean = true;
-
- if (fileName && value && typesToApprove) {
- let extension:string = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase();
- valid = typesToApprove.split(',').indexOf(extension) > -1;
- }
-
- ngModel.$setValidity('filetype', valid);
- if(!value) {
- ngModel.$setPristine();
- }
- return value;
- };
-
- //For DOM -> model validation
- ngModel.$parsers.unshift(validate);
-
- };
-
- public static factory = ()=> {
- return new FileTypeDirective();
- };
-
- }
-
- FileTypeDirective.factory.$inject = [];
-}
diff --git a/catalog-ui/app/scripts/directives/file-upload/file-upload.ts b/catalog-ui/app/scripts/directives/file-upload/file-upload.ts
deleted file mode 100644
index 16db3e7e21..0000000000
--- a/catalog-ui/app/scripts/directives/file-upload/file-upload.ts
+++ /dev/null
@@ -1,134 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/**
- * Created by obarda on 1/27/2016.
- */
-/// <reference path="../../references"/>
-module Sdc.Directives {
- 'use strict';
-
- export class FileUploadModel {
- filetype: string;
- filename: string;
- filesize: number;
- base64: string;
- }
-
- export interface IFileUploadScope extends ng.IScope {
- fileModel: FileUploadModel;
- formElement:ng.IFormController;
- extensions: string;
- elementDisabled: string;
- elementName: string;
- elementRequired: string;
- myFileModel: any; // From the ng bind to <input type=file
- defaultText: string;
- onFileChangedInDirective:Function;
-
- getExtensionsWithDot():string;
- onFileChange():void
- onFileClick(element:any):void;
- setEmptyError(element):void;
- validateField(field:any):boolean;
- cancel():void;
- }
-
-
- export class FileUploadDirective implements ng.IDirective {
-
- constructor(private $templateCache:ng.ITemplateCacheService, private sdcConfig:Models.IAppConfigurtaion) {
- }
-
- scope = {
- fileModel: '=',
- formElement: '=',
- extensions: '@',
- elementDisabled: '@',
- elementName: '@',
- elementRequired: '@',
- onFileChangedInDirective: '=?',
- defaultText: '=',
- };
-
- restrict = 'E';
- replace = true;
- template = ():string => {
- return this.$templateCache.get('/app/scripts/directives/file-upload/file-upload.html');
- };
-
- link = (scope:IFileUploadScope, element:any, $attr:any) => {
-
- // In case the browse has filename, set it valid.
- // When editing artifact the file is not sent again, so if we have filename I do not want to show error.
- if (scope.fileModel && scope.fileModel.filename && scope.fileModel.filename!==''){
- scope.formElement[scope.elementName].$setValidity('required', true);
- }
-
- scope.getExtensionsWithDot = ():string => {
- let ret = [];
- if(scope.extensions) {
- _.each(scope.extensions.split(','), function (item) {
- ret.push("." + item.toString());
- });
- }
- return ret.join(",");
- };
-
- scope.onFileChange = ():void => {
- if (scope.onFileChangedInDirective) {
- scope.onFileChangedInDirective();
- }
- if (scope.myFileModel) {
- scope.fileModel = scope.myFileModel;
- scope.formElement[scope.elementName].$setValidity('required', true);
- }
- };
-
- scope.setEmptyError = (element):void => {
- if(element.files[0].size){
- scope.formElement[scope.elementName].$setValidity('emptyFile', true);
- }else{
- scope.formElement[scope.elementName].$setValidity('emptyFile', false);
- scope.fileModel = undefined;
- }
-
- };
-
- // Workaround, in case user select a file then cancel (X) then select the file again, the event onChange is not fired.
- // This is a workaround to fix this issue.
- scope.onFileClick = (element:any):void => {
- element.value = null;
- };
-
- scope.cancel = ():void => {
- scope.fileModel.filename = '';
- scope.formElement[scope.elementName].$pristine;
- scope.formElement[scope.elementName].$setValidity('required', false);
- }
- };
-
- public static factory = ($templateCache:ng.ITemplateCacheService, sdcConfig:Models.IAppConfigurtaion)=> {
- return new FileUploadDirective($templateCache, sdcConfig);
- };
-
- }
-
- FileUploadDirective.factory.$inject = ['$templateCache', 'sdcConfig'];
-}
diff --git a/catalog-ui/app/scripts/directives/graphs-v2/common/common-graph-utils.ts b/catalog-ui/app/scripts/directives/graphs-v2/common/common-graph-utils.ts
deleted file mode 100644
index e01e455e93..0000000000
--- a/catalog-ui/app/scripts/directives/graphs-v2/common/common-graph-utils.ts
+++ /dev/null
@@ -1,361 +0,0 @@
-/**
- * Created by obarda on 12/21/2016.
- */
-/**
- * Created by obarda on 12/13/2016.
- */
-/// <reference path="../../../references"/>
-module Sdc.Graph.Utils {
-
- export class CommonGraphUtils {
-
- constructor(private NodesFactory:Sdc.Utils.NodesFactory, private LinksFactory:Sdc.Utils.LinksFactory) {
-
- }
-
- public safeApply = (scope:ng.IScope, fn:any) => { //todo remove to general utils
- let phase = scope.$root.$$phase;
- if (phase == '$apply' || phase == '$digest') {
- if (fn && (typeof(fn) === 'function')) {
- fn();
- }
- } else {
- scope.$apply(fn);
- }
- };
-
- /**
- * Draw node on the graph
- * @param cy
- * @param compositionGraphNode
- * @param position
- * @returns {CollectionElements}
- */
- public addNodeToGraph(cy:Cy.Instance, compositionGraphNode:Models.Graph.CommonNodeBase, position?:Cy.Position):Cy.CollectionElements {
-
- var node = cy.add(<Cy.ElementDefinition> {
- group: 'nodes',
- position: position,
- data: compositionGraphNode,
- classes: compositionGraphNode.classes
- });
-
- 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.
- * If the node is UCPE the function will create all cp lan&wan for the ucpe
- * @param cy
- * @param compositionGraphNode
- * @returns {Cy.CollectionElements}
- */
- public addComponentInstanceNodeToGraph(cy:Cy.Instance, compositionGraphNode:Models.Graph.CompositionCiNodeBase):Cy.CollectionElements {
-
- let nodePosition = {
- x: +compositionGraphNode.componentInstance.posX,
- y: +compositionGraphNode.componentInstance.posY
- };
-
- let node = this.addNodeToGraph(cy, compositionGraphNode, nodePosition);
- if (compositionGraphNode.isUcpe) {
- this.createUcpeCpNodes(cy, node);
- }
- return node;
- };
-
- /**
- * This function will create CP_WAN & CP_LAN for the UCPE. this is a special node on the group that will behave like ports on the ucpe
- * @param cy
- * @param ucpeGraphNode
- */
- private createUcpeCpNodes(cy:Cy.Instance, ucpeGraphNode:Cy.CollectionNodes):void {
-
- let requirementsArray:Array<any> = ucpeGraphNode.data().componentInstance.requirements["tosca.capabilities.Node"];
- //show only LAN or WAN requirements
- requirementsArray = _.reject(requirementsArray, (requirement:any) => {
- let name:string = requirement.ownerName.toLowerCase();
- return name.indexOf('lan') === -1 && name.indexOf('wan') === -1;
- });
- requirementsArray.sort(function (a, b) {
- let nameA = a.ownerName.toLowerCase().match(/[^ ]+/)[0];
- let nameB = b.ownerName.toLowerCase().match(/[^ ]+/)[0];
- let numA = _.last(a.ownerName.toLowerCase().split(' '));
- let numB = _.last(b.ownerName.toLowerCase().split(' '));
-
- if (nameA === nameB) return numA > numB ? 1 : -1;
- return nameA < nameB ? 1 : -1;
- });
- let position = angular.copy(ucpeGraphNode.boundingbox());
- //add CP nodes to group
- let topCps:number = 0;
- for (let i = 0; i < requirementsArray.length; i++) {
-
- let cpNode = this.NodesFactory.createUcpeCpNode(angular.copy(ucpeGraphNode.data().componentInstance));
- cpNode.componentInstance.capabilities = requirementsArray[i];
- cpNode.id = requirementsArray[i].ownerId;
- cpNode.group = ucpeGraphNode.data().componentInstance.uniqueId;
- cpNode.name = requirementsArray[i].ownerName; //for tooltip
- cpNode.displayName = requirementsArray[i].ownerName;
- cpNode.displayName = cpNode.displayName.length > 5 ? cpNode.displayName.substring(0, 5) + '...' : cpNode.displayName;
-
-
- if (cpNode.name.toLowerCase().indexOf('lan') > -1) {
- cpNode.textPosition = "top";
- cpNode.componentInstance.posX = position.x1 + (i * 90) - (topCps * 90) + 53;
- cpNode.componentInstance.posY = position.y1 + 400 + 27;
- } else {
- cpNode.textPosition = "bottom";
- cpNode.componentInstance.posX = position.x1 + (topCps * 90) + 53;
- cpNode.componentInstance.posY = position.y1 + 27;
- topCps++;
- }
- let cyCpNode = this.addComponentInstanceNodeToGraph(cy, cpNode);
- cyCpNode.lock();
- }
- };
-
- /**
- *
- * @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)
- */
- 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;
- }
-
- /**
- * Add link to graph - only draw the link
- * @param cy
- * @param link
- */
- public insertLinkToGraph = (cy:Cy.Instance, link:Models.CompositionCiLinkBase) => {
-
- if (!this.isRelationCertified(cy.nodes(), link.source, link.target)) {
- link.classes = 'not-certified-link';
- }
- cy.add({
- group: 'edges',
- data: link,
- classes: link.classes
- });
-
- };
-
- /**
- * go over the relations and draw links on the graph
- * @param cy
- * @param instancesRelations
- */
- public initGraphLinks(cy:Cy.Instance, instancesRelations:Array<Models.RelationshipModel>) {
-
- if (instancesRelations) {
- _.forEach(instancesRelations, (relationshipModel:Models.RelationshipModel) => {
- _.forEach(relationshipModel.relationships, (relationship:Models.Relationship) => {
- let linkToCreate = this.LinksFactory.createGraphLink(cy, relationshipModel, relationship);
- this.insertLinkToGraph(cy, linkToCreate);
- });
- });
- }
- }
-
- /**
- * Determine which nodes are in the UCPE and set child data for them.
- * @param cy
- */
- public initUcpeChildren(cy:Cy.Instance){
- let ucpe:Cy.CollectionNodes = cy.nodes('[?isUcpe]'); // Get ucpe on graph if exist
- _.each(cy.edges('.ucpe-host-link'), (link)=>{
-
- let ucpeChild:Cy.CollectionNodes = (link.source().id() == ucpe.id())? link.target() : link.source();
- this.initUcpeChildData(ucpeChild, ucpe);
-
- //vls dont have ucpe-host-link connection, so need to find them and iterate separately
- let connectedVLs = ucpeChild.connectedEdges().connectedNodes('.vl-node');
- _.forEach(connectedVLs, (vl)=>{ //all connected vls must be UCPE children because not allowed to connect to a VL outside of the UCPE
- this.initUcpeChildData(vl, ucpe);
- });
- });
- }
-
- /**
- * Set properties for nodes contained by the UCPE
- * @param childNode- node contained in UCPE
- * @param ucpe- ucpe container node
- */
- public initUcpeChildData(childNode:Cy.CollectionNodes, ucpe:Cy.CollectionNodes){
-
- if(!childNode.data('isInsideGroup')){
- this.updateUcpeChildPosition(childNode, ucpe);
- childNode.data({isInsideGroup: true});
- }
-
- }
-
- /**
- * Updates UCPE child node offset, which allows child nodes to be dragged in synchronization with ucpe
- * @param childNode- node contained in UCPE
- * @param ucpe- ucpe container node
- */
- public updateUcpeChildPosition(childNode:Cy.CollectionNodes, ucpe:Cy.CollectionNodes){
- let childPos:Cy.Position = childNode.relativePosition();
- let ucpePos:Cy.Position = ucpe.relativePosition();
- let offset:Cy.Position = {
- x: childPos.x - ucpePos.x,
- y: childPos.y - ucpePos.y
- };
- childNode.data("ucpeOffset", offset);
- }
-
- /**
- * Removes ucpe-child properties from the node
- * @param childNode- node being removed from UCPE
- */
- public removeUcpeChildData(childNode:Cy.CollectionNodes){
- childNode.removeData("ucpeOffset");
- childNode.data({isInsideGroup: false});
-
- }
-
-
- public HTMLCoordsToCytoscapeCoords(cytoscapeBoundingBox:Cy.Extent, mousePos:Cy.Position):Cy.Position {
- return {x: mousePos.x + cytoscapeBoundingBox.x1, y: mousePos.y + cytoscapeBoundingBox.y1}
- };
-
-
- 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;
-
- return this.HTMLCoordsToCytoscapeCoords(cy.extent(), {
- x: x,
- y: y
- });
- };
-
-
- public getNodePosition(node:Cy.CollectionFirstNode):Cy.Position{
- let nodePosition = node.relativePoint();
- if(node.data().isUcpe){ //UCPEs use bounding box and not relative point.
- nodePosition = {x: node.boundingbox().x1, y: node.boundingbox().y1};
- }
-
- return nodePosition;
- }
-
- /**
- * 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;
-
- };
-
-
- /**
- * Check if node node bounds position is inside any ucpe on graph, and return the ucpe
- * @param {diagram} the diagram.
- * @param {nodeActualBounds} the actual bound position of the node.
- * @return the ucpe if found else return null
- */
- public isInUcpe = (cy: Cy.Instance, nodeBounds: Cy.BoundingBox): Cy.CollectionElements => {
-
- let ucpeNodes = cy.nodes('[?isUcpe]').filterFn((ucpeNode) => {
- return this.isFirstBoxContainsInSecondBox(nodeBounds, ucpeNode.boundingbox());
- });
- return ucpeNodes;
- };
-
- /**
- *
- * @param cy
- * @param node
- * @returns {Array}
- */
- public getLinkableNodes(cy:Cy.Instance, node:Cy.CollectionFirstNode):Array<Models.Graph.CompositionCiNodeBase>{
- let compatibleNodes = [];
- _.each(cy.nodes(), (tempNode)=>{
- if(this.nodeLocationsCompatible(cy, node, tempNode)){
- compatibleNodes.push(tempNode.data());
- }
- });
- return compatibleNodes;
- }
-
- /**
- * Checks whether node locations are compatible in reference to UCPEs.
- * Returns true if both nodes are in UCPE or both nodes out, or one node is UCPEpart.
- * @param node1
- * @param node2
- */
- 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; }
-
- 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);
- };
- };
-
-
-
- CommonGraphUtils.$inject = ['NodesFactory', 'LinksFactory'];
-} \ No newline at end of file
diff --git a/catalog-ui/app/scripts/directives/graphs-v2/composition-graph/composition-graph.directive.ts b/catalog-ui/app/scripts/directives/graphs-v2/composition-graph/composition-graph.directive.ts
deleted file mode 100644
index 708f1d091a..0000000000
--- a/catalog-ui/app/scripts/directives/graphs-v2/composition-graph/composition-graph.directive.ts
+++ /dev/null
@@ -1,555 +0,0 @@
-/// <reference path="../../../references"/>
-module Sdc.Directives {
-
- import ComponentFactory = Sdc.Utils.ComponentFactory;
- import LoaderService = Sdc.Services.LoaderService;
- import GRAPH_EVENTS = Sdc.Utils.Constants.GRAPH_EVENTS;
-
- interface ICompositionGraphScope extends ng.IScope {
-
- component:Models.Components.Component;
- isViewOnly:boolean;
- // Link menu - create link menu
- relationMenuDirectiveObj:Models.RelationMenuDirectiveObj;
- isLinkMenuOpen:boolean;
- createLinkFromMenu:(chosenMatch:Models.MatchBase, vl:Models.Components.Component)=>void;
-
- //modify link menu - for now only delete menu
- relationMenuTimeout:ng.IPromise<any>;
- linkMenuObject:Models.LinkMenu;
-
- //left palette functions callbacks
- dropCallback(event:JQueryEventObject, ui:any):void;
- beforeDropCallback(event:IDragDropEvent):void;
- verifyDrop(event:JQueryEventObject, ui:any):void;
-
- //Links menus
- deleteRelation(link:Cy.CollectionEdges):void;
- hideRelationMenu();
- }
-
- export class CompositionGraph implements ng.IDirective {
- private _cy:Cy.Instance;
- private _currentlyCLickedNodePosition:Cy.Position;
- private $document:JQuery = $(document);
- private dragElement:JQuery;
- private dragComponent: Sdc.Models.ComponentsInstances.ComponentInstance;
-
- constructor(private $q:ng.IQService,
- private $filter:ng.IFilterService,
- private $log:ng.ILogService,
- private $timeout:ng.ITimeoutService,
- private NodesFactory:Sdc.Utils.NodesFactory,
- private CompositionGraphLinkUtils:Sdc.Graph.Utils.CompositionGraphLinkUtils,
- private GeneralGraphUtils:Graph.Utils.CompositionGraphGeneralUtils,
- private ComponentInstanceFactory:Utils.ComponentInstanceFactory,
- private NodesGraphUtils:Sdc.Graph.Utils.CompositionGraphNodesUtils,
- private eventListenerService:Services.EventListenerService,
- private ComponentFactory:ComponentFactory,
- private LoaderService:LoaderService,
- private commonGraphUtils:Graph.Utils.CommonGraphUtils,
- private matchCapabilitiesRequirementsUtils:Graph.Utils.MatchCapabilitiesRequirementsUtils) {
-
- }
-
- restrict = 'E';
- templateUrl = '/app/scripts/directives/graphs-v2/composition-graph/composition-graph.html';
- scope = {
- component: '=',
- isViewOnly: '='
- };
-
- link = (scope:ICompositionGraphScope, el:JQuery) => {
- this.loadGraph(scope, el);
-
- scope.$on('$destroy', () => {
- this._cy.destroy();
- _.forEach(GRAPH_EVENTS, (event) => {
- this.eventListenerService.unRegisterObserver(event);
- });
- });
-
- };
-
- private loadGraph = (scope:ICompositionGraphScope, el:JQuery) => {
-
-
- let graphEl = el.find('.sdc-composition-graph-wrapper');
- this.initGraph(graphEl, scope.isViewOnly);
- this.initGraphNodes(scope.component.componentInstances, scope.isViewOnly);
- this.commonGraphUtils.initGraphLinks(this._cy, scope.component.componentInstancesRelations);
- this.commonGraphUtils.initUcpeChildren(this._cy);
- this.initDropZone(scope);
- this.registerCytoscapeGraphEvents(scope);
- this.registerCustomEvents(scope, el);
- this.initViewMode(scope.isViewOnly);
-
- };
-
- private initGraph(graphEl:JQuery, isViewOnly:boolean) {
-
- this._cy = cytoscape({
- container: graphEl,
- style: Sdc.Graph.Utils.ComponentIntanceNodesStyle.getCompositionGraphStyle(),
- zoomingEnabled: false,
- selectionType: 'single',
- boxSelectionEnabled: true,
- autolock: isViewOnly,
- autoungrabify: isViewOnly
- });
- }
-
- private initViewMode(isViewOnly:boolean) {
-
- if (isViewOnly) {
- //remove event listeners
- this._cy.off('drag');
- this._cy.off('handlemouseout');
- this._cy.off('handlemouseover');
- this._cy.edges().unselectify();
- }
- };
-
- private registerCustomEvents(scope:ICompositionGraphScope, el:JQuery) {
-
- this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_PALETTE_COMPONENT_HOVER_IN, (component:Models.DisplayComponent) => {
- this.$log.info(`composition-graph::registerEventServiceEvents:: palette hover on component: ${component.uniqueId}`);
-
- let nodesData = this.NodesGraphUtils.getAllNodesData(this._cy.nodes());
- let nodesLinks = this.GeneralGraphUtils.getAllCompositionCiLinks(this._cy);
-
- if (this.GeneralGraphUtils.componentRequirementsAndCapabilitiesCaching.containsKey(component.uniqueId)) {
- let cacheComponent = this.GeneralGraphUtils.componentRequirementsAndCapabilitiesCaching.getValue(component.uniqueId);
- let filteredNodesData = this.matchCapabilitiesRequirementsUtils.findByMatchingCapabilitiesToRequirements(cacheComponent, nodesData, nodesLinks);
-
- this.matchCapabilitiesRequirementsUtils.highlightMatchingComponents(filteredNodesData, this._cy);
- this.matchCapabilitiesRequirementsUtils.fadeNonMachingComponents(filteredNodesData, nodesData, this._cy);
-
- return;
- }
-
- component.component.updateRequirementsCapabilities()
- .then((res) => {
- component.component.capabilities = res.capabilities;
- component.component.requirements = res.requirements;
-
- let filteredNodesData = this.matchCapabilitiesRequirementsUtils.findByMatchingCapabilitiesToRequirements(component.component, nodesData, nodesLinks);
- this.matchCapabilitiesRequirementsUtils.fadeNonMachingComponents(filteredNodesData, nodesData, this._cy);
- this.matchCapabilitiesRequirementsUtils.highlightMatchingComponents(filteredNodesData, this._cy)
- });
- });
-
- this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_PALETTE_COMPONENT_HOVER_OUT, () => {
- this._cy.emit('hidehandles');
- this.matchCapabilitiesRequirementsUtils.resetFadedNodes(this._cy);
- });
-
- this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_PALETTE_COMPONENT_DRAG_START, (dragElement, dragComponent) => {
-
- this.dragElement = dragElement;
- this.dragComponent = this.ComponentInstanceFactory.createComponentInstanceFromComponent(dragComponent);
- });
-
- this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_PALETTE_COMPONENT_DRAG_ACTION, (event:IDragDropEvent) => {
- this._onComponentDrag(event);
-
- });
-
- this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_COMPONENT_INSTANCE_NAME_CHANGED, (component:Models.ComponentsInstances.ComponentInstance) => {
-
- let selectedNode = this._cy.getElementById(component.uniqueId);
- selectedNode.data().componentInstance.name = component.name;
- selectedNode.data('displayName', selectedNode.data().getDisplayName());
-
- });
-
- this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_DELETE_COMPONENT_INSTANCE, (componentInstance:Models.ComponentsInstances.ComponentInstance) => {
- let nodeToDelete = this._cy.getElementById(componentInstance.uniqueId);
- this.NodesGraphUtils.deleteNode(this._cy, scope.component, nodeToDelete);
- });
-
- this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_DELETE_MULTIPLE_COMPONENTS, () => {
-
- this._cy.$('node:selected').each((i:number, node:Cy.CollectionNodes) => {
- this.NodesGraphUtils.deleteNode(this._cy, scope.component, node);
- });
-
- });
-
- this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_DELETE_EDGE, (releaseLoading:boolean, linksToDelete:Cy.CollectionEdges) => {
- this.CompositionGraphLinkUtils.deleteLink(this._cy, scope.component, releaseLoading, linksToDelete);
- });
-
- this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_INSERT_NODE_TO_UCPE, (node:Cy.CollectionNodes, ucpe:Cy.CollectionNodes, updateExistingNode: boolean) => {
-
- this.commonGraphUtils.initUcpeChildData(node, ucpe);
- //check if item is a VL, and if so, skip adding the binding to ucpe
- if(!(node.data() instanceof Sdc.Models.Graph.CompositionCiNodeVl)){
- this.CompositionGraphLinkUtils.createVfToUcpeLink(scope.component, this._cy, ucpe.data(), node.data()); //create link from the node to the ucpe
- }
-
- if(updateExistingNode){
- let vlsPendingDeletion:Cy.CollectionNodes = this.NodesGraphUtils.deleteNodeVLsUponMoveToOrFromUCPE(scope.component, node.cy(), node); //delete connected VLs that no longer have 2 links
- this.CompositionGraphLinkUtils.deleteLinksWhenNodeMovedFromOrToUCPE(scope.component, node.cy(), node, vlsPendingDeletion); //delete all connected links if needed
- this.GeneralGraphUtils.pushUpdateComponentInstanceActionToQueue(scope.component, true, node.data().componentInstance); //update componentInstance position
- }
-
- });
-
- this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_REMOVE_NODE_FROM_UCPE, (node:Cy.CollectionNodes, ucpe:Cy.CollectionNodes) => {
- this.commonGraphUtils.removeUcpeChildData(node);
- let vlsPendingDeletion:Cy.CollectionNodes = this.NodesGraphUtils.deleteNodeVLsUponMoveToOrFromUCPE(scope.component, node.cy(), node);
- this.CompositionGraphLinkUtils.deleteLinksWhenNodeMovedFromOrToUCPE(scope.component, node.cy(), node, vlsPendingDeletion); //delete all connected links if needed
- this.GeneralGraphUtils.pushUpdateComponentInstanceActionToQueue(scope.component, true, node.data().componentInstance); //update componentInstance position
- });
-
- this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_VERSION_CHANGED, (component:Models.Components.Component) => {
- scope.component = component;
- this.loadGraph(scope, el);
- });
-
-
- scope.createLinkFromMenu = (chosenMatch:Models.MatchBase, vl:Models.Components.Component):void => {
- scope.isLinkMenuOpen = false;
-
- this.CompositionGraphLinkUtils.createLinkFromMenu(this._cy, chosenMatch, vl, scope.component);
- };
-
- scope.hideRelationMenu = () => {
- this.commonGraphUtils.safeApply(scope, () => {
- scope.linkMenuObject = null;
- this.$timeout.cancel(scope.relationMenuTimeout);
- });
- };
-
-
- scope.deleteRelation = (link:Cy.CollectionEdges) => {
- scope.hideRelationMenu();
-
- //if multiple edges selected, delete the VL itself so edges get deleted automatically
- if (this._cy.$('edge:selected').length > 1) {
- this.NodesGraphUtils.deleteNode(this._cy, scope.component, this._cy.$('node:selected'));
- } else {
- this.CompositionGraphLinkUtils.deleteLink(this._cy, scope.component, true, link);
- }
- };
- }
-
-
- private registerCytoscapeGraphEvents(scope:ICompositionGraphScope) {
-
- this._cy.on('addedgemouseup', (event, data) => {
- scope.relationMenuDirectiveObj = this.CompositionGraphLinkUtils.onLinkDrawn(this._cy, data.source, data.target);
- if (scope.relationMenuDirectiveObj != null) {
- scope.$apply(() => {
- scope.isLinkMenuOpen = true;
- });
- }
- });
- this._cy.on('tapstart', 'node', (event:Cy.EventObject) => {
- this._currentlyCLickedNodePosition = angular.copy(event.cyTarget[0].position()); //update node position on drag
- if(event.cyTarget.data().isUcpe){
- this._cy.nodes('.ucpe-cp').unlock();
- event.cyTarget.style('opacity', 0.5);
- }
- });
-
- this._cy.on('drag', 'node', (event:Cy.EventObject) => {
-
- if (event.cyTarget.data().isDraggable) {
- event.cyTarget.style({'overlay-opacity': 0.24});
- if (this.GeneralGraphUtils.isValidDrop(this._cy, event.cyTarget)) {
- event.cyTarget.style({'overlay-color': Utils.Constants.GraphColors.NODE_BACKGROUND_COLOR});
- } else {
- event.cyTarget.style({'overlay-color': Utils.Constants.GraphColors.NODE_OVERLAPPING_BACKGROUND_COLOR});
- }
- }
-
- if(event.cyTarget.data().isUcpe){
- let pos = event.cyTarget.position();
-
- this._cy.nodes('[?isInsideGroup]').positions((i, node)=>{
- return {
- x: pos.x + node.data("ucpeOffset").x,
- y: pos.y + node.data("ucpeOffset").y
- }
- });
- }
- });
-
-
- this._cy.on('handlemouseover', (event, payload) => {
-
- if (payload.node.grabbed()) { //no need to add opacity while we are dragging and hovering othe nodes
- return;
- }
-
- let nodesData = this.NodesGraphUtils.getAllNodesData(this._cy.nodes());
- let nodesLinks = this.GeneralGraphUtils.getAllCompositionCiLinks(this._cy);
-
- let linkableNodes = this.commonGraphUtils.getLinkableNodes(this._cy, payload.node);
- let filteredNodesData = this.matchCapabilitiesRequirementsUtils.findByMatchingCapabilitiesToRequirements(payload.node.data().componentInstance, linkableNodes, nodesLinks);
- this.matchCapabilitiesRequirementsUtils.highlightMatchingComponents(filteredNodesData, this._cy);
- this.matchCapabilitiesRequirementsUtils.fadeNonMachingComponents(filteredNodesData, nodesData, this._cy, payload.node.data());
-
- });
-
- this._cy.on('handlemouseout', () => {
- this._cy.emit('hidehandles');
- this.matchCapabilitiesRequirementsUtils.resetFadedNodes(this._cy);
- });
-
-
- this._cy.on('tapend', (event:Cy.EventObject) => {
-
- 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(Sdc.Utils.Constants.GRAPH_EVENTS.ON_GRAPH_BACKGROUND_CLICKED);
- }
- scope.hideRelationMenu();
- }
-
- else if (event.cyTarget.isEdge()) { //On Edge clicked
- if (scope.isViewOnly) return;
- this.CompositionGraphLinkUtils.handleLinkClick(this._cy, event);
- this.openModifyLinkMenu(scope, this.CompositionGraphLinkUtils.getModifyLinkMenu(event.cyTarget[0], event), 6000);
- }
-
- else { //On Node clicked
- this._cy.nodes(':grabbed').style({'overlay-opacity': 0});
-
- let isUcpe:boolean = event.cyTarget.data().isUcpe;
- let newPosition = event.cyTarget[0].position();
- //node position changed (drop after drag event) - we need to update position
- if (this._currentlyCLickedNodePosition.x !== newPosition.x || this._currentlyCLickedNodePosition.y !== newPosition.y) {
- let nodesMoved:Cy.CollectionNodes = this._cy.$(':grabbed');
- if(isUcpe){
- nodesMoved = nodesMoved.add(this._cy.nodes('[?isInsideGroup]:free')); //'child' nodes will not be recognized as "grabbed" elements within cytoscape. manually add them to collection of nodes moved.
- }
- this.NodesGraphUtils.onNodesPositionChanged(this._cy, scope.component, nodesMoved);
- } else {
- this.$log.debug('composition-graph::onNodeSelectedEvent:: fired');
- scope.$apply(() => {
- this.eventListenerService.notifyObservers(Sdc.Utils.Constants.GRAPH_EVENTS.ON_NODE_SELECTED, event.cyTarget.data().componentInstance);
- });
- }
-
- if(isUcpe){
- this._cy.nodes('.ucpe-cp').lock();
- event.cyTarget.style('opacity', 1);
- }
-
- }
- });
-
- this._cy.on('boxselect', 'node', (event:Cy.EventObject) => {
- this.eventListenerService.notifyObservers(Utils.Constants.GRAPH_EVENTS.ON_NODE_SELECTED, event.cyTarget.data().componentInstance);
- });
- }
-
- private openModifyLinkMenu = (scope:ICompositionGraphScope, linkMenuObject:Models.LinkMenu, timeOutInMilliseconds?:number) => {
-
- this.commonGraphUtils.safeApply(scope, () => {
- scope.linkMenuObject = linkMenuObject;
- });
-
- scope.relationMenuTimeout = this.$timeout(() => {
- scope.hideRelationMenu();
- }, timeOutInMilliseconds ? timeOutInMilliseconds : 6000);
- };
-
- private initGraphNodes(componentInstances:Models.ComponentsInstances.ComponentInstance[], isViewOnly:boolean) {
-
- if (!isViewOnly) { //Init nodes handle extension - enable dynamic links
- setTimeout(()=> {
- let handles = new CytoscapeEdgeEditation;
- handles.init(this._cy, 18);
- handles.registerHandle(Sdc.Graph.Utils.ComponentIntanceNodesStyle.getBasicNodeHanlde());
- handles.registerHandle(Sdc.Graph.Utils.ComponentIntanceNodesStyle.getBasicSmallNodeHandle());
- handles.registerHandle(Sdc.Graph.Utils.ComponentIntanceNodesStyle.getUcpeCpNodeHandle());
- }, 0);
- }
-
- _.each(componentInstances, (instance) => {
- let compositionGraphNode:Models.Graph.CompositionCiNodeBase = this.NodesFactory.createNode(instance);
- this.commonGraphUtils.addComponentInstanceNodeToGraph(this._cy, compositionGraphNode);
- });
-
-
-
- }
-
-
- private initDropZone(scope:ICompositionGraphScope) {
-
- if (scope.isViewOnly) {
- return;
- }
- scope.dropCallback = (event:IDragDropEvent) => {
- this.$log.debug(`composition-graph::dropCallback:: fired`);
- this.addNode(event, scope);
- };
-
- scope.verifyDrop = (event:JQueryEventObject) => {
-
- if(this.dragElement.hasClass('red')){
- return false;
- }
- return true;
- };
-
- scope.beforeDropCallback = (event:IDragDropEvent): ng.IPromise<void> => {
- let deferred: ng.IDeferred<void> = this.$q.defer<void>();
- if(this.dragElement.hasClass('red')){
- deferred.reject();
- } else {
- deferred.resolve();
- }
-
- return deferred.promise;
- }
- }
-
- private _getNodeBBox(event:IDragDropEvent, position?:Cy.Position) {
- let bbox = <Cy.BoundingBox>{};
- if (!position) {
- position = this.commonGraphUtils.getCytoscapeNodePosition(this._cy, event);
- }
- let cushionWidth:number = 40;
- let cushionHeight:number = 40;
-
- bbox.x1 = position.x - cushionWidth / 2;
- bbox.y1 = position.y - cushionHeight / 2;
- bbox.x2 = position.x + cushionWidth / 2;
- bbox.y2 = position.y + cushionHeight / 2;
- return bbox;
- }
-
- private createComponentInstanceOnGraphFromComponent(fullComponent:Models.Components.Component, event:IDragDropEvent, scope:ICompositionGraphScope) {
-
- let componentInstanceToCreate:Models.ComponentsInstances.ComponentInstance = this.ComponentInstanceFactory.createComponentInstanceFromComponent(fullComponent);
- let cytoscapePosition:Cy.Position = this.commonGraphUtils.getCytoscapeNodePosition(this._cy, event);
-
- componentInstanceToCreate.posX = cytoscapePosition.x;
- componentInstanceToCreate.posY = cytoscapePosition.y;
-
-
- let onFailedCreatingInstance:(error:any) => void = (error:any) => {
- this.LoaderService.hideLoader('composition-graph');
- };
-
- //on success - update node data
- let onSuccessCreatingInstance = (createInstance:Models.ComponentsInstances.ComponentInstance):void => {
-
- this.LoaderService.hideLoader('composition-graph');
-
- createInstance.name = this.$filter('resourceName')(createInstance.name);
- createInstance.requirements = new Models.RequirementsGroup(fullComponent.requirements);
- createInstance.capabilities = new Models.CapabilitiesGroup(fullComponent.capabilities);
- createInstance.componentVersion = fullComponent.version;
- createInstance.icon = fullComponent.icon;
- createInstance.setInstanceRC();
-
- let newNode:Models.Graph.CompositionCiNodeBase = this.NodesFactory.createNode(createInstance);
- let cyNode:Cy.CollectionNodes = this.commonGraphUtils.addComponentInstanceNodeToGraph(this._cy, newNode);
-
- //check if node was dropped into a UCPE
- let ucpe:Cy.CollectionElements = this.commonGraphUtils.isInUcpe(this._cy, cyNode.boundingbox());
- if (ucpe.length > 0) {
- this.eventListenerService.notifyObservers(Utils.Constants.GRAPH_EVENTS.ON_INSERT_NODE_TO_UCPE, cyNode, ucpe, false);
- }
-
- };
-
- // Create the component instance on server
- this.GeneralGraphUtils.getGraphUtilsServerUpdateQueue().addBlockingUIAction(() => {
- scope.component.createComponentInstance(componentInstanceToCreate).then(onSuccessCreatingInstance, onFailedCreatingInstance);
- });
- }
-
- private _onComponentDrag(event:IDragDropEvent) {
-
- if(event.clientX < Sdc.Utils.Constants.GraphUIObjects.DIAGRAM_PALETTE_WIDTH_OFFSET || event.clientY < Sdc.Utils.Constants.GraphUIObjects.DIAGRAM_HEADER_OFFSET){ //hovering over palette. Dont bother computing validity of drop
- this.dragElement.removeClass('red');
- return;
- }
-
- let offsetPosition = {x: event.clientX - Sdc.Utils.Constants.GraphUIObjects.DIAGRAM_PALETTE_WIDTH_OFFSET, y: event.clientY - Sdc.Utils.Constants.GraphUIObjects.DIAGRAM_HEADER_OFFSET}
- let bbox = this._getNodeBBox(event, offsetPosition);
-
- if (this.GeneralGraphUtils.isPaletteDropValid(this._cy, bbox, this.dragComponent)) {
- this.dragElement.removeClass('red');
- } else {
- this.dragElement.addClass('red');
- }
- }
-
- private addNode(event:IDragDropEvent, scope:ICompositionGraphScope) {
- this.LoaderService.showLoader('composition-graph');
-
- this.$log.debug('composition-graph::addNode:: fired');
- let draggedComponent:Models.Components.Component = event.dataTransfer.component;
-
- if (this.GeneralGraphUtils.componentRequirementsAndCapabilitiesCaching.containsKey(draggedComponent.uniqueId)) {
- this.$log.debug('composition-graph::addNode:: capabilities found in cache, creating component');
- let fullComponent = this.GeneralGraphUtils.componentRequirementsAndCapabilitiesCaching.getValue(draggedComponent.uniqueId);
- this.createComponentInstanceOnGraphFromComponent(fullComponent, event, scope);
- return;
- }
-
- this.$log.debug('composition-graph::addNode:: capabilities not found, requesting from server');
- this.ComponentFactory.getComponentFromServer(draggedComponent.getComponentSubType(), draggedComponent.uniqueId)
- .then((fullComponent:Models.Components.Component) => {
- this.createComponentInstanceOnGraphFromComponent(fullComponent, event, scope);
- });
- }
-
- public static factory = ($q,
- $filter,
- $log,
- $timeout,
- NodesFactory,
- LinksGraphUtils,
- GeneralGraphUtils,
- ComponentInstanceFactory,
- NodesGraphUtils,
- EventListenerService,
- ComponentFactory,
- LoaderService,
- CommonGraphUtils,
- MatchCapabilitiesRequirementsUtils) => {
- return new CompositionGraph(
- $q,
- $filter,
- $log,
- $timeout,
- NodesFactory,
- LinksGraphUtils,
- GeneralGraphUtils,
- ComponentInstanceFactory,
- NodesGraphUtils,
- EventListenerService,
- ComponentFactory,
- LoaderService,
- CommonGraphUtils,
- MatchCapabilitiesRequirementsUtils);
- }
- }
-
- CompositionGraph.factory.$inject = [
- '$q',
- '$filter',
- '$log',
- '$timeout',
- 'NodesFactory',
- 'CompositionGraphLinkUtils',
- 'CompositionGraphGeneralUtils',
- 'ComponentInstanceFactory',
- 'CompositionGraphNodesUtils',
- 'EventListenerService',
- 'ComponentFactory',
- 'LoaderService',
- 'CommonGraphUtils',
- 'MatchCapabilitiesRequirementsUtils'
- ];
-} \ No newline at end of file
diff --git a/catalog-ui/app/scripts/directives/graphs-v2/composition-graph/utils/composition-graph-general-utils.ts b/catalog-ui/app/scripts/directives/graphs-v2/composition-graph/utils/composition-graph-general-utils.ts
deleted file mode 100644
index 495a243d75..0000000000
--- a/catalog-ui/app/scripts/directives/graphs-v2/composition-graph/utils/composition-graph-general-utils.ts
+++ /dev/null
@@ -1,243 +0,0 @@
-/// <reference path="../../../../references"/>
-module Sdc.Graph.Utils {
-
- import Dictionary = Sdc.Utils.Dictionary;
-
- export class CompositionGraphGeneralUtils {
-
- public componentRequirementsAndCapabilitiesCaching = new Dictionary<string, Models.Components.Component>();
- protected static graphUtilsUpdateQueue: Sdc.Utils.Functions.QueueUtils;
-
- constructor(private $q: ng.IQService,
- private LoaderService: Services.LoaderService,
- private commonGraphUtils: Sdc.Graph.Utils.CommonGraphUtils,
- private matchCapabilitiesRequirementsUtils: Graph.Utils.MatchCapabilitiesRequirementsUtils) {
- CompositionGraphGeneralUtils.graphUtilsUpdateQueue = new Sdc.Utils.Functions.QueueUtils(this.$q);
- }
-
-
- /**
- * Get the offset for the link creation Menu
- * @param point
- * @returns {Cy.Position}
- */
- public calcMenuOffset: Function = (point: Cy.Position): Cy.Position => {
- point.x = point.x + 60;
- point.y = point.y + 105;
- return point;
- };
-
- /**
- * return the top left position of the link menu
- * @param cy
- * @param targetNodePosition
- * @returns {Cy.Position}
- */
- public getLinkMenuPosition = (cy: Cy.Instance, targetNodePosition: Cy.Position) => {
- let menuPosition: Cy.Position = this.calcMenuOffset(targetNodePosition); //get the link mid point
- if (document.body.scrollHeight < menuPosition.y + Sdc.Utils.Constants.GraphUIObjects.LINK_MENU_HEIGHT + $(document.getElementsByClassName('sdc-composition-graph-wrapper')).offset().top) { // if position menu is overflow bottom
- menuPosition.y = document.body.scrollHeight - Sdc.Utils.Constants.GraphUIObjects.TOP_HEADER_HEIGHT - Sdc.Utils.Constants.GraphUIObjects.LINK_MENU_HEIGHT;
- }
- return menuPosition;
- };
-
-
- /**
- * will return true/false if two nodes overlapping
- *
- * @param graph node
- */
- private isNodesOverlapping(node: Cy.CollectionFirstNode, draggedNode: Cy.CollectionFirstNode): boolean {
-
- let nodeBoundingBox: Cy.BoundingBox = node.renderedBoundingBox();
- let secondNodeBoundingBox: Cy.BoundingBox = draggedNode.renderedBoundingBox();
-
- return this.isBBoxOverlapping(nodeBoundingBox, secondNodeBoundingBox);
- }
-
- /**
- * Checks whether the bounding boxes of two nodes are overlapping on any side
- * @param nodeOneBBox
- * @param nodeTwoBBox
- * @returns {boolean}
- */
- private isBBoxOverlapping(nodeOneBBox: Cy.BoundingBox, nodeTwoBBox: Cy.BoundingBox) {
- return (((nodeOneBBox.x1 < nodeTwoBBox.x1 && nodeOneBBox.x2 > nodeTwoBBox.x1) ||
- (nodeOneBBox.x1 < nodeTwoBBox.x2 && nodeOneBBox.x2 > nodeTwoBBox.x2) ||
- (nodeTwoBBox.x1 < nodeOneBBox.x1 && nodeTwoBBox.x2 > nodeOneBBox.x2)) &&
- ((nodeOneBBox.y1 < nodeTwoBBox.y1 && nodeOneBBox.y2 > nodeTwoBBox.y1) ||
- (nodeOneBBox.y1 < nodeTwoBBox.y2 && nodeOneBBox.y2 > nodeTwoBBox.y2) ||
- (nodeTwoBBox.y1 < nodeOneBBox.y1 && nodeTwoBBox.y2 > nodeOneBBox.y2)))
- }
-
-
- /**
- * Checks whether a specific component instance can be hosted on the UCPE instance
- * @param cy - Cytoscape instance
- * @param fromUcpeInstance
- * @param toComponentInstance
- * @returns {Models.MatchReqToCapability}
- */
- public canBeHostedOn(cy: Cy.Instance, fromUcpeInstance: Models.ComponentsInstances.ComponentInstance, toComponentInstance: Models.ComponentsInstances.ComponentInstance): Models.MatchReqToCapability {
-
- let matches: Array<Models.MatchBase> = this.matchCapabilitiesRequirementsUtils.getMatchedRequirementsCapabilities(fromUcpeInstance, toComponentInstance, this.getAllCompositionCiLinks(cy));
- let hostedOnMatch: Models.MatchBase = _.find(matches, (match: Models.MatchReqToCapability) => {
- return match.requirement.capability.toLowerCase() === 'tosca.capabilities.container';
- });
-
- return <Models.MatchReqToCapability>hostedOnMatch;
- };
-
-
- /**
- * Checks whether node can be dropped into UCPE
- * @param cy
- * @param nodeToInsert
- * @param ucpeNode
- * @returns {boolean}
- */
- private isValidDropInsideUCPE(cy: Cy.Instance, nodeToInsert: Models.ComponentsInstances.ComponentInstance, ucpeNode: Models.ComponentsInstances.ComponentInstance): boolean {
-
- let hostedOnMatch: Models.MatchReqToCapability = this.canBeHostedOn(cy, ucpeNode, nodeToInsert);
- let result: boolean = !angular.isUndefined(hostedOnMatch) || nodeToInsert.isVl(); //group validation
- return result;
-
- };
-
-
- /**
- * For drops from palette, checks whether the node can be dropped. If node is being held over another node, check if capable of hosting
- * @param cy
- * @param pseudoNodeBBox
- * @param paletteComponentInstance
- * @returns {boolean}
- */
- public isPaletteDropValid(cy: Cy.Instance, pseudoNodeBBox: Cy.BoundingBox, paletteComponentInstance:Sdc.Models.ComponentsInstances.ComponentInstance) {
-
- let componentIsUCPE:boolean = (paletteComponentInstance.capabilities && paletteComponentInstance.capabilities['tosca.capabilities.Container'] && paletteComponentInstance.name.toLowerCase().indexOf('ucpe') > -1);
-
- if(componentIsUCPE && cy.nodes('[?isUcpe]').length > 0) { //second UCPE not allowed
- return false;
- }
-
- let illegalOverlappingNodes = _.filter(cy.nodes("[isSdcElement]"), (graphNode: Cy.CollectionFirstNode) => {
-
- if(this.isBBoxOverlapping(pseudoNodeBBox, graphNode.renderedBoundingBox())){
- if (!componentIsUCPE && graphNode.data().isUcpe) {
- return !this.isValidDropInsideUCPE(cy, paletteComponentInstance, graphNode.data().componentInstance); //if this is valid insert into ucpe, we return false - no illegal overlapping nodes
- }
- return true;
- }
-
- return false;
- });
-
- return illegalOverlappingNodes.length === 0;
- }
-
- /**
- * will return true/false if a drop of a single node is valid
- *
- * @param graph node
- */
- public isValidDrop(cy: Cy.Instance, draggedNode: Cy.CollectionFirstNode): boolean {
-
- let illegalOverlappingNodes = _.filter(cy.nodes("[isSdcElement]"), (graphNode: Cy.CollectionFirstNode) => { //all sdc nodes, removing child nodes (childe node allways collaps
-
- if (draggedNode.data().isUcpe && (graphNode.isChild() || graphNode.data().isInsideGroup)) { //ucpe cps always inside ucpe, no overlapping
- return false;
- }
- if(draggedNode.data().isInsideGroup && (!draggedNode.active() || graphNode.data().isUcpe)) {
- return false;
- }
-
- if (!draggedNode.data().isUcpe && !(draggedNode.data() instanceof Sdc.Models.Graph.CompositionCiNodeUcpeCp) && graphNode.data().isUcpe) { //case we are dragging a node into UCPE
- let isEntirelyInUCPE:boolean = this.commonGraphUtils.isFirstBoxContainsInSecondBox(draggedNode.renderedBoundingBox(), graphNode.renderedBoundingBox());
- if (isEntirelyInUCPE){
- if(this.isValidDropInsideUCPE(cy, draggedNode.data().componentInstance, graphNode.data().componentInstance)){ //if this is valid insert into ucpe, we return false - no illegal overlapping nodes
- return false;
- }
- }
- }
- return graphNode.data().id !== draggedNode.data().id && this.isNodesOverlapping(draggedNode, graphNode);
-
- });
- // return false;
- return illegalOverlappingNodes.length === 0;
- };
-
- /**
- * will return true/false if the move of the nodes is valid (no node overlapping and verifying if insert into UCPE is valid)
- *
- * @param nodesArray - the selected drags nodes
- */
- public isGroupValidDrop(cy: Cy.Instance, nodesArray: Cy.CollectionNodes): boolean {
- var filterDraggedNodes = nodesArray.filter('[?isDraggable]');
- let isValidDrop = _.every(filterDraggedNodes, (node: Cy.CollectionFirstNode) => {
- return this.isValidDrop(cy, node);
-
- });
- return isValidDrop;
- };
-
- /**
- * get all links in diagram
- * @param cy
- * @returns {any[]|boolean[]}
- */
- public getAllCompositionCiLinks = (cy: Cy.Instance): Array<Models.CompositionCiLinkBase> => {
- return _.map(cy.edges("[isSdcElement]"), (edge: Cy.CollectionEdges) => {
- return edge.data();
- });
- };
-
-
- /**
- * Get Graph Utils server queue
- * @returns {Sdc.Utils.Functions.QueueUtils}
- */
- public getGraphUtilsServerUpdateQueue(): Sdc.Utils.Functions.QueueUtils {
- return CompositionGraphGeneralUtils.graphUtilsUpdateQueue;
- }
- ;
-
- /**
- *
- * @param blockAction - true/false if this is a block action
- * @param instances
- * @param component
- */
- public pushMultipleUpdateComponentInstancesRequestToQueue = (blockAction: boolean, instances: Array<Models.ComponentsInstances.ComponentInstance>, component: Models.Components.Component): void => {
- if (blockAction) {
- this.getGraphUtilsServerUpdateQueue().addBlockingUIAction(
- () => component.updateMultipleComponentInstances(instances)
- );
- } else {
- this.getGraphUtilsServerUpdateQueue().addNonBlockingUIAction(
- () => component.updateMultipleComponentInstances(instances),
- () => this.LoaderService.hideLoader('composition-graph'));
- }
- };
-
- /**
- * this function will update component instance data
- * @param blockAction - true/false if this is a block action
- * @param updatedInstance
- */
- public pushUpdateComponentInstanceActionToQueue = (component: Models.Components.Component, blockAction: boolean, updatedInstance: Models.ComponentsInstances.ComponentInstance): void => {
-
- if (blockAction) {
- this.LoaderService.showLoader('composition-graph');
- this.getGraphUtilsServerUpdateQueue().addBlockingUIAction(
- () => component.updateComponentInstance(updatedInstance)
- );
- } else {
- this.getGraphUtilsServerUpdateQueue().addNonBlockingUIAction(
- () => component.updateComponentInstance(updatedInstance),
- () => this.LoaderService.hideLoader('composition-graph'));
- }
- };
- }
-
- CompositionGraphGeneralUtils.$inject = ['$q', 'LoaderService', 'CommonGraphUtils', 'MatchCapabilitiesRequirementsUtils'];
-} \ No newline at end of file
diff --git a/catalog-ui/app/scripts/directives/graphs-v2/composition-graph/utils/composition-graph-links-utils.ts b/catalog-ui/app/scripts/directives/graphs-v2/composition-graph/utils/composition-graph-links-utils.ts
deleted file mode 100644
index 602e6b6def..0000000000
--- a/catalog-ui/app/scripts/directives/graphs-v2/composition-graph/utils/composition-graph-links-utils.ts
+++ /dev/null
@@ -1,347 +0,0 @@
-/**
- * Created by obarda on 6/28/2016.
- */
-/// <reference path="../../../../references"/>
-module Sdc.Graph.Utils {
-
- import ImageCreatorService = Sdc.Utils.ImageCreatorService;
- import Module = Sdc.Models.Module;
- export class CompositionGraphLinkUtils {
-
- private p2pVL:Models.Components.Component;
- private mp2mpVL:Models.Components.Component;
-
- constructor(private linksFactory:Sdc.Utils.LinksFactory,
- private loaderService:Services.LoaderService,
- private generalGraphUtils:Sdc.Graph.Utils.CompositionGraphGeneralUtils,
- private leftPaletteLoaderService:Services.Components.LeftPaletteLoaderService,
- private componentInstanceFactory:Sdc.Utils.ComponentInstanceFactory,
- private nodesFactory:Sdc.Utils.NodesFactory,
- private commonGraphUtils: Sdc.Graph.Utils.CommonGraphUtils,
- private matchCapabilitiesRequirementsUtils: Graph.Utils.MatchCapabilitiesRequirementsUtils) {
-
- this.initScopeVls();
-
- }
-
-
- /**
- * Delete the link on server and then remove it from graph
- * @param component
- * @param releaseLoading - true/false release the loader when finished
- * @param link - the link to delete
- */
- public deleteLink = (cy:Cy.Instance, component:Models.Components.Component, releaseLoading:boolean, link:Cy.CollectionEdges) => {
-
- this.loaderService.showLoader('composition-graph');
- let onSuccessDeleteRelation = (response) => {
- cy.remove(link);
- };
-
- if (!releaseLoading) {
- this.generalGraphUtils.getGraphUtilsServerUpdateQueue().addBlockingUIAction(
- () => component.deleteRelation(link.data().relation).then(onSuccessDeleteRelation)
- );
- } else {
- this.generalGraphUtils.getGraphUtilsServerUpdateQueue().addBlockingUIActionWithReleaseCallback(
- () => component.deleteRelation(link.data().relation).then(onSuccessDeleteRelation),
- () => this.loaderService.hideLoader('composition-graph'));
- }
- };
-
- /**
- * create the link on server and than draw it on graph
- * @param link - the link to create
- * @param cy
- * @param component
- */
- public createLink = (link:Models.CompositionCiLinkBase, cy:Cy.Instance, component:Models.Components.Component):void => {
-
- this.loaderService.showLoader('composition-graph');
-
- let onSuccess:(response:Models.RelationshipModel) => void = (relation:Models.RelationshipModel) => {
- link.setRelation(relation);
- this.commonGraphUtils.insertLinkToGraph(cy, link);
- };
-
- link.updateLinkDirection();
-
- this.generalGraphUtils.getGraphUtilsServerUpdateQueue().addBlockingUIActionWithReleaseCallback(
- () => component.createRelation(link.relation).then(onSuccess),
- () => this.loaderService.hideLoader('composition-graph')
- );
- };
-
-
- public initScopeVls = ():void => {
-
- let vls = this.leftPaletteLoaderService.getFullDataComponentList(Sdc.Utils.Constants.ResourceType.VL);
- vls.forEach((item) => {
- let key = _.find(Object.keys(item.capabilities), (key) => {
- return _.includes(key.toLowerCase(), 'linkable');
- });
- let linkable = item.capabilities[key];
- if (linkable) {
- if (linkable[0].maxOccurrences == '2') {
- this.p2pVL = _.find(vls, (component:Models.Components.Component) => {
- return component.uniqueId === item.uniqueId;
- });
-
- } else {//assuming unbounded occurrences
- this.mp2mpVL = _.find(vls, (component:Models.Components.Component) => {
- return component.uniqueId === item.uniqueId;
- });
- }
- }
- });
- };
-
- private setVLlinks = (match:Models.MatchReqToReq, vl:Models.ComponentsInstances.ComponentInstance):Array<Models.RelationshipModel> => {
-
- let relationship1 = new Models.Relationship();
- let relationship2 = new Models.Relationship();
- let newRelationshipModel1 = new Models.RelationshipModel();
- let newRelationshipModel2 = new Models.RelationshipModel();
-
- let capability:Models.Capability = vl.capabilities.findValueByKey('linkable')[0];
- relationship1.setRelationProperties(capability, match.requirement);
- relationship2.setRelationProperties(capability, match.secondRequirement);
-
- newRelationshipModel1.setRelationshipModelParams(match.fromNode, vl.uniqueId, [relationship1]);
- newRelationshipModel2.setRelationshipModelParams(match.toNode, vl.uniqueId, [relationship2]);
-
- return [newRelationshipModel1, newRelationshipModel2];
- };
-
- private createVlinks = (cy:Cy.Instance, component:Models.Components.Component, matchReqToReq:Models.MatchReqToReq, vl:Models.Components.Component):void => {
-
- let componentInstance:Models.ComponentsInstances.ComponentInstance = this.componentInstanceFactory.createComponentInstanceFromComponent(vl);
- let fromNodePosition:Cy.Position = cy.getElementById(matchReqToReq.fromNode).relativePosition();
- let toNodePosition:Cy.Position = cy.getElementById(matchReqToReq.toNode).relativePosition();
- let location:Cy.Position = {
- x: 0.5 * (fromNodePosition.x + toNodePosition.x),
- y: 0.5 * (fromNodePosition.y + toNodePosition.y)
- }
-
- componentInstance.posX = location.x;
- componentInstance.posY = location.y;
-
- let onFailed:(error:any) => void = (error:any) => {
- this.loaderService.hideLoader('composition-graph');
- console.info('onFailed', error);
- };
-
- let onSuccess = (response:Models.ComponentsInstances.ComponentInstance):void => {
-
- console.info('onSuccses', response);
- response.requirements = new Models.RequirementsGroup(vl.requirements);
- response.capabilities = new Models.CapabilitiesGroup(vl.capabilities);
- response.componentVersion = vl.version;
- response.setInstanceRC();
-
- let newLinks = this.setVLlinks(matchReqToReq, response);
- let newNode = this.nodesFactory.createNode(response);
-
- this.commonGraphUtils.addComponentInstanceNodeToGraph(cy, newNode);
-
- _.forEach(newLinks, (link) => {
- let linkObg:Models.CompositionCiLinkBase = this.linksFactory.createGraphLink(cy, link, link.relationships[0]);
- this.createLink(linkObg, cy, component);
- });
- };
- component.createComponentInstance(componentInstance).then(onSuccess, onFailed);
- };
-
- private createSimpleLink = (match:Models.MatchReqToCapability, cy:Cy.Instance, component:Models.Components.Component):void => {
- let newRelation:Models.RelationshipModel = match.matchToRelationModel();
- let linkObg:Models.CompositionCiLinkBase = this.linksFactory.createGraphLink(cy,newRelation, newRelation.relationships[0]);
- this.createLink(linkObg, cy, component);
- };
-
- public createLinkFromMenu = (cy:Cy.Instance, chosenMatch:Models.MatchBase, vl:Models.Components.Component, component:Models.Components.Component):void => {
-
- if (chosenMatch) {
- if (chosenMatch && chosenMatch instanceof Models.MatchReqToReq) {
- this.createVlinks(cy, component, chosenMatch, vl); //TODO orit implement
- }
- if (chosenMatch && chosenMatch instanceof Models.MatchReqToCapability) {
- this.createSimpleLink(chosenMatch, cy, component);
- }
- }
- };
-
-
- /**
- * Filters the matches for UCPE links so that shown requirements and capabilites are only related to the selected ucpe-cp
- * @param fromNode
- * @param toNode
- * @param matchesArray
- * @returns {Array<Models.MatchBase>}
- */
- public filterUcpeLinks(fromNode: Models.Graph.CompositionCiNodeBase, toNode: Models.Graph.CompositionCiNodeBase, matchesArray: Array<Models.MatchBase>): any {
-
- let matchLink: Array<Models.MatchBase>;
-
- if (fromNode.isUcpePart) {
- matchLink = _.filter(matchesArray, (match: Models.MatchBase) => {
- return match.isOwner(fromNode.id);
- });
- }
-
- if (toNode.isUcpePart) {
- matchLink = _.filter(matchesArray, (match: Models.MatchBase) => {
- return match.isOwner(toNode.id);
- });
- }
- return matchLink ? matchLink : matchesArray;
- }
-
-
- /**
- * open the connect link menu if the link drawn is valid - match requirements & capabilities
- * @param cy
- * @param fromNode
- * @param toNode
- * @returns {any}
- */
- public onLinkDrawn(cy:Cy.Instance, fromNode:Cy.CollectionFirstNode, toNode:Cy.CollectionFirstNode):Models.RelationMenuDirectiveObj {
-
- if(!this.commonGraphUtils.nodeLocationsCompatible(cy, fromNode, toNode)){ return null; }
- let linkModel:Array<Models.CompositionCiLinkBase> = this.generalGraphUtils.getAllCompositionCiLinks(cy);
-
- let possibleRelations:Array<Models.MatchBase> = this.matchCapabilitiesRequirementsUtils.getMatchedRequirementsCapabilities(fromNode.data().componentInstance,
- toNode.data().componentInstance, linkModel, this.mp2mpVL); //TODO orit - add p2p and mp2mp
-
- //filter relations found to limit to specific ucpe-cp
- possibleRelations = this.filterUcpeLinks(fromNode.data(), toNode.data(), possibleRelations);
-
- //if found possibleRelations between the nodes we create relation menu directive and open the link menu
- if (possibleRelations.length) {
- let menuPosition = this.generalGraphUtils.getLinkMenuPosition(cy, toNode.renderedPoint());
- return new Models.RelationMenuDirectiveObj(fromNode.data(), toNode.data(), this.mp2mpVL, this.p2pVL, menuPosition, possibleRelations);
- }
- return null;
- };
-
-
- /**
- * when we drag instance in to UCPE or out of UCPE - get all links we need to delete - one node in ucpe and one node outside of ucpe
- * @param node - the node we dragged into or out of the ucpe
- */
- public deleteLinksWhenNodeMovedFromOrToUCPE(component:Models.Components.Component, cy:Cy.Instance, nodeMoved:Cy.CollectionNodes, vlsPendingDeletion?:Cy.CollectionNodes):void {
-
-
- let linksToDelete:Cy.CollectionElements = cy.collection();
- _.forEach(nodeMoved.neighborhood('node'), (neighborNode)=>{
-
- if(neighborNode.data().isUcpePart){ //existing connections to ucpe or ucpe-cp - we want to delete even though nodeLocationsCompatible will technically return true
- linksToDelete = linksToDelete.add(nodeMoved.edgesWith(neighborNode)); // This will delete the ucpe-host-link, or the vl-ucpe-link if nodeMoved is vl
- } else if(!this.commonGraphUtils.nodeLocationsCompatible(cy, nodeMoved, neighborNode)){ //connection to regular node or vl - check if locations are compatible
- if(!vlsPendingDeletion || !vlsPendingDeletion.intersect(neighborNode).length){ //Check if this is a link to a VL pending deletion, to prevent double deletion of between the node moved and vl
- linksToDelete = linksToDelete.add(nodeMoved.edgesWith(neighborNode));
- }
- }
- });
-
-
-
- linksToDelete.each((i, link)=>{
- this.deleteLink(cy, component, false, link);
- });
-
- };
-
-
- /**
- * Creates a hostedOn link between a VF and UCPE
- * @param component
- * @param cy
- * @param ucpeNode
- * @param vfNode
- */
- public createVfToUcpeLink = (component: Models.Components.Component, cy:Cy.Instance, ucpeNode:Models.Graph.NodeUcpe, vfNode:Models.Graph.CompositionCiNodeVf):void => {
- let hostedOnMatch:Models.MatchReqToCapability = this.generalGraphUtils.canBeHostedOn(cy, ucpeNode.componentInstance, vfNode.componentInstance);
- /* create relation */
- let newRelation = new Models.RelationshipModel();
- newRelation.fromNode = ucpeNode.id;
- newRelation.toNode = vfNode.id;
-
- let link:Models.CompositionCiLinkBase = this.linksFactory.createUcpeHostLink(newRelation);
- link.relation = hostedOnMatch.matchToRelationModel();
- this.createLink(link, cy, component);
- };
-
-
- /**
- * Handles click event on links.
- * If one edge selected: do nothing.
- /*Two edges selected - always select all
- /* Three or more edges: first click - select all, secondary click - select single.
- * @param cy
- * @param event
- */
- public handleLinkClick(cy:Cy.Instance, event : Cy.EventObject) {
- if(cy.$('edge:selected').length > 2 && 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);
- }
- }
-
- }
-
-
- /**
- * Calculates the position for the menu that modifies an existing link
- * @param event
- * @param elementWidth
- * @param elementHeight
- * @returns {Sdc.Models.Graph.Point}
- */
- public calculateLinkMenuPosition(event, elementWidth, elementHeight): Sdc.Models.Graph.Point {
- let point: Sdc.Models.Graph.Point = new Sdc.Models.Graph.Point(event.originalEvent.x,event.originalEvent.y);
- if(event.originalEvent.view.screen.height-elementHeight<point.y){
- point.y = event.originalEvent.view.screen.height-elementHeight;
- }
- if(event.originalEvent.view.screen.width-elementWidth<point.x){
- point.x = event.originalEvent.view.screen.width-elementWidth;
- }
- return point;
- };
-
-
- /**
- * Gets the menu that is displayed when you click an existing link.
- * @param link
- * @param event
- * @returns {Models.LinkMenu}
- */
- public getModifyLinkMenu(link:Cy.CollectionFirstEdge, event:Cy.EventObject):Models.LinkMenu{
- let point:Sdc.Models.Graph.Point = this.calculateLinkMenuPosition(event,Sdc.Utils.Constants.GraphUIObjects.MENU_LINK_VL_WIDTH_OFFSET,Sdc.Utils.Constants.GraphUIObjects.MENU_LINK_VL_HEIGHT_OFFSET);
- let menu:Models.LinkMenu = new Models.LinkMenu(point, true, link);
- return menu;
- };
-
- }
-
-
-
- CompositionGraphLinkUtils.$inject = [
- 'LinksFactory',
- 'LoaderService',
- 'CompositionGraphGeneralUtils',
- 'LeftPaletteLoaderService',
- 'ComponentInstanceFactory',
- 'NodesFactory',
- 'CommonGraphUtils',
- 'MatchCapabilitiesRequirementsUtils'
- ];
-} \ No newline at end of file
diff --git a/catalog-ui/app/scripts/directives/graphs-v2/composition-graph/utils/composition-graph-nodes-utils.ts b/catalog-ui/app/scripts/directives/graphs-v2/composition-graph/utils/composition-graph-nodes-utils.ts
deleted file mode 100644
index 95c31d16b1..0000000000
--- a/catalog-ui/app/scripts/directives/graphs-v2/composition-graph/utils/composition-graph-nodes-utils.ts
+++ /dev/null
@@ -1,220 +0,0 @@
-/**
- * Created by obarda on 11/9/2016.
- */
-
-/// <reference path="../../../../references"/>
-module Sdc.Graph.Utils {
-
- export class CompositionGraphNodesUtils {
- constructor(private NodesFactory:Sdc.Utils.NodesFactory, private $log:ng.ILogService,
- private GeneralGraphUtils:Graph.Utils.CompositionGraphGeneralUtils,
- private commonGraphUtils: Sdc.Graph.Utils.CommonGraphUtils,
- private eventListenerService: Services.EventListenerService,
- private loaderService:Services.LoaderService) {
-
- }
-
- /**
- * Returns component instances for all nodes passed in
- * @param nodes - Cy nodes
- * @returns {any[]}
- */
- public getAllNodesData(nodes:Cy.CollectionNodes) {
- return _.map(nodes, (node:Cy.CollectionFirstNode)=> {
- return node.data();
- })
- };
-
- /**
- * Deletes component instances on server and then removes it from the graph as well
- * @param cy
- * @param component
- * @param nodeToDelete
- */
- public deleteNode(cy: Cy.Instance, component:Models.Components.Component, nodeToDelete:Cy.CollectionNodes):void {
-
- this.loaderService.showLoader('composition-graph');
- let onSuccess:(response:Models.ComponentsInstances.ComponentInstance) => void = (response:Models.ComponentsInstances.ComponentInstance) => {
- console.info('onSuccess', response);
-
- //if node to delete is a UCPE, remove all children (except UCPE-CPs) and remove their "hostedOn" links
- if (nodeToDelete.data().isUcpe){
- _.each(cy.nodes('[?isInsideGroup]'), (node)=>{
- this.eventListenerService.notifyObservers(Sdc.Utils.Constants.GRAPH_EVENTS.ON_REMOVE_NODE_FROM_UCPE, node, nodeToDelete);
- });
- }
-
- //check whether the node is connected to any VLs that only have one other connection. If so, delete that VL as well
- if(!(nodeToDelete.data() instanceof Sdc.Models.Graph.CompositionCiNodeVl)){
- let connectedVls:Array<Cy.CollectionFirstNode> = this.getConnectedVlToNode(nodeToDelete);
- this.handleConnectedVlsToDelete(connectedVls);
- }
-
- //update UI
- cy.remove(nodeToDelete);
-
- };
-
- let onFailed:(response:any) => void = (response:any) => {
- console.info('onFailed', response);
- };
-
-
- this.GeneralGraphUtils.getGraphUtilsServerUpdateQueue().addBlockingUIActionWithReleaseCallback(
- () => component.deleteComponentInstance(nodeToDelete.data().componentInstance.uniqueId).then(onSuccess, onFailed),
- () => this.loaderService.hideLoader('composition-graph')
- );
-
- };
-
-
- /**
- * Finds all VLs connected to a single node
- * @param node
- * @returns {Array<Cy.CollectionFirstNode>}
- */
- public getConnectedVlToNode = (node: Cy.CollectionNodes): Array<Cy.CollectionFirstNode> => {
- let connectedVls: Array<Cy.CollectionFirstNode> = new Array<Cy.CollectionFirstNode>();
- _.forEach(node.connectedEdges().connectedNodes(), (node: Cy.CollectionFirstNode) => {
- if (node.data() instanceof Models.Graph.CompositionCiNodeVl) {
- connectedVls.push(node);
- }
- });
- return connectedVls;
- };
-
-
- /**
- * Delete all VLs that have only two connected nodes (this function is called when deleting a node)
- * @param connectedVls
- */
- public handleConnectedVlsToDelete = (connectedVls: Array<Cy.CollectionFirstNode>) => {
- _.forEach(connectedVls, (vlToDelete: Cy.CollectionNodes) => {
-
- if (vlToDelete.connectedEdges().length === 2) { // if vl connected only to 2 nodes need to delete the vl
- this.eventListenerService.notifyObservers(Sdc.Utils.Constants.GRAPH_EVENTS.ON_DELETE_COMPONENT_INSTANCE, vlToDelete.data().componentInstance);
- }
- });
- };
-
-
- /**
- * This function is called when moving a node in or out of UCPE.
- * Deletes all connected VLs that have less than 2 valid connections remaining after the move
- * Returns the collection of vls that are in the process of deletion (async) to prevent duplicate calls while deletion is in progress
- * @param component
- * @param cy
- * @param node - node that was moved in/out of ucpe
- */
- public deleteNodeVLsUponMoveToOrFromUCPE = (component:Models.Components.Component, cy:Cy.Instance, node:Cy.CollectionNodes):Cy.CollectionNodes =>{
- if(node.data() instanceof Models.Graph.CompositionCiNodeVl){ return;}
-
- let connectedVLsToDelete:Cy.CollectionNodes = cy.collection();
- _.forEach(node.neighborhood('node'), (connectedNode) => {
-
- //Find all neighboring nodes that are VLs
- if(connectedNode.data() instanceof Models.Graph.CompositionCiNodeVl){
-
- //check VL's neighbors to see if it has 2 or more nodes whose location is compatible with VL (regardless of whether VL is in or out of UCPE)
- let compatibleNodeCount = 0;
- let vlNeighborhood = connectedNode.neighborhood('node');
- _.forEach(vlNeighborhood, (vlNeighborNode)=>{
- if(this.commonGraphUtils.nodeLocationsCompatible(cy, connectedNode, vlNeighborNode)) {
- compatibleNodeCount ++;
- }
- });
-
- if(compatibleNodeCount < 2) {
- connectedVLsToDelete = connectedVLsToDelete.add(connectedNode);
- }
- }
- });
-
- connectedVLsToDelete.each((i, vlToDelete:Cy.CollectionNodes)=>{
- this.deleteNode(cy, component, vlToDelete);
- });
- return connectedVLsToDelete;
- };
-
- /**
- * This function will update nodes position. if the new position is into or out of ucpe, the node will trigger the ucpe events
- * @param cy
- * @param component
- * @param nodesMoved - the node/multiple nodes now moved by the user
- */
- public onNodesPositionChanged = (cy: Cy.Instance, component:Models.Components.Component, nodesMoved: Cy.CollectionNodes): void => {
-
- if (nodesMoved.length === 0) {
- return;
- }
-
- let isValidMove:boolean = this.GeneralGraphUtils.isGroupValidDrop(cy, nodesMoved);
- if (isValidMove) {
-
- this.$log.debug(`composition-graph::ValidDrop:: updating node position`);
- let instancesToUpdateInNonBlockingAction:Array<Models.ComponentsInstances.ComponentInstance> = new Array<Models.ComponentsInstances.ComponentInstance>();
-
- _.each(nodesMoved, (node:Cy.CollectionFirstNode)=> { //update all nodes new position
-
- if(node.data().isUcpePart && !node.data().isUcpe){ return; }//No need to update UCPE-CPs
-
- //update position
- let newPosition:Cy.Position = this.commonGraphUtils.getNodePosition(node);
- node.data().componentInstance.updatePosition(newPosition.x, newPosition.y);
-
- //check if node moved to or from UCPE
- let ucpe = this.commonGraphUtils.isInUcpe(node.cy(), node.boundingbox());
- if(node.data().isInsideGroup || ucpe.length) {
- this.handleUcpeChildMove(node, ucpe, instancesToUpdateInNonBlockingAction);
- } else {
- instancesToUpdateInNonBlockingAction.push(node.data().componentInstance);
- }
-
- });
-
- if (instancesToUpdateInNonBlockingAction.length > 0) {
- this.GeneralGraphUtils.pushMultipleUpdateComponentInstancesRequestToQueue(false, instancesToUpdateInNonBlockingAction, component);
- }
- } else {
- this.$log.debug(`composition-graph::notValidDrop:: node return to latest position`);
- //reset nodes position
- nodesMoved.positions((i, node) => {
- return {
- x: +node.data().componentInstance.posX,
- y: +node.data().componentInstance.posY
- };
- })
- }
-
- this.GeneralGraphUtils.getGraphUtilsServerUpdateQueue().addBlockingUIActionWithReleaseCallback(() => {
- }, () => {
- this.loaderService.hideLoader('composition-graph');
- });
-
- };
-
- /**
- * Checks whether the node has been added or removed from UCPE and triggers appropriate events
- * @param node - node moved
- * @param ucpeContainer - UCPE container that the node has been moved to. When moving a node out of ucpe, param will be empty
- * @param instancesToUpdateInNonBlockingAction
- */
- public handleUcpeChildMove(node:Cy.CollectionFirstNode, ucpeContainer:Cy.CollectionElements, instancesToUpdateInNonBlockingAction:Array<Models.ComponentsInstances.ComponentInstance>){
-
- if(node.data().isInsideGroup){
- if(ucpeContainer.length){ //moving node within UCPE. Simply update position
- this.commonGraphUtils.updateUcpeChildPosition(<Cy.CollectionNodes>node, ucpeContainer);
- instancesToUpdateInNonBlockingAction.push(node.data().componentInstance);
- } else { //removing node from UCPE. Notify observers
- this.eventListenerService.notifyObservers(Sdc.Utils.Constants.GRAPH_EVENTS.ON_REMOVE_NODE_FROM_UCPE, node, ucpeContainer);
- }
- } else if(!node.data().isInsideGroup && ucpeContainer.length && !node.data().isUcpePart){ //adding node to UCPE
- this.eventListenerService.notifyObservers(Sdc.Utils.Constants.GRAPH_EVENTS.ON_INSERT_NODE_TO_UCPE, node, ucpeContainer, true);
- }
- }
-
- }
-
-
- CompositionGraphNodesUtils.$inject = ['NodesFactory', '$log', 'CompositionGraphGeneralUtils', 'CommonGraphUtils', 'EventListenerService', 'LoaderService'];
-} \ No newline at end of file
diff --git a/catalog-ui/app/scripts/directives/graphs-v2/composition-graph/utils/match-capability-requierment-utils.ts b/catalog-ui/app/scripts/directives/graphs-v2/composition-graph/utils/match-capability-requierment-utils.ts
deleted file mode 100644
index 5a401df317..0000000000
--- a/catalog-ui/app/scripts/directives/graphs-v2/composition-graph/utils/match-capability-requierment-utils.ts
+++ /dev/null
@@ -1,265 +0,0 @@
-/**
- * Created by obarda on 1/1/2017.
- */
-/// <reference path="../../../../references"/>
-module Sdc.Graph.Utils {
-
- export class MatchCapabilitiesRequirementsUtils {
-
- constructor() {
- }
-
-
-
- public static linkable(requirement1:Models.Requirement, requirement2:Models.Requirement, vlCapability:Models.Capability):boolean {
- return MatchCapabilitiesRequirementsUtils.isMatch(requirement1, vlCapability) && MatchCapabilitiesRequirementsUtils.isMatch(requirement2, vlCapability);
- };
-
-
- /**
- * Shows + icon in corner of each node passed in
- * @param filteredNodesData
- * @param cy
- */
- public highlightMatchingComponents(filteredNodesData, cy:Cy.Instance) {
- _.each(filteredNodesData, (data:any) => {
- let node = cy.getElementById(data.id);
- cy.emit('showhandle', [node]);
- });
- }
-
- /**
- * Adds opacity to each node that cannot be linked to hovered node
- * @param filteredNodesData
- * @param nodesData
- * @param cy
- * @param hoveredNodeData
- */
- public fadeNonMachingComponents(filteredNodesData, nodesData, cy:Cy.Instance, hoveredNodeData?) {
- let fadeNodes = _.xorWith(nodesData, filteredNodesData, (node1, node2) => {
- return node1.id === node2.id;
- });
- if (hoveredNodeData) {
- _.remove(fadeNodes, hoveredNodeData);
- }
- cy.batch(()=> {
- _.each(fadeNodes, (node) => {
- cy.getElementById(node.id).style({'background-image-opacity': 0.4});
- });
- })
- }
-
- /**
- * Resets all nodes to regular opacity
- * @param cy
- */
- public resetFadedNodes(cy:Cy.Instance) {
- cy.batch(()=> {
- cy.nodes().style({'background-image-opacity': 1});
- })
- }
-
- // -------------------------------------------ALL FUNCTIONS NEED REFACTORING---------------------------------------------------------------//
-
- private static requirementFulfilled(fromNodeId:string, requirement:any, links:Array<Models.CompositionCiLinkBase>):boolean {
- return _.some(links, {
- 'relation': {
- 'fromNode': fromNodeId,
- 'relationships': [{
- 'requirementOwnerId': requirement.ownerId,
- 'requirement': requirement.name,
- 'relationship': {
- 'type': requirement.relationship
- }
- }
- ]
- }
- });
- };
-
- private static isMatch(requirement:Models.Requirement, capability:Models.Capability):boolean {
- if (capability.type === requirement.capability) {
- if (requirement.node) {
- if (_.includes(capability.capabilitySources, requirement.node)) {
- return true;
- }
- } else {
- return true;
- }
- }
- return false;
- };
-
- private getFromToMatches(requirements1:Models.RequirementsGroup,
- requirements2:Models.RequirementsGroup,
- capabilities:Models.CapabilitiesGroup,
- links:Array<Models.CompositionCiLinkBase>,
- fromId:string,
- toId:string,
- vlCapability?:Models.Capability):Array<Models.MatchBase> {
- let matches:Array<Models.MatchBase> = new Array<Models.MatchBase>();
- _.forEach(requirements1, (requirementValue:Array<Models.Requirement>, key) => {
- _.forEach(requirementValue, (requirement:Models.Requirement) => {
- if (requirement.name !== "dependency" && !MatchCapabilitiesRequirementsUtils.requirementFulfilled(fromId, requirement, links)) {
- _.forEach(capabilities, (capabilityValue:Array<Models.Capability>, key) => {
- _.forEach(capabilityValue, (capability:Models.Capability) => {
- if (MatchCapabilitiesRequirementsUtils.isMatch(requirement, capability)) {
- let match:Models.MatchReqToCapability = new Models.MatchReqToCapability(requirement, capability, true, fromId, toId);
- matches.push(match);
- }
- });
- });
- if (vlCapability) {
- _.forEach(requirements2, (requirement2Value:Array<Models.Requirement>, key) => {
- _.forEach(requirement2Value, (requirement2:Models.Requirement) => {
- if (!MatchCapabilitiesRequirementsUtils.requirementFulfilled(toId, requirement2, links) && MatchCapabilitiesRequirementsUtils.linkable(requirement, requirement2, vlCapability)) {
- let match:Models.MatchReqToReq = new Models.MatchReqToReq(requirement, requirement2, true, fromId, toId);
- matches.push(match);
- }
- });
- });
- }
- }
- });
- });
- return matches;
- }
-
- private getToFromMatches(requirements:Models.RequirementsGroup, capabilities:Models.CapabilitiesGroup, links:Array<Models.CompositionCiLinkBase>, fromId:string, toId:string):Array<Models.MatchReqToCapability> {
- let matches:Array<Models.MatchReqToCapability> = [];
- _.forEach(requirements, (requirementValue:Array<Models.Requirement>, key) => {
- _.forEach(requirementValue, (requirement:Models.Requirement) => {
- if (requirement.name !== "dependency" && !MatchCapabilitiesRequirementsUtils.requirementFulfilled(toId, requirement, links)) {
- _.forEach(capabilities, (capabilityValue:Array<Models.Capability>, key) => {
- _.forEach(capabilityValue, (capability:Models.Capability) => {
- if (MatchCapabilitiesRequirementsUtils.isMatch(requirement, capability)) {
- let match:Models.MatchReqToCapability = new Models.MatchReqToCapability(requirement, capability, false, toId, fromId);
- matches.push(match);
- }
- });
- });
- }
- });
- });
- return matches;
- }
-
- public getMatchedRequirementsCapabilities(fromComponentInstance:Models.ComponentsInstances.ComponentInstance,
- toComponentInstance:Models.ComponentsInstances.ComponentInstance,
- links:Array<Models.CompositionCiLinkBase>,
- vl?:Models.Components.Component):Array<Models.MatchBase> {//TODO allow for VL array
- let linkCapability;
- if (vl) {
- let linkCapabilities:Array<Models.Capability> = vl.capabilities.findValueByKey('linkable');
- if (linkCapabilities) {
- linkCapability = linkCapabilities[0];
- }
- }
- let fromToMatches:Array<Models.MatchBase> = this.getFromToMatches(fromComponentInstance.requirements,
- toComponentInstance.requirements,
- toComponentInstance.capabilities,
- links,
- fromComponentInstance.uniqueId,
- toComponentInstance.uniqueId,
- linkCapability);
- let toFromMatches:Array<Models.MatchReqToCapability> = this.getToFromMatches(toComponentInstance.requirements,
- fromComponentInstance.capabilities,
- links,
- fromComponentInstance.uniqueId,
- toComponentInstance.uniqueId);
-
- return fromToMatches.concat(toFromMatches);
- }
-
-
-
-
-
- /**
- * Step I: Check if capabilities of component match requirements of nodeDataArray
- * 1. Get component capabilities and loop on each capability
- * 2. Inside the loop, perform another loop on all nodeDataArray, and fetch the requirements for each one
- * 3. Loop on the requirements, and verify match (see in code the rules)
- *
- * Step II: Check if requirements of component match capabilities of nodeDataArray
- * 1. Get component requirements and loop on each requirement
- * 2.
- *
- * @param component - this is the hovered resource of the left panel of composition screen
- * @param nodeDataArray - Array of resource instances that are on the canvas
- * @param links -getMatchedRequirementsCapabilities
- * @param vl -
- * @returns {any[]|T[]}
- */
- public findByMatchingCapabilitiesToRequirements(component:Models.Components.Component,
- nodeDataArray:Array<Models.Graph.CompositionCiNodeBase>,
- links:Array<Models.CompositionCiLinkBase>,
- vl?:Models.Components.Component):Array<any> {//TODO allow for VL array
- let res = [];
-
- // STEP I
- {
- let capabilities:any = component.capabilities;
- _.forEach(capabilities, (capabilityValue:Array<any>, capabilityKey)=> {
- _.forEach(capabilityValue, (capability)=> {
- _.forEach(nodeDataArray, (node:Models.Graph.CompositionCiNodeBase)=> {
- if (node && node.componentInstance) {
- let requirements:any = node.componentInstance.requirements;
- let fromNodeId:string = node.componentInstance.uniqueId;
- _.forEach(requirements, (requirementValue:Array<any>, requirementKey)=> {
- _.forEach(requirementValue, (requirement)=> {
- if (requirement.name !== "dependency" && MatchCapabilitiesRequirementsUtils.isMatch(requirement, capability)
- && !MatchCapabilitiesRequirementsUtils.requirementFulfilled(fromNodeId, requirement, links)) {
- res.push(node);
- }
- });
- });
- }
- });
- });
- });
- }
-
- // STEP II
- {
- let requirements:any = component.requirements;
- let fromNodeId:string = component.uniqueId;
- let linkCapability:Array<Models.Capability> = vl ? vl.capabilities.findValueByKey('linkable') : undefined;
-
- _.forEach(requirements, (requirementValue:Array<any>, requirementKey)=> {
- _.forEach(requirementValue, (requirement)=> {
- if (requirement.name !== "dependency" && !MatchCapabilitiesRequirementsUtils.requirementFulfilled(fromNodeId, requirement, links)) {
- _.forEach(nodeDataArray, (node:any)=> {
- if (node && node.componentInstance && node.category !== 'groupCp') {
- let capabilities:any = node.componentInstance.capabilities;
- _.forEach(capabilities, (capabilityValue:Array<any>, capabilityKey)=> {
- _.forEach(capabilityValue, (capability)=> {
- if (MatchCapabilitiesRequirementsUtils.isMatch(requirement, capability)) {
- res.push(node);
- }
- });
- });
- if (linkCapability) {
- let linkRequirements = node.componentInstance.requirements;
- _.forEach(linkRequirements, (value:Array<any>, key)=> {
- _.forEach(value, (linkRequirement)=> {
- if (!MatchCapabilitiesRequirementsUtils.requirementFulfilled(node.componentInstance.uniqueId, linkRequirement, links)
- && MatchCapabilitiesRequirementsUtils.linkable(requirement, linkRequirement, linkCapability[0])) {
- res.push(node);
- }
- });
- });
- }
- }
- });
- }
- });
- });
- }
-
- return _.uniq(res);
- };
- }
-
- MatchCapabilitiesRequirementsUtils.$inject = [];
-} \ No newline at end of file
diff --git a/catalog-ui/app/scripts/directives/graphs-v2/deployment-graph/deployment-graph.directive.ts b/catalog-ui/app/scripts/directives/graphs-v2/deployment-graph/deployment-graph.directive.ts
deleted file mode 100644
index d6d4aef374..0000000000
--- a/catalog-ui/app/scripts/directives/graphs-v2/deployment-graph/deployment-graph.directive.ts
+++ /dev/null
@@ -1,114 +0,0 @@
-/**
- * Created by obarda on 12/19/2016.
- */
-/// <reference path="../../../references"/>
-module Sdc.Directives {
-
- import Util = jasmine.Util;
-
- interface IDeploymentGraphScope extends ng.IScope {
- component:Models.Components.Component;
- }
-
- export class DeploymentGraph implements ng.IDirective {
- private _cy:Cy.Instance;
-
- constructor(private NodesFactory:Utils.NodesFactory, private commonGraphUtils:Graph.Utils.CommonGraphUtils,
- private deploymentGraphGeneralUtils:Graph.Utils.DeploymentGraphGeneralUtils, private ComponentInstanceFactory: Sdc.Utils.ComponentInstanceFactory) {
- }
-
- restrict = 'E';
- templateUrl = '/app/scripts/directives/graphs-v2/deployment-graph/deployment-graph.html';
- scope = {
- component: '=',
- isViewOnly: '='
- };
-
- link = (scope:IDeploymentGraphScope, el:JQuery) => {
- if(scope.component.isResource()) {
- this.loadGraph(scope, el);
- this.registerGraphEvents();
- }
- };
-
-
- public initGraphNodes = (cy:Cy.Instance, component:Models.Components.Component):void => {
- if (component.groups) { // Init module nodes
- _.each(component.groups, (groupModule:Models.Module) => {
- let moduleNode = this.NodesFactory.createModuleNode(groupModule);
- this.commonGraphUtils.addNodeToGraph(cy, moduleNode);
-
- });
- }
- _.each(component.componentInstances, (instance:Models.ComponentsInstances.ComponentInstance) => { // Init component instance nodes
- let componentInstanceNode = this.NodesFactory.createNode(instance);
- componentInstanceNode.parent = this.deploymentGraphGeneralUtils.findInstanceModule(component.groups, instance.uniqueId);
- if (componentInstanceNode.parent) { // we are not drawing instances that are not a part of a module
- this.commonGraphUtils.addComponentInstanceNodeToGraph(cy, componentInstanceNode);
- }
- });
-
- // This is a special functionality to pass the cytoscape default behavior - we can't create Parent module node without children's
- // so we must add an empty dummy child node
- _.each(this._cy.nodes('[?isGroup]'), (moduleNode: Cy.CollectionFirstNode) => {
- if (!moduleNode.isParent()) {
- let dummyInstance = this.ComponentInstanceFactory.createEmptyComponentInstance();
- let componentInstanceNode = this.NodesFactory.createNode(dummyInstance);
- componentInstanceNode.parent = moduleNode.id();
- let dummyNode = this.commonGraphUtils.addNodeToGraph(cy, componentInstanceNode, moduleNode.position());
- dummyNode.addClass('dummy-node');
- }
- })
- };
-
- private registerGraphEvents() {
-
- this._cy.on('afterExpand', (event) => {
- event.cyTarget.qtip({});
- });
-
- this._cy.on('afterCollapse', (event) => {
- this.commonGraphUtils.initNodeTooltip(event.cyTarget);
- });
- }
-
- private loadGraph = (scope:IDeploymentGraphScope, el:JQuery) => {
-
- let graphEl = el.find('.sdc-deployment-graph-wrapper');
- this._cy = cytoscape({
- container: graphEl,
- style: Sdc.Graph.Utils.ComponentIntanceNodesStyle.getCompositionGraphStyle().concat(Sdc.Graph.Utils.ModulesNodesStyle.getModuleGraphStyle()),
- zoomingEnabled: false,
- selectionType: 'single',
-
- });
-
- //adding expand collapse extension
- this._cy.expandCollapse({
- layoutBy: {
- name: "grid",
- animate: true,
- randomize: false,
- fit: true
- },
- fisheye: false,
- undoable: false,
- expandCollapseCueSize: 18,
- expandCueImage: Sdc.Utils.Constants.IMAGE_PATH + '/styles/images/resource-icons/' + 'closeModule.png',
- collapseCueImage: Sdc.Utils.Constants.IMAGE_PATH + '/styles/images/resource-icons/' + 'openModule.png',
- expandCollapseCueSensitivity: 2,
- cueOffset: -20
- });
-
- this.initGraphNodes(this._cy, scope.component); //creating instances nodes
- this.commonGraphUtils.initGraphLinks(this._cy, scope.component.componentInstancesRelations);
- this._cy.collapseAll();
- };
-
- public static factory = (NodesFactory:Utils.NodesFactory, CommonGraphUtils:Graph.Utils.CommonGraphUtils, DeploymentGraphGeneralUtils:Graph.Utils.DeploymentGraphGeneralUtils, ComponentInstanceFactory: Utils.ComponentInstanceFactory) => {
- return new DeploymentGraph(NodesFactory, CommonGraphUtils, DeploymentGraphGeneralUtils, ComponentInstanceFactory)
- }
- }
-
- DeploymentGraph.factory.$inject = ['NodesFactory', 'CommonGraphUtils', 'DeploymentGraphGeneralUtils', 'ComponentInstanceFactory'];
-} \ No newline at end of file
diff --git a/catalog-ui/app/scripts/directives/graphs-v2/deployment-graph/deployment-utils/deployment-graph-general-utils.ts b/catalog-ui/app/scripts/directives/graphs-v2/deployment-graph/deployment-utils/deployment-graph-general-utils.ts
deleted file mode 100644
index 3ad9da56be..0000000000
--- a/catalog-ui/app/scripts/directives/graphs-v2/deployment-graph/deployment-utils/deployment-graph-general-utils.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-/**
- * Created by obarda on 12/21/2016.
- */
-/// <reference path="../../../../references"/>
-module Sdc.Graph.Utils {
-
- export class DeploymentGraphGeneralUtils {
-
- constructor() {
-
- }
-
- public findInstanceModule = (groupsArray:Array<Models.Module>, componentInstanceId:string):string => {
- let parentGroup:Sdc.Models.Module = _.find(groupsArray, (group:Sdc.Models.Module) => {
- return _.find(group.members, (member) => {
- return member === componentInstanceId;
- });
- });
- return parentGroup ? parentGroup.uniqueId : "";
- };
- }
-
- DeploymentGraphGeneralUtils.$inject = [];
-} \ No newline at end of file
diff --git a/catalog-ui/app/scripts/directives/graphs-v2/image-creator/image-creator.service.ts b/catalog-ui/app/scripts/directives/graphs-v2/image-creator/image-creator.service.ts
deleted file mode 100644
index e3b17e163d..0000000000
--- a/catalog-ui/app/scripts/directives/graphs-v2/image-creator/image-creator.service.ts
+++ /dev/null
@@ -1,46 +0,0 @@
-module Sdc.Utils {
- export class ImageCreatorService {
- static '$inject' = ['$q'];
- private _canvas: HTMLCanvasElement;
-
- constructor(private $q: ng.IQService) {
- this._canvas = <HTMLCanvasElement>$('<canvas>')[0];
- this._canvas.setAttribute('style', 'display:none');
-
- let body = document.getElementsByTagName('body')[0];
- body.appendChild(this._canvas);
- }
-
- getImageBase64(imageBaseUri: string, imageLayerUri: string): ng.IPromise<string> {
- let deferred = this.$q.defer();
- let imageBase = new Image();
- let imageLayer = new Image();
- let imagesLoaded = 0;
- let onImageLoaded = () => {
- imagesLoaded++;
-
- if (imagesLoaded < 2) {
- return;
- }
- this._canvas.setAttribute('width', imageBase.width.toString());
- this._canvas.setAttribute('height', imageBase.height.toString());
-
- let canvasCtx = this._canvas.getContext('2d');
- canvasCtx.clearRect(0, 0, this._canvas.width, this._canvas.height);
-
- canvasCtx.drawImage(imageBase, 0, 0, imageBase.width, imageBase.height);
- canvasCtx.drawImage(imageLayer, imageBase.width - imageLayer.width, 0, imageLayer.width, imageLayer.height);
-
- let base64Image = this._canvas.toDataURL();
- deferred.resolve(base64Image);
- };
-
- imageBase.onload = onImageLoaded;
- imageLayer.onload = onImageLoaded;
- imageBase.src = imageBaseUri;
- imageLayer.src = imageLayerUri;
-
- return deferred.promise;
- }
- }
-} \ No newline at end of file
diff --git a/catalog-ui/app/scripts/directives/graphs-v2/palette/palette.directive.ts b/catalog-ui/app/scripts/directives/graphs-v2/palette/palette.directive.ts
deleted file mode 100644
index c00da6d1df..0000000000
--- a/catalog-ui/app/scripts/directives/graphs-v2/palette/palette.directive.ts
+++ /dev/null
@@ -1,327 +0,0 @@
-/// <reference path="../../../references"/>
-
-module Sdc.Directives {
- import Dictionary = Sdc.Utils.Dictionary;
- import GRAPH_EVENTS = Sdc.Utils.Constants.GRAPH_EVENTS;
- import ImageCreatorService = Sdc.Utils.ImageCreatorService;
- interface IPaletteScope {
- components: any;
- currentComponent: any;
- model: any;
- displaySortedCategories: any;
- expandedSection: string;
-
- p2pVL: Models.Components.Component;
- mp2mpVL: Models.Components.Component;
- vlType: string;
- dragElement: JQuery;
- dragbleNode: {
- event: JQueryEventObject,
- components: Models.DisplayComponent,
- ui: any
- }
-
- sectionClick: (section: string)=>void;
- searchComponents: (searchText: string)=>void;
- onMouseOver: (displayComponent: Models.DisplayComponent)=>void;
- onMouseOut: (displayComponent: Models.DisplayComponent)=>void;
- dragStartCallback: (event: JQueryEventObject, ui, displayComponent: Models.DisplayComponent)=>void;
- dragStopCallback: ()=>void;
- onDragCallback: (event:JQueryEventObject) => void;
- setElementTemplate: (e: JQueryEventObject)=>void;
-
- isOnDrag: boolean;
- isDragable: boolean;
- isLoading: boolean;
- isViewOnly: boolean;
- }
-
- export class Palette implements ng.IDirective {
- constructor(private $log: ng.ILogService,
- private LeftPaletteLoaderService,
- private sdcConfig,
- private ComponentFactory,
- private ComponentInstanceFactory: Utils.ComponentInstanceFactory,
- private NodesFactory: Utils.NodesFactory,
- private CompositionGraphGeneralUtils: Graph.Utils.CompositionGraphGeneralUtils,
- private EventListenerService: Services.EventListenerService,
- private sdcMenu: Models.IAppMenu) {
-
- }
-
- private fetchingComponentFromServer: boolean = false;
- private nodeHtmlSubstitute: JQuery;
-
- scope = {
- components: '=',
- currentComponent: '=',
- isViewOnly: '=',
- isLoading: '='
- };
- restrict = 'E';
- templateUrl = '/app/scripts/directives/graphs-v2/palette/palette.html';
-
- link = (scope: IPaletteScope, el: JQuery) => {
- this.nodeHtmlSubstitute = $('<div class="node-substitute"><span></span><img /></div>');
- el.append(this.nodeHtmlSubstitute);
-
- this.initComponents(scope);
- this.initScopeVls(scope);
- this.initEvents(scope);
- this.initDragEvents(scope);
- this._initExpandedSection(scope, '');
- };
-
- private leftPanelResourceFilter(resourcesNotAbstract: Array<Models.DisplayComponent>, resourceFilterTypes: Array<string>): Array<Models.DisplayComponent> {
- let filterResources = _.filter(resourcesNotAbstract, (component) => {
- return resourceFilterTypes.indexOf(component.getComponentSubType()) > -1;
- });
- return filterResources;
- }
-
- private initLeftPanel(leftPanelComponents: Array<Models.DisplayComponent>, resourceFilterTypes: Array<string>): Models.LeftPanelModel {
- let leftPanelModel = new Models.LeftPanelModel();
-
- if (resourceFilterTypes && resourceFilterTypes.length) {
- leftPanelComponents = this.leftPanelResourceFilter(leftPanelComponents, resourceFilterTypes);
- }
- leftPanelModel.numberOfElements = leftPanelComponents && leftPanelComponents.length || 0;
-
- if (leftPanelComponents && leftPanelComponents.length) {
-
- let categories: any = _.groupBy(leftPanelComponents, 'mainCategory');
- for (let category in categories)
- categories[category] = _.groupBy(categories[category], 'subCategory');
-
- leftPanelModel.sortedCategories = categories;
- }
- return leftPanelModel;
- }
-
- private initScopeVls(scope: IPaletteScope): void {
- let vls = this.LeftPaletteLoaderService.getFullDataComponentList(Utils.Constants.ResourceType.VL);
- scope.vlType = null;
- vls.forEach((item) => {
- let key = _.find(Object.keys(item.capabilities), (key) => {
- return _.includes(key.toLowerCase(), 'linkable');
- });
- let linkable = item.capabilities[key];
- if (linkable) {
- if (linkable[0].maxOccurrences == '2') {
- scope.p2pVL = _.find(vls, (component: Models.Components.Component) => {
- return component.uniqueId === item.uniqueId;
- });
-
- } else {//assuming unbounded occurrences
- scope.mp2mpVL = _.find(vls, (component: Models.Components.Component) => {
- return component.uniqueId === item.uniqueId;
- });
- }
- }
- });
- };
-
- private initEvents(scope: IPaletteScope) {
- /**
- *
- * @param section
- */
- scope.sectionClick = (section: string) => {
- if (section === scope.expandedSection) {
- scope.expandedSection = '';
- return;
- }
- scope.expandedSection = section;
- };
-
- scope.onMouseOver = (displayComponent: Models.DisplayComponent) => {
- if (scope.isOnDrag) {
- return;
- }
- scope.isOnDrag = true;
-
- this.EventListenerService.notifyObservers(GRAPH_EVENTS.ON_PALETTE_COMPONENT_HOVER_IN, displayComponent);
- this.$log.debug('palette::onMouseOver:: fired');
-
- if (this.CompositionGraphGeneralUtils.componentRequirementsAndCapabilitiesCaching.containsKey(displayComponent.uniqueId)) {
- this.$log.debug(`palette::onMouseOver:: component id ${displayComponent.uniqueId} found in cache`);
- let cacheComponent: Models.Components.Component = this.CompositionGraphGeneralUtils.componentRequirementsAndCapabilitiesCaching.getValue(displayComponent.uniqueId);
-
- //TODO: Danny: fire event to highlight matching nodes
- //showMatchingNodes(cacheComponent);
- return;
- }
-
- this.$log.debug(`palette::onMouseOver:: component id ${displayComponent.uniqueId} not found in cache, initiating server get`);
- // This will bring the component from the server including requirements and capabilities
- // Check that we do not fetch many times, because only in the success we add the component to componentRequirementsAndCapabilitiesCaching
- if (this.fetchingComponentFromServer) {
- return;
- }
-
- this.fetchingComponentFromServer = true;
- this.ComponentFactory.getComponentFromServer(displayComponent.componentSubType, displayComponent.uniqueId)
- .then((component: Models.Components.Component) => {
- this.$log.debug(`palette::onMouseOver:: component id ${displayComponent.uniqueId} fetch success`);
- this.LeftPaletteLoaderService.updateSpecificComponentLeftPalette(component, scope.currentComponent.componentType);
- this.CompositionGraphGeneralUtils.componentRequirementsAndCapabilitiesCaching.setValue(component.uniqueId, component);
- this.fetchingComponentFromServer = false;
-
- //TODO: Danny: fire event to highlight matching nodes
- //showMatchingNodes(component);
- })
- .catch(() => {
- this.$log.debug('palette::onMouseOver:: component id fetch error');
- this.fetchingComponentFromServer = false;
- });
-
-
- };
-
- scope.onMouseOut = () => {
- scope.isOnDrag = false;
- this.EventListenerService.notifyObservers(GRAPH_EVENTS.ON_PALETTE_COMPONENT_HOVER_OUT);
- }
- }
-
- private initComponents(scope: IPaletteScope) {
- scope.searchComponents = (searchText: any): void => {
- scope.displaySortedCategories = this._searchComponents(searchText, scope.model.sortedCategories);
- this._initExpandedSection(scope, searchText);
- };
-
- scope.isDragable = scope.currentComponent.isComplex();
- let entityType: string = scope.currentComponent.componentType.toLowerCase();
- let resourceFilterTypes: Array<string> = this.sdcConfig.resourceTypesFilter[entityType];
-
- scope.components = this.LeftPaletteLoaderService.getLeftPanelComponentsForDisplay(scope.currentComponent.componentType);
- scope.model = this.initLeftPanel(scope.components, resourceFilterTypes);
- scope.displaySortedCategories = angular.copy(scope.model.sortedCategories);
- }
-
- private _initExpandedSection(scope: IPaletteScope, searchText: string): void {
- if (searchText == '') {
- let isContainingCategory: boolean = false;
- let categoryToExpand: string;
- if (scope.currentComponent && scope.currentComponent.categories && scope.currentComponent.categories[0]) {
- categoryToExpand = this.sdcMenu.categoriesDictionary[scope.currentComponent.categories[0].name];
- for (let category in scope.model.sortedCategories) {
- if (categoryToExpand == category) {
- isContainingCategory = true;
- break;
- }
- }
- }
- isContainingCategory ? scope.expandedSection = categoryToExpand : scope.expandedSection = 'Generic';
- }
- else {
- scope.expandedSection = Object.keys(scope.displaySortedCategories).sort()[0];
- }
- };
-
- private initDragEvents(scope: IPaletteScope) {
- scope.dragStartCallback = (event: IDragDropEvent, ui, displayComponent: Models.DisplayComponent): void => {
- if (scope.isLoading || !scope.isDragable || scope.isViewOnly) {
- return;
- }
-
- let component = _.find(this.LeftPaletteLoaderService.getFullDataComponentListWithVls(scope.currentComponent.componentType), (componentFullData: Models.DisplayComponent) => {
- return displayComponent.uniqueId === componentFullData.uniqueId;
- });
- this.EventListenerService.notifyObservers(GRAPH_EVENTS.ON_PALETTE_COMPONENT_DRAG_START, scope.dragElement, component);
-
- scope.isOnDrag = true;
-
-
-
- // this.graphUtils.showMatchingNodes(component, myDiagram, scope.sdcConfig.imagesPath);
- // document.addEventListener('mousemove', moveOnDocument);
- event.dataTransfer.component = component;
- };
-
- scope.dragStopCallback = () => {
- scope.isOnDrag = false;
- };
-
- scope.onDragCallback = (event:IDragDropEvent): void => {
- this.EventListenerService.notifyObservers(GRAPH_EVENTS.ON_PALETTE_COMPONENT_DRAG_ACTION, event);
- };
- scope.setElementTemplate = (e) => {
- let dragComponent: Models.Components.Component = _.find(this.LeftPaletteLoaderService.getFullDataComponentListWithVls(scope.currentComponent.componentType),
- (fullComponent: Models.Components.Component) => {
- return (<any>angular.element(e.currentTarget).scope()).component.uniqueId === fullComponent.uniqueId;
- });
- let componentInstance: Models.ComponentsInstances.ComponentInstance = this.ComponentInstanceFactory.createComponentInstanceFromComponent(dragComponent);
- let node: Models.Graph.CompositionCiNodeBase = this.NodesFactory.createNode(componentInstance);
-
- // myDiagram.dragFromPalette = node;
- this.nodeHtmlSubstitute.find("img").attr('src', node.img);
- scope.dragElement = this.nodeHtmlSubstitute.clone().show();
-
- return scope.dragElement;
- };
- }
-
- private _searchComponents = (searchText: string, categories: any): void => {
- let displaySortedCategories = angular.copy(categories);
- if (searchText != '') {
- angular.forEach(categories, function (category: any, categoryKey) {
-
- angular.forEach(category, function (subcategory: Array<Models.DisplayComponent>, subcategoryKey) {
- let filteredResources = [];
- angular.forEach(subcategory, function (component: Models.DisplayComponent) {
-
- let resourceFilterTerm: string = component.searchFilterTerms;
- if (resourceFilterTerm.indexOf(searchText.toLowerCase()) >= 0) {
- filteredResources.push(component);
- }
- });
- if (filteredResources.length > 0) {
- displaySortedCategories[categoryKey][subcategoryKey] = filteredResources;
- }
- else {
- delete displaySortedCategories[categoryKey][subcategoryKey];
- }
- });
- if (!(Object.keys(displaySortedCategories[categoryKey]).length > 0)) {
- delete displaySortedCategories[categoryKey];
- }
-
- });
- }
- return displaySortedCategories;
- };
-
- public static factory = ($log,
- LeftPaletteLoaderService,
- sdcConfig,
- ComponentFactory,
- ComponentInstanceFactory,
- NodesFactory,
- CompositionGraphGeneralUtils,
- EventListenerService,
- sdcMenu) => {
- return new Palette($log,
- LeftPaletteLoaderService,
- sdcConfig,
- ComponentFactory,
- ComponentInstanceFactory,
- NodesFactory,
- CompositionGraphGeneralUtils,
- EventListenerService,
- sdcMenu);
- };
- }
-
- Palette.factory.$inject = [
- '$log',
- 'LeftPaletteLoaderService',
- 'sdcConfig',
- 'ComponentFactory',
- 'ComponentInstanceFactory',
- 'NodesFactory',
- 'CompositionGraphGeneralUtils',
- 'EventListenerService',
- 'sdcMenu'
- ];
-} \ No newline at end of file
diff --git a/catalog-ui/app/scripts/directives/graphs-v2/relation-menu/relation-menu.ts b/catalog-ui/app/scripts/directives/graphs-v2/relation-menu/relation-menu.ts
deleted file mode 100644
index 22a2d078b7..0000000000
--- a/catalog-ui/app/scripts/directives/graphs-v2/relation-menu/relation-menu.ts
+++ /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=========================================================
- */
-/// <reference path="../../../references"/>
-module Sdc.Directives {
- 'use strict';
-
-
- export interface IRelationMenuScope extends ng.IScope {
- relationMenuDirectiveObj:Models.RelationMenuDirectiveObj;
- createRelation:Function;
- isLinkMenuOpen:boolean;
- hideRelationMatch:Function;
- cancel:Function;
-
- saveRelation();
- showMatch(arr1:Array<Models.MatchBase>, arr2:Array<Models.MatchBase>):boolean;
- hasMatchesToShow(matchesObj:Models.MatchBase, selectedMatch:Array<Models.MatchBase>);
- updateSelectionText():void;
-
- }
-
-
- export class RelationMenuDirective implements ng.IDirective {
-
- constructor(private $templateCache:ng.ITemplateCacheService,
- private $filter:ng.IFilterService
- ) {
- }
-
- scope = {
- relationMenuDirectiveObj: '=',
- isLinkMenuOpen: '=',
- createRelation: '&',
- cancel:'&'
- };
-
- restrict = 'E';
- replace = true;
- template = ():string => {
- return this.$templateCache.get('/app/scripts/directives/graphs-v2/relation-menu/relation-menu.html');
- };
-
- link = (scope:IRelationMenuScope, element:JQuery, $attr:ng.IAttributes) => {
-
- scope.saveRelation = ():void=> {
- let chosenMatches:Array<any> = _.intersection(scope.relationMenuDirectiveObj.rightSideLink.selectedMatch, scope.relationMenuDirectiveObj.leftSideLink.selectedMatch);
- let chosenMatch:Models.MatchBase = chosenMatches[0];
- let chosenVL:Models.Components.Component;
- if ("mptmp" === scope.relationMenuDirectiveObj.vlType) {
- chosenVL = scope.relationMenuDirectiveObj.mp2mpVL;
- } else {
- chosenVL = scope.relationMenuDirectiveObj.p2pVL;
- }
- scope.createRelation()(chosenMatch,chosenVL);
- };
-
-
- scope.hideRelationMatch = () => {
- scope.isLinkMenuOpen = false;
- scope.cancel();
- };
-
- //to show options in link menu
- scope.showMatch = (arr1:Array<Models.MatchBase>, arr2:Array<Models.MatchBase>):boolean => {
- return !arr1 || !arr2 || _.intersection(arr1, arr2).length > 0;
- };
-
- //to show requirements/capabilities title
- scope.hasMatchesToShow = (matchesObj:Models.MatchBase, selectedMatch:Array<Models.MatchBase>):boolean => {
- let result:boolean = false;
- _.forEach(matchesObj, (matchesArr:Array<Models.MatchBase>) => {
- if (!result) {
- result = scope.showMatch(matchesArr, selectedMatch);
- }
- });
- return result;
- };
-
-
- scope.updateSelectionText = ():void => {
- let left:string = scope.relationMenuDirectiveObj.leftSideLink.selectedMatch ? this.$filter('resourceName')(scope.relationMenuDirectiveObj.leftSideLink.selectedMatch[0].getDisplayText('left')) : '';
- let both:string = scope.relationMenuDirectiveObj.leftSideLink.selectedMatch && scope.relationMenuDirectiveObj.rightSideLink.selectedMatch ? ' - ' +
- this.$filter('resourceName')(scope.relationMenuDirectiveObj.leftSideLink.selectedMatch[0].requirement.relationship) + ' - ' : '';
- let right:string = scope.relationMenuDirectiveObj.rightSideLink.selectedMatch ? this.$filter('resourceName')(scope.relationMenuDirectiveObj.rightSideLink.selectedMatch[0].getDisplayText('right')) : '';
- scope.relationMenuDirectiveObj.selectionText = left + both + right;
- };
-
-
- }
- public static factory = ($templateCache:ng.ITemplateCacheService , $filter:ng.IFilterService)=> {
- return new RelationMenuDirective($templateCache, $filter);
- };
- }
-
- RelationMenuDirective.factory.$inject = ['$templateCache', '$filter'];
-}
diff --git a/catalog-ui/app/scripts/directives/info-tooltip/info-tooltip.ts b/catalog-ui/app/scripts/directives/info-tooltip/info-tooltip.ts
deleted file mode 100644
index cd81b14ce8..0000000000
--- a/catalog-ui/app/scripts/directives/info-tooltip/info-tooltip.ts
+++ /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=========================================================
- */
-/**
- * Created by rcohen on 9/25/2016.
- */
-/// <reference path="../../references"/>
-module Sdc.Directives {
- 'use strict';
-
- export interface IInfoTooltipScope extends ng.IScope {
- infoMessageTranslate:string;
- direction:string;
- }
-
-
- export class InfoTooltipDirective implements ng.IDirective {
-
- constructor(private $templateCache:ng.ITemplateCacheService) {
- }
-
- scope = {
- infoMessageTranslate:'@',
- direction:'@'//get 'right' or 'left', the default is 'right'
- };
-
- restrict = 'E';
- replace = true;
- template = ():string => {
- return this.$templateCache.get('/app/scripts/directives/info-tooltip/info-tooltip.html');
- };
-
- link = (scope:IInfoTooltipScope, element:any, $attr:any) => {
- scope.direction = scope.direction || 'right';
- };
-
- public static factory = ($templateCache:ng.ITemplateCacheService)=> {
- return new InfoTooltipDirective($templateCache);
- };
-
- }
-
- InfoTooltipDirective.factory.$inject = ['$templateCache'];
-}
diff --git a/catalog-ui/app/scripts/directives/invalid-characters/invalid-characters.ts b/catalog-ui/app/scripts/directives/invalid-characters/invalid-characters.ts
deleted file mode 100644
index 7ab98b0d23..0000000000
--- a/catalog-ui/app/scripts/directives/invalid-characters/invalid-characters.ts
+++ /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=========================================================
- */
-/// <reference path="../../references"/>
-module Sdc.Directives {
- 'use strict';
-
- export class InvalidCharactersDirective implements ng.IDirective {
-
- constructor() {}
-
- require = 'ngModel';
-
- link = (scope, elem, attrs, ngModel) => {
-
- let invalidCharacters = [];
-
- attrs.$observe('invalidCharacters', (val:string) => {
- invalidCharacters = val.split('');
- validate(ngModel.$viewValue);
- });
-
- let validate: Function = function (value) {
-
- let valid:boolean = true;
-
- if(value) {
- for (let i = 0; i < invalidCharacters.length; i++) {
- if (value.indexOf(invalidCharacters[i]) != - 1) {
- valid = false;
- }
- }
- }
-
- ngModel.$setValidity('invalidCharacters', valid);
- if(!value) {
- ngModel.$setPristine();
- }
- return value;
- };
-
- //For DOM -> model validation
- ngModel.$parsers.unshift(validate);
- //For model -> DOM validation
- ngModel.$formatters.unshift(validate);
-
- };
-
- public static factory = ()=> {
- return new InvalidCharactersDirective();
- };
-
- }
-
- InvalidCharactersDirective.factory.$inject = [];
-}
diff --git a/catalog-ui/app/scripts/directives/layout/top-nav/top-nav.ts b/catalog-ui/app/scripts/directives/layout/top-nav/top-nav.ts
deleted file mode 100644
index 356e43b7f7..0000000000
--- a/catalog-ui/app/scripts/directives/layout/top-nav/top-nav.ts
+++ /dev/null
@@ -1,155 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../../references"/>
-module Sdc.Directives {
- 'use strict';
-
- export interface ITopNavScope extends ng.IScope {
- topLvlSelectedIndex: number;
- hideSearch: boolean;
- searchBind: any;
- menuModel: Array<Utils.MenuItemGroup>;
-
- topLvlMenu: Utils.MenuItemGroup;
- goToState(state:string, params:Array<any>):ng.IPromise<boolean>;
- menuItemClick: Function;
- user: Models.IUserProperties;
- version:string;
- }
-
-
- export class TopNavDirective implements ng.IDirective {
-
- constructor(private $templateCache:ng.ITemplateCacheService,
- private $filter:ng.IFilterService,
- private $state:ng.ui.IStateService,
- private $q: ng.IQService,
- private userResourceService: Sdc.Services.IUserResourceClass
- ) {
- }
-
- public replace = true;
- public restrict = 'E';
- public transclude = false;
-
-
- scope = {
- topLvlSelectedIndex: '@?',
- hideSearch: '=',
- searchBind: '=',
- version: '@',
- notificationIconCallback: '=',
- menuModel: '=?',
- };
-
- template = ():string => {
- return this.$templateCache.get('/app/scripts/directives/layout/top-nav/top-nav.html');
- };
-
- public link = (scope:ITopNavScope, $elem:ng.IAugmentedJQuery, $attrs:angular.IAttributes) => {
-
- let getTopLvlSelectedIndexByState = ():number => {
- if (!scope.topLvlMenu.menuItems) {
- return 0;
- }
-
- let result = -1;
-
- //set result to current state
- scope.topLvlMenu.menuItems.forEach((item:Utils.MenuItem, index:number)=> {
- if (item.state === this.$state.current.name) {
- result = index;
- }
- });
-
- //if it's a different state , checking previous state param
- if (result === -1) {
- scope.topLvlMenu.menuItems.forEach((item:Utils.MenuItem, index:number)=> {
- if (item.state === this.$state.params['previousState']) {
- result = index;
- }
- });
- }
-
- if (result === -1) {
- result = 0;
- }
-
- return result;
- };
-
- scope.user = this.userResourceService.getLoggedinUser();
-
- let tmpArray:Array<Utils.MenuItem> = [
- new Utils.MenuItem(this.$filter('translate')("TOP_MENU_HOME_BUTTON"), null, "dashboard", "goToState", null, null),
- new Utils.MenuItem(this.$filter('translate')("TOP_MENU_CATALOG_BUTTON"), null, "catalog", "goToState", null, null)
- ];
-
- // Only designer can perform onboarding
- if (scope.user && scope.user.role === 'DESIGNER'){
- tmpArray.push(new Utils.MenuItem(this.$filter('translate')("TOP_MENU_ON_BOARD_BUTTON"), null, "onboardVendor", "goToState", null, null));
- }
-
- scope.topLvlMenu = new Utils.MenuItemGroup(0, tmpArray , true );
- scope.topLvlMenu.selectedIndex = isNaN(scope.topLvlSelectedIndex) ? getTopLvlSelectedIndexByState() : scope.topLvlSelectedIndex;
-
- let generateMenu = () => {
- if (scope.menuModel && scope.menuModel[0] !== scope.topLvlMenu) {
- scope.menuModel.unshift(scope.topLvlMenu);
- }
- };
- scope.$watch('menuModel', generateMenu);
-
- generateMenu();
-
- /////scope functions////
-
- scope.goToState = (state:string, params:Array<any>):ng.IPromise<boolean> => {
- let deferred = this.$q.defer();
- this.$state.go(state, params && params.length > 0 ? [0] : undefined);
- deferred.resolve(true);
- return deferred.promise;
- };
-
- scope.menuItemClick = (itemGroup:Utils.MenuItemGroup, item:Utils.MenuItem) => {
-
- itemGroup.itemClick = false;
-
- let onSuccess = ():void => {
- itemGroup.selectedIndex = itemGroup.menuItems.indexOf(item);
- };
- let onFailed = ():void => {};
-
- if (item.callback) {
- (item.callback.apply(undefined, item.params)).then(onSuccess, onFailed);
- } else {
- scope[item.action](item.state, item.params).then(onSuccess, onFailed);
- }
- };
- };
-
- public static factory = ($templateCache:ng.ITemplateCacheService, $filter:ng.IFilterService, $state:ng.ui.IStateService, $q: ng.IQService, userResourceService: Sdc.Services.IUserResourceClass)=> {
- return new TopNavDirective($templateCache, $filter, $state,$q, userResourceService);
- };
-
- }
-
- TopNavDirective.factory.$inject = ['$templateCache', '$filter', '$state','$q', 'Sdc.Services.UserResourceService'];
-}
diff --git a/catalog-ui/app/scripts/directives/layout/top-progress/top-progress.ts b/catalog-ui/app/scripts/directives/layout/top-progress/top-progress.ts
deleted file mode 100644
index 8e8a289281..0000000000
--- a/catalog-ui/app/scripts/directives/layout/top-progress/top-progress.ts
+++ /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=========================================================
- */
-/// <reference path="../../../references"/>
-module Sdc.Directives {
- 'use strict';
-
- export interface ITopProgressScope extends ng.IScope {
- progressValue:number;
- progressMessage:string;
- }
-
- export class TopProgressDirective implements ng.IDirective {
-
- constructor(private $templateCache:ng.ITemplateCacheService) {}
-
- public replace = true;
- public restrict = 'E';
- public transclude = false;
-
- scope = {
- progressValue: '=',
- progressMessage: '='
- };
-
- template = ():string => {
- return this.$templateCache.get('/app/scripts/directives/layout/top-progress/top-progress.html');
- };
-
- public link = (scope:ITopProgressScope, $elem:ng.IAugmentedJQuery, $attrs:angular.IAttributes) => {
-
- };
-
- public static factory = ($templateCache:ng.ITemplateCacheService)=> {
- return new TopProgressDirective($templateCache);
- };
-
- }
-
- TopProgressDirective.factory.$inject = ['$templateCache'];
-}
diff --git a/catalog-ui/app/scripts/directives/loader/loader-directive.ts b/catalog-ui/app/scripts/directives/loader/loader-directive.ts
deleted file mode 100644
index 77c8977ac5..0000000000
--- a/catalog-ui/app/scripts/directives/loader/loader-directive.ts
+++ /dev/null
@@ -1,155 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../references"/>
-module Sdc.Directives {
- 'use strict';
- export interface ILoaderScope extends ng.IScope {
- display: boolean; // Toggle show || hide scroll
- size: string; // small || medium || large
- elementSelector: string; // Jquery selector to hide and scroll inside
- relative: boolean; // Will use the parent of <loader> element and hide it and scroll inside
- loaderType: string;
- }
-
- export class LoaderDirective implements ng.IDirective {
-
- constructor(private $templateCache: ng.ITemplateCacheService, private EventListenerService: Services.EventListenerService) {
- }
-
- /*
- * relative is used when inserting the HTML loader inside some div <loader data-display="isLoading" relative="true"></loader>
- * elementSelector when we want to pass the Jquery selector of the loader.
- */
- scope = {
- display: '=',
- size: '@?',
- elementSelector: '@?',
- relative: '=?',
- loaderType: '@?'
- };
-
- public replace = false;
- public restrict = 'E';
- template = (): string => {
- return this.$templateCache.get('/app/scripts/directives/loader/loader-directive.html');
- };
-
- link = (scope: ILoaderScope, element: any) => {
-
- let interval;
-
- this.EventListenerService.registerObserverCallback(Utils.Constants.EVENTS.SHOW_LOADER_EVENT, (loaderType)=> {
- if (scope.loaderType !== loaderType) {
- return;
- }
- scope.display = true;
- });
- this.EventListenerService.registerObserverCallback(Utils.Constants.EVENTS.HIDE_LOADER_EVENT, (loaderType)=> {
- if (scope.loaderType !== loaderType) {
- return;
- }
- scope.display = false;
- });
-
- let calculateSizesForFixPosition = (positionStyle: string): void => {
- // This is problematic, I do not want to change the parent position.
- // set the loader on all the screen
- let parentPosition = element.parent().position();
- let parentWidth = element.parent().width();
- let parentHeight = element.parent().height();
- element.css('position', positionStyle);
- element.css('top', parentPosition.top);
- element.css('left', parentPosition.left);
- element.css('width', parentWidth);
- element.css('height', parentHeight);
- };
-
- let setStyle = (positionStyle: string): void => {
-
- switch (positionStyle) {
- case 'absolute':
- case 'fixed':
- // The parent size is not set yet, still loading, so need to use interval to update the size.
- interval = window.setInterval(()=> {
- calculateSizesForFixPosition(positionStyle);
- }, 2000);
- break;
- default:
- // Can change the parent position to relative without causing style issues.
- element.parent().css('position', 'relative');
- break;
- }
- };
-
- // This should be executed after the dom loaded
- window.setTimeout((): void => {
-
- element.css('display', 'none');
-
- if (scope.elementSelector) {
- let elemParent = angular.element(scope.elementSelector);
- let positionStyle: string = elemParent.css('position');
- setStyle(positionStyle);
- }
-
- if (scope.relative === true) {
- let positionStyle: string = element.parent().css('position');
- setStyle(positionStyle);
- }
-
- if (!scope.size) {
- scope.size = 'large';
- }
-
- }, 0);
-
- if (scope.elementSelector) {
-
- }
-
- function cleanUp() {
- clearInterval(interval);
- }
-
- scope.$watch("display", (newVal, oldVal) => {
- element.css('display', 'none');
- if (newVal === true) {
- window.setTimeout((): void => {
- element.css('display', 'block');
- }, 500);
- } else {
- window.setTimeout((): void => {
- element.css('display', 'none');
- }, 0);
- }
- });
-
- scope.$on('$destroy', cleanUp);
-
- };
-
- public static factory = ($templateCache: ng.ITemplateCacheService, EventListenerService: Services.EventListenerService)=> {
- return new LoaderDirective($templateCache, EventListenerService);
- };
-
- }
-
- LoaderDirective.factory.$inject = ['$templateCache', 'EventListenerService'];
-}
diff --git a/catalog-ui/app/scripts/directives/modal/sdc-modal.ts b/catalog-ui/app/scripts/directives/modal/sdc-modal.ts
deleted file mode 100644
index 338035c9f1..0000000000
--- a/catalog-ui/app/scripts/directives/modal/sdc-modal.ts
+++ /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=========================================================
- */
-/// <reference path="../../references"/>
-module Sdc.Directives {
- 'use strict';
-
- export interface ISdcModalScope extends ng.IScope {
- modal:ng.ui.bootstrap.IModalServiceInstance;
- hideBackground:string;
- ok():void;
- close(result:any):void;
- cancel(reason:any):void;
- }
-
- export interface ISdcModalButton {
- name:string;
- css:string;
- disabled?:boolean;
- callback:Function;
- }
-
- export class SdcModalDirective implements ng.IDirective {
-
- constructor(
- private $templateCache: ng.ITemplateCacheService
- ) {}
-
- scope = {
- modal: '=',
- type: '@',
- header: '@',
- headerTranslate: '@',
- headerTranslateValues: '@',
- showCloseButton: '@',
- hideBackground: '@',
- buttons: '=',
- getCloseModalResponse: '='
- };
-
- public replace = true;
- public restrict = 'E';
- public transclude = true;
-
- template = (): string => {
- return this.$templateCache.get('/app/scripts/directives/modal/sdc-modal.html');
- };
-
- link = (scope:ISdcModalScope, $elem:any) => {
-
- if (scope.hideBackground==="true"){
- $(".modal-backdrop").css('opacity','0');
- }
-
- scope.close = function (result:any) {
- scope.modal.close(result);
- };
-
- scope.ok = function () {
- scope.modal.close();
- };
-
- scope.cancel = function (reason:any) {
- if(this.getCloseModalResponse)
- scope.modal.dismiss(this.getCloseModalResponse());
- else {
- scope.modal.dismiss();
- }
- };
-
- if (scope.modal) {
- scope.modal.result.then(function (selectedItem) {
- //$scope.selected = selectedItem;
- }, function () {
- //console.info('Modal dismissed at: ' + new Date());
- });
- }
- }
-
- public static factory = ($templateCache: ng.ITemplateCacheService)=> {
- return new SdcModalDirective($templateCache);
- };
-
- }
-
- SdcModalDirective.factory.$inject = ['$templateCache'];
-}
diff --git a/catalog-ui/app/scripts/directives/page-scroller/page-scroller.html b/catalog-ui/app/scripts/directives/page-scroller/page-scroller.html
deleted file mode 100644
index 7359386901..0000000000
--- a/catalog-ui/app/scripts/directives/page-scroller/page-scroller.html
+++ /dev/null
@@ -1,22 +0,0 @@
-<div class="sdc-page-scroller">
-
- <nav data-ng-if="showNav!==false" class="welcome-nav">
- <div data-ng-if="showCloseButton===true" data-ng-click="onCloseButtonClick()" class="asdc-welcome-close"></div>
- <ul>
- <li data-ng-repeat="slide in slidesData | orderBy:'+position'"><a href="#{{slide.id}}" data-ng-click="onNavButtonClick(slide)" class=""></a></li>
- </ul>
- </nav>
-
- <div class="nav-previous-next" data-ng-if="showPreviousNext===true">
- <span class="go-prev" data-ng-click="goToPrevSlide()">previous slide</span>
- <span class="go-next" data-ng-click="goToNextSlide()">next slide</span>
- </div>
-
- <div class="slides-container">
- <section data-ng-repeat="slide in slidesData | orderBy:'+position'" class="slide" id="{{slide.id}}" on-last-repeat>
- <ng-include src="slide.url"></ng-include>
- </section>
- </div>
-
-</div>
-
diff --git a/catalog-ui/app/scripts/directives/page-scroller/page-scroller.less b/catalog-ui/app/scripts/directives/page-scroller/page-scroller.less
deleted file mode 100644
index 14f8568f07..0000000000
--- a/catalog-ui/app/scripts/directives/page-scroller/page-scroller.less
+++ /dev/null
@@ -1,98 +0,0 @@
-.sdc-page-scroller {
-
- /****************** Navigation ***************/
- nav {
- position: fixed;
- top: 0;
- right: 0;
- z-index: 100;
- display: flex;
- flex-direction: column;
- width: 100px;
- bottom: 0;
- background-color: #000;
- align-items: center;
- justify-content: center;
- }
-
- nav ul {
- list-style: none;
- text-align: center;
- margin-top: 0;
- padding: 0;
- }
-
- nav ul li {
- display: block;
- margin-bottom: 15px;
-
- }
-
- nav ul li:last-child {
-
- }
-
- nav a {
- display: block;
- height: 6px;
- width: 6px;
- border-radius: 50%;
- background-color: #4a4c4d;
- }
-
- nav a.active {
- position: relative;
- }
-
- nav a.active::after {
- content: '';
- display: block;
- position: absolute;
- border: 2px solid #0198d1;
- width: 16px;
- height: 16px;
- border-radius: 50%;
- top: -5px;
- left: -5px;
- }
-
- /****************** Previous Next navigation ***************/
- .go-prev, .go-next {
- cursor: pointer;
- font-weight: bold;
- text-decoration: underline;
- }
-
- .slides-container {
- position: absolute;
- left: 0;
- top: 0;
- width: 100%;
- height: 100%;
- overflow-y: hidden;
- z-index: 10;
- }
-
- .slide {
- position: relative;
- width: 100%;
- height: 100%;
- overflow: hidden;
- }
-
- .slide .centered {
- width: 60%;
- margin: 200px auto 0;
- }
-
- .slide .centered h1 {
- text-align: center;
- }
-
- .slide .centered p {
- text-align: center;
- margin-top: 20px;
- font-size: 20px;
- }
-
-}
diff --git a/catalog-ui/app/scripts/directives/page-scroller/page-scroller.ts b/catalog-ui/app/scripts/directives/page-scroller/page-scroller.ts
deleted file mode 100644
index bb89f9a55a..0000000000
--- a/catalog-ui/app/scripts/directives/page-scroller/page-scroller.ts
+++ /dev/null
@@ -1,247 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../references"/>
-module Sdc.Directives {
- 'use strict';
-
- export interface SlideData {
- url: string;
- id: string;
- index: number;
- callback: Function;
- }
-
- export interface ISdcPageScrollDirectiveScope extends ng.IScope {
- slidesData:Array<SlideData>;
- showNav: boolean;
- showPreviousNext: boolean;
- currentSlide:SlideData;
- showCloseButton:boolean;
- closeButtonCallback:Function;
- startSlideIndex:number;
-
- onNavButtonClick(slideName):void;
- onCloseButtonClick():void;
- goToPrevSlide():void;
- goToNextSlide():void;
- goToSlide(slide:SlideData):void;
- onSlideChangeEnd():void;
- onMouseWheel(event):void;
- onKeyDown(event):void;
- onResize(event):void;
- gotoSlideIndex(index):void;
- }
-
- export class SdcPageScrollDirective implements ng.IDirective {
-
- constructor(private $templateCache:ng.ITemplateCacheService) {
-
- }
-
- scope = {
- slidesData: '=',
- showNav: '=',
- showPreviousNext: '=',
- showCloseButton: '=',
- closeButtonCallback: '=',
- startSlideIndex: '=?'
- };
-
- public replace = true;
- public restrict = 'E';
- private delayExec:any;
-
- template = ():string => {
- return this.$templateCache.get('/app/scripts/directives/page-scroller/page-scroller.html');
- };
-
- link = ($scope:ISdcPageScrollDirectiveScope, $elem:JQuery, attr:any) => {
- let isAnimating = false; //Animating flag - is our app animating
- let pageHeight = $(window).innerHeight(); //The height of the window
- let slidesContainer;
- let navButtons;
- let slides:any; //Only graph-links that starts with
-
- //Key codes for up and down arrows on keyboard. We'll be using this to navigate change slides using the keyboard
- let keyCodes = {
- UP : 38,
- DOWN: 40
- };
-
- $scope.onCloseButtonClick = ():void => {
- if ($scope.closeButtonCallback){
- $scope.closeButtonCallback();
- };
- };
-
- // Wait for the dom to load (after ngRepeat).
- $scope.$on('onRepeatLast', (scope, element, attrs) => {
- slides = $(".slide", slidesContainer);
- slidesContainer = $(".slides-container");
- navButtons = $("nav a").filter("[href^='#']");
-
- // Adding event listeners
- $(window).on("resize", (e) => {$scope.onResize(e);}).resize();
- $(window).on("mousewheel DOMMouseScroll", (e) => {$scope.onMouseWheel(e);});
- $(document).on("keydown", (e) => {$scope.onKeyDown(e);});
-
- //Going to the first slide
- if ($scope.startSlideIndex){
- $scope.gotoSlideIndex($scope.startSlideIndex);
- } else {
- $scope.gotoSlideIndex(0);
- }
-
- });
-
- $scope.gotoSlideIndex = (index) => {
- $scope.goToSlide($scope.slidesData[index]);
- };
-
- // When a button is clicked - first get the button href, and then slide to the container, if there's such a container
- $scope.onNavButtonClick = (slide:SlideData):void => {
- $scope.goToSlide(slide);
- };
-
- // If there's a previous slide, slide to it
- $scope.goToPrevSlide = ():void => {
- let previousSlide = $scope.slidesData[$scope.currentSlide.index-1];
- if (previousSlide) {
- $scope.goToSlide(previousSlide);
- }
- };
-
- // If there's a next slide, slide to it
- $scope.goToNextSlide = ():void => {
- let nextSlide = $scope.slidesData[$scope.currentSlide.index+1];
- if (nextSlide) {
- $scope.goToSlide(nextSlide);
- }
- };
-
- // Actual transition between slides
- $scope.goToSlide = (slide:SlideData):void => {
- //console.log("start goToSlide");
- //If the slides are not changing and there's such a slide
- if(!isAnimating && slide) {
- //setting animating flag to true
- isAnimating = true;
- $scope.currentSlide = slide;
- $scope.currentSlide.callback();
-
- //Sliding to current slide
- let calculatedY = pageHeight * ($scope.currentSlide.index);
- //console.log("$scope.currentSlide.index: " + $scope.currentSlide.index + " | calculatedY: " + calculatedY);
-
- $('.slides-container').animate(
- {
- scrollTop: calculatedY + 'px'
- },
- {
- duration: 1000,
- specialEasing: {
- width: "linear",
- height: "easeInOutQuart"
- },
- complete: function() {
- $scope.onSlideChangeEnd();
- }
- }
- );
-
- //Animating menu items
- $(".sdc-page-scroller nav a.active").removeClass("active");
- $(".sdc-page-scroller nav [href='#" + $scope.currentSlide.id + "']").addClass("active");
- }
- };
-
- // Once the sliding is finished, we need to restore "isAnimating" flag.
- // You can also do other things in this function, such as changing page title
- $scope.onSlideChangeEnd = ():void => {
-
-
-
- isAnimating = false;
- };
-
- // When user scrolls with the mouse, we have to change slides
- $scope.onMouseWheel = (event):void => {
- //Normalize event wheel delta
- let delta = event.originalEvent.wheelDelta / 30 || -event.originalEvent.detail;
-
- //If the user scrolled up, it goes to previous slide, otherwise - to next slide
- if(delta < -1) {
- this.delayAction($scope.goToNextSlide);
- } else if(delta > 1) {
- this.delayAction($scope.goToPrevSlide);
- }
- event.preventDefault();
- };
-
- // Getting the pressed key. Only if it's up or down arrow, we go to prev or next slide and prevent default behaviour
- // This way, if there's text input, the user is still able to fill it
- $scope.onKeyDown = (event):void => {
- let PRESSED_KEY = event.keyCode;
-
- if(PRESSED_KEY == keyCodes.UP){
- $scope.goToPrevSlide();
- event.preventDefault();
- } else if(PRESSED_KEY == keyCodes.DOWN){
- $scope.goToNextSlide();
- event.preventDefault();
- }
- };
-
- // When user resize it's browser we need to know the new height, so we can properly align the current slide
- $scope.onResize = (event):void => {
- //This will give us the new height of the window
- let newPageHeight = $(window).innerHeight();
-
- // If the new height is different from the old height ( the browser is resized vertically ), the slides are resized
- if(pageHeight !== newPageHeight) {
- pageHeight = newPageHeight;
- }
- };
- };
-
- private initSlides = ():void => {
- //pageHeight
- };
-
- private delayAction = (action:Function):void => {
- clearTimeout(this.delayExec);
- this.delayExec = setTimeout(function () {
- action();
- }, 100);
- };
-
- public static factory = ($templateCache:ng.ITemplateCacheService)=> {
- return new SdcPageScrollDirective($templateCache);
- };
-
- }
-
- SdcPageScrollDirective.factory.$inject = ['$templateCache'];
-
-}
-
-
-
-
diff --git a/catalog-ui/app/scripts/directives/perfect-scrollbar/angular-perfect-scrollbar.ts b/catalog-ui/app/scripts/directives/perfect-scrollbar/angular-perfect-scrollbar.ts
deleted file mode 100644
index b53a059a40..0000000000
--- a/catalog-ui/app/scripts/directives/perfect-scrollbar/angular-perfect-scrollbar.ts
+++ /dev/null
@@ -1,159 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../references"/>
-module Sdc.Directives {
-
- 'use strict';
-
- export interface IPerfectScrollerScope extends ng.IScope {
- //update(event:string): void;
- }
-
- export class PerfectScrollerDirective implements ng.IDirective {
-
- constructor(
- private $templateCache: ng.ITemplateCacheService,
- private $parse:any,
- private $window:any) {
-
- }
-
- replace = true;
- restrict = 'EA';
- transclude = true;
-
- template = (): string => {
- return '<div><div ng-transclude></div></div>';
- };
-
- link = ($scope:IPerfectScrollerScope, $elem, $attr) => {
- let self = this;
- let options = {};
-
- let psOptions = [
- 'wheelSpeed', 'wheelPropagation', 'minScrollbarLength', 'useBothWheelAxes',
- 'useKeyboard', 'suppressScrollX', 'suppressScrollY', 'scrollXMarginOffset',
- 'scrollYMarginOffset', 'includePadding'//, 'onScroll', 'scrollDown'
- ];
-
- for (let i=0, l=psOptions.length; i<l; i++) {
- let opt = psOptions[i];
- if ($attr[opt] !== undefined) {
- options[opt] = self.$parse($attr[opt])();
- }
- }
-
- $scope.$evalAsync(function() {
- $elem.perfectScrollbar(options);
- let onScrollHandler = self.$parse($attr.onScroll)
- $elem.scroll(function(){
- let scrollTop = $elem.scrollTop()
- let scrollHeight = $elem.prop('scrollHeight') - $elem.height()
- $scope.$apply(function() {
- onScrollHandler($scope, {
- scrollTop: scrollTop,
- scrollHeight: scrollHeight
- })
- })
- });
- });
-
- /*
- $scope.update = (event:string): void => {
- $scope.$evalAsync(function() {
- //if ($attr.scrollDown == 'true' && event != 'mouseenter') {
- if (event != 'mouseenter') {
- setTimeout(function () {
- $($elem).scrollTop($($elem).prop("scrollHeight"));
- }, 100);
- }
- $elem.perfectScrollbar('update');
- });
- };
- */
-
- // This is necessary when you don't watch anything with the scrollbar
- $elem.bind('mouseenter', function(){
- //console.log("mouseenter");
- $elem.perfectScrollbar('update');
- });
-
- $elem.bind('mouseleave', function(){
- //console.log("mouseleave");
- setTimeout(function () {
- $(window).trigger('mouseup');
- $elem.perfectScrollbar('update');
- }, 10);
- });
-
- $elem.bind('click', function(){
- //console.log("click");
- // Wait 500 milliseconds until the collapse finish closing and update.
- setTimeout(function () {
- $elem.perfectScrollbar('update');
- }, 500);
- });
-
- /**
- * Check if the content of the scroller was changed, and if changed update the scroller.
- * Because DOMSubtreeModified event is fire many time (while filling the content), I'm checking that
- * there is at least 100 milliseconds between DOMSubtreeModified events to update the scrollbar.
- * @type {boolean}
- */
- let insideDOMSubtreeModified=false;
- $elem.bind('DOMSubtreeModified', function(){
- if (insideDOMSubtreeModified==false) {
- insideDOMSubtreeModified=true;
- setTimeout(function () {
- insideDOMSubtreeModified=false;
- $elem.perfectScrollbar('update');
- }, 100);
- }
- });
-
- // Possible future improvement - check the type here and use the appropriate watch for non-arrays
- if ($attr.refreshOnChange) {
- $scope.$watchCollection($attr.refreshOnChange, function() {
- $elem.perfectScrollbar('update');
- });
- }
-
- /*
- // this is from a pull request - I am not totally sure what the original issue is but seems harmless
- if ($attr.refreshOnResize) {
- self.$window.on('resize', function(e){$scope.update(e)});
- }
- */
-
- $elem.bind('$destroy', function() {
- //self.$window.off('resize', function(e){$scope.update(e)});
- $elem.perfectScrollbar('destroy');
- });
-
- };
-
- public static factory = ($templateCache: ng.ITemplateCacheService, $parse:any, $window:any)=> {
- return new PerfectScrollerDirective($templateCache, $parse, $window);
- };
-
- }
-
- PerfectScrollerDirective.factory.$inject = ['$templateCache','$parse','$window'];
-}
diff --git a/catalog-ui/app/scripts/directives/print-graph-screen/print-graph-screen.ts b/catalog-ui/app/scripts/directives/print-graph-screen/print-graph-screen.ts
deleted file mode 100644
index 8204928e6f..0000000000
--- a/catalog-ui/app/scripts/directives/print-graph-screen/print-graph-screen.ts
+++ /dev/null
@@ -1,211 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../references"/>
-module Sdc.Directives {
- 'use strict';
-
- export interface IPrintGraphScreenScope extends ng.IScope {
- entity:Models.Components.Component;
- }
-
-
- export class PrintGraphScreenDirective implements ng.IDirective {
-
- constructor(
- private $filter: ng.IFilterService,
- private sdcMenu:Models.IAppMenu,
- private sdcConfig:Models.IAppConfigurtaion,
- private urlToBase64Service:Sdc.Services.UrlToBase64Service
- ) {}
-
- scope = {
- entity: '='
- };
- restrict = 'A';
- link = (scope:IPrintGraphScreenScope, element:any) => {
-
-
- element.bind('click', function() {
- printScreen();
- });
-
-
- // TODO we need to implement export to PDF in cytoscape
- let printScreen = ():void => {
-
- //
- // let pdf :any = new jsPDF('landscape', 'mm', 'a4');
- // pdf.setProperties({
- // title: scope.entity.name,
- // subject: 'Design Snapshot for ' + scope.entity.name,
- // author: scope.entity.creatorFullName,
- // keywords: scope.entity.tags.join(', '),
- // creator: scope.entity.creatorFullName
- // });
- //
- // // A4 measures is 210 × 297 millimeters
- // let pdfWidth :number = 297,
- // pdfHeight :number = 210,
- // leftColumnWidth :number = 80;
- //
- // //left bar background
- // pdf.setDrawColor(0);
- // pdf.setFillColor(248, 249, 251);
- // pdf.rect(0, 0, leftColumnWidth, pdfHeight, 'F');
- //
- // //entity name
- // pdf.setFontSize(12);
- // pdf.setTextColor(38, 61, 77);
- // let splitTitle :any = pdf.splitTextToSize(scope.entity.name, 50);
- // pdf.text(22, 15 - (splitTitle.length - 1) * 2, splitTitle);
- //
- // //line
- // pdf.setLineWidth(0.2);
- // pdf.setDrawColor(208, 209, 213);
- // pdf.line(0, 28, leftColumnWidth, 28);
- //
- //
- // pdf.setFontSize(10);
- // let properties :any = getPdfProperties();
- //
- // let topOffset :number = 39, lines;
- // properties.forEach( (item:any) => {
- // if (!item.value) {
- // return;
- // }
- // if (item.title === 'Description:') {
- // topOffset += 5;
- // }
- //
- // pdf.setTextColor(38, 61, 77);
- // pdf.text(5, topOffset, item.title);
- // pdf.setTextColor(102, 102, 102);
- // lines = pdf.splitTextToSize(item.value, 49);
- // pdf.text(5 + item.offset, topOffset, lines[0]);
- // if (lines.length > 1) {
- // lines = pdf.splitTextToSize(item.value.substring(lines[0].length + 1), 65);
- // if (lines.length > 8) {
- // lines = lines.slice(0, 7);
- // lines[lines.length - 1] += '...';
- // }
- // pdf.text(5, topOffset + 4, lines);
- // topOffset += 4 * (lines.length);
- // }
- //
- // topOffset += 6;
- // });
- //
- //
- // //another background in case the text was too long
- // let declarationLineOffset :number = 176;
- // pdf.setDrawColor(0);
- // pdf.setFillColor(248, 249, 251);
- // pdf.rect(0, declarationLineOffset, leftColumnWidth, pdfHeight - declarationLineOffset, 'F');
- // //line
- // pdf.setLineWidth(0.2);
- // pdf.setDrawColor(208, 209, 213);
- // pdf.line(0, declarationLineOffset, leftColumnWidth, declarationLineOffset);
- //
- // //declaration
- // pdf.setFontSize(10.5);
- // pdf.setTextColor(38, 61, 77);
- // pdf.text(5, 185, 'Declaration');
- // pdf.setFontSize(9);
- // pdf.setTextColor(102, 102, 102);
- // pdf.setFontType('bold');
- // pdf.text(5, 190, this.$filter('translate')('PDF_FILE_DECLARATION_BOLD'));
- // pdf.setFontType('normal');
- // pdf.text(5, 194, pdf.splitTextToSize(this.$filter('translate')('PDF_FILE_DECLARATION'), 65));
- //
- // //entity icon
- // let self = this;
- // let addEntityIcon:Function = () => {
- // let iconPath:string = self.sdcConfig.imagesPath + '/styles/images/';
- // if (scope.entity.isService()) {
- // iconPath += 'service-icons/' + scope.entity.icon + '.png';
- // } else {
- // iconPath += 'resource-icons/' + scope.entity.icon + '.png';
- // }
- // self.urlToBase64Service.downloadUrl(iconPath, (base64string:string):void => {
- // if (base64string) {
- // pdf.addImage(base64string, 'JPEG', 5, 7, 15, 15);
- // }
- // pdf.save(scope.entity.name + '.pdf');
- // });
- // };
- //
- // //actual snapshop of canvas
- //
- // let diagramDiv :any = document.getElementById('myDiagram');
- // let diagram :any = null;// Sdc.Graph.Diagram.fromDiv(diagramDiv), canvasImg = new Image();
- // diagram.startTransaction('print screen');
- // let canvasImgBase64:any = diagram.makeImageData({
- // //scale: 1,
- // // size: new Sdc.Graph.Size(pdfHeight * 5, NaN),
- // background: 'white',
- // type: 'image/jpeg'
- // });
- // diagramDiv.firstElementChild.toDataURL();
- // diagram.commitTransaction('print screen');
- //
- // canvasImg.onload = () => {
- // if (canvasImg.height > 0) {
- // let canvasImgRatio:number = Math.min((pdfWidth - leftColumnWidth - 15) / canvasImg.width, pdfHeight / canvasImg.height);
- // let canvasImgWidth:number = canvasImg.width * canvasImgRatio,
- // canvasImgHeight:number = canvasImg.height * canvasImgRatio;
- // let canvasImgOffset:number = (pdfHeight - canvasImgHeight) / 2;
- // pdf.addImage(canvasImg, 'JPEG', leftColumnWidth, canvasImgOffset, canvasImgWidth, canvasImgHeight);
- //
- // addEntityIcon();
- // }
- // };
- //
- // if(canvasImg.src === 'data:,') { //empty canvas
- // addEntityIcon();
- // } else {
- // canvasImg.src = canvasImgBase64;
- // }
- };
-
- let getPdfProperties = ():Array<any> => {
- return [
- {title: this.$filter('translate')('GENERAL_LABEL_TYPE'), value: scope.entity.getComponentSubType(), offset: 10},
- {title: this.$filter('translate')('GENERAL_LABEL_VERSION'), value: scope.entity.version, offset: 15},
- {title: this.$filter('translate')('GENERAL_LABEL_CATEGORY'), value: scope.entity.categories.length ? scope.entity.categories[0].name : '', offset: 16},
- {title: this.$filter('translate')('GENERAL_LABEL_CREATION_DATE'), value: this.$filter('date')(scope.entity.creationDate, 'MM/dd/yyyy'), offset: 24},
- {title: this.$filter('translate')('GENERAL_LABEL_AUTHOR'), value: scope.entity.creatorFullName, offset: 13},
- {title: this.$filter('translate')('GENERAL_LABEL_CONTACT_ID'), value: scope.entity.contactId, offset: 41},
- {title: this.$filter('translate')('GENERAL_LABEL_STATUS'), value: (<any>this.sdcMenu).LifeCycleStatuses[scope.entity.lifecycleState].text, offset: 13},
- {title: this.$filter('translate')('GENERAL_LABEL_PROJECT_CODE'), value: scope.entity.projectCode, offset: 15},
- {title: this.$filter('translate')('GENERAL_LABEL_DESCRIPTION'), value: scope.entity.description, offset: 20},
- {title: this.$filter('translate')('GENERAL_LABEL_TAGS'), value: scope.entity.tags.join(', '), offset: 10}
- ];
- };
-
- };
-
- public static factory = ($filter:ng.IFilterService, sdcMenu:Models.IAppMenu, sdcConfig:Models.IAppConfigurtaion, urlToBase64Service:Sdc.Services.UrlToBase64Service)=> {
- return new PrintGraphScreenDirective($filter, sdcMenu, sdcConfig, urlToBase64Service);
- };
-
- }
-
- PrintGraphScreenDirective.factory.$inject = ['$filter', 'sdcMenu', 'sdcConfig', 'Sdc.Services.UrlToBase64Service'];
-}
diff --git a/catalog-ui/app/scripts/directives/property-types/data-type-fields-structure/data-type-fields-structure.ts b/catalog-ui/app/scripts/directives/property-types/data-type-fields-structure/data-type-fields-structure.ts
deleted file mode 100644
index 94567ca36b..0000000000
--- a/catalog-ui/app/scripts/directives/property-types/data-type-fields-structure/data-type-fields-structure.ts
+++ /dev/null
@@ -1,165 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/**
- * Created by obarda on 1/27/2016.
- */
-/// <reference path="../../../references"/>
-module Sdc.Directives {
- 'use strict';
-
- export interface IDataTypeFieldsStructureScope extends ng.IScope {
- parentFormObj:ng.IFormController;
- dataTypeProperties:Array<Models.DataTypePropertyModel>;
- typeName:string;
- valueObjRef:any;
- propertyNameValidationPattern: RegExp;
- fieldsPrefixName:string;
- readOnly:boolean;
- currentTypeDefaultValue:any;
- types:Models.DataTypesMap;
- expandByDefault:boolean;
- expand:boolean;
- expanded:boolean;
- dataTypesService:Sdc.Services.DataTypesService;
-
- expandAndCollapse():void;
- getValidationPattern(type:string):RegExp;
- validateIntRange(value:string):boolean;
- onValueChange(propertyName:string, type:string):void
- }
-
-
- export class DataTypeFieldsStructureDirective implements ng.IDirective {
-
- constructor(private $templateCache:ng.ITemplateCacheService,
- private DataTypesService:Sdc.Services.DataTypesService,
- private PropertyNameValidationPattern: RegExp,
- private ValidationUtils:Sdc.Utils.ValidationUtils) {
- }
-
- scope = {
- valueObjRef: '=',
- typeName: '=',
- parentFormObj: '=',
- fieldsPrefixName: '=',
- readOnly: '=',
- defaultValue: '@',
- types: '=',
- expandByDefault: '='
- };
-
- restrict = 'E';
- replace = true;
- template = ():string => {
- return this.$templateCache.get('/app/scripts/directives/property-types/data-type-fields-structure/data-type-fields-structure.html');
- };
- public types=Utils.Constants.PROPERTY_DATA.TYPES;
-
- //get data type properties array and return object with the properties and their default value
- //(for example: get: [{name:"prop1",defaultValue:1 ...},{name:"prop2", defaultValue:"bla bla" ...}]
- // return: {prop1: 1, prop2: "bla bla"}
- private getDefaultValue = (dataTypeProperties:Array<Models.DataTypePropertyModel>):any => {
- let defaultValue = {};
- for(let i=0; i < dataTypeProperties.length; i++){
- if(dataTypeProperties[i].type!='string'){
- if(dataTypeProperties[i].defaultValue){
- defaultValue[dataTypeProperties[i].name] = JSON.parse(dataTypeProperties[i].defaultValue);
- }
- }else{
- defaultValue[dataTypeProperties[i].name] = dataTypeProperties[i].defaultValue;
- }
- }
- return defaultValue;
- };
-
- private initDataOnScope = (scope:any, $attr:any):void =>{
- scope.dataTypesService = this.DataTypesService;
- scope.dataTypeProperties = this.DataTypesService.getFirsLevelOfDataTypeProperties(scope.typeName,scope.types);
- if($attr.defaultValue){
- scope.currentTypeDefaultValue = JSON.parse($attr.defaultValue);
- }else{
- scope.currentTypeDefaultValue = this.getDefaultValue(scope.dataTypeProperties);
- }
-
- if(!scope.valueObjRef) {
- scope.valueObjRef = {};
- }
-
- _.forEach(scope.currentTypeDefaultValue, (value, key)=> {
- if(!scope.valueObjRef[key]){
- if(typeof scope.currentTypeDefaultValue[key] == 'object'){
- angular.copy(scope.currentTypeDefaultValue[key], scope.valueObjRef[key]);
- }else{
- scope.valueObjRef[key] = scope.currentTypeDefaultValue[key];
- }
- }
- });
- };
-
- private rerender = (scope:any):void =>{
- scope.expanded = false;
- scope.expand = false;
- if(scope.expandByDefault){
- scope.expandAndCollapse();
- }
- };
-
- link = (scope:IDataTypeFieldsStructureScope, element:any, $attr:any) => {
- scope.propertyNameValidationPattern = this.PropertyNameValidationPattern;
-
- scope.$watchCollection('[typeName,fieldsPrefixName]', (newData:any):void => {
- this.rerender(scope);
- });
-
-
- scope.expandAndCollapse = ():void => {
- if(!scope.expanded){
- this.initDataOnScope(scope,$attr);
- scope.expanded=true;
- }
- scope.expand=!scope.expand;
- };
-
- scope.getValidationPattern = (type:string):RegExp => {
- return this.ValidationUtils.getValidationPattern(type);
- };
-
- scope.validateIntRange = (value:string):boolean => {
- return !value || this.ValidationUtils.validateIntRange(value);
- };
-
- scope.onValueChange = (propertyName:string, type:string):void => {
- scope.valueObjRef[propertyName] = !angular.isUndefined(scope.valueObjRef[propertyName]) ? scope.valueObjRef[propertyName] : scope.currentTypeDefaultValue[propertyName];
- if(scope.valueObjRef[propertyName] && type != 'string'){
- scope.valueObjRef[propertyName] = JSON.parse(scope.valueObjRef[propertyName]);
- }
- };
- };
-
- public static factory = ($templateCache:ng.ITemplateCacheService,
- DataTypesService:Sdc.Services.DataTypesService,
- PropertyNameValidationPattern:RegExp,
- ValidationUtils:Sdc.Utils.ValidationUtils)=> {
- return new DataTypeFieldsStructureDirective($templateCache,DataTypesService,PropertyNameValidationPattern,ValidationUtils);
- };
- }
-
- DataTypeFieldsStructureDirective.factory.$inject = ['$templateCache','Sdc.Services.DataTypesService','PropertyNameValidationPattern','ValidationUtils'];
-}
diff --git a/catalog-ui/app/scripts/directives/property-types/type-list/type-list-directive.ts b/catalog-ui/app/scripts/directives/property-types/type-list/type-list-directive.ts
deleted file mode 100644
index ce5ee1ffa6..0000000000
--- a/catalog-ui/app/scripts/directives/property-types/type-list/type-list-directive.ts
+++ /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=========================================================
- */
-/**
- * Created by rcohen on 9/15/2016.
- */
-/// <reference path="../../../references"/>
-module Sdc.Directives {
- 'use strict';
- /// import Model = go.Model;
-
- export interface ITypeListScope extends ng.IScope {
- parentFormObj:ng.IFormController;
- schemaProperty:Models.SchemaProperty;
- isSchemaTypeDataType:boolean;
- valueObjRef:any;
- propertyNameValidationPattern: RegExp;
- fieldsPrefixName:string;
- readOnly:boolean;
- listDefaultValue:any;
- types:Models.DataTypesMap;
- listNewItem:any;
- maxLength:number;
-
- getValidationPattern(type:string):RegExp;
- validateIntRange(value:string):boolean;
- addListItem():void;
- deleteListItem(listItemIndex:number):void
- }
-
-
- export class TypeListDirective implements ng.IDirective {
-
- constructor(private $templateCache:ng.ITemplateCacheService,
- private DataTypesService:Sdc.Services.DataTypesService,
- private PropertyNameValidationPattern: RegExp,
- private ValidationUtils:Sdc.Utils.ValidationUtils) {
- }
-
- scope = {
- valueObjRef: '=',//ref to list object in the parent value object
- schemaProperty: '=',//get the schema.property object
- parentFormObj: '=',//ref to parent form (get angular form object)
- fieldsPrefixName: '=',//prefix for form fields names
- readOnly: '=',//is form read only
- defaultValue: '@',//this list default value
- types: '=',//data types list
- maxLength: '='
- };
-
- restrict = 'E';
- replace = true;
- template = ():string => {
- return this.$templateCache.get('/app/scripts/directives/property-types/type-list/type-list-directive.html');
- };
-
- link = (scope:ITypeListScope, element:any, $attr:any) => {
- scope.propertyNameValidationPattern = this.PropertyNameValidationPattern;
-
- //reset valueObjRef when schema type is changed
- scope.$watchCollection('schemaProperty.type', (newData:any):void => {
- scope.isSchemaTypeDataType = this.DataTypesService.isDataTypeForSchemaType(scope.schemaProperty,scope.types);
- //insert 1 empty item dt by default
- if(scope.isSchemaTypeDataType && (!scope.valueObjRef||!scope.valueObjRef.length)){
- scope.valueObjRef = scope.valueObjRef ||[];
- scope.valueObjRef.push({});
- }
- });
-
- //when user brows between properties in "edit property form"
- scope.$watchCollection('fieldsPrefixName', (newData:any):void => {
- scope.listNewItem={value:''};
-
- if($attr.defaultValue){
- scope.listDefaultValue = JSON.parse($attr.defaultValue);
- }
- });
-
- scope.getValidationPattern = (type:string):RegExp => {
- return this.ValidationUtils.getValidationPattern(type);
- };
-
- scope.validateIntRange = (value:string):boolean => {
- return !value || this.ValidationUtils.validateIntRange(value);
- };
-
- scope.addListItem = ():void => {
- scope.valueObjRef = scope.valueObjRef ||[];
- let newVal = ((scope.schemaProperty.simpleType||scope.schemaProperty.type)==Utils.Constants.PROPERTY_TYPES.STRING?scope.listNewItem.value:JSON.parse(scope.listNewItem.value));
- scope.valueObjRef.push(newVal);
- scope.listNewItem.value = "";
- };
-
- scope.deleteListItem = (listItemIndex:number):void => {
- scope.valueObjRef.splice(listItemIndex,1);
- if (!scope.valueObjRef.length) {
- if (scope.listDefaultValue ) {
- angular.copy(scope.listDefaultValue, scope.valueObjRef);
- }
- }
- };
- };
-
- public static factory = ($templateCache:ng.ITemplateCacheService,
- DataTypesService:Sdc.Services.DataTypesService,
- PropertyNameValidationPattern:RegExp,
- ValidationUtils:Sdc.Utils.ValidationUtils)=> {
- return new TypeListDirective($templateCache,DataTypesService,PropertyNameValidationPattern,ValidationUtils);
- };
- }
-
- TypeListDirective.factory.$inject = ['$templateCache','Sdc.Services.DataTypesService','PropertyNameValidationPattern','ValidationUtils'];
-}
-
diff --git a/catalog-ui/app/scripts/directives/property-types/type-map/type-map-directive.ts b/catalog-ui/app/scripts/directives/property-types/type-map/type-map-directive.ts
deleted file mode 100644
index d94ccf3886..0000000000
--- a/catalog-ui/app/scripts/directives/property-types/type-map/type-map-directive.ts
+++ /dev/null
@@ -1,157 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/**
- * Created by rcohen on 9/15/2016.
- */
-/// <reference path="../../../references"/>
-module Sdc.Directives {
- 'use strict';
-
- export interface ITypeMapScope extends ng.IScope {
- parentFormObj:ng.IFormController;
- schemaProperty:Models.SchemaProperty;
- isSchemaTypeDataType:boolean;
- valueObjRef:any;
- mapKeys:Array<string>;//array of map keys
- propertyNameValidationPattern: RegExp;
- fieldsPrefixName:string;
- readOnly:boolean;
- mapDefaultValue:any;
- types:Models.DataTypesMap;
- maxLength:number;
-
- getValidationPattern(type:string):RegExp;
- validateIntRange(value:string):boolean;
- changeKeyOfMap(newKey:string, index:number, fieldName:string):void;
- deleteMapItem(index:number):void;
- addMapItemFields():void;
- parseToCorrectType(objectOfValues:any, locationInObj:string, type:string):void;
- getNumber(num:number):Array<any>;
- }
-
-
- export class TypeMapDirective implements ng.IDirective {
-
- constructor(private $templateCache:ng.ITemplateCacheService,
- private DataTypesService:Sdc.Services.DataTypesService,
- private PropertyNameValidationPattern: RegExp,
- private ValidationUtils:Sdc.Utils.ValidationUtils,
- private $timeout: ng.ITimeoutService) {
- }
-
- scope = {
- valueObjRef: '=',//ref to map object in the parent value object
- schemaProperty: '=',//get the schema.property object
- parentFormObj: '=',//ref to parent form (get angular form object)
- fieldsPrefixName: '=',//prefix for form fields names
- readOnly: '=',//is form read only
- defaultValue: '@',//this map default value
- types: '=',//data types list
- maxLength: '='
- };
-
- restrict = 'E';
- replace = true;
- template = ():string => {
- return this.$templateCache.get('/app/scripts/directives/property-types/type-map/type-map-directive.html');
- };
-
- link = (scope:ITypeMapScope, element:any, $attr:any) => {
- scope.propertyNameValidationPattern = this.PropertyNameValidationPattern;
-
- //reset valueObjRef and mapKeys when schema type is changed
- scope.$watchCollection('schemaProperty.type', (newData:any):void => {
- scope.isSchemaTypeDataType = this.DataTypesService.isDataTypeForSchemaType(scope.schemaProperty,scope.types);
- if(scope.valueObjRef){
- scope.mapKeys = Object.keys(scope.valueObjRef);
- }
- });
-
- //when user brows between properties in "edit property form"
- scope.$watchCollection('fieldsPrefixName', (newData:any):void => {
- if(!scope.valueObjRef) {
- scope.valueObjRef={};
- }
- scope.mapKeys = Object.keys(scope.valueObjRef);
-
- if($attr.defaultValue){
- scope.mapDefaultValue = JSON.parse($attr.defaultValue);
- }
- });
-
- //return dummy array in order to prevent rendering map-keys ng-repeat again when a map key is changed
- scope.getNumber = (num:number):Array<any> => {
- return new Array(num);
- };
-
- scope.getValidationPattern = (type:string):RegExp => {
- return this.ValidationUtils.getValidationPattern(type);
- };
-
- scope.validateIntRange = (value:string):boolean => {
- return !value || this.ValidationUtils.validateIntRange(value);
- };
-
- scope.changeKeyOfMap = (newKey:string, index:number, fieldName:string) : void => {
- let oldKey = Object.keys(scope.valueObjRef)[index];
- if(Object.keys(scope.valueObjRef).indexOf(newKey)>-1){
- scope.parentFormObj[fieldName].$setValidity('keyExist', false);
- }else{
- scope.parentFormObj[fieldName].$setValidity('keyExist', true);
- if(!scope.parentFormObj[fieldName].$invalid){
- angular.copy(JSON.parse(JSON.stringify(scope.valueObjRef).replace('"'+oldKey+'":', '"'+newKey+'":')),scope.valueObjRef);//update key
- }
- }
- };
-
- scope.deleteMapItem=(index:number):void=>{
- delete scope.valueObjRef[scope.mapKeys[index]];
- scope.mapKeys.splice(index,1);
- if (!scope.mapKeys.length) {//only when user removes all pairs of key-value fields - put the default
- if ( scope.mapDefaultValue ) {
- angular.copy(scope.mapDefaultValue, scope.valueObjRef);
- scope.mapKeys = Object.keys(scope.valueObjRef);
- }
- }
- };
-
- scope.addMapItemFields = ():void => {
- scope.valueObjRef['']= null;
- scope.mapKeys = Object.keys(scope.valueObjRef);
- };
-
- scope.parseToCorrectType = (objectOfValues:any, locationInObj:string, type:string):void => {
- if(objectOfValues[locationInObj] && type != Utils.Constants.PROPERTY_TYPES.STRING){
- objectOfValues[locationInObj] = JSON.parse(objectOfValues[locationInObj]);
- }
- }
- };
-
- public static factory = ($templateCache:ng.ITemplateCacheService,
- DataTypesService:Sdc.Services.DataTypesService,
- PropertyNameValidationPattern:RegExp,
- ValidationUtils:Sdc.Utils.ValidationUtils,
- $timeout: ng.ITimeoutService)=> {
- return new TypeMapDirective($templateCache,DataTypesService,PropertyNameValidationPattern,ValidationUtils,$timeout);
- };
- }
-
- TypeMapDirective.factory.$inject = ['$templateCache','Sdc.Services.DataTypesService','PropertyNameValidationPattern','ValidationUtils','$timeout'];
-}
diff --git a/catalog-ui/app/scripts/directives/punch-out/punch-out.ts b/catalog-ui/app/scripts/directives/punch-out/punch-out.ts
deleted file mode 100644
index f00b7971a9..0000000000
--- a/catalog-ui/app/scripts/directives/punch-out/punch-out.ts
+++ /dev/null
@@ -1,99 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../references"/>
-module Sdc.Directives {
- 'use strict';
- export interface IPunchOutScope extends ng.IScope {
- name: string;
- data: any;
- user: Models.IUserProperties;
- onEvent: Function;
- }
-
- export class PunchOutDirective implements ng.IDirective {
-
- constructor(
- private sdcConfig: Sdc.Models.IAppConfigurtaion) {}
-
- scope = {
- name: '=',
- data: '=',
- user: '=',
- onEvent: '&'
- };
-
- replace = false;
- restrict = 'E';
-
- link = (scope: IPunchOutScope, element: ng.IAugmentedJQuery):void => {
- // global registry object
- let PunchOutRegistry = window['PunchOutRegistry'];
-
- let render = ():void => {
- let cookieConfig = this.sdcConfig.cookie;
- let props = {
- name: scope.name,
- options: {
- data: scope.data,
- apiRoot: this.sdcConfig.api.root,
- apiHeaders: {
- userId: {
- name: cookieConfig.userIdSuffix,
- value: scope.user.userId
- },
- userFirstName: {
- name: cookieConfig.userFirstName,
- value: scope.user.firstName
- },
- userLastName: {
- name: cookieConfig.userLastName,
- value: scope.user.lastName
- },
- userEmail: {
- name: cookieConfig.userEmail,
- value: scope.user.email
- }
- }
- },
- onEvent: (...args) => {
- scope.$apply(() => {
- scope.onEvent().apply(null, args);
- });
- }
- };
- PunchOutRegistry.render(props, element[0]);
- };
-
- let unmount = ():void => {
- PunchOutRegistry.unmount(element[0]);
- };
-
- scope.$watch('data', render);
- element.on('$destroy', unmount);
- };
-
- public static factory = (sdcConfig: Sdc.Models.IAppConfigurtaion) => {
- return new PunchOutDirective(sdcConfig);
- };
-
- }
-
- PunchOutDirective.factory.$inject = ['sdcConfig'];
-}
diff --git a/catalog-ui/app/scripts/directives/sdc-tabs/sdc-single-tab/sdc-single-tab-directive.ts b/catalog-ui/app/scripts/directives/sdc-tabs/sdc-single-tab/sdc-single-tab-directive.ts
deleted file mode 100644
index 26390a7501..0000000000
--- a/catalog-ui/app/scripts/directives/sdc-tabs/sdc-single-tab/sdc-single-tab-directive.ts
+++ /dev/null
@@ -1,67 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../../references"/>
-module Sdc.Directives {
- 'use strict';
-
- export class SdcSingleTabDirective implements ng.IDirective {
-
- constructor(private $compile:ng.ICompileService, private $parse:ng.IParseService) {
- }
- restrict = 'E';
-
- link = (scope, elem:any, attrs:any, ctrl:any) => {
- if(!elem.attr('inner-sdc-single-tab')) {
- let name = this.$parse(elem.attr('ctrl'))(scope);
- elem = elem.removeAttr('ctrl');
- elem.attr('inner-sdc-single-tab', name);
- this.$compile(elem)(scope);
- }
- };
-
- public static factory = ($compile:ng.ICompileService, $parse:ng.IParseService)=> {
- return new SdcSingleTabDirective($compile, $parse);
- };
- }
-
- export class InnerSdcSingleTabDirective implements ng.IDirective {
-
- constructor(private $templateCache:ng.ITemplateCacheService) {
- }
-
- scope = {
- singleTab: "=",
- isViewOnly: "="
- };
-
- replace = true;
- restrict = 'A';
- controller = '@';
- template = '<div ng-include src="singleTab.templateUrl"></div>';
-
- public static factory = ($templateCache:ng.ITemplateCacheService)=> {
- return new InnerSdcSingleTabDirective($templateCache);
- };
- }
-
- SdcSingleTabDirective.factory.$inject = ['$compile', '$parse'];
- InnerSdcSingleTabDirective.factory.$inject = ['$templateCache'];
-
-}
diff --git a/catalog-ui/app/scripts/directives/sdc-tabs/sdc-tabs-directive.ts b/catalog-ui/app/scripts/directives/sdc-tabs/sdc-tabs-directive.ts
deleted file mode 100644
index 91d1744ae5..0000000000
--- a/catalog-ui/app/scripts/directives/sdc-tabs/sdc-tabs-directive.ts
+++ /dev/null
@@ -1,69 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/**
- * Created by obarda on 7/28/2016.
- */
-/// <reference path="../../references"/>
-module Sdc.Directives {
- 'use strict';
-
- export interface ISdcTabsDirectiveScope extends ng.IScope {
- tabs:Array<Models.Tab>;
- selectedTab: Models.Tab;
- isActive: boolean;
- onTabSelected(selectedTab: Models.Tab);
- }
-
- export class SdcTabsDirective implements ng.IDirective {
-
- constructor(private $templateCache:ng.ITemplateCacheService) {
- }
-
- scope = {
- tabs: "=",
- selectedTab: "=?",
- isViewOnly: "="
- };
-
- replace = true;
- restrict = 'E';
- template = ():string => {
- return this.$templateCache.get('/app/scripts/directives/sdc-tabs/sdc-tabs-directive-view.html');
- };
-
- link = (scope:ISdcTabsDirectiveScope) => {
- scope.isActive = true;
-
- if(!scope.selectedTab){
- scope.selectedTab = scope.tabs[0];
- }
-
- scope.onTabSelected = (selectedTab: Models.Tab) => {
- scope.selectedTab = selectedTab;
- }
- };
-
- public static factory = ($templateCache:ng.ITemplateCacheService)=> {
- return new SdcTabsDirective($templateCache);
- };
- }
-
- SdcTabsDirective.factory.$inject = ['$templateCache'];
-}
diff --git a/catalog-ui/app/scripts/directives/structure-tree/structure-tree-directive.ts b/catalog-ui/app/scripts/directives/structure-tree/structure-tree-directive.ts
deleted file mode 100644
index 1edce6f36e..0000000000
--- a/catalog-ui/app/scripts/directives/structure-tree/structure-tree-directive.ts
+++ /dev/null
@@ -1,197 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../references"/>
-module Sdc.Directives {
- 'use strict';
-
-
- export interface IStructureTreeScope extends ng.IScope {
-
- component: Models.Components.Component;
- structureTree: StructureTree;
- }
-
- class StructureTree {
-
- serviceRoot:ResourceInstanceNode;
-
- constructor(private uniqueId:string, private resourceInstanceName:string, private resourceInstanceIcon:string, private certified:boolean) {
- this.serviceRoot = new ResourceInstanceNode(uniqueId, resourceInstanceName, resourceInstanceIcon, certified);
- }
-
- }
-
- class ResourceInstanceNode {
- id:string;
- icon:string;
- name:string;
- resourceInstancesList:Array<ResourceInstanceNode>;
- isAlreadyInTree:boolean;
- certified:boolean;
-
-
- constructor(private uniqueId:string, private resourceInstanceName:string, private resourceInstanceIcon:string, certified:boolean) {
- this.id = uniqueId;
- this.name = resourceInstanceName;
- this.icon = resourceInstanceIcon;
- this.resourceInstancesList = [];
- this.isAlreadyInTree = false;
- this.certified = certified;
- }
- }
-
- export class StructureTreeDirective implements ng.IDirective {
-
-
- constructor(private $templateCache:ng.ITemplateCacheService) {
- }
-
- scope = {
- component: '=',
- };
- restrict = 'E';
- template = ():string => {
- return this.$templateCache.get('/app/scripts/directives/structure-tree/structure-tree-directive.html');
- };
-
- link = (scope:IStructureTreeScope, $elem:any) => {
-
- let RESOURCE_INSTANCE_LIST:string = "resourceInstancesChildesList";
- let resourceInstanceMap:Utils.Dictionary<string, ResourceInstanceNode>;
- let relations:Array<Models.RelationshipModel>;
- //************* Start Building Tree Functions *******************//
-
- //remove unnecessary instances
- let initResourceInstanceMap = ():void => {
-
- resourceInstanceMap = new Utils.Dictionary<string, ResourceInstanceNode>();
-
- _.forEach(scope.component.componentInstances, (resourceInstance:Models.ComponentsInstances.ComponentInstance)=> {
- if (_.some(Object.keys(resourceInstance.capabilities), (key:string)=> {
- return 'tosca.capabilities.container' == key.toLowerCase();
- }) || _.some(Object.keys(resourceInstance.requirements),(key:string)=> {
- return 'tosca.capabilities.container' == key.toLowerCase();
- })) {
-
- let isCertified = 0 === (parseFloat(resourceInstance.componentVersion) % 1);
- let node:ResourceInstanceNode = new ResourceInstanceNode(resourceInstance.uniqueId,
- resourceInstance.name,
- resourceInstance.icon,
- isCertified);
- resourceInstanceMap.setValue(resourceInstance.uniqueId, node);
- }
- });
- };
-
- //remove unnecessary relations
- let initRelations = ():void => {
- relations = _.filter(scope.component.componentInstancesRelations, (relation:Models.RelationshipModel)=> {
- return resourceInstanceMap.containsKey(relation.fromNode) && resourceInstanceMap.containsKey(relation.toNode);
- });
- };
-
- let buildTree = ():void => {
- if (scope.component) {
- scope.structureTree = new StructureTree(scope.component.uniqueId, scope.component.name, scope.component.icon, 'CERTIFIED' === scope.component.lifecycleState);
- initResourceInstanceMap();
- initRelations();
-
- let parentNodesList = _.groupBy(relations, (node:any)=> {
- return node.fromNode;
- });
-
- for (let parent in parentNodesList) {
- _.forEach(parentNodesList[parent], (childNode)=> {
- parentNodesList[parent][RESOURCE_INSTANCE_LIST] = [];
- parentNodesList[parent][RESOURCE_INSTANCE_LIST].push(mergeAllSubtrees(childNode, parentNodesList));
- });
- }
-
- //add the resourceInstanceList for the service root node
- for (let parent in parentNodesList) {
- let resourceInstanceNode:ResourceInstanceNode = resourceInstanceMap.getValue(parent);
- resourceInstanceNode.resourceInstancesList = parentNodesList[parent];
- resourceInstanceNode.resourceInstancesList = parentNodesList[parent][RESOURCE_INSTANCE_LIST];
- resourceInstanceNode.isAlreadyInTree = true;
- scope.structureTree.serviceRoot.resourceInstancesList.push(resourceInstanceNode);
- }
-
- // Add all node that have no connection to the rootNode
- resourceInstanceMap.forEach((key:string, value:ResourceInstanceNode) => {
- if (!value.isAlreadyInTree) {
- scope.structureTree.serviceRoot.resourceInstancesList.push(value);
- }
- });
- }
- };
-
- //this recursion is merging all the subtrees
- let mergeAllSubtrees = (connectionData:any, parentNodesList:any):ResourceInstanceNode => {
- let resourceInstanceNode:ResourceInstanceNode = resourceInstanceMap.getValue(connectionData.toNode);
- resourceInstanceNode.isAlreadyInTree = true;
- if (parentNodesList[resourceInstanceNode.id]) {
- if (parentNodesList[resourceInstanceNode.id][RESOURCE_INSTANCE_LIST]) {
- resourceInstanceNode.resourceInstancesList = parentNodesList[resourceInstanceNode.id][RESOURCE_INSTANCE_LIST];
- }
- else {
- _.forEach(parentNodesList[resourceInstanceNode.id], (children)=> {
- resourceInstanceNode.resourceInstancesList.push(mergeAllSubtrees(children, parentNodesList));
- });
- }
- delete parentNodesList[resourceInstanceNode.id];
- }
- return resourceInstanceNode;
- };
- //************* End Building Tree Functions *******************//
-
- //************* Start Watchers *******************//
- scope.$watch('component.name', ():void => {
- if (scope.structureTree)
- scope.structureTree.serviceRoot.name = scope.component.name;
- });
-
- scope.$watch('component.icon', ():void => {
- if (scope.structureTree)
- scope.structureTree.serviceRoot.icon = scope.component.icon;
- });
-
- scope.$watchCollection('component.componentInstancesRelations', ():void => {
- buildTree();
- });
-
- scope.$watchCollection('component.componentInstances', ():void => {
- buildTree();
- });
-
- //************* End Watchers *******************//
-
- buildTree();
-
- };
-
-
- public static factory = ($templateCache:ng.ITemplateCacheService) => {
- return new StructureTreeDirective($templateCache);
- };
- }
-
- StructureTreeDirective.factory.$inject = ['$templateCache'];
-
-}
diff --git a/catalog-ui/app/scripts/directives/tag/tag-directive.ts b/catalog-ui/app/scripts/directives/tag/tag-directive.ts
deleted file mode 100644
index 64d245e242..0000000000
--- a/catalog-ui/app/scripts/directives/tag/tag-directive.ts
+++ /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=========================================================
- */
-/// <reference path="../../references"/>
-module Sdc.Directives {
- 'use strict';
-
- export class TagData {
- tag:string;
- tooltip:string;
- id: string;
- }
-
- export interface ITagScope extends ng.IScope {
- tagData: TagData;
- onDelete: Function;
- delete:Function;
- hideTooltip:boolean;
- hideDelete:boolean;
- sdcDisable: boolean;
- }
-
- export class TagDirective implements ng.IDirective {
-
- constructor(private $templateCache:ng.ITemplateCacheService) {
- }
-
- scope = {
- tagData: '=',
- onDelete: '&',
- hideTooltip: '=',
- hideDelete: '=',
- sdcDisable: '='
- };
-
- replace = true;
- restrict = 'EA';
- template = ():string => {
- return this.$templateCache.get('/app/scripts/directives/tag/tag-directive.html');
- };
-
- link = (scope:ITagScope) => {
- scope.delete = ()=>{
- scope.onDelete({'uniqueId':scope.tagData.id});
- }
- };
-
- public static factory = ($templateCache:ng.ITemplateCacheService)=> {
- return new TagDirective($templateCache);
- };
-
- }
-
- TagDirective.factory.$inject = ['$templateCache'];
-}
diff --git a/catalog-ui/app/scripts/directives/tutorial/image-template.html b/catalog-ui/app/scripts/directives/tutorial/image-template.html
deleted file mode 100644
index 7e7f7af356..0000000000
--- a/catalog-ui/app/scripts/directives/tutorial/image-template.html
+++ /dev/null
@@ -1,7 +0,0 @@
-<perfect-scrollbar include-padding="true" class="sdc-tutorial-container-content sdc-tutorial-image-template">
- <div class="{{pageObject.data.imageClass}}"></div>
- <div class="sdc-tutorial-image-template-text">
- <h1 translate="{{pageObject.data.title}}"></h1>
- <p class="sdc-welcome-page-description2" translate="{{pageObject.data.description}}"></p>
- </div>
-</perfect-scrollbar>
diff --git a/catalog-ui/app/scripts/directives/tutorial/text-template.html b/catalog-ui/app/scripts/directives/tutorial/text-template.html
deleted file mode 100644
index dc1173be64..0000000000
--- a/catalog-ui/app/scripts/directives/tutorial/text-template.html
+++ /dev/null
@@ -1,4 +0,0 @@
-<perfect-scrollbar include-padding="true" class="sdc-tutorial-container-content sdc-tutorial-text-template">
- <h1 translate="{{pageObject.data.title}}"></h1>
- <p class="sdc-welcome-page-description2" translate="{{pageObject.data.description}}"></p>
-</perfect-scrollbar>
diff --git a/catalog-ui/app/scripts/directives/tutorial/tutorial-directive.html b/catalog-ui/app/scripts/directives/tutorial/tutorial-directive.html
deleted file mode 100644
index 191752fc1f..0000000000
--- a/catalog-ui/app/scripts/directives/tutorial/tutorial-directive.html
+++ /dev/null
@@ -1,22 +0,0 @@
-<div class="sdc-tutorial-page" data-ng-if="showTutorial">
- <div class="sdc-tutorial-container-wrapper">
- <div class="sdc-tutorial-skip" translate="{{isFirstTime?'TUTRIAL_GENERAL_SKIP_BUTTON':'TUTRIAL_GENERAL_CLOSE_BUTTON'}}" data-ng-click="closeTutorial()"></div>
- <div class="sdc-tutorial-container">
- <div class="sdc-tutorial-container-tabs">
- <div class="sdc-tutorial-container-tab" data-ng-repeat="tab in tabs" data-ng-class="{'selected': tab.id===pageObject.tab}">
- <span translate="{{tab.name}}" data-ng-click="initPage(tab.defaultPage)"></span>
- </div>
- </div>
- <ng-include src="templateUrl"></ng-include>
- </div>
-
- <div class="sdc-tutorial-footer">
- <div class="sdc-tutorial-footer-prev-button"><span data-ng-show="hasPrevious()" translate="TUTRIAL_GENERAL_PREVIOUS_BUTTON" data-ng-click="previous()"></span></div>
- <div class="sdc-tutorial-footer-page-counter"><span class="selected" data-ng-bind="currentPageIndex+1"></span>/<span class="total" data-ng-bind="totalPages"></span></div>
- <div class="sdc-tutorial-footer-next-button">
- <span data-ng-if="hasNext()" translate="TUTRIAL_GENERAL_NEXT_BUTTON" data-ng-click="next()"></span>
- <span data-ng-if="(currentPageIndex+1) === totalPages" translate="TUTRIAL_GENERAL_NEXT_BUTTON_END" data-ng-click="closeAndShowLastPage()"></span>
- </div>
- </div>
- </div>
-</div>
diff --git a/catalog-ui/app/scripts/directives/tutorial/tutorial-directive.less b/catalog-ui/app/scripts/directives/tutorial/tutorial-directive.less
deleted file mode 100644
index 410a54e9c1..0000000000
--- a/catalog-ui/app/scripts/directives/tutorial/tutorial-directive.less
+++ /dev/null
@@ -1,213 +0,0 @@
-.sdc-tutorial-page {
-
- width: 100%;
- height: 100%;
- background-color: rgba(0,0,0,0.8);
-
- display: flex;
- align-items: center;
- justify-content: center;
- position: absolute;
- top: 0;
- left: 0;
- z-index: 3000;
-
- .sdc-tutorial-container-wrapper {
- display: flex;
- flex-direction: column;
- }
-
- .sdc-tutorial-container {
- .bg_c;
- width: 830px;
- height: 466px;
- box-shadow: 1px 2px 2px 0px rgba(0, 0, 0, 0.35);
- }
-
- .sdc-tutorial-container-tabs {
- height: 56px;
- display: flex;
- flex-direction: row;
- }
-
- .sdc-tutorial-container-tab {
- .a_6;
- flex-grow: 1;
- align-items: center;
- justify-content: center;
- display: flex;
- height: 56px;
- position: relative;
- opacity: 0.8;
-
- span {
- .hand;
- }
-
- &::after {
- content: '';
- display: block;
- border-right: solid 1px ;
- border-color: rgba(59, 123, 155, 0.31);
- height: 28px;
- right: 0;
- position: absolute;
- top: 14px; //(56-28)/2
- width: 1px;
- }
-
- &:last-child:after {
- display: none;
- }
-
- &.selected {
- opacity: 1;
- .bold;
- }
-
- }
-
- .sdc-tutorial-container-content {
- .bg_a;
- .perfect-scrollbar;
- display: flex;
- align-items: center;
- height: 410px;
- }
-
- .sdc-tutorial-skip {
- .c_1;
- .hand;
- text-align: right;
- margin-bottom: 9px;
- }
-
- .sdc-tutorial-footer {
- .c_4;
- margin-top: 9px;
-
- .sdc-tutorial-footer-prev-button {
- float: left;
- position: relative;
- padding-left: 14px;
- .noselect;
-
- span {
- .hand;
- &::before {
- content: '<';
- display: block;
- position: absolute;
- left: 0;
- top: 0;
- }
- }
- }
-
- .sdc-tutorial-footer-page-counter {
- .e_3;
- position: absolute;
- left: 50%;
- margin-top: 2px;
- cursor: default;
- .noselect;
-
- .selected {
- .c_3;
- .bold;
- margin-right: 2px;
- }
-
- .total {
- margin-left: 2px;
- }
- }
-
- .sdc-tutorial-footer-next-button {
- float: right;
- position: relative;
- padding-right: 14px;
- .noselect;
-
- span {
- .hand;
-
- &::after {
- content: '>';
- display: block;
- position: absolute;
- right: 0;
- top: 0;
- }
- }
- }
-
- }
-
-}
-
-///////////////// TEXT TEMPLATE
-.sdc-tutorial-text-template {
-
- padding: 20px 65px;
-
- h1 {
- .c_15;
- margin-top: 0;
- }
-
- p {
- .c_10;
- }
-}
-
-///////////////// IMAGE TEMPLATE
-.sdc-tutorial-image-template {
-
- .sdc-tutorial-image-template-text {
- padding: 16px 38px;
- height: 118px;
- h1 {
- .c_11;
- margin: 0 0 4px 0;
- }
-
- p {
- .c_4;
- font-weight: 300;
- line-height: 21px;
- }
-
- }
-
- .sdc-tutorial-page-2-image { background: transparent url('../../../styles/images/tutorial/2.png') no-repeat 0 0; width: 830px; height: 292px;}
- .sdc-tutorial-page-3-image { background: transparent url('../../../styles/images/tutorial/3.png') no-repeat 0 0; width: 830px; height: 292px;}
- .sdc-tutorial-page-4-image { background: transparent url('../../../styles/images/tutorial/4.png') no-repeat 0 0; width: 830px; height: 292px;}
- .sdc-tutorial-page-5-image { background: transparent url('../../../styles/images/tutorial/5.png') no-repeat 0 0; width: 830px; height: 292px;}
- .sdc-tutorial-page-6-image { background: transparent url('../../../styles/images/tutorial/6.png') no-repeat 0 0; width: 830px; height: 292px;}
- .sdc-tutorial-page-7-image { background: transparent url('../../../styles/images/tutorial/7.png') no-repeat 0 0; width: 830px; height: 292px;}
- .sdc-tutorial-page-8-image { background: transparent url('../../../styles/images/tutorial/8.png') no-repeat 0 0; width: 830px; height: 292px;}
-
- .sdc-tutorial-page-10-image { background: transparent url('../../../styles/images/tutorial/10.png') no-repeat 0 0; width: 830px; height: 292px;}
- .sdc-tutorial-page-11-image { background: transparent url('../../../styles/images/tutorial/11.png') no-repeat 0 0; width: 830px; height: 292px;}
-
- .sdc-tutorial-page-13-image { background: transparent url('../../../styles/images/tutorial/13.png') no-repeat 0 0; width: 830px; height: 292px;}
- .sdc-tutorial-page-14-image { background: transparent url('../../../styles/images/tutorial/14.png') no-repeat 0 0; width: 830px; height: 292px;}
- .sdc-tutorial-page-15-image { background: transparent url('../../../styles/images/tutorial/15.png') no-repeat 0 0; width: 830px; height: 292px;}
- .sdc-tutorial-page-16-image { background: transparent url('../../../styles/images/tutorial/16.png') no-repeat 0 0; width: 830px; height: 292px;}
- .sdc-tutorial-page-17-image { background: transparent url('../../../styles/images/tutorial/17.png') no-repeat 0 0; width: 830px; height: 292px;}
- .sdc-tutorial-page-18-image { background: transparent url('../../../styles/images/tutorial/18.png') no-repeat 0 0; width: 830px; height: 292px;}
- .sdc-tutorial-page-19-image { background: transparent url('../../../styles/images/tutorial/19.png') no-repeat 0 0; width: 830px; height: 292px;}
- .sdc-tutorial-page-20-image { background: transparent url('../../../styles/images/tutorial/20.png') no-repeat 0 0; width: 830px; height: 292px;}
- .sdc-tutorial-page-21-image { background: transparent url('../../../styles/images/tutorial/21.png') no-repeat 0 0; width: 830px; height: 292px;}
- .sdc-tutorial-page-22-image { background: transparent url('../../../styles/images/tutorial/22.png') no-repeat 0 0; width: 830px; height: 292px;}
- .sdc-tutorial-page-23-image { background: transparent url('../../../styles/images/tutorial/23.png') no-repeat 0 0; width: 830px; height: 292px;}
- .sdc-tutorial-page-24-image { background: transparent url('../../../styles/images/tutorial/24.png') no-repeat 0 0; width: 830px; height: 292px;}
- .sdc-tutorial-page-25-image { background: transparent url('../../../styles/images/tutorial/25.png') no-repeat 0 0; width: 830px; height: 292px;}
- .sdc-tutorial-page-26-image { background: transparent url('../../../styles/images/tutorial/26.png') no-repeat 0 0; width: 830px; height: 292px;}
- .sdc-tutorial-page-27-image { background: transparent url('../../../styles/images/tutorial/27.png') no-repeat 0 0; width: 830px; height: 292px;}
- .sdc-tutorial-page-28-image { background: transparent url('../../../styles/images/tutorial/28.png') no-repeat 0 0; width: 830px; height: 292px;}
- .sdc-tutorial-page-29-image { background: transparent url('../../../styles/images/tutorial/29.png') no-repeat 0 0; width: 830px; height: 292px;}
- .sdc-tutorial-page-30-image { background: transparent url('../../../styles/images/tutorial/30.png') no-repeat 0 0; width: 830px; height: 292px;}
-
-}
diff --git a/catalog-ui/app/scripts/directives/tutorial/tutorial-directive.ts b/catalog-ui/app/scripts/directives/tutorial/tutorial-directive.ts
deleted file mode 100644
index 7df35cade9..0000000000
--- a/catalog-ui/app/scripts/directives/tutorial/tutorial-directive.ts
+++ /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=========================================================
- */
-/// <reference path="../../references"/>
-module Sdc.Directives {
- 'use strict';
- export interface ITutorialScope extends ng.IScope {
- showTutorial:boolean;
- isFirstTime:boolean;
- templateUrl:string;
- totalPages: number;
- currentPageIndex: number;
- page:number;
- tabs:Array<string>;
- tutorialData:any;
- pageObject:any;
-
- initPage:Function;
- next:Function;
- previous:Function;
- hasNext():boolean;
- hasPrevious():boolean;
- closeTutorial:Function;
- closeAndShowLastPage:Function;
- }
-
- export class TutorialDirective implements ng.IDirective {
-
- constructor(
- private $templateCache:ng.ITemplateCacheService,
- private sdcConfig:Models.IAppConfigurtaion,
- private $state:ng.ui.IStateService
- ) {
- }
-
- scope = {
- page: '=',
- showTutorial: '=',
- isFirstTime: '='
- };
-
- replace = false;
- restrict = 'EA';
- template = ():string => {
- return this.$templateCache.get('/app/scripts/directives/tutorial/tutorial-directive.html');
- };
-
- link = (scope:ITutorialScope, $elem:any) => {
-
- let findPageIndex:Function = (pageId:number):number=> {
- for (let i:number=0;i<scope.totalPages;i++){
- if (scope.tutorialData.pages[i].id===pageId){
- return i;
- }
- }
- return -1;
- }
-
- let showCurrentPage:Function = ():void=> {
- scope.pageObject = scope.tutorialData.pages[scope.currentPageIndex];
- scope.templateUrl = '/app/scripts/directives/tutorial/' + scope.pageObject.template + '.html';
- }
-
- scope.tutorialData = this.sdcConfig.tutorial;
-
- scope.closeTutorial = ()=> {
- scope.showTutorial = false;
- if(scope.isFirstTime){
- scope.isFirstTime=false;
- }
- }
-
- scope.closeAndShowLastPage = ()=> {
- if(scope.isFirstTime){
- this.$state.go('dashboard.tutorial-end');
- }
- scope.closeTutorial();
- }
-
- let init:Function = ():void => {
- scope.tabs = scope.tutorialData.tabs;
- scope.totalPages = scope.tutorialData.pages.length;
- scope.initPage(scope.page);
-
- }
-
- scope.initPage = (pageId) => {
- scope.currentPageIndex = findPageIndex(pageId);
- showCurrentPage();
- }
-
- scope.next = ():void => {
- if (scope.hasNext()){
- scope.currentPageIndex++;
- showCurrentPage();
- }
- }
-
- scope.previous = ():void => {
- if (scope.hasPrevious()){
- scope.currentPageIndex--;
- showCurrentPage();
- }
- }
-
- scope.hasNext = ():boolean => {
- return (scope.currentPageIndex+1) < scope.totalPages;
- }
-
- scope.hasPrevious = ():boolean => {
- return scope.currentPageIndex>0;
- }
-
- angular.element(document).ready(function () {
- init();
- });
-
- scope.$watch('showTutorial', (showTutorial:any):void => {
- scope.initPage(scope.page);
- });
-
- };
-
- public static factory = ($templateCache:ng.ITemplateCacheService, sdcConfig:Models.IAppConfigurtaion, $state:ng.ui.IStateService)=> {
- return new TutorialDirective($templateCache, sdcConfig, $state);
- };
-
- }
-
- TutorialDirective.factory.$inject = ['$templateCache', 'sdcConfig', '$state'];
-}
diff --git a/catalog-ui/app/scripts/directives/user-header-details/user-header-details-directive.ts b/catalog-ui/app/scripts/directives/user-header-details/user-header-details-directive.ts
deleted file mode 100644
index 46c43a266b..0000000000
--- a/catalog-ui/app/scripts/directives/user-header-details/user-header-details-directive.ts
+++ /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=========================================================
- */
-/// <reference path="../../references"/>
-module Sdc.Directives {
- 'use strict';
- export interface IUserHeaderDetailsScope extends ng.IScope {
- name: string;
- role: string;
- iconUrl: string;
- UserResourceClass:Services.IUserResourceClass;
- user: Models.IUser;
- sdcConfig:Models.IAppConfigurtaion;
- initUser:Function;
- }
-
- export class UserHeaderDetailsDirective implements ng.IDirective {
-
- constructor(private $templateCache:ng.ITemplateCacheService, private $http:ng.IHttpService, private sdcConfig:Models.IAppConfigurtaion, private UserResourceClass:Services.IUserResourceClass) {
- }
-
- scope = {
- iconUrl: '=?'
- };
-
- replace = true;
- restrict = 'E';
- template = ():string => {
- return this.$templateCache.get('/app/scripts/directives/user-header-details/user-header-details-directive.html');
- };
-
- link = (scope:IUserHeaderDetailsScope) => {
-
- scope.initUser = ():void => {
- let defaultUserId:string;
- let user:Services.IUserResource = this.UserResourceClass.getLoggedinUser();
- if (!user) {
- defaultUserId = this.$http.defaults.headers.common[this.sdcConfig.cookie.userIdSuffix];
- user = this.UserResourceClass.get({id: defaultUserId}, ():void => {
- scope.user = new Models.User(user);
- });
- } else {
- scope.user = new Models.User(user);
- }
- };
- scope.initUser();
- };
-
- public static factory = ($templateCache:ng.ITemplateCacheService, $http:ng.IHttpService, sdcConfig:Models.IAppConfigurtaion, UserResourceClass:Services.IUserResourceClass)=> {
- return new UserHeaderDetailsDirective($templateCache, $http, sdcConfig, UserResourceClass);
- };
-
- }
-
- UserHeaderDetailsDirective.factory.$inject = ['$templateCache', '$http', 'sdcConfig', 'Sdc.Services.UserResourceService'];
-}
diff --git a/catalog-ui/app/scripts/directives/utils/expand-collapse-menu-box/expand-collaps-menu-box.ts b/catalog-ui/app/scripts/directives/utils/expand-collapse-menu-box/expand-collaps-menu-box.ts
deleted file mode 100644
index 9756ff9e49..0000000000
--- a/catalog-ui/app/scripts/directives/utils/expand-collapse-menu-box/expand-collaps-menu-box.ts
+++ /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=========================================================
- */
-/// <reference path="../../../references"/>
-module Sdc.Directives {
- 'use strict';
- export interface IExpandCollapseMenuBoxDirectiveScope extends ng.IScope {
- menuItemsGroup: Utils.MenuItemGroup;
- menuTitle: string;
- parentScope: ng.IScope;
- onMenuItemClick(menuItem: Utils.MenuItem):void;
- }
-
- export class ExpandCollapseMenuBoxDirective implements ng.IDirective {
-
- constructor(private $templateCache:ng.ITemplateCacheService) {
- }
-
- scope = {
- menuTitle: '@',
- menuItemsGroup: '=',
- parentScope: '='
- };
-
- public replace = false;
- public restrict = 'AE';
- public transclude = true;
-
- template = ():string => {
- return this.$templateCache.get('/app/scripts/directives/utils/expand-collapse-menu-box/expand-collapse-menu-box.html');
- };
-
- link = (scope:IExpandCollapseMenuBoxDirectiveScope, $elem:any) => {
- scope.onMenuItemClick = (menuItem: Utils.MenuItem):void => {
- let onSuccess = ():void => {
- scope.menuItemsGroup.selectedIndex = scope.menuItemsGroup.menuItems.indexOf(menuItem);
- };
- let onFailed = ():void => {};
- scope.parentScope[menuItem.action](menuItem.state).then(onSuccess, onFailed);
- }
- };
-
- public static factory = ($templateCache:ng.ITemplateCacheService)=> {
- return new ExpandCollapseMenuBoxDirective($templateCache);
- };
-
- }
-
- ExpandCollapseMenuBoxDirective.factory.$inject = ['$templateCache'];
-}
diff --git a/catalog-ui/app/scripts/directives/utils/expand-collapse/expand-collapse.ts b/catalog-ui/app/scripts/directives/utils/expand-collapse/expand-collapse.ts
deleted file mode 100644
index b294da6c13..0000000000
--- a/catalog-ui/app/scripts/directives/utils/expand-collapse/expand-collapse.ts
+++ /dev/null
@@ -1,136 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../../references"/>
-module Sdc.Directives {
- 'use strict';
- export interface IExpandCollapseScope extends ng.IScope {
- toggle(): void;
- collapsed: boolean;
- expandedSelector: string;
- content:string;
- isCloseOnInit:boolean;
- loadDataFunction: Function;
- isLoadingData: boolean;
- }
-
- export class ExpandCollapseDirective implements ng.IDirective {
-
- constructor(private $templateCache:ng.ITemplateCacheService) {
- }
-
- scope = {
- expandedSelector: '@',
- loadDataFunction: '&?',
- isCloseOnInit: '=?'
- };
-
- public replace = false;
- public restrict = 'AE';
- public transclude = true;
-
- template = ():string => {
- return this.$templateCache.get('/app/scripts/directives/utils/expand-collapse/expand-collapse.html');
- };
-
- link = (scope:IExpandCollapseScope, $elem:any) => {
- scope.collapsed = false;
- scope.isLoadingData = false;
- $elem.addClass('expanded');
-
-
- if(scope.isCloseOnInit) {
- window.setTimeout(function () {
- toggle();
- },0);
- }
-
- $elem.click(function(){
- toggle();
- });
-
- let expand = ():void => {
- $elem.addClass('expanded');
- scope.collapsed = false;
-
- let element = $(scope.expandedSelector)[0];
- let prevWidth = element.style.height;
- element.style.height = 'auto';
- let endWidth = getComputedStyle(element).height;
- element.style.height = prevWidth;
- element.offsetHeight; // force repaint
- element.style.transition = 'height .3s ease-in-out';
- element.style.height = endWidth;
- element.hidden = false;
- element.addEventListener('transitionend', function transitionEnd(event) {
- if (event['propertyName'] == 'height') {
- element.style.transition = '';
- element.style.height = 'auto';
- element.removeEventListener('transitionend', transitionEnd, false);
- }
- }, false)
- };
-
- let collapse = ():void => {
- $elem.removeClass('expanded');
- scope.collapsed = true;
-
- let element = $(scope.expandedSelector)[0];
- element.style.height = getComputedStyle(element).height;
- element.style.transition = 'height .5s ease-in-out';
- element.offsetHeight; // force repaint
- element.style.height = '0px';
- element.hidden = true;
- };
-
- let toggle = ():void => {
- if (scope.collapsed === true){
- if(scope.loadDataFunction) {
- scope.isLoadingData = true;
- let onSuccess = () => {
- window.setTimeout(function () {
- expand();
- scope.isLoadingData = false;
- },0);
- };
- scope.loadDataFunction().then(onSuccess);
- }
- else {
- if(scope.isLoadingData === false) {
- expand();
- }
- }
-
- } else {
- if(scope.isLoadingData === false) {
- collapse();
- }
- }
- }
-
- };
-
- public static factory = ($templateCache:ng.ITemplateCacheService)=> {
- return new ExpandCollapseDirective($templateCache);
- };
-
- }
-
- ExpandCollapseDirective.factory.$inject = ['$templateCache'];
-}
diff --git a/catalog-ui/app/scripts/directives/utils/page-selector/page-selector.html b/catalog-ui/app/scripts/directives/utils/page-selector/page-selector.html
deleted file mode 100644
index 4fbea447e2..0000000000
--- a/catalog-ui/app/scripts/directives/utils/page-selector/page-selector.html
+++ /dev/null
@@ -1,9 +0,0 @@
-<div class="i-sdc-left-sidebar-page-nav">
- <ul data-ng-class="{'expanded': expanded===true}">
- <li data-ng-repeat="item in list | filter:exceptSelectedComparator"
- data-ng-click="expanded=false"
- class="sidebar-page-nav-item"
- ui-sref="{{item.url}}">{{item.name}}</li>
- </ul>
- <div class="sidebar-page-nav-item-selected" data-ng-click="openCollapse()">{{selected}}<span data-ng-class="{'expanded': expanded===true}"></span></div>
-</div>
diff --git a/catalog-ui/app/scripts/directives/utils/page-selector/page-selector.less b/catalog-ui/app/scripts/directives/utils/page-selector/page-selector.less
deleted file mode 100644
index da70218263..0000000000
--- a/catalog-ui/app/scripts/directives/utils/page-selector/page-selector.less
+++ /dev/null
@@ -1,51 +0,0 @@
-.i-sdc-left-sidebar-page-nav {
-
- height: 64px;
-
- .sidebar-page-nav-item-selected,
- .sidebar-page-nav-item {
- .i_11;
- background-color: #e0e5e9;
- width: 100%;
- height: 64px;
- border-bottom: solid 1px #cccccc;
- line-height: 64px;
- text-align: center;
- cursor: pointer;
- vertical-align: middle;
- list-style: none;
- padding: 0;
- margin: 0;
- }
-
- .sidebar-page-nav-item-selected {
- z-index: 1010;
- position: absolute;
- top: 0px;
- }
-
- .sidebar-page-nav-item-selected span {
- .sprite;
- .sprite.table-arrow;
- position: absolute;
- top: 28px;
- margin-left: 10px;
-
- &.expanded {
- .sprite;
- .sprite.table-arrow.opened;
- top: 30px;
- }
- }
-
- ul {
- position: absolute;
- top: 0px;
- padding: 0;
- width: 100%;
- z-index: 99;
- visibility: hidden; //Need this and not display none, so I can use the function: getComputedStyle
- .box-shadow(0px 4px 2px -2px rgba(0, 0, 0, 0.36));
- }
-
-}
diff --git a/catalog-ui/app/scripts/directives/utils/page-selector/page-selector.ts b/catalog-ui/app/scripts/directives/utils/page-selector/page-selector.ts
deleted file mode 100644
index c185fe1c15..0000000000
--- a/catalog-ui/app/scripts/directives/utils/page-selector/page-selector.ts
+++ /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=========================================================
- */
-/// <reference path="../../../references"/>
-module Sdc.Directives {
- 'use strict';
-
- class ListItem {
- name;
- url;
- }
-
- export interface IPageSelectorScope extends ng.IScope {
- selected:string;
- expanded: boolean;
- list:Array<ListItem>;
- exceptSelectedComparator(actual, expected):boolean;
- openCollapse();
- }
-
- export class PageSelectorDirective implements ng.IDirective {
-
- constructor(private $templateCache:ng.ITemplateCacheService) {
- }
-
- scope = {
- list: '=',
- selected: '@',
- };
-
- public replace = true;
- public restrict = 'E';
- public transclude = false;
-
- private ulElement:HTMLElement;
- private itemHeight:number = 64;
-
- private getUlHeight = ():number => {
- let tmp:string = getComputedStyle(this.ulElement).height;
- //console.log("tmp: " + tmp);
- let ulHeight:number = parseInt(tmp.substr(0,tmp.length-2));
- //console.log("ulHeight: " + ulHeight);
- return ulHeight;
- };
-
- template = ():string => {
- return this.$templateCache.get('/app/scripts/directives/utils/page-selector/page-selector.html');
- };
-
- link = (scope:IPageSelectorScope, $elem:any) => {
- scope.expanded=false;
-
- window.setTimeout(() => {
- this.ulElement = angular.element(".i-sdc-left-sidebar-page-nav ul")[0];
- console.log("this.ulElement: " + this.ulElement);
- console.log("this.itemHeight: " + this.itemHeight);
- this.ulElement.style.top = (this.itemHeight - this.getUlHeight() - 5) + 'px';
- this.ulElement.style.visibility = 'visible';
- },10);
-
- this.ulElement = angular.element(".i-sdc-left-sidebar-page-nav ul")[0];
-
- scope.exceptSelectedComparator = (actual) => {
- if (actual.name===scope.selected) {
- return false;
- }
- return true;
- };
-
- scope.openCollapse = ():void => {
- scope.expanded=!scope.expanded;
- if (scope.expanded===true) {
- this.ulElement.style.transition = 'top 0.4s ease-out';
- this.ulElement.style.top = this.itemHeight + 'px';
- } else {
- this.ulElement.style.transition = 'top 0.4s ease-in';
- this.ulElement.style.top = (this.itemHeight - this.getUlHeight() - 5) + 'px';
- }
- };
-
- };
-
- public static factory = ($templateCache:ng.ITemplateCacheService)=> {
- return new PageSelectorDirective($templateCache);
- };
-
- }
-
- PageSelectorDirective.factory.$inject = ['$templateCache'];
-}
diff --git a/catalog-ui/app/scripts/directives/utils/sdc-keyboard-events/sdc-keyboard-events.ts b/catalog-ui/app/scripts/directives/utils/sdc-keyboard-events/sdc-keyboard-events.ts
deleted file mode 100644
index 9e61caa812..0000000000
--- a/catalog-ui/app/scripts/directives/utils/sdc-keyboard-events/sdc-keyboard-events.ts
+++ /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=========================================================
- */
-/// <reference path="../../../references"/>
-module Sdc.Directives {
- 'use strict';
-
- export interface ISdcKeyboardEventsScope extends ng.IScope {
- keyEnter:Function;
- keyShift:Function;
- keyCtrl:Function;
- keyEscape:Function;
- keySpace:Function;
- }
-
- export class SdcKeyboardEventsDirective implements ng.IDirective {
-
- constructor() {
- }
-
- scope = {
- keyEnter: '=',
- keyShift: '=',
- keyCtrl: '=',
- keyEscape: '=',
- keySpace: '='
- };
-
- public replace = false;
- public restrict = 'A';
- public transclude = false;
-
- link = (scope:ISdcKeyboardEventsScope, element:ng.IAugmentedJQuery, attrs:angular.IAttributes) => {
-
- element.bind("keydown keypress", function (event) {
- //console.log(event.which);
- switch (event.which) {
- case 13: // enter key
- scope.$apply(function (){
- if (scope.keyEnter) {
- scope.keyEnter();
- event.preventDefault();
- }
- });
- break;
- case 16: // shift key
- scope.$apply(function (){
- if (scope.keyShift) {
- scope.keyShift();
- event.preventDefault();
- }
- });
- break;
- case 17: // ctrl key
- scope.$apply(function (){
- if (scope.keyCtrl) {
- scope.keyCtrl();
- event.preventDefault();
- }
- });
- break;
- case 27: // escape key
- scope.$apply(function (){
- if (scope.keyEscape) {
- scope.keyEscape();
- event.preventDefault();
- }
- });
- break;
- case 32: // space key
- scope.$apply(function (){
- if (scope.keySpace) {
- scope.keySpace();
- event.preventDefault();
- }
- });
- break;
- }
- });
-
- };
-
- public static factory = ()=> {
- return new SdcKeyboardEventsDirective();
- };
-
- }
-
- SdcKeyboardEventsDirective.factory.$inject = [];
-}
diff --git a/catalog-ui/app/scripts/directives/utils/sdc-tags/sdc-tags.ts b/catalog-ui/app/scripts/directives/utils/sdc-tags/sdc-tags.ts
deleted file mode 100644
index 3f4147c920..0000000000
--- a/catalog-ui/app/scripts/directives/utils/sdc-tags/sdc-tags.ts
+++ /dev/null
@@ -1,97 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../../references"/>
-module Sdc.Directives {
- 'use strict';
-
- export interface ISdcTagsScope extends ng.IScope {
- tags:Array<string>;
- specialTag:string;
- newTag:string;
- formElement:ng.IFormController;
- elementName:string;
- pattern:any;
- sdcDisabled:boolean;
- maxTags:number;
- deleteTag(tag:string):void;
- addTag(tag:string):void;
- validateName():void;
- }
-
- export class SdcTagsDirective implements ng.IDirective {
-
- constructor(private $templateCache:ng.ITemplateCacheService) {
- }
-
- scope = {
- tags: '=',
- specialTag: '=',
- pattern: '=',
- sdcDisabled: '=',
- formElement: '=',
- elementName: '@',
- maxTags: '@'
- };
-
- public replace = false;
- public restrict = 'E';
- public transclude = false;
-
- template = ():string => {
- return this.$templateCache.get('/app/scripts/directives/utils/sdc-tags/sdc-tags.html');
- };
-
- link = (scope:ISdcTagsScope, element:ng.INgModelController) => {
-
- scope.deleteTag = (tag:string):void => {
- scope.tags.splice(scope.tags.indexOf(tag),1);
- };
-
- scope.addTag = ():void => {
- let valid = scope.formElement[scope.elementName].$valid;
- if (valid &&
- scope.tags.length<scope.maxTags &&
- scope.newTag &&
- scope.newTag!=='' &&
- scope.tags.indexOf(scope.newTag)===-1 &&
- scope.newTag!==scope.specialTag) {
- scope.tags.push(scope.newTag);
- scope.newTag='';
- }
- };
-
- scope.validateName = ():void => {
- if (scope.tags.indexOf(scope.newTag)>-1) {
- scope.formElement[scope.elementName].$setValidity('nameExist', false);
- }else{
- scope.formElement[scope.elementName].$setValidity('nameExist', true);
- }
- }
-
- };
-
- public static factory = ($templateCache:ng.ITemplateCacheService)=> {
- return new SdcTagsDirective($templateCache);
- };
-
- }
-
- SdcTagsDirective.factory.$inject = ['$templateCache'];
-}
diff --git a/catalog-ui/app/scripts/directives/utils/sdc_error_tooltip/sdc_error_tooltip.html b/catalog-ui/app/scripts/directives/utils/sdc_error_tooltip/sdc_error_tooltip.html
deleted file mode 100644
index 376381b8af..0000000000
--- a/catalog-ui/app/scripts/directives/utils/sdc_error_tooltip/sdc_error_tooltip.html
+++ /dev/null
@@ -1,6 +0,0 @@
-<div class="i-sdc-form-item-error-message" style="display: none;">
- <span class="i-sdc-form-item-error-icon-open"></span>
- <ng-transclude>
-
- </ng-transclude>
-</div>
diff --git a/catalog-ui/app/scripts/directives/utils/sdc_error_tooltip/sdc_error_tooltip.ts b/catalog-ui/app/scripts/directives/utils/sdc_error_tooltip/sdc_error_tooltip.ts
deleted file mode 100644
index dc30ea7f41..0000000000
--- a/catalog-ui/app/scripts/directives/utils/sdc_error_tooltip/sdc_error_tooltip.ts
+++ /dev/null
@@ -1,109 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../../references"/>
-module Sdc.Directives {
- 'use strict';
-
- export interface ISdcErrorTooltipScope extends ng.IScope {
- alignToSelector: string;
- topMargin: string;
- }
-
- export class SdcErrorTooltipDirective implements ng.IDirective {
-
- constructor(private $templateCache:ng.ITemplateCacheService) {
- }
-
- scope = {
- alignToSelector: '@', // Jquery selector to align to
- topMargin: '@' // The margin from the top, in case there is label or not the top margin is different.
- };
-
- public replace = false;
- public restrict = 'E';
- public transclude = true;
-
- template = ():string => {
- return this.$templateCache.get('/app/scripts/directives/utils/sdc_error_tooltip/sdc_error_tooltip.html');
- };
-
- link = (scope:ISdcErrorTooltipScope, $elem:any) => {
- let _self = this;
-
- $elem.addClass("i-sdc-form-item-error-icon");
-
- // Calculate the position of the elements after they loaded to the dom.
- window.setTimeout(function(){
- _self.calculatePosition(scope, $elem);
- },100);
-
- $elem.bind('mouseover', function(){
- $(".i-sdc-form-item-error-message",$elem).css("display", "block");
- });
-
- $elem.bind('mouseleave', function(){
- $(".i-sdc-form-item-error-message",$elem).css("display", "none");
- });
-
- }
-
- private calculatePosition(scope:ISdcErrorTooltipScope, $elem:any):void {
- let leftMargin = 13;
- let topMargin = scope.topMargin? parseInt(scope.topMargin) : 10;
-
- if (scope.alignToSelector) {
- // Set the position of the error, in case user add align-to-selector attribute
- let jObj = $(scope.alignToSelector);
- if (jObj.length > 0) {
- let height1 = jObj.outerHeight();
- $elem.css('left', jObj.position().left + jObj.outerWidth() + leftMargin);
- //$elem.css('top', jObj.position().top + topMargin + (height1 / 2));
- $elem.css('top', jObj.position().top + (height1 / 2) - 5); // Label margin is: 2
- }
- } else {
- // Set the position of the error, according to the input element.
- let inputElm = $elem.siblings('input');
- let textareaElm = $elem.siblings('textarea');
- let selectElm = $elem.siblings('select');
- if (inputElm.length > 0) {
- $elem.css('left', inputElm.outerWidth() + leftMargin);
- $elem.css('top', inputElm.position().top + topMargin);
- } else if (textareaElm.length > 0) {
- $elem.css('left', textareaElm.outerWidth() + leftMargin);
- let height2 = textareaElm.outerHeight();
- let elmHeight2 = $elem.outerHeight();
- //let top = textareaElm.position().top;
- $elem.css('bottom', (height2 - (elmHeight2 / 2)) / 2);
- } else if (selectElm.length > 0) {
- $elem.css('left', selectElm.outerWidth() + leftMargin);
- $elem.css('top', selectElm.position().top + topMargin);
- }
- }
- }
-
- public static factory = ($templateCache:ng.ITemplateCacheService)=> {
- return new SdcErrorTooltipDirective($templateCache);
- };
-
- }
-
- SdcErrorTooltipDirective.factory.$inject = ['$templateCache'];
-
-}
diff --git a/catalog-ui/app/scripts/directives/utils/sdc_messages/sdc-message.ts b/catalog-ui/app/scripts/directives/utils/sdc_messages/sdc-message.ts
deleted file mode 100644
index d41ef1ce04..0000000000
--- a/catalog-ui/app/scripts/directives/utils/sdc_messages/sdc-message.ts
+++ /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=========================================================
- */
-/// <reference path="../../../references"/>
-module Sdc.Directives {
- 'use strict';
- export interface ISdcMessageScope extends ng.IScope {
- sdcTranslate: string;
- sdcTranslateValues:string;
- sdcAlign:string;
- }
-
- export class SdcMessageDirective implements ng.IDirective {
-
- constructor(private $animate:any, private $filter:any, private $parse:any) {
- }
-
- scope = {
- field: '=',
- required: '@',
- pattern: '@',
- sdcTranslate: '@',
- sdcTranslateValues: '@',
- sdcAlign: '@'
- };
-
- public terminal = true;
- public restrict = 'A';
- public transclude = 'element';
- public require = '^^sdcMessages';
-
- link = (scope:ISdcMessageScope, $element:any, $attrs:any,sdcMessagesCtrl:any, $transclude:any) => {
- let self = this;
-
- let commentNode = $element[0];
-
- let records;
- let staticExp = $attrs.sdcMessage || $attrs.when;
- let dynamicExp = $attrs.sdcMessageExp || $attrs.whenExp;
- let assignRecords = function(items) {
- records = items
- ? (angular.isArray(items)
- ? items
- : items.split(/[\s,]+/))
- : null;
- sdcMessagesCtrl.reRender();
- };
-
- if (dynamicExp) {
- assignRecords(scope.$eval(dynamicExp));
- scope.$watchCollection(dynamicExp, assignRecords);
- } else {
- assignRecords(staticExp);
- }
-
- let currentElement, messageCtrl;
- sdcMessagesCtrl.register(commentNode, messageCtrl = {
- test: function (name) {
- return self.contains(records, name);
- },
- attach: function () {
- if (!currentElement) {
- $transclude(scope, function (elm) {
-
- self.$animate.enter(elm, null, $element);
- currentElement = elm;
-
- elm.addClass("i-sdc-form-item-error-message");
-
- //$compile
- let text;
- if (scope.sdcTranslate) {
- text = self.$filter('translate')(scope.sdcTranslate, scope.sdcTranslateValues);
- } else {
- //TODO: Need to handle this
- //let t = elm.html();
- //let t = angular.element("<span>" + elm.html() + "</span>");
- //text = self.$parse(t);
- }
-
- //scope.sdcTranslateValues
- elm.html(text);
-
- elm.prepend("<span class='error'></span>");
-
- // Adding OK to close the message
- //let okElm = $('<span />').attr('class', 'ok').html('OK');
- //okElm.click(function(e){
- // messageCtrl.detach();
- //});
- //elm.append(okElm);
-
- // Handle the position
- if (scope.sdcAlign){
- let choosenElm = $(scope.sdcAlign);
- if (choosenElm.length > 0) {
- let height1 = choosenElm.outerHeight();
- let elmHeight1 = elm.outerHeight();
- elm.css('left', choosenElm.outerWidth());
- elm.css('bottom', (height1 - (elmHeight1 / 2)) / 2);
- }
- } else {
- // Set the position of the error, according to the input element.
- let inputElm = elm.parent().siblings('input');
- let textareaElm = elm.parent().siblings('textarea');
- let selectElm = elm.parent().siblings('select');
- if (inputElm.length > 0) {
- elm.css('left', inputElm.outerWidth());
- elm.css('top', inputElm.position().top);
- } else if (textareaElm.length > 0) {
- elm.css('left', textareaElm.outerWidth());
- let height = textareaElm.outerHeight();
- let elmHeight = elm.outerHeight();
- //let top = textareaElm.position().top;
- elm.css('bottom', (height - (elmHeight / 2)) / 2);
- } else if (selectElm.length > 0) {
- elm.css('left', selectElm.outerWidth());
- elm.css('top', selectElm.position().top);
- }
- }
-
- // Each time we attach this node to a message we get a new id that we can match
- // when we are destroying the node later.
- let $$attachId = currentElement.$$attachId = sdcMessagesCtrl.getAttachId();
-
- // in the event that the parent element is destroyed
- // by any other structural directive then it's time
- // to deregister the message from the controller
- currentElement.on('$destroy', function () {
- if (currentElement && currentElement.$$attachId === $$attachId) {
- sdcMessagesCtrl.deregister(commentNode);
- messageCtrl.detach();
- }
- });
- });
- }
- },
- detach: function () {
- if (currentElement) {
- let elm = currentElement;
- currentElement = null;
- self.$animate.leave(elm);
- }
- }
- });
- }
-
- contains = (collection, key):any => {
- if (collection) {
- return angular.isArray(collection)
- ? collection.indexOf(key) >= 0
- : collection.hasOwnProperty(key);
- }
- }
-
- public static factory = ($animate:any, $filter:any, $parse:any)=> {
- return new SdcMessageDirective($animate, $filter, $parse);
- };
-
- }
-
- SdcMessageDirective.factory.$inject = ['$animate', '$filter', '$parse'];
-}
diff --git a/catalog-ui/app/scripts/directives/utils/sdc_messages/sdc-messages.less b/catalog-ui/app/scripts/directives/utils/sdc_messages/sdc-messages.less
deleted file mode 100644
index d8dfdbb73b..0000000000
--- a/catalog-ui/app/scripts/directives/utils/sdc_messages/sdc-messages.less
+++ /dev/null
@@ -1,10 +0,0 @@
-.ellipsis-directive-more-less {
- .a_9;
- .bold;
- .hand;
- float: right;
- margin-right: 17px;
- line-height: 23px;
- text-decoration: underline;
- text-align: left;
-}
diff --git a/catalog-ui/app/scripts/directives/utils/sdc_messages/sdc-messages.ts b/catalog-ui/app/scripts/directives/utils/sdc_messages/sdc-messages.ts
deleted file mode 100644
index f8b435b1fa..0000000000
--- a/catalog-ui/app/scripts/directives/utils/sdc_messages/sdc-messages.ts
+++ /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=========================================================
- */
-/// <reference path="../../../references"/>
-module Sdc.Directives {
- 'use strict';
- export interface ISdcMessagesScope extends ng.IScope {
- sdcMessages: any;
- editForm:ng.IFormController;
- }
-
- export class SdcMessagesDirective implements ng.IDirective {
-
- constructor() {}
-
- scope = {
- sdcMessages: '='
- };
-
- public restrict = 'AE';
- public require = 'sdcMessages';
- public controller = SdcMessagesController;
-
- /*template = ():string => {
- return this.$templateCache.get('/app/scripts/directives/utils/sdc-messages/sdc-messages.html');
- };
-
- public static factory = ($templateCache:ng.ITemplateCacheService)=> {
- return new SdcMessagesDirective($templateCache);
- };*/
-
- public static factory = ()=> {
- return new SdcMessagesDirective();
- }
-
- }
-
- export class SdcMessagesController {
-
- messages:any;
- getAttachId:Function;
- render:any;
- reRender:Function;
- register:Function;
- deregister:Function;
- head:any;
-
- static '$inject' = [
- '$element',
- '$scope',
- '$attrs',
- '$animate'
- ];
-
- constructor(private $element:JQuery,
- private $scope:ISdcMessagesScope,
- private $attrs:ng.IAttributes,
- private $animate:any
- ) {
-
- this.init();
-
- }
-
- init=():void => {
- let self = this;
-
- let ACTIVE_CLASS:string = 'ng-active';
- let INACTIVE_CLASS:string = 'ng-inactive';
-
- let ctrl = this;
- let latestKey = 0;
- let nextAttachId = 0;
-
- this.getAttachId = function getAttachId() { return nextAttachId++; };
-
- let messages = this.messages = {};
- let renderLater, cachedCollection;
-
- this.render = function(collection) {
- collection = collection || {};
-
- renderLater = false;
- cachedCollection = collection;
-
- // this is true if the attribute is empty or if the attribute value is truthy
- let multiple = self.isAttrTruthy(self.$scope, self.$attrs['sdcMessagesMultiple']) || self.isAttrTruthy(self.$scope, self.$attrs['multiple']);
-
- let unmatchedMessages = [];
- let matchedKeys = {};
- let messageItem = ctrl.head;
- let messageFound = false;
- let totalMessages = 0;
-
- // we use != instead of !== to allow for both undefined and null values
- while (messageItem != null) {
- totalMessages++;
- let messageCtrl = messageItem.message;
-
- let messageUsed = false;
- if (!messageFound) {
- _.each(collection, function(value, key) {
- if (!messageUsed && self.truthy(value) && messageCtrl.test(key)) {
- // this is to prevent the same error name from showing up twice
- if (matchedKeys[key]) return;
- matchedKeys[key] = true;
-
- messageUsed = true;
- messageCtrl.attach();
- }
- });
- }
-
- if (messageUsed) {
- // unless we want to display multiple messages then we should
- // set a flag here to avoid displaying the next message in the list
- messageFound = !multiple;
- } else {
- unmatchedMessages.push(messageCtrl);
- }
-
- messageItem = messageItem.next;
- }
-
- _.each(unmatchedMessages, function(messageCtrl) {
- messageCtrl.detach();
- });
-
- unmatchedMessages.length !== totalMessages
- ? ctrl.$animate.setClass(self.$element, ACTIVE_CLASS, INACTIVE_CLASS)
- : ctrl.$animate.setClass(self.$element, INACTIVE_CLASS, ACTIVE_CLASS);
- };
-
- self.$scope.$watchCollection('sdcMessages' || self.$attrs['for'], function(newVal:any, oldVal:any){
- ctrl.render(newVal);
- });
-
- this.reRender = function() {
- if (!renderLater) {
- renderLater = true;
- self.$scope.$evalAsync(function() {
- if (renderLater) {
- cachedCollection && ctrl.render(cachedCollection);
- }
- });
- }
- };
-
- this.register = function(comment, messageCtrl) {
- let nextKey = latestKey.toString();
- messages[nextKey] = {
- message: messageCtrl
- };
- insertMessageNode(self.$element[0], comment, nextKey);
- comment.$$sdcMessageNode = nextKey;
- latestKey++;
-
- ctrl.reRender();
- };
-
- this.deregister = function(comment) {
- let key = comment.$$sdcMessageNode;
- delete comment.$$sdcMessageNode;
- removeMessageNode(self.$element[0], comment, key);
- delete messages[key];
- ctrl.reRender();
- };
-
- function findPreviousMessage(parent, comment) {
- let prevNode = comment;
- let parentLookup = [];
- while (prevNode && prevNode !== parent) {
- let prevKey = prevNode.$$sdcMessageNode;
- if (prevKey && prevKey.length) {
- return messages[prevKey];
- }
-
- // dive deeper into the DOM and examine its children for any sdcMessage
- // comments that may be in an element that appears deeper in the list
- if (prevNode.childNodes.length && parentLookup.indexOf(prevNode) == -1) {
- parentLookup.push(prevNode);
- prevNode = prevNode.childNodes[prevNode.childNodes.length - 1];
- } else {
- prevNode = prevNode.previousSibling || prevNode.parentNode;
- }
- }
- }
-
- function insertMessageNode(parent, comment, key) {
- let messageNode = messages[key];
- if (!ctrl.head) {
- ctrl.head = messageNode;
- } else {
- let match = findPreviousMessage(parent, comment);
- if (match) {
- messageNode.next = match.next;
- match.next = messageNode;
- } else {
- messageNode.next = ctrl.head;
- ctrl.head = messageNode;
- }
- }
- }
-
- function removeMessageNode(parent, comment, key) {
- let messageNode = messages[key];
-
- let match = findPreviousMessage(parent, comment);
- if (match) {
- match.next = messageNode.next;
- } else {
- ctrl.head = messageNode.next;
- }
- }
- }
-
- isAttrTruthy = (scope, attr):any => {
- return (angular.isString(attr) && attr.length === 0) || //empty attribute
- this.truthy(scope.$eval(attr));
- }
-
- truthy = (val):any => {
- return angular.isString(val) ? val.length : !!val;
- }
-
- }
-
- SdcMessagesDirective.factory.$inject = ['$templateCache','$animate'];
-}
diff --git a/catalog-ui/app/scripts/directives/utils/sdc_messages/sdc_messages.html b/catalog-ui/app/scripts/directives/utils/sdc_messages/sdc_messages.html
deleted file mode 100644
index 09b1cad4d2..0000000000
--- a/catalog-ui/app/scripts/directives/utils/sdc_messages/sdc_messages.html
+++ /dev/null
@@ -1 +0,0 @@
-<span>aaa</span>
diff --git a/catalog-ui/app/scripts/directives/utils/smart-tooltip/smart-tooltip.ts b/catalog-ui/app/scripts/directives/utils/smart-tooltip/smart-tooltip.ts
deleted file mode 100644
index 49a57245e7..0000000000
--- a/catalog-ui/app/scripts/directives/utils/smart-tooltip/smart-tooltip.ts
+++ /dev/null
@@ -1,85 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../../references"/>
-module Sdc.Directives {
- 'use strict';
-
- export interface ISmartTooltipScope extends ng.IScope {
- sdcSmartToolip;
- }
-
- export class SmartTooltipDirective implements ng.IDirective {
-
- constructor(private $templateCache:ng.ITemplateCacheService,
- private $compile:ng.ICompileService) {
- }
-
- public replace = false;
- public restrict = 'A';
- public transclude = false;
-
- public link = (scope:ISmartTooltipScope, $elem:ng.IAugmentedJQuery, $attrs:angular.IAttributes) => {
-
- if ($elem[0].hasAttribute('style')===false){
- $elem[0].setAttribute("style", "overflow: hidden; white-space: nowrap; text-overflow: ellipsis;");
- } else {
- let styles = $elem.attr('style');
- $elem[0].setAttribute("style", styles + ";overflow: hidden; white-space: nowrap; text-overflow: ellipsis;");
- }
-
- $elem.bind('mouseenter', () => {
- if($elem[0].offsetWidth < $elem[0].scrollWidth && !$elem.attr('tooltips')){
- $attrs.$set('tooltips', 'tooltips');
- if ($attrs['sdcSmartTooltip'] && $attrs['sdcSmartTooltip'].length>0){
- $elem.attr('tooltip-content', $attrs['sdcSmartTooltip']);
- } else {
- $attrs.$set('tooltip-content', $elem.text());
- }
-
- //One possible problem arises when the ngIf is placed on the root element of the template.
- //ngIf removes the node and places a comment in it's place. Then it watches over the expression and adds/removes the actual HTML element as necessary.
- //The problem seems to be that if it is placed on the root element of the template, then a single comment is what is left from the
- //whole template (even if only temporarily), which gets ignored (I am not sure if this is browser-specific behaviour), resulting in an empty template.
-
- // Remove ng-if attribute and its value (if we reach here, we pass ng-if (ng-if===true), so we can remove it).
- $elem.removeAttr('ng-if');
- $elem.removeAttr('data-ng-if');
-
- // Remove me (the directive from the element)
- let template = $elem[0].outerHTML;
- template = template.replace('sdc-smart-tooltip=""','');
- template = template.replace('sdc-smart-tooltip="' + $elem.text() + '"','');
- //console.log(template);
-
- let el = this.$compile(template)(scope);
- console.log(el);
- $elem.replaceWith(el);
- }
- });
- };
-
- public static factory = ($templateCache:ng.ITemplateCacheService, $compile:ng.ICompileService)=> {
- return new SmartTooltipDirective($templateCache, $compile);
- };
-
- }
-
- SmartTooltipDirective.factory.$inject = ['$templateCache', '$compile'];
-}
diff --git a/catalog-ui/app/scripts/directives/utils/wizard_steps/sdc-wizard-steps.html b/catalog-ui/app/scripts/directives/utils/wizard_steps/sdc-wizard-steps.html
deleted file mode 100644
index 0c9b97a58c..0000000000
--- a/catalog-ui/app/scripts/directives/utils/wizard_steps/sdc-wizard-steps.html
+++ /dev/null
@@ -1,16 +0,0 @@
-<ul class="sdc-wizard-step">
- <li class="step" data-ng-repeat="step in steps track by $index">
- <div class="step-wrapper">
- <button class="step-index"
- data-ng-click="controllerStepClicked(step.name)"
- data-ng-class="{'selected': step.selected===true, 'valid': step.valid===true, 'disabled': !step.enabled || step.enabled===false}">
- {{$index+1}}
- </button>
- <span class="step-name"
- data-ng-class="{'selected': step.selected===true, 'valid': step.valid===true, 'disabled': !step.enabled || step.enabled===false}">{{step.name}}
- </span>
- </div>
- <div class="step-seperator"></div>
- </li>
-</ul>
-
diff --git a/catalog-ui/app/scripts/directives/utils/wizard_steps/sdc-wizard-steps.less b/catalog-ui/app/scripts/directives/utils/wizard_steps/sdc-wizard-steps.less
deleted file mode 100644
index 8b777923a0..0000000000
--- a/catalog-ui/app/scripts/directives/utils/wizard_steps/sdc-wizard-steps.less
+++ /dev/null
@@ -1,69 +0,0 @@
-@circle-radius: 18px;
-@gap: 70px;
-@gap-width: 2px;
-@valid-width: 2px;
-
-ul.sdc-wizard-step {
- padding: 0;
- margin: 0;
-
- li.step {
- position: relative;
- list-style: none;
-
- .step-wrapper {
- line-height: @circle-radius*2;
- height: @circle-radius*2;
- margin-bottom: @gap;
-
- button.step-index {
- ._w-sdc-wizard-step-btn(@circle-radius);
- z-index: 99;
- display: inline-block;
-
- &.valid {
- display: inline-block;
- }
-
- }
-
- span.step-name {
- .b_7;
- line-height: @circle-radius;
- display: inline-block;
- word-wrap: break-word;
- width: calc(~"100%" - @circle-radius*2 + 4);
- vertical-align: middle;
- padding-left: 10px;
- white-space: normal;
-
- &.selected {
- .a_7;
- font-weight: bold;
- }
-
- &.disabled {
- border: none;
- background-color: transparent;
- }
-
- }
- }
-
- .step-seperator {
- border-right: @gap-width solid @color_n;
- height: @gap + @circle-radius*2;
- position: absolute;
- top: @circle-radius*2-@circle-radius;
- left: @circle-radius - @gap-width/2;
- }
-
- }
-
- li.step:last-child {
- .step-seperator {
- display: none;
- }
- }
-
-}
diff --git a/catalog-ui/app/scripts/directives/utils/wizard_steps/sdc-wizard-steps.ts b/catalog-ui/app/scripts/directives/utils/wizard_steps/sdc-wizard-steps.ts
deleted file mode 100644
index 9cad36ab78..0000000000
--- a/catalog-ui/app/scripts/directives/utils/wizard_steps/sdc-wizard-steps.ts
+++ /dev/null
@@ -1,139 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../../references"/>
-module Sdc.Directives {
-
- 'use strict';
-
- export interface IWizardStep {
- name: string;
- selected?: boolean;
- valid?:boolean;
- enabled?:boolean;
- callback: Function;
- }
-
- export interface ISdcWizardStepScope extends ng.IScope {
- steps:Array<IWizardStep>;
- control:any;
- internalControl:any;
-
- stepClicked(stepName:string):void;
- controllerStepClicked(stepName:string):void;
-
- setStepValidity(stepName:string, valid:boolean):void;
- controllerSetStepValidity(step:IWizardStep, valid:boolean):void;
- }
-
- export interface SdcWizardStepMethods {
- unSelectAllSteps():void;
- selectStep(step:IWizardStep):void;
- }
-
- export class SdcWizardStepDirective implements ng.IDirective {
-
- constructor(private $templateCache:ng.ITemplateCacheService) {
- }
-
- scope = {
- steps: '=',
- control: '='
- };
-
- public replace = false;
- public restrict = 'E';
- public transclude = true;
- public controller = SdcWizardStepDirectiveController;
-
- template = ():string => {
- return this.$templateCache.get('/app/scripts/directives/utils/wizard_steps/sdc-wizard-steps.html');
- };
-
- link = (scope:ISdcWizardStepScope, $elem:JQuery, attr:any, controller:SdcWizardStepDirectiveController) => {
- scope.internalControl = scope.control || {};
- scope.internalControl.stepClicked = (step:string):void => {
- scope.controllerStepClicked(step);
- };
-
- scope.internalControl.setStepValidity = (step:IWizardStep, valid:boolean):void => {
- scope.controllerSetStepValidity(step, valid);
- };
- }
-
- public static factory = ($templateCache:ng.ITemplateCacheService)=> {
- return new SdcWizardStepDirective($templateCache);
- };
-
- }
-
- SdcWizardStepDirective.factory.$inject = ['$templateCache'];
-
- export class SdcWizardStepDirectiveController {
- static $inject = ['$element', '$scope'];
-
- methods:SdcWizardStepMethods = <SdcWizardStepMethods>{};
-
- constructor(public $element: JQuery,
- public $scope: ISdcWizardStepScope) {
-
- this.initMethods();
- this.initScope();
- }
-
- private initScope = ():void => {
-
- this.$scope.controllerStepClicked = (stepName:string):void => {
- let selectedStep:IWizardStep = <IWizardStep>_.find(this.$scope.steps, function (item) {
- return item.name === stepName;
- });
-
- if (selectedStep && selectedStep.enabled===true){
- let result:boolean = selectedStep.callback();
- if (result===true){
- this.methods.unSelectAllSteps();
- this.methods.selectStep(selectedStep);
- }
- }
- };
-
- this.$scope.controllerSetStepValidity = (step:IWizardStep, valid:boolean):void => {
- step.valid=valid;
- };
-
- };
-
- private initMethods = ():void => {
-
- this.methods.unSelectAllSteps = ():void => {
- this.$scope.steps.forEach(function (step) {
- step.selected = false;
- });
- }
-
- this.methods.selectStep = (step:IWizardStep):void => {
- if (step.enabled===true){
- step.selected=true;
- }
- }
- };
-
- }
-
-}
diff --git a/catalog-ui/app/scripts/filters/_category-name-filter.ts b/catalog-ui/app/scripts/filters/_category-name-filter.ts
deleted file mode 100644
index 77bbf47684..0000000000
--- a/catalog-ui/app/scripts/filters/_category-name-filter.ts
+++ /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=========================================================
- */
-/// <reference path="../references"/>
-module Sdc.Filters {
-
- export class CategoryNameFilter{
-
- constructor() {
- let filter = <CategoryNameFilter>( (name:string) => {
- if(name){
- let newName:string = _.last(name.split('/'));
- if (newName){
- return newName;
- }
- return name;
- }
- });
-
- return filter;
- }
- }
-
-}
diff --git a/catalog-ui/app/scripts/filters/capitalize-filter.ts b/catalog-ui/app/scripts/filters/capitalize-filter.ts
deleted file mode 100644
index ef0469aaa1..0000000000
--- a/catalog-ui/app/scripts/filters/capitalize-filter.ts
+++ /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=========================================================
- */
-module Sdc.Filters {
-
- export class CapitalizeFilter{
-
- constructor() {
- let filter = <CapitalizeFilter>( (sentence:string) => {
- if (sentence != null) {
- let newSentence:string = "";
- let words = sentence.split(' ');
- for (let i=0; i < words.length; ++i){
- let word:string = words[i].toLowerCase();
- newSentence += word.substring(0,1).toUpperCase()+word.substring(1) + ' ';
- }
- return newSentence.trim();
- }else{
- return sentence;
- }
- });
-
- return filter;
- }
- }
-
-}
diff --git a/catalog-ui/app/scripts/filters/catalog-status-filter.ts b/catalog-ui/app/scripts/filters/catalog-status-filter.ts
deleted file mode 100644
index 5b382f6513..0000000000
--- a/catalog-ui/app/scripts/filters/catalog-status-filter.ts
+++ /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=========================================================
- */
-/// <reference path="../references"/>
-/**
- * Created by obarda on 19/08/2015.
- */
-module Sdc.Filters {
-
- export class CatalogStatusFilter{
-
- constructor() {
- let filter = <CatalogStatusFilter>( (statuses:any) => {
- let filtered = [];
- angular.forEach(statuses, function(status) {
- filtered.push(status);
- });
- return filtered;
- });
-
- return filter;
- }
- }
-
-}
diff --git a/catalog-ui/app/scripts/filters/category-icon-filter.ts b/catalog-ui/app/scripts/filters/category-icon-filter.ts
deleted file mode 100644
index 6916a13399..0000000000
--- a/catalog-ui/app/scripts/filters/category-icon-filter.ts
+++ /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=========================================================
- */
-/// <reference path="../references"/>
-module Sdc.Filters {
-
- export class CategoryIconFilter{
-
- constructor() {
- let filter = <CategoryIconFilter>( (category:string) => {
- let map = {
- 'Application Layer 4+/Application Servers': ['applicationServer', 'server'],
- 'Application Layer 4+/Media Servers': ['applicationServer', 'server'],
- 'Application Layer 4+/Web Server': ['applicationServer', 'server'],
- 'Network Layer 4+/Common Network Resources': ['network', 'loadBalancer'],
- 'Generic/Infrastructure': ['objectStorage', 'compute'],
- 'Generic/Network Elements': ['port', 'network', 'router'],
- 'Application Layer 4+/Database': ['database'],
- 'Generic/Database': ['database'],
- 'Network Layer 2-3/Router': ['router'],
- 'Network Layer 2-3/Gateway': ['gateway'],
- 'Network Layer 2-3/LAN Connectors': ['connector'],
- 'Network Layer 2-3/WAN Connectors': ['connector'],
- 'Application Layer 4+/Border Elements': ['borderElement'],
- 'Application Layer 4+/Load Balancer': ['loadBalancer'],
- 'Application Layer 4+/Call Control': ['call_controll'],
- 'VoIP Call Control': ['call_controll'],
- 'Mobility': ['mobility'],
- 'Network L1-3': ['network_l_1-3'],
- 'Network L4': ['network_l_4']
- }
- return map[category];
-
- });
- return filter;
- }
- }
-}
diff --git a/catalog-ui/app/scripts/filters/category-type-filter.ts b/catalog-ui/app/scripts/filters/category-type-filter.ts
deleted file mode 100644
index 482e566e5a..0000000000
--- a/catalog-ui/app/scripts/filters/category-type-filter.ts
+++ /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=========================================================
- */
-/// <reference path="../references"/>
-module Sdc.Filters {
-
- export class CategoryTypeFilter {
-
- static $inject = ['Sdc.Services.CacheService'];
-
- constructor(cacheService:Services.CacheService) {
- let filter = <CategoryTypeFilter> (categories:any, selectedType:Array<string>) => {
-
- if (!selectedType.length)
- return categories;
-
- let filteredCategories:any = [];
- selectedType.forEach((type:string) => {
- filteredCategories = filteredCategories.concat(cacheService.get(type.toLowerCase() + 'Categories'));
- });
-
- return _.filter(categories, function (category:any) {
- return filteredCategories.indexOf(category) != -1;
- });
- };
- return filter;
- }
- }
-}
diff --git a/catalog-ui/app/scripts/filters/graph-resource-name-filter.ts b/catalog-ui/app/scripts/filters/graph-resource-name-filter.ts
deleted file mode 100644
index 63f0d780be..0000000000
--- a/catalog-ui/app/scripts/filters/graph-resource-name-filter.ts
+++ /dev/null
@@ -1,47 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../references"/>
-module Sdc.Filters {
-
- export class GraphResourceNameFilter {
-
-
- constructor() {
- let filter = <GraphResourceNameFilter>( (name:string) => {
- let context = document.createElement("canvas").getContext("2d");
- context.font = "13px Arial";
-
- if(67 < context.measureText(name).width) {
- let newLen = name.length - 3;
- let newName = name.substring(0, newLen);
-
- while (59 < (context.measureText(newName).width)) {
- newName = newName.substring(0, (--newLen));
- }
- return newName + '...';
- }
-
- return name;
- });
- return filter;
- }
- }
-
-}
diff --git a/catalog-ui/app/scripts/filters/product-subcategory-name-filter.ts b/catalog-ui/app/scripts/filters/product-subcategory-name-filter.ts
deleted file mode 100644
index 66d7a76c28..0000000000
--- a/catalog-ui/app/scripts/filters/product-subcategory-name-filter.ts
+++ /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=========================================================
- */
-module Sdc.Filters {
-
- export class ProductSubCategoryNameFilter{
-
- constructor() {
- let filter = <CategoryNameFilter>( (name:string) => {
- if(name){
- let newName:string = _.last(name.split('/'));
- if (newName){
- return newName;
- }
- return name;
- }
- });
-
- return filter;
- }
- }
-
-}
diff --git a/catalog-ui/app/scripts/filters/relation-name-fllter.ts b/catalog-ui/app/scripts/filters/relation-name-fllter.ts
deleted file mode 100644
index 7d97eea372..0000000000
--- a/catalog-ui/app/scripts/filters/relation-name-fllter.ts
+++ /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=========================================================
- */
-/// <reference path="../references"/>
-module Sdc.Filters {
-
- export class RelationNameFilter{
-
- constructor() {
- let filter = <RelationNameFilter>( (relationshipType:string) => {
- let icons: Array<string> = [
- 'AttachesTo',
- 'BindsTo',
- 'DependsOn',
- 'HostedOn',
- 'LinksTo',
- 'RoutesTo'
- ];
-
- let result:string = 'ConnectedTo';
-
- if (relationshipType) {
- let arr = relationshipType.split('.'); // looks like tosca.relationships.AttachesTo
- relationshipType = arr[arr.length - 1];
- if (icons.indexOf(relationshipType) > -1) {
- result = relationshipType;
- }
- }
-
- return result;
- });
-
- return filter;
- }
- }
-
-}
diff --git a/catalog-ui/app/scripts/filters/resource-type-filter.ts b/catalog-ui/app/scripts/filters/resource-type-filter.ts
deleted file mode 100644
index 6aa79dae76..0000000000
--- a/catalog-ui/app/scripts/filters/resource-type-filter.ts
+++ /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=========================================================
- */
-/// <reference path="../references"/>
-module Sdc.Filters {
-
- export class ResourceTypeFilter{
- static '$inject' = ['Sdc.Services.CacheService'];
- constructor(cacheService:Services.CacheService)
- {
- let filter = <ResourceTypeFilter> (resourceType:string) => {
- let uiConfiguration:any = cacheService.get('UIConfiguration');
-
- if(uiConfiguration.resourceTypes && uiConfiguration.resourceTypes[resourceType]){
- return uiConfiguration.resourceTypes[resourceType];
- }
- return resourceType;
- }
- return filter;
- }
- }
-}
diff --git a/catalog-ui/app/scripts/filters/string-to-date-filter.ts b/catalog-ui/app/scripts/filters/string-to-date-filter.ts
deleted file mode 100644
index 1c4919d419..0000000000
--- a/catalog-ui/app/scripts/filters/string-to-date-filter.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../references"/>
-module Sdc.Filters {
-
- export class StringToDateFilter{
-
- constructor() {
- let filter = <StringToDateFilter>( (date:string) => {
- if(date){
- return new Date(date.replace(" UTC", '').replace(" ", 'T') + '+00:00');
- }
- });
- return filter;
- }
- }
-}
diff --git a/catalog-ui/app/scripts/filters/truncate-filter.ts b/catalog-ui/app/scripts/filters/truncate-filter.ts
deleted file mode 100644
index 1470e5937d..0000000000
--- a/catalog-ui/app/scripts/filters/truncate-filter.ts
+++ /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=========================================================
- */
-module Sdc.Filters {
-
- export class TruncateFilter {
- constructor() {
- let filter = <TruncateFilter> (str:string, length:number) => {
- if (str.length <= length) {
- return str;
- }
-
- //if(str[length - 1] === ' '){
- // return str.substring(0, length - 1) + '...';
- //}
-
- let char;
- let index = length;
- while (char !== ' ' && index !== 0) {
- index--;
- char = str[index];
- }
- if (index === 0) {
- return (index === 0) ? str : str.substring(0, length - 3) + '...';
- }
- return (index === 0) ? str : str.substring(0, index) + '...';
- };
- return filter;
- }
-
- }
-}
diff --git a/catalog-ui/app/scripts/models/activity.ts b/catalog-ui/app/scripts/models/activity.ts
deleted file mode 100644
index 4f8648d6b7..0000000000
--- a/catalog-ui/app/scripts/models/activity.ts
+++ /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=========================================================
- */
-/**
- * Created by obarda on 19/11/2015.
- */
-/// <reference path="../references"/>
-module Sdc.Models {
- 'use strict';
-
- /*this is in uppercase because of the server response*/
- export class Activity{
- TIMESTAMP: string;
- ACTION:string;
- MODIFIER:string;
- STATUS:string;
- DESC:string;
- COMMENT:string;
- //custom data
- public dateFormat:string;
-
- constructor() {
- }
- public toJSON = ():any => {
- this.dateFormat = undefined;
- return this;
- };
-
- }
-}
-
-
diff --git a/catalog-ui/app/scripts/models/app-config.ts b/catalog-ui/app/scripts/models/app-config.ts
deleted file mode 100644
index f0a316fc92..0000000000
--- a/catalog-ui/app/scripts/models/app-config.ts
+++ /dev/null
@@ -1,232 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../references"/>
-module Sdc.Models {
-
- 'use strict';
- export interface IApi {
- baseUrl:string;
-
- //***** NEW API *******//
- GET_component: string;
- PUT_component: string;
- GET_component_validate_name: string;
- POST_changeLifecycleState: string;
- component_api_root:string;
- welcome_page_video_url:string;
- //*********//
-
- GET_user: string;
- GET_user_authorize: string;
- GET_all_users: string;
- POST_create_user;
- DELETE_delete_user;
- POST_edit_user_role;
- GET_resource: string;
- GET_resources_latestversion_notabstract:string;
- GET_resources_certified_not_abstract: string;
- GET_resources_certified_abstract: string;
- PUT_resource: string;
- GET_resource_property: string;
- GET_resource_artifact:string;
- GET_download_instance_artifact:string;
- POST_instance_artifact:string;
- GET_resource_additional_information:string;
- GET_service_artifact:string;
- GET_resource_interface_artifact:string;
- GET_resource_api_artifact:string;
- GET_resource_validate_name: string;
- GET_resource_artifact_types: string;
- GET_activity_log: string;
- GET_configuration_ui: string;
- GET_service: string;
- PUT_product: string;
- GET_product: string;
- GET_ecomp_menu_items: string;
- GET_product_validate_name: string;
- GET_service_validate_name: string;
- GET_service_distributions: string;
- GET_service_distributions_components: string;
- POST_service_distribution_deploy: string;
- GET_element: string;
- GET_catalog: string;
- GET_resource_category: string;
- GET_service_category: string;
- resource_instance: string;
- GET_resource_instance_property: string;
- GET_relationship:string;
- GET_lifecycle_state_resource:string;
- GET_lifecycle_state_CHECKIN:string;
- GET_lifecycle_state_CERTIFICATIONREQUEST:string;
- GET_lifecycle_state_UNDOCHECKOUT:string;
- root: string;
- PUT_service: string;
- GET_download_artifact: string;
- GET_SDC_Version: string;
- GET_categories: string;
- POST_category: string;
- POST_subcategory: string;
- POST_change_instance_version: string;
- GET_requirements_capabilities: string;
- GET_onboarding: string;
- GET_component_from_csar_uuid: string;
- kibana:string;
-
- //Added by Ikram -- starts
- GET_product_category: string;
- GET_product_category_temp: string;
- GET_product_sub_category: string;
- //Added by Ikram -- ends
-
- }
-
- export interface ILogConfig {
- minLogLevel: string;
- prefix: string;
- }
-
- export interface ICookie {
- junctionName: string;
- prefix: string;
- userIdSuffix: string;
- userFirstName: string;
- userLastName: string;
- userEmail: string;
- }
- export interface IUserTypes {
- admin: any;
- designer: any;
- tester: any;
- }
-
- export interface IConfigStatuses {
- inDesign: IConfigStatus;
- readyForCertification: IConfigStatus;
- inCertification: IConfigStatus;
- certified: IConfigStatus;
- distributed: IConfigStatus;
-
- }
-
- export interface IConfigStatus {
- name: string;
- values: Array<string>;
- }
-
- export interface IConfigRoles {
- ADMIN: IConfigRole;
- DESIGNER: IConfigRole;
- TESTER: IConfigRole;
- OPS: IConfigRole;
- GOVERNOR: IConfigRole;
- PRODUCT_MANAGER: IConfigRole;
- PRODUCT_STRATEGIST: IConfigRole;
- }
-
- export interface IConfigRole {
- pages: Array<string>;
- states: IConfigState;
- }
-
- export interface IConfigState {
- NOT_CERTIFIED_CHECKOUT: Array<IConfigDistribution>;
- NOT_CERTIFIED_CHECKIN: Array<IConfigDistribution>;
- READY_FOR_CERTIFICATION: Array<IConfigDistribution>;
- CERTIFICATION_IN_PROGRESS: Array<IConfigDistribution>;
- CERTIFIED: Array<IConfigDistribution>;
- }
-
- export interface IConfigDistribution {
- DISTRIBUTION_NOT_APPROVED: Array<ConfigMenuItem>;
- DISTRIBUTION_APPROVED: Array<ConfigMenuItem>;
- DISTRIBUTED: Array<ConfigMenuItem>;
- DISTRIBUTION_REJECTED: Array<ConfigMenuItem>;
- }
-
- export interface IConfirmationMessage {
- showComment: boolean;
- title: string;
- message: string;
- }
-
- export interface IConfirmationMessages {
- checkin: IConfirmationMessage;
- checkout: IConfirmationMessage;
- certify: IConfirmationMessage;
- failCertification: IConfirmationMessage;
- certificationRequest: IConfirmationMessage;
- approve: IConfirmationMessage;
- reject: IConfirmationMessage;
- }
-
- export interface IAlertMessage {
- title: string;
- message: string;
- }
-
- export interface IAlertMessages {
- deleteInstance: IAlertMessage;
- exitWithoutSaving: IConfirmationMessage;
- }
-
- class ConfigMenuItem {
- text:string;
- action:string;
- url:string;
- disable:boolean = false;
- }
-
- export interface IAppConfigurtaion {
- environment:string;
- api: IApi;
- resourceTypesFilter:IResourceTypesFilter;
- logConfig: ILogConfig;
- cookie: ICookie;
- imagesPath: string;
- toscaFileExtension:string;
- csarFileExtension:string;
- testers: Array<ITester>
- tutorial:any;
- roles: Array<string>;
- cpEndPointInstances: Array<string>;
- openSource:boolean;
- }
- export interface IResourceTypesFilter {
- resource: Array<string>;
- }
-
- export interface ITester {
- email: string;
- }
-
- export interface IAppMenu {
- roles: IConfigRoles;
- confirmationMessages: IConfirmationMessages;
- alertMessages: IAlertMessages;
- statuses: IConfigStatuses;
- catalogMenuItem: any;
- categoriesDictionary:any;
- canvas_buttons:Object;
- component_workspace_menu_option: any;
- LifeCycleStatuses: any;
- DistributionStatuses: any;
- ChangeLifecycleStateButton:any;
- }
-}
diff --git a/catalog-ui/app/scripts/models/artifacts.ts b/catalog-ui/app/scripts/models/artifacts.ts
deleted file mode 100644
index 8ee98d90d1..0000000000
--- a/catalog-ui/app/scripts/models/artifacts.ts
+++ /dev/null
@@ -1,115 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../references"/>
-module Sdc.Models {
- 'use strict';
-
- //this object contains keys, each key contain ArtifactModel
- export class ArtifactGroupModel{
- constructor(artifacts?:Models.ArtifactGroupModel) {
- _.forEach(artifacts, (artifact:Models.ArtifactModel, key) => {
- this[key] = new Models.ArtifactModel(artifact);
- });
- }
-
- public filteredByType (type:string): Models.ArtifactGroupModel {
- return JSON.parse(JSON.stringify(_.pick(this, (artifact)=>{ return artifact.artifactType == type})));
- };
- }
-
- export class ArtifactModel {
-
- artifactDisplayName:string;
- artifactGroupType:string;
- uniqueId:string;
- artifactName:string;
- artifactLabel:string;
- artifactType:string;
- artifactUUID:string;
- artifactVersion:string;
- creatorFullName:string;
- creationDate:number;
- lastUpdateDate:number;
- description:string;
- mandatory:boolean;
- serviceApi:boolean;
- payloadData:string;
- timeout:number;
- esId:string;
- "Content-MD5":string;
- artifactChecksum:string;
- apiUrl:string;
- heatParameters:Array<any>;
- generatedFromId:string;
-
- //custom properties
- selected:boolean;
- originalDescription:string;
-
- constructor(artifact?:ArtifactModel) {
- if(artifact) {
- this.artifactDisplayName = artifact.artifactDisplayName;
- this.artifactGroupType = artifact.artifactGroupType;
- this.uniqueId = artifact.uniqueId;
- this.artifactName = artifact.artifactName;
- this.artifactLabel = artifact.artifactLabel;
- this.artifactType = artifact.artifactType;
- this.artifactUUID = artifact.artifactUUID;
- this.artifactVersion = artifact.artifactVersion;
- this.creatorFullName = artifact.creatorFullName;
- this.creationDate = artifact.creationDate;
- this.lastUpdateDate = artifact.lastUpdateDate;
- this.description = artifact.description;
- this.mandatory = artifact.mandatory;
- this.serviceApi = artifact.serviceApi;
- this.payloadData = artifact.payloadData;
- this.timeout = artifact.timeout;
- this.esId = artifact.esId;
- this["Content-MD5"] = artifact["Content-MD5"];
- this.artifactChecksum = artifact.artifactChecksum;
- this.apiUrl = artifact.apiUrl;
- this.heatParameters = _.sortBy(artifact.heatParameters, 'name');
- this.generatedFromId = artifact.generatedFromId;
- this.selected = artifact.selected ? artifact.selected : false;
- this.originalDescription = artifact.description;
- }
- }
-
- public isHEAT = ():boolean => {
- return Utils.Constants.ArtifactType.HEAT === this.artifactType.substring(0,4);
- };
-
- // public isEditableInInstanceLevel = ():boolean => {
- // return true;
- // };
-
- public isThirdParty = ():boolean => {
- return _.has(Utils.Constants.ArtifactType.THIRD_PARTY_RESERVED_TYPES, this.artifactType);
- };
-
- public toJSON = ():any => {
- this.selected = undefined;
- this.originalDescription = undefined;
- return this;
- };
- }
-}
-
-
diff --git a/catalog-ui/app/scripts/models/aschema-property.ts b/catalog-ui/app/scripts/models/aschema-property.ts
deleted file mode 100644
index 7ecc85c302..0000000000
--- a/catalog-ui/app/scripts/models/aschema-property.ts
+++ /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=========================================================
- */
-/**
- * Created by osonsino on 16/05/2016.
- */
-/// <reference path="../references"/>
-module Sdc.Models {
- 'use strict';
-
- export class SchemaPropertyGroupModel{
- property: SchemaProperty;
-
- constructor(schemaProperty?:Models.SchemaProperty) {
- this.property = schemaProperty;
- }
- }
-
- export class SchemaProperty {
-
- type: string;
- required: boolean;
- definition: boolean;
- description: string;
- password: boolean;
- //custom properties
- simpleType: string;
-
- constructor(schemaProperty?:SchemaProperty) {
- if(schemaProperty) {
- this.type = schemaProperty.type;
- this.required = schemaProperty.required;
- this.definition = schemaProperty.definition;
- this.description = schemaProperty.description;
- this.password = schemaProperty.password;
- this.simpleType = schemaProperty.simpleType;
- }
- }
-
- public toJSON = ():any => {
- this.simpleType = undefined;
- return this;
- };
- }
-}
-
-
diff --git a/catalog-ui/app/scripts/models/attributes.ts b/catalog-ui/app/scripts/models/attributes.ts
deleted file mode 100644
index ea4c7a5a23..0000000000
--- a/catalog-ui/app/scripts/models/attributes.ts
+++ /dev/null
@@ -1,139 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../references"/>
-module Sdc.Models {
- 'use strict';
-
- export class AttributesGroup {
- constructor(attributesObj?:Models.AttributesGroup) {
- _.forEach(attributesObj, (attributes:Array<Models.AttributeModel>, instance) => {
- this[instance] = [];
- _.forEach(attributes, (attribute:Models.AttributeModel):void => {
- attribute.resourceInstanceUniqueId = instance;
- attribute.readonly = true;
- this[instance].push(new Models.AttributeModel(attribute));
- });
- });
- }
- }
-
- export interface IAttributeModel {
-
- //server data
- uniqueId:string;
- name:string;
- defaultValue:string;
- description:string;
- type:string;
- schema:Models.SchemaAttributeGroupModel;
- status:string;
- value:string;
- hidden:boolean;
- parentUniqueId:string;
- //custom data
- resourceInstanceUniqueId:string;
- readonly:boolean;
- valueUniqueUid:string;
- }
-
- export class AttributeModel implements IAttributeModel {
-
- //server data
- uniqueId:string;
- name:string;
- defaultValue:string;
- description:string;
- type:string;
- schema:Models.SchemaAttributeGroupModel;
- status:string;
- value:string;
- hidden:boolean;
- parentUniqueId:string;
- //custom data
- resourceInstanceUniqueId:string;
- readonly:boolean;
- valueUniqueUid:string;
-
- constructor(attribute?:Models.AttributeModel) {
- if (attribute) {
- this.uniqueId = attribute.uniqueId;
- this.name = attribute.name;
- this.defaultValue = attribute.defaultValue;
- this.description = attribute.description;
- this.type = attribute.type;
- this.status = attribute.status;
- this.schema = attribute.schema;
- this.value = attribute.value;
- this.hidden = attribute.hidden;
- this.parentUniqueId = attribute.parentUniqueId;
- this.resourceInstanceUniqueId = attribute.resourceInstanceUniqueId;
- this.readonly = attribute.readonly;
- this.valueUniqueUid = attribute.valueUniqueUid;
- }
-
- if (!this.schema || !this.schema.property) {
- this.schema = new Models.SchemaPropertyGroupModel(new Models.SchemaProperty());
- } else {
- //forcing creating new object, so editing different one than the object in the table
- this.schema = new Models.SchemaAttributeGroupModel(new Models.SchemaAttribute(this.schema.property));
- }
-
- this.convertValueToView();
- }
-
- public convertToServerObject:Function = ():string => {
- if (this.defaultValue && this.type === 'map') {
- this.defaultValue = '{' + this.defaultValue + '}';
- }
- if (this.defaultValue && this.type === 'list') {
- this.defaultValue = '[' + this.defaultValue + ']';
- }
- this.defaultValue = this.defaultValue != "" && this.defaultValue != "[]" && this.defaultValue != "{}" ? this.defaultValue : null;
-
- return JSON.stringify(this);
- };
-
-
- public convertValueToView() {
- //unwrapping value {} or [] if type is complex
- if (this.defaultValue && (this.type === 'map' || this.type === 'list') &&
- ['[', '{'].indexOf(this.defaultValue.charAt(0)) > -1 &&
- [']', '}'].indexOf(this.defaultValue.slice(-1)) > -1) {
- this.defaultValue = this.defaultValue.slice(1, -1);
- }
-
- //also for value - for the modal in canvas
- if (this.value && (this.type === 'map' || this.type === 'list') &&
- ['[', '{'].indexOf(this.value.charAt(0)) > -1 &&
- [']', '}'].indexOf(this.value.slice(-1)) > -1) {
- this.value = this.value.slice(1, -1);
- }
- }
-
- public toJSON = ():any => {
- if (!this.resourceInstanceUniqueId) {
- this.value = undefined;
- }
- this.readonly = undefined;
- this.resourceInstanceUniqueId = undefined;
- return this;
- };
- }
-}
diff --git a/catalog-ui/app/scripts/models/capability.ts b/catalog-ui/app/scripts/models/capability.ts
deleted file mode 100644
index 815be5a389..0000000000
--- a/catalog-ui/app/scripts/models/capability.ts
+++ /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=========================================================
- */
-/**
- * Created by obarda on 4/20/2016.
- */
-/// <reference path="../references"/>
-module Sdc.Models {
- 'use strict';
-
- //this is an object contains keys, when each key has matching array.
- // for example: key = tosca.capabilities.network.Linkable and the match array is array of capabilities objects
- export class CapabilitiesGroup {
- constructor(capabilityGroupObj?:Models.CapabilitiesGroup) {
- _.forEach(capabilityGroupObj, (capabilitiesArrayObj:Array<Models.Capability>, instance) => {
- this[instance] = [];
- _.forEach(capabilitiesArrayObj, (capability:Models.Capability):void => {
- this[instance].push(new Models.Capability(capability));
- });
- });
- }
-
- public findValueByKey(keySubstring:string):Array<Models.Capability> {
- let key:string = _.find(Object.keys(this), (key)=> {
- return _.includes(key.toLowerCase(), keySubstring);
- });
- return this[key];
- }
- }
-
- export class Capability {
-
- //server data
- name:string;
- ownerId:string;
- ownerName:string;
- type:string;
- uniqueId:string;
- capabilitySources:Array<String>;
- minOccurrences:string;
- maxOccurrences:string;
- properties:Array<Models.PropertyModel>;
- description:string;
- validSourceTypes:Array<string>;
- //custom
- selected:boolean;
- filterTerm:string;
-
- constructor(capability?:Capability) {
-
- if (capability) {
- //server data
- this.name = capability.name;
- this.ownerId = capability.ownerId;
- this.ownerName = capability.ownerName;
- this.type = capability.type;
- this.uniqueId = capability.uniqueId;
- this.capabilitySources = capability.capabilitySources;
- this.minOccurrences = capability.minOccurrences;
- this.maxOccurrences = capability.maxOccurrences;
- this.properties = capability.properties;
- this.description = capability.description;
- this.validSourceTypes = capability.validSourceTypes;
- this.selected = capability.selected;
- this.initFilterTerm();
-
- }
- }
-
- public getFullTitle():string {
- let maxOccurrences:string = this.maxOccurrences === 'UNBOUNDED' ? '∞' : this.maxOccurrences;
- return this.ownerName + ': ' + this.name + ': [' + this.minOccurrences + ', ' + maxOccurrences + ']';
- }
-
- public toJSON = ():any => {
- this.selected = undefined;
- this.filterTerm = undefined;
- return this;
- };
-
- private initFilterTerm = ():void =>{
- this.filterTerm = this.name + " " +
- (this.type ? (this.type.substring("tosca.capabilities.".length) + " " ) : "") +
- (this.description||"") + " " +
- (this.ownerName||"") + " " +
- (this.validSourceTypes ? (this.validSourceTypes.join(',') + " ") : "") +
- this.minOccurrences+","+this.maxOccurrences;
- if(this.properties && this.properties.length){
- _.forEach(this.properties,(prop:Models.PropertyModel)=>{
- this.filterTerm += " "+ prop.name +
- " " + (prop.description||"") +
- " " + prop.type +
- (prop.schema && prop.schema.property?(" " + prop.schema.property.type):"");
- });
- }
- }
- }
-}
-
-
diff --git a/catalog-ui/app/scripts/models/category.ts b/catalog-ui/app/scripts/models/category.ts
deleted file mode 100644
index 730460cbc0..0000000000
--- a/catalog-ui/app/scripts/models/category.ts
+++ /dev/null
@@ -1,67 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../references"/>
-module Sdc.Models {
- 'use strict';
-
- export class ICategoryBase {
-
- //server properties
- name: string;
- normalizedName: string;
- uniqueId:string;
- icons: Array<string>;
-
- //custom properties
- filterTerms: string;
- isDisabled: boolean;
- filteredGroup: Array<Models.IGroup>;
-
- constructor(category?: ICategoryBase){
- if (category) {
- this.name = category.name;
- this.normalizedName = category.normalizedName;
- this.icons = category.icons;
- this.filterTerms = category.filterTerms;
- this.isDisabled = category.isDisabled;
- this.filteredGroup = category.filteredGroup;
- }
- }
- }
-
- export class IMainCategory extends ICategoryBase {
- subcategories:Array<ISubCategory>;
- constructor();
- constructor(category?: IMainCategory){
- super(category);
- if (category) {
- this.subcategories = category.subcategories;
- }
- }
- }
-
- export class ISubCategory extends ICategoryBase {
- groupings:Array<ICategoryBase>;
- }
-
- export interface IGroup extends ICategoryBase {
- }
-
-}
diff --git a/catalog-ui/app/scripts/models/comments.ts b/catalog-ui/app/scripts/models/comments.ts
deleted file mode 100644
index 0f7643690d..0000000000
--- a/catalog-ui/app/scripts/models/comments.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../references"/>
-module Sdc.Models {
- 'use strict';
-
- export class AsdcComment{
- public userRemarks: string;
-
- constructor() {
- }
- }
-}
-
-
-
diff --git a/catalog-ui/app/scripts/models/components/component.ts b/catalog-ui/app/scripts/models/components/component.ts
deleted file mode 100644
index c0fb3a9fbb..0000000000
--- a/catalog-ui/app/scripts/models/components/component.ts
+++ /dev/null
@@ -1,828 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/**
- * Created by obarda on 2/4/2016.
- */
-/// <reference path="../../references"/>
-module Sdc.Models.Components {
- 'use strict';
- import Util = jasmine.Util;
-
- export interface IComponent {
-
- //---------------------------------------------- API CALLS ----------------------------------------------------//
-
- //Component API
- getComponent():ng.IPromise<Models.Components.Component>;
- updateComponent():ng.IPromise<Models.Components.Component>;
- createComponentOnServer():ng.IPromise<Models.Components.Component>;
- changeLifecycleState(state:string, commentObj:Models.AsdcComment):ng.IPromise<Models.Components.Component>;
- validateName(newName:string):ng.IPromise<Models.IValidate>;
- updateRequirementsCapabilities():ng.IPromise<any>;
-
- //Artifacts API
- addOrUpdateArtifact(artifact:ArtifactModel):ng.IPromise<Models.ArtifactModel>;
- updateMultipleArtifacts(artifacts:Array<Models.ArtifactModel>):ng.IPromise<any>;
- deleteArtifact(artifactId:string, artifactLabel:string):ng.IPromise<Models.ArtifactModel>;
- downloadInstanceArtifact(artifactId:string):ng.IPromise<Models.IFileDownload>;
- downloadArtifact(artifactId:string):ng.IPromise<Models.IFileDownload>;
-
- //Property API
- addOrUpdateProperty(property:Models.PropertyModel):ng.IPromise<Models.PropertyModel>;
- deleteProperty(propertyId:string):ng.IPromise<Models.PropertyModel>;
- updateInstanceProperty(property:Models.PropertyModel):ng.IPromise<Models.PropertyModel>;
-
- //Attribute API
- deleteAttribute(attributeId:string):ng.IPromise<Models.AttributeModel>;
- addOrUpdateAttribute(attribute:Models.AttributeModel):ng.IPromise<Models.AttributeModel>;
- updateInstanceAttribute(attribute:Models.AttributeModel):ng.IPromise<Models.AttributeModel>;
-
-
-
-
- //Component Instance API
- createComponentInstance(componentInstance:Models.ComponentsInstances.ComponentInstance):ng.IPromise<Models.ComponentsInstances.ComponentInstance>;
- deleteComponentInstance(componentInstanceId:string):ng.IPromise<Models.ComponentsInstances.ComponentInstance>;
- addOrUpdateInstanceArtifact(artifact:Models.ArtifactModel):ng.IPromise<Models.ArtifactModel>;
- deleteInstanceArtifact(artifactId:string, artifactLabel:string):ng.IPromise<Models.ArtifactModel>;
- uploadInstanceEnvFile(artifact:Models.ArtifactModel): ng.IPromise<Models.ArtifactModel>;
- changeComponentInstanceVersion(componentUid:string):ng.IPromise<Models.Components.Component>;
- updateComponentInstance(componentInstance:Models.ComponentsInstances.ComponentInstance): ng.IPromise<Models.ComponentsInstances.ComponentInstance>;
- updateMultipleComponentInstances(instances: Array<Models.ComponentsInstances.ComponentInstance>):ng.IPromise<Array<Models.ComponentsInstances.ComponentInstance>>;
-
- //Inputs API
- getComponentInstanceInputProperties(componentInstanceId: string, inputId: string):ng.IPromise<Array<Models.PropertyModel>>
- getComponentInputs(componentId: string):ng.IPromise<Array<Models.InputModel>>;
-
- createRelation(link:Models.RelationshipModel):ng.IPromise<Models.RelationshipModel>;
- deleteRelation(link:Models.RelationshipModel):ng.IPromise<Models.RelationshipModel>;
-
-
- //Modules
- getModuleForDisplay(moduleId:string):ng.IPromise<Models.DisplayModule>;
- updateGroupMetadata(group:Models.Module):ng.IPromise<Models.Module>;
- //---------------------------------------------- HELP FUNCTIONS ----------------------------------------------------//
-
- getComponentSubType():string;
- isAlreadyCertified():boolean;
- isProduct():boolean;
- isService():boolean;
- isResource():boolean;
- isComplex():boolean;
- getAdditionalInformation():Array<Models.AdditionalInformationModel>;
- getAllVersionsAsSortedArray():Array<any>;
- getStatus(sdcMenu:Models.IAppMenu):string;
- }
-
-
- export class Component implements IComponent {
-
- //server data
- public abstract:string;
- public uniqueId:string;
- public uuid:string;
- public invariantUUID:string;
- public name:string;
- public version:string;
- public creationDate:number;
- public lastUpdateDate:number;
- public description:string;
- public lifecycleState:string;
- public tags:Array<string>;
- public icon:string;
- public contactId:string;
- public allVersions:any;
- public creatorUserId:string;
- public creatorFullName:string;
- public lastUpdaterUserId:string;
- public lastUpdaterFullName:string;
- public componentType:string;
- public deploymentArtifacts:Models.ArtifactGroupModel;
- public artifacts:Models.ArtifactGroupModel;
- public toscaArtifacts:Models.ArtifactGroupModel;
- public distributionStatus:string;
- public categories:Array<Models.IMainCategory>;
- public componentInstancesProperties:Models.PropertiesGroup;
- public componentInstancesAttributes:Models.AttributesGroup;
- public componentInstancesRelations:Array<Models.RelationshipModel>;
- public componentInstances:Array<Models.ComponentsInstances.ComponentInstance>;
- public inputs:Array<Models.InputModel>;
- public capabilities:Models.CapabilitiesGroup;
- public requirements:Models.RequirementsGroup;
- public additionalInformation:any;
- public properties:Array<Models.PropertyModel>;
- public attributes:Array<Models.AttributeModel>;
- public highestVersion:boolean;
- public vendorName:string;
- public vendorRelease:string;
- public derivedList:Array<any>;
- public interfaces:any;
- public normalizedName:string;
- public systemName:string;
- public projectCode:string;
- public groups:Array<Models.Module>;
- //custom properties
- public componentService:Sdc.Services.Components.IComponentService;
- public filterTerm:string;
- public iconSprite:string;
- public selectedInstance:Models.ComponentsInstances.ComponentInstance;
- public mainCategory:string;
- public subCategory:string;
- public selectedCategory:string;
- public showMenu:boolean;
-
-
- constructor(componentService:Sdc.Services.Components.IComponentService,
- protected $q:ng.IQService,
- component?:Component) {
- if (component) {
- this.abstract = component.abstract;
- this.uniqueId = component.uniqueId;
- this.uuid = component.uuid;
- this.invariantUUID = component.invariantUUID;
- this.additionalInformation = component.additionalInformation;
- this.artifacts = new Sdc.Models.ArtifactGroupModel(component.artifacts);
- this.toscaArtifacts = new Sdc.Models.ArtifactGroupModel(component.toscaArtifacts);
- this.contactId = component.contactId;
- this.categories = component.categories;
- this.creatorUserId = component.creatorUserId;
- this.creationDate = component.creationDate;
- this.creatorFullName = component.creatorFullName;
- this.description = component.description;
- this.icon = component.icon;
- this.lastUpdateDate = component.lastUpdateDate;
- this.lastUpdaterUserId = component.lastUpdaterUserId;
- this.lastUpdaterFullName = component.lastUpdaterFullName;
- this.lifecycleState = component.lifecycleState;
- this.initComponentInstanceRelations(component.componentInstancesRelations);
- this.componentInstancesProperties = new Models.PropertiesGroup(component.componentInstancesProperties);
- this.componentInstancesAttributes = new Models.AttributesGroup(component.componentInstancesAttributes);
- this.name = component.name;
- this.version = component.version;
- this.tags = component.tags;
- this.capabilities = new Models.CapabilitiesGroup(component.capabilities);
- this.requirements = new Models.RequirementsGroup(component.requirements);
- this.allVersions = component.allVersions;
- this.deploymentArtifacts = new Sdc.Models.ArtifactGroupModel(component.deploymentArtifacts);
- this.componentType = component.componentType;
- this.distributionStatus = component.distributionStatus;
- this.highestVersion = component.highestVersion;
- this.vendorName = component.vendorName;
- this.vendorRelease = component.vendorRelease;
- this.derivedList = component.derivedList;
- this.interfaces = component.interfaces;
- this.normalizedName = component.normalizedName;
- this.systemName = component.systemName;
- this.projectCode = component.projectCode;
- this.inputs = component.inputs;
- this.componentInstances = Utils.CommonUtils.initComponentInstances(component.componentInstances);
- this.properties = Utils.CommonUtils.initProperties(component.properties, this.uniqueId);
- this.attributes = Utils.CommonUtils.initAttributes(component.attributes, this.uniqueId);
- this.selectedInstance = component.selectedInstance;
- this.iconSprite = component.iconSprite;
- this.showMenu = true;
- this.groups = Utils.CommonUtils.initModules(component.groups);
- }
-
- //custom properties
- this.componentService = componentService;
- }
-
- public setUniqueId = (uniqueId:string):void => {
- this.uniqueId = uniqueId;
- };
-
- public setSelectedInstance = (componentInstance:Models.ComponentsInstances.ComponentInstance):void => {
- this.selectedInstance = componentInstance;
- };
-
- //------------------------------------------ Init Functions ----------------------------------------------------------------//
-
- private initComponentInstanceRelations = (componentInstanceRelationsObj:Array<Models.RelationshipModel>):void => {
- if (componentInstanceRelationsObj) {
- this.componentInstancesRelations = [];
- _.forEach(componentInstanceRelationsObj, (instanceRelation:Models.RelationshipModel):void => {
- this.componentInstancesRelations.push(new Models.RelationshipModel(instanceRelation));
- });
- }
- };
- //----------------------------------------------------------------------------------------------------------------------//
-
- //------------------------------------------ API Calls ----------------------------------------------------------------//
- public changeLifecycleState = (state:string, commentObj:Models.AsdcComment):ng.IPromise<Models.Components.Component> => {
- return this.componentService.changeLifecycleState(this, state, JSON.stringify(commentObj));
- };
-
- public getComponent = ():ng.IPromise<Models.Components.Component> => {
- return this.componentService.getComponent(this.uniqueId);
- };
-
- public createComponentOnServer = ():ng.IPromise<Models.Components.Component> => {
- this.handleTags();
- return this.componentService.createComponent(this);
- };
-
- public updateComponent = ():ng.IPromise<Models.Components.Component> => {
- this.handleTags();
- return this.componentService.updateComponent(this);
- };
-
- public validateName = (newName:string, subtype?:string):ng.IPromise<Models.IValidate> => {
- return this.componentService.validateName(newName, subtype);
- };
-
- public downloadArtifact = (artifactId:string):ng.IPromise<Models.IFileDownload> => {
- return this.componentService.downloadArtifact(this.uniqueId, artifactId);
- };
-
- public addOrUpdateArtifact = (artifact:ArtifactModel):ng.IPromise<Models.ArtifactModel> => {
- let deferred = this.$q.defer();
- let onSuccess = (artifactObj:Models.ArtifactModel):void => {
- let newArtifact = new Models.ArtifactModel(artifactObj);
- let artifacts = this.getArtifactsByType(artifactObj.artifactGroupType);
- artifacts[artifactObj.artifactLabel] = newArtifact;
- deferred.resolve(newArtifact);
- };
- let onError = (error:any):void => {
- deferred.reject(error);
- };
- this.componentService.addOrUpdateArtifact(this.uniqueId, artifact).then(onSuccess, onError);
- return deferred.promise;
- };
-
- public updateMultipleArtifacts = (artifacts:Array<Models.ArtifactModel>):ng.IPromise<any>=> {
- let deferred = this.$q.defer();
- let onSuccess = (response:any):void => {
- deferred.resolve(response);
- };
- let onError = (error:any):void => {
- deferred.reject(error);
- };
- let q = new Utils.Functions.QueueUtils(this.$q);
-
- _.forEach(artifacts, (artifact)=> {
- q.addBlockingUIAction(()=> this.addOrUpdateArtifact(artifact).then(onSuccess, onError));
- });
- return deferred.promise;
- };
-
-
- public deleteArtifact = (artifactId:string, artifactLabel:string):ng.IPromise<Models.ArtifactModel> => {
- let deferred = this.$q.defer();
- let onSuccess = (artifactObj:Models.ArtifactModel):void => {
- let newArtifact = new Models.ArtifactModel(artifactObj);
- let artifacts = this.getArtifactsByType(artifactObj.artifactGroupType);
- if (newArtifact.mandatory || newArtifact.serviceApi) {
- artifacts[newArtifact.artifactLabel] = newArtifact;
- }
- else {
- delete artifacts[artifactLabel];
- }
- deferred.resolve(newArtifact);
- };
- this.componentService.deleteArtifact(this.uniqueId, artifactId, artifactLabel).then(onSuccess);
- return deferred.promise;
- };
-
-
- public addOrUpdateProperty = (property:Models.PropertyModel):ng.IPromise<Models.PropertyModel> => {
- let deferred = this.$q.defer();
-
- let onError = (error:any):void => {
- deferred.reject(error);
- };
-
- if (!property.uniqueId) {
- let onSuccess = (property:Models.PropertyModel):void => {
- let newProperty = new Models.PropertyModel(property);
- this.properties.push(newProperty);
- deferred.resolve(newProperty);
- };
- this.componentService.addProperty(this.uniqueId, property).then(onSuccess, onError);
- }
- else {
- let onSuccess = (newProperty:Models.PropertyModel):void => {
- // find exist instance property in parent component for update the new value ( find bu uniqueId )
- let existProperty:Models.PropertyModel = <Models.PropertyModel>_.find(this.properties, {uniqueId: newProperty.uniqueId});
- let propertyIndex = this.properties.indexOf(existProperty);
- newProperty.readonly = this.uniqueId != newProperty.parentUniqueId;
- this.properties[propertyIndex] = newProperty;
- deferred.resolve(newProperty);
- };
- this.componentService.updateProperty(this.uniqueId, property).then(onSuccess, onError);
- }
- return deferred.promise;
- };
-
- public addOrUpdateAttribute = (attribute:Models.AttributeModel):ng.IPromise<Models.AttributeModel> => {
- let deferred = this.$q.defer();
-
- let onError = (error:any):void => {
- deferred.reject(error);
- };
-
- if (!attribute.uniqueId) {
- let onSuccess = (attribute:Models.AttributeModel):void => {
- let newAttribute = new Models.AttributeModel(attribute);
- this.attributes.push(newAttribute);
- deferred.resolve(newAttribute);
- };
- this.componentService.addAttribute(this.uniqueId, attribute).then(onSuccess, onError);
- }
- else {
- let onSuccess = (newAttribute:Models.AttributeModel):void => {
- let existAttribute:Models.AttributeModel = <Models.AttributeModel>_.find(this.attributes, {uniqueId: newAttribute.uniqueId});
- let attributeIndex = this.attributes.indexOf(existAttribute);
- newAttribute.readonly = this.uniqueId != newAttribute.parentUniqueId;
- this.attributes[attributeIndex] = newAttribute;
- deferred.resolve(newAttribute);
- };
- this.componentService.updateAttribute(this.uniqueId, attribute).then(onSuccess, onError);
- }
- return deferred.promise;
- };
-
- public deleteProperty = (propertyId:string):ng.IPromise<Models.PropertyModel> => {
- let deferred = this.$q.defer();
- let onSuccess = ():void => {
- console.log("Property deleted");
- delete _.remove(this.properties, {uniqueId: propertyId})[0];
- deferred.resolve();
- };
- let onFailed = ():void => {
- console.log("Failed to delete property");
- deferred.reject();
- };
- this.componentService.deleteProperty(this.uniqueId, propertyId).then(onSuccess, onFailed);
- return deferred.promise;
- };
-
- public deleteAttribute = (attributeId:string):ng.IPromise<Models.AttributeModel> => {
- let deferred = this.$q.defer();
- let onSuccess = ():void => {
- console.log("Attribute deleted");
- delete _.remove(this.attributes, {uniqueId: attributeId})[0];
- };
- let onFailed = ():void => {
- console.log("Failed to delete attribute");
- };
- this.componentService.deleteAttribute(this.uniqueId, attributeId).then(onSuccess, onFailed);
- return deferred.promise;
- };
-
- public updateInstanceProperty = (property:Models.PropertyModel):ng.IPromise<Models.PropertyModel> => {
- let deferred = this.$q.defer();
- let onSuccess = (newProperty:Models.PropertyModel):void => {
- // find exist instance property in parent component for update the new value ( find bu uniqueId & path)
- let existProperty:Models.PropertyModel = <Models.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;
- deferred.resolve(newProperty);
- };
- let onFailed = (error:any):void => {
- console.log('Failed to update property value');
- deferred.reject(error);
- };
- this.componentService.updateInstanceProperty(this.uniqueId, property).then(onSuccess, onFailed);
- return deferred.promise;
- };
-
- public updateInstanceAttribute = (attribute:Models.AttributeModel):ng.IPromise<Models.AttributeModel> => {
- let deferred = this.$q.defer();
- let onSuccess = (newAttribute:Models.AttributeModel):void => {
- let existAttribute:Models.AttributeModel = <Models.AttributeModel>_.find(this.componentInstancesAttributes[newAttribute.resourceInstanceUniqueId], {uniqueId: newAttribute.uniqueId});
- let index = this.componentInstancesAttributes[newAttribute.resourceInstanceUniqueId].indexOf(existAttribute);
- this.componentInstancesAttributes[newAttribute.resourceInstanceUniqueId][index] = newAttribute;
- deferred.resolve(newAttribute);
- };
- let onFailed = (error:any):void => {
- console.log('Failed to update attribute value');
- deferred.reject(error);
- };
- this.componentService.updateInstanceAttribute(this.uniqueId, attribute).then(onSuccess, onFailed);
- return deferred.promise;
- };
-
- public downloadInstanceArtifact = (artifactId:string):ng.IPromise<Models.IFileDownload> => {
- return this.componentService.downloadInstanceArtifact(this.uniqueId, this.selectedInstance.uniqueId, artifactId);
- };
-
- public deleteInstanceArtifact = (artifactId:string, artifactLabel:string):ng.IPromise<Models.ArtifactModel> => {
- let deferred = this.$q.defer();
- let onSuccess = (artifactObj:Models.ArtifactModel):void => {
- let newArtifact = new Models.ArtifactModel(artifactObj);
- let artifacts = this.selectedInstance.deploymentArtifacts;
- if (newArtifact.mandatory || newArtifact.serviceApi) {//?????????
- artifacts[newArtifact.artifactLabel] = newArtifact;
- }
- else {
- delete artifacts[artifactLabel];
- }
- deferred.resolve(newArtifact);
- };
- this.componentService.deleteInstanceArtifact(this.uniqueId,this.selectedInstance.uniqueId, artifactId, artifactLabel).then(onSuccess);
- return deferred.promise;
- };
-
- public addOrUpdateInstanceArtifact = (artifact:ArtifactModel):ng.IPromise<Models.ArtifactModel> => {
- let deferred = this.$q.defer();
- let onSuccess = (artifactObj:Models.ArtifactModel):void => {
- this.selectedInstance.deploymentArtifacts[artifactObj.artifactLabel] = artifactObj;
- deferred.resolve(artifactObj);
- };
- let onError = (error:any):void => {
- deferred.reject(error);
- };
- if(artifact.uniqueId){
- this.componentService.updateInstanceArtifact(this.uniqueId, this.selectedInstance.uniqueId, artifact).then(onSuccess, onError);
- }else{
- this.componentService.addInstanceArtifact(this.uniqueId, this.selectedInstance.uniqueId, artifact).then(onSuccess, onError);
- }
- return deferred.promise;
- };
-
- public uploadInstanceEnvFile = (artifact:Models.ArtifactModel):ng.IPromise<Models.ArtifactModel> => {
- let deferred = this.$q.defer();
- let onSuccess = (artifactObj:Models.ArtifactModel):void => {
- this.selectedInstance.deploymentArtifacts[artifactObj.artifactLabel] = artifactObj;
- deferred.resolve(artifactObj);
- };
- let onError = (error:any):void => {
- deferred.reject(error);
- };
- this.componentService.uploadInstanceEnvFile(this.uniqueId, this.selectedInstance.uniqueId, artifact).then(onSuccess, onError);
- return deferred.promise;
- };
-
- //this function will update the instance version than the function call getComponent to update the current component and return the new instance version
- public changeComponentInstanceVersion = (componentUid:string):ng.IPromise<Models.Components.Component> => {
- let deferred = this.$q.defer();
- let onFailed = (error:any):void => {
- deferred.reject(error);
- };
- let onSuccess = (componentInstance:Models.ComponentsInstances.ComponentInstance):void => {
- let onSuccess = (component:Models.Components.Component):void => {
- component.setSelectedInstance(componentInstance);
- deferred.resolve(component);
- };
- this.getComponent().then(onSuccess, onFailed);
- };
- this.componentService.changeResourceInstanceVersion(this.uniqueId, this.selectedInstance.uniqueId, componentUid).then(onSuccess, onFailed);
- return deferred.promise;
- };
-
- public createComponentInstance = (componentInstance:Models.ComponentsInstances.ComponentInstance):ng.IPromise<Models.ComponentsInstances.ComponentInstance> => {
- let deferred = this.$q.defer();
- let onSuccess = (instance:Models.ComponentsInstances.ComponentInstance):void => {
- let onSuccess = (component:Models.Components.Component):void => {
- this.componentInstances = Utils.CommonUtils.initComponentInstances(component.componentInstances);
- this.componentInstancesProperties = new Models.PropertiesGroup(component.componentInstancesProperties);
- this.componentInstancesAttributes = new Models.AttributesGroup(component.componentInstancesAttributes);
- deferred.resolve(instance);
- };
- this.getComponent().then(onSuccess);
- };
- let onFailed = (error:any):void => {
- deferred.reject(error);
- };
- this.componentService.createComponentInstance(this.uniqueId, componentInstance).then(onSuccess, onFailed);
- return deferred.promise;
- };
-
- public updateComponentInstance = (componentInstance:Models.ComponentsInstances.ComponentInstance):ng.IPromise<Models.ComponentsInstances.ComponentInstance> => {
- let deferred = this.$q.defer();
- let onSuccess = (updatedInstance:Models.ComponentsInstances.ComponentInstance):void => {
- let componentInstance:Models.ComponentsInstances.ComponentInstance = _.find(this.componentInstances, (instance:Models.ComponentsInstances.ComponentInstance) => {
- return instance.uniqueId === updatedInstance.uniqueId;
- });
-
- let index = this.componentInstances.indexOf(componentInstance);
- this.componentInstances[index] = componentInstance;
- deferred.resolve(updatedInstance);
-
- };
- let onFailed = (error:any):void => {
- deferred.reject(error);
- };
- this.componentService.updateComponentInstance(this.uniqueId, componentInstance).then(onSuccess, onFailed);
- return deferred.promise;
- };
-
- public updateMultipleComponentInstances = (instances: Array<Models.ComponentsInstances.ComponentInstance>):ng.IPromise<Array<Models.ComponentsInstances.ComponentInstance>> => {
- let deferred = this.$q.defer();
- let onSuccess = (updatedInstances:Array<Models.ComponentsInstances.ComponentInstance>):void => {
- deferred.resolve(updatedInstances);
- };
- let onFailed = (error:any):void => {
- deferred.reject(error);
- };
- this.componentService.updateMultipleComponentInstances(this.uniqueId, instances).then(onSuccess, onFailed);
- return deferred.promise;
- };
-
- public deleteComponentInstance = (componentInstanceId:string):ng.IPromise<Models.ComponentsInstances.ComponentInstance> => {
- let deferred = this.$q.defer();
- let onSuccess = ():void => {
- let onSuccess = (component:Models.Components.Component):void => {
- this.componentInstances = Utils.CommonUtils.initComponentInstances(component.componentInstances);
- this.componentInstancesProperties = new Models.PropertiesGroup(component.componentInstancesProperties);
- this.componentInstancesAttributes = new Models.AttributesGroup(component.componentInstancesAttributes);
- this.initComponentInstanceRelations(component.componentInstancesRelations);
- deferred.resolve();
- };
- this.getComponent().then(onSuccess);
- };
- let onFailed = (error:any):void => {
- deferred.reject(error);
- };
- this.componentService.deleteComponentInstance(this.uniqueId, componentInstanceId).then(onSuccess, onFailed);
- return deferred.promise;
- };
-
-
- public createRelation = (relation:Models.RelationshipModel):ng.IPromise<Models.RelationshipModel> => {
- let deferred = this.$q.defer();
- let onSuccess = (relation:Models.RelationshipModel):void => {
- console.info('Link created successfully', relation);
- if (!this.componentInstancesRelations) {
- this.componentInstancesRelations = [];
- }
- this.componentInstancesRelations.push(new Models.RelationshipModel(relation));
- deferred.resolve(relation);
- };
- let onFailed = (error:any):void => {
- console.info('Failed to create relation', error);
- deferred.reject(error);
- };
- this.componentService.createRelation(this.uniqueId, relation).then(onSuccess, onFailed);
- return deferred.promise;
- };
-
- public deleteRelation = (relation:Models.RelationshipModel):ng.IPromise<Models.RelationshipModel> => {
- let deferred = this.$q.defer();
- let onSuccess = (responseRelation:Models.RelationshipModel):void => {
- console.log("Link Deleted In Server");
- let relationToDelete = _.find(this.componentInstancesRelations, (item) => {
- return item.fromNode === relation.fromNode && item.toNode === relation.toNode && _.some(item.relationships, (relationship)=> {
- return angular.equals(relation.relationships[0], relationship);
- });
- });
- let index = this.componentInstancesRelations.indexOf(relationToDelete);
- if (relationToDelete != undefined && index > -1) {
- if (relationToDelete.relationships.length == 1) {
- this.componentInstancesRelations.splice(index, 1);
- } else {
- this.componentInstancesRelations[index].relationships =
- _.reject(this.componentInstancesRelations[index].relationships, relation.relationships[0]);
- }
- } else {
- console.error("Error while deleting relation - the return delete relation from server was not found in UI")
- }
- deferred.resolve(relation);
- };
- let onFailed = (error:any):void => {
- console.error("Failed To Delete Link");
- deferred.reject(error);
- };
- this.componentService.deleteRelation(this.uniqueId, relation).then(onSuccess, onFailed);
- return deferred.promise;
- };
-
- public updateRequirementsCapabilities = ():ng.IPromise<any> => {
- let deferred = this.$q.defer();
- let onSuccess = (response:any):void => {
- this.capabilities = response.capabilities;
- this.requirements = response.requirements;
- deferred.resolve(response);
- };
- let onFailed = (error:any):void => {
- deferred.reject(error);
- };
- this.componentService.getRequirementsCapabilities(this.uniqueId).then(onSuccess, onFailed);
- return deferred.promise;
- };
-
- public getModuleForDisplay = (moduleId:string):ng.IPromise<Models.DisplayModule> => {
-
- let deferred = this.$q.defer();
- let onSuccess = (response:Models.DisplayModule):void => {
- deferred.resolve(response);
- };
- let onFailed = (error:any):void => {
- deferred.reject(error);
- };
- this.componentService.getModuleForDisplay(this.uniqueId, moduleId).then(onSuccess, onFailed);
- return deferred.promise;
- };
-
- // this function get all instances filtered by inputs and properties (optional) - if no search string insert - this function will
- // get all the instances of the component (in service only VF instances)
- public getComponentInstancesFilteredByInputsAndProperties = (searchText?:string):ng.IPromise<Array<Models.ComponentsInstances.ComponentInstance>> => {
-
- let deferred = this.$q.defer();
- let onSuccess = (response: Array<Models.ComponentsInstances.ComponentInstance>):void => {
- deferred.resolve(response);
- };
- let onFailed = (error:any): void => {
- deferred.reject(error);
- };
- this.componentService.getComponentInstancesFilteredByInputsAndProperties(this.uniqueId, searchText).then(onSuccess, onFailed);
- return deferred.promise;
- };
-
-
- // get inputs for instance - Pagination function
- public getComponentInputs = ():ng.IPromise<Array<Models.InputModel>> => {
-
- let deferred = this.$q.defer();
- let onSuccess = (inputsRes: Array<Models.InputModel>):void => {
- this.inputs = inputsRes;
- deferred.resolve(inputsRes);
- };
- let onFailed = (error:any): void => {
- deferred.reject(error);
- };
- this.componentService.getComponentInputs(this.uniqueId).then(onSuccess, onFailed);
- return deferred.promise;
- };
-
-
- // get inputs instance - Pagination function
- public getComponentInstanceInputs = (componentInstanceId: string, originComponentUid: string):ng.IPromise<Array<Models.InputModel>> => {
-
- let deferred = this.$q.defer();
- let onSuccess = (response: Array<Models.InputModel>):void => {
- deferred.resolve(response);
- };
- let onFailed = (error:any): void => {
- deferred.reject(error);
- };
- this.componentService.getComponentInstanceInputs(this.uniqueId, componentInstanceId, originComponentUid).then(onSuccess, onFailed);
- return deferred.promise;
- };
-
- // get inputs inatnce - Pagination function
- public getComponentInstanceInputProperties = (componentInstanceId: string, inputId: string):ng.IPromise<Array<Models.PropertyModel>> => {
-
- let deferred = this.$q.defer();
- let onSuccess = (response: Array<Models.PropertyModel>):void => {
- deferred.resolve(response);
- };
- let onFailed = (error:any): void => {
- deferred.reject(error);
- };
- this.componentService.getComponentInstanceInputProperties(this.uniqueId, componentInstanceId, inputId).then(onSuccess, onFailed);
- return deferred.promise;
- };
-
- public updateGroupMetadata = (module: Models.Module):ng.IPromise<Models.Module> => {
-
- let deferred = this.$q.defer();
-
- let onSuccess = (updatedModule:Models.Module):void => {
- let groupIndex: number = _.indexOf(this.groups, _.find(this.groups, (module: Models.Module) => {
- return module.uniqueId === updatedModule.uniqueId;
- }));
-
- if(groupIndex !== -1) {
- this.groups[groupIndex] = updatedModule;
- }
- deferred.resolve(updatedModule);
- };
- let onFailed = (error:any):void => {
- deferred.reject(error);
- };
-
- this.componentService.updateGroupMetadata(this.uniqueId, module).then(onSuccess, onFailed);
-
- return deferred.promise;
- };
-
- //------------------------------------------ Help Functions ----------------------------------------------------------------//
-
- public isProduct = ():boolean => {
- return this instanceof Product;
- };
-
- public isService = ():boolean => {
- return this instanceof Service;
- };
-
- public isResource = ():boolean => {
- return this instanceof Resource;
- };
-
- public getComponentSubType = ():string => {
- return this.componentType;
- };
-
- public isAlreadyCertified = ():boolean => {
- return parseInt(this.version) >= 1;
- };
-
- public isComplex = ():boolean => {
- return true;
- };
-
- //sort string version value from hash to sorted version (i.e 1.9 before 1.11)
- private sortVersions = (v1:string, v2:string):number => {
- let ver1 = v1.split('.');
- let ver2 = v2.split('.');
- let diff = parseInt(_.first(ver1)) - parseInt(_.first(ver2));
- if (!diff){
- return parseInt(_.last(ver1)) - parseInt(_.last(ver2));
- }
- return diff;
- };
-
- public getAllVersionsAsSortedArray = ():Array<any> => {
- let res = [];
- if(this.allVersions){
- let keys = Object.keys(this.allVersions).sort(this.sortVersions);
- _.forEach(keys, (key)=> {
- res.push({
- versionNumber: key,
- versionId: this.allVersions[key]
- })
- });
- }
- return res;
- };
-
- public isLatestVersion = ():boolean => {
- if (this.allVersions){
- return this.version === _.last(Object.keys(this.allVersions).sort(this.sortVersions));
- }else{
- return true;
- }
-
- };
-
- public getAdditionalInformation = ():Array<Models.AdditionalInformationModel> => {
- let additionalInformationObject:any = _.find(this.additionalInformation, (obj:any):boolean => {
- return obj.parentUniqueId == this.uniqueId;
- });
- if (additionalInformationObject) {
- return additionalInformationObject.parameters;
- }
- return [];
- };
-
- public handleTags = ():void => {
- let isContainTag = _.find(this.tags, (tag)=> {
- return tag === this.name;
- });
- if (!isContainTag) {
- this.tags.push(this.name);
- }
- };
-
- public getArtifactsByType = (artifactGroupType:string):Models.ArtifactGroupModel => {
- switch (artifactGroupType) {
- case Utils.Constants.ArtifactGroupType.DEPLOYMENT:
- return this.deploymentArtifacts;
- case Utils.Constants.ArtifactGroupType.INFORMATION:
- return this.artifacts;
- }
- };
-
- public getStatus =(sdcMenu:Models.IAppMenu):string =>{
- let status:string = sdcMenu.LifeCycleStatuses[this.lifecycleState].text;
- if(this.lifecycleState == "CERTIFIED" && sdcMenu.DistributionStatuses[this.distributionStatus]) {
- status = sdcMenu.DistributionStatuses[this.distributionStatus].text;
- }
- return status;
- };
-
- public toJSON = ():any => {
- this.componentService = undefined;
- this.filterTerm = undefined;
- this.iconSprite = undefined;
- this.mainCategory = undefined;
- this.subCategory = undefined;
- this.selectedInstance = undefined;
- this.showMenu = undefined;
- this.$q = undefined;
- this.selectedCategory = undefined;
- return this;
- };
- }
-}
-
diff --git a/catalog-ui/app/scripts/models/components/displayComponent.ts b/catalog-ui/app/scripts/models/components/displayComponent.ts
deleted file mode 100644
index 578f392470..0000000000
--- a/catalog-ui/app/scripts/models/components/displayComponent.ts
+++ /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=========================================================
- */
-/**
- * Created by obarda on 7/5/2016.
- */
-/// <reference path="../../references"/>
-module Sdc.Models {
- 'use strict';
-
- export class DisplayComponent {
-
- uniqueId:string;
- displayName:string;
- version:string;
- mainCategory:string;
- subCategory:string;
- iconClass:string;
- componentSubType:string;
- searchFilterTerms:string;
- certifiedIconClass:string;
- icon:string;
- isRequirmentAndCapabilitiesLoaded:boolean;
-
- constructor(public component:Models.Components.Component) {
- this.icon = component.icon;
- this.version = component.version;
- this.uniqueId = component.uniqueId;
- this.isRequirmentAndCapabilitiesLoaded = false;
-
- if (component.categories && component.categories[0] && component.categories[0].subcategories && component.categories[0].subcategories[0]) {
- this.mainCategory = component.categories[0].name;
- this.subCategory = component.categories[0].subcategories[0].name;
- } else {
- this.mainCategory = 'Generic';
- this.subCategory = 'Generic';
- }
- if (component instanceof Models.Components.Resource) {
- this.componentSubType = (<Models.Components.Resource>component).resourceType;
- } else {
- this.componentSubType = component.componentType;
- }
-
- this.initDisplayName(component.name);
- this.searchFilterTerms = (this.displayName + ' ' + component.description + ' ' + component.tags.join(' ')).toLowerCase() + ' ' + component.version;
- this.initIconSprite(component.icon);
- this.certifiedIconClass = component.lifecycleState != 'CERTIFIED' ? 'non-certified' : '';
- if(component.icon === 'vl' || component.icon === 'cp') {
- this.certifiedIconClass = this.certifiedIconClass + " " + 'smaller-icon';
- }
- }
-
- public initDisplayName = (name:string):void => {
- let newName =
- _.last(_.last(_.last(_.last(_.last(_.last(_.last(_.last(name.split('tosca.nodes.'))
- .split('network.')).split('relationships.')).split('org.openecomp.')).split('resource.nfv.'))
- .split('nodes.module.')).split('cp.')).split('vl.'));
- if (newName){
- this.displayName = newName;
- } else {
- this.displayName = name;
- }
- };
-
- public initIconSprite = (icon:string ):void => {
- switch (this.componentSubType) {
- case Utils.Constants.ComponentType.SERVICE:
- this.iconClass = "sprite-services-icons " + icon;
- break;
- case Utils.Constants.ComponentType.PRODUCT:
- this.iconClass = "sprite-product-icons " + icon;
- break;
- default:
- this.iconClass = "sprite-resource-icons " + icon;
- }
- }
-
- public getComponentSubType = ():string => {
- return this.componentSubType;
- };
- }
-}
diff --git a/catalog-ui/app/scripts/models/components/product.ts b/catalog-ui/app/scripts/models/components/product.ts
deleted file mode 100644
index 6ba3404afb..0000000000
--- a/catalog-ui/app/scripts/models/components/product.ts
+++ /dev/null
@@ -1,109 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/**
- * Created by obarda on 2/4/2016.
- */
-/// <reference path="../../references"/>
-module Sdc.Models.Components {
- 'use strict';
-
- export class Product extends Component{
-
- public contacts:Array<string>;
- public componentService: Services.Components.IProductService;
- public fullName: string;
-
- constructor(componentService: Services.Components.IProductService, $q:ng.IQService, component?:Product) {
- super(componentService, $q, component);
-
- if(component) {
- this.fullName = component.fullName;
- this.filterTerm = this.name + ' ' + this.description + ' ' + (this.tags ? this.tags.toString() : '') + ' ' + this.version;
- this.contacts = component.contacts;
- }
- this.componentService = componentService;
- this.iconSprite = "sprite-product-icons";
- }
-
- public deleteGroup = (uniqueId: string): void => {
- _.forEach(this.categories, (category: Models.IMainCategory) => {
- _.forEach(category.subcategories, (subcategory:Models.ISubCategory) => {
- subcategory.groupings = _.reject (subcategory.groupings, (group:Models.IGroup) => {
- return group.uniqueId === uniqueId;
- });
- if(subcategory.groupings.length == 0){ // if there is no groups, delete the subcategory
- category.subcategories = _.reject (category.subcategories, (subcategoryObj:Models.ISubCategory) => {
- return subcategoryObj.uniqueId === subcategory.uniqueId;
- });
- if(category.subcategories.length == 0){ // if there is no subcategory, delete the category
- this.categories = _.reject (this.categories , (categoryObj:Models.IMainCategory) => {
- return categoryObj.uniqueId === category.uniqueId;
- });
- }
- }
- });
- });
- };
-
- private getCategoryObjectById = (categoriesArray:Array<Models.ICategoryBase>, categoryUniqueId:string):Models.ICategoryBase => {
- let categorySelected = _.find(categoriesArray, (category) => {
- return category.uniqueId === categoryUniqueId;
- });
- return categorySelected;
- };
-
- public addGroup = (category: Models.IMainCategory, subcategory: Models.ISubCategory, group: Models.IGroup): void => {
- if(!this.categories){
- this.categories = new Array<Models.IMainCategory>();
- }
- let existingCategory:Models.IMainCategory = <Models.IMainCategory>this.getCategoryObjectById(this.categories, category.uniqueId);
- let newGroup = angular.copy(group);
- newGroup.filterTerms = undefined;
- newGroup.isDisabled = undefined;
- if(!existingCategory){
- let newCategory: Models.IMainCategory = angular.copy(category);
- newCategory.filteredGroup = undefined;
- newCategory.subcategories = [];
- let newSubcategory:Models.ISubCategory = angular.copy(subcategory);
- newSubcategory.groupings = [];
- newSubcategory.groupings.push(newGroup);
- newCategory.subcategories.push(newSubcategory);
- this.categories.push(newCategory);
- }
- else{
- let existingSubcategory:Models.ISubCategory = <Models.ISubCategory> this.getCategoryObjectById(existingCategory.subcategories, subcategory.uniqueId);
- if(!existingSubcategory){
- let newSubcategory:Models.ISubCategory = angular.copy(subcategory);
- newSubcategory.groupings = [];
- newSubcategory.groupings.push(newGroup);
- existingCategory.subcategories.push(newSubcategory);
-
- } else {
- let existingGroup:Models.IGroup = <Models.IGroup> this.getCategoryObjectById(existingSubcategory.groupings, group.uniqueId);
- if(!existingGroup){
- existingSubcategory.groupings.push(newGroup);
- }
- }
- }
- };
-
- }
-}
-
diff --git a/catalog-ui/app/scripts/models/components/resource.ts b/catalog-ui/app/scripts/models/components/resource.ts
deleted file mode 100644
index 243ef3463c..0000000000
--- a/catalog-ui/app/scripts/models/components/resource.ts
+++ /dev/null
@@ -1,185 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/**
- * Created by obarda on 2/3/2016.
- */
-/// <reference path="../../references"/>
-module Sdc.Models.Components {
- 'use strict';
-
- export class Resource extends Component {
-
- public interfaces: any;
- public derivedFrom:Array<string>;
- public componentService: Services.Components.IResourceService;
- public resourceType:string;
- public payloadData:string;
- public payloadName:string;
- public importedFile: Sdc.Directives.FileUploadModel;
-
- // Onboarding parameters
- public csarUUID:string;
- public csarVersion:string;
- public csarPackageType:string;
- public packageId:string;
-
- constructor(componentService: Services.Components.IResourceService, $q: ng.IQService, component?:Resource) {
- super(componentService, $q, component);
- if(component) {
-
- this.interfaces = component.interfaces;
- this.derivedFrom = component.derivedFrom;
- this.payloadData = component.payloadData ? component.payloadData : undefined;
- this.payloadName = component.payloadName ? component.payloadName : undefined;
- this.resourceType = component.resourceType;
- this.csarUUID = component.csarUUID;
- this.csarVersion = component.csarVersion;
- this.filterTerm = this.name + ' ' + this.description + ' ' + (this.tags ? this.tags.toString() : '') + ' ' + this.version + ' ' + this.resourceType;
-
- if (component.categories && component.categories[0] && component.categories[0].subcategories && component.categories[0].subcategories[0]) {
- component.mainCategory = component.categories[0].name;
- component.subCategory = component.categories[0].subcategories[0].name;
- this.selectedCategory = component.mainCategory + "_#_" + component.subCategory;
- this.importedFile = component.importedFile;
- }
- } else {
- this.resourceType = Utils.Constants.ResourceType.VF;
- }
-
- this.componentService = componentService;
- this.iconSprite = "sprite-resource-icons";
- }
-
- public getComponentSubType = ():string => {
- return this.resourceType;
- };
-
- public isComplex = ():boolean => {
- return this.resourceType === Utils.Constants.ResourceType.VF;
- };
-
- public isVl = ():boolean => {
- return Utils.Constants.ResourceType.VL == this.resourceType;
- };
-
- public isCsarComponent = ():boolean => {
- return !!this.csarUUID;
- };
-
- public createComponentOnServer = ():ng.IPromise<Models.Components.Component> => {
- let deferred = this.$q.defer();
- let onSuccess = (component:Models.Components.Resource):void => {
- this.payloadData = undefined;
- this.payloadName = undefined;
- deferred.resolve(component);
- };
- let onError = (error:any):void => {
- deferred.reject(error);
- };
-
- this.handleTags();
- if(this.importedFile){
- this.payloadData = this.importedFile.base64;
- this.payloadName = this.importedFile.filename;
- }
- this.componentService.createComponent(this).then(onSuccess, onError);
- return deferred.promise;
- };
-
- /* we need to change the name of the input to vfInstanceName + input name before sending to server in order to create the inputs on the service
- * we also need to remove already selected inputs (the inputs that already create on server, and disabled in the view - but they are selected so they are still in the view model
- */
- public createInputsFormInstances = (instanceInputsPropertiesMap:Models.InstanceInputsPropertiesMapData):ng.IPromise<Array<Models.InputModel>> => {
- let deferred = this.$q.defer();
- /*
- let instanceInputsPropertiesMapToCreate: Models.InstanceInputsPropertiesMapData = new Models.InstanceInputsPropertiesMapData();
- _.forEach(instanceInputsPropertiesMap, (properties:Array<Models.PropertyModel>, instanceId:string) => {
-
- if(properties && properties.length > 0) {
- let componentInstance:Models.ComponentsInstances.ComponentInstance = _.find(this.componentInstances, (instace:Models.ComponentsInstances.ComponentInstance) => {
- return instace.uniqueId === instanceId;
- });
-
- instanceInputsPropertiesMapToCreate[instanceId] = new Array<Models.PropertyModel>();
- _.forEach(properties, (property:Models.PropertyModel) => {
-
- if(!property.isAlreadySelected) {
- let newInput = new Models.PropertyModel(property);
- newInput.name = componentInstance.normalizedName + '_' + property.name;
- instanceInputsPropertiesMapToCreate[instanceId].push(newInput);
- }
- });
- if( instanceInputsPropertiesMapToCreate[instanceId].length === 0) {
- delete instanceInputsPropertiesMapToCreate[instanceId];
- }
- } else {
- delete instanceInputsPropertiesMapToCreate[instanceId];
- }
- });
-
- if(Object.keys(instanceInputsPropertiesMapToCreate).length > 0) {
- let deferred = this.$q.defer();
- let onSuccess = (propertiesCreated: Array<Models.PropertyModel>):void => {
- this.inputs = propertiesCreated.concat(this.inputs);
- deferred.resolve(propertiesCreated);
- };
- let onFailed = (error:any): void => {
- deferred.reject(error);
- };
- this.componentService.createInputsFromInstancesInputsProperties(this.uniqueId, new Models.InstanceInputsPropertiesMap(instanceInputsPropertiesMapToCreate)).then(onSuccess, onFailed);
- }
- */
- return deferred.promise;
- };
-
- // we need to change the name of the input to vfInstanceName + input name before sending to server in order to create the inputs on the service
- public getResourceInputInputs = (inputId:string):ng.IPromise<Array<Models.InputModel>> => {
- let deferred = this.$q.defer();
- let onSuccess = (inputInputs: Array<Models.InputModel>):void => {
- let input: Models.InputModel = _.find(this.inputs, (input:Models.InputModel) => {
- return input.uniqueId === inputId;
- });
- input.inputs = inputInputs;
- deferred.resolve(inputInputs);
- };
- let onFailed = (error:any): void => {
- deferred.reject(error);
- };
- this.componentService.getComponentInputInputs(this.uniqueId, inputId).then(onSuccess, onFailed);
- return deferred.promise;
- };
-
- public toJSON = ():any => {
- this.componentService = undefined;
- this.filterTerm = undefined;
- this.iconSprite = undefined;
- this.mainCategory = undefined;
- this.subCategory = undefined;
- this.selectedInstance = undefined;
- this.showMenu = undefined;
- this.$q = undefined;
- this.selectedCategory = undefined;
- this.importedFile = undefined;
- return this;
- };
- }
-}
-
-
diff --git a/catalog-ui/app/scripts/models/components/service.ts b/catalog-ui/app/scripts/models/components/service.ts
deleted file mode 100644
index b1730aae94..0000000000
--- a/catalog-ui/app/scripts/models/components/service.ts
+++ /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=========================================================
- */
-/**
- * Created by obarda on 2/4/2016.
- */
-/// <reference path="../../references"/>
-module Sdc.Models.Components {
- 'use strict';
-
-
- export class Service extends Component {
-
- public serviceApiArtifacts:Models.ArtifactGroupModel;
- public componentService:Services.Components.IServiceService;
-
- constructor(componentService:Services.Components.IServiceService, $q:ng.IQService, component?:Service) {
- super(componentService, $q, component);
- if (component) {
- this.serviceApiArtifacts = new Models.ArtifactGroupModel(component.serviceApiArtifacts);
- this.filterTerm = this.name + ' ' + this.description + ' ' + (this.tags ? this.tags.toString() : '') + ' ' + this.version;
- if (component.categories && component.categories[0]) {
- this.mainCategory = component.categories[0].name;
- this.selectedCategory = this.mainCategory;
- }
- }
- this.componentService = componentService;
- this.iconSprite = "sprite-services-icons";
- }
-
- public getDistributionsList = ():ng.IPromise<Array<Models.Distribution>> => {
- return this.componentService.getDistributionsList(this.uuid);
- };
-
- public getDistributionsComponent = (distributionId:string):ng.IPromise<Array<Models.DistributionComponent>> => {
- return this.componentService.getDistributionComponents(distributionId);
- };
-
- public markAsDeployed = (distributionId:string):ng.IPromise<any> => {
- return this.componentService.markAsDeployed(this.uniqueId, distributionId);
- };
-
- /* we need to change the name of the input to vfInstanceName + input name before sending to server in order to create the inputs on the service
- * we also need to remove already selected inputs (the inputs that already create on server, and disabled in the view - but they are selected so they are still in the view model
- */
- public createInputsFormInstances = (instancesInputsMap:Models.InstancesInputsMapData):ng.IPromise<Array<Models.InputModel>> => {
- let deferred = this.$q.defer();
-
- let instancesInputsMapToCreate: Models.InstancesInputsMapData = new Models.InstancesInputsMapData();
- _.forEach(instancesInputsMap, (inputs:Array<Models.InputModel>, instanceId:string) => {
-
- if(inputs && inputs.length > 0) {
- let componentInstance:Models.ComponentsInstances.ComponentInstance = _.find(this.componentInstances, (instace:Models.ComponentsInstances.ComponentInstance) => {
- return instace.uniqueId === instanceId;
- });
- instancesInputsMapToCreate[instanceId] = new Array<Models.InputModel>();
- _.forEach(inputs, (input:Models.InputModel) => {
-
- if(!input.isAlreadySelected) {
- let newInput = new Models.InputModel(input);
- newInput.name = componentInstance.normalizedName + '_' + input.name;
- instancesInputsMapToCreate[instanceId].push(newInput);
- }
- });
- if( instancesInputsMapToCreate[instanceId].length === 0) {
- delete instancesInputsMapToCreate[instanceId];
- }
- } else {
- delete instancesInputsMapToCreate[instanceId];
- }
- });
-
- if(Object.keys(instancesInputsMapToCreate).length > 0) {
- let deferred = this.$q.defer();
- let onSuccess = (inputsCreated: Array<Models.InputModel>):void => {
- this.inputs = inputsCreated.concat(this.inputs);
- deferred.resolve(inputsCreated);
- };
- let onFailed = (error:any): void => {
- deferred.reject(error);
- };
- this.componentService.createInputsFromInstancesInputs(this.uniqueId, new Models.InstancesInputsMap(instancesInputsMapToCreate)).then(onSuccess, onFailed);
- }
- return deferred.promise;
- };
-
- // we need to change the name of the input to vfInstanceName + input name before sending to server in order to create the inputs on the service
- public getServiceInputInputs = (inputId:string):ng.IPromise<Array<Models.InputModel>> => {
- let deferred = this.$q.defer();
- let onSuccess = (inputInputs: Array<Models.InputModel>):void => {
- let input: Models.InputModel = _.find(this.inputs, (input:Models.InputModel) => {
- return input.uniqueId === inputId;
- });
- input.inputs = inputInputs;
- deferred.resolve(inputInputs);
- };
- let onFailed = (error:any): void => {
- deferred.reject(error);
- };
- this.componentService.getComponentInputInputs(this.uniqueId, inputId).then(onSuccess, onFailed);
- return deferred.promise;
- };
-
- public deleteServiceInput = (inputId:string):ng.IPromise<Models.InputModel> => {
- var deferred = this.$q.defer();
-
- var onSuccess = (input: Models.InputModel):void => {
- deferred.resolve(input)
- };
-
- var onFailed = (error:any) : void => {
- deferred.reject(error);
- };
-
- this.componentService.deleteComponentInput(this.uniqueId, inputId).then(onSuccess, onFailed);
- return deferred.promise;
- };
-
- public getArtifactsByType = (artifactGroupType:string):Models.ArtifactGroupModel => {
- switch (artifactGroupType) {
- case Utils.Constants.ArtifactGroupType.DEPLOYMENT:
- return this.deploymentArtifacts;
- case Utils.Constants.ArtifactGroupType.INFORMATION:
- return this.artifacts;
- case Utils.Constants.ArtifactGroupType.SERVICE_API:
- return this.serviceApiArtifacts;
- }
- };
- }
-}
-
diff --git a/catalog-ui/app/scripts/models/componentsInstances/componentInstance.ts b/catalog-ui/app/scripts/models/componentsInstances/componentInstance.ts
deleted file mode 100644
index af2f338998..0000000000
--- a/catalog-ui/app/scripts/models/componentsInstances/componentInstance.ts
+++ /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=========================================================
- */
-/**
- * Created by obarda on 2/4/2016.
- */
-/// <reference path="../../references"/>
-module Sdc.Models.ComponentsInstances {
- 'use strict';
-
- export class ComponentInstance{
-
- public componentUid: string;
- public componentName:string;
- public posX: number;
- public posY: number;
- public componentVersion:string;
- public description: string;
- public icon: string;
- public name: string;
- public normalizedName:string;
- public originType: string;
- public deploymentArtifacts: Models.ArtifactGroupModel;
- public propertyValueCounter: number;
- public uniqueId: string;
- public creationTime: number;
- public modificationTime: number;
- public capabilities: Models.CapabilitiesGroup;
- public requirements: Models.RequirementsGroup;
-
- //custom properties
- public certified: boolean;
- public iconSprite:string;
- public inputs: Array<Models.InputModel>;
- public properties: Array<Models.PropertyModel>;
-
- constructor(componentInstance?: ComponentInstance) {
-
- if(componentInstance) {
- this.componentUid = componentInstance.componentUid;
- this.componentName = componentInstance.componentName;
-
- this.componentVersion = componentInstance.componentVersion;
- this.description = componentInstance.description;
- this.icon = componentInstance.icon;
- this.name = componentInstance.name;
- this.normalizedName = componentInstance.normalizedName;
- this.originType = componentInstance.originType;
- this.deploymentArtifacts = new Models.ArtifactGroupModel(componentInstance.deploymentArtifacts);
- this.uniqueId = componentInstance.uniqueId;
- this.creationTime = componentInstance.creationTime;
- this.modificationTime = componentInstance.modificationTime;
- this.propertyValueCounter = componentInstance.propertyValueCounter;
- this.capabilities = new Models.CapabilitiesGroup(componentInstance.capabilities);
- this.requirements = new Models.RequirementsGroup(componentInstance.requirements);
- this.certified = componentInstance.certified;
- this.updatePosition(componentInstance.posX, componentInstance.posY);
- }
- }
-
- public isUcpe = ():boolean =>{
- if(this.originType === 'VF' && this.capabilities && this.capabilities['tosca.capabilities.Container'] && this.name.toLowerCase().indexOf('ucpe') > -1){
- return true;
- }
- return false;
- };
-
- public isVl = ():boolean =>{
- return this.originType === 'VL';
- };
-
-
- public setInstanceRC = ():void=>{
- _.forEach(this.requirements, (requirementValue:Array<any>, requirementKey)=> {
- _.forEach(requirementValue, (requirement)=> {
- if (!requirement.ownerName){
- requirement['ownerId'] = this.uniqueId;
- requirement['ownerName'] = this.name;
- }
- });
- });
- _.forEach(this.capabilities, (capabilityValue:Array<any>, capabilityKey)=> {
- _.forEach(capabilityValue, (capability)=> {
- if (!capability.ownerName){
- capability['ownerId'] = this.uniqueId;
- capability['ownerName'] = this.name;
- }
- });
- });
- };
-
- public updatePosition (posX:number, posY:number) {
- this.posX = posX;
- this.posY = posY;
- }
-
- public toJSON = ():any => {
-
- var serverInstance = angular.copy(this);
- serverInstance.certified = undefined;
- serverInstance.iconSprite = undefined;
- serverInstance.inputs = undefined;
- serverInstance.properties = undefined;
- serverInstance.requirements = undefined;
- serverInstance.capabilities = undefined;
- return serverInstance;
- };
- }
-
-}
diff --git a/catalog-ui/app/scripts/models/componentsInstances/productInstance.ts b/catalog-ui/app/scripts/models/componentsInstances/productInstance.ts
deleted file mode 100644
index 71ef9bb7d3..0000000000
--- a/catalog-ui/app/scripts/models/componentsInstances/productInstance.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/**
- * Created by obarda on 2/4/2016.
- */
-/// <reference path="../../references"/>
-module Sdc.Models.ComponentsInstances {
- 'use strict';
-
- export class ProductInstance extends ComponentInstance{
-
- constructor(componentInstance?: ProductInstance) {
- super(componentInstance);
- this.iconSprite = "sprite-product-icons";
- }
- }
-}
diff --git a/catalog-ui/app/scripts/models/componentsInstances/resourceInstance.ts b/catalog-ui/app/scripts/models/componentsInstances/resourceInstance.ts
deleted file mode 100644
index 67df05ded9..0000000000
--- a/catalog-ui/app/scripts/models/componentsInstances/resourceInstance.ts
+++ /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=========================================================
- */
-/**
- * Created by obarda on 2/4/2016.
- */
-/// <reference path="../../references"/>
-module Sdc.Models.ComponentsInstances {
- 'use strict';
-
- export class ResourceInstance extends ComponentInstance{
-
- constructor(componentInstance?: ResourceInstance) {
- super(componentInstance);
-
- this.iconSprite = "sprite-resource-icons";
- }
- }
-}
-
diff --git a/catalog-ui/app/scripts/models/componentsInstances/serviceInstance.ts b/catalog-ui/app/scripts/models/componentsInstances/serviceInstance.ts
deleted file mode 100644
index 0d78feafd3..0000000000
--- a/catalog-ui/app/scripts/models/componentsInstances/serviceInstance.ts
+++ /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=========================================================
- */
-/**
- * Created by obarda on 2/4/2016.
- */
-/// <reference path="../../references"/>
-module Sdc.Models.ComponentsInstances {
- 'use strict';
-
- export class ServiceInstance extends ComponentInstance{
-
- constructor(componentInstance?: ServiceInstance) {
- super(componentInstance);
- this.iconSprite = "sprite-services-icons";
- }
- }
-}
-
diff --git a/catalog-ui/app/scripts/models/csar-component.ts b/catalog-ui/app/scripts/models/csar-component.ts
deleted file mode 100644
index da649c1efd..0000000000
--- a/catalog-ui/app/scripts/models/csar-component.ts
+++ /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=========================================================
- */
-module Sdc.Models {
- 'use strict';
-
- export interface ICsarComponent {
- displayName:string;
- description:string;
- vspName:string;
- version:string;
- packageId:string;
- category:string;
- subCategory:string
- vendorName:string;
- packageType:string;
- vendorRelease:string;
- }
-
-}
diff --git a/catalog-ui/app/scripts/models/data-type-properties.ts b/catalog-ui/app/scripts/models/data-type-properties.ts
deleted file mode 100644
index 973978d9b2..0000000000
--- a/catalog-ui/app/scripts/models/data-type-properties.ts
+++ /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=========================================================
- */
-/**
- * Created by rcohen on 9/25/2016.
- */
-/// <reference path="../references"/>
-module Sdc.Models {
- 'use strict';
-
- export class DataTypePropertyModel {
-
- //server data
- uniqueId:string;
- type:string;
- required:boolean;
- definition:boolean;
- description:string;
- password:boolean;
- name:string;
- parentUniqueId:string;
- defaultValue:string;
- constraints:Array<any>;
- //custom
- simpleType:string;
-
- constructor(dataTypeProperty:DataTypePropertyModel) {
- if (dataTypeProperty) {
- this.uniqueId = dataTypeProperty.uniqueId;
- this.type = dataTypeProperty.type;
- this.required = dataTypeProperty.required;
- this.definition = dataTypeProperty.definition;
- this.description = dataTypeProperty.description;
- this.password = dataTypeProperty.password;
- this.name = dataTypeProperty.name;
- this.parentUniqueId = dataTypeProperty.parentUniqueId;
- this.defaultValue = dataTypeProperty.defaultValue;
- this.constraints = dataTypeProperty.constraints;
- this.simpleType = dataTypeProperty.simpleType;
- }
- }
-
- public toJSON = ():any => {
- this.simpleType = undefined;
- return this;
- };
- }
-
-}
diff --git a/catalog-ui/app/scripts/models/data-types.ts b/catalog-ui/app/scripts/models/data-types.ts
deleted file mode 100644
index d7de238f3b..0000000000
--- a/catalog-ui/app/scripts/models/data-types.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/**
- * Created by rcohen on 9/25/2016.
- */
-/// <reference path="../references"/>
-module Sdc.Models {
- 'use strict';
-
- export class DataTypeModel {
-
- //server data
- name:string;
- uniqueId:string;
- derivedFromName:string;
- creationTime:string;
- modificationTime:string;
- properties:Array<Models.DataTypePropertyModel>;
-
- constructor(dataType:DataTypeModel) {
- if (dataType) {
- this.uniqueId = dataType.uniqueId;
- this.name = dataType.name;
- this.derivedFromName = dataType.derivedFromName;
- this.creationTime = dataType.creationTime;
- this.modificationTime = dataType.modificationTime;
- this.properties = dataType.properties;
- }
- }
-
- public toJSON = ():any => {
-
- return this;
- };
- }
-
-}
-
diff --git a/catalog-ui/app/scripts/models/distribution.ts b/catalog-ui/app/scripts/models/distribution.ts
deleted file mode 100644
index 1c3a9568dd..0000000000
--- a/catalog-ui/app/scripts/models/distribution.ts
+++ /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=========================================================
- */
-/// <reference path="../references"/>
-module Sdc.Models {
- 'use strict';
-
- export class DistributionStatuses{
- public omfComponentID: string;
- public url: string;
- public timestamp:string;
- public status: string;
-
- constructor() {
- }
- }
-
-
- export class DistributionComponent{
- public omfComponentID: string;
- public url: string;
- public timestamp:string;
- public status: string;
-
- constructor() {
- }
- }
-
- export class Distribution {
- public distributionID:string;
- public timestamp:string;
- public userId:string;
- public deployementStatus:string;
- public distributionComponents:Array<Models.DistributionComponent>;
- public statusCount:any;
- //custom data
- public dateFormat:string;
-
- constructor() {
- }
- public toJSON = ():any => {
- this.dateFormat = undefined;
- return this;
- };
-
- }
-
-}
-
-
diff --git a/catalog-ui/app/scripts/models/file-download.ts b/catalog-ui/app/scripts/models/file-download.ts
deleted file mode 100644
index 8a74ed57c1..0000000000
--- a/catalog-ui/app/scripts/models/file-download.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../references"/>
-module Sdc.Models {
- 'use strict';
-
- export interface IFileDownload{
- artifactName: string;
- base64Contents:string;
- }
-}
diff --git a/catalog-ui/app/scripts/models/graph/d2-node.ts b/catalog-ui/app/scripts/models/graph/d2-node.ts
deleted file mode 100644
index 16daa5470d..0000000000
--- a/catalog-ui/app/scripts/models/graph/d2-node.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../references"/>
-
-// module Sdc.Models {
-//
-// export interface D2Node extends go.Node {
-// //TODO:should be typesafe!
-// resource: any;
-// key:string;
-// data:any;
-// canvasPosition: {x:number;y:number};
-// }
-// }
diff --git a/catalog-ui/app/scripts/models/graph/graph-links/common-base-link.ts b/catalog-ui/app/scripts/models/graph/graph-links/common-base-link.ts
deleted file mode 100644
index 7d21c5d978..0000000000
--- a/catalog-ui/app/scripts/models/graph/graph-links/common-base-link.ts
+++ /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=========================================================
- */
-/**
- * Created by obarda on 6/29/2016.
- */
-/// <reference path="../../../references"/>
-module Sdc.Models {
-
- export class CommonLinkBase {
-
- img:string;
- color:string;
- classes: string;
-
- //this is cytoscapejs fields
- public source: string;
- public target: string;
- public type: string;
- public isSdcElement: boolean;
-
- constructor() {
- this.isSdcElement = true;
- this.type = 'sdc-link';
-
- }
-
- public setImage = (imgUrl: string) => {
- this.img = imgUrl;
- };
-
- public setColor = (color: string) => {
- this.color = color;
- };
-
- }
-}
diff --git a/catalog-ui/app/scripts/models/graph/graph-links/common-ci-link-base.ts b/catalog-ui/app/scripts/models/graph/graph-links/common-ci-link-base.ts
deleted file mode 100644
index 1e7416ac3e..0000000000
--- a/catalog-ui/app/scripts/models/graph/graph-links/common-ci-link-base.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/**
- * Created by obarda on 6/29/2016.
- */
-/// <reference path="../../../references"/>
-module Sdc.Models {
-
- export interface ICommonCiLinkBase {
-
- }
-
- export class CommonCiLinkBase extends CommonLinkBase implements ICommonCiLinkBase {
-
- relation:RelationshipModel;
-
-
- constructor(relation?:RelationshipModel, singleRelationship?:Models.Relationship) {
- super();
- if (relation) {
- if(singleRelationship){
- this.relation = new Models.RelationshipModel(relation, singleRelationship);
- }else{
- this.relation = new Models.RelationshipModel(relation);
- }
- this.source = relation.fromNode;
- this.target = relation.toNode;
- } else {
- this.relation = new RelationshipModel();
- }
- }
- }
-}
diff --git a/catalog-ui/app/scripts/models/graph/graph-links/composition-graph-links/composition-ci-simple-link.ts b/catalog-ui/app/scripts/models/graph/graph-links/composition-graph-links/composition-ci-simple-link.ts
deleted file mode 100644
index c2deddbfc3..0000000000
--- a/catalog-ui/app/scripts/models/graph/graph-links/composition-graph-links/composition-ci-simple-link.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../../../references"/>
-module Sdc.Models {
-
- export class CompositionCiSimpleLink extends CompositionCiLinkBase {
-
- constructor(relation?:RelationshipModel, singleRelationship?:Models.Relationship) {
- super(relation, singleRelationship);
- this.color = Utils.Constants.GraphColors.BASE_LINK;
- this.classes = 'simple-link';
- }
- }
-}
diff --git a/catalog-ui/app/scripts/models/graph/graph-links/composition-graph-links/composition-ci-ucpe-link.ts b/catalog-ui/app/scripts/models/graph/graph-links/composition-graph-links/composition-ci-ucpe-link.ts
deleted file mode 100644
index 5d035ccc2c..0000000000
--- a/catalog-ui/app/scripts/models/graph/graph-links/composition-graph-links/composition-ci-ucpe-link.ts
+++ /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=========================================================
- */
-/// <reference path="../../../../references"/>
-module Sdc.Models {
-
- export class CompositionCiUcpeLink extends CompositionCiLinkBase {
-
- isFromUcpe: boolean;
- constructor(relation?:RelationshipModel, from?:boolean, singleRelation?:Relationship) {
- super(relation, singleRelation);
- this.isFromUcpe = from;
- this.target = relation.toNode;
- this.source = singleRelation.requirementOwnerId;
- this.relation.relationships = [singleRelation];
- this.color = Utils.Constants.GraphColors.BASE_LINK;
- }
-
- updateLinkDirection():void {}
- }
-}
diff --git a/catalog-ui/app/scripts/models/graph/graph-links/links-factory.ts b/catalog-ui/app/scripts/models/graph/graph-links/links-factory.ts
deleted file mode 100644
index 8f6cd6d321..0000000000
--- a/catalog-ui/app/scripts/models/graph/graph-links/links-factory.ts
+++ /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=========================================================
- */
-/**
- * Created by obarda on 5/1/2016.
- */
-/// <reference path="../../../references"/>
-module Sdc.Utils {
- 'use strict';
-
- export class LinksFactory {
-
- constructor() {
- }
-
- public createGraphLink = (cy: Cy.Instance, relation:Models.RelationshipModel, singleRelation:Models.Relationship):Models.CompositionCiLinkBase => {
-
- let newRelation:Models.CompositionCiLinkBase;
-
- let fromNode:Models.Graph.CompositionCiNodeBase = cy.getElementById(relation.fromNode).data();
- let toNode:Models.Graph.CompositionCiNodeBase = cy.getElementById(relation.toNode).data() ;
-
- if ((relation.fromNode && fromNode.isUcpePart) || (relation.toNode && toNode.isUcpePart )) { //Link from or to node inside ucpe
-
- if (singleRelation && singleRelation.relationship.type && singleRelation.relationship.type == 'tosca.relationships.HostedOn') {
- newRelation = new Models.LinkUcpeHost(relation, singleRelation);
- } else if (singleRelation.relationship.type && _.includes(singleRelation.relationship.type.toLowerCase(), 'link')) {
- newRelation = new Models.CompositionCiVlUcpeLink(relation, fromNode.isUcpePart, singleRelation);
- } else {
- newRelation = new Models.CompositionCiUcpeLink(relation, fromNode.isUcpePart, singleRelation);
- }
- } else if (singleRelation.relationship.type && _.includes(singleRelation.relationship.type.toLowerCase(), 'link')) {
- newRelation = new Models.CompositionCiVLink(relation, singleRelation);
- } else {
- newRelation = new Models.CompositionCiSimpleLink(relation, singleRelation);
- }
-
- return newRelation;
- };
-
- public createUcpeHostLink = (relation:Models.RelationshipModel):Models.LinkUcpeHost => {
- return new Models.LinkUcpeHost(relation);
- };
-
- public createVLLink = (relation:Models.RelationshipModel):Models.CompositionCiVLink => {
- return new Models.CompositionCiVLink(relation);
- }
-
-
- public createModuleGraphLinks= (relation:Models.RelationshipModel, singleRelation:Models.Relationship):Models.ModuleCiLinkBase => {
-
- let newRelation:Models.ModuleCiLinkBase;
-
- if (_.includes(singleRelation.relationship.type.toLowerCase(), 'link')) {
- newRelation = new Models.ModuleCiVlLink(relation, singleRelation);
- } else {
- newRelation = new Models.ModuleCiLinkBase(relation, singleRelation);
- }
-
- return newRelation;
- };
-
- }
-}
diff --git a/catalog-ui/app/scripts/models/graph/graphTooltip.ts b/catalog-ui/app/scripts/models/graph/graphTooltip.ts
deleted file mode 100644
index 08a85e1126..0000000000
--- a/catalog-ui/app/scripts/models/graph/graphTooltip.ts
+++ /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=========================================================
- */
-/// <reference path="../../references"/>
-module Sdc.Models {
- 'use strict';
-
- export class GraphTooltip{
- position: Cy.Position;
- isShow:boolean;
- text:string;
-
- constructor();
- constructor(position: Cy.Position, isShow:boolean, text: string);
- constructor(position?: Cy.Position, isShow?:boolean, text?: string) {
- this.position = position;
- this.isShow = isShow;
- this.text = text;
- }
- }
-}
-
diff --git a/catalog-ui/app/scripts/models/graph/link-menu.ts b/catalog-ui/app/scripts/models/graph/link-menu.ts
deleted file mode 100644
index 606c392982..0000000000
--- a/catalog-ui/app/scripts/models/graph/link-menu.ts
+++ /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=========================================================
- */
-/// <reference path="../../references"/>
-module Sdc.Models {
- 'use strict';
-
- export class LinkMenu {
- position:Sdc.Models.Graph.Point;
- isShow:boolean;
- link:Cy.CollectionFirstEdge;
-
- constructor();
- constructor(point:Sdc.Models.Graph.Point, isShow:boolean, link:Cy.CollectionFirstEdge);
- constructor(point?:Sdc.Models.Graph.Point, isShow?:boolean, link?:Cy.CollectionFirstEdge) {
- this.position = point ? point: new Sdc.Models.Graph.Point();
- this.isShow = isShow ? isShow : false;
- this.link = link ? link : null;
- }
- }
-}
-
diff --git a/catalog-ui/app/scripts/models/graph/match-relation.ts b/catalog-ui/app/scripts/models/graph/match-relation.ts
deleted file mode 100644
index 8d864c675b..0000000000
--- a/catalog-ui/app/scripts/models/graph/match-relation.ts
+++ /dev/null
@@ -1,109 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../references"/>
-module Sdc.Models {
- 'use strict';
-
- export class MatchBase {
- requirement:Models.Requirement;
- isFromTo:boolean;
- fromNode:string;
- toNode:string;
-
- constructor(requirement:Models.Requirement, isFromTo:boolean, fromNode:string, toNode:string) {
- this.requirement = requirement;
- this.isFromTo = isFromTo;
- this.fromNode = fromNode;
- this.toNode = toNode;
- }
-
- public getDisplayText = (menuSide:string):string => {return '';};
-
- public isOwner = (id:string):boolean => { return false; }
-
- }
-
- export class MatchReqToReq extends MatchBase {
-
- secondRequirement:Models.Requirement;
-
- constructor(requirement:Models.Requirement, secondRequirement:Models.Requirement, isFromTo:boolean, fromNode:string, toNode:string) {
- super(requirement, isFromTo, fromNode, toNode);
- this.secondRequirement = secondRequirement;
- }
-
- public getDisplayText = (menuSide:string):string => {
- if ('left' == menuSide) {
- return this.requirement.getFullTitle();
- }
- return this.secondRequirement.getFullTitle();
- };
-
- public isOwner = (id:string):boolean => {
- return this.secondRequirement.ownerId === id || this.requirement.ownerId === id;
- }
- }
-
- export class MatchReqToCapability extends MatchBase {
-
- capability:Models.Capability;
-
- constructor(requirement:Models.Requirement, capability:Models.Capability, isFromTo:boolean, fromNode:string, toNode:string) {
- super(requirement, isFromTo, fromNode, toNode);
- this.capability = capability;
- }
-
- public matchToRelation = ():Models.Relationship => {
- let relationship:Models.Relationship = new Models.Relationship();
- relationship.capability = this.capability.name;
- relationship.capabilityOwnerId = this.capability.ownerId;
- relationship.capabilityUid = this.capability.uniqueId;
- relationship.relationship = new Models.RelationType(this.capability.type);
- relationship.requirement = this.requirement.name;
- relationship.requirementOwnerId = this.requirement.ownerId;
- relationship.requirementUid = this.requirement.uniqueId;
- return relationship;
- };
-
-
- public getDisplayText = (menuSide:string):string => {
- if (this.isFromTo && 'left' == menuSide || !this.isFromTo && 'right' == menuSide) {
- return this.requirement.getFullTitle();
- }
- return this.capability.getFullTitle();
-
- };
-
- public isOwner = (id:string):boolean => {
- return this.capability.ownerId === id || this.requirement.ownerId === id;
- };
-
-
- public matchToRelationModel = ():Models.RelationshipModel => {
- let relationshipModel:Models.RelationshipModel = new Models.RelationshipModel();
- let relationship:Models.Relationship = this.matchToRelation();
- relationshipModel.setRelationshipModelParams(this.fromNode, this.toNode, [relationship]);
- return relationshipModel;
- };
- }
-
-}
-
-
diff --git a/catalog-ui/app/scripts/models/graph/nodes/base-common-node.ts b/catalog-ui/app/scripts/models/graph/nodes/base-common-node.ts
deleted file mode 100644
index e1957e61aa..0000000000
--- a/catalog-ui/app/scripts/models/graph/nodes/base-common-node.ts
+++ /dev/null
@@ -1,73 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/**
- * Created by obarda on 6/29/2016.
- */
-/// <reference path="../../../references"/>
-
-module Sdc.Models.Graph {
- 'use strict';
-
- export abstract class CommonNodeBase {
-
- public displayName:string;
- public name:string;
- public img:string;
- public certified:boolean;
- public isGroup:boolean;
- public imagesPath: string;
- public isDraggable: boolean; //we need to to manage manually the dragging on the graph inside groups (ucpe-cp is not draggable)
-
- //cytoscape fields
- public id:string;
- public type:string; //type is for the edge edition extension, by type we put the green plus icon in position
- public isSdcElement:boolean; //this fields is in order to filter sdc elements from all extensions elements
- public classes: string;
- public parent: string;
- public allowConnection: boolean; //this is for egeEdition extension in order to decide if connection to a node is available
-
- constructor() {
-
- this.imagesPath = Services.AngularJSBridge.getAngularConfig().imagesPath;
- this.type = "basic-node";
- this.isSdcElement = true;
- this.isDraggable = true;
- this.allowConnection = true;
- }
-
- public updateNameForDisplay =() => {
- let context = document.createElement("canvas").getContext("2d");
- context.font = "13px Arial";
-
- if (63 < context.measureText(this.name).width) {
- let newLen = this.name.length - 3;
- let newName = this.name.substring(0, newLen);
-
- while (60 < (context.measureText(newName).width)) {
- newName = newName.substring(0, (--newLen));
- }
- this.displayName = newName + '...';
- return;
- }
-
- this.displayName = this.name;
- };
- }
-}
diff --git a/catalog-ui/app/scripts/models/graph/nodes/common-ci-node-base.ts b/catalog-ui/app/scripts/models/graph/nodes/common-ci-node-base.ts
deleted file mode 100644
index 1597650654..0000000000
--- a/catalog-ui/app/scripts/models/graph/nodes/common-ci-node-base.ts
+++ /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=========================================================
- */
-/// <reference path="../../../references"/>
-module Sdc.Models.Graph {
-
- export abstract class CommonCINodeBase extends CommonNodeBase {
-
- public certified:boolean;
- public template:string;
- public componentInstance:Models.ComponentsInstances.ComponentInstance;
- public group:string;
-
- constructor(instance:Models.ComponentsInstances.ComponentInstance) {
- super();
- this.componentInstance = instance;
- this.id = this.componentInstance.uniqueId;
- this.name = this.componentInstance.name;
- this.img = '';
- this.certified = this.isCertified(this.componentInstance.componentVersion);
- this.displayName = instance.name;
- }
-
- private isCertified(version:string):boolean {
- return 0 === (parseFloat(version)) % 1;
- }
-
- }
-}
-
diff --git a/catalog-ui/app/scripts/models/graph/nodes/composition-graph-nodes/composition-ci-node-base.ts b/catalog-ui/app/scripts/models/graph/nodes/composition-graph-nodes/composition-ci-node-base.ts
deleted file mode 100644
index 5f4c0df3c2..0000000000
--- a/catalog-ui/app/scripts/models/graph/nodes/composition-graph-nodes/composition-ci-node-base.ts
+++ /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=========================================================
- */
-/// <reference path="../../../../references"/>
-
-module Sdc.Models.Graph {
-
- export interface ICompositionCiNodeBase {
-
- }
-
-
- export abstract class CompositionCiNodeBase extends CommonCINodeBase implements ICompositionCiNodeBase {
-
- public textPosition: string; //need to move to cp UCPE
- public isUcpe: boolean;
- public isInsideGroup: boolean;
- public isUcpePart: boolean;
-
- constructor(instance: Models.ComponentsInstances.ComponentInstance,
- public imageCreator: Utils.ImageCreatorService) {
- super(instance);
- this.init();
- }
-
- private init() {
-
- this.displayName = this.getDisplayName();
- this.isUcpe = false;
- this.isGroup = false;
- this.isUcpePart = false;
- this.isInsideGroup = false;
-
- }
-
- public initImage(node: Cy.Collection): string {
-
- this.imageCreator.getImageBase64(this.imagesPath + Utils.Constants.ImagesUrl.RESOURCE_ICONS + this.componentInstance.icon + '.png',
- this.imagesPath + Utils.Constants.ImagesUrl.RESOURCE_ICONS + 'uncertified.png')
- .then(imageBase64 => {
- this.img = imageBase64;
- node.style({'background-image': this.img});
- });
-
- return this.img;
- }
-
- protected getDisplayName(): string {
-
- let graphResourceName = Services.AngularJSBridge.getFilter('graphResourceName');
- let resourceName = Services.AngularJSBridge.getFilter('resourceName');
- return graphResourceName(resourceName(this.componentInstance.name));
- }
-
- }
-}
diff --git a/catalog-ui/app/scripts/models/graph/nodes/composition-graph-nodes/composition-ci-node-cp.ts b/catalog-ui/app/scripts/models/graph/nodes/composition-graph-nodes/composition-ci-node-cp.ts
deleted file mode 100644
index 6286c8245d..0000000000
--- a/catalog-ui/app/scripts/models/graph/nodes/composition-graph-nodes/composition-ci-node-cp.ts
+++ /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=========================================================
- */
-/// <reference path="../../../../references"/>
-
-module Sdc.Models.Graph {
-
- export class CompositionCiNodeCp extends CompositionCiNodeBase {
-
- constructor(instance:Models.ComponentsInstances.ComponentInstance,
- imageCreator: Utils.ImageCreatorService) {
- super(instance, imageCreator);
- this.initCp();
- }
-
- private initCp():void {
- let sdcConfig = Services.AngularJSBridge.getAngularConfig();
- this.img = sdcConfig.imagesPath + Utils.Constants.ImagesUrl.RESOURCE_ICONS + this.componentInstance.icon + '.png';
- this.type = "basic-small-node";
- //if the cp from type cpEndPointInstances create with another template
- if(sdcConfig.cpEndPointInstances.indexOf(this.componentInstance.icon) > -1){
- this.classes = 'cp-end-point-node';
- }else {
- this.classes = 'cp-node';
- }
- if(!this.certified) {
- this.classes = this.classes + ' not-certified';
- }
-
- }
- }
-}
diff --git a/catalog-ui/app/scripts/models/graph/nodes/composition-graph-nodes/composition-ci-node-service.ts b/catalog-ui/app/scripts/models/graph/nodes/composition-graph-nodes/composition-ci-node-service.ts
deleted file mode 100644
index 41bf0cef98..0000000000
--- a/catalog-ui/app/scripts/models/graph/nodes/composition-graph-nodes/composition-ci-node-service.ts
+++ /dev/null
@@ -1,42 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../../../references"/>
-
-module Sdc.Models.Graph {
-
- export class CompositionCiNodeService extends CompositionCiNodeBase {
-
- constructor(instance:Models.ComponentsInstances.ComponentInstance,
- imageCreator: Utils.ImageCreatorService) {
- super(instance, imageCreator);
- this.initService();
- }
-
- private initService():void {
-
- this.img = this.imagesPath + Utils.Constants.ImagesUrl.SERVICE_ICONS + this.componentInstance.icon + '.png';
- this.classes = 'service-node'
- if(!this.certified) {
- this.classes = this.classes + ' not-certified';
- }
-
- }
- }
-}
diff --git a/catalog-ui/app/scripts/models/graph/nodes/composition-graph-nodes/composition-ci-node-ucpe.ts b/catalog-ui/app/scripts/models/graph/nodes/composition-graph-nodes/composition-ci-node-ucpe.ts
deleted file mode 100644
index bc91e004f4..0000000000
--- a/catalog-ui/app/scripts/models/graph/nodes/composition-graph-nodes/composition-ci-node-ucpe.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../../../references"/>
-
-module Sdc.Models.Graph {
-
- export class NodeUcpe extends CompositionCiNodeBase {
- constructor(instance:Models.ComponentsInstances.ComponentInstance,
- imageCreator:Utils.ImageCreatorService) {
- super(instance, imageCreator);
- this.initUcpe();
- }
-
- private initUcpe():void {
- this.isUcpe = true;
- this.isGroup = true;
- this.isUcpePart = true;
- this.classes = 'ucpe-node';
- this.type = 'ucpe-node';
- this.allowConnection = false;
-
- if (!this.certified) {
- this.classes = this.classes + ' not-certified-ucpe';
- }
- }
-
- }
-}
-
-
-
-
-
diff --git a/catalog-ui/app/scripts/models/graph/nodes/composition-graph-nodes/composition-ci-node-vf.ts b/catalog-ui/app/scripts/models/graph/nodes/composition-graph-nodes/composition-ci-node-vf.ts
deleted file mode 100644
index d090960046..0000000000
--- a/catalog-ui/app/scripts/models/graph/nodes/composition-graph-nodes/composition-ci-node-vf.ts
+++ /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=========================================================
- */
-/// <reference path="../../../../references"/>
-
-module Sdc.Models.Graph {
-
- export class CompositionCiNodeVf extends CompositionCiNodeBase {
-
- constructor(instance: Models.ComponentsInstances.ComponentInstance,
- imageCreator: Utils.ImageCreatorService) {
- super(instance, imageCreator);
- this.initVf();
- }
-
- private initVf(): void {
- this.img = this.imagesPath + Utils.Constants.ImagesUrl.RESOURCE_ICONS + this.componentInstance.icon + '.png';
- this.classes = 'vf-node';
- if(!this.certified) {
- this.classes = this.classes + ' not-certified';
- }
- }
-
- }
-}
diff --git a/catalog-ui/app/scripts/models/graph/nodes/composition-graph-nodes/composition-ci-node-vfc.ts b/catalog-ui/app/scripts/models/graph/nodes/composition-graph-nodes/composition-ci-node-vfc.ts
deleted file mode 100644
index 04f45c87fb..0000000000
--- a/catalog-ui/app/scripts/models/graph/nodes/composition-graph-nodes/composition-ci-node-vfc.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../../../references"/>
-
-module Sdc.Models.Graph {
- export class CompositionCiNodeVfc extends CompositionCiNodeBase {
- constructor(instance:Models.ComponentsInstances.ComponentInstance, imageCreator: Utils.ImageCreatorService) {
- super(instance, imageCreator);
- this.initVfc();
- }
-
- private initVfc():void {
- this.img = this.imagesPath + Utils.Constants.ImagesUrl.RESOURCE_ICONS+ this.componentInstance.icon + '.png';
- }
- }
-}
diff --git a/catalog-ui/app/scripts/models/graph/nodes/nodes-factory.ts b/catalog-ui/app/scripts/models/graph/nodes/nodes-factory.ts
deleted file mode 100644
index b19b1a7261..0000000000
--- a/catalog-ui/app/scripts/models/graph/nodes/nodes-factory.ts
+++ /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=========================================================
- */
-/// <reference path="../../../references"/>
-module Sdc.Utils {
- 'use strict';
-
- export class NodesFactory {
-
- constructor(
- private imageCreator:ImageCreatorService) {
- }
-
- public createNode = (instance:Models.ComponentsInstances.ComponentInstance):Models.Graph.CompositionCiNodeBase => {
-
- if (instance.isUcpe()) {
- return new Models.Graph.NodeUcpe(instance, this.imageCreator);
- }
- if (instance.originType === Utils.Constants.ComponentType.SERVICE) {
- return new Models.Graph.CompositionCiNodeService(instance, this.imageCreator);
- }
- if (instance.originType === Utils.Constants.ResourceType.CP) {
- return new Models.Graph.CompositionCiNodeCp(instance, this.imageCreator);
- }
- if (instance.originType === Utils.Constants.ResourceType.VL) {
- return new Models.Graph.CompositionCiNodeVl(instance, this.imageCreator);
- }
-
- return new Models.Graph.CompositionCiNodeVf(instance, this.imageCreator);
- };
-
- public createModuleNode = (module:Models.Module):Models.Graph.ModuleNodeBase => {
-
- return new Models.Graph.ModuleNodeBase(module);
- };
-
- public createUcpeCpNode = (instance:Models.ComponentsInstances.ComponentInstance):Models.Graph.CompositionCiNodeCp => {
-
-
- return new Models.Graph.CompositionCiNodeUcpeCp(instance, this.imageCreator);
- }
- }
-
- NodesFactory.$inject = [
- 'ImageCreatorService'
- ];
-}
diff --git a/catalog-ui/app/scripts/models/graph/point.ts b/catalog-ui/app/scripts/models/graph/point.ts
deleted file mode 100644
index 0efd4c6040..0000000000
--- a/catalog-ui/app/scripts/models/graph/point.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-/**
- * Created by obarda on 11/7/2016.
- */
-/// <reference path="../../references"/>
-
-module Sdc.Models.Graph {
-
-
- export class Point {
- /**
- * The two-argument constructor produces the Point(x, y).
- * @param {number} x
- * @param {number} y
- */
- constructor(x?:number, y?:number) {
- this.x = x || 0;
- this.y = y || 0;
- }
-
- /**Gets or sets the x value of the Point.*/
- x:number;
-
- /**Gets or sets the y value of the Point.*/
- y:number;
- }
-} \ No newline at end of file
diff --git a/catalog-ui/app/scripts/models/graph/relationMenuObjects.ts b/catalog-ui/app/scripts/models/graph/relationMenuObjects.ts
deleted file mode 100644
index 266ed76cfa..0000000000
--- a/catalog-ui/app/scripts/models/graph/relationMenuObjects.ts
+++ /dev/null
@@ -1,138 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../references"/>
-module Sdc.Models {
- 'use strict';
-
-
- export class RelationMenuDirectiveObj {
-
- fromNode:Models.Graph.CompositionCiNodeBase;
- toNode:Models.Graph.CompositionCiNodeBase;
- // modelLinks:Array<Models.CompositionCiLinkBase>;
- mp2mpVL:Models.Components.Component;
- p2pVL:Models.Components.Component;
- menuPosition: Cy.Position;
- rightSideLink:GraphLinkMenuSide;
- leftSideLink:GraphLinkMenuSide;
- selectionText:string;
- vlType:string;
-
- constructor(fromNode:Models.Graph.CompositionCiNodeBase, toNode:Models.Graph.CompositionCiNodeBase, mp2mpVL:Models.Components.Component, p2pVL:Models.Components.Component, menuPosition:Cy.Position, possibleRelations:Array<Models.MatchBase>) {
- this.fromNode = fromNode;
- this.toNode = toNode;
- // this.modelLinks = modelLinks;
- this.mp2mpVL = mp2mpVL;
- this.p2pVL = p2pVL;
- this.menuPosition = menuPosition;
- this.leftSideLink = new GraphLinkMenuSide(this.fromNode.componentInstance);
- this.rightSideLink = new GraphLinkMenuSide(this.toNode.componentInstance);
- this.selectionText = '';
- this.vlType = null;
-
- possibleRelations.forEach((match:any) => {
-
- let reqObjKey: string = match.requirement.ownerName + match.requirement.uniqueId;
- let capObjKey: string = match.secondRequirement ? match.secondRequirement.ownerName + match.secondRequirement.uniqueId
- : match.capability.ownerName + match.capability.uniqueId;
-
- if (match.fromNode === this.leftSideLink.componentInstance.uniqueId) {
- //init the left side requirements Array
- if (!this.leftSideLink.requirements[reqObjKey]) {
- this.leftSideLink.requirements[reqObjKey] = [];
- }
- //push the match to fromNode object (from node is always the requirement)
- this.leftSideLink.requirements[reqObjKey].push(match);
-
- if (match instanceof Models.MatchReqToReq) {
- //init the right side requirements Array
- if (!this.rightSideLink.requirements[capObjKey]) {
- this.rightSideLink.requirements[capObjKey] = [];
- }
- this.rightSideLink.requirements[capObjKey].push(match);
- } else {
- //init the right side capabilities Array
- if (!this.rightSideLink.capabilities[capObjKey]) {
- this.rightSideLink.capabilities[capObjKey] = [];
- }
- //add to array
- this.rightSideLink.capabilities[capObjKey].push(match);
- }
-
- } else {
- if (!this.rightSideLink.requirements[reqObjKey]) {
- this.rightSideLink.requirements[reqObjKey] = [];
- }
- this.rightSideLink.requirements[reqObjKey].push(match);
-
- if (!this.leftSideLink.capabilities[capObjKey]) {
- this.leftSideLink.capabilities[capObjKey] = [];
- }
- this.leftSideLink.capabilities[capObjKey].push(match);
- }
- });
-
- }
- }
-
-
- export class GraphLinkMenuSide {
- public componentInstance:Models.ComponentsInstances.ComponentInstance;
- public selectedMatch:Array<any>; //match array returned by function in utils
- public requirements:any; //array of matches returned by function in utils
- public capabilities:any; //array of matches returned by function in utils
-
- constructor(componentInstance:Models.ComponentsInstances.ComponentInstance) {
- this.componentInstance = componentInstance;
- this.capabilities = {};
- this.requirements = {};
- }
-
- public selectMatchArr(matchArr:Array<Models.MatchBase>):void {
- if (this.selectedMatch === matchArr) {
- this.selectedMatch = undefined;
- } else {
- this.selectedMatch = matchArr;
- }
- }
-
-
- //TODO move to match object
- public getPreviewText(showReq:boolean):string {
- if (!this.selectedMatch) {
- return '';
- }
-
- let match:any = this.selectedMatch[0];
- if (showReq) {
- return match.requirement.ownerName + ': ' + match.requirement.name +
- ': [' + match.requirement.minOccurrences + ', ' + match.requirement.maxOccurrences + ']';
- } else if (match.secondRequirement) {
- return match.secondRequirement.ownerName + ': ' + match.secondRequirement.name +
- ': [' + match.secondRequirement.minOccurrences + ', ' + match.secondRequirement.maxOccurrences + ']';
- }
- else {
- return match.capability.ownerName + ': ' + match.capability.name +
- ': [' + match.capability.minOccurrences + ', ' + match.capability.maxOccurrences + ']';
- }
- }
- }
-
-}
diff --git a/catalog-ui/app/scripts/models/graph/relationship.ts b/catalog-ui/app/scripts/models/graph/relationship.ts
deleted file mode 100644
index e0dfbbd6d1..0000000000
--- a/catalog-ui/app/scripts/models/graph/relationship.ts
+++ /dev/null
@@ -1,107 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../references"/>
-module Sdc.Models {
- 'use strict';
-
- export class RelationshipModel {
- fromNode:string;
- toNode:string;
- relationships:Array<Relationship>;
-
- constructor(relationshipModel?:RelationshipModel, singleRelationship?:Relationship) {
- if(relationshipModel){
- this.fromNode = relationshipModel.fromNode;
- this.toNode = relationshipModel.toNode;
- this.relationships = [];
- if (relationshipModel.relationships && !singleRelationship) {
- _.forEach(relationshipModel.relationships, (relation:Models.Relationship):void => {
- this.relationships.push(new Models.Relationship(relation));
- });
- }else if(singleRelationship){
- this.relationships.push(singleRelationship);
- }
- }
- }
-
- public setRelationshipModelParams (fromNode: string, toNode:string, relationships:Array<Relationship>) {
- this.fromNode = fromNode;
- this.toNode = toNode;
- this.relationships = relationships;
- }
- }
-
- export class RelationType {
- type:string;
-
- constructor(type?:string) {
- if(type){
- this.type = type;
- }
- }
- }
-
- export class Relationship {
- capability:string;
- capabilityOwnerId:string;
- capabilityUid:string;
- relationship:RelationType;
- requirement:string;
- requirementOwnerId:string;
- requirementUid:string;
-
- constructor(relationship?:Models.Relationship) {
- if(relationship) {
- this.capability = relationship.capability;
- this.capabilityOwnerId = relationship.capabilityOwnerId;
- this.capabilityUid = relationship.capabilityUid;
- this.relationship = new RelationType(relationship.relationship.type);
- this.requirement = relationship.requirement;
- this.requirementOwnerId = relationship.requirementOwnerId;
- this.requirementUid = relationship.requirementUid;
- } else {
- this.relationship = new RelationType();
- }
-
- }
-
- //public setRelationProperties = (capability:string, capabilityOwnerId:string, capabilityUid:string, relationship:RelationType, requirement:string, requirementOwnerId:string, requirementUid:string )=>{
- // this.capability = capability;
- // this.capabilityOwnerId = capabilityOwnerId;
- // this.capabilityUid = capabilityUid;
- // this.relationship = relationship;
- // this.requirement =requirement;
- // this.requirementOwnerId = requirementOwnerId;
- // this.requirementUid = requirementUid;
- //}
-
-
- public setRelationProperties = (capability:Models.Capability, requirement:Models.Requirement)=>{
- this.capability = capability.name;
- this.capabilityOwnerId = capability.ownerId;
- this.capabilityUid = capability.uniqueId;
- this.relationship = new Models.RelationType(capability.type);
- this.requirement = requirement.name;
- this.requirementOwnerId = requirement.ownerId;
- this.requirementUid = requirement.uniqueId;
- };
-
- }
-}
diff --git a/catalog-ui/app/scripts/models/inputs.ts b/catalog-ui/app/scripts/models/inputs.ts
deleted file mode 100644
index 68e26e246e..0000000000
--- a/catalog-ui/app/scripts/models/inputs.ts
+++ /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=========================================================
- */
-/**
- * Created by obarda on 8/24/2016.
- */
-/// <reference path="../references"/>
-module Sdc.Models {
- 'use strict';
-
- export class InputModel {
-
- //server data
- uniqueId:string;
- name:string;
- type:string;
- password:boolean;
- required:boolean;
- definition:boolean;
- parentUniqueId:string;
- description:string;
- componentInstanceName:string;
- componentInstanceId:string;
-
- //costom properties
- isNew: boolean;
- properties:Array<Models.PropertyModel>;
- inputs:Array<Models.InputModel>;
- isAlreadySelected: boolean;
- filterTerm: string;
-
- constructor(input:InputModel) {
- if (input) {
- this.uniqueId = input.uniqueId;
- this.name = input.name;
- this.type = input.type;
- this.description = input.description;
- this.password = input.password;
- this.required = input.required;
- this.definition = input.definition;
- this.parentUniqueId = input.parentUniqueId;
- this.description = input.description;
- this.componentInstanceName = input.componentInstanceName;
- this.componentInstanceId = input.componentInstanceId;
- this.filterTerm = this.name + ' ' + this.description + ' ' + this.type + ' ' + this.componentInstanceName;
- }
- }
-
- public toJSON = ():any => {
- this.isNew = undefined;
- this.properties = undefined;
- this.inputs = undefined;
- this.isAlreadySelected = undefined;
- this.filterTerm = undefined;
- return this;
- };
- }
-}
diff --git a/catalog-ui/app/scripts/models/instance-inputs-properties-map.ts b/catalog-ui/app/scripts/models/instance-inputs-properties-map.ts
deleted file mode 100644
index 2c67dfd718..0000000000
--- a/catalog-ui/app/scripts/models/instance-inputs-properties-map.ts
+++ /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=========================================================
- */
-/**
- * Created by obarda on 9/12/2016.
- */
-/// <reference path="../references"/>
-module Sdc.Models {
- 'use strict';
-
- export class InstanceInputsPropertiesMapData {
- [instanceId:string]: Array<PropertyModel>;
- }
-
- export class InstanceInputsPropertiesMap {
- componentInstanceInputsProperties:InstanceInputsPropertiesMapData;
-
- constructor(componentInstanceInputsPropertiesMapData:InstanceInputsPropertiesMapData) {
- this.componentInstanceInputsProperties = componentInstanceInputsPropertiesMapData;
- }
- }
-
-}
diff --git a/catalog-ui/app/scripts/models/instances-inputs-map.ts b/catalog-ui/app/scripts/models/instances-inputs-map.ts
deleted file mode 100644
index 1643a125ae..0000000000
--- a/catalog-ui/app/scripts/models/instances-inputs-map.ts
+++ /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=========================================================
- */
-/**
- * Created by obarda on 9/12/2016.
- */
-/// <reference path="../references"/>
-module Sdc.Models {
- 'use strict';
-
- export class InstancesInputsMapData {
- [instanceId:string]: Array<InputModel>;
- }
-
- export class InstancesInputsMap {
- componentInstanceInputsMap:InstancesInputsMapData;
-
- constructor(componentInstanceInputsMapData:InstancesInputsMapData) {
- this.componentInstanceInputsMap = componentInstanceInputsMapData;
- }
- }
-
-}
diff --git a/catalog-ui/app/scripts/models/left-panel.ts b/catalog-ui/app/scripts/models/left-panel.ts
deleted file mode 100644
index a47170c7c2..0000000000
--- a/catalog-ui/app/scripts/models/left-panel.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../references"/>
-module Sdc.Models {
- 'use strict';
-
- export class LeftPanelModel {
- numberOfElements:number;
- sortedCategories:any;
-
- constructor() {
- this.numberOfElements = 0;
- this.sortedCategories = {};
- }
- }
-}
diff --git a/catalog-ui/app/scripts/models/member.ts b/catalog-ui/app/scripts/models/member.ts
deleted file mode 100644
index 21dc907333..0000000000
--- a/catalog-ui/app/scripts/models/member.ts
+++ /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=========================================================
- */
-/**
- * Created by obarda on 8/2/2016.
- */
-
-/// <reference path="../references"/>
-module Sdc.Models {
- 'use strict';
-
- export class Members {
-
- [index: string]: string;
-
- constructor(members?:Members) {
- _.forEach(members, (memberId:string, index) => {
- this[index] = memberId;
- });
- }
- }
-}
-
diff --git a/catalog-ui/app/scripts/models/modules/base-module.ts b/catalog-ui/app/scripts/models/modules/base-module.ts
deleted file mode 100644
index 2df52cc907..0000000000
--- a/catalog-ui/app/scripts/models/modules/base-module.ts
+++ /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=========================================================
- */
-
-/**
- * Created by obarda on 2/4/2016.
- */
-/// <reference path="../../references"/>
-module Sdc.Models {
- 'use strict';
-
- export class Module {
-
- public name:string;
- public groupUUID:string;
- public invariantUUID:string;
- public propertyValueCounter:number;
- public type:string;
- public typeUid:string;
- public uniqueId:string;
- public version: string;
- public artifacts: Array<string> | Array<Models.ArtifactModel>;
- public artifactsUuid: Array<string>;
- public properties: Array<Models.PropertyModel>;
- public members: Array<string>;
-
-
- constructor(module?: Module) {
- if(module) {
- this.name = module.name;
- this.groupUUID = module.groupUUID;
- this.invariantUUID = module.invariantUUID;
- this.propertyValueCounter = module.propertyValueCounter;
- this.type = module.type;
- this.typeUid = module.typeUid;
- this.uniqueId = module.uniqueId;
- this.version = module.version;
- this.artifacts = module.artifacts;
- this.artifactsUuid = module.artifactsUuid;
- this.properties = Utils.CommonUtils.initProperties(module.properties);
- this.members = module.members;
-
- this.name = this.name.replace(/:/g, '..');
-
- }
- }
- }
-
- export class DisplayModule extends Module {
-
- isBase: string;
- artifacts:Array<Models.ArtifactModel>;
-
- //custom properties
- public vfInstanceName: string;
- public heatName: string;
- public moduleName: string;
-
- constructor(displayModule?:Models.DisplayModule) {
- super(displayModule);
-
- this.isBase = displayModule.isBase;
- this.initArtifactsForDisplay(displayModule.artifacts);
-
- //splitting module name for display and edit
- let splitName:Array<string> = this.name.split('..');
- this.vfInstanceName = splitName[0];
- this.heatName = splitName[1];
- this.moduleName = splitName[2];
- }
-
- private initArtifactsForDisplay = (artifacts:Array<Models.ArtifactModel>):void => {
- this.artifacts = new Array<Models.ArtifactModel>();
- _.forEach(artifacts, (artifact:Models.ArtifactModel) => {
- this.artifacts.push(new Models.ArtifactModel(artifact));
- });
- };
-
- public updateName = ():void => {
- this.name = this.vfInstanceName + '..' + this.heatName + '..' + this.moduleName;
- };
-
- public toJSON = ():any => {
- this.vfInstanceName = undefined;
- this.heatName = undefined;
- this.moduleName = undefined;
- this.isBase = undefined;
- this.artifacts = undefined;
- return this;
- };
- }
-}
diff --git a/catalog-ui/app/scripts/models/properties.ts b/catalog-ui/app/scripts/models/properties.ts
deleted file mode 100644
index 679ca03b44..0000000000
--- a/catalog-ui/app/scripts/models/properties.ts
+++ /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=========================================================
- */
-/// <reference path="../references"/>
-module Sdc.Models {
- 'use strict';
-
- export class PropertiesGroup {
- constructor(propertiesObj?:Models.PropertiesGroup){
- _.forEach(propertiesObj, (properties:Array<Models.PropertyModel>, instance) => {
- this[instance] = [];
- _.forEach(properties, (property:Models.PropertyModel):void => {
- property.resourceInstanceUniqueId = instance;
- property.readonly = true;
- this[instance].push(new Models.PropertyModel(property));
- });
- });
- }
- }
-
- export interface IPropertyModel {
-
- //server data
- uniqueId: string;
- name: string;
- constraints: Array<Object>;
- defaultValue: string;
- description: string;
- password: boolean;
- required: boolean;
- type: string;
- source: string;
- parentUniqueId: string;
- schema: Models.SchemaPropertyGroupModel;
-
- //instance properties
- value:string;
- valueUniqueUid:string;
- path:Array<string>;
- rules:Array<Object>;
-
- //custom properties
- resourceInstanceUniqueId: string;
- readonly: boolean;
- simpleType: string;
- }
-
- export class PropertyModel implements IPropertyModel{
-
- //server data
- uniqueId:string;
- name:string;
- constraints:Array<Object>;
- defaultValue:string;
- description:string;
- password:boolean;
- required:boolean;
- type:string;
- source:string;
- parentUniqueId:string;
- schema: Models.SchemaPropertyGroupModel;
-
- //instance properties
- value:string;
- valueUniqueUid:string;
- path:Array<string>;
- rules:Array<Object>;
-
- //custom properties
- resourceInstanceUniqueId:string;
- readonly:boolean;
- simpleType: string;
- filterTerm: string;
- isAlreadySelected: boolean;
-
- constructor(property?:Models.PropertyModel) {
- if (property) {
- this.uniqueId = property.uniqueId;
- this.name = property.name;
- this.constraints = property.constraints;
- this.defaultValue = property.defaultValue;
- this.description = property.description;
- this.password = property.password;
- this.required = property.required;
- this.type = property.type;
- this.source = property.source;
- this.parentUniqueId = property.parentUniqueId;
- this.schema = property.schema;
- this.value = property.value?property.value:property.defaultValue;
- this.valueUniqueUid = property.valueUniqueUid;
- this.path = property.path;
- this.rules = property.rules;
- this.resourceInstanceUniqueId = property.resourceInstanceUniqueId;
- this.readonly = property.readonly;
- this.simpleType = property.simpleType;
-
-
- }
-
- if(!this.schema || !this.schema.property) {
- this.schema = new Models.SchemaPropertyGroupModel(new Models.SchemaProperty());
- } else {
- //forcing creating new object, so editing different one than the object in the table
- this.schema = new Models.SchemaPropertyGroupModel(new Models.SchemaProperty(this.schema.property));
- }
- if(property) {
- this.filterTerm = this.name + " " + (this.description||"") +" " + this.type;
- if(this.schema.property && this.schema.property.type) {
- this.filterTerm += " " +this.schema.property.type;
- }
- }
- }
-
- public convertToServerObject:Function = ():string => {
- let serverObject = {};
- let mapData = {
- "type": this.type,
- "required": this.required || false,
- "defaultValue": this.defaultValue != "" && this.defaultValue != "[]" && this.defaultValue != "{}" ? this.defaultValue :null,
- "description": this.description,
- "constraints": this.constraints,
- "isPassword": this.password || false,
- "schema": this.schema,
- "name": this.name
- };
- serverObject[this.name] = mapData;
-
- return JSON.stringify(serverObject);
- };
-
-
- // public convertValueToView () {
- // //unwrapping value {} or [] if type is complex
- // if (this.defaultValue && (this.type === 'map' || this.type === 'list') &&
- // ['[','{'].indexOf(this.defaultValue.charAt(0)) > -1 &&
- // [']','}'].indexOf(this.defaultValue.slice(-1)) > -1) {
- // this.defaultValue = this.defaultValue.slice(1, -1);
- // }
- //
- // //also for value - for the modal in canvas
- // if (this.value && (this.type === 'map' || this.type === 'list') &&
- // ['[','{'].indexOf(this.value.charAt(0)) > -1 &&
- // [']','}'].indexOf(this.value.slice(-1)) > -1) {
- // this.value = this.value.slice(1, -1);
- // }
- // }
-
- public toJSON = ():any => {
- if(!this.resourceInstanceUniqueId){
- this.value = undefined;
- }
- this.readonly = undefined;
- this.resourceInstanceUniqueId = undefined;
- this.simpleType = undefined;
- this.value = this.value === "{}" || this.value === "[]" ? undefined: this.value;
- this.defaultValue = this.defaultValue === "{}" || this.defaultValue === "[]" ? undefined: this.defaultValue;
- return this;
- };
- }
-}
diff --git a/catalog-ui/app/scripts/models/requirement.ts b/catalog-ui/app/scripts/models/requirement.ts
deleted file mode 100644
index 091bfc139e..0000000000
--- a/catalog-ui/app/scripts/models/requirement.ts
+++ /dev/null
@@ -1,91 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
- /*
- * Created by obarda on 4/20/2016.
- */
-/// <reference path="../references"/>
-module Sdc.Models {
- 'use strict';
- //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{
- constructor(requirementGroupObj?:Models.RequirementsGroup){
- _.forEach(requirementGroupObj, (requirementsArrayObj:Array<Models.Requirement>, instance) => {
- this[instance] = [];
- _.forEach(requirementsArrayObj, (requirement:Models.Requirement):void => {
- this[instance].push(new Models.Requirement(requirement));
- });
- });
- }
- }
-
- export class Requirement {
-
- //server data
- capability:string;
- name: string;
- ownerId: string;
- ownerName:string;
- node:string;
- uniqueId:string;
- relationship: string;
- minOccurrences: string;
- maxOccurrences: string;
- //custom
- filterTerm:string;
- constructor(requirement?:Requirement) {
-
- if(requirement) {
- this.capability = requirement.capability;
- this.name = requirement.name;
- this.ownerId = requirement.ownerId;
- this.ownerName = requirement.ownerName;
- this.node = requirement.node;
- this.uniqueId = requirement.uniqueId;
- this.relationship = requirement.relationship;
- this.minOccurrences = requirement.minOccurrences;
- this.maxOccurrences = requirement.maxOccurrences;
- this.initFilterTerm();
-
- }
- }
-
- public getFullTitle():string {
- return this.ownerName + ': ' + this.name +
- ': [' + this.minOccurrences + ', ' + this.maxOccurrences + ']';
- }
-
- public toJSON = ():any => {
- this.filterTerm = undefined;
- return this;
- };
-
- private initFilterTerm = ():void =>{
- this.filterTerm = (this.name + " ") +
- (this.ownerName + " " ) +
- (this.capability ? (this.capability.substring("tosca.capabilities.".length) + " " ) : "") +
- (this.node? (this.node.substring("tosca.nodes.".length) +" ") : "") +
- (this.relationship? (this.relationship.substring("tosca.relationships.".length) +" ") : "") +
- this.minOccurrences+","+this.maxOccurrences;
- }
- }
-}
-
-
diff --git a/catalog-ui/app/scripts/models/tab.ts b/catalog-ui/app/scripts/models/tab.ts
deleted file mode 100644
index cc42d4f348..0000000000
--- a/catalog-ui/app/scripts/models/tab.ts
+++ /dev/null
@@ -1,47 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/**
- * Created by obarda on 7/31/2016.
- */
-/// <reference path="../references"/>
-module Sdc.Models {
- 'use strict';
-
- export class Tab {
-
- public templateUrl:string;
- public controller:string;
- public data:any;
- public icon:string;
- public name:string;
-
- constructor(templateUrl:string, controller:string, name:string, data?:any, icon?:string) {
-
- this.templateUrl = templateUrl;
- this.controller = controller;
- this.icon = icon;
- this.data = data;
- this.name = name;
- }
- }
-}
-
-
-
diff --git a/catalog-ui/app/scripts/models/tooltip-data.ts b/catalog-ui/app/scripts/models/tooltip-data.ts
deleted file mode 100644
index 027904b245..0000000000
--- a/catalog-ui/app/scripts/models/tooltip-data.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../references"/>
-module Sdc.Models {
- 'use strict';
-
- export class TooltipData{
- }
-}
-
-
diff --git a/catalog-ui/app/scripts/models/user.ts b/catalog-ui/app/scripts/models/user.ts
deleted file mode 100644
index 836066f5f9..0000000000
--- a/catalog-ui/app/scripts/models/user.ts
+++ /dev/null
@@ -1,117 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../references"/>
-module Sdc.Models {
- 'use strict';
-
- export enum UserRole {
- ADMIN,
- DESIGNER,
- TESTER,
- GOVERNOR,
- OPS,
- PRODUCT_MANAGER,
- PRODUCT_STRATEGIST
- }
-
- export interface IUserManager {
- isInEditMode: boolean;
- filterTerm: string;
- }
-
- export interface IUserProperties extends IUserManager{
- firstName: string;
- lastName: string;
- userId: string;
- email: string;
- role: string;
- tempRole:string;
- lastLoginTime: string;
- status:string;
- }
-
- export interface IUser {
- resource: Services.IUserResource;
- getRole(): UserRole;
- getRoleToView(): string;
- getName(): string;
- getFirstName(): string;
- getLastName(): string;
- }
-
- export class User implements IUser {
-
- constructor(public resource:Services.IUserResource) {
- }
-
- public getLastName = () => {
- return this.resource.lastName;
- }
-
- public getFirstName = () => {
- return this.resource.firstName;
- }
-
- public getName = () => {
- return this.resource.firstName + ' ' + this.resource.lastName;
- }
-
- public getLastLogin = () => {
- if (!this.resource.lastLoginTime || this.resource.lastLoginTime === "0") {
- return "";
- } else {
- return this.resource.lastLoginTime;
- }
- }
-
- public getRole = ():UserRole => {
- let role:UserRole;
- switch (UserRole[this.resource.role.toUpperCase()]) {
- case UserRole.ADMIN:
- role = UserRole.ADMIN;
- break;
- case UserRole.DESIGNER:
- role = UserRole.DESIGNER;
- break;
- case UserRole.TESTER:
- role = UserRole.TESTER;
- break;
- case UserRole.GOVERNOR:
- role = UserRole.GOVERNOR;
- break;
- case UserRole.OPS:
- role = UserRole.OPS;
- break;
- case UserRole.PRODUCT_MANAGER:
- role = UserRole.PRODUCT_MANAGER;
- break;
- case UserRole.PRODUCT_STRATEGIST:
- role = UserRole.PRODUCT_STRATEGIST;
- break;
- }
- return role;
- }
-
- public getRoleToView = ():string => {
- let role:string = this.resource.role.toLowerCase().replace('governor','governance_Rep');
- return role.charAt(0).toUpperCase() + role.slice(1).replace('_',' ');
- }
- }
-}
diff --git a/catalog-ui/app/scripts/models/validate.ts b/catalog-ui/app/scripts/models/validate.ts
deleted file mode 100644
index 21540d38b6..0000000000
--- a/catalog-ui/app/scripts/models/validate.ts
+++ /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=========================================================
- */
-/// <reference path="../references"/>
-module Sdc.Models {
- 'use strict';
-
- export interface IValidate{
- isValid : boolean;
- }
-}
-
-
diff --git a/catalog-ui/app/scripts/modules/directive-module.ts b/catalog-ui/app/scripts/modules/directive-module.ts
deleted file mode 100644
index 70a15378fa..0000000000
--- a/catalog-ui/app/scripts/modules/directive-module.ts
+++ /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=========================================================
- */
-/// <reference path="../references"/>
-module Sdc {
- let moduleName:string = 'Sdc.Directives';
- let directiveModule:ng.IModule = angular.module(moduleName, []);
-
- directiveModule.directive('clickedOutside', Directives.ClickedOutsideDirective.factory);
- directiveModule.directive('loader', Directives.LoaderDirective.factory);
- directiveModule.directive('userHeaderDetails', Directives.UserHeaderDetailsDirective.factory);
- directiveModule.directive('ellipsis', Directives.EllipsisDirective.factory);
- directiveModule.directive('downloadArtifact', Directives.DownloadArtifactDirective.factory);
- directiveModule.directive('fileType', Directives.FileTypeDirective.factory);
- directiveModule.directive('invalidCharacters', Directives.InvalidCharactersDirective.factory);
- directiveModule.directive('tutorial', Directives.TutorialDirective.factory);
- directiveModule.directive('perfectScrollbar', Directives.PerfectScrollerDirective.factory);
- directiveModule.directive('expandCollapse', Directives.ExpandCollapseDirective.factory);
- directiveModule.directive('sdcModal', Directives.SdcModalDirective.factory);
- directiveModule.directive('sdcMessages', Directives.SdcMessagesDirective.factory);
- directiveModule.directive('sdcMessage', Directives.SdcMessageDirective.factory);
- directiveModule.directive('sdcErrorTooltip', Directives.SdcErrorTooltipDirective.factory);
- directiveModule.directive('fileOpener', Directives.FileOpenerDirective.factory);
- directiveModule.directive('fileUpload', Directives.FileUploadDirective.factory);
- directiveModule.directive('structureTree', Directives.StructureTreeDirective.factory);
- directiveModule.directive('sdcWizardStep', Directives.SdcWizardStepDirective.factory);
- directiveModule.directive('sdcPageSelector', Directives.PageSelectorDirective.factory);
- directiveModule.directive('sdcSmartTooltip', Directives.SmartTooltipDirective.factory);
- directiveModule.directive('printGraphScreen', Directives.PrintGraphScreenDirective.factory);
- directiveModule.directive('sdcTag', Directives.TagDirective.factory);
- directiveModule.directive('sdcTags', Directives.SdcTagsDirective.factory);
- directiveModule.directive('sdcKeyboardEvents', Directives.SdcKeyboardEventsDirective.factory);
- directiveModule.directive('expandCollapseMenuBox', Directives.ExpandCollapseMenuBoxDirective.factory);
- directiveModule.directive('sdcPageScroll', Directives.SdcPageScrollDirective.factory);
- directiveModule.directive('punchOut', Directives.PunchOutDirective.factory);
- directiveModule.directive('relationMenu', Directives.RelationMenuDirective.factory);
- directiveModule.directive('customValidation', Directives.CustomValidationDirective.factory);
- directiveModule.directive('ecompHeader', Directives.EcompHeaderDirective.factory);
- directiveModule.directive('editNamePopover', Directives.EditNamePopoverDirective.factory);
- directiveModule.directive('fieldsStructure', Directives.DataTypeFieldsStructureDirective.factory);
- directiveModule.directive('typeMap', Directives.TypeMapDirective.factory);
- directiveModule.directive('typeList', Directives.TypeListDirective.factory);
- directiveModule.directive('infoTooltip', Directives.InfoTooltipDirective.factory);
-
- directiveModule.directive('sdcTabs', Directives.SdcTabsDirective.factory);
- directiveModule.directive('sdcSingleTab', Directives.SdcSingleTabDirective.factory);
- directiveModule.directive('innerSdcSingleTab', Directives.InnerSdcSingleTabDirective.factory);
-
- //composition
- directiveModule.directive('palette', Directives.Palette.factory);
- directiveModule.directive('compositionGraph', Directives.CompositionGraph.factory);
-
- //deployment
- directiveModule.directive('deploymentGraph', Directives.DeploymentGraph.factory);
-
- // Layouts
- directiveModule.directive('topNav', Directives.TopNavDirective.factory);
- directiveModule.directive('topProgress', Directives.TopProgressDirective.factory);
-
- // Elements
- directiveModule.directive('sdcCheckbox', Directives.CheckboxElementDirective.factory);
- directiveModule.directive('sdcRadioButton', Directives.RadiobuttonElementDirective.factory);
-
- //Graph Utils - Common
- directiveModule.service('CommonGraphUtils', Sdc.Graph.Utils.CommonGraphUtils);
-
- //Composition Graph Utils
- directiveModule.service('CompositionGraphNodesUtils', Sdc.Graph.Utils.CompositionGraphNodesUtils);
- directiveModule.service('CompositionGraphGeneralUtils', Sdc.Graph.Utils.CompositionGraphGeneralUtils);
- directiveModule.service('CompositionGraphLinkUtils', Sdc.Graph.Utils.CompositionGraphLinkUtils);
- directiveModule.service('MatchCapabilitiesRequirementsUtils', Sdc.Graph.Utils.MatchCapabilitiesRequirementsUtils);
-
- //Composition Graph Utils
- directiveModule.service('DeploymentGraphGeneralUtils', Sdc.Graph.Utils.DeploymentGraphGeneralUtils);
-
- //Util service for graph
- directiveModule.service('NodesFactory', Sdc.Utils.NodesFactory);
- directiveModule.service('LinksFactory', Sdc.Utils.LinksFactory);
- directiveModule.service('ImageCreatorService', Sdc.Utils.ImageCreatorService);
-
- //directiveModule.service('GraphUtilsServerUpdateQueue', Sdc.Directives.GraphUtilsServerUpdateQueue);
-
- //controller for go.js
- directiveModule.controller('SdcWizardStepDirectiveController', Directives.SdcWizardStepDirectiveController);
-
- // Events
- directiveModule.directive('onLastRepeat', Directives.OnLastRepeatDirective.factory);
-}
-
-
diff --git a/catalog-ui/app/scripts/modules/filters.ts b/catalog-ui/app/scripts/modules/filters.ts
deleted file mode 100644
index 1bf31507fd..0000000000
--- a/catalog-ui/app/scripts/modules/filters.ts
+++ /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=========================================================
- */
-/// <reference path="../references"/>
-module Sdc {
-
- let moduleName: string = 'Sdc.Filters';
- let filterModule: ng.IModule = angular.module(moduleName, []);
- filterModule.filter("resourceName", Sdc.Filters.ResourceNameFilter);
- filterModule.filter("graphResourceName", Sdc.Filters.GraphResourceNameFilter);
- filterModule.filter("categoryNameFilter", Sdc.Filters.CategoryNameFilter);
- filterModule.filter("entityFilter", Sdc.Filters.EntityFilter);
- filterModule.filter("truncate", Sdc.Filters.TruncateFilter);
- filterModule.filter("catalogStatusFilter", Sdc.Filters.CatalogStatusFilter);
- filterModule.filter("categoryTypeFilter", Sdc.Filters.CategoryTypeFilter);
- filterModule.filter("stringToDateFilter", Sdc.Filters.StringToDateFilter);
- filterModule.filter("categoryIcon", Sdc.Filters.CategoryIconFilter);
- filterModule.filter("capitalizeFilter", Sdc.Filters.CapitalizeFilter);
- filterModule.filter("underscoreLessFilter", Sdc.Filters.UnderscoreLessFilter);
- filterModule.filter("resourceTypeName", Sdc.Filters.ResourceTypeFilter);
- filterModule.filter("relationName", Sdc.Filters.RelationNameFilter);
- filterModule.filter("trim", Sdc.Filters.TrimFilter);
- filterModule.filter("clearWhiteSpaces", Sdc.Filters.ClearWhiteSpacesFilter);
- filterModule.filter('testsId', Sdc.Filters.TestsIdFilter);
-
- //Added by Ikram
- filterModule.filter("productCategoryNameFilter", Sdc.Filters.ProductCategoryNameFilter);
-}
diff --git a/catalog-ui/app/scripts/modules/service-module.ts b/catalog-ui/app/scripts/modules/service-module.ts
deleted file mode 100644
index c77e8b0ad4..0000000000
--- a/catalog-ui/app/scripts/modules/service-module.ts
+++ /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=========================================================
- */
-/// <reference path="../references"/>
-module Sdc {
- let moduleName:string = 'Sdc.Services';
- let serviceModule:ng.IModule = angular.module(moduleName, []);
-
- serviceModule.service('Sdc.Services.ConfigurationUiService', Services.ConfigurationUiService);
- serviceModule.service('Sdc.Services.CookieService', Services.CookieService);
- serviceModule.service('Sdc.Services.EntityService', Services.EntityService);
- serviceModule.service('Sdc.Services.AvailableIconsService', Services.AvailableIconsService);
- serviceModule.service('Sdc.Services.RelationIconsService', Services.RelationIconsService);
- serviceModule.service('Sdc.Services.UrlToBase64Service', Services.UrlToBase64Service);
- serviceModule.service('Sdc.Services.CacheService', Services.CacheService);
- serviceModule.service('Sdc.Services.HeaderInterceptor', Services.HeaderInterceptor);
- serviceModule.service('Sdc.Services.HttpErrorInterceptor', Services.HttpErrorInterceptor);
- serviceModule.service('Sdc.Services.SharingService', Services.SharingService);
- serviceModule.service('Sdc.Services.SdcVersionService', Services.SdcVersionService);
- serviceModule.service('Sdc.Services.ActivityLogService', Services.ActivityLogService);
- serviceModule.service('Sdc.Services.OnboardingService', Services.OnboardingService);
- serviceModule.service('Sdc.Services.EcompHeaderService', Services.EcompHeaderService);
- serviceModule.service('Sdc.Services.DataTypesService', Services.DataTypesService);
-
- //Components Services
- serviceModule.service('Sdc.Services.Components.ComponentService', Services.Components.ComponentService);
- serviceModule.service('Sdc.Services.Components.ServiceService', Services.Components.ServiceService);
- serviceModule.service('Sdc.Services.Components.ResourceService', Services.Components.ResourceService);
- serviceModule.service('Sdc.Services.Components.ProductService', Services.Components.ProductService);
- serviceModule.service('LeftPaletteLoaderService', Services.Components.LeftPaletteLoaderService);
- serviceModule.service('EventListenerService', Services.EventListenerService);
- serviceModule.service('Sdc.Services.ProgressService', Services.ProgressService);
-
- //Utils
- serviceModule.service('ArtifactsUtils', Sdc.Utils.ArtifactsUtils);
- serviceModule.service('FileUtils', Sdc.Utils.FileUtils);
- serviceModule.service('ValidationUtils', Sdc.Utils.ValidationUtils);
-
-
-
-
- serviceModule.service('AngularJSBridge', Sdc.Services.AngularJSBridge);
- serviceModule.service('LoaderService', Sdc.Services.LoaderService);
-
- serviceModule.factory('Sdc.Services.UserResourceService', Services.UserResourceService.getResource);
- serviceModule.factory('Sdc.Services.CategoryResourceService', Services.CategoryResourceService.getResource);
-
-}
diff --git a/catalog-ui/app/scripts/modules/view-model-module.ts b/catalog-ui/app/scripts/modules/view-model-module.ts
deleted file mode 100644
index 19cf5b45f4..0000000000
--- a/catalog-ui/app/scripts/modules/view-model-module.ts
+++ /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=========================================================
- */
-/// <reference path="../references"/>
-module Sdc {
- let moduleName: string = 'Sdc.ViewModels';
- let viewModelModule: ng.IModule = angular.module(moduleName, []);
-
- viewModelModule
- .controller(moduleName+'.DashboardViewModel', ViewModels.DashboardViewModel)
- .controller(moduleName+'.CompositionViewModel', ViewModels.CompositionViewModel)
-
- .controller(moduleName+'.DetailsViewModel', ViewModels.DetailsViewModel)
- .controller(moduleName+'.ResourceArtifactsViewModel', ViewModels.ResourceArtifactsViewModel)
- .controller(moduleName+'.PropertyFormViewModel', ViewModels.PropertyFormViewModel)
- .controller(moduleName+'.ArtifactResourceFormViewModel', ViewModels.ArtifactResourceFormViewModel)
- .controller(moduleName+'.AttributeFormViewModel', ViewModels.AttributeFormViewModel)
- .controller(moduleName+'.ResourcePropertiesViewModel', ViewModels.ResourcePropertiesViewModel)
- .controller(moduleName+'.CatalogViewModel', ViewModels.CatalogViewModel)
- .controller(moduleName+'.OnboardVendorViewModel', ViewModels.OnboardVendorViewModel)
- .controller(moduleName+'.DistributionViewModel', ViewModels.DistributionViewModel)
- .controller(moduleName+'.SupportViewModel', ViewModels.SupportViewModel)
- .controller(moduleName+'.ConfirmationModalViewModel', ViewModels.ConfirmationModalViewModel)
- .controller(moduleName+'.EmailModalViewModel', ViewModels.EmailModalViewModel)
- .controller(moduleName+'.MessageModalViewModel', ViewModels.MessageModalViewModel)
- .controller(moduleName+'.ServerMessageModalViewModel', ViewModels.ServerMessageModalViewModel)
- .controller(moduleName+'.ClientMessageModalViewModel', ViewModels.ClientMessageModalViewModel)
- .controller(moduleName+'.ErrorViewModel', ViewModels.ErrorViewModel)
- .controller(moduleName+'.ComponentViewerViewModel', ViewModels.ComponentViewerViewModel)
- .controller(moduleName+'.RelationsViewModel', ViewModels.RelationsViewModel)
- .controller(moduleName+'.ResourceInstanceNameViewModel', ViewModels.ResourceInstanceNameViewModel)
- .controller(moduleName+'.WelcomeViewModel', ViewModels.WelcomeViewModel)
- .controller(moduleName+'.PreLoadingViewModel', ViewModels.PreLoadingViewModel)
- .controller(moduleName+'.TutorialEndViewModel', ViewModels.TutorialEndViewModel)
- .controller(moduleName+'.AdminDashboardViewModel', ViewModels.AdminDashboardViewModel)
- .controller(moduleName+'.EnvParametersFormViewModel', ViewModels.EnvParametersFormViewModel)
- .controller(moduleName+'.StructureViewModel', ViewModels.StructureViewModel)
- .controller(moduleName+'.AddCategoryModalViewModel', ViewModels.AddCategoryModalViewModel)
- .controller(moduleName+'.DashboardCoverViewModel', ViewModels.DashboardCoverViewModel)
- .controller(moduleName+'.UserManagementViewModel', ViewModels.UserManagementViewModel)
- .controller(moduleName+'.CategoryManagementViewModel', ViewModels.CategoryManagementViewModel)
- .controller(moduleName+'.WelcomeStepsControllerViewModel', ViewModels.WelcomeStepsControllerViewModel)
- .controller(moduleName+'.OnboardingModalViewModel', ViewModels.OnboardingModalViewModel)
- .controller(moduleName+'.DistributionStatusModalViewModel', ViewModels.DistributionStatusModalViewModel)
-
- .controller(moduleName+'.Wizard.EditWizardViewModel', ViewModels.Wizard.EditWizardViewModel)
- .controller(moduleName+'.Wizard.CreateWizardViewModel', ViewModels.Wizard.CreateWizardViewModel)
- .controller(moduleName+'.Wizard.ImportWizardViewModel', ViewModels.Wizard.ImportWizardViewModel)
- .controller(moduleName+'.Wizard.GeneralStepViewModel', ViewModels.Wizard.GeneralStepViewModel)
- .controller(moduleName+'.Wizard.IconsStepViewModel', ViewModels.Wizard.IconsStepViewModel)
- .controller(moduleName+'.Wizard.ArtifactInformationStepViewModel', ViewModels.Wizard.ArtifactInformationStepViewModel)
- .controller(moduleName+'.Wizard.ArtifactDeploymentStepViewModel', ViewModels.Wizard.ArtifactDeploymentStepViewModel)
- .controller(moduleName+'.Wizard.PropertiesStepViewModel', ViewModels.Wizard.PropertiesStepViewModel)
- .controller(moduleName+'.Wizard.ArtifactResourceFormStepViewModel', ViewModels.Wizard.ArtifactResourceFormStepViewModel)
- .controller(moduleName+'.Wizard.PropertyFormViewModel', ViewModels.Wizard.PropertyFormViewModel)
- .controller(moduleName+'.Wizard.HierarchyStepViewModel',ViewModels.Wizard.HierarchyStepViewModel)
-
- //NEW
- .controller(moduleName+'.WorkspaceViewModel', ViewModels.WorkspaceViewModel)
- .controller(moduleName+'.GeneralViewModel', ViewModels.GeneralViewModel)
- .controller(moduleName+'.IconsViewModel', ViewModels.IconsViewModel)
- .controller(moduleName+'.DeploymentArtifactsViewModel', ViewModels.DeploymentArtifactsViewModel)
- .controller(moduleName+'.InformationArtifactsViewModel', ViewModels.InformationArtifactsViewModel)
- .controller(moduleName+'.ToscaArtifactsViewModel', ViewModels.ToscaArtifactsViewModel)
- .controller(moduleName+'.PropertiesViewModel', ViewModels.PropertiesViewModel)
- .controller(moduleName+'.AttributesViewModel', ViewModels.AttributesViewModel)
- .controller(moduleName+'.ProductHierarchyViewModel',ViewModels.ProductHierarchyViewModel)
- .controller(moduleName+'.ActivityLogViewModel',ViewModels.ActivityLogViewModel)
- .controller(moduleName+'.ManagementWorkflowViewModel',ViewModels.ManagementWorkflowViewModel)
- .controller(moduleName+'.NetworkCallFlowViewModel',ViewModels.NetworkCallFlowViewModel)
- .controller(moduleName+'.DeploymentViewModel',ViewModels.DeploymentViewModel)
- .controller(moduleName+'.ResourceInputsViewModel',ViewModels.ResourceInputsViewModel)
- .controller(moduleName+'.ServiceInputsViewModel', ViewModels.ServiceInputsViewModel)
- .controller(moduleName+'.ReqAndCapabilitiesViewModel', ViewModels.ReqAndCapabilitiesViewModel)
-
-
-
- //TABS
- .controller(moduleName+'.HierarchyViewModel',ViewModels.HierarchyViewModel)
-}
diff --git a/catalog-ui/app/scripts/services/activity-log-service.ts b/catalog-ui/app/scripts/services/activity-log-service.ts
deleted file mode 100644
index 6fe27c447e..0000000000
--- a/catalog-ui/app/scripts/services/activity-log-service.ts
+++ /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=========================================================
- */
-/// <reference path="../references"/>
-module Sdc.Services {
- 'use strict';
-
- // Define an interface of the object you want to use, providing it's properties
- export interface IActivityLogService{
- getActivityLogService(type :string, id: string): ng.IPromise<Array<Models.Activity>>;
- }
-
- export class ActivityLogService implements IActivityLogService{
-
-
- static '$inject' = ['$http', '$q','sdcConfig'];
- private api: Models.IApi;
-
- constructor(private $http: ng.IHttpService, private $q: ng.IQService, sdcConfig: Models.IAppConfigurtaion){
- this.api = sdcConfig.api;
- }
-
- getActivityLogService = (type:string, id:string): ng.IPromise<Array<Models.Activity>> =>{
- let defer = this.$q.defer<any>();
- this.$http.get(this.api.root + this.api.GET_activity_log.replace(':type', type).replace(':id', id))
- .success((activityLog: any) => {
- defer.resolve(activityLog);
- });
- return defer.promise;
- }
- }
-}
diff --git a/catalog-ui/app/scripts/services/angular-js-bridge-service.ts b/catalog-ui/app/scripts/services/angular-js-bridge-service.ts
deleted file mode 100644
index 2d8fb01b13..0000000000
--- a/catalog-ui/app/scripts/services/angular-js-bridge-service.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-module Sdc.Services {
- export class AngularJSBridge{
- private static _$filter: ng.IFilterService;
- private static _sdcConfig: Models.IAppConfigurtaion;
-
- public static getFilter(filterName: string){
- return AngularJSBridge._$filter(filterName);
- }
-
- public static getAngularConfig(){
- return AngularJSBridge._sdcConfig;
- }
-
-
- constructor($filter: ng.IFilterService, sdcConfig: Models.IAppConfigurtaion){
- AngularJSBridge._$filter = $filter;
- AngularJSBridge._sdcConfig = sdcConfig;
- }
- }
-
- AngularJSBridge.$inject = ['$filter', 'sdcConfig']
-} \ No newline at end of file
diff --git a/catalog-ui/app/scripts/services/available-icons-service.ts b/catalog-ui/app/scripts/services/available-icons-service.ts
deleted file mode 100644
index 5c20afe5f2..0000000000
--- a/catalog-ui/app/scripts/services/available-icons-service.ts
+++ /dev/null
@@ -1,105 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/**
- * Created by obarda on 2/23/2016.
- */
-/// <reference path="../references"/>
-module Sdc.Services {
- 'use strict';
-
- interface IAvailableIconsService {
- getIcons(componentType: Utils.Constants.ComponentType):Array<string>;
- }
-
- export class AvailableIconsService implements IAvailableIconsService {
- constructor() {}
- public getIcons = (componentType: string): Array<string> => {
- let icons: string[];
- switch (componentType){
- case Utils.Constants.ComponentType.SERVICE:
- icons = [
- 'call_controll',
- 'mobility',
- 'network_l_1-3',
- 'network_l_4'
- ];
- break;
-
- case Utils.Constants.ComponentType.RESOURCE:
- icons= [
- 'router',
- 'database',
- 'network',
- 'objectStorage',
- 'connector',
- 'brocade',
- 'cisco',
- 'ericsson',
- 'tropo',
- 'fortinet',
- 'att',
- 'broadsoft',
- 'alcatelLucent',
- 'metaswitch',
- 'aricent',
- 'mySql',
- 'oracle',
- 'nokia_siemens',
- 'juniper',
- 'call_controll',
- 'borderElement',
- 'applicationServer',
- 'server',
- 'port',
- 'loadBalancer',
- 'compute',
- 'gateway',
- 'cp',
- 'vl',
- 'vfw',
- 'firewall'
- ];
- break;
-
- case Utils.Constants.ComponentType.PRODUCT:
- icons = [
- 'vfw',
- 'network',
- 'security',
- 'cloud',
- 'setting',
- 'orphan',
- 'wanx',
- 'vrouter',
- 'ucpe',
- 'mobility'
-
- ];
- break;
-
- }
- return icons;
- }
-
- }
-}
-
-
-
diff --git a/catalog-ui/app/scripts/services/cache-service.ts b/catalog-ui/app/scripts/services/cache-service.ts
deleted file mode 100644
index 3e5e5495c7..0000000000
--- a/catalog-ui/app/scripts/services/cache-service.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../references"/>
-module Sdc.Services {
-
- 'use strict';
-
- interface ICacheService {
- get(key:string):any;
- set(key:string, value:any):void;
- }
-
- export class CacheService implements ICacheService {
-
- static '$inject' = ['sdcConfig', '$document'];
- private storage:Utils.Dictionary<string, any>;
-
- constructor() {
- this.storage = new Utils.Dictionary<string, any>();
- };
-
- public get = (key:string):any => {
- return this.storage.getValue(key);
- };
-
- public set = (key:string, value:any):void => {
- this.storage.setValue(key, value);
- };
-
- public remove = (key:string):void => {
- if (this.storage.containsKey(key)){
- this.storage.remove(key);
- }
- };
-
- public contains = (key:string):boolean => {
- return this.storage.containsKey(key);
- };
-
- }
-}
diff --git a/catalog-ui/app/scripts/services/category-resource-service.ts b/catalog-ui/app/scripts/services/category-resource-service.ts
deleted file mode 100644
index eef1b445e6..0000000000
--- a/catalog-ui/app/scripts/services/category-resource-service.ts
+++ /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=========================================================
- */
-/// <reference path="../references"/>
-module Sdc.Services {
- import IMainCategory = Sdc.Models.IMainCategory;
- 'use strict';
-
- // Define an interface of the object you want to use, providing it's properties
- export interface ICategoryResource extends Models.IUserProperties,ng.resource.IResource<ICategoryResource>{
- name:string;
- uniqueId:string;
- subcategories:Array<ICategoryResource>;
-
- getAllCategories(params?: Object, success?: Function, error?: Function): Array<IMainCategory>;
- $saveSubCategory(params?: Object, success?: Function, error?: Function): any;
- $deleteSubCategory(params?: Object, success?: Function, error?: Function): any;
- }
-
- // Define your resource, adding the signature of the custom actions
- export interface ICategoryResourceClass extends ng.resource.IResourceClass<ICategoryResource>{
- getAllCategories(params?: Object, success?: Function, error?: Function): Array<IMainCategory>;
- saveSubCategory(params?: Object, success?: Function, error?: Function): any;
- deleteSubCategory(params?: Object, success?: Function, error?: Function): any;
- }
-
- export class CategoryResourceService{
-
- public static getResource = (
- $resource: ng.resource.IResourceService,
- sdcConfig: Models.IAppConfigurtaion
- ): ICategoryResourceClass => {
-
- // Define your custom actions here as IActionDescriptor
- let getAllCategoriesAction : ng.resource.IActionDescriptor = {
- method: 'GET',
- isArray: true,
- url: sdcConfig.api.root + sdcConfig.api.GET_categories
- };
- let saveSubCategory : ng.resource.IActionDescriptor = {
- method: 'POST',
- isArray: false,
- url: sdcConfig.api.root + sdcConfig.api.POST_subcategory
- };
- let deleteSubCategory: ng.resource.IActionDescriptor = {
- method: 'DELETE',
- isArray: false,
- url: sdcConfig.api.root + sdcConfig.api.POST_subcategory
- };
-
-
- let url: string = sdcConfig.api.root + sdcConfig.api.POST_category;
- let categoryResource: ICategoryResourceClass = <ICategoryResourceClass>$resource(
- url,
- { types: '@types', categoryId: '@categoryId' },
- {
- getAllCategories: getAllCategoriesAction,
- saveSubCategory: saveSubCategory,
- deleteSubCategory: deleteSubCategory
- }
- );
-
- return categoryResource;
- }
- }
- CategoryResourceService.getResource.$inject = ['$resource', 'sdcConfig'];
-}
diff --git a/catalog-ui/app/scripts/services/components/component-service.ts b/catalog-ui/app/scripts/services/components/component-service.ts
deleted file mode 100644
index 393ea71c03..0000000000
--- a/catalog-ui/app/scripts/services/components/component-service.ts
+++ /dev/null
@@ -1,698 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../references"/>
-module Sdc.Services.Components {
-
- 'use strict';
-
- declare let CryptoJS:any;
-
- export interface IComponentService {
-
- getComponent(id:string);
- updateComponent(component:Models.Components.Component):ng.IPromise<Models.Components.Component>;
- changeLifecycleState(component:Models.Components.Component, state:string, userRemarks:any):ng.IPromise<Models.Components.Component> ;
- validateName(newName:string, subtype?:string):ng.IPromise<Models.IValidate>;
- createComponent(component:Models.Components.Component):ng.IPromise<Models.Components.Component>;
- addOrUpdateArtifact(componentId:string, artifact:Models.ArtifactModel):ng.IPromise<Models.ArtifactModel>;
- deleteArtifact(componentId:string, artifact:string, artifactLabel):ng.IPromise<Models.ArtifactModel>;
- addProperty(componentId:string, property:Models.PropertyModel):ng.IPromise<Models.PropertyModel>;
- updateProperty(componentId:string, property:Models.PropertyModel):ng.IPromise<Models.PropertyModel>;
- addAttribute(componentId:string, attribute:Models.AttributeModel):ng.IPromise<Models.AttributeModel>;
- updateAttribute(componentId:string, attribute:Models.AttributeModel):ng.IPromise<Models.AttributeModel>;
- deleteProperty(componentId:string, propertyId:string):ng.IPromise<Models.PropertyModel>;
- deleteAttribute(componentId:string, attributeId:string):ng.IPromise<Models.AttributeModel>;
- changeResourceInstanceVersion(componentId:string, componentInstanceId:string, componentUid:string):ng.IPromise<Models.ComponentsInstances.ComponentInstance>;
- updateInstanceArtifact(componentId:string, instanceId:string, artifact:Models.ArtifactModel):ng.IPromise<Models.ArtifactModel>;
- addInstanceArtifact(componentId: string, instanceId: string, artifact:Models.ArtifactModel):ng.IPromise<Models.ArtifactModel>;
- deleteInstanceArtifact(componentId: string, instanceId: string, artifact:string, artifactLabel):ng.IPromise<Models.ArtifactModel>;
- createComponentInstance(componentId:string, componentInstance:Models.ComponentsInstances.ComponentInstance):ng.IPromise<Models.ComponentsInstances.ComponentInstance>;
- updateComponentInstance(componentId:string, componentInstance:Models.ComponentsInstances.ComponentInstance):ng.IPromise<Models.ComponentsInstances.ComponentInstance>;
- updateMultipleComponentInstances(componentId:string, instances:Array<Models.ComponentsInstances.ComponentInstance>):ng.IPromise< Array<Models.ComponentsInstances.ComponentInstance>>;
- downloadArtifact(componentId:string, artifactId:string):ng.IPromise<Models.IFileDownload>;
- uploadInstanceEnvFile(componentId:string, instanceId:string, artifact:Models.ArtifactModel):ng.IPromise<Models.ArtifactModel>;
- downloadInstanceArtifact(componentId:string, instanceId:string, artifactId:string):ng.IPromise<Models.IFileDownload>;
- deleteComponentInstance(componentId:string, componentInstanceId:string):ng.IPromise<Models.ComponentsInstances.ComponentInstance>;
- createRelation(componentId:string, link:Models.RelationshipModel):ng.IPromise<Models.RelationshipModel>;
- deleteRelation(componentId:string, link:Models.RelationshipModel):ng.IPromise<Models.RelationshipModel>;
- getRequirementsCapabilities(componentId:string):ng.IPromise<any>;
- updateInstanceProperty(componentId:string, property:Models.PropertyModel):ng.IPromise<Models.PropertyModel>;
- updateInstanceAttribute(componentId:string, attribute:Models.AttributeModel):ng.IPromise<Models.AttributeModel>;
- getComponentInstancesFilteredByInputsAndProperties(componentId:string, searchText:string):ng.IPromise<Array<Models.ComponentsInstances.ComponentInstance>>
- getComponentInstanceInputs(componentId:string, instanceId:string, originComponentUid):ng.IPromise<Array<Models.InputModel>>;
- getComponentInputs(componentId:string):ng.IPromise<Array<Models.InputModel>>;
- getComponentInstanceInputProperties(componentId:string, instanceId:string, inputId:string):ng.IPromise<Array<Models.PropertyModel>>;
- getModuleForDisplay(componentId:string, moduleId:string):ng.IPromise<Models.DisplayModule>;
- updateGroupMetadata(componentId:string, group:Models.Module):ng.IPromise<Models.Module>;
- getComponentInputInputs(serviceId:string, input:string): ng.IPromise<Array<Models.InputModel>>;
- createInputsFromInstancesInputs(serviceId:string, instancesInputsMap:Models.InstancesInputsMap): ng.IPromise<Array<Models.InputModel>>;
- createInputsFromInstancesInputsProperties(resourceId:string, instanceInputsPropertiesMap:Models.InstanceInputsPropertiesMap): ng.IPromise<Array<Models.PropertyModel>>;
- deleteComponentInput(serviceId:string, inputId:string):ng.IPromise<Models.InputModel>;
- }
-
- export class ComponentService implements IComponentService {
-
- static '$inject' = [
- '$log',
- 'Restangular',
- 'sdcConfig',
- 'Sdc.Services.SharingService',
- '$q',
- '$interval',
- '$base64',
- 'ComponentInstanceFactory'
- ];
-
- constructor(protected $log: ng.ILogService,
- protected restangular:restangular.IElement,
- protected sdcConfig:Models.IAppConfigurtaion,
- protected sharingService:Sdc.Services.SharingService,
- protected $q:ng.IQService,
- protected $interval:any,
- protected $base64:any,
- protected ComponentInstanceFactory:Utils.ComponentInstanceFactory) {
-
- this.restangular.setBaseUrl(sdcConfig.api.root + sdcConfig.api.component_api_root);
- this.restangular.setRequestInterceptor(function (elem, operation) {
- if (operation === "remove") {
- return null;
- }
- return elem;
- });
- // this.restangular.setDefaultHeaders({'Content-Type': 'application/json; charset=UTF-8'});
- }
-
- //this function is override by each service, we need to change this method to abstract when updtaing typescript version
- protected createComponentObject = (component:Models.Components.Component):Models.Components.Component => {
- return component;
- };
-
- public getComponent = (id:string):ng.IPromise<Models.Components.Component> => {
- let deferred = this.$q.defer();
- this.restangular.one(id).get().then((response:Models.Components.Component) => {
- let component:Models.Components.Component = this.createComponentObject(response);
- //this.$log.debug("Component Loaded successfully : ", component);
- deferred.resolve(component);
- }, (err)=> {
- this.$log.debug("Failed to load component with ID: " + id);
- deferred.reject(err);
- });
- return deferred.promise;
- };
-
- public updateComponent = (component:Models.Components.Component):ng.IPromise<Models.Components.Component> => {
- // If this is resource
- if (component instanceof Sdc.Models.Components.Resource) {
- let resource:Sdc.Models.Components.Resource = <Sdc.Models.Components.Resource>component;
- if (resource.importedFile) {
- // Update resource with payload data.
- return this.updateResourceWithPayload(resource);
- } else {
- if (component.csarUUID) {
- // Update resource without payload data.
- return this.updateResource(component);
- } else {
- // Update resource without payload data (metadata).
- return this.updateResourceMetadata(component);
- }
- }
- } else {
- return this.updateService(component);
- }
- };
-
- private updateService = (component:Models.Components.Component):ng.IPromise<Models.Components.Component> => {
- let deferred = this.$q.defer();
- this.restangular.one(component.uniqueId).one("metadata").customPUT(JSON.stringify(component)).then((response:Models.Components.Component) => {
- let component:Models.Components.Component = this.createComponentObject(response);
- deferred.resolve(component);
- }, (err)=> {
- deferred.reject(err);
- });
- return deferred.promise;
- };
-
- private updateResource = (component:Models.Components.Component):ng.IPromise<Models.Components.Component> => {
- let deferred = this.$q.defer();
- this.restangular.one(component.uniqueId).customPUT(JSON.stringify(component)).then((response:Models.Components.Component) => {
- let component:Models.Components.Component = this.createComponentObject(response);
- deferred.resolve(component);
- }, (err)=> {
- deferred.reject(err);
- });
- return deferred.promise;
- };
-
- private updateResourceMetadata = (component:Models.Components.Component):ng.IPromise<Models.Components.Component> => {
- let deferred = this.$q.defer();
- this.restangular.one(component.uniqueId).one('metadata').customPUT(JSON.stringify(component)).then((response:Models.Components.Component) => {
- let component:Models.Components.Component = this.createComponentObject(response);
- deferred.resolve(component);
- }, (err)=> {
- deferred.reject(err);
- });
- return deferred.promise;
- };
-
- /**
- * Only resource can be updated with payload data
- * @param component
- * @returns {IPromise<T>}
- */
- private updateResourceWithPayload = (resource:Sdc.Models.Components.Resource):ng.IPromise<Models.Components.Component> => {
- let deferred = this.$q.defer();
-
- resource.payloadData = resource.importedFile.base64;
- resource.payloadName = resource.importedFile.filename;
- let headerObj = this.getHeaderMd5(resource);
-
- this.restangular.one(resource.uniqueId).customPUT(JSON.stringify(resource), '', {}, headerObj).then((response:Models.Components.Component) => {
- let componentResult:Models.Components.Component = this.createComponentObject(response);
- deferred.resolve(componentResult);
- }, (err)=> {
- deferred.reject(err);
- });
-
- return deferred.promise;
- };
-
- public createComponent = (component:Models.Components.Component):ng.IPromise<Models.Components.Component> => {
- let deferred = this.$q.defer();
- let headerObj = this.getHeaderMd5(component);
- this.restangular.customPOST(JSON.stringify(component), '', {}, headerObj).then((response:Models.Components.Component) => {
- let component:Models.Components.Component = this.createComponentObject(response);
- deferred.resolve(component);
- }, (err)=> {
- deferred.reject(err);
- });
- return deferred.promise;
- };
-
- public validateName = (newName:string, subtype?:string):ng.IPromise<Models.IValidate> => {
- let deferred = this.$q.defer();
- this.restangular.one("validate-name").one(newName).get({'subtype': subtype}).then((response:any) => {
- deferred.resolve(response.plain());
- }, (err)=> {
- deferred.reject(err);
- });
- return deferred.promise;
- };
-
- public changeLifecycleState = (component:Models.Components.Component, state:string, userRemarks:any):ng.IPromise<Models.Components.Component> => {
- let deferred = this.$q.defer();
- this.restangular.one(component.uniqueId).one(state).customPOST(userRemarks).then((response:Models.Components.Component) => {
- this.sharingService.addUuidValue(response.uniqueId, response.uuid);
- let component:Models.Components.Component = this.createComponentObject(response);
- deferred.resolve(component);
- }, (err)=> {
- deferred.reject(err);
- });
- return deferred.promise;
- };
-
- // ------------------------------------------------ Artifacts API --------------------------------------------------//
- public addOrUpdateArtifact = (componentId:string, artifact:Models.ArtifactModel):ng.IPromise<Models.ArtifactModel> => {
- let deferred = this.$q.defer();
- let headerObj = {};
- if (artifact.payloadData) {
- headerObj = this.getHeaderMd5(artifact);
- }
- this.restangular.one(componentId).one("artifacts").customPOST(JSON.stringify(artifact), artifact.uniqueId, {}, headerObj).then((response:any) => {
- deferred.resolve(response.plain());
- }, (err)=> {
- deferred.reject(err);
- });
- return deferred.promise;
- };
-
- public downloadArtifact = (componentId:string, artifactId:string):ng.IPromise<Models.IFileDownload> => {
- let deferred = this.$q.defer();
- this.restangular.one(componentId).one("artifacts").one(artifactId).get().then((response:any) => {
- deferred.resolve(response.plain());
- }, (err)=> {
- deferred.reject(err);
- });
- return deferred.promise;
- };
-
- public deleteArtifact = (componentId:string, artifactId:string, artifactLabel:string):ng.IPromise<Models.ArtifactModel> => {
- let deferred = this.$q.defer();
- this.restangular.one(componentId).one("artifacts").one(artifactId).remove({'operation': artifactLabel}).then((response:Models.ArtifactModel) => {
- deferred.resolve(response);
- }, (err)=> {
- deferred.reject(err);
- });
- return deferred.promise;
- };
-
-
- // ------------------------------------------------ Properties API --------------------------------------------------//
- public addProperty = (componentId:string, property:Models.PropertyModel):ng.IPromise<Models.PropertyModel> => {
- let deferred = this.$q.defer();
- this.restangular.one(componentId).one("properties").customPOST(property.convertToServerObject()).then((response:any) => {
- let property:Models.PropertyModel = new Models.PropertyModel(response[Object.keys(response)[0]]);
- deferred.resolve(property);
- }, (err)=> {
- deferred.reject(err);
- });
- return deferred.promise;
- };
-
- public updateProperty = (componentId:string, property:Models.PropertyModel):ng.IPromise<Models.PropertyModel> => {
- let deferred = this.$q.defer();
- this.restangular.one(componentId).one("properties").one(property.uniqueId).customPUT(property.convertToServerObject()).then((response:any) => {
- let property:Models.PropertyModel = new Models.PropertyModel(response[Object.keys(response)[0]]);
- deferred.resolve(property);
- }, (err)=> {
- deferred.reject(err);
- });
- return deferred.promise;
- };
-
- public deleteProperty = (componentId:string, propertyId:string):ng.IPromise<Models.PropertyModel> => {
- let deferred = this.$q.defer();
- this.restangular.one(componentId).one("properties").one(propertyId).remove().then((response:any) => {
- deferred.resolve(response);
- }, (err)=> {
- deferred.reject(err);
- });
- return deferred.promise;
- };
-
- // ------------------------------------------------ Attributes API --------------------------------------------------//
- public addAttribute = (componentId:string, attribute:Models.AttributeModel):ng.IPromise<Models.AttributeModel> => {
- let deferred = this.$q.defer();
- this.restangular.one(componentId).one("attributes").customPOST(attribute.convertToServerObject()).then((response:any) => {
- let attribute:Models.AttributeModel = new Models.AttributeModel(response);
- deferred.resolve(attribute);
- }, (err)=> {
- deferred.reject(err);
- });
- return deferred.promise;
- };
-
- public updateAttribute = (componentId:string, attribute:Models.AttributeModel):ng.IPromise<Models.AttributeModel> => {
- let deferred = this.$q.defer();
- this.restangular.one(componentId).one("attributes").one(attribute.uniqueId).customPUT(attribute.convertToServerObject()).then((response:any) => {
- let attribute:Models.AttributeModel = new Models.AttributeModel(response);
- deferred.resolve(attribute);
- }, (err)=> {
- deferred.reject(err);
- });
- return deferred.promise;
- };
-
- public deleteAttribute = (componentId:string, attributeId:string):ng.IPromise<Models.AttributeModel> => {
- let deferred = this.$q.defer();
- this.restangular.one(componentId).one("attributes").one(attributeId).remove().then((response:any) => {
- deferred.resolve(response);
- }, (err)=> {
- deferred.reject(err);
- });
- return deferred.promise;
- };
-
- // ------------------------------------------------ Component Instances API --------------------------------------------------//
-
- public createComponentInstance = (componentId:string, componentInstance:Models.ComponentsInstances.ComponentInstance):ng.IPromise<Models.ComponentsInstances.ComponentInstance> => {
- let deferred = this.$q.defer();
- this.restangular.one(componentId).one("resourceInstance").customPOST(JSON.stringify(componentInstance)).then((response:any) => {
- let componentInstance:Models.ComponentsInstances.ComponentInstance = Utils.ComponentInstanceFactory.createComponentInstance(response);
- this.$log.debug("Component Instance created", componentInstance);
- deferred.resolve(componentInstance);
- }, (err)=> {
- this.$log.debug("Failed to create componentInstance. With Name: " + componentInstance.name);
- deferred.reject(err);
- });
- return deferred.promise;
- };
-
- public updateComponentInstance = (componentId:string, componentInstance:Models.ComponentsInstances.ComponentInstance):ng.IPromise<Models.ComponentsInstances.ComponentInstance> => {
- let deferred = this.$q.defer();
- this.restangular.one(componentId).one("resourceInstance").one(componentInstance.uniqueId).customPOST(JSON.stringify(componentInstance)).then((response:any) => {
- let componentInstance:Models.ComponentsInstances.ComponentInstance = Utils.ComponentInstanceFactory.createComponentInstance(response);
- this.$log.debug("Component Instance was updated", componentInstance);
- deferred.resolve(componentInstance);
- }, (err)=> {
- this.$log.debug("Failed to update componentInstance. With ID: " + componentInstance.uniqueId + "Name: " + componentInstance.name);
- deferred.reject(err);
- });
- return deferred.promise;
- };
-
- public updateMultipleComponentInstances = (componentId:string, instances:Array<Models.ComponentsInstances.ComponentInstance>):ng.IPromise<Array<Models.ComponentsInstances.ComponentInstance>> => {
- let deferred = this.$q.defer();
- this.restangular.one(componentId).one("resourceInstance/multipleComponentInstance").customPOST(JSON.stringify(instances)).then((response:any) => {
- this.$log.debug("Multiple Component Instances was updated", response);
- let updateInstances:Array<Models.ComponentsInstances.ComponentInstance> = new Array<Models.ComponentsInstances.ComponentInstance>();
- _.forEach(response, (componentInstance:Models.ComponentsInstances.ComponentInstance) => {
- let updatedComponentInstance:Models.ComponentsInstances.ComponentInstance = Utils.ComponentInstanceFactory.createComponentInstance(componentInstance);
- updateInstances.push(updatedComponentInstance);
- });
- deferred.resolve(updateInstances);
- }, (err)=> {
- this.$log.debug("Failed to update Multiple componentInstance.");
- deferred.reject(err);
- });
- return deferred.promise;
- };
-
- public deleteComponentInstance = (componentId:string, componentInstanceId:string):ng.IPromise<Models.ComponentsInstances.ComponentInstance> => {
- let deferred = this.$q.defer();
- this.restangular.one(componentId).one("resourceInstance").one(componentInstanceId).remove().then(() => {
- this.$log.debug("Component Instance was deleted");
- deferred.resolve();
- }, (err)=> {
- this.$log.debug("Failed to delete componentInstance. With ID: " + componentInstanceId);
- deferred.reject(err);
- });
- return deferred.promise;
- };
-
- public changeResourceInstanceVersion = (componentId:string, componentInstanceId:string, componentUid:string):ng.IPromise<Models.ComponentsInstances.ComponentInstance> => {
- let deferred = this.$q.defer();
- this.restangular.one(componentId).one("resourceInstance").one(componentInstanceId).one("changeVersion").customPOST({'componentUid': componentUid}).then((response:any) => {
- let componentInstance:Models.ComponentsInstances.ComponentInstance = Utils.ComponentInstanceFactory.createComponentInstance(response);
- deferred.resolve(componentInstance);
- }, (err)=> {
- deferred.reject(err);
- });
- return deferred.promise;
- };
-
- public downloadInstanceArtifact = (componentId:string, instanceId:string, artifactId:string):ng.IPromise<Models.IFileDownload> => {
- let deferred = this.$q.defer();
- this.restangular.one(componentId).one("resourceInstances").one(instanceId).one("artifacts").one(artifactId).get().then((response:any) => {
- deferred.resolve(response.plain());
- }, (err)=> {
- deferred.reject(err);
- });
- return deferred.promise;
- };
-
- public updateInstanceArtifact = (componentId:string, instanceId:string, artifact:Models.ArtifactModel):ng.IPromise<Models.ArtifactModel> => {
- let deferred = this.$q.defer();
- let headerObj = {};
- if(artifact.payloadData){
- headerObj = this.getHeaderMd5(artifact);
- }
- this.restangular.one(componentId).one("resourceInstance").one(instanceId).one("artifacts").customPOST(JSON.stringify(artifact), artifact.uniqueId , {}, headerObj).then((response: any) => {
- let newArtifact = new Models.ArtifactModel(response);
- deferred.resolve(newArtifact);
- }, (err)=>{
- deferred.reject(err);
- });
- return deferred.promise;
- };
-
- public addInstanceArtifact = (componentId: string, instanceId: string, artifact:Models.ArtifactModel): ng.IPromise<Models.ArtifactModel> => {
- let deferred = this.$q.defer();
- let headerObj = {};
- if(artifact.payloadData){
- headerObj = this.getHeaderMd5(artifact);
- }
- this.restangular.one(componentId).one("resourceInstance").one(instanceId).one("artifacts").customPOST(JSON.stringify(artifact), artifact.uniqueId , {}, headerObj).then((response: any) => {
- let artifact:Models.ArtifactModel = new Models.ArtifactModel(response.plain());
- deferred.resolve(artifact);
- }, (err)=> {
- deferred.reject(err);
- });
- return deferred.promise;
- };
-
- public deleteInstanceArtifact = (componentId: string , instanceId: string, artifactId:string, artifactLabel: string): ng.IPromise<Models.ArtifactModel> => {
- let deferred = this.$q.defer();
- this.restangular.one(componentId).one("resourceInstance").one(instanceId).one("artifacts").one(artifactId).remove({'operation': artifactLabel}).then((response: Models.ArtifactModel) => {
- deferred.resolve(response);
- }, (err)=>{
- deferred.reject(err);
- });
- return deferred.promise;
- };
-
- public uploadInstanceEnvFile = (componentId:string, instanceId:string, artifact:Models.ArtifactModel):ng.IPromise<Models.ArtifactModel> => {
- let deferred = this.$q.defer();
- let headerObj = {};
- if (artifact.payloadData) {
- headerObj = this.getHeaderMd5(artifact);
- }
- this.restangular.one(componentId).one("resourceInstance").one(instanceId).one("artifacts").customPOST(JSON.stringify(artifact), artifact.uniqueId, {}, headerObj).then((response:any) => {
- let newArtifact = new Models.ArtifactModel(response);
- deferred.resolve(newArtifact);
- }, (err)=> {
- deferred.reject(err);
- });
- return deferred.promise;
- };
-
- public updateInstanceProperty = (componentId:string, property:Models.PropertyModel):ng.IPromise<Models.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 Models.PropertyModel(response);
- newProperty.readonly = true;
- newProperty.resourceInstanceUniqueId = instanceId;
- deferred.resolve(newProperty);
- }, (err)=> {
- deferred.reject(err);
- });
- return deferred.promise;
- };
-
- public updateInstanceAttribute = (componentId:string, attribute:Models.AttributeModel):ng.IPromise<Models.AttributeModel> => {
- let deferred = this.$q.defer();
- let instanceId = attribute.resourceInstanceUniqueId;
- this.restangular.one(componentId).one("resourceInstance").one(instanceId).one("attribute").customPOST(JSON.stringify(attribute)).then((response:any) => {
- let newAttribute = new Models.AttributeModel(response);
- newAttribute.readonly = true;
- newAttribute.resourceInstanceUniqueId = instanceId;
- deferred.resolve(newAttribute);
- }, (err)=> {
- deferred.reject(err);
- });
- return deferred.promise;
- };
-
- public createRelation = (componentId:string, link:Models.RelationshipModel):ng.IPromise<Models.RelationshipModel> => {
- let deferred = this.$q.defer();
- this.restangular.one(componentId).one("resourceInstance").one("associate").customPOST(JSON.stringify(link)).then((response:any) => {
- let relation:Models.RelationshipModel = new Models.RelationshipModel(response.plain());
- this.$log.debug("Link created successfully ", relation);
- deferred.resolve(relation);
- }, (err)=> {
- this.$log.debug("Failed to create Link From: " + link.fromNode + "To: " + link.toNode);
- deferred.reject(err);
- });
- return deferred.promise;
- };
-
- public deleteRelation = (componentId:string, link:Models.RelationshipModel):ng.IPromise<Models.RelationshipModel> => {
- let deferred = this.$q.defer();
- this.restangular.one(componentId).one("resourceInstance").one("dissociate").customPUT(JSON.stringify(link)).then((response:any) => {
- let relation:Models.RelationshipModel = new Models.RelationshipModel(response);
- this.$log.debug("Link deleted successfully ", relation);
- deferred.resolve(relation);
- }, (err)=> {
- this.$log.debug("Failed to delete Link From: " + link.fromNode + "To: " + link.toNode);
- deferred.reject(err);
- });
- return deferred.promise;
- };
-
- public getRequirementsCapabilities = (componentId:string):ng.IPromise<any> => {
- let deferred = this.$q.defer();
- this.restangular.one(componentId).one("requirmentsCapabilities").get().then((response:any) => {
- this.$log.debug("Component requirement capabilities recived: ", response);
- deferred.resolve(response);
- }, (err)=> {
- this.$log.debug("Failed to get requirements & capabilities");
- deferred.reject(err);
- });
- return deferred.promise;
- };
-
- public getModuleForDisplay = (componentId:string, moduleId:string):ng.IPromise<Models.DisplayModule> => {
- let deferred = this.$q.defer();
- this.restangular.one(componentId).one("groups").one(moduleId).get().then((response:any) => {
- this.$log.debug("module loaded successfully: ", response);
- let module:Models.DisplayModule = new Models.DisplayModule(response);
- deferred.resolve(module);
- }, (err)=> {
- this.$log.debug("Failed to get module with id: ", moduleId);
- deferred.reject(err);
- });
- return deferred.promise;
- };
-
- public getComponentInstancesFilteredByInputsAndProperties = (componentId:string, searchText?:string):ng.IPromise<Array<Models.ComponentsInstances.ComponentInstance>> => {
- let deferred = this.$q.defer();
- this.restangular.one(componentId).one("componentInstances").get({'searchText': searchText}).then((response:any) => {
- this.$log.debug("component instances return successfully: ", response);
- let componentInstances:Array<Models.ComponentsInstances.ComponentInstance> = Utils.CommonUtils.initComponentInstances(response);
- deferred.resolve(componentInstances);
- }, (err) => {
- this.$log.debug("Failed to get component instances of component with id: " + componentId);
- deferred.reject(err);
- });
-
- return deferred.promise;
- };
-
- public getComponentInstanceInputs = (componentId:string, instanceId:string, originComponentUid):ng.IPromise<Array<Models.InputModel>> => {
-
- let deferred = this.$q.defer();
- this.restangular.one(componentId).one("componentInstances").one(instanceId).one(originComponentUid).one("inputs").get().then((response:any) => {
- this.$log.debug("component instance input return successfully: ", response);
- let inputsArray:Array<Models.InputModel> = new Array<Models.InputModel>();
- _.forEach(response, (inputObj:Models.InputModel) => {
- inputsArray.push(new Models.InputModel(inputObj));
- });
- deferred.resolve(inputsArray);
- }, (err) => {
- this.$log.debug("Failed to get component instance input with id: " + instanceId);
- deferred.reject(err);
- });
-
- return deferred.promise;
- };
-
- public getComponentInputs = (componentId:string):ng.IPromise<Array<Models.InputModel>> => {
-
- let deferred = this.$q.defer();
- this.restangular.one(componentId).one("inputs").get().then((response:any) => {
- this.$log.debug("component inputs return successfully: ", response);
- let inputsArray:Array<Models.InputModel> = new Array<Models.InputModel>();
- _.forEach(response, (inputObj:Models.InputModel) => {
- inputsArray.push(new Models.InputModel(inputObj));
- });
- deferred.resolve(inputsArray);
- }, (err) => {
- this.$log.debug("Failed to get component inputs for component with id: " + componentId);
- deferred.reject(err);
- });
-
- return deferred.promise;
- };
-
- public getComponentInstanceInputProperties = (componentId:string, instanceId:string, inputId:string):ng.IPromise<Array<Models.PropertyModel>> => {
-
- let deferred = this.$q.defer();
- this.restangular.one(componentId).one("componentInstances").one(instanceId).one(inputId).one("properties").get().then((response:any) => {
- this.$log.debug("component instance input properties return successfully: ", response);
- let propertiesArray:Array<Models.PropertyModel> = new Array<Models.PropertyModel>();
- _.forEach(response, (propertyObj:Models.PropertyModel) => {
- propertiesArray.push(new Models.PropertyModel(propertyObj));
- });
- deferred.resolve(propertiesArray);
- }, (err) => {
- this.$log.debug("Failed to get component instance input properties with instanceId: " + instanceId + "and input id: " + inputId);
- deferred.reject(err);
- });
-
- return deferred.promise;
- };
-
- public updateGroupMetadata = (componentId:string, group:Models.Module):ng.IPromise<Models.Module> => {
-
- let deferred = this.$q.defer();
- this.restangular.one(componentId).one("groups").one(group.uniqueId).one("metadata").customPUT(JSON.stringify(group)).then((response:Models.Module) => {
- this.$log.debug("group metadata updated successfully: ", response);
- let updatedGroup:Models.Module = new Models.Module(response);
-
- deferred.resolve(updatedGroup);
- }, (err) => {
- this.$log.debug("Failed to update group metadata for component: " + componentId + " for group with id: " + group.uniqueId);
- deferred.reject(err);
- });
-
- return deferred.promise;
- };
-
- public getComponentInputInputs = (serviceId:string, inputId:string): ng.IPromise<Array<Models.InputModel>> => {
- let defer = this.$q.defer<any>();
- this.restangular.one(serviceId).one("inputs").one(inputId).one("inputs").get().then((response: any) => {
- let inputsArray:Array<Models.InputModel> = new Array<Models.InputModel>();
- _.forEach(response, (inputObj:Models.InputModel) => {
- inputsArray.push(new Models.InputModel(inputObj));
- });
- defer.resolve(inputsArray);
- }, (err)=>{
- this.$log.debug("failed to get inputs of input : ", err);
- defer.reject(err);
- });
- return defer.promise;
- };
-
- createInputsFromInstancesInputsProperties = (resourceId:string, instancePropertyMap:Models.InstanceInputsPropertiesMap): ng.IPromise<Array<Models.PropertyModel>> => {
- let defer = this.$q.defer<any>();
- this.restangular.one(resourceId).one("create/properties").customPOST(instancePropertyMap).then((response: any) => {
- let inputsArray:Array<Models.PropertyModel> = new Array<Models.PropertyModel>();
- _.forEach(response, (inputObj:Models.PropertyModel) => {
- inputsArray.push(new Models.PropertyModel(inputObj));
- });
- defer.resolve(inputsArray);
- }, (err)=>{
- this.$log.debug("failed to create service inputs from VF instances inputs : ", err);
- defer.reject(err);
- });
- return defer.promise;
- };
-
- createInputsFromInstancesInputs = (serviceId:string, instancesMap:Models.InstancesInputsMap): ng.IPromise<Array<Models.InputModel>> => {
- let defer = this.$q.defer<any>();
- this.restangular.one(serviceId).one("create/inputs").customPOST(instancesMap).then((response: any) => {
- let inputsArray:Array<Models.InputModel> = new Array<Models.InputModel>();
- _.forEach(response, (inputObj:Models.InputModel) => {
- inputsArray.push(new Models.InputModel(inputObj));
- });
- defer.resolve(inputsArray);
- }, (err)=>{
- this.$log.debug("failed to create service inputs from VF instances inputs : ", err);
- defer.reject(err);
- });
- return defer.promise;
- };
-
- deleteComponentInput = (serviceId:string, inputId:string) : ng.IPromise<Models.InputModel> => {
- var defer = this.$q.defer();
- this.restangular.one(serviceId).one("delete").one(inputId).one("input").remove().then((response: any) => {
- var inputToDelete = new Models.InputModel(response);
-
- defer.resolve(inputToDelete);
- }, (err)=> {
- console.log("failed to delete input from service: ", err);
- defer.reject(err);
- });
- return defer.promise;
- };
-
- private getHeaderMd5 = (object:any):any => {
- let headerObj={};
- // This is ugly workaround!!!
- // The md5 result is not correct if we do not add the line JSON.stringify(resource); twice.
- JSON.stringify(object);
- let componentString:string = JSON.stringify(object);
- let md5Result = md5(componentString).toLowerCase();
- headerObj = {'Content-MD5': this.$base64.encode(md5Result)};
- return headerObj;
- };
-
- }
-}
diff --git a/catalog-ui/app/scripts/services/components/product-service.ts b/catalog-ui/app/scripts/services/components/product-service.ts
deleted file mode 100644
index 69171fbbfa..0000000000
--- a/catalog-ui/app/scripts/services/components/product-service.ts
+++ /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=========================================================
- */
-/**
- * Created by obarda on 2/8/2016.
- */
-/// <reference path="../../references"/>
-module Sdc.Services.Components {
- 'use strict';
-
- export interface IProductService extends IComponentService {
-
- }
-
- export class ProductService extends ComponentService implements IProductService {
-
- static '$inject' = [
- '$log',
- 'Restangular',
- 'sdcConfig',
- 'Sdc.Services.SharingService',
- '$q',
- '$interval',
- '$base64',
- 'ComponentInstanceFactory'
- ];
-
- constructor(protected $log: ng.ILogService,
- protected restangular: restangular.IElement,
- protected sdcConfig: Models.IAppConfigurtaion,
- protected sharingService: Sdc.Services.SharingService,
- protected $q: ng.IQService,
- protected $interval: any,
- protected $base64: any,
- protected ComponentInstanceFactory: Utils.ComponentInstanceFactory) {
- super($log, restangular, sdcConfig, sharingService, $q, $interval, $base64, ComponentInstanceFactory);
-
- this.restangular = restangular.one("products");
- }
-
- createComponentObject = (component: Models.Components.Component): Models.Components.Component => {
- return new Models.Components.Product(this, this.$q, <Models.Components.Product>component);
- };
- }
-}
diff --git a/catalog-ui/app/scripts/services/components/resource-service.ts b/catalog-ui/app/scripts/services/components/resource-service.ts
deleted file mode 100644
index 48781da48e..0000000000
--- a/catalog-ui/app/scripts/services/components/resource-service.ts
+++ /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=========================================================
- */
-/**
- * Created by obarda on 2/4/2016.
- */
-/// <reference path="../../references"/>
-module Sdc.Services.Components {
- 'use strict';
-
- export interface IResourceService extends IComponentService {
-
- }
-
- export class ResourceService extends ComponentService implements IResourceService {
-
- static '$inject' = [
- '$log',
- 'Restangular',
- 'sdcConfig',
- 'Sdc.Services.SharingService',
- '$q',
- '$interval',
- '$base64',
- 'ComponentInstanceFactory'
- ];
-
- constructor(protected $log: ng.ILogService,
- protected restangular: restangular.IElement,
- protected sdcConfig: Models.IAppConfigurtaion,
- protected sharingService: Sdc.Services.SharingService,
- protected $q: ng.IQService,
- protected $interval: any,
- protected $base64: any,
- protected ComponentInstanceFactory: Utils.ComponentInstanceFactory) {
- super($log, restangular, sdcConfig, sharingService, $q, $interval, $base64, ComponentInstanceFactory);
-
- this.restangular = restangular.one("resources");
- }
-
- createComponentObject = (component: Models.Components.Component): Models.Components.Component => {
- return new Models.Components.Resource(this, this.$q, <Models.Components.Resource>component);
- };
- }
-}
diff --git a/catalog-ui/app/scripts/services/components/service-service.ts b/catalog-ui/app/scripts/services/components/service-service.ts
deleted file mode 100644
index fef0b47512..0000000000
--- a/catalog-ui/app/scripts/services/components/service-service.ts
+++ /dev/null
@@ -1,97 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/**
- * Created by obarda on 2/4/2016.
- */
-/// <reference path="../../references"/>
-module Sdc.Services.Components {
- 'use strict';
-
-
- export interface IServiceService extends IComponentService {
- getDistributionsList(uuid: string): ng.IPromise<Array<Models.Distribution>>;
- getDistributionComponents(distributionId: string): ng.IPromise<Array<Models.DistributionComponent>>;
- markAsDeployed(serviceId: string, distributionId: string): ng.IPromise<any>;
- }
-
- export class ServiceService extends ComponentService implements IServiceService {
-
- static '$inject' = [
- '$log',
- 'Restangular',
- 'sdcConfig',
- 'Sdc.Services.SharingService',
- '$q',
- '$interval',
- '$base64',
- 'ComponentInstanceFactory'
- ];
-
- public distribution: string = "distribution";
-
- constructor(protected $log: ng.ILogService,
- protected restangular: restangular.IElement,
- protected sdcConfig: Models.IAppConfigurtaion,
- protected sharingService: Sdc.Services.SharingService,
- protected $q: ng.IQService,
- protected $interval: any,
- protected $base64: any,
- protected ComponentInstanceFactory: Utils.ComponentInstanceFactory) {
- super($log, restangular, sdcConfig, sharingService, $q, $interval, $base64, ComponentInstanceFactory);
-
- this.restangular = restangular.one("services");
- }
-
- getDistributionsList = (uuid: string): ng.IPromise<Array<Models.Distribution>> => {
- let defer = this.$q.defer<Array<Models.Distribution>>();
- this.restangular.one(uuid).one("distribution").get().then((distributions: any) => {
- defer.resolve(<Array<Models.Distribution>> distributions.distributionStatusOfServiceList);
- }, (err)=> {
- defer.reject(err);
- });
- return defer.promise;
- };
-
- getDistributionComponents = (distributionId: string): ng.IPromise<Array<Models.DistributionComponent>> => {
- let defer = this.$q.defer<Array<Models.DistributionComponent>>();
- this.restangular.one("distribution").one(distributionId).get().then((distributions: any) => {
- defer.resolve(<Array<Models.DistributionComponent>> distributions.distributionStatusList);
- }, (err)=> {
- defer.reject(err);
- });
- return defer.promise;
- };
-
- markAsDeployed = (serviceId: string, distributionId: string): ng.IPromise<any> => {
- let defer = this.$q.defer<any>();
- this.restangular.one(serviceId).one("distribution").one(distributionId).one("markDeployed").customPOST().then((result: any) => {
- defer.resolve(result);
- }, (err)=> {
-
- defer.reject(err);
- });
- return defer.promise;
- };
-
- createComponentObject = (component: Models.Components.Component): Models.Components.Component => {
- return new Models.Components.Service(this, this.$q, <Models.Components.Service>component);
- };
- }
-}
diff --git a/catalog-ui/app/scripts/services/components/utils/composition-left-palette-service.ts b/catalog-ui/app/scripts/services/components/utils/composition-left-palette-service.ts
deleted file mode 100644
index 25ac1cdf17..0000000000
--- a/catalog-ui/app/scripts/services/components/utils/composition-left-palette-service.ts
+++ /dev/null
@@ -1,248 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/**
- * Created by obarda on 3/13/2016.
- */
-/// <reference path="../../../references"/>
-module Sdc.Services.Components {
-
- 'use strict';
-
- export class LeftPanelLatestVersion {
- uid: string;
- version: string;
- }
-
- export class LeftPaletteDataObject {
- currentUpdatingIdsList: Array<string>;
- latestVersionAndIdsList: Array<LeftPanelLatestVersion>;
- fullDataLeftPaletteComponents: Array<Models.Components.Component>;
- displayLeftPanelComponents: Array<Models.DisplayComponent>;
- onFinishLoadingEvent: string;
-
- constructor(onFinishEventListener: string) {
-
- this.fullDataLeftPaletteComponents = new Array<Models.Components.Component>();
- this.displayLeftPanelComponents = new Array<Models.DisplayComponent>();
- this.currentUpdatingIdsList = new Array<string>();
- this.latestVersionAndIdsList = new Array<LeftPanelLatestVersion>();
- this.onFinishLoadingEvent = onFinishEventListener;
- }
- }
-
- export class LeftPaletteLoaderService {
-
- static '$inject' = [
- 'Restangular',
- 'sdcConfig',
- '$q',
- '$base64',
- 'ComponentFactory',
- 'EventListenerService'
-
- ];
-
- constructor(protected restangular: restangular.IElement,
- protected sdcConfig: Models.IAppConfigurtaion,
- protected $q: ng.IQService,
- protected $base64: any,
- protected ComponentFactory: Utils.ComponentFactory,
- protected EventListenerService: Services.EventListenerService) {
-
- this.restangular.setBaseUrl(sdcConfig.api.root + sdcConfig.api.component_api_root);
- }
-
- private serviceLeftPaletteData: LeftPaletteDataObject;
- private resourceLeftPaletteData: LeftPaletteDataObject;
- private productLeftPaletteData: LeftPaletteDataObject;
- private vlData: LeftPaletteDataObject;
-
- public loadLeftPanel = (): void => {
-
- this.serviceLeftPaletteData = new LeftPaletteDataObject(Utils.Constants.EVENTS.SERVICE_LEFT_PALETTE_UPDATE_EVENT);
- this.resourceLeftPaletteData = new LeftPaletteDataObject(Utils.Constants.EVENTS.RESOURCE_LEFT_PALETTE_UPDATE_EVENT);
- this.productLeftPaletteData = new LeftPaletteDataObject(Utils.Constants.EVENTS.PRODUCT_LEFT_PALETTE_UPDATE_EVENT);
- this.vlData = new LeftPaletteDataObject(Utils.Constants.EVENTS.VL_LEFT_PALETTE_UPDATE_EVENT);
-
- //initiating service palette
- this.updateComponentLeftPalette(Utils.Constants.ComponentType.SERVICE);
-
- //initiating resource palette
- this.updateComponentLeftPalette(Utils.Constants.ComponentType.RESOURCE);
-
- //initiating product palette
- this.updateComponentLeftPalette(Utils.Constants.ComponentType.PRODUCT);
-
- //initiating vl
- this.updateComponentLeftPalette(Utils.Constants.ResourceType.VL);
- };
-
- private updateData = (latestVersionComponents: Array<Models.Components.Component>, leftPaletteDataObj: LeftPaletteDataObject) => {
-
- let fullDataComponentsArray: Array<Models.Components.Component> = new Array<Models.Components.Component>();
- let displayComponentsArray: Array<Models.DisplayComponent> = new Array<Models.DisplayComponent>();
-
- _.forEach(latestVersionComponents, (componentObj: any) => {
- let component: Models.Components.Component = this.ComponentFactory.createComponent(componentObj);
- fullDataComponentsArray.push(component);
- displayComponentsArray.push(new Models.DisplayComponent(component));
- });
-
- leftPaletteDataObj.fullDataLeftPaletteComponents = leftPaletteDataObj.fullDataLeftPaletteComponents.concat(fullDataComponentsArray);
- leftPaletteDataObj.displayLeftPanelComponents = leftPaletteDataObj.displayLeftPanelComponents.concat(displayComponentsArray);
- };
-
- private getTypeUrl = (componentType: string): string => {
- return Utils.Constants.ComponentType.PRODUCT === componentType ? "services" : "resources";
- };
-
- private onFinishLoading = (componentType: string, leftPaletteData: LeftPaletteDataObject): void => {
- leftPaletteData.currentUpdatingIdsList = [];
- this.EventListenerService.notifyObservers(leftPaletteData.onFinishLoadingEvent);
- };
-
- private getPartialLastVersionFullComponents = (componentType: string, componentInternalType: string, leftPaletteData: LeftPaletteDataObject): void => {
- this.restangular.one(this.getTypeUrl(componentType)).one('/latestversion/notabstract').customPOST(leftPaletteData.currentUpdatingIdsList, '', {'internalComponentType': componentInternalType}).then((componentsArray: any) => {
- this.updateData(componentsArray, leftPaletteData);
- this.onFinishLoading(componentType, leftPaletteData); //when finish loading update view
- });
- };
-
- private removeNotUpdatedComponents = (leftPaletteObject: LeftPaletteDataObject) => {
-
- leftPaletteObject.fullDataLeftPaletteComponents = _.filter(leftPaletteObject.fullDataLeftPaletteComponents, (component)=> {
- return leftPaletteObject.currentUpdatingIdsList.indexOf(component.uniqueId) != -1;
- });
- leftPaletteObject.displayLeftPanelComponents = _.filter(leftPaletteObject.displayLeftPanelComponents, (component)=> {
- return leftPaletteObject.currentUpdatingIdsList.indexOf(component.uniqueId) != -1;
- });
- };
-
- private findIdsToUpdate = (leftPaletteObj: LeftPaletteDataObject): Array<string> => {
- let idsToUpdate = <string[]>_.difference(leftPaletteObj.currentUpdatingIdsList, _.map(leftPaletteObj.fullDataLeftPaletteComponents, 'uniqueId'));
- let neededUpdate = _.filter(leftPaletteObj.fullDataLeftPaletteComponents, (component) => {
- let updated = _.find(leftPaletteObj.latestVersionAndIdsList, (versionAndId: LeftPanelLatestVersion) => {
- return versionAndId.uid === component.uniqueId && versionAndId.version != component.version
- });
- return updated != undefined;
- });
- if (neededUpdate && neededUpdate.length > 0) {
- let neededUpdateIds = <string[]>_.map(neededUpdate, 'uid');
- idsToUpdate.concat(neededUpdateIds);
- }
- return idsToUpdate;
- };
-
- private updateCurrentIdsList = (componentType: string, leftPaletteObj: LeftPaletteDataObject): void=> {
- this.removeNotUpdatedComponents(leftPaletteObj);
- leftPaletteObj.currentUpdatingIdsList = this.findIdsToUpdate(leftPaletteObj);
- //remove all components that needed update from current lists
- if (leftPaletteObj.currentUpdatingIdsList.length > 0) {
- leftPaletteObj.displayLeftPanelComponents = _.filter(leftPaletteObj.displayLeftPanelComponents, (component)=> {
- return leftPaletteObj.currentUpdatingIdsList.indexOf(component.uniqueId) === -1;
- });
- leftPaletteObj.fullDataLeftPaletteComponents = _.filter(leftPaletteObj.fullDataLeftPaletteComponents, (component)=> {
- return leftPaletteObj.currentUpdatingIdsList.indexOf(component.uniqueId) === -1;
- });
- }
- };
-
- private updateLeftPalette = (componentType, componentInternalType: string, leftPaletteData: LeftPaletteDataObject): void => {
- if (leftPaletteData.currentUpdatingIdsList.length > 0) return; //this means the service is still performing update
- this.restangular.one(this.getTypeUrl(componentType)).one('/latestversion/notabstract/uidonly').get({'internalComponentType': componentInternalType}).then((latestVersionUniqueIds: Array<LeftPanelLatestVersion>) => {
- leftPaletteData.latestVersionAndIdsList = latestVersionUniqueIds;
- leftPaletteData.currentUpdatingIdsList = <string[]>_.map(latestVersionUniqueIds, 'uid')
-
- if (leftPaletteData.fullDataLeftPaletteComponents.length === 0) { //this is when first loading product or resource left palette
- this.getPartialLastVersionFullComponents(componentType, componentInternalType, leftPaletteData);
- } else {
- this.updateCurrentIdsList(componentType, leftPaletteData);
- if (leftPaletteData.currentUpdatingIdsList.length === 0) {
- this.onFinishLoading(componentType, leftPaletteData); //when finish loading update view
- return;
- }
- this.getPartialLastVersionFullComponents(componentType, componentInternalType, leftPaletteData);
- }
- });
- };
-
- public getLeftPanelComponentsForDisplay = (componentType: string): Array<Models.DisplayComponent> => {
- switch (componentType) {
- case Utils.Constants.ComponentType.SERVICE:
- return this.serviceLeftPaletteData.displayLeftPanelComponents;
- case Utils.Constants.ComponentType.PRODUCT:
- return this.productLeftPaletteData.displayLeftPanelComponents;
- default:
- return this.resourceLeftPaletteData.displayLeftPanelComponents;
- }
- };
-
- public getFullDataComponentList = (componentType: string): Array<Models.Components.Component> => {
- switch (componentType) {
- case Utils.Constants.ResourceType.VL:
- return this.vlData.fullDataLeftPaletteComponents;
- case Utils.Constants.ComponentType.SERVICE:
- return this.serviceLeftPaletteData.fullDataLeftPaletteComponents;
- case Utils.Constants.ComponentType.PRODUCT:
- return this.productLeftPaletteData.fullDataLeftPaletteComponents;
- default :
- return this.resourceLeftPaletteData.fullDataLeftPaletteComponents;
- }
- };
-
- public getFullDataComponentListWithVls = (componentType: string): Array<Models.Components.Component> => {
- let listPart1: Array<Models.Components.Component>;
- let listPart2: Array<Models.Components.Component>;
- if (componentType === Utils.Constants.ResourceType.VL) {
- listPart1 = [];
- listPart2 = this.getFullDataComponentList(Utils.Constants.ResourceType.VL);
- } else {
- listPart1 = this.getFullDataComponentList(componentType);
- listPart2 = this.getFullDataComponentList(Utils.Constants.ResourceType.VL);
- }
- return listPart1.concat(listPart2);
- };
-
- public updateSpecificComponentLeftPalette = (component: Models.Components.Component, componentType: string): void => {
- let listComponents: Array<Models.Components.Component> = this.getFullDataComponentList(componentType);
- for (let i in listComponents) {
- if (listComponents[i].uniqueId === component.uniqueId) {
- listComponents[i] = component;
- }
- }
- };
-
- public updateComponentLeftPalette = (componentType): void => {
- switch (componentType) {
- case Utils.Constants.ResourceType.VL:
- this.updateLeftPalette(Utils.Constants.ComponentType.RESOURCE, Utils.Constants.ResourceType.VL, this.vlData);
- break;
- case Utils.Constants.ComponentType.SERVICE:
- this.updateLeftPalette(Utils.Constants.ComponentType.SERVICE, Utils.Constants.ComponentType.SERVICE, this.serviceLeftPaletteData);
- break;
- case Utils.Constants.ComponentType.PRODUCT:
- this.updateLeftPalette(Utils.Constants.ComponentType.PRODUCT, Utils.Constants.ComponentType.SERVICE, this.productLeftPaletteData);
- break;
- default:
- this.updateLeftPalette(Utils.Constants.ComponentType.RESOURCE, Utils.Constants.ResourceType.VF, this.resourceLeftPaletteData);
- }
- };
- }
-}
diff --git a/catalog-ui/app/scripts/services/cookie-service.ts b/catalog-ui/app/scripts/services/cookie-service.ts
deleted file mode 100644
index b23a7dccde..0000000000
--- a/catalog-ui/app/scripts/services/cookie-service.ts
+++ /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=========================================================
- */
-/// <reference path="../references"/>
-module Sdc.Services {
-
- 'use strict';
-
- interface ICookieService {
- getUserId(): string;
- getFirstName(): string;
- getLastName(): string;
- getEmail(): string;
- getUserIdSuffix(): string;
- }
-
- export class CookieService implements ICookieService {
-
- static '$inject' = ['sdcConfig', '$document'];
- private cookie: Sdc.Models.ICookie;
- private cookiePrefix: string;
-
-
- constructor(sdcConfig: Models.IAppConfigurtaion, private $document) {
- this.cookie = sdcConfig.cookie;
-
- this.cookiePrefix = '';
- let junctionName: string = this.getCookieByName(this.cookie.junctionName);
- if ((junctionName !== null) && (junctionName !== '')){
- this.cookiePrefix = this.cookie.prefix+junctionName+'!';
- }
- }
-
- private getCookieByName = (cookieName: string): string => {
- cookieName += '=';
- let cookies: Array<string> = this.$document[0].cookie.split(';');
- let cookieVal: string = '';
- cookies.forEach((cookie: string) => {
- while(cookie.charAt(0) === ' '){
- cookie = cookie.substring(1);
- }
- if(cookie.indexOf(cookieName) === 0){
- cookieVal = cookie.substring(cookieName.length, cookie.length);
- return;
- }
- });
- return cookieVal;
- };
-
- public getUserIdSuffix = (): string => {
- return this.cookie.userIdSuffix;
- };
-
- public getUserId = (): string => {
- let userIdCookieName: string = this.cookiePrefix+this.cookie.userIdSuffix;
- let userId: string = this.getCookieByName(userIdCookieName);
- return userId;
- };
-
- public getFirstName = (): string => {
- let firstNameCookieName: string = this.cookiePrefix+this.cookie.userFirstName;
- let firstName: string = this.getCookieByName(firstNameCookieName);
- return firstName;
- };
-
- public getLastName = (): string => {
- let lastNameCookieName: string = this.cookiePrefix+this.cookie.userLastName;
- let lastName: string = this.getCookieByName(lastNameCookieName);
- return lastName;
- };
-
- public getEmail = (): string => {
- let emailCookieName: string = this.cookiePrefix+this.cookie.userEmail;
- let email: string = this.getCookieByName(emailCookieName);
- return email;
- };
-
- }
-}
diff --git a/catalog-ui/app/scripts/services/data-types-service.ts b/catalog-ui/app/scripts/services/data-types-service.ts
deleted file mode 100644
index 0e5fca8b5d..0000000000
--- a/catalog-ui/app/scripts/services/data-types-service.ts
+++ /dev/null
@@ -1,129 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../references"/>
-module Sdc.Services {
-
- 'use strict';
-
- export interface IDataTypesService {
- //declare methods
- getAllDataTypes():ng.IPromise<Models.PropertyModel>;
- getFirsLevelOfDataTypeProperties(dataTypeName:string, dataTypes:Models.DataTypesMap):Array<Models.DataTypePropertyModel>;
- isDataTypeForSchemaType(property:Models.SchemaProperty, types:Models.DataTypesMap):boolean;
- isDataTypeForPropertyType(property:Models.PropertyModel, types:Models.DataTypesMap):boolean;
- isDataTypeForDataTypePropertyType(property:Models.DataTypePropertyModel, types:Models.DataTypesMap):boolean;
- }
-
- export class DataTypesService implements IDataTypesService {
-
- static '$inject' = [
- 'sdcConfig',
- '$q',
- '$http'
- ];
-
- constructor(private sdcConfig:Models.IAppConfigurtaion,
- private $q:ng.IQService,
- private $http:ng.IHttpService) {
- }
-
- //if the dt derived from simple- return the first parent type, else- return null
- private getTypeForDataTypeDerivedFromSimple = (dataTypeName:string, dataTypes:Models.DataTypesMap):string => {
- /////////temporary hack for tosca primitives///////////////////////
- if(!dataTypes[dataTypeName]){
- return 'string';
- }
- ///////////////////////////////////////////////////////////////////
- if(dataTypes[dataTypeName].derivedFromName == "tosca.datatypes.Root" || dataTypes[dataTypeName].properties){
- return null;
- }
- if(Utils.Constants.PROPERTY_DATA.SIMPLE_TYPES.indexOf(dataTypes[dataTypeName].derivedFromName) > -1 ){
- return dataTypes[dataTypeName].derivedFromName
- }
- return this.getTypeForDataTypeDerivedFromSimple(dataTypes[dataTypeName].derivedFromName,dataTypes);
- };
-
- public getAllDataTypes = ():ng.IPromise<Models.PropertyModel> => {
- let deferred = this.$q.defer();
- this.$http({
- url: this.sdcConfig.api.root + this.sdcConfig.api.component_api_root + "dataTypes",
- method: "get"
- })
- .success((response:any) => {
- deferred.resolve(response);
- })
- .error((err) => {
- deferred.reject(err);
- });
- return deferred.promise;
- };
-
- //return list of data type properties and all its parents properties
- //(not include the properties of its properties, in case this data type has not primitive properties)
- public getFirsLevelOfDataTypeProperties = (dataTypeName:string, dataTypes:Models.DataTypesMap):Array<Models.DataTypePropertyModel> => {
- let properties = dataTypes[dataTypeName].properties || [];
- if(dataTypes[dataTypeName].derivedFromName != "tosca.datatypes.Root" ){
- properties = this.getFirsLevelOfDataTypeProperties(dataTypes[dataTypeName].derivedFromName,dataTypes).concat(properties);
- }
- return properties;
- };
-
- //return false when type= data type (=not simple type) that not derived from simple type
- public isDataTypeForSchemaType = (property:Models.SchemaProperty, types:Models.DataTypesMap):boolean=>{
- property.simpleType="";
- if(property.type && Utils.Constants.PROPERTY_DATA.TYPES.indexOf(property.type) > -1){
- return false;
- }
- let simpleType = this.getTypeForDataTypeDerivedFromSimple(property.type, types);
- if(simpleType){
- property.simpleType=simpleType;
- return false;
- }
- return true;
- };
-
- public isDataTypeForPropertyType = (property:Models.PropertyModel, types:Models.DataTypesMap):boolean=>{
- property.simpleType="";
- if(property.type && Utils.Constants.PROPERTY_DATA.TYPES.indexOf(property.type) > -1){
- return false;
- }
- let simpleType = this.getTypeForDataTypeDerivedFromSimple(property.type, types);
- if(simpleType){
- property.simpleType=simpleType;
- return false;
- }
- return true;
- };
-
- public isDataTypeForDataTypePropertyType = (property:Models.DataTypePropertyModel, types:Models.DataTypesMap):boolean=>{
- property.simpleType="";
- if(property.type && Utils.Constants.PROPERTY_DATA.TYPES.indexOf(property.type) > -1){
- return false;
- }
- let simpleType = this.getTypeForDataTypeDerivedFromSimple(property.type, types);
- if(simpleType){
- property.simpleType=simpleType;
- return false;
- }
- return true;
- };
-
- }
-}
diff --git a/catalog-ui/app/scripts/services/ecomp-service.ts b/catalog-ui/app/scripts/services/ecomp-service.ts
deleted file mode 100644
index d7910bd612..0000000000
--- a/catalog-ui/app/scripts/services/ecomp-service.ts
+++ /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=========================================================
- */
-/// <reference path="../references"/>
-module Sdc.Services {
-
- 'use strict';
-
- interface IEcompHeaderService {
- getMenuItems(userId): ng.IPromise<Array<any>>;
- }
-
- export class EcompHeaderService implements IEcompHeaderService {
- static '$inject' = ['$http', '$q', 'sdcConfig'];
- private api:Models.IApi;
-
- constructor(private $http:ng.IHttpService,
- private $q:ng.IQService,
- private sdcConfig:Models.IAppConfigurtaion) {
- this.api = sdcConfig.api;
- }
-
- getMenuItems = (userId):ng.IPromise<Array<any>> => {
- let defer = this.$q.defer<Array<any>>();
- //defer.resolve(this.mockData);
- this.$http.get(this.api.root + this.api.GET_ecomp_menu_items.replace(':userId', userId))
- .success((response:any) => {
- defer.resolve(response);
- })
- .error((response) => {
- defer.reject(response);
- });
-
- return defer.promise;
- };
-
- }
-}
diff --git a/catalog-ui/app/scripts/services/entity-service.ts b/catalog-ui/app/scripts/services/entity-service.ts
deleted file mode 100644
index a9d5a421ce..0000000000
--- a/catalog-ui/app/scripts/services/entity-service.ts
+++ /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=========================================================
- */
-/// <reference path="../references"/>
-module Sdc.Services {
-
- 'use strict';
-
- interface IEntityService {
- getAllComponents(): ng.IPromise<Array<Models.Components.Component>>;
- }
-
- interface IComponentsArray {
- services:Array<Models.Components.Service>;
- resources:Array<Models.Components.Resource>;
- products:Array<Models.Components.Product>;
- }
-
- export class EntityService implements IEntityService {
- static '$inject' = ['$http', '$q', 'sdcConfig', 'Sdc.Services.SharingService','ComponentFactory','Sdc.Services.CacheService'];
- private api:Models.IApi;
-
- constructor(private $http:ng.IHttpService,
- private $q:ng.IQService,
- private sdcConfig:Models.IAppConfigurtaion,
- private sharingService:Sdc.Services.SharingService,
- private ComponentFactory: Sdc.Utils.ComponentFactory,
- private cacheService:Sdc.Services.CacheService
- ) {
- this.api = sdcConfig.api;
- }
-
- getCatalog = ():ng.IPromise<Array<Models.Components.Component>> => {
- let defer = this.$q.defer<Array<Models.Components.Component>>();
- this.$http.get(this.api.root + this.api.GET_catalog)
- .success((followedResponse:IComponentsArray) => {
-
- let componentsList:Array<Models.Components.Component> = new Array();
-
- followedResponse.services.forEach((serviceResponse: Models.Components.Service) => {
- let component:Models.Components.Service = this.ComponentFactory.createService(serviceResponse); // new Models.Components.Service(serviceResponse);
- componentsList.push(component);
- this.sharingService.addUuidValue(component.uniqueId, component.uuid);
- });
-
- followedResponse.resources.forEach((resourceResponse:Models.Components.Resource) => {
- let component:Models.Components.Resource = this.ComponentFactory.createResource(resourceResponse);
- componentsList.push(component);
- this.sharingService.addUuidValue(component.uniqueId, component.uuid);
- });
-
- followedResponse.products.forEach((productResponse:Models.Components.Product) => {
-
- let component:Models.Components.Product = this.ComponentFactory.createProduct(productResponse);
- componentsList.push(component);
- this.sharingService.addUuidValue(component.uniqueId, component.uuid);
- });
-
- this.cacheService.set('breadcrumbsComponents',componentsList);
- defer.resolve(componentsList);
- })
- .error((responce) => {
- defer.reject(responce);
- });
- return defer.promise;
- };
-
- getAllComponents = ():ng.IPromise<Array<Models.Components.Component>> => {
- let defer = this.$q.defer<Array<Models.Components.Component>>();
- this.$http.get(this.api.root + this.api.GET_element)
- .success((componentResponse:IComponentsArray) => {
- let componentsList:Array<Models.Components.Component> = [];
-
- componentResponse.services && componentResponse.services.forEach((serviceResponse:Models.Components.Service) => {
- let component:Models.Components.Service = this.ComponentFactory.createService(serviceResponse);
- componentsList.push(component);
- this.sharingService.addUuidValue(component.uniqueId, component.uuid);
- });
-
- componentResponse.resources && componentResponse.resources.forEach((resourceResponse:Models.Components.Resource) => {
- let component:Models.Components.Resource = this.ComponentFactory.createResource(resourceResponse);
- componentsList.push(component);
- this.sharingService.addUuidValue(component.uniqueId, component.uuid);
- });
-
- componentResponse.products && componentResponse.products.forEach((productsResponse:Models.Components.Product) => {
- let component:Models.Components.Product = this.ComponentFactory.createProduct(productsResponse);
- componentsList.push(component);
- this.sharingService.addUuidValue(component.uniqueId, component.uuid);
- });
- this.cacheService.set('breadcrumbsComponents',componentsList);
- defer.resolve(componentsList);
- });
-
- return defer.promise;
- };
- }
-}
diff --git a/catalog-ui/app/scripts/services/event-listener-service.ts b/catalog-ui/app/scripts/services/event-listener-service.ts
deleted file mode 100644
index 67afd65c56..0000000000
--- a/catalog-ui/app/scripts/services/event-listener-service.ts
+++ /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=========================================================
- */
-/**
- * Created by obarda on 7/4/2016.
- */
-/// <reference path="../references"/>
-module Sdc.Services {
-
- 'use strict';
-
- interface IEventListenerService {
-
- }
-
- interface ICallbackData {
- callback:Function;
- args:any[];
- }
-
- export class EventListenerService implements IEventListenerService {
-
- public observerCallbacks:Utils.Dictionary<string, ICallbackData[]> = new Utils.Dictionary<string, Array<ICallbackData>>();
-
- //register an observer + callback
- public registerObserverCallback = (eventName:string, callback:Function, ...args) => {
- let callbackData = {
- callback: callback,
- args: args
- }
-
- if (this.observerCallbacks.containsKey(eventName)) {
- let callbacks = this.observerCallbacks.getValue(eventName);
-
- // Only insert the callback if the callback is different from existing callbacks.
- for (let i = 0; i < callbacks.length; i++) {
- if (callbacks[i].toString() === callback.toString()) {
- return; // Do not add this callback.
- }
- }
-
- callbacks.push(callbackData);
- this.observerCallbacks.setValue(eventName, callbacks);
- } else {
- this.observerCallbacks.setValue(eventName, [callbackData]);
- }
- };
-
- //unregister an observer
- public unRegisterObserver = (eventName:string) => {
- if (this.observerCallbacks.containsKey(eventName)) {
- this.observerCallbacks.remove(eventName);
- }
- };
-
- public notifyObservers = function (eventName:string, ...args) {
- _.forEach(this.observerCallbacks.getValue(eventName), (callbackData:ICallbackData) => {
- callbackData.callback(...args);
- });
- };
- }
-}
diff --git a/catalog-ui/app/scripts/services/header-interceptor.ts b/catalog-ui/app/scripts/services/header-interceptor.ts
deleted file mode 100644
index 7f362d3f8c..0000000000
--- a/catalog-ui/app/scripts/services/header-interceptor.ts
+++ /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=========================================================
- */
-/// <reference path="../references"/>
-module Sdc.Services {
- 'use strict';
-
- //Method name should be exactly "response" - http://docs.angularjs.org/api/ng/service/$http
- export interface IInterceptor {
- request: Function;
-
- }
-
- export class HeaderInterceptor implements IInterceptor {
- public static $inject = [
- '$log',
- '$injector',
- '$q',
- 'uuid4',
- 'Sdc.Services.SharingService',
- 'sdcConfig',
- '$location'
-
-
- ];
-
- public static Factory($log: ng.ILogService,
- $injector: ng.auto.IInjectorService,
- $q: ng.IQService,
- uuid4: any,
- sharingService: Sdc.Services.SharingService,
- sdcConfig: Models.IAppConfigurtaion,
- $location: ng.ILocationService) {
- return new HeaderInterceptor($log, $injector, $q, uuid4, sharingService, sdcConfig, $location);
- }
-
- constructor(private $log: ng.ILogService,
- private $injector: ng.auto.IInjectorService,
- private $q: ng.IQService,
- private uuid4: any,
- private sharingService: Sdc.Services.SharingService,
- private sdcConfig: Models.IAppConfigurtaion,
- private $location: ng.ILocationService) {
- this.$log.debug('initializing AuthenticationInterceptor');
- }
-
- public request = (requestSuccess): ng.IPromise<any> => {
- requestSuccess.headers['X-ECOMP-RequestID'] = this.uuid4.generate();
- /**
- * For every request to the server, that the service id, or resource id is sent in the URL, need to pass UUID in the header.
- * Check if the unique id exists in uuidMap, and if so get the UUID and add it to the header.
- */
- let map: Utils.Dictionary<string, string> = this.sharingService.getUuidMap();
- if (map && requestSuccess.url.indexOf(this.sdcConfig.api.root) === 0) {
- this.$log.debug("url: " + requestSuccess.url);
- map.forEach((key: string) => {
- if (requestSuccess.url.indexOf(key) !== -1) {
- requestSuccess.headers['X-ECOMP-ServiceID'] = this.sharingService.getUuidValue(key);
- }
- });
- }
- return requestSuccess;
- };
-
- public response = (responseSuccess): ng.IPromise<any> => {
- let responseData = responseSuccess.data;
- if (responseData) {
- let data = JSON.stringify(responseData);
- if (data && (data.indexOf("Global Logon: Login") > 0)) {
- this.$location.path('dashboard/welcome');
- window.location.reload();
- }
- }
- return responseSuccess;
- }
- }
-}
diff --git a/catalog-ui/app/scripts/services/http-error-interceptor.ts b/catalog-ui/app/scripts/services/http-error-interceptor.ts
deleted file mode 100644
index c04659dfec..0000000000
--- a/catalog-ui/app/scripts/services/http-error-interceptor.ts
+++ /dev/null
@@ -1,118 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../references"/>
-module Sdc.Services {
- 'use strict';
-
- export class HttpErrorInterceptor {
- public static $inject = ['$injector', '$q'];
-
- public static Factory($injector: ng.auto.IInjectorService, $q: angular.IQService) {
- return new HttpErrorInterceptor($injector, $q);
- }
-
- constructor(private $injector: ng.auto.IInjectorService, private $q: angular.IQService) {
- }
-
- public formatMessageArrays = (message: string, variables: Array<string>)=> {
- return message.replace(/\[%(\d+)\]/g, function (_, m) {
- let tmp = [];
- let list = variables[--m].split(";");
- list.forEach(function (item) {
- tmp.push("<li>" + item + "</li>");
- });
- return "<ul>" + tmp.join("") + "</ul>";
- });
- };
-
- public responseError = (rejection: any)=> {
-
- let text: string;
- let variables;
- let messageId: string = "";
- let isKnownException = false;
-
- if (rejection.data && rejection.data.serviceException) {
- text = rejection.data.serviceException.text;
- variables = rejection.data.serviceException.variables;
- messageId = rejection.data.serviceException.messageId;
- isKnownException = true;
- } else if (rejection.data && rejection.data.requestError && rejection.data.requestError.serviceException) {
- text = rejection.data.requestError.serviceException.text;
- variables = rejection.data.requestError.serviceException.variables;
- messageId = rejection.data.requestError.serviceException.messageId;
- isKnownException = true;
- } else if (rejection.data && rejection.data.requestError && rejection.data.requestError.policyException) {
- text = rejection.data.requestError.policyException.text;
- variables = rejection.data.requestError.policyException.variables;
- messageId = rejection.data.requestError.policyException.messageId;
- isKnownException = true;
- } else if (rejection.data) {
- text = 'Wrong error format from server';
- console.error(text);
- isKnownException = false;
- }
-
- let data: Sdc.ViewModels.IServerMessageModalModel;
- if (isKnownException) {
- // Remove the "Error: " text at the begining
- if (text.trim().indexOf("Error:") === 0) {
- text = text.replace("Error:", "").trim();
- }
-
- //mshitrit DE199895 bug fix
- let count: number = 0;
- variables.forEach(function (item) {
- variables[count] = item ? item.replace('<', '&lt').replace('>', '&gt') : '';
- count++;
- });
-
- // Format the message in case has array to <ul><li>
- text = this.formatMessageArrays(text, variables);
-
- // Format the message %1 %2
- text = text.format(variables);
-
- // Need to inject the MessageService manually to prevent circular dependencies (because MessageService use $templateCache that use $http).
- data = {
- title: 'Error',
- message: text,
- messageId: messageId,
- status: rejection.status,
- severity: Utils.Constants.SEVERITY.ERROR
- };
- } else {
- // Need to inject the MessageService manually to prevent circular dependencies (because MessageService use $templateCache that use $http).
- data = {
- title: 'Error',
- message: rejection.status !== -1 ? rejection.statusText : "Error getting response from server",
- messageId: messageId,
- status: rejection.status,
- severity: Utils.Constants.SEVERITY.ERROR
- };
- }
-
- let modalsHandler = this.$injector.get('ModalsHandler');
- modalsHandler.openServerMessageModal(data);
-
- return this.$q.reject(rejection);
- }
- }
-}
diff --git a/catalog-ui/app/scripts/services/loader-service.ts b/catalog-ui/app/scripts/services/loader-service.ts
deleted file mode 100644
index 6a1a1febe1..0000000000
--- a/catalog-ui/app/scripts/services/loader-service.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-/**
- * Created by obarda on 3/13/2016.
- */
-/// <reference path="../references"/>
-module Sdc.Services {
- 'use strict';
-
- export class LoaderService {
-
-
- constructor(private eventListenerService: Services.EventListenerService) {
-
- }
-
- public showLoader(...args) {
- this.eventListenerService.notifyObservers(Utils.Constants.EVENTS.SHOW_LOADER_EVENT, ...args);
- }
-
- public hideLoader(...args) {
- this.eventListenerService.notifyObservers(Utils.Constants.EVENTS.HIDE_LOADER_EVENT, ...args);
- }
-
- }
-
- LoaderService.$inject = ['EventListenerService'];
-}
diff --git a/catalog-ui/app/scripts/services/onboarding-service.ts b/catalog-ui/app/scripts/services/onboarding-service.ts
deleted file mode 100644
index c09871d67f..0000000000
--- a/catalog-ui/app/scripts/services/onboarding-service.ts
+++ /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=========================================================
- */
-/// <reference path="../references"/>
-module Sdc.Services {
-
- 'use strict';
-
- interface IOnboardingService {
- getOnboardingComponents(): ng.IPromise<Array<Models.Components.IComponent>>;
- getComponentFromCsarUuid(csarUuid:string): ng.IPromise<Models.Components.Component>;
- downloadOnboardingCsar(packageId:string):ng.IPromise<Models.IFileDownload>;
- }
-
- export class OnboardingService implements IOnboardingService {
-
- static '$inject' = ['$http', '$q', 'sdcConfig', 'ComponentFactory'];
- private api:Models.IApi;
-
- constructor(private $http:ng.IHttpService,
- private $q:ng.IQService,
- private sdcConfig:Models.IAppConfigurtaion,
- private ComponentFactory: Sdc.Utils.ComponentFactory
- ) {
- this.api = sdcConfig.api;
- }
-
- getOnboardingComponents = ():ng.IPromise<Array<Models.Components.IComponent>> => {
- let defer = this.$q.defer<Array<Models.Components.IComponent>>();
- this.$http.get(this.api.GET_onboarding)
- .success((response:any) => {
- let onboardingComponents:Array<Models.ICsarComponent> = response.results;
- let componentsList:Array<Models.Components.IComponent> = new Array();
-
- onboardingComponents.forEach((obc: Models.ICsarComponent) => {
- let component:Models.Components.Component = this.ComponentFactory.createFromCsarComponent(obc);
- componentsList.push(component);
- });
-
- defer.resolve(componentsList);
- })
- .error((response) => {
- defer.reject(response);
- });
-
- return defer.promise;
- };
-
- downloadOnboardingCsar = (packageId:string):ng.IPromise<Models.IFileDownload> => {
- let defer = this.$q.defer();
- this.$http({
- url: this.api.GET_onboarding + "/" + packageId,
- method: "get",
- responseType: "blob"
- })
- .success((response:any) => {
- defer.resolve(response);
- })
- .error((err) => {
- defer.reject(err);
- });
-
- return defer.promise;
- };
-
- getComponentFromCsarUuid = (csarUuid:string):ng.IPromise<Models.Components.Component> => {
- let defer = this.$q.defer<Models.Components.Component>();
- this.$http.get(this.api.root + this.api.GET_component_from_csar_uuid.replace(':csar_uuid', csarUuid))
- .success((response:any) => {
- let component:Models.Components.Resource;
- // If the status is 400, this means that the component not found.
- // I do not want to return error from server, because a popup will appear in client with the error.
- // So returning success (200) with status 400.
- if (response.status!==400) {
- component = new Models.Components.Resource(null, this.$q, <Models.Components.Resource>response);
- }
- defer.resolve(component);
- })
- .error((response) => {
- defer.reject(response);
- });
-
- return defer.promise;
- };
-
- }
-}
diff --git a/catalog-ui/app/scripts/services/progress-service.ts b/catalog-ui/app/scripts/services/progress-service.ts
deleted file mode 100644
index caa463fc98..0000000000
--- a/catalog-ui/app/scripts/services/progress-service.ts
+++ /dev/null
@@ -1,112 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/**
- * Created by obarda on 7/7/2016.
- */
-/**
- * Created by obarda on 7/4/2016.
- */
-/// <reference path="../references"/>
-module Sdc.Services {
-
- 'use strict';
- import IIntervalService = angular.IIntervalService;
-
- export class ProgressService {
-
- public progresses:any = {};
-
- static '$inject' = ['$interval'];
-
- constructor(
- protected $interval:any
- ) {}
-
- private totalProgress:number = 90;
- private startProgress:number = 10;
- private onePercentIntervalSeconds:number = 5;
- private createComponentInterval;
-
- public setProgressValue(name:string, value:number):void {
- if (!this.progresses[name]) {
- this.progresses[name]={};
- }
- this.progresses[name].value = value;
- }
-
- public getProgressValue(name:string):number{
- if (this.progresses[name]){
- return this.progresses[name].value;
- }
- return 0;
- }
-
- public deleteProgressValue(name:string):void{
- this.stopCreateComponentInterval();
- delete this.progresses[name];
- }
-
-
- private stopCreateComponentInterval = ():void => {
- this.$interval.cancel(this.createComponentInterval);
- };
-
-
-
- public initCreateComponentProgress = (componentId:string):void => {
- var progressValue:number = this.startProgress;
- if(!this.getProgressValue(componentId)){
- this.stopCreateComponentInterval();
- this.setProgressValue(componentId, this.startProgress);
- this.createComponentInterval = this.$interval(():void => {
- //TODO replace getProgressMockData to real data after BE provide the API
- var progressValue = this.getProgressMockData(componentId);
- if (progressValue<=this.totalProgress ) {
- this.setProgressValue(componentId, progressValue);
- } else {
- /**
- * Currently the progress is not really checking against the BE.
- * So the progress can pass 100. So the workaround for now, in case we pass 90 (totalProgress)
- * stop the interval, so the progress will be kept at 90 until the promise will return value and set
- * the progress to 100.
- */
- this.deleteProgressValue(componentId);
- }
- }, this.onePercentIntervalSeconds*1000);
- }
-
- };
-
-
- private getProgressMockData =(id:string):number =>{
- var progressValue = this.getProgressValue(id);
- if(progressValue>0){
- progressValue = progressValue + 1;
- }
- //if not finish always stay on 90%
- if (progressValue>90){
- progressValue =90;
- }
-
- return progressValue;
- }
-
- }
-}
diff --git a/catalog-ui/app/scripts/services/relation-icons-service.ts b/catalog-ui/app/scripts/services/relation-icons-service.ts
deleted file mode 100644
index 3d3b494f16..0000000000
--- a/catalog-ui/app/scripts/services/relation-icons-service.ts
+++ /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=========================================================
- */
-/// <reference path="../references"/>
-module Sdc.Services {
- 'use strict';
-
- export interface IRelationIconsService {
- getIconPath(iconName:string):string;
- }
-
- export class RelationIconsService implements IRelationIconsService {
- constructor() {}
- private icons: Array<string> = [
- 'AttachesTo',
- 'BindsTo',
- 'DependsOn',
- 'HostedOn',
- 'LinksTo',
- 'RoutesTo'
- ];
-
- public getIconPath = (relationshipType:string): string => {
- let result:string = 'ConnectedTo';
- let baseUrl:string = '/styles/images/relationship-icons/';
-
- if (relationshipType) {
- let arr = relationshipType.split('.'); // looks like tosca.relationships.AttachesTo
- relationshipType = arr[arr.length - 1];
- if (this.icons.indexOf(relationshipType) > -1) {
- result = relationshipType;
- }
- if('LinksTo'==result){
- return '';
- }
- }
-
- return baseUrl + result + '.svg';
- }
-
- }
-}
-
-
-
diff --git a/catalog-ui/app/scripts/services/sdc-version-service.ts b/catalog-ui/app/scripts/services/sdc-version-service.ts
deleted file mode 100644
index 1744381bca..0000000000
--- a/catalog-ui/app/scripts/services/sdc-version-service.ts
+++ /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=========================================================
- */
-/// <reference path="../references"/>
-module Sdc.Services {
- 'use strict';
-
- export interface ISdcVersionService {
- getVersion():ng.IPromise<any>;
- }
- export class SdcVersionService implements ISdcVersionService{
-
- static '$inject' = ['$http', '$q','sdcConfig'];
- private api: Models.IApi;
-
- constructor(private $http: ng.IHttpService, private $q: ng.IQService, sdcConfig: Models.IAppConfigurtaion){
- this.api = sdcConfig.api;
- }
-
- public getVersion():ng.IPromise<any>{
- let defer = this.$q.defer<Array<Models.Distribution>>();
- let url = this.api.root + this.api.GET_SDC_Version;
- console.log("======================>" + url);
- this.$http.get(url)
- .success((version: any) => {
- defer.resolve(version);
- });
- return defer.promise;
- }
- }
-}
-
diff --git a/catalog-ui/app/scripts/services/sharing-service.ts b/catalog-ui/app/scripts/services/sharing-service.ts
deleted file mode 100644
index 14c3158611..0000000000
--- a/catalog-ui/app/scripts/services/sharing-service.ts
+++ /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=========================================================
- */
-/// <reference path="../references"/>
-module Sdc.Services {
- 'use strict';
-
- export class SharingService {
-
- private uuidMap: Utils.Dictionary<string, string> = new Utils.Dictionary<string,string>();
-
- public getUuidValue = (uniqueId:string):string => {
- return this.uuidMap.getValue(uniqueId);
- };
-
- public addUuidValue = (uniqueId:string, uuid:string):void => {
- this.uuidMap.setValue(uniqueId, uuid);
- };
-
- public getUuidMap = ():Utils.Dictionary<string, string> => {
- return this.uuidMap;
- };
-
- }
-}
diff --git a/catalog-ui/app/scripts/services/url-tobase64-service.ts b/catalog-ui/app/scripts/services/url-tobase64-service.ts
deleted file mode 100644
index 2d6980da3f..0000000000
--- a/catalog-ui/app/scripts/services/url-tobase64-service.ts
+++ /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=========================================================
- */
-/// <reference path="../references"/>
-module Sdc.Services {
- 'use strict';
-
- export interface IUrlToBase64Service {
- downloadUrl(url:string, callback:Function):void;
- }
-
- export class UrlToBase64Service implements IUrlToBase64Service {
- constructor() {}
-
- public downloadUrl = (url:string, callback:Function): void => {
- let xhr :any = new XMLHttpRequest();
-
- xhr.onload = ():void => {
- let reader = new FileReader();
- reader.onloadend = ():void => {
- if (xhr.status === 200) {
- callback(reader.result);
- } else {
- callback(null);
- }
- };
- reader.readAsDataURL(xhr.response);
- };
- xhr.open('GET', url);
- xhr.responseType = 'blob';
- xhr.send();
- }
-
- }
-}
-
diff --git a/catalog-ui/app/scripts/services/user-resource-service.ts b/catalog-ui/app/scripts/services/user-resource-service.ts
deleted file mode 100644
index 7414e2221e..0000000000
--- a/catalog-ui/app/scripts/services/user-resource-service.ts
+++ /dev/null
@@ -1,123 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../references"/>
-module Sdc.Services {
- 'use strict';
-
- // Define an interface of the object you want to use, providing it's properties
- export interface IUserResource extends Models.IUserProperties,ng.resource.IResource<IUserResource>{
-
- }
-
- // Define your resource, adding the signature of the custom actions
- export interface IUserResourceClass extends ng.resource.IResourceClass<IUserResource>{
- authorize(): IUserResource;
- getLoggedinUser(): IUserResource;
- setLoggedinUser(user: IUserResource): void;
- getAllUsers(success?: Function, error?: Function): Array<IUserResource>;
- createUser(IResourceResource, success?: Function, error?: Function): void;
- editUserRole(IResourceResource, success?: Function, error?: Function): void;
- deleteUser(IResourceResource, success?: Function, error?: Function): void;
- }
-
- export class UserResourceService{
-
- public static getResource = (
- $resource: ng.resource.IResourceService,
- sdcConfig: Models.IAppConfigurtaion,
- cookieService: Services.CookieService
- ): IUserResourceClass => {
-
- let url: string = sdcConfig.api.root+sdcConfig.api.GET_user;
- let authorizeUrl: string = sdcConfig.api.root+sdcConfig.api.GET_user_authorize;
- let authorizeActionHeaders: any = {};
- let cookie: Models.ICookie = sdcConfig.cookie;
- authorizeActionHeaders[cookie.userFirstName] = cookieService.getFirstName();
- authorizeActionHeaders[cookie.userLastName] = cookieService.getLastName();
- authorizeActionHeaders[cookie.userEmail] = cookieService.getEmail();
- authorizeActionHeaders[cookie.userIdSuffix] = cookieService.getUserId();
-
- // Define your custom actions here as IActionDescriptor
- let authorizeAction : ng.resource.IActionDescriptor = {
- method: 'GET',
- isArray: false,
- url: authorizeUrl,
- headers: authorizeActionHeaders
- };
-
- let getAllUsers : ng.resource.IActionDescriptor = {
- method: 'GET',
- isArray: true,
- url: sdcConfig.api.root + sdcConfig.api.GET_all_users
- };
-
- let editUserRole : ng.resource.IActionDescriptor = {
- method: 'POST',
- isArray: false,
- url: sdcConfig.api.root + sdcConfig.api.POST_edit_user_role,
- transformRequest: (data, headers)=>{
- data.payloadData = undefined;
- data.payloadName = undefined;
- return JSON.stringify(data);
- }
- };
-
- let deleteUser : ng.resource.IActionDescriptor = {
- method: 'DELETE',
- isArray: false,
- url: sdcConfig.api.root + sdcConfig.api.DELETE_delete_user
- };
-
- let createUser : ng.resource.IActionDescriptor = {
- method: 'POST',
- isArray: false,
- url: sdcConfig.api.root + sdcConfig.api.POST_create_user,
- transformRequest: (data, headers)=>{
- data.payloadData = undefined;
- data.payloadName = undefined;
- return JSON.stringify(data);
- }
- };
- let userResource: IUserResourceClass = <IUserResourceClass>$resource(
- url,
- { id: '@id'},
- {
- authorize: authorizeAction,
- getAllUsers: getAllUsers,
- createUser: createUser,
- editUserRole:editUserRole,
- deleteUser:deleteUser}
- );
-
- let _loggedinUser: IUserResource;
-
- userResource.getLoggedinUser = () => {
- return _loggedinUser;
- };
-
- userResource.setLoggedinUser = (loggedinUser: IUserResource) => {
- _loggedinUser = loggedinUser;
- };
-
- return userResource;
- }
- }
- UserResourceService.getResource.$inject = ['$resource', 'sdcConfig', 'Sdc.Services.CookieService'];
-}
diff --git a/catalog-ui/app/scripts/utils/artifacts-utils.ts b/catalog-ui/app/scripts/utils/artifacts-utils.ts
deleted file mode 100644
index 439a0e98d0..0000000000
--- a/catalog-ui/app/scripts/utils/artifacts-utils.ts
+++ /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=========================================================
- */
-/// <reference path="../references"/>
-module Sdc.Utils {
- export class ArtifactsUtils {
-
- static '$inject' = [
- '$filter',
- '$templateCache',
- '$modal'
- ];
-
- constructor(private $filter:ng.IFilterService,
- private $templateCache:ng.ITemplateCacheService,
- private $modal:ng.ui.bootstrap.IModalService) {
-
- }
-
- public getArtifactTypeByState(currentState:string):string {
- switch (currentState) {
- case "workspace.composition.lifecycle":
- return "interface";
- case "workspace.composition.api":
- return "api";
- case "workspace.composition.deployment":
- return "deployment";
- default:
- return "normal";
- }
- }
-
- public getTitle(artifactType:string, selectedComponent:Models.Components.Component):string {
- switch (artifactType) {
- case "interface":
- return "Lifecycle Management";
- case "api":
- return "API Artifacts";
- case "deployment":
- return "Deployment Artifacts";
- default:
- if (!selectedComponent) {
- return "";
- } else {
- return this.$filter("resourceName")(selectedComponent.name) + ' Artifacts';
- }
- }
- }
-
- public setArtifactType = (artifact:Models.ArtifactModel, artifactType:string):void => {
- switch (artifactType) {
- case "api":
- artifact.artifactGroupType = 'SERVICE_API';
- break;
- case "deployment":
- artifact.artifactGroupType = 'DEPLOYMENT';
- break;
- default:
- artifact.artifactGroupType = 'INFORMATIONAL';
- break;
- }
- };
-
- public isLicenseType = (artifactType:string) :boolean => {
- let isLicense:boolean = false;
-
- if(Utils.Constants.ArtifactType.VENDOR_LICENSE === artifactType || Utils.Constants.ArtifactType.VF_LICENSE === artifactType) {
- isLicense = true;
- }
-
- return isLicense;
- };
-
- public removeArtifact = (artifact:Models.ArtifactModel, artifactsArr:Array<Models.ArtifactModel>):void => {
-
- if (!artifact.mandatory && (Utils.Constants.ArtifactGroupType.INFORMATION == artifact.artifactGroupType ||
- Utils.Constants.ArtifactGroupType.DEPLOYMENT == artifact.artifactGroupType)) {
- _.remove(artifactsArr, {uniqueId: artifact.uniqueId});
- }
- else {
- let artifactToDelete = _.find(artifactsArr, {uniqueId: artifact.uniqueId});
-
- delete artifactToDelete.esId;
- delete artifactToDelete.description;
- delete artifactToDelete.artifactName;
- delete artifactToDelete.apiUrl;
- }
- };
-
- public addAnotherAfterSave(scope:Sdc.ViewModels.IArtifactResourceFormViewModelScope) {
- let newArtifact = new Models.ArtifactModel();
- this.setArtifactType(newArtifact, scope.artifactType);
- scope.editArtifactResourceModel.artifactResource = newArtifact;
-
- scope.forms.editForm['description'].$setPristine();
- if(scope.forms.editForm['artifactLabel']){
- scope.forms.editForm['artifactLabel'].$setPristine();
- }
- if(scope.forms.editForm['type']){
- scope.forms.editForm['type'].$setPristine();
- }
-
- }
- }
-}
diff --git a/catalog-ui/app/scripts/utils/change-lifecycle-state-handler.ts b/catalog-ui/app/scripts/utils/change-lifecycle-state-handler.ts
deleted file mode 100644
index 7722a899b9..0000000000
--- a/catalog-ui/app/scripts/utils/change-lifecycle-state-handler.ts
+++ /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=========================================================
- */
-/**
- * Created by obarda on 2/11/2016.
- */
-/// <reference path="../references"/>
-module Sdc.Utils {
-
- export class ChangeLifecycleStateHandler {
-
- static '$inject' = [
- 'sdcConfig',
- 'sdcMenu',
- 'ComponentFactory',
- '$templateCache',
- '$filter',
- '$modal',
- 'ModalsHandler'
- ];
-
- constructor(
- private sdcConfig:Models.IAppConfigurtaion,
- private sdcMenu:Models.IAppMenu,
- private ComponentFactory: Sdc.Utils.ComponentFactory,
- private $templateCache:ng.ITemplateCacheService,
- private $filter:ng.IFilterService,
- private $modal:ng.ui.bootstrap.IModalService,
- private ModalsHandler: Utils.ModalsHandler
-
- ) {
-
- }
-
- changeLifecycleState = (component:Models.Components.Component, data:any, scope:any, onSuccessCallback?: Function, onErrorCallback?: Function):void => {
-
- let self = this;
-
- let getContacts = (component:Models.Components.Component):string =>{
- let testers = this.sdcConfig.testers;
- let result:string = testers[component.componentType][component.categories[0].name]?
- testers[component.componentType][component.categories[0].name]:
- testers[component.componentType]['default'];
- return result;
- };
-
- let onSuccess = (newComponent:Models.Components.Component):void => {
- //scope.isLoading = false;
- console.info(component.componentType.toLowerCase + ' change state ' , newComponent);
- if(onSuccessCallback) {
- onSuccessCallback(self.ComponentFactory.createComponent(newComponent));
- }
- };
-
- let onError = (error):void => {
- scope.isLoading = false;
- console.info('Failed to changeLifecycleState to ', data.url);
- if(onErrorCallback) {
- onErrorCallback(error);
- }
- };
-
- let comment:Models.AsdcComment = new Models.AsdcComment();
- if (data.alertModal) {
- // Show alert dialog if defined in menu.json
- //-------------------------------------------------
- let onOk = (confirmationText):void => {
- comment.userRemarks = confirmationText;
- scope.isLoading = true;
- component.changeLifecycleState(data.url, comment).then(onSuccess, onError);
- };
-
- let onCancel = ():void => {
- console.info('Cancel pressed');
- scope.isLoading = false;
- };
-
- let modalTitle = this.sdcMenu.alertMessages[data.alertModal].title;
- let modalMessage = this.sdcMenu.alertMessages[data.alertModal].message.format([component.componentType.toLowerCase()]);
- this.ModalsHandler.openAlertModal(modalTitle, modalMessage).then(onOk, onCancel);
- } else if (data.confirmationModal) {
- // Show confirmation dialog if defined in menu.json
- //-------------------------------------------------
- let onOk = (confirmationText):void => {
- comment.userRemarks = confirmationText;
- scope.isLoading = true;
- component.changeLifecycleState(data.url, comment).then(onSuccess, onError);
- };
-
- let onCancel = ():void => {
- console.info('Cancel pressed');
- scope.isLoading = false;
- };
-
- let modalTitle = this.sdcMenu.confirmationMessages[data.confirmationModal].title;
- let modalMessage = this.sdcMenu.confirmationMessages[data.confirmationModal].message.format([component.componentType.toLowerCase()]);
- let modalShowComment = this.sdcMenu.confirmationMessages[data.confirmationModal].showComment;
- this.ModalsHandler.openConfirmationModal(modalTitle, modalMessage, modalShowComment).then(onOk, onCancel);
-
- } else if (data.emailModal) {
- // Show email dialog if defined in menu.json
- //-------------------------------------------------
- let onOk = (resource):void => {
- if (resource){
- onSuccess(resource);
- } else {
- onError("Error changing life cycle state");
- }
- };
-
- let onCancel = ():void => {
- scope.isLoading = false;
- };
-
- let emailModel: ViewModels.IEmailModalModel = <ViewModels.IEmailModalModel>{};
- emailModel.email = <ViewModels.IEmailModalModel_Email>{};
- emailModel.data = <ViewModels.IEmailModalModel_Data>{};
- emailModel.title = this.$filter('translate')("EMAIL_MODAL_TITLE");
- emailModel.email.to = getContacts(component);
- emailModel.email.subject = this.$filter('translate')("EMAIL_MODAL_SUBJECT", "{'entityName': '" + this.$filter('resourceName')(component.name) + "','entityVersion': '" + component.version + "'}");
- emailModel.email.message = '';
- emailModel.data.component = component;
- emailModel.data.stateUrl = data.url;
-
- this.ModalsHandler.openEmailModal(emailModel).then(onOk, onCancel);
-
- } else {
- // Submit to server only (no modal is shown).
- scope.isLoading = true;
- component.changeLifecycleState(data.url, comment).then(onSuccess, onError);
- }
-
- }
- }
-}
diff --git a/catalog-ui/app/scripts/utils/common-utils.ts b/catalog-ui/app/scripts/utils/common-utils.ts
deleted file mode 100644
index aef6b9908d..0000000000
--- a/catalog-ui/app/scripts/utils/common-utils.ts
+++ /dev/null
@@ -1,81 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/**
- * Created by obarda on 6/30/2016.
- */
-/// <reference path="../references.ts"/>
-module Sdc.Utils {
-
- export class CommonUtils {
-
- static initProperties(propertiesObj:Array<Sdc.Models.PropertyModel>, uniqueId?:string):Array<Sdc.Models.PropertyModel> {
-
- let properties = new Array<Sdc.Models.PropertyModel>();
- if (propertiesObj) {
- _.forEach(propertiesObj, (property:Sdc.Models.PropertyModel):void => {
- if (uniqueId) {
- property.readonly = property.parentUniqueId != uniqueId;
- }
- properties.push(new Sdc.Models.PropertyModel(property));
- });
- }
- return properties;
- };
-
- static initAttributes(attributesObj:Array<Sdc.Models.AttributeModel>, uniqueId?:string):Array<Sdc.Models.AttributeModel> {
-
- let attributes = new Array<Sdc.Models.AttributeModel>();
- if (attributesObj) {
- _.forEach(attributesObj, (attribute:Sdc.Models.AttributeModel):void => {
- if (uniqueId) {
- attribute.readonly = attribute.parentUniqueId != uniqueId;
- }
- attributes.push(new Sdc.Models.AttributeModel(attribute));
- });
- }
- return attributes;
- };
-
- static initComponentInstances(componentInstanceObj:Array<Models.ComponentsInstances.ResourceInstance>):Array<Models.ComponentsInstances.ResourceInstance> {
-
- let componentInstances = new Array<Models.ComponentsInstances.ResourceInstance>();
- if (componentInstanceObj) {
- _.forEach(componentInstanceObj, (instance:Models.ComponentsInstances.ResourceInstance):void => {
- componentInstances.push(Utils.ComponentInstanceFactory.createComponentInstance(instance));
- });
- }
- return componentInstances;
- };
-
- static initModules(moduleArrayObj:Array<Models.Module>):Array<Models.Module> {
-
- let modules = new Array<Models.Module>();
-
- if (moduleArrayObj) {
- _.forEach(moduleArrayObj, (module:Models.Module):void => {
- if(module.type === "org.openecomp.groups.VfModule"){
- modules.push(new Models.Module(module));
- }
- });
- }
- return modules;
- };
- }
-}
diff --git a/catalog-ui/app/scripts/utils/component-factory.ts b/catalog-ui/app/scripts/utils/component-factory.ts
deleted file mode 100644
index 1bb139dc45..0000000000
--- a/catalog-ui/app/scripts/utils/component-factory.ts
+++ /dev/null
@@ -1,181 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/**
- * Created by obarda on 2/8/2016.
- */
-/// <reference path="../references"/>
-module Sdc.Utils {
- 'use strict';
- import Resource = Sdc.Models.Components.Resource;
-
- export class ComponentFactory {
-
- static '$inject' = [
- 'Sdc.Services.Components.ResourceService',
- 'Sdc.Services.Components.ServiceService',
- 'Sdc.Services.Components.ProductService',
- 'Sdc.Services.CacheService',
- '$q'
- ];
-
- constructor(
- private ResourceService:Services.Components.ResourceService,
- private ServiceService:Services.Components.ServiceService,
- private ProductService:Services.Components.ProductService,
- private cacheService:Services.CacheService,
- private $q: ng.IQService) {
- }
-
- public createComponent = (component:Models.Components.Component):Models.Components.Component => {
- let newComponent:Models.Components.Component;
- switch (component.componentType) {
-
- case 'SERVICE':
- newComponent = new Models.Components.Service(this.ServiceService, this.$q, <Models.Components.Service> component);
- break;
-
- case 'RESOURCE':
- newComponent = new Models.Components.Resource(this.ResourceService, this.$q, <Models.Components.Resource> component);
- break;
-
- case 'PRODUCT':
- newComponent = new Models.Components.Product(this.ProductService, this.$q, <Models.Components.Product> component);
- break;
- }
- return newComponent;
- };
-
- public createProduct = (product:Models.Components.Product):Models.Components.Product => {
- let newProduct:Models.Components.Product = new Models.Components.Product(this.ProductService, this.$q, <Models.Components.Product> product);
- return newProduct;
- };
-
- public createService = (service:Models.Components.Service):Models.Components.Service => {
- let newService:Models.Components.Service = new Models.Components.Service(this.ServiceService, this.$q, <Models.Components.Service> service);
- return newService;
- };
-
- public createResource = (resource:Models.Components.Resource):Models.Components.Resource => {
- let newResource:Models.Components.Resource = new Models.Components.Resource(this.ResourceService, this.$q, <Models.Components.Resource> resource);
- return newResource;
- };
-
- public createFromCsarComponent = (csar:Models.ICsarComponent):Models.Components.Component => {
- let newResource:Sdc.Models.Components.Resource = <Sdc.Models.Components.Resource>this.createEmptyComponent(Sdc.Utils.Constants.ComponentType.RESOURCE);
- newResource.name = csar.vspName;
-
- /**
- * Onboarding CSAR contains category and sub category that are uniqueId.
- * Need to find the category and sub category and extract the name from them.
- * First concat all sub categories to one array.
- * Then find the selected sub category and category.
- * @type {any}
- */
- let availableCategories = angular.copy(this.cacheService.get('resourceCategories'));
- let allSubs = [];
- _.each(availableCategories, (main:Models.IMainCategory)=>{
- if (main.subcategories) {
- allSubs = allSubs.concat(main.subcategories);
- }
- });
-
- let selectedCategory:Models.IMainCategory = _.find(availableCategories, function(main:Models.IMainCategory){
- return main.uniqueId === csar.category;
- });
-
- let selectedSubCategory:Models.ISubCategory = _.find(allSubs,(sub:Models.ISubCategory)=>{
- return sub.uniqueId === csar.subCategory;
- });
-
- // Build the categories and sub categories array (same format as component category)
- let categories:Array<Models.IMainCategory> = new Array();
- let subcategories:Array<Models.ISubCategory> = new Array();
- if (selectedCategory && selectedSubCategory) {
- subcategories.push(selectedSubCategory);
- selectedCategory.subcategories = subcategories;
- categories.push(selectedCategory);
- }
-
- // Fill the component with details from CSAR
- newResource.selectedCategory = selectedCategory && selectedSubCategory ? selectedCategory.name + "_#_" + selectedSubCategory.name : '';
- newResource.categories = categories;
- newResource.vendorName = csar.vendorName;
- newResource.vendorRelease = csar.vendorRelease;
- newResource.csarUUID = csar.packageId;
- newResource.csarPackageType = csar.packageType;
- newResource.csarVersion = csar.version;
- newResource.packageId = csar.packageId;
- newResource.description = csar.description;
- return newResource;
- };
-
- public createEmptyComponent = (componentType: string):Models.Components.Component => {
- let newComponent:Models.Components.Component;
-
- switch (componentType) {
-
- case Utils.Constants.ComponentType.SERVICE:
- newComponent = new Models.Components.Service(this.ServiceService, this.$q);
- break;
-
- case Utils.Constants.ComponentType.RESOURCE:
- case Utils.Constants.ResourceType.VF:
- case Utils.Constants.ResourceType.VL:
- case Utils.Constants.ResourceType.VFC:
- case Utils.Constants.ResourceType.CP:
- newComponent = new Models.Components.Resource(this.ResourceService, this.$q);
- break;
-
- case Utils.Constants.ComponentType.PRODUCT:
- newComponent = new Models.Components.Product(this.ProductService, this.$q);
- break;
- }
- newComponent.componentType = componentType;
- newComponent.tags = [];
- newComponent.icon = Utils.Constants.DEFAULT_ICON;
- return newComponent;
- };
-
-
- public getServiceFromServer = (componentId: string): ng.IPromise<Models.Components.Service> => {
- let service: Models.Components.Service = <Models.Components.Service>this.createEmptyComponent(Utils.Constants.ComponentType.SERVICE);
- service.setUniqueId(componentId);
- return service.getComponent();
- };
-
- public getResourceFromServer = (componentId: string): ng.IPromise<Models.Components.Resource> => {
- let resource: Models.Components.Resource = <Models.Components.Resource>this.createEmptyComponent(Utils.Constants.ComponentType.RESOURCE);
- resource.setUniqueId(componentId);
- return resource.getComponent();
- };
-
- public getComponentFromServer = (componentType: string, componentId: string): ng.IPromise<Models.Components.Component> => {
- let newComponent: Models.Components.Component = this.createEmptyComponent(componentType);
- newComponent.setUniqueId(componentId);
- return newComponent.getComponent();
- };
-
- public createComponentOnServer = (componentObject:Models.Components.Component):ng.IPromise<Models.Components.Component> => {
- let component: Models.Components.Component = this.createComponent(componentObject);
- return component.createComponentOnServer();
-
- };
- }
-}
diff --git a/catalog-ui/app/scripts/utils/component-instance-factory.ts b/catalog-ui/app/scripts/utils/component-instance-factory.ts
deleted file mode 100644
index 5f698aa46c..0000000000
--- a/catalog-ui/app/scripts/utils/component-instance-factory.ts
+++ /dev/null
@@ -1,85 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/**
- * Created by obarda on 3/7/2016.
- */
-/**
- * Created by obarda on 2/8/2016.
- */
-/// <reference path="../references"/>
-module Sdc.Utils {
- 'use strict';
-
- export class ComponentInstanceFactory {
-
- static createComponentInstance(componentInstance:Models.ComponentsInstances.ComponentInstance):Models.ComponentsInstances.ComponentInstance {
- let newComponentInstance:Models.ComponentsInstances.ComponentInstance;
- switch (componentInstance.originType) {
- case 'SERVICE':
- newComponentInstance = new Models.ComponentsInstances.ServiceInstance(componentInstance);
- break;
-
- case 'PRODUCT':
- newComponentInstance = new Models.ComponentsInstances.ProductInstance(componentInstance);
- break;
-
- default :
- newComponentInstance = new Models.ComponentsInstances.ResourceInstance(componentInstance);
- break;
- }
- return newComponentInstance;
- };
-
- public createEmptyComponentInstance = (componentInstanceType?: string):Models.ComponentsInstances.ComponentInstance => {
- let newComponentInstance:Models.ComponentsInstances.ComponentInstance;
- switch (componentInstanceType) {
- case 'SERVICE':
- newComponentInstance = new Models.ComponentsInstances.ServiceInstance();
- break;
-
- case 'PRODUCT':
- newComponentInstance = new Models.ComponentsInstances.ProductInstance();
- break;
-
- default :
- newComponentInstance = new Models.ComponentsInstances.ResourceInstance();
- break;
- }
- return newComponentInstance;
- };
-
- public createComponentInstanceFromComponent = (component: Models.Components.Component):Models.ComponentsInstances.ComponentInstance => {
- let newComponentInstance:Models.ComponentsInstances.ComponentInstance = this.createEmptyComponentInstance(component.componentType);
- newComponentInstance.uniqueId = component.uniqueId + (new Date()).getTime();
- newComponentInstance.posX = 0;
- newComponentInstance.posY = 0;
- newComponentInstance.name = component.name;
- newComponentInstance.componentVersion = component.version;
- newComponentInstance.originType = component.getComponentSubType();
- //new component instance -> req. & cap. are added on successful instance creation
- newComponentInstance.requirements = component.requirements;
- newComponentInstance.capabilities = component.capabilities;
- newComponentInstance.icon = component.icon;
- newComponentInstance.componentUid = component.uniqueId;
- return newComponentInstance;
- };
-
- }
-}
diff --git a/catalog-ui/app/scripts/utils/constants.ts b/catalog-ui/app/scripts/utils/constants.ts
deleted file mode 100644
index 6db1edf29d..0000000000
--- a/catalog-ui/app/scripts/utils/constants.ts
+++ /dev/null
@@ -1,247 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/**
- * Created by obarda on 2/18/2016.
- */
-/// <reference path="../references"/>
-module Sdc.Utils.Constants {
-
- import SuiteOrSpec = jasmine.SuiteOrSpec;
- export let DEFAULT_ICON = 'defaulticon';
- export let CP_END_POINT = 'CpEndPoint';
- export let CHANGE_COMPONENT_CSAR_VERSION_FLAG = 'changeComponentCsarVersion';
- export let IMAGE_PATH = '';
-
- export class ComponentType {
- static SERVICE = 'SERVICE';
- static RESOURCE = 'RESOURCE';
- static PRODUCT = 'PRODUCT';
- }
-
- export class ResourceType {
- static VF = 'VF';
- static VL = 'VL';
- static CP = 'CP';
- static VFC = 'VFC';
- }
-
- export class ComponentState {
- static CERTIFICATION_IN_PROGRESS = 'CERTIFICATION_IN_PROGRESS';
- static CERTIFIED = 'CERTIFIED';
- static NOT_CERTIFIED_CHECKOUT = 'NOT_CERTIFIED_CHECKOUT';
- static NOT_CERTIFIED_CHECKIN = 'NOT_CERTIFIED_CHECKIN';
- static READY_FOR_CERTIFICATION = 'READY_FOR_CERTIFICATION';
- }
-
- export class DistributionStatus {
- DISTRIBUTION_NOT_APPROVED = 'DISTRIBUTION_NOT_APPROVED';
- DISTRIBUTION_APPROVED = 'DISTRIBUTION_APPROVED';
- DISTRIBUTED = 'DISTRIBUTED';
- DISTRIBUTION_REJECTED = 'DISTRIBUTION_REJECTED';
- }
-
- export class ArtifactGroupType {
- static DEPLOYMENT = "DEPLOYMENT";
- static INFORMATION = "INFORMATIONAL";
- static SERVICE_API = "SERVICE_API";
- }
-
- export class ArtifactType {
- static HEAT = "HEAT";
- static VF_LICENSE = "VF_LICENSE";
- static VENDOR_LICENSE = "VENDOR_LICENSE";
- static THIRD_PARTY_RESERVED_TYPES = { WORKFLOW:"WORKFLOW",
- NETWORK_CALL_FLOW:"NETWORK_CALL_FLOW",
- 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"};
- static TOSCA = { TOSCA_TEMPLATE:"TOSCA_TEMPLATE", TOSCA_CSAR:"TOSCA_CSAR"};
- }
-
- export class SEVERITY {
- public static DEBUG = 'DEBUG';
- public static INFO = 'INFO';
- public static WARNING = 'WARNING';
- public static ERROR = 'ERROR';
- }
-
- export class PROPERTY_TYPES {
- public static STRING = 'string';
- public static INTEGER = 'integer';
- public static FLOAT = 'float';
- public static BOOLEAN = 'boolean';
- public static JSON = 'json';
- public static MAP = 'map';
- public static LIST = 'list';
- }
-
- export class SOURCES {
- public static A_AND_AI = 'A&AI';
- public static ORDER = 'Order';
- public static RUNTIME = 'Runtime';
- }
-
- export class PROPERTY_DATA {
- public static TYPES = [PROPERTY_TYPES.STRING, PROPERTY_TYPES.INTEGER, PROPERTY_TYPES.FLOAT, PROPERTY_TYPES.BOOLEAN, PROPERTY_TYPES.JSON, PROPERTY_TYPES.LIST, PROPERTY_TYPES.MAP];
- public static SIMPLE_TYPES = [PROPERTY_TYPES.STRING, PROPERTY_TYPES.INTEGER, PROPERTY_TYPES.FLOAT, PROPERTY_TYPES.BOOLEAN, PROPERTY_TYPES.JSON];
- public static SOURCES = [SOURCES.A_AND_AI, SOURCES.ORDER, SOURCES.RUNTIME];
- }
-
- export class PROPERTY_VALUE_CONSTRAINTS {
- public static MAX_LENGTH = 100;
- public static JSON_MAX_LENGTH = 4096;
- }
-
- export class Role {
- public static ADMIN = 'ADMIN';
- public static DESIGNER = 'DESIGNER';
- public static PRODUCT_STRATEGIST = 'PRODUCT_STRATEGIST';
- public static PRODUCT_MANAGER = 'PRODUCT_MANAGER';
- public static TESTER = 'TESTER';
- public static OPS = 'OPS';
- public static GOVERNOR = 'GOVERNOR';
- }
-
- export enum FormState{
- CREATE,
- UPDATE,
- IMPORT,
- VIEW
- }
-
- export class WorkspaceMode {
- public static CREATE = 'create';
- public static EDIT = 'edit';
- public static IMPORT = 'import';
- public static VIEW = 'view';
- }
-
- export class ImagesUrl {
- public static RESOURCE_ICONS = '/styles/images/resource-icons/';
- public static SERVICE_ICONS = '/styles/images/service-icons/';
- public static SELECTED_UCPE_INSTANCE = '/styles/images/resource-icons/selectedUcpeInstance.png';
- public static SELECTED_CP_INSTANCE = '/styles/images/resource-icons/selectedCPInstance.png';
- public static SELECTED_VL_INSTANCE = '/styles/images/resource-icons/selectedVLInstance.png';
- public static CANVAS_PLUS_ICON = '/styles/images/resource-icons/canvasPlusIcon.png';
- public static MODULE_ICON = '/styles/images/resource-icons/module.png';
- public static OPEN_MODULE_ICON = '/styles/images/resource-icons/openModule.png';
- public static OPEN_MODULE_HOVER_ICON = '/styles/images/resource-icons/openModuleHover.png';
- public static CLOSE_MODULE_ICON = '/styles/images/resource-icons/closeModule.png';
- public static CLOSE_MODULE_HOVER_ICON = '/styles/images/resource-icons/closeModuleHover.png';
- }
-
- export class ModalType {
- static STANDARD = 'standard';
- static ERROR = 'error';
- static ALERT = 'alert';
- }
-
- export class GraphColors {
- public static NOT_CERTIFIED_LINK = 'rgb(218,31,61)';
- public static VL_LINK = 'rgb(216,216,216)';
- public static ACTIVE_LINK = '#30bdf2';
- public static BASE_LINK = 'rgb(55,55,55)';
- public static NODE_BACKGROUND_COLOR = 'rgba(46, 162, 157, 0.24)';
- public static NODE_SHADOW_COLOR = 'rgba(198, 230, 228, 0.7)';
- public static NODE_OVERLAPPING_BACKGROUND_COLOR = 'rgba(179, 10, 60, 0.24)';
- public static NODE_OVERLAPPING_SHADOW_COLOR = 'rgba(236, 194, 206, 0.7)';
- public static NODE_UCPE_CP = '#9063cd';
- public static NODE_UCPE = '#fbfbfb';
- public static NODE_SELECTED_BORDER_COLOR = '#30bdf2';
- }
-
- export class GraphTransactionLogText {
- public static REMOVE_TEMP_LINK = "remove tempLink";
- public static DELETE_LINK = "delete link";
- public static ADD_LINK = "delete link";
- public static ADD_NODE = "adding node";
- }
-
- export class GraphUIObjects {
- public static LINK_MENU_HEIGHT = 420;
- public static TOP_HEADER_HEIGHT = 200;
- public static TOOLTIP_OFFSET_X = 50;
- public static TOOLTIP_OFFSET_Y = 145;
- public static TOOLTIP_LINK_OFFSET_X = 35;
- public static TOOLTIP_LINK_OFFSET_Y = 75;
- public static MENU_LINK_VL_HEIGHT_OFFSET = 250;
- public static MENU_LINK_VL_WIDTH_OFFSET = 200;
- public static MENU_LINK_SIMPLE_HEIGHT_OFFSET = 180;
- public static MENU_LINK_SIMPLE_WIDTH_OFFSET = 130;
- public static DIAGRAM_RIGHT_WIDTH_OFFSET = 248;
- public static DIAGRAM_HEADER_OFFSET = 103;
- public static DIAGRAM_PALETTE_WIDTH_OFFSET = 247;
-
- }
-
- export class States {
- public static WORKSPACE_GENERAL = 'workspace.general';
- public static WORKSPACE_ICONS = 'workspace.icons';
- public static WORKSPACE_ACTIVITY_LOG = 'workspace.activity_log';
- public static WORKSPACE_DEPLOYMENT_ARTIFACTS = 'workspace.deployment_artifacts';
- public static WORKSPACE_PROPERTIES = 'workspace.properties';
- public static WORKSPACE_SERVICE_INPUTS = 'workspace.service_inputs';
- public static WORKSPACE_RESOURCE_INPUTS = 'workspace.resource_inputs';
- public static WORKSPACE_ATTRIBUTES = 'workspace.attributes';
- public static WORKSPACE_HIERARCHY = 'workspace.hierarchy';
- public static WORKSPACE_INFORMATION_ARTIFACTS = 'workspace.information_artifacts';
- public static WORKSPACE_TOSCA_ARTIFACTS = 'workspace.tosca_artifacts';
- public static WORKSPACE_COMPOSITION = 'workspace.composition';
- public static WORKSPACE_NETWORK_CALL_FLOW = 'workspace.network_call_flow';
- public static WORKSPACE_MANAGEMENT_WORKFLOW = 'workspace.management_workflow';
- public static WORKSPACE_DEPLOYMENT = 'workspace.deployment';
- public static WORKSPACE_DISTRIBUTION = 'workspace.distribution';
- public static WORKSPACE_REQUIREMENTS_AND_CAPABILITIES = 'workspace.reqAndCap';
- }
-
- export class EVENTS {
- static RESOURCE_LEFT_PALETTE_UPDATE_EVENT = "resourceLeftPanelUpdateEvent";
- static SERVICE_LEFT_PALETTE_UPDATE_EVENT = "serviceLeftPanelUpdateEvent";
- static PRODUCT_LEFT_PALETTE_UPDATE_EVENT = "productLeftPanelUdateEvent";
- static VL_LEFT_PALETTE_UPDATE_EVENT = "vlLeftPanelUdateEvent";
- static ON_CSAR_LOADING = "onCsarLoading";
- static DOWNLOAD_ARTIFACT_FINISH_EVENT = "downloadArtifactFinishEvent";
- static ON_WORKSPACE_SAVE_BUTTON_CLICK = "onWorkspaceSaveButtonClick";
- static ON_WORKSPACE_SAVE_BUTTON_SUCCESS = "onWorkspaceSaveButtonSuccess";
- static ON_WORKSPACE_SAVE_BUTTON_ERROR = "onWorkspaceSaveButtonError";
-
- //Loader events
- static SHOW_LOADER_EVENT = "showLoaderEvent";
- static HIDE_LOADER_EVENT = "hideLoaderEvent";
- }
-
- export class GRAPH_EVENTS {
- static ON_NODE_SELECTED = "onNodeSelected";
- static ON_GRAPH_BACKGROUND_CLICKED = "onGraphBackgroundClicked";
- static ON_PALETTE_COMPONENT_HOVER_IN = 'onPaletteComponentHoverIn';
- static ON_PALETTE_COMPONENT_HOVER_OUT = 'onPaletteComponentHoverOut';
- static ON_PALETTE_COMPONENT_DRAG_START = 'onPaletteComponentDragStart';
- static ON_PALETTE_COMPONENT_DRAG_ACTION = 'onPaletteComponentDragAction';
- static ON_COMPONENT_INSTANCE_NAME_CHANGED = 'onComponentInstanceNameChanged';
- static ON_DELETE_COMPONENT_INSTANCE = 'onDeleteComponentInstance';
- static ON_DELETE_MULTIPLE_COMPONENTS = 'onDeleteMultipleComponents';
- static ON_DELETE_EDGE = 'onDeleteEdge';
- static ON_INSERT_NODE_TO_UCPE = 'onInsertNodeToUCPE';
- static ON_REMOVE_NODE_FROM_UCPE = 'onRemoveNodeFromUCPE';
- static ON_VERSION_CHANGED = 'onVersionChanged';
- }
-
-}
diff --git a/catalog-ui/app/scripts/utils/dictionary/dictionary.ts b/catalog-ui/app/scripts/utils/dictionary/dictionary.ts
deleted file mode 100644
index ef9a1bc4ea..0000000000
--- a/catalog-ui/app/scripts/utils/dictionary/dictionary.ts
+++ /dev/null
@@ -1,257 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/**
-
- This code was copy from collections.ts lib
- https://github.com/basarat/typescript-collections
-**/
-
-module Sdc.Utils{
- 'use strict';
-
- // Used internally by dictionary
- interface IDictionaryPair<K, V>{
- key: K;
- value: V;
- }
-
- export class Dictionary<K, V>{
-
- /**
- * Object holding the key-value pairs.
- * @type {Object}
- * @private
- */
- private table: { [key: string]: IDictionaryPair<K, V> };
- //: [key: K] will not work since indices can only by strings in javascript and typescript enforces this.
-
- /**
- * Number of elements in the list.
- * @type {number}
- * @private
- */
- private nElements: number;
-
- /**
- * Function used to convert keys to strings.
- * @type {function(Object):string}
- * @private
- */
- private toStr: (key: K) => string;
-
-
- /**
- * Creates an empty dictionary.
- * @class <p>Dictionaries map keys to values; each key can map to at most one value.
- * This implementation accepts any kind of objects as keys.</p>
- *
- * <p>If the keys are custom objects a function which converts keys to unique
- * strings must be provided. Example:</p>
- * <pre>
- * function petToString(pet) {
- * return pet.name;
- * }
- * </pre>
- * @constructor
- * @param {function(Object):string=} toStrFunction optional function used
- * to convert keys to strings. If the keys aren"t strings or if toString()
- * is not appropriate, a custom function which receives a key and returns a
- * unique string must be provided.
- */
- constructor(toStrFunction?: (key: K) => string) {
- this.table = {};
- this.nElements = 0;
- this.toStr = toStrFunction || this.defaultToString;
- }
-
-
- /**
- copy from angular.js isUndefined
- */
- private isUndefined = (value: any):boolean => {
- return typeof value === 'undefined';
- }
-
- defaultToString = (item: any): string => {
- return item.toString();
- }
-
- /**
- * Returns the value to which this dictionary maps the specified key.
- * Returns undefined if this dictionary contains no mapping for this key.
- * @param {Object} key key whose associated value is to be returned.
- * @return {*} the value to which this dictionary maps the specified key or
- * undefined if the map contains no mapping for this key.
- */
- getValue = (key: K): V => {
- let pair: IDictionaryPair<K, V> = this.table[this.toStr(key)];
- if (this.isUndefined(pair)) {
- return undefined;
- }
- return pair.value;
- }
-
-
- /**
- * Associates the specified value with the specified key in this dictionary.
- * If the dictionary previously contained a mapping for this key, the old
- * value is replaced by the specified value.
- * @param {Object} key key with which the specified value is to be
- * associated.
- * @param {Object} value value to be associated with the specified key.
- * @return {*} previous value associated with the specified key, or undefined if
- * there was no mapping for the key or if the key/value are undefined.
- */
- setValue = (key: K, value: V): V => {
-
- if (this.isUndefined(key) || this.isUndefined(value)) {
- return undefined;
- }
-
- let ret: V;
- let k = this.toStr(key);
- let previousElement: IDictionaryPair<K, V> = this.table[k];
- if (this.isUndefined(previousElement)) {
- this.nElements++;
- ret = undefined;
- } else {
- ret = previousElement.value;
- }
- this.table[k] = {
- key: key,
- value: value
- };
- return ret;
- }
-
- /**
- * Removes the mapping for this key from this dictionary if it is present.
- * @param {Object} key key whose mapping is to be removed from the
- * dictionary.
- * @return {*} previous value associated with specified key, or undefined if
- * there was no mapping for key.
- */
- remove = (key: K): V => {
- let k = this.toStr(key);
- let previousElement: IDictionaryPair<K, V> = this.table[k];
- if (!this.isUndefined(previousElement)) {
- delete this.table[k];
- this.nElements--;
- return previousElement.value;
- }
- return undefined;
- }
-
- /**
- * Returns an array containing all of the keys in this dictionary.
- * @return {Array} an array containing all of the keys in this dictionary.
- */
- keys = (): K[] => {
- let array: K[] = [];
- for (let name in this.table) {
- if (this.table.hasOwnProperty(name)) {
- let pair: IDictionaryPair<K, V> = this.table[name];
- array.push(pair.key);
- }
- }
- return array;
- }
-
- /**
- * Returns an array containing all of the values in this dictionary.
- * @return {Array} an array containing all of the values in this dictionary.
- */
- values = (): V[] => {
- let array: V[] = [];
- for (let name in this.table) {
- if (this.table.hasOwnProperty(name)) {
- let pair: IDictionaryPair<K, V> = this.table[name];
- array.push(pair.value);
- }
- }
- return array;
- }
-
- /**
- * Executes the provided function once for each key-value pair
- * present in this dictionary.
- * @param {function(Object,Object):*} callback function to execute, it is
- * invoked with two arguments: key and value. To break the iteration you can
- * optionally return false.
- */
- forEach = (callback: (key: K, value: V) => any): void => {
- for (let name in this.table) {
- if (this.table.hasOwnProperty(name)) {
- let pair: IDictionaryPair<K, V> = this.table[name];
- let ret = callback(pair.key, pair.value);
- if (ret === false) {
- return;
- }
- }
- }
- }
-
- /**
- * Returns true if this dictionary contains a mapping for the specified key.
- * @param {Object} key key whose presence in this dictionary is to be
- * tested.
- * @return {boolean} true if this dictionary contains a mapping for the
- * specified key.
- */
- containsKey = (key: K): boolean => {
- return !this.isUndefined(this.getValue(key));
- }
-
- /**
- * Removes all mappings from this dictionary.
- * @this {Dictionary}
- */
- clear = () => {
-
- this.table = {};
- this.nElements = 0;
- }
-
- /**
- * Returns the number of keys in this dictionary.
- * @return {number} the number of key-value mappings in this dictionary.
- */
- size = (): number => {
- return this.nElements;
- }
-
- /**
- * Returns true if this dictionary contains no mappings.
- * @return {boolean} true if this dictionary contains no mappings.
- */
- isEmpty = (): boolean => {
- return this.nElements <= 0;
- }
-
- toString = (): string => {
- let toret = "{";
- this.forEach((k, v) => {
- toret = toret + "\n\t" + k.toString() + " : " + v.toString();
- });
- return toret + "\n}";
- }
- } // End of dictionary
-
-}
diff --git a/catalog-ui/app/scripts/utils/file-utils.ts b/catalog-ui/app/scripts/utils/file-utils.ts
deleted file mode 100644
index db6251f199..0000000000
--- a/catalog-ui/app/scripts/utils/file-utils.ts
+++ /dev/null
@@ -1,73 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../references"/>
-module Sdc.Utils {
- export class FileUtils {
-
- static '$inject' = [
- '$window'
- ];
-
- constructor(private $window: any) {
- }
-
- public byteCharactersToBlob = (byteCharacters, contentType): any => {
- contentType = contentType || '';
- let sliceSize = 1024;
- let bytesLength = byteCharacters.length;
- let slicesCount = Math.ceil(bytesLength / sliceSize);
- let byteArrays = new Array(slicesCount);
-
- for (let sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
- let begin = sliceIndex * sliceSize;
- let end = Math.min(begin + sliceSize, bytesLength);
-
- let bytes = new Array(end - begin);
- for (let offset = begin, i = 0; offset < end; ++i, ++offset) {
- bytes[i] = byteCharacters[offset].charCodeAt(0);
- }
- byteArrays[sliceIndex] = new Uint8Array(bytes);
- }
- return new Blob(byteArrays, {type: contentType});
- };
-
- public base64toBlob = (base64Data, contentType): any => {
- let byteCharacters = atob(base64Data);
- return this.byteCharactersToBlob(byteCharacters, contentType);
- };
-
- public downloadFile = (blob, fileName): void=> {
- let url = this.$window.URL.createObjectURL(blob);
- let downloadLink = document.createElement("a");
-
- downloadLink.setAttribute('href', url);
- downloadLink.setAttribute('download', fileName);
- document.body.appendChild(downloadLink);
- downloadLink.click();
-
- //time out for firefox
- setTimeout(()=> {
- document.body.removeChild(downloadLink);
- this.$window.URL.revokeObjectURL(url);
- }, 100);
- }
-
- }
-}
diff --git a/catalog-ui/app/scripts/utils/functions.ts b/catalog-ui/app/scripts/utils/functions.ts
deleted file mode 100644
index 32bc9243cf..0000000000
--- a/catalog-ui/app/scripts/utils/functions.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../references"/>
-module Sdc.Utils.Functions {
-
- export class QueueUtils {
-
- private executionQueue : any;
-
- constructor(private $q:ng.IQService){
- this.executionQueue = this.getDummyPromise();
- }
-
-
- private getDummyPromise = (): ng.IPromise<boolean> => {
- let deferred : ng.IDeferred<boolean>= this.$q.defer();
- deferred.resolve(true);
- return deferred.promise;
- };
-
-
- private addMethodToQueue = (runMe:Function) : void => {
- this.executionQueue = this.executionQueue.then(runMe, runMe);
- };
-
- addNonBlockingUIAction = (update:Function , releaseUIcallBack:Function) : void => {
- releaseUIcallBack();
- this.addMethodToQueue(update);
- };
-
- // The Method call is responsible for releasing the UI
- addBlockingUIAction = ( blockingServerRequest : Function ):void => {
- this.addMethodToQueue(blockingServerRequest);
- };
-
- addBlockingUIActionWithReleaseCallback = ( blockingServerRequest : Function, releaseUIcallBack:Function):void=>{
- this.addMethodToQueue(blockingServerRequest);
- this.addMethodToQueue(releaseUIcallBack);
- };
- }
-}
diff --git a/catalog-ui/app/scripts/utils/menu-handler.ts b/catalog-ui/app/scripts/utils/menu-handler.ts
deleted file mode 100644
index 0f2b7de3be..0000000000
--- a/catalog-ui/app/scripts/utils/menu-handler.ts
+++ /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=========================================================
- */
-/// <reference path="../references.ts"/>
-module Sdc.Utils {
-
- 'use strict';
-
- export class MenuItem {
- text: string;
- callback: (...args: Array<any>) => ng.IPromise<boolean>;
- state: string;
- action: string;
- params: Array<any>;
- isDisabled: boolean;
- disabledRoles: Array<string>;
- blockedForTypes:Array<string>; // This item will not be shown for specific components types.
-
- //TODO check if needed
- confirmationModal:string; // Open confirmation modal (user should select "OK" or "Cancel"), and continue with the action.
- emailModal:string; // Open email modal (user should fill email details), and continue with the action.
- url:string; // Data added to menu item, in case the function need to use it, example: for function "changeLifecycleState", I need to pass also the state "CHECKOUT" that I want the state to change to.
-
-
- constructor(text: string, callback: (...args: Array<any>) => ng.IPromise<boolean>, state:string, action:string, params?: Array<any>, blockedForTypes?:Array<string>) {
- this.text = text;
- this.callback = callback;
- this.state = state;
- this.action = action;
- this.params = params;
- this.blockedForTypes = blockedForTypes;
- }
- }
-
- export class MenuItemGroup {
- selectedIndex: number;
- menuItems: Array<MenuItem>;
- itemClick: boolean;
-
- constructor(selectedIndex?:number, menuItems?: Array<MenuItem>, itemClick?: boolean) {
- this.selectedIndex = selectedIndex;
- this.menuItems = menuItems;
- this.itemClick = itemClick;
- }
-
- public updateSelectedMenuItemText (newText: string) {
- this.menuItems[this.selectedIndex].text = newText;
- }
- }
-
-
- export class MenuHandler {
-
- static '$inject' = [
- 'sdcConfig',
- 'sdcMenu',
- 'ComponentFactory',
- '$templateCache',
- '$filter',
- '$modal',
- 'ModalsHandler',
- '$state',
- '$q'
- ];
-
- constructor(
- private sdcConfig:Models.IAppConfigurtaion,
- private sdcMenu:Models.IAppMenu,
- private ComponentFactory: ComponentFactory,
- private $templateCache:ng.ITemplateCacheService,
- private $filter:ng.IFilterService,
- private $modal:ng.ui.bootstrap.IModalService,
- private ModalsHandler: ModalsHandler,
- private $state:ng.ui.IStateService,
- private $q:ng.IQService
- ) {
-
- }
-
-
- generateBreadcrumbsModelFromComponents = (components: Array<Sdc.Models.Components.Component>, selected:Sdc.Models.Components.Component):MenuItemGroup => {
- let result = new MenuItemGroup(0, [], false);
- if (components) {
-
- // Search the component in all components by uuid (and not uniqueid, gives access to an assets's minor versions).
- let selectedItem = _.find(components, (item:Sdc.Models.Components.Component) => {
- return item.uuid === selected.uuid;
- });
-
- // If not found search by invariantUUID
- if(undefined == selectedItem){
- selectedItem = _.find(components, (item:Sdc.Models.Components.Component) => {
- //invariantUUID && Certified State matches between major versions
- return item.invariantUUID === selected.invariantUUID && item.lifecycleState === Utils.Constants.ComponentState.CERTIFIED;
- });
- }
-
- // If not found search by name (name is unique).
- if(undefined == selectedItem){
- selectedItem = _.find(components, (item:Sdc.Models.Components.Component) => {
- return item.name === selected.name;
- });
- }
-
- result.selectedIndex = components.indexOf(selectedItem);
- components[result.selectedIndex] = selected;
- let clickItemCallback = (component: Sdc.Models.Components.Component): ng.IPromise<boolean> => {
- this.$state.go('workspace.general', {id: component.uniqueId, type:component.componentType.toLowerCase(), mode: Utils.Constants.WorkspaceMode.VIEW});
- return this.$q.when(true);
- };
-
- components.forEach((component:Sdc.Models.Components.Component) => {
- let menuItem = new MenuItem(
- // component.name,
- component.getComponentSubType() + ': ' + this.$filter('resourceName')(component.name),
- clickItemCallback,
- null,
- null,
- [component]
- );
- // menuItem.text = component.name;
- result.menuItems.push(menuItem);
- });
- }
- return result;
- };
-
- }
-}
diff --git a/catalog-ui/app/scripts/utils/modals-handler.ts b/catalog-ui/app/scripts/utils/modals-handler.ts
deleted file mode 100644
index f3e80a7a24..0000000000
--- a/catalog-ui/app/scripts/utils/modals-handler.ts
+++ /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=========================================================
- */
-/**
- * Created by obarda on 2/11/2016.
- */
-/// <reference path="../references"/>
-module Sdc.Utils {
-
- export interface IModalsHandler {
-
- openViewerModal(component:Models.Components.Component):void;
- openDistributionStatusModal(distribution: Models.Distribution,status:string):void;
- openConfirmationModal (title:string, message:string, showComment:boolean, size?: string):ng.IPromise<any>;
- openAlertModal (title:string, message:string, size?: string):ng.IPromise<any>;
- openStandardModal (title:string, message:string, size?: string):ng.IPromise<any>;
- openErrorModal (title:string, message:string, size?: string):ng.IPromise<any>;
- openEmailModal(emailModel:ViewModels.IEmailModalModel) :ng.IPromise<any>;
- openServerMessageModal(data:Sdc.ViewModels.IServerMessageModalModel): ng.IPromise<any>;
- openClientMessageModal(data:Sdc.ViewModels.IClientMessageModalModel): ng.IPromise<ng.ui.bootstrap.IModalServiceInstance>;
- openWizardArtifactModal(artifact: Models.ArtifactModel, component:Models.Components.Component): ng.IPromise<any>;
- openWizard(componentType: Utils.Constants.ComponentType, component?:Models.Components.Component, importedFile?: any): ng.IPromise<any>;
- }
-
- export class ModalsHandler implements IModalsHandler{
-
- static '$inject' = [
- '$templateCache',
- '$modal',
- '$q'
- ];
-
- constructor(private $templateCache:ng.ITemplateCacheService,
- private $modal:ng.ui.bootstrap.IModalService,
- private $q:ng.IQService) {
- }
-
- openViewerModal = (component:Models.Components.Component):void => {
-
- let modalOptions:ng.ui.bootstrap.IModalSettings = {
- template: this.$templateCache.get('/app/scripts/view-models/component-viewer/component-viewer.html'),
- controller: 'Sdc.ViewModels.ComponentViewerViewModel',
- size: 'lg',
- backdrop: 'static',
- resolve: {
- component: ():Models.Components.Component=> {
- return component;
- }
- }
- };
- this.$modal.open(modalOptions);
- };
-
-
- openDistributionStatusModal = (distribution: Models.Distribution,status:string): ng.IPromise<any> => {
- let deferred = this.$q.defer();
- let modalOptions:ng.ui.bootstrap.IModalSettings = {
- template: this.$templateCache.get('/app/scripts/view-models/workspace/tabs/distribution/disribution-status-modal/disribution-status-modal-view.html'),
- controller: 'Sdc.ViewModels.DistributionStatusModalViewModel',
- size: 'sdc-xl',
- backdrop: 'static',
- resolve: {
- data: ():any => {
- return {
- 'distribution': distribution,
- 'status': status
- };
- }
- }
- };
- let modalInstance:ng.ui.bootstrap.IModalServiceInstance = this.$modal.open(modalOptions);
- deferred.resolve(modalInstance.result);
- return deferred.promise;
- };
-
-
-
- openAlertModal = (title:string, message:string, size?: string):ng.IPromise<any> => {
- return this.openConfirmationModalBase(title, message, false, Utils.Constants.ModalType.ALERT, size);
- };
-
- openStandardModal = (title:string, message:string, size?: string):ng.IPromise<any> => {
- return this.openConfirmationModalBase(title, message, false, Utils.Constants.ModalType.STANDARD, size);
- };
-
- openErrorModal = (title:string, message:string, size?: string):ng.IPromise<any> => {
- return this.openConfirmationModalBase(title, message, false, Utils.Constants.ModalType.ERROR, size);
- };
-
- openConfirmationModal = (title:string, message:string, showComment:boolean, size?: string):ng.IPromise<any> => {
- return this.openConfirmationModalBase(title, message, showComment, Utils.Constants.ModalType.STANDARD, size);
- };
-
- private openConfirmationModalBase = (title:string, message:string, showComment:boolean, type:Utils.Constants.ModalType, size?: string):ng.IPromise<any> => {
- let deferred = this.$q.defer();
- let modalOptions:ng.ui.bootstrap.IModalSettings = {
- template: this.$templateCache.get('/app/scripts/view-models/modals/confirmation-modal/confirmation-modal-view.html'),
- controller: 'Sdc.ViewModels.ConfirmationModalViewModel',
- size: size? size:'sdc-sm',
- backdrop: 'static',
- resolve: {
- confirmationModalModel: ():Sdc.ViewModels.IConfirmationModalModel => {
- let model:Sdc.ViewModels.IConfirmationModalModel = {
- title: title,
- message: message,
- showComment: showComment,
- type: type
- };
- return model;
- }
- }
- };
-
- let modalInstance:ng.ui.bootstrap.IModalServiceInstance = this.$modal.open(modalOptions);
- deferred.resolve(modalInstance.result);
- return deferred.promise;
- };
-
- openEmailModal = (emailModel:ViewModels.IEmailModalModel):ng.IPromise<any> => {
-
- let deferred = this.$q.defer();
- let modalOptions:ng.ui.bootstrap.IModalSettings = {
- template: this.$templateCache.get('/app/scripts/view-models/modals/email-modal/email-modal-view.html'),
- controller: 'Sdc.ViewModels.EmailModalViewModel',
- size: 'sdc-sm',
- backdrop: 'static',
- resolve: {
- emailModalModel: ():ViewModels.IEmailModalModel => {
- return emailModel;
- }
- }
- };
- let modalInstance:ng.ui.bootstrap.IModalServiceInstance = this.$modal.open(modalOptions);
- deferred.resolve(modalInstance.result);
- return deferred.promise;
-
- };
-
- openServerMessageModal = (data:Sdc.ViewModels.IServerMessageModalModel):ng.IPromise<any> => {
- let deferred = this.$q.defer();
- let modalOptions:ng.ui.bootstrap.IModalSettings = {
- template: this.$templateCache.get('/app/scripts/view-models/modals/message-modal/message-server-modal/server-message-modal-view.html'),
- controller: 'Sdc.ViewModels.ServerMessageModalViewModel',
- size: 'sdc-sm',
- backdrop: 'static',
- resolve: {
- serverMessageModalModel: ():Sdc.ViewModels.IServerMessageModalModel => {
- return data;
- }
- }
- };
-
- let modalInstance:ng.ui.bootstrap.IModalServiceInstance = this.$modal.open(modalOptions);
- deferred.resolve(modalInstance.result);
- return deferred.promise;
- };
-
- openClientMessageModal = (data:Sdc.ViewModels.IClientMessageModalModel):ng.IPromise<any> => {
- let deferred = this.$q.defer();
- let modalOptions:ng.ui.bootstrap.IModalSettings = {
- template: this.$templateCache.get('/app/scripts/view-models/modals/message-modal/message-client-modal/client-message-modal-view.html'),
- controller: 'Sdc.ViewModels.ClientMessageModalViewModel',
- size: 'sdc-sm',
- backdrop: 'static',
- resolve: {
- clientMessageModalModel: ():Sdc.ViewModels.IClientMessageModalModel => {
- return data;
- }
- }
- };
- let modalInstance:ng.ui.bootstrap.IModalServiceInstance = this.$modal.open(modalOptions);
- deferred.resolve(modalInstance);
- return deferred.promise;
- };
-
- openOnboadrdingModal = (okButtonText:string,currentCsarUUID?:string): ng.IPromise<any> => {
- let deferred = this.$q.defer();
- let modalOptions:ng.ui.bootstrap.IModalSettings = {
- template: this.$templateCache.get('/app/scripts/view-models/modals/onboarding-modal/onboarding-modal-view.html'),
- controller: 'Sdc.ViewModels.OnboardingModalViewModel',
- size: 'sdc-xl',
- backdrop: 'static',
- resolve: {
- okButtonText:():string=>{
- return okButtonText;
- },
- currentCsarUUID:():string=>{
- return currentCsarUUID||null;
- }
- }
- };
- let modalInstance:ng.ui.bootstrap.IModalServiceInstance = this.$modal.open(modalOptions);
- deferred.resolve(modalInstance.result);
- return deferred.promise;
- };
-
-
- openWizard = (componentType: Utils.Constants.ComponentType, component?:Models.Components.Component, importedFile?: any): ng.IPromise<any> => {
- let deferred = this.$q.defer();
- let template = this.$templateCache.get('/app/scripts/view-models/wizard/wizard-creation-base.html');
-
- let controller:string;
- if(component){
- controller = 'Sdc.ViewModels.Wizard.EditWizardViewModel'; //Edit mode
- } else {
- if (importedFile){
- controller = 'Sdc.ViewModels.Wizard.ImportWizardViewModel'; // Import Mode
- } else {
- controller = 'Sdc.ViewModels.Wizard.CreateWizardViewModel'; // Create Mode
- }
- }
- let modalOptions:ng.ui.bootstrap.IModalSettings = {
- template: template,
- controller: controller,
- size: 'sdc-xl',
- backdrop: 'static',
- keyboard: false,
- resolve: {
- data: ():any => {
- return {
- 'componentType': componentType,
- 'component': component,
- 'importFile':importedFile
- };
- }
- }
- };
-
- let modalInstance:ng.ui.bootstrap.IModalServiceInstance = this.$modal.open(modalOptions);
- deferred.resolve(modalInstance.result);
- return deferred.promise;
- };
-
- openWizardArtifactModal = (artifact: Models.ArtifactModel, component:Models.Components.Component): ng.IPromise<any> => {
- let deferred = this.$q.defer();
- let viewModelsHtmlBasePath:string = '/app/scripts/view-models/';
- let modalOptions:ng.ui.bootstrap.IModalSettings = {
- template: this.$templateCache.get(viewModelsHtmlBasePath + 'wizard/artifact-form-step/artifact-form-step-view.html'),
- controller: 'Sdc.ViewModels.Wizard.ArtifactResourceFormStepViewModel',
- size: 'sdc-md',
- backdrop: 'static',
- keyboard: false,
- resolve: {
- artifact: ():Models.ArtifactModel => {
- return artifact;
- },
- component: (): Models.Components.Component => {
- return component;
- }
- }
- };
-
- let modalInstance:ng.ui.bootstrap.IModalServiceInstance = this.$modal.open(modalOptions);
- deferred.resolve(modalInstance.result);
- return deferred.promise;
- };
-
- }
-}
diff --git a/catalog-ui/app/scripts/utils/prototypes.ts b/catalog-ui/app/scripts/utils/prototypes.ts
deleted file mode 100644
index de961cfc4b..0000000000
--- a/catalog-ui/app/scripts/utils/prototypes.ts
+++ /dev/null
@@ -1,155 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-interface String {
- format(variables:Array<string>):string
-}
-
-interface Array<T> {
- clean(o: T): Array<T>;
-}
-
-
-/**
- * This function will replace the %<number> with strings (from array).
- * Example: "Requested '%1' resource was not found.".format(["MyResource"]);
- * Note: in case the array contains empty string the function will also remove the '' or the "".
- */
-if (!String.hasOwnProperty("format")) {
- String.prototype["format"] = function (variables:Array<string>) : string {
-
- if (variables===null || variables===undefined || variables.length===0){
- variables=[''];
- }
-
- for (let i=0;i<variables.length;i++){
- if (variables[i]==='' || variables[i]===null){
- variables[i]='--DELETE--';
- }
- }
-
- let res = this.replace(/%(\d+)/g, function(_,m) {
- return variables[--m];
- });
-
- res = res.replace(" '--DELETE--' "," ");
- res = res.replace(" \"--DELETE--\" "," ");
- res = res.replace("'--DELETE--'","");
- res = res.replace("\"--DELETE--\"","");
- res = res.replace("--DELETE--","");
-
- return res;
- };
-}
-
-if (!String.hasOwnProperty("capitalizeFirstLetter")) {
- String.prototype["capitalizeFirstLetter"] = function() {
- return this.charAt(0).toUpperCase() + this.slice(1);
- };
-}
-
-if (!String.hasOwnProperty("replaceAll")) {
- String.prototype["replaceAll"] = function (find:string, replace:string) : string {
- return this.replace(new RegExp(find, 'g'), replace);
- };
-}
-
-if (!Array.hasOwnProperty("clean")) {
- Array.prototype.clean = function (deleteValue) {
- for (let i = 0; i < this.length; i++) {
- if (this[i] == deleteValue) {
- this.splice(i, 1);
- i--;
- }
- }
- return this;
- };
-}
-
-if (!Array.prototype.map) {
- Array.prototype.map = function(callback, thisArg) {
-
- let T, A, k;
-
- if (this == null) {
- throw new TypeError(" this is null or not defined");
- }
-
- // 1. Let O be the result of calling ToObject passing the |this| value as the argument.
- let O = Object(this);
-
- // 2. Let lenValue be the result of calling the Get internal method of O with the argument "length".
- // 3. Let len be ToUint32(lenValue).
- let len = O.length >>> 0;
-
- // 4. If IsCallable(callback) is false, throw a TypeError exception.
- // See: http://es5.github.com/#x9.11
- if (typeof callback !== "function") {
- throw new TypeError(callback + " is not a function");
- }
-
- // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
- if (thisArg) {
- T = thisArg;
- }
-
- // 6. Let A be a new array created as if by the expression new Array(len) where Array is
- // the standard built-in constructor with that name and len is the value of len.
- A = new Array(len);
-
- // 7. Let k be 0
- k = 0;
-
- // 8. Repeat, while k < len
- while(k < len) {
-
- let kValue, mappedValue;
-
- // a. Let Pk be ToString(k).
- // This is implicit for LHS operands of the in operator
- // b. Let kPresent be the result of calling the HasProperty internal method of O with argument Pk.
- // This step can be combined with c
- // c. If kPresent is true, then
- if (k in O) {
-
- // i. Let kValue be the result of calling the Get internal method of O with argument Pk.
- kValue = O[ k ];
-
- // ii. Let mappedValue be the result of calling the Call internal method of callback
- // with T as the this value and argument list containing kValue, k, and O.
- mappedValue = callback.call(T, kValue, k, O);
-
- // iii. Call the DefineOwnProperty internal method of A with arguments
- // Pk, Property Descriptor {Value: mappedValue, : true, Enumerable: true, Configurable: true},
- // and false.
-
- // In browsers that support Object.defineProperty, use the following:
- // Object.defineProperty(A, Pk, { value: mappedValue, writable: true, enumerable: true, configurable: true });
-
- // For best browser support, use the following:
- A[ k ] = mappedValue;
- }
- // d. Increase k by 1.
- k++;
- }
-
- // 9. return A
- return A;
- };
-}
diff --git a/catalog-ui/app/scripts/utils/validation-utils.ts b/catalog-ui/app/scripts/utils/validation-utils.ts
deleted file mode 100644
index 7618e7d0e3..0000000000
--- a/catalog-ui/app/scripts/utils/validation-utils.ts
+++ /dev/null
@@ -1,173 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../references"/>
-
-module Sdc.Utils {
- class basePattern{
- pattern:RegExp;
- base:number;
- constructor(pattern:RegExp, base:number){
- this.pattern = pattern;
- this.base = base;
- }
- }
-
- export interface IMapRegex{
- integer: RegExp;
- boolean: RegExp;
- float: RegExp;
- string: RegExp;
- }
-
- export class ValidationUtils {
-
- static '$inject' = [
- 'IntegerNoLeadingZeroValidationPattern',
- 'FloatValidationPattern',
- 'CommentValidationPattern',
- 'BooleanValidationPattern',
- 'NumberValidationPattern',
- 'LabelValidationPattern',
- ];
- private trueRegex : string = '[t][r][u][e]|[t]|[o][n]|[y]|[y][e][s]|[1]';
- private falseRegex : string = '[f][a][l][s][e]|[f]|[o][f][f]|[n]|[n][o]|[0]';
- private heatBooleanValidationPattern : RegExp = new RegExp( '^('+this.trueRegex+'|'+this.falseRegex+')$');
-
-
- constructor(private IntegerNoLeadingZeroValidationPattern:RegExp,
- private FloatValidationPattern:RegExp,
- private CommentValidationPattern:RegExp,
- private BooleanValidationPattern:RegExp,
- private NumberValidationPattern:RegExp,
- private LabelValidationPattern:RegExp) {}
-
- public stripAndSanitize(text:string):string{
- if(!text){
- return null;
- }
- return text.replace(/\s+/g, ' ').replace(/%[A-Fa-f0-9]{2}/g, '').trim();
- }
-
- public getValidationPattern = (validationType:string , parameterType?:string) : RegExp => {
- switch (validationType){
- case 'integer':
- return this.IntegerNoLeadingZeroValidationPattern;
- case 'float':
- return this.FloatValidationPattern;
- case 'number':
- return this.NumberValidationPattern;
- case 'string':
- return this.CommentValidationPattern;
- case 'boolean':
- {
- //Bug Fix DE197437 [Patch]Mismatch between BE to FE regarding supported characters in Boolean filed
- if( parameterType && parameterType === 'heat'){
- return this.heatBooleanValidationPattern;
- }
- else{
- return this.BooleanValidationPattern;
- }
-
- }
-
- case 'label':
- return this.LabelValidationPattern;
- case 'category':
- return this.LabelValidationPattern;
- default :
- return null;
- }
- };
-
- public getPropertyListPatterns():IMapRegex {
- return {
- integer: /^(0|[-+]?[1-9][0-9]*|[-+]?0x[0-9a-fA-F]+|[-+]?0o[0-7]+)(,?(0|[-+]?[1-9][0-9]*|[-+]?0x[0-9a-fA-F]+|[-+]?0o[0-7]+))*$/,
- string: /^"[\u0000-\u0021\u0023-\u00BF]+"(\s*,?\s*"[\u0000-\u0021\u0023-\u00BF]+")*$/,
- boolean: /^([Tt][Rr][Uu][Ee]|[Ff][Aa][Ll][Ss][Ee])(,?([Tt][Rr][Uu][Ee]|[Ff][Aa][Ll][Ss][Ee]))*$/,
- float: /^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?(,?[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?f?)*$/
- };
- }
- public getPropertyMapPatterns():IMapRegex {
- return {
- integer: /^"\w+"\s*:\s?(0|[-+]?[1-9][0-9]*|[-+]?0x[0-9a-fA-F]+|[-+]?0o[0-7]+)+(\s*,?\s*"\w+"\s?:\s?(0|[-+]?[1-9][0-9]*|[-+]?0x[0-9a-fA-F]+|[-+]?0o[0-7]+)+)*$/,
- string: /^"\w+"\s?:\s?"[\u0000-\u0021\u0023-\u00BF]*"(\s*,?\s*"\w+"\s?:\s?"[\u0000-\u0021\u0023-\u00BF]*")*$/,
- boolean: /^"\w+"\s?:\s?([Tt][Rr][Uu][Ee]|[Ff][Aa][Ll][Ss][Ee])(\s*,?\s*"\w+"\s?:\s?([Tt][Rr][Uu][Ee]|[Ff][Aa][Ll][Ss][Ee]))*$/,
- float: /^"\w+"\s?:\s?[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?f?(\s*,?\s*"\w+"\s?:\s?[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?f?)*$/
- };
- }
- public validateUniqueKeys(viewValue:string):boolean {
- if(!viewValue) {
- return true; //allow empty value
- }
-
- let json:string = "{" + viewValue.replace(/\s\s+/g, ' ') + "}";
- try{
- let obj:any = JSON.parse(json);
- /*
- //Method #1 : check json string length before & after parsing
- let newJson:string = JSON.stringify(obj);
- if (newJson.length < json.length) {
- return false;
- }*/
-
- //Method #2 : check how many times we can find "KEY": in json string
- let result:boolean = true;
- Object.keys(obj).forEach((key:string) => {
- result = result && json.split('"' + key + '":').length === 2;
- });
- return result;
-
- }catch(e){
- return false; //not a valid JSON
- }
-
- //return true;
- }
-
- public validateJson = (json:string):boolean => {
- try{
- JSON.parse(json);
- return true;
- }catch(err){
- console.log('invalid json');
- return false;
- }
- };
-
- public validateIntRange = (value:string):boolean => {
-
- let base8 = new basePattern(/^([-+]?0o[0-7]+)$/, 8);
- let base10 = new basePattern(/^(0|[-+]?[1-9][0-9]*)$/, 10);
- let base16 = new basePattern(/^([-+]?0x[0-9a-fA-F]+)$/, 16);
-
- let min:number = -0x80000000;
- let max:number = 0x7fffffff;
- let intPatterns:Array<basePattern> = [base8, base10, base16];
- let matchedBase = _.find(intPatterns, (item)=> {
- return item.pattern.test(value);
- });
-
- let parsed:number = parseInt(value.replace('o',''), matchedBase.base);
- if(parsed){
- return min <= parsed && max >= parsed;
- }
- }
- }
-}
diff --git a/catalog-ui/app/scripts/view-models/admin-dashboard/add-category-modal/add-category-modal-view-model.ts b/catalog-ui/app/scripts/view-models/admin-dashboard/add-category-modal/add-category-modal-view-model.ts
deleted file mode 100644
index 93c1dac174..0000000000
--- a/catalog-ui/app/scripts/view-models/admin-dashboard/add-category-modal/add-category-modal-view-model.ts
+++ /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=========================================================
- */
-/// <reference path="../../../references"/>
-module Sdc.ViewModels {
- 'use strict';
-
- interface IAddCategoryModalViewModelScope extends ng.IScope {
- category:Sdc.Services.ICategoryResource;
- modelType:string;
- footerButtons: Array<any>;
- forms:any;
-
- save():void;
- close():void;
- }
-
- export class AddCategoryModalViewModel {
-
- static '$inject' = [
- '$scope',
- 'Sdc.Services.CategoryResourceService',
- '$modalInstance',
- 'parentCategory',
- 'type'
- ];
-
- constructor(
- private $scope:IAddCategoryModalViewModelScope,
- private categoryResourceService:Sdc.Services.ICategoryResourceClass,
- private $modalInstance:ng.ui.bootstrap.IModalServiceInstance,
- private parentCategory:Sdc.Services.ICategoryResource,
- private type:string
- ){
- this.initScope();
- }
-
- private initScope = ():void => {
- this.$scope.forms = {};
- this.$scope.modelType = this.parentCategory ? 'sub category' : 'category';
- this.$scope.category = new this.categoryResourceService();
-
- this.$scope.close = ():void => {
- this.$modalInstance.dismiss();
- };
-
- this.$scope.save = ():void => {
-
- let onOk = (newCategory :Sdc.Services.ICategoryResource):void => {
- this.$modalInstance.close(newCategory);
- };
-
- let onCancel = ():void => {
- //error
- };
-
- if(!this.parentCategory) {
- this.$scope.category.$save({types: this.type+"s"}, onOk, onCancel);
- }else{
- this.$scope.category.$saveSubCategory({types: this.type+"s", categoryId: this.parentCategory.uniqueId}, onOk, onCancel);
- }
-
- };
-
- this.$scope.footerButtons = [
- {'name': 'OK', 'css': 'blue', 'callback': this.$scope.save, 'disabled': true},
- {'name': 'Cancel', 'css': 'grey', 'callback': this.$scope.close}
- ];
-
- this.$scope.$watch("forms.editForm.$invalid", (newVal, oldVal) => {
- this.$scope.footerButtons[0].disabled = this.$scope.forms.editForm.$invalid;
- });
-
- }
-
-
- }
-}
diff --git a/catalog-ui/app/scripts/view-models/admin-dashboard/admin-dashboard-view-model.ts b/catalog-ui/app/scripts/view-models/admin-dashboard/admin-dashboard-view-model.ts
deleted file mode 100644
index d7cbbcc68d..0000000000
--- a/catalog-ui/app/scripts/view-models/admin-dashboard/admin-dashboard-view-model.ts
+++ /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=========================================================
- */
-/// <reference path="../../references"/>
-module Sdc.ViewModels {
-
- 'use strict';
-
- interface IAdminDashboardViewModelScope extends ng.IScope {
- version:string;
- sdcConfig:Models.IAppConfigurtaion;
- isLoading: boolean;
- currentTab: string;
- templateUrl:string;
- monitorUrl:string;
- moveToTab(tab:string):void;
- isSelected(tab:string):boolean;
- }
-
-
- export class AdminDashboardViewModel {
- static '$inject' = [
- '$scope',
- 'Sdc.Services.CacheService',
- 'sdcConfig'
- ];
-
- constructor(private $scope:IAdminDashboardViewModelScope,
- private cacheService:Services.CacheService,
- private sdcConfig:Models.IAppConfigurtaion) {
-
- this.initScope();
- }
-
-
- private initScope = ():void => {
-
- this.$scope.version = this.cacheService.get('version');
- this.$scope.sdcConfig = this.sdcConfig;
- this.$scope.monitorUrl = this.$scope.sdcConfig.api.kibana;
- this.$scope.isSelected=(tab:string):boolean => {
- return tab===this.$scope.currentTab;
- }
-
- this.$scope.moveToTab=(tab:string):void => {
- if (tab===this.$scope.currentTab){
- return;
- }
- else if(tab === 'USER_MANAGEMENT'){
- this.$scope.templateUrl = '/app/scripts/view-models/admin-dashboard/user-management/user-management-view.html';
- }
- else if(tab ==='CATEGORY_MANAGEMENT'){
- this.$scope.templateUrl = '/app/scripts/view-models/admin-dashboard/category-management/category-management-view.html';
- }
- /* else if(tab ==='ECOMP'){
- this.$scope.templateUrl = '/app/scripts/view-models/admin-dashboard/ecomp/ecomp-view.html';
- }*/
- this.$scope.currentTab = tab;
- };
-
- this.$scope.moveToTab('USER_MANAGEMENT');
-
-
- }
- }
-}
diff --git a/catalog-ui/app/scripts/view-models/admin-dashboard/category-management/category-management-view-model.ts b/catalog-ui/app/scripts/view-models/admin-dashboard/category-management/category-management-view-model.ts
deleted file mode 100644
index a3ad7a2714..0000000000
--- a/catalog-ui/app/scripts/view-models/admin-dashboard/category-management/category-management-view-model.ts
+++ /dev/null
@@ -1,197 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../../references"/>
-module Sdc.ViewModels {
- 'use strict';
-
- interface ICategoryManagementViewModelScope extends ng.IScope {
- SERVICE:string;
- RESOURCE:string;
- categoriesToShow: Array<Sdc.Services.ICategoryResource>;
- serviceCategories: Array<Sdc.Services.ICategoryResource>;
- resourceCategories: Array<Sdc.Services.ICategoryResource>;
- selectedCategory: Sdc.Services.ICategoryResource;
- selectedSubCategory: Sdc.Services.ICategoryResource;
- modalInstance:ng.ui.bootstrap.IModalServiceInstance;
- isLoading:boolean;
- type:string;
- namePattern:RegExp;
-
- selectCategory(category:Sdc.Services.ICategoryResource) :void;
- selectSubCategory(subcategory:Sdc.Services.ICategoryResource) :void;
- selectType(type:string) :void;
- deleteCategory(category:Sdc.Services.ICategoryResource, subCategory:Sdc.Services.ICategoryResource) :void;
- createCategoryModal(parentCategory:Sdc.Services.ICategoryResource) :void;
- }
-
- export class CategoryManagementViewModel {
- static '$inject' = [
- '$scope',
- 'sdcConfig',
- 'Sdc.Services.CacheService',
- '$templateCache',
- '$modal',
- '$filter',
- 'ValidationUtils',
- 'ModalsHandler'
- ];
-
- constructor(private $scope:ICategoryManagementViewModelScope,
- private sdcConfig:Models.IAppConfigurtaion,
- private cacheService:Services.CacheService,
- private $templateCache:ng.ITemplateCacheService,
- private $modal:ng.ui.bootstrap.IModalService,
- private $filter:ng.IFilterService,
- private ValidationUtils: Sdc.Utils.ValidationUtils,
- private ModalsHandler: Utils.ModalsHandler
- ) {
-
- this.initScope();
- this.$scope.selectType(Sdc.Utils.Constants.ComponentType.SERVICE.toLocaleLowerCase());
-
- }
-
- private initScope = ():void => {
- let scope:ICategoryManagementViewModelScope = this.$scope;
- scope.SERVICE = Sdc.Utils.Constants.ComponentType.SERVICE.toLocaleLowerCase();
- scope.RESOURCE = Sdc.Utils.Constants.ComponentType.RESOURCE.toLocaleLowerCase();
-
- scope.namePattern = this.ValidationUtils.getValidationPattern('cssClasses');
-
- scope.selectCategory = (category :Sdc.Services.ICategoryResource) => {
- if(scope.selectedCategory !== category) {
- scope.selectedSubCategory = null;
- }
- scope.selectedCategory = category;
- };
- scope.selectSubCategory = (subcategory :Sdc.Services.ICategoryResource) => {
- scope.selectedSubCategory = subcategory;
- };
- scope.selectType = (type:string):void => {
- if (scope.type !== type) {
- scope.selectedCategory = null;
- scope.selectedSubCategory = null;
- }
-
- scope.type = type;
- scope.categoriesToShow = scope[type + 'Categories'];
- };
-
- scope.createCategoryModal = (parentCategory:Sdc.Services.ICategoryResource):void => {
- //can't create a sub category for service
- if(parentCategory && scope.type === Sdc.Utils.Constants.ComponentType.SERVICE.toLowerCase()) {
- return;
- }
-
- let type:string = scope.type;
-
- let onOk = (newCategory :Sdc.Services.ICategoryResource):void => {
- if(!parentCategory) {
- scope[type + 'Categories'].push(newCategory);
- }else{
- if(!parentCategory.subcategories) {
- parentCategory.subcategories = [];
- }
- parentCategory.subcategories.push(newCategory);
- }
- };
-
- let onCancel = ():void => {
-
- };
-
- let modalOptions:ng.ui.bootstrap.IModalSettings = {
- template: this.$templateCache.get('/app/scripts/view-models/admin-dashboard/add-category-modal/add-category-modal-view.html'),
- controller: 'Sdc.ViewModels.AddCategoryModalViewModel',
- size: 'sdc-xsm',
- backdrop: 'static',
- scope: scope,
- resolve: {
- parentCategory: function () {
- return parentCategory;
- },
- type: function () {
- return type;
- }
- }
- };
-
- scope.modalInstance = this.$modal.open(modalOptions);
- scope.modalInstance.result.then(onOk, onCancel);
-
- };
-
- scope.deleteCategory = (category: Sdc.Services.ICategoryResource, subCategory: Sdc.Services.ICategoryResource): void => {
-
- let onOk = ():void => {
-
- scope.isLoading = true;
- let type:string = scope.type;
-
- let onError = (response):void => {
- scope.isLoading = false;
- console.info('onFaild', response);
- };
-
- let onSuccess = (response: any) :void => {
- let arr:Array<Sdc.Services.ICategoryResource>;
-
- if(!subCategory) {
- arr = this.$scope[type + 'Categories'];
- arr.splice(arr.indexOf(category), 1);
- if(category === scope.selectedCategory) {
- scope.selectedCategory = null;
- scope.selectedSubCategory = null;
- }
- } else {
- arr = category.subcategories;
- arr.splice(arr.indexOf(subCategory), 1);
- }
-
- scope.isLoading = false;
- };
-
- if(!subCategory) {
- category.$delete({
- types: type+"s",
- categoryId: category.uniqueId
- }
- , onSuccess, onError);
- } else {
- category.$deleteSubCategory({
- types: type+"s",
- categoryId: category.uniqueId,
- subCategoryId: subCategory.uniqueId,
- }
- , onSuccess, onError);
- }
- };
- let modelType:string = subCategory ? 'sub category' : 'cssClasses';
- let title:string = this.$filter('translate')("DELETE_CATEGORY_MODAL_HEADER", "{'modelType': '" + modelType +"' }");
- let message:string = this.$filter('translate')("DELETE_CATEGORY_MODAL_CATEGORY_NAME", "{'modelType': '" + modelType +"' }");
-
- this.ModalsHandler.openConfirmationModal(title, message, false, 'sdc-xsm').then(onOk);
- };
-
- this.$scope.serviceCategories = this.cacheService.get('serviceCategories');
- this.$scope.resourceCategories = this.cacheService.get('resourceCategories');
- }
- }
-}
diff --git a/catalog-ui/app/scripts/view-models/admin-dashboard/user-management/user-management-view-model.ts b/catalog-ui/app/scripts/view-models/admin-dashboard/user-management/user-management-view-model.ts
deleted file mode 100644
index 3921d0cf8f..0000000000
--- a/catalog-ui/app/scripts/view-models/admin-dashboard/user-management/user-management-view-model.ts
+++ /dev/null
@@ -1,220 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../../references"/>
-module Sdc.ViewModels {
-
- import IUserProperties = Sdc.Models.IUserProperties;
- 'use strict';
-
- interface IUserManagementViewModelScope extends ng.IScope {
- sdcConfig:Models.IAppConfigurtaion;
- usersList: Array<Models.IUserProperties>;
- isLoading: boolean;
- isNewUser: boolean;
- sortBy:string;
- reverse:boolean;
- tableHeadersList:any;
- roles:Array<string>;
- newUser: Models.IUser;
- currentUser: Sdc.Services.IUserResource;
- userIdValidationPattern: RegExp;
- editForm:ng.IFormController;
- getAllUsers():void;
- editUserRole(user:IUserProperties);
- sort(sortBy:string): void;
- createUser(): void;
- deleteUser(userId:string) : void;
- onEditUserPressed(user:IUserProperties): void;
- saveUserChanges(user:IUserProperties) :void;
- getTitle(role:string): string;
- clearForm():void;
-
- }
-
-
- export class UserManagementViewModel {
- static '$inject' = [
- '$scope',
- 'sdcConfig',
- 'Sdc.Services.UserResourceService',
- '$templateCache',
- '$modal',
- 'UserIdValidationPattern',
- '$filter',
- 'ModalsHandler'
- ];
-
- constructor(private $scope:IUserManagementViewModelScope,
- private sdcConfig:Models.IAppConfigurtaion,
- private userResourceService:Sdc.Services.IUserResourceClass,
- private $templateCache:ng.ITemplateCacheService,
- private $modal:ng.ui.bootstrap.IModalService,
- private UserIdValidationPattern:RegExp,
- private $filter:ng.IFilterService,
- private ModalsHandler: Utils.ModalsHandler
- ) {
-
- this.initScope();
-
- }
-
-
-
- private getAllUsers = ():void => {
- this.$scope.isLoading = true;
-
- let onError = (response) => {
- this.$scope.isLoading = false;
- console.info('onFaild', response);
- };
- let onSuccess = (response: Array<Models.IUserProperties>) => {
- this.$scope.usersList = response;
- _.forEach(this.$scope.usersList,(user:any,i:number)=>{
- user.index = i;
- });
- this.$scope.isLoading = false;
- };
- this.userResourceService.getAllUsers(onSuccess, onError);
- };
-
- private updateUserFilterTerm = (user: IUserProperties): void =>{
- user.filterTerm = user.firstName + ' ' + user.lastName + ' ' + user.userId + ' ' + user.email + ' ' + user.role + ' ' + this.$filter('date')(user.lastLoginTime, "MM/dd/yyyy");
- };
-
- private initScope = ():void => {
- let self=this;
-
- this.$scope.tableHeadersList = [
- {title: "First Name", property: 'firstName'},
- {title: "Last Name", property: 'lastName'},
- {title: this.$filter('translate')("USER_MANAGEMENT_TABLE_HEADER_USER_ID"), property: 'userId'},
- {title: "Email", property: 'email'},
- {title: "Role", property: 'role'},
- {title: "Last Active", property: 'lastLoginTime'}
- ];
- this.$scope.userIdValidationPattern = this.UserIdValidationPattern;
- this.$scope.sortBy = 'lastLoginTime';
- this.$scope.reverse = false;
- this.$scope.roles = this.sdcConfig.roles;
- this.$scope.isNewUser = false;
- this.$scope.currentUser = this.userResourceService.getLoggedinUser();
- this.getAllUsers();
-
- let resource : Services.IUserResource = <Services.IUserResource>{};
- this.$scope.newUser = new Sdc.Models.User(resource);
-
- this.$scope.sort = (sortBy:string):void => {//default sort by descending last update. default for alphabetical = ascending
- this.$scope.isNewUser = false;
- this.$scope.reverse = (this.$scope.sortBy === sortBy) ? ( !this.$scope.reverse) : this.$scope.reverse = false;
- this.$scope.sortBy = sortBy;
- };
-
- this.$scope.createUser = () : void => {
-
- let onError = (response) => {
- this.$scope.isLoading = false;
- console.info('onFaild', response);
- };
-
- let onSuccess = (response: Models.IUserProperties) => {
- this.$scope.newUser.resource['index'] = this.$scope.usersList.length;
- this.$scope.newUser.resource.lastLoginTime = "0";
- this.$scope.newUser.resource.status = response.status;
- this.updateUserFilterTerm(this.$scope.newUser.resource);
- this.$scope.usersList.unshift(this.$scope.newUser.resource);
- this.$scope.isNewUser = true;
- this.$scope.sortBy = 'index';
- this.$scope.reverse = true;
- this.$scope.isLoading = false;
- this.$scope.newUser = new Sdc.Models.User(null);
- this.$scope.editForm.$setPristine();
- let _self = this;
- setTimeout(function () {
- _self.$scope.isNewUser = false;
- }, 7000);
- };
- this.userResourceService.createUser({ userId: this.$scope.newUser.resource.userId, role: this.$scope.newUser.resource.role}, onSuccess, onError);
- };
-
-
- this.$scope.onEditUserPressed = (user:IUserProperties): void => {
- user.isInEditMode = true;
- user.tempRole = user.role;
- };
-
- this.$scope.editUserRole = (user:IUserProperties): void => {
- let roleBeforeUpdate: string = user.role;
- user.role= user.tempRole;
-
- let onError = (response) => {
- this.$scope.isLoading = false;
- user.role = roleBeforeUpdate;
- console.info('onFaild', response);
- };
- let onSuccess = (response: any) => {
- this.$scope.isLoading = false;
- user.tempRole = user.role;
- this.updateUserFilterTerm(user);
- };
-
- this.userResourceService.editUserRole({ id: user.userId, role: user.role}, onSuccess, onError);
- };
-
- this.$scope.saveUserChanges = (user:IUserProperties): void => {
- if(user.tempRole != user.role){
- this.$scope.editUserRole(user)
- }
- user.isInEditMode = false;
- };
-
- this.$scope.deleteUser = (userId:string): void => {
-
- let onOk = ():void => {
- this.$scope.isLoading = true;
-
- let onError = (response):void => {
- this.$scope.isLoading = false;
- console.info('onFaild', response);
- };
-
- let onSuccess = (response: any) :void => {
- _.remove(this.$scope.usersList, {userId: userId });
- this.$scope.isLoading = false;
- };
- this.userResourceService.deleteUser({ id: userId}, onSuccess, onError);
- };
-
- let title:string = this.$filter('translate')("USER_MANAGEMENT_VIEW_DELETE_MODAL_TITLE");
- let message:string = this.$filter('translate')("USER_MANAGEMENT_VIEW_DELETE_MODAL_TEXT");
- this.ModalsHandler.openConfirmationModal(title, message, false).then(onOk);
- };
-
- this.$scope.getTitle = (role:string):string =>{
- return role.toLowerCase().replace('governor','governance_Rep').replace('_',' ');
- };
-
- this.$scope.clearForm =():void =>{
- if(!this.$scope.editForm['contactId'].$viewValue && !this.$scope.editForm['role'].$viewValue){
- this.$scope.editForm.$setPristine();
- }
- };
- }
- }
-}
diff --git a/catalog-ui/app/scripts/view-models/catalog/catalog-view-model.ts b/catalog-ui/app/scripts/view-models/catalog/catalog-view-model.ts
deleted file mode 100644
index bf37e92e56..0000000000
--- a/catalog-ui/app/scripts/view-models/catalog/catalog-view-model.ts
+++ /dev/null
@@ -1,312 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../references"/>
-module Sdc.ViewModels {
-
- 'use strict';
-
- interface Checkboxes {
- componentTypes:Array<string>;
- resourceSubTypes:Array<string>;
- }
-
- interface CheckboxesFilter {
- // Types
- selectedComponentTypes:Array<string>;
- selectedResourceSubTypes:Array<string>;
- // Categories
- selectedCategoriesModel:Array<string>;
- // Statuses
- selectedStatuses:Array<string>;
- }
-
- interface Gui {
- isLoading: boolean;
- onResourceSubTypesClick:Function;
- onComponentTypeClick:Function;
- onCategoryClick:Function;
- onSubcategoryClick:Function;
- onGroupClick:Function;
- }
-
- export interface ICatalogViewModelScope extends ng.IScope {
- checkboxes:Checkboxes;
- checkboxesFilter:CheckboxesFilter;
- gui:Gui;
-
- categories: Array<Models.IMainCategory>;
- confStatus: Models.IConfigStatuses;
- sdcMenu:Models.IAppMenu;
- catalogFilterdItems: Array<Models.Components.Component>;
- expandedSection: Array<string>;
- actionStrategy: any;
- user: Models.IUserProperties;
- catalogMenuItem: any;
- version:string;
- sortBy:string;
- reverse:boolean;
-
- //this is for UI paging
- numberOfItemToDisplay:number;
- isAllItemDisplay: boolean;
-
- openViewerModal(isResource: boolean, uniqueId: string): void;
- changeLifecycleState(entity:any,state:string): void;
- sectionClick (section:string):void;
- order(sortBy:string): void;
- getNumOfElements(num:number): string;
- goToComponent(component:Models.Components.Component):void;
- raiseNumberOfElementToDisplay():void;
- }
-
- export class CatalogViewModel {
- static '$inject' = [
- '$scope',
- '$filter',
- 'Sdc.Services.EntityService',
- 'sdcConfig',
- 'sdcMenu',
- '$state',
- '$q',
- 'Sdc.Services.UserResourceService',
- '$modal',
- '$templateCache',
- 'Sdc.Services.CacheService',
- 'ComponentFactory',
- 'ChangeLifecycleStateHandler',
- 'ModalsHandler',
- 'MenuHandler'
- ];
-
- constructor(private $scope:ICatalogViewModelScope,
- private $filter:ng.IFilterService,
- private EntityService:Services.EntityService,
- private sdcConfig:Models.IAppConfigurtaion,
- private sdcMenu:Models.IAppMenu,
- private $state:any,
- private $q:any,
- private userResourceService:Sdc.Services.IUserResourceClass,
- private $modal:ng.ui.bootstrap.IModalService,
- private $templateCache:ng.ITemplateCacheService,
- private cacheService:Services.CacheService,
- private ComponentFactory: Sdc.Utils.ComponentFactory,
- private ChangeLifecycleStateHandler: Sdc.Utils.ChangeLifecycleStateHandler,
- private OpenViewModalHandler: Utils.ModalsHandler,
- private MenuHandler: Utils.MenuHandler
- ) {
-
- this.initScopeMembers();
- this.initCatalogData(); // Async task to get catalog from server.
- this.initScopeMethods();
- }
-
- private initCatalogData = ():void => {
- let onSuccess = (followedResponse:Array<Models.Components.Component>):void => {
- this.$scope.catalogFilterdItems = followedResponse;
- this.$scope.isAllItemDisplay = this.$scope.numberOfItemToDisplay >= this.$scope.catalogFilterdItems.length;
- this.$scope.categories = this.cacheService.get('serviceCategories').concat(this.cacheService.get('resourceCategories')).concat(this.cacheService.get('productCategories'));
- this.$scope.gui.isLoading = false;
- };
-
- let onError = ():void => {
- console.info('Failed to load catalog CatalogViewModel::initCatalog');
- this.$scope.gui.isLoading = false;
- };
- this.EntityService.getCatalog().then(onSuccess, onError);
- };
-
-
-
- private initScopeMembers = ():void => {
- // Gui init
- this.$scope.gui = <Gui>{};
- this.$scope.gui.isLoading = true;
- this.$scope.numberOfItemToDisplay = 0;
- //this.$scope.categories = this.cacheService.get('categoriesMap');
- this.$scope.sdcMenu = this.sdcMenu;
- this.$scope.confStatus = this.sdcMenu.statuses;
- this.$scope.expandedSection = ["type", "cssClasses", "product-category", "status"];
- this.$scope.user = this.userResourceService.getLoggedinUser();
- this.$scope.catalogMenuItem = this.sdcMenu.catalogMenuItem;
- this.$scope.version = this.cacheService.get('version');
- this.$scope.sortBy = 'lastUpdateDate';
- this.$scope.reverse = true;
-
-
- // Checklist init
- this.$scope.checkboxes = <Checkboxes>{};
- this.$scope.checkboxes.componentTypes = ['Resource', 'Service', 'Product'];
- this.$scope.checkboxes.resourceSubTypes = ['VF', 'VFC', 'CP', 'VL'];
-
- // Checkboxes filter init
- this.$scope.checkboxesFilter = <CheckboxesFilter>{};
- this.$scope.checkboxesFilter.selectedComponentTypes = [];
- this.$scope.checkboxesFilter.selectedResourceSubTypes = [];
- this.$scope.checkboxesFilter.selectedCategoriesModel = [];
- this.$scope.checkboxesFilter.selectedStatuses = [];
-
- // this.$scope.isAllItemDisplay = this.$scope.numberOfItemToDisplay >= this.$scope.catalogFilterdItems.length;
- };
-
- private initScopeMethods = ():void => {
- this.$scope.sectionClick = (section:string):void => {
- let index:number = this.$scope.expandedSection.indexOf(section);
- if (index!==-1) {
- this.$scope.expandedSection.splice(index,1);
- } else {
- this.$scope.expandedSection.push(section);
- }
- };
-
-
- this.$scope.order = (sortBy:string):void => {//default sort by descending last update. default for alphabetical = ascending
- this.$scope.reverse = (this.$scope.sortBy === sortBy) ? !this.$scope.reverse : (sortBy === 'lastUpdateDate') ? true: false;
- this.$scope.sortBy = sortBy;
- };
-
-
- this.$scope.goToComponent = (component:Models.Components.Component):void => {
- this.$scope.gui.isLoading = true;
- this.$state.go('workspace.general', {id: component.uniqueId, type:component.componentType.toLowerCase()});
- };
-
-
- // Will print the number of elements found in catalog
- this.$scope.getNumOfElements = (num:number) : string => {
- if (!num || num===0){
- return "No Elements found";
- } else if (num===1){
- return "1 Element found";
- }else {
- return num + " Elements found";
- }
- };
-
- /**
- * Select | unselect sub resource when resource is clicked | unclicked.
- * @param type
- */
- this.$scope.gui.onComponentTypeClick = (type:string): void => {
- if (type==='Resource'){
- if (this.$scope.checkboxesFilter.selectedComponentTypes.indexOf('Resource')===-1){
- // If the resource was not selected, unselect all childs.
- this.$scope.checkboxesFilter.selectedResourceSubTypes = [];
- } else {
- // If the resource was selected, select all childs
- this.$scope.checkboxesFilter.selectedResourceSubTypes = angular.copy(this.$scope.checkboxes.resourceSubTypes);
- }
- }
- };
-
- /**
- * Selecting | unselect resources when sub resource is clicked | unclicked.
- */
- this.$scope.gui.onResourceSubTypesClick = ():void => {
- if (this.$scope.checkboxesFilter.selectedResourceSubTypes && this.$scope.checkboxesFilter.selectedResourceSubTypes.length===this.$scope.checkboxes.resourceSubTypes.length){
- this.$scope.checkboxesFilter.selectedComponentTypes.push('Resource');
- } else {
- this.$scope.checkboxesFilter.selectedComponentTypes = _.without(this.$scope.checkboxesFilter.selectedComponentTypes,'Resource');
- }
- };
-
- this.$scope.gui.onCategoryClick = (category:Models.IMainCategory): void => {
- // Select | Unselect all childs
- if (this.isCategorySelected(category.uniqueId)){
- this.$scope.checkboxesFilter.selectedCategoriesModel = this.$scope.checkboxesFilter.selectedCategoriesModel.concat(angular.copy(_.map(category.subcategories, (item) => { return item.uniqueId; })));
- if (category.subcategories) {
- category.subcategories.forEach((sub:Models.ISubCategory)=> { // Loop on all selected subcategories and mark the childrens
- this.$scope.checkboxesFilter.selectedCategoriesModel = this.$scope.checkboxesFilter.selectedCategoriesModel.concat(angular.copy(_.map(sub.groupings, (item) => {
- return item.uniqueId;
- })));
- });
- }
- } else {
- this.$scope.checkboxesFilter.selectedCategoriesModel = _.difference(this.$scope.checkboxesFilter.selectedCategoriesModel, _.map(category.subcategories, (item) => { return item.uniqueId; }));
- if (category.subcategories) {
- category.subcategories.forEach((sub:Models.ISubCategory)=> { // Loop on all selected subcategories and un mark the childrens
- this.$scope.checkboxesFilter.selectedCategoriesModel = _.difference(this.$scope.checkboxesFilter.selectedCategoriesModel, _.map(sub.groupings, (item) => {
- return item.uniqueId;
- }));
- });
- }
- }
- };
-
- this.$scope.gui.onSubcategoryClick = (category:Models.IMainCategory, subCategory:Models.ISubCategory) : void => {
- // Select | Unselect all childs
- if (this.isCategorySelected(subCategory.uniqueId)){
- this.$scope.checkboxesFilter.selectedCategoriesModel = this.$scope.checkboxesFilter.selectedCategoriesModel.concat(angular.copy(_.map(subCategory.groupings, (item) => { return item.uniqueId; })));
- } else {
- this.$scope.checkboxesFilter.selectedCategoriesModel = _.difference(this.$scope.checkboxesFilter.selectedCategoriesModel, _.map(subCategory.groupings, (item) => { return item.uniqueId; }));
- }
-
- // Mark | Un mark the parent when all childs selected.
- if (this.areAllCategoryChildsSelected(category)){
- // Add the category to checkboxesFilter.selectedCategoriesModel
- this.$scope.checkboxesFilter.selectedCategoriesModel.push(category.uniqueId);
- } else {
- this.$scope.checkboxesFilter.selectedCategoriesModel = _.without(this.$scope.checkboxesFilter.selectedCategoriesModel, category.uniqueId);
- }
-
- };
-
- this.$scope.raiseNumberOfElementToDisplay = () : void => {
- this.$scope.numberOfItemToDisplay = this.$scope.numberOfItemToDisplay +35;
- if(this.$scope.catalogFilterdItems) {
- this.$scope.isAllItemDisplay = this.$scope.numberOfItemToDisplay >= this.$scope.catalogFilterdItems.length;
- }
- };
-
- this.$scope.gui.onGroupClick = (subCategory:Models.ISubCategory) : void => {
- // Mark | Un mark the parent when all childs selected.
- if (this.areAllSubCategoryChildsSelected(subCategory)){
- // Add the category to checkboxesFilter.selectedCategoriesModel
- this.$scope.checkboxesFilter.selectedCategoriesModel.push(subCategory.uniqueId);
- } else {
- this.$scope.checkboxesFilter.selectedCategoriesModel = _.without(this.$scope.checkboxesFilter.selectedCategoriesModel, subCategory.uniqueId);
- }
- };
-
-
- };
-
- private areAllCategoryChildsSelected = (category:Models.IMainCategory):boolean => {
- if (!category.subcategories){return false;}
- let allIds = _.map(category.subcategories, (sub:Models.ISubCategory)=>{return sub.uniqueId;});
- let total = _.intersection(this.$scope.checkboxesFilter.selectedCategoriesModel, allIds);
- return total.length === category.subcategories.length?true:false;
- };
-
- private areAllSubCategoryChildsSelected = (subCategory:Models.ISubCategory):boolean => {
- if (!subCategory.groupings){return false;}
- let allIds = _.map(subCategory.groupings, (group:Models.IGroup)=>{return group.uniqueId;});
- let total = _.intersection(this.$scope.checkboxesFilter.selectedCategoriesModel, allIds);
- return total.length === subCategory.groupings.length?true:false;
- };
-
- private isCategorySelected = (uniqueId:string):boolean => {
- if (this.$scope.checkboxesFilter.selectedCategoriesModel.indexOf(uniqueId)!==-1){
- return true;
- }
- return false;
- };
-
- }
-}
diff --git a/catalog-ui/app/scripts/view-models/catalog/catalog-view-tests.ts b/catalog-ui/app/scripts/view-models/catalog/catalog-view-tests.ts
deleted file mode 100644
index 3e21835233..0000000000
--- a/catalog-ui/app/scripts/view-models/catalog/catalog-view-tests.ts
+++ /dev/null
@@ -1,309 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../references"/>
-describe("test catalog-view", () => {
-
- let $controllerMock:ng.IControllerService;
- let $qMock:ng.IQService;
- let $httpBackendMock:ng.IHttpBackendService;
- let $scopeMock:Sdc.ViewModels.ICatalogViewModelScope;
- let $stateMock:ng.ui.IStateService;
- let $stateParams:any;
- let entityServiceMock;
- let cacheServiceMock;
-
- beforeEach(angular.mock.module('sdcApp'));
-
- let getAllEntitiesResponseMock = [
- {
- "uniqueId": "855acdc7-7976-4913-9fa6-25220bd5a069",
- "uuid": "8bc54f94-082c-42fa-9049-84767df3ff05",
- "contactId": "qa1234",
- "category": "VoIP Call Control",
- "creationDate": 1447234712398,
- "description": "ddddd",
- "highestVersion": true,
- "icon": "mobility",
- "lastUpdateDate": 1447234712398,
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT",
- "distributionStatus": "DISTRIBUTION_NOT_APPROVED",
- "projectCode": "233233",
- "name": "mas mas mas mas mas mas mas mas mas mas mas mas ma",
- "version": "0.1",
- "type": 0,
- "tags": [
- "mas mas mas mas mas mas mas mas mas mas mas mas ma"
- ],
- "systemName": "MasMasMasMasMasMasMasMasMasMasMasMasMa",
- "vnf": true,
- "$$hashKey": "object:30"
- },
- {
- "uniqueId": "4bb577ce-cb2c-4cb7-bb39-58644b5e73cb",
- "uuid": "e27f4723-c9ec-4160-89da-dbf84d19a7e3",
- "contactId": "qa1111",
- "category": "Mobility",
- "creationDate": 1447238503181,
- "description": "aqa",
- "highestVersion": true,
- "icon": "call_controll",
- "lastUpdateDate": 1447248991388,
- "lastUpdaterUserId": "jm0007",
- "lastUpdaterFullName": "Joni Mitchell",
- "lifecycleState": "CERTIFIED",
- "distributionStatus": "DISTRIBUTION_REJECTED",
- "projectCode": "111111",
- "name": "martin18",
- "version": "1.0",
- "type": 0,
- "tags": [
- "martin18"
- ],
- "systemName": "Martin18",
- "vnf": true
- },
- {
- "uniqueId": "f192f4a6-7fbf-42e4-a546-37509df28dc1",
- "uuid": "0b77dc0d-222e-4d10-85cd-e420c9481417",
- "contactId": "fd1212",
- "category": "Application Layer 4+/Web Server",
- "creationDate": 1447233679778,
- "description": "geefw",
- "highestVersion": true,
- "icon": "database",
- "lastUpdateDate": 1447233681582,
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT",
- "name": "ger",
- "version": "0.1",
- "type": 1,
- "tags": [
- "ger"
- ],
- "vendorName": "fewwfe",
- "vendorRelease": "fewew",
- "systemName": "Ger",
- "$$hashKey": "object:31"
- },
- {
- "uniqueId": "78392d08-1859-47c2-b1f2-1a35b7f8c30e",
- "uuid": "8cdd63b2-6a62-4376-9012-624f424f71d4",
- "contactId": "qw1234",
- "category": "Application Layer 4+/Application Servers",
- "creationDate": 1447234046114,
- "description": "test",
- "highestVersion": true,
- "icon": "router",
- "lastUpdateDate": 1447234050545,
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT",
- "name": "test",
- "version": "0.1",
- "type": 1,
- "tags": [
- "test"
- ],
- "vendorName": "test",
- "vendorRelease": "test",
- "systemName": "Test",
- "$$hashKey": "object:32"
- },
- {
- "uniqueId": "939e153d-2236-410f-b4a9-3b4bf8c79c9e",
- "uuid": "84862547-4f56-4058-b78e-40df5f374d7e",
- "contactId": "qw1234",
- "category": "Application Layer 4+/Application Servers",
- "creationDate": 1447235242560,
- "description": "jlk",
- "highestVersion": true,
- "icon": "database",
- "lastUpdateDate": 1447235328062,
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "lifecycleState": "NOT_CERTIFIED_CHECKIN",
- "name": "new",
- "version": "0.1",
- "type": 1,
- "tags": [
- "new"
- ],
- "vendorName": "e",
- "vendorRelease": "e",
- "systemName": "New",
- "$$hashKey": "object:33"
- },
- {
- "uniqueId": "ece818e0-fd59-477a-baf6-e27461a7ce23",
- "uuid": "8db823c2-6a9c-4636-8676-f5e713270dd7",
- "contactId": "uf2345",
- "category": "Network Layer 2-3/Router",
- "creationDate": 1447235352429,
- "description": "u",
- "highestVersion": true,
- "icon": "network",
- "lastUpdateDate": 1447235370064,
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT",
- "name": "u",
- "version": "0.1",
- "type": 1,
- "tags": [
- "u"
- ],
- "vendorName": "u",
- "vendorRelease": "u",
- "systemName": "U",
- "$$hashKey": "object:34"
- }
- ];
-
- let resourceCategoriesResponseMock = [{"name":"Network L2-3","normalizedName":"network l2-3","uniqueId":"resourceNewCategory.network l2-3","subcategories":[{"name":"Gateway","normalizedName":"gateway","uniqueId":"resourceNewCategory.network l2-3.gateway","icons":["gateway"]},{"name":"Infrastructure","normalizedName":"infrastructure","uniqueId":"resourceNewCategory.network l2-3.infrastructure","icons":["ucpe"]},{"name":"WAN Connectors","normalizedName":"wan connectors","uniqueId":"resourceNewCategory.network l2-3.wan connectors","icons":["network","connector","port"]},{"name":"LAN Connectors","normalizedName":"lan connectors","uniqueId":"resourceNewCategory.network l2-3.lan connectors","icons":["network","connector","port"]},{"name":"Router","normalizedName":"router","uniqueId":"resourceNewCategory.network l2-3.router","icons":["router","vRouter"]}]},{"name":"Network L4+","normalizedName":"network l4+","uniqueId":"resourceNewCategory.network l4+","subcategories":[{"name":"Common Network Resources","normalizedName":"common network resources","uniqueId":"resourceNewCategory.network l4+.common network resources","icons":["network"]}]},{"name":"Application L4+","normalizedName":"application l4+","uniqueId":"resourceNewCategory.application l4+","subcategories":[{"name":"Load Balancer","normalizedName":"load balancer","uniqueId":"resourceNewCategory.application l4+.load balancer","icons":["loadBalancer"]},{"name":"Media Servers","normalizedName":"media servers","uniqueId":"resourceNewCategory.application l4+.media servers","icons":["applicationServer"]},{"name":"Application Server","normalizedName":"application server","uniqueId":"resourceNewCategory.application l4+.application server","icons":["applicationServer"]},{"name":"Database","normalizedName":"database","uniqueId":"resourceNewCategory.application l4+.database","icons":["database"]},{"name":"Call Control","normalizedName":"call control","uniqueId":"resourceNewCategory.application l4+.call control","icons":["call_controll"]},{"name":"Border Element","normalizedName":"border element","uniqueId":"resourceNewCategory.application l4+.border element","icons":["borderElement"]},{"name":"Web Server","normalizedName":"web server","uniqueId":"resourceNewCategory.application l4+.web server","icons":["applicationServer"]},{"name":"Firewall","normalizedName":"firewall","uniqueId":"resourceNewCategory.application l4+.firewall","icons":["firewall"]}]},{"name":"Generic","normalizedName":"generic","uniqueId":"resourceNewCategory.generic","subcategories":[{"name":"Database","normalizedName":"database","uniqueId":"resourceNewCategory.generic.database","icons":["database"]},{"name":"Abstract","normalizedName":"abstract","uniqueId":"resourceNewCategory.generic.abstract","icons":["objectStorage","compute"]},{"name":"Network Elements","normalizedName":"network elements","uniqueId":"resourceNewCategory.generic.network elements","icons":["network","connector"]},{"name":"Infrastructure","normalizedName":"infrastructure","uniqueId":"resourceNewCategory.generic.infrastructure","icons":["connector"]}]},{"name":"NewCategory","normalizedName":"newcategory","uniqueId":"resourceNewCategory.newcategory","subcategories":[{"name":"MyNewSubCategory","normalizedName":"mynewsubcategory","uniqueId":"resourceNewCategory.newcategory.mynewsubcategory"}]}];
-
- let getAllEntitiesDefered:ng.IDeferred<any> = null;
-
- beforeEach(angular.mock.inject((_$controller_:ng.IControllerService,
- _$httpBackend_:ng.IHttpBackendService,
- _$rootScope_,
- _$q_:ng.IQService,
- _$state_:ng.ui.IStateService,
- _$stateParams_:any) => {
-
- $controllerMock = _$controller_;
- $httpBackendMock = _$httpBackend_
- $scopeMock = _$rootScope_.$new();
- $qMock = _$q_;
- $stateMock = _$state_;
- $stateParams = _$stateParams_;
-
-
- //handle all http request thet not relevant to the tests
- $httpBackendMock.expectGET(/.*languages\/en_US.json.*/).respond(200, JSON.stringify({}));
- $httpBackendMock.expectGET(/.*rest\/version.*/).respond(200, JSON.stringify({}));
- $httpBackendMock.expectGET(/.*configuration\/ui.*/).respond(200, JSON.stringify({}));
- $httpBackendMock.expectGET(/.*user\/authorize.*/).respond(200, JSON.stringify({}));
- $httpBackendMock.expectGET(/.*categories\/services.*/).respond(200, JSON.stringify({}));
- $httpBackendMock.expectGET(/.*categories\/resources.*/).respond(200, JSON.stringify({}));
- $httpBackendMock.expectGET(/.*categories\/products.*/).respond(200, JSON.stringify({}));
- $httpBackendMock.expectGET('http://feHost:8181/sdc1/feProxy/rest/version').respond(200, JSON.stringify({}));
-
- /**
- * Mock the service
- * @type {any}
- */
- getAllEntitiesDefered = $qMock.defer();
- getAllEntitiesDefered.resolve(getAllEntitiesResponseMock);
-
- cacheServiceMock = jasmine.createSpyObj('cacheServiceMock', ['get']);
- cacheServiceMock.get.and.callFake(function(string){return resourceCategoriesResponseMock;});
- /*
- cacheServiceMock.get.and.callFake(function(value:string){
- switch(value){
- case 'serviceCategories':
- console.log('serviceCategories');
- break;
- case 'resourceCategories':
- console.log('resourceCategories');
- break;
- case 'productCategories':
- console.log('productCategories');
- break;
- default :
- console.log('default');
- break;
- }
- });
- */
-
- entityServiceMock = jasmine.createSpyObj('entityServiceMock', ['getCatalog']);
- entityServiceMock.getCatalog.and.returnValue(getAllEntitiesDefered.promise);
-
- // $stateParams['show'] = '';
-
- /**
- * Need to inject into the controller only the objects that we want to MOCK
- * those that we need to change theirs behaviors
- */
- $controllerMock(Sdc.ViewModels.CatalogViewModel, {
- '$scope': $scopeMock,
- '$stateParams': $stateParams,
- 'Sdc.Services.EntityService': entityServiceMock,
- 'Sdc.Services.CacheService': cacheServiceMock
- });
-
- }));
-
-
- beforeEach(function () {
- });
-
- describe("test GUI events on checkbox type resource click", function () {
-
- /**
- * The function checks only for resource type.
- * Select the Resource and verify that the sub resources are selected.
- *
- */
- it('test onComponentTypeClick (check select checkbox of Resource type)', function () {
- $scopeMock.$apply();
- $scopeMock.checkboxesFilter.selectedComponentTypes = ['Resource'];
- $scopeMock.gui.onComponentTypeClick('Resource');
- expect($scopeMock.checkboxesFilter.selectedResourceSubTypes.length === 4).toBeTruthy();
- });
-
- /**
- * The function checks only for resource type.
- * Un select the Resource and verify that the sub resources are selected.
- *
- */
- it('test onComponentTypeClick (check un select checkbox of Resource type)', function () {
- $scopeMock.$apply();
- $scopeMock.gui.onComponentTypeClick('Resource');
- expect($scopeMock.checkboxesFilter.selectedResourceSubTypes.length === 0).toBeTruthy();
- });
-
- });
-
- describe("test GUI events on checkbox main category click -> sub categories are selected", function () {
-
- /**
- * The function checks that after selecting 2 main categories, the subcategories are selected also.
- *
- */
- it('test onComponentTypeClick (check select checkbox of Resource type)', function () {
- let category1 = resourceCategoriesResponseMock[0];
- let category2 = resourceCategoriesResponseMock[1];
-
- $scopeMock.$apply();
- $scopeMock.checkboxesFilter.selectedCategoriesModel = [category1.uniqueId, category2.uniqueId];
- $scopeMock.gui.onCategoryClick(category1);
- $scopeMock.gui.onCategoryClick(category2);
-
- expect($scopeMock.checkboxesFilter.selectedCategoriesModel.length===8).toBeTruthy();
- });
-
- });
-
-
-});
diff --git a/catalog-ui/app/scripts/view-models/component-viewer/activity-log/activity-log-view.html b/catalog-ui/app/scripts/view-models/component-viewer/activity-log/activity-log-view.html
deleted file mode 100644
index ac51e9014c..0000000000
--- a/catalog-ui/app/scripts/view-models/component-viewer/activity-log/activity-log-view.html
+++ /dev/null
@@ -1,16 +0,0 @@
-<div ng-repeat="activityDate in activityDateArray " class="w-sdc-component-viewer-right-activity-log" >
- <div class="w-sdc-component-viewer-right-activity-log-date" >{{activityDate | date: 'longDate'}}</div>
- <div ng-repeat="activity in activityLog[activityDate] | orderBy: '-TIMESTAMP'">
- <div class="w-sdc-component-viewer-right-activity-log-time">{{activity.TIMESTAMP.replace(" UTC", '') | stringToDateFilter | date: 'mediumTime':'UTC'}}</div>
- <div class="w-sdc-component-viewer-right-activity-log-content">{{"Action: " + parseAction(activity.ACTION) + " Performed by: " + activity.MODIFIER + " Status: " + activity.STATUS}}</div>
- </div>
- </div>
-</div>
-
-
-
-
-
-
-
-
diff --git a/catalog-ui/app/scripts/view-models/component-viewer/activity-log/activity-log-view.less b/catalog-ui/app/scripts/view-models/component-viewer/activity-log/activity-log-view.less
deleted file mode 100644
index 4a7676b6e2..0000000000
--- a/catalog-ui/app/scripts/view-models/component-viewer/activity-log/activity-log-view.less
+++ /dev/null
@@ -1,18 +0,0 @@
-.w-sdc-component-viewer-right-activity-log{
-
- .w-sdc-component-viewer-right-activity-log-date{
- .backgroundColor.n;
- .font-color.g;
- padding: 4px 11px
- }
- .w-sdc-component-viewer-right-activity-log-time{
- .g_3;
- padding: 12px 0px 0px 11px;
- }
-
- .w-sdc-component-viewer-right-activity-log-content{
- .g_1;
- padding: 0px 0px 12px 11px;
- border-bottom: 1px solid rgba(0, 0, 0, 0.17);
- }
-}
diff --git a/catalog-ui/app/scripts/view-models/component-viewer/component-viewer-view-model.ts b/catalog-ui/app/scripts/view-models/component-viewer/component-viewer-view-model.ts
deleted file mode 100644
index 3ae8ad70fb..0000000000
--- a/catalog-ui/app/scripts/view-models/component-viewer/component-viewer-view-model.ts
+++ /dev/null
@@ -1,211 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../references"/>
-
-module Sdc.ViewModels {
- 'use strict';
-
- interface IComponentViewerViewModelScope extends ng.IScope {
- component: Models.Components.Component;
- additionalInformations: Array<Models.AdditionalInformationModel>;
- activityLog: any;
- activityDateArray: Array<any>; //this is in order to sort the dates
- inputs: Array<any>;
- isLoading: boolean;
- templateUrl: string;
- currentTab:string;
- preVersion:string;
- sdcMenu:Models.IAppMenu;
- versionsList:Array<any>;
- close(): void;
- hasItems(obj:any): boolean;
- onVersionChanged(version:any) : void;
- moveToTab(tab:string):void;
- isSelected(tab:string):boolean;
- getActivityLog(uniqueId:string):void;
- parseAction(action:string):string;
- }
-
- export class ComponentViewerViewModel {
-
- static '$inject' = [
- '$scope',
- '$modalInstance',
- 'component',
- 'Sdc.Services.ActivityLogService',
- 'sdcMenu',
- 'ComponentFactory'
- ];
-
- constructor(private $scope:IComponentViewerViewModelScope,
- private $modalInstance:ng.ui.bootstrap.IModalServiceInstance,
- private component:Models.Components.Component,
- private activityLogService:Services.ActivityLogService,
- private sdcMenu:Models.IAppMenu,
- private ComponentFactory: Utils.ComponentFactory) {
- this.initScope(component);
- }
-
- //creating objects for versions
- private initVersionObject:Function = ():void => {
- this.$scope.versionsList = [];
- for (let version in this.$scope.component.allVersions) {
- this.$scope.versionsList.push({
- versionNumber: version,
- versioning: this.versioning(version),
- versionId: this.$scope.component.allVersions[version]
- });
- }
-
- };
-
- private versioning:Function = (versionNumber:string):string => {
- let version:Array<string> = versionNumber.split('.');
- return '00000000'.slice(version[0].length) + version[0] + '.' + '00000000'.slice(version[1].length) + version[1];
- };
-
- private showComponentInformationView:Function = ():void => {
- if (this.$scope.component.isResource()) {
- this.$scope.templateUrl = '/app/scripts/view-models/component-viewer/properties/resource-properties-view.html';
- } else if(this.$scope.component.isService()) {
- this.$scope.templateUrl = '/app/scripts/view-models/component-viewer/properties/service-properties-view.html';
- } else {
- this.$scope.templateUrl = '/app/scripts/view-models/component-viewer/properties/product-properties-view.html';
- }
- };
-
- private showActivityLogView:Function = ():void => {
- this.$scope.templateUrl = '/app/scripts/view-models/component-viewer/activity-log/activity-log-view.html';
- };
-
- private initComponent = (component:Models.Components.Component):void => {
- this.$scope.component = component;
- this.$scope.additionalInformations = component.getAdditionalInformation();
- this.initVersionObject();
- this.$scope.isLoading = false;
- };
-
- private initScope = (component:Models.Components.Component):void => {
- this.$scope.isLoading = false;
- this.initComponent(component);
- this.$scope.currentTab = 'PROPERTIES';
- this.$scope.preVersion = component.version;
- this.$scope.sdcMenu = this.sdcMenu;
- this.showComponentInformationView();
- //service inputs
- if (component.isService()) {
- let inputs:Array<any> = [];
-
- for (let group in component.componentInstancesProperties) {
- if (component.componentInstancesProperties[group]) {
- component.componentInstancesProperties[group].forEach((property:Models.PropertyModel):void => {
- if (!property.value) {
- property.value = property.defaultValue;
- }
- inputs.push({
- name: property.name,
- value: property.value,
- type: property.type
- });
- });
- }
- }
- this.$scope.inputs = inputs;
- }
-
- this.$scope.hasItems = (obj:any):boolean => {
- return Object.keys(obj).length > 0;
- };
-
- this.$scope.close = ():void => {
- this.$modalInstance.dismiss();
- };
-
- this.$scope.onVersionChanged = (version:any):void => {
- if (version.versionNumber != this.$scope.component.version) {
- this.$scope.isLoading = true;
- this.ComponentFactory.getComponentFromServer(this.component.componentType, version.versionId).then((component: Models.Components.Component):void => {
- this.initComponent(component);
- });
- if (this.$scope.currentTab === 'ACTIVITY_LOG') {
- this.$scope.getActivityLog(version.versionId);
- }
-
- }
- };
-
- this.$scope.getActivityLog = (uniqueId:any):void => {
-
- let onError = (response) => {
- this.$scope.isLoading = false;
- console.info('onFaild', response);
-
- };
- let onSuccess = (response:Array<Models.Activity>) => {
- this.$scope.activityLog = _.groupBy(response, function (activity:Models.Activity) { //group by date only
- let dateTime:Date = new Date(activity.TIMESTAMP.replace(" UTC", '').replace(" ", 'T'));
- // let date:Date = new Date(dateTime.getFullYear(), dateTime.getMonth(), dateTime.getDate());
- return dateTime.getTime();
- });
- /*this is in order to sort the jsonObject by date*/
- this.$scope.activityDateArray = Object.keys(this.$scope.activityLog);
- this.$scope.activityDateArray.sort().reverse();
- this.$scope.isLoading = false;
- };
-
- this.$scope.isLoading = true;
- if (this.$scope.component.isResource()) {
- this.activityLogService.getActivityLogService('resources', uniqueId).then(onSuccess, onError);
- }
- if (this.$scope.component.isService()) {
- this.activityLogService.getActivityLogService('services', uniqueId).then(onSuccess, onError);
- }
-
- };
-
- this.$scope.moveToTab = (tab:string):void => {
- if (tab === this.$scope.currentTab) {
- return;
- } else if (tab === 'PROPERTIES') {
- this.showComponentInformationView();
- this.$scope.preVersion = this.$scope.component.version;
- } else if (tab === 'ACTIVITY_LOG') {
- if (!this.$scope.activityLog || this.$scope.preVersion != this.$scope.component.version) {
- this.$scope.activityLog = this.$scope.getActivityLog(this.$scope.component.uniqueId);
- }
- this.showActivityLogView();
- } else {
- console.error("Tab " + tab + " not found!");
- return;
- }
- this.$scope.currentTab = tab;
- };
-
- this.$scope.isSelected = (tab:string):boolean => {
- return tab === this.$scope.currentTab;
- };
-
- this.$scope.parseAction = (action:string) => {
- return action ? action.split(/(?=[A-Z])/).join(' ') : '';
- };
-
- }
- }
-}
diff --git a/catalog-ui/app/scripts/view-models/component-viewer/component-viewer.html b/catalog-ui/app/scripts/view-models/component-viewer/component-viewer.html
deleted file mode 100644
index 6f244b048e..0000000000
--- a/catalog-ui/app/scripts/view-models/component-viewer/component-viewer.html
+++ /dev/null
@@ -1,55 +0,0 @@
-<div class="w-sdc-resource-viewer">
- <loader data-display="isLoading"></loader>
- <div class="w-sdc-resource-viewer-modal-close sprite x-btn-black" data-ng-click="close()">X</div>
- <div class="w-sdc-resource-viewer-content" data-ng-if="component">
- <div class="w-sdc-resource-viewer-left">
- <h3 class="w-sdc-resource-viewer-left-title clearfix">
- <div class="w-sdc-resource-viewer-left-title-icon i-sdc-form-item-suggested-icon borderElement large {{component.iconSprite}} {{component.icon}}"></div>
- <span class="w-sdc-resource-viewer-left-title-name"
- tooltips tooltip-content="{{component.name | resourceName}}">{{component.name | resourceName}}</span>
- <br/>
- <span class="w-sdc-resource-viewer-left-title-version">v{{component.version}}</span>
- </h3>
- <p class="w-sdc-resource-viewer-left-title-uuid">
- UUID: {{component.uuid}}
- </p>
- <div class="w-sdc-resource-viewer-leftbar-section">
- <div class="w-sdc-resource-viewer-leftbar-section-title">Version History</div>
- <perfect-scrollbar class="w-sdc-resource-viewer-version">
- <div class="i-sdc-resource-viewer-version-container">
- <div data-ng-repeat="version in versionsList | orderBy: '-versioning'">
- <span class="i-sdc-resource-viewer-version-item" data-ng-class="{'active': version.versionNumber == component.version}" data-ng-click="onVersionChanged(version)">{{ version.versionNumber }}</span>
- </div>
- </div>
- </perfect-scrollbar>
- </div>
-
- <div class="w-sdc-resource-viewer-leftbar-section">
- <div class="w-sdc-resource-viewer-leftbar-section-title">Composition</div>
- <perfect-scrollbar class="w-sdc-resource-viewer-leftbar-section-structure" ng-show="component.isComplex()">
- <structure-tree component="component"></structure-tree>
- </perfect-scrollbar>
- </div>
- </div>
-
- <div class="w-sdc-resource-viewer-right">
- <button class="w-sdc-resource-viewer-right-tab"
- data-ng-class="{'selected': isSelected('PROPERTIES')}"
- data-ng-click="moveToTab('PROPERTIES')"
- translate="ENTITY_VIEWER_PROPERTIES_TAB">
- </button>
-
- <button class="w-sdc-resource-viewer-right-tab"
- data-ng-if="component.isResource() || component.isService()"
- data-ng-class="{'selected': isSelected('ACTIVITY_LOG')}"
- data-ng-click="moveToTab('ACTIVITY_LOG')"
- translate="ENTITY_VIEWER_ACTIVITY_LOG_TAB">
- </button>
-
- <perfect-scrollbar include-padding="true" class="w-sdc-resource-viewer-right-content">
- <ng-include src="templateUrl" ng-if="true"></ng-include>
- </perfect-scrollbar>
- <div style="clear:both;"></div>
- </div>
- </div>
-</div>
diff --git a/catalog-ui/app/scripts/view-models/component-viewer/component-viewer.less b/catalog-ui/app/scripts/view-models/component-viewer/component-viewer.less
deleted file mode 100644
index 2fe5676d62..0000000000
--- a/catalog-ui/app/scripts/view-models/component-viewer/component-viewer.less
+++ /dev/null
@@ -1,148 +0,0 @@
-html .modal-component-viewer{
- width: 1084px;
-}
-
-.w-sdc-resource-viewer {
- .b_7;
- .w-sdc-resource-viewer-modal-close{
- z-index: 2;
- text-indent: -100px;
- overflow: hidden;
- top: 19px;
- }
- .w-sdc-resource-viewer-content {
- position: relative;
- overflow: hidden;
-
- .w-sdc-resource-viewer-left {
-
- .bg_j;
- display: table-cell;
- width: 282px;
-
- .w-sdc-resource-viewer-left-title {
- margin: 0;
- display: block;
- height: 100px;
- padding: 20px 0;
- }
-
- .w-sdc-resource-viewer-left-title-icon {
- margin: 0 15px;
- vertical-align: middle;
- float: left;
- }
-
- .w-sdc-resource-viewer-left-title-name {
- .g_7;
- max-width: 160px;
- overflow: hidden;
- display: inline-block;
- text-overflow: ellipsis;
- vertical-align: middle;
- line-height: 23px;
- padding-top: 10px;
- font-weight: bold;
- white-space: nowrap;
- }
-
- .w-sdc-resource-viewer-left-title-version {
- .g_13;
- float: left;
- }
-
- .w-sdc-resource-viewer-left-title-uuid {
- .g_14;
- text-align: center;
- border-top: 1px solid rgba(120, 136, 148, 0.26);
- width: 95%;
- margin: auto;
- padding: 7px 0;
- }
-
- .w-sdc-resource-viewer-leftbar-section {
- font-family: omnes-medium, sans-serif;
- }
-
- .w-sdc-resource-viewer-leftbar-section-title {
- .bg_o;
- color: #fff;
- font-size: 14px;
- padding: 12px 20px;
- text-transform: uppercase;
- }
-
- .w-sdc-resource-viewer-leftbar-section-structure{
- .perfect-scrollbar;
- max-height: 525px;
- }
- .w-sdc-resource-viewer-version {
- font-weight: bold;
- .perfect-scrollbar;
- }
-
- .i-sdc-resource-viewer-version-container {
- padding: 13px 0px 13px 13px;
- max-height: 218px;
-
- .i-sdc-resource-viewer-version-item {
-
- &.active {
- .a_7;
- }
- &:hover {
- cursor: pointer;
- }
- }
-
- }
- }
-
- .w-sdc-resource-viewer-right {
- .bg_c;
- display: table-cell;
- vertical-align: top;
- padding: 0; // for the scroller to be on all width
- width: 716px;
- padding: 25px 0px 0px 35px;
-
- .w-sdc-resource-viewer-right-content {
- padding: 0 52px 0 0px;
- margin-bottom: 25px;
- height: 700px;
- overflow: hidden;
- position: relative;
-
- }
-
- .w-sdc-resource-viewer-right-tab {
- .b_6;
-
- .hand;
- background-color: transparent;
- position: relative;
- font-weight: 500;
- line-height: 30px;
- border: none;
- border-bottom: solid 1px @color_c;
- vertical-align: middle;
- padding: 0px 30px 20px 0px;
-
-
- &:focus,
- &:active {
- outline: none;
-
- }
- &.selected {
- outline: none;
- font-weight: 700;
- .font-color.a;
- }
- }
-
-
- }
-
- }
-}
diff --git a/catalog-ui/app/scripts/view-models/component-viewer/properties/product-properties-view.html b/catalog-ui/app/scripts/view-models/component-viewer/properties/product-properties-view.html
deleted file mode 100644
index 8aeda603f8..0000000000
--- a/catalog-ui/app/scripts/view-models/component-viewer/properties/product-properties-view.html
+++ /dev/null
@@ -1,76 +0,0 @@
-<div class="w-sdc-component-viewer-right-properties">
-
- <h4 class="w-sdc-resource-viewer-right-title">General Information</h4>
- <div class="w-sdc-resource-viewer-right-content-section">
- <div class='sdc-resource-viewer-sidebar-section-content-column-1'>
- <div class="sdc-resource-viewer-sidebar-section-content-item">
- <span class="sdc-resource-viewer-sidebar-section-content-item-label" translate="GENERAL_LABEL_TYPE"></span>
- <span class="sdc-resource-viewer-sidebar-section-content-item-value" translate="GENERAL_LABEL_PRODUCT"></span>
- </div>
- <div class="sdc-resource-viewer-sidebar-section-content-item">
- <span class="sdc-resource-viewer-sidebar-section-content-item-label" translate="GENERAL_LABEL_VERSION"></span>
- <span class="sdc-resource-viewer-sidebar-section-content-item-value" data-ng-bind="component.version"></span>
- </div>
- <div class="sdc-resource-viewer-sidebar-section-content-item">
- <span class="sdc-resource-viewer-sidebar-section-content-item-label" translate="GENERAL_LABEL_CATEGORY"></span>
- <span class="sdc-resource-viewer-sidebar-section-content-item-value" tooltips tooltip-content="{{component.category}}" data-ng-bind="component.category"></span>
- </div>
- <div class="sdc-resource-viewer-sidebar-section-content-item">
- <span class="sdc-resource-viewer-sidebar-section-content-item-label" translate="GENERAL_LABEL_CREATION_DATE"></span>
- <span class="sdc-resource-viewer-sidebar-section-content-item-value" data-ng-bind="component.creationDate | date: 'MM/dd/yyyy'"></span>
- </div>
- <div class="sdc-resource-viewer-sidebar-section-content-item">
- <span class="sdc-resource-viewer-sidebar-section-content-item-label" translate="GENERAL_LABEL_AUTHOR"></span>
- <span class="sdc-resource-viewer-sidebar-section-content-item-value" data-ng-bind="component.creatorFullName"></span>
- </div>
- <div class="sdc-resource-viewer-sidebar-section-content-item">
- <span class="sdc-resource-viewer-sidebar-section-content-item-label" translate="GENERAL_LABEL_CONTACT_ID"></span>
- <span class="sdc-resource-viewer-sidebar-section-content-item-value" data-ng-bind="component.contacts[0]"></span>
- </div>
- <div class="sdc-resource-viewer-sidebar-section-content-item">
- <span class="sdc-resource-viewer-sidebar-section-content-item-label" translate="GENERAL_LABEL_PROJECT_CODE"></span>
- <span class="sdc-resource-viewer-sidebar-section-content-item-value" data-ng-bind="component.projectCode"></span>
- </div>
- <div class="sdc-resource-viewer-sidebar-section-content-item">
- <span class="sdc-resource-viewer-sidebar-section-content-item-label">Life Cycle Status:</span>
- <span class="sdc-resource-viewer-sidebar-section-content-item-value">
- {{sdcMenu.LifeCycleStatuses[component.lifecycleState].text}}
- </span>
- </div>
- <div class="sdc-resource-viewer-sidebar-section-content-item">
- <span class="sdc-resource-viewer-sidebar-section-content-item-label">Distribution Status:</span>
- <span class="sdc-resource-viewer-sidebar-section-content-item-value">
- {{sdcMenu.DistributionStatuses[component.distributionStatus].text}}
- </span>
- </div>
- </div>
- <div class='sdc-resource-viewer-sidebar-section-content-column-2'>
- <div class="sdc-resource-viewer-sidebar-section-content-item description">
- <span class="sdc-resource-viewer-sidebar-section-content-item-label" translate="GENERAL_LABEL_DESCRIPTION"></span>
- <span class="sdc-resource-viewer-sidebar-section-content-item-value" data-ng-bind="component.description"></span>
- </div>
- <div class="sdc-resource-viewer-sidebar-section-content-item" >
- <span class="sdc-resource-viewer-sidebar-section-content-item-label" translate="GENERAL_LABEL_TAGS"></span>
- <span tooltips tooltip-content="{{component.tags.join(', ')}}" class="sdc-resource-viewer-sidebar-section-content-tags" data-ng-repeat="(tag, tagName) in component.tags">
- {{tagName}}{{$last ? '' : ','}}
- </span>
- </div>
- </div>
- </div>
- <h4 class="w-sdc-resource-viewer-right-title">Additional Information</h4>
-
- <div class="sdc-properties-container w-sdc-resource-viewer-right-content-section">
- <table class="w-sdc-resource-viewer-right-table" data-ng-show="additionalInformations.length">
- <thead class="w-sdc-resource-viewer-right-table-head">
- <th class="w-sdc-resource-viewer-right-table-head-cell cols-2">Key</th>
- <th class="w-sdc-resource-viewer-right-table-head-cell cols-2">Value</th>
- </thead>
- <tbody>
- <tr data-ng-repeat="additionalInformation in additionalInformations">
- <td><span class="ellipsis-cols2" tooltips tooltip-content="{{additionalInformation.key}}">{{additionalInformation.key}}</span></td>
- <td><span class="ellipsis-cols2" tooltips tooltip-content="{{additionalInformation.value}}">{{additionalInformation.value}}</span></td>
- </tr>
- </tbody>
- </table>
- </div>
-</div>
diff --git a/catalog-ui/app/scripts/view-models/component-viewer/properties/properties-view.less b/catalog-ui/app/scripts/view-models/component-viewer/properties/properties-view.less
deleted file mode 100644
index c0beed338f..0000000000
--- a/catalog-ui/app/scripts/view-models/component-viewer/properties/properties-view.less
+++ /dev/null
@@ -1,128 +0,0 @@
-.w-sdc-component-viewer-right-properties {
- .w-sdc-resource-viewer-tabs {
- height: 42px;
- }
-
- .w-sdc-resource-viewer-right-content-section {
- margin: 0 0 20px 16px;
- }
-
- .sdc-resource-viewer-sidebar-section-content-column-1,
- .sdc-resource-viewer-sidebar-section-content-column-2 {
- display: table-cell;
- width: 50%;
- }
- .sdc-resource-viewer-sidebar-section-content-item {
- .b_7;
- margin-bottom: 5px;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- width: 305px;
- }
- .sdc-resource-viewer-sidebar-section-content-item-label {
- .bold;
- .g_9;
- }
- .w-sdc-resource-viewer-right .sdc-resource-viewer-sidebar-section-content-column-1 {
- .sdc-resource-viewer-sidebar-section-content-item {
- width: 390px;
- }
- }
- .sdc-resource-viewer-sidebar-section-content-item.description {
- margin: 0;
-
- .sdc-resource-viewer-sidebar-section-content-item-value {
- word-wrap: break-word;
- white-space: normal;
- display: block;
-
- }
- .sdc-resource-viewer-sidebar-section-content-tags {
- word-wrap: break-word;
- white-space: pre-wrap;
- display: inline-block;
- max-width: 167px;
-
- }
- }
-
- .w-sdc-resource-viewer-right-title {
- .g_1;
- .bg_n;
- padding: 7px 15px;
- margin: 0px 0 25px;
- font-weight: bold;
- }
-
- .w-sdc-resource-viewer-right-table-head-cell {
- .g_9;
- text-align: left;
- }
-
- .cols-1 {
- width: 100%;
- }
- .cols-2 {
- width: 50%;
- }
- .cols-3 {
- width: 33%;
- }
-
- .sdc-properties-container table tbody td.label {
- .bold;
- }
-
- .w-sdc-designer-sidebar-section-content,
- .w-sdc-resource-viewer-right-table {
- display: table;
- width: 100%;
- .b_9;
- word-break: break-all;
-
- tbody td {
- padding: 4px 20px 0 0;
-
- .ellipsis-directive-more-less {
- display: none;
- }
-
- .ellipsis-cols2 {
- .sdc-ellipsis;
- max-width: 340px;
- }
- .ellipsis-cols3 {
- .sdc-ellipsis;
- max-width: 200px;
- }
- }
-
- }
-
- .i-sdc-designer-sidebar-section-content-column-1 {
- display: table-cell;
- width: 50%;
- }
-
- .i-sdc-designer-sidebar-section-content-column-2 {
- display: table-cell;
- width: 50%;
- }
-
- .i-sdc-resource-viewer-artifacts-item-action,
- .sdc-information-artifacts-icon {
- .sprite;
- display: inline-block;
- width: 20px;
- height: 20px;
- cursor: pointer;
- vertical-align: middle;
- &.download {
- .sprite.e-sdc-small-download;
- }
- &.preview {
- .e-sdc-small-icon-eye;
- }
- }
-}
diff --git a/catalog-ui/app/scripts/view-models/component-viewer/properties/resource-properties-view.html b/catalog-ui/app/scripts/view-models/component-viewer/properties/resource-properties-view.html
deleted file mode 100644
index c02e7aba7e..0000000000
--- a/catalog-ui/app/scripts/view-models/component-viewer/properties/resource-properties-view.html
+++ /dev/null
@@ -1,169 +0,0 @@
-<div class="w-sdc-component-viewer-right-properties">
-
- <h4 class="w-sdc-resource-viewer-right-title">General Information</h4>
- <div class="w-sdc-resource-viewer-right-content-section">
- <div class='sdc-resource-viewer-sidebar-section-content-column-1'>
- <div class="sdc-resource-viewer-sidebar-section-content-item">
- <span class="sdc-resource-viewer-sidebar-section-content-item-label" translate="GENERAL_LABEL_TYPE"></span>
- <span class="sdc-resource-viewer-sidebar-section-content-item-value" >Resource</span>
- </div>
- <div class="sdc-resource-viewer-sidebar-section-content-item">
- <span class="sdc-resource-viewer-sidebar-section-content-item-label" translate="GENERAL_LABEL_RESOURCE_TYPE"></span>
- <span class="sdc-resource-viewer-sidebar-section-content-item-value" data-ng-bind="component.resourceType | resourceTypeName"></span>
- </div>
- <div class="sdc-resource-viewer-sidebar-section-content-item">
- <span class="sdc-resource-viewer-sidebar-section-content-item-label" translate="GENERAL_LABEL_VERSION"></span>
- <span class="sdc-resource-viewer-sidebar-section-content-item-value" data-ng-bind="component.version"></span>
- </div>
- <div class="sdc-resource-viewer-sidebar-section-content-item">
- <span class="sdc-resource-viewer-sidebar-section-content-item-label" translate="GENERAL_LABEL_CATEGORY"></span>
- <span class="sdc-resource-viewer-sidebar-section-content-item-value" tooltips tooltip-content="{{component.categories[0].name}}" data-ng-bind="component.categories[0].name"></span>
- </div>
- <div class="sdc-resource-viewer-sidebar-section-content-item">
- <span class="sdc-resource-viewer-sidebar-section-content-item-label" translate="GENERAL_LABEL_SUB_CATEGORY"></span>
- <span class="sdc-resource-viewer-sidebar-section-content-item-value" tooltips tooltip-content="{{component.categories[0].subcategories[0].name}}" data-ng-bind="component.categories[0].subcategories[0].name"></span>
- </div>
- <div class="sdc-resource-viewer-sidebar-section-content-item">
- <span class="sdc-resource-viewer-sidebar-section-content-item-label" translate="GENERAL_LABEL_CREATION_DATE"></span>
- <span class="sdc-resource-viewer-sidebar-section-content-item-value" data-ng-bind="component.creationDate | date: 'MM/dd/yyyy'"></span>
- </div>
- <div class="sdc-resource-viewer-sidebar-section-content-item">
- <span class="sdc-resource-viewer-sidebar-section-content-item-label" translate="GENERAL_LABEL_AUTHOR"></span>
- <span class="sdc-resource-viewer-sidebar-section-content-item-value" data-ng-bind="component.creatorFullName"></span>
- </div>
- <div class="sdc-resource-viewer-sidebar-section-content-item">
- <span class="sdc-resource-viewer-sidebar-section-content-item-label" translate="GENERAL_LABEL_VENDOR_NAME"></span>
- <span class="sdc-resource-viewer-sidebar-section-content-item-value" data-ng-bind="component.vendorName"></span>
- </div>
- <div class="sdc-resource-viewer-sidebar-section-content-item">
- <span class="sdc-resource-viewer-sidebar-section-content-item-label" translate="GENERAL_LABEL_VENDOR_RELEASE"></span>
- <span class="sdc-resource-viewer-sidebar-section-content-item-value" data-ng-bind="component.vendorRelease"></span>
- </div>
- <div class="sdc-resource-viewer-sidebar-section-content-item">
- <span class="sdc-resource-viewer-sidebar-section-content-item-label" translate="GENERAL_LABEL_CONTACT_ID"></span>
- <span class="sdc-resource-viewer-sidebar-section-content-item-value" data-ng-bind="component.contactId"></span>
- </div>
- <div class="sdc-resource-viewer-sidebar-section-content-item">
- <span class="sdc-resource-viewer-sidebar-section-content-item-label">Life Cycle Status:</span>
- <span class="sdc-resource-viewer-sidebar-section-content-item-value">
- {{sdcMenu.LifeCycleStatuses[component.lifecycleState].text}}
- </span>
- </div>
- <div class="sdc-resource-viewer-sidebar-section-content-item">
- <span class="sdc-resource-viewer-sidebar-section-content-item-label">System Name:</span>
- <span class="sdc-resource-viewer-sidebar-section-content-item-value" tooltips tooltip-content="{{component.systemName}}" data-ng-bind="component.systemName"></span>
- </div>
- <div class="sdc-resource-viewer-sidebar-section-content-item">
- <span class="sdc-resource-viewer-sidebar-section-content-item-label" translate="GENERAL_LABEL_LICENSE_TYPE"></span>
- <span class="sdc-resource-viewer-sidebar-section-content-item-value" data-ng-bind="component.licenseType"></span>
- </div>
- </div>
- <div class='sdc-resource-viewer-sidebar-section-content-column-2'>
- <div class="sdc-resource-viewer-sidebar-section-content-item description">
- <span class="sdc-resource-viewer-sidebar-section-content-item-label" translate="GENERAL_LABEL_DESCRIPTION"></span>
- <span class="sdc-resource-viewer-sidebar-section-content-item-value" data-ng-bind="component.description"></span>
- </div>
- <div class="sdc-resource-viewer-sidebar-section-content-item">
- <span class="sdc-resource-viewer-sidebar-section-content-item-label" translate="GENERAL_LABEL_TAGS"></span>
- <span class="sdc-resource-viewer-sidebar-section-content-tags" data-ng-repeat="(tag, tagName) in component.tags" tooltips tooltip-content="{{component.tags.join(', ')}}">{{tagName}}{{$last ? '' : ','}}</span>
- </div>
- </div>
- </div>
-
- <h4 class="w-sdc-resource-viewer-right-title">Additional Information</h4>
-
- <div class="sdc-properties-container w-sdc-resource-viewer-right-content-section">
- <table class="w-sdc-resource-viewer-right-table" data-ng-show="additionalInformations.length">
- <thead class="w-sdc-resource-viewer-right-table-head">
- <th class="w-sdc-resource-viewer-right-table-head-cell cols-2">Key</th>
- <th class="w-sdc-resource-viewer-right-table-head-cell cols-2">Value</th>
- </thead>
- <tbody>
- <tr data-ng-repeat="additionalInformation in additionalInformations">
- <td><span class="ellipsis-cols2" tooltips tooltip-content="{{additionalInformation.key}}">{{additionalInformation.key}}</span></td>
- <td><span class="ellipsis-cols2" tooltips tooltip-content="{{additionalInformation.value}}">{{additionalInformation.value}}</span></td>
- </tr>
- </tbody>
- </table>
- </div>
-
- <h4 class="w-sdc-resource-viewer-right-title">Properties</h4>
- <div class="sdc-properties-container w-sdc-resource-viewer-right-content-section">
- <table class="w-sdc-resource-viewer-right-table" data-ng-show="component.properties.length">
- <thead class="w-sdc-resource-viewer-right-table-head">
- <th class="w-sdc-resource-viewer-right-table-head-cell cols-2">Name</th>
- <th class="w-sdc-resource-viewer-right-table-head-cell cols-3">Type (Constraints)</th>
- <th class="w-sdc-resource-viewer-right-table-head-cell cols-3">Default Value</th>
- </thead>
- <tbody>
- <tr data-ng-repeat="property in component.properties">
- <td><span class="ellipsis-cols2" data-tests-id="{{property.name}}" tooltips tooltip-content="{{property.name}}">{{property.name}}</span></td>
- <td><span data-tests-id="{{property.type}}">{{property.type}}</span></td>
- <td><span class="ellipsis-cols3" data-tests-id="{{property.defaultValue}}" tooltips tooltip-content="{{property.defaultValue}}">{{property.defaultValue}}</span></td>
- </tr>
- </tbody>
- </table>
- </div>
-
- <h4 class="w-sdc-resource-viewer-right-title">Requirements</h4>
- <div class="sdc-requirements-container w-sdc-resource-viewer-right-content-section" >
- <table class="w-sdc-resource-viewer-right-table" data-ng-show="hasItems(component.requirements)">
- <thead class="w-sdc-resource-viewer-right-table-head">
- <th class="w-sdc-resource-viewer-right-table-head-cell cols-1">Type</th>
- </thead>
- <tbody>
- <tr data-ng-repeat="(key, value) in component.requirements">
- <td>{{value[0].name}}</td>
- </tr>
- </tbody>
- </table>
- </div>
-
-
- <h4 class="w-sdc-resource-viewer-right-title">Deployment Artifacts</h4>
-
- <div class="sdc-information-container w-sdc-resource-viewer-right-content-section" >
- <table class="w-sdc-resource-viewer-right-table" data-ng-show="hasItems(component.deploymentArtifacts)">
- <thead class="w-sdc-resource-viewer-right-table-head">
- <th class="w-sdc-resource-viewer-right-table-head-cell cols-2">Name</th>
- <th class="w-sdc-resource-viewer-right-table-head-cell cols-3">File</th>
- <th class="w-sdc-resource-viewer-right-table-head-cell cols-3">Version</th>
- <th class="w-sdc-resource-viewer-right-table-head-cell cols-3"></th>
- </thead>
- <tbody>
- <tr data-ng-repeat="(artifactLogicName, artifact) in component.deploymentArtifacts">
- <td><span class="ellipsis-cols2" data-tests-id="{{artifact.artifactDisplayName}}" tooltips tooltip-content="{{artifact.artifactDisplayName}}">{{artifact.artifactDisplayName}}</span></td>
- <td><span class="ellipsis-cols3" data-tests-id="{{artifact.artifactName}}" tooltips tooltip-content="{{artifact.artifactName}}">{{artifact.artifactName}}</span></td>
- <td><span class="ellipsis-cols3" data-tests-id="{{artifact.artifactVersion}}" tooltips tooltip-content="{{artifact.artifactVersion}}" data-ng-if="artifact.esId">{{artifact.artifactVersion}}</span></td>
- <td class="cols-3">
- <download-artifact class="sdc-information-artifacts-icon download" data-ng-if="artifact.artifactName" component="component" artifact="artifact"></download-artifact>
- <!--span class="sdc-information-artifacts-icon preview"></span-->
- </td>
- </tr>
- </tbody>
- </table>
- </div>
-
- <h4 class="w-sdc-resource-viewer-right-title">Information Artifacts</h4>
- <div class="sdc-information-container w-sdc-resource-viewer-right-content-section" >
- <table class="w-sdc-resource-viewer-right-table" data-ng-show="hasItems(component.artifacts)">
- <thead class="w-sdc-resource-viewer-right-table-head">
- <th class="w-sdc-resource-viewer-right-table-head-cell cols-2">Name</th>
- <th class="w-sdc-resource-viewer-right-table-head-cell cols-3">File</th>
- <th class="w-sdc-resource-viewer-right-table-head-cell cols-3">Version</th>
- <th class="w-sdc-resource-viewer-right-table-head-cell cols-3"></th>
- </thead>
- <tbody>
- <tr data-ng-repeat="(artifactLogicName, artifact) in component.artifacts">
- <td><span class="ellipsis-cols2" data-tests-id="{{artifact.artifactDisplayName}}" tooltips tooltip-content="{{artifact.artifactDisplayName}}">{{artifact.artifactDisplayName}}</span></td>
- <td><span class="ellipsis-cols3" data-tests-id="{{artifact.artifactName}}" tooltips tooltip-content="{{artifact.artifactName}}">{{artifact.artifactName}}</span></td>
- <td><span class="ellipsis-cols3" data-tests-id="{{artifact.artifactVersion}}" tooltips tooltip-content="{{artifact.artifactVersion}}" data-ng-if="artifact.esId">{{artifact.artifactVersion}}</span></td>
- <td class="cols-3">
- <download-artifact class="sdc-information-artifacts-icon download" data-ng-if="artifact.artifactName" component="component" artifact="artifact"></download-artifact>
- <!--span class="sdc-information-artifacts-icon preview"></span-->
- </td>
- </tr>
- </tbody>
- </table>
- </div>
-</div>
diff --git a/catalog-ui/app/scripts/view-models/component-viewer/properties/service-properties-view.html b/catalog-ui/app/scripts/view-models/component-viewer/properties/service-properties-view.html
deleted file mode 100644
index 01f872c13c..0000000000
--- a/catalog-ui/app/scripts/view-models/component-viewer/properties/service-properties-view.html
+++ /dev/null
@@ -1,167 +0,0 @@
-<div class="w-sdc-component-viewer-right-properties">
-
- <h4 class="w-sdc-resource-viewer-right-title">General Information</h4>
- <div class="w-sdc-resource-viewer-right-content-section">
- <div class='sdc-resource-viewer-sidebar-section-content-column-1'>
- <div class="sdc-resource-viewer-sidebar-section-content-item">
- <span class="sdc-resource-viewer-sidebar-section-content-item-label" translate="GENERAL_LABEL_TYPE"></span>
- <span class="sdc-resource-viewer-sidebar-section-content-item-value" translate="GENERAL_LABEL_SERVICE"></span>
- </div>
- <div class="sdc-resource-viewer-sidebar-section-content-item">
- <span class="sdc-resource-viewer-sidebar-section-content-item-label" translate="GENERAL_LABEL_VERSION"></span>
- <span class="sdc-resource-viewer-sidebar-section-content-item-value" data-ng-bind="component.version"></span>
- </div>
- <div class="sdc-resource-viewer-sidebar-section-content-item">
- <span class="sdc-resource-viewer-sidebar-section-content-item-label" translate="GENERAL_LABEL_CATEGORY"></span>
- <span class="sdc-resource-viewer-sidebar-section-content-item-value" tooltips tooltip-content="{{component.categories[0].name}}" data-ng-bind="component.categories[0].name"></span>
- </div>
- <div class="sdc-resource-viewer-sidebar-section-content-item">
- <span class="sdc-resource-viewer-sidebar-section-content-item-label" translate="GENERAL_LABEL_CREATION_DATE"></span>
- <span class="sdc-resource-viewer-sidebar-section-content-item-value" data-ng-bind="component.creationDate | date: 'MM/dd/yyyy'"></span>
- </div>
- <div class="sdc-resource-viewer-sidebar-section-content-item">
- <span class="sdc-resource-viewer-sidebar-section-content-item-label" translate="GENERAL_LABEL_AUTHOR"></span>
- <span class="sdc-resource-viewer-sidebar-section-content-item-value" data-ng-bind="component.creatorFullName"></span>
- </div>
- <div class="sdc-resource-viewer-sidebar-section-content-item">
- <span class="sdc-resource-viewer-sidebar-section-content-item-label" translate="GENERAL_LABEL_CONTACT_ID"></span>
- <span class="sdc-resource-viewer-sidebar-section-content-item-value" data-ng-bind="component.contactId"></span>
- </div>
- <div class="sdc-resource-viewer-sidebar-section-content-item">
- <span class="sdc-resource-viewer-sidebar-section-content-item-label" translate="GENERAL_LABEL_PROJECT_CODE"></span>
- <span class="sdc-resource-viewer-sidebar-section-content-item-value" data-ng-bind="component.projectCode"></span>
- </div>
- <div class="sdc-resource-viewer-sidebar-section-content-item">
- <span class="sdc-resource-viewer-sidebar-section-content-item-label">Life Cycle Status:</span>
- <span class="sdc-resource-viewer-sidebar-section-content-item-value"> {{sdcMenu.LifeCycleStatuses[component.lifecycleState].text}}</span>
- </div>
- <div class="sdc-resource-viewer-sidebar-section-content-item">
- <span class="sdc-resource-viewer-sidebar-section-content-item-label">Distribution Status:</span>
- <span class="sdc-resource-viewer-sidebar-section-content-item-value">{{sdcMenu.DistributionStatuses[component.distributionStatus].text}}</span>
- </div>
-
- <div class="sdc-resource-viewer-sidebar-section-content-item">
- <span class="sdc-resource-viewer-sidebar-section-content-item-label">System Name:</span>
- <span class="sdc-resource-viewer-sidebar-section-content-item-value" tooltips tooltip-content="{{component.systemName}}" data-ng-bind="component.systemName"></span>
- </div>
- </div>
- <div class='sdc-resource-viewer-sidebar-section-content-column-2'>
- <div class="sdc-resource-viewer-sidebar-section-content-item description">
- <span class="sdc-resource-viewer-sidebar-section-content-item-label" translate="GENERAL_LABEL_DESCRIPTION"></span>
- <span class="sdc-resource-viewer-sidebar-section-content-item-value" data-ng-bind="component.description"></span>
- </div>
- <div class="sdc-resource-viewer-sidebar-section-content-item" >
- <span class="sdc-resource-viewer-sidebar-section-content-item-label" translate="GENERAL_LABEL_TAGS"></span>
- <span tooltips tooltip-content="{{component.tags.join(', ')}}" class="sdc-resource-viewer-sidebar-section-content-tags" data-ng-repeat="(tag, tagName) in component.tags">{{tagName}}{{$last ? '' : ','}}</span>
- </div>
- </div>
- </div>
- <h4 class="w-sdc-resource-viewer-right-title">Additional Information</h4>
-
- <div class="sdc-properties-container w-sdc-resource-viewer-right-content-section">
- <table class="w-sdc-resource-viewer-right-table" data-ng-show="additionalInformations.length">
- <thead class="w-sdc-resource-viewer-right-table-head">
- <th class="w-sdc-resource-viewer-right-table-head-cell cols-2">Key</th>
- <th class="w-sdc-resource-viewer-right-table-head-cell cols-2">Value</th>
- </thead>
- <tbody>
- <tr data-ng-repeat="additionalInformation in additionalInformations">
- <td><span class="ellipsis-cols2" tooltips tooltip-content="{{additionalInformation.key}}">{{additionalInformation.key}}</span></td>
- <td><span class="ellipsis-cols2" tooltips tooltip-content="{{additionalInformation.value}}">{{additionalInformation.value}}</span></td>
- </tr>
- </tbody>
- </table>
- </div>
-
- <h4 class="w-sdc-resource-viewer-right-title">Inputs</h4>
-
- <div class="sdc-properties-container w-sdc-resource-viewer-right-content-section">
- <table class="w-sdc-resource-viewer-right-table" data-ng-show="inputs.length">
- <thead class="w-sdc-resource-viewer-right-table-head">
- <th class="w-sdc-resource-viewer-right-table-head-cell cols-2">Name</th>
- <th class="w-sdc-resource-viewer-right-table-head-cell cols-3">Type (Constraints)</th>
- <th class="w-sdc-resource-viewer-right-table-head-cell cols-3">Default Value</th>
- </thead>
- <tbody>
- <tr data-ng-repeat="input in inputs">
- <td><span class="ellipsis-cols2" data-tests-id="{{input.name}}" tooltips tooltip-content="{{input.name}}">{{input.name}}</span></td>
- <td>{{input.type}}</td>
- <td><span class="ellipsis-cols3" data-tests-id="{{input.value}}" tooltips tooltip-content="{{input.value}}">{{input.value}}</span></td>
- </tr>
- </tbody>
- </table>
- </div>
-
- <h4 class="w-sdc-resource-viewer-right-title">API Artifacts</h4>
-
- <div class="sdc-requirements-container w-sdc-resource-viewer-right-content-section">
- <table class="w-sdc-resource-viewer-right-table" data-ng-show="hasItems(component.serviceApiArtifacts)">
- <thead class="w-sdc-resource-viewer-right-table-head">
- <th class="w-sdc-resource-viewer-right-table-head-cell cols-2">Name</th>
- <th class="w-sdc-resource-viewer-right-table-head-cell cols-3">File</th>
- <th class="w-sdc-resource-viewer-right-table-head-cell cols-3">Version</th>
- <th class="w-sdc-resource-viewer-right-table-head-cell cols-3"></th>
- </thead>
- <tbody>
- <tr data-ng-repeat="(artifactLogicName, artifact) in component.serviceApiArtifacts">
- <td><span class="ellipsis-cols2" data-tests-id="{{artifact.artifactDisplayName}}" tooltips tooltip-content="{{artifact.artifactDisplayName}}">{{artifact.artifactDisplayName}}</span></td>
- <td><span class="ellipsis-cols3" data-tests-id="{{artifact.artifactName}}" tooltips tooltip-content="{{artifact.artifactName}}">{{artifact.artifactName}}</span></td>
- <td><span class="ellipsis-cols3" data-tests-id="{{artifact.artifactVersion}}" tooltips tooltip-content="{{artifact.artifactVersion}}" data-ng-if="artifact.esId">{{artifact.artifactVersion}}</span></td>
- <td class="cols-3">
- <download-artifact class="sdc-information-artifacts-icon download" data-ng-if="artifact.artifactName" component="component" artifact="artifact"></download-artifact>
- <!--span class="sdc-information-artifacts-icon preview"></span-->
- </td>
- </tr>
- </tbody>
- </table>
- </div>
-
- <h4 class="w-sdc-resource-viewer-right-title">Deployment Artifacts</h4>
-
- <div class="sdc-information-container w-sdc-resource-viewer-right-content-section">
- <table class="w-sdc-resource-viewer-right-table" data-ng-show="hasItems(component.deploymentArtifacts)">
- <thead class="w-sdc-resource-viewer-right-table-head">
- <th class="w-sdc-resource-viewer-right-table-head-cell cols-2">Name</th>
- <th class="w-sdc-resource-viewer-right-table-head-cell cols-3">File</th>
- <th class="w-sdc-resource-viewer-right-table-head-cell cols-3">Version</th>
- <th class="w-sdc-resource-viewer-right-table-head-cell cols-3"></th>
- </thead>
- <tbody>
- <tr data-ng-repeat="(artifactLogicName, artifact) in component.deploymentArtifacts">
- <td><span class="ellipsis-cols2" data-tests-id="{{artifact.artifactDisplayName}}" tooltips tooltip-content="{{artifact.artifactDisplayName}}">{{artifact.artifactDisplayName}}</span></td>
- <td><span class="ellipsis-cols3" data-tests-id="{{artifact.artifactName}}" tooltips tooltip-content="{{artifact.artifactName}}">{{artifact.artifactName}}</span></td>
- <td><span class="ellipsis-cols3" data-tests-id="{{artifact.artifactVersion}}" tooltips tooltip-content="{{artifact.artifactVersion}}" data-ng-if="artifact.esId">{{artifact.artifactVersion}}</span></td>
- <td class="cols-3">
- <download-artifact class="sdc-information-artifacts-icon download" data-ng-if="artifact.artifactName" component="component" artifact="artifact"></download-artifact>
- <!--span class="sdc-information-artifacts-icon preview"></span-->
- </td>
- </tr>
- </tbody>
- </table>
- </div>
-
-
- <h4 class="w-sdc-resource-viewer-right-title">Information Artifacts</h4>
-
- <div class="sdc-information-container w-sdc-resource-viewer-right-content-section">
- <table class="w-sdc-resource-viewer-right-table" data-ng-show="hasItems(component.artifacts)">
- <thead class="w-sdc-resource-viewer-right-table-head">
- <th class="w-sdc-resource-viewer-right-table-head-cell cols-2">Name</th>
- <th class="w-sdc-resource-viewer-right-table-head-cell cols-3">File</th>
- <th class="w-sdc-resource-viewer-right-table-head-cell cols-3">Version</th>
- <th class="w-sdc-resource-viewer-right-table-head-cell cols-3"></th>
- </thead>
- <tbody>
- <tr data-ng-repeat="(artifactLogicName, artifact) in component.artifacts">
- <td><span class="ellipsis-cols2" data-tests-id="{{artifact.artifactDisplayName}}" tooltips tooltip-content="{{artifact.artifactDisplayName}}">{{artifact.artifactDisplayName}}</span></td>
- <td><span class="ellipsis-cols3" data-tests-id="{{artifact.artifactName}}" tooltips tooltip-content="{{artifact.artifactName}}">{{artifact.artifactName}}</span></td>
- <td><span class="ellipsis-cols3" data-tests-id="{{artifact.artifactVersion}}" tooltips tooltip-content="{{artifact.artifactVersion}}" data-ng-if="artifact.esId">{{artifact.artifactVersion}}</span></td>
- <td class="cols-3">
- <download-artifact class="sdc-information-artifacts-icon download" data-ng-if="artifact.artifactName" component="component" artifact="artifact"></download-artifact>
- <!--span class="sdc-information-artifacts-icon preview"></span-->
- </td>
- </tr>
- </tbody>
- </table>
- </div>
-</div>
diff --git a/catalog-ui/app/scripts/view-models/dashboard/cover/dashboard-cover-view-model.ts b/catalog-ui/app/scripts/view-models/dashboard/cover/dashboard-cover-view-model.ts
deleted file mode 100644
index 9979b6451b..0000000000
--- a/catalog-ui/app/scripts/view-models/dashboard/cover/dashboard-cover-view-model.ts
+++ /dev/null
@@ -1,91 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../../references"/>
-module Sdc.ViewModels {
-
- 'use strict';
-
- export interface IDashboardCoverViewModelScope extends ng.IScope {
- showTutorial:boolean;
- version:string;
- modalInstance:ng.ui.bootstrap.IModalServiceInstance;
- }
-
- export class DashboardCoverViewModel {
- static '$inject' = [
- '$scope',
- '$stateParams',
- 'Sdc.Services.CacheService',
- '$templateCache',
- '$state',
- '$modal',
- 'sdcConfig'
- ];
-
- constructor(private $scope:IDashboardCoverViewModelScope,
- private $stateParams:any,
- private cacheService:Services.CacheService,
- private $templateCache:ng.ITemplateCacheService,
- private $state:any,
- private $modal:ng.ui.bootstrap.IModalService,
- private sdcConfig:Models.IAppConfigurtaion) {
-
- // Show the tutorial if needed when the dashboard page is opened.<script src="bower_components/angular-filter/dist/angular-filter.min.js"></script>
- // This is called from the welcome page.
- if (this.$stateParams.show === 'tutorial') {
- this.$scope.showTutorial = true;
- } else if (this.$stateParams.show === 'whatsnew') {
- this.$scope.version = this.cacheService.get('version');
- this.openWhatsNewModal(this.$scope);
- }
-
- this.initScope();
- }
-
- private initScope = ():void => {
-
- };
-
- private openWhatsNewModal = (scope:IDashboardCoverViewModelScope):void => {
-
- let onOk = ():void => {};
-
- let onCancel = ():void => {
- this.$state.go('dashboard.welcome', {show: ''});
- };
-
- let modalOptions:ng.ui.bootstrap.IModalSettings = {
- template: this.$templateCache.get('/app/scripts/view-models/whats-new/whats-new-view.html'),
- controller: 'Sdc.ViewModels.WhatsNewViewModel',
- size: 'sdc-l',
- backdrop: 'static',
- scope: scope,
- resolve: {
- 'version': scope.version
- }
- };
-
- scope.modalInstance = this.$modal.open(modalOptions);
- scope.modalInstance.result.then(onOk, onCancel);
- };
-
- }
-
-}
diff --git a/catalog-ui/app/scripts/view-models/dashboard/cover/dashboard-cover-view.html b/catalog-ui/app/scripts/view-models/dashboard/cover/dashboard-cover-view.html
deleted file mode 100644
index c8657cba23..0000000000
--- a/catalog-ui/app/scripts/view-models/dashboard/cover/dashboard-cover-view.html
+++ /dev/null
@@ -1 +0,0 @@
-<div class="sdc-welcome-page"></div>
diff --git a/catalog-ui/app/scripts/view-models/dashboard/dashboard-view-model-tests.ts b/catalog-ui/app/scripts/view-models/dashboard/dashboard-view-model-tests.ts
deleted file mode 100644
index d97d9bb5ec..0000000000
--- a/catalog-ui/app/scripts/view-models/dashboard/dashboard-view-model-tests.ts
+++ /dev/null
@@ -1,276 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../references"/>
-
-describe("dashboard View Model ", () => {
-
- let $controllerMock:ng.IControllerService;
- let $qMock:ng.IQService;
- let $httpBackendMock:ng.IHttpBackendService;
- let $scopeMock:Sdc.ViewModels.IDashboardViewModelScope;
- let $stateMock:ng.ui.IStateService;
- let $stateParams:any;
- let entityServiceMock;
-
-
- let getAllEntitiesResponseMock = [
- {
- "uniqueId": "855acdc7-7976-4913-9fa6-25220bd5a069",
- "uuid": "8bc54f94-082c-42fa-9049-84767df3ff05",
- "contactId": "qa1234",
- "category": "VoIP Call Control",
- "creationDate": 1447234712398,
- "description": "ddddd",
- "highestVersion": true,
- "icon": "mobility",
- "lastUpdateDate": 1447234712398,
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT",
- "distributionStatus": "DISTRIBUTION_NOT_APPROVED",
- "projectCode": "233233",
- "name": "mas mas mas mas mas mas mas mas mas mas mas mas ma",
- "version": "0.1",
- "type": 0,
- "tags": [
- "mas mas mas mas mas mas mas mas mas mas mas mas ma"
- ],
- "systemName": "MasMasMasMasMasMasMasMasMasMasMasMasMa",
- "vnf": true,
- "$$hashKey": "object:30"
- },
- {
- "uniqueId": "4bb577ce-cb2c-4cb7-bb39-58644b5e73cb",
- "uuid": "e27f4723-c9ec-4160-89da-dbf84d19a7e3",
- "contactId": "qa1111",
- "category": "Mobility",
- "creationDate": 1447238503181,
- "description": "aqa",
- "highestVersion": true,
- "icon": "call_controll",
- "lastUpdateDate": 1447248991388,
- "lastUpdaterUserId": "jm0007",
- "lastUpdaterFullName": "Joni Mitchell",
- "lifecycleState": "CERTIFIED",
- "distributionStatus": "DISTRIBUTION_REJECTED",
- "projectCode": "111111",
- "name": "martin18",
- "version": "1.0",
- "type": 0,
- "tags": [
- "martin18"
- ],
- "systemName": "Martin18",
- "vnf": true
- },
- {
- "uniqueId": "f192f4a6-7fbf-42e4-a546-37509df28dc1",
- "uuid": "0b77dc0d-222e-4d10-85cd-e420c9481417",
- "contactId": "fd1212",
- "category": "Application Layer 4+/Web Server",
- "creationDate": 1447233679778,
- "description": "geefw",
- "highestVersion": true,
- "icon": "database",
- "lastUpdateDate": 1447233681582,
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT",
- "name": "ger",
- "version": "0.1",
- "type": 1,
- "tags": [
- "ger"
- ],
- "vendorName": "fewwfe",
- "vendorRelease": "fewew",
- "systemName": "Ger",
- "$$hashKey": "object:31"
- },
- {
- "uniqueId": "78392d08-1859-47c2-b1f2-1a35b7f8c30e",
- "uuid": "8cdd63b2-6a62-4376-9012-624f424f71d4",
- "contactId": "qw1234",
- "category": "Application Layer 4+/Application Servers",
- "creationDate": 1447234046114,
- "description": "test",
- "highestVersion": true,
- "icon": "router",
- "lastUpdateDate": 1447234050545,
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT",
- "name": "test",
- "version": "0.1",
- "type": 1,
- "tags": [
- "test"
- ],
- "vendorName": "test",
- "vendorRelease": "test",
- "systemName": "Test",
- "$$hashKey": "object:32"
- },
- {
- "uniqueId": "939e153d-2236-410f-b4a9-3b4bf8c79c9e",
- "uuid": "84862547-4f56-4058-b78e-40df5f374d7e",
- "contactId": "qw1234",
- "category": "Application Layer 4+/Application Servers",
- "creationDate": 1447235242560,
- "description": "jlk",
- "highestVersion": true,
- "icon": "database",
- "lastUpdateDate": 1447235328062,
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "lifecycleState": "NOT_CERTIFIED_CHECKIN",
- "name": "new",
- "version": "0.1",
- "type": 1,
- "tags": [
- "new"
- ],
- "vendorName": "e",
- "vendorRelease": "e",
- "systemName": "New",
- "$$hashKey": "object:33"
- },
- {
- "uniqueId": "ece818e0-fd59-477a-baf6-e27461a7ce23",
- "uuid": "8db823c2-6a9c-4636-8676-f5e713270dd7",
- "contactId": "uf2345",
- "category": "Network Layer 2-3/Router",
- "creationDate": 1447235352429,
- "description": "u",
- "highestVersion": true,
- "icon": "network",
- "lastUpdateDate": 1447235370064,
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT",
- "name": "u",
- "version": "0.1",
- "type": 1,
- "tags": [
- "u"
- ],
- "vendorName": "u",
- "vendorRelease": "u",
- "systemName": "U",
- "$$hashKey": "object:34"
- }
- ];
- let getAllEntitiesDefered:ng.IDeferred<any> = null;
-
- beforeEach(angular.mock.module('sdcApp'));
-
- beforeEach(angular.mock.inject((_$controller_:ng.IControllerService,
- _$httpBackend_:ng.IHttpBackendService,
- _$rootScope_,
- _$q_:ng.IQService,
- _$state_:ng.ui.IStateService,
- _$stateParams_:any) => {
-
- $controllerMock = _$controller_;
- $httpBackendMock = _$httpBackend_
- $scopeMock = _$rootScope_.$new();
- $qMock = _$q_;
- $stateMock = _$state_;
- $stateParams = _$stateParams_;
-
-
- //handle all http request thet not relevant to the tests
- $httpBackendMock.expectGET(/.*languages\/en_US.json.*/).respond(200, JSON.stringify({}));
- // $httpBackendMock.expectGET(/.*resources\/certified\/abstract.*/).respond(200, JSON.stringify({}));
- $httpBackendMock.expectGET(/.*rest\/version.*/).respond(200, JSON.stringify({}));
- $httpBackendMock.expectGET(/.*configuration\/ui.*/).respond(200, JSON.stringify({}));
- $httpBackendMock.expectGET(/.*user\/authorize.*/).respond(200, JSON.stringify({}));
- $httpBackendMock.expectGET(/.*categories\/services.*/).respond(200, JSON.stringify({}));
- $httpBackendMock.expectGET(/.*categories\/resources.*/).respond(200, JSON.stringify({}));
- $httpBackendMock.expectGET(/.*categories\/products.*/).respond(200, JSON.stringify({}));
- $httpBackendMock.expectGET('http://feHost:8181/sdc1/feProxy/rest/version').respond(200, JSON.stringify({}));
-
- /**
- * Mock the service
- * @type {any}
- */
- getAllEntitiesDefered = $qMock.defer();
- getAllEntitiesDefered.resolve(getAllEntitiesResponseMock);
- entityServiceMock = jasmine.createSpyObj('entityServiceMock', ['getAllComponents']);
- entityServiceMock.getAllComponents.and.returnValue(getAllEntitiesDefered.promise);
-
- // $stateParams['show'] = '';
-
- /**
- * Need to inject into the controller only the objects that we want to MOCK
- * those that we need to change theirs behaviors
- */
- $controllerMock(Sdc.ViewModels.DashboardViewModel, {
- '$scope': $scopeMock,
- '$stateParams': $stateParams,
- 'Sdc.Services.EntityService': entityServiceMock,
- });
-
- }));
-
-
- describe("when Controller 'DashboardViewModel' created", () => {
-
- it('should generate all entities', () => {
- $scopeMock.$apply();
- expect($scopeMock.components.length).toBe(getAllEntitiesResponseMock.length);
- });
-
-
- it('should show tutorial page ', () => {
- $stateParams.show = 'tutorial';
-
- $controllerMock(Sdc.ViewModels.DashboardViewModel, {
- '$scope': $scopeMock,
- '$stateParams': $stateParams,
- 'Sdc.Services.EntityService': entityServiceMock,
- //to complete injects
- });
-
- $scopeMock.$apply();
- expect($scopeMock.isFirstTime).toBeTruthy();
- expect($scopeMock.showTutorial).toBeTruthy();
- });
-
- });
-
-
- describe("when function 'entitiesCount' invoked", () => {
-
- beforeEach(() => {
- $controllerMock(Sdc.ViewModels.DashboardViewModel, {
- '$scope': $scopeMock,
- 'Sdc.Services.EntityService': entityServiceMock,
- });
- $scopeMock.$apply();
- });
-
- it('should return entities count per folder', () => {
-
- });
-
-
- });
-});
diff --git a/catalog-ui/app/scripts/view-models/dashboard/dashboard-view-model.ts b/catalog-ui/app/scripts/view-models/dashboard/dashboard-view-model.ts
deleted file mode 100644
index 8325a3f133..0000000000
--- a/catalog-ui/app/scripts/view-models/dashboard/dashboard-view-model.ts
+++ /dev/null
@@ -1,415 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../references"/>
-module Sdc.ViewModels {
-
- 'use strict';
- import ResourceType = Sdc.Utils.Constants.ResourceType;
-
- export interface IDashboardViewModelScope extends ng.IScope {
-
- isLoading: boolean;
- components: Array<Models.Components.Component>;
- folders: FoldersMenu;
- roles: Models.IConfigRoles;
- user: Models.IUserProperties;
- sdcConfig:Models.IAppConfigurtaion;
- sdcMenu:Models.IAppMenu;
- sharingService:Sdc.Services.SharingService;
- showTutorial:boolean;
- isFirstTime:boolean;
- version:string;
- checkboxesFilter:CheckboxesFilter;
-
- onImportVfc(file:any):void;
- onImportVf(file:any):void;
- openCreateModal(componentType: Utils.Constants.ComponentType, importedFile:any): void;
- openWhatsNewModal(version:string):void;
- openDesignerModal(isResource:boolean, uniqueId:string): void;
- openViewerModal(entity:any) : void;
- setSelectedFolder(folderItem: FoldersItemsMenu): void;
- entitiesCount(folderItem: FoldersItemsMenu): number;
- getCurrentFolderDistributed(): Array<Models.Components.Component>;
- changeLifecycleState(entity:any, data:any): void;
- goToComponent(component:Models.Components.Component):void;
- wizardDebugEdit:Function;
- notificationIconCallback:Function;
- }
-
- interface CheckboxesFilter {
- // Statuses
- selectedStatuses:Array<string>;
- // distributed
- distributed:Array<string>;
- }
-
- export interface IItemMenu {
-
- }
-
- export interface IMenuItemProperties {
- text: string;
- group: string;
- state: string;
- dist: string;
- groupname: string;
- states: Array<any>;
- }
-
- export class FoldersMenu {
-
- private _folders: Array<FoldersItemsMenu> = [];
-
- constructor(folders: Array<IMenuItemProperties>) {
- let self = this;
- folders.forEach(function(folder: IMenuItemProperties) {
- if (folder.groupname){
- self._folders.push(new FoldersItemsMenuGroup(folder));
- } else {
- self._folders.push(new FoldersItemsMenu(folder));
- }
- });
- self._folders[0].setSelected(true);
- }
-
- public getFolders = (): Array<FoldersItemsMenu> => {
- return this._folders;
- };
-
- public getCurrentFolder = (): FoldersItemsMenu => {
- let menuItem: FoldersItemsMenu = undefined;
- this.getFolders().forEach(function(tmpFolder: FoldersItemsMenu) {
- if (tmpFolder.isSelected()){
- menuItem = tmpFolder;
- }
- });
- return menuItem;
- };
-
- public setSelected = (folder: FoldersItemsMenu):void => {
- this.getFolders().forEach(function(tmpFolder: FoldersItemsMenu) {
- tmpFolder.setSelected(false);
- });
- folder.setSelected(true);
- }
-
- }
-
- export class FoldersItemsMenu implements IItemMenu {
-
- public text:string;
- public group: string;
- public state: string;
- public dist: string;
- public states: Array<any>;
-
- private selected: boolean = false;
-
- constructor(menuProperties: IMenuItemProperties) {
- this.text = menuProperties.text;
- this.group = menuProperties.group;
- this.state = menuProperties.state;
- this.states = menuProperties.states;
- this.dist = menuProperties.dist;
- }
-
- public isSelected = ():boolean => {
- return this.selected;
- };
-
- public setSelected = (value: boolean):void => {
- this.selected = value;
- };
-
- public isGroup = ():boolean => {
- return false;
- }
-
- }
-
- export class FoldersItemsMenuGroup extends FoldersItemsMenu {
-
- public groupname:string;
-
- constructor(menuProperties: IMenuItemProperties) {
- super(menuProperties);
- this.groupname = menuProperties.groupname;
- }
-
- public isGroup = ():boolean => {
- return true;
- }
-
- }
-
- export class DashboardViewModel {
- static '$inject' = [
- '$scope',
- '$filter',
- 'Sdc.Services.EntityService',
- '$http',
- 'sdcConfig',
- 'sdcMenu',
- '$modal',
- '$templateCache',
- '$state',
- '$stateParams',
- 'Sdc.Services.UserResourceService',
- 'Sdc.Services.SharingService',
- 'Sdc.Services.CacheService',
- '$q',
- 'ComponentFactory',
- 'ChangeLifecycleStateHandler',
- 'ModalsHandler',
- 'MenuHandler'
- ];
-
- private components: Array<Models.Components.Component>;
-
- constructor(private $scope:IDashboardViewModelScope,
- private $filter:ng.IFilterService,
- private entityService:Services.EntityService,
- private $http:ng.IHttpService,
- private sdcConfig:Models.IAppConfigurtaion,
- private sdcMenu:Models.IAppMenu,
- private $modal:ng.ui.bootstrap.IModalService,
- private $templateCache:ng.ITemplateCacheService,
- private $state:any,
- private $stateParams:any,
- private userResourceService:Sdc.Services.IUserResourceClass,
- private sharingService:Services.SharingService,
- private cacheService:Services.CacheService,
- private $q:ng.IQService,
- private ComponentFactory: Sdc.Utils.ComponentFactory,
- private ChangeLifecycleStateHandler: Sdc.Utils.ChangeLifecycleStateHandler,
- private ModalsHandler: Sdc.Utils.ModalsHandler,
- private MenuHandler: Utils.MenuHandler
- ) {
- this.initScope();
- this.initFolders();
- this.initEntities(true);
-
- if (this.$stateParams){
-
- if (this.$state.params.folder){
- let self = this;
- let folderName = this.$state.params.folder.replaceAll("_"," ");
-
- this.$scope.folders.getFolders().forEach(function(tmpFolder: FoldersItemsMenu) {
- if (tmpFolder.text === folderName){
- self.$scope.setSelectedFolder(tmpFolder);
- }
- });
- }
-
- // Show the tutorial if needed when the dashboard page is opened.<script src="bower_components/angular-filter/dist/angular-filter.min.js"></script>
- // This is called from the welcome page.
- else if (this.$stateParams.show==='tutorial'){
- this.$scope.showTutorial = true;
- this.$scope.isFirstTime = true;
- }
- }
- }
-
- private initFolders = ():void => {
- if (this.$scope.user) {
- this.$scope.folders = new FoldersMenu(this.$scope.roles[this.$scope.user.role].folder);
- }
- };
-
- private initScope = ():void => {
- let self = this;
-
- this.$scope.version = this.cacheService.get('version');
- this.$scope.sharingService = this.sharingService;
- this.$scope.isLoading = false;
- this.$scope.sdcConfig = this.sdcConfig;
- this.$scope.sdcMenu = this.sdcMenu;
- this.$scope.user = this.userResourceService.getLoggedinUser();
- this.$scope.roles = this.sdcMenu.roles;
- this.$scope.showTutorial = false;
- this.$scope.isFirstTime = false;
-
- // Open onboarding modal
- this.$scope.notificationIconCallback = ():void => {
- this.ModalsHandler.openOnboadrdingModal('Import').then(()=>{
- // OK
- }, ()=>{
- // ERROR
- });
- };
-
- // Checkboxes filter init
- this.$scope.checkboxesFilter = <CheckboxesFilter>{};
- this.$scope.checkboxesFilter.selectedStatuses = [];
- this.$scope.checkboxesFilter.distributed = [];
-
- let appendTemplateAndControllerForProduct:Function = (modalOptions:ng.ui.bootstrap.IModalSettings, isViewer:boolean):void => {
- let viewModelsHtmlBasePath:string = '/app/scripts/view-models/';
-
- if (isViewer) {
- modalOptions.template = this.$templateCache.get(viewModelsHtmlBasePath + 'entity-viewer/product-viewer-view.html');
- modalOptions.controller = 'Sdc.ViewModels.ResourceViewerViewModel';
- } else {
- modalOptions.template = this.$templateCache.get(viewModelsHtmlBasePath + 'entity-handler/product-form/product-form-view.html');
- modalOptions.controller = 'Sdc.ViewModels.ProductFormViewModel';
- }
-
- };
-
- this.$scope.onImportVf = (file:any):void => {
- if(file && file.filename) {
- // Check that the file has valid extension.
- let fileExtension:string = file.filename.split(".").pop();
- if (this.sdcConfig.csarFileExtension.indexOf(fileExtension.toLowerCase()) !== -1){
- this.$state.go('workspace.general', {type:Utils.Constants.ComponentType.RESOURCE.toLowerCase(), importedFile: file, resourceType: ResourceType.VF});
- }else {
- let data:Sdc.ViewModels.IClientMessageModalModel = {
- title: self.$filter('translate')("NEW_SERVICE_RESOURCE_ERROR_VALID_CSAR_EXTENSIONS_TITLE"),
- message: self.$filter('translate')("NEW_SERVICE_RESOURCE_ERROR_VALID_CSAR_EXTENSIONS", "{'extensions': '" + this.sdcConfig.csarFileExtension + "'}"),
- severity: Utils.Constants.SEVERITY.ERROR
- };
- this.ModalsHandler.openClientMessageModal(data);
- }
- }
- };
-
- this.$scope.onImportVfc = (file:any):void => {
- if(file && file.filename) {
- // Check that the file has valid extension.
- let fileExtension:string = file.filename.split(".").pop();
- if (this.sdcConfig.toscaFileExtension.indexOf(fileExtension.toLowerCase()) !== -1){
- this.$state.go('workspace.general', {type:Utils.Constants.ComponentType.RESOURCE.toLowerCase(), importedFile: file, resourceType: ResourceType.VFC});
- }else {
- let data:Sdc.ViewModels.IClientMessageModalModel = {
- title: self.$filter('translate')("NEW_SERVICE_RESOURCE_ERROR_VALID_TOSCA_EXTENSIONS_TITLE"),
- message: self.$filter('translate')("NEW_SERVICE_RESOURCE_ERROR_VALID_TOSCA_EXTENSIONS", "{'extensions': '" + this.sdcConfig.toscaFileExtension + "'}"),
- severity: Utils.Constants.SEVERITY.ERROR
- };
- this.ModalsHandler.openClientMessageModal(data);
- }
- }
- };
-
- this.$scope.openCreateModal = (componentType: string, importedFile:any):void => {
- if (importedFile){
- this.initEntities(true); // Return from import
- } else {
- this.$state.go('workspace.general', {type:componentType.toLowerCase()});
- }
-
- };
-
- this.$scope.entitiesCount = (folderItem: FoldersItemsMenu): any => {
- let self = this;
- let total: number = 0;
- if (folderItem.isGroup()){
- this.$scope.folders.getFolders().forEach(function(tmpFolder: FoldersItemsMenu){
- if (tmpFolder.group && tmpFolder.group===(<FoldersItemsMenuGroup>folderItem).groupname){
- total = total + self._getTotalCounts(tmpFolder, self);
- }
- });
- } else {
- total = total + self._getTotalCounts(folderItem, self);
- }
- return total;
- };
-
- this.$scope.getCurrentFolderDistributed = (): Array<any> => {
- let self = this;
- let states = [];
- if (this.$scope.folders) {
- let folderItem:FoldersItemsMenu = this.$scope.folders.getCurrentFolder();
- if (folderItem.isGroup()) {
- this.$scope.folders.getFolders().forEach(function (tmpFolder:FoldersItemsMenu) {
- if (tmpFolder.group && tmpFolder.group === (<FoldersItemsMenuGroup>folderItem).groupname) {
- self._setStates(tmpFolder, states);
- }
- });
- } else {
- self._setStates(folderItem, states);
- }
- }
- return states;
- };
-
- this.$scope.setSelectedFolder = (folderItem: FoldersItemsMenu):void => {
- this.$scope.folders.setSelected(folderItem);
- };
-
- this.$scope.goToComponent = (component:Models.Components.Component):void => {
- this.$scope.isLoading=true;
- this.$state.go('workspace.general', {id: component.uniqueId, type:component.componentType.toLowerCase() });
- };
-
- };
-
- private _getTotalCounts(tmpFolder, self): number {
- let total: number = 0;
- if (tmpFolder.dist !== undefined) {
- let distributions = tmpFolder.dist.split(',');
- distributions.forEach((item:any) => {
- total = total + self.getEntitiesByStateDist(tmpFolder.state, item).length;
- });
- }
- else {
- total = total + self.getEntitiesByStateDist(tmpFolder.state, tmpFolder.dist).length;
- }
- return total;
- }
-
- private _setStates(tmpFolder, states) {
- if (tmpFolder.states !== undefined) {
- tmpFolder.states.forEach(function (item:any) {
- states.push({"state": item.state, "dist": item.dist});
- });
- } else {
- states.push({"state": tmpFolder.state, "dist": tmpFolder.dist});
- }
- }
-
- private initEntities = (reload:boolean):void => {
- this.$scope.isLoading = reload;
- this.entityService.getAllComponents().then(
- (components: Array<Models.Components.Component>) => {
- this.components = components;
- this.$scope.components = components;
- this.$scope.isLoading = false;
- });
- };
-
- private getEntitiesByStateDist = (state: string, dist: string) : Array<Models.Components.Component> => {
- let gObj:Array<Models.Components.Component>;
- if (this.components && (state || dist)) {
- gObj = this.components.filter(function (obj:Models.Components.Component) {
- if (dist !== undefined && obj.distributionStatus === dist && obj.lifecycleState === state){
- return true;
- } else if (dist === undefined && obj.lifecycleState === state) {
- return true;
- }
- return false;
- });
- } else {
- gObj = [];
- }
- return gObj;
- }
- }
-}
diff --git a/catalog-ui/app/scripts/view-models/dashboard/dashboard-view.html b/catalog-ui/app/scripts/view-models/dashboard/dashboard-view.html
deleted file mode 100644
index 0aef4e19c6..0000000000
--- a/catalog-ui/app/scripts/view-models/dashboard/dashboard-view.html
+++ /dev/null
@@ -1,106 +0,0 @@
-<div class="sdc-catalog-container">
- <loader data-display="isLoading"></loader>
-
- <!-- HEADER -->
-<!--
- <ecomp-header menu-data="menuItems" version="{{version}}"></ecomp-header>
--->
-
- <div class="w-sdc-main-container">
-
- <perfect-scrollbar include-padding="true" class="w-sdc-main-right-container">
-
- <!-- ADD Component -->
- <div ng-if="user.role === 'DESIGNER' || user.role === 'PRODUCT_MANAGER'" class="w-sdc-dashboard-card-new"
- data-ng-mouseleave="displayActions = false"
- data-ng-mouseover="displayActions = true"
- data-ng-init="displayActions = false">
- <div class="w-sdc-dashboard-card-new-content" data-tests-id="AddButtonsArea">
- <div class="w-sdc-dashboard-card-new-content-plus" data-ng-show="!displayActions"></div>
- <div class="sdc-dashboard-create-element-container" data-ng-show="displayActions">
- <button data-ng-if="roles[user.role].dashboard.showCreateNewProduct" class="tlv-btn outline blue" data-ng-click="openCreateModal('PRODUCT')">Create Product</button>
- <button data-ng-if="roles[user.role].dashboard.showCreateNew" data-tests-id="createResourceButton" class="tlv-btn outline blue" data-ng-click="openCreateModal('RESOURCE')">Add VF</button>
- <button data-ng-if="roles[user.role].dashboard.showCreateNew" data-tests-id="createServiceButton" class="tlv-btn outline blue" data-ng-click="openCreateModal('SERVICE')">Add Service</button>
- </div>
- </div>
- </div>
-
- <!-- Import Component -->
- <div ng-if="user.role === 'DESIGNER'" class="w-sdc-dashboard-card-new"
- data-ng-mouseleave="displayActions = false"
- data-ng-mouseover="displayActions = true"
- data-ng-init="displayActions = false">
- <div class="w-sdc-dashboard-card-new-content" data-tests-id="importButtonsArea" >
- <div class="w-sdc-dashboard-card-import-content-plus" data-ng-show="!displayActions"></div>
- <div class="sdc-dashboard-import-element-container" data-ng-show="displayActions">
- <div data-ng-if="roles[user.role].dashboard.showCreateNew" class="tlv-btn outline blue">Import VFC
- <file-opener on-file-upload="onImportVfc(file)" data-tests-id="importVFCbutton" extensions="{{sdcConfig.toscaFileExtension}}" data-ng-click="displayActions=false"></file-opener>
- </div>
- <div data-ng-if="roles[user.role].dashboard.showCreateNew" class="tlv-btn outline blue" data-ng-click="notificationIconCallback()">Import VSP</div>
- <div data-ng-if="roles[user.role].dashboard.showCreateNew" class="tlv-btn outline blue import-dcae">Import DCAE asset
- <file-opener on-file-upload="onImportVf(file)" data-tests-id="importVFbutton" extensions="{{sdcConfig.csarFileExtension}}" data-ng-click="displayActions=false"></file-opener>
- </div>
- </div>
- </div>
- </div>
-
- <div
- data-ng-class="{'sdc-hide-popover': hidePopover,'resource' : component.isResource(),'service' : component.isService()}"
- class="w-sdc-dashboard-card"
- data-ng-repeat="component in components | entityFilter:checkboxesFilter | filter:search"
- >
- <div class="w-sdc-dashboard-card-body" data-tests-id="dashboard-Elements" data-ng-click="goToComponent(component)">
- <!--<div class="w-sdc-dashboard-card-description">{{entity.description}}</div>-->
- <div class="w-sdc-dashboard-card-avatar"><span data-tests-id="asset-type" class="{{component.getComponentSubType()}}"></span></div>
- <!--<div class="w-sdc-dashboard-card-edit" data-ng-class="component.lifecycleState" data-tests-id="{{component.lifecycleState}}"></div>-->
- <div class="w-sdc-dashboard-card-schema-image {{component.iconSprite}} {{component.icon}}"
- data-ng-class="{'sprite-resource-icons': component.isResource(), 'sprite-services-icons': component.isService()}"
- data-tests-id="{{component.name}}"></div>
- <div class="w-sdc-dashboard-card-info-name-container">
- <span class="w-sdc-dashboard-card-info-name" tooltips
- tooltip-content="{{component.name | resourceName}}"> {{component.name | resourceName}}</span>
- </div>
- </div>
- <div class="w-sdc-dashboard-card-footer">
-
- <div class="w-sdc-dashboard-card-info">
- <div class="w-sdc-dashboard-card-info-lifecycleState">
- <span class="w-sdc-dashboard-card-info-lifecycleState" tooltips
- tooltip-content="{{component.getStatus(sdcMenu)}}"> {{component.getStatus(sdcMenu)}}</span>
- </div>
- <div class="w-sdc-dashboard-card-info-user"data-tests-id="{{component.name}}Version">V {{component.version}}</div>
- </div>
- <!--<div class="w-sdc-dashboard-card-info-lifecycleState-icon sprite-new {{sdcMenu.LifeCycleStatuses[component.lifecycleState].icon}}"></div>-->
- </div>
- </div>
-
- </perfect-scrollbar>
-
- <div class="w-sdc-left-sidebar">
- <div class="i-sdc-left-sidebar-item "
- data-ng-repeat="folder in folders.getFolders()"
- data-ng-class="{'category-title': folder.isGroup(), 'selectedLink': folder.isSelected()}"
- >
- <span data-ng-if="folder.isGroup()">{{folder.text}}</span>
-
- <sdc-checkbox data-ng-if="!folder.isGroup() && !folder.dist"
- elem-id="checkbox-{{folder.text | lowercase | clearWhiteSpaces}}"
- sdc-checklist-model="checkboxesFilter.selectedStatuses"
- sdc-checklist-value="folder.state"
- text="{{folder.text}}"></sdc-checkbox>
-
- <sdc-checkbox data-ng-if="!folder.isGroup() && folder.dist"
- elem-id="checkbox-{{folder.text | lowercase | clearWhiteSpaces}}"
- sdc-checklist-model="checkboxesFilter.distributed"
- sdc-checklist-value="folder.dist"
- text="{{folder.text}}"></sdc-checkbox>
- <span class="i-sdc-left-sidebar-item-state-count">{{entitiesCount(folder)}}</span>
- </div>
- </div>
-
- </div>
-
- <top-nav top-lvl-selected-index="0" version="{{version}}" search-bind="search.filterTerm" notification-icon-callback="notificationIconCallback" version="{{version}}"></top-nav>
-
-</div>
-<div data-ui-view=""></div>
diff --git a/catalog-ui/app/scripts/view-models/forms/artifact-form/artifact-form-view-model.ts b/catalog-ui/app/scripts/view-models/forms/artifact-form/artifact-form-view-model.ts
deleted file mode 100644
index 092594b0d5..0000000000
--- a/catalog-ui/app/scripts/view-models/forms/artifact-form/artifact-form-view-model.ts
+++ /dev/null
@@ -1,354 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../../references"/>
-
-module Sdc.ViewModels {
- 'use strict';
- import Resource = Sdc.Models.Components.Resource;
-
- export interface IEditArtifactModel {
- artifactResource: Models.ArtifactModel;
- artifactTypes: Array<string>;
- artifactFile: any;
- }
-
- export interface IArtifactResourceFormViewModelScope extends ng.IScope {
- forms:any;
- $$childTail: any;
- isNew: boolean;
- isLoading: boolean;
- validationPattern: RegExp;
- urlValidationPattern: RegExp;
- labelValidationPattern: RegExp;
- integerValidationPattern: RegExp;
- commentValidationPattern: RegExp;
- artifactType: string;
- editArtifactResourceModel: IEditArtifactModel;
- defaultHeatTimeout: number;
- validExtensions: any;
- originalArtifactName: string;
- editForm: ng.IFormController;
- footerButtons: Array<any>;
- modalInstanceArtifact:ng.ui.bootstrap.IModalServiceInstance;
-
- fileExtensions():string;
- save(doNotCloseModal?:boolean): void;
- saveAndAnother(): void;
- close(): void;
- getOptions(): Array<string>;
- isDeploymentHeat(): boolean;
- onFileChange(): void;
- setDefaultTimeout(): void;
- openEditEnvParametersModal(artifact:Models.ArtifactModel):void;
- getFormTitle():string;
- fileUploadRequired():string;
- isArtifactOwner():boolean;
- }
-
- export class ArtifactResourceFormViewModel {
-
- private artifactArr:Array<Models.ArtifactModel>;
-
- static '$inject' = [
- '$scope',
- '$modalInstance',
- 'artifact',
- 'Sdc.Services.CacheService',
- 'ValidationPattern',
- 'UrlValidationPattern',
- 'LabelValidationPattern',
- 'IntegerValidationPattern',
- 'CommentValidationPattern',
- 'ValidationUtils',
- '$base64',
- '$state',
- 'ArtifactsUtils',
- '$modal',
- '$templateCache',
- 'component'
- ];
-
- private formState:Utils.Constants.FormState;
- private entityId:string;
-
- constructor(private $scope:IArtifactResourceFormViewModelScope,
- private $modalInstance:ng.ui.bootstrap.IModalServiceInstance,
- private artifact:Models.ArtifactModel,
- private cacheService:Services.CacheService,
- private ValidationPattern:RegExp,
- private UrlValidationPattern:RegExp,
- private LabelValidationPattern:RegExp,
- private IntegerValidationPattern : RegExp,
- private CommentValidationPattern: RegExp,
- private ValidationUtils: Sdc.Utils.ValidationUtils,
- private $base64:any,
- private $state:any,
- private artifactsUtils:Sdc.Utils.ArtifactsUtils,
- private $modal:ng.ui.bootstrap.IModalService,
- private $templateCache:ng.ITemplateCacheService,
- private component:Models.Components.Component) {
-
-
- this.entityId = this.component.uniqueId;
- this.artifactArr = [];
- this.formState = angular.isDefined(artifact.artifactLabel) ? Utils.Constants.FormState.UPDATE : Utils.Constants.FormState.CREATE;
- this.initScope();
- }
-
- private initEntity = ():void => {
- this.$scope.editArtifactResourceModel.artifactResource = this.artifact;
- this.$scope.originalArtifactName = this.artifact.artifactName;
- };
-
-
- private initFooterButtons = ():void =>{
-
- this.$scope.footerButtons = [
- {'name': 'Done', 'css': 'blue', 'callback': this.$scope.save}
- ];
- if (this.$scope.isNew){
- this.$scope.footerButtons.push( {'name': 'Add Another', 'css': 'grey', 'disabled': !this.$scope.isNew && 'deployment' === this.$scope.artifactType, 'callback': this.$scope.saveAndAnother});
- }
-
- };
-
-
- private initArtifactTypes = ():void => {
-
- let artifactTypes:any = this.cacheService.get('UIConfiguration');
-
- if('deployment' === this.$scope.artifactType) {
-
- this.$scope.validExtensions = ('HEAT_ENV' == this.artifact.artifactType||this.component.selectedInstance)?//to remove the first condition?
- artifactTypes.artifacts.deployment.resourceInstanceDeploymentArtifacts
- : this.component.isResource() ? artifactTypes.artifacts.deployment.resourceDeploymentArtifacts
- : artifactTypes.artifacts.deployment.serviceDeploymentArtifacts;
-
- if(this.$scope.validExtensions) {
- this.$scope.editArtifactResourceModel.artifactTypes = Object.keys(this.$scope.validExtensions);
- }
- this.$scope.defaultHeatTimeout = artifactTypes.defaultHeatTimeout;
- if(this.$scope.isNew) {
- let isHeat='HEAT_ENV' == this.artifact.artifactType;
- _.remove(this.$scope.editArtifactResourceModel.artifactTypes, (item:string)=> {
- return 'HEAT' == item.substring(0,4)||(!isHeat && item == "VF_MODULES_METADATA") ||
- _.has(Utils.Constants.ArtifactType.THIRD_PARTY_RESERVED_TYPES, item);
- });
- }
-
- }if (this.$scope.artifactType === 'normal') {
- this.$scope.editArtifactResourceModel.artifactTypes = artifactTypes.artifacts.other.map((element:any)=> {
- return element.name;
- });
- _.remove(this.$scope.editArtifactResourceModel.artifactTypes, (item:string)=> {
- return _.has(Utils.Constants.ArtifactType.THIRD_PARTY_RESERVED_TYPES, item) ||
- _.has(Utils.Constants.ArtifactType.TOSCA, item);
- })
- }
-
- if(this.component.isResource() && (<Resource>this.component).isCsarComponent()) {
- _.remove(this.$scope.editArtifactResourceModel.artifactTypes, (item:string) => {
- return this.artifactsUtils.isLicenseType(item);
- })
- }
-
- };
-
- private initEditArtifactResourceModel = ():void => {
- this.$scope.editArtifactResourceModel = {
- artifactResource: null,
- artifactTypes: null,
- artifactFile:{}
- };
-
- this.initEntity();
- };
-
- private initScope = ():void => {
-
- this.$scope.validationPattern = this.ValidationPattern;
- this.$scope.urlValidationPattern = this.UrlValidationPattern;
- this.$scope.labelValidationPattern = this.LabelValidationPattern;
- this.$scope.integerValidationPattern = this.IntegerValidationPattern;
- this.$scope.commentValidationPattern = this.CommentValidationPattern;
- this.$scope.isLoading = false;
- this.$scope.isNew = (this.formState === Utils.Constants.FormState.CREATE);
- this.$scope.artifactType = this.artifactsUtils.getArtifactTypeByState(this.$state.current.name);
- this.$scope.modalInstanceArtifact = this.$modalInstance;
-
- this.initEditArtifactResourceModel();
- this.initArtifactTypes();
-
- // In case of edit, show the file name in browse.
- if (this.artifact.artifactName!=="" && 'HEAT_ENV'!==this.artifact.artifactType){
- this.$scope.editArtifactResourceModel.artifactFile = {};
- this.$scope.editArtifactResourceModel.artifactFile.filename = this.artifact.artifactName;
- }
-
- //scope methods
- this.$scope.isDeploymentHeat = ():boolean => {
- return !this.$scope.isNew && this.$scope.artifactType === 'deployment' &&
- 'HEAT' === this.$scope.editArtifactResourceModel.artifactResource.artifactType.substring(0,4);
- };
- this.$scope.onFileChange = ():void => {
- if(this.$scope.editArtifactResourceModel.artifactFile && this.$scope.editArtifactResourceModel.artifactFile.filename) {
- this.$scope.editArtifactResourceModel.artifactResource.artifactName = this.$scope.editArtifactResourceModel.artifactFile.filename;
- } else {
- this.$scope.editArtifactResourceModel.artifactResource.artifactName = this.$scope.originalArtifactName;
- }
- };
- this.$scope.setDefaultTimeout = ():void => {
- if(this.$scope.isDeploymentHeat() && !this.$scope.editArtifactResourceModel.artifactResource.timeout) {
- this.$scope.editArtifactResourceModel.artifactResource.timeout = this.$scope.defaultHeatTimeout;
- }
- };
-
- this.$scope.fileExtensions = ():string => {
- let type:string = this.$scope.editArtifactResourceModel.artifactResource.artifactType;
- return type && this.$scope.validExtensions && this.$scope.validExtensions[type].acceptedTypes ?
- this.$scope.validExtensions[type].acceptedTypes.join(',') : "";
- };
-
- this.$scope.save = (doNotCloseModal?:boolean):void => {
- this.$scope.isLoading = true;
- this.$scope.editArtifactResourceModel.artifactResource.description = this.ValidationUtils.stripAndSanitize(this.$scope.editArtifactResourceModel.artifactResource.description);
-
- if (!this.$scope.isDeploymentHeat()) {
- this.$scope.editArtifactResourceModel.artifactResource.timeout = null;
- }
-
- if (this.$scope.editArtifactResourceModel.artifactFile) {
- this.$scope.editArtifactResourceModel.artifactResource.payloadData = this.$scope.editArtifactResourceModel.artifactFile.base64;
- this.$scope.editArtifactResourceModel.artifactResource.artifactName = this.$scope.editArtifactResourceModel.artifactFile.filename;
- }
-
- let onFaild = (response):void => {
- this.$scope.isLoading = false;
- console.info('onFaild', response);
- };
-
- let onSuccess = (artifactResource:Models.ArtifactModel):void => {
- this.$scope.isLoading = false;
- this.$scope.originalArtifactName = "";
-
- if(this.$scope.isDeploymentHeat()){
- if(artifactResource.heatParameters) {
- this.$scope.openEditEnvParametersModal(artifactResource);
- }
- }
-
- if (!doNotCloseModal) {
- this.$modalInstance.close();
- //this.artifactArr = [];
- } else {
- this.$scope.editArtifactResourceModel.artifactFile = null;
- angular.element("input[type='file']").val(null); // for support chrome when upload the same file
- this.artifactsUtils.addAnotherAfterSave(this.$scope);
- }
-
- };
-
- if('HEAT_ENV' == this.artifact.artifactType){
- this.component.uploadInstanceEnvFile(this.$scope.editArtifactResourceModel.artifactResource).then(onSuccess, onFaild);
- }else if(this.$scope.isArtifactOwner()){
- this.component.addOrUpdateInstanceArtifact(this.$scope.editArtifactResourceModel.artifactResource).then(onSuccess, onFaild);
- }else {
- this.component.addOrUpdateArtifact(this.$scope.editArtifactResourceModel.artifactResource).then(onSuccess, onFaild);
- }
- };
-
- this.$scope.isArtifactOwner = ():boolean=> {
- return this.component.isService() && !!this.component.selectedInstance;
- };
-
- this.$scope.saveAndAnother = ():void => {
- this.$scope.save(true);
- };
-
- this.$scope.close = ():void => {
- this.$modalInstance.close();
- this.artifactArr = [];
- };
-
- this.$scope.fileUploadRequired = ():string => {
- if (this.$scope.editArtifactResourceModel.artifactFile.filename){
- // This is edit mode
- return 'false';
- } else {
- return 'true';
- }
- };
-
- this.$scope.getFormTitle =(): string =>{
- if('HEAT_ENV' == this.artifact.artifactType){
- return 'Update HEAT ENV';
- }
- if(this.$scope.isDeploymentHeat()){
- if(!this.$scope.editArtifactResourceModel.artifactResource.artifactChecksum){
- return 'Add HEAT Template';
- }
- return 'Update HEAT Template';
- }
- if(this.$scope.isNew){
- return 'Add Artifact';
- }
- return 'Update Artifact';
- };
-
- this.$scope.openEditEnvParametersModal = (artifactResource:Models.ArtifactModel):void => {
-
- let modalOptions:ng.ui.bootstrap.IModalSettings = {
- template: this.$templateCache.get('/app/scripts/view-models/forms/env-parameters-form/env-parameters-form.html'),
- controller: 'Sdc.ViewModels.EnvParametersFormViewModel',
- size: 'sdc-md',
- backdrop: 'static',
- resolve: {
- artifact: ():Models.ArtifactModel => {
- return artifactResource;
- },
- component: ():Models.Components.Component => {
- return this.component;
- }
- }
- };
-
- let modalInstance:ng.ui.bootstrap.IModalServiceInstance = this.$modal.open(modalOptions);
- modalInstance
- .result
- .then(():void => {
- });
- };
-
- this.$scope.forms = {};
-
- this.initFooterButtons();
-
-
- this.$scope.$watch("forms.editForm.$invalid", (newVal, oldVal) => {
- this.$scope.footerButtons[0].disabled = this.$scope.forms.editForm.$invalid;
- if(this.$scope.isNew){
- this.$scope.footerButtons[1].disabled = this.$scope.forms.editForm.$invalid;
- }
- });
-
- }
-
- }
-}
diff --git a/catalog-ui/app/scripts/view-models/forms/attribute-form/attribute-from-view-model.ts b/catalog-ui/app/scripts/view-models/forms/attribute-form/attribute-from-view-model.ts
deleted file mode 100644
index d369cfa5d1..0000000000
--- a/catalog-ui/app/scripts/view-models/forms/attribute-form/attribute-from-view-model.ts
+++ /dev/null
@@ -1,255 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../../references"/>
-
-module Sdc.ViewModels {
- 'use strict';
-
- export interface IEditAttributeModel {
- attribute: Models.AttributeModel;
- types: Array<string>;
- simpleTypes: Array<string>;
- }
-
- interface IAttributeFormViewModelScope extends ng.IScope {
- $$childTail: any;
- forms:any;
- editForm:ng.IFormController;
- footerButtons: Array<any>;
- isService: boolean;
- editAttributeModel: IEditAttributeModel;
- modalInstanceAttribute:ng.ui.bootstrap.IModalServiceInstance;
- isNew: boolean;
- listRegex: Sdc.Utils.IMapRegex;
- mapRegex: Sdc.Utils.IMapRegex;
- propertyNameValidationPattern: RegExp;
- commentValidationPattern: RegExp;
- isLoading: boolean;
- validationPattern: RegExp;
-
- save():void;
- close(): void;
- onTypeChange():void;
- onValueChange(): void;
- isAttributeValueOwner():boolean;
- validateIntRange(value:string):boolean;
- validateUniqueKeys(viewValue:string):boolean;
- getValidationTranslate(): string;
- showSchema(): boolean;
- isSchemaEditable(): boolean;
- validateName():void;
- }
-
- export class AttributeFormViewModel {
-
- static '$inject' = [
- '$scope',
- '$modalInstance',
- 'attribute',
- 'ValidationUtils',
- 'CommentValidationPattern',
- 'PropertyNameValidationPattern',
- 'component'
- ];
-
- private formState: Sdc.Utils.Constants.FormState;
-
-
- constructor(private $scope:IAttributeFormViewModelScope,
- private $modalInstance:ng.ui.bootstrap.IModalServiceInstance,
- private attribute: Models.AttributeModel,
- private ValidationUtils:Sdc.Utils.ValidationUtils,
- private CommentValidationPattern:RegExp,
- private PropertyNameValidationPattern: RegExp,
- private component: Models.Components.Component) {
- this.formState = angular.isDefined(attribute.name) ? Utils.Constants.FormState.UPDATE : Utils.Constants.FormState.CREATE;
- this.initScope();
- }
-
- private initResource = ():void => {
- this.$scope.editAttributeModel.attribute = new Sdc.Models.AttributeModel(this.attribute);
- if (this.$scope.editAttributeModel.types.indexOf(this.attribute.type) === -1) {//attribute defaulte type is string too?
- this.attribute.type = "string";
- }
- };
-
- private initEditAttributeModel = ():void => {
- this.$scope.editAttributeModel = {
- attribute: null,
- types: ['integer', 'string', 'float', 'boolean', 'list', 'map'],
- simpleTypes: ['integer', 'string', 'float', 'boolean']
- };
-
- this.initResource();
- };
-
- private initScope = ():void => {
-
- //scope attributes
- this.$scope.forms = {};
- this.$scope.propertyNameValidationPattern = this.PropertyNameValidationPattern;
- this.$scope.commentValidationPattern = this.CommentValidationPattern;
-
- this.$scope.modalInstanceAttribute = this.$modalInstance;
- this.$scope.listRegex = this.ValidationUtils.getPropertyListPatterns();
- this.$scope.mapRegex = this.ValidationUtils.getPropertyMapPatterns();
-
- this.$scope.isNew = (this.formState === Utils.Constants.FormState.CREATE);
- this.$scope.isLoading = false;
-
- this.initEditAttributeModel();
- this.setValidationPattern();
-
- //scope methods
- this.$scope.save = ():void => {
- if(!this.$scope.forms.editForm.$invalid){
- let attribute:Models.AttributeModel = this.$scope.editAttributeModel.attribute;
- this.$scope.editAttributeModel.attribute.description = this.ValidationUtils.stripAndSanitize(this.$scope.editAttributeModel.attribute.description);
- ////if read only - just closes the modal
- if (this.$scope.editAttributeModel.attribute.readonly && !this.$scope.isAttributeValueOwner()) {
- this.$modalInstance.close();
- return;
- }
- this.$scope.isLoading = true;
- let onAttributeFaild = (response):void => {
- console.info('onFaild', response);
- this.$scope.isLoading = false;
- };
-
- let onAttributeSuccess = (attributeFromBE:Models.AttributeModel):void => {
- console.info('onAttributeResourceSuccess : ', attributeFromBE);
- this.$scope.isLoading = false;
- this.$modalInstance.close();
- };
-
- //in case we have uniqueId we call update method
- if (this.$scope.isAttributeValueOwner()) {
- this.component.updateInstanceAttribute(attribute).then(onAttributeSuccess, onAttributeFaild);
- } else {
- this.component.addOrUpdateAttribute(attribute).then(onAttributeSuccess, onAttributeFaild);
- }
- }
- };
-
- this.$scope.close = ():void => {
- this.$modalInstance.close();
- };
-
- this.$scope.validateName = ():void => {
- let existsAttr: Models.AttributeModel = _.find(this.component.attributes, (attribute:Models.AttributeModel) => {
- return attribute.name === this.$scope.editAttributeModel.attribute.name;
- });
- if(existsAttr){
- this.$scope.forms.editForm["attributeName"].$setValidity('nameExist', false);
- }else{
- this.$scope.forms.editForm["attributeName"].$setValidity('nameExist', true);
- }
-
- };
-
- this.$scope.onTypeChange = ():void => {
- this.$scope.editAttributeModel.attribute.value = '';
- this.$scope.editAttributeModel.attribute.defaultValue = '';
- this.setValidationPattern();
- };
-
- this.$scope.isAttributeValueOwner = ():boolean=> {
- return this.component.isService() || !!this.component.selectedInstance;
- };
-
- this.$scope.onValueChange = ():void => {
- if (!this.$scope.editAttributeModel.attribute.value) {
- if (this.$scope.isAttributeValueOwner()) {
- this.$scope.editAttributeModel.attribute.value = this.$scope.editAttributeModel.attribute.defaultValue;
- }
- }
- };
-
-
- this.$scope.validateUniqueKeys = (viewValue:string) : boolean => {
- if(this.$scope.editAttributeModel.attribute.type === 'map') {
- return this.ValidationUtils.validateUniqueKeys(viewValue);
- }
- else {
- return true; //always valid if not a map
- }
- };
-
- this.$scope.validateIntRange = (value:string):boolean => {
- return !value || this.ValidationUtils.validateIntRange(value);
- };
-
- this.$scope.isSchemaEditable = () :boolean => {
- let schemaType=this.$scope.editAttributeModel.attribute.schema.property.type;
- return this.$scope.editAttributeModel.simpleTypes.indexOf(schemaType) > -1||!schemaType;
- };
-
- this.$scope.showSchema = () :boolean => {
- return ['list', 'map'].indexOf(this.$scope.editAttributeModel.attribute.type) > -1;
- };
-
- this.$scope.getValidationTranslate = () : string => {
- let result = "ATTRIBUTE_EDIT_PATTERN";
- if (this.$scope.showSchema()) {
-
- result = "ATTRIBUTE_EDIT_" + this.$scope.editAttributeModel.attribute.type.toUpperCase();
-
- if(this.$scope.editAttributeModel.attribute.schema.property.type === Utils.Constants.PROPERTY_TYPES.STRING) {
- result += "_STRING";
- }else if(this.$scope.editAttributeModel.attribute.schema.property.type === Utils.Constants.PROPERTY_TYPES.BOOLEAN) {
- result += "_BOOLEAN";
- } else {
- result += "_GENERIC";
- }
- }
-
- return result;
- };
-
- // Add the done button at the footer.
- this.$scope.footerButtons = [
- {'name': 'Done', 'css':'blue', 'callback': this.$scope.save},
- {'name':'Cancel', 'css':'grey', 'callback': this.$scope.close}
- ];
-
- this.$scope.$watchCollection("forms.editForm.$invalid", (newVal, oldVal) => {
- this.$scope.footerButtons[0].disabled = this.$scope.forms.editForm.$invalid;
- });
-
- }
-
-
- private setValidationPattern = ():void => {
-
- if(this.$scope.editAttributeModel.attribute.type === 'list') {
- this.$scope.validationPattern = this.$scope.listRegex[this.$scope.editAttributeModel.attribute.schema.property.type];
- }
- else if(this.$scope.editAttributeModel.attribute.type === 'map') {
- this.$scope.validationPattern = this.$scope.mapRegex[this.$scope.editAttributeModel.attribute.schema.property.type];
- }
- else{
- this.$scope.validationPattern = this.ValidationUtils.getValidationPattern(this.$scope.editAttributeModel.attribute.type);
- }
-
- };
-
-
- }
-}
diff --git a/catalog-ui/app/scripts/view-models/forms/env-parameters-form/env-parameters-form.html b/catalog-ui/app/scripts/view-models/forms/env-parameters-form/env-parameters-form.html
deleted file mode 100644
index 69367dc68c..0000000000
--- a/catalog-ui/app/scripts/view-models/forms/env-parameters-form/env-parameters-form.html
+++ /dev/null
@@ -1,39 +0,0 @@
-<sdc-modal modal="envParametersModal" type="classic" class="sdc-env-form-container" buttons="saveButton" header="{{isInstance()?'HEAT Template':'Update Parameters'}}" show-close-button="true">
- <div class="sdc-env-form-container">
- <div class="w-sdc-modal-body">
- <span class="w-sdc-modal-body-content" data-ng-if="!isInstance()" translate="UPDATE_PARAMETERS_TEXT"></span>
- <form novalidate class="" name="editForm">
- <perfect-scrollbar class="perfect-scrollbar w-sdc-form w-sdc-env-form-container">
- <div class="i-sdc-form-item" data-ng-repeat="parameter in heatParameters track by $index">
- <div class="left-column-container">
- <ng-form name="editForm">
- <label class="i-sdc-env-form-label" data-ng-class="{required:parameter.defaultValue}"
- data-ng-bind="parameter.name +' (' + parameter.type + ')'" tooltips tooltip-content="{{parameter.name +' (' + parameter.type + ')'}}"></label>
- <input class="i-sdc-form-input" data-ng-class="{error:(editForm.currentValue.$invalid)}"
- data-ng-model-options="{ debounce: 200 }"
- data-ng-model="parameter.currentValue"
- type="text"
- name="currentValue"
- data-ng-pattern="getValidationPattern(parameter.type, 'heat')"
- data-ng-required="parameter.defaultValue"
- data-ng-change="'json'==parameter.type && editForm.currentValue.$setValidity('pattern', validateJson(parameter.currentValue))"
- data-ng-blur="(editForm.currentValue.$error.required && (parameter.currentValue=parameter.defaultValue))"
- />
-
- <div class="input-error" data-ng-show="editForm.currentValue.$invalid">
- <span ng-show="editForm.currentValue.$error.required" translate="VALIDATION_ERROR_REQUIRED" translate-values="{'field': 'Value'}"></span>
- <span ng-show="editForm.currentValue.$error.pattern && parameter.type==='string'" translate="VALIDATION_ERROR_SPECIAL_CHARS_NOT_ALLOWED"></span>
- <span ng-show="editForm.currentValue.$error.pattern && !(parameter.type==='string')" translate="VALIDATION_ERROR_TYPE" translate-values="{'type': '{{parameter.type}}'}"></span>
- </div>
- </ng-form>
- </div>
- <div class="i-sdc-env-form-label-description">
- <label class="i-sdc-env-form-label" data-ng-bind="parameter.description" tooltips tooltip-content="{{parameter.description}}"></label>
- </div>
- </div>
- </perfect-scrollbar>
- <div class="env-file-generation-label" data-ng-if="isInstance()" translate="ENV_FILE_GENERATION"></div>
- </form>
- </div>
- </div>
-</sdc-modal>
diff --git a/catalog-ui/app/scripts/view-models/forms/env-parameters-form/env-parameters-form.less b/catalog-ui/app/scripts/view-models/forms/env-parameters-form/env-parameters-form.less
deleted file mode 100644
index c58c94ab22..0000000000
--- a/catalog-ui/app/scripts/view-models/forms/env-parameters-form/env-parameters-form.less
+++ /dev/null
@@ -1,74 +0,0 @@
-
-.sdc-env-form-container{
- .w-sdc-modal-body{
- padding: 20px 10px 2px 10px;
- }
- .w-sdc-modal-body-content{
- .b_6;
- display: block;
- }
-
- .env-file-generation-label{
- .p_9;
- .bold;
- margin-bottom: 20px;
- }
-}
-
-.w-sdc-env-form-container {
- border-top: 1px solid #cdcdcd;
- border-bottom: 1px solid #cdcdcd;
- height: 356px;
- margin: 35px 0 10px 0;
-
- .w-sdc-form {
- text-align: left;
- }
- .i-sdc-form-item{
- display: inline-block;
- .description{
- margin-bottom: 2px;
- vertical-align: baseline;
- padding: 32px 0 0 0;
- text-transform: capitalize;
- .b_1;
- }
- }
- .left-column-container{
- width: 250px;
- float: left;
- .i-sdc-env-form-label {
- overflow: hidden;
- max-width: 100%;
- text-overflow: ellipsis;
- display: inline-block;
- white-space: nowrap;
-
- &.required::before {
- color: #f33;
- content: '*';
- margin-right: 4px;
- }
- }
- }
- .i-sdc-env-form-label-description {
- float: right;
-
- .i-sdc-env-form-label {
- .p_9;
- // height: 20px;
- margin: 30px 0px 0px 30px;
- overflow: hidden;
- max-width: 245px;
- text-overflow: ellipsis;
- display: inline-block;
- white-space: nowrap;
-
- &.required::before {
- color: #f33;
- content: '*';
- margin-right: 4px;
- }
- }
- }
-}
diff --git a/catalog-ui/app/scripts/view-models/forms/env-parameters-form/env-parameters-form.ts b/catalog-ui/app/scripts/view-models/forms/env-parameters-form/env-parameters-form.ts
deleted file mode 100644
index d1bae440cc..0000000000
--- a/catalog-ui/app/scripts/view-models/forms/env-parameters-form/env-parameters-form.ts
+++ /dev/null
@@ -1,149 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../../references"/>
-
-module Sdc.ViewModels {
- 'use strict';
-
- export interface IEnvParametersFormViewModelScope extends ng.IScope {
- isLoading: boolean;
- type:string;
- heatParameters:any;
- editForm:ng.IFormController;
- artifactResource:Models.ArtifactModel;
- saveButton: Array<any>;
- envParametersModal: ng.ui.bootstrap.IModalServiceInstance;
-
- getValidationPattern(type:string):RegExp;
- isInstance():boolean;
- validateJson(json:string):boolean;
- close(): void;
- save():void;
- }
-
- export class EnvParametersFormViewModel {
-
-
- static '$inject' = [
- '$scope',
- '$state',
- '$modalInstance',
- 'artifact',
- // 'ArtifactsUtils',
- 'ValidationUtils',
- 'component'
- ];
-
-
- constructor(private $scope:IEnvParametersFormViewModelScope,
- private $state:any,
- private $modalInstance:ng.ui.bootstrap.IModalServiceInstance,
- private artifact:Models.ArtifactModel,
- // private artifactsUtils:Sdc.Utils.ArtifactsUtils,
- private ValidationUtils: Sdc.Utils.ValidationUtils,
- private component:Models.Components.Component) {
-
-
- this.initScope();
- }
-
- private updateInstanceHeat = ():void => {
- let success =(responseArtifact:Models.ArtifactModel): void => {
- this.$scope.isLoading = false;
- this.$modalInstance.close();
- };
-
- let error = ():void => {
- this.$scope.isLoading = false;
- console.info('Failed to load save artifact');
- };
-
- this.component.addOrUpdateInstanceArtifact(this.$scope.artifactResource).then(success, error);
-
- };
-
- private initScope = ():void => {
- this.$scope.envParametersModal = this.$modalInstance;
- this.$scope.artifactResource= this.artifact;
- this.$scope.heatParameters = angular.copy(this.artifact.heatParameters);
-
- this.$scope.getValidationPattern = (validationType:string , parameterType?:string):RegExp => {
- return this.ValidationUtils.getValidationPattern(validationType, parameterType);
- };
-
- this.$scope.validateJson = (json:string):boolean => {
- if(!json){
- return true;
- }
- return this.ValidationUtils.validateJson(json);
- };
-
- this.$scope.isInstance =(): boolean =>{
- return !!this.component.selectedInstance;
- };
-
-
- this.$scope.save = ():void => {
- this.$scope.isLoading = true;
- this.artifact.heatParameters = this.$scope.heatParameters;
- this.artifact.heatParameters.forEach((parameter:any):void => {
- /* if ("" === parameter.currentValue) {
- parameter.currentValue = null;
- }else */
- if(!parameter.currentValue && parameter.defaultValue) {
- parameter.currentValue = parameter.defaultValue;
- }
- });
-
- if(this.$scope.isInstance()){
- this.updateInstanceHeat();
- return;
- }
-
- let success =(responseArtifact:Models.ArtifactModel): void => {
- this.$scope.isLoading = false;
- this.$modalInstance.close();
-
- };
-
- let error = ():void => {
- this.$scope.isLoading = false;
- console.info('Failed to load save artifact');
- };
-
- this.component.addOrUpdateArtifact(this.$scope.artifactResource).then(success, error);
- };
-
- this.$scope.saveButton = [
- {'name': 'Save', 'css': 'blue', 'callback': this.$scope.save}
- ];
-
- this.$scope.close = ():void => {
- //this.artifact.heatParameters.forEach((parameter:any):void => {
- // if (!parameter.currentValue && parameter.defaultValue) {
- // parameter.currentValue = parameter.defaultValue;
- // }
- //});
- this.$modalInstance.dismiss();
- };
-
- };
- }
-}
diff --git a/catalog-ui/app/scripts/view-models/forms/property-form/property-form-view-model.ts b/catalog-ui/app/scripts/view-models/forms/property-form/property-form-view-model.ts
deleted file mode 100644
index c9732aa9a6..0000000000
--- a/catalog-ui/app/scripts/view-models/forms/property-form/property-form-view-model.ts
+++ /dev/null
@@ -1,330 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../../references"/>
-
-module Sdc.ViewModels {
- 'use strict';
-
- export interface IEditPropertyModel {
- property: Models.PropertyModel;
- types: Array<string>;
- simpleTypes: Array<string>;
- sources: Array<string>;
- }
-
- interface IPropertyFormViewModelScope extends ng.IScope {
- forms:any;
- editForm:ng.IFormController;
- footerButtons: Array<any>;
- isNew: boolean;
- isLoading: boolean;
- isService: boolean;
- validationPattern: RegExp;
- propertyNameValidationPattern: RegExp;
- commentValidationPattern: RegExp;
- editPropertyModel: IEditPropertyModel;
- modalInstanceProperty:ng.ui.bootstrap.IModalServiceInstance;
- currentPropertyIndex:number;
- isLastProperty:boolean;
- myValue:any;
- nonPrimitiveTypes:Array<string>;
- dataTypes:Models.DataTypesMap;
- isTypeDataType:boolean;
- maxLength:number;
-
- save(doNotCloseModal?:boolean): void;
- getValidationPattern(type:string): RegExp;
- validateIntRange(value:string):boolean;
- close(): void;
- onValueChange(): void;
- onSchemaTypeChange():void;
- onTypeChange(resetSchema:boolean): void;
- isPropertyValueOwner():boolean;
- showSchema(): boolean;
- delete(property:Models.PropertyModel): void;
- getPrev(): void;
- getNext(): void;
- isSimpleType(typeName:string):boolean;
- getDefaultValue():any;
- }
-
- export class PropertyFormViewModel {
-
- static '$inject' = [
- '$scope',
- 'Sdc.Services.DataTypesService',
- '$modalInstance',
- 'property',
- 'ValidationPattern',
- 'PropertyNameValidationPattern',
- 'CommentValidationPattern',
- 'ValidationUtils',
- 'component',
- '$filter',
- 'ModalsHandler',
- 'filteredProperties',
- '$timeout'
- ];
-
- private formState: Sdc.Utils.Constants.FormState;
-
- constructor(private $scope:IPropertyFormViewModelScope,
- private DataTypesService:Sdc.Services.DataTypesService,
- private $modalInstance:ng.ui.bootstrap.IModalServiceInstance,
- private property: Models.PropertyModel,
- private ValidationPattern:RegExp,
- private PropertyNameValidationPattern: RegExp,
- private CommentValidationPattern:RegExp,
- private ValidationUtils:Sdc.Utils.ValidationUtils,
- private component: Models.Components.Component,
- private $filter:ng.IFilterService,
- private ModalsHandler:Utils.ModalsHandler,
- private filteredProperties: Array<Models.PropertyModel>,
- private $timeout: ng.ITimeoutService) {
-
- this.formState = angular.isDefined(property.name) ? Utils.Constants.FormState.UPDATE : Utils.Constants.FormState.CREATE;
- this.initScope();
- }
-
- private initResource = ():void => {
- this.$scope.editPropertyModel.property = new Sdc.Models.PropertyModel(this.property);
- this.$scope.editPropertyModel.property.type = this.property.type? this.property.type: null;
- this.setMaxLength();
- // if (this.$scope.editPropertyModel.types.indexOf(this.property.type) === -1 && !this.$scope.isNew) {
- // this.property.type = "string";
- // }
- };
-
- private initEditPropertyModel = ():void => {
- this.$scope.editPropertyModel = {
- property: null,
- types: Utils.Constants.PROPERTY_DATA.TYPES,
- simpleTypes: Utils.Constants.PROPERTY_DATA.SIMPLE_TYPES,
- sources: Utils.Constants.PROPERTY_DATA.SOURCES
- };
-
- this.initResource();
- };
-
- private initForNotSimpleType = ():void => {
- let property = this.$scope.editPropertyModel.property;
- this.$scope.isTypeDataType=this.DataTypesService.isDataTypeForPropertyType(this.$scope.editPropertyModel.property,this.$scope.dataTypes);
- if(property.type && this.$scope.editPropertyModel.simpleTypes.indexOf(property.type)==-1){
- if(!(property.value||property.defaultValue)) {
- switch (property.type) {
- case Utils.Constants.PROPERTY_TYPES.MAP:
- this.$scope.myValue = {'':null};
- break;
- case Utils.Constants.PROPERTY_TYPES.LIST:
- this.$scope.myValue = [];
- break;
- default:
- this.$scope.myValue = {};
- }
- }else{
- this.$scope.myValue = JSON.parse(property.value||property.defaultValue);
- }
- }
- };
-
- private setMaxLength = ():void => {
- switch (this.$scope.editPropertyModel.property.type) {
- case Utils.Constants.PROPERTY_TYPES.MAP:
- case Utils.Constants.PROPERTY_TYPES.LIST:
- this.$scope.maxLength = this.$scope.editPropertyModel.property.schema.property.type == Utils.Constants.PROPERTY_TYPES.JSON?
- Utils.Constants.PROPERTY_VALUE_CONSTRAINTS.JSON_MAX_LENGTH:
- Utils.Constants.PROPERTY_VALUE_CONSTRAINTS.MAX_LENGTH;
- break;
- case Utils.Constants.PROPERTY_TYPES.JSON:
- this.$scope.maxLength = Utils.Constants.PROPERTY_VALUE_CONSTRAINTS.JSON_MAX_LENGTH;
- break;
- default:
- this.$scope.maxLength = Utils.Constants.PROPERTY_VALUE_CONSTRAINTS.MAX_LENGTH;
- }
- };
-
-
- private initScope = ():void => {
-
- //scope properties
- this.$scope.forms = {};
- this.$scope.validationPattern = this.ValidationPattern;
- this.$scope.propertyNameValidationPattern = this.PropertyNameValidationPattern;
- this.$scope.commentValidationPattern = this.CommentValidationPattern;
- this.$scope.isLoading = false;
- this.$scope.isNew = (this.formState === Utils.Constants.FormState.CREATE);
- this.$scope.isService = this.component.isService();
- this.$scope.modalInstanceProperty = this.$modalInstance;
- this.$scope.currentPropertyIndex = _.findIndex(this.filteredProperties, i=> i.name == this.property.name );
- this.$scope.isLastProperty= this.$scope.currentPropertyIndex==(this.filteredProperties.length-1);
-
- this.initEditPropertyModel();
-
- this.DataTypesService.getAllDataTypes().then((response:any) => {
- this.$scope.dataTypes = response;
- delete response['tosca.datatypes.Root'];
- this.$scope.nonPrimitiveTypes =_.filter(Object.keys(response),(type:string)=>{
- return this.$scope.editPropertyModel.types.indexOf(type)==-1;
- });
- this.initForNotSimpleType();
- }, (err)=> {});
-
-
-
-
-
- //scope methods
- this.$scope.save = (doNotCloseModal?:boolean):void => {
- let property:Models.PropertyModel = this.$scope.editPropertyModel.property;
- this.$scope.editPropertyModel.property.description = this.ValidationUtils.stripAndSanitize(this.$scope.editPropertyModel.property.description);
- ////if read only - just closes the modal
- if (this.$scope.editPropertyModel.property.readonly && !this.$scope.isPropertyValueOwner()) {
- this.$modalInstance.close();
- return;
- }
-
- this.$scope.isLoading = true;
-
- let onPropertyFaild = (response):void => {
- console.info('onFaild', response);
- this.$scope.isLoading = false;
- };
-
- let onPropertySuccess = (propertyFromBE:Models.PropertyModel):void => {
- console.info('onPropertyResourceSuccess : ', propertyFromBE);
- this.$scope.isLoading = false;
-
- if (!doNotCloseModal) {
- this.$modalInstance.close();
- } else {
- this.$scope.forms.editForm.$setPristine();
- this.$scope.editPropertyModel.property = new Models.PropertyModel();
- }
- };
-
- //in case we have uniqueId we call update method
- if (this.$scope.isPropertyValueOwner()) {
- if(!this.$scope.editPropertyModel.property.simpleType && !this.$scope.isSimpleType(property.type)){
- let myValueString:string = JSON.stringify(this.$scope.myValue);
- property.value = myValueString;
- }
- this.component.updateInstanceProperty(property).then(onPropertySuccess, onPropertyFaild);
- } else {
- if(!this.$scope.editPropertyModel.property.simpleType && !this.$scope.isSimpleType(property.type)){
- let myValueString:string = JSON.stringify(this.$scope.myValue);
- property.defaultValue = myValueString;
- }else{
- this.$scope.editPropertyModel.property.defaultValue = this.$scope.editPropertyModel.property.value;
- }
- this.component.addOrUpdateProperty(property).then(onPropertySuccess, onPropertyFaild);
- }
- };
-
-
- this.$scope.isPropertyValueOwner = ():boolean=> {
- return this.component.isService() || !!this.component.selectedInstance;
- };
-
- this.$scope.getPrev = ():void=> {
- this.property = this.filteredProperties[--this.$scope.currentPropertyIndex];
- this.initResource();
- this.initForNotSimpleType();
- this.$scope.isLastProperty=false;
- };
-
- this.$scope.getNext = ():void=> {
- this.property = this.filteredProperties[++this.$scope.currentPropertyIndex];
- this.initResource();
- this.initForNotSimpleType();
- this.$scope.isLastProperty= this.$scope.currentPropertyIndex==(this.filteredProperties.length-1);
- };
-
- this.$scope.isSimpleType = (typeName:string):boolean=>{
- return typeName && this.$scope.editPropertyModel.simpleTypes.indexOf(typeName)!=-1;
- };
-
- this.$scope.showSchema = () :boolean => {
- return [Utils.Constants.PROPERTY_TYPES.LIST, Utils.Constants.PROPERTY_TYPES.MAP].indexOf(this.$scope.editPropertyModel.property.type) > -1;
- };
-
- this.$scope.getValidationPattern = (type:string):RegExp => {
- return this.ValidationUtils.getValidationPattern(type);
- };
-
- this.$scope.validateIntRange = (value:string):boolean => {
- return !value || this.ValidationUtils.validateIntRange(value);
- };
-
- this.$scope.close = ():void => {
- this.$modalInstance.close();
- };
-
- // put default value when instance value is empty
- this.$scope.onValueChange = ():void => {
- if (!this.$scope.editPropertyModel.property.value) {
- if (this.$scope.isPropertyValueOwner()) {
- this.$scope.editPropertyModel.property.value = this.$scope.editPropertyModel.property.defaultValue;
- }
- }
- };
-
- // Add the done button at the footer.
- this.$scope.footerButtons = [
- {'name': 'Save', 'css': 'blue', 'callback': this.$scope.save },
- {'name': 'Cancel', 'css': 'grey', 'callback':this.$scope.close }
- ];
-
- this.$scope.$watch("forms.editForm.$invalid", (newVal, oldVal) => {
- this.$scope.footerButtons[0].disabled = this.$scope.forms.editForm.$invalid;
- });
-
- this.$scope.getDefaultValue = ():any => {
- return this.$scope.isPropertyValueOwner() ? this.$scope.editPropertyModel.property.defaultValue : null;
- };
-
- this.$scope.onTypeChange = ():void => {
- this.$scope.editPropertyModel.property.value = '';
- this.$scope.editPropertyModel.property.defaultValue = '';
- this.setMaxLength();
- this.initForNotSimpleType();
- };
-
- this.$scope.onSchemaTypeChange = ():void => {
- if(this.$scope.editPropertyModel.property.type==Utils.Constants.PROPERTY_TYPES.MAP){
- this.$scope.myValue={'':null};
- }else if(this.$scope.editPropertyModel.property.type==Utils.Constants.PROPERTY_TYPES.LIST){
- this.$scope.myValue=[];
- }
- this.setMaxLength();
- };
-
- this.$scope.delete = (property:Models.PropertyModel):void => {
- let onOk = ():void => {
- this.component.deleteProperty(property.uniqueId).then(
- this.$scope.close
- );
- };
- let title:string = this.$filter('translate')("PROPERTY_VIEW_DELETE_MODAL_TITLE");
- let message:string = this.$filter('translate')("PROPERTY_VIEW_DELETE_MODAL_TEXT", "{'name': '" + property.name + "'}");
- this.ModalsHandler.openConfirmationModal(title, message, false).then(onOk);
- };
- }
- }
-}
diff --git a/catalog-ui/app/scripts/view-models/forms/resource-instance-name-form/resource-instance-name-model.ts b/catalog-ui/app/scripts/view-models/forms/resource-instance-name-form/resource-instance-name-model.ts
deleted file mode 100644
index b69bf4a2a6..0000000000
--- a/catalog-ui/app/scripts/view-models/forms/resource-instance-name-form/resource-instance-name-model.ts
+++ /dev/null
@@ -1,105 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../../references"/>
-
-module Sdc.ViewModels {
- 'use strict';
-
- interface IResourceInstanceViewModelScope extends ng.IScope {
-
- componentInstanceModel: Sdc.Models.ComponentsInstances.ComponentInstance;
- validationPattern: RegExp;
- oldName:string;
- isAlreadyPressed:boolean;
- footerButtons: Array<any>;
- forms:any;
- modalInstanceName:ng.ui.bootstrap.IModalServiceInstance;
-
- save(): void;
- close(): void;
- }
-
- export class ResourceInstanceNameViewModel {
-
- static '$inject' = [
- '$scope',
- 'ValidationPattern',
- '$modalInstance',
- 'ComponentInstanceFactory',
- 'component'
- ];
-
-
- constructor(private $scope:IResourceInstanceViewModelScope,
- private ValidationPattern:RegExp,
- private $modalInstance:ng.ui.bootstrap.IModalServiceInstance,
- private ComponentInstanceFactory:Utils.ComponentInstanceFactory,
- private component:Models.Components.Component) {
-
- this.initScope();
- }
-
-
- private initScope = ():void => {
- this.$scope.forms = {};
- this.$scope.validationPattern = this.ValidationPattern;
- this.$scope.componentInstanceModel = Utils.ComponentInstanceFactory.createComponentInstance(this.component.selectedInstance);
- this.$scope.oldName = this.component.selectedInstance.name;
- this.$scope.modalInstanceName = this.$modalInstance;
-
- this.$scope.isAlreadyPressed = false;
-
-
- this.$scope.close = ():void => {
- this.$modalInstance.dismiss();
- };
-
- this.$scope.save = ():void => {
-
- let onFailed = () => {
- this.$scope.isAlreadyPressed = true;
- };
-
- let onSuccess = (componentInstance:Models.ComponentsInstances.ComponentInstance) => {
- this.$modalInstance.close();
- this.$scope.isAlreadyPressed = false;
- this.$scope.componentInstanceModel = componentInstance;
- //this.component.name = componentInstance.name;//DE219124
- this.component.selectedInstance.name = componentInstance.name;
-
- };
-
- this.$scope.isAlreadyPressed = true;
- if (this.$scope.oldName != this.$scope.componentInstanceModel.name) {
- this.component.updateComponentInstance(this.$scope.componentInstanceModel).then(onSuccess, onFailed);
- }
- };
-
- this.$scope.footerButtons = [
- {'name': 'OK', 'css': 'blue', 'callback': this.$scope.save, 'disabled': (!this.$scope.componentInstanceModel.name || this.$scope.componentInstanceModel.name === this.$scope.oldName) || this.$scope.isAlreadyPressed},
- {'name': 'Cancel', 'css': 'grey', 'callback': this.$scope.close}
- ];
-
- this.$scope.$watch("forms.editNameForm.$invalid", (newVal, oldVal) => {
- this.$scope.footerButtons[0].disabled = this.$scope.forms.editNameForm.$invalid;
- });
- }
- }
-}
diff --git a/catalog-ui/app/scripts/view-models/modals/confirmation-modal/confirmation-modal-view-model.ts b/catalog-ui/app/scripts/view-models/modals/confirmation-modal/confirmation-modal-view-model.ts
deleted file mode 100644
index f906593d8a..0000000000
--- a/catalog-ui/app/scripts/view-models/modals/confirmation-modal/confirmation-modal-view-model.ts
+++ /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=========================================================
- */
-/// <reference path="../../../references"/>
-module Sdc.ViewModels {
- 'use strict';
-
- export interface IConfirmationModalModel {
- title: string;
- message: string;
- showComment: boolean;
- type: Utils.Constants.ModalType;
- }
-
- interface IConfirmationModalViewModelScope {
- modalInstanceConfirmation:ng.ui.bootstrap.IModalServiceInstance;
- confirmationModalModel: IConfirmationModalModel;
- comment: any;
- commentValidationPattern:RegExp;
- editForm:ng.IFormController;
- okButtonColor: string;
- hideCancelButton: boolean;
- ok(): any;
- cancel(): void;
- }
-
- export class ConfirmationModalViewModel {
-
- static '$inject' = ['$scope', '$modalInstance', 'confirmationModalModel', 'CommentValidationPattern', 'ValidationUtils', '$templateCache', '$modal'];
-
- constructor(private $scope:IConfirmationModalViewModelScope,
- private $modalInstance:ng.ui.bootstrap.IModalServiceInstance,
- confirmationModalModel:IConfirmationModalModel,
- private CommentValidationPattern: RegExp,
- private ValidationUtils: Sdc.Utils.ValidationUtils,
- private $templateCache:ng.ITemplateCacheService,
- private $modal:ng.ui.bootstrap.IModalService) {
-
- this.initScope(confirmationModalModel);
- }
-
- private initScope = (confirmationModalModel:IConfirmationModalModel):void => {
- let self = this;
- this.$scope.hideCancelButton = false;
- this.$scope.modalInstanceConfirmation = this.$modalInstance;
- this.$scope.confirmationModalModel = confirmationModalModel;
- this.$scope.comment = {"text": ''};
- this.$scope.commentValidationPattern = this.CommentValidationPattern;
-
- this.$scope.ok = ():any => {
- self.$modalInstance.close(this.ValidationUtils.stripAndSanitize(self.$scope.comment.text));
- };
-
- this.$scope.cancel = ():void => {
- console.info('Cancel pressed on: ' + this.$scope.confirmationModalModel.title);
- self.$modalInstance.dismiss();
- };
-
- // Set the OK button color according to modal type (standard, error, alert)
- let _okButtonColor = 'blue'; // Default
- switch (confirmationModalModel.type) {
- case Sdc.Utils.Constants.ModalType.STANDARD:
- _okButtonColor='blue';
- break;
- case Sdc.Utils.Constants.ModalType.ERROR:
- _okButtonColor='red';
- break;
- case Sdc.Utils.Constants.ModalType.ALERT:
- this.$scope.hideCancelButton = true;
- _okButtonColor='grey';
- break;
- default:
- _okButtonColor='blue';
- break;
- }
- this.$scope.okButtonColor = _okButtonColor;
-
- }
- }
-}
diff --git a/catalog-ui/app/scripts/view-models/modals/email-modal/email-modal-view-model.ts b/catalog-ui/app/scripts/view-models/modals/email-modal/email-modal-view-model.ts
deleted file mode 100644
index 6430a955a6..0000000000
--- a/catalog-ui/app/scripts/view-models/modals/email-modal/email-modal-view-model.ts
+++ /dev/null
@@ -1,117 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../../references"/>
-module Sdc.ViewModels {
- 'use strict';
-
- export interface IEmailModalModel_Email {
- to: string;
- subject: string;
- message: string;
- }
-
- export interface IEmailModalModel_Data {
- component: Models.Components.Component;
- stateUrl: string;
- }
-
- export interface IEmailModalModel {
- title: string;
- email: IEmailModalModel_Email;
- data: IEmailModalModel_Data;
- }
-
- interface IEmailModalViewModelScope {
- modalInstanceEmail:ng.ui.bootstrap.IModalServiceInstance;
- emailModalModel: IEmailModalModel;
- submitInProgress:boolean;
- commentValidationPattern:RegExp;
- isLoading:boolean;
- submit(): any;
- cancel(): void;
- validateField(field:any):boolean;
- }
-
- export class EmailModalViewModel {
-
- static '$inject' = ['$scope', '$filter', 'sdcConfig', '$modalInstance', 'emailModalModel', 'ValidationUtils', 'CommentValidationPattern'];
-
- constructor(private $scope:IEmailModalViewModelScope,
- private $filter:ng.IFilterService,
- private sdcConfig:Models.IAppConfigurtaion,
- private $modalInstance:ng.ui.bootstrap.IModalServiceInstance,
- private emailModalModel:IEmailModalModel,
- private ValidationUtils: Sdc.Utils.ValidationUtils,
- private CommentValidationPattern: RegExp) {
-
- this.initScope(emailModalModel);
- }
-
- private initScope = (emailModalModel:IEmailModalModel):void => {
- this.$scope.emailModalModel = emailModalModel;
- this.$scope.submitInProgress=false;
- this.$scope.commentValidationPattern = this.CommentValidationPattern;
- this.$scope.modalInstanceEmail = this.$modalInstance;
-
- this.$scope.submit = ():any => {
-
- let onSuccess = (component:Models.Components.Component) => {
- this.$scope.isLoading = false;
- this.$scope.submitInProgress=false;
- let link:string = encodeURI(this.sdcConfig.api.baseUrl + "?folder=Ready_For_Testing");
- let outlook:string = this.$filter('translate')("EMAIL_OUTLOOK_MESSAGE", "{'to': '" + emailModalModel.email.to + "','subject': '" + emailModalModel.email.subject + "','message': '" + emailModalModel.email.message + "', 'entityNameAndVersion': '" + emailModalModel.email.subject + "','link': '" + link + "'}");
- if(!this.sdcConfig.openSource) {
- window.location.href=outlook; // Open outlook with the email to send
- }
- this.$modalInstance.close(component); // Close the dialog
- };
-
- let onError = () => {
- this.$scope.isLoading = false;
- this.$scope.submitInProgress=false;
- this.$modalInstance.close(); // Close the dialog
- };
-
- // Submit to server
- // Prevent from user pressing multiple times on submit.
- if (this.$scope.submitInProgress===false) {
- this.$scope.isLoading = true;
- this.$scope.submitInProgress = true;
- let comment:Models.AsdcComment = new Models.AsdcComment();
- comment.userRemarks = emailModalModel.email.message;
- emailModalModel.data.component.changeLifecycleState(emailModalModel.data.stateUrl, comment).then(onSuccess, onError);
- }
- };
-
- this.$scope.cancel = ():void => {
- this.$modalInstance.dismiss();
- };
-
- this.$scope.validateField = (field:any):boolean => {
- if (field && field.$dirty && field.$invalid){
- return true;
- }
- return false;
- };
- }
-
-
- }
-}
diff --git a/catalog-ui/app/scripts/view-models/modals/error-modal/error-403-view.html b/catalog-ui/app/scripts/view-models/modals/error-modal/error-403-view.html
deleted file mode 100644
index 185fcce461..0000000000
--- a/catalog-ui/app/scripts/view-models/modals/error-modal/error-403-view.html
+++ /dev/null
@@ -1,4 +0,0 @@
-<div class="sdc-error-403-container" >
- <div class="sdc-error-403-container-title" translate="GENERAL_ERROR_403_TITLE"></div>
- <div class="w-sdc-error-403-text w-sdc-form" translate="GENERAL_ERROR_403_DESCRIPTION" translate-values="{{ mailtoJson }}"></div>
-</div>
diff --git a/catalog-ui/app/scripts/view-models/modals/error-modal/error-view-model.ts b/catalog-ui/app/scripts/view-models/modals/error-modal/error-view-model.ts
deleted file mode 100644
index b8b2bfbbe7..0000000000
--- a/catalog-ui/app/scripts/view-models/modals/error-modal/error-view-model.ts
+++ /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=========================================================
- */
-/// <reference path="../../../references"/>
-module Sdc.ViewModels {
- 'use strict';
-
- interface IErrorViewModelScope{
- mailtoJson: any;
- }
-
- export class ErrorViewModel {
-
- static '$inject' = ['$scope', 'Sdc.Services.CookieService', '$window', '$filter'];
-
- constructor($scope:IErrorViewModelScope, cookieService:Services.CookieService, $window, $filter:ng.IFilterService){
- let adminEmail:string = $filter('translate')('ADMIN_EMAIL');
- let subjectPrefix:string = $filter('translate')('EMAIL_SUBJECT_PREFIX');
- let userDetails = cookieService.getFirstName() + ' '+cookieService.getLastName() + ' ('+cookieService.getUserId() + ')';
- let line = adminEmail+'?subject='+$window.encodeURIComponent(subjectPrefix+' '+userDetails);
- $scope.mailtoJson = {
- "mailto": line
- };
- }
-
- }
-}
diff --git a/catalog-ui/app/scripts/view-models/modals/message-modal/message-base-modal-model.ts b/catalog-ui/app/scripts/view-models/modals/message-modal/message-base-modal-model.ts
deleted file mode 100644
index 26df780d25..0000000000
--- a/catalog-ui/app/scripts/view-models/modals/message-modal/message-base-modal-model.ts
+++ /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=========================================================
- */
-/// <reference path="../../../references"/>
-module Sdc.ViewModels {
- 'use strict';
-
- export interface IMessageModalModel {
- title: string;
- message: string;
- severity: Utils.Constants.SEVERITY;
- }
-
- export interface IMessageModalViewModelScope extends ng.IScope {
- footerButtons: Array<any>;
- messageModalModel: IMessageModalModel;
- modalInstanceError:ng.ui.bootstrap.IModalServiceInstance;
- ok(): void;
- }
-
- export class MessageModalViewModel {
-
- constructor(private $baseScope:IMessageModalViewModelScope,
- private $baseModalInstance:ng.ui.bootstrap.IModalServiceInstance,
- private baseMessageModalModel:IMessageModalModel) {
-
- this.initScope(baseMessageModalModel);
- }
-
- private initScope = (messageModalViewModel:IMessageModalModel):void => {
-
- this.$baseScope.messageModalModel = messageModalViewModel;
- this.$baseScope.modalInstanceError = this.$baseModalInstance;
-
- this.$baseScope.ok = ():void => {
- this.$baseModalInstance.close();
- };
-
- this.$baseScope.footerButtons = [
- {
- 'name': 'OK',
- 'css': 'grey',
- 'callback': this.$baseScope.ok
- }
- ];
- }
- }
-}
diff --git a/catalog-ui/app/scripts/view-models/modals/message-modal/message-server-modal/server-message-modal-view-model.ts b/catalog-ui/app/scripts/view-models/modals/message-modal/message-server-modal/server-message-modal-view-model.ts
deleted file mode 100644
index f7a0dcfabf..0000000000
--- a/catalog-ui/app/scripts/view-models/modals/message-modal/message-server-modal/server-message-modal-view-model.ts
+++ /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=========================================================
- */
-/// <reference path="../../../../references"/>
-module Sdc.ViewModels {
- 'use strict';
-
- export interface IServerMessageModalModel extends IMessageModalModel {
- status: string;
- messageId: string;
- }
-
- export interface IServerMessageModalViewModelScope extends IMessageModalViewModelScope {
- serverMessageModalModel: IServerMessageModalModel;
- }
-
- export class ServerMessageModalViewModel extends MessageModalViewModel {
-
- static '$inject' = ['$scope', '$modalInstance', 'serverMessageModalModel'];
-
- constructor(private $scope:IServerMessageModalViewModelScope,
- private $modalInstance:ng.ui.bootstrap.IModalServiceInstance,
- private serverMessageModalModel:IServerMessageModalModel) {
-
- super($scope, $modalInstance, serverMessageModalModel);
- }
-
- }
-}
diff --git a/catalog-ui/app/scripts/view-models/modals/onboarding-modal/onboarding-modal-view-model.ts b/catalog-ui/app/scripts/view-models/modals/onboarding-modal/onboarding-modal-view-model.ts
deleted file mode 100644
index a6e85c4abc..0000000000
--- a/catalog-ui/app/scripts/view-models/modals/onboarding-modal/onboarding-modal-view-model.ts
+++ /dev/null
@@ -1,249 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../../references"/>
-module Sdc.ViewModels {
- 'use strict';
- import Resource = Sdc.Models.Components.Resource;
- import ComponentFactory = Sdc.Utils.ComponentFactory;
-
- interface IOnboardingModalViewModelScope {
- modalOnboarding: ng.ui.bootstrap.IModalServiceInstance;
- componentsList: Array<Models.Components.IComponent>;
- tableHeadersList: Array<any>;
- selectedComponent: Models.Components.Component;
- componentFromServer: Models.Components.Component;
- reverse: boolean;
- sortBy: string;
- searchBind: string;
- okButtonText: string;
- isCsarComponentExists: boolean;
- user: Models.IUser;
- isLoading: boolean;
-
- doSelectComponent(component: Models.Components.Component): void;
- doUpdateCsar(): void;
- doImportCsar(): void;
- sort(sortBy: string): void;
- downloadCsar(packageId: string): void;
- }
-
- export class OnboardingModalViewModel {
-
- static '$inject' = [
- '$scope',
- '$filter',
- '$state',
- 'sdcConfig',
- '$modalInstance',
- 'Sdc.Services.OnboardingService',
- 'okButtonText',
- 'currentCsarUUID',
- 'Sdc.Services.CacheService',
- 'FileUtils',
- 'ComponentFactory',
- 'ModalsHandler'
- ];
-
- constructor(private $scope: IOnboardingModalViewModelScope,
- private $filter: ng.IFilterService,
- private $state: any,
- private sdcConfig: Models.IAppConfigurtaion,
- private $modalInstance: ng.ui.bootstrap.IModalServiceInstance,
- private onBoardingService: Sdc.Services.OnboardingService,
- private okButtonText: string,
- private currentCsarUUID: string,
- private cacheService: Services.CacheService,
- private fileUtils: Sdc.Utils.FileUtils,
- private componentFactory: Utils.ComponentFactory,
- private modalsHandler: Sdc.Utils.ModalsHandler) {
-
- this.init();
- }
-
- /**
- * Called from controller constructor, this will call onboarding service to get list
- * of "mini" components (empty components created from CSAR).
- * The list is inserted to componentsList on $scope.
- * And then call initScope method.
- */
- private init = (): void => {
- this.initOnboardingComponentsList();
- };
-
- private initScope = (): void => {
-
- this.initSortedTableScope();
- this.initModalScope();
- this.$scope.sortBy = "name"; // Default sort by
- this.$scope.user = this.cacheService.get('user');
- this.$scope.okButtonText = this.okButtonText;
-
- // Dismiss the modal and pass the "mini" component to workspace general page
- this.$scope.doImportCsar = (): void => {
- this.$modalInstance.dismiss();
- this.$state.go('workspace.general', {
- type: Utils.Constants.ComponentType.RESOURCE.toLowerCase(),
- componentCsar: this.$scope.selectedComponent
- });
- };
-
- this.$scope.doUpdateCsar = (): void => {
- // In case user select on update the checkin and submit for testing buttons (in general page) should be disabled.
- // to do that we need to pass to workspace.general state parameter to know to disable the buttons.
- this.$modalInstance.close();
- // Change the component version to the CSAR version we want to update.
- /*(<Resource>this.$scope.componentFromServer).csarVersion = (<Resource>this.$scope.selectedComponent).csarVersion;
- let component:Models.Components.Component = this.componentFactory.createComponent(this.$scope.componentFromServer);
- this.$state.go('workspace.general', {vspComponent: component, disableButtons: true });*/
- this.cacheService.set(Utils.Constants.CHANGE_COMPONENT_CSAR_VERSION_FLAG, (<Resource>this.$scope.selectedComponent).csarVersion);
- this.$state.go('workspace.general', {
- id: this.$scope.componentFromServer.uniqueId,
- type: this.$scope.componentFromServer.componentType.toLowerCase(),
- disableButtons: true
- });
- };
-
- this.$scope.downloadCsar = (packageId: string): void => {
- this.onBoardingService.downloadOnboardingCsar(packageId).then(
- (file: any): void => {
- if (file) {
- this.fileUtils.downloadFile(file, packageId + '.zip');
- }
- }, (): void => {
- let data: Sdc.ViewModels.IServerMessageModalModel = {
- title: 'Download error',
- message: "Error downloading file",
- severity: Utils.Constants.SEVERITY.ERROR,
- messageId: "",
- status: ""
- };
- this.modalsHandler.openServerMessageModal(data);
- }
- );
- };
-
- // When the user select a row, set the component as selectedComponent
- this.$scope.doSelectComponent = (component: Models.Components.Component): void => {
-
- if (this.$scope.selectedComponent === component) {
- // Collapse the item
- this.$scope.selectedComponent = undefined;
- return;
- }
-
- this.$scope.isLoading = true;
- this.$scope.componentFromServer = undefined;
- this.$scope.selectedComponent = component;
-
- let onSuccess = (componentFromServer: Models.Components.Component): void => {
- this.$scope.isLoading = false;
- if (componentFromServer) {
- this.$scope.componentFromServer = componentFromServer;
- this.$scope.isCsarComponentExists = true;
- } else {
- this.$scope.componentFromServer = component;
- this.$scope.isCsarComponentExists = false;
- }
- };
-
- let onError = (): void => {
- this.$scope.isLoading = false;
- this.$scope.componentFromServer = component;
- this.$scope.isCsarComponentExists = false;
- };
-
- this.onBoardingService.getComponentFromCsarUuid((<Resource>component).csarUUID).then(onSuccess, onError);
- };
-
- };
-
- private initSortedTableScope = (): void => {
- this.$scope.tableHeadersList = [
- {title: 'Name', property: 'name'},
- {title: 'Vendor', property: 'vendorName'},
- {title: 'Category', property: 'categories'},
- {title: 'Version', property: 'csarVersion'},
- {title: '#', property: 'importAndUpdate'}
- //{title: 'Date', property: 'componentDate'}
- ];
-
- this.$scope.sort = (sortBy: string): void => {
- this.$scope.reverse = (this.$scope.sortBy === sortBy) ? !this.$scope.reverse : false;
- this.$scope.sortBy = sortBy;
- };
- };
-
- private initModalScope = (): void => {
- // Enable the modal directive to close
- this.$scope.modalOnboarding = this.$modalInstance;
- };
-
- private initOnboardingComponentsList = (): void => {
- let onSuccess = (onboardingResponse: Array<Models.Components.IComponent>): void => {
- initMaxVersionOfItemsInList(onboardingResponse);
-
- if (this.currentCsarUUID) {
- //this.$scope.componentsList = this.$filter('filter')(this.$scope.componentsList, {csarUUID: this.currentCsarUUID});
- this.$scope.componentsList = this.$filter('filter')(this.$scope.componentsList,
- (input): boolean => {
- return input.csarUUID === this.currentCsarUUID;
- }
- );
- }
- this.initScope();
- };
-
- let onError = (): void => {
- console.log("Error getting onboarding list");
- this.initScope();
- };
-
- let initMaxVersionOfItemsInList = (onboardingResponse: Array<Models.Components.IComponent>): void => {
- // Get only the latest version of each item
- this.$scope.componentsList = [];
-
- // Get all unique items from the list
- let uniqueItems = _.uniqBy(onboardingResponse, 'packageId');
-
- // Loop on all the items with unique packageId
- _.each(uniqueItems, (item: any): void => {
- // Find all the items that has same packageId
- let ItemsFound: Array<Models.Components.IComponent> = _.filter(onboardingResponse, (inListItem: any): any => {
- return inListItem.packageId === item.packageId;
- });
-
- // Loop on all the items with same packageId and find the max version.
- let maxItem: any;
- _.each(ItemsFound, (ItemFound: any): void => {
- if (!maxItem) {
- maxItem = ItemFound;
- } else if (maxItem && parseInt(maxItem.csarVersion) < parseInt(ItemFound.csarVersion)) {
- maxItem = ItemFound;
- }
- });
- this.$scope.componentsList.push(maxItem);
- });
- };
-
- this.onBoardingService.getOnboardingComponents().then(onSuccess, onError);
- };
-
- }
-}
diff --git a/catalog-ui/app/scripts/view-models/onboard-vendor/onboard-vendor-view-model.ts b/catalog-ui/app/scripts/view-models/onboard-vendor/onboard-vendor-view-model.ts
deleted file mode 100644
index c8be2b7361..0000000000
--- a/catalog-ui/app/scripts/view-models/onboard-vendor/onboard-vendor-view-model.ts
+++ /dev/null
@@ -1,148 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../references.ts"/>
-module Sdc.ViewModels {
- 'use strict';
-
- export class BreadcrumbsMenuItem {
- key: string;
- displayText: string;
- }
-
- export class BreadcrumbsMenu {
- selectedKey: string;
- menuItems: Array<BreadcrumbsMenuItem>;
- }
-
- export class BreadcrumbsPath {
- selectedKeys: Array<string>;
- }
-
- export class VendorData {
- breadcrumbs: BreadcrumbsPath;
- }
-
- export interface IOnboardVendorViewModelScope extends ng.IScope {
- vendorData: VendorData;
- onVendorEvent: Function;
- topNavMenuModel: Array<Utils.MenuItemGroup>;
- topNavRootMenu: Utils.MenuItemGroup;
- user:Models.IUserProperties;
- version:string;
- }
-
- export class OnboardVendorViewModel {
- static '$inject' = [
- '$scope',
- '$q',
- 'Sdc.Services.CacheService'
- ];
-
- private firstControlledTopNavMenu: Utils.MenuItemGroup;
-
- constructor(
- private $scope: IOnboardVendorViewModelScope,
- private $q: ng.IQService,
- private cacheService:Services.CacheService
- ) {
-
- this.$scope.vendorData = {
- breadcrumbs: {
- selectedKeys: []
- }
- };
-
- this.$scope.version = this.cacheService.get('version');
-
- this.$scope.onVendorEvent = (eventName:string, data:any): void => {
- switch (eventName) {
- case 'breadcrumbsupdated':
- this.handleBreadcrumbsUpdate(data);
- break;
- }
- };
-
- this.$scope.topNavMenuModel = [];
-
- this.$scope.user = this.cacheService.get('user');
- }
-
- updateBreadcrumbsPath = (selectedKeys: Array<string>): ng.IPromise<boolean> => {
- let topNavMenuModel = this.$scope.topNavMenuModel;
- let startIndex = topNavMenuModel.indexOf(this.firstControlledTopNavMenu);
- if (startIndex === -1) {
- startIndex = topNavMenuModel.length;
- }
- topNavMenuModel.splice(startIndex + selectedKeys.length);
- this.$scope.vendorData = {
- breadcrumbs: { selectedKeys: selectedKeys }
- };
-
- return this.$q.when(true);
- };
-
- handleBreadcrumbsUpdate(breadcrumbsMenus: Array<BreadcrumbsMenu>): void {
- let selectedKeys = [];
- let topNavMenus = breadcrumbsMenus.map((breadcrumbMenu, breadcrumbIndex) => {
- let topNavMenu = new Utils.MenuItemGroup();
- topNavMenu.menuItems = breadcrumbMenu.menuItems.map(menuItem =>
- new Utils.MenuItem(
- menuItem.displayText,
- this.updateBreadcrumbsPath,
- null,
- null,
- [selectedKeys.concat([menuItem.key])]
- )
- );
- topNavMenu.selectedIndex = _.findIndex(
- breadcrumbMenu.menuItems,
- menuItem => menuItem.key === breadcrumbMenu.selectedKey
- );
- selectedKeys.push(breadcrumbMenu.selectedKey);
- return topNavMenu;
- });
-
- let topNavMenuModel = this.$scope.topNavMenuModel;
- let len = topNavMenuModel.length;
- let startIndex = topNavMenuModel.indexOf(this.firstControlledTopNavMenu);
- if (startIndex === -1) {
- startIndex = len;
- }
- topNavMenuModel.splice(startIndex, len - startIndex);
- topNavMenuModel.push.apply(topNavMenuModel, topNavMenus);
- this.firstControlledTopNavMenu = topNavMenus[0];
-
- if (startIndex === 1 && this.$scope.topNavRootMenu == null) {
- let topNavRootMenu = topNavMenuModel[0];
- let onboardItem = topNavRootMenu.menuItems[topNavRootMenu.selectedIndex];
- let originalCallback = onboardItem.callback;
- onboardItem.callback = (...args) => {
- let ret = this.updateBreadcrumbsPath([]);
- return originalCallback && originalCallback.apply(undefined, args) || ret;
- };
- this.$scope.topNavRootMenu = topNavRootMenu;
- }
-
- this.updateBreadcrumbsPath(selectedKeys);
- }
- }
-
-
-}
diff --git a/catalog-ui/app/scripts/view-models/preloading/preloading-view.less b/catalog-ui/app/scripts/view-models/preloading/preloading-view.less
deleted file mode 100644
index b02ea54621..0000000000
--- a/catalog-ui/app/scripts/view-models/preloading/preloading-view.less
+++ /dev/null
@@ -1,107 +0,0 @@
-/*
-.sdc-loading-page {
-
- background-color: @main_color_l;
- width: 100%;
- height: 100%;
-
- display: flex;
- align-items: center;
- justify-content: center;
- flex-direction: column;
-
- h1 {
- .c_5;
- text-align: center;
- }
-
- p {
- display: block;
- .e_4;
- }
-
- .caption1, .caption2 {
- visibility: hidden;
- }
-
- .load-container-wrapper {
- position: relative;
-
- .load-container {
-
- @background_color: #000000;
-
- .loader,
- .loader:before,
- .loader:after {
- border-radius: 50%;
- }
- .loader:before,
- .loader:after {
- position: absolute;
- content: '';
- }
- .loader:before {
- width: 5.2em;
- height: 10.2em;
- background: @background_color;
- border-radius: 10.2em 0 0 10.2em;
- top: -0.1em;
- left: -0.1em;
- -webkit-transform-origin: 5.2em 5.1em;
- transform-origin: 5.2em 5.1em;
- -webkit-animation: load2 2s infinite ease 1.5s;
- animation: load2 2s infinite ease 1.5s;
- }
- .loader {
- color: #ffffff;
- font-size: 11px;
- text-indent: -99999em;
- margin: 0 auto;
- /!*margin: 55px auto;*!/
- position: relative;
- width: 10em;
- height: 10em;
- box-shadow: inset 0 0 0 1em;
- -webkit-transform: translateZ(0);
- -ms-transform: translateZ(0);
- transform: translateZ(0);
- }
- .loader:after {
- width: 5.2em;
- height: 10.2em;
- background: @background_color;
- border-radius: 0 10.2em 10.2em 0;
- top: -0.1em;
- left: 5.1em;
- -webkit-transform-origin: 0px 5.1em;
- transform-origin: 0px 5.1em;
- -webkit-animation: load2 2s infinite ease;
- animation: load2 2s infinite ease;
- }
- @-webkit-keyframes load2 {
- 0% {
- -webkit-transform: rotate(0deg);
- transform: rotate(0deg);
- }
- 100% {
- -webkit-transform: rotate(360deg);
- transform: rotate(360deg);
- }
- }
- @keyframes load2 {
- 0% {
- -webkit-transform: rotate(0deg);
- transform: rotate(0deg);
- }
- 100% {
- -webkit-transform: rotate(360deg);
- transform: rotate(360deg);
- }
- }
- }
-
- }
-
-}
-*/
diff --git a/catalog-ui/app/scripts/view-models/preloading/preloading-view.ts b/catalog-ui/app/scripts/view-models/preloading/preloading-view.ts
deleted file mode 100644
index 7127b70e3c..0000000000
--- a/catalog-ui/app/scripts/view-models/preloading/preloading-view.ts
+++ /dev/null
@@ -1,47 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-module Sdc.ViewModels {
- 'use strict';
-
- interface IPreLoadingViewScope {
- startZoomIn: boolean;
- }
-
- export class PreLoadingViewModel {
-
- static '$inject' = ['$scope'];
- constructor(private $scope:IPreLoadingViewScope){
- this.init($scope);
- }
-
- private init = ($scope:IPreLoadingViewScope):void => {
- this.animate($('.caption1'),'fadeInUp',400);
- this.animate($('.caption2'),'fadeInUp',800);
- };
-
- private animate = (element:any, animation:string, when:number):void => {
- window.setTimeout(()=>{
- element.addClass("animated " + animation);
- element[0].style="visibility: visible;";
- },when);
- };
-
- }
-}
diff --git a/catalog-ui/app/scripts/view-models/support/support-view-model.ts b/catalog-ui/app/scripts/view-models/support/support-view-model.ts
deleted file mode 100644
index 2142cffdda..0000000000
--- a/catalog-ui/app/scripts/view-models/support/support-view-model.ts
+++ /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=========================================================
- */
-/// <reference path="../../references"/>
-
-module Sdc.ViewModels {
- 'use strict';
-
- interface ISupportViewModelScope {
- version:string;
- }
-
- export class SupportViewModel{
-
- static '$inject' = ['$scope','Sdc.Services.CacheService'];
- constructor(private $scope:ISupportViewModelScope,
- private cacheService:Services.CacheService){
- this.$scope.version = this.cacheService.get('version');
- }
-
- }
-}
diff --git a/catalog-ui/app/scripts/view-models/tabs/hierarchy/hierarchy-view-model.ts b/catalog-ui/app/scripts/view-models/tabs/hierarchy/hierarchy-view-model.ts
deleted file mode 100644
index bd59199eb4..0000000000
--- a/catalog-ui/app/scripts/view-models/tabs/hierarchy/hierarchy-view-model.ts
+++ /dev/null
@@ -1,99 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/**
- * Created by obarda on 7/28/2016.
- */
-/**
- * Created by obarda on 4/4/2016.
- */
-/// <reference path="../../../references"/>
-module Sdc.ViewModels {
- 'use strict';
- import Module = Sdc.Models.Module;
-
- export interface IHierarchyScope extends ng.IScope {
- component:Models.Components.Component;
- selectedIndex: number;
- selectedModule:Models.DisplayModule;
- singleTab:Models.Tab;
- templateUrl:string;
- isLoading:boolean;
-
- onModuleSelected(moduleId:string, selectedIndex: number):void;
- onModuleNameChanged(module:Models.DisplayModule):void;
- updateHeatName():void;
- }
-
- export class HierarchyViewModel {
-
- static '$inject' = [
- '$scope'
- ];
-
- constructor(private $scope:IHierarchyScope) {
- this.$scope.component = this.$scope.singleTab.data;
- this.$scope.isLoading = false;
- this.initScopeMethods();
- }
-
- private initScopeMethods():void {
-
- this.$scope.templateUrl = '/app/scripts/view-models/tabs/hierarchy/edit-module-name-popover.html';
- this.$scope.onModuleSelected = (moduleId:string, selectedIndex: number):void => {
-
- let onSuccess = (module:Models.DisplayModule) => {
- console.log("Module Loaded: ", module);
- this.$scope.selectedModule = module;
- this.$scope.isLoading = false;
- };
-
- let onFailed = () => {
- this.$scope.isLoading = false;
- };
-
- this.$scope.selectedIndex = selectedIndex;
- if( !this.$scope.selectedModule || (this.$scope.selectedModule && this.$scope.selectedModule.uniqueId != moduleId)) {
- this.$scope.isLoading = true;
- this.$scope.component.getModuleForDisplay(moduleId).then(onSuccess, onFailed);
- }
- };
-
- this.$scope.updateHeatName = () => {
- this.$scope.isLoading = true;
-
- let originalName:string = this.$scope.selectedModule.name;
-
- let onSuccess = (module:Models.Module) => {
- console.log("Module name updated:", module.name);
- this.$scope.selectedModule.name = module.name;
- this.$scope.isLoading = false;
- };
-
- let onFailed = () => {
- this.$scope.isLoading = false;
- this.$scope.selectedModule.name = originalName;
- };
-
- this.$scope.selectedModule.updateName();
- this.$scope.component.updateGroupMetadata(new Models.DisplayModule(this.$scope.selectedModule)).then(onSuccess, onFailed);
- };
- }
- }
-}
diff --git a/catalog-ui/app/scripts/view-models/tabs/hierarchy/hierarchy-view.html b/catalog-ui/app/scripts/view-models/tabs/hierarchy/hierarchy-view.html
deleted file mode 100644
index 971105c191..0000000000
--- a/catalog-ui/app/scripts/view-models/tabs/hierarchy/hierarchy-view.html
+++ /dev/null
@@ -1,57 +0,0 @@
-<div class="sdc-general-tab hierarchy-tab" ng-class="">
- <loader data-display="isLoading" relative="true" size="medium"></loader>
- <div class="sdc-general-tab-title" data-tests-id="tab-header" translate="HIERARCHY_TAB_TITLE"></div>
- <div class="sdc-general-tab-sub-title" data-tests-id="tab-sub-header">{{component.name}}</div>
-
- <div class="resizable-container">
- <div class="resizable-section">
- <perfect-scrollbar scroll-y-margin-offset="0" include-padding="true"
- class="general-tab-scrollbar-container">
-
- <expand-collapse expanded-selector=".hierarchy-module-member-list.{{$index}}"
- class="general-tab-expand-collapse" is-close-on-init="true"
- data-tests-id="hierarchy-module-{{$index}}"
- data-ng-repeat-start="module in component.groups">
- <div class="expand-collapse-title" data-tests-id="hierarchy-module-{{$index}}-title" ng-class="{'selected': selectedIndex === $index}" data-ng-click="onModuleSelected(module.uniqueId, $index)">
- <div class="expand-collapse-title-icon"></div>
- <span class="expand-collapse-title-text" data-ng-bind="module.name" tooltips
- tooltip-content="{{module.name}}"></span>
-
- </div>
- </expand-collapse>
-
- <div data-ng-repeat-end="" class="hierarchy-module-member-list {{$index}}">
- <div ng-repeat="(memberName, value) in ::module.members track by $index">
- <div class="expand-collapse-sub-title" tooltips tooltip-content="{{memberName}}">{{memberName}}</div>
- </div>
- </div>
- </perfect-scrollbar>
- </div>
-
- <div resizable r-directions="['top']" r-flex="true" ng-if="selectedModule" class="resizable-section module-data-container" data-tests-id="selected-module-data">
- <perfect-scrollbar scroll-y-margin-offset="0" include-padding="true"
- class="general-tab-scrollbar-container">
- <div class="module-data">
- <div>
- <div class="module-name module-text-overflow" data-tests-id="selected-module-name" tooltips tooltip-content="{{selectedModule.name}}">{{selectedModule.name}}</div>
- <div class="edit-name-container">
- <edit-name-popover header="Edit Module Name" direction="auto top" module="selectedModule" on-save="updateHeatName()" ng-class="{'disabled': isViewOnly}" class="sdc-edit-icon" data-tests-id="edit-name-popover-icon"></edit-name-popover>
- </div>
- </div>
- <div class="module-text-overflow" data-tests-id="selected-module-group-uuid" tooltips tooltip-content="{{selectedModule.groupUUID}}"> Module ID: {{selectedModule.groupUUID}}</div>
- <div class="module-text-overflow" data-tests-id="selected-module-is-base" tooltips tooltip-content="{{selectedModule.invariantUUID}}">Invariant UUID: {{selectedModule.invariantUUID}}</div>
- <div data-tests-id="selected-module-version">Version: {{selectedModule.version}}</div>
- <div data-tests-id="selected-module-is-base">IsBase: {{selectedModule.isBase}}</div>
-
- </div>
- <div ng-repeat="artifact in selectedModule.artifacts track by $index">
- <div class="artifact-data">
- <div class="artifact-name module-text-overflow" data-tests-id="selected-module-artifact-name" tooltips tooltip-content="{{artifact.artifactName}}">{{artifact.artifactName}}</div>
- <div class="module-text-overflow" tooltips data-tests-id="selected-module-artifact-uuid" tooltip-content="{{artifact.artifactUUID}}"> UUID: {{artifact.artifactUUID}}</div>
- <div data-tests-id="selected-module-artifact-version">Version: {{artifact.artifactVersion}}</div>
- </div>
- </div>
- </perfect-scrollbar>
- </div>
- </div>
-</div>
diff --git a/catalog-ui/app/scripts/view-models/tutorial-end/tutorial-end.ts b/catalog-ui/app/scripts/view-models/tutorial-end/tutorial-end.ts
deleted file mode 100644
index 411d3f8d24..0000000000
--- a/catalog-ui/app/scripts/view-models/tutorial-end/tutorial-end.ts
+++ /dev/null
@@ -1,42 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../references"/>
-module Sdc.ViewModels {
- 'use strict';
-
- interface ITutorialEndViewModelScope extends ng.IScope {}
-
- export class TutorialEndViewModel {
-
- static '$inject' = [
- '$scope'
- ];
- constructor(
- private $scope:ITutorialEndViewModelScope
- ){
- this.init();
- }
-
- private init = ():void => {
-
- }
-
- }
-}
diff --git a/catalog-ui/app/scripts/view-models/welcome/slide0.html b/catalog-ui/app/scripts/view-models/welcome/slide0.html
deleted file mode 100644
index 48d37215a4..0000000000
--- a/catalog-ui/app/scripts/view-models/welcome/slide0.html
+++ /dev/null
@@ -1,50 +0,0 @@
-<div class="slide" id="slide-0" data-ng-controller="Sdc.ViewModels.WelcomeStepsControllerViewModel">
- <div class="asdc-welcome-frame frame-0">
- <div class="asdc-welcome-header">
- <a class="sprite-welcome logo" class="welcome-logo" ui-sref="dashboard"></a>
- </div>
-
- <div class="asdc-welcome-cover"></div>
- <div class="asdc-whats-new">
-
- <div class="news-items-row">
- <div class="news-item-wrapper bg-1">
- <div class="news-title" translate="WHATS_NEW_1_TITLE"></div>
- <div class="news-body" translate="WHATS_NEW_1_BODY"></div>
- </div>
- <div class="news-item-wrapper bg-2">
- <div class="news-title" translate="WHATS_NEW_2_TITLE"></div>
- <div class="news-body" translate="WHATS_NEW_2_BODY"></div>
- </div>
- <div class="news-item-wrapper bg-3">
- <div class="news-title" translate="WHATS_NEW_3_TITLE"></div>
- <div class="news-body" translate="WHATS_NEW_3_BODY"></div>
- </div>
- <div class="news-item-wrapper bg-4">
- <div class="news-title" translate="WHATS_NEW_4_TITLE"></div>
- <div class="news-body" translate="WHATS_NEW_4_BODY"></div>
- </div>
- </div>
-
- <div class="news-items-row">
- <div class="news-item-wrapper bg-5">
- <div class="news-title" translate="WHATS_NEW_5_TITLE"></div>
- <div class="news-body" translate="WHATS_NEW_5_BODY"></div>
- </div>
- <div class="news-item-wrapper bg-6">
- <div class="news-title" translate="WHATS_NEW_6_TITLE"></div>
- <div class="news-body" translate="WHATS_NEW_6_BODY"></div>
- </div>
- <div class="news-item-wrapper bg-7">
- <div class="news-title" translate="WHATS_NEW_7_TITLE"></div>
- <div class="news-body" translate="WHATS_NEW_7_BODY"></div>
- </div>
- <div class="news-item-wrapper bg-8">
- <div class="news-title" translate="WHATS_NEW_8_TITLE"></div>
- <div class="news-body" translate="WHATS_NEW_8_BODY"></div>
- </div>
- </div>
-
- </div>
- </div>
-</div>
diff --git a/catalog-ui/app/scripts/view-models/welcome/slide1.html b/catalog-ui/app/scripts/view-models/welcome/slide1.html
deleted file mode 100644
index 9252026a6b..0000000000
--- a/catalog-ui/app/scripts/view-models/welcome/slide1.html
+++ /dev/null
@@ -1,34 +0,0 @@
-<div class="slide" id="slide-1" data-ng-controller="Sdc.ViewModels.WelcomeStepsControllerViewModel">
- <div class="asdc-welcome-frame frame-01">
- <div class="asdc-welcome-header">
- <!--<a class="sprite-welcome logo" class="welcome-logo" ui-sref="dashboard"></a>-->
- <!--<a class="whats-new" data-ng-click="gotoSlideIndex(0)">What`s New</a>-->
- </div>
-
- <!--<video id="asdc-welcome-video" class="asdc-welcome-video">&lt;!&ndash; autoplay loop muted &ndash;&gt;
- <source ng-src="{{video_mp4}}" type="video/mp4" />
- <source ng-src="{{video_ogg}}" type='video/ogg' />
- </video>-->
-
- <div class="asdc-welcome-cover"></div>
- <div class="asdc-welcome-main">
-
- <!--<div class="asdc-welcome-main-title">INNOVATIVE. RAPID. RELIABLE</div>
- <div class="asdc-welcome-main-message">
- AT&Ts leading collaborative network solution design platform
- </div>
-
- <div class="asdc-welcome-main-back-btn-ph">
- <a class="asdc-welcome-main-back-btn" ui-sref="dashboard">Home</a>
- </div>
-
- <div class="asdc-welcome-video-icon">
- <div class="asdc-welcome-video-icon-play sprite-welcome play" data-ng-click="onPlayVideo()"></div>
- <div class="asdc-welcome-inner-circle"></div>
- </div>-->
-
- <h1>Welcome to SDC</h1>
-
- </div>
- </div>
-</div>
diff --git a/catalog-ui/app/scripts/view-models/welcome/slide2.html b/catalog-ui/app/scripts/view-models/welcome/slide2.html
deleted file mode 100644
index 4329bf462d..0000000000
--- a/catalog-ui/app/scripts/view-models/welcome/slide2.html
+++ /dev/null
@@ -1,26 +0,0 @@
-<div class="slide" id="slide-2">
- <div class="asdc-welcome-frame frame-02">
- <div class="asdc-welcome-slide-text-box">
- <div class="asdc-welcome-slide-text-box-title">
- Innovate <br>
- network- design <br>
- platform <br>
- </div>
- <div class="asdc-welcome-slide-text-box-content">
- <p>
- Adapt swiftly to the constant demands placed on <br> networks by ongoing technological advances.
- </p>
- <p>
- Using ASDC’s innovative network-design platform,<br> quickly and easily create and share software
- <br>
- components.
- </p>
- </div>
- </div>
- <div class="asdc-welcome-slide-image-box">
- <img src="styles/images/welcome/ss-01.png" alt="01" class="asdc-welcome-slide-image">
- </div>
- <div class="asdc-welcome-frame-shape"></div>
- <div class="asdc-welcome-frame-connection"></div>
- </div>
-</div>
diff --git a/catalog-ui/app/scripts/view-models/welcome/slide3.html b/catalog-ui/app/scripts/view-models/welcome/slide3.html
deleted file mode 100644
index dd5448beac..0000000000
--- a/catalog-ui/app/scripts/view-models/welcome/slide3.html
+++ /dev/null
@@ -1,27 +0,0 @@
-<div class="slide" id="slide-3">
- <div class="asdc-welcome-frame frame-03">
-
- <div class="asdc-welcome-slide-text-box">
- <div class="asdc-welcome-slide-text-box-title">
- Enhance <br>
- and extend
- </div>
- <div class="asdc-welcome-slide-text-box-content">
- <p>
- Blend, build and arrange resources and services in the <br> designer workspace.
- </p>
- <p>
- Let your creativity lead the way to any number of <br> network solutions.
- </p>
- <p>
- Then simply click on elements to customize and refine <br> their specific properties to match your needs.
- </p>
- </div>
- </div>
- <div class="asdc-welcome-slide-image-box">
- <img src="styles/images/welcome/ss-02.png" alt="02" class="asdc-welcome-slide-image">
- </div>
- <div class="asdc-welcome-frame-shape"></div>
- <div class="asdc-welcome-frame-connection"></div>
- </div>
-</div>
diff --git a/catalog-ui/app/scripts/view-models/welcome/slide4.html b/catalog-ui/app/scripts/view-models/welcome/slide4.html
deleted file mode 100644
index 1428ce5375..0000000000
--- a/catalog-ui/app/scripts/view-models/welcome/slide4.html
+++ /dev/null
@@ -1,29 +0,0 @@
-<div class="slide" id="slide-4">
- <div class="asdc-welcome-frame frame-04">
- <div class="asdc-welcome-slide-text-box">
- <div class="asdc-welcome-slide-text-box-title">
- Share <br>
- and Collaborate
- </div>
- <div class="asdc-welcome-slide-text-box-content">
- <p>
- Graphically arranged, the Catalog is an easily <br> searchable collection of resources, services and
- <br> products that provides you with a variety of <br> network elements.
- </p>
- <p>
- Benefit from these assets by using them as <br> building blocks to form any number of network
- <br> solutions.
- </p>
- <p>
- After being certified for release, share and <br> collaborate with others as your solution is
- <br> automatically included in the catalog.
- </p>
- </div>
- </div>
- <div class="asdc-welcome-slide-image-box">
- <img src="styles/images/welcome/ss-03.png" alt="03" class="asdc-welcome-slide-image">
- </div>
- <div class="asdc-welcome-frame-shape"></div>
- <div class="asdc-welcome-frame-connection"></div>
- </div>
-</div>
diff --git a/catalog-ui/app/scripts/view-models/welcome/slide5.html b/catalog-ui/app/scripts/view-models/welcome/slide5.html
deleted file mode 100644
index 913573c8fc..0000000000
--- a/catalog-ui/app/scripts/view-models/welcome/slide5.html
+++ /dev/null
@@ -1,27 +0,0 @@
-<div class="slide" id="slide-5">
- <div class="asdc-welcome-frame frame-05">
- <div class="asdc-welcome-slide-text-box">
- <div class="asdc-welcome-slide-text-box-title">
- Fast, efficient <br>
- and reliable
- </div>
- <div class="asdc-welcome-slide-text-box-content">
- <p>
- ASDC is a platform built around a simple error-free
- <br>process for resource and service design and distribution.
- <br>
- <br>An integrated certification process makes ASDC a safe
- <br>and reliable environment to experiment, review and test
- <br>your work.
- <br>
- <br>Once approved your solution is ready to be used in
- <br>the real-world.
- </p>
-
- </div>
-
- </div>
- <div class="asdc-welcome-frame-shape"></div>
-
- </div>
-</div>
diff --git a/catalog-ui/app/scripts/view-models/welcome/slide6.html b/catalog-ui/app/scripts/view-models/welcome/slide6.html
deleted file mode 100644
index 22006f7f82..0000000000
--- a/catalog-ui/app/scripts/view-models/welcome/slide6.html
+++ /dev/null
@@ -1,26 +0,0 @@
-<div class="slide" id="slide-6">
- <div class="asdc-welcome-frame frame-06">
-
- <div class="asdc-welcome-cover"></div>
- <div class="asdc-welcome-main">
-
- <div class="asdc-welcome-main-title">ASDC</div>
- <div class="asdc-welcome-main-message">
- jump starting your network solutions.
- </div>
- <div class="asdc-welcome-main-back-btn-ph">
- <a class="asdc-welcome-main-back-btn" ui-sref="dashboard">Home</a>
- </div>
- </div>
-
- <div class="asdc-welcome-footer">
- © 2016 AT&T Intellectual Property.© 2016 AT&T Intellectual Property. link. This link will open a new
- window This link will open a new window All rights reserved.
- <br/>
- AT&T, Globe logo, Mobilizing Your World and DIRECTV are registered trademarks of AT&T Intellectual
- Property and/or AT&T affiliated companies. All other marks are the property of their respective owners.
-
- </div>
-
- </div>
-</div>
diff --git a/catalog-ui/app/scripts/view-models/welcome/welcome-steps-controller.ts b/catalog-ui/app/scripts/view-models/welcome/welcome-steps-controller.ts
deleted file mode 100644
index 816afcf2d2..0000000000
--- a/catalog-ui/app/scripts/view-models/welcome/welcome-steps-controller.ts
+++ /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=========================================================
- */
-/// <reference path="../../references"/>
-module Sdc.ViewModels {
- 'use strict';
-
- export interface IWelcomeStepsController {
- video_mp4: string;
- video_ogg: string;
- onPlayVideo: Function;
- }
-
- export class WelcomeStepsControllerViewModel {
-
- static '$inject' = [
- '$scope',
- '$sce',
- 'sdcConfig',
- '$state',
- '$filter'
- ];
-
- constructor(
- private $scope:IWelcomeStepsController,
- private $sce:any,
- private sdcConfig: Models.IAppConfigurtaion,
- private $state:ng.ui.IStateService,
- private $filter:ng.IFilterService
- ){
- this.init();
- this.initScope();
- }
-
- private init = ():void => {
-
- };
-
- private initScope = ():void => {
-
- this.$scope.onPlayVideo = ():void => {
- //console.log("onPlayVideo");
- $("#sdc-page-scroller").removeClass("animated fadeIn");
- $("#sdc-page-scroller").addClass("animated fadeOut");
- window.setTimeout(()=>{$("#sdc-page-scroller").css("display","none");},500);
-
- $("#sdc-welcome-video-wrapper").removeClass("animated fadeOut");
- $("#sdc-welcome-video-wrapper").addClass("animated fadeIn");
- window.setTimeout(()=>{$("#sdc-welcome-video-wrapper").css("display","block");},0);
-
- let videoElement:any = $("#asdc-welcome-video")[0];
- videoElement.play();
- };
-
- };
-
- }
-}
diff --git a/catalog-ui/app/scripts/view-models/welcome/welcome-view.html b/catalog-ui/app/scripts/view-models/welcome/welcome-view.html
deleted file mode 100644
index ba41e88a4e..0000000000
--- a/catalog-ui/app/scripts/view-models/welcome/welcome-view.html
+++ /dev/null
@@ -1,22 +0,0 @@
-<div class="sdc-welcome-new-page">
-
- <!--<div id="sdc-welcome-video-wrapper">
- <div class="asdc-welcome-video-close sprite-welcome close" data-ng-click="onCloseVideoButton()"></div>
- <video id="asdc-welcome-video" class="asdc-welcome-video">
- <source ng-src="{{video_mp4}}" type="video/mp4" />
- <source ng-src="{{video_ogg}}" type='video/ogg' />
- </video>
- </div>-->
-
- <div class="os-welcome">Welcome to SDC</div>
-
- <!--<sdc-page-scroll id="sdc-page-scroller"
- start-slide-index="1"
- slides-data="slides"
- show-nav="true"
- show-close-button="true"
- close-button-callback="onCloseButton">
-
- </sdc-page-scroll>
--->
-</div>
diff --git a/catalog-ui/app/scripts/view-models/welcome/welcome-view.ts b/catalog-ui/app/scripts/view-models/welcome/welcome-view.ts
deleted file mode 100644
index 0a0c923481..0000000000
--- a/catalog-ui/app/scripts/view-models/welcome/welcome-view.ts
+++ /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=========================================================
- */
-/// <reference path="../../references"/>
-module Sdc.ViewModels {
- 'use strict';
-
- export interface IWelcomeViewMode {
- slides:Array<Sdc.Directives.SlideData>;
- onCloseButton():void;
- onCloseVideoButton():void;
-
- video_mp4: string;
- video_ogg: string;
- }
-
- export class WelcomeViewModel {
-
- firstLoad:boolean = true;
- alreadyAnimated:Array<number> = [];
-
- static '$inject' = [
- '$scope',
- '$sce',
- 'sdcConfig',
- '$state',
- '$filter'
- ];
-
- constructor(
- private $scope:IWelcomeViewMode,
- private $sce:any,
- private sdcConfig: Models.IAppConfigurtaion,
- private $state:ng.ui.IStateService,
- private $filter:ng.IFilterService
- ){
- /*this.init();
- this.initScope();
- window.setTimeout(():void => {
- this.loadImages(():void=> {
- window.setTimeout(():void =>{
- $(".sdc-welcome-new-page").addClass("animated fadeIn");
- this.animateGeneral();
- this.animate1();
- },1000);
- });
- },0);*/
- }
-
- private initScope = ():void => {
-
- this.$scope.onCloseButton = ():void => {
- //console.log("onCloseButton");
- this.$state.go("dashboard", {});
- };
-
- this.$scope.onCloseVideoButton = ():void => {
- //console.log("onCloseVideoButton");
- $("#sdc-page-scroller").removeClass("animated fadeOut");
- $("#sdc-page-scroller").addClass("animated fadeIn");
- window.setTimeout(()=>{$("#sdc-page-scroller").css("display","block");},0);
-
- $("#sdc-welcome-video-wrapper").removeClass("animated fadeIn");
- $("#sdc-welcome-video-wrapper").addClass("animated fadeOut");
- window.setTimeout(()=>{$("#sdc-welcome-video-wrapper").css("display","none");},500);
-
- let videoElement:any = $("#asdc-welcome-video")[0];
- videoElement.pause();
- };
-
- let url: string = this.sdcConfig.api.welcome_page_video_url;
-
- this.$scope.video_mp4 = this.$sce.trustAsResourceUrl(url + ".mp4");
- this.$scope.video_ogg = this.$sce.trustAsResourceUrl(url + ".ogg");
-
- };
-
- private init = ():void => {
- let viewModelsHtmlBasePath:string = '/app/scripts/view-models/';
- this.$scope.slides = [
- {"url": viewModelsHtmlBasePath + 'welcome/slide0.html', "id": "slide-0", "index": 0, "callback": () => {this.animate0();}},
- {"url": viewModelsHtmlBasePath + 'welcome/slide1.html', "id": "slide-1", "index": 1, "callback": () => {}},
- {"url": viewModelsHtmlBasePath + 'welcome/slide2.html', "id": "slide-2", "index": 2, "callback": () => {this.animate2();}},
- {"url": viewModelsHtmlBasePath + 'welcome/slide3.html', "id": "slide-3", "index": 3, "callback": () => {this.animate3();}},
- {"url": viewModelsHtmlBasePath + 'welcome/slide4.html', "id": "slide-4", "index": 4, "callback": () => {this.animate4();}},
- {"url": viewModelsHtmlBasePath + 'welcome/slide5.html', "id": "slide-5", "index": 5, "callback": () => {this.animate5();}},
- {"url": viewModelsHtmlBasePath + 'welcome/slide6.html', "id": "slide-6", "index": 6, "callback": () => {this.animate6();}}
- ];
-
- $('body').keyup((e):void=> {
- if (e.keyCode == 27) { // escape key maps to keycode `27`
- this.$state.go('dashboard');
- }
- });
- };
-
- private animateGeneral = ():void => {
- //console.log("animateGeneral");
-
- /*// Animate the right navigation
- if (this.firstLoad===true) {
- //TODO: Israel
- //TweenLite.from('.page-nav', 2, {x: "100px", delay: 2});
- }
- */
-
- this.firstLoad = false;
- };
-
- /*private loadImages = (callback: Function):void => {
- let src = $('#slide-1 .asdc-welcome-frame').css('background-image');
- let url = src.match(/\((.*?)\)/)[1].replace(/('|")/g,'');
-
- let img = new Image();
- img.onload = function() {
- callback();
- //alert('image loaded');
- };
- img.src = url;
- /!*if (img.complete){
- callback;
- }*!/
- };*/
-
- private animate = (element:any, animation:string, when:number):void => {
- window.setTimeout(()=>{
- element.addClass("animated " + animation);
- if (element[0]) {
- element[0].style = "visibility: visible;";
- }
- },when);
- };
-
- private hide = (element:any, animation:string, animationToHide:string, when:number):void => {
- element.addClass("animated " + animation);
- element[0].style="visibility: hidden;";
- };
-
- private animate0 = ():void => {
- if (this.alreadyAnimated.indexOf(0)!==-1){
- return;
- } else {
- this.alreadyAnimated.push(0);
- }
- //console.log("slide 0 - animate");
- this.animate($('#slide-0 .bg-1'),'fadeInDown',500);
- this.animate($('#slide-0 .bg-2'),'fadeInDown',1000);
- this.animate($('#slide-0 .bg-3'),'fadeInDown',1500);
- this.animate($('#slide-0 .bg-4'),'fadeInDown',2000);
-
- this.animate($('#slide-0 .bg-5'),'fadeInDown',2500);
- this.animate($('#slide-0 .bg-6'),'fadeInDown',3000);
- this.animate($('#slide-0 .bg-7'),'fadeInDown',3500);
- this.animate($('#slide-0 .bg-8'),'fadeInDown',4000);
- };
-
- private animate1 = ():void => {
- if (this.alreadyAnimated.indexOf(1)!==-1){
- return;
- } else {
- this.alreadyAnimated.push(1);
- }
- //console.log("slide 1 - animate");
-
- this.animate($('#slide-1 .asdc-welcome-main-title'),'fadeInUp',1000);
- this.animate($('#slide-1 .asdc-welcome-main-message'),'fadeInUp',2000);
-
- this.animate($('#slide-1 .asdc-welcome-main-back-btn'),'fadeIn',3000);
-
- this.animate($('#slide-1 .asdc-welcome-video-icon'),'zoomIn',3000);
- this.animate($('#slide-1 .asdc-welcome-inner-circle'),'zoomIn',3000);
-
- this.animate($('.welcome-nav'),'slideInRight',2000);
- };
-
- private animate2 = ():void => {
- if (this.alreadyAnimated.indexOf(2)!==-1){
- return;
- } else {
- this.alreadyAnimated.push(2);
- }
- //console.log("slide 2 - animate");
- this.animate($('#slide-2 .asdc-welcome-frame-shape'),'zoomIn',500);
- this.animate($('#slide-2 .asdc-welcome-slide-text-box-content'),'fadeInUp',2000);
- this.animate($('#slide-2 .asdc-welcome-slide-text-box-title'),'fadeInUp',1000);
- };
-
- private animate3 = ():void => {
- if (this.alreadyAnimated.indexOf(3)!==-1){
- return;
- } else {
- this.alreadyAnimated.push(3);
- }
- //console.log("slide 3 - animate");
- this.animate($('#slide-3 .asdc-welcome-frame-shape'),'zoomIn',500);
- this.animate($('#slide-3 .asdc-welcome-slide-text-box-content'),'fadeInUp',2000);
- this.animate($('#slide-3 .asdc-welcome-slide-text-box-title'),'fadeInUp',1000);
- };
-
- private animate4 = ():void => {
- if (this.alreadyAnimated.indexOf(4)!==-1){
- return;
- } else {
- this.alreadyAnimated.push(4);
- }
- //console.log("slide 4 - animate");
- this.animate($('#slide-4 .asdc-welcome-frame-shape'),'zoomIn',500);
- this.animate($('#slide-4 .asdc-welcome-slide-text-box-content'),'fadeInUp',2000);
- this.animate($('#slide-4 .asdc-welcome-slide-text-box-title'),'fadeInUp',1000);
- };
-
- private animate5 = ():void => {
- if (this.alreadyAnimated.indexOf(5)!==-1){
- return;
- } else {
- this.alreadyAnimated.push(5);
- }
- //console.log("slide 5 - animate");
- this.animate($('#slide-5 .asdc-welcome-frame-shape'),'zoomIn',500);
- this.animate($('#slide-5 .asdc-welcome-slide-text-box-content'),'fadeInUp',2000);
- this.animate($('#slide-5 .asdc-welcome-slide-text-box-title'),'fadeInUp',1000);
- };
-
- private animate6 = ():void => {
- if (this.alreadyAnimated.indexOf(6)!==-1){
- return;
- } else {
- this.alreadyAnimated.push(6);
- }
- //console.log("slide 6 - animate");
- this.animate($('#slide-6 .asdc-welcome-main-message'),'fadeInUp',2000);
- this.animate($('#slide-6 .asdc-welcome-main-title'),'fadeInUp',1000);
- this.animate($('#slide-6 .asdc-welcome-main-back-btn'),'fadeInUp',3000);
- };
-
- private animateCss = (element:JQuery, animationName:string):void => {
- let animationEnd = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend';
- element.addClass('animated ' + animationName).one(animationEnd, function() {
- element.removeClass('animated ' + animationName);
- });
- };
-
- private unAnimateCss = (element:JQuery, animationName:string):void => {
- let animationEnd = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend';
- element.addClass('animated ' + animationName).one(animationEnd, function() {
- element.removeClass('animated ' + animationName);
- });
- };
-
- }
-}
diff --git a/catalog-ui/app/scripts/view-models/wizard/ReadMe.txt b/catalog-ui/app/scripts/view-models/wizard/ReadMe.txt
deleted file mode 100644
index ca5cfb988a..0000000000
--- a/catalog-ui/app/scripts/view-models/wizard/ReadMe.txt
+++ /dev/null
@@ -1,54 +0,0 @@
-import-asset wizard
-========================================================
-
-What should be done in each wizard step:
-----------------------------------------
-
-1. Each step scope should extend IAssetCreationStepScope (this way you can call methods on the wizard scope).
- Example:
- export interface IGeneralStepScope extends IAssetCreationStepScope {
-
- }
-
-2. Each step class should implements IAssetCreationStep
- Example: export class GeneralStepViewModel implements IAssetCreationStep {
-
- }
-
-3. Add the method: public save = (callback:Function):void => {}
- The method should perform the save and call: callback(true); in case of success, or callback(false); in case of error.
- Example:
- var onSuccess:Function = (resourceProperties:Services.IResourceResource) => {
- this.$scope.setAngularResourceOfResource(resourceProperties);
- var resourceObj = new Sdc.Models.Resource(resourceProperties);
- this.$scope.setEntity(resourceObj);
- this.$scope.latestEntityName = (resourceProperties.resourceName);
- callback(true);
- };
-
-4. Add the first line after the constructor: this.$scope.registerChild(this);
- This will register the current step reference in the wizard.
-
-5. Each step can get and set angular $resource of resource from the wizard.
- // Will be called from each step to get current entity.
- this.$scope.getAngularResourceOfResource = ():Services.IResourceResource => {
- return this.resourceProperties;
- };
-
- // Will be called from each step after save to update the resource.
- this.$scope.setAngularResourceOfResource = (resourceProperties:Services.IResourceResource):void => {
- this.resourceProperties = resourceProperties;
- this.fillAssetNameAndType();
- };
-
- Note: after success save, set setAngularResourceOfResource in the wizard (see example in step 3).
-
-6. The wizard needs to know if the step is valid (to know if to show next button), I used the following to update the wizard:
- this.$scope.$watch("editForm.$valid", function(newVal, oldVal){
- this.$scope.setValidState(newVal);
- });
-
- Note: in case there is no save for the step, and the step is always valid, call: this.$scope.setValidState(true);
-
-
-
diff --git a/catalog-ui/app/scripts/view-models/wizard/artifact-deployment-step/artifact-deployment-step.html b/catalog-ui/app/scripts/view-models/wizard/artifact-deployment-step/artifact-deployment-step.html
deleted file mode 100644
index 97817d59f2..0000000000
--- a/catalog-ui/app/scripts/view-models/wizard/artifact-deployment-step/artifact-deployment-step.html
+++ /dev/null
@@ -1,137 +0,0 @@
-<div class="artifact-deployment-step" data-ng-controller="Sdc.ViewModels.Wizard.ArtifactDeploymentStepViewModel">
-
- <div data-tests-id="add-deployment-artifact-button" data-tests-id="addGrey" class="w-sdc-classic-btn gray" data-ng-click="addOrUpdate({})">Add</div>
-
- <div class="table-container-flex">
-
- <div class="table">
-
- <div class="head flex-container">
- <div class="table-header head-row hand flex-item" data-ng-repeat="header in tableHeadersList track by $index" data-ng-click="sort(header.property)">{{header.title}}
- <span data-ng-if="sortBy === header.property" class="table-header-sort-arrow" data-ng-class="{'down': reverse, 'up':!reverse}"> </span>
- </div>
- <div class="table-no-text-header head-row flex-item"></div>
- </div>
-
- <form class="body" name="editForm">
-
- <perfect-scrollbar scroll-y-margin-offset="0" include-padding="true" class="scrollbar-container">
-
- <!-- Artifact row -->
- <div ng-if="noArtifactsToShow()" class="no-row-text" translate="DEPLOYMENT_ARTIFACT_NO_ARTIFACTS_TO_DISPLAY"></div>
- <div data-ng-repeat-start="artifact in artifacts | orderBy:sortBy:reverse track by $index"
- class="flex-container data-row"
- data-ng-class="{'selected': artifact.selected || undefined==artifact.selected && updateInProgress}"
- data-ng-if="artifact.esId">
-
- <div class="table-col-general flex-item" data-ng-click="update(artifact)">
- <loader data-display="isLoading"></loader>
- <span class="sprite table-arrow" data-tests-id="{{artifact.artifactDisplayName}}" data-ng-class="{'opened': artifact.selected || undefined==artifact.selected && updateInProgress}"></span>
- {{artifact.artifactDisplayName}}
- </div>
-
- <div class="table-col-general flex-item" data-tests-id="{{artifact.artifactType}}">
- {{artifact.artifactType}}
- </div>
- <div class="table-col-general flex-item" data-tests-id="{{artifact.timeout}}">
- {{artifact.timeout? artifact.timeout:''}}
- </div>
-
- <div class="table-btn-col flex-item" sdc-keyboard-events>
- <button class="table-edit-btn" data-ng-click="addOrUpdate(artifact)"></button>
- <button class="table-delete-btn" data-ng-click="delete(artifact)"> </button>
- </div>
- </div>
- <div data-ng-repeat-end="" data-ng-if="artifact.selected || undefined==artifact.selected && updateInProgress" class="w-sdc-form item-opened">
- <!-- Artifact panel opened -->
-
- <!-- Description field -->
- <div class="w-sdc-form-item" ng-form="descriptionForm" data-ng-class="{error:(descriptionForm.$dirty && descriptionForm.$invalid)}">
- <label class="i-sdc-env-form-label required">Description</label>
- <textarea class="i-sdc-form-textarea {{$index}}"
- data-ng-maxlength="256"
- maxlength="256"
- data-ng-required="true"
- name="description"
- data-ng-model="artifact.description"
- data-ng-model-options="{ debounce: 200 }"
- data-ng-pattern="getValidationPattern('string')"
- data-tests-id="description">
- </textarea>
-
- <div class="input-error" data-ng-show="descriptionForm.$dirty && descriptionForm.$invalid">
- <span ng-show="descriptionForm.$error.required" translate="ADD_ARTIFACT_ERROR_DESCRIPTION_REQUIRED"></span>
- <span ng-show="descriptionForm.$error.maxlength" translate="VALIDATION_ERROR_MAX_LENGTH" translate-values="{'max': '256' }"></span>
- <span ng-show="descriptionForm.$error.pattern" translate="VALIDATION_ERROR_SPECIAL_CHARS_NOT_ALLOWED"></span>
- </div>
-
- </div>
-
- <!-- Parameters in 2 columns -->
- <div class="w-sdc-form-columns-wrapper" data-ng-if="artifact.heatParameters">
- <!-- Left column -->
- <div class="w-sdc-form-column">
- <div class="i-sdc-form-item" ng-form="parameterForm" data-ng-repeat="parameter in artifact.heatParameters.slice(0, artifact.heatParameters.length%2+artifact.heatParameters.length/2) | orderBy: 'name' track by $index">
- <label class="i-sdc-env-form-label" data-ng-class="{required:parameter.defaultValue}" tooltip-side="top" sdc-smart-tooltip>{{parameter.name +' (' + parameter.type + ')'}}</label>
- <span class="parameter-description" tooltips tooltip-side="top" tooltip-content="{{parameter.description}}">?</span>
- <input class="i-sdc-form-input" data-ng-class="{error:(parameterForm.currentValue.$invalid)}"
- data-ng-model-options="{ debounce: 200 }"
- data-ng-model="parameter.currentValue"
- type="text"
- name="currentValue"
- data-ng-pattern="getValidationPattern(parameter.type, 'heat')"
- data-ng-required="parameter.defaultValue"
- data-ng-change="'json'==parameter.type && parameterForm.currentValue.$setValidity('pattern', validateJson(parameter.currentValue))"
- data-ng-blur="!parameterForm.currentValue.$error.pattern && resetValue(parameter)"
- />
-
- <div class="input-error" data-ng-show="parameterForm.currentValue.$invalid">
- <span ng-show="parameterForm.currentValue.$error.required" translate="VALIDATION_ERROR_REQUIRED" translate-values="{'field': 'Value'}"></span>
- <span ng-show="parameterForm.currentValue.$error.pattern && parameter.type==='string'" translate="VALIDATION_ERROR_SPECIAL_CHARS_NOT_ALLOWED"></span>
- <span ng-show="parameterForm.currentValue.$error.pattern && !(parameter.type==='string')" translate="VALIDATION_ERROR_TYPE" translate-values="{'type': '{{parameter.type}}'}"></span>
- </div>
- </div>
- </div>
-
- <!-- Right column -->
- <div class="w-sdc-form-column">
- <div class="i-sdc-form-item" ng-form="parameterForm" data-ng-repeat="parameter in artifact.heatParameters.slice(artifact.heatParameters.length%2+artifact.heatParameters.length/2) | orderBy: 'name' track by $index">
- <label class="i-sdc-env-form-label" data-ng-class="{required:parameter.defaultValue}" tooltip-side="top" sdc-smart-tooltip>{{parameter.name +' (' + parameter.type + ')'}}</label>
- <span class="parameter-description" tooltips tooltip-side="top" tooltip-content="{{parameter.description}}">?</span>
- <input class="i-sdc-form-input" data-ng-class="{error:(parameterForm.currentValue.$invalid)}"
- data-ng-model-options="{ debounce: 200 }"
- data-ng-model="parameter.currentValue"
- type="text"
- name="currentValue"
- data-ng-pattern="getValidationPattern(parameter.type, 'heat')"
- data-ng-required="parameter.defaultValue"
- data-ng-change="'json'==parameter.type && parameterForm.currentValue.$setValidity('pattern', validateJson(parameter.currentValue))"
- data-ng-blur="!parameterForm.currentValue.$error.pattern && resetValue(parameter)"
- />
-
- <div class="input-error" data-ng-show="parameterForm.currentValue.$invalid">
- <span ng-show="parameterForm.currentValue.$error.required" translate="VALIDATION_ERROR_REQUIRED" translate-values="{'field': 'Value'}"></span>
- <span ng-show="parameterForm.currentValue.$error.pattern && parameter.type==='string'" translate="VALIDATION_ERROR_SPECIAL_CHARS_NOT_ALLOWED"></span>
- <span ng-show="parameterForm.currentValue.$error.pattern && !(parameter.type==='string')" translate="VALIDATION_ERROR_TYPE" translate-values="{'type': '{{parameter.type}}'}"></span>
- </div>
- </div>
- </div>
-
- </div><!-- Close: Parameters in 2 columns -->
- </div><!-- Close: Artifact panel opened -->
-
- <!-- Add artifacts buttons -->
- <button class="add-button" data-ng-repeat="artifact in artifacts track by $index"
- data-ng-show="!artifact.esId"
- data-tests-id="{{artifact.artifactDisplayName}}"
- translate="DEPLOYMENT_ARTIFACT_BUTTON_ADD_HEAT"
- translate-values="{'name': '{{artifact.artifactDisplayName}}'}"
- data-ng-click="addOrUpdate(artifact)"></button>
-
- <!-- Top add button -->
- <button class="add-button" translate="DEPLOYMENT_ARTIFACT_BUTTON_ADD_OTHER" data-ng-click="addOrUpdate({})"></button>
- </perfect-scrollbar>
- </form>
- </div>
- </div>
-</div>
diff --git a/catalog-ui/app/scripts/view-models/wizard/artifact-deployment-step/artifact-deployment-step.less b/catalog-ui/app/scripts/view-models/wizard/artifact-deployment-step/artifact-deployment-step.less
deleted file mode 100644
index 043fba3277..0000000000
--- a/catalog-ui/app/scripts/view-models/wizard/artifact-deployment-step/artifact-deployment-step.less
+++ /dev/null
@@ -1,107 +0,0 @@
-.artifact-deployment-step {
-
- .table-container-flex .table .body .data-row + div.item-opened {
- padding: 10px 40px 10px 30px;
- }
-
- .w-sdc-classic-btn {
- float: right;
- margin-bottom: 10px;
- }
-
- .table {
- height:412px;
- margin-bottom: 0;
- }
-
- .parameter-description {
- .circle(18px, @color_p);
- content: '?';
- line-height: 18px;
- vertical-align: middle;
- margin-left: 5px;
- cursor: default;
- display: inline-block;
- position: absolute;
- top: 16px;
- }
-
- .table-container-flex {
-
- margin-top: 0px;
-
- .flex-item:nth-child(1) {
- flex-grow: 15;
- padding: 5px 4px;
- .hand;
- span.table-arrow {
- margin-right: 7px;
-
- }
- }
-
- .flex-item:nth-child(2) {
- padding: 5px 4px;
- flex-grow: 6;
- }
-
- .flex-item:nth-child(3) {
- padding: 5px 4px;
- flex-grow: 9;
- }
-
- .flex-item:nth-child(4) {
- padding: 5px 4px;
- flex-grow: 3;
- padding-top: 10px;
- }
- }
- .w-sdc-form{
- text-align: left;
-
- .w-sdc-env-params{
- border-top: 1px solid #cdcdcd;
- margin: 25px 0 10px 0;
- }
-
- .i-sdc-form-textarea {
- border: 1px solid @color_e;
- min-height: 60px;
- padding: 10px 13px;
- width: 100%;
- resize: none;
-
- &:disabled {
- .disabled;
- }
- }
-
- .w-sdc-form-item {
- &.error {
- .i-sdc-form-input,
- .i-sdc-form-select,
- .i-sdc-form-textarea {
- border-color: @color_h;
- outline: none;
- box-sizing: border-box;
- }
- }
- }
-
- .i-sdc-env-form-label{
- .p_9;
- overflow: hidden;
- max-width: 245px;
- text-overflow: ellipsis;
- display: inline-block;
- white-space: nowrap;
- margin-top: 14px;
-
- &.required::before {
- color: #f33;
- content: '*';
- margin-right: 4px;
- }
- }
- }
-}
diff --git a/catalog-ui/app/scripts/view-models/wizard/artifact-deployment-step/artifact-deployment-step.ts b/catalog-ui/app/scripts/view-models/wizard/artifact-deployment-step/artifact-deployment-step.ts
deleted file mode 100644
index 80f145b9b1..0000000000
--- a/catalog-ui/app/scripts/view-models/wizard/artifact-deployment-step/artifact-deployment-step.ts
+++ /dev/null
@@ -1,228 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../../references"/>
-module Sdc.ViewModels.Wizard {
- 'use strict';
- import ArtifactModel = Sdc.Models.ArtifactModel;
-
- interface IArtifactDeploymentStepViewModelScope extends IWizardCreationStepScope {
- tableHeadersList: Array<any>;
- reverse: boolean;
- sortBy:string;
- component: Models.Components.Component;
- artifacts: Array<Models.ArtifactModel>;
- editForm:ng.IFormController;
- isLoading:boolean;
- artifactDescriptions:any;
- updateInProgress:boolean;
-
- addOrUpdate(artifact:Models.ArtifactModel): void;
- update(artifact:Models.ArtifactModel): void;
- delete(artifact:Models.ArtifactModel): void;
- sort(sortBy:string): void;
- noArtifactsToShow():boolean;
- getValidationPattern(validationType:string, parameterType?:string):RegExp;
- validateJson(json:string):boolean;
- resetValue(parameter:any):void;
- }
-
- export class ArtifactDeploymentStepViewModel implements IWizardCreationStep {
-
- static '$inject' = [
- '$scope',
- '$filter',
- '$modal',
- '$templateCache',
- 'ValidationUtils',
- 'ModalsHandler'
- ];
-
- constructor(
- private $scope:IArtifactDeploymentStepViewModelScope,
- private $filter:ng.IFilterService,
- private $modal:ng.ui.bootstrap.IModalService,
- private $templateCache:ng.ITemplateCacheService,
- private validationUtils: Sdc.Utils.ValidationUtils,
- private ModalsHandler: Utils.ModalsHandler
- ){
- this.$scope.registerChild(this);
- this.$scope.setValidState(true);
- this.initScope();
- }
-
- private initDescriptions = ():void =>{
- this.$scope.artifactDescriptions = {};
- _.forEach(this.$scope.component.deploymentArtifacts,(artifact:Models.ArtifactModel):void => {
- this.$scope.artifactDescriptions[artifact.artifactLabel] = artifact.description;
- });
- };
-
-
- private setArtifact = (artifact:Models.ArtifactModel):void =>{
- if(artifact.heatParameters) {
- artifact.heatParameters.forEach((parameter:any):void => {
- if (!parameter.currentValue && parameter.defaultValue) {
- parameter.currentValue = parameter.defaultValue;
- } else if ("" === parameter.currentValue) {
- parameter.currentValue = null;
- }
- });
- }
- if(!artifact.description || !this.$scope.getValidationPattern('string').test(artifact.description)){
- artifact.description = this.$scope.artifactDescriptions[artifact.artifactLabel];
- }
- };
-
- private updateAll = ():void =>{
- let artifacts:Array<Models.ArtifactModel>= [];
- _.forEach(this.$scope.component.deploymentArtifacts,(artifact:Models.ArtifactModel): void => {
- if(artifact.selected) {
- this.setArtifact(artifact);
- artifacts.push(artifact);
- }
- });
- this.$scope.component.updateMultipleArtifacts(artifacts);
- };
-
-
-
- private initScope = (): void => {
- let self = this;
- this.$scope.isLoading = false;
- this.$scope.updateInProgress = false;
- this.$scope.component = this.$scope.getComponent();
- this.initDescriptions();
- this.$scope.artifacts = <ArtifactModel[]>_.values(this.$scope.component.deploymentArtifacts);
-
-
- this.$scope.tableHeadersList = [
- {title:'Name', property: 'artifactDisplayName'},
- {title:'Type', property: 'artifactType'},
- {title:'Deployment timeout', property: 'timeout'}
- ];
-
- this.$scope.sort = (sortBy:string):void => {
- this.$scope.reverse = (this.$scope.sortBy === sortBy) ? !this.$scope.reverse : false;
- this.$scope.sortBy = sortBy;
- };
-
- this.$scope.getValidationPattern = (validationType:string, parameterType?:string):RegExp => {
- return this.validationUtils.getValidationPattern(validationType, parameterType);
- };
-
- this.$scope.validateJson = (json:string):boolean => {
- if(!json){
- return true;
- }
- return this.validationUtils.validateJson(json);
- };
-
-
- this.$scope.addOrUpdate = (artifact:Models.ArtifactModel): void => {
- artifact.artifactGroupType = 'DEPLOYMENT';
- let artifactCopy = new Models.ArtifactModel(artifact);
- this.ModalsHandler.openWizardArtifactModal(artifactCopy, this.$scope.component).then(() => {
- this.$scope.artifactDescriptions[artifactCopy.artifactLabel]= artifactCopy.description;
- this.$scope.artifacts = <ArtifactModel[]>_.values(this.$scope.component.deploymentArtifacts);
- })
- };
-
- this.$scope.noArtifactsToShow = ():boolean =>{
- return !_.some(this.$scope.artifacts, 'esId');
- };
-
- this.$scope.resetValue = (parameter:any):void => {
- if(!parameter.currentValue && parameter.defaultValue){
- parameter.currentValue = parameter.defaultValue;
- }
- else if('boolean'==parameter.type){
- parameter.currentValue = parameter.currentValue.toUpperCase();
- }
- };
-
-
- this.$scope.$watch('editForm.$valid', ():void => {
- if(this.$scope.editForm) {
- this.$scope.setValidState(this.$scope.editForm.$valid);
- }
- });
-
- this.$scope.update = (artifact:Models.ArtifactModel):void =>{
- if(false == this.$scope.isLoading) {
- if(artifact.selected) {
- this.$scope.isLoading = true;
- this.$scope.updateInProgress = true;
- let onSuccess = (responseArtifact:Models.ArtifactModel):void => {
- this.$scope.artifactDescriptions[responseArtifact.artifactLabel] = responseArtifact.description;
- this.$scope.artifacts = <ArtifactModel[]>_.values(this.$scope.component.deploymentArtifacts);
- this.$scope.isLoading = false;
- this.$scope.updateInProgress = false;
- artifact.selected = !artifact.selected;
- };
-
- let onFailed = (error:any):void => {
- console.log('Delete artifact returned error:', error);
- this.$scope.isLoading = false;
- this.$scope.updateInProgress = false;
- artifact.selected = !artifact.selected;
- };
-
- this.setArtifact(artifact);
- this.$scope.component.addOrUpdateArtifact(artifact).then(onSuccess, onFailed);
- } else {
- artifact.selected = !artifact.selected;
- }
- }
- };
-
- this.$scope.delete = (artifact:Models.ArtifactModel):void => {
- let onOk = ():void => {
- this.$scope.isLoading = true;
- let onSuccess = ():void => {
- this.$scope.isLoading = false;
- this.$scope.artifacts = <ArtifactModel[]>_.values(this.$scope.component.deploymentArtifacts);
- };
-
- let onFailed = (error:any):void => {
- this.$scope.isLoading = false;
- console.log('Delete artifact returned error:', error);
- };
-
- this.$scope.component.deleteArtifact(artifact.uniqueId, artifact.artifactLabel).then(onSuccess, onFailed);
- };
-
- let title:string = self.$filter('translate')("ARTIFACT_VIEW_DELETE_MODAL_TITLE");
- let message:string = self.$filter('translate')("ARTIFACT_VIEW_DELETE_MODAL_TEXT", "{'name': '" + artifact.artifactDisplayName + "'}");
- this.ModalsHandler.openConfirmationModal(title, message, false).then(onOk);
- };
- };
-
- public save = (callback:Function):void => {
- this.updateAll();
- this.$scope.setComponent(this.$scope.component);
- callback(true);
- };
-
- public back = (callback:Function):void => {
- this.$scope.setComponent(this.$scope.component);
- callback(true);
- }
- }
-}
diff --git a/catalog-ui/app/scripts/view-models/wizard/artifact-form-step/artifact-form-step-view-model.ts b/catalog-ui/app/scripts/view-models/wizard/artifact-form-step/artifact-form-step-view-model.ts
deleted file mode 100644
index 459729c179..0000000000
--- a/catalog-ui/app/scripts/view-models/wizard/artifact-form-step/artifact-form-step-view-model.ts
+++ /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=========================================================
- */
-/// <reference path="../../../references"/>
-module Sdc.ViewModels.Wizard {
- 'use strict';
- import Resource = Sdc.Models.Components.Resource;
-
- export interface IEditArtifactStepModel {
- artifactResource: Models.ArtifactModel;
- artifactTypes: Array<string>;
- artifactsFormList: any;
- artifactFile:any;
- }
-
- export interface IArtifactResourceFormStepViewModelScope extends ng.IScope {
- editForm:ng.IFormController;
- forms:any;
- footerButtons: Array<any>;
- isNew: boolean;
- isPlaceHolderArtifact:boolean;
- isLoading: boolean;
- validationPattern: RegExp;
- urlValidationPattern: RegExp;
- labelValidationPattern: RegExp;
- integerValidationPattern: RegExp;
- commentValidationPattern: RegExp;
- artifactType: string;
- artifactGroupType:string;
- editArtifactResourceModel: IEditArtifactStepModel;
- defaultHeatTimeout: number;
- validExtensions: any;
- originalArtifactName: string;
- modalInstanceArtifact:ng.ui.bootstrap.IModalServiceInstance;
- selectedArtifact:string;
-
- fileExtensions():string;
- save(): void;
- close(): void;
- changeArtifact(selectedArtifact:string):void;
- getOptions(): Array<string>;
- removeInputLabel(): void;
- fileUploadRequired():string;
- isDeploymentHeat():boolean;
- setDefaultTimeout():void;
- getFormTitle():string;
- }
-
- export class ArtifactResourceFormStepViewModel {
-
- static '$inject' = [
- '$scope',
- '$modalInstance',
- 'artifact',
- 'component',
- 'Sdc.Services.CacheService',
- 'ValidationPattern',
- 'UrlValidationPattern',
- 'LabelValidationPattern',
- 'IntegerValidationPattern',
- 'CommentValidationPattern',
- 'ValidationUtils',
- 'ArtifactsUtils',
- '$state',
- '$modal',
- '$templateCache'
- ];
-
- private formState:Utils.Constants.FormState;
- private entityId:string;
-
- constructor(private $scope:IArtifactResourceFormStepViewModelScope,
- private $modalInstance:ng.ui.bootstrap.IModalServiceInstance,
- private artifact:Models.ArtifactModel,
- private component:Models.Components.Component,
- private cacheService:Services.CacheService,
- private ValidationPattern:RegExp,
- private UrlValidationPattern:RegExp,
- private LabelValidationPattern:RegExp,
- private IntegerValidationPattern:RegExp,
- private CommentValidationPattern:RegExp,
- private ValidationUtils:Sdc.Utils.ValidationUtils,
- private ArtifactsUtils:Sdc.Utils.ArtifactsUtils,
- private $state:any,
- private $modal:ng.ui.bootstrap.IModalService,
- private $templateCache:ng.ITemplateCacheService) {
-
-
- this.entityId = this.component.uniqueId;
- this.formState = angular.isDefined(artifact.artifactLabel) ? Utils.Constants.FormState.UPDATE : Utils.Constants.FormState.CREATE;
-
- this.initScope();
- this.initEditArtifactResourceModel();
- this.initComponent();
- this.initArtifactTypes();
- }
-
- private initEditArtifactResourceModel = ():void => {
- this.$scope.editArtifactResourceModel = {
- artifactResource: null,
- artifactTypes: null,
- artifactsFormList: {},
- artifactFile: {}
- }
- };
-
- private initComponent = ():void => {
- this.$scope.editArtifactResourceModel.artifactResource = this.artifact;
- this.$scope.originalArtifactName = this.artifact.artifactName;
- let artifacts:any = Utils.Constants.ArtifactGroupType.INFORMATION === this.artifact.artifactGroupType?
- this.component.artifacts : this.component.deploymentArtifacts;
- this.$scope.editArtifactResourceModel.artifactsFormList = _.pick(artifacts, (artifact:Models.ArtifactModel)=> {
- return artifact.artifactLabel && !artifact.esId;
- });
- this.$scope.editArtifactResourceModel.artifactFile.filename= this.artifact.artifactName?this.artifact.artifactName:'';
-
- if(this.artifact.artifactLabel){//this is edit mode
- this.$scope.editArtifactResourceModel.artifactsFormList[this.artifact.artifactLabel]= this.artifact;
- this.$scope.selectedArtifact = this.artifact.artifactDisplayName;
- }
- };
-
- private initArtifactTypes = ():void => {
- let artifactTypes:any = this.cacheService.get('UIConfiguration');
-
- if (Utils.Constants.ArtifactGroupType.INFORMATION === this.artifact.artifactGroupType) {
- this.$scope.editArtifactResourceModel.artifactTypes = artifactTypes.artifacts.other.map((element:any)=> {
- return element.name;
- });
- _.remove(this.$scope.editArtifactResourceModel.artifactTypes, (item:string)=> {
- return _.has(Utils.Constants.ArtifactType.THIRD_PARTY_RESERVED_TYPES, item) ||
- _.has(Utils.Constants.ArtifactType.TOSCA, item);
- })
- }else if(Utils.Constants.ArtifactGroupType.DEPLOYMENT === this.artifact.artifactGroupType) {
-
- this.$scope.validExtensions = artifactTypes.artifacts.deployment.resourceDeploymentArtifacts;
- if(this.$scope.validExtensions) {
- this.$scope.editArtifactResourceModel.artifactTypes = Object.keys(this.$scope.validExtensions);
- }
- this.$scope.defaultHeatTimeout = artifactTypes.defaultHeatTimeout;
-
- if(!this.$scope.isPlaceHolderArtifact) {
- _.remove(this.$scope.editArtifactResourceModel.artifactTypes, (item:string)=> {
- return Utils.Constants.ArtifactType.HEAT == item.substring(0,4) ||
- _.has(Utils.Constants.ArtifactType.THIRD_PARTY_RESERVED_TYPES, item);
- })
- }
-
- if(this.component.isResource() && (<Resource>this.component).isCsarComponent()) {
- _.remove(this.$scope.editArtifactResourceModel.artifactTypes, (item:string) => {
- return this.ArtifactsUtils.isLicenseType(item);
- })
- }
- }
- };
-
- private initScope = ():void => {
-
- this.$scope.modalInstanceArtifact = this.$modalInstance;
- this.$scope.validationPattern = this.ValidationPattern;
- this.$scope.urlValidationPattern = this.UrlValidationPattern;
- this.$scope.labelValidationPattern = this.LabelValidationPattern;
- this.$scope.integerValidationPattern = this.IntegerValidationPattern;
- this.$scope.commentValidationPattern = this.CommentValidationPattern;
- this.$scope.isLoading = false;
- this.$scope.isPlaceHolderArtifact = true;
- this.$scope.isNew = (this.formState === Utils.Constants.FormState.CREATE);
- this.$scope.artifactGroupType = this.artifact.artifactGroupType;
- this.$scope.selectedArtifact = '?';
-
- this.$scope.fileExtensions = ():string => {
- let type:string = this.$scope.editArtifactResourceModel.artifactResource.artifactType;
- return type && this.$scope.validExtensions && this.$scope.validExtensions[type].acceptedTypes ?
- this.$scope.validExtensions[type].acceptedTypes.join(',') : "";
- };
-
- this.$scope.removeInputLabel = ():void => {
- this.$scope.isPlaceHolderArtifact = true;
- };
-
- this.$scope.fileUploadRequired = ():string => {
- if (this.$scope.isNew===false){
- return 'false'; // This is edit mode
- } else {
- return 'true';
- }
- };
-
- this.$scope.isDeploymentHeat = ():boolean =>{
- return Utils.Constants.ArtifactGroupType.DEPLOYMENT === this.artifact.artifactGroupType
- && this.$scope.editArtifactResourceModel.artifactResource
- && this.$scope.editArtifactResourceModel.artifactResource.artifactType
- && Utils.Constants.ArtifactType.HEAT === this.$scope.editArtifactResourceModel.artifactResource.artifactType.substring(0,4);
- };
-
- this.$scope.getFormTitle =(): string =>{
- let title:string = this.artifact.esId? 'Update':'Add';
- if (Utils.Constants.ArtifactGroupType.DEPLOYMENT === this.artifact.artifactGroupType) {
- title += ' Deployment';
- }
- title += ' Artifact';
- return title;
- };
-
- this.$scope.setDefaultTimeout = ():void => {
- if(!this.$scope.editArtifactResourceModel.artifactResource.timeout) {
- this.$scope.editArtifactResourceModel.artifactResource.timeout = this.$scope.defaultHeatTimeout;
- }
- };
-
- this.$scope.changeArtifact = (selectedArtifact:string):void => {
- let tempArtifact:Models.ArtifactModel = this.$scope.editArtifactResourceModel.artifactResource;
- this.$scope.editArtifactResourceModel.artifactResource = null;
-
- if (selectedArtifact && selectedArtifact != '' && selectedArtifact != '?') {
- let artifactResource = <Models.ArtifactModel>_.find(this.$scope.editArtifactResourceModel.artifactsFormList,{'artifactDisplayName':selectedArtifact});
- this.$scope.editArtifactResourceModel.artifactResource = new Sdc.Models.ArtifactModel(artifactResource);
- this.$scope.originalArtifactName = this.$scope.editArtifactResourceModel.artifactResource.artifactName;
- this.$scope.isPlaceHolderArtifact = true;
- if(this.$scope.isDeploymentHeat()){
- this.$scope.setDefaultTimeout();
- }
- } else if (selectedArtifact === "") {
- //this.$scope.editArtifactResourceModel.artifactFile = {};
- this.$scope.editArtifactResourceModel.artifactResource = <Models.ArtifactModel>{};
- this.$scope.editArtifactResourceModel.artifactResource.artifactGroupType = this.$scope.artifactGroupType;
- this.$scope.isPlaceHolderArtifact = false;
- }
-
- if (_.size(this.$scope.editArtifactResourceModel.artifactFile) && this.$scope.editArtifactResourceModel.artifactResource) {
- this.$scope.editArtifactResourceModel.artifactResource.artifactName = this.$scope.editArtifactResourceModel.artifactFile.filename;
- }
- if(tempArtifact && tempArtifact.description != ''){
- this.$scope.editArtifactResourceModel.artifactResource.description = tempArtifact.description;
- }
-
- this.initArtifactTypes();
- this.$scope.isNew = true;
-
- };
-
-
- this.$scope.save = ():void => {
- this.$scope.isLoading = true;
- this.$scope.editArtifactResourceModel.artifactResource.description =
- this.ValidationUtils.stripAndSanitize(this.$scope.editArtifactResourceModel.artifactResource.description);
-
- if (this.$scope.editArtifactResourceModel.artifactFile) {
- this.$scope.editArtifactResourceModel.artifactResource.payloadData = this.$scope.editArtifactResourceModel.artifactFile.base64;
- this.$scope.editArtifactResourceModel.artifactResource.artifactName = this.$scope.editArtifactResourceModel.artifactFile.filename;
- }
-
- let onFailed = (response) => {
- this.$scope.isLoading = false;
- console.info('onFaild', response);
- this.$scope.editArtifactResourceModel.artifactResource.esId = undefined;
- };
-
- let onSuccess = () => {
- this.$scope.isLoading = false;
- this.$scope.originalArtifactName = "";
- this.$modalInstance.close();
-
- };
-
- this.component.addOrUpdateArtifact(this.$scope.editArtifactResourceModel.artifactResource).then(onSuccess, onFailed);
- };
-
-
- this.$scope.close = ():void => {
- this.$modalInstance.dismiss();
- };
-
- //new form layout for import asset
- this.$scope.forms = {};
- this.$scope.footerButtons = [
- {'name': this.artifact.esId ? 'Update' : 'Add', 'css': 'blue', 'callback': this.$scope.save},
- {'name': 'Cancel', 'css': 'grey', 'callback': this.$scope.close}
- ];
-
- this.$scope.$watch("forms.editForm.$invalid", (newVal, oldVal) => {
- this.$scope.footerButtons[0].disabled = this.$scope.forms.editForm.$invalid;
- });
-
- }
-
- }
-}
diff --git a/catalog-ui/app/scripts/view-models/wizard/artifact-form-step/artifact-form-step-view.html b/catalog-ui/app/scripts/view-models/wizard/artifact-form-step/artifact-form-step-view.html
deleted file mode 100644
index 2643b99c20..0000000000
--- a/catalog-ui/app/scripts/view-models/wizard/artifact-form-step/artifact-form-step-view.html
+++ /dev/null
@@ -1,147 +0,0 @@
-<sdc-modal modal="modalInstanceArtifact" type="classic" class="sdc-add-artifact" buttons="footerButtons" header="{{getFormTitle()}}" show-close-button="true">
-
- <loader data-display="isLoading"></loader>
-
- <form novalidate class="w-sdc-form two-columns" name="forms.editForm">
-
- <!--------------------- ARTIFACT FILE -------------------->
- <div class="i-sdc-form-item">
- <label class="required">Upload File</label>
- <file-upload id="fileUploadElement"
- form-element="forms.editForm"
- element-required="{{fileUploadRequired()}}"
- element-name="myArtifactFile"
- file-model="editArtifactResourceModel.artifactFile"
- extensions="{{fileExtensions()}}"
- data-ng-class="{'error': forms.editForm.myArtifactFile.$dirty && forms.editForm.myArtifactFile.$invalid}"></file-upload>
-
- <div class="input-error-file-upload" data-ng-show="forms.editForm.myArtifactFile.$dirty && forms.editForm.myArtifactFile.$invalid">
- <span ng-show="forms.editForm.myArtifactFile.$error.required && !forms.editForm.myArtifactFile.$error.emptyFile" translate="ADD_ARTIFACT_ERROR_FILE_REQUIRED"></span>
- <span ng-show="forms.editForm.myArtifactFile.$error.maxsize" translate="VALIDATION_ERROR_MAX_FILE_SIZE"></span>
- <span ng-if="'DEPLOYMENT' === artifactGroupType" ng-show="forms.editForm.myArtifactFile.$error.filetype" translate="ADD_ARTIFACT_ERROR_VALID_EXTENSIONS" translate-values="{'extensions': '{{fileExtensions()}}'}"></span>
- <span ng-show="forms.editForm.myArtifactFile.$error.emptyFile" translate="VALIDATION_ERROR_EMPTY_FILE"></span>
- </div>
- </div>
- <!--------------------- ARTIFACT FILE -------------------->
-
- <div class="w-sdc-form-columns-wrapper">
- <div class="w-sdc-form-column">
-
- <div class="i-sdc-form-item" data-ng-class="{error:(forms.editForm.placeHolder.$dirty && forms.editForm.placeHolder.$invalid)}" data-ng-show="isPlaceHolderArtifact">
- <label class="i-sdc-form-label required">Artifact</label>
- <select class="i-sdc-form-select"
- name="placeHolder"
- data-ng-disabled="!isNew"
- data-ng-model="selectedArtifact"
- data-ng-change="changeArtifact(selectedArtifact)"
- data-tests-id="selectArtifact">
- <option disabled value="?">Select Artifact</option>
- <option data-ng-repeat="(key,value) in editArtifactResourceModel.artifactsFormList">{{value.artifactDisplayName}}</option>
- <option value="">Create New Artifact</option>
-
- </select>
-
- <div class="input-error" data-ng-show="forms.editForm.placeHolder.$dirty && forms.editForm.placeHolder.$invalid">
- <span ng-show="forms.editForm.placeHolder.$error.required" translate="ADD_ARTIFACT_ERROR_TYPE_REQUIRED"></span>
- </div>
- </div>
-
- <div class="i-sdc-form-item" data-ng-class="{error:(forms.editForm.artifactLabel.$dirty && forms.editForm.artifactLabel.$invalid)}" data-ng-show="!isPlaceHolderArtifact">
- <label class="i-sdc-form-label required">Artifact Label</label>
- <input class="i-sdc-form-input"
- data-ng-maxlength="25"
- data-ng-model="editArtifactResourceModel.artifactResource.artifactLabel"
- type="text"
- name="artifactLabel"
- data-required
- data-ng-model-options="{ debounce: 200 }"
- data-ng-pattern="labelValidationPattern"
- maxlength="25"
- data-ng-disabled="!isNew || editArtifactResourceModel.artifactResource.mandatory"
- data-tests-id="artifactLabel"
- autofocus/>
- <span class="w-sdc-icon-cancel" data-ng-click="selectedArtifact='?'; removeInputLabel()"></span>
-
- <div class="input-error" data-ng-show="forms.editForm.artifactLabel.$dirty && forms.editForm.artifactLabel.$invalid">
- <span ng-show="forms.editForm.artifactLabel.$error.required" translate="ADD_ARTIFACT_ERROR_LABEL_REQUIRED"></span>
- <span ng-show="forms.editForm.artifactLabel.$error.maxlength" translate="VALIDATION_ERROR_MAX_LENGTH" translate-values="{'max': '25' }"></span>
- <span ng-show="forms.editForm.artifactLabel.$error.pattern" translate="VALIDATION_ERROR_SPECIAL_CHARS_NOT_ALLOWED"></span>
- </div>
- </div>
-
- <div class="i-sdc-form-item" data-ng-class="{error:(forms.editForm.timeout.$dirty && forms.editForm.timeout.$invalid)}"
- data-ng-if="isDeploymentHeat()">
- <label class="i-sdc-form-label">Deployment Timeout (minutes)</label>
- <input class="i-sdc-form-input"
- data-ng-maxlength="25"
- data-ng-model="editArtifactResourceModel.artifactResource.timeout"
- type="number"
- name="timeout"
- min="1"
- max="2147483647"
- data-ng-model-options="{ debounce: 200 }"
- data-ng-pattern="integerValidationPattern"
- data-ng-init="setDefaultTimeout()"
- data-ng-change="setDefaultTimeout()"
- maxlength="25"
- data-tests-id="timeout"/>
-
- <div class="input-error" data-ng-show="forms.editForm.timeout.$dirty && forms.editForm.timeout.$invalid">
- <span ng-show="forms.editForm.timeout.$error.maxlength" translate="VALIDATION_ERROR_MAX_LENGTH" translate-values="{'max': '25' }"></span>
- <span ng-show="forms.editForm.timeout.$error.pattern" translate="ADD_ARTIFACT_ERROR_TIMEOUT_PATTERN"></span>
- <span ng-show="forms.editForm.timeout.$error.min" translate="ADD_ARTIFACT_ERROR_TIMEOUT_MIN"></span>
- </div>
- </div>
- <div class="i-sdc-form-item" data-ng-class="{error:(forms.editForm.type.$dirty && forms.editForm.type.$invalid)}">
- <label class="i-sdc-form-label required">Type</label>
- <select class="i-sdc-form-select"
- data-required
- name="type"
- data-ng-disabled="!isNew || editArtifactResourceModel.artifactResource.mandatory || '?'==selectedArtifact"
- data-ng-model="editArtifactResourceModel.artifactResource.artifactType"
- data-ng-options="type as type for type in editArtifactResourceModel.artifactTypes track by type | uppercase"
- data-tests-id="artifacttype">
- <option value="">Choose Type</option>
- </select>
-
- <div class="input-error" data-ng-show="forms.editForm.type.$dirty && forms.editForm.type.$invalid">
- <span ng-show="forms.editForm.type.$error.required" translate="ADD_ARTIFACT_ERROR_TYPE_REQUIRED"></span>
- </div>
-
- </div>
- </div>
-
- <div class="w-sdc-form-column">
-
- <div class="i-sdc-form-item"
- data-ng-class="{error:(forms.editForm.description.$dirty && forms.editForm.description.$invalid)}">
- <label class="i-sdc-form-label required">Description</label>
- <textarea class="i-sdc-form-textarea"
- data-ng-maxlength="256"
- maxlength="256"
- data-required
- name="description"
- data-ng-model="editArtifactResourceModel.artifactResource.description"
- data-ng-model-options="{ debounce: 200 }"
- data-ng-pattern="commentValidationPattern"
- data-tests-id="description"
- >
- </textarea>
-
- <div class="input-error" data-ng-show="forms.editForm.description.$dirty && forms.editForm.description.$invalid">
- <span ng-show="forms.editForm.description.$error.required" translate="ADD_ARTIFACT_ERROR_DESCRIPTION_REQUIRED"></span>
- <span ng-show="forms.editForm.description.$error.maxlength" translate="VALIDATION_ERROR_MAX_LENGTH" translate-values="{'max': '256' }"></span>
- <span ng-show="forms.editForm.description.$error.pattern" translate="VALIDATION_ERROR_SPECIAL_CHARS_NOT_ALLOWED"></span>
- </div>
-
- </div>
- </div>
- </div>
-
- <span class="w-sdc-form-note" data-ng-show="forms.editForm.$invalid && false" translate="LABEL_ALL_FIELDS_ARE_MANDATORY"></span>
-
- </form>
-
-</sdc-modal>
-
-
diff --git a/catalog-ui/app/scripts/view-models/wizard/artifact-form-step/artifact-form-step.less b/catalog-ui/app/scripts/view-models/wizard/artifact-form-step/artifact-form-step.less
deleted file mode 100644
index a189c12d62..0000000000
--- a/catalog-ui/app/scripts/view-models/wizard/artifact-form-step/artifact-form-step.less
+++ /dev/null
@@ -1,45 +0,0 @@
-.sdc-add-artifact {
-
- .w-sdc-form-note {
- .h_9;
- display: block;
- position: relative;
- top: 13px;
- }
-
- .w-sdc-form {
-
- .i-sdc-form-textarea{
- min-height: 95px;
- }
-
- .i-sdc-form-item.upload input[type="file"] {
- display: none
- }
-
- .w-sdc-icon-cancel {
- position: absolute;
- right: 7px;
- top: 33px;
- .sprite;
- .sprite.small-x-btn-black;
- .hand;
- }
- }
-
- .artifact-info {
- text-align: left;
- color: rgb(140, 140, 140);
- font-size: 13px;
- margin-top: -40px;
- margin-bottom: 5px;
- width: 600px;
- min-height: initial;
-
- span {
- color: #666666;
- padding-left: 4px;
- }
- }
-
-}
diff --git a/catalog-ui/app/scripts/view-models/wizard/artifact-information-step/artifact-information-step.html b/catalog-ui/app/scripts/view-models/wizard/artifact-information-step/artifact-information-step.html
deleted file mode 100644
index ea4566561c..0000000000
--- a/catalog-ui/app/scripts/view-models/wizard/artifact-information-step/artifact-information-step.html
+++ /dev/null
@@ -1,48 +0,0 @@
-<div class="artifact-step" data-ng-controller="Sdc.ViewModels.Wizard.ArtifactInformationStepViewModel">
- <div data-tests-id="add-information-artifact-button" data-tests-id="addGrey" class="w-sdc-classic-btn gray" data-ng-click="addOrUpdate({})" type="button">Add </div>
- <div class="table-container-flex">
- <div class="table">
- <div class="head flex-container">
- <div class="table-header head-row hand flex-item" ng-repeat="header in tableHeadersList track by $index" data-ng-click="sort(header.property)">{{header.title}}
- <span data-ng-show="sortBy === header.property" class="table-header-sort-arrow" data-ng-class="{'down': reverse, 'up':!reverse}"> </span>
- </div>
- <div class="table-no-text-header head-row flex-item"></div>
- </div>
- <div class="body">
- <perfect-scrollbar suppress-scroll-x="true" scroll-y-margin-offset="0" include-padding="true" class="scrollbar-container">
- <div data-ng-if="showNoArtifactMessage()" class="no-row-text">
- There are no information artifacts to display
- </div>
- <div data-ng-repeat-start="artifact in artifacts| orderBy:sortBy:reverse track by $index"
- class="flex-container data-row"
- data-ng-class="{'selected': artifact.selected}"
- data-ng-if="artifact.esId">
-
- <div class="table-col-general flex-item" data-ng-click="artifact.selected = !artifact.selected">
- <span class="sprite table-arrow" data-ng-class="{'opened': artifact.selected}" data-tests-id="{{artifact.artifactDisplayName}}"></span>
- {{artifact.artifactDisplayName}}
- </div>
-
- <div class="table-col-general flex-item" data-ng-click="artifact.selected = !artifact.selected" data-tests-id="{{artifact.artifactType}}">
- {{artifact.artifactType}}
- </div>
-
- <div class="table-btn-col flex-item" sdc-keyboard-events>
- <button class="table-edit-btn" data-ng-click="addOrUpdate(artifact)"></button>
- <button class="table-delete-btn" data-ng-click="delete(artifact)"> </button>
- </div>
- </div>
- <div data-ng-repeat-end="" data-ng-if="artifact.selected" class="item-opened" data-ng-bind="artifact.description"></div>
- <button class="add-button" data-ng-repeat="artifact in artifacts track by $index"
- data-ng-show="!artifact.esId"
- data-tests-id="{{artifact.artifactDisplayName}}"
- translate="DEPLOYMENT_ARTIFACT_BUTTON_ADD_HEAT"
- translate-values="{'name': '{{artifact.artifactDisplayName}}'}"
- data-ng-click="addOrUpdate(artifact)"></button>
- <button class="add-button" translate="DEPLOYMENT_ARTIFACT_BUTTON_ADD_OTHER"
- data-ng-click="addOrUpdate({})"></button>
- </perfect-scrollbar>
- </div>
- </div>
- </div>
-</div>
diff --git a/catalog-ui/app/scripts/view-models/wizard/artifact-information-step/artifact-information-step.less b/catalog-ui/app/scripts/view-models/wizard/artifact-information-step/artifact-information-step.less
deleted file mode 100644
index b0600ca483..0000000000
--- a/catalog-ui/app/scripts/view-models/wizard/artifact-information-step/artifact-information-step.less
+++ /dev/null
@@ -1,50 +0,0 @@
-.artifact-step {
-
- .w-sdc-classic-btn {
- float: right;
- margin-bottom: 10px;
- }
-
- .table{
- height: 412px;
- margin-bottom: 0;
- }
-
- .table-container-flex {
- margin-top: 0px;
-
- .item-opened{
- word-wrap: break-word;
- }
-
-
- .flex-item:nth-child(1) {
- padding: 5px 4px;
- flex-grow: 15;
- .hand;
- span.table-arrow {
- margin-right: 7px;
- }
- }
-
- .flex-item:nth-child(2) {
- padding: 5px 4px;
- flex-grow: 6;
- }
-
- .flex-item:nth-child(3) {
- padding: 5px 4px;
- flex-grow: 3;
- padding-top: 10px;
- }
-
- .flex-item:nth-child(4) {
- padding: 5px 4px;
- flex-grow: 1;
- }
-
- }
-
-}
-
-
diff --git a/catalog-ui/app/scripts/view-models/wizard/artifact-information-step/artifact-information-step.ts b/catalog-ui/app/scripts/view-models/wizard/artifact-information-step/artifact-information-step.ts
deleted file mode 100644
index f6e25a53a3..0000000000
--- a/catalog-ui/app/scripts/view-models/wizard/artifact-information-step/artifact-information-step.ts
+++ /dev/null
@@ -1,168 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../../references"/>
-module Sdc.ViewModels.Wizard {
- 'use strict';
- import ArtifactModel = Sdc.Models.ArtifactModel;
-
- export interface IArtifactInformationStepScope extends IWizardCreationScope {
- artifacts: Array<Models.ArtifactModel>;
- tableHeadersList: Array<any>;
- artifactType: string;
- isResourceInstance:boolean;
- downloadFile:Models.IFileDownload;
- isLoading:boolean;
- sortBy:string;
- reverse:boolean;
- component:Models.Components.Component;
-
- getTitle(): string;
- addOrUpdate(artifact:Models.ArtifactModel): void;
- delete(artifact:Models.ArtifactModel): void;
- download(artifact:Models.ArtifactModel): void;
- clickArtifactName(artifact:any):void;
- openEditEnvParametersModal(artifactResource: Models.ArtifactModel):void;
- sort(sortBy:string): void;
- showNoArtifactMessage():boolean;
- }
-
- export class ArtifactInformationStepViewModel implements IWizardCreationStep {
-
- static '$inject' = [
- '$scope',
- '$filter',
- '$modal',
- '$templateCache',
- 'Sdc.Services.SharingService',
- '$state',
- 'sdcConfig',
- 'ModalsHandler'
- ];
-
- constructor(private $scope:IArtifactInformationStepScope,
- private $filter:ng.IFilterService,
- private $modal:ng.ui.bootstrap.IModalService,
- private $templateCache:ng.ITemplateCacheService,
- private sharingService:Sdc.Services.SharingService,
- private $state:any,
- private sdcConfig:Models.IAppConfigurtaion,
- private ModalsHandler: Utils.ModalsHandler) {
- this.$scope.registerChild(this);
- this.$scope.setValidState(true);
- this.initScope();
- }
-
-
- private getMappedObjects():any {
- return {
- normal: this.$scope.component.artifacts
- };
- }
-
- private initScope = ():void => {
- let self = this;
- this.$scope.isLoading = false;
- this.$scope.sortBy = 'artifactDisplayName';
- this.$scope.reverse = false;
-
- this.$scope.artifactType = 'normal';
- this.$scope.getTitle = ():string => {
- return this.$filter("resourceName")(this.$scope.component.name) + ' Artifacts';
-
- };
-
- this.$scope.tableHeadersList = [
- {title: 'Name', property: 'artifactDisplayName'},
- {title: 'Type', property: 'artifactType'}
- ];
-
-
- this.$scope.component = this.$scope.getComponent();
- this.$scope.artifacts = <ArtifactModel[]>_.values(this.$scope.component.artifacts);
-
-
- this.$scope.sort = (sortBy:string):void => {
- this.$scope.reverse = (this.$scope.sortBy === sortBy) ? !this.$scope.reverse : false;
- this.$scope.sortBy = sortBy;
- };
-
-
- this.$scope.addOrUpdate = (artifact:Models.ArtifactModel):void => {
- artifact.artifactGroupType = 'INFORMATIONAL';
- this.ModalsHandler.openWizardArtifactModal(artifact, this.$scope.getComponent()).then(() => {
- this.$scope.artifacts = <ArtifactModel[]>_.values(this.$scope.component.artifacts);
- });
- };
-
- this.$scope.showNoArtifactMessage = ():boolean => {
- let artifacts:any = [];
- artifacts = _.filter(this.$scope.artifacts, (artifact:Models.ArtifactModel)=> {
- return artifact.esId;
- });
-
- if (artifacts.length === 0) {
- return true;
- }
- return false;
- }
-
- this.$scope.delete = (artifact:Models.ArtifactModel):void => {
-
- let onOk = ():void => {
- this.$scope.isLoading = true;
- let onSuccess = ():void => {
- this.$scope.isLoading = false;
- this.$scope.artifacts = <ArtifactModel[]>_.values(this.$scope.component.artifacts);
- };
-
- let onFailed = (error:any):void => {
- console.log('Delete artifact returned error:', error);
- this.$scope.isLoading = false;
- };
-
- this.$scope.component.deleteArtifact(artifact.uniqueId, artifact.artifactLabel).then(onSuccess, onFailed);
- };
-
- let title:string = this.$filter('translate')("ARTIFACT_VIEW_DELETE_MODAL_TITLE");
- let message:string = this.$filter('translate')("ARTIFACT_VIEW_DELETE_MODAL_TEXT", "{'name': '" + artifact.artifactDisplayName + "'}");
- this.ModalsHandler.openConfirmationModal(title, message, false).then(onOk);
- };
-
- this.$scope.clickArtifactName = (artifact:any) => {
- if ('deployment' !== this.$scope.artifactType || 'HEAT' !== artifact.artifactType || !artifact.esId) {
- this.$scope.addOrUpdate(artifact);
- }
-
- };
-
- }
-
- public save = (callback:Function):void => {
- this.$scope.setComponent(this.$scope.component);
- callback(true);
- }
-
- public back = (callback:Function):void => {
- callback(true);
- }
-
- }
-
-}
diff --git a/catalog-ui/app/scripts/view-models/wizard/general-step/general-step.html b/catalog-ui/app/scripts/view-models/wizard/general-step/general-step.html
deleted file mode 100644
index db975caf47..0000000000
--- a/catalog-ui/app/scripts/view-models/wizard/general-step/general-step.html
+++ /dev/null
@@ -1,270 +0,0 @@
-<div include-padding="true" class="sdc-wizard-general-step">
- <div ng-controller="Sdc.ViewModels.Wizard.GeneralStepViewModel">
- <form novalidate class="w-sdc-form" name="editForm">
- <div class="w-sdc-form-section-container">
-
- <!--------------------- IMPORT TOSCA FILE -------------------->
- <file-upload id="fileUploadElement"
- ng-if="!isCreate"
- element-name="fileElement"
- element-disabled="{{!isNew}}"
- form-element="editForm"
- file-model="model.tosca"
- extensions="{{toscaFileExtensions}}"
- data-ng-class="{'error': !editForm.fileElement.$valid || !model.tosca.filename}"></file-upload>
-
- <div class="input-error-file-upload" data-ng-show="!isCreate && (!editForm.fileElement.$valid || !model.tosca.filename)">
- <!-- editForm.fileElement.$error.required <== Can not use this, because the browse is done from outside for the first time -->
- <span ng-show="!model.tosca.filename && !editForm.fileElement.$error.emptyFile" translate="NEW_SERVICE_RESOURCE_ERROR_TOSCA_FILE_REQUIRED"></span><!-- Required -->
- <span ng-show="editForm.fileElement.$error.emptyFile" translate="VALIDATION_ERROR_EMPTY_FILE"></span>
- <span ng-show="editForm.fileElement.$error.filetype" translate="NEW_SERVICE_RESOURCE_ERROR_VALID_TOSCA_EXTENSIONS" translate-values="{'extensions': '{{toscaFileExtensions}}' }"></span>
- </div>
- <!--------------------- IMPORT TOSCA FILE -------------------->
-
- <div class="w-sdc-form-columns-wrapper">
-
- <div class="w-sdc-form-column">
-
- <!--------------------- NAME -------------------->
- <div class="i-sdc-form-item" data-ng-class="{'error': validateField(editForm.componentName)}">
- <label class="i-sdc-form-label required">Name</label>
- <input class="i-sdc-form-input"
- name="componentName"
- data-ng-init="isNew && validateName(true)"
- data-ng-change="validateName()"
- data-ng-maxlength="{{component.isProduct()?'25':'50'}}"
- maxlength="{{component.isProduct()?'25':'50'}}"
- data-ng-minlength="{{component.isProduct()?'4':'0'}}"
- minlength="{{component.isProduct()?'4':'0'}}"
- data-ng-model="model.name"
- type="text"
- data-required
- data-ng-model-options="{ debounce: 500 }"
- data-ng-pattern="validation.validationPattern"
- data-ng-disabled="model.isAlreadyCertified"
- data-tests-id="name"
- autofocus
- />
-
- <div class="input-error" data-ng-show="validateField(editForm.componentName)">
- <span ng-show="editForm.componentName.$error.required" translate="NEW_SERVICE_RESOURCE_ERROR_RESOURCE_NAME_REQUIRED"></span>
- <span ng-show="editForm.componentName.$error.maxlength" translate="VALIDATION_ERROR_MAX_LENGTH" translate-values="{'max': '50' }"></span>
- <span ng-show="editForm.componentName.$error.minlength" translate="VALIDATION_ERROR_MIN_LENGTH" translate-values="{'min': '4' }"></span>
- <span ng-show="editForm.componentName.$error.nameExist" translate="NEW_SERVICE_RESOURCE_ERROR_NAME_EXISTS"></span>
- <span ng-show="editForm.componentName.$error.pattern" translate="VALIDATION_ERROR_SPECIAL_CHARS_NOT_ALLOWED"></span>
- </div>
- </div>
- <!--------------------- NAME -------------------->
-
- <!--------------------- FULL NAME -------------------->
- <div ng-if="component.isProduct()" class="i-sdc-form-item" data-ng-class="{'error': validateField(editForm.fullName)}">
- <label class="i-sdc-form-label required">Full Name</label>
- <input class="i-sdc-form-input"
- name="fullName"
- data-ng-change="validateName()"
- data-ng-maxlength="100"
- maxlength="100"
- data-ng-minlength="4"
- minlength="4"
- data-ng-model="model.fullName"
- type="text"
- data-required
- data-ng-model-options="{ debounce: 500 }"
- data-ng-pattern="validation.validationPattern"
- data-tests-id="fullName"
- autofocus
- />
-
- <div class="input-error" data-ng-show="validateField(editForm.fullName)">
- <span ng-show="editForm.fullName.$error.required" translate="NEW_SERVICE_RESOURCE_ERROR_RESOURCE_NAME_REQUIRED"></span>
- <span ng-show="editForm.fullName.$error.maxlength" translate="VALIDATION_ERROR_MAX_LENGTH" translate-values="{'max': '50' }"></span>
- <span ng-show="editForm.fullName.$error.minlength" translate="VALIDATION_ERROR_MIN_LENGTH" translate-values="{'min': '4' }"></span>
- <span ng-show="editForm.fullName.$error.nameExist" translate="NEW_SERVICE_RESOURCE_ERROR_NAME_EXISTS"></span>
- <span ng-show="editForm.fullName.$error.pattern" translate="VALIDATION_ERROR_SPECIAL_CHARS_NOT_ALLOWED"></span>
- </div>
- </div>
- <!--------------------- NAME -------------------->
-
- <!--------------------- DESCRIPTION -------------------->
- <div class="i-sdc-form-item"
- data-ng-class="{'error': validateField(editForm.description)}">
- <label class="i-sdc-form-label required">Description</label>
- <textarea class="i-sdc-form-textarea description"
- name="description"
- data-ng-maxlength="1024"
- data-required
- data-ng-model="model.description"
- data-ng-model-options="{ debounce: 500 }"
- data-ng-pattern="validation.commentValidationPattern"
- maxlength="1024"
- data-tests-id="description"></textarea>
- <!-- placeholder="Description here..." -->
-
- <div class="input-error" data-ng-show="validateField(editForm.description)">
- <span ng-show="editForm.description.$error.required" translate="NEW_SERVICE_RESOURCE_ERROR_RESOURCE_DESCRIPTION_REQUIRED"></span>
- <span ng-show="editForm.description.$error.maxlength" translate="VALIDATION_ERROR_MAX_LENGTH" translate-values="{'max': '1024' }"></span>
- <span ng-show="editForm.description.$error.pattern" translate="VALIDATION_ERROR_SPECIAL_CHARS_NOT_ALLOWED"></span>
- </div>
- </div>
- <!--------------------- DESCRIPTION -------------------->
-
- <!--------------------- CATEGORIES -------------------->
- <div class="i-sdc-form-item"
- data-ng-class="{'error': validateField(editForm.category)}"
- data-ng-if="categories && categories.length && !component.isProduct()">
- <label class="i-sdc-form-label required">Category</label>
- <select class="i-sdc-form-select"
- data-required
- name="category"
- data-ng-change="setIconToDefault()"
- data-ng-disabled="model.isAlreadyCertified"
- data-ng-model="model.category"
- data-tests-id="selectGeneralCategory"
- >
- <option value="">Select category</option>
- <optgroup ng-if="component.isResource()" data-ng-repeat="mainCategory in categories | orderBy:['name']" label="{{mainCategory.name}}" data-tests-id="{{mainCategory.name}}">
- <option data-ng-repeat="subCategory in mainCategory.subcategories track by $index"
- data-ng-selected="model.category===calculateUnique(mainCategory.name,subCategory.name)"
- data-tests-id="{{subCategory.name}}"
- value="{{calculateUnique(mainCategory.name,subCategory.name)}}">{{subCategory.name}}
-
- </option>
- </optgroup>
- <option ng-if="component.isService()" data-ng-repeat="mainCategory in categories | orderBy:['name']"
- data-ng-selected="model.category===mainCategory.name"
- value="{{mainCategory.name}}"
- data-tests-id="{{mainCategory.name}}">{{mainCategory.name}}</option>
- </select>
-
- <div class="input-error" data-ng-show="validateField(editForm.category)">
- <span ng-show="editForm.category.$error.required" translate="NEW_SERVICE_RESOURCE_ERROR_CATEGORY_REQUIRED"></span>
- </div>
- </div>
- <!--------------------- CATEGORIES -------------------->
-
- <!--------------------- VENDOR NAME -------------------->
- <div ng-if="component.isResource()" class="i-sdc-form-item" data-ng-class="{'error': validateField(editForm.vendorName)}">
- <label class="i-sdc-form-label required">Vendor</label>
- <input class="i-sdc-form-input" type="text"
- data-ng-model="model.vendorName"
- data-ng-model-options="{ debounce: 500 }"
- data-ng-maxlength="25"
- data-required
- ng-click="oldValue = model.vendorName"
- name="vendorName"
- data-ng-change="onVendorNameChange(oldValue)"
- data-ng-pattern="validation.vendorValidationPattern"
- maxlength="25"
- data-ng-disabled="model.isAlreadyCertified"
- data-tests-id="vendorName"
- />
-
- <div class="input-error" data-ng-show="validateField(editForm.vendorName)">
- <span ng-show="editForm.vendorName.$error.required" translate="NEW_SERVICE_RESOURCE_ERROR_VENDOR_NAME_REQUIRED"></span>
- <span ng-show="editForm.vendorName.$error.maxlength" translate="VALIDATION_ERROR_MAX_LENGTH" translate-values="{'max': '25' }"></span>
- <span ng-show="editForm.vendorName.$error.pattern" translate="VALIDATION_ERROR_SPECIAL_CHARS_NOT_ALLOWED"></span>
- </div>
-
- </div>
-
- <!--------------------- VENDOR NAME -------------------->
-
- <!--------------------- VENDOR RELEASE -------------------->
- <div ng-if="component.isResource()"
- class="i-sdc-form-item"
- data-ng-class="{'error': validateField(editForm.vendorRelease)}">
- <label class="i-sdc-form-label required">Vendor Release</label>
- <input class="i-sdc-form-input" type="text"
- data-ng-model="model.vendorRelease"
- data-ng-model-options="{ debounce: 500 }"
- data-ng-maxlength="25"
- data-required
- name="vendorRelease"
- data-ng-pattern="validation.vendorValidationPattern"
- maxlength="25"
- data-tests-id="vendorRelease"
- />
-
- <div class="input-error" data-ng-show="validateField(editForm.vendorRelease)">
- <span ng-show="editForm.vendorRelease.$error.required" translate="NEW_SERVICE_RESOURCE_ERROR_VENDOR_RELEASE_REQUIRED"></span>
- <span ng-show="editForm.vendorRelease.$error.maxlength" translate="VALIDATION_ERROR_MAX_LENGTH" translate-values="{'max': '128' }"></span>
- <span ng-show="editForm.vendorRelease.$error.pattern" translate="VALIDATION_ERROR_SPECIAL_CHARS_NOT_ALLOWED"></span>
- </div>
- </div>
- <!--------------------- VENDOR RELEASE -------------------->
-
-
-
- </div><!-- Close w-sdc-form-column -->
-
- <div class="w-sdc-form-column">
-
- <!--------------------- RESOURCE TAGS -------------------->
- <div class="i-sdc-form-item" data-ng-class="{'error': validateField(editForm.tags)}">
- <label class="i-sdc-form-label">Tags</label>
-
- <sdc-tags form-element="editForm" element-name="tags" max-tags="20" class="i-sdc-form-item-tags" tags="model.tags" pattern="validation.tagValidationPattern" special-tag="model.name"></sdc-tags>
-
- <div class="input-error" data-ng-show="validateField(editForm.tags)">
- <span ng-show="editForm.tags.$error.pattern" translate="VALIDATION_ERROR_SPECIAL_CHARS_NOT_ALLOWED"></span>
- </div>
- </div>
- <!--------------------- RESOURCE TAGS -------------------->
-
- <!--------------------- CONTACT ID -------------------->
- <div class="i-sdc-form-item" data-ng-class="{'error': validateField(editForm.contactId)}">
- <label class="i-sdc-form-label required" translate="GENERAL_LABEL_CONTACT_ID"></label>
- <input class="i-sdc-form-input disabled" type="text"
- data-ng-model="model.userId"
- data-required
- name="contactId"
- data-ng-pattern="validation.contactIdValidationPattern"
- data-ng-model-options="{ debounce: 500 }"
- data-tests-id="userId"
- maxlength="50"
- />
-
- <div class="input-error" data-ng-show="validateField(editForm.contactId)">
- <span ng-show="editForm.contactId.$error.required" translate="NEW_SERVICE_RESOURCE_ERROR_CONTACT_REQUIRED"></span>
- <span ng-show="editForm.contactId.$error.pattern" translate="NEW_SERVICE_RESOURCE_ERROR_CONTACT_NOT_VALID"></span>
- </div>
- </div>
- <!--------------------- CONTACT ID -------------------->
-
- <!--------------------- PROJECT CODE -------------------->
- <div class="i-sdc-form-item" data-ng-if="!component.isResource()"
- data-ng-class="{'error': validateField(editForm.projectCode)}">
- <label class="i-sdc-form-label required" translate="GENERAL_LABEL_PROJECT_CODE"></label>
- <input class="i-sdc-form-input" type="text"
- data-ng-model="model.projectCode"
- data-ng-model-options="{ debounce: 500 }"
- data-ng-maxlength="128"
- data-required
- name="projectCode"
- data-ng-pattern="validation.projectCodeValidationPattern"
- maxlength="50"
- data-tests-id="projectCode"
- />
-
- <div class="input-error" data-ng-show="validateField(editForm.projectCode)">
- <span ng-show="editForm.projectCode.$error.required" translate="NEW_SERVICE_RESOURCE_ERROR_PROJECT_CODE_REQUIRED"></span>
- <span ng-show="editForm.projectCode.$error.pattern" translate="NEW_SERVICE_RESOURCE_ERROR_PROJECT_CODE_NOT_VALID"></span>
- </div>
- </div>
- <!--------------------- VENDOR RELEASE -------------------->
-
-
- </div><!-- Close w-sdc-form-column -->
-
- </div><!-- Close w-sdc-form-column -->
-
- <div class="w-sdc-form-messages-wrapper">
- <span class="w-sdc-form-messages-msg" data-ng-show="isSaved"><span class="w-sdc-form-messages-msg-v"></span>Your resource has been saved</span>
- </div>
-
- </div><!-- Close w-sdc-form-section-container -->
-
- </form>
-
- </div>
-</div>
diff --git a/catalog-ui/app/scripts/view-models/wizard/general-step/general-step.less b/catalog-ui/app/scripts/view-models/wizard/general-step/general-step.less
deleted file mode 100644
index 700997a423..0000000000
--- a/catalog-ui/app/scripts/view-models/wizard/general-step/general-step.less
+++ /dev/null
@@ -1,34 +0,0 @@
-.sdc-wizard-general-step {
-
- .w-sdc-form {
- padding: 0;
-
- .w-sdc-form-section-container {
- text-align: center;
- }
-
- .i-sdc-form-item {
- &.upload {
- margin-top: 0;
- width: auto;
- padding: 10px;
- }
- }
-
- .template-desc {
- border: 1px dashed @border_color_f;
- height: 130px;
- overflow: hidden;
- padding: 10px 6px 6px 6px;
- margin-top: 10px;
- }
-
- .sdc-tag .tag {
- max-width: 225px;
- }
-
- }
-
-}
-
-
diff --git a/catalog-ui/app/scripts/view-models/wizard/general-step/general-step.ts b/catalog-ui/app/scripts/view-models/wizard/general-step/general-step.ts
deleted file mode 100644
index 74c681e433..0000000000
--- a/catalog-ui/app/scripts/view-models/wizard/general-step/general-step.ts
+++ /dev/null
@@ -1,381 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../../references"/>
-module Sdc.ViewModels.Wizard {
- import ISubCategory = Sdc.Models.ISubCategory;
- import IMainCategory = Sdc.Models.IMainCategory;
- 'use strict';
-
- /*
- * TODO: The template (derived from is not necessary here).
- * Need to delete it from all remarks.
- * */
-
- export class UIModel {
- tosca:Sdc.Directives.FileUploadModel;
- name:string;
- description:string;
- vendorName:string;
- vendorRelease:string;
- category:string;
- tags:Array<string>;
- userId:string;
- icon:string;
- projectCode:string;
- fullName:string;
- isAlreadyCertified:boolean;
- }
-
- export class Validation {
- validationPattern: RegExp;
- contactIdValidationPattern: RegExp;
- tagValidationPattern: RegExp;
- vendorValidationPattern: RegExp;
- commentValidationPattern: RegExp;
- projectCodeValidationPattern: RegExp;
- }
-
- export interface IGeneralStepScope extends IWizardCreationStepScope {
- model:UIModel;
- validation:Validation;
- editForm:ng.IFormController;
- component: Models.Components.Component;
- categories: Array<IMainCategory>;
- latestComponentName:string;
- latestCategoryId: string;
- latestVendorName: string;
- isNew:boolean;
- toscaFileExtensions:any;
- isCreate:boolean;
-
- onToscaFileChange():void
- validateField(field:any):boolean;
- validateName(isInit:boolean): void;
- calculateUnique(mainCategory:string, subCategory:string):string; // Build unique string from main and sub category
- calculatedTagsMaxLength():number;
- setIconToDefault():void;
- onVendorNameChange(oldVendorName: string): void;
- }
-
- export class GeneralStepViewModel implements IWizardCreationStep {
-
- static '$inject' = [
- '$scope',
- 'Sdc.Services.CacheService',
- 'ValidationPattern',
- 'ContactIdValidationPattern',
- 'TagValidationPattern',
- 'VendorValidationPattern',
- 'CommentValidationPattern',
- 'ValidationUtils',
- 'sdcConfig',
- 'ComponentFactory',
- 'ProjectCodeValidationPattern'
- ];
-
- constructor(private $scope:IGeneralStepScope,
- private cacheService:Services.CacheService,
- private ValidationPattern:RegExp,
- private ContactIdValidationPattern:RegExp,
- private TagValidationPattern:RegExp,
- private VendorValidationPattern:RegExp,
- private CommentValidationPattern: RegExp,
- private ValidationUtils: Sdc.Utils.ValidationUtils,
- private sdcConfig:Models.IAppConfigurtaion,
- private ComponentFactory: Sdc.Utils.ComponentFactory,
- private ProjectCodeValidationPattern:RegExp
- ) {
-
- this.$scope.registerChild(this);
- this.initScopeValidation();
- this.initScopeMethods();
- this.initScope();
- this.$scope.isCreate = this.$scope.data.importFile === undefined;
- }
-
- private initScopeValidation = (): void => {
- this.$scope.validation = new Validation();
- this.$scope.validation.validationPattern = this.ValidationPattern;
- this.$scope.validation.contactIdValidationPattern = this.ContactIdValidationPattern;
- this.$scope.validation.tagValidationPattern = this.TagValidationPattern;
- this.$scope.validation.vendorValidationPattern = this.VendorValidationPattern;
- this.$scope.validation.commentValidationPattern = this.CommentValidationPattern;
- this.$scope.validation.projectCodeValidationPattern = this.ProjectCodeValidationPattern;
- };
-
- private initScope = ():void => {
-
- // Init UIModel
- this.$scope.model = new UIModel();
-
- // Init categories
- if(this.$scope.data.componentType === Utils.Constants.ComponentType.RESOURCE){
- this.$scope.categories = this.cacheService.get('resourceCategories');
- }
- if (this.$scope.data.componentType === Utils.Constants.ComponentType.SERVICE) {
- this.$scope.categories = this.cacheService.get('serviceCategories');
- }
-
- this.$scope.model.category='';
-
- //init file extenstions
- this.$scope.toscaFileExtensions = this.sdcConfig.toscaFileExtension;
-
- // Init Tosca import file
- if (this.$scope.data.importFile) {
- this.$scope.model.tosca = this.$scope.data.importFile;
- }
-
- // Case insert or update
- this.$scope.component = this.$scope.getComponent();
- if ( this.$scope.component!==undefined){
- // Update mode
-
- //this.$scope.latestCategoryId = this.$scope.component[0].uniqueId;
- //this.$scope.latestVendorName = this.$scope.component.vendorName;
- this.$scope.latestComponentName = this.$scope.component.name;
- this.$scope.isNew=false;
- this.resource2ModelUi(this.$scope.component);
- } else {
- // Create mode
- this.$scope.isNew=true;
- this.$scope.model.tags=[]; // Init tags
- this.$scope.model.userId = this.cacheService.get("user").userId; // Fill user ID from logged in user
- this.$scope.model.icon = Utils.Constants.DEFAULT_ICON; // Set the default icon
- this.$scope.component = this.ComponentFactory.createEmptyComponent(this.$scope.data.componentType);
- }
- };
-
- private initScopeMethods = ():void => {
-
- this.$scope.validateField = (field:any):boolean => {
- if (field && field.$dirty && field.$invalid){
- return true;
- }
- return false;
- };
-
- this.$scope.validateName = (isInit:boolean):void => {
- if (isInit===undefined){isInit=false;}
-
- let name = this.$scope.model.name;
- if (!name || name===""){
- if (this.$scope.editForm
- && this.$scope.editForm["componentName"]
- && this.$scope.editForm["componentName"].$error){
-
- // Clear the error name already exists
- this.$scope.editForm["componentName"].$setValidity('nameExist', true);
- }
-
- return;
- }
- let subtype:string = Utils.Constants.ComponentType.RESOURCE == this.$scope.data.componentType?
- this.$scope.data.importFile? 'VFC':'VF' : undefined;
-
- let onFailed = (response) => {
- //console.info('onFaild', response);
- //this.$scope.isLoading = false;
- };
-
- let onSuccess = (validation:Models.IValidate) => {
- this.$scope.editForm["componentName"].$setValidity('nameExist', validation.isValid);
- };
-
- if (isInit){
- // When page is init after update
- if (this.$scope.model.name !== this.$scope.latestComponentName){
- if(!this.$scope.component.isProduct()) {//TODO remove when backend is ready
- this.$scope.component.validateName(name, subtype).then(onSuccess, onFailed);
- }
- }
- } else {
- // Validating on change (has debounce)
- if (this.$scope.editForm
- && this.$scope.editForm["componentName"]
- && this.$scope.editForm["componentName"].$error
- && !this.$scope.editForm["componentName"].$error.pattern
- && this.$scope.model.name !== this.$scope.latestComponentName
- ) {
- if(!this.$scope.component.isProduct()) { //TODO remove when backend is ready
- this.$scope.component.validateName(name, subtype).then(onSuccess, onFailed);
- }
- } else if (this.$scope.model.name === this.$scope.latestComponentName) {
- // Clear the error
- this.$scope.editForm["componentName"].$setValidity('nameExist', true);
- }
- }
- };
-
- this.$scope.calculateUnique = (mainCategory:string, subCategory:string):string => {
- let uniqueId: string = mainCategory;
- if(subCategory) {
- uniqueId += "_#_" + subCategory; // Set the select category combobox to show the selected category.
- }
- return uniqueId;
- };
-
- // Notify the parent if this step valid or not.
- this.$scope.$watch("editForm.$valid", (newVal, oldVal) => {
- //console.log("editForm validation: " + newVal);
- this.$scope.setValidState(newVal);
- });
-
- this.$scope.setIconToDefault = ():void => {
- this.$scope.model.icon = Utils.Constants.DEFAULT_ICON;
- };
-
- this.$scope.onVendorNameChange = (oldVendorName: string):void => {
- if(this.$scope.component.icon === oldVendorName) {
- this.$scope.setIconToDefault();
- }
- };
- };
-
- public save = (callback:Function):void => {
- this.modelUi2Resource();
-
- let onFailed = (response) => {
- callback(false);
- };
-
- let onSuccess = (component:Models.Components.Component) => {
- this.$scope.component = component;
- this.$scope.setComponent(this.$scope.component);
- this.$scope.latestComponentName = (component.name);
- callback(true);
- };
-
- try {
- //Send the form with attached tosca file.
- if (this.$scope.isNew===true) {
- this.ComponentFactory.createComponentOnServer(this.$scope.component).then(onSuccess, onFailed);
- } else {
- this.$scope.component.updateComponent().then(onSuccess, onFailed);
- }
- }catch(e){
- //console.log("ERROR: Error in updating/creating component: " + e);
- callback(false);
- }
-
- };
-
- public back = (callback:Function):void => {
- callback(true);
- }
-
- // Fill the resource properties object with data from UIModel
- private modelUi2Resource = ():void => {
-
- this.$scope.component.name = this.$scope.model.name;
- this.$scope.component.description = this.ValidationUtils.stripAndSanitize(this.$scope.model.description);
- this.$scope.component.vendorName = this.$scope.model.vendorName;
- this.$scope.component.vendorRelease = this.$scope.model.vendorRelease;
- this.$scope.component.tags = angular.copy(this.$scope.model.tags);
- this.$scope.component.tags.push(this.$scope.model.name);
- this.$scope.component.contactId = this.$scope.model.userId;
- this.$scope.component.icon = this.$scope.model.icon;
-
- if(this.$scope.component.isResource()) {
- (<Models.Components.Resource>this.$scope.component).resourceType = "VF";
-
- // Handle the tosca file
- if (this.$scope.model.tosca && this.$scope.isNew) {
- (<Models.Components.Resource>this.$scope.component).payloadData = this.$scope.model.tosca.base64;
- (<Models.Components.Resource>this.$scope.component).payloadName = this.$scope.model.tosca.filename;
- }
-
- this.$scope.component.categories = this.convertCategoryStringToOneArray();
- }
-
- if(this.$scope.component.isProduct()) {
- this.$scope.component.projectCode = this.$scope.model.projectCode;
- // Handle the tosca file
- this.$scope.component.categories = undefined;
- (<Models.Components.Product>this.$scope.component).contacts = new Array<string>();
- (<Models.Components.Product>this.$scope.component).contacts.push(this.$scope.component.contactId);
- (<Models.Components.Product>this.$scope.component).fullName = this.$scope.model.fullName;
- }
-
- if(this.$scope.component.isService()) {
- this.$scope.component.projectCode = this.$scope.model.projectCode;
- this.$scope.component.categories = this.convertCategoryStringToOneArray();
- }
- };
-
- // Fill the UIModel from data from resource properties
- private resource2ModelUi = (component: Models.Components.Component):void => {
- this.$scope.model.name = component.name;
- this.$scope.model.description = component.description;
- this.$scope.model.vendorName = component.vendorName;
- this.$scope.model.vendorRelease = component.vendorRelease;
- this.$scope.model.tags = _.reject(component.tags, (item)=>{return item===component.name});
- this.$scope.model.userId = component.contactId;
- this.$scope.model.icon = component.icon;
- this.$scope.model.projectCode = component.projectCode;
- this.$scope.model.isAlreadyCertified = component.isAlreadyCertified();
-
- if(!this.$scope.component.isProduct()) {
- this.$scope.model.category = this.convertCategoryOneArrayToString(component.categories);
- }
-
- if(component.isProduct()) {
- this.$scope.model.fullName = (<Models.Components.Product>component).fullName;
-
- }
-
- };
-
- // Convert category string MainCategory_#_SubCategory to Array with one item (like the server except)
- private convertCategoryStringToOneArray = ():Array<Models.IMainCategory> => {
- let tmp = this.$scope.model.category.split("_#_");
- let mainCategory = tmp[0];
- let subCategory = tmp[1];
-
- // Find the selected category and add the relevant sub category.
- let selectedMainCategory:IMainCategory = <Models.IMainCategory>_.find(this.$scope.categories, function (item) {
- return item["name"] === mainCategory
- });
- let mainCategoryClone = jQuery.extend(true, {}, selectedMainCategory);
- if(subCategory) {
- mainCategoryClone['subcategories'] = [{
- "name": subCategory
- }];
- }
- let tmpSelected = <Models.IMainCategory> mainCategoryClone;
-
- let result:Array<Models.IMainCategory> = [];
- result.push(tmpSelected);
-
- return result;
- };
-
- private convertCategoryOneArrayToString = (categories:Array<Models.IMainCategory>):string => {
- let mainCategory:string = categories[0].name;
- let subCategory:string = '';
- if(categories[0].subcategories) {
- subCategory = categories[0].subcategories[0].name;
- }
- return this.$scope.calculateUnique(mainCategory, subCategory);
- };
-
- }
-
-}
diff --git a/catalog-ui/app/scripts/view-models/wizard/hierarchy-step/hierarchy-step.html b/catalog-ui/app/scripts/view-models/wizard/hierarchy-step/hierarchy-step.html
deleted file mode 100644
index 7fc3e9224f..0000000000
--- a/catalog-ui/app/scripts/view-models/wizard/hierarchy-step/hierarchy-step.html
+++ /dev/null
@@ -1,40 +0,0 @@
-<div class="hierarchy-step" data-ng-controller="Sdc.ViewModels.Wizard.HierarchyStepViewModel">
- <div class="dropdown-container" clicked-outside="{onClickedOutside: 'clickOutside()', clickedOutsideEnable: 'true'}" >
- <input placeholder="Add Group" data-ng-click="onInputTextClicked()" class="dropdown-input-text" data-ng-model="search.filterTerms" data-ng-model-options="{debounce: 200}"/>
- <div data-ng-class="{'show': showDropDown}" class="dropdown-content" >
- <perfect-scrollbar scroll-y-margin-offset="0" include-padding="false" class="scrollbar-container">
- <div ng-repeat="category in categoriesOptions track by $index">
- <div ng-repeat="subcategory in category.subcategories track by $index">
- <div class="dropdown-option" ng-show="!category.filteredGroup || category.filteredGroup.length > 0">
- <div class="category-container">
- <div class="category">{{category.name}}</div>
- <div class="subcategory">{{subcategory.name}}</div>
- </div>
- <div class="groupings-container">
- <div ng-init="group.filterTerms = group.name + ' ' + category.name + ' ' + subcategory.name"
- ng-repeat="group in (category.filteredGroup = (subcategory.groupings | filter:search )) track by $index">
- <div class="group" data-ng-disabled="group.isDisabled" data-ng-class="{'disabled-group': group.isDisabled}" ng-click="onGroupSelected(category, subcategory, group)">
- <span >{{group.name}}</span>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- </perfect-scrollbar>
- </div>
- </div>
- <div class="hierarchy-groups-container">
- <perfect-scrollbar scroll-y-margin-offset="0" include-padding="true" class="scrollbar-container">
- <div ng-if="!product.categories.length || product.categories.length === 0" class="no-groups-text" translate="NEW_PRODUCT_NO_CATEGORIES_TO_DISPLAY"></div>
- <div ng-repeat="category in product.categories track by $index">
- <div ng-repeat="subcategory in category.subcategories track by $index">
- <div class="group-tag" ng-repeat="group in subcategory.groupings track by $index"
- data-ng-init="tooltip = '<b>' + category.name + '</b><br />' + subcategory.name">
- <sdc-tag data-on-delete="deleteGroup(uniqueId)" data-tag-data="{tag: group.name, tooltip: tooltip, id: group.uniqueId }"></sdc-tag>
- </div>
- </div>
- </div>
- </perfect-scrollbar>
- </div>
-</div>
diff --git a/catalog-ui/app/scripts/view-models/wizard/hierarchy-step/hierarchy-step.less b/catalog-ui/app/scripts/view-models/wizard/hierarchy-step/hierarchy-step.less
deleted file mode 100644
index 74786c127a..0000000000
--- a/catalog-ui/app/scripts/view-models/wizard/hierarchy-step/hierarchy-step.less
+++ /dev/null
@@ -1,125 +0,0 @@
-.hierarchy-step {
- margin-top: 35px;
-
- .scrollbar-container{
- max-height:400px;
- .perfect-scrollbar;
- }
-
- .dropdown-container {
- position: relative;
- display: inline-block;
- width: 100%;
-
- &:after{
- top: 47%;
- right: 1%;
- border: solid transparent;
- content: " ";
- height: 0;
- width: 0;
- position: absolute;
- pointer-events: none;
- border-color: rgba(0, 0, 0, 0);
- border-top-color: black;
- border-width: 4px;
- margin-left: -4px;
- }
-
- .dropdown-input-text {
- width: 100%;
- padding: 4px 10px;
- }
-
- .dropdown-content {
- .perfect-scrollbar;
- border: 1px solid #d8d8d8;
- display: none;
- position: absolute;
- overflow: hidden;
- width: 100%;
- .bg_c;
- max-height: 400px;
- z-index: 999999;
-
- .dropdown-option {
- border-bottom: 1px solid #d8d8d8;
- display: inline-block;
- width: 100%;
- }
-
- .category-container{
- width: 250px;
- float: left;
- padding-left: 5px;
-
- .category {
- .bold;
- padding: 3px 3px 2px 3px;
- &:after{
- .sprite;
- .arrow-left;
- content: '';
- margin-left: 5px;
- transform: rotate(180deg);
- }
- }
- .subcategory {
- padding-left: 3px;
- }
- }
-
- .groupings-container{
- display: inline-block;
- width: 424px;
- border-left: 1px solid #d8d8d8;
- min-height: 55px;
- .group{
- padding: 3px 3px 3px 10px;
- &:hover{
- .hand;
- .bg_n;
- }
- &.disabled-group {
- opacity: 0.5;
- &:hover{
- cursor: auto;
- .bg_c;
- }
- }
- }
- }
-
- .seperator {
- height: 1px;
- width: 100%;
- .bg_j;
- margin: 5px 0px;
- }
- }
- .show {
- display: block;
- }
- }
-
- .hierarchy-groups-container{
- .b_9;
- width: 100%;
- border: 1px solid #d8d8d8;
- height: 425px;
- padding: 15px;
- text-align: center;
-
- .no-group-text{
- text-align: center;
- margin-top:25px;
- a {
- cursor: pointer;
- }
- }
- .group-tag{
- display: inline-block;
- float: left;
- }
- }
-}
diff --git a/catalog-ui/app/scripts/view-models/wizard/hierarchy-step/hierarchy-step.ts b/catalog-ui/app/scripts/view-models/wizard/hierarchy-step/hierarchy-step.ts
deleted file mode 100644
index a974c0af81..0000000000
--- a/catalog-ui/app/scripts/view-models/wizard/hierarchy-step/hierarchy-step.ts
+++ /dev/null
@@ -1,149 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../../references"/>
-module Sdc.ViewModels.Wizard {
- 'use strict';
-
- export interface IHierarchyStepScope extends IWizardCreationScope {
-
- categoriesOptions: Array<Models.IMainCategory>;
- product:Models.Components.Product;
- isLoading:boolean;
- showDropDown:boolean;
-
- onInputTextClicked():void;
- onGroupSelected(category: Models.IMainCategory, subcategory: Models.ISubCategory, group: Models.IGroup):void;
- clickOutside():void;
- deleteGroup(uniqueId:string):void;
- }
-
- export class HierarchyStepViewModel implements IWizardCreationStep {
-
- static '$inject' = [
- '$scope',
- 'Sdc.Services.CacheService',
- 'ComponentFactory'
- ];
-
- constructor(private $scope:IHierarchyStepScope,
- private cacheService:Sdc.Services.CacheService,
- private ComponentFactory: Sdc.Utils.ComponentFactory) {
-
- this.$scope.registerChild(this);
- this.$scope.setValidState(true);
- this.$scope.product = <Models.Components.Product>this.$scope.getComponent();
- this.initScope();
- }
-
- private initCategories = () => {
- this.$scope.categoriesOptions = angular.copy(this.cacheService.get('productCategories'));
- let selectedGroup:Array<Models.IGroup> = [];
- _.forEach(this.$scope.product.categories, (category: Models.IMainCategory) => {
- _.forEach(category.subcategories, (subcategory:Models.ISubCategory) => {
- selectedGroup = selectedGroup.concat(subcategory.groupings);
- });
- });
- _.forEach(this.$scope.categoriesOptions, (category: Models.IMainCategory) => {
- _.forEach(category.subcategories, (subcategory:Models.ISubCategory) => {
- _.forEach(subcategory.groupings, (group:Models.ISubCategory) => {
- let componentGroup:Models.IGroup = _.find(selectedGroup, (componentGroupObj) => {
- return componentGroupObj.uniqueId == group.uniqueId;
- });
- if(componentGroup){
- group.isDisabled = true;
- }
- });
- });
- });
- };
-
- private setFormValidation = ():void => {
- if(!this.$scope.product.categories || this.$scope.product.categories.length === 0){
- this.$scope.setValidState(false);
- }
- else{
- this.$scope.setValidState(true);
- }
-
- };
-
- private initScope = ():void => {
- this.$scope.isLoading= false;
- this.$scope.showDropDown =false;
- this.initCategories();
- this.setFormValidation();
-
- this.$scope.onGroupSelected = (category: Models.IMainCategory, subcategory: Models.ISubCategory, group: Models.IGroup):void => {
- this.$scope.showDropDown = false;
- this.$scope.product.addGroup(category, subcategory, group);
- group.isDisabled = true;
- this.setFormValidation();
- };
-
- this.$scope.onInputTextClicked = ():void => {//just edit the component in place, no pop up nor server update ?
- this.$scope.showDropDown = !this.$scope.showDropDown;
- };
-
- this.$scope.clickOutside = (): any => {
- this.$scope.showDropDown = false;
- };
-
- this.$scope.deleteGroup = (uniqueId:string) : void => {
- //delete group from component
- this.$scope.product.deleteGroup(uniqueId);
- this.setFormValidation();
- //enabled group
- _.forEach(this.$scope.categoriesOptions, (category: Models.IMainCategory) => {
- _.forEach(category.subcategories, (subcategory:Models.ISubCategory) => {
- let groupObj:Models.IGroup = _.find (subcategory.groupings, (group) => {
- return group.uniqueId === uniqueId;
- });
- if(groupObj){
- groupObj.isDisabled = false;
- }
- });
- });
- }
- };
-
- public save = (callback:Function):void => {
- let onFailed = (response) => {
- callback(false);
- };
-
- let onSuccess = (component: Models.Components.Component) => {
- this.$scope.product = <Models.Components.Product> this.ComponentFactory.createComponent(component);
- this.$scope.setComponent(this.$scope.product);
- callback(true);
- };
-
- try {
- this.$scope.product.updateComponent().then(onSuccess, onFailed);
- }catch(e){
- //console.log("ERROR: Error in updating/creating component: " + e);
- callback(false);
- }
- };
-
- public back = (callback:Function):void => {
- this.save(callback);
- }
- }
-}
diff --git a/catalog-ui/app/scripts/view-models/wizard/icons-step/icons-step.html b/catalog-ui/app/scripts/view-models/wizard/icons-step/icons-step.html
deleted file mode 100644
index 2ae386283c..0000000000
--- a/catalog-ui/app/scripts/view-models/wizard/icons-step/icons-step.html
+++ /dev/null
@@ -1,26 +0,0 @@
-<div class="icons-step" data-ng-controller="Sdc.ViewModels.Wizard.IconsStepViewModel">
-
- <form novalidate class="w-sdc-form" name="iconForm">
- <label class="i-sdc-form-label icons-label required">Icons</label>
- <div class="selected-icon-container">
- <div class="i-sdc-form-item-suggested-icon medium selected-icon {{iconSprite}} {{component.icon}}"
- ng-model="component.icon"
- tooltips tooltip-content='{{component.icon | translate}}'
- >
- </div>
- </div>
-
- <label class="i-sdc-form-label icons-label required">Select one of the icons below for the asset</label>
- <div class="i-sdc-form-item suggested-icons-container">
- <div class ="suggested-icon-wrapper" ng-class="component.icon==='{{iconSrc}}' ? 'selected' : '' " data-ng-repeat="iconSrc in icons track by $index">
- <div class="i-sdc-form-item-suggested-icon medium {{iconSprite}} {{iconSrc}}" data-ng-class="component.isAlreadyCertified()? 'disable':'hand'"
- ng-model="component.icon"
- data-tests-id="{{iconSrc}} iconBox"
- data-ng-click="!component.isAlreadyCertified() && setComponentIcon(iconSrc)"
- tooltips tooltip-content='{{iconSrc | translate}}'
- >
- </div>
- </div>
- </div>
- </form>
-</div>
diff --git a/catalog-ui/app/scripts/view-models/wizard/icons-step/icons-step.less b/catalog-ui/app/scripts/view-models/wizard/icons-step/icons-step.less
deleted file mode 100644
index c03c949962..0000000000
--- a/catalog-ui/app/scripts/view-models/wizard/icons-step/icons-step.less
+++ /dev/null
@@ -1,55 +0,0 @@
-.icons-step {
-
- .w-sdc-form {
- padding-top: 0px;
- padding-bottom: 0px;
- .selected-icon-container {
- text-align: left;
- border: 1px solid #cfcfcf;
- clear: both;
- margin-bottom: 15px;
- padding-left: 3px;
- padding-bottom: 3px;
- .selected-icon {
- margin: 8px 5px 0px 6px;
- }
- }
-
- .suggested-icons-container {
- text-align: left;
- border: 1px solid #cfcfcf;
- clear: both;
- padding-left: 3px;
- height: 340px;
- margin-bottom: 0px;
-
- .suggested-icon-wrapper {
- margin: 8px 5px 0px 6px;
- display: inline-block;
-
- &.selected {
- border: 1px solid @color_p;
- border-radius: 25px;
- box-shadow: 0 0 2px #888;
- display: inline-block;
- line-height: 0px;
- padding: 2px;
- }
-
- }
- .suggested-icon {
- // margin: 8px 5px 0px 6px;
- display: inline-block;
- &.disable{
- opacity: 0.4;
- }
- }
-
-
- }
-
- .icons-label {
- float: left;
- }
- }
-}
diff --git a/catalog-ui/app/scripts/view-models/wizard/icons-step/icons-step.ts b/catalog-ui/app/scripts/view-models/wizard/icons-step/icons-step.ts
deleted file mode 100644
index 4dc5e377fa..0000000000
--- a/catalog-ui/app/scripts/view-models/wizard/icons-step/icons-step.ts
+++ /dev/null
@@ -1,150 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../../references"/>
-module Sdc.ViewModels.Wizard {
- 'use strict';
-
- export interface IIconsStepScope extends IWizardCreationStepScope{
- icons : Array<string>;
- component: Models.Components.Component;
- iconSprite: string;
- setComponentIcon(iconSrc:string): void;
- }
-
- export class IconsStepViewModel implements IWizardCreationStep {
-
- static '$inject' = [
- '$scope',
- 'Sdc.Services.AvailableIconsService',
- 'ComponentFactory'
- ];
-
- constructor(private $scope:IIconsStepScope,
- private availableIconsService:Services.AvailableIconsService,
- private ComponentFactory: Sdc.Utils.ComponentFactory) {
-
- this.$scope.registerChild(this);
- this.$scope.component = this.$scope.getComponent();
- this.$scope.iconSprite = this.$scope.component.iconSprite;
- this.initScope();
- this.initIcons();
-
- if(this.$scope.component.isResource()) {
- this.initVendor();
- }
- // In case there is one icons select it.
- if( this.$scope.icons.length == 1 && !this.$scope.component.isAlreadyCertified()){
- this.$scope.setComponentIcon(this.$scope.icons[0]);
- }
- }
-
- private initIcons = ():void => {
-
- // For subcategories that where created by admin, there is no icons
- this.$scope.icons = new Array<string>();
- if (this.$scope.component.categories && this.$scope.component.categories.length > 0) {
-
- _.forEach(this.$scope.component.categories, (category:Models.IMainCategory):void => {
- if (category.icons) {
- this.$scope.icons = this.$scope.icons.concat(category.icons);
- }
- if (category.subcategories) {
- _.forEach(category.subcategories, (subcategory:Models.ISubCategory):void => {
- if (subcategory.icons) {
- this.$scope.icons = this.$scope.icons.concat(subcategory.icons);
- }
- });
- }
- });
- }
-
- if (this.$scope.component.isResource()) {
- let resourceType:string = this.$scope.component.getComponentSubType();
- if (resourceType === 'VL') {
- this.$scope.icons = ['vl'];
- }
- if (resourceType === 'CP') {
- this.$scope.icons = ['cp'];
- }
- }
-
- if (this.$scope.icons.length === 0) {
- this.$scope.icons = this.availableIconsService.getIcons(this.$scope.component.componentType);
- }
-
- };
-
- private initVendor = ():void => {
- let vendors:Array<string> = this.availableIconsService.getIcons(this.$scope.component.componentType).slice(5, 19);
- let vendorName = this.$scope.component.vendorName.toLowerCase();
- if ('at&t' === vendorName){
- vendorName = 'att';
- }
- if ('nokia' === vendorName){
- vendorName = 'nokiasiemens';
- }
-
- let vendor:string = _.find(vendors, (vendor:string)=>{
- return vendor.replace(/[_]/g, '').toLowerCase() === vendorName;
- });
-
- if(vendor && this.$scope.icons.indexOf(vendor)===-1) {
- this.$scope.icons.push(vendor);
- }
- };
-
- private initScope():void {
- this.$scope.icons = [];
-
- if(this.$scope.component.icon === Utils.Constants.DEFAULT_ICON){
- this.$scope.setValidState(false);
- }
-
- this.$scope.setComponentIcon = (iconSrc:string):void => {
- this.$scope.component.icon = iconSrc;
- this.$scope.setValidState(true);
- }
- }
-
- save(callback:Function):void {
- let onFailed = () => {
- callback(false);
- };
-
- let onSuccess = (component:Models.Components.Component) => {
- this.$scope.component = component;
- this.$scope.setComponent(this.$scope.component);
- callback(true);
- };
-
- try {
- this.$scope.component.updateComponent().then(onSuccess, onFailed);
- }catch(e){
- callback(false);
- }
- }
-
- public back = (callback:Function):void => {
- this.save(callback);
- }
-
- }
-
-}
diff --git a/catalog-ui/app/scripts/view-models/wizard/properties-step/properties-step.html b/catalog-ui/app/scripts/view-models/wizard/properties-step/properties-step.html
deleted file mode 100644
index 4429451871..0000000000
--- a/catalog-ui/app/scripts/view-models/wizard/properties-step/properties-step.html
+++ /dev/null
@@ -1,57 +0,0 @@
-<div class="properties-step" data-ng-controller="Sdc.ViewModels.Wizard.PropertiesStepViewModel">
-
- <div class="w-sdc-classic-btn gray" data-tests-id="addGrey" data-ng-click="addOrUpdateProperty()">Add</div>
-
- <div class="table-container-flex">
-
- <div class="table">
- <div class="head flex-container">
- <div class="table-header head-row hand flex-item" data-ng-repeat="header in tableHeadersList track by $index" data-ng-click="sort(header.property)">{{header.title}}
- <span data-ng-if="sortBy === header.property" class="table-header-sort-arrow" data-ng-class="{'down': reverse, 'up':!reverse}"> </span>
- </div>
- <div class="table-no-text-header head-row flex-item"></div>
- <!--div class="table-no-text-header head-row flex-item"></div-->
- </div>
-
- <div class="body">
- <perfect-scrollbar scroll-y-margin-offset="0" include-padding="true" class="scrollbar-container">
- <div data-ng-if="component.properties.length === 0 " class="no-row-text">
- There are no properties to display <br>
- click <a data-ng-click="addOrUpdateProperty()">here</a> to add one
- </div>
- <div data-ng-repeat-start="property in component.properties | orderBy:sortBy:reverse track by $index"
- class="flex-container data-row" data-ng-class="{'selected': property.selected}"
- data-ng-click="property.selected = !property.selected">
-
- <div class="table-col-general flex-item text">
- <span class="sprite table-arrow" data-ng-class="{'opened': property.selected}"></span>
- <span data-tests-id="{{property.name}}" tooltips tooltip-content="{{property.name}}">{{property.name}}</span>
-
- </div>
-
- <div class="table-col-general flex-item text" data-tests-id="{{property.type}}" data-ng-bind="property.type"></div>
-
- <div class="table-col-general flex-item text">
- <span tooltips tooltip-content="{{property.defaultValue}}" data-tests-id="{{property.defaultValue}}" data-ng-bind="property.defaultValue"></span>
- </div>
-
- <div class="table-btn-col flex-item">
- <button class="table-edit-btn" data-ng-show="property.parentUniqueId==component.uniqueId"
- data-ng-click="addOrUpdateProperty(property); $event.stopPropagation();"> </button>
- <button class="table-delete-btn" data-ng-show="property.parentUniqueId==component.uniqueId"
- data-ng-click="delete(property); $event.stopPropagation();"> </button>
- </div>
-
- <!--div class="table-btn-col flex-item">
-
- </div-->
- </div>
- <div data-ng-repeat-end="" data-ng-if="property.selected && property.description" class="item-opened" data-ng-bind="property.description">
- </div>
- </perfect-scrollbar>
- </div>
-
- </div>
- </div>
-
-</div>
diff --git a/catalog-ui/app/scripts/view-models/wizard/properties-step/properties-step.less b/catalog-ui/app/scripts/view-models/wizard/properties-step/properties-step.less
deleted file mode 100644
index 0d7dad8dc2..0000000000
--- a/catalog-ui/app/scripts/view-models/wizard/properties-step/properties-step.less
+++ /dev/null
@@ -1,55 +0,0 @@
-.properties-step {
-
- .w-sdc-classic-btn {
- float: right;
- margin-bottom: 10px;
- }
-
- .table{
- height: 412px;
- margin-bottom: 0;
- }
-
- .table-container-flex {
- margin-top: 0px;
-
- .text{
- overflow: hidden;
- text-overflow: ellipsis;
- display: inline-block;
- white-space: nowrap;
- padding: 5px 4px;
-
- }
-
- .flex-item:nth-child(1) {
- flex-grow: 15;
-
- .hand;
- span.table-arrow {
- margin-right: 7px;
- }
- }
-
- .flex-item:nth-child(2) {
- flex-grow: 6;
- }
-
- .flex-item:nth-child(3) {
- flex-grow: 9;
- }
-
- .flex-item:nth-child(4) {
- flex-grow: 3;
- //padding-top: 10px;
- padding: 10px 4px;
-
- }
-
- .flex-item:nth-child(5) {
- flex-grow: 1;
- }
-
- }
-
-}
diff --git a/catalog-ui/app/scripts/view-models/wizard/properties-step/properties-step.ts b/catalog-ui/app/scripts/view-models/wizard/properties-step/properties-step.ts
deleted file mode 100644
index 08dfb5e153..0000000000
--- a/catalog-ui/app/scripts/view-models/wizard/properties-step/properties-step.ts
+++ /dev/null
@@ -1,123 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../../references"/>
-module Sdc.ViewModels.Wizard {
- 'use strict';
-
- interface IPropertiesStepViewModelScope extends IWizardCreationStepScope {
- component: Models.Components.Component;
- tableHeadersList: Array<any>;
- reverse: boolean;
- sortBy:string;
-
- addOrUpdateProperty(): void;
- delete(property: Models.PropertyModel): void;
- sort(sortBy:string): void;
- }
-
- export class PropertiesStepViewModel implements IWizardCreationStep {
-
- static '$inject' = [
- '$scope',
- '$filter',
- '$modal',
- '$templateCache',
- 'ModalsHandler'
- ];
-
-
- constructor(
- private $scope:IPropertiesStepViewModelScope,
- private $filter:ng.IFilterService,
- private $modal:ng.ui.bootstrap.IModalService,
- private $templateCache:ng.ITemplateCacheService,
- private ModalsHandler: Utils.ModalsHandler
- ){
-
- this.$scope.registerChild(this);
- this.$scope.setValidState(true);
- this.initScope();
- }
-
- public save = (callback:Function):void => {
- this.$scope.setComponent(this.$scope.component);
- callback(true);
- };
-
- public back = (callback:Function):void => {
- this.$scope.setComponent(this.$scope.component);
- callback(true);
- }
-
-
- private openEditPropertyModal = (property: Models.PropertyModel): void => {
- let viewModelsHtmlBasePath: string = '/app/scripts/view-models/';
-
- let modalOptions: ng.ui.bootstrap.IModalSettings = {
- template: this.$templateCache.get(viewModelsHtmlBasePath+'wizard/property-form/property-form.html'),
- controller: 'Sdc.ViewModels.Wizard.PropertyFormViewModel',
- size: 'sdc-md',
- backdrop: 'static',
- keyboard: false,
- resolve: {
- property: (): Models.PropertyModel => {
- return property;
- },
- component: (): Models.Components.Component => {
- return <Models.Components.Component> this.$scope.getComponent();
- }
- }
- };
- this.$modal.open(modalOptions);
- };
-
- private initScope = (): void => {
-
- let self = this;
- this.$scope.component = this.$scope.getComponent();
- this.$scope.sortBy = 'name';
- this.$scope.reverse = false;
-
- this.$scope.tableHeadersList = [
- {title:'Name', property: 'name'},
- {title:'Type', property: 'type'},
- {title:'Default Value', property: 'defaultValue'}
- ];
- this.$scope.sort = (sortBy:string):void => {
- this.$scope.reverse = (this.$scope.sortBy === sortBy) ? !this.$scope.reverse : false;
- this.$scope.sortBy = sortBy;
- };
-
- this.$scope.addOrUpdateProperty = (property?: Models.PropertyModel): void => {
- this.openEditPropertyModal(property ? property : new Models.PropertyModel());
- };
-
- this.$scope.delete = (property: Models.PropertyModel): void => {
-
- let onOk = (): void => {
- this.$scope.component.deleteProperty(property.uniqueId);
- };
- let title:string = this.$filter('translate')("PROPERTY_VIEW_DELETE_MODAL_TITLE");
- let message:string = this.$filter('translate')("PROPERTY_VIEW_DELETE_MODAL_TEXT", "{'name': '" + property.name + "'}");
- this.ModalsHandler.openConfirmationModal(title, message, false).then(onOk);
- };
- }
- }
-}
diff --git a/catalog-ui/app/scripts/view-models/wizard/property-form/property-form-view-model-tests.ts b/catalog-ui/app/scripts/view-models/wizard/property-form/property-form-view-model-tests.ts
deleted file mode 100644
index 3f390841ca..0000000000
--- a/catalog-ui/app/scripts/view-models/wizard/property-form/property-form-view-model-tests.ts
+++ /dev/null
@@ -1,163 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../../references"/>
-
-describe("property form View Model ", () => {
-
- let $controllerMock:ng.IControllerService;
- let $qMock:ng.IQService;
- let $httpBackendMock:ng.IHttpBackendService;
- let $scopeMock:Sdc.ViewModels.Wizard.IPropertyFormViewModelScope;
- let $stateMock:ng.ui.IStateService;
- let $stateParams:any;
- let component = {
- "uniqueId": "ece818e0-fd59-477a-baf6-e27461a7ce23",
- "uuid": "8db823c2-6a9c-4636-8676-f5e713270dd7",
- "contactId": "uf2345",
- "category": "Network Layer 2-3/Router",
- "creationDate": 1447235352429,
- "description": "u",
- "highestVersion": true,
- "icon": "network",
- "lastUpdateDate": 1447235370064,
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT",
- "name": "u",
- "version": "0.1",
- "type": 1,
- "tags": [
- "u"
- ],
- "vendorName": "u",
- "vendorRelease": "u",
- "systemName": "U",
- "$$hashKey": "object:34"
- };
-
-
- beforeEach(angular.mock.module('sdcApp'));
-
- beforeEach(angular.mock.inject((_$controller_:ng.IControllerService,
- _$httpBackend_:ng.IHttpBackendService,
- _$rootScope_,
- _$q_:ng.IQService,
- _$state_:ng.ui.IStateService,
- _$stateParams_:any) => {
-
- $controllerMock = _$controller_;
- $httpBackendMock = _$httpBackend_
- $scopeMock = _$rootScope_.$new();
- $qMock = _$q_;
- $stateMock = _$state_;
- $stateParams = _$stateParams_;
-
-
- //handle all http request thet not relevant to the tests
- $httpBackendMock.expectGET(/.*languages\/en_US.json.*/).respond(200, JSON.stringify({}));
- // $httpBackendMock.expectGET(/.*resources\/certified\/abstract.*/).respond(200, JSON.stringify({}));
- $httpBackendMock.expectGET(/.*rest\/version.*/).respond(200, JSON.stringify({}));
- $httpBackendMock.expectGET(/.*configuration\/ui.*/).respond(200, JSON.stringify({}));
- $httpBackendMock.expectGET(/.*user\/authorize.*/).respond(200, JSON.stringify({}));
- $httpBackendMock.expectGET(/.*categories\/services.*/).respond(200, JSON.stringify({}));
- $httpBackendMock.expectGET(/.*categories\/resources.*/).respond(200, JSON.stringify({}));
- $httpBackendMock.expectGET(/.*categories\/products.*/).respond(200, JSON.stringify({}));
- $httpBackendMock.expectGET('http://feHost:8181/sdc1/feProxy/rest/version').respond(200, JSON.stringify({}));
-
- /**
- * Mock the service
- * @type {any}
- */
- //getAllEntitiesDefered = $qMock.defer();
- //getAllEntitiesDefered.resolve(getAllEntitiesResponseMock);
- //entityServiceMock = jasmine.createSpyObj('entityServiceMock', ['getAllComponents']);
- //entityServiceMock.getAllComponents.and.returnValue(getAllEntitiesDefered.promise);
-
- // $stateParams['show'] = '';
-
- /**
- * Need to inject into the controller only the objects that we want to MOCK
- * those that we need to change theirs behaviors
- */
- $controllerMock(Sdc.ViewModels.Wizard.PropertyFormViewModel, {
- '$scope': $scopeMock,
- 'property': new Sdc.Models.PropertyModel(),
- 'component': component,
- });
-
- }));
-
- describe("when Controller 'PropertyFormViewModel' created", () => {
-
- it('should have a regexp per each type', () => {
- $scopeMock.$apply();
- expect(Object.keys($scopeMock.listRegex).length).toBe($scopeMock.editPropertyModel["simpleTypes"].length);
- });
-
- it('should have equal regexps for map and list', () => {
- $scopeMock.$apply();
- expect(Object.keys($scopeMock.listRegex).length).toBe(Object.keys($scopeMock.mapRegex).length);
- });
-
- });
-
- /*describe("when Controller 'DashboardViewModel' created", () => {
-
- it('should generate all entities', () => {
- $scopeMock.$apply();
- expect($scopeMock.components.length).toBe(getAllEntitiesResponseMock.length);
- });
-
-
- it('should show tutorial page ', () => {
- $stateParams.show = 'tutorial';
-
- $controllerMock(Sdc.ViewModels.DashboardViewModel, {
- '$scope': $scopeMock,
- '$stateParams': $stateParams,
- 'Sdc.Services.EntityService': entityServiceMock,
- //to complete injects
- });
-
- $scopeMock.$apply();
- expect($scopeMock.isFirstTime).toBeTruthy();
- expect($scopeMock.showTutorial).toBeTruthy();
- });
-
- });
-
-
- describe("when function 'entitiesCount' invoked", () => {
-
- beforeEach(() => {
- $controllerMock(Sdc.ViewModels.DashboardViewModel, {
- '$scope': $scopeMock,
- 'Sdc.Services.EntityService': entityServiceMock,
- });
- $scopeMock.$apply();
- });
-
- it('should return entities count per folder', () => {
-
- });
-
-
- });*/
-});
diff --git a/catalog-ui/app/scripts/view-models/wizard/property-form/property-form-view-model.ts b/catalog-ui/app/scripts/view-models/wizard/property-form/property-form-view-model.ts
deleted file mode 100644
index 5cb0ef1ddd..0000000000
--- a/catalog-ui/app/scripts/view-models/wizard/property-form/property-form-view-model.ts
+++ /dev/null
@@ -1,250 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../../references"/>
-
-module Sdc.ViewModels.Wizard {
- 'use strict';
-
- export interface IEditPropertyModel{
- property: Models.PropertyModel;
- types: Array<string>;
- simpleTypes: Array<string>;
- sources: Array<string>;
- }
-
- export interface IPropertyFormViewModelScope extends ng.IScope{
-
- $$childTail: any;
- editForm:ng.IFormController;
- forms:any;
- footerButtons: Array<any>;
- isNew: boolean;
- isLoading: boolean;
- validationPattern: RegExp;
- propertyNameValidationPattern: RegExp;
- integerValidationPattern: RegExp;
- floatValidationPattern: RegExp;
- commentValidationPattern: RegExp;
- listRegex: Sdc.Utils.IMapRegex;
- mapRegex: Sdc.Utils.IMapRegex;
- editPropertyModel: IEditPropertyModel;
- modalInstanceProperty: ng.ui.bootstrap.IModalServiceInstance;
- save(doNotCloseModal?: boolean): void;
- saveAndAnother(): void;
- getValidation(): RegExp;
- validateIntRange(value:string):boolean;
- close(): void;
- onValueChange(): void;
- onTypeChange(resetSchema:boolean): void;
- showSchema(): boolean;
- getValidationTranslate():string;
- validateUniqueKeys(viewValue:string):boolean;
- }
-
- export class PropertyFormViewModel{
-
- private originalValue: string;
-
- static '$inject' = [
- '$scope',
- '$modalInstance',
- 'property',
- 'ValidationPattern',
- 'PropertyNameValidationPattern',
- 'IntegerNoLeadingZeroValidationPattern',
- 'FloatValidationPattern',
- 'CommentValidationPattern',
- 'ValidationUtils',
- 'component'
- ];
-
- private formState: Utils.Constants.FormState;
- private entityId: string;
- private resourceInstanceUniqueId: string;
- private readonly: boolean;
-
- constructor(
- private $scope:IPropertyFormViewModelScope,
- private $modalInstance: ng.ui.bootstrap.IModalServiceInstance,
- private property : Models.PropertyModel,
- private ValidationPattern : RegExp,
- private PropertyNameValidationPattern: RegExp,
- private IntegerNoLeadingZeroValidationPattern : RegExp,
- private FloatValidationPattern : RegExp,
- private CommentValidationPattern: RegExp,
- private ValidationUtils: Sdc.Utils.ValidationUtils,
- private component:Models.Components.Component
- ){
- this.entityId = this.component.uniqueId;
- this.formState = angular.isDefined(property.name) ? Utils.Constants.FormState.UPDATE : Utils.Constants.FormState.CREATE;
- this.initScope();
- }
-
-
- private initResource = (): void => {
- this.$scope.editPropertyModel.property = new Sdc.Models.PropertyModel(this.property);
- this.originalValue = this.property.defaultValue;
- if(this.$scope.editPropertyModel.types.indexOf(this.property.type) === -1 && !this.$scope.isNew){
- this.property.type = "string";
- }
- };
-
- private initEditPropertyModel = (): void => {
- this.$scope.editPropertyModel = {
- property: null,
- types: ['integer', 'string', 'float', 'boolean', 'list', 'map'],
- simpleTypes: ['integer', 'string', 'float', 'boolean'],
- sources: ['A&AI', 'Order', 'Runtime']
- };
-
- this.initResource();
- };
-
- private initScope = (): void => {
-
- this.$scope.modalInstanceProperty = this.$modalInstance;
- //scope properties
- this.$scope.validationPattern = this.ValidationPattern;
- this.$scope.propertyNameValidationPattern = this.PropertyNameValidationPattern;
- this.$scope.integerValidationPattern = this.IntegerNoLeadingZeroValidationPattern;
- this.$scope.floatValidationPattern = this.FloatValidationPattern;
- this.$scope.commentValidationPattern = this.CommentValidationPattern;
-
- //map & list validation patterns
- this.$scope.listRegex = this.ValidationUtils.getPropertyListPatterns();
- this.$scope.mapRegex = this.ValidationUtils.getPropertyMapPatterns();
-
- this.$scope.isLoading = false;
- this.$scope.isNew = (this.formState === Utils.Constants.FormState.CREATE);
- this.initEditPropertyModel();
-
- //scope methods
- this.$scope.save = (): void => {
- this.$scope.editPropertyModel.property.description = this.ValidationUtils.stripAndSanitize(this.$scope.editPropertyModel.property.description);
- this.$scope.isLoading = true;
-
- let onFailed = (response) => {
- console.info('onFaild',response);
- this.$scope.isLoading = false;
- this.$scope.editPropertyModel.property.readonly = this.readonly;
- this.$scope.editPropertyModel.property.resourceInstanceUniqueId = this.resourceInstanceUniqueId;
- };
-
- let onSuccess = (property: Models.PropertyModel): void => {
- console.info('property added : ',property);
- this.$scope.isLoading = false;
- property.resourceInstanceUniqueId = this.resourceInstanceUniqueId;
- property.readonly = (property.parentUniqueId !== this.component.uniqueId) /*|| this.component.isService()*/;
-
- this.$modalInstance.close();
- };
-
- this.resourceInstanceUniqueId = this.$scope.editPropertyModel.property.resourceInstanceUniqueId;
- this.readonly = this.$scope.editPropertyModel.property.readonly;
- this.$scope.editPropertyModel.property.defaultValue = this.$scope.editPropertyModel.property.defaultValue ? this.$scope.editPropertyModel.property.defaultValue:null;
-
- this.component.addOrUpdateProperty(this.$scope.editPropertyModel.property).then(onSuccess, onFailed);
- };
-
- this.$scope.saveAndAnother = (): void => {
- this.$scope.save();
- };
-
- this.$scope.showSchema = () :boolean => {
- return ['list', 'map'].indexOf(this.$scope.editPropertyModel.property.type) > -1;
- };
-
- this.$scope.getValidationTranslate = () : string => {
- let result = "PROPERTY_EDIT_PATTERN";
- if (this.$scope.showSchema()) {
-
- result = "PROPERTY_EDIT_" + this.$scope.editPropertyModel.property.type.toUpperCase();
-
- if(this.$scope.editPropertyModel.property.schema.property.type === 'string') {
- result += "_STRING";
- } else {
- result += "_GENERIC";
- }
- }
-
- return result;
- };
-
- this.$scope.getValidation = () : RegExp => {
- let type = this.$scope.editPropertyModel.property.type;
- switch (type){
- case 'integer':
- return this.$scope.integerValidationPattern;
- case 'float':
- return this.$scope.floatValidationPattern;
- case 'list':
- return this.$scope.listRegex[this.$scope.editPropertyModel.property.schema.property.type];
- case 'map':
- return this.$scope.mapRegex[this.$scope.editPropertyModel.property.schema.property.type];
- default :
- return null;
- }
- };
-
- this.$scope.validateUniqueKeys = (viewValue:string) : boolean => {
- if(this.$scope.editPropertyModel.property.type === 'map') {
- return this.ValidationUtils.validateUniqueKeys(viewValue);
- }
- else {
- return true; //always valid if not a map
- }
- };
-
- this.$scope.validateIntRange = (value:string):boolean => {
- return !value || this.ValidationUtils.validateIntRange(value);
- };
-
- this.$scope.close = (): void => {
- this.$modalInstance.close();
- };
-
- this.$scope.onValueChange = (): void => {
- if(!this.$scope.editPropertyModel.property.defaultValue && this.$scope.editPropertyModel.property.required) {
- this.$scope.editPropertyModel.property.defaultValue = this.originalValue;
- }
- };
-
- this.$scope.onTypeChange = (resetSchema:boolean): void => {
- this.$scope.editPropertyModel.property.defaultValue = '';
- if (resetSchema) {
- this.$scope.editPropertyModel.property.schema.property.type = '';
- }
- };
-
- //new form layout for import asset
- this.$scope.forms = {};
- this.$scope.footerButtons = [
- {'name': this.$scope.isNew ? 'Add' : 'Update', 'css':'blue', 'callback': this.$scope.save},
- {'name':'Cancel', 'css':'grey', 'callback': this.$scope.close}
- ];
-
- this.$scope.$watch('forms.editForm.$invalid', () => {
- this.$scope.footerButtons[0].disabled = this.$scope.forms.editForm.$invalid;
- });
-
- }
-
- }
-}
diff --git a/catalog-ui/app/scripts/view-models/wizard/property-form/property-form.html b/catalog-ui/app/scripts/view-models/wizard/property-form/property-form.html
deleted file mode 100644
index be237112a4..0000000000
--- a/catalog-ui/app/scripts/view-models/wizard/property-form/property-form.html
+++ /dev/null
@@ -1,133 +0,0 @@
-<sdc-modal modal="modalInstanceProperty" type="classic" class="sdc-add-property" buttons="footerButtons" header="{{isNew ? 'Add' : 'Update' }} Property" show-close-button="true">
-
- <form novalidate class="w-sdc-form two-columns" name="forms.editForm" >
-
- <div class="w-sdc-form-columns-wrapper">
-
- <div class="w-sdc-form-column">
-
- <div class="i-sdc-form-item" data-ng-class="{error:(forms.editForm.propertyName.$dirty && forms.editForm.propertyName.$invalid)}">
- <label class="i-sdc-form-label" ng-class="{'required': !isService}">Name</label>
- <input class="i-sdc-form-input"
- data-ng-maxlength="50"
- data-ng-disabled="!isNew || editPropertyModel.property.readonly"
- maxlength="50"
- data-ng-model="editPropertyModel.property.name"
- type="text"
- name="propertyName"
- data-ng-pattern="propertyNameValidationPattern"
- data-required
- data-ng-model-options="{ debounce: 200 }"
- data-tests-id="propertyName"
- autofocus />
-
- <div class="input-error" data-ng-show="forms.editForm.propertyName.$dirty && forms.editForm.propertyName.$invalid">
- <span ng-show="forms.editForm.propertyName.$error.required" translate="VALIDATION_ERROR_REQUIRED" translate-values="{'field': 'Property name' }"></span>
- <span ng-show="forms.editForm.propertyName.$error.maxlength" translate="VALIDATION_ERROR_MAX_LENGTH" translate-values="{'max': '128' }"></span>
- <span ng-show="forms.editForm.propertyName.$error.pattern" translate="VALIDATION_ERROR_SPECIAL_CHARS_NOT_ALLOWED"></span>
- </div>
- </div>
-
-
- <div class="i-sdc-form-item" data-ng-class="{error:(forms.editForm.schemaType.$dirty && forms.editForm.schemaType.$invalid)}"
- data-ng-if="showSchema()">
- <label class="i-sdc-form-label required">Entry Schema</label>
- <select class="i-sdc-form-select"
- data-required
- name="schemaType"
- data-tests-id="schemaType"
- data-ng-change="onTypeChange(false)"
- data-ng-model="editPropertyModel.property.schema.property.type"
- data-ng-options="type for type in editPropertyModel.simpleTypes">
- <option value="">Choose Schema Type</option>
- </select>
-
- <div class="input-error" data-ng-show="forms.editForm.schemaType.$dirty && forms.editForm.schemaType.$invalid">
- <span ng-show="forms.editForm.schemaType.$error.required" translate="VALIDATION_ERROR_REQUIRED" translate-values="{'field': 'Entry schema' }"></span>
- </div>
- </div>
-
-
- <div class="i-sdc-form-item" data-ng-class="{error:(forms.editForm.value.$dirty && forms.editForm.value.$invalid)}">
- <label class="i-sdc-form-label">Default Value</label>
- <input class="i-sdc-form-input"
- ng-if="!(editPropertyModel.property.type == 'boolean')"
- data-ng-maxlength="100"
- data-ng-disableddddddd="editPropertyModel.property.readonly && !isService && !isPropertyValueOwner()"
- maxlength="100"
- data-ng-model="editPropertyModel.property.defaultValue"
- type="text"
- name="value"
- data-custom-validation="" data-validation-func="validateUniqueKeys"
- data-ng-pattern="getValidation()"
- data-ng-model-options="{ debounce: 200 }"
- data-ng-change="!forms.editForm.value.$error.pattern && ('integer'==editPropertyModel.property.type && forms.editForm.value.$setValidity('pattern', validateIntRange(editPropertyModel.property.defaultValue)) || onValueChange())"
- data-tests-id="defaultValue"
- autofocus />
- <select class="i-sdc-form-select"
- ng-if="editPropertyModel.property.type == 'boolean'"
- data-ng-disabled="editPropertyModel.property.readonly && !isPropertyValueOwner()"
- name="value"
- data-ng-change="onValueChange()"
- data-ng-model="editPropertyModel.property.defaultValue">
- <option value=""></option>
- <option value="true">true</option>
- <option value="false">false</option>
- </select>
-
- <div class="input-error" data-ng-show="forms.editForm.value.$dirty && forms.editForm.value.$invalid">
- <span ng-show="forms.editForm.value.$error.required" translate="VALIDATION_ERROR_REQUIRED" translate-values="{'field': 'Property' }"></span>
- <span ng-show="forms.editForm.value.$error.maxlength" translate="VALIDATION_ERROR_MAX_LENGTH" translate-values="{'max': '100' }"></span>
- <span ng-show="forms.editForm.value.$error.pattern" translate="{{getValidationTranslate()}}"></span>
- <span ng-show="forms.editForm.value.$error.customValidation" translate="PROPERTY_EDIT_MAP_UNIQUE_KEYS"></span>
- </div>
- </div>
-
- </div>
-
- <div class="w-sdc-form-column">
-
- <div class="i-sdc-form-item" data-ng-class="{error:(forms.editForm.type.$dirty && forms.editForm.type.$invalid)}">
- <label class="i-sdc-form-label" ng-class="{'required': !isService}">Type</label>
- <select class="i-sdc-form-select"
- data-required
- data-ng-disableddddddd="editPropertyModel.property.readonly"
- data-tests-id="propertyType"
- name="type"
- data-ng-change="onTypeChange(true)"
- data-ng-model="editPropertyModel.property.type"
- data-ng-options="type for type in editPropertyModel.types">
- <option value="">Choose Type</option>
- </select>
-
- <div class="input-error" data-ng-show="forms.editForm.type.$dirty && forms.editForm.type.$invalid">
- <span ng-show="forms.editForm.type.$error.required" translate="VALIDATION_ERROR_REQUIRED" translate-values="{'field': 'Type' }"></span>
- </div>
- </div>
-
- <div class="i-sdc-form-item" data-ng-class="{error:(forms.editForm.description.$dirty && forms.editForm.description.$invalid)}">
- <label class="i-sdc-form-label">Description</label>
- <textarea class="i-sdc-form-textarea"
- data-ng-maxlength="256"
- data-ng-disableddddddd="editPropertyModel.property.readonly"
- maxlength="256"
- data-ng-pattern="commentValidationPattern"
- name="description"
- data-ng-model="editPropertyModel.property.description"
- data-ng-model-options="{ debounce: 200 }"
- data-tests-id="description"
- ></textarea>
-
- <div class="input-error" data-ng-show="forms.editForm.description.$dirty && forms.editForm.description.$invalid">
- <span ng-show="forms.editForm.description.$error.maxlength" translate="VALIDATION_ERROR_MAX_LENGTH" translate-values="{'max': '256' }"></span>
- <span ng-show="forms.editForm.description.$error.pattern" translate="VALIDATION_ERROR_SPECIAL_CHARS_NOT_ALLOWED"></span>
- <span ng-show="forms.editForm.description.$error.required" translate="VALIDATION_ERROR_REQUIRED" translate-values="{'field': 'Description' }"></span>
- </div>
- </div>
-
- </div>
-
- </div>
- </form>
-
-</sdc-modal>
diff --git a/catalog-ui/app/scripts/view-models/wizard/property-form/property-form.less b/catalog-ui/app/scripts/view-models/wizard/property-form/property-form.less
deleted file mode 100644
index 52b8564fdb..0000000000
--- a/catalog-ui/app/scripts/view-models/wizard/property-form/property-form.less
+++ /dev/null
@@ -1,7 +0,0 @@
-.sdc-add-property{
-
- .w-sdc-form {
-
- }
-
-}
diff --git a/catalog-ui/app/scripts/view-models/wizard/wizard-creation-base.html b/catalog-ui/app/scripts/view-models/wizard/wizard-creation-base.html
deleted file mode 100644
index afa9307265..0000000000
--- a/catalog-ui/app/scripts/view-models/wizard/wizard-creation-base.html
+++ /dev/null
@@ -1,12 +0,0 @@
-<loader data-display="isLoading"></loader>
-<div class="sdc-wizard-name-type-label" data-ng-if="assetName!==undefined"><span class="sprite sprite-green-tick animated flash"></span><span class="name">{{assetName}}</span>&nbsp;|&nbsp;<span class="type">{{assetType}}</span></div>
-<sdc-modal modal="modalInstance" type="classic" get-close-modal-response="getComponent" buttons="footerButtons" class="sdc-wizard" header="{{modalTitle}}" show-close-button="true">
- <div class="sdc-wizard-wrapper">
- <div class="sdc-wizard-left-content">
- <sdc-wizard-step steps="directiveSteps" control="assetCreationControl" class="wizard-steps-line"></sdc-wizard-step>
- </div>
- <div class="sdc-wizard-right-content">
- <ng-include src="templateUrl" class="sdc-wizard-right-include"></ng-include>
- </div>
- </div>
-</sdc-modal>
diff --git a/catalog-ui/app/scripts/view-models/wizard/wizard-creation-base.less b/catalog-ui/app/scripts/view-models/wizard/wizard-creation-base.less
deleted file mode 100644
index 591186789b..0000000000
--- a/catalog-ui/app/scripts/view-models/wizard/wizard-creation-base.less
+++ /dev/null
@@ -1,60 +0,0 @@
-.sdc-wizard-wrapper {
- display: flex;
- padding: 80px 0;
- height: 620px;
- // So input validation error will be shown outside the modal (long messages).
- // overflow: hidden;
-
- .sdc-wizard-left-content {
- width: 400px;
- white-space: nowrap;
-
- .wizard-steps-line {
- padding: 0 80px 0 0;
- display: block;
- }
-
- }
-
- .sdc-wizard-right-content {
- margin-right: 200px;
- /* background-color: #fafafa; */
- height: 100%;
- width: 100%;
- .perfect-scrollbar;
- overflow: visible;
- //.animation-duration(2s);
-
- .sdc-wizard-right-include {
-
- }
- }
-
-}
-
-.sprite-green-tick.animated {
- .animation-duration(3s);
-}
-
-.sdc-wizard-name-type-label {
- position: absolute;
- top: 64px;
- right: 40px;
-
- span {
- .b_7;
- &.name {.bold;}
- &.sprite-green-tick {
- position: absolute;
- left: -22px;
- top: 5px;
- }
- }
-
-}
-
-.w-wizard-footer {
- button.cancel {
- margin-right: 120px;
- }
-}
diff --git a/catalog-ui/app/scripts/view-models/wizard/wizard-creation-base.ts b/catalog-ui/app/scripts/view-models/wizard/wizard-creation-base.ts
deleted file mode 100644
index 365d3aedf6..0000000000
--- a/catalog-ui/app/scripts/view-models/wizard/wizard-creation-base.ts
+++ /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=========================================================
- */
-/// <reference path="../../references"/>
-module Sdc.ViewModels.Wizard {
- 'use strict';
-
- export class StepNames {
- static general = "General";
- static icon = "Icon";
- static deploymentArtifact = "Deployment Artifact";
- static informationArtifact = "Information Artifact";
- static properties = "Properties";
- static hierarchy = "Hierarchy";
- }
-
- class FooterButtons {
- static cancel = "Cancel";
- static back = "Back";
- static next = "Next";
- static finish = "Finish";
- }
-
- export class WizardCreationTypes {
- static importAsset = "importAsset";
- static create = "create";
- static edit = "edit";
- }
-
- export class _CreationStep {
- name:string;
- url:string;
- }
-
- export class CurrentStep {
- assetCreationStep:_CreationStep;
- reference:IWizardCreationStep;
- index:number;
- valid: boolean;
- }
-
- export interface IWizardCreationStep {
- save(callback:Function):void;
- back(callback:Function):void;
- }
-
- export interface IWizardCreationStepScope extends ng.IScope {
- data:any;
- getComponent():Sdc.Models.Components.Component;
- setComponent(component: Sdc.Models.Components.Component):void;
- registerChild(child:IWizardCreationStep):void; // Called from the step
- setValidState(valid:boolean):void; // Called from the step
- }
-
- export interface IWizardCreationScope extends ng.IScope {
- isLoading: boolean;
- data:any; // data passed from dashboard (opener), need it on the scope, because general step will use this (extends the scope)
- directiveSteps: Array<Sdc.Directives.IWizardStep>; // Steps for the directive, on the scope (on the scope because need to pass to directive via HTML)
- templateUrl: string; // On the scope because need to pass to <ng-include> via HTML
- footerButtons: Array<Sdc.Directives.ISdcModalButton>; // Wizard footer buttons (on the scope because need to pass to directive via HTML)
- assetCreationControl:any; // Link to wizard directive functions.
- modalInstance:ng.ui.bootstrap.IModalServiceInstance; // Reference to the modal, so we can close it (on the scope because need to pass to directive via HTML)
- assetName:string;
- assetType:string;
- modalTitle:string;
- getComponent():Sdc.Models.Components.Component;
- setComponent(component: Sdc.Models.Components.Component):void;
- registerChild(child:IWizardCreationStep):void; // Called from the step
- setValidState(valid:boolean):void; // Called from the step
- }
-
- export class WizardCreationBaseViewModel {
-
- component: Sdc.Models.Components.Component;
- protected assetCreationSteps: Array<_CreationStep>; // Contains URL and name so we can replace them
- currentStep:CurrentStep;
- protected type:string;
-
- constructor(protected $scope:IWizardCreationScope,
- protected data:any,
- protected ComponentFactory: Utils.ComponentFactory,
- protected $modalInstance: ng.ui.bootstrap.IModalServiceInstance
- ) {
-
- this.$scope.data = data;
- this.currentStep = new CurrentStep();
- this.currentStep.valid=false;
- this.$scope.modalInstance = this.$modalInstance;
- this.initScope();
- this.noBackspaceNav();
-
- // In case the modal was opened with filled resource (edit mode).
- if (data.component){
- this.$scope.setComponent(data.component);
- data.componentType = this.$scope.getComponent().componentType;
- window.setTimeout(()=>{
- this.safeApply(this.setCurrentStepByIndex(0, false));
- },100);
- } else {
- // Default step to start with
- window.setTimeout(()=>{
- this.safeApply(this.setCurrentStepByIndex(0, false));
- },100);
- }
-
- }
-
- private safeApply = (fn:any) => {
- let phase = this.$scope.$root.$$phase;
- if (phase == '$apply' || phase == '$digest') {
- if (fn && (typeof(fn) === 'function')) {
- fn();
- }
- } else {
- this.$scope.$apply(fn);
- }
- };
-
- private initScope = ():void => {
-
- // Control to call functions on wizard step directive
- this.$scope.assetCreationControl = {};
-
- // Footer buttons definitions for the modal directive.
- this.$scope.footerButtons = [
- {"name":FooterButtons.cancel, "css":'white cancel',"callback": ()=>{this.btnCancelClicked();}},
- {"name":FooterButtons.back, "disabled":true, "css":'white back',"callback": ()=>{this.btnBackClicked();}},
- {"name":FooterButtons.next, "disabled":true, "css":'blue next',"callback": ()=>{this.btnNextClicked();}},
- {"name":FooterButtons.finish, "disabled":true, "css":'white finish',"callback": ()=>{this.btnFinishedClicked();}}
- ];
-
- // Will be called from step constructor to register him.
- // So the current step will be the reference.
- this.$scope.registerChild=(child:IWizardCreationStep):void => {
- this.currentStep.reference=child;
- };
-
- // Will be called from each step to notify if the step is valid
- // The wizard will set the "Next", "Finish" buttons accordingly.
- this.$scope.setValidState = (valid:boolean):void => {
- this.currentStep.valid=valid;
- let currentDirectiveStep:Sdc.Directives.IWizardStep = this.$scope.directiveSteps[this.currentStep.index];
- this.$scope.assetCreationControl.setStepValidity(currentDirectiveStep, valid);
- this.footerButtonsStateMachine();
- this.wizardButtonsIconsStateMachine();
- };
-
- /**
- * Will be called from each step to get current entity.
- * This will return copy of the entity (not reference), because I do not want that the step will change entity parameters.
- * If the step need to update the entity it can call setComponent function.
- * @returns {Sdc.Models.IEntity}
- */
- this.$scope.getComponent = ():Sdc.Models.Components.Component => {
- return this.component;
- };
-
- // Will be called from each step after save to update the resource.
- this.$scope.setComponent = (component:Sdc.Models.Components.Component):void => {
- this.component = component;
- };
-
- };
-
- protected setCurrentStepByName = (stepName:string):boolean => {
- let stepIndex:number = this.getStepIndex(stepName);
- return this.setCurrentStepByIndex(stepIndex);
- };
-
- // Set the current step, change the URL in ng-include.
- protected setCurrentStepByIndex = (index:number, doSave:boolean=true):boolean => {
- let result:boolean = false;
- if (this.currentStep.index!==index) { // Check that not pressing on same step, also the first time currentStepIndex=undefined
- if (doSave===true) {
- this.callStepSave(() => {
- // This section will be executed only if success save.
-
- // Set current step in the left wizard directive = valid
- let currentDirectiveStep:Sdc.Directives.IWizardStep = this.$scope.directiveSteps[this.currentStep.index];
- this.$scope.assetCreationControl.setStepValidity(currentDirectiveStep, true);
-
- // Move to next step
- let step:_CreationStep = this.assetCreationSteps[index];
- this.currentStep.index = index;
- this.currentStep.assetCreationStep = step;
- this.$scope.templateUrl = step.url;
-
- // Update the next/back buttons and steps buttons.
- this.footerButtonsStateMachine();
- this.wizardButtonsIconsStateMachine();
-
- // Can not perform step click without enabling the step
- this.$scope.directiveSteps[index].enabled = true; // Need to set the step enabled, before clicking it.
- this.$scope.assetCreationControl.stepClicked(step.name);
-
- // After saving the asset name and type will be shown in the top right of the screen.
- this.fillAssetNameAndType();
-
- result=true;
- });
- } else {
- // For the first time
- let step:_CreationStep = this.assetCreationSteps[index];
- this.currentStep.index = index;
- this.currentStep.assetCreationStep=step;
- this.$scope.templateUrl = step.url;
- this.$scope.directiveSteps[index].enabled = true; // Need to set the step enabled, before clicking it.
- this.$scope.assetCreationControl.stepClicked(step.name);
- result=true;
- }
-
- //this.updateFooterButtonsStates();
-
- } else {
- result=true;
- }
- return result;
- };
-
- // Save the current step
- private callStepSave = (successCallback:Function):void => {
- this.$scope.isLoading = true;
- this.currentStep.reference.save((result:boolean)=>{
- this.$scope.isLoading = false;
- if (result===true){
- successCallback();
- } else {
- // Set the next and finish button enabled.
- //this.updateFooterButtonsStates(true);
- }
- });
- };
-
- // Save the current step
- private callStepBack = (successCallback:Function):void => {
- this.$scope.isLoading = true;
- this.currentStep.reference.back((result:boolean)=>{
- this.$scope.isLoading = false;
- if (result===true){
- successCallback();
- } else {
- // Set the next and finish button enabled.
- //this.updateFooterButtonsStates(true);
- }
- });
- };
-
- private getStepIndex = (stepName:string):number => {
- let index:number=-1;
- let tmp = _.find(this.assetCreationSteps, function (item, indx) {
- index = indx;
- return item.name === stepName;
- });
- return index;
- };
-
- private btnNextClicked = ():void => {
- if (this.hasNext()===true) {
- let tmp = this.currentStep.index+1;
- this.setCurrentStepByIndex(tmp);
- }
- };
-
- private btnBackClicked = ():void => {
- if (this.hasBack()===true) {
- this.callStepBack(() => {
- let tmp = this.currentStep.index-1;
- this.setCurrentStepByIndex(tmp, false);
- });
- }
- };
-
- private btnCancelClicked = ():void => {
- this.$modalInstance.dismiss(this.$scope.getComponent());
- };
-
- private btnFinishedClicked = ():void => {
- this.callStepSave(() => {
- this.$modalInstance.close(this.$scope.getComponent());
- });
- };
-
- // Check if we can move next
- private hasNext = ():boolean => {
- if (this.assetCreationSteps.length-1>this.currentStep.index){
- return true;
- } else {
- return false;
- }
- };
-
- // Check if we can move back
- private hasBack = ():boolean => {
- if (this.currentStep.index===0){
- return false;
- } else {
- return true;
- }
- };
-
- private fillAssetNameAndType=():void => {
- this.$scope.assetName = this.$scope.getComponent().name;
- this.$scope.assetType = this.$scope.getComponent().getComponentSubType();
-
- };
-
- protected enableAllWizardSteps=():void => {
- this.$scope.directiveSteps.forEach((step:Sdc.Directives.IWizardStep) => {
- step.enabled=true;
- });
- };
-
- protected disableAllWizardSteps=():void => {
- this.$scope.directiveSteps.forEach((step:Sdc.Directives.IWizardStep) => {
- step.enabled=false;
- });
- };
-
- private footerButtonsStateMachine = ():void => {
- //console.log("footerButtonsStateMachine, current step validity: " + this.currentStep.valid);
- let stepIndex:number = this.currentStep.index;
- let cancelButton = this.$scope.footerButtons[0];
- let backButton = this.$scope.footerButtons[1];
- let nextButton = this.$scope.footerButtons[2];
- let finishButton = this.$scope.footerButtons[3];
-
- // NEXT button
- // Disable next button if it is the last step, and if not check the validity of the step.
- if (this.hasNext()){
- nextButton.disabled = !this.currentStep.valid;
- } else {
- nextButton.disabled = true;
- }
-
- // BACK button
- backButton.disabled = !this.hasBack();
-
- // FINISH button
- // If step 2 is valid show the finish button.
- if (stepIndex>=1 && this.currentStep.valid===true) {
- finishButton.disabled = false;
- }
- if (this.currentStep.valid===false){
- finishButton.disabled = true;
- }
-
- // EDIT
- if (this.type===WizardCreationTypes.edit && this.currentStep.valid===true){
- finishButton.disabled = false;
- }
-
- };
-
-
-
- private wizardButtonsIconsStateMachine = ():void => {
-
- // Enable or disable wizard directive next step, in case the current step form is valid or not.
- let stepIndex:number = this.currentStep.index;
- if (this.$scope.directiveSteps[stepIndex + 1]) {
- this.$scope.directiveSteps[stepIndex + 1].enabled = this.currentStep.valid;
- }
-
- // In case step 1 and 2 are valid, we can open all other steps.
- if (this.$scope.directiveSteps[0].valid===true && this.$scope.directiveSteps[1].valid===true){
- // Enable all wizard directive steps
- this.enableAllWizardSteps();
- } else if (this.currentStep.valid===false) {
- // Disable all steps
- this.disableAllWizardSteps();
- }
- };
-
- private noBackspaceNav:Function = ():void => {
- this.$scope.$on('$locationChangeStart', (event, newUrl, oldUrl):void =>{
- event.preventDefault();
- })
- };
-
-
- }
-
-}
diff --git a/catalog-ui/app/scripts/view-models/wizard/wizard-state/create-wizard.ts b/catalog-ui/app/scripts/view-models/wizard/wizard-state/create-wizard.ts
deleted file mode 100644
index 9490cddfdb..0000000000
--- a/catalog-ui/app/scripts/view-models/wizard/wizard-state/create-wizard.ts
+++ /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=========================================================
- */
-/**
- * Created by obarda on 3/15/2016.
- */
-/// <reference path="../../../references"/>
-module Sdc.ViewModels.Wizard {
- 'use strict';
-
- export class CreateWizardViewModel extends WizardCreationBaseViewModel {
-
- static '$inject' = [
- '$scope',
- 'data',
- 'ComponentFactory',
- '$modalInstance'
- ];
-
- constructor(public $scope:IWizardCreationScope,
- public data:any,
- public ComponentFactory: Sdc.Utils.ComponentFactory,
- public $modalInstance: ng.ui.bootstrap.IModalServiceInstance) {
-
- super($scope, data, ComponentFactory, $modalInstance);
- this.type = WizardCreationTypes.create;
- this.init();
- this.initCreateAssetScope();
- }
-
- private init = ():void => {
-
- switch (this.data.componentType){
- case Utils.Constants.ComponentType.RESOURCE: {
- this.assetCreationSteps = [
- {"name": StepNames.general, "url": '/app/scripts/view-models/wizard/general-step/general-step.html'},
- {"name": StepNames.icon, "url": '/app/scripts/view-models/wizard/icons-step/icons-step.html'},
- {"name": StepNames.deploymentArtifact, "url": '/app/scripts/view-models/wizard/artifact-deployment-step/artifact-deployment-step.html'},
- {"name": StepNames.informationArtifact, "url": '/app/scripts/view-models/wizard/artifact-information-step/artifact-information-step.html'},
- {"name": StepNames.properties, "url": '/app/scripts/view-models/wizard/properties-step/properties-step.html'}
- ];
- }
- break;
-
- case Utils.Constants.ComponentType.SERVICE: {
- this.assetCreationSteps = [
- {"name": StepNames.general, "url": '/app/scripts/view-models/wizard/general-step/general-step.html'},
- {"name": StepNames.icon, "url": '/app/scripts/view-models/wizard/icons-step/icons-step.html'}
- ];
- }
- break;
-
- case Utils.Constants.ComponentType.PRODUCT: {
- this.assetCreationSteps = [
- {"name": StepNames.general, "url": '/app/scripts/view-models/wizard/general-step/general-step.html'},
- {"name": StepNames.hierarchy, "url": '/app/scripts/view-models/wizard/hierarchy-step/hierarchy-step.html'},
- {"name": StepNames.icon, "url": '/app/scripts/view-models/wizard/icons-step/icons-step.html'}
- ];
- }
- break;
- }
- };
-
- private initCreateAssetScope = ():void => {
- switch (this.data.componentType){
- case Utils.Constants.ComponentType.RESOURCE: {
- this.$scope.directiveSteps = [
- {"name": StepNames.general, "enabled": true, "callback": ()=> {return this.setCurrentStepByName(StepNames.general);}},
- {"name": StepNames.icon, "enabled": false, "callback": ()=> {return this.setCurrentStepByName(StepNames.icon);}},
- {"name": StepNames.deploymentArtifact, "enabled": false, "callback": ()=> {return this.setCurrentStepByName(StepNames.deploymentArtifact);}},
- {"name": StepNames.informationArtifact, "enabled": false, "callback": ()=> {return this.setCurrentStepByName(StepNames.informationArtifact);}},
- {"name": StepNames.properties, "enabled": false, "callback": ()=> {return this.setCurrentStepByName(StepNames.properties);}}
- ];
- this.$scope.modalTitle = "Create VF";
- break;
- }
- case Utils.Constants.ComponentType.SERVICE: {
- this.$scope.directiveSteps = [
- {"name": StepNames.general, "enabled": true, "callback": ()=> {return this.setCurrentStepByName(StepNames.general);}},
- {"name": StepNames.icon, "enabled": false, "callback": ()=> {return this.setCurrentStepByName(StepNames.icon);}},
-
- ];
- this.$scope.modalTitle = "Create Service";
- break;
- }
- case Utils.Constants.ComponentType.PRODUCT: {
- this.$scope.directiveSteps = [
- {"name": StepNames.general, "enabled": true, "callback": ()=> {return this.setCurrentStepByName(StepNames.general);}},
- {"name": StepNames.hierarchy, "enabled":false, "callback": ()=> {return this.setCurrentStepByName(StepNames.hierarchy);}},
- {"name": StepNames.icon, "enabled": false, "callback": ()=> {return this.setCurrentStepByName(StepNames.icon);}}
- ];
- this.$scope.modalTitle = "Create Product";
- break;
- }
- }
- }
- }
-}
diff --git a/catalog-ui/app/scripts/view-models/wizard/wizard-state/edit-wizard.ts b/catalog-ui/app/scripts/view-models/wizard/wizard-state/edit-wizard.ts
deleted file mode 100644
index 353c487e0a..0000000000
--- a/catalog-ui/app/scripts/view-models/wizard/wizard-state/edit-wizard.ts
+++ /dev/null
@@ -1,164 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../../references"/>
-module Sdc.ViewModels.Wizard {
- 'use strict';
-
- export class EditWizardViewModel extends WizardCreationBaseViewModel {
-
- static '$inject' = [
- '$scope',
- 'data',
- 'ComponentFactory',
- '$modalInstance'
- ];
-
- constructor(public $scope:IWizardCreationScope,
- public data:any,
- public ComponentFactory: Sdc.Utils.ComponentFactory,
- public $modalInstance: ng.ui.bootstrap.IModalServiceInstance) {
-
- super($scope, data, ComponentFactory, $modalInstance);
- this.type = WizardCreationTypes.edit;
- this.init();
- this.initCreateAssetScope();
-
- // Enable all wizard directive steps
- this.enableAllWizardSteps();
- }
-
- private init = ():void => {
- switch (this.data.component.componentType){
- case Utils.Constants.ComponentType.RESOURCE: {
- if(this.data.component.isComplex()) {
- this.assetCreationSteps = [
- {
- "name": StepNames.general,
- "url": '/app/scripts/view-models/wizard/general-step/general-step.html'
- },
- {
- "name": StepNames.icon,
- "url": '/app/scripts/view-models/wizard/icons-step/icons-step.html'
- },
- {
- "name": StepNames.deploymentArtifact,
- "url": '/app/scripts/view-models/wizard/artifact-deployment-step/artifact-deployment-step.html'
- },
- {
- "name": StepNames.informationArtifact,
- "url": '/app/scripts/view-models/wizard/artifact-information-step/artifact-information-step.html'
- },
- {
- "name": StepNames.properties,
- "url": '/app/scripts/view-models/wizard/properties-step/properties-step.html'
- }
- ];
- }else{
- this.assetCreationSteps = [
- {"name": StepNames.general, "url": '/app/scripts/view-models/wizard/general-step/general-step.html'},
- {"name": StepNames.icon, "url": '/app/scripts/view-models/wizard/icons-step/icons-step.html'},
- {"name": StepNames.informationArtifact, "url": '/app/scripts/view-models/wizard/artifact-information-step/artifact-information-step.html'},
- {"name": StepNames.properties, "url": '/app/scripts/view-models/wizard/properties-step/properties-step.html'}
- ];
- }
- break;
- }
- case Utils.Constants.ComponentType.SERVICE: {
- this.assetCreationSteps = [
- {"name": StepNames.general, "url": '/app/scripts/view-models/wizard/general-step/general-step.html'},
- {"name": StepNames.icon, "url": '/app/scripts/view-models/wizard/icons-step/icons-step.html'}
- ];
- break;
- }
- case Utils.Constants.ComponentType.PRODUCT: {
- this.assetCreationSteps = [
- {"name": StepNames.general, "url": '/app/scripts/view-models/wizard/general-step/general-step.html'},
- {"name": StepNames.hierarchy, "url": '/app/scripts/view-models/wizard/hierarchy-step/hierarchy-step.html'},
- {"name": StepNames.icon, "url": '/app/scripts/view-models/wizard/icons-step/icons-step.html'}
- ];
- break;
- }
- }
- };
-
- private initCreateAssetScope = ():void => {
- switch (this.data.component.componentType){
- case Utils.Constants.ComponentType.RESOURCE: {
- if(this.data.component.isComplex()) {
- this.$scope.directiveSteps = [
- {
- "name": StepNames.general, "enabled": true, "callback": ()=> {
- return this.setCurrentStepByName(StepNames.general);
- }
- },
- {
- "name": StepNames.icon, "enabled": false, "callback": ()=> {
- return this.setCurrentStepByName(StepNames.icon);
- }
- },
- {
- "name": StepNames.deploymentArtifact, "enabled": false, "callback": ()=> {
- return this.setCurrentStepByName(StepNames.deploymentArtifact);
- }
- },
- {
- "name": StepNames.informationArtifact, "enabled": false, "callback": ()=> {
- return this.setCurrentStepByName(StepNames.informationArtifact);
- }
- },
- {
- "name": StepNames.properties, "enabled": false, "callback": ()=> {
- return this.setCurrentStepByName(StepNames.properties);
- }
- }
- ];
- }else{
- this.$scope.directiveSteps = [
- {"name": StepNames.general, "enabled": true, "callback": ()=> {return this.setCurrentStepByName(StepNames.general);}},
- {"name": StepNames.icon, "enabled": false, "callback": ()=> {return this.setCurrentStepByName(StepNames.icon);}},
- {"name": StepNames.informationArtifact, "enabled": false, "callback": ()=> {return this.setCurrentStepByName(StepNames.informationArtifact);}},
- {"name": StepNames.properties, "enabled": false, "callback": ()=> {return this.setCurrentStepByName(StepNames.properties);}}
- ];
- }
- this.$scope.modalTitle = "Edit " + this.data.component.resourceType;
- break;
- }
- case Utils.Constants.ComponentType.SERVICE: {
- this.$scope.directiveSteps = [
- {"name": StepNames.general, "enabled": true, "callback": ()=> {return this.setCurrentStepByName(StepNames.general);}},
- {"name": StepNames.icon, "enabled": false, "callback": ()=> {return this.setCurrentStepByName(StepNames.icon);}}
- ];
- this.$scope.modalTitle = "Edit Service";
- break;
- }
- case Utils.Constants.ComponentType.PRODUCT: {
- this.$scope.directiveSteps = [
- {"name": StepNames.general, "enabled": true, "callback": ()=> {return this.setCurrentStepByName(StepNames.general);}},
- {"name": StepNames.hierarchy, "enabled":false, "callback": ()=> {return this.setCurrentStepByName(StepNames.hierarchy);}},
- {"name": StepNames.icon, "enabled": false, "callback": ()=> {return this.setCurrentStepByName(StepNames.icon);}}
- ];
- this.$scope.modalTitle = "Edit Product";
- break;
- }
- }
- }
- }
-}
-
diff --git a/catalog-ui/app/scripts/view-models/wizard/wizard-state/import-wizard.ts b/catalog-ui/app/scripts/view-models/wizard/wizard-state/import-wizard.ts
deleted file mode 100644
index 5fe1bf7e59..0000000000
--- a/catalog-ui/app/scripts/view-models/wizard/wizard-state/import-wizard.ts
+++ /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=========================================================
- */
-/// <reference path="../../../references"/>
-module Sdc.ViewModels.Wizard {
- 'use strict';
-
- export class ImportWizardViewModel extends WizardCreationBaseViewModel {
-
- static '$inject' = [
- '$scope',
- 'data',
- 'ComponentFactory',
- '$modalInstance'
- ];
-
- constructor(public $scope:IWizardCreationScope,
- public data:any,
- public ComponentFactory: Sdc.Utils.ComponentFactory,
- public $modalInstance: ng.ui.bootstrap.IModalServiceInstance) {
-
- super($scope, data, ComponentFactory, $modalInstance );
- this.type = WizardCreationTypes.importAsset;
- this.init();
- this.initImportAssetScope();
- }
-
- private init = ():void => {
- this.assetCreationSteps = [
- {"name": StepNames.general, "url": '/app/scripts/view-models/wizard/general-step/general-step.html'},
- {"name": StepNames.icon, "url": '/app/scripts/view-models/wizard/icons-step/icons-step.html'},
- {"name": StepNames.informationArtifact, "url": '/app/scripts/view-models/wizard/artifact-information-step/artifact-information-step.html'},
- {"name": StepNames.properties, "url": '/app/scripts/view-models/wizard/properties-step/properties-step.html'}
- ];
- };
-
- private initImportAssetScope = ():void => {
- this.$scope.directiveSteps = [
- {"name": StepNames.general, "enabled": true, "callback": ()=> {return this.setCurrentStepByName(StepNames.general);}},
- {"name": StepNames.icon, "enabled": false, "callback": ()=> {return this.setCurrentStepByName(StepNames.icon);}},
- {"name": StepNames.informationArtifact, "enabled": false, "callback": ()=> {return this.setCurrentStepByName(StepNames.informationArtifact);}},
- {"name": StepNames.properties, "enabled": false, "callback": ()=> {return this.setCurrentStepByName(StepNames.properties);}}
- ];
-
- this.$scope.modalTitle = "Import Asset";
- };
- }
-}
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/activity-log/activity-log.ts b/catalog-ui/app/scripts/view-models/workspace/tabs/activity-log/activity-log.ts
deleted file mode 100644
index 665d0c0ef6..0000000000
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/activity-log/activity-log.ts
+++ /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=========================================================
- */
-/// <reference path="../../../../references"/>
-module Sdc.ViewModels {
- 'use strict';
-
- export interface IActivityLogViewModelScope extends IWorkspaceViewModelScope {
- activityDateArray: Array<any>; //this is in order to sort the dates
- activityLog: Array<Models.Activity>;
- preVersion:string;
-
- tableHeadersList: Array<any>;
- reverse: boolean;
- sortBy:string;
- searchBind:string;
-
- getActivityLog(uniqueId:string):void;
- onVersionChanged(version:any) : void;
- parseAction(action:string):string;
- sort(sortBy:string): void;
- }
-
- export class ActivityLogViewModel {
-
- static '$inject' = [
- '$scope',
- '$state',
- 'Sdc.Services.ActivityLogService'
- ];
-
- constructor(private $scope:IActivityLogViewModelScope,
- private $state:ng.ui.IStateService,
- private activityLogService:Services.ActivityLogService
- ) {
-
- this.initScope();
- this.$scope.setValidState(true);
- this.initSortedTableScope();
- this.$scope.updateSelectedMenuItem();
-
- // Set default sorting
- this.$scope.sortBy = 'logDate';
- }
-
- private initScope():void {
-
- this.$scope.preVersion = this.$scope.component.version;
-
- this.$scope.onVersionChanged = (version:any):void => {
- if (version.versionNumber != this.$scope.component.version) {
- this.$scope.isLoading = true;
- this.$scope.getActivityLog(version.versionId);
- }
- };
-
- this.$scope.getActivityLog = (uniqueId:any):void => {
-
- let onError = (response) => {
- this.$scope.isLoading = false;
- console.info('onFaild', response);
-
- };
-
- let onSuccess = (response:Array<Models.Activity>) => {
- this.$scope.activityLog = _.sortBy(response, function(o) { return o.TIMESTAMP; }); //response; //
- this.$scope.isLoading = false;
- };
-
- this.$scope.isLoading = true;
- if (this.$scope.component.isResource()) {
- this.activityLogService.getActivityLogService('resources', uniqueId).then(onSuccess, onError);
- }
- if (this.$scope.component.isService()) {
- this.activityLogService.getActivityLogService('services', uniqueId).then(onSuccess, onError);
- }
-
- };
-
- if (!this.$scope.activityLog || this.$scope.preVersion != this.$scope.component.version) {
- this.$scope.getActivityLog(this.$scope.component.uniqueId);
- }
-
- this.$scope.parseAction = (action:string) => {
- return action ? action.split(/(?=[A-Z])/).join(' ') : '';
- };
-
- }
-
- private initSortedTableScope = ():void => {
- this.$scope.tableHeadersList = [
- {title: 'Date', property: 'logDate'},
- {title: 'Action', property: 'logAction'},
- {title: 'Comment', property: 'logComment'},
- {title: 'Username', property: 'logUsername'},
- {title: 'Status', property: 'logStatus'}
- ];
-
- this.$scope.sort = (sortBy:string):void => {
- this.$scope.reverse = (this.$scope.sortBy === sortBy) ? !this.$scope.reverse : false;
- this.$scope.sortBy = sortBy;
- };
- };
-
- }
-}
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/attributes/attributes-view-model.ts b/catalog-ui/app/scripts/view-models/workspace/tabs/attributes/attributes-view-model.ts
deleted file mode 100644
index 469da6a2e1..0000000000
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/attributes/attributes-view-model.ts
+++ /dev/null
@@ -1,107 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../../../references"/>
-module Sdc.ViewModels {
- 'use strict';
-
- interface IAttributesViewModelScope extends IWorkspaceViewModelScope {
- tableHeadersList: Array<any>;
- reverse: boolean;
- sortBy:string;
-
- addOrUpdateAttribute(attribute?:Models.AttributeModel): void;
- delete(attribute:Models.AttributeModel): void;
- sort(sortBy:string): void;
- }
-
- export class AttributesViewModel {
-
- static '$inject' = [
- '$scope',
- '$filter',
- '$modal',
- '$templateCache',
- 'ModalsHandler'
- ];
-
-
- constructor(private $scope:IAttributesViewModelScope,
- private $filter:ng.IFilterService,
- private $modal:ng.ui.bootstrap.IModalService,
- private $templateCache:ng.ITemplateCacheService,
- private ModalsHandler:Utils.ModalsHandler) {
- this.initScope();
- this.$scope.updateSelectedMenuItem();
- }
-
-
- private openEditAttributeModal = (attribute:Models.AttributeModel):void => {
- let viewModelsHtmlBasePath:string = '/app/scripts/view-models/';
-
- let modalOptions:ng.ui.bootstrap.IModalSettings = {
- template: this.$templateCache.get(viewModelsHtmlBasePath + 'forms/attribute-form/attribute-form-view.html'),
- controller: 'Sdc.ViewModels.AttributeFormViewModel',
- size: 'sdc-md',
- backdrop: 'static',
- keyboard: false,
- resolve: {
- attribute: ():Models.AttributeModel => {
- return attribute;
- },
- component: ():Models.Components.Component => {
- return <Models.Components.Component> this.$scope.component;
- }
- }
- };
- this.$modal.open(modalOptions);
- };
-
- private initScope = ():void => {
-
- //let self = this;
- this.$scope.sortBy = 'name';
- this.$scope.reverse = false;
- this.$scope.setValidState(true);
- this.$scope.tableHeadersList = [
- {title: 'Name', property: 'name'},
- {title: 'Type', property: 'type'},
- {title: 'Default Value', property: 'defaultValue'}
- ];
- this.$scope.sort = (sortBy:string):void => {
- this.$scope.reverse = (this.$scope.sortBy === sortBy) ? !this.$scope.reverse : false;
- this.$scope.sortBy = sortBy;
- };
-
- this.$scope.addOrUpdateAttribute = (attribute?:Models.AttributeModel):void => {
- this.openEditAttributeModal(attribute ? attribute : new Models.AttributeModel());
- };
-
- this.$scope.delete = (attribute:Models.AttributeModel):void => {
-
- let onOk = ():void => {
- this.$scope.component.deleteAttribute(attribute.uniqueId);
- };
- let title:string = this.$filter('translate')("ATTRIBUTE_VIEW_DELETE_MODAL_TITLE");
- let message:string = this.$filter('translate')("ATTRIBUTE_VIEW_DELETE_MODAL_TEXT", "{'name': '" + attribute.name + "'}");
- this.ModalsHandler.openConfirmationModal(title, message, false).then(onOk);
- };
- }
- }
-}
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/composition/composition-view-model.ts b/catalog-ui/app/scripts/view-models/workspace/tabs/composition/composition-view-model.ts
deleted file mode 100644
index f8eeaf7f64..0000000000
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/composition/composition-view-model.ts
+++ /dev/null
@@ -1,232 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-/// <reference path="../../../../references"/>
-module Sdc.ViewModels {
- 'use strict';
-
- export interface ICompositionViewModelScope extends IWorkspaceViewModelScope {
-
- currentComponent: Models.Components.Component;
- selectedComponent: Models.Components.Component;
- isLoading: boolean;
- graphApi:any;
- sharingService:Sdc.Services.SharingService;
- sdcMenu:Models.IAppMenu;
- version:string;
- isViewOnly:boolean;
- isLoadingRightPanel:boolean;
- setComponent(component: Models.Components.Component);
- isComponentInstanceSelected():boolean;
- updateSelectedComponent(): void
- openUpdateModal();
- deleteSelectedComponentInstance():void;
- onBackgroundClick():void;
- setSelectedInstance(componentInstance: Models.ComponentsInstances.ComponentInstance): void;
- printScreen():void;
-
- cacheComponentsInstancesFullData: Models.Components.Component;
- }
-
- export class CompositionViewModel {
-
- static '$inject' = [
- '$scope',
- '$log',
- 'sdcMenu',
- 'MenuHandler',
- '$modal',
- '$templateCache',
- '$state',
- 'Sdc.Services.SharingService',
- '$filter',
- 'Sdc.Services.CacheService',
- 'ComponentFactory',
- 'ChangeLifecycleStateHandler',
- 'LeftPaletteLoaderService',
- 'ModalsHandler',
- 'EventListenerService'
- ];
-
- constructor(private $scope:ICompositionViewModelScope,
- private $log: ng.ILogService,
- private sdcMenu:Models.IAppMenu,
- private MenuHandler: Utils.MenuHandler,
- private $modal:ng.ui.bootstrap.IModalService,
- private $templateCache:ng.ITemplateCacheService,
- private $state:ng.ui.IStateService,
- private sharingService:Services.SharingService,
- private $filter:ng.IFilterService,
- private cacheService:Services.CacheService,
- private ComponentFactory: Utils.ComponentFactory,
- private ChangeLifecycleStateHandler: Sdc.Utils.ChangeLifecycleStateHandler,
- private LeftPaletteLoaderService: Services.Components.LeftPaletteLoaderService,
- private ModalsHandler: Sdc.Utils.ModalsHandler,
- private eventListenerService:Services.EventListenerService) {
-
- this.$scope.setValidState(true);
- this.initScope();
- this.$scope.updateSelectedMenuItem();
- this.registerGraphEvents(this.$scope);
- }
- private cacheComponentsInstancesFullData: Array<Models.Components.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 => {
-
- this.eventListenerService.registerObserverCallback(Utils.Constants.GRAPH_EVENTS.ON_NODE_SELECTED, scope.setSelectedInstance);
- this.eventListenerService.registerObserverCallback(Utils.Constants.GRAPH_EVENTS.ON_GRAPH_BACKGROUND_CLICKED, scope.onBackgroundClick);
-
- }
- private openUpdateComponentInstanceNameModal = ():void => {
-
- let viewModelsHtmlBasePath:string = '/app/scripts/view-models/';
- let modalOptions:ng.ui.bootstrap.IModalSettings = {
- template: this.$templateCache.get(viewModelsHtmlBasePath + 'forms/resource-instance-name-form/resource-instance-name-view.html'),
- controller: 'Sdc.ViewModels.ResourceInstanceNameViewModel',
- size: 'sdc-sm',
- backdrop: 'static',
- resolve: {
- component: ():Models.Components.Component => {
- return this.$scope.currentComponent;
-
- }
- }
- };
-
- let modalInstance:ng.ui.bootstrap.IModalServiceInstance = this.$modal.open(modalOptions);
- modalInstance.result.then(():void => {
- this.eventListenerService.notifyObservers(Utils.Constants.GRAPH_EVENTS.ON_COMPONENT_INSTANCE_NAME_CHANGED, this.$scope.currentComponent.selectedInstance);
- //this.$scope.graphApi.updateNodeName(this.$scope.currentComponent.selectedInstance);
- });
- };
-
- private removeSelectedComponentInstance = ():void => {
- this.eventListenerService.notifyObservers(Utils.Constants.GRAPH_EVENTS.ON_DELETE_MULTIPLE_COMPONENTS);
- };
-
- private updateUuidMap = ():void => {
- /**
- * In case user press F5, the page is refreshed and this.sharingService.currentEntity will be undefined,
- * but after loadService or loadResource this.sharingService.currentEntity will be defined.
- * Need to update the uuidMap with the new resource or service.
- */
- this.sharingService.addUuidValue(this.$scope.currentComponent.uniqueId,this.$scope.currentComponent.uuid);
- };
-
- private initScope = ():void => {
-
- this.$scope.sharingService = this.sharingService;
- this.$scope.sdcMenu = this.sdcMenu;
- this.$scope.isLoading = false;
- this.$scope.isLoadingRightPanel = false;
- this.$scope.graphApi = {};
- this.$scope.version = this.cacheService.get('version');
- this.initComponent();
-
- this.cacheComponentsInstancesFullData = new Array<Models.Components.Component>();
-
- this.$scope.isComponentInstanceSelected = ():boolean => {
- return this.$scope.currentComponent && this.$scope.currentComponent.selectedInstance != undefined && this.$scope.currentComponent.selectedInstance != null;
- };
-
- this.$scope.updateSelectedComponent = (): void => {
- if(this.$scope.currentComponent.selectedInstance){
-
- let componentParent = _.find(this.cacheComponentsInstancesFullData, (component) => {
- return component.uniqueId === this.$scope.currentComponent.selectedInstance.componentUid;
- });
- if(componentParent) {
- this.$scope.selectedComponent = componentParent;
- }
- else {
- try {
- let onSuccess = (component:Models.Components.Component) => {
- this.$scope.isLoadingRightPanel = false;
- this.$scope.selectedComponent = component;
- this.cacheComponentsInstancesFullData.push(component);
- };
- let onError = (component:Models.Components.Component) => {
- console.log("Error updating selected component");
- this.$scope.isLoadingRightPanel = false;
- };
- this.ComponentFactory.getComponentFromServer(this.$scope.currentComponent.selectedInstance.originType, this.$scope.currentComponent.selectedInstance.componentUid).then(onSuccess, onError);
- } catch(e){
- console.log("Error updating selected component", e);
- this.$scope.isLoadingRightPanel = false;
- }
- }
- }
- else {
- this.$scope.selectedComponent = this.$scope.currentComponent;
- }
- };
-
- this.$scope.setSelectedInstance = (selectedComponent:Models.ComponentsInstances.ComponentInstance):void => {
-
- this.$log.debug('composition-view-model::onNodeSelected:: with id: '+ selectedComponent.uniqueId);
- this.$scope.currentComponent.setSelectedInstance(selectedComponent);
- this.$scope.updateSelectedComponent();
-
- if (this.$state.current.name === 'workspace.composition.api') {
- this.$state.go('workspace.composition.details');
- }
- if (this.$state.current.name === 'workspace.composition.relations' && this.$scope.currentComponent.isProduct()) {
- this.$state.go('workspace.composition.details');
- }
- };
-
- this.$scope.onBackgroundClick = ():void => {
- this.$scope.currentComponent.selectedInstance = null;
- this.$scope.selectedComponent = this.$scope.currentComponent;
-
- if (this.$state.current.name === 'workspace.composition.api') {
- this.$state.go('workspace.composition.details');
- }
- };
-
- this.$scope.openUpdateModal = ():void => {
- this.openUpdateComponentInstanceNameModal();
- };
-
- 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);
- };
-
- this.$scope.setComponent = (component: Models.Components.Product):void => {
- this.$scope.currentComponent = component;
- }
-
- }
- }
-}
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/composition/tabs/artifacts/artifacts-view-model.ts b/catalog-ui/app/scripts/view-models/workspace/tabs/composition/tabs/artifacts/artifacts-view-model.ts
deleted file mode 100644
index 5bb5d2cbbd..0000000000
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/composition/tabs/artifacts/artifacts-view-model.ts
+++ /dev/null
@@ -1,255 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../../../../../references"/>
-module Sdc.ViewModels {
- 'use strict';
- import Resource = Sdc.Models.Components.Resource;
-
- export interface IArtifactsViewModelScope extends ICompositionViewModelScope {
- artifacts: Array<Models.ArtifactModel>;
- artifactType: string;
- downloadFile:Models.IFileDownload;
- isLoading:boolean;
-
- getTitle(): string;
- addOrUpdate(artifact:Models.ArtifactModel): void;
- delete(artifact:Models.ArtifactModel): void;
- download(artifact:Models.ArtifactModel): void;
- openEditEnvParametersModal(artifact:Models.ArtifactModel):void;
- getEnvArtifact(heatArtifact:Models.ArtifactModel):any;
- getEnvArtifactName(artifact:Models.ArtifactModel):string;
- isLicenseArtifact(artifact:Models.ArtifactModel):boolean;
- isVFiArtifact(artifact:Models.ArtifactModel):boolean;
- }
-
- export class ResourceArtifactsViewModel {
-
- static '$inject' = [
- '$scope',
- '$filter',
- '$modal',
- '$templateCache',
- '$state',
- 'sdcConfig',
- 'ArtifactsUtils',
- 'ModalsHandler',
- 'Sdc.Services.CacheService'
- ];
-
- constructor(private $scope:IArtifactsViewModelScope,
- private $filter:ng.IFilterService,
- private $modal:ng.ui.bootstrap.IModalService,
- private $templateCache:ng.ITemplateCacheService,
- private $state:any,
- private sdcConfig:Models.IAppConfigurtaion,
- private artifactsUtils:Sdc.Utils.ArtifactsUtils,
- private ModalsHandler: Utils.ModalsHandler,
- private cacheService:Services.CacheService) {
-
- this.initScope();
- }
-
-
- private initArtifactArr = (artifactType:string):void => {
- let artifacts:Array<Models.ArtifactModel> = [];
-
- if (this.$scope.selectedComponent) {
- if ('interface' == artifactType) {
- let interfaces = this.$scope.selectedComponent.interfaces;
- if (interfaces && interfaces.standard && interfaces.standard.operations) {
-
- angular.forEach(interfaces.standard.operations, (operation:any, interfaceName:string):void => {
- let item:Sdc.Models.ArtifactModel = <Sdc.Models.ArtifactModel>{};
- if (operation.implementation) {
- item = <Sdc.Models.ArtifactModel> operation.implementation;
- }
- item.artifactDisplayName = interfaceName;
- item.artifactLabel = interfaceName;
- item.mandatory = false;
- artifacts.push(item);
- });
- }
- }else {
- //init normal artifacts, deployment or api artifacts
- let artifactsObj:Models.ArtifactGroupModel;
- switch (artifactType) {
- case "api":
- artifactsObj = (<Models.Components.Service>this.$scope.selectedComponent).serviceApiArtifacts;
- break;
- case "deployment":
- if (!this.$scope.isComponentInstanceSelected()) {
- artifactsObj = this.$scope.selectedComponent.deploymentArtifacts;
- } else {
- artifactsObj = this.$scope.currentComponent.selectedInstance.deploymentArtifacts;
- }
- break;
- default:
- artifactsObj = this.$scope.selectedComponent.artifacts;
- break;
- }
- _.forEach(artifactsObj, (artifact:Models.ArtifactModel, key) => {
- artifacts.push(artifact);
- });
- }
- }
- this.$scope.artifacts = artifacts;
- };
-
- private openEditArtifactModal = (artifact:Models.ArtifactModel):void => {
- let viewModelsHtmlBasePath:string = '/app/scripts/view-models/';
-
- let modalOptions:ng.ui.bootstrap.IModalSettings = {
- template: this.$templateCache.get(viewModelsHtmlBasePath + 'forms/artifact-form/artifact-form-view.html'),
- controller: 'Sdc.ViewModels.ArtifactResourceFormViewModel',
- size: 'sdc-md',
- backdrop: 'static',
- keyboard: false,
- resolve: {
- artifact: ():Models.ArtifactModel => {
- return artifact;
- },
- component: (): Models.Components.Component => {
- return this.$scope.currentComponent;
- }
- }
- };
-
- let modalInstance:ng.ui.bootstrap.IModalServiceInstance = this.$modal.open(modalOptions);
- modalInstance
- .result
- .then(():void => {
- this.initArtifactArr(this.$scope.artifactType);
- });
- };
-
- private initScope = ():void => {
- let self = this;
- this.$scope.isLoading= false;
- this.$scope.artifactType = this.artifactsUtils.getArtifactTypeByState(this.$state.current.name);
- this.initArtifactArr(this.$scope.artifactType);
-
- this.$scope.getTitle = ():string => {
- return this.artifactsUtils.getTitle(this.$scope.artifactType, this.$scope.selectedComponent);
- };
-
- let vfiArtifactTypes:any = this.cacheService.get('UIConfiguration').artifacts.deployment.resourceInstanceDeploymentArtifacts;
-
- this.$scope.isVFiArtifact=(artifact:Models.ArtifactModel):boolean=>{
- return vfiArtifactTypes[artifact.artifactType];
- }
-
- this.$scope.$watch('selectedComponent', (newResource:Models.Components.Component):void => {
- if (newResource) {
- this.initArtifactArr(this.$scope.artifactType);
- }
- });
-
-
- this.$scope.$watch('currentComponent.selectedInstance', (newInstance:Models.ComponentsInstances.ComponentInstance):void => {
- if (newInstance) {
- this.initArtifactArr(this.$scope.artifactType);
- }
- });
-
- this.$scope.addOrUpdate = (artifact:Models.ArtifactModel):void => {
- this.artifactsUtils.setArtifactType(artifact, this.$scope.artifactType);
- let artifactCopy = new Models.ArtifactModel(artifact);
- this.openEditArtifactModal(artifactCopy);
- };
-
-
- this.$scope.delete = (artifact:Models.ArtifactModel):void => {
-
- let onOk = ():void => {
- this.$scope.isLoading= true;
- this.artifactsUtils.removeArtifact(artifact, this.$scope.artifacts);
-
- let success = (responseArtifact:Models.ArtifactModel):void => {
- this.initArtifactArr(this.$scope.artifactType);
- this.$scope.isLoading= false;
- };
-
- let error =(error:any):void =>{
- console.log('Delete artifact returned error:', error);
- this.initArtifactArr(this.$scope.artifactType);
- this.$scope.isLoading= false;
- };
- if(this.$scope.isComponentInstanceSelected()){
- this.$scope.currentComponent.deleteInstanceArtifact(artifact.uniqueId, artifact.artifactLabel).then(success, error);
- }else{
- this.$scope.currentComponent.deleteArtifact(artifact.uniqueId, artifact.artifactLabel).then(success, error);//TODO simulate error (make sure error returns)
- }
- };
- let title: string = this.$filter('translate')("ARTIFACT_VIEW_DELETE_MODAL_TITLE");
- let message: string = this.$filter('translate')("ARTIFACT_VIEW_DELETE_MODAL_TEXT", "{'name': '" + artifact.artifactDisplayName + "'}");
- this.ModalsHandler.openConfirmationModal(title, message, false).then(onOk);
- };
-
-
- this.$scope.getEnvArtifact = (heatArtifact:Models.ArtifactModel):any=>{
- return _.find(this.$scope.artifacts, (item:Models.ArtifactModel)=>{
- return item.generatedFromId === heatArtifact.uniqueId;
- });
- };
-
- this.$scope.getEnvArtifactName = (artifact:Models.ArtifactModel):string =>{
- let envArtifact = this.$scope.getEnvArtifact(artifact);
- if(envArtifact){
- return envArtifact.artifactDisplayName;
- }
- };
-
- this.$scope.isLicenseArtifact = (artifact:Models.ArtifactModel) :boolean => {
- let isLicense:boolean = false;
- if(this.$scope.component.isResource() && (<Resource>this.$scope.component).isCsarComponent()) {
- isLicense = this.artifactsUtils.isLicenseType(artifact.artifactType);
- }
-
- return isLicense;
- };
-
- this.$scope.openEditEnvParametersModal = (artifact:Models.ArtifactModel):void => {
-
- let modalOptions:ng.ui.bootstrap.IModalSettings = {
- template: this.$templateCache.get('/app/scripts/view-models/forms/env-parameters-form/env-parameters-form.html'),
- controller: 'Sdc.ViewModels.EnvParametersFormViewModel',
- size: 'sdc-md',
- backdrop: 'static',
- resolve: {
- artifact: ():Models.ArtifactModel => {
- return artifact;
- },
- component: (): Models.Components.Component => {
- return this.$scope.currentComponent;
- }
- }
- };
-
- let modalInstance:ng.ui.bootstrap.IModalServiceInstance = this.$modal.open(modalOptions);
- modalInstance
- .result
- .then(():void => {
- this.initArtifactArr(this.$scope.artifactType);
- });
- };
-
- }
- }
-}
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/composition/tabs/details/details-view-model.ts b/catalog-ui/app/scripts/view-models/workspace/tabs/composition/tabs/details/details-view-model.ts
deleted file mode 100644
index b28de8d331..0000000000
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/composition/tabs/details/details-view-model.ts
+++ /dev/null
@@ -1,132 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../../../../../references"/>
-module Sdc.ViewModels {
-
- 'use strict';
-
- export interface IEditResourceVersion {
- allVersions: any;
- changeVersion: string;
- }
-
- interface IDetailsViewModelScope extends ICompositionViewModelScope {
- isLoading: boolean;
- $parent: ICompositionViewModelScope;
- expandedSection: Array<string>;
- editForm:ng.IFormController;
- editResourceVersion: IEditResourceVersion;
-
- changeResourceVersion(): void;
- }
-
- export class DetailsViewModel {
-
- static '$inject' = [
- '$scope',
- 'LeftPaletteLoaderService',
- 'EventListenerService'
-
- ];
-
- constructor(private $scope:IDetailsViewModelScope,
- private LeftPaletteLoaderService:Services.Components.LeftPaletteLoaderService,
- private eventListenerService:Services.EventListenerService) {
- this.initScope();
- }
-
- private clearSelectedVersion = ():void => {
- this.$scope.editResourceVersion = {
- allVersions: {},
- changeVersion: null
- };
- };
-
- private versioning:Function = (versionNumber:string):string => {
- let version:Array<string> = versionNumber.split('.');
- return '00000000'.slice(version[0].length) + version[0] + '.' + '00000000'.slice(version[1].length) + version[1];
- };
-
- private initEditResourceVersion = ():void => {
- this.clearSelectedVersion();
- this.$scope.editResourceVersion.allVersions[this.$scope.currentComponent.selectedInstance.componentVersion] = this.$scope.currentComponent.selectedInstance.componentUid;
- _.merge(this.$scope.editResourceVersion.allVersions, angular.copy(this.$scope.selectedComponent.allVersions));
- let sorted:any= _.sortBy(_.toPairs(this.$scope.editResourceVersion.allVersions), (item)=>{
- return this.versioning(item[0]);
- });
- this.clearSelectedVersion();
- _.forEach(sorted, (item)=> {
- this.$scope.editResourceVersion.allVersions[item[0]]= item[1];
- });
-
- let highestVersion = _.last(Object.keys(this.$scope.selectedComponent.allVersions));
-
- //TODO - ask ronny - what happend if the parent is not in the leftPalette (instance of csar for example)
- if (parseFloat(highestVersion) % 1) { //if highest is minor, make sure it is the latest checked in -
- let latestVersionComponent:Models.Components.Component = _.find(this.LeftPaletteLoaderService.getFullDataComponentListWithVls(this.$scope.currentComponent.componentType), (component:Models.Components.Component) => { //latest checked in
- return (component.systemName === this.$scope.selectedComponent.systemName
- || component.uuid === this.$scope.selectedComponent.uuid);
- });
- let latestVersion:string = latestVersionComponent ? latestVersionComponent.version : highestVersion;
-
- if (highestVersion != latestVersion) { //highest is checked out - remove from options
- this.$scope.editResourceVersion.allVersions = _.omit(this.$scope.editResourceVersion.allVersions, highestVersion);
- }
- }
- this.$scope.editResourceVersion.changeVersion = this.$scope.currentComponent.selectedInstance.componentVersion;
- };
-
- private initScope = ():void => {
- this.$scope.isLoading = false;
- this.$scope.$parent.isLoading = false;
- this.$scope.expandedSection = ['general', 'tags'];
- //this.clearSelectedVersion();
-
- this.$scope.$watch('selectedComponent', (component:Models.Components.Component) => {
- if (this.$scope.isComponentInstanceSelected()) {
- this.initEditResourceVersion();
- }
- });
-
- this.$scope.changeResourceVersion = ():void => {
- this.$scope.isLoading = true;
- this.$scope.$parent.isLoading = true;
-
- let onSuccess = (component:Models.Components.Component)=> {
- this.$scope.isLoading = false;
- this.$scope.$parent.isLoading = false;
- this.$scope.setComponent(component);
- this.$scope.updateSelectedComponent();
-
- this.eventListenerService.notifyObservers(Sdc.Utils.Constants.GRAPH_EVENTS.ON_VERSION_CHANGED, this.$scope.currentComponent);
- };
-
- let onFailed = (error:any)=> {
- this.$scope.isLoading = false;
- this.$scope.$parent.isLoading = false;
- console.log(error);
- };
-
- let componentUid:string = this.$scope.editResourceVersion.allVersions[this.$scope.editResourceVersion.changeVersion];
- this.$scope.currentComponent.changeComponentInstanceVersion(componentUid).then(onSuccess, onFailed);
- };
- }
- }
-}
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/composition/tabs/properties-and-attributes/properties-view-model.ts b/catalog-ui/app/scripts/view-models/workspace/tabs/composition/tabs/properties-and-attributes/properties-view-model.ts
deleted file mode 100644
index aef25c51ce..0000000000
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/composition/tabs/properties-and-attributes/properties-view-model.ts
+++ /dev/null
@@ -1,228 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../../../../../references"/>
-module Sdc.ViewModels {
- 'use strict';
-
- interface IResourcePropertiesAndAttributesViewModelScope extends ICompositionViewModelScope {
- properties: Models.PropertiesGroup;
- attributes: Models.AttributesGroup;
- propertiesMessage: string;
- addProperty(): void;
- updateProperty(property:Models.PropertyModel): void;
- deleteProperty(property:Models.PropertyModel): void;
- viewAttribute(attribute:Models.AttributeModel): void;
- groupNameByKey(key:string): string;
- isPropertyOwner():boolean;
- }
-
- export class ResourcePropertiesViewModel {
-
- static '$inject' = [
- '$scope',
- '$filter',
- '$modal',
- '$templateCache',
- 'ModalsHandler'
- ];
-
-
- constructor(private $scope:IResourcePropertiesAndAttributesViewModelScope,
- private $filter:ng.IFilterService,
- private $modal:ng.ui.bootstrap.IModalService,
- private $templateCache:ng.ITemplateCacheService,
- private ModalsHandler: Utils.ModalsHandler) {
-
- this.initScope();
- }
-
- private initComponentProperties = ():void => {
- let result:Models.PropertiesGroup = {};
-
- if(this.$scope.selectedComponent){
- this.$scope.propertiesMessage = undefined;
- if(this.$scope.isComponentInstanceSelected()){
- if (this.$scope.currentComponent.selectedInstance.originType==='VF') {
- // Temporally fix to hide properties for VF (UI stack when there are many properties)
- this.$scope.propertiesMessage = "Note: properties for VF are disabled";
- } else {
- result[this.$scope.currentComponent.selectedInstance.uniqueId] = this.$scope.currentComponent.componentInstancesProperties[this.$scope.currentComponent.selectedInstance.uniqueId];
- }
- }else if(this.$scope.currentComponent.isService()){
- // Temporally fix to hide properties for service (UI stack when there are many properties)
- //result = this.$scope.currentComponent.componentInstancesProperties;
- this.$scope.propertiesMessage = "Note: properties for service are disabled";
- }else{
- let key = this.$scope.selectedComponent.uniqueId;
- result[key]= Array<Models.PropertyModel>();
- let derived = Array<Models.PropertyModel>();
- _.forEach(this.$scope.selectedComponent.properties, (property:Models.PropertyModel) => {
- if(key == property.parentUniqueId){
- result[key].push(property);
- }else{
- property.readonly = true;
- derived.push(property);
- }
- });
- if(derived.length){
- result['derived']= derived;
- }
- }
- this.$scope.properties = result;
- }
- };
-
-
- private initComponentAttributes = ():void => {
- let result:Models.AttributesGroup = {};
-
- if(this.$scope.selectedComponent){
- if(this.$scope.isComponentInstanceSelected()){
- result[this.$scope.currentComponent.selectedInstance.uniqueId] = this.$scope.currentComponent.componentInstancesAttributes[this.$scope.currentComponent.selectedInstance.uniqueId];
- }else if(this.$scope.currentComponent.isService()){
- result = this.$scope.currentComponent.componentInstancesAttributes;
- }
- this.$scope.attributes = result;
- }
- };
-
- private openEditPropertyModal = (property:Models.PropertyModel):void => {
- let viewModelsHtmlBasePath:string = '/app/scripts/view-models/';
-
- let modalOptions:ng.ui.bootstrap.IModalSettings = {
- template: this.$templateCache.get(viewModelsHtmlBasePath + 'forms/property-form/property-form-view.html'),
- controller: 'Sdc.ViewModels.PropertyFormViewModel',
- size: 'sdc-l',
- backdrop: 'static',
- keyboard: false,
- resolve: {
- property: ():Models.PropertyModel => {
- return property;
- },
- component: ():Models.Components.Component => {
- return this.$scope.currentComponent;
- },
- filteredProperties: ():Array<Models.PropertyModel> => {
- return this.$scope.selectedComponent.properties
- }
- }
- };
-
-
- let modalInstance:ng.ui.bootstrap.IModalServiceInstance = this.$modal.open(modalOptions);
- modalInstance
- .result
- .then(():void => {
- // this.initComponentProperties();
- });
- };
-
- private openAttributeModal = (atrribute:Models.AttributeModel):void => {
- let viewModelsHtmlBasePath:string = '/app/scripts/view-models/';
-
- let modalOptions:ng.ui.bootstrap.IModalSettings = {
- template: this.$templateCache.get(viewModelsHtmlBasePath + 'forms/attribute-form/attribute-form-view.html'),
- controller: 'Sdc.ViewModels.AttributeFormViewModel',
- size: 'sdc-md',
- backdrop: 'static',
- keyboard: false,
- resolve: {
- attribute: ():Models.AttributeModel => {
- return atrribute;
- },
- component: ():Models.Components.Component => {
- return this.$scope.currentComponent;
- }
- }
- };
- this.$modal.open(modalOptions);
- };
-
-
-
-
- private initScope = ():void => {
- this.initComponentProperties();
- this.initComponentAttributes();
-
- this.$scope.$watchCollection('currentComponent.componentInstancesProperties', (newData:any):void => {
- this.initComponentProperties();
- });
-
- this.$scope.$watchCollection('currentComponent.properties', (newData:any):void => {
- this.initComponentProperties();
- });
-
- this.$scope.$watch('currentComponent.selectedInstance', (newInstance:Models.ComponentsInstances.ComponentInstance):void => {
- if (angular.isDefined(newInstance)) {
- this.initComponentProperties();
- this.initComponentAttributes();
- }
- });
-
- this.$scope.$watchCollection('currentComponent.componentInstancesAttributes', (newData:any):void => {
- this.initComponentAttributes();
- });
-
- this.$scope.isPropertyOwner = ():boolean => {
- return this.$scope.currentComponent && this.$scope.currentComponent.isResource() &&
- !this.$scope.isComponentInstanceSelected();
- };
-
- this.$scope.addProperty = ():void => {
- let property = new Models.PropertyModel();
- this.openEditPropertyModal(property);
- };
-
- this.$scope.updateProperty = (property:Models.PropertyModel):void => {
- this.openEditPropertyModal(property);
- };
-
- this.$scope.deleteProperty = (property:Models.PropertyModel):void => {
-
- let onOk = ():void => {
- this.$scope.currentComponent.deleteProperty(property.uniqueId);
- };
-
- let title:string = this.$filter('translate')("PROPERTY_VIEW_DELETE_MODAL_TITLE");
- let message:string = this.$filter('translate')("PROPERTY_VIEW_DELETE_MODAL_TEXT", "{'name': '" + property.name + "'}");
- this.ModalsHandler.openConfirmationModal(title, message, false).then(onOk);
- };
-
- this.$scope.viewAttribute = (attribute:Models.AttributeModel):void => {
- this.openAttributeModal(attribute);
- };
-
- this.$scope.groupNameByKey = (key:string):string => {
- switch (key){
- case 'derived':
- return "Derived";
-
- case this.$scope.currentComponent.uniqueId:
- return this.$filter("resourceName")(this.$scope.currentComponent.name);
-
- default:
- return this.$filter("resourceName")((_.find(this.$scope.currentComponent.componentInstances, {uniqueId:key})).name);
- }
- };
-
- }
- }
-}
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/composition/tabs/relations/relations-view-model.ts b/catalog-ui/app/scripts/view-models/workspace/tabs/composition/tabs/relations/relations-view-model.ts
deleted file mode 100644
index 119a59d5af..0000000000
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/composition/tabs/relations/relations-view-model.ts
+++ /dev/null
@@ -1,81 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../../../../../references"/>>
-module Sdc.ViewModels {
- 'use strict';
-
- interface IRelationsViewModelScope extends ICompositionViewModelScope {
- isLoading: boolean;
- $parent: ICompositionViewModelScope;
- getRelation(requirement:any): any;
- }
-
- export class RelationsViewModel {
-
- static '$inject' = [
- '$scope',
- '$filter'
- ];
-
- constructor(private $scope:IRelationsViewModelScope,
- private $filter:ng.IFilterService) {
- this.initScope();
- }
-
-
- private updateRC = ():void =>{
- if(this.$scope.currentComponent) {
- this.$scope.currentComponent.updateRequirementsCapabilities();
- }
- };
-
- private initScope = ():void => {
-
- this.$scope.isLoading = this.$scope.$parent.isLoading;
-
- this.$scope.getRelation = (requirement:any):any => {
-
- if(this.$scope.isComponentInstanceSelected() && this.$scope.currentComponent.componentInstancesRelations ) {
- let relationItem = _.filter(this.$scope.currentComponent.componentInstancesRelations, (relation:any) => {
- return relation.fromNode === this.$scope.currentComponent.selectedInstance.uniqueId &&
- _.some(relation.relationships, {'requirement': requirement.name,
- 'requirementOwnerId': requirement.ownerId});
- });
-
- if (relationItem && relationItem.length) {
- return {
- type: requirement.relationship.split('.').pop(),
- requirementName: this.$filter('resourceName')(this.$scope.currentComponent.componentInstances[_.map
- (this.$scope.currentComponent.componentInstances, "uniqueId").indexOf(relationItem[0].toNode)].name)
- };
- }
- }
- return null;
- };
-
- if(!this.$scope.isComponentInstanceSelected()) {
- this.$scope.$watch('currentComponent.componentInstances + currentComponent.componentInstancesRelations', ():void => {
- this.updateRC();
- });
-
- }
- }
- }
-}
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/composition/tabs/relations/relations-view.html b/catalog-ui/app/scripts/view-models/workspace/tabs/composition/tabs/relations/relations-view.html
deleted file mode 100644
index 72eaae27cf..0000000000
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/composition/tabs/relations/relations-view.html
+++ /dev/null
@@ -1,57 +0,0 @@
-<perfect-scrollbar class="w-sdc-designer-sidebar-tab-content relations">
-
- <div class="w-sdc-designer-sidebar-section w-sdc-designer-sidebar-section-relations">
- <expand-collapse expanded-selector=".w-sdc-designer-sidebar-section-content.capabilities" class="w-sdc-designer-sidebar-section-title">
- Capabilities
- <div class="w-sdc-designer-sidebar-section-title-icon"></div>
- </expand-collapse>
-
- <div class="w-sdc-designer-sidebar-section-content capabilities">
- <div class="i-sdc-designer-sidebar-section-content-item">
- <div class="i-sdc-designer-sidebar-section-content-item-relations-group" data-ng-repeat="(key, value) in (isComponentInstanceSelected() ? currentComponent.selectedInstance.capabilities : selectedComponent.capabilities) track by $index">
- <div class="i-sdc-designer-sidebar-section-content-item-relations" data-ng-repeat="capability in value track by $index">
- <div class="i-sdc-designer-sidebar-section-content-item-relations-details">
- <div class="i-sdc-designer-sidebar-section-content-item-relations-details-name">{{capability.name}}&nbsp;
- <span ng-if="selectedComponent.isComplex() && capability.ownerName"
- class="i-sdc-designer-sidebar-section-content-item-relations-details-ownerName"
- tooltips tooltip-class="tooltip-custom break-word-tooltip"
- tooltip-content="{{capability.ownerName | resourceName}}">&nbsp;&nbsp;{{capability.ownerName | resourceName}}</span></div>
- <div class="i-sdc-designer-sidebar-section-content-item-relations-details-desc">{{capability.type}}</div>
- </div></div>
- </div>
- </div>
- </div>
- </div>
-
- <div class="w-sdc-designer-sidebar-section w-sdc-designer-sidebar-section-relations">
- <expand-collapse expanded-selector=".w-sdc-designer-sidebar-section-content.requirements" class="w-sdc-designer-sidebar-section-title">
- Requirements
- <div class="w-sdc-designer-sidebar-section-title-icon"></div>
- </expand-collapse>
-
- <div class="w-sdc-designer-sidebar-section-content requirements">
- <div class="i-sdc-designer-sidebar-section-content-item">
- <div class="i-sdc-designer-sidebar-section-content-item-relations-group" data-ng-repeat="(key, value) in (isComponentInstanceSelected() ? currentComponent.selectedInstance.requirements : selectedComponent.requirements) track by $index">
- <div class="i-sdc-designer-sidebar-section-content-item-relations" data-ng-repeat="requirement in value track by $index">
- <div class="i-sdc-designer-sidebar-section-content-item-relations-details">
- <div class="i-sdc-designer-sidebar-section-content-item-relations-details-name">{{requirement.name}}&nbsp;
- <span ng-if="selectedComponent.isComplex() && requirement.ownerName"
- class="i-sdc-designer-sidebar-section-content-item-relations-details-ownerName"
- tooltips tooltip-class="tooltip-custom break-word-tooltip"
- tooltip-content="{{requirement.ownerName | resourceName}}">&nbsp;&nbsp;{{requirement.ownerName | resourceName}}</span></div>
- <div class="i-sdc-designer-sidebar-section-content-item-relations-details-desc">{{requirement.node}}
- <div data-ng-if="getRelation(requirement) != null">
- <div class="i-sdc-designer-sidebar-section-content-item-relations-details-indent-box"></div>
- <div class="i-sdc-designer-sidebar-section-content-item-relations-details-child">
- <span class="i-sdc-designer-sidebar-section-content-item-relations-details-desc">{{getRelation(requirement).type}} <br/></span>
- <span class="i-sdc-designer-sidebar-section-content-item-relations-details-name">{{getRelation(requirement).requirementName}}</span>
- </div>
- </div>
- </div>
- </div></div>
- </div>
- </div>
- </div>
- </div>
-
-</perfect-scrollbar>
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/composition/tabs/structure/structure-view.ts b/catalog-ui/app/scripts/view-models/workspace/tabs/composition/tabs/structure/structure-view.ts
deleted file mode 100644
index daeab7f2f3..0000000000
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/composition/tabs/structure/structure-view.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../../../../../references"/>
-module Sdc.ViewModels {
- 'use strict';
-
- interface IStructureViewModel extends ICompositionViewModelScope {}
-
- export class StructureViewModel {
- static '$inject' = [
- '$scope'
- ];
-
- constructor(private $scope:IStructureViewModel) {
- }
- }
- }
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts-view-model.ts b/catalog-ui/app/scripts/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts-view-model.ts
deleted file mode 100644
index 43511e2deb..0000000000
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts-view-model.ts
+++ /dev/null
@@ -1,253 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../../../references"/>
-module Sdc.ViewModels {
- 'use strict';
- import Resource = Sdc.Models.Components.Resource;
- import ArtifactModel = Sdc.Models.ArtifactModel;
-
- interface IDeploymentArtifactsViewModelScope extends IWorkspaceViewModelScope {
- tableHeadersList: Array<any>;
- reverse: boolean;
- sortBy:string;
- artifacts: Array<Models.ArtifactModel>;
- editForm:ng.IFormController;
- isLoading:boolean;
- artifactDescriptions:any;
- updateInProgress:boolean;
-
- addOrUpdate(artifact:Models.ArtifactModel): void;
- update(artifact:Models.ArtifactModel): void;
- delete(artifact:Models.ArtifactModel): void;
- sort(sortBy:string): void;
- noArtifactsToShow():boolean;
- getValidationPattern(validationType:string, parameterType?:string):RegExp;
- validateJson(json:string):boolean;
- resetValue(parameter:any):void;
- viewModeOrCsarComponent():boolean;
- isLicenseArtifact(artifact:Models.ArtifactModel): boolean;
-
- }
-
- export class DeploymentArtifactsViewModel {
-
- static '$inject' = [
- '$scope',
- '$filter',
- '$modal',
- '$templateCache',
- 'ValidationUtils',
- 'ArtifactsUtils',
- 'ModalsHandler'
- ];
-
- constructor(private $scope:IDeploymentArtifactsViewModelScope,
- private $filter:ng.IFilterService,
- private $modal:ng.ui.bootstrap.IModalService,
- private $templateCache:ng.ITemplateCacheService,
- private validationUtils:Sdc.Utils.ValidationUtils,
- private artifactsUtils:Sdc.Utils.ArtifactsUtils,
- private ModalsHandler:Utils.ModalsHandler) {
- this.initScope();
- this.$scope.updateSelectedMenuItem();
- }
-
- private initDescriptions = ():void => {
- this.$scope.artifactDescriptions = {};
- _.forEach(this.$scope.component.deploymentArtifacts, (artifact:Models.ArtifactModel):void => {
- this.$scope.artifactDescriptions[artifact.artifactLabel] = artifact.description;
- });
- };
-
-
- private setArtifact = (artifact:Models.ArtifactModel):void => {
- if (artifact.heatParameters) {
- artifact.heatParameters.forEach((parameter:any):void => {
- if (!parameter.currentValue && parameter.defaultValue) {
- parameter.currentValue = parameter.defaultValue;
- } else if ("" === parameter.currentValue) {
- parameter.currentValue = null;
- }
- });
- }
- if (!artifact.description || !this.$scope.getValidationPattern('string').test(artifact.description)) {
- artifact.description = this.$scope.artifactDescriptions[artifact.artifactLabel];
- }
- };
-
- private updateAll = ():void => {
- let artifacts:Array<Models.ArtifactModel> = [];
- _.forEach(this.$scope.component.deploymentArtifacts, (artifact:Models.ArtifactModel):void => {
- if (artifact.selected) {
- this.setArtifact(artifact);
- artifacts.push(artifact);
- }
- });
- this.$scope.component.updateMultipleArtifacts(artifacts);
- };
-
-
- private initScope = ():void => {
- let self = this;
- this.$scope.isLoading = false;
- this.$scope.updateInProgress = false;
- this.initDescriptions();
- this.$scope.artifacts = <ArtifactModel[]>_.values(this.$scope.component.deploymentArtifacts);
- this.$scope.setValidState(true);
-
- this.$scope.tableHeadersList = [
- {title: 'Name', property: 'artifactDisplayName'},
- {title: 'Type', property: 'artifactType'},
- {title: 'Deployment timeout', property: 'timeout'}
- ];
-
- this.$scope.isLicenseArtifact = (artifact:Models.ArtifactModel) :boolean => {
- let isLicense:boolean = false;
- if(this.$scope.component.isResource() && (<Resource>this.$scope.component).isCsarComponent()) {
-
- isLicense = this.artifactsUtils.isLicenseType(artifact.artifactType);
- }
-
- return isLicense;
- };
-
- this.$scope.sort = (sortBy:string):void => {
- this.$scope.reverse = (this.$scope.sortBy === sortBy) ? !this.$scope.reverse : false;
- this.$scope.sortBy = sortBy;
- };
-
- this.$scope.getValidationPattern = (validationType:string, parameterType?:string):RegExp => {
- return this.validationUtils.getValidationPattern(validationType, parameterType);
- };
-
- this.$scope.validateJson = (json:string):boolean => {
- if(!json){
- return true;
- }
- return this.validationUtils.validateJson(json);
- };
-
- this.$scope.viewModeOrCsarComponent = ():boolean => {
- return this.$scope.isViewMode() || (this.$scope.component.isResource() && (<Resource>this.$scope.component).isCsarComponent());
- };
-
-
- this.$scope.addOrUpdate = (artifact:Models.ArtifactModel):void => {
- artifact.artifactGroupType = 'DEPLOYMENT';
- let artifactCopy = new Models.ArtifactModel(artifact);
-
- let success = (response:any):void => {
- self.$scope.artifactDescriptions[artifactCopy.artifactLabel] = artifactCopy.description;
- self.$scope.artifacts = <ArtifactModel[]>_.values(self.$scope.component.deploymentArtifacts);
- };
-
- let error = (err:any):void =>{
- console.log(err);
- self.$scope.artifacts = <ArtifactModel[]>_.values(self.$scope.component.deploymentArtifacts);
- };
-
-
- this.ModalsHandler.openWizardArtifactModal(artifactCopy, self.$scope.component).then(success, error);
- };
-
- this.$scope.noArtifactsToShow = ():boolean => {
- return !_.some(this.$scope.artifacts, 'esId');
- };
-
-
- this.$scope.resetValue = (parameter:any):void => {
- if (!parameter.currentValue && parameter.defaultValue) {
- parameter.currentValue = parameter.defaultValue;
- }
- else if ('boolean' == parameter.type) {
- parameter.currentValue = parameter.currentValue.toUpperCase();
- }
- };
-
-
- this.$scope.$watch('editForm.$valid', ():void => {
- if (this.$scope.editForm) {
- // this.$scope.setValidState(this.$scope.editForm.$valid);
- }
- });
-
- this.$scope.update = (artifact:Models.ArtifactModel):void => {
- if (false == this.$scope.isLoading) {
- if (artifact.selected && !this.$scope.isViewMode()) {
- this.$scope.isLoading = true;
- this.$scope.updateInProgress = true;
- let onSuccess = (responseArtifact:Models.ArtifactModel):void => {
- this.$scope.artifactDescriptions[responseArtifact.artifactLabel] = responseArtifact.description;
- this.$scope.artifacts = <ArtifactModel[]>_.values(this.$scope.component.deploymentArtifacts);
- this.$scope.isLoading = false;
- artifact.selected = !artifact.selected;
- this.$scope.updateInProgress = false;
- };
-
- let onFailed = (error:any):void => {
- console.log('Delete artifact returned error:', error);
- this.$scope.isLoading = false;
- artifact.selected = !artifact.selected;
- this.$scope.updateInProgress = false;
- };
-
- this.setArtifact(artifact);
- this.$scope.component.addOrUpdateArtifact(artifact).then(onSuccess, onFailed);
- } else {
- artifact.selected = !artifact.selected;
-
- }
- }
- };
-
- this.$scope.delete = (artifact:Models.ArtifactModel):void => {
- let onOk = ():void => {
- this.$scope.isLoading = true;
- let onSuccess = ():void => {
- this.$scope.isLoading = false;
- this.$scope.artifacts = <ArtifactModel[]>_.values(this.$scope.component.deploymentArtifacts);
- };
-
- let onFailed = (error:any):void => {
- this.$scope.isLoading = false;
- console.log('Delete artifact returned error:', error);
- };
-
- this.$scope.component.deleteArtifact(artifact.uniqueId, artifact.artifactLabel).then(onSuccess, onFailed);
- };
-
- let title:string = self.$filter('translate')("ARTIFACT_VIEW_DELETE_MODAL_TITLE");
- let message:string = self.$filter('translate')("ARTIFACT_VIEW_DELETE_MODAL_TEXT", "{'name': '" + artifact.artifactDisplayName + "'}");
- this.ModalsHandler.openConfirmationModal(title, message, false).then(onOk);
- };
- };
-
- public save = (callback:Function):void => {
- this.updateAll();
- this.$scope.setComponent(this.$scope.component);
- callback(true);
- };
-
- public back = (callback:Function):void => {
- this.$scope.setComponent(this.$scope.component);
- callback(true);
- }
- }
-}
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts-view.html b/catalog-ui/app/scripts/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts-view.html
deleted file mode 100644
index 1547618134..0000000000
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts-view.html
+++ /dev/null
@@ -1,149 +0,0 @@
-<div class="workspace-deployment-artifact">
-
- <div data-tests-id="add-deployment-artifact-button" ng-if="!isViewMode()" data-ng-class="{'disabled': isDisableMode()}" data-tests-id="add-property-button" class="add-btn" data-ng-click="addOrUpdate({})">Add</div>
-
- <div class="table-container-flex">
-
- <div class="table" data-ng-class="{'view-mode': isViewMode()}">
- <loader data-display="isLoading"></loader>
- <div class="head flex-container">
- <div class="table-header head-row hand flex-item" data-ng-repeat="header in tableHeadersList track by $index" data-ng-click="sort(header.property)">{{header.title}}
- <span data-ng-if="sortBy === header.property" class="table-header-sort-arrow" data-ng-class="{'down': reverse, 'up':!reverse}"> </span>
- </div>
- <div class="table-no-text-header head-row flex-item"></div>
- </div>
-
- <form class="body" name="editForm">
-
- <perfect-scrollbar scroll-y-margin-offset="0" include-padding="true" class="scrollbar-container">
-
- <!-- Artifact row -->
- <div ng-if="noArtifactsToShow()" data-ng-class="{'disabled': isDisableMode()}" class="no-row-text" translate="DEPLOYMENT_ARTIFACT_NO_ARTIFACTS_TO_DISPLAY"></div>
- <div data-ng-repeat-start="artifact in artifacts | orderBy:sortBy:reverse track by $index"
- class="flex-container data-row"
- data-ng-class="{'selected': artifact.selected || undefined==artifact.selected && updateInProgress}"
- data-ng-if="artifact.esId">
-
- <div class="table-col-general flex-item" data-ng-click="update(artifact)">
-
- <span class="sprite table-arrow" data-tests-id="{{artifact.artifactDisplayName}}" data-ng-class="{'opened': artifact.selected || undefined==artifact.selected && updateInProgress}"></span>
- {{artifact.artifactDisplayName}}
- </div>
-
- <div class="table-col-general flex-item" data-tests-id="{{artifact.artifactType}}">
- {{artifact.artifactType}}
- </div>
- <div class="table-col-general flex-item" data-tests-id="{{artifact.timeout}}">
- {{artifact.timeout? artifact.timeout:''}}
- </div>
-
- <div class="table-btn-col flex-item">
- <button class="table-edit-btn" data-tests-id="edit_{{artifact.artifactDisplayName}}"
- data-ng-if="!isViewMode() && !artifact.isHEAT() && !artifact.isThirdParty() && !isLicenseArtifact(artifact)" data-ng-click="addOrUpdate(artifact)"></button>
- <button class="table-delete-btn" data-tests-id="delete_{{artifact.artifactDisplayName}}"
- data-ng-if="!isViewMode() && !artifact.isHEAT() && !artifact.isThirdParty() && !isLicenseArtifact(artifact)" data-ng-click="delete(artifact)"> </button>
- <button class="table-download-btn" download-artifact data-tests-id="download_{{artifact.artifactDisplayName}}"
- data-ng-if="artifact.artifactName" component="component" artifact="artifact"></button>
-
-
- </div>
- </div>
- <div data-ng-repeat-end="" data-ng-if="artifact.selected || undefined==artifact.selected && updateInProgress" class="w-sdc-form item-opened">
- <!-- Artifact panel opened -->
-
- <!-- Description field -->
- <div class="w-sdc-form-item" ng-form="descriptionForm" data-ng-class="{error:(descriptionForm.$dirty && descriptionForm.$invalid)}">
- <label class="i-sdc-env-form-label required">Description</label>
- <textarea class="i-sdc-form-textarea {{$index}}" data-ng-class="{'view-mode': isViewMode()}"
- data-ng-maxlength="256"
- maxlength="256"
- data-ng-required="true"
- name="description"
- data-ng-model="artifact.description"
- data-ng-model-options="{ debounce: 200 }"
- data-ng-pattern="getValidationPattern('string')"
- ng-readonly="isViewMode()"
- data-tests-id="description">
- </textarea>
-
- <div class="input-error" data-ng-show="descriptionForm.$dirty && descriptionForm.$invalid">
- <span ng-show="descriptionForm.$error.required" translate="ADD_ARTIFACT_ERROR_DESCRIPTION_REQUIRED"></span>
- <span ng-show="descriptionForm.$error.maxlength" translate="VALIDATION_ERROR_MAX_LENGTH" translate-values="{'max': '256' }"></span>
- <span ng-show="descriptionForm.$error.pattern" translate="VALIDATION_ERROR_SPECIAL_CHARS_NOT_ALLOWED"></span>
- </div>
-
- </div>
-
- <!-- Parameters in 2 columns -->
- <div class="w-sdc-form-columns-wrapper" data-ng-if="artifact.heatParameters">
- <!-- Left column -->
- <div class="w-sdc-form-column">
- <div class="i-sdc-form-item" ng-form="parameterForm"
- data-ng-repeat="parameter in artifact.heatParameters.slice(0, artifact.heatParameters.length%2+artifact.heatParameters.length/2) track by $index">
- <label class="i-sdc-env-form-label" data-ng-class="{required:parameter.defaultValue}" tooltip-side="top" sdc-smart-tooltip>{{parameter.name +' (' + parameter.type + ')'}}</label>
- <span class="parameter-description" tooltips tooltip-side="top" tooltip-content="{{parameter.description}}">?</span>
- <input class="i-sdc-form-input" data-ng-class="{error:(parameterForm.currentValue.$invalid),'view-mode': isViewMode() }"
- data-ng-model-options="{ debounce: 200 }"
- data-ng-model="parameter.currentValue"
- type="text"
- name="currentValue"
- data-ng-pattern="getValidationPattern(parameter.type, 'heat')"
- data-ng-required="parameter.defaultValue"
- data-ng-change="'json'==parameter.type && parameterForm.currentValue.$setValidity('pattern', validateJson(parameter.currentValue))"
- data-ng-blur="!parameterForm.currentValue.$error.pattern && resetValue(parameter)"
- />
-
- <div class="input-error" data-ng-show="parameterForm.currentValue.$invalid">
- <span ng-show="parameterForm.currentValue.$error.required" translate="VALIDATION_ERROR_REQUIRED" translate-values="{'field': 'Value'}"></span>
- <span ng-show="parameterForm.currentValue.$error.pattern && parameter.type==='string'" translate="VALIDATION_ERROR_SPECIAL_CHARS_NOT_ALLOWED"></span>
- <span ng-show="parameterForm.currentValue.$error.pattern && !(parameter.type==='string')" translate="VALIDATION_ERROR_TYPE" translate-values="{'type': '{{parameter.type}}'}"></span>
- </div>
- </div>
- </div>
-
- <!-- Right column -->
- <div class="w-sdc-form-column">
- <div class="i-sdc-form-item" ng-form="parameterForm" data-ng-repeat="parameter in artifact.heatParameters.slice(artifact.heatParameters.length%2+artifact.heatParameters.length/2) track by $index">
- <label class="i-sdc-env-form-label" data-ng-class="{required:parameter.defaultValue}" tooltip-side="top" sdc-smart-tooltip>{{parameter.name +' (' + parameter.type + ')'}}</label>
- <span class="parameter-description" tooltips tooltip-side="top" tooltip-content="{{parameter.description}}">?</span>
- <input class="i-sdc-form-input" data-ng-class="{error:(parameterForm.currentValue.$invalid), 'view-mode': isViewMode()}"
- data-ng-model-options="{ debounce: 200 }"
- data-ng-model="parameter.currentValue"
- type="text"
- name="currentValue"
- data-ng-pattern="getValidationPattern(parameter.type, 'heat')"
- data-ng-required="parameter.defaultValue"
- data-ng-change="'json'==parameter.type && parameterForm.currentValue.$setValidity('pattern', validateJson(parameter.currentValue))"
- data-ng-blur="!parameterForm.currentValue.$error.pattern && resetValue(parameter)"
- />
-
- <div class="input-error" data-ng-show="parameterForm.currentValue.$invalid">
- <span ng-show="parameterForm.currentValue.$error.required" translate="VALIDATION_ERROR_REQUIRED" translate-values="{'field': 'Value'}"></span>
- <span ng-show="parameterForm.currentValue.$error.pattern && parameter.type==='string'" translate="VALIDATION_ERROR_SPECIAL_CHARS_NOT_ALLOWED"></span>
- <span ng-show="parameterForm.currentValue.$error.pattern && !(parameter.type==='string')" translate="VALIDATION_ERROR_TYPE" translate-values="{'type': '{{parameter.type}}'}"></span>
- </div>
- </div>
- </div>
-
-
- </div><!-- Close: Parameters in 2 columns -->
- </div><!-- Close: Artifact panel opened -->
-
- <!-- Add artifacts buttons -->
- <button class="add-button" data-ng-repeat="artifact in artifacts track by $index"
- type="button"
- data-ng-show="!artifact.esId"
- data-ng-if="!viewModeOrCsarComponent()"
- data-ng-class="{'disabled': isDisableMode() || component.isCsarComponent()}"
- data-tests-id="{{artifact.artifactDisplayName}} deployment_artifact"
- translate="DEPLOYMENT_ARTIFACT_BUTTON_ADD_HEAT"
- translate-values="{'name': '{{artifact.artifactDisplayName}}'}"
- data-ng-click="addOrUpdate(artifact)"></button>
-
- <!-- Top add button -->
- <button class="add-button" type="button" data-ng-if="!isViewMode()" data-ng-class="{'disabled': isDisableMode()}" translate="DEPLOYMENT_ARTIFACT_BUTTON_ADD_OTHER" data-ng-click="addOrUpdate({})"></button>
- </perfect-scrollbar>
- </form>
- </div>
- </div>
-</div>
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/deployment/deployment-view-model.ts b/catalog-ui/app/scripts/view-models/workspace/tabs/deployment/deployment-view-model.ts
deleted file mode 100644
index f8afc0b758..0000000000
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/deployment/deployment-view-model.ts
+++ /dev/null
@@ -1,127 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../../../references"/>
-module Sdc.ViewModels {
- 'use strict';
-
- export interface IDeploymentViewModelScope extends IWorkspaceViewModelScope {
-
- currentComponent: Models.Components.Component;
- selectedComponent: Models.Components.Component;
- isLoading: boolean;
- sharingService:Sdc.Services.SharingService;
- sdcMenu:Models.IAppMenu;
- version:string;
- isViewOnly:boolean;
- tabs:Array<Models.Tab>;
-
- setComponent(component: Models.Components.Component);
- isComponentInstanceSelected():boolean;
- updateSelectedComponent(): void
- openUpdateModal();
- deleteSelectedComponentInstance():void;
- onBackgroundClick():void;
- setSelectedInstance(componentInstance: Models.ComponentsInstances.ComponentInstance): void;
- printScreen():void;
-
- }
-
- export class DeploymentViewModel {
-
- static '$inject' = [
- '$scope',
- 'sdcMenu',
- 'MenuHandler',
- '$modal',
- '$templateCache',
- '$state',
- 'Sdc.Services.SharingService',
- '$filter',
- 'Sdc.Services.CacheService',
- 'ComponentFactory',
- 'ChangeLifecycleStateHandler',
- 'LeftPaletteLoaderService',
- 'ModalsHandler'
- ];
-
- constructor(private $scope:IDeploymentViewModelScope,
- private sdcMenu:Models.IAppMenu,
- private MenuHandler: Utils.MenuHandler,
- private $modal:ng.ui.bootstrap.IModalService,
- private $templateCache:ng.ITemplateCacheService,
- private $state:ng.ui.IStateService,
- private sharingService:Services.SharingService,
- private $filter:ng.IFilterService,
- private cacheService:Services.CacheService,
- private ComponentFactory: Utils.ComponentFactory,
- private ChangeLifecycleStateHandler: Sdc.Utils.ChangeLifecycleStateHandler,
- private LeftPaletteLoaderService: Services.Components.LeftPaletteLoaderService,
- private ModalsHandler: Sdc.Utils.ModalsHandler) {
-
- this.$scope.setValidState(true);
- this.initScope();
- this.$scope.updateSelectedMenuItem();
- }
-
-
- private initComponent = ():void => {
-
- this.$scope.currentComponent = this.$scope.component;
- this.$scope.selectedComponent = this.$scope.currentComponent;
- this.updateUuidMap();
- this.$scope.isViewOnly = this.$scope.isViewMode();
- };
-
-
- private updateUuidMap = ():void => {
- /**
- * In case user press F5, the page is refreshed and this.sharingService.currentEntity will be undefined,
- * but after loadService or loadResource this.sharingService.currentEntity will be defined.
- * Need to update the uuidMap with the new resource or service.
- */
- this.sharingService.addUuidValue(this.$scope.currentComponent.uniqueId,this.$scope.currentComponent.uuid);
- };
-
- private initRightTabs = ()=> {
- if(this.$scope.currentComponent.groups){
-
- let hierarchyTab = new Models.Tab('/app/scripts/view-models/tabs/hierarchy/hierarchy-view.html', 'Sdc.ViewModels.HierarchyViewModel', 'hierarchy', this.$scope.currentComponent, 'hierarchy');
- this.$scope.tabs = Array<Models.Tab>();
- this.$scope.tabs.push(hierarchyTab)
- }
-
- }
- private initScope = ():void => {
-
- this.$scope.sharingService = this.sharingService;
- this.$scope.sdcMenu = this.sdcMenu;
- this.$scope.isLoading = false;
-
- this.$scope.version = this.cacheService.get('version');
- this.initComponent();
-
- this.$scope.setComponent = (component: Models.Components.Product):void => {
- this.$scope.currentComponent = component;
- }
-
- this.initRightTabs();
- }
- }
-}
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/distribution/disribution-status-modal/disribution-status-modal-view-model.ts b/catalog-ui/app/scripts/view-models/workspace/tabs/distribution/disribution-status-modal/disribution-status-modal-view-model.ts
deleted file mode 100644
index c0d6aba915..0000000000
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/distribution/disribution-status-modal/disribution-status-modal-view-model.ts
+++ /dev/null
@@ -1,67 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../../../../references"/>
-module Sdc.ViewModels {
- 'use strict';
-
- interface IDistributionStatusModalViewModelScope {
- distribution:Models.Distribution;
- status:string;
- getStatusCount(distributionComponent:Array<Models.DistributionComponent>):any;
- getUrlName(url:string):string;
- modalDitributionStatus:ng.ui.bootstrap.IModalServiceInstance;
- footerButtons: Array<any>;
- close(): void;
- }
-
- export class DistributionStatusModalViewModel {
-
- static '$inject' = ['$scope','$modalInstance', 'data'];
-
- constructor(private $scope:IDistributionStatusModalViewModelScope,
- private $modalInstance:ng.ui.bootstrap.IModalServiceInstance,
- private data:any
- ) {
- this.initScope();
- }
-
- private initScope = ():void => {
- this.$scope.distribution = this.data.distribution;
- this.$scope.status = this.data.status;
- this.$scope.modalDitributionStatus = this.$modalInstance;
-
- this.$scope.getUrlName = (url:string):string =>{
- let urlName:string = _.last(url.split('/'));
- return urlName;
- };
-
- this.$scope.close = ():void => {
- this.$modalInstance.close();
- };
-
- this.$scope.footerButtons = [
- {'name': 'Close', 'css': 'blue', 'callback': this.$scope.close }
- ];
-
- };
-
-
- }
-}
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/distribution/distribution-view-model.ts b/catalog-ui/app/scripts/view-models/workspace/tabs/distribution/distribution-view-model.ts
deleted file mode 100644
index 219585fc3d..0000000000
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/distribution/distribution-view-model.ts
+++ /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=========================================================
- */
-/// <reference path="../../../../references"/>
-
-module Sdc.ViewModels {
- 'use strict';
-
- interface IDistributionViewModel extends IWorkspaceViewModelScope{
- modalDistribution:ng.ui.bootstrap.IModalServiceInstance;
- service: Models.Components.Service;
- distributions : Array<Models.Distribution>;
- showComponents(distribution:Models.Distribution): void;
- markAsDeployed(distribution:Models.Distribution): void;
- getStatusCount(distributionComponent:Array<Models.DistributionComponent>):any;
- initDistributions():void;
- getUrlName(url:string):string;
- close(): void;
- openDisributionStatusModal:Function;
- }
-
- export class DistributionViewModel{
-
- static '$inject' = [
- '$scope',
- 'ModalsHandler'
-
- ];
-
- constructor(
- private $scope:IDistributionViewModel,
- private ModalsHandler: Sdc.Utils.ModalsHandler
- ){
- this.initScope();
- this.$scope.setValidState(true);
- this.$scope.updateSelectedMenuItem();
- }
-
- private initScope = (): void => {
- this.$scope.service = <Models.Components.Service>this.$scope.component;
-
-
- // Open Distribution status modal
- this.$scope.openDisributionStatusModal = (distribution: Models.Distribution,status:string):void => {
- this.ModalsHandler.openDistributionStatusModal(distribution,status).then(()=>{
- // OK
- }, ()=>{
- // ERROR
- });
- };
-
-
- this.$scope.showComponents = (distribution: Models.Distribution): void => {
- let onError = (response) => {
- console.info('onError showComponents',response);
- };
- let onSuccess = (distributionComponents: Array<Models.DistributionComponent>) => {
- distribution.distributionComponents = distributionComponents;
- distribution.statusCount = this.$scope.getStatusCount(distribution.distributionComponents);
- // distribution.components = this.aggregateDistributionComponent(distributionComponents);;
- };
- this.$scope.service.getDistributionsComponent(distribution.distributionID).then(onSuccess, onError);
- };
-
- this.$scope.getStatusCount = (distributionComponent:Array<Models.DistributionComponent>):any => {
- return _.countBy(distributionComponent, 'status')
- };
-
- this.$scope.getUrlName = (url:string):string =>{
- let urlName:string = _.last(url.split('/'));
- return urlName;
- };
-
- this.$scope.markAsDeployed = (distribution: Models.Distribution): void => {
- let onError = (response) => {
- console.info('onError markAsDeployed',response);
- };
- let onSuccess = (result: any) => {
- distribution.deployementStatus = 'Deployed';
- };
- this.$scope.service.markAsDeployed(distribution.distributionID).then(onSuccess, onError);
-
- };
-
- this.$scope.initDistributions = (): void => {
- let onError = (response) => {
- console.info('onError initDistributions',response);
- };
- let onSuccess = (distributions: Array<Models.Distribution>) => {
- this.$scope.distributions = distributions;
- };
- this.$scope.service.getDistributionsList().then(onSuccess, onError);
- };
-
- this.$scope.initDistributions();
-
- };
-
-
- private aggregateDistributionComponent = (distributionComponents:Array<Models.DistributionComponent>):any =>{
- let aggregateDistributions:Utils.Dictionary<string,Utils.Dictionary<string,Array<Models.DistributionComponent>>> = new Utils.Dictionary<string,Utils.Dictionary<string,Array<Models.DistributionComponent>>>();
- let tempAggregateDistributions:any= _.groupBy(distributionComponents,'omfComponentID');
- let aa = new Utils.Dictionary<string,Array<Models.DistributionComponent>>();
-
- let tempAggregate:any;
- _.forEach(tempAggregateDistributions,(distributionComponents:Array<Models.DistributionComponent>,omfComponentID:string)=>{
-
- let urls:any = _.groupBy(distributionComponents,'url');
- aggregateDistributions.setValue(omfComponentID,urls);
- // aggregateDistributions[omfComponentID] = ;
-
- });
- console.log(aggregateDistributions);
- return aggregateDistributions;
- };
-
-
- }
-}
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/general/general-view-model.ts b/catalog-ui/app/scripts/view-models/workspace/tabs/general/general-view-model.ts
deleted file mode 100644
index f613648596..0000000000
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/general/general-view-model.ts
+++ /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=========================================================
- */
-/// <reference path="../../../../references"/>
-module Sdc.ViewModels {
-
- 'use strict';
- import Resource = Sdc.Models.Components.Resource;
- import ISubCategory = Sdc.Models.ISubCategory;
- import IMainCategory = Sdc.Models.IMainCategory;
- import ResourceType = Sdc.Utils.Constants.ResourceType;
-
- export class Validation {
- validationPattern:RegExp;
- contactIdValidationPattern:RegExp;
- tagValidationPattern:RegExp;
- vendorValidationPattern:RegExp;
- commentValidationPattern:RegExp;
- projectCodeValidationPattern:RegExp;
- }
-
- export interface IGeneralScope extends IWorkspaceViewModelScope {
- validation:Validation;
- editForm:ng.IFormController;
- categories: Array<IMainCategory>;
- latestCategoryId: string;
- latestVendorName: string;
- importedFileExtension:any;
- isCreate:boolean;
- isShowFileBrowse:boolean;
- isShowOnboardingSelectionBrowse:boolean;
- importedToscaBrowseFileText:string;
- importCsarProgressKey:string;
- browseFileLabel:string;
-
-
- onToscaFileChange():void
- validateField(field:any):boolean;
- validateName(isInit:boolean): void;
- calculateUnique(mainCategory:string, subCategory:string):string; // Build unique string from main and sub category
- onVendorNameChange(oldVendorName:string): void;
- convertCategoryStringToOneArray(category:string, subcategory:string):Array<Models.IMainCategory>;
- onCategoryChange():void;
- openOnBoardingModal():void;
- initCategoreis():void;
- }
-
- export class GeneralViewModel {
-
- static '$inject' = [
- '$scope',
- 'Sdc.Services.CacheService',
- 'ValidationPattern',
- 'ContactIdValidationPattern',
- 'TagValidationPattern',
- 'VendorValidationPattern',
- 'CommentValidationPattern',
- 'ValidationUtils',
- 'sdcConfig',
- 'ProjectCodeValidationPattern',
- '$state',
- 'ModalsHandler',
- 'EventListenerService',
- 'Notification',
- 'Sdc.Services.ProgressService',
- '$interval',
- '$filter',
- '$timeout'
- ];
-
- constructor(private $scope:IGeneralScope,
- private cacheService:Services.CacheService,
- private ValidationPattern:RegExp,
- private ContactIdValidationPattern:RegExp,
- private TagValidationPattern:RegExp,
- private VendorValidationPattern:RegExp,
- private CommentValidationPattern:RegExp,
- private ValidationUtils:Sdc.Utils.ValidationUtils,
- private sdcConfig:Models.IAppConfigurtaion,
- private ProjectCodeValidationPattern:RegExp,
- private $state:ng.ui.IStateService,
- private ModalsHandler: Sdc.Utils.ModalsHandler,
- private EventListenerService:Services.EventListenerService,
- private Notification:any,
- private progressService:Sdc.Services.ProgressService,
- protected $interval:any,
- private $filter:ng.IFilterService,
- private $timeout:ng.ITimeoutService
- ){
-
- this.registerToSuccessSaveEvent();
- this.initScopeValidation();
- this.initScopeMethods();
- this.initScope();
- this.$scope.updateSelectedMenuItem();
- }
-
- private registerToSuccessSaveEvent = ():void => {
- // Register to save success to show notification to user.
- this.EventListenerService.registerObserverCallback(Utils.Constants.EVENTS.ON_WORKSPACE_SAVE_BUTTON_SUCCESS, this.showSuccessNotificationMessage);
-
- };
-
- private showSuccessNotificationMessage = ():void => {
- // In case we import CSAR. Notify user when import VF was finished.
- this.Notification.success({
- message: this.$filter('translate')("IMPORT_VF_MESSAGE_CREATE_FINISHED_DESCRIPTION"),
- title: this.$filter('translate')("IMPORT_VF_MESSAGE_CREATE_FINISHED_TITLE")
- });
-
- //set the form Pristine after save to reset the unsaved changes (whit for dom reload)
- this.$timeout(()=> {
- if(this.$scope.editForm) {
- this.$scope.editForm.$setPristine();
- }
- }, 500);
-
- };
-
-
-
- private initScopeValidation = ():void => {
- this.$scope.validation = new Validation();
- this.$scope.validation.validationPattern = this.ValidationPattern;
- this.$scope.validation.contactIdValidationPattern = this.ContactIdValidationPattern;
- this.$scope.validation.tagValidationPattern = this.TagValidationPattern;
- this.$scope.validation.vendorValidationPattern = this.VendorValidationPattern;
- this.$scope.validation.commentValidationPattern = this.CommentValidationPattern;
- this.$scope.validation.projectCodeValidationPattern = this.ProjectCodeValidationPattern;
- };
-
- private initScope = ():void => {
-
- // Work around to change the csar version
- if (this.cacheService.get(Utils.Constants.CHANGE_COMPONENT_CSAR_VERSION_FLAG)) {
- (<Resource>this.$scope.component).csarVersion = this.cacheService.get(Utils.Constants.CHANGE_COMPONENT_CSAR_VERSION_FLAG);
- }
-
- this.$scope.importedToscaBrowseFileText = this.$scope.component.name + " (" + (<Resource>this.$scope.component).csarVersion + ")";
- this.$scope.importCsarProgressKey = "importCsarProgressKey";
- this.$scope.browseFileLabel = this.$scope.component.isResource() && (<Resource>this.$scope.component).resourceType===ResourceType.VF? "Upload file" : "Upload VFC";
- this.$scope.progressService = this.progressService;
-
- // Workaround to short vendor name to 25 chars
- // onboarding send 27 chars, and the validation pattern is 25 chars.
- if (this.$scope.component.vendorName){
- this.$scope.component.vendorName = this.$scope.component.vendorName.substr(0, 25);
- }
-
- // Init UIModel
- this.$scope.component.tags = _.without(this.$scope.component.tags, this.$scope.component.name);
-
- // Init categories
- this.$scope.initCategoreis();
-
- // Init the decision if to show file browse.
- this.$scope.isShowFileBrowse = false;
- if (this.$scope.component.isResource()){
- let resource:Sdc.Models.Components.Resource = <Sdc.Models.Components.Resource>this.$scope.component;
- console.log(resource.name + ": " + resource.csarUUID);
- if (resource.importedFile){ // Component has imported file.
- this.$scope.isShowFileBrowse = true;
- }
- if (this.$scope.isEditMode() && resource.resourceType== ResourceType.VF && !resource.csarUUID){
- this.$scope.isShowFileBrowse = true;
- }
- };
-
- // Init the decision if to show onboarding
- this.$scope.isShowOnboardingSelectionBrowse = false;
- if (this.$scope.component.isResource() &&
- this.$scope.isEditMode() &&
- (<Resource>this.$scope.component).resourceType== ResourceType.VF &&
- (<Resource>this.$scope.component).csarUUID) {
- this.$scope.isShowOnboardingSelectionBrowse = true;
- }
-
- //init file extensions based on the file that was imported.
- if (this.$scope.component.isResource() && (<Resource>this.$scope.component).importedFile){
- let fileName:string = (<Resource>this.$scope.component).importedFile.filename;
- let fileExtension:string = fileName.split(".").pop();
- if (this.sdcConfig.csarFileExtension.indexOf(fileExtension.toLowerCase()) !== -1){
- this.$scope.importedFileExtension = this.sdcConfig.csarFileExtension;
- (<Resource>this.$scope.component).importedFile.filetype="csar";
- } else if (this.sdcConfig.toscaFileExtension.indexOf(fileExtension.toLowerCase()) !== -1){
- (<Resource>this.$scope.component).importedFile.filetype="yaml";
- this.$scope.importedFileExtension = this.sdcConfig.toscaFileExtension;
- }
- }else if(this.$scope.isEditMode()&& (<Resource>this.$scope.component).resourceType === ResourceType.VF){
- this.$scope.importedFileExtension = this.sdcConfig.csarFileExtension;
- //(<Resource>this.$scope.component).importedFile.filetype="csar";
- }
-
- this.$scope.setValidState(true);
-
- this.$scope.calculateUnique = (mainCategory:string, subCategory:string):string => {
- let uniqueId:string = mainCategory;
- if (subCategory) {
- uniqueId += "_#_" + subCategory; // Set the select category combobox to show the selected category.
- }
- return uniqueId;
- };
-
- //TODO remove this after handling contact in UI
- if(this.$scope.component.isProduct() && this.$scope.isCreateMode()){
- (<Models.Components.Product>this.$scope.component).contacts = [];
- (<Models.Components.Product>this.$scope.component).contacts.push(this.cacheService.get("user").userId);
- }else if(this.$scope.isCreateMode()){
- this.$scope.component.contactId = this.cacheService.get("user").userId;
- }
-
- };
-
- // Convert category string MainCategory_#_SubCategory to Array with one item (like the server except)
- private convertCategoryStringToOneArray = ():Array<Models.IMainCategory> => {
- let tmp = this.$scope.component.selectedCategory.split("_#_");
- let mainCategory = tmp[0];
- let subCategory = tmp[1];
-
- // Find the selected category and add the relevant sub category.
- let selectedMainCategory:IMainCategory = <Models.IMainCategory>_.find(this.$scope.categories, function (item) {
- return item["name"] === mainCategory;
-
- });
-
- let mainCategoryClone = angular.copy(selectedMainCategory);
- if (subCategory) {
- let selectedSubcategory = <Models.ISubCategory>_.find(selectedMainCategory.subcategories, function (item) {
- return item["name"] === subCategory;
- });
- mainCategoryClone['subcategories'] = [angular.copy(selectedSubcategory)];
- }
- let tmpSelected = <Models.IMainCategory> mainCategoryClone;
-
- let result:Array<Models.IMainCategory> = [];
- result.push(tmpSelected);
-
- return result;
- };
-
- private updateComponentNameInBreadcrumbs = ():void => {
- //update breadcrum after changing name
- this.$scope.breadcrumbsModel[1].updateSelectedMenuItemText(this.$scope.component.getComponentSubType() + ': ' + this.$scope.component.name);
- this.$scope.updateMenuComponentName(this.$scope.component.name);
- };
-
- private initScopeMethods = ():void => {
-
- this.$scope.initCategoreis = ():void => {
- if (this.$scope.componentType === Utils.Constants.ComponentType.RESOURCE) {
- this.$scope.categories = this.cacheService.get('resourceCategories');
-
- }
- if (this.$scope.componentType === Utils.Constants.ComponentType.SERVICE) {
- this.$scope.categories = this.cacheService.get('serviceCategories');
- }
- }
-
- this.$scope.validateField = (field:any):boolean => {
- if (field && field.$dirty && field.$invalid) {
- return true;
- }
- return false;
- };
-
- this.$scope.openOnBoardingModal=():void => {
- let csarUUID = (<Resource>this.$scope.component).csarUUID;
- this.ModalsHandler.openOnboadrdingModal('Update', csarUUID).then(()=>{
- // OK
- this.$scope.uploadFileChangedInGeneralTab();
- }, ()=>{
- // ERROR
- });
- };
-
- this.$scope.validateName = (isInit:boolean):void => {
- if (isInit === undefined) {
- isInit = false;
- }
-
- let name = this.$scope.component.name;
- if (!name || name === "") {
- if (this.$scope.editForm
- && this.$scope.editForm["componentName"]
- && this.$scope.editForm["componentName"].$error) {
-
- // Clear the error name already exists
- this.$scope.editForm["componentName"].$setValidity('nameExist', true);
- }
-
- return;
- }
- //?????????????????????????
- let subtype:string = Utils.Constants.ComponentType.RESOURCE == this.$scope.componentType ? this.$scope.component.getComponentSubType() : undefined;
-
- let onFailed = (response) => {
- //console.info('onFaild', response);
- //this.$scope.isLoading = false;
- };
-
- let onSuccess = (validation:Models.IValidate) => {
- this.$scope.editForm["componentName"].$setValidity('nameExist', validation.isValid);
- if(validation.isValid){
- //update breadcrumb after changing name
- this.updateComponentNameInBreadcrumbs();
- }
- };
-
- if (isInit) {
- // When page is init after update
- if (this.$scope.component.name !== this.$scope.originComponent.name) {
- if (!(this.$scope.componentType===Utils.Constants.ComponentType.RESOURCE && (<Resource>this.$scope.component).csarUUID!==undefined)
- ){
- this.$scope.component.validateName(name, subtype).then(onSuccess, onFailed);
- }
- }
- } else {
- // Validating on change (has debounce)
- if (this.$scope.editForm
- && this.$scope.editForm["componentName"]
- && this.$scope.editForm["componentName"].$error
- && !this.$scope.editForm["componentName"].$error.pattern
- && this.$scope.component.name !== this.$scope.originComponent.name
- ) {
- if (!(this.$scope.componentType===Utils.Constants.ComponentType.RESOURCE && (<Resource>this.$scope.component).csarUUID!==undefined)
- ){
- this.$scope.component.validateName(name, subtype).then(onSuccess, onFailed);
- }
- } else if (this.$scope.component.name === this.$scope.originComponent.name) {
- // Clear the error
- this.$scope.editForm["componentName"].$setValidity('nameExist', true);
- }
- }
- };
-
- this.$scope.$watchCollection('component.name', (newData:any):void => {
- this.$scope.validateName(false);
- });
-
- // Notify the parent if this step valid or not.
- this.$scope.$watch("editForm.$valid", (newVal, oldVal) => {
- this.$scope.setValidState(newVal);
- });
-
- this.$scope.$watch("editForm.$dirty", (newVal, oldVal) => {
- if (newVal!==oldVal) {
- this.$state.current.data.unsavedChanges = newVal && !this.$scope.isCreateMode();
- }
- });
-
- this.$scope.onCategoryChange = ():void => {
- this.$scope.component.categories = this.convertCategoryStringToOneArray();
- this.$scope.component.icon = Utils.Constants.DEFAULT_ICON;
- };
-
- this.$scope.onVendorNameChange = (oldVendorName:string):void => {
- if (this.$scope.component.icon === oldVendorName) {
- this.$scope.component.icon = Utils.Constants.DEFAULT_ICON;
- }
- };
- };
- }
-}
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/icons/icons-view-model.ts b/catalog-ui/app/scripts/view-models/workspace/tabs/icons/icons-view-model.ts
deleted file mode 100644
index a591641d0a..0000000000
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/icons/icons-view-model.ts
+++ /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=========================================================
- */
-/**
- * Created by obarda on 4/4/2016.
- */
-/// <reference path="../../../../references"/>
-module Sdc.ViewModels {
- 'use strict';
-
- export interface IIconsScope extends IWorkspaceViewModelScope {
- icons : Array<string>;
- iconSprite: string;
- setComponentIcon(iconSrc:string): void;
- }
-
- export class IconsViewModel {
-
- static '$inject' = [
- '$scope',
- 'Sdc.Services.AvailableIconsService',
- 'ComponentFactory',
- '$state'
- ];
-
- constructor(private $scope:IIconsScope,
- private availableIconsService:Services.AvailableIconsService,
- private ComponentFactory:Sdc.Utils.ComponentFactory,
- private $state:ng.ui.IStateService) {
-
-
- this.initScope();
- this.initIcons();
- this.$scope.updateSelectedMenuItem();
- this.$scope.iconSprite = this.$scope.component.iconSprite;
-
- if (this.$scope.component.isResource()) {
- this.initVendor();
- }
- }
-
- private initialIcon:string = this.$scope.component.icon;
- private initIcons = ():void => {
-
- // For subcategories that where created by admin, there is no icons
- this.$scope.icons = new Array<string>();
- if (this.$scope.component.categories && this.$scope.component.categories.length > 0) {
-
- _.forEach(this.$scope.component.categories, (category:Models.IMainCategory):void => {
- if (category.icons) {
- this.$scope.icons = this.$scope.icons.concat(category.icons);
- }
- if (category.subcategories) {
- _.forEach(category.subcategories, (subcategory:Models.ISubCategory):void => {
- if (subcategory.icons) {
- this.$scope.icons = this.$scope.icons.concat(subcategory.icons);
- }
- });
- }
- });
- }
-
- if (this.$scope.component.isResource()) {
- let resourceType:string = this.$scope.component.getComponentSubType();
- if (resourceType === 'VL') {
- this.$scope.icons = ['vl'];
- }
- if (resourceType === 'CP') {
- this.$scope.icons = ['cp'];
- }
- }
-
- if (this.$scope.icons.length === 0) {
- this.$scope.icons = this.availableIconsService.getIcons(this.$scope.component.componentType);
- }
- //we always add the defual icon to the list
- this.$scope.icons.push('defaulticon');
- };
-
- private initVendor = ():void => {
- let vendors:Array<string> = this.availableIconsService.getIcons(this.$scope.component.componentType).slice(5, 19);
- let vendorName = this.$scope.component.vendorName.toLowerCase();
- if ('at&t' === vendorName) {
- vendorName = 'att';
- }
- if ('nokia' === vendorName) {
- vendorName = 'nokiasiemens';
- }
-
- let vendor:string = _.find(vendors, (vendor:string)=> {
- return vendor.replace(/[_]/g, '').toLowerCase() === vendorName;
- });
-
- if (vendor && this.$scope.icons.indexOf(vendor) === -1) {
- this.$scope.icons.push(vendor);
- }
- };
-
- private initScope():void {
- this.$scope.icons = [];
- this.$scope.setValidState(true);
- //if(this.$scope.component.icon === Utils.Constants.DEFAULT_ICON){
- // //this.$scope.setValidState(false);
- //}
-
- this.$scope.setComponentIcon = (iconSrc:string):void => {
- this.$state.current.data.unsavedChanges = !this.$scope.isViewMode() && (iconSrc != this.initialIcon);
- this.$scope.component.icon = iconSrc;
- // this.$scope.setValidState(true);
- };
-
- }
-
- }
-}
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/information-artifacts/information-artifacts-view-model.ts b/catalog-ui/app/scripts/view-models/workspace/tabs/information-artifacts/information-artifacts-view-model.ts
deleted file mode 100644
index 3a048c1879..0000000000
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/information-artifacts/information-artifacts-view-model.ts
+++ /dev/null
@@ -1,150 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../../../references"/>
-module Sdc.ViewModels {
- 'use strict';
- import ArtifactModel = Sdc.Models.ArtifactModel;
-
- export interface IInformationArtifactsScope extends IWorkspaceViewModelScope {
- artifacts: Array<Models.ArtifactModel>;
- tableHeadersList: Array<any>;
- artifactType: string;
- isResourceInstance:boolean;
- downloadFile:Models.IFileDownload;
- isLoading:boolean;
- sortBy:string;
- reverse:boolean;
-
- getTitle(): string;
- addOrUpdate(artifact:Models.ArtifactModel): void;
- delete(artifact:Models.ArtifactModel): void;
- download(artifact:Models.ArtifactModel): void;
- clickArtifactName(artifact:any):void;
- openEditEnvParametersModal(artifactResource:Models.ArtifactModel):void;
- sort(sortBy:string): void;
- showNoArtifactMessage():boolean;
- }
-
- export class InformationArtifactsViewModel {
-
- static '$inject' = [
- '$scope',
- '$filter',
- '$modal',
- '$templateCache',
- 'Sdc.Services.SharingService',
- '$state',
- 'sdcConfig',
- 'ModalsHandler'
- ];
-
- constructor(private $scope:IInformationArtifactsScope,
- private $filter:ng.IFilterService,
- private $modal:ng.ui.bootstrap.IModalService,
- private $templateCache:ng.ITemplateCacheService,
- private sharingService:Sdc.Services.SharingService,
- private $state:any,
- private sdcConfig:Models.IAppConfigurtaion,
- private ModalsHandler:Utils.ModalsHandler) {
- this.initScope();
- this.$scope.updateSelectedMenuItem();
- }
-
-
- private getMappedObjects():any {
- return {
- normal: this.$scope.component.artifacts
- };
- }
-
- private initScope = ():void => {
- let self = this;
- this.$scope.isLoading = false;
- this.$scope.sortBy = 'artifactDisplayName';
- this.$scope.reverse = false;
- this.$scope.setValidState(true);
- this.$scope.artifactType = 'normal';
- this.$scope.getTitle = ():string => {
- return this.$filter("resourceName")(this.$scope.component.name) + ' Artifacts';
-
- };
-
- this.$scope.tableHeadersList = [
- {title: 'Name', property: 'artifactDisplayName'},
- {title: 'Type', property: 'artifactType'}
- ];
-
- this.$scope.artifacts = <ArtifactModel[]>_.values(this.$scope.component.artifacts);
- this.$scope.sort = (sortBy:string):void => {
- this.$scope.reverse = (this.$scope.sortBy === sortBy) ? !this.$scope.reverse : false;
- this.$scope.sortBy = sortBy;
- };
-
-
- this.$scope.addOrUpdate = (artifact:Models.ArtifactModel):void => {
- artifact.artifactGroupType = 'INFORMATIONAL';
- this.ModalsHandler.openWizardArtifactModal(artifact, this.$scope.component).then(() => {
- this.$scope.artifacts = <ArtifactModel[]>_.values(this.$scope.component.artifacts);
- });
- };
-
- this.$scope.showNoArtifactMessage = ():boolean => {
- let artifacts:any = [];
- artifacts = _.filter(this.$scope.artifacts, (artifact:Models.ArtifactModel)=> {
- return artifact.esId;
- });
-
- if (artifacts.length === 0) {
- return true;
- }
- return false;
- };
-
- this.$scope.delete = (artifact:Models.ArtifactModel):void => {
-
- let onOk = ():void => {
- this.$scope.isLoading = true;
- let onSuccess = ():void => {
- this.$scope.isLoading = false;
- this.$scope.artifacts = <ArtifactModel[]>_.values(this.$scope.component.artifacts);
- };
-
- let onFailed = (error:any):void => {
- console.log('Delete artifact returned error:', error);
- this.$scope.isLoading = false;
- };
-
- this.$scope.component.deleteArtifact(artifact.uniqueId, artifact.artifactLabel).then(onSuccess, onFailed);
- };
-
- let title:string = this.$filter('translate')("ARTIFACT_VIEW_DELETE_MODAL_TITLE");
- let message:string = this.$filter('translate')("ARTIFACT_VIEW_DELETE_MODAL_TEXT", "{'name': '" + artifact.artifactDisplayName + "'}");
- this.ModalsHandler.openConfirmationModal(title, message, false).then(onOk);
- };
-
- this.$scope.clickArtifactName = (artifact:any) => {
- if (!artifact.esId) {
- this.$scope.addOrUpdate(artifact);
- }
-
- };
- }
- }
-}
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/inputs/resource-input/resource-inputs-view-model.ts b/catalog-ui/app/scripts/view-models/workspace/tabs/inputs/resource-input/resource-inputs-view-model.ts
deleted file mode 100644
index 2dc1b1d9ff..0000000000
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/inputs/resource-input/resource-inputs-view-model.ts
+++ /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=========================================================
- */
-/// <reference path="../../../../../references"/>
-module Sdc.ViewModels {
- 'use strict';
- import Dictionary = Sdc.Utils.Dictionary;
- import InputModel = Sdc.Models.InputModel;
-
- export interface IInputsViewModelScope extends IWorkspaceViewModelScope {
- InstanceInputsProperties:Models.InstanceInputsPropertiesMapData; //this is tha map object that hold the selected inputs and the inputs we already used
- vfInstancesList: Array<Models.ComponentsInstances.ComponentInstance>;
- component:Models.Components.Resource;
-
- onArrowPressed():void;
- getInputPropertiesForInstance(instanceId:string, instance:Models.ComponentsInstances.ComponentInstance): ng.IPromise<boolean> ;
- loadInputPropertiesForInstance(instanceId:string, input:Models.InputModel): ng.IPromise<boolean> ;
- loadInputInputs(input:Models.InputModel): ng.IPromise<boolean>;
- }
-
- export class ResourceInputsViewModel {
-
- static '$inject' = [
- '$scope',
- '$q'
- ];
-
- constructor(private $scope:IInputsViewModelScope, private $q: ng.IQService) {
- this.initScope();
- }
-
- private initScope = (): void => {
-
- this.$scope.InstanceInputsProperties = new Models.InstanceInputsPropertiesMapData();
- this.$scope.vfInstancesList = this.$scope.component.componentInstances;
-
- // Need to cast all inputs to InputModel for the search to work
- let tmpInputs:Array<Models.InputModel> = new Array<Models.InputModel>();
- _.each(this.$scope.component.inputs, (input):void => {
- tmpInputs.push(new Models.InputModel(input));
- });
- this.$scope.component.inputs = tmpInputs;
- // This function is not supported for resource
- //this.$scope.component.getComponentInputs();
-
- /*
- * When clicking on instance input in the left or right table, this function will load all properties of the selected input
- */
- this.$scope.getInputPropertiesForInstance = (instanceId:string, instance:Models.ComponentsInstances.ComponentInstance): ng.IPromise<boolean> => {
- let deferred = this.$q.defer();
- instance.properties = this.$scope.component.componentInstancesProperties[instanceId];
- deferred.resolve(true);
- return deferred.promise;
- };
-
- /*
- * When clicking on input in the right table, this function will load all inputs of the selected input
- */
- this.$scope.loadInputInputs = (input:Models.InputModel): ng.IPromise<boolean> => {
- let deferred = this.$q.defer();
-
- let onSuccess = () => { deferred.resolve(true); };
- let onError = () => { deferred.resolve(false); };
-
- if(!input.inputs) {
- this.$scope.component.getResourceInputInputs(input.uniqueId).then(onSuccess, onError);
- } else {
- deferred.resolve(true);
- }
- return deferred.promise;
- };
-
- /*
- * When clicking on instance input in the left or right table, this function will load all properties of the selected input
- */
- this.$scope.loadInputPropertiesForInstance = (instanceId:string, input:Models.InputModel): ng.IPromise<boolean> => {
- let deferred = this.$q.defer();
-
- let onSuccess = (properties:Array<Models.PropertyModel>) => {
- input.properties = properties;
- deferred.resolve(true);
- };
-
- let onError = () => {
- deferred.resolve(false)
- };
-
- if(!input.properties) {
- this.$scope.component.getComponentInstanceInputProperties(instanceId, input.uniqueId).then(onSuccess, onError);
- } else {
- deferred.resolve(true);
- }
- return deferred.promise;
- };
-
- /*
- * When pressing the arrow, we create service inputs from the inputs selected
- */
- this.$scope.onArrowPressed = ():void => {
- let onSuccess = (inputsCreated: Array<Models.InputModel>) => {
-
- //disabled all the inputs in the left table
- _.forEach(this.$scope.InstanceInputsProperties, (properties:Array<Models.PropertyModel>) => {
- _.forEach(properties, (property:Models.PropertyModel) => {
- property.isAlreadySelected = true;
- });
- });
-
- // Adding color to the new inputs (right table)
- _.forEach(inputsCreated, (input) => {
- input.isNew = true;
- });
-
- // Removing color to the new inputs (right table)
- setTimeout(() => {
- _.forEach(inputsCreated, (input) => {
- input.isNew = false;
- });
- this.$scope.$apply();
- }, 3000);
- };
-
- this.$scope.component.createInputsFormInstances(this.$scope.InstanceInputsProperties).then(onSuccess);
- };
-
- }
-
- }
-}
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/inputs/resource-input/resource-inputs-view.html b/catalog-ui/app/scripts/view-models/workspace/tabs/inputs/resource-input/resource-inputs-view.html
deleted file mode 100644
index 7cdf5a2fa4..0000000000
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/inputs/resource-input/resource-inputs-view.html
+++ /dev/null
@@ -1,136 +0,0 @@
-<div class="workspace-inputs">
- <div class="table-container-flex">
- <div class="w-sdc-inputs-search pull-left hideme">
- <input type="text" class="w-sdc-inputs-search-input" placeholder="Search"/>
- <div class="search-icon-container">
- <span class="w-sdc-search-icon inputs-search-icon magnification-white"></span>
- </div>
- </div>
- <div class="table">
- <div class="table-header">VFC instances inputs</div>
- <div class="body">
- <div class="table-loader" ng-class="{'tlv-loader large loader': isLoading}"></div>
- <perfect-scrollbar scroll-y-margin-offset="0" class="scrollbar-container">
-
- <expand-collapse expanded-selector=".vf-instance-list.{{$index}}"
- class="expand-collapse-table-row"
- load-data-function="getInputPropertiesForInstance(instance.uniqueId, instance)"
- is-close-on-init="true"
- data-ng-repeat-start="instance in vfInstancesList track by $index">
- <div class="flex-container data-row">
- <div class="expand-collapse-inputs-table-icon"></div>
- <div class="table-col-general flex-item text">
- <span class="title-text">{{instance.name}}</span>
- </div>
- </div>
-
- </expand-collapse>
-
- <div data-ng-repeat-end="" class="vf-instance-list {{$index}}">
-
- <div class="empty-row" ng-if="instance.properties.length===0">No properties to display</div>
-
- <div ng-repeat="property in instance.properties track by $index">
- <div class="property-row flex-container">
- <div class="flex-item text property-name-container">
- <span class="title-blue-text property-name-text">{{property.name}}</span>
- <span class="text instance-name-text">{{property.name}}</span>
- </div>
- <div class="type-schema-container">
- <div class="text">
- <span>{{property.type}}</span>
- </div>
- </div>
- <div class="type-schema-container">
- <div class="text">
- <span>{{property.schema.property.type}} </span>
- </div>
- </div>
- <!--<sdc-checkbox
- class="type-schema-container input-check-box"
- disabled ="property.isAlreadySelected"
- sdc-checklist-model="InstanceInputsProperties[instance.uniqueId]"
- sdc-checklist-value="property"
- data-ng-click="$event.stopPropagation()"></sdc-checkbox>-->
- </div>
- </div>
-
- </div>
-
- </perfect-scrollbar>
- </div>
- </div>
- </div>
-
- <div class="inputs-button-container pull-left">
- <!--<div ng-click="onArrowPressed()" class="right-arrow-btn"></div>-->
- </div>
-
- <div class="table-container-flex">
- <div class="w-sdc-inputs-search pull-left">
- <input type="text" class="w-sdc-inputs-search-input" data-ng-model="search.filterTerm" placeholder="Search" data-ng-model-options="{debounce: 200}"/>
- <div class="search-icon-container">
- <span class="w-sdc-search-icon inputs-search-icon magnification-white"></span>
- </div>
- </div>
- <div class="table">
- <div class="body">
- <div class="table-header">Resource instance inputs</div>
- <perfect-scrollbar scroll-y-margin-offset="0" include-padding="true" class="scrollbar-container">
- <expand-collapse expanded-selector=".resource-inputs.{{$index}}"
- class="expand-collapse-table-row"
- load-data-function="loadInputPropertiesForInstance(resourceInput.uniqueId, resourceInput)"
- is-close-on-init="true"
- data-ng-repeat-start="resourceInput in component.inputs | filter:search track by $index ">
- <div class="input-row service-input-row">
- <div class="title-text">{{resourceInput.name}}</div>
- <div class="flex-container" ng-class="resourceInput.isNew ? 'new-input': 'service-input-row'">
- <div class="expand-collapse-inputs-table-icon"></div>
- <div class="flex-item">
- <div>
- <span class="title-text">Description:</span>
- <span>{{resourceInput.description}}</span>
- </div>
- </div>
- <div class="flex-item ">
- <div class="text">
- <span class="title-text">VF Instance:</span>
- <span>{{resourceInput.name}}</span>
- </div>
- <div class="text">
- <span class="title-text">Type:</span>
- <span>{{resourceInput.type}} </span>
- </div>
- </div>
- </div>
- </div>
- </expand-collapse>
-
- <div data-ng-repeat-end="" class="input-inputs-list resource-inputs {{$index}}">
- <div class="empty-row" ng-if="resourceInput.properties.length===0">No properties to display</div>
- <div ng-repeat="property in resourceInput.properties track by $index">
- <div class="property-row flex-container">
- <div class="flex-item text property-name-container">
- <span
- class="title-blue-text property-name-text">{{property.name}}</span>
- <span class="text instance-name-text">{{property.name}}</span>
- </div>
- <div class="type-schema-container">
- <div class="text">
- <span>{{property.type}}</span>
- </div>
- </div>
- <div class="type-schema-container">
- <div class="text">
- <span>{{property.schema.property.type}} </span>
- </div>
- </div>
- </div>
- </div>
- </div>
-
- </perfect-scrollbar>
- </div>
- </div>
- </div>
-</div>
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/inputs/service-input/service-inputs-view-model.ts b/catalog-ui/app/scripts/view-models/workspace/tabs/inputs/service-input/service-inputs-view-model.ts
deleted file mode 100644
index 6c8391720a..0000000000
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/inputs/service-input/service-inputs-view-model.ts
+++ /dev/null
@@ -1,246 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../../../../references"/>
-module Sdc.ViewModels {
- 'use strict';
- import IAngularEvent = angular.IAngularEvent;
- import ComponentInstance = Sdc.Models.ComponentsInstances.ComponentInstance;
-
-
- interface IServiceInputsViewModelScope extends IWorkspaceViewModelScope {
-
- vfInstancesList: Array<ComponentInstance>;
- selectedInputs:Array<Models.InputModel>;
- instanceInputsMap:Models.InstancesInputsMapData; //this is tha map object that hold the selected inputs and the inputs we already used
- component:Models.Components.Service;
- sdcMenu:Models.IAppMenu;
-
- onArrowPressed():void;
- loadComponentInputs(): void;
- loadInstanceInputs(instance:ComponentInstance): ng.IPromise<boolean> ;
- loadInputPropertiesForInstance(instanceId:string, input:Models.InputModel): ng.IPromise<boolean> ;
- loadInputInputs(input:Models.InputModel): ng.IPromise<boolean>;
- deleteInput(input:Models.InputModel):void
- }
-
- export class ServiceInputsViewModel {
-
- static '$inject' = [
- '$scope',
- '$q',
- 'ModalsHandler'
- ];
-
- constructor(private $scope:IServiceInputsViewModelScope,
- private $q: ng.IQService,
- private ModalsHandler: Sdc.Utils.ModalsHandler) {
- this.initScope();
- }
-
- /*
- * When loading the screen again, we need to disabled the inputs that already created on the service,
- * we do that by comparing the service input name, to the instance name + '_' + the resource instance input name.
- */
- private disableEnableSelectedInputs = (instance: ComponentInstance): void => {
-
- let alreadySelectedInput = new Array<Models.InputModel>();
- _.forEach(instance.inputs, (input:Models.InputModel) => {
- let expectedServiceInputName = instance.normalizedName + '_' + input.name;
- let inputAlreadyInService: Models.InputModel = _.find(this.$scope.component.inputs, (serviceInput: Models.InputModel) => {
- return serviceInput.name === expectedServiceInputName;
- });
- if(inputAlreadyInService) {
- input.isAlreadySelected = true;
- alreadySelectedInput.push(input);
- } else {
- input.isAlreadySelected = false;
- }
- });
- this.$scope.instanceInputsMap[instance.uniqueId] = alreadySelectedInput;
- };
-
- private initScope = (): void => {
-
- this.$scope.instanceInputsMap = new Models.InstancesInputsMapData();
- this.$scope.isLoading = true;
- this.$scope.selectedInputs = new Array<Models.InputModel>();
-
- // Why do we need this? we call this later.
- //this.$scope.component.getComponentInputs();
-
- let onSuccess = (componentInstances:Array<ComponentInstance>) => {
- console.log("component instances loaded: ", componentInstances);
- this.$scope.vfInstancesList = componentInstances;
- this.$scope.isLoading = false;
- };
-
- //This function will get al component instance for the left table - in future the instances will be filter according to search text
- this.$scope.component.getComponentInstancesFilteredByInputsAndProperties().then(onSuccess);
-
- // This function will get the service inputs for the right table
- this.$scope.component.getComponentInputs();
-
-
- /*
- * When clicking on instance in the left table, this function will load all instance inputs
- */
- this.$scope.loadInstanceInputs = (instance:ComponentInstance): ng.IPromise<boolean> => {
- let deferred = this.$q.defer();
-
- let onSuccess = (inputs:Array<Models.InputModel>) => {
- instance.inputs = inputs;
- this.disableEnableSelectedInputs(instance);
- deferred.resolve(true);
- };
-
- let onError = () => {
- deferred.resolve(false);
- };
-
- if(!instance.inputs) {
- this.$scope.component.getComponentInstanceInputs(instance.uniqueId, instance.componentUid).then(onSuccess, onError);
- this.disableEnableSelectedInputs(instance);
- } else {
- deferred.resolve(true);
- }
- return deferred.promise;
- };
-
- /*
- * When clicking on instance input in the left or right table, this function will load all properties of the selected input
- */
- this.$scope.loadInputPropertiesForInstance = (instanceId:string, input:Models.InputModel): ng.IPromise<boolean> => {
- let deferred = this.$q.defer();
-
- let onSuccess = (properties:Array<Models.PropertyModel>) => {
- input.properties = properties;
- deferred.resolve(true);
- };
-
- let onError = () => {
- deferred.resolve(false)
- };
-
- if(!input.properties) {
- this.$scope.component.getComponentInstanceInputProperties(instanceId, input.uniqueId).then(onSuccess, onError);
- } else {
- deferred.resolve(true);
- }
- return deferred.promise;
- };
-
- /*
- * When clicking on input in the right table, this function will load all inputs of the selected input
- */
- this.$scope.loadInputInputs = (input:Models.InputModel): ng.IPromise<boolean> => {
- let deferred = this.$q.defer();
-
- let onSuccess = () => { deferred.resolve(true); };
- let onError = () => { deferred.resolve(false); };
-
- if(!input.inputs) { // Caching, if exists do not get it.
- this.$scope.component.getServiceInputInputs(input.uniqueId).then(onSuccess, onError);
- } else {
- deferred.resolve(true);
- }
- return deferred.promise;
- };
-
- /*
- * When pressing the arrow, we create service inputs from the inputs selected
- */
- this.$scope.onArrowPressed = ():void => {
- let onSuccess = (inputsCreated: Array<Models.InputModel>) => {
-
- //disabled all the inputs in the left table
- _.forEach(this.$scope.instanceInputsMap, (inputs:Array<Models.InputModel>, instanceId:string) => {
- _.forEach(inputs, (input:Models.InputModel) => {
- input.isAlreadySelected = true;
- });
- });
-
- this.addColorToItems(inputsCreated);
- };
-
- this.$scope.component.createInputsFormInstances(this.$scope.instanceInputsMap).then(onSuccess);
- };
-
- this.$scope.deleteInput = (input: Models.InputModel):void => {
-
- var onDelete = ():void => {
- var onSuccess = (deletedInput: Models.InputModel, componentInstanceId:string):void => {
- // Remove from component.inputs the deleted input (service inputs)
- var remainingServiceInputs:Array<Models.InputModel> = _.filter(this.$scope.component.inputs, (input:Models.InputModel):boolean => {
- return input.uniqueId !== deletedInput.uniqueId;
- });
- this.$scope.component.inputs = remainingServiceInputs;
-
- // Find the instance that contains the deleted input, and set disable|enable the deleted input
- var deletedInputComponentInstance:ComponentInstance = _.find(this.$scope.vfInstancesList, (instanceWithChildToDelete:ComponentInstance):boolean => {
- return instanceWithChildToDelete.uniqueId === componentInstanceId;
- });
- this.disableEnableSelectedInputs(deletedInputComponentInstance);
- };
-
- var onFailed = (error:any) : void => {
- console.log("Error deleting input");
- };
-
- this.addColorToItems([input]);
-
- // Get service inputs of input (so after delete we will know the component instance)
- this.$scope.loadInputInputs(input).then((result:boolean):void=>{
- if (result && input.inputs.length>0) {
- var componentInstanceId:string = input.inputs[0].componentInstanceId;
- this.$scope.component.deleteServiceInput(input.uniqueId).then((deletedInput: Models.InputModel):void => {
- onSuccess(deletedInput, componentInstanceId);
- }, onFailed);
- }
- });
- };
-
- // Get confirmation modal text from menu.json
- var state = "deleteInput";
- var title:string = this.$scope.sdcMenu.alertMessages[state].title;
- var message:string = this.$scope.sdcMenu.alertMessages[state].message.format([input.name]);
-
- // Open confirmation modal
- this.ModalsHandler.openAlertModal(title, message).then(onDelete);
- }
- };
-
- private addColorToItems = (inputsCreated:Array<Models.InputModel>):void => {
-
- // Adding color to the new inputs (right table)
- _.forEach(inputsCreated, (input) => {
- input.isNew = true;
- });
-
- // Removing color to the new inputs (right table)
- setTimeout(() => {
- _.forEach(inputsCreated, (input) => {
- input.isNew = false;
- });
- this.$scope.$apply();
- }, 3000);
- };
-
- }
-}
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/inputs/service-input/service-inputs-view.html b/catalog-ui/app/scripts/view-models/workspace/tabs/inputs/service-input/service-inputs-view.html
deleted file mode 100644
index bf15a70322..0000000000
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/inputs/service-input/service-inputs-view.html
+++ /dev/null
@@ -1,205 +0,0 @@
-<div class="workspace-inputs">
- <div class="table-container-flex">
- <div class="w-sdc-inputs-search pull-left hideme">
- <input type="text" class="w-sdc-inputs-search-input" placeholder="Search"/>
- <div class="search-icon-container">
- <span class="w-sdc-search-icon inputs-search-icon magnification-white"></span>
- </div>
- </div>
- <div class="table">
- <div class="table-header">Resource instance inputs</div>
- <div class="body">
- <div class="table-loader" ng-class="{'tlv-loader large loader': isLoading}"></div>
- <perfect-scrollbar scroll-y-margin-offset="0" class="scrollbar-container">
-
- <expand-collapse expanded-selector=".vf-instance-list.{{$index}}"
- class="expand-collapse-table-row"
- load-data-function="loadInstanceInputs(instance)"
- is-close-on-init="true"
- data-ng-repeat-start="instance in vfInstancesList track by $index">
- <div class="flex-container data-row">
- <div class="expand-collapse-inputs-table-icon"></div>
- <div class="table-col-general flex-item text" data-tests-id="inputs-vf-instance-{{$index}}">
- <span class="title-text">{{instance.name}}</span>
- </div>
- </div>
-
- </expand-collapse>
-
- <div data-ng-repeat-end="" class="vf-instance-list {{$index}}">
-
- <expand-collapse expanded-selector=".input-list.{{$parent.$index}}-{{$index}}"
- class="expand-collapse-table-row"
- load-data-function="loadInputPropertiesForInstance(instance.uniqueId, input)"
- is-close-on-init="true"
- data-ng-repeat-start="input in instance.inputs track by $index">
- <div class="input-row" ng-class="{'selected': selectedInput.uniqueId === input.uniqueId}">
- <div class="title-text">{{input.name}}</div>
- <div class="flex-container">
- <div class="expand-collapse-inputs-table-icon"></div>
- <div class="flex-item">
-
- <div>
- <span class="title-text">Description:</span>
- <span tooltips tooltip-content="{{input.description}}">{{input.description}}</span>
- </div>
- </div>
- <div class="flex-item ">
- <div class="text">
- <span class="title-text">VF Instance:</span>
- <span tooltips tooltip-content="{{instance.name}}">{{instance.name}}</span>
- </div>
- <div class="text">
- <span class="title-text">Type:</span>
- <span tooltips tooltip-content="{{input.type}}">{{input.type}} </span>
- </div>
- </div>
- <sdc-checkbox
- class="input-check-box"
- disabled ="input.isAlreadySelected || isViewMode()"
- sdc-checklist-model="instanceInputsMap[instance.uniqueId]"
- sdc-checklist-value="input"
- data-tests-id="inputs-checkbox-{{$index}}"
- data-ng-click=" $event.stopPropagation()"></sdc-checkbox>
- </div>
- </div>
-
-
- </expand-collapse>
-
- <div data-ng-repeat-end="" class="input-list {{$parent.$index}}-{{$index}}">
- <div class="empty-row" ng-if="input.properties.length===0">No properties to display</div>
-
- <div ng-repeat="property in input.properties track by $index">
- <div class="property-row flex-container">
- <div class="flex-item text property-name-container">
- <span class="title-blue-text property-name-text" tooltips tooltip-content="{{property.name}}">{{property.name}}</span>
- <span class="text instance-name-text" tooltips tooltip-content="{{property.name}}">{{property.name}}</span>
- </div>
- <div class="type-schema-container">
- <div class="text">
- <span tooltips tooltip-content="{{property.type}}">{{property.type}}</span>
- </div>
- </div>
- <div class="type-schema-container">
- <div class="text">
- <span tooltips tooltip-content="{{property.schema.property.type}}">{{property.schema.property.type}} </span>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- </perfect-scrollbar>
- </div>
- </div>
- </div>
-
- <div class="inputs-button-container pull-left">
- <div ng-click="onArrowPressed()" class="right-arrow-btn" data-tests-id="add-inputs-to-service-button"></div>
- </div>
-
- <div class="table-container-flex">
- <div class="w-sdc-inputs-search pull-left">
- <input type="text" class="w-sdc-inputs-search-input" data-ng-model="search.filterTerm" placeholder="Search" data-ng-model-options="{debounce: 200}"/>
- <div class="search-icon-container">
- <span class="w-sdc-search-icon inputs-search-icon magnification-white"></span>
- </div>
- </div>
- <div class="table">
- <div class="body">
- <div class="table-header">Service Inputs</div>
- <perfect-scrollbar scroll-y-margin-offset="0" include-padding="true" class="scrollbar-container">
- <expand-collapse expanded-selector=".service-inputs.{{$index}}"
- class="expand-collapse-table-row"
- load-data-function="loadInputInputs(serviceInput)"
- is-close-on-init="true"
- data-ng-repeat-start="serviceInput in component.inputs | filter:search track by $index ">
- <div class="input-row service-input-row " data-tests-id="service-input-{{$index}}" ng-class="serviceInput.isNew ? 'new-input': ''">
- <div class="title-text">{{serviceInput.name}}</div>
- <div class="flex-container">
- <div class="expand-collapse-inputs-table-icon"></div>
- <div class="flex-item">
- <div>
- <span class="title-text">Description:</span>
- <span tooltips tooltip-content="{{serviceInput.description}}">{{serviceInput.description}}</span>
- </div>
- </div>
- <div class="flex-item ">
- <div class="text">
- <span class="title-text">VF Instance:</span>
- <span tooltips tooltip-content="{{serviceInput.name}}">{{serviceInput.name}}</span>
- </div>
- <div class="text">
- <span class="title-text">Type:</span>
- <span tooltips tooltip-content="{{serviceInput.type}}">{{serviceInput.type}} </span>
- </div>
- </div>
- <div class="delete">
- <span class="sprite-new delete-icon remove-input-icon"
- data-ng-class="{'disabled': isViewMode()}"
- data-ng-click="deleteInput(serviceInput); $event.stopPropagation();"
- data-tests-id="delete-input-{{$index}}"></span>
- </div>
- </div>
- </div>
- </expand-collapse>
-
- <div data-ng-repeat-end="" class="service-inputs {{$index}}">
- <expand-collapse expanded-selector=".input-inputs-list.{{$parent.$index}}-{{$index}}"
- class="expand-collapse-table-row"
- load-data-function="loadInputPropertiesForInstance(input.componentInstanceId, input)"
- is-close-on-init="true"
- data-ng-repeat-start="input in serviceInput.inputs track by $index">
- <div class="input-row">
- <div class="title-text">{{input.name}}</div>
- <div class="flex-container">
- <div class="expand-collapse-inputs-table-icon"></div>
- <div class="flex-item">
- <div>
- <span class="title-text">Description:</span>
- <span tooltips tooltip-content="{{input.description}}">{{input.description}}</span>
- </div>
- </div>
- <div class="flex-item ">
- <div class="text">
- <span class="title-text">VF Instance:</span>
- <span tooltips tooltip-content="{{instance.componentInstanceName}}">{{instance.componentInstanceName}}</span>
- </div>
- <div class="text">
- <span class="title-text">Type:</span>
- <span tooltips tooltip-content="{{input.type}}">{{input.type}} </span>
- </div>
- </div>
- </div>
- </div>
- </expand-collapse>
-
- <div data-ng-repeat-end="" class="input-inputs-list {{$parent.$index}}-{{$index}}">
- <div class="empty-row" ng-if="input.properties.length===0">No properties to display</div>
- <div ng-repeat="property in input.properties track by $index">
- <div class="property-row flex-container">
- <div class="flex-item text property-name-container">
- <span
- class="title-blue-text property-name-text" tooltips tooltips-content="{{property.name}}">{{property.name}}</span>
- <span class="text instance-name-text" tooltips tooltips-content="{{property.name}}">{{property.name}}</span>
- </div>
- <div class="type-schema-container">
- <div class="text">
- <span tooltips tooltips-content="{{property.type}}">{{property.type}}</span>
- </div>
- </div>
- <div class="type-schema-container">
- <div class="text">
- <span tooltips tooltips-content="{{property.schema.property.type}}">{{property.schema.property.type}} </span>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- </perfect-scrollbar>
- </div>
- </div>
- </div>
-</div>
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/network-call-flow/network-call-flow-view-model.ts b/catalog-ui/app/scripts/view-models/workspace/tabs/network-call-flow/network-call-flow-view-model.ts
deleted file mode 100644
index 064f1c5896..0000000000
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/network-call-flow/network-call-flow-view-model.ts
+++ /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=========================================================
- */
-/// <reference path="../../../../references"/>
-module Sdc.ViewModels {
- 'use strict';
-
- export interface INetworkCallFlowViewModelScope extends IWorkspaceViewModelScope {
- vendorMessageModel:VendorModel;
- }
-
- export class participant {
- name:string;
- id:string;
-
- constructor(instance:Models.ComponentsInstances.ComponentInstance){
- this.name = instance.name;
- this.id = instance.uniqueId;
- }
- }
-
-
- export class NetworkCallFlowViewModel {
-
- static '$inject' = [
- '$scope',
- 'uuid4'
- ];
-
- constructor(private $scope:INetworkCallFlowViewModelScope,
- private uuid4:any) {
-
- this.initScope();
- this.$scope.updateSelectedMenuItem();
- }
-
- private getVFParticipantsFromInstances(instances:Array<Models.ComponentsInstances.ComponentInstance>):Array<participant> {
- let participants = [];
- _.forEach(instances,(instance)=> {
- if(Utils.Constants.ResourceType.VF == instance.originType){
- participants.push(new participant(instance));
- }
- });
- return participants;
- }
-
-
- private initScope():void {
- this.$scope.vendorMessageModel = new VendorModel(
- this.$scope.component.artifacts.filteredByType(Utils.Constants.ArtifactType.THIRD_PARTY_RESERVED_TYPES.NETWORK_CALL_FLOW),
- this.$scope.component.uniqueId,
- this.$scope.isViewMode(),
- this.$scope.user.userId,
- this.uuid4.generate(),
- Utils.Constants.ArtifactType.THIRD_PARTY_RESERVED_TYPES.NETWORK_CALL_FLOW,
- this.getVFParticipantsFromInstances(this.$scope.component.componentInstances)
- );
-
- this.$scope.thirdParty = true;
- this.$scope.setValidState(true);
- }
-
- }
-}
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/product-hierarchy/product-hierarchy-view-model.ts b/catalog-ui/app/scripts/view-models/workspace/tabs/product-hierarchy/product-hierarchy-view-model.ts
deleted file mode 100644
index faf77a5215..0000000000
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/product-hierarchy/product-hierarchy-view-model.ts
+++ /dev/null
@@ -1,134 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/**
- * Created by obarda on 4/7/2016.
- */
-/// <reference path="../../../../references"/>
-module Sdc.ViewModels {
- 'use strict';
-
- export interface IProductHierarchyScope extends IWorkspaceViewModelScope {
-
- categoriesOptions: Array<Models.IMainCategory>;
- product:Models.Components.Product;
- isLoading:boolean;
- showDropDown:boolean;
-
- onInputTextClicked():void;
- onGroupSelected(category: Models.IMainCategory, subcategory: Models.ISubCategory, group: Models.IGroup):void;
- clickOutside():void;
- deleteGroup(uniqueId:string):void;
- }
-
- export class ProductHierarchyViewModel {
-
- static '$inject' = [
- '$scope',
- 'Sdc.Services.CacheService',
- 'ComponentFactory',
- '$state'
- ];
-
- constructor(private $scope:IProductHierarchyScope,
- private cacheService:Sdc.Services.CacheService,
- private ComponentFactory: Sdc.Utils.ComponentFactory,
- private $state:ng.ui.IStateService) {
-
-
- this.$scope.product = <Models.Components.Product>this.$scope.getComponent();
- this.$scope.setValidState(true);
- this.initScope();
- this.$scope.updateSelectedMenuItem();
- }
-
- private initCategories = () => {
- this.$scope.categoriesOptions = angular.copy(this.cacheService.get('productCategories'));
- let selectedGroup:Array<Models.IGroup> = [];
- _.forEach(this.$scope.product.categories, (category: Models.IMainCategory) => {
- _.forEach(category.subcategories, (subcategory:Models.ISubCategory) => {
- selectedGroup = selectedGroup.concat(subcategory.groupings);
- });
- });
- _.forEach(this.$scope.categoriesOptions, (category: Models.IMainCategory) => {
- _.forEach(category.subcategories, (subcategory:Models.ISubCategory) => {
- _.forEach(subcategory.groupings, (group:Models.ISubCategory) => {
- let componentGroup:Models.IGroup = _.find(selectedGroup, (componentGroupObj) => {
- return componentGroupObj.uniqueId == group.uniqueId;
- });
- if(componentGroup){
- group.isDisabled = true;
- }
- });
- });
- });
- };
-
- private setFormValidation = ():void => {
- //if(!this.$scope.product.categories || this.$scope.product.categories.length === 0){
- // this.$scope.setValidState(false);
- //}
- //else{
- this.$scope.setValidState(true);
- // }
-
- };
-
- private initScope = ():void => {
- this.$scope.isLoading= false;
- this.$scope.showDropDown =false;
- this.initCategories();
- this.setFormValidation();
-
- this.$scope.onGroupSelected = (category: Models.IMainCategory, subcategory: Models.ISubCategory, group: Models.IGroup):void => {
- this.$scope.product.addGroup(category, subcategory, group);
- this.$state.current.data.unsavedChanges = !this.$scope.isViewMode();
- group.isDisabled = true;
- this.$scope.showDropDown = false;
- this.setFormValidation();
- };
-
- this.$scope.onInputTextClicked = ():void => {//just edit the component in place, no pop up nor server update ?
- this.$scope.showDropDown = !this.$scope.showDropDown;
- };
-
- this.$scope.clickOutside = (): any => {
- this.$scope.showDropDown = false;
- };
-
- this.$scope.deleteGroup = (uniqueId:string) : void => {
- //delete group from component
- this.$scope.product.deleteGroup(uniqueId);
- this.$state.current.data.unsavedChanges = !this.$scope.isViewMode();
- this.setFormValidation();
- //enabled group
- _.forEach(this.$scope.categoriesOptions, (category: Models.IMainCategory) => {
- _.forEach(category.subcategories, (subcategory:Models.ISubCategory) => {
- let groupObj:Models.IGroup = _.find (subcategory.groupings, (group) => {
- return group.uniqueId === uniqueId;
- });
- if(groupObj){
- groupObj.isDisabled = false;
- }
- });
- });
- }
- };
- }
-}
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/properties/properties-view-model.ts b/catalog-ui/app/scripts/view-models/workspace/tabs/properties/properties-view-model.ts
deleted file mode 100644
index 9b824bfca9..0000000000
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/properties/properties-view-model.ts
+++ /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=========================================================
- */
-/// <reference path="../../../../references"/>
-module Sdc.ViewModels {
- 'use strict';
-
- interface IPropertiesViewModelScope extends IWorkspaceViewModelScope {
- tableHeadersList: Array<any>;
- reverse: boolean;
- sortBy:string;
- filteredProperties:any;
-
- addOrUpdateProperty(property?:Models.PropertyModel): void;
- delete(property:Models.PropertyModel): void;
- sort(sortBy:string): void;
- }
-
- export class PropertiesViewModel {
-
- static '$inject' = [
- '$scope',
- '$filter',
- '$modal',
- '$templateCache',
- 'ModalsHandler'
- ];
-
-
- constructor(private $scope:IPropertiesViewModelScope,
- private $filter:ng.IFilterService,
- private $modal:ng.ui.bootstrap.IModalService,
- private $templateCache:ng.ITemplateCacheService,
- private ModalsHandler:Utils.ModalsHandler) {
- this.initScope();
- this.$scope.updateSelectedMenuItem();
- }
-
-
- private openEditPropertyModal = (property:Models.PropertyModel):void => {
- let viewModelsHtmlBasePath:string = '/app/scripts/view-models/';
-
- let modalOptions:ng.ui.bootstrap.IModalSettings = {
- template: this.$templateCache.get(viewModelsHtmlBasePath + 'forms/property-form/property-form-view.html'),
- controller: 'Sdc.ViewModels.PropertyFormViewModel',
- size: 'sdc-l',
- backdrop: 'static',
- keyboard: false,
- resolve: {
- property: ():Models.PropertyModel => {
- return property;
- },
- component: ():Models.Components.Component => {
- return <Models.Components.Component> this.$scope.component;
- },
- filteredProperties: ():Array<Models.PropertyModel> => {
- return this.$scope.filteredProperties.properties;
- }
- }
- };
- this.$modal.open(modalOptions);
- };
-
- private initScope = ():void => {
-
- //let self = this;
- this.$scope.filteredProperties={properties:[]};
- this.$scope.sortBy = 'name';
- this.$scope.reverse = false;
- this.$scope.setValidState(true);
- this.$scope.tableHeadersList = [
- {title: 'Name', property: 'name'},
- {title: 'Type', property: 'type'},
- {title: 'Schema', property: 'schema.property.type'},
- {title: 'Description', property: 'description'},
- ];
- this.$scope.sort = (sortBy:string):void => {
- this.$scope.reverse = (this.$scope.sortBy === sortBy) ? !this.$scope.reverse : false;
- this.$scope.sortBy = sortBy;
- };
-
-
- this.$scope.addOrUpdateProperty = (property?:Models.PropertyModel):void => {
- this.openEditPropertyModal(property ? property : new Models.PropertyModel());
- };
-
- this.$scope.delete = (property:Models.PropertyModel):void => {
-
- let onOk = ():void => {
- this.$scope.component.deleteProperty(property.uniqueId);
- };
- let title:string = this.$filter('translate')("PROPERTY_VIEW_DELETE_MODAL_TITLE");
- let message:string = this.$filter('translate')("PROPERTY_VIEW_DELETE_MODAL_TEXT", "{'name': '" + property.name + "'}");
- this.ModalsHandler.openConfirmationModal(title, message, false).then(onOk);
- };
- }
- }
-}
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/req-and-capabilities/req-and-capabilities-view-model.ts b/catalog-ui/app/scripts/view-models/workspace/tabs/req-and-capabilities/req-and-capabilities-view-model.ts
deleted file mode 100644
index 97a117e8b7..0000000000
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/req-and-capabilities/req-and-capabilities-view-model.ts
+++ /dev/null
@@ -1,165 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/**
- * Created by rcohen on 9/22/2016.
- */
-/// <reference path="../../../../references"/>
-module Sdc.ViewModels {
- 'use strict';
- import tree = d3.layout.tree;
-
- export class SortTableDefined {
- reverse:boolean;
- sortByField:string;
- }
-
- interface IReqAndCapabilitiesViewModelScope extends IWorkspaceViewModelScope {
- requirementsTableHeadersList: Array<any>;
- capabilitiesTableHeadersList: Array<any>;
- capabilityPropertiesTableHeadersList: Array<any>;
- requirementsSortTableDefined: SortTableDefined;
- capabilitiesSortTableDefined: SortTableDefined;
- propertiesSortTableDefined: SortTableDefined;
- requirements:Array<Models.Requirement>;
- capabilities:Array<Models.Capability>;
- mode:string;
- filteredProperties:Array<Array<Models.PropertyModel>>;
- searchText:string;
-
- sort(sortBy:string, sortByTableDefined:SortTableDefined):void;
- updateProperty(property:Models.PropertyModel, indexInFilteredProperties:number):void;
- allCapabilitiesSelected(selected:boolean):void;
- }
-
- export class ReqAndCapabilitiesViewModel {
-
- static '$inject' = [
- '$scope',
- '$filter',
- '$modal',
- '$templateCache',
- 'ModalsHandler'
- ];
-
-
- constructor(private $scope:IReqAndCapabilitiesViewModelScope,
- private $filter:ng.IFilterService,
- private $modal:ng.ui.bootstrap.IModalService,
- private $templateCache:ng.ITemplateCacheService) {
- this.initScope();
- this.$scope.updateSelectedMenuItem();
- }
-
-
- private openEditPropertyModal = (property:Models.PropertyModel, indexInFilteredProperties:number):void => {
- let viewModelsHtmlBasePath:string = '/app/scripts/view-models/';
- //...because there is not be api
- _.forEach(this.$scope.filteredProperties[indexInFilteredProperties],(prop:Models.PropertyModel)=>{
- prop.readonly = true;
- });
- let modalOptions:ng.ui.bootstrap.IModalSettings = {
- template: this.$templateCache.get(viewModelsHtmlBasePath + 'forms/property-form/property-form-view.html'),
- controller: 'Sdc.ViewModels.PropertyFormViewModel',
- size: 'sdc-l',
- backdrop: 'static',
- keyboard: false,
- resolve: {
- property: ():Models.PropertyModel => {
- return property;
- },
- component: ():Models.Components.Component => {
- return <Models.Components.Component> this.$scope.component;
- },
- filteredProperties: ():Array<Models.PropertyModel> => {
- return this.$scope.filteredProperties[indexInFilteredProperties];
- }
- }
- };
- this.$modal.open(modalOptions);
- };
-
- private initScope = ():void => {
-
- this.$scope.requirementsSortTableDefined = {
- reverse: false,
- sortByField: 'name'
- };
- this.$scope.capabilitiesSortTableDefined = {
- reverse: false,
- sortByField: 'name'
- };
- this.$scope.propertiesSortTableDefined = {
- reverse: false,
- sortByField: 'name'
- };
-
- this.$scope.setValidState(true);
- this.$scope.requirementsTableHeadersList = [
- {title: 'Name', property: 'name'},
- {title: 'Capability', property: 'capability'},
- {title: 'Node', property: 'node'},
- {title: 'Relationship', property: 'relationship'},
- {title: 'Connected To', property: ''},
- {title: 'Occurrences', property: ''}
- ];
- this.$scope.capabilitiesTableHeadersList = [
- {title: 'Name', property: 'name'},
- {title: 'Type', property: 'type'},
- {title: 'Description', property: ''},
- {title: 'Valid Source', property: ''},
- {title: 'Occurrences', property: ''}
- ];
- this.$scope.capabilityPropertiesTableHeadersList = [
- {title: 'Name', property: 'name'},
- {title: 'Type', property: 'type'},
- {title: 'Schema', property: 'schema.property.type'},
- {title: 'Description', property: 'description'},
- ];
- this.$scope.filteredProperties=[];
-
- this.$scope.mode='requirements';
- this.$scope.requirements=[];
- _.forEach(this.$scope.component.requirements,(req:Array<Models.Requirement>,capName)=>{
- this.$scope.requirements=this.$scope.requirements.concat(req);
- });
-
- this.$scope.capabilities=[];
- _.forEach(this.$scope.component.capabilities,(cap:Array<Models.Capability>,capName)=>{
- this.$scope.capabilities=this.$scope.capabilities.concat(cap);
- });
-
- this.$scope.sort = (sortBy:string, sortByTableDefined:SortTableDefined):void => {
- sortByTableDefined.reverse = (sortByTableDefined.sortByField === sortBy) ? !sortByTableDefined.reverse : false;
- sortByTableDefined.sortByField = sortBy;
- };
-
- this.$scope.updateProperty = (property:Models.PropertyModel, indexInFilteredProperties:number):void => {
- this.openEditPropertyModal(property, indexInFilteredProperties);
- };
-
- this.$scope.allCapabilitiesSelected = (selected:boolean):void => {
- _.forEach(this.$scope.capabilities,(cap:Models.Capability)=>{
- cap.selected = selected;
- });
- };
- }
- }
-}
-
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/tosca-artifacts/tosca-artifacts-view-model.ts b/catalog-ui/app/scripts/view-models/workspace/tabs/tosca-artifacts/tosca-artifacts-view-model.ts
deleted file mode 100644
index 1e6bc04924..0000000000
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/tosca-artifacts/tosca-artifacts-view-model.ts
+++ /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=========================================================
- */
-/// <reference path="../../../../references"/>
-module Sdc.ViewModels {
- 'use strict';
- import ArtifactModel = Sdc.Models.ArtifactModel;
-
- export interface IToscaArtifactsScope extends IWorkspaceViewModelScope {
- artifacts: Array<Models.ArtifactModel>;
- tableHeadersList: Array<any>;
- artifactType: string;
- downloadFile:Models.IFileDownload;
- isLoading:boolean;
- sortBy:string;
- reverse:boolean;
-
- getTitle(): string;
- download(artifact:Models.ArtifactModel): void;
- sort(sortBy:string): void;
- showNoArtifactMessage():boolean;
- }
-
- export class ToscaArtifactsViewModel {
-
- static '$inject' = [
- '$scope',
- '$filter'
- ];
-
- constructor(private $scope:IToscaArtifactsScope,
- private $filter:ng.IFilterService) {
- this.initScope();
- this.$scope.updateSelectedMenuItem();
- }
-
- private initScope = ():void => {
- let self = this;
- this.$scope.isLoading = false;
- this.$scope.sortBy = 'artifactDisplayName';
- this.$scope.reverse = false;
- this.$scope.setValidState(true);
- this.$scope.artifactType = 'normal';
- this.$scope.getTitle = ():string => {
- return this.$filter("resourceName")(this.$scope.component.name) + ' Artifacts';
-
- };
-
- this.$scope.tableHeadersList = [
- {title: 'Name', property: 'artifactDisplayName'},
- {title: 'Type', property: 'artifactType'}
- ];
-
- this.$scope.artifacts = <ArtifactModel[]>_.values(this.$scope.component.toscaArtifacts);
- this.$scope.sort = (sortBy:string):void => {
- this.$scope.reverse = (this.$scope.sortBy === sortBy) ? !this.$scope.reverse : false;
- this.$scope.sortBy = sortBy;
- };
-
-
-
- this.$scope.showNoArtifactMessage = ():boolean => {
- if (this.$scope.artifacts.length === 0) {
- return true;
- }
- return false;
- };
-
- }
- }
-}
diff --git a/catalog-ui/app/scripts/view-models/workspace/workspace-view-model.ts b/catalog-ui/app/scripts/view-models/workspace/workspace-view-model.ts
deleted file mode 100644
index a8523f24f5..0000000000
--- a/catalog-ui/app/scripts/view-models/workspace/workspace-view-model.ts
+++ /dev/null
@@ -1,703 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/**
- * Created by obarda on 3/30/2016.
- */
-/// <reference path="../../references"/>
-module Sdc.ViewModels {
-
- 'use strict';
- import Resource = Sdc.Models.Components.Resource;
- import ResourceType = Sdc.Utils.Constants.ResourceType;
-
- export interface IWorkspaceViewModelScope extends ng.IScope {
-
- isLoading: boolean;
- isCreateProgress: boolean;
- component: Models.Components.Component;
- originComponent: Models.Components.Component;
- componentType: string;
- importFile: any;
- leftBarTabs: Utils.MenuItemGroup;
- isNew: boolean;
- isFromImport: boolean;
- isValidForm: boolean;
- mode: Utils.Constants.WorkspaceMode;
- breadcrumbsModel: Array<Utils.MenuItemGroup>;
- sdcMenu: Models.IAppMenu;
- changeLifecycleStateButtons: any;
- version: string;
- versionsList: Array<any>;
- changeVersion: any;
- isComposition: boolean;
- isDeployment: boolean;
- $state: ng.ui.IStateService;
- user: Models.IUserProperties;
- thirdParty: boolean;
- disabledButtons: boolean;
- menuComponentTitle: string;
- progressService: Sdc.Services.ProgressService;
- progressMessage: string;
- // leftPanelComponents:Array<Models.Components.Component>; //this is in order to load the left panel once, and not wait long time when moving to composition
-
- showChangeStateButton(): boolean;
- getComponent(): Sdc.Models.Components.Component;
- setComponent(component: Sdc.Models.Components.Component): void;
- onMenuItemPressed(state: string): ng.IPromise<boolean>;
- save(): ng.IPromise<boolean>;
- setValidState(isValid: boolean): void;
- revert(): void;
- changeLifecycleState(state: string): void;
- enabledTabs(): void
- isDesigner(): boolean;
- isViewMode(): boolean;
- isEditMode(): boolean;
- isCreateMode(): boolean;
- isDisableMode(): boolean;
- showFullIcons(): boolean;
- goToBreadcrumbHome(): void;
- onVersionChanged(selectedId: string): void;
- getLatestVersion(): void;
- getStatus(): string;
- showLifecycleIcon(): boolean;
- updateSelectedMenuItem(): void;
- uploadFileChangedInGeneralTab(): void;
- updateMenuComponentName(ComponentName: string): void;
- }
-
- export class WorkspaceViewModel {
-
- static '$inject' = [
- '$scope',
- 'injectComponent',
- 'ComponentFactory',
- '$state',
- 'sdcMenu',
- '$q',
- 'MenuHandler',
- 'Sdc.Services.CacheService',
- 'ChangeLifecycleStateHandler',
- 'ModalsHandler',
- 'LeftPaletteLoaderService',
- '$filter',
- 'EventListenerService',
- 'Sdc.Services.EntityService',
- 'Notification',
- '$stateParams',
- 'Sdc.Services.ProgressService'
- ];
-
- constructor(private $scope: IWorkspaceViewModelScope,
- private injectComponent: Models.Components.Component,
- private ComponentFactory: Utils.ComponentFactory,
- private $state: ng.ui.IStateService,
- private sdcMenu: Models.IAppMenu,
- private $q: ng.IQService,
- private MenuHandler: Utils.MenuHandler,
- private cacheService: Services.CacheService,
- private ChangeLifecycleStateHandler: Sdc.Utils.ChangeLifecycleStateHandler,
- private ModalsHandler: Sdc.Utils.ModalsHandler,
- private LeftPaletteLoaderService: Services.Components.LeftPaletteLoaderService,
- private $filter: ng.IFilterService,
- private EventListenerService: Services.EventListenerService,
- private EntityService: Sdc.Services.EntityService,
- private Notification: any,
- private $stateParams: any,
- private progressService: Sdc.Services.ProgressService) {
-
- this.initScope();
- this.initAfterScope();
- }
-
- private role: string;
- private components: Array<Models.Components.Component>;
-
- private initViewMode = (): Utils.Constants.WorkspaceMode => {
- let mode = Utils.Constants.WorkspaceMode.VIEW;
-
- if (!this.$state.params['id']) { //&& !this.$state.params['vspComponent']
- mode = Utils.Constants.WorkspaceMode.CREATE;
- } else {
- if (this.$scope.component.lifecycleState === Utils.Constants.ComponentState.NOT_CERTIFIED_CHECKOUT &&
- this.$scope.component.lastUpdaterUserId === this.cacheService.get("user").userId) {
- if (this.$scope.component.isProduct() && this.role == Utils.Constants.Role.PRODUCT_MANAGER) {
- mode = Utils.Constants.WorkspaceMode.EDIT;
- }
- if ((this.$scope.component.isService() || this.$scope.component.isResource()) && this.role == Utils.Constants.Role.DESIGNER) {
- mode = Utils.Constants.WorkspaceMode.EDIT;
- }
- }
- }
- return mode;
- };
-
- private initChangeLifecycleStateButtons = (): void => {
- let state = this.$scope.component.isService() && (Utils.Constants.Role.OPS == this.role || Utils.Constants.Role.GOVERNOR == this.role) ? this.$scope.component.distributionStatus : this.$scope.component.lifecycleState;
- this.$scope.changeLifecycleStateButtons = this.sdcMenu.roles[this.role].changeLifecycleStateButtons[state];
- };
-
- private isNeedSave = (): boolean => {
- if (this.$scope.isEditMode() && //this is a workaround for onboarding - we need to get the artifact in order to avoid saving the vf when moving from their tabs
- (this.$state.current.name === Utils.Constants.States.WORKSPACE_MANAGEMENT_WORKFLOW || this.$state.current.name === Utils.Constants.States.WORKSPACE_NETWORK_CALL_FLOW)) {
- return true;
- }
- return this.$scope.isEditMode() &&
- this.$state.current.data && this.$state.current.data.unsavedChanges;
- };
-
- private initScope = (): void => {
-
- this.$scope.component = this.injectComponent;
- this.$scope.menuComponentTitle = this.$scope.component.name;
- this.$scope.disabledButtons = false;
- this.$scope.originComponent = this.ComponentFactory.createComponent(this.$scope.component);
- this.$scope.componentType = this.$scope.component.componentType;
- this.$scope.version = this.cacheService.get('version');
- this.$scope.user = this.cacheService.get("user");
- this.role = this.$scope.user.role;
- this.$scope.mode = this.initViewMode();
- this.$scope.isValidForm = true;
- this.initChangeLifecycleStateButtons();
- this.initVersionObject();
- this.$scope.$state = this.$state;
- this.$scope.isLoading = false;
- this.$scope.isComposition = (this.$state.current.name.indexOf(Utils.Constants.States.WORKSPACE_COMPOSITION) > -1);
- this.$scope.isDeployment = (this.$state.current.name.indexOf(Utils.Constants.States.WORKSPACE_DEPLOYMENT) > -1);
- this.$scope.progressService = this.progressService;
-
- this.$scope.getComponent = (): Sdc.Models.Components.Component => {
- return this.$scope.component;
- };
-
- this.$scope.updateMenuComponentName = (ComponentName: string): void => {
- this.$scope.menuComponentTitle = ComponentName;
- };
-
- this.$scope.sdcMenu = this.sdcMenu;
- // Will be called from each step after save to update the resource.
- this.$scope.setComponent = (component: Sdc.Models.Components.Component): void => {
- this.$scope.component = component;
- };
-
- this.$scope.uploadFileChangedInGeneralTab = (): void => {
- // In case user select browse file, and in update mode, need to disable submit for testing and checkin buttons.
- if (this.$scope.isEditMode() && this.$scope.component.isResource() && (<Resource>this.$scope.component).resourceType == ResourceType.VF) {
- this.$scope.disabledButtons = true;
- }
- };
-
- this.$scope.onMenuItemPressed = (state: string): ng.IPromise<boolean> => {
- let deferred = this.$q.defer();
- if (this.isNeedSave()) {
- if (this.$scope.isValidForm) {
- let onSuccess = (): void => {
- this.$state.go(state, {
- id: this.$scope.component.uniqueId,
- type: this.$scope.component.componentType.toLowerCase(),
- components: this.components
- });
- deferred.resolve(true);
- };
- this.$scope.save().then(onSuccess);
- } else {
- console.log('form is not valid');
- deferred.reject(false);
- }
- } else {
- this.$state.go(state, {
- id: this.$scope.component.uniqueId,
- type: this.$scope.component.componentType.toLowerCase(),
- components: this.components
- });
- deferred.resolve(true);
- }
- return deferred.promise;
- };
-
- this.$scope.setValidState = (isValid: boolean): void => {
- this.$scope.isValidForm = isValid;
- };
-
- this.$scope.onVersionChanged = (selectedId: string): void => {
- this.$scope.isLoading = true;
- if (this.$state.current.data && this.$state.current.data.unsavedChanges) {
- this.$scope.changeVersion.selectedVersion = _.find(this.$scope.versionsList, {versionId: this.$scope.component.uniqueId});
- }
- this.$state.go(this.$state.current.name, {
- id: selectedId,
- type: this.$scope.componentType.toLowerCase(),
- mode: Utils.Constants.WorkspaceMode.VIEW,
- components: this.$state.params['components']
- });
-
- };
-
- this.$scope.getLatestVersion = (): void => {
- this.$scope.onVersionChanged(_.first(this.$scope.versionsList).versionId);
- };
-
- this.$scope.save = (state?: string): ng.IPromise<boolean> => {
- this.EventListenerService.notifyObservers(Utils.Constants.EVENTS.ON_WORKSPACE_SAVE_BUTTON_CLICK);
-
- this.progressService.initCreateComponentProgress(this.$scope.component.uniqueId);
-
- let deferred = this.$q.defer();
- let modalInstance: ng.ui.bootstrap.IModalServiceInstance;
-
- let onFailed = () => {
- this.EventListenerService.notifyObservers(Utils.Constants.EVENTS.ON_WORKSPACE_SAVE_BUTTON_ERROR);
- this.progressService.deleteProgressValue(this.$scope.component.uniqueId);
- modalInstance && modalInstance.close(); // Close the modal in case it is opened.
- this.$scope.isCreateProgress = false;
- this.$scope.isLoading = false; // stop the progress.
-
- this.$scope.setValidState(true); // Set the form valid (if sent form is valid, the error from server).
- if (!this.$scope.isCreateMode()) {
- this.$scope.component = this.$scope.originComponent; // Set the component back to the original.
- this.enableMenuItems(); // Enable the menu items (left tabs), so user can press on them.
- this.$scope.disabledButtons = false; // Enable "submit for testing" & checking buttons.
- }
-
- deferred.reject(false);
- };
-
- let onSuccessCreate = (component: Models.Components.Component) => {
-
- this.EventListenerService.notifyObservers(Utils.Constants.EVENTS.ON_WORKSPACE_SAVE_BUTTON_SUCCESS);
- this.progressService.deleteProgressValue(this.$scope.component.uniqueId);
- //update components for breadcrumbs
- this.components.unshift(component);
- this.$state.go(Utils.Constants.States.WORKSPACE_GENERAL, {
- id: component.uniqueId,
- type: component.componentType.toLowerCase(),
- components: this.components
- });
-
- deferred.resolve(true);
- };
-
- let onSuccessUpdate = (component: Models.Components.Component) => {
- this.$scope.isCreateProgress = false;
- this.$scope.disabledButtons = false;
- this.EventListenerService.notifyObservers(Utils.Constants.EVENTS.ON_WORKSPACE_SAVE_BUTTON_SUCCESS);
- this.progressService.deleteProgressValue(this.$scope.component.uniqueId);
-
- // Stop the circle loader.
- this.$scope.isLoading = false;
-
- component.tags = _.reject(component.tags, (item)=> {
- return item === component.name
- });
-
- // Update the components
- 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;
- }
-
- deferred.resolve(true);
- };
-
- if (this.$scope.isCreateMode()) {
- this.$scope.progressMessage = "Creating Asset...";
- // CREATE MODE
- this.$scope.isCreateProgress = true;
-
- // Start creating the component
- this.ComponentFactory.createComponentOnServer(this.$scope.component).then(onSuccessCreate, onFailed);
-
- // In case we import CSAR. Notify user that import VF will take long time (the create is performed in the background).
- if (this.$scope.component.isResource() && (<Resource>this.$scope.component).csarUUID) {
- this.Notification.info({
- message: this.$filter('translate')("IMPORT_VF_MESSAGE_CREATE_TAKES_LONG_TIME_DESCRIPTION"),
- title: this.$filter('translate')("IMPORT_VF_MESSAGE_CREATE_TAKES_LONG_TIME_TITLE")
- });
- }
- } else {
- // UPDATE MODE
- this.$scope.isCreateProgress = true;
- this.$scope.progressMessage = "Updating Asset...";
- this.disableMenuItems();
-
-
- // Work around to change the csar version
- if (this.cacheService.get(Utils.Constants.CHANGE_COMPONENT_CSAR_VERSION_FLAG)) {
- (<Resource>this.$scope.component).csarVersion = this.cacheService.get(Utils.Constants.CHANGE_COMPONENT_CSAR_VERSION_FLAG);
- this.cacheService.remove(Utils.Constants.CHANGE_COMPONENT_CSAR_VERSION_FLAG);
- }
-
- this.$scope.component.updateComponent().then(onSuccessUpdate, onFailed);
- }
- return deferred.promise;
- };
-
- this.$scope.revert = (): void => {
- //in state of import file leave the file in place
- if (this.$scope.component.isResource() && (<Resource>this.$scope.component).importedFile) {
- let tempFile: Sdc.Directives.FileUploadModel = (<Resource>this.$scope.component).importedFile;
- this.$scope.component = this.ComponentFactory.createComponent(this.$scope.originComponent);
- (<Resource>this.$scope.component).importedFile = tempFile;
- } else {
- this.$scope.component = this.ComponentFactory.createComponent(this.$scope.originComponent);
- }
-
- };
-
- this.$scope.changeLifecycleState = (state: string): void => {
- if (this.isNeedSave() && state !== 'deleteVersion') {
- this.$scope.save().then(() => {
- changeLifecycleState(state);
- })
- } else {
- changeLifecycleState(state);
- }
- };
-
- let defaultActionAfterChangeLifecycleState = (): void => {
- if (this.$state.current.data && this.$state.current.data.unsavedChanges) {
- this.$state.current.data.unsavedChanges = false;
- }
- this.$state.go('dashboard');
- };
-
- let changeLifecycleState = (state: string) => {
- if ('monitor' === state) {
- this.$state.go('workspace.distribution');
- return;
- }
-
- let data = this.$scope.changeLifecycleStateButtons[state];
- let onSuccess = (component: Models.Components.Component): void => {
- //Updating the component from server response
-
- //the server returns only metaData (small component) except checkout (Full component) ,so we update only the statuses of distribution & lifecycle
- this.$scope.component.lifecycleState = component.lifecycleState;
- this.$scope.component.distributionStatus = component.distributionStatus;
-
- switch (data.url) {
- case 'lifecycleState/CHECKOUT':
- // only checkOut get the full component from server
- this.$scope.component = component;
- // Work around to change the csar version
- if (this.cacheService.get(Utils.Constants.CHANGE_COMPONENT_CSAR_VERSION_FLAG)) {
- (<Resource>this.$scope.component).csarVersion = this.cacheService.get(Utils.Constants.CHANGE_COMPONENT_CSAR_VERSION_FLAG);
- }
-
- //when checking out a minor version uuid remains
- let bcComponent: Sdc.Models.Components.Component = _.find(this.components, (item) => {
- return item.uuid === component.uuid;
- });
- if (bcComponent) {
- this.components[this.components.indexOf(bcComponent)] = component;
- } else {
- //when checking out a major(certified) version
- this.components.unshift(component);
- }
-
- this.$state.go(this.$state.current.name, {
- id: component.uniqueId,
- type: component.componentType.toLowerCase(),
- components: this.components
- });
- this.Notification.success({
- message: this.$filter('translate')("CHECKOUT_SUCCESS_MESSAGE_TEXT"),
- title: this.$filter('translate')("CHECKOUT_SUCCESS_MESSAGE_TITLE")
- });
- break;
- case 'lifecycleState/CHECKIN':
- defaultActionAfterChangeLifecycleState();
- this.Notification.success({
- message: this.$filter('translate')("CHECKIN_SUCCESS_MESSAGE_TEXT"),
- title: this.$filter('translate')("CHECKIN_SUCCESS_MESSAGE_TITLE")
- });
- break;
- case 'lifecycleState/UNDOCHECKOUT':
- defaultActionAfterChangeLifecycleState();
- this.Notification.success({
- message: this.$filter('translate')("DELETE_SUCCESS_MESSAGE_TEXT"),
- title: this.$filter('translate')("DELETE_SUCCESS_MESSAGE_TITLE")
- });
- break;
- case 'lifecycleState/certificationRequest':
- defaultActionAfterChangeLifecycleState();
- this.Notification.success({
- message: this.$filter('translate')("SUBMIT_FOR_TESTING_SUCCESS_MESSAGE_TEXT"),
- title: this.$filter('translate')("SUBMIT_FOR_TESTING_SUCCESS_MESSAGE_TITLE")
- });
- break;
- //Tester Role
- case 'lifecycleState/failCertification':
- defaultActionAfterChangeLifecycleState();
- this.Notification.success({
- message: this.$filter('translate')("REJECT_SUCCESS_MESSAGE_TEXT"),
- title: this.$filter('translate')("REJECT_SUCCESS_MESSAGE_TITLE")
- });
- break;
- case 'lifecycleState/certify':
- defaultActionAfterChangeLifecycleState();
- this.Notification.success({
- message: this.$filter('translate')("ACCEPT_TESTING_SUCCESS_MESSAGE_TEXT"),
- title: this.$filter('translate')("ACCEPT_TESTING_SUCCESS_MESSAGE_TITLE")
- });
- break;
- //DE203504 Bug Fix Start
- case 'lifecycleState/startCertification':
- this.initChangeLifecycleStateButtons();
- this.Notification.success({
- message: this.$filter('translate')("START_TESTING_SUCCESS_MESSAGE_TEXT"),
- title: this.$filter('translate')("START_TESTING_SUCCESS_MESSAGE_TITLE")
- });
- break;
- case 'lifecycleState/cancelCertification':
- this.initChangeLifecycleStateButtons();
- this.Notification.success({
- message: this.$filter('translate')("CANCEL_TESTING_SUCCESS_MESSAGE_TEXT"),
- title: this.$filter('translate')("CANCEL_TESTING_SUCCESS_MESSAGE_TITLE")
- });
- break;
- //Ops Role
- case 'distribution/PROD/activate':
- this.initChangeLifecycleStateButtons();
- this.Notification.success({
- message: this.$filter('translate')("DISTRIBUTE_SUCCESS_MESSAGE_TEXT"),
- title: this.$filter('translate')("DISTRIBUTE_SUCCESS_MESSAGE_TITLE")
- });
- break;
- //Governor Role
- case 'distribution-state/reject':
- this.initChangeLifecycleStateButtons();
- this.Notification.success({
- message: this.$filter('translate')("REJECT_SUCCESS_MESSAGE_TEXT"),
- title: this.$filter('translate')("REJECT_SUCCESS_MESSAGE_TITLE")
- });
- break;
- case 'distribution-state/approve':
- this.initChangeLifecycleStateButtons();
- this.$state.go('catalog');
- this.Notification.success({
- message: this.$filter('translate')("APPROVE_SUCCESS_MESSAGE_TEXT"),
- title: this.$filter('translate')("APPROVE_SUCCESS_MESSAGE_TITLE")
- });
- break;
- //DE203504 Bug Fix End
-
- default :
- defaultActionAfterChangeLifecycleState();
-
- }
- if (data.url != 'lifecycleState/CHECKOUT') {
- this.$scope.isLoading = false;
- }
- };
- //this.$scope.isLoading = true;
- this.ChangeLifecycleStateHandler.changeLifecycleState(this.$scope.component, data, this.$scope, onSuccess);
- };
-
- this.$scope.enabledTabs = (): void => {
- this.$scope.leftBarTabs.menuItems.forEach((item: Utils.MenuItem) => {
- item.isDisabled = false;
- });
- };
-
- this.$scope.isViewMode = (): boolean => {
- return this.$scope.mode === Utils.Constants.WorkspaceMode.VIEW;
- };
-
- this.$scope.isDesigner = (): boolean => {
- return this.role == Utils.Constants.Role.DESIGNER;
- };
-
- this.$scope.isDisableMode = (): boolean => {
- return this.$scope.mode === Utils.Constants.WorkspaceMode.VIEW && this.$scope.component.lifecycleState === Utils.Constants.ComponentState.NOT_CERTIFIED_CHECKIN;
- };
-
- this.$scope.showFullIcons = (): boolean => {
- //we show revert and save icons only in general\icon view
- return this.$state.current.name === Utils.Constants.States.WORKSPACE_GENERAL ||
- this.$state.current.name === Utils.Constants.States.WORKSPACE_ICONS;
- };
-
- this.$scope.isCreateMode = (): boolean => {
- return this.$scope.mode === Utils.Constants.WorkspaceMode.CREATE;
- };
-
- this.$scope.isEditMode = (): boolean => {
- return this.$scope.mode === Utils.Constants.WorkspaceMode.EDIT;
- };
-
- this.$scope.goToBreadcrumbHome = (): void => {
- let bcHome: Sdc.Utils.MenuItemGroup = this.$scope.breadcrumbsModel[0];
- this.$state.go(bcHome.menuItems[bcHome.selectedIndex].state);
- };
-
- this.$scope.showLifecycleIcon = (): boolean => {
- return this.role == Utils.Constants.Role.DESIGNER ||
- this.role == Utils.Constants.Role.PRODUCT_MANAGER;
- };
-
- this.$scope.getStatus = (): string => {
- if (this.$scope.isCreateMode()) {
- return 'IN DESIGN';
- }
-
- return this.$scope.component.getStatus(this.sdcMenu);
- };
-
- this.initMenuItems();
-
- this.$scope.showChangeStateButton = (): boolean => {
- let result: boolean = true;
- if (!this.$scope.component.isLatestVersion() && Utils.Constants.Role.OPS != this.role && Utils.Constants.Role.GOVERNOR != this.role) {
- result = false;
- }
- if (this.role === Utils.Constants.Role.PRODUCT_MANAGER && !this.$scope.component.isProduct()) {
- result = false;
- }
- if ((this.role === Utils.Constants.Role.DESIGNER || this.role === Utils.Constants.Role.TESTER)
- && this.$scope.component.isProduct()) {
- result = false;
- }
- if (Utils.Constants.ComponentState.NOT_CERTIFIED_CHECKOUT === this.$scope.component.lifecycleState && this.$scope.isViewMode()) {
- result = false;
- }
- if (Utils.Constants.ComponentState.CERTIFIED != this.$scope.component.lifecycleState &&
- (Utils.Constants.Role.OPS == this.role || Utils.Constants.Role.GOVERNOR == this.role)) {
- result = false;
- }
- return result;
- };
-
- this.$scope.updateSelectedMenuItem = (): void => {
- let selectedItem: Sdc.Utils.MenuItem = _.find(this.$scope.leftBarTabs.menuItems, (item: Sdc.Utils.MenuItem) => {
- return item.state === this.$state.current.name;
- });
- this.$scope.leftBarTabs.selectedIndex = selectedItem ? this.$scope.leftBarTabs.menuItems.indexOf(selectedItem) : 0;
- };
-
- this.$scope.$watch('$state.current.name', (newVal: string): void => {
- if (newVal) {
- this.$scope.isComposition = (newVal.indexOf(Utils.Constants.States.WORKSPACE_COMPOSITION) > -1);
- this.$scope.isDeployment = (newVal.indexOf(Utils.Constants.States.WORKSPACE_DEPLOYMENT) > -1);
- }
- });
- };
-
- private initAfterScope = (): void => {
- // In case user select csar from the onboarding modal, need to disable checkout and submit for testing.
- if (this.$state.params['disableButtons'] === true) {
- this.$scope.uploadFileChangedInGeneralTab();
- }
- };
-
- private initVersionObject = (): void => {
- this.$scope.versionsList = (this.$scope.component.getAllVersionsAsSortedArray()).reverse();
- this.$scope.changeVersion = {selectedVersion: _.find(this.$scope.versionsList, {versionId: this.$scope.component.uniqueId})};
- };
-
- private getNewComponentBreadcrumbItem = (): Utils.MenuItem => {
- let text = "";
- if (this.$scope.component.isResource() && (<Resource>this.$scope.component).isCsarComponent()) {
- text = this.$scope.component.getComponentSubType() + ': ' + this.$scope.component.name;
- } else {
- text = 'Create new ' + this.$state.params['type'];
- }
- return new Utils.MenuItem(text, null, Utils.Constants.States.WORKSPACE_GENERAL, 'goToState', [this.$state.params]);
- };
-
- private updateMenuItemByRole = (menuItems: Array<Utils.MenuItem>, role: string) => {
- let tempMenuItems: Array<Utils.MenuItem> = new Array<Utils.MenuItem>();
- menuItems.forEach((item: Utils.MenuItem) => {
- //remove item if role is disabled
- if (!(item.disabledRoles && item.disabledRoles.indexOf(role) > -1)) {
- tempMenuItems.push(item);
- }
- });
- return tempMenuItems;
- };
-
- private initBreadcrumbs = () => {
- this.components = this.cacheService.get('breadcrumbsComponents');
- let breadcrumbsComponentsLvl = this.MenuHandler.generateBreadcrumbsModelFromComponents(this.components, this.$scope.component);
-
- if (this.$scope.isCreateMode()) {
- let createItem = this.getNewComponentBreadcrumbItem();
- if (!breadcrumbsComponentsLvl.menuItems) {
- breadcrumbsComponentsLvl.menuItems = [];
- }
- breadcrumbsComponentsLvl.menuItems.unshift(createItem);
- breadcrumbsComponentsLvl.selectedIndex = 0;
- }
-
- this.$scope.breadcrumbsModel = [breadcrumbsComponentsLvl, this.$scope.leftBarTabs];
- };
-
- private initMenuItems() {
-
- let inCreateMode = this.$scope.isCreateMode();
- this.$scope.leftBarTabs = new Utils.MenuItemGroup();
- this.$scope.leftBarTabs.menuItems = this.updateMenuItemByRole(this.sdcMenu.component_workspace_menu_option[this.$scope.component.getComponentSubType()], this.role);
-
- this.$scope.leftBarTabs.menuItems.forEach((item: Utils.MenuItem) => {
- item.params = [item.state];
- item.callback = this.$scope.onMenuItemPressed;
- item.isDisabled = (inCreateMode && Utils.Constants.States.WORKSPACE_GENERAL != item.state) ||
- (Utils.Constants.States.WORKSPACE_DEPLOYMENT === item.state && this.$scope.component.groups.length === 0 && this.$scope.component.isResource());
- });
-
- if (this.cacheService.get('breadcrumbsComponents')) {
- this.initBreadcrumbs();
- } else {
- let onSuccess = (components: Array<Models.Components.Component>) => {
- this.cacheService.set('breadcrumbsComponents', components);
- this.initBreadcrumbs();
- };
- this.EntityService.getCatalog().then(onSuccess); //getAllComponents() doesnt return components from catalog
- }
- }
-
- private disableMenuItems() {
- this.$scope.leftBarTabs.menuItems.forEach((item: Utils.MenuItem) => {
- item.params = [item.state];
- item.callback = this.$scope.onMenuItemPressed;
- item.isDisabled = (Utils.Constants.States.WORKSPACE_GENERAL != item.state);
- });
- }
-
- private enableMenuItems() {
- this.$scope.leftBarTabs.menuItems.forEach((item: Utils.MenuItem) => {
- item.params = [item.state];
- item.callback = this.$scope.onMenuItemPressed;
- item.isDisabled = false;
- });
- }
-
- }
-}
-
-
diff --git a/catalog-ui/app/scripts/view-models/workspace/workspace.less b/catalog-ui/app/scripts/view-models/workspace/workspace.less
deleted file mode 100644
index d8bff1b634..0000000000
--- a/catalog-ui/app/scripts/view-models/workspace/workspace.less
+++ /dev/null
@@ -1,144 +0,0 @@
-.sdc-workspace-container {
- .bg_p;
-
- .add-btn {
- .f-color.a;
- .f-type._12_m;
- .hand;
- float: right;
- margin-bottom: 15px;
-
- &:before {
- .sprite-new;
- .plus-icon;
- margin-right: 5px;
- content: "";
-
- }
- &:hover {
- .f-color.b;
- &:before {
- .sprite-new;
- .plus-icon-hover;
- }
- }
-
- }
- .w-sdc-left-sidebar {
- padding: 3px 3px 0px 0px;
- background-color: @main_color_p;
- box-shadow: 7px -3px 6px -8px @main_color_n;
- z-index: 2;
- }
-
- .sdc-asset-creation-info {
- .n_12_r;
- float: right;
- margin: 8px 20px 0 0;
- }
-
- .w-sdc-main-right-container {
-
- padding: 0px 0px 0px 0px;
- background-color: @main_color_p;
- z-index: 1;
-
- .sdc-workspace-top-bar {
- height: @action_nav_height;
- padding: 12px 10px 0px 50px;
- border-bottom: 1px solid @main_color_o;
- display: flex;
- justify-content: space-between;
-
- .version-container {
-
- }
-
- .progress-container {
- flex-grow: 4;
- z-index: 10000000;
-
- .general-view-top-progress {
- width: 30%;
- margin: 0 auto;
- }
- }
-
- .not-latest {
- position: absolute;
- left: 24px;
- top: 20px;
- .sprite-new;
- .asdc-warning;
- }
-
- .sdc-workspace-top-bar-buttons {
-
- > button, > span:not(.delimiter) {
- margin-right: 10px;
- vertical-align: middle;
- .hand;
-
- &.sprite-new {
- text-indent: 100%;
- }
- &.disabled, &:hover.disabled {
- pointer-events: none;
- }
- }
- .delimiter {
- height: 32px;
- width: 1px;
- background-color: #959595;
- display: inline-block;
- vertical-align: middle;
- margin-right: 20px;
- }
-
- }
-
- .lifecycle-state {
- padding: 7px 0 0 10px;
- margin: 2px 0 7px 10px;
- border-left: 1px solid @main_color_o;
- line-height: 15px;
- font-family: @font-omnes-medium;
- color: @main_color_m;
-
- .lifecycle-state-icon {
- .sprite-new;
- }
- .lifecycle-state-text {
-
- font-weight: bold;
- text-transform: uppercase;
- vertical-align: top;
- padding: 3px;
- }
- }
-
- .version-selector {
- // float:left;
- background-color: transparent;
- border: none;
- margin-top: 6px;
- }
- }
- .w-sdc-main-container-body-content {
- height:100%;
-
- text-align: center;
- align-items: center;
- padding: 40px 14% 20px 14%;
- &.third-party {
- text-align: left;
- padding: 0;
- position: absolute;
- top: @action_nav_height;
- left: 0;
- right: 0;
- bottom: 0;
- }
- }
- }
-}
diff --git a/catalog-ui/app/styles/app.less b/catalog-ui/app/styles/app.less
deleted file mode 100644
index cec5b86753..0000000000
--- a/catalog-ui/app/styles/app.less
+++ /dev/null
@@ -1,122 +0,0 @@
-.sdc-main-container{
- width: 100%;
- height: 100%;
-}
-
-// injector:less
-@import 'animation.less';
-@import 'buttons.less';
-@import 'dark-header.less';
-@import 'fonts.less';
-@import 'form-elements.less';
-@import 'global.less';
-@import 'layout/header.less';
-@import 'layout/main.less';
-@import 'layout/sidebar.less';
-@import 'mixins.less';
-@import 'mixins_old.less';
-@import 'modal.less';
-@import 'scroller.less';
-@import 'sprite-old.less';
-@import 'sprite-product-icons.less';
-@import 'sprite-resource-icons.less';
-@import 'sprite-services-icons.less';
-@import 'sprite.less';
-@import 'table-flex.less';
-@import 'tlv-buttons.less';
-@import 'tlv-checkbox.less';
-@import 'tlv-loader.less';
-@import 'tlv-sprite.less';
-@import 'tooltips.less';
-@import 'variables-old.less';
-@import 'variables.less';
-@import 'welcome-sprite.less';
-@import 'welcome-style.less';
-@import '../scripts/directives/ecomp-header/ecomp-header.less';
-@import '../scripts/directives/edit-name-popover/edit-name-popover.less';
-@import '../scripts/directives/elements/checkbox/checkbox.less';
-@import '../scripts/directives/elements/radiobutton/radiobutton.less';
-@import '../scripts/directives/ellipsis/ellipsis-directive.less';
-@import '../scripts/directives/file-upload/file-upload.less';
-@import '../scripts/directives/graphs-v2/composition-graph/composition-graph.less';
-@import '../scripts/directives/graphs-v2/deployment-graph/deployment-graph.less';
-@import '../scripts/directives/graphs-v2/palette/palette.less';
-@import '../scripts/directives/graphs-v2/relation-menu/relation-menu.less';
-@import '../scripts/directives/info-tooltip/info-tooltip.less';
-@import '../scripts/directives/layout/top-nav/top-nav.less';
-@import '../scripts/directives/layout/top-progress/top-progress.less';
-@import '../scripts/directives/loader/loader-directive.less';
-@import '../scripts/directives/modal/sdc-modal.less';
-@import '../scripts/directives/page-scroller/page-scroller.less';
-@import '../scripts/directives/property-types/data-type-fields-structure/data-type-fields-structure.less';
-@import '../scripts/directives/property-types/type-list/type-list-directive.less';
-@import '../scripts/directives/property-types/type-map/type-map-directive.less';
-@import '../scripts/directives/sdc-tabs/sdc-single-tab/sdc-single-tab.less';
-@import '../scripts/directives/sdc-tabs/sdc-tabs.less';
-@import '../scripts/directives/structure-tree/structure-tree-directive.less';
-@import '../scripts/directives/tag/tag-directive.less';
-@import '../scripts/directives/tutorial/tutorial-directive.less';
-@import '../scripts/directives/user-header-details/user-header-details-directive.less';
-@import '../scripts/directives/utils/expand-collapse-menu-box/expand-collapse-menu-box.less';
-@import '../scripts/directives/utils/expand-collapse/expand-collapse.less';
-@import '../scripts/directives/utils/page-selector/page-selector.less';
-@import '../scripts/directives/utils/sdc-tags/sdc-tags.less';
-@import '../scripts/directives/utils/sdc_messages/sdc-messages.less';
-@import '../scripts/directives/utils/wizard_steps/sdc-wizard-steps.less';
-@import '../scripts/view-models/admin-dashboard/add-category-modal/add-category-modal-view.less';
-@import '../scripts/view-models/admin-dashboard/admin-dashboard.less';
-@import '../scripts/view-models/admin-dashboard/category-management/category-management.less';
-@import '../scripts/view-models/admin-dashboard/user-management/user-management.less';
-@import '../scripts/view-models/catalog/catalog.less';
-@import '../scripts/view-models/component-viewer/activity-log/activity-log-view.less';
-@import '../scripts/view-models/component-viewer/component-viewer.less';
-@import '../scripts/view-models/component-viewer/properties/properties-view.less';
-@import '../scripts/view-models/dashboard/dashboard.less';
-@import '../scripts/view-models/forms/artifact-form/artifact-form.less';
-@import '../scripts/view-models/forms/env-parameters-form/env-parameters-form.less';
-@import '../scripts/view-models/forms/property-form/property-form.less';
-@import '../scripts/view-models/forms/resource-instance-name-form/resource-instance-name.less';
-@import '../scripts/view-models/modals/confirmation-modal/confirmation-modal.less';
-@import '../scripts/view-models/modals/email-modal/email-modal.less';
-@import '../scripts/view-models/modals/error-modal/error.less';
-@import '../scripts/view-models/modals/message-modal/message-client-modal/client-message-modal.less';
-@import '../scripts/view-models/modals/message-modal/message-server-modal/server-message-modal.less';
-@import '../scripts/view-models/modals/onboarding-modal/onboarding-modal.less';
-@import '../scripts/view-models/onboard-vendor/onboard-vendor.less';
-@import '../scripts/view-models/preloading/preloading-view.less';
-@import '../scripts/view-models/support/support.less';
-@import '../scripts/view-models/tabs/general-tab.less';
-@import '../scripts/view-models/tabs/hierarchy/hierarchy.less';
-@import '../scripts/view-models/tutorial-end/tutorial-end.less';
-@import '../scripts/view-models/wizard/artifact-deployment-step/artifact-deployment-step.less';
-@import '../scripts/view-models/wizard/artifact-form-step/artifact-form-step.less';
-@import '../scripts/view-models/wizard/artifact-information-step/artifact-information-step.less';
-@import '../scripts/view-models/wizard/general-step/general-step.less';
-@import '../scripts/view-models/wizard/hierarchy-step/hierarchy-step.less';
-@import '../scripts/view-models/wizard/icons-step/icons-step.less';
-@import '../scripts/view-models/wizard/properties-step/properties-step.less';
-@import '../scripts/view-models/wizard/property-form/property-form.less';
-@import '../scripts/view-models/wizard/wizard-creation-base.less';
-@import '../scripts/view-models/workspace/tabs/activity-log/activity-log.less';
-@import '../scripts/view-models/workspace/tabs/attributes/attributes.less';
-@import '../scripts/view-models/workspace/tabs/composition/composition.less';
-@import '../scripts/view-models/workspace/tabs/composition/tabs/artifacts/artifacts.less';
-@import '../scripts/view-models/workspace/tabs/composition/tabs/details/details.less';
-@import '../scripts/view-models/workspace/tabs/composition/tabs/properties-and-attributes/properties.less';
-@import '../scripts/view-models/workspace/tabs/composition/tabs/relations/relations.less';
-@import '../scripts/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts.less';
-@import '../scripts/view-models/workspace/tabs/deployment/deployment.less';
-@import '../scripts/view-models/workspace/tabs/distribution/disribution-status-modal/disribution-status-modal.less';
-@import '../scripts/view-models/workspace/tabs/distribution/distribution.less';
-@import '../scripts/view-models/workspace/tabs/general/general.less';
-@import '../scripts/view-models/workspace/tabs/icons/icons.less';
-@import '../scripts/view-models/workspace/tabs/information-artifacts/information-artifacts.less';
-@import '../scripts/view-models/workspace/tabs/inputs/inputs.less';
-@import '../scripts/view-models/workspace/tabs/inputs/resource-input/resource-inputs.less';
-@import '../scripts/view-models/workspace/tabs/inputs/service-input/service-inputs.less';
-@import '../scripts/view-models/workspace/tabs/product-hierarchy/product-hierarchy.less';
-@import '../scripts/view-models/workspace/tabs/properties/properties.less';
-@import '../scripts/view-models/workspace/tabs/req-and-capabilities/req-and-capabilities.less';
-@import '../scripts/view-models/workspace/tabs/tosca-artifacts/tosca-artifacts.less';
-@import '../scripts/view-models/workspace/workspace.less';
-// endinjector:less
diff --git a/catalog-ui/app/styles/images/resource-icons/compute-uncertified.png b/catalog-ui/app/styles/images/resource-icons/compute-uncertified.png
deleted file mode 100644
index f1254d2dfc..0000000000
--- a/catalog-ui/app/styles/images/resource-icons/compute-uncertified.png
+++ /dev/null
Binary files differ
diff --git a/catalog-ui/app/styles/images/sprites/sprite-global.png b/catalog-ui/app/styles/images/sprites/sprite-global.png
deleted file mode 100644
index bb2334216a..0000000000
--- a/catalog-ui/app/styles/images/sprites/sprite-global.png
+++ /dev/null
Binary files differ
diff --git a/catalog-ui/app/styles/images/welcome/SD&C_Welcome15.jpg b/catalog-ui/app/styles/images/welcome/SD&C_Welcome15.jpg
deleted file mode 100644
index b53b229546..0000000000
--- a/catalog-ui/app/styles/images/welcome/SD&C_Welcome15.jpg
+++ /dev/null
Binary files differ
diff --git a/catalog-ui/app/styles/images/welcome/SD&C_Welcome15_b.jpg b/catalog-ui/app/styles/images/welcome/SD&C_Welcome15_b.jpg
deleted file mode 100644
index bae42eb7d6..0000000000
--- a/catalog-ui/app/styles/images/welcome/SD&C_Welcome15_b.jpg
+++ /dev/null
Binary files differ
diff --git a/catalog-ui/app/styles/images/welcome/bg/001.jpg b/catalog-ui/app/styles/images/welcome/bg/001.jpg
deleted file mode 100644
index 19bc76b300..0000000000
--- a/catalog-ui/app/styles/images/welcome/bg/001.jpg
+++ /dev/null
Binary files differ
diff --git a/catalog-ui/app/styles/images/welcome/bg/002.jpg b/catalog-ui/app/styles/images/welcome/bg/002.jpg
deleted file mode 100644
index 7d5fc2ef12..0000000000
--- a/catalog-ui/app/styles/images/welcome/bg/002.jpg
+++ /dev/null
Binary files differ
diff --git a/catalog-ui/app/styles/images/welcome/bg/003.png b/catalog-ui/app/styles/images/welcome/bg/003.png
deleted file mode 100644
index c33b14fe9c..0000000000
--- a/catalog-ui/app/styles/images/welcome/bg/003.png
+++ /dev/null
Binary files differ
diff --git a/catalog-ui/app/styles/images/welcome/bg/004.png b/catalog-ui/app/styles/images/welcome/bg/004.png
deleted file mode 100644
index 08578bb1ec..0000000000
--- a/catalog-ui/app/styles/images/welcome/bg/004.png
+++ /dev/null
Binary files differ
diff --git a/catalog-ui/app/styles/images/welcome/bg/bg02.png b/catalog-ui/app/styles/images/welcome/bg/bg02.png
deleted file mode 100644
index 3b10aa45f7..0000000000
--- a/catalog-ui/app/styles/images/welcome/bg/bg02.png
+++ /dev/null
Binary files differ
diff --git a/catalog-ui/app/styles/images/welcome/bg/bg03.png b/catalog-ui/app/styles/images/welcome/bg/bg03.png
deleted file mode 100644
index 50fe924f5d..0000000000
--- a/catalog-ui/app/styles/images/welcome/bg/bg03.png
+++ /dev/null
Binary files differ
diff --git a/catalog-ui/app/styles/images/welcome/bg/connection02.png b/catalog-ui/app/styles/images/welcome/bg/connection02.png
deleted file mode 100644
index 157acba384..0000000000
--- a/catalog-ui/app/styles/images/welcome/bg/connection02.png
+++ /dev/null
Binary files differ
diff --git a/catalog-ui/app/styles/images/welcome/bg/connection03.png b/catalog-ui/app/styles/images/welcome/bg/connection03.png
deleted file mode 100644
index 01f21fcf41..0000000000
--- a/catalog-ui/app/styles/images/welcome/bg/connection03.png
+++ /dev/null
Binary files differ
diff --git a/catalog-ui/app/styles/images/welcome/bg/connection04.png b/catalog-ui/app/styles/images/welcome/bg/connection04.png
deleted file mode 100644
index 174dbfe5dd..0000000000
--- a/catalog-ui/app/styles/images/welcome/bg/connection04.png
+++ /dev/null
Binary files differ
diff --git a/catalog-ui/app/styles/images/welcome/bg/global.png b/catalog-ui/app/styles/images/welcome/bg/global.png
deleted file mode 100644
index 09b366404e..0000000000
--- a/catalog-ui/app/styles/images/welcome/bg/global.png
+++ /dev/null
Binary files differ
diff --git a/catalog-ui/app/styles/images/welcome/bg/shape02.png b/catalog-ui/app/styles/images/welcome/bg/shape02.png
deleted file mode 100644
index 91400da15d..0000000000
--- a/catalog-ui/app/styles/images/welcome/bg/shape02.png
+++ /dev/null
Binary files differ
diff --git a/catalog-ui/app/styles/images/welcome/bg/shape03.png b/catalog-ui/app/styles/images/welcome/bg/shape03.png
deleted file mode 100644
index af6384674b..0000000000
--- a/catalog-ui/app/styles/images/welcome/bg/shape03.png
+++ /dev/null
Binary files differ
diff --git a/catalog-ui/app/styles/images/welcome/bg/shape04.png b/catalog-ui/app/styles/images/welcome/bg/shape04.png
deleted file mode 100644
index 36759df6e5..0000000000
--- a/catalog-ui/app/styles/images/welcome/bg/shape04.png
+++ /dev/null
Binary files differ
diff --git a/catalog-ui/app/styles/images/welcome/bg/shape05.png b/catalog-ui/app/styles/images/welcome/bg/shape05.png
deleted file mode 100644
index 336411fd80..0000000000
--- a/catalog-ui/app/styles/images/welcome/bg/shape05.png
+++ /dev/null
Binary files differ
diff --git a/catalog-ui/app/styles/images/welcome/laptop.png b/catalog-ui/app/styles/images/welcome/laptop.png
deleted file mode 100644
index 160e743d1b..0000000000
--- a/catalog-ui/app/styles/images/welcome/laptop.png
+++ /dev/null
Binary files differ
diff --git a/catalog-ui/app/styles/images/welcome/logo_att.png b/catalog-ui/app/styles/images/welcome/logo_att.png
deleted file mode 100644
index e145a1ae5d..0000000000
--- a/catalog-ui/app/styles/images/welcome/logo_att.png
+++ /dev/null
Binary files differ
diff --git a/catalog-ui/app/styles/images/welcome/ss-01.png b/catalog-ui/app/styles/images/welcome/ss-01.png
deleted file mode 100644
index abd4cd7a46..0000000000
--- a/catalog-ui/app/styles/images/welcome/ss-01.png
+++ /dev/null
Binary files differ
diff --git a/catalog-ui/app/styles/images/welcome/ss-02.png b/catalog-ui/app/styles/images/welcome/ss-02.png
deleted file mode 100644
index d4d0038b64..0000000000
--- a/catalog-ui/app/styles/images/welcome/ss-02.png
+++ /dev/null
Binary files differ
diff --git a/catalog-ui/app/styles/images/welcome/ss-03.png b/catalog-ui/app/styles/images/welcome/ss-03.png
deleted file mode 100644
index 9a259ca7c2..0000000000
--- a/catalog-ui/app/styles/images/welcome/ss-03.png
+++ /dev/null
Binary files differ
diff --git a/catalog-ui/app/styles/welcome-style.less b/catalog-ui/app/styles/welcome-style.less
deleted file mode 100644
index 0d969878c7..0000000000
--- a/catalog-ui/app/styles/welcome-style.less
+++ /dev/null
@@ -1,651 +0,0 @@
-@zoom-in-animation-play: 2s;
-@zoom-in-animation: 3s;
-@slide-fade-in-text-main-animation: 2s;
-
-html,
-body {
- height: 100%;
- /*overflow-x: hidden;*/
-}
-
-* {
- box-sizing: border-box;
-}
-
-body {
- background-image: url(images/welcome/bg/global.png);
-}
-
-.sdc-welcome-new-page {
-
- opacity: 1;
- height: 100%;
- background-color: @main_color_l;
-
- .os-welcome {
- top: 47%;
- position: fixed;
- left: 42%;
- font-size: 40px;
- }
-
- #slide-2, #slide-3, #slide-4, #slide-5 {
- padding: 0 50px 0 30px;
- }
-
- .visible {
- visibility: visible;
- }
-
- .asdc-welcome-close {
- position: absolute;
- right: 38px;
- top: 30px;
- z-index: 101;
- cursor: pointer;
-
- .sprite-welcome;
- .sprite-welcome.close;
-
- &:hover {
- .sprite-welcome.close_white;
- }
- }
-
- .asdc-welcome-frame {
- height: 100vh;
- width: 100%;
- background-size: cover;
- position: relative;
- display: flex;
- align-items: center;
- justify-content: center;
- }
-
- .asdc-welcome-frame.frame-0 {
- background-image: url(images/welcome/bg/002.jpg);
- background-size: cover;
-
- .asdc-whats-new {
-
- z-index: 1;
-
- .news-items-row {
- display: flex;
- flex-direction: row;
-
- .news-item-wrapper {
- width: 250px;
- height: 343px;
- background-color: @main_color_p;
- margin: 16px;
- padding: 40px 20px 20px 20px;
- border-radius: 4px;
- opacity: 0;
-
- ul {
- padding-left: 17px;
- li {
- list-style: disc;
- }
- }
-
- ol {
- padding-left: 12px;
- }
-
- &.bg-1 {border-bottom: solid 5px @main_color_a;}
- &.bg-2 {border-bottom: solid 5px @main_color_j;}
- &.bg-3 {border-bottom: solid 5px @main_color_d;}
- &.bg-4 {border-bottom: solid 5px @main_color_i;}
- &.bg-5 {border-bottom: solid 5px @main_color_e;}
- &.bg-6 {border-bottom: solid 5px @func_color_b;}
- &.bg-7 {border-bottom: solid 5px @main_color_c;}
- &.bg-8 {border-bottom: solid 5px @main_color_k;}
-
- .news-body {
- .m_14_r;
- }
- .news-title {
- margin-bottom: 20px;
- .s_18_m;
- }
- }
- }
-
-
- }
- }
-
- .asdc-welcome-frame.frame-01 {
- background-image: url(images/welcome/bg/002.png);
- background-size: cover;
- }
-
- .asdc-welcome-frame.frame-02 .asdc-welcome-slide-image-box {
- position: absolute;
- right: 11.6vw;
- top: 10.5vw;
- z-index: 1;
- }
-
- .asdc-welcome-frame.frame-02 .asdc-welcome-slide-text-box {
- position: absolute;
- top: 33%;
- left: 10%;
- z-index: 1;
- }
-
- .asdc-welcome-frame.frame-02 .asdc-welcome-frame-shape {
- background-image: url(images/welcome/bg/shape02.png);
- position: absolute;
- height: 19vw;
- width: 19vw;
- top: 2.1vw;
- left: 32.1vw;
- /* opacity: .3; */
- background-size: contain;
- /* background-repeat: no-repeat; */
- z-index: 0;
- visibility: hidden;
-
- animation-duration: @zoom-in-animation;
- -moz-animation-duration: @zoom-in-animation;
- -webkit-animation-duration: @zoom-in-animation;
- }
-
- .asdc-welcome-frame.frame-02 .asdc-welcome-frame-connection {
- background-image: url(images/welcome/bg/connection02.png);
- width: 56px;
- height: 27vw;
- position: absolute;
- bottom: 0;
- right: 295px;
- background-position: 0px 35vw;
- }
-
- .asdc-welcome-frame.frame-03 .asdc-welcome-slide-image-box {
- position: absolute;
- left: 6%;
- top: 20%;
- z-index: 1;
- }
-
- .asdc-welcome-frame.frame-03 .asdc-welcome-slide-text-box {
- position: absolute;
- top: 38%;
- right: 14.2vw;
- z-index: 1;
- }
-
- .asdc-welcome-frame.frame-03 .asdc-welcome-frame-shape {
- background-image: url(images/welcome/bg/shape03.png);
- position: absolute;
- height: 378px;
- width: 252px;
- top: 0vw;
- right: 195px;
- background-size: contain;
- z-index: 0;
- visibility: hidden;
-
- animation-duration: @zoom-in-animation;
- -moz-animation-duration: @zoom-in-animation;
- -webkit-animation-duration: @zoom-in-animation;
- }
-
- .asdc-welcome-frame.frame-03 .asdc-welcome-frame-connection {
- background-image: url(images/welcome/bg/connection03.png);
- width: 204px;
- height: 371px;
- position: absolute;
- bottom: -109px;
- right: 590px;
- }
-
- .asdc-welcome-frame.frame-04 .asdc-welcome-slide-image-box {
- position: absolute;
- right: 10%;
- top: 20%;
- z-index: 5;
- }
-
- .asdc-welcome-frame.frame-04 .asdc-welcome-slide-text-box {
- position: absolute;
- top: 34%;
- left: 8%;
- z-index: 5;
- }
-
- .asdc-welcome-frame.frame-04 .asdc-welcome-frame-connection {
- background-image: url(images/welcome/bg/connection04.png);
- width: 56px;
- height: 752px;
- position: absolute;
- bottom: -143px;
- right: 946px;
- }
-
- .asdc-welcome-frame.frame-04 .asdc-welcome-frame-shape {
- background-image: url(images/welcome/bg/shape04.png);
- position: absolute;
- height: 412px;
- width: 355px;
- top: 0;
- right: 734px;
- z-index: 1;
- visibility: hidden;
-
- animation-duration: @zoom-in-animation;
- -moz-animation-duration: @zoom-in-animation;
- -webkit-animation-duration: @zoom-in-animation;
- }
-
- .asdc-welcome-frame.frame-05 .asdc-welcome-slide-text-box {
- position: absolute;
- top: 29%;
- right: 10%;
- z-index: 5;
- }
-
- .asdc-welcome-frame.frame-05 .asdc-welcome-frame-shape {
- background-image: url(images/welcome/bg/shape05.png);
- position: absolute;
- height: 794px;
- width: 597px;
- top: 0;
- right: 40%;
- z-index: 1;
- visibility: hidden;
-
- animation-duration: @zoom-in-animation;
- -moz-animation-duration: @zoom-in-animation;
- -webkit-animation-duration: @zoom-in-animation;
- }
-
- .asdc-welcome-frame.frame-06 {
- background-image: url(images/welcome/bg/004.png);
- background-size: cover;
- }
-
- .asdc-welcome-frame.frame-06 .asdc-welcome-main {
- bottom: 30%;
- }
-
- .asdc-welcome-header {
- /*background-color: rgba(17, 21, 33, 0.52);*/
- height: 70px;
- width: 100%;
- padding: 55px 0 0 65px;
- color: #fff;
- z-index: 1;
- position: absolute;
- left: 0;
- top: 0;
- }
-
- .welcome-nav {
- visibility: hidden;
- }
-
- .welcome-logo {
- cursor: pointer;
- }
-
- #sdc-welcome-video-wrapper {
- opacity: 0;
- }
-
- .asdc-welcome-video-close {
- position: absolute;
- top: 30px;
- right: 30px;
- z-index: 1;
- }
-
- .asdc-welcome-video {
- position: fixed;
- top: 50%;
- left: 50%;
- min-width: 100%;
- min-height: 100%;
- width: auto;
- height: auto;
- -webkit-transform: translateX(-50%) translateY(-50%);
- transform: translateX(-50%) translateY(-50%);
- }
-
- .asdc-welcome-video-icon {
- cursor: pointer;
- /*margin-bottom: 80px;*/
- visibility: hidden;
- width: 140px;
- margin: 0 auto;
- right: -24px;
- position: relative;
-
- animation-duration: @zoom-in-animation-play;
- -moz-animation-duration: @zoom-in-animation-play;
- -webkit-animation-duration: @zoom-in-animation-play;
-
- .asdc-welcome-video-icon-play {
- position: absolute;
- top: -11px;
- left: -11px;
- z-index: 1;
- }
-
- .asdc-welcome-video-icon-play:hover + .asdc-welcome-inner-circle {
- -webkit-animation-play-state: running;
- -moz-animation-play-state: running;
- animation-play-state: running;
-
- -webkit-transform: rotate(360deg);
- -moz-transform: rotate(360deg);
- transform: rotate(360deg);
-
- -webkit-animation:turning_acw 3s;
- -moz-animation:turning_acw 3s;
- animation:turning_acw 3s;
-
- -webkit-animation-iteration-count: 99;
- -moz-animation-iteration-count: 99;
- animation-iteration-count: 99;
- }
-
- .asdc-welcome-inner-circle {
- border: 2px solid #ECEBFA;
- border-left-color:#666666;
- border-right-color:#999999;
- .opacity(0.5);
-
- -webkit-transform: rotate(360deg);
- -moz-transform: rotate(360deg);
- transform: rotate(360deg);
-
- position:absolute;
-
- width: 96px;
- height: 96px;
-
- .border-radius(96px);
-
- -webkit-animation:turning_acw 3s;
- -moz-animation:turning_acw 3s;
- animation:turning_acw 3s;
-
- -webkit-animation-iteration-count: 3;
- -moz-animation-iteration-count: 3;
- animation-iteration-count: 3;
- }
- }
-
- /*@-webkit-keyframes turning_acw {
- 0%{
- -webkit-transform: rotate(360deg); }
- 100%{
- -webkit-transform: rotate(0deg); }
- }
-
- @-moz-keyframes turning_acw {
- 0%{
- -moz-transform: rotate(360deg); }
- 100%{
- -moz-transform: rotate(0deg); }
- }*/
-
- @keyframes turning_acw {
- 0%{
- transform: rotate(360deg); }
- 100%{
- transform: rotate(0deg); }
- }
-
- .asdc-welcome-title {
- color: #373f51;
- font-size: 2.4vw;
- font-family: omnes-light;
- line-height: 1.0em;
- letter-spacing: -0.01em;
- }
-
- .asdc-welcome-main {
- text-align: center;
- position: absolute;
- bottom: 40%;
- z-index: 1;
- color: #fff;
- left: 0;
- width: 100%;
- }
-
- .whats-new {
- .p_16_r;
- position: absolute;
- left: 205px;
- top: 45px;
- cursor: pointer;
- text-decoration: none;
- }
-
- .asdc-welcome-main-title {
- color: #fff;
- font-size: 62px;
- font-family: omnes-light;
- visibility: hidden;
- height: 72px;
-
- animation-duration: @slide-fade-in-text-main-animation;
- -moz-animation-duration: @slide-fade-in-text-main-animation;
- -webkit-animation-duration: @slide-fade-in-text-main-animation;
- }
-
- .asdc-welcome-main-message {
- font-size: 28px;
- font-family: omnes-light;
- line-height: 1.8em;
- visibility: hidden;
-
- animation-duration: @slide-fade-in-text-main-animation;
- -moz-animation-duration: @slide-fade-in-text-main-animation;
- -webkit-animation-duration: @slide-fade-in-text-main-animation;
- }
-
- .asdc-welcome-main-back-btn-ph {
- margin: 24px 0 70px;
- }
-
- .asdc-welcome-main-back-btn {
- font-size: 16px;
- color: #009fdb;
- font-family: omnes-medium;
- border: 2px solid;
- border-radius: 3px;
- line-height: 40px;
- min-width: 242px;
- display: inline-block;
- visibility: hidden;
- text-decoration: none;
-
- &:hover {
- color: #33bfec;
- border-color: #33bfec;
- }
- }
-
- .asdc-welcome-cover {
- position: absolute;
- top: 0px;
- right: 0;
- left: 0;
- bottom: 0;
- background-color: rgba(14, 13, 12, 0.8);
- z-index: 0;
- }
-
- .asdc-welcome-slide-text-box {
- border-radius: 10px;
- background-color: #fff;
- padding: 10px;
- }
-
- .asdc-welcome-slide-text-box-title {
- color: #373f51;
- font-size: 2.4vw;
- font-family: omnes-light;
- letter-spacing: -0.015em;
- line-height: 1.04em;
- visibility: hidden;
-
- animation-duration: @slide-fade-in-text-main-animation;
- -moz-animation-duration: @slide-fade-in-text-main-animation;
- -webkit-animation-duration: @slide-fade-in-text-main-animation;
- }
-
- .asdc-welcome-slide-text-box-content {
- color: #737b81;
- font-size: 1vw;
- font-family: omnes-light;
- padding-top: .5vw;
- line-height: 1.3em;
- visibility: hidden;
-
- animation-duration: @slide-fade-in-text-main-animation;
- -moz-animation-duration: @slide-fade-in-text-main-animation;
- -webkit-animation-duration: @slide-fade-in-text-main-animation;
- }
-
- .asdc-welcome-slide-image-box {
- box-shadow: 1px 1px 5px 0px rgba(0, 0, 0, 0.2);
- height: 29.6vw;
- width: 40vw;
- }
-
- .asdc-welcome-slide-image {
- height: 100%;
- width: 100%;
- }
-
- /*.asdc-welcome-frame-content {*/
- /*display: flex;*/
- /*justify-content: center;*/
- /*align-items: center;*/
- /*}*/
- /*.asdc-welcome-frame-content-text {*/
- /*color: #666;*/
- /*font-size: 16px;*/
- /*font-family: omnes-light;*/
- /*margin-top: 30px;*/
- /*line-height: 1.6em;*/
- /*}*/
- /*.asdc-welcome-frame-content-text-p {*/
- /*position: relative;*/
- /*}*/
- /*.asdc-welcome-frame-content-text-p-icon {*/
- /*position: absolute;*/
- /*height: 25px;*/
- /*width: 25px;*/
- /*left: -40px;*/
- /*top: 10px;*/
- /*}*/
- /*.asdc-welcome-frame.frame-02 .asdc-welcome-frame-content-right,*/
- /*.asdc-welcome-frame.frame-04 .asdc-welcome-frame-content-right {*/
- /*max-width: 30%;*/
- /*flex: 1;*/
- /*margin-left: 5%;*/
- /*}*/
- /*.asdc-welcome-frame.frame-02 .asdc-welcome-frame-content-left,*/
- /*.asdc-welcome-frame.frame-04 .asdc-welcome-frame-content-left {*/
- /*max-width: 55%;*/
- /*flex: 1;*/
- /*}*/
- /*.asdc-welcome-frame.frame-04 .asdc-welcome-frame-content-img {*/
- /*width: 36vw;*/
- /*}*/
- /*.asdc-welcome-frame.frame-03 .asdc-welcome-frame-content-left {*/
- /*max-width: 30%;*/
- /*flex: 1;*/
- /*margin-right: 5%;*/
- /*}*/
- /*.asdc-welcome-frame.frame-03 .asdc-welcome-frame-content-right {*/
- /*max-width: 55%;*/
- /*flex: 1;*/
- /*}*/
- /*.asdc-welcome-frame.frame-03 .asdc-welcome-frame-content-img {*/
- /*left: 0;*/
- /*right: auto;*/
- /*}*/
- /*.asdc-welcome-frame.frame-03 .asdc-welcome-frame-content-img-bubble {*/
- /*left: auto;*/
- /*top: 0;*/
- /*position: absolute;*/
- /*right: 0;*/
- /*top: -7vh;*/
- /*}*/
- /*.asdc-welcome-frame.frame-05 .asdc-welcome-frame-content{*/
- /*color: #fff;*/
- /*font-size: 37px;*/
- /*font-family: omnes-light;*/
- /*flex-direction: column;*/
- /*}*/
- /*.asdc-welcome-frame-content-img-ph {*/
- /*position: relative;*/
- /*!*width: 42%*!*/
- /*!*width: 840px;*!*/
- /*!*height: 674px;*!*/
- /*width: 52vw;*/
- /*height: 39vw;*/
- /*}*/
- /*.asdc-welcome-frame-content-img {*/
- /*width: 45vw;*/
- /*position: absolute;*/
- /*z-index: 1;*/
- /*right: 0;*/
- /*bottom: 0;*/
- /*}*/
- /*.asdc-welcome-frame-content-img-bubble {*/
- /*border-radius: 50%;*/
- /*height: 38vw;*/
- /*width: 38vw;*/
- /*position: absolute;*/
- /*left: 0;*/
- /*top: 0;*/
- /*position: absolute;*/
- /*right: 0;*/
- /*top: -7vh;*/
- /*}*/
- /*.asdc-welcome-frame-content-img-bubble.blue {*/
- /*background: linear-gradient(to right, #067ab4 0%, #44c8f5 100%);*/
- /*}*/
- /*.asdc-welcome-frame-content-img-bubble.green {*/
- /*background: linear-gradient(to right, #77be46 0%, #d2e15f 100%);*/
- /*}*/
- /*.asdc-welcome-frame-content-img-bubble.purple {*/
- /*background: linear-gradient(to right, #8a559f 0%, #d6b7e5 100%);*/
- /*}*/
- /*.asdc-welcome-button {*/
- /*font-family: omnes-medium;*/
- /*font-size: 14px;*/
- /*background-color: #009fdb;*/
- /*text-decoration: none;*/
- /*border: 0;*/
- /*border-radius: 4px;*/
- /*color: #fff;*/
- /*text-align: center;*/
- /*line-height: 30px;*/
- /*min-width: 200px;*/
- /*margin-top: 50px;*/
- /*}*/
- .asdc-welcome-footer {
- background-color: #000;
- position: absolute;
- bottom: 0;
- width: 100%;
- font-size: 12px;
- padding: 20px 10%;
- left: 0;
- color: #fff;
- text-align: center;
- }
-
-}
diff --git a/catalog-ui/app/third-party/ng-infinite-scroll/.npmignore b/catalog-ui/app/third-party/ng-infinite-scroll/.npmignore
deleted file mode 100644
index dcbd092327..0000000000
--- a/catalog-ui/app/third-party/ng-infinite-scroll/.npmignore
+++ /dev/null
@@ -1,3 +0,0 @@
-compile/*
-node_modules
-.tmp
diff --git a/catalog-ui/app/third-party/ng-infinite-scroll/.travis.yml b/catalog-ui/app/third-party/ng-infinite-scroll/.travis.yml
deleted file mode 100644
index ee95ccb343..0000000000
--- a/catalog-ui/app/third-party/ng-infinite-scroll/.travis.yml
+++ /dev/null
@@ -1,12 +0,0 @@
-language: node_js
-node_js:
- - 0.10
-
-install:
- - npm install
-
-before_script:
- - npm install -g grunt-cli
-
-script:
- - grunt test:protractor-travis
diff --git a/catalog-ui/app/third-party/ng-infinite-scroll/Gruntfile.coffee b/catalog-ui/app/third-party/ng-infinite-scroll/Gruntfile.coffee
deleted file mode 100644
index a9b9405731..0000000000
--- a/catalog-ui/app/third-party/ng-infinite-scroll/Gruntfile.coffee
+++ /dev/null
@@ -1,110 +0,0 @@
-module.exports = (grunt) ->
- grunt.loadNpmTasks 'grunt-coffeelint'
- grunt.loadNpmTasks 'grunt-contrib-clean'
- grunt.loadNpmTasks 'grunt-contrib-coffee'
- grunt.loadNpmTasks 'grunt-contrib-concat'
- grunt.loadNpmTasks 'grunt-contrib-connect'
- grunt.loadNpmTasks 'grunt-contrib-uglify'
- grunt.loadNpmTasks 'grunt-protractor-runner'
-
- sauceUser = 'pomerantsevp'
- sauceKey = '497ab04e-f31b-4a7b-9b18-ae3fbe023222'
-
- grunt.initConfig
- pkg: grunt.file.readJSON 'package.json'
- meta:
- banner: '/* <%= pkg.name %> - v<%= pkg.version %> - <%= grunt.template.today("yyyy-mm-dd") %> */\n'
- coffeelint:
- src: 'src/**/*.coffee'
- options:
- max_line_length:
- level: 'ignore'
- line_endings:
- value: 'unix'
- level: 'error'
- no_stand_alone_at:
- level: 'error'
- clean:
- options:
- force: true
- build: ["compile/**", "build/**"]
- coffee:
- compile:
- files: [
- {
- expand: true
- cwd: 'src/'
- src: '**/*.coffee'
- dest: 'compile/'
- ext: '.js'
- }
- ],
- options:
- bare: true
- concat:
- options:
- banner: '<%= meta.banner %>'
- dist:
- src: 'compile/**/*.js'
- dest: 'build/ng-infinite-scroll.js'
- uglify:
- options:
- banner: '<%= meta.banner %>'
- dist:
- src: ['build/ng-infinite-scroll.js']
- dest: 'build/ng-infinite-scroll.min.js'
- connect:
- testserver:
- options:
- port: 8000
- hostname: '0.0.0.0'
- middleware: (connect, options) ->
- base = if Array.isArray(options.base) then options.base[options.base.length - 1] else options.base
- [connect.static(base)]
- protractor:
- local:
- options:
- configFile: 'test/protractor-local.conf.js'
- args:
- params:
- testThrottleValue: 500
- travis:
- options:
- configFile: 'test/protractor-travis.conf.js'
- args:
- params:
- # When using Sauce Connect, we should use a large timeout
- # since everything is generally much slower than when testing locally.
- testThrottleValue: 10000
- sauceUser: sauceUser
- sauceKey: sauceKey
-
- grunt.registerTask 'webdriver', () ->
- done = this.async()
- p = require('child_process').spawn('node', ['node_modules/protractor/bin/webdriver-manager', 'update'])
- p.stdout.pipe(process.stdout)
- p.stderr.pipe(process.stderr)
- p.on 'exit', (code) ->
- if code isnt 0 then grunt.fail.warn('Webdriver failed to update')
- done()
-
- grunt.registerTask 'sauce-connect', () ->
- done = this.async()
- require('sauce-connect-launcher')({username: sauceUser, accessKey: sauceKey}, (err, sauceConnectProcess) ->
- if err then console.error(err.message)
- else done()
- )
-
- grunt.registerTask 'default', ['coffeelint', 'clean', 'coffee', 'concat', 'uglify']
- grunt.registerTask 'test:protractor-local', [
- 'default',
- 'webdriver',
- 'connect:testserver',
- 'protractor:local'
- ]
-
- grunt.registerTask 'test:protractor-travis', [
- 'connect:testserver',
- 'sauce-connect',
- 'protractor:travis'
- ]
diff --git a/catalog-ui/app/third-party/ng-infinite-scroll/LICENSE b/catalog-ui/app/third-party/ng-infinite-scroll/LICENSE
deleted file mode 100644
index 44ae2bfc40..0000000000
--- a/catalog-ui/app/third-party/ng-infinite-scroll/LICENSE
+++ /dev/null
@@ -1,22 +0,0 @@
-Copyright (c) 2012 Michelle Tilley
-
-Permission is hereby granted, free of charge, to any person
-obtaining a copy of this software and associated documentation
-files (the "Software"), to deal in the Software without
-restriction, including without limitation the rights to use,
-copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the
-Software is furnished to do so, subject to the following
-conditions:
-
-The above copyright notice and this permission notice shall be
-included in all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
-OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
-HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
-WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
-OTHER DEALINGS IN THE SOFTWARE.
diff --git a/catalog-ui/app/third-party/ng-infinite-scroll/README.md b/catalog-ui/app/third-party/ng-infinite-scroll/README.md
deleted file mode 100644
index aa8d8630e2..0000000000
--- a/catalog-ui/app/third-party/ng-infinite-scroll/README.md
+++ /dev/null
@@ -1,71 +0,0 @@
-[**Maintainer help needed**: I'm looking for fellows that are willing to help me maintain and improve this project.](https://github.com/sroze/ngInfiniteScroll/issues/267)
-
----
-
-![logo](http://sroze.github.com/ngInfiniteScroll/images/logo-resized.png)
-
-[![Build Status](https://travis-ci.org/sroze/ngInfiniteScroll.png?branch=master)](https://travis-ci.org/sroze/ngInfiniteScroll)
-
-ngInfiniteScroll is a directive for [AngularJS](http://angularjs.org/) to evaluate an expression when the bottom of the directive's element approaches the bottom of the browser window, which can be used to implement infinite scrolling.
-
-Demos
------
-
-Check out the running demos [at the ngInfiniteScroll web site](http://sroze.github.com/ngInfiniteScroll/demos.html).
-
-Version Numbers
----------------
-
-ngInfinite Scroll follows [semantic versioning](http://semver.org/) and uses the following versioning scheme:
-
- * Versions starting with 0 (e.g. 0.1.0, 0.2.0, etc.) are for initial development, and the API is not stable
- * Versions with an even minor version (1.0.0, 1.4.0, 2.2.0, etc.) are stable releases
- * Versions with an odd minor version (1.1.0, 1.3.0, 2.1.0, etc.) are development releases
-
-The [download page](http://sroze.github.com/ngInfiniteScroll/#download) allows you to pick among various versions and specify which releases are stable (not including pre-release builds).
-
-Getting Started
----------------
-
- * Download ngInfiniteScroll from [the download page on the ngInfiniteScroll web site](http://sroze.github.com/ngInfiniteScroll/#download) or install it with:
- * [Bower](http://bower.io/) via `bower install ngInfiniteScroll`
- * [NPM](https://www.npmjs.com) via `npm install --save ng-infinite-scroll`
- * [Nuget](https://www.nuget.org) via `PM> Install-Package ng-infinite-scroll`
- * Include the script tag on your page after the AngularJS script tag (ngInfiniteScroll *doesn't* require jQuery)
-
- <script type='text/javascript' src='path/to/angular.min.js'></script>
- <script type='text/javascript' src='path/to/ng-infinite-scroll.min.js'></script>
-
- * Ensure that your application module specifies `infinite-scroll` as a dependency:
-
- angular.module('myApplication', ['infinite-scroll']);
-
- * Use the directive by specifying an `infinite-scroll` attribute on an element.
-
- <div infinite-scroll="myPagingFunction()" infinite-scroll-distance="3"></div>
-
-Note that neither the module nor the directive use the `ng` prefix, as that prefix is reserved for the core Angular module.
-
-Detailed Documentation
-----------------------
-
-ngInfiniteScroll accepts several attributes to customize the behavior of the directive; detailed instructions can be found [on the ngInfiniteScroll web site](http://sroze.github.com/ngInfiniteScroll/documentation.html).
-
-Ports
------
-
-If you use [AngularDart](https://github.com/angular/angular.dart), Juha Komulainen has [a port of the project](http://pub.dartlang.org/packages/ng_infinite_scroll) you can use.
-
-License
--------
-
-ngInfiniteScroll is licensed under the MIT license. See the LICENSE file for more details.
-
-Testing
--------
-
-ngInfiniteScroll uses Protractor for testing. Note that you will need to have Chrome browser, and the `grunt-cli` npm package installed globally if you wish to use grunt (`npm install -g grunt-cli`). Then, install the dependencies with `npm install`.
-
-* `grunt test:protractor-local` - run tests
-
-Thank you very much @pomerantsev for your work on these Protractor tests.
diff --git a/catalog-ui/app/third-party/ng-infinite-scroll/bower.json b/catalog-ui/app/third-party/ng-infinite-scroll/bower.json
deleted file mode 100644
index 1171c45190..0000000000
--- a/catalog-ui/app/third-party/ng-infinite-scroll/bower.json
+++ /dev/null
@@ -1,16 +0,0 @@
-{
- "name": "ngInfiniteScroll",
- "main": "build/ng-infinite-scroll.js",
- "ignore": [
- "**/.*",
- "_*",
- "node_modules",
- "compile",
- "test",
- "Gruntfile.coffee",
- ".*"
- ],
- "dependencies": {
- "angular": ">=1.2.0"
- }
-}
diff --git a/catalog-ui/app/third-party/ng-infinite-scroll/build/ng-infinite-scroll.js b/catalog-ui/app/third-party/ng-infinite-scroll/build/ng-infinite-scroll.js
deleted file mode 100644
index 0585004832..0000000000
--- a/catalog-ui/app/third-party/ng-infinite-scroll/build/ng-infinite-scroll.js
+++ /dev/null
@@ -1,209 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-/* ng-infinite-scroll - v1.3.0 - 2016-06-30 */
-angular.module('infinite-scroll', []).value('THROTTLE_MILLISECONDS', null).directive('infiniteScroll', [
- '$rootScope', '$window', '$interval', 'THROTTLE_MILLISECONDS', function($rootScope, $window, $interval, THROTTLE_MILLISECONDS) {
- return {
- scope: {
- infiniteScroll: '&',
- infiniteScrollContainer: '=',
- infiniteScrollDistance: '=',
- infiniteScrollDisabled: '=',
- infiniteScrollUseDocumentBottom: '=',
- infiniteScrollListenForEvent: '@'
- },
- link: function(scope, elem, attrs) {
- var changeContainer, checkInterval, checkWhenEnabled, container, handleInfiniteScrollContainer, handleInfiniteScrollDisabled, handleInfiniteScrollDistance, handleInfiniteScrollUseDocumentBottom, handler, height, immediateCheck, offsetTop, pageYOffset, scrollDistance, scrollEnabled, throttle, unregisterEventListener, useDocumentBottom, windowElement;
- windowElement = angular.element($window);
- scrollDistance = null;
- scrollEnabled = null;
- checkWhenEnabled = null;
- container = null;
- immediateCheck = true;
- useDocumentBottom = false;
- unregisterEventListener = null;
- checkInterval = false;
- height = function(elem) {
- elem = elem[0] || elem;
- if (isNaN(elem.offsetHeight)) {
- return elem.document.documentElement.clientHeight;
- } else {
- return elem.offsetHeight;
- }
- };
- offsetTop = function(elem) {
- if (!elem[0].getBoundingClientRect || elem.css('none')) {
- return;
- }
- return elem[0].getBoundingClientRect().top + pageYOffset(elem);
- };
- pageYOffset = function(elem) {
- elem = elem[0] || elem;
- if (isNaN(window.pageYOffset)) {
- return elem.document.documentElement.scrollTop;
- } else {
- return elem.ownerDocument.defaultView.pageYOffset;
- }
- };
- handler = function() {
- var containerBottom, containerTopOffset, elementBottom, remaining, shouldScroll;
- if (container === windowElement) {
- containerBottom = height(container) + pageYOffset(container[0].document.documentElement);
- elementBottom = offsetTop(elem) + height(elem);
- } else {
- containerBottom = height(container);
- containerTopOffset = 0;
- if (offsetTop(container) !== void 0) {
- containerTopOffset = offsetTop(container);
- }
- elementBottom = offsetTop(elem) - containerTopOffset + height(elem);
- }
- if (useDocumentBottom) {
- elementBottom = height((elem[0].ownerDocument || elem[0].document).documentElement);
- }
- remaining = elementBottom - containerBottom;
- shouldScroll = remaining <= height(container) * scrollDistance + 1;
- if (shouldScroll) {
- checkWhenEnabled = true;
- if (scrollEnabled) {
- if (scope.$$phase || $rootScope.$$phase) {
- return scope.infiniteScroll();
- } else {
- return scope.$apply(scope.infiniteScroll);
- }
- }
- } else {
- if (checkInterval) {
- $interval.cancel(checkInterval);
- }
- return checkWhenEnabled = false;
- }
- };
- throttle = function(func, wait) {
- var later, previous, timeout;
- timeout = null;
- previous = 0;
- later = function() {
- previous = new Date().getTime();
- $interval.cancel(timeout);
- timeout = null;
- return func.call();
- };
- return function() {
- var now, remaining;
- now = new Date().getTime();
- remaining = wait - (now - previous);
- if (remaining <= 0) {
- $interval.cancel(timeout);
- timeout = null;
- previous = now;
- return func.call();
- } else {
- if (!timeout) {
- return timeout = $interval(later, remaining, 1);
- }
- }
- };
- };
- if (THROTTLE_MILLISECONDS != null) {
- handler = throttle(handler, THROTTLE_MILLISECONDS);
- }
- scope.$on('$destroy', function() {
- container.unbind('scroll', handler);
- if (unregisterEventListener != null) {
- unregisterEventListener();
- unregisterEventListener = null;
- }
- if (checkInterval) {
- return $interval.cancel(checkInterval);
- }
- });
- handleInfiniteScrollDistance = function(v) {
- return scrollDistance = parseFloat(v) || 0;
- };
- scope.$watch('infiniteScrollDistance', handleInfiniteScrollDistance);
- handleInfiniteScrollDistance(scope.infiniteScrollDistance);
- handleInfiniteScrollDisabled = function(v) {
- scrollEnabled = !v;
- if (scrollEnabled && checkWhenEnabled) {
- checkWhenEnabled = false;
- return handler();
- }
- };
- scope.$watch('infiniteScrollDisabled', handleInfiniteScrollDisabled);
- handleInfiniteScrollDisabled(scope.infiniteScrollDisabled);
- handleInfiniteScrollUseDocumentBottom = function(v) {
- return useDocumentBottom = v;
- };
- scope.$watch('infiniteScrollUseDocumentBottom', handleInfiniteScrollUseDocumentBottom);
- handleInfiniteScrollUseDocumentBottom(scope.infiniteScrollUseDocumentBottom);
- changeContainer = function(newContainer) {
- if (container != null) {
- container.unbind('scroll', handler);
- }
- container = newContainer;
- if (newContainer != null) {
- return container.bind('scroll', handler);
- }
- };
- changeContainer(windowElement);
- if (scope.infiniteScrollListenForEvent) {
- unregisterEventListener = $rootScope.$on(scope.infiniteScrollListenForEvent, handler);
- }
- handleInfiniteScrollContainer = function(newContainer) {
- if ((newContainer == null) || newContainer.length === 0) {
- return;
- }
- if (newContainer.nodeType && newContainer.nodeType === 1) {
- newContainer = angular.element(newContainer);
- } else if (typeof newContainer.append === 'function') {
- newContainer = angular.element(newContainer[newContainer.length - 1]);
- } else if (typeof newContainer === 'string') {
- newContainer = angular.element(document.querySelector(newContainer));
- }
- if (newContainer != null) {
- return changeContainer(newContainer);
- } else {
- throw new Error("invalid infinite-scroll-container attribute.");
- }
- };
- scope.$watch('infiniteScrollContainer', handleInfiniteScrollContainer);
- handleInfiniteScrollContainer(scope.infiniteScrollContainer || []);
- if (attrs.infiniteScrollParent != null) {
- changeContainer(angular.element(elem.parent()));
- }
- if (attrs.infiniteScrollImmediateCheck != null) {
- immediateCheck = scope.$eval(attrs.infiniteScrollImmediateCheck);
- }
- return checkInterval = $interval((function() {
- if (immediateCheck) {
- handler();
- }
- return $interval.cancel(checkInterval);
- }));
- }
- };
- }
-]);
-
-if (typeof module !== "undefined" && typeof exports !== "undefined" && module.exports === exports) {
- module.exports = 'infinite-scroll';
-}
diff --git a/catalog-ui/app/third-party/ng-infinite-scroll/build/ng-infinite-scroll.min.js b/catalog-ui/app/third-party/ng-infinite-scroll/build/ng-infinite-scroll.min.js
deleted file mode 100644
index e2a3036422..0000000000
--- a/catalog-ui/app/third-party/ng-infinite-scroll/build/ng-infinite-scroll.min.js
+++ /dev/null
@@ -1,22 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-/* ng-infinite-scroll - v1.3.0 - 2016-06-30 */
-angular.module("infinite-scroll",[]).value("THROTTLE_MILLISECONDS",null).directive("infiniteScroll",["$rootScope","$window","$interval","THROTTLE_MILLISECONDS",function(a,b,c,d){return{scope:{infiniteScroll:"&",infiniteScrollContainer:"=",infiniteScrollDistance:"=",infiniteScrollDisabled:"=",infiniteScrollUseDocumentBottom:"=",infiniteScrollListenForEvent:"@"},link:function(e,f,g){var h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z;return z=angular.element(b),u=null,v=null,j=null,k=null,r=!0,y=!1,x=null,i=!1,q=function(a){return a=a[0]||a,isNaN(a.offsetHeight)?a.document.documentElement.clientHeight:a.offsetHeight},s=function(a){if(a[0].getBoundingClientRect&&!a.css("none"))return a[0].getBoundingClientRect().top+t(a)},t=function(a){return a=a[0]||a,isNaN(window.pageYOffset)?a.document.documentElement.scrollTop:a.ownerDocument.defaultView.pageYOffset},p=function(){var b,d,g,h,l;return k===z?(b=q(k)+t(k[0].document.documentElement),g=s(f)+q(f)):(b=q(k),d=0,void 0!==s(k)&&(d=s(k)),g=s(f)-d+q(f)),y&&(g=q((f[0].ownerDocument||f[0].document).documentElement)),h=g-b,l=h<=q(k)*u+1,l?(j=!0,v?e.$$phase||a.$$phase?e.infiniteScroll():e.$apply(e.infiniteScroll):void 0):(i&&c.cancel(i),j=!1)},w=function(a,b){var d,e,f;return f=null,e=0,d=function(){return e=(new Date).getTime(),c.cancel(f),f=null,a.call()},function(){var g,h;return g=(new Date).getTime(),h=b-(g-e),h<=0?(c.cancel(f),f=null,e=g,a.call()):f?void 0:f=c(d,h,1)}},null!=d&&(p=w(p,d)),e.$on("$destroy",function(){if(k.unbind("scroll",p),null!=x&&(x(),x=null),i)return c.cancel(i)}),n=function(a){return u=parseFloat(a)||0},e.$watch("infiniteScrollDistance",n),n(e.infiniteScrollDistance),m=function(a){if(v=!a,v&&j)return j=!1,p()},e.$watch("infiniteScrollDisabled",m),m(e.infiniteScrollDisabled),o=function(a){return y=a},e.$watch("infiniteScrollUseDocumentBottom",o),o(e.infiniteScrollUseDocumentBottom),h=function(a){if(null!=k&&k.unbind("scroll",p),k=a,null!=a)return k.bind("scroll",p)},h(z),e.infiniteScrollListenForEvent&&(x=a.$on(e.infiniteScrollListenForEvent,p)),l=function(a){if(null!=a&&0!==a.length){if(a.nodeType&&1===a.nodeType?a=angular.element(a):"function"==typeof a.append?a=angular.element(a[a.length-1]):"string"==typeof a&&(a=angular.element(document.querySelector(a))),null!=a)return h(a);throw new Error("invalid infinite-scroll-container attribute.")}},e.$watch("infiniteScrollContainer",l),l(e.infiniteScrollContainer||[]),null!=g.infiniteScrollParent&&h(angular.element(f.parent())),null!=g.infiniteScrollImmediateCheck&&(r=e.$eval(g.infiniteScrollImmediateCheck)),i=c(function(){return r&&p(),c.cancel(i)})}}}]),"undefined"!=typeof module&&"undefined"!=typeof exports&&module.exports===exports&&(module.exports="infinite-scroll");
diff --git a/catalog-ui/app/third-party/ng-infinite-scroll/package.json b/catalog-ui/app/third-party/ng-infinite-scroll/package.json
deleted file mode 100644
index 8859faecdc..0000000000
--- a/catalog-ui/app/third-party/ng-infinite-scroll/package.json
+++ /dev/null
@@ -1,80 +0,0 @@
-{
- "name": "ng-infinite-scroll",
- "version": "1.3.0",
- "description": "Infinite scrolling for AngularJS",
- "repository": {
- "type": "git",
- "url": "git://github.com/sroze/ngInfiniteScroll.git"
- },
- "main": "build/ng-infinite-scroll.js",
- "browser": "build/ng-infinite-scroll.js",
- "scripts": {
- "test": "grunt test:protractor-local"
- },
- "author": {
- "name": "Michelle Tilley",
- "email": "michelle@michelletilley.net",
- "url": "http://michelletilley.net"
- },
- "contributors": [
- {
- "name": "Samuel ROZE",
- "email": "samuel.roze@gmail.com",
- "url": "http://sroze.io"
- }
- ],
- "license": "MIT",
- "devDependencies": {
- "coffee-script": "~1.8.0",
- "grunt": "~0.4.5",
- "grunt-coffeelint": "~0.0.13",
- "grunt-contrib-clean": "~0.6.0",
- "grunt-contrib-coffee": "~0.12.0",
- "grunt-contrib-concat": "~0.5.0",
- "grunt-contrib-connect": "0.8.0",
- "grunt-contrib-uglify": "~0.6.0",
- "grunt-protractor-runner": "1.1.4",
- "mkdirp": "0.5.0",
- "protractor": "1.4.0",
- "sauce-connect-launcher": "0.9.0"
- },
- "gitHead": "6fbf4b41947f9a3023b4aba0e613231950ccc4a1",
- "bugs": {
- "url": "https://github.com/sroze/ngInfiniteScroll/issues"
- },
- "homepage": "https://github.com/sroze/ngInfiniteScroll#readme",
- "_id": "ng-infinite-scroll@1.3.0",
- "_shasum": "c2e98d8fd134b0525a4d2cf58c95d9b583755112",
- "_from": "ng-infinite-scroll@>=1.3.0 <2.0.0",
- "_npmVersion": "3.9.5",
- "_nodeVersion": "6.2.2",
- "_npmUser": {
- "name": "graingert",
- "email": "tagrain@gmail.com"
- },
- "dist": {
- "shasum": "c2e98d8fd134b0525a4d2cf58c95d9b583755112",
- "tarball": "https://registry.npmjs.org/ng-infinite-scroll/-/ng-infinite-scroll-1.3.0.tgz"
- },
- "maintainers": [
- {
- "name": "binarymuse",
- "email": "michelle@michelletilley.net"
- },
- {
- "name": "graingert",
- "email": "tagrain@gmail.com"
- },
- {
- "name": "sroze",
- "email": "samuel.roze@gmail.com"
- }
- ],
- "_npmOperationalInternal": {
- "host": "packages-12-west.internal.npmjs.com",
- "tmp": "tmp/ng-infinite-scroll-1.3.0.tgz_1467302375605_0.8192659560590982"
- },
- "directories": {},
- "_resolved": "https://registry.npmjs.org/ng-infinite-scroll/-/ng-infinite-scroll-1.3.0.tgz",
- "readme": "ERROR: No README data found!"
-}
diff --git a/catalog-ui/app/third-party/ng-infinite-scroll/src/infinite-scroll.coffee b/catalog-ui/app/third-party/ng-infinite-scroll/src/infinite-scroll.coffee
deleted file mode 100644
index cf2f90fc19..0000000000
--- a/catalog-ui/app/third-party/ng-infinite-scroll/src/infinite-scroll.coffee
+++ /dev/null
@@ -1,209 +0,0 @@
-angular.module('infinite-scroll', [])
- .value('THROTTLE_MILLISECONDS', null)
- .directive 'infiniteScroll', [
- '$rootScope', '$window', '$interval', 'THROTTLE_MILLISECONDS',
-($rootScope, $window, $interval, THROTTLE_MILLISECONDS) ->
- scope:
- infiniteScroll: '&'
- infiniteScrollContainer: '='
- infiniteScrollDistance: '='
- infiniteScrollDisabled: '='
- infiniteScrollUseDocumentBottom: '=',
- infiniteScrollListenForEvent: '@'
-
- link: (scope, elem, attrs) ->
- windowElement = angular.element($window)
-
- scrollDistance = null
- scrollEnabled = null
- checkWhenEnabled = null
- container = null
- immediateCheck = true
- useDocumentBottom = false
- unregisterEventListener = null
- checkInterval = false
-
- height = (elem) ->
- elem = elem[0] or elem
-
- if isNaN(elem.offsetHeight) then elem.document.documentElement.clientHeight else elem.offsetHeight
-
- offsetTop = (elem) ->
- if not elem[0].getBoundingClientRect or elem.css('none')
- return
-
- elem[0].getBoundingClientRect().top + pageYOffset(elem)
-
- pageYOffset = (elem) ->
- elem = elem[0] or elem
-
- if isNaN(window.pageYOffset) then elem.document.documentElement.scrollTop else elem.ownerDocument.defaultView.pageYOffset
-
- # infinite-scroll specifies a function to call when the window,
- # or some other container specified by infinite-scroll-container,
- # is scrolled within a certain range from the bottom of the
- # document. It is recommended to use infinite-scroll-disabled
- # with a boolean that is set to true when the function is
- # called in order to throttle the function call.
- handler = ->
- if container == windowElement
- containerBottom = height(container) + pageYOffset(container[0].document.documentElement)
- elementBottom = offsetTop(elem) + height(elem)
- else
- containerBottom = height(container)
- containerTopOffset = 0
- if offsetTop(container) != undefined
- containerTopOffset = offsetTop(container)
- elementBottom = offsetTop(elem) - containerTopOffset + height(elem)
-
- if(useDocumentBottom)
- elementBottom = height((elem[0].ownerDocument || elem[0].document).documentElement)
-
- remaining = elementBottom - containerBottom
- shouldScroll = remaining <= height(container) * scrollDistance + 1
-
- if shouldScroll
- checkWhenEnabled = true
-
- if scrollEnabled
- if scope.$$phase || $rootScope.$$phase
- scope.infiniteScroll()
- else
- scope.$apply(scope.infiniteScroll)
- else
- if checkInterval then $interval.cancel checkInterval
- checkWhenEnabled = false
-
- # The optional THROTTLE_MILLISECONDS configuration value specifies
- # a minimum time that should elapse between each call to the
- # handler. N.b. the first call the handler will be run
- # immediately, and the final call will always result in the
- # handler being called after the `wait` period elapses.
- # A slimmed down version of underscore's implementation.
- throttle = (func, wait) ->
- timeout = null
- previous = 0
- later = ->
- previous = new Date().getTime()
- $interval.cancel(timeout)
- timeout = null
- func.call()
-
- return ->
- now = new Date().getTime()
- remaining = wait - (now - previous)
- if remaining <= 0
- $interval.cancel(timeout)
- timeout = null
- previous = now
- func.call()
- else timeout = $interval(later, remaining, 1) unless timeout
-
- if THROTTLE_MILLISECONDS?
- handler = throttle(handler, THROTTLE_MILLISECONDS)
-
- scope.$on '$destroy', ->
- container.unbind 'scroll', handler
- if unregisterEventListener?
- unregisterEventListener()
- unregisterEventListener = null
- if checkInterval
- $interval.cancel checkInterval
-
- # infinite-scroll-distance specifies how close to the bottom of the page
- # the window is allowed to be before we trigger a new scroll. The value
- # provided is multiplied by the container height; for example, to load
- # more when the bottom of the page is less than 3 container heights away,
- # specify a value of 3. Defaults to 0.
- handleInfiniteScrollDistance = (v) ->
- scrollDistance = parseFloat(v) or 0
-
- scope.$watch 'infiniteScrollDistance', handleInfiniteScrollDistance
- # If I don't explicitly call the handler here, tests fail. Don't know why yet.
- handleInfiniteScrollDistance scope.infiniteScrollDistance
-
- # infinite-scroll-disabled specifies a boolean that will keep the
- # infnite scroll function from being called; this is useful for
- # debouncing or throttling the function call. If an infinite
- # scroll is triggered but this value evaluates to true, then
- # once it switches back to false the infinite scroll function
- # will be triggered again.
- handleInfiniteScrollDisabled = (v) ->
- scrollEnabled = !v
- if scrollEnabled && checkWhenEnabled
- checkWhenEnabled = false
- handler()
-
- scope.$watch 'infiniteScrollDisabled', handleInfiniteScrollDisabled
- # If I don't explicitly call the handler here, tests fail. Don't know why yet.
- handleInfiniteScrollDisabled scope.infiniteScrollDisabled
-
- # use the bottom of the document instead of the element's bottom.
- # This useful when the element does not have a height due to its
- # children being absolute positioned.
- handleInfiniteScrollUseDocumentBottom = (v) ->
- useDocumentBottom = v
-
- scope.$watch 'infiniteScrollUseDocumentBottom', handleInfiniteScrollUseDocumentBottom
- handleInfiniteScrollUseDocumentBottom scope.infiniteScrollUseDocumentBottom
-
- # infinite-scroll-container sets the container which we want to be
- # infinte scrolled, instead of the whole window. Must be an
- # Angular or jQuery element, or, if jQuery is loaded,
- # a jQuery selector as a string.
- changeContainer = (newContainer) ->
- if container?
- container.unbind 'scroll', handler
-
- container = newContainer
- if newContainer?
- container.bind 'scroll', handler
-
- changeContainer windowElement
-
- if scope.infiniteScrollListenForEvent
- unregisterEventListener = $rootScope.$on scope.infiniteScrollListenForEvent, handler
-
- handleInfiniteScrollContainer = (newContainer) ->
- # TODO: For some reason newContainer is sometimes null instead
- # of the empty array, which Angular is supposed to pass when the
- # element is not defined
- # (https://github.com/sroze/ngInfiniteScroll/pull/7#commitcomment-5748431).
- # So I leave both checks.
- if (not newContainer?) or newContainer.length == 0
- return
-
- if newContainer.nodeType && newContainer.nodeType == 1
- newContainer = angular.element newContainer
- else if typeof newContainer.append == 'function'
- newContainer = angular.element newContainer[newContainer.length - 1]
- else if typeof newContainer == 'string'
- newContainer = angular.element document.querySelector newContainer
-
- if newContainer?
- changeContainer newContainer
- else
- throw new Error("invalid infinite-scroll-container attribute.")
-
- scope.$watch 'infiniteScrollContainer', handleInfiniteScrollContainer
- handleInfiniteScrollContainer(scope.infiniteScrollContainer or [])
-
- # infinite-scroll-parent establishes this element's parent as the
- # container infinitely scrolled instead of the whole window.
- if attrs.infiniteScrollParent?
- changeContainer angular.element elem.parent()
-
- # infinte-scoll-immediate-check sets whether or not run the
- # expression passed on infinite-scroll for the first time when the
- # directive first loads, before any actual scroll.
- if attrs.infiniteScrollImmediateCheck?
- immediateCheck = scope.$eval(attrs.infiniteScrollImmediateCheck)
-
- checkInterval = $interval (->
- if immediateCheck
- handler()
- $interval.cancel checkInterval
- )
-]
-if typeof module != "undefined" && typeof exports != "undefined" && module.exports == exports
- module.exports = 'infinite-scroll'
diff --git a/catalog-ui/app/third-party/ng-infinite-scroll/test/protractor-local.conf.js b/catalog-ui/app/third-party/ng-infinite-scroll/test/protractor-local.conf.js
deleted file mode 100644
index 134c723f91..0000000000
--- a/catalog-ui/app/third-party/ng-infinite-scroll/test/protractor-local.conf.js
+++ /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=========================================================
- */
-
-var config = require('./protractor-shared.conf').config;
-
-config.multiCapabilities = [
- { browserName: 'chrome' }
-];
-
-exports.config = config;
diff --git a/catalog-ui/app/third-party/ng-infinite-scroll/test/protractor-shared.conf.js b/catalog-ui/app/third-party/ng-infinite-scroll/test/protractor-shared.conf.js
deleted file mode 100644
index d1e567d7b4..0000000000
--- a/catalog-ui/app/third-party/ng-infinite-scroll/test/protractor-shared.conf.js
+++ /dev/null
@@ -1,26 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-exports.config = {
- specs: ['**/*.spec.coffee'],
- baseUrl: 'http://localhost:8000/',
- allScriptsTimeout: 30000,
- getPageTimeout: 30000
-};
diff --git a/catalog-ui/app/third-party/ng-infinite-scroll/test/protractor-travis.conf.js b/catalog-ui/app/third-party/ng-infinite-scroll/test/protractor-travis.conf.js
deleted file mode 100644
index 54fe0bd828..0000000000
--- a/catalog-ui/app/third-party/ng-infinite-scroll/test/protractor-travis.conf.js
+++ /dev/null
@@ -1,32 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-var config = require('./protractor-shared.conf').config;
-
-// All available platform / browser combinations can be found on https://saucelabs.com/platforms
-config.multiCapabilities = [
- {
- browserName: 'chrome',
- platform: 'OS X 10.10',
- version: '37'
- }
-];
-
-exports.config = config;
diff --git a/catalog-ui/app/third-party/ng-infinite-scroll/test/spec/ng-infinite-scroll.spec.coffee b/catalog-ui/app/third-party/ng-infinite-scroll/test/spec/ng-infinite-scroll.spec.coffee
deleted file mode 100644
index 07e6fec8be..0000000000
--- a/catalog-ui/app/third-party/ng-infinite-scroll/test/spec/ng-infinite-scroll.spec.coffee
+++ /dev/null
@@ -1,221 +0,0 @@
-fs = require "fs"
-mkdirp = require "mkdirp"
-
-getTemplate = (angularVersion, container, attrs, throttle) ->
- """
- <!doctype html>
- <head>
- <style>
- html, body {
- height: 100%;
- }
- </style>
- <script src='http://ajax.googleapis.com/ajax/libs/angularjs/#{angularVersion}/angular.min.js'></script>
- <script src="../../build/ng-infinite-scroll.js"></script>
- <script>
- angular.module('app', ['infinite-scroll'])
- .config(function ($provide) {
- $provide.value('THROTTLE_MILLISECONDS', #{throttle});
- })
- .run(function ($rootScope) {
- $rootScope.items = [];
- $rootScope.loadMore = function () {
- [].push.apply($rootScope.items, new Array(100));
- };
-
- $rootScope.busy = true;
-
- $rootScope.enable = function () {
- $rootScope.busy = false;
- };
-
- $rootScope.triggerEvent = function () {
- $rootScope.$emit('anEvent');
- };
- });
- </script>
- </head>
- <body ng-app="app">
- <a id="action" ng-click="enable()">Enable</a>
- <a id="force" ng-click="loadMore()">Force</a>
- <a id="trigger" ng-click="triggerEvent()">Trigger</a>
- #{containers[container].start}
- <div infinite-scroll="loadMore()" #{containers[container].attr} #{attrs}>
- <p ng-repeat='item in items track by $index'>
- {{$index}}
- </p>
- </div>
- #{containers[container].end}
- </body>
- """
-
-containers =
- window:
- start: ""
- end: ""
- attr: ""
- parent:
- start: "<div id='parent' style='height: 50%; overflow: auto;'>"
- end: "</div>"
- attr: "infinite-scroll-parent"
- ancestor:
- start: "<div id='ancestor' style='height: 50%; overflow: auto;'><div>"
- end: "</div></div>"
- attr: "infinite-scroll-container='\"#ancestor\"'"
-
-getElementByIdScript = (id) ->
- "document.getElementById('#{id}')"
-
-calculateChildrenHeightScript = (id) ->
- """
- [].concat.apply([], #{getElementByIdScript(id)}.childNodes)
- .map(function (el) { return el.offsetHeight ? el.offsetHeight : 0; })
- .reduce(function (cur, prev) { return prev + cur; }, 0)
- """
-
-scrollToBottomScript = (container) ->
- if container is "window"
- "window.scrollTo(0, document.body.scrollHeight)"
- else
- "#{getElementByIdScript(container)}.scrollTop = #{calculateChildrenHeightScript(container)}"
-
-scrollToLastScreenScript = (container, offset) ->
- # 2 * window.innerHeight means that the bottom of the screen should be somewhere close to
- # body height - window height. That means that the top of the window is body height - 2 * window height.
- if container is "window"
- "window.scrollTo(0, document.body.scrollHeight - 2 * window.innerHeight + #{offset})"
- else
- """
- #{getElementByIdScript(container)}.scrollTop =
- #{calculateChildrenHeightScript(container)} - 2 * #{getElementByIdScript(container)}.offsetHeight + #{offset}
- """
-
-collapseItemsScript = (container) ->
- """
- var items = document.getElementsByTagName('p')
- for (i = 0; i < items.length; ++i) {
- items[i].style.display = 'none'
- }
- """
-
-getItems = ->
- element.all(By.repeater "item in items")
-
-tmpDir = ".tmp"
-pathToDocument = "#{tmpDir}/index.html"
-
-describe "ng-infinite-scroll", ->
- for angularVersion in ["1.2.0", "1.3.4"]
- describe "with Angular #{angularVersion}", ->
- for container in ["window", "ancestor", "parent"]
- describe "with #{container} as container", ->
-
- replaceIndexFile = (attrs, throttle) ->
- mkdirp tmpDir
- fs.writeFileSync(pathToDocument, getTemplate(angularVersion, container, attrs, throttle))
-
- describe "without throttling", ->
-
- throttle = null
-
- it "should be triggered immediately and when container is scrolled to the bottom", ->
- replaceIndexFile "", throttle
- browser.get pathToDocument
- expect(getItems().count()).toBe 100
- browser.driver.executeScript(scrollToBottomScript(container))
- expect(getItems().count()).toBe 200
-
- it "does not trigger immediately when infinite-scroll-immediate-check is false", ->
- replaceIndexFile "infinite-scroll-immediate-check='false'", throttle
- browser.get pathToDocument
- expect(getItems().count()).toBe 0
- element(By.id("force")).click()
- expect(getItems().count()).toBe 100
- browser.driver.executeScript(scrollToBottomScript(container))
- expect(getItems().count()).toBe 200
-
- it "respects the disabled attribute", ->
- replaceIndexFile "infinite-scroll-disabled='busy'", throttle
- browser.get pathToDocument
- expect(getItems().count()).toBe 0
- element(By.id("action")).click()
- expect(getItems().count()).toBe 100
-
- it "respects the infinite-scroll-distance attribute", ->
- replaceIndexFile "infinite-scroll-distance='1'", throttle
- browser.get pathToDocument
- expect(getItems().count()).toBe 100
- browser.driver.executeScript(scrollToLastScreenScript(container, -20))
- expect(getItems().count()).toBe 100
- browser.driver.executeScript(scrollToLastScreenScript(container, 20))
- expect(getItems().count()).toBe 200
-
- describe "with an event handler", ->
-
- it "calls the event handler on an event", ->
- replaceIndexFile "infinite-scroll-listen-for-event='anEvent'", throttle
- browser.get pathToDocument
- expect(getItems().count()).toBe 100
- browser.driver.executeScript(collapseItemsScript(container))
- expect(getItems().count()).toBe 100
- element(By.id("trigger")).click()
- expect(getItems().count()).toBe 200
-
- describe "with throttling", ->
-
- throttle = browser.params.testThrottleValue
-
- it "should be triggered immediately and when container is scrolled to the bottom", ->
- replaceIndexFile "", throttle
- browser.get pathToDocument
- expect(getItems().count()).toBe 100
- browser.driver.executeScript(scrollToBottomScript(container))
- expect(getItems().count()).toBe 100
- browser.sleep(throttle)
- expect(getItems().count()).toBe 200
-
- it "does not trigger immediately when infinite-scroll-immediate-check is false", ->
- replaceIndexFile "infinite-scroll-immediate-check='false'", throttle
- browser.get pathToDocument
- expect(getItems().count()).toBe 0
- element(By.id("force")).click()
- expect(getItems().count()).toBe 100
-
- it "respects the disabled attribute and is throttled when page loads", ->
- replaceIndexFile "infinite-scroll-disabled='busy'", throttle
- browser.get pathToDocument
- expect(getItems().count()).toBe 0
- element(By.id("action")).click()
- expect(getItems().count()).toBe 0
- browser.sleep(throttle)
- expect(getItems().count()).toBe 100
-
- it "is not throttled when re-enabled if the throttle time has already elapsed", ->
- replaceIndexFile "infinite-scroll-disabled='busy'", throttle
- browser.get pathToDocument
- expect(getItems().count()).toBe 0
- browser.sleep(throttle)
- element(By.id("action")).click()
- expect(getItems().count()).toBe 100
-
- it "respects the infinite-scroll-distance attribute", ->
- replaceIndexFile "infinite-scroll-distance='1'", throttle
- browser.get pathToDocument
- expect(getItems().count()).toBe 100
- browser.driver.executeScript(scrollToLastScreenScript(container, 20))
- expect(getItems().count()).toBe 100
- browser.sleep(throttle)
- expect(getItems().count()).toBe 200
-
- describe "with an event handler", ->
-
- it "calls the event handler on an event", ->
- replaceIndexFile "infinite-scroll-listen-for-event='anEvent'", throttle
- browser.get pathToDocument
- expect(getItems().count()).toBe 100
- browser.driver.executeScript(collapseItemsScript(container))
- expect(getItems().count()).toBe 100
- element(By.id("trigger")).click()
- expect(getItems().count()).toBe 100
- browser.sleep(throttle)
- expect(getItems().count()).toBe 200
diff --git a/catalog-ui/bower dependecies b/catalog-ui/bower dependecies
deleted file mode 100644
index 7a21bbcef7..0000000000
--- a/catalog-ui/bower dependecies
+++ /dev/null
@@ -1,29 +0,0 @@
-{
- "name": "catalog-ui",
- "private": true,
- "dependencies": {
- "angular": "~1.3.x",
- "angular-base64": "~2.0.5", //for translate base 64
- "angular-base64-upload": "~0.1.8", //upload file base 64
- "angular-bootstrap": "~0.13.0",
- "angular-dragdrop": "~1.0.11", //for drag & drop elements in canvas
- "angular-filter": "~0.5.6", // for filter categories
- "angular-md5": "~0.1.7", //translate from & to md5
- "angular-perfect-scrollbar": "~0.0.4", // fir design cross browser scrollbar
- "angular-qtip2-directive": "~0.1.2", // for design tooltips
- "angular-resource": "~1.3.15", // for restfully Api
- "angular-sanitize": "~1.4.4", //https://docs.angularjs.org/api/ngSanitize/service/$sanitize
- "angular-ui-router": "~0.2.14",
- "angular-uuid4": "~0.3.0",
- "bootstrap": "3.3.4", // dependency for angular bootstrap
- "checklist-model": "~0.2.4", // for categories check list model
- "jquery": "~1.11.1",
- "lodash": "~3.7.0", // js utils functions
- "angular-translate": "~2.8.0", // dependencies for language support
- "angular-translate-loader-static-files": "~2.8.0" // for language support
- },
- "resolutions": {
- "angular": "~1.3.x",
- "jquery": "~2.0.3"
- }
-}
diff --git a/catalog-ui/bower.json b/catalog-ui/bower.json
deleted file mode 100644
index d941f1620a..0000000000
--- a/catalog-ui/bower.json
+++ /dev/null
@@ -1,42 +0,0 @@
-{
- "name": "catalog-ui",
- "private": true,
- "dependencies": {
- "angular": "1.5.0",
- "angular-base64": "2.0.5",
- "angular-base64-upload": "0.1.19",
- "angular-bootstrap": "0.14.3",
- "angular-dragdrop": "https://github.com/dimkinv/angular-dragdrop.git#1.0.14",
- "angular-filter": "0.5.14",
- "angular-mocks": "1.5.0",
- "angular-perfect-scrollbar": "0.0.4",
- "angular-resource": "1.5.11",
- "angular-sanitize": "1.4.4",
- "angular-tooltips": "0.1.23",
- "angular-translate": "2.8.0",
- "angular-translate-loader-static-files": "2.8.0",
- "angular-ui-router": "0.2.14",
- "angular-uuid4": "0.3.0",
- "bootstrap": "3.3.4",
- "checklist-model": "0.2.4",
- "jquery": "2.2.4",
- "jspdf": "1.0.272",
- "animate.css": "~3.5.1",
- "angular-clipboard": "1.5.0",
- "ui-bootstrap": "1.3.3",
- "angular-resizable": "1.2.0",
- "angular-ui-notification": "0.2.0",
- "js-md5": "md5#0.4.1",
- "cytoscape": "^2.7.10",
- "lodash": "^4.17.2",
- "restangular": "^1.5.2",
- "cytoscape-expand-collapse": "https://github.com/bardit/cytoscape.js-expand-collapse.git",
- "cytoscape-qtip": "https://github.com/bardit/cytoscape.js-qtip.git",
- "qtip2": "^2.2.1"
- },
- "resolutions": {
- "angular": "1.5.0",
- "jquery": "2.2.4",
- "angular-translate": "2.8.1"
- }
-}
diff --git a/catalog-ui/build_catalog_ui.bat b/catalog-ui/build_catalog_ui.bat
index 7a153e9ae7..b00ee0875b 100644
--- a/catalog-ui/build_catalog_ui.bat
+++ b/catalog-ui/build_catalog_ui.bat
@@ -1,27 +1,26 @@
rem nvmw use v0.12.4
+echo "configure proxy for ATT"
+call npm config set proxy http://one.proxy.att.com:8080
+
+echo "npm cache clean"
+call npm cache clean
echo "npm install"
call npm install
if %errorlevel% NEQ 0 GOTO BAD_EXIT
-echo "bower install"
-call bower install
-if %errorlevel% NEQ 0 GOTO BAD_EXIT
-
-
-echo "build --v"
-grunt build --v
+echo "npm run build:prod"
+npm run build:prod
if %errorlevel% NEQ 0 GOTO BAD_EXIT
GOTO SMOOTH
-
:BAD_EXIT
echo BOO
-exit/ b 1
+exit /b 1
:SMOOTH
diff --git a/catalog-ui/build_catalog_ui.sh b/catalog-ui/build_catalog_ui.sh
index 8bae776893..36f798513a 100644
--- a/catalog-ui/build_catalog_ui.sh
+++ b/catalog-ui/build_catalog_ui.sh
@@ -1,84 +1,50 @@
-
#!/bin/sh
-### Set the node environment.
-#NODE_VERSION="v6.2.2"
-
-#echo "Set the node environment."
-#. "$NVM_DIR/nvm.sh"
-#echo "OK."
-#echo ""
+### Set the node environment.
+NODE_VERSION="v6.10.0"
-### Add newer c++ compiler.
-#if [ -f /opt/rh/devtoolset-4/enable ]; then
-# . /opt/rh/devtoolset-4/enable
-#fi
+### Set the NVM root dir
+NVM_DIR=/home/${USER}/.nvm
-### Set the node version manager version.
-#echo "Set the node version manager version."
-#nvm use ${NODE_VERSION}
-#echo "OK."
-#echo ""
-
-### Run install bower.
-echo "Run install bower."
-#if [ -e $NVM_DIR/versions/node/${NODE_VERSION}/lib/node_modules/bower/bin/bower ]; then
-# echo " - bower is already installed."
-#else
-npm install bower
-#fi
-#echo "OK."
-#echo ""
+echo "Set the node environment."
+. "${NVM_DIR}/nvm.sh"
+echo "OK."
+echo ""
-### Run install grunt-cli.
-echo "Run install grunt-cli."
-#if [ -e $NVM_DIR/versions/node/${NODE_VERSION}/lib/node_modules/grunt-cli/bin/grunt ]; then
-# echo " - grunt-cli is already installed."
-#else
-npm install grunt-cli
-#fi
-#echo "OK."
-#echo ""
+### Add newer c++ compiler.
+if [ -f /opt/rh/devtoolset-4/enable ]; then
+ . /opt/rh/devtoolset-4/enable
+fi
-### Clean the Node cache.
-#echo "Clean the Node cache - if stuck."
-#npm cache clean
-#echo "OK."
-#echo ""
+### Set the node version manager version.
+echo "Set the node version manager version."
+nvm use ${NODE_VERSION}
+echo "OK."
+echo ""
### Run the Node package manager (NPM).
echo "Run the Node package manager (NPM)."
-#npm config set proxy http://one.proxy.att.com:8080
-#npm config set https-proxy http://one.proxy.att.com:8080
-#npm config set registry https://registry.npmjs.org
-
npm install
echo "OK."
echo ""
-### Install the Bower components.
-echo "Install the Bower components."
-bower install
-echo "OK."
-echo ""
-
-
-
### Build the application.
echo "Build the application."
-grunt build
+npm run build:prod
+echo "OK."
+echo ""
diff --git a/catalog-ui/configurations/dev.js b/catalog-ui/configurations/dev.js
new file mode 100644
index 0000000000..4058071183
--- /dev/null
+++ b/catalog-ui/configurations/dev.js
@@ -0,0 +1,431 @@
+const SDC_CONFIG = {
+ "environment": "dev",
+ "api": {
+ "GET_component": "/v1/catalog/:type/:id",
+ "PUT_component": "/v1/catalog/:type/:id/metadata",
+ "GET_component_validate_name": "/v1/catalog/:type/validate-name/:name",
+ "POST_changeLifecycleState": "/v1/catalog/",
+ "component_api_root": "/v1/catalog/",
+ "GET_user": "/v1/user/:id",
+ "GET_user_authorize": "/v1/user/authorize",
+ "GET_all_users": "/v1/user/users",
+ "POST_create_user": "/v1/user",
+ "DELETE_delete_user": "/v1/user/:id",
+ "POST_edit_user_role": "/v1/user/:id/role",
+ "GET_resource": "/v1/catalog/resources/:id",
+ "GET_resources_latestversion_notabstract":"/v1/catalog/:type/latestversion/notabstract/:id",
+ "GET_resources_certified_not_abstract": "/v1/catalog/resources/certified/notabstract/:id",
+ "GET_resources_certified_abstract": "/v1/catalog/resources/certified/abstract/:id",
+ "GET_resource_property": "/v1/catalog/:type/:entityId/properties/:id",
+ "PUT_resource": "/v1/catalog/resources/:id/metadata",
+ "GET_resource_artifact": "/v1/catalog/:type/:entityId/artifacts/:id",
+ "GET_download_instance_artifact": "/v1/catalog/:type/:entityId/resourceInstances/:instanceId/artifacts/:id",
+ "POST_instance_artifact": "/v1/catalog/:type/:entityId/resourceInstance/:instanceId/artifacts/:id",
+ "GET_resource_additional_information": "/v1/catalog/:type/:entityId/additionalinfo/:id",
+ "GET_service_artifact": "/v1/catalog/services/:serviceId/artifacts/:id",
+ "GET_resource_interface_artifact": "/v1/catalog/:type/:entityId/standard/:operation/artifacts/:id",
+ "GET_resource_api_artifact": "/v1/catalog/:type/:entityId/artifacts/api/:id",
+ "GET_configuration_ui": "/v1/configuration/ui",
+ "GET_resource_validate_name": "/v1/catalog/resources/validate-name/:name",
+ "GET_activity_log": "/v1/catalog/audit-records/:type/:id",
+ "GET_service": "/v1/catalog/services/:id",
+ "GET_service_validate_name": "/v1/catalog/services/validate-name/:name",
+ "GET_service_distributions":"/v1/catalog/services/:uuid/distribution",
+ "GET_service_distributions_components":"/v1/catalog/services/distribution/:distributionId",
+ "POST_service_distribution_deploy" : "/v1/catalog/services/:serviceId/distribution/:distributionId/markDeployed",
+ "GET_element": "/v1/followed",
+ "GET_catalog": "/v1/screen",
+ "GET_ecomp_menu_items": "/v1/user/:userId/functionalmenu",
+ "GET_resource_category": "/v1/resourceCategories",
+ "GET_service_category": "/v1/serviceCategories",
+ "resource_instance": "/v1/catalog/:entityType/:entityId/resourceInstance/:id",
+ "GET_resource_instance_property": "/v1/catalog/:type/:entityId/resourceInstance/:componentInstanceId/property/:propertyValueId",
+ "GET_relationship": "/v1/catalog/:entityType/:entityId/resourceInstance/:action",
+ "GET_lifecycle_state_resource": "/v1/catalog/:type/:id/lifecycleState/:action",
+ "GET_lifecycle_state_CHECKIN":"lifecycleState/CHECKIN",
+ "GET_lifecycle_state_CERTIFICATIONREQUEST":"lifecycleState/CERTIFICATIONREQUEST",
+ "GET_lifecycle_state_UNDOCHECKOUT":"lifecycleState/UNDOCHECKOUT",
+ "root": "/sdc1/feProxy/rest",
+ "PUT_service": "/v1/catalog/services/:id/metadata",
+ "GET_download_artifact": "/v1/catalog/",
+ "GET_SDC_Version": "/version",
+ "GET_categories": "/v1/categories/:types",
+ "POST_category": "/v1/category/:types/:categoryId",
+ "POST_subcategory": "/v1/category/:types/:categoryId/subCategory/:subCategoryId",
+ "POST_change_instance_version": "/v1/catalog/:entityType/:entityId/resourceInstance/:id/changeVersion",
+ "GET_requirements_capabilities": "/v1/catalog/requirmentsCapabilities/:type/:id",
+ "GET_resource_artifact_types": "/v1/artifactTypes",
+ "GET_product_catalog": "/v1/productScreen",
+ "GET_product_category": "/v1/productCategories",
+ "GET_product_category_temp": "/v1/artifactTypes",
+ "POST_product": "/v1/catalog/products/:id/metadata",
+ "GET_product_validate_name": "/v1/catalog/services/validate-name/:name",
+ "GET_product": "/v1/catalog/products/:id",
+ "GET_product_sub_category": "/v1/productSubCategories",
+ "GET_onboarding": "/sdc1/feProxy/onboarding-api/v1.0/vendor-software-products/packages",
+ "GET_component_from_csar_uuid": "/v1/catalog/resources/csar/:csar_uuid",
+ "kibana": "/sdc1/kibanaProxy/"
+ },
+ "resourceTypesFilter":{
+ "resource":["CP","VFC","VL"],
+ "service":["CP","VF","VL"],
+ "product":[]
+ },
+ "logConfig": {
+ "minLogLevel": "debug",
+ "prefix": "sdcApp"
+ },
+ "cookie": {
+ "junctionName": "IV_JCT",
+ "prefix": "AMWEBJCT!",
+ "userIdSuffix": "USER_ID",
+ "userFirstName": "HTTP_CSP_FIRSTNAME",
+ "userLastName": "HTTP_CSP_LASTNAME",
+ "userEmail": "HTTP_CSP_EMAIL",
+ "xEcompRequestId": " X-ECOMP-RequestID"
+ },
+ "imagesPath": "",
+ "cpEndPointInstances" : ["cloudep","ossep","personep","premisesep"],
+ "toscaFileExtension":"yaml,yml",
+ "csarFileExtension":"csar",
+ "showOutlook": false,
+ "validationConfigPath":"configurations/validation.json",
+ "categories": {},
+ "testers": {
+ "RESOURCE": {
+ "Network L2-3": "DL-ASDCL1-3ResourceCertificationTeam",
+ "Network L4+": "DL-ASDCL4-7ResourceCertificationTeam",
+ "Application L4+": "DL-ASDCL4-7ResourceCertificationTeam",
+ "default": "DL-ASDCL1-3ResourceCertificationTeam;DL-ASDCL4-7ResourceCertificationTeam"
+ },
+ "SERVICE": {
+ "Network L1-3": "DL-ASDCL1-4ServiceCertificationTeam",
+ "Network L4+": "DL-ASDCL4-7ServiceCertificationTeam",
+ "default": "DL-ASDCL1-4ServiceCertificationTeam;DL-ASDCL4-7ServiceCertificationTeam"
+ }
+ },
+ "roles": ["ADMIN", "TESTER", "GOVERNOR", "OPS", "DESIGNER", "PRODUCT_MANAGER", "PRODUCT_STRATEGIST"],
+ "tutorial": {
+ "tabs": [
+ {
+ "id":1,
+ "name":"TUTRIAL_GENERAL_TAB_1",
+ "defaultPage":1
+ },
+ {
+ "id":2,
+ "name":"TUTRIAL_GENERAL_TAB_2",
+ "defaultPage":9
+ },
+ {
+ "id":3,
+ "name":"TUTRIAL_GENERAL_TAB_3",
+ "defaultPage":12
+ }
+ ],
+ "pages":
+ [
+ {
+ "id":1,
+ "template": "text-template",
+ "tab": 1,
+ "data":{
+ "title":"TUTORIAL_PAGE1_TITLE",
+ "description":"TUTORIAL_PAGE1_TEXT"
+ }
+
+ },
+ {
+ "id":2,
+ "template": "image-template",
+ "tab": 1,
+ "data":{
+ "title":"TUTORIAL_PAGE2_TITLE",
+ "description":"TUTORIAL_PAGE2_TEXT",
+ "imageClass":"sdc-tutorial-page-2-image"
+ }
+ },
+ {
+ "id":3,
+ "template": "image-template",
+ "tab": 1,
+ "data":{
+ "title":"TUTORIAL_PAGE3_TITLE",
+ "description":"TUTORIAL_PAGE3_TEXT",
+ "imageClass":"sdc-tutorial-page-3-image"
+ }
+ },
+ {
+ "id":4,
+ "template": "image-template",
+ "tab": 1,
+ "data":{
+ "title":"TUTORIAL_PAGE4_TITLE",
+ "description":"TUTORIAL_PAGE4_TEXT",
+ "imageClass":"sdc-tutorial-page-4-image"
+ }
+ },
+ {
+ "id":5,
+ "template": "image-template",
+ "tab": 1,
+ "data":{
+ "title":"TUTORIAL_PAGE5_TITLE",
+ "description":"TUTORIAL_PAGE5_TEXT",
+ "imageClass":"sdc-tutorial-page-5-image"
+ }
+ },
+ {
+ "id":6,
+ "template": "image-template",
+ "tab": 1,
+ "data":{
+ "title":"TUTORIAL_PAGE6_TITLE",
+ "description":"TUTORIAL_PAGE6_TEXT",
+ "imageClass":"sdc-tutorial-page-6-image"
+ }
+ },
+ {
+ "id":7,
+ "template": "image-template",
+ "tab": 1,
+ "data":{
+ "title":"TUTORIAL_PAGE7_TITLE",
+ "description":"TUTORIAL_PAGE7_TEXT",
+ "imageClass":"sdc-tutorial-page-7-image"
+ }
+ },
+ {
+ "id":8,
+ "template": "image-template",
+ "tab": 1,
+ "data":{
+ "title":"TUTORIAL_PAGE8_TITLE",
+ "description":"TUTORIAL_PAGE8_TEXT",
+ "imageClass":"sdc-tutorial-page-8-image"
+ }
+ },
+ {
+ "id":9,
+ "template": "text-template",
+ "tab": 2,
+ "data":{
+ "title":"TUTORIAL_PAGE9_TITLE",
+ "description":"TUTORIAL_PAGE9_TEXT"
+ }
+ },
+ {
+ "id":10,
+ "template": "image-template",
+ "tab": 2,
+ "data":{
+ "title":"TUTORIAL_PAGE10_TITLE",
+ "description":"TUTORIAL_PAGE10_TEXT",
+ "imageClass":"sdc-tutorial-page-10-image"
+ }
+ },
+ {
+ "id":11,
+ "template": "image-template",
+ "tab": 2,
+ "data":{
+ "title":"TUTORIAL_PAGE11_TITLE",
+ "description":"TUTORIAL_PAGE11_TEXT",
+ "imageClass":"sdc-tutorial-page-11-image"
+ }
+ },
+ {
+ "id":12,
+ "template": "text-template",
+ "tab": 3,
+ "data":{
+ "title":"TUTORIAL_PAGE12_TITLE",
+ "description":"TUTORIAL_PAGE12_TEXT"
+ }
+ },
+ {
+ "id":13,
+ "template": "image-template",
+ "tab": 3,
+ "data":{
+ "title":"TUTORIAL_PAGE13_TITLE",
+ "description":"TUTORIAL_PAGE13_TEXT",
+ "imageClass":"sdc-tutorial-page-13-image"
+ }
+ },
+ {
+ "id":14,
+ "template": "image-template",
+ "tab": 3,
+ "data":{
+ "title":"TUTORIAL_PAGE14_TITLE",
+ "description":"TUTORIAL_PAGE14_TEXT",
+ "imageClass":"sdc-tutorial-page-14-image"
+ }
+ },
+ {
+ "id":15,
+ "template": "image-template",
+ "tab": 3,
+ "data":{
+ "title":"TUTORIAL_PAGE15_TITLE",
+ "description":"TUTORIAL_PAGE15_TEXT",
+ "imageClass":"sdc-tutorial-page-15-image"
+ }
+ },
+ {
+ "id":16,
+ "template": "image-template",
+ "tab": 3,
+ "data":{
+ "title":"TUTORIAL_PAGE16_TITLE",
+ "description":"TUTORIAL_PAGE16_TEXT",
+ "imageClass":"sdc-tutorial-page-16-image"
+ }
+ },
+ {
+ "id":17,
+ "template": "image-template",
+ "tab": 3,
+ "data":{
+ "title":"TUTORIAL_PAGE17_TITLE",
+ "description":"TUTORIAL_PAGE17_TEXT",
+ "imageClass":"sdc-tutorial-page-17-image"
+ }
+ },
+ {
+ "id":18,
+ "template": "image-template",
+ "tab": 3,
+ "data":{
+ "title":"TUTORIAL_PAGE18_TITLE",
+ "description":"TUTORIAL_PAGE18_TEXT",
+ "imageClass":"sdc-tutorial-page-18-image"
+ }
+ },
+ {
+ "id":19,
+ "template": "image-template",
+ "tab": 3,
+ "data":{
+ "title":"TUTORIAL_PAGE19_TITLE",
+ "description":"TUTORIAL_PAGE19_TEXT",
+ "imageClass":"sdc-tutorial-page-19-image"
+ }
+ },
+ {
+ "id":20,
+ "template": "image-template",
+ "tab": 3,
+ "data":{
+ "title":"TUTORIAL_PAGE20_TITLE",
+ "description":"TUTORIAL_PAGE20_TEXT",
+ "imageClass":"sdc-tutorial-page-20-image"
+ }
+ },
+ {
+ "id":21,
+ "template": "image-template",
+ "tab": 3,
+ "data":{
+ "title":"TUTORIAL_PAGE21_TITLE",
+ "description":"TUTORIAL_PAGE21_TEXT",
+ "imageClass":"sdc-tutorial-page-21-image"
+ }
+ },
+ {
+ "id":22,
+ "template": "image-template",
+ "tab": 3,
+ "data":{
+ "title":"TUTORIAL_PAGE22_TITLE",
+ "description":"TUTORIAL_PAGE22_TEXT",
+ "imageClass":"sdc-tutorial-page-22-image"
+ }
+ },
+ {
+ "id":23,
+ "template": "image-template",
+ "tab": 3,
+ "data":{
+ "title":"TUTORIAL_PAGE23_TITLE",
+ "description":"TUTORIAL_PAGE23_TEXT",
+ "imageClass":"sdc-tutorial-page-23-image"
+ }
+ },
+ {
+ "id":24,
+ "template": "image-template",
+ "tab": 3,
+ "data":{
+ "title":"TUTORIAL_PAGE24_TITLE",
+ "description":"TUTORIAL_PAGE24_TEXT",
+ "imageClass":"sdc-tutorial-page-24-image"
+ }
+ },
+ {
+ "id":25,
+ "template": "image-template",
+ "tab": 3,
+ "data":{
+ "title":"TUTORIAL_PAGE25_TITLE",
+ "description":"TUTORIAL_PAGE25_TEXT",
+ "imageClass":"sdc-tutorial-page-25-image"
+ }
+ },
+ {
+ "id":26,
+ "template": "image-template",
+ "tab": 3,
+ "data":{
+ "title":"TUTORIAL_PAGE26_TITLE",
+ "description":"TUTORIAL_PAGE26_TEXT",
+ "imageClass":"sdc-tutorial-page-26-image"
+ }
+ },
+ {
+ "id":27,
+ "template": "image-template",
+ "tab": 3,
+ "data":{
+ "title":"TUTORIAL_PAGE27_TITLE",
+ "description":"TUTORIAL_PAGE27_TEXT",
+ "imageClass":"sdc-tutorial-page-27-image"
+ }
+ },
+ {
+ "id":28,
+ "template": "image-template",
+ "tab": 3,
+ "data":{
+ "title":"TUTORIAL_PAGE28_TITLE",
+ "description":"TUTORIAL_PAGE28_TEXT",
+ "imageClass":"sdc-tutorial-page-28-image"
+ }
+ },
+ {
+ "id":29,
+ "template": "image-template",
+ "tab": 3,
+ "data":{
+ "title":"TUTORIAL_PAGE29_TITLE",
+ "description":"TUTORIAL_PAGE29_TEXT",
+ "imageClass":"sdc-tutorial-page-29-image"
+ }
+ },
+ {
+ "id":30,
+ "template": "image-template",
+ "tab": 3,
+ "data":{
+ "title":"TUTORIAL_PAGE30_TITLE",
+ "description":"TUTORIAL_PAGE30_TEXT",
+ "imageClass":"sdc-tutorial-page-30-image"
+ }
+ }
+
+ ]
+ }
+};
+
+module.exports = SDC_CONFIG; \ No newline at end of file
diff --git a/catalog-ui/configurations/dev.json b/catalog-ui/configurations/dev.json
deleted file mode 100644
index 4cc09d3c31..0000000000
--- a/catalog-ui/configurations/dev.json
+++ /dev/null
@@ -1,430 +0,0 @@
-{
- "environment": "dev",
- "api": {
- "GET_component": "/v1/catalog/:type/:id",
- "PUT_component": "/v1/catalog/:type/:id/metadata",
- "GET_component_validate_name": "/v1/catalog/:type/validate-name/:name",
- "POST_changeLifecycleState": "/v1/catalog/",
- "component_api_root": "/v1/catalog/",
- "welcome_page_video_url": "http://0.0.0.0:8282/moti/movie",
-
- "GET_user": "/v1/user/:id",
- "GET_user_authorize": "/v1/user/authorize",
- "GET_all_users": "/v1/user/users",
- "POST_create_user": "/v1/user",
- "DELETE_delete_user": "/v1/user/:id",
- "POST_edit_user_role": "/v1/user/:id/role",
- "GET_resource": "/v1/catalog/resources/:id",
- "GET_resources_latestversion_notabstract":"/v1/catalog/:type/latestversion/notabstract/:id",
- "GET_resources_certified_not_abstract": "/v1/catalog/resources/certified/notabstract/:id",
- "GET_resources_certified_abstract": "/v1/catalog/resources/certified/abstract/:id",
- "GET_resource_property": "/v1/catalog/:type/:entityId/properties/:id",
- "PUT_resource": "/v1/catalog/resources/:id/metadata",
- "GET_resource_artifact": "/v1/catalog/:type/:entityId/artifacts/:id",
- "GET_download_instance_artifact": "/v1/catalog/:type/:entityId/resourceInstances/:instanceId/artifacts/:id",
- "POST_instance_artifact": "/v1/catalog/:type/:entityId/resourceInstance/:instanceId/artifacts/:id",
- "GET_resource_additional_information": "/v1/catalog/:type/:entityId/additionalinfo/:id",
- "GET_service_artifact": "/v1/catalog/services/:serviceId/artifacts/:id",
- "GET_resource_interface_artifact": "/v1/catalog/:type/:entityId/standard/:operation/artifacts/:id",
- "GET_resource_api_artifact": "/v1/catalog/:type/:entityId/artifacts/api/:id",
- "GET_configuration_ui": "/v1/configuration/ui",
- "GET_resource_validate_name": "/v1/catalog/resources/validate-name/:name",
- "GET_activity_log": "/v1/catalog/audit-records/:type/:id",
- "GET_service": "/v1/catalog/services/:id",
- "GET_service_validate_name": "/v1/catalog/services/validate-name/:name",
- "GET_service_distributions":"/v1/catalog/services/:uuid/distribution",
- "GET_service_distributions_components":"/v1/catalog/services/distribution/:distributionId",
- "POST_service_distribution_deploy" : "/v1/catalog/services/:serviceId/distribution/:distributionId/markDeployed",
- "GET_element": "/v1/followed",
- "GET_catalog": "/v1/screen",
- "GET_ecomp_menu_items": "/v1/user/:userId/functionalmenu",
- "GET_resource_category": "/v1/resourceCategories",
- "GET_service_category": "/v1/serviceCategories",
- "resource_instance": "/v1/catalog/:entityType/:entityId/resourceInstance/:id",
- "GET_resource_instance_property": "/v1/catalog/:type/:entityId/resourceInstance/:componentInstanceId/property/:propertyValueId",
- "GET_relationship": "/v1/catalog/:entityType/:entityId/resourceInstance/:action",
- "GET_lifecycle_state_resource": "/v1/catalog/:type/:id/lifecycleState/:action",
- "GET_lifecycle_state_CHECKIN":"lifecycleState/CHECKIN",
- "GET_lifecycle_state_CERTIFICATIONREQUEST":"lifecycleState/CERTIFICATIONREQUEST",
- "GET_lifecycle_state_UNDOCHECKOUT":"lifecycleState/UNDOCHECKOUT",
- "root": "http://feHost:8181/sdc1/feProxy/rest",
- "PUT_service": "/v1/catalog/services/:id/metadata",
- "GET_download_artifact": "/v1/catalog/",
- "GET_SDC_Version": "/version",
- "GET_categories": "/v1/categories/:types",
- "POST_category": "/v1/category/:types/:categoryId",
- "POST_subcategory": "/v1/category/:types/:categoryId/subCategory/:subCategoryId",
- "POST_change_instance_version": "/v1/catalog/:entityType/:entityId/resourceInstance/:id/changeVersion",
- "GET_requirements_capabilities": "/v1/catalog/requirmentsCapabilities/:type/:id",
- "GET_resource_artifact_types": "/v1/artifactTypes",
- "GET_product_catalog": "/v1/productScreen",
- "GET_product_category": "/v1/productCategories",
- "GET_product_category_temp": "/v1/artifactTypes",
- "POST_product": "/v1/catalog/products/:id/metadata",
- "GET_product_validate_name": "/v1/catalog/services/validate-name/:name",
- "GET_product": "/v1/catalog/products/:id",
- "GET_product_sub_category": "/v1/productSubCategories",
- "GET_onboarding": "http://fehost:8181/sdc1/feProxy/onboarding-api/v1.0/vendor-software-products/packages",
- "GET_component_from_csar_uuid": "/v1/catalog/resources/csar/:csar_uuid",
- "kibana": "/sdc1/kibanaProxy/"
- },
- "resourceTypesFilter":{
- "resource":["CP","VFC"],
- "service":["CP","VF"],
- "product":[]
- },
- "logConfig": {
- "minLogLevel": "debug",
- "prefix": "sdcApp"
- },
- "cookie": {
- "junctionName": "IV_JCT",
- "prefix": "AMWEBJCT!",
- "userIdSuffix": "USER_ID",
- "userFirstName": "HTTP_CSP_FIRSTNAME",
- "userLastName": "HTTP_CSP_LASTNAME",
- "userEmail": "HTTP_CSP_EMAIL",
- "xEcompRequestId": " X-ECOMP-RequestID"
- },
- "imagesPath": "",
- "cpEndPointInstances" : ["cloudep","ossep","personep","premisesep"],
- "toscaFileExtension":"yaml,yml",
- "csarFileExtension":"csar",
- "openSource": true,
- "categories": {},
- "testers": {
- "RESOURCE": {
- "Network L2-3": "DL-ASDCL1-3ResourceCertificationTeam",
- "Network L4+": "DL-ASDCL4-7ResourceCertificationTeam",
- "Application L4+": "DL-ASDCL4-7ResourceCertificationTeam",
- "default": "DL-ASDCL1-3ResourceCertificationTeam;DL-ASDCL4-7ResourceCertificationTeam"
- },
- "SERVICE": {
- "Network L1-3": "DL-ASDCL1-4ServiceCertificationTeam",
- "Network L4+": "DL-ASDCL4-7ServiceCertificationTeam",
- "default": "DL-ASDCL1-4ServiceCertificationTeam;DL-ASDCL4-7ServiceCertificationTeam"
- }
- },
- "roles": ["ADMIN", "TESTER", "GOVERNOR", "OPS", "DESIGNER", "PRODUCT_MANAGER", "PRODUCT_STRATEGIST"],
- "tutorial": {
- "tabs": [
- {
- "id":1,
- "name":"TUTRIAL_GENERAL_TAB_1",
- "defaultPage":1
- },
- {
- "id":2,
- "name":"TUTRIAL_GENERAL_TAB_2",
- "defaultPage":9
- },
- {
- "id":3,
- "name":"TUTRIAL_GENERAL_TAB_3",
- "defaultPage":12
- }
- ],
- "pages":
- [
- {
- "id":1,
- "template": "text-template",
- "tab": 1,
- "data":{
- "title":"TUTORIAL_PAGE1_TITLE",
- "description":"TUTORIAL_PAGE1_TEXT"
- }
-
- },
- {
- "id":2,
- "template": "image-template",
- "tab": 1,
- "data":{
- "title":"TUTORIAL_PAGE2_TITLE",
- "description":"TUTORIAL_PAGE2_TEXT",
- "imageClass":"sdc-tutorial-page-2-image"
- }
- },
- {
- "id":3,
- "template": "image-template",
- "tab": 1,
- "data":{
- "title":"TUTORIAL_PAGE3_TITLE",
- "description":"TUTORIAL_PAGE3_TEXT",
- "imageClass":"sdc-tutorial-page-3-image"
- }
- },
- {
- "id":4,
- "template": "image-template",
- "tab": 1,
- "data":{
- "title":"TUTORIAL_PAGE4_TITLE",
- "description":"TUTORIAL_PAGE4_TEXT",
- "imageClass":"sdc-tutorial-page-4-image"
- }
- },
- {
- "id":5,
- "template": "image-template",
- "tab": 1,
- "data":{
- "title":"TUTORIAL_PAGE5_TITLE",
- "description":"TUTORIAL_PAGE5_TEXT",
- "imageClass":"sdc-tutorial-page-5-image"
- }
- },
- {
- "id":6,
- "template": "image-template",
- "tab": 1,
- "data":{
- "title":"TUTORIAL_PAGE6_TITLE",
- "description":"TUTORIAL_PAGE6_TEXT",
- "imageClass":"sdc-tutorial-page-6-image"
- }
- },
- {
- "id":7,
- "template": "image-template",
- "tab": 1,
- "data":{
- "title":"TUTORIAL_PAGE7_TITLE",
- "description":"TUTORIAL_PAGE7_TEXT",
- "imageClass":"sdc-tutorial-page-7-image"
- }
- },
- {
- "id":8,
- "template": "image-template",
- "tab": 1,
- "data":{
- "title":"TUTORIAL_PAGE8_TITLE",
- "description":"TUTORIAL_PAGE8_TEXT",
- "imageClass":"sdc-tutorial-page-8-image"
- }
- },
- {
- "id":9,
- "template": "text-template",
- "tab": 2,
- "data":{
- "title":"TUTORIAL_PAGE9_TITLE",
- "description":"TUTORIAL_PAGE9_TEXT"
- }
- },
- {
- "id":10,
- "template": "image-template",
- "tab": 2,
- "data":{
- "title":"TUTORIAL_PAGE10_TITLE",
- "description":"TUTORIAL_PAGE10_TEXT",
- "imageClass":"sdc-tutorial-page-10-image"
- }
- },
- {
- "id":11,
- "template": "image-template",
- "tab": 2,
- "data":{
- "title":"TUTORIAL_PAGE11_TITLE",
- "description":"TUTORIAL_PAGE11_TEXT",
- "imageClass":"sdc-tutorial-page-11-image"
- }
- },
- {
- "id":12,
- "template": "text-template",
- "tab": 3,
- "data":{
- "title":"TUTORIAL_PAGE12_TITLE",
- "description":"TUTORIAL_PAGE12_TEXT"
- }
- },
- {
- "id":13,
- "template": "image-template",
- "tab": 3,
- "data":{
- "title":"TUTORIAL_PAGE13_TITLE",
- "description":"TUTORIAL_PAGE13_TEXT",
- "imageClass":"sdc-tutorial-page-13-image"
- }
- },
- {
- "id":14,
- "template": "image-template",
- "tab": 3,
- "data":{
- "title":"TUTORIAL_PAGE14_TITLE",
- "description":"TUTORIAL_PAGE14_TEXT",
- "imageClass":"sdc-tutorial-page-14-image"
- }
- },
- {
- "id":15,
- "template": "image-template",
- "tab": 3,
- "data":{
- "title":"TUTORIAL_PAGE15_TITLE",
- "description":"TUTORIAL_PAGE15_TEXT",
- "imageClass":"sdc-tutorial-page-15-image"
- }
- },
- {
- "id":16,
- "template": "image-template",
- "tab": 3,
- "data":{
- "title":"TUTORIAL_PAGE16_TITLE",
- "description":"TUTORIAL_PAGE16_TEXT",
- "imageClass":"sdc-tutorial-page-16-image"
- }
- },
- {
- "id":17,
- "template": "image-template",
- "tab": 3,
- "data":{
- "title":"TUTORIAL_PAGE17_TITLE",
- "description":"TUTORIAL_PAGE17_TEXT",
- "imageClass":"sdc-tutorial-page-17-image"
- }
- },
- {
- "id":18,
- "template": "image-template",
- "tab": 3,
- "data":{
- "title":"TUTORIAL_PAGE18_TITLE",
- "description":"TUTORIAL_PAGE18_TEXT",
- "imageClass":"sdc-tutorial-page-18-image"
- }
- },
- {
- "id":19,
- "template": "image-template",
- "tab": 3,
- "data":{
- "title":"TUTORIAL_PAGE19_TITLE",
- "description":"TUTORIAL_PAGE19_TEXT",
- "imageClass":"sdc-tutorial-page-19-image"
- }
- },
- {
- "id":20,
- "template": "image-template",
- "tab": 3,
- "data":{
- "title":"TUTORIAL_PAGE20_TITLE",
- "description":"TUTORIAL_PAGE20_TEXT",
- "imageClass":"sdc-tutorial-page-20-image"
- }
- },
- {
- "id":21,
- "template": "image-template",
- "tab": 3,
- "data":{
- "title":"TUTORIAL_PAGE21_TITLE",
- "description":"TUTORIAL_PAGE21_TEXT",
- "imageClass":"sdc-tutorial-page-21-image"
- }
- },
- {
- "id":22,
- "template": "image-template",
- "tab": 3,
- "data":{
- "title":"TUTORIAL_PAGE22_TITLE",
- "description":"TUTORIAL_PAGE22_TEXT",
- "imageClass":"sdc-tutorial-page-22-image"
- }
- },
- {
- "id":23,
- "template": "image-template",
- "tab": 3,
- "data":{
- "title":"TUTORIAL_PAGE23_TITLE",
- "description":"TUTORIAL_PAGE23_TEXT",
- "imageClass":"sdc-tutorial-page-23-image"
- }
- },
- {
- "id":24,
- "template": "image-template",
- "tab": 3,
- "data":{
- "title":"TUTORIAL_PAGE24_TITLE",
- "description":"TUTORIAL_PAGE24_TEXT",
- "imageClass":"sdc-tutorial-page-24-image"
- }
- },
- {
- "id":25,
- "template": "image-template",
- "tab": 3,
- "data":{
- "title":"TUTORIAL_PAGE25_TITLE",
- "description":"TUTORIAL_PAGE25_TEXT",
- "imageClass":"sdc-tutorial-page-25-image"
- }
- },
- {
- "id":26,
- "template": "image-template",
- "tab": 3,
- "data":{
- "title":"TUTORIAL_PAGE26_TITLE",
- "description":"TUTORIAL_PAGE26_TEXT",
- "imageClass":"sdc-tutorial-page-26-image"
- }
- },
- {
- "id":27,
- "template": "image-template",
- "tab": 3,
- "data":{
- "title":"TUTORIAL_PAGE27_TITLE",
- "description":"TUTORIAL_PAGE27_TEXT",
- "imageClass":"sdc-tutorial-page-27-image"
- }
- },
- {
- "id":28,
- "template": "image-template",
- "tab": 3,
- "data":{
- "title":"TUTORIAL_PAGE28_TITLE",
- "description":"TUTORIAL_PAGE28_TEXT",
- "imageClass":"sdc-tutorial-page-28-image"
- }
- },
- {
- "id":29,
- "template": "image-template",
- "tab": 3,
- "data":{
- "title":"TUTORIAL_PAGE29_TITLE",
- "description":"TUTORIAL_PAGE29_TEXT",
- "imageClass":"sdc-tutorial-page-29-image"
- }
- },
- {
- "id":30,
- "template": "image-template",
- "tab": 3,
- "data":{
- "title":"TUTORIAL_PAGE30_TITLE",
- "description":"TUTORIAL_PAGE30_TEXT",
- "imageClass":"sdc-tutorial-page-30-image"
- }
- }
-
- ]
- }
-}
diff --git a/catalog-ui/configurations/menu.json b/catalog-ui/configurations/menu.js
index cd451e79f1..12dda2d78b 100644
--- a/catalog-ui/configurations/menu.json
+++ b/catalog-ui/configurations/menu.js
@@ -1,4 +1,4 @@
-{
+const SDC_MENU_CONFIG = {
"roles":{
"ADMIN":{
"title": "Admin's Workspace",
@@ -6,29 +6,24 @@
"states":{
"NOT_CERTIFIED_CHECKOUT":{
"ANY":[
- {"text":"Submit for Testing","action":"changeLifecycleState", "url":"lifecycleState/certificationRequest" , "emailModal": "lifecycleState/CERTIFICATIONREQUEST"},
- {"text":"View" ,"action":"openViewerModal"}
+ {"text":"Submit for Testing","action":"changeLifecycleState", "url":"lifecycleState/certificationRequest" , "emailModal": "lifecycleState/CERTIFICATIONREQUEST"}
]
},
"NOT_CERTIFIED_CHECKIN": {
"ANY": [
- {"text": "Submit for Testing", "action": "changeLifecycleState", "url": "lifecycleState/certificationRequest", "emailModal": "lifecycleState/CERTIFICATIONREQUEST"},
- {"text": "View","action": "openViewerModal"}
+ {"text": "Submit for Testing", "action": "changeLifecycleState", "url": "lifecycleState/certificationRequest", "emailModal": "lifecycleState/CERTIFICATIONREQUEST"}
]
},
"READY_FOR_CERTIFICATION": {
"ANY":[
- {"text": "View","action": "openViewerModal"}
]
},
"CERTIFICATION_IN_PROGRESS":{
"ANY":[
- {"text":"View" ,"action":"openViewerModal"}
]
},
"CERTIFIED":{
"ANY":[
- {"text":"View" ,"action":"openViewerModal"}
]
}
}
@@ -54,29 +49,24 @@
"states":{
"NOT_CERTIFIED_CHECKOUT":{
"ANY":[
- {"text":"Submit for Testing","action":"changeLifecycleState", "url":"lifecycleState/certificationRequest", "emailModal": "lifecycleState/CERTIFICATIONREQUEST"},
- {"text":"View" ,"action":"openViewerModal"}
+ {"text":"Submit for Testing","action":"changeLifecycleState", "url":"lifecycleState/certificationRequest", "emailModal": "lifecycleState/CERTIFICATIONREQUEST"}
]
},
"NOT_CERTIFIED_CHECKIN": {
"ANY": [
- {"text": "Submit for Testing", "action": "changeLifecycleState", "url": "lifecycleState/certificationRequest", "emailModal": "lifecycleState/CERTIFICATIONREQUEST"},
- {"text": "View","action": "openViewerModal"}
+ {"text": "Submit for Testing", "action": "changeLifecycleState", "url": "lifecycleState/certificationRequest", "emailModal": "lifecycleState/CERTIFICATIONREQUEST"}
]
},
"READY_FOR_CERTIFICATION": {
"ANY":[
- {"text": "View","action": "openViewerModal"}
]
},
"CERTIFICATION_IN_PROGRESS":{
"ANY":[
- {"text":"View" ,"action":"openViewerModal"}
]
},
"CERTIFIED":{
"ANY":[
- {"text":"View" ,"action":"openViewerModal"}
]
}
},
@@ -103,27 +93,22 @@
"states":{
"NOT_CERTIFIED_CHECKOUT":{
"ANY":[
- {"text":"View" ,"action":"openViewerModal"}
]
},
"NOT_CERTIFIED_CHECKIN": {
"ANY": [
- {"text": "View","action": "openViewerModal"}
]
},
"READY_FOR_CERTIFICATION": {
"ANY":[
- {"text": "View","action": "openViewerModal"}
]
},
"CERTIFICATION_IN_PROGRESS":{
"ANY":[
- {"text":"View" ,"action":"openViewerModal"}
]
},
"CERTIFIED":{
"ANY":[
- {"text":"View" ,"action":"openViewerModal"}
]
}
},
@@ -154,27 +139,22 @@
"states":{
"NOT_CERTIFIED_CHECKOUT":{
"ANY":[
- {"text":"View" ,"action":"openViewerModal"}
]
},
"NOT_CERTIFIED_CHECKIN": {
"ANY": [
- {"text": "View","action": "openViewerModal"}
]
},
"READY_FOR_CERTIFICATION": {
"ANY":[
- {"text": "View","action": "openViewerModal"}
]
},
"CERTIFICATION_IN_PROGRESS":{
"ANY":[
- {"text":"View" ,"action":"openViewerModal"}
]
},
"CERTIFIED":{
"ANY":[
- {"text":"View" ,"action":"openViewerModal"}
]
}
},
@@ -207,13 +187,11 @@
"states": {
"READY_FOR_CERTIFICATION":{
"ANY":[
- {"text":"View" ,"action":"openViewerModal"},
{"text":"Start Testing","action":"changeLifecycleState", "url":"lifecycleState/startCertification"}
]
},
"CERTIFICATION_IN_PROGRESS":{
"ANY":[
- {"text":"View" ,"action":"openViewerModal"},
{"text":"Accept","action":"changeLifecycleState", "url":"lifecycleState/certify", "confirmationModal": "lifecycleState/certify"},
{"text":"Reject","action":"changeLifecycleState", "url":"lifecycleState/failCertification", "confirmationModal": "lifecycleState/failCertification"},
{"text":"Cancel","action":"changeLifecycleState", "url":"lifecycleState/cancelCertification", "confirmationModal": "lifecycleState/cancel" }
@@ -234,21 +212,19 @@
"showCreateNewProduct": false
},
"changeLifecycleStateButtons":{
- "DISTRIBUTION_APPROVED":{ "distribute": {"text":"Distribute", "url":"distribution/PROD/activate"},
+ "DISTRIBUTION_APPROVED":{ "distribute": {"text":"Distribute", "url":"distribution/PROD/activate", "conformanceLevelModal": { "url":"distribution-state/reject", "confirmationModal": "distribution-state/reject" }},
"monitor": {"text":"Monitor", "disabled":true}
},
- "DISTRIBUTED":{ "redistribute": {"text":"Redistribute", "url":"distribution/PROD/activate"},
+ "DISTRIBUTED":{ "redistribute": {"text":"Redistribute", "url":"distribution/PROD/activate", "conformanceLevelModal": { "url":"distribution-state/reject", "confirmationModal": "distribution-state/reject" }},
"monitor": {"text":"Monitor", "url":"distribution-state/monitor"}
}
},
"states": {
"CERTIFIED": {
"DISTRIBUTION_APPROVED": [
- {"text": "View","action": "openViewerModal"},
{"text": "Distribute","action":"changeLifecycleState", "url":"distribution/PROD/activate"}
],
"DISTRIBUTED": [
- {"text": "View","action": "openViewerModal"},
{"text": "Monitor","action":"openDistributionModal", "url":"distribution-state/monitor"},
{"text": "Redistribute","action":"changeLifecycleState", "url":"distribution/PROD/activate"}
]
@@ -268,33 +244,29 @@
"showCreateNewProduct": false
},
"changeLifecycleStateButtons":{
- "DISTRIBUTION_NOT_APPROVED":{ "approve": {"text":"Approve", "url":"distribution-state/approve", "confirmationModal": "distribution-state/approve"},
+ "DISTRIBUTION_NOT_APPROVED":{ "approve": {"text":"Approve", "url":"distribution-state/approve", "confirmationModal": "distribution-state/approve", "conformanceLevelModal": { "url":"distribution-state/reject", "confirmationModal": "distribution-state/reject" }},
"reject": {"text":"Reject", "url":"distribution-state/reject", "confirmationModal": "distribution-state/reject"}
},
"DISTRIBUTION_APPROVED":{ "reject": {"text":"Reject", "url":"distribution-state/reject", "confirmationModal": "distribution-state/reject"}
},
"DISTRIBUTED": { "reject": {"text":"Reject", "url":"distribution-state/reject", "confirmationModal": "distribution-state/reject"}
},
- "DISTRIBUTION_REJECTED": { "approve": {"text": "Approve", "url": "distribution-state/approve", "confirmationModal": "distribution-state/approve"}
+ "DISTRIBUTION_REJECTED": { "approve": {"text": "Approve", "url": "distribution-state/approve", "confirmationModal": "distribution-state/approve", "conformanceLevelModal": { "url":"distribution-state/reject", "confirmationModal": "distribution-state/reject" }}
}
},
"states": {
"CERTIFIED": {
"DISTRIBUTION_NOT_APPROVED": [
- {"text": "View","action": "openViewerModal"},
{"text":"Approve","action":"changeLifecycleState", "url":"distribution-state/approve", "confirmationModal": "distribution-state/approve"},
{"text":"Reject","action":"changeLifecycleState", "url":"distribution-state/reject", "confirmationModal": "distribution-state/reject"}
],
"DISTRIBUTION_APPROVED": [
- {"text": "View","action": "openViewerModal"},
{"text":"Reject","action":"changeLifecycleState", "url":"distribution-state/reject", "confirmationModal": "distribution-state/reject"}
],
"DISTRIBUTED": [
- {"text": "View","action": "openViewerModal"},
{"text":"Reject","action":"changeLifecycleState", "url":"distribution-state/reject", "confirmationModal": "distribution-state/reject"}
],
"DISTRIBUTION_REJECTED": [
- {"text": "View","action": "openViewerModal"},
{"text":"Approve","action":"changeLifecycleState", "url":"distribution-state/approve", "confirmationModal": "distribution-state/approve"}
]
}
@@ -311,7 +283,7 @@
"confirmationMessages": {
"lifecycleState/CHECKIN": {"showComment":true, "title": "Check in confirmation", "message": "Please add comment and confirm the check in."},
"lifecycleState/CHECKOUT": {"showComment":true, "title": "Check out confirmation", "message": "Please add comment and confirm the check out."},
- "lifecycleState/certify": {"showComment":true, "title": "Distribution confirmation", "message": "Please add comment and confirm test results."},
+ "lifecycleState/certify": {"showComment":true, "title": "Certification confirmation", "message": "Please add comment and confirm test results."},
"lifecycleState/cancel": {"showComment":true, "title": "Cancel test", "message": "Please add comment and cancel test."},
"lifecycleState/failCertification": {"showComment":true, "title": "Rejection confirmation", "message": "Please add comment and confirm test results."},
"lifecycleState/CERTIFICATIONREQUEST": {"showComment":true, "title": "Submit for testing", "message": "Please add comment and submit for testing."},
@@ -361,32 +333,26 @@
"states":{
"NOT_CERTIFIED_CHECKOUT":{
"ANY":[
- {"text":"Submit for Testing","action":"changeLifecycleState", "url":"lifecycleState/certificationRequest", "emailModal": "lifecycleState/CERTIFICATIONREQUEST"},
- {"text":"View" ,"action":"openViewerModal"}
+ {"text":"Submit for Testing","action":"changeLifecycleState", "url":"lifecycleState/certificationRequest", "emailModal": "lifecycleState/CERTIFICATIONREQUEST"}
],
"NOT_OWNER":[
- {"text":"View" ,"action":"openViewerModal"}
]
},
"NOT_CERTIFIED_CHECKIN": {
"ANY": [
- {"text": "Submit for Testing", "action": "changeLifecycleState", "url": "lifecycleState/certificationRequest", "emailModal": "lifecycleState/CERTIFICATIONREQUEST"},
- {"text": "View","action": "openViewerModal"}
+ {"text": "Submit for Testing", "action": "changeLifecycleState", "url": "lifecycleState/certificationRequest", "emailModal": "lifecycleState/CERTIFICATIONREQUEST"}
]
},
"READY_FOR_CERTIFICATION": {
"ANY":[
- {"text": "View","action": "openViewerModal"}
]
},
"CERTIFICATION_IN_PROGRESS":{
"ANY":[
- {"text":"View" ,"action":"openViewerModal"}
]
},
"CERTIFIED":{
"ANY":[
- {"text":"View" ,"action":"openViewerModal"}
]
}
@@ -396,30 +362,24 @@
"states":{
"NOT_CERTIFIED_CHECKOUT":{
"ANY":[
- {"text":"View" ,"action":"openViewerModal"}
],
"NOT_OWNER":[
- {"text":"View" ,"action":"openViewerModal"}
]
},
"NOT_CERTIFIED_CHECKIN": {
"ANY": [
- {"text": "View","action": "openViewerModal"}
]
},
"READY_FOR_CERTIFICATION": {
"ANY":[
- {"text": "View","action": "openViewerModal"}
]
},
"CERTIFICATION_IN_PROGRESS":{
"ANY":[
- {"text":"View" ,"action":"openViewerModal"}
]
},
"CERTIFIED":{
"ANY":[
- {"text":"View" ,"action":"openViewerModal"}
]
}
},
@@ -443,30 +403,24 @@
"states":{
"NOT_CERTIFIED_CHECKOUT":{
"ANY":[
- {"text":"View" ,"action":"openViewerModal"}
],
"NOT_OWNER":[
- {"text":"View" ,"action":"openViewerModal"}
]
},
"NOT_CERTIFIED_CHECKIN": {
"ANY": [
- {"text": "View","action": "openViewerModal"}
]
},
"READY_FOR_CERTIFICATION": {
"ANY":[
- {"text": "View","action": "openViewerModal"}
]
},
"CERTIFICATION_IN_PROGRESS":{
"ANY":[
- {"text":"View" ,"action":"openViewerModal"}
]
},
"CERTIFIED":{
"ANY":[
- {"text":"View" ,"action":"openViewerModal"}
]
}
},
@@ -484,7 +438,6 @@
"states":{
"ANY":{
"ANY":[
- {"text":"View" ,"action":"openViewerModal"}
]
}
}
@@ -513,6 +466,7 @@
"VFC":[
{"text":"General", "action":"onMenuItemPressed", "state": "workspace.general"},
{"text":"Icon", "action":"onMenuItemPressed", "state": "workspace.icons"},
+ {"text":"Deployment Artifact", "action":"onMenuItemPressed", "state": "workspace.deployment_artifacts"},
{"text":"Information Artifact", "action":"onMenuItemPressed", "state": "workspace.information_artifacts"},
{"text":"TOSCA Artifacts", "action":"onMenuItemPressed", "state": "workspace.tosca_artifacts"},
{"text":"Properties", "action":"onMenuItemPressed", "state": "workspace.properties"},
@@ -523,6 +477,7 @@
"VL":[
{"text":"General", "action":"onMenuItemPressed", "state": "workspace.general"},
{"text":"Icon", "action":"onMenuItemPressed", "state": "workspace.icons"},
+ {"text":"Deployment Artifact", "action":"onMenuItemPressed", "state": "workspace.deployment_artifacts"},
{"text":"Information Artifact", "action":"onMenuItemPressed", "state": "workspace.information_artifacts"},
{"text":"TOSCA Artifacts", "action":"onMenuItemPressed", "state": "workspace.tosca_artifacts"},
{"text":"Properties", "action":"onMenuItemPressed", "state": "workspace.properties"},
@@ -533,6 +488,7 @@
"CP":[
{"text":"General", "action":"onMenuItemPressed", "state": "workspace.general"},
{"text":"Icon", "action":"onMenuItemPressed", "state": "workspace.icons"},
+ {"text":"Deployment Artifact", "action":"onMenuItemPressed", "state": "workspace.deployment_artifacts"},
{"text":"Information Artifact", "action":"onMenuItemPressed", "state": "workspace.information_artifacts"},
{"text":"TOSCA Artifacts", "action":"onMenuItemPressed", "state": "workspace.tosca_artifacts"},
{"text":"Properties", "action":"onMenuItemPressed", "state": "workspace.properties"},
@@ -546,11 +502,12 @@
{"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":"Properties", "action":"onMenuItemPressed", "state": "workspace.properties"},
+ // {"text":"Properties", "action":"onMenuItemPressed", "state": "workspace.properties"},
{"text":"Composition", "action":"onMenuItemPressed", "state": "workspace.composition.details"},
{"text":"Activity Log", "action":"onMenuItemPressed", "state": "workspace.activity_log"},
{"text":"Deployment", "action":"onMenuItemPressed", "state": "workspace.deployment"},
- {"text":"Inputs", "action":"onMenuItemPressed", "state": "workspace.resource_inputs"}
+ // {"text":"Inputs", "action":"onMenuItemPressed", "state": "workspace.resource_inputs"},
+ {"text":"Properties Assignment", "action":"onMenuItemPressed", "state": "workspace.properties_assignment"}
],
"SERVICE":[
{"text":"General", "action":"onMenuItemPressed", "state": "workspace.general"},
@@ -562,7 +519,8 @@
{"text":"Network Call Flow ", "action":"onMenuItemPressed", "state": "workspace.network_call_flow"},
{"text":"Monitor ", "action":"onMenuItemPressed", "state": "workspace.distribution", "disabledRoles": ["ADMIN", "TESTER", "GOVERNOR", "DESIGNER", "PRODUCT_MANAGER", "PRODUCT_STRATEGIST"]},
{"text":"Deployment", "action":"onMenuItemPressed", "state": "workspace.deployment"},
- {"text":"Inputs", "action":"onMenuItemPressed", "state": "workspace.service_inputs"}
+ // {"text":"Inputs", "action":"onMenuItemPressed", "state": "workspace.service_inputs"},
+ {"text":"Properties Assignment", "action":"onMenuItemPressed", "state": "workspace.properties_assignment"}
],
"PRODUCT":[
{"text":"General", "action":"onMenuItemPressed", "state": "workspace.general"},
@@ -572,5 +530,6 @@
]
}
-
}
+
+module.exports = SDC_MENU_CONFIG;
diff --git a/catalog-ui/configurations/mock.json b/catalog-ui/configurations/mock.json
index 21836a837d..2abcbe0ce2 100644
--- a/catalog-ui/configurations/mock.json
+++ b/catalog-ui/configurations/mock.json
@@ -126,13 +126,11 @@
"states":{
"NOT_CERTIFIED_CHECKOUT":[
{"text":"Check in","action":"changeLifecycleState", "url":"CHECKIN"},
- {"text":"View" ,"action":"openViewerModal"},
{"text":"Edit" ,"action":"goToEntity"}
],
"NOT_CERTIFIED_CHECKIN":[
{"text":"Check out","action":"changeLifecycleState", "url":"CHECKOUT"},
- {"text":"Submit for Testing","action":"changeLifecycleState", "url":"certificationRequest"},
- {"text":"View" ,"action":"openViewerModal"}
+ {"text":"Submit for Testing","action":"changeLifecycleState", "url":"certificationRequest"}
],
"READY_FOR_CERTIFICATION":[],
@@ -147,22 +145,17 @@
"NOT_CERTIFIED_CHECKOUT":[
{"text":"Edit" ,"action":"goToEntity"},
{"text":"Check in","action":"changeLifecycleState", "url":"CHECKIN"},
- {"text":"Submit for Testing","action":"changeLifecycleState", "url":"certificationRequest"},
- {"text":"View" ,"action":"openViewerModal"}
+ {"text":"Submit for Testing","action":"changeLifecycleState", "url":"certificationRequest"}
],
"NOT_CERTIFIED_CHECKIN":[
{"text":"Check out","action":"changeLifecycleState", "url":"CHECKOUT"},
- {"text":"Submit for Testing","action":"changeLifecycleState", "url":"certificationRequest"},
- {"text":"View" ,"action":"openViewerModal"}
+ {"text":"Submit for Testing","action":"changeLifecycleState", "url":"certificationRequest"}
],
"READY_FOR_CERTIFICATION":[
- {"text":"View" ,"action":"openViewerModal"}
],
"CERTIFICATION_IN_PROGRESS":[
- {"text":"View" ,"action":"openViewerModal"}
],
"CERTIFIED":[
- {"text":"View" ,"action":"openViewerModal"}
]
}
diff --git a/catalog-ui/configurations/prod.js b/catalog-ui/configurations/prod.js
new file mode 100644
index 0000000000..30cb3f2146
--- /dev/null
+++ b/catalog-ui/configurations/prod.js
@@ -0,0 +1,432 @@
+const SDC_CONFIG = {
+ "environment": "prod",
+ "api": {
+ "GET_component": "/v1/catalog/:type/:id",
+ "PUT_component": "/v1/catalog/:type/:id/metadata",
+ "GET_component_validate_name": "/v1/catalog/:type/validate-name/:name",
+ "POST_changeLifecycleState": "/v1/catalog/",
+ "component_api_root": "/v1/catalog/",
+ "GET_user": "/v1/user/:id",
+ "GET_user_authorize": "/v1/user/authorize",
+ "GET_all_users": "/v1/user/users",
+ "POST_create_user": "/v1/user",
+ "DELETE_delete_user": "/v1/user/:id",
+ "POST_edit_user_role": "/v1/user/:id/role",
+ "GET_resource": "/v1/catalog/resources/:id",
+ "GET_resources_latestversion_notabstract":"/v1/catalog/:type/latestversion/notabstract/:id",
+ "GET_resources_certified_not_abstract": "/v1/catalog/resources/certified/notabstract/:id",
+ "GET_resources_certified_abstract": "/v1/catalog/resources/certified/abstract/:id",
+ "GET_resource_property": "/v1/catalog/:type/:entityId/properties/:id",
+ "PUT_resource": "/v1/catalog/resources/:id/metadata",
+ "GET_resource_artifact": "/v1/catalog/:type/:entityId/artifacts/:id",
+ "GET_download_instance_artifact": "/v1/catalog/:type/:entityId/resourceInstances/:instanceId/artifacts/:id",
+ "POST_instance_artifact": "/v1/catalog/:type/:entityId/resourceInstance/:instanceId/artifacts/:id",
+ "GET_resource_additional_information": "/v1/catalog/:type/:entityId/additionalinfo/:id",
+ "GET_service_artifact": "/v1/catalog/services/:serviceId/artifacts/:id",
+ "GET_resource_interface_artifact": "/v1/catalog/:type/:entityId/standard/:operation/artifacts/:id",
+ "GET_resource_api_artifact": "/v1/catalog/:type/:entityId/artifacts/api/:id",
+ "GET_configuration_ui": "/v1/configuration/ui",
+ "GET_resource_validate_name": "/v1/catalog/resources/validate-name/:name",
+ "GET_activity_log": "/v1/catalog/audit-records/:type/:id",
+ "GET_service": "/v1/catalog/services/:id",
+ "GET_service_validate_name": "/v1/catalog/services/validate-name/:name",
+ "GET_service_distributions":"/v1/catalog/services/:uuid/distribution",
+ "GET_service_distributions_components":"/v1/catalog/services/distribution/:distributionId",
+ "POST_service_distribution_deploy" : "/v1/catalog/services/:serviceId/distribution/:distributionId/markDeployed",
+ "GET_element": "/v1/followed",
+ "GET_catalog": "/v1/screen",
+ "GET_ecomp_menu_items": "/v1/user/:userId/functionalmenu",
+ "GET_resource_category": "/v1/resourceCategories",
+ "GET_service_category": "/v1/serviceCategories",
+ "resource_instance": "/v1/catalog/:entityType/:entityId/resourceInstance/:id",
+ "GET_resource_instance_property": "/v1/catalog/:type/:entityId/resourceInstance/:componentInstanceId/property/:propertyValueId",
+ "GET_relationship": "/v1/catalog/:entityType/:entityId/resourceInstance/:action",
+ "GET_lifecycle_state_resource": "/v1/catalog/:type/:id/lifecycleState/:action",
+ "GET_lifecycle_state_CHECKIN":"lifecycleState/CHECKIN",
+ "GET_lifecycle_state_CERTIFICATIONREQUEST":"lifecycleState/CERTIFICATIONREQUEST",
+ "GET_lifecycle_state_UNDOCHECKOUT":"lifecycleState/UNDOCHECKOUT",
+ "root": "/sdc1/feProxy/rest",
+ "PUT_service": "/v1/catalog/services/:id/metadata",
+ "GET_download_artifact": "/v1/catalog/",
+ "GET_SDC_Version": "/version",
+ "GET_categories": "/v1/categories/:types",
+ "POST_category": "/v1/category/:types/:categoryId",
+ "POST_subcategory": "/v1/category/:types/:categoryId/subCategory/:subCategoryId",
+ "POST_change_instance_version": "/v1/catalog/:entityType/:entityId/resourceInstance/:id/changeVersion",
+ "GET_requirements_capabilities": "/v1/catalog/requirmentsCapabilities/:type/:id",
+ "GET_resource_artifact_types": "/v1/artifactTypes",
+ "GET_product_catalog": "/v1/productScreen",
+ "GET_product_category": "/v1/productCategories",
+ "GET_product_category_temp": "/v1/artifactTypes",
+ "POST_product": "/v1/catalog/products/:id/metadata",
+ "GET_product_validate_name": "/v1/catalog/services/validate-name/:name",
+ "GET_product": "/v1/catalog/products/:id",
+ "GET_product_sub_category": "/v1/productSubCategories",
+ "GET_onboarding": "/sdc1/feProxy/onboarding-api/v1.0/vendor-software-products/packages",
+ "GET_component_from_csar_uuid": "/v1/catalog/resources/csar/:csar_uuid",
+ "kibana": "/sdc1/kibanaProxy/"
+ },
+ "resourceTypesFilter":{
+ "resource":["CP","VFC","VL"],
+ "service":["CP","VF","VL"],
+ "product":[]
+ },
+ "logConfig": {
+ "minLogLevel": "debug",
+ "prefix": "sdcApp"
+ },
+ "cookie": {
+ "junctionName": "IV_JCT",
+ "prefix": "AMWEBJCT!",
+ "userIdSuffix": "USER_ID",
+ "userFirstName": "HTTP_CSP_FIRSTNAME",
+ "userLastName": "HTTP_CSP_LASTNAME",
+ "userEmail": "HTTP_CSP_EMAIL",
+ "xEcompRequestId": " X-ECOMP-RequestID"
+ },
+ "imagesPath": "/sdc1",
+ "cpEndPointInstances" : ["cloudep","ossep","personep","premisesep"],
+ "toscaFileExtension":"yaml,yml",
+ "csarFileExtension":"csar",
+ "showOutlook": false,
+ "validationConfigPath":"sdc1/configurations/validation.json",
+ "categories": {},
+ "testers": {
+ "RESOURCE": {
+ "Network L2-3": "DL-ASDCL1-3ResourceCertificationTeam",
+ "Network L4+": "DL-ASDCL4-7ResourceCertificationTeam",
+ "Application L4+": "DL-ASDCL4-7ResourceCertificationTeam",
+ "default": "DL-ASDCL1-3ResourceCertificationTeam;DL-ASDCL4-7ResourceCertificationTeam"
+ },
+ "SERVICE": {
+ "Network L1-3": "DL-ASDCL1-4ServiceCertificationTeam",
+ "Network L4+": "DL-ASDCL4-7ServiceCertificationTeam",
+ "default": "DL-ASDCL1-4ServiceCertificationTeam;DL-ASDCL4-7ServiceCertificationTeam"
+ }
+ },
+ "roles": ["ADMIN", "TESTER", "GOVERNOR", "OPS", "DESIGNER", "PRODUCT_MANAGER", "PRODUCT_STRATEGIST"],
+ "tutorial": {
+ "tabs": [
+ {
+ "id":1,
+ "name":"TUTRIAL_GENERAL_TAB_1",
+ "defaultPage":1
+ },
+ {
+ "id":2,
+ "name":"TUTRIAL_GENERAL_TAB_2",
+ "defaultPage":9
+ },
+ {
+ "id":3,
+ "name":"TUTRIAL_GENERAL_TAB_3",
+ "defaultPage":12
+ }
+ ],
+ "pages":
+ [
+ {
+ "id":1,
+ "template": "text-template",
+ "tab": 1,
+ "data":{
+ "title":"TUTORIAL_PAGE1_TITLE",
+ "description":"TUTORIAL_PAGE1_TEXT"
+ }
+
+ },
+ {
+ "id":2,
+ "template": "image-template",
+ "tab": 1,
+ "data":{
+ "title":"TUTORIAL_PAGE2_TITLE",
+ "description":"TUTORIAL_PAGE2_TEXT",
+ "imageClass":"sdc-tutorial-page-2-image"
+ }
+ },
+ {
+ "id":3,
+ "template": "image-template",
+ "tab": 1,
+ "data":{
+ "title":"TUTORIAL_PAGE3_TITLE",
+ "description":"TUTORIAL_PAGE3_TEXT",
+ "imageClass":"sdc-tutorial-page-3-image"
+ }
+ },
+ {
+ "id":4,
+ "template": "image-template",
+ "tab": 1,
+ "data":{
+ "title":"TUTORIAL_PAGE4_TITLE",
+ "description":"TUTORIAL_PAGE4_TEXT",
+ "imageClass":"sdc-tutorial-page-4-image"
+ }
+ },
+ {
+ "id":5,
+ "template": "image-template",
+ "tab": 1,
+ "data":{
+ "title":"TUTORIAL_PAGE5_TITLE",
+ "description":"TUTORIAL_PAGE5_TEXT",
+ "imageClass":"sdc-tutorial-page-5-image"
+ }
+ },
+ {
+ "id":6,
+ "template": "image-template",
+ "tab": 1,
+ "data":{
+ "title":"TUTORIAL_PAGE6_TITLE",
+ "description":"TUTORIAL_PAGE6_TEXT",
+ "imageClass":"sdc-tutorial-page-6-image"
+ }
+ },
+ {
+ "id":7,
+ "template": "image-template",
+ "tab": 1,
+ "data":{
+ "title":"TUTORIAL_PAGE7_TITLE",
+ "description":"TUTORIAL_PAGE7_TEXT",
+ "imageClass":"sdc-tutorial-page-7-image"
+ }
+ },
+ {
+ "id":8,
+ "template": "image-template",
+ "tab": 1,
+ "data":{
+ "title":"TUTORIAL_PAGE8_TITLE",
+ "description":"TUTORIAL_PAGE8_TEXT",
+ "imageClass":"sdc-tutorial-page-8-image"
+ }
+ },
+ {
+ "id":9,
+ "template": "text-template",
+ "tab": 2,
+ "data":{
+ "title":"TUTORIAL_PAGE9_TITLE",
+ "description":"TUTORIAL_PAGE9_TEXT"
+ }
+ },
+ {
+ "id":10,
+ "template": "image-template",
+ "tab": 2,
+ "data":{
+ "title":"TUTORIAL_PAGE10_TITLE",
+ "description":"TUTORIAL_PAGE10_TEXT",
+ "imageClass":"sdc-tutorial-page-10-image"
+ }
+ },
+ {
+ "id":11,
+ "template": "image-template",
+ "tab": 2,
+ "data":{
+ "title":"TUTORIAL_PAGE11_TITLE",
+ "description":"TUTORIAL_PAGE11_TEXT",
+ "imageClass":"sdc-tutorial-page-11-image"
+ }
+ },
+ {
+ "id":12,
+ "template": "text-template",
+ "tab": 3,
+ "data":{
+ "title":"TUTORIAL_PAGE12_TITLE",
+ "description":"TUTORIAL_PAGE12_TEXT"
+ }
+ },
+ {
+ "id":13,
+ "template": "image-template",
+ "tab": 3,
+ "data":{
+ "title":"TUTORIAL_PAGE13_TITLE",
+ "description":"TUTORIAL_PAGE13_TEXT",
+ "imageClass":"sdc-tutorial-page-13-image"
+ }
+ },
+ {
+ "id":14,
+ "template": "image-template",
+ "tab": 3,
+ "data":{
+ "title":"TUTORIAL_PAGE14_TITLE",
+ "description":"TUTORIAL_PAGE14_TEXT",
+ "imageClass":"sdc-tutorial-page-14-image"
+ }
+ },
+ {
+ "id":15,
+ "template": "image-template",
+ "tab": 3,
+ "data":{
+ "title":"TUTORIAL_PAGE15_TITLE",
+ "description":"TUTORIAL_PAGE15_TEXT",
+ "imageClass":"sdc-tutorial-page-15-image"
+ }
+ },
+ {
+ "id":16,
+ "template": "image-template",
+ "tab": 3,
+ "data":{
+ "title":"TUTORIAL_PAGE16_TITLE",
+ "description":"TUTORIAL_PAGE16_TEXT",
+ "imageClass":"sdc-tutorial-page-16-image"
+ }
+ },
+ {
+ "id":17,
+ "template": "image-template",
+ "tab": 3,
+ "data":{
+ "title":"TUTORIAL_PAGE17_TITLE",
+ "description":"TUTORIAL_PAGE17_TEXT",
+ "imageClass":"sdc-tutorial-page-17-image"
+ }
+ },
+ {
+ "id":18,
+ "template": "image-template",
+ "tab": 3,
+ "data":{
+ "title":"TUTORIAL_PAGE18_TITLE",
+ "description":"TUTORIAL_PAGE18_TEXT",
+ "imageClass":"sdc-tutorial-page-18-image"
+ }
+ },
+ {
+ "id":19,
+ "template": "image-template",
+ "tab": 3,
+ "data":{
+ "title":"TUTORIAL_PAGE19_TITLE",
+ "description":"TUTORIAL_PAGE19_TEXT",
+ "imageClass":"sdc-tutorial-page-19-image"
+ }
+ },
+ {
+ "id":20,
+ "template": "image-template",
+ "tab": 3,
+ "data":{
+ "title":"TUTORIAL_PAGE20_TITLE",
+ "description":"TUTORIAL_PAGE20_TEXT",
+ "imageClass":"sdc-tutorial-page-20-image"
+ }
+ },
+ {
+ "id":21,
+ "template": "image-template",
+ "tab": 3,
+ "data":{
+ "title":"TUTORIAL_PAGE21_TITLE",
+ "description":"TUTORIAL_PAGE21_TEXT",
+ "imageClass":"sdc-tutorial-page-21-image"
+ }
+ },
+ {
+ "id":22,
+ "template": "image-template",
+ "tab": 3,
+ "data":{
+ "title":"TUTORIAL_PAGE22_TITLE",
+ "description":"TUTORIAL_PAGE22_TEXT",
+ "imageClass":"sdc-tutorial-page-22-image"
+ }
+ },
+ {
+ "id":23,
+ "template": "image-template",
+ "tab": 3,
+ "data":{
+ "title":"TUTORIAL_PAGE23_TITLE",
+ "description":"TUTORIAL_PAGE23_TEXT",
+ "imageClass":"sdc-tutorial-page-23-image"
+ }
+ },
+ {
+ "id":24,
+ "template": "image-template",
+ "tab": 3,
+ "data":{
+ "title":"TUTORIAL_PAGE24_TITLE",
+ "description":"TUTORIAL_PAGE24_TEXT",
+ "imageClass":"sdc-tutorial-page-24-image"
+ }
+ },
+ {
+ "id":25,
+ "template": "image-template",
+ "tab": 3,
+ "data":{
+ "title":"TUTORIAL_PAGE25_TITLE",
+ "description":"TUTORIAL_PAGE25_TEXT",
+ "imageClass":"sdc-tutorial-page-25-image"
+ }
+ },
+ {
+ "id":26,
+ "template": "image-template",
+ "tab": 3,
+ "data":{
+ "title":"TUTORIAL_PAGE26_TITLE",
+ "description":"TUTORIAL_PAGE26_TEXT",
+ "imageClass":"sdc-tutorial-page-26-image"
+ }
+ },
+ {
+ "id":27,
+ "template": "image-template",
+ "tab": 3,
+ "data":{
+ "title":"TUTORIAL_PAGE27_TITLE",
+ "description":"TUTORIAL_PAGE27_TEXT",
+ "imageClass":"sdc-tutorial-page-27-image"
+ }
+ },
+ {
+ "id":28,
+ "template": "image-template",
+ "tab": 3,
+ "data":{
+ "title":"TUTORIAL_PAGE28_TITLE",
+ "description":"TUTORIAL_PAGE28_TEXT",
+ "imageClass":"sdc-tutorial-page-28-image"
+ }
+ },
+ {
+ "id":29,
+ "template": "image-template",
+ "tab": 3,
+ "data":{
+ "title":"TUTORIAL_PAGE29_TITLE",
+ "description":"TUTORIAL_PAGE29_TEXT",
+ "imageClass":"sdc-tutorial-page-29-image"
+ }
+ },
+ {
+ "id":30,
+ "template": "image-template",
+ "tab": 3,
+ "data":{
+ "title":"TUTORIAL_PAGE30_TITLE",
+ "description":"TUTORIAL_PAGE30_TEXT",
+ "imageClass":"sdc-tutorial-page-30-image"
+ }
+ }
+
+ ]
+ }
+
+};
+
+module.exports = SDC_CONFIG;
diff --git a/catalog-ui/configurations/prod.json b/catalog-ui/configurations/prod.json
deleted file mode 100644
index cbe579c3e9..0000000000
--- a/catalog-ui/configurations/prod.json
+++ /dev/null
@@ -1,432 +0,0 @@
-{
- "environment": "prod",
- "api": {
-
- "GET_component": "/v1/catalog/:type/:id",
- "PUT_component": "/v1/catalog/:type/:id/metadata",
- "GET_component_validate_name": "/v1/catalog/:type/validate-name/:name",
- "POST_changeLifecycleState": "/v1/catalog/",
- "component_api_root": "/v1/catalog/",
- "welcome_page_video_url": "http://0.0.0.0:8282/moti/movie",
-
- "GET_user": "/v1/user/:id",
- "GET_user_authorize": "/v1/user/authorize",
- "GET_all_users": "/v1/user/users",
- "POST_create_user": "/v1/user",
- "DELETE_delete_user": "/v1/user/:id",
- "POST_edit_user_role": "/v1/user/:id/role",
- "GET_resource": "/v1/catalog/resources/:id",
- "GET_resources_latestversion_notabstract":"/v1/catalog/:type/latestversion/notabstract/:id",
- "GET_resources_certified_not_abstract": "/v1/catalog/resources/certified/notabstract/:id",
- "GET_resources_certified_abstract": "/v1/catalog/resources/certified/abstract/:id",
- "GET_resource_property": "/v1/catalog/:type/:entityId/properties/:id",
- "PUT_resource": "/v1/catalog/resources/:id/metadata",
- "GET_resource_artifact": "/v1/catalog/:type/:entityId/artifacts/:id",
- "GET_download_instance_artifact": "/v1/catalog/:type/:entityId/resourceInstances/:instanceId/artifacts/:id",
- "POST_instance_artifact": "/v1/catalog/:type/:entityId/resourceInstance/:instanceId/artifacts/:id",
- "GET_resource_additional_information": "/v1/catalog/:type/:entityId/additionalinfo/:id",
- "GET_service_artifact": "/v1/catalog/services/:serviceId/artifacts/:id",
- "GET_resource_interface_artifact": "/v1/catalog/:type/:entityId/standard/:operation/artifacts/:id",
- "GET_resource_api_artifact": "/v1/catalog/:type/:entityId/artifacts/api/:id",
- "GET_configuration_ui": "/v1/configuration/ui",
- "GET_resource_validate_name": "/v1/catalog/resources/validate-name/:name",
- "GET_activity_log": "/v1/catalog/audit-records/:type/:id",
- "GET_service": "/v1/catalog/services/:id",
- "GET_service_validate_name": "/v1/catalog/services/validate-name/:name",
- "GET_service_distributions":"/v1/catalog/services/:uuid/distribution",
- "GET_service_distributions_components":"/v1/catalog/services/distribution/:distributionId",
- "POST_service_distribution_deploy" : "/v1/catalog/services/:serviceId/distribution/:distributionId/markDeployed",
- "GET_element": "/v1/followed",
- "GET_catalog": "/v1/screen",
- "GET_ecomp_menu_items": "/v1/user/:userId/functionalmenu",
- "GET_resource_category": "/v1/resourceCategories",
- "GET_service_category": "/v1/serviceCategories",
- "resource_instance": "/v1/catalog/:entityType/:entityId/resourceInstance/:id",
- "GET_resource_instance_property": "/v1/catalog/:type/:entityId/resourceInstance/:componentInstanceId/property/:propertyValueId",
- "GET_relationship": "/v1/catalog/:entityType/:entityId/resourceInstance/:action",
- "GET_lifecycle_state_resource": "/v1/catalog/:type/:id/lifecycleState/:action",
- "GET_lifecycle_state_CHECKIN":"lifecycleState/CHECKIN",
- "GET_lifecycle_state_CERTIFICATIONREQUEST":"lifecycleState/CERTIFICATIONREQUEST",
- "GET_lifecycle_state_UNDOCHECKOUT":"lifecycleState/UNDOCHECKOUT",
- "root": "/sdc1/feProxy/rest",
- "PUT_service": "/v1/catalog/services/:id/metadata",
- "GET_download_artifact": "/v1/catalog/",
- "GET_SDC_Version": "/version",
- "GET_categories": "/v1/categories/:types",
- "POST_category": "/v1/category/:types/:categoryId",
- "POST_subcategory": "/v1/category/:types/:categoryId/subCategory/:subCategoryId",
- "POST_change_instance_version": "/v1/catalog/:entityType/:entityId/resourceInstance/:id/changeVersion",
- "GET_requirements_capabilities": "/v1/catalog/requirmentsCapabilities/:type/:id",
- "GET_resource_artifact_types": "/v1/artifactTypes",
- "GET_product_catalog": "/v1/productScreen",
- "GET_product_category": "/v1/productCategories",
- "GET_product_category_temp": "/v1/artifactTypes",
- "POST_product": "/v1/catalog/products/:id/metadata",
- "GET_product_validate_name": "/v1/catalog/services/validate-name/:name",
- "GET_product": "/v1/catalog/products/:id",
- "GET_product_sub_category": "/v1/productSubCategories",
- "GET_onboarding": "/sdc1/feProxy/onboarding-api/v1.0/vendor-software-products/packages",
- "GET_component_from_csar_uuid": "/v1/catalog/resources/csar/:csar_uuid",
- "kibana": "/sdc1/kibanaProxy/"
- },
- "resourceTypesFilter":{
- "resource":["CP","VFC"],
- "service":["CP","VF"],
- "product":[]
- },
- "logConfig": {
- "minLogLevel": "debug",
- "prefix": "sdcApp"
- },
- "cookie": {
- "junctionName": "IV_JCT",
- "prefix": "AMWEBJCT!",
- "userIdSuffix": "USER_ID",
- "userFirstName": "HTTP_CSP_FIRSTNAME",
- "userLastName": "HTTP_CSP_LASTNAME",
- "userEmail": "HTTP_CSP_EMAIL",
- "xEcompRequestId": " X-ECOMP-RequestID"
- },
- "imagesPath": "/sdc1",
- "cpEndPointInstances" : ["cloudep","ossep","personep","premisesep"],
- "toscaFileExtension":"yaml,yml",
- "csarFileExtension":"csar",
- "openSource": true,
- "categories": {},
- "testers": {
- "RESOURCE": {
- "Network L2-3": "DL-ASDCL1-3ResourceCertificationTeam",
- "Network L4+": "DL-ASDCL4-7ResourceCertificationTeam",
- "Application L4+": "DL-ASDCL4-7ResourceCertificationTeam",
- "default": "DL-ASDCL1-3ResourceCertificationTeam;DL-ASDCL4-7ResourceCertificationTeam"
- },
- "SERVICE": {
- "Network L1-3": "DL-ASDCL1-4ServiceCertificationTeam",
- "Network L4+": "DL-ASDCL4-7ServiceCertificationTeam",
- "default": "DL-ASDCL1-4ServiceCertificationTeam;DL-ASDCL4-7ServiceCertificationTeam"
- }
- },
- "roles": ["ADMIN", "TESTER", "GOVERNOR", "OPS", "DESIGNER", "PRODUCT_MANAGER", "PRODUCT_STRATEGIST"],
- "tutorial": {
- "tabs": [
- {
- "id":1,
- "name":"TUTRIAL_GENERAL_TAB_1",
- "defaultPage":1
- },
- {
- "id":2,
- "name":"TUTRIAL_GENERAL_TAB_2",
- "defaultPage":9
- },
- {
- "id":3,
- "name":"TUTRIAL_GENERAL_TAB_3",
- "defaultPage":12
- }
- ],
- "pages":
- [
- {
- "id":1,
- "template": "text-template",
- "tab": 1,
- "data":{
- "title":"TUTORIAL_PAGE1_TITLE",
- "description":"TUTORIAL_PAGE1_TEXT"
- }
-
- },
- {
- "id":2,
- "template": "image-template",
- "tab": 1,
- "data":{
- "title":"TUTORIAL_PAGE2_TITLE",
- "description":"TUTORIAL_PAGE2_TEXT",
- "imageClass":"sdc-tutorial-page-2-image"
- }
- },
- {
- "id":3,
- "template": "image-template",
- "tab": 1,
- "data":{
- "title":"TUTORIAL_PAGE3_TITLE",
- "description":"TUTORIAL_PAGE3_TEXT",
- "imageClass":"sdc-tutorial-page-3-image"
- }
- },
- {
- "id":4,
- "template": "image-template",
- "tab": 1,
- "data":{
- "title":"TUTORIAL_PAGE4_TITLE",
- "description":"TUTORIAL_PAGE4_TEXT",
- "imageClass":"sdc-tutorial-page-4-image"
- }
- },
- {
- "id":5,
- "template": "image-template",
- "tab": 1,
- "data":{
- "title":"TUTORIAL_PAGE5_TITLE",
- "description":"TUTORIAL_PAGE5_TEXT",
- "imageClass":"sdc-tutorial-page-5-image"
- }
- },
- {
- "id":6,
- "template": "image-template",
- "tab": 1,
- "data":{
- "title":"TUTORIAL_PAGE6_TITLE",
- "description":"TUTORIAL_PAGE6_TEXT",
- "imageClass":"sdc-tutorial-page-6-image"
- }
- },
- {
- "id":7,
- "template": "image-template",
- "tab": 1,
- "data":{
- "title":"TUTORIAL_PAGE7_TITLE",
- "description":"TUTORIAL_PAGE7_TEXT",
- "imageClass":"sdc-tutorial-page-7-image"
- }
- },
- {
- "id":8,
- "template": "image-template",
- "tab": 1,
- "data":{
- "title":"TUTORIAL_PAGE8_TITLE",
- "description":"TUTORIAL_PAGE8_TEXT",
- "imageClass":"sdc-tutorial-page-8-image"
- }
- },
- {
- "id":9,
- "template": "text-template",
- "tab": 2,
- "data":{
- "title":"TUTORIAL_PAGE9_TITLE",
- "description":"TUTORIAL_PAGE9_TEXT"
- }
- },
- {
- "id":10,
- "template": "image-template",
- "tab": 2,
- "data":{
- "title":"TUTORIAL_PAGE10_TITLE",
- "description":"TUTORIAL_PAGE10_TEXT",
- "imageClass":"sdc-tutorial-page-10-image"
- }
- },
- {
- "id":11,
- "template": "image-template",
- "tab": 2,
- "data":{
- "title":"TUTORIAL_PAGE11_TITLE",
- "description":"TUTORIAL_PAGE11_TEXT",
- "imageClass":"sdc-tutorial-page-11-image"
- }
- },
- {
- "id":12,
- "template": "text-template",
- "tab": 3,
- "data":{
- "title":"TUTORIAL_PAGE12_TITLE",
- "description":"TUTORIAL_PAGE12_TEXT"
- }
- },
- {
- "id":13,
- "template": "image-template",
- "tab": 3,
- "data":{
- "title":"TUTORIAL_PAGE13_TITLE",
- "description":"TUTORIAL_PAGE13_TEXT",
- "imageClass":"sdc-tutorial-page-13-image"
- }
- },
- {
- "id":14,
- "template": "image-template",
- "tab": 3,
- "data":{
- "title":"TUTORIAL_PAGE14_TITLE",
- "description":"TUTORIAL_PAGE14_TEXT",
- "imageClass":"sdc-tutorial-page-14-image"
- }
- },
- {
- "id":15,
- "template": "image-template",
- "tab": 3,
- "data":{
- "title":"TUTORIAL_PAGE15_TITLE",
- "description":"TUTORIAL_PAGE15_TEXT",
- "imageClass":"sdc-tutorial-page-15-image"
- }
- },
- {
- "id":16,
- "template": "image-template",
- "tab": 3,
- "data":{
- "title":"TUTORIAL_PAGE16_TITLE",
- "description":"TUTORIAL_PAGE16_TEXT",
- "imageClass":"sdc-tutorial-page-16-image"
- }
- },
- {
- "id":17,
- "template": "image-template",
- "tab": 3,
- "data":{
- "title":"TUTORIAL_PAGE17_TITLE",
- "description":"TUTORIAL_PAGE17_TEXT",
- "imageClass":"sdc-tutorial-page-17-image"
- }
- },
- {
- "id":18,
- "template": "image-template",
- "tab": 3,
- "data":{
- "title":"TUTORIAL_PAGE18_TITLE",
- "description":"TUTORIAL_PAGE18_TEXT",
- "imageClass":"sdc-tutorial-page-18-image"
- }
- },
- {
- "id":19,
- "template": "image-template",
- "tab": 3,
- "data":{
- "title":"TUTORIAL_PAGE19_TITLE",
- "description":"TUTORIAL_PAGE19_TEXT",
- "imageClass":"sdc-tutorial-page-19-image"
- }
- },
- {
- "id":20,
- "template": "image-template",
- "tab": 3,
- "data":{
- "title":"TUTORIAL_PAGE20_TITLE",
- "description":"TUTORIAL_PAGE20_TEXT",
- "imageClass":"sdc-tutorial-page-20-image"
- }
- },
- {
- "id":21,
- "template": "image-template",
- "tab": 3,
- "data":{
- "title":"TUTORIAL_PAGE21_TITLE",
- "description":"TUTORIAL_PAGE21_TEXT",
- "imageClass":"sdc-tutorial-page-21-image"
- }
- },
- {
- "id":22,
- "template": "image-template",
- "tab": 3,
- "data":{
- "title":"TUTORIAL_PAGE22_TITLE",
- "description":"TUTORIAL_PAGE22_TEXT",
- "imageClass":"sdc-tutorial-page-22-image"
- }
- },
- {
- "id":23,
- "template": "image-template",
- "tab": 3,
- "data":{
- "title":"TUTORIAL_PAGE23_TITLE",
- "description":"TUTORIAL_PAGE23_TEXT",
- "imageClass":"sdc-tutorial-page-23-image"
- }
- },
- {
- "id":24,
- "template": "image-template",
- "tab": 3,
- "data":{
- "title":"TUTORIAL_PAGE24_TITLE",
- "description":"TUTORIAL_PAGE24_TEXT",
- "imageClass":"sdc-tutorial-page-24-image"
- }
- },
- {
- "id":25,
- "template": "image-template",
- "tab": 3,
- "data":{
- "title":"TUTORIAL_PAGE25_TITLE",
- "description":"TUTORIAL_PAGE25_TEXT",
- "imageClass":"sdc-tutorial-page-25-image"
- }
- },
- {
- "id":26,
- "template": "image-template",
- "tab": 3,
- "data":{
- "title":"TUTORIAL_PAGE26_TITLE",
- "description":"TUTORIAL_PAGE26_TEXT",
- "imageClass":"sdc-tutorial-page-26-image"
- }
- },
- {
- "id":27,
- "template": "image-template",
- "tab": 3,
- "data":{
- "title":"TUTORIAL_PAGE27_TITLE",
- "description":"TUTORIAL_PAGE27_TEXT",
- "imageClass":"sdc-tutorial-page-27-image"
- }
- },
- {
- "id":28,
- "template": "image-template",
- "tab": 3,
- "data":{
- "title":"TUTORIAL_PAGE28_TITLE",
- "description":"TUTORIAL_PAGE28_TEXT",
- "imageClass":"sdc-tutorial-page-28-image"
- }
- },
- {
- "id":29,
- "template": "image-template",
- "tab": 3,
- "data":{
- "title":"TUTORIAL_PAGE29_TITLE",
- "description":"TUTORIAL_PAGE29_TEXT",
- "imageClass":"sdc-tutorial-page-29-image"
- }
- },
- {
- "id":30,
- "template": "image-template",
- "tab": 3,
- "data":{
- "title":"TUTORIAL_PAGE30_TITLE",
- "description":"TUTORIAL_PAGE30_TEXT",
- "imageClass":"sdc-tutorial-page-30-image"
- }
- }
-
- ]
- }
-
-}
diff --git a/catalog-ui/configurations/validation.json b/catalog-ui/configurations/validation.json
new file mode 100644
index 0000000000..01b899d7bd
--- /dev/null
+++ b/catalog-ui/configurations/validation.json
@@ -0,0 +1,12 @@
+{
+ "propertyValue": {
+ "max": 2500,
+ "min": 0
+ },
+
+ "validationPatterns": {
+ "string": "^[\\sa-zA-Z0-9+-]+$",
+ "comment": "^[\\u0000-\\u00BF]*$",
+ "integer": "^(([-+]?\\d+)|([-+]?0x[0-9a-fA-F]+))$"
+ }
+}
diff --git a/catalog-ui/docs/colors.jpg b/catalog-ui/docs/colors.jpg
deleted file mode 100644
index edc038c0d2..0000000000
--- a/catalog-ui/docs/colors.jpg
+++ /dev/null
Binary files differ
diff --git a/catalog-ui/e2e/app.e2e-spec.ts b/catalog-ui/e2e/app.e2e-spec.ts
new file mode 100644
index 0000000000..914805e00c
--- /dev/null
+++ b/catalog-ui/e2e/app.e2e-spec.ts
@@ -0,0 +1,14 @@
+import { CatalogUiPage } from './app.po';
+
+describe('catalog-ui App', function() {
+ let page: CatalogUiPage;
+
+ beforeEach(() => {
+ page = new CatalogUiPage();
+ });
+
+ it('should display message saying app works', () => {
+ page.navigateTo();
+ expect(page.getParagraphText()).toEqual('app works!');
+ });
+});
diff --git a/catalog-ui/e2e/app.po.ts b/catalog-ui/e2e/app.po.ts
new file mode 100644
index 0000000000..8084cae329
--- /dev/null
+++ b/catalog-ui/e2e/app.po.ts
@@ -0,0 +1,11 @@
+import { browser, element, by } from 'protractor';
+
+export class CatalogUiPage {
+ navigateTo() {
+ return browser.get('/');
+ }
+
+ getParagraphText() {
+ return element(by.css('app-root h1')).getText();
+ }
+}
diff --git a/catalog-ui/e2e/tsconfig.json b/catalog-ui/e2e/tsconfig.json
new file mode 100644
index 0000000000..656bdb14ff
--- /dev/null
+++ b/catalog-ui/e2e/tsconfig.json
@@ -0,0 +1,16 @@
+{
+ "compileOnSave": false,
+ "compilerOptions": {
+ "declaration": false,
+ "emitDecoratorMetadata": true,
+ "experimentalDecorators": true,
+ "module": "commonjs",
+ "moduleResolution": "node",
+ "outDir": "../dist/out-tsc-e2e",
+ "sourceMap": true,
+ "target": "es5",
+ "typeRoots": [
+ "../node_modules/@types"
+ ]
+ }
+}
diff --git a/catalog-ui/karma.conf.js b/catalog-ui/karma.conf.js
new file mode 100644
index 0000000000..1f2613a346
--- /dev/null
+++ b/catalog-ui/karma.conf.js
@@ -0,0 +1,43 @@
+// Karma configuration file, see link for more information
+// https://karma-runner.github.io/0.13/config/configuration-file.html
+
+module.exports = function (config) {
+ config.set({
+ basePath: '',
+ frameworks: ['jasmine', 'angular-cli'],
+ plugins: [
+ require('karma-jasmine'),
+ require('karma-chrome-launcher'),
+ require('karma-remap-istanbul'),
+ require('angular-cli/plugins/karma')
+ ],
+ files: [
+ { pattern: './src/test.ts', watched: false }
+ ],
+ preprocessors: {
+ './src/test.ts': ['angular-cli']
+ },
+ mime: {
+ 'text/x-typescript': ['ts','tsx']
+ },
+ remapIstanbulReporter: {
+ reports: {
+ html: 'coverage',
+ lcovonly: './coverage/coverage.lcov'
+ }
+ },
+ angularCli: {
+ config: './angular-cli.json',
+ environment: 'dev'
+ },
+ reporters: config.angularCli && config.angularCli.codeCoverage
+ ? ['progress', 'karma-remap-istanbul']
+ : ['progress'],
+ port: 9876,
+ colors: true,
+ logLevel: config.LOG_INFO,
+ autoWatch: true,
+ browsers: ['Chrome'],
+ singleRun: false
+ });
+};
diff --git a/catalog-ui/non_bower_components/cytoscape.js-edge-editation/README.md b/catalog-ui/non_bower_components/cytoscape.js-edge-editation/README.md
deleted file mode 100644
index 909dcb06d1..0000000000
--- a/catalog-ui/non_bower_components/cytoscape.js-edge-editation/README.md
+++ /dev/null
@@ -1,58 +0,0 @@
-# cytoscape.js-edge-editation
-Extension for Cytoscape.js, which adds handles to nodes and allows to create different types of edges
-
-
-## Dependencies
-
-Extension was tested with these versions of libraries:
-
-* jQuery 2.1.1
-* Cytoscape.js 2.6.0
-
-## Install
-
-Use git clone or direct zip download and unpack archive into your project. Then, simply insert \<script\> tag after
-Cytoscape.js and jQuery:
-
-```html
-<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
-<script src="cytoscape.js"></script>
-<script src="CytoscapeEdgeEditation.js"></script>
-```
-
-## How to use
-
-First, you need to initialize extension. After initializing Cytoscape.js:
-
-```js
-var cy = cytoscape({...});
-var handles = new CytoscapeEdgeEditation;
-handles.init(cy);
-```
-
-Then, you need to register handles to certain node types:
-
-```js
-handles.registerHandle({
- positionX: "left", //horizontal position of the handle (left | center | right)
- positionY: "center", //vertical position of the handle (top | center | bottom)
- color: "#48FF00", //color of the handle
- type: "some_type", //stored as data() attribute, can be used for styling
- single: true, //wheter only one edge of this type can start from same node (default false)
- nodeTypeNames: ["type2"] //which types of nodes will contain this handle
- noMultigraph: false //whereter two nodes can't be connected with multiple edges (does not consider orientation)
-});
-
-handles.registerHandle({...});
-handles.registerHandle({...});
-```
-
-Type of node is stored in data section:
-
-```js
-cy.add({
- data: { id: 'n4', type: "type2"},
-});
-```
-![Screenshot](http://i.imgbox.com/drCuXQqu.png)
-![Screenshot](http://i.imgbox.com/23jr7qPa.png)
diff --git a/catalog-ui/non_bower_components/cytoscape.js-edge-editation/index.html b/catalog-ui/non_bower_components/cytoscape.js-edge-editation/index.html
deleted file mode 100644
index d19fd36c24..0000000000
--- a/catalog-ui/non_bower_components/cytoscape.js-edge-editation/index.html
+++ /dev/null
@@ -1,169 +0,0 @@
-<!doctype html>
-<html lang="cs">
-<head>
- <meta charset="UTF-8">
- <title>CytoscapeEdgeEditation</title>
- <script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
- <script src="bower_components/cytoscape/dist/cytoscape.js"></script>
- <script src="CytoscapeEdgeEditation.js"></script>
- <script>
- $(function(){
- //INITIALIZATION
- var domContainer = $(".cy");
- var cy = cytoscape({
- container: domContainer,
- style: [
- {
- selector: 'node[type="type1"]',
- style: {
- 'background-color': '#FFEB12',
- }
- },
- {
- selector: 'node[type="type2"]',
- style: {
- 'background-color': '#2CE8F2',
- }
- },
- {
- selector: 'edge',
- style: {
- 'width': 3,
- 'target-arrow-shape': 'triangle'
- }
- },
- {
- selector: 'edge[type="default"]',
- style: {
- 'line-color': 'green',
- 'target-arrow-color': 'green',
- }
- },
- {
- selector: 'edge[type="yes"]',
- style: {
- 'line-color': '#48FF00',
- 'target-arrow-color': '#48FF00',
- }
- },
- {
- selector: 'edge[type="no"]',
- style: {
- 'line-color': '#ED1000',
- 'target-arrow-color': '#ED1000',
- }
- }
- ]
- });
-
-
- var handles = new CytoscapeEdgeEditation;
- handles.init(cy);
-
- handles.registerHandle({
- positionX: "center",
- positionY: "bottom",
- color: "green",
- type: "default",
- single: false,
- nodeTypeNames: ["type1"]
- });
-
- handles.registerHandle({
- positionX: "center",
- positionY: "top",
- color: "green",
- type: "default",
- single: false,
- nodeTypeNames: ["type1"]
- });
-
- handles.registerHandle({
- positionX: "left",
- positionY: "center",
- color: "green",
- type: "default",
- single: false,
- nodeTypeNames: ["type1"]
- });
-
- handles.registerHandle({
- positionX: "right",
- positionY: "center",
- color: "green",
- type: "default",
- single: false,
- nodeTypeNames: ["type1"]
- // noMultigraph: true
- });
-
- handles.registerHandle({
- positionX: "left",
- positionY: "center",
- color: "#48FF00",
- type: "yes",
- single: true,
- nodeTypeNames: ["type2"]
- });
-
- handles.registerHandle({
- positionX: "right",
- positionY: "center",
- color: "#ED1000",
- type: "no",
- single: true,
- nodeTypeNames: ["type2"]
- });
-
-
- //ADD NODES
- cy.add({
- data: { id: 'n1', type: "type1"},
- });
-
- cy.add({
- data: { id: 'n2', type: "type1"},
- });
-
- cy.add({
- data: { id: 'n3', type: "type1"},
- });
-
- cy.add({
- data: { id: 'n4', type: "type2"},
- });
-
-
- //ADJUST HEIGHT
- var resizeViewport = function(){
- $(".cy").height($(window).height());
- cy.resize();
- };
-
- $(window).resize(resizeViewport);
- resizeViewport();
-
- //LAYOUT
- cy.layout({
- name: 'random',
- fit: true,
- padding: 40,
- boundingBox: {x1: -200, y1:-200, x2:300, y2: 200}
- });
- });
- </script>
- <style>
- * {
- padding: 0;
- margin: 0;
- }
- .cy {
- width: 100%;
- height:100%;
- }
- </style>
-</head>
-<body>
- <div class="cy"></div>
-</body>
-</html> \ No newline at end of file
diff --git a/catalog-ui/package.json b/catalog-ui/package.json
index beb2af9996..075d059753 100644
--- a/catalog-ui/package.json
+++ b/catalog-ui/package.json
@@ -1,41 +1,45 @@
{
"name": "catalog-ui",
- "description": "ASDC Single page application",
+ "version": "1707.1.0",
+ "description": "SDC Single page application",
+ "main": "src/main.ts",
+ "author": "",
"repository": {
"type": "git",
"url": "git@gitlab:root/D2-SDnC.git"
},
+ "scripts": {
+ "designer": "npm start -- --env.role designer",
+ "tester": "npm start -- --env.role tester",
+ "ops": "npm start -- --env.role ops",
+ "governor": "npm start -- --env.role governor",
+ "admin": "npm start -- --env.role admin",
+ "start": "webpack-dev-server",
+ "build": "webpack --config webpack.config.js",
+ "build:prod": "webpack --config webpack.production.js",
+ "test": "karma start ./karma.conf.js",
+ "lint": "ng lint",
+ "e2e": "protractor ./protractor.conf.js",
+ "pree2e": "webdriver-manager update --standalone false --gecko false --quiet"
+ },
"devDependencies": {
"apache-server-configs": "^2.7.1",
+ "autoprefixer": "^6.5.3",
+ "copy-webpack-plugin": "^4.0.1",
"cors": "2.7.1",
- "grunt": "1.0.1",
- "grunt-angular-templates": "1.1.0",
- "grunt-autoprefixer": "3.0.4",
- "grunt-concurrent": "0.5.0",
- "grunt-contrib-clean": "1.0.0",
- "grunt-contrib-concat": "1.0.1",
- "grunt-contrib-connect": "0.10.1",
- "grunt-contrib-copy": "1.0.0",
- "grunt-contrib-cssmin": "0.10.0",
- "grunt-contrib-htmlmin": "2.1.0",
- "grunt-contrib-imagemin": "1.0.1",
- "grunt-contrib-jshint": "1.1.0",
- "grunt-contrib-uglify": "2.0.0",
- "grunt-contrib-watch": "1.0.0",
- "grunt-include-source": "1.0.0",
- "grunt-karma": "2.0.0",
- "grunt-mocha": "1.0.2",
- "grunt-newer": "0.7.0",
- "grunt-ng-constant": "1.1.0",
- "grunt-rev": "0.1.0",
- "grunt-svgmin": "4.0.0",
- "grunt-text-replace": "0.4.0",
- "grunt-tslint": "^3.3.0",
- "grunt-usemin": "3.1.1",
- "grunt-wiredep": "2.0.0",
+ "css-loader": "^0.26.1",
+ "cssnano": "^3.10.0",
+ "exports-loader": "^0.6.3",
+ "express": "^4.14.0",
+ "extract-text-webpack-plugin": "^2.1.0",
+ "file-loader": "^0.10.0",
+ "html-loader": "^0.4.5",
+ "html-webpack-plugin": "^2.28.0",
"http-proxy-middleware": "^0.14.0",
+ "istanbul-instrumenter-loader": "^2.0.0",
"jasmine-core": "2.5.2",
"jshint-stylish": "2.2.1",
+ "json-loader": "^0.5.4",
"karma": "1.4.0",
"karma-chrome-launcher": "0.2.2",
"karma-coverage": "1.1.1",
@@ -45,23 +49,98 @@
"karma-ng-html2js-preprocessor": "1.0.0",
"karma-ng-scenario": "1.0.0",
"karma-phantomjs-launcher": "0.2.1",
+
+ "karma-sourcemap-loader": "^0.3.7",
+ "less": "^2.7.2",
+ "less-loader": "^2.2.3",
"load-grunt-tasks": "3.5.2",
"phantomjs": "2.1.7",
+ "postcss-loader": "^0.13.0",
+ "postcss-url": "^5.1.2",
+ "raw-loader": "^0.5.1",
+ "sass-loader": "^4.1.1",
+ "script-loader": "^0.7.0",
+ "source-map-loader": "^0.1.5",
+ "style-loader": "^0.13.1",
+ "stylus-loader": "^2.4.0",
"time-grunt": "1.4.0",
- "tslint": "^3.15.1"
+ "url-loader": "^0.5.7",
+ "webpack-dev-middleware": "^1.10.1",
+ "webpack-dev-server": "~2.3.0"
},
"engines": {
"node": ">=6.9.4"
},
"dependencies": {
+ "@angular/cli": "^1.0.0-rc.1",
+ "@angular/common": "^2.4.8",
+ "@angular/compiler": "^2.4.8",
+ "@angular/compiler-cli": "^2.4.8",
+ "@angular/core": "^2.4.8",
+ "@angular/forms": "^2.4.8",
+ "@angular/http": "^2.4.8",
+ "@angular/platform-browser": "^2.4.8",
+ "@angular/platform-browser-dynamic": "^2.4.8",
+ "@angular/router": "^3.4.8",
+ "@angular/upgrade": "^2.4.8",
+ "@types/core-js": "^0.9.35",
+ "@types/js-md5": "^0.4.0",
+ "@types/lodash": "^4.14.52",
+ "@types/node": "^7.0.5",
+ "@types/q": "0.0.32",
+ "angular": "^1.6.2",
+ "angular-base64": "^2.0.5",
+ "angular-base64-upload": "^0.1.19",
+ "angular-clipboard": "^1.5.0",
+ "angular-dragdrop": "github:dimkinv/angular-dragdrop",
+ "angular-filter": "^0.5.15",
+ "angular-resizable": "^1.2.0",
+ "angular-resource": "1.5.11",
+ "angular-sanitize": "^1.4.4",
+ "angular-tooltips": "0.1.23",
+ "angular-translate": "^2.15.1",
+ "angular-translate-loader-static-files": "^2.15.1",
+ "angular-ui-bootstrap": "1.3.3",
+ "angular-ui-notification": "^0.3.6",
+ "angular-ui-router": "^0.4.2",
+ "angular-uuid4": "^0.3.1",
+ "angular2-uuid": "^1.1.1",
+ "animate.css": "^3.5.2",
+ "awesome-typescript-loader": "^3.0.8",
+ "babel-core": "^6.23.1",
+ "babel-loader": "^6.3.2",
+ "bootstrap": "^3.3.7",
+ "checklist-model": "^0.11.0",
+ "class-transformer": "^0.1.6",
+ "clean-webpack-plugin": "^0.1.16",
+ "codelyzer": "^2.0.1",
+ "core-js": "^2.4.1",
+ "cytoscape": "^2.7.15",
+ "cytoscape-expand-collapse": "github:bardit/cytoscape.js-expand-collapse",
+ "cytoscape-qtip": "github:bardit/cytoscape.js-qtip",
"cytoscape.js-undo-redo": "^1.0.1",
"express": "4.14.0",
- "grunt-asset-injector": "0.1.0",
- "grunt-contrib-less": "1.4.0",
- "grunt-express-server": "0.5.3",
- "grunt-ts": "5.5.1",
- "grunt-html2js": "0.3.6",
+ "jquery": "^2.2.4",
+ "jqueryui": "^1.11.1",
+ "js-md5": "^0.4.2",
+ "lodash": "^4.17.2",
"multer": "1.2.1",
- "ng-html2js": "2.0.0"
+ "ng-html2js": "2.0.0",
+ "ng-infinite-scroll": "^1.3.0",
+ "perfect-scrollbar": "^0.6.16",
+ "qtip2": "^3.0.3",
+ "reflect-metadata": "^0.1.10",
+ "restangular": "^1.6.1",
+ "rxjs": "^5.2.0",
+ "ts-helpers": "^1.1.2",
+ "ts-node": "^2.1.0",
+ "tslint": "^4.4.2",
+ "typescript": "^2.1.6",
+ "typings": "^2.1.0",
+ "underscore": "^1.8.3",
+ "webpack": "^2.2.1",
+ "webpack-dev-server": "^2.4.1",
+ "webpack-merge": "^4.0.0",
+ "zone.js": "^0.7.7"
}
}
diff --git a/catalog-ui/pom.xml b/catalog-ui/pom.xml
index 1825fd3f2c..9923a6bfa5 100644
--- a/catalog-ui/pom.xml
+++ b/catalog-ui/pom.xml
@@ -5,7 +5,7 @@
<groupId>org.openecomp.sdc</groupId>
<artifactId>catalog-ui</artifactId>
- <packaging>pom</packaging>
+ <packaging>pom</packaging>
<parent>
@@ -25,166 +25,36 @@
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>2.6.1</version>
- <executions>
- <execution>
- <id>clean.fe.webapp.folder</id>
- <phase>initialize</phase>
- <goals>
- <goal>clean</goal>
- </goals>
- <configuration>
+ <executions>
+ <execution>
+ <id>clean.fe.webapp.folder</id>
+ <phase>initialize</phase>
+ <goals>
+ <goal>clean</goal>
+ </goals>
+ <configuration>
- <filesets>
- <fileset>
- <directory>${project.parent.basedir}/catalog-fe/src/main/webapp</directory>
- <includes>
- <include>**/*</include>
- <include>*</include>
- </includes>
- <excludes>
- <exclude>META-INF/*</exclude>
- <exclude>WEB-INF/*</exclude>
- </excludes>
- <followSymlinks>false</followSymlinks>
- </fileset>
- </filesets>
- </configuration>
- </execution>
- </executions>
+ <filesets>
+ <fileset>
+ <directory>${project.parent.basedir}/catalog-fe/src/main/webapp</directory>
+ <includes>
+ <include>**/*</include>
+ <include>*</include>
+ </includes>
+ <excludes>
+ <exclude>META-INF/*</exclude>
+ <exclude>WEB-INF/*</exclude>
+ </excludes>
+ <followSymlinks>false</followSymlinks>
+ </fileset>
+ </filesets>
+ </configuration>
+ </execution>
+ </executions>
</plugin>
<plugin>
- <groupId>io.wcm.maven.plugins</groupId>
- <artifactId>nodejs-maven-plugin</artifactId>
- <executions>
- <execution>
- <phase>compile</phase>
- <goals>
- <goal>run</goal>
- </goals>
- </execution>
- </executions>
- <configuration>
- <tasks>
- <npmInstallTask>
- <workingDirectory>${project.basedir}</workingDirectory>
- </npmInstallTask>
- <nodeJsTask>
- <workingDirectory>${project.basedir}</workingDirectory>
- <moduleName>bower</moduleName>
- <arguments>
- <argument>install</argument>
- </arguments>
- </nodeJsTask>
- <nodeJsTask>
- <workingDirectory>${project.basedir}</workingDirectory>
- <moduleName>grunt</moduleName>
- <arguments>
- <argument>build</argument>
- </arguments>
- </nodeJsTask>
- <!-- <npmInstallTask>
- <workingDirectory>${project.basedir}</workingDirectory>
- </npmInstallTask>
- <nodeJsTask>
- <workingDirectory>${project.basedir}</workingDirectory>
- <moduleName>gulp</moduleName>
- <arguments>
- <argument>build</argument>
- </arguments>
- </nodeJsTask> -->
- </tasks>
- </configuration>
- </plugin>
-
-
- <!-- <plugin>
- <groupId>com.github.eirslett</groupId>
- <artifactId>frontend-maven-plugin</artifactId>
- <version>1.3</version>
- <configuration>
- <nodeVersion>v7.5.0</nodeVersion>
- <nodeDownloadRoot>https://nodejs.org/dist/</nodeDownloadRoot>
- <npmDownloadRoot>https://nodejs.org/dist/npm/</npmDownloadRoot>
- <installDirectory>./</installDirectory>
- </configuration>
- <executions>
- <execution>
- <id>install node and npm</id>
- <goals>
- <goal>install-node-and-npm</goal>
- </goals>
- <phase>generate-resources</phase>
- </execution>
-
- <execution>
- <id>npm install bower</id>
- <goals>
- <goal>npm</goal>
- </goals>
-
- <phase>generate-resources</phase>
-
- <configuration>
- <arguments>install bower</arguments>
- </configuration>
- </execution>
-
- <execution>
- <id>npm install grunt-cli</id>
- <goals>
- <goal>npm</goal>
- </goals>
-
- <phase>generate-resources</phase>
-
- <configuration>
- <arguments>install grunt-cli</arguments>
- </configuration>
- </execution>
-
- <execution>
- <id>npm install</id>
- <goals>
- <goal>npm</goal>
- </goals>
-
- <phase>generate-resources</phase>
-
- <configuration>
- <arguments>install</arguments>
- </configuration>
- </execution>
-
- <execution>
- <id>bower install</id>
- <goals>
- <goal>bower</goal>
- </goals>
-
- <configuration>
- <arguments>install</arguments>
- </configuration>
- </execution>
-
- <execution>
- <id>grunt build</id>
- <goals>
- <goal>grunt</goal>
- </goals>
-
- <phase>generate-resources</phase>
-
- <configuration>
- <arguments>build</arguments>
- </configuration>
- </execution>
-
- </executions>
- </plugin>
- -->
- <plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>2.7</version>
<executions>
@@ -198,7 +68,7 @@
<outputDirectory>${project.parent.basedir}/catalog-fe/src/main/webapp</outputDirectory>
<resources>
<resource>
- <directory>${project.basedir}/app/dist</directory>
+ <directory>${project.basedir}/dist</directory>
<filtering>false</filtering>
</resource>
</resources>
@@ -206,14 +76,56 @@
</execution>
</executions>
</plugin>
+ <plugin>
+ <groupId>com.github.eirslett</groupId>
+ <artifactId>frontend-maven-plugin</artifactId>
+ <version>1.4</version>
+
+ <executions>
+
+ <execution>
+ <id>install node and npm</id>
+ <goals>
+ <goal>install-node-and-npm</goal>
+ </goals>
+ <configuration>
+ <!-- See https://nodejs.org/en/download/ for latest node and npm (lts) versions -->
+ <nodeVersion>v6.9.5</nodeVersion>
+ <npmVersion>3.10.10</npmVersion>
+ </configuration>
+ </execution>
+
+ <execution>
+ <id>npm install</id>
+ <goals>
+ <goal>npm</goal>
+ </goals>
+ <!-- Optional configuration which provides for running any npm command -->
+ <configuration>
+ <arguments>install</arguments>
+ </configuration>
+ </execution>
+
+ <execution>
+ <id>npm run build</id>
+ <goals>
+ <goal>npm</goal>
+ </goals>
+ <configuration>
+ <arguments>run build:prod</arguments>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+
</plugins>
</build>
- <profiles>
+ <profiles>
<profile>
- <id>not-minified</id>
+ <id>CI</id>
<activation>
<activeByDefault>false</activeByDefault>
</activation>
@@ -230,27 +142,12 @@
<goals>
<goal>copy-resources</goal>
</goals>
+
<configuration>
<outputDirectory>${project.parent.basedir}/catalog-fe/src/main/webapp</outputDirectory>
<resources>
<resource>
- <directory>${project.basedir}/app</directory>
- <includes>
- <include>languages/**</include>
- <include>scripts/**</include>
- <include>styles/**</include>
- <include>third-party/**</include>
- <include>index.html</include>
- <include>robots.txt</include>
- <include>favicon.png</include>
- </includes>
- <filtering>false</filtering>
- </resource>
- <resource>
- <directory>${project.basedir}</directory>
- <includes>
- <include>bower_components/**</include>
- </includes>
+ <directory>${project.basedir}/dist</directory>
<filtering>false</filtering>
</resource>
</resources>
@@ -258,9 +155,146 @@
</execution>
</executions>
</plugin>
+
+
+
+ <!-- ============================================= -->
+ <!-- Build the UI module node code -->
+ <!-- ============================================= -->
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>exec-maven-plugin</artifactId>
+ <version>1.4.0</version>
+ <executions>
+
+ <!-- Set execution permissions for the build script -->
+ <execution>
+ <id>set.script.permissions</id>
+ <phase>generate-sources</phase>
+ <goals>
+ <goal>exec</goal>
+ </goals>
+
+ <configuration>
+ <workingDirectory>${project.basedir}</workingDirectory>
+ <executable>/bin/chmod</executable>
+ <arguments>
+ <argument>755</argument>
+ <argument>./build_catalog_ui.sh</argument>
+ </arguments>
+ </configuration>
+ </execution>
+
+ <!-- Run the build script -->
+ <execution>
+ <id>execute grant build</id>
+ <phase>generate-sources</phase>
+ <goals>
+ <goal>exec</goal>
+ </goals>
+
+ <configuration>
+ <workingDirectory>${project.basedir}</workingDirectory>
+ <executable>./build_catalog_ui.sh</executable>
+ </configuration>
+ </execution>
+
+ <!-- Undo checkout the build script -->
+ <execution>
+ <id>undo.checkout.script</id>
+ <phase>generate-sources</phase>
+ <goals>
+ <goal>exec</goal>
+ </goals>
+
+ <configuration>
+ <workingDirectory>${project.basedir}</workingDirectory>
+ <executable>/usr/bin/git</executable>
+ <arguments>
+ <argument>checkout</argument>
+ <argument>--</argument>
+ <argument>./build_catalog_ui.sh</argument>
+ </arguments>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
</plugins>
</build>
</profile>
+
+
+ <profile>
+ <id>Fortify</id>
+ <activation>
+ <activeByDefault>false</activeByDefault>
+ </activation>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>com.fortify.ps.maven.plugin</groupId>
+ <artifactId>sca-maven-plugin</artifactId>
+ <version>4.30</version>
+ <configuration>
+ <source>1.8</source>
+ <buildId>${project.parent.artifactId}</buildId>
+ <toplevelArtifactId>${project.parent.artifactId}</toplevelArtifactId>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+ </profile>
+
+ <profile>
+ <id>not-minified</id>
+ <activation>
+ <activeByDefault>false</activeByDefault>
+ </activation>
+
+ <build>
+ <plugins>
+ <plugin>
+ <artifactId>maven-resources-plugin</artifactId>
+ <version>2.7</version>
+ <executions>
+ <execution>
+ <id>copy-resources</id>
+ <phase>package</phase>
+ <goals>
+ <goal>copy-resources</goal>
+ </goals>
+ <configuration>
+ <outputDirectory>${project.parent.basedir}/catalog-fe/src/main/webapp</outputDirectory>
+ <resources>
+ <resource>
+ <directory>${project.basedir}/app</directory>
+ <includes>
+ <include>languages/**</include>
+ <include>scripts/**</include>
+ <include>styles/**</include>
+ <include>third-party/**</include>
+ <include>index.html</include>
+ <include>robots.txt</include>
+ <include>favicon.png</include>
+ </includes>
+ <filtering>false</filtering>
+ </resource>
+ <resource>
+ <directory>${project.basedir}</directory>
+ <includes>
+ <include>bower_components/**</include>
+ </includes>
+ <filtering>false</filtering>
+ </resource>
+ </resources>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
+ </profile>
</profiles>
</project>
diff --git a/catalog-ui/protractor.conf.js b/catalog-ui/protractor.conf.js
new file mode 100644
index 0000000000..ffded70180
--- /dev/null
+++ b/catalog-ui/protractor.conf.js
@@ -0,0 +1,32 @@
+// Protractor configuration file, see link for more information
+// https://github.com/angular/protractor/blob/master/lib/config.ts
+
+/*global jasmine */
+var SpecReporter = require('jasmine-spec-reporter');
+
+exports.config = {
+ allScriptsTimeout: 11000,
+ specs: [
+ './e2e/**/*.e2e-spec.ts'
+ ],
+ capabilities: {
+ 'browserName': 'chrome'
+ },
+ directConnect: true,
+ baseUrl: 'http://localhost:4200/',
+ framework: 'jasmine',
+ jasmineNodeOpts: {
+ showColors: true,
+ defaultTimeoutInterval: 30000,
+ print: function() {}
+ },
+ useAllAngular2AppRoots: true,
+ beforeLaunch: function() {
+ require('ts-node').register({
+ project: 'e2e'
+ });
+ },
+ onPrepare: function() {
+ jasmine.getEnv().addReporter(new SpecReporter());
+ }
+};
diff --git a/catalog-ui/server-mock/mock-data/artifact/artifact-types.json b/catalog-ui/server-mock/mock-data/artifact/artifact-types.json
deleted file mode 100644
index b9cdabee51..0000000000
--- a/catalog-ui/server-mock/mock-data/artifact/artifact-types.json
+++ /dev/null
@@ -1,23 +0,0 @@
-[
- {
- "name": "CHEF"
- },
- {
- "name": "PUPPET"
- },
- {
- "name": "SHELL"
- },
- {
- "name": "YANG"
- },
- {
- "name": "HEAT"
- },
- {
- "name": "BPEL"
- },
- {
- "name": "DG-XML"
- }
-]
diff --git a/catalog-ui/server-mock/mock-data/category/category.json b/catalog-ui/server-mock/mock-data/category/category.json
deleted file mode 100644
index 2dabb50ba6..0000000000
--- a/catalog-ui/server-mock/mock-data/category/category.json
+++ /dev/null
@@ -1,65 +0,0 @@
-[
- {
- "name": "Infrastructure"
- },
- {
- "name": "Databases"
- },
- {
- "name": "Web Servers"
- },
- {
- "name": "Web Applications"
- },
- {
- "name": "Network Elements"
- },
- {
- "name": "VoIP"
- },
- {
- "name": "IMS"
- },
- {
- "name": "Security"
- },
- {
- "name": "Video"
- },
- {
- "name": "Mobility"
- },
- {
- "name": "IoT"
- },
- {
- "name": "Big Data"
- },
- {
- "name": "WAN Connectivity"
- },
- {
- "name": "LAN Connectivity"
- },
- {
- "name": "Compute as a Service"
- },
- {
- "name": "Platform as a Service"
- },
- {
- "name": "Storage as a Service"
- },
- {
- "name": "Call Control"
- },
- {
- "name": "Collaboration"
- },
- {
- "name": "Messaging"
- },
- {
- "name": "Abstract"
- }
-]
diff --git a/catalog-ui/server-mock/mock-data/element/element.json b/catalog-ui/server-mock/mock-data/element/element.json
deleted file mode 100644
index 181c0edcf2..0000000000
--- a/catalog-ui/server-mock/mock-data/element/element.json
+++ /dev/null
@@ -1,2915 +0,0 @@
-{
- "resources": [
- {
- "uniqueId": "res_hgdgg.0.1",
- "resourceName": "hgdgg",
- "resourceVersion": "0.1",
- "creatorUserId": "cs0008",
- "creatorFullName": "Carlos Santana",
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "creationDate": 1435825652946,
- "lastUpdateDate": 1435825652946,
- "description": "hfhdgfdgfh",
- "icon": "icon-red2",
- "tags": [
- "hgdgg"
- ],
- "category": "Call Control",
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT",
- "derivedFrom": [
- "tosca.nodes.WebApplication"
- ],
- "artifacts": {
-
- },
- "interfaces": {
-
- },
- "capabilities": {
- "app_endpoint": {
- "uniqueId": "capability.res_tosca.nodes.webapplication.1.0.app_endpoint",
- "type": "tosca.capabilities.Endpoint"
- },
- "feature": {
- "uniqueId": "capability.res_tosca.nodes.root.1.0.feature",
- "type": "tosca.capabilities.Node"
- }
- },
- "requirements": {
- "dependency": {
- "uniqueId": "res_tosca.nodes.root.1.0.dependency",
- "capability": "tosca.capabilities.Node",
- "node": "tosca.nodes.Root",
- "relationship": "tosca.relationships.DependsOn"
- },
- "host": {
- "uniqueId": "res_tosca.nodes.webapplication.1.0.host",
- "capability": "tosca.capabilities.Container",
- "node": "tosca.nodes.WebServer",
- "relationship": "tosca.relationships.HostedOn"
- }
- },
- "vendorName": "fhgghf",
- "vendorRelease": "fggf",
- "contactId": "hg1234",
- "abstract": false,
- "highestVersion": true
- },
- {
- "uniqueId": "res_martin223.0.1",
- "resourceName": "martin223",
- "resourceVersion": "0.1",
- "creatorUserId": "cs0008",
- "creatorFullName": "Carlos Santana",
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "creationDate": 1435842460057,
- "lastUpdateDate": 1435842460057,
- "description": "desc",
- "icon": "icon-red2",
- "tags": [
- "martin223",
- "tag"
- ],
- "category": "Databases",
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT",
- "derivedFrom": [
- "tosca.nodes.Root"
- ],
- "artifacts": {
-
- },
- "interfaces": {
-
- },
- "capabilities": {
- "feature": {
- "uniqueId": "capability.res_tosca.nodes.root.1.0.feature",
- "type": "tosca.capabilities.Node"
- }
- },
- "requirements": {
- "dependency": {
- "uniqueId": "res_tosca.nodes.root.1.0.dependency",
- "capability": "tosca.capabilities.Node",
- "node": "tosca.nodes.Root",
- "relationship": "tosca.relationships.DependsOn"
- }
- },
- "vendorName": "Oracle",
- "vendorRelease": "1.2.5",
- "contactId": "Al1234",
- "abstract": false,
- "highestVersion": true
- },
- {
- "uniqueId": "res_mlrlv.0.1",
- "resourceName": "mlrlv",
- "resourceVersion": "0.1",
- "creatorUserId": "cs0008",
- "creatorFullName": "Carlos Santana",
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "creationDate": 1436079916172,
- "lastUpdateDate": 1436079916172,
- "description": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬-®¯°±²³´µ¶•¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ",
- "icon": "icon-red2",
- "tags": [
- "mlrlvtag"
- ],
- "category": "Databases",
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT",
- "derivedFrom": [
- "tosca.nodes.Root"
- ],
- "artifacts": {
-
- },
- "interfaces": {
-
- },
- "capabilities": {
- "feature": {
- "uniqueId": "capability.res_tosca.nodes.root.1.0.feature",
- "type": "tosca.capabilities.Node"
- }
- },
- "requirements": {
- "dependency": {
- "uniqueId": "res_tosca.nodes.root.1.0.dependency",
- "capability": "tosca.capabilities.Node",
- "node": "tosca.nodes.Root",
- "relationship": "tosca.relationships.DependsOn"
- }
- },
- "vendorName": "Oracle",
- "vendorRelease": "1.2.4",
- "contactId": "Al1234",
- "abstract": false,
- "highestVersion": true
- },
- {
- "uniqueId": "res_%&+-.0.1",
- "resourceName": "%&+-",
- "resourceVersion": "0.1",
- "creatorUserId": "cs0008",
- "creatorFullName": "Carlos Santana",
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "creationDate": 1436079975445,
- "lastUpdateDate": 1436079975445,
- "description": "%&+-%&+-%&+-%&+-%&+-%&+-",
- "icon": "icon-red2",
- "tags": [
- "%&+-%&+-"
- ],
- "category": "Databases",
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT",
- "derivedFrom": [
- "tosca.nodes.Root"
- ],
- "artifacts": {
-
- },
- "interfaces": {
-
- },
- "capabilities": {
- "feature": {
- "uniqueId": "capability.res_tosca.nodes.root.1.0.feature",
- "type": "tosca.capabilities.Node"
- }
- },
- "requirements": {
- "dependency": {
- "uniqueId": "res_tosca.nodes.root.1.0.dependency",
- "capability": "tosca.capabilities.Node",
- "node": "tosca.nodes.Root",
- "relationship": "tosca.relationships.DependsOn"
- }
- },
- "vendorName": "%&+-",
- "vendorRelease": "%&+-",
- "contactId": "Al1234",
- "abstract": false,
- "highestVersion": true
- },
- {
- "uniqueId": "res_1.0.1",
- "resourceName": "1",
- "resourceVersion": "0.1",
- "creatorUserId": "cs0008",
- "creatorFullName": "Carlos Santana",
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "creationDate": 1436080002091,
- "lastUpdateDate": 1436080002091,
- "description": "1",
- "icon": "icon-red2",
- "tags": [
- "11"
- ],
- "category": "Databases",
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT",
- "derivedFrom": [
- "tosca.nodes.Root"
- ],
- "artifacts": {
-
- },
- "interfaces": {
-
- },
- "capabilities": {
- "feature": {
- "uniqueId": "capability.res_tosca.nodes.root.1.0.feature",
- "type": "tosca.capabilities.Node"
- }
- },
- "requirements": {
- "dependency": {
- "uniqueId": "res_tosca.nodes.root.1.0.dependency",
- "capability": "tosca.capabilities.Node",
- "node": "tosca.nodes.Root",
- "relationship": "tosca.relationships.DependsOn"
- }
- },
- "vendorName": "1",
- "vendorRelease": "1",
- "contactId": "Al1234",
- "abstract": false,
- "highestVersion": true
- },
- {
- "uniqueId": "res_jjjjjj.0.1",
- "resourceName": "jjjjjj",
- "resourceVersion": "0.1",
- "creatorUserId": "cs0008",
- "creatorFullName": "Carlos Santana",
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "creationDate": 1436080425475,
- "lastUpdateDate": 1436080425475,
- "description": "h",
- "icon": "icon-red2",
- "tags": [
- "jjjjjj"
- ],
- "category": "Collaboration",
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT",
- "derivedFrom": [
- "tosca.nodes.WebServer"
- ],
- "artifacts": {
- "10 numbers limit reached": {
- "uniqueId": "res_jjjjjj.0.1.10 numbers limit reached",
- "artifactType": "CHEF",
- "artifactName": "10 numbers limit reached.png",
- "userIdLastUpdater": "cs0008",
- "creatorFullName": "Carlos Santana",
- "updaterFullName": "Carlos Santana",
- "creationDate": 1436081038417,
- "lastUpdateDate": 1436081038417,
- "esId": "res_jjjjjj.0.1:10 numbers limit reached.png",
- "logicalName": "10 numbers limit reached",
- "description": "dsfsdfs"
- }
- },
- "interfaces": {
-
- },
- "capabilities": {
- "host": {
- "uniqueId": "capability.res_tosca.nodes.webserver.1.0.host",
- "type": "tosca.capabilities.Container",
- "validSourceTypes": [
- "tosca.nodes.WebApplication"
- ]
- },
- "admin_endpoint": {
- "uniqueId": "capability.res_tosca.nodes.webserver.1.0.admin_endpoint",
- "type": "tosca.capabilities.Endpoint.Admin"
- },
- "feature": {
- "uniqueId": "capability.res_tosca.nodes.root.1.0.feature",
- "type": "tosca.capabilities.Node"
- },
- "data_endpoint": {
- "uniqueId": "capability.res_tosca.nodes.webserver.1.0.data_endpoint",
- "type": "tosca.capabilities.Endpoint"
- }
- },
- "requirements": {
- "dependency": {
- "uniqueId": "res_tosca.nodes.root.1.0.dependency",
- "capability": "tosca.capabilities.Node",
- "node": "tosca.nodes.Root",
- "relationship": "tosca.relationships.DependsOn"
- },
- "host": {
- "uniqueId": "res_tosca.nodes.softwarecomponent.1.0.host",
- "capability": "tosca.capabilities.Container",
- "node": "tosca.nodes.Compute",
- "relationship": "tosca.relationships.HostedOn"
- }
- },
- "vendorName": "g",
- "vendorRelease": "f",
- "contactId": "aa1234",
- "abstract": false,
- "highestVersion": true
- },
- {
- "uniqueId": "res_qfdsy.0.1",
- "resourceName": "qfdsy",
- "resourceVersion": "0.1",
- "creatorUserId": "cs0008",
- "creatorFullName": "Carlos Santana",
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "creationDate": 1436084743821,
- "lastUpdateDate": 1436084743821,
- "description": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬-®¯°±²³´µ¶•¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ",
- "icon": "icon-red2",
- "tags": [
- "qfdsytag"
- ],
- "category": "Messaging",
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT",
- "derivedFrom": [
- "tosca.nodes.Root"
- ],
- "artifacts": {
-
- },
- "interfaces": {
-
- },
- "capabilities": {
- "feature": {
- "uniqueId": "capability.res_tosca.nodes.root.1.0.feature",
- "type": "tosca.capabilities.Node"
- }
- },
- "requirements": {
- "dependency": {
- "uniqueId": "res_tosca.nodes.root.1.0.dependency",
- "capability": "tosca.capabilities.Node",
- "node": "tosca.nodes.Root",
- "relationship": "tosca.relationships.DependsOn"
- }
- },
- "vendorName": "Oracle",
- "vendorRelease": "1.2.4",
- "contactId": "Al1234",
- "abstract": false,
- "highestVersion": true
- },
- {
- "uniqueId": "res_nqstw.0.1",
- "resourceName": "nqstw",
- "resourceVersion": "0.1",
- "creatorUserId": "cs0008",
- "creatorFullName": "Carlos Santana",
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "creationDate": 1436084798999,
- "lastUpdateDate": 1436084798999,
- "description": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬-®¯°±²³´µ¶•¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ",
- "icon": "icon-red2",
- "tags": [
- "nqstwtag"
- ],
- "category": "WAN Connectivity",
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT",
- "derivedFrom": [
- "tosca.nodes.Root"
- ],
- "artifacts": {
-
- },
- "interfaces": {
-
- },
- "capabilities": {
- "feature": {
- "uniqueId": "capability.res_tosca.nodes.root.1.0.feature",
- "type": "tosca.capabilities.Node"
- }
- },
- "requirements": {
- "dependency": {
- "uniqueId": "res_tosca.nodes.root.1.0.dependency",
- "capability": "tosca.capabilities.Node",
- "node": "tosca.nodes.Root",
- "relationship": "tosca.relationships.DependsOn"
- }
- },
- "vendorName": "Oracle",
- "vendorRelease": "1.2.4",
- "contactId": "Al1234",
- "abstract": false,
- "highestVersion": true
- },
- {
- "uniqueId": "res_rfpjx.0.1",
- "resourceName": "rfpjx",
- "resourceVersion": "0.1",
- "creatorUserId": "cs0008",
- "creatorFullName": "Carlos Santana",
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "creationDate": 1436084844179,
- "lastUpdateDate": 1436084844179,
- "description": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬-®¯°±²³´µ¶•¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ",
- "icon": "icon-red2",
- "tags": [
- "rfpjxtag"
- ],
- "category": "Messaging",
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT",
- "derivedFrom": [
- "tosca.nodes.Root"
- ],
- "artifacts": {
-
- },
- "interfaces": {
-
- },
- "capabilities": {
- "feature": {
- "uniqueId": "capability.res_tosca.nodes.root.1.0.feature",
- "type": "tosca.capabilities.Node"
- }
- },
- "requirements": {
- "dependency": {
- "uniqueId": "res_tosca.nodes.root.1.0.dependency",
- "capability": "tosca.capabilities.Node",
- "node": "tosca.nodes.Root",
- "relationship": "tosca.relationships.DependsOn"
- }
- },
- "vendorName": "Oracle",
- "vendorRelease": "1.2.4",
- "contactId": "Al1234",
- "abstract": false,
- "highestVersion": true
- },
- {
- "uniqueId": "res_martin22.0.1",
- "resourceName": "martin22",
- "resourceVersion": "0.1",
- "creatorUserId": "cs0008",
- "creatorFullName": "Carlos Santana",
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "creationDate": 1436093847314,
- "lastUpdateDate": 1436093847314,
- "description": "desc",
- "icon": "icon-red2",
- "tags": [
- "martin22",
- "martin22tag"
- ],
- "category": "Security",
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT",
- "derivedFrom": [
- "tosca.nodes.Root"
- ],
- "artifacts": {
- "gizmorambo": {
- "uniqueId": "res_martin22.0.1.gizmorambo",
- "artifactType": "YANG",
- "artifactName": "gizmorambo.jpg",
- "userIdLastUpdater": "cs0008",
- "creatorFullName": "Carlos Santana",
- "updaterFullName": "Carlos Santana",
- "creationDate": 1436093856933,
- "lastUpdateDate": 1436093856933,
- "esId": "res_martin22.0.1:gizmorambo.jpg",
- "logicalName": "gizmorambo",
- "description": "BlaBla"
- }
- },
- "properties": {
- "Test1": {
- "uniqueId": "res_martin22.0.1.Test1",
- "type": "string",
- "required": false,
- "defaultValue": "10",
- "description": "BlaBla",
- "constraints": [
- {
- "rangeMinValue": "100",
- "rangeMaxValue": "990"
- }
- ],
- "definition": true,
- "password": false
- }
- },
- "interfaces": {
-
- },
- "capabilities": {
- "feature": {
- "uniqueId": "capability.res_tosca.nodes.root.1.0.feature",
- "type": "tosca.capabilities.Node"
- }
- },
- "requirements": {
- "dependency": {
- "uniqueId": "res_tosca.nodes.root.1.0.dependency",
- "capability": "tosca.capabilities.Node",
- "node": "tosca.nodes.Root",
- "relationship": "tosca.relationships.DependsOn"
- }
- },
- "vendorName": "Oracle",
- "vendorRelease": "1.2.5",
- "contactId": "Al1234",
- "abstract": false,
- "highestVersion": true
- },
- {
- "uniqueId": "res_jkjk.0.1",
- "resourceName": "jkjk",
- "resourceVersion": "0.1",
- "creatorUserId": "cs0008",
- "creatorFullName": "Carlos Santana",
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "creationDate": 1436095288548,
- "lastUpdateDate": 1436095288548,
- "description": "jkjkj",
- "icon": "icon-red2",
- "tags": [
- "jkjk"
- ],
- "category": "Big Data",
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT",
- "derivedFrom": [
- "tosca.nodes.Container.Runtime"
- ],
- "artifacts": {
-
- },
- "interfaces": {
-
- },
- "capabilities": {
- "host": {
- "uniqueId": "capability.res_tosca.nodes.container.runtime.1.0.host",
- "type": "tosca.capabilities.Container"
- },
- "scalable": {
- "uniqueId": "capability.res_tosca.nodes.container.runtime.1.0.scalable",
- "type": "tosca.capabilities.Scalable"
- },
- "feature": {
- "uniqueId": "capability.res_tosca.nodes.root.1.0.feature",
- "type": "tosca.capabilities.Node"
- }
- },
- "requirements": {
- "dependency": {
- "uniqueId": "res_tosca.nodes.root.1.0.dependency",
- "capability": "tosca.capabilities.Node",
- "node": "tosca.nodes.Root",
- "relationship": "tosca.relationships.DependsOn"
- },
- "host": {
- "uniqueId": "res_tosca.nodes.softwarecomponent.1.0.host",
- "capability": "tosca.capabilities.Container",
- "node": "tosca.nodes.Compute",
- "relationship": "tosca.relationships.HostedOn"
- }
- },
- "vendorName": "gggg",
- "vendorRelease": "fffff",
- "contactId": "ff1234",
- "abstract": false,
- "highestVersion": true
- },
- {
- "uniqueId": "res_bvbvcxb.0.1",
- "resourceName": "bvbvcxb",
- "resourceVersion": "0.1",
- "creatorUserId": "cs0008",
- "creatorFullName": "Carlos Santana",
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "creationDate": 1436164182890,
- "lastUpdateDate": 1436164182890,
- "description": "vcbcv",
- "icon": "icon-red2",
- "tags": [
- "bvbvcxb"
- ],
- "category": "Call Control",
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT",
- "derivedFrom": [
- "tosca.nodes.WebServer"
- ],
- "artifacts": {
-
- },
- "interfaces": {
-
- },
- "capabilities": {
- "host": {
- "uniqueId": "capability.res_tosca.nodes.webserver.1.0.host",
- "type": "tosca.capabilities.Container",
- "validSourceTypes": [
- "tosca.nodes.WebApplication"
- ]
- },
- "admin_endpoint": {
- "uniqueId": "capability.res_tosca.nodes.webserver.1.0.admin_endpoint",
- "type": "tosca.capabilities.Endpoint.Admin"
- },
- "feature": {
- "uniqueId": "capability.res_tosca.nodes.root.1.0.feature",
- "type": "tosca.capabilities.Node"
- },
- "data_endpoint": {
- "uniqueId": "capability.res_tosca.nodes.webserver.1.0.data_endpoint",
- "type": "tosca.capabilities.Endpoint"
- }
- },
- "requirements": {
- "dependency": {
- "uniqueId": "res_tosca.nodes.root.1.0.dependency",
- "capability": "tosca.capabilities.Node",
- "node": "tosca.nodes.Root",
- "relationship": "tosca.relationships.DependsOn"
- },
- "host": {
- "uniqueId": "res_tosca.nodes.softwarecomponent.1.0.host",
- "capability": "tosca.capabilities.Container",
- "node": "tosca.nodes.Compute",
- "relationship": "tosca.relationships.HostedOn"
- }
- },
- "vendorName": "vcbxcvb",
- "vendorRelease": "cvbvc",
- "contactId": "qw1234",
- "abstract": false,
- "highestVersion": true
- },
- {
- "uniqueId": "res_sd.0.1",
- "resourceName": "sd",
- "resourceVersion": "0.1",
- "creatorUserId": "cs0008",
- "creatorFullName": "Carlos Santana",
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "creationDate": 1436255440040,
- "lastUpdateDate": 1436255440040,
- "description": "de",
- "icon": "icon-red3",
- "tags": [
- "sdde"
- ],
- "category": "Call Control",
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT",
- "derivedFrom": [
- "tosca.nodes.Root"
- ],
- "artifacts": {
-
- },
- "interfaces": {
-
- },
- "capabilities": {
- "feature": {
- "uniqueId": "capability.res_tosca.nodes.root.1.0.feature",
- "type": "tosca.capabilities.Node"
- }
- },
- "requirements": {
- "dependency": {
- "uniqueId": "res_tosca.nodes.root.1.0.dependency",
- "capability": "tosca.capabilities.Node",
- "node": "tosca.nodes.Root",
- "relationship": "tosca.relationships.DependsOn"
- }
- },
- "vendorName": "ded",
- "vendorRelease": "ede",
- "contactId": "dd2222",
- "abstract": false,
- "highestVersion": true
- },
- {
- "uniqueId": "res_martin221.0.1",
- "resourceName": "martin221",
- "resourceVersion": "0.1",
- "creatorUserId": "cs0008",
- "creatorFullName": "Carlos Santana",
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "creationDate": 1436275310912,
- "lastUpdateDate": 1436275310912,
- "description": "desc",
- "icon": "icon-red2",
- "tags": [
- "martin221",
- "martin221tag"
- ],
- "category": "Security",
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT",
- "derivedFrom": [
- "tosca.nodes.WebServer"
- ],
- "artifacts": {
-
- },
- "interfaces": {
-
- },
- "capabilities": {
- "host": {
- "uniqueId": "capability.res_tosca.nodes.webserver.1.0.host",
- "type": "tosca.capabilities.Container",
- "validSourceTypes": [
- "tosca.nodes.WebApplication"
- ]
- },
- "admin_endpoint": {
- "uniqueId": "capability.res_tosca.nodes.webserver.1.0.admin_endpoint",
- "type": "tosca.capabilities.Endpoint.Admin"
- },
- "feature": {
- "uniqueId": "capability.res_tosca.nodes.root.1.0.feature",
- "type": "tosca.capabilities.Node"
- },
- "data_endpoint": {
- "uniqueId": "capability.res_tosca.nodes.webserver.1.0.data_endpoint",
- "type": "tosca.capabilities.Endpoint"
- }
- },
- "requirements": {
- "dependency": {
- "uniqueId": "res_tosca.nodes.root.1.0.dependency",
- "capability": "tosca.capabilities.Node",
- "node": "tosca.nodes.Root",
- "relationship": "tosca.relationships.DependsOn"
- },
- "host": {
- "uniqueId": "res_tosca.nodes.softwarecomponent.1.0.host",
- "capability": "tosca.capabilities.Container",
- "node": "tosca.nodes.Compute",
- "relationship": "tosca.relationships.HostedOn"
- }
- },
- "vendorName": "Oracle",
- "vendorRelease": "1.2.5",
- "contactId": "Al1234",
- "abstract": false,
- "highestVersion": true
- },
- {
- "uniqueId": "res_gfnfgf.0.1",
- "resourceName": "gfnfgf",
- "resourceVersion": "0.1",
- "creatorUserId": "cs0008",
- "creatorFullName": "Carlos Santana",
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "creationDate": 1436275654252,
- "lastUpdateDate": 1436275654252,
- "description": "hfghfgh",
- "icon": "icon-red2",
- "tags": [
- "gfnfgf"
- ],
- "category": "Call Control",
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT",
- "derivedFrom": [
- "tosca.nodes.WebServer"
- ],
- "artifacts": {
-
- },
- "interfaces": {
-
- },
- "capabilities": {
- "host": {
- "uniqueId": "capability.res_tosca.nodes.webserver.1.0.host",
- "type": "tosca.capabilities.Container",
- "validSourceTypes": [
- "tosca.nodes.WebApplication"
- ]
- },
- "admin_endpoint": {
- "uniqueId": "capability.res_tosca.nodes.webserver.1.0.admin_endpoint",
- "type": "tosca.capabilities.Endpoint.Admin"
- },
- "feature": {
- "uniqueId": "capability.res_tosca.nodes.root.1.0.feature",
- "type": "tosca.capabilities.Node"
- },
- "data_endpoint": {
- "uniqueId": "capability.res_tosca.nodes.webserver.1.0.data_endpoint",
- "type": "tosca.capabilities.Endpoint"
- }
- },
- "requirements": {
- "dependency": {
- "uniqueId": "res_tosca.nodes.root.1.0.dependency",
- "capability": "tosca.capabilities.Node",
- "node": "tosca.nodes.Root",
- "relationship": "tosca.relationships.DependsOn"
- },
- "host": {
- "uniqueId": "res_tosca.nodes.softwarecomponent.1.0.host",
- "capability": "tosca.capabilities.Container",
- "node": "tosca.nodes.Compute",
- "relationship": "tosca.relationships.HostedOn"
- }
- },
- "vendorName": "gfhgf",
- "vendorRelease": "gfhgf",
- "contactId": "gg1234",
- "abstract": false,
- "highestVersion": true
- },
- {
- "uniqueId": "res_ddd.0.1",
- "resourceName": "ddd",
- "resourceVersion": "0.1",
- "creatorUserId": "cs0008",
- "creatorFullName": "Carlos Santana",
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "creationDate": 1436338105711,
- "lastUpdateDate": 1436338105711,
- "description": "dsff",
- "icon": "icon-red1",
- "tags": [
- "sddd"
- ],
- "category": "Big Data",
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT",
- "derivedFrom": [
- "tosca.nodes.SoftwareComponent"
- ],
- "artifacts": {
-
- },
- "interfaces": {
-
- },
- "capabilities": {
- "feature": {
- "uniqueId": "capability.res_tosca.nodes.root.1.0.feature",
- "type": "tosca.capabilities.Node"
- }
- },
- "requirements": {
- "dependency": {
- "uniqueId": "res_tosca.nodes.root.1.0.dependency",
- "capability": "tosca.capabilities.Node",
- "node": "tosca.nodes.Root",
- "relationship": "tosca.relationships.DependsOn"
- },
- "host": {
- "uniqueId": "res_tosca.nodes.softwarecomponent.1.0.host",
- "capability": "tosca.capabilities.Container",
- "node": "tosca.nodes.Compute",
- "relationship": "tosca.relationships.HostedOn"
- }
- },
- "vendorName": "sadfasdf",
- "vendorRelease": "adsfadsf",
- "contactId": "ds200p",
- "abstract": false,
- "highestVersion": true
- },
- {
- "uniqueId": "res_hhdfd.0.1",
- "resourceName": "hhdfd",
- "resourceVersion": "0.1",
- "creatorUserId": "cs0008",
- "creatorFullName": "Carlos Santana",
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "creationDate": 1436342424025,
- "lastUpdateDate": 1436342424025,
- "description": "fdhdffh",
- "icon": "icon-red2",
- "tags": [
- "hhdfd"
- ],
- "category": "Big Data",
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT",
- "derivedFrom": [
- "tosca.nodes.Root"
- ],
- "artifacts": {
-
- },
- "interfaces": {
-
- },
- "capabilities": {
- "feature": {
- "uniqueId": "capability.res_tosca.nodes.root.1.0.feature",
- "type": "tosca.capabilities.Node"
- }
- },
- "requirements": {
- "dependency": {
- "uniqueId": "res_tosca.nodes.root.1.0.dependency",
- "capability": "tosca.capabilities.Node",
- "node": "tosca.nodes.Root",
- "relationship": "tosca.relationships.DependsOn"
- }
- },
- "vendorName": "fdhfddfh",
- "vendorRelease": "fdhdf",
- "contactId": "fg1234",
- "abstract": false,
- "highestVersion": true
- },
- {
- "uniqueId": "res_infobae.0.1",
- "resourceName": "infobae",
- "resourceVersion": "0.1",
- "creatorUserId": "cs0008",
- "creatorFullName": "Carlos Santana",
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "creationDate": 1436346185743,
- "lastUpdateDate": 1436346185743,
- "description": "es el",
- "icon": "icon-red2",
- "tags": [
- "infobae"
- ],
- "category": "Big Data",
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT",
- "derivedFrom": [
- "tosca.nodes.WebApplication"
- ],
- "artifacts": {
-
- },
- "interfaces": {
-
- },
- "capabilities": {
- "app_endpoint": {
- "uniqueId": "capability.res_tosca.nodes.webapplication.1.0.app_endpoint",
- "type": "tosca.capabilities.Endpoint"
- },
- "feature": {
- "uniqueId": "capability.res_tosca.nodes.root.1.0.feature",
- "type": "tosca.capabilities.Node"
- }
- },
- "requirements": {
- "dependency": {
- "uniqueId": "res_tosca.nodes.root.1.0.dependency",
- "capability": "tosca.capabilities.Node",
- "node": "tosca.nodes.Root",
- "relationship": "tosca.relationships.DependsOn"
- },
- "host": {
- "uniqueId": "res_tosca.nodes.webapplication.1.0.host",
- "capability": "tosca.capabilities.Container",
- "node": "tosca.nodes.WebServer",
- "relationship": "tosca.relationships.HostedOn"
- }
- },
- "vendorName": "ffff",
- "vendorRelease": "ffff",
- "contactId": "ss1234",
- "abstract": false,
- "highestVersion": true
- },
- {
- "uniqueId": "res_df.0.1",
- "resourceName": "df",
- "resourceVersion": "0.1",
- "creatorUserId": "cs0008",
- "creatorFullName": "Carlos Santana",
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "creationDate": 1436352980564,
- "lastUpdateDate": 1436352980564,
- "description": "sdf",
- "icon": "icon-red2",
- "tags": [
- "dfsdf"
- ],
- "category": "Messaging",
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT",
- "derivedFrom": [
- "tosca.nodes.WebServer"
- ],
- "artifacts": {
-
- },
- "interfaces": {
-
- },
- "capabilities": {
- "host": {
- "uniqueId": "capability.res_tosca.nodes.webserver.1.0.host",
- "type": "tosca.capabilities.Container",
- "validSourceTypes": [
- "tosca.nodes.WebApplication"
- ]
- },
- "admin_endpoint": {
- "uniqueId": "capability.res_tosca.nodes.webserver.1.0.admin_endpoint",
- "type": "tosca.capabilities.Endpoint.Admin"
- },
- "feature": {
- "uniqueId": "capability.res_tosca.nodes.root.1.0.feature",
- "type": "tosca.capabilities.Node"
- },
- "data_endpoint": {
- "uniqueId": "capability.res_tosca.nodes.webserver.1.0.data_endpoint",
- "type": "tosca.capabilities.Endpoint"
- }
- },
- "requirements": {
- "dependency": {
- "uniqueId": "res_tosca.nodes.root.1.0.dependency",
- "capability": "tosca.capabilities.Node",
- "node": "tosca.nodes.Root",
- "relationship": "tosca.relationships.DependsOn"
- },
- "host": {
- "uniqueId": "res_tosca.nodes.softwarecomponent.1.0.host",
- "capability": "tosca.capabilities.Container",
- "node": "tosca.nodes.Compute",
- "relationship": "tosca.relationships.HostedOn"
- }
- },
- "vendorName": "sdf",
- "vendorRelease": "sdf",
- "contactId": "jh7654",
- "abstract": false,
- "highestVersion": true
- },
- {
- "uniqueId": "res_ddddd.0.1",
- "resourceName": "ddddd",
- "resourceVersion": "0.1",
- "creatorUserId": "cs0008",
- "creatorFullName": "Carlos Santana",
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "creationDate": 1436353021637,
- "lastUpdateDate": 1436353021637,
- "description": "ddsd",
- "icon": "icon-red2",
- "tags": [
- "ddddd"
- ],
- "category": "Compute as a Service",
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT",
- "derivedFrom": [
- "tosca.nodes.Root"
- ],
- "artifacts": {
- "misdevices": {
- "uniqueId": "res_ddddd.0.1.misdevices",
- "artifactType": "PUPPET",
- "artifactName": "misdevices.docx",
- "userIdLastUpdater": "cs0008",
- "creatorFullName": "Carlos Santana",
- "updaterFullName": "Carlos Santana",
- "creationDate": 1436353036161,
- "lastUpdateDate": 1436353036161,
- "esId": "res_ddddd.0.1:misdevices.docx",
- "logicalName": "misdevices",
- "description": "eeeeee"
- }
- },
- "interfaces": {
-
- },
- "capabilities": {
- "feature": {
- "uniqueId": "capability.res_tosca.nodes.root.1.0.feature",
- "type": "tosca.capabilities.Node"
- }
- },
- "requirements": {
- "dependency": {
- "uniqueId": "res_tosca.nodes.root.1.0.dependency",
- "capability": "tosca.capabilities.Node",
- "node": "tosca.nodes.Root",
- "relationship": "tosca.relationships.DependsOn"
- }
- },
- "vendorName": "dfsd",
- "vendorRelease": "ddddd",
- "contactId": "ss1234",
- "abstract": false,
- "highestVersion": true
- },
- {
- "uniqueId": "res_yo.0.1",
- "resourceName": "yo",
- "resourceVersion": "0.1",
- "creatorUserId": "cs0008",
- "creatorFullName": "Carlos Santana",
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "creationDate": 1436369145382,
- "lastUpdateDate": 1436369145382,
- "description": "dddd",
- "icon": "icon-red2",
- "tags": [
- "yo"
- ],
- "category": "Collaboration",
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT",
- "derivedFrom": [
- "tosca.nodes.WebServer"
- ],
- "artifacts": {
-
- },
- "interfaces": {
-
- },
- "capabilities": {
- "host": {
- "uniqueId": "capability.res_tosca.nodes.webserver.1.0.host",
- "type": "tosca.capabilities.Container",
- "validSourceTypes": [
- "tosca.nodes.WebApplication"
- ]
- },
- "admin_endpoint": {
- "uniqueId": "capability.res_tosca.nodes.webserver.1.0.admin_endpoint",
- "type": "tosca.capabilities.Endpoint.Admin"
- },
- "feature": {
- "uniqueId": "capability.res_tosca.nodes.root.1.0.feature",
- "type": "tosca.capabilities.Node"
- },
- "data_endpoint": {
- "uniqueId": "capability.res_tosca.nodes.webserver.1.0.data_endpoint",
- "type": "tosca.capabilities.Endpoint"
- }
- },
- "requirements": {
- "dependency": {
- "uniqueId": "res_tosca.nodes.root.1.0.dependency",
- "capability": "tosca.capabilities.Node",
- "node": "tosca.nodes.Root",
- "relationship": "tosca.relationships.DependsOn"
- },
- "host": {
- "uniqueId": "res_tosca.nodes.softwarecomponent.1.0.host",
- "capability": "tosca.capabilities.Container",
- "node": "tosca.nodes.Compute",
- "relationship": "tosca.relationships.HostedOn"
- }
- },
- "vendorName": "dds",
- "vendorRelease": "ssss",
- "contactId": "ss1234",
- "abstract": false,
- "highestVersion": true
- },
- {
- "uniqueId": "res_martin2213.0.1",
- "resourceName": "martin2213",
- "resourceVersion": "0.1",
- "creatorUserId": "cs0008",
- "creatorFullName": "Carlos Santana",
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "creationDate": 1436369231581,
- "lastUpdateDate": 1436369231581,
- "description": "desc",
- "icon": "icon-red2",
- "tags": [
- "martin2213",
- "martin2213tag"
- ],
- "category": "Messaging",
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT",
- "derivedFrom": [
- "tosca.nodes.DBMS"
- ],
- "artifacts": {
-
- },
- "interfaces": {
-
- },
- "capabilities": {
- "host": {
- "uniqueId": "capability.res_tosca.nodes.dbms.1.0.host",
- "type": "tosca.capabilities.Container",
- "validSourceTypes": [
- "tosca.nodes.Database"
- ]
- },
- "feature": {
- "uniqueId": "capability.res_tosca.nodes.root.1.0.feature",
- "type": "tosca.capabilities.Node"
- }
- },
- "requirements": {
- "dependency": {
- "uniqueId": "res_tosca.nodes.root.1.0.dependency",
- "capability": "tosca.capabilities.Node",
- "node": "tosca.nodes.Root",
- "relationship": "tosca.relationships.DependsOn"
- },
- "host": {
- "uniqueId": "res_tosca.nodes.softwarecomponent.1.0.host",
- "capability": "tosca.capabilities.Container",
- "node": "tosca.nodes.Compute",
- "relationship": "tosca.relationships.HostedOn"
- }
- },
- "vendorName": "Oracle",
- "vendorRelease": "1.2.5",
- "contactId": "Al1234",
- "abstract": false,
- "highestVersion": true
- }
- ],
- "services": [
- {
- "componentMetadataDefinition": {
- "uniqueId": "svc_wduma.0.1",
- "name": "wduma",
- "version": "0.1",
- "creationDate": 1436081587500,
- "lastUpdateDate": 1436081587500,
- "description": "BLa BLa",
- "state": "NOT_CERTIFIED_CHECKOUT",
- "tags": [
- "wduma",
- "wdumatag"
- ],
- "icon": "network_l_4",
- "highestVersion": true
- },
- "artifacts": {
-
- },
- "category": "Databases",
- "creatorUserId": "cs0008",
- "creatorFullName": "Carlos Santana",
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "serviceName": "wduma",
- "creationDate": 1436081587500,
- "icon": "network_l_4",
- "version": "0.1",
- "description": "BLa BLa",
- "tags": [
- "wduma",
- "wdumatag"
- ],
- "uniqueId": "svc_wduma.0.1",
- "lastUpdateDate": 1436081587500,
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT"
- },
- {
- "componentMetadataDefinition": {
- "uniqueId": "svc_r.0.1",
- "name": "r",
- "version": "0.1",
- "creationDate": 1436083434172,
- "lastUpdateDate": 1436083434172,
- "description": "r",
- "state": "NOT_CERTIFIED_CHECKOUT",
- "tags": [
- "rrrr"
- ],
- "icon": "network_l_4",
- "highestVersion": true
- },
- "artifacts": {
-
- },
- "category": "IoT",
- "creatorUserId": "cs0008",
- "creatorFullName": "Carlos Santana",
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "serviceName": "r",
- "creationDate": 1436083434172,
- "icon": "network_l_4",
- "version": "0.1",
- "description": "r",
- "tags": [
- "rrrr"
- ],
- "uniqueId": "svc_r.0.1",
- "lastUpdateDate": 1436083434172,
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT"
- },
- {
- "componentMetadataDefinition": {
- "uniqueId": "svc_otdiz.0.1",
- "name": "otdiz",
- "version": "0.1",
- "creationDate": 1436094819610,
- "lastUpdateDate": 1436094819610,
- "description": "BLa BLa",
- "state": "NOT_CERTIFIED_CHECKOUT",
- "tags": [
- "otdiz",
- "otdiztag"
- ],
- "icon": "network_l_4",
- "highestVersion": true
- },
- "artifacts": {
-
- },
- "category": "Platform as a Service",
- "creatorUserId": "cs0008",
- "creatorFullName": "Carlos Santana",
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "serviceName": "otdiz",
- "creationDate": 1436094819610,
- "icon": "network_l_4",
- "version": "0.1",
- "description": "BLa BLa",
- "tags": [
- "otdiz",
- "otdiztag"
- ],
- "uniqueId": "svc_otdiz.0.1",
- "lastUpdateDate": 1436094819610,
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT"
- },
- {
- "componentMetadataDefinition": {
- "uniqueId": "svc_gxkvl.0.1",
- "name": "gxkvl",
- "version": "0.1",
- "creationDate": 1436094992972,
- "lastUpdateDate": 1436094992972,
- "description": "BLa BLa",
- "state": "NOT_CERTIFIED_CHECKOUT",
- "tags": [
- "gxkvl",
- "gxkvltag"
- ],
- "icon": "network_l_4",
- "highestVersion": true
- },
- "artifacts": {
-
- },
- "category": "Security",
- "creatorUserId": "cs0008",
- "creatorFullName": "Carlos Santana",
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "serviceName": "gxkvl",
- "creationDate": 1436094992972,
- "icon": "network_l_4",
- "version": "0.1",
- "description": "BLa BLa",
- "tags": [
- "gxkvl",
- "gxkvltag"
- ],
- "uniqueId": "svc_gxkvl.0.1",
- "lastUpdateDate": 1436094992972,
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT"
- },
- {
- "componentMetadataDefinition": {
- "uniqueId": "svc_testservice.0.1",
- "name": "testService",
- "version": "0.1",
- "creationDate": 1436098158942,
- "lastUpdateDate": 1436098158942,
- "description": "description",
- "state": "NOT_CERTIFIED_CHECKOUT",
- "tags": [
- "tag1"
- ],
- "icon": "myICON.jpg",
- "highestVersion": true
- },
- "artifacts": {
- "install_apache": {
- "uniqueId": "svc_testservice.0.1.install_apache",
- "artifactType": "SHELL",
- "artifactName": "install_apache.sh",
- "userIdLastUpdater": "cs0008",
- "creatorFullName": "Carlos Santana",
- "updaterFullName": "Carlos Santana",
- "creationDate": 1436098195328,
- "lastUpdateDate": 1436098195328,
- "esId": "svc_testservice.0.1:install_apache.sh",
- "logicalName": "install_apache"
- }
- },
- "category": "Databases",
- "creatorUserId": "cs0008",
- "creatorFullName": "Carlos Santana",
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "serviceName": "testService",
- "creationDate": 1436098158942,
- "icon": "myICON.jpg",
- "version": "0.1",
- "description": "description",
- "tags": [
- "tag1"
- ],
- "uniqueId": "svc_testservice.0.1",
- "lastUpdateDate": 1436098158942,
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT"
- },
- {
- "componentMetadataDefinition": {
- "uniqueId": "svc_newtestservice5.0.1",
- "name": "newTestService5",
- "version": "0.1",
- "creationDate": 1436111412660,
- "lastUpdateDate": 1436111412660,
- "description": "service Description",
- "state": "NOT_CERTIFIED_CHECKOUT",
- "tags": [
- "newTestService5",
- "serviceTag"
- ],
- "icon": "network_l_4",
- "highestVersion": true
- },
- "artifacts": {
-
- },
- "category": "Big Data",
- "creatorUserId": "cs0008",
- "creatorFullName": "Carlos Santana",
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "serviceName": "newTestService5",
- "creationDate": 1436111412660,
- "icon": "network_l_4",
- "version": "0.1",
- "description": "service Description",
- "tags": [
- "newTestService5",
- "serviceTag"
- ],
- "uniqueId": "svc_newtestservice5.0.1",
- "lastUpdateDate": 1436111412660,
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT"
- },
- {
- "componentMetadataDefinition": {
- "uniqueId": "svc_newtestservice.0.1",
- "name": "newTestService",
- "version": "0.1",
- "creationDate": 1436114463660,
- "lastUpdateDate": 1436114463660,
- "description": "service Description",
- "state": "NOT_CERTIFIED_CHECKOUT",
- "tags": [
- "serviceTag"
- ],
- "icon": "myIcon.jpg",
- "vendorName": "Oracle",
- "vendorRelease": "0.1",
- "contactId": "al1976",
- "highestVersion": true
- },
- "artifacts": {
-
- },
- "category": "Big Data",
- "creatorUserId": "cs0008",
- "creatorFullName": "Carlos Santana",
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "serviceName": "newTestService",
- "creationDate": 1436114463660,
- "icon": "myIcon.jpg",
- "version": "0.1",
- "description": "service Description",
- "tags": [
- "serviceTag"
- ],
- "uniqueId": "svc_newtestservice.0.1",
- "lastUpdateDate": 1436114463660,
- "contactId": "al1976",
- "vendorName": "Oracle",
- "vendorRelease": "0.1",
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT"
- },
- {
- "componentMetadataDefinition": {
- "uniqueId": "svc_éø⦹.0.1",
- "name": "éø¦¹",
- "version": "0.1",
- "creationDate": 1436168481712,
- "lastUpdateDate": 1436168481712,
- "description": "service Description",
- "state": "NOT_CERTIFIED_CHECKOUT",
- "tags": [
- "éø¦¹",
- "éø¦¹serviceTag"
- ],
- "icon": "network_l_4",
- "highestVersion": true
- },
- "artifacts": {
-
- },
- "category": "Big Data",
- "creatorUserId": "cs0008",
- "creatorFullName": "Carlos Santana",
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "serviceName": "éø¦¹",
- "creationDate": 1436168481712,
- "icon": "network_l_4",
- "version": "0.1",
- "description": "service Description",
- "tags": [
- "éø¦¹",
- "éø¦¹serviceTag"
- ],
- "uniqueId": "svc_éø⦹.0.1",
- "lastUpdateDate": 1436168481712,
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT"
- },
- {
- "componentMetadataDefinition": {
- "uniqueId": "svc_mmmm.0.1",
- "name": "mmmm",
- "version": "0.1",
- "creationDate": 1436175721980,
- "lastUpdateDate": 1436175721980,
- "description": "jjjj",
- "state": "NOT_CERTIFIED_CHECKOUT",
- "tags": [
- "mmmm"
- ],
- "icon": "network_l_4",
- "highestVersion": true
- },
- "artifacts": {
- "Subtitle": {
- "uniqueId": "svc_mmmm.0.1.Subtitle",
- "artifactType": "SHELL",
- "artifactName": "Subtitle.png",
- "userIdLastUpdater": "cs0008",
- "creatorFullName": "Carlos Santana",
- "updaterFullName": "Carlos Santana",
- "creationDate": 1436180446882,
- "lastUpdateDate": 1436180446882,
- "esId": "svc_mmmm.0.1:Subtitle.png",
- "logicalName": "Subtitle",
- "description": "dfdssfsd"
- },
- "10 numbers limit reached": {
- "uniqueId": "svc_mmmm.0.1.10 numbers limit reached",
- "artifactType": "SHELL",
- "artifactName": "10 numbers limit reached.png",
- "userIdLastUpdater": "cs0008",
- "creatorFullName": "Carlos Santana",
- "updaterFullName": "Carlos Santana",
- "creationDate": 1436178322094,
- "lastUpdateDate": 1436178322094,
- "esId": "svc_mmmm.0.1:10 numbers limit reached.png",
- "logicalName": "10 numbers limit reached",
- "description": "hdfhdfhddf"
- },
- "Screenshot_2014-09-08-13-07-49": {
- "uniqueId": "svc_mmmm.0.1.Screenshot_2014-09-08-13-07-49",
- "artifactType": "SHELL",
- "artifactName": "Screenshot_2014-09-08-13-07-49.png",
- "userIdLastUpdater": "cs0008",
- "creatorFullName": "Carlos Santana",
- "updaterFullName": "Carlos Santana",
- "creationDate": 1436180394486,
- "lastUpdateDate": 1436180394486,
- "esId": "svc_mmmm.0.1:Screenshot_2014-09-08-13-07-49.png",
- "logicalName": "Screenshot_2014-09-08-13-07-49",
- "description": "fdgfdgfdg"
- },
- "Slow upload ": {
- "uniqueId": "svc_mmmm.0.1.Slow upload ",
- "artifactType": "SHELL",
- "artifactName": "Slow upload .png",
- "userIdLastUpdater": "cs0008",
- "creatorFullName": "Carlos Santana",
- "updaterFullName": "Carlos Santana",
- "creationDate": 1436180490467,
- "lastUpdateDate": 1436180490467,
- "esId": "svc_mmmm.0.1:Slow upload .png",
- "logicalName": "Slow upload ",
- "description": "sdffdsfds"
- },
- "img009": {
- "uniqueId": "svc_mmmm.0.1.img009",
- "artifactType": "PUPPET",
- "artifactName": "img009.jpg",
- "userIdLastUpdater": "cs0008",
- "creatorFullName": "Carlos Santana",
- "updaterFullName": "Carlos Santana",
- "creationDate": 1436178135843,
- "lastUpdateDate": 1436178135843,
- "esId": "svc_mmmm.0.1:img009.jpg",
- "logicalName": "img009",
- "description": "hhhhh"
- },
- "casa1": {
- "uniqueId": "svc_mmmm.0.1.casa1",
- "artifactType": "HEAT",
- "artifactName": "casa1.JPG",
- "userIdLastUpdater": "cs0008",
- "creatorFullName": "Carlos Santana",
- "updaterFullName": "Carlos Santana",
- "creationDate": 1436180424159,
- "lastUpdateDate": 1436180424159,
- "esId": "svc_mmmm.0.1:casa1.JPG",
- "logicalName": "casa1",
- "description": "fgsdfsdsdf"
- }
- },
- "category": "Call Control",
- "creatorUserId": "cs0008",
- "creatorFullName": "Carlos Santana",
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "serviceName": "mmmm",
- "creationDate": 1436175721980,
- "icon": "network_l_4",
- "version": "0.1",
- "description": "jjjj",
- "tags": [
- "mmmm"
- ],
- "uniqueId": "svc_mmmm.0.1",
- "lastUpdateDate": 1436175721980,
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT"
- },
- {
- "componentMetadataDefinition": {
- "uniqueId": "svc_fgfdgdfg.0.1",
- "name": "fgfdgdfg",
- "version": "0.1",
- "creationDate": 1436189750913,
- "lastUpdateDate": 1436189750913,
- "description": "fgdfgdf",
- "state": "NOT_CERTIFIED_CHECKOUT",
- "tags": [
- "fgfdgdfg"
- ],
- "icon": "network_l_4",
- "highestVersion": true
- },
- "artifacts": {
-
- },
- "category": "Databases",
- "creatorUserId": "cs0008",
- "creatorFullName": "Carlos Santana",
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "serviceName": "fgfdgdfg",
- "creationDate": 1436189750913,
- "icon": "network_l_4",
- "version": "0.1",
- "description": "fgdfgdf",
- "tags": [
- "fgfdgdfg"
- ],
- "uniqueId": "svc_fgfdgdfg.0.1",
- "lastUpdateDate": 1436189750913,
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT"
- },
- {
- "componentMetadataDefinition": {
- "uniqueId": "svc_jujuy.0.1",
- "name": "jujuy",
- "version": "0.1",
- "creationDate": 1436190515151,
- "lastUpdateDate": 1436190515151,
- "description": "gfhdf",
- "state": "NOT_CERTIFIED_CHECKOUT",
- "tags": [
- "jujuyggg"
- ],
- "icon": "network_l_1-3",
- "highestVersion": true
- },
- "artifacts": {
- "ServicePanel": {
- "uniqueId": "svc_jujuy.0.1.ServicePanel",
- "artifactType": "SHELL",
- "artifactName": "ServicePanel.JPG",
- "userIdLastUpdater": "cs0008",
- "creatorFullName": "Carlos Santana",
- "updaterFullName": "Carlos Santana",
- "creationDate": 1436191109314,
- "lastUpdateDate": 1436191109314,
- "esId": "svc_jujuy.0.1:ServicePanel.JPG",
- "logicalName": "ServicePanel",
- "description": "ddddddddddddddddddd"
- },
- "IconEnd": {
- "uniqueId": "svc_jujuy.0.1.IconEnd",
- "artifactType": "PUPPET",
- "artifactName": "IconEnd.JPG",
- "userIdLastUpdater": "cs0008",
- "creatorFullName": "Carlos Santana",
- "updaterFullName": "Carlos Santana",
- "creationDate": 1436190528852,
- "lastUpdateDate": 1436190528852,
- "esId": "svc_jujuy.0.1:IconEnd.JPG",
- "logicalName": "IconEnd",
- "description": "fffffff"
- },
- "IconCenter": {
- "uniqueId": "svc_jujuy.0.1.IconCenter",
- "artifactType": "SHELL",
- "artifactName": "IconCenter.JPG",
- "userIdLastUpdater": "cs0008",
- "creatorFullName": "Carlos Santana",
- "updaterFullName": "Carlos Santana",
- "creationDate": 1436190584441,
- "lastUpdateDate": 1436190584441,
- "esId": "svc_jujuy.0.1:IconCenter.JPG",
- "logicalName": "IconCenter",
- "description": "fffff"
- },
- "udateresource": {
- "uniqueId": "svc_jujuy.0.1.udateresource",
- "artifactType": "YANG",
- "artifactName": "udateresource.JPG",
- "userIdLastUpdater": "cs0008",
- "creatorFullName": "Carlos Santana",
- "updaterFullName": "Carlos Santana",
- "creationDate": 1436191131313,
- "lastUpdateDate": 1436191131313,
- "esId": "svc_jujuy.0.1:udateresource.JPG",
- "logicalName": "udateresource",
- "description": "dddd"
- },
- "toobolar": {
- "uniqueId": "svc_jujuy.0.1.toobolar",
- "artifactType": "SHELL",
- "artifactName": "toobolar.JPG",
- "userIdLastUpdater": "cs0008",
- "creatorFullName": "Carlos Santana",
- "updaterFullName": "Carlos Santana",
- "creationDate": 1436191146471,
- "lastUpdateDate": 1436191146471,
- "esId": "svc_jujuy.0.1:toobolar.JPG",
- "logicalName": "toobolar",
- "description": "sssssssssssssss"
- }
- },
- "category": "Collaboration",
- "creatorUserId": "cs0008",
- "creatorFullName": "Carlos Santana",
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "serviceName": "jujuy",
- "creationDate": 1436190515151,
- "icon": "network_l_1-3",
- "version": "0.1",
- "description": "gfhdf",
- "tags": [
- "jujuyggg"
- ],
- "uniqueId": "svc_jujuy.0.1",
- "lastUpdateDate": 1436190515151,
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT"
- },
- {
- "componentMetadataDefinition": {
- "uniqueId": "svc_martin39.0.1",
- "name": "martin39",
- "version": "0.1",
- "creationDate": 1436252371041,
- "lastUpdateDate": 1436252371041,
- "description": "fffffff",
- "state": "NOT_CERTIFIED_CHECKOUT",
- "tags": [
- "martin39"
- ],
- "icon": "network_l_4",
- "highestVersion": true
- },
- "artifacts": {
- "toobolar": {
- "uniqueId": "svc_martin39.0.1.toobolar",
- "artifactType": "SHELL",
- "artifactName": "toobolar.JPG",
- "userIdLastUpdater": "cs0008",
- "creatorFullName": "Carlos Santana",
- "updaterFullName": "Carlos Santana",
- "creationDate": 1436252434415,
- "lastUpdateDate": 1436252434415,
- "esId": "svc_martin39.0.1:toobolar.JPG",
- "logicalName": "toobolar",
- "description": "ffff"
- }
- },
- "category": "Compute as a Service",
- "creatorUserId": "cs0008",
- "creatorFullName": "Carlos Santana",
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "serviceName": "martin39",
- "creationDate": 1436252371041,
- "icon": "network_l_4",
- "version": "0.1",
- "description": "fffffff",
- "tags": [
- "martin39"
- ],
- "uniqueId": "svc_martin39.0.1",
- "lastUpdateDate": 1436252371041,
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT"
- },
- {
- "componentMetadataDefinition": {
- "uniqueId": "svc_asdasd.0.1",
- "name": "asdasd",
- "version": "0.1",
- "creationDate": 1436253177668,
- "lastUpdateDate": 1436253177668,
- "description": "asdasd",
- "state": "NOT_CERTIFIED_CHECKOUT",
- "tags": [
- "asdasd"
- ],
- "icon": "network_l_4",
- "highestVersion": true
- },
- "artifacts": {
-
- },
- "category": "Collaboration",
- "creatorUserId": "cs0008",
- "creatorFullName": "Carlos Santana",
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "serviceName": "asdasd",
- "creationDate": 1436253177668,
- "icon": "network_l_4",
- "version": "0.1",
- "description": "asdasd",
- "tags": [
- "asdasd"
- ],
- "uniqueId": "svc_asdasd.0.1",
- "lastUpdateDate": 1436253177668,
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT"
- },
- {
- "componentMetadataDefinition": {
- "uniqueId": "svc_fgdfgfd.0.1",
- "name": "fgdfgfd",
- "version": "0.1",
- "creationDate": 1436255258481,
- "lastUpdateDate": 1436255258481,
- "description": "dfgdfg",
- "state": "NOT_CERTIFIED_CHECKOUT",
- "tags": [
- "fgdfgfd"
- ],
- "icon": "network_l_4",
- "highestVersion": true
- },
- "artifacts": {
-
- },
- "category": "Compute as a Service",
- "creatorUserId": "cs0008",
- "creatorFullName": "Carlos Santana",
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "serviceName": "fgdfgfd",
- "creationDate": 1436255258481,
- "icon": "network_l_4",
- "version": "0.1",
- "description": "dfgdfg",
- "tags": [
- "fgdfgfd"
- ],
- "uniqueId": "svc_fgdfgfd.0.1",
- "lastUpdateDate": 1436255258481,
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT"
- },
- {
- "componentMetadataDefinition": {
- "uniqueId": "svc_fdgd.0.1",
- "name": "fdgd",
- "version": "0.1",
- "creationDate": 1436257427821,
- "lastUpdateDate": 1436257427821,
- "description": "fdg",
- "state": "NOT_CERTIFIED_CHECKOUT",
- "tags": [
- "fdgd"
- ],
- "icon": "call_controll",
- "highestVersion": true
- },
- "artifacts": {
- "toobolar": {
- "uniqueId": "svc_fdgd.0.1.toobolar",
- "artifactType": "SHELL",
- "artifactName": "toobolar.JPG",
- "userIdLastUpdater": "cs0008",
- "creatorFullName": "Carlos Santana",
- "updaterFullName": "Carlos Santana",
- "creationDate": 1436257614747,
- "lastUpdateDate": 1436257614747,
- "esId": "svc_fdgd.0.1:toobolar.JPG",
- "logicalName": "toobolar",
- "description": "dfsdfsd"
- }
- },
- "category": "Compute as a Service",
- "creatorUserId": "cs0008",
- "creatorFullName": "Carlos Santana",
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "serviceName": "fdgd",
- "creationDate": 1436257427821,
- "icon": "call_controll",
- "version": "0.1",
- "description": "fdg",
- "tags": [
- "fdgd"
- ],
- "uniqueId": "svc_fdgd.0.1",
- "lastUpdateDate": 1436257427821,
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT"
- },
- {
- "componentMetadataDefinition": {
- "uniqueId": "svc_fdgdfgfd.0.1",
- "name": "fdgdfgfd",
- "version": "0.1",
- "creationDate": 1436266653797,
- "lastUpdateDate": 1436266653797,
- "description": "fdfdgf",
- "state": "NOT_CERTIFIED_CHECKOUT",
- "tags": [
- "fdgdfgfd"
- ],
- "icon": "network_l_4",
- "highestVersion": true
- },
- "artifacts": {
- "IMG_20141222_072027": {
- "uniqueId": "svc_fdgdfgfd.0.1.IMG_20141222_072027",
- "artifactType": "SHELL",
- "artifactName": "IMG_20141222_072027.jpg",
- "userIdLastUpdater": "cs0008",
- "creatorFullName": "Carlos Santana",
- "updaterFullName": "Carlos Santana",
- "creationDate": 1436267970999,
- "lastUpdateDate": 1436267970999,
- "esId": "svc_fdgdfgfd.0.1:IMG_20141222_072027.jpg",
- "logicalName": "IMG_20141222_072027",
- "description": "FEDF"
- }
- },
- "category": "Call Control",
- "creatorUserId": "cs0008",
- "creatorFullName": "Carlos Santana",
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "serviceName": "fdgdfgfd",
- "creationDate": 1436266653797,
- "icon": "network_l_4",
- "version": "0.1",
- "description": "fdfdgf",
- "tags": [
- "fdgdfgfd"
- ],
- "uniqueId": "svc_fdgdfgfd.0.1",
- "lastUpdateDate": 1436266653797,
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT"
- },
- {
- "componentMetadataDefinition": {
- "uniqueId": "svc_fbgvdfb.0.1",
- "name": "fbgvdfb",
- "version": "0.1",
- "creationDate": 1436267394596,
- "lastUpdateDate": 1436267394596,
- "description": "sdbdbs",
- "state": "NOT_CERTIFIED_CHECKOUT",
- "tags": [
- "fbgvdfb"
- ],
- "icon": "network_l_4",
- "highestVersion": true
- },
- "artifacts": {
- "IMG_20140413_185621": {
- "uniqueId": "svc_fbgvdfb.0.1.IMG_20140413_185621",
- "artifactType": "YANG",
- "artifactName": "IMG_20140413_185621.jpg",
- "userIdLastUpdater": "cs0008",
- "creatorFullName": "Carlos Santana",
- "updaterFullName": "Carlos Santana",
- "creationDate": 1436267701461,
- "lastUpdateDate": 1436267701461,
- "esId": "svc_fbgvdfb.0.1:IMG_20140413_185621.jpg",
- "logicalName": "IMG_20140413_185621",
- "description": "ACSCA"
- },
- "IMG_20140413_185643": {
- "uniqueId": "svc_fbgvdfb.0.1.IMG_20140413_185643",
- "artifactType": "CHEF",
- "artifactName": "IMG_20140413_185643.jpg",
- "userIdLastUpdater": "cs0008",
- "creatorFullName": "Carlos Santana",
- "updaterFullName": "Carlos Santana",
- "creationDate": 1436267871628,
- "lastUpdateDate": 1436267871628,
- "esId": "svc_fbgvdfb.0.1:IMG_20140413_185643.jpg",
- "logicalName": "IMG_20140413_185643",
- "description": "ASDFAWSE"
- }
- },
- "category": "Call Control",
- "creatorUserId": "cs0008",
- "creatorFullName": "Carlos Santana",
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "serviceName": "fbgvdfb",
- "creationDate": 1436267394596,
- "icon": "network_l_4",
- "version": "0.1",
- "description": "sdbdbs",
- "tags": [
- "fbgvdfb"
- ],
- "uniqueId": "svc_fbgvdfb.0.1",
- "lastUpdateDate": 1436267394596,
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT"
- },
- {
- "componentMetadataDefinition": {
- "uniqueId": "svc_asdasds.0.1",
- "name": "asdasds",
- "version": "0.1",
- "creationDate": 1436268972057,
- "lastUpdateDate": 1436268972057,
- "description": "asdasdasd",
- "state": "NOT_CERTIFIED_CHECKOUT",
- "tags": [
- "asdasds"
- ],
- "icon": "network_l_4",
- "highestVersion": true
- },
- "artifacts": {
-
- },
- "category": "Collaboration",
- "creatorUserId": "cs0008",
- "creatorFullName": "Carlos Santana",
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "serviceName": "asdasds",
- "creationDate": 1436268972057,
- "icon": "network_l_4",
- "version": "0.1",
- "description": "asdasdasd",
- "tags": [
- "asdasds"
- ],
- "uniqueId": "svc_asdasds.0.1",
- "lastUpdateDate": 1436268972057,
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT"
- },
- {
- "componentMetadataDefinition": {
- "uniqueId": "svc_kkkkk.0.1",
- "name": "kkkkk",
- "version": "0.1",
- "creationDate": 1436271848416,
- "lastUpdateDate": 1436271848416,
- "description": "hggh",
- "state": "NOT_CERTIFIED_CHECKOUT",
- "tags": [
- "kkkkk"
- ],
- "icon": "network_l_4",
- "highestVersion": true
- },
- "artifacts": {
- "dessaper": {
- "uniqueId": "svc_kkkkk.0.1.dessaper",
- "artifactType": "SHELL",
- "artifactName": "dessaper.JPG",
- "userIdLastUpdater": "cs0008",
- "creatorFullName": "Carlos Santana",
- "updaterFullName": "Carlos Santana",
- "creationDate": 1436271866025,
- "lastUpdateDate": 1436271866025,
- "esId": "svc_kkkkk.0.1:dessaper.JPG",
- "logicalName": "dessaper",
- "description": "fgdf"
- }
- },
- "category": "Call Control",
- "creatorUserId": "cs0008",
- "creatorFullName": "Carlos Santana",
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "serviceName": "kkkkk",
- "creationDate": 1436271848416,
- "icon": "network_l_4",
- "version": "0.1",
- "description": "hggh",
- "tags": [
- "kkkkk"
- ],
- "uniqueId": "svc_kkkkk.0.1",
- "lastUpdateDate": 1436271848416,
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT"
- },
- {
- "componentMetadataDefinition": {
- "uniqueId": "svc_alex.0.1",
- "name": "alex",
- "version": "0.1",
- "creationDate": 1436276482974,
- "lastUpdateDate": 1436276482974,
- "description": "Bla Bla",
- "state": "NOT_CERTIFIED_CHECKOUT",
- "tags": [
- "alex",
- "ddd"
- ],
- "icon": "network_l_4",
- "highestVersion": true
- },
- "artifacts": {
- "pencil": {
- "uniqueId": "svc_alex.0.1.pencil",
- "artifactType": "CHEF",
- "artifactName": "pencil.JPG",
- "userIdLastUpdater": "cs0008",
- "creatorFullName": "Carlos Santana",
- "updaterFullName": "Carlos Santana",
- "creationDate": 1436276810898,
- "lastUpdateDate": 1436276810898,
- "esId": "svc_alex.0.1:pencil.JPG",
- "logicalName": "pencil",
- "description": "nk"
- },
- "Web Accessibility": {
- "uniqueId": "svc_alex.0.1.Web Accessibility",
- "artifactType": "HEAT",
- "artifactName": "Web Accessibility.pptx",
- "userIdLastUpdater": "cs0008",
- "creatorFullName": "Carlos Santana",
- "updaterFullName": "Carlos Santana",
- "creationDate": 1436276689984,
- "lastUpdateDate": 1436276689984,
- "esId": "svc_alex.0.1:Web Accessibility.pptx",
- "logicalName": "Web Accessibility",
- "description": "dfhgf"
- },
- "toobolar": {
- "uniqueId": "svc_alex.0.1.toobolar",
- "artifactType": "CHEF",
- "artifactName": "toobolar.JPG",
- "userIdLastUpdater": "cs0008",
- "creatorFullName": "Carlos Santana",
- "updaterFullName": "Carlos Santana",
- "creationDate": 1436276821186,
- "lastUpdateDate": 1436276821186,
- "esId": "svc_alex.0.1:toobolar.JPG",
- "logicalName": "toobolar",
- "description": "dgrt"
- }
- },
- "category": "IoT",
- "creatorUserId": "cs0008",
- "creatorFullName": "Carlos Santana",
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "serviceName": "alex",
- "creationDate": 1436276482974,
- "icon": "network_l_4",
- "version": "0.1",
- "description": "Bla Bla",
- "tags": [
- "alex",
- "ddd"
- ],
- "uniqueId": "svc_alex.0.1",
- "lastUpdateDate": 1436276482974,
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT"
- },
- {
- "componentMetadataDefinition": {
- "uniqueId": "svc_martin392.0.1",
- "name": "martin392",
- "version": "0.1",
- "creationDate": 1436276986104,
- "lastUpdateDate": 1436276986104,
- "description": "ddddd",
- "state": "NOT_CERTIFIED_CHECKOUT",
- "tags": [
- "martin392"
- ],
- "icon": "network_l_4",
- "highestVersion": true
- },
- "artifacts": {
-
- },
- "category": "Collaboration",
- "creatorUserId": "cs0008",
- "creatorFullName": "Carlos Santana",
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "serviceName": "martin392",
- "creationDate": 1436276986104,
- "icon": "network_l_4",
- "version": "0.1",
- "description": "ddddd",
- "tags": [
- "martin392"
- ],
- "uniqueId": "svc_martin392.0.1",
- "lastUpdateDate": 1436276986104,
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT"
- },
- {
- "componentMetadataDefinition": {
- "uniqueId": "svc_alex1.0.1",
- "name": "Alex1",
- "version": "0.1",
- "creationDate": 1436277034499,
- "lastUpdateDate": 1436277034499,
- "description": "vvg",
- "state": "NOT_CERTIFIED_CHECKOUT",
- "tags": [
- "Alex1"
- ],
- "icon": "network_l_1-3",
- "highestVersion": true
- },
- "artifacts": {
-
- },
- "category": "IoT",
- "creatorUserId": "cs0008",
- "creatorFullName": "Carlos Santana",
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "serviceName": "Alex1",
- "creationDate": 1436277034499,
- "icon": "network_l_1-3",
- "version": "0.1",
- "description": "vvg",
- "tags": [
- "Alex1"
- ],
- "uniqueId": "svc_alex1.0.1",
- "lastUpdateDate": 1436277034499,
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT"
- },
- {
- "componentMetadataDefinition": {
- "uniqueId": "svc_alex2.0.1",
- "name": "Alex2",
- "version": "0.1",
- "creationDate": 1436277071235,
- "lastUpdateDate": 1436277071235,
- "description": "sas",
- "state": "NOT_CERTIFIED_CHECKOUT",
- "tags": [
- "Alex2"
- ],
- "icon": "network_l_4",
- "highestVersion": true
- },
- "artifacts": {
-
- },
- "category": "Big Data",
- "creatorUserId": "cs0008",
- "creatorFullName": "Carlos Santana",
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "serviceName": "Alex2",
- "creationDate": 1436277071235,
- "icon": "network_l_4",
- "version": "0.1",
- "description": "sas",
- "tags": [
- "Alex2"
- ],
- "uniqueId": "svc_alex2.0.1",
- "lastUpdateDate": 1436277071235,
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT"
- },
- {
- "componentMetadataDefinition": {
- "uniqueId": "svc_gfhgfhfg.0.1",
- "name": "gfhgfhfg",
- "version": "0.1",
- "creationDate": 1436337425800,
- "lastUpdateDate": 1436337425800,
- "description": "fghg",
- "state": "NOT_CERTIFIED_CHECKOUT",
- "tags": [
- "gfhgfhgfgfhfg"
- ],
- "icon": "network_l_1-3",
- "highestVersion": true
- },
- "artifacts": {
- "Footer_menu": {
- "uniqueId": "svc_gfhgfhfg.0.1.Footer_menu",
- "artifactType": "SHELL",
- "artifactName": "Footer_menu.JPG",
- "userIdLastUpdater": "cs0008",
- "creatorFullName": "Carlos Santana",
- "updaterFullName": "Carlos Santana",
- "creationDate": 1436337460108,
- "lastUpdateDate": 1436337460108,
- "esId": "svc_gfhgfhfg.0.1:Footer_menu.JPG",
- "logicalName": "Footer_menu",
- "description": "gfhgfh"
- }
- },
- "category": "Call Control",
- "creatorUserId": "cs0008",
- "creatorFullName": "Carlos Santana",
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "serviceName": "gfhgfhfg",
- "creationDate": 1436337425800,
- "icon": "network_l_1-3",
- "version": "0.1",
- "description": "fghg",
- "tags": [
- "gfhgfhgfgfhfg"
- ],
- "uniqueId": "svc_gfhgfhfg.0.1",
- "lastUpdateDate": 1436337425800,
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT"
- },
- {
- "componentMetadataDefinition": {
- "uniqueId": "svc_fffffdd.0.1",
- "name": "fffffdd",
- "version": "0.1",
- "creationDate": 1436342516321,
- "lastUpdateDate": 1436342516321,
- "description": "fdgg",
- "state": "NOT_CERTIFIED_CHECKOUT",
- "tags": [
- "fffffdd"
- ],
- "icon": "network_l_4",
- "highestVersion": true
- },
- "artifacts": {
-
- },
- "category": "Call Control",
- "creatorUserId": "cs0008",
- "creatorFullName": "Carlos Santana",
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "serviceName": "fffffdd",
- "creationDate": 1436342516321,
- "icon": "network_l_4",
- "version": "0.1",
- "description": "fdgg",
- "tags": [
- "fffffdd"
- ],
- "uniqueId": "svc_fffffdd.0.1",
- "lastUpdateDate": 1436342516321,
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT"
- },
- {
- "componentMetadataDefinition": {
- "uniqueId": "svc_martin.0.1",
- "name": "martin",
- "version": "0.1",
- "creationDate": 1436342857036,
- "lastUpdateDate": 1436342857036,
- "description": "gggg",
- "state": "NOT_CERTIFIED_CHECKOUT",
- "tags": [
- "martin"
- ],
- "icon": "network_l_4",
- "highestVersion": true
- },
- "artifacts": {
-
- },
- "category": "Call Control",
- "creatorUserId": "cs0008",
- "creatorFullName": "Carlos Santana",
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "serviceName": "martin",
- "creationDate": 1436342857036,
- "icon": "network_l_4",
- "version": "0.1",
- "description": "gggg",
- "tags": [
- "martin"
- ],
- "uniqueId": "svc_martin.0.1",
- "lastUpdateDate": 1436342857036,
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT"
- },
- {
- "componentMetadataDefinition": {
- "uniqueId": "svc_fghj.0.1",
- "name": "fghj",
- "version": "0.1",
- "creationDate": 1436343201655,
- "lastUpdateDate": 1436343201655,
- "description": "fghjfhj",
- "state": "NOT_CERTIFIED_CHECKOUT",
- "tags": [
- "fghj"
- ],
- "icon": "network_l_4",
- "highestVersion": true
- },
- "artifacts": {
-
- },
- "category": "Big Data",
- "creatorUserId": "cs0008",
- "creatorFullName": "Carlos Santana",
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "serviceName": "fghj",
- "creationDate": 1436343201655,
- "icon": "network_l_4",
- "version": "0.1",
- "description": "fghjfhj",
- "tags": [
- "fghj"
- ],
- "uniqueId": "svc_fghj.0.1",
- "lastUpdateDate": 1436343201655,
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT"
- },
- {
- "componentMetadataDefinition": {
- "uniqueId": "svc_lol.0.1",
- "name": "lol",
- "version": "0.1",
- "creationDate": 1436343380208,
- "lastUpdateDate": 1436343380208,
- "description": "ggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggddddddddddddddddddddddddddddddssssssssssssssssswwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwpopopoddddssssssssssssssssswwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwpopopoddddssssssssssssssssswwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwpopopoddddssssssssssssssssswwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwpopopoddddssssssssssssssssswwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwpopopoddddssssssssssssssssswwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwpopopoddddssssssssssssssssswwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwpopopoddddssssssssssssssssswwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwpopopoddddssssssssssssssssswwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwpopopoddddssssssssssssssssswwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwpopopoddddssssssssssssssssswwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwpopopoddddssssssssss",
- "state": "NOT_CERTIFIED_CHECKOUT",
- "tags": [
- "lol"
- ],
- "icon": "network_l_4",
- "highestVersion": true
- },
- "artifacts": {
- "10 numbers limit reached": {
- "uniqueId": "svc_lol.0.1.10 numbers limit reached",
- "artifactType": "SHELL",
- "artifactName": "10 numbers limit reached.png",
- "userIdLastUpdater": "cs0008",
- "creatorFullName": "Carlos Santana",
- "updaterFullName": "Carlos Santana",
- "creationDate": 1436344950166,
- "lastUpdateDate": 1436344950166,
- "esId": "svc_lol.0.1:10 numbers limit reached.png",
- "logicalName": "10 numbers limit reached",
- "description": "yyyyyyy"
- },
- "Addproperty": {
- "uniqueId": "svc_lol.0.1.Addproperty",
- "artifactType": "PUPPET",
- "artifactName": "Addproperty.JPG",
- "userIdLastUpdater": "cs0008",
- "creatorFullName": "Carlos Santana",
- "updaterFullName": "Carlos Santana",
- "creationDate": 1436344939800,
- "lastUpdateDate": 1436344939800,
- "esId": "svc_lol.0.1:Addproperty.JPG",
- "logicalName": "Addproperty",
- "description": "hhhhhhh"
- },
- "IMG_20140418_142614": {
- "uniqueId": "svc_lol.0.1.IMG_20140418_142614",
- "artifactType": "SHELL",
- "artifactName": "IMG_20140418_142614.jpg",
- "userIdLastUpdater": "cs0008",
- "creatorFullName": "Carlos Santana",
- "updaterFullName": "Carlos Santana",
- "creationDate": 1436344895625,
- "lastUpdateDate": 1436344895625,
- "esId": "svc_lol.0.1:IMG_20140418_142614.jpg",
- "logicalName": "IMG_20140418_142614",
- "description": "bbbbbb"
- },
- "IMG_20140618_195014": {
- "uniqueId": "svc_lol.0.1.IMG_20140618_195014",
- "artifactType": "CHEF",
- "artifactName": "IMG_20140618_195014.jpg",
- "userIdLastUpdater": "cs0008",
- "creatorFullName": "Carlos Santana",
- "updaterFullName": "Carlos Santana",
- "creationDate": 1436344912378,
- "lastUpdateDate": 1436344912378,
- "esId": "svc_lol.0.1:IMG_20140618_195014.jpg",
- "logicalName": "IMG_20140618_195014",
- "description": "bbbbb"
- },
- "IMG_20161213_222041": {
- "uniqueId": "svc_lol.0.1.IMG_20161213_222041",
- "artifactType": "HEAT",
- "artifactName": "IMG_20161213_222041.jpg",
- "userIdLastUpdater": "cs0008",
- "creatorFullName": "Carlos Santana",
- "updaterFullName": "Carlos Santana",
- "creationDate": 1436343693049,
- "lastUpdateDate": 1436343693049,
- "esId": "svc_lol.0.1:IMG_20161213_222041.jpg",
- "logicalName": "IMG_20161213_222041",
- "description": "jjjjjjjjjjjjjjjjjjjjjjjdfjjjjjjjjjjjjjjjjjjjjjjjdfjjjjjjjjjjjjjjjjjjjjjjjdfjjjjjjjjjjjjjjjjjjjjjjjdfjjjjjjjjjjjjjjjjjjjjjjjdfjjjjjjjjjjjjjjjjjjjjjjjdfjjjjjjjjjjjjjjjjjjjjjjjdfjjjjjjjjjjjjjjjjjjjjjjjdfjjjjjjjjjjjjjjjjjjjjjjjdfjjjjjjjjjjjjjjjjjjjjjjjdfjjjjjjjjjjjjjjjjjjjjjjjdfjjjjjjjjjjjjjjjjjjjjjjjdfjjjjjjjjjjjjjjjjjjjjjjjdfjjjjjjjjjjjjjjjjjjjjjjjdfjjjjjjjjjjjjjjjjjjjjjjjdfjjjjjjjjjjjjjjjjjjjjjjjdfjjjjjjjjjjjjjjjjjjjjjjjdfjjjjjjjjjjjjjjjjjjjjjjjdfjjjjjjjjjjjjjjjjjjjjjjjdfjjjjjjjjjjjjjjjjjjjjjjjdfjjjjjjjjjjjjjjjjjjjjjjjdfjjjjjjjjjjjjjjjjjjjjjjjdfjjjjjjjjjjjjjjjjjjjjjjjdfjjjjjjjjjjjjjjjjjjjjjjjdfjjjjjjjjjjjjjjjjjjjjjjjdfjjjjjjjjjjjjjjjjjjjjjjjdfjjjjjjjjjjjjjjjjjjjjjjjdfjjjjjjjjjjjjjjjjjjjjjjjdfjjjjjjjjjjjjjjjjjjjjjjjdfjjjjjjjjjjjjjjjjjjjjjjjdfjjjjjjjjjjjjjjjjjjjjjjjdfjjjjjjjjjjjjjjjjjjjjjjjdfjjjjjjjjjjjjjjjjjjjjjjjdfjjjjjjjjjjjjjjjjjjjjjjjdfjjjjjjjjjjjjjjjjjjjjjjjdfjjjjjjjjjjjjjjjjjjjjjjjdfjjjjjjjjjjjjjjjjjjjjjjjdfjjjjjjjjjjjjjjjjjjjjjjjdfjjjjjjj4444444444444444444444444444444444444444444444444444444444444444444"
- },
- "IMG_20140418_142634": {
- "uniqueId": "svc_lol.0.1.IMG_20140418_142634",
- "artifactType": "PUPPET",
- "artifactName": "IMG_20140418_142634.jpg",
- "userIdLastUpdater": "cs0008",
- "creatorFullName": "Carlos Santana",
- "updaterFullName": "Carlos Santana",
- "creationDate": 1436344878280,
- "lastUpdateDate": 1436344878280,
- "esId": "svc_lol.0.1:IMG_20140418_142634.jpg",
- "logicalName": "IMG_20140418_142634",
- "description": "bbbbbb"
- }
- },
- "category": "Web Servers",
- "creatorUserId": "cs0008",
- "creatorFullName": "Carlos Santana",
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "serviceName": "lol",
- "creationDate": 1436343380208,
- "icon": "network_l_4",
- "version": "0.1",
- "description": "ggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggddddddddddddddddddddddddddddddssssssssssssssssswwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwpopopoddddssssssssssssssssswwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwpopopoddddssssssssssssssssswwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwpopopoddddssssssssssssssssswwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwpopopoddddssssssssssssssssswwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwpopopoddddssssssssssssssssswwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwpopopoddddssssssssssssssssswwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwpopopoddddssssssssssssssssswwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwpopopoddddssssssssssssssssswwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwpopopoddddssssssssssssssssswwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwpopopoddddssssssssssssssssswwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwpopopoddddssssssssss",
- "tags": [
- "lol"
- ],
- "uniqueId": "svc_lol.0.1",
- "lastUpdateDate": 1436343380208,
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT"
- },
- {
- "componentMetadataDefinition": {
- "uniqueId": "svc_clarin.0.1",
- "name": "clarin",
- "version": "0.1",
- "creationDate": 1436346144421,
- "lastUpdateDate": 1436346144421,
- "description": "soy yo",
- "state": "NOT_CERTIFIED_CHECKOUT",
- "tags": [
- "clarin"
- ],
- "icon": "network_l_4",
- "highestVersion": true
- },
- "artifacts": {
-
- },
- "category": "Infrastructure",
- "creatorUserId": "cs0008",
- "creatorFullName": "Carlos Santana",
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "serviceName": "clarin",
- "creationDate": 1436346144421,
- "icon": "network_l_4",
- "version": "0.1",
- "description": "soy yo",
- "tags": [
- "clarin"
- ],
- "uniqueId": "svc_clarin.0.1",
- "lastUpdateDate": 1436346144421,
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT"
- },
- {
- "componentMetadataDefinition": {
- "uniqueId": "svc_jkhkjh.0.1",
- "name": "jkhkjh",
- "version": "0.1",
- "creationDate": 1436356292329,
- "lastUpdateDate": 1436356292329,
- "description": "kjhlk",
- "state": "NOT_CERTIFIED_CHECKOUT",
- "tags": [
- "jkhkjh"
- ],
- "icon": "network_l_4",
- "highestVersion": true
- },
- "artifacts": {
- "Screenshot_1": {
- "uniqueId": "svc_jkhkjh.0.1.Screenshot_1",
- "artifactType": "PUPPET",
- "artifactName": "Screenshot_1.png",
- "userIdLastUpdater": "cs0008",
- "creatorFullName": "Carlos Santana",
- "updaterFullName": "Carlos Santana",
- "creationDate": 1436356484212,
- "lastUpdateDate": 1436356484212,
- "esId": "svc_jkhkjh.0.1:Screenshot_1.png",
- "logicalName": "Screenshot_1",
- "description": "zfvbgsadfgsdhsdghsdhdsghsdhzfvbgsadfgsdhsdghsdhdsghsdhzfvbgsadfgsdhsdghsdhdsghsdhzfvbgsadfgsdhsdghsdhdsghsdhzfvbgsadfgsdhsdghsdhdsghsdhzfvbgsadfgsdhsdghsdhdsghsdhzfvbgsadfgsdhsdghsdhdsghsdhzfvbgsadfgsdhsdghsdhdsghsdhzfvbgsadfgsdhsdghsdhdsghsdhzfvbgsadfgsdhsdghsdhdsghsdhzfvbgsadfgsdhsdghsdhdsghsdhzfvbgsadfgsdhsdghsdhdsghsdhzfvbgsadfgsdhsdghsdhdsghsdhzfvbgsadfgsdhsdghsdhdsghsdh"
- }
- },
- "category": "Call Control",
- "creatorUserId": "cs0008",
- "creatorFullName": "Carlos Santana",
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "resourceInstances": [
- {
- "uniqueId": "svc_jkhkjh.0.1.res_tosca.nodes.compute.1.0.compute_1",
- "name": "compute_1",
- "resourceUid": "res_tosca.nodes.compute.1.0",
- "creationTime": 1436356602608,
- "modificationTime": 1436356602608,
- "description": "Represents a real or virtual machine or server. Information specified on the Compute\r\t node will be used to find the machine that fits the given requirements in the cloud\r\t available machines. If no sizing information are specified the cloud provider default\r\t machine will be used. It is strongly recommended to specify the required CPUs and memory\r\t at least.",
- "posX": "781",
- "posY": "241",
- "icon": "defaulticon"
- },
- {
- "uniqueId": "svc_jkhkjh.0.1.res_tosca.nodes.compute.1.0.compute_2",
- "name": "compute_2",
- "resourceUid": "res_tosca.nodes.compute.1.0",
- "creationTime": 1436356789445,
- "modificationTime": 1436356789445,
- "description": "Represents a real or virtual machine or server. Information specified on the Compute\r\t node will be used to find the machine that fits the given requirements in the cloud\r\t available machines. If no sizing information are specified the cloud provider default\r\t machine will be used. It is strongly recommended to specify the required CPUs and memory\r\t at least.",
- "posX": "695",
- "posY": "204",
- "icon": "defaulticon"
- },
- {
- "uniqueId": "svc_jkhkjh.0.1.res_tosca.nodes.network.network.1.0.network_3",
- "name": "network_3",
- "resourceUid": "res_tosca.nodes.network.network.1.0",
- "creationTime": 1436356792215,
- "modificationTime": 1436356792215,
- "description": "Represents a simple , logical network service.",
- "posX": "706",
- "posY": "381",
- "icon": "defaulticon"
- },
- {
- "uniqueId": "svc_jkhkjh.0.1.res_tosca.nodes.network.port.1.0.port_4",
- "name": "port_4",
- "resourceUid": "res_tosca.nodes.network.port.1.0",
- "creationTime": 1436356793840,
- "modificationTime": 1436356793840,
- "description": "Represents a logical entity that associates between Compute and Network normative types.",
- "posX": "662",
- "posY": "552",
- "icon": "defaulticon"
- }
- ],
- "resourceInstancesRelations": [
-
- ],
- "serviceName": "jkhkjh",
- "creationDate": 1436356292329,
- "icon": "network_l_4",
- "version": "0.1",
- "description": "kjhlk",
- "tags": [
- "jkhkjh"
- ],
- "uniqueId": "svc_jkhkjh.0.1",
- "lastUpdateDate": 1436356292329,
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT"
- },
- {
- "componentMetadataDefinition": {
- "uniqueId": "svc_resrw.0.1",
- "name": "resrw",
- "version": "0.1",
- "creationDate": 1436358721893,
- "lastUpdateDate": 1436358721893,
- "description": "rer",
- "state": "NOT_CERTIFIED_CHECKOUT",
- "tags": [
- "resrwrer",
- "lklkl"
- ],
- "icon": "network_l_1-3",
- "highestVersion": true
- },
- "artifacts": {
-
- },
- "category": "Call Control",
- "creatorUserId": "cs0008",
- "creatorFullName": "Carlos Santana",
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "resourceInstances": [
- {
- "uniqueId": "svc_resrw.0.1.res_tosca.nodes.compute.1.0.compute_1",
- "name": "compute_1",
- "resourceUid": "res_tosca.nodes.compute.1.0",
- "creationTime": 1436358725759,
- "modificationTime": 1436358725759,
- "description": "Represents a real or virtual machine or server. Information specified on the Compute\r\t node will be used to find the machine that fits the given requirements in the cloud\r\t available machines. If no sizing information are specified the cloud provider default\r\t machine will be used. It is strongly recommended to specify the required CPUs and memory\r\t at least.",
- "posX": "221",
- "posY": "251",
- "icon": "defaulticon"
- },
- {
- "uniqueId": "svc_resrw.0.1.res_tosca.nodes.network.network.1.0.network_2",
- "name": "network_2",
- "resourceUid": "res_tosca.nodes.network.network.1.0",
- "creationTime": 1436358727329,
- "modificationTime": 1436358727329,
- "description": "Represents a simple , logical network service.",
- "posX": "626",
- "posY": "340",
- "icon": "defaulticon"
- },
- {
- "uniqueId": "svc_resrw.0.1.res_tosca.nodes.network.port.1.0.port_3",
- "name": "port_3",
- "resourceUid": "res_tosca.nodes.network.port.1.0",
- "creationTime": 1436358729466,
- "modificationTime": 1436358729466,
- "description": "Represents a logical entity that associates between Compute and Network normative types.",
- "posX": "558",
- "posY": "275",
- "icon": "defaulticon"
- }
- ],
- "resourceInstancesRelations": [
-
- ],
- "serviceName": "resrw",
- "creationDate": 1436358721893,
- "icon": "network_l_1-3",
- "version": "0.1",
- "description": "rer",
- "tags": [
- "resrwrer",
- "lklkl"
- ],
- "uniqueId": "svc_resrw.0.1",
- "lastUpdateDate": 1436358721893,
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT"
- },
- {
- "componentMetadataDefinition": {
- "uniqueId": "svc_coco.0.1",
- "name": "coco",
- "version": "0.1",
- "creationDate": 1436362653722,
- "lastUpdateDate": 1436362653722,
- "description": "hhh",
- "state": "NOT_CERTIFIED_CHECKOUT",
- "tags": [
- "coco"
- ],
- "icon": "network_l_4",
- "highestVersion": true
- },
- "artifacts": {
-
- },
- "category": "Call Control",
- "creatorUserId": "cs0008",
- "creatorFullName": "Carlos Santana",
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "serviceName": "coco",
- "creationDate": 1436362653722,
- "icon": "network_l_4",
- "version": "0.1",
- "description": "hhh",
- "tags": [
- "coco"
- ],
- "uniqueId": "svc_coco.0.1",
- "lastUpdateDate": 1436362653722,
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT"
- },
- {
- "componentMetadataDefinition": {
- "uniqueId": "svc_nermartin.0.1",
- "name": "nerMartin",
- "version": "0.1",
- "creationDate": 1436366670488,
- "lastUpdateDate": 1436366670488,
- "description": "gggggggggg",
- "state": "NOT_CERTIFIED_CHECKOUT",
- "tags": [
- "nerMartin"
- ],
- "icon": "network_l_4",
- "highestVersion": true
- },
- "artifacts": {
-
- },
- "category": "IMS",
- "creatorUserId": "cs0008",
- "creatorFullName": "Carlos Santana",
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "serviceName": "nerMartin",
- "creationDate": 1436366670488,
- "icon": "network_l_4",
- "version": "0.1",
- "description": "gggggggggg",
- "tags": [
- "nerMartin"
- ],
- "uniqueId": "svc_nermartin.0.1",
- "lastUpdateDate": 1436366670488,
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT"
- },
- {
- "componentMetadataDefinition": {
- "uniqueId": "svc_susana.0.1",
- "name": "susana",
- "version": "0.1",
- "creationDate": 1436367239625,
- "lastUpdateDate": 1436367239625,
- "description": "fff",
- "state": "NOT_CERTIFIED_CHECKOUT",
- "tags": [
- "susana"
- ],
- "icon": "network_l_4",
- "highestVersion": true
- },
- "artifacts": {
-
- },
- "category": "Call Control",
- "creatorUserId": "cs0008",
- "creatorFullName": "Carlos Santana",
- "lastUpdaterUserId": "cs0008",
- "lastUpdaterFullName": "Carlos Santana",
- "serviceName": "susana",
- "creationDate": 1436367239625,
- "icon": "network_l_4",
- "version": "0.1",
- "description": "fff",
- "tags": [
- "susana"
- ],
- "uniqueId": "svc_susana.0.1",
- "lastUpdateDate": 1436367239625,
- "lifecycleState": "NOT_CERTIFIED_CHECKOUT"
- }
- ]
-}
diff --git a/catalog-ui/server-mock/mock-data/resource/properties.json b/catalog-ui/server-mock/mock-data/resource/properties.json
deleted file mode 100644
index 8ed7e78970..0000000000
--- a/catalog-ui/server-mock/mock-data/resource/properties.json
+++ /dev/null
@@ -1,35 +0,0 @@
-[
- {
- "uniqueId": "uniqueId_1",
- "name": "disk_size",
- "type": "integer",
- "required": false,
- "defaultValue": "10",
- "description": "Size of the local disk, in Gigabytes (GB), available to applications running on the Compute node.",
- "constraints": [
- {
- "inRange": [
- "100"
- ]
- }
- ],
- "isPassword": false
- },
- {
- "uniqueId": "uniqueId_2",
- "name": "num_cpus",
- "type": "integer",
- "required": false,
- "defaultValue": "2",
- "description": "Number of (actual or virtual) CPUs associated with the Compute node.",
- "constraints": [
- {
- "inRange": [
- "1",
- "4"
- ]
- }
- ],
- "isPassword": false
- }
-]
diff --git a/catalog-ui/server-mock/mock-data/resource/resource.json b/catalog-ui/server-mock/mock-data/resource/resource.json
deleted file mode 100644
index bc04f40730..0000000000
--- a/catalog-ui/server-mock/mock-data/resource/resource.json
+++ /dev/null
@@ -1,153 +0,0 @@
-{
- "uniqueId": "my-resource.1.0.0",
- "isAbstract": false,
- "resourceName": "my-resource",
- "resourceVersion": "1.0.0",
- "isHighestVersion": false,
- "vendorName": "vendorName",
- "vendorRelease": "vendorRelease",
- "contactId": "contactId",
- "olderVersions": [
- "bla"
- ],
- "resourceIconSrc": "images/resource-icons/firewall.png",
- "icon":"icon-red2",
- "creatorUserId": "jh0003",
- "creatorFullName": "Jimmy Hendrix",
- "lastUpdaterUserId": "jh000322",
- "lastUpdaterFullName": "JHaval Jimmy Hendrix",
- "creationDate": 1431525184379,
- "lastUpdateDate": 1431525184394,
- "description": "Description bla bla",
- "tags": [
- "some tag",
- "tag2",
- "tag3",
- "tag4"
- ],
- "category": "Infrastructure",
- "lifecycleState": "CERTIFIED",
- "derivedFrom": [
- "template1"
- ],
- "artifacts": {
- "db_content": {
- "uniqueId": "my-resource.1.0.0.db_content",
- "artifactType": "puppet",
- "artifactRef": "http://swift OR CATALOG FE /myfile",
- "artifactName": "some Artifact Name1",
- "artifactRepository": "SWIFT",
- "artifactData": "base 64 dajfvsd fsdfsfs s==",
- "artifactChecksum": "base 64 dsdsd==",
- "userIdCreator": "jh0003",
- "userIdLastUpdater": "jh0003",
- "creatorFullName": "Jimmy Hendrix",
- "updaterFullName": "Jimmy Hendrix",
- "creationDate": 1431525184377,
- "lastUpdateDate": 1431525184377
- },
- "db_content_2": {
- "uniqueId": "my-resource.1.0.0.db_content_2",
- "artifactType": "puppet",
- "artifactRef": "http://swift OR CATALOG FE /myfile",
- "artifactName": "some Artifact Name2",
- "artifactRepository": "SWIFT",
- "artifactData": "base 64 dajfvsd fsdfsfs s==",
- "artifactChecksum": "base 64 dsdsd==",
- "userIdCreator": "jh0003",
- "userIdLastUpdater": "jh0003",
- "creatorFullName": "Jimmy Hendrix",
- "updaterFullName": "Jimmy Hendrix",
- "creationDate": 1431525184377,
- "lastUpdateDate": 1431525184377
- },
- "db_content_3": {
- "uniqueId": "my-resource.1.0.0.db_content_3",
- "artifactType": "puppet",
- "artifactRef": "http://swift OR CATALOG FE /myfile",
- "artifactName": "some Artifact Name3",
- "artifactRepository": "SWIFT",
- "artifactData": "base 64 dajfvsd fsdfsfs s==",
- "artifactChecksum": "base 64 dsdsd==",
- "userIdCreator": "jh0003",
- "userIdLastUpdater": "jh0003",
- "creatorFullName": "Jimmy Hendrix",
- "updaterFullName": "Jimmy Hendrix",
- "creationDate": 1431525184377,
- "lastUpdateDate": 1431525184377
- }
- },
- "properties": {
- "disk_size": {
- "uniqueId": "uniqueId_1",
- "type": "integer",
- "required": false,
- "defaultValue": "10",
- "description": "Size of the local disk, in Gigabytes (GB), available to applications running on the Compute node.",
- "constraints": [
- {
- "inRange": [
- "100"
- ]
- }
- ],
- "isPassword": false
- },
- "num_cpus": {
- "uniqueId": "uniqueId_2",
- "type": "integer",
- "required": false,
- "defaultValue": "2",
- "description": "Number of (actual or virtual) CPUs associated with the Compute node.",
- "constraints": [
- {
- "inRange": [
- "1",
- "4"
- ]
- }
- ],
- "isPassword": false
- }
- },
- "attributes": {
- "tmp": {}
- },
- "interfaces": {
- "tmp": {
- "operations": {}
- }
- },
- "capabilities": {
- "host": {
- "uniqueId": "capability.tosca.nodes.Compute.1.0.host",
- "type": "tosca.capabilities.Container",
- "validSourceTypes": [
- "tosca.nodes.SC"
- ]
- }
- },
- "requirements": {
- "host": {
- "uniqueId": "tosca.nodes.SoftwareComponent.1.0.host",
- "capability": "tosca.capabilities.Container",
- "node": "tosca.nodes.Compute",
- "requirementImpl": {
- "uniqueId": "requirementImpl.my-resource.1.0.host",
- "nodeId": "tosca.nodes.Compute.1.0",
- "requirementProperties": {
- "host": {
- "uniqueId": "capabilityInst.requirementImpl.my-resource.1.0.host.host",
- "properties": {
- "disk_size": "10",
- "num_cpus": "2"
- }
- }
- }
- }
- }
- },
- "defaultCapabilities": [
- "defaultCapabilities"
- ]
-}
diff --git a/catalog-ui/server-mock/mock-data/resources/resourcesAbstract.json b/catalog-ui/server-mock/mock-data/resources/resourcesAbstract.json
deleted file mode 100644
index b678ea9b6b..0000000000
--- a/catalog-ui/server-mock/mock-data/resources/resourcesAbstract.json
+++ /dev/null
@@ -1,284 +0,0 @@
-[
- {
- "uniqueId": "tosca.nodes.root.1.0",
- "resourceName": "tosca.nodes.root",
- "resourceVersion": "1.0",
- "creatorUserId": "jh0003",
- "creatorFullName": "Jimmy Hendrix",
- "lastUpdaterUserId": "jh0003",
- "lastUpdaterFullName": "Jimmy Hendrix",
- "creationDate": 1433412546396,
- "lastUpdateDate": 1433412546396,
- "description": "Represents a generic software component that can be managed and run by a Compute Node Type.",
- "icon": "icon-red1",
- "tags": [
- "Root"
- ],
- "category": "Abstract",
- "lifecycleState": "CERTIFIED",
- "vendorName": "ATT (Tosca)",
- "vendorRelease": "1.0.0.wd03",
- "contactId": "jh0003",
- "abstract": true,
- "highestVersion": false
- },
- {
- "uniqueId": "tosca.nodes.softwarecomponent.1.0",
- "resourceName": "tosca.nodes.softwarecomponent",
- "resourceVersion": "1.0",
- "creatorUserId": "jh0003",
- "creatorFullName": "Jimmy Hendrix",
- "lastUpdaterUserId": "jh0003",
- "lastUpdaterFullName": "Jimmy Hendrix",
- "creationDate": 1433412547841,
- "lastUpdateDate": 1433412547841,
- "description": "Represents a generic software component that can be managed and run by a Compute Node Type.",
- "icon": "icon-red2",
- "tags": [
- "Software Component"
- ],
- "category": "Abstract",
- "lifecycleState": "CERTIFIED",
- "derivedFrom": [
- "tosca.nodes.root"
- ],
- "properties": {
- "component_version": {
- "uniqueId": "tosca.nodes.softwarecomponent.1.0.component_version",
- "type": "version",
- "required": false,
- "definition": true,
- "password": false
- },
- "admin_credential": {
- "uniqueId": "tosca.nodes.softwarecomponent.1.0.admin_credential",
- "type": "tosca.datatypes.Credential",
- "required": false,
- "definition": true,
- "password": false
- }
- },
- "vendorName": "ATT (Tosca)",
- "vendorRelease": "1.0.0.wd03",
- "contactId": "jh0003",
- "abstract": true,
- "highestVersion": false
- },
- {
- "uniqueId": "tosca.nodes.webserver.1.0",
- "resourceName": "tosca.nodes.webserver",
- "resourceVersion": "1.0",
- "creatorUserId": "jh0003",
- "creatorFullName": "Jimmy Hendrix",
- "lastUpdaterUserId": "jh0003",
- "lastUpdaterFullName": "Jimmy Hendrix",
- "creationDate": 1433412548140,
- "lastUpdateDate": 1433412548140,
- "description": "Represents an abstract software component or service that is capable of hosting and providing management operations for one or more Web Application nodes.",
- "icon": "icon-red1",
- "tags": [
- "Web Server"
- ],
- "category": "Abstract",
- "lifecycleState": "CERTIFIED",
- "derivedFrom": [
- "tosca.nodes.softwarecomponent"
- ],
- "vendorName": "ATT (Tosca)",
- "vendorRelease": "1.0.0.wd03",
- "contactId": "jh0003",
- "abstract": true,
- "highestVersion": false
- },
- {
- "uniqueId": "tosca.nodes.webapplication.1.0",
- "resourceName": "tosca.nodes.webapplication",
- "resourceVersion": "1.0",
- "creatorUserId": "jh0003",
- "creatorFullName": "Jimmy Hendrix",
- "lastUpdaterUserId": "jh0003",
- "lastUpdaterFullName": "Jimmy Hendrix",
- "creationDate": 1433412548382,
- "lastUpdateDate": 1433412548382,
- "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.",
- "icon": "icon-red3",
- "tags": [
- "Web Application"
- ],
- "category": "Abstract",
- "lifecycleState": "CERTIFIED",
- "derivedFrom": [
- "tosca.nodes.root"
- ],
- "properties": {
- "context_root": {
- "uniqueId": "tosca.nodes.webapplication.1.0.context_root",
- "type": "string",
- "required": false,
- "definition": true,
- "password": false
- }
- },
- "vendorName": "ATT (Tosca)",
- "vendorRelease": "1.0.0.wd03",
- "contactId": "jh0003",
- "abstract": true,
- "highestVersion": false
- },
- {
- "uniqueId": "tosca.nodes.dbms.1.0",
- "resourceName": "tosca.nodes.dbms",
- "resourceVersion": "1.0",
- "creatorUserId": "jh0003",
- "creatorFullName": "Jimmy Hendrix",
- "lastUpdaterUserId": "jh0003",
- "lastUpdaterFullName": "Jimmy Hendrix",
- "creationDate": 1433412548607,
- "lastUpdateDate": 1433412548607,
- "description": "Represents a typical relational, SQL Database Management System software component or service.",
- "icon": "icon-red4",
- "tags": [
- "DBMS"
- ],
- "category": "Abstract",
- "lifecycleState": "CERTIFIED",
- "derivedFrom": [
- "tosca.nodes.softwarecomponent"
- ],
- "properties": {
- "port": {
- "uniqueId": "tosca.nodes.dbms.1.0.port",
- "type": "integer",
- "required": false,
- "description": "the port the DBMS service will listen to for data and requests",
- "definition": true,
- "password": false
- },
- "root_password": {
- "uniqueId": "tosca.nodes.dbms.1.0.root_password",
- "type": "string",
- "required": false,
- "description": "the optional root password for the DBMS service",
- "definition": true,
- "password": false
- }
- },
- "vendorName": "ATT (Tosca)",
- "vendorRelease": "1.0.0.wd03",
- "contactId": "jh0003",
- "abstract": true,
- "highestVersion": false
- },
- {
- "uniqueId": "tosca.nodes.database.1.0",
- "resourceName": "tosca.nodes.database",
- "resourceVersion": "1.0",
- "creatorUserId": "jh0003",
- "creatorFullName": "Jimmy Hendrix",
- "lastUpdaterUserId": "jh0003",
- "lastUpdaterFullName": "Jimmy Hendrix",
- "creationDate": 1433412548836,
- "lastUpdateDate": 1433412548836,
- "description": "Represents a logical database that can be managed and hosted by a DBMS node.",
- "icon": "icon-red3",
- "tags": [
- "Database"
- ],
- "category": "Abstract",
- "lifecycleState": "CERTIFIED",
- "derivedFrom": [
- "tosca.nodes.root"
- ],
- "properties": {
- "port": {
- "uniqueId": "tosca.nodes.database.1.0.port",
- "type": "integer",
- "required": false,
- "description": "the port the underlying database service will listen to for data",
- "definition": true,
- "password": false
- },
- "name": {
- "uniqueId": "tosca.nodes.database.1.0.name",
- "type": "string",
- "required": false,
- "description": "the logical name of the database",
- "definition": true,
- "password": false
- },
- "user": {
- "uniqueId": "tosca.nodes.database.1.0.user",
- "type": "string",
- "required": false,
- "description": "the optional user account name for DB administration",
- "definition": true,
- "password": false
- },
- "password": {
- "uniqueId": "tosca.nodes.database.1.0.password",
- "type": "string",
- "required": false,
- "description": "the optional password for the DB user account",
- "definition": true,
- "password": false
- }
- },
- "vendorName": "ATT (Tosca)",
- "vendorRelease": "1.0.0.wd03",
- "contactId": "jh0003",
- "abstract": true,
- "highestVersion": false
- },
- {
- "uniqueId": "tosca.nodes.container.runtime.1.0",
- "resourceName": "tosca.nodes.container.runtime",
- "resourceVersion": "1.0",
- "creatorUserId": "jh0003",
- "creatorFullName": "Jimmy Hendrix",
- "lastUpdaterUserId": "jh0003",
- "lastUpdaterFullName": "Jimmy Hendrix",
- "creationDate": 1433412549532,
- "lastUpdateDate": 1433412549532,
- "description": "Represents operating system-level virtualization technology used to run multiple application services on a single Compute host.",
- "icon": "icon-red12",
- "tags": [
- "Container"
- ],
- "category": "Abstract",
- "lifecycleState": "CERTIFIED",
- "derivedFrom": [
- "tosca.nodes.softwarecomponent"
- ],
- "vendorName": "ATT (Tosca)",
- "vendorRelease": "1.0.0.wd03",
- "contactId": "jh0003",
- "abstract": true,
- "highestVersion": false
- },
- {
- "uniqueId": "tosca.nodes.container.application.1.0",
- "resourceName": "tosca.nodes.container.application",
- "resourceVersion": "1.0",
- "creatorUserId": "jh0003",
- "creatorFullName": "Jimmy Hendrix",
- "lastUpdaterUserId": "jh0003",
- "lastUpdaterFullName": "Jimmy Hendrix",
- "creationDate": 1433412549709,
- "lastUpdateDate": 1433412549709,
- "description": "Represents an application that requires Container-level virtualization technology.",
- "icon": "icon-red4",
- "tags": [
- "Container Application"
- ],
- "category": "Abstract",
- "lifecycleState": "CERTIFIED",
- "derivedFrom": [
- "tosca.nodes.root"
- ],
- "vendorName": "ATT (Tosca)",
- "vendorRelease": "1.0.0.wd03",
- "contactId": "jh0003",
- "abstract": true,
- "highestVersion": false
- }
-]
diff --git a/catalog-ui/server-mock/mock-data/resources/resourcesNotAbstract.json b/catalog-ui/server-mock/mock-data/resources/resourcesNotAbstract.json
deleted file mode 100644
index eab325c9cf..0000000000
--- a/catalog-ui/server-mock/mock-data/resources/resourcesNotAbstract.json
+++ /dev/null
@@ -1,510 +0,0 @@
-[
- {
- "uniqueId": "tosca.nodes.compute.1.0",
- "resourceName": "tosca.nodes.compute",
- "resourceVersion": "1.0",
- "creatorUserId": "jh0003",
- "creatorFullName": "Jimmy Hendrix",
- "lastUpdaterUserId": "jh0003",
- "lastUpdaterFullName": "Jimmy Hendrix",
- "creationDate": 1433412547566,
- "lastUpdateDate": 1433412547566,
- "coordinates": {
- "x":150,
- "y":250
- },
- "description": "Represents a real or virtual machine or server. Information specified on the Compute\t node will be used to find the machine that fits the given requirements in the cloud\t available machines. If no sizing information are specified the cloud provider default\t machine will be used. It is strongly recommended to specify the required CPUs and memory\t at least.",
- "icon": "icon-red2",
- "tags": [
- "Compute"
- ],
- "category": "Infrastructure",
- "lifecycleState": "CERTIFIED",
- "derivedFrom": [
- "tosca.nodes.root"
- ],
- "vendorName": "ATT (Tosca)",
- "vendorRelease": "1.0.0.wd03",
- "contactId": "jh0003",
- "abstract": false,
- "highestVersion": false,
- "capabilities": {
- "host": {
- "uniqueId": "capability.tosca.nodes.Compute.1.0.host",
- "type": "tosca.capabilities.Container",
- "validSourceTypes": [
- "tosca.nodes.SC"
- ]
- },
- "db1": {
- "uniqueId": "capability.tosca.nodes.Compute.1.0.host",
- "type": "tosca.capabilities.Container",
- "validSourceTypes": [
- "tosca.nodes.SC"
- ]
- },
- "linux1": {
- "uniqueId": "capability.tosca.nodes.Compute.1.0.host",
- "type": "tosca.capabilities.Container",
- "validSourceTypes": [
- "tosca.nodes.SC"
- ]
- }
- },
- "requirements": {
- "host": {
- "uniqueId": "tosca.nodes.SoftwareComponent.1.0.host",
- "capability": "tosca.capabilities.Container",
- "node": "tosca.nodes.Compute",
- "requirementImpl": {
- "uniqueId": "requirementImpl.my-resource.1.0.host",
- "nodeId": "tosca.nodes.Compute.1.0",
- "requirementProperties": {
- "host": {
- "uniqueId": "capabilityInst.requirementImpl.my-resource.1.0.host.host",
- "properties": {
- "disk_size": "10",
- "num_cpus": "2"
- }
- }
- }
- }
- }
- }
- },
- {
- "uniqueId": "tosca.nodes.objectstorage.1.0",
- "resourceName": "tosca.nodes.objectstorage",
- "resourceVersion": "1.0",
- "creatorUserId": "jh0003",
- "creatorFullName": "Jimmy Hendrix",
- "lastUpdaterUserId": "jh0003",
- "lastUpdaterFullName": "Jimmy Hendrix",
- "creationDate": 1433412549091,
- "lastUpdateDate": 1433412549091,
- "coordinates": {
- "x":150,
- "y":250
- },
- "description": "Represents storage that provides the ability to store data as objects (or BLOBs of data) without consideration for the underlying filesystem or devices.",
- "icon": "icon-red1",
- "tags": [
- "ObjectStorage"
- ],
- "category": "Infrastructure",
- "lifecycleState": "CERTIFIED",
- "derivedFrom": [
- "tosca.nodes.root"
- ],
- "properties": {
- "maxsize": {
- "uniqueId": "tosca.nodes.objectstorage.1.0.maxsize",
- "type": "scalar-unit.size",
- "required": false,
- "constraints": [
- {
-
- }
- ],
- "definition": true,
- "password": false
- },
- "name": {
- "uniqueId": "tosca.nodes.objectstorage.1.0.name",
- "type": "string",
- "required": false,
- "definition": true,
- "password": false
- },
- "size": {
- "uniqueId": "tosca.nodes.objectstorage.1.0.size",
- "type": "scalar-unit.size",
- "required": false,
- "constraints": [
- {
-
- }
- ],
- "definition": true,
- "password": false
- }
- },
- "vendorName": "ATT (Tosca)",
- "vendorRelease": "1.0.0.wd03",
- "contactId": "jh0003",
- "abstract": false,
- "highestVersion": false,
- "capabilities": {
- "host2": {
- "uniqueId": "capability.tosca.nodes.Compute.1.0.host",
- "type": "tosca.capabilities.Container",
- "validSourceTypes": [
- "tosca.nodes.SC"
- ]
- },
- "db": {
- "uniqueId": "capability.tosca.nodes.Compute.1.0.host",
- "type": "tosca.capabilities.Container",
- "validSourceTypes": [
- "tosca.nodes.SC"
- ]
- },
- "linux2": {
- "uniqueId": "capability.tosca.nodes.Compute.1.0.host",
- "type": "tosca.capabilities.Container",
- "validSourceTypes": [
- "tosca.nodes.SC"
- ]
- }
- },
- "requirements": {
- "db": {
- "uniqueId": "tosca.nodes.SoftwareComponent.1.0.host",
- "capability": "tosca.capabilities.Container",
- "node": "tosca.nodes.Compute",
- "requirementImpl": {
- "uniqueId": "requirementImpl.my-resource.1.0.host",
- "nodeId": "tosca.nodes.Compute.1.0",
- "requirementProperties": {
- "host": {
- "uniqueId": "capabilityInst.requirementImpl.my-resource.1.0.host.host",
- "properties": {
- "disk_size": "10",
- "num_cpus": "2"
- }
- }
- }
- }
- }
- }
- },
- {
- "uniqueId": "tosca.nodes.blockstorage.1.0",
- "resourceName": "tosca.nodes.blockstorage",
- "resourceVersion": "1.0",
- "creatorUserId": "jh0003",
- "creatorFullName": "Jimmy Hendrix",
- "lastUpdaterUserId": "jh0003",
- "lastUpdaterFullName": "Jimmy Hendrix",
- "creationDate": 1433412549327,
- "lastUpdateDate": 1433412549327,
- "coordinates": {
- "x":150,
- "y":250
- },
- "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.",
- "icon": "icon-red3",
- "tags": [
- "BlockStorage"
- ],
- "category": "Infrastructure",
- "lifecycleState": "CERTIFIED",
- "derivedFrom": [
- "tosca.nodes.root"
- ],
- "properties": {
- "volume_id": {
- "uniqueId": "tosca.nodes.blockstorage.1.0.volume_id",
- "type": "string",
- "required": false,
- "definition": true,
- "password": false
- },
- "snapshot_id": {
- "uniqueId": "tosca.nodes.blockstorage.1.0.snapshot_id",
- "type": "string",
- "required": false,
- "definition": true,
- "password": false
- },
- "size": {
- "uniqueId": "tosca.nodes.blockstorage.1.0.size",
- "type": "scalar-unit.size",
- "required": false,
- "constraints": [
- {
-
- }
- ],
- "definition": true,
- "password": false
- }
- },
- "vendorName": "ATT (Tosca)",
- "vendorRelease": "1.0.0.wd03",
- "contactId": "jh0003",
- "abstract": false,
- "highestVersion": false,
- "capabilities": {
- "host3": {
- "uniqueId": "capability.tosca.nodes.Compute.1.0.host",
- "type": "tosca.capabilities.Container",
- "validSourceTypes": [
- "tosca.nodes.SC"
- ]
- },
- "db3": {
- "uniqueId": "capability.tosca.nodes.Compute.1.0.host",
- "type": "tosca.capabilities.Container",
- "validSourceTypes": [
- "tosca.nodes.SC"
- ]
- },
- "linux": {
- "uniqueId": "capability.tosca.nodes.Compute.1.0.host",
- "type": "tosca.capabilities.Container",
- "validSourceTypes": [
- "tosca.nodes.SC"
- ]
- }
- },
- "requirements": {
- "linux": {
- "uniqueId": "tosca.nodes.SoftwareComponent.1.0.host",
- "capability": "tosca.capabilities.Container",
- "node": "tosca.nodes.Compute",
- "requirementImpl": {
- "uniqueId": "requirementImpl.my-resource.1.0.host",
- "nodeId": "tosca.nodes.Compute.1.0",
- "requirementProperties": {
- "host": {
- "uniqueId": "capabilityInst.requirementImpl.my-resource.1.0.host.host",
- "properties": {
- "disk_size": "10",
- "num_cpus": "2"
- }
- }
- }
- }
- }
- }
- },
- {
- "uniqueId": "tosca.nodes.loadbalancer.1.0",
- "resourceName": "tosca.nodes.loadbalancer",
- "resourceVersion": "1.0",
- "creatorUserId": "jh0003",
- "creatorFullName": "Jimmy Hendrix",
- "lastUpdaterUserId": "jh0003",
- "lastUpdaterFullName": "Jimmy Hendrix",
- "creationDate": 1433412549878,
- "lastUpdateDate": 1433412549878,
- "coordinates": {
- "x":150,
- "y":250
- },
- "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).",
- "icon": "icon-red4",
- "tags": [
- "Load Balancer"
- ],
- "category": "Infrastructure",
- "lifecycleState": "CERTIFIED",
- "derivedFrom": [
- "tosca.nodes.root"
- ],
- "properties": {
- "algorithm": {
- "uniqueId": "tosca.nodes.loadbalancer.1.0.algorithm",
- "type": "string",
- "required": false,
- "definition": true,
- "password": false
- }
- },
- "vendorName": "ATT (Tosca)",
- "vendorRelease": "1.0.0.wd03",
- "contactId": "jh0003",
- "abstract": false,
- "highestVersion": false,
- "capabilities": {
- "host": {
- "uniqueId": "capability.tosca.nodes.Compute.1.0.host",
- "type": "tosca.capabilities.Container",
- "validSourceTypes": [
- "tosca.nodes.SC"
- ]
- },
- "db4": {
- "uniqueId": "capability.tosca.nodes.Compute.1.0.host",
- "type": "tosca.capabilities.Container",
- "validSourceTypes": [
- "tosca.nodes.SC"
- ]
- },
- "linux4": {
- "uniqueId": "capability.tosca.nodes.Compute.1.0.host",
- "type": "tosca.capabilities.Container",
- "validSourceTypes": [
- "tosca.nodes.SC"
- ]
- }
- },
- "requirements": {
- "linux": {
- "uniqueId": "tosca.nodes.SoftwareComponent.1.0.host",
- "capability": "tosca.capabilities.Container",
- "node": "tosca.nodes.Compute",
- "requirementImpl": {
- "uniqueId": "requirementImpl.my-resource.1.0.host",
- "nodeId": "tosca.nodes.Compute.1.0",
- "requirementProperties": {
- "host": {
- "uniqueId": "capabilityInst.requirementImpl.my-resource.1.0.host.host",
- "properties": {
- "disk_size": "10",
- "num_cpus": "2"
- }
- }
- }
- }
- }
- }
- },
- {
- "uniqueId": "tosca.nodes.titan.1.0",
- "resourceName": "tosca.nodes.titan",
- "resourceVersion": "1.0",
- "creatorUserId": "jh0003",
- "creatorFullName": "Jimmy Hendrix",
- "lastUpdaterUserId": "jh0003",
- "lastUpdaterFullName": "Jimmy Hendrix",
- "creationDate": 1433412550046,
- "lastUpdateDate": 1433412550046,
- "coordinates": {
- "x":150,
- "y":250
- },
- "description": "Titan is a scalable graph database optimized for storing and querying graphs containing hundreds of billions of vertices and edges distributed across a multi-machine cluster. Titan is a transactional database that can support thousands of concurrent users executing complex graph traversals in real time.",
- "icon": "icon-red4",
- "tags": [
- "Titan"
- ],
- "category": "Big Data",
- "lifecycleState": "CERTIFIED",
- "derivedFrom": [
- "tosca.nodes.root"
- ],
- "vendorName": "ATT (Tosca)",
- "vendorRelease": "1.0.0.wd03",
- "contactId": "jh0003",
- "abstract": false,
- "highestVersion": false,
- "capabilities": {
- "host5": {
- "uniqueId": "capability.tosca.nodes.Compute.1.0.host",
- "type": "tosca.capabilities.Container",
- "validSourceTypes": [
- "tosca.nodes.SC"
- ]
- },
- "db": {
- "uniqueId": "capability.tosca.nodes.Compute.1.0.host",
- "type": "tosca.capabilities.Container",
- "validSourceTypes": [
- "tosca.nodes.SC"
- ]
- },
- "linux5": {
- "uniqueId": "capability.tosca.nodes.Compute.1.0.host",
- "type": "tosca.capabilities.Container",
- "validSourceTypes": [
- "tosca.nodes.SC"
- ]
- }
- },
- "requirements": {
- "linux": {
- "uniqueId": "tosca.nodes.SoftwareComponent.1.0.host",
- "capability": "tosca.capabilities.Container",
- "node": "tosca.nodes.Compute",
- "requirementImpl": {
- "uniqueId": "requirementImpl.my-resource.1.0.host",
- "nodeId": "tosca.nodes.Compute.1.0",
- "requirementProperties": {
- "host": {
- "uniqueId": "capabilityInst.requirementImpl.my-resource.1.0.host.host",
- "properties": {
- "disk_size": "10",
- "num_cpus": "2"
- }
- }
- }
- }
- }
- }
- },
- {
- "uniqueId": "tosca.nodes.tas.1.0",
- "resourceName": "tosca.nodes.tas",
- "resourceVersion": "1.0",
- "creatorUserId": "jh0003",
- "creatorFullName": "Jimmy Hendrix",
- "lastUpdaterUserId": "jh0003",
- "lastUpdaterFullName": "Jimmy Hendrix",
- "creationDate": 1433412550197,
- "lastUpdateDate": 1433412550197,
- "coordinates": {
- "x":150,
- "y":250
- },
- "description": "Telephony application server.",
- "icon": "icon-red1",
- "tags": [
- "TAS"
- ],
- "category": "VoIP",
- "lifecycleState": "CERTIFIED",
- "derivedFrom": [
- "tosca.nodes.root"
- ],
- "vendorName": "ATT (Tosca)",
- "vendorRelease": "1.0.0.wd03",
- "contactId": "jh0003",
- "abstract": false,
- "highestVersion": false,
- "capabilities": {
- "host": {
- "uniqueId": "capability.tosca.nodes.Compute.1.0.host",
- "type": "tosca.capabilities.Container",
- "validSourceTypes": [
- "tosca.nodes.SC"
- ]
- },
- "db6": {
- "uniqueId": "capability.tosca.nodes.Compute.1.0.host",
- "type": "tosca.capabilities.Container",
- "validSourceTypes": [
- "tosca.nodes.SC"
- ]
- },
- "linux6": {
- "uniqueId": "capability.tosca.nodes.Compute.1.0.host",
- "type": "tosca.capabilities.Container",
- "validSourceTypes": [
- "tosca.nodes.SC"
- ]
- }
- },
- "requirements": {
- "db": {
- "uniqueId": "tosca.nodes.SoftwareComponent.1.0.host",
- "capability": "tosca.capabilities.Container",
- "node": "tosca.nodes.Compute",
- "requirementImpl": {
- "uniqueId": "requirementImpl.my-resource.1.0.host",
- "nodeId": "tosca.nodes.Compute.1.0",
- "requirementProperties": {
- "host": {
- "uniqueId": "capabilityInst.requirementImpl.my-resource.1.0.host.host",
- "properties": {
- "disk_size": "10",
- "num_cpus": "2"
- }
- }
- }
- }
- }
- }
- }
-]
diff --git a/catalog-ui/server-mock/mock-data/template/template.json b/catalog-ui/server-mock/mock-data/template/template.json
deleted file mode 100644
index 2747491c0e..0000000000
--- a/catalog-ui/server-mock/mock-data/template/template.json
+++ /dev/null
@@ -1,37 +0,0 @@
-[
- {
- "uniqueId": "1",
- "resourceName": "template1",
- "description":"description description description description description "
- },
- {
- "uniqueId": "2",
- "resourceName": "template2",
- "description":"description description description description description "
- },
- {
- "uniqueId": "3",
- "resourceName": "template3",
- "description":"description description description description description "
- },
- {
- "uniqueId": "4",
- "resourceName": "template4",
- "description":"description description description description description "
- },
- {
- "uniqueId": "5",
- "resourceName": "template5",
- "description":"description description description description description "
- },
- {
- "uniqueId": "6",
- "resourceName": "template6",
- "description":"description description description description description "
- },
- {
- "uniqueId": "7",
- "resourceName": "template7",
- "description":"description description description description description "
- }
- ]
diff --git a/catalog-ui/server-mock/mock-data/user/user.json b/catalog-ui/server-mock/mock-data/user/user.json
deleted file mode 100644
index 5e793db6c6..0000000000
--- a/catalog-ui/server-mock/mock-data/user/user.json
+++ /dev/null
@@ -1,7 +0,0 @@
-{
- "firstName": "James",
- "lastName": "Brown",
- "userId": "jb1234u",
- "email": "jb1234u@sdc.com",
- "role": "ADMIN"
-}
diff --git a/catalog-ui/server-mock/mock-server.js b/catalog-ui/server-mock/mock-server.js
deleted file mode 100644
index 6f4c88a62d..0000000000
--- a/catalog-ui/server-mock/mock-server.js
+++ /dev/null
@@ -1,140 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-var express = require('express');
-var mockApis = require('../configurations/mock.json').sdcConfig;
-//var mockUris = require('../configurations/mock.json');
-var cors = require('cors');
-var multer = require('multer')
-var basePathToMockData = './mock-data/';
-var app = express();
-
-var allowedHeaders = 'Content-Type,Authorization,If-Modified-Since,';
-allowedHeaders += mockApis.cookie.userIdSuffix;
-allowedHeaders += ','+mockApis.cookie.userEmail;
-allowedHeaders += ','+mockApis.cookie.userFirstName;
-allowedHeaders += ','+mockApis.cookie.userLastName;
-allowedHeaders += ','+mockApis.cookie.xEcompRequestId;
-
-
-
-app.use(cors({
- // origin: '*',
- origin: function(origin, callback) {
- callback(null, true);
- },
- methods: 'GET, POST, PUT, DELETE',
- allowedHeaders: allowedHeaders,
- credentials: true
-}));
-
-//set cookie middleware
-app.use(function(req, res, next) {
-
- res.cookie(mockApis.cookie.userIdSuffix, req.headers[mockApis.cookie.userIdSuffix] || mockApis.userTypes.designer.userId );
- res.cookie(mockApis.cookie.userEmail, req.headers[mockApis.cookie.userEmail] || mockApis.userTypes.designer.email);
- res.cookie(mockApis.cookie.userFirstName, req.headers[mockApis.cookie.userFirstName] || mockApis.userTypes.designer.firstName);
- res.cookie(mockApis.cookie.userLastName, req.headers[mockApis.cookie.userLastName] || mockApis.userTypes.designer.lastName);
- res.cookie(mockApis.cookie.xEcompRequestId, req.headers[mockApis.cookie.xEcompRequestId] || mockApis.userTypes.designer.lastName);
- next();
-});
-
-var userRoutes = require('./routes/user');
-app.use('/v1/user', userRoutes);
-var resourceRoutes = require('./routes/resource');
-app.use('/v1/resource', resourceRoutes);
-var templateRoutes = require('./routes/template');
-app.use('/v1/template', templateRoutes);
-var propertyRoutes = require('./routes/property');
-app.use('/v1/resource/:resourceId/property', propertyRoutes);
-var resourcesRoutes = require('./routes/resources');
-app.use('/v1/catalog/resources', resourcesRoutes);
-
-/******************************************* MOCKS ENPOINTS *************************************************/
-/* get user details */
-// app.get(mockApis.api.GET_user, function (req, res) {
-// var user = require(basePathToMockData+'user/user.json');
-// res.send(user);
-// });
-
-/* get elements */
-app.get(mockApis.api.GET_element, function (req, res) {
-
- var element = require(basePathToMockData+'element/element.json');
- res.send(element);
-});
-
-/* get elements */
-app.get(mockApis.api.GET_catalog, function (req, res) {
-
- var element = require(basePathToMockData+'element/element.json');
- res.send(element);
-});
-
-/* get categories */
-app.get(mockApis.api.GET_category, function (req, res) {
-
- var categories = require(basePathToMockData+'category/category.json');
- res.send(categories);
-});
-
-
-/* get categories */
-app.get(mockApis.api.GET_configuration_ui, function (req, res) {
-
- var categories = require(basePathToMockData+'artifact/artifact-types.json');
- res.send(categories);
-});
-
-
-
-
-
-
-
-
-//upload artifact file
-app.use(multer({ dest: './uploads/',
- rename: function (fieldname, filename) {
- return filename+Date.now();
- },
- onFileUploadStart: function (file) {
- console.log(file.originalname + ' is starting ...')
- },
- onFileUploadComplete: function (file) {
- console.log(file.fieldname + ' uploaded to ' + file.path)
- done=true;
- }
-}));
-
-var done=false;
-app.post(mockApis.api.GET_resource_artifact,function(req,res){
- if(done==true){
- console.log(req.files);
- res.end("File uploaded.");
- }
-});
-
-
-/**************************************************** *******************************************************/
-
-var server = app.listen(9999, function () {
- console.log('mock server listening on port %d', server.address().port);
-});
diff --git a/catalog-ui/server-mock/routes/property.js b/catalog-ui/server-mock/routes/property.js
deleted file mode 100644
index 2756018035..0000000000
--- a/catalog-ui/server-mock/routes/property.js
+++ /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=========================================================
- */
-
-var express = require('express');
-var properties = require('../mock-data/resource/properties.json');
-
-var router = express.Router();
-
-router.get('/', function (req, res) {
- console.log('query');
- res.send(properties);
-});
-
-router.post('/:id', function (req, res) {
- console.log("post /:id", req);
- res.send(properties[0]);
-});
-
-router.get('/:id', function (req, res) {
- res.send(properties[0]);
-});
-
-
-router.post('/', function (req, res) {
- console.log("post ", req);
- res.send(properties[0]);
-});
-module.exports= router;
diff --git a/catalog-ui/server-mock/routes/resource.js b/catalog-ui/server-mock/routes/resource.js
deleted file mode 100644
index f02b6227e8..0000000000
--- a/catalog-ui/server-mock/routes/resource.js
+++ /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=========================================================
- */
-
-var express = require('express');
-var resource = require('../mock-data/resource/resource.json');
-
-var router = express.Router();
-
-router.get('/', function (req, res) {
- console.log('query');
- res.send([resource]);
-});
-
-router.post('/:id', function (req, res) {
- console.log("post /:id");
- res.send(resource);
-});
-
-router.get('/:id', function (req, res) {
- console.log("post ");
- res.send(resource);
-});
-
-
-router.post('/', function (req, res) {
- console.log("post ");
- res.send(resource);
-});
-
-router.get('/validate-name/:name', function (req, res) {
-
- var name = req.params.name;
- var response = {'isValid':true};
- if (name==='exist'){
- response = {'isValid':false};
- }
- res.send(response);
-
-});
-
-
-
-module.exports= router;
diff --git a/catalog-ui/server-mock/routes/resources.js b/catalog-ui/server-mock/routes/resources.js
deleted file mode 100644
index 589848981c..0000000000
--- a/catalog-ui/server-mock/routes/resources.js
+++ /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=========================================================
- */
-
-var express = require('express');
-var resourcesNotAbstract = require('../mock-data/resources/resourcesNotAbstract.json');
-var resourcesAbstract = require('../mock-data/resources/resourcesAbstract.json');
-
-var router = express.Router();
-
-router.get('/certified/notabstract', function (req, res) {
- res.send(resourcesNotAbstract);
-});
-
-
-router.get('/certified/abstract', function (req, res) {
- res.send(resourcesAbstract);
-});
-
-
-
-module.exports= router;
diff --git a/catalog-ui/server-mock/routes/template.js b/catalog-ui/server-mock/routes/template.js
deleted file mode 100644
index 3b7653967e..0000000000
--- a/catalog-ui/server-mock/routes/template.js
+++ /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=========================================================
- */
-
-var express = require('express');
-var templates = require('../mock-data/template/template.json');
-
-var router = express.Router();
-
-router.get('/', function (req, res) {
- console.log('query');
- res.send(templates);
-});
-
-router.post('/:id', function (req, res) {
- console.log("post /:id", req);
- res.send(templates[0]);
-});
-
-router.get('/:id', function (req, res) {
- res.send(templates[0]);
-});
-
-
-router.post('/', function (req, res) {
- console.log("post ", req);
- res.send(templates[0]);
-});
-module.exports= router;
diff --git a/catalog-ui/server-mock/routes/user.js b/catalog-ui/server-mock/routes/user.js
deleted file mode 100644
index d01f4397e9..0000000000
--- a/catalog-ui/server-mock/routes/user.js
+++ /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=========================================================
- */
-
-var express = require('express');
-var user = require('../mock-data/user/user.json');
-
-var router = express.Router();
-
-router.get('/', function (req, res) {
- console.log('query');
- res.send([user]);
-});
-
-router.post('/:id', function (req, res) {
- console.log("post /:id", req);
- res.send(user);
-});
-
-router.get('/:id', function (req, res) {
- res.send(user);
-});
-
-
-router.post('/', function (req, res) {
- console.log("post ", req);
- res.send(user);
-});
-module.exports= router;
diff --git a/catalog-ui/app/_favicon.png b/catalog-ui/src/app/_favicon.png
index 6e9f04df69..6e9f04df69 100644
--- a/catalog-ui/app/_favicon.png
+++ b/catalog-ui/src/app/_favicon.png
Binary files differ
diff --git a/catalog-ui/src/app/app.ts b/catalog-ui/src/app/app.ts
new file mode 100644
index 0000000000..7f85bb9eb3
--- /dev/null
+++ b/catalog-ui/src/app/app.ts
@@ -0,0 +1,837 @@
+'use strict';
+
+//import 'restangular';
+//import 'angular-ui-router';
+import "reflect-metadata";
+import 'ng-infinite-scroll';
+import './modules/filters.ts';
+import './modules/utils.ts';
+import './modules/directive-module.ts';
+import './modules/service-module';
+import './modules/view-model-module.ts';
+
+import {
+ IUserResourceClass,
+ DataTypesService,
+ LeftPaletteLoaderService,
+ EcompHeaderService,
+ CookieService,
+ ConfigurationUiService,
+ CacheService,
+ IUserResource,
+ SdcVersionService,
+ ICategoryResourceClass,
+ EntityService
+} from "./services";
+import {forwardRef} from '@angular/core';
+import {UpgradeAdapter} from '@angular/upgrade';
+import {CHANGE_COMPONENT_CSAR_VERSION_FLAG, States} from "./utils";
+import {IAppConfigurtaion, IAppMenu, IMainCategory, Resource, IHostedApplication} from "./models";
+import {ComponentFactory} from "./utils/component-factory";
+import {ModalsHandler} from "./utils/modals-handler";
+import {downgradeComponent} from "@angular/upgrade/static";
+
+import {AppModule} from './ng2/app.module';
+import {PropertiesAssignmentComponent} from "./ng2/pages/properties-assignment/properties-assignment.page.component";
+import {Component} from "./models/components/component";
+import {ComponentServiceNg2} from "./ng2/services/component-services/component.service";
+import {ComponentMetadata} from "./models/component-metadata";
+import {Categories} from "./models/categories";
+
+
+let moduleName:string = 'sdcApp';
+let viewModelsModuleName:string = 'Sdc.ViewModels';
+let directivesModuleName:string = 'Sdc.Directives';
+let servicesModuleName:string = 'Sdc.Services';
+let filtersModuleName:string = 'Sdc.Filters';
+let utilsModuleName:string = 'Sdc.Utils';
+
+// Load configuration according to environment.
+declare var __ENV__:string;
+let sdcConfig:IAppConfigurtaion;
+let sdcMenu:IAppMenu;
+let pathPrefix:string = '';
+if (__ENV__ === 'dev') {
+ sdcConfig = require('./../../configurations/dev.js');
+} else if (__ENV__ === 'prod') {
+ sdcConfig = require('./../../configurations/prod.js');
+ pathPrefix = 'sdc1/';
+} else {
+ console.log("ERROR: Environment configuration not found!");
+}
+sdcMenu = require('./../../configurations/menu.js');
+
+let dependentModules:Array<string> = [
+ 'ui.router',
+ 'ui.bootstrap',
+ 'ui.bootstrap.tpls',
+ 'ngDragDrop',
+ 'ui-notification',
+ 'ngResource',
+ 'ngSanitize',
+ 'naif.base64',
+ 'base64',
+ 'uuid4',
+ 'checklist-model',
+ 'angular.filter',
+ 'pascalprecht.translate',
+ '720kb.tooltips',
+ 'restangular',
+ 'angular-clipboard',
+ 'angularResizable',
+ 'infinite-scroll',
+ viewModelsModuleName,
+ directivesModuleName,
+ servicesModuleName,
+ filtersModuleName,
+ utilsModuleName
+];
+
+// ===================== Hosted applications section ====================
+// Define here new hosted apps
+let hostedApplications:Array<IHostedApplication> = [
+ {
+ "moduleName": "dcaeApp",
+ "navTitle": "DCAE",
+ "defaultState": 'dcae.app.home',
+ "state": {
+ "name": "dcae",
+ "url": "/dcae",
+ "relativeHtmlPath": 'dcae-app/dcae-app-view.html',
+ "controllerName": '.DcaeAppViewModel'
+ }
+ }
+];
+
+// Check if module exists (in case the javascript was not loaded).
+let isModuleExists = (moduleName:string):boolean => {
+ try {
+ angular.module(moduleName);
+ dependentModules.push(moduleName);
+ return true;
+ } catch (e) {
+ console.log('Module ' + moduleName + ' does not exists');
+ return false;
+ }
+};
+
+// Check which hosted applications exists
+_.each(hostedApplications, (hostedApp)=> {
+ if (isModuleExists(hostedApp.moduleName)) {
+ hostedApp['exists'] = true;
+ }
+});
+// ===================== Hosted applications section ====================
+
+export const ng1appModule:ng.IModule = angular.module(moduleName, dependentModules);
+angular.module('sdcApp').directive('propertiesAssignment', downgradeComponent({component: PropertiesAssignmentComponent}) as angular.IDirectiveFactory);
+
+ng1appModule.config([
+ '$stateProvider',
+ '$translateProvider',
+ '$urlRouterProvider',
+ '$httpProvider',
+ 'tooltipsConfigProvider',
+ 'NotificationProvider',
+ ($stateProvider:any,
+ $translateProvider:any,
+ $urlRouterProvider:ng.ui.IUrlRouterProvider,
+ $httpProvider:ng.IHttpProvider,
+ tooltipsConfigProvider:any,
+ NotificationProvider:any):void => {
+
+ NotificationProvider.setOptions({
+ delay: 10000,
+ startTop: 10,
+ startRight: 10,
+ closeOnClick: true,
+ verticalSpacing: 20,
+ horizontalSpacing: 20,
+ positionX: 'right',
+ positionY: 'top'
+ });
+
+ $translateProvider.useStaticFilesLoader({
+ prefix: pathPrefix + 'assets/languages/',
+ langKey: '',
+ suffix: '.json?d=' + (new Date()).getTime()
+ });
+ $translateProvider.useSanitizeValueStrategy('escaped');
+ $translateProvider.preferredLanguage('en_US');
+
+ $httpProvider.interceptors.push('Sdc.Services.HeaderInterceptor');
+ $httpProvider.interceptors.push('Sdc.Services.HttpErrorInterceptor');
+ $urlRouterProvider.otherwise('welcome');
+
+ $stateProvider.state(
+ 'dashboard', {
+ url: '/dashboard?show&folder',
+ templateUrl: "./view-models/dashboard/dashboard-view.html",
+ controller: viewModelsModuleName + '.DashboardViewModel',
+ }
+ );
+
+ $stateProvider.state(
+ 'welcome', {
+ url: '/welcome',
+ templateUrl: "./view-models/welcome/welcome-view.html",
+ controller: viewModelsModuleName + '.WelcomeViewModel'
+ }
+ );
+
+ let componentsParam:Array<any> = ['$stateParams', 'Sdc.Services.EntityService', 'Sdc.Services.CacheService', ($stateParams:any, EntityService:EntityService, cacheService:CacheService) => {
+ if (cacheService.get('breadcrumbsComponents')) {
+ return cacheService.get('breadcrumbsComponents');
+ } else {
+ return EntityService.getCatalog();
+ }
+ }];
+
+ $stateProvider.state(
+ 'workspace', {
+ url: '/workspace/:id/:type/',
+ params: {'importedFile': null, 'componentCsar': null, 'resourceType': null, 'disableButtons': null},
+ templateUrl: './view-models/workspace/workspace-view.html',
+ controller: viewModelsModuleName + '.WorkspaceViewModel',
+ resolve: {
+ injectComponent: ['$stateParams', 'ComponentFactory', 'ComponentServiceNg2', function ($stateParams, ComponentFactory:ComponentFactory, ComponentServiceNg2:ComponentServiceNg2) {
+ if ($stateParams.id) {
+ return ComponentFactory.getComponentWithMetadataFromServer($stateParams.type.toUpperCase(), $stateParams.id);
+ } else if ($stateParams.componentCsar && $stateParams.componentCsar.csarUUID) {
+ return $stateParams.componentCsar;
+ } else {
+ let emptyComponent = ComponentFactory.createEmptyComponent($stateParams.type.toUpperCase());
+ if (emptyComponent.isResource() && $stateParams.resourceType) {
+ // Set the resource type
+ (<Resource>emptyComponent).resourceType = $stateParams.resourceType;
+ }
+ if ($stateParams.importedFile) {
+ (<Resource>emptyComponent).importedFile = $stateParams.importedFile;
+ }
+ return emptyComponent;
+ }
+ }],
+ components: componentsParam
+ }
+ }
+ );
+
+ $stateProvider.state(
+ States.WORKSPACE_GENERAL, {
+ url: 'general',
+ parent: 'workspace',
+ controller: viewModelsModuleName + '.GeneralViewModel',
+ templateUrl: './view-models/workspace/tabs/general/general-view.html',
+ data: {unsavedChanges: false, bodyClass: 'general'}
+ }
+ );
+ //
+ $stateProvider.state(
+ States.WORKSPACE_ICONS, {
+ url: 'icons',
+ parent: 'workspace',
+ controller: viewModelsModuleName + '.IconsViewModel',
+ templateUrl: './view-models/workspace/tabs/icons/icons-view.html',
+ data: {unsavedChanges: false, bodyClass: 'icons'}
+
+ }
+ );
+
+ $stateProvider.state(
+ States.WORKSPACE_ACTIVITY_LOG, {
+ url: 'activity_log',
+ parent: 'workspace',
+ controller: viewModelsModuleName + '.ActivityLogViewModel',
+ templateUrl: './view-models/workspace/tabs/activity-log/activity-log.html',
+ data: {unsavedChanges: false}
+ }
+ );
+
+ $stateProvider.state(
+ States.WORKSPACE_DEPLOYMENT_ARTIFACTS, {
+ url: 'deployment_artifacts',
+ parent: 'workspace',
+ controller: viewModelsModuleName + '.DeploymentArtifactsViewModel',
+ templateUrl: './view-models/workspace/tabs/deployment-artifacts/deployment-artifacts-view.html',
+ data: {
+ bodyClass: 'deployment_artifacts'
+ }
+ }
+ );
+
+ $stateProvider.state(
+ States.WORKSPACE_HIERARCHY, {
+ url: 'hierarchy',
+ parent: 'workspace',
+ controller: viewModelsModuleName + '.ProductHierarchyViewModel',
+ templateUrl: './view-models/workspace/tabs/product-hierarchy/product-hierarchy-view.html',
+ data: {unsavedChanges: false}
+
+ }
+ );
+
+ $stateProvider.state(
+ States.WORKSPACE_INFORMATION_ARTIFACTS, {
+ url: 'information_artifacts',
+ parent: 'workspace',
+ controller: viewModelsModuleName + '.InformationArtifactsViewModel',
+ templateUrl: './view-models/workspace/tabs/information-artifacts/information-artifacts-view.html',
+ data: {
+ bodyClass: 'information_artifacts'
+ }
+ }
+ );
+
+ $stateProvider.state(
+ States.WORKSPACE_TOSCA_ARTIFACTS, {
+ url: 'tosca_artifacts',
+ parent: 'workspace',
+ controller: viewModelsModuleName + '.ToscaArtifactsViewModel',
+ templateUrl: './view-models/workspace/tabs/tosca-artifacts/tosca-artifacts-view.html',
+ data: {
+ bodyClass: 'tosca_artifacts'
+ }
+ }
+ );
+
+ $stateProvider.state(
+ States.WORKSPACE_PROPERTIES, {
+ url: 'properties',
+ parent: 'workspace',
+ controller: viewModelsModuleName + '.PropertiesViewModel',
+ templateUrl: './view-models/workspace/tabs/properties/properties-view.html',
+ data: {
+ bodyClass: 'properties'
+ }
+ }
+ );
+
+ $stateProvider.state(
+ States.WORKSPACE_SERVICE_INPUTS, {
+ url: 'service_inputs',
+ parent: 'workspace',
+ controller: viewModelsModuleName + '.ServiceInputsViewModel',
+ templateUrl: './view-models/workspace/tabs/inputs/service-input/service-inputs-view.html',
+ data: {
+ bodyClass: 'workspace-inputs'
+ }
+ }
+ );
+
+ $stateProvider.state(
+ States.WORKSPACE_PROPERTIES_ASSIGNMENT, {
+ url: 'properties_assignment',
+ params: {'component': null},
+ template: '<properties-assignment></properties-assignment>',
+ parent: 'workspace',
+ resolve: {
+ componentData: ['injectComponent', '$stateParams', function (injectComponent:Component, $stateParams) {
+ //injectComponent.componentService = null; // this is for not passing the service so no one will use old api and start using new api
+ $stateParams.component = injectComponent;
+ return injectComponent;
+ }],
+ },
+ data: {
+ bodyClass: 'properties-assignment'
+ }
+ }
+ );
+
+ $stateProvider.state(
+ States.WORKSPACE_RESOURCE_INPUTS, {
+ url: 'resource_inputs',
+ parent: 'workspace',
+ controller: viewModelsModuleName + '.ResourceInputsViewModel',
+ templateUrl: './view-models/workspace/tabs/inputs/resource-input/resource-inputs-view.html',
+ data: {
+ bodyClass: 'workspace-inputs'
+ }
+ }
+ );
+
+ $stateProvider.state(
+ States.WORKSPACE_ATTRIBUTES, {
+ url: 'attributes',
+ parent: 'workspace',
+ controller: viewModelsModuleName + '.AttributesViewModel',
+ templateUrl: './view-models/workspace/tabs/attributes/attributes-view.html',
+ data: {
+ bodyClass: 'attributes'
+ }
+ }
+ );
+
+ $stateProvider.state(
+ States.WORKSPACE_REQUIREMENTS_AND_CAPABILITIES, {
+ url: 'req_and_capabilities',
+ parent: 'workspace',
+ controller: viewModelsModuleName + '.ReqAndCapabilitiesViewModel',
+ templateUrl: './view-models/workspace/tabs/req-and-capabilities/req-and-capabilities-view.html',
+ data: {
+ bodyClass: 'attributes'
+ }
+ }
+ );
+
+
+ $stateProvider.state(
+ States.WORKSPACE_MANAGEMENT_WORKFLOW, {
+ parent: 'workspace',
+ url: 'management_workflow',
+ templateUrl: './view-models/workspace/tabs/management-workflow/management-workflow-view.html',
+ controller: viewModelsModuleName + '.ManagementWorkflowViewModel'
+ }
+ );
+
+ $stateProvider.state(
+ States.WORKSPACE_NETWORK_CALL_FLOW, {
+ parent: 'workspace',
+ url: 'network_call_flow',
+ templateUrl: './view-models/workspace/tabs/network-call-flow/network-call-flow-view.html',
+ controller: viewModelsModuleName + '.NetworkCallFlowViewModel'
+ }
+ );
+
+ $stateProvider.state(
+ States.WORKSPACE_DISTRIBUTION, {
+ parent: 'workspace',
+ url: 'distribution',
+ templateUrl: './view-models/workspace/tabs/distribution/distribution-view.html',
+ controller: viewModelsModuleName + '.DistributionViewModel'
+ }
+ );
+
+ $stateProvider.state(
+ States.WORKSPACE_COMPOSITION, {
+ url: 'composition/',
+ parent: 'workspace',
+ controller: viewModelsModuleName + '.CompositionViewModel',
+ templateUrl: './view-models/workspace/tabs/composition/composition-view.html',
+ data: {
+ bodyClass: 'composition'
+ }
+ }
+ );
+
+ // $stateProvider.state(
+ // States.WORKSPACE_NG2, {
+ // url: 'ng2/',
+ // component: downgradeComponent({component: NG2Example2Component}), //viewModelsModuleName + '.NG2Example',
+ // templateUrl: './ng2/view-ng2/ng2.example2/ng2.example2.component.html'
+ // }
+ // );
+
+ $stateProvider.state(
+ States.WORKSPACE_DEPLOYMENT, {
+ url: 'deployment/',
+ parent: 'workspace',
+ templateUrl: './view-models/workspace/tabs/deployment/deployment-view.html',
+ controller: viewModelsModuleName + '.DeploymentViewModel',
+ data: {
+ bodyClass: 'composition'
+ }
+ }
+ );
+
+ $stateProvider.state(
+ 'workspace.composition.details', {
+ url: 'details',
+ parent: 'workspace.composition',
+ templateUrl: './view-models/workspace/tabs/composition/tabs/details/details-view.html',
+ controller: viewModelsModuleName + '.DetailsViewModel'
+ }
+ );
+
+ $stateProvider.state(
+ 'workspace.composition.properties', {
+ url: 'properties',
+ parent: 'workspace.composition',
+ templateUrl: './view-models/workspace/tabs/composition/tabs/properties-and-attributes/properties-view.html',
+ controller: viewModelsModuleName + '.ResourcePropertiesViewModel'
+ }
+ );
+
+ $stateProvider.state(
+ 'workspace.composition.artifacts', {
+ url: 'artifacts',
+ parent: 'workspace.composition',
+ templateUrl: './view-models/workspace/tabs/composition/tabs/artifacts/artifacts-view.html',
+ controller: viewModelsModuleName + '.ResourceArtifactsViewModel'
+ }
+ );
+
+ $stateProvider.state(
+ 'workspace.composition.relations', {
+ url: 'relations',
+ parent: 'workspace.composition',
+ templateUrl: './view-models/workspace/tabs/composition/tabs/relations/relations-view.html',
+ controller: viewModelsModuleName + '.RelationsViewModel'
+ }
+ );
+
+ $stateProvider.state(
+ 'workspace.composition.structure', {
+ url: 'structure',
+ parent: 'workspace.composition',
+ templateUrl: './view-models/workspace/tabs/composition/tabs/structure/structure-view.html',
+ controller: viewModelsModuleName + '.StructureViewModel'
+ }
+ );
+ $stateProvider.state(
+ 'workspace.composition.lifecycle', {
+ url: 'lifecycle',
+ parent: 'workspace.composition',
+ templateUrl: './view-models/workspace/tabs/composition/tabs/artifacts/artifacts-view.html',
+ controller: viewModelsModuleName + '.ResourceArtifactsViewModel'
+ }
+ );
+
+ $stateProvider.state(
+ 'workspace.composition.api', {
+ url: 'api',
+ parent: 'workspace.composition',
+ templateUrl: './view-models/workspace/tabs/composition/tabs/artifacts/artifacts-view.html',
+ controller: viewModelsModuleName + '.ResourceArtifactsViewModel'
+ }
+ );
+ $stateProvider.state(
+ 'workspace.composition.deployment', {
+ url: 'deployment',
+ parent: 'workspace.composition',
+ templateUrl: './view-models/workspace/tabs/composition/tabs/artifacts/artifacts-view.html',
+ controller: viewModelsModuleName + '.ResourceArtifactsViewModel'
+ }
+ );
+
+ $stateProvider.state(
+ 'adminDashboard', {
+ url: '/adminDashboard',
+ templateUrl: './view-models/admin-dashboard/admin-dashboard-view.html',
+ controller: viewModelsModuleName + '.AdminDashboardViewModel',
+ permissions: ['ADMIN']
+ }
+ );
+
+ $stateProvider.state(
+ 'onboardVendor', {
+ url: '/onboardVendor',
+ templateUrl: './view-models/onboard-vendor/onboard-vendor-view.html',
+ controller: viewModelsModuleName + '.OnboardVendorViewModel'//,
+ }
+ );
+
+ // Build the states for all hosted apps dynamically
+ _.each(hostedApplications, (hostedApp)=> {
+ if (hostedApp.exists) {
+ $stateProvider.state(
+ hostedApp.state.name, {
+ url: hostedApp.state.url,
+ templateUrl: './view-models/dcae-app/dcae-app-view.html',
+ controller: viewModelsModuleName + hostedApp.state.controllerName
+ }
+ );
+ }
+ });
+
+ $stateProvider.state(
+ 'catalog', {
+ url: '/catalog',
+ templateUrl: './view-models/catalog/catalog-view.html',
+ controller: viewModelsModuleName + '.CatalogViewModel',
+ resolve: {
+ auth: ["$q", "Sdc.Services.UserResourceService", ($q:any, userResourceService:IUserResourceClass) => {
+ let userInfo:IUserResource = userResourceService.getLoggedinUser();
+ if (userInfo) {
+ return $q.when(userInfo);
+ } else {
+ return $q.reject({authenticated: false});
+ }
+ }]
+ }
+ }
+ );
+
+ $stateProvider.state(
+ 'support', {
+ url: '/support',
+ templateUrl: './view-models/support/support-view.html',
+ controller: viewModelsModuleName + '.SupportViewModel'
+ }
+ );
+
+ $stateProvider.state(
+ 'error-403', {
+ url: '/error-403',
+ templateUrl: "./view-models/modals/error-modal/error-403-view.html",
+ controller: viewModelsModuleName + '.ErrorViewModel'
+ }
+ );
+
+ tooltipsConfigProvider.options({
+ side: 'bottom',
+ delay: '600',
+ class: 'tooltip-custom',
+ lazy: 0,
+ try: 0
+ });
+
+ }
+]);
+
+ng1appModule.value('ValidationPattern', /^[\s\w\&_.:-]{1,1024}$/);
+ng1appModule.value('ComponentNameValidationPattern', /^(?=.*[^. ])[\s\w\&_.:-]{1,1024}$/); //DE250513 - same as ValidationPattern above, plus requirement that name not consist of dots and/or spaces alone.
+ng1appModule.value('PropertyNameValidationPattern', /^[a-zA-Z0-9_:-]{1,50}$/);// DE210977
+ng1appModule.value('TagValidationPattern', /^[\s\w_.-]{1,50}$/);
+ng1appModule.value('VendorValidationPattern', /^[\x20-\x21\x23-\x29\x2B-\x2E\x30-\x39\x3B\x3D\x40-\x5B\x5D-\x7B\x7D-\xFF]{1,25}$/);
+ng1appModule.value('ContactIdValidationPattern', /^[\s\w-]{1,50}$/);
+ng1appModule.value('UserIdValidationPattern', /^[\s\w-]{1,50}$/);
+ng1appModule.value('ProjectCodeValidationPattern', /^[\s\w-]{5,50}$/);
+ng1appModule.value('LabelValidationPattern', /^[\sa-zA-Z0-9+-]{1,25}$/);
+ng1appModule.value('UrlValidationPattern', /^(https?|ftp):\/\/(((([A-Za-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([A-Za-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([A-Za-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([A-Za-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([A-Za-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([A-Za-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([A-Za-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([A-Za-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([A-Za-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([A-Za-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([A-Za-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([A-Za-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/);
+ng1appModule.value('IntegerValidationPattern', /^(([-+]?\d+)|([-+]?0x[0-9a-fA-F]+))$/);
+ng1appModule.value('IntegerNoLeadingZeroValidationPattern', /^(0|[-+]?[1-9][0-9]*|[-+]?0x[0-9a-fA-F]+|[-+]?0o[0-7]+)$/);
+ng1appModule.value('FloatValidationPattern', /^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?f?$/);
+ng1appModule.value('NumberValidationPattern', /^((([-+]?\d+)|([-+]?0x[0-9a-fA-F]+))|([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?))$/);
+ng1appModule.value('KeyValidationPattern', /^[\s\w-]{1,50}$/);
+ng1appModule.value('CommentValidationPattern', /^[\u0000-\u00BF]*$/);
+ng1appModule.value('BooleanValidationPattern', /^([Tt][Rr][Uu][Ee]|[Ff][Aa][Ll][Ss][Ee])$/);
+ng1appModule.value('MapKeyValidationPattern', /^[\w]{1,50}$/);
+
+ng1appModule.constant('sdcConfig', sdcConfig);
+ng1appModule.constant('sdcMenu', sdcMenu);
+
+ng1appModule.run([
+ '$http',
+ 'Sdc.Services.CacheService',
+ 'Sdc.Services.CookieService',
+ 'Sdc.Services.ConfigurationUiService',
+ 'Sdc.Services.UserResourceService',
+ 'Sdc.Services.CategoryResourceService',
+ 'Sdc.Services.SdcVersionService',
+ '$state',
+ '$rootScope',
+ '$location',
+ 'sdcMenu',
+ 'ModalsHandler',
+ 'Sdc.Services.EcompHeaderService',
+ 'LeftPaletteLoaderService',
+ 'Sdc.Services.DataTypesService',
+ 'AngularJSBridge',
+ ($http:ng.IHttpService,
+ cacheService:CacheService,
+ cookieService:CookieService,
+ ConfigurationUi:ConfigurationUiService,
+ UserResourceClass:IUserResourceClass,
+ categoryResourceService:ICategoryResourceClass,
+ sdcVersionService:SdcVersionService,
+ $state:ng.ui.IStateService,
+ $rootScope:ng.IRootScopeService,
+ $location:ng.ILocationService,
+ sdcMenu:IAppMenu,
+ ModalsHandler:ModalsHandler,
+ ecompHeaderService:EcompHeaderService,
+ LeftPaletteLoaderService:LeftPaletteLoaderService,
+ DataTypesService:DataTypesService,
+ AngularJSBridge):void => {
+
+ //handle cache data - version
+ let initAsdcVersion:Function = ():void => {
+
+ let onFailed = (response) => {
+ console.info('onFailed initAsdcVersion', response);
+ cacheService.set('version', 'N/A');
+ };
+
+ let onSuccess = (version:any) => {
+ let tmpVerArray = version.version.split(".");
+ let ver = tmpVerArray[0] + "." + tmpVerArray[1] + "." + tmpVerArray[2];
+ cacheService.set('version', ver);
+ };
+
+ sdcVersionService.getVersion().then(onSuccess, onFailed);
+
+ };
+
+ let initEcompMenu:Function = (user):void => {
+ ecompHeaderService.getMenuItems(user.userId).then((data)=> {
+ $rootScope['menuItems'] = data;
+ });
+ };
+
+ let initConfigurationUi:Function = ():void => {
+ ConfigurationUi
+ .getConfigurationUi()
+ .then((configurationUi:any) => {
+ cacheService.set('UIConfiguration', configurationUi);
+ });
+ };
+
+ let initCategories:Function = ():void => {
+ let onError = ():void => {
+ console.log('Failed to init categories');
+ };
+
+ categoryResourceService.getAllCategories((categories: Categories):void => {
+ cacheService.set('serviceCategories', categories.serviceCategories);
+ cacheService.set('resourceCategories', categories.resourceCategories);
+ cacheService.set('productCategories', categories.productCategories);
+ }, onError);
+ };
+
+ // Add hosted applications to sdcConfig
+ sdcConfig.hostedApplications = hostedApplications;
+
+ //handle http config
+ $http.defaults.withCredentials = true;
+ $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w';
+ $http.defaults.headers.common[cookieService.getUserIdSuffix()] = cookieService.getUserId();
+
+ initAsdcVersion();
+ initConfigurationUi();
+ // initLeftPalette();
+ DataTypesService.initDataTypes();
+
+ //handle stateChangeStart
+ let internalDeregisterStateChangeStartWatcher:Function = ():void => {
+ if (deregisterStateChangeStartWatcher) {
+ deregisterStateChangeStartWatcher();
+ deregisterStateChangeStartWatcher = null;
+ }
+ };
+
+ let removeLoader:Function = ():void => {
+ $(".sdc-loading-page .main-loader").addClass("animated fadeOut");
+ $(".sdc-loading-page .caption1").addClass("animated fadeOut");
+ $(".sdc-loading-page .caption2").addClass("animated fadeOut");
+ window.setTimeout(():void=> {
+ $(".sdc-loading-page .main-loader").css("display", "none");
+ $(".sdc-loading-page .caption1").css("display", "none");
+ $(".sdc-loading-page .caption2").css("display", "none");
+ $(".sdc-loading-page").addClass("animated fadeOut");
+ }, 1000);
+ };
+
+ let onNavigateOut:Function = (toState, toParams):void => {
+ let onOk = ():void => {
+ $state.current.data.unsavedChanges = false;
+ $state.go(toState.name, toParams);
+ };
+
+ let data = sdcMenu.alertMessages.exitWithoutSaving;
+ //open notify to user if changes are not saved
+ ModalsHandler.openAlertModal(data.title, data.message).then(onOk);
+ };
+
+ let onStateChangeStart:Function = (event, toState, toParams, fromState, fromParams):void => {
+ console.info((new Date()).getTime());
+ console.info('$stateChangeStart', toState.name);
+ //set body class
+ $rootScope['bodyClass'] = 'default-class';
+ if (toState.data && toState.data.bodyClass) {
+ $rootScope['bodyClass'] = toState.data.bodyClass;
+ }
+
+ // Workaround in case we are entering other state then workspace (user move to catalog)
+ // remove the changeComponentCsarVersion, user should open again the VSP list and select one for update.
+ if (toState.name.indexOf('workspace') === -1) {
+ if (cacheService.contains(CHANGE_COMPONENT_CSAR_VERSION_FLAG)) {
+ cacheService.remove(CHANGE_COMPONENT_CSAR_VERSION_FLAG);
+ }
+ }
+
+ //saving last state to params , for breadcrumbs
+ if (['dashboard', 'catalog', 'onboardVendor'].indexOf(fromState.name) > -1) {
+ toParams.previousState = fromState.name;
+ } else {
+ toParams.previousState = fromParams.previousState;
+ }
+
+ if (toState.name !== 'error-403' && !UserResourceClass.getLoggedinUser()) {
+ internalDeregisterStateChangeStartWatcher();
+ event.preventDefault();
+
+ UserResourceClass.authorize().$promise.then((user:IUserResource) => {
+ if (!doesUserHasAccess(toState, user)) {
+ $state.go('error-403');
+ console.info('User has no permissions');
+ registerStateChangeStartWatcher();
+ return;
+ }
+ UserResourceClass.setLoggedinUser(user);
+ cacheService.set('user', user);
+ initCategories();
+ // initEcompMenu(user);
+ setTimeout(function () {
+
+ removeLoader();
+
+ // initCategories();
+ if (UserResourceClass.getLoggedinUser().role === 'ADMIN') {
+ // toState.name = "adminDashboard";
+ $state.go("adminDashboard", toParams);
+ registerStateChangeStartWatcher();
+ return;
+ }
+
+ // After user authorized init categories
+ window.setTimeout(():void=> {
+ if ($state.current.name === '') {
+ $state.go(toState.name, toParams);
+ }
+
+ console.log("------$state.current.name=" + $state.current.name);
+ console.info('-----registerStateChangeStartWatcher authorize $stateChangeStart');
+ registerStateChangeStartWatcher();
+
+ }, 1000);
+
+ }, 0);
+
+ }, () => {
+ $state.go('error-403');
+
+ console.info('registerStateChangeStartWatcher error-403 $stateChangeStart');
+ registerStateChangeStartWatcher();
+ });
+ }
+ else if (UserResourceClass.getLoggedinUser()) {
+ internalDeregisterStateChangeStartWatcher();
+ if (!doesUserHasAccess(toState, UserResourceClass.getLoggedinUser())) {
+ event.preventDefault();
+ $state.go('error-403');
+ console.info('User has no permissions');
+ }
+ if (toState.name === "welcome") {
+ $state.go("dashboard");
+ }
+ registerStateChangeStartWatcher();
+ //if form is dirty and not save - notify to user
+ if (fromState.data && fromState.data.unsavedChanges && fromParams.id != toParams.id) {
+ event.preventDefault();
+ onNavigateOut(toState, toParams);
+ }
+ }
+
+ };
+
+ let doesUserHasAccess:Function = (toState, user):boolean => {
+
+ let isUserHasAccess = true;
+ if (toState.permissions && toState.permissions.length > 0) {
+ isUserHasAccess = _.includes(toState.permissions, user.role);
+ }
+ return isUserHasAccess;
+ };
+ let deregisterStateChangeStartWatcher:Function;
+
+ let registerStateChangeStartWatcher:Function = ():void => {
+ internalDeregisterStateChangeStartWatcher();
+ console.info('registerStateChangeStartWatcher $stateChangeStart');
+ deregisterStateChangeStartWatcher = $rootScope.$on('$stateChangeStart', (event, toState, toParams, fromState, fromParams):void => {
+ onStateChangeStart(event, toState, toParams, fromState, fromParams);
+ });
+ };
+
+ registerStateChangeStartWatcher();
+ }]);
+
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/composition/tabs/relations/relations.less b/catalog-ui/src/app/directives/capabilities-and-requirements/capabilities-requirements-list.less
index 212b9785e9..0860261b97 100644
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/composition/tabs/relations/relations.less
+++ b/catalog-ui/src/app/directives/capabilities-and-requirements/capabilities-requirements-list.less
@@ -1,14 +1,15 @@
-.w-sdc-designer-sidebar-tab-content.relations {
+.i-sdc-designer-sidebar-capabilities-requirements {
- .w-sdc-designer-sidebar-section-content {
- padding: 0;
- }
+ .b_7;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
- .w-sdc-designer-sidebar-section-title {
- &.expanded {
- margin-bottom: 0;
+ &.description {
+ margin-top: 28px;
+ white-space: normal;
+ word-wrap: break-word;
}
- }
.i-sdc-designer-sidebar-section-content-item-relations {
border-bottom: 1px solid @color_e;
@@ -28,15 +29,13 @@
display: block;
}
-
}
-
}
+
.w-sdc-designer-sidebar-section-relations:not(:last-child) .i-sdc-designer-sidebar-section-content-item-relations-group:last-child .i-sdc-designer-sidebar-section-content-item-relations:last-child {
border-bottom: none;
}
-
.i-sdc-designer-sidebar-section-content-item-relations.hand {
.hand;
}
@@ -65,16 +64,16 @@
.i-sdc-designer-sidebar-section-content-item-relations-details-ownerName {
.b_13;
- font-weight:400;
+ font-weight: 400;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
- &:before{
- .sprite;
- .arrow-left;
- content: '';
- }
+ &:before {
+ .sprite;
+ .arrow-left;
+ content: '';
+ }
}
.i-sdc-designer-sidebar-section-content-item-relations-details-desc {
@@ -82,8 +81,9 @@
line-height: 14px;
word-wrap: break-word;
white-space: normal;
+ max-width: 265px;
- .i-sdc-designer-sidebar-section-content-item-relations-details-indent-box{
+ .i-sdc-designer-sidebar-section-content-item-relations-details-indent-box {
border-left: 1px #848586 solid;
height: 40px;
margin-left: 2px;
@@ -92,7 +92,7 @@
width: 25px;
float: left;
}
- .i-sdc-designer-sidebar-section-content-item-relations-details-child{
+ .i-sdc-designer-sidebar-section-content-item-relations-details-child {
margin-top: 30px;
float: left;
padding-left: 10px;
@@ -110,7 +110,4 @@
top: 22px;
display: none;
}
-
}
-
-
diff --git a/catalog-ui/src/app/directives/capabilities-and-requirements/capability/capabilities-list-directive.ts b/catalog-ui/src/app/directives/capabilities-and-requirements/capability/capabilities-list-directive.ts
new file mode 100644
index 0000000000..e71478fa4d
--- /dev/null
+++ b/catalog-ui/src/app/directives/capabilities-and-requirements/capability/capabilities-list-directive.ts
@@ -0,0 +1,40 @@
+/**
+ * Created by ob0695 on 5/9/2017.
+ */
+/**
+ * Created by obarda on 1/8/2017.
+ */
+'use strict';
+import {CapabilitiesGroup} from "app/models";
+
+export interface ICapabilitiesListScope extends ng.IScope {
+ capabilities:CapabilitiesGroup;
+}
+
+
+export class CapabilitiesListDirective implements ng.IDirective {
+
+ constructor() {
+
+ }
+
+ scope = {
+ capabilities: '=',
+ };
+
+ restrict = 'E';
+ replace = true;
+ template = ():string => {
+ return require('./capabilities-list-view.html');
+ };
+
+ link = (scope:ICapabilitiesListScope, element:any, $attr:any) => {
+
+ };
+
+ public static factory = ()=> {
+ return new CapabilitiesListDirective();
+ };
+}
+
+CapabilitiesListDirective.factory.$inject = [];
diff --git a/catalog-ui/src/app/directives/capabilities-and-requirements/capability/capabilities-list-view.html b/catalog-ui/src/app/directives/capabilities-and-requirements/capability/capabilities-list-view.html
new file mode 100644
index 0000000000..c86a6df785
--- /dev/null
+++ b/catalog-ui/src/app/directives/capabilities-and-requirements/capability/capabilities-list-view.html
@@ -0,0 +1,14 @@
+<div class="i-sdc-designer-sidebar-capabilities-requirements">
+ <div class="i-sdc-designer-sidebar-section-content-item-relations-group">
+ <div class="i-sdc-designer-sidebar-section-content-item-relations"
+ data-ng-repeat="capability in capabilities track by $index">
+ <div class="i-sdc-designer-sidebar-section-content-item-relations-details">
+ <div class="i-sdc-designer-sidebar-section-content-item-relations-details-name">{{capability.name}}&nbsp;</div>
+ <div class="i-sdc-designer-sidebar-section-content-item-relations-details-desc" sdc-smart-tooltip>
+ {{capability.type}}
+ </div>
+ </div>
+ </div>
+ </div>
+</div>
+
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
new file mode 100644
index 0000000000..9863b5d271
--- /dev/null
+++ b/catalog-ui/src/app/directives/capabilities-and-requirements/requirement/requirements-list-directive.ts
@@ -0,0 +1,71 @@
+/**
+ * Created by ob0695 on 5/9/2017.
+ */
+/**
+ * Created by ob0695 on 5/9/2017.
+ */
+/**
+ * Created by obarda on 1/8/2017.
+ */
+'use strict';
+import {RequirementsGroup, Component} from "app/models";
+
+export interface IRequirementsListScope extends ng.IScope {
+
+ requirements:RequirementsGroup;
+ currentComponent: Component;
+}
+
+
+export class RequirementsListDirective implements ng.IDirective {
+
+ constructor(private $filter: ng.IFilterService) {
+
+ }
+
+ scope = {
+ requirements: '=',
+ component: '='
+ };
+
+ restrict = 'E';
+ replace = true;
+ template = ():string => {
+ return require('./requirements-list-view.html');
+ };
+
+ link = (scope:IRequirementsListScope) => {
+
+ scope.isInstanceSelected = () : boolean => {
+ return scope.component && scope.component.selectedInstance != undefined && scope.component.selectedInstance != null;
+ }
+
+ scope.getRelation = (requirement:any):any => {
+ if (scope.isInstanceSelected() && scope.component.componentInstancesRelations) {
+ let relationItem = _.filter(scope.component.componentInstancesRelations, (relation:any) => {
+ return relation.fromNode === scope.component.selectedInstance.uniqueId &&
+ _.some(relation.relationships, {
+ 'requirement': requirement.name,
+ 'requirementOwnerId': requirement.ownerId
+ });
+ });
+
+ if (relationItem && relationItem.length) {
+ return {
+ type: requirement.relationship.split('.').pop(),
+ requirementName: this.$filter('resourceName')(scope.component.componentInstances[_.map
+ (scope.component.componentInstances, "uniqueId").indexOf(relationItem[0].toNode)].name)
+ };
+ }
+ }
+ return null;
+ };
+
+ };
+
+ public static factory = ($filter: ng.IFilterService)=> {
+ return new RequirementsListDirective($filter);
+ };
+}
+
+RequirementsListDirective.factory.$inject = ['$filter'];
diff --git a/catalog-ui/src/app/directives/capabilities-and-requirements/requirement/requirements-list-view.html b/catalog-ui/src/app/directives/capabilities-and-requirements/requirement/requirements-list-view.html
new file mode 100644
index 0000000000..a6487fe72a
--- /dev/null
+++ b/catalog-ui/src/app/directives/capabilities-and-requirements/requirement/requirements-list-view.html
@@ -0,0 +1,19 @@
+<div class="i-sdc-designer-sidebar-capabilities-requirements">
+ <div class="i-sdc-designer-sidebar-section-content-item-relations-group">
+ <div class="i-sdc-designer-sidebar-section-content-item-relations"
+ data-ng-repeat="requirement in requirements track by $index">
+ <div class="i-sdc-designer-sidebar-section-content-item-relations-details">
+ <div class="i-sdc-designer-sidebar-section-content-item-relations-details-name">{{requirement.name}}&nbsp;</div>
+ <div class="i-sdc-designer-sidebar-section-content-item-relations-details-desc">{{requirement.node}}
+ <div data-ng-if="getRelation(requirement) != null">
+ <div class="i-sdc-designer-sidebar-section-content-item-relations-details-indent-box"></div>
+ <div class="i-sdc-designer-sidebar-section-content-item-relations-details-child">
+ <span class="i-sdc-designer-sidebar-section-content-item-relations-details-desc">{{getRelation(requirement).type}} <br/></span>
+ <span class="i-sdc-designer-sidebar-section-content-item-relations-details-name">{{getRelation(requirement).requirementName}}</span>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+</div>
diff --git a/catalog-ui/src/app/directives/clicked-outside/clicked-outside-directive.ts b/catalog-ui/src/app/directives/clicked-outside/clicked-outside-directive.ts
new file mode 100644
index 0000000000..009e104740
--- /dev/null
+++ b/catalog-ui/src/app/directives/clicked-outside/clicked-outside-directive.ts
@@ -0,0 +1,110 @@
+class ClickedOutsideModel {
+
+ private clickedOutsideContainerSelector:string;
+ private onClickedOutsideGetter:Function;
+ private clickedOutsideEnableGetter:Function;
+
+ constructor(clickedOutsideData:any) {
+ this.clickedOutsideContainerSelector = clickedOutsideData.clickedOutsideContainerSelector;
+ this.onClickedOutsideGetter = clickedOutsideData.onClickedOutsideGetter;
+ this.clickedOutsideEnableGetter = clickedOutsideData.clickedOutsideEnableGetter;
+ }
+
+ public getClickedOutsideContainerSelector = ():string => {
+ return this.clickedOutsideContainerSelector;
+ }
+
+ public getOnClickedOutsideGetter = ():Function => {
+ return this.onClickedOutsideGetter;
+ }
+
+ public getClickedOutsideEnableGetter = ():Function => {
+ return this.clickedOutsideEnableGetter;
+ }
+}
+
+export interface IClickedOutsideDirectiveScope extends ng.IScope {
+}
+
+export class ClickedOutsideDirective implements ng.IDirective {
+
+ constructor(private $document:JQuery, private $parse:ng.IParseService) {
+ }
+
+ restrict = 'A';
+
+ link = (scope:IClickedOutsideDirectiveScope, element:JQuery, attrs) => {
+
+ let container:HTMLElement;
+ let attrsAfterEval = scope.$eval(attrs.clickedOutside);
+ attrsAfterEval.onClickedOutsideGetter = this.$parse(attrsAfterEval.onClickedOutside);
+ attrsAfterEval.clickedOutsideEnableGetter = this.$parse(attrsAfterEval.clickedOutsideEnable);
+
+ let clickedOutsideModel:ClickedOutsideModel = new ClickedOutsideModel(attrsAfterEval);
+
+
+ let getContainer:Function = ():HTMLElement => {
+ if (!container) {
+ let clickedOutsideContainerSelector:string = clickedOutsideModel.getClickedOutsideContainerSelector();
+ if (!angular.isUndefined(clickedOutsideContainerSelector) && clickedOutsideContainerSelector !== '') {
+ container = element.parents(clickedOutsideContainerSelector + ':first')[0];
+ if (!container) {
+ container = element[0];
+ }
+ } else {
+ container = element[0];
+ }
+ }
+ return container;
+ };
+
+
+ let onClickedOutside = (event:JQueryEventObject) => {
+ let containerDomElement:HTMLElement = getContainer();
+ let targetDomElementJq:JQuery = angular.element(event.target);
+ if (targetDomElementJq.hasClass('tooltip') || targetDomElementJq.parents('.tooltip:first').length) {
+ return;
+ }
+ let targetDomElement:HTMLElement = targetDomElementJq[0];
+ if (!containerDomElement.contains(targetDomElement)) {
+ scope.$apply(() => {
+ let onClickedOutsideGetter:Function = clickedOutsideModel.getOnClickedOutsideGetter();
+ onClickedOutsideGetter(scope);
+ });
+ }
+ };
+
+ let attachDomEvents:Function = () => {
+ this.$document.on('mousedown', onClickedOutside);
+ };
+
+ let detachDomEvents:Function = () => {
+ this.$document.off('mousedown', onClickedOutside);
+ };
+
+ //
+ scope.$on('$destroy', () => {
+ detachDomEvents();
+ });
+
+
+ scope.$watch(() => {
+ let clickedOutsideEnableGetter:Function = clickedOutsideModel.getClickedOutsideEnableGetter();
+ return clickedOutsideEnableGetter(scope);
+ }, (newValue:boolean) => {
+ if (newValue) {
+ attachDomEvents();
+ return;
+ }
+ detachDomEvents();
+ });
+
+
+ }
+
+ public static factory = ($document:JQuery, $parse:ng.IParseService) => {
+ return new ClickedOutsideDirective($document, $parse);
+ }
+}
+
+ClickedOutsideDirective.factory.$inject = ['$document', '$parse'];
diff --git a/catalog-ui/src/app/directives/custom-validation/custom-validation.ts b/catalog-ui/src/app/directives/custom-validation/custom-validation.ts
new file mode 100644
index 0000000000..e35a747e1b
--- /dev/null
+++ b/catalog-ui/src/app/directives/custom-validation/custom-validation.ts
@@ -0,0 +1,32 @@
+'use strict';
+export interface ICustomValidationScope extends ng.IScope {
+ validationFunc:Function;
+}
+
+export class CustomValidationDirective implements ng.IDirective {
+
+ constructor() {
+ }
+
+ require = 'ngModel';
+ restrict = 'A';
+
+ scope = {
+ validationFunc: '='
+ };
+
+ link = (scope:ICustomValidationScope, elem, attrs, ngModel) => {
+
+ ngModel.$validators.customValidation = (modelValue, viewValue):boolean => {
+ return scope.validationFunc(viewValue);
+ };
+
+ };
+
+ public static factory = ()=> {
+ return new CustomValidationDirective();
+ };
+
+}
+
+CustomValidationDirective.factory.$inject = [];
diff --git a/catalog-ui/src/app/directives/download-artifact/download-artifact.ts b/catalog-ui/src/app/directives/download-artifact/download-artifact.ts
new file mode 100644
index 0000000000..7c817935cf
--- /dev/null
+++ b/catalog-ui/src/app/directives/download-artifact/download-artifact.ts
@@ -0,0 +1,125 @@
+'use strict';
+import {IFileDownload, Component, ArtifactModel} from "app/models";
+import {EventListenerService, CacheService} from "app/services";
+import {EVENTS, FileUtils} from "app/utils";
+
+export class DOWNLOAD_CSS_CLASSES {
+ static DOWNLOAD_ICON = "table-download-btn tosca";
+ static LOADER_ICON = "tlv-loader small loader";
+}
+
+export interface IDownloadArtifactScope extends ng.IScope {
+ $window:any;
+ artifact:ArtifactModel;
+ component:Component;
+ instance:boolean;
+ download:Function;
+ showLoader:boolean;
+ downloadIconClass:string;
+ updateDownloadIcon:Function;
+}
+
+export class DownloadArtifactDirective implements ng.IDirective {
+
+ constructor(private $window:any, private cacheService:CacheService, private EventListenerService:EventListenerService, private fileUtils:FileUtils) {
+ }
+
+ scope = {
+ artifact: '=',
+ component: '=',
+ instance: '=',
+ showLoader: '=',
+ downloadIconClass: '@'
+ };
+ restrict = 'EA';
+
+ link = (scope:IDownloadArtifactScope, element:any) => {
+ scope.$window = this.$window;
+
+ element.on("click", function () {
+ scope.download(scope.artifact);
+ });
+
+
+ let initDownloadLoader = ()=> {
+ //if the artifact is in a middle of download progress register form callBack & change icon from download to loader
+ if (scope.showLoader && this.cacheService.get(scope.artifact.uniqueId)) {
+ this.EventListenerService.registerObserverCallback(EVENTS.DOWNLOAD_ARTIFACT_FINISH_EVENT + scope.artifact.uniqueId, scope.updateDownloadIcon);
+ window.setTimeout(():void => {
+ if (this.cacheService.get(scope.artifact.uniqueId)) {
+ element[0].className = DOWNLOAD_CSS_CLASSES.LOADER_ICON;
+ }
+ }, 1000);
+
+ }
+ };
+
+ let setDownloadedFileLoader = ()=> {
+ if (scope.showLoader) {
+ //set in cache service thet the artifact is in download progress
+ this.cacheService.set(scope.artifact.uniqueId, true);
+ initDownloadLoader();
+ }
+ };
+
+ let removeDownloadedFileLoader = ()=> {
+ if (scope.showLoader) {
+ this.cacheService.set(scope.artifact.uniqueId, false);
+ this.EventListenerService.notifyObservers(EVENTS.DOWNLOAD_ARTIFACT_FINISH_EVENT + scope.artifact.uniqueId);
+ }
+ };
+
+
+ //replace the loader to download icon
+ scope.updateDownloadIcon = () => {
+ element[0].className = scope.downloadIconClass || DOWNLOAD_CSS_CLASSES.DOWNLOAD_ICON;
+ };
+
+
+ initDownloadLoader();
+
+ scope.download = (artifact:ArtifactModel):void => {
+
+ let onFaild = (response):void => {
+ console.info('onFaild', response);
+ removeDownloadedFileLoader();
+ };
+
+ let onSuccess = (data:IFileDownload):void => {
+ downloadFile(data);
+ removeDownloadedFileLoader();
+ };
+
+ setDownloadedFileLoader();
+
+ if (scope.instance) {
+ scope.component.downloadInstanceArtifact(artifact.uniqueId).then(onSuccess, onFaild);
+ } else {
+ scope.component.downloadArtifact(artifact.uniqueId).then(onSuccess, onFaild);
+ }
+ };
+
+ let downloadFile = (file:IFileDownload):void => {
+ if (file) {
+ let blob = this.fileUtils.base64toBlob(file.base64Contents, '');
+ let fileName = file.artifactName;
+ this.fileUtils.downloadFile(blob, fileName);
+ }
+ };
+
+ element.on('$destroy', ()=> {
+ //remove listener of download event
+ if (scope.artifact && scope.artifact.uniqueId) {
+ this.EventListenerService.unRegisterObserver(EVENTS.DOWNLOAD_ARTIFACT_FINISH_EVENT + scope.artifact.uniqueId);
+ }
+ });
+
+ };
+
+ public static factory = ($window:any, cacheService:CacheService, EventListenerService:EventListenerService, fileUtils:FileUtils)=> {
+ return new DownloadArtifactDirective($window, cacheService, EventListenerService, fileUtils);
+ };
+
+}
+
+DownloadArtifactDirective.factory.$inject = ['$window', 'Sdc.Services.CacheService', 'EventListenerService', 'FileUtils'];
diff --git a/catalog-ui/src/app/directives/ecomp-footer/ecomp-footer.html b/catalog-ui/src/app/directives/ecomp-footer/ecomp-footer.html
new file mode 100644
index 0000000000..a50731443d
--- /dev/null
+++ b/catalog-ui/src/app/directives/ecomp-footer/ecomp-footer.html
@@ -0,0 +1,8 @@
+<div class="footer-wrapper">
+ <div class="divider-footer-bottom">
+ <div class="footer-copyright-text">
+ <p>
+ </p>
+ </div>
+ </div>
+</div>
diff --git a/catalog-ui/src/app/directives/ecomp-footer/ecomp-footer.less b/catalog-ui/src/app/directives/ecomp-footer/ecomp-footer.less
new file mode 100644
index 0000000000..4c54a11fec
--- /dev/null
+++ b/catalog-ui/src/app/directives/ecomp-footer/ecomp-footer.less
@@ -0,0 +1,47 @@
+
+.footer-wrapper {
+ position: fixed;
+ bottom: 0px;
+ left: 0px;
+ width: 100%;
+ background-color: #222222;
+ color: #ffffff;
+ font-family: "Arial";
+ font-size: 11px;
+ height: @footer_height;
+}
+
+.footer-wrapper a {
+ color: #ffffff;
+ margin: 0;
+ padding: 0;
+ text-decoration: underline;
+}
+
+.divider-footer-bottom {
+ margin: 0 auto;
+ width: 1020px;
+}
+
+.footer-copyright-text {
+ display: inline-block;
+ width:612px;
+ margin-top: 18px;
+ margin-left: 50px;
+ text-align: left;
+ vertical-align: top;
+}
+
+.footer-logo1 {
+ display: inline-block;
+ margin-top: 20px;
+ margin-left: 124px;
+}
+
+.footer-logo2 {
+ margin-top: 22px;
+ margin-left: 9px;
+ display: inline-block;
+ font-size: 24px;
+ vertical-align: top;
+}
diff --git a/catalog-ui/src/app/directives/ecomp-footer/ecomp-footer.ts b/catalog-ui/src/app/directives/ecomp-footer/ecomp-footer.ts
new file mode 100644
index 0000000000..f104926fc6
--- /dev/null
+++ b/catalog-ui/src/app/directives/ecomp-footer/ecomp-footer.ts
@@ -0,0 +1,33 @@
+'use strict';
+import {IAppConfigurtaion} from "app/models";
+
+export interface IEcompFooterDirectiveScope extends ng.IScope {
+
+}
+
+export class EcompFooterDirective implements ng.IDirective {
+
+ constructor(private sdcConfig:IAppConfigurtaion) {
+
+ }
+
+ public replace = true;
+ public restrict = 'E';
+
+ public scope = {};
+
+ template = ():string => {
+ return require('./ecomp-footer.html');
+ };
+
+ link = (scope:IEcompFooterDirectiveScope, $elem:JQuery, attr:any) => {
+
+ };
+
+ public static factory = (sdcConfig:IAppConfigurtaion)=> {
+ return new EcompFooterDirective(sdcConfig);
+ };
+
+}
+
+EcompFooterDirective.factory.$inject = ['sdcConfig'];
diff --git a/catalog-ui/app/scripts/directives/ecomp-header/ecomp-header.html b/catalog-ui/src/app/directives/ecomp-header/ecomp-header.html
index e86f9df8b0..67799420f4 100644
--- a/catalog-ui/app/scripts/directives/ecomp-header/ecomp-header.html
+++ b/catalog-ui/src/app/directives/ecomp-header/ecomp-header.html
@@ -3,8 +3,8 @@
<div class="sdc-ecomp-header">
<div class="sdc-ecomp-logo-wrapper">
- <a class="sdc-ecomp-header-title" data-ng-if="clickableLogo==='true'" data-ui-sref="dashboard"><span class="sdc-ecomp-logo"></span>ASDC</a>
- <a class="sdc-ecomp-header-title" data-ng-if="clickableLogo==='false'"><span class="sdc-ecomp-logo"></span>ASDC</a>
+ <a class="sdc-ecomp-header-title" data-ng-if="clickableLogo==='true'" data-ui-sref="dashboard" translate="PROJECT_TITLE"><span class="sdc-ecomp-logo"></span></a>
+ <a class="sdc-ecomp-header-title" data-ng-if="clickableLogo==='false'"><span class="sdc-ecomp-logo" translate="PROJECT_TITLE"></span></a>
<div class="sdc-ecomp-header-version"> v.{{version}}</div>
</div>
diff --git a/catalog-ui/app/scripts/directives/ecomp-header/ecomp-header.less b/catalog-ui/src/app/directives/ecomp-header/ecomp-header.less
index a6f7e9b5a2..8fa80c4237 100644
--- a/catalog-ui/app/scripts/directives/ecomp-header/ecomp-header.less
+++ b/catalog-ui/src/app/directives/ecomp-header/ecomp-header.less
@@ -214,7 +214,7 @@
position: relative;
.sdc-ecomp-logo {
- background-image: url("images/att_logo_white.png");
+ background-image: url("/assets/styles/images/att_logo_white.png");
background-repeat: no-repeat;
display: inline-block;
vertical-align: middle;
diff --git a/catalog-ui/src/app/directives/ecomp-header/ecomp-header.ts b/catalog-ui/src/app/directives/ecomp-header/ecomp-header.ts
new file mode 100644
index 0000000000..ba96e80484
--- /dev/null
+++ b/catalog-ui/src/app/directives/ecomp-header/ecomp-header.ts
@@ -0,0 +1,217 @@
+'use strict';
+import {IAppConfigurtaion, User, IUser} from "app/models";
+import {IUserResourceClass, IUserResource} from "app/services";
+
+export class MenuItem {
+ menuId:number;
+ column:number;
+ text:string;
+ parentMenuId:number;
+ url:string;
+ children:Array<MenuItem>
+}
+
+export interface IEcompHeaderDirectiveScope extends ng.IScope {
+ menuData:Array<MenuItem>;
+ version:string;
+ clickableLogo:string;
+ contactUsUrl:string;
+ getAccessUrl:string;
+ megaMenuDataObjectTemp:Array<any>;
+ megaMenuDataObject:Array<any>;
+
+ selectedTopMenu:MenuItem;
+ selectedSubMenu:MenuItem;
+
+ firstMenuLevelClick:Function;
+ subMenuEnterAction:Function;
+ subMenuLeaveAction:Function;
+
+ memuItemClick:Function;
+ user:IUser;
+}
+
+export class EcompHeaderDirective implements ng.IDirective {
+
+ constructor(private $http:ng.IHttpService,
+ private sdcConfig:IAppConfigurtaion,
+ private UserResourceClass:IUserResourceClass) {
+
+ }
+
+ scope = {
+ menuData: '=',
+ version: '@',
+ clickableLogo: '@?'
+ };
+
+ public replace = true;
+ public restrict = 'E';
+ public controller = EcompHeaderController;
+
+ template = ():string => {
+ return 'src/app/directives/ecomp-header/ecomp-header.html';
+ };
+
+ link = ($scope:IEcompHeaderDirectiveScope, $elem:JQuery, attr:any) => {
+
+ if (!$scope.clickableLogo) {
+ $scope.clickableLogo = "true";
+ }
+
+ let findMenuItemById = (menuId):MenuItem => {
+ let selectedMenuItem:MenuItem = _.find($scope.menuData, (item:MenuItem)=> {
+ if (item.menuId === menuId) {
+ return item;
+ }
+ });
+ return selectedMenuItem;
+ };
+
+ let initUser = ():void => {
+ let defaultUserId:string;
+ let user:IUserResource = this.UserResourceClass.getLoggedinUser();
+ if (!user) {
+ defaultUserId = this.$http.defaults.headers.common[this.sdcConfig.cookie.userIdSuffix];
+ user = this.UserResourceClass.get({id: defaultUserId}, ():void => {
+ $scope.user = new User(user);
+ });
+ } else {
+ $scope.user = new User(user);
+ }
+ };
+
+ $scope.firstMenuLevelClick = (menuId:number):void => {
+ let selectedMenuItem:MenuItem = _.find($scope.megaMenuDataObjectTemp, (item:MenuItem)=> {
+ if (item.menuId === menuId) {
+ return item;
+ }
+ });
+ if (selectedMenuItem) {
+ $scope.selectedTopMenu = selectedMenuItem;
+ //console.log("Selected menu item: " + selectedMenuItem.text);
+ }
+ };
+
+ $scope.subMenuEnterAction = (menuId:number):void => {
+ $scope.selectedSubMenu = findMenuItemById(menuId);
+ };
+
+ $scope.subMenuLeaveAction = (menuId:number):void => {
+ $scope.selectedTopMenu = undefined;
+ };
+
+ $scope.memuItemClick = (menuItem:MenuItem):void => {
+ if (menuItem.url) {
+ window.location.href = menuItem.url;
+ } else {
+ console.log("Menu item: " + menuItem.text + " does not have defined URL!");
+ }
+ };
+
+ initUser();
+
+ };
+
+ public static factory = ($http:ng.IHttpService,
+ sdcConfig:IAppConfigurtaion,
+ UserResourceClass:IUserResourceClass)=> {
+ return new EcompHeaderDirective($http, sdcConfig, UserResourceClass);
+ };
+
+}
+
+export class EcompHeaderController {
+
+ messages:any;
+ getAttachId:Function;
+ render:any;
+ reRender:Function;
+ register:Function;
+ deregister:Function;
+ head:any;
+
+ static '$inject' = [
+ '$element',
+ '$scope',
+ '$attrs',
+ '$animate'
+ ];
+
+ constructor(private $element:JQuery,
+ private $scope:IEcompHeaderDirectiveScope,
+ private $attrs:ng.IAttributes,
+ private $animate:any) {
+
+ this.$scope = $scope;
+
+ this.$scope.$watch('menuData', (newVal, oldVal) => {
+ if (newVal) {
+ this.init();
+ }
+ });
+
+ }
+
+ init = ():void => {
+
+ this.$scope.contactUsUrl = "https://wiki.web.att.com/display/EcompPortal/ECOMP+Portal+Home";
+ this.$scope.getAccessUrl = "http://ecomp-tlv-dev2.uccentral.att.com:8080/ecompportal/get_access";
+
+ let unflatten = (array, parent?, tree?) => {
+ tree = typeof tree !== 'undefined' ? tree : [];
+ parent = typeof parent !== 'undefined' ? parent : {menuId: null};
+ let children = _.filter(array, function (child) {
+ return child["parentMenuId"] == parent.menuId;
+ });
+ if (!_.isEmpty(children)) {
+ if (parent.menuId === null) {
+ tree = children;
+ } else {
+ parent['children'] = children
+ }
+ _.each(children, function (child) {
+ unflatten(array, child)
+ });
+ }
+ return tree;
+ };
+
+ let menuStructureConvert = (menuItems) => {
+ console.log(menuItems);
+ this.$scope.megaMenuDataObjectTemp = [
+ {
+ menuId: 1001,
+ text: "ECOMP",
+ children: menuItems
+ },
+ {
+ menuId: 1002,
+ text: "Help",
+ children: [
+ {
+ text: "Contact Us",
+ url: this.$scope.contactUsUrl
+ }]
+ }
+ ];
+
+ /*{
+ text:"Get Access",
+ url: this.$scope.getAccessUrl
+ }*/
+ return this.$scope.megaMenuDataObjectTemp;
+ };
+
+ let a = unflatten(this.$scope.menuData);
+ this.$scope.megaMenuDataObject = menuStructureConvert(a);
+ //console.log(this.$scope.megaMenuDataObject);
+ };
+}
+
+EcompHeaderDirective.factory.$inject = ['$http', 'sdcConfig', 'Sdc.Services.UserResourceService'];
+
+
+
+
+
diff --git a/catalog-ui/app/scripts/directives/edit-name-popover/edit-module-name-popover.html b/catalog-ui/src/app/directives/edit-name-popover/edit-module-name-popover.html
index d90c52d9a6..d90c52d9a6 100644
--- a/catalog-ui/app/scripts/directives/edit-name-popover/edit-module-name-popover.html
+++ b/catalog-ui/src/app/directives/edit-name-popover/edit-module-name-popover.html
diff --git a/catalog-ui/src/app/directives/edit-name-popover/edit-name-popover-directive.ts b/catalog-ui/src/app/directives/edit-name-popover/edit-name-popover-directive.ts
new file mode 100644
index 0000000000..b99f11fcf9
--- /dev/null
+++ b/catalog-ui/src/app/directives/edit-name-popover/edit-name-popover-directive.ts
@@ -0,0 +1,77 @@
+'use strict';
+
+export interface IEditNamePopoverDirectiveScope extends ng.IScope {
+ isOpen:boolean;
+ templateUrl:string;
+ module:any;
+ direction:string;
+ header:string;
+ heatNameValidationPattern:RegExp;
+ originalName:string;
+ onSave:any;
+
+ closePopover(isCancel:boolean):void;
+ validateField(field:any, originalName:string):boolean;
+ updateHeatName(heatName:string):void;
+ onInit():void;
+}
+
+export class EditNamePopoverDirective implements ng.IDirective {
+
+ constructor(private ValidationPattern:RegExp,private $templateCache:ng.ITemplateCacheService) {
+ }
+
+ scope = {
+ direction: "@?",
+ module: "=",
+ header: "@?",
+ onSave: "&"
+ };
+
+ link = (scope:IEditNamePopoverDirectiveScope) => {
+ if (!scope.direction) {
+ scope.direction = 'top';
+ }
+
+ scope.originalName = '';
+ this.$templateCache.put("edit-module-name-popover.html", require('./edit-module-name-popover.html'));
+ scope.templateUrl = "edit-module-name-popover.html";
+ scope.isOpen = false;
+
+ scope.closePopover = (isCancel:boolean = true) => {
+ scope.isOpen = !scope.isOpen;
+
+ if (isCancel) {
+ scope.module.heatName = scope.originalName;
+ }
+ };
+
+ scope.onInit = () => {
+ scope.originalName = scope.module.heatName;
+ };
+
+ scope.validateField = (field:any):boolean => {
+ return !!(field && field.$dirty && field.$invalid);
+ };
+
+ scope.heatNameValidationPattern = this.ValidationPattern;
+
+ scope.updateHeatName = () => {
+ scope.closePopover(false);
+ scope.onSave();
+ }
+
+ };
+
+ replace = true;
+ restrict = 'E';
+ template = ():string => {
+ return require('./edit-name-popover-view.html');
+ };
+
+ public static factory = (ValidationPattern:RegExp,$templateCache:ng.ITemplateCacheService)=> {
+ return new EditNamePopoverDirective(ValidationPattern,$templateCache);
+ }
+}
+
+EditNamePopoverDirective.factory.$inject = ['ValidationPattern','$templateCache'];
diff --git a/catalog-ui/src/app/directives/edit-name-popover/edit-name-popover-view.html b/catalog-ui/src/app/directives/edit-name-popover/edit-name-popover-view.html
new file mode 100644
index 0000000000..23340ccee2
--- /dev/null
+++ b/catalog-ui/src/app/directives/edit-name-popover/edit-name-popover-view.html
@@ -0,0 +1 @@
+<div uib-popover-template="templateUrl" popover-class="edit-name-popover" popover-title="{{header}}" popover-placement="{{direction}}" popover-is-open="isOpen" popover-append-to-body="true"></div>
diff --git a/catalog-ui/app/scripts/directives/edit-name-popover/edit-name-popover.less b/catalog-ui/src/app/directives/edit-name-popover/edit-name-popover.less
index 3d76a352ce..55dcd80a27 100644
--- a/catalog-ui/app/scripts/directives/edit-name-popover/edit-name-popover.less
+++ b/catalog-ui/src/app/directives/edit-name-popover/edit-name-popover.less
@@ -1,9 +1,18 @@
-.popover {
+.edit-name-popover{
max-width: none;
width: 310px;
left: initial !important;
right: 10px;
z-index: 100;
+
+ .arrow {
+ left: 95% !important;
+ border-width: 7px;
+ bottom: -8px !important;
+ }
+}
+
+.popover {
border-radius: 0;
.top > .arrow {
@@ -20,12 +29,6 @@
font-weight: bold;
}
- .arrow {
- left: 95% !important;
- border-width: 7px;
- bottom: -8px !important;
- }
-
.popover-content {
width: inherit;
padding: 9px 20px;
diff --git a/catalog-ui/app/scripts/directives/elements/checkbox/checkbox.html b/catalog-ui/src/app/directives/elements/checkbox/checkbox.html
index daf2a89ac2..1e25408188 100644
--- a/catalog-ui/app/scripts/directives/elements/checkbox/checkbox.html
+++ b/catalog-ui/src/app/directives/elements/checkbox/checkbox.html
@@ -7,6 +7,7 @@
ng-disabled="disabled"
checklist-model="sdcChecklistModel"
checklist-value="sdcChecklistValue"
+ checklist-change="sdcChecklistChange()"
/>
<span sdc-smart-tooltip class="tlv-checkbox-label" data-tests-id="{{elemId}}">{{text}}</span>
diff --git a/catalog-ui/app/scripts/directives/elements/checkbox/checkbox.less b/catalog-ui/src/app/directives/elements/checkbox/checkbox.less
index 0747a680a9..0747a680a9 100644
--- a/catalog-ui/app/scripts/directives/elements/checkbox/checkbox.less
+++ b/catalog-ui/src/app/directives/elements/checkbox/checkbox.less
diff --git a/catalog-ui/src/app/directives/elements/checkbox/checkbox.ts b/catalog-ui/src/app/directives/elements/checkbox/checkbox.ts
new file mode 100644
index 0000000000..ec0be8ab07
--- /dev/null
+++ b/catalog-ui/src/app/directives/elements/checkbox/checkbox.ts
@@ -0,0 +1,43 @@
+'use strict';
+
+export interface ICheckboxElementScope extends ng.IScope {
+ elemId:string;
+ text:string;
+ sdcChecklistModel:any;
+ sdcChecklistValue:string;
+ disabled:boolean;
+}
+
+export class CheckboxElementDirective implements ng.IDirective {
+
+ constructor(private $filter:ng.IFilterService) {
+ }
+
+ public replace = true;
+ public restrict = 'E';
+ public transclude = false;
+
+ scope = {
+ elemId: '@',
+ text: '@',
+ disabled: '=',
+ sdcChecklistModel: '=',
+ sdcChecklistValue: '=',
+ sdcChecklistChange: '&'
+ };
+
+ template = ():string => {
+ return require('./checkbox.html');
+ };
+
+ public link = (scope:ICheckboxElementScope, $elem:ng.IAugmentedJQuery, $attrs:angular.IAttributes) => {
+
+ };
+
+ public static factory = ($filter:ng.IFilterService)=> {
+ return new CheckboxElementDirective($filter);
+ };
+
+}
+
+CheckboxElementDirective.factory.$inject = ['$filter'];
diff --git a/catalog-ui/app/scripts/directives/elements/radiobutton/radiobutton.html b/catalog-ui/src/app/directives/elements/radiobutton/radiobutton.html
index b31fae5d73..b31fae5d73 100644
--- a/catalog-ui/app/scripts/directives/elements/radiobutton/radiobutton.html
+++ b/catalog-ui/src/app/directives/elements/radiobutton/radiobutton.html
diff --git a/catalog-ui/app/scripts/directives/elements/radiobutton/radiobutton.less b/catalog-ui/src/app/directives/elements/radiobutton/radiobutton.less
index e69de29bb2..e69de29bb2 100644
--- a/catalog-ui/app/scripts/directives/elements/radiobutton/radiobutton.less
+++ b/catalog-ui/src/app/directives/elements/radiobutton/radiobutton.less
diff --git a/catalog-ui/src/app/directives/elements/radiobutton/radiobutton.ts b/catalog-ui/src/app/directives/elements/radiobutton/radiobutton.ts
new file mode 100644
index 0000000000..1384a82674
--- /dev/null
+++ b/catalog-ui/src/app/directives/elements/radiobutton/radiobutton.ts
@@ -0,0 +1,48 @@
+import INgModelController = angular.INgModelController;
+'use strict';
+
+export interface IRadiobuttonElementScope extends ng.IScope {
+ elemId:string;
+ elemName:string;
+ text:string;
+ sdcModel:any;
+ value:any;
+ disabled:boolean;
+ onValueChange:Function;
+}
+
+export class RadiobuttonElementDirective implements ng.IDirective {
+
+ constructor(private $filter:ng.IFilterService) {
+ }
+
+ public replace = true;
+ public restrict = 'E';
+ public transclude = false;
+
+ scope = {
+ elemId: '@',
+ elemName: '@',
+ text: '@',
+ sdcModel: '=',
+ value: '@',
+ disabled: '=',
+ onValueChange: '&'
+ };
+
+ template = ():string => {
+ return require('./radiobutton.html');
+ };
+
+ public link = (scope:IRadiobuttonElementScope, $elem:ng.IAugmentedJQuery, $attrs:angular.IAttributes) => {
+ //$elem.removeAttr("id")
+ //console.log(scope.sdcChecklistValue);
+ };
+
+ public static factory = ($filter:ng.IFilterService)=> {
+ return new RadiobuttonElementDirective($filter);
+ };
+
+}
+
+RadiobuttonElementDirective.factory.$inject = ['$filter'];
diff --git a/catalog-ui/app/scripts/directives/ellipsis/ellipsis-directive.html b/catalog-ui/src/app/directives/ellipsis/ellipsis-directive.html
index 31fa06adda..31fa06adda 100644
--- a/catalog-ui/app/scripts/directives/ellipsis/ellipsis-directive.html
+++ b/catalog-ui/src/app/directives/ellipsis/ellipsis-directive.html
diff --git a/catalog-ui/app/scripts/directives/ellipsis/ellipsis-directive.less b/catalog-ui/src/app/directives/ellipsis/ellipsis-directive.less
index d8dfdbb73b..d8dfdbb73b 100644
--- a/catalog-ui/app/scripts/directives/ellipsis/ellipsis-directive.less
+++ b/catalog-ui/src/app/directives/ellipsis/ellipsis-directive.less
diff --git a/catalog-ui/src/app/directives/ellipsis/ellipsis-directive.ts b/catalog-ui/src/app/directives/ellipsis/ellipsis-directive.ts
new file mode 100644
index 0000000000..8fbbd4d486
--- /dev/null
+++ b/catalog-ui/src/app/directives/ellipsis/ellipsis-directive.ts
@@ -0,0 +1,57 @@
+'use strict';
+export interface IEllipsisScope extends ng.IScope {
+ ellipsis:string;
+ maxChars:number;
+ toggleText():void;
+ collapsed:boolean;
+ actualText:string;
+
+}
+
+export class EllipsisDirective implements ng.IDirective {
+
+ constructor() {
+ }
+
+ scope = {
+ ellipsis: '=',
+ moreClass: '@',
+ maxChars: '='
+ };
+
+ replace = false;
+ restrict = 'A';
+ template = ():string => {
+ return require('./ellipsis-directive.html');
+ };
+
+ link = (scope:IEllipsisScope, $elem:any) => {
+
+
+ scope.collapsed = true;
+
+ scope.toggleText = ():void => {
+ if (scope.ellipsis && scope.collapsed) {
+ scope.actualText = scope.ellipsis.substr(0, scope.maxChars);
+ scope.actualText += scope.ellipsis.length > scope.maxChars ? '...' : '';
+ }
+ else {
+ scope.actualText = scope.ellipsis;
+ }
+ };
+
+ scope.$watch("ellipsis", function () {
+ scope.collapsed = true;
+ scope.toggleText();
+ });
+
+
+ };
+
+ public static factory = ()=> {
+ return new EllipsisDirective();
+ };
+
+}
+
+EllipsisDirective.factory.$inject = [];
diff --git a/catalog-ui/src/app/directives/events/on-last-repeat/on-last-repeat.ts b/catalog-ui/src/app/directives/events/on-last-repeat/on-last-repeat.ts
new file mode 100644
index 0000000000..84014159f0
--- /dev/null
+++ b/catalog-ui/src/app/directives/events/on-last-repeat/on-last-repeat.ts
@@ -0,0 +1,40 @@
+'use strict';
+
+/**
+ * Usage:
+ * In data-ng-repeat html: <ol ng-repeat="record in records" on-last-repeat>
+ * In the controller, catch the last repeat:
+ * $scope.$on('onRepeatLast', function(scope, element, attrs){
+ * //work your magic
+ * });
+ */
+export interface IOnLastRepeatDirectiveScope extends ng.IScope {
+ $last:any;
+}
+
+export class OnLastRepeatDirective implements ng.IDirective {
+
+ constructor() {
+ }
+
+ scope = {};
+
+ restrict = 'AE';
+ replace = true;
+
+ link = (scope:IOnLastRepeatDirectiveScope, element:any, attrs:any) => {
+ let s:any = scope.$parent; // repeat scope
+ if (s.$last) {
+ setTimeout(function () {
+ s.$emit('onRepeatLast', element, attrs);
+ }, 1);
+ }
+ };
+
+ public static factory = ()=> {
+ return new OnLastRepeatDirective();
+ };
+
+}
+
+OnLastRepeatDirective.factory.$inject = [];
diff --git a/catalog-ui/src/app/directives/export-json-to-excel/export-json-to-excel.html b/catalog-ui/src/app/directives/export-json-to-excel/export-json-to-excel.html
new file mode 100644
index 0000000000..55696b33fa
--- /dev/null
+++ b/catalog-ui/src/app/directives/export-json-to-excel/export-json-to-excel.html
@@ -0,0 +1,7 @@
+<span data-ng-click="export()"
+ class="sprite-new download-btn hand"
+ uib-tooltip="Download"
+ tooltip-class="uib-custom-tooltip"
+ tooltip-placement="bottom"
+ data-tests-id="download-excel"></span>
+
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
new file mode 100644
index 0000000000..deb1c94936
--- /dev/null
+++ b/catalog-ui/src/app/directives/export-json-to-excel/export-json-to-excel.ts
@@ -0,0 +1,61 @@
+'use strict';
+import {FileUtils} from "app/utils";
+
+export interface IJsonExportExcelScope extends ng.IScope {
+ initExportExcelData:Function;
+ export:()=>void;
+}
+
+export class JsonExportExcelDirective implements ng.IDirective {
+
+ constructor(private fileUtils:FileUtils) {
+ }
+
+ scope = {
+ initExportExcelData: '&'//get function that init and returns Models.ExportExcel
+ };
+
+ public restrict = 'E';
+ replace = true;
+ template = ():string => {
+ return require('./export-json-to-excel.html');
+ };
+
+ private jsonToTableText = (headers:string, dataObj:Array<Object>):string=> {
+ let tableText = headers + "\n";
+ _.each(dataObj, (rowData:any) => {
+ tableText += _.values(rowData).join() + "\n";
+ });
+ return tableText;
+ };
+
+ link = (scope:IJsonExportExcelScope, $elem:any) => {
+ scope.export = ():void => {
+ let exportExcelData = scope.initExportExcelData();
+ exportExcelData.fileName = !!exportExcelData.fileName ? exportExcelData.fileName : 'export-excel';
+
+ let headers = exportExcelData.tableHeaders.join(",");
+ let tableData = "";
+ if (exportExcelData.groupByField) {
+ _.each(_.groupBy(exportExcelData.dataObj, exportExcelData.groupByField), (groupData:Array<Object>) => {
+ tableData += this.jsonToTableText(headers, groupData);
+ tableData += '\n';
+ });
+ } else {
+ tableData = this.jsonToTableText(headers, exportExcelData.dataObj);
+ }
+
+ let blob = new Blob([exportExcelData.metaData.join('\n\n') + '\n\n' + tableData], {type: "text/csv;charset=utf-8"});
+
+ return this.fileUtils.downloadFile(blob, exportExcelData.fileName + '.csv');
+ };
+
+ };
+
+ public static factory = (fileUtils:FileUtils)=> {
+ return new JsonExportExcelDirective( fileUtils);
+ };
+
+}
+
+JsonExportExcelDirective.factory.$inject = ['FileUtils'];
diff --git a/catalog-ui/app/scripts/directives/file-opener/file-opener.html b/catalog-ui/src/app/directives/file-opener/file-opener.html
index 38f82554e9..38f82554e9 100644
--- a/catalog-ui/app/scripts/directives/file-opener/file-opener.html
+++ b/catalog-ui/src/app/directives/file-opener/file-opener.html
diff --git a/catalog-ui/src/app/directives/file-opener/file-opener.ts b/catalog-ui/src/app/directives/file-opener/file-opener.ts
new file mode 100644
index 0000000000..95e43262f5
--- /dev/null
+++ b/catalog-ui/src/app/directives/file-opener/file-opener.ts
@@ -0,0 +1,54 @@
+'use strict';
+
+export interface IFileOpenerScope extends ng.IScope {
+ importFile:any;
+ testsId:any;
+ extensions:string;
+
+ onFileSelect():void;
+ onFileUpload(file:any):void;
+ getExtensionsWithDot():string;
+}
+
+export class FileOpenerDirective implements ng.IDirective {
+
+ constructor(private $compile:ng.ICompileService) {
+ }
+
+ scope = {
+ onFileUpload: '&',
+ testsId: '@',
+ extensions: '@'
+ };
+
+ restrict = 'AE';
+ replace = true;
+ template = ():string => {
+ return require('./file-opener.html');
+ };
+
+ link = (scope:IFileOpenerScope, element:any) => {
+
+ scope.onFileSelect = () => {
+ scope.onFileUpload({file: scope.importFile});
+ element.html('app/directives/file-opener/file-opener.html');
+ this.$compile(element.contents())(scope);
+ };
+
+ scope.getExtensionsWithDot = ():string => {
+ let ret = [];
+ _.each(scope.extensions.split(','), function (item) {
+ ret.push("." + item.toString());
+ });
+ return ret.join(",");
+ };
+
+ };
+
+ public static factory = ($compile:ng.ICompileService)=> {
+ return new FileOpenerDirective($compile);
+ };
+
+}
+
+FileOpenerDirective.factory.$inject = ['$compile'];
diff --git a/catalog-ui/src/app/directives/file-type/file-type.ts b/catalog-ui/src/app/directives/file-type/file-type.ts
new file mode 100644
index 0000000000..11795724d0
--- /dev/null
+++ b/catalog-ui/src/app/directives/file-type/file-type.ts
@@ -0,0 +1,45 @@
+'use strict';
+
+export class FileTypeDirective implements ng.IDirective {
+
+ constructor() {
+ }
+
+ require = 'ngModel';
+
+ link = (scope, elem, attrs, ngModel) => {
+
+ let typesToApprove = "";
+
+ attrs.$observe('fileType', (val:string) => {
+ typesToApprove = val;
+ validate(ngModel.$viewValue);
+ });
+
+ let validate:Function = function (value) {
+ let fileName:string = elem.val(), valid:boolean = true;
+
+ if (fileName && value && typesToApprove) {
+ let extension:string = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase();
+ valid = typesToApprove.split(',').indexOf(extension) > -1;
+ }
+
+ ngModel.$setValidity('filetype', valid);
+ if (!value) {
+ ngModel.$setPristine();
+ }
+ return value;
+ };
+
+ //For DOM -> model validation
+ ngModel.$parsers.unshift(validate);
+
+ };
+
+ public static factory = ()=> {
+ return new FileTypeDirective();
+ };
+
+}
+
+FileTypeDirective.factory.$inject = [];
diff --git a/catalog-ui/app/scripts/directives/file-upload/file-upload.html b/catalog-ui/src/app/directives/file-upload/file-upload.html
index 7cbc8d25f3..a69340d0ba 100644
--- a/catalog-ui/app/scripts/directives/file-upload/file-upload.html
+++ b/catalog-ui/src/app/directives/file-upload/file-upload.html
@@ -12,6 +12,7 @@
data-ng-change="onFileChange()"
onchange="angular.element(this).scope().setEmptyError(this)"
onclick="angular.element(this).scope().onFileClick(this)"
+ on-after-validate="onAfterValidate"
data-ng-required="{{elementRequired}}"
data-ng-disabled="elementDisabled==='true'"
data-tests-id="browseButton"
diff --git a/catalog-ui/app/scripts/directives/file-upload/file-upload.less b/catalog-ui/src/app/directives/file-upload/file-upload.less
index 1c4b010853..1c4b010853 100644
--- a/catalog-ui/app/scripts/directives/file-upload/file-upload.less
+++ b/catalog-ui/src/app/directives/file-upload/file-upload.less
diff --git a/catalog-ui/src/app/directives/file-upload/file-upload.ts b/catalog-ui/src/app/directives/file-upload/file-upload.ts
new file mode 100644
index 0000000000..63a6f08062
--- /dev/null
+++ b/catalog-ui/src/app/directives/file-upload/file-upload.ts
@@ -0,0 +1,130 @@
+/**
+ * Created by obarda on 1/27/2016.
+ */
+'use strict';
+import {IAppConfigurtaion} from "app/models";
+
+export class FileUploadModel {
+ filetype:string;
+ filename:string;
+ filesize:number;
+ base64:string;
+}
+
+export interface IFileUploadScope extends ng.IScope {
+ fileModel:FileUploadModel;
+ formElement:ng.IFormController;
+ extensions:string;
+ elementDisabled:string;
+ elementName:string;
+ elementRequired:string;
+ myFileModel:any; // From the ng bind to <input type=file
+ defaultText:string;
+ onFileChangedInDirective:Function;
+
+ getExtensionsWithDot():string;
+ onFileChange():void
+ onFileClick(element:any):void;
+ onAfterValidate():void;
+ setEmptyError(element):void;
+ validateField(field:any):boolean;
+ cancel():void;
+}
+
+
+export class FileUploadDirective implements ng.IDirective {
+
+ constructor(private sdcConfig:IAppConfigurtaion) {
+ }
+
+ scope = {
+ fileModel: '=',
+ formElement: '=',
+ extensions: '@',
+ elementDisabled: '@',
+ elementName: '@',
+ elementRequired: '@',
+ onFileChangedInDirective: '=?',
+ defaultText: '=',
+ };
+
+ restrict = 'E';
+ replace = true;
+ template = ():string => {
+ return require('./file-upload.html');
+ };
+
+ link = (scope:IFileUploadScope, element:any, $attr:any) => {
+
+ // In case the browse has filename, set it valid.
+ // When editing artifact the file is not sent again, so if we have filename I do not want to show error.
+ if (scope.fileModel && scope.fileModel.filename && scope.fileModel.filename !== '') {
+ scope.formElement[scope.elementName].$setValidity('required', true);
+ }
+
+ scope.getExtensionsWithDot = ():string => {
+ let ret = [];
+ if (scope.extensions) {
+ _.each(scope.extensions.split(','), function (item) {
+ ret.push("." + item.toString());
+ });
+ }
+ return ret.join(",");
+ };
+
+ scope.onFileChange = ():void => {
+ if (scope.onFileChangedInDirective) {
+ scope.onFileChangedInDirective();
+ }
+ if (scope.myFileModel) {
+ scope.fileModel = scope.myFileModel;
+ scope.formElement[scope.elementName].$setValidity('required', true);
+ }
+ };
+
+ scope.setEmptyError = (element):void => {
+ if (element.files[0].size) {
+ scope.formElement[scope.elementName].$setValidity('emptyFile', true);
+ } else {
+ scope.formElement[scope.elementName].$setValidity('emptyFile', false);
+ scope.fileModel = undefined;
+ }
+
+ };
+
+ // Prevent case-sensitivity in the upload-file accept parameter
+ // Workaround for github issue: https://github.com/adonespitogo/angular-base64-upload/issues/81
+ scope.onAfterValidate = () => {
+ if (!scope.formElement[scope.elementName].$valid && scope.extensions) {
+ let uploadfileExtension:string = scope.fileModel.filename.split('.').pop().toLowerCase();
+ if (scope.extensions.split(',').indexOf(uploadfileExtension) > -1) {
+ scope.formElement[scope.elementName].$setValidity('accept', true);
+ }
+ }
+ // Adding fix for cases when we're changing file type for upload from file that requires certain
+ // extensions to a file that don't requires any extensions
+ if (!scope.formElement[scope.elementName].$valid && scope.formElement[scope.elementName].$error.accept && scope.extensions === "") {
+ scope.formElement[scope.elementName].$setValidity('accept', true);
+ }
+ };
+
+ // Workaround, in case user select a file then cancel (X) then select the file again, the event onChange is not fired.
+ // This is a workaround to fix this issue.
+ scope.onFileClick = (element:any):void => {
+ element.value = null;
+ };
+
+ scope.cancel = ():void => {
+ scope.fileModel.filename = '';
+ scope.formElement[scope.elementName].$pristine;
+ scope.formElement[scope.elementName].$setValidity('required', false);
+ }
+ };
+
+ public static factory = (sdcConfig:IAppConfigurtaion)=> {
+ return new FileUploadDirective(sdcConfig);
+ };
+
+}
+
+FileUploadDirective.factory.$inject = [ 'sdcConfig'];
diff --git a/catalog-ui/src/app/directives/graphs-v2/asset-popover/asset-popover.html b/catalog-ui/src/app/directives/graphs-v2/asset-popover/asset-popover.html
new file mode 100644
index 0000000000..659ff7014f
--- /dev/null
+++ b/catalog-ui/src/app/directives/graphs-v2/asset-popover/asset-popover.html
@@ -0,0 +1,11 @@
+<div class="assetPopover" ng-class="assetPopoverObj.menuSide" ng-style="{left: assetPopoverObj.menuPosition.x, top: assetPopoverObj.menuPosition.y}">
+ <div class="display-name-tooltip" >{{assetPopoverObj.displayName}}</div>
+
+ <div class="assetMenu">
+ <!--<div class="sprite-new expand-asset-icon" uib-tooltip="Open" tooltip-class="uib-custom-tooltip" tooltip-placement="{{tooltipSide}}"></div>-->
+ <div class="sprite-new view-info-icon" uib-tooltip="Information" tooltip-class="uib-custom-tooltip" tooltip-placement="{{assetPopoverObj.menuSide}}"></div>
+ <div class="sprite-new cp-icon" uib-tooltip="Connection Points" tooltip-class="uib-custom-tooltip" tooltip-placement="{{assetPopoverObj.menuSide}}"></div>
+ <div class="sprite-new vl-icon" uib-tooltip="Links" tooltip-class="uib-custom-tooltip" tooltip-placement="{{assetPopoverObj.menuSide}}"></div>
+ <div class="sprite-new trash-icon" uib-tooltip="Delete" tooltip-class="uib-custom-tooltip" tooltip-placement="{{assetPopoverObj.menuSide}}" ng-click="deleteAsset()" data-ng-class="{'disabled-icon': assetPopoverObj.isViewOnly}"></div>
+ </div>
+</div>
diff --git a/catalog-ui/src/app/directives/graphs-v2/asset-popover/asset-popover.less b/catalog-ui/src/app/directives/graphs-v2/asset-popover/asset-popover.less
new file mode 100644
index 0000000000..44de4dfed1
--- /dev/null
+++ b/catalog-ui/src/app/directives/graphs-v2/asset-popover/asset-popover.less
@@ -0,0 +1,64 @@
+.assetPopover {
+ font-family: omnes-regular,sans-serif;
+ font-size: 13px;
+ width:230px;
+ padding:0 15px;
+ position:absolute;
+ display:flex;
+ flex-direction:column;
+ align-items:flex-start;
+
+ &.left {
+ align-items:flex-end;
+
+ .uib-custom-tooltip {
+ margin-left:-10px;
+ }
+ }
+
+ .display-name-tooltip {
+
+ border:solid 1px @main_color_p;
+ color: @main_color_p;
+ padding:5px 10px;
+ width:200px;
+ margin-bottom:10px;
+ border-radius: 2px;
+ background-color: rgba(80, 99, 113, 0.8);
+ box-shadow: 0px 3px 7.44px 0.56px rgba(0, 0, 0, 0.33);
+ }
+
+ .uib-custom-tooltip {
+ margin-left:20px;
+ font-family: omnes-regular,sans-serif;
+ font-size: 13px;
+ }
+
+ .assetMenu {
+
+ border-radius: 2px;
+ border: solid 1px @main_color_p;
+ background-color: rgba(234, 234, 234, 0.7);
+ box-shadow: 0px 3px 7.44px 0.56px rgba(0, 0, 0, 0.33);
+ display:flex;
+ flex-direction: column;
+ justify-content: center;
+ align-items:center;
+
+ .sprite-new {
+ border-bottom:solid 1px #CCC;
+ &:hover:not(.disabled-icon) {
+ .hand;
+ }
+ &:active:not(.disabled-icon) {
+ background-color: @main_color_a;
+ border-bottom-color: @main_color_a;
+ }
+ &.trash-icon {
+ border-bottom: none;
+ }
+ }
+
+
+ }
+}
diff --git a/catalog-ui/app/scripts/filters/resource-name-filter.ts b/catalog-ui/src/app/directives/graphs-v2/asset-popover/asset-popover.ts
index a1f6162a4c..c560161d6e 100644
--- a/catalog-ui/app/scripts/filters/resource-name-filter.ts
+++ b/catalog-ui/src/app/directives/graphs-v2/asset-popover/asset-popover.ts
@@ -17,29 +17,39 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-/// <reference path="../references"/>
-module Sdc.Filters {
- export class ResourceNameFilter{
+'use strict';
+import {AssetPopoverObj} from "app/models";
+export interface IAssetPopoverScope extends ng.IScope {
+ assetPopoverObj:AssetPopoverObj;
+ deleteAsset:Function;
+}
+
+export class AssetPopoverDirective implements ng.IDirective {
constructor() {
- let filter = <ResourceNameFilter>( (name:string) => {
- if(name){
- //let newName:string = _.last(name.split('.'));
- let newName =
- _.last(_.last(_.last(_.last(_.last(_.last(_.last(_.last(name.split('tosca.nodes.'))
- .split('network.')).split('relationships.')).split('org.openecomp.')).split('resource.nfv.'))
- .split('nodes.module.')).split('cp.')).split('vl.'));
- if (newName){
- return newName;
- }
- return name;
- }
- });
-
- return filter;
}
- }
+ scope = {
+ assetPopoverObj: '=',
+ deleteAsset: '&'
+ };
+
+ restrict = 'E';
+ replace = true;
+ template = ():string => {
+ return require('app/directives/graphs-v2/asset-popover/asset-popover.html');
+ };
+
+ link = (scope:IAssetPopoverScope, element:JQuery, $attr:ng.IAttributes) => {
+
+ };
+
+ public static factory = ()=> {
+ return new AssetPopoverDirective();
+ };
}
+
+AssetPopoverDirective.factory.$inject = [];
+
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
new file mode 100644
index 0000000000..0b02173e9a
--- /dev/null
+++ b/catalog-ui/src/app/directives/graphs-v2/common/common-graph-utils.ts
@@ -0,0 +1,372 @@
+import {CommonNodeBase, CompositionCiLinkBase, RelationshipModel, Relationship, CompositionCiNodeBase, NodesFactory, LinksFactory} from "app/models";
+import {GraphUIObjects} from "app/utils";
+/**
+ * Created by obarda on 12/21/2016.
+ */
+export class CommonGraphUtils {
+
+ constructor(private NodesFactory:NodesFactory, private LinksFactory:LinksFactory) {
+
+ }
+
+ public safeApply = (scope:ng.IScope, fn:any) => { //todo remove to general utils
+ let phase = scope.$root.$$phase;
+ if (phase == '$apply' || phase == '$digest') {
+ if (fn && (typeof(fn) === 'function')) {
+ fn();
+ }
+ } else {
+ scope.$apply(fn);
+ }
+ };
+
+ /**
+ * Draw node on the graph
+ * @param cy
+ * @param compositionGraphNode
+ * @param position
+ * @returns {CollectionElements}
+ */
+ public addNodeToGraph(cy:Cy.Instance, compositionGraphNode:CommonNodeBase, position?:Cy.Position):Cy.CollectionElements {
+
+ let node = cy.add(<Cy.ElementDefinition> {
+ group: 'nodes',
+ position: position,
+ data: compositionGraphNode,
+ classes: compositionGraphNode.classes
+ });
+
+ 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.
+ * If the node is UCPE the function will create all cp lan&wan for the ucpe
+ * @param cy
+ * @param compositionGraphNode
+ * @returns {Cy.CollectionElements}
+ */
+ public addComponentInstanceNodeToGraph(cy:Cy.Instance, compositionGraphNode:CompositionCiNodeBase):Cy.CollectionElements {
+
+ let nodePosition = {
+ x: +compositionGraphNode.componentInstance.posX,
+ y: +compositionGraphNode.componentInstance.posY
+ };
+
+ let node = this.addNodeToGraph(cy, compositionGraphNode, nodePosition);
+ if (compositionGraphNode.isUcpe) {
+ this.createUcpeCpNodes(cy, node);
+ }
+ return node;
+ };
+
+ /**
+ * This function will create CP_WAN & CP_LAN for the UCPE. this is a special node on the group that will behave like ports on the ucpe
+ * @param cy
+ * @param ucpeGraphNode
+ */
+ private createUcpeCpNodes(cy:Cy.Instance, ucpeGraphNode:Cy.CollectionNodes):void {
+
+ let requirementsArray:Array<any> = ucpeGraphNode.data().componentInstance.requirements["tosca.capabilities.Node"];
+ //show only LAN or WAN requirements
+ requirementsArray = _.reject(requirementsArray, (requirement:any) => {
+ let name:string = requirement.ownerName.toLowerCase();
+ return name.indexOf('lan') === -1 && name.indexOf('wan') === -1;
+ });
+ requirementsArray.sort(function (a, b) {
+ let nameA = a.ownerName.toLowerCase().match(/[^ ]+/)[0];
+ let nameB = b.ownerName.toLowerCase().match(/[^ ]+/)[0];
+ let numA = _.last(a.ownerName.toLowerCase().split(' '));
+ let numB = _.last(b.ownerName.toLowerCase().split(' '));
+
+ if (nameA === nameB) return numA > numB ? 1 : -1;
+ return nameA < nameB ? 1 : -1;
+ });
+ let position = angular.copy(ucpeGraphNode.boundingbox());
+ //add CP nodes to group
+ let topCps:number = 0;
+ for (let i = 0; i < requirementsArray.length; i++) {
+
+ let cpNode = this.NodesFactory.createUcpeCpNode(angular.copy(ucpeGraphNode.data().componentInstance));
+ cpNode.componentInstance.capabilities = requirementsArray[i];
+ cpNode.id = requirementsArray[i].ownerId;
+ cpNode.group = ucpeGraphNode.data().componentInstance.uniqueId;
+ cpNode.name = requirementsArray[i].ownerName; //for tooltip
+ cpNode.displayName = requirementsArray[i].ownerName;
+ cpNode.displayName = cpNode.displayName.length > 5 ? cpNode.displayName.substring(0, 5) + '...' : cpNode.displayName;
+
+
+ if (cpNode.name.toLowerCase().indexOf('lan') > -1) {
+ cpNode.textPosition = "top";
+ cpNode.componentInstance.posX = position.x1 + (i * 90) - (topCps * 90) + 53;
+ cpNode.componentInstance.posY = position.y1 + 400 + 27;
+ } else {
+ cpNode.textPosition = "bottom";
+ cpNode.componentInstance.posX = position.x1 + (topCps * 90) + 53;
+ cpNode.componentInstance.posY = position.y1 + 27;
+ topCps++;
+ }
+ let cyCpNode = this.addComponentInstanceNodeToGraph(cy, cpNode);
+ cyCpNode.lock();
+ }
+ };
+
+ /**
+ *
+ * @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)
+ */
+ 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;
+ }
+
+ /**
+ * Add link to graph - only draw the link
+ * @param cy
+ * @param link
+ */
+ public insertLinkToGraph = (cy:Cy.Instance, link:CompositionCiLinkBase) => {
+
+ if (!this.isRelationCertified(cy.nodes(), link.source, link.target)) {
+ link.classes = 'not-certified-link';
+ }
+ cy.add({
+ group: 'edges',
+ data: link,
+ classes: link.classes
+ });
+
+ };
+
+ /**
+ * go over the relations and draw links on the graph
+ * @param cy
+ * @param instancesRelations
+ */
+ public initGraphLinks(cy:Cy.Instance, instancesRelations:Array<RelationshipModel>) {
+
+ if (instancesRelations) {
+ _.forEach(instancesRelations, (relationshipModel:RelationshipModel) => {
+ _.forEach(relationshipModel.relationships, (relationship:Relationship) => {
+ let linkToCreate = this.LinksFactory.createGraphLink(cy, relationshipModel, relationship);
+ this.insertLinkToGraph(cy, linkToCreate);
+ });
+ });
+ }
+ }
+
+ /**
+ * Determine which nodes are in the UCPE and set child data for them.
+ * @param cy
+ */
+ public initUcpeChildren(cy:Cy.Instance) {
+ let ucpe:Cy.CollectionNodes = cy.nodes('[?isUcpe]'); // Get ucpe on graph if exist
+ _.each(cy.edges('.ucpe-host-link'), (link)=> {
+
+ let ucpeChild:Cy.CollectionNodes = (link.source().id() == ucpe.id()) ? link.target() : link.source();
+ this.initUcpeChildData(ucpeChild, ucpe);
+
+ //vls dont have ucpe-host-link connection, so need to find them and iterate separately
+ let connectedVLs = ucpeChild.connectedEdges().connectedNodes('.vl-node');
+ _.forEach(connectedVLs, (vl)=> { //all connected vls must be UCPE children because not allowed to connect to a VL outside of the UCPE
+ this.initUcpeChildData(vl, ucpe);
+ });
+ });
+ }
+
+ /**
+ * Set properties for nodes contained by the UCPE
+ * @param childNode- node contained in UCPE
+ * @param ucpe- ucpe container node
+ */
+ public initUcpeChildData(childNode:Cy.CollectionNodes, ucpe:Cy.CollectionNodes) {
+
+ if (!childNode.data('isInsideGroup')) {
+ this.updateUcpeChildPosition(childNode, ucpe);
+ childNode.data({isInsideGroup: true});
+ }
+
+ }
+
+ /**
+ * Updates UCPE child node offset, which allows child nodes to be dragged in synchronization with ucpe
+ * @param childNode- node contained in UCPE
+ * @param ucpe- ucpe container node
+ */
+ public updateUcpeChildPosition(childNode:Cy.CollectionNodes, ucpe:Cy.CollectionNodes) {
+ let childPos:Cy.Position = childNode.relativePosition();
+ let ucpePos:Cy.Position = ucpe.relativePosition();
+ let offset:Cy.Position = {
+ x: childPos.x - ucpePos.x,
+ y: childPos.y - ucpePos.y
+ };
+ childNode.data("ucpeOffset", offset);
+ }
+
+ /**
+ * Removes ucpe-child properties from the node
+ * @param childNode- node being removed from UCPE
+ */
+ public removeUcpeChildData(childNode:Cy.CollectionNodes) {
+ childNode.removeData("ucpeOffset");
+ childNode.data({isInsideGroup: false});
+
+ }
+
+
+ public HTMLCoordsToCytoscapeCoords(cytoscapeBoundingBox:Cy.Extent, mousePos:Cy.Position):Cy.Position {
+ return {x: mousePos.x + cytoscapeBoundingBox.x1, y: mousePos.y + cytoscapeBoundingBox.y1}
+ };
+
+
+ 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;
+
+ return this.HTMLCoordsToCytoscapeCoords(cy.extent(), {
+ x: x,
+ y: y
+ });
+ };
+
+
+ public getNodePosition(node:Cy.CollectionFirstNode):Cy.Position {
+ let nodePosition = node.relativePoint();
+ if (node.data().isUcpe) { //UCPEs use bounding box and not relative point.
+ nodePosition = {x: node.boundingbox().x1, y: node.boundingbox().y1};
+ }
+
+ 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 => {
+ if(!additionalOffset) additionalOffset = {x: 0, y:0};
+
+ let nodePosition = node.renderedPosition();
+ let posWithOffset:Cy.Position = {
+ x: nodePosition.x + GraphUIObjects.DIAGRAM_PALETTE_WIDTH_OFFSET + additionalOffset.x,
+ y: nodePosition.y + GraphUIObjects.COMPOSITION_HEADER_OFFSET + additionalOffset.y
+ };
+ 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 firstBox.x1 > secondBox.x1 && firstBox.x2 < secondBox.x2 && firstBox.y1 > secondBox.y1 && firstBox.y2 < secondBox.y2;
+
+ };
+
+
+ /**
+ * Check if node node bounds position is inside any ucpe on graph, and return the ucpe
+ * @param {diagram} the diagram.
+ * @param {nodeActualBounds} the actual bound position of the node.
+ * @return the ucpe if found else return null
+ */
+ public isInUcpe = (cy:Cy.Instance, nodeBounds:Cy.BoundingBox):Cy.CollectionElements => {
+
+ let ucpeNodes = cy.nodes('[?isUcpe]').filterFn((ucpeNode) => {
+ return this.isFirstBoxContainsInSecondBox(nodeBounds, ucpeNode.boundingbox());
+ });
+ return ucpeNodes;
+ };
+
+ /**
+ *
+ * @param cy
+ * @param node
+ * @returns {Array}
+ */
+ public getLinkableNodes(cy:Cy.Instance, node:Cy.CollectionFirstNode):Array<CompositionCiNodeBase> {
+ let compatibleNodes = [];
+ _.each(cy.nodes(), (tempNode)=> {
+ if (this.nodeLocationsCompatible(cy, node, tempNode)) {
+ compatibleNodes.push(tempNode.data());
+ }
+ });
+ return compatibleNodes;
+ }
+
+ /**
+ * Checks whether node locations are compatible in reference to UCPEs.
+ * Returns true if both nodes are in UCPE or both nodes out, or one node is UCPEpart.
+ * @param node1
+ * @param node2
+ */
+ 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; }
+
+ 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);
+ };
+}
+
+CommonGraphUtils.$inject = ['NodesFactory', 'LinksFactory']; \ No newline at end of file
diff --git a/catalog-ui/app/scripts/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 2ec0174aa9..971dabafe8 100644
--- a/catalog-ui/app/scripts/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
@@ -1,13 +1,10 @@
+import {GraphColors} from "app/utils/constants";
/**
* Created by obarda on 12/18/2016.
*/
-/**
- * Created by obarda on 12/13/2016.
- */
-/// <reference path="../../../../references"/>
-module Sdc.Graph.Utils.ComponentIntanceNodesStyle {
+export class ComponentInstanceNodesStyle {
- export function getCompositionGraphStyle():Array<Cy.Stylesheet> {
+ public static getCompositionGraphStyle = ():Array<Cy.Stylesheet> => {
return [
{
selector: 'core',
@@ -29,7 +26,7 @@ module Sdc.Graph.Utils.ComponentIntanceNodesStyle {
'events': 'yes',
'text-events': 'yes',
'text-border-width': 15,
- 'text-border-color': Sdc.Utils.Constants.GraphColors.NODE_UCPE,
+ 'text-border-color': GraphColors.NODE_UCPE,
'text-margin-y': 5
}
},
@@ -49,7 +46,7 @@ module Sdc.Graph.Utils.ComponentIntanceNodesStyle {
'text-halign': 'center',
'background-fit': 'cover',
'background-clip': 'node',
- 'overlay-color': Sdc.Utils.Constants.GraphColors.NODE_BACKGROUND_COLOR,
+ 'overlay-color': GraphColors.NODE_BACKGROUND_COLOR,
'overlay-opacity': 0
}
},
@@ -68,7 +65,7 @@ module Sdc.Graph.Utils.ComponentIntanceNodesStyle {
'text-valign': 'bottom',
'text-halign': 'center',
'background-opacity': 0,
- 'overlay-color': Sdc.Utils.Constants.GraphColors.NODE_BACKGROUND_COLOR,
+ 'overlay-color': GraphColors.NODE_BACKGROUND_COLOR,
'overlay-opacity': 0
}
},
@@ -86,7 +83,7 @@ module Sdc.Graph.Utils.ComponentIntanceNodesStyle {
'text-valign': 'bottom',
'text-halign': 'center',
'background-opacity': 0,
- 'overlay-color': Sdc.Utils.Constants.GraphColors.NODE_BACKGROUND_COLOR,
+ 'overlay-color': GraphColors.NODE_BACKGROUND_COLOR,
'overlay-opacity': 0
}
},
@@ -104,14 +101,14 @@ module Sdc.Graph.Utils.ComponentIntanceNodesStyle {
'text-valign': 'bottom',
'text-halign': 'center',
'background-opacity': 0,
- 'overlay-color': Sdc.Utils.Constants.GraphColors.NODE_BACKGROUND_COLOR,
+ 'overlay-color': GraphColors.NODE_BACKGROUND_COLOR,
'overlay-opacity': 0
}
},
{
selector: '.ucpe-cp',
css: {
- 'background-color': Sdc.Utils.Constants.GraphColors.NODE_UCPE_CP,
+ 'background-color': GraphColors.NODE_UCPE_CP,
'background-width': 15,
'background-height': 15,
'width': 15,
@@ -121,7 +118,7 @@ module Sdc.Graph.Utils.ComponentIntanceNodesStyle {
'label': 'data(displayName)',
'text-valign': 'data(textPosition)',
'text-margin-y': (ele:Cy.Collection) => {
- return (ele.data('textPosition') == 'top')? -5 : 5;
+ return (ele.data('textPosition') == 'top') ? -5 : 5;
},
'font-size': 12
}
@@ -138,7 +135,7 @@ module Sdc.Graph.Utils.ComponentIntanceNodesStyle {
selector: '.simple-link',
css: {
'width': 1,
- 'line-color': Sdc.Utils.Constants.GraphColors.BASE_LINK,
+ 'line-color': GraphColors.BASE_LINK,
'target-arrow-color': '#3b7b9b',
'target-arrow-shape': 'triangle',
'curve-style': 'bezier',
@@ -149,7 +146,7 @@ module Sdc.Graph.Utils.ComponentIntanceNodesStyle {
selector: '.vl-link',
css: {
'width': 3,
- 'line-color': Sdc.Utils.Constants.GraphColors.VL_LINK,
+ 'line-color': GraphColors.VL_LINK,
'curve-style': 'bezier',
'control-point-step-size': 30
}
@@ -164,7 +161,7 @@ module Sdc.Graph.Utils.ComponentIntanceNodesStyle {
selector: '.not-certified-link',
css: {
'width': 1,
- 'line-color': Sdc.Utils.Constants.GraphColors.NOT_CERTIFIED_LINK,
+ 'line-color': GraphColors.NOT_CERTIFIED_LINK,
'curve-style': 'bezier',
'control-point-step-size': 30,
'line-style': 'dashed',
@@ -182,20 +179,20 @@ module Sdc.Graph.Utils.ComponentIntanceNodesStyle {
return ele.data().initImage(ele)
},
"border-width": 0
- }
+ }
},
{
selector: 'node:selected',
css: {
"border-width": 2,
- "border-color": Sdc.Utils.Constants.GraphColors.NODE_SELECTED_BORDER_COLOR,
+ "border-color": GraphColors.NODE_SELECTED_BORDER_COLOR,
'shape': 'rectangle'
}
},
{
selector: 'edge:selected',
css: {
- 'line-color': Sdc.Utils.Constants.GraphColors.ACTIVE_LINK
+ 'line-color': GraphColors.ACTIVE_LINK
}
},
@@ -208,7 +205,7 @@ module Sdc.Graph.Utils.ComponentIntanceNodesStyle {
]
}
- export function getBasicNodeHanlde() {
+ public static getBasicNodeHanlde = () => {
return {
positionX: "center",
positionY: "top",
@@ -218,14 +215,14 @@ module Sdc.Graph.Utils.ComponentIntanceNodesStyle {
type: "default",
single: false,
nodeTypeNames: ["basic-node"],
- imageUrl: Sdc.Utils.Constants.IMAGE_PATH + '/styles/images/resource-icons/' + 'canvasPlusIcon.png',
+ imageUrl: '/assets/styles/images/resource-icons/' + 'canvasPlusIcon.png',
lineWidth: 2,
lineStyle: 'dashed'
}
}
- export function getBasicSmallNodeHandle() {
+ public static getBasicSmallNodeHandle = () => {
return {
positionX: "center",
positionY: "top",
@@ -235,13 +232,13 @@ module Sdc.Graph.Utils.ComponentIntanceNodesStyle {
type: "default",
single: false,
nodeTypeNames: ["basic-small-node"],
- imageUrl: Sdc.Utils.Constants.IMAGE_PATH + '/styles/images/resource-icons/' + 'canvasPlusIcon.png',
+ imageUrl: '/assets/styles/images/resource-icons/' + 'canvasPlusIcon.png',
lineWidth: 2,
lineStyle: 'dashed'
}
}
- export function getUcpeCpNodeHandle() {
+ public static getUcpeCpNodeHandle = () => {
return {
positionX: "center",
positionY: "center",
@@ -251,9 +248,9 @@ module Sdc.Graph.Utils.ComponentIntanceNodesStyle {
type: "default",
single: false,
nodeTypeNames: ["ucpe-cp-node"],
- imageUrl: Sdc.Utils.Constants.IMAGE_PATH + '/styles/images/resource-icons/' + 'canvasPlusIcon.png',
+ imageUrl: '/assets/styles/images/resource-icons/' + 'canvasPlusIcon.png',
lineWidth: 2,
lineStyle: 'dashed'
}
}
-} \ No newline at end of file
+}
diff --git a/catalog-ui/app/scripts/directives/graphs-v2/common/style/module-node-style.ts b/catalog-ui/src/app/directives/graphs-v2/common/style/module-node-style.ts
index 62436fbf74..0c92c90538 100644
--- a/catalog-ui/app/scripts/directives/graphs-v2/common/style/module-node-style.ts
+++ b/catalog-ui/src/app/directives/graphs-v2/common/style/module-node-style.ts
@@ -1,16 +1,7 @@
-/**
- * Created by obarda on 1/1/2017.
- */
-/**
- * Created by obarda on 12/18/2016.
- */
-/**
- * Created by obarda on 12/13/2016.
- */
-/// <reference path="../../../../references"/>
-module Sdc.Graph.Utils.ModulesNodesStyle {
+import {GraphColors} from "app/utils";
+export class ModulesNodesStyle {
- export function getModuleGraphStyle():Array<Cy.Stylesheet> {
+ public static getModuleGraphStyle = ():Array<Cy.Stylesheet> => {
return [
{
@@ -36,7 +27,7 @@ module Sdc.Graph.Utils.ModulesNodesStyle {
'background-color': 'transparent',
'background-opacity': 0,
"border-width": 2,
- "border-color": Sdc.Utils.Constants.GraphColors.NODE_SELECTED_BORDER_COLOR,
+ "border-color": GraphColors.NODE_SELECTED_BORDER_COLOR,
'border-style': 'dashed',
'label': 'data(displayName)',
'events': 'yes',
@@ -55,19 +46,19 @@ module Sdc.Graph.Utils.ModulesNodesStyle {
{
selector: '.simple-link:selected',
css: {
- 'line-color': Sdc.Utils.Constants.GraphColors.BASE_LINK,
+ 'line-color': GraphColors.BASE_LINK,
}
},
{
selector: '.vl-link:selected',
css: {
- 'line-color': Sdc.Utils.Constants.GraphColors.VL_LINK,
+ 'line-color': GraphColors.VL_LINK,
}
},
{
selector: '.cy-expand-collapse-collapsed-node:selected',
css: {
- "border-color": Sdc.Utils.Constants.GraphColors.NODE_SELECTED_BORDER_COLOR,
+ "border-color": GraphColors.NODE_SELECTED_BORDER_COLOR,
'border-opacity': 1,
'border-style': 'solid',
'border-width': 2
@@ -76,7 +67,7 @@ module Sdc.Graph.Utils.ModulesNodesStyle {
{
selector: '.module-node:selected',
css: {
- "border-color": Sdc.Utils.Constants.GraphColors.NODE_SELECTED_BORDER_COLOR,
+ "border-color": GraphColors.NODE_SELECTED_BORDER_COLOR,
'border-opacity': 1
}
},
@@ -89,4 +80,4 @@ module Sdc.Graph.Utils.ModulesNodesStyle {
},
]
}
-} \ No newline at end of file
+}
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
new file mode 100644
index 0000000000..db03aa53fb
--- /dev/null
+++ b/catalog-ui/src/app/directives/graphs-v2/composition-graph/composition-graph.directive.ts
@@ -0,0 +1,539 @@
+import {
+ MatchBase,
+ LinkMenu,
+ ComponentInstance,
+ LeftPaletteComponent,
+ Component,
+ RelationMenuDirectiveObj,
+ CompositionCiNodeBase,
+ CompositionCiNodeVl,
+ NodesFactory/*,
+ AssetPopoverObj*/
+} from "app/models";
+import {ComponentInstanceFactory, ComponentFactory, GRAPH_EVENTS, GraphColors} from "app/utils";
+import {EventListenerService, LoaderService} from "app/services";
+import {CompositionGraphLinkUtils} from "./utils/composition-graph-links-utils";
+import {CompositionGraphGeneralUtils} from "./utils/composition-graph-general-utils";
+import {CompositionGraphNodesUtils} from "./utils/composition-graph-nodes-utils";
+import {CommonGraphUtils} from "../common/common-graph-utils";
+import {MatchCapabilitiesRequirementsUtils} from "./utils/match-capability-requierment-utils";
+import {CompositionGraphPaletteUtils} from "./utils/composition-graph-palette-utils";
+import {ComponentInstanceNodesStyle} from "../common/style/component-instances-nodes-style";
+import {CytoscapeEdgeEditation} from 'third-party/cytoscape.js-edge-editation/CytoscapeEdgeEditation.js';
+import {ComponentServiceNg2} from "../../../ng2/services/component-services/component.service";
+import {ComponentGenericResponse} from "../../../ng2/services/responses/component-generic-response";
+
+interface ICompositionGraphScope extends ng.IScope {
+
+ component:Component;
+ isLoading: boolean;
+ isViewOnly:boolean;
+ // Link menu - create link menu
+ relationMenuDirectiveObj:RelationMenuDirectiveObj;
+ isLinkMenuOpen:boolean;
+ createLinkFromMenu:(chosenMatch:MatchBase, vl:Component)=>void;
+
+ //modify link menu - for now only delete menu
+ relationMenuTimeout:ng.IPromise<any>;
+ linkMenuObject:LinkMenu;
+
+ //left palette functions callbacks
+ dropCallback(event:JQueryEventObject, ui:any):void;
+ beforeDropCallback(event:IDragDropEvent):void;
+ verifyDrop(event:JQueryEventObject, ui:any):void;
+
+ //Links menus
+ deleteRelation(link:Cy.CollectionEdges):void;
+ hideRelationMenu();
+ /*//asset popover menu
+ assetPopoverObj:AssetPopoverObj;
+ assetPopoverOpen:boolean;
+ hideAssetPopover():void;
+ deleteNode(nodeId:string):void;*/
+}
+
+export class CompositionGraph implements ng.IDirective {
+ private _cy:Cy.Instance;
+ private _currentlyCLickedNodePosition:Cy.Position;
+ // private $document:JQuery = $(document);
+ private dragElement:JQuery;
+ private dragComponent:ComponentInstance;
+
+ constructor(private $q:ng.IQService,
+ private $log:ng.ILogService,
+ private $timeout:ng.ITimeoutService,
+ private NodesFactory:NodesFactory,
+ private CompositionGraphLinkUtils:CompositionGraphLinkUtils,
+ private GeneralGraphUtils:CompositionGraphGeneralUtils,
+ private ComponentInstanceFactory:ComponentInstanceFactory,
+ private NodesGraphUtils:CompositionGraphNodesUtils,
+ private eventListenerService:EventListenerService,
+ private ComponentFactory:ComponentFactory,
+ private LoaderService:LoaderService,
+ private commonGraphUtils:CommonGraphUtils,
+ private matchCapabilitiesRequirementsUtils:MatchCapabilitiesRequirementsUtils,
+ private CompositionGraphPaletteUtils:CompositionGraphPaletteUtils,
+ private ComponentServiceNg2: ComponentServiceNg2) {
+
+ }
+
+ restrict = 'E';
+ template = require('./composition-graph.html');
+ scope = {
+ component: '=',
+ isViewOnly: '='
+ };
+
+ link = (scope:ICompositionGraphScope, el:JQuery) => {
+
+ this.loadGraph(scope, el);
+
+ if(scope.component.componentInstances && scope.component.componentInstancesRelations) {
+ this.loadGraphData(scope);
+ } else {
+ //when we don't have the data we register to on graph load event
+ this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_COMPOSITION_GRAPH_DATA_LOADED, () => {
+ this.loadGraphData(scope);
+ });
+ }
+ scope.$on('$destroy', () => {
+ this._cy.destroy();
+ _.forEach(GRAPH_EVENTS, (event) => {
+ this.eventListenerService.unRegisterObserver(event);
+ });
+ });
+
+ };
+
+ private loadGraphData = (scope:ICompositionGraphScope) => {
+ this.initGraphNodes(scope.component.componentInstances, scope.isViewOnly);
+ this.commonGraphUtils.initGraphLinks(this._cy, scope.component.componentInstancesRelations);
+ this.commonGraphUtils.initUcpeChildren(this._cy);
+ }
+
+ private loadGraph = (scope:ICompositionGraphScope, el:JQuery) => {
+
+ let graphEl = el.find('.sdc-composition-graph-wrapper');
+ this.initGraph(graphEl, scope.isViewOnly);
+ this.initDropZone(scope);
+ this.registerCytoscapeGraphEvents(scope);
+ this.registerCustomEvents(scope, el);
+ this.initViewMode(scope.isViewOnly);
+
+ };
+
+ private initGraph(graphEl:JQuery, isViewOnly:boolean) {
+
+ this._cy = cytoscape({
+ container: graphEl,
+ style: ComponentInstanceNodesStyle.getCompositionGraphStyle(),
+ zoomingEnabled: false,
+ selectionType: 'single',
+ boxSelectionEnabled: true,
+ autolock: isViewOnly,
+ autoungrabify: isViewOnly
+ });
+ }
+
+ private initViewMode(isViewOnly:boolean) {
+
+ if (isViewOnly) {
+ //remove event listeners
+ this._cy.off('drag');
+ this._cy.off('handlemouseout');
+ this._cy.off('handlemouseover');
+ this._cy.edges().unselectify();
+ }
+ };
+
+ private registerCustomEvents(scope:ICompositionGraphScope, el:JQuery) {
+
+ this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_PALETTE_COMPONENT_HOVER_IN, (leftPaletteComponent:LeftPaletteComponent) => {
+ this.$log.info(`composition-graph::registerEventServiceEvents:: palette hover on component: ${leftPaletteComponent.uniqueId}`);
+
+ let nodesData = this.NodesGraphUtils.getAllNodesData(this._cy.nodes());
+ let nodesLinks = this.GeneralGraphUtils.getAllCompositionCiLinks(this._cy);
+
+ if (this.GeneralGraphUtils.componentRequirementsAndCapabilitiesCaching.containsKey(leftPaletteComponent.uniqueId)) {
+ let cacheComponent = this.GeneralGraphUtils.componentRequirementsAndCapabilitiesCaching.getValue(leftPaletteComponent.uniqueId);
+ let filteredNodesData = this.matchCapabilitiesRequirementsUtils.findByMatchingCapabilitiesToRequirements(cacheComponent, nodesData, nodesLinks);
+
+ this.matchCapabilitiesRequirementsUtils.highlightMatchingComponents(filteredNodesData, this._cy);
+ this.matchCapabilitiesRequirementsUtils.fadeNonMachingComponents(filteredNodesData, nodesData, this._cy);
+
+ return;
+ }
+
+ //----------------------- ORIT TO FIX------------------------//
+
+ this.ComponentServiceNg2.getCapabilitiesAndRequirements(leftPaletteComponent.componentType, leftPaletteComponent.uniqueId).subscribe((response: ComponentGenericResponse) => {
+
+ let component = this.ComponentFactory.createEmptyComponent(leftPaletteComponent.componentType);
+ component.uniqueId = component.uniqueId;
+ component.capabilities = response.capabilities;
+ component.requirements = response.requirements;
+ this.GeneralGraphUtils.componentRequirementsAndCapabilitiesCaching.setValue(leftPaletteComponent.uniqueId, component);
+ let filteredNodesData = this.matchCapabilitiesRequirementsUtils.findByMatchingCapabilitiesToRequirements(component, nodesData, nodesLinks);
+ this.matchCapabilitiesRequirementsUtils.fadeNonMachingComponents(filteredNodesData, nodesData, this._cy);
+ this.matchCapabilitiesRequirementsUtils.highlightMatchingComponents(filteredNodesData, this._cy)
+ });
+ });
+
+ this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_PALETTE_COMPONENT_HOVER_OUT, () => {
+ this._cy.emit('hidehandles');
+ this.matchCapabilitiesRequirementsUtils.resetFadedNodes(this._cy);
+ });
+
+ this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_PALETTE_COMPONENT_DRAG_START, (dragElement, dragComponent) => {
+
+ this.dragElement = dragElement;
+ this.dragComponent = this.ComponentInstanceFactory.createComponentInstanceFromComponent(dragComponent);
+ });
+
+ this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_PALETTE_COMPONENT_DRAG_ACTION, (event:IDragDropEvent) => {
+ this.CompositionGraphPaletteUtils.onComponentDrag(this._cy, event, this.dragElement, this.dragComponent);
+
+ });
+
+ this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_COMPONENT_INSTANCE_NAME_CHANGED, (component:ComponentInstance) => {
+
+ let selectedNode = this._cy.getElementById(component.uniqueId);
+ selectedNode.data().componentInstance.name = component.name;
+ selectedNode.data('name', component.name); //used for tooltip
+ selectedNode.data('displayName', selectedNode.data().getDisplayName()); //abbreviated
+
+ });
+
+ this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_DELETE_COMPONENT_INSTANCE, (componentInstance:ComponentInstance) => {
+ let nodeToDelete = this._cy.getElementById(componentInstance.uniqueId);
+ this.NodesGraphUtils.deleteNode(this._cy, scope.component, nodeToDelete);
+ });
+
+ this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_DELETE_MULTIPLE_COMPONENTS, () => {
+
+ this._cy.$('node:selected').each((i:number, node:Cy.CollectionNodes) => {
+ this.NodesGraphUtils.deleteNode(this._cy, scope.component, node);
+ });
+
+ });
+
+ this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_DELETE_EDGE, (releaseLoading:boolean, linksToDelete:Cy.CollectionEdges) => {
+ this.CompositionGraphLinkUtils.deleteLink(this._cy, scope.component, releaseLoading, linksToDelete);
+ });
+
+ this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_INSERT_NODE_TO_UCPE, (node:Cy.CollectionNodes, ucpe:Cy.CollectionNodes, updateExistingNode:boolean) => {
+
+ this.commonGraphUtils.initUcpeChildData(node, ucpe);
+ //check if item is a VL, and if so, skip adding the binding to ucpe
+ if (!(node.data() instanceof CompositionCiNodeVl)) {
+ this.CompositionGraphLinkUtils.createVfToUcpeLink(scope.component, this._cy, ucpe.data(), node.data()); //create link from the node to the ucpe
+ }
+
+ if (updateExistingNode) {
+ let vlsPendingDeletion:Cy.CollectionNodes = this.NodesGraphUtils.deleteNodeVLsUponMoveToOrFromUCPE(scope.component, node.cy(), node); //delete connected VLs that no longer have 2 links
+ this.CompositionGraphLinkUtils.deleteLinksWhenNodeMovedFromOrToUCPE(scope.component, node.cy(), node, vlsPendingDeletion); //delete all connected links if needed
+ this.GeneralGraphUtils.pushUpdateComponentInstanceActionToQueue(scope.component, true, node.data().componentInstance); //update componentInstance position
+ }
+
+ });
+
+ this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_REMOVE_NODE_FROM_UCPE, (node:Cy.CollectionNodes, ucpe:Cy.CollectionNodes) => {
+ this.commonGraphUtils.removeUcpeChildData(node);
+ let vlsPendingDeletion:Cy.CollectionNodes = this.NodesGraphUtils.deleteNodeVLsUponMoveToOrFromUCPE(scope.component, node.cy(), node);
+ this.CompositionGraphLinkUtils.deleteLinksWhenNodeMovedFromOrToUCPE(scope.component, node.cy(), node, vlsPendingDeletion); //delete all connected links if needed
+ this.GeneralGraphUtils.pushUpdateComponentInstanceActionToQueue(scope.component, true, node.data().componentInstance); //update componentInstance position
+ });
+
+ this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_VERSION_CHANGED, (component:Component) => {
+ scope.component = component;
+ this.loadGraphData(scope);
+ });
+
+
+ scope.createLinkFromMenu = (chosenMatch:MatchBase):void => {
+ scope.isLinkMenuOpen = false;
+ this.CompositionGraphLinkUtils.createLinkFromMenu(this._cy, chosenMatch, scope.component);
+ };
+
+ scope.hideRelationMenu = () => {
+ this.commonGraphUtils.safeApply(scope, () => {
+ scope.linkMenuObject = null;
+ this.$timeout.cancel(scope.relationMenuTimeout);
+ });
+ };
+
+
+ scope.deleteRelation = (link:Cy.CollectionEdges) => {
+ scope.hideRelationMenu();
+
+ //if multiple edges selected, delete the VL itself so edges get deleted automatically
+ if (this._cy.$('edge:selected').length > 1) {
+ this.NodesGraphUtils.deleteNode(this._cy, scope.component, this._cy.$('node:selected'));
+ } else {
+ this.CompositionGraphLinkUtils.deleteLink(this._cy, scope.component, true, link);
+ }
+ };
+
+ /*
+ scope.hideAssetPopover = ():void => {
+
+ this.commonGraphUtils.safeApply(scope, () => {
+ scope.assetPopoverOpen = false;
+ scope.assetPopoverObj = null;
+ });
+ };
+
+ scope.deleteNode = (nodeId:string):void => {
+ if (!scope.isViewOnly) {
+ this.NodesGraphUtils.confirmDeleteNode(nodeId, this._cy, scope.component);
+ //scope.hideAssetPopover();
+ }
+ };*/
+ }
+
+ private registerCytoscapeGraphEvents(scope:ICompositionGraphScope) {
+
+ this._cy.on('addedgemouseup', (event, data) => {
+ scope.relationMenuDirectiveObj = this.CompositionGraphLinkUtils.onLinkDrawn(this._cy, data.source, data.target);
+ if (scope.relationMenuDirectiveObj != null) {
+ scope.$apply(() => {
+ scope.isLinkMenuOpen = true;
+ });
+ }
+ });
+ this._cy.on('tapstart', 'node', (event:Cy.EventObject) => {
+ this._currentlyCLickedNodePosition = angular.copy(event.cyTarget[0].position()); //update node position on drag
+ if (event.cyTarget.data().isUcpe) {
+ this._cy.nodes('.ucpe-cp').unlock();
+ event.cyTarget.style('opacity', 0.5);
+ }
+ //scope.hideAssetPopover();
+ });
+
+ this._cy.on('drag', 'node', (event:Cy.EventObject) => {
+
+ if (event.cyTarget.data().isDraggable) {
+ event.cyTarget.style({'overlay-opacity': 0.24});
+ if (this.GeneralGraphUtils.isValidDrop(this._cy, event.cyTarget)) {
+ event.cyTarget.style({'overlay-color': GraphColors.NODE_BACKGROUND_COLOR});
+ } else {
+ event.cyTarget.style({'overlay-color': GraphColors.NODE_OVERLAPPING_BACKGROUND_COLOR});
+ }
+ }
+
+ if (event.cyTarget.data().isUcpe) {
+ let pos = event.cyTarget.position();
+
+ this._cy.nodes('[?isInsideGroup]').positions((i, node)=> {
+ return {
+ x: pos.x + node.data("ucpeOffset").x,
+ y: pos.y + node.data("ucpeOffset").y
+ }
+ });
+ }
+ });
+
+ /* this._cy.on('mouseover', 'node', (event:Cy.EventObject) => {
+ if (!this._cy.scratch('_edge_editation_highlights')) {
+ this.commonGraphUtils.safeApply(scope, () => {
+ this.showNodePopoverMenu(scope, event.cyTarget[0]);
+ });
+ }
+ });
+
+ this._cy.on('mouseout', 'node', (event:Cy.EventObject) => {
+ scope.hideAssetPopover();
+ });*/
+ this._cy.on('handlemouseover', (event, payload) => {
+
+ if (payload.node.grabbed() /* || this._cy.scratch('_edge_editation_highlights') === true*/) { //no need to add opacity while we are dragging and hovering othe nodes- or if opacity was already calculated for these nodes
+ return;
+ }
+ let nodesData = this.NodesGraphUtils.getAllNodesData(this._cy.nodes());
+ let nodesLinks = this.GeneralGraphUtils.getAllCompositionCiLinks(this._cy);
+
+ let linkableNodes = this.commonGraphUtils.getLinkableNodes(this._cy, payload.node);
+ let filteredNodesData = this.matchCapabilitiesRequirementsUtils.findByMatchingCapabilitiesToRequirements(payload.node.data().componentInstance, linkableNodes, nodesLinks);
+ this.matchCapabilitiesRequirementsUtils.highlightMatchingComponents(filteredNodesData, this._cy);
+ this.matchCapabilitiesRequirementsUtils.fadeNonMachingComponents(filteredNodesData, nodesData, this._cy, payload.node.data());
+ /*
+ this._cy.scratch()._edge_editation_highlights = true;
+ scope.hideAssetPopover();*/
+ });
+
+ this._cy.on('handlemouseout', () => {
+ if (this._cy.scratch('_edge_editation_highlights') === true) {
+ this._cy.removeScratch('_edge_editation_highlights');
+ this._cy.emit('hidehandles');
+ this.matchCapabilitiesRequirementsUtils.resetFadedNodes(this._cy);
+ }
+ });
+
+
+ this._cy.on('tapend', (event:Cy.EventObject) => {
+
+ 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);
+ }
+ scope.hideRelationMenu();
+ }
+
+ else if (event.cyTarget.isEdge()) { //On Edge clicked
+ if (scope.isViewOnly) return;
+ this.CompositionGraphLinkUtils.handleLinkClick(this._cy, event);
+ this.openModifyLinkMenu(scope, this.CompositionGraphLinkUtils.getModifyLinkMenu(event.cyTarget[0], event), 6000);
+ }
+
+ else { //On Node clicked
+ this._cy.nodes(':grabbed').style({'overlay-opacity': 0});
+
+ let isUcpe:boolean = event.cyTarget.data().isUcpe;
+ let newPosition = event.cyTarget[0].position();
+ //node position changed (drop after drag event) - we need to update position
+ if (this._currentlyCLickedNodePosition.x !== newPosition.x || this._currentlyCLickedNodePosition.y !== newPosition.y) {
+ let nodesMoved:Cy.CollectionNodes = this._cy.$(':grabbed');
+ if (isUcpe) {
+ nodesMoved = nodesMoved.add(this._cy.nodes('[?isInsideGroup]:free')); //'child' nodes will not be recognized as "grabbed" elements within cytoscape. manually add them to collection of nodes moved.
+ }
+ this.NodesGraphUtils.onNodesPositionChanged(this._cy, scope.component, nodesMoved);
+ } else {
+ this.$log.debug('composition-graph::onNodeSelectedEvent:: fired');
+ scope.$apply(() => {
+ this.eventListenerService.notifyObservers(GRAPH_EVENTS.ON_NODE_SELECTED, event.cyTarget.data().componentInstance);
+ //open node popover menu
+ //this.showNodePopoverMenu(scope, event.cyTarget[0]);
+ });
+ }
+
+ if (isUcpe) {
+ this._cy.nodes('.ucpe-cp').lock();
+ event.cyTarget.style('opacity', 1);
+ }
+
+ }
+ });
+
+ this._cy.on('boxselect', 'node', (event:Cy.EventObject) => {
+ this.eventListenerService.notifyObservers(GRAPH_EVENTS.ON_NODE_SELECTED, event.cyTarget.data().componentInstance);
+ });
+ }
+
+ /*
+ 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) => {
+
+ this.commonGraphUtils.safeApply(scope, () => {
+ scope.linkMenuObject = linkMenuObject;
+ });
+
+ scope.relationMenuTimeout = this.$timeout(() => {
+ scope.hideRelationMenu();
+ }, timeOutInMilliseconds ? timeOutInMilliseconds : 6000);
+ };
+
+ private initGraphNodes(componentInstances:ComponentInstance[], isViewOnly:boolean) {
+
+ if (!isViewOnly) { //Init nodes handle extension - enable dynamic links
+ setTimeout(()=> {
+ let handles = new CytoscapeEdgeEditation;
+ handles.init(this._cy, 18);
+ handles.registerHandle(ComponentInstanceNodesStyle.getBasicNodeHanlde());
+ handles.registerHandle(ComponentInstanceNodesStyle.getBasicSmallNodeHandle());
+ handles.registerHandle(ComponentInstanceNodesStyle.getUcpeCpNodeHandle());
+ }, 0);
+ }
+
+ _.each(componentInstances, (instance) => {
+ let compositionGraphNode:CompositionCiNodeBase = this.NodesFactory.createNode(instance);
+ this.commonGraphUtils.addComponentInstanceNodeToGraph(this._cy, compositionGraphNode);
+ });
+ }
+
+
+ private initDropZone(scope:ICompositionGraphScope) {
+
+ if (scope.isViewOnly) {
+ return;
+ }
+ scope.dropCallback = (event:IDragDropEvent) => {
+ this.$log.debug(`composition-graph::dropCallback:: fired`);
+ this.CompositionGraphPaletteUtils.addNodeFromPalette(this._cy, event, scope.component);
+ };
+
+ scope.verifyDrop = (event:JQueryEventObject) => {
+
+ if (this.dragElement.hasClass('red')) {
+ return false;
+ }
+ return true;
+ };
+
+ scope.beforeDropCallback = (event:IDragDropEvent):ng.IPromise<void> => {
+ let deferred:ng.IDeferred<void> = this.$q.defer<void>();
+ if (this.dragElement.hasClass('red')) {
+ deferred.reject();
+ } else {
+ deferred.resolve();
+ }
+
+ return deferred.promise;
+ }
+ }
+
+ public static factory = ($q,
+ $log,
+ $timeout,
+ NodesFactory,
+ LinksGraphUtils,
+ GeneralGraphUtils,
+ ComponentInstanceFactory,
+ NodesGraphUtils,
+ EventListenerService,
+ ComponentFactory,
+ LoaderService,
+ CommonGraphUtils,
+ MatchCapabilitiesRequirementsUtils,
+ CompositionGraphPaletteUtils,
+ ComponentServiceNg2) => {
+ return new CompositionGraph(
+ $q,
+ $log,
+ $timeout,
+ NodesFactory,
+ LinksGraphUtils,
+ GeneralGraphUtils,
+ ComponentInstanceFactory,
+ NodesGraphUtils,
+ EventListenerService,
+ ComponentFactory,
+ LoaderService,
+ CommonGraphUtils,
+ MatchCapabilitiesRequirementsUtils,
+ CompositionGraphPaletteUtils,
+ ComponentServiceNg2);
+ }
+}
+
+CompositionGraph.factory.$inject = [
+ '$q',
+ '$log',
+ '$timeout',
+ 'NodesFactory',
+ 'CompositionGraphLinkUtils',
+ 'CompositionGraphGeneralUtils',
+ 'ComponentInstanceFactory',
+ 'CompositionGraphNodesUtils',
+ 'EventListenerService',
+ 'ComponentFactory',
+ 'LoaderService',
+ 'CommonGraphUtils',
+ 'MatchCapabilitiesRequirementsUtils',
+ 'CompositionGraphPaletteUtils',
+ 'ComponentServiceNg2'
+];
diff --git a/catalog-ui/app/scripts/directives/graphs-v2/composition-graph/composition-graph.html b/catalog-ui/src/app/directives/graphs-v2/composition-graph/composition-graph.html
index 5f2c488341..1e69d3384a 100644
--- a/catalog-ui/app/scripts/directives/graphs-v2/composition-graph/composition-graph.html
+++ b/catalog-ui/src/app/directives/graphs-v2/composition-graph/composition-graph.html
@@ -15,8 +15,9 @@
<div class="w-sdc-canvas-menu-content hand" data-ng-click="deleteRelation(linkMenuObject.link)">
<div class="w-sdc-canvas-menu-content-delete-button"></div>
- <!--{{relationComponent.data.relation.relationships[0].relationship.type | relationName }}-->
Delete
</div>
</div>
+
+<!--<asset-popover ng-if="assetPopoverOpen" asset-popover-obj="assetPopoverObj" delete-asset="deleteNode(assetPopoverObj.nodeId)"></asset-popover>-->
diff --git a/catalog-ui/app/scripts/directives/graphs-v2/composition-graph/composition-graph.less b/catalog-ui/src/app/directives/graphs-v2/composition-graph/composition-graph.less
index 7b999967b7..56c8b5529d 100644
--- a/catalog-ui/app/scripts/directives/graphs-v2/composition-graph/composition-graph.less
+++ b/catalog-ui/src/app/directives/graphs-v2/composition-graph/composition-graph.less
@@ -1,14 +1,14 @@
composition-graph {
display: block;
-
height:100%;
width: 100%;
+
.sdc-composition-graph-wrapper{
height:100%;
width: 100%;
}
- &.view-only{
+ .view-only{
background-color:rgb(248, 248, 248);
}
-} \ No newline at end of file
+}
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
new file mode 100644
index 0000000000..1303e7a894
--- /dev/null
+++ b/catalog-ui/src/app/directives/graphs-v2/composition-graph/utils/composition-graph-general-utils.ts
@@ -0,0 +1,244 @@
+import {ComponentInstance, Component, MatchReqToCapability, MatchBase, CompositionCiLinkBase, CompositionCiNodeUcpeCp} from "app/models";
+import {QueueUtils, Dictionary, GraphUIObjects} from "app/utils";
+import {LoaderService} from "app/services";
+import {MatchCapabilitiesRequirementsUtils} from "./match-capability-requierment-utils";
+import {CommonGraphUtils} from "../../common/common-graph-utils";
+
+
+export class CompositionGraphGeneralUtils {
+
+ public componentRequirementsAndCapabilitiesCaching = new Dictionary<string, Component>();
+ protected static graphUtilsUpdateQueue:QueueUtils;
+
+ constructor(private $q:ng.IQService,
+ private LoaderService:LoaderService,
+ private commonGraphUtils:CommonGraphUtils,
+ private matchCapabilitiesRequirementsUtils:MatchCapabilitiesRequirementsUtils) {
+ CompositionGraphGeneralUtils.graphUtilsUpdateQueue = new QueueUtils(this.$q);
+ }
+
+
+ /**
+ * Get the offset for the link creation Menu
+ * @param point
+ * @returns {Cy.Position}
+ */
+ public calcMenuOffset:Function = (point:Cy.Position):Cy.Position => {
+ point.x = point.x + 60;
+ point.y = point.y + 105;
+ return point;
+ };
+
+ /**
+ * return the top left position of the link menu
+ * @param cy
+ * @param targetNodePosition
+ * @returns {Cy.Position}
+ */
+ public getLinkMenuPosition = (cy:Cy.Instance, targetNodePosition:Cy.Position) => {
+ let menuPosition:Cy.Position = this.calcMenuOffset(targetNodePosition); //get the link mid point
+ if ($(document.body).height() < menuPosition.y + GraphUIObjects.LINK_MENU_HEIGHT + $(document.getElementsByClassName('sdc-composition-graph-wrapper')).offset().top) { // if position menu is overflow bottom
+ menuPosition.y = $(document.body).height() - GraphUIObjects.TOP_HEADER_HEIGHT - GraphUIObjects.LINK_MENU_HEIGHT;
+ }
+ return menuPosition;
+ };
+
+
+ /**
+ * will return true/false if two nodes overlapping
+ *
+ * @param graph node
+ */
+ private isNodesOverlapping(node:Cy.CollectionFirstNode, draggedNode:Cy.CollectionFirstNode):boolean {
+
+ let nodeBoundingBox:Cy.BoundingBox = node.renderedBoundingBox();
+ let secondNodeBoundingBox:Cy.BoundingBox = draggedNode.renderedBoundingBox();
+
+ return this.isBBoxOverlapping(nodeBoundingBox, secondNodeBoundingBox);
+ }
+
+ /**
+ * Checks whether the bounding boxes of two nodes are overlapping on any side
+ * @param nodeOneBBox
+ * @param nodeTwoBBox
+ * @returns {boolean}
+ */
+ private isBBoxOverlapping(nodeOneBBox:Cy.BoundingBox, nodeTwoBBox:Cy.BoundingBox) {
+ return (((nodeOneBBox.x1 < nodeTwoBBox.x1 && nodeOneBBox.x2 > nodeTwoBBox.x1) ||
+ (nodeOneBBox.x1 < nodeTwoBBox.x2 && nodeOneBBox.x2 > nodeTwoBBox.x2) ||
+ (nodeTwoBBox.x1 < nodeOneBBox.x1 && nodeTwoBBox.x2 > nodeOneBBox.x2)) &&
+ ((nodeOneBBox.y1 < nodeTwoBBox.y1 && nodeOneBBox.y2 > nodeTwoBBox.y1) ||
+ (nodeOneBBox.y1 < nodeTwoBBox.y2 && nodeOneBBox.y2 > nodeTwoBBox.y2) ||
+ (nodeTwoBBox.y1 < nodeOneBBox.y1 && nodeTwoBBox.y2 > nodeOneBBox.y2)))
+ }
+
+
+ /**
+ * Checks whether a specific component instance can be hosted on the UCPE instance
+ * @param cy - Cytoscape instance
+ * @param fromUcpeInstance
+ * @param toComponentInstance
+ * @returns {MatchReqToCapability}
+ */
+ public canBeHostedOn(cy:Cy.Instance, fromUcpeInstance:ComponentInstance, toComponentInstance:ComponentInstance):MatchReqToCapability {
+
+ let matches:Array<MatchBase> = this.matchCapabilitiesRequirementsUtils.getMatchedRequirementsCapabilities(fromUcpeInstance, toComponentInstance, this.getAllCompositionCiLinks(cy));
+ let hostedOnMatch:MatchBase = _.find(matches, (match:MatchReqToCapability) => {
+ return match.requirement.capability.toLowerCase() === 'tosca.capabilities.container';
+ });
+
+ return <MatchReqToCapability>hostedOnMatch;
+ };
+
+
+ /**
+ * Checks whether node can be dropped into UCPE
+ * @param cy
+ * @param nodeToInsert
+ * @param ucpeNode
+ * @returns {boolean}
+ */
+ private isValidDropInsideUCPE(cy:Cy.Instance, nodeToInsert:ComponentInstance, ucpeNode:ComponentInstance):boolean {
+
+ let hostedOnMatch:MatchReqToCapability = this.canBeHostedOn(cy, ucpeNode, nodeToInsert);
+ let result:boolean = !angular.isUndefined(hostedOnMatch) || nodeToInsert.isVl(); //group validation
+ return result;
+
+ };
+
+
+ /**
+ * For drops from palette, checks whether the node can be dropped. If node is being held over another node, check if capable of hosting
+ * @param cy
+ * @param pseudoNodeBBox
+ * @param paletteComponentInstance
+ * @returns {boolean}
+ */
+ public isPaletteDropValid(cy:Cy.Instance, pseudoNodeBBox:Cy.BoundingBox, paletteComponentInstance:ComponentInstance) {
+
+ let componentIsUCPE:boolean = (paletteComponentInstance.capabilities && paletteComponentInstance.capabilities['tosca.capabilities.Container'] && paletteComponentInstance.name.toLowerCase().indexOf('ucpe') > -1);
+
+ if (componentIsUCPE && cy.nodes('[?isUcpe]').length > 0) { //second UCPE not allowed
+ return false;
+ }
+
+ let illegalOverlappingNodes = _.filter(cy.nodes("[isSdcElement]"), (graphNode:Cy.CollectionFirstNode) => {
+
+ if (this.isBBoxOverlapping(pseudoNodeBBox, graphNode.renderedBoundingBox())) {
+ if (!componentIsUCPE && graphNode.data().isUcpe) {
+ return !this.isValidDropInsideUCPE(cy, paletteComponentInstance, graphNode.data().componentInstance); //if this is valid insert into ucpe, we return false - no illegal overlapping nodes
+ }
+ return true;
+ }
+
+ return false;
+ });
+
+ return illegalOverlappingNodes.length === 0;
+ }
+
+ /**
+ * will return true/false if a drop of a single node is valid
+ *
+ * @param graph node
+ */
+ public isValidDrop(cy:Cy.Instance, draggedNode:Cy.CollectionFirstNode):boolean {
+
+ let illegalOverlappingNodes = _.filter(cy.nodes("[isSdcElement]"), (graphNode:Cy.CollectionFirstNode) => { //all sdc nodes, removing child nodes (childe node allways collaps
+
+ if (draggedNode.data().isUcpe && (graphNode.isChild() || graphNode.data().isInsideGroup)) { //ucpe cps always inside ucpe, no overlapping
+ return false;
+ }
+ if (draggedNode.data().isInsideGroup && (!draggedNode.active() || graphNode.data().isUcpe)) {
+ return false;
+ }
+
+ if (!draggedNode.data().isUcpe && !(draggedNode.data() instanceof CompositionCiNodeUcpeCp) && graphNode.data().isUcpe) { //case we are dragging a node into UCPE
+ let isEntirelyInUCPE:boolean = this.commonGraphUtils.isFirstBoxContainsInSecondBox(draggedNode.renderedBoundingBox(), graphNode.renderedBoundingBox());
+ if (isEntirelyInUCPE) {
+ if (this.isValidDropInsideUCPE(cy, draggedNode.data().componentInstance, graphNode.data().componentInstance)) { //if this is valid insert into ucpe, we return false - no illegal overlapping nodes
+ return false;
+ }
+ }
+ }
+ return graphNode.data().id !== draggedNode.data().id && this.isNodesOverlapping(draggedNode, graphNode);
+
+ });
+ // return false;
+ return illegalOverlappingNodes.length === 0;
+ };
+
+ /**
+ * will return true/false if the move of the nodes is valid (no node overlapping and verifying if insert into UCPE is valid)
+ *
+ * @param nodesArray - the selected drags nodes
+ */
+ public isGroupValidDrop(cy:Cy.Instance, nodesArray:Cy.CollectionNodes):boolean {
+ let filterDraggedNodes = nodesArray.filter('[?isDraggable]');
+ let isValidDrop = _.every(filterDraggedNodes, (node:Cy.CollectionFirstNode) => {
+ return this.isValidDrop(cy, node);
+
+ });
+ return isValidDrop;
+ };
+
+ /**
+ * get all links in diagram
+ * @param cy
+ * @returns {any[]|boolean[]}
+ */
+ public getAllCompositionCiLinks = (cy:Cy.Instance):Array<CompositionCiLinkBase> => {
+ return _.map(cy.edges("[isSdcElement]"), (edge:Cy.CollectionEdges) => {
+ return edge.data();
+ });
+ };
+
+
+ /**
+ * Get Graph Utils server queue
+ * @returns {QueueUtils}
+ */
+ public getGraphUtilsServerUpdateQueue():QueueUtils {
+ return CompositionGraphGeneralUtils.graphUtilsUpdateQueue;
+ }
+ ;
+
+ /**
+ *
+ * @param blockAction - true/false if this is a block action
+ * @param instances
+ * @param component
+ */
+ public pushMultipleUpdateComponentInstancesRequestToQueue = (blockAction:boolean, instances:Array<ComponentInstance>, component:Component):void => {
+ if (blockAction) {
+ this.getGraphUtilsServerUpdateQueue().addBlockingUIAction(
+ () => component.updateMultipleComponentInstances(instances)
+ );
+ } else {
+ this.getGraphUtilsServerUpdateQueue().addNonBlockingUIAction(
+ () => component.updateMultipleComponentInstances(instances),
+ () => this.LoaderService.hideLoader('composition-graph'));
+ }
+ };
+
+ /**
+ * this function will update component instance data
+ * @param blockAction - true/false if this is a block action
+ * @param updatedInstance
+ */
+ public pushUpdateComponentInstanceActionToQueue = (component:Component, blockAction:boolean, updatedInstance:ComponentInstance):void => {
+
+ if (blockAction) {
+ this.LoaderService.showLoader('composition-graph');
+ this.getGraphUtilsServerUpdateQueue().addBlockingUIAction(
+ () => component.updateComponentInstance(updatedInstance)
+ );
+ } else {
+ this.getGraphUtilsServerUpdateQueue().addNonBlockingUIAction(
+ () => component.updateComponentInstance(updatedInstance),
+ () => this.LoaderService.hideLoader('composition-graph'));
+ }
+ };
+}
+
+CompositionGraphGeneralUtils.$inject = ['$q', 'LoaderService', 'CommonGraphUtils', 'MatchCapabilitiesRequirementsUtils'];
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
new file mode 100644
index 0000000000..314c761edd
--- /dev/null
+++ b/catalog-ui/src/app/directives/graphs-v2/composition-graph/utils/composition-graph-links-utils.ts
@@ -0,0 +1,271 @@
+/**
+ * Created by obarda on 6/28/2016.
+ */
+import {GraphUIObjects, ComponentInstanceFactory, ResourceType} from "app/utils";
+import {LeftPaletteLoaderService, LoaderService} from "app/services";
+import {
+ NodeUcpe,
+ CompositionCiNodeVf,
+ MatchReqToCapability,
+ MatchBase,
+ MatchReqToReq,
+ ComponentInstance,
+ CompositionCiNodeBase,
+ RelationshipModel,
+ RelationMenuDirectiveObj,
+ CapabilitiesGroup,
+ LinksFactory,
+ NodesFactory,
+ RequirementsGroup,
+ Component,
+ Relationship,
+ Capability,
+ LinkMenu,
+ Point,
+ CompositionCiLinkBase
+} from "app/models";
+import {CommonGraphUtils} from "../../common/common-graph-utils";
+import {CompositionGraphGeneralUtils} from "./composition-graph-general-utils";
+import {MatchCapabilitiesRequirementsUtils} from "./match-capability-requierment-utils";
+
+export class CompositionGraphLinkUtils {
+
+ constructor(private linksFactory:LinksFactory,
+ private loaderService:LoaderService,
+ private generalGraphUtils:CompositionGraphGeneralUtils,
+ private commonGraphUtils:CommonGraphUtils,
+ private matchCapabilitiesRequirementsUtils:MatchCapabilitiesRequirementsUtils) {
+ }
+
+
+ /**
+ * Delete the link on server and then remove it from graph
+ * @param component
+ * @param releaseLoading - true/false release the loader when finished
+ * @param link - the link to delete
+ */
+ public deleteLink = (cy:Cy.Instance, component:Component, releaseLoading:boolean, link:Cy.CollectionEdges) => {
+
+ this.loaderService.showLoader('composition-graph');
+ let onSuccessDeleteRelation = (response) => {
+ cy.remove(link);
+ };
+
+ if (!releaseLoading) {
+ this.generalGraphUtils.getGraphUtilsServerUpdateQueue().addBlockingUIAction(
+ () => component.deleteRelation(link.data().relation).then(onSuccessDeleteRelation)
+ );
+ } else {
+ this.generalGraphUtils.getGraphUtilsServerUpdateQueue().addBlockingUIActionWithReleaseCallback(
+ () => component.deleteRelation(link.data().relation).then(onSuccessDeleteRelation),
+ () => this.loaderService.hideLoader('composition-graph'));
+ }
+ };
+
+ /**
+ * create the link on server and than draw it on graph
+ * @param link - the link to create
+ * @param cy
+ * @param component
+ */
+ public createLink = (link:CompositionCiLinkBase, cy:Cy.Instance, component:Component):void => {
+
+ this.loaderService.showLoader('composition-graph');
+
+ let onSuccess:(response:RelationshipModel) => void = (relation:RelationshipModel) => {
+ link.setRelation(relation);
+ this.commonGraphUtils.insertLinkToGraph(cy, link);
+ };
+
+ link.updateLinkDirection();
+
+ this.generalGraphUtils.getGraphUtilsServerUpdateQueue().addBlockingUIActionWithReleaseCallback(
+ () => component.createRelation(link.relation).then(onSuccess),
+ () => this.loaderService.hideLoader('composition-graph')
+ );
+ };
+
+ private createSimpleLink = (match:MatchReqToCapability, cy:Cy.Instance, component:Component):void => {
+ let newRelation:RelationshipModel = match.matchToRelationModel();
+ let linkObg:CompositionCiLinkBase = this.linksFactory.createGraphLink(cy, newRelation, newRelation.relationships[0]);
+ this.createLink(linkObg, cy, component);
+ };
+
+ public createLinkFromMenu = (cy:Cy.Instance, chosenMatch:MatchBase, component:Component):void => {
+
+ if (chosenMatch) {
+ if (chosenMatch && chosenMatch instanceof MatchReqToCapability) {
+ this.createSimpleLink(chosenMatch, cy, component);
+ }
+ }
+ };
+
+
+ /**
+ * Filters the matches for UCPE links so that shown requirements and capabilites are only related to the selected ucpe-cp
+ * @param fromNode
+ * @param toNode
+ * @param matchesArray
+ * @returns {Array<MatchBase>}
+ */
+ public filterUcpeLinks(fromNode:CompositionCiNodeBase, toNode:CompositionCiNodeBase, matchesArray:Array<MatchBase>):any {
+
+ let matchLink:Array<MatchBase>;
+
+ if (fromNode.isUcpePart) {
+ matchLink = _.filter(matchesArray, (match:MatchBase) => {
+ return match.isOwner(fromNode.id);
+ });
+ }
+
+ if (toNode.isUcpePart) {
+ matchLink = _.filter(matchesArray, (match:MatchBase) => {
+ return match.isOwner(toNode.id);
+ });
+ }
+ return matchLink ? matchLink : matchesArray;
+ }
+
+
+ /**
+ * open the connect link menu if the link drawn is valid - match requirements & capabilities
+ * @param cy
+ * @param fromNode
+ * @param toNode
+ * @returns {any}
+ */
+ public onLinkDrawn(cy:Cy.Instance, fromNode:Cy.CollectionFirstNode, toNode:Cy.CollectionFirstNode):RelationMenuDirectiveObj {
+
+ if (!this.commonGraphUtils.nodeLocationsCompatible(cy, fromNode, toNode)) {
+ return null;
+ }
+ let linkModel:Array<CompositionCiLinkBase> = this.generalGraphUtils.getAllCompositionCiLinks(cy);
+
+ let possibleRelations:Array<MatchBase> = this.matchCapabilitiesRequirementsUtils.getMatchedRequirementsCapabilities(fromNode.data().componentInstance,
+ toNode.data().componentInstance, linkModel);
+
+ //filter relations found to limit to specific ucpe-cp
+ possibleRelations = this.filterUcpeLinks(fromNode.data(), toNode.data(), possibleRelations);
+
+ //if found possibleRelations between the nodes we create relation menu directive and open the link menu
+ if (possibleRelations.length) {
+ let menuPosition = this.generalGraphUtils.getLinkMenuPosition(cy, toNode.renderedPoint());
+ return new RelationMenuDirectiveObj(fromNode.data(), toNode.data(), menuPosition, possibleRelations);
+ }
+ return null;
+ };
+
+
+ /**
+ * when we drag instance in to UCPE or out of UCPE - get all links we need to delete - one node in ucpe and one node outside of ucpe
+ * @param node - the node we dragged into or out of the ucpe
+ */
+ public deleteLinksWhenNodeMovedFromOrToUCPE(component:Component, cy:Cy.Instance, nodeMoved:Cy.CollectionNodes, vlsPendingDeletion?:Cy.CollectionNodes):void {
+
+
+ let linksToDelete:Cy.CollectionElements = cy.collection();
+ _.forEach(nodeMoved.neighborhood('node'), (neighborNode)=> {
+
+ if (neighborNode.data().isUcpePart) { //existing connections to ucpe or ucpe-cp - we want to delete even though nodeLocationsCompatible will technically return true
+ linksToDelete = linksToDelete.add(nodeMoved.edgesWith(neighborNode)); // This will delete the ucpe-host-link, or the vl-ucpe-link if nodeMoved is vl
+ } else if (!this.commonGraphUtils.nodeLocationsCompatible(cy, nodeMoved, neighborNode)) { //connection to regular node or vl - check if locations are compatible
+ if (!vlsPendingDeletion || !vlsPendingDeletion.intersect(neighborNode).length) { //Check if this is a link to a VL pending deletion, to prevent double deletion of between the node moved and vl
+ linksToDelete = linksToDelete.add(nodeMoved.edgesWith(neighborNode));
+ }
+ }
+ });
+
+ linksToDelete.each((i, link)=> {
+ this.deleteLink(cy, component, false, link);
+ });
+
+ };
+
+ /**
+ * Creates a hostedOn link between a VF and UCPE
+ * @param component
+ * @param cy
+ * @param ucpeNode
+ * @param vfNode
+ */
+ public createVfToUcpeLink = (component:Component, cy:Cy.Instance, ucpeNode:NodeUcpe, vfNode:CompositionCiNodeVf):void => {
+ let hostedOnMatch:MatchReqToCapability = this.generalGraphUtils.canBeHostedOn(cy, ucpeNode.componentInstance, vfNode.componentInstance);
+ /* create relation */
+ let newRelation = new RelationshipModel();
+ newRelation.fromNode = ucpeNode.id;
+ newRelation.toNode = vfNode.id;
+
+ let link:CompositionCiLinkBase = this.linksFactory.createUcpeHostLink(newRelation);
+ link.relation = hostedOnMatch.matchToRelationModel();
+ this.createLink(link, cy, component);
+ };
+
+
+ /**
+ * Handles click event on links.
+ * If one edge selected: do nothing.
+ /*Two edges selected - always select all
+ /* Three or more edges: first click - select all, secondary click - select single.
+ * @param cy
+ * @param event
+ */
+ public handleLinkClick(cy:Cy.Instance, event:Cy.EventObject) {
+ if (cy.$('edge:selected').length > 2 && 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);
+ }
+ }
+
+ }
+
+
+ /**
+ * Calculates the position for the menu that modifies an existing link
+ * @param event
+ * @param elementWidth
+ * @param elementHeight
+ * @returns {Point}
+ */
+ public calculateLinkMenuPosition(event, elementWidth, elementHeight):Point {
+ let point:Point = new Point(event.originalEvent.x, event.originalEvent.y);
+ if (event.originalEvent.view.screen.height - elementHeight < point.y) {
+ point.y = event.originalEvent.view.screen.height - elementHeight;
+ }
+ if (event.originalEvent.view.screen.width - elementWidth < point.x) {
+ point.x = event.originalEvent.view.screen.width - elementWidth;
+ }
+ return point;
+ };
+
+
+ /**
+ * Gets the menu that is displayed when you click an existing link.
+ * @param link
+ * @param event
+ * @returns {LinkMenu}
+ */
+ public getModifyLinkMenu(link:Cy.CollectionFirstEdge, event:Cy.EventObject):LinkMenu {
+ let point:Point = this.calculateLinkMenuPosition(event, GraphUIObjects.MENU_LINK_VL_WIDTH_OFFSET, GraphUIObjects.MENU_LINK_VL_HEIGHT_OFFSET);
+ let menu:LinkMenu = new LinkMenu(point, true, link);
+ return menu;
+ };
+
+}
+
+
+CompositionGraphLinkUtils.$inject = [
+ 'LinksFactory',
+ 'LoaderService',
+ 'CompositionGraphGeneralUtils',
+ 'CommonGraphUtils',
+ 'MatchCapabilitiesRequirementsUtils'
+];
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
new file mode 100644
index 0000000000..96afc8a4ea
--- /dev/null
+++ b/catalog-ui/src/app/directives/graphs-v2/composition-graph/utils/composition-graph-nodes-utils.ts
@@ -0,0 +1,266 @@
+import {Component, NodesFactory, ComponentInstance, CompositionCiNodeVl,IAppMenu,AssetPopoverObj} 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";
+/**
+ * Created by obarda on 11/9/2016.
+ */
+export class CompositionGraphNodesUtils {
+ constructor(private NodesFactory:NodesFactory, private $log:ng.ILogService,
+ private GeneralGraphUtils:CompositionGraphGeneralUtils,
+ private commonGraphUtils:CommonGraphUtils,
+ private eventListenerService:EventListenerService,
+ private loaderService:LoaderService /*,
+ private sdcMenu: IAppMenu,
+ private ModalsHandler: ModalsHandler*/) {
+
+ }
+
+ /**
+ * Returns component instances for all nodes passed in
+ * @param nodes - Cy nodes
+ * @returns {any[]}
+ */
+ public getAllNodesData(nodes:Cy.CollectionNodes) {
+ return _.map(nodes, (node:Cy.CollectionFirstNode)=> {
+ return node.data();
+ })
+ };
+
+ /**
+ * Deletes component instances on server and then removes it from the graph as well
+ * @param cy
+ * @param component
+ * @param nodeToDelete
+ */
+ public deleteNode(cy:Cy.Instance, component:Component, nodeToDelete:Cy.CollectionNodes):void {
+
+ this.loaderService.showLoader('composition-graph');
+ let onSuccess:(response:ComponentInstance) => void = (response:ComponentInstance) => {
+ console.info('onSuccess', response);
+
+ //if node to delete is a UCPE, remove all children (except UCPE-CPs) and remove their "hostedOn" links
+ if (nodeToDelete.data().isUcpe) {
+ _.each(cy.nodes('[?isInsideGroup]'), (node)=> {
+ this.eventListenerService.notifyObservers(GRAPH_EVENTS.ON_REMOVE_NODE_FROM_UCPE, node, nodeToDelete);
+ });
+ }
+
+ //check whether the node is connected to any VLs that only have one other connection. If so, delete that VL as well
+ if (!(nodeToDelete.data() instanceof CompositionCiNodeVl)) {
+ let connectedVls:Array<Cy.CollectionFirstNode> = this.getConnectedVlToNode(nodeToDelete);
+ this.handleConnectedVlsToDelete(connectedVls);
+ }
+
+ //update UI
+ cy.remove(nodeToDelete);
+
+ };
+
+ let onFailed:(response:any) => void = (response:any) => {
+ console.info('onFailed', response);
+ };
+
+
+ this.GeneralGraphUtils.getGraphUtilsServerUpdateQueue().addBlockingUIActionWithReleaseCallback(
+ () => component.deleteComponentInstance(nodeToDelete.data().componentInstance.uniqueId).then(onSuccess, onFailed),
+ () => this.loaderService.hideLoader('composition-graph')
+ );
+
+ };
+
+/*
+ public confirmDeleteNode = (nodeId:string, cy:Cy.Instance, component:Component) => {
+ let node:Cy.CollectionNodes = cy.getElementById(nodeId);
+ let onOk = ():void => {
+ this.deleteNode(cy, component, node);
+ };
+
+ let componentInstance:ComponentInstance = node.data().componentInstance;
+ let state = "deleteInstance";
+ let title:string = this.sdcMenu.alertMessages[state].title;
+ let message:string = this.sdcMenu.alertMessages[state].message.format([componentInstance.name]);
+
+ this.ModalsHandler.openAlertModal(title, message).then(onOk);
+ };*/
+ /**
+ * Finds all VLs connected to a single node
+ * @param node
+ * @returns {Array<Cy.CollectionFirstNode>}
+ */
+ public getConnectedVlToNode = (node:Cy.CollectionNodes):Array<Cy.CollectionFirstNode> => {
+ let connectedVls:Array<Cy.CollectionFirstNode> = new Array<Cy.CollectionFirstNode>();
+ _.forEach(node.connectedEdges().connectedNodes(), (node:Cy.CollectionFirstNode) => {
+ if (node.data() instanceof CompositionCiNodeVl) {
+ connectedVls.push(node);
+ }
+ });
+ return connectedVls;
+ };
+
+
+ /**
+ * Delete all VLs that have only two connected nodes (this function is called when deleting a node)
+ * @param connectedVls
+ */
+ public handleConnectedVlsToDelete = (connectedVls:Array<Cy.CollectionFirstNode>) => {
+ _.forEach(connectedVls, (vlToDelete:Cy.CollectionNodes) => {
+
+ if (vlToDelete.connectedEdges().length === 2) { // if vl connected only to 2 nodes need to delete the vl
+ this.eventListenerService.notifyObservers(GRAPH_EVENTS.ON_DELETE_COMPONENT_INSTANCE, vlToDelete.data().componentInstance);
+ }
+ });
+ };
+
+
+ /**
+ * This function is called when moving a node in or out of UCPE.
+ * Deletes all connected VLs that have less than 2 valid connections remaining after the move
+ * Returns the collection of vls that are in the process of deletion (async) to prevent duplicate calls while deletion is in progress
+ * @param component
+ * @param cy
+ * @param node - node that was moved in/out of ucpe
+ */
+ public deleteNodeVLsUponMoveToOrFromUCPE = (component:Component, cy:Cy.Instance, node:Cy.CollectionNodes):Cy.CollectionNodes => {
+ if (node.data() instanceof CompositionCiNodeVl) {
+ return;
+ }
+
+ let connectedVLsToDelete:Cy.CollectionNodes = cy.collection();
+ _.forEach(node.neighborhood('node'), (connectedNode) => {
+
+ //Find all neighboring nodes that are VLs
+ if (connectedNode.data() instanceof CompositionCiNodeVl) {
+
+ //check VL's neighbors to see if it has 2 or more nodes whose location is compatible with VL (regardless of whether VL is in or out of UCPE)
+ let compatibleNodeCount = 0;
+ let vlNeighborhood = connectedNode.neighborhood('node');
+ _.forEach(vlNeighborhood, (vlNeighborNode)=> {
+ if (this.commonGraphUtils.nodeLocationsCompatible(cy, connectedNode, vlNeighborNode)) {
+ compatibleNodeCount++;
+ }
+ });
+
+ if (compatibleNodeCount < 2) {
+ connectedVLsToDelete = connectedVLsToDelete.add(connectedNode);
+ }
+ }
+ });
+
+ connectedVLsToDelete.each((i, vlToDelete:Cy.CollectionNodes)=> {
+ this.deleteNode(cy, component, vlToDelete);
+ });
+ return connectedVLsToDelete;
+ };
+
+ /**
+ * This function will update nodes position. if the new position is into or out of ucpe, the node will trigger the ucpe events
+ * @param cy
+ * @param component
+ * @param nodesMoved - the node/multiple nodes now moved by the user
+ */
+ public onNodesPositionChanged = (cy:Cy.Instance, component:Component, nodesMoved:Cy.CollectionNodes):void => {
+
+ if (nodesMoved.length === 0) {
+ return;
+ }
+
+ let isValidMove:boolean = this.GeneralGraphUtils.isGroupValidDrop(cy, nodesMoved);
+ if (isValidMove) {
+
+ this.$log.debug(`composition-graph::ValidDrop:: updating node position`);
+ let instancesToUpdateInNonBlockingAction:Array<ComponentInstance> = new Array<ComponentInstance>();
+
+ _.each(nodesMoved, (node:Cy.CollectionFirstNode)=> { //update all nodes new position
+
+ if (node.data().isUcpePart && !node.data().isUcpe) {
+ return;
+ }//No need to update UCPE-CPs
+
+ //update position
+ let newPosition:Cy.Position = this.commonGraphUtils.getNodePosition(node);
+ node.data().componentInstance.updatePosition(newPosition.x, newPosition.y);
+
+ //check if node moved to or from UCPE
+ let ucpe = this.commonGraphUtils.isInUcpe(node.cy(), node.boundingbox());
+ if (node.data().isInsideGroup || ucpe.length) {
+ this.handleUcpeChildMove(node, ucpe, instancesToUpdateInNonBlockingAction);
+ } else {
+ instancesToUpdateInNonBlockingAction.push(node.data().componentInstance);
+ }
+
+ });
+
+ if (instancesToUpdateInNonBlockingAction.length > 0) {
+ this.GeneralGraphUtils.pushMultipleUpdateComponentInstancesRequestToQueue(false, instancesToUpdateInNonBlockingAction, component);
+ }
+ } else {
+ this.$log.debug(`composition-graph::notValidDrop:: node return to latest position`);
+ //reset nodes position
+ nodesMoved.positions((i, node) => {
+ return {
+ x: +node.data().componentInstance.posX,
+ y: +node.data().componentInstance.posY
+ };
+ })
+ }
+
+ this.GeneralGraphUtils.getGraphUtilsServerUpdateQueue().addBlockingUIActionWithReleaseCallback(() => {
+ }, () => {
+ this.loaderService.hideLoader('composition-graph');
+ });
+
+ };
+
+ /**
+ * Checks whether the node has been added or removed from UCPE and triggers appropriate events
+ * @param node - node moved
+ * @param ucpeContainer - UCPE container that the node has been moved to. When moving a node out of ucpe, param will be empty
+ * @param instancesToUpdateInNonBlockingAction
+ */
+ public handleUcpeChildMove(node:Cy.CollectionFirstNode, ucpeContainer:Cy.CollectionElements, instancesToUpdateInNonBlockingAction:Array<ComponentInstance>) {
+
+ if (node.data().isInsideGroup) {
+ if (ucpeContainer.length) { //moving node within UCPE. Simply update position
+ this.commonGraphUtils.updateUcpeChildPosition(<Cy.CollectionNodes>node, ucpeContainer);
+ instancesToUpdateInNonBlockingAction.push(node.data().componentInstance);
+ } else { //removing node from UCPE. Notify observers
+ this.eventListenerService.notifyObservers(GRAPH_EVENTS.ON_REMOVE_NODE_FROM_UCPE, node, ucpeContainer);
+ }
+ } else if (!node.data().isInsideGroup && ucpeContainer.length && !node.data().isUcpePart) { //adding node to UCPE
+ this.eventListenerService.notifyObservers(GRAPH_EVENTS.ON_INSERT_NODE_TO_UCPE, node, ucpeContainer, true);
+ }
+ }
+ /**
+ * Gets the position for the asset popover menu
+ * Then, check if right edge of menu would overlap horizontal screen edge (palette offset + canvas width - right panel)
+ * Then, check if bottom edge of menu would overlap the vertical end of the canvas.
+ * @param cy
+ * @param node
+ * @returns {Cy.Position}
+
+ public createAssetPopover = (cy: Cy.Instance, node:Cy.CollectionFirstNode, isViewOnly:boolean):AssetPopoverObj => {
+
+ let menuOffset:Cy.Position = { x: node.renderedWidth() / 2, y: -(node.renderedWidth() / 2) };// getNodePositionWithOffset returns central point of node. First add node.renderedWidth()/2 to get its to border.
+ let menuPosition:Cy.Position = this.commonGraphUtils.getNodePositionWithOffset(node, menuOffset);
+ let menuSide:string = 'right';
+
+ if(menuPosition.x + GraphUIObjects.COMPOSITION_NODE_MENU_WIDTH >= cy.width() + GraphUIObjects.DIAGRAM_PALETTE_WIDTH_OFFSET - GraphUIObjects.COMPOSITION_RIGHT_PANEL_OFFSET){
+ menuPosition.x -= menuOffset.x * 2 + GraphUIObjects.COMPOSITION_NODE_MENU_WIDTH; //menu position already includes offset to the right. Therefore, subtract double offset so we have same distance from node for menu on left
+ menuSide = 'left';
+ }
+
+ if(menuPosition.y + GraphUIObjects.COMPOSITION_NODE_MENU_HEIGHT >= cy.height()){
+ menuPosition.y = menuPosition.y - GraphUIObjects.COMPOSITION_NODE_MENU_HEIGHT - menuOffset.y * 2;
+ }
+
+ return new AssetPopoverObj(node.data().id, node.data().name, menuPosition, menuSide, isViewOnly);
+ };
+ */
+
+ }
+
+
+ CompositionGraphNodesUtils.$inject = ['NodesFactory', '$log', 'CompositionGraphGeneralUtils', 'CommonGraphUtils', 'EventListenerService', 'LoaderService' /*, 'sdcMenu', 'ModalsHandler'*/]
+
diff --git a/catalog-ui/src/app/directives/graphs-v2/composition-graph/utils/composition-graph-palette-utils.ts b/catalog-ui/src/app/directives/graphs-v2/composition-graph/utils/composition-graph-palette-utils.ts
new file mode 100644
index 0000000000..83bf747501
--- /dev/null
+++ b/catalog-ui/src/app/directives/graphs-v2/composition-graph/utils/composition-graph-palette-utils.ts
@@ -0,0 +1,163 @@
+import {EventListenerService, LoaderService} from "app/services";
+import {CapabilitiesGroup, NodesFactory, ComponentInstance, Component, CompositionCiNodeBase, RequirementsGroup} from "app/models";
+import {ComponentFactory, ComponentInstanceFactory, GRAPH_EVENTS, GraphUIObjects} from "app/utils";
+import {CompositionGraphGeneralUtils} from "./composition-graph-general-utils";
+import {CommonGraphUtils} from "../../common/common-graph-utils";
+import 'angular-dragdrop';
+import {LeftPaletteComponent} from "../../../../models/components/displayComponent";
+
+export class CompositionGraphPaletteUtils {
+
+ constructor(private ComponentFactory:ComponentFactory,
+ private $filter:ng.IFilterService,
+ private loaderService:LoaderService,
+ private generalGraphUtils:CompositionGraphGeneralUtils,
+ private componentInstanceFactory:ComponentInstanceFactory,
+ private nodesFactory:NodesFactory,
+ private commonGraphUtils:CommonGraphUtils,
+ private eventListenerService:EventListenerService) {
+ }
+
+ /**
+ * Calculate the dragged element (html element) position on canvas
+ * @param cy
+ * @param event
+ * @param position
+ * @returns {Cy.BoundingBox}
+ * @private
+ */
+ private _getNodeBBox(cy:Cy.Instance, event:IDragDropEvent, position?:Cy.Position) {
+ let bbox = <Cy.BoundingBox>{};
+ if (!position) {
+ position = this.commonGraphUtils.getCytoscapeNodePosition(cy, event);
+ }
+ let cushionWidth:number = 40;
+ let cushionHeight:number = 40;
+
+ bbox.x1 = position.x - cushionWidth / 2;
+ bbox.y1 = position.y - cushionHeight / 2;
+ bbox.x2 = position.x + cushionWidth / 2;
+ bbox.y2 = position.y + cushionHeight / 2;
+ return bbox;
+ }
+
+ /**
+ * Create the component instance, update data from parent component in the left palette and notify on_insert_to_ucpe if component was dragg into ucpe
+ * @param cy
+ * @param fullComponent
+ * @param event
+ * @param component
+ */
+ private _createComponentInstanceOnGraphFromPaletteComponent(cy:Cy.Instance, fullComponent:LeftPaletteComponent, event:IDragDropEvent, component:Component) {
+
+ let componentInstanceToCreate:ComponentInstance = this.componentInstanceFactory.createComponentInstanceFromComponent(fullComponent);
+ let cytoscapePosition:Cy.Position = this.commonGraphUtils.getCytoscapeNodePosition(cy, event);
+
+ componentInstanceToCreate.posX = cytoscapePosition.x;
+ componentInstanceToCreate.posY = cytoscapePosition.y;
+
+
+ let onFailedCreatingInstance:(error:any) => void = (error:any) => {
+ this.loaderService.hideLoader('composition-graph');
+ };
+
+ //on success - update node data
+ let onSuccessCreatingInstance = (createInstance:ComponentInstance):void => {
+
+ this.loaderService.hideLoader('composition-graph');
+
+ createInstance.name = this.$filter('resourceName')(createInstance.name);
+ createInstance.requirements = new RequirementsGroup(createInstance.requirements);
+ createInstance.capabilities = new CapabilitiesGroup(createInstance.capabilities);
+ createInstance.componentVersion = fullComponent.version;
+ createInstance.icon = fullComponent.icon;
+ createInstance.setInstanceRC();
+
+ let newNode:CompositionCiNodeBase = this.nodesFactory.createNode(createInstance);
+ let cyNode:Cy.CollectionNodes = this.commonGraphUtils.addComponentInstanceNodeToGraph(cy, newNode);
+
+ //check if node was dropped into a UCPE
+ let ucpe:Cy.CollectionElements = this.commonGraphUtils.isInUcpe(cy, cyNode.boundingbox());
+ if (ucpe.length > 0) {
+ this.eventListenerService.notifyObservers(GRAPH_EVENTS.ON_INSERT_NODE_TO_UCPE, cyNode, ucpe, false);
+ }
+ this.eventListenerService.notifyObservers(GRAPH_EVENTS.ON_CREATE_COMPONENT_INSTANCE);
+
+ };
+
+ this.loaderService.showLoader('composition-graph');
+
+ // Create the component instance on server
+ this.generalGraphUtils.getGraphUtilsServerUpdateQueue().addBlockingUIAction(() => {
+ component.createComponentInstance(componentInstanceToCreate).then(onSuccessCreatingInstance, onFailedCreatingInstance);
+ });
+ }
+
+ /**
+ * Thid function applay red/green background when component dragged from palette
+ * @param cy
+ * @param event
+ * @param dragElement
+ * @param dragComponent
+ */
+ public onComponentDrag(cy:Cy.Instance, event:IDragDropEvent, dragElement:JQuery, dragComponent:ComponentInstance) {
+
+ if (event.clientX < GraphUIObjects.DIAGRAM_PALETTE_WIDTH_OFFSET || event.clientY < GraphUIObjects.DIAGRAM_HEADER_OFFSET) { //hovering over palette. Dont bother computing validity of drop
+ dragElement.removeClass('red');
+ return;
+ }
+
+ let offsetPosition = {
+ x: event.clientX - GraphUIObjects.DIAGRAM_PALETTE_WIDTH_OFFSET,
+ y: event.clientY - GraphUIObjects.DIAGRAM_HEADER_OFFSET
+ };
+ let bbox = this._getNodeBBox(cy, event, offsetPosition);
+
+ if (this.generalGraphUtils.isPaletteDropValid(cy, bbox, dragComponent)) {
+ dragElement.removeClass('red');
+ } else {
+ dragElement.addClass('red');
+ }
+ }
+
+ /**
+ * This function is called when after dropping node on canvas
+ * Check if the capability & requirements fulfilled and if not get from server
+ * @param cy
+ * @param event
+ * @param component
+ */
+ public addNodeFromPalette(cy:Cy.Instance, event:IDragDropEvent, component:Component) {
+ this.loaderService.showLoader('composition-graph');
+
+ let draggedComponent:LeftPaletteComponent = event.dataTransfer.component;
+
+ if (this.generalGraphUtils.componentRequirementsAndCapabilitiesCaching.containsKey(draggedComponent.uniqueId)) {
+ let fullComponent = this.generalGraphUtils.componentRequirementsAndCapabilitiesCaching.getValue(draggedComponent.uniqueId);
+ draggedComponent.capabilities = fullComponent.capabilities;
+ draggedComponent.requirements = fullComponent.requirements;
+ this._createComponentInstanceOnGraphFromPaletteComponent(cy, draggedComponent, event, component);
+
+ } else {
+
+ this.ComponentFactory.getComponentFromServer(draggedComponent.getComponentSubType(), draggedComponent.uniqueId)
+ .then((fullComponent:Component) => {
+ draggedComponent.capabilities = fullComponent.capabilities;
+ draggedComponent.requirements = fullComponent.requirements;
+ this._createComponentInstanceOnGraphFromPaletteComponent(cy, draggedComponent, event, component);
+ });
+ }
+ }
+}
+
+
+CompositionGraphPaletteUtils.$inject = [
+ 'ComponentFactory',
+ '$filter',
+ 'LoaderService',
+ 'CompositionGraphGeneralUtils',
+ 'ComponentInstanceFactory',
+ 'NodesFactory',
+ 'CommonGraphUtils',
+ 'EventListenerService'
+];
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
new file mode 100644
index 0000000000..0e21f033be
--- /dev/null
+++ b/catalog-ui/src/app/directives/graphs-v2/composition-graph/utils/match-capability-requierment-utils.ts
@@ -0,0 +1,259 @@
+import {Requirement, CompositionCiLinkBase, ComponentInstance, CapabilitiesGroup, RequirementsGroup, MatchReqToCapability, MatchBase,
+ MatchReqToReq,CompositionCiNodeBase, Component, Capability} from "app/models";
+/**
+ * Created by obarda on 1/1/2017.
+ */
+
+export class MatchCapabilitiesRequirementsUtils {
+
+ constructor() {
+ }
+
+ public static linkable(requirement1:Requirement, requirement2:Requirement, vlCapability:Capability):boolean {
+ return MatchCapabilitiesRequirementsUtils.isMatch(requirement1, vlCapability) && MatchCapabilitiesRequirementsUtils.isMatch(requirement2, vlCapability);
+ };
+
+
+ /**
+ * Shows + icon in corner of each node passed in
+ * @param filteredNodesData
+ * @param cy
+ */
+ public highlightMatchingComponents(filteredNodesData, cy:Cy.Instance) {
+ _.each(filteredNodesData, (data:any) => {
+ let node = cy.getElementById(data.id);
+ cy.emit('showhandle', [node]);
+ });
+ }
+
+ /**
+ * Adds opacity to each node that cannot be linked to hovered node
+ * @param filteredNodesData
+ * @param nodesData
+ * @param cy
+ * @param hoveredNodeData
+ */
+ public fadeNonMachingComponents(filteredNodesData, nodesData, cy:Cy.Instance, hoveredNodeData?) {
+ let fadeNodes = _.xorWith(nodesData, filteredNodesData, (node1, node2) => {
+ return node1.id === node2.id;
+ });
+ if (hoveredNodeData) {
+ _.remove(fadeNodes, hoveredNodeData);
+ }
+ cy.batch(()=> {
+ _.each(fadeNodes, (node) => {
+ cy.getElementById(node.id).style({'background-image-opacity': 0.4});
+ });
+ })
+ }
+
+ /**
+ * Resets all nodes to regular opacity
+ * @param cy
+ */
+ public resetFadedNodes(cy:Cy.Instance) {
+ cy.batch(()=> {
+ cy.nodes().style({'background-image-opacity': 1});
+ })
+ }
+
+ // -------------------------------------------ALL FUNCTIONS NEED REFACTORING---------------------------------------------------------------//
+
+ private static requirementFulfilled(fromNodeId:string, requirement:any, links:Array<CompositionCiLinkBase>):boolean {
+ return _.some(links, {
+ 'relation': {
+ 'fromNode': fromNodeId,
+ 'relationships': [{
+ 'requirementOwnerId': requirement.ownerId,
+ 'requirement': requirement.name,
+ 'relationship': {
+ 'type': requirement.relationship
+ }
+ }
+ ]
+ }
+ });
+ };
+
+ private static isMatch(requirement:Requirement, capability:Capability):boolean {
+ if (capability.type === requirement.capability) {
+ if (requirement.node) {
+ if (_.includes(capability.capabilitySources, requirement.node)) {
+ return true;
+ }
+ } else {
+ return true;
+ }
+ }
+ return false;
+ };
+
+ private getFromToMatches(requirements1:RequirementsGroup,
+ requirements2:RequirementsGroup,
+ capabilities:CapabilitiesGroup,
+ links:Array<CompositionCiLinkBase>,
+ fromId:string,
+ toId:string,
+ vlCapability?:Capability):Array<MatchBase> {
+ let matches:Array<MatchBase> = new Array<MatchBase>();
+ _.forEach(requirements1, (requirementValue:Array<Requirement>, key) => {
+ _.forEach(requirementValue, (requirement:Requirement) => {
+ if (requirement.name !== "dependency" && !MatchCapabilitiesRequirementsUtils.requirementFulfilled(fromId, requirement, links)) {
+ _.forEach(capabilities, (capabilityValue:Array<Capability>, key) => {
+ _.forEach(capabilityValue, (capability:Capability) => {
+ if (MatchCapabilitiesRequirementsUtils.isMatch(requirement, capability)) {
+ let match:MatchReqToCapability = new MatchReqToCapability(requirement, capability, true, fromId, toId);
+ matches.push(match);
+ }
+ });
+ });
+ if (vlCapability) {
+ _.forEach(requirements2, (requirement2Value:Array<Requirement>, key) => {
+ _.forEach(requirement2Value, (requirement2:Requirement) => {
+ if (!MatchCapabilitiesRequirementsUtils.requirementFulfilled(toId, requirement2, links) && MatchCapabilitiesRequirementsUtils.linkable(requirement, requirement2, vlCapability)) {
+ let match:MatchReqToReq = new MatchReqToReq(requirement, requirement2, true, fromId, toId);
+ matches.push(match);
+ }
+ });
+ });
+ }
+ }
+ });
+ });
+ return matches;
+ }
+
+ private getToFromMatches(requirements:RequirementsGroup, capabilities:CapabilitiesGroup, links:Array<CompositionCiLinkBase>, fromId:string, toId:string):Array<MatchReqToCapability> {
+ let matches:Array<MatchReqToCapability> = [];
+ _.forEach(requirements, (requirementValue:Array<Requirement>, key) => {
+ _.forEach(requirementValue, (requirement:Requirement) => {
+ if (requirement.name !== "dependency" && !MatchCapabilitiesRequirementsUtils.requirementFulfilled(toId, requirement, links)) {
+ _.forEach(capabilities, (capabilityValue:Array<Capability>, key) => {
+ _.forEach(capabilityValue, (capability:Capability) => {
+ if (MatchCapabilitiesRequirementsUtils.isMatch(requirement, capability)) {
+ let match:MatchReqToCapability = new MatchReqToCapability(requirement, capability, false, toId, fromId);
+ matches.push(match);
+ }
+ });
+ });
+ }
+ });
+ });
+ return matches;
+ }
+
+ public getMatchedRequirementsCapabilities(fromComponentInstance:ComponentInstance,
+ toComponentInstance:ComponentInstance,
+ links:Array<CompositionCiLinkBase>,
+ vl?:Component):Array<MatchBase> {//TODO allow for VL array
+ let linkCapability;
+ if (vl) {
+ let linkCapabilities:Array<Capability> = vl.capabilities.findValueByKey('linkable');
+ if (linkCapabilities) {
+ linkCapability = linkCapabilities[0];
+ }
+ }
+ let fromToMatches:Array<MatchBase> = this.getFromToMatches(fromComponentInstance.requirements,
+ toComponentInstance.requirements,
+ toComponentInstance.capabilities,
+ links,
+ fromComponentInstance.uniqueId,
+ toComponentInstance.uniqueId,
+ linkCapability);
+ let toFromMatches:Array<MatchReqToCapability> = this.getToFromMatches(toComponentInstance.requirements,
+ fromComponentInstance.capabilities,
+ links,
+ fromComponentInstance.uniqueId,
+ toComponentInstance.uniqueId);
+
+ return fromToMatches.concat(toFromMatches);
+ }
+
+
+ /**
+ * Step I: Check if capabilities of component match requirements of nodeDataArray
+ * 1. Get component capabilities and loop on each capability
+ * 2. Inside the loop, perform another loop on all nodeDataArray, and fetch the requirements for each one
+ * 3. Loop on the requirements, and verify match (see in code the rules)
+ *
+ * Step II: Check if requirements of component match capabilities of nodeDataArray
+ * 1. Get component requirements and loop on each requirement
+ * 2.
+ *
+ * @param component - this is the hovered resource of the left panel of composition screen
+ * @param nodeDataArray - Array of resource instances that are on the canvas
+ * @param links -getMatchedRequirementsCapabilities
+ * @param vl -
+ * @returns {any[]|T[]}
+ */
+ public findByMatchingCapabilitiesToRequirements(component:Component,
+ nodeDataArray:Array<CompositionCiNodeBase>,
+ links:Array<CompositionCiLinkBase>,
+ vl?:Component):Array<any> {//TODO allow for VL array
+ let res = [];
+
+ // STEP I
+ {
+ let capabilities:any = component.capabilities;
+ _.forEach(capabilities, (capabilityValue:Array<any>, capabilityKey)=> {
+ _.forEach(capabilityValue, (capability)=> {
+ _.forEach(nodeDataArray, (node:CompositionCiNodeBase)=> {
+ if (node && node.componentInstance) {
+ let requirements:any = node.componentInstance.requirements;
+ let fromNodeId:string = node.componentInstance.uniqueId;
+ _.forEach(requirements, (requirementValue:Array<any>, requirementKey)=> {
+ _.forEach(requirementValue, (requirement)=> {
+ if (requirement.name !== "dependency" && MatchCapabilitiesRequirementsUtils.isMatch(requirement, capability)
+ && !MatchCapabilitiesRequirementsUtils.requirementFulfilled(fromNodeId, requirement, links)) {
+ res.push(node);
+ }
+ });
+ });
+ }
+ });
+ });
+ });
+ }
+
+ // STEP II
+ {
+ let requirements:any = component.requirements;
+ let fromNodeId:string = component.uniqueId;
+ let linkCapability:Array<Capability> = vl ? vl.capabilities.findValueByKey('linkable') : undefined;
+
+ _.forEach(requirements, (requirementValue:Array<any>, requirementKey)=> {
+ _.forEach(requirementValue, (requirement)=> {
+ if (requirement.name !== "dependency" && !MatchCapabilitiesRequirementsUtils.requirementFulfilled(fromNodeId, requirement, links)) {
+ _.forEach(nodeDataArray, (node:any)=> {
+ if (node && node.componentInstance && node.category !== 'groupCp') {
+ let capabilities:any = node.componentInstance.capabilities;
+ _.forEach(capabilities, (capabilityValue:Array<any>, capabilityKey)=> {
+ _.forEach(capabilityValue, (capability)=> {
+ if (MatchCapabilitiesRequirementsUtils.isMatch(requirement, capability)) {
+ res.push(node);
+ }
+ });
+ });
+ if (linkCapability) {
+ let linkRequirements = node.componentInstance.requirements;
+ _.forEach(linkRequirements, (value:Array<any>, key)=> {
+ _.forEach(value, (linkRequirement)=> {
+ if (!MatchCapabilitiesRequirementsUtils.requirementFulfilled(node.componentInstance.uniqueId, linkRequirement, links)
+ && MatchCapabilitiesRequirementsUtils.linkable(requirement, linkRequirement, linkCapability[0])) {
+ res.push(node);
+ }
+ });
+ });
+ }
+ }
+ });
+ }
+ });
+ });
+ }
+
+ return _.uniq(res);
+ };
+}
+
+MatchCapabilitiesRequirementsUtils.$inject = [];
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
new file mode 100644
index 0000000000..5ad6570013
--- /dev/null
+++ b/catalog-ui/src/app/directives/graphs-v2/deployment-graph/deployment-graph.directive.ts
@@ -0,0 +1,122 @@
+import {Component, Module, NodesFactory, ComponentInstance} from "app/models";
+import {ComponentInstanceFactory} from "app/utils";
+import {DeploymentGraphGeneralUtils} from "./deployment-utils/deployment-graph-general-utils";
+import {CommonGraphUtils} from "../common/common-graph-utils";
+import {ComponentInstanceNodesStyle} from "../common/style/component-instances-nodes-style";
+import {ModulesNodesStyle} from "../common/style/module-node-style";
+import {GRAPH_EVENTS} from "app/utils";
+import {EventListenerService} from "app/services";
+import 'cytoscape-expand-collapse';
+
+interface IDeploymentGraphScope extends ng.IScope {
+ component:Component;
+}
+
+export class DeploymentGraph implements ng.IDirective {
+ private _cy:Cy.Instance;
+
+ constructor(private NodesFactory:NodesFactory, private commonGraphUtils:CommonGraphUtils,
+ private deploymentGraphGeneralUtils:DeploymentGraphGeneralUtils, private ComponentInstanceFactory:ComponentInstanceFactory, private eventListenerService:EventListenerService) {
+ }
+
+ restrict = 'E';
+ template = require('./deployment-graph.html');
+ scope = {
+ component: '=',
+ isViewOnly: '='
+ };
+
+ link = (scope:IDeploymentGraphScope, el:JQuery) => {
+
+ if (scope.component.isResource()) {
+ if (scope.component.componentInstances && scope.component.componentInstancesRelations && scope.component.groups) {
+ this.loadGraph(scope, el);
+ } else {
+ this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_DEPLOYMENT_GRAPH_DATA_LOADED, () => {
+ this.loadGraph(scope, el);
+ });
+ }
+ }
+ };
+
+
+ public initGraphNodes = (cy:Cy.Instance, component:Component):void => {
+ if (component.groups) { // Init module nodes
+ _.each(component.groups, (groupModule:Module) => {
+ let moduleNode = this.NodesFactory.createModuleNode(groupModule);
+ this.commonGraphUtils.addNodeToGraph(cy, moduleNode);
+
+ });
+ }
+ _.each(component.componentInstances, (instance:ComponentInstance) => { // Init component instance nodes
+ let componentInstanceNode = this.NodesFactory.createNode(instance);
+ componentInstanceNode.parent = this.deploymentGraphGeneralUtils.findInstanceModule(component.groups, instance.uniqueId);
+ if (componentInstanceNode.parent) { // we are not drawing instances that are not a part of a module
+ this.commonGraphUtils.addComponentInstanceNodeToGraph(cy, componentInstanceNode);
+ }
+ });
+
+ // This is a special functionality to pass the cytoscape default behavior - we can't create Parent module node without children's
+ // so we must add an empty dummy child node
+ _.each(this._cy.nodes('[?isGroup]'), (moduleNode:Cy.CollectionFirstNode) => {
+ if (!moduleNode.isParent()) {
+ let dummyInstance = this.ComponentInstanceFactory.createEmptyComponentInstance();
+ let componentInstanceNode = this.NodesFactory.createNode(dummyInstance);
+ componentInstanceNode.parent = moduleNode.id();
+ let dummyNode = this.commonGraphUtils.addNodeToGraph(cy, componentInstanceNode, moduleNode.position());
+ dummyNode.addClass('dummy-node');
+ }
+ })
+ };
+
+ private registerGraphEvents() {
+
+ this._cy.on('afterExpand', (event) => {
+ event.cyTarget.qtip({});
+ });
+
+ this._cy.on('afterCollapse', (event) => {
+ this.commonGraphUtils.initNodeTooltip(event.cyTarget);
+ });
+ }
+
+ private loadGraph = (scope:IDeploymentGraphScope, el:JQuery) => {
+
+ let graphEl = el.find('.sdc-deployment-graph-wrapper');
+ this._cy = cytoscape({
+ container: graphEl,
+ style: ComponentInstanceNodesStyle.getCompositionGraphStyle().concat(ModulesNodesStyle.getModuleGraphStyle()),
+ zoomingEnabled: false,
+ selectionType: 'single',
+
+ });
+
+ //adding expand collapse extension
+ this._cy.expandCollapse({
+ layoutBy: {
+ name: "grid",
+ animate: true,
+ randomize: false,
+ fit: true
+ },
+ fisheye: false,
+ undoable: false,
+ expandCollapseCueSize: 18,
+ expandCueImage: '/assets/styles/images/resource-icons/' + 'closeModule.png',
+ collapseCueImage: '/assets/styles/images/resource-icons/' + 'openModule.png',
+ expandCollapseCueSensitivity: 2,
+ cueOffset: -20
+ });
+
+ this.initGraphNodes(this._cy, scope.component); //creating instances nodes
+ this.commonGraphUtils.initGraphLinks(this._cy, scope.component.componentInstancesRelations);
+ this._cy.collapseAll();
+ this.registerGraphEvents();
+ };
+
+ public static factory = (NodesFactory:NodesFactory, CommonGraphUtils:CommonGraphUtils, DeploymentGraphGeneralUtils:DeploymentGraphGeneralUtils, ComponentInstanceFactory:ComponentInstanceFactory, EventListenerService:EventListenerService) => {
+ return new DeploymentGraph(NodesFactory, CommonGraphUtils, DeploymentGraphGeneralUtils, ComponentInstanceFactory, EventListenerService)
+ }
+}
+
+DeploymentGraph.factory.$inject = ['NodesFactory', 'CommonGraphUtils', 'DeploymentGraphGeneralUtils', 'ComponentInstanceFactory', 'EventListenerService'];
diff --git a/catalog-ui/app/scripts/directives/graphs-v2/deployment-graph/deployment-graph.html b/catalog-ui/src/app/directives/graphs-v2/deployment-graph/deployment-graph.html
index 55e1c131f4..56c2d8b200 100644
--- a/catalog-ui/app/scripts/directives/graphs-v2/deployment-graph/deployment-graph.html
+++ b/catalog-ui/src/app/directives/graphs-v2/deployment-graph/deployment-graph.html
@@ -1,2 +1,2 @@
<div class="sdc-deployment-graph-wrapper" ng-class="{'view-only':isViewOnly}">
-</div> \ No newline at end of file
+</div>
diff --git a/catalog-ui/app/scripts/directives/graphs-v2/deployment-graph/deployment-graph.less b/catalog-ui/src/app/directives/graphs-v2/deployment-graph/deployment-graph.less
index ff8fc46380..f83ee8a891 100644
--- a/catalog-ui/app/scripts/directives/graphs-v2/deployment-graph/deployment-graph.less
+++ b/catalog-ui/src/app/directives/graphs-v2/deployment-graph/deployment-graph.less
@@ -11,4 +11,4 @@ deployment-graph {
.view-only{
background-color:rgb(248, 248, 248);
}
-} \ No newline at end of file
+}
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
new file mode 100644
index 0000000000..368455cb24
--- /dev/null
+++ b/catalog-ui/src/app/directives/graphs-v2/deployment-graph/deployment-utils/deployment-graph-general-utils.ts
@@ -0,0 +1,22 @@
+import {Module} from "app/models";
+/**
+ * Created by obarda on 12/21/2016.
+ */
+
+export class DeploymentGraphGeneralUtils {
+
+ constructor() {
+
+ }
+
+ public findInstanceModule = (groupsArray:Array<Module>, componentInstanceId:string):string => {
+ let parentGroup:Module = _.find(groupsArray, (group:Module) => {
+ return _.find(group.members, (member) => {
+ return member === componentInstanceId;
+ });
+ });
+ return parentGroup ? parentGroup.uniqueId : "";
+ };
+}
+
+DeploymentGraphGeneralUtils.$inject = [];
diff --git a/catalog-ui/src/app/directives/graphs-v2/image-creator/image-creator.service.ts b/catalog-ui/src/app/directives/graphs-v2/image-creator/image-creator.service.ts
new file mode 100644
index 0000000000..1bafb2f32b
--- /dev/null
+++ b/catalog-ui/src/app/directives/graphs-v2/image-creator/image-creator.service.ts
@@ -0,0 +1,45 @@
+'use strict';
+export class ImageCreatorService {
+ static '$inject' = ['$q'];
+ private _canvas:HTMLCanvasElement;
+
+ constructor(private $q:ng.IQService) {
+ this._canvas = <HTMLCanvasElement>$('<canvas>')[0];
+ this._canvas.setAttribute('style', 'display:none');
+
+ let body = document.getElementsByTagName('body')[0];
+ body.appendChild(this._canvas);
+ }
+
+ getImageBase64(imageBaseUri:string, imageLayerUri:string):ng.IPromise<string> {
+ let deferred = this.$q.defer();
+ let imageBase = new Image();
+ let imageLayer = new Image();
+ let imagesLoaded = 0;
+ let onImageLoaded = () => {
+ imagesLoaded++;
+
+ if (imagesLoaded < 2) {
+ return;
+ }
+ this._canvas.setAttribute('width', imageBase.width.toString());
+ this._canvas.setAttribute('height', imageBase.height.toString());
+
+ let canvasCtx = this._canvas.getContext('2d');
+ canvasCtx.clearRect(0, 0, this._canvas.width, this._canvas.height);
+
+ canvasCtx.drawImage(imageBase, 0, 0, imageBase.width, imageBase.height);
+ canvasCtx.drawImage(imageLayer, imageBase.width - imageLayer.width, 0, imageLayer.width, imageLayer.height);
+
+ let base64Image = this._canvas.toDataURL();
+ deferred.resolve(base64Image);
+ };
+
+ imageBase.onload = onImageLoaded;
+ imageLayer.onload = onImageLoaded;
+ imageBase.src = imageBaseUri;
+ imageLayer.src = imageLayerUri;
+
+ return deferred.promise;
+ }
+}
diff --git a/catalog-ui/app/scripts/directives/graphs-v2/palette/interfaces/i-dragdrop-event.d.ts b/catalog-ui/src/app/directives/graphs-v2/palette/interfaces/i-dragdrop-event.d.ts
index 26c042611c..26c042611c 100644
--- a/catalog-ui/app/scripts/directives/graphs-v2/palette/interfaces/i-dragdrop-event.d.ts
+++ b/catalog-ui/src/app/directives/graphs-v2/palette/interfaces/i-dragdrop-event.d.ts
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
new file mode 100644
index 0000000000..4bfbe5270e
--- /dev/null
+++ b/catalog-ui/src/app/directives/graphs-v2/palette/palette.directive.ts
@@ -0,0 +1,349 @@
+import {
+ Component,
+ IAppMenu,
+ LeftPanelModel,
+ NodesFactory,
+ LeftPaletteComponent,
+ CompositionCiNodeBase,
+ ComponentInstance
+} from "app/models";
+import {CompositionGraphGeneralUtils} from "../composition-graph/utils/composition-graph-general-utils";
+import {EventListenerService} from "app/services";
+import {ResourceType, GRAPH_EVENTS, EVENTS, ComponentInstanceFactory, ModalsHandler} from "app/utils";
+import 'angular-dragdrop';
+import {LeftPaletteLoaderService} from "../../../services/components/utils/composition-left-palette-service";
+
+interface IPaletteScope {
+ components:Array<LeftPaletteComponent>;
+ currentComponent:Component;
+ model:any;
+ displaySortedCategories:any;
+ expandedSection:string;
+ dragElement:JQuery;
+ dragbleNode:{
+ event:JQueryEventObject,
+ components:LeftPaletteComponent,
+ ui:any
+ }
+
+ sectionClick:(section:string)=>void;
+ searchComponents:(searchText:string)=>void;
+ onMouseOver:(displayComponent:LeftPaletteComponent)=>void;
+ onMouseOut:(displayComponent:LeftPaletteComponent)=>void;
+ dragStartCallback:(event:JQueryEventObject, ui, displayComponent:LeftPaletteComponent)=>void;
+ dragStopCallback:()=>void;
+ onDragCallback:(event:JQueryEventObject) => void;
+
+ setElementTemplate:(e:JQueryEventObject)=>void;
+
+ isOnDrag:boolean;
+ isDragable:boolean;
+ isLoading:boolean;
+ isViewOnly:boolean;
+}
+
+export class Palette implements ng.IDirective {
+ constructor(private $log:ng.ILogService,
+ private LeftPaletteLoaderService: LeftPaletteLoaderService,
+ private sdcConfig,
+ private ComponentFactory,
+ private ComponentInstanceFactory:ComponentInstanceFactory,
+ private NodesFactory:NodesFactory,
+ private CompositionGraphGeneralUtils:CompositionGraphGeneralUtils,
+ private EventListenerService:EventListenerService,
+ private sdcMenu:IAppMenu,
+ private ModalsHandler:ModalsHandler) {
+
+ }
+
+ private fetchingComponentFromServer:boolean = false;
+ private nodeHtmlSubstitute:JQuery;
+
+ scope = {
+ currentComponent: '=',
+ isViewOnly: '=',
+ isLoading: '='
+ };
+ restrict = 'E';
+ template = require('./palette.html');
+
+ link = (scope:IPaletteScope, el:JQuery) => {
+ 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);
+ this.initDragEvents(scope);
+ this._initExpandedSection(scope, '');
+ el.on('$destroy', ()=> {
+ //remove listener of download event
+ this.unRegisterEventListenerForLeftPalette(scope);
+ });
+ };
+
+ private registerEventListenerForLeftPalette = (scope:IPaletteScope):void => {
+ if (scope.currentComponent.isResource()) {
+ this.EventListenerService.registerObserverCallback(EVENTS.RESOURCE_LEFT_PALETTE_UPDATE_EVENT, () => {
+ this.updateLeftPanelDisplay(scope);
+ });
+ }
+ if (scope.currentComponent.isService()) {
+ this.EventListenerService.registerObserverCallback(EVENTS.SERVICE_LEFT_PALETTE_UPDATE_EVENT, () => {
+ this.updateLeftPanelDisplay(scope);
+ });
+ }
+ if (scope.currentComponent.isProduct()) {
+ this.EventListenerService.registerObserverCallback(EVENTS.PRODUCT_LEFT_PALETTE_UPDATE_EVENT, () => {
+ this.updateLeftPanelDisplay(scope);
+ });
+ }
+ };
+
+ private unRegisterEventListenerForLeftPalette = (scope:IPaletteScope):void => {
+ if (scope.currentComponent.isResource()) {
+ this.EventListenerService.unRegisterObserver(EVENTS.RESOURCE_LEFT_PALETTE_UPDATE_EVENT);
+ }
+ if (scope.currentComponent.isService()) {
+ this.EventListenerService.unRegisterObserver(EVENTS.SERVICE_LEFT_PALETTE_UPDATE_EVENT);
+ }
+ if (scope.currentComponent.isProduct()) {
+ this.EventListenerService.unRegisterObserver(EVENTS.PRODUCT_LEFT_PALETTE_UPDATE_EVENT);
+ }
+ };
+
+ private leftPanelResourceFilter(resourcesNotAbstract:Array<LeftPaletteComponent>, resourceFilterTypes:Array<string>):Array<LeftPaletteComponent> {
+ let filterResources = _.filter(resourcesNotAbstract, (component) => {
+ return resourceFilterTypes.indexOf(component.getComponentSubType()) > -1;
+ });
+ return filterResources;
+ }
+
+ private initLeftPanel(leftPanelComponents:Array<LeftPaletteComponent>, resourceFilterTypes:Array<string>):LeftPanelModel {
+ let leftPanelModel = new LeftPanelModel();
+
+ if (resourceFilterTypes && resourceFilterTypes.length) {
+ leftPanelComponents = this.leftPanelResourceFilter(leftPanelComponents, resourceFilterTypes);
+ }
+ leftPanelModel.numberOfElements = leftPanelComponents && leftPanelComponents.length || 0;
+
+ if (leftPanelComponents && leftPanelComponents.length) {
+
+ let categories:any = _.groupBy(leftPanelComponents, 'mainCategory');
+ for (let category in categories)
+ categories[category] = _.groupBy(categories[category], 'subCategory');
+
+ leftPanelModel.sortedCategories = categories;
+ }
+ return leftPanelModel;
+ }
+
+
+ private initEvents(scope:IPaletteScope) {
+ /**
+ *
+ * @param section
+ */
+ scope.sectionClick = (section:string) => {
+ if (section === scope.expandedSection) {
+ scope.expandedSection = '';
+ return;
+ }
+ scope.expandedSection = section;
+ };
+
+ scope.onMouseOver = (displayComponent:LeftPaletteComponent) => {
+ if (scope.isOnDrag) {
+ return;
+ }
+ scope.isOnDrag = true;
+
+ this.EventListenerService.notifyObservers(GRAPH_EVENTS.ON_PALETTE_COMPONENT_HOVER_IN, displayComponent);
+ this.$log.debug('palette::onMouseOver:: fired');
+ //
+ // if (this.CompositionGraphGeneralUtils.componentRequirementsAndCapabilitiesCaching.containsKey(displayComponent.uniqueId)) {
+ // this.$log.debug(`palette::onMouseOver:: component id ${displayComponent.uniqueId} found in cache`);
+ // let cacheComponent:Component = this.CompositionGraphGeneralUtils.componentRequirementsAndCapabilitiesCaching.getValue(displayComponent.uniqueId);
+ //
+ // //TODO: Danny: fire event to highlight matching nodes
+ // //showMatchingNodes(cacheComponent);
+ // return;
+ // }
+ //
+ // this.$log.debug(`palette::onMouseOver:: component id ${displayComponent.uniqueId} not found in cache, initiating server get`);
+ // // This will bring the component from the server including requirements and capabilities
+ // // Check that we do not fetch many times, because only in the success we add the component to componentRequirementsAndCapabilitiesCaching
+ // if (this.fetchingComponentFromServer) {
+ // return;
+ // }
+ //
+ // this.fetchingComponentFromServer = true;
+ // this.ComponentFactory.getComponentFromServer(displayComponent.componentSubType, displayComponent.uniqueId)
+ // .then((component:Component) => {
+ // this.$log.debug(`palette::onMouseOver:: component id ${displayComponent.uniqueId} fetch success`);
+ // // this.LeftPaletteLoaderService.updateSpecificComponentLeftPalette(component, scope.currentComponent.componentType);
+ // this.CompositionGraphGeneralUtils.componentRequirementsAndCapabilitiesCaching.setValue(component.uniqueId, component);
+ // this.fetchingComponentFromServer = false;
+ //
+ // //TODO: Danny: fire event to highlight matching nodes
+ // //showMatchingNodes(component);
+ // })
+ // .catch(() => {
+ // this.$log.debug('palette::onMouseOver:: component id fetch error');
+ // this.fetchingComponentFromServer = false;
+ // });
+
+
+ };
+
+ scope.onMouseOut = () => {
+ scope.isOnDrag = false;
+ this.EventListenerService.notifyObservers(GRAPH_EVENTS.ON_PALETTE_COMPONENT_HOVER_OUT);
+ }
+ }
+
+ private initComponents(scope:IPaletteScope) {
+ scope.searchComponents = (searchText:any):void => {
+ scope.displaySortedCategories = this._searchComponents(searchText, scope.model.sortedCategories);
+ this._initExpandedSection(scope, searchText);
+ };
+
+ scope.isDragable = scope.currentComponent.isComplex();
+ this.updateLeftPanelDisplay(scope);
+ }
+
+ private updateLeftPanelDisplay(scope:IPaletteScope) {
+ let entityType:string = scope.currentComponent.componentType.toLowerCase();
+ let resourceFilterTypes:Array<string> = this.sdcConfig.resourceTypesFilter[entityType];
+ scope.components = this.LeftPaletteLoaderService.getLeftPanelComponentsForDisplay(scope.currentComponent.componentType);
+ scope.model = this.initLeftPanel(scope.components, resourceFilterTypes);
+ scope.displaySortedCategories = angular.copy(scope.model.sortedCategories);
+ };
+
+ private _initExpandedSection(scope:IPaletteScope, searchText:string):void {
+ if (searchText == '') {
+ let isContainingCategory:boolean = false;
+ let categoryToExpand:string;
+ if (scope.currentComponent && scope.currentComponent.categories && scope.currentComponent.categories[0]) {
+ categoryToExpand = this.sdcMenu.categoriesDictionary[scope.currentComponent.categories[0].name];
+ for (let category in scope.model.sortedCategories) {
+ if (categoryToExpand == category) {
+ isContainingCategory = true;
+ break;
+ }
+ }
+ }
+ isContainingCategory ? scope.expandedSection = categoryToExpand : scope.expandedSection = 'Generic';
+ }
+ else {
+ scope.expandedSection = Object.keys(scope.displaySortedCategories).sort()[0];
+ }
+ };
+
+ private initDragEvents(scope:IPaletteScope) {
+ scope.dragStartCallback = (event:IDragDropEvent, ui, displayComponent:LeftPaletteComponent):void => {
+ if (scope.isLoading || !scope.isDragable || scope.isViewOnly) {
+ return;
+ }
+
+ let component = _.find(this.LeftPaletteLoaderService.getLeftPanelComponentsForDisplay(scope.currentComponent.componentType), (componentFullData:LeftPaletteComponent) => {
+ return displayComponent.uniqueId === componentFullData.uniqueId;
+ });
+ this.EventListenerService.notifyObservers(GRAPH_EVENTS.ON_PALETTE_COMPONENT_DRAG_START, scope.dragElement, component);
+
+ scope.isOnDrag = true;
+
+ // this.graphUtils.showMatchingNodes(component, myDiagram, scope.sdcConfig.imagesPath);
+ // document.addEventListener('mousemove', moveOnDocument);
+ event.dataTransfer.component = component;
+ };
+
+ scope.dragStopCallback = () => {
+ scope.isOnDrag = false;
+ };
+
+ scope.onDragCallback = (event:IDragDropEvent):void => {
+ this.EventListenerService.notifyObservers(GRAPH_EVENTS.ON_PALETTE_COMPONENT_DRAG_ACTION, event);
+ };
+ scope.setElementTemplate = (e) => {
+ let dragComponent:LeftPaletteComponent = _.find(this.LeftPaletteLoaderService.getLeftPanelComponentsForDisplay(scope.currentComponent.componentType),
+ (fullComponent:LeftPaletteComponent) => {
+ return (<any>angular.element(e.currentTarget).scope()).component.uniqueId === fullComponent.uniqueId;
+ });
+ let componentInstance:ComponentInstance = this.ComponentInstanceFactory.createComponentInstanceFromComponent(dragComponent);
+ let node:CompositionCiNodeBase = this.NodesFactory.createNode(componentInstance);
+
+ // myDiagram.dragFromPalette = node;
+ this.nodeHtmlSubstitute.find("img").attr('src', node.img);
+ scope.dragElement = this.nodeHtmlSubstitute.clone().show();
+
+ return scope.dragElement;
+ };
+ }
+
+ private _searchComponents = (searchText:string, categories:any):void => {
+ let displaySortedCategories = angular.copy(categories);
+ if (searchText != '') {
+ angular.forEach(categories, function (category:any, categoryKey) {
+
+ angular.forEach(category, function (subcategory:Array<LeftPaletteComponent>, subcategoryKey) {
+ let filteredResources = [];
+ angular.forEach(subcategory, function (component:LeftPaletteComponent) {
+
+ let resourceFilterTerm:string = component.searchFilterTerms;
+ if (resourceFilterTerm.indexOf(searchText.toLowerCase()) >= 0) {
+ filteredResources.push(component);
+ }
+ });
+ if (filteredResources.length > 0) {
+ displaySortedCategories[categoryKey][subcategoryKey] = filteredResources;
+ }
+ else {
+ delete displaySortedCategories[categoryKey][subcategoryKey];
+ }
+ });
+ if (!(Object.keys(displaySortedCategories[categoryKey]).length > 0)) {
+ delete displaySortedCategories[categoryKey];
+ }
+
+ });
+ }
+ return displaySortedCategories;
+ };
+
+ public static factory = ($log,
+ LeftPaletteLoaderService,
+ sdcConfig,
+ ComponentFactory,
+ ComponentInstanceFactory,
+ NodesFactory,
+ CompositionGraphGeneralUtils,
+ EventListenerService,
+ sdcMenu,
+ ModalsHandler) => {
+ return new Palette($log,
+ LeftPaletteLoaderService,
+ sdcConfig,
+ ComponentFactory,
+ ComponentInstanceFactory,
+ NodesFactory,
+ CompositionGraphGeneralUtils,
+ EventListenerService,
+ sdcMenu,
+ ModalsHandler);
+ };
+}
+
+Palette.factory.$inject = [
+ '$log',
+ 'LeftPaletteLoaderService',
+ 'sdcConfig',
+ 'ComponentFactory',
+ 'ComponentInstanceFactory',
+ 'NodesFactory',
+ 'CompositionGraphGeneralUtils',
+ 'EventListenerService',
+ 'sdcMenu',
+ 'ModalsHandler'
+];
diff --git a/catalog-ui/app/scripts/directives/graphs-v2/palette/palette.html b/catalog-ui/src/app/directives/graphs-v2/palette/palette.html
index a8dd827927..4b123e5777 100644
--- a/catalog-ui/app/scripts/directives/graphs-v2/palette/palette.html
+++ b/catalog-ui/src/app/directives/graphs-v2/palette/palette.html
@@ -49,11 +49,9 @@
</div>
<div class="i-sdc-designer-leftbar-section-content-item-info-text"> Type:
{{component.componentSubType}}
- <a data-ng-click="openViewerModal(component)"
- class="i-sdc-designer-leftbar-section-content-item-info-text-link hand">More</a>
</div>
</div>
</div>
</div>
</div>
-</div> \ No newline at end of file
+</div>
diff --git a/catalog-ui/app/scripts/directives/graphs-v2/palette/palette.less b/catalog-ui/src/app/directives/graphs-v2/palette/palette.less
index 85657a43a5..85657a43a5 100644
--- a/catalog-ui/app/scripts/directives/graphs-v2/palette/palette.less
+++ b/catalog-ui/src/app/directives/graphs-v2/palette/palette.less
diff --git a/catalog-ui/app/scripts/directives/graphs-v2/relation-menu/relation-menu.html b/catalog-ui/src/app/directives/graphs-v2/relation-menu/relation-menu.html
index a0a9e4af27..a0a9e4af27 100644
--- a/catalog-ui/app/scripts/directives/graphs-v2/relation-menu/relation-menu.html
+++ b/catalog-ui/src/app/directives/graphs-v2/relation-menu/relation-menu.html
diff --git a/catalog-ui/app/scripts/directives/graphs-v2/relation-menu/relation-menu.less b/catalog-ui/src/app/directives/graphs-v2/relation-menu/relation-menu.less
index dea814dbec..dea814dbec 100644
--- a/catalog-ui/app/scripts/directives/graphs-v2/relation-menu/relation-menu.less
+++ b/catalog-ui/src/app/directives/graphs-v2/relation-menu/relation-menu.less
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
new file mode 100644
index 0000000000..b05385b668
--- /dev/null
+++ b/catalog-ui/src/app/directives/graphs-v2/relation-menu/relation-menu.ts
@@ -0,0 +1,103 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+'use strict'
+import {MatchBase, RelationMenuDirectiveObj} from "app/models";
+import {Component} from "../../../models/components/component";
+
+export interface IRelationMenuScope extends ng.IScope {
+ relationMenuDirectiveObj:RelationMenuDirectiveObj;
+ createRelation:Function;
+ isLinkMenuOpen:boolean;
+ hideRelationMatch:Function;
+ cancel:Function;
+
+ saveRelation();
+ showMatch(arr1:Array<MatchBase>, arr2:Array<MatchBase>):boolean;
+ hasMatchesToShow(matchesObj:MatchBase, selectedMatch:Array<MatchBase>);
+ updateSelectionText():void;
+
+}
+
+
+export class RelationMenuDirective implements ng.IDirective {
+
+ constructor(private $filter:ng.IFilterService) {
+ }
+
+ scope = {
+ relationMenuDirectiveObj: '=',
+ isLinkMenuOpen: '=',
+ createRelation: '&',
+ cancel: '&'
+ };
+
+ restrict = 'E';
+ replace = true;
+ template = ():string => {
+ return require('./relation-menu.html');
+ };
+
+ link = (scope:IRelationMenuScope, element:JQuery, $attr:ng.IAttributes) => {
+
+ scope.saveRelation = ():void=> {
+ let chosenMatches:Array<any> = _.intersection(scope.relationMenuDirectiveObj.rightSideLink.selectedMatch, scope.relationMenuDirectiveObj.leftSideLink.selectedMatch);
+ let chosenMatch:MatchBase = chosenMatches[0];
+ scope.createRelation()(chosenMatch);
+ };
+
+
+ scope.hideRelationMatch = () => {
+ scope.isLinkMenuOpen = false;
+ scope.cancel();
+ };
+
+ //to show options in link menu
+ scope.showMatch = (arr1:Array<MatchBase>, arr2:Array<MatchBase>):boolean => {
+ return !arr1 || !arr2 || _.intersection(arr1, arr2).length > 0;
+ };
+
+ //to show requirements/capabilities title
+ scope.hasMatchesToShow = (matchesObj:MatchBase, selectedMatch:Array<MatchBase>):boolean => {
+ let result:boolean = false;
+ _.forEach(matchesObj, (matchesArr:Array<MatchBase>) => {
+ if (!result) {
+ result = scope.showMatch(matchesArr, selectedMatch);
+ }
+ });
+ return result;
+ };
+
+
+ scope.updateSelectionText = ():void => {
+ let left:string = scope.relationMenuDirectiveObj.leftSideLink.selectedMatch ? this.$filter('resourceName')(scope.relationMenuDirectiveObj.leftSideLink.selectedMatch[0].getDisplayText('left')) : '';
+ let both:string = scope.relationMenuDirectiveObj.leftSideLink.selectedMatch && scope.relationMenuDirectiveObj.rightSideLink.selectedMatch ? ' - ' +
+ this.$filter('resourceName')(scope.relationMenuDirectiveObj.leftSideLink.selectedMatch[0].requirement.relationship) + ' - ' : '';
+ let right:string = scope.relationMenuDirectiveObj.rightSideLink.selectedMatch ? this.$filter('resourceName')(scope.relationMenuDirectiveObj.rightSideLink.selectedMatch[0].getDisplayText('right')) : '';
+ scope.relationMenuDirectiveObj.selectionText = left + both + right;
+ };
+
+
+ }
+ public static factory = ($filter:ng.IFilterService)=> {
+ return new RelationMenuDirective($filter);
+ };
+}
+
+RelationMenuDirective.factory.$inject = ['$filter'];
diff --git a/catalog-ui/app/scripts/directives/info-tooltip/info-tooltip.html b/catalog-ui/src/app/directives/info-tooltip/info-tooltip.html
index 5c2bdcf5f1..5c2bdcf5f1 100644
--- a/catalog-ui/app/scripts/directives/info-tooltip/info-tooltip.html
+++ b/catalog-ui/src/app/directives/info-tooltip/info-tooltip.html
diff --git a/catalog-ui/app/scripts/directives/info-tooltip/info-tooltip.less b/catalog-ui/src/app/directives/info-tooltip/info-tooltip.less
index 8811af16a4..cc3e3dc1ec 100644
--- a/catalog-ui/app/scripts/directives/info-tooltip/info-tooltip.less
+++ b/catalog-ui/src/app/directives/info-tooltip/info-tooltip.less
@@ -13,7 +13,7 @@
left: 2px;
}
.info-tooltip-content {
- box-shadow: 0px 3px 6px 0px rgba(0, 0, 0, 0.5);
+ box-shadow: 0px 4px 6px 0px rgba(0, 0, 0, 0.5);
border: 1px solid @main_color_o;
border-radius: 3px;
border-top: 3px solid @main_color_a;
@@ -34,6 +34,9 @@
margin: 15px;
word-break: normal;
font-size: 14px;
+ font-weight: normal;
+ text-align: left;
+ line-height: normal;
}
}
}
diff --git a/catalog-ui/src/app/directives/info-tooltip/info-tooltip.ts b/catalog-ui/src/app/directives/info-tooltip/info-tooltip.ts
new file mode 100644
index 0000000000..63ecdc6091
--- /dev/null
+++ b/catalog-ui/src/app/directives/info-tooltip/info-tooltip.ts
@@ -0,0 +1,37 @@
+/**
+ * Created by rcohen on 9/25/2016.
+ */
+'use strict';
+
+export interface IInfoTooltipScope extends ng.IScope {
+ infoMessageTranslate:string;
+ direction:string;
+}
+
+
+export class InfoTooltipDirective implements ng.IDirective {
+
+ constructor() {
+ }
+
+ scope = {
+ infoMessageTranslate: '@',
+ direction: '@'//get 'right' or 'left', the default is 'right'
+ };
+
+ restrict = 'E';
+ replace = true;
+ template = ():string => {
+ return require('./info-tooltip.html');
+ };
+
+ link = (scope:IInfoTooltipScope, element:any, $attr:any) => {
+ scope.direction = scope.direction || 'right';
+ };
+
+ public static factory = ()=> {
+ return new InfoTooltipDirective();
+ };
+}
+
+InfoTooltipDirective.factory.$inject = [];
diff --git a/catalog-ui/src/app/directives/inputs-and-properties/inputs/input-row-directive.ts b/catalog-ui/src/app/directives/inputs-and-properties/inputs/input-row-directive.ts
new file mode 100644
index 0000000000..221c20d08f
--- /dev/null
+++ b/catalog-ui/src/app/directives/inputs-and-properties/inputs/input-row-directive.ts
@@ -0,0 +1,43 @@
+/**
+ * Created by obarda on 1/8/2017.
+ */
+'use strict';
+
+export interface IInputRowDirective extends ng.IScope {
+ showDeleteIcon:boolean;
+}
+
+
+export class InputRowDirective implements ng.IDirective {
+
+ constructor() {
+
+ }
+
+ scope = {
+ instanceInputsMap: '=',
+ input: '=',
+ instanceName: '=',
+ instanceId: '=',
+ isViewOnly: '=',
+ deleteInput: '&',
+ onNameClicked: '&',
+ onCheckboxClicked: '&'
+ };
+
+ restrict = 'E';
+ replace = true;
+ template = ():string => {
+ return require('./input-row-view.html');
+ };
+
+ link = (scope:IInputRowDirective, element:any, $attr:any) => {
+ scope.showDeleteIcon = $attr.deleteInput ? true : false;
+ };
+
+ public static factory = ()=> {
+ return new InputRowDirective();
+ };
+}
+
+InputRowDirective.factory.$inject = [];
diff --git a/catalog-ui/src/app/directives/inputs-and-properties/inputs/input-row-view.html b/catalog-ui/src/app/directives/inputs-and-properties/inputs/input-row-view.html
new file mode 100644
index 0000000000..872a26bc27
--- /dev/null
+++ b/catalog-ui/src/app/directives/inputs-and-properties/inputs/input-row-view.html
@@ -0,0 +1,43 @@
+<div class="input-row">
+ <div class="title-text" ng-click="onNameClicked(input)" data-tests-id="inputName_{{input.name}}">
+ {{input.name}}
+ </div>
+ <div class="flex-container">
+ <div class="expand-collapse-inputs-table-icon"></div>
+ <div class="flex-item">
+ <div class="no-overflow">
+ <span class="title-text">Description:</span>
+ <span tooltips tooltip-content="{{input.description}}" data-tests-id="inputDescription_{{input.name}}">{{input.description}}</span>
+ </div>
+ <div class="text" tooltips tooltip-content="{{input.defaultValue}}">
+ <span class="title-text">Default Value:</span>
+ <span data-tests-id="inputDefaultValue_{{input.name}}">{{input.defaultValue}}</span>
+ </div>
+ </div>
+ <div class="flex-item ">
+ <div class="text">
+ <span class="title-text">VF Instance:</span>
+ <span tooltips tooltip-content="{{instanceName}}" data-tests-id="inputInstanceName_{{input.name}}">{{instanceName}}</span>
+ </div>
+ <div class="text">
+ <span class="title-text">Type:</span>
+ <span tooltips tooltip-content="{{input.type}}" data-tests-id="inputType_{{input.name}}">{{input.type}} </span>
+ </div>
+ </div>
+ <sdc-checkbox ng-if="instanceInputsMap"
+ class="input-check-box"
+ disabled="input.isAlreadySelected || isViewOnly"
+ sdc-checklist-model="instanceInputsMap[instanceId]"
+ sdc-checklist-value="input"
+ sdc-checklist-change="onCheckboxClicked()"
+ data-tests-id="inputsCheckbox_{{input.name}}"
+ data-ng-click=" $event.stopPropagation()"></sdc-checkbox>
+
+ <div class="delete" ng-if="showDeleteIcon">
+ <span class="sprite-new delete-icon remove-input-icon"
+ data-ng-class="{'disabled': isViewOnly || input.isDeleteDisabled}"
+ data-ng-click="deleteInput(input); $event.stopPropagation();"
+ data-tests-id="deleteInput_{{input.name}}"></span>
+ </div>
+ </div>
+</div>
diff --git a/catalog-ui/src/app/directives/inputs-and-properties/inputs/input-row.less b/catalog-ui/src/app/directives/inputs-and-properties/inputs/input-row.less
new file mode 100644
index 0000000000..fa79b45c3c
--- /dev/null
+++ b/catalog-ui/src/app/directives/inputs-and-properties/inputs/input-row.less
@@ -0,0 +1,54 @@
+&.expanded {
+ .input-row {
+ background-color: @tlv_color_v;
+ }
+}
+
+.input-row {
+ padding-left: 45px;
+ background: @tlv_color_t;
+ border: @main_color_o solid 1px;
+ align-items: center;
+ .hand;
+ margin: 1px 0px 1px 0px;
+
+ &.selected {
+ background-color: @tlv_color_v;
+ }
+ .flex-item {
+ min-height: 60px;
+ padding: 0 15px;
+ }
+ .input-check-box {
+ padding-right: 10px;
+ margin-top: 9px;
+ }
+ & > .title-text {
+ text-align: start;
+ padding: 4px 35px 0 35px;
+ }
+
+ .expand-collapse-inputs-table-icon {
+ margin-top: 15px;
+ }
+
+ .delete {
+ width: 50px;
+ padding: 0;
+ position: relative;
+ }
+
+ .remove-input-icon {
+ position: absolute;
+ top: 12px;
+ right: 18px;
+ }
+
+ .remove-input-icon:hover {
+ .delete-icon-hover;
+ }
+}
+
+.input-row:hover {
+ .bg_j;
+}
diff --git a/catalog-ui/src/app/directives/inputs-and-properties/properties/property-row-directive.ts b/catalog-ui/src/app/directives/inputs-and-properties/properties/property-row-directive.ts
new file mode 100644
index 0000000000..a9ff71cda5
--- /dev/null
+++ b/catalog-ui/src/app/directives/inputs-and-properties/properties/property-row-directive.ts
@@ -0,0 +1,42 @@
+/**
+ * Created by obarda on 1/8/2017.
+ */
+'use strict';
+
+export interface IPropertyRowDirective extends ng.IScope {
+ onNameClicked:Function;
+ isClickable:boolean;
+}
+
+export class PropertyRowDirective implements ng.IDirective {
+
+ constructor() {
+
+ }
+
+ scope = {
+ property: '=',
+ instanceName: '=',
+ instanceId: '=',
+ instancePropertiesMap: '=',
+ onNameClicked: '&',
+ onCheckboxClicked: '&'
+ };
+
+ restrict = 'E';
+ replace = true;
+ template = ():string => {
+ return require('./property-row-view.html');
+ };
+
+ link = (scope:IPropertyRowDirective, element:any, $attr:any) => {
+ scope.isClickable = $attr.onNameClicked ? true : false;
+ };
+
+ public static factory = ()=> {
+ return new PropertyRowDirective();
+ };
+
+}
+
+PropertyRowDirective.factory.$inject = [];
diff --git a/catalog-ui/src/app/directives/inputs-and-properties/properties/property-row-view.html b/catalog-ui/src/app/directives/inputs-and-properties/properties/property-row-view.html
new file mode 100644
index 0000000000..ff82a8b685
--- /dev/null
+++ b/catalog-ui/src/app/directives/inputs-and-properties/properties/property-row-view.html
@@ -0,0 +1,26 @@
+<div class="property-row flex-container">
+ <div class="flex-item text property-name-container">
+ <span class="title-blue-text property-name-text " data-ng-class="{'hand': isClickable}" data-tests-id="propertyName" data-ng-click="onNameClicked(property)" tooltips tooltip-content="{{property.name}}">{{property.name}}</span>
+ </div>
+ <div class="flex-item text property-name-container">
+ <span class="text instance-name-text" data-tests-id="instanceName" tooltips tooltip-content="{{instanceName}}">{{instanceName}}</span>
+ </div>
+ <div class="type-schema-container">
+ <div class="text">
+ <span tooltips tooltip-content="propertyName_{{property.type}}" data-tests-id="propertyType">{{property.type}}</span>
+ </div>
+ </div>
+ <div class="type-schema-container">
+ <div class="text">
+ <span tooltips tooltip-content="{{property.schema.property.type}}" data-tests-id="propertySchema">{{property.schema.property.type}} </span>
+ </div>
+ </div>
+ <sdc-checkbox ng-if="instancePropertiesMap"
+ class="property-check-box"
+ disabled="property.isAlreadySelected || isViewOnly"
+ sdc-checklist-model="instancePropertiesMap[instanceId]"
+ sdc-checklist-value="property"
+ sdc-checklist-change="onCheckboxClicked()"
+ data-tests-id="propertyCheckbox_{{property.name}}"
+ data-ng-click=" $event.stopPropagation()"></sdc-checkbox>
+</div>
diff --git a/catalog-ui/src/app/directives/inputs-and-properties/properties/property-row-view.less b/catalog-ui/src/app/directives/inputs-and-properties/properties/property-row-view.less
new file mode 100644
index 0000000000..e25427bda2
--- /dev/null
+++ b/catalog-ui/src/app/directives/inputs-and-properties/properties/property-row-view.less
@@ -0,0 +1,35 @@
+.property-row {
+ border-bottom: 1px solid @border_color_d;
+ padding-left: 10px;
+ .property-name-container {
+ display: flex;
+ flex-grow: 3;
+ }
+
+ .type-schema-container {
+ flex-grow: 2;
+ border-left: 1px solid @border_color_d;
+ text-align: left;
+ line-height: 30px;
+ text-transform: capitalize;
+ width: 10px;
+ }
+
+ .property-check-box {
+ padding-right: 10px;
+ margin-top: 9px;
+ }
+}
+
+.property-row:hover {
+ background-color: @func_color_r;
+}
+
+&.expanded {
+ .flex-container {
+ .expand-collapse-inputs-table-icon {
+ transform: rotate(180deg);
+ left: 0px;
+ }
+ }
+}
diff --git a/catalog-ui/src/app/directives/invalid-characters/invalid-characters.ts b/catalog-ui/src/app/directives/invalid-characters/invalid-characters.ts
new file mode 100644
index 0000000000..20ed71e53f
--- /dev/null
+++ b/catalog-ui/src/app/directives/invalid-characters/invalid-characters.ts
@@ -0,0 +1,51 @@
+'use strict';
+
+export class InvalidCharactersDirective implements ng.IDirective {
+
+ constructor() {
+ }
+
+ require = 'ngModel';
+
+ link = (scope, elem, attrs, ngModel) => {
+
+ let invalidCharacters = [];
+
+ attrs.$observe('invalidCharacters', (val:string) => {
+ invalidCharacters = val.split('');
+ validate(ngModel.$viewValue);
+ });
+
+ let validate:Function = function (value) {
+
+ let valid:boolean = true;
+
+ if (value) {
+ for (let i = 0; i < invalidCharacters.length; i++) {
+ if (value.indexOf(invalidCharacters[i]) != -1) {
+ valid = false;
+ }
+ }
+ }
+
+ ngModel.$setValidity('invalidCharacters', valid);
+ if (!value) {
+ ngModel.$setPristine();
+ }
+ return value;
+ };
+
+ //For DOM -> model validation
+ ngModel.$parsers.unshift(validate);
+ //For model -> DOM validation
+ ngModel.$formatters.unshift(validate);
+
+ };
+
+ public static factory = ()=> {
+ return new InvalidCharactersDirective();
+ };
+
+}
+
+InvalidCharactersDirective.factory.$inject = [];
diff --git a/catalog-ui/app/scripts/directives/layout/top-nav/top-nav.html b/catalog-ui/src/app/directives/layout/top-nav/top-nav.html
index 40b1e86d90..60d3d63855 100644
--- a/catalog-ui/app/scripts/directives/layout/top-nav/top-nav.html
+++ b/catalog-ui/src/app/directives/layout/top-nav/top-nav.html
@@ -1,7 +1,7 @@
<nav class="top-nav">
<div class="asdc-app-title-wrapper">
- <a class="asdc-app-title">SDC</a> <!-- data-ui-sref="dashboard" -->
+ <a class="asdc-app-title" translate="PROJECT_TITLE"></a>
<div class="asdc-version"> v.{{version}}</div>
</div>
diff --git a/catalog-ui/app/scripts/directives/layout/top-nav/top-nav.less b/catalog-ui/src/app/directives/layout/top-nav/top-nav.less
index 65021bdc4d..65021bdc4d 100644
--- a/catalog-ui/app/scripts/directives/layout/top-nav/top-nav.less
+++ b/catalog-ui/src/app/directives/layout/top-nav/top-nav.less
diff --git a/catalog-ui/src/app/directives/layout/top-nav/top-nav.ts b/catalog-ui/src/app/directives/layout/top-nav/top-nav.ts
new file mode 100644
index 0000000000..c7208a909a
--- /dev/null
+++ b/catalog-ui/src/app/directives/layout/top-nav/top-nav.ts
@@ -0,0 +1,141 @@
+'use strict';
+import {IAppConfigurtaion, IHostedApplication, IUserProperties} from "app/models";
+import {IUserResourceClass} from "app/services";
+import {MenuItemGroup, MenuItem} from "app/utils";
+
+export interface ITopNavScope extends ng.IScope {
+ topLvlSelectedIndex:number;
+ hideSearch:boolean;
+ searchBind:any;
+ menuModel:Array<MenuItemGroup>;
+
+ topLvlMenu:MenuItemGroup;
+ goToState(state:string, params:Array<any>):ng.IPromise<boolean>;
+ menuItemClick:Function;
+ user:IUserProperties;
+ version:string;
+}
+
+
+export class TopNavDirective implements ng.IDirective {
+
+ constructor(private $filter:ng.IFilterService,
+ private $state:ng.ui.IStateService,
+ private $q:ng.IQService,
+ private userResourceService:IUserResourceClass,
+ private sdcConfig:IAppConfigurtaion) {
+ }
+
+ public replace = true;
+ public restrict = 'E';
+ public transclude = false;
+
+
+ scope = {
+ topLvlSelectedIndex: '@?',
+ hideSearch: '=',
+ searchBind: '=',
+ version: '@',
+ notificationIconCallback: '=',
+ menuModel: '=?',
+ };
+
+ template = ():string => {
+ return require('./top-nav.html');
+ };
+
+ public link = (scope:ITopNavScope, $elem:ng.IAugmentedJQuery, $attrs:angular.IAttributes) => {
+
+ let getTopLvlSelectedIndexByState = ():number => {
+ if (!scope.topLvlMenu.menuItems) {
+ return 0;
+ }
+
+ let result = -1;
+
+ //set result to current state
+ scope.topLvlMenu.menuItems.forEach((item:MenuItem, index:number)=> {
+ if (item.state === this.$state.current.name) {
+ result = index;
+ }
+ });
+
+ //if it's a different state , checking previous state param
+ if (result === -1) {
+ scope.topLvlMenu.menuItems.forEach((item:MenuItem, index:number)=> {
+ if (item.state === this.$state.params['previousState']) {
+ result = index;
+ }
+ });
+ }
+
+ if (result === -1) {
+ result = 0;
+ }
+
+ return result;
+ };
+
+ scope.user = this.userResourceService.getLoggedinUser();
+
+ let tmpArray:Array<MenuItem> = [
+ new MenuItem(this.$filter('translate')("TOP_MENU_HOME_BUTTON"), null, "dashboard", "goToState", null, null),
+ new MenuItem(this.$filter('translate')("TOP_MENU_CATALOG_BUTTON"), null, "catalog", "goToState", null, null)
+ ];
+
+ // Only designer can perform onboarding
+ if (scope.user && scope.user.role === 'DESIGNER') {
+ tmpArray.push(new MenuItem(this.$filter('translate')("TOP_MENU_ON_BOARD_BUTTON"), null, "onboardVendor", "goToState", null, null));
+ _.each(this.sdcConfig.hostedApplications, (hostedApp:IHostedApplication)=> {
+ if (hostedApp.exists) {
+ tmpArray.push(new MenuItem(hostedApp.navTitle, null, hostedApp.defaultState, "goToState", null, null));
+ }
+ });
+ }
+
+ scope.topLvlMenu = new MenuItemGroup(0, tmpArray, true);
+ scope.topLvlMenu.selectedIndex = isNaN(scope.topLvlSelectedIndex) ? getTopLvlSelectedIndexByState() : scope.topLvlSelectedIndex;
+
+ let generateMenu = () => {
+ if (scope.menuModel && scope.menuModel[0] !== scope.topLvlMenu) {
+ scope.menuModel.unshift(scope.topLvlMenu);
+ }
+ };
+ scope.$watch('menuModel', generateMenu);
+
+ generateMenu();
+
+ /////scope functions////
+
+ scope.goToState = (state:string, params:Array<any>):ng.IPromise<boolean> => {
+ let deferred = this.$q.defer();
+ this.$state.go(state, params && params.length > 0 ? [0] : undefined);
+ deferred.resolve(true);
+ return deferred.promise;
+ };
+
+ scope.menuItemClick = (itemGroup:MenuItemGroup, item:MenuItem) => {
+
+ itemGroup.itemClick = false;
+
+ let onSuccess = ():void => {
+ itemGroup.selectedIndex = itemGroup.menuItems.indexOf(item);
+ };
+ let onFailed = ():void => {
+ };
+
+ if (item.callback) {
+ (item.callback.apply(undefined, item.params)).then(onSuccess, onFailed);
+ } else {
+ scope[item.action](item.state, item.params).then(onSuccess, onFailed);
+ }
+ };
+ };
+
+ public static factory = ($filter:ng.IFilterService, $state:ng.ui.IStateService, $q:ng.IQService, userResourceService:IUserResourceClass, sdcConfig:IAppConfigurtaion)=> {
+ return new TopNavDirective($filter, $state, $q, userResourceService, sdcConfig);
+ };
+
+}
+
+TopNavDirective.factory.$inject = ['$filter', '$state', '$q', 'Sdc.Services.UserResourceService', 'sdcConfig'];
diff --git a/catalog-ui/app/scripts/directives/layout/top-progress/top-progress.html b/catalog-ui/src/app/directives/layout/top-progress/top-progress.html
index ab2c8e364e..ab2c8e364e 100644
--- a/catalog-ui/app/scripts/directives/layout/top-progress/top-progress.html
+++ b/catalog-ui/src/app/directives/layout/top-progress/top-progress.html
diff --git a/catalog-ui/app/scripts/directives/layout/top-progress/top-progress.less b/catalog-ui/src/app/directives/layout/top-progress/top-progress.less
index acce826f80..ce70bd7378 100644
--- a/catalog-ui/app/scripts/directives/layout/top-progress/top-progress.less
+++ b/catalog-ui/src/app/directives/layout/top-progress/top-progress.less
@@ -3,6 +3,8 @@
.sdc-progress-title {
.n_12_r;
+ height: 17px;
+ display: block;
.progress-percentage {
float: right;
diff --git a/catalog-ui/src/app/directives/layout/top-progress/top-progress.ts b/catalog-ui/src/app/directives/layout/top-progress/top-progress.ts
new file mode 100644
index 0000000000..06beb43ea1
--- /dev/null
+++ b/catalog-ui/src/app/directives/layout/top-progress/top-progress.ts
@@ -0,0 +1,36 @@
+'use strict';
+
+export interface ITopProgressScope extends ng.IScope {
+ progressValue:number;
+ progressMessage:string;
+}
+
+export class TopProgressDirective implements ng.IDirective {
+
+ constructor() {
+ }
+
+ public replace = true;
+ public restrict = 'E';
+ public transclude = false;
+
+ scope = {
+ progressValue: '=',
+ progressMessage: '='
+ };
+
+ template = ():string => {
+ return require('./top-progress.html');
+ };
+
+ public link = (scope:ITopProgressScope, $elem:ng.IAugmentedJQuery, $attrs:angular.IAttributes) => {
+
+ };
+
+ public static factory = ()=> {
+ return new TopProgressDirective();
+ };
+
+}
+
+TopProgressDirective.factory.$inject = [];
diff --git a/catalog-ui/app/scripts/directives/loader/loader-directive.html b/catalog-ui/src/app/directives/loader/loader-directive.html
index e40b059a57..e40b059a57 100644
--- a/catalog-ui/app/scripts/directives/loader/loader-directive.html
+++ b/catalog-ui/src/app/directives/loader/loader-directive.html
diff --git a/catalog-ui/app/scripts/directives/loader/loader-directive.less b/catalog-ui/src/app/directives/loader/loader-directive.less
index ae0b41aab1..ae0b41aab1 100644
--- a/catalog-ui/app/scripts/directives/loader/loader-directive.less
+++ b/catalog-ui/src/app/directives/loader/loader-directive.less
diff --git a/catalog-ui/src/app/directives/loader/loader-directive.ts b/catalog-ui/src/app/directives/loader/loader-directive.ts
new file mode 100644
index 0000000000..aa9c4b09c4
--- /dev/null
+++ b/catalog-ui/src/app/directives/loader/loader-directive.ts
@@ -0,0 +1,155 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+'use strict';
+import {EVENTS} from "app/utils";
+import {EventListenerService} from "app/services";
+
+export interface ILoaderScope extends ng.IScope {
+ display:boolean; // Toggle show || hide scroll
+ size:string; // small || medium || large
+ elementSelector:string; // Jquery selector to hide and scroll inside
+ relative:boolean; // Will use the parent of <loader> element and hide it and scroll inside
+ loaderType:string;
+}
+
+export class LoaderDirective implements ng.IDirective {
+
+ constructor(private EventListenerService:EventListenerService) {
+ }
+
+ /*
+ * relative is used when inserting the HTML loader inside some div <loader data-display="isLoading" relative="true"></loader>
+ * elementSelector when we want to pass the Jquery selector of the loader.
+ */
+ scope = {
+ display: '=',
+ size: '@?',
+ elementSelector: '@?',
+ relative: '=?',
+ loaderType: '@?'
+ };
+
+ public replace = false;
+ public restrict = 'E';
+ template = ():string => {
+ return require('./loader-directive.html');
+ }
+
+ link = (scope:ILoaderScope, element:any) => {
+
+ let interval;
+
+ this.EventListenerService.registerObserverCallback(EVENTS.SHOW_LOADER_EVENT, (loaderType)=> {
+ if (scope.loaderType !== loaderType) {
+ return;
+ }
+ scope.display = true;
+ });
+ this.EventListenerService.registerObserverCallback(EVENTS.HIDE_LOADER_EVENT, (loaderType)=> {
+ if (scope.loaderType !== loaderType) {
+ return;
+ }
+ scope.display = false;
+ });
+
+ let calculateSizesForFixPosition = (positionStyle:string):void => {
+ // This is problematic, I do not want to change the parent position.
+ // set the loader on all the screen
+ let parentPosition = element.parent().position();
+ let parentWidth = element.parent().width();
+ let parentHeight = element.parent().height();
+ element.css('position', positionStyle);
+ element.css('top', parentPosition.top);
+ element.css('left', parentPosition.left);
+ element.css('width', parentWidth);
+ element.css('height', parentHeight);
+ };
+
+ let setStyle = (positionStyle:string):void => {
+
+ switch (positionStyle) {
+ case 'absolute':
+ case 'fixed':
+ // The parent size is not set yet, still loading, so need to use interval to update the size.
+ interval = window.setInterval(()=> {
+ calculateSizesForFixPosition(positionStyle);
+ }, 2000);
+ break;
+ default:
+ // Can change the parent position to relative without causing style issues.
+ element.parent().css('position', 'relative');
+ break;
+ }
+ };
+
+ // This should be executed after the dom loaded
+ window.setTimeout(():void => {
+
+ element.css('display', 'none');
+
+ if (scope.elementSelector) {
+ let elemParent = angular.element(scope.elementSelector);
+ let positionStyle:string = elemParent.css('position');
+ setStyle(positionStyle);
+ }
+
+ if (scope.relative === true) {
+ let positionStyle:string = element.parent().css('position');
+ setStyle(positionStyle);
+ }
+
+ if (!scope.size) {
+ scope.size = 'large';
+ }
+
+ }, 0);
+
+ if (scope.elementSelector) {
+
+ }
+
+ function cleanUp() {
+ clearInterval(interval);
+ }
+
+ scope.$watch("display", (newVal, oldVal) => {
+ element.css('display', 'none');
+ if (newVal === true) {
+ window.setTimeout(():void => {
+ element.css('display', 'block');
+ }, 500);
+ } else {
+ window.setTimeout(():void => {
+ element.css('display', 'none');
+ }, 0);
+ }
+ });
+
+ scope.$on('$destroy', cleanUp);
+
+ };
+
+ public static factory = (EventListenerService:EventListenerService)=> {
+ return new LoaderDirective( EventListenerService);
+ };
+
+}
+
+LoaderDirective.factory.$inject = ['EventListenerService'];
diff --git a/catalog-ui/app/scripts/directives/modal/sdc-modal.html b/catalog-ui/src/app/directives/modal/sdc-modal.html
index a8419f162d..a8419f162d 100644
--- a/catalog-ui/app/scripts/directives/modal/sdc-modal.html
+++ b/catalog-ui/src/app/directives/modal/sdc-modal.html
diff --git a/catalog-ui/app/scripts/directives/modal/sdc-modal.less b/catalog-ui/src/app/directives/modal/sdc-modal.less
index d8dfdbb73b..d8dfdbb73b 100644
--- a/catalog-ui/app/scripts/directives/modal/sdc-modal.less
+++ b/catalog-ui/src/app/directives/modal/sdc-modal.less
diff --git a/catalog-ui/src/app/directives/modal/sdc-modal.ts b/catalog-ui/src/app/directives/modal/sdc-modal.ts
new file mode 100644
index 0000000000..aedc28262f
--- /dev/null
+++ b/catalog-ui/src/app/directives/modal/sdc-modal.ts
@@ -0,0 +1,80 @@
+'use strict';
+
+export interface ISdcModalScope extends ng.IScope {
+ modal:ng.ui.bootstrap.IModalServiceInstance;
+ hideBackground:string;
+ ok():void;
+ close(result:any):void;
+ cancel(reason:any):void;
+}
+
+export interface ISdcModalButton {
+ name:string;
+ css:string;
+ disabled?:boolean;
+ callback:Function;
+}
+
+export class SdcModalDirective implements ng.IDirective {
+
+ constructor() {
+ }
+
+ scope = {
+ modal: '=',
+ type: '@',
+ header: '@',
+ headerTranslate: '@',
+ headerTranslateValues: '@',
+ showCloseButton: '@',
+ hideBackground: '@',
+ buttons: '=',
+ getCloseModalResponse: '='
+ };
+
+ public replace = true;
+ public restrict = 'E';
+ public transclude = true;
+
+ template = ():string => {
+ return require('./sdc-modal.html');
+ };
+
+ link = (scope:ISdcModalScope, $elem:any) => {
+
+ if (scope.hideBackground === "true") {
+ $(".modal-backdrop").css('opacity', '0');
+ }
+
+ scope.close = function (result:any) {
+ scope.modal.close(result);
+ };
+
+ scope.ok = function () {
+ scope.modal.close();
+ };
+
+ scope.cancel = function (reason:any) {
+ if (this.getCloseModalResponse)
+ scope.modal.dismiss(this.getCloseModalResponse());
+ else {
+ scope.modal.dismiss();
+ }
+ };
+
+ if (scope.modal) {
+ scope.modal.result.then(function (selectedItem) {
+ //$scope.selected = selectedItem;
+ }, function () {
+ //console.info('Modal dismissed at: ' + new Date());
+ });
+ }
+ }
+
+ public static factory = ()=> {
+ return new SdcModalDirective();
+ };
+
+}
+
+SdcModalDirective.factory.$inject = [];
diff --git a/catalog-ui/src/app/directives/perfect-scrollbar/angular-perfect-scrollbar.ts b/catalog-ui/src/app/directives/perfect-scrollbar/angular-perfect-scrollbar.ts
new file mode 100644
index 0000000000..914a7049bb
--- /dev/null
+++ b/catalog-ui/src/app/directives/perfect-scrollbar/angular-perfect-scrollbar.ts
@@ -0,0 +1,125 @@
+'use strict';
+
+export interface IPerfectScrollerScope extends ng.IScope {
+ //update(event:string): void;
+}
+
+export class PerfectScrollerDirective implements ng.IDirective {
+
+ constructor(private $parse:any) {
+
+ }
+
+ replace = true;
+ restrict = 'EA';
+ transclude = true;
+
+ template = ():string => {
+ return '<div><div ng-transclude=""></div></div>';
+ };
+
+ link = ($scope:IPerfectScrollerScope, $elem, $attr) => {
+ let self = this;
+ let options = {};
+
+ let psOptions = [
+ 'wheelSpeed', 'wheelPropagation', 'minScrollbarLength', 'useBothWheelAxes',
+ 'useKeyboard', 'suppressScrollX', 'suppressScrollY', 'scrollXMarginOffset',
+ 'scrollYMarginOffset', 'includePadding'//, 'onScroll', 'scrollDown'
+ ];
+
+ for (let i = 0, l = psOptions.length; i < l; i++) {
+ let opt = psOptions[i];
+ if ($attr[opt] !== undefined) {
+ options[opt] = self.$parse($attr[opt])();
+ }
+ }
+
+ $scope.$evalAsync(function () {
+ $elem.perfectScrollbar(options);
+ let onScrollHandler = self.$parse($attr.onScroll)
+ $elem.scroll(function () {
+ let scrollTop = $elem.scrollTop()
+ let scrollHeight = $elem.prop('scrollHeight') - $elem.height()
+ $scope.$apply(function () {
+ onScrollHandler($scope, {
+ scrollTop: scrollTop,
+ scrollHeight: scrollHeight
+ })
+ })
+ });
+ });
+
+ /*
+ $scope.update = (event:string): void => {
+ $scope.$evalAsync(function() {
+ //if ($attr.scrollDown == 'true' && event != 'mouseenter') {
+ if (event != 'mouseenter') {
+ setTimeout(function () {
+ $($elem).scrollTop($($elem).prop("scrollHeight"));
+ }, 100);
+ }
+ $elem.perfectScrollbar('update');
+ });
+ };
+ */
+
+ // This is necessary when you don't watch anything with the scrollbar
+ $elem.bind('mouseenter', function () {
+ //console.log("mouseenter");
+ $elem.perfectScrollbar('update');
+ });
+
+ $elem.bind('mouseleave', function () {
+ //console.log("mouseleave");
+ setTimeout(function () {
+ $(window).trigger('mouseup');
+ $elem.perfectScrollbar('update');
+ }, 10);
+ });
+
+ $elem.bind('click', function () {
+ //console.log("click");
+ // Wait 500 milliseconds until the collapse finish closing and update.
+ setTimeout(function () {
+ $elem.perfectScrollbar('update');
+ }, 500);
+ });
+
+ /**
+ * Check if the content of the scroller was changed, and if changed update the scroller.
+ * Because DOMSubtreeModified event is fire many time (while filling the content), I'm checking that
+ * there is at least 100 milliseconds between DOMSubtreeModified events to update the scrollbar.
+ * @type {boolean}
+ */
+ let insideDOMSubtreeModified = false;
+ $elem.bind('DOMSubtreeModified', function () {
+ if (insideDOMSubtreeModified == false) {
+ insideDOMSubtreeModified = true;
+ setTimeout(function () {
+ insideDOMSubtreeModified = false;
+ $elem.perfectScrollbar('update');
+ }, 100);
+ }
+ });
+
+ // Possible future improvement - check the type here and use the appropriate watch for non-arrays
+ if ($attr.refreshOnChange) {
+ $scope.$watchCollection($attr.refreshOnChange, function () {
+ $elem.perfectScrollbar('update');
+ });
+ }
+
+ $elem.bind('$destroy', function () {
+ $elem.perfectScrollbar('destroy');
+ });
+
+ };
+
+ public static factory = ($parse:any)=> {
+ return new PerfectScrollerDirective($parse);
+ };
+
+}
+
+PerfectScrollerDirective.factory.$inject = ['$parse'];
diff --git a/catalog-ui/src/app/directives/print-graph-screen/print-graph-screen.ts b/catalog-ui/src/app/directives/print-graph-screen/print-graph-screen.ts
new file mode 100644
index 0000000000..a6e07eefee
--- /dev/null
+++ b/catalog-ui/src/app/directives/print-graph-screen/print-graph-screen.ts
@@ -0,0 +1,190 @@
+'use strict';
+import {IAppMenu, Component, IAppConfigurtaion} from "app/models";
+import {UrlToBase64Service} from "app/services";
+
+export interface IPrintGraphScreenScope extends ng.IScope {
+ entity:Component;
+}
+
+
+export class PrintGraphScreenDirective implements ng.IDirective {
+
+ constructor(private $filter:ng.IFilterService,
+ private sdcMenu:IAppMenu,
+ private sdcConfig:IAppConfigurtaion,
+ private urlToBase64Service:UrlToBase64Service) {
+ }
+
+ scope = {
+ entity: '='
+ };
+ restrict = 'A';
+ link = (scope:IPrintGraphScreenScope, element:any) => {
+
+
+ element.bind('click', function () {
+ printScreen();
+ });
+
+
+ let printScreen = ():void => {
+ //
+ // let pdf :any = new jsPDF('landscape', 'mm', 'a4');
+ // pdf.setProperties({
+ // title: scope.entity.name,
+ // subject: 'Design Snapshot for ' + scope.entity.name,
+ // author: scope.entity.creatorFullName,
+ // keywords: scope.entity.tags.join(', '),
+ // creator: scope.entity.creatorFullName
+ // });
+ //
+ // // A4 measures is 210 × 297 millimeters
+ // let pdfWidth :number = 297,
+ // pdfHeight :number = 210,
+ // leftColumnWidth :number = 80;
+ //
+ // //left bar background
+ // pdf.setDrawColor(0);
+ // pdf.setFillColor(248, 249, 251);
+ // pdf.rect(0, 0, leftColumnWidth, pdfHeight, 'F');
+ //
+ // //entity name
+ // pdf.setFontSize(12);
+ // pdf.setTextColor(38, 61, 77);
+ // let splitTitle :any = pdf.splitTextToSize(scope.entity.name, 50);
+ // pdf.text(22, 15 - (splitTitle.length - 1) * 2, splitTitle);
+ //
+ // //line
+ // pdf.setLineWidth(0.2);
+ // pdf.setDrawColor(208, 209, 213);
+ // pdf.line(0, 28, leftColumnWidth, 28);
+ //
+ //
+ // pdf.setFontSize(10);
+ // let properties :any = getPdfProperties();
+ //
+ // let topOffset :number = 39, lines;
+ // properties.forEach( (item:any) => {
+ // if (!item.value) {
+ // return;
+ // }
+ // if (item.title === 'Description:') {
+ // topOffset += 5;
+ // }
+ //
+ // pdf.setTextColor(38, 61, 77);
+ // pdf.text(5, topOffset, item.title);
+ // pdf.setTextColor(102, 102, 102);
+ // lines = pdf.splitTextToSize(item.value, 49);
+ // pdf.text(5 + item.offset, topOffset, lines[0]);
+ // if (lines.length > 1) {
+ // lines = pdf.splitTextToSize(item.value.substring(lines[0].length + 1), 65);
+ // if (lines.length > 8) {
+ // lines = lines.slice(0, 7);
+ // lines[lines.length - 1] += '...';
+ // }
+ // pdf.text(5, topOffset + 4, lines);
+ // topOffset += 4 * (lines.length);
+ // }
+ //
+ // topOffset += 6;
+ // });
+ //
+ //
+ // //another background in case the text was too long
+ // let declarationLineOffset :number = 176;
+ // pdf.setDrawColor(0);
+ // pdf.setFillColor(248, 249, 251);
+ // pdf.rect(0, declarationLineOffset, leftColumnWidth, pdfHeight - declarationLineOffset, 'F');
+ // //line
+ // pdf.setLineWidth(0.2);
+ // pdf.setDrawColor(208, 209, 213);
+ // pdf.line(0, declarationLineOffset, leftColumnWidth, declarationLineOffset);
+ //
+ // //declaration
+ // pdf.setFontSize(10.5);
+ // pdf.setTextColor(38, 61, 77);
+ // pdf.text(5, 185, 'Declaration');
+ // pdf.setFontSize(9);
+ // pdf.setTextColor(102, 102, 102);
+ // pdf.setFontType('bold');
+ // pdf.text(5, 190, this.$filter('translate')('PDF_FILE_DECLARATION_BOLD'));
+ // pdf.setFontType('normal');
+ // pdf.text(5, 194, pdf.splitTextToSize(this.$filter('translate')('PDF_FILE_DECLARATION'), 65));
+ //
+ // //entity icon
+ // let self = this;
+ // let addEntityIcon:Function = () => {
+ // let iconPath:string = self.sdcConfig.imagesPath + '/styles/images/';
+ // if (scope.entity.isService()) {
+ // iconPath += 'service-icons/' + scope.entity.icon + '.png';
+ // } else {
+ // iconPath += 'resource-icons/' + scope.entity.icon + '.png';
+ // }
+ // self.urlToBase64Service.downloadUrl(iconPath, (base64string:string):void => {
+ // if (base64string) {
+ // pdf.addImage(base64string, 'JPEG', 5, 7, 15, 15);
+ // }
+ // pdf.save(scope.entity.name + '.pdf');
+ // });
+ // };
+ //
+ // //actual snapshop of canvas
+ // let diagramDiv :any = document.getElementById('myDiagram');
+ // let diagram :go.Diagram = go.Diagram.fromDiv(diagramDiv), canvasImg = new Image();
+ // diagram.startTransaction('print screen');
+ // let canvasImgBase64:any = diagram.makeImageData({
+ // //scale: 1,
+ // size: new go.Size(pdfHeight * 5, NaN),
+ // background: 'white',
+ // type: 'image/jpeg'
+ // });
+ // diagramDiv.firstElementChild.toDataURL();
+ // diagram.commitTransaction('print screen');
+ //
+ // canvasImg.onload = () => {
+ // if (canvasImg.height > 0) {
+ // let canvasImgRatio:number = Math.min((pdfWidth - leftColumnWidth - 15) / canvasImg.width, pdfHeight / canvasImg.height);
+ // let canvasImgWidth:number = canvasImg.width * canvasImgRatio,
+ // canvasImgHeight:number = canvasImg.height * canvasImgRatio;
+ // let canvasImgOffset:number = (pdfHeight - canvasImgHeight) / 2;
+ // pdf.addImage(canvasImg, 'JPEG', leftColumnWidth, canvasImgOffset, canvasImgWidth, canvasImgHeight);
+ //
+ // addEntityIcon();
+ // }
+ // };
+ //
+ // if(canvasImg.src === 'data:,') { //empty canvas
+ // addEntityIcon();
+ // } else {
+ // canvasImg.src = canvasImgBase64;
+ // }
+ };
+
+
+ let getPdfProperties = ():Array<any> => {
+ // return [
+ // {title: this.$filter('translate')('GENERAL_LABEL_TYPE'), value: scope.entity.getComponentSubType(), offset: 10},
+ // {title: this.$filter('translate')('GENERAL_LABEL_VERSION'), value: scope.entity.version, offset: 15},
+ // {title: this.$filter('translate')('GENERAL_LABEL_CATEGORY'), value: scope.entity.categories.length ? scope.entity.categories[0].name : '', offset: 16},
+ // {title: this.$filter('translate')('GENERAL_LABEL_CREATION_DATE'), value: this.$filter('date')(scope.entity.creationDate, 'MM/dd/yyyy'), offset: 24},
+ // {title: this.$filter('translate')('GENERAL_LABEL_AUTHOR'), value: scope.entity.creatorFullName, offset: 13},
+ // {title: this.$filter('translate')('GENERAL_LABEL_CONTACT_ID'), value: scope.entity.contactId, offset: 41},
+ // {title: this.$filter('translate')('GENERAL_LABEL_STATUS'), value: (<any>this.sdcMenu).LifeCycleStatuses[scope.entity.lifecycleState].text, offset: 13},
+ // {title: this.$filter('translate')('GENERAL_LABEL_PROJECT_CODE'), value: scope.entity.projectCode, offset: 15},
+ // {title: this.$filter('translate')('GENERAL_LABEL_DESCRIPTION'), value: scope.entity.description, offset: 20},
+ // {title: this.$filter('translate')('GENERAL_LABEL_TAGS'), value: scope.entity.tags.join(', '), offset: 10}
+ // ];
+ return null;
+ };
+
+
+ };
+
+ public static factory = ($filter:ng.IFilterService, sdcMenu:IAppMenu, sdcConfig:IAppConfigurtaion, urlToBase64Service:UrlToBase64Service)=> {
+ return new PrintGraphScreenDirective($filter, sdcMenu, sdcConfig, urlToBase64Service);
+ };
+
+}
+
+PrintGraphScreenDirective.factory.$inject = ['$filter', 'sdcMenu', 'sdcConfig', 'Sdc.Services.UrlToBase64Service'];
diff --git a/catalog-ui/app/scripts/directives/property-types/data-type-fields-structure/data-type-fields-structure.html b/catalog-ui/src/app/directives/property-types/data-type-fields-structure/data-type-fields-structure.html
index b4583fd304..b62824d544 100644
--- a/catalog-ui/app/scripts/directives/property-types/data-type-fields-structure/data-type-fields-structure.html
+++ b/catalog-ui/src/app/directives/property-types/data-type-fields-structure/data-type-fields-structure.html
@@ -13,16 +13,17 @@
</div>
</div>
<!--<div class="property-value">-->
- <div data-ng-if="dataTypesService.isDataTypeForDataTypePropertyType(property,types)" class="inner-structure">
+ <div data-ng-if="dataTypesService.isDataTypeForDataTypePropertyType(property)" class="inner-structure">
<fields-structure value-obj-ref="(valueObjRef[property.name])"
type-name="property.type"
parent-form-obj="parentFormObj"
fields-prefix-name="fieldsPrefixName+property.name"
read-only="readOnly"
- default-value="{{currentTypeDefaultValue[property.name]}}"
- types="types"></fields-structure>
+ default-value="{{currentTypeDefaultValue[property.name]}}">
+
+ </fields-structure>
</div>
- <div data-ng-if="!dataTypesService.isDataTypeForDataTypePropertyType(property,types)" ng-switch="property.type">
+ <div data-ng-if="!dataTypesService.isDataTypeForDataTypePropertyType(property)" ng-switch="property.type">
<div ng-switch-when="map">
<type-map value-obj-ref="valueObjRef[property.name]"
schema-property="property.schema.property"
@@ -48,13 +49,13 @@
ng-if="!((property.simpleType||property.type) == 'boolean')"
data-ng-maxlength="100"
data-ng-disabled="readOnly"
- maxlength="100"
+ maxlength="{{(property.simpleType||property.type) == 'integer'? 10 : 100}}"
data-ng-model="valueObjRef[property.name]"
type="text"
name="{{fieldsPrefixName+property.name}}"
data-ng-pattern="getValidationPattern((property.simpleType||property.type))"
data-ng-model-options="{ debounce: 200 }"
- data-ng-change="!parentFormObj[fieldsPrefixName+property.name].$error.pattern && ('integer'==property.type && parentFormObj[fieldsPrefixName+property.name].$setValidity('pattern', validateIntRange(valueObjRef[property.name])) || onValueChange(property.name, (property.simpleType||property.type)))"
+ data-ng-change="inputOnValueChange(property)"
autofocus />
<select class="i-sdc-form-select"
data-tests-id="{{fieldsPrefixName+property.name}}"
diff --git a/catalog-ui/app/scripts/directives/property-types/data-type-fields-structure/data-type-fields-structure.less b/catalog-ui/src/app/directives/property-types/data-type-fields-structure/data-type-fields-structure.less
index 5c65fdc9dc..5c65fdc9dc 100644
--- a/catalog-ui/app/scripts/directives/property-types/data-type-fields-structure/data-type-fields-structure.less
+++ b/catalog-ui/src/app/directives/property-types/data-type-fields-structure/data-type-fields-structure.less
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
new file mode 100644
index 0000000000..2506dbe400
--- /dev/null
+++ b/catalog-ui/src/app/directives/property-types/data-type-fields-structure/data-type-fields-structure.ts
@@ -0,0 +1,154 @@
+/**
+ * Created by obarda on 1/27/2016.
+ */
+'use strict';
+import {DataTypesService} from "app/services";
+import { ValidationUtils } from "app/utils";
+import { DataTypePropertyModel } from "app/models/data-type-properties";
+import { DataTypesMap} from "app/models";
+
+export interface IDataTypeFieldsStructureScope extends ng.IScope {
+ parentFormObj:ng.IFormController;
+ dataTypeProperties:Array<DataTypePropertyModel>;
+ typeName:string;
+ valueObjRef:any;
+ propertyNameValidationPattern:RegExp;
+ fieldsPrefixName:string;
+ readOnly:boolean;
+ currentTypeDefaultValue:any;
+ types:DataTypesMap;
+ expandByDefault:boolean;
+ expand:boolean;
+ expanded:boolean;
+ dataTypesService:DataTypesService;
+
+ expandAndCollapse():void;
+ getValidationPattern(type:string):RegExp;
+ validateIntRange(value:string):boolean;
+ onValueChange(propertyName:string, type:string):void
+ inputOnValueChange(property:any):void;
+}
+
+
+export class DataTypeFieldsStructureDirective implements ng.IDirective {
+
+ constructor(private DataTypesService:DataTypesService,
+ private PropertyNameValidationPattern:RegExp,
+ private ValidationUtils:ValidationUtils) {
+ }
+
+ scope = {
+ valueObjRef: '=',
+ typeName: '=',
+ parentFormObj: '=',
+ fieldsPrefixName: '=',
+ readOnly: '=',
+ defaultValue: '@',
+ // types: '=',
+ expandByDefault: '='
+ };
+
+ restrict = 'E';
+ replace = true;
+ template = ():string => {
+ return require('./data-type-fields-structure.html');
+ };
+ //public types=Utils.Constants.PROPERTY_DATA.TYPES;
+
+ //get data type properties array and return object with the properties and their default value
+ //(for example: get: [{name:"prop1",defaultValue:1 ...},{name:"prop2", defaultValue:"bla bla" ...}]
+ // return: {prop1: 1, prop2: "bla bla"}
+ private getDefaultValue = (dataTypeProperties:Array<DataTypePropertyModel>):any => {
+ let defaultValue = {};
+ for (let i = 0; i < dataTypeProperties.length; i++) {
+ if (dataTypeProperties[i].type != 'string') {
+ if (!angular.isUndefined(dataTypeProperties[i].defaultValue)) {
+ defaultValue[dataTypeProperties[i].name] = JSON.parse(dataTypeProperties[i].defaultValue);
+ }
+ } else {
+ defaultValue[dataTypeProperties[i].name] = dataTypeProperties[i].defaultValue;
+ }
+ }
+ return defaultValue;
+ };
+
+ private initDataOnScope = (scope:any, $attr:any):void => {
+ scope.dataTypesService = this.DataTypesService;
+ scope.dataTypeProperties = this.DataTypesService.getFirsLevelOfDataTypeProperties(scope.typeName);
+ if ($attr.defaultValue) {
+ scope.currentTypeDefaultValue = JSON.parse($attr.defaultValue);
+ } else {
+ scope.currentTypeDefaultValue = this.getDefaultValue(scope.dataTypeProperties);
+ }
+
+ if (!scope.valueObjRef) {
+ scope.valueObjRef = {};
+ }
+
+ _.forEach(scope.currentTypeDefaultValue, (value, key)=> {
+ if (angular.isUndefined(scope.valueObjRef[key])) {
+ if (typeof scope.currentTypeDefaultValue[key] == 'object') {
+ angular.copy(scope.currentTypeDefaultValue[key], scope.valueObjRef[key]);
+ } else {
+ scope.valueObjRef[key] = scope.currentTypeDefaultValue[key];
+ }
+ }
+ });
+ };
+
+ private rerender = (scope:any):void => {
+ scope.expanded = false;
+ scope.expand = false;
+ if (scope.expandByDefault) {
+ scope.expandAndCollapse();
+ }
+ };
+
+ link = (scope:IDataTypeFieldsStructureScope, element:any, $attr:any) => {
+ scope.propertyNameValidationPattern = this.PropertyNameValidationPattern;
+
+ scope.$watchCollection('[typeName,fieldsPrefixName]', (newData:any):void => {
+ this.rerender(scope);
+ });
+
+
+ scope.expandAndCollapse = ():void => {
+ if (!scope.expanded) {
+ this.initDataOnScope(scope, $attr);
+ scope.expanded = true;
+ }
+ scope.expand = !scope.expand;
+ };
+
+ scope.getValidationPattern = (type:string):RegExp => {
+ return this.ValidationUtils.getValidationPattern(type);
+ };
+
+ scope.validateIntRange = (value:string):boolean => {
+ return !value || this.ValidationUtils.validateIntRange(value);
+ };
+
+ scope.onValueChange = (propertyName:string, type:string):void => {
+ scope.valueObjRef[propertyName] = !angular.isUndefined(scope.valueObjRef[propertyName]) ? scope.valueObjRef[propertyName] : scope.currentTypeDefaultValue[propertyName];
+ if (scope.valueObjRef[propertyName] && type != 'string') {
+ scope.valueObjRef[propertyName] = JSON.parse(scope.valueObjRef[propertyName]);
+ }
+ };
+
+ scope.inputOnValueChange = (property:any) => {
+
+ let value = !scope.parentFormObj[scope.fieldsPrefixName + property.name].$error.pattern
+ && ('integer' == property.type && scope.parentFormObj[scope.fieldsPrefixName + property.name].$setValidity('pattern', scope.validateIntRange(scope.valueObjRef[property.name]))
+ || scope.onValueChange(property.name, (property.simpleType || property.type)));
+ return value;
+ }
+ };
+
+ public static factory = (DataTypesService:DataTypesService,
+ PropertyNameValidationPattern:RegExp,
+ ValidationUtils:ValidationUtils)=> {
+ return new DataTypeFieldsStructureDirective(DataTypesService, PropertyNameValidationPattern, ValidationUtils);
+ };
+}
+
+DataTypeFieldsStructureDirective.factory.$inject = ['Sdc.Services.DataTypesService', 'PropertyNameValidationPattern', 'ValidationUtils'];
diff --git a/catalog-ui/app/scripts/directives/property-types/type-list/type-list-directive.html b/catalog-ui/src/app/directives/property-types/type-list/type-list-directive.html
index 410a24e62b..138e848e59 100644
--- a/catalog-ui/app/scripts/directives/property-types/type-list/type-list-directive.html
+++ b/catalog-ui/src/app/directives/property-types/type-list/type-list-directive.html
@@ -34,7 +34,7 @@
<div class="list-value-items">
<span class="list-value-item" data-ng-repeat="value in valueObjRef track by $index">
{{value}}
- <span class="delete-list-item sprite-new small-x-button" data-ng-click="deleteListItem($index)"></span>
+ <span ng-if="!readOnly" class="delete-list-item sprite-new small-x-button" data-ng-click="deleteListItem($index)"></span>
</span>
</div>
</div>
@@ -46,8 +46,7 @@
type-name="schemaProperty.type"
parent-form-obj="parentFormObj"
fields-prefix-name="fieldsPrefixName+''+$index"
- read-only="readOnly"
- types="types"></fields-structure>
+ read-only="readOnly"></fields-structure>
</div>
<div class="add-btn add-list-item" data-tests-id="add-list-item"
data-ng-class="{'disabled': readOnly}" data-ng-click="listNewItem.value='{}';addListItem();">Add</div>
diff --git a/catalog-ui/app/scripts/directives/property-types/type-list/type-list-directive.less b/catalog-ui/src/app/directives/property-types/type-list/type-list-directive.less
index eb4214e135..71263f2642 100644
--- a/catalog-ui/app/scripts/directives/property-types/type-list/type-list-directive.less
+++ b/catalog-ui/src/app/directives/property-types/type-list/type-list-directive.less
@@ -21,9 +21,9 @@
display: inline-block;
background-color: @tlv_color_v;
margin: 10px 0 0 10px;
- padding-left: 8px;
+ padding: 0 8px;
.delete-list-item{
- margin: 0 6px 0 10px;
+ margin: 0 0 0 2px;
.hand;
}
}
diff --git a/catalog-ui/src/app/directives/property-types/type-list/type-list-directive.ts b/catalog-ui/src/app/directives/property-types/type-list/type-list-directive.ts
new file mode 100644
index 0000000000..ac5da2be73
--- /dev/null
+++ b/catalog-ui/src/app/directives/property-types/type-list/type-list-directive.ts
@@ -0,0 +1,106 @@
+/**
+ * Created by rcohen on 9/15/2016.
+ */
+'use strict';
+import {SchemaProperty} from "app/models";
+import {ValidationUtils, PROPERTY_TYPES} from "app/utils";
+import {DataTypesService} from "app/services";
+
+export interface ITypeListScope extends ng.IScope {
+ parentFormObj:ng.IFormController;
+ schemaProperty:SchemaProperty;
+ isSchemaTypeDataType:boolean;
+ valueObjRef:any;
+ propertyNameValidationPattern:RegExp;
+ fieldsPrefixName:string;
+ readOnly:boolean;
+ listDefaultValue:any;
+ listNewItem:any;
+ maxLength:number;
+
+ getValidationPattern(type:string):RegExp;
+ validateIntRange(value:string):boolean;
+ addListItem():void;
+ deleteListItem(listItemIndex:number):void
+}
+
+
+export class TypeListDirective implements ng.IDirective {
+
+ constructor(private DataTypesService:DataTypesService,
+ private PropertyNameValidationPattern:RegExp,
+ private ValidationUtils:ValidationUtils) {
+ }
+
+ scope = {
+ valueObjRef: '=',//ref to list object in the parent value object
+ schemaProperty: '=',//get the schema.property object
+ parentFormObj: '=',//ref to parent form (get angular form object)
+ fieldsPrefixName: '=',//prefix for form fields names
+ readOnly: '=',//is form read only
+ defaultValue: '@',//this list default value
+ maxLength: '='
+ };
+
+ restrict = 'E';
+ replace = true;
+ template = ():string => {
+ return require('./type-list-directive.html');
+ };
+
+ link = (scope:ITypeListScope, element:any, $attr:any) => {
+ scope.propertyNameValidationPattern = this.PropertyNameValidationPattern;
+
+ //reset valueObjRef when schema type is changed
+ scope.$watchCollection('schemaProperty.type', (newData:any):void => {
+ scope.isSchemaTypeDataType = this.DataTypesService.isDataTypeForSchemaType(scope.schemaProperty);
+ //insert 1 empty item dt by default
+ if (scope.isSchemaTypeDataType && (!scope.valueObjRef || !scope.valueObjRef.length)) {
+ scope.valueObjRef = scope.valueObjRef || [];
+ scope.valueObjRef.push({});
+ }
+ });
+
+ //when user brows between properties in "edit property form"
+ scope.$watchCollection('fieldsPrefixName', (newData:any):void => {
+ scope.listNewItem = {value: ''};
+
+ if ($attr.defaultValue) {
+ scope.listDefaultValue = JSON.parse($attr.defaultValue);
+ }
+ });
+
+ scope.getValidationPattern = (type:string):RegExp => {
+ return this.ValidationUtils.getValidationPattern(type);
+ };
+
+ scope.validateIntRange = (value:string):boolean => {
+ return !value || this.ValidationUtils.validateIntRange(value);
+ };
+
+ scope.addListItem = ():void => {
+ scope.valueObjRef = scope.valueObjRef || [];
+ let newVal = ((scope.schemaProperty.simpleType || scope.schemaProperty.type) == PROPERTY_TYPES.STRING ? scope.listNewItem.value : JSON.parse(scope.listNewItem.value));
+ scope.valueObjRef.push(newVal);
+ scope.listNewItem.value = "";
+ };
+
+ scope.deleteListItem = (listItemIndex:number):void => {
+ scope.valueObjRef.splice(listItemIndex, 1);
+ if (!scope.valueObjRef.length) {
+ if (scope.listDefaultValue) {
+ angular.copy(scope.listDefaultValue, scope.valueObjRef);
+ }
+ }
+ };
+ };
+
+ public static factory = (DataTypesService:DataTypesService,
+ PropertyNameValidationPattern:RegExp,
+ ValidationUtils:ValidationUtils)=> {
+ return new TypeListDirective(DataTypesService, PropertyNameValidationPattern, ValidationUtils);
+ };
+}
+
+TypeListDirective.factory.$inject = ['Sdc.Services.DataTypesService', 'PropertyNameValidationPattern', 'ValidationUtils'];
+
diff --git a/catalog-ui/app/scripts/directives/property-types/type-map/type-map-directive.html b/catalog-ui/src/app/directives/property-types/type-map/type-map-directive.html
index ed82b840dc..37b076f26e 100644
--- a/catalog-ui/app/scripts/directives/property-types/type-map/type-map-directive.html
+++ b/catalog-ui/src/app/directives/property-types/type-map/type-map-directive.html
@@ -6,8 +6,10 @@
data-tests-id="mapKey{{fieldsPrefixName}}{{$index}}"
data-ng-model="mapKeys[$index]"
type="text"
+ data-ng-maxlength="50"
+ maxlength="50"
name="mapKey{{fieldsPrefixName}}{{$index}}"
- data-ng-pattern="propertyNameValidationPattern"
+ data-ng-pattern="MapKeyValidationPattern"
data-ng-model-options="{ debounce: 200 }"
data-ng-change="changeKeyOfMap(mapKeys[$index], $index,'mapKey'+fieldsPrefixName+$index);$event.stopPropagation();"
data-ng-disabled="readOnly"
@@ -16,6 +18,8 @@
<div class="input-error" data-ng-show="parentFormObj['mapKey'+fieldsPrefixName+$index].$dirty && parentFormObj['mapKey'+fieldsPrefixName+$index].$invalid">
<span ng-show="parentFormObj['mapKey'+fieldsPrefixName+$index].$error.keyExist" translate="PROPERTY_EDIT_MAP_UNIQUE_KEYS"></span>
<span ng-show="parentFormObj['mapKey'+fieldsPrefixName+$index].$error.required" translate="VALIDATION_ERROR_REQUIRED" translate-values="{'field': 'Key' }"></span>
+ <span ng-show="parentFormObj['mapKey'+fieldsPrefixName+$index].$error.maxlength" translate="VALIDATION_ERROR_MAX_LENGTH" translate-values="{'max': '50' }"></span>
+ <span ng-show="parentFormObj['mapKey'+fieldsPrefixName+$index].$error.pattern" translate="VALIDATION_ERROR_SPECIAL_CHARS_NOT_ALLOWED"></span>
</div>
</div>
<div data-ng-if="!isSchemaTypeDataType" class="i-sdc-form-item map-item-field" data-ng-class="{error:(parentFormObj['mapValue'+fieldsPrefixName+$index].$dirty && parentFormObj['mapValue'+fieldsPrefixName+$index].$invalid)}">
@@ -57,7 +61,6 @@
parent-form-obj="parentFormObj"
fields-prefix-name="'mapValue'+fieldsPrefixName+''+$index"
read-only="readOnly"
- types="types"
></fields-structure>
</div>
<span ng-click="deleteMapItem($index)" class="delete-map-item" data-tests-id="delete-map-item{{fieldsPrefixName}}{{$index}}" data-ng-class="{'disabled': readOnly}"></span>
diff --git a/catalog-ui/app/scripts/directives/property-types/type-map/type-map-directive.less b/catalog-ui/src/app/directives/property-types/type-map/type-map-directive.less
index 2480b626f2..2480b626f2 100644
--- a/catalog-ui/app/scripts/directives/property-types/type-map/type-map-directive.less
+++ b/catalog-ui/src/app/directives/property-types/type-map/type-map-directive.less
diff --git a/catalog-ui/src/app/directives/property-types/type-map/type-map-directive.ts b/catalog-ui/src/app/directives/property-types/type-map/type-map-directive.ts
new file mode 100644
index 0000000000..a0c9a6c460
--- /dev/null
+++ b/catalog-ui/src/app/directives/property-types/type-map/type-map-directive.ts
@@ -0,0 +1,143 @@
+/**
+ * Created by rcohen on 9/15/2016.
+ */
+'use strict';
+import {ValidationUtils, PROPERTY_TYPES} from "app/utils";
+import {DataTypesService} from "app/services";
+import {SchemaProperty} from "app/models";
+
+export interface ITypeMapScope extends ng.IScope {
+ parentFormObj:ng.IFormController;
+ schemaProperty:SchemaProperty;
+ isSchemaTypeDataType:boolean;
+ valueObjRef:any;
+ mapKeys:Array<string>;//array of map keys
+ MapKeyValidationPattern:RegExp;
+ fieldsPrefixName:string;
+ readOnly:boolean;
+ mapDefaultValue:any;
+ maxLength:number;
+
+ getValidationPattern(type:string):RegExp;
+ validateIntRange(value:string):boolean;
+ changeKeyOfMap(newKey:string, index:number, fieldName:string):void;
+ deleteMapItem(index:number):void;
+ addMapItemFields():void;
+ parseToCorrectType(objectOfValues:any, locationInObj:string, type:string):void;
+ getNumber(num:number):Array<any>;
+}
+
+
+export class TypeMapDirective implements ng.IDirective {
+
+ constructor(private DataTypesService:DataTypesService,
+ private MapKeyValidationPattern:RegExp,
+ private ValidationUtils:ValidationUtils,
+ private $timeout:ng.ITimeoutService) {
+ }
+
+ scope = {
+ valueObjRef: '=',//ref to map object in the parent value object
+ schemaProperty: '=',//get the schema.property object
+ parentFormObj: '=',//ref to parent form (get angular form object)
+ fieldsPrefixName: '=',//prefix for form fields names
+ readOnly: '=',//is form read only
+ defaultValue: '@',//this map default value
+ maxLength: '='
+ };
+
+ restrict = 'E';
+ replace = true;
+ template = ():string => {
+ return require('./type-map-directive.html');
+ };
+
+ link = (scope:ITypeMapScope, element:any, $attr:any) => {
+ scope.MapKeyValidationPattern = this.MapKeyValidationPattern;
+
+ //reset valueObjRef and mapKeys when schema type is changed
+ scope.$watchCollection('schemaProperty.type', (newData:any):void => {
+ scope.isSchemaTypeDataType = this.DataTypesService.isDataTypeForSchemaType(scope.schemaProperty);
+ if (scope.valueObjRef) {
+ scope.mapKeys = Object.keys(scope.valueObjRef);
+ }
+ });
+
+ //when user brows between properties in "edit property form"
+ scope.$watchCollection('fieldsPrefixName', (newData:any):void => {
+ if (!scope.valueObjRef) {
+ scope.valueObjRef = {};
+ }
+ scope.mapKeys = Object.keys(scope.valueObjRef);
+
+ if ($attr.defaultValue) {
+ scope.mapDefaultValue = JSON.parse($attr.defaultValue);
+ }
+ });
+
+ //return dummy array in order to prevent rendering map-keys ng-repeat again when a map key is changed
+ scope.getNumber = (num:number):Array<any> => {
+ return new Array(num);
+ };
+
+ scope.getValidationPattern = (type:string):RegExp => {
+ return this.ValidationUtils.getValidationPattern(type);
+ };
+
+ scope.validateIntRange = (value:string):boolean => {
+ return !value || this.ValidationUtils.validateIntRange(value);
+ };
+
+ scope.changeKeyOfMap = (newKey:string, index:number, fieldName:string):void => {
+ let oldKey = Object.keys(scope.valueObjRef)[index];
+ let existsKeyIndex = Object.keys(scope.valueObjRef).indexOf(newKey);
+ if (existsKeyIndex > -1 && existsKeyIndex != index) {
+ scope.parentFormObj[fieldName].$setValidity('keyExist', false);
+ } else {
+ scope.parentFormObj[fieldName].$setValidity('keyExist', true);
+ if (!scope.parentFormObj[fieldName].$invalid) {
+ let newObj = {};
+ angular.forEach(scope.valueObjRef,function(value:any,key:string){
+ if(key == oldKey){
+ newObj[newKey] = value;
+ }else{
+ newObj[key] = value;
+ }
+ });
+ scope.valueObjRef = newObj;
+ }
+ }
+ };
+
+ scope.deleteMapItem = (index:number):void=> {
+ delete scope.valueObjRef[scope.mapKeys[index]];
+ scope.mapKeys.splice(index, 1);
+ if (!scope.mapKeys.length) {//only when user removes all pairs of key-value fields - put the default
+ if (scope.mapDefaultValue) {
+ angular.copy(scope.mapDefaultValue, scope.valueObjRef);
+ scope.mapKeys = Object.keys(scope.valueObjRef);
+ }
+ }
+ };
+
+ scope.addMapItemFields = ():void => {
+ scope.valueObjRef[''] = null;
+ scope.mapKeys = Object.keys(scope.valueObjRef);
+ };
+
+ scope.parseToCorrectType = (objectOfValues:any, locationInObj:string, type:string):void => {
+ if (objectOfValues[locationInObj] && type != PROPERTY_TYPES.STRING) {
+ objectOfValues[locationInObj] = JSON.parse(objectOfValues[locationInObj]);
+ }
+ }
+ };
+
+ public static factory = (DataTypesService:DataTypesService,
+ MapKeyValidationPattern:RegExp,
+ ValidationUtils:ValidationUtils,
+ $timeout:ng.ITimeoutService)=> {
+ return new TypeMapDirective(DataTypesService, MapKeyValidationPattern, ValidationUtils, $timeout);
+ };
+}
+
+TypeMapDirective.factory.$inject = ['Sdc.Services.DataTypesService', 'MapKeyValidationPattern', 'ValidationUtils', '$timeout'];
diff --git a/catalog-ui/src/app/directives/punch-out/punch-out.ts b/catalog-ui/src/app/directives/punch-out/punch-out.ts
new file mode 100644
index 0000000000..aa15f1f3e9
--- /dev/null
+++ b/catalog-ui/src/app/directives/punch-out/punch-out.ts
@@ -0,0 +1,80 @@
+'use strict';
+import {IUserProperties, IAppConfigurtaion} from "app/models";
+let PunchOutRegistry = require('third-party/PunchOutRegistry.js');
+
+export interface IPunchOutScope extends ng.IScope {
+ name:string;
+ data:any;
+ user:IUserProperties;
+ onEvent:Function;
+}
+
+export class PunchOutDirective implements ng.IDirective {
+
+ constructor(private sdcConfig:IAppConfigurtaion) {
+ }
+
+ scope = {
+ name: '=',
+ data: '=',
+ user: '=',
+ onEvent: '&'
+ };
+
+ replace = false;
+ restrict = 'E';
+
+ link = (scope:IPunchOutScope, element:ng.IAugmentedJQuery):void => {
+ // global registry object
+ let PunchOutRegistry = window['PunchOutRegistry'];
+
+ let render = ():void => {
+ let cookieConfig = this.sdcConfig.cookie;
+ let props = {
+ name: scope.name,
+ options: {
+ data: scope.data,
+ apiRoot: this.sdcConfig.api.root,
+ apiHeaders: {
+ userId: {
+ name: cookieConfig.userIdSuffix,
+ value: scope.user.userId
+ },
+ userFirstName: {
+ name: cookieConfig.userFirstName,
+ value: scope.user.firstName
+ },
+ userLastName: {
+ name: cookieConfig.userLastName,
+ value: scope.user.lastName
+ },
+ userEmail: {
+ name: cookieConfig.userEmail,
+ value: scope.user.email
+ }
+ }
+ },
+ onEvent: (...args) => {
+ scope.$apply(() => {
+ scope.onEvent().apply(null, args);
+ });
+ }
+ };
+ PunchOutRegistry.render(props, element[0]);
+ };
+
+ let unmount = ():void => {
+ PunchOutRegistry.unmount(element[0]);
+ };
+
+ scope.$watch('data', render);
+ element.on('$destroy', unmount);
+ };
+
+ public static factory = (sdcConfig:IAppConfigurtaion) => {
+ return new PunchOutDirective(sdcConfig);
+ };
+
+}
+
+PunchOutDirective.factory.$inject = ['sdcConfig'];
diff --git a/catalog-ui/src/app/directives/sdc-tabs/sdc-single-tab/sdc-single-tab-directive.ts b/catalog-ui/src/app/directives/sdc-tabs/sdc-single-tab/sdc-single-tab-directive.ts
new file mode 100644
index 0000000000..a41d9c59e4
--- /dev/null
+++ b/catalog-ui/src/app/directives/sdc-tabs/sdc-single-tab/sdc-single-tab-directive.ts
@@ -0,0 +1,46 @@
+'use strict';
+
+export class SdcSingleTabDirective implements ng.IDirective {
+
+ constructor(private $compile:ng.ICompileService, private $parse:ng.IParseService) {
+ }
+
+ restrict = 'E';
+
+ link = (scope, elem:any, attrs:any, ctrl:any) => {
+ if (!elem.attr('inner-sdc-single-tab')) {
+ let name = this.$parse(elem.attr('ctrl'))(scope);
+ elem = elem.removeAttr('ctrl');
+ elem.attr('inner-sdc-single-tab', name);
+ this.$compile(elem)(scope);
+ }
+ };
+
+ public static factory = ($compile:ng.ICompileService, $parse:ng.IParseService)=> {
+ return new SdcSingleTabDirective($compile, $parse);
+ };
+}
+
+export class InnerSdcSingleTabDirective implements ng.IDirective {
+
+ constructor() {
+ }
+
+ scope = {
+ singleTab: "=",
+ isViewOnly: "="
+ };
+
+ replace = true;
+ restrict = 'A';
+ controller = '@';
+ template = '<div ng-include src="singleTab.templateUrl"></div>';
+
+ public static factory = ()=> {
+ return new InnerSdcSingleTabDirective();
+ };
+}
+
+SdcSingleTabDirective.factory.$inject = ['$compile', '$parse'];
+InnerSdcSingleTabDirective.factory.$inject = [];
+
diff --git a/catalog-ui/app/scripts/directives/sdc-tabs/sdc-single-tab/sdc-single-tab.less b/catalog-ui/src/app/directives/sdc-tabs/sdc-single-tab/sdc-single-tab.less
index 8b13789179..8b13789179 100644
--- a/catalog-ui/app/scripts/directives/sdc-tabs/sdc-single-tab/sdc-single-tab.less
+++ b/catalog-ui/src/app/directives/sdc-tabs/sdc-single-tab/sdc-single-tab.less
diff --git a/catalog-ui/app/scripts/directives/sdc-tabs/sdc-tabs-directive-view.html b/catalog-ui/src/app/directives/sdc-tabs/sdc-tabs-directive-view.html
index d51d221922..4dc71b8780 100644
--- a/catalog-ui/app/scripts/directives/sdc-tabs/sdc-tabs-directive-view.html
+++ b/catalog-ui/src/app/directives/sdc-tabs/sdc-tabs-directive-view.html
@@ -11,7 +11,7 @@
</div>
</div>
</div>
- <div class="sdc-single-tab-content" ng-if="isActive">
+ <div class="sdc-single-tab-content" ng-show="isActive">
<sdc-single-tab class="sdc-single-tab-content-body" ng-if="selectedTab" ctrl="selectedTab.controller" data-dests-id="selected-tab" single-tab="selectedTab" is-view-only="isViewOnly"></sdc-single-tab>
</div>
</div>
diff --git a/catalog-ui/src/app/directives/sdc-tabs/sdc-tabs-directive.ts b/catalog-ui/src/app/directives/sdc-tabs/sdc-tabs-directive.ts
new file mode 100644
index 0000000000..1567bfba53
--- /dev/null
+++ b/catalog-ui/src/app/directives/sdc-tabs/sdc-tabs-directive.ts
@@ -0,0 +1,48 @@
+/**
+ * Created by obarda on 7/28/2016.
+ */
+'use strict';
+import {Tab} from "app/models";
+
+export interface ISdcTabsDirectiveScope extends ng.IScope {
+ tabs:Array<Tab>;
+ selectedTab:Tab;
+ isActive:boolean;
+ onTabSelected(selectedTab:Tab);
+}
+
+export class SdcTabsDirective implements ng.IDirective {
+
+ constructor() {
+ }
+
+ scope = {
+ tabs: "=",
+ selectedTab: "=?",
+ isViewOnly: "="
+ };
+
+ replace = true;
+ restrict = 'E';
+ template = ():string => {
+ return require('./sdc-tabs-directive-view.html');
+ };
+
+ link = (scope:ISdcTabsDirectiveScope) => {
+ scope.isActive = true;
+
+ if (!scope.selectedTab) {
+ scope.selectedTab = scope.tabs[0];
+ }
+
+ scope.onTabSelected = (selectedTab:Tab) => {
+ scope.selectedTab = selectedTab;
+ }
+ };
+
+ public static factory = ()=> {
+ return new SdcTabsDirective();
+ };
+}
+
+SdcTabsDirective.factory.$inject = [];
diff --git a/catalog-ui/app/scripts/directives/sdc-tabs/sdc-tabs.less b/catalog-ui/src/app/directives/sdc-tabs/sdc-tabs.less
index ad390010ed..15b6fe9e1d 100644
--- a/catalog-ui/app/scripts/directives/sdc-tabs/sdc-tabs.less
+++ b/catalog-ui/src/app/directives/sdc-tabs/sdc-tabs.less
@@ -1,14 +1,13 @@
.sdc-tabs-body {
height: 100%;
width: 330px;
- position: absolute;
.sdc-tabs {
display: inline-block;
width: 40px;
vertical-align: top;
position: relative;
z-index: 99;
- right: 332px;
+
.sdc-tab-arrow {
cursor: pointer;
width: 40px;
@@ -45,8 +44,8 @@
}
.not-active {
- // position: absolute;
- right: 41px;
+ position: absolute;
+ right: 0px;
}
.sdc-single-tab-content {
@@ -59,7 +58,7 @@
top: 0;
position: absolute;
box-shadow: 0.3px 1px 3px rgba(24, 24, 25, 0.42);
- right: 331px;
+
.sdc-single-tab-content-body {
height: 100%;
display: flex;
diff --git a/catalog-ui/src/app/directives/select-property-types/select-data-type-fields-structure/select-data-type-fields-structure.html b/catalog-ui/src/app/directives/select-property-types/select-data-type-fields-structure/select-data-type-fields-structure.html
new file mode 100644
index 0000000000..8560e66978
--- /dev/null
+++ b/catalog-ui/src/app/directives/select-property-types/select-data-type-fields-structure/select-data-type-fields-structure.html
@@ -0,0 +1,81 @@
+<div class="data-type-fields-structure">
+ <div class="open-close">
+ <div class="open-close-button" data-ng-class="{'expand':expand,'collapse':!expand}"
+ data-ng-click="expandAndCollapse()"></div>
+ <span class="data-type-name">{{typeName.replace("org.openecomp.datatypes.heat.","")}}</span>
+ </div>
+ <div data-ng-show="expand" data-ng-repeat="property in dataTypeProperties" class="property" data-ng-init="property.isAlreadyInput = isAlreadyInput(property)">
+
+ <sdc-radio-button sdc-model="dataTypesService.selectedPropertiesName" value="{{path + '#' + property.name}}" data-ng-if="path && !property.isAlreadyInput"
+ disabled="false" elem-name="selectedPropertiesName" elem-id="{{path + '#' + property.name}}" class="selectPropertyType"
+ on-value-change="setSelectedType(property)" data-tests-id="propertyRadioButton_{{property.name}}"></sdc-radio-button>
+ <div class="existInputContainer" data-ng-if="property.isAlreadyInput"><span class="existInput"></span></div>
+ <div class="i-sdc-form-item property-name">
+ <div tooltips tooltip-content="{{property.name}}">
+ <input class="i-sdc-form-input"
+ type="text"
+ data-ng-disabled="true"
+ value="{{property.name}}"/>
+ </div>
+ </div>
+ <div data-ng-if="dataTypesService.isDataTypeForDataTypePropertyType(property)" class="inner-structure">
+ <select-fields-structure value-obj-ref="(valueObjRef[property.name])"
+ type-name="property.type"
+ parent-form-obj="parentFormObj"
+ fields-prefix-name="fieldsPrefixName+property.name"
+ read-only="readOnly"
+ default-value="{{currentTypeDefaultValue[property.name]}}"
+ path="{{path + '#' + property.name}}"
+ is-parent-already-input="isParentAlreadyInput"
+ ></select-fields-structure>
+
+ </div>
+ <div data-ng-if="!dataTypesService.isDataTypeForDataTypePropertyType(property)" ng-switch="property.type">
+ <div ng-switch-when="map">
+ <select-type-map value-obj-ref="valueObjRef[property.name]"
+ schema-property="property.schema.property"
+ parent-form-obj="parentFormObj"
+ fields-prefix-name="fieldsPrefixName+property.name"
+ read-only="readOnly"
+ default-value="{{currentTypeDefaultValue[property.name]}}"
+ ></select-type-map>
+ </div>
+ <div ng-switch-when="list">
+ <select-type-list value-obj-ref="valueObjRef[property.name]"
+ schema-property="property.schema.property"
+ parent-form-obj="parentFormObj"
+ fields-prefix-name="fieldsPrefixName+property.name"
+ read-only="readOnly"
+ default-value="{{currentTypeDefaultValue[property.name]}}"
+ ></select-type-list>
+ </div>
+ <div ng-switch-default class="primitive-value-field">
+ <div class="i-sdc-form-item"
+ data-ng-class="{error:(parentFormObj[fieldsPrefixName+property.name].$dirty && parentFormObj[fieldsPrefixName+property.name].$invalid)}">
+ <input class="i-sdc-form-input"
+ data-tests-id="{{fieldsPrefixName+property.name}}"
+ ng-if="!((property.simpleType||property.type) == 'boolean')"
+ data-ng-maxlength="100"
+ data-ng-disabled="readOnly"
+ maxlength="100"
+ data-ng-model="valueObjRef[property.name]"
+ type="text"
+ name="{{fieldsPrefixName+property.name}}"
+ data-ng-model-options="{ debounce: 200 }"
+ data-ng-change="!parentFormObj[fieldsPrefixName+property.name].$error.pattern && ('integer'==property.type && parentFormObj[fieldsPrefixName+property.name].$setValidity('pattern', validateIntRange(valueObjRef[property.name])) || onValueChange(property.name, (property.simpleType||property.type)))"
+ autofocus/>
+ <select class="i-sdc-form-select"
+ data-tests-id="{{fieldsPrefixName+property.name}}"
+ ng-if="(property.simpleType||property.type) == 'boolean'"
+ data-ng-disabled="readOnly"
+ name="{{fieldsPrefixName+property.name}}"
+ data-ng-change="onValueChange(property.name,'boolean')"
+ data-ng-model="valueObjRef[property.name]"
+ data-ng-options="option.v as option.n for option in [{ n: '', v: undefined }, { n: 'false', v: false }, { n: 'true', v: true }]">
+ </select>
+
+ </div>
+ </div>
+ </div>
+ </div>
+</div>
diff --git a/catalog-ui/src/app/directives/select-property-types/select-data-type-fields-structure/select-data-type-fields-structure.less b/catalog-ui/src/app/directives/select-property-types/select-data-type-fields-structure/select-data-type-fields-structure.less
new file mode 100644
index 0000000000..43d2d646a1
--- /dev/null
+++ b/catalog-ui/src/app/directives/select-property-types/select-data-type-fields-structure/select-data-type-fields-structure.less
@@ -0,0 +1,117 @@
+
+.selectPropertyType {
+ .tlv-radio-label {
+ margin-top: -7px;
+ }
+}
+
+.data-type-fields-structure {
+ background-color: @tlv_color_v;
+ padding: 10px;
+ display: table-caption;
+ .open-close {
+ position: relative;
+ .open-close-button {
+ position: absolute;
+ top: 50%;
+ margin-top: -7px;
+ &.expand {
+ .sprite-new;
+ .expand-collapse-minus-icon;
+ }
+ &.collapse {
+ .sprite-new;
+ .expand-collapse-plus-icon;
+ }
+ }
+
+ }
+
+ .existInputContainer {
+ height: 30px;
+ width: 20px;
+ position: relative;
+ }
+ .existInput {
+ .sprite-new;
+ .sdc-success;
+ position: absolute;
+ top: 18px;
+ left: 3px;
+ }
+
+ .data-type-name {
+ .m_16_m;
+ margin-left: 22px;
+ }
+
+ .i-sdc-form-input:disabled{
+ .disabled;
+ &[type="text"]{
+ opacity: 1 !important;
+ background-color: @tlv_color_t;
+ color:black;
+ }
+ }
+
+ .property {
+ display: flex;
+ min-width: 365px;
+ min-height: 46px;
+ input[type="text"], select {
+ width: 170px;
+ }
+ .property-name {
+ float: left;
+ margin-top: 8px;
+ }
+ .primitive-value-field {
+ float: right;
+ margin-top: 8px;
+ margin-left: 10px;
+ }
+ .inner-structure {
+ display: -webkit-box;
+ }
+ }
+
+ [ng-switch-when="map"] {
+ margin-top: 8px;
+ margin-left: 10px;
+ .map-item {
+ border: solid 1px @main_color_o;
+ min-width: 401px;
+ min-height: 69px;
+ float: none !important;
+ }
+ .add-map-item {
+ width: auto;
+ float: none;
+ &:nth-child(1) {
+ position: relative;
+ top: 6px;
+ }
+ .add-btn {
+ float: none;
+ }
+ }
+
+ }
+
+ [ng-switch-when="list"] {
+ float: left;
+ margin-top: 8px;
+ margin-left: 10px;
+ min-width: 280px;
+ .dt-list-item {
+ border: solid 1px @main_color_o;
+ }
+ .list-value-items {
+ width: 280px;
+ }
+ }
+}
+
+
+
+
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
new file mode 100644
index 0000000000..aee4b3b6af
--- /dev/null
+++ b/catalog-ui/src/app/directives/select-property-types/select-data-type-fields-structure/select-data-type-fields-structure.ts
@@ -0,0 +1,184 @@
+/**
+ * Created by obarda on 1/27/2016.
+ */
+'use strict';
+import {ValidationUtils} from "app/utils";
+import { DataTypesService } from "app/services";
+import { DataTypePropertyModel } from "app/models/data-type-properties";
+import {DataTypesMap, PropertyModel} from "app/models";
+
+export interface ISelectDataTypeFieldsStructureScope extends ng.IScope {
+ parentFormObj:ng.IFormController;
+ dataTypeProperties:Array<DataTypePropertyModel>;
+ typeName:string;
+ valueObjRef:any;
+ propertyNameValidationPattern:RegExp;
+ fieldsPrefixName:string;
+ readOnly:boolean;
+ currentTypeDefaultValue:any;
+ types:DataTypesMap;
+ expandByDefault:boolean;
+ expand:boolean;
+ expanded:boolean;
+ dataTypesService:DataTypesService;
+ path:string;
+ isParentAlreadyInput:boolean;
+
+ expandAndCollapse():void;
+ getValidationPattern(type:string):RegExp;
+ validateIntRange(value:string):boolean;
+ isAlreadyInput(property:PropertyModel):boolean;
+ setSelectedType(property:PropertyModel):void;
+ onValueChange(propertyName:string, type:string):void;
+}
+
+
+export class SelectDataTypeFieldsStructureDirective implements ng.IDirective {
+
+ constructor(private DataTypesService:DataTypesService,
+ private PropertyNameValidationPattern:RegExp,
+ private ValidationUtils:ValidationUtils) {
+ }
+
+ scope = {
+ valueObjRef: '=',
+ typeName: '=',
+ parentFormObj: '=',
+ fieldsPrefixName: '=',
+ readOnly: '=',
+ defaultValue: '@',
+ expandByDefault: '=',
+ path: '@',
+ isParentAlreadyInput: '='
+ };
+
+ restrict = 'E';
+ replace = true;
+ template = ():string => {
+ return require('./select-data-type-fields-structure.html');
+ };
+ // public types=Utils.Constants.PROPERTY_DATA.TYPES;
+
+ //get data type properties array and return object with the properties and their default value
+ //(for example: get: [{name:"prop1",defaultValue:1 ...},{name:"prop2", defaultValue:"bla bla" ...}]
+ // return: {prop1: 1, prop2: "bla bla"}
+ private getDefaultValue = (dataTypeProperties:Array<DataTypePropertyModel>):any => {
+ let defaultValue = {};
+ for (let i = 0; i < dataTypeProperties.length; i++) {
+ if (dataTypeProperties[i].type != 'string') {
+ if (!angular.isUndefined(dataTypeProperties[i].defaultValue)) {
+ defaultValue[dataTypeProperties[i].name] = JSON.parse(dataTypeProperties[i].defaultValue);
+ }
+ } else {
+ defaultValue[dataTypeProperties[i].name] = dataTypeProperties[i].defaultValue;
+ }
+ }
+ return defaultValue;
+ };
+
+ private initDataOnScope = (scope:ISelectDataTypeFieldsStructureScope, $attr:any):void => {
+ scope.dataTypesService = this.DataTypesService;
+ scope.dataTypeProperties = angular.copy(this.DataTypesService.getFirsLevelOfDataTypeProperties(scope.typeName));
+ if ($attr.defaultValue) {
+ scope.currentTypeDefaultValue = JSON.parse($attr.defaultValue);
+ } else {
+ scope.currentTypeDefaultValue = this.getDefaultValue(scope.dataTypeProperties);
+ }
+
+ if (!scope.valueObjRef) {
+ scope.valueObjRef = {};
+ }
+
+ _.forEach(scope.currentTypeDefaultValue, (value, key)=> {
+ if (angular.isUndefined(scope.valueObjRef[key])) {
+ if (typeof scope.currentTypeDefaultValue[key] == 'object') {
+ angular.copy(scope.currentTypeDefaultValue[key], scope.valueObjRef[key]);
+ } else {
+ scope.valueObjRef[key] = scope.currentTypeDefaultValue[key];
+ }
+ }
+ });
+ };
+
+ private rerender = (scope:any):void => {
+ scope.expanded = false;
+ scope.expand = false;
+ if (scope.expandByDefault) {
+ scope.expandAndCollapse();
+ }
+ };
+
+ link = (scope:ISelectDataTypeFieldsStructureScope, element:any, $attr:any) => {
+ scope.propertyNameValidationPattern = this.PropertyNameValidationPattern;
+
+ scope.$watchCollection('[typeName,fieldsPrefixName]', (newData:any):void => {
+ this.rerender(scope);
+ });
+
+
+ scope.expandAndCollapse = ():void => {
+ if (!scope.expanded) {
+ this.initDataOnScope(scope, $attr);
+ scope.expanded = true;
+ }
+ scope.expand = !scope.expand;
+ };
+
+ scope.getValidationPattern = (type:string):RegExp => {
+ return this.ValidationUtils.getValidationPattern(type);
+ };
+
+ scope.validateIntRange = (value:string):boolean => {
+ return !value || this.ValidationUtils.validateIntRange(value);
+ };
+
+ /*
+ check if property is alrady declered on the service by meatching the input name & the property name
+
+ */
+ scope.isAlreadyInput = (property:PropertyModel):boolean => {
+ if (scope.path) {
+ if (scope.isParentAlreadyInput) {
+ return true;
+ }
+ let parentInputName = this.DataTypesService.selectedInstance.normalizedName + '_' + scope.path.replace('#', '_');// set the input parent as he need to declared as input
+ let inputName = parentInputName + '_' + property.name;// set the input name as he need to declared as input
+ let selectedProperty = _.find(this.DataTypesService.selectedComponentInputs, (componentInput)=> {
+ if (componentInput.name == parentInputName) { //check if the parent(all the complex) is already declared
+ scope.isParentAlreadyInput = true;
+ return true;
+ } else if (componentInput.name.substring(0, inputName.length) == inputName) { //check if specific property inside the complex
+ return true;
+ }
+ //return componentInput.name == parentInputName || componentInput.name.substring(0,inputName.length) == inputName;//check if the parent(all the complex) is already declared or specific property inside the complex
+ });
+ if (selectedProperty) {
+ return true;
+ }
+ }
+ return false;
+ };
+
+ scope.setSelectedType = (property:PropertyModel):void=> {
+ scope.dataTypesService.selectedInput = property;
+ scope.dataTypesService.selectedPropertiesName = scope.path + '#' + property.name;
+ };
+
+ scope.onValueChange = (propertyName:string, type:string):void => {
+ scope.valueObjRef[propertyName] = !angular.isUndefined(scope.valueObjRef[propertyName]) ? scope.valueObjRef[propertyName] : scope.currentTypeDefaultValue[propertyName];
+ if (scope.valueObjRef[propertyName] && type != 'string') {
+ scope.valueObjRef[propertyName] = JSON.parse(scope.valueObjRef[propertyName]);
+ }
+ };
+
+
+ };
+
+ public static factory = (DataTypesService:DataTypesService,
+ PropertyNameValidationPattern:RegExp,
+ ValidationUtils:ValidationUtils)=> {
+ return new SelectDataTypeFieldsStructureDirective(DataTypesService, PropertyNameValidationPattern, ValidationUtils);
+ };
+}
+
+SelectDataTypeFieldsStructureDirective.factory.$inject = ['Sdc.Services.DataTypesService', 'PropertyNameValidationPattern', 'ValidationUtils'];
diff --git a/catalog-ui/src/app/directives/select-property-types/select-type-list/select-type-list-directive.html b/catalog-ui/src/app/directives/select-property-types/select-type-list/select-type-list-directive.html
new file mode 100644
index 0000000000..f439147301
--- /dev/null
+++ b/catalog-ui/src/app/directives/select-property-types/select-type-list/select-type-list-directive.html
@@ -0,0 +1,56 @@
+<div>
+ <div data-ng-if="!isSchemaTypeDataType">
+ <div class="i-sdc-form-item list-new-item" data-ng-class="{error:(parentFormObj['listNewItem'+fieldsPrefixName].$dirty && parentFormObj['listNewItem'+fieldsPrefixName].$invalid)}">
+ <input class="i-sdc-form-input"
+ data-tests-id="listNewItem{{fieldsPrefixName}}"
+ ng-if="!((schemaProperty.simpleType||schemaProperty.type) == 'boolean')"
+ data-ng-disabled="readOnly"
+ data-ng-model="listNewItem.value"
+ type="text"
+ name="listNewItem{{fieldsPrefixName}}"
+ data-ng-model-options="{ debounce: 200 }"
+ placeholder="Type a value and then click ADD"
+ data-ng-maxlength="maxLength"
+ maxlength="{{maxLength}}"
+ sdc-keyboard-events="" key-enter="schemaProperty.type && !parentFormObj['listNewItem'+fieldsPrefixName].$invalid && listNewItem.value && addListItem"
+ autofocus />
+ <select class="i-sdc-form-select"
+ data-tests-id="listNewItem{{fieldsPrefixName}}"
+ ng-if="(schemaProperty.simpleType||schemaProperty.type) == 'boolean'"
+ data-ng-disabled="readOnly"
+ name="listNewItem{{fieldsPrefixName}}"
+ data-ng-model="listNewItem.value">
+ <option value="true">true</option>
+ <option value="false">false</option>
+ </select>
+ <div class="input-error" data-ng-show="parentFormObj['listNewItem'+fieldsPrefixName].$dirty && parentFormObj['listNewItem'+fieldsPrefixName].$invalid">
+ <span ng-show="parentFormObj['listNewItem'+fieldsPrefixName].$error.pattern" translate="PROPERTY_EDIT_PATTERN"></span>
+ <span ng-show="parentFormObj['listNewItem'+fieldsPrefixName].$error.maxlength" translate="VALIDATION_ERROR_MAX_LENGTH" translate-values="{'max': '{{maxLength}}' }"></span>
+ </div>
+ </div>
+ <!--<div class="add-btn add-list-item" data-tests-id="add-list-item{{fieldsPrefixName}}"-->
+ <!--data-ng-class="{'disabled': readOnly || !schemaProperty.type || parentFormObj['listNewItem'+fieldsPrefixName].$invalid || !listNewItem.value}" data-ng-click="addListItem()">Add</div>-->
+ <div class="list-value-items">
+ <span class="list-value-item" data-ng-repeat="value in valueObjRef track by $index">
+ {{value}}
+ <span ng-if="!readOnly" class="delete-list-item sprite-new small-x-button" data-ng-click="deleteListItem($index)"></span>
+ </span>
+ </div>
+ </div>
+ <div data-ng-if="isSchemaTypeDataType">
+ <div class="dt-list">
+ <div data-ng-repeat="value in valueObjRef track by $index" class="dt-list-item">
+ <select-fields-structure value-obj-ref="valueObjRef[$index]"
+ type-name="schemaProperty.type"
+ parent-form-obj="parentFormObj"
+ fields-prefix-name="fieldsPrefixName+''+$index"
+ read-only="readOnly">
+ <!--path="{{path}}"-->
+ </select-fields-structure>
+ </div>
+ <!--<div class="add-btn add-list-item" data-tests-id="add-list-item"-->
+ <!--data-ng-class="{'disabled': readOnly}" data-ng-click="listNewItem.value='{}';addListItem();">Add</div>-->
+ </div>
+
+ </div>
+</div>
diff --git a/catalog-ui/src/app/directives/select-property-types/select-type-list/select-type-list-directive.less b/catalog-ui/src/app/directives/select-property-types/select-type-list/select-type-list-directive.less
new file mode 100644
index 0000000000..71263f2642
--- /dev/null
+++ b/catalog-ui/src/app/directives/select-property-types/select-type-list/select-type-list-directive.less
@@ -0,0 +1,85 @@
+.list-new-item{
+ float: left;
+ width: 50%;
+ min-width: 221px;
+ margin-right: 15px;
+ input{
+ min-width: 221px;
+ }
+}
+
+.list-value-items{
+ -webkit-border-radius: 2px;
+ -moz-border-radius: 2px;
+ border-radius: 2px;
+ border: 1px solid @main_color_o;
+ padding-bottom: 10px;
+ min-height: 100px;
+ clear: both;
+ background-color: white;
+ .list-value-item{
+ display: inline-block;
+ background-color: @tlv_color_v;
+ margin: 10px 0 0 10px;
+ padding: 0 8px;
+ .delete-list-item{
+ margin: 0 0 0 2px;
+ .hand;
+ }
+ }
+}
+
+.add-btn {
+ .f-color.a;
+ .f-type._14_m;
+ .hand;
+
+ &.add-list-item {
+ float: left;
+ margin-top: 5px;
+ width: 44px;
+ }
+
+ &:before {
+ .sprite-new;
+ .plus-icon;
+ margin-right: 5px;
+ content: "";
+
+ }
+ &:hover {
+ .f-color.b;
+ &:before {
+ .sprite-new;
+ .plus-icon-hover;
+ }
+ }
+
+}
+
+.dt-list{
+ display: table-caption;
+ .dt-list-item {
+ border-radius: 3px;
+ background-color: @tlv_color_v;
+ display: inline-block;
+ .delete-dt-list-item{
+ float: right;
+ position: relative;
+ top: 5px;
+ right: 5px;
+ .sprite-new;
+ .delete-icon;
+ &:hover{
+ .delete-icon-hover;
+ }
+ }
+ .data-type-name{
+ margin-right: 16px;
+ }
+ }
+ &>.add-list-item{
+ float:none;
+ }
+}
+
diff --git a/catalog-ui/src/app/directives/select-property-types/select-type-list/select-type-list-directive.ts b/catalog-ui/src/app/directives/select-property-types/select-type-list/select-type-list-directive.ts
new file mode 100644
index 0000000000..d277040798
--- /dev/null
+++ b/catalog-ui/src/app/directives/select-property-types/select-type-list/select-type-list-directive.ts
@@ -0,0 +1,108 @@
+/**
+ * Created by rcohen on 9/15/2016.
+ */
+'use strict';
+import {DataTypesService} from "app/services/data-types-service";
+import {SchemaProperty} from "app/models/aschema-property";
+import {ValidationUtils, PROPERTY_TYPES} from "app/utils";
+
+export interface ISelectTypeListScope extends ng.IScope {
+ parentFormObj:ng.IFormController;
+ schemaProperty:SchemaProperty;
+ isSchemaTypeDataType:boolean;
+ valueObjRef:any;
+ propertyNameValidationPattern:RegExp;
+ fieldsPrefixName:string;
+ readOnly:boolean;
+ listDefaultValue:any;
+ listNewItem:any;
+ maxLength:number;
+ dataTypesService:DataTypesService;
+
+ getValidationPattern(type:string):RegExp;
+ validateIntRange(value:string):boolean;
+ addListItem():void;
+ deleteListItem(listItemIndex:number):void
+}
+
+export class SelectTypeListDirective implements ng.IDirective {
+
+ constructor(private DataTypesService:DataTypesService,
+ private PropertyNameValidationPattern:RegExp,
+ private ValidationUtils:ValidationUtils) {
+ }
+
+ scope = {
+ valueObjRef: '=',//ref to list object in the parent value object
+ schemaProperty: '=',//get the schema.property object
+ parentFormObj: '=',//ref to parent form (get angular form object)
+ fieldsPrefixName: '=',//prefix for form fields names
+ readOnly: '=',//is form read only
+ defaultValue: '@',//this list default value
+ maxLength: '=',
+ path: '@'
+ };
+
+ restrict = 'E';
+ replace = true;
+ template = ():string => {
+ return require('./select-type-list-directive.html');
+ };
+
+ link = (scope:ISelectTypeListScope, element:any, $attr:any) => {
+ scope.dataTypesService = this.DataTypesService;
+ scope.propertyNameValidationPattern = this.PropertyNameValidationPattern;
+
+ //reset valueObjRef when schema type is changed
+ scope.$watchCollection('schemaProperty.type', (newData:any):void => {
+ scope.isSchemaTypeDataType = this.DataTypesService.isDataTypeForSchemaType(scope.schemaProperty);
+ //insert 1 empty item dt by default
+ if (scope.isSchemaTypeDataType && (!scope.valueObjRef || !scope.valueObjRef.length)) {
+ scope.valueObjRef = scope.valueObjRef || [];
+ scope.valueObjRef.push({});
+ }
+ });
+
+ //when user brows between properties in "edit property form"
+ scope.$watchCollection('fieldsPrefixName', (newData:any):void => {
+ scope.listNewItem = {value: ''};
+
+ if ($attr.defaultValue) {
+ scope.listDefaultValue = JSON.parse($attr.defaultValue);
+ }
+ });
+
+ scope.getValidationPattern = (type:string):RegExp => {
+ return this.ValidationUtils.getValidationPattern(type);
+ };
+
+ scope.validateIntRange = (value:string):boolean => {
+ return !value || this.ValidationUtils.validateIntRange(value);
+ };
+
+ scope.addListItem = ():void => {
+ scope.valueObjRef = scope.valueObjRef || [];
+ let newVal = ((scope.schemaProperty.simpleType || scope.schemaProperty.type) == PROPERTY_TYPES.STRING ? scope.listNewItem.value : JSON.parse(scope.listNewItem.value));
+ scope.valueObjRef.push(newVal);
+ scope.listNewItem.value = "";
+ };
+
+ scope.deleteListItem = (listItemIndex:number):void => {
+ scope.valueObjRef.splice(listItemIndex, 1);
+ if (!scope.valueObjRef.length) {
+ if (scope.listDefaultValue) {
+ angular.copy(scope.listDefaultValue, scope.valueObjRef);
+ }
+ }
+ };
+ };
+
+ public static factory = (DataTypesService:DataTypesService,
+ PropertyNameValidationPattern:RegExp,
+ ValidationUtils:ValidationUtils)=> {
+ return new SelectTypeListDirective(DataTypesService, PropertyNameValidationPattern, ValidationUtils);
+ };
+}
+
+SelectTypeListDirective.factory.$inject = ['Sdc.Services.DataTypesService', 'PropertyNameValidationPattern', 'ValidationUtils'];
+
diff --git a/catalog-ui/src/app/directives/select-property-types/select-type-map/select-type-map-directive.html b/catalog-ui/src/app/directives/select-property-types/select-type-map/select-type-map-directive.html
new file mode 100644
index 0000000000..a56428e5c2
--- /dev/null
+++ b/catalog-ui/src/app/directives/select-property-types/select-type-map/select-type-map-directive.html
@@ -0,0 +1,56 @@
+<div>
+ <div data-ng-repeat="i in getNumber(mapKeys.length) track by $index" class="map-item" data-ng-class="{'primitive-value-map':!isSchemaTypeDataType}">
+ <div class="i-sdc-form-item map-item-field" data-ng-class="{error:(parentFormObj['mapKey'+fieldsPrefixName+$index].$dirty && parentFormObj['mapKey'+fieldsPrefixName+$index].$invalid)}">
+ <label class="i-sdc-form-label required">Key</label>
+ <input class="i-sdc-form-input"
+ data-tests-id="mapKey{{fieldsPrefixName}}{{$index}}"
+ data-ng-model="mapKeys[$index]"
+ type="text"
+ data-ng-maxlength="50"
+ maxlength="50"
+ name="mapKey{{fieldsPrefixName}}{{$index}}"
+ data-ng-model-options="{ debounce: 200 }"
+ data-ng-change="changeKeyOfMap(mapKeys[$index], $index,'mapKey'+fieldsPrefixName+$index);$event.stopPropagation();"
+ data-ng-disabled="readOnly"
+ data-required
+ autofocus/>
+ </div>
+ <div data-ng-if="!isSchemaTypeDataType" class="i-sdc-form-item map-item-field" data-ng-class="{error:(parentFormObj['mapValue'+fieldsPrefixName+$index].$dirty && parentFormObj['mapValue'+fieldsPrefixName+$index].$invalid)}">
+ <label class="i-sdc-form-label required">Value</label>
+ <input class="i-sdc-form-input"
+ ng-if="!((schemaProperty.simpleType||schemaProperty.type) == 'boolean')"
+ data-ng-disabled="readOnly"
+ data-ng-model="valueObjRef[mapKeys[$index]]"
+ type="text"
+ name="mapValue{{fieldsPrefixName}}{{$index}}"
+ data-tests-id="mapValue{{fieldsPrefixName}}{{$index}}"
+ data-ng-change="!parentFormObj['mapValue'+fieldsPrefixName+$index].$error.pattern && parseToCorrectType(valueObjRef, key, (schemaProperty.simpleType||schemaProperty.type))"
+ data-ng-model-options="{ debounce: 200 }"
+ data-ng-maxlength="maxLength"
+ maxlength="{{maxLength}}"
+ data-required
+ autofocus />
+ <select class="i-sdc-form-select"
+ data-tests-id="mapValue{{fieldsPrefixName}}{{$index}}"
+ ng-if="(schemaProperty.simpleType||schemaProperty.type) == 'boolean'"
+ data-ng-disabled="readOnly"
+ name="mapValue{{fieldsPrefixName}}{{$index}}"
+ data-ng-model="valueObjRef[mapKeys[$index]]"
+ data-required>
+ <option value="true">true</option>
+ <option value="false">false</option>
+ </select>
+ </div>
+ <div data-ng-if="isSchemaTypeDataType" class="i-sdc-form-item map-item-field">
+ <label class="i-sdc-form-label">Value</label>
+ <select-fields-structure value-obj-ref="valueObjRef[mapKeys[$index]]"
+ type-name="schemaProperty.type"
+ parent-form-obj="parentFormObj"
+ fields-prefix-name="'mapValue'+fieldsPrefixName+''+$index"
+ read-only="readOnly">
+ <!--path="{{path + '#' + mapKeys[$index]}}"-->
+ </select-fields-structure>
+ </div>
+ </div>
+</div>
+
diff --git a/catalog-ui/src/app/directives/select-property-types/select-type-map/select-type-map-directive.less b/catalog-ui/src/app/directives/select-property-types/select-type-map/select-type-map-directive.less
new file mode 100644
index 0000000000..2480b626f2
--- /dev/null
+++ b/catalog-ui/src/app/directives/select-property-types/select-type-map/select-type-map-directive.less
@@ -0,0 +1,83 @@
+.add-map-item{
+ &:nth-child(odd){
+ float: right;
+ }
+ &:nth-child(1){
+ float: none;
+ .add-btn{
+ float: none;
+ }
+ }
+ width: 400px;
+ .add-btn{
+ width: 44px;
+ float: right;
+ }
+ &.schema-data-type{
+ float:none;
+ .add-btn{
+ float: none;
+ }
+ }
+}
+
+.add-btn {
+ .f-color.a;
+ .f-type._14_m;
+ .hand;
+
+ &:before {
+ .sprite-new;
+ .plus-icon;
+ margin-right: 5px;
+ content: "";
+
+ }
+ &:hover {
+ .f-color.b;
+ &:before {
+ .sprite-new;
+ .plus-icon-hover;
+ }
+ }
+
+}
+
+.map-item{
+ min-width: 389px;
+ min-height: 65px;
+ background-color: @tlv_color_v;
+ border-radius: 3px;
+ margin-bottom: 8px;
+ float: left;
+ display: flex;
+ &:nth-child(even).primitive-value-map{
+ float: right;
+ }
+ .delete-map-item {
+ float: right;
+ position: relative;
+ top: 5px;
+ right: 5px;
+ .sprite-new;
+ .delete-icon;
+ &:hover{
+ .delete-icon-hover;
+ }
+ }
+ .map-item-field {
+ margin: 7px 12px !important;
+ float: left;
+ min-width: 170px;
+ min-height: 50px;
+ select{
+ width:171px;
+ }
+ input[type="text"]{
+ width: 170px;
+ }
+ &>.data-type-fields-structure{
+ padding: 0;
+ }
+ }
+}
diff --git a/catalog-ui/src/app/directives/select-property-types/select-type-map/select-type-map-directive.ts b/catalog-ui/src/app/directives/select-property-types/select-type-map/select-type-map-directive.ts
new file mode 100644
index 0000000000..19df8dfb71
--- /dev/null
+++ b/catalog-ui/src/app/directives/select-property-types/select-type-map/select-type-map-directive.ts
@@ -0,0 +1,139 @@
+/**
+ * Created by rcohen on 9/15/2016.
+ */
+'use strict';
+import {SchemaProperty} from "app/models";
+import {DataTypesService} from "app/services";
+import {ValidationUtils, PROPERTY_TYPES} from "app/utils";
+
+export interface ISelectTypeMapScope extends ng.IScope {
+ parentFormObj:ng.IFormController;
+ schemaProperty:SchemaProperty;
+ isSchemaTypeDataType:boolean;
+ valueObjRef:any;
+ mapKeys:Array<string>;//array of map keys
+ MapKeyValidationPattern:RegExp;
+ fieldsPrefixName:string;
+ readOnly:boolean;
+ mapDefaultValue:any;
+ maxLength:number;
+ dataTypesService:DataTypesService;
+
+ getValidationPattern(type:string):RegExp;
+ validateIntRange(value:string):boolean;
+ changeKeyOfMap(newKey:string, index:number, fieldName:string):void;
+ deleteMapItem(index:number):void;
+ addMapItemFields():void;
+ parseToCorrectType(objectOfValues:any, locationInObj:string, type:string):void;
+ getNumber(num:number):Array<any>;
+}
+
+
+export class SelectTypeMapDirective implements ng.IDirective {
+
+ constructor(private DataTypesService:DataTypesService,
+ private MapKeyValidationPattern:RegExp,
+ private ValidationUtils:ValidationUtils,
+ private $timeout:ng.ITimeoutService) {
+ }
+
+ scope = {
+ valueObjRef: '=',//ref to map object in the parent value object
+ schemaProperty: '=',//get the schema.property object
+ parentFormObj: '=',//ref to parent form (get angular form object)
+ fieldsPrefixName: '=',//prefix for form fields names
+ readOnly: '=',//is form read only
+ defaultValue: '@',//this map default value
+ maxLength: '=',
+ path: '@'
+ };
+
+ restrict = 'E';
+ replace = true;
+ template = ():string => {
+ return require('./select-type-map-directive.html');
+ };
+
+ link = (scope:ISelectTypeMapScope, element:any, $attr:any) => {
+
+ scope.dataTypesService = this.DataTypesService;
+ scope.MapKeyValidationPattern = this.MapKeyValidationPattern;
+
+ //reset valueObjRef and mapKeys when schema type is changed
+ scope.$watchCollection('schemaProperty.type', (newData:any):void => {
+ scope.isSchemaTypeDataType = this.DataTypesService.isDataTypeForSchemaType(scope.schemaProperty);
+ if (scope.valueObjRef) {
+ scope.mapKeys = Object.keys(scope.valueObjRef);
+ }
+ });
+
+ //when user brows between properties in "edit property form"
+ scope.$watchCollection('fieldsPrefixName', (newData:any):void => {
+ if (!scope.valueObjRef) {
+ scope.valueObjRef = {};
+ }
+ scope.mapKeys = Object.keys(scope.valueObjRef);
+
+ if ($attr.defaultValue) {
+ scope.mapDefaultValue = JSON.parse($attr.defaultValue);
+ }
+ });
+
+ //return dummy array in order to prevent rendering map-keys ng-repeat again when a map key is changed
+ scope.getNumber = (num:number):Array<any> => {
+ return new Array(num);
+ };
+
+ scope.getValidationPattern = (type:string):RegExp => {
+ return this.ValidationUtils.getValidationPattern(type);
+ };
+
+ scope.validateIntRange = (value:string):boolean => {
+ return !value || this.ValidationUtils.validateIntRange(value);
+ };
+
+ scope.changeKeyOfMap = (newKey:string, index:number, fieldName:string):void => {
+ let oldKey = Object.keys(scope.valueObjRef)[index];
+ let existsKeyIndex = Object.keys(scope.valueObjRef).indexOf(newKey);
+ if (existsKeyIndex > -1 && existsKeyIndex != index) {
+ scope.parentFormObj[fieldName].$setValidity('keyExist', false);
+ } else {
+ scope.parentFormObj[fieldName].$setValidity('keyExist', true);
+ if (!scope.parentFormObj[fieldName].$invalid) {
+ angular.copy(JSON.parse(JSON.stringify(scope.valueObjRef).replace('"' + oldKey + '":', '"' + newKey + '":')), scope.valueObjRef);//update key
+ }
+ }
+ };
+
+ scope.deleteMapItem = (index:number):void=> {
+ delete scope.valueObjRef[scope.mapKeys[index]];
+ scope.mapKeys.splice(index, 1);
+ if (!scope.mapKeys.length) {//only when user removes all pairs of key-value fields - put the default
+ if (scope.mapDefaultValue) {
+ angular.copy(scope.mapDefaultValue, scope.valueObjRef);
+ scope.mapKeys = Object.keys(scope.valueObjRef);
+ }
+ }
+ };
+
+ scope.addMapItemFields = ():void => {
+ scope.valueObjRef[''] = null;
+ scope.mapKeys = Object.keys(scope.valueObjRef);
+ };
+
+ scope.parseToCorrectType = (objectOfValues:any, locationInObj:string, type:string):void => {
+ if (objectOfValues[locationInObj] && type != PROPERTY_TYPES.STRING) {
+ objectOfValues[locationInObj] = JSON.parse(objectOfValues[locationInObj]);
+ }
+ }
+ };
+
+ public static factory = (DataTypesService:DataTypesService,
+ MapKeyValidationPattern:RegExp,
+ ValidationUtils:ValidationUtils,
+ $timeout:ng.ITimeoutService)=> {
+ return new SelectTypeMapDirective(DataTypesService, MapKeyValidationPattern, ValidationUtils, $timeout);
+ };
+}
+
+SelectTypeMapDirective.factory.$inject = ['Sdc.Services.DataTypesService', 'MapKeyValidationPattern', 'ValidationUtils', '$timeout'];
diff --git a/catalog-ui/app/scripts/directives/structure-tree/structure-tree-directive.html b/catalog-ui/src/app/directives/structure-tree/structure-tree-directive.html
index 7d8a883b33..7d8a883b33 100644
--- a/catalog-ui/app/scripts/directives/structure-tree/structure-tree-directive.html
+++ b/catalog-ui/src/app/directives/structure-tree/structure-tree-directive.html
diff --git a/catalog-ui/app/scripts/directives/structure-tree/structure-tree-directive.less b/catalog-ui/src/app/directives/structure-tree/structure-tree-directive.less
index 094c3f70ba..094c3f70ba 100644
--- a/catalog-ui/app/scripts/directives/structure-tree/structure-tree-directive.less
+++ b/catalog-ui/src/app/directives/structure-tree/structure-tree-directive.less
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
new file mode 100644
index 0000000000..4d6fbee4db
--- /dev/null
+++ b/catalog-ui/src/app/directives/structure-tree/structure-tree-directive.ts
@@ -0,0 +1,195 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+'use strict';
+import {RelationshipModel, Component, ComponentInstance} from "app/models";
+import {Dictionary} from "app/utils";
+
+
+export interface IStructureTreeScope extends ng.IScope {
+
+ component:Component;
+ structureTree:StructureTree;
+}
+
+class StructureTree {
+
+ serviceRoot:ResourceInstanceNode;
+
+ constructor(private uniqueId:string, private resourceInstanceName:string, private resourceInstanceIcon:string, private certified:boolean) {
+ this.serviceRoot = new ResourceInstanceNode(uniqueId, resourceInstanceName, resourceInstanceIcon, certified);
+ }
+
+}
+
+class ResourceInstanceNode {
+ id:string;
+ icon:string;
+ name:string;
+ resourceInstancesList:Array<ResourceInstanceNode>;
+ isAlreadyInTree:boolean;
+ certified:boolean;
+
+
+ constructor(private uniqueId:string, private resourceInstanceName:string, private resourceInstanceIcon:string, certified:boolean) {
+ this.id = uniqueId;
+ this.name = resourceInstanceName;
+ this.icon = resourceInstanceIcon;
+ this.resourceInstancesList = [];
+ this.isAlreadyInTree = false;
+ this.certified = certified;
+ }
+}
+
+export class StructureTreeDirective implements ng.IDirective {
+
+
+ constructor() {
+ }
+
+ scope = {
+ component: '=',
+ };
+ restrict = 'E';
+ template = ():string => {
+ return require('./structure-tree-directive.html');
+ };
+
+ link = (scope:IStructureTreeScope, $elem:any) => {
+
+ let RESOURCE_INSTANCE_LIST:string = "resourceInstancesChildesList";
+ let resourceInstanceMap:Dictionary<string, ResourceInstanceNode>;
+ let relations:Array<RelationshipModel>;
+ //************* Start Building Tree Functions *******************//
+
+ //remove unnecessary instances
+ let initResourceInstanceMap = ():void => {
+
+ resourceInstanceMap = new Dictionary<string, ResourceInstanceNode>();
+
+ _.forEach(scope.component.componentInstances, (resourceInstance:ComponentInstance)=> {
+ if (_.some(Object.keys(resourceInstance.capabilities), (key:string)=> {
+ return 'tosca.capabilities.container' == key.toLowerCase();
+ }) || _.some(Object.keys(resourceInstance.requirements), (key:string)=> {
+ return 'tosca.capabilities.container' == key.toLowerCase();
+ })) {
+
+ let isCertified = 0 === (parseFloat(resourceInstance.componentVersion) % 1);
+ let node:ResourceInstanceNode = new ResourceInstanceNode(resourceInstance.uniqueId,
+ resourceInstance.name,
+ resourceInstance.icon,
+ isCertified);
+ resourceInstanceMap.setValue(resourceInstance.uniqueId, node);
+ }
+ });
+ };
+
+ //remove unnecessary relations
+ let initRelations = ():void => {
+ relations = _.filter(scope.component.componentInstancesRelations, (relation:RelationshipModel)=> {
+ return resourceInstanceMap.containsKey(relation.fromNode) && resourceInstanceMap.containsKey(relation.toNode);
+ });
+ };
+
+ let buildTree = ():void => {
+ if (scope.component) {
+ scope.structureTree = new StructureTree(scope.component.uniqueId, scope.component.name, scope.component.icon, 'CERTIFIED' === scope.component.lifecycleState);
+ initResourceInstanceMap();
+ initRelations();
+
+ let parentNodesList = _.groupBy(relations, (node:any)=> {
+ return node.fromNode;
+ });
+
+ for (let parent in parentNodesList) {
+ _.forEach(parentNodesList[parent], (childNode)=> {
+ parentNodesList[parent][RESOURCE_INSTANCE_LIST] = [];
+ parentNodesList[parent][RESOURCE_INSTANCE_LIST].push(mergeAllSubtrees(childNode, parentNodesList));
+ });
+ }
+
+ //add the resourceInstanceList for the service root node
+ for (let parent in parentNodesList) {
+ let resourceInstanceNode:ResourceInstanceNode = resourceInstanceMap.getValue(parent);
+ resourceInstanceNode.resourceInstancesList = parentNodesList[parent];
+ resourceInstanceNode.resourceInstancesList = parentNodesList[parent][RESOURCE_INSTANCE_LIST];
+ resourceInstanceNode.isAlreadyInTree = true;
+ scope.structureTree.serviceRoot.resourceInstancesList.push(resourceInstanceNode);
+ }
+
+ // Add all node that have no connection to the rootNode
+ resourceInstanceMap.forEach((key:string, value:ResourceInstanceNode) => {
+ if (!value.isAlreadyInTree) {
+ scope.structureTree.serviceRoot.resourceInstancesList.push(value);
+ }
+ });
+ }
+ };
+
+ //this recursion is merging all the subtrees
+ let mergeAllSubtrees = (connectionData:any, parentNodesList:any):ResourceInstanceNode => {
+ let resourceInstanceNode:ResourceInstanceNode = resourceInstanceMap.getValue(connectionData.toNode);
+ resourceInstanceNode.isAlreadyInTree = true;
+ if (parentNodesList[resourceInstanceNode.id]) {
+ if (parentNodesList[resourceInstanceNode.id][RESOURCE_INSTANCE_LIST]) {
+ resourceInstanceNode.resourceInstancesList = parentNodesList[resourceInstanceNode.id][RESOURCE_INSTANCE_LIST];
+ }
+ else {
+ _.forEach(parentNodesList[resourceInstanceNode.id], (children)=> {
+ resourceInstanceNode.resourceInstancesList.push(mergeAllSubtrees(children, parentNodesList));
+ });
+ }
+ delete parentNodesList[resourceInstanceNode.id];
+ }
+ return resourceInstanceNode;
+ };
+ //************* End Building Tree Functions *******************//
+
+ //************* Start Watchers *******************//
+ scope.$watch('component.name', ():void => {
+ if (scope.structureTree)
+ scope.structureTree.serviceRoot.name = scope.component.name;
+ });
+
+ scope.$watch('component.icon', ():void => {
+ if (scope.structureTree)
+ scope.structureTree.serviceRoot.icon = scope.component.icon;
+ });
+
+ scope.$watchCollection('component.componentInstancesRelations', ():void => {
+ buildTree();
+ });
+
+ scope.$watchCollection('component.componentInstances', ():void => {
+ buildTree();
+ });
+
+ //************* End Watchers *******************//
+
+ buildTree();
+
+ };
+
+
+ public static factory = () => {
+ return new StructureTreeDirective();
+ };
+}
+
+StructureTreeDirective.factory.$inject = [];
diff --git a/catalog-ui/app/scripts/directives/tag/tag-directive.html b/catalog-ui/src/app/directives/tag/tag-directive.html
index 28c22a7978..28c22a7978 100644
--- a/catalog-ui/app/scripts/directives/tag/tag-directive.html
+++ b/catalog-ui/src/app/directives/tag/tag-directive.html
diff --git a/catalog-ui/app/scripts/directives/tag/tag-directive.less b/catalog-ui/src/app/directives/tag/tag-directive.less
index f72e366ac6..f72e366ac6 100644
--- a/catalog-ui/app/scripts/directives/tag/tag-directive.less
+++ b/catalog-ui/src/app/directives/tag/tag-directive.less
diff --git a/catalog-ui/src/app/directives/tag/tag-directive.ts b/catalog-ui/src/app/directives/tag/tag-directive.ts
new file mode 100644
index 0000000000..77a26fc6f7
--- /dev/null
+++ b/catalog-ui/src/app/directives/tag/tag-directive.ts
@@ -0,0 +1,49 @@
+'use strict';
+
+export class TagData {
+ tag:string;
+ tooltip:string;
+ id:string;
+}
+
+export interface ITagScope extends ng.IScope {
+ tagData:TagData;
+ onDelete:Function;
+ delete:Function;
+ hideTooltip:boolean;
+ hideDelete:boolean;
+ sdcDisable:boolean;
+}
+
+export class TagDirective implements ng.IDirective {
+
+ constructor() {
+ }
+
+ scope = {
+ tagData: '=',
+ onDelete: '&',
+ hideTooltip: '=',
+ hideDelete: '=',
+ sdcDisable: '='
+ };
+
+ replace = true;
+ restrict = 'EA';
+ template = ():string => {
+ return require('./tag-directive.html');
+ };
+
+ link = (scope:ITagScope) => {
+ scope.delete = ()=> {
+ scope.onDelete({'uniqueId': scope.tagData.id});
+ }
+ };
+
+ public static factory = ()=> {
+ return new TagDirective();
+ };
+
+}
+
+TagDirective.factory.$inject = [];
diff --git a/catalog-ui/app/scripts/directives/user-header-details/user-header-details-directive.html b/catalog-ui/src/app/directives/user-header-details/user-header-details-directive.html
index 1c99a18ab5..1c99a18ab5 100644
--- a/catalog-ui/app/scripts/directives/user-header-details/user-header-details-directive.html
+++ b/catalog-ui/src/app/directives/user-header-details/user-header-details-directive.html
diff --git a/catalog-ui/app/scripts/directives/user-header-details/user-header-details-directive.less b/catalog-ui/src/app/directives/user-header-details/user-header-details-directive.less
index a14db7c6ee..e432581f3b 100644
--- a/catalog-ui/app/scripts/directives/user-header-details/user-header-details-directive.less
+++ b/catalog-ui/src/app/directives/user-header-details/user-header-details-directive.less
@@ -8,7 +8,7 @@
}
.w-sdc-header-user-icon {
- background: no-repeat url('../../../styles/images/anonymous.jpg');
+ background: no-repeat url('/assets/styles/images/anonymous.jpg');
border-radius: 50%;
height: 47px;
width: 47px;
diff --git a/catalog-ui/src/app/directives/user-header-details/user-header-details-directive.ts b/catalog-ui/src/app/directives/user-header-details/user-header-details-directive.ts
new file mode 100644
index 0000000000..a1a54b0517
--- /dev/null
+++ b/catalog-ui/src/app/directives/user-header-details/user-header-details-directive.ts
@@ -0,0 +1,52 @@
+'use strict';
+import {User, IUser, IAppConfigurtaion} from "app/models";
+import {IUserResourceClass, IUserResource} from "app/services";
+export interface IUserHeaderDetailsScope extends ng.IScope {
+ name:string;
+ role:string;
+ iconUrl:string;
+ UserResourceClass:IUserResourceClass;
+ user:IUser;
+ sdcConfig:IAppConfigurtaion;
+ initUser:Function;
+}
+
+export class UserHeaderDetailsDirective implements ng.IDirective {
+
+ constructor(private $http:ng.IHttpService, private sdcConfig:IAppConfigurtaion, private UserResourceClass:IUserResourceClass) {
+ }
+
+ scope = {
+ iconUrl: '=?'
+ };
+
+ replace = true;
+ restrict = 'E';
+ template = ():string => {
+ return require('./user-header-details-directive.html');
+ };
+
+ link = (scope:IUserHeaderDetailsScope) => {
+
+ scope.initUser = ():void => {
+ let defaultUserId:string;
+ let user:IUserResource = this.UserResourceClass.getLoggedinUser();
+ if (!user) {
+ defaultUserId = this.$http.defaults.headers.common[this.sdcConfig.cookie.userIdSuffix];
+ user = this.UserResourceClass.get({id: defaultUserId}, ():void => {
+ scope.user = new User(user);
+ });
+ } else {
+ scope.user = new User(user);
+ }
+ };
+ scope.initUser();
+ };
+
+ public static factory = ($http:ng.IHttpService, sdcConfig:IAppConfigurtaion, UserResourceClass:IUserResourceClass)=> {
+ return new UserHeaderDetailsDirective($http, sdcConfig, UserResourceClass);
+ };
+
+}
+
+UserHeaderDetailsDirective.factory.$inject = ['$http', 'sdcConfig', 'Sdc.Services.UserResourceService'];
diff --git a/catalog-ui/src/app/directives/utils/expand-collapse-list-header/expand-collapse-list-header.html b/catalog-ui/src/app/directives/utils/expand-collapse-list-header/expand-collapse-list-header.html
new file mode 100644
index 0000000000..b351273c08
--- /dev/null
+++ b/catalog-ui/src/app/directives/utils/expand-collapse-list-header/expand-collapse-list-header.html
@@ -0,0 +1,19 @@
+<div class="main-wrap" data-tests-id="list-of-{{title}}">
+ <div class="header">
+ <div class="title">{{title}}</div>
+ <div class="buttons">
+ <span class="order-by hand sprite-new"
+ data-ng-show="expandCollapseListData.expandCollapse"
+ data-ng-class="{'asc':!desc, 'desc':desc }"
+ data-ng-click="swapOrderBy()"></span>
+ <span class="search hand sprite-new search-icon"
+ data-ng-class="{'selected':showSearchBox}"
+ data-ng-show="expandCollapseListData.expandCollapse"
+ data-ng-click="showHideSearchBox()"></span>
+ <span class="hand sprite-new expand-list"
+ data-ng-class="{'open':expandCollapseListData.expandCollapse}"
+ data-ng-click="expandCollapseListData.expandCollapse=!expandCollapseListData.expandCollapse"></span>
+ </div>
+ </div>
+ <input type="text" id="list-search-box" class="search-box" data-ng-if="expandCollapseListData.expandCollapse && showSearchBox" data-ng-model="expandCollapseListData.filter" autofocus/>
+</div>
diff --git a/catalog-ui/src/app/directives/utils/expand-collapse-list-header/expand-collapse-list-header.less b/catalog-ui/src/app/directives/utils/expand-collapse-list-header/expand-collapse-list-header.less
new file mode 100644
index 0000000000..2a80f28007
--- /dev/null
+++ b/catalog-ui/src/app/directives/utils/expand-collapse-list-header/expand-collapse-list-header.less
@@ -0,0 +1,43 @@
+.main-wrap{
+ text-align: center;
+ .header{
+ background-color: @tlv_color_w;
+ height: 42px;
+ border-bottom: 1px solid rgba(0, 159, 219, 0.6);
+ border-top: 1px solid rgba(0, 159, 219, 0.6);
+ .title{
+ .f-type._14_m;
+ color: @main_color_l;
+ font-weight: 400;
+ line-height: 42px;
+ padding-left: 18px;
+ float: left;
+ }
+ .buttons{
+ float: right;
+ padding-right: 11px;
+ line-height: 42px;
+ span{
+ vertical-align: middle;
+ }
+ .search,.order-by{
+ margin-right: 5px;
+ }
+ //temporary///
+ .search{
+ display: none;
+ }
+ //////////////
+ }
+ }
+
+ .search-box{
+ border-radius: 2px;
+ height: 30px;
+ width:275px;
+ border: 1px @tlv_color_x solid;
+ margin: 8px 0;
+ padding: 0 5px;
+ }
+}
+
diff --git a/catalog-ui/src/app/directives/utils/expand-collapse-list-header/expand-collapse-list-header.ts b/catalog-ui/src/app/directives/utils/expand-collapse-list-header/expand-collapse-list-header.ts
new file mode 100644
index 0000000000..73cb2def0b
--- /dev/null
+++ b/catalog-ui/src/app/directives/utils/expand-collapse-list-header/expand-collapse-list-header.ts
@@ -0,0 +1,66 @@
+/**
+ * Created by rcohen on 12/5/2016.
+ */
+'use strict';
+
+export class ExpandCollapseListData {
+ filter:string;//variable for filter text
+ orderByField:string;//order by field name
+ expandCollapse:boolean;//boolean param for expand collapse the list
+}
+
+export interface IExpandCollapseListHeaderScope extends ng.IScope {
+ title:string;//the title on the header
+ expandCollapseListData:ExpandCollapseListData;
+ showSearchBox:boolean;
+ desc:boolean;//order by desc or asc
+
+ swapOrderBy():void;
+ showHideSearchBox():void;
+}
+
+export class ExpandCollapseListHeaderDirective implements ng.IDirective {
+
+ constructor(private $timeout:ng.ITimeoutService) {
+ }
+
+ scope = {
+ title: '@',
+ expandCollapseListData: '='
+ };
+
+ public replace = false;
+ public restrict = 'AE';
+ public transclude = true;
+
+ template = ():string => {
+ return require('./expand-collapse-list-header.html');
+ };
+
+ link = (scope:IExpandCollapseListHeaderScope, $elem:any) => {
+ scope.swapOrderBy = ():void => {
+ if (scope.expandCollapseListData.orderByField.charAt(0) === '-') {
+ scope.expandCollapseListData.orderByField = scope.expandCollapseListData.orderByField.substr(1);
+ } else {
+ scope.expandCollapseListData.orderByField = '-' + scope.expandCollapseListData.orderByField;
+ }
+ scope.desc = !scope.desc;
+ };
+
+ scope.showHideSearchBox = ():void => {
+ scope.showSearchBox = !scope.showSearchBox;
+ if (scope.showSearchBox) {
+ this.$timeout(function () {
+ angular.element("#list-search-box").focus();
+ }, 0);
+ }
+ };
+ };
+
+ public static factory = ($timeout:ng.ITimeoutService)=> {
+ return new ExpandCollapseListHeaderDirective($timeout);
+ };
+
+}
+
+ExpandCollapseListHeaderDirective.factory.$inject = ['$timeout'];
diff --git a/catalog-ui/src/app/directives/utils/expand-collapse-menu-box/expand-collaps-menu-box.ts b/catalog-ui/src/app/directives/utils/expand-collapse-menu-box/expand-collaps-menu-box.ts
new file mode 100644
index 0000000000..2a2432fcea
--- /dev/null
+++ b/catalog-ui/src/app/directives/utils/expand-collapse-menu-box/expand-collaps-menu-box.ts
@@ -0,0 +1,47 @@
+'use strict';
+import {MenuItem, MenuItemGroup} from "app/utils";
+
+export interface IExpandCollapseMenuBoxDirectiveScope extends ng.IScope {
+ menuItemsGroup:MenuItemGroup;
+ menuTitle:string;
+ parentScope:ng.IScope;
+ onMenuItemClick(menuItem:MenuItem):void;
+}
+
+export class ExpandCollapseMenuBoxDirective implements ng.IDirective {
+
+ constructor() {
+ }
+
+ scope = {
+ menuTitle: '@',
+ menuItemsGroup: '=',
+ parentScope: '='
+ };
+
+ public replace = false;
+ public restrict = 'AE';
+ public transclude = true;
+
+ template = ():string => {
+ return require('./expand-collapse-menu-box.html');
+ };
+
+ link = (scope:IExpandCollapseMenuBoxDirectiveScope) => {
+ scope.onMenuItemClick = (menuItem:MenuItem):void => {
+ let onSuccess = ():void => {
+ scope.menuItemsGroup.selectedIndex = scope.menuItemsGroup.menuItems.indexOf(menuItem);
+ };
+ let onFailed = ():void => {
+ };
+ scope.parentScope[menuItem.action](menuItem.state).then(onSuccess, onFailed);
+ }
+ };
+
+ public static factory = ()=> {
+ return new ExpandCollapseMenuBoxDirective();
+ };
+
+}
+
+ExpandCollapseMenuBoxDirective.factory.$inject = [];
diff --git a/catalog-ui/app/scripts/directives/utils/expand-collapse-menu-box/expand-collapse-menu-box.html b/catalog-ui/src/app/directives/utils/expand-collapse-menu-box/expand-collapse-menu-box.html
index bbd7e59e7c..f90f00f230 100644
--- a/catalog-ui/app/scripts/directives/utils/expand-collapse-menu-box/expand-collapse-menu-box.html
+++ b/catalog-ui/src/app/directives/utils/expand-collapse-menu-box/expand-collapse-menu-box.html
@@ -1,11 +1,13 @@
<div class="expand-collapse-menu-box">
<expand-collapse expanded-selector=".w-sdc-designer-sidebar-section-content" class="expand-collapse-menu-box-title">
- <div class="expand-collapse-menu-box-title-icon"></div>
- <span class="w-sdc-designer-sidebar-section-title-text" data-ng-bind="menuTitle" tooltips tooltip-content="{{menuTitle}}"></span>
+ <div class="expand-collapse-header">
+ <div class="expand-collapse-menu-box-title-icon"></div>
+ <span class="w-sdc-designer-sidebar-section-title-text" data-ng-bind="menuTitle" tooltips tooltip-content="{{menuTitle}}"></span>
+ </div>
</expand-collapse>
<div class="w-sdc-designer-sidebar-section-content" >
- <div class="i-sdc-designer-sidebar-section-content-item expand-collapse-menu-box-item"
+ <div class="i-sdc-designer-sidebar-section-content-item expand-collapse-menu-box-item second-level"
ng-class="{'selected': $index == menuItemsGroup.selectedIndex}" ng-repeat="(key, menuItem) in menuItemsGroup.menuItems track by $index">
<div class="expand-collapse-menu-box-item-text" ng-click="onMenuItemClick(menuItem)" ng-class="{'disabled': menuItem.isDisabled }" data-tests-id="{{menuItem.text}}step" >{{menuItem.text}}</div>
</div>
diff --git a/catalog-ui/app/scripts/directives/utils/expand-collapse-menu-box/expand-collapse-menu-box.less b/catalog-ui/src/app/directives/utils/expand-collapse-menu-box/expand-collapse-menu-box.less
index d8ceeaea71..13ec1c99be 100644
--- a/catalog-ui/app/scripts/directives/utils/expand-collapse-menu-box/expand-collapse-menu-box.less
+++ b/catalog-ui/src/app/directives/utils/expand-collapse-menu-box/expand-collapse-menu-box.less
@@ -1,14 +1,21 @@
.expand-collapse-menu-box {
line-height: 20px;
- padding: 13px 0px 5px 10px;
- background-color: @func_color_r;
- margin: 3px 3px 5px 0px;
+ //padding: 13px 0px 5px 10px;
+ background-color: @tlv_color_t;
+ //margin: 3px 3px 5px 0px;
+ .expand-collapse-header{
+ border-bottom: 1px solid @main_color_o;
+ height: @action_nav_height;
+ background-color:@main_color_p;
+ display:flex;
+ align-items:center;
+ }
.expand-collapse-menu-box-title {
.f-type._18_m;
- color: @main_color_m;
- font-weight: bold;
+ color: @main_color_a;
+ //font-weight: bold;
.hand;
.w-sdc-designer-sidebar-section-title-text{
max-width: 185px;
@@ -16,6 +23,7 @@
text-overflow: ellipsis;
display: inline-block;
white-space: nowrap;
+ padding: 8px 0;
}
&.expanded {
@@ -31,23 +39,27 @@
margin-right: 6px;
transition: .3s all;
position: relative;
-
+ vertical-align: text-top;
+ margin-left: 14px;
+ vertical-align: 14px;
}
.w-sdc-designer-sidebar-section-content {
overflow: hidden;
- padding-top: 13px;
+ //padding-top: 13px;
.expand-collapse-menu-box-item {
.hand;
padding-left: 14px;
- margin: 0px 0px 10px 10px;
+ //margin: 0px 0px 10px 10px;
font-family: @font-omnes-medium;
color: @main_color_m;
line-height: 18px;
&.selected {
- padding-left: 10px;
- font-weight: bold;
- border-left: 4px solid @main_color_a;
+ //padding-left: 10px;
+ //font-weight: bold;
+ //border-left: 4px solid @main_color_a;
+ background-color: #009fdb;
+ color: #ffffff;
}
}
diff --git a/catalog-ui/app/scripts/directives/utils/expand-collapse/expand-collapse.html b/catalog-ui/src/app/directives/utils/expand-collapse/expand-collapse.html
index a2358ea2b7..a2358ea2b7 100644
--- a/catalog-ui/app/scripts/directives/utils/expand-collapse/expand-collapse.html
+++ b/catalog-ui/src/app/directives/utils/expand-collapse/expand-collapse.html
diff --git a/catalog-ui/app/scripts/directives/utils/expand-collapse/expand-collapse.less b/catalog-ui/src/app/directives/utils/expand-collapse/expand-collapse.less
index d0d8fa3251..e6b7b7d516 100644
--- a/catalog-ui/app/scripts/directives/utils/expand-collapse/expand-collapse.less
+++ b/catalog-ui/src/app/directives/utils/expand-collapse/expand-collapse.less
@@ -8,3 +8,4 @@
text-decoration: underline;
text-align: left;
}
+
diff --git a/catalog-ui/src/app/directives/utils/expand-collapse/expand-collapse.ts b/catalog-ui/src/app/directives/utils/expand-collapse/expand-collapse.ts
new file mode 100644
index 0000000000..3993f06036
--- /dev/null
+++ b/catalog-ui/src/app/directives/utils/expand-collapse/expand-collapse.ts
@@ -0,0 +1,115 @@
+'use strict';
+export interface IExpandCollapseScope extends ng.IScope {
+ toggle():void;
+ collapsed:boolean;
+ expandedSelector:string;
+ content:string;
+ isCloseOnInit:boolean;
+ loadDataFunction:Function;
+ isLoadingData:boolean;
+}
+
+export class ExpandCollapseDirective implements ng.IDirective {
+
+ constructor() {
+ }
+
+ scope = {
+ expandedSelector: '@',
+ loadDataFunction: '&?',
+ isCloseOnInit: '=?'
+ };
+
+ public replace = false;
+ public restrict = 'AE';
+ public transclude = true;
+
+ template = ():string => {
+ return require('./expand-collapse.html');
+ };
+
+ link = (scope:IExpandCollapseScope, $elem:any) => {
+ scope.collapsed = false;
+ scope.isLoadingData = false;
+ $elem.addClass('expanded');
+
+
+ if (scope.isCloseOnInit) {
+ window.setTimeout(function () {
+ toggle();
+ }, 0);
+ }
+ //
+ // $elem.click(function () {
+ // toggle();
+ // });
+ $elem.bind('click', function() {
+ toggle();
+ })
+ let expand = ():void => {
+ $elem.addClass('expanded');
+ scope.collapsed = false;
+
+ let element = $(scope.expandedSelector)[0];
+ let prevWidth = element.style.height;
+ element.style.height = 'auto';
+ let endWidth = getComputedStyle(element).height;
+ element.style.height = prevWidth;
+ element.offsetHeight; // force repaint
+ element.style.transition = 'height .3s ease-in-out';
+ element.style.height = endWidth;
+ element.hidden = false;
+ element.addEventListener('transitionend', function transitionEnd(event) {
+ if (event['propertyName'] == 'height') {
+ element.style.transition = '';
+ element.style.height = 'auto';
+ element.removeEventListener('transitionend', transitionEnd, false);
+ }
+ }, false)
+ };
+
+ let collapse = ():void => {
+ $elem.removeClass('expanded');
+ scope.collapsed = true;
+
+ let element = $(scope.expandedSelector)[0];
+ element.style.height = getComputedStyle(element).height;
+ element.style.transition = 'height .5s ease-in-out';
+ element.offsetHeight; // force repaint
+ element.style.height = '0px';
+ element.hidden = true;
+ };
+
+ let toggle = ():void => {
+ if (scope.collapsed === true) {
+ if (scope.loadDataFunction) {
+ scope.isLoadingData = true;
+ let onSuccess = () => {
+ window.setTimeout(function () {
+ expand();
+ scope.isLoadingData = false;
+ }, 0);
+ };
+ scope.loadDataFunction().then(onSuccess);
+ }
+ else {
+ if (scope.isLoadingData === false) {
+ expand();
+ }
+ }
+
+ } else {
+ if (scope.isLoadingData === false) {
+ collapse();
+ }
+ }
+ }
+
+ };
+
+ public static factory = ()=> {
+ return new ExpandCollapseDirective();
+ };
+}
+
+ExpandCollapseDirective.factory.$inject = [];
diff --git a/catalog-ui/src/app/directives/utils/sdc-keyboard-events/sdc-keyboard-events.ts b/catalog-ui/src/app/directives/utils/sdc-keyboard-events/sdc-keyboard-events.ts
new file mode 100644
index 0000000000..71a963a492
--- /dev/null
+++ b/catalog-ui/src/app/directives/utils/sdc-keyboard-events/sdc-keyboard-events.ts
@@ -0,0 +1,84 @@
+'use strict';
+
+export interface ISdcKeyboardEventsScope extends ng.IScope {
+ keyEnter:Function;
+ keyShift:Function;
+ keyCtrl:Function;
+ keyEscape:Function;
+ keySpace:Function;
+}
+
+export class SdcKeyboardEventsDirective implements ng.IDirective {
+
+ constructor() {
+ }
+
+ scope = {
+ keyEnter: '=',
+ keyShift: '=',
+ keyCtrl: '=',
+ keyEscape: '=',
+ keySpace: '='
+ };
+
+ public replace = false;
+ public restrict = 'A';
+ public transclude = false;
+
+ link = (scope:ISdcKeyboardEventsScope, element:ng.IAugmentedJQuery, attrs:angular.IAttributes) => {
+
+ element.bind("keydown keypress", function (event) {
+ //console.log(event.which);
+ switch (event.which) {
+ case 13: // enter key
+ scope.$apply(function () {
+ if (scope.keyEnter) {
+ scope.keyEnter();
+ event.preventDefault();
+ }
+ });
+ break;
+ case 16: // shift key
+ scope.$apply(function () {
+ if (scope.keyShift) {
+ scope.keyShift();
+ event.preventDefault();
+ }
+ });
+ break;
+ case 17: // ctrl key
+ scope.$apply(function () {
+ if (scope.keyCtrl) {
+ scope.keyCtrl();
+ event.preventDefault();
+ }
+ });
+ break;
+ case 27: // escape key
+ scope.$apply(function () {
+ if (scope.keyEscape) {
+ scope.keyEscape();
+ event.preventDefault();
+ }
+ });
+ break;
+ case 32: // space key
+ scope.$apply(function () {
+ if (scope.keySpace) {
+ scope.keySpace();
+ event.preventDefault();
+ }
+ });
+ break;
+ }
+ });
+
+ };
+
+ public static factory = ()=> {
+ return new SdcKeyboardEventsDirective();
+ };
+
+}
+
+SdcKeyboardEventsDirective.factory.$inject = [];
diff --git a/catalog-ui/app/scripts/directives/utils/sdc-tags/sdc-tags.html b/catalog-ui/src/app/directives/utils/sdc-tags/sdc-tags.html
index fb1ada69c3..fb1ada69c3 100644
--- a/catalog-ui/app/scripts/directives/utils/sdc-tags/sdc-tags.html
+++ b/catalog-ui/src/app/directives/utils/sdc-tags/sdc-tags.html
diff --git a/catalog-ui/app/scripts/directives/utils/sdc-tags/sdc-tags.less b/catalog-ui/src/app/directives/utils/sdc-tags/sdc-tags.less
index 942196e663..942196e663 100644
--- a/catalog-ui/app/scripts/directives/utils/sdc-tags/sdc-tags.less
+++ b/catalog-ui/src/app/directives/utils/sdc-tags/sdc-tags.less
diff --git a/catalog-ui/src/app/directives/utils/sdc-tags/sdc-tags.ts b/catalog-ui/src/app/directives/utils/sdc-tags/sdc-tags.ts
new file mode 100644
index 0000000000..082a77dd9f
--- /dev/null
+++ b/catalog-ui/src/app/directives/utils/sdc-tags/sdc-tags.ts
@@ -0,0 +1,75 @@
+'use strict';
+
+export interface ISdcTagsScope extends ng.IScope {
+ tags:Array<string>;
+ specialTag:string;
+ newTag:string;
+ formElement:ng.IFormController;
+ elementName:string;
+ pattern:any;
+ sdcDisabled:boolean;
+ maxTags:number;
+ deleteTag(tag:string):void;
+ addTag(tag:string):void;
+ validateName():void;
+}
+
+export class SdcTagsDirective implements ng.IDirective {
+
+ constructor() {
+ }
+
+ scope = {
+ tags: '=',
+ specialTag: '=',
+ pattern: '=',
+ sdcDisabled: '=',
+ formElement: '=',
+ elementName: '@',
+ maxTags: '@'
+ };
+
+ public replace = false;
+ public restrict = 'E';
+ public transclude = false;
+
+ template = ():string => {
+ return require('./sdc-tags.html');
+ };
+
+ link = (scope:ISdcTagsScope, element:ng.INgModelController) => {
+
+ scope.deleteTag = (tag:string):void => {
+ scope.tags.splice(scope.tags.indexOf(tag), 1);
+ };
+
+ scope.addTag = ():void => {
+ let valid = scope.formElement[scope.elementName].$valid;
+ if (valid &&
+ scope.tags.length < scope.maxTags &&
+ scope.newTag &&
+ scope.newTag !== '' &&
+ scope.tags.indexOf(scope.newTag) === -1 &&
+ scope.newTag !== scope.specialTag) {
+ scope.tags.push(scope.newTag);
+ scope.newTag = '';
+ }
+ };
+
+ scope.validateName = ():void => {
+ if (scope.tags.indexOf(scope.newTag) > -1) {
+ scope.formElement[scope.elementName].$setValidity('nameExist', false);
+ } else {
+ scope.formElement[scope.elementName].$setValidity('nameExist', true);
+ }
+ }
+
+ };
+
+ public static factory = ()=> {
+ return new SdcTagsDirective();
+ };
+
+}
+
+SdcTagsDirective.factory.$inject = [];
diff --git a/catalog-ui/src/app/directives/utils/smart-tooltip/smart-tooltip.ts b/catalog-ui/src/app/directives/utils/smart-tooltip/smart-tooltip.ts
new file mode 100644
index 0000000000..d0177b4094
--- /dev/null
+++ b/catalog-ui/src/app/directives/utils/smart-tooltip/smart-tooltip.ts
@@ -0,0 +1,61 @@
+'use strict';
+
+export interface ISmartTooltipScope extends ng.IScope {
+ sdcSmartToolip;
+}
+
+export class SmartTooltipDirective implements ng.IDirective {
+
+ constructor(private $compile:ng.ICompileService) {
+ }
+
+ public replace = false;
+ public restrict = 'A';
+ public transclude = false;
+
+ public link = (scope:ISmartTooltipScope, $elem:ng.IAugmentedJQuery, $attrs:angular.IAttributes) => {
+
+ if ($elem[0].hasAttribute('style') === false) {
+ $elem[0].setAttribute("style", "overflow: hidden; white-space: nowrap; text-overflow: ellipsis;");
+ } else {
+ let styles = $elem.attr('style');
+ $elem[0].setAttribute("style", styles + ";overflow: hidden; white-space: nowrap; text-overflow: ellipsis;");
+ }
+
+ $elem.bind('mouseenter', () => {
+ if ($elem[0].offsetWidth < $elem[0].scrollWidth && !$elem.attr('tooltips')) {
+ $attrs.$set('tooltips', 'tooltips');
+ if ($attrs['sdcSmartTooltip'] && $attrs['sdcSmartTooltip'].length > 0) {
+ $elem.attr('tooltip-content', $attrs['sdcSmartTooltip']);
+ } else {
+ $attrs.$set('tooltip-content', $elem.text());
+ }
+
+ //One possible problem arises when the ngIf is placed on the root element of the template.
+ //ngIf removes the node and places a comment in it's place. Then it watches over the expression and adds/removes the actual HTML element as necessary.
+ //The problem seems to be that if it is placed on the root element of the template, then a single comment is what is left from the
+ //whole template (even if only temporarily), which gets ignored (I am not sure if this is browser-specific behaviour), resulting in an empty template.
+
+ // Remove ng-if attribute and its value (if we reach here, we pass ng-if (ng-if===true), so we can remove it).
+ $elem.removeAttr('ng-if');
+ $elem.removeAttr('data-ng-if');
+
+ // Remove me (the directive from the element)
+ let template = $elem[0].outerHTML;
+ template = template.replace('sdc-smart-tooltip=""', '');
+ template = template.replace('sdc-smart-tooltip="' + $elem.text() + '"', '');
+ //console.log(template);
+
+ let el = this.$compile(template)(scope);
+ console.log(el);
+ $elem.replaceWith(el);
+ }
+ });
+ };
+
+ public static factory = ($compile:ng.ICompileService)=> {
+ return new SmartTooltipDirective($compile);
+ };
+}
+
+SmartTooltipDirective.factory.$inject = ['$compile'];
diff --git a/catalog-ui/src/app/directives/utils/validation-on-load/validation-on-load.ts b/catalog-ui/src/app/directives/utils/validation-on-load/validation-on-load.ts
new file mode 100644
index 0000000000..d489efa928
--- /dev/null
+++ b/catalog-ui/src/app/directives/utils/validation-on-load/validation-on-load.ts
@@ -0,0 +1,48 @@
+'use strict';
+
+export interface IValidationOnLoadScope extends ng.IScope {
+ formToValidate:ng.IFormController;
+}
+
+export class ValidationOnLoadDirective implements ng.IDirective {
+
+ constructor(private $timeout:ng.ITimeoutService) {
+ }
+
+ scope = {
+ formToValidate: '='
+ };
+
+ public replace = false;
+ public restrict = 'A';
+
+
+ public link = (scope:IValidationOnLoadScope, $elem:ng.IAugmentedJQuery, $attrs:angular.IAttributes) => {
+
+ let init = ()=> {
+ //validate errors
+ if (scope.formToValidate.$error) {
+ angular.forEach(scope.formToValidate.$error, (value, key)=> {
+ //skip on the required error if its a new form
+ if (key != 'required') {
+ angular.forEach(value, function (field) {
+ field.$setDirty();//trigger to show the error label
+ });
+ }
+ })
+ }
+ };
+
+ this.$timeout(()=> {
+ init();
+ }, 0);
+
+ };
+
+ public static factory = ($timeout:ng.ITimeoutService)=> {
+ return new ValidationOnLoadDirective($timeout);
+ };
+
+}
+
+ValidationOnLoadDirective.factory.$inject = ['$timeout'];
diff --git a/catalog-ui/src/app/filters.ts b/catalog-ui/src/app/filters.ts
new file mode 100644
index 0000000000..3a71c73289
--- /dev/null
+++ b/catalog-ui/src/app/filters.ts
@@ -0,0 +1,15 @@
+/**
+ * Created by ob0695 on 2/26/2017.
+ */
+export * from './filters/catalog-status-filter';
+export * from './filters/category-type-filter';
+export * from './filters/clear-whitespaces-filter';
+export * from './filters/entity-filter';
+export * from './filters/graph-resource-name-filter';
+export * from './filters/resource-name-filter';
+export * from './filters/resource-type-filter';
+export * from './filters/string-to-date-filter';
+export * from './filters/tests-id-filter';
+export * from './filters/trim-filter';
+export * from './filters/truncate-filter';
+
diff --git a/catalog-ui/src/app/filters/catalog-status-filter.ts b/catalog-ui/src/app/filters/catalog-status-filter.ts
new file mode 100644
index 0000000000..c28ec1d1e5
--- /dev/null
+++ b/catalog-ui/src/app/filters/catalog-status-filter.ts
@@ -0,0 +1,18 @@
+/**
+ * Created by obarda on 19/08/2015.
+ */
+export class CatalogStatusFilter {
+
+ constructor() {
+ let filter = <CatalogStatusFilter>( (statuses:any) => {
+ let filtered = [];
+ angular.forEach(statuses, function (status) {
+ filtered.push(status);
+ });
+ return filtered;
+ });
+
+ return filter;
+ }
+}
+
diff --git a/catalog-ui/src/app/filters/category-type-filter.ts b/catalog-ui/src/app/filters/category-type-filter.ts
new file mode 100644
index 0000000000..66663263c3
--- /dev/null
+++ b/catalog-ui/src/app/filters/category-type-filter.ts
@@ -0,0 +1,28 @@
+import {ComponentType} from "../utils/constants";
+import {CacheService} from "../services/cache-service";
+export class CategoryTypeFilter {
+
+ static $inject = ['Sdc.Services.CacheService'];
+
+ constructor(cacheService:CacheService) {
+ let filter = <CategoryTypeFilter>(categories:any, selectedType:Array<string>, selectedSubResourceTypes:Array<string>) => {
+
+ if (selectedType.indexOf(ComponentType.RESOURCE) === -1 && selectedSubResourceTypes.length > 0) {
+ selectedType = selectedType.concat([ComponentType.RESOURCE]);
+ }
+
+ if (!selectedType.length)
+ return categories;
+
+ let filteredCategories:any = [];
+ selectedType.forEach((type:string) => {
+ filteredCategories = filteredCategories.concat(cacheService.get(type.toLowerCase() + 'Categories'));
+ });
+
+ return _.filter(categories, function (category:any) {
+ return filteredCategories.indexOf(category) != -1;
+ });
+ };
+ return filter;
+ }
+}
diff --git a/catalog-ui/src/app/filters/clear-whitespaces-filter.ts b/catalog-ui/src/app/filters/clear-whitespaces-filter.ts
new file mode 100644
index 0000000000..ea6129e22b
--- /dev/null
+++ b/catalog-ui/src/app/filters/clear-whitespaces-filter.ts
@@ -0,0 +1,16 @@
+export class ClearWhiteSpacesFilter {
+
+ constructor() {
+ let filter = <ClearWhiteSpacesFilter>( (text:string) => {
+ if (!angular.isString(text)) {
+ return text;
+ }
+
+ return text.replace(/ /g, ''); // remove also whitespaces inside
+ });
+
+ return filter;
+ }
+}
+
+
diff --git a/catalog-ui/app/scripts/filters/entity-filter.ts b/catalog-ui/src/app/filters/entity-filter.ts
index ce60d69833..97d9b85f9b 100644
--- a/catalog-ui/app/scripts/filters/entity-filter.ts
+++ b/catalog-ui/src/app/filters/entity-filter.ts
@@ -1,38 +1,17 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../references"/>
-module Sdc.Filters {
-
- export class EntityFilter{
+import {Component, Resource} from "../models";
+export class EntityFilter {
constructor() {
- let filter = <EntityFilter>( (components:Array<Models.Components.Component>, filter:any) => {
+ let filter = <EntityFilter>( (components:Array<Component>, filter:any) => {
- let filteredComponents:Array<Models.Components.Component> = components;
+ let filteredComponents:Array<Component> = components;
// filter by type
// --------------------------------------------------------------------------
- if ((filter.selectedComponentTypes && filter.selectedComponentTypes.length>0) || (filter.selectedResourceSubTypes && filter.selectedResourceSubTypes.length>0)) {
+ if ((filter.selectedComponentTypes && filter.selectedComponentTypes.length > 0) || (filter.selectedResourceSubTypes && filter.selectedResourceSubTypes.length > 0)) {
let filteredTypes = [];
- angular.forEach(components, (component:Models.Components.Component):void => {
+ angular.forEach(components, (component:Component):void => {
// Filter by component type
let typeLower:string = component.componentType.toLowerCase();
let typeFirstCapital:string = typeLower.charAt(0).toUpperCase() + typeLower.slice(1);
@@ -43,7 +22,7 @@ module Sdc.Filters {
// Filter by resource sub type, only in case the resource checkbox was not selected (because in this case we already added all the components in above section).
if (component.isResource() && filter.selectedComponentTypes.indexOf("Resource") === -1 && filter.selectedResourceSubTypes.length > 0) {
//filteredComponents.pop(); // Remove the last inserted component.
- let resource:Sdc.Models.Components.Resource = <Sdc.Models.Components.Resource>component;
+ let resource:Resource = <Resource>component;
if (filter.selectedResourceSubTypes.indexOf(resource.getComponentSubType()) !== -1) {
filteredTypes.push(component);
}
@@ -54,9 +33,9 @@ module Sdc.Filters {
// filter by categories & subcategories & groupings
// --------------------------------------------------------------------------
- if (filter.selectedCategoriesModel && filter.selectedCategoriesModel.length>0) {
+ if (filter.selectedCategoriesModel && filter.selectedCategoriesModel.length > 0) {
let filteredCategories = [];
- angular.forEach(filteredComponents, (component:Models.Components.Component):void => {
+ 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) {
@@ -72,16 +51,16 @@ module Sdc.Filters {
// --------------------------------------------------------------------------
if (filter.selectedStatuses && filter.selectedStatuses.length > 0) {
//convert array of array to string array
- let selectedStatuses:Array<string> = [].concat.apply([],filter.selectedStatuses);
+ let selectedStatuses:Array<string> = [].concat.apply([], filter.selectedStatuses);
let filteredStatuses = [];
- angular.forEach(filteredComponents, (component:Models.Components.Component):void => {
+ angular.forEach(filteredComponents, (component:Component):void => {
if (selectedStatuses.indexOf(component.lifecycleState) > -1) {
filteredStatuses.push(component);
}
//if status DISTRIBUTED && CERTIFIED are selected the component will added in CERTIFIED status , not need to add twice
- if(selectedStatuses.indexOf('DISTRIBUTED') > -1 && !(selectedStatuses.indexOf('CERTIFIED') > -1)){
- if( component.distributionStatus && component.distributionStatus.indexOf('DISTRIBUTED') > -1 && component.lifecycleState.indexOf('CERTIFIED') > -1){
+ if (selectedStatuses.indexOf('DISTRIBUTED') > -1 && !(selectedStatuses.indexOf('CERTIFIED') > -1)) {
+ if (component.distributionStatus && component.distributionStatus.indexOf('DISTRIBUTED') > -1 && component.lifecycleState.indexOf('CERTIFIED') > -1) {
filteredStatuses.push(component);
}
}
@@ -92,13 +71,13 @@ module Sdc.Filters {
// filter by statuses and distributed
// --------------------------------------------------------------------------
if (filter.distributed != undefined && filter.distributed.length > 0) {
- let filterDistributed: Array<any> = filter.distributed;
+ let filterDistributed:Array<any> = filter.distributed;
let filteredDistributed = [];
angular.forEach(filteredComponents, (entity) => {
filterDistributed.forEach((distribute) => {
let distributeItem = distribute.split(',');
distributeItem.forEach((item) => {
- if (item !== undefined && entity.distributionStatus === item){
+ if (item !== undefined && entity.distributionStatus === item) {
filteredDistributed.push(entity);
}
})
@@ -107,11 +86,9 @@ module Sdc.Filters {
filteredComponents = filteredDistributed;
}
- return filteredComponents;
- });
+ return filteredComponents;
+ });
- return filter;
+ return filter;
}
- }
-
}
diff --git a/catalog-ui/src/app/filters/graph-resource-name-filter.ts b/catalog-ui/src/app/filters/graph-resource-name-filter.ts
new file mode 100644
index 0000000000..a4698612f6
--- /dev/null
+++ b/catalog-ui/src/app/filters/graph-resource-name-filter.ts
@@ -0,0 +1,22 @@
+export class GraphResourceNameFilter {
+
+ constructor() {
+ let filter = <GraphResourceNameFilter>( (name:string) => {
+ let context = document.createElement("canvas").getContext("2d");
+ context.font = "13px Arial";
+
+ if (67 < context.measureText(name).width) {
+ let newLen = name.length - 3;
+ let newName = name.substring(0, newLen);
+
+ while (59 < (context.measureText(newName).width)) {
+ newName = newName.substring(0, (--newLen));
+ }
+ return newName + '...';
+ }
+
+ return name;
+ });
+ return filter;
+ }
+}
diff --git a/catalog-ui/src/app/filters/resource-name-filter.ts b/catalog-ui/src/app/filters/resource-name-filter.ts
new file mode 100644
index 0000000000..cd0189dc9a
--- /dev/null
+++ b/catalog-ui/src/app/filters/resource-name-filter.ts
@@ -0,0 +1,21 @@
+export class ResourceNameFilter {
+
+
+ constructor() {
+ let filter = <ResourceNameFilter>( (name:string) => {
+ if (name) {
+ //let newName:string = _.last(name.split('.'));
+ let newName =
+ _.last(_.last(_.last(_.last(_.last(_.last(_.last(_.last(name.split('tosca.nodes.'))
+ .split('network.')).split('relationships.')).split('org.openecomp.')).split('resource.nfv.'))
+ .split('nodes.module.')).split('cp.')).split('vl.'));
+ if (newName) {
+ return newName;
+ }
+ return name;
+ }
+ });
+
+ return filter;
+ }
+}
diff --git a/catalog-ui/src/app/filters/resource-type-filter.ts b/catalog-ui/src/app/filters/resource-type-filter.ts
new file mode 100644
index 0000000000..f2d06f0edd
--- /dev/null
+++ b/catalog-ui/src/app/filters/resource-type-filter.ts
@@ -0,0 +1,17 @@
+import {CacheService} from "../services/cache-service";
+
+export class ResourceTypeFilter {
+ static '$inject' = ['Sdc.Services.CacheService'];
+
+ constructor(cacheService:CacheService) {
+ let filter = <ResourceTypeFilter>(resourceType:string) => {
+ let uiConfiguration:any = cacheService.get('UIConfiguration');
+
+ if (uiConfiguration.resourceTypes && uiConfiguration.resourceTypes[resourceType]) {
+ return uiConfiguration.resourceTypes[resourceType];
+ }
+ return resourceType;
+ }
+ return filter;
+ }
+}
diff --git a/catalog-ui/src/app/filters/string-to-date-filter.ts b/catalog-ui/src/app/filters/string-to-date-filter.ts
new file mode 100644
index 0000000000..846180a2cc
--- /dev/null
+++ b/catalog-ui/src/app/filters/string-to-date-filter.ts
@@ -0,0 +1,12 @@
+export class StringToDateFilter {
+
+ constructor() {
+ let filter = <StringToDateFilter>( (date:string) => {
+ if (date) {
+ return new Date(date.replace(" UTC", '').replace(" ", 'T') + '+00:00');
+ }
+ });
+ return filter;
+ }
+}
+
diff --git a/catalog-ui/src/app/filters/tests-id-filter.ts b/catalog-ui/src/app/filters/tests-id-filter.ts
new file mode 100644
index 0000000000..0e5af31169
--- /dev/null
+++ b/catalog-ui/src/app/filters/tests-id-filter.ts
@@ -0,0 +1,11 @@
+export class TestsIdFilter {
+
+ constructor() {
+ let filter = <TestsIdFilter>( (testId:string) => {
+ return testId.replace(/\s/g, '_').toLowerCase();
+ });
+
+ return filter;
+ }
+}
+
diff --git a/catalog-ui/src/app/filters/trim-filter.ts b/catalog-ui/src/app/filters/trim-filter.ts
new file mode 100644
index 0000000000..f174034748
--- /dev/null
+++ b/catalog-ui/src/app/filters/trim-filter.ts
@@ -0,0 +1,15 @@
+export class TrimFilter {
+
+ constructor() {
+ let filter = <TrimFilter>( (text:string) => {
+ if (!angular.isString(text)) {
+ return text;
+ }
+
+ return text.replace(/^\s+|\s+$/g, ''); // you could use .trim, but it's not going to work in IE<9
+ });
+
+ return filter;
+ }
+}
+
diff --git a/catalog-ui/src/app/filters/truncate-filter.ts b/catalog-ui/src/app/filters/truncate-filter.ts
new file mode 100644
index 0000000000..e660871e3b
--- /dev/null
+++ b/catalog-ui/src/app/filters/truncate-filter.ts
@@ -0,0 +1,26 @@
+export class TruncateFilter {
+ constructor() {
+ let filter = <TruncateFilter>(str:string, length:number) => {
+ if (str.length <= length) {
+ return str;
+ }
+
+ //if(str[length - 1] === ' '){
+ // return str.substring(0, length - 1) + '...';
+ //}
+
+ let char;
+ let index = length;
+ while (char !== ' ' && index !== 0) {
+ index--;
+ char = str[index];
+ }
+ if (index === 0) {
+ return (index === 0) ? str : str.substring(0, length - 3) + '...';
+ }
+ return (index === 0) ? str : str.substring(0, index) + '...';
+ };
+ return filter;
+ }
+
+}
diff --git a/catalog-ui/src/app/models.ts b/catalog-ui/src/app/models.ts
new file mode 100644
index 0000000000..5b286d0667
--- /dev/null
+++ b/catalog-ui/src/app/models.ts
@@ -0,0 +1,84 @@
+/**
+ * Created by ob0695 on 2/23/2017.
+ */
+import from = require("core-js/fn/array/from");
+export * from './models/activity';
+export * from './models/additional-information';
+export * from './models/app-config';
+export * from './models/validation-config';
+export * from './models/artifacts';
+export * from './models/aschema-property';
+export * from './models/schema-attribute';
+export * from './models/attributes';
+export * from './models/capability';
+export * from './models/category';
+export * from './models/comments';
+export * from './models/components/component';
+export * from './models/components/displayComponent';
+export * from './models/components/product';
+export * from './models/components/resource';
+export * from './models/components/service';
+export * from './models/componentsInstances/componentInstance';
+export * from './models/componentsInstances/productInstance';
+export * from './models/componentsInstances/resourceInstance';
+export * from './models/componentsInstances/serviceInstance';
+export * from './models/csar-component';
+//export * from './models/data-type-properties';
+export * from './models/properties-inputs/property-be-model';
+export * from './models/properties-inputs/property-fe-model';
+export * from './models/properties-inputs/property-fe-map';
+export * from './models/properties-inputs/derived-fe-property';
+export * from './models/properties-inputs/input-fe-model';
+export * from './models/data-types-map';
+export * from './models/data-types';
+export * from './models/distribution';
+export * from './models/export-excel';
+export * from './models/file-download';
+export * from './models/graph/graph-links/common-base-link';
+export * from './models/graph/graph-links/common-ci-link-base';
+export * from './models/graph/graph-links/composition-graph-links/composition-ci-link-base';
+export * from './models/graph/graph-links/composition-graph-links/composition-ci-simple-link';
+export * from './models/graph/graph-links/composition-graph-links/composition-ci-ucpe-host-link';
+export * from './models/graph/graph-links/composition-graph-links/composition-ci-ucpe-link';
+export * from './models/graph/graph-links/composition-graph-links/composition-ci-vl-link';
+export * from './models/graph/graph-links/composition-graph-links/composition-ci-vl-ucpe-link';
+export * from './models/graph/graph-links/links-factory';
+export * from './models/graph/graph-links/module-graph-links/module-ci-link-base';
+export * from './models/graph/graph-links/module-graph-links/module-ci-vl-link';
+export * from './models/graph/graphTooltip';
+export * from './models/graph/assetPopoverObj';
+export * from './models/graph/link-menu';
+export * from './models/graph/match-relation';
+export * from './models/graph/nodes/base-common-node';
+export * from './models/graph/nodes/common-ci-node-base';
+export * from './models/graph/nodes/composition-graph-nodes/composition-ci-node-base';
+export * from './models/graph/nodes/composition-graph-nodes/composition-ci-node-cp';
+export * from './models/graph/nodes/composition-graph-nodes/composition-ci-node-service';
+export * from './models/graph/nodes/composition-graph-nodes/composition-ci-node-ucpe-cp';
+export * from './models/graph/nodes/composition-graph-nodes/composition-ci-node-ucpe';
+export * from './models/graph/nodes/composition-graph-nodes/composition-ci-node-vf';
+export * from './models/graph/nodes/composition-graph-nodes/composition-ci-node-vfc';
+export * from './models/graph/nodes/composition-graph-nodes/composition-ci-node-vl';
+export * from './models/graph/nodes/modules-graph-nodes/module-node-base';
+export * from './models/graph/nodes/nodes-factory';
+export * from './models/graph/point';
+export * from './models/graph/relationMenuObjects';
+export * from './models/graph/relationship';
+export * from './models/heat-parameters';
+export * from './models/input-property-base';
+export * from './models/inputs-and-properties';
+export * from './models/inputs';
+export * from './models/instance-inputs-properties-map';
+export * from './models/left-panel';
+export * from './models/member';
+export * from './models/modules/base-module';
+export * from './models/properties';
+export * from './models/requirement';
+export * from './models/tab';
+export * from './models/tooltip-data';
+export * from './models/user';
+export * from './models/validate';
+export * from './models/component-metadata';
+
+export * from './models/button';
+export * from './models/filter-properties-assignment-data'
diff --git a/catalog-ui/src/app/models/activity.ts b/catalog-ui/src/app/models/activity.ts
new file mode 100644
index 0000000000..d60e69258c
--- /dev/null
+++ b/catalog-ui/src/app/models/activity.ts
@@ -0,0 +1,27 @@
+/**
+ * Created by obarda on 19/11/2015.
+ */
+'use strict';
+
+/*this is in uppercase because of the server response*/
+export class Activity {
+ TIMESTAMP:string;
+ ACTION:string;
+ MODIFIER:string;
+ STATUS:string;
+ DESC:string;
+ COMMENT:string;
+ //custom data
+ public dateFormat:string;
+
+ constructor() {
+ }
+
+ public toJSON = ():any => {
+ this.dateFormat = undefined;
+ return this;
+ };
+
+}
+
+
diff --git a/catalog-ui/src/app/models/additional-information.ts b/catalog-ui/src/app/models/additional-information.ts
new file mode 100644
index 0000000000..0fc850a227
--- /dev/null
+++ b/catalog-ui/src/app/models/additional-information.ts
@@ -0,0 +1,20 @@
+'use strict';
+export interface IAdditionalInformationModel {
+ uniqueId:string;
+ key:string;
+ value:string;
+}
+
+
+export class AdditionalInformationModel implements IAdditionalInformationModel {
+ uniqueId:string;
+ key:string;
+ value:string;
+
+ constructor() {
+ this.uniqueId = '';
+ this.key = '';
+ this.value = '';
+
+ }
+}
diff --git a/catalog-ui/src/app/models/app-config.ts b/catalog-ui/src/app/models/app-config.ts
new file mode 100644
index 0000000000..a80dd40da8
--- /dev/null
+++ b/catalog-ui/src/app/models/app-config.ts
@@ -0,0 +1,226 @@
+'use strict';
+export interface IApi {
+ baseUrl:string;
+
+ //***** NEW API *******//
+ GET_component:string;
+ PUT_component:string;
+ GET_component_validate_name:string;
+ POST_changeLifecycleState:string;
+ component_api_root:string;
+ //*********//
+
+ GET_user:string;
+ GET_user_authorize:string;
+ GET_all_users:string;
+ POST_create_user;
+ DELETE_delete_user;
+ POST_edit_user_role;
+ GET_resource:string;
+ GET_resources_latestversion_notabstract:string;
+ GET_resources_certified_not_abstract:string;
+ GET_resources_certified_abstract:string;
+ PUT_resource:string;
+ GET_resource_property:string;
+ GET_resource_artifact:string;
+ GET_download_instance_artifact:string;
+ POST_instance_artifact:string;
+ GET_resource_additional_information:string;
+ GET_service_artifact:string;
+ GET_resource_interface_artifact:string;
+ GET_resource_api_artifact:string;
+ GET_resource_validate_name:string;
+ GET_resource_artifact_types:string;
+ GET_activity_log:string;
+ GET_configuration_ui:string;
+ GET_service:string;
+ PUT_product:string;
+ GET_product:string;
+ GET_ecomp_menu_items:string;
+ GET_product_validate_name:string;
+ GET_service_validate_name:string;
+ GET_service_distributions:string;
+ GET_service_distributions_components:string;
+ POST_service_distribution_deploy:string;
+ GET_element:string;
+ GET_catalog:string;
+ GET_resource_category:string;
+ GET_service_category:string;
+ resource_instance:string;
+ GET_resource_instance_property:string;
+ GET_relationship:string;
+ GET_lifecycle_state_resource:string;
+ GET_lifecycle_state_CHECKIN:string;
+ GET_lifecycle_state_CERTIFICATIONREQUEST:string;
+ GET_lifecycle_state_UNDOCHECKOUT:string;
+ root:string;
+ PUT_service:string;
+ GET_download_artifact:string;
+ GET_SDC_Version:string;
+ GET_categories:string;
+ POST_category:string;
+ POST_subcategory:string;
+ POST_change_instance_version:string;
+ GET_requirements_capabilities:string;
+ GET_onboarding:string;
+ GET_component_from_csar_uuid:string;
+ kibana:string;
+
+ //Added by Ikram -- starts
+ GET_product_category:string;
+ GET_product_category_temp:string;
+ GET_product_sub_category:string;
+ //Added by Ikram -- ends
+
+}
+
+export interface ILogConfig {
+ minLogLevel:string;
+ prefix:string;
+}
+
+export interface ICookie {
+ junctionName:string;
+ prefix:string;
+ userIdSuffix:string;
+ userFirstName:string;
+ userLastName:string;
+ userEmail:string;
+}
+export interface IUserTypes {
+ admin:any;
+ designer:any;
+ tester:any;
+}
+
+export interface IConfigStatuses {
+ inDesign:IConfigStatus;
+ readyForCertification:IConfigStatus;
+ inCertification:IConfigStatus;
+ certified:IConfigStatus;
+ distributed:IConfigStatus;
+}
+
+export interface IConfigStatus {
+ name:string;
+ values:Array<string>;
+}
+
+export interface IConfigRoles {
+ ADMIN:IConfigRole;
+ DESIGNER:IConfigRole;
+ TESTER:IConfigRole;
+ OPS:IConfigRole;
+ GOVERNOR:IConfigRole;
+ PRODUCT_MANAGER:IConfigRole;
+ PRODUCT_STRATEGIST:IConfigRole;
+}
+
+export interface IConfigRole {
+ pages:Array<string>;
+ states:IConfigState;
+}
+
+export interface IConfigState {
+ NOT_CERTIFIED_CHECKOUT:Array<IConfigDistribution>;
+ NOT_CERTIFIED_CHECKIN:Array<IConfigDistribution>;
+ READY_FOR_CERTIFICATION:Array<IConfigDistribution>;
+ CERTIFICATION_IN_PROGRESS:Array<IConfigDistribution>;
+ CERTIFIED:Array<IConfigDistribution>;
+}
+
+export interface IConfigDistribution {
+ DISTRIBUTION_NOT_APPROVED:Array<ConfigMenuItem>;
+ DISTRIBUTION_APPROVED:Array<ConfigMenuItem>;
+ DISTRIBUTED:Array<ConfigMenuItem>;
+ DISTRIBUTION_REJECTED:Array<ConfigMenuItem>;
+}
+
+export interface IConfirmationMessage {
+ showComment:boolean;
+ title:string;
+ message:string;
+}
+
+export interface IConfirmationMessages {
+ checkin:IConfirmationMessage;
+ checkout:IConfirmationMessage;
+ certify:IConfirmationMessage;
+ failCertification:IConfirmationMessage;
+ certificationRequest:IConfirmationMessage;
+ approve:IConfirmationMessage;
+ reject:IConfirmationMessage;
+}
+
+export interface IAlertMessage {
+ title:string;
+ message:string;
+}
+
+export interface IAlertMessages {
+ deleteInstance:IAlertMessage;
+ exitWithoutSaving:IConfirmationMessage;
+}
+
+class ConfigMenuItem {
+ text:string;
+ action:string;
+ url:string;
+ disable:boolean = false;
+}
+
+export interface IAppConfigurtaion {
+ environment:string;
+ api:IApi;
+ hostedApplications:Array<IHostedApplication>;
+ resourceTypesFilter:IResourceTypesFilter;
+ logConfig:ILogConfig;
+ cookie:ICookie;
+ imagesPath:string;
+ toscaFileExtension:string;
+ csarFileExtension:string;
+ testers:Array<ITester>
+ tutorial:any;
+ roles:Array<string>;
+ cpEndPointInstances:Array<string>;
+ openSource:boolean;
+ showOutlook:boolean;
+ validationConfigPath:string;
+}
+
+export interface IResourceTypesFilter {
+ resource:Array<string>;
+}
+
+export interface IHostedApplication {
+ moduleName:string;
+ navTitle:string;
+ defaultState:string;
+ exists?:boolean;
+ state:IHostedApplicationState;
+}
+
+export interface IHostedApplicationState {
+ name:string;
+ url:string;
+ relativeHtmlPath:string;
+ controllerName:string;
+}
+
+export interface ITester {
+ email:string;
+}
+
+export interface IAppMenu {
+ roles:IConfigRoles;
+ confirmationMessages:IConfirmationMessages;
+ alertMessages:IAlertMessages;
+ statuses:IConfigStatuses;
+ catalogMenuItem:any;
+ categoriesDictionary:any;
+ canvas_buttons:Object;
+ component_workspace_menu_option:any;
+ LifeCycleStatuses:any;
+ DistributionStatuses:any;
+ ChangeLifecycleStateButton:any;
+}
diff --git a/catalog-ui/src/app/models/artifacts.ts b/catalog-ui/src/app/models/artifacts.ts
new file mode 100644
index 0000000000..63e4b594f1
--- /dev/null
+++ b/catalog-ui/src/app/models/artifacts.ts
@@ -0,0 +1,101 @@
+'use strict';
+
+import {ArtifactType} from './../utils';
+import {HeatParameterModel} from "./heat-parameters";
+
+//this object contains keys, each key contain ArtifactModel
+export class ArtifactGroupModel {
+
+ constructor(artifacts?:ArtifactGroupModel) {
+ _.forEach(artifacts, (artifact:ArtifactModel, key) => {
+ this[key] = new ArtifactModel(artifact);
+ });
+ }
+
+ public filteredByType(type:string):ArtifactGroupModel {
+ let tmpArtifactGroupModel = new ArtifactGroupModel();
+ _.each(Object.keys(this), (key)=>{
+ if (this[key].artifactType === type) {
+ tmpArtifactGroupModel[key] = this[key];
+ }
+ });
+ return tmpArtifactGroupModel;
+ };
+}
+
+export class ArtifactModel {
+
+ artifactDisplayName:string;
+ artifactGroupType:string;
+ uniqueId:string;
+ artifactName:string;
+ artifactLabel:string;
+ artifactType:string;
+ artifactUUID:string;
+ artifactVersion:string;
+ creatorFullName:string;
+ creationDate:number;
+ lastUpdateDate:number;
+ description:string;
+ mandatory:boolean;
+ serviceApi:boolean;
+ payloadData:string;
+ timeout:number;
+ esId:string;
+ "Content-MD5":string;
+ artifactChecksum:string;
+ apiUrl:string;
+ heatParameters:Array<HeatParameterModel>;
+ generatedFromId:string;
+
+ //custom properties
+ selected:boolean;
+ originalDescription:string;
+ envArtifact:ArtifactModel;
+
+ constructor(artifact?:ArtifactModel) {
+ if (artifact) {
+ this.artifactDisplayName = artifact.artifactDisplayName;
+ this.artifactGroupType = artifact.artifactGroupType;
+ this.uniqueId = artifact.uniqueId;
+ this.artifactName = artifact.artifactName;
+ this.artifactLabel = artifact.artifactLabel;
+ this.artifactType = artifact.artifactType;
+ this.artifactUUID = artifact.artifactUUID;
+ this.artifactVersion = artifact.artifactVersion;
+ this.creatorFullName = artifact.creatorFullName;
+ this.creationDate = artifact.creationDate;
+ this.lastUpdateDate = artifact.lastUpdateDate;
+ this.description = artifact.description;
+ this.mandatory = artifact.mandatory;
+ this.serviceApi = artifact.serviceApi;
+ this.payloadData = artifact.payloadData;
+ this.timeout = artifact.timeout;
+ this.esId = artifact.esId;
+ this["Content-MD5"] = artifact["Content-MD5"];
+ this.artifactChecksum = artifact.artifactChecksum;
+ this.apiUrl = artifact.apiUrl;
+ this.heatParameters = _.sortBy(artifact.heatParameters, 'name');
+ this.generatedFromId = artifact.generatedFromId;
+ this.selected = artifact.selected ? artifact.selected : false;
+ this.originalDescription = artifact.description;
+ }
+ }
+
+ public isHEAT = ():boolean => {
+ return ArtifactType.HEAT === this.artifactType || ArtifactType.HEAT_VOL === this.artifactType || ArtifactType.HEAT_NET === this.artifactType;
+ };
+
+ public isThirdParty = ():boolean => {
+ return _.has(ArtifactType.THIRD_PARTY_RESERVED_TYPES, this.artifactType);
+ };
+
+ public toJSON = ():any => {
+ this.selected = undefined;
+ this.originalDescription = undefined;
+ this.envArtifact = undefined;
+ return this;
+ };
+}
+
+
diff --git a/catalog-ui/src/app/models/aschema-property.ts b/catalog-ui/src/app/models/aschema-property.ts
new file mode 100644
index 0000000000..a430a8cc0e
--- /dev/null
+++ b/catalog-ui/src/app/models/aschema-property.ts
@@ -0,0 +1,56 @@
+/**
+ * Created by osonsino on 16/05/2016.
+ */
+'use strict';
+import { PROPERTY_DATA } from "app/utils";
+
+export class SchemaPropertyGroupModel {
+ property:SchemaProperty;
+
+ constructor(schemaProperty?:SchemaProperty) {
+ this.property = schemaProperty;
+ }
+}
+
+export class SchemaProperty {
+
+ type:string;
+ required:boolean;
+ definition:boolean;
+ description:string;
+ password:boolean;
+ //custom properties
+ simpleType:string;
+ isSimpleType: boolean;
+ isDataType: boolean;
+ private _derivedFromSimpleTypeName:string;
+ get derivedFromSimpleTypeName():string {
+ return this._derivedFromSimpleTypeName;
+ }
+ set derivedFromSimpleTypeName(derivedFromSimpleTypeName:string) {
+ this._derivedFromSimpleTypeName = derivedFromSimpleTypeName;
+ }
+
+ constructor(schemaProperty?:SchemaProperty) {
+ if (schemaProperty) {
+ this.type = schemaProperty.type;
+ this.required = schemaProperty.required;
+ this.definition = schemaProperty.definition;
+ this.description = schemaProperty.description;
+ this.password = schemaProperty.password;
+ this.simpleType = schemaProperty.simpleType;
+ this.isSimpleType = (-1 < PROPERTY_DATA.SIMPLE_TYPES.indexOf(this.type));
+ this.isDataType = PROPERTY_DATA.TYPES.indexOf(this.type) == -1;
+ }
+ }
+
+ public toJSON = ():any => {
+ this.simpleType = undefined;
+ this.isSimpleType = undefined;
+ this.isDataType = undefined;
+ this._derivedFromSimpleTypeName = undefined;
+ return this;
+ };
+}
+
+
diff --git a/catalog-ui/src/app/models/attributes.ts b/catalog-ui/src/app/models/attributes.ts
new file mode 100644
index 0000000000..f2562e98bf
--- /dev/null
+++ b/catalog-ui/src/app/models/attributes.ts
@@ -0,0 +1,119 @@
+'use strict';
+import {SchemaAttributeGroupModel, SchemaAttribute} from "./schema-attribute";
+import {SchemaPropertyGroupModel, SchemaProperty} from "./aschema-property";
+
+export class AttributesGroup {
+ constructor(attributesObj?:AttributesGroup) {
+ _.forEach(attributesObj, (attributes:Array<AttributeModel>, instance) => {
+ this[instance] = [];
+ _.forEach(attributes, (attribute:AttributeModel):void => {
+ attribute.resourceInstanceUniqueId = instance;
+ attribute.readonly = true;
+ this[instance].push(new AttributeModel(attribute));
+ });
+ });
+ }
+}
+
+export interface IAttributeModel {
+
+ //server data
+ uniqueId:string;
+ name:string;
+ defaultValue:string;
+ description:string;
+ type:string;
+ schema:SchemaAttributeGroupModel;
+ status:string;
+ value:string;
+ hidden:boolean;
+ parentUniqueId:string;
+ //custom data
+ resourceInstanceUniqueId:string;
+ readonly:boolean;
+ valueUniqueUid:string;
+}
+
+export class AttributeModel implements IAttributeModel {
+
+ //server data
+ uniqueId:string;
+ name:string;
+ defaultValue:string;
+ description:string;
+ type:string;
+ schema:SchemaAttributeGroupModel;
+ status:string;
+ value:string;
+ hidden:boolean;
+ parentUniqueId:string;
+ //custom data
+ resourceInstanceUniqueId:string;
+ readonly:boolean;
+ valueUniqueUid:string;
+
+ constructor(attribute?:AttributeModel) {
+ if (attribute) {
+ this.uniqueId = attribute.uniqueId;
+ this.name = attribute.name;
+ this.defaultValue = attribute.defaultValue;
+ this.description = attribute.description;
+ this.type = attribute.type;
+ this.status = attribute.status;
+ this.schema = attribute.schema;
+ this.value = attribute.value;
+ this.hidden = attribute.hidden;
+ this.parentUniqueId = attribute.parentUniqueId;
+ this.resourceInstanceUniqueId = attribute.resourceInstanceUniqueId;
+ this.readonly = attribute.readonly;
+ this.valueUniqueUid = attribute.valueUniqueUid;
+ }
+
+ if (!this.schema || !this.schema.property) {
+ this.schema = new SchemaPropertyGroupModel(new SchemaProperty());
+ } else {
+ //forcing creating new object, so editing different one than the object in the table
+ this.schema = new SchemaAttributeGroupModel(new SchemaAttribute(this.schema.property));
+ }
+
+ this.convertValueToView();
+ }
+
+ public convertToServerObject:Function = ():string => {
+ if (this.defaultValue && this.type === 'map') {
+ this.defaultValue = '{' + this.defaultValue + '}';
+ }
+ if (this.defaultValue && this.type === 'list') {
+ this.defaultValue = '[' + this.defaultValue + ']';
+ }
+ this.defaultValue = this.defaultValue != "" && this.defaultValue != "[]" && this.defaultValue != "{}" ? this.defaultValue : null;
+
+ return JSON.stringify(this);
+ };
+
+
+ public convertValueToView() {
+ //unwrapping value {} or [] if type is complex
+ if (this.defaultValue && (this.type === 'map' || this.type === 'list') &&
+ ['[', '{'].indexOf(this.defaultValue.charAt(0)) > -1 &&
+ [']', '}'].indexOf(this.defaultValue.slice(-1)) > -1) {
+ this.defaultValue = this.defaultValue.slice(1, -1);
+ }
+
+ //also for value - for the modal in canvas
+ if (this.value && (this.type === 'map' || this.type === 'list') &&
+ ['[', '{'].indexOf(this.value.charAt(0)) > -1 &&
+ [']', '}'].indexOf(this.value.slice(-1)) > -1) {
+ this.value = this.value.slice(1, -1);
+ }
+ }
+
+ public toJSON = ():any => {
+ if (!this.resourceInstanceUniqueId) {
+ this.value = undefined;
+ }
+ this.readonly = undefined;
+ this.resourceInstanceUniqueId = undefined;
+ return this;
+ };
+}
diff --git a/catalog-ui/src/app/models/button.ts b/catalog-ui/src/app/models/button.ts
new file mode 100644
index 0000000000..8fbaf9091c
--- /dev/null
+++ b/catalog-ui/src/app/models/button.ts
@@ -0,0 +1,20 @@
+/**
+ * Created by rc2122 on 5/10/2017.
+ */
+export class ButtonModel {
+ text: string;
+ cssClass: string;
+ callback: Function;
+ getDisabled:Function;
+ constructor(text?:string, cssClass?:string, callback?:Function, getDisabled?:Function){
+ this.text = text;
+ this.cssClass = cssClass;
+ this.callback = callback;
+ this.getDisabled = getDisabled;
+
+ }
+}
+
+export class ButtonsModelMap {
+ [buttonName: string]: ButtonModel;
+}
diff --git a/catalog-ui/src/app/models/capability.ts b/catalog-ui/src/app/models/capability.ts
new file mode 100644
index 0000000000..94995bca55
--- /dev/null
+++ b/catalog-ui/src/app/models/capability.ts
@@ -0,0 +1,95 @@
+/**
+ * Created by obarda on 4/20/2016.
+ */
+'use strict';
+import {PropertyModel} from "./properties";
+
+//this is an object contains keys, when each key has matching array.
+// for example: key = tosca.capabilities.network.Linkable and the match array is array of capabilities objects
+export class CapabilitiesGroup {
+ constructor(capabilityGroupObj?:CapabilitiesGroup) {
+ _.forEach(capabilityGroupObj, (capabilitiesArrayObj:Array<Capability>, instance) => {
+ this[instance] = [];
+ _.forEach(capabilitiesArrayObj, (capability:Capability):void => {
+ this[instance].push(new Capability(capability));
+ });
+ });
+ }
+
+ public findValueByKey(keySubstring:string):Array<Capability> {
+ let key:string = _.find(Object.keys(this), (key)=> {
+ return _.includes(key.toLowerCase(), keySubstring);
+ });
+ return this[key];
+ }
+}
+
+export class Capability {
+
+ //server data
+ name:string;
+ ownerId:string;
+ ownerName:string;
+ type:string;
+ uniqueId:string;
+ capabilitySources:Array<String>;
+ minOccurrences:string;
+ maxOccurrences:string;
+ properties:Array<PropertyModel>;
+ description:string;
+ validSourceTypes:Array<string>;
+ //custom
+ selected:boolean;
+ filterTerm:string;
+
+ constructor(capability?:Capability) {
+
+ if (capability) {
+ //server data
+ this.name = capability.name;
+ this.ownerId = capability.ownerId;
+ this.ownerName = capability.ownerName;
+ this.type = capability.type;
+ this.uniqueId = capability.uniqueId;
+ this.capabilitySources = capability.capabilitySources;
+ this.minOccurrences = capability.minOccurrences;
+ this.maxOccurrences = capability.maxOccurrences;
+ this.properties = capability.properties;
+ this.description = capability.description;
+ this.validSourceTypes = capability.validSourceTypes;
+ this.selected = capability.selected;
+ this.initFilterTerm();
+
+ }
+ }
+
+ public getFullTitle():string {
+ let maxOccurrences:string = this.maxOccurrences === 'UNBOUNDED' ? '∞' : this.maxOccurrences;
+ return this.ownerName + ': ' + this.name + ': [' + this.minOccurrences + ', ' + maxOccurrences + ']';
+ }
+
+ public toJSON = ():any => {
+ this.selected = undefined;
+ this.filterTerm = undefined;
+ return this;
+ };
+
+ private initFilterTerm = ():void => {
+ this.filterTerm = this.name + " " +
+ (this.type ? (this.type.replace("tosca.capabilities.", "") + " " ) : "") +
+ (this.description || "") + " " +
+ (this.ownerName || "") + " " +
+ (this.validSourceTypes ? (this.validSourceTypes.join(',') + " ") : "") +
+ this.minOccurrences + "," + this.maxOccurrences;
+ if (this.properties && this.properties.length) {
+ _.forEach(this.properties, (prop:PropertyModel)=> {
+ this.filterTerm += " " + prop.name +
+ " " + (prop.description || "") +
+ " " + prop.type +
+ (prop.schema && prop.schema.property ? (" " + prop.schema.property.type) : "");
+ });
+ }
+ }
+}
+
+
diff --git a/catalog-ui/src/app/models/categories.ts b/catalog-ui/src/app/models/categories.ts
new file mode 100644
index 0000000000..2aad61194f
--- /dev/null
+++ b/catalog-ui/src/app/models/categories.ts
@@ -0,0 +1,10 @@
+import {IMainCategory} from "./category";
+/**
+ * Created by ob0695 on 5/8/2017.
+ */
+export class Categories {
+
+ resourceCategories:Array<IMainCategory>;
+ productCategories:Array<IMainCategory>;
+ serviceCategories:Array<IMainCategory>;
+}
diff --git a/catalog-ui/src/app/models/category.ts b/catalog-ui/src/app/models/category.ts
new file mode 100644
index 0000000000..fcfe61bfd6
--- /dev/null
+++ b/catalog-ui/src/app/models/category.ts
@@ -0,0 +1,47 @@
+'use strict';
+
+
+
+export class ICategoryBase {
+
+ //server properties
+ name:string;
+ normalizedName:string;
+ uniqueId:string;
+ icons:Array<string>;
+
+ //custom properties
+ filterTerms:string;
+ isDisabled:boolean;
+ filteredGroup:Array<IGroup>;
+
+ constructor(category?:ICategoryBase) {
+ if (category) {
+ this.name = category.name;
+ this.normalizedName = category.normalizedName;
+ this.icons = category.icons;
+ this.filterTerms = category.filterTerms;
+ this.isDisabled = category.isDisabled;
+ this.filteredGroup = category.filteredGroup;
+ }
+ }
+}
+
+export class IMainCategory extends ICategoryBase {
+ subcategories:Array<ISubCategory>;
+
+ constructor();
+ constructor(category?:IMainCategory) {
+ super(category);
+ if (category) {
+ this.subcategories = category.subcategories;
+ }
+ }
+}
+
+export class ISubCategory extends ICategoryBase {
+ groupings:Array<ICategoryBase>;
+}
+
+export interface IGroup extends ICategoryBase {
+}
diff --git a/catalog-ui/src/app/models/comments.ts b/catalog-ui/src/app/models/comments.ts
new file mode 100644
index 0000000000..b61713cc2c
--- /dev/null
+++ b/catalog-ui/src/app/models/comments.ts
@@ -0,0 +1,11 @@
+'use strict';
+
+export class AsdcComment {
+ public userRemarks:string;
+
+ constructor() {
+ }
+}
+
+
+
diff --git a/catalog-ui/src/app/models/component-metadata.ts b/catalog-ui/src/app/models/component-metadata.ts
new file mode 100644
index 0000000000..9476d75bd0
--- /dev/null
+++ b/catalog-ui/src/app/models/component-metadata.ts
@@ -0,0 +1,89 @@
+import {IMainCategory} from "./category";
+/**
+ * Created by obarda on 4/18/2017.
+ */
+export class ComponentMetadata {
+
+ public abstract:string;
+ public uniqueId:string;
+ public uuid:string;
+ public invariantUUID:string;
+ public name:string;
+ public version:string;
+ public creationDate:number;
+ public lastUpdateDate:number;
+ public description:string;
+ public lifecycleState:string;
+ public tags:Array<string>;
+ public icon:string;
+ public contactId:string;
+ public allVersions:any;
+ public creatorUserId:string;
+ public creatorFullName:string;
+ public lastUpdaterUserId:string;
+ public lastUpdaterFullName:string;
+ public componentType:string;
+ public categories:Array<IMainCategory>;
+ public highestVersion:boolean;
+ public normalizedName:string;
+ public systemName:string;
+
+ //Resource only
+ public resourceType: string;
+ public csarUUID:string;
+ public csarVersion:string;
+ public derivedList: string[];
+ public vendorName:string;
+ public vendorRelease:string;
+ public derivedFrom: Array<string>;
+
+ //Service only
+ public projectCode:string;
+ public distributionStatus:string;
+ public ecompGeneratedNaming: boolean;
+ public namingPolicy: string;
+
+
+ //backend lifecycleState
+ public state:string;
+
+ deserialize (response): ComponentMetadata {
+ this.abstract = response.abstract;
+ this.uniqueId = response.uniqueId;
+ this.uuid = response.uuid;
+ this.invariantUUID = response.invariantUUID;
+ this.contactId = response.contactId;
+ this.categories = response.categories;
+ this.creatorUserId = response.creatorUserId;
+ this.creationDate = response.creationDate;
+ this.creatorFullName = response.creatorFullName;
+ this.description = response.description;
+ this.icon = response.icon;
+ this.lastUpdateDate = response.lastUpdateDate;
+ this.lastUpdaterUserId = response.lastUpdaterUserId;
+ this.lastUpdaterFullName = response.lastUpdaterFullName;
+ this.lifecycleState = response.lifecycleState;
+ this.name = response.name;
+ this.version = response.version;
+ this.tags = angular.copy(response.tags, this.tags);
+ this.allVersions = response.allVersions;
+ this.componentType = response.componentType;
+ this.distributionStatus = response.distributionStatus;
+ this.highestVersion = response.highestVersion;
+ this.vendorName = response.vendorName;
+ this.vendorRelease = response.vendorRelease;
+ this.derivedList = response.derivedList;
+ this.normalizedName = response.normalizedName;
+ this.systemName = response.systemName;
+ this.projectCode = response.projectCode;
+ this.resourceType = response.resourceType;
+ this.csarUUID = response.csarUUID;
+ this.csarVersion = response.version;
+ this.state = response.state;
+ this.ecompGeneratedNaming = response.ecompGeneratedNaming;
+ this.namingPolicy = response.namingPolicy;
+ this.derivedFrom = response.derivedFrom;
+ return this;
+ }
+
+}
diff --git a/catalog-ui/src/app/models/components/component.ts b/catalog-ui/src/app/models/components/component.ts
new file mode 100644
index 0000000000..898285f032
--- /dev/null
+++ b/catalog-ui/src/app/models/components/component.ts
@@ -0,0 +1,911 @@
+'use strict';
+
+import {AsdcComment, ArtifactModel, ArtifactGroupModel, IFileDownload, PropertyModel, PropertiesGroup, AttributeModel, AttributesGroup, ComponentInstance,
+ InputModel, DisplayModule, Module, IValidate, RelationshipModel, IMainCategory, RequirementsGroup, CapabilitiesGroup, AdditionalInformationModel,
+ Resource, IAppMenu, Product, Service} from "../../models";
+
+import {IComponentService} from "../../services/components/component-service";
+import {CommonUtils} from "../../utils/common-utils";
+import {QueueUtils} from "../../utils/functions";
+import {ArtifactGroupType} from "../../utils/constants";
+import {ComponentMetadata} from "../component-metadata";
+
+// import {}
+export interface IComponent {
+
+ //---------------------------------------------- API CALLS ----------------------------------------------------//
+
+ //Component API
+ getComponent():ng.IPromise<Component>;
+ updateComponent():ng.IPromise<Component>;
+ createComponentOnServer():ng.IPromise<Component>;
+ changeLifecycleState(state:string, commentObj:AsdcComment):ng.IPromise<Component>;
+ validateName(newName:string):ng.IPromise<IValidate>;
+ updateRequirementsCapabilities():ng.IPromise<any>;
+
+ //Artifacts API
+ addOrUpdateArtifact(artifact:ArtifactModel):ng.IPromise<ArtifactModel>;
+ updateMultipleArtifacts(artifacts:Array<ArtifactModel>):ng.IPromise<any>;
+ deleteArtifact(artifactId:string, artifactLabel:string):ng.IPromise<ArtifactModel>;
+ downloadInstanceArtifact(artifactId:string):ng.IPromise<IFileDownload>;
+ downloadArtifact(artifactId:string):ng.IPromise<IFileDownload>;
+ getArtifactByGroupType(artifactGroupType:string):ng.IPromise<ArtifactGroupModel>;
+
+
+ //Property API
+ addOrUpdateProperty(property:PropertyModel):ng.IPromise<PropertyModel>;
+ deleteProperty(propertyId:string):ng.IPromise<PropertyModel>;
+ updateInstanceProperty(property:PropertyModel):ng.IPromise<PropertyModel>;
+
+ //Attribute API
+ deleteAttribute(attributeId:string):ng.IPromise<AttributeModel>;
+ addOrUpdateAttribute(attribute:AttributeModel):ng.IPromise<AttributeModel>;
+ updateInstanceAttribute(attribute:AttributeModel):ng.IPromise<AttributeModel>;
+
+
+
+
+ //Component Instance API
+ createComponentInstance(componentInstance:ComponentInstance):ng.IPromise<ComponentInstance>;
+ deleteComponentInstance(componentInstanceId:string):ng.IPromise<ComponentInstance>;
+ addOrUpdateInstanceArtifact(artifact:ArtifactModel):ng.IPromise<ArtifactModel>;
+ deleteInstanceArtifact(artifactId:string, artifactLabel:string):ng.IPromise<ArtifactModel>;
+ uploadInstanceEnvFile(artifact:ArtifactModel):ng.IPromise<ArtifactModel>;
+ changeComponentInstanceVersion(componentUid:string):ng.IPromise<Component>;
+ updateComponentInstance(componentInstance:ComponentInstance):ng.IPromise<ComponentInstance>;
+ updateMultipleComponentInstances(instances:Array<ComponentInstance>):ng.IPromise<Array<ComponentInstance>>;
+
+ //Inputs API
+ getComponentInstanceInputProperties(componentInstanceId:string, inputId:string):ng.IPromise<Array<PropertyModel>>
+ getComponentInstanceProperties(componentInstanceId:string):ng.IPromise<Array<PropertyModel>>
+ getComponentInputs(componentId:string):ng.IPromise<Array<InputModel>>;
+
+ createRelation(link:RelationshipModel):ng.IPromise<RelationshipModel>;
+ deleteRelation(link:RelationshipModel):ng.IPromise<RelationshipModel>;
+
+
+ //Modules
+ getModuleForDisplay(moduleId:string):ng.IPromise<DisplayModule>;
+ getModuleInstanceForDisplay(componentInstanceId:string, moduleId:string):ng.IPromise<DisplayModule>;
+ updateGroupMetadata(group:Module):ng.IPromise<Module>;
+ //---------------------------------------------- HELP FUNCTIONS ----------------------------------------------------//
+
+ getComponentSubType():string;
+ isAlreadyCertified():boolean;
+ isProduct():boolean;
+ isService():boolean;
+ isResource():boolean;
+ isComplex():boolean;
+ getAdditionalInformation():Array<AdditionalInformationModel>;
+ getAllVersionsAsSortedArray():Array<any>;
+ getStatus(sdcMenu:IAppMenu):string;
+}
+
+
+export abstract class Component implements IComponent {
+
+ //server data
+ public abstract:string;
+ public uniqueId:string;
+ public uuid:string;
+ public invariantUUID:string;
+ public name:string;
+ public version:string;
+ public creationDate:number;
+ public lastUpdateDate:number;
+ public description:string;
+ public lifecycleState:string;
+ public tags:Array<string>;
+ public icon:string;
+ public contactId:string;
+ public allVersions:any;
+ public creatorUserId:string;
+ public creatorFullName:string;
+ public lastUpdaterUserId:string;
+ public lastUpdaterFullName:string;
+ public componentType:string;
+ public deploymentArtifacts:ArtifactGroupModel;
+ public artifacts:ArtifactGroupModel;
+ public toscaArtifacts:ArtifactGroupModel;
+ public distributionStatus:string;
+ public categories:Array<IMainCategory>;
+ public componentInstancesProperties:PropertiesGroup;
+ public componentInstancesAttributes:AttributesGroup;
+ public componentInstancesRelations:Array<RelationshipModel>;
+ public componentInstances:Array<ComponentInstance>;
+ public inputs:Array<InputModel>;
+ public capabilities:CapabilitiesGroup;
+ public requirements:RequirementsGroup;
+ public additionalInformation:any;
+ public properties:Array<PropertyModel>;
+ public attributes:Array<AttributeModel>;
+ public highestVersion:boolean;
+ public vendorName:string;
+ public vendorRelease:string;
+ public derivedList:Array<any>;
+ public interfaces:any;
+ public normalizedName:string;
+ public systemName:string;
+ public projectCode:string;
+ public groups:Array<Module>;
+ //custom properties
+ public componentService:IComponentService;
+ public filterTerm:string;
+ public iconSprite:string;
+ public selectedInstance:ComponentInstance;
+ public mainCategory:string;
+ public subCategory:string;
+ public selectedCategory:string;
+ public showMenu:boolean;
+
+
+ constructor(componentService:IComponentService, protected $q:ng.IQService, component?:Component) {
+ if (component) {
+ this.abstract = component.abstract;
+ this.uniqueId = component.uniqueId;
+ this.uuid = component.uuid;
+ this.invariantUUID = component.invariantUUID;
+ this.additionalInformation = component.additionalInformation;
+ this.artifacts = new ArtifactGroupModel(component.artifacts);
+ this.toscaArtifacts = new ArtifactGroupModel(component.toscaArtifacts);
+ this.contactId = component.contactId;
+ this.categories = component.categories;
+ this.creatorUserId = component.creatorUserId;
+ this.creationDate = component.creationDate;
+ this.creatorFullName = component.creatorFullName;
+ this.description = component.description;
+ this.icon = component.icon;
+ this.lastUpdateDate = component.lastUpdateDate;
+ this.lastUpdaterUserId = component.lastUpdaterUserId;
+ this.lastUpdaterFullName = component.lastUpdaterFullName;
+ this.lifecycleState = component.lifecycleState;
+ this.componentInstancesRelations = CommonUtils.initComponentInstanceRelations(component.componentInstancesRelations);
+ this.componentInstancesProperties = new PropertiesGroup(component.componentInstancesProperties);
+ this.componentInstancesAttributes = new AttributesGroup(component.componentInstancesAttributes);
+ this.name = component.name;
+ this.version = component.version;
+ this.tags = [];
+ angular.copy(component.tags, this.tags);
+ this.capabilities = new CapabilitiesGroup(component.capabilities);
+ this.requirements = new RequirementsGroup(component.requirements);
+ this.allVersions = component.allVersions;
+ this.deploymentArtifacts = new ArtifactGroupModel(component.deploymentArtifacts);
+ this.componentType = component.componentType;
+ this.distributionStatus = component.distributionStatus;
+ this.highestVersion = component.highestVersion;
+ this.vendorName = component.vendorName;
+ this.vendorRelease = component.vendorRelease;
+ this.derivedList = component.derivedList;
+ this.interfaces = component.interfaces;
+ this.normalizedName = component.normalizedName;
+ this.systemName = component.systemName;
+ this.projectCode = component.projectCode;
+ this.inputs = component.inputs;
+ this.componentInstances = CommonUtils.initComponentInstances(component.componentInstances);
+ this.properties = CommonUtils.initProperties(component.properties, this.uniqueId);
+ this.attributes = CommonUtils.initAttributes(component.attributes, this.uniqueId);
+ this.selectedInstance = component.selectedInstance;
+ this.iconSprite = component.iconSprite;
+ this.showMenu = true;
+ this.groups = CommonUtils.initModules(component.groups);
+ }
+
+ //custom properties
+ this.componentService = componentService;
+ }
+
+ public setUniqueId = (uniqueId:string):void => {
+ this.uniqueId = uniqueId;
+ };
+
+ public setSelectedInstance = (componentInstance:ComponentInstance):void => {
+ this.selectedInstance = componentInstance;
+ };
+
+
+ //------------------------------------------ API Calls ----------------------------------------------------------------//
+ public changeLifecycleState = (state:string, commentObj:AsdcComment):ng.IPromise<Component> => {
+ return this.componentService.changeLifecycleState(this, state, JSON.stringify(commentObj));
+ };
+
+ public getComponent = ():ng.IPromise<Component> => {
+ return this.componentService.getComponent(this.uniqueId);
+ };
+
+ public createComponentOnServer = ():ng.IPromise<Component> => {
+ this.handleTags();
+ return this.componentService.createComponent(this);
+ };
+
+ public updateComponent = ():ng.IPromise<Component> => {
+ this.handleTags();
+ return this.componentService.updateComponent(this);
+ };
+
+ public validateName = (newName:string, subtype?:string):ng.IPromise<IValidate> => {
+ return this.componentService.validateName(newName, subtype);
+ };
+
+ public downloadArtifact = (artifactId:string):ng.IPromise<IFileDownload> => {
+ return this.componentService.downloadArtifact(this.uniqueId, artifactId);
+ };
+
+ public addOrUpdateArtifact = (artifact:ArtifactModel):ng.IPromise<ArtifactModel> => {
+ let deferred = this.$q.defer();
+ let onSuccess = (artifactObj:ArtifactModel):void => {
+ let newArtifact = new ArtifactModel(artifactObj);
+ let artifacts = this.getArtifactsByType(artifactObj.artifactGroupType);
+ artifacts[artifactObj.artifactLabel] = newArtifact;
+ deferred.resolve(newArtifact);
+ };
+ let onError = (error:any):void => {
+ deferred.reject(error);
+ };
+ this.componentService.addOrUpdateArtifact(this.uniqueId, artifact).then(onSuccess, onError);
+ return deferred.promise;
+ };
+
+ public updateMultipleArtifacts = (artifacts:Array<ArtifactModel>):ng.IPromise<any>=> {
+ let deferred = this.$q.defer();
+ let onSuccess = (response:any):void => {
+ deferred.resolve(response);
+ };
+ let onError = (error:any):void => {
+ deferred.reject(error);
+ };
+ let q = new QueueUtils(this.$q);
+
+ _.forEach(artifacts, (artifact)=> {
+ q.addBlockingUIAction(()=> this.addOrUpdateArtifact(artifact).then(onSuccess, onError));
+ });
+ return deferred.promise;
+ };
+
+
+ public deleteArtifact = (artifactId:string, artifactLabel:string):ng.IPromise<ArtifactModel> => {
+ let deferred = this.$q.defer();
+ let onSuccess = (artifactObj:ArtifactModel):void => {
+ let newArtifact = new ArtifactModel(artifactObj);
+ let artifacts = this.getArtifactsByType(artifactObj.artifactGroupType);
+ if (newArtifact.mandatory || newArtifact.serviceApi) {
+ artifacts[newArtifact.artifactLabel] = newArtifact;
+ }
+ else {
+ delete artifacts[artifactLabel];
+ }
+ deferred.resolve(newArtifact);
+ };
+ this.componentService.deleteArtifact(this.uniqueId, artifactId, artifactLabel).then(onSuccess);
+ return deferred.promise;
+ };
+
+ public getArtifactByGroupType = (artifactGroupType:string):ng.IPromise<ArtifactGroupModel> => {
+
+ let deferred = this.$q.defer();
+ let onSuccess = (response:ArtifactGroupModel):void => {
+ deferred.resolve(response);
+ };
+ let onFailed = (error:any):void => {
+ deferred.reject(error);
+ };
+ this.componentService.getArtifactByGroupType(this.uniqueId, artifactGroupType).then(onSuccess, onFailed);
+ return deferred.promise;
+ };
+
+ public getComponentInstanceArtifactsByGroupType = (componentInstanceId:string, artifactGroupType:string):ng.IPromise<ArtifactGroupModel> => {
+
+ let deferred = this.$q.defer();
+ let onSuccess = (response:ArtifactGroupModel):void => {
+ deferred.resolve(response);
+ };
+ let onFailed = (error:any):void => {
+ deferred.reject(error);
+ };
+ this.componentService.getComponentInstanceArtifactsByGroupType(this.uniqueId, componentInstanceId, artifactGroupType).then(onSuccess, onFailed);
+ return deferred.promise;
+ };
+
+ public addOrUpdateProperty = (property:PropertyModel):ng.IPromise<PropertyModel> => {
+ let deferred = this.$q.defer();
+
+ let onError = (error:any):void => {
+ deferred.reject(error);
+ };
+
+ if (!property.uniqueId) {
+ let onSuccess = (property:PropertyModel):void => {
+ let newProperty = new PropertyModel(property);
+ this.properties.push(newProperty);
+ deferred.resolve(newProperty);
+ };
+ this.componentService.addProperty(this.uniqueId, property).then(onSuccess, onError);
+ }
+ else {
+ let onSuccess = (newProperty:PropertyModel):void => {
+ // find exist instance property in parent component for update the new value ( find bu uniqueId )
+ let existProperty:PropertyModel = <PropertyModel>_.find(this.properties, {uniqueId: newProperty.uniqueId});
+ let propertyIndex = this.properties.indexOf(existProperty);
+ newProperty.readonly = this.uniqueId != newProperty.parentUniqueId;
+ this.properties[propertyIndex] = newProperty;
+ deferred.resolve(newProperty);
+ };
+ this.componentService.updateProperty(this.uniqueId, property).then(onSuccess, onError);
+ }
+ return deferred.promise;
+ };
+
+ public addOrUpdateAttribute = (attribute:AttributeModel):ng.IPromise<AttributeModel> => {
+ let deferred = this.$q.defer();
+
+ let onError = (error:any):void => {
+ deferred.reject(error);
+ };
+
+ if (!attribute.uniqueId) {
+ let onSuccess = (attribute:AttributeModel):void => {
+ let newAttribute = new AttributeModel(attribute);
+ this.attributes.push(newAttribute);
+ deferred.resolve(newAttribute);
+ };
+ this.componentService.addAttribute(this.uniqueId, attribute).then(onSuccess, onError);
+ }
+ else {
+ let onSuccess = (newAttribute:AttributeModel):void => {
+ let existAttribute:AttributeModel = <AttributeModel>_.find(this.attributes, {uniqueId: newAttribute.uniqueId});
+ let attributeIndex = this.attributes.indexOf(existAttribute);
+ newAttribute.readonly = this.uniqueId != newAttribute.parentUniqueId;
+ this.attributes[attributeIndex] = newAttribute;
+ deferred.resolve(newAttribute);
+ };
+ this.componentService.updateAttribute(this.uniqueId, attribute).then(onSuccess, onError);
+ }
+ return deferred.promise;
+ };
+
+ public deleteProperty = (propertyId:string):ng.IPromise<PropertyModel> => {
+ let deferred = this.$q.defer();
+ let onSuccess = ():void => {
+ console.log("Property deleted");
+ delete _.remove(this.properties, {uniqueId: propertyId})[0];
+ deferred.resolve();
+ };
+ let onFailed = ():void => {
+ console.log("Failed to delete property");
+ deferred.reject();
+ };
+ this.componentService.deleteProperty(this.uniqueId, propertyId).then(onSuccess, onFailed);
+ return deferred.promise;
+ };
+
+ public deleteAttribute = (attributeId:string):ng.IPromise<AttributeModel> => {
+ let deferred = this.$q.defer();
+ let onSuccess = ():void => {
+ console.log("Attribute deleted");
+ delete _.remove(this.attributes, {uniqueId: attributeId})[0];
+ };
+ let onFailed = ():void => {
+ console.log("Failed to delete attribute");
+ };
+ this.componentService.deleteAttribute(this.uniqueId, attributeId).then(onSuccess, onFailed);
+ 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
+ });
+ let index = this.componentInstancesProperties[newProperty.resourceInstanceUniqueId].indexOf(existProperty);
+ this.componentInstancesProperties[newProperty.resourceInstanceUniqueId][index] = newProperty;
+ deferred.resolve(newProperty);
+ };
+ let onFailed = (error:any):void => {
+ console.log('Failed to update property value');
+ deferred.reject(error);
+ };
+ this.componentService.updateInstanceProperty(this.uniqueId, property).then(onSuccess, onFailed);
+ return deferred.promise;
+ };
+
+ public updateInstanceAttribute = (attribute:AttributeModel):ng.IPromise<AttributeModel> => {
+ let deferred = this.$q.defer();
+ let onSuccess = (newAttribute:AttributeModel):void => {
+ let existAttribute:AttributeModel = <AttributeModel>_.find(this.componentInstancesAttributes[newAttribute.resourceInstanceUniqueId], {uniqueId: newAttribute.uniqueId});
+ let index = this.componentInstancesAttributes[newAttribute.resourceInstanceUniqueId].indexOf(existAttribute);
+ this.componentInstancesAttributes[newAttribute.resourceInstanceUniqueId][index] = newAttribute;
+ deferred.resolve(newAttribute);
+ };
+ let onFailed = (error:any):void => {
+ console.log('Failed to update attribute value');
+ deferred.reject(error);
+ };
+ this.componentService.updateInstanceAttribute(this.uniqueId, attribute).then(onSuccess, onFailed);
+ return deferred.promise;
+ };
+
+ public downloadInstanceArtifact = (artifactId:string):ng.IPromise<IFileDownload> => {
+ return this.componentService.downloadInstanceArtifact(this.uniqueId, this.selectedInstance.uniqueId, artifactId);
+ };
+
+ public deleteInstanceArtifact = (artifactId:string, artifactLabel:string):ng.IPromise<ArtifactModel> => {
+ let deferred = this.$q.defer();
+ let onSuccess = (artifactObj:ArtifactModel):void => {
+ let newArtifact = new ArtifactModel(artifactObj);
+ let artifacts = this.selectedInstance.deploymentArtifacts;
+ if (newArtifact.mandatory || newArtifact.serviceApi) {//?????????
+ artifacts[newArtifact.artifactLabel] = newArtifact;
+ }
+ else {
+ delete artifacts[artifactLabel];
+ }
+ deferred.resolve(newArtifact);
+ };
+ this.componentService.deleteInstanceArtifact(this.uniqueId, this.selectedInstance.uniqueId, artifactId, artifactLabel).then(onSuccess);
+ return deferred.promise;
+ };
+
+ public addOrUpdateInstanceArtifact = (artifact:ArtifactModel):ng.IPromise<ArtifactModel> => {
+ let deferred = this.$q.defer();
+ let onSuccess = (artifactObj:ArtifactModel):void => {
+ switch (artifactObj.artifactGroupType) {
+ case ArtifactGroupType.DEPLOYMENT:
+ this.selectedInstance.deploymentArtifacts[artifactObj.artifactLabel] = artifactObj;
+ break;
+ case ArtifactGroupType.INFORMATION:
+ this.selectedInstance.artifacts[artifactObj.artifactLabel] = artifactObj;
+ break;
+ }
+ deferred.resolve(artifactObj);
+ };
+ let onError = (error:any):void => {
+ deferred.reject(error);
+ };
+ if (artifact.uniqueId) {
+ this.componentService.updateInstanceArtifact(this.uniqueId, this.selectedInstance.uniqueId, artifact).then(onSuccess, onError);
+ } else {
+ this.componentService.addInstanceArtifact(this.uniqueId, this.selectedInstance.uniqueId, artifact).then(onSuccess, onError);
+ }
+ return deferred.promise;
+ };
+
+ public uploadInstanceEnvFile = (artifact:ArtifactModel):ng.IPromise<ArtifactModel> => {
+ let deferred = this.$q.defer();
+ let onSuccess = (artifactObj:ArtifactModel):void => {
+ this.selectedInstance.deploymentArtifacts[artifactObj.artifactLabel] = artifactObj;
+ deferred.resolve(artifactObj);
+ };
+ let onError = (error:any):void => {
+ deferred.reject(error);
+ };
+ this.componentService.uploadInstanceEnvFile(this.uniqueId, this.selectedInstance.uniqueId, artifact).then(onSuccess, onError);
+ return deferred.promise;
+ };
+
+ //this function will update the instance version than the function call getComponent to update the current component and return the new instance version
+ public changeComponentInstanceVersion = (componentUid:string):ng.IPromise<Component> => {
+ let deferred = this.$q.defer();
+ let onFailed = (error:any):void => {
+ deferred.reject(error);
+ };
+ let onSuccess = (componentInstance:ComponentInstance):void => {
+ let onSuccess = (component:Component):void => {
+ component.setSelectedInstance(componentInstance);
+ deferred.resolve(component);
+ };
+ this.getComponent().then(onSuccess, onFailed);
+ };
+ this.componentService.changeResourceInstanceVersion(this.uniqueId, this.selectedInstance.uniqueId, componentUid).then(onSuccess, onFailed);
+ return deferred.promise;
+ };
+
+ public createComponentInstance = (componentInstance:ComponentInstance):ng.IPromise<ComponentInstance> => {
+ let deferred = this.$q.defer();
+ let onSuccess = (instance:ComponentInstance):void => {
+ this.componentInstances.push(instance);
+ deferred.resolve(instance);
+ };
+ let onFailed = (error:any):void => {
+ deferred.reject(error);
+ };
+ this.componentService.createComponentInstance(this.uniqueId, componentInstance).then(onSuccess, onFailed);
+ return deferred.promise;
+ };
+
+ public updateComponentInstance = (componentInstance:ComponentInstance):ng.IPromise<ComponentInstance> => {
+ let deferred = this.$q.defer();
+ let onSuccess = (updatedInstance:ComponentInstance):void => {
+ let componentInstance:ComponentInstance = _.find(this.componentInstances, (instance:ComponentInstance) => {
+ return instance.uniqueId === updatedInstance.uniqueId;
+ });
+
+ let index = this.componentInstances.indexOf(componentInstance);
+ this.componentInstances[index] = componentInstance;
+ deferred.resolve(updatedInstance);
+
+ };
+ let onFailed = (error:any):void => {
+ deferred.reject(error);
+ };
+ this.componentService.updateComponentInstance(this.uniqueId, componentInstance).then(onSuccess, onFailed);
+ return deferred.promise;
+ };
+
+ public updateMultipleComponentInstances = (instances:Array<ComponentInstance>):ng.IPromise<Array<ComponentInstance>> => {
+ let deferred = this.$q.defer();
+ let onSuccess = (updatedInstances:Array<ComponentInstance>):void => {
+ _.forEach(updatedInstances, (updatedComponentInstance) => {
+ let componentInstance:ComponentInstance = _.find(this.componentInstances, (instance:ComponentInstance) => {
+ return instance.uniqueId === updatedComponentInstance.uniqueId;
+ });
+
+ let index = this.componentInstances.indexOf(componentInstance);
+ this.componentInstances[index] = componentInstance;
+
+ });
+ deferred.resolve(updatedInstances);
+
+ };
+ let onFailed = (error:any):void => {
+ deferred.reject(error);
+ };
+ this.componentService.updateMultipleComponentInstances(this.uniqueId, instances).then(onSuccess, onFailed);
+ return deferred.promise;
+ };
+
+ public deleteComponentInstance = (componentInstanceId:string):ng.IPromise<ComponentInstance> => {
+ let deferred = this.$q.defer();
+ let onSuccess = ():void => {
+ let onSuccess = (component:Component):void => {
+ this.componentInstances = CommonUtils.initComponentInstances(component.componentInstances);
+ this.componentInstancesProperties = new PropertiesGroup(component.componentInstancesProperties);
+ this.componentInstancesAttributes = new AttributesGroup(component.componentInstancesAttributes);
+ this.groups = component.groups;
+ this.componentInstancesRelations = CommonUtils.initComponentInstanceRelations(component.componentInstancesRelations);
+ deferred.resolve();
+ };
+ this.getComponent().then(onSuccess);
+ };
+ let onFailed = (error:any):void => {
+ deferred.reject(error);
+ };
+ this.componentService.deleteComponentInstance(this.uniqueId, componentInstanceId).then(onSuccess, onFailed);
+ return deferred.promise;
+ };
+
+
+ public createRelation = (relation:RelationshipModel):ng.IPromise<RelationshipModel> => {
+ let deferred = this.$q.defer();
+ let onSuccess = (relation:RelationshipModel):void => {
+ console.info('Link created successfully', relation);
+ if (!this.componentInstancesRelations) {
+ this.componentInstancesRelations = [];
+ }
+ this.componentInstancesRelations.push(new RelationshipModel(relation));
+ deferred.resolve(relation);
+ };
+ let onFailed = (error:any):void => {
+ console.info('Failed to create relation', error);
+ deferred.reject(error);
+ };
+ this.componentService.createRelation(this.uniqueId, relation).then(onSuccess, onFailed);
+ return deferred.promise;
+ };
+
+ public deleteRelation = (relation:RelationshipModel):ng.IPromise<RelationshipModel> => {
+ let deferred = this.$q.defer();
+ let onSuccess = (responseRelation:RelationshipModel):void => {
+ console.log("Link Deleted In Server");
+ let relationToDelete = _.find(this.componentInstancesRelations, (item) => {
+ return item.fromNode === relation.fromNode && item.toNode === relation.toNode && _.some(item.relationships, (relationship)=> {
+ return angular.equals(relation.relationships[0], relationship);
+ });
+ });
+ let index = this.componentInstancesRelations.indexOf(relationToDelete);
+ if (relationToDelete != undefined && index > -1) {
+ if (relationToDelete.relationships.length == 1) {
+ this.componentInstancesRelations.splice(index, 1);
+ } else {
+ this.componentInstancesRelations[index].relationships =
+ _.reject(this.componentInstancesRelations[index].relationships, relation.relationships[0]);
+ }
+ } else {
+ console.error("Error while deleting relation - the return delete relation from server was not found in UI")
+ }
+ deferred.resolve(relation);
+ };
+ let onFailed = (error:any):void => {
+ console.error("Failed To Delete Link");
+ deferred.reject(error);
+ };
+ this.componentService.deleteRelation(this.uniqueId, relation).then(onSuccess, onFailed);
+ return deferred.promise;
+ };
+
+ public updateRequirementsCapabilities = ():ng.IPromise<any> => {
+ let deferred = this.$q.defer();
+ let onSuccess = (response:any):void => {
+ this.capabilities = response.capabilities;
+ this.requirements = response.requirements;
+ deferred.resolve(response);
+ };
+ let onFailed = (error:any):void => {
+ deferred.reject(error);
+ };
+ this.componentService.getRequirementsCapabilities(this.uniqueId).then(onSuccess, onFailed);
+ return deferred.promise;
+ };
+
+ public getModuleForDisplay = (moduleId:string):ng.IPromise<DisplayModule> => {
+
+ let deferred = this.$q.defer();
+ let onSuccess = (response:DisplayModule):void => {
+ deferred.resolve(response);
+ };
+ let onFailed = (error:any):void => {
+ deferred.reject(error);
+ };
+ this.componentService.getModuleForDisplay(this.uniqueId, moduleId).then(onSuccess, onFailed);
+ return deferred.promise;
+ };
+
+ public getModuleInstanceForDisplay = (componentInstanceId:string, moduleId:string):ng.IPromise<DisplayModule> => {
+
+ let deferred = this.$q.defer();
+ let onSuccess = (response:DisplayModule):void => {
+ deferred.resolve(response);
+ };
+ let onFailed = (error:any):void => {
+ deferred.reject(error);
+ };
+ this.componentService.getComponentInstanceModule(this.uniqueId, componentInstanceId, moduleId).then(onSuccess, onFailed);
+ return deferred.promise;
+ };
+
+
+ // this function get all instances filtered by inputs and properties (optional) - if no search string insert - this function will
+ // get all the instances of the component (in service only VF instances)
+ public getComponentInstancesFilteredByInputsAndProperties = (searchText?:string):ng.IPromise<Array<ComponentInstance>> => {
+
+ let deferred = this.$q.defer();
+ let onSuccess = (response:Array<ComponentInstance>):void => {
+ deferred.resolve(response);
+ };
+ let onFailed = (error:any):void => {
+ deferred.reject(error);
+ };
+ this.componentService.getComponentInstancesFilteredByInputsAndProperties(this.uniqueId, searchText).then(onSuccess, onFailed);
+ return deferred.promise;
+ };
+
+
+ // get inputs for instance - Pagination function
+ public getComponentInputs = ():ng.IPromise<Array<InputModel>> => {
+
+ let deferred = this.$q.defer();
+ let onSuccess = (inputsRes:Array<InputModel>):void => {
+ this.inputs = inputsRes;
+ deferred.resolve(inputsRes);
+ };
+ let onFailed = (error:any):void => {
+ deferred.reject(error);
+ };
+ this.componentService.getComponentInputs(this.uniqueId).then(onSuccess, onFailed);
+ return deferred.promise;
+ };
+
+
+ // get inputs instance - Pagination function
+ public getComponentInstanceInputs = (componentInstanceId:string, originComponentUid:string):ng.IPromise<Array<InputModel>> => {
+
+ let deferred = this.$q.defer();
+ let onSuccess = (response:Array<InputModel>):void => {
+ deferred.resolve(response);
+ };
+ let onFailed = (error:any):void => {
+ deferred.reject(error);
+ };
+ this.componentService.getComponentInstanceInputs(this.uniqueId, componentInstanceId, originComponentUid).then(onSuccess, onFailed);
+ return deferred.promise;
+ };
+
+ // get inputs inatnce - Pagination function
+ public getComponentInstanceInputProperties = (componentInstanceId:string, inputId:string):ng.IPromise<Array<PropertyModel>> => {
+
+ let deferred = this.$q.defer();
+ let onSuccess = (response:Array<PropertyModel>):void => {
+ deferred.resolve(response);
+ };
+ let onFailed = (error:any):void => {
+ deferred.reject(error);
+ };
+ this.componentService.getComponentInstanceInputProperties(this.uniqueId, componentInstanceId, inputId).then(onSuccess, onFailed);
+ return deferred.promise;
+ };
+
+ // get inputs inatnce - Pagination function
+ public getComponentInstanceProperties = (componentInstanceId:string):ng.IPromise<Array<PropertyModel>> => {
+
+ let deferred = this.$q.defer();
+ let onSuccess = (response:Array<PropertyModel>):void => {
+ deferred.resolve(response);
+ };
+ let onFailed = (error:any):void => {
+ deferred.reject(error);
+ };
+ this.componentService.getComponentInstanceProperties(this.uniqueId, componentInstanceId).then(onSuccess, onFailed);
+ return deferred.promise;
+ };
+
+
+ public updateGroupMetadata = (module:Module):ng.IPromise<Module> => {
+
+ let deferred = this.$q.defer();
+
+ let onSuccess = (updatedModule:Module):void => {
+ let groupIndex:number = _.indexOf(this.groups, _.find(this.groups, (module:Module) => {
+ return module.uniqueId === updatedModule.uniqueId;
+ }));
+
+ if (groupIndex !== -1) {
+ this.groups[groupIndex] = updatedModule;
+ }
+ deferred.resolve(updatedModule);
+ };
+ let onFailed = (error:any):void => {
+ deferred.reject(error);
+ };
+
+ this.componentService.updateGroupMetadata(this.uniqueId, module).then(onSuccess, onFailed);
+
+ return deferred.promise;
+ };
+
+ //------------------------------------------ Help Functions ----------------------------------------------------------------//
+
+ public isProduct = ():boolean => {
+ return this instanceof Product;
+ };
+
+ public isService = ():boolean => {
+ return this instanceof Service;
+ };
+
+ public isResource = ():boolean => {
+ return this instanceof Resource;
+ };
+
+ public getComponentSubType = ():string => {
+ return this.componentType;
+ };
+
+ public isAlreadyCertified = ():boolean => {
+ return parseInt(this.version) >= 1;
+ };
+
+ public isComplex = ():boolean => {
+ return true;
+ };
+
+ //sort string version value from hash to sorted version (i.e 1.9 before 1.11)
+ private sortVersions = (v1:string, v2:string):number => {
+ let ver1 = v1.split('.');
+ let ver2 = v2.split('.');
+ let diff = parseInt(_.first(ver1)) - parseInt(_.first(ver2));
+ if (!diff) {
+ return parseInt(_.last(ver1)) - parseInt(_.last(ver2));
+ }
+ return diff;
+ };
+
+ public getAllVersionsAsSortedArray = ():Array<any> => {
+ let res = [];
+ if (this.allVersions) {
+ let keys = Object.keys(this.allVersions).sort(this.sortVersions);
+ _.forEach(keys, (key)=> {
+ res.push({
+ versionNumber: key,
+ versionId: this.allVersions[key]
+ })
+ });
+ }
+ return res;
+ };
+
+ public isLatestVersion = ():boolean => {
+ if (this.allVersions) {
+ return this.version === _.last(Object.keys(this.allVersions).sort(this.sortVersions));
+ } else {
+ return true;
+ }
+
+ };
+
+ public getAdditionalInformation = ():Array<AdditionalInformationModel> => {
+ let additionalInformationObject:any = _.find(this.additionalInformation, (obj:any):boolean => {
+ return obj.parentUniqueId == this.uniqueId;
+ });
+ if (additionalInformationObject) {
+ return additionalInformationObject.parameters;
+ }
+ return [];
+ };
+
+ public handleTags = ():void => {
+ let isContainTag = _.find(this.tags, (tag)=> {
+ return tag === this.name;
+ });
+ if (!isContainTag) {
+ this.tags.push(this.name);
+ }
+ };
+
+ public getArtifactsByType = (artifactGroupType:string):ArtifactGroupModel => {
+ switch (artifactGroupType) {
+ case ArtifactGroupType.DEPLOYMENT:
+ return this.deploymentArtifacts;
+ case ArtifactGroupType.INFORMATION:
+ return this.artifacts;
+ }
+ };
+
+ public getStatus = (sdcMenu:IAppMenu):string => {
+ let status:string = sdcMenu.LifeCycleStatuses[this.lifecycleState].text;
+ if (this.lifecycleState == "CERTIFIED" && sdcMenu.DistributionStatuses[this.distributionStatus]) {
+ status = sdcMenu.DistributionStatuses[this.distributionStatus].text;
+ }
+ return status;
+ };
+
+ public abstract setComponentDisplayData():void;
+ public abstract getTypeUrl():string;
+
+ public setComponentMetadata(componentMetadata: ComponentMetadata) {
+ this.abstract = componentMetadata.abstract;
+ this.uniqueId = componentMetadata.uniqueId;
+ this.uuid = componentMetadata.uuid;
+ this.invariantUUID = componentMetadata.invariantUUID;
+ this.contactId = componentMetadata.contactId;
+ this.categories = componentMetadata.categories;
+ this.creatorUserId = componentMetadata.creatorUserId;
+ this.creationDate = componentMetadata.creationDate;
+ this.creatorFullName = componentMetadata.creatorFullName;
+ this.description = componentMetadata.description;
+ this.icon = componentMetadata.icon;
+ this.lastUpdateDate = componentMetadata.lastUpdateDate;
+ this.lastUpdaterUserId = componentMetadata.lastUpdaterUserId;
+ this.lastUpdaterFullName = componentMetadata.lastUpdaterFullName;
+ this.lifecycleState = componentMetadata.lifecycleState;
+ this.name = componentMetadata.name;
+ this.version = componentMetadata.version;
+ this.tags = angular.copy(componentMetadata.tags, this.tags);
+ this.allVersions = componentMetadata.allVersions;
+ this.componentType = componentMetadata.componentType;
+ this.distributionStatus = componentMetadata.distributionStatus;
+ this.highestVersion = componentMetadata.highestVersion;
+ this.vendorName = componentMetadata.vendorName;
+ this.vendorRelease = componentMetadata.vendorRelease;
+ this.derivedList = componentMetadata.derivedList;
+ this.normalizedName = componentMetadata.normalizedName;
+ this.systemName = componentMetadata.systemName;
+ this.projectCode = componentMetadata.projectCode;
+ this.categories = componentMetadata.categories;
+
+ }
+
+ public toJSON = ():any => {
+ this.componentService = undefined;
+ this.filterTerm = undefined;
+ this.iconSprite = undefined;
+ this.mainCategory = undefined;
+ this.subCategory = undefined;
+ this.selectedInstance = undefined;
+ this.showMenu = undefined;
+ this.$q = undefined;
+ this.selectedCategory = undefined;
+ return this;
+ };
+}
+
diff --git a/catalog-ui/src/app/models/components/displayComponent.ts b/catalog-ui/src/app/models/components/displayComponent.ts
new file mode 100644
index 0000000000..8b2b522fd9
--- /dev/null
+++ b/catalog-ui/src/app/models/components/displayComponent.ts
@@ -0,0 +1,111 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+/**
+ * Created by obarda on 7/5/2016.
+ */
+
+'use strict';
+import {ComponentType} from "../../utils/constants";
+import {ComponentMetadata} from "../component-metadata";
+import {RequirementsGroup} from "../requirement";
+import {CapabilitiesGroup} from "../capability";
+
+export class LeftPaletteComponent {
+
+ uniqueId:string;
+ displayName:string;
+ version:string;
+ mainCategory:string;
+ subCategory:string;
+ iconClass:string;
+ componentSubType:string;
+ searchFilterTerms:string;
+ certifiedIconClass:string;
+ icon:string;
+ isRequirmentAndCapabilitiesLoaded:boolean;
+
+ uuid:string;
+ name:string;
+ lifecycleState:string;
+ allVersions:any;
+ componentType:string;
+ systemName:string;
+
+ capabilities:CapabilitiesGroup;
+ requirements:RequirementsGroup;
+
+ constructor(public component:ComponentMetadata) {
+ this.icon = component.icon;
+ this.version = component.version;
+ this.uniqueId = component.uniqueId;
+ this.isRequirmentAndCapabilitiesLoaded = false;
+ this.uuid = component.uuid;
+ this.name = component.name;
+ this.allVersions = component.allVersions;
+ this.componentType = component.componentType;
+ this.systemName = component.systemName;
+
+ if (component.categories && component.categories[0] && component.categories[0].subcategories && component.categories[0].subcategories[0]) {
+ this.mainCategory = component.categories[0].name;
+ this.subCategory = component.categories[0].subcategories[0].name;
+ } else {
+ this.mainCategory = 'Generic';
+ this.subCategory = 'Generic';
+ }
+
+ 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);
+ this.certifiedIconClass = component.lifecycleState != 'CERTIFIED' ? 'non-certified' : '';
+ if (component.icon === 'vl' || component.icon === 'cp') {
+ this.certifiedIconClass = this.certifiedIconClass + " " + 'smaller-icon';
+ }
+ }
+
+ public initDisplayName = (name:string):void => {
+ let newName =
+ _.last(_.last(_.last(_.last(_.last(_.last(_.last(_.last(name.split('tosca.nodes.'))
+ .split('network.')).split('relationships.')).split('org.openecomp.')).split('resource.nfv.'))
+ .split('nodes.module.')).split('cp.')).split('vl.'));
+ if (newName) {
+ this.displayName = newName;
+ } else {
+ this.displayName = name;
+ }
+ };
+
+ public initIconSprite = (icon:string):void => {
+ switch (this.componentSubType) {
+ case ComponentType.SERVICE:
+ this.iconClass = "sprite-services-icons " + icon;
+ break;
+ case ComponentType.PRODUCT:
+ this.iconClass = "sprite-product-icons " + icon;
+ break;
+ default:
+ this.iconClass = "sprite-resource-icons " + icon;
+ }
+ }
+
+ public getComponentSubType = ():string => {
+ return this.componentSubType;
+ };
+}
diff --git a/catalog-ui/src/app/models/components/product.ts b/catalog-ui/src/app/models/components/product.ts
new file mode 100644
index 0000000000..0f2c00e822
--- /dev/null
+++ b/catalog-ui/src/app/models/components/product.ts
@@ -0,0 +1,105 @@
+/**
+ * Created by obarda on 2/4/2016.
+ */
+'use strict';
+import {Component} from "./component";
+import {IProductService} from "../../services/components/product-service";
+import {IGroup, ISubCategory, IMainCategory, ICategoryBase} from "../category";
+import {ComponentMetadata} from "../component-metadata";
+
+export class Product extends Component {
+
+ public contacts:Array<string>;
+ public componentService:IProductService;
+ public fullName:string;
+
+ constructor(componentService:IProductService, $q:ng.IQService, component?:Product) {
+ super(componentService, $q, component);
+
+ if (component) {
+ this.fullName = component.fullName;
+ this.filterTerm = this.name + ' ' + this.description + ' ' + (this.tags ? this.tags.toString() : '') + ' ' + this.version;
+ this.contacts = component.contacts;
+ }
+ this.componentService = componentService;
+ this.iconSprite = "sprite-product-icons";
+ }
+
+ public deleteGroup = (uniqueId:string):void => {
+ _.forEach(this.categories, (category:IMainCategory) => {
+ _.forEach(category.subcategories, (subcategory:ISubCategory) => {
+ subcategory.groupings = _.reject(subcategory.groupings, (group:IGroup) => {
+ return group.uniqueId === uniqueId;
+ });
+ if (subcategory.groupings.length == 0) { // if there is no groups, delete the subcategory
+ category.subcategories = _.reject(category.subcategories, (subcategoryObj:ISubCategory) => {
+ return subcategoryObj.uniqueId === subcategory.uniqueId;
+ });
+ if (category.subcategories.length == 0) { // if there is no subcategory, delete the category
+ this.categories = _.reject(this.categories, (categoryObj:IMainCategory) => {
+ return categoryObj.uniqueId === category.uniqueId;
+ });
+ }
+ }
+ });
+ });
+ };
+
+ private getCategoryObjectById = (categoriesArray:Array<ICategoryBase>, categoryUniqueId:string):ICategoryBase => {
+ let categorySelected = _.find(categoriesArray, (category) => {
+ return category.uniqueId === categoryUniqueId;
+ });
+ return categorySelected;
+ };
+
+ public addGroup = (category:IMainCategory, subcategory:ISubCategory, group:IGroup):void => {
+ if (!this.categories) {
+ this.categories = new Array<IMainCategory>();
+ }
+ let existingCategory:IMainCategory = <IMainCategory>this.getCategoryObjectById(this.categories, category.uniqueId);
+ let newGroup = angular.copy(group);
+ newGroup.filterTerms = undefined;
+ newGroup.isDisabled = undefined;
+ if (!existingCategory) {
+ let newCategory:IMainCategory = angular.copy(category);
+ newCategory.filteredGroup = undefined;
+ newCategory.subcategories = [];
+ let newSubcategory:ISubCategory = angular.copy(subcategory);
+ newSubcategory.groupings = [];
+ newSubcategory.groupings.push(newGroup);
+ newCategory.subcategories.push(newSubcategory);
+ this.categories.push(newCategory);
+ }
+ else {
+ let existingSubcategory:ISubCategory = <ISubCategory> this.getCategoryObjectById(existingCategory.subcategories, subcategory.uniqueId);
+ if (!existingSubcategory) {
+ let newSubcategory:ISubCategory = angular.copy(subcategory);
+ newSubcategory.groupings = [];
+ newSubcategory.groupings.push(newGroup);
+ existingCategory.subcategories.push(newSubcategory);
+
+ } else {
+ let existingGroup:IGroup = <IGroup> this.getCategoryObjectById(existingSubcategory.groupings, group.uniqueId);
+ if (!existingGroup) {
+ existingSubcategory.groupings.push(newGroup);
+ }
+ }
+ }
+ };
+
+ getTypeUrl():string {
+ return 'products/';
+ }
+
+ public setComponentMetadata(componentMetadata:ComponentMetadata) {
+ super.setComponentMetadata(componentMetadata);
+ this.setComponentDisplayData();
+ };
+
+ setComponentDisplayData():void {
+ this.filterTerm = this.name + ' ' + this.description + ' ' + (this.tags ? this.tags.toString() : '') + ' ' + this.version;
+ this.iconSprite = "sprite-product-icons";
+ }
+}
+
+
diff --git a/catalog-ui/src/app/models/components/resource.ts b/catalog-ui/src/app/models/components/resource.ts
new file mode 100644
index 0000000000..e594451e1a
--- /dev/null
+++ b/catalog-ui/src/app/models/components/resource.ts
@@ -0,0 +1,157 @@
+/**
+ * Created by obarda on 2/3/2016.
+ */
+'use strict';
+import {InstancesInputsOrPropertiesMapData} from "../instance-inputs-properties-map";
+import {PropertyModel} from "../properties";
+import {DisplayModule} from "../modules/base-module";
+import {InputModel} from "../inputs";
+import {ResourceType} from "../../utils/constants";
+import {Component} from "./component";
+import {FileUploadModel} from "../../directives/file-upload/file-upload";
+import {IResourceService} from "../../services/components/resource-service";
+import {ComponentMetadata} from "../component-metadata";
+
+export class Resource extends Component {
+
+ public interfaces:any;
+ public derivedFrom:Array<string>;
+ public componentService:IResourceService;
+ public resourceType:string;
+ public payloadData:string;
+ public payloadName:string;
+ public importedFile:FileUploadModel;
+
+ // Onboarding parameters
+ public csarUUID:string;
+ public csarVersion:string;
+ public csarPackageType:string;
+ public packageId:string;
+
+ constructor(componentService:IResourceService, $q:ng.IQService, component?:Resource) {
+ super(componentService, $q, component);
+ if (component) {
+
+ this.interfaces = component.interfaces;
+ this.derivedFrom = component.derivedFrom;
+ this.payloadData = component.payloadData ? component.payloadData : undefined;
+ this.payloadName = component.payloadName ? component.payloadName : undefined;
+ this.resourceType = component.resourceType;
+ this.csarUUID = component.csarUUID;
+ this.csarVersion = component.csarVersion;
+ this.filterTerm = this.name + ' ' + this.description + ' ' + (this.tags ? this.tags.toString() : '') + ' ' + this.version + ' ' + this.resourceType;
+ if (component.categories && component.categories[0] && component.categories[0].subcategories && component.categories[0].subcategories[0]) {
+ component.mainCategory = component.categories[0].name;
+ component.subCategory = component.categories[0].subcategories[0].name;
+ this.selectedCategory = component.mainCategory + "_#_" + component.subCategory;
+ this.importedFile = component.importedFile;
+ }
+ } else {
+ this.resourceType = ResourceType.VF;
+ }
+
+ this.componentService = componentService;
+ this.iconSprite = "sprite-resource-icons";
+ }
+
+ public setComponentMetadata(componentMetadata: ComponentMetadata) {
+ super.setComponentMetadata(componentMetadata);
+ this.resourceType = componentMetadata.resourceType;
+ this.csarUUID = componentMetadata.csarUUID;
+ this.csarVersion = componentMetadata.csarVersion;
+ this.derivedFrom = componentMetadata.derivedFrom;
+ this.setComponentDisplayData();
+ };
+
+ public getComponentSubType = ():string => {
+ return this.resourceType;
+ };
+
+ public isComplex = ():boolean => {
+ return this.resourceType === ResourceType.VF;
+ };
+
+ public isVl = ():boolean => {
+ return ResourceType.VL == this.resourceType;
+ };
+
+ public isCsarComponent = ():boolean => {
+ return !!this.csarUUID;
+ };
+
+ public createComponentOnServer = ():ng.IPromise<Component> => {
+ let deferred = this.$q.defer();
+ let onSuccess = (component:Resource):void => {
+ this.payloadData = undefined;
+ this.payloadName = undefined;
+ deferred.resolve(component);
+ };
+ let onError = (error:any):void => {
+ deferred.reject(error);
+ };
+
+ this.handleTags();
+ if (this.importedFile) {
+ this.payloadData = this.importedFile.base64;
+ this.payloadName = this.importedFile.filename;
+ }
+ this.componentService.createComponent(this).then(onSuccess, onError);
+ return deferred.promise;
+ };
+
+
+ public updateResourceGroupProperties = (module:DisplayModule, properties:Array<PropertyModel>):ng.IPromise<Array<PropertyModel>> => {
+ let deferred = this.$q.defer();
+ let onSuccess = (updatedProperties:Array<PropertyModel>):void => {
+ _.forEach(updatedProperties, (property:PropertyModel) => { // Replace all updated properties on the module we needed to update
+ _.extend(_.find(module.properties, {uniqueId: property.uniqueId}), property);
+
+ });
+ //_.extend(_.findWhere(this.groups, {uniqueId: module.uniqueId }), module); // replace the module on the component so all data will be updates if the module sent to the function is a copy
+ deferred.resolve(updatedProperties);
+ };
+ let onError = (error:any):void => {
+ deferred.reject(error);
+ };
+
+ this.componentService.updateResourceGroupProperties(this.uniqueId, module.uniqueId, properties).then(onSuccess, onError);
+ return deferred.promise;
+ };
+
+ // For now we only implement the logic in service level
+ public createInputsFormInstances = (instanceInputsPropertiesMap:InstancesInputsOrPropertiesMapData):ng.IPromise<Array<InputModel>> => {
+ let deferred = this.$q.defer();
+ return deferred.promise;
+ };
+
+ getTypeUrl():string {
+ return 'resources/';
+ }
+
+
+ setComponentDisplayData():void {
+ this.filterTerm = this.name + ' ' + this.description + ' ' + (this.tags ? this.tags.toString() : '') + ' ' + this.version + ' ' + this.resourceType;
+ if (this.categories && this.categories[0] && this.categories[0].subcategories && this.categories[0].subcategories[0]) {
+ this.mainCategory = this.categories[0].name;
+ this.subCategory = this.categories[0].subcategories[0].name;
+ this.selectedCategory = this.mainCategory + "_#_" + this.subCategory;
+ this.iconSprite = "sprite-resource-icons";
+ }
+ };
+
+ public toJSON = ():any => {
+ this.componentService = undefined;
+ this.filterTerm = undefined;
+ this.iconSprite = undefined;
+ this.mainCategory = undefined;
+ this.subCategory = undefined;
+ this.selectedInstance = undefined;
+ this.showMenu = undefined;
+ this.$q = undefined;
+ this.selectedCategory = undefined;
+ this.importedFile = undefined;
+ return this;
+ };
+}
+
+
diff --git a/catalog-ui/src/app/models/components/service.ts b/catalog-ui/src/app/models/components/service.ts
new file mode 100644
index 0000000000..a4dd3155d7
--- /dev/null
+++ b/catalog-ui/src/app/models/components/service.ts
@@ -0,0 +1,150 @@
+/**
+ * Created by obarda on 2/4/2016.
+ */
+'use strict';
+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";
+
+export class Service extends Component {
+
+ public serviceApiArtifacts:ArtifactGroupModel;
+ public componentService:IServiceService;
+ public ecompGeneratedNaming:boolean;
+ public namingPolicy:string;
+
+ constructor(componentService:IServiceService, $q:ng.IQService, component?:Service) {
+ super(componentService, $q, component);
+ this.ecompGeneratedNaming = true;
+ if (component) {
+ this.serviceApiArtifacts = new ArtifactGroupModel(component.serviceApiArtifacts);
+ this.filterTerm = this.name + ' ' + this.description + ' ' + (this.tags ? this.tags.toString() : '') + ' ' + this.version;
+ this.ecompGeneratedNaming = component.ecompGeneratedNaming;
+ this.namingPolicy = component.namingPolicy;
+ if (component.categories && component.categories[0]) {
+ this.mainCategory = component.categories[0].name;
+ this.selectedCategory = this.mainCategory;
+ }
+ }
+ this.componentService = componentService;
+ this.iconSprite = "sprite-services-icons";
+ }
+
+ public getDistributionsList = ():ng.IPromise<Array<Distribution>> => {
+ return this.componentService.getDistributionsList(this.uuid);
+ };
+
+ public getDistributionsComponent = (distributionId:string):ng.IPromise<Array<DistributionComponent>> => {
+ return this.componentService.getDistributionComponents(distributionId);
+ };
+
+ public markAsDeployed = (distributionId:string):ng.IPromise<any> => {
+ return this.componentService.markAsDeployed(this.uniqueId, distributionId);
+ };
+
+ /* we need to change the name of the input to vfInstanceName + input name before sending to server in order to create the inputs on the service
+ * we also need to remove already selected inputs (the inputs that already create on server, and disabled in the view - but they are selected so they are still in the view model
+ */
+ public createInputsFormInstances = (instancesInputsMap:InstancesInputsOrPropertiesMapData, instancePropertiesMap:InstancesInputsOrPropertiesMapData):ng.IPromise<Array<InputModel>> => {
+
+ let deferred = this.$q.defer();
+ let onSuccess = (inputsCreated:Array<InputModel>):void => {
+ this.inputs = inputsCreated.concat(this.inputs);
+ deferred.resolve(inputsCreated);
+ };
+ let onFailed = (error:any):void => {
+ deferred.reject(error);
+ };
+
+ let propertiesAndInputsMap:InstancesInputsPropertiesMap = new InstancesInputsPropertiesMap(instancesInputsMap, instancePropertiesMap);
+ propertiesAndInputsMap = propertiesAndInputsMap.cleanUnnecessaryDataBeforeSending(); // We need to create a copy of the map, without the already selected inputs / properties, and to send the clean map
+ this.componentService.createInputsFromInstancesInputs(this.uniqueId, propertiesAndInputsMap).then(onSuccess, onFailed);
+ return deferred.promise;
+ };
+
+ // we need to change the name of the input to vfInstanceName + input name before sending to server in order to create the inputs on the service
+ public getServiceInputInputsAndProperties = (inputId:string):ng.IPromise<Array<InputModel>> => {
+ let deferred = this.$q.defer();
+ let onSuccess = (inputsAndProperties:InputsAndProperties):void => {
+ let input:InputModel = _.find(this.inputs, (input:InputModel) => {
+ return input.uniqueId === inputId;
+ });
+ input.inputs = inputsAndProperties.inputs;
+ input.properties = inputsAndProperties.properties;
+ deferred.resolve(inputsAndProperties);
+ };
+ let onFailed = (error:any):void => {
+ deferred.reject(error);
+ };
+ this.componentService.getComponentInputInputsAndProperties(this.uniqueId, inputId).then(onSuccess, onFailed);
+ return deferred.promise;
+ };
+
+ public deleteServiceInput = (inputId:string):ng.IPromise<InputModel> => {
+ let deferred = this.$q.defer();
+
+ let onSuccess = (deletedInput:InputModel):void => {
+ delete _.remove(this.inputs, {uniqueId: deletedInput.uniqueId})[0];
+ deferred.resolve(deletedInput);
+ };
+
+ let onFailed = (error:any):void => {
+ deferred.reject(error);
+ };
+
+ this.componentService.deleteComponentInput(this.uniqueId, inputId).then(onSuccess, onFailed);
+ return deferred.promise;
+ };
+
+ public getArtifactsByType = (artifactGroupType:string):ArtifactGroupModel => {
+ switch (artifactGroupType) {
+ case ArtifactGroupType.DEPLOYMENT:
+ return this.deploymentArtifacts;
+ case ArtifactGroupType.INFORMATION:
+ return this.artifacts;
+ case ArtifactGroupType.SERVICE_API:
+ return this.serviceApiArtifacts;
+ }
+ };
+
+ public updateGroupInstanceProperties = (resourceInstanceId:string, group:DisplayModule, properties:Array<PropertyModel>):ng.IPromise<Array<PropertyModel>> => {
+
+ let deferred = this.$q.defer();
+ let onSuccess = (updatedProperties:Array<PropertyModel>):void => {
+ _.forEach(updatedProperties, (property:PropertyModel) => { // Replace all updated properties on the we needed to update
+ _.extend(_.find(group.properties, {uniqueId: property.uniqueId}), property);
+ });
+ deferred.resolve(updatedProperties);
+ };
+ let onError = (error:any):void => {
+ deferred.reject(error);
+ };
+
+ this.componentService.updateGroupInstanceProperties(this.uniqueId, resourceInstanceId, group.groupInstanceUniqueId, properties).then(onSuccess, onError);
+ return deferred.promise;
+ };
+
+ getTypeUrl():string {
+ return 'services/';
+ }
+
+
+ public setComponentMetadata(componentMetadata: ComponentMetadata) {
+ super.setComponentMetadata(componentMetadata);
+ this.ecompGeneratedNaming = componentMetadata.ecompGeneratedNaming;
+ this.namingPolicy = componentMetadata.namingPolicy;
+ this.setComponentDisplayData();
+ }
+
+ setComponentDisplayData():void {
+ this.filterTerm = this.name + ' ' + this.description + ' ' + (this.tags ? this.tags.toString() : '') + ' ' + this.version;
+ if (this.categories && this.categories[0]) {
+ this.mainCategory = this.categories[0].name;
+ this.selectedCategory = this.mainCategory;
+ }
+ this.iconSprite = "sprite-services-icons";
+ }
+}
+
diff --git a/catalog-ui/src/app/models/componentsInstances/componentInstance.ts b/catalog-ui/src/app/models/componentsInstances/componentInstance.ts
new file mode 100644
index 0000000000..22c6232548
--- /dev/null
+++ b/catalog-ui/src/app/models/componentsInstances/componentInstance.ts
@@ -0,0 +1,113 @@
+/**
+ * Created by obarda on 2/4/2016.
+ */
+'use strict';
+import {ArtifactGroupModel, CapabilitiesGroup,RequirementsGroup, PropertyModel, InputModel, Module} from "../../models";
+import {ResourceType} from "../../utils/constants";
+
+export class ComponentInstance {
+
+ public componentUid:string;
+ public componentName:string;
+ public posX:number;
+ public posY:number;
+ public componentVersion:string;
+ public description:string;
+ public icon:string;
+ public name:string;
+ public normalizedName:string;
+ public originType:string;
+ public deploymentArtifacts:ArtifactGroupModel;
+ public artifacts:ArtifactGroupModel;
+ public propertyValueCounter:number;
+ public uniqueId:string;
+ public creationTime:number;
+ public modificationTime:number;
+ public capabilities:CapabilitiesGroup;
+ public requirements:RequirementsGroup;
+ public customizationUUID:string;
+ //custom properties
+ public certified:boolean;
+ public iconSprite:string;
+ public inputs:Array<InputModel>;
+ public properties:Array<PropertyModel>;
+ public groupInstances:Array<Module>;
+
+ constructor(componentInstance?:ComponentInstance) {
+
+ if (componentInstance) {
+ this.componentUid = componentInstance.componentUid;
+ this.componentName = componentInstance.componentName;
+
+ this.componentVersion = componentInstance.componentVersion;
+ this.description = componentInstance.description;
+ this.icon = componentInstance.icon;
+ this.name = componentInstance.name;
+ this.normalizedName = componentInstance.normalizedName;
+ this.originType = componentInstance.originType;
+ this.deploymentArtifacts = new ArtifactGroupModel(componentInstance.deploymentArtifacts);
+ this.artifacts = new ArtifactGroupModel(componentInstance.artifacts);
+ this.uniqueId = componentInstance.uniqueId;
+ this.creationTime = componentInstance.creationTime;
+ this.modificationTime = componentInstance.modificationTime;
+ this.propertyValueCounter = componentInstance.propertyValueCounter;
+ this.capabilities = new CapabilitiesGroup(componentInstance.capabilities);
+ this.requirements = new RequirementsGroup(componentInstance.requirements);
+ this.certified = componentInstance.certified;
+ this.customizationUUID = componentInstance.customizationUUID;
+ this.updatePosition(componentInstance.posX, componentInstance.posY);
+ this.groupInstances = componentInstance.groupInstances;
+ }
+ }
+
+ public isUcpe = ():boolean => {
+ if (this.originType === 'VF' && this.capabilities && this.capabilities['tosca.capabilities.Container'] && this.name.toLowerCase().indexOf('ucpe') > -1) {
+ return true;
+ }
+ return false;
+ };
+
+ public isVl = ():boolean => {
+ return this.originType === 'VL';
+ };
+
+ public isComplex = () : boolean => {
+ return this.originType === ResourceType.VF;
+ }
+
+ public setInstanceRC = ():void=> {
+ _.forEach(this.requirements, (requirementValue:Array<any>, requirementKey)=> {
+ _.forEach(requirementValue, (requirement)=> {
+ if (!requirement.ownerName) {
+ requirement['ownerId'] = this.uniqueId;
+ requirement['ownerName'] = this.name;
+ }
+ });
+ });
+ _.forEach(this.capabilities, (capabilityValue:Array<any>, capabilityKey)=> {
+ _.forEach(capabilityValue, (capability)=> {
+ if (!capability.ownerName) {
+ capability['ownerId'] = this.uniqueId;
+ capability['ownerName'] = this.name;
+ }
+ });
+ });
+ };
+
+ public updatePosition(posX:number, posY:number) {
+ this.posX = posX;
+ this.posY = posY;
+ }
+
+ public toJSON = ():any => {
+ let temp = angular.copy(this);
+ temp.certified = undefined;
+ temp.iconSprite = undefined;
+ temp.inputs = undefined;
+ temp.groupInstances = undefined;
+ temp.properties = undefined;
+ temp.requirements = undefined;
+ temp.capabilities = undefined;
+ return temp;
+ };
+}
diff --git a/catalog-ui/src/app/models/componentsInstances/productInstance.ts b/catalog-ui/src/app/models/componentsInstances/productInstance.ts
new file mode 100644
index 0000000000..7b73f83988
--- /dev/null
+++ b/catalog-ui/src/app/models/componentsInstances/productInstance.ts
@@ -0,0 +1,13 @@
+/**
+ * Created by obarda on 2/4/2016.
+ */
+'use strict';
+import {ComponentInstance} from "./componentInstance";
+
+export class ProductInstance extends ComponentInstance {
+
+ constructor(componentInstance?:ProductInstance) {
+ super(componentInstance);
+ this.iconSprite = "sprite-product-icons";
+ }
+}
diff --git a/catalog-ui/src/app/models/componentsInstances/resourceInstance.ts b/catalog-ui/src/app/models/componentsInstances/resourceInstance.ts
new file mode 100644
index 0000000000..be4bde9af9
--- /dev/null
+++ b/catalog-ui/src/app/models/componentsInstances/resourceInstance.ts
@@ -0,0 +1,15 @@
+/**
+ * Created by obarda on 2/4/2016.
+ */
+'use strict';
+import {ComponentInstance} from "./componentInstance";
+
+export class ResourceInstance extends ComponentInstance {
+
+ constructor(componentInstance?:ResourceInstance) {
+ super(componentInstance);
+
+ this.iconSprite = "sprite-resource-icons";
+ }
+}
+
diff --git a/catalog-ui/src/app/models/componentsInstances/serviceInstance.ts b/catalog-ui/src/app/models/componentsInstances/serviceInstance.ts
new file mode 100644
index 0000000000..060519b83d
--- /dev/null
+++ b/catalog-ui/src/app/models/componentsInstances/serviceInstance.ts
@@ -0,0 +1,14 @@
+/**
+ * Created by obarda on 2/4/2016.
+ */
+'use strict';
+import {ComponentInstance} from "./componentInstance";
+
+export class ServiceInstance extends ComponentInstance {
+
+ constructor(componentInstance?:ServiceInstance) {
+ super(componentInstance);
+ this.iconSprite = "sprite-services-icons";
+ }
+}
+
diff --git a/catalog-ui/src/app/models/csar-component.ts b/catalog-ui/src/app/models/csar-component.ts
new file mode 100644
index 0000000000..301da959f7
--- /dev/null
+++ b/catalog-ui/src/app/models/csar-component.ts
@@ -0,0 +1,15 @@
+'use strict';
+
+export interface ICsarComponent {
+ displayName:string;
+ description:string;
+ vspName:string;
+ version:string;
+ packageId:string;
+ category:string;
+ subCategory:string
+ vendorName:string;
+ packageType:string;
+ vendorRelease:string;
+}
+
diff --git a/catalog-ui/src/app/models/data-type-properties.ts b/catalog-ui/src/app/models/data-type-properties.ts
new file mode 100644
index 0000000000..a36e87b0fc
--- /dev/null
+++ b/catalog-ui/src/app/models/data-type-properties.ts
@@ -0,0 +1,39 @@
+/**
+ * Created by rcohen on 9/25/2016.
+ */
+'use strict';
+import {SchemaPropertyGroupModel} from "./aschema-property";
+import {PropertyModel} from "./properties";
+
+export class DataTypePropertyModel extends PropertyModel{
+ //custom
+ simpleType:string;
+ valueObjectRef:any;
+ childrenProperties:Array<DataTypePropertyModel>;
+ isAllChildrenLevelsCalculated:boolean;
+ treeNodeId:string;
+ parent:DataTypePropertyModel;
+ expandedChildPropertyId:string;
+
+ constructor(property?:PropertyModel);
+ constructor(name:string, type:string, treeNodeId:string, parent:DataTypePropertyModel, valueObjectRef:any, schema?:SchemaPropertyGroupModel);
+ constructor(nameOrPropertyObj?:string | PropertyModel, type?:string, treeNodeId?:string, parent?:DataTypePropertyModel, valueObjectRef?:any, schema?:SchemaPropertyGroupModel){
+ super(typeof nameOrPropertyObj === "string" ? null : nameOrPropertyObj);
+ if ( typeof nameOrPropertyObj === "string" ) {
+ this.name = nameOrPropertyObj;
+ this.type = type;
+ this.treeNodeId = treeNodeId;
+ this.parent = parent;
+ this.valueObjectRef = valueObjectRef;
+ this.schema = schema;
+ }
+ }
+
+ public updateExpandedChildPropertyId = (childPropertyId:string):void =>{
+ if(this.expandedChildPropertyId == childPropertyId){
+ this.expandedChildPropertyId = "";
+ }else{
+ this.expandedChildPropertyId = childPropertyId;
+ }
+ }
+}
diff --git a/catalog-ui/src/app/models/data-types-map.ts b/catalog-ui/src/app/models/data-types-map.ts
new file mode 100644
index 0000000000..8aa38e26e7
--- /dev/null
+++ b/catalog-ui/src/app/models/data-types-map.ts
@@ -0,0 +1,17 @@
+/**
+ * Created by rcohen on 9/25/2016.
+ */
+'use strict';
+import {DataTypeModel} from "./data-types";
+
+export class DataTypesMapData {
+ [dataTypeId:string]:Array<DataTypeModel>;
+}
+
+export class DataTypesMap {
+ dataTypesMap:DataTypesMapData;
+
+ constructor(dataTypesMap:DataTypesMapData) {
+ this.dataTypesMap = dataTypesMap;
+ }
+}
diff --git a/catalog-ui/src/app/models/data-types.ts b/catalog-ui/src/app/models/data-types.ts
new file mode 100644
index 0000000000..060ebf7e7d
--- /dev/null
+++ b/catalog-ui/src/app/models/data-types.ts
@@ -0,0 +1,34 @@
+/**
+ * Created by rcohen on 9/25/2016.
+ */
+'use strict';
+import {PropertyBEModel} from "./properties-inputs/property-be-model";
+
+export class DataTypeModel {
+
+ //server data
+ name:string;
+ uniqueId:string;
+ derivedFromName:string;
+ derivedFrom:DataTypeModel;
+ creationTime:string;
+ modificationTime:string;
+ properties: Array<PropertyBEModel>;
+
+ constructor(dataType:DataTypeModel) {
+ if (dataType) {
+ this.uniqueId = dataType.uniqueId;
+ this.name = dataType.name;
+ this.derivedFromName = dataType.derivedFromName;
+ this.creationTime = dataType.creationTime;
+ this.modificationTime = dataType.modificationTime;
+ this.properties = dataType.properties;
+ }
+ }
+
+ public toJSON = ():any => {
+
+ return this;
+ };
+}
+
diff --git a/catalog-ui/src/app/models/distribution.ts b/catalog-ui/src/app/models/distribution.ts
new file mode 100644
index 0000000000..b6854c68a2
--- /dev/null
+++ b/catalog-ui/src/app/models/distribution.ts
@@ -0,0 +1,43 @@
+'use strict';
+
+export class DistributionStatuses {
+ public omfComponentID:string;
+ public url:string;
+ public timestamp:string;
+ public status:string;
+
+ constructor() {
+ }
+}
+
+
+export class DistributionComponent {
+ public omfComponentID:string;
+ public url:string;
+ public timestamp:string;
+ public status:string;
+
+ constructor() {
+ }
+}
+
+export class Distribution {
+ public distributionID:string;
+ public timestamp:string;
+ public userId:string;
+ public deployementStatus:string;
+ public distributionComponents:Array<DistributionComponent>;
+ public statusCount:any;
+ //custom data
+ public dateFormat:string;
+
+ constructor() {
+ }
+
+ public toJSON = ():any => {
+ this.dateFormat = undefined;
+ return this;
+ };
+}
+
+
diff --git a/catalog-ui/src/app/models/export-excel.ts b/catalog-ui/src/app/models/export-excel.ts
new file mode 100644
index 0000000000..7d0bc56a7b
--- /dev/null
+++ b/catalog-ui/src/app/models/export-excel.ts
@@ -0,0 +1,12 @@
+/**
+ * Created by rcohen on 11/7/2016.
+ */
+'use strict';
+
+export class ExportExcel {
+ fileName:string;
+ metaData:Array<string>;//array of text rows that display on the top of table
+ dataObj:any;//array of JSONs - the table data
+ tableHeaders:Array<string>;
+ groupByField:string;//[optional] get field name in order to split data to some tables group by this field
+}
diff --git a/catalog-ui/src/app/models/file-download.ts b/catalog-ui/src/app/models/file-download.ts
new file mode 100644
index 0000000000..d63963e1ba
--- /dev/null
+++ b/catalog-ui/src/app/models/file-download.ts
@@ -0,0 +1,6 @@
+'use strict';
+
+export interface IFileDownload {
+ artifactName:string;
+ base64Contents:string;
+}
diff --git a/catalog-ui/src/app/models/filter-properties-assignment-data.ts b/catalog-ui/src/app/models/filter-properties-assignment-data.ts
new file mode 100644
index 0000000000..067ac630de
--- /dev/null
+++ b/catalog-ui/src/app/models/filter-properties-assignment-data.ts
@@ -0,0 +1,10 @@
+/**
+ * Created by rc2122 on 5/16/2017.
+ */
+export class FilterPropertiesAssignmentData {
+ propertyName:string;
+ selectedTypes:Array<string>;
+ constructor(){
+ this.selectedTypes = [];
+ }
+}
diff --git a/catalog-ui/app/scripts/filters/trim-filter.ts b/catalog-ui/src/app/models/graph/assetPopoverObj.ts
index fd231abc8d..c4fea9b994 100644
--- a/catalog-ui/app/scripts/filters/trim-filter.ts
+++ b/catalog-ui/src/app/models/graph/assetPopoverObj.ts
@@ -17,22 +17,27 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-/// <reference path="../references"/>
-module Sdc.Filters {
- export class TrimFilter {
+'use strict';
- constructor() {
- let filter = <TrimFilter>( (text:string) => {
- if (!angular.isString(text)) {
- return text;
- }
+export class AssetPopoverObj {
- return text.replace(/^\s+|\s+$/g, ''); // you could use .trim, but it's not going to work in IE<9
- });
+ nodeId:string;
+ displayName:string;
+ menuPosition:Cy.Position;
+ menuSide:string;
+ isViewOnly:boolean;
+ VLArray:Array<any>;
+ CPArray:Array<any>;
- return filter;
- }
+ constructor(nodeId:string, displayName:string, menuPosition:Cy.Position, menuSide:string, isViewOnly?:boolean, VLArray?:Array<any>, CPArray?:Array<any>) {
+ this.nodeId = nodeId;
+ this.displayName = displayName;
+ this.menuPosition = {x: menuPosition.x, y: menuPosition.y};
+ this.menuSide = menuSide;
+ this.isViewOnly = isViewOnly || false;
+ this.VLArray = VLArray || [];
+ this.CPArray = CPArray || [];
}
}
diff --git a/catalog-ui/app/scripts/models/graph/graph-links/module-graph-links/module-ci-link-base.ts b/catalog-ui/src/app/models/graph/graph-links/common-base-link.ts
index b85e7673f5..4d6d989daf 100644
--- a/catalog-ui/app/scripts/models/graph/graph-links/module-graph-links/module-ci-link-base.ts
+++ b/catalog-ui/src/app/models/graph/graph-links/common-base-link.ts
@@ -20,19 +20,31 @@
/**
* Created by obarda on 6/29/2016.
*/
-/// <reference path="../../../../references"/>
-module Sdc.Models {
- export interface IModuleCiLinkBase extends ICommonCiLinkBase{
+export class CommonLinkBase {
- }
+ img:string;
+ color:string;
+ classes:string;
- export class ModuleCiLinkBase extends CommonCiLinkBase implements IModuleCiLinkBase {
+ //this is cytoscapejs fields
+ public source:string;
+ public target:string;
+ public type:string;
+ public isSdcElement:boolean;
- constructor(relation?:RelationshipModel, singleRelationship?:Models.Relationship) {
- super(relation, singleRelationship);
- this.color = Utils.Constants.GraphColors.BASE_LINK;
- }
+ constructor() {
+ this.isSdcElement = true;
+ this.type = 'sdc-link';
}
+
+ public setImage = (imgUrl:string) => {
+ this.img = imgUrl;
+ };
+
+ public setColor = (color:string) => {
+ this.color = color;
+ };
+
}
diff --git a/catalog-ui/app/scripts/models/graph/nodes/modules-graph-nodes/module-node-base.ts b/catalog-ui/src/app/models/graph/graph-links/common-ci-link-base.ts
index cd6ab3ba85..12e66c86f9 100644
--- a/catalog-ui/app/scripts/models/graph/nodes/modules-graph-nodes/module-node-base.ts
+++ b/catalog-ui/src/app/models/graph/graph-links/common-ci-link-base.ts
@@ -17,36 +17,33 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+import {Relationship, RelationshipModel} from "../relationship";
+import {CommonLinkBase} from "./common-base-link";
/**
* Created by obarda on 6/29/2016.
*/
-/// <reference path="../../../../references"/>
-module Sdc.Models.Graph {
- 'use strict';
+export interface ICommonCiLinkBase {
- export interface IModuleNodeBase {
- }
-
- export class ModuleNodeBase extends CommonNodeBase implements IModuleNodeBase {
+}
- module:Module;
+export class CommonCiLinkBase extends CommonLinkBase implements ICommonCiLinkBase {
- constructor(module:Module) {
- super();
- this.module = module;
- this.init();
- }
+ relation:RelationshipModel;
- private init() {
-
- this.id = this.module.uniqueId;
- this.name = this.module.name;
- this.displayName = this.module.name;
- this.isGroup = true;
- this.img = Utils.Constants.IMAGE_PATH + Utils.Constants.ImagesUrl.MODULE_ICON;
- this.classes = "module-node";
- }
+ constructor(relation?:RelationshipModel, singleRelationship?:Relationship) {
+ super();
+ if (relation) {
+ if (singleRelationship) {
+ this.relation = new RelationshipModel(relation, singleRelationship);
+ } else {
+ this.relation = new RelationshipModel(relation);
+ }
+ this.source = relation.fromNode;
+ this.target = relation.toNode;
+ } else {
+ this.relation = new RelationshipModel();
}
+ }
}
diff --git a/catalog-ui/app/scripts/services/configuration-ui-service.ts b/catalog-ui/src/app/models/graph/graph-links/composition-graph-links/composition-ci-link-base.ts
index 51eb3dcd9c..04b28c7ceb 100644
--- a/catalog-ui/app/scripts/services/configuration-ui-service.ts
+++ b/catalog-ui/src/app/models/graph/graph-links/composition-graph-links/composition-ci-link-base.ts
@@ -17,33 +17,30 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-/// <reference path="../references"/>
-module Sdc.Services {
- 'use strict'
+import {ICommonCiLinkBase, CommonCiLinkBase} from "../common-ci-link-base";
+import {RelationshipModel, Relationship} from "../../relationship";
- interface IConfigurationUiService {
- getConfigurationUi(): ng.IPromise<any>;
- }
-
- export class ConfigurationUiService implements IConfigurationUiService{
+export interface ICompositionCiLinkBase extends ICommonCiLinkBase {
+ updateLinkDirection():void;
+}
- static '$inject' = ['$http', '$q','sdcConfig'];
- private api: Models.IApi;
+export class CompositionCiLinkBase extends CommonCiLinkBase implements ICompositionCiLinkBase {
- constructor(private $http: ng.IHttpService, private $q: ng.IQService, sdcConfig: Models.IAppConfigurtaion){
- this.api = sdcConfig.api;
- }
+ type:string;
+ visible:boolean;
- getConfigurationUi = (): ng.IPromise<any> =>{
- let defer = this.$q.defer<any>();
- this.$http.get(this.api.root+this.api.GET_configuration_ui)
- .success((result: any) => {
- defer.resolve(result);
- });
- return defer.promise;
+ constructor(relation?:RelationshipModel, singleRelationship?:Relationship) {
+ super(relation, singleRelationship);
+ this.visible = true;
}
- }
+ public setRelation = (relation:RelationshipModel) => {
+ this.relation = relation;
+ };
+ updateLinkDirection():void {
+ this.source = this.relation.fromNode;
+ this.target = this.relation.toNode;
+ }
}
diff --git a/catalog-ui/app/scripts/filters/tests-id-filter.ts b/catalog-ui/src/app/models/graph/graph-links/composition-graph-links/composition-ci-simple-link.ts
index 12c5e6fd79..e213fa9b33 100644
--- a/catalog-ui/app/scripts/filters/tests-id-filter.ts
+++ b/catalog-ui/src/app/models/graph/graph-links/composition-graph-links/composition-ci-simple-link.ts
@@ -17,17 +17,16 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-module Sdc.Filters {
- export class TestsIdFilter{
+import {CompositionCiLinkBase} from "./composition-ci-link-base";
+import {Relationship, RelationshipModel} from "../../relationship";
+import {GraphColors} from "../../../../utils/constants";
- constructor() {
- let filter = <TestsIdFilter>( (testId:string) => {
- return testId.replace(/\s/g, '_').toLowerCase();
- });
+export class CompositionCiSimpleLink extends CompositionCiLinkBase {
- return filter;
- }
+ constructor(relation?:RelationshipModel, singleRelationship?:Relationship) {
+ super(relation, singleRelationship);
+ this.color = GraphColors.BASE_LINK;
+ this.classes = 'simple-link';
}
-
}
diff --git a/catalog-ui/app/scripts/models/graph/graph-links/composition-graph-links/composition-ci-ucpe-host-link.ts b/catalog-ui/src/app/models/graph/graph-links/composition-graph-links/composition-ci-ucpe-host-link.ts
index 7a30c20eee..b756dab129 100644
--- a/catalog-ui/app/scripts/models/graph/graph-links/composition-graph-links/composition-ci-ucpe-host-link.ts
+++ b/catalog-ui/src/app/models/graph/graph-links/composition-graph-links/composition-ci-ucpe-host-link.ts
@@ -17,17 +17,16 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+import {RelationshipModel, Relationship} from "../../relationship";
+import {CompositionCiLinkBase} from "./composition-ci-link-base";
/**
* Created by obarda on 4/20/2016.
*/
-/// <reference path="../../../../references"/>
-module Sdc.Models {
- export class LinkUcpeHost extends CompositionCiLinkBase {
+export class LinkUcpeHost extends CompositionCiLinkBase {
- constructor(relation?:RelationshipModel, singleRelationship?:Models.Relationship) {
- super(relation, singleRelationship);
- this.visible = false;
- this.classes = "ucpe-host-link";
- }
+ constructor(relation?:RelationshipModel, singleRelationship?:Relationship) {
+ super(relation, singleRelationship);
+ this.visible = false;
+ this.classes = "ucpe-host-link";
}
}
diff --git a/catalog-ui/app/scripts/models/data-types-map.ts b/catalog-ui/src/app/models/graph/graph-links/composition-graph-links/composition-ci-ucpe-link.ts
index d1bee48e41..fc8631781a 100644
--- a/catalog-ui/app/scripts/models/data-types-map.ts
+++ b/catalog-ui/src/app/models/graph/graph-links/composition-graph-links/composition-ci-ucpe-link.ts
@@ -17,23 +17,23 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-/**
- * Created by rcohen on 9/25/2016.
- */
-/// <reference path="../references"/>
-module Sdc.Models {
- 'use strict';
- export class DataTypesMapData {
- [dataTypeId:string]: Array<DataTypeModel>;
- }
+import {RelationshipModel, Relationship} from "../../relationship";
+import {CompositionCiLinkBase} from "./composition-ci-link-base";
+import {GraphColors} from "../../../../utils/constants";
+export class CompositionCiUcpeLink extends CompositionCiLinkBase {
- export class DataTypesMap {
- dataTypesMap:DataTypesMapData;
+ isFromUcpe:boolean;
- constructor(dataTypesMap:DataTypesMapData) {
- this.dataTypesMap = dataTypesMap;
- }
+ constructor(relation?:RelationshipModel, from?:boolean, singleRelation?:Relationship) {
+ super(relation, singleRelation);
+ this.isFromUcpe = from;
+ this.target = relation.toNode;
+ this.source = singleRelation.requirementOwnerId;
+ this.relation.relationships = [singleRelation];
+ this.color = GraphColors.BASE_LINK;
}
+ updateLinkDirection():void {
+ }
}
diff --git a/catalog-ui/app/scripts/models/graph/graph-links/composition-graph-links/composition-ci-vl-link.ts b/catalog-ui/src/app/models/graph/graph-links/composition-graph-links/composition-ci-vl-link.ts
index a347db6cb5..e0824ccbe8 100644
--- a/catalog-ui/app/scripts/models/graph/graph-links/composition-graph-links/composition-ci-vl-link.ts
+++ b/catalog-ui/src/app/models/graph/graph-links/composition-graph-links/composition-ci-vl-link.ts
@@ -17,18 +17,18 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-/// <reference path="../../../../references"/>
-module Sdc.Models {
- export class CompositionCiVLink extends CompositionCiLinkBase {
+import {CompositionCiLinkBase} from "./composition-ci-link-base";
+import {RelationshipModel, Relationship} from "../../relationship";
+import {GraphColors} from "../../../../utils/constants";
- constructor(relation?:RelationshipModel, singleRelationship?:Models.Relationship) {
- super(relation, singleRelationship);
- this.color = Utils.Constants.GraphColors.VL_LINK;
- this.classes ='vl-link';
- }
+export class CompositionCiVLink extends CompositionCiLinkBase {
+ constructor(relation?:RelationshipModel, singleRelationship?:Relationship) {
+ super(relation, singleRelationship);
+ this.color = GraphColors.VL_LINK;
+ this.classes = 'vl-link';
+ }
- }
}
diff --git a/catalog-ui/app/scripts/models/graph/graph-links/composition-graph-links/composition-ci-vl-ucpe-link.ts b/catalog-ui/src/app/models/graph/graph-links/composition-graph-links/composition-ci-vl-ucpe-link.ts
index 2ebc796cb9..854eeecad5 100644
--- a/catalog-ui/app/scripts/models/graph/graph-links/composition-graph-links/composition-ci-vl-ucpe-link.ts
+++ b/catalog-ui/src/app/models/graph/graph-links/composition-graph-links/composition-ci-vl-ucpe-link.ts
@@ -17,17 +17,17 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+import {CompositionCiUcpeLink} from "./composition-ci-ucpe-link";
+import {Relationship, RelationshipModel} from "../../relationship";
+import {GraphColors} from "../../../../utils/constants";
/**
* Created by obarda on 4/20/2016.
*/
-/// <reference path="../../../../references"/>
-module Sdc.Models {
- export class CompositionCiVlUcpeLink extends CompositionCiUcpeLink {
+export class CompositionCiVlUcpeLink extends CompositionCiUcpeLink {
- constructor(relation?:RelationshipModel, from?:boolean, singleRelation?:Relationship) {
- super(relation, from, singleRelation);
- this.color = Utils.Constants.GraphColors.VL_LINK;
- }
+ constructor(relation?:RelationshipModel, from?:boolean, singleRelation?:Relationship) {
+ super(relation, from, singleRelation);
+ this.color = GraphColors.VL_LINK;
}
}
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
new file mode 100644
index 0000000000..7fdc0838ed
--- /dev/null
+++ b/catalog-ui/src/app/models/graph/graph-links/links-factory.ts
@@ -0,0 +1,79 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+/**
+ * Created by obarda on 5/1/2016.
+ */
+'use strict';
+import {RelationshipModel, Relationship, CompositionCiLinkBase, CompositionCiNodeBase, LinkUcpeHost, CompositionCiUcpeLink,
+ CompositionCiVlUcpeLink, CompositionCiSimpleLink, ModuleCiLinkBase, ModuleCiVlLink, CompositionCiVLink} from "../../../models";
+
+export class LinksFactory {
+
+ constructor() {
+ }
+
+ public createGraphLink = (cy:Cy.Instance, relation:RelationshipModel, singleRelation:Relationship):CompositionCiLinkBase => {
+
+ let newRelation:CompositionCiLinkBase;
+
+ let fromNode:CompositionCiNodeBase = cy.getElementById(relation.fromNode).data();
+ let toNode:CompositionCiNodeBase = cy.getElementById(relation.toNode).data();
+
+ if ((relation.fromNode && fromNode.isUcpePart) || (relation.toNode && toNode.isUcpePart )) { //Link from or to node inside ucpe
+
+ if (singleRelation && singleRelation.relationship.type && singleRelation.relationship.type == 'tosca.relationships.HostedOn') {
+ newRelation = new LinkUcpeHost(relation, singleRelation);
+ } else if (singleRelation.relationship.type && _.includes(singleRelation.relationship.type.toLowerCase(), 'link')) {
+ newRelation = new CompositionCiVlUcpeLink(relation, fromNode.isUcpePart, singleRelation);
+ } else {
+ newRelation = new CompositionCiUcpeLink(relation, fromNode.isUcpePart, singleRelation);
+ }
+ } else if (singleRelation.relationship.type && _.includes(singleRelation.relationship.type.toLowerCase(), 'link')) {
+ newRelation = new CompositionCiVLink(relation, singleRelation);
+ } else {
+ newRelation = new CompositionCiSimpleLink(relation, singleRelation);
+ }
+
+ return newRelation;
+ };
+
+ public createUcpeHostLink = (relation:RelationshipModel):LinkUcpeHost => {
+ return new LinkUcpeHost(relation);
+ };
+
+ public createVLLink = (relation:RelationshipModel):CompositionCiVLink => {
+ return new CompositionCiVLink(relation);
+ }
+
+
+ public createModuleGraphLinks = (relation:RelationshipModel, singleRelation:Relationship):ModuleCiLinkBase => {
+
+ let newRelation:ModuleCiLinkBase;
+
+ if (_.includes(singleRelation.relationship.type.toLowerCase(), 'link')) {
+ newRelation = new ModuleCiVlLink(relation, singleRelation);
+ } else {
+ newRelation = new ModuleCiLinkBase(relation, singleRelation);
+ }
+
+ return newRelation;
+ };
+
+}
diff --git a/catalog-ui/app/scripts/models/graph/graph-links/module-graph-links/module-ci-vl-link.ts b/catalog-ui/src/app/models/graph/graph-links/module-graph-links/module-ci-link-base.ts
index a421610792..73cd2923eb 100644
--- a/catalog-ui/app/scripts/models/graph/graph-links/module-graph-links/module-ci-vl-link.ts
+++ b/catalog-ui/src/app/models/graph/graph-links/module-graph-links/module-ci-link-base.ts
@@ -20,18 +20,18 @@
/**
* Created by obarda on 6/29/2016.
*/
-/// <reference path="../../../../references"/>
-module Sdc.Models {
+import {Relationship, RelationshipModel, ICommonCiLinkBase, CommonCiLinkBase} from "../../../../models";
+import {GraphColors} from "../../../../utils/constants";
- export interface IModuleCiVlLink extends ICommonCiLinkBase{
+export interface IModuleCiLinkBase extends ICommonCiLinkBase {
- }
+}
- export class ModuleCiVlLink extends CommonCiLinkBase implements IModuleCiVlLink {
+export class ModuleCiLinkBase extends CommonCiLinkBase implements IModuleCiLinkBase {
- constructor(relation?:RelationshipModel, singleRelationship?:Models.Relationship) {
- super(relation, singleRelationship);
- this.color = Utils.Constants.GraphColors.VL_LINK;
- }
+ constructor(relation?:RelationshipModel, singleRelationship?:Relationship) {
+ super(relation, singleRelationship);
+ this.color = GraphColors.BASE_LINK;
}
+
}
diff --git a/catalog-ui/app/scripts/filters/clear-whitespaces-filter.ts b/catalog-ui/src/app/models/graph/graph-links/module-graph-links/module-ci-vl-link.ts
index 5c946e1715..0bc675d465 100644
--- a/catalog-ui/app/scripts/filters/clear-whitespaces-filter.ts
+++ b/catalog-ui/src/app/models/graph/graph-links/module-graph-links/module-ci-vl-link.ts
@@ -17,23 +17,17 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-/// <reference path="../references"/>
-module Sdc.Filters {
+import {Relationship, RelationshipModel, ICommonCiLinkBase, CommonCiLinkBase} from "../../../../models";
+import {GraphColors} from "../../../../utils/constants";
- export class ClearWhiteSpacesFilter {
+export interface IModuleCiVlLink extends ICommonCiLinkBase {
- constructor() {
- let filter = <ClearWhiteSpacesFilter>( (text:string) => {
- if (!angular.isString(text)) {
- return text;
- }
+}
- return text.replace(/ /g,''); // remove also whitespaces inside
- });
+export class ModuleCiVlLink extends CommonCiLinkBase implements IModuleCiVlLink {
- return filter;
- }
+ constructor(relation?:RelationshipModel, singleRelationship?:Relationship) {
+ super(relation, singleRelationship);
+ this.color = GraphColors.VL_LINK;
}
}
-
-
diff --git a/catalog-ui/app/scripts/filters/underscoreless-filter.ts b/catalog-ui/src/app/models/graph/graphTooltip.ts
index 6849a36f04..790608e7f7 100644
--- a/catalog-ui/app/scripts/filters/underscoreless-filter.ts
+++ b/catalog-ui/src/app/models/graph/graphTooltip.ts
@@ -17,17 +17,19 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-module Sdc.Filters {
+'use strict';
- export class UnderscoreLessFilter{
+export class GraphTooltip {
+ position:Cy.Position;
+ isShow:boolean;
+ text:string;
- constructor() {
- let filter = <UnderscoreLessFilter>( (sentence:string) => {
- return sentence.replace(/_/g, ' ');
- });
-
- return filter;
- }
+ constructor();
+ constructor(position:Cy.Position, isShow:boolean, text:string);
+ constructor(position?:Cy.Position, isShow?:boolean, text?:string) {
+ this.position = position;
+ this.isShow = isShow;
+ this.text = text;
}
-
}
+
diff --git a/catalog-ui/app/scripts/filters/product-category-name-filter.ts b/catalog-ui/src/app/models/graph/link-menu.ts
index afe8c7ef08..b3352dd815 100644
--- a/catalog-ui/app/scripts/filters/product-category-name-filter.ts
+++ b/catalog-ui/src/app/models/graph/link-menu.ts
@@ -17,23 +17,20 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-module Sdc.Filters {
+'use strict';
+import {Point} from "./point";
- export class ProductCategoryNameFilter{
+export class LinkMenu {
+ position:Point;
+ isShow:boolean;
+ link:Cy.CollectionFirstEdge;
- constructor() {
- let filter = <CategoryNameFilter>( (name:string) => {
- if(name){
- let newName:string = name.split('/')[1];
- if (newName){
- return newName;
- }
- return name;
- }
- });
-
- return filter;
- }
+ constructor();
+ constructor(point:Point, isShow:boolean, link:Cy.CollectionFirstEdge);
+ constructor(point?:Point, isShow?:boolean, link?:Cy.CollectionFirstEdge) {
+ this.position = point ? point : new Point();
+ this.isShow = isShow ? isShow : false;
+ this.link = link ? link : null;
}
-
}
+
diff --git a/catalog-ui/src/app/models/graph/match-relation.ts b/catalog-ui/src/app/models/graph/match-relation.ts
new file mode 100644
index 0000000000..2de2e930b6
--- /dev/null
+++ b/catalog-ui/src/app/models/graph/match-relation.ts
@@ -0,0 +1,111 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+'use strict';
+import {Requirement} from "../requirement";
+import {Capability} from "../capability";
+import {Relationship, RelationshipModel, RelationType} from "./relationship";
+
+export class MatchBase {
+ requirement:Requirement;
+ isFromTo:boolean;
+ fromNode:string;
+ toNode:string;
+
+ constructor(requirement:Requirement, isFromTo:boolean, fromNode:string, toNode:string) {
+ this.requirement = requirement;
+ this.isFromTo = isFromTo;
+ this.fromNode = fromNode;
+ this.toNode = toNode;
+ }
+
+ public getDisplayText = (menuSide:string):string => {
+ return '';
+ };
+
+ public isOwner = (id:string):boolean => {
+ return false;
+ }
+
+}
+
+export class MatchReqToReq extends MatchBase {
+
+ secondRequirement:Requirement;
+
+ constructor(requirement:Requirement, secondRequirement:Requirement, isFromTo:boolean, fromNode:string, toNode:string) {
+ super(requirement, isFromTo, fromNode, toNode);
+ this.secondRequirement = secondRequirement;
+ }
+
+ public getDisplayText = (menuSide:string):string => {
+ if ('left' == menuSide) {
+ return this.requirement.getFullTitle();
+ }
+ return this.secondRequirement.getFullTitle();
+ };
+
+ public isOwner = (id:string):boolean => {
+ return this.secondRequirement.ownerId === id || this.requirement.ownerId === id;
+ }
+}
+
+export class MatchReqToCapability extends MatchBase {
+
+ capability:Capability;
+
+ constructor(requirement:Requirement, capability:Capability, isFromTo:boolean, fromNode:string, toNode:string) {
+ super(requirement, isFromTo, fromNode, toNode);
+ this.capability = capability;
+ }
+
+ public matchToRelation = ():Relationship => {
+ let relationship:Relationship = new Relationship();
+ relationship.capability = this.capability.name;
+ relationship.capabilityOwnerId = this.capability.ownerId;
+ relationship.capabilityUid = this.capability.uniqueId;
+ relationship.relationship = new RelationType(this.capability.type);
+ relationship.requirement = this.requirement.name;
+ relationship.requirementOwnerId = this.requirement.ownerId;
+ relationship.requirementUid = this.requirement.uniqueId;
+ return relationship;
+ };
+
+
+ public getDisplayText = (menuSide:string):string => {
+ if (this.isFromTo && 'left' == menuSide || !this.isFromTo && 'right' == menuSide) {
+ return this.requirement.getFullTitle();
+ }
+ return this.capability.getFullTitle();
+
+ };
+
+ public isOwner = (id:string):boolean => {
+ return this.capability.ownerId === id || this.requirement.ownerId === id;
+ };
+
+ public matchToRelationModel = ():RelationshipModel => {
+ let relationshipModel:RelationshipModel = new RelationshipModel();
+ let relationship:Relationship = this.matchToRelation();
+ relationshipModel.setRelationshipModelParams(this.fromNode, this.toNode, [relationship]);
+ return relationshipModel;
+ };
+}
+
+
diff --git a/catalog-ui/src/app/models/graph/nodes/base-common-node.ts b/catalog-ui/src/app/models/graph/nodes/base-common-node.ts
new file mode 100644
index 0000000000..aee6b02086
--- /dev/null
+++ b/catalog-ui/src/app/models/graph/nodes/base-common-node.ts
@@ -0,0 +1,70 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+/**
+ * Created by obarda on 6/29/2016.
+ */
+'use strict';
+import {AngularJSBridge} from "../../../services/angular-js-bridge-service";
+
+export abstract class CommonNodeBase {
+
+ public displayName:string;
+ public name:string;
+ public img:string;
+ public certified:boolean;
+ public isGroup:boolean;
+ public imagesPath:string;
+ public isDraggable:boolean; //we need to to manage manually the dragging on the graph inside groups (ucpe-cp is not draggable)
+
+ //cytoscape fields
+ public id:string;
+ public type:string; //type is for the edge edition extension, by type we put the green plus icon in position
+ public isSdcElement:boolean; //this fields is in order to filter sdc elements from all extensions elements
+ public classes:string;
+ public parent:string;
+ public allowConnection:boolean; //this is for egeEdition extension in order to decide if connection to a node is available
+
+ constructor() {
+
+ this.imagesPath = AngularJSBridge.getAngularConfig().imagesPath;
+ this.type = "basic-node";
+ this.isSdcElement = true;
+ this.isDraggable = true;
+ this.allowConnection = true;
+ }
+
+ public updateNameForDisplay = () => {
+ let context = document.createElement("canvas").getContext("2d");
+ context.font = "13px Arial";
+
+ if (63 < context.measureText(this.name).width) {
+ let newLen = this.name.length - 3;
+ let newName = this.name.substring(0, newLen);
+
+ while (60 < (context.measureText(newName).width)) {
+ newName = newName.substring(0, (--newLen));
+ }
+ this.displayName = newName + '...';
+ return;
+ }
+
+ this.displayName = this.name;
+ };
+}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ToscaArtifactsPage.java b/catalog-ui/src/app/models/graph/nodes/common-ci-node-base.ts
index dcc5f0640a..98fb583625 100644
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ToscaArtifactsPage.java
+++ b/catalog-ui/src/app/models/graph/nodes/common-ci-node-base.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,19 +17,28 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+import {CommonNodeBase} from "./base-common-node";
+import {ComponentInstance} from "../../componentsInstances/componentInstance";
+export abstract class CommonCINodeBase extends CommonNodeBase {
-package org.openecomp.sdc.ci.tests.pages;
+ public certified:boolean;
+ public template:string;
+ public componentInstance:ComponentInstance;
+ public group:string;
-import java.util.List;
+ constructor(instance:ComponentInstance) {
+ super();
+ this.componentInstance = instance;
+ this.id = this.componentInstance.uniqueId;
+ this.name = this.componentInstance.name;
+ this.img = '';
+ this.certified = this.isCertified(this.componentInstance.componentVersion);
+ this.displayName = instance.name;
+ }
-import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils;
-import org.openqa.selenium.By;
-import org.openqa.selenium.WebElement;
-
-public class ToscaArtifactsPage extends InformationalArtifactPage {
-
- public ToscaArtifactsPage() {
-
- }
+ private isCertified(version:string):boolean {
+ return 0 === (parseFloat(version)) % 1;
+ }
}
+
diff --git a/catalog-ui/src/app/models/graph/nodes/composition-graph-nodes/composition-ci-node-base.ts b/catalog-ui/src/app/models/graph/nodes/composition-graph-nodes/composition-ci-node-base.ts
new file mode 100644
index 0000000000..d17d97ac19
--- /dev/null
+++ b/catalog-ui/src/app/models/graph/nodes/composition-graph-nodes/composition-ci-node-base.ts
@@ -0,0 +1,73 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR 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 {ComponentInstance} from "../../../componentsInstances/componentInstance";
+import {CommonCINodeBase} from "../common-ci-node-base";
+import {ImageCreatorService} from "app/directives/graphs-v2/image-creator/image-creator.service";
+import {ImagesUrl} from "app/utils";
+import {AngularJSBridge} from "app/services";
+
+export interface ICompositionCiNodeBase {
+
+}
+
+export abstract class CompositionCiNodeBase extends CommonCINodeBase implements ICompositionCiNodeBase {
+
+ public textPosition:string; //need to move to cp UCPE
+ public isUcpe:boolean;
+ public isInsideGroup:boolean;
+ public isUcpePart:boolean;
+
+ constructor(instance:ComponentInstance,
+ public imageCreator:ImageCreatorService) {
+ super(instance);
+ this.init();
+ }
+
+ private init() {
+
+ this.displayName = this.getDisplayName();
+ this.isUcpe = false;
+ this.isGroup = false;
+ this.isUcpePart = false;
+ this.isInsideGroup = false;
+
+ }
+
+ public initImage(node:Cy.Collection):string {
+
+ this.imageCreator.getImageBase64(this.imagesPath + ImagesUrl.RESOURCE_ICONS + this.componentInstance.icon + '.png',
+ this.imagesPath + ImagesUrl.RESOURCE_ICONS + 'uncertified.png')
+ .then(imageBase64 => {
+ this.img = imageBase64;
+ node.style({'background-image': this.img});
+ });
+
+ return this.img;
+ }
+
+ protected getDisplayName():string {
+
+ let graphResourceName = AngularJSBridge.getFilter('graphResourceName');
+ let resourceName = AngularJSBridge.getFilter('resourceName');
+ return graphResourceName(resourceName(this.componentInstance.name));
+ }
+
+}
diff --git a/catalog-ui/src/app/models/graph/nodes/composition-graph-nodes/composition-ci-node-cp.ts b/catalog-ui/src/app/models/graph/nodes/composition-graph-nodes/composition-ci-node-cp.ts
new file mode 100644
index 0000000000..e6d0cc178f
--- /dev/null
+++ b/catalog-ui/src/app/models/graph/nodes/composition-graph-nodes/composition-ci-node-cp.ts
@@ -0,0 +1,50 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+import {CompositionCiNodeBase} from "./composition-ci-node-base";
+import {ComponentInstance} from "../../../componentsInstances/componentInstance";
+import {ImageCreatorService} from "../../../../directives/graphs-v2/image-creator/image-creator.service";
+import {AngularJSBridge} from "../../../../services/angular-js-bridge-service";
+import {ImagesUrl} from "../../../../utils/constants";
+
+export class CompositionCiNodeCp extends CompositionCiNodeBase {
+
+ constructor(instance:ComponentInstance,
+ imageCreator:ImageCreatorService) {
+ super(instance, imageCreator);
+ this.initCp();
+ }
+
+ private initCp():void {
+ let sdcConfig = AngularJSBridge.getAngularConfig();
+ this.img = sdcConfig.imagesPath + ImagesUrl.RESOURCE_ICONS + this.componentInstance.icon + '.png';
+ this.type = "basic-small-node";
+ //if the cp from type cpEndPointInstances create with another template
+ if (sdcConfig.cpEndPointInstances.indexOf(this.componentInstance.icon) > -1) {
+ this.classes = 'cp-end-point-node';
+ } else {
+ this.classes = 'cp-node';
+ }
+ if (!this.certified) {
+ this.classes = this.classes + ' not-certified';
+ }
+
+ }
+}
diff --git a/catalog-ui/app/scripts/models/schema-attribute.ts b/catalog-ui/src/app/models/graph/nodes/composition-graph-nodes/composition-ci-node-service.ts
index 725a7589e0..dd2fb6c6dd 100644
--- a/catalog-ui/app/scripts/models/schema-attribute.ts
+++ b/catalog-ui/src/app/models/graph/nodes/composition-graph-nodes/composition-ci-node-service.ts
@@ -17,21 +17,25 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-/// <reference path="../references"/>
-module Sdc.Models {
- 'use strict';
- export class SchemaAttributeGroupModel{
- property: SchemaAttribute;
+import {ImagesUrl} from "../../../../utils/constants";
+import {ComponentInstance, CompositionCiNodeBase} from "../../../../models";
+import {ImageCreatorService} from "../../../../directives/graphs-v2/image-creator/image-creator.service";
+export class CompositionCiNodeService extends CompositionCiNodeBase {
- constructor(schemaAttribute?:Models.SchemaAttribute) {
- this.property = schemaAttribute;
- }
+ constructor(instance:ComponentInstance,
+ imageCreator:ImageCreatorService) {
+ super(instance, imageCreator);
+ this.initService();
}
- export class SchemaAttribute extends SchemaProperty{
+ private initService():void {
+
+ this.img = this.imagesPath + ImagesUrl.SERVICE_ICONS + this.componentInstance.icon + '.png';
+ this.classes = 'service-node'
+ if (!this.certified) {
+ this.classes = this.classes + ' not-certified';
+ }
}
}
-
-
diff --git a/catalog-ui/app/scripts/models/graph/nodes/composition-graph-nodes/composition-ci-node-ucpe-cp.ts b/catalog-ui/src/app/models/graph/nodes/composition-graph-nodes/composition-ci-node-ucpe-cp.ts
index 9123ff7224..37882963d3 100644
--- a/catalog-ui/app/scripts/models/graph/nodes/composition-graph-nodes/composition-ci-node-ucpe-cp.ts
+++ b/catalog-ui/src/app/models/graph/nodes/composition-graph-nodes/composition-ci-node-ucpe-cp.ts
@@ -17,23 +17,19 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-/// <reference path="../../../../references"/>
-
-module Sdc.Models.Graph {
-
- export class CompositionCiNodeUcpeCp extends CompositionCiNodeCp {
-
- constructor(instance:Models.ComponentsInstances.ComponentInstance,
- imageCreator: Utils.ImageCreatorService) {
- super(instance, imageCreator);
- this.isUcpePart = true;
- this.classes = 'ucpe-cp'; // the css class for the node
- this.parent = instance.uniqueId;
- this.type = 'ucpe-cp-node'; //the type is for the handle (plus icon) extension
- this.isDraggable = false;
- }
+import {CompositionCiNodeCp, ComponentInstance} from "./../../../../models";
+import {ImageCreatorService} from "../../../../directives/graphs-v2/image-creator/image-creator.service";
+export class CompositionCiNodeUcpeCp extends CompositionCiNodeCp {
+ constructor(instance:ComponentInstance,
+ imageCreator:ImageCreatorService) {
+ super(instance, imageCreator);
+ this.isUcpePart = true;
+ this.classes = 'ucpe-cp'; // the css class for the node
+ this.parent = instance.uniqueId;
+ this.type = 'ucpe-cp-node'; //the type is for the handle (plus icon) extension
+ this.isDraggable = false;
}
}
diff --git a/catalog-ui/app/scripts/view-models/modals/message-modal/message-client-modal/client-message-modal-view-model.ts b/catalog-ui/src/app/models/graph/nodes/composition-graph-nodes/composition-ci-node-ucpe.ts
index 82afe11fe4..d209a10019 100644
--- a/catalog-ui/app/scripts/view-models/modals/message-modal/message-client-modal/client-message-modal-view-model.ts
+++ b/catalog-ui/src/app/models/graph/nodes/composition-graph-nodes/composition-ci-node-ucpe.ts
@@ -17,27 +17,34 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-/// <reference path="../../../../references"/>
-module Sdc.ViewModels {
- 'use strict';
- export interface IClientMessageModalModel extends IMessageModalModel {
+import {ComponentInstance} from "../../../componentsInstances/componentInstance";
+import {ImageCreatorService} from "../../../../directives/graphs-v2/image-creator/image-creator.service";
+import {CompositionCiNodeBase} from "./composition-ci-node-base";
+
+export class NodeUcpe extends CompositionCiNodeBase {
+ constructor(instance:ComponentInstance,
+ imageCreator:ImageCreatorService) {
+ super(instance, imageCreator);
+ this.initUcpe();
}
- export interface IClientMessageModalViewModelScope extends IMessageModalViewModelScope {
- clientMessageModalModel: IClientMessageModalModel;
+ private initUcpe():void {
+ this.isUcpe = true;
+ this.isGroup = true;
+ this.isUcpePart = true;
+ this.classes = 'ucpe-node';
+ this.type = 'ucpe-node';
+ this.allowConnection = false;
+
+ if (!this.certified) {
+ this.classes = this.classes + ' not-certified-ucpe';
+ }
}
- export class ClientMessageModalViewModel extends MessageModalViewModel {
+}
+
- static '$inject' = ['$scope', '$modalInstance', 'clientMessageModalModel'];
- constructor(private $scope:IClientMessageModalViewModelScope,
- private $modalInstance:ng.ui.bootstrap.IModalServiceInstance,
- private clientMessageModalModel:IClientMessageModalModel) {
- super($scope, $modalInstance, clientMessageModalModel);
- }
- }
-}
diff --git a/catalog-ui/app/scripts/models/graph/graph-links/composition-graph-links/composition-ci-link-base.ts b/catalog-ui/src/app/models/graph/nodes/composition-graph-nodes/composition-ci-node-vf.ts
index 3587198615..cb0cd59b13 100644
--- a/catalog-ui/app/scripts/models/graph/graph-links/composition-graph-links/composition-ci-link-base.ts
+++ b/catalog-ui/src/app/models/graph/nodes/composition-graph-nodes/composition-ci-node-vf.ts
@@ -17,30 +17,25 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-/// <reference path="../../../../references"/>
-module Sdc.Models {
+import {CompositionCiNodeBase} from "./composition-ci-node-base";
+import {ComponentInstance} from "../../../componentsInstances/componentInstance";
+import {ImageCreatorService} from "../../../../directives/graphs-v2/image-creator/image-creator.service";
+import {ImagesUrl} from "../../../../utils/constants";
- export interface ICompositionCiLinkBase extends ICommonCiLinkBase{
- updateLinkDirection():void;
- }
-
- export class CompositionCiLinkBase extends CommonCiLinkBase implements ICompositionCiLinkBase {
+export class CompositionCiNodeVf extends CompositionCiNodeBase {
- type:string;
- visible:boolean;
-
- constructor(relation?:RelationshipModel, singleRelationship?:Models.Relationship) {
- super(relation, singleRelationship);
- this.visible = true;
- }
-
- public setRelation = (relation: Models.RelationshipModel) => {
- this.relation = relation;
- };
+ constructor(instance:ComponentInstance,
+ imageCreator:ImageCreatorService) {
+ super(instance, imageCreator);
+ this.initVf();
+ }
- updateLinkDirection():void{
- this.source = this.relation.fromNode;
- this.target = this.relation.toNode;
+ private initVf():void {
+ this.img = this.imagesPath + ImagesUrl.RESOURCE_ICONS + this.componentInstance.icon + '.png';
+ this.classes = 'vf-node';
+ if (!this.certified) {
+ this.classes = this.classes + ' not-certified';
}
}
+
}
diff --git a/catalog-ui/app/scripts/models/additional-information.ts b/catalog-ui/src/app/models/graph/nodes/composition-graph-nodes/composition-ci-node-vfc.ts
index bcac2e5d12..e08e6a4915 100644
--- a/catalog-ui/app/scripts/models/additional-information.ts
+++ b/catalog-ui/src/app/models/graph/nodes/composition-graph-nodes/composition-ci-node-vfc.ts
@@ -17,28 +17,18 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-/// <reference path="../references"/>
-module Sdc.Models {
- 'use strict';
+import {CompositionCiNodeBase} from "./composition-ci-node-base";
+import {ImageCreatorService} from "../../../../directives/graphs-v2/image-creator/image-creator.service";
+import {ComponentInstance} from "../../../componentsInstances/componentInstance";
+import {ImagesUrl} from "../../../../utils/constants";
-
- export interface IAdditionalInformationModel {
- uniqueId: string;
- key: string;
- value: string;
+export class CompositionCiNodeVfc extends CompositionCiNodeBase {
+ constructor(instance:ComponentInstance, imageCreator:ImageCreatorService) {
+ super(instance, imageCreator);
+ this.initVfc();
}
-
- export class AdditionalInformationModel implements IAdditionalInformationModel {
- uniqueId:string;
- key:string;
- value:string;
-
- constructor() {
- this.uniqueId = '';
- this.key = '';
- this.value = '';
-
- }
+ private initVfc():void {
+ this.img = this.imagesPath + ImagesUrl.RESOURCE_ICONS + this.componentInstance.icon + '.png';
}
}
diff --git a/catalog-ui/app/scripts/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 ed9a0d9d87..596d12058f 100644
--- a/catalog-ui/app/scripts/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,22 +17,24 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-/// <reference path="../../../../references"/>
+import {ComponentInstance} from "../../../componentsInstances/componentInstance";
+import {ImageCreatorService} from "../../../../directives/graphs-v2/image-creator/image-creator.service";
+import {CompositionCiNodeBase} from "./composition-ci-node-base";
+import {ImagesUrl} from "../../../../utils/constants";
-module Sdc.Models.Graph {
+export class CompositionCiNodeVl extends CompositionCiNodeBase {
+ private toolTipText:string;
- export class CompositionCiNodeVl extends CompositionCiNodeBase {
- private toolTipText:string;
-
- constructor(instance:Models.ComponentsInstances.ComponentInstance, imageCreator: Utils.ImageCreatorService) {
- super(instance, imageCreator);
- this.initVl();
+ constructor(instance:ComponentInstance, imageCreator:ImageCreatorService) {
+ super(instance, imageCreator);
+ this.initVl();
- }
+ }
- private initVl():void {
- this.type = "basic-small-node";
- this.toolTipText = 'Point to point';
+ private initVl():void {
+ this.type = "basic-small-node";
+ this.toolTipText = 'Point to point';
+ if(this.componentInstance.capabilities) {
let key:string = _.find(Object.keys(this.componentInstance.capabilities), (key)=> {
return _.includes(key.toLowerCase(), 'linkable');
});
@@ -41,14 +43,14 @@ module Sdc.Models.Graph {
if ('UNBOUNDED' == linkable[0].maxOccurrences) {
this.toolTipText = 'Multi point';
}
- }
- this.img = this.imagesPath + Utils.Constants.ImagesUrl.RESOURCE_ICONS + 'vl.png';
- this.classes = 'vl-node';
- if(!this.certified) {
- this.classes = this.classes + ' not-certified';
}
}
+ this.img = this.imagesPath + ImagesUrl.RESOURCE_ICONS + 'vl.png';
+ this.classes = 'vl-node';
+ if (!this.certified) {
+ this.classes = this.classes + ' not-certified';
+ }
}
}
diff --git a/catalog-ui/app/scripts/modules/utils.ts b/catalog-ui/src/app/models/graph/nodes/modules-graph-nodes/module-node-base.ts
index fd5eaf2a4b..51e3591304 100644
--- a/catalog-ui/app/scripts/modules/utils.ts
+++ b/catalog-ui/src/app/models/graph/nodes/modules-graph-nodes/module-node-base.ts
@@ -18,22 +18,34 @@
* ============LICENSE_END=========================================================
*/
/**
- * Created by obarda on 2/11/2016.
+ * Created by obarda on 6/29/2016.
*/
-/// <reference path="../references"/>
-module Sdc {
- let moduleName:string = 'Sdc.Utils';
- let serviceModule:ng.IModule = angular.module(moduleName, []);
+'use strict';
+import {ImagesUrl} from "../../../../utils/constants";
+import {Module} from "../../../modules/base-module";
+import {CommonNodeBase} from "../base-common-node";
+export interface IModuleNodeBase {
+}
+
+export class ModuleNodeBase extends CommonNodeBase implements IModuleNodeBase {
+
+ module:Module;
+ constructor(module:Module) {
+ super();
+ this.module = module;
+ this.init();
+ }
- //Utils
- serviceModule.service('ComponentFactory', Sdc.Utils.ComponentFactory);
- serviceModule.service('ComponentInstanceFactory', Sdc.Utils.ComponentInstanceFactory);
- serviceModule.service('ChangeLifecycleStateHandler', Sdc.Utils.ChangeLifecycleStateHandler);
- serviceModule.service('ModalsHandler', Sdc.Utils.ModalsHandler);
- serviceModule.service('MenuHandler', Sdc.Utils.MenuHandler);
+ private init() {
-
+ this.id = this.module.uniqueId;
+ this.name = this.module.name;
+ this.displayName = this.module.name;
+ this.isGroup = true;
+ this.img = ImagesUrl.MODULE_ICON;
+ this.classes = "module-node";
+ }
}
diff --git a/catalog-ui/src/app/models/graph/nodes/nodes-factory.ts b/catalog-ui/src/app/models/graph/nodes/nodes-factory.ts
new file mode 100644
index 0000000000..6c4f71e722
--- /dev/null
+++ b/catalog-ui/src/app/models/graph/nodes/nodes-factory.ts
@@ -0,0 +1,63 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+'use strict';
+
+import {CompositionCiNodeUcpeCp, Module, ModuleNodeBase, CompositionCiNodeVf, CompositionCiNodeVl, CompositionCiNodeCp,
+ NodeUcpe, CompositionCiNodeService, CompositionCiNodeBase, ComponentInstance} from "./../../../models";
+import {ComponentType, ResourceType} from "../../../utils/constants";
+import {ImageCreatorService} from "../../../directives/graphs-v2/image-creator/image-creator.service";
+
+export class NodesFactory {
+
+ constructor(private imageCreator:ImageCreatorService) {
+ }
+
+ public createNode = (instance:ComponentInstance):CompositionCiNodeBase => {
+
+ if (instance.isUcpe()) {
+ return new NodeUcpe(instance, this.imageCreator);
+ }
+ if (instance.originType === ComponentType.SERVICE) {
+ return new CompositionCiNodeService(instance, this.imageCreator);
+ }
+ if (instance.originType === ResourceType.CP) {
+ return new CompositionCiNodeCp(instance, this.imageCreator);
+ }
+ if (instance.originType === ResourceType.VL) {
+ return new CompositionCiNodeVl(instance, this.imageCreator);
+ }
+
+ return new CompositionCiNodeVf(instance, this.imageCreator);
+ };
+
+ public createModuleNode = (module:Module):ModuleNodeBase => {
+
+ return new ModuleNodeBase(module);
+ };
+
+ public createUcpeCpNode = (instance:ComponentInstance):CompositionCiNodeCp => {
+
+ return new CompositionCiNodeUcpeCp(instance, this.imageCreator);
+ }
+}
+
+NodesFactory.$inject = [
+ 'ImageCreatorService'
+];
diff --git a/catalog-ui/src/app/models/graph/point.ts b/catalog-ui/src/app/models/graph/point.ts
new file mode 100644
index 0000000000..8fece5af99
--- /dev/null
+++ b/catalog-ui/src/app/models/graph/point.ts
@@ -0,0 +1,20 @@
+/**
+ * Created by obarda on 11/7/2016.
+ */
+export class Point {
+ /**
+ * The two-argument constructor produces the Point(x, y).
+ * @param {number} x
+ * @param {number} y
+ */
+ constructor(x?:number, y?:number) {
+ this.x = x || 0;
+ this.y = y || 0;
+ }
+
+ /**Gets or sets the x value of the Point.*/
+ x:number;
+
+ /**Gets or sets the y value of the Point.*/
+ y:number;
+}
diff --git a/catalog-ui/src/app/models/graph/relationMenuObjects.ts b/catalog-ui/src/app/models/graph/relationMenuObjects.ts
new file mode 100644
index 0000000000..aaef0b218c
--- /dev/null
+++ b/catalog-ui/src/app/models/graph/relationMenuObjects.ts
@@ -0,0 +1,131 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+'use strict';
+import {MatchReqToReq, MatchBase} from "./match-relation";
+import {CompositionCiNodeBase} from "./nodes/composition-graph-nodes/composition-ci-node-base";
+import {Component} from "../components/component";
+import {ComponentInstance} from "../componentsInstances/componentInstance";
+
+export class RelationMenuDirectiveObj {
+
+ fromNode:CompositionCiNodeBase;
+ toNode:CompositionCiNodeBase;
+ menuPosition:Cy.Position;
+ rightSideLink:GraphLinkMenuSide;
+ leftSideLink:GraphLinkMenuSide;
+ selectionText:string;
+ vlType:string;
+
+ constructor(fromNode:CompositionCiNodeBase, toNode:CompositionCiNodeBase, menuPosition:Cy.Position, possibleRelations:Array<MatchBase>) {
+ this.fromNode = fromNode;
+ this.toNode = toNode;
+ // this.modelLinks = modelLinks;
+ this.menuPosition = menuPosition;
+ this.leftSideLink = new GraphLinkMenuSide(this.fromNode.componentInstance);
+ this.rightSideLink = new GraphLinkMenuSide(this.toNode.componentInstance);
+ this.selectionText = '';
+ this.vlType = null;
+
+ possibleRelations.forEach((match:any) => {
+
+ let reqObjKey:string = match.requirement.ownerName + match.requirement.uniqueId;
+ let capObjKey:string = match.secondRequirement ? match.secondRequirement.ownerName + match.secondRequirement.uniqueId
+ : match.capability.ownerName + match.capability.uniqueId;
+
+ if (match.fromNode === this.leftSideLink.componentInstance.uniqueId) {
+ //init the left side requirements Array
+ if (!this.leftSideLink.requirements[reqObjKey]) {
+ this.leftSideLink.requirements[reqObjKey] = [];
+ }
+ //push the match to fromNode object (from node is always the requirement)
+ this.leftSideLink.requirements[reqObjKey].push(match);
+
+ if (match instanceof MatchReqToReq) {
+ //init the right side requirements Array
+ if (!this.rightSideLink.requirements[capObjKey]) {
+ this.rightSideLink.requirements[capObjKey] = [];
+ }
+ this.rightSideLink.requirements[capObjKey].push(match);
+ } else {
+ //init the right side capabilities Array
+ if (!this.rightSideLink.capabilities[capObjKey]) {
+ this.rightSideLink.capabilities[capObjKey] = [];
+ }
+ //add to array
+ this.rightSideLink.capabilities[capObjKey].push(match);
+ }
+
+ } else {
+ if (!this.rightSideLink.requirements[reqObjKey]) {
+ this.rightSideLink.requirements[reqObjKey] = [];
+ }
+ this.rightSideLink.requirements[reqObjKey].push(match);
+
+ if (!this.leftSideLink.capabilities[capObjKey]) {
+ this.leftSideLink.capabilities[capObjKey] = [];
+ }
+ this.leftSideLink.capabilities[capObjKey].push(match);
+ }
+ });
+
+ }
+}
+
+export class GraphLinkMenuSide {
+ public componentInstance:ComponentInstance;
+ public selectedMatch:Array<any>; //match array returned by function in utils
+ public requirements:any; //array of matches returned by function in utils
+ public capabilities:any; //array of matches returned by function in utils
+
+ constructor(componentInstance:ComponentInstance) {
+ this.componentInstance = componentInstance;
+ this.capabilities = {};
+ this.requirements = {};
+ }
+
+ public selectMatchArr(matchArr:Array<MatchBase>):void {
+ if (this.selectedMatch === matchArr) {
+ this.selectedMatch = undefined;
+ } else {
+ this.selectedMatch = matchArr;
+ }
+ }
+
+
+ //TODO move to match object
+ public getPreviewText(showReq:boolean):string {
+ if (!this.selectedMatch) {
+ return '';
+ }
+
+ let match:any = this.selectedMatch[0];
+ if (showReq) {
+ return match.requirement.ownerName + ': ' + match.requirement.name +
+ ': [' + match.requirement.minOccurrences + ', ' + match.requirement.maxOccurrences + ']';
+ } else if (match.secondRequirement) {
+ return match.secondRequirement.ownerName + ': ' + match.secondRequirement.name +
+ ': [' + match.secondRequirement.minOccurrences + ', ' + match.secondRequirement.maxOccurrences + ']';
+ }
+ else {
+ return match.capability.ownerName + ': ' + match.capability.name +
+ ': [' + match.capability.minOccurrences + ', ' + match.capability.maxOccurrences + ']';
+ }
+ }
+}
diff --git a/catalog-ui/src/app/models/graph/relationship.ts b/catalog-ui/src/app/models/graph/relationship.ts
new file mode 100644
index 0000000000..6345ab4c04
--- /dev/null
+++ b/catalog-ui/src/app/models/graph/relationship.ts
@@ -0,0 +1,95 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+'use strict';
+import {Capability} from "../capability";
+import {Requirement} from "../requirement";
+
+export class RelationshipModel {
+ fromNode:string;
+ toNode:string;
+ relationships:Array<Relationship>;
+
+ constructor(relationshipModel?:RelationshipModel, singleRelationship?:Relationship) {
+ if (relationshipModel) {
+ this.fromNode = relationshipModel.fromNode;
+ this.toNode = relationshipModel.toNode;
+ this.relationships = [];
+ if (relationshipModel.relationships && !singleRelationship) {
+ _.forEach(relationshipModel.relationships, (relation:Relationship):void => {
+ this.relationships.push(new Relationship(relation));
+ });
+ } else if (singleRelationship) {
+ this.relationships.push(singleRelationship);
+ }
+ }
+ }
+
+ public setRelationshipModelParams(fromNode:string, toNode:string, relationships:Array<Relationship>) {
+ this.fromNode = fromNode;
+ this.toNode = toNode;
+ this.relationships = relationships;
+ }
+}
+
+export class RelationType {
+ type:string;
+
+ constructor(type?:string) {
+ if (type) {
+ this.type = type;
+ }
+ }
+}
+
+export class Relationship {
+ capability:string;
+ capabilityOwnerId:string;
+ capabilityUid:string;
+ relationship:RelationType;
+ requirement:string;
+ requirementOwnerId:string;
+ requirementUid:string;
+
+ constructor(relationship?:Relationship) {
+ if (relationship) {
+ this.capability = relationship.capability;
+ this.capabilityOwnerId = relationship.capabilityOwnerId;
+ this.capabilityUid = relationship.capabilityUid;
+ this.relationship = new RelationType(relationship.relationship.type);
+ this.requirement = relationship.requirement;
+ this.requirementOwnerId = relationship.requirementOwnerId;
+ this.requirementUid = relationship.requirementUid;
+ } else {
+ this.relationship = new RelationType();
+ }
+
+ }
+
+ public setRelationProperties = (capability:Capability, requirement:Requirement)=> {
+ this.capability = capability.name;
+ this.capabilityOwnerId = capability.ownerId;
+ this.capabilityUid = capability.uniqueId;
+ this.relationship = new RelationType(capability.type);
+ this.requirement = requirement.name;
+ this.requirementOwnerId = requirement.ownerId;
+ this.requirementUid = requirement.uniqueId;
+ };
+
+}
diff --git a/catalog-ui/src/app/models/heat-parameters.ts b/catalog-ui/src/app/models/heat-parameters.ts
new file mode 100644
index 0000000000..be5ad92fb0
--- /dev/null
+++ b/catalog-ui/src/app/models/heat-parameters.ts
@@ -0,0 +1,18 @@
+/**
+ * Created by rcohen on 10/31/2016.
+ */
+'use strict';
+
+export class HeatParameterModel {
+ uniqueId:string;
+ name:string;
+ type:string;
+ description:string;
+ currentValue:string;
+ defaultValue:string;
+
+ constructor(parameter?:HeatParameterModel) {
+ }
+
+}
+
diff --git a/catalog-ui/src/app/models/input-property-base.ts b/catalog-ui/src/app/models/input-property-base.ts
new file mode 100644
index 0000000000..dce76d597e
--- /dev/null
+++ b/catalog-ui/src/app/models/input-property-base.ts
@@ -0,0 +1,26 @@
+/**
+ * Created by obarda on 1/22/2017.
+ */
+'use strict';
+import {SchemaPropertyGroupModel} from "./aschema-property";
+
+export interface InputPropertyBase {
+
+ uniqueId:string;
+ name:string;
+ defaultValue:string;
+ description:string;
+ password:boolean;
+ required:boolean;
+ type:string;
+ parentUniqueId:string;
+ schema:SchemaPropertyGroupModel;
+ componentInstanceId:string;
+
+ //instance properties
+ value:string;
+
+ //custom properties
+ isAlreadySelected:boolean;
+}
+
diff --git a/catalog-ui/src/app/models/inputs-and-properties.ts b/catalog-ui/src/app/models/inputs-and-properties.ts
new file mode 100644
index 0000000000..18ff928918
--- /dev/null
+++ b/catalog-ui/src/app/models/inputs-and-properties.ts
@@ -0,0 +1,22 @@
+/**
+ * Created by obarda on 1/11/2017.
+ */
+'use strict';
+import {PropertyModel} from "./properties";
+import {InputModel} from "./inputs";
+
+export class InputsAndProperties {
+
+ inputs:Array<InputModel>;
+ properties:Array<PropertyModel>;
+
+
+ constructor(inputs?:Array<InputModel>, properties?:Array<PropertyModel>) {
+ if (inputs && inputs.length > 0) {
+ this.inputs = inputs;
+ }
+ if (properties && properties.length > 0) {
+ this.properties = properties;
+ }
+ }
+}
diff --git a/catalog-ui/src/app/models/inputs.ts b/catalog-ui/src/app/models/inputs.ts
new file mode 100644
index 0000000000..55e739b452
--- /dev/null
+++ b/catalog-ui/src/app/models/inputs.ts
@@ -0,0 +1,80 @@
+/**
+ * Created by obarda on 8/24/2016.
+ */
+'use strict';
+import {PropertyModel} from "./properties";
+import {InputPropertyBase} from "./input-property-base";
+import {SchemaPropertyGroupModel} from "./aschema-property";
+
+export interface IInputModel extends InputPropertyBase {
+ //server data
+ definition:boolean;
+ value:string;
+ componentInstanceName:string;
+ //costom properties
+ isNew:boolean;
+ properties:Array<PropertyModel>;
+ inputs:Array<InputModel>;
+ filterTerm:string;
+
+}
+export class InputModel implements IInputModel {
+
+ //server data
+ uniqueId:string;
+ name:string;
+ type:string;
+ password:boolean;
+ required:boolean;
+ definition:boolean;
+ parentUniqueId:string;
+ description:string;
+ componentInstanceName:string;
+ componentInstanceId:string;
+ schema:SchemaPropertyGroupModel;
+ defaultValue:string;
+ value:string;
+
+ //costom properties
+ isNew:boolean;
+ isDeleteDisabled:boolean;
+ properties:Array<PropertyModel>;
+ inputs:Array<InputModel>;
+ isAlreadySelected:boolean;
+ filterTerm:string;
+
+ constructor(input:InputModel) {
+
+ if (input) {
+ this.uniqueId = input.uniqueId;
+ this.name = input.name;
+ this.type = input.type;
+ this.description = input.description;
+ this.password = input.password;
+ this.required = input.required;
+ this.definition = input.definition;
+ this.parentUniqueId = input.parentUniqueId;
+ this.description = input.description;
+ this.componentInstanceName = input.componentInstanceName;
+ this.componentInstanceId = input.componentInstanceId;
+ this.schema = input.schema;
+ this.defaultValue = input.defaultValue;
+ this.value = input.value;
+ this.filterTerm = this.name + ' ' + this.description + ' ' + this.type + ' ' + this.componentInstanceName;
+ this.inputs = input.inputs;
+ this.properties = input.properties;
+ }
+ }
+
+ public toJSON = ():any => {
+ let input = angular.copy(this);
+ input.isNew = undefined;
+ input.isDeleteDisabled = undefined;
+ input.properties = undefined;
+ input.inputs = undefined;
+ input.isAlreadySelected = undefined;
+ input.filterTerm = undefined;
+ return input;
+ };
+}
+
diff --git a/catalog-ui/src/app/models/instance-inputs-properties-map.ts b/catalog-ui/src/app/models/instance-inputs-properties-map.ts
new file mode 100644
index 0000000000..47b99dfffd
--- /dev/null
+++ b/catalog-ui/src/app/models/instance-inputs-properties-map.ts
@@ -0,0 +1,67 @@
+/**
+ * Created by obarda on 9/12/2016.
+ */
+'use strict';
+import {InputPropertyBase} from "./input-property-base";
+import {PropertyModel} from "./properties";
+import {InputModel} from "./inputs";
+
+export class InstancesInputsOrPropertiesMapData {
+ [instanceId:string]:Array<InputPropertyBase>;
+}
+
+export class InstancesInputsPropertiesMap {
+ componentInstanceProperties:InstancesInputsOrPropertiesMapData;
+ componentInstanceInputsMap:InstancesInputsOrPropertiesMapData;
+
+ constructor(componentInstanceInputsMapData:InstancesInputsOrPropertiesMapData, componentInstanceInputsPropertiesMapData:InstancesInputsOrPropertiesMapData) {
+ this.componentInstanceInputsMap = componentInstanceInputsMapData;
+ this.componentInstanceProperties = componentInstanceInputsPropertiesMapData;
+ }
+
+ private removeUnnecessaryData = (properties:Array<InputPropertyBase>, instanceId:string, mapData:any) => {
+ mapData[instanceId] = [];
+ if (properties && properties.length > 0) {
+ _.forEach(properties, (propertyOrInput:InputPropertyBase) => {
+ if (propertyOrInput instanceof PropertyModel) { // Handle Properties
+ if (propertyOrInput && !propertyOrInput.isAlreadySelected) {
+ mapData[instanceId].push(propertyOrInput);
+ }
+ }
+ if (propertyOrInput instanceof InputModel) { // Handle Inputs
+ if (propertyOrInput && !propertyOrInput.isAlreadySelected) {
+ mapData[instanceId].push(propertyOrInput);
+ }
+ }
+ });
+ if (mapData[instanceId].length === 0) {
+ delete mapData[instanceId];
+ }
+ } else {
+ delete mapData[instanceId];
+ }
+ }
+
+ /*
+ In the toJson we remove all inputs and property already selected (The check box selected but they are disable)
+ also we remove empty array in order to prevent Backend error
+ */
+
+ public cleanUnnecessaryDataBeforeSending = ():InstancesInputsPropertiesMap => {
+
+ let map:InstancesInputsPropertiesMap = new InstancesInputsPropertiesMap(new InstancesInputsOrPropertiesMapData(), new InstancesInputsOrPropertiesMapData());
+ angular.copy(this, map);
+
+ //Removing unnecessary data from inputs map
+ _.forEach(map.componentInstanceInputsMap, (inputs:Array<InputModel>, instanceId:string) => {
+ this.removeUnnecessaryData(inputs, instanceId, map.componentInstanceInputsMap);
+ });
+
+ //Removing unnecessary data from properties map
+ _.forEach(map.componentInstanceProperties, (properties:Array<PropertyModel>, instanceId:string) => {
+ this.removeUnnecessaryData(properties, instanceId, map.componentInstanceProperties);
+ });
+
+ return map;
+ };
+}
diff --git a/catalog-ui/src/app/models/left-panel.ts b/catalog-ui/src/app/models/left-panel.ts
new file mode 100644
index 0000000000..759d5f317e
--- /dev/null
+++ b/catalog-ui/src/app/models/left-panel.ts
@@ -0,0 +1,11 @@
+'use strict';
+
+export class LeftPanelModel {
+ numberOfElements:number;
+ sortedCategories:any;
+
+ constructor() {
+ this.numberOfElements = 0;
+ this.sortedCategories = {};
+ }
+}
diff --git a/catalog-ui/src/app/models/member.ts b/catalog-ui/src/app/models/member.ts
new file mode 100644
index 0000000000..a2d9d17aec
--- /dev/null
+++ b/catalog-ui/src/app/models/member.ts
@@ -0,0 +1,16 @@
+/**
+ * Created by obarda on 8/2/2016.
+ */
+'use strict';
+
+export class Members {
+
+ [index:string]:string;
+
+ constructor(members?:Members) {
+ _.forEach(members, (memberId:string, index) => {
+ this[index] = memberId;
+ });
+ }
+}
+
diff --git a/catalog-ui/src/app/models/modules/base-module.ts b/catalog-ui/src/app/models/modules/base-module.ts
new file mode 100644
index 0000000000..4a5f282468
--- /dev/null
+++ b/catalog-ui/src/app/models/modules/base-module.ts
@@ -0,0 +1,95 @@
+/**
+ * Created by obarda on 6/30/2016.
+ */
+/**
+ * Created by obarda on 2/4/2016.
+ */
+'use strict';
+import {PropertyModel} from "../properties";
+import {ArtifactModel} from "../artifacts";
+import {CommonUtils} from "../../utils/common-utils";
+export class Module {
+
+ public name:string;
+ public groupUUID:string;
+ public invariantUUID:string;
+ public propertyValueCounter:number;
+ public type:string;
+ public typeUid:string;
+ public uniqueId:string;
+ public version:string;
+ public artifacts:Array<string> | Array<ArtifactModel>;
+ public artifactsUuid:Array<string>;
+ public properties:Array<PropertyModel>;
+ public members:Array<string>;
+ public customizationUUID:string;
+ public groupInstanceUniqueId:string; // This will only have a value if this is a group instance
+
+ constructor(module?:Module) {
+ if (module) {
+ this.name = module.name;
+ this.groupUUID = module.groupUUID;
+ this.invariantUUID = module.invariantUUID;
+ this.propertyValueCounter = module.propertyValueCounter;
+ this.type = module.type;
+ this.typeUid = module.typeUid;
+ this.uniqueId = module.uniqueId;
+ this.version = module.version;
+ this.artifacts = module.artifacts;
+ this.artifactsUuid = module.artifactsUuid;
+ this.properties = CommonUtils.initProperties(module.properties);
+ this.members = module.members;
+ this.customizationUUID = module.customizationUUID;
+ this.groupInstanceUniqueId = module.groupInstanceUniqueId;
+ this.name = this.name.replace(/:/g, '..');
+
+ }
+ }
+}
+
+export class DisplayModule extends Module {
+
+ isBase:string;
+ artifacts:Array<ArtifactModel>;
+
+ //custom properties
+ public vfInstanceName:string;
+ public heatName:string;
+ public moduleName:string;
+ public customizationUUID:string;
+
+
+ constructor(displayModule?:DisplayModule) {
+ super(displayModule);
+
+ this.isBase = displayModule.isBase;
+ this.customizationUUID = displayModule.customizationUUID;
+ this.initArtifactsForDisplay(displayModule.artifacts);
+
+ //splitting module name for display and edit
+ let splitName:Array<string> = this.name.split('..');
+ this.vfInstanceName = splitName[0];
+ this.heatName = splitName[1];
+ this.moduleName = splitName[2];
+ }
+
+ private initArtifactsForDisplay = (artifacts:Array<ArtifactModel>):void => {
+ this.artifacts = new Array<ArtifactModel>();
+ _.forEach(artifacts, (artifact:ArtifactModel) => {
+ this.artifacts.push(new ArtifactModel(artifact));
+ });
+ };
+
+ public updateName = ():void => {
+ this.name = this.vfInstanceName + '..' + this.heatName + '..' + this.moduleName;
+ };
+
+ public toJSON = ():any => {
+ this.vfInstanceName = undefined;
+ this.heatName = undefined;
+ this.moduleName = undefined;
+ this.isBase = undefined;
+ this.artifacts = undefined;
+ return this;
+ };
+}
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
new file mode 100644
index 0000000000..1d79353453
--- /dev/null
+++ b/catalog-ui/src/app/models/properties-inputs/derived-fe-property.ts
@@ -0,0 +1,72 @@
+import { SchemaPropertyGroupModel, SchemaProperty } from '../aschema-property';
+import { PROPERTY_DATA, PROPERTY_TYPES} from 'app/utils';
+import { PropertyBEModel } from '../../models';
+
+export enum DerivedPropertyType {
+ SIMPLE,
+ LIST,
+ MAP,
+ COMPLEX //other datatype, list of non-simple, or map of non-simple
+}
+
+export class DerivedFEProperty extends PropertyBEModel {
+ parentName: string;
+ propertiesName: string; //"network_assignments#ipv4_subnet#use_ipv4 = parentPath + name
+ derivedDataType: DerivedPropertyType;
+ isDeclared: boolean;
+ isSelected: boolean;
+ isDisabled: boolean;
+ isChildOfListOrMap: boolean;
+
+ constructor(property: PropertyBEModel, parentName?: string)
+ constructor(name: string, parentName: string, type: string, value: string, isChildOfListOrMap?:boolean, schema?: SchemaPropertyGroupModel);
+ constructor(nameOrPropertyObj?: string | PropertyBEModel, parentName?: string, type?: string, value?: string, isChildOfListOrMap?: boolean, schema?: SchemaPropertyGroupModel) {
+
+ super(typeof nameOrPropertyObj === 'string' ? null : nameOrPropertyObj);
+
+ if (typeof nameOrPropertyObj !== 'string') { //constructor #1
+ this.parentName = parentName ? parentName : null;
+ this.propertiesName = (parentName) ? parentName + '#' + nameOrPropertyObj.name : nameOrPropertyObj.name;
+ } else { //constructor #2
+ this.name = nameOrPropertyObj;
+ this.type = type;
+ this.parentName = parentName;
+ this.propertiesName = parentName + '#' + nameOrPropertyObj;
+ this.value = value;
+ if (schema) {
+ this.schema = new SchemaPropertyGroupModel(new SchemaProperty(schema.property));
+ }
+ }
+ this.derivedDataType = this.getDerivedPropertyType();
+ this.isChildOfListOrMap = (isChildOfListOrMap) ? isChildOfListOrMap : false;
+ }
+
+ public getDerivedPropertyType = () => {
+ if (PROPERTY_DATA.SIMPLE_TYPES.indexOf(this.type) > -1) {
+ return DerivedPropertyType.SIMPLE;
+ } else if (this.type == PROPERTY_TYPES.LIST) {
+ return DerivedPropertyType.LIST;
+ } else if (this.type == PROPERTY_TYPES.MAP) {
+ return DerivedPropertyType.MAP;
+ } else {
+ return DerivedPropertyType.COMPLEX;
+ }
+ }
+
+}
+export class DerivedFEPropertyMap {
+ [parentPath: string]: Array<DerivedFEProperty>;
+}
+
+
+
+// isDataType: boolean;
+
+
+// canAdd: boolean;
+// canCollapse: boolean;
+// canBeDeclared: boolean;
+
+// derivedValue: string;
+// derivedValueType: string;
+// propertiesName: string; \ No newline at end of file
diff --git a/catalog-ui/src/app/models/properties-inputs/input-fe-model.ts b/catalog-ui/src/app/models/properties-inputs/input-fe-model.ts
new file mode 100644
index 0000000000..1261df3d6d
--- /dev/null
+++ b/catalog-ui/src/app/models/properties-inputs/input-fe-model.ts
@@ -0,0 +1,32 @@
+import { SchemaPropertyGroupModel, SchemaProperty } from "../aschema-property";
+import { PropertyBEModel } from "../../models";
+import {PROPERTY_DATA} from "../../utils/constants";
+
+export class InputFEModel extends PropertyBEModel {
+ isSimpleType: boolean;
+ isDataType: boolean;
+ instanceName: string;
+ propertyName: string;
+
+
+ constructor(input?: PropertyBEModel) {
+ super(input);
+ if (input) {
+ this.isSimpleType = PROPERTY_DATA.SIMPLE_TYPES.indexOf(this.type) > -1;
+ this.isDataType = PROPERTY_DATA.TYPES.indexOf(this.type) == -1;
+ let propNameIndex:number = this.name.indexOf('_');
+ this.instanceName = this.name.substring(0, propNameIndex);
+ if (input.inputPath) {
+ this.propertyName = input.inputPath.substring(0, input.inputPath.indexOf('#'))
+ } else {
+ this.propertyName = this.name.substring(propNameIndex + 1);
+ }
+ }
+ }
+
+
+
+ public toJSON = (): any => {
+ };
+
+}
diff --git a/catalog-ui/src/app/models/properties-inputs/property-be-model.ts b/catalog-ui/src/app/models/properties-inputs/property-be-model.ts
new file mode 100644
index 0000000000..a5279d0668
--- /dev/null
+++ b/catalog-ui/src/app/models/properties-inputs/property-be-model.ts
@@ -0,0 +1,84 @@
+import { SchemaPropertyGroupModel, SchemaProperty } from "../aschema-property";
+
+export class PropertyBEModel {
+
+ defaultValue: string;
+ description: string;
+ fromDerived: boolean;
+ name: string;
+ parentUniqueId: string;
+ password: boolean;
+ required: boolean;
+ schema: SchemaPropertyGroupModel;
+ type: string;
+ uniqueId: string;
+ value: string;
+ definition: boolean;
+ inputPath: string;
+ propertiesName: string;
+ input: PropertyBEModel;
+
+ constructor(property?: PropertyBEModel, childProperty?:PropertyBEModel) {
+ if (property) {
+ this.defaultValue = property.defaultValue;
+ this.description = property.description;
+ this.fromDerived = property.fromDerived;
+ this.name = property.name;
+ this.parentUniqueId = property.parentUniqueId;
+ this.password = property.password;
+ this.required = property.required;
+ this.schema = property.schema;
+ this.type = property.type;
+ this.uniqueId = property.uniqueId;
+ this.value = property.value ? property.value : property.defaultValue;
+ this.definition = property.definition;
+ if (property.inputPath) {
+ this.inputPath = property.inputPath;
+ }
+ }
+ if (childProperty) {
+ this.input = childProperty;
+ this.propertiesName = childProperty.propertiesName;
+ }
+
+ if (!this.schema || !this.schema.property) {
+ this.schema = new SchemaPropertyGroupModel(new SchemaProperty());
+ } else { //forcing creating new object, so editing different one than the object in the table
+ this.schema = new SchemaPropertyGroupModel(new SchemaProperty(this.schema.property));
+ }
+ }
+
+
+
+ public toJSON = (): any => {
+ let temp = angular.copy(this);
+ temp.value = temp.value === "{}" || temp.value === "[]" ? undefined : temp.value;
+ temp.defaultValue = temp.defaultValue === "{}" || temp.defaultValue === "[]" ? undefined : temp.defaultValue;
+ return temp;
+ };
+
+}
+
+
+// EXTRAS FROM CONSTRUCTOR:
+// this.source = property.source;
+// this.valueUniqueUid = property.valueUniqueUid;
+// this.path = property.path;
+// this.rules = property.rules;
+// this.resourceInstanceUniqueId = property.resourceInstanceUniqueId;
+// this.readonly = property.readonly;
+// this.simpleType = property.simpleType;
+// this.componentInstanceId = property.componentInstanceId;
+// this.parentValue = property.parentValue;
+//NEW PROPERTIES MAY NEED:
+// export class PropertyFEModel extends PropertyBEModel {
+// componentInstanceId: string;
+// isAlreadySelected: boolean;
+// filterTerm: string;
+// }
+//FOR INPUTS, BE ALSO INCLUDES:
+//export class InputFEModel extends PropertyBEModel {
+// hidden: boolean;
+// label: string;
+// immutable: boolean;
+// }
diff --git a/catalog-ui/src/app/models/properties-inputs/property-fe-map.ts b/catalog-ui/src/app/models/properties-inputs/property-fe-map.ts
new file mode 100644
index 0000000000..3b267460b1
--- /dev/null
+++ b/catalog-ui/src/app/models/properties-inputs/property-fe-map.ts
@@ -0,0 +1,21 @@
+'use strict';
+import { PropertyBEModel, PropertyFEModel } from "../../models";
+
+export class InstanceBePropertiesMap {
+ [instanceId: string]: Array<PropertyBEModel>;
+}
+
+export class InstanceFePropertiesMap {
+ [instanceId: string]: Array<PropertyFEModel>;
+}
+
+export class InstancePropertiesAPIMap {
+ componentInstanceProperties: InstanceBePropertiesMap;
+ componentInstanceInputsMap: InstanceBePropertiesMap;
+
+ constructor(inputsMapData: InstanceBePropertiesMap, propertiesMapData: InstanceBePropertiesMap) {
+ this.componentInstanceInputsMap = inputsMapData ? inputsMapData: new InstanceBePropertiesMap();
+ this.componentInstanceProperties = propertiesMapData ? propertiesMapData: new InstanceBePropertiesMap();
+ }
+
+}
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
new file mode 100644
index 0000000000..29f2c79225
--- /dev/null
+++ b/catalog-ui/src/app/models/properties-inputs/property-fe-model.ts
@@ -0,0 +1,132 @@
+import {SchemaPropertyGroupModel, SchemaProperty} from '../aschema-property';
+import { PROPERTY_DATA } from 'app/utils';
+import { PropertyBEModel, DerivedFEPropertyMap, DerivedFEProperty } from '../../models';
+
+
+export class PropertyFEModel extends PropertyBEModel {
+
+ //START - TO REMOVE:
+ treeNodeId: string;
+ parent: PropertyFEModel;
+
+ childrenProperties: Array<PropertyFEModel>;
+ isAllChildrenLevelsCalculated: boolean;
+ uniqueId: string;
+ valueObjectRef: any;
+ //END - TO REMOVE:
+
+ expandedChildPropertyId: string;
+ flattenedChildren: Array<DerivedFEProperty>; //[parentPath] : Array<DerivedFEProp>
+ isDataType: boolean; //aka- isComplexType. (Type is NOT: simple, list, or map)
+ isDeclared: boolean;
+ isDisabled: boolean;
+ isSelected: boolean;
+ isSimpleType: boolean;
+
+ private _derivedFromSimpleTypeName:string;
+ get derivedFromSimpleTypeName():string {
+ return this._derivedFromSimpleTypeName;
+ }
+ set derivedFromSimpleTypeName(derivedFromSimpleTypeName:string) {
+ this._derivedFromSimpleTypeName = derivedFromSimpleTypeName;
+ }
+
+ constructor(property?: PropertyBEModel);
+ constructor(name: string, type: string, treeNodeId: string, parent: PropertyFEModel, valueObjectRef: any, schema?: SchemaPropertyGroupModel);
+ constructor(nameOrPropertyObj?: string | PropertyBEModel, type?: string, treeNodeId?: string, parent?: PropertyFEModel, valueObjectRef?: any, schema?: SchemaPropertyGroupModel) {
+
+ super(typeof nameOrPropertyObj === 'string' ? null : nameOrPropertyObj);
+
+ if (typeof nameOrPropertyObj === 'string') {
+ this.name = nameOrPropertyObj;
+ this.type = type;
+ this.treeNodeId = treeNodeId;
+ this.parent = parent;
+ this.valueObjectRef = valueObjectRef;
+ this.value = this.value || this.defaultValue;
+ if(schema){
+ this.schema = new SchemaPropertyGroupModel(new SchemaProperty(schema.property));
+ }
+ }
+
+ this.isSimpleType = PROPERTY_DATA.SIMPLE_TYPES.indexOf(this.type) > -1;
+ this.isDataType = PROPERTY_DATA.TYPES.indexOf(this.type) == -1;
+ this.setNonDeclared();
+ }
+
+ public convertChildToInput = (childName: string): void => {
+ //childName: "mac_count_required"
+ let childJson = this.flattenedChildren[childName].map((child) => {
+
+ });
+ };
+
+ public getChildJsonRecursive = (child: string, value?: string): void => {
+ //TODO: use array.map for the below
+ /* value += "{" + this.flattenedChildren[child].name + ":";
+ if (this.flattenedChildren[child].valueType == 'simple') {
+ value += this.flattenedChildren[child].value + '}';
+ return value;
+ } else {
+ this.flattenedChildren[child].forEach(grandChild => {
+ if (this.flattenedChildren[grandChild].valueType == 'simple') {
+ return "{" + this.flattenedChildren[grandChild].name + ':' + this.flattenedChildren[child].value.toString() + "}";
+ } else {
+ return this.getChildJsonRecursive(grandChild + '#' + this.flattenedChildren[child].name);
+ }
+ });
+ }
+
+ return "{" + this.flattenedChildren[child].name + this.flattenedChildren[child].value.toString() + "}";
+*/
+
+ };
+
+ public setNonDeclared = (childPath?: string): void => {
+ if (!childPath) { //declaring a child prop
+ this.isDeclared = false;
+ } else {
+ let childProp: DerivedFEProperty = this.flattenedChildren.find(child => child.propertiesName == childPath);
+ childProp.isDeclared = false;
+ }
+ }
+
+ public setAsDeclared = (childNameToDeclare?:string): void => {
+ if (!childNameToDeclare) { //declaring a child prop
+ this.isSelected = false;
+ this.isDeclared = true;
+ } else {
+ let childProp: DerivedFEProperty = this.flattenedChildren.find(child => child.propertiesName == childNameToDeclare);
+ childProp.isSelected = false;
+ childProp.isDeclared = true;
+ }
+ }
+
+
+
+ //For expand-collapse functionality
+ public updateExpandedChildPropertyId = (childPropertyId: string): void => {
+ if (childPropertyId.lastIndexOf('#') > -1) {
+ this.expandedChildPropertyId = (this.expandedChildPropertyId == childPropertyId) ? (childPropertyId.substring(0, childPropertyId.lastIndexOf('#'))) : childPropertyId;
+ } else {
+ this.expandedChildPropertyId = this.name;
+ }
+ //console.log("expandedChild is now " + this.expandedChildPropertyId);
+ }
+
+ public convertToServerObject: Function = (): any => { //TODO: Idan, Rachel, Nechama: Decide what we need to do here
+ // let serverObject = {};
+ // let mapData = {
+ // 'type': this.type,
+ // 'required': this.required || false,
+ // 'defaultValue': this.defaultValue != '' && this.defaultValue != '[]' && this.defaultValue != '{}' ? this.defaultValue : null,
+ // 'description': this.description,
+ // 'isPassword': this.password || false,
+ // 'schema': this.schema,
+ // 'name': this.name
+ // };
+ // serverObject[this.name] = mapData;
+
+ //return JSON.stringify(serverObject);
+ };
+}
diff --git a/catalog-ui/src/app/models/properties.ts b/catalog-ui/src/app/models/properties.ts
new file mode 100644
index 0000000000..357dac2e7d
--- /dev/null
+++ b/catalog-ui/src/app/models/properties.ts
@@ -0,0 +1,141 @@
+'use strict';
+import {SchemaPropertyGroupModel, SchemaProperty} from "./aschema-property";
+import {InputPropertyBase} from "./input-property-base";
+
+export class PropertiesGroup {
+ constructor(propertiesObj?:PropertiesGroup) {
+ _.forEach(propertiesObj, (properties:Array<PropertyModel>, instance) => {
+ this[instance] = [];
+ _.forEach(properties, (property:PropertyModel):void => {
+ property.resourceInstanceUniqueId = instance;
+ property.readonly = true;
+ this[instance].push(new PropertyModel(property));
+ });
+ });
+ }
+}
+
+export interface IPropertyModel extends InputPropertyBase {
+
+ //server data
+ constraints:Array<Object>;
+ source:string;
+
+ //instance properties
+ valueUniqueUid:string;
+ path:Array<string>;
+ rules:Array<Object>;
+ propertiesName:string;
+ input:any;
+
+ //custom properties
+ resourceInstanceUniqueId:string;
+ readonly:boolean;
+ simpleType:string;
+}
+
+export class PropertyModel implements IPropertyModel {
+
+ //server data
+ uniqueId:string;
+ name:string;
+ constraints:Array<Object>;
+ defaultValue:string;
+ description:string;
+ password:boolean;
+ required:boolean;
+ type:string;
+ source:string;
+ parentUniqueId:string;
+ schema:SchemaPropertyGroupModel;
+ componentInstanceId:string;
+ parentValue:string;
+
+ //instance properties
+ value:string;
+ valueUniqueUid:string;
+ path:Array<string>;
+ rules:Array<Object>;
+ propertiesName:string;
+ input:any;
+
+ //custom properties
+ resourceInstanceUniqueId:string;
+ readonly:boolean;
+ simpleType:string;
+ filterTerm:string;
+ isAlreadySelected:boolean;
+ addOn:string;
+
+
+ constructor(property?:PropertyModel) {
+ if (property) {
+ this.uniqueId = property.uniqueId;
+ this.name = property.name;
+ this.constraints = property.constraints;
+ this.defaultValue = property.defaultValue;
+ this.description = property.description;
+ this.password = property.password;
+ this.required = property.required;
+ this.type = property.type;
+ this.source = property.source;
+ this.parentUniqueId = property.parentUniqueId;
+ this.schema = property.schema;
+ this.value = property.value ? property.value : property.defaultValue;
+ this.valueUniqueUid = property.valueUniqueUid;
+ this.path = property.path;
+ this.rules = property.rules;
+ this.resourceInstanceUniqueId = property.resourceInstanceUniqueId;
+ this.readonly = property.readonly;
+ this.simpleType = property.simpleType;
+ this.componentInstanceId = property.componentInstanceId;
+ this.parentValue = property.parentValue;
+ }
+
+ if (!this.schema || !this.schema.property) {
+ this.schema = new SchemaPropertyGroupModel(new SchemaProperty());
+ } else {
+ //forcing creating new object, so editing different one than the object in the table
+ this.schema = new SchemaPropertyGroupModel(new SchemaProperty(this.schema.property));
+ }
+ if (property && property.uniqueId) {
+ this.filterTerm = this.name + " " + (this.description || "") + " " + this.type.replace("org.openecomp.datatypes.heat.", "");
+ if (this.schema.property && this.schema.property.type) {
+ this.filterTerm += " " + this.schema.property.type.replace("org.openecomp.datatypes.heat.", "");
+ }
+ }
+ }
+
+ public convertToServerObject:Function = ():string => {
+ let serverObject = {};
+ let mapData = {
+ "type": this.type,
+ "required": this.required || false,
+ "defaultValue": this.defaultValue != "" && this.defaultValue != "[]" && this.defaultValue != "{}" ? this.defaultValue : null,
+ "description": this.description,
+ "constraints": this.constraints,
+ "isPassword": this.password || false,
+ "schema": this.schema,
+ "name": this.name
+ };
+ serverObject[this.name] = mapData;
+
+ return JSON.stringify(serverObject);
+ };
+
+ public toJSON = ():any => {
+ // if(!this.resourceInstanceUniqueId){
+ // this.value = undefined;
+ // }
+ let temp = angular.copy(this);
+ temp.readonly = undefined;
+ temp.resourceInstanceUniqueId = undefined;
+ temp.simpleType = undefined;
+ temp.value = temp.value === "{}" || temp.value === "[]" ? undefined : temp.value;
+ temp.defaultValue = temp.defaultValue === "{}" || temp.defaultValue === "[]" ? undefined : temp.defaultValue;
+ temp.rules = null; //don't send rules to server until feature is fully supported
+ temp.isAlreadySelected = undefined;
+ temp.addOn = undefined;
+ return temp;
+ };
+}
diff --git a/catalog-ui/src/app/models/property-fe-model.ts b/catalog-ui/src/app/models/property-fe-model.ts
new file mode 100644
index 0000000000..f83d6d6b51
--- /dev/null
+++ b/catalog-ui/src/app/models/property-fe-model.ts
@@ -0,0 +1,78 @@
+import {SchemaPropertyGroupModel, SchemaProperty} from './aschema-property';
+import { PROPERTY_DATA } from 'app/utils';
+import { FilterPropertiesAssignmentData, PropertyBEModel } from 'app/models';
+
+export class PropertyFEModel extends PropertyBEModel {
+ public static filterData:FilterPropertiesAssignmentData;
+ childrenProperties: Array<PropertyFEModel>;
+ expandedChildPropertyId: string;
+ isAllChildrenLevelsCalculated: boolean;
+ isDataType: boolean;
+ isDisabled: boolean;
+ isSelected: boolean;
+ isSimpleType: boolean;
+ parent: PropertyFEModel;
+ treeNodeId: string;
+ valueObjectRef: any;
+ private _derivedFromSimpleTypeName:string;
+ get derivedFromSimpleTypeName():string {
+ return this._derivedFromSimpleTypeName;
+ }
+ set derivedFromSimpleTypeName(derivedFromSimpleTypeName:string) {
+ this._derivedFromSimpleTypeName = derivedFromSimpleTypeName;
+ }
+
+ constructor(property?: PropertyBEModel);
+ constructor(name: string, type: string, treeNodeId: string, parent: PropertyFEModel, valueObjectRef: any, schema?: SchemaPropertyGroupModel);
+ constructor(nameOrPropertyObj?: string | PropertyBEModel, type?: string, treeNodeId?: string, parent?: PropertyFEModel, valueObjectRef?: any, schema?: SchemaPropertyGroupModel) {
+
+ super(typeof nameOrPropertyObj === 'string' ? null : nameOrPropertyObj);
+
+ if (typeof nameOrPropertyObj === 'string') {
+ this.name = nameOrPropertyObj;
+ this.type = type;
+ this.treeNodeId = treeNodeId;
+ this.parent = parent;
+ this.valueObjectRef = valueObjectRef;
+ this.value = this.value || this.defaultValue;
+ if(schema){
+ this.schema = new SchemaPropertyGroupModel(new SchemaProperty(schema.property));
+ }
+ }
+ this.isSimpleType = PROPERTY_DATA.SIMPLE_TYPES.indexOf(this.type) > -1;
+ this.isDataType = PROPERTY_DATA.TYPES.indexOf(this.type) == -1;
+ this.setNonDeclared();
+ }
+
+
+ public setNonDeclared = (): void => {
+ this.isSelected = false;
+ this.isDisabled = false;
+ }
+
+ public setAsDeclared = (): void => {
+ this.isSelected = true;
+ this.isDisabled = true;
+ }
+
+ //For expand-collapse functionality
+ public updateExpandedChildPropertyId = (childPropertyId: string): void => {
+ this.expandedChildPropertyId = (this.expandedChildPropertyId == childPropertyId) ? '' : childPropertyId;
+ }
+
+ public convertToServerObject: Function = (): any => { //TODO: Idan, Rachel, Nechama: Decide what we need to do here
+ // let serverObject = {};
+ // let mapData = {
+ // 'type': this.type,
+ // 'required': this.required || false,
+ // 'defaultValue': this.defaultValue != '' && this.defaultValue != '[]' && this.defaultValue != '{}' ? this.defaultValue : null,
+ // 'description': this.description,
+ // 'isPassword': this.password || false,
+ // 'schema': this.schema,
+ // 'name': this.name
+ // };
+ // serverObject[this.name] = mapData;
+
+ //return JSON.stringify(serverObject);
+ };
+}
diff --git a/catalog-ui/src/app/models/requirement.ts b/catalog-ui/src/app/models/requirement.ts
new file mode 100644
index 0000000000..e62c809ec9
--- /dev/null
+++ b/catalog-ui/src/app/models/requirement.ts
@@ -0,0 +1,71 @@
+/**
+ * Created by obarda on 4/20/2016.
+ */
+'use strict';
+//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 {
+ [key: string]: Array<Requirement>;
+ constructor(requirementGroupObj?:RequirementsGroup) {
+ _.forEach(requirementGroupObj, (requirementsArrayObj:Array<Requirement>, instance) => {
+ this[instance] = [];
+ _.forEach(requirementsArrayObj, (requirement:Requirement):void => {
+ this[instance].push(new Requirement(requirement));
+ });
+ });
+ }
+}
+
+export class Requirement {
+
+ //server data
+ capability:string;
+ name:string;
+ ownerId:string;
+ ownerName:string;
+ node:string;
+ uniqueId:string;
+ relationship:string;
+ minOccurrences:string;
+ maxOccurrences:string;
+ //custom
+ filterTerm:string;
+
+ constructor(requirement?:Requirement) {
+
+ if (requirement) {
+ this.capability = requirement.capability;
+ this.name = requirement.name;
+ this.ownerId = requirement.ownerId;
+ this.ownerName = requirement.ownerName;
+ this.node = requirement.node;
+ this.uniqueId = requirement.uniqueId;
+ this.relationship = requirement.relationship;
+ this.minOccurrences = requirement.minOccurrences;
+ this.maxOccurrences = requirement.maxOccurrences;
+ this.initFilterTerm();
+
+ }
+ }
+
+ public getFullTitle():string {
+ return this.ownerName + ': ' + this.name +
+ ': [' + this.minOccurrences + ', ' + this.maxOccurrences + ']';
+ }
+
+ public toJSON = ():any => {
+ this.filterTerm = undefined;
+ return this;
+ };
+
+ private initFilterTerm = ():void => {
+ this.filterTerm = (this.name + " ") +
+ (this.ownerName + " " ) +
+ (this.capability ? (this.capability.substring("tosca.capabilities.".length) + " " ) : "") +
+ (this.node ? (this.node.substring("tosca.nodes.".length) + " ") : "") +
+ (this.relationship ? (this.relationship.substring("tosca.relationships.".length) + " ") : "") +
+ this.minOccurrences + "," + this.maxOccurrences;
+ }
+}
+
+
diff --git a/catalog-ui/src/app/models/schema-attribute.ts b/catalog-ui/src/app/models/schema-attribute.ts
new file mode 100644
index 0000000000..3c48aa3fa2
--- /dev/null
+++ b/catalog-ui/src/app/models/schema-attribute.ts
@@ -0,0 +1,16 @@
+'use strict';
+import {SchemaProperty} from "./aschema-property";
+
+export class SchemaAttributeGroupModel {
+ property:SchemaAttribute;
+
+ constructor(schemaAttribute?:SchemaAttribute) {
+ this.property = schemaAttribute;
+ }
+}
+
+export class SchemaAttribute extends SchemaProperty {
+
+}
+
+
diff --git a/catalog-ui/src/app/models/tab.ts b/catalog-ui/src/app/models/tab.ts
new file mode 100644
index 0000000000..a7ce509ce0
--- /dev/null
+++ b/catalog-ui/src/app/models/tab.ts
@@ -0,0 +1,27 @@
+/**
+ * Created by obarda on 7/31/2016.
+ */
+'use strict';
+
+export class Tab {
+
+ public templateUrl:string;
+ public controller:string;
+ public data:any;
+ public icon:string;
+ public name:string;
+ public isViewMode:boolean;
+
+ constructor(templateUrl:string, controller:string, name:string, isViewMode:boolean, data?:any, icon?:string) {
+
+ this.templateUrl = templateUrl;
+ this.controller = controller;
+ this.icon = icon;
+ this.data = data;
+ this.name = name;
+ this.isViewMode = isViewMode;
+ }
+}
+
+
+
diff --git a/catalog-ui/src/app/models/tooltip-data.ts b/catalog-ui/src/app/models/tooltip-data.ts
new file mode 100644
index 0000000000..902a20e926
--- /dev/null
+++ b/catalog-ui/src/app/models/tooltip-data.ts
@@ -0,0 +1,6 @@
+'use strict';
+
+export class TooltipData {
+}
+
+
diff --git a/catalog-ui/src/app/models/user.ts b/catalog-ui/src/app/models/user.ts
new file mode 100644
index 0000000000..8ef800acb7
--- /dev/null
+++ b/catalog-ui/src/app/models/user.ts
@@ -0,0 +1,96 @@
+'use strict';
+import {IUserResource} from "../services/user-resource-service";
+
+export enum UserRole {
+ ADMIN,
+ DESIGNER,
+ TESTER,
+ GOVERNOR,
+ OPS,
+ PRODUCT_MANAGER,
+ PRODUCT_STRATEGIST
+}
+
+export interface IUserManager {
+ isInEditMode:boolean;
+ filterTerm:string;
+}
+
+export interface IUserProperties extends IUserManager {
+ firstName:string;
+ lastName:string;
+ userId:string;
+ email:string;
+ role:string;
+ tempRole:string;
+ lastLoginTime:string;
+ status:string;
+}
+
+export interface IUser {
+ resource:IUserResource;
+ getRole():UserRole;
+ getRoleToView():string;
+ getName():string;
+ getFirstName():string;
+ getLastName():string;
+}
+
+export class User implements IUser {
+
+ constructor(public resource:IUserResource) {
+ }
+
+ public getLastName = () => {
+ return this.resource.lastName;
+ }
+
+ public getFirstName = () => {
+ return this.resource.firstName;
+ }
+
+ public getName = () => {
+ return this.resource.firstName + ' ' + this.resource.lastName;
+ }
+
+ public getLastLogin = () => {
+ if (!this.resource.lastLoginTime || this.resource.lastLoginTime === "0") {
+ return "";
+ } else {
+ return this.resource.lastLoginTime;
+ }
+ }
+
+ public getRole = ():UserRole => {
+ let role:UserRole;
+ switch (UserRole[this.resource.role.toUpperCase()]) {
+ case UserRole.ADMIN:
+ role = UserRole.ADMIN;
+ break;
+ case UserRole.DESIGNER:
+ role = UserRole.DESIGNER;
+ break;
+ case UserRole.TESTER:
+ role = UserRole.TESTER;
+ break;
+ case UserRole.GOVERNOR:
+ role = UserRole.GOVERNOR;
+ break;
+ case UserRole.OPS:
+ role = UserRole.OPS;
+ break;
+ case UserRole.PRODUCT_MANAGER:
+ role = UserRole.PRODUCT_MANAGER;
+ break;
+ case UserRole.PRODUCT_STRATEGIST:
+ role = UserRole.PRODUCT_STRATEGIST;
+ break;
+ }
+ return role;
+ }
+
+ public getRoleToView = ():string => {
+ let role:string = this.resource.role.toLowerCase().replace('governor', 'governance_Rep');
+ return role.charAt(0).toUpperCase() + role.slice(1).replace('_', ' ');
+ }
+}
diff --git a/catalog-ui/src/app/models/validate.ts b/catalog-ui/src/app/models/validate.ts
new file mode 100644
index 0000000000..59638ab4dd
--- /dev/null
+++ b/catalog-ui/src/app/models/validate.ts
@@ -0,0 +1,7 @@
+'use strict';
+
+export interface IValidate {
+ isValid:boolean;
+}
+
+
diff --git a/catalog-ui/src/app/models/validation-config.ts b/catalog-ui/src/app/models/validation-config.ts
new file mode 100644
index 0000000000..3524addf86
--- /dev/null
+++ b/catalog-ui/src/app/models/validation-config.ts
@@ -0,0 +1,20 @@
+class PropertyValue {
+ min: number;
+ max: number;
+}
+
+class validationPatterns {
+ string: string;
+ comment:string;
+ integer: string;
+}
+
+export class Validations {
+ propertyValue: PropertyValue;
+ validationPatterns: validationPatterns;
+}
+
+export class ValidationConfiguration {
+ static validation: Validations;
+
+}
diff --git a/catalog-ui/src/app/modules/directive-module.ts b/catalog-ui/src/app/modules/directive-module.ts
new file mode 100644
index 0000000000..6ad89b8db7
--- /dev/null
+++ b/catalog-ui/src/app/modules/directive-module.ts
@@ -0,0 +1,152 @@
+import {ClickedOutsideDirective} from "../directives/clicked-outside/clicked-outside-directive";
+import {LoaderDirective} from "../directives/loader/loader-directive";
+import {UserHeaderDetailsDirective} from "../directives/user-header-details/user-header-details-directive";
+import {FileTypeDirective} from "../directives/file-type/file-type";
+import {DownloadArtifactDirective} from "../directives/download-artifact/download-artifact";
+import {EllipsisDirective} from "../directives/ellipsis/ellipsis-directive";
+import {InvalidCharactersDirective} from "../directives/invalid-characters/invalid-characters";
+import {ExpandCollapseDirective} from "../directives/utils/expand-collapse/expand-collapse";
+import {PerfectScrollerDirective} from "../directives/perfect-scrollbar/angular-perfect-scrollbar";
+import {SdcModalDirective} from "../directives/modal/sdc-modal";
+import {FileOpenerDirective} from "../directives/file-opener/file-opener";
+import {FileUploadDirective} from "../directives/file-upload/file-upload";
+import {StructureTreeDirective} from "../directives/structure-tree/structure-tree-directive";
+import {SmartTooltipDirective} from "../directives/utils/smart-tooltip/smart-tooltip";
+import {PrintGraphScreenDirective} from "../directives/print-graph-screen/print-graph-screen";
+import {TagDirective} from "../directives/tag/tag-directive";
+import {SdcTagsDirective} from "../directives/utils/sdc-tags/sdc-tags";
+import {SdcKeyboardEventsDirective} from "../directives/utils/sdc-keyboard-events/sdc-keyboard-events";
+import {ExpandCollapseMenuBoxDirective} from "../directives/utils/expand-collapse-menu-box/expand-collaps-menu-box";
+import {PunchOutDirective} from "../directives/punch-out/punch-out";
+import {CustomValidationDirective} from "../directives/custom-validation/custom-validation";
+import {EcompHeaderDirective} from "../directives/ecomp-header/ecomp-header";
+import {EcompFooterDirective} from "../directives/ecomp-footer/ecomp-footer";
+import {EditNamePopoverDirective} from "../directives/edit-name-popover/edit-name-popover-directive";
+import {DataTypeFieldsStructureDirective} from "../directives/property-types/data-type-fields-structure/data-type-fields-structure";
+import {TypeMapDirective} from "../directives/property-types/type-map/type-map-directive";
+import {TypeListDirective} from "../directives/property-types/type-list/type-list-directive";
+import {SelectDataTypeFieldsStructureDirective} from "../directives/select-property-types/select-data-type-fields-structure/select-data-type-fields-structure";
+import {SelectTypeMapDirective} from "../directives/select-property-types/select-type-map/select-type-map-directive";
+import {SelectTypeListDirective} from "../directives/select-property-types/select-type-list/select-type-list-directive";
+import {ValidationOnLoadDirective} from "../directives/utils/validation-on-load/validation-on-load";
+import {InfoTooltipDirective} from "../directives/info-tooltip/info-tooltip";
+import {SdcTabsDirective} from "../directives/sdc-tabs/sdc-tabs-directive";
+import {SdcSingleTabDirective, InnerSdcSingleTabDirective} from "../directives/sdc-tabs/sdc-single-tab/sdc-single-tab-directive";
+import {ExpandCollapseListHeaderDirective} from "../directives/utils/expand-collapse-list-header/expand-collapse-list-header";
+import {JsonExportExcelDirective} from "../directives/export-json-to-excel/export-json-to-excel";
+import {TopNavDirective} from "../directives/layout/top-nav/top-nav";
+import {TopProgressDirective} from "../directives/layout/top-progress/top-progress";
+import {CheckboxElementDirective} from "../directives/elements/checkbox/checkbox";
+import {RadiobuttonElementDirective} from "../directives/elements/radiobutton/radiobutton";
+import {OnLastRepeatDirective} from "../directives/events/on-last-repeat/on-last-repeat";
+import {InputRowDirective} from "../directives/inputs-and-properties/inputs/input-row-directive";
+import {PropertyRowDirective} from "../directives/inputs-and-properties/properties/property-row-directive";
+import {NodesFactory} from "../models/graph/nodes/nodes-factory";
+import {LinksFactory} from "../models/graph/graph-links/links-factory";
+import {ImageCreatorService} from "../directives/graphs-v2/image-creator/image-creator.service";
+import {Palette} from "../directives/graphs-v2/palette/palette.directive";
+import {CompositionGraph} from "../directives/graphs-v2/composition-graph/composition-graph.directive";
+import {RelationMenuDirective} from "../directives/graphs-v2/relation-menu/relation-menu";
+import {DeploymentGraph} from "../directives/graphs-v2/deployment-graph/deployment-graph.directive";
+import {CommonGraphUtils} from "../directives/graphs-v2/common/common-graph-utils";
+import {CompositionGraphNodesUtils} from "../directives/graphs-v2/composition-graph/utils/composition-graph-nodes-utils";
+import {CompositionGraphGeneralUtils} from "../directives/graphs-v2/composition-graph/utils/composition-graph-general-utils";
+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 {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";
+
+let moduleName:string = 'Sdc.Directives';
+let directiveModule:ng.IModule = angular.module(moduleName, []);
+
+directiveModule.directive('clickedOutside', ClickedOutsideDirective.factory);
+directiveModule.directive('loader', LoaderDirective.factory);
+directiveModule.directive('userHeaderDetails', UserHeaderDetailsDirective.factory);
+directiveModule.directive('ellipsis', EllipsisDirective.factory);
+directiveModule.directive('downloadArtifact', DownloadArtifactDirective.factory);
+directiveModule.directive('fileType', FileTypeDirective.factory);
+directiveModule.directive('invalidCharacters', InvalidCharactersDirective.factory);
+directiveModule.directive('perfectScrollbar', PerfectScrollerDirective.factory);
+directiveModule.directive('expandCollapse', ExpandCollapseDirective.factory);
+directiveModule.directive('sdcModal', SdcModalDirective.factory);
+directiveModule.directive('fileOpener', FileOpenerDirective.factory);
+directiveModule.directive('fileUpload', FileUploadDirective.factory);
+directiveModule.directive('structureTree', StructureTreeDirective.factory);
+directiveModule.directive('sdcSmartTooltip', SmartTooltipDirective.factory);
+directiveModule.directive('printGraphScreen', PrintGraphScreenDirective.factory);
+directiveModule.directive('sdcTag', TagDirective.factory);
+directiveModule.directive('sdcTags', SdcTagsDirective.factory);
+directiveModule.directive('sdcKeyboardEvents', SdcKeyboardEventsDirective.factory);
+directiveModule.directive('expandCollapseMenuBox', ExpandCollapseMenuBoxDirective.factory);
+directiveModule.directive('punchOut', PunchOutDirective.factory);
+directiveModule.directive('customValidation', CustomValidationDirective.factory);
+directiveModule.directive('ecompHeader', EcompHeaderDirective.factory);
+directiveModule.directive('ecompFooter', EcompFooterDirective.factory);
+directiveModule.directive('editNamePopover', EditNamePopoverDirective.factory);
+directiveModule.directive('fieldsStructure', DataTypeFieldsStructureDirective.factory);
+directiveModule.directive('typeMap', TypeMapDirective.factory);
+directiveModule.directive('typeList', TypeListDirective.factory);
+directiveModule.directive('selectFieldsStructure', SelectDataTypeFieldsStructureDirective.factory);
+directiveModule.directive('selectTypeMap', SelectTypeMapDirective.factory);
+directiveModule.directive('selectTypeList', SelectTypeListDirective.factory);
+directiveModule.directive('infoTooltip', InfoTooltipDirective.factory);
+directiveModule.directive('validationOnLoad', ValidationOnLoadDirective.factory);
+directiveModule.directive('sdcTabs', SdcTabsDirective.factory);
+directiveModule.directive('sdcSingleTab', SdcSingleTabDirective.factory);
+directiveModule.directive('innerSdcSingleTab', InnerSdcSingleTabDirective.factory);
+directiveModule.directive('jsonExportExcel', JsonExportExcelDirective.factory);
+directiveModule.directive('expandCollapseListHeader', ExpandCollapseListHeaderDirective.factory);
+//
+// // Layouts
+directiveModule.directive('topNav', TopNavDirective.factory);
+directiveModule.directive('topProgress', TopProgressDirective.factory);
+//
+// // Elements
+directiveModule.directive('sdcCheckbox', CheckboxElementDirective.factory);
+directiveModule.directive('sdcRadioButton', RadiobuttonElementDirective.factory);
+//
+// // Events
+directiveModule.directive('onLastRepeat', OnLastRepeatDirective.factory);
+//
+// //Inputs & Properties
+directiveModule.directive('inputRow', InputRowDirective.factory);
+directiveModule.directive('propertyRow', PropertyRowDirective.factory);
+//
+//
+// // ------------------------------------------- Composition & Deployment Graphs------------------------------------------//
+//
+// //Util service for Graph
+directiveModule.service('NodesFactory', NodesFactory);
+directiveModule.service('LinksFactory', LinksFactory);
+directiveModule.service('ImageCreatorService', ImageCreatorService);
+//
+// //composition
+directiveModule.directive('palette', Palette.factory);
+directiveModule.directive('compositionGraph', CompositionGraph.factory);
+directiveModule.directive('relationMenu', RelationMenuDirective.factory);
+ //directiveModule.directive('assetPopover', AssetPopoverDirective.factory);
+//
+// //deployment
+directiveModule.directive('deploymentGraph', DeploymentGraph.factory);
+//
+// //Graph Utils - Common
+directiveModule.service('CommonGraphUtils', CommonGraphUtils);
+//
+// //Composition Graph Utils
+directiveModule.service('CompositionGraphNodesUtils', CompositionGraphNodesUtils);
+directiveModule.service('CompositionGraphGeneralUtils', CompositionGraphGeneralUtils);
+directiveModule.service('CompositionGraphLinkUtils', CompositionGraphLinkUtils);
+directiveModule.service('CompositionGraphPaletteUtils', CompositionGraphPaletteUtils);
+directiveModule.service('MatchCapabilitiesRequirementsUtils', MatchCapabilitiesRequirementsUtils);
+//
+// //Deployment Graph Utils
+directiveModule.service('DeploymentGraphGeneralUtils', DeploymentGraphGeneralUtils);
+
+
+//Compoisiton right tab directives
+directiveModule.directive('capabilitiesList', CapabilitiesListDirective.factory);
+directiveModule.directive('requirementsList', RequirementsListDirective.factory);
diff --git a/catalog-ui/src/app/modules/filters.ts b/catalog-ui/src/app/modules/filters.ts
new file mode 100644
index 0000000000..a62283f927
--- /dev/null
+++ b/catalog-ui/src/app/modules/filters.ts
@@ -0,0 +1,26 @@
+import {TestsIdFilter} from "../filters/tests-id-filter";
+import {TrimFilter} from "../filters/trim-filter";
+import {ResourceTypeFilter} from "../filters/resource-type-filter";
+import {StringToDateFilter} from "../filters/string-to-date-filter";
+import {CategoryTypeFilter} from "../filters/category-type-filter";
+import {CatalogStatusFilter} from "../filters/catalog-status-filter";
+import {TruncateFilter} from "../filters/truncate-filter";
+import {EntityFilter} from "../filters/entity-filter";
+import {GraphResourceNameFilter} from "../filters/graph-resource-name-filter";
+import {ResourceNameFilter} from "../filters/resource-name-filter";
+import {ClearWhiteSpacesFilter} from "../filters/clear-whitespaces-filter";
+
+let moduleName:string = 'Sdc.Filters';
+let filterModule:ng.IModule = angular.module(moduleName, []);
+
+filterModule.filter("resourceName", ResourceNameFilter);
+filterModule.filter("graphResourceName", GraphResourceNameFilter);
+filterModule.filter("entityFilter", EntityFilter);
+filterModule.filter("truncate", TruncateFilter);
+filterModule.filter("catalogStatusFilter", CatalogStatusFilter);
+filterModule.filter("categoryTypeFilter", CategoryTypeFilter);
+filterModule.filter("stringToDateFilter", StringToDateFilter);
+filterModule.filter("resourceTypeName", ResourceTypeFilter);
+filterModule.filter("trim", TrimFilter);
+filterModule.filter("clearWhiteSpaces", ClearWhiteSpacesFilter);
+filterModule.filter('testsId', TestsIdFilter);
diff --git a/catalog-ui/src/app/modules/service-module.ts b/catalog-ui/src/app/modules/service-module.ts
new file mode 100644
index 0000000000..55ba87b9fb
--- /dev/null
+++ b/catalog-ui/src/app/modules/service-module.ts
@@ -0,0 +1,66 @@
+import {ConfigurationUiService} from "../services/configuration-ui-service";
+import {CookieService} from "../services/cookie-service";
+import {EntityService} from "../services/entity-service";
+import {AvailableIconsService} from "../services/available-icons-service";
+import {UrlToBase64Service} from "../services/url-tobase64-service";
+import {CacheService} from "../services/cache-service";
+import {HeaderInterceptor} from "../services/header-interceptor";
+import {HttpErrorInterceptor} from "../services/http-error-interceptor";
+import {SharingService} from "../services/sharing-service";
+import {SdcVersionService} from "../services/sdc-version-service";
+import {ActivityLogService} from "../services/activity-log-service";
+import {OnboardingService} from "../services/onboarding-service";
+import {EcompHeaderService} from "../services/ecomp-service";
+import {DataTypesService} from "../services/data-types-service";
+import {ComponentService} from "../services/components/component-service";
+import {ServiceService} from "../services/components/service-service";
+import {ResourceService} from "../services/components/resource-service";
+import {ProductService} from "../services/components/product-service";
+import {LeftPaletteLoaderService} from "../services/components/utils/composition-left-palette-service";
+import {EventListenerService} from "../services/event-listener-service";
+import {ProgressService} from "../services/progress-service";
+import {ArtifactsUtils} from "../utils/artifacts-utils";
+import {FileUtils} from "../utils/file-utils";
+import {ValidationUtils} from "../utils/validation-utils";
+import {AngularJSBridge} from "../services/angular-js-bridge-service";
+import {LoaderService} from "../services/loader-service";
+import {UserResourceService} from "../services/user-resource-service";
+import {CategoryResourceService} from "../services/category-resource-service";
+
+let moduleName:string = 'Sdc.Services';
+let serviceModule:ng.IModule = angular.module(moduleName, []);
+
+serviceModule.service('Sdc.Services.ConfigurationUiService', ConfigurationUiService);
+serviceModule.service('Sdc.Services.CookieService', CookieService);
+serviceModule.service('Sdc.Services.EntityService', EntityService);
+serviceModule.service('Sdc.Services.AvailableIconsService', AvailableIconsService);
+serviceModule.service('Sdc.Services.UrlToBase64Service', UrlToBase64Service);
+serviceModule.service('Sdc.Services.CacheService', CacheService);
+serviceModule.service('Sdc.Services.HeaderInterceptor', HeaderInterceptor);
+serviceModule.service('Sdc.Services.HttpErrorInterceptor', HttpErrorInterceptor);
+serviceModule.service('Sdc.Services.SharingService', SharingService);
+serviceModule.service('Sdc.Services.SdcVersionService', SdcVersionService);
+serviceModule.service('Sdc.Services.ActivityLogService', ActivityLogService);
+serviceModule.service('Sdc.Services.OnboardingService', OnboardingService);
+serviceModule.service('Sdc.Services.EcompHeaderService', EcompHeaderService);
+serviceModule.service('Sdc.Services.DataTypesService', DataTypesService);
+
+//Components Services
+serviceModule.service('Sdc.Services.Components.ComponentService', ComponentService);
+serviceModule.service('Sdc.Services.Components.ServiceService',ServiceService);
+serviceModule.service('Sdc.Services.Components.ResourceService', ResourceService);
+serviceModule.service('Sdc.Services.Components.ProductService', ProductService);
+serviceModule.service('LeftPaletteLoaderService', LeftPaletteLoaderService);
+serviceModule.service('EventListenerService', EventListenerService);
+serviceModule.service('Sdc.Services.ProgressService', ProgressService);
+
+//Utils
+serviceModule.service('ArtifactsUtils', ArtifactsUtils);
+serviceModule.service('FileUtils', FileUtils);
+serviceModule.service('ValidationUtils', ValidationUtils);
+
+serviceModule.service('AngularJSBridge',AngularJSBridge);
+serviceModule.service('LoaderService', LoaderService);
+
+serviceModule.factory('Sdc.Services.UserResourceService', UserResourceService.getResource);
+serviceModule.factory('Sdc.Services.CategoryResourceService', CategoryResourceService.getResource);
diff --git a/catalog-ui/src/app/modules/utils.ts b/catalog-ui/src/app/modules/utils.ts
new file mode 100644
index 0000000000..529857ac39
--- /dev/null
+++ b/catalog-ui/src/app/modules/utils.ts
@@ -0,0 +1,16 @@
+import {ComponentFactory} from "../utils/component-factory";
+import {ComponentInstanceFactory} from "../utils/component-instance-factory";
+import {ChangeLifecycleStateHandler} from "../utils/change-lifecycle-state-handler";
+import {ModalsHandler} from "../utils/modals-handler";
+import {MenuHandler} from "../utils/menu-handler";
+
+let moduleName:string = 'Sdc.Utils';
+let serviceModule:ng.IModule = angular.module(moduleName, []);
+
+//Utils
+serviceModule.service('ComponentFactory', ComponentFactory);
+serviceModule.service('ComponentInstanceFactory', ComponentInstanceFactory);
+serviceModule.service('ChangeLifecycleStateHandler', ChangeLifecycleStateHandler);
+serviceModule.service('ModalsHandler', ModalsHandler);
+serviceModule.service('MenuHandler', MenuHandler);
+
diff --git a/catalog-ui/src/app/modules/view-model-module.ts b/catalog-ui/src/app/modules/view-model-module.ts
new file mode 100644
index 0000000000..4060fe794e
--- /dev/null
+++ b/catalog-ui/src/app/modules/view-model-module.ts
@@ -0,0 +1,125 @@
+import {AddCategoryModalViewModel} from "../view-models/admin-dashboard/add-category-modal/add-category-modal-view-model";
+import {DashboardViewModel} from "../view-models/dashboard/dashboard-view-model";
+import {WorkspaceViewModel} from "../view-models/workspace/workspace-view-model";
+import {CompositionViewModel} from "../view-models/workspace/tabs/composition/composition-view-model";
+import {DetailsViewModel} from "../view-models/workspace/tabs/composition/tabs/details/details-view-model";
+import {ResourceArtifactsViewModel} from "../view-models/workspace/tabs/composition/tabs/artifacts/artifacts-view-model";
+import {PropertyFormBaseView} from "../view-models/forms/property-forms/base-property-form/property-form-base-model";
+import {PropertyFormViewModel} from "../view-models/forms/property-forms/component-property-form/property-form-view-model";
+import {ModulePropertyView} from "../view-models/forms/property-forms/module-property-modal/module-property-model";
+import {ArtifactResourceFormViewModel} from "../view-models/forms/artifact-form/artifact-form-view-model";
+import {SelectDataTypeViewModel} from "../view-models/forms/property-forms/select-datatype-modal/select-datatype-modal-view-model";
+import {AttributeFormViewModel} from "../view-models/forms/attribute-form/attribute-from-view-model";
+import {ResourcePropertiesViewModel} from "../view-models/workspace/tabs/composition/tabs/properties-and-attributes/properties-view-model";
+import {CatalogViewModel} from "../view-models/catalog/catalog-view-model";
+import {OnboardVendorViewModel} from "../view-models/onboard-vendor/onboard-vendor-view-model";
+import {DistributionViewModel} from "../view-models/workspace/tabs/distribution/distribution-view-model";
+import {SupportViewModel} from "../view-models/support/support-view-model";
+import {ConfirmationModalViewModel} from "../view-models/modals/confirmation-modal/confirmation-modal-view-model";
+import {EmailModalViewModel} from "../view-models/modals/email-modal/email-modal-view-model";
+import {MessageModalViewModel} from "../view-models/modals/message-modal/message-base-modal-model";
+import {ServerMessageModalViewModel} from "../view-models/modals/message-modal/message-server-modal/server-message-modal-view-model";
+import {ClientMessageModalViewModel} from "../view-models/modals/message-modal/message-client-modal/client-message-modal-view-model";
+import {ErrorViewModel} from "../view-models/modals/error-modal/error-view-model";
+import {RelationsViewModel} from "../view-models/workspace/tabs/composition/tabs/relations/relations-view-model";
+import {ResourceInstanceNameViewModel} from "../view-models/forms/resource-instance-name-form/resource-instance-name-model";
+import {WelcomeViewModel} from "../view-models/welcome/welcome-view";
+import {PreLoadingViewModel} from "../view-models/preloading/preloading-view";
+import {TutorialEndViewModel} from "../view-models/tutorial-end/tutorial-end";
+import {AdminDashboardViewModel} from "../view-models/admin-dashboard/admin-dashboard-view-model";
+import {EnvParametersFormViewModel} from "../view-models/forms/env-parameters-form/env-parameters-form";
+import {StructureViewModel} from "../view-models/workspace/tabs/composition/tabs/structure/structure-view";
+import {UserManagementViewModel} from "../view-models/admin-dashboard/user-management/user-management-view-model";
+import {CategoryManagementViewModel} from "../view-models/admin-dashboard/category-management/category-management-view-model";
+
+import {OnboardingModalViewModel} from "../view-models/modals/onboarding-modal/onboarding-modal-view-model";
+import {DistributionStatusModalViewModel} from "../view-models/workspace/tabs/distribution/disribution-status-modal/disribution-status-modal-view-model";
+import {DcaeAppViewModel} from "../view-models/dcae-app/dcae-app-view-model";
+import {GeneralViewModel} from "../view-models/workspace/tabs/general/general-view-model";
+import {IconsViewModel} from "../view-models/workspace/tabs/icons/icons-view-model";
+import {DeploymentArtifactsViewModel} from "../view-models/workspace/tabs/deployment-artifacts/deployment-artifacts-view-model";
+import {InformationArtifactsViewModel} from "../view-models/workspace/tabs/information-artifacts/information-artifacts-view-model";
+import {ToscaArtifactsViewModel} from "../view-models/workspace/tabs/tosca-artifacts/tosca-artifacts-view-model";
+import {PropertiesViewModel} from "../view-models/workspace/tabs/properties/properties-view-model";
+import {AttributesViewModel} from "../view-models/workspace/tabs/attributes/attributes-view-model";
+import {ProductHierarchyViewModel} from "../view-models/workspace/tabs/product-hierarchy/product-hierarchy-view-model";
+import {ActivityLogViewModel} from "../view-models/workspace/tabs/activity-log/activity-log";
+import {ManagementWorkflowViewModel} from "../view-models/workspace/tabs/management-workflow/management-workflow-view-model";
+import {NetworkCallFlowViewModel} from "../view-models/workspace/tabs/network-call-flow/network-call-flow-view-model";
+import {DeploymentViewModel} from "../view-models/workspace/tabs/deployment/deployment-view-model";
+import {ResourceInputsViewModel} from "../view-models/workspace/tabs/inputs/resource-input/resource-inputs-view-model";
+import {ServiceInputsViewModel} from "../view-models/workspace/tabs/inputs/service-input/service-inputs-view-model";
+import {ReqAndCapabilitiesViewModel} from "../view-models/workspace/tabs/req-and-capabilities/req-and-capabilities-view-model";
+import {InputFormViewModel} from "../view-models/forms/input-form/input-form-view-modal";
+import {HierarchyViewModel} from "../view-models/tabs/hierarchy/hierarchy-view-model";
+import {downgradeComponent} from "@angular/upgrade/static";
+import {ConformanceLevelModalViewModel} from "../view-models/workspace/conformance-level-modal/conformance-level-modal-view-model";
+// import {NG2ExampleComponent} from "../ng2/view-ng2/ng2.example.component/ng2.example.component";
+// import {upgradeAdapter} from "../ng2/app.module";
+// import { UpgradeAdapter } from '@angular/upgrade';
+let moduleName:string = 'Sdc.ViewModels';
+let viewModelModule:ng.IModule = angular.module(moduleName, []);
+
+viewModelModule
+ .controller(moduleName + '.DashboardViewModel', DashboardViewModel)
+
+ .controller(moduleName + '.DetailsViewModel', DetailsViewModel)
+ .controller(moduleName + '.ResourceArtifactsViewModel', ResourceArtifactsViewModel)
+ .controller(moduleName + '.PropertyFormBaseView', PropertyFormBaseView)
+ .controller(moduleName + '.PropertyFormViewModel', PropertyFormViewModel)
+ .controller(moduleName + '.ModulePropertyView', ModulePropertyView)
+ .controller(moduleName + '.SelectDataTypeViewModel', SelectDataTypeViewModel)
+ .controller(moduleName + '.ArtifactResourceFormViewModel', ArtifactResourceFormViewModel)
+ .controller(moduleName + '.AttributeFormViewModel', AttributeFormViewModel)
+ .controller(moduleName + '.ResourcePropertiesViewModel', ResourcePropertiesViewModel)
+ .controller(moduleName + '.CatalogViewModel', CatalogViewModel)
+ .controller(moduleName + '.OnboardVendorViewModel', OnboardVendorViewModel)
+ .controller(moduleName + '.DistributionViewModel', DistributionViewModel)
+ .controller(moduleName + '.SupportViewModel', SupportViewModel)
+ .controller(moduleName + '.ConfirmationModalViewModel', ConfirmationModalViewModel)
+ .controller(moduleName + '.EmailModalViewModel', EmailModalViewModel)
+ .controller(moduleName + '.MessageModalViewModel', MessageModalViewModel)
+ .controller(moduleName + '.ServerMessageModalViewModel', ServerMessageModalViewModel)
+ .controller(moduleName + '.ClientMessageModalViewModel', ClientMessageModalViewModel)
+ .controller(moduleName + '.ErrorViewModel', ErrorViewModel)
+ .controller(moduleName + '.RelationsViewModel', RelationsViewModel)
+ .controller(moduleName + '.ResourceInstanceNameViewModel', ResourceInstanceNameViewModel)
+ .controller(moduleName + '.WelcomeViewModel', WelcomeViewModel)
+ .controller(moduleName + '.PreLoadingViewModel', PreLoadingViewModel)
+ .controller(moduleName + '.TutorialEndViewModel', TutorialEndViewModel)
+ .controller(moduleName + '.AdminDashboardViewModel', AdminDashboardViewModel)
+ .controller(moduleName + '.EnvParametersFormViewModel', EnvParametersFormViewModel)
+ .controller(moduleName + '.StructureViewModel', StructureViewModel)
+ .controller(moduleName + '.AddCategoryModalViewModel', AddCategoryModalViewModel)
+ .controller(moduleName + '.UserManagementViewModel', UserManagementViewModel)
+ .controller(moduleName + '.CategoryManagementViewModel', CategoryManagementViewModel)
+ .controller(moduleName + '.OnboardingModalViewModel', OnboardingModalViewModel)
+ .controller(moduleName + '.DistributionStatusModalViewModel', DistributionStatusModalViewModel)
+ .controller(moduleName + '.DcaeAppViewModel', DcaeAppViewModel)
+ //
+ // //NEW
+ .controller(moduleName + '.WorkspaceViewModel', WorkspaceViewModel)
+ .controller(moduleName + '.ConformanceLevelModalViewModel', ConformanceLevelModalViewModel)
+ .controller(moduleName + '.CompositionViewModel', CompositionViewModel)
+ .controller(moduleName + '.GeneralViewModel', GeneralViewModel)
+ .controller(moduleName + '.IconsViewModel', IconsViewModel)
+ .controller(moduleName + '.DeploymentArtifactsViewModel', DeploymentArtifactsViewModel)
+ .controller(moduleName + '.InformationArtifactsViewModel', InformationArtifactsViewModel)
+ .controller(moduleName + '.ToscaArtifactsViewModel', ToscaArtifactsViewModel)
+ .controller(moduleName + '.PropertiesViewModel', PropertiesViewModel)
+ .controller(moduleName + '.AttributesViewModel', AttributesViewModel)
+ .controller(moduleName + '.ProductHierarchyViewModel', ProductHierarchyViewModel)
+ .controller(moduleName + '.ActivityLogViewModel', ActivityLogViewModel)
+ .controller(moduleName + '.ManagementWorkflowViewModel', ManagementWorkflowViewModel)
+ .controller(moduleName + '.NetworkCallFlowViewModel', NetworkCallFlowViewModel)
+ .controller(moduleName + '.DeploymentViewModel', DeploymentViewModel)
+ .controller(moduleName + '.ResourceInputsViewModel', ResourceInputsViewModel)
+ .controller(moduleName + '.ServiceInputsViewModel', ServiceInputsViewModel)
+ .controller(moduleName + '.ReqAndCapabilitiesViewModel', ReqAndCapabilitiesViewModel)
+ .controller(moduleName + '.InputFormViewModel', InputFormViewModel)
+ //
+ // //TABS
+ .controller(moduleName + '.HierarchyViewModel', HierarchyViewModel)
+
+ // NG2
+ //.controller(moduleName + '.NG2Example', downgradeComponent({component: NG2Example2Component}) );
diff --git a/catalog-ui/app/scripts/view-models/modals/message-modal/message-client-modal/client-message-modal.less b/catalog-ui/src/app/ng2/app.component.css
index e69de29bb2..e69de29bb2 100644
--- a/catalog-ui/app/scripts/view-models/modals/message-modal/message-client-modal/client-message-modal.less
+++ b/catalog-ui/src/app/ng2/app.component.css
diff --git a/catalog-ui/src/app/ng2/app.component.html b/catalog-ui/src/app/ng2/app.component.html
new file mode 100644
index 0000000000..ed90b3deda
--- /dev/null
+++ b/catalog-ui/src/app/ng2/app.component.html
@@ -0,0 +1,6 @@
+<!--<nav>
+ <app-navbar></app-navbar>
+</nav>
+<main>
+ <router-outlet></router-outlet>
+</main>--> \ No newline at end of file
diff --git a/catalog-ui/src/app/ng2/app.component.ts b/catalog-ui/src/app/ng2/app.component.ts
new file mode 100644
index 0000000000..0499045a79
--- /dev/null
+++ b/catalog-ui/src/app/ng2/app.component.ts
@@ -0,0 +1,15 @@
+import { Component, Inject } from '@angular/core';
+import { AuthenticationService } from './services/authentication.service';
+
+@Component({
+ selector: 'app-root',
+ templateUrl: './app.component.html',
+ styleUrls: ['./app.component.css']
+})
+export class AppComponent {
+
+ constructor(auth:AuthenticationService){
+
+ }
+
+}
diff --git a/catalog-ui/src/app/ng2/app.module.ts b/catalog-ui/src/app/ng2/app.module.ts
new file mode 100644
index 0000000000..9e122cd288
--- /dev/null
+++ b/catalog-ui/src/app/ng2/app.module.ts
@@ -0,0 +1,74 @@
+import {BrowserModule} from '@angular/platform-browser';
+import {NgModule, APP_INITIALIZER} from '@angular/core';
+import {FormsModule} from '@angular/forms';
+import {forwardRef} from '@angular/core';
+import {AppComponent} from './app.component';
+import {UpgradeAdapter} from '@angular/upgrade';
+import {UpgradeModule} from '@angular/upgrade/static';
+import {PropertiesAssignmentModule} from './pages/properties-assignment/properties-assignment.module';
+import {
+ DataTypesServiceProvider, SharingServiceProvider, CookieServiceProvider,
+ StateParamsServiceFactory
+} from "./utils/ng1-upgraded-provider";
+import {ConfigService} from "./services/config.service";
+import {HttpService} from "./services/http.service";
+import {HttpModule} from '@angular/http';
+import {AuthenticationService} from './services/authentication.service';
+import {Cookie2Service} from "./services/cookie.service";
+import {ComponentServiceNg2} from "./services/component-services/component.service";
+import {ServiceServiceNg2} from "./services/component-services/service.service";
+import {ComponentInstanceServiceNg2} from "./services/component-instance-services/component-instance.service";
+
+export const upgradeAdapter = new UpgradeAdapter(forwardRef(() => AppModule));
+
+export function configServiceFactory(config:ConfigService) {
+ return () => config.loadValidationConfiguration();
+}
+
+// export function httpServiceFactory(backend: XHRBackend, options: RequestOptions) {
+// return new HttpService(backend, options);
+// }
+
+@NgModule({
+ declarations: [
+ AppComponent
+ ],
+ imports: [
+ BrowserModule,
+ UpgradeModule,
+ FormsModule,
+ HttpModule,
+ PropertiesAssignmentModule
+ ],
+ exports: [],
+ entryComponents: [],
+ providers: [
+ HttpService,
+ DataTypesServiceProvider,
+ SharingServiceProvider,
+ CookieServiceProvider,
+ StateParamsServiceFactory,
+ AuthenticationService,
+ Cookie2Service,
+ ConfigService,
+ ComponentServiceNg2,
+ ServiceServiceNg2,
+ ComponentInstanceServiceNg2,
+ {
+ provide: APP_INITIALIZER,
+ useFactory: configServiceFactory,
+ deps: [ConfigService],
+ multi: true
+ }
+ ],
+ bootstrap: [AppComponent]
+})
+
+
+export class AppModule {
+ // ngDoBootstrap() {}
+ constructor(public upgrade:UpgradeModule) {
+
+
+ }
+}
diff --git a/catalog-ui/src/app/ng2/app.routing.ts b/catalog-ui/src/app/ng2/app.routing.ts
new file mode 100644
index 0000000000..38bc92619f
--- /dev/null
+++ b/catalog-ui/src/app/ng2/app.routing.ts
@@ -0,0 +1,20 @@
+import { RouterModule, Route } from '@angular/router';
+import { ModuleWithProviders } from '@angular/core';
+// import { Page1Component } from "./pages/page1/page1.component";
+// import { Page2Component } from "./pages/page2/page2.component";
+import { PageNotFoundComponent } from "./pages/page404/page404.component";
+
+const routes: Route[] = [
+ // { path: 'page1', component: Page1Component },
+ // { path: 'page2', component: Page2Component },
+ // { path: '', pathMatch: 'full', redirectTo: 'page1'},
+ { path: '**', component: PageNotFoundComponent }
+ /*{ loadChildren: './pages/dashboard/dashboard.module#DashboardModule', path: 'dashboard' }*/
+];
+
+export const routing: ModuleWithProviders = RouterModule.forRoot(
+ routes,
+ {
+ useHash: true
+ }
+);
diff --git a/catalog-ui/src/app/ng2/components/dynamic-element/dynamic-element.component.less b/catalog-ui/src/app/ng2/components/dynamic-element/dynamic-element.component.less
new file mode 100644
index 0000000000..e219d49aa4
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/dynamic-element/dynamic-element.component.less
@@ -0,0 +1,3 @@
+dynamic-element {
+
+}
diff --git a/catalog-ui/src/app/ng2/components/dynamic-element/dynamic-element.component.ts b/catalog-ui/src/app/ng2/components/dynamic-element/dynamic-element.component.ts
new file mode 100644
index 0000000000..de5965e488
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/dynamic-element/dynamic-element.component.ts
@@ -0,0 +1,117 @@
+import { Component, Compiler, EventEmitter, ViewContainerRef, ViewChild, Input, Output, ElementRef, ComponentRef, ComponentFactory, ComponentFactoryResolver } from '@angular/core'
+import { UiElementCheckBoxComponent } from './elements-ui/checkbox/ui-element-checkbox.component';
+import { UiElementDropDownComponent, DropdownValue } from './elements-ui/dropdown/ui-element-dropdown.component';
+import { UiElementInputComponent } from './elements-ui/input/ui-element-input.component';
+import {UiElementPopoverInputComponent} from "./elements-ui/popover-input/ui-element-popover-input.component";
+import {ValidationConfiguration} from "app/models";
+
+@Component({
+ selector: 'dynamic-element',
+ template: `<div #target></div>`,
+ styleUrls: ['./dynamic-element.component.less'],
+ entryComponents: [
+ UiElementInputComponent,
+ UiElementDropDownComponent,
+ UiElementCheckBoxComponent,
+ UiElementPopoverInputComponent
+ ]
+})
+export class DynamicElementComponent {
+
+ @ViewChild('target', { read: ViewContainerRef }) target: any;
+ @Input() type: any;
+ @Input() name: string;
+ 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;
+ }
+
+ cmpRef: ComponentRef<any>;
+ private isViewInitialized: boolean = false;
+ validation = ValidationConfiguration.validation;
+
+ constructor(
+ private componentFactoryResolver: ComponentFactoryResolver,
+ private compiler: Compiler,
+ private el: ElementRef) {
+ }
+
+ updateComponent() {
+ if (!this.isViewInitialized) {
+ return;
+ }
+ if (this.cmpRef) {
+ this.cmpRef.destroy();
+ }
+
+ // Factory to create component based on type or peroperty name.
+ switch(this.type) {
+ case 'list':
+ case 'integer':
+ this.createComponent(UiElementInputComponent);
+ this.cmpRef.instance.pattern = this.validation.validationPatterns.integer;
+ break;
+ case 'string':
+ switch(this.name.toUpperCase()) {
+ case 'SUBNETPOOLID':
+ this.createComponent(UiElementPopoverInputComponent);
+ break;
+ default:
+ this.createComponent(UiElementInputComponent);
+ }
+ break;
+ case 'boolean':
+ //this.createComponent(UiElementCheckBoxComponent);
+
+ this.createComponent(UiElementDropDownComponent);
+
+ // Build drop down values
+ let tmp = [];
+ tmp.push(new DropdownValue('true','TRUE'));
+ tmp.push(new DropdownValue('false','FALSE'));
+ this.cmpRef.instance.values = tmp;
+ break;
+ 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;
+ }
+
+ // 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)
+ });
+
+ }
+
+ createComponent(ComponentToCreate:any):void {
+ let factory = this.componentFactoryResolver.resolveComponentFactory(ComponentToCreate);
+ this.cmpRef = this.target.createComponent(factory);
+ }
+
+ ngOnChanges() {
+ this.updateComponent();
+ }
+
+ ngAfterContentInit() {
+ //console.log("DynamicElementComponent: ngAfterContentInit: type: " + this.type + " value: " + this.value);
+ this.isViewInitialized = true;
+ this.updateComponent();
+ }
+
+ ngOnDestroy() {
+ if (this.cmpRef) {
+ this.cmpRef.destroy();
+ }
+ }
+
+}
diff --git a/catalog-ui/src/app/ng2/components/dynamic-element/dynamic-element.module.ts b/catalog-ui/src/app/ng2/components/dynamic-element/dynamic-element.module.ts
new file mode 100644
index 0000000000..18b044bc9d
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/dynamic-element/dynamic-element.module.ts
@@ -0,0 +1,34 @@
+import { NgModule } from "@angular/core";
+import { UiElementCheckBoxComponent } from './elements-ui/checkbox/ui-element-checkbox.component';
+import { UiElementDropDownComponent } from './elements-ui/dropdown/ui-element-dropdown.component';
+import { UiElementInputComponent } from './elements-ui/input/ui-element-input.component';
+import { DynamicElementComponent } from "app/ng2/components/dynamic-element/dynamic-element.component";
+import { BrowserModule } from '@angular/platform-browser'
+import { FormsModule, ReactiveFormsModule } from '@angular/forms'
+import { UiElementPopoverInputComponent } from "./elements-ui/popover-input/ui-element-popover-input.component";
+import {PopoverModule} from "../popover/popover.module";
+import {TooltipModule} from "../tooltip/tooltip.module";
+
+@NgModule({
+ declarations: [
+ DynamicElementComponent,
+ UiElementInputComponent,
+ UiElementCheckBoxComponent,
+ UiElementDropDownComponent,
+ UiElementPopoverInputComponent
+ ],
+ imports: [
+ BrowserModule,
+ FormsModule,
+ PopoverModule,
+ ReactiveFormsModule,
+ TooltipModule
+ ],
+ exports: [
+ DynamicElementComponent
+ ],
+ providers: []
+})
+export class DynamicElementModule {
+
+}
diff --git a/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/checkbox/ui-element-checkbox.component.html b/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/checkbox/ui-element-checkbox.component.html
new file mode 100644
index 0000000000..2ad3d8e94a
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/checkbox/ui-element-checkbox.component.html
@@ -0,0 +1 @@
+<input #{{name}} [(ngModel)]="value" type="checkbox" (change)="onSave(value)" />
diff --git a/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/checkbox/ui-element-checkbox.component.less b/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/checkbox/ui-element-checkbox.component.less
new file mode 100644
index 0000000000..bed097fe5e
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/checkbox/ui-element-checkbox.component.less
@@ -0,0 +1,2 @@
+/deep/ ui-element-checkbox {
+}
diff --git a/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/checkbox/ui-element-checkbox.component.ts b/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/checkbox/ui-element-checkbox.component.ts
new file mode 100644
index 0000000000..152303aee7
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/checkbox/ui-element-checkbox.component.ts
@@ -0,0 +1,27 @@
+import { Component, ViewChild, ElementRef, ContentChildren, Input } from '@angular/core';
+import { BrowserModule } from '@angular/platform-browser'
+import { UiElementBase, UiElementBaseInterface } from './../ui-element-base.component';
+
+@Component({
+ selector: 'ui-element-checkbox',
+ templateUrl: './ui-element-checkbox.component.html',
+ styleUrls: ['./ui-element-checkbox.component.less'],
+})
+export class UiElementCheckBoxComponent extends UiElementBase implements UiElementBaseInterface {
+
+ constructor() {
+ super();
+ }
+
+ ngAfterContentInit() {
+ // Convert the value to boolean (instanceOf does not work, the type is undefined).
+ if (this.value==='true' || this.value==='false') {
+ this.value = this.value==='true'?true:false;
+ }
+ }
+
+ onSave() {
+ this.baseEmitter.emit(this.value);
+ }
+
+}
diff --git a/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/dropdown/ui-element-dropdown.component.html b/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/dropdown/ui-element-dropdown.component.html
new file mode 100644
index 0000000000..589d00e42d
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/dropdown/ui-element-dropdown.component.html
@@ -0,0 +1,3 @@
+<select name='{{name}}' [(ngModel)]="value" #t (change)="onSave()">
+ <option *ngFor="let ddvalue of values" [value]="ddvalue.value">{{ddvalue.label}}</option>
+</select>
diff --git a/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/dropdown/ui-element-dropdown.component.less b/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/dropdown/ui-element-dropdown.component.less
new file mode 100644
index 0000000000..ea3e35140e
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/dropdown/ui-element-dropdown.component.less
@@ -0,0 +1,11 @@
+@import '../../../../../../assets/styles/variables';
+
+/deep/ ui-element-dropdown {
+
+ select {
+ text-indent: 6px;
+ border: solid 1px @main_color_o;
+ width: 100%;
+ }
+
+}
diff --git a/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/dropdown/ui-element-dropdown.component.ts b/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/dropdown/ui-element-dropdown.component.ts
new file mode 100644
index 0000000000..208bf54983
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/dropdown/ui-element-dropdown.component.ts
@@ -0,0 +1,33 @@
+import { Component, EventEmitter, Output, Input } from '@angular/core'
+import { BrowserModule } from '@angular/platform-browser'
+import { UiElementBase, UiElementBaseInterface } from './../ui-element-base.component';
+
+export class DropdownValue {
+ value:string;
+ label:string;
+
+ constructor(value:string,label:string) {
+ this.value = value;
+ this.label = label;
+ }
+}
+
+@Component({
+ selector: 'ui-element-dropdown',
+ templateUrl: './ui-element-dropdown.component.html',
+ styleUrls: ['./ui-element-dropdown.component.less'],
+})
+export class UiElementDropDownComponent extends UiElementBase implements UiElementBaseInterface {
+
+ @Input()
+ values: DropdownValue[];
+
+ constructor() {
+ super();
+ }
+
+ onSave() {
+ this.baseEmitter.emit(this.value);
+ }
+
+}
diff --git a/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/input/ui-element-input.component.html b/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/input/ui-element-input.component.html
new file mode 100644
index 0000000000..00fea65b72
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/input/ui-element-input.component.html
@@ -0,0 +1,13 @@
+<input
+ class="value-input"
+ [ngClass]="{'error': control.invalid}"
+ type="text"
+ [name]="name"
+ [(ngModel)]="value"
+ (change)="onSave()"
+ [attr.maxlength]="validation.propertyValue.max"
+ [attr.minlength]="validation.propertyValue.min"
+ [pattern]="pattern"
+ [formControl]="control"
+ tooltip="{{value}}"
+ />
diff --git a/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/input/ui-element-input.component.less b/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/input/ui-element-input.component.less
new file mode 100644
index 0000000000..d320c7ff8b
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/input/ui-element-input.component.less
@@ -0,0 +1,17 @@
+@import '../../../../../../assets/styles/variables';
+
+/deep/ ui-element-input {
+
+ input {
+ text-indent: 6px;
+ border: solid 1px @main_color_o;
+ }
+
+ .error {
+ border: solid 1px @func_color_q;
+ color: @func_color_q;
+ outline: none;
+ box-sizing: border-box;
+ }
+
+}
diff --git a/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/input/ui-element-input.component.ts b/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/input/ui-element-input.component.ts
new file mode 100644
index 0000000000..5a14d8f206
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/input/ui-element-input.component.ts
@@ -0,0 +1,22 @@
+import { Component, ViewChild, ElementRef, ContentChildren } from '@angular/core';
+import { BrowserModule } from '@angular/platform-browser'
+import { UiElementBase, UiElementBaseInterface } from './../ui-element-base.component';
+
+@Component({
+ selector: 'ui-element-input',
+ templateUrl: './ui-element-input.component.html',
+ styleUrls: ['./ui-element-input.component.less'],
+})
+export class UiElementInputComponent extends UiElementBase implements UiElementBaseInterface {
+
+ constructor() {
+ 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/dynamic-element/elements-ui/popover-input/ui-element-popover-input.component.html b/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/popover-input/ui-element-popover-input.component.html
new file mode 100644
index 0000000000..5adceb49a0
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/popover-input/ui-element-popover-input.component.html
@@ -0,0 +1,26 @@
+<div class="popover-input-wrapper" tooltip="{{value}}">
+ <input
+ class="value-input"
+ type="text"
+ [ngClass]="{'error': control.invalid}"
+ [name]="name"
+ [value]="value"
+ disabled
+ />
+ <button [popover]="popoverForm">Edit</button>
+</div>
+
+<popover-content #popoverForm [title]="name" [buttons]="buttonsArray" [placement]="'top'" [closeOnClickOutside]="true">
+ <div class="edit-subnet-wrapper">
+ <textarea rows="5"
+ #textArea
+ class="subnet-value"
+ [ngClass]="{'error': control.invalid}"
+ [(ngModel)]="value"
+ [attr.maxlength]="validation.propertyValue.max"
+ [attr.minlength]="validation.propertyValue.min"
+ [pattern]="pattern"
+ [formControl]="control"
+ ></textarea>
+ </div>
+</popover-content>
diff --git a/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/popover-input/ui-element-popover-input.component.less b/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/popover-input/ui-element-popover-input.component.less
new file mode 100644
index 0000000000..5be443f7b6
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/popover-input/ui-element-popover-input.component.less
@@ -0,0 +1,36 @@
+@import '../../../../../../assets/styles/variables';
+
+.popover-input-wrapper {
+ display: flex;
+}
+
+/deep/ ui-element-popover-input {
+
+ .popover {
+ max-width: 350px;
+ width: 350px;
+ }
+
+ .edit-subnet-wrapper {
+ padding: 12px;
+
+ .subnet-value {
+ width: 100%;
+ resize: none;
+ }
+ }
+
+ input {
+ padding-right: 6px;
+ padding-left: 6px;
+ border: solid 1px @main_color_o;
+ }
+
+ .error {
+ border: solid 1px @func_color_q;
+ color: @func_color_q;
+ outline: none;
+ box-sizing: border-box;
+ }
+
+}
diff --git a/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/popover-input/ui-element-popover-input.component.ts b/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/popover-input/ui-element-popover-input.component.ts
new file mode 100644
index 0000000000..7300417686
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/popover-input/ui-element-popover-input.component.ts
@@ -0,0 +1,39 @@
+import {Component, ViewChild, ElementRef} from '@angular/core';
+import {UiElementBase, UiElementBaseInterface} from "../ui-element-base.component";
+import {ButtonsModelMap, ButtonModel} from "app/models";
+import { PopoverContentComponent } from "app/ng2/components/popover/popover-content.component"
+import { PopoverComponent } from "app/ng2/components/popover/popover.component"
+
+@Component({
+ selector: 'ui-element-popover-input',
+ templateUrl: './ui-element-popover-input.component.html',
+ styleUrls: ['./ui-element-popover-input.component.less']
+})
+export class UiElementPopoverInputComponent extends UiElementBase implements UiElementBaseInterface {
+
+ @ViewChild('textArea') textArea: ElementRef;
+ @ViewChild('popoverForm') popoverContentComponent: PopoverContentComponent;
+
+ 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.buttonsArray = { 'test': this.saveButton };
+
+ // Define the regex pattern for this controller
+ this.pattern = this.validation.validationPatterns.comment;
+
+ // Disable / Enable button according to validation
+ //this.control.valueChanges.subscribe(data => this.saveButton.disabled = this.control.invalid);
+ }
+}
diff --git a/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/ui-element-base.component.ts b/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/ui-element-base.component.ts
new file mode 100644
index 0000000000..b60271f6f0
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/ui-element-base.component.ts
@@ -0,0 +1,34 @@
+import { Component, EventEmitter, Input, Output } from '@angular/core'
+import { ValidationConfiguration } from "app/models";
+import { FormControl, Validators } from '@angular/forms';
+
+export interface UiElementBaseInterface {
+ onSave();
+}
+
+@Component({
+ template: ``,
+ styles: []
+})
+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;
+ }
+
+ protected name: string;
+ protected type: string;
+ protected value: any;
+ protected pattern: any;
+
+ constructor() {
+ //this.control = new FormControl('', [Validators.required]);
+ this.control = new FormControl('', []);
+ }
+
+}
diff --git a/catalog-ui/src/app/ng2/components/filter-properties-assignment/filter-properties-assignment.component.html b/catalog-ui/src/app/ng2/components/filter-properties-assignment/filter-properties-assignment.component.html
new file mode 100644
index 0000000000..4d2b91f3b4
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/filter-properties-assignment/filter-properties-assignment.component.html
@@ -0,0 +1,26 @@
+<popover-content #filterPopover [title]="'Filters'" [buttons]="footerButtons" placement="bottom-right" [hideArrow]="true">
+ <!--<form [formGroup]="filterForm">-->
+ <form>
+ <div class="field">
+ <label>Resource Type</label>
+ <div>
+ <checkbox [label]="'All'" [(checked)]="allSelected" (checkedChange)="selectAll()"></checkbox>
+ </div>
+ <div *ngFor="let type of typesOptions">
+ <checkbox [label]="type" [(checked)]="selectedTypes[type]" (checkedChange)="onTypeSelected(type)"></checkbox>
+ </div>
+ </div>
+ <div class="field">
+ <label>Property Name</label>
+ <input class="i-sdc-form-input"
+ name="propertyName"
+ [(ngModel)]="filterData.propertyName"
+ placeholder="Type here"
+ required
+ />
+ </div>
+ </form>
+</popover-content>
+<div class="open-filter-button" [popover]="filterPopover" [ngClass]="{'open':showPopover}" (onShown)="showPopover = true" (onHidden)="showPopover = false">
+ <div class="sprite-new filter-icon"></div>
+</div>
diff --git a/catalog-ui/src/app/ng2/components/filter-properties-assignment/filter-properties-assignment.component.less b/catalog-ui/src/app/ng2/components/filter-properties-assignment/filter-properties-assignment.component.less
new file mode 100644
index 0000000000..c1341b8dcf
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/filter-properties-assignment/filter-properties-assignment.component.less
@@ -0,0 +1,38 @@
+@import '../../../../assets/styles/variables';
+form{
+ margin: 0 20px;
+ .field{
+ padding:20px 0;
+ &:not(:last-child){
+ border-bottom: solid 1px @main_color_o;
+ }
+ }
+ /deep/ [ng-reflect-checked="true"]{
+ /deep/ .checkbox-label-content{
+ color: @main_color_a;
+ }
+ }
+}
+
+.open-filter-button{
+ cursor: pointer;
+ width: 25px;
+ height: 34px;
+ display: inline-block;
+ &.open{
+ z-index: 1061;
+ position: relative;
+ top: 2px;
+ background-color: @main_color_p;
+ border: solid 1px @main_color_c;
+ border-bottom: none;
+ }
+ .filter-icon{
+ top: 8px;
+ position: relative;
+ }
+}
+
+/deep/ .popover{
+ border: solid 1px @main_color_c !important;
+}
diff --git a/catalog-ui/src/app/ng2/components/filter-properties-assignment/filter-properties-assignment.component.ts b/catalog-ui/src/app/ng2/components/filter-properties-assignment/filter-properties-assignment.component.ts
new file mode 100644
index 0000000000..c23e08bc0d
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/filter-properties-assignment/filter-properties-assignment.component.ts
@@ -0,0 +1,77 @@
+/**
+ * Created by rc2122 on 5/16/2017.
+ */
+import {Component, Input, Output, EventEmitter, ViewChild} from '@angular/core';
+import {ButtonModel, ButtonsModelMap, FilterPropertiesAssignmentData} from "app/models";
+import {PopoverComponent} from "../popover/popover.component";
+import * as sdcConfig from "../../../../../configurations/dev"
+
+@Component({
+ selector: 'filter-properties-assignment',
+ templateUrl: './filter-properties-assignment.component.html',
+ styleUrls: ['./filter-properties-assignment.component.less']
+})
+
+export class FilterPropertiesAssignmentComponent {
+ @Input() componentType: string;
+ @Output() searchProperties: EventEmitter<FilterPropertiesAssignmentData> = new EventEmitter<FilterPropertiesAssignmentData>();
+ footerButtons:ButtonsModelMap = {};
+ typesOptions:Array<string>;//All optional types
+ selectedTypes:Object = {};
+ allSelected:boolean = false;//if all option selected
+ filterData:FilterPropertiesAssignmentData = new FilterPropertiesAssignmentData();
+ @ViewChild('filterPopover') filterPopover: PopoverComponent;
+
+ ngOnInit() {
+ this.footerButtons['Apply'] = new ButtonModel('Apply', 'blue', this.search, this.someTypesSelectedAndThereIsPropertyName);
+ this.footerButtons['Close'] = new ButtonModel('Close', 'grey', this.close);
+ this.componentType = this.componentType.toLocaleLowerCase();
+ this.typesOptions = sdcConfig.resourceTypesFilter[this.componentType];
+ }
+
+ selectAll = () => {
+ _.forEach(this.typesOptions, (type) => {
+ this.selectedTypes[type] = this.allSelected;
+ });
+ }
+
+ onTypeSelected = (type:string) => {
+ if(!this.selectedTypes[type]){
+ this.allSelected = false;//unselected 'All'
+ }
+ };
+
+ search = () => {
+ console.log('search props');
+ this.filterData.selectedTypes = [];
+ _.forEach(sdcConfig.resourceTypesFilter[this.componentType], (type) => {
+ if(this.selectedTypes[type]){
+ this.filterData.selectedTypes.push(type);
+ }
+ });
+ this.searchProperties.emit(this.filterData);
+ this.filterPopover.hide();
+ }
+
+ close = () => {
+ this.filterPopover.hide();
+ }
+
+ someTypesSelectedAndThereIsPropertyName = ():boolean => {
+ if( _.find(Object.keys(this.selectedTypes),(key) => {
+ return this.selectedTypes[key];
+ }) && this.filterData.propertyName ){
+ return null
+ }
+ return true;
+ }
+
+ clearAll = ():void => {
+ this.filterData.propertyName = "";
+ _.forEach(this.selectedTypes,(value, key) => {
+ this.selectedTypes[key] = false;
+ });
+ this.allSelected = false;
+ }
+
+}
diff --git a/catalog-ui/src/app/ng2/components/hierarchy-navigtion/hierarchy-display-options.ts b/catalog-ui/src/app/ng2/components/hierarchy-navigtion/hierarchy-display-options.ts
new file mode 100644
index 0000000000..7045286ccd
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/hierarchy-navigtion/hierarchy-display-options.ts
@@ -0,0 +1,12 @@
+export class HierarchyDisplayOptions {
+ idProperty: string;
+ valueProperty: string;
+ childrenProperty: string;
+ searchText:string;
+ constructor(idProperty:string, valueProperty:string, childrenProperty?:string, searchText?:string) {
+ this.idProperty = idProperty;
+ this.valueProperty = valueProperty;
+ this.childrenProperty = childrenProperty;
+ this.searchText = searchText;
+ }
+}
diff --git a/catalog-ui/src/app/ng2/components/hierarchy-navigtion/hierarchy-navigation.component.html b/catalog-ui/src/app/ng2/components/hierarchy-navigtion/hierarchy-navigation.component.html
new file mode 100644
index 0000000000..40a1c37cee
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/hierarchy-navigtion/hierarchy-navigation.component.html
@@ -0,0 +1,13 @@
+<div class="navigation-wrapper">
+ <div class="node-item" *ngFor="let item of displayData" (click)="onClick($event, item)">
+ <div class="node-data-wrapper" [ngClass]="{'selected': selectedItem && selectedItem === item[displayOptions.idProperty]}">
+ <span class="node-data" [ngClass]="{'mark':item[displayOptions.valueProperty] === displayOptions.searchText}">{{item[displayOptions.valueProperty]}}</span>
+ </div>
+ <div class="children-node" *ngIf="item[displayOptions.childrenProperty]">
+ <hierarchy-navigation class="children-hierarchy" [displayData]="item[displayOptions.childrenProperty]"
+ [selectedItem]="selectedItem"
+ [displayOptions]="displayOptions"
+ (updateSelected)="onSelectedUpdate($event)"></hierarchy-navigation>
+ </div>
+ </div>
+</div>
diff --git a/catalog-ui/src/app/ng2/components/hierarchy-navigtion/hierarchy-navigation.component.less b/catalog-ui/src/app/ng2/components/hierarchy-navigtion/hierarchy-navigation.component.less
new file mode 100644
index 0000000000..57d51616a8
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/hierarchy-navigtion/hierarchy-navigation.component.less
@@ -0,0 +1,51 @@
+.navigation-wrapper {
+ text-align: left;
+}
+
+.node-item {
+ border: 1px dotted;
+ border-right: none;
+ border-bottom: none;
+}
+
+.node-item:last-child {
+ border-left: none;
+}
+
+.node-data-wrapper {
+ cursor: default;
+ height: 30px;
+ line-height: 2.6em;;
+ position: relative;
+ top: -1.1em;
+ background-color: white;
+ margin-left: 0.7em;
+}
+
+.children-node {
+ padding-left: 40px;
+}
+
+.node-data {
+ margin-left: 10px;
+ margin-right: 10px;
+}
+
+.node-data-wrapper.selected {
+ background-color: #e6f6fb;
+
+ .node-data {
+ color: #009fdb;
+ }
+}
+
+.node-data-wrapper:hover {
+ background-color: #eaeaea;
+}
+
+.mark{
+ background-color: yellow;
+}
+
+
+
diff --git a/catalog-ui/src/app/ng2/components/hierarchy-navigtion/hierarchy-navigation.component.ts b/catalog-ui/src/app/ng2/components/hierarchy-navigtion/hierarchy-navigation.component.ts
new file mode 100644
index 0000000000..428bbb4b04
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/hierarchy-navigtion/hierarchy-navigation.component.ts
@@ -0,0 +1,28 @@
+import {Component, Input, Output, EventEmitter} from '@angular/core';
+import {HierarchyDisplayOptions} from './hierarchy-display-options';
+
+
+@Component({
+ selector: 'hierarchy-navigation',
+ templateUrl: './hierarchy-navigation.component.html',
+ styleUrls: ['./hierarchy-navigation.component.less']
+})
+
+export class HierarchyNavigationComponent {
+ @Input() displayData: Array<any>;
+ @Input() selectedItem: any;
+ @Input() displayOptions: HierarchyDisplayOptions;
+
+ @Output() updateSelected:EventEmitter<any> = new EventEmitter();
+
+ 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/inputs-table/inputs-table.component.html b/catalog-ui/src/app/ng2/components/inputs-table/inputs-table.component.html
new file mode 100644
index 0000000000..e7801b82cf
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/inputs-table/inputs-table.component.html
@@ -0,0 +1,37 @@
+<div class="properties-table">
+ <div class="table-header">
+ <div class="table-cell col1">Property Name</div>
+ <div class="table-cell col2">Type</div>
+ <div class="table-cell col3">ES</div>
+ <div class="table-cell valueCol">Value</div>
+ </div>
+ <div class="table-body">
+ <div class="no-data" *ngIf="!inputs || !inputs.length">No data to display</div>
+ <div class="table-row" *ngFor="let input of inputs">
+ <div class="table-cell col1">
+ <span tooltip="{{input.name}}" >{{input.name}}</span>
+ <span *ngIf="input.description"
+ class="property-description-icon sprite-new show-desc"
+ tooltip="{{input.description}}"></span>
+ </div>
+ <div class="table-cell col2">{{input.type | contentAfterLastDot}}</div>
+ <div class="table-cell col3">{{input.schema && input.schema.property && input.schema.property.type ? (input.schema.property.type | contentAfterLastDot) : ''}}</div>
+ <div class="table-cell valueCol input-value-col" [class.inner-table-container]="input.childrenProperties || !input.isSimpleType">
+ <dynamic-element class="value-input"
+ *ngIf="input.isSimpleType"
+ pattern="validationUtils.getValidationPattern(input.type)"
+ [(value)]="input.defaultValue"
+ [type]="input.type"
+ [name]="input.name"
+ (change)="onInputValueChanged(input);">
+ </dynamic-element>
+ <div class="delete-button-container">
+ <span class="sprite-new delete-btn" (click)="onDeleteInput(input)"></span>
+ </div>
+ </div>
+
+ </div>
+ </div>
+</div>
+
+
diff --git a/catalog-ui/src/app/ng2/components/inputs-table/inputs-table.component.ts b/catalog-ui/src/app/ng2/components/inputs-table/inputs-table.component.ts
new file mode 100644
index 0000000000..ea01edf043
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/inputs-table/inputs-table.component.ts
@@ -0,0 +1,33 @@
+/**
+ * Created by rc2122 on 5/4/2017.
+ */
+import {Component, Input, Output, EventEmitter} from "@angular/core";
+import {InputFEModel} from "app/models";
+
+@Component({
+ selector: 'inputs-table',
+ templateUrl: './inputs-table.component.html',
+ styleUrls: ['../properties-table/properties-table.component.less']
+})
+export class InputsTableComponent {
+
+ @Input() inputs: Array<InputFEModel>;
+
+ @Output() inputValueChanged: EventEmitter<any> = new EventEmitter<any>();
+ @Output() deleteInput: EventEmitter<any> = new EventEmitter<any>();
+
+ constructor (){
+ }
+
+ onInputValueChanged = (input) => {
+ this.inputValueChanged.emit(input);
+ };
+
+ onDeleteInput = (input) => {
+ this.deleteInput.emit(input);
+ }
+
+
+}
+
+
diff --git a/catalog-ui/src/app/ng2/components/popover/popover-content.component.html b/catalog-ui/src/app/ng2/components/popover/popover-content.component.html
new file mode 100644
index 0000000000..6d76f0ad06
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/popover/popover-content.component.html
@@ -0,0 +1,24 @@
+<div #popoverDiv class="popover {{ effectivePlacement }}"
+ [style.top]="top + 'px'"
+ [style.left]="left + 'px'"
+ [class.in]="isIn"
+ [class.fade]="animation"
+ style="display: block"
+ role="popover"
+ [ngClass]="{'hide-arrow':hideArrow}">
+ <div [hidden]="!closeOnMouseOutside" class="virtual-area"></div>
+ <div class="arrow" *ngIf="!hideArrow"></div>
+ <div class="popover-header">
+ <span class="title">{{ title }}</span>
+ <span class="close-button" (click)="popover.hide()"></span>
+ </div>
+ <ng-content></ng-content>
+ <div class="popover-footer">
+ <button *ngFor="let buttonName of buttonsNames"
+ class="tlv-btn {{buttons[buttonName].cssClass}}"
+ [disabled] = "buttons[buttonName].getDisabled && buttons[buttonName].getDisabled()"
+ (click) = "buttons[buttonName].callback()">{{buttons[buttonName].text}}</button>
+ </div>
+</div>
+
+
diff --git a/catalog-ui/src/app/ng2/components/popover/popover-content.component.less b/catalog-ui/src/app/ng2/components/popover/popover-content.component.less
new file mode 100644
index 0000000000..f7b62e91f7
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/popover/popover-content.component.less
@@ -0,0 +1,73 @@
+@import '../../../../assets/styles/variables';
+@import '../../../../assets/styles/mixins';
+@import '../../../../assets/styles/sprite-old';
+.popover .virtual-area {
+ height: 11px;
+ width: 100%;
+ position: absolute;
+}
+.popover.top .virtual-area {
+ bottom: -11px;
+}
+.popover.bottom .virtual-area {
+ top: -11px;
+}
+.popover.left .virtual-area {
+ right: -11px;
+}
+.popover.right .virtual-area {
+ left: -11px;
+}
+.popover.hide-arrow{
+ margin: 0;
+}
+
+.popover-header{
+ .m_14_m;
+ font-weight: bold;
+ -webkit-box-flex: 1;
+ -ms-flex-positive: 1;
+ flex-grow: 1;
+ height: 40px;
+ line-height: 48px;
+ display: -webkit-box;
+ display: -ms-flexbox;
+ display: flex;
+ text-align: left;
+ border-bottom: solid 1px @main_color_o;
+ -webkit-box-align: center;
+ -ms-flex-align: center;
+ align-items: center;
+ margin: 0px 20px;
+ .title{
+ -webkit-box-flex: 999;
+ -ms-flex-positive: 999;
+ flex-grow: 999;
+ }
+ .close-button{
+ .sprite;
+ .sprite.x-btn-black;
+ cursor: pointer;
+ }
+}
+
+.popover-footer{
+ background-color: @tlv_color_t;
+ height: 40px;
+ clear: both;
+ -webkit-box-flex: 1;
+ -ms-flex-positive: 1;
+ flex-grow: 1;
+ display: -webkit-box;
+ display: -ms-flexbox;
+ display: flex;
+ -webkit-box-align: center;
+ -ms-flex-align: center;
+ align-items: center;
+ -webkit-box-pack: end;
+ -ms-flex-pack: end;
+ justify-content: flex-end;
+ button{
+ margin: 8px 12px 8px 6px;
+ }
+}
diff --git a/catalog-ui/src/app/ng2/components/popover/popover-content.component.ts b/catalog-ui/src/app/ng2/components/popover/popover-content.component.ts
new file mode 100644
index 0000000000..c4489f59b9
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/popover/popover-content.component.ts
@@ -0,0 +1,258 @@
+import {Component, Input, Output, AfterViewInit, ElementRef, ChangeDetectorRef, OnDestroy, ViewChild, EventEmitter, Renderer } from "@angular/core";
+import {ButtonsModelMap} from "app/models";
+import {PopoverComponent} from "./popover.component";
+
+@Component({
+ selector: "popover-content",
+ templateUrl:'./popover-content.component.html',
+ styleUrls:['popover-content.component.less']
+})
+export class PopoverContentComponent implements AfterViewInit, OnDestroy {
+
+ @Input() public title: string;
+ @Input() public buttons:ButtonsModelMap;
+
+ @Input()
+ content: string;
+
+ @Input()
+ placement: "top"|"bottom"|"left"|"right"|"auto"|"auto top"|"auto bottom"|"auto left"|"auto right" = "bottom";
+
+ @Input()
+ animation: boolean = true;
+
+ @Input()
+ closeOnClickOutside: boolean = false;
+
+ @Input()
+ closeOnMouseOutside: boolean = false;
+
+ @Input()
+ hideArrow: boolean = false;
+
+ @ViewChild("popoverDiv")
+ popoverDiv: ElementRef;
+
+ buttonsNames:Array<string>;
+
+ popover: PopoverComponent;
+ onCloseFromOutside = new EventEmitter();
+ top: number = -10000;
+ left: number = -10000;
+ isIn: boolean = false;
+ displayType: string = "none";
+ effectivePlacement: string;
+
+ onDocumentMouseDown = (event: any) => {
+ const element = this.element.nativeElement;
+ if (!element || !this.popover) return;
+ if (element.contains(event.target) || this.popover.getElement().contains(event.target)) return;
+ this.hide();
+ this.onCloseFromOutside.emit(undefined);
+ };
+
+
+ constructor(protected element: ElementRef,
+ protected cdr: ChangeDetectorRef,
+ protected renderer: Renderer) {
+ }
+
+ listenClickFunc: any;
+ listenMouseFunc: any;
+
+ ngAfterViewInit(): void {
+ this.buttonsNames = Object.keys(this.buttons);
+ if (this.closeOnClickOutside)
+ this.listenClickFunc = this.renderer.listenGlobal("document", "mousedown", (event: any) => this.onDocumentMouseDown(event));
+ if (this.closeOnMouseOutside)
+ this.listenMouseFunc = this.renderer.listenGlobal("document", "mouseover", (event: any) => this.onDocumentMouseDown(event));
+
+ this.show();
+ this.cdr.detectChanges();
+ }
+
+ ngOnDestroy() {
+ if (this.closeOnClickOutside)
+ this.listenClickFunc();
+ if (this.closeOnMouseOutside)
+ this.listenMouseFunc();
+ }
+
+ // -------------------------------------------------------------------------
+ // Public Methods
+ // -------------------------------------------------------------------------
+
+ show(): void {
+ if (!this.popover || !this.popover.getElement())
+ return;
+
+ const p = this.positionElements(this.popover.getElement(), this.popoverDiv.nativeElement, this.placement);
+ this.displayType = "block";
+ this.top = p.top;
+ this.left = p.left;
+ this.isIn = true;
+ }
+
+ hide(): void {
+ this.top = -10000;
+ this.left = -10000;
+ this.isIn = true;
+ this.popover.hide();
+ }
+
+ hideFromPopover() {
+ this.top = -10000;
+ this.left = -10000;
+ this.isIn = true;
+ }
+
+ // -------------------------------------------------------------------------
+ // Protected Methods
+ // -------------------------------------------------------------------------
+
+ protected positionElements(hostEl: HTMLElement, targetEl: HTMLElement, positionStr: string, appendToBody: boolean = false): { top: number, left: number } {
+ let positionStrParts = positionStr.split("-");
+ let pos0 = positionStrParts[0];
+ let pos1 = positionStrParts[1] || "center";
+ let hostElPos = appendToBody ? this.offset(hostEl) : this.position(hostEl);
+ let targetElWidth = targetEl.offsetWidth;
+ let targetElHeight = targetEl.offsetHeight;
+
+ this.effectivePlacement = pos0 = this.getEffectivePlacement(pos0, hostEl, targetEl);
+
+ let shiftWidth: any = {
+ center: function (): number {
+ return hostElPos.left + hostElPos.width / 2 - targetElWidth / 2;
+ },
+ left: function (): number {
+ return hostElPos.left;
+ },
+ right: function (): number {
+ return hostElPos.left + hostElPos.width - targetElWidth;
+ }
+ };
+
+ let shiftHeight: any = {
+ center: function (): number {
+ return hostElPos.top + hostElPos.height / 2 - targetElHeight / 2;
+ },
+ top: function (): number {
+ return hostElPos.top;
+ },
+ bottom: function (): number {
+ return hostElPos.top + hostElPos.height - targetElHeight;
+ }
+ };
+
+ let targetElPos: { top: number, left: number };
+ switch (pos0) {
+ case "right":
+ targetElPos = {
+ top: shiftHeight[pos1](),
+ left: hostElPos.left + hostElPos.width
+ };
+ break;
+
+ case "left":
+ targetElPos = {
+ top: shiftHeight[pos1](),
+ left: hostElPos.left - targetElWidth
+ };
+ break;
+
+ case "bottom":
+ targetElPos = {
+ top: hostElPos.top + hostElPos.height,
+ left: shiftWidth[pos1]()
+ };
+ break;
+
+ default:
+ targetElPos = {
+ top: hostElPos.top - targetElHeight,
+ left: shiftWidth[pos1]()
+ };
+ break;
+ }
+
+ return targetElPos;
+ }
+
+ protected position(nativeEl: HTMLElement): { width: number, height: number, top: number, left: number } {
+ let offsetParentBCR = { top: 0, left: 0 };
+ const elBCR = this.offset(nativeEl);
+ const offsetParentEl = this.parentOffsetEl(nativeEl);
+ if (offsetParentEl !== window.document) {
+ offsetParentBCR = this.offset(offsetParentEl);
+ offsetParentBCR.top += offsetParentEl.clientTop - offsetParentEl.scrollTop;
+ offsetParentBCR.left += offsetParentEl.clientLeft - offsetParentEl.scrollLeft;
+ }
+
+ const boundingClientRect = nativeEl.getBoundingClientRect();
+ return {
+ width: boundingClientRect.width || nativeEl.offsetWidth,
+ height: boundingClientRect.height || nativeEl.offsetHeight,
+ top: elBCR.top - offsetParentBCR.top,
+ left: elBCR.left - offsetParentBCR.left
+ };
+ }
+
+ protected offset(nativeEl: any): { width: number, height: number, top: number, left: number } {
+ const boundingClientRect = nativeEl.getBoundingClientRect();
+ return {
+ width: boundingClientRect.width || nativeEl.offsetWidth,
+ height: boundingClientRect.height || nativeEl.offsetHeight,
+ top: boundingClientRect.top + (window.pageYOffset || window.document.documentElement.scrollTop),
+ left: boundingClientRect.left + (window.pageXOffset || window.document.documentElement.scrollLeft)
+ };
+ }
+
+ protected getStyle(nativeEl: HTMLElement, cssProp: string): string {
+ if ((nativeEl as any).currentStyle) // IE
+ return (nativeEl as any).currentStyle[cssProp];
+
+ if (window.getComputedStyle)
+ return (window.getComputedStyle as any)(nativeEl)[cssProp];
+
+ // finally try and get inline style
+ return (nativeEl.style as any)[cssProp];
+ }
+
+ protected isStaticPositioned(nativeEl: HTMLElement): boolean {
+ return (this.getStyle(nativeEl, "position") || "static" ) === "static";
+ }
+
+ protected parentOffsetEl(nativeEl: HTMLElement): any {
+ let offsetParent: any = nativeEl.offsetParent || window.document;
+ while (offsetParent && offsetParent !== window.document && this.isStaticPositioned(offsetParent)) {
+ offsetParent = offsetParent.offsetParent;
+ }
+ return offsetParent || window.document;
+ }
+
+ protected getEffectivePlacement(placement: string, hostElement: HTMLElement, targetElement: HTMLElement): string {
+ const placementParts = placement.split(" ");
+ if (placementParts[0] !== "auto") {
+ return placement;
+ }
+
+ const hostElBoundingRect = hostElement.getBoundingClientRect();
+
+ const desiredPlacement = placementParts[1] || "bottom";
+
+ if (desiredPlacement === "top" && hostElBoundingRect.top - targetElement.offsetHeight < 0) {
+ return "bottom";
+ }
+ if (desiredPlacement === "bottom" && hostElBoundingRect.bottom + targetElement.offsetHeight > window.innerHeight) {
+ return "top";
+ }
+ if (desiredPlacement === "left" && hostElBoundingRect.left - targetElement.offsetWidth < 0) {
+ return "right";
+ }
+ if (desiredPlacement === "right" && hostElBoundingRect.right + targetElement.offsetWidth > window.innerWidth) {
+ return "left";
+ }
+
+ return desiredPlacement;
+ }
+}
diff --git a/catalog-ui/src/app/ng2/components/popover/popover.component.ts b/catalog-ui/src/app/ng2/components/popover/popover.component.ts
new file mode 100644
index 0000000000..a7e2881b29
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/popover/popover.component.ts
@@ -0,0 +1,159 @@
+import { Directive, HostListener, ComponentRef, ViewContainerRef, ComponentFactoryResolver, ComponentFactory, Input, OnChanges, SimpleChange, Output, EventEmitter } from "@angular/core";
+import {PopoverContentComponent} from "./popover-content.component";
+
+@Directive({
+ selector: "[popover]",
+ exportAs: "popover"
+})
+export class PopoverComponent implements OnChanges {
+
+ protected PopoverComponent = PopoverContentComponent;
+ protected popover: ComponentRef<PopoverContentComponent>;
+ protected visible: boolean;
+
+
+ constructor(protected viewContainerRef: ViewContainerRef,
+ protected resolver: ComponentFactoryResolver) {
+ }
+
+ @Input("popover")
+ content: string|PopoverContentComponent;
+
+ @Input()
+ popoverDisabled: boolean;
+
+ @Input()
+ popoverAnimation: boolean;
+
+ @Input()
+ popoverPlacement: "top"|"bottom"|"left"|"right"|"auto"|"auto top"|"auto bottom"|"auto left"|"auto right";
+
+ @Input()
+ popoverTitle: string;
+
+ @Input()
+ popoverOnHover: boolean = false;
+
+ @Input()
+ popoverCloseOnClickOutside: boolean;
+
+ @Input()
+ popoverCloseOnMouseOutside: boolean;
+
+ @Input()
+ popoverDismissTimeout: number = 0;
+
+ @Output()
+ onShown = new EventEmitter<PopoverComponent>();
+
+ @Output()
+ onHidden = new EventEmitter<PopoverComponent>();
+
+ @HostListener("click")
+ showOrHideOnClick(): void {
+ if (this.popoverOnHover) return;
+ if (this.popoverDisabled) return;
+ this.toggle();
+ }
+
+ @HostListener("focusin")
+ @HostListener("mouseenter")
+ showOnHover(): void {
+ if (!this.popoverOnHover) return;
+ if (this.popoverDisabled) return;
+ this.show();
+ }
+
+ @HostListener("focusout")
+ @HostListener("mouseleave")
+ hideOnHover(): void {
+ if (this.popoverCloseOnMouseOutside) return;
+ if (!this.popoverOnHover) return;
+ if (this.popoverDisabled) return;
+ this.hide();
+ }
+
+ ngOnChanges(changes: {[propertyName: string]: SimpleChange}) {
+ if (changes["popoverDisabled"]) {
+ if (changes["popoverDisabled"].currentValue) {
+ this.hide();
+ }
+ }
+ }
+
+ toggle() {
+ if (!this.visible) {
+ this.show();
+ } else {
+ this.hide();
+ }
+ }
+
+ show() {
+ if (this.visible) return;
+
+ this.visible = true;
+ if (typeof this.content === "string") {
+ const factory = this.resolver.resolveComponentFactory(this.PopoverComponent);
+ if (!this.visible)
+ return;
+
+ this.popover = this.viewContainerRef.createComponent(factory);
+ const popover = this.popover.instance as PopoverContentComponent;
+ popover.popover = this;
+ popover.content = this.content as string;
+ if (this.popoverPlacement !== undefined)
+ popover.placement = this.popoverPlacement;
+ if (this.popoverAnimation !== undefined)
+ popover.animation = this.popoverAnimation;
+ if (this.popoverTitle !== undefined)
+ popover.title = this.popoverTitle;
+ if (this.popoverCloseOnClickOutside !== undefined)
+ popover.closeOnClickOutside = this.popoverCloseOnClickOutside;
+ if (this.popoverCloseOnMouseOutside !== undefined)
+ popover.closeOnMouseOutside = this.popoverCloseOnMouseOutside;
+
+ popover.onCloseFromOutside.subscribe(() => this.hide());
+ if (this.popoverDismissTimeout > 0)
+ setTimeout(() => this.hide(), this.popoverDismissTimeout);
+ } else {
+ const popover = this.content as PopoverContentComponent;
+ popover.popover = this;
+ if (this.popoverPlacement !== undefined)
+ popover.placement = this.popoverPlacement;
+ if (this.popoverAnimation !== undefined)
+ popover.animation = this.popoverAnimation;
+ if (this.popoverTitle !== undefined)
+ popover.title = this.popoverTitle;
+ if (this.popoverCloseOnClickOutside !== undefined)
+ popover.closeOnClickOutside = this.popoverCloseOnClickOutside;
+ if (this.popoverCloseOnMouseOutside !== undefined)
+ popover.closeOnMouseOutside = this.popoverCloseOnMouseOutside;
+
+ popover.onCloseFromOutside.subscribe(() => this.hide());
+ if (this.popoverDismissTimeout > 0)
+ setTimeout(() => this.hide(), this.popoverDismissTimeout);
+ popover.show();
+ }
+
+ this.onShown.emit(this);
+ }
+
+ hide() {
+ if (!this.visible) return;
+
+ this.visible = false;
+ if (this.popover)
+ this.popover.destroy();
+
+ if (this.content instanceof PopoverContentComponent)
+ (this.content as PopoverContentComponent).hideFromPopover();
+
+ this.onHidden.emit(this);
+ }
+
+ getElement() {
+ return this.viewContainerRef.element.nativeElement;
+ }
+
+}
diff --git a/catalog-ui/src/app/ng2/components/popover/popover.module.ts b/catalog-ui/src/app/ng2/components/popover/popover.module.ts
new file mode 100644
index 0000000000..4bd8426ce1
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/popover/popover.module.ts
@@ -0,0 +1,27 @@
+/**
+ * Created by rc2122 on 5/17/2017.
+ */
+import {NgModule} from "@angular/core";
+import { CommonModule } from '@angular/common';
+import {PopoverComponent} from "./popover.component";
+import {PopoverContentComponent} from "./popover-content.component";
+
+@NgModule({
+ declarations: [
+ PopoverComponent,
+ PopoverContentComponent
+ ],
+ imports: [
+ // PopoverComponent,
+ // PopoverContentComponent
+ CommonModule
+ ],
+ exports: [
+ PopoverComponent,
+ PopoverContentComponent
+ ],
+ providers: []
+})
+export class PopoverModule {
+
+}
diff --git a/catalog-ui/src/app/ng2/components/properties-table/derived-property/derived-property.component.html b/catalog-ui/src/app/ng2/components/properties-table/derived-property/derived-property.component.html
new file mode 100644
index 0000000000..6e7d4e882b
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/properties-table/derived-property/derived-property.component.html
@@ -0,0 +1,24 @@
+<!-- TODO: refactor this to be dynamic -->
+<div class="derived-property-row" *ngIf="propertyObj.isDeclared || propertyObj.derivedDataType == derivedPropertyTypes.SIMPLE">
+ <div class="table-cell" [ngClass]="{'iltered':propertyObj.name === propertyNameSearchText}"><checkbox [label]="propertyObj.name" [(checked)]="propertyObj.isSelected" [disabled]="propertyObj.isDisabled ||propertyObj.isDeclared" (checkedChange)="checkedChange($event)"></checkbox></div>
+
+ <div class="table-cell simple">
+ <input type="text" [(ngModel)]="propertyObj.value" [disabled]="propertyObj.isDisabled || propertyObj.isDeclared" (change)="valueChanged.emit()" />
+ </div>
+</div>
+<div class="derived-property-row" *ngIf="!propertyObj.isDeclared && propertyObj.derivedDataType == derivedPropertyTypes.COMPLEX">
+ <div class="table-cell" [ngClass]="{'filtered':propertyObj.name === propertyNameSearchText}"><checkbox [label]="propertyObj.name" [(checked)]="propertyObj.isSelected" [disabled]="propertyObj.isDisabled ||propertyObj.isDeclared" (checkedChange)="checkedChange($event)"></checkbox></div>
+ <div class="table-cell complex">
+ <span class="datatype-text">{{propertyObj.type | contentAfterLastDot }}</span>
+ <span (click)="expandChildById(propertyObj.propertiesName)" class="expand-icon" [class.expanded]="expanded">V</span>
+ </div>
+</div>
+<div class="derived-property-row" *ngIf="!propertyObj.isDeclared && propertyObj.derivedDataType == derivedPropertyTypes.SIMPLELIST ||propertyObj.derivedDataType == derivedPropertyTypes.SIMPLEMAP">
+ <div class="table-cell">
+ <span [ngClass]="{'filtered':propertyObj.name === propertyNameSearchText}">{{propertyObj.name}}</span>
+ </div>
+ <div class="table-cell simple2">
+ <div class="sprite-new add-item-icon" (click)="addRows(propertyObj)"></div>
+ </div>
+</div>
+
diff --git a/catalog-ui/src/app/ng2/components/properties-table/derived-property/derived-property.component.less b/catalog-ui/src/app/ng2/components/properties-table/derived-property/derived-property.component.less
new file mode 100644
index 0000000000..3102c5ceb8
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/properties-table/derived-property/derived-property.component.less
@@ -0,0 +1,35 @@
+.derived-property-row {
+ display:flex;
+ flex-direction:row;
+ position:relative;
+ border-top: #d2d2d2 solid 1px;
+
+ &:first-child {
+ border-top:none;
+ }
+ .table-cell {
+ flex: 0 0 50%;
+ padding:5px;
+ position:relative;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+
+ &:first-child {
+ border-right:#d2d2d2 solid 1px;
+ overflow:hidden;
+ }
+ span.expand-icon {
+ position: absolute;
+ right: 10px;
+ transition: 200ms transform ease-in-out;
+ }
+ span.expand-icon.expanded {
+ transform: rotate(-180deg);
+ }
+ }
+}
+.filtered {
+ /deep/ .checkbox-label-content{
+ background-color: yellow;
+ }
+}
diff --git a/catalog-ui/src/app/ng2/components/properties-table/derived-property/derived-property.component.ts b/catalog-ui/src/app/ng2/components/properties-table/derived-property/derived-property.component.ts
new file mode 100644
index 0000000000..16f069a685
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/properties-table/derived-property/derived-property.component.ts
@@ -0,0 +1,46 @@
+/**
+ * Created by rc2122 on 4/20/2017.
+ */
+import {Component, Input, Output, EventEmitter} from "@angular/core";
+import { DerivedFEProperty, DerivedPropertyType} from "app/models";
+import {PropertiesService} from "../../../services/properties.service";
+
+@Component({
+ selector: 'derived-property',
+ templateUrl: './derived-property.component.html',
+ styleUrls: ['./derived-property.component.less']
+})
+export class DerivedPropertyComponent {
+
+ derivedPropertyTypes = DerivedPropertyType; //http://stackoverflow.com/questions/35835984/how-to-use-a-typescript-enum-value-in-an-angular2-ngswitch-statement
+
+ @Input() propertyObj: DerivedFEProperty;
+ @Input() propertyNameSearchText: string;
+ @Input() expanded: boolean;
+ @Output() valueChanged: EventEmitter<any> = new EventEmitter<any>();
+ @Output() expandChild: EventEmitter<string> = new EventEmitter<string>();
+ @Output() selectProperty: EventEmitter<boolean> = new EventEmitter<boolean>();
+
+
+ constructor ( private propertiesService:PropertiesService){
+ }
+
+
+ propValueChanged = () => {
+ this.valueChanged.emit(this.propertyObj);
+ };
+
+ expandChildById = (id: string) => {
+ this.expandChild.emit(id);
+ }
+
+ checkedChange = (isChecked:boolean) => {
+ this.selectProperty.emit(isChecked);
+ }
+
+ addRows = (flatProperty: DerivedFEProperty): void => {
+ console.log("ADDING A ROW OF TYPE " + flatProperty.type);
+ console.log(flatProperty);
+ }
+
+}
diff --git a/catalog-ui/src/app/ng2/components/properties-table/dynamic-property/dynamic-property.component.html b/catalog-ui/src/app/ng2/components/properties-table/dynamic-property/dynamic-property.component.html
new file mode 100644
index 0000000000..17e4002ae5
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/properties-table/dynamic-property/dynamic-property.component.html
@@ -0,0 +1,66 @@
+<div class="dynamic-property-row"
+ [ngClass]="{'selected': selectedPropertyId === property.uniqueId }"
+ [class.with-top-border]="property.isChildOfListOrMap"
+ (click)="onClickPropertyRow(property, $event)">
+ <!-- LEFT CELL - for all NON-PropFEModel properties except for MAP)-->
+ <ng-container *ngIf="!isPropertyFEModel">
+ <div class="table-cell" *ngIf="canBeDeclared"> <!-- simple children of complex type -->
+ <checkbox [label]="property.name" [(checked)]="property.isSelected" [disabled]="property.isDisabled ||property.isDeclared" (checkedChange)="checkProperty.emit(property.propertiesName)"
+ ></checkbox>
+ </div>
+ <div class="table-cell" *ngIf="!canBeDeclared && !property.isChildOfListOrMap">{{property.name}}</div> <!-- simple children of complex type within map or list -->
+ </ng-container>
+ <!-- RIGHT CELL -->
+ <ng-container *ngIf="propType == derivedPropertyTypes.SIMPLE || property.isDeclared">
+ <div class="table-cell" [class.full-width]="isPropertyFEModel || property.isChildOfListOrMap">
+ <dynamic-element class="value-input"
+ pattern="validationUtils.getValidationPattern(property.type)"
+ [(value)]="property.value"
+ [type]="property.type"
+ [name]="property.name"
+ (valueChange)="propValueChanged(property);"
+ > <!--[disabled]="property.isDisabled || property.isDeclared" -->
+ </dynamic-element>
+ </div>
+ </ng-container>
+ <ng-container *ngIf="!property.isDeclared"> <!-- other cases need to fail if isDeclared, in which case we need to use full width value above instead) -->
+
+ <ng-container *ngIf="propType == derivedPropertyTypes.COMPLEX && !isPropertyFEModel">
+ <div class="table-cell complex" [class.full-width]="property.isChildOfListOrMap">
+ <span>{{property.type | contentAfterLastDot }}</span>
+ </div>
+ </ng-container>
+ <ng-container *ngIf="property.isChildOfListOrMap && propType == derivedPropertyTypes.MAP">
+ <div class="table-cell map-entry"><input type="text" /></div>
+ <div class="table-cell" *ngIf="property.schema.property.isSimpleType">
+ <input type="text" [(ngModel)]="property.value" /></div>
+ <div class="table-cell" *ngIf="!property.schema.property.isSimpleType">
+ <span>{{property.schema.property.type | contentAfterLastDot }}</span>
+ </div>
+ </ng-container>
+
+ <!-- ICONS: add, delete, and expand -->
+ <div *ngIf="(propType == derivedPropertyTypes.LIST || propType == derivedPropertyTypes.MAP) && !property.isChildOfListOrMap" class="table-cell"><span class="sprite-new add-item-icon" (click)="addRows()"></span></div>
+ <span *ngIf="property.isChildOfListOrMap" class="delete-span sprite-new delete-item-icon" (click)="deleteItem.emit(property.propertiesName)"></span>
+ <span *ngIf="propType == derivedPropertyTypes.COMPLEX || (property.isChildOfListOrMap && propChildren)" (click)="expandChildById(propPath)" class="expand-icon" [class.expanded]="propPath == expandedChildId">V</span>
+ </ng-container>
+
+</div>
+<!-- Now, recurse into children -->
+<ng-container *ngIf="propChildren && !property.isDeclared">
+ <ng-container *ngFor="let prop of propChildren | filterChildProperties: expandedChildId; trackBy:prop?.propertiesName">
+ <dynamic-property
+ [selectedPropertyId]="selectedPropertyId"
+ [canBeDeclared]="childrenCanBeDeclared"
+ [property]="prop"
+ [expandedChildId]="expandedChildId"
+ [propChildren]=""
+ (valueChanged)="propValueChanged(prop);"
+ (expandChild)="expandChildById($event)"
+ (deleteItem)="deleteListOrMapItem($event)"
+ (clickOnPropertyRow)="onClickPropertyRow($event)"
+ (checkProperty)="checkedChange($event)"
+ >
+ </dynamic-property>
+ </ng-container>
+</ng-container>
diff --git a/catalog-ui/src/app/ng2/components/properties-table/dynamic-property/dynamic-property.component.less b/catalog-ui/src/app/ng2/components/properties-table/dynamic-property/dynamic-property.component.less
new file mode 100644
index 0000000000..53cde3035a
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/properties-table/dynamic-property/dynamic-property.component.less
@@ -0,0 +1,48 @@
+.dynamic-property-row {
+ display:flex;
+ flex-direction:row;
+ position:relative;
+
+ .table-cell {
+ flex: 1 0 50%;
+ padding:5px;
+ position:relative;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+
+
+ &.full-width {
+ border-right:none;
+ flex: 0 0 100%;
+ }
+
+ &:first-child:not(:only-child) {
+ border-right:#d2d2d2 solid 1px;
+ overflow:hidden;
+ }
+
+
+ }
+ span.delete-item-icon{
+ position: absolute;
+ right: 25px;
+ top: 10px;
+ }
+ span.add-item-icon {
+ float:right;
+ }
+ span.expand-icon {
+ position: absolute;
+ top:6px;
+ right: 10px;
+ transition: 200ms transform ease-in-out;
+ }
+ span.expand-icon.expanded {
+ transform: rotate(-180deg);
+ }
+}
+.filtered {
+ /deep/ .checkbox-label-content{
+ background-color: yellow;
+ }
+}
diff --git a/catalog-ui/src/app/ng2/components/properties-table/dynamic-property/dynamic-property.component.ts b/catalog-ui/src/app/ng2/components/properties-table/dynamic-property/dynamic-property.component.ts
new file mode 100644
index 0000000000..0ca93a773f
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/properties-table/dynamic-property/dynamic-property.component.ts
@@ -0,0 +1,149 @@
+import {Component, Input, Output, EventEmitter} from "@angular/core";
+import { PropertyBEModel, PropertyFEModel, DerivedFEProperty, DerivedPropertyType, SchemaPropertyGroupModel, DataTypeModel } from "app/models";
+import { PROPERTY_DATA, PROPERTY_TYPES } from 'app/utils';
+import { PropertiesUtils } from "app/ng2/pages/properties-assignment/properties.utils";
+import { DataTypeService } from "../../../services/data-type.service";
+import { UUID } from "angular2-uuid";
+
+
+@Component({
+ selector: 'dynamic-property',
+ templateUrl: './dynamic-property.component.html',
+ styleUrls: ['./dynamic-property.component.less']
+})
+export class DynamicPropertyComponent {
+
+ derivedPropertyTypes = DerivedPropertyType; //http://stackoverflow.com/questions/35835984/how-to-use-a-typescript-enum-value-in-an-angular2-ngswitch-statement
+ propType: DerivedPropertyType;
+ propPath: string;
+ isPropertyFEModel: boolean;
+ mapOfIDsAndKeys: Map<string, string> = new Map(); //used for map and list
+
+ childrenCanBeDeclared: boolean;
+ @Input() canBeDeclared: boolean;
+ @Input() property: PropertyFEModel | DerivedFEProperty;
+ @Input() propChildren: Array<DerivedFEProperty>;
+ @Input() expandedChildId: string;
+ @Input() selectedPropertyId: string;
+
+ @Output() valueChanged: EventEmitter<any> = new EventEmitter<any>();
+ @Output() expandChild: EventEmitter<string> = new EventEmitter<string>();
+ @Output() checkProperty: EventEmitter<string> = new EventEmitter<string>();
+ @Output() deleteItem: EventEmitter<string> = new EventEmitter<string>();
+ @Output() clickOnPropertyRow: EventEmitter<PropertyFEModel | DerivedFEProperty> = new EventEmitter<PropertyFEModel | DerivedFEProperty>();
+
+ constructor(private propertiesUtils: PropertiesUtils, private dataTypeService: DataTypeService) {
+ }
+
+ ngOnInit() {
+ this.isPropertyFEModel = this.property instanceof PropertyFEModel;
+ if (this.property instanceof PropertyFEModel) {
+ this.propType = this.getDerivedPropertyType(this.property.type);
+ this.propPath = this.property.name;
+ } else {
+ this.propType = this.property.derivedDataType;
+ this.propPath = this.property.propertiesName;
+ }
+
+ this.childrenCanBeDeclared = this.canBeDeclared && this.propType != this.derivedPropertyTypes.MAP && this.propType != this.derivedPropertyTypes.LIST;
+
+ if (this.propType == this.derivedPropertyTypes.LIST || this.propType == this.derivedPropertyTypes.MAP) {
+ this.initializeValues();
+ }
+
+ }
+
+ initializeValues = () => {
+ let tempValue: any;
+ if (this.property.value) {
+ tempValue = JSON.parse(this.property.value);
+ if (!_.isEmpty(tempValue)) {
+ tempValue.forEach((element, key) => {
+ let newChildID: string = this.createNewChildProperty(JSON.stringify(element));
+ this.mapOfIDsAndKeys[newChildID] = key;
+ console.log(this.mapOfIDsAndKeys);
+ });
+ }
+ }
+ //this.pseudoChildren = [];
+ //this.valueObjRef = [];
+ //TODO: generate necessary elements for existing values here
+ // if (this.propType == this.derivedPropertyTypes.LIST) {
+ // this.valueObjRef = (this.property.value) ? JSON.parse(this.property.value) : [];
+ // } else if (this.propType == this.derivedPropertyTypes.MAP) {
+ // this.valueObjRef = (this.property.value)? JSON.parse(this.property.value) : {};
+ // }
+ console.log(this.property.value);
+ }
+
+ onClickPropertyRow = (property, event) => {
+ // Because DynamicPropertyComponent is recrusive second time the event is fire event.stopPropagation = undefined
+ event && event.stopPropagation && event.stopPropagation();
+ this.clickOnPropertyRow.emit(property);
+ }
+
+ deleteListOrMapItem = (itemName: string) => {
+ this.propChildren = this.propChildren.filter(prop => prop.propertiesName.indexOf(itemName) != 0); //remove item and children;
+ }
+
+ propValueChanged = (property) => {
+ console.log("property value change!! Prop type: " + property.type + " New value: " + property.value);
+ this.valueChanged.emit(property);
+ };
+
+ expandChildById = (id: string) => {
+ this.expandedChildId = id;
+ this.expandChild.emit(id);
+ }
+
+ checkedChange = (propName: string) => {
+ this.checkProperty.emit(propName);
+ }
+
+
+
+ addRows = (): void => { //from within the template, when creating empty item
+ let childPropId = this.createNewChildProperty();
+ this.expandChildById(this.propPath + "#" + childPropId);
+ }
+
+ createNewChildProperty = (value?:string):string => {
+ let propUUID:string = UUID.UUID();
+ let newProp: DerivedFEProperty;
+ if (this.propType == this.derivedPropertyTypes.LIST) { //for list - create new prop of schema type
+ newProp = new DerivedFEProperty(propUUID, this.propPath, this.property.schema.property.type, value, true);
+ } else { //for map - create new prop of type map, with schema, but with flag that its a child
+ newProp = new DerivedFEProperty(propUUID, this.propPath, this.property.type, value, true, this.property.schema);
+ }
+
+
+ this.propChildren = this.propChildren || [];
+ this.propChildren.push(newProp);
+
+ //if it's a complex type, add children properties
+ if (!this.property.schema.property.isSimpleType) {
+ let schemaDataType: DataTypeModel = this.dataTypeService.getDataTypeByTypeName(this.property.schema.property.type);
+ this.dataTypeService.getDerivedDataTypeProperties(schemaDataType, this.propChildren, newProp.propertiesName);
+ this.propertiesUtils.assignValuesRecursively(JSON.parse(value), this.propChildren, newProp.propertiesName);
+ console.log(JSON.stringify(this.propChildren));
+ }
+
+ return propUUID;
+ }
+
+
+
+ //TODO: remove this and move to somewhere central!! (or make all properties be the same type...)
+ getDerivedPropertyType = (type) => {
+ if (PROPERTY_DATA.SIMPLE_TYPES.indexOf(type) > -1) {
+ return DerivedPropertyType.SIMPLE;
+ } else if (type == PROPERTY_TYPES.LIST) {
+ return DerivedPropertyType.LIST;
+ } else if (type == PROPERTY_TYPES.MAP) {
+ return DerivedPropertyType.MAP;
+ } else {
+ return DerivedPropertyType.COMPLEX;
+ }
+ }
+
+}
diff --git a/catalog-ui/src/app/ng2/components/properties-table/list-property/list-property.component.html b/catalog-ui/src/app/ng2/components/properties-table/list-property/list-property.component.html
new file mode 100644
index 0000000000..a251d33649
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/properties-table/list-property/list-property.component.html
@@ -0,0 +1,33 @@
+<div class="add-data-row">
+ <div class="sprite-new add-item-icon" (click)="addListItem()"></div>
+</div>
+<div *ngIf="property.schema.property.isSimpleType && property.valueObjectRef && property.valueObjectRef.length">
+ <!--the ngFor runs on dummy array in the list array length and not on list array in order to prevent from page do the ngFor again when user changes an item-->
+ <div class="simple-list-item" *ngFor="let item of getNumber(property.valueObjectRef); let i = index">
+ <input class="value-input" [(ngModel)]="property.valueObjectRef[i]"
+ type="property.schema.property.derivedFromSimpleTypeName || property.schema.property.type"
+ (change)="propValueChanged()"/>
+ <span class="delete-span sprite-new delete-item-icon" (click)="deleteListItem(i)"></span>
+ </div>
+</div>
+<div class="test" *ngIf="property.schema.property.isDataType && property.childrenProperties && property.childrenProperties.length">
+ <template ngFor let-item [ngForOf]="property.childrenProperties" let-i="index">
+ <div class="table-inner-row" (click)="onChildPropertySelected(item)" [ngClass]="{'selected': selectedPropertyId === item.treeNodeId}">
+ <div class="table-cell">{{item.name}}</div>
+ <div class="table-cell">
+ <span class="delete-span sprite-new delete-item-icon" (click)="deleteListItem(i)"></span>
+ <span (click)="property.updateExpandedChildPropertyId(item.treeNodeId)">V</span>
+ </div>
+ </div>
+ <div class="table-inner-row" *ngIf="property.expandedChildPropertyId == item.treeNodeId">
+ <div class="inner-table-container">
+ <properties-value-inner-table [property]="item"
+ (selectChildProperty)="onChildPropertySelected($event)"
+ [selectedPropertyId]="selectedPropertyId"
+ [propertyNameSearchText]="propertyNameSearchText"
+ (valueChanged)="propValueChanged()"></properties-value-inner-table>
+ </div>
+ </div>
+ </template>
+
+</div>
diff --git a/catalog-ui/src/app/ng2/components/properties-table/list-property/list-property.component.less b/catalog-ui/src/app/ng2/components/properties-table/list-property/list-property.component.less
new file mode 100644
index 0000000000..7c4d90a38d
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/properties-table/list-property/list-property.component.less
@@ -0,0 +1,3 @@
+.simple-list-item{
+ position: relative;
+}
diff --git a/catalog-ui/src/app/ng2/components/properties-table/list-property/list-property.component.ts b/catalog-ui/src/app/ng2/components/properties-table/list-property/list-property.component.ts
new file mode 100644
index 0000000000..96f8c680a2
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/properties-table/list-property/list-property.component.ts
@@ -0,0 +1,85 @@
+/**
+ * Created by rc2122 on 4/23/2017.
+ */
+import {Component, Input, Output, EventEmitter} from "@angular/core";
+import { PropertyFEModel} from "app/models";
+import {PropertiesService} from "app/ng2/services/properties.service";
+import { ContentAfterLastDotPipe } from "app/ng2/pipes/contentAfterLastDot.pipe";
+import {UUID} from "angular2-uuid";
+import {ComponentType} from "app/utils";
+
+@Component({
+ selector: 'list-property',
+ templateUrl: './list-property.component.html',
+ styleUrls: ['../properties-value-inner-table/properties-value-inner-table.component.less', './list-property.component.less']
+})
+export class ListPropertyComponent {
+
+ @Input() property: PropertyFEModel;
+ @Input() selectedPropertyId: string;
+ @Input() propertyNameSearchText:string;
+
+ @Output() valueChanged: EventEmitter<any> = new EventEmitter<any>();
+ @Output() selectChildProperty: EventEmitter<any> = new EventEmitter<PropertyFEModel>();
+
+ constructor ( private propertiesService:PropertiesService, private contentAfterLastDotPipe:ContentAfterLastDotPipe ){
+ }
+
+ propValueChanged = () => {
+ this.valueChanged.emit(this.property);
+ };
+
+ onChildPropertySelected = (property) => {
+ this.selectChildProperty.emit(property);
+ };
+
+ getNumber = (valueObjectRef: any): Array<any> => {
+ let num: number = (valueObjectRef) ? valueObjectRef.length : 0;
+ return new Array(num);
+ }
+
+ createNewChildProperty = ():void => {
+ let newProperty: PropertyFEModel = new PropertyFEModel(this.contentAfterLastDotPipe.transform(this.property.schema.property.type),
+ this.property.schema.property.type,
+ UUID.UUID(),
+ this.property,
+ this.property.valueObjectRef[this.property.childrenProperties.length]
+ );
+ this.propertiesService.createPropertiesTreeForProp(newProperty);
+ this.property.childrenProperties.push(newProperty);
+ }
+
+ addListItem = ():void => {
+ this.property.valueObjectRef = this.property.valueObjectRef || [];
+ this.property.childrenProperties = this.property.childrenProperties || [];
+ if (this.property.schema.property.isSimpleType){
+ if( this.property.valueObjectRef.indexOf("") == -1 ) {//prevent insert multiple empty simple type items to list
+ this.property.valueObjectRef.push("");
+ }
+ }else{
+ this.property.valueObjectRef[this.property.childrenProperties.length] = {};
+ this.property.childrenProperties = this.property.childrenProperties || [];
+ this.createNewChildProperty();
+ this.valueChanged.emit(this.property);
+ }
+ }
+
+ deleteListItem = (indexInList:number):void => {
+ this.property.valueObjectRef.splice(indexInList, 1);
+ if(this.property.childrenProperties){
+ this.property.childrenProperties.splice(indexInList, 1);
+ }
+ if (!this.property.valueObjectRef.length) {//only when user removes all items from list - put the default
+ if ( this.property.defaultValue ) {
+ angular.copy(JSON.parse(this.property.defaultValue), this.property.valueObjectRef);
+ if (this.property.schema.property.isDataType){
+ _.forEach(this.property.valueObjectRef, () => {
+ this.createNewChildProperty();
+ });
+ }
+ }
+ }
+ this.valueChanged.emit(this.property);
+ }
+
+}
diff --git a/catalog-ui/src/app/ng2/components/properties-table/map-property/map-property.component.html b/catalog-ui/src/app/ng2/components/properties-table/map-property/map-property.component.html
new file mode 100644
index 0000000000..e1975175a8
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/properties-table/map-property/map-property.component.html
@@ -0,0 +1,38 @@
+<div class="add-data-row">
+ <div class="sprite-new add-item-icon" (click)="addMapItemFields()"></div>
+</div>
+
+<!--the ngFor runs on dummy array in mapKey array length and not on maKeys array in order to prevent from page do the ngFor again when user changes a key-->
+<template ngFor let-num [ngForOf]="getNumber(mapKeys.length)" let-i="index">
+ <div class="table-inner-row"
+ [ngClass]="{'selected': property.schema.property.isDataType && selectedPropertyId === property.childrenProperties[i].treeNodeId}"
+ (click)="property.schema.property.isDataType && onChildPropertySelected(property.childrenProperties[i])">
+ <div class="table-cell">
+ <input class="value-input" (keyup)="changeKeyOfMap(mapKeys[i], i);$event.stopPropagation();"
+ [(ngModel)]="mapKeys[i]"
+ name="mapKey{{property.treeNodeId}}{{i}}"
+ (change)="propValueChanged()"/>
+ </div>
+ <div class="table-cell">
+ <input class="value-input" *ngIf="property.schema.property.isSimpleType"
+ [(ngModel)]="property.valueObjectRef[mapKeys[i]]"
+ type="property.schema.property.derivedFromSimpleTypeName || property.schema.property.type"
+ (change)="propValueChanged()"/>
+ <div *ngIf="property.schema.property.isDataType">
+ <div>{{ property.schema.property.type | contentAfterLastDot }}</div>
+ <span (click)="property.updateExpandedChildPropertyId(property.childrenProperties[i].treeNodeId)">V</span>
+ </div>
+ <span class="delete-span sprite-new delete-item-icon" (click)="deleteMapItem(i)"></span>
+ </div>
+ </div>
+ <div class="table-inner-row" *ngIf="property.schema.property.isDataType && property.expandedChildPropertyId == property.childrenProperties[i].treeNodeId">
+ <div class="inner-table-container">
+ <properties-value-inner-table [property]="property.childrenProperties[i]"
+ [selectedPropertyId]="selectedPropertyId"
+ [propertyNameSearchText]="propertyNameSearchText"
+ (selectChildProperty)="onChildPropertySelected($event)"
+ (valueChanged)="propValueChanged()"></properties-value-inner-table>
+ </div>
+ </div>
+</template>
+
diff --git a/catalog-ui/src/app/ng2/components/properties-table/map-property/map-property.component.ts b/catalog-ui/src/app/ng2/components/properties-table/map-property/map-property.component.ts
new file mode 100644
index 0000000000..d62d0b94e3
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/properties-table/map-property/map-property.component.ts
@@ -0,0 +1,121 @@
+/**
+ * Created by rc2122 on 4/24/2017.
+ */
+/**
+ * Created by rc2122 on 4/23/2017.
+ */
+import {Component, Input, Output, EventEmitter} from "@angular/core";
+import { PropertyFEModel} from "app/models";
+import { PropertiesService } from "../../../services/properties.service";
+import {ComponentType} from "app/utils";
+import {UUID} from "angular2-uuid";
+
+@Component({
+ selector: 'map-property',
+ templateUrl: './map-property.component.html',
+ styleUrls: ['../properties-value-inner-table/properties-value-inner-table.component.less']
+})
+export class MapPropertyComponent {
+
+ @Input() property: PropertyFEModel;
+ @Input() selectedPropertyId: string;
+ @Input() propertyNameSearchText:string;
+
+ @Output() valueChanged: EventEmitter<any> = new EventEmitter<any>();
+ @Output() selectChildProperty: EventEmitter<any> = new EventEmitter<PropertyFEModel>();
+
+ constructor ( private propertiesService:PropertiesService){
+ }
+
+ mapKeys:Array<string>;
+
+ ngOnInit() {
+ this.mapKeys = Object.keys(this.property.valueObjectRef);
+ }
+
+ propValueChanged = () => {
+ this.valueChanged.emit(this.property);
+ };
+
+ onChildPropertySelected = (property) => {
+ this.selectChildProperty.emit(property);
+ };
+
+ getNumber = (num:number):Array<any> => {
+ return new Array(num);
+ }
+
+ createNewChildProperty = (mapKey:string):void => {
+
+ let newProperty: PropertyFEModel = new PropertyFEModel(mapKey,
+ this.property.schema.property.type,
+ UUID.UUID(), this.property,
+ this.property.valueObjectRef[mapKey]);
+ this.propertiesService.createPropertiesTreeForProp(newProperty);
+ this.property.childrenProperties = this.property.childrenProperties || [];
+ this.property.childrenProperties.push(newProperty);
+ }
+
+ //get: new key and the index of this item in the map
+ //This method checks if the new key isn't exist already in the map and update the object and the children array with the new key
+ changeKeyOfMap = (newKey:string, index:number):void => {
+ //let fieldName:string = "mapKey" + this.property.treeNodeId + index;
+ let oldKey:string = Object.keys(this.property.valueObjectRef)[index];
+ let existsKeyIndex:number = Object.keys(this.property.valueObjectRef).indexOf(newKey);
+ if (existsKeyIndex > -1 && existsKeyIndex != index) {
+ //error for exists key validation
+ } else {
+ //remove error for exists key validation and if the form is valid - update the map object
+ let newObj = {};
+ angular.forEach(this.property.valueObjectRef,function(value:any,key:string){
+ if(key == oldKey){
+ newObj[newKey] = value;
+ }else{
+ newObj[key] = value;
+ }
+ });
+ this.property.valueObjectRef = newObj;
+ this.property.parent.valueObjectRef[this.property.name] = this.property.valueObjectRef;//in order to prevent break ref
+ if(this.property.childrenProperties){
+ this.property.childrenProperties[index].name = newKey;//update this property childrenProperties with the new key
+ }
+ }
+ }
+
+ //get: index of the item in the map
+ //This method removes item from map.
+ deleteMapItem = (index:number):void=> {
+ delete this.property.valueObjectRef[this.mapKeys[index]];
+ this.mapKeys.splice(index, 1);
+ if(this.property.childrenProperties){
+ this.property.childrenProperties.splice(index, 1);
+ }
+ if (!this.mapKeys.length) {//only when user removes all pairs of key-value fields - put the default
+ if (this.property.defaultValue) {
+ angular.copy(JSON.parse(this.property.defaultValue), this.property.valueObjectRef);
+ this.mapKeys = Object.keys(this.property.valueObjectRef);
+ if (this.property.schema.property.isDataType){
+ angular.forEach(this.property.valueObjectRef, (value, key) => {
+ this.createNewChildProperty(key);
+ }, this);
+ }
+ }
+ }
+ this.valueChanged.emit(this.property);
+ }
+
+ //This method inserts new empty item to map
+ addMapItemFields = ():void => {
+ this.property.valueObjectRef = this.property.valueObjectRef || {};
+ if (this.property.schema.property.isSimpleType){
+ this.property.valueObjectRef[''] = null;
+ }else{
+ if(!this.property.valueObjectRef['']){
+ this.property.valueObjectRef[''] = {};
+ this.createNewChildProperty('');
+ }
+ }
+ this.mapKeys = Object.keys(this.property.valueObjectRef);
+ }
+}
+
diff --git a/catalog-ui/src/app/ng2/components/properties-table/properties-table.component.html b/catalog-ui/src/app/ng2/components/properties-table/properties-table.component.html
new file mode 100644
index 0000000000..3ab47074e7
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/properties-table/properties-table.component.html
@@ -0,0 +1,135 @@
+
+
+<div class="properties-table">
+ <div class="table-header">
+ <div class="table-cell col1">Property Name</div>
+ <div class="table-cell col2">Type</div>
+ <div class="table-cell col3">ES</div>
+ <div class="table-cell valueCol">Value</div>
+ </div>
+ <div class="table-body">
+ <div class="no-data" *ngIf="!feInstancesNames">No data to display</div>
+
+ <div *ngFor="let instanceName of feInstancesNames; trackBy:instanceName">
+ <div class="table-rows-header">{{instanceName | contentAfterLastDot}}</div>
+
+ <div class="table-row" *ngFor="let property of fePropertiesMap[instanceName]; trackBy:property?.name" (click)="onClickPropertyRow(property, instanceName, $event)" [ngClass]="{'selected': selectedPropertyId === property.uniqueId}">
+ <div class="table-cell col1">
+ <checkbox [label]="property.name"
+ [(checked)]="property.isSelected"
+ [disabled]="property.isDisabled || property.isDeclared"
+ (checkedChange)="propertyChecked(property)"
+ tooltip="{{property.name}}"></checkbox>
+ <span *ngIf="property.description" class="property-description-icon sprite-new show-desc" tooltip="{{property.description}}"></span>
+ </div>
+ <div class="table-cell col2">{{property.type | contentAfterLastDot}}</div>
+ <div class="table-cell col3">{{property.schema && property.schema.property && property.schema.property.type ? (property.schema.property.type
+ | contentAfterLastDot) : ''}}</div>
+ <div class="table-cell valueCol">
+ <!-- [ngClass]="{'filtered':property.name === propertyNameSearchText}" (selectProperty)="propertySelected(property, $event, flatProperty.propertiesName)" [propType]="property.type" [propSchema]="property.schema" [propKey]="" [propValue]="property.value"-->
+ <dynamic-property
+ [selectedPropertyId]="selectedPropertyId"
+ [canBeDeclared]="true"
+ [property]="property"
+ [expandedChildId]="property.expandedChildPropertyId"
+ [propChildren]="property.flattenedChildren | filterChildProperties : property.expandedChildPropertyId"
+ (valueChanged)="propValueChanged(property);"
+ (expandChild)="property.updateExpandedChildPropertyId($event)"
+ (clickOnPropertyRow)="onClickPropertyInnerRow($event, instanceName)"
+ (checkProperty)="propertyChecked(property, $event)"
+ >
+ </dynamic-property>
+
+ </div>
+ </div>
+<!--
+ <div *ngIf="!property.isSimpleType && !property.isDeclared" class="table-cell valueCol child-property-container">
+
+ <div class="child-property-row" *ngFor="let flatProperty of property.flattenedChildren | filterChildProperties : property.expandedChildPropertyId"
+ [ngClass]="{'selected': selectedPropertyId === flatProperty.uniqueId}" (click)="clickOnPropertyRow(flatProperty, instanceName, $event)" [@fadeIn]="''">
+ <derived-property [propertyObj]="flatProperty" [propertyNameSearchText]="propertyNameSearchText" [expanded]="flatProperty.propertiesName == property.expandedChildPropertyId"
+ (selectProperty)="propertySelected(property, $event, flatProperty.propertiesName)" (valueChanged)="propValueChanged(property)" (expandChild)="property.updateExpandedChildPropertyId($event)"></derived-property>
+ </div>
+
+ </div>
+ <!--
+
+
+ <property [propertyObj]="flatProperty"
+ [expanded]="flatProperty.parentName == property.expandedChildPropertyId"
+ (valueChanged)="propValueChanged($event)"
+ (selectChildProperty)="onChildPropertySelected($event)"></property>
+ <list-property *ngIf="property.type == 'list'"
+ [property]="property"
+ [selectedPropertyId]="selectedPropertyId"
+ (valueChanged)="propValueChanged($event)"
+ (selectChildProperty)="onChildPropertySelected($event)"></list-property>
+ <map-property *ngIf="property.type == 'map'"
+ [property]="property"
+ [selectedPropertyId]="selectedPropertyId"
+ (valueChanged)="propValueChanged($event)"
+ (selectChildProperty)="onChildPropertySelected($event)"></map-property>
+ <properties-value-inner-table *ngIf="property.isDataType"
+ [property]="property"
+ [selectedPropertyId]="selectedPropertyId"
+ (selectChildProperty)="onChildPropertySelected($event)"
+ (valueChanged)="propValueChanged($event)"></properties-value-inner-table>
+ -->
+
+
+
+ </div>
+
+ </div>
+</div>
+<!--
+<div class="properties-table" style="display:block">
+ <div class="table-header">
+ <div class="table-cell col1">Property Name</div>
+ <div class="table-cell col2">Type</div>
+ <div class="table-cell col3">ES</div>
+ <div class="table-cell valueCol">Value</div>
+ </div>
+ <div class="table-body">
+ <div class="no-data" *ngIf="!properties || !properties.length">No data to display</div>
+ <div class="table-row" *ngFor="let property of properties" (click)="clickOnPropertyRow(property)">
+ <div class="table-cell col1"><checkbox [label]="property.name" [(checked)]="property.isSelected" (checkedChange)="propSelected(property)" [disabled]="property.isDisabled"></checkbox></div>
+ <div class="table-cell col2">{{property.type | contentAfterLastDot}}</div>
+ <div class="table-cell col3">{{property.schema && property.schema.property && property.schema.property.type ? (property.schema.property.type | contentAfterLastDot) : ''}}</div>
+ <div class="table-cell valueCol" [class.inner-table-container]="property.childrenProperties || !property.isSimpleType">
+ <!--<input class="value-input" *ngIf="property.isSimpleType"
+ type="property.derivedFromSimpleTypeName || property.type"
+ [(ngModel)]="property.value"
+ (change)="putDefaultValueInEmptyProperty(property);propValueChanged(property);"
+ pattern="validationUtils.getValidationPattern(property.type)"/>
+ <dynamic-element
+ class="value-input"
+ *ngIf="property.isSimpleType"
+ [(value)]="property.value"
+ (valueChange)="putDefaultValueInEmptyProperty(property);propValueChanged(property);"
+ [type]="property.derivedFromSimpleTypeName || property.type"
+ [name]="property.name">
+ </dynamic-element>
+ <list-property *ngIf="property.type == 'list'"
+ [property]="property"
+ [selectedPropertyId]="selectedPropertyId"
+ (valueChanged)="propValueChanged($event)"
+ (selectChildProperty)="onChildPropertySelected($event)"></list-property>
+ <map-property *ngIf="property.type == 'map'"
+ [property]="property"
+ [selectedPropertyId]="selectedPropertyId"
+ (valueChanged)="propValueChanged($event)"
+ (selectChildProperty)="onChildPropertySelected($event)"></map-property>
+ <properties-value-inner-table *ngIf="property.isDataType"
+ [property]="property"
+ [selectedPropertyId]="selectedPropertyId"
+ (selectChildProperty)="onChildPropertySelected($event)"
+ (valueChanged)="propValueChanged($event)"></properties-value-inner-table>
+ </div>
+
+ </div>
+ </div>
+</div> -->
+
+
+
diff --git a/catalog-ui/src/app/ng2/components/properties-table/properties-table.component.less b/catalog-ui/src/app/ng2/components/properties-table/properties-table.component.less
new file mode 100644
index 0000000000..de080dfdc9
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/properties-table/properties-table.component.less
@@ -0,0 +1,188 @@
+
+@import './../../../../assets/styles/variables.less';
+
+:host /deep/ input { width:100%;}
+
+.properties-table {
+ display:flex;
+ flex-direction:column;
+ flex: 1;
+ height:100%;
+ text-align:left;
+
+
+ .child-property-container {
+ display:flex;
+ flex-direction:column;
+
+ &.table-cell {
+ padding:0;
+ }
+
+ .child-property-row {
+ border-bottom: #d2d2d2 solid 1px;
+ &:last-child {
+ border-bottom:none;
+ }
+ }
+ }
+
+
+ derived-property, dynamic-property {
+ width:100%;
+ }
+
+ /deep/ dynamic-property dynamic-property .dynamic-property-row {
+ border-top:solid #d2d2d2 1px;
+ }
+
+ /deep/ dynamic-property dynamic-property:first-of-type .dynamic-property-row:not(.with-top-border) {
+ border-top: none;
+ }
+
+ properties-value-inner-table {
+ width: 100%;
+ }
+
+ .table-header {
+ font-weight:bold;
+ border-top: #d2d2d2 solid 1px;
+ background-color: #eaeaea;
+
+ .valueCol {
+ justify-content: flex-start;
+ padding: 5px;
+ }
+ }
+ .table-header, .table-row {
+ display: flex;
+ flex-direction:row;
+ flex: 0 0 auto;
+ }
+
+ .table-body {
+ display:flex;
+ flex-direction: column;
+ overflow-y:auto;
+ flex: 1;
+
+ .no-data {
+ border: #d2d2d2 solid 1px;
+ border-top:none;
+ text-align: center;
+ height: 100%;
+ padding: 20px;
+ }
+ /deep/.selected{
+ background-color: #e6f6fb;
+ color: #009fdb;
+ }
+ }
+
+ .table-rows-header {
+ font-size:16px;
+ flex:1;
+ border: #d2d2d2 solid 1px;
+ border-top:none;
+ padding: 5px;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ overflow: hidden;
+ background-color: @tlv_color_v;
+ }
+
+ .table-row {
+ &:hover {
+ background-color:#f8f8f8; cursor:pointer;
+ }
+
+ &:last-child {
+ flex: 1 0 auto;
+ }
+ .selected-row {
+ background-color:#e6f6fb;
+ }
+ }
+ .table-cell {
+ font-size:13px;
+ flex:1;
+ border: #d2d2d2 solid 1px;
+ border-right:none;
+ border-top:none;
+ padding: 5px;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ overflow: hidden;
+
+ &:last-child {
+ border-right:#d2d2d2 solid 1px;
+ }
+ &.col1 {
+ flex: 0 0 300px;
+ max-width:300px;
+
+ .property-description-icon {
+ float: right;
+ margin-top: 4px;
+ }
+ }
+ &.col2 {
+ flex: 0 0 150px;
+ max-width:150px;
+ }
+
+ &.col3 {
+ flex:0 0 120px;
+ max-width:120px;
+ }
+
+ &.valueCol {
+ flex: 1 0 auto;
+ min-width: 350px;
+ display: flex;
+ justify-content: flex-end;
+ padding: 0px;
+
+ .value-input {
+ flex: 1;
+ max-height: 24px;
+ border: none;
+ background-color: inherit;
+
+ &:focus, &:active {
+ border:none;
+ outline:none;
+ }
+ }
+
+ .delete-btn {
+ flex: 0 0 auto;
+ }
+
+ .delete-button-container {
+ max-height: 24px;
+ }
+
+ &.inner-table-container {
+ padding: 0px;
+
+ .delete-button-container {
+ padding: 3px 5px 0 0 ;
+ }
+ }
+ }
+
+ &.input-value-col {
+ padding: 5px;
+ }
+
+
+ }
+
+ .filtered {
+ /deep/ .checkbox-label-content{
+ background-color: yellow;
+ }
+ }
+
+}
diff --git a/catalog-ui/src/app/ng2/components/properties-table/properties-table.component.ts b/catalog-ui/src/app/ng2/components/properties-table/properties-table.component.ts
new file mode 100644
index 0000000000..d5a9b40425
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/properties-table/properties-table.component.ts
@@ -0,0 +1,93 @@
+import { Component, Input, Output, EventEmitter, SimpleChanges, ViewChild, ElementRef } from "@angular/core";
+import { trigger, state, style, transition, animate} from '@angular/core';
+import {PropertyFEModel, DerivedFEProperty, DerivedPropertyType, InstanceFePropertiesMap} from "app/models";
+import {PropertiesService} from "../../services/properties.service";
+// import { GroupByPipe } from 'app/ng2/pipes/groupBy.pipe';
+//import {PropertiesValueInnerTableComponent} from "./properties-table/properties-value-inner-table/properties-value-inner-table";
+import { DynamicElementComponent } from 'app/ng2/components/dynamic-element/dynamic-element.component';
+import { KeysPipe } from 'app/ng2/pipes/keys.pipe';
+
+@Component({
+ selector: 'properties-table',
+ templateUrl: './properties-table.component.html',
+ styleUrls: ['./properties-table.component.less'],
+ animations: [trigger('fadeIn', [transition(':enter', [style({ opacity: '0' }), animate('.3s ease-out', style({ opacity: '1' }))]) ])]
+})
+export class PropertiesTableComponent {
+
+ @Input() fePropertiesMap: InstanceFePropertiesMap;
+ @Input() selectedPropertyId: string;
+ @Input() displayDeleteButton: boolean;
+ @Input() propertyNameSearchText:string;
+
+ @Output() valueChanged: EventEmitter<any> = new EventEmitter<any>();
+ @Output() selectPropertyRow: EventEmitter<PropertyRowSelectedEvent> = new EventEmitter<PropertyRowSelectedEvent>();
+ @Output() updateCheckedPropertyCount: EventEmitter<boolean> = new EventEmitter<boolean>();
+ //@Output() selectInstanceRow: EventEmitter<string> = new EventEmitter<string>();
+
+ feInstancesNames: Array<string>;
+
+ constructor ( private propertiesService:PropertiesService ){
+ }
+
+ /**
+ * Update feInstancesNames when fePropertiesMap: InstanceFePropertiesMap change (after getting response from server)
+ */
+ ngOnChanges(changes: SimpleChanges) {
+ if (changes['fePropertiesMap']) {
+ if (changes['fePropertiesMap'].currentValue) {
+ let keysPipe = new KeysPipe();
+ let fiteredArr = keysPipe.transform(changes['fePropertiesMap'].currentValue,[]);
+ this.feInstancesNames = fiteredArr;
+ }
+ }
+ }
+
+ propValueChanged = (property) => {
+ !property.isDeclared && this.valueChanged.emit(property);
+ };
+
+ // Click on main row (row of propertyFEModel)
+ onClickPropertyRow = (property:PropertyFEModel, instanceName:string, event?) => {
+ //event && event.stopPropagation();
+ let propertyRowSelectedEvent:PropertyRowSelectedEvent = new PropertyRowSelectedEvent(property, instanceName);
+ this.selectPropertyRow.emit(propertyRowSelectedEvent);
+ };
+
+ // Click on inner row (row of DerivedFEProperty)
+ onClickPropertyInnerRow = (property:DerivedFEProperty, instanceName:string) => {
+ let propertyRowSelectedEvent:PropertyRowSelectedEvent = new PropertyRowSelectedEvent(property, instanceName);
+ this.selectPropertyRow.emit(propertyRowSelectedEvent);
+ }
+
+ propertyChecked = (prop: PropertyFEModel, childPropName?: string) => {
+ let isChecked: boolean = (!childPropName)? prop.isSelected : prop.flattenedChildren.find(prop => prop.propertiesName == childPropName).isSelected;
+
+ console.log(isChecked, childPropName, prop);
+ if (!isChecked) {
+ this.propertiesService.undoDisableRelatedProperties(prop, childPropName);
+ } else {
+ this.propertiesService.disableRelatedProperties(prop, childPropName);
+ }
+ this.updateCheckedPropertyCount.emit(isChecked);
+ }
+
+ putDefaultValueInEmptyProperty = (property:PropertyFEModel):void => {
+ property.value = property.value || property.defaultValue;
+ }
+
+ // clickOnInstanceRow = (instanceName:string) =>{
+ // this.selectInstanceRow.emit(instanceName);
+ // };
+
+}
+
+export class PropertyRowSelectedEvent {
+ propertyModel:PropertyFEModel | DerivedFEProperty;
+ instanceName:string;
+ constructor ( propertyModel:PropertyFEModel | DerivedFEProperty, instanceName:string ){
+ this.propertyModel = propertyModel;
+ this.instanceName = instanceName;
+ }
+}
+
diff --git a/catalog-ui/src/app/ng2/components/properties-table/properties-value-inner-table/properties-value-inner-table.component.html b/catalog-ui/src/app/ng2/components/properties-table/properties-value-inner-table/properties-value-inner-table.component.html
new file mode 100644
index 0000000000..61555cac50
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/properties-table/properties-value-inner-table/properties-value-inner-table.component.html
@@ -0,0 +1,41 @@
+
+<template ngFor let-childProp [ngForOf]="property.childrenProperties" let-i="index">
+ <div class="table-inner-row" (click)="onChildPropertySelected(childProp)" [ngClass]="{'selected': selectedPropertyId === childProp.treeNodeId}">
+ <div class="table-cell" [ngClass]="{'filtered':childProp.name === propertyNameSearchText}">
+ <checkbox [label]="childProp.name" [(checked)]="childProp.isSelected" [disabled]="property.isDisabled"></checkbox>
+ </div>
+ <div class="table-cell prop-value">
+ <input class="value-input" *ngIf="childProp.isSimpleType"
+ [(ngModel)]="property.valueObjectRef[childProp.name]"
+ (change)="putDefaultValueInEmptyChildProperty(childProp);propValueChanged();"
+ type="childProp.derivedFromSimpleTypeName || childProp.type"/>
+ <span class="datatype-text" *ngIf="childProp.isDataType">{{ childProp.type | contentAfterLastDot }}</span>
+ <span *ngIf="!childProp.isSimpleType" (click)="property.updateExpandedChildPropertyId(childProp.treeNodeId)">V</span>
+ </div>
+ </div>
+ <div class="table-inner-row" *ngIf="childProp.type === 'list' && property.expandedChildPropertyId === childProp.treeNodeId">
+ <list-property [property]="childProp"
+ [selectedPropertyId]="selectedPropertyId"
+ [propertyNameSearchText]="propertyNameSearchText"
+ (valueChanged)="propValueChanged()"
+ (selectChildProperty)="onChildPropertySelected($event)"></list-property>
+
+ </div>
+ <div class="table-inner-row" *ngIf="childProp.type === 'map' && property.expandedChildPropertyId == childProp.treeNodeId">
+ <map-property [property]="childProp"
+ [selectedPropertyId]="selectedPropertyId"
+ [propertyNameSearchText]="propertyNameSearchText"
+ (valueChanged)="propValueChanged()"
+ (selectChildProperty)="onChildPropertySelected($event)"></map-property>
+
+ </div>
+ <div class="table-inner-row" *ngIf="childProp.isDataType && property.expandedChildPropertyId == childProp.treeNodeId">
+ <properties-value-inner-table [property]="childProp"
+ [selectedPropertyId]="selectedPropertyId"
+ [propertyNameSearchText]="propertyNameSearchText"
+ (selectChildProperty)="onChildPropertySelected($event)"
+ (valueChanged)="propValueChanged()"></properties-value-inner-table>
+ </div>
+</template>
+
+
diff --git a/catalog-ui/src/app/ng2/components/properties-table/properties-value-inner-table/properties-value-inner-table.component.less b/catalog-ui/src/app/ng2/components/properties-table/properties-value-inner-table/properties-value-inner-table.component.less
new file mode 100644
index 0000000000..1b7f6d4cd1
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/properties-table/properties-value-inner-table/properties-value-inner-table.component.less
@@ -0,0 +1,71 @@
+table { width:100%;}
+tr {border-bottom: #d2d2d2 solid 1px;}
+tr:last-child { border-bottom:none;}
+td { border:none; padding:5px;}
+td:first-child { border-right:#d2d2d2 solid 1px;}
+
+.prop-value{
+ span {
+ position: absolute;
+ top: 5px;
+ right: 2px;
+
+ &.delete-span {
+ right:20px;
+ }
+
+ &.datatype-text {
+ position:static;
+ }
+
+ }
+}
+
+.add-data-row {
+ padding:5px;
+ text-align:right;
+ border-bottom: #d2d2d2 solid 1px;
+
+ &:last-child {
+ border-bottom:none;
+ }
+}
+.table-inner-row {
+ display:flex;
+ flex-direction:row;
+ border-bottom: #d2d2d2 solid 1px;
+ flex: 0 0 100%;
+ position:relative;
+
+ &:last-child {
+ border-bottom:none;
+ }
+
+ .table-cell {
+ flex: 0 0 50%;
+ padding:5px;
+ position:relative;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+
+ &:first-child {
+ border-right:#d2d2d2 solid 1px;
+ overflow:hidden;
+ }
+
+
+ }
+
+ .table-inner-container, .inner-table-container {
+ flex: 0 0 100%;
+ }
+}
+/deep/ map-property, /deep/ properties-value-inner-table, /deep/ list-property{
+ width:100%;
+}
+
+.filtered {
+ /deep/ .checkbox-label-content{
+ background-color: yellow;
+ }
+}
diff --git a/catalog-ui/src/app/ng2/components/properties-table/properties-value-inner-table/properties-value-inner-table.component.ts b/catalog-ui/src/app/ng2/components/properties-table/properties-value-inner-table/properties-value-inner-table.component.ts
new file mode 100644
index 0000000000..7d0b219ffe
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/properties-table/properties-value-inner-table/properties-value-inner-table.component.ts
@@ -0,0 +1,37 @@
+/**
+ * Created by rc2122 on 4/20/2017.
+ */
+import {Component, Input, Output, EventEmitter} from "@angular/core";
+import {PropertyFEModel} from "app/models";
+import {PropertiesService} from "../../../services/properties.service";
+
+@Component({
+ selector: 'properties-value-inner-table',
+ templateUrl: './properties-value-inner-table.component.html',
+ styleUrls: ['./properties-value-inner-table.component.less']
+})
+export class PropertiesValueInnerTableComponent {
+
+ @Input() property: PropertyFEModel;
+ @Input() selectedPropertyId: string;
+ @Input() propertyNameSearchText:string;
+
+ @Output() selectChildProperty: EventEmitter<any> = new EventEmitter<PropertyFEModel>();
+ @Output() valueChanged: EventEmitter<any> = new EventEmitter<any>();
+
+ constructor ( private propertiesService:PropertiesService){
+ }
+
+
+ onChildPropertySelected = (property) => {
+ this.selectChildProperty.emit(property);
+ };
+
+ propValueChanged = () => {
+ this.valueChanged.emit(this.property);
+ };
+
+ putDefaultValueInEmptyChildProperty = (childProp:PropertyFEModel):void => {
+ this.property.valueObjectRef[childProp.name] = this.property.valueObjectRef[childProp.name] || childProp.defaultValue;
+ }
+}
diff --git a/catalog-ui/src/app/ng2/components/tooltip/tooltip-content.component.html b/catalog-ui/src/app/ng2/components/tooltip/tooltip-content.component.html
new file mode 100644
index 0000000000..1fbf45e39f
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/tooltip/tooltip-content.component.html
@@ -0,0 +1,12 @@
+<div class="tooltip {{ placement }}"
+ [style.top]="top + 'px'"
+ [style.left]="left + 'px'"
+ [class.in]="isIn"
+ [class.fade]="isFade"
+ role="tooltip">
+ <div class="tooltip-arrow"></div>
+ <div class="tooltip-inner">
+ <ng-content></ng-content>
+ {{ content }}
+ </div>
+</div>
diff --git a/catalog-ui/src/app/ng2/components/tooltip/tooltip-content.component.less b/catalog-ui/src/app/ng2/components/tooltip/tooltip-content.component.less
new file mode 100644
index 0000000000..1ff496f840
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/tooltip/tooltip-content.component.less
@@ -0,0 +1,11 @@
+.tooltip-inner {
+ word-wrap: break-word;
+ max-width: 300px;
+}
+
+.tooltip.bottom .tooltip-arrow {
+ border-bottom-color: #000 !important;
+}
+
+
+
diff --git a/catalog-ui/src/app/ng2/components/tooltip/tooltip-content.component.ts b/catalog-ui/src/app/ng2/components/tooltip/tooltip-content.component.ts
new file mode 100644
index 0000000000..6e3e8065bb
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/tooltip/tooltip-content.component.ts
@@ -0,0 +1,195 @@
+import {Component, AfterViewInit, Input, ElementRef, ChangeDetectorRef} from "@angular/core";
+
+@Component
+({
+ selector: "tooltip-content",
+ templateUrl: "./tooltip-content.component.html",
+ styleUrls: ["./tooltip-content.component.less"]
+})
+
+export class TooltipContentComponent implements AfterViewInit {
+
+ // -------------------------------------------------------------------------
+ // Inputs / Outputs
+ // -------------------------------------------------------------------------
+
+ @Input() hostElement: HTMLElement;
+ @Input() content: string;
+ @Input() placement: "top"|"bottom"|"left"|"right" = "bottom";
+ @Input() animation: boolean = true;
+
+ // -------------------------------------------------------------------------
+ // Properties
+ // -------------------------------------------------------------------------
+
+ top: number = -100000;
+ left: number = -100000;
+ isIn: boolean = false;
+ isFade: boolean = false;
+
+ // -------------------------------------------------------------------------
+ // Constructor
+ // -------------------------------------------------------------------------
+
+ constructor(private element: ElementRef,
+ private cdr: ChangeDetectorRef) {
+ }
+
+ // -------------------------------------------------------------------------
+ // Lifecycle callbacks
+ // -------------------------------------------------------------------------
+
+ ngAfterViewInit(): void {
+ this.show();
+ this.cdr.detectChanges();
+ }
+
+ // -------------------------------------------------------------------------
+ // Public Methods
+ // -------------------------------------------------------------------------
+
+ show(): void {
+ if(!this.hostElement) {
+ return;
+ }
+
+ const position = this.positionElement(this.hostElement, this.element.nativeElement.children[0], this.placement);
+ this.top = position.top;
+ this.left = position.left;
+ this.isIn = true;
+ if (this.animation) {
+ this.isFade = true;
+ }
+ }
+
+ hide(): void {
+ this.top = -100000;
+ this.left = -100000;
+ this.isIn = true;
+ if(this.animation) {
+ this.isFade = false;
+ }
+ }
+
+ // -------------------------------------------------------------------------
+ // Private Methods
+ // -------------------------------------------------------------------------
+
+ private positionElement(hostElem: HTMLElement, targetElem: HTMLElement, positionStr: string, appendToBody: boolean = false): {top: number, left: number} {
+ let positionStrParts = positionStr.split("-");
+ let pos0 = positionStrParts[0];
+ let pos1 = positionStrParts[1] || "center";
+ let hostElemPosition = appendToBody ? this.offset(hostElem) : this.position(hostElem);
+ let targetElemWidth = targetElem.offsetWidth;
+ let targetElemHeight = targetElem.offsetHeight;
+ let shiftWidth: any = {
+ center(): number {
+ return hostElemPosition.left + hostElemPosition.width / 2 - targetElemWidth / 2;
+ },
+ left(): number {
+ return hostElemPosition.left;
+ },
+ right(): number {
+ return hostElemPosition.left + hostElemPosition.width;
+ }
+ };
+
+ let shiftHeight: any = {
+ center: function (): number {
+ return hostElemPosition.top + hostElemPosition.height / 2 - targetElemHeight / 2;
+ },
+ top: function (): number {
+ return hostElemPosition.top;
+ },
+ bottom: function (): number {
+ return hostElemPosition.top + hostElemPosition.height;
+ }
+ }
+
+ let targetElemPosition: {top: number, left: number};
+
+ switch (pos0) {
+ case "right":
+ targetElemPosition = {
+ top: shiftHeight[pos1](),
+ left: shiftWidth[pos0]()
+ };
+ break;
+
+ case "left":
+ targetElemPosition = {
+ top: shiftHeight[pos1](),
+ left: hostElemPosition.left - targetElemWidth
+ };
+ break;
+
+ case "bottom":
+ targetElemPosition = {
+ top: shiftHeight[pos0](),
+ left: shiftWidth[pos1]()
+ };
+ break;
+
+ default:
+ targetElemPosition = {
+ top: hostElemPosition.top - targetElemHeight,
+ left: shiftWidth[pos1]()
+ };
+ break;
+ }
+
+ return targetElemPosition;
+ }
+
+
+ private position(nativeElem: HTMLElement): {width: number, height: number, top: number, left: number} {
+ let offsetParentCBR = {top: 0, left: 0};
+ const elemBCR = this.offset(nativeElem);
+ const offsetParentElem = this.parentOffsetElem(nativeElem);
+ if(offsetParentElem !== window.document) {
+ offsetParentCBR = this.offset(offsetParentElem);
+ offsetParentCBR.top += offsetParentElem.clientTop - offsetParentElem.scrollTop;
+ offsetParentCBR.left += offsetParentElem.clientLeft - offsetParentElem.scrollTop;
+ }
+
+ const boundingClientRect = nativeElem.getBoundingClientRect();
+
+ return {
+ width: boundingClientRect.width || nativeElem.offsetWidth,
+ height: boundingClientRect.height || nativeElem.offsetHeight,
+ top: elemBCR.top - offsetParentCBR.top,
+ left: elemBCR.left - offsetParentCBR.left
+ };
+ }
+
+ private offset(nativeElem:any): {width: number, height: number, top: number, left: number} {
+ const boundingClientRect = nativeElem.getBoundingClientRect();
+ return {
+ width: boundingClientRect.width || nativeElem.offsetWidth,
+ height: boundingClientRect.height || nativeElem.offsetHeight,
+ top: boundingClientRect.top + (window.pageYOffset || window.document.documentElement.scrollTop),
+ left: boundingClientRect.left + (window.pageXOffset || window.document.documentElement.scrollLeft)
+ };
+ }
+
+ private getStyle(nativeElem: HTMLElement, cssProperty: string): string {
+ if(window.getComputedStyle) {
+ return (window.getComputedStyle(nativeElem) as any)[cssProperty];
+ }
+
+ return (nativeElem.style as any)[cssProperty];
+ }
+
+ private isStaticPositioned(nativeElem: HTMLElement): boolean {
+ return (this.getStyle(nativeElem, "position") || "static") === "static";
+ }
+
+ private parentOffsetElem(nativeElem: HTMLElement): any {
+ let offsetParent: any = nativeElem.offsetParent || window.document;
+ while (offsetParent && offsetParent !== window.document && this.isStaticPositioned(offsetParent)) {
+ offsetParent = offsetParent.offsetParent;
+ }
+
+ return offsetParent || window.document;
+ }
+}
diff --git a/catalog-ui/src/app/ng2/components/tooltip/tooltip.component.ts b/catalog-ui/src/app/ng2/components/tooltip/tooltip.component.ts
new file mode 100644
index 0000000000..e98b69003e
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/tooltip/tooltip.component.ts
@@ -0,0 +1,81 @@
+import {
+ Directive, ComponentRef, ViewContainerRef, ComponentFactoryResolver, Input, HostListener
+} from "@angular/core";
+import {TooltipContentComponent} from "./tooltip-content.component";
+
+@Directive ({
+ selector: "[tooltip]"
+})
+export class TooltipComponent {
+
+ // -------------------------------------------------------------------------
+ // Properties
+ // -------------------------------------------------------------------------
+
+ private tooltip: ComponentRef<TooltipContentComponent>;
+ private visible: boolean;
+
+ // -------------------------------------------------------------------------
+ // Constructor
+ // -------------------------------------------------------------------------
+
+ constructor(private viewContainerRef: ViewContainerRef,
+ private resolver: ComponentFactoryResolver) {
+ }
+
+ // -------------------------------------------------------------------------
+ // Inputs / Outputs
+ // -------------------------------------------------------------------------
+
+ @Input("tooltip") content: string|TooltipContentComponent;
+ @Input() tooltipDisabled: boolean;
+ @Input() tooltipAnimation: boolean = true;
+ @Input() tooltipPlacement: "top"|"bottom"|"left"|"right" = "bottom";
+
+ // -------------------------------------------------------------------------
+ // Public Methods
+ // -------------------------------------------------------------------------
+
+ @HostListener("mouseenter")
+ show(): void {
+ if(this.tooltipDisabled || this.visible || this.content === "") {
+ return;
+ }
+
+ this.visible = true;
+ if (typeof this.content === "string") {
+ const factory = this.resolver.resolveComponentFactory(TooltipContentComponent);
+ if (!this.visible) {
+ return;
+ }
+
+ this.tooltip = this.viewContainerRef.createComponent(factory);
+ this.tooltip.instance.hostElement = this.viewContainerRef.element.nativeElement;
+ this.tooltip.instance.content = this.content as string;
+ this.tooltip.instance.placement = this.tooltipPlacement;
+ this.tooltip.instance.animation = this.tooltipAnimation;
+ } else {
+ const tooltip = this.content as TooltipContentComponent;
+ tooltip.hostElement = this.viewContainerRef.element.nativeElement;
+ tooltip.placement = this.tooltipPlacement;
+ tooltip.animation = this.tooltipAnimation;
+ tooltip.show();
+ }
+ }
+
+ @HostListener("mouseleave")
+ hide(): void {
+ if (!this.visible) {
+ return;
+ }
+
+ this.visible = false;
+ if (this.tooltip) {
+ this.tooltip.destroy();
+ }
+ if (this.content instanceof TooltipContentComponent) {
+ (this.content as TooltipContentComponent).hide();
+ }
+ }
+}
+
diff --git a/catalog-ui/src/app/ng2/components/tooltip/tooltip.module.ts b/catalog-ui/src/app/ng2/components/tooltip/tooltip.module.ts
new file mode 100644
index 0000000000..69976da6af
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/tooltip/tooltip.module.ts
@@ -0,0 +1,25 @@
+import {NgModule} from "@angular/core";
+import {TooltipContentComponent} from "./tooltip-content.component";
+import {TooltipComponent} from "./tooltip.component";
+import {CommonModule} from "@angular/common";
+
+@NgModule({
+ declarations: [
+ TooltipComponent,
+ TooltipContentComponent,
+ ],
+ imports: [
+ CommonModule
+ ],
+ exports: [
+ TooltipComponent,
+ TooltipContentComponent,
+ ],
+ entryComponents: [
+ TooltipContentComponent
+ ],
+ providers: []
+})
+export class TooltipModule {
+
+}
diff --git a/catalog-ui/src/app/ng2/pages/page404/page404.component.html b/catalog-ui/src/app/ng2/pages/page404/page404.component.html
new file mode 100644
index 0000000000..d488587154
--- /dev/null
+++ b/catalog-ui/src/app/ng2/pages/page404/page404.component.html
@@ -0,0 +1,3 @@
+<div class="page404">
+ Page404
+</div>
diff --git a/catalog-ui/src/app/ng2/pages/page404/page404.component.less b/catalog-ui/src/app/ng2/pages/page404/page404.component.less
new file mode 100644
index 0000000000..2672f22f27
--- /dev/null
+++ b/catalog-ui/src/app/ng2/pages/page404/page404.component.less
@@ -0,0 +1,4 @@
+.page404 {
+ font-size: 100px;
+ color: #ff0000;
+}
diff --git a/catalog-ui/src/app/ng2/pages/page404/page404.component.ts b/catalog-ui/src/app/ng2/pages/page404/page404.component.ts
new file mode 100644
index 0000000000..a3baf4fd02
--- /dev/null
+++ b/catalog-ui/src/app/ng2/pages/page404/page404.component.ts
@@ -0,0 +1,9 @@
+import { Component, Inject } from '@angular/core';
+
+@Component({
+ templateUrl: './page404.component.html',
+ styleUrls: ['./page404.component.less']
+})
+export class PageNotFoundComponent {
+
+}
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
new file mode 100644
index 0000000000..6ef3e57678
--- /dev/null
+++ b/catalog-ui/src/app/ng2/pages/properties-assignment/properties-assignment.module.ts
@@ -0,0 +1,72 @@
+import { NgModule } from "@angular/core";
+import { PropertiesAssignmentComponent } from "./properties-assignment.page.component";
+import { HierarchyNavigationComponent } from "./../../components/hierarchy-navigtion/hierarchy-navigation.component";
+import { BrowserModule } from "@angular/platform-browser";
+import { FormsModule } from "@angular/forms";
+import { HttpModule } from "@angular/http";
+import { TabModule } from '../../shared/tabs/tabs.module';
+import { CheckboxModule} from '../../shared/checkbox/checkbox.module';
+import { PropertiesTableComponent } from '../../components/properties-table/properties-table.component';
+import { InputsTableComponent } from '../../components/inputs-table/inputs-table.component';
+import { ContentAfterLastDotPipe } from "../../pipes/contentAfterLastDot.pipe";
+import { SearchFilterPipe } from "../../pipes/searchFilter.pipe";
+import { FilterChildPropertiesPipe } from "../../pipes/filterChildProperties.pipe";
+import { DataTypeService } from './../../services/data-type.service';
+import { PropertiesService } from './../../services/properties.service';
+import { PropertiesUtils } from './properties.utils';
+import { PostsService } from "../../services/posts.service";
+import { PropertiesValueInnerTableComponent } from "./../../components/properties-table/properties-value-inner-table/properties-value-inner-table.component";
+import { ListPropertyComponent } from "./../../components/properties-table/list-property/list-property.component";
+import { MapPropertyComponent } from "./../../components/properties-table/map-property/map-property.component";
+import { DynamicElementModule } from 'app/ng2/components/dynamic-element/dynamic-element.module';
+import { DynamicPropertyComponent } from './../../components/properties-table/dynamic-property/dynamic-property.component';
+import { DerivedPropertyComponent } from './../../components/properties-table/derived-property/derived-property.component';
+// import {PopoverContentComponent} from "../../components/popover/popover-content.component"
+// import {PopoverComponent} from "../../components/popover/popover.component"
+import { PopoverModule } from "../../components/popover/popover.module"
+import { FilterPropertiesAssignmentComponent } from "./../../components/filter-properties-assignment/filter-properties-assignment.component";
+import { GroupByPipe } from 'app/ng2/pipes/groupBy.pipe';
+import { KeysPipe } from 'app/ng2/pipes/keys.pipe';
+import {TooltipModule} from "../../components/tooltip/tooltip.module";
+
+@NgModule({
+ declarations: [
+ PropertiesAssignmentComponent,
+ PropertiesTableComponent,
+ InputsTableComponent,
+ ContentAfterLastDotPipe,
+ GroupByPipe,
+ KeysPipe,
+ SearchFilterPipe,
+ FilterChildPropertiesPipe,
+ HierarchyNavigationComponent,
+ PropertiesValueInnerTableComponent,
+ ListPropertyComponent,
+ MapPropertyComponent,
+ DerivedPropertyComponent,
+ DynamicPropertyComponent,
+ // PopoverContentComponent,
+ // PopoverComponent,
+ FilterPropertiesAssignmentComponent
+ ],
+ imports: [
+ BrowserModule,
+ FormsModule,
+ HttpModule,
+ TabModule,
+ CheckboxModule,
+ DynamicElementModule,
+ PopoverModule,
+ TooltipModule
+ ],
+ entryComponents: [PropertiesAssignmentComponent],
+ exports: [
+ PropertiesAssignmentComponent
+ // PopoverContentComponent,
+ // PopoverComponent
+ ],
+ providers: [PropertiesService, PropertiesUtils, DataTypeService, PostsService, ContentAfterLastDotPipe, GroupByPipe, KeysPipe]
+})
+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
new file mode 100644
index 0000000000..d1b671cff2
--- /dev/null
+++ b/catalog-ui/src/app/ng2/pages/properties-assignment/properties-assignment.page.component.html
@@ -0,0 +1,57 @@
+<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 | searchFilter:'name':searchQuery"
+ [selectedPropertyId]="selectedFlatProperty.uniqueId"
+ [propertyNameSearchText]="searchPropertyName"
+ (valueChanged)="propertyValueChanged($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" [inputs]="inputs | searchFilter:'name':searchQuery" (deleteInput)="deleteInput($event)" (inputValueChanged)="inputValueChanged($event)"></inputs-table>
+ </tab>
+ </tabs>
+ <div class="header">
+ <div class="search-filter-container">
+ <input type="text" class="search-box" placeholder="Search" [(ngModel)]="searchQuery" />
+ <span class="sprite search-icon"></span>
+ <filter-properties-assignment *ngIf="!hideAdvanceSearch" #advanceSearch class="advance-search" [componentType]="component.componentType" (searchProperties)="searchPropertiesInstances($event)"></filter-properties-assignment>
+ <span *ngIf="displayClearSearch && !hideAdvanceSearch" (click)="clickOnClearSearch()" class="clear-filter">Clear All</span>
+ </div>
+ <button class="tlv-btn blue declare-button" [disabled]="!checkedPropertiesCount" (click)="declareProperties()">Declare</button>
+ </div>
+ </div>
+ <div class="right-column gray-border">
+ <tabs #hierarchyNavTabs tabStyle="simple-tabs">
+ <tab tabTitle="Composition">
+ <div class="hierarchy-nav-container">
+ <div class="hierarchy-header">{{component.name}}</div>
+ <div *ngIf="!instancesNavigationData || instancesNavigationData.length === 0">No data to display</div>
+ <hierarchy-navigation class="hierarchy-nav" (updateSelected)="onInstanceSelectedUpdate($event)"
+ [displayData]="instancesNavigationData"
+ [selectedItem]="selectedInstanceData.uniqueId"
+ [displayOptions]="hierarchyInstancesDisplayOptions"></hierarchy-navigation>
+ </div>
+ </tab>
+ <tab tabTitle="Property Structure">
+ <div class="hierarchy-nav-container">
+ <div class="hierarchy-header">{{propertyStructureHeader || selectedFlatProperty.name || "No Property Selected"}}</div>
+ <div *ngIf="!propertiesNavigationData || propertiesNavigationData.length === 0">No data to display</div>
+ <hierarchy-navigation class="hierarchy-nav" (updateSelected)="onPropertySelectedUpdate($event)"
+ [displayData]="propertiesNavigationData"
+ [selectedItem]="selectedFlatProperty.uniqueId"
+ [displayOptions]="hierarchyPropertiesDisplayOptions"></hierarchy-navigation>
+ </div>
+ </tab>
+ </tabs>
+ </div>
+ </div>
+</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
new file mode 100644
index 0000000000..f7a62bbcb5
--- /dev/null
+++ b/catalog-ui/src/app/ng2/pages/properties-assignment/properties-assignment.page.component.less
@@ -0,0 +1,158 @@
+@import '../../../../assets/styles/variables';
+@ng2-shadow-gray: #f8f8f8;
+@ng2-light-gray: #eaeaea;
+@ng2-medium-gray: #d2d2d2;
+@ng2-med-dark-gray: #999999;
+@ng2-dark-gray: #5a5a5a;
+@ng2-shadow-blue: #e6f6fb;
+@ng2-bold-blue: #009fdb;
+@ng2-success-green:#4ca90c;
+@ng2-title-font-size:16px;
+@ng2-text-font-size: 14px;
+
+:host { display:block; height: 100%; }
+/deep/ tabs {display:flex; flex-direction:column; height:100%; }
+
+.properties-assignment-page {
+ height: 100%;
+
+ .main-content {
+ display:flex;
+ flex-direction:row;
+ height: 100%;
+ }
+
+ .left-column {
+ flex: 1 0 500px;
+ position: relative;
+ margin: 0 0 1em 0;
+
+ /deep/ .tabs {
+ width:25%;
+ text-align:center;
+
+ }
+
+ /deep/ .tab {
+ padding: 10px .5em;
+
+ &.active {
+ color:#009fdb;
+ border-color: #d2d2d2;
+ border-top: solid 4px #009fdb;
+ background-color: white;
+ padding-top:7px;
+ }
+ }
+
+ .header {
+ position:absolute;
+ top:0;
+ right:0;
+ min-width:200px;
+ }
+
+ .search-filter-container{
+ position: relative;
+ right: 164px;
+ }
+
+ .search-box {
+ border: 1px solid @ng2-medium-gray;
+ border-radius: 4px;
+ height: 32px;
+ margin: 0;
+ padding: 2px 20px 4px 10px;
+ outline: none;
+ font-style: italic;
+ color:@ng2-med-dark-gray;
+ margin-right:10px;
+
+ &::-moz-placeholder { color:@ng2-med-dark-gray;}
+ &::-webkit-input-placeholder{ color:@ng2-med-dark-gray;}
+ }
+ .search-icon {
+ background-position: -48px -3137px;
+ width: 14px;
+ height: 14px;
+ position: relative;
+ right: 34px;
+ top: 4px;
+ }
+ .advance-search{
+ position: relative;
+ right: 22px;
+ }
+ .clear-filter{
+ cursor: pointer;
+ color: @main_color_c;
+ font-family: @font-omnes-medium-italic;
+ text-decoration: underline;
+ position: relative;
+ top: 4px;
+ right: 16px;
+ }
+
+ .declare-button{
+ position: absolute;
+ top: 0;
+ right: 0;
+ }
+ }
+
+ .right-column {
+ display:flex;
+ flex:0 0 350px;
+ flex-direction:column;
+ margin: 3em 0 1em 1em;
+ padding: 10px;
+ overflow:auto;
+
+ /deep/ .tabs {
+ width: 33%;
+ }
+
+ /deep/ .tab {
+ padding: 0.5em 1em 0 1em;
+ white-space: nowrap;
+ font-size: 13px;
+ }
+ }
+
+ .hierarchy-tabs {
+ flex: 0 0 40px;
+ }
+
+ .gray-border {
+ border: 1px solid #ddd;
+ }
+
+
+ .hierarchy-nav-container {
+ flex:1;
+ overflow: auto;
+ flex-direction: column;
+ height: 100%;
+ }
+
+ .hierarchy-header {
+ height:30px;
+ line-height: 2.5em;
+ display: flex;
+ width: 100%;
+ padding-left: 14px;
+ font-weight: bold;
+ text-align: left;
+ background-color: @ng2-light-gray;
+ font-size: 13px;
+ }
+
+ .hierarchy-nav {
+ display: grid;
+ margin-top: 1em;
+ margin-left: 1em;
+ font-size: 12px;
+ padding-top: 1em;
+ }
+}
+
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
new file mode 100644
index 0000000000..299615b122
--- /dev/null
+++ b/catalog-ui/src/app/ng2/pages/properties-assignment/properties-assignment.page.component.ts
@@ -0,0 +1,344 @@
+import {Component, ViewChild, ElementRef, Renderer, Inject} from "@angular/core";
+import {PostsService} from "../../services/posts.service";
+import {PropertiesService, SimpleFlatProperty} from "../../services/properties.service";
+import { PropertiesUtils } from './properties.utils';
+import { PropertyFEModel, InstanceFePropertiesMap, InstanceBePropertiesMap, InstancePropertiesAPIMap, Component as ComponentData, FilterPropertiesAssignmentData } from "app/models";
+import { PROPERTY_TYPES, ResourceType } from "app/utils";
+import property = require("lodash/property");
+import {ComponentServiceNg2} from "../../services/component-services/component.service";
+import {ComponentInstanceServiceNg2} from "../../services/component-instance-services/component-instance.service"
+import {InputFEModel, ComponentInstance, PropertyBEModel, DerivedFEProperty, ResourceInstance} from "app/models";
+import {HierarchyDisplayOptions} from "../../components/hierarchy-navigtion/hierarchy-display-options"
+import {PropertyRowSelectedEvent} from "./../../components/properties-table/properties-table.component";
+import { KeysPipe } from 'app/ng2/pipes/keys.pipe';
+import {FilterPropertiesAssignmentComponent} from "../../components/filter-properties-assignment/filter-properties-assignment.component";
+
+@Component({
+ templateUrl: './properties-assignment.page.component.html',
+ styleUrls: ['./properties-assignment.page.component.less']
+})
+export class PropertiesAssignmentComponent {
+ title = "Properties & Inputs";
+
+ component:ComponentData;
+
+ propertiesNavigationData = [];
+ instancesNavigationData = [];
+
+ instanceFePropertiesMap:InstanceFePropertiesMap;
+ inputs: Array<InputFEModel> = [];
+ instances: Array<ComponentInstance> = [];
+ searchQuery: string;
+ propertyStructureHeader: string
+
+ selectedFlatProperty: SimpleFlatProperty = new SimpleFlatProperty();
+ selectedInstanceType: string;
+ selectedInstanceData: ComponentInstance = new ComponentInstance();
+ checkedPropertiesCount: number = 0;
+
+ hierarchyPropertiesDisplayOptions:HierarchyDisplayOptions = new HierarchyDisplayOptions('uniqueId', 'name', 'childrens');
+ hierarchyInstancesDisplayOptions:HierarchyDisplayOptions = new HierarchyDisplayOptions('uniqueId', 'name');
+ displayClearSearch = false;
+ searchPropertyName:string;
+ hideAdvanceSearch:boolean;
+
+ @ViewChild('hierarchyNavTabs') hierarchyNavTabs: ElementRef;
+ @ViewChild('propertyInputTabs') propertyInputTabs: ElementRef;
+ @ViewChild('advanceSearch') advanceSearch: FilterPropertiesAssignmentComponent;
+
+ constructor(private propertiesService:PropertiesService,
+ private propertiesUtils:PropertiesUtils,
+ private componentServiceNg2:ComponentServiceNg2,
+ private componentInstanceServiceNg2:ComponentInstanceServiceNg2,
+ @Inject("$stateParams") _stateParams,
+ private renderer: Renderer) {
+
+ this.instanceFePropertiesMap = new InstanceFePropertiesMap();
+
+ /* This is the way you can access the component data, please do not use any data except metadata, all other data should be received from the new api calls on the first time
+ than if the data is already exist, no need to call the api again - Ask orit if you have any questions*/
+ this.component = _stateParams.component;
+ }
+
+ ngOnInit() {
+ console.log("==>" + this.constructor.name + ": ngOnInit");
+ this.componentServiceNg2
+ .getComponentResourceInstances(this.component)
+ .subscribe(response => {
+ this.instances = response.componentInstances;
+
+ _.forEach(this.instances, (instance) => {
+ this.instancesNavigationData.push(instance);
+ });
+
+ this.selectFirstInstanceByDefault();
+ });
+
+ this.componentServiceNg2
+ .getComponentInputs(this.component)
+ .subscribe(response => {
+ _.forEach(response.inputs, (input: PropertyBEModel) => {
+ this.inputs.push(new InputFEModel(input));
+ });
+ })
+ }
+
+ selectFirstInstanceByDefault = () => {
+ if (this.instancesNavigationData[0] !== undefined) {
+ this.onInstanceSelectedUpdate(this.instancesNavigationData[0]);
+ }
+ }
+
+ propertyValueChanged = (event) => {
+ console.log("==>" + this.constructor.name + ": propertyValueChanged " + event);
+
+ if(this.selectedInstanceData.originType === ResourceType.VF) {
+ console.log("I want to update input value on the resource instance");
+ let inputToUpdate = new PropertyBEModel(event);
+ this.componentInstanceServiceNg2
+ .updateInstanceInput(this.component, this.selectedInstanceData.uniqueId, inputToUpdate)
+ .subscribe(response => {
+ console.log("update resource instance input and got this response: ",response);
+ })
+ }
+ else {
+ // Copying the actual value from the object ref into the value if it's from a complex type
+ if(event.isDataType) {
+ event.value = JSON.stringify(event.valueObjectRef);
+ }
+ let propertyBe = new PropertyBEModel(event);
+ this.componentInstanceServiceNg2
+ .updateInstanceProperty(this.component, this.selectedInstanceData.uniqueId, propertyBe)
+ .subscribe(response => {
+ console.log("updated resource instance property and got this response: ",response);
+ });
+ console.log(event);
+ }
+
+ };
+
+ inputValueChanged = (event) => {
+ console.log("==>" + this.constructor.name + ": inputValueChanged");
+ let inputToUpdate = new PropertyBEModel(event);
+
+ this.componentServiceNg2
+ .updateComponentInput(this.component, inputToUpdate)
+ .subscribe(response => {
+ console.log("updated the component input and got this response: ", response);
+ })
+ };
+
+ declareProperties = ():void => {
+ console.log("==>" + this.constructor.name + ": declareProperties");
+
+ let selectedProperties: InstanceBePropertiesMap = new InstanceBePropertiesMap();
+
+ let instancesNames = new KeysPipe().transform(this.instanceFePropertiesMap,[]);
+ angular.forEach(instancesNames, (instanceName:string):void=>{
+ selectedProperties[instanceName] = this.propertiesService.getCheckedProperties(this.instanceFePropertiesMap[instanceName]);
+ //selectedProperties[this.selectedInstanceData.uniqueId] = this.propertiesService.getCheckedProperties(this.properties);
+ });
+
+ let inputsToCreate: InstancePropertiesAPIMap;
+ if (this.selectedInstanceType !== ResourceType.VF) {
+ inputsToCreate = new InstancePropertiesAPIMap(null, selectedProperties);
+ } else {
+ inputsToCreate = new InstancePropertiesAPIMap(selectedProperties, null);
+ }
+ this.componentServiceNg2
+ .createInput(this.component, inputsToCreate)
+ .subscribe(response => {
+ this.setInputTabIndication(response.length);
+ this.checkedPropertiesCount = 0;
+ _.forEach(response, (input: PropertyBEModel) => { this.inputs.push(new InputFEModel(input)); });
+ this.findAndDisableDeclaredProperties();
+ });
+ }
+
+ //TODO: Can remove? no one use it
+ // getSelectedFEProps = (): Array<PropertyFEModel> => {
+ // return this.properties.filter(prop => prop.isSelected && !prop.isDeclared);
+ // }
+
+ onInstanceSelectedUpdate = (resourceInstance: ResourceInstance) => {
+ console.log("==>" + this.constructor.name + ": onInstanceSelectedUpdate");
+ let instanceBePropertiesMap: InstanceBePropertiesMap = new InstanceBePropertiesMap();
+ this.selectedInstanceData = resourceInstance;
+ this.selectedInstanceType = resourceInstance.originType;
+
+ if(resourceInstance.originType === ResourceType.VF) {
+ this.componentInstanceServiceNg2
+ .getComponentInstanceInputs(this.component, resourceInstance)
+ .subscribe(response => {
+ instanceBePropertiesMap[resourceInstance.uniqueId] = response;
+ this.processInstancePropertiesResponse(instanceBePropertiesMap);
+ });
+ } else {
+ this.componentInstanceServiceNg2
+ .getComponentInstanceProperties(this.component, resourceInstance.uniqueId)
+ .subscribe(response => {
+ instanceBePropertiesMap[resourceInstance.uniqueId] = response;
+ this.processInstancePropertiesResponse(instanceBePropertiesMap);
+ });
+ }
+
+ if( this.searchPropertyName ){
+ this.clearSearch();
+ }
+ };
+
+ /**
+ * Entry point handling response from server
+ */
+ processInstancePropertiesResponse = (instanceBePropertiesMap:InstanceBePropertiesMap) => {
+ this.instanceFePropertiesMap = this.propertiesUtils.convertPropertiesMapToFEAndCreateChildren(instanceBePropertiesMap); //create flattened children
+ this.findAndDisableDeclaredProperties(); //disable properties or flattened children that are declared
+ this.checkedPropertiesCount = 0;
+ };
+
+ /**
+ * Handle select node in navigation area, and select the row in table
+ */
+ onPropertySelectedUpdate = ($event) => {
+ console.log("==>" + this.constructor.name + ": onPropertySelectedUpdate");
+ this.selectedFlatProperty = $event;
+ let parentProperty:PropertyFEModel = this.propertiesService.getParentPropertyFEModelFromPath(this.instanceFePropertiesMap[this.selectedFlatProperty.instanceName], this.selectedFlatProperty.path);
+ parentProperty.expandedChildPropertyId = this.selectedFlatProperty.path;
+ };
+
+ /**
+ * When user select row in table, this will prepare the hirarchy object for the tree.
+ */
+ selectPropertyRow = (propertyRowSelectedEvent:PropertyRowSelectedEvent) => {
+ console.log("==>" + this.constructor.name + ": selectPropertyRow " + propertyRowSelectedEvent.propertyModel.name);
+ let property = propertyRowSelectedEvent.propertyModel;
+ let instanceName = propertyRowSelectedEvent.instanceName;
+ this.propertyStructureHeader = null;
+
+ // Build hirarchy tree for the navigation and update propertiesNavigationData with it.
+ if(this.selectedInstanceData.originType !== ResourceType.VF) {
+ let simpleFlatProperty:Array<SimpleFlatProperty>;
+ if (property instanceof PropertyFEModel) {
+ simpleFlatProperty = this.propertiesService.getSimplePropertiesTree(property, instanceName);
+ } else if (property instanceof DerivedFEProperty) {
+ // Need to find parent PropertyFEModel
+ let parentPropertyFEModel:PropertyFEModel = _.find(this.instanceFePropertiesMap[instanceName], (tmpFeProperty):boolean => {
+ return property.propertiesName.indexOf(tmpFeProperty.name)===0;
+ });
+ simpleFlatProperty = this.propertiesService.getSimplePropertiesTree(parentPropertyFEModel, instanceName);
+ }
+ this.propertiesNavigationData = simpleFlatProperty;
+ }
+
+ // Updatet the header in the navigation tree with property name.
+ if(property instanceof DerivedFEProperty) {
+ this.propertyStructureHeader = (property.propertiesName.split('#'))[0];
+ }
+
+ // Set selected property in table
+ this.selectedFlatProperty = new SimpleFlatProperty(property.uniqueId, null, property.name, null);
+ this.renderer.invokeElementMethod(this.hierarchyNavTabs, 'triggerTabChange', ['Property Structure']);
+ };
+
+ //TODO: Can remove? no one use it
+ // findParentProperty = (childProp: DerivedFEProperty): PropertyFEModel => {
+ // return this.properties.find(prop => prop.name == childProp.propertiesName.substring(0, childProp.propertiesName.indexOf("#")));
+ // }
+
+ //used for declare button, to keep count of newly checked properties (and ignore declared properties)
+ updateCheckedPropertyCount = (increment: boolean):void => {
+ this.checkedPropertiesCount += (increment) ? 1 : -1;
+ console.log("CheckedProperties count is now.... " + this.checkedPropertiesCount);
+ }
+
+ selectInstanceRow = ($event) => {//get instance name
+ this.selectedInstanceData = _.find(this.instancesNavigationData, (instance:ComponentInstance) => {
+ return instance.name == $event;
+ });
+ this.renderer.invokeElementMethod(
+ this.hierarchyNavTabs, 'triggerTabChange', ['Composition']);
+ }
+
+ tabChanged = (event) => {
+ console.log("==>" + this.constructor.name + ": tabChanged " + event);
+ this.hideAdvanceSearch = event.title !== "Properties";
+ this.searchQuery = '';
+ };
+
+ deleteInput = (input:InputFEModel) => {
+ console.log("==>" + this.constructor.name + ": deleteInput");
+ let inputToDelete = new PropertyBEModel(input);
+
+ this.componentServiceNg2
+ .deleteInput(this.component, inputToDelete)
+ .subscribe(response => {
+ this.inputs = this.inputs.filter(input => input.uniqueId !== response.uniqueId);
+ let propToEnable: PropertyFEModel = this.instanceFePropertiesMap[input.instanceName].find(prop => prop.name == input.propertyName);
+ propToEnable.setNonDeclared(response.inputPath);
+ this.propertiesService.undoDisableRelatedProperties(propToEnable, response.inputPath);
+ //this.propertiesService.initValueObjectRef(propToEnable); //TODO:speak to BE about value returned by server
+ });
+ }
+
+ setInputTabIndication = (numInputs: number): void => {
+ this.renderer.invokeElementMethod( this.propertyInputTabs, 'setTabIndication', ['Inputs', numInputs]);
+ }
+
+ findAndDisableDeclaredProperties = () => {
+ this.inputs.filter(input => input.instanceName === this.selectedInstanceData.normalizedName).forEach(input => {
+ let prop: PropertyFEModel = this.instanceFePropertiesMap[this.selectedInstanceData.uniqueId].find(prop => prop.name === input.propertyName);
+ if (prop) {
+ prop.setAsDeclared(input.inputPath); //if a path was sent, its a child prop. this param is optional
+ this.propertiesService.disableRelatedProperties(prop, input.inputPath)
+ //this.propertiesService.initValueObjectRef(prop);
+ }
+ });
+ };
+
+ searchPropertiesInstances = (filterData:FilterPropertiesAssignmentData) => {
+ //let filteredProperties = this.componentServiceNg2.filterComponentInstanceProperties(this.component, filterData);
+ let instanceBePropertiesMap:InstanceBePropertiesMap;
+ this.componentServiceNg2
+ .filterComponentInstanceProperties(this.component, filterData)
+ .subscribe(response => {
+ //instanceBePropertiesMap=response;
+ //console.log("================filter results=============");
+ //console.table(instanceBePropertiesMap);
+ this.processInstancePropertiesResponse(response);
+
+
+ //this.properties = [];
+ // _.forEach(instanceBePropertiesMap, (InstanceProperties:Array<PropertyBEModel>, instanceName:string) => {
+ // this.properties = this.properties.concat(this.propertiesService.convertPropertiesToFEAndCreateChildren(InstanceProperties, instanceName));
+ // });
+
+
+ // this.instancesNavigationData = _.filter(this.instancesNavigationData, (instance:ComponentInstance) => {
+ // return instanceBePropertiesMap[instance.name];
+ // });
+
+ // this.hierarchyPropertiesDisplayOptions.searchText = filterData.propertyName;//mark results in tree
+ this.searchPropertyName = filterData.propertyName;//mark in table
+ this.renderer.invokeElementMethod(this.hierarchyNavTabs, 'triggerTabChange', ['Composition']);
+ this.propertiesNavigationData = [];
+ this.displayClearSearch = true;
+ });
+
+ };
+
+ clearSearch = () => {
+ this.instancesNavigationData = this.instances;
+ this.searchPropertyName = "";
+ this.hierarchyPropertiesDisplayOptions.searchText = "";
+ this.displayClearSearch = false;
+ this.advanceSearch.clearAll();
+ }
+
+ clickOnClearSearch = () => {
+ this.clearSearch();
+ this.selectFirstInstanceByDefault();
+ this.renderer.invokeElementMethod(
+ this.hierarchyNavTabs, 'triggerTabChange', ['Composition']);
+ }
+
+}
diff --git a/catalog-ui/src/app/ng2/pages/properties-assignment/properties.utils.ts b/catalog-ui/src/app/ng2/pages/properties-assignment/properties.utils.ts
new file mode 100644
index 0000000000..79769e21b5
--- /dev/null
+++ b/catalog-ui/src/app/ng2/pages/properties-assignment/properties.utils.ts
@@ -0,0 +1,78 @@
+import { Injectable } from '@angular/core';
+import { DataTypeModel, PropertyFEModel, PropertyBEModel, InstanceBePropertiesMap, InstanceFePropertiesMap, SchemaProperty, DerivedFEProperty, DerivedFEPropertyMap, DerivedPropertyType, InputFEModel} from "app/models";
+import { DataTypeService } from "app/ng2/services/data-type.service";
+import { PROPERTY_TYPES } from "app/utils";
+import { UUID } from "angular2-uuid";
+
+@Injectable()
+export class PropertiesUtils {
+
+ constructor(private dataTypeService:DataTypeService) {}
+
+ /**
+ * Entry point when getting properties from server
+ * Returning InstanceFePropertiesMap
+ */
+ public convertPropertiesMapToFEAndCreateChildren = (instancePropertiesMap:InstanceBePropertiesMap): InstanceFePropertiesMap => {
+ let instanceFePropertiesMap:InstanceFePropertiesMap = new InstanceFePropertiesMap();
+ angular.forEach(instancePropertiesMap, (properties:Array<PropertyBEModel>, instanceName:string) => {
+ instanceFePropertiesMap[instanceName] = this.convertPropertiesToFEAndCreateChildren(properties);
+ });
+ return instanceFePropertiesMap;
+ }
+
+ /**
+ * Convert the properties Array<PropertyBEModel> to Array<PropertyFEModel>
+ */
+ private convertPropertiesToFEAndCreateChildren = (properties: Array<PropertyBEModel>): Array<PropertyFEModel> => {
+ let propertyFeArray: Array<PropertyFEModel> = [];
+ _.forEach(properties, (property: PropertyBEModel, index: number) => {
+ //console.log("=======" + property.name + "========");
+ if(!this.dataTypeService.getDataTypeByTypeName(property.type)){ // if type not exist in data types remove property from list
+ console.log("ERROR: missing type " + property.type + " in dataTypes , of property ",property);
+ return;
+ }
+ let propertyFe:PropertyFEModel = new PropertyFEModel(property);
+ if (propertyFe.isDataType) { //prop is not simple, list, or map. Need to create children.
+ let tempProps: Array<DerivedFEProperty> = [];
+ let dataTypeObj: DataTypeModel = this.dataTypeService.getDataTypeByTypeName(propertyFe.type);
+ this.dataTypeService.getDerivedDataTypeProperties(dataTypeObj, tempProps, propertyFe.name);
+ propertyFe.flattenedChildren = tempProps;
+ propertyFe.expandedChildPropertyId = propertyFe.name;
+ this.initValueObjectRef(propertyFe);
+ }
+ propertyFeArray.push(propertyFe);
+
+
+ });
+ return propertyFeArray;
+
+ //TODO: need to look at schema to create the nested properties for the following cases:
+ // 1 - when value is populated for a complex type (list or map)
+ // 2 - when adding new entries to a complex type (eg. adding a new entry to a list of AddressRequirements)
+ }
+
+ public initValueObjectRef = (property: PropertyFEModel): void => {
+ //console.log("Property " + property.name + " has value: " + property.value);
+ if (!property.isDataType || property.isDeclared) { //if property is declared, it gets a simple input instead. List and map values and pseudo-children will be handled in property component
+ property.value = property.value || property.defaultValue;
+ } else if (property.value){ //we have a complex property with a value. Lets parse property.value and populate our flattened children with those values
+ this.assignValuesRecursively(JSON.parse(property.value), property.flattenedChildren, property.name);
+ }
+ }
+
+ public assignValuesRecursively = (valueJSON: any, derivedPropArray: Array<DerivedFEProperty>, propName: string) => {
+ if (valueJSON && Object.keys(valueJSON)) {
+ Object.keys(valueJSON).forEach(valueKey => {
+ let childProp: DerivedFEProperty = derivedPropArray.find(prop => prop.propertiesName == propName + "#" + valueKey);
+ if (!childProp) return;
+ if (childProp.isDeclared || (childProp.derivedDataType != DerivedPropertyType.COMPLEX && !_.isEmpty(valueJSON[valueKey]))) {
+ childProp.value = (typeof valueJSON[valueKey] === 'object')? JSON.stringify(valueJSON[valueKey]) : valueJSON[valueKey];
+ } else {
+ this.assignValuesRecursively(valueJSON[valueKey], derivedPropArray, childProp.propertiesName)
+ }
+ });
+ }
+ }
+
+}
diff --git a/catalog-ui/src/app/ng2/pipes/contentAfterLastDot.pipe.ts b/catalog-ui/src/app/ng2/pipes/contentAfterLastDot.pipe.ts
new file mode 100644
index 0000000000..68fba92b77
--- /dev/null
+++ b/catalog-ui/src/app/ng2/pipes/contentAfterLastDot.pipe.ts
@@ -0,0 +1,8 @@
+import { Pipe, PipeTransform } from '@angular/core';
+
+@Pipe({ name: 'contentAfterLastDot' })
+export class ContentAfterLastDotPipe implements PipeTransform {
+ transform(value:string): string {
+ return value.split('.').pop();
+ }
+} \ No newline at end of file
diff --git a/catalog-ui/src/app/ng2/pipes/filterChildProperties.pipe.ts b/catalog-ui/src/app/ng2/pipes/filterChildProperties.pipe.ts
new file mode 100644
index 0000000000..d2eaef0391
--- /dev/null
+++ b/catalog-ui/src/app/ng2/pipes/filterChildProperties.pipe.ts
@@ -0,0 +1,18 @@
+import { Pipe, PipeTransform } from '@angular/core';
+import { DerivedFEProperty } from 'app/models';
+
+@Pipe({
+ name: 'filterChildProperties',
+})
+export class FilterChildPropertiesPipe implements PipeTransform {
+ public transform(childProperties: Array<DerivedFEProperty>, parentId: string) {
+ if (!parentId || !childProperties) return childProperties;
+
+ let validParents: Array<string> = [parentId];
+ while (parentId.lastIndexOf('#') > 0) {
+ parentId = parentId.substring(0, parentId.lastIndexOf('#'));
+ validParents.push(parentId);
+ }
+ return childProperties.filter(derivedProp => validParents.indexOf(derivedProp.parentName) > -1);
+ }
+} \ No newline at end of file
diff --git a/catalog-ui/src/app/ng2/pipes/groupBy.pipe.ts b/catalog-ui/src/app/ng2/pipes/groupBy.pipe.ts
new file mode 100644
index 0000000000..17ccc0ca75
--- /dev/null
+++ b/catalog-ui/src/app/ng2/pipes/groupBy.pipe.ts
@@ -0,0 +1,19 @@
+/**
+ * Created by rc2122 on 5/17/2017.
+ */
+import {Pipe, PipeTransform} from '@angular/core';
+
+@Pipe({name: 'groupBy'})
+export class GroupByPipe implements PipeTransform {
+ transform(value: Array<any>, field: string): Array<any> {
+ const groupedObj = value.reduce((prev, cur)=> {
+ if(!prev[cur[field]]) {
+ prev[cur[field]] = [cur];
+ } else {
+ prev[cur[field]].push(cur);
+ }
+ return prev;
+ }, {});
+ return Object.keys(groupedObj).map((key:string) => {return { key, value: groupedObj[key] }; });
+ }
+}
diff --git a/catalog-ui/src/app/ng2/pipes/keys.pipe.ts b/catalog-ui/src/app/ng2/pipes/keys.pipe.ts
new file mode 100644
index 0000000000..13bd26969c
--- /dev/null
+++ b/catalog-ui/src/app/ng2/pipes/keys.pipe.ts
@@ -0,0 +1,12 @@
+import { Pipe, PipeTransform } from '@angular/core';
+
+@Pipe({name: 'keys'})
+export class KeysPipe implements PipeTransform {
+ transform(value, args:string[]) : any {
+ let keys = [];
+ for (let key in value) {
+ keys.push(key);
+ }
+ return keys;
+ }
+}
diff --git a/catalog-ui/src/app/ng2/pipes/searchFilter.pipe.ts b/catalog-ui/src/app/ng2/pipes/searchFilter.pipe.ts
new file mode 100644
index 0000000000..7e017e8590
--- /dev/null
+++ b/catalog-ui/src/app/ng2/pipes/searchFilter.pipe.ts
@@ -0,0 +1,18 @@
+import { Pipe, PipeTransform } from '@angular/core';
+
+@Pipe({
+ name: 'searchFilter',
+})
+export class SearchFilterPipe implements PipeTransform {
+ public transform(value, key: string, term: string) {
+ if (!term || !term.length) return value;
+ return value.filter((item) => {
+ if (item.hasOwnProperty(key)) {
+ let regExp = new RegExp(term, 'gi');
+ return regExp.test(item[key]);
+ } else {
+ return false;
+ }
+ });
+ }
+} \ No newline at end of file
diff --git a/catalog-ui/src/app/ng2/services/authentication.service.ts b/catalog-ui/src/app/ng2/services/authentication.service.ts
new file mode 100644
index 0000000000..7fe3e22f4c
--- /dev/null
+++ b/catalog-ui/src/app/ng2/services/authentication.service.ts
@@ -0,0 +1,40 @@
+import { Injectable } from '@angular/core';
+import { sdc2Config } from './../../../main';
+import {IAppConfigurtaion, ICookie} from "../../models/app-config";
+import {Response, Headers, RequestOptions, Http} from '@angular/http';
+import {Cookie2Service} from "./cookie.service";
+import { Observable } from 'rxjs/Observable';
+
+@Injectable()
+export class AuthenticationService {
+
+ private cookieService:Cookie2Service;
+ private http:Http;
+
+ constructor(cookieService:Cookie2Service, http: Http) {
+ this.cookieService = cookieService;
+ this.http = http;
+ }
+
+ private getAuthHeaders():any {
+ let cookie:ICookie = sdc2Config.cookie;
+ let authHeaders:any = {};
+ authHeaders[cookie.userFirstName] = this.cookieService.getFirstName();
+ authHeaders[cookie.userLastName] = this.cookieService.getLastName();
+ authHeaders[cookie.userEmail] = this.cookieService.getEmail();
+ authHeaders[cookie.userIdSuffix] = this.cookieService.getUserId();
+ return authHeaders;
+ }
+
+ public authenticate(): Observable<JSON> {
+ let options = new RequestOptions({
+ headers: new Headers(this.getAuthHeaders())
+ });
+
+ let authUrl = sdc2Config.api.root + sdc2Config.api.GET_user_authorize;
+ return this.http
+ .get(authUrl, options)
+ .map((res: Response) => res.json());
+ }
+
+} \ No newline at end of file
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
new file mode 100644
index 0000000000..85709894ff
--- /dev/null
+++ b/catalog-ui/src/app/ng2/services/component-instance-services/component-instance.service.ts
@@ -0,0 +1,51 @@
+import {Injectable} from '@angular/core';
+import {Response, RequestOptions, Headers} from '@angular/http';
+import { Observable } from 'rxjs/Observable';
+import {HttpService} from "../http.service";
+import {sdc2Config} from "../../../../main";
+import {PropertyBEModel} from "app/models";
+import {CommonUtils} from "app/utils";
+import {Component, ComponentInstance, InputModel} from "app/models";
+
+@Injectable()
+export class ComponentInstanceServiceNg2 {
+
+ protected baseUrl;
+
+ constructor(private http: HttpService) {
+ this.baseUrl = sdc2Config.api.root + sdc2Config.api.component_api_root;
+ }
+
+ getComponentInstanceProperties(component: Component, componentInstanceId: string): Observable<Array<PropertyBEModel>> {
+
+ return this.http.get(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/componentInstances/' + componentInstanceId + '/properties')
+ .map((res: Response) => {
+ return CommonUtils.initBeProperties(res.json());
+ })
+ }
+
+ getComponentInstanceInputs(component: Component, componentInstance: ComponentInstance): Observable<Array<PropertyBEModel>> {
+ return this.http.get(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/componentInstances/' + componentInstance.uniqueId + '/' + componentInstance.componentUid + '/inputs')
+ .map((res: Response) => {
+ return CommonUtils.initInputs(res.json());
+ })
+ }
+
+ updateInstanceProperty(component: Component, componentInstanceId: string, property: PropertyBEModel): Observable<PropertyBEModel> {
+
+ return this.http.post(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/resourceInstance/' + componentInstanceId + '/property', property)
+ .map((res: Response) => {
+ return new PropertyBEModel(res.json());
+ })
+ }
+
+ updateInstanceInput(component: Component, componentInstanceId: string, input: PropertyBEModel): Observable<PropertyBEModel> {
+
+ return this.http.post(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/resourceInstance/' + componentInstanceId + '/input', input)
+ .map((res: Response) => {
+ return new PropertyBEModel(res.json());
+ })
+ }
+
+
+}
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
new file mode 100644
index 0000000000..3fa9fde40c
--- /dev/null
+++ b/catalog-ui/src/app/ng2/services/component-services/component.service.ts
@@ -0,0 +1,149 @@
+import {Injectable, Query} 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 {HttpService} from "../http.service";
+import {COMPONENT_FIELDS} from "app/utils";
+import {ComponentGenericResponse} from "../responses/component-generic-response";
+import {sdc2Config} from "../../../../main";
+import {InstanceBePropertiesMap} from "../../../models/properties-inputs/property-fe-map";
+import {API_QUERY_PARAMS} from "app/utils";
+import {ComponentType, ServerTypeUrl} from "../../../utils/constants";
+
+declare var angular:angular.IAngularStatic;
+
+@Injectable()
+export class ComponentServiceNg2 {
+
+ protected baseUrl;
+
+ constructor(private http:HttpService) {
+ this.baseUrl = sdc2Config.api.root + sdc2Config.api.component_api_root;
+ }
+
+ private getComponentDataByFieldsName(componentType:string, componentId: string, fields:Array<string>):Observable<ComponentGenericResponse> {
+
+ let params:URLSearchParams = new URLSearchParams();
+ _.forEach(fields, (field:string):void => {
+ params.append(API_QUERY_PARAMS.INCLUDE, field);
+ });
+
+ return this.http.get(this.baseUrl + this.getServerTypeUrl(componentType) + componentId + '/filteredDataByParams', {search: params})
+ .map((res:Response) => {
+ return new ComponentGenericResponse().deserialize(res.json());
+ }).do(error => console.log('server data:', error));
+ }
+
+ private getServerTypeUrl = (componentType:string):string => {
+ switch (componentType) {
+ case ComponentType.PRODUCT:
+ return ServerTypeUrl.PRODUCTS;
+ case ComponentType.SERVICE:
+ return ServerTypeUrl.SERVICES;
+ default:
+ return ServerTypeUrl.RESOURCES;
+ }
+ }
+
+ getComponentMetadata(component:Component):Observable<ComponentGenericResponse> {
+ return this.getComponentDataByFieldsName(component.componentType, component.uniqueId, [COMPONENT_FIELDS.COMPONENT_METADATA]);
+ }
+
+ getComponentInstanceAttributesAndProperties(component:Component):Observable<ComponentGenericResponse> {
+ return this.getComponentDataByFieldsName(component.componentType, component.uniqueId, [COMPONENT_FIELDS.COMPONENT_INSTANCES_PROPERTIES, COMPONENT_FIELDS.COMPONENT_INSTANCES_ATTRIBUTES]);
+ }
+
+ getComponentAttributes(component:Component):Observable<ComponentGenericResponse> {
+ 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]);
+ }
+
+ getComponentResourceInstances(component:Component):Observable<ComponentGenericResponse> {
+ return this.getComponentDataByFieldsName(component.componentType, component.uniqueId, [COMPONENT_FIELDS.COMPONENT_INSTANCES]);
+ }
+
+ getComponentInputs(component:Component):Observable<ComponentGenericResponse> {
+ return this.getComponentDataByFieldsName(component.componentType, component.uniqueId, [COMPONENT_FIELDS.COMPONENT_INPUTS]);
+ }
+
+ getComponentDeploymentArtifacts(component:Component):Observable<ComponentGenericResponse> {
+ return this.getComponentDataByFieldsName(component.componentType, component.uniqueId, [COMPONENT_FIELDS.COMPONENT_DEPLOYMENT_ARTIFACTS]);
+ }
+
+ getComponentInformationalArtifacts(component:Component):Observable<ComponentGenericResponse> {
+ return this.getComponentDataByFieldsName(component.componentType, component.uniqueId, [COMPONENT_FIELDS.COMPONENT_INFORMATIONAL_ARTIFACTS]);
+ }
+
+ getComponentInformationalArtifactsAndInstances(component:Component):Observable<ComponentGenericResponse> {
+ return this.getComponentDataByFieldsName(component.componentType, component.uniqueId, [COMPONENT_FIELDS.COMPONENT_INFORMATIONAL_ARTIFACTS, COMPONENT_FIELDS.COMPONENT_INSTANCES]);
+ }
+
+ getComponentToscaArtifacts(component:Component):Observable<ComponentGenericResponse> {
+ return this.getComponentDataByFieldsName(component.componentType, component.uniqueId, [COMPONENT_FIELDS.COMPONENT_TOSCA_ARTIFACTS]);
+ }
+
+ getComponentProperties(component:Component):Observable<ComponentGenericResponse> {
+ return this.getComponentDataByFieldsName(component.componentType, component.uniqueId, [COMPONENT_FIELDS.COMPONENT_PROPERTIES]);
+ }
+
+ getCapabilitiesAndRequirements(componentType: string, componentId:string):Observable<ComponentGenericResponse> {
+ return this.getComponentDataByFieldsName(componentType, componentId, [COMPONENT_FIELDS.COMPONENT_REQUIREMENTS, COMPONENT_FIELDS.COMPONENT_CAPABILITIES]);
+ }
+
+ getDeploymentGraphData(component:Component):Observable<ComponentGenericResponse> {
+ return this.getComponentDataByFieldsName(component.componentType, component.uniqueId, [COMPONENT_FIELDS.COMPONENT_INSTANCES_RELATION, COMPONENT_FIELDS.COMPONENT_INSTANCES, COMPONENT_FIELDS.COMPONENT_GROUPS]);
+ }
+
+ createInput(component:Component, inputsToCreate:InstancePropertiesAPIMap):Observable<any> {
+ return this.http.post(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/create/inputs', inputsToCreate)
+ .map(res => {
+ return res.json();
+ })
+ }
+
+ deleteInput(component:Component, input:PropertyBEModel):Observable<PropertyBEModel> {
+
+ return this.http.delete(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/delete/' + input.uniqueId + '/input')
+ .map((res:Response) => {
+ return new PropertyBEModel(res.json());
+ })
+ }
+
+ updateComponentInput(component:Component, input:PropertyBEModel):Observable<PropertyBEModel> {
+
+ return this.http.post(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/update/inputs', input)
+ .map((res:Response) => {
+ return new PropertyBEModel(res.json())
+ })
+ }
+
+ filterComponentInstanceProperties(component: Component, filterData:FilterPropertiesAssignmentData): Observable<InstanceBePropertiesMap> {//instance-property-be-map
+ let params: URLSearchParams = new URLSearchParams();
+ _.forEach(filterData.selectedTypes, (type:string) => {
+ params.append('resourceType', type);
+ });
+
+ return this.http.get(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/filteredproperties/' + filterData.propertyName, {search: params})
+ .map((res: Response) => {
+ return res.json();
+ });
+
+ // return {'ExtVL 0':[{definition: false,name:"network_assignments",password:false,required:true,type:"org.openecomp.datatypes.network.NetworkAssignments",uniqueId:"623cca1c-d605-4c9c-9f2b-935ec85ebcf8.network_assignments"},
+ // {definition: false,name: "exVL_naming",password: false,required: true,type: "org.openecomp.datatypes.Naming",uniqueId: "623cca1c-d605-4c9c-9f2b-935ec85ebcf8.exVL_naming"},
+ // {definition: false,name: "network_flows",password: false,required: false,type: "org.openecomp.datatypes.network.NetworkFlows",uniqueId: "623cca1c-d605-4c9c-9f2b-935ec85ebcf8.network_flows"},
+ // {definition: false,name: "provider_network",password: false,required: true,type: "org.openecomp.datatypes.network.ProviderNetwork",uniqueId: "623cca1c-d605-4c9c-9f2b-935ec85ebcf8.provider_network"},
+ // {definition: false,name: "network_homing",password: false,required: true,type: "org.openecomp.datatypes.EcompHoming",uniqueId: "623cca1c-d605-4c9c-9f2b-935ec85ebcf8.network_homing"}],
+ // 'NetworkCP 0':[{definition: false,description: "identifies MAC address assignments to the CP",name: "mac_requirements",password: false,required: false,type: "org.openecomp.datatypes.network.MacRequirements",uniqueId: "26ec2bfd-b904-46c7-87ed-b32775120f2c.mac_requirements"}],
+ // 'NetworkCP 1':[{definition: false,description: "identifies MAC address assignments to the CP",name: "mac_requirements",password: false,required: false,type: "org.openecomp.datatypes.network.MacRequirements",uniqueId: "26ec2bfd-b904-46c7-87ed-b32775120f2c.mac_requirements"}]};
+
+
+ }
+}
+
+angular.module('Sdc.Services').factory('ComponentServiceNg2', downgradeInjectable(ComponentServiceNg2)); // This is in order to use the service in angular1 till we finish remove all angular1 code
diff --git a/catalog-ui/src/app/ng2/services/component-services/resource.service.ts b/catalog-ui/src/app/ng2/services/component-services/resource.service.ts
new file mode 100644
index 0000000000..650f244d38
--- /dev/null
+++ b/catalog-ui/src/app/ng2/services/component-services/resource.service.ts
@@ -0,0 +1,18 @@
+import { Injectable } from '@angular/core';
+import 'rxjs/add/operator/map';
+import 'rxjs/add/operator/toPromise';
+import { Http, Response, Headers, RequestOptions } from '@angular/http';
+
+@Injectable()
+export class ResourceServiceNg2 {
+
+ protected baseUrl = "";
+
+ constructor(private http: Http) {
+
+ }
+
+
+
+
+}
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
new file mode 100644
index 0000000000..b47b64c5c2
--- /dev/null
+++ b/catalog-ui/src/app/ng2/services/component-services/service.service.ts
@@ -0,0 +1,31 @@
+import { Injectable } from '@angular/core';
+import { Observable } from 'rxjs/Observable';
+import 'rxjs/add/operator/map';
+import 'rxjs/add/operator/toPromise';
+import { Response } from '@angular/http';
+import {Service} from "app/models";
+import { downgradeInjectable } from '@angular/upgrade/static';
+import {sdc2Config} from "../../../../main";
+import {HttpService} from "../http.service";
+
+
+@Injectable()
+export class ServiceServiceNg2 {
+
+ protected baseUrl = "";
+
+ constructor(private http: HttpService) {
+ this.baseUrl = sdc2Config.api.root + sdc2Config.api.component_api_root;
+ }
+
+ validateConformanceLevel(service: Service): Observable<boolean> {
+
+ return this.http.get(this.baseUrl + service.getTypeUrl() + service.uniqueId + '/conformanceLevelValidation')
+ .map((res: Response) => {
+ return res.json();
+ });
+ }
+
+}
+
+angular.module('Sdc.Services').factory('ServiceServiceNg2', downgradeInjectable(ServiceServiceNg2)); // This is in order to use the service in angular1 till we finish remove all angular1 code
diff --git a/catalog-ui/src/app/ng2/services/config.service.ts b/catalog-ui/src/app/ng2/services/config.service.ts
new file mode 100644
index 0000000000..0ac3b5a397
--- /dev/null
+++ b/catalog-ui/src/app/ng2/services/config.service.ts
@@ -0,0 +1,51 @@
+/**
+ * Created by ob0695 on 4/9/2017.
+ */
+
+import { Injectable } from '@angular/core';
+import { Http, Response } from '@angular/http';
+import 'rxjs/add/operator/toPromise';
+import {IAppConfigurtaion, ValidationConfiguration, Validations} from "app/models";
+import {sdc2Config} from './../../../main';
+
+declare var __ENV__: string;
+
+@Injectable()
+export class ConfigService {
+
+ private baseUrl;
+ public configuration: IAppConfigurtaion;
+
+ constructor(private http: Http) {
+ this.baseUrl = sdc2Config.api.root + sdc2Config.api.component_api_root;
+ }
+
+ loadValidationConfiguration(): Promise<ValidationConfiguration> {
+ let url: string = sdc2Config.validationConfigPath;
+ let promise: Promise<ValidationConfiguration> = this.http.get(url).map((res: Response) => res.json()).toPromise();
+ promise.then((validationData: Validations) => {
+ ValidationConfiguration.validation = validationData;
+ }).catch((ex) => {
+ console.error('Error loading validation.json configuration file, using fallback data', ex);
+
+ let fallback:Validations = {
+ "propertyValue": {
+ "max": 2500,
+ "min": 0
+ },
+
+ "validationPatterns": {
+ "string": "^[\\sa-zA-Z0-9+-]+$",
+ "comment": "^[\\sa-zA-Z0-9+-_\\{\\}\"]+$",
+ "integer": "^(([-+]?\\d+)|([-+]?0x[0-9a-fA-F]+))$"
+ }
+ };
+
+ ValidationConfiguration.validation = fallback;
+
+ });
+
+ return promise;
+ }
+
+}
diff --git a/catalog-ui/src/app/ng2/services/cookie.service.ts b/catalog-ui/src/app/ng2/services/cookie.service.ts
new file mode 100644
index 0000000000..2dc2ac3e6b
--- /dev/null
+++ b/catalog-ui/src/app/ng2/services/cookie.service.ts
@@ -0,0 +1,65 @@
+import { Injectable } from '@angular/core';
+import {IAppConfigurtaion, ICookie} from "../../models/app-config";
+import {sdc2Config} from './../../../main';
+
+@Injectable()
+export class Cookie2Service {
+
+ private cookie:ICookie;
+ private cookiePrefix:string;
+
+ constructor() {
+ this.cookie = sdc2Config.cookie;
+
+ this.cookiePrefix = '';
+ let junctionName:string = this.getCookieByName(this.cookie.junctionName);
+ if ((junctionName !== null) && (junctionName !== '')) {
+ this.cookiePrefix = this.cookie.prefix + junctionName + '!';
+ }
+ console.log("junctionName:" + junctionName);
+ }
+
+ private getCookieByName = (cookieName:string):string => {
+ cookieName += '=';
+ let cookies:Array<string> = document.cookie.split(';');
+ let cookieVal:string = '';
+ cookies.forEach((cookie:string) => {
+ while (cookie.charAt(0) === ' ') {
+ cookie = cookie.substring(1);
+ }
+ if (cookie.indexOf(cookieName) === 0) {
+ cookieVal = cookie.substring(cookieName.length, cookie.length);
+ return;
+ }
+ });
+ return cookieVal;
+ };
+
+ public getUserIdSuffix = ():string => {
+ return this.cookie.userIdSuffix;
+ };
+
+ public getUserId = ():string => {
+ let userIdCookieName:string = this.cookiePrefix + this.cookie.userIdSuffix;
+ let userId:string = this.getCookieByName(userIdCookieName);
+ return userId;
+ };
+
+ public getFirstName = ():string => {
+ let firstNameCookieName:string = this.cookiePrefix + this.cookie.userFirstName;
+ let firstName:string = this.getCookieByName(firstNameCookieName);
+ return firstName;
+ };
+
+ public getLastName = ():string => {
+ let lastNameCookieName:string = this.cookiePrefix + this.cookie.userLastName;
+ let lastName:string = this.getCookieByName(lastNameCookieName);
+ return lastName;
+ };
+
+ public getEmail = ():string => {
+ let emailCookieName:string = this.cookiePrefix + this.cookie.userEmail;
+ let email:string = this.getCookieByName(emailCookieName);
+ return email;
+ }
+}
diff --git a/catalog-ui/src/app/ng2/services/data-type.service.ts b/catalog-ui/src/app/ng2/services/data-type.service.ts
new file mode 100644
index 0000000000..e7ea1a8430
--- /dev/null
+++ b/catalog-ui/src/app/ng2/services/data-type.service.ts
@@ -0,0 +1,69 @@
+import { Injectable } from '@angular/core';
+import { DataTypeModel, DataTypesMap, PropertyBEModel, PropertyFEModel, DerivedFEProperty, DerivedFEPropertyMap } from "app/models";
+import { DataTypesService } from "app/services/data-types-service";
+import { PROPERTY_DATA, PROPERTY_TYPES } from "app/utils";
+
+/** This is a new service for NG2, to eventually replace app/services/data-types-service.ts
+ *
+ * This service is a singleton that holds a map of all DataTypes, recieved from server on load.
+ * It also contains convenience methods to check if a string is a valid dataType, and to retrieve a dataType's properties recursively
+ */
+
+@Injectable()
+export class DataTypeService {
+ private dataTypes: DataTypesMap;
+
+ constructor(private dataTypeService: DataTypesService) {
+ this.dataTypes = dataTypeService.getAllDataTypes(); //This should eventually be replaced by an NG2 call to the backend instead of utilizing Angular1 downgraded component.
+ }
+
+ public getDataTypeByTypeName(typeName: string): DataTypeModel {
+ return this.dataTypes[typeName];
+ }
+/*
+ //if the dt derived from simple- return the first parent type, else- return null
+ public getTypeForDataTypeDerivedFromSimple = (dataTypeName:string):string => {
+ /////////temporary hack for tosca primitives///////////////////////
+ if (!this.dataTypes[dataTypeName]) {
+ return PROPERTY_TYPES.STRING;
+ }
+ ///////////////////////////////////////////////////////////////////
+ if (this.dataTypes[dataTypeName].derivedFromName == PROPERTY_DATA.ROOT_DATA_TYPE || this.dataTypes[dataTypeName].properties) {
+ return null;
+ }
+ if (PROPERTY_DATA.SIMPLE_TYPES.indexOf(this.dataTypes[dataTypeName].derivedFromName) > -1) {
+ return this.dataTypes[dataTypeName].derivedFromName
+ }
+ return this.getTypeForDataTypeDerivedFromSimple(this.dataTypes[dataTypeName].derivedFromName);
+ };
+
+ /**
+ * The function returns all properties for the DataType passed in, and recurses through parent dataTypes (derivedFrom) to retrieve their properties as well
+ * @param dataTypeObj
+ *
+ public getDataTypePropertiesRecursively(dataTypeObj: DataTypeModel): Array<PropertyBEModel> {
+ let propertiesArray: Array<PropertyBEModel> = dataTypeObj.properties || [];
+ if (PROPERTY_DATA.ROOT_DATA_TYPE !== dataTypeObj.derivedFromName) {
+ propertiesArray = propertiesArray.concat(this.getDataTypePropertiesRecursively(dataTypeObj.derivedFrom));
+ }
+ return propertiesArray;
+ }
+*/
+
+ public getDerivedDataTypeProperties(dataTypeObj: DataTypeModel, propertiesArray: Array<DerivedFEProperty>, parentName: string) {
+ //push all child properties to array
+ if (dataTypeObj.properties) {
+ dataTypeObj.properties.forEach((derivedProperty) => {
+ propertiesArray.push(new DerivedFEProperty(derivedProperty, parentName));
+ let derivedDataTypeObj: DataTypeModel = this.getDataTypeByTypeName(derivedProperty.type);
+ this.getDerivedDataTypeProperties(derivedDataTypeObj, propertiesArray, parentName + "#" + derivedProperty.name);
+ });
+ }
+ //recurse parent (derivedFrom), in case one of parents contains properties
+ if (PROPERTY_DATA.ROOT_DATA_TYPE !== dataTypeObj.derivedFrom.name) {
+ this.getDerivedDataTypeProperties(dataTypeObj.derivedFrom, propertiesArray, parentName);
+ }
+ }
+
+}
+
diff --git a/catalog-ui/src/app/ng2/services/http.service.ts b/catalog-ui/src/app/ng2/services/http.service.ts
new file mode 100644
index 0000000000..92e8ced142
--- /dev/null
+++ b/catalog-ui/src/app/ng2/services/http.service.ts
@@ -0,0 +1,73 @@
+import {Injectable} from '@angular/core';
+import {Http, XHRBackend, RequestOptions, Request, RequestOptionsArgs, Response, Headers} from '@angular/http';
+import {Observable} from 'rxjs/Observable';
+import {UUID} from 'angular2-uuid';
+import 'rxjs/add/operator/map';
+import 'rxjs/add/operator/catch';
+import {Dictionary} from "../../utils/dictionary/dictionary";
+import {SharingService, CookieService} from "app/services";
+import {sdc2Config} from './../../../main';
+
+@Injectable()
+export class HttpService extends Http {
+
+ constructor(backend:XHRBackend, options:RequestOptions, private sharingService:SharingService, private cookieService: CookieService) {
+ super(backend, options);
+ this._defaultOptions.withCredentials = true;
+ this._defaultOptions.headers.append(cookieService.getUserIdSuffix(), cookieService.getUserId());
+ }
+
+ request(request:string|Request, options?:RequestOptionsArgs):Observable<Response> {
+ /**
+ * For every request to the server, that the service id, or resource id is sent in the URL, need to pass UUID in the header.
+ * Check if the unique id exists in uuidMap, and if so get the UUID and add it to the header.
+ */
+ if (typeof request === 'string') { // meaning we have to add the token to the options, not in url
+ if (!options) {
+ // make option object
+ options = {headers: new Headers()};
+ }
+
+ var uuidValue = this.getUuidValue(request);
+ if(uuidValue!= ''){
+ options.headers['X-ECOMP-ServiceID'] = uuidValue;
+
+ }
+ options.headers.set('X-ECOMP-RequestID', UUID.UUID());
+
+ } else {
+ // we have to add the token to the url object
+ var uuidValue = this.getUuidValue((<Request>request).url);
+ if(uuidValue!= ''){
+ request.headers.set('X-ECOMP-ServiceID',uuidValue);
+
+ }
+ request.headers.set('X-ECOMP-RequestID', UUID.UUID());
+ }
+ return super.request(request, options).catch(this.catchAuthError(this));
+ }
+
+ private getUuidValue = (url: string) :string => {
+ let map:Dictionary<string, string> = this.sharingService.getUuidMap();
+ if (map && url.indexOf(sdc2Config.api.root) > 0) {
+ map.forEach((key:string) => {
+ if (url.indexOf(key) !== -1) {
+ return this.sharingService.getUuidValue(key);
+ }
+ });
+ }
+ return '';
+ }
+
+ private catchAuthError(self:HttpService) {
+ // we have to pass HttpService's own instance here as `self`
+ return (res:Response) => {
+ console.log(res);
+ if (res.status === 401 || res.status === 403) {
+ // if not authenticated
+ console.log(res);
+ }
+ return Observable.throw(res);
+ };
+ }
+}
diff --git a/catalog-ui/src/app/ng2/services/mocks/properties.mock.ts b/catalog-ui/src/app/ng2/services/mocks/properties.mock.ts
new file mode 100644
index 0000000000..0ce253e80b
--- /dev/null
+++ b/catalog-ui/src/app/ng2/services/mocks/properties.mock.ts
@@ -0,0 +1,16 @@
+// import { PropertiesResponse } from './../../services/responses/properties.response';
+//
+// export const PROPERTIES_RESPONSE: PropertiesResponse = {
+// "status":"ok",
+// "errorcode":0,
+// "properties": [
+// {"name": "name1"},
+// {"name": "name2"}
+// ]
+// };
+
+
+export const COMPONENT_INSTANCE_RESPONSE: any = [{"uniqueId":"23b78e64-1734-4898-889d-eab9eba50019.724ef51f-7595-4336-a8ef-b144e1c937da.contrailv2vlansubinterface5","name":"CP2","normalizedName":"cp2","componentUid":"724ef51f-7595-4336-a8ef-b144e1c937da","creationTime":1489586037851,"modificationTime":1489586037851,"posX":"549","posY":"531","propertyValueCounter":1,"inputValueCounter":1,"originType":"CP","customizationUUID":"0222925a-06c6-48ca-8573-13ba3b650539"},{"uniqueId":"23b78e64-1734-4898-889d-eab9eba50019.8ac5a229-60d8-4d7f-8e0f-b630da55c3ae.ldsa_os27","name":"VF22","normalizedName":"vf22","componentUid":"8ac5a229-60d8-4d7f-8e0f-b630da55c3ae","creationTime":1489590640842,"modificationTime":1489590640842,"posX":"644","posY":"359","propertyValueCounter":1,"inputValueCounter":1,"originType":"VF","customizationUUID":"fb34e6a1-f0cc-42e3-853f-178fb122d670"},{"uniqueId":"23b78e64-1734-4898-889d-eab9eba50019.00ac92c4-a0c5-4567-aefb-f2b7f3fecba9.vl4","name":"VL1","normalizedName":"vl1","componentUid":"00ac92c4-a0c5-4567-aefb-f2b7f3fecba9","creationTime":1489586006630,"modificationTime":1489586006630,"posX":"486","posY":"530","propertyValueCounter":1,"inputValueCounter":1,"originType":"VL","customizationUUID":"8d156a97-38ca-4637-a6a6-9268dd708431"},{"uniqueId":"23b78e64-1734-4898-889d-eab9eba50019.39bf293d-2aa9-4596-b85d-a6fdef18aadc.newvf428","name":"VF11","normalizedName":"vf11","componentUid":"39bf293d-2aa9-4596-b85d-a6fdef18aadc","creationTime":1489590742501,"modificationTime":1489590742501,"posX":"350","posY":"76","propertyValueCounter":1,"inputValueCounter":1,"originType":"VF","customizationUUID":"253f646d-87d0-4b84-bc20-20343b6e28a2"},{"uniqueId":"23b78e64-1734-4898-889d-eab9eba50019.f8f30484-5761-4de8-9de8-12f288ee0a54.contrailport7","name":"CP1","normalizedName":"cp1","componentUid":"f8f30484-5761-4de8-9de8-12f288ee0a54","creationTime":1489587207447,"modificationTime":1489587207447,"posX":"418","posY":"531","propertyValueCounter":1,"inputValueCounter":1,"originType":"CP","customizationUUID":"206b4ffa-e520-496a-b57b-0c103eff8c17"},{"uniqueId":"23b78e64-1734-4898-889d-eab9eba50019.16022d8c-80cf-46e5-a730-5b4f634ea905.extcp38","name":"ExtCP 38","normalizedName":"extcp38","componentUid":"16022d8c-80cf-46e5-a730-5b4f634ea905","creationTime":1489654844116,"modificationTime":1489654844116,"posX":"473","posY":"419","propertyValueCounter":5,"inputValueCounter":1,"originType":"CP","customizationUUID":"21ebc94a-65b9-463e-b696-07cea08f789a"},{"uniqueId":"23b78e64-1734-4898-889d-eab9eba50019.f8f30484-5761-4de8-9de8-12f288ee0a54.contrailport44","name":"ContrailPort 44","normalizedName":"contrailport44","componentUid":"f8f30484-5761-4de8-9de8-12f288ee0a54","creationTime":1489939897435,"modificationTime":1489939897435,"posX":"480","posY":"265","propertyValueCounter":1,"inputValueCounter":1,"originType":"CP","customizationUUID":"607e5819-fa19-4aac-97f6-04f092493a02"},{"uniqueId":"23b78e64-1734-4898-889d-eab9eba50019.8ac5a229-60d8-4d7f-8e0f-b630da55c3ae.ldsa_os6","name":"VF2","normalizedName":"vf2","componentUid":"8ac5a229-60d8-4d7f-8e0f-b630da55c3ae","creationTime":1489586613957,"modificationTime":1489586613957,"posX":"638","posY":"531","propertyValueCounter":1,"inputValueCounter":1,"originType":"VF","customizationUUID":"12501356-44cc-427b-8749-c114d3434271"},{"uniqueId":"23b78e64-1734-4898-889d-eab9eba50019.8ac5a229-60d8-4d7f-8e0f-b630da55c3ae.ldsa_os8","name":"VF1","normalizedName":"vf1","componentUid":"8ac5a229-60d8-4d7f-8e0f-b630da55c3ae","creationTime":1489587393612,"modificationTime":1489587393612,"posX":"334","posY":"529","propertyValueCounter":1,"inputValueCounter":1,"originType":"VF","customizationUUID":"cbca1972-e64c-4119-a430-ec90aa1397a7"},{"uniqueId":"23b78e64-1734-4898-889d-eab9eba50019.8ac5a229-60d8-4d7f-8e0f-b630da55c3ae.ldsa_os32","name":"VF12","normalizedName":"vf12","componentUid":"8ac5a229-60d8-4d7f-8e0f-b630da55c3ae","creationTime":1489591429630,"modificationTime":1489591429630,"posX":"367","posY":"269","propertyValueCounter":1,"inputValueCounter":1,"originType":"VF","customizationUUID":"ac9c77c1-e84d-4967-9ea2-d929b56d10a8"}];
+export const COMPONENT_INPUT_RESPONSE: any = [{"uniqueId":"23b78e64-1734-4898-889d-eab9eba50019.extcp38_mac_requirements_mac_range_plan","type":"string","required":true,"definition":false,"description":"reference to a MAC address range plan","password":false,"name":"extcp38_mac_requirements_mac_range_plan","parentUniqueId":"23b78e64-1734-4898-889d-eab9eba50019"},{"uniqueId":"23b78e64-1734-4898-889d-eab9eba50019.extcp38_order","type":"integer","required":true,"definition":false,"description":"The order of the CP on the compute instance (e.g. eth2).","schema":{"property":{"definition":true,"password":false}},"password":false,"name":"extcp38_order","parentUniqueId":"23b78e64-1734-4898-889d-eab9eba50019"},{"uniqueId":"23b78e64-1734-4898-889d-eab9eba50019.extcp38_network_role_tag","type":"string","required":true,"definition":false,"description":"Must correlate to the set of defined “network-role” tag identifiers from the associated HEAT template","schema":{"property":{"definition":true,"password":false}},"password":false,"name":"extcp38_network_role_tag","parentUniqueId":"23b78e64-1734-4898-889d-eab9eba50019"}];
+export const COMPONENT_PROPERTIES_RESPONSE: any =[{"schema":{"property":{"password":false,"definition":false}},"password":false,"parentUniqueId":"b80765f0-ef2b-43b1-b658-04e13970b5cf","defaultValue":"{\"naming_policy\":\"ggg\",\"ecomp_generated_naming\":false,\"supplemental_data\":{\"fff\":\"44\",\"uuu\":\"56\"}}","name":"inner-map-1","definition":false,"type":"org.openecomp.datatypes.EcompNaming","uniqueId":"property.b80765f0-ef2b-43b1-b658-04e13970b5cf.inner-map-1","required":false},{"schema":{"property":{"password":false,"definition":false}},"password":false,"parentUniqueId":"b80765f0-ef2b-43b1-b658-04e13970b5cf","defaultValue":"{\"min_subnets_count\":1,\"supplemental_data\":{\"aa\":\"11\",\"bb\":\"22\"},\"cidr_mask\":23,\"dhcp_enabled\":false,\"ip_version\":3}","name":"inner-simple-map","definition":false,"type":"org.openecomp.datatypes.network.IPv4SubnetAssignments","uniqueId":"property.b80765f0-ef2b-43b1-b658-04e13970b5cf.inner-simple-map","required":false},{"schema":{"property":{"password":false,"definition":false,"type":"org.openecomp.datatypes.heat.network.AddressPair"}},"password":false,"parentUniqueId":"b80765f0-ef2b-43b1-b658-04e13970b5cf","defaultValue":"{\"aaa\":{\"mac_address\":\"34\",\"ip_address\":\"56\"},\"bbb\":{\"mac_address\":\"sddf\",\"ip_address\":\"dfdg\"}}","name":"data-type-map","definition":false,"type":"map","uniqueId":"property.b80765f0-ef2b-43b1-b658-04e13970b5cf.data-type-map","required":false},{"schema":{"property":{"password":false,"definition":false,"type":"string"}},"password":false,"parentUniqueId":"b80765f0-ef2b-43b1-b658-04e13970b5cf","defaultValue":"{\"www\":\"dfsdf\",\"aaaa\":\"ert\"}","name":"simple-map","definition":false,"type":"map","uniqueId":"property.b80765f0-ef2b-43b1-b658-04e13970b5cf.simple-map","required":false}];
+
diff --git a/catalog-ui/src/app/ng2/services/posts.service.ts b/catalog-ui/src/app/ng2/services/posts.service.ts
new file mode 100644
index 0000000000..dbfd44f219
--- /dev/null
+++ b/catalog-ui/src/app/ng2/services/posts.service.ts
@@ -0,0 +1,54 @@
+import { Injectable } from '@angular/core';
+import { Observable } from 'rxjs/Observable';
+import 'rxjs/add/operator/map';
+import 'rxjs/add/operator/toPromise';
+import 'rxjs/Rx';
+import {Response, Headers, RequestOptions, Http} from '@angular/http';
+import { COMPONENT_INSTANCE_RESPONSE,COMPONENT_INPUT_RESPONSE,COMPONENT_PROPERTIES_RESPONSE } from './mocks/properties.mock';
+import { HttpService } from './http.service';
+import { sdc2Config } from './../../../main';
+import {IAppConfigurtaion} from "../../models/app-config";
+
+@Injectable()
+export class PostsService {
+
+ private base;
+
+ constructor(private http: HttpService) {
+ this.base = sdc2Config.api.root;
+ }
+
+ getAppVersion(): Observable<JSON> {
+ return this.http
+ .get(this.base + sdc2Config.api.GET_SDC_Version)
+ .map((res: Response) => res.json());
+ }
+
+ // getProperties(id:string): Observable<any> {
+ // return this.http
+ // .get(this.base + sdc2Config.api.GET_SDC_Version)
+ // .map((res: Response) => res.json());
+ // }
+
+ getProperties(): Observable<any> {
+ return Observable.create(observer => {
+ observer.next(COMPONENT_PROPERTIES_RESPONSE);
+ observer.complete();
+ });
+ }
+
+ getInstance(): Observable<any> {
+ return Observable.create(observer => {
+ observer.next(COMPONENT_INSTANCE_RESPONSE);
+ observer.complete();
+ });
+ }
+
+ getInputs(): Observable<any> {
+ return Observable.create(observer => {
+ observer.next(COMPONENT_INPUT_RESPONSE);
+ observer.complete();
+ });
+ }
+
+}
diff --git a/catalog-ui/src/app/ng2/services/properties.service.ts b/catalog-ui/src/app/ng2/services/properties.service.ts
new file mode 100644
index 0000000000..638e537cd1
--- /dev/null
+++ b/catalog-ui/src/app/ng2/services/properties.service.ts
@@ -0,0 +1,249 @@
+import { Injectable } from '@angular/core';
+import { DataTypeModel, PropertyFEModel, PropertyBEModel, SchemaProperty, DerivedFEProperty, DerivedFEPropertyMap, DerivedPropertyType, InputFEModel} from "app/models";
+import { DataTypeService } from "./data-type.service";
+import { PROPERTY_TYPES } from "app/utils";
+import { ContentAfterLastDotPipe } from "../pipes/contentAfterLastDot.pipe";
+import { UUID } from "angular2-uuid";
+
+@Injectable()
+export class PropertiesService {
+
+ constructor(private dataTypeService:DataTypeService, private contentAfterLastDotPipe:ContentAfterLastDotPipe) {
+ }
+
+ public getParentPropertyFEModelFromPath = (properties:Array<PropertyFEModel>, path:string) => {
+ let parent:PropertyFEModel = _.find(properties, (property:PropertyFEModel):boolean=>{
+ return property.name === path.substring(0, path.indexOf('#'));
+ });
+ return parent;
+ }
+
+ //undo disabling of parent and child props=
+ public undoDisableRelatedProperties = (property: PropertyFEModel, childPath?: string): void => {
+ property.isDisabled = false;
+ if (!childPath) {
+ property.isSelected = false;
+ property.flattenedChildren && property.flattenedChildren.map(child => child.isDisabled = false);
+ } else { //QND - unselect everything and then re-do the disabling of declared props. TODO: put a flag on propertyFEModel instead to indicate who's causing them to be disabled instead
+ property.flattenedChildren.filter(child => child.isDisabled && !child.isDeclared).map(child => child.isDisabled = false);
+ property.flattenedChildren.filter(child => child.isDeclared || child.isSelected).forEach((childProp) => { //handle brothers who are selected - redo their disabled relatives as well
+ this.disableRelatedProperties(property, childProp.propertiesName);
+ });
+ }
+ }
+
+ //disable parents and children of prop
+ public disableRelatedProperties = (property:PropertyFEModel, childPath?: string): void => {
+ if (!childPath) { //selecting the parent property
+ property.isSelected = true;
+ property.flattenedChildren && property.flattenedChildren.map(child => { child.isSelected = false; child.isDisabled = true; });
+ } else {
+ property.isSelected = false;
+ property.isDisabled = true;
+ property.flattenedChildren.filter((childProp: DerivedFEProperty) => {
+ return (childProp.propertiesName.indexOf(childPath + "#") > -1 //is child of prop to disable
+ || childPath.indexOf(childProp.propertiesName + "#") > -1); //is parent of prop to disable
+ }).map((child: DerivedFEProperty) => { child.isSelected = false; child.isDisabled = true; });
+ }
+ }
+
+ public getCheckedProperties = (properties:Array<PropertyFEModel>): Array<PropertyBEModel> => {
+ let selectedProps: Array<PropertyBEModel> = [];
+ properties.forEach(prop => {
+ if (prop.isSelected && !prop.isDeclared && !prop.isDisabled) {
+ selectedProps.push(new PropertyBEModel(prop));
+ } else if(prop.flattenedChildren) {
+ prop.flattenedChildren.forEach((child) => {
+ if (child.isSelected && !child.isDeclared && !child.isDisabled) {
+ let childProp = new PropertyBEModel(prop, child); //create it from the parent
+ selectedProps.push(childProp);
+ }
+ })
+ }
+ });
+ return selectedProps;
+ }
+
+ /**
+ * Build hirarchy structure for the tree when user selects on table row.
+ * First create Array<SimpleFlatProperty> and insert also the parent (PropertyFEModel) to this array.
+ * The Array is flat and contains SimpleFlatProperty that has parentName and uniqueId.
+ * Now we build hirarchy from this Array (that includes childrens) and return it for the tree
+ *
+ * @argument property: PropertyFEModel - property contains flattenedChildren array of DerivedFEProperty
+ * @returns Array<SimpleFlatProperty> - containing childrens Array<SimpleFlatProperty>, augmantin childrens to SimpleFlatProperty.
+ */
+ public getSimplePropertiesTree(property: PropertyFEModel, instanceName:string):Array<SimpleFlatProperty> {
+ // Build Array of SimpleFlatProperty before unflatten function
+ let flattenProperties:Array<SimpleFlatProperty> = [];
+ flattenProperties.push(new SimpleFlatProperty(property.uniqueId, property.name, property.name, '', instanceName)); // Push the root property
+ _.each(property.flattenedChildren, (child:DerivedFEProperty):void => {
+ flattenProperties.push(new SimpleFlatProperty(child.uniqueId, child.propertiesName, child.name, child.parentName, instanceName));
+ });
+
+ let tree = this.unflatten(flattenProperties, '', []);
+ return tree[0].childrens; // Return the childrens without the root.
+ }
+
+ /**
+ * Unflatten Array<SimpleFlatProperty> and build hirarchy.
+ * The result will be Array<SimpleFlatProperty> that augmantin with childrens for each SimpleFlatProperty.
+ */
+ private unflatten( array:Array<SimpleFlatProperty>, parent:any, tree?:any ):any {
+ tree = typeof tree!=='undefined' ? tree : [];
+ parent = typeof parent!=='undefined' && parent!=='' ? parent : { path: '' };
+
+ var childrens = _.filter( array, (child:SimpleFlatProperty):boolean => {
+ return child.parentName == parent.path;
+ });
+
+ if( !_.isEmpty( childrens ) ){
+ if( parent.path == '' ){
+ tree = childrens;
+ } else {
+ parent['childrens'] = childrens;
+ }
+ _.each( childrens, ( child ):void => {
+ this.unflatten( array, child );
+ });
+ }
+ return tree;
+ }
+
+ // TODO: To remove
+ // public convertPropertiesToFEAndInitialize(properties: Array<PropertyBEModel>): Array<PropertyFEModel> {
+ // let props:Array<PropertyFEModel> = [];
+ // _.forEach(properties, (property: PropertyFEModel, index: number) => {
+ // props[index] = new PropertyFEModel(property);
+ // this.initValueObjectRef(props[index]);
+ // if (props[index].isDataType ||
+ // ((props[index].type === PROPERTY_TYPES.MAP || props[index].type === PROPERTY_TYPES.LIST) && props[index].schema.property.isDataType)) {
+ // props[index].valueObjectRef = props[index].valueObjectRef || {};
+ // let defaultValueObject:any = props[index].defaultValue ? JSON.parse(props[index].defaultValue): null;
+ // this.createPropertiesTreeForProp(props[index], true, defaultValueObject);
+ // }
+ // });
+ // return props;
+ // }
+
+
+ /**
+ * Converts a property's map values to properties and adds them to property.childrenProperties
+ * @param property - property to add children to
+ * @param onlyFirstLevel - recursively retrieve properties for each dataType?
+ */
+ //TODO: To remove
+ // public createPropertyNodesForMapOfDataTypes(property: PropertyFEModel, onlyFirstLevel:boolean):void {
+ // property.childrenProperties = [];
+ // angular.forEach(property.valueObjectRef,function(itemInMap:any, keyInMap:string){
+ // let newProperty: PropertyFEModel = new PropertyFEModel(keyInMap,
+ // property.schema.property.type,
+ // UUID.UUID(),
+ // property,
+ // property.valueObjectRef[keyInMap]);
+ // !onlyFirstLevel && this.createPropertiesTreeForProp(newProperty);
+ // property.childrenProperties.push(newProperty);
+ // },this);
+ // }
+
+
+ /**
+ * Converts a property's list values to properties and adds them to property.childrenProperties
+ * @param property - property to add children to
+ * @param onlyFirstLevel - recursively retrieve properties for each dataType?
+ */
+ //TODO: To remove
+ // public createPropertyNodesForListOfDataTypes(property: PropertyFEModel, onlyFirstLevel:boolean):void {
+ // property.childrenProperties = [];
+ // property.valueObjectRef.forEach((itemInList:any, index:number):void =>{
+ // let newProperty: PropertyFEModel = new PropertyFEModel(this.contentAfterLastDotPipe.transform(property.schema.property.type),
+ // property.schema.property.type,
+ // UUID.UUID(),
+ // property,
+ // property.valueObjectRef[index]);
+ // !onlyFirstLevel && this.createPropertiesTreeForProp(newProperty);
+ // property.childrenProperties.push(newProperty);
+ // });
+ // }
+
+ // private checkIfPropertyDerivedFromSimpleAndUpdateProp(property:PropertyFEModel | SchemaProperty): boolean{
+ // property.derivedFromSimpleTypeName = this.dataTypeService.getTypeForDataTypeDerivedFromSimple(property.type);
+ // if(property.derivedFromSimpleTypeName){
+ // property.isSimpleType = true;
+ // property.isDataType = false;
+ // }
+ // return property.isSimpleType;
+ // }
+
+ // TODO: Remove
+ public createPropertiesTreeForProp(property: PropertyFEModel, onlyFirstLevel?: boolean, defaultValueObj?: any): void {
+ }
+
+ public getPropertyFEModelFromDerivedPropertyUniqueId(properties: Array<PropertyFEModel>, uniqueId: string): PropertyFEModel {
+ // _.each(properties, (property):void => {
+ // property.flattenedChildren
+
+ // });
+
+ // let rootProperty = _.find(properties, (property):boolean => { return property.uniqueId === uniqueId; });
+ // if
+ return null;
+ }
+
+ /**
+ * Utilizes the dataTypeService to retrieve children properties from dataTypes recursively.
+ * @param property
+ * @param onlyFirstLevel
+ */
+ // TODO: To remove
+ // public createPropertiesTreeForProp(property: PropertyFEModel, onlyFirstLevel?:boolean, defaultValueObj?:any ):void{
+ // if (property.isDataType && !this.checkIfPropertyDerivedFromSimpleAndUpdateProp(property)){
+ // let dataType: DataTypeModel = this.dataTypeService.getDataTypeByTypeName(property.type);
+ // property.childrenProperties = [];
+ // let childrenProperties = this.dataTypeService.getDataTypePropertiesRecursively(dataType);
+ // childrenProperties.forEach((childProperty: PropertyBEModel):void => {
+ // let childDataTypePropertyObj: PropertyFEModel = new PropertyFEModel(childProperty.name, childProperty.type,UUID.UUID(),property, {}, childProperty.schema);
+ // //init empty object in valueObjectRef[childProperty.name] because this property's children should has ref to this obj.
+ // if(!property.valueObjectRef[childDataTypePropertyObj.name]){
+ // if ((childDataTypePropertyObj.isDataType && !this.checkIfPropertyDerivedFromSimpleAndUpdateProp(childDataTypePropertyObj))
+ // || childDataTypePropertyObj.type === PROPERTY_TYPES.MAP){
+ // property.valueObjectRef[childDataTypePropertyObj.name] = {};
+ // }else if(childDataTypePropertyObj.type === PROPERTY_TYPES.LIST){
+ // property.valueObjectRef[childDataTypePropertyObj.name] = [];
+ // }
+ // }
+ // childDataTypePropertyObj.valueObjectRef = property.valueObjectRef[childDataTypePropertyObj.name];
+ // property.valueObjectRef[childDataTypePropertyObj.name] = property.valueObjectRef[childProperty.name] || childDataTypePropertyObj.defaultValue;
+ // if( !childDataTypePropertyObj.isDataType && defaultValueObj ){//init property default value
+ // childDataTypePropertyObj.defaultValue = JSON.stringify(defaultValueObj[childDataTypePropertyObj.name]);
+ // }
+ // property.childrenProperties.push(childDataTypePropertyObj);
+ // !onlyFirstLevel && this.createPropertiesTreeForProp(childDataTypePropertyObj, false, (defaultValueObj ? defaultValueObj[childDataTypePropertyObj.name] : null));
+ // });
+ // } else if (property.type == PROPERTY_TYPES.MAP && property.schema.property.isDataType && !this.checkIfPropertyDerivedFromSimpleAndUpdateProp(property.schema.property)){
+ // if( property.valueObjectRef && !_.isEmpty(property.valueObjectRef)){
+ // this.createPropertyNodesForMapOfDataTypes(property, onlyFirstLevel);
+ // }
+ // } else if (property.type == PROPERTY_TYPES.LIST && property.schema.property.isDataType && !this.checkIfPropertyDerivedFromSimpleAndUpdateProp(property.schema.property)){
+ // if( property.valueObjectRef && property.valueObjectRef.length){
+ // this.createPropertyNodesForListOfDataTypes(property, onlyFirstLevel);
+ // }
+ // }
+ // }
+}
+
+export class SimpleFlatProperty {
+ uniqueId:string;
+ path:string;
+ name:string;
+ parentName:string;
+ instanceName:string;
+
+ constructor(uniqueId?:string, path?:string, name?: string, parentName?:string, instanceName?:string) {
+ this.uniqueId = uniqueId;
+ this.path = path;
+ this.name = name;
+ this.parentName = parentName;
+ this.instanceName = instanceName;
+ }
+}
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
new file mode 100644
index 0000000000..7dcd95d712
--- /dev/null
+++ b/catalog-ui/src/app/ng2/services/responses/component-generic-response.ts
@@ -0,0 +1,77 @@
+/**
+ * Created by ob0695 on 4/18/2017.
+ */
+
+import { ArtifactGroupModel, PropertyModel, PropertiesGroup, AttributeModel, AttributesGroup, ComponentInstance,
+ InputModel, Module, ComponentMetadata, RelationshipModel, RequirementsGroup, CapabilitiesGroup,InputFEModel} from "app/models";
+import {CommonUtils} from "app/utils";
+import {Serializable} from "../utils/serializable";
+import {PropertyBEModel} from "../../../models/properties-inputs/property-be-model";
+
+export class ComponentGenericResponse implements Serializable<ComponentGenericResponse> {
+
+ public metadata: ComponentMetadata;
+ public deploymentArtifacts:ArtifactGroupModel;
+ public artifacts:ArtifactGroupModel;
+ public toscaArtifacts:ArtifactGroupModel;
+ public componentInstancesProperties:PropertiesGroup;
+ public componentInstancesAttributes:AttributesGroup;
+ public componentInstancesRelations:Array<RelationshipModel>;
+ public componentInstances:Array<ComponentInstance>;
+ public inputs:Array<PropertyBEModel>;
+ public capabilities:CapabilitiesGroup;
+ public requirements:RequirementsGroup;
+ public properties:Array<PropertyModel>;
+ public attributes:Array<AttributeModel>;
+ public groups:Array<Module>;
+ public interfaces:any;
+ public additionalInformation:any;
+ public derivedList:Array<any>;
+
+ deserialize (response): ComponentGenericResponse {
+
+ if(response.componentInstancesProperties) {
+ this.componentInstancesProperties = new PropertiesGroup(response.componentInstancesProperties);
+ }
+ if(response.componentInstancesAttributes) {
+ this.componentInstancesAttributes = new AttributesGroup(response.componentInstancesAttributes);
+ }
+ if(response.componentInstances) {
+ this.componentInstances = CommonUtils.initComponentInstances(response.componentInstances);
+ }
+ if(response.componentInstancesRelations) {
+ this.componentInstancesRelations = CommonUtils.initComponentInstanceRelations(response.componentInstancesRelations);
+ }
+ if(response.deploymentArtifacts) {
+ this.deploymentArtifacts = new ArtifactGroupModel(response.deploymentArtifacts);
+ }
+ if(response.inputs) {
+ this.inputs = CommonUtils.initInputs(response.inputs);
+ }
+ if(response.attributes) {
+ this.attributes = CommonUtils.initAttributes(response.attributes);
+ }
+ if(response.artifacts) {
+ this.artifacts = new ArtifactGroupModel(response.artifacts);
+ }
+ if(response.properties) {
+ this.properties = CommonUtils.initProperties(response.properties);
+ }
+ if(response.capabilities) {
+ this.capabilities = new CapabilitiesGroup(response.capabilities);
+ }
+ if(response.requirements) {
+ this.requirements = new RequirementsGroup(response.requirements);
+ }
+ if(response.toscaArtifacts) {
+ this.toscaArtifacts = new ArtifactGroupModel(response.toscaArtifacts);
+ }
+ if(response.metadata) {
+ this.metadata = new ComponentMetadata().deserialize(response.metadata);
+ }
+ if(response.groups) {
+ this.groups = CommonUtils.initModules(response.groups);
+ }
+ return this;
+ }
+}
diff --git a/catalog-ui/src/app/ng2/services/responses/properties.response.ts b/catalog-ui/src/app/ng2/services/responses/properties.response.ts
new file mode 100644
index 0000000000..a3d82500eb
--- /dev/null
+++ b/catalog-ui/src/app/ng2/services/responses/properties.response.ts
@@ -0,0 +1,7 @@
+export class PropertiesResponse {
+ properties: Array<Property>;
+}
+
+class Property {
+ name: string
+}
diff --git a/catalog-ui/src/app/ng2/services/utils/serializable.ts b/catalog-ui/src/app/ng2/services/utils/serializable.ts
new file mode 100644
index 0000000000..f8be120613
--- /dev/null
+++ b/catalog-ui/src/app/ng2/services/utils/serializable.ts
@@ -0,0 +1,6 @@
+/**
+ * Created by ob0695 on 4/26/2017.
+ */
+export interface Serializable<T> {
+ deserialize(input: Object): T;
+}
diff --git a/catalog-ui/src/app/ng2/shared/checkbox/checkbox.component.html b/catalog-ui/src/app/ng2/shared/checkbox/checkbox.component.html
new file mode 100644
index 0000000000..efe830d6e0
--- /dev/null
+++ b/catalog-ui/src/app/ng2/shared/checkbox/checkbox.component.html
@@ -0,0 +1,8 @@
+<div class="checkbox-container {{checkboxStyle}}">
+ <div class="checkbox-animation" [@checkEffect]="checked"></div>
+ <label class="checkbox-label" >
+ <input type="checkbox" class="checkbox-hidden" [ngModel]="checked" (ngModelChange)="toggleState($event)" [disabled]="disabled" />
+ <div class="checkbox-icon"></div>
+ <span *ngIf="label" class="checkbox-label-content">{{label}}</span>
+ </label>
+</div> \ No newline at end of file
diff --git a/catalog-ui/src/app/ng2/shared/checkbox/checkbox.component.less b/catalog-ui/src/app/ng2/shared/checkbox/checkbox.component.less
new file mode 100644
index 0000000000..7ed8a22194
--- /dev/null
+++ b/catalog-ui/src/app/ng2/shared/checkbox/checkbox.component.less
@@ -0,0 +1,64 @@
+ @import '../../../../assets/styles/tlv-sprite';
+
+.checkbox-container {
+ display:inline-block;
+ position:relative;
+ text-align: left;
+ height: 20px;
+
+
+ .checkbox-icon {
+ display: inline-block;
+ }
+
+ .checkbox-label {
+ font-weight: normal;
+ font-size: inherit;
+ }
+
+ .checkbox-label-content {
+ margin-left:2px;
+ }
+
+ .checkbox-icon::before {
+ .tlv-sprite;
+ background-position: -10px -60px;
+ width: 14px;
+ height: 14px;
+ content: '';
+ display: inline-block;
+ margin-right: 0px;
+ margin-top: -2px;
+ vertical-align: middle;
+ }
+
+ input[type=checkbox].checkbox-hidden {
+ width:0;
+ height:0;
+ display:none;
+ &:checked ~ .checkbox-icon::before{
+ background-position: -10px -120px;
+ }
+ &[disabled] ~ .checkbox-icon::before {
+ /* TODO: add disabled styles here */
+ background-image: none;
+ background-color: #EFEFEF;
+ border-radius: 2px;
+ border: solid #CCC 1px;
+ }
+ }
+
+ .checkbox-animation {
+ background-color: #009fdb;
+ position: absolute;
+ left: 2px;
+ top: 5px;
+ width:10px;
+ height:10px;
+ border-radius: 50%;
+ z-index: 1;
+ pointer-events: none;
+ opacity:0;
+ }
+
+}
diff --git a/catalog-ui/src/app/ng2/shared/checkbox/checkbox.component.ts b/catalog-ui/src/app/ng2/shared/checkbox/checkbox.component.ts
new file mode 100644
index 0000000000..5a9954c336
--- /dev/null
+++ b/catalog-ui/src/app/ng2/shared/checkbox/checkbox.component.ts
@@ -0,0 +1,30 @@
+import { Component, Input, Output, EventEmitter, ViewEncapsulation } from '@angular/core';
+import { trigger, state, style, transition, animate, keyframes } from '@angular/core';
+
+@Component({
+ selector: 'checkbox',
+ templateUrl: './checkbox.component.html',
+ styleUrls: ['./checkbox.component.less'],
+ encapsulation: ViewEncapsulation.None,
+ animations: [
+ trigger('checkEffect', [
+ state('true', style({ position: 'absolute', left: '2px', top: '5px', width: '10px', height: '10px', display: 'none', opacity: '.5' })),
+ state('false', style({ left: '-18px', top: '-15px', height: '50px', width: '50px', opacity: '0' })),
+ transition('1 => 0', animate('150ms ease-out')),
+ transition('0 => 1', animate('150ms ease-in'))
+ ])
+ ]
+})
+export class CheckboxComponent {
+
+ @Input() checkboxStyle: string;
+ @Input() label: string;
+ @Input() checked: boolean;
+ @Input() disabled: boolean;
+ @Output() checkedChange: EventEmitter<any> = new EventEmitter<any>();
+
+ toggleState(newValue:boolean) {
+ this.checkedChange.emit(newValue);
+ }
+}
+
diff --git a/catalog-ui/src/app/ng2/shared/checkbox/checkbox.module.ts b/catalog-ui/src/app/ng2/shared/checkbox/checkbox.module.ts
new file mode 100644
index 0000000000..116aa7f025
--- /dev/null
+++ b/catalog-ui/src/app/ng2/shared/checkbox/checkbox.module.ts
@@ -0,0 +1,28 @@
+import { NgModule } from '@angular/core';
+import { CommonModule } from '@angular/common';
+import { FormsModule } from '@angular/forms';
+import { BrowserModule } from '@angular/platform-browser';
+import { CheckboxComponent } from './checkbox.component';
+
+
+@NgModule({
+ imports: [CommonModule, BrowserModule, FormsModule],
+ declarations: [CheckboxComponent],
+ bootstrap: [],
+ exports: [CheckboxComponent]
+})
+export class CheckboxModule { }
+
+/** README: **/
+
+/** USAGE Example:
+ *In page.module.ts: import CheckboxModule
+ *In HTML:
+ *<checkbox checkboxStyle="class-goes-here" [label]="'Text goes here'" [disabled]="variable-goes-here" [(checked)]="default-or-variable-goes-here" (checkedChange)="change-event-goes-here()"></checkbox>
+ */
+
+/**STYLING: (ViewEncapsulation is set to None to allow styles to be overridden or customized)
+ *
+ * To create or override styles:
+ * Use /deep/ or >>> prefix to override styles via other components stylesheets
+ */ \ No newline at end of file
diff --git a/catalog-ui/src/app/ng2/shared/navbar/navbar-routes.config.ts b/catalog-ui/src/app/ng2/shared/navbar/navbar-routes.config.ts
new file mode 100644
index 0000000000..d8a21e66c8
--- /dev/null
+++ b/catalog-ui/src/app/ng2/shared/navbar/navbar-routes.config.ts
@@ -0,0 +1,7 @@
+import { MenuType, RouteInfo } from './navbar.metadata';
+
+export const ROUTES: RouteInfo[] = [
+ { path: 'page1', title: 'Logo', menuType: MenuType.BRAND },
+ { path: 'page1', title: 'Page 1', menuType: MenuType.LEFT },
+ { path: 'page2', title: 'Page 2', menuType: MenuType.LEFT }
+];
diff --git a/catalog-ui/src/app/ng2/shared/navbar/navbar.component.html b/catalog-ui/src/app/ng2/shared/navbar/navbar.component.html
new file mode 100644
index 0000000000..d783be4c27
--- /dev/null
+++ b/catalog-ui/src/app/ng2/shared/navbar/navbar.component.html
@@ -0,0 +1,23 @@
+<nav class="navbar navbar-dark">
+ <div class="clearfix">
+ <button (click)="isCollapsed = !isCollapsed"
+ class="navbar-toggler pull-xs-right hidden-sm-up" type="button"
+ aria-controls="bd-main-nav"
+ aria-label="Toggle navigation">
+ {{menuIcon}}
+ </button>
+ <a (click)="isCollapsed = true" class="navbar-brand hidden-sm-up" [routerLink]="[brandMenu.path]">
+ {{brandMenu.title}}
+ </a>
+ </div>
+ <div class="navbar-toggleable-xs navbar-collapse" id="bd-main-nav" [attr.aria-expanded]="!isCollapsed" [ngClass]="{collapse: isCollapsed}">
+ <ul class="nav navbar-nav">
+ <li (click)="isCollapsed = true" class="nav-item" routerLinkActive="active">
+ <a class="navbar-brand hidden-xs-down" [routerLink]="[brandMenu.path]">{{brandMenu.title}}</a>
+ </li>
+ <li (click)="isCollapsed = true" *ngFor="let menuItem of menuItems" class="nav-item" routerLinkActive="active" [ngClass]="getMenuItemClasses(menuItem)">
+ <a class="nav-item nav-link" [routerLink]="[menuItem.path]" routerLinkActive="active">{{menuItem.title}}</a>
+ </li>
+ </ul>
+ </div>
+</nav>
diff --git a/catalog-ui/src/app/ng2/shared/navbar/navbar.component.less b/catalog-ui/src/app/ng2/shared/navbar/navbar.component.less
new file mode 100644
index 0000000000..3e5165b798
--- /dev/null
+++ b/catalog-ui/src/app/ng2/shared/navbar/navbar.component.less
@@ -0,0 +1,11 @@
+.active {
+ color: #ffffff;
+}
+.navbar-toggler {
+ border: solid 1px #cccccc;
+ color: #ff0000;
+}
+.navbar {
+ background-color: #0000ff;
+ border-radius: 0;
+} \ No newline at end of file
diff --git a/catalog-ui/src/app/ng2/shared/navbar/navbar.component.ts b/catalog-ui/src/app/ng2/shared/navbar/navbar.component.ts
new file mode 100644
index 0000000000..b174f9d18d
--- /dev/null
+++ b/catalog-ui/src/app/ng2/shared/navbar/navbar.component.ts
@@ -0,0 +1,32 @@
+import {Component, OnInit, ViewEncapsulation} from '@angular/core';
+import { ROUTES } from './navbar-routes.config';
+import { MenuType, RouteInfo } from './navbar.metadata';
+
+@Component({
+ selector: 'app-navbar',
+ templateUrl: './navbar.component.html',
+ styleUrls: [ './navbar.component.less' ],
+ encapsulation: ViewEncapsulation.None
+})
+export class NavbarComponent implements OnInit {
+ public menuItems: Array<RouteInfo>;
+ public brandMenu: RouteInfo;
+ isCollapsed = true;
+
+ constructor() {}
+
+ ngOnInit() {
+ this.menuItems = ROUTES.filter(menuItem => menuItem.menuType !== MenuType.BRAND);
+ this.brandMenu = ROUTES.filter(menuItem => menuItem.menuType === MenuType.BRAND)[0];
+ }
+
+ public get menuIcon(): string {
+ return this.isCollapsed ? '☰' : '✖';
+ }
+
+ public getMenuItemClasses(menuItem: any) {
+ return {
+ 'pull-xs-right': this.isCollapsed && menuItem.menuType === MenuType.RIGHT
+ };
+ }
+}
diff --git a/catalog-ui/src/app/ng2/shared/navbar/navbar.metadata.ts b/catalog-ui/src/app/ng2/shared/navbar/navbar.metadata.ts
new file mode 100644
index 0000000000..245d0e6cfe
--- /dev/null
+++ b/catalog-ui/src/app/ng2/shared/navbar/navbar.metadata.ts
@@ -0,0 +1,11 @@
+export enum MenuType {
+ BRAND,
+ LEFT,
+ RIGHT
+}
+
+export interface RouteInfo {
+ path: string;
+ title: string;
+ menuType: MenuType;
+}
diff --git a/catalog-ui/src/app/ng2/shared/navbar/navbar.module.ts b/catalog-ui/src/app/ng2/shared/navbar/navbar.module.ts
new file mode 100644
index 0000000000..18120a61fb
--- /dev/null
+++ b/catalog-ui/src/app/ng2/shared/navbar/navbar.module.ts
@@ -0,0 +1,16 @@
+import { NgModule } from '@angular/core';
+import { CommonModule } from '@angular/common';
+import { RouterModule } from '@angular/router';
+import { NavbarComponent } from "./navbar.component";
+
+@NgModule({
+ imports: [
+ RouterModule,
+ CommonModule
+ ],
+ declarations: [ NavbarComponent ],
+ exports: [
+ NavbarComponent
+ ]
+})
+export class NavbarModule {}
diff --git a/catalog-ui/src/app/ng2/shared/shared.module.ts b/catalog-ui/src/app/ng2/shared/shared.module.ts
new file mode 100644
index 0000000000..3e59e04441
--- /dev/null
+++ b/catalog-ui/src/app/ng2/shared/shared.module.ts
@@ -0,0 +1,20 @@
+import { NgModule } from '@angular/core';
+
+import { CommonModule } from '@angular/common';
+import { RouterModule } from '@angular/router';
+import { NavbarModule } from "./navbar/navbar.module";
+
+@NgModule({
+ declarations: [
+
+ ],
+ imports: [
+ CommonModule,
+ RouterModule,
+ NavbarModule
+ ],
+ exports: [
+ ]
+})
+
+export class SharedModule {}
diff --git a/catalog-ui/src/app/ng2/shared/tabs/tab/tab.component.ts b/catalog-ui/src/app/ng2/shared/tabs/tab/tab.component.ts
new file mode 100644
index 0000000000..06dcfa0b16
--- /dev/null
+++ b/catalog-ui/src/app/ng2/shared/tabs/tab/tab.component.ts
@@ -0,0 +1,18 @@
+import { Component, Input } from '@angular/core';
+import { ViewEncapsulation } from '@angular/core';
+
+@Component({
+ selector: 'tab',
+ template: `
+ <div *ngIf="active" class="tab-content">
+ <ng-content></ng-content>
+ </div>
+ `,
+ encapsulation: ViewEncapsulation.None
+})
+export class Tab {
+ @Input('tabTitle') title: string;
+ @Input() active:boolean = false;
+ @Input() indication?: number;
+
+} \ No newline at end of file
diff --git a/catalog-ui/src/app/ng2/shared/tabs/tabs.component.html b/catalog-ui/src/app/ng2/shared/tabs/tabs.component.html
new file mode 100644
index 0000000000..3e263a3862
--- /dev/null
+++ b/catalog-ui/src/app/ng2/shared/tabs/tabs.component.html
@@ -0,0 +1,9 @@
+<div class="tabs {{tabStyle}}">
+ <div class="tab" *ngFor="let tab of tabs" (click)="selectTab(tab)" [class.active]="tab.active">
+ {{tab.title}}
+ <div class="tab-indication" *ngIf="tab.indication" [@indicatorAnimation]="tab.indication">{{tab.indication}}</div>
+ </div>
+</div>
+<div class="tab-content-container">
+ <ng-content></ng-content>
+</div> \ No newline at end of file
diff --git a/catalog-ui/src/app/ng2/shared/tabs/tabs.component.less b/catalog-ui/src/app/ng2/shared/tabs/tabs.component.less
new file mode 100644
index 0000000000..aa59428a64
--- /dev/null
+++ b/catalog-ui/src/app/ng2/shared/tabs/tabs.component.less
@@ -0,0 +1,85 @@
+@import '../../../../assets/styles/variables';
+
+.tabs {
+ display:flex;
+ flex: 0 0 auto;
+ flex-direction:row;
+}
+
+.tab {
+ flex: 1 0 auto;
+ cursor: pointer;
+ padding: .5em;
+}
+
+.tab-content-container {
+ flex: 1;
+ height: 100%;
+ overflow: hidden;
+ width:100%;
+}
+
+.tab-content {
+ height:100%;
+}
+
+/*Tab styles*/
+.tabs{
+ &.round-tabs .tab{
+ background-color: #f8f8f8;
+ color: #959595;
+ border: solid 1px #d2d2d2;
+ border-bottom:none;
+ border-left:none;
+ position:relative;
+
+ &:first-child {
+ border-top-left-radius: 8px;
+ border-left:solid 1px #d2d2d2;
+ }
+ &:last-child {
+ border-top-right-radius: 8px;
+ }
+
+ &.active {
+ background-color:#009fdb;
+ color:#e9e9e9;
+ border-color:#009fdb;
+ }
+
+ .tab-indication {
+ position: absolute;
+ top: -10px;
+ background-color: #009fdb;
+ right: 10px;
+ padding: 2px 0;
+ border-radius: 15px;
+ border: solid 1px #d2d2d2;
+ color:white;
+ width: 25px;
+ height: 25px;
+ text-align: center;
+
+ }
+ }
+
+ &.simple-tabs .tab {
+ font-size: 12px;
+ color: @main_color_n;
+
+ &:after {
+ display:block;
+ content: '';
+ border-bottom: 2px solid @main_color_a;
+ transform: scaleX(0);
+ transition: transform 200ms ease-in-out;
+ }
+
+ &.active {
+ color: @main_color_a;
+ &:after {
+ transform: scaleX(1);
+ }
+ }
+ }
+}
diff --git a/catalog-ui/src/app/ng2/shared/tabs/tabs.component.ts b/catalog-ui/src/app/ng2/shared/tabs/tabs.component.ts
new file mode 100644
index 0000000000..dc5616c6cb
--- /dev/null
+++ b/catalog-ui/src/app/ng2/shared/tabs/tabs.component.ts
@@ -0,0 +1,58 @@
+import { Component, ContentChildren, QueryList, AfterContentInit, Input, Output, EventEmitter } from '@angular/core';
+import { Tab } from './tab/tab.component';
+import { ViewEncapsulation } from '@angular/core';
+import { trigger, state, style, transition, animate, keyframes } from '@angular/core';
+
+@Component({
+ selector: 'tabs',
+ templateUrl: './tabs.component.html',
+ styleUrls: ['./tabs.component.less'],
+ encapsulation: ViewEncapsulation.None,
+ animations: [
+ trigger('indicatorAnimation', [
+ transition(':enter', [style({ transform: 'translateY(-50%)', opacity: 0 }), animate('250ms', style({ transform: 'translateY(0)', opacity: 1 })) ]),
+ transition(':leave', [style({ opacity: 1 }), animate('500ms', style({ opacity: 0 })) ])
+ ])
+ ]
+})
+export class Tabs implements AfterContentInit {
+
+ @Input() tabStyle: string;
+ @Input() hideIndicationOnTabChange?: boolean = false;
+ @ContentChildren(Tab) tabs: QueryList<Tab>;
+ @Output() tabChanged: EventEmitter<Tab> = new EventEmitter<Tab>();
+
+
+ ngAfterContentInit() {
+ //after contentChildren are set, determine active tab. If no active tab set, activate the first one
+ let activeTabs = this.tabs.filter((tab) => tab.active);
+
+ if (activeTabs.length === 0) {
+ this.selectTab(this.tabs.first);
+ }
+ }
+
+ selectTab(tab: Tab) {
+ //activate the tab the user clicked.
+ this.tabs.toArray().forEach(tab => {
+ tab.active = false;
+ if (this.hideIndicationOnTabChange && tab.indication) {
+ tab.indication = null;
+ }
+ });
+ tab.active = true;
+ this.tabChanged.emit(tab);
+ }
+
+ triggerTabChange(tabTitle) {
+ this.tabs.toArray().forEach(tab => {
+ tab.active = (tab.title == tabTitle) ? true : false;
+ });
+ }
+
+ setTabIndication(tabTitle:string, indication?:number) {
+ let selectedTab: Tab = this.tabs.toArray().find(tab => tab.title == tabTitle);
+ selectedTab.indication = indication || null;
+ }
+
+}
diff --git a/catalog-ui/src/app/ng2/shared/tabs/tabs.module.ts b/catalog-ui/src/app/ng2/shared/tabs/tabs.module.ts
new file mode 100644
index 0000000000..36c7335fde
--- /dev/null
+++ b/catalog-ui/src/app/ng2/shared/tabs/tabs.module.ts
@@ -0,0 +1,35 @@
+import { Component, NgModule } from '@angular/core'
+import { BrowserModule } from '@angular/platform-browser'
+
+import { Tabs } from './tabs.component';
+import { Tab } from './tab/tab.component';
+
+
+@NgModule({
+ imports: [BrowserModule],
+ declarations: [Tabs, Tab],
+ bootstrap: [],
+ exports: [Tabs, Tab]
+})
+export class TabModule { }
+
+/** README: **/
+
+/** USAGE Example:
+ *In page.module.ts: import TabModule
+ *In HTML:
+ *<tabs tabStyle="class-goes-here" (tabChanged)="tabChangedEvent($event) [hideIndicationOnTabChange]="optional-boolean">
+ * <tab [tabTitle]="'Tab 1'">Content of tab 1</tab>
+ * <tab tabTitle="Tab 2" >Content of tab 2</tab>
+ * ...
+ *</tabs>
+ */
+
+/**STYLING: (ViewEncapsulation is set to None to allow styles to be overridden or customized)
+ * Existing options:
+ * tabStyle="round-tabs" will provide generic rounded tab look
+ *
+ * To create or override styles:
+ * Parent div has class ".tabs". Each tab has class ".tab". Active tab has class ".active".
+ * Use /deep/ or >>> prefix to override styles via other components stylesheets
+ */ \ 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
new file mode 100644
index 0000000000..c8c1d9b721
--- /dev/null
+++ b/catalog-ui/src/app/ng2/utils/ng1-upgraded-provider.ts
@@ -0,0 +1,51 @@
+/**
+ * Created by rc2122 on 4/6/2017.
+ */
+import {DataTypesService} from "../../services/data-types-service";
+import ICacheObject = angular.ICacheObject;
+import {SharingService} from "../../services/sharing-service";
+import {CookieService} from "../../services/cookie-service";
+
+/** Services we need to upgrade from angular1 to angular2 - in the future we need to rewrite them all to angular2 **/
+
+export function dataTypesServiceFactory(cacheObj: ICacheObject) {
+ return cacheObj.get('Sdc.Services.DataTypesService');
+}
+
+export function sharingServiceFactory(cacheObj: ICacheObject) {
+ return cacheObj.get('Sdc.Services.SharingService');
+}
+
+export function cookieServiceFactory(cacheObj: ICacheObject) {
+ return cacheObj.get('Sdc.Services.CookieService');
+}
+
+export function stateParamsServiceFactory(cacheObj: ICacheObject) {
+ return cacheObj.get('$stateParams');
+}
+
+export const DataTypesServiceProvider = {
+ provide: DataTypesService,
+ useFactory: dataTypesServiceFactory,
+ deps: ['$injector']
+};
+
+
+export const SharingServiceProvider = {
+ provide: SharingService,
+ useFactory: sharingServiceFactory,
+ deps: ['$injector']
+};
+
+
+export const CookieServiceProvider = {
+ provide: CookieService,
+ useFactory: cookieServiceFactory,
+ deps: ['$injector']
+};
+
+export const StateParamsServiceFactory = {
+ provide: '$stateParams',
+ useFactory: stateParamsServiceFactory,
+ deps: ['$injector']
+};
diff --git a/catalog-ui/src/app/services.ts b/catalog-ui/src/app/services.ts
new file mode 100644
index 0000000000..5b4358a90c
--- /dev/null
+++ b/catalog-ui/src/app/services.ts
@@ -0,0 +1,32 @@
+/**
+ * Created by ob0695 on 2/23/2017.
+ */
+export * from './services/activity-log-service';
+export * from './services/available-icons-service';
+export * from './services/cache-service';
+export * from './services/configuration-ui-service';
+export * from './services/category-resource-service';
+export * from './services/components/component-service';
+export * from './services/components/product-service';
+export * from './services/components/resource-service';
+export * from './services/components/service-service';
+export * from './services/components/resource-service';
+export * from './services/components/utils/composition-left-palette-service';
+export * from './services/components/resource-service';
+export * from './services/components/resource-service';
+export * from './services/category-resource-service';
+export * from './services/cookie-service';
+export * from './services/data-types-service';
+export * from './services/ecomp-service';
+export * from './services/entity-service';
+export * from './services/event-listener-service';
+export * from './services/header-interceptor';
+export * from './services/loader-service';
+export * from './services/onboarding-service';
+export * from './services/progress-service';
+export * from './services/sdc-version-service';
+export * from './services/sharing-service';
+export * from './services/url-tobase64-service';
+export * from './services/user-resource-service';
+export * from './services/angular-js-bridge-service';
+
diff --git a/catalog-ui/src/app/services/activity-log-service.ts b/catalog-ui/src/app/services/activity-log-service.ts
new file mode 100644
index 0000000000..565dc9a39c
--- /dev/null
+++ b/catalog-ui/src/app/services/activity-log-service.ts
@@ -0,0 +1,28 @@
+'use strict';
+import {Activity} from "../models/activity";
+import {IAppConfigurtaion, IApi} from "../models/app-config";
+
+// Define an interface of the object you want to use, providing it's properties
+export interface IActivityLogService {
+ getActivityLogService(type:string, id:string):ng.IPromise<Array<Activity>>;
+}
+
+export class ActivityLogService implements IActivityLogService {
+
+
+ static '$inject' = ['$http', '$q', 'sdcConfig'];
+ private api:IApi;
+
+ constructor(private $http:ng.IHttpService, private $q:ng.IQService, sdcConfig:IAppConfigurtaion) {
+ this.api = sdcConfig.api;
+ }
+
+ getActivityLogService = (type:string, id:string):ng.IPromise<Array<Activity>> => {
+ let defer = this.$q.defer<any>();
+ this.$http.get(this.api.root + this.api.GET_activity_log.replace(':type', type).replace(':id', id))
+ .then((activityLog:any) => {
+ defer.resolve(activityLog.data);
+ });
+ return defer.promise;
+ }
+}
diff --git a/catalog-ui/src/app/services/angular-js-bridge-service.ts b/catalog-ui/src/app/services/angular-js-bridge-service.ts
new file mode 100644
index 0000000000..1eaea878dd
--- /dev/null
+++ b/catalog-ui/src/app/services/angular-js-bridge-service.ts
@@ -0,0 +1,23 @@
+'use strict';
+import {IAppConfigurtaion} from "../models/app-config";
+
+export class AngularJSBridge {
+ private static _$filter:ng.IFilterService;
+ private static _sdcConfig:IAppConfigurtaion;
+
+ public static getFilter(filterName:string) {
+ return AngularJSBridge._$filter(filterName);
+ }
+
+ public static getAngularConfig() {
+ return AngularJSBridge._sdcConfig;
+ }
+
+
+ constructor($filter:ng.IFilterService, sdcConfig:IAppConfigurtaion) {
+ AngularJSBridge._$filter = $filter;
+ AngularJSBridge._sdcConfig = sdcConfig;
+ }
+}
+
+AngularJSBridge.$inject = ['$filter', 'sdcConfig']
diff --git a/catalog-ui/src/app/services/available-icons-service.ts b/catalog-ui/src/app/services/available-icons-service.ts
new file mode 100644
index 0000000000..ad17b069d6
--- /dev/null
+++ b/catalog-ui/src/app/services/available-icons-service.ts
@@ -0,0 +1,87 @@
+/**
+ * Created by obarda on 2/23/2016.
+ */
+'use strict';
+import {ComponentType} from "../utils/constants";
+
+interface IAvailableIconsService {
+ getIcons(componentType:ComponentType):Array<string>;
+}
+
+export class AvailableIconsService implements IAvailableIconsService {
+ constructor() {
+ }
+
+ public getIcons = (componentType:string):Array<string> => {
+
+ let icons:Array<string>;
+
+ switch (componentType) {
+ case ComponentType.SERVICE:
+ icons = [
+ 'call_controll',
+ 'mobility',
+ 'network_l_1-3',
+ 'network_l_4'
+ ];
+ break;
+
+ case ComponentType.RESOURCE:
+ icons = [
+ 'router',
+ 'database',
+ 'network',
+ 'objectStorage',
+ 'connector',
+ 'brocade',
+ 'cisco',
+ 'ericsson',
+ 'tropo',
+ 'fortinet',
+ 'att',
+ 'broadsoft',
+ 'alcatelLucent',
+ 'metaswitch',
+ 'aricent',
+ 'mySql',
+ 'oracle',
+ 'nokia_siemens',
+ 'juniper',
+ 'call_controll',
+ 'borderElement',
+ 'applicationServer',
+ 'server',
+ 'port',
+ 'loadBalancer',
+ 'compute',
+ 'gateway',
+ 'cp',
+ 'vl',
+ 'vfw',
+ 'firewall'
+ ];
+ break;
+
+ case ComponentType.PRODUCT:
+ icons = [
+ 'vfw',
+ 'network',
+ 'security',
+ 'cloud',
+ 'setting',
+ 'orphan',
+ 'wanx',
+ 'vrouter',
+ 'ucpe',
+ 'mobility'
+
+ ];
+ break;
+
+ }
+ return icons;
+ }
+}
+
+
+
diff --git a/catalog-ui/src/app/services/cache-service.ts b/catalog-ui/src/app/services/cache-service.ts
new file mode 100644
index 0000000000..9ee08c8478
--- /dev/null
+++ b/catalog-ui/src/app/services/cache-service.ts
@@ -0,0 +1,34 @@
+'use strict';
+import {Dictionary} from "app/utils";
+
+interface ICacheService {
+ get(key:string):any;
+ set(key:string, value:any):void;
+}
+
+export class CacheService implements ICacheService {
+
+ private storage:Dictionary<string, any>;
+
+ constructor() {
+ this.storage = new Dictionary<string, any>();
+ };
+
+ public get = (key:string):any => {
+ return this.storage.getValue(key);
+ };
+
+ public set = (key:string, value:any):void => {
+ this.storage.setValue(key, value);
+ };
+
+ public remove = (key:string):void => {
+ if (this.storage.containsKey(key)) {
+ this.storage.remove(key);
+ }
+ };
+
+ public contains = (key:string):boolean => {
+ return this.storage.containsKey(key);
+ };
+}
diff --git a/catalog-ui/src/app/services/category-resource-service.ts b/catalog-ui/src/app/services/category-resource-service.ts
new file mode 100644
index 0000000000..a2e3c61e0a
--- /dev/null
+++ b/catalog-ui/src/app/services/category-resource-service.ts
@@ -0,0 +1,61 @@
+'use strict';
+// import 'angular-resource';
+import {IAppConfigurtaion, IMainCategory, IUserProperties} from "../models";
+import {Categories} from "../models/categories";
+
+// Define an interface of the object you want to use, providing it's properties
+export interface ICategoryResource extends IUserProperties,ng.resource.IResource<ICategoryResource> {
+ name:string;
+ uniqueId:string;
+ subcategories:Array<ICategoryResource>;
+
+ getAllCategories(params?:Object, success?:Function, error?:Function):Categories;
+ $saveSubCategory(params?:Object, success?:Function, error?:Function):any;
+ $deleteSubCategory(params?:Object, success?:Function, error?:Function):any;
+}
+
+// Define your resource, adding the signature of the custom actions
+export interface ICategoryResourceClass extends ng.resource.IResourceClass<ICategoryResource> {
+ getAllCategories(params?:Object, success?:Function, error?:Function):Categories;
+ saveSubCategory(params?:Object, success?:Function, error?:Function):any;
+ deleteSubCategory(params?:Object, success?:Function, error?:Function):any;
+}
+
+export class CategoryResourceService {
+
+ public static getResource = ($resource:ng.resource.IResourceService,
+ sdcConfig:IAppConfigurtaion):ICategoryResourceClass => {
+
+ // Define your custom actions here as IActionDescriptor
+ let getAllCategoriesAction:ng.resource.IActionDescriptor = {
+ method: 'GET',
+ isArray: false,
+ url: sdcConfig.api.root + sdcConfig.api.GET_categories
+ };
+ let saveSubCategory:ng.resource.IActionDescriptor = {
+ method: 'POST',
+ isArray: false,
+ url: sdcConfig.api.root + sdcConfig.api.POST_subcategory
+ };
+ let deleteSubCategory:ng.resource.IActionDescriptor = {
+ method: 'DELETE',
+ isArray: false,
+ url: sdcConfig.api.root + sdcConfig.api.POST_subcategory
+ };
+
+
+ let url:string = sdcConfig.api.root + sdcConfig.api.POST_category;
+ let categoryResource:ICategoryResourceClass = <ICategoryResourceClass>$resource(
+ url,
+ {types: '@types', categoryId: '@categoryId'},
+ {
+ getAllCategories: getAllCategoriesAction,
+ saveSubCategory: saveSubCategory,
+ deleteSubCategory: deleteSubCategory
+ }
+ );
+
+ return categoryResource;
+ }
+}
+CategoryResourceService.getResource.$inject = ['$resource', 'sdcConfig'];
diff --git a/catalog-ui/src/app/services/components/component-service.ts b/catalog-ui/src/app/services/components/component-service.ts
new file mode 100644
index 0000000000..1a6b9a8a14
--- /dev/null
+++ b/catalog-ui/src/app/services/components/component-service.ts
@@ -0,0 +1,755 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+'use strict';
+import {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";
+import {SharingService} from "../sharing-service";
+
+export interface IComponentService {
+
+ getComponent(id:string);
+ updateComponent(component:Component):ng.IPromise<Component>;
+ changeLifecycleState(component:Component, state:string, userRemarks:any):ng.IPromise<Component> ;
+ validateName(newName:string, subtype?:string):ng.IPromise<IValidate>;
+ createComponent(component:Component):ng.IPromise<Component>;
+ addOrUpdateArtifact(componentId:string, artifact:ArtifactModel):ng.IPromise<ArtifactModel>;
+ deleteArtifact(componentId:string, artifact:string, artifactLabel):ng.IPromise<ArtifactModel>;
+ addProperty(componentId:string, property:PropertyModel):ng.IPromise<PropertyModel>;
+ updateProperty(componentId:string, property:PropertyModel):ng.IPromise<PropertyModel>;
+ addAttribute(componentId:string, attribute:AttributeModel):ng.IPromise<AttributeModel>;
+ updateAttribute(componentId:string, attribute:AttributeModel):ng.IPromise<AttributeModel>;
+ deleteProperty(componentId:string, propertyId:string):ng.IPromise<PropertyModel>;
+ deleteAttribute(componentId:string, attributeId:string):ng.IPromise<AttributeModel>;
+ 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>;
+ deleteInstanceArtifact(componentId:string, instanceId:string, artifact:string, artifactLabel):ng.IPromise<ArtifactModel>;
+ createComponentInstance(componentId:string, componentInstance:ComponentInstance):ng.IPromise<ComponentInstance>;
+ updateComponentInstance(componentId:string, componentInstance:ComponentInstance):ng.IPromise<ComponentInstance>;
+ updateMultipleComponentInstances(componentId:string, instances:Array<ComponentInstance>):ng.IPromise< Array<ComponentInstance>>;
+ downloadArtifact(componentId:string, artifactId:string):ng.IPromise<IFileDownload>;
+ uploadInstanceEnvFile(componentId:string, instanceId:string, artifact:ArtifactModel):ng.IPromise<ArtifactModel>;
+ downloadInstanceArtifact(componentId:string, instanceId:string, artifactId:string):ng.IPromise<IFileDownload>;
+ deleteComponentInstance(componentId:string, componentInstanceId:string):ng.IPromise<ComponentInstance>;
+ createRelation(componentId:string, link:RelationshipModel):ng.IPromise<RelationshipModel>;
+ deleteRelation(componentId:string, link:RelationshipModel):ng.IPromise<RelationshipModel>;
+ getRequirementsCapabilities(componentId:string):ng.IPromise<any>;
+ updateInstanceProperty(componentId:string, property: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>>;
+ getComponentInputs(componentId:string):ng.IPromise<Array<InputModel>>;
+ getComponentInstanceInputProperties(componentId:string, instanceId:string, inputId:string):ng.IPromise<Array<PropertyModel>>;
+ getComponentInstanceProperties(componentId:string, instanceId:string):ng.IPromise<Array<PropertyModel>>;
+ getModuleForDisplay(componentId:string, moduleId:string):ng.IPromise<DisplayModule>;
+ getComponentInstanceModule(componentId:string, componentInstanceId:string, moduleId:string):ng.IPromise<DisplayModule>;
+ updateGroupMetadata(componentId:string, group:Module):ng.IPromise<Module>;
+ getComponentInputInputsAndProperties(serviceId:string, input:string):ng.IPromise<InputsAndProperties>;
+ createInputsFromInstancesInputs(serviceId:string, instancesInputsMap:InstancesInputsPropertiesMap):ng.IPromise<Array<InputModel>>;
+ createInputsFromInstancesInputsProperties(resourceId:string, instanceInputsPropertiesMap:InstancesInputsPropertiesMap):ng.IPromise<Array<PropertyModel>>;
+ deleteComponentInput(serviceId:string, inputId:string):ng.IPromise<InputModel>;
+ getArtifactByGroupType(componentId:string, artifactGroupType:string):ng.IPromise<ArtifactGroupModel>;
+ getComponentInstanceArtifactsByGroupType(componentId:string, componentInstanceId:string, artifactGroupType:string):ng.IPromise<ArtifactGroupModel>;
+}
+
+export class ComponentService implements IComponentService {
+
+ static '$inject' = [
+ 'Restangular',
+ 'sdcConfig',
+ 'Sdc.Services.SharingService',
+ '$q',
+ '$base64'
+ ];
+
+ constructor(protected restangular:restangular.IElement,
+ protected sdcConfig:IAppConfigurtaion,
+ protected sharingService:SharingService,
+ protected $q:ng.IQService,
+ protected $base64:any
+ ) {
+
+ this.restangular.setBaseUrl(sdcConfig.api.root + sdcConfig.api.component_api_root);
+ this.restangular.setRequestInterceptor(function (elem, operation) {
+ if (operation === "remove") {
+ return null;
+ }
+ return elem;
+ });
+ // this.restangular.setDefaultHeaders({'Content-Type': 'application/json; charset=UTF-8'});
+ }
+
+ //this function is override by each service, we need to change this method to abstract when updtaing typescript version
+ protected createComponentObject = (component:Component):Component => {
+ return component;
+ };
+
+ public getComponent = (id:string):ng.IPromise<Component> => {
+ let deferred = this.$q.defer();
+ this.restangular.one(id).get().then((response:Component) => {
+ let component:Component = this.createComponentObject(response);
+ //console.log("Component Loaded successfully : ", component);
+ deferred.resolve(component);
+ }, (err)=> {
+ console.log("Failed to load component with ID: " + id);
+ deferred.reject(err);
+ });
+ return deferred.promise;
+ };
+
+ public updateComponent = (component:Component):ng.IPromise<Component> => {
+ // If this is resource
+ if (component instanceof Resource) {
+ let resource:Resource = <Resource>component;
+ if (resource.importedFile) {
+ // Update resource with payload data.
+ return this.updateResourceWithPayload(resource);
+ } else {
+ if (component.csarUUID) {
+ // Update resource without payload data.
+ return this.updateResource(component);
+ } else {
+ // Update resource without payload data (metadata).
+ return this.updateResourceMetadata(component);
+ }
+ }
+ } else {
+ return this.updateService(component);
+ }
+ };
+
+ private updateService = (component:Component):ng.IPromise<Component> => {
+ let deferred = this.$q.defer();
+ this.restangular.one(component.uniqueId).one("metadata").customPUT(JSON.stringify(component)).then((response:Component) => {
+ let component:Component = this.createComponentObject(response);
+ deferred.resolve(component);
+ }, (err)=> {
+ deferred.reject(err);
+ });
+ return deferred.promise;
+ };
+
+ private updateResource = (component:Component):ng.IPromise<Component> => {
+ let deferred = this.$q.defer();
+ this.restangular.one(component.uniqueId).customPUT(JSON.stringify(component)).then((response:Component) => {
+ let component:Component = this.createComponentObject(response);
+ deferred.resolve(component);
+ }, (err)=> {
+ deferred.reject(err);
+ });
+ return deferred.promise;
+ };
+
+ private updateResourceMetadata = (component:Component):ng.IPromise<Component> => {
+ let deferred = this.$q.defer();
+ this.restangular.one(component.uniqueId).one('metadata').customPUT(JSON.stringify(component)).then((response:Component) => {
+ let component:Component = this.createComponentObject(response);
+ deferred.resolve(component);
+ }, (err)=> {
+ deferred.reject(err);
+ });
+ return deferred.promise;
+ };
+
+ /**
+ * Only resource can be updated with payload data
+ * @param component
+ * @returns {IPromise<T>}
+ */
+ private updateResourceWithPayload = (resource:Resource):ng.IPromise<Component> => {
+ let deferred = this.$q.defer();
+
+ resource.payloadData = resource.importedFile.base64;
+ resource.payloadName = resource.importedFile.filename;
+ let headerObj = this.getHeaderMd5(resource);
+
+ this.restangular.one(resource.uniqueId).customPUT(JSON.stringify(resource), '', {}, headerObj).then((response:Component) => {
+ let componentResult:Component = this.createComponentObject(response);
+ deferred.resolve(componentResult);
+ }, (err)=> {
+ deferred.reject(err);
+ });
+
+ return deferred.promise;
+ };
+
+ public createComponent = (component:Component):ng.IPromise<Component> => {
+ let deferred = this.$q.defer();
+ let headerObj = this.getHeaderMd5(component);
+ this.restangular.customPOST(JSON.stringify(component), '', {}, headerObj).then((response:Component) => {
+ let component:Component = this.createComponentObject(response);
+ deferred.resolve(component);
+ }, (err)=> {
+ deferred.reject(err);
+ });
+ return deferred.promise;
+ };
+
+ public validateName = (newName:string, subtype?:string):ng.IPromise<IValidate> => {
+ let deferred = this.$q.defer();
+ this.restangular.one("validate-name").one(newName).get({'subtype': subtype}).then((response:any) => {
+ deferred.resolve(response.plain());
+ }, (err)=> {
+ deferred.reject(err);
+ });
+ return deferred.promise;
+ };
+
+ public changeLifecycleState = (component:Component, state:string, userRemarks:any):ng.IPromise<Component> => {
+ let deferred = this.$q.defer();
+ this.restangular.one(component.uniqueId).one(state).customPOST(userRemarks).then((response:Component) => {
+ this.sharingService.addUuidValue(response.uniqueId, response.uuid);
+ let component:Component = this.createComponentObject(response);
+ deferred.resolve(component);
+ }, (err)=> {
+ deferred.reject(err);
+ });
+ return deferred.promise;
+ };
+
+ // ------------------------------------------------ Artifacts API --------------------------------------------------//
+ public addOrUpdateArtifact = (componentId:string, artifact:ArtifactModel):ng.IPromise<ArtifactModel> => {
+ let deferred = this.$q.defer();
+ let headerObj = {};
+ if (artifact.payloadData) {
+ headerObj = this.getHeaderMd5(artifact);
+ }
+ this.restangular.one(componentId).one("artifacts").customPOST(JSON.stringify(artifact), artifact.uniqueId, {}, headerObj).then((response:any) => {
+ deferred.resolve(response.plain());
+ }, (err)=> {
+ deferred.reject(err);
+ });
+ return deferred.promise;
+ };
+
+ public downloadArtifact = (componentId:string, artifactId:string):ng.IPromise<IFileDownload> => {
+ let deferred = this.$q.defer();
+ this.restangular.one(componentId).one("artifacts").one(artifactId).get().then((response:any) => {
+ deferred.resolve(response.plain());
+ }, (err)=> {
+ deferred.reject(err);
+ });
+ return deferred.promise;
+ };
+
+ public deleteArtifact = (componentId:string, artifactId:string, artifactLabel:string):ng.IPromise<ArtifactModel> => {
+ let deferred = this.$q.defer();
+ this.restangular.one(componentId).one("artifacts").one(artifactId).remove({'operation': artifactLabel}).then((response:ArtifactModel) => {
+ deferred.resolve(response);
+ }, (err)=> {
+ deferred.reject(err);
+ });
+ return deferred.promise;
+ };
+
+ public getArtifactByGroupType = (componentId:string, artifactGroupType:string):ng.IPromise<ArtifactGroupModel> => {
+ let deferred = this.$q.defer();
+ this.restangular.one(componentId).one("artifactsByType").one(artifactGroupType).get().then((response:any) => {
+ var artifacts:ArtifactGroupModel = new ArtifactGroupModel(response.plain());
+ deferred.resolve(artifacts);
+ }, (err)=> {
+ deferred.reject(err);
+ });
+ return deferred.promise;
+ };
+
+ public getComponentInstanceArtifactsByGroupType = (componentId:string, componentInstanceId:string, artifactGroupType:string):ng.IPromise<ArtifactGroupModel> => {
+ let deferred = this.$q.defer();
+ this.restangular.one(componentId).one("resourceInstances").one(componentInstanceId).one("artifactsByType").one(artifactGroupType).get().then((response:any) => {
+ var artifacts:ArtifactGroupModel = new ArtifactGroupModel(response.plain());
+ deferred.resolve(artifacts);
+ }, (err)=> {
+ deferred.reject(err);
+ });
+ return deferred.promise;
+ };
+
+
+ // ------------------------------------------------ Properties API --------------------------------------------------//
+ public addProperty = (componentId:string, property:PropertyModel):ng.IPromise<PropertyModel> => {
+ let deferred = this.$q.defer();
+ this.restangular.one(componentId).one("properties").customPOST(property.convertToServerObject()).then((response:any) => {
+ let property:PropertyModel = new PropertyModel(response[Object.keys(response)[0]]);
+ deferred.resolve(property);
+ }, (err)=> {
+ deferred.reject(err);
+ });
+ return deferred.promise;
+ };
+
+ public updateProperty = (componentId:string, property:PropertyModel):ng.IPromise<PropertyModel> => {
+ let deferred = this.$q.defer();
+ this.restangular.one(componentId).one("properties").one(property.uniqueId).customPUT(property.convertToServerObject()).then((response:any) => {
+ let property:PropertyModel = new PropertyModel(response[Object.keys(response)[0]]);
+ deferred.resolve(property);
+ }, (err)=> {
+ deferred.reject(err);
+ });
+ return deferred.promise;
+ };
+
+ public deleteProperty = (componentId:string, propertyId:string):ng.IPromise<PropertyModel> => {
+ let deferred = this.$q.defer();
+ this.restangular.one(componentId).one("properties").one(propertyId).remove().then((response:any) => {
+ deferred.resolve(response);
+ }, (err)=> {
+ deferred.reject(err);
+ });
+ return deferred.promise;
+ };
+
+ // ------------------------------------------------ Attributes API --------------------------------------------------//
+ public addAttribute = (componentId:string, attribute:AttributeModel):ng.IPromise<AttributeModel> => {
+ let deferred = this.$q.defer();
+ this.restangular.one(componentId).one("attributes").customPOST(attribute.convertToServerObject()).then((response:any) => {
+ let attribute:AttributeModel = new AttributeModel(response);
+ deferred.resolve(attribute);
+ }, (err)=> {
+ deferred.reject(err);
+ });
+ return deferred.promise;
+ };
+
+ public updateAttribute = (componentId:string, attribute:AttributeModel):ng.IPromise<AttributeModel> => {
+ let deferred = this.$q.defer();
+ this.restangular.one(componentId).one("attributes").one(attribute.uniqueId).customPUT(attribute.convertToServerObject()).then((response:any) => {
+ let attribute:AttributeModel = new AttributeModel(response);
+ deferred.resolve(attribute);
+ }, (err)=> {
+ deferred.reject(err);
+ });
+ return deferred.promise;
+ };
+
+ public deleteAttribute = (componentId:string, attributeId:string):ng.IPromise<AttributeModel> => {
+ let deferred = this.$q.defer();
+ this.restangular.one(componentId).one("attributes").one(attributeId).remove().then((response:any) => {
+ deferred.resolve(response);
+ }, (err)=> {
+ deferred.reject(err);
+ });
+ return deferred.promise;
+ };
+
+ // ------------------------------------------------ Component Instances API --------------------------------------------------//
+
+ public createComponentInstance = (componentId:string, componentInstance:ComponentInstance):ng.IPromise<ComponentInstance> => {
+ let deferred = this.$q.defer();
+ this.restangular.one(componentId).one("resourceInstance").customPOST(JSON.stringify(componentInstance)).then((response:any) => {
+ let componentInstance:ComponentInstance = ComponentInstanceFactory.createComponentInstance(response);
+ console.log("Component Instance created", componentInstance);
+ deferred.resolve(componentInstance);
+ }, (err)=> {
+ console.log("Failed to create componentInstance. With Name: " + componentInstance.name);
+ deferred.reject(err);
+ });
+ return deferred.promise;
+ };
+
+ public updateComponentInstance = (componentId:string, componentInstance:ComponentInstance):ng.IPromise<ComponentInstance> => {
+ let deferred = this.$q.defer();
+ this.restangular.one(componentId).one("resourceInstance").one(componentInstance.uniqueId).customPOST(JSON.stringify(componentInstance)).then((response:any) => {
+ let componentInstance:ComponentInstance = ComponentInstanceFactory.createComponentInstance(response);
+ console.log("Component Instance was updated", componentInstance);
+ deferred.resolve(componentInstance);
+ }, (err)=> {
+ console.log("Failed to update componentInstance. With ID: " + componentInstance.uniqueId + "Name: " + componentInstance.name);
+ deferred.reject(err);
+ });
+ return deferred.promise;
+ };
+
+ public updateMultipleComponentInstances = (componentId:string, instances:Array<ComponentInstance>):ng.IPromise<Array<ComponentInstance>> => {
+ let deferred = this.$q.defer();
+ this.restangular.one(componentId).one("resourceInstance/multipleComponentInstance").customPOST(JSON.stringify(instances)).then((response:any) => {
+ console.log("Multiple Component Instances was updated", response);
+ let updateInstances:Array<ComponentInstance> = new Array<ComponentInstance>();
+ _.forEach(response, (componentInstance:ComponentInstance) => {
+ let updatedComponentInstance:ComponentInstance = ComponentInstanceFactory.createComponentInstance(componentInstance);
+ updateInstances.push(updatedComponentInstance);
+ });
+ deferred.resolve(updateInstances);
+ }, (err)=> {
+ console.log("Failed to update Multiple componentInstance.");
+ deferred.reject(err);
+ });
+ return deferred.promise;
+ };
+
+ public deleteComponentInstance = (componentId:string, componentInstanceId:string):ng.IPromise<ComponentInstance> => {
+ let deferred = this.$q.defer();
+ this.restangular.one(componentId).one("resourceInstance").one(componentInstanceId).remove().then(() => {
+ console.log("Component Instance was deleted");
+ deferred.resolve();
+ }, (err)=> {
+ console.log("Failed to delete componentInstance. With ID: " + componentInstanceId);
+ 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) => {
+ let componentInstance:ComponentInstance = ComponentInstanceFactory.createComponentInstance(response);
+ deferred.resolve(componentInstance);
+ }, (err)=> {
+ deferred.reject(err);
+ });
+ return deferred.promise;
+ };
+
+ public downloadInstanceArtifact = (componentId:string, instanceId:string, artifactId:string):ng.IPromise<IFileDownload> => {
+ let deferred = this.$q.defer();
+ this.restangular.one(componentId).one("resourceInstances").one(instanceId).one("artifacts").one(artifactId).get().then((response:any) => {
+ deferred.resolve(response.plain());
+ }, (err)=> {
+ deferred.reject(err);
+ });
+ return deferred.promise;
+ };
+
+ public updateInstanceArtifact = (componentId:string, instanceId:string, artifact:ArtifactModel):ng.IPromise<ArtifactModel> => {
+ let deferred = this.$q.defer();
+ let headerObj = {};
+ if (artifact.payloadData) {
+ headerObj = this.getHeaderMd5(artifact);
+ }
+ this.restangular.one(componentId).one("resourceInstance").one(instanceId).one("artifacts").customPOST(JSON.stringify(artifact), artifact.uniqueId, {}, headerObj).then((response:any) => {
+ let newArtifact = new ArtifactModel(response);
+ deferred.resolve(newArtifact);
+ }, (err)=> {
+ deferred.reject(err);
+ });
+ return deferred.promise;
+ };
+
+ public addInstanceArtifact = (componentId:string, instanceId:string, artifact:ArtifactModel):ng.IPromise<ArtifactModel> => {
+ let deferred = this.$q.defer();
+ let headerObj = {};
+ if (artifact.payloadData) {
+ headerObj = this.getHeaderMd5(artifact);
+ }
+ this.restangular.one(componentId).one("resourceInstance").one(instanceId).one("artifacts").customPOST(JSON.stringify(artifact), artifact.uniqueId, {}, headerObj).then((response:any) => {
+ let artifact:ArtifactModel = new ArtifactModel(response.plain());
+ deferred.resolve(artifact);
+ }, (err)=> {
+ deferred.reject(err);
+ });
+ return deferred.promise;
+ };
+
+ public deleteInstanceArtifact = (componentId:string, instanceId:string, artifactId:string, artifactLabel:string):ng.IPromise<ArtifactModel> => {
+ let deferred = this.$q.defer();
+ this.restangular.one(componentId).one("resourceInstance").one(instanceId).one("artifacts").one(artifactId).remove({'operation': artifactLabel}).then((response:ArtifactModel) => {
+ deferred.resolve(response);
+ }, (err)=> {
+ deferred.reject(err);
+ });
+ return deferred.promise;
+ };
+
+ public uploadInstanceEnvFile = (componentId:string, instanceId:string, artifact:ArtifactModel):ng.IPromise<ArtifactModel> => {
+ let deferred = this.$q.defer();
+ let headerObj = {};
+ if (artifact.payloadData) {
+ headerObj = this.getHeaderMd5(artifact);
+ }
+ this.restangular.one(componentId).one("resourceInstance").one(instanceId).one("artifacts").customPOST(JSON.stringify(artifact), artifact.uniqueId, {}, headerObj).then((response:any) => {
+ let newArtifact = new ArtifactModel(response);
+ deferred.resolve(newArtifact);
+ }, (err)=> {
+ deferred.reject(err);
+ });
+ 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);
+ }, (err)=> {
+ deferred.reject(err);
+ });
+ return deferred.promise;
+ };
+
+ public updateInstanceAttribute = (componentId:string, attribute:AttributeModel):ng.IPromise<AttributeModel> => {
+ let deferred = this.$q.defer();
+ let instanceId = attribute.resourceInstanceUniqueId;
+ this.restangular.one(componentId).one("resourceInstance").one(instanceId).one("attribute").customPOST(JSON.stringify(attribute)).then((response:any) => {
+ let newAttribute = new AttributeModel(response);
+ newAttribute.readonly = true;
+ newAttribute.resourceInstanceUniqueId = instanceId;
+ deferred.resolve(newAttribute);
+ }, (err)=> {
+ deferred.reject(err);
+ });
+ return deferred.promise;
+ };
+
+ public createRelation = (componentId:string, link:RelationshipModel):ng.IPromise<RelationshipModel> => {
+ let deferred = this.$q.defer();
+ this.restangular.one(componentId).one("resourceInstance").one("associate").customPOST(JSON.stringify(link)).then((response:any) => {
+ let relation:RelationshipModel = new RelationshipModel(response.plain());
+ console.log("Link created successfully ", relation);
+ deferred.resolve(relation);
+ }, (err)=> {
+ console.log("Failed to create Link From: " + link.fromNode + "To: " + link.toNode);
+ deferred.reject(err);
+ });
+ return deferred.promise;
+ };
+
+ public deleteRelation = (componentId:string, link:RelationshipModel):ng.IPromise<RelationshipModel> => {
+ let deferred = this.$q.defer();
+ this.restangular.one(componentId).one("resourceInstance").one("dissociate").customPUT(JSON.stringify(link)).then((response:any) => {
+ let relation:RelationshipModel = new RelationshipModel(response);
+ console.log("Link deleted successfully ", relation);
+ deferred.resolve(relation);
+ }, (err)=> {
+ console.log("Failed to delete Link From: " + link.fromNode + "To: " + link.toNode);
+ deferred.reject(err);
+ });
+ return deferred.promise;
+ };
+
+ public getRequirementsCapabilities = (componentId:string):ng.IPromise<any> => {
+ let deferred = this.$q.defer();
+ this.restangular.one(componentId).one("requirmentsCapabilities").get().then((response:any) => {
+ console.log("Component requirement capabilities recived: ", response);
+ deferred.resolve(response);
+ }, (err)=> {
+ console.log("Failed to get requirements & capabilities");
+ deferred.reject(err);
+ });
+ return deferred.promise;
+ };
+
+ public getModuleForDisplay = (componentId:string, moduleId:string):ng.IPromise<DisplayModule> => {
+ let deferred = this.$q.defer();
+ this.restangular.one(componentId).one("groups").one(moduleId).get().then((response:any) => {
+ console.log("module loaded successfully: ", response);
+ let module:DisplayModule = new DisplayModule(response);
+ deferred.resolve(module);
+ }, (err)=> {
+ console.log("Failed to get module with id: ", moduleId);
+ deferred.reject(err);
+ });
+ return deferred.promise;
+ };
+
+ public getComponentInstanceModule = (componentId:string, componentInstanceId:string, moduleId:string):ng.IPromise<Module> => {
+ let deferred = this.$q.defer();
+ this.restangular.one(componentId).one("resourceInstance").one(componentInstanceId).one("groupInstance").one(moduleId).get().then((response:any) => {
+ console.log("module loaded successfully: ", response);
+ let module:DisplayModule = new DisplayModule(response);
+ deferred.resolve(module);
+ }, (err)=> {
+ console.log("Failed to get module with id: ", moduleId);
+ deferred.reject(err);
+ });
+ return deferred.promise;
+ };
+
+ public getComponentInstancesFilteredByInputsAndProperties = (componentId:string, searchText?:string):ng.IPromise<Array<ComponentInstance>> => {
+ let deferred = this.$q.defer();
+ this.restangular.one(componentId).one("componentInstances").get({'searchText': searchText}).then((response:any) => {
+ console.log("component instances return successfully: ", response);
+ let componentInstances:Array<ComponentInstance> = CommonUtils.initComponentInstances(response);
+ deferred.resolve(componentInstances);
+ }, (err) => {
+ console.log("Failed to get component instances of component with id: " + componentId);
+ deferred.reject(err);
+ });
+
+ return deferred.promise;
+ };
+
+ public getComponentInstanceInputs = (componentId:string, instanceId:string, originComponentUid):ng.IPromise<Array<InputModel>> => {
+
+ let deferred = this.$q.defer();
+ this.restangular.one(componentId).one("componentInstances").one(instanceId).one(originComponentUid).one("inputs").get().then((response:any) => {
+ console.log("component instance input return successfully: ", response);
+ let inputsArray:Array<InputModel> = new Array<InputModel>();
+ _.forEach(response, (inputObj:InputModel) => {
+ inputsArray.push(new InputModel(inputObj));
+ });
+ deferred.resolve(inputsArray);
+ }, (err) => {
+ console.log("Failed to get component instance input with id: " + instanceId);
+ deferred.reject(err);
+ });
+
+ return deferred.promise;
+ };
+
+ public getComponentInputs = (componentId:string):ng.IPromise<Array<InputModel>> => {
+
+ let deferred = this.$q.defer();
+ this.restangular.one(componentId).one("inputs").get().then((response:any) => {
+ console.log("component inputs return successfully: ", response);
+ let inputsArray:Array<InputModel> = new Array<InputModel>();
+ _.forEach(response, (inputObj:InputModel) => {
+ inputsArray.push(new InputModel(inputObj));
+ });
+ deferred.resolve(inputsArray);
+ }, (err) => {
+ console.log("Failed to get component inputs for component with id: " + componentId);
+ deferred.reject(err);
+ });
+
+ return deferred.promise;
+ };
+
+ public getComponentInstanceInputProperties = (componentId:string, instanceId:string, inputId:string):ng.IPromise<Array<PropertyModel>> => {
+
+ let deferred = this.$q.defer();
+ this.restangular.one(componentId).one("componentInstances").one(instanceId).one(inputId).one("properties").get().then((response:any) => {
+ console.log("component instance input properties return successfully: ", response);
+ let propertiesArray:Array<PropertyModel> = new Array<PropertyModel>();
+ _.forEach(response, (propertyObj:PropertyModel) => {
+ propertiesArray.push(new PropertyModel(propertyObj));
+ });
+ deferred.resolve(propertiesArray);
+ }, (err) => {
+ console.log("Failed to get component instance input properties with instanceId: " + instanceId + "and input id: " + inputId);
+ deferred.reject(err);
+ });
+
+ return deferred.promise;
+ };
+
+
+ public getComponentInstanceProperties = (componentId:string, instanceId:string):ng.IPromise<Array<PropertyModel>> => {
+
+ let deferred = this.$q.defer();
+ this.restangular.one(componentId).one("componentInstances").one(instanceId).one("properties").get().then((response:any) => {
+ console.log("component instance properties return successfully: ", response);
+ let propertiesArray:Array<PropertyModel> = new Array<PropertyModel>();
+ _.forEach(response, (propertyObj:PropertyModel) => {
+ propertiesArray.push(new PropertyModel(propertyObj));
+ });
+ deferred.resolve(propertiesArray);
+ }, (err) => {
+ console.log("Failed to get component instance properties with instanceId: " + instanceId);
+ deferred.reject(err);
+ });
+
+ return deferred.promise;
+ };
+
+ public updateGroupMetadata = (componentId:string, group:Module):ng.IPromise<Module> => {
+
+ let deferred = this.$q.defer();
+ this.restangular.one(componentId).one("groups").one(group.uniqueId).one("metadata").customPUT(JSON.stringify(group)).then((response:Module) => {
+ console.log("group metadata updated successfully: ", response);
+ let updatedGroup:Module = new Module(response);
+
+ deferred.resolve(updatedGroup);
+ }, (err) => {
+ console.log("Failed to update group metadata for component: " + componentId + " for group with id: " + group.uniqueId);
+ deferred.reject(err);
+ });
+
+ return deferred.promise;
+ };
+
+ public getComponentInputInputsAndProperties = (serviceId:string, inputId:string):ng.IPromise<InputsAndProperties> => {
+ let defer = this.$q.defer<any>();
+ this.restangular.one(serviceId).one("inputs").one(inputId).get().then((response:InputsAndProperties) => {
+
+ let inputsArray:Array<InputModel> = new Array<InputModel>();
+ _.forEach(response.inputs, (inputObj:InputModel) => {
+ inputsArray.push(new InputModel(inputObj));
+ });
+
+ let propertiesArray:Array<PropertyModel> = new Array<PropertyModel>();
+ _.forEach(response.properties, (property:PropertyModel) => {
+ propertiesArray.push(new PropertyModel(property));
+ });
+
+ defer.resolve(new InputsAndProperties(inputsArray, propertiesArray));
+ }, (err)=> {
+ console.log("failed to get inputs of input : ", err);
+ defer.reject(err);
+ });
+ return defer.promise;
+ };
+
+ createInputsFromInstancesInputsProperties = (resourceId:string, instancePropertyMap:InstancesInputsPropertiesMap):ng.IPromise<Array<PropertyModel>> => {
+ let defer = this.$q.defer<any>();
+ this.restangular.one(resourceId).one("create/properties").customPOST(instancePropertyMap).then((response:any) => {
+ let inputsArray:Array<PropertyModel> = new Array<PropertyModel>();
+ _.forEach(response, (inputObj:PropertyModel) => {
+ inputsArray.push(new PropertyModel(inputObj));
+ });
+ defer.resolve(inputsArray);
+ }, (err)=> {
+ console.log("failed to create service inputs from VF instances inputs : ", err);
+ defer.reject(err);
+ });
+ return defer.promise;
+ };
+
+ createInputsFromInstancesInputs = (serviceId:string, instancesMap:InstancesInputsPropertiesMap):ng.IPromise<Array<InputModel>> => {
+ let defer = this.$q.defer<any>();
+ this.restangular.one(serviceId).one("create/inputs").customPOST(instancesMap).then((response:any) => {
+ let inputsArray:Array<InputModel> = new Array<InputModel>();
+ _.forEach(response, (inputObj:InputModel) => {
+ inputsArray.push(new InputModel(inputObj));
+ });
+ defer.resolve(inputsArray);
+ }, (err)=> {
+ console.log("failed to create service inputs from VF instances inputs : ", err);
+ defer.reject(err);
+ });
+ return defer.promise;
+ };
+
+ deleteComponentInput = (serviceId:string, inputId:string):ng.IPromise<InputModel> => {
+ let defer = this.$q.defer();
+ this.restangular.one(serviceId).one("delete").one(inputId).one("input").remove().then((response:any) => {
+ let inputToDelete = new InputModel(response);
+ defer.resolve(inputToDelete);
+ }, (err)=> {
+ console.log("failed to delete input from service: ", err);
+ defer.reject(err);
+ });
+ return defer.promise;
+ };
+
+ private getHeaderMd5 = (object:any):any => {
+ let headerObj = {};
+ // This is ugly workaround!!!
+ // The md5 result is not correct if we do not add the line JSON.stringify(resource); twice.
+ JSON.stringify(object);
+ let componentString:string = JSON.stringify(object);
+ let md5Result = md5(componentString).toLowerCase();
+ headerObj = {'Content-MD5': this.$base64.encode(md5Result)};
+ return headerObj;
+ };
+
+}
diff --git a/catalog-ui/src/app/services/components/product-service.ts b/catalog-ui/src/app/services/components/product-service.ts
new file mode 100644
index 0000000000..c1a14478d2
--- /dev/null
+++ b/catalog-ui/src/app/services/components/product-service.ts
@@ -0,0 +1,35 @@
+/**
+ * Created by obarda on 2/8/2016.
+ */
+'use strict';
+import {IComponentService, ComponentService} from "./component-service";
+import {SharingService} from "../sharing-service";
+import {Product, Component, IAppConfigurtaion} from "../../models";
+
+export interface IProductService extends IComponentService {
+
+}
+
+export class ProductService extends ComponentService implements IProductService {
+
+ static '$inject' = [
+ 'Restangular',
+ 'sdcConfig',
+ 'Sdc.Services.SharingService',
+ '$q',
+ '$base64'
+ ];
+
+ constructor(protected restangular:restangular.IElement,
+ protected sdcConfig:IAppConfigurtaion,
+ protected sharingService:SharingService,
+ protected $q:ng.IQService,
+ protected $base64:any) {
+ super(restangular, sdcConfig, sharingService, $q, $base64);
+ this.restangular = restangular.one("products");
+ }
+
+ createComponentObject = (component:Component):Component => {
+ return new Product(this, this.$q, <Product>component);
+ };
+}
diff --git a/catalog-ui/src/app/services/components/resource-service.ts b/catalog-ui/src/app/services/components/resource-service.ts
new file mode 100644
index 0000000000..470f1e2061
--- /dev/null
+++ b/catalog-ui/src/app/services/components/resource-service.ts
@@ -0,0 +1,52 @@
+/**
+ * Created by obarda on 2/4/2016.
+ */
+'use strict';
+import {IComponentService, ComponentService} from "./component-service";
+import {PropertyModel, IAppConfigurtaion, Resource, Component} from "../../models";
+import {SharingService} from "../sharing-service";
+
+export interface IResourceService extends IComponentService {
+ updateResourceGroupProperties(uniqueId:string, groupId:string, properties:Array<PropertyModel>):ng.IPromise<Array<PropertyModel>>
+}
+
+export class ResourceService extends ComponentService implements IResourceService {
+
+ static '$inject' = [
+ 'Restangular',
+ 'sdcConfig',
+ 'Sdc.Services.SharingService',
+ '$q',
+ '$base64'
+ ];
+
+ constructor(protected restangular:restangular.IElement,
+ protected sdcConfig:IAppConfigurtaion,
+ protected sharingService:SharingService,
+ protected $q:ng.IQService,
+ protected $base64:any
+ ) {
+ super(restangular, sdcConfig, sharingService, $q, $base64);
+
+ this.restangular = restangular.one("resources");
+ }
+
+ createComponentObject = (component:Component):Component => {
+ return new Resource(this, this.$q, <Resource>component);
+ };
+
+
+ updateResourceGroupProperties = (uniqueId:string, groupId:string, properties:Array<PropertyModel>):ng.IPromise<Array<PropertyModel>> => {
+ let defer = this.$q.defer<Array<PropertyModel>>();
+ this.restangular.one(uniqueId).one("groups").one(groupId).one('properties').customPUT(JSON.stringify(properties)).then((updatesProperties:any) => {
+ let propertiesArray:Array<PropertyModel> = new Array<PropertyModel>();
+ _.forEach(updatesProperties, (propertyObj:PropertyModel) => {
+ propertiesArray.push(new PropertyModel(propertyObj));
+ });
+ defer.resolve(propertiesArray);
+ }, (err)=> {
+ defer.reject(err);
+ });
+ return defer.promise;
+ };
+}
diff --git a/catalog-ui/src/app/services/components/service-service.ts b/catalog-ui/src/app/services/components/service-service.ts
new file mode 100644
index 0000000000..f0fe90bf7f
--- /dev/null
+++ b/catalog-ui/src/app/services/components/service-service.ts
@@ -0,0 +1,86 @@
+/**
+ * Created by obarda on 2/4/2016.
+ */
+'use strict';
+import {IComponentService, ComponentService} from "./component-service";
+import {Distribution, DistributionComponent, Service, PropertyModel, Component, IAppConfigurtaion} from "app/models";
+import {SharingService} from "../sharing-service";
+
+export interface IServiceService extends IComponentService {
+ getDistributionsList(uuid:string):ng.IPromise<Array<Distribution>>;
+ getDistributionComponents(distributionId:string):ng.IPromise<Array<DistributionComponent>>;
+ markAsDeployed(serviceId:string, distributionId:string):ng.IPromise<any>;
+ updateGroupInstanceProperties(serviceId:string, resourceInstanceId:string, groupInstanceId:string, groupInstanceProperties:Array<PropertyModel>):ng.IPromise<Array<PropertyModel>>;
+}
+
+export class ServiceService extends ComponentService implements IServiceService {
+
+ static '$inject' = [
+ 'Restangular',
+ 'sdcConfig',
+ 'Sdc.Services.SharingService',
+ '$q',
+ '$base64'
+ ];
+
+ public distribution:string = "distribution";
+
+ constructor(protected restangular:restangular.IElement,
+ protected sdcConfig:IAppConfigurtaion,
+ protected sharingService:SharingService,
+ protected $q:ng.IQService,
+ protected $base64:any) {
+ super(restangular, sdcConfig, sharingService, $q, $base64);
+
+ this.restangular = restangular.one("services");
+ }
+
+ getDistributionsList = (uuid:string):ng.IPromise<Array<Distribution>> => {
+ let defer = this.$q.defer<Array<Distribution>>();
+ this.restangular.one(uuid).one("distribution").get().then((distributions:any) => {
+ defer.resolve(<Array<Distribution>> distributions.distributionStatusOfServiceList);
+ }, (err)=> {
+ defer.reject(err);
+ });
+ return defer.promise;
+ };
+
+ getDistributionComponents = (distributionId:string):ng.IPromise<Array<DistributionComponent>> => {
+ let defer = this.$q.defer<Array<DistributionComponent>>();
+ this.restangular.one("distribution").one(distributionId).get().then((distributions:any) => {
+ defer.resolve(<Array<DistributionComponent>> distributions.distributionStatusList);
+ }, (err)=> {
+ defer.reject(err);
+ });
+ return defer.promise;
+ };
+
+ markAsDeployed = (serviceId:string, distributionId:string):ng.IPromise<any> => {
+ let defer = this.$q.defer<any>();
+ this.restangular.one(serviceId).one("distribution").one(distributionId).one("markDeployed").customPOST().then((result:any) => {
+ defer.resolve(result);
+ }, (err)=> {
+
+ defer.reject(err);
+ });
+ return defer.promise;
+ };
+
+ createComponentObject = (component:Component):Component => {
+ return new Service(this, this.$q, <Service>component);
+ };
+
+ updateGroupInstanceProperties = (serviceId:string, resourceInstanceId:string, groupInstanceId:string, groupInstanceProperties:Array<PropertyModel>):ng.IPromise<Array<PropertyModel>> => {
+ let defer = this.$q.defer<Array<PropertyModel>>();
+ this.restangular.one(serviceId).one("resourceInstance").one(resourceInstanceId).one('groupInstance').one(groupInstanceId).customPUT(JSON.stringify(groupInstanceProperties)).then((updatedProperties:any) => {
+ let propertiesArray:Array<PropertyModel> = new Array<PropertyModel>();
+ _.forEach(updatedProperties, (propertyObj:PropertyModel) => {
+ propertiesArray.push(new PropertyModel(propertyObj));
+ });
+ defer.resolve(propertiesArray);
+ }, (err)=> {
+ defer.reject(err);
+ });
+ return defer.promise;
+ };
+}
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
new file mode 100644
index 0000000000..0abdbcfcb3
--- /dev/null
+++ b/catalog-ui/src/app/services/components/utils/composition-left-palette-service.ts
@@ -0,0 +1,120 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+/**
+ * Created by obarda on 3/13/2016.
+ */
+'use strict';
+import {LeftPaletteComponent} from "../../../models/components/displayComponent";
+import {Component} from "../../../models/components/component";
+import {EventListenerService} from "../../event-listener-service";
+import {ComponentFactory} from "../../../utils/component-factory";
+import {IAppConfigurtaion} from "../../../models/app-config";
+import {ResourceType, ComponentType, EVENTS} from "../../../utils/constants";
+import {ComponentMetadata} from "../../../models/component-metadata";
+
+export class LeftPaletteDataObject {
+ displayLeftPanelComponents:Array<LeftPaletteComponent>;
+ onFinishLoadingEvent:string;
+
+ constructor(onFinishEventListener:string) {
+
+ this.displayLeftPanelComponents = new Array<LeftPaletteComponent>();
+ this.onFinishLoadingEvent = onFinishEventListener;
+ }
+}
+
+export class LeftPaletteLoaderService {
+
+ static '$inject' = [
+ 'Restangular',
+ 'sdcConfig',
+ '$q',
+ 'ComponentFactory',
+ 'EventListenerService'
+
+ ];
+
+ constructor(protected restangular:restangular.IElement,
+ protected sdcConfig:IAppConfigurtaion,
+ protected $q:ng.IQService,
+ protected ComponentFactory:ComponentFactory,
+ protected EventListenerService:EventListenerService) {
+
+ this.restangular.setBaseUrl(sdcConfig.api.root + sdcConfig.api.component_api_root);
+
+ }
+
+ private serviceLeftPaletteData:LeftPaletteDataObject;
+ private resourceLeftPaletteData:LeftPaletteDataObject;
+ private productLeftPaletteData:LeftPaletteDataObject;
+ private vlData:LeftPaletteDataObject;
+
+ public loadLeftPanel = (componentType: string):void => {
+ this.serviceLeftPaletteData = new LeftPaletteDataObject(EVENTS.SERVICE_LEFT_PALETTE_UPDATE_EVENT);
+ this.resourceLeftPaletteData = new LeftPaletteDataObject(EVENTS.RESOURCE_LEFT_PALETTE_UPDATE_EVENT);
+ this.updateComponentLeftPalette(componentType);
+ }
+
+
+ private getTypeUrl = (componentType:string):string => {
+ return ComponentType.PRODUCT === componentType ? "services" : "resources";
+ };
+
+ private onFinishLoading = (componentType:string, leftPaletteData:LeftPaletteDataObject):void => {
+ this.EventListenerService.notifyObservers(leftPaletteData.onFinishLoadingEvent);
+ };
+
+ private updateLeftPalette = (componentType, componentInternalType:string, leftPaletteData:LeftPaletteDataObject):void => {
+
+ this.restangular.one(this.getTypeUrl(componentType)).one('/latestversion/notabstract/metadata').get({'internalComponentType': componentInternalType}).then((leftPaletteComponentMetadata:Array<ComponentMetadata>) => {
+ _.forEach(leftPaletteComponentMetadata, (componentMetadata:ComponentMetadata) => {
+ leftPaletteData.displayLeftPanelComponents.push(new LeftPaletteComponent(componentMetadata));
+ });
+ this.onFinishLoading(componentType, leftPaletteData);
+ });
+ };
+
+ public getLeftPanelComponentsForDisplay = (componentType:string):Array<LeftPaletteComponent> => {
+ switch (componentType) {
+ case ComponentType.SERVICE:
+ return this.serviceLeftPaletteData.displayLeftPanelComponents;
+ case ComponentType.PRODUCT:
+ return this.productLeftPaletteData.displayLeftPanelComponents;
+ default:
+ return this.resourceLeftPaletteData.displayLeftPanelComponents;
+ }
+ };
+
+ public updateComponentLeftPalette = (componentType):void => {
+ switch (componentType) {
+ case ResourceType.VL:
+ this.updateLeftPalette(ComponentType.RESOURCE, ResourceType.VL, this.vlData);
+ break;
+ case ComponentType.SERVICE:
+ this.updateLeftPalette(ComponentType.SERVICE, ComponentType.SERVICE, this.serviceLeftPaletteData);
+ break;
+ case ComponentType.PRODUCT:
+ this.updateLeftPalette(ComponentType.PRODUCT, ComponentType.SERVICE, this.productLeftPaletteData);
+ break;
+ default:
+ this.updateLeftPalette(ComponentType.RESOURCE, ResourceType.VF, this.resourceLeftPaletteData);
+ }
+ };
+}
diff --git a/catalog-ui/src/app/services/configuration-ui-service.ts b/catalog-ui/src/app/services/configuration-ui-service.ts
new file mode 100644
index 0000000000..92da0a50ed
--- /dev/null
+++ b/catalog-ui/src/app/services/configuration-ui-service.ts
@@ -0,0 +1,25 @@
+'use strict'
+import {IAppConfigurtaion, IApi} from "../models/app-config";
+
+interface IConfigurationUiService {
+ getConfigurationUi():ng.IPromise<any>;
+}
+
+export class ConfigurationUiService implements IConfigurationUiService {
+
+ static '$inject' = ['$http', '$q', 'sdcConfig'];
+ private api:IApi;
+
+ constructor(private $http:ng.IHttpService, private $q:ng.IQService, sdcConfig:IAppConfigurtaion) {
+ this.api = sdcConfig.api;
+ }
+
+ public getConfigurationUi = ():ng.IPromise<any> => {
+ let defer = this.$q.defer<any>();
+ this.$http.get(this.api.root + this.api.GET_configuration_ui)
+ .then((result:any) => {
+ defer.resolve(result.data);
+ });
+ return defer.promise;
+ }
+}
diff --git a/catalog-ui/src/app/services/cookie-service.ts b/catalog-ui/src/app/services/cookie-service.ts
new file mode 100644
index 0000000000..8f88835c18
--- /dev/null
+++ b/catalog-ui/src/app/services/cookie-service.ts
@@ -0,0 +1,72 @@
+'use strict';
+import {IAppConfigurtaion, ICookie} from "../models/app-config";
+
+interface ICookieService {
+ getUserId():string;
+ getFirstName():string;
+ getLastName():string;
+ getEmail():string;
+ getUserIdSuffix():string;
+}
+
+export class CookieService implements ICookieService {
+
+ static '$inject' = ['sdcConfig', '$document'];
+ private cookie:ICookie;
+ private cookiePrefix:string;
+
+
+ constructor(sdcConfig:IAppConfigurtaion, private $document) {
+ this.cookie = sdcConfig.cookie;
+
+ this.cookiePrefix = '';
+ let junctionName:string = this.getCookieByName(this.cookie.junctionName);
+ if ((junctionName !== null) && (junctionName !== '')) {
+ this.cookiePrefix = this.cookie.prefix + junctionName + '!';
+ }
+ }
+
+ private getCookieByName = (cookieName:string):string => {
+ cookieName += '=';
+ let cookies:Array<string> = this.$document[0].cookie.split(';');
+ let cookieVal:string = '';
+ cookies.forEach((cookie:string) => {
+ while (cookie.charAt(0) === ' ') {
+ cookie = cookie.substring(1);
+ }
+ if (cookie.indexOf(cookieName) === 0) {
+ cookieVal = cookie.substring(cookieName.length, cookie.length);
+ return;
+ }
+ });
+ return cookieVal;
+ };
+
+ public getUserIdSuffix = ():string => {
+ return this.cookie.userIdSuffix;
+ };
+
+ public getUserId = ():string => {
+ let userIdCookieName:string = this.cookiePrefix + this.cookie.userIdSuffix;
+ let userId:string = this.getCookieByName(userIdCookieName);
+ return userId;
+ };
+
+ public getFirstName = ():string => {
+ let firstNameCookieName:string = this.cookiePrefix + this.cookie.userFirstName;
+ let firstName:string = this.getCookieByName(firstNameCookieName);
+ return firstName;
+ };
+
+ public getLastName = ():string => {
+ let lastNameCookieName:string = this.cookiePrefix + this.cookie.userLastName;
+ let lastName:string = this.getCookieByName(lastNameCookieName);
+ return lastName;
+ };
+
+ public getEmail = ():string => {
+ let emailCookieName:string = this.cookiePrefix + this.cookie.userEmail;
+ let email:string = this.getCookieByName(emailCookieName);
+ return email;
+ }
+}
diff --git a/catalog-ui/src/app/services/data-types-service.ts b/catalog-ui/src/app/services/data-types-service.ts
new file mode 100644
index 0000000000..1c6ac07fdc
--- /dev/null
+++ b/catalog-ui/src/app/services/data-types-service.ts
@@ -0,0 +1,125 @@
+'use strict';
+import { DataTypePropertyModel } from "../models/data-type-properties";
+import {ComponentInstance, InputModel, DataTypesMap, PropertyModel, InputPropertyBase, IAppConfigurtaion, SchemaProperty} from "../models";
+import {PROPERTY_DATA} from "../utils/constants";
+
+export interface IDataTypesService {
+
+ dataTypes:DataTypesMap; //Data type map
+ selectedPropertiesName:string;
+ selectedInput:PropertyModel;
+ alreadySelectedProperties:Array<InputPropertyBase>;
+ selectedInstance:ComponentInstance;
+ selectedComponentInputs:Array<InputModel>;
+ //declare methods
+ initDataTypes():void;
+ getAllDataTypes():DataTypesMap;
+ getFirsLevelOfDataTypeProperties(dataTypeName:string):Array<DataTypePropertyModel>;
+ isDataTypeForSchemaType(property:SchemaProperty):boolean;
+ isDataTypeForPropertyType(property:PropertyModel):boolean;
+ isDataTypeForDataTypePropertyType(property:DataTypePropertyModel):boolean;
+}
+
+export class DataTypesService implements IDataTypesService {
+
+ static '$inject' = [
+ 'sdcConfig',
+ '$q',
+ '$http'
+ ];
+
+ constructor(private sdcConfig:IAppConfigurtaion,
+ private $q:ng.IQService,
+ private $http:ng.IHttpService) {
+
+ }
+
+ dataTypes:DataTypesMap; //Data type map
+ selectedPropertiesName:string;
+ selectedInput:PropertyModel;
+ alreadySelectedProperties:Array<InputPropertyBase>;
+ selectedInstance:ComponentInstance;
+ selectedComponentInputs:Array<InputModel>;
+
+ public initDataTypes = ():void => {
+ this.$http({
+ url: this.sdcConfig.api.root + this.sdcConfig.api.component_api_root + "dataTypes",
+ method: "get"
+ }).then((response:any) => {
+ this.dataTypes = response.data;
+ delete this.dataTypes['tosca.datatypes.Root'];
+ });
+ };
+
+ public getAllDataTypes = ():DataTypesMap => {
+ return this.dataTypes;
+ };
+
+ //if the dt derived from simple- return the first parent type, else- return null
+ private getTypeForDataTypeDerivedFromSimple = (dataTypeName:string):string => {
+ /////////temporary hack for tosca primitives///////////////////////
+ if (!this.dataTypes[dataTypeName]) {
+ return 'string';
+ }
+ ///////////////////////////////////////////////////////////////////
+ if (this.dataTypes[dataTypeName].derivedFromName == "tosca.datatypes.Root" || this.dataTypes[dataTypeName].properties) {
+ return null;
+ }
+ if (PROPERTY_DATA.SIMPLE_TYPES.indexOf(this.dataTypes[dataTypeName].derivedFromName) > -1) {
+ return this.dataTypes[dataTypeName].derivedFromName
+ }
+ return this.getTypeForDataTypeDerivedFromSimple(this.dataTypes[dataTypeName].derivedFromName);
+ };
+
+
+ //return list of data type properties and all its parents properties
+ //(not include the properties of its properties, in case this data type has not primitive properties)
+ public getFirsLevelOfDataTypeProperties = (dataTypeName:string):Array<DataTypePropertyModel> => {
+ let properties = this.dataTypes[dataTypeName].properties || [];
+ if (this.dataTypes[dataTypeName].derivedFromName != "tosca.datatypes.Root") {
+ properties = this.getFirsLevelOfDataTypeProperties(this.dataTypes[dataTypeName].derivedFromName).concat(properties);
+ }
+ return properties;
+ };
+
+ //return false when type= data type (=not simple type) that not derived from simple type
+ public isDataTypeForSchemaType = (property:SchemaProperty):boolean=> {
+ property.simpleType = "";
+ if (property.type && PROPERTY_DATA.TYPES.indexOf(property.type) > -1) {
+ return false;
+ }
+ let simpleType = this.getTypeForDataTypeDerivedFromSimple(property.type);
+ if (simpleType) {
+ property.simpleType = simpleType;
+ return false;
+ }
+ return true;
+ };
+
+ public isDataTypeForPropertyType = (property:PropertyModel):boolean=> {
+ property.simpleType = "";
+ if (property.type && PROPERTY_DATA.TYPES.indexOf(property.type) > -1) {
+ return false;
+ }
+ let simpleType = this.getTypeForDataTypeDerivedFromSimple(property.type);
+ if (simpleType) {
+ property.simpleType = simpleType;
+ return false;
+ }
+ return true;
+ };
+
+
+ public isDataTypeForDataTypePropertyType = (property:DataTypePropertyModel):boolean=> {
+ property.simpleType = "";
+ if (property.type && PROPERTY_DATA.TYPES.indexOf(property.type) > -1) {
+ return false;
+ }
+ let simpleType = this.getTypeForDataTypeDerivedFromSimple(property.type);
+ if (simpleType) {
+ property.simpleType = simpleType;
+ return false;
+ }
+ return true;
+ };
+}
diff --git a/catalog-ui/src/app/services/ecomp-service.ts b/catalog-ui/src/app/services/ecomp-service.ts
new file mode 100644
index 0000000000..2703a50fc3
--- /dev/null
+++ b/catalog-ui/src/app/services/ecomp-service.ts
@@ -0,0 +1,30 @@
+'use strict';
+import {IAppConfigurtaion, IApi} from "../models/app-config";
+
+interface IEcompHeaderService {
+ getMenuItems(userId):ng.IPromise<Array<any>>;
+}
+
+export class EcompHeaderService implements IEcompHeaderService {
+ static '$inject' = ['$http', '$q', 'sdcConfig'];
+ private api:IApi;
+
+ constructor(private $http:ng.IHttpService,
+ private $q:ng.IQService,
+ private sdcConfig:IAppConfigurtaion) {
+ this.api = sdcConfig.api;
+ }
+
+ getMenuItems = (userId):ng.IPromise<Array<any>> => {
+ let defer = this.$q.defer<Array<any>>();
+ //defer.resolve(this.mockData);
+ this.$http.get(this.api.root + this.api.GET_ecomp_menu_items.replace(':userId', userId))
+ .then((response:any) => {
+ defer.resolve(response.data);
+ }, (response) => {
+ defer.reject(response.data);
+ });
+
+ return defer.promise;
+ };
+}
diff --git a/catalog-ui/src/app/services/entity-service.ts b/catalog-ui/src/app/services/entity-service.ts
new file mode 100644
index 0000000000..d480bf9104
--- /dev/null
+++ b/catalog-ui/src/app/services/entity-service.ts
@@ -0,0 +1,94 @@
+'use strict';
+import {Product, Service, IApi, IAppConfigurtaion, Resource, Component} from "../models";
+import {SharingService} from "./sharing-service";
+import {ComponentFactory} from "../utils/component-factory";
+import {CacheService} from "./cache-service";
+
+interface IEntityService {
+ getAllComponents():ng.IPromise<Array<Component>>;
+}
+
+interface IComponentsArray {
+ services:Array<Service>;
+ resources:Array<Resource>;
+ products:Array<Product>;
+}
+
+export class EntityService implements IEntityService {
+ static '$inject' = ['$http', '$q', 'sdcConfig', 'Sdc.Services.SharingService', 'ComponentFactory', 'Sdc.Services.CacheService'];
+ private api:IApi;
+
+ constructor(private $http:ng.IHttpService,
+ private $q:ng.IQService,
+ private sdcConfig:IAppConfigurtaion,
+ private sharingService:SharingService,
+ private ComponentFactory:ComponentFactory,
+ private cacheService:CacheService) {
+ this.api = sdcConfig.api;
+ }
+
+ getCatalog = ():ng.IPromise<Array<Component>> => {
+ let defer = this.$q.defer<Array<Component>>();
+ this.$http.get(this.api.root + this.api.GET_catalog)
+ .then((response:any) => {
+ let followedResponse: IComponentsArray = response.data;
+ let componentsList:Array<Component> = new Array();
+
+ 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) => {
+ let component:Resource = this.ComponentFactory.createResource(resourceResponse);
+ componentsList.push(component);
+ this.sharingService.addUuidValue(component.uniqueId, component.uuid);
+ });
+
+ followedResponse.products.forEach((productResponse:Product) => {
+
+ let component:Product = this.ComponentFactory.createProduct(productResponse);
+ componentsList.push(component);
+ this.sharingService.addUuidValue(component.uniqueId, component.uuid);
+ });
+
+ this.cacheService.set('breadcrumbsComponents', componentsList);
+ defer.resolve(componentsList);
+ },(responce) => {
+ defer.reject(responce);
+ });
+ return defer.promise;
+ };
+
+ getAllComponents = ():ng.IPromise<Array<Component>> => {
+ let defer = this.$q.defer<Array<Component>>();
+ this.$http.get(this.api.root + this.api.GET_element)
+ .then((response:any) => {
+ let componentResponse:IComponentsArray = response.data;
+ let componentsList:Array<Component> = [];
+
+ componentResponse.services && componentResponse.services.forEach((serviceResponse:Service) => {
+ let component:Service = this.ComponentFactory.createService(serviceResponse);
+ componentsList.push(component);
+ this.sharingService.addUuidValue(component.uniqueId, component.uuid);
+ });
+
+ componentResponse.resources && componentResponse.resources.forEach((resourceResponse:Resource) => {
+ let component:Resource = this.ComponentFactory.createResource(resourceResponse);
+ componentsList.push(component);
+ this.sharingService.addUuidValue(component.uniqueId, component.uuid);
+ });
+
+ componentResponse.products && componentResponse.products.forEach((productsResponse:Product) => {
+ let component:Product = this.ComponentFactory.createProduct(productsResponse);
+ componentsList.push(component);
+ this.sharingService.addUuidValue(component.uniqueId, component.uuid);
+ });
+ this.cacheService.set('breadcrumbsComponents', componentsList);
+ defer.resolve(componentsList);
+ });
+
+ return defer.promise;
+ };
+}
diff --git a/catalog-ui/src/app/services/event-listener-service.ts b/catalog-ui/src/app/services/event-listener-service.ts
new file mode 100644
index 0000000000..51aa857e51
--- /dev/null
+++ b/catalog-ui/src/app/services/event-listener-service.ts
@@ -0,0 +1,85 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+/**
+ * Created by obarda on 7/4/2016.
+ */
+'use strict';
+import {Dictionary} from "../utils/dictionary/dictionary";
+
+interface IEventListenerService {
+
+}
+
+interface ICallbackData {
+ callback:Function;
+ args:any[];
+}
+
+export class EventListenerService implements IEventListenerService {
+
+ public observerCallbacks:Dictionary<string, ICallbackData[]> = new Dictionary<string, Array<ICallbackData>>();
+
+ //register an observer + callback
+ public registerObserverCallback = (eventName:string, callback:Function, ...args) => {
+ let callbackData = {
+ callback: callback,
+ args: args
+ }
+
+ if (this.observerCallbacks.containsKey(eventName)) {
+ let callbacks = this.observerCallbacks.getValue(eventName);
+
+ // Only insert the callback if the callback is different from existing callbacks.
+ for (let i = 0; i < callbacks.length; i++) {
+ if (callbacks[i].toString() === callback.toString()) {
+ return; // Do not add this callback.
+ }
+ }
+
+ callbacks.push(callbackData);
+ this.observerCallbacks.setValue(eventName, callbacks);
+ } else {
+ this.observerCallbacks.setValue(eventName, [callbackData]);
+ }
+ };
+
+ //unregister an observer
+ public unRegisterObserver = (eventName:string, callbackFunc?:Function) => {
+ if (this.observerCallbacks.containsKey(eventName)) {
+
+ let callbacks: ICallbackData[] = this.observerCallbacks.getValue(eventName);
+ if(callbacks.length === 1) {
+ this.observerCallbacks.remove(eventName);
+ } else {
+ let filterCallbacks = _.filter(callbacks, (callBackObj) => {
+ return callBackObj.callback != callbackFunc;
+ });
+ this.observerCallbacks.setValue(eventName, filterCallbacks);
+ }
+
+ }
+ };
+
+ public notifyObservers = function (eventName:string, ...args) {
+ _.forEach(this.observerCallbacks.getValue(eventName), (callbackData:ICallbackData) => {
+ callbackData.callback(...args);
+ });
+ };
+}
diff --git a/catalog-ui/src/app/services/header-interceptor.ts b/catalog-ui/src/app/services/header-interceptor.ts
new file mode 100644
index 0000000000..a1e79934d8
--- /dev/null
+++ b/catalog-ui/src/app/services/header-interceptor.ts
@@ -0,0 +1,69 @@
+'use strict';
+import {IAppConfigurtaion} from "../models/app-config";
+import {Dictionary} from "../utils/dictionary/dictionary";
+import {SharingService} from "./sharing-service";
+
+//Method name should be exactly "response" - http://docs.angularjs.org/api/ng/service/$http
+export interface IInterceptor {
+ request:Function;
+
+}
+
+export class HeaderInterceptor implements IInterceptor {
+ public static $inject = [
+ '$injector',
+ '$q',
+ 'uuid4',
+ 'Sdc.Services.SharingService',
+ 'sdcConfig',
+ '$location'
+ ];
+
+ public static Factory($injector:ng.auto.IInjectorService,
+ $q:ng.IQService,
+ uuid4:any,
+ sharingService:SharingService,
+ sdcConfig:IAppConfigurtaion,
+ $location:ng.ILocationService) {
+ return new HeaderInterceptor($injector, $q, uuid4, sharingService, sdcConfig, $location);
+ }
+
+ constructor(private $injector:ng.auto.IInjectorService,
+ private $q:ng.IQService,
+ private uuid4:any,
+ private sharingService:SharingService,
+ private sdcConfig:IAppConfigurtaion,
+ private $location:ng.ILocationService) {
+ console.debug('header-interceptor: initializing AuthenticationInterceptor');
+ }
+
+ public request = (requestSuccess):ng.IPromise<any> => {
+ requestSuccess.headers['X-ECOMP-RequestID'] = this.uuid4.generate();
+ /**
+ * For every request to the server, that the service id, or resource id is sent in the URL, need to pass UUID in the header.
+ * Check if the unique id exists in uuidMap, and if so get the UUID and add it to the header.
+ */
+ let map:Dictionary<string, string> = this.sharingService.getUuidMap();
+ if (map && requestSuccess.url.indexOf(this.sdcConfig.api.root) === 0) {
+ console.log("header-interceptor: url: " + requestSuccess.url);
+ map.forEach((key:string) => {
+ if (requestSuccess.url.indexOf(key) !== -1) {
+ requestSuccess.headers['X-ECOMP-ServiceID'] = this.sharingService.getUuidValue(key);
+ }
+ });
+ }
+ return requestSuccess;
+ };
+
+ public response = (responseSuccess):ng.IPromise<any> => {
+ let responseData = responseSuccess.data;
+ if (responseData) {
+ let data = JSON.stringify(responseData);
+ if (data && (data.indexOf("Global Logon: Login") > 0)) {
+ this.$location.path('dashboard/welcome');
+ window.location.reload();
+ }
+ }
+ return responseSuccess;
+ }
+}
diff --git a/catalog-ui/src/app/services/http-error-interceptor.ts b/catalog-ui/src/app/services/http-error-interceptor.ts
new file mode 100644
index 0000000000..b61091c37c
--- /dev/null
+++ b/catalog-ui/src/app/services/http-error-interceptor.ts
@@ -0,0 +1,99 @@
+'use strict';
+import {IServerMessageModalModel} from "../view-models/modals/message-modal/message-server-modal/server-message-modal-view-model";
+import {SEVERITY} from "../utils/constants";
+import 'app/utils/prototypes.ts';
+
+export class HttpErrorInterceptor {
+ public static $inject = ['$injector', '$q'];
+
+ public static Factory($injector:ng.auto.IInjectorService, $q:angular.IQService) {
+ return new HttpErrorInterceptor($injector, $q);
+ }
+
+ constructor(private $injector:ng.auto.IInjectorService, private $q:angular.IQService) {
+ }
+
+ public formatMessageArrays = (message:string, variables:Array<string>)=> {
+ return message.replace(/\[%(\d+)\]/g, function (_, m) {
+ let tmp = [];
+ let list = variables[--m].split(";");
+ list.forEach(function (item) {
+ tmp.push("<li>" + item + "</li>");
+ });
+ return "<ul>" + tmp.join("") + "</ul>";
+ });
+ };
+
+ public responseError = (rejection:any)=> {
+
+ let text:string;
+ let variables;
+ let messageId:string = "";
+ let isKnownException = false;
+
+ if (rejection.data && rejection.data.serviceException) {
+ text = rejection.data.serviceException.text;
+ variables = rejection.data.serviceException.variables;
+ messageId = rejection.data.serviceException.messageId;
+ isKnownException = true;
+ } else if (rejection.data && rejection.data.requestError && rejection.data.requestError.serviceException) {
+ text = rejection.data.requestError.serviceException.text;
+ variables = rejection.data.requestError.serviceException.variables;
+ messageId = rejection.data.requestError.serviceException.messageId;
+ isKnownException = true;
+ } else if (rejection.data && rejection.data.requestError && rejection.data.requestError.policyException) {
+ text = rejection.data.requestError.policyException.text;
+ variables = rejection.data.requestError.policyException.variables;
+ messageId = rejection.data.requestError.policyException.messageId;
+ isKnownException = true;
+ } else if (rejection.data) {
+ text = 'Wrong error format from server';
+ console.error(text);
+ isKnownException = false;
+ }
+
+ let data:IServerMessageModalModel;
+ if (isKnownException) {
+ // Remove the "Error: " text at the begining
+ if (text.trim().indexOf("Error:") === 0) {
+ text = text.replace("Error:", "").trim();
+ }
+
+ //mshitrit DE199895 bug fix
+ let count:number = 0;
+ variables.forEach(function (item) {
+ variables[count] = item ? item.replace('<', '&lt').replace('>', '&gt') : '';
+ count++;
+ });
+
+ // Format the message in case has array to <ul><li>
+ text = this.formatMessageArrays(text, variables);
+
+ // Format the message %1 %2
+ text = text.format(variables);
+
+ // Need to inject the MessageService manually to prevent circular dependencies (because MessageService use $templateCache that use $http).
+ data = {
+ title: 'Error',
+ message: text,
+ messageId: messageId,
+ status: rejection.status,
+ severity: SEVERITY.ERROR
+ };
+ } else {
+ // Need to inject the MessageService manually to prevent circular dependencies (because MessageService use $templateCache that use $http).
+ data = {
+ title: 'Error',
+ message: rejection.status !== -1 ? rejection.statusText : "Error getting response from server",
+ messageId: messageId,
+ status: rejection.status,
+ severity: SEVERITY.ERROR
+ };
+ }
+
+ let modalsHandler = this.$injector.get('ModalsHandler');
+ modalsHandler.openServerMessageModal(data);
+
+ return this.$q.reject(rejection);
+ }
+}
diff --git a/catalog-ui/src/app/services/loader-service.ts b/catalog-ui/src/app/services/loader-service.ts
new file mode 100644
index 0000000000..4bf8a6afe0
--- /dev/null
+++ b/catalog-ui/src/app/services/loader-service.ts
@@ -0,0 +1,24 @@
+/**
+ * Created by obarda on 3/13/2016.
+ */
+'use strict';
+import {EventListenerService} from "./event-listener-service";
+import {EVENTS} from "../utils/constants";
+
+export class LoaderService {
+
+
+ constructor(private eventListenerService:EventListenerService) {
+
+ }
+
+ public showLoader(...args) {
+ this.eventListenerService.notifyObservers(EVENTS.SHOW_LOADER_EVENT, ...args);
+ }
+
+ public hideLoader(...args) {
+ this.eventListenerService.notifyObservers(EVENTS.HIDE_LOADER_EVENT, ...args);
+ }
+}
+
+LoaderService.$inject = ['EventListenerService'];
diff --git a/catalog-ui/src/app/services/onboarding-service.ts b/catalog-ui/src/app/services/onboarding-service.ts
new file mode 100644
index 0000000000..8b93b18ca9
--- /dev/null
+++ b/catalog-ui/src/app/services/onboarding-service.ts
@@ -0,0 +1,82 @@
+'use strict';
+import {Component, IComponent} from "../models/components/component";
+import {ICsarComponent} from "../models/csar-component";
+import {IAppConfigurtaion, IApi} from "../models/app-config";
+import {IFileDownload} from "../models/file-download";
+import {Resource} from "../models/components/resource";
+import {ComponentFactory} from "../utils/component-factory";
+
+interface IOnboardingService {
+ getOnboardingComponents():ng.IPromise<Array<IComponent>>;
+ getComponentFromCsarUuid(csarUuid:string):ng.IPromise<Component>;
+ downloadOnboardingCsar(packageId:string):ng.IPromise<IFileDownload>;
+}
+
+export class OnboardingService implements IOnboardingService {
+
+ static '$inject' = ['$http', '$q', 'sdcConfig', 'ComponentFactory'];
+ private api:IApi;
+
+ constructor(private $http:ng.IHttpService,
+ private $q:ng.IQService,
+ private sdcConfig:IAppConfigurtaion,
+ private ComponentFactory:ComponentFactory) {
+ this.api = sdcConfig.api;
+ }
+
+ getOnboardingComponents = ():ng.IPromise<Array<IComponent>> => {
+ let defer = this.$q.defer<Array<IComponent>>();
+ this.$http.get(this.api.GET_onboarding)
+ .then((response:any) => {
+ let onboardingComponents:Array<ICsarComponent> = response.data.results;
+ let componentsList:Array<IComponent> = new Array();
+
+ onboardingComponents.forEach((obc:ICsarComponent) => {
+ let component:Component = this.ComponentFactory.createFromCsarComponent(obc);
+ componentsList.push(component);
+ });
+
+ defer.resolve(componentsList);
+ },(response) => {
+ defer.reject(response);
+ });
+
+ return defer.promise;
+ };
+
+ downloadOnboardingCsar = (packageId:string):ng.IPromise<IFileDownload> => {
+ let defer = this.$q.defer();
+ this.$http({
+ url: this.api.GET_onboarding + "/" + packageId,
+ method: "get",
+ responseType: "blob"
+ })
+ .then((response:any) => {
+ defer.resolve(response.data);
+ }, (err) => {
+ defer.reject(err);
+ });
+
+ return defer.promise;
+ };
+
+ getComponentFromCsarUuid = (csarUuid:string):ng.IPromise<Component> => {
+ let defer = this.$q.defer<Component>();
+ this.$http.get(this.api.root + this.api.GET_component_from_csar_uuid.replace(':csar_uuid', csarUuid))
+ .then((response:any) => {
+ let component:Resource;
+ // If the status is 400, this means that the component not found.
+ // I do not want to return error from server, because a popup will appear in client with the error.
+ // So returning success (200) with status 400.
+ if (response.data.status !== 400) {
+ component = new Resource(null, this.$q, <Resource>response.data);
+ }
+ defer.resolve(component);
+ },(response) => {
+ defer.reject(response.data);
+ });
+
+ return defer.promise;
+ };
+
+}
diff --git a/catalog-ui/src/app/services/progress-service.ts b/catalog-ui/src/app/services/progress-service.ts
new file mode 100644
index 0000000000..59ae16d734
--- /dev/null
+++ b/catalog-ui/src/app/services/progress-service.ts
@@ -0,0 +1,85 @@
+/**
+ * Created by obarda on 7/7/2016.
+ */
+
+'use strict';
+import IIntervalService = angular.IIntervalService;
+
+export class ProgressService {
+
+ public progresses:any = {};
+
+ static '$inject' = ['$interval'];
+
+ constructor(protected $interval:any) {
+ }
+
+ private totalProgress:number = 90;
+ private startProgress:number = 10;
+ private onePercentIntervalSeconds:number = 5;
+ private createComponentInterval;
+
+ public setProgressValue(name:string, value:number):void {
+ if (!this.progresses[name]) {
+ this.progresses[name] = {};
+ }
+ this.progresses[name].value = value;
+ }
+
+ public getProgressValue(name:string):number {
+ if (this.progresses[name]) {
+ return this.progresses[name].value;
+ }
+ return 0;
+ }
+
+ public deleteProgressValue(name:string):void {
+ this.stopCreateComponentInterval();
+ delete this.progresses[name];
+ }
+
+
+ private stopCreateComponentInterval = ():void => {
+ this.$interval.cancel(this.createComponentInterval);
+ };
+
+
+ public initCreateComponentProgress = (componentId:string):void => {
+ let progressValue:number = this.startProgress;
+ if (!this.getProgressValue(componentId)) {
+ this.stopCreateComponentInterval();
+ this.setProgressValue(componentId, this.startProgress);
+ this.createComponentInterval = this.$interval(():void => {
+ //TODO replace getProgressMockData to real data after BE provide the API
+ let progressValue = this.getProgressMockData(componentId);
+ if (progressValue <= this.totalProgress) {
+ this.setProgressValue(componentId, progressValue);
+ } else {
+ /**
+ * Currently the progress is not really checking against the BE.
+ * So the progress can pass 100. So the workaround for now, in case we pass 90 (totalProgress)
+ * stop the interval, so the progress will be kept at 90 until the promise will return value and set
+ * the progress to 100.
+ */
+ this.deleteProgressValue(componentId);
+ }
+ }, this.onePercentIntervalSeconds * 1000);
+ }
+
+ };
+
+
+ private getProgressMockData = (id:string):number => {
+ let progressValue = this.getProgressValue(id);
+ if (progressValue > 0) {
+ progressValue = progressValue + 1;
+ }
+ //if not finish always stay on 90%
+ if (progressValue > 90) {
+ progressValue = 90;
+ }
+
+ return progressValue;
+ }
+
+}
diff --git a/catalog-ui/src/app/services/sdc-version-service.ts b/catalog-ui/src/app/services/sdc-version-service.ts
new file mode 100644
index 0000000000..47001e9c9c
--- /dev/null
+++ b/catalog-ui/src/app/services/sdc-version-service.ts
@@ -0,0 +1,26 @@
+'use strict';
+import {Distribution} from "../models/distribution";
+import {IAppConfigurtaion, IApi} from "../models/app-config";
+
+export interface ISdcVersionService {
+ getVersion():ng.IPromise<any>;
+}
+export class SdcVersionService implements ISdcVersionService {
+
+ static '$inject' = ['$http', '$q', 'sdcConfig'];
+ private api:IApi;
+
+ constructor(private $http:ng.IHttpService, private $q:ng.IQService, sdcConfig:IAppConfigurtaion) {
+ this.api = sdcConfig.api;
+ }
+
+ public getVersion():ng.IPromise<any> {
+ let defer = this.$q.defer<Array<Distribution>>();
+ this.$http.get(this.api.root + this.api.GET_SDC_Version)
+ .then((version:any) => {
+ defer.resolve(version.data);
+ });
+ return defer.promise;
+ }
+}
+
diff --git a/catalog-ui/src/app/services/sharing-service.ts b/catalog-ui/src/app/services/sharing-service.ts
new file mode 100644
index 0000000000..706f01f16b
--- /dev/null
+++ b/catalog-ui/src/app/services/sharing-service.ts
@@ -0,0 +1,20 @@
+'use strict';
+import {Dictionary} from "app/utils";
+
+export class SharingService {
+
+ private uuidMap:Dictionary<string, string> = new Dictionary<string,string>();
+
+ public getUuidValue = (uniqueId:string):string => {
+ return this.uuidMap.getValue(uniqueId);
+ };
+
+ public addUuidValue = (uniqueId:string, uuid:string):void => {
+ this.uuidMap.setValue(uniqueId, uuid);
+ };
+
+ public getUuidMap = ():Dictionary<string, string> => {
+ return this.uuidMap;
+ };
+
+}
diff --git a/catalog-ui/src/app/services/url-tobase64-service.ts b/catalog-ui/src/app/services/url-tobase64-service.ts
new file mode 100644
index 0000000000..4e8dc18c7f
--- /dev/null
+++ b/catalog-ui/src/app/services/url-tobase64-service.ts
@@ -0,0 +1,30 @@
+'use strict';
+
+export interface IUrlToBase64Service {
+ downloadUrl(url:string, callback:Function):void;
+}
+
+export class UrlToBase64Service implements IUrlToBase64Service {
+ constructor() {
+ }
+
+ public downloadUrl = (url:string, callback:Function):void => {
+ let xhr:any = new XMLHttpRequest();
+
+ xhr.onload = ():void => {
+ let reader = new FileReader();
+ reader.onloadend = ():void => {
+ if (xhr.status === 200) {
+ callback(reader.result);
+ } else {
+ callback(null);
+ }
+ };
+ reader.readAsDataURL(xhr.response);
+ };
+ xhr.open('GET', url);
+ xhr.responseType = 'blob';
+ xhr.send();
+ }
+}
+
diff --git a/catalog-ui/src/app/services/user-resource-service.ts b/catalog-ui/src/app/services/user-resource-service.ts
new file mode 100644
index 0000000000..b881e3a98a
--- /dev/null
+++ b/catalog-ui/src/app/services/user-resource-service.ts
@@ -0,0 +1,103 @@
+'use strict';
+import {IUserProperties} from "../models/user";
+import {ICookie, IAppConfigurtaion} from "../models/app-config";
+import {CookieService} from "./cookie-service";
+
+// Define an interface of the object you want to use, providing it's properties
+export interface IUserResource extends IUserProperties,ng.resource.IResource<IUserResource> {
+
+}
+
+// Define your resource, adding the signature of the custom actions
+export interface IUserResourceClass extends ng.resource.IResourceClass<IUserResource> {
+ authorize():IUserResource;
+ getLoggedinUser():IUserResource;
+ setLoggedinUser(user:IUserResource):void;
+ getAllUsers(success?:Function, error?:Function):Array<IUserResource>;
+ createUser(IResourceResource, success?:Function, error?:Function):void;
+ editUserRole(IResourceResource, success?:Function, error?:Function):void;
+ deleteUser(IResourceResource, success?:Function, error?:Function):void;
+}
+
+export class UserResourceService {
+
+ public static getResource = ($resource:ng.resource.IResourceService,
+ sdcConfig:IAppConfigurtaion,
+ cookieService:CookieService):IUserResourceClass => {
+
+ let url:string = sdcConfig.api.root + sdcConfig.api.GET_user;
+ let authorizeUrl:string = sdcConfig.api.root + sdcConfig.api.GET_user_authorize;
+ let authorizeActionHeaders:any = {};
+ let cookie:ICookie = sdcConfig.cookie;
+ authorizeActionHeaders[cookie.userFirstName] = cookieService.getFirstName();
+ authorizeActionHeaders[cookie.userLastName] = cookieService.getLastName();
+ authorizeActionHeaders[cookie.userEmail] = cookieService.getEmail();
+ authorizeActionHeaders[cookie.userIdSuffix] = cookieService.getUserId();
+
+ // Define your custom actions here as IActionDescriptor
+ let authorizeAction:ng.resource.IActionDescriptor = {
+ method: 'GET',
+ isArray: false,
+ url: authorizeUrl,
+ headers: authorizeActionHeaders
+ };
+
+ let getAllUsers:ng.resource.IActionDescriptor = {
+ method: 'GET',
+ isArray: true,
+ url: sdcConfig.api.root + sdcConfig.api.GET_all_users
+ };
+
+ let editUserRole:ng.resource.IActionDescriptor = {
+ method: 'POST',
+ isArray: false,
+ url: sdcConfig.api.root + sdcConfig.api.POST_edit_user_role,
+ transformRequest: (data, headers)=> {
+ data.payloadData = undefined;
+ data.payloadName = undefined;
+ return JSON.stringify(data);
+ }
+ };
+
+ let deleteUser:ng.resource.IActionDescriptor = {
+ method: 'DELETE',
+ isArray: false,
+ url: sdcConfig.api.root + sdcConfig.api.DELETE_delete_user
+ };
+
+ let createUser:ng.resource.IActionDescriptor = {
+ method: 'POST',
+ isArray: false,
+ url: sdcConfig.api.root + sdcConfig.api.POST_create_user,
+ transformRequest: (data, headers)=> {
+ data.payloadData = undefined;
+ data.payloadName = undefined;
+ return JSON.stringify(data);
+ }
+ };
+ let userResource:IUserResourceClass = <IUserResourceClass>$resource(
+ url,
+ {id: '@id'},
+ {
+ authorize: authorizeAction,
+ getAllUsers: getAllUsers,
+ createUser: createUser,
+ editUserRole: editUserRole,
+ deleteUser: deleteUser
+ }
+ );
+
+ let _loggedinUser:IUserResource;
+
+ userResource.getLoggedinUser = () => {
+ return _loggedinUser;
+ };
+
+ userResource.setLoggedinUser = (loggedinUser:IUserResource) => {
+ _loggedinUser = loggedinUser;
+ };
+
+ return userResource;
+ }
+}
+UserResourceService.getResource.$inject = ['$resource', 'sdcConfig', 'Sdc.Services.CookieService'];
diff --git a/catalog-ui/src/app/utils.ts b/catalog-ui/src/app/utils.ts
new file mode 100644
index 0000000000..734c276c56
--- /dev/null
+++ b/catalog-ui/src/app/utils.ts
@@ -0,0 +1,15 @@
+/**
+ * Created by ob0695 on 2/23/2017.
+ */
+export * from './utils/dictionary/dictionary';
+export * from './utils/artifacts-utils';
+export * from'./utils/file-utils'
+export * from './utils/validation-utils'
+export * from './utils/component-factory';
+export * from './utils/component-instance-factory';
+export * from './utils/change-lifecycle-state-handler';
+export * from './utils/modals-handler';
+export * from './utils/menu-handler';
+export * from './utils/constants';
+export * from './utils/common-utils';
+export * from './utils/functions';
diff --git a/catalog-ui/src/app/utils/artifacts-utils.ts b/catalog-ui/src/app/utils/artifacts-utils.ts
new file mode 100644
index 0000000000..b52fe6f03e
--- /dev/null
+++ b/catalog-ui/src/app/utils/artifacts-utils.ts
@@ -0,0 +1,104 @@
+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' = [
+ '$filter'
+ ];
+
+ constructor(private $filter:ng.IFilterService) {
+
+ }
+
+ public getArtifactTypeByState(currentState:string):string {
+ switch (currentState) {
+ case "workspace.composition.lifecycle":
+ return "interface";
+ case "workspace.composition.api":
+ return "api";
+ case "workspace.deployment_artifacts":
+ case "workspace.composition.deployment":
+ return "deployment";
+ case "workspace.composition.artifacts":
+ return "informational";
+ default:
+ return "informational";
+ }
+ }
+
+ public getTitle(artifactType:string, selectedComponent:Component):string {
+ switch (artifactType) {
+ case "interface":
+ return "Lifecycle Management";
+ case "api":
+ return "API Artifacts";
+ case "deployment":
+ return "Deployment Artifacts";
+ case "informational":
+ return "Informational Artifacts";
+ default:
+ if (!selectedComponent) {
+ return "";
+ } else {
+ return this.$filter("resourceName")(selectedComponent.name) + ' Artifacts';
+ }
+ }
+ }
+
+ public setArtifactType = (artifact:ArtifactModel, artifactType:string):void => {
+ switch (artifactType) {
+ case "api":
+ artifact.artifactGroupType = ArtifactGroupType.SERVICE_API;
+ break;
+ case "deployment":
+ artifact.artifactGroupType = ArtifactGroupType.DEPLOYMENT;
+ break;
+ default:
+ artifact.artifactGroupType = ArtifactGroupType.INFORMATION;
+ break;
+ }
+ };
+
+ public isLicenseType = (artifactType:string):boolean => {
+ let isLicense:boolean = false;
+
+ if (ArtifactType.VENDOR_LICENSE === artifactType || ArtifactType.VF_LICENSE === artifactType) {
+ isLicense = true;
+ }
+
+ return isLicense;
+ };
+
+ public removeArtifact = (artifact:ArtifactModel, artifactsArr:Array<ArtifactModel>):void => {
+
+ if (!artifact.mandatory && (ArtifactGroupType.INFORMATION == artifact.artifactGroupType ||
+ ArtifactGroupType.DEPLOYMENT == artifact.artifactGroupType)) {
+ _.remove(artifactsArr, {uniqueId: artifact.uniqueId});
+ }
+ else {
+ let artifactToDelete = _.find(artifactsArr, {uniqueId: artifact.uniqueId});
+
+ delete artifactToDelete.esId;
+ delete artifactToDelete.description;
+ delete artifactToDelete.artifactName;
+ delete artifactToDelete.apiUrl;
+ }
+ };
+
+ public addAnotherAfterSave(scope:IArtifactResourceFormViewModelScope) {
+ let newArtifact = new ArtifactModel();
+ this.setArtifactType(newArtifact, scope.artifactType);
+ scope.editArtifactResourceModel.artifactResource = newArtifact;
+
+ scope.forms.editForm['description'].$setPristine();
+ if (scope.forms.editForm['artifactLabel']) {
+ scope.forms.editForm['artifactLabel'].$setPristine();
+ }
+ if (scope.forms.editForm['type']) {
+ scope.forms.editForm['type'].$setPristine();
+ }
+
+ }
+}
diff --git a/catalog-ui/src/app/utils/change-lifecycle-state-handler.ts b/catalog-ui/src/app/utils/change-lifecycle-state-handler.ts
new file mode 100644
index 0000000000..dc59e3bb98
--- /dev/null
+++ b/catalog-ui/src/app/utils/change-lifecycle-state-handler.ts
@@ -0,0 +1,163 @@
+import {ComponentFactory} from "./component-factory";
+import {Component, Service,IAppMenu, IAppConfigurtaion} from "../models";
+import {IEmailModalModel, IEmailModalModel_Email, IEmailModalModel_Data} from "../view-models/modals/email-modal/email-modal-view-model";
+import {AsdcComment} from "../models/comments";
+import {ModalsHandler} from "./modals-handler";
+import {ServiceServiceNg2} from "../ng2/services/component-services/service.service";
+
+/**
+ * Created by obarda on 2/11/2016.
+ */
+
+export class ChangeLifecycleStateHandler {
+
+ static '$inject' = [
+ 'sdcConfig',
+ 'sdcMenu',
+ 'ComponentFactory',
+ '$filter',
+ 'ModalsHandler',
+ 'ServiceServiceNg2'
+ ];
+
+ constructor(private sdcConfig:IAppConfigurtaion,
+ private sdcMenu:IAppMenu,
+ private ComponentFactory:ComponentFactory,
+ private $filter:ng.IFilterService,
+ private ModalsHandler:ModalsHandler,
+ private ServiceServiceNg2:ServiceServiceNg2) {
+
+ }
+
+ private actualChangeLifecycleState = (component:Component, data:any, scope:any, onSuccessCallback?:Function, onErrorCallback?:Function):void => {
+
+ let self = this;
+
+ let getContacts = (component:Component):string => {
+ let testers = this.sdcConfig.testers;
+ let result:string = testers[component.componentType][component.categories[0].name] ?
+ testers[component.componentType][component.categories[0].name] :
+ testers[component.componentType]['default'];
+ return result;
+ };
+
+ let onSuccess = (newComponent:Component):void => {
+ //scope.isLoading = false;
+ console.info(component.componentType.toLowerCase + ' change state ', newComponent);
+ if (onSuccessCallback) {
+ onSuccessCallback(self.ComponentFactory.createComponent(newComponent), data.url);
+ }
+ };
+
+ let onError = (error):void => {
+ scope.isLoading = false;
+ console.info('Failed to changeLifecycleState to ', data.url);
+ if (onErrorCallback) {
+ onErrorCallback(error);
+ }
+ };
+
+ let comment:AsdcComment = new AsdcComment();
+ if (data.alertModal) {
+ // Show alert dialog if defined in menu.json
+ //-------------------------------------------------
+ let onOk = (confirmationText):void => {
+ comment.userRemarks = confirmationText;
+ scope.isLoading = true;
+ component.changeLifecycleState(data.url, comment).then(onSuccess, onError);
+ };
+
+ let onCancel = ():void => {
+ console.info('Cancel pressed');
+ scope.isLoading = false;
+ };
+
+ let modalTitle = this.sdcMenu.alertMessages[data.alertModal].title;
+ let modalMessage = this.sdcMenu.alertMessages[data.alertModal].message.format([component.componentType.toLowerCase()]);
+ this.ModalsHandler.openAlertModal(modalTitle, modalMessage).then(onOk, onCancel);
+ } else if (data.confirmationModal) {
+ // Show confirmation dialog if defined in menu.json
+ //-------------------------------------------------
+ let onOk = (confirmationText):void => {
+ comment.userRemarks = confirmationText;
+ scope.isLoading = true;
+ component.changeLifecycleState(data.url, comment).then(onSuccess, onError);
+ };
+
+ let onCancel = ():void => {
+ console.info('Cancel pressed');
+ scope.isLoading = false;
+ };
+
+ let modalTitle = this.sdcMenu.confirmationMessages[data.confirmationModal].title;
+ let modalMessage = this.sdcMenu.confirmationMessages[data.confirmationModal].message.format([component.componentType.toLowerCase()]);
+ let modalShowComment = this.sdcMenu.confirmationMessages[data.confirmationModal].showComment;
+ this.ModalsHandler.openConfirmationModal(modalTitle, modalMessage, modalShowComment).then(onOk, onCancel);
+
+ } else if (data.emailModal) {
+ // Show email dialog if defined in menu.json
+ //-------------------------------------------------
+ let onOk = (resource):void => {
+ if (resource) {
+ onSuccess(resource);
+ } else {
+ onError("Error changing life cycle state");
+ }
+ };
+
+ let onCancel = ():void => {
+ scope.isLoading = false;
+ };
+
+ let emailModel:IEmailModalModel = <IEmailModalModel>{};
+ emailModel.email = <IEmailModalModel_Email>{};
+ emailModel.data = <IEmailModalModel_Data>{};
+ emailModel.title = this.$filter('translate')("EMAIL_MODAL_TITLE");
+ emailModel.email.to = getContacts(component);
+ emailModel.email.subject = this.$filter('translate')("EMAIL_MODAL_SUBJECT", "{'entityName': '" + this.$filter('resourceName')(component.name) + "','entityVersion': '" + component.version + "'}");
+ emailModel.email.message = '';
+ emailModel.data.component = component;
+ emailModel.data.stateUrl = data.url;
+
+ this.ModalsHandler.openEmailModal(emailModel).then(onOk, onCancel);
+
+ } else {
+ // Submit to server only (no modal is shown).
+ scope.isLoading = true;
+ component.changeLifecycleState(data.url, comment).then(onSuccess, onError);
+ }
+
+ }
+
+ public changeLifecycleState = (component:Component, data:any, scope:any, onSuccessCallback?:Function, onErrorCallback?:Function):void => {
+
+ if (data.conformanceLevelModal) {
+ this.validateConformanceLevel(component, data, scope, onSuccessCallback, onErrorCallback);
+ } else {
+ this.actualChangeLifecycleState(component, data, scope, onSuccessCallback, onErrorCallback);
+ }
+ }
+
+ private validateConformanceLevel = (component:Component, data:any, scope:any, onSuccessCallback?:Function, onErrorCallback?:Function):void => {
+ // Validate conformance level if defined in menu.json
+ //-------------------------------------------------
+ this.ServiceServiceNg2.validateConformanceLevel(<Service>component).subscribe((res:boolean) => {
+ if (res === true) {
+ //conformance level is ok - continue
+ this.actualChangeLifecycleState(component, data, scope, onSuccessCallback, onErrorCallback);
+
+ } else {
+ //show warning modal
+ this.ModalsHandler.openConformanceLevelModal()
+ .then(() => {
+ //continue distribute
+ this.actualChangeLifecycleState(component, data, scope, onSuccessCallback, onErrorCallback);
+
+ }).catch(() => {
+ //reject distribution
+ this.actualChangeLifecycleState(component, data.conformanceLevelModal, scope, onSuccessCallback, onErrorCallback);
+ });
+ }
+ });
+ }
+}
diff --git a/catalog-ui/src/app/utils/common-utils.ts b/catalog-ui/src/app/utils/common-utils.ts
new file mode 100644
index 0000000000..d8019d2f96
--- /dev/null
+++ b/catalog-ui/src/app/utils/common-utils.ts
@@ -0,0 +1,96 @@
+import {Module, AttributeModel, ResourceInstance, PropertyModel, InputFEModel} from "../models";
+import {ComponentInstanceFactory} from "./component-instance-factory";
+import {PropertyBEModel, RelationshipModel} from "app/models";
+
+export class CommonUtils {
+
+ static initProperties(propertiesObj:Array<PropertyModel>, uniqueId?:string):Array<PropertyModel> {
+
+ let properties = new Array<PropertyModel>();
+ if (propertiesObj) {
+ _.forEach(propertiesObj, (property:PropertyModel):void => {
+ if (uniqueId) {
+ property.readonly = property.parentUniqueId != uniqueId;
+ }
+ properties.push(new PropertyModel(property));
+ });
+ }
+ return properties;
+ };
+
+ static initAttributes(attributesObj:Array<AttributeModel>, uniqueId?:string):Array<AttributeModel> {
+
+ let attributes = new Array<AttributeModel>();
+ if (attributesObj) {
+ _.forEach(attributesObj, (attribute:AttributeModel):void => {
+ if (uniqueId) {
+ attribute.readonly = attribute.parentUniqueId != uniqueId;
+ }
+ attributes.push(new AttributeModel(attribute));
+ });
+ }
+ return attributes;
+ };
+
+ static initComponentInstances(componentInstanceObj:Array<ResourceInstance>):Array<ResourceInstance> {
+
+ let componentInstances = new Array<ResourceInstance>();
+ if (componentInstanceObj) {
+ _.forEach(componentInstanceObj, (instance:ResourceInstance):void => {
+ componentInstances.push(ComponentInstanceFactory.createComponentInstance(instance));
+ });
+ }
+ return componentInstances;
+ };
+
+ static initModules(moduleArrayObj:Array<Module>):Array<Module> {
+
+ let modules = new Array<Module>();
+
+ if (moduleArrayObj) {
+ _.forEach(moduleArrayObj, (module:Module):void => {
+ if (module.type === "org.openecomp.groups.VfModule") {
+ modules.push(new Module(module));
+ }
+ });
+ }
+ return modules;
+ };
+
+ static initInputs(inputsObj:Array<PropertyBEModel>):Array<PropertyBEModel> {
+
+ let inputs = new Array<PropertyBEModel>();
+
+ if(inputsObj) {
+ _.forEach(inputsObj, (input:PropertyBEModel):void => {
+ inputs.push(new PropertyBEModel(input));
+ })
+ }
+
+ return inputs;
+ }
+
+ static initBeProperties(propertiesObj: Array<PropertyBEModel>): Array<PropertyBEModel> {
+
+ let properties = new Array<PropertyBEModel>();
+
+ if (propertiesObj) {
+ _.forEach(propertiesObj, (property: PropertyBEModel): void => {
+ properties.push(new PropertyBEModel(property));
+ })
+ }
+
+ return properties;
+ }
+
+ static initComponentInstanceRelations = (componentInstanceRelationsObj:Array<RelationshipModel>):Array<RelationshipModel> => {
+ if (componentInstanceRelationsObj) {
+ let componentInstancesRelations: Array<RelationshipModel> = [];
+ _.forEach(componentInstanceRelationsObj, (instanceRelation:RelationshipModel):void => {
+ componentInstancesRelations.push(new RelationshipModel(instanceRelation));
+ });
+ return componentInstancesRelations;
+ }
+ };
+}
+
diff --git a/catalog-ui/src/app/utils/component-factory.ts b/catalog-ui/src/app/utils/component-factory.ts
new file mode 100644
index 0000000000..18edbfb02c
--- /dev/null
+++ b/catalog-ui/src/app/utils/component-factory.ts
@@ -0,0 +1,161 @@
+'use strict';
+import {DEFAULT_ICON, ResourceType, ComponentType} from "./constants";
+import {ServiceService, CacheService, ResourceService, ProductService} from "app/services";
+import {IMainCategory, ISubCategory, ICsarComponent, Component, Resource, Service, Product} from "app/models";
+import {ComponentMetadata} from "../models/component-metadata";
+import {ComponentServiceNg2} from "../ng2/services/component-services/component.service";
+import {ComponentGenericResponse} from "../ng2/services/responses/component-generic-response";
+
+
+export class ComponentFactory {
+
+ static '$inject' = [
+ 'Sdc.Services.Components.ResourceService',
+ 'Sdc.Services.Components.ServiceService',
+ 'Sdc.Services.Components.ProductService',
+ 'Sdc.Services.CacheService',
+ '$q',
+ 'ComponentServiceNg2'
+ ];
+
+ constructor(private ResourceService:ResourceService,
+ private ServiceService:ServiceService,
+ private ProductService:ProductService,
+ private cacheService:CacheService,
+ private $q:ng.IQService,
+ private ComponentServiceNg2: ComponentServiceNg2) {
+ }
+
+ public createComponent = (component:Component):Component => {
+ let newComponent:Component;
+ switch (component.componentType) {
+
+ case 'SERVICE':
+ newComponent = new Service(this.ServiceService, this.$q, <Service> component);
+ break;
+
+ case 'RESOURCE':
+ newComponent = new Resource(this.ResourceService, this.$q, <Resource> component);
+ break;
+
+ case 'PRODUCT':
+ newComponent = new Product(this.ProductService, this.$q, <Product> component);
+ break;
+ }
+ return newComponent;
+ };
+
+ public createProduct = (product:Product):Product => {
+ let newProduct:Product = new Product(this.ProductService, this.$q, <Product> product);
+ return newProduct;
+ };
+
+ public createService = (service:Service):Service => {
+ let newService:Service = new Service(this.ServiceService, this.$q, <Service> service);
+ return newService;
+ };
+
+ public createResource = (resource:Resource):Resource => {
+ let newResource:Resource = new Resource(this.ResourceService, this.$q, <Resource> resource);
+ return newResource;
+ };
+
+ public createFromCsarComponent = (csar:ICsarComponent):Component => {
+ let newResource:Resource = <Resource>this.createEmptyComponent(ComponentType.RESOURCE);
+ newResource.name = csar.vspName;
+
+ /**
+ * Onboarding CSAR contains category and sub category that are uniqueId.
+ * Need to find the category and sub category and extract the name from them.
+ * First concat all sub categories to one array.
+ * Then find the selected sub category and category.
+ * @type {any}
+ */
+ let availableCategories = angular.copy(this.cacheService.get('resourceCategories'));
+ let allSubs = [];
+ _.each(availableCategories, (main:IMainCategory)=> {
+ if (main.subcategories) {
+ allSubs = allSubs.concat(main.subcategories);
+ }
+ });
+
+ let selectedCategory:IMainCategory = _.find(availableCategories, function (main:IMainCategory) {
+ return main.uniqueId === csar.category;
+ });
+
+ let selectedSubCategory:ISubCategory = _.find(allSubs, (sub:ISubCategory)=> {
+ return sub.uniqueId === csar.subCategory;
+ });
+
+ // Build the categories and sub categories array (same format as component category)
+ let categories:Array<IMainCategory> = new Array();
+ let subcategories:Array<ISubCategory> = new Array();
+ if (selectedCategory && selectedSubCategory) {
+ subcategories.push(selectedSubCategory);
+ selectedCategory.subcategories = subcategories;
+ categories.push(selectedCategory);
+ }
+
+ // Fill the component with details from CSAR
+ newResource.selectedCategory = selectedCategory && selectedSubCategory ? selectedCategory.name + "_#_" + selectedSubCategory.name : '';
+ newResource.categories = categories;
+ newResource.vendorName = csar.vendorName;
+ newResource.vendorRelease = csar.vendorRelease;
+ newResource.csarUUID = csar.packageId;
+ newResource.csarPackageType = csar.packageType;
+ newResource.csarVersion = csar.version;
+ newResource.packageId = csar.packageId;
+ newResource.description = csar.description;
+ return newResource;
+ };
+
+ public createEmptyComponent = (componentType:string):Component => {
+ let newComponent:Component;
+
+ switch (componentType) {
+
+ case ComponentType.SERVICE:
+ newComponent = new Service(this.ServiceService, this.$q);
+ break;
+
+ case ComponentType.RESOURCE:
+ case ResourceType.VF:
+ case ResourceType.VL:
+ case ResourceType.VFC:
+ case ResourceType.CP:
+ newComponent = new Resource(this.ResourceService, this.$q);
+ break;
+
+ case ComponentType.PRODUCT:
+ newComponent = new Product(this.ProductService, this.$q);
+ break;
+ }
+ newComponent.componentType = componentType;
+ newComponent.tags = [];
+ newComponent.icon = DEFAULT_ICON;
+ return newComponent;
+ };
+
+ public getComponentFromServer = (componentType:string, componentId:string):ng.IPromise<Component> => {
+ let newComponent:Component = this.createEmptyComponent(componentType);
+ newComponent.setUniqueId(componentId);
+ return newComponent.getComponent();
+ };
+
+ public createComponentOnServer = (componentObject:Component):ng.IPromise<Component> => {
+ let component:Component = this.createComponent(componentObject);
+ return component.createComponentOnServer();
+
+ };
+
+ public getComponentWithMetadataFromServer = (componentType:string, componentId:string):ng.IPromise<Component> => {
+ let deferred = this.$q.defer();
+ let component = this.createEmptyComponent(componentType);
+ component.setUniqueId(componentId);
+ this.ComponentServiceNg2.getComponentMetadata(component).subscribe((response:ComponentGenericResponse) => {
+ component.setComponentMetadata(response.metadata);
+ deferred.resolve(component);
+ });
+ return deferred.promise;
+ }
+}
diff --git a/catalog-ui/src/app/utils/component-instance-factory.ts b/catalog-ui/src/app/utils/component-instance-factory.ts
new file mode 100644
index 0000000000..df92f20c90
--- /dev/null
+++ b/catalog-ui/src/app/utils/component-instance-factory.ts
@@ -0,0 +1,81 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+/**
+ * Created by obarda on 3/7/2016.
+ */
+'use strict';
+import {ComponentInstance, ServiceInstance, ProductInstance, ResourceInstance, Component} from "../models";
+import {LeftPaletteComponent} from "../models/components/displayComponent";
+
+export class ComponentInstanceFactory {
+
+ static createComponentInstance(componentInstance:ComponentInstance):ComponentInstance {
+ let newComponentInstance:ComponentInstance;
+ switch (componentInstance.originType) {
+ case 'SERVICE':
+ newComponentInstance = new ServiceInstance(componentInstance);
+ break;
+
+ case 'PRODUCT':
+ newComponentInstance = new ProductInstance(componentInstance);
+ break;
+
+ default :
+ newComponentInstance = new ResourceInstance(componentInstance);
+ break;
+ }
+ return newComponentInstance;
+ };
+
+ public createEmptyComponentInstance = (componentInstanceType?:string):ComponentInstance => {
+ let newComponentInstance:ComponentInstance;
+ switch (componentInstanceType) {
+ case 'SERVICE':
+ newComponentInstance = new ServiceInstance();
+ break;
+
+ case 'PRODUCT':
+ newComponentInstance = new ProductInstance();
+ break;
+
+ default :
+ newComponentInstance = new ResourceInstance();
+ break;
+ }
+ return newComponentInstance;
+ };
+
+ public createComponentInstanceFromComponent = (component:LeftPaletteComponent):ComponentInstance => {
+ let newComponentInstance:ComponentInstance = this.createEmptyComponentInstance(component.componentType);
+ newComponentInstance.uniqueId = component.uniqueId + (new Date()).getTime();
+ newComponentInstance.posX = 0;
+ newComponentInstance.posY = 0;
+ newComponentInstance.name = component.name;
+ newComponentInstance.componentVersion = component.version;
+ newComponentInstance.originType = component.getComponentSubType();
+ //new component instance -> req. & cap. are added on successful instance creation
+ newComponentInstance.requirements = component.requirements;
+ newComponentInstance.capabilities = component.capabilities;
+ newComponentInstance.icon = component.icon;
+ newComponentInstance.componentUid = component.uniqueId;
+ return newComponentInstance;
+ };
+
+}
diff --git a/catalog-ui/src/app/utils/constants.ts b/catalog-ui/src/app/utils/constants.ts
new file mode 100644
index 0000000000..d55079d662
--- /dev/null
+++ b/catalog-ui/src/app/utils/constants.ts
@@ -0,0 +1,277 @@
+/**
+ * Created by obarda on 2/18/2016.
+ */
+
+export let DEFAULT_ICON = 'defaulticon';
+export let CP_END_POINT = 'CpEndPoint';
+export let CHANGE_COMPONENT_CSAR_VERSION_FLAG = 'changeComponentCsarVersion';
+
+export class ComponentType {
+ static SERVICE = 'SERVICE';
+ static RESOURCE = 'RESOURCE';
+ static PRODUCT = 'PRODUCT';
+}
+
+export class ServerTypeUrl {
+ static RESOURCES = 'resources/';
+ static SERVICES = 'services/';
+ static PRODUCTS = 'product/';
+}
+
+export class ResourceType {
+ static VF = 'VF';
+ static VL = 'VL';
+ static CP = 'CP';
+ static VFC = 'VFC';
+ static VFCMT = 'VFCMT';
+}
+
+export class ComponentState {
+ static CERTIFICATION_IN_PROGRESS = 'CERTIFICATION_IN_PROGRESS';
+ static CERTIFIED = 'CERTIFIED';
+ static NOT_CERTIFIED_CHECKOUT = 'NOT_CERTIFIED_CHECKOUT';
+ static NOT_CERTIFIED_CHECKIN = 'NOT_CERTIFIED_CHECKIN';
+ static READY_FOR_CERTIFICATION = 'READY_FOR_CERTIFICATION';
+}
+
+export class DistributionStatus {
+ DISTRIBUTION_NOT_APPROVED = 'DISTRIBUTION_NOT_APPROVED';
+ DISTRIBUTION_APPROVED = 'DISTRIBUTION_APPROVED';
+ DISTRIBUTED = 'DISTRIBUTED';
+ DISTRIBUTION_REJECTED = 'DISTRIBUTION_REJECTED';
+}
+
+export class ArtifactGroupType {
+ static DEPLOYMENT = "DEPLOYMENT";
+ static INFORMATION = "INFORMATIONAL";
+ static SERVICE_API = "SERVICE_API";
+}
+
+export class ArtifactType {
+ static HEAT = "HEAT";
+ static HEAT_VOL = "HEAT_VOL";
+ static HEAT_NET = "HEAT_NET";
+ static VF_LICENSE = "VF_LICENSE";
+ static VENDOR_LICENSE = "VENDOR_LICENSE";
+ static THIRD_PARTY_RESERVED_TYPES = {
+ WORKFLOW: "WORKFLOW",
+ NETWORK_CALL_FLOW: "NETWORK_CALL_FLOW",
+ 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"
+ };
+ static TOSCA = {TOSCA_TEMPLATE: "TOSCA_TEMPLATE", TOSCA_CSAR: "TOSCA_CSAR"};
+}
+
+export class SEVERITY {
+ public static DEBUG = 'DEBUG';
+ public static INFO = 'INFO';
+ public static WARNING = 'WARNING';
+ public static ERROR = 'ERROR';
+}
+
+export class PROPERTY_TYPES {
+ public static STRING = 'string';
+ public static INTEGER = 'integer';
+ public static FLOAT = 'float';
+ public static BOOLEAN = 'boolean';
+ public static JSON = 'json';
+ public static MAP = 'map';
+ public static LIST = 'list';
+}
+
+export class SOURCES {
+ public static A_AND_AI = 'A&AI';
+ public static ORDER = 'Order';
+ public static RUNTIME = 'Runtime';
+}
+
+export class PROPERTY_DATA {
+ public static TYPES = [PROPERTY_TYPES.STRING, PROPERTY_TYPES.INTEGER, PROPERTY_TYPES.FLOAT, PROPERTY_TYPES.BOOLEAN, PROPERTY_TYPES.JSON, PROPERTY_TYPES.LIST, PROPERTY_TYPES.MAP];
+ public static SIMPLE_TYPES = [PROPERTY_TYPES.STRING, PROPERTY_TYPES.INTEGER, PROPERTY_TYPES.FLOAT, PROPERTY_TYPES.BOOLEAN, PROPERTY_TYPES.JSON];
+ public static ROOT_DATA_TYPE = "tosca.datatypes.Root";
+ public static SOURCES = [SOURCES.A_AND_AI, SOURCES.ORDER, SOURCES.RUNTIME];
+}
+
+export class PROPERTY_VALUE_CONSTRAINTS {
+ public static MAX_LENGTH = 100;
+ public static JSON_MAX_LENGTH = 4096;
+}
+
+export class Role {
+ public static ADMIN = 'ADMIN';
+ public static DESIGNER = 'DESIGNER';
+ public static PRODUCT_STRATEGIST = 'PRODUCT_STRATEGIST';
+ public static PRODUCT_MANAGER = 'PRODUCT_MANAGER';
+ public static TESTER = 'TESTER';
+ public static OPS = 'OPS';
+ public static GOVERNOR = 'GOVERNOR';
+}
+
+export enum FormState{
+ CREATE,
+ UPDATE,
+ IMPORT,
+ VIEW
+}
+
+export class WorkspaceMode {
+ public static CREATE = 'create';
+ public static EDIT = 'edit';
+ public static IMPORT = 'import';
+ public static VIEW = 'view';
+}
+
+export class ImagesUrl {
+ public static RESOURCE_ICONS = '/assets/styles/images/resource-icons/';
+ public static SERVICE_ICONS = '/assets/styles/images/service-icons/';
+ public static SELECTED_UCPE_INSTANCE = '/assets/styles/images/resource-icons/selectedUcpeInstance.png';
+ public static SELECTED_CP_INSTANCE = '/assets/styles/images/resource-icons/selectedCPInstance.png';
+ public static SELECTED_VL_INSTANCE = '/assets/styles/images/resource-icons/selectedVLInstance.png';
+ public static CANVAS_PLUS_ICON = '/assets/styles/images/resource-icons/canvasPlusIcon.png';
+ public static MODULE_ICON = '/assets/styles/images/resource-icons/module.png';
+ public static OPEN_MODULE_ICON = '/assets/styles/images/resource-icons/openModule.png';
+ public static OPEN_MODULE_HOVER_ICON = '/assets/styles/images/resource-icons/openModuleHover.png';
+ public static CLOSE_MODULE_ICON = '/assets/styles/images/resource-icons/closeModule.png';
+ public static CLOSE_MODULE_HOVER_ICON = '/assets/styles/images/resource-icons/closeModuleHover.png';
+}
+
+export class ModalType {
+ static STANDARD = 'standard';
+ static ERROR = 'error';
+ static ALERT = 'alert';
+}
+
+export class GraphColors {
+ public static NOT_CERTIFIED_LINK = 'rgb(218,31,61)';
+ public static VL_LINK = 'rgb(216,216,216)';
+ public static ACTIVE_LINK = '#30bdf2';
+ public static BASE_LINK = 'rgb(55,55,55)';
+ public static NODE_BACKGROUND_COLOR = 'rgba(46, 162, 157, 0.24)';
+ public static NODE_SHADOW_COLOR = 'rgba(198, 230, 228, 0.7)';
+ public static NODE_OVERLAPPING_BACKGROUND_COLOR = 'rgba(179, 10, 60, 0.24)';
+ public static NODE_OVERLAPPING_SHADOW_COLOR = 'rgba(236, 194, 206, 0.7)';
+ public static NODE_UCPE_CP = '#9063cd';
+ public static NODE_UCPE = '#fbfbfb';
+ public static NODE_SELECTED_BORDER_COLOR = '#30bdf2';
+}
+export class GraphTransactionLogText {
+ public static REMOVE_TEMP_LINK = "remove tempLink";
+ public static DELETE_LINK = "delete link";
+ public static ADD_LINK = "delete link";
+ public static ADD_NODE = "adding node";
+}
+
+export class GraphUIObjects {
+ public static LINK_MENU_HEIGHT = 420;
+ public static TOP_HEADER_HEIGHT = 200;
+ public static TOOLTIP_OFFSET_X = 50;
+ public static TOOLTIP_OFFSET_Y = 145;
+ public static TOOLTIP_LINK_OFFSET_X = 35;
+ public static TOOLTIP_LINK_OFFSET_Y = 75;
+ public static MENU_LINK_VL_HEIGHT_OFFSET = 250;
+ public static MENU_LINK_VL_WIDTH_OFFSET = 200;
+ public static MENU_LINK_SIMPLE_HEIGHT_OFFSET = 180;
+ public static MENU_LINK_SIMPLE_WIDTH_OFFSET = 130;
+ public static DIAGRAM_RIGHT_WIDTH_OFFSET = 248;
+ public static DIAGRAM_HEADER_OFFSET = 103;
+ public static DIAGRAM_PALETTE_WIDTH_OFFSET = 247;
+ // public static COMPOSITION_HEADER_OFFSET = 50;
+ // public static COMPOSITION_NODE_MENU_WIDTH = 230;
+ // public static COMPOSITION_NODE_MENU_HEIGHT = 200;
+ // public static COMPOSITION_RIGHT_PANEL_OFFSET = 300;
+}
+
+
+export class States {
+ public static WORKSPACE_GENERAL = 'workspace.general';
+ public static WORKSPACE_ICONS = 'workspace.icons';
+ public static WORKSPACE_ACTIVITY_LOG = 'workspace.activity_log';
+ public static WORKSPACE_DEPLOYMENT_ARTIFACTS = 'workspace.deployment_artifacts';
+ public static WORKSPACE_PROPERTIES = 'workspace.properties';
+ public static WORKSPACE_SERVICE_INPUTS = 'workspace.service_inputs';
+ public static WORKSPACE_RESOURCE_INPUTS = 'workspace.resource_inputs';
+ public static WORKSPACE_ATTRIBUTES = 'workspace.attributes';
+ public static WORKSPACE_HIERARCHY = 'workspace.hierarchy';
+ public static WORKSPACE_INFORMATION_ARTIFACTS = 'workspace.information_artifacts';
+ public static WORKSPACE_TOSCA_ARTIFACTS = 'workspace.tosca_artifacts';
+ public static WORKSPACE_COMPOSITION = 'workspace.composition';
+ public static WORKSPACE_NETWORK_CALL_FLOW = 'workspace.network_call_flow';
+ public static WORKSPACE_MANAGEMENT_WORKFLOW = 'workspace.management_workflow';
+ public static WORKSPACE_DEPLOYMENT = 'workspace.deployment';
+ public static WORKSPACE_DISTRIBUTION = 'workspace.distribution';
+ public static WORKSPACE_PROPERTIES_ASSIGNMENT = 'workspace.properties_assignment';
+ public static WORKSPACE_REQUIREMENTS_AND_CAPABILITIES = 'workspace.reqAndCap';
+ public static WORKSPACE_NG2 = 'workspace.ng2';
+}
+
+export class EVENTS {
+ static RESOURCE_LEFT_PALETTE_UPDATE_EVENT = "resourceLeftPanelUpdateEvent";
+ static SERVICE_LEFT_PALETTE_UPDATE_EVENT = "serviceLeftPanelUpdateEvent";
+ static PRODUCT_LEFT_PALETTE_UPDATE_EVENT = "productLeftPanelUdateEvent";
+ static VL_LEFT_PALETTE_UPDATE_EVENT = "vlLeftPanelUdateEvent";
+ static ON_CSAR_LOADING = "onCsarLoading";
+ static DOWNLOAD_ARTIFACT_FINISH_EVENT = "downloadArtifactFinishEvent";
+ static ON_WORKSPACE_SAVE_BUTTON_CLICK = "onWorkspaceSaveButtonClick";
+ static ON_WORKSPACE_SAVE_BUTTON_SUCCESS = "onWorkspaceSaveButtonSuccess";
+ static ON_WORKSPACE_SAVE_BUTTON_ERROR = "onWorkspaceSaveButtonError";
+
+ //Loader events
+ static SHOW_LOADER_EVENT = "showLoaderEvent";
+ static HIDE_LOADER_EVENT = "hideLoaderEvent";
+}
+
+
+export class UNIQUE_GROUP_PROPERTIES_NAME {
+ public static MIN_VF_MODULE_INSTANCES = 'min_vf_module_instances';
+ public static MAX_VF_MODULE_INSTANCES = 'max_vf_module_instances';
+ public static INITIAL_COUNT = 'initial_count';
+ public static IS_BASE = 'isBase';
+ public static VF_MODULE_TYPE = 'vf_module_type';
+ public static VF_MODULE_LABEL = 'vf_module_label';
+ public static VF_MODULE_DESCRIPTION = 'vf_module_description';
+ public static VOLUME_GROUP = 'volume_group';
+}
+
+
+export class GRAPH_EVENTS {
+ static ON_COMPOSITION_GRAPH_DATA_LOADED = 'onCompositionGraphDataLoaded';
+ static ON_DEPLOYMENT_GRAPH_DATA_LOADED = 'onDeploymentGraphDataLoaded';
+ static ON_NODE_SELECTED = "onNodeSelected";
+ static ON_GRAPH_BACKGROUND_CLICKED = "onGraphBackgroundClicked";
+ static ON_PALETTE_COMPONENT_HOVER_IN = 'onPaletteComponentHoverIn';
+ static ON_PALETTE_COMPONENT_HOVER_OUT = 'onPaletteComponentHoverOut';
+ static ON_PALETTE_COMPONENT_DRAG_START = 'onPaletteComponentDragStart';
+ static ON_PALETTE_COMPONENT_DRAG_ACTION = 'onPaletteComponentDragAction';
+ static ON_COMPONENT_INSTANCE_NAME_CHANGED = 'onComponentInstanceNameChanged';
+ static ON_DELETE_COMPONENT_INSTANCE = 'onDeleteComponentInstance';
+ static ON_DELETE_MULTIPLE_COMPONENTS = 'onDeleteMultipleComponents';
+ static ON_DELETE_EDGE = 'onDeleteEdge';
+ static ON_INSERT_NODE_TO_UCPE = 'onInsertNodeToUCPE';
+ static ON_REMOVE_NODE_FROM_UCPE = 'onRemoveNodeFromUCPE';
+ static ON_VERSION_CHANGED = 'onVersionChanged';
+ static ON_CREATE_COMPONENT_INSTANCE = 'onCreateComponentInstance';
+}
+
+
+export class COMPONENT_FIELDS {
+ static COMPONENT_INSTANCES_PROPERTIES = "componentInstancesProperties";
+ static COMPONENT_INSTANCES_ATTRIBUTES = "componentInstancesAttributes";
+ static COMPONENT_ATTRIBUTES = "attributes";
+ static COMPONENT_INSTANCES = "componentInstances";
+ static COMPONENT_INSTANCES_RELATION = "componentInstancesRelations";
+ static COMPONENT_INPUTS = "inputs";
+ static COMPONENT_METADATA = "metadata";
+ static COMPONENT_DEPLOYMENT_ARTIFACTS = "deploymentArtifacts";
+ static COMPONENT_INFORMATIONAL_ARTIFACTS = "artifacts";
+ static COMPONENT_PROPERTIES = "properties";
+ static COMPONENT_CAPABILITIES = "capabilities";
+ static COMPONENT_REQUIREMENTS = "requirements";
+ static COMPONENT_TOSCA_ARTIFACTS = "toscaArtifacts";
+ static COMPONENT_GROUPS = "groups";
+
+}
+export class API_QUERY_PARAMS {
+ static INCLUDE = "include";
+}
diff --git a/catalog-ui/src/app/utils/dictionary/dictionary.ts b/catalog-ui/src/app/utils/dictionary/dictionary.ts
new file mode 100644
index 0000000000..fd2a028c34
--- /dev/null
+++ b/catalog-ui/src/app/utils/dictionary/dictionary.ts
@@ -0,0 +1,235 @@
+/**
+
+ This code was copy from collections.ts lib
+ https://github.com/basarat/typescript-collections
+ **/
+'use strict';
+
+// Used internally by dictionary
+interface IDictionaryPair<K, V> {
+ key:K;
+ value:V;
+}
+
+export class Dictionary<K, V> {
+
+ /**
+ * Object holding the key-value pairs.
+ * @type {Object}
+ * @private
+ */
+ private table:{ [key:string]:IDictionaryPair<K, V> };
+ //: [key: K] will not work since indices can only by strings in javascript and typescript enforces this.
+
+ /**
+ * Number of elements in the list.
+ * @type {number}
+ * @private
+ */
+ private nElements:number;
+
+ /**
+ * Function used to convert keys to strings.
+ * @type {function(Object):string}
+ * @private
+ */
+ private toStr:(key:K) => string;
+
+
+ /**
+ * Creates an empty dictionary.
+ * @class <p>Dictionaries map keys to values; each key can map to at most one value.
+ * This implementation accepts any kind of objects as keys.</p>
+ *
+ * <p>If the keys are custom objects a function which converts keys to unique
+ * strings must be provided. Example:</p>
+ * <pre>
+ * function petToString(pet) {
+ * return pet.name;
+ * }
+ * </pre>
+ * @constructor
+ * @param {function(Object):string=} toStrFunction optional function used
+ * to convert keys to strings. If the keys aren"t strings or if toString()
+ * is not appropriate, a custom function which receives a key and returns a
+ * unique string must be provided.
+ */
+ constructor(toStrFunction?:(key:K) => string) {
+ this.table = {};
+ this.nElements = 0;
+ this.toStr = toStrFunction || this.defaultToString;
+ }
+
+
+ /**
+ copy from angular.js isUndefined
+ */
+ private isUndefined = (value:any):boolean => {
+ return typeof value === 'undefined';
+ }
+
+ defaultToString = (item:any):string => {
+ return item.toString();
+ }
+
+ /**
+ * Returns the value to which this dictionary maps the specified key.
+ * Returns undefined if this dictionary contains no mapping for this key.
+ * @param {Object} key key whose associated value is to be returned.
+ * @return {*} the value to which this dictionary maps the specified key or
+ * undefined if the map contains no mapping for this key.
+ */
+ getValue = (key:K):V => {
+ let pair:IDictionaryPair<K, V> = this.table[this.toStr(key)];
+ if (this.isUndefined(pair)) {
+ return undefined;
+ }
+ return pair.value;
+ }
+
+
+ /**
+ * Associates the specified value with the specified key in this dictionary.
+ * If the dictionary previously contained a mapping for this key, the old
+ * value is replaced by the specified value.
+ * @param {Object} key key with which the specified value is to be
+ * associated.
+ * @param {Object} value value to be associated with the specified key.
+ * @return {*} previous value associated with the specified key, or undefined if
+ * there was no mapping for the key or if the key/value are undefined.
+ */
+ setValue = (key:K, value:V):V => {
+
+ if (this.isUndefined(key) || this.isUndefined(value)) {
+ return undefined;
+ }
+
+ let ret:V;
+ let k = this.toStr(key);
+ let previousElement:IDictionaryPair<K, V> = this.table[k];
+ if (this.isUndefined(previousElement)) {
+ this.nElements++;
+ ret = undefined;
+ } else {
+ ret = previousElement.value;
+ }
+ this.table[k] = {
+ key: key,
+ value: value
+ };
+ return ret;
+ }
+
+ /**
+ * Removes the mapping for this key from this dictionary if it is present.
+ * @param {Object} key key whose mapping is to be removed from the
+ * dictionary.
+ * @return {*} previous value associated with specified key, or undefined if
+ * there was no mapping for key.
+ */
+ remove = (key:K):V => {
+ let k = this.toStr(key);
+ let previousElement:IDictionaryPair<K, V> = this.table[k];
+ if (!this.isUndefined(previousElement)) {
+ delete this.table[k];
+ this.nElements--;
+ return previousElement.value;
+ }
+ return undefined;
+ }
+
+ /**
+ * Returns an array containing all of the keys in this dictionary.
+ * @return {Array} an array containing all of the keys in this dictionary.
+ */
+ keys = ():K[] => {
+ let array:K[] = [];
+ for (let name in this.table) {
+ if (this.table.hasOwnProperty(name)) {
+ let pair:IDictionaryPair<K, V> = this.table[name];
+ array.push(pair.key);
+ }
+ }
+ return array;
+ }
+
+ /**
+ * Returns an array containing all of the values in this dictionary.
+ * @return {Array} an array containing all of the values in this dictionary.
+ */
+ values = ():V[] => {
+ let array:V[] = [];
+ for (let name in this.table) {
+ if (this.table.hasOwnProperty(name)) {
+ let pair:IDictionaryPair<K, V> = this.table[name];
+ array.push(pair.value);
+ }
+ }
+ return array;
+ }
+
+ /**
+ * Executes the provided function once for each key-value pair
+ * present in this dictionary.
+ * @param {function(Object,Object):*} callback function to execute, it is
+ * invoked with two arguments: key and value. To break the iteration you can
+ * optionally return false.
+ */
+ forEach = (callback:(key:K, value:V) => any):void => {
+ for (let name in this.table) {
+ if (this.table.hasOwnProperty(name)) {
+ let pair:IDictionaryPair<K, V> = this.table[name];
+ let ret = callback(pair.key, pair.value);
+ if (ret === false) {
+ return;
+ }
+ }
+ }
+ }
+
+ /**
+ * Returns true if this dictionary contains a mapping for the specified key.
+ * @param {Object} key key whose presence in this dictionary is to be
+ * tested.
+ * @return {boolean} true if this dictionary contains a mapping for the
+ * specified key.
+ */
+ containsKey = (key:K):boolean => {
+ return !this.isUndefined(this.getValue(key));
+ }
+
+ /**
+ * Removes all mappings from this dictionary.
+ * @this {Dictionary}
+ */
+ clear = () => {
+
+ this.table = {};
+ this.nElements = 0;
+ }
+
+ /**
+ * Returns the number of keys in this dictionary.
+ * @return {number} the number of key-value mappings in this dictionary.
+ */
+ size = ():number => {
+ return this.nElements;
+ }
+
+ /**
+ * Returns true if this dictionary contains no mappings.
+ * @return {boolean} true if this dictionary contains no mappings.
+ */
+ isEmpty = ():boolean => {
+ return this.nElements <= 0;
+ }
+
+ toString = ():string => {
+ let toret = "{";
+ this.forEach((k, v) => {
+ toret = toret + "\n\t" + k.toString() + " : " + v.toString();
+ });
+ return toret + "\n}";
+ }
+} // End of dictionary
+
diff --git a/catalog-ui/src/app/utils/file-utils.ts b/catalog-ui/src/app/utils/file-utils.ts
new file mode 100644
index 0000000000..d8c18229c3
--- /dev/null
+++ b/catalog-ui/src/app/utils/file-utils.ts
@@ -0,0 +1,51 @@
+export class FileUtils {
+
+ static '$inject' = [
+ '$window'
+ ];
+
+ constructor(private $window:any) {
+ }
+
+ public byteCharactersToBlob = (byteCharacters, contentType):any => {
+ contentType = contentType || '';
+ let sliceSize = 1024;
+ let bytesLength = byteCharacters.length;
+ let slicesCount = Math.ceil(bytesLength / sliceSize);
+ let byteArrays = new Array(slicesCount);
+
+ for (let sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
+ let begin = sliceIndex * sliceSize;
+ let end = Math.min(begin + sliceSize, bytesLength);
+
+ let bytes = new Array(end - begin);
+ for (let offset = begin, i = 0; offset < end; ++i, ++offset) {
+ bytes[i] = byteCharacters[offset].charCodeAt(0);
+ }
+ byteArrays[sliceIndex] = new Uint8Array(bytes);
+ }
+ return new Blob(byteArrays, {type: contentType});
+ };
+
+ public base64toBlob = (base64Data, contentType):any => {
+ let byteCharacters = atob(base64Data);
+ return this.byteCharactersToBlob(byteCharacters, contentType);
+ };
+
+ public downloadFile = (blob, fileName):void=> {
+ let url = this.$window.URL.createObjectURL(blob);
+ let downloadLink = document.createElement("a");
+
+ downloadLink.setAttribute('href', url);
+ downloadLink.setAttribute('download', fileName);
+ document.body.appendChild(downloadLink);
+
+ var clickEvent = new MouseEvent("click", {
+ "view": window,
+ "bubbles": true,
+ "cancelable": true
+ });
+ downloadLink.dispatchEvent(clickEvent);
+
+ }
+}
diff --git a/catalog-ui/src/app/utils/functions.ts b/catalog-ui/src/app/utils/functions.ts
new file mode 100644
index 0000000000..24f8008393
--- /dev/null
+++ b/catalog-ui/src/app/utils/functions.ts
@@ -0,0 +1,35 @@
+export class QueueUtils {
+
+ private executionQueue:any;
+
+ constructor(private $q:ng.IQService) {
+ this.executionQueue = this.getDummyPromise();
+ }
+
+
+ private getDummyPromise = ():ng.IPromise<boolean> => {
+ let deferred:ng.IDeferred<boolean> = this.$q.defer();
+ deferred.resolve(true);
+ return deferred.promise;
+ };
+
+
+ private addMethodToQueue = (runMe:Function):void => {
+ this.executionQueue = this.executionQueue.then(runMe, runMe);
+ };
+
+ addNonBlockingUIAction = (update:Function, releaseUIcallBack:Function):void => {
+ releaseUIcallBack();
+ this.addMethodToQueue(update);
+ };
+
+ // The Method call is responsible for releasing the UI
+ addBlockingUIAction = (blockingServerRequest:Function):void => {
+ this.addMethodToQueue(blockingServerRequest);
+ };
+
+ addBlockingUIActionWithReleaseCallback = (blockingServerRequest:Function, releaseUIcallBack:Function):void=> {
+ this.addMethodToQueue(blockingServerRequest);
+ this.addMethodToQueue(releaseUIcallBack);
+ };
+}
diff --git a/catalog-ui/src/app/utils/menu-handler.ts b/catalog-ui/src/app/utils/menu-handler.ts
new file mode 100644
index 0000000000..1dc5a203e2
--- /dev/null
+++ b/catalog-ui/src/app/utils/menu-handler.ts
@@ -0,0 +1,125 @@
+'use strict';
+import {WorkspaceMode, ComponentState} from "./constants";
+import {IAppConfigurtaion, IAppMenu, Component} from "../models";
+import {ComponentFactory} from "./component-factory";
+import {ModalsHandler} from "./modals-handler";
+
+export class MenuItem {
+ text:string;
+ callback:(...args:Array<any>) => ng.IPromise<boolean>;
+ state:string;
+ action:string;
+ params:Array<any>;
+ isDisabled:boolean;
+ disabledRoles:Array<string>;
+ blockedForTypes:Array<string>; // This item will not be shown for specific components types.
+
+ //TODO check if needed
+ alertModal:string;
+ conformanceLevelModal: boolean; // Call validateConformanceLevel API and shows conformanceLevelModal if necessary, then continue with action or invokes another action
+ confirmationModal:string; // Open confirmation modal (user should select "OK" or "Cancel"), and continue with the action.
+ emailModal:string; // Open email modal (user should fill email details), and continue with the action.
+ url:string; // Data added to menu item, in case the function need to use it, example: for function "changeLifecycleState", I need to pass also the state "CHECKOUT" that I want the state to change to.
+
+
+ constructor(text:string, callback:(...args:Array<any>) => ng.IPromise<boolean>, state:string, action:string, params?:Array<any>, blockedForTypes?:Array<string>) {
+ this.text = text;
+ this.callback = callback;
+ this.state = state;
+ this.action = action;
+ this.params = params;
+ this.blockedForTypes = blockedForTypes;
+ }
+}
+
+export class MenuItemGroup {
+ selectedIndex:number;
+ menuItems:Array<MenuItem>;
+ itemClick:boolean;
+
+ constructor(selectedIndex?:number, menuItems?:Array<MenuItem>, itemClick?:boolean) {
+ this.selectedIndex = selectedIndex;
+ this.menuItems = menuItems;
+ this.itemClick = itemClick;
+ }
+
+ public updateSelectedMenuItemText(newText:string) {
+ this.menuItems[this.selectedIndex].text = newText;
+ }
+}
+
+
+export class MenuHandler {
+
+ static '$inject' = [
+ 'sdcConfig',
+ 'sdcMenu',
+ 'ComponentFactory',
+ '$filter',
+ 'ModalsHandler',
+ '$state',
+ '$q'
+ ];
+
+ constructor(private sdcConfig:IAppConfigurtaion,
+ private sdcMenu:IAppMenu,
+ private ComponentFactory:ComponentFactory,
+ private $filter:ng.IFilterService,
+ private ModalsHandler:ModalsHandler,
+ private $state:ng.ui.IStateService,
+ private $q:ng.IQService) {
+
+ }
+
+
+ generateBreadcrumbsModelFromComponents = (components:Array<Component>, selected:Component):MenuItemGroup => {
+ let result = new MenuItemGroup(0, [], false);
+ if (components) {
+
+ // 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 (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 (undefined == selectedItem) {
+ selectedItem = _.find(components, (item:Component) => {
+ return item.name === selected.name;
+ });
+ }
+
+ result.selectedIndex = components.indexOf(selectedItem);
+ components[result.selectedIndex] = selected;
+ let clickItemCallback = (component:Component):ng.IPromise<boolean> => {
+ this.$state.go('workspace.general', {
+ id: component.uniqueId,
+ type: component.componentType.toLowerCase(),
+ mode: WorkspaceMode.VIEW
+ });
+ return this.$q.when(true);
+ };
+
+ components.forEach((component:Component) => {
+ let menuItem = new MenuItem(
+ // component.name,
+ component.getComponentSubType() + ': ' + this.$filter('resourceName')(component.name),
+ clickItemCallback,
+ null,
+ null,
+ [component]
+ );
+ // menuItem.text = component.name;
+ result.menuItems.push(menuItem);
+ });
+ }
+ return result;
+ };
+}
diff --git a/catalog-ui/src/app/utils/modals-handler.ts b/catalog-ui/src/app/utils/modals-handler.ts
new file mode 100644
index 0000000000..fe864cb658
--- /dev/null
+++ b/catalog-ui/src/app/utils/modals-handler.ts
@@ -0,0 +1,389 @@
+import {PropertyModel, Component, ArtifactModel, Distribution, InputModel, DisplayModule, InputPropertyBase} from "../models";
+import {IEmailModalModel} from "../view-models/modals/email-modal/email-modal-view-model";
+import {IClientMessageModalModel} from "../view-models/modals/message-modal/message-client-modal/client-message-modal-view-model";
+import {IServerMessageModalModel} from "../view-models/modals/message-modal/message-server-modal/server-message-modal-view-model";
+import {IConfirmationModalModel} from "../view-models/modals/confirmation-modal/confirmation-modal-view-model";
+import {ModalType} from "./constants";
+import {AttributeModel} from "../models/attributes";
+
+export interface IModalsHandler {
+
+
+ openDistributionStatusModal (distribution:Distribution, status:string, component:Component):ng.IPromise<any>;
+ openConfirmationModal (title:string, message:string, showComment:boolean, size?:string):ng.IPromise<any>;
+ openAlertModal (title:string, message:string, size?:string):ng.IPromise<any>;
+ openEmailModal(emailModel:IEmailModalModel):ng.IPromise<any>;
+ openServerMessageModal(data:IServerMessageModalModel):ng.IPromise<any>;
+ openClientMessageModal(data:IClientMessageModalModel):ng.IPromise<ng.ui.bootstrap.IModalServiceInstance>;
+ openArtifactModal(artifact:ArtifactModel, component:Component):ng.IPromise<any>;
+ openEditPropertyModal(property:PropertyModel, component:Component, filteredProperties:Array<PropertyModel>, isPropertyOwnValue:boolean):ng.IPromise<any>;
+}
+
+export class ModalsHandler implements IModalsHandler {
+
+ static '$inject' = [
+ '$uibModal',
+ '$q'
+ ];
+
+ constructor(private $uibModal:ng.ui.bootstrap.IModalService,
+ private $q:ng.IQService) {
+ }
+
+
+
+
+ openDistributionStatusModal = (distribution:Distribution, status:string, component:Component):ng.IPromise<any> => {
+ let deferred = this.$q.defer();
+ let modalOptions:ng.ui.bootstrap.IModalSettings = {
+ templateUrl: '../view-models/workspace/tabs/distribution/disribution-status-modal/disribution-status-modal-view.html',
+ controller: 'Sdc.ViewModels.DistributionStatusModalViewModel',
+ size: 'sdc-xl',
+ backdrop: 'static',
+ resolve: {
+ data: ():any => {
+ return {
+ 'distribution': distribution,
+ 'status': status,
+ 'component': component
+ };
+ }
+ }
+ };
+ let modalInstance:ng.ui.bootstrap.IModalServiceInstance = this.$uibModal.open(modalOptions);
+ deferred.resolve(modalInstance.result);
+ return deferred.promise;
+ };
+
+
+ openAlertModal = (title:string, message:string, size?:string):ng.IPromise<any> => {
+ return this.openConfirmationModalBase(title, message, false, ModalType.ALERT, size);
+ };
+
+ openConfirmationModal = (title:string, message:string, showComment:boolean, size?:string):ng.IPromise<any> => {
+ return this.openConfirmationModalBase(title, message, showComment, ModalType.STANDARD, size);
+ };
+
+ private openConfirmationModalBase = (title:string, message:string, showComment:boolean, type:ModalType, size?:string):ng.IPromise<any> => {
+ let deferred = this.$q.defer();
+ let modalOptions:ng.ui.bootstrap.IModalSettings = {
+ templateUrl: '../view-models/modals/confirmation-modal/confirmation-modal-view.html',
+ controller: 'Sdc.ViewModels.ConfirmationModalViewModel',
+ size: size ? size : 'sdc-sm',
+ backdrop: 'static',
+ resolve: {
+ confirmationModalModel: ():IConfirmationModalModel => {
+ let model:IConfirmationModalModel = {
+ title: title,
+ message: message,
+ showComment: showComment,
+ type: type
+ };
+ return model;
+ }
+ }
+ };
+
+ let modalInstance:ng.ui.bootstrap.IModalServiceInstance = this.$uibModal.open(modalOptions);
+ deferred.resolve(modalInstance.result);
+ return deferred.promise;
+ };
+
+ openEmailModal = (emailModel:IEmailModalModel):ng.IPromise<any> => {
+
+ let deferred = this.$q.defer();
+ let modalOptions:ng.ui.bootstrap.IModalSettings = {
+ templateUrl: '../view-models/modals/email-modal/email-modal-view.html',
+ controller: 'Sdc.ViewModels.EmailModalViewModel',
+ size: 'sdc-sm',
+ backdrop: 'static',
+ resolve: {
+ emailModalModel: ():IEmailModalModel => {
+ return emailModel;
+ }
+ }
+ };
+ let modalInstance:ng.ui.bootstrap.IModalServiceInstance = this.$uibModal.open(modalOptions);
+ deferred.resolve(modalInstance.result);
+ return deferred.promise;
+
+ };
+
+ openServerMessageModal = (data:IServerMessageModalModel):ng.IPromise<any> => {
+ let deferred = this.$q.defer();
+ let modalOptions:ng.ui.bootstrap.IModalSettings = {
+ templateUrl: '../view-models/modals/message-modal/message-server-modal/server-message-modal-view.html',
+ controller: 'Sdc.ViewModels.ServerMessageModalViewModel',
+ size: 'sdc-sm',
+ backdrop: 'static',
+ resolve: {
+ serverMessageModalModel: ():IServerMessageModalModel => {
+ return data;
+ }
+ }
+ };
+
+ let modalInstance:ng.ui.bootstrap.IModalServiceInstance = this.$uibModal.open(modalOptions);
+ deferred.resolve(modalInstance.result);
+ return deferred.promise;
+ };
+
+ openClientMessageModal = (data:IClientMessageModalModel):ng.IPromise<any> => {
+ let deferred = this.$q.defer();
+ let modalOptions:ng.ui.bootstrap.IModalSettings = {
+ templateUrl: '../view-models/modals/message-modal/message-client-modal/client-message-modal-view.html',
+ controller: 'Sdc.ViewModels.ClientMessageModalViewModel',
+ size: 'sdc-sm',
+ backdrop: 'static',
+ resolve: {
+ clientMessageModalModel: ():IClientMessageModalModel => {
+ return data;
+ }
+ }
+ };
+ let modalInstance:ng.ui.bootstrap.IModalServiceInstance = this.$uibModal.open(modalOptions);
+ deferred.resolve(modalInstance);
+ return deferred.promise;
+ };
+
+ openOnboadrdingModal = (okButtonText:string, currentCsarUUID?:string):ng.IPromise<any> => {
+ let deferred = this.$q.defer();
+ let modalOptions:ng.ui.bootstrap.IModalSettings = {
+ templateUrl: '../view-models/modals/onboarding-modal/onboarding-modal-view.html',
+ controller: 'Sdc.ViewModels.OnboardingModalViewModel',
+ size: 'sdc-xl',
+ backdrop: 'static',
+ resolve: {
+ okButtonText: ():string=> {
+ return okButtonText;
+ },
+ currentCsarUUID: ():string=> {
+ return currentCsarUUID || null;
+ }
+ }
+ };
+ let modalInstance:ng.ui.bootstrap.IModalServiceInstance = this.$uibModal.open(modalOptions);
+ deferred.resolve(modalInstance.result);
+ return deferred.promise;
+ };
+
+ openEditEnvParametersModal = (artifactResource:ArtifactModel, component?:Component):ng.IPromise<any> => {
+ let deferred = this.$q.defer();
+ let modalOptions:ng.ui.bootstrap.IModalSettings = {
+ templateUrl: '../view-models/forms/env-parameters-form/env-parameters-form.html',
+ controller: 'Sdc.ViewModels.EnvParametersFormViewModel',
+ size: 'sdc-xl',
+ backdrop: 'static',
+ resolve: {
+ artifact: ():ArtifactModel => {
+ return artifactResource;
+ },
+ component: ():Component => {
+ return component;
+ }
+ }
+ };
+ let modalInstance:ng.ui.bootstrap.IModalServiceInstance = this.$uibModal.open(modalOptions);
+ deferred.resolve(modalInstance.result);
+ return deferred.promise;
+ };
+
+ openEditInputValueModal = (input:InputModel):ng.IPromise<any> => {
+ let deferred = this.$q.defer();
+ let modalOptions:ng.ui.bootstrap.IModalSettings = {
+ templateUrl: '../view-models/forms/input-form/input-form-view.html',
+ controller: 'Sdc.ViewModels.InputFormViewModel',
+ size: 'sdc-md',
+ backdrop: 'static',
+ resolve: {
+ input: ():InputModel => {
+ return input;
+ }
+ }
+ };
+ let modalInstance:ng.ui.bootstrap.IModalServiceInstance = this.$uibModal.open(modalOptions);
+ deferred.resolve(modalInstance.result);
+ return deferred.promise;
+ };
+
+ openArtifactModal = (artifact:ArtifactModel, component:Component):ng.IPromise<any> => {
+ let deferred = this.$q.defer();
+
+ let modalOptions:ng.ui.bootstrap.IModalSettings = {
+ templateUrl: '../view-models/forms/artifact-form/artifact-form-view.html',
+ controller: 'Sdc.ViewModels.ArtifactResourceFormViewModel',
+ size: 'sdc-md',
+ backdrop: 'static',
+ keyboard: false,
+ resolve: {
+ artifact: ():ArtifactModel => {
+ return artifact;
+ },
+ component: ():Component => {
+ return component;
+ }
+ }
+ };
+
+ let modalInstance:ng.ui.bootstrap.IModalServiceInstance = this.$uibModal.open(modalOptions);
+ deferred.resolve(modalInstance.result);
+ return deferred.promise;
+ };
+
+
+ /**
+ *
+ * This function openes up the edit property modal
+ *
+ * @param property - the property to edit
+ * @param component - the component who is the owner of the property
+ * @param filteredProperties - the filtered properties list to scroll between in the edit modal
+ * @param isPropertyValueOwner - boolean telling if the component is eligible of editing the property
+ * @returns {IPromise<T>} - Promise telling if the modal has opened or not
+ */
+ openEditPropertyModal = (property:PropertyModel, component:Component, filteredProperties:Array<PropertyModel>, isPropertyValueOwner:boolean):ng.IPromise<any> => {
+ let deferred = this.$q.defer();
+
+ let modalOptions:ng.ui.bootstrap.IModalSettings = {
+ templateUrl: '../view-models/forms/property-forms/component-property-form/property-form-view.html',
+ controller: 'Sdc.ViewModels.PropertyFormViewModel',
+ size: 'sdc-l',
+ backdrop: 'static',
+ keyboard: false,
+ resolve: {
+ property: ():PropertyModel => {
+ return property;
+ },
+ component: ():Component => {
+ return <Component> component;
+ },
+ filteredProperties: ():Array<PropertyModel> => {
+ return filteredProperties;
+ },
+ isPropertyValueOwner: ():boolean => {
+ return isPropertyValueOwner;
+ }
+ }
+ };
+
+ let modalInstance:ng.ui.bootstrap.IModalServiceInstance = this.$uibModal.open(modalOptions);
+ deferred.resolve(modalInstance.result);
+ return deferred.promise;
+ };
+
+
+ openEditModulePropertyModal = (property:PropertyModel, component:Component, selectedModule:DisplayModule):ng.IPromise<any> => {
+ let deferred = this.$q.defer();
+
+ let modalOptions:ng.ui.bootstrap.IModalSettings = {
+ templateUrl: '../view-models/forms/property-forms/base-property-form/property-form-base-view.html',
+ controller: 'Sdc.ViewModels.ModulePropertyView',
+ size: 'sdc-l',
+ backdrop: 'static',
+ keyboard: false,
+ resolve: {
+ originalProperty: ():PropertyModel => {
+ return property;
+ },
+ component: ():Component => {
+ return <Component> component;
+ },
+ selectedModule: ():DisplayModule => {
+ return selectedModule;
+ }
+ }
+ };
+
+ let modalInstance:ng.ui.bootstrap.IModalServiceInstance = this.$uibModal.open(modalOptions);
+ deferred.resolve(modalInstance.result);
+ return deferred.promise;
+ };
+
+ openSelectDataTypeModal = (property:PropertyModel, component:Component, filteredProperties:Array<PropertyModel>, propertiesMap:Array<InputPropertyBase>):ng.IPromise<any> => {
+ let deferred = this.$q.defer();
+
+ let modalOptions:ng.ui.bootstrap.IModalSettings = {
+ templateUrl: '../view-models/forms/property-forms/base-property-form/property-form-base-view.html',
+ controller: 'Sdc.ViewModels.SelectDataTypeViewModel',
+ size: 'sdc-l',
+ backdrop: 'static',
+ keyboard: false,
+ resolve: {
+ originalProperty: ():PropertyModel => {
+ return property;
+ },
+ component: ():Component => {
+ return <Component> component;
+ },
+ filteredProperties: ():Array<PropertyModel> => {
+ return filteredProperties;
+ },
+ propertiesMap: ():Array<InputPropertyBase>=> {
+ return propertiesMap;
+ }
+ }
+ };
+
+ let modalInstance:ng.ui.bootstrap.IModalServiceInstance = this.$uibModal.open(modalOptions);
+ deferred.resolve(modalInstance.result);
+ return deferred.promise;
+ };
+
+ public openEditAttributeModal = (attribute:AttributeModel, component: Component):void => {
+
+ let modalOptions:ng.ui.bootstrap.IModalSettings = {
+ templateUrl: '../view-models/forms/attribute-form/attribute-form-view.html',
+ controller: 'Sdc.ViewModels.AttributeFormViewModel',
+ size: 'sdc-md',
+ backdrop: 'static',
+ keyboard: false,
+ resolve: {
+ attribute: ():AttributeModel => {
+ return attribute;
+ },
+ component: ():Component => {
+ return component;
+ }
+ }
+ };
+ this.$uibModal.open(modalOptions);
+ };
+
+ public openUpdateComponentInstanceNameModal = (currentComponent: Component):ng.IPromise<any> => {
+ let deferred = this.$q.defer();
+
+ let modalOptions:ng.ui.bootstrap.IModalSettings = {
+ templateUrl: '../view-models/forms/resource-instance-name-form/resource-instance-name-view.html',
+ controller: 'Sdc.ViewModels.ResourceInstanceNameViewModel',
+ size: 'sdc-sm',
+ backdrop: 'static',
+ resolve: {
+ component: ():Component => {
+ return currentComponent;
+ }
+ }
+ };
+
+ let modalInstance:ng.ui.bootstrap.IModalServiceInstance = this.$uibModal.open(modalOptions);
+ deferred.resolve(modalInstance.result);
+ return deferred.promise;
+ };
+
+ public openConformanceLevelModal = ():ng.IPromise<any> => {
+ let deferred = this.$q.defer();
+ let modalOptions:ng.ui.bootstrap.IModalSettings = {
+ templateUrl: '../view-models/workspace/conformance-level-modal/conformance-level-modal-view.html',
+ controller: 'Sdc.ViewModels.ConformanceLevelModalViewModel',
+ size: 'sdc-sm',
+ backdrop: 'static',
+ resolve: {
+
+ }
+ };
+
+ let modalInstance:ng.ui.bootstrap.IModalServiceInstance = this.$uibModal.open(modalOptions);
+ deferred.resolve(modalInstance.result);
+ return deferred.promise;
+ };
+
+}
diff --git a/catalog-ui/src/app/utils/prototypes.ts b/catalog-ui/src/app/utils/prototypes.ts
new file mode 100644
index 0000000000..2aa718a06c
--- /dev/null
+++ b/catalog-ui/src/app/utils/prototypes.ts
@@ -0,0 +1,64 @@
+interface String {
+ format(variables:Array<string>):string
+}
+
+interface Array<T> {
+ clean(o:T):Array<T>;
+}
+
+
+/**
+ * This function will replace the %<number> with strings (from array).
+ * Example: "Requested '%1' resource was not found.".format(["MyResource"]);
+ * Note: in case the array contains empty string the function will also remove the '' or the "".
+ */
+if (!String.hasOwnProperty("format")) {
+ String.prototype["format"] = function (variables:Array<string>):string {
+
+ if (variables === null || variables === undefined || variables.length === 0) {
+ variables = [''];
+ }
+
+ for (let i = 0; i < variables.length; i++) {
+ if (variables[i] === '' || variables[i] === null) {
+ variables[i] = '--DELETE--';
+ }
+ }
+
+ let res = this.replace(/%(\d+)/g, function (_, m) {
+ return variables[--m];
+ });
+
+ res = res.replace(" '--DELETE--' ", " ");
+ res = res.replace(" \"--DELETE--\" ", " ");
+ res = res.replace("'--DELETE--'", "");
+ res = res.replace("\"--DELETE--\"", "");
+ res = res.replace("--DELETE--", "");
+
+ return res;
+ };
+}
+
+if (!String.hasOwnProperty("capitalizeFirstLetter")) {
+ String.prototype["capitalizeFirstLetter"] = function () {
+ return this.charAt(0).toUpperCase() + this.slice(1);
+ };
+}
+
+if (!String.hasOwnProperty("replaceAll")) {
+ String.prototype["replaceAll"] = function (find:string, replace:string):string {
+ return this.replace(new RegExp(find, 'g'), replace);
+ };
+}
+
+if (!Array.hasOwnProperty("clean")) {
+ Array.prototype.clean = function (deleteValue) {
+ for (let i = 0; i < this.length; i++) {
+ if (this[i] == deleteValue) {
+ this.splice(i, 1);
+ i--;
+ }
+ }
+ return this;
+ };
+}
diff --git a/catalog-ui/src/app/utils/validation-utils.ts b/catalog-ui/src/app/utils/validation-utils.ts
new file mode 100644
index 0000000000..9246d3350d
--- /dev/null
+++ b/catalog-ui/src/app/utils/validation-utils.ts
@@ -0,0 +1,153 @@
+class basePattern {
+ pattern:RegExp;
+ base:number;
+
+ constructor(pattern:RegExp, base:number) {
+ this.pattern = pattern;
+ this.base = base;
+ }
+}
+
+export interface IMapRegex {
+ integer:RegExp;
+ boolean:RegExp;
+ float:RegExp;
+ string:RegExp;
+}
+
+export class ValidationUtils {
+
+ static '$inject' = [
+ 'IntegerNoLeadingZeroValidationPattern',
+ 'FloatValidationPattern',
+ 'CommentValidationPattern',
+ 'BooleanValidationPattern',
+ 'NumberValidationPattern',
+ 'LabelValidationPattern',
+ ];
+ private trueRegex:string = '[t][r][u][e]|[t]|[o][n]|[y]|[y][e][s]|[1]';
+ private falseRegex:string = '[f][a][l][s][e]|[f]|[o][f][f]|[n]|[n][o]|[0]';
+ private heatBooleanValidationPattern:RegExp = new RegExp('^(' + this.trueRegex + '|' + this.falseRegex + ')$');
+
+
+ constructor(private IntegerNoLeadingZeroValidationPattern:RegExp,
+ private FloatValidationPattern:RegExp,
+ private CommentValidationPattern:RegExp,
+ private BooleanValidationPattern:RegExp,
+ private NumberValidationPattern:RegExp,
+ private LabelValidationPattern:RegExp) {
+ }
+
+ public stripAndSanitize(text:string):string {
+ if (!text) {
+ return null;
+ }
+ return text.replace(/\s+/g, ' ').replace(/%[A-Fa-f0-9]{2}/g, '').trim();
+ }
+
+ public getValidationPattern = (validationType:string, parameterType?:string):RegExp => {
+ switch (validationType) {
+ case 'integer':
+ return this.IntegerNoLeadingZeroValidationPattern;
+ case 'float':
+ return this.FloatValidationPattern;
+ case 'number':
+ return this.NumberValidationPattern;
+ case 'string':
+ return this.CommentValidationPattern;
+ case 'boolean':
+ {
+ //Bug Fix DE197437 [Patch]Mismatch between BE to FE regarding supported characters in Boolean filed
+ if (parameterType && parameterType === 'heat') {
+ return this.heatBooleanValidationPattern;
+ }
+ else {
+ return this.BooleanValidationPattern;
+ }
+ }
+
+ case 'label':
+ return this.LabelValidationPattern;
+ case 'category':
+ return this.LabelValidationPattern;
+ default :
+ return null;
+ }
+ };
+
+ public getPropertyListPatterns():IMapRegex {
+ return {
+ integer: /^(0|[-+]?[1-9][0-9]*|[-+]?0x[0-9a-fA-F]+|[-+]?0o[0-7]+)(,?(0|[-+]?[1-9][0-9]*|[-+]?0x[0-9a-fA-F]+|[-+]?0o[0-7]+))*$/,
+ string: /^"[\u0000-\u0021\u0023-\u00BF]+"(\s*,?\s*"[\u0000-\u0021\u0023-\u00BF]+")*$/,
+ boolean: /^([Tt][Rr][Uu][Ee]|[Ff][Aa][Ll][Ss][Ee])(,?([Tt][Rr][Uu][Ee]|[Ff][Aa][Ll][Ss][Ee]))*$/,
+ float: /^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?(,?[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?f?)*$/
+ };
+ }
+
+ public getPropertyMapPatterns():IMapRegex {
+ return {
+ integer: /^"\w+"\s*:\s?(0|[-+]?[1-9][0-9]*|[-+]?0x[0-9a-fA-F]+|[-+]?0o[0-7]+)+(\s*,?\s*"\w+"\s?:\s?(0|[-+]?[1-9][0-9]*|[-+]?0x[0-9a-fA-F]+|[-+]?0o[0-7]+)+)*$/,
+ string: /^"\w+"\s?:\s?"[\u0000-\u0021\u0023-\u00BF]*"(\s*,?\s*"\w+"\s?:\s?"[\u0000-\u0021\u0023-\u00BF]*")*$/,
+ boolean: /^"\w+"\s?:\s?([Tt][Rr][Uu][Ee]|[Ff][Aa][Ll][Ss][Ee])(\s*,?\s*"\w+"\s?:\s?([Tt][Rr][Uu][Ee]|[Ff][Aa][Ll][Ss][Ee]))*$/,
+ float: /^"\w+"\s?:\s?[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?f?(\s*,?\s*"\w+"\s?:\s?[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?f?)*$/
+ };
+ }
+
+ public validateUniqueKeys(viewValue:string):boolean {
+ if (!viewValue) {
+ return true; //allow empty value
+ }
+
+ let json:string = "{" + viewValue.replace(/\s\s+/g, ' ') + "}";
+ try {
+ let obj:any = JSON.parse(json);
+ /*
+ //Method #1 : check json string length before & after parsing
+ let newJson:string = JSON.stringify(obj);
+ if (newJson.length < json.length) {
+ return false;
+ }*/
+
+ //Method #2 : check how many times we can find "KEY": in json string
+ let result:boolean = true;
+ Object.keys(obj).forEach((key:string) => {
+ result = result && json.split('"' + key + '":').length === 2;
+ });
+ return result;
+
+ } catch (e) {
+ return false; //not a valid JSON
+ }
+
+ //return true;
+ }
+
+ public validateJson = (json:string):boolean => {
+ try {
+ JSON.parse(json);
+ return true;
+ } catch (err) {
+ console.log('invalid json');
+ return false;
+ }
+ };
+
+ public validateIntRange = (value:string):boolean => {
+
+ let base8 = new basePattern(/^([-+]?0o[0-7]+)$/, 8);
+ let base10 = new basePattern(/^(0|[-+]?[1-9][0-9]*)$/, 10);
+ let base16 = new basePattern(/^([-+]?0x[0-9a-fA-F]+)$/, 16);
+
+ let min:number = -0x80000000;
+ let max:number = 0x7fffffff;
+ let intPatterns:Array<basePattern> = [base8, base10, base16];
+ let matchedBase = _.find(intPatterns, (item)=> {
+ return item.pattern.test(value);
+ });
+
+ let parsed:number = parseInt(value.replace('o', ''), matchedBase.base);
+ if (parsed) {
+ return min <= parsed && max >= parsed;
+ }
+ }
+}
diff --git a/catalog-ui/src/app/view-models/admin-dashboard/add-category-modal/add-category-modal-view-model.ts b/catalog-ui/src/app/view-models/admin-dashboard/add-category-modal/add-category-modal-view-model.ts
new file mode 100644
index 0000000000..c421e632da
--- /dev/null
+++ b/catalog-ui/src/app/view-models/admin-dashboard/add-category-modal/add-category-modal-view-model.ts
@@ -0,0 +1,72 @@
+'use strict';
+import {ICategoryResourceClass, ICategoryResource} from "../../../services/category-resource-service";
+
+interface IAddCategoryModalViewModelScope extends ng.IScope {
+ category:ICategoryResource;
+ modelType:string;
+ footerButtons:Array<any>;
+ forms:any;
+
+ save():void;
+ close():void;
+}
+
+export class AddCategoryModalViewModel {
+
+ static '$inject' = [
+ '$scope',
+ 'Sdc.Services.CategoryResourceService',
+ '$uibModalInstance',
+ 'parentCategory',
+ 'type'
+ ];
+
+ constructor(private $scope:IAddCategoryModalViewModelScope,
+ private categoryResourceService:ICategoryResourceClass,
+ private $uibModalInstance:ng.ui.bootstrap.IModalServiceInstance,
+ private parentCategory:ICategoryResource,
+ private type:string) {
+ this.initScope();
+ }
+
+ private initScope = ():void => {
+ this.$scope.forms = {};
+ this.$scope.modelType = this.parentCategory ? 'sub category' : 'category';
+ this.$scope.category = new this.categoryResourceService();
+
+ this.$scope.close = ():void => {
+ this.$uibModalInstance.dismiss();
+ };
+
+ this.$scope.save = ():void => {
+
+ let onOk = (newCategory:ICategoryResource):void => {
+ this.$uibModalInstance.close(newCategory);
+ };
+
+ let onCancel = ():void => {
+ //error
+ };
+
+ if (!this.parentCategory) {
+ this.$scope.category.$save({types: this.type + "s"}, onOk, onCancel);
+ } else {
+ this.$scope.category.$saveSubCategory({
+ types: this.type + "s",
+ categoryId: this.parentCategory.uniqueId
+ }, onOk, onCancel);
+ }
+
+ };
+
+ this.$scope.footerButtons = [
+ {'name': 'OK', 'css': 'blue', 'callback': this.$scope.save, 'disabled': true},
+ {'name': 'Cancel', 'css': 'grey', 'callback': this.$scope.close}
+ ];
+
+ this.$scope.$watch("forms.editForm.$invalid", (newVal, oldVal) => {
+ this.$scope.footerButtons[0].disabled = this.$scope.forms.editForm.$invalid;
+ });
+
+ }
+}
diff --git a/catalog-ui/app/scripts/view-models/admin-dashboard/add-category-modal/add-category-modal-view.html b/catalog-ui/src/app/view-models/admin-dashboard/add-category-modal/add-category-modal-view.html
index 5718982661..a9df3e6009 100644
--- a/catalog-ui/app/scripts/view-models/admin-dashboard/add-category-modal/add-category-modal-view.html
+++ b/catalog-ui/src/app/view-models/admin-dashboard/add-category-modal/add-category-modal-view.html
@@ -26,10 +26,10 @@
maxlength="25"
autofocus />
- <div class="input-error" data-ng-show="editForm.categoryName.$dirty && editForm.categoryName.$invalid">
- <span ng-show="editForm.categoryName.$error.required" translate="CREATE_CATEGORY_MODAL_REQUIRED" translate-values="{'modelType': '{{modelType}}' }"></span>
- <span ng-show="editForm.categoryName.$error.minlength" translate="CREATE_CATEGORY_MODAL_MINLENGTH" translate-values="{'minlength': '4', 'modelType': '{{modelType}}' }"></span>
- <span ng-show="editForm.categoryName.$error.pattern" translate="CREATE_CATEGORY_MODAL_PATTERN" translate-values="{'modelType': '{{modelType}}' }"></span>
+ <div class="input-error" data-ng-show="forms.editForm.categoryName.$dirty && forms.editForm.categoryName.$invalid">
+ <span ng-show="forms.editForm.categoryName.$error.required" translate="CREATE_CATEGORY_MODAL_REQUIRED" translate-values="{'modelType': '{{modelType}}' }"></span>
+ <span ng-show="forms.editForm.categoryName.$error.minlength" translate="CREATE_CATEGORY_MODAL_MINLENGTH" translate-values="{'minlength': '4', 'modelType': '{{modelType}}' }"></span>
+ <span ng-show="forms.editForm.categoryName.$error.pattern" translate="CREATE_CATEGORY_MODAL_PATTERN" translate-values="{'modelType': '{{modelType}}' }"></span>
</div>
</div>
diff --git a/catalog-ui/app/scripts/view-models/admin-dashboard/add-category-modal/add-category-modal-view.less b/catalog-ui/src/app/view-models/admin-dashboard/add-category-modal/add-category-modal-view.less
index 39d84aab23..39d84aab23 100644
--- a/catalog-ui/app/scripts/view-models/admin-dashboard/add-category-modal/add-category-modal-view.less
+++ b/catalog-ui/src/app/view-models/admin-dashboard/add-category-modal/add-category-modal-view.less
diff --git a/catalog-ui/src/app/view-models/admin-dashboard/admin-dashboard-view-model.ts b/catalog-ui/src/app/view-models/admin-dashboard/admin-dashboard-view-model.ts
new file mode 100644
index 0000000000..c8503bce42
--- /dev/null
+++ b/catalog-ui/src/app/view-models/admin-dashboard/admin-dashboard-view-model.ts
@@ -0,0 +1,61 @@
+'use strict';
+import {CacheService} from "app/services";
+import {IAppConfigurtaion} from "app/models";
+
+interface IAdminDashboardViewModelScope extends ng.IScope {
+ version:string;
+ sdcConfig:IAppConfigurtaion;
+ isLoading:boolean;
+ currentTab:string;
+ templateUrl:string;
+ monitorUrl:string;
+ moveToTab(tab:string):void;
+ isSelected(tab:string):boolean;
+}
+
+
+export class AdminDashboardViewModel {
+ static '$inject' = [
+ '$scope',
+ '$templateCache',
+ 'Sdc.Services.CacheService',
+ 'sdcConfig'
+ ];
+
+ constructor(private $scope:IAdminDashboardViewModelScope,
+ private $templateCache:ng.ITemplateCacheService,
+ private cacheService:CacheService,
+ private sdcConfig:IAppConfigurtaion) {
+
+ this.initScope();
+ }
+
+ private initScope = ():void => {
+
+ this.$scope.version = this.cacheService.get('version');
+ this.$scope.sdcConfig = this.sdcConfig;
+ this.$scope.monitorUrl = this.$scope.sdcConfig.api.kibana;
+ this.$scope.isSelected = (tab:string):boolean => {
+ return tab === this.$scope.currentTab;
+ }
+
+ this.$scope.moveToTab = (tab:string):void => {
+ if (tab === this.$scope.currentTab) {
+ return;
+ }
+ else if (tab === 'USER_MANAGEMENT') {
+ this.$scope.templateUrl="user-management-view.html";
+ this.$templateCache.put("user-management-view.html", require('app/view-models/admin-dashboard/user-management/user-management-view.html'));
+ }
+ else if (tab === 'CATEGORY_MANAGEMENT') {
+ this.$scope.templateUrl="category-management-view.html";
+ this.$templateCache.put("category-management-view.html", require('app/view-models/admin-dashboard/category-management/category-management-view.html'));
+ }
+ this.$scope.currentTab = tab;
+ };
+
+ this.$scope.moveToTab('USER_MANAGEMENT');
+
+
+ }
+}
diff --git a/catalog-ui/app/scripts/view-models/admin-dashboard/admin-dashboard-view.html b/catalog-ui/src/app/view-models/admin-dashboard/admin-dashboard-view.html
index 063525a4bf..150f7c2554 100644
--- a/catalog-ui/app/scripts/view-models/admin-dashboard/admin-dashboard-view.html
+++ b/catalog-ui/src/app/view-models/admin-dashboard/admin-dashboard-view.html
@@ -21,4 +21,6 @@
<div class="sdc-admin-body">
<ng-include src="templateUrl" ng-if="true"></ng-include>
</div>
+
+ <ecomp-footer></ecomp-footer>
</div>
diff --git a/catalog-ui/app/scripts/view-models/admin-dashboard/admin-dashboard.less b/catalog-ui/src/app/view-models/admin-dashboard/admin-dashboard.less
index 874a02c431..874a02c431 100644
--- a/catalog-ui/app/scripts/view-models/admin-dashboard/admin-dashboard.less
+++ b/catalog-ui/src/app/view-models/admin-dashboard/admin-dashboard.less
diff --git a/catalog-ui/src/app/view-models/admin-dashboard/category-management/category-management-view-model.ts b/catalog-ui/src/app/view-models/admin-dashboard/category-management/category-management-view-model.ts
new file mode 100644
index 0000000000..ba390c4bee
--- /dev/null
+++ b/catalog-ui/src/app/view-models/admin-dashboard/category-management/category-management-view-model.ts
@@ -0,0 +1,176 @@
+'use strict';
+import {ModalsHandler, ValidationUtils} from "app/utils";
+import {CacheService, ICategoryResource} from "app/services";
+import {IAppConfigurtaion} from "app/models";
+import {ComponentType} from "../../../utils/constants";
+
+interface ICategoryManagementViewModelScope extends ng.IScope {
+ SERVICE:string;
+ RESOURCE:string;
+ categoriesToShow:Array<ICategoryResource>;
+ serviceCategories:Array<ICategoryResource>;
+ resourceCategories:Array<ICategoryResource>;
+ selectedCategory:ICategoryResource;
+ selectedSubCategory:ICategoryResource;
+ modalInstance:ng.ui.bootstrap.IModalServiceInstance;
+ isLoading:boolean;
+ type:string;
+ namePattern:RegExp;
+
+ selectCategory(category:ICategoryResource):void;
+ selectSubCategory(subcategory:ICategoryResource):void;
+ selectType(type:string):void;
+ deleteCategory(category:ICategoryResource, subCategory:ICategoryResource):void;
+ createCategoryModal(parentCategory:ICategoryResource):void;
+}
+
+export class CategoryManagementViewModel {
+ static '$inject' = [
+ '$scope',
+ 'sdcConfig',
+ 'Sdc.Services.CacheService',
+ '$uibModal',
+ '$filter',
+ 'ValidationUtils',
+ 'ModalsHandler'
+ ];
+
+ constructor(private $scope:ICategoryManagementViewModelScope,
+ private sdcConfig:IAppConfigurtaion,
+ private cacheService:CacheService,
+ private $uibModal:ng.ui.bootstrap.IModalService,
+ private $filter:ng.IFilterService,
+ private ValidationUtils:ValidationUtils,
+ private ModalsHandler:ModalsHandler) {
+
+ this.initScope();
+ this.$scope.selectType(ComponentType.SERVICE.toLocaleLowerCase());
+
+ }
+
+ private initScope = ():void => {
+ let scope:ICategoryManagementViewModelScope = this.$scope;
+ scope.SERVICE = ComponentType.SERVICE.toLocaleLowerCase();
+ scope.RESOURCE = ComponentType.RESOURCE.toLocaleLowerCase();
+
+ scope.namePattern = this.ValidationUtils.getValidationPattern('category');
+
+ scope.selectCategory = (category:ICategoryResource) => {
+ if (scope.selectedCategory !== category) {
+ scope.selectedSubCategory = null;
+ }
+ scope.selectedCategory = category;
+ };
+ scope.selectSubCategory = (subcategory:ICategoryResource) => {
+ scope.selectedSubCategory = subcategory;
+ };
+ scope.selectType = (type:string):void => {
+ if (scope.type !== type) {
+ scope.selectedCategory = null;
+ scope.selectedSubCategory = null;
+ }
+
+ scope.type = type;
+ scope.categoriesToShow = scope[type + 'Categories'];
+ };
+
+ scope.createCategoryModal = (parentCategory:ICategoryResource):void => {
+ //can't create a sub category for service
+ if (parentCategory && scope.type === ComponentType.SERVICE.toLowerCase()) {
+ return;
+ }
+
+ let type:string = scope.type;
+
+ let onOk = (newCategory:ICategoryResource):void => {
+ if (!parentCategory) {
+ scope[type + 'Categories'].push(newCategory);
+ } else {
+ if (!parentCategory.subcategories) {
+ parentCategory.subcategories = [];
+ }
+ parentCategory.subcategories.push(newCategory);
+ }
+ };
+
+ let onCancel = ():void => {
+
+ };
+
+ let modalOptions:ng.ui.bootstrap.IModalSettings = {
+ template: 'src/app/view-models/admin-dashboard/add-category-modal/add-category-modal-view.html',
+ controller: 'Sdc.ViewModels.AddCategoryModalViewModel',
+ size: 'sdc-xsm',
+ backdrop: 'static',
+ scope: scope,
+ resolve: {
+ parentCategory: function () {
+ return parentCategory;
+ },
+ type: function () {
+ return type;
+ }
+ }
+ };
+
+ scope.modalInstance = this.$uibModal.open(modalOptions);
+ scope.modalInstance.result.then(onOk, onCancel);
+
+ };
+
+ scope.deleteCategory = (category:ICategoryResource, subCategory:ICategoryResource):void => {
+
+ let onOk = ():void => {
+
+ scope.isLoading = true;
+ let type:string = scope.type;
+
+ let onError = (response):void => {
+ scope.isLoading = false;
+ console.info('onFaild', response);
+ };
+
+ let onSuccess = (response:any):void => {
+ let arr:Array<ICategoryResource>;
+
+ if (!subCategory) {
+ arr = this.$scope[type + 'Categories'];
+ arr.splice(arr.indexOf(category), 1);
+ if (category === scope.selectedCategory) {
+ scope.selectedCategory = null;
+ scope.selectedSubCategory = null;
+ }
+ } else {
+ arr = category.subcategories;
+ arr.splice(arr.indexOf(subCategory), 1);
+ }
+
+ scope.isLoading = false;
+ };
+
+ if (!subCategory) {
+ category.$delete({
+ types: type + "s",
+ categoryId: category.uniqueId
+ }
+ , onSuccess, onError);
+ } else {
+ category.$deleteSubCategory({
+ types: type + "s",
+ categoryId: category.uniqueId,
+ subCategoryId: subCategory.uniqueId,
+ }
+ , onSuccess, onError);
+ }
+ };
+ let modelType:string = subCategory ? 'sub category' : 'category';
+ let title:string = this.$filter('translate')("DELETE_CATEGORY_MODAL_HEADER", "{'modelType': '" + modelType + "' }");
+ let message:string = this.$filter('translate')("DELETE_CATEGORY_MODAL_CATEGORY_NAME", "{'modelType': '" + modelType + "' }");
+
+ this.ModalsHandler.openConfirmationModal(title, message, false, 'sdc-xsm').then(onOk);
+ };
+
+ this.$scope.serviceCategories = this.cacheService.get('serviceCategories');
+ this.$scope.resourceCategories = this.cacheService.get('resourceCategories');
+ }
+}
diff --git a/catalog-ui/app/scripts/view-models/admin-dashboard/category-management/category-management-view.html b/catalog-ui/src/app/view-models/admin-dashboard/category-management/category-management-view.html
index 95a002d3d7..95a002d3d7 100644
--- a/catalog-ui/app/scripts/view-models/admin-dashboard/category-management/category-management-view.html
+++ b/catalog-ui/src/app/view-models/admin-dashboard/category-management/category-management-view.html
diff --git a/catalog-ui/app/scripts/view-models/admin-dashboard/category-management/category-management.less b/catalog-ui/src/app/view-models/admin-dashboard/category-management/category-management.less
index 011122c9e8..011122c9e8 100644
--- a/catalog-ui/app/scripts/view-models/admin-dashboard/category-management/category-management.less
+++ b/catalog-ui/src/app/view-models/admin-dashboard/category-management/category-management.less
diff --git a/catalog-ui/app/scripts/view-models/admin-dashboard/ecomp/ecomp-view.html b/catalog-ui/src/app/view-models/admin-dashboard/ecomp/ecomp-view.html
index 7c89b545c5..7c89b545c5 100644
--- a/catalog-ui/app/scripts/view-models/admin-dashboard/ecomp/ecomp-view.html
+++ b/catalog-ui/src/app/view-models/admin-dashboard/ecomp/ecomp-view.html
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
new file mode 100644
index 0000000000..82cc3a74da
--- /dev/null
+++ b/catalog-ui/src/app/view-models/admin-dashboard/user-management/user-management-view-model.ts
@@ -0,0 +1,202 @@
+'use strict';
+import {ModalsHandler} from "app/utils";
+import {IUserResource, IUserResourceClass} from "app/services";
+import {User, IUserProperties, IUser, IAppConfigurtaion} from "app/models";
+
+interface IUserManagementViewModelScope extends ng.IScope {
+ sdcConfig:IAppConfigurtaion;
+ usersList:Array<IUserProperties>;
+ isLoading:boolean;
+ isNewUser:boolean;
+ sortBy:string;
+ reverse:boolean;
+ tableHeadersList:any;
+ roles:Array<string>;
+ newUser:IUser;
+ currentUser:IUserResource;
+ userIdValidationPattern:RegExp;
+ editForm:ng.IFormController;
+ getAllUsers():void;
+ editUserRole(user:IUserProperties);
+ sort(sortBy:string):void;
+ createUser():void;
+ deleteUser(userId:string):void;
+ onEditUserPressed(user:IUserProperties):void;
+ saveUserChanges(user:IUserProperties):void;
+ getTitle(role:string):string;
+ clearForm():void;
+
+}
+
+
+export class UserManagementViewModel {
+ static '$inject' = [
+ '$scope',
+ 'sdcConfig',
+ 'Sdc.Services.UserResourceService',
+ 'UserIdValidationPattern',
+ '$filter',
+ 'ModalsHandler'
+ ];
+
+ constructor(private $scope:IUserManagementViewModelScope,
+ private sdcConfig:IAppConfigurtaion,
+ private userResourceService:IUserResourceClass,
+ private UserIdValidationPattern:RegExp,
+ private $filter:ng.IFilterService,
+ private ModalsHandler:ModalsHandler) {
+
+ this.initScope();
+
+ }
+
+
+ private getAllUsers = ():void => {
+ this.$scope.isLoading = true;
+
+ let onError = (response) => {
+ this.$scope.isLoading = false;
+ console.info('onFaild', response);
+ };
+ let onSuccess = (response:Array<IUserProperties>) => {
+ this.$scope.usersList = response;
+ _.forEach(this.$scope.usersList, (user:any, i:number)=> {
+ user.index = i;
+ });
+ this.$scope.isLoading = false;
+ };
+ this.userResourceService.getAllUsers(onSuccess, onError);
+ };
+
+ private updateUserFilterTerm = (user:IUserProperties):void => {
+ user.filterTerm = user.firstName + ' ' + user.lastName + ' ' + user.userId + ' ' + user.email + ' ' + user.role + ' ' + this.$filter('date')(user.lastLoginTime, "MM/dd/yyyy");
+ };
+
+ private initScope = ():void => {
+ let self = this;
+
+ this.$scope.tableHeadersList = [{title: "First Name", property: 'firstName'}, {
+ title: "Last Name",
+ property: 'lastName'
+ },
+ {
+ title: this.$filter('translate')("USER_MANAGEMENT_TABLE_HEADER_USER_ID"),
+ property: 'userId'
+ }, {title: "Email", property: 'email'}, {title: "Role", property: 'role'}, {
+ title: "Last Active",
+ property: 'lastLoginTime'
+ }];
+ this.$scope.userIdValidationPattern = this.UserIdValidationPattern;
+ this.$scope.sortBy = 'lastLoginTime';
+ this.$scope.reverse = false;
+ this.$scope.roles = this.sdcConfig.roles;
+ this.$scope.isNewUser = false;
+ this.$scope.currentUser = this.userResourceService.getLoggedinUser();
+ this.getAllUsers();
+
+ let resource:IUserResource = <IUserResource>{};
+ this.$scope.newUser = new User(resource);
+
+ this.$scope.sort = (sortBy:string):void => {//default sort by descending last update. default for alphabetical = ascending
+ this.$scope.isNewUser = false;
+ this.$scope.reverse = (this.$scope.sortBy === sortBy) ? ( !this.$scope.reverse) : this.$scope.reverse = false;
+ this.$scope.sortBy = sortBy;
+ };
+
+ this.$scope.createUser = ():void => {
+
+ let onError = (response) => {
+ this.$scope.isLoading = false;
+ console.info('onFaild', response);
+ };
+
+ let onSuccess = (response:IUserProperties) => {
+ this.$scope.newUser.resource['index'] = this.$scope.usersList.length;
+ this.$scope.newUser.resource.lastLoginTime = "0";
+ this.$scope.newUser.resource.status = response.status;
+ this.updateUserFilterTerm(this.$scope.newUser.resource);
+ this.$scope.usersList.unshift(this.$scope.newUser.resource);
+ this.$scope.isNewUser = true;
+ this.$scope.sortBy = 'index';
+ this.$scope.reverse = true;
+ this.$scope.isLoading = false;
+ this.$scope.newUser = new User(null);
+ this.$scope.editForm.$setPristine();
+ let _self = this;
+ setTimeout(function () {
+ _self.$scope.isNewUser = false;
+ }, 7000);
+ };
+ this.userResourceService.createUser({
+ userId: this.$scope.newUser.resource.userId,
+ role: this.$scope.newUser.resource.role
+ }, onSuccess, onError);
+ };
+
+
+ this.$scope.onEditUserPressed = (user:IUserProperties):void => {
+ user.isInEditMode = true;
+ user.tempRole = user.role;
+ };
+
+ this.$scope.editUserRole = (user:IUserProperties):void => {
+ let roleBeforeUpdate:string = user.role;
+ user.role = user.tempRole;
+
+ let onError = (response) => {
+ this.$scope.isLoading = false;
+ user.role = roleBeforeUpdate;
+ console.info('onFaild', response);
+ };
+ let onSuccess = (response:any) => {
+ this.$scope.isLoading = false;
+ user.tempRole = user.role;
+ this.updateUserFilterTerm(user);
+ };
+
+ this.userResourceService.editUserRole({id: user.userId, role: user.role}, onSuccess, onError);
+ };
+
+ this.$scope.saveUserChanges = (user:IUserProperties):void => {
+ if (user.tempRole != user.role) {
+ this.$scope.editUserRole(user)
+ }
+ user.isInEditMode = false;
+ };
+
+ this.$scope.deleteUser = (userId:string):void => {
+
+ let onOk = ():void => {
+ this.$scope.isLoading = true;
+
+ let onError = (response):void => {
+ this.$scope.isLoading = false;
+ console.info('onFaild', response);
+ };
+
+ let onSuccess = (response:any):void => {
+ _.remove(this.$scope.usersList, {userId: userId});
+ this.$scope.isLoading = false;
+ };
+ this.userResourceService.deleteUser({id: userId}, onSuccess, onError);
+ };
+
+ let title:string = this.$filter('translate')("USER_MANAGEMENT_VIEW_DELETE_MODAL_TITLE");
+ let message:string = this.$filter('translate')("USER_MANAGEMENT_VIEW_DELETE_MODAL_TEXT");
+ this.ModalsHandler.openConfirmationModal(title, message, false).then(onOk);
+ };
+
+ this.$scope.getTitle = (role:string):string => {
+ return role.toLowerCase().replace('governor', 'governance_Rep').replace('_', ' ');
+ };
+
+ this.$scope.clearForm = ():void => {
+ if (!this.$scope.editForm['contactId'].$viewValue && !this.$scope.editForm['role'].$viewValue) {
+ this.$scope.editForm.$setPristine();
+ }
+ //if(this.$scope.editForm['contactId'].$viewValue === '' && this.$scope.editForm['role'].$viewValue){
+ // this.$scope.editForm.$setPristine();
+ //}
+ };
+ }
+}
diff --git a/catalog-ui/app/scripts/view-models/admin-dashboard/user-management/user-management-view.html b/catalog-ui/src/app/view-models/admin-dashboard/user-management/user-management-view.html
index 26e720b044..d2983873cc 100644
--- a/catalog-ui/app/scripts/view-models/admin-dashboard/user-management/user-management-view.html
+++ b/catalog-ui/src/app/view-models/admin-dashboard/user-management/user-management-view.html
@@ -3,7 +3,7 @@
<div class="sdc-user-management-top-bar">
<div class="sdc-user-management-top-bar-search-container">
<label class="sdc-user-management-top-bar-search-text">Search User</label>
- <input type="text" class="sdc-user-management-top-bar-form-input" placeholder="{{ USER_MANAGEMENT_SEARCH_LABEL | translate }}" data-ng-model="search.filterTerm" ng-model-options="{ debounce: 500 }" data-tests-id="searchbox" />
+ <input type="text" class="sdc-user-management-top-bar-form-input" placeholder="Search user by name, userId, email or role" data-ng-model="search.filterTerm" ng-model-options="{ debounce: 500 }" data-tests-id="searchbox" />
<span class="w-sdc-search-icon" data-ng-class="{'cancel':search.filterTerm, 'magnification':!search.filterTerm}" data-ng-click="search.filterTerm=''" ></span>
</div>
<div class="vertical-border-container">
@@ -23,7 +23,7 @@
data-ng-change="clearForm()"
data-ng-blur="clearForm()"
data-required
- data-tests-id="newuserid" />
+ data-tests-id="newuserId" />
<div class="input-error" data-ng-show="editForm.contactId.$dirty && editForm.contactId.$invalid">
<span ng-show="editForm.contactId.$error.required" translate="NEW_USER_ERROR_USER_ID_REQUIRED"></span>
@@ -67,30 +67,31 @@
<div ng-init="user.filterTerm = user.firstName + ' ' + user.lastName + ' ' + user.userId + ' ' + user.email + ' ' + user.role + ' ' + (user.lastLoginTime | date: 'MM/dd/yyyy')"
ng-repeat="user in usersList | filter: search | orderBy:sortBy:reverse"
data-ng-class="{'sdc-user-management-table-new-user-row': (isNewUser && $first), 'sdc-user-management-table-row-edit-mode': user.isInEditMode}"
- class="sdc-user-management-flex-container data-row" data-tests-id="tdRow">
+ class="sdc-user-management-flex-container data-row" data-tests-id="row_{{$index}}">
- <div sdc-smart-tooltip class="sdc-user-management-table-col-general sdc-user-management-flex-item" data-tests-id="td{{tableHeadersList[0].title}}">{{user.firstName || '---'}}</div>
- <div sdc-smart-tooltip class="sdc-user-management-table-col-general sdc-user-management-flex-item" data-tests-id="td{{tableHeadersList[1].title}}">{{user.lastName || '---' }}</div>
- <div class="sdc-user-management-table-col-userid sdc-user-management-flex-item" data-tests-id="td{{tableHeadersList[2].title}}">{{user.userId || '---'}}</div>
- <div sdc-smart-tooltip class="sdc-user-management-table-col-general sdc-user-management-flex-item" data-tests-id="td{{tableHeadersList[3].title}}">{{user.email || '---'}}</div>
- <div class="sdc-user-management-table-col-general sdc-user-management-flex-item" data-tests-id="td{{tableHeadersList[4].title}}">
+ <div sdc-smart-tooltip class="sdc-user-management-table-col-general sdc-user-management-flex-item" data-tests-id="firstName_{{$index}}">{{user.firstName || '---'}}</div>
+ <div sdc-smart-tooltip class="sdc-user-management-table-col-general sdc-user-management-flex-item" data-tests-id="lastName__{{$index}}">{{user.lastName || '---' }}</div>
+ <div class="sdc-user-management-flex-item" data-tests-id="userId_{{$index}}">{{user.userId || '---'}}</div>
+ <div sdc-smart-tooltip class="sdc-user-management-table-col-general sdc-user-management-flex-item" data-tests-id="email_{{$index}}">{{user.email || '---'}}</div>
+ <div class="sdc-user-management-table-col-general sdc-user-management-flex-item">
<div class="sdc-user-management-table-role-select capitalize sdc-user-management-table-role-label"
data-ng-if="!user.isInEditMode"
+ data-tests-id="role_{{$index}}"
data-ng-bind="getTitle(user.role)"></div>
<select class="sdc-user-management-table-role-select capitalize"
- data-tests-id="tdselectrole"
+ data-tests-id="selectRole_{{$index}}"
data-ng-if="user.isInEditMode"
data-ng-model="user.tempRole"
data-ng-options="role as (getTitle(role)) for role in roles | orderBy:'role'">
</select>
</div>
- <div class="sdc-user-management-table-col-general sdc-user-management-flex-item" data-tests-id="td{{tableHeadersList[5].title}}">{{user.lastLoginTime == 0 ? 'Waiting' : (user.lastLoginTime | date:'MM/dd/yyyy')}}</div>
+ <div class="sdc-user-management-table-col-general sdc-user-management-flex-item" data-tests-id="lastActive_{{$index}}">{{user.lastLoginTime == 0 ? 'Waiting' : (user.lastLoginTime | date:'MM/dd/yyyy')}}</div>
<div class="sdc-user-management-table-btn-col sdc-user-management-flex-item">
- <button data-ng-disabled="user.isInEditMode" data-ng-hide="user.isInEditMode || currentUser.userId === user.userId" class="sdc-user-management-table-edit-btn" ng-click="onEditUserPressed(user)" data-tests-id="updateuser{{user.userId}}"> </button>
- <button data-ng-show="user.isInEditMode" class="sdc-user-management-table-save-btn" ng-click="saveUserChanges(user)" data-tests-id="tdsave"> </button>
+ <button data-ng-disabled="user.isInEditMode" data-ng-hide="user.isInEditMode || currentUser.userId === user.userId" class="sdc-user-management-table-edit-btn" ng-click="onEditUserPressed(user)" data-tests-id="updateUser_{{$index}}"> </button>
+ <button data-ng-show="user.isInEditMode" class="sdc-user-management-table-save-btn" ng-click="saveUserChanges(user)" data-tests-id="save_{{$index}}"> </button>
</div>
<div class="sdc-user-management-table-btn-col sdc-user-management-flex-item">
- <button data-ng-hide="currentUser.userId === user.userId" class="sdc-user-management-table-delete-btn" ng-click="deleteUser(user.userId)" data-tests-id="delete{{user.userId}}"> </button>
+ <button data-ng-hide="currentUser.userId === user.userId" class="sdc-user-management-table-delete-btn" ng-click="deleteUser(user.userId)" data-tests-id="delete_{{$index}}"> </button>
</div>
</div>
diff --git a/catalog-ui/app/scripts/view-models/admin-dashboard/user-management/user-management.less b/catalog-ui/src/app/view-models/admin-dashboard/user-management/user-management.less
index 934faab9e7..934faab9e7 100644
--- a/catalog-ui/app/scripts/view-models/admin-dashboard/user-management/user-management.less
+++ b/catalog-ui/src/app/view-models/admin-dashboard/user-management/user-management.less
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
new file mode 100644
index 0000000000..0e7e4aaeae
--- /dev/null
+++ b/catalog-ui/src/app/view-models/catalog/catalog-view-model.ts
@@ -0,0 +1,303 @@
+'use strict';
+import {Component, IMainCategory, IGroup, IConfigStatuses, IAppMenu, IAppConfigurtaion, IUserProperties, ISubCategory} from "app/models";
+import {EntityService, IUserResourceClass, CacheService} from "app/services";
+import {ComponentFactory, ResourceType, MenuHandler, ChangeLifecycleStateHandler} from "app/utils";
+
+
+interface Checkboxes {
+ componentTypes:Array<string>;
+ resourceSubTypes:Array<string>;
+}
+
+interface CheckboxesFilter {
+ // Types
+ selectedComponentTypes:Array<string>;
+ selectedResourceSubTypes:Array<string>;
+ // Categories
+ selectedCategoriesModel:Array<string>;
+ // Statuses
+ selectedStatuses:Array<string>;
+}
+
+interface Gui {
+ isLoading:boolean;
+ onResourceSubTypesClick:Function;
+ onComponentTypeClick:Function;
+ onCategoryClick:Function;
+ onSubcategoryClick:Function;
+ onGroupClick:Function;
+}
+
+export interface ICatalogViewModelScope extends ng.IScope {
+ checkboxes:Checkboxes;
+ checkboxesFilter:CheckboxesFilter;
+ gui:Gui;
+
+ categories:Array<IMainCategory>;
+ confStatus:IConfigStatuses;
+ sdcMenu:IAppMenu;
+ catalogFilterdItems:Array<Component>;
+ expandedSection:Array<string>;
+ actionStrategy:any;
+ user:IUserProperties;
+ catalogMenuItem:any;
+ version:string;
+ sortBy:string;
+ reverse:boolean;
+ vfcmtType:string;
+
+ //this is for UI paging
+ numberOfItemToDisplay:number;
+ isAllItemDisplay:boolean;
+
+ changeLifecycleState(entity:any, state:string):void;
+ sectionClick (section:string):void;
+ order(sortBy:string):void;
+ getNumOfElements(num:number):string;
+ goToComponent(component:Component):void;
+ raiseNumberOfElementToDisplay():void;
+}
+
+export class CatalogViewModel {
+ static '$inject' = [
+ '$scope',
+ '$filter',
+ 'Sdc.Services.EntityService',
+ 'sdcConfig',
+ 'sdcMenu',
+ '$state',
+ '$q',
+ 'Sdc.Services.UserResourceService',
+ 'Sdc.Services.CacheService',
+ 'ComponentFactory',
+ 'ChangeLifecycleStateHandler',
+ 'MenuHandler'
+ ];
+
+ constructor(private $scope:ICatalogViewModelScope,
+ private $filter:ng.IFilterService,
+ private EntityService:EntityService,
+ private sdcConfig:IAppConfigurtaion,
+ private sdcMenu:IAppMenu,
+ private $state:ng.ui.IStateService,
+ private $q:ng.IQService,
+ private userResourceService:IUserResourceClass,
+ private cacheService:CacheService,
+ private ComponentFactory:ComponentFactory,
+ private ChangeLifecycleStateHandler:ChangeLifecycleStateHandler,
+ private MenuHandler:MenuHandler) {
+
+
+ this.initScopeMembers();
+ this.initCatalogData(); // Async task to get catalog from server.
+ this.initScopeMethods();
+ }
+
+ private initCatalogData = ():void => {
+ let onSuccess = (followedResponse:Array<Component>):void => {
+ this.$scope.catalogFilterdItems = followedResponse;
+ this.$scope.isAllItemDisplay = this.$scope.numberOfItemToDisplay >= this.$scope.catalogFilterdItems.length;
+ this.$scope.categories = this.cacheService.get('serviceCategories').concat(this.cacheService.get('resourceCategories')).concat(this.cacheService.get('productCategories'));
+ this.$scope.gui.isLoading = false;
+ };
+
+ let onError = ():void => {
+ console.info('Failed to load catalog CatalogViewModel::initCatalog');
+ this.$scope.gui.isLoading = false;
+ };
+ this.EntityService.getCatalog().then(onSuccess, onError);
+ };
+
+
+ private initScopeMembers = ():void => {
+ // Gui init
+ this.$scope.gui = <Gui>{};
+ this.$scope.gui.isLoading = true;
+ this.$scope.numberOfItemToDisplay = 0;
+ //this.$scope.categories = this.cacheService.get('categoriesMap');
+ this.$scope.sdcMenu = this.sdcMenu;
+ this.$scope.confStatus = this.sdcMenu.statuses;
+ this.$scope.expandedSection = ["type", "category", "product-category", "status"];
+ this.$scope.user = this.userResourceService.getLoggedinUser();
+ this.$scope.catalogMenuItem = this.sdcMenu.catalogMenuItem;
+ this.$scope.version = this.cacheService.get('version');
+ this.$scope.sortBy = 'lastUpdateDate';
+ this.$scope.reverse = true;
+
+
+ // Checklist init
+ this.$scope.checkboxes = <Checkboxes>{};
+ this.$scope.checkboxes.componentTypes = ['Resource', 'Service', 'Product'];
+ this.$scope.checkboxes.resourceSubTypes = ['VF', 'VFC', 'CP', 'VL'];
+
+ // Checkboxes filter init
+ this.$scope.checkboxesFilter = <CheckboxesFilter>{};
+ this.$scope.checkboxesFilter.selectedComponentTypes = [];
+ this.$scope.checkboxesFilter.selectedResourceSubTypes = [];
+ this.$scope.checkboxesFilter.selectedCategoriesModel = [];
+ this.$scope.checkboxesFilter.selectedStatuses = [];
+
+ // this.$scope.isAllItemDisplay = this.$scope.numberOfItemToDisplay >= this.$scope.catalogFilterdItems.length;
+
+ this.$scope.vfcmtType = ResourceType.VFCMT;
+ };
+
+ private initScopeMethods = ():void => {
+ this.$scope.sectionClick = (section:string):void => {
+ let index:number = this.$scope.expandedSection.indexOf(section);
+ if (index !== -1) {
+ this.$scope.expandedSection.splice(index, 1);
+ } else {
+ this.$scope.expandedSection.push(section);
+ }
+ };
+
+
+ this.$scope.order = (sortBy:string):void => {//default sort by descending last update. default for alphabetical = ascending
+ this.$scope.reverse = (this.$scope.sortBy === sortBy) ? !this.$scope.reverse : (sortBy === 'lastUpdateDate') ? true : false;
+ this.$scope.sortBy = sortBy;
+ };
+
+
+ this.$scope.goToComponent = (component:Component):void => {
+ this.$scope.gui.isLoading = true;
+ this.$state.go('workspace.general', {id: component.uniqueId, type: component.componentType.toLowerCase()});
+ };
+
+
+ // Will print the number of elements found in catalog
+ this.$scope.getNumOfElements = (num:number):string => {
+ if (!num || num === 0) {
+ return "No Elements found";
+ } else if (num === 1) {
+ return "1 Element found";
+ } else {
+ return num + " Elements found";
+ }
+ };
+
+ /**
+ * Select | unselect sub resource when resource is clicked | unclicked.
+ * @param type
+ */
+ this.$scope.gui.onComponentTypeClick = (type:string):void => {
+ if (type === 'Resource') {
+ if (this.$scope.checkboxesFilter.selectedComponentTypes.indexOf('Resource') === -1) {
+ // If the resource was not selected, unselect all childs.
+ this.$scope.checkboxesFilter.selectedResourceSubTypes = [];
+ } else {
+ // If the resource was selected, select all childs
+ this.$scope.checkboxesFilter.selectedResourceSubTypes = angular.copy(this.$scope.checkboxes.resourceSubTypes);
+ }
+ }
+ };
+
+ /**
+ * Selecting | unselect resources when sub resource is clicked | unclicked.
+ */
+ this.$scope.gui.onResourceSubTypesClick = ():void => {
+ if (this.$scope.checkboxesFilter.selectedResourceSubTypes && this.$scope.checkboxesFilter.selectedResourceSubTypes.length === this.$scope.checkboxes.resourceSubTypes.length) {
+ this.$scope.checkboxesFilter.selectedComponentTypes.push('Resource');
+ } else {
+ this.$scope.checkboxesFilter.selectedComponentTypes = _.without(this.$scope.checkboxesFilter.selectedComponentTypes, 'Resource');
+ }
+ };
+
+ this.$scope.gui.onCategoryClick = (category:IMainCategory):void => {
+ // Select | Unselect all childs
+ if (this.isCategorySelected(category.uniqueId)) {
+ this.$scope.checkboxesFilter.selectedCategoriesModel = this.$scope.checkboxesFilter.selectedCategoriesModel.concat(angular.copy(_.map(category.subcategories, (item) => {
+ return item.uniqueId;
+ })));
+ if (category.subcategories) {
+ category.subcategories.forEach((sub:ISubCategory)=> { // Loop on all selected subcategories and mark the childrens
+ this.$scope.checkboxesFilter.selectedCategoriesModel = this.$scope.checkboxesFilter.selectedCategoriesModel.concat(angular.copy(_.map(sub.groupings, (item) => {
+ return item.uniqueId;
+ })));
+ });
+ }
+ } else {
+ this.$scope.checkboxesFilter.selectedCategoriesModel = _.difference(this.$scope.checkboxesFilter.selectedCategoriesModel, _.map(category.subcategories, (item) => {
+ return item.uniqueId;
+ }));
+ if (category.subcategories) {
+ category.subcategories.forEach((sub:ISubCategory)=> { // Loop on all selected subcategories and un mark the childrens
+ this.$scope.checkboxesFilter.selectedCategoriesModel = _.difference(this.$scope.checkboxesFilter.selectedCategoriesModel, _.map(sub.groupings, (item) => {
+ return item.uniqueId;
+ }));
+ });
+ }
+ }
+ };
+
+ this.$scope.gui.onSubcategoryClick = (category:IMainCategory, subCategory:ISubCategory):void => {
+ // Select | Unselect all childs
+ if (this.isCategorySelected(subCategory.uniqueId)) {
+ this.$scope.checkboxesFilter.selectedCategoriesModel = this.$scope.checkboxesFilter.selectedCategoriesModel.concat(angular.copy(_.map(subCategory.groupings, (item) => {
+ return item.uniqueId;
+ })));
+ } else {
+ this.$scope.checkboxesFilter.selectedCategoriesModel = _.difference(this.$scope.checkboxesFilter.selectedCategoriesModel, _.map(subCategory.groupings, (item) => {
+ return item.uniqueId;
+ }));
+ }
+
+ // Mark | Un mark the parent when all childs selected.
+ if (this.areAllCategoryChildsSelected(category)) {
+ // Add the category to checkboxesFilter.selectedCategoriesModel
+ this.$scope.checkboxesFilter.selectedCategoriesModel.push(category.uniqueId);
+ } else {
+ this.$scope.checkboxesFilter.selectedCategoriesModel = _.without(this.$scope.checkboxesFilter.selectedCategoriesModel, category.uniqueId);
+ }
+
+ };
+
+ this.$scope.raiseNumberOfElementToDisplay = ():void => {
+ this.$scope.numberOfItemToDisplay = this.$scope.numberOfItemToDisplay + 35;
+ if (this.$scope.catalogFilterdItems) {
+ this.$scope.isAllItemDisplay = this.$scope.numberOfItemToDisplay >= this.$scope.catalogFilterdItems.length;
+ }
+ };
+
+ this.$scope.gui.onGroupClick = (subCategory:ISubCategory):void => {
+ // Mark | Un mark the parent when all childs selected.
+ if (this.areAllSubCategoryChildsSelected(subCategory)) {
+ // Add the category to checkboxesFilter.selectedCategoriesModel
+ this.$scope.checkboxesFilter.selectedCategoriesModel.push(subCategory.uniqueId);
+ } else {
+ this.$scope.checkboxesFilter.selectedCategoriesModel = _.without(this.$scope.checkboxesFilter.selectedCategoriesModel, subCategory.uniqueId);
+ }
+ };
+
+
+ };
+
+ private areAllCategoryChildsSelected = (category:IMainCategory):boolean => {
+ if (!category.subcategories) {
+ return false;
+ }
+ let allIds = _.map(category.subcategories, (sub:ISubCategory)=> {
+ return sub.uniqueId;
+ });
+ let total = _.intersection(this.$scope.checkboxesFilter.selectedCategoriesModel, allIds);
+ return total.length === category.subcategories.length ? true : false;
+ };
+
+ private areAllSubCategoryChildsSelected = (subCategory:ISubCategory):boolean => {
+ if (!subCategory.groupings) {
+ return false;
+ }
+ let allIds = _.map(subCategory.groupings, (group:IGroup)=> {
+ return group.uniqueId;
+ });
+ let total = _.intersection(this.$scope.checkboxesFilter.selectedCategoriesModel, allIds);
+ return total.length === subCategory.groupings.length ? true : false;
+ };
+
+ private isCategorySelected = (uniqueId:string):boolean => {
+ if (this.$scope.checkboxesFilter.selectedCategoriesModel.indexOf(uniqueId) !== -1) {
+ return true;
+ }
+ return false;
+ };
+}
diff --git a/catalog-ui/app/scripts/view-models/catalog/catalog-view.html b/catalog-ui/src/app/view-models/catalog/catalog-view.html
index 0d46dc2a24..03ca4cb81f 100644
--- a/catalog-ui/app/scripts/view-models/catalog/catalog-view.html
+++ b/catalog-ui/src/app/view-models/catalog/catalog-view.html
@@ -54,11 +54,10 @@
<span class="i-sdc-designer-leftbar-section-title-text" data-tests-id="categoriesFilterTitle">Categories</span>
</div>
<div class="i-sdc-designer-leftbar-section-content">
-
<!-- CATEGORY CHECKBOX -->
<ul class="list-unstyled i-sdc-designer-leftbar-section-content-ul">
<li class="i-sdc-designer-leftbar-section-content-ul-li"
- data-ng-repeat="category in categories track by category.uniqueId | categoryTypeFilter:checkboxesFilter.selectedComponentTypes | orderBy: category">
+ data-ng-repeat="category in categories | categoryTypeFilter:checkboxesFilter.selectedComponentTypes:checkboxesFilter.selectedResourceSubTypes | orderBy: category">
<sdc-checkbox elem-id="checkbox-{{category.uniqueId | lowercase | clearWhiteSpaces}}"
sdc-checklist-model="checkboxesFilter.selectedCategoriesModel"
@@ -136,7 +135,7 @@
<!-- HEADER -->
<div>
<div class="w-sdc-dashboard-catalog-header">
- {{getNumOfElements((catalogFilterdItems | entityFilter:checkboxesFilter | filter:search).length)}}
+ {{getNumOfElements((catalogFilterdItems| filter:{resourceType:('!'+vfcmtType)} | entityFilter:checkboxesFilter | filter:search).length)}}
</div>
<div class="w-sdc-dashboard-catalog-header-right">
<span class="w-sdc-dashboard-catalog-header-order" translate="SORT_CAPTION"></span>&nbsp;&nbsp;
@@ -151,35 +150,43 @@
</div>
<div infinite-scroll-disabled='isAllItemDisplay' infinite-scroll="raiseNumberOfElementToDisplay()" infinite-scroll-container="'#catalog-main-scroll'" infinite-scroll-parent>
- <!-- CARDS -->
- <div data-ng-class="{'sdc-hide-popover': hidePopover}"
- data-ng-init="component.filterTerm = component.name + ' ' + component.description + ' ' + component.tags.toString() + ' ' + component.version"
- class="w-sdc-dashboard-card"
- data-ng-repeat="component in catalogFilterdItems | entityFilter:checkboxesFilter | filter:search | orderBy:sortBy:reverse | limitTo:numberOfItemToDisplay"
- data-ng-class="{'resource' : component.isResource(), 'service' : component.isService(), 'product' : component.isProduct()}">
-
- <div class="w-sdc-dashboard-card-body" data-ng-click="gui.isLoading || goToComponent(component)">
- <div class="w-sdc-dashboard-card-avatar"><span data-tests-id="asset-type" class="{{component.getComponentSubType()}}"></span></div>
- <!--<div class="w-sdc-dashboard-card-edit " data-ng-class="component.lifecycleState" data-tests-id="assetlifecycleState {{getStatus()}}"></div>-->
- <div class="w-sdc-dashboard-card-schema-image {{component.icon}}" data-tests-id="{{component.categories[0].subcategories[0].uniqueId}}" data-ng-class="{'sprite-resource-icons':component.isResource(), 'sprite-services-icons':component.isService(), 'sprite-product-icons':component.isProduct()}"></div>
- <!--<div class="w-sdc-dashboard-card-description">{{component.description}}</div>-->
- <div class="w-sdc-dashboard-card-info-name-container">
- <span class="w-sdc-dashboard-card-info-name" tooltips
- tooltip-content="{{component.name | resourceName}}"> {{component.name | resourceName}}</span>
- </div>
- </div>
- <div class="w-sdc-dashboard-card-footer">
- <div class="w-sdc-dashboard-card-info">
- <div class="w-sdc-dashboard-card-info-lifecycleState">
- <span class="w-sdc-dashboard-card-info-lifecycleState" tooltips
- tooltip-content="{{component.getStatus(sdcMenu)}}"> {{component.getStatus(sdcMenu)}}</span>
+ <div class='w-sdc-row-flex-items'>
+
+ <!-- Tile new -->
+ <div data-ng-init="component.filterTerm = component.name + ' ' + component.description + ' ' + component.tags.toString() + ' ' + component.version"
+ class="sdc-tile-catalog sdc-tile-fix-width"
+ data-ng-repeat="component in catalogFilterdItems| filter:{resourceType:('!'+vfcmtType)} | entityFilter:checkboxesFilter | filter:search | orderBy:sortBy:reverse | limitTo:numberOfItemToDisplay"
+ >
+
+ <div class="sdc-tile-header">
+ <div class='sdc-tile-header-type' data-ng-class="{'purple': component.isResource(), 'blue': !component.isResource()}">
+ <div data-ng-if="component.isResource()" data-tests-id="asset-type">{{component.getComponentSubType()}}</div>
+ <div data-ng-if="component.isService()">S</div>
+ </div>
+ </div>
+ <div class='sdc-tile-content' data-ng-click="gui.isLoading || goToComponent(component)">
+ <div class='sdc-tile-content-icon'>
+ <div class="{{component.iconSprite}} {{component.icon}}"
+ data-ng-class="{'sprite-resource-icons': component.isResource(), 'sprite-services-icons': component.isService()}"
+ data-tests-id="{{component.name}}"></div>
+ </div>
+ <div class='sdc-tile-content-info'>
+ <div class="sdc-tile-content-info-item-name" data-tests-id="{{component.name | resourceName}}" sdc-smart-tooltip>{{component.name | resourceName}}</div>
+ <div class="sdc-tile-content-info-version-info">
+ <div class="sdc-tile-content-info-version-info-text" data-tests-id="{{component.name}}Version">V {{component.version}}</div>
+ </div>
</div>
- <div class="w-sdc-dashboard-card-info-user">V {{component.version}}</div>
</div>
- <!--<div class="w-sdc-dashboard-card-info-lifecycleState-icon sprite-new {{sdcMenu.LifeCycleStatuses[component.lifecycleState].icon}}"></div>-->
+ <div class='sdc-tile-footer'>
+ <div class='sdc-tile-footer-text'>{{component.getStatus(sdcMenu)}}</div>
+ </div>
+
</div>
+ <!-- Tile new -->
+
</div>
+
</div>
</perfect-scrollbar>
@@ -187,4 +194,6 @@
<top-nav top-lvl-selected-index="1" search-bind="search.filterTerm" version="{{version}}"></top-nav>
+ <ecomp-footer></ecomp-footer>
+
</div>
diff --git a/catalog-ui/app/scripts/view-models/catalog/catalog.less b/catalog-ui/src/app/view-models/catalog/catalog.less
index 8be90a6a59..9db9192167 100644
--- a/catalog-ui/app/scripts/view-models/catalog/catalog.less
+++ b/catalog-ui/src/app/view-models/catalog/catalog.less
@@ -83,7 +83,7 @@
&.NOT_CERTIFIED_CHECKOUT,
&.NOT_CERTIFIED_CHECKIN {
.i-sdc-categories-list-item-icon {
- background: url('../../../styles/images/sprites/sprite-global-old.png') no-repeat -53px -2889px;
+ background: url('/assets/styles/images/sprites/sprite-global-old.png') no-repeat -53px -2889px;
width: 14px;
height: 14px;
@@ -92,7 +92,7 @@
&.CERTIFIED {
.i-sdc-categories-list-item-icon {
- background: url('../../../styles/images/sprites/sprite-global-old.png') no-repeat -53px -3034px;
+ background: url('/assets/styles/images/sprites/sprite-global-old.png') no-repeat -53px -3034px;
width: 14px;
height: 16px;
}
@@ -100,7 +100,7 @@
&.READY_FOR_CERTIFICATION {
.i-sdc-categories-list-item-icon {
- background: url('../../../styles/images/sprites/sprite-global-old.png') no-repeat -53px -2985px;
+ background: url('/assets/styles/images/sprites/sprite-global-old.png') no-repeat -53px -2985px;
width: 14px;
height: 16px;
}
@@ -108,7 +108,7 @@
&.CERTIFICATION_IN_PROGRESS {
.i-sdc-categories-list-item-icon {
- background: url('../../../styles/images/sprites/sprite-global-old.png') no-repeat -53px -2934px;
+ background: url('/assets/styles/images/sprites/sprite-global-old.png') no-repeat -53px -2934px;
width: 14px;
height: 16px;
}
@@ -117,7 +117,7 @@
&.DISTRIBUTED,
&.TBD {
.i-sdc-categories-list-item-icon {
- background: url('../../../styles/images/sprites/sprite-global-old.png') no-repeat -43px -3087px;
+ background: url('/assets/styles/images/sprites/sprite-global-old.png') no-repeat -43px -3087px;
width: 24px;
height: 14px;
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
new file mode 100644
index 0000000000..d0b74a9062
--- /dev/null
+++ b/catalog-ui/src/app/view-models/dashboard/dashboard-view-model.ts
@@ -0,0 +1,387 @@
+'use strict';
+import {IConfigRoles, IAppConfigurtaion, IAppMenu, IUserProperties, Component} from "app/models";
+import {EntityService, IUserResourceClass, SharingService, CacheService} from "app/services";
+import {ComponentType, ResourceType, MenuHandler, ModalsHandler, ChangeLifecycleStateHandler, SEVERITY, ComponentFactory} from "app/utils";
+import {IClientMessageModalModel} from "../modals/message-modal/message-client-modal/client-message-modal-view-model";
+
+export interface IDashboardViewModelScope extends ng.IScope {
+
+ isLoading:boolean;
+ components:Array<Component>;
+ folders:FoldersMenu;
+ roles:IConfigRoles;
+ user:IUserProperties;
+ sdcConfig:IAppConfigurtaion;
+ sdcMenu:IAppMenu;
+ sharingService:SharingService;
+ showTutorial:boolean;
+ isFirstTime:boolean;
+ version:string;
+ checkboxesFilter:CheckboxesFilter;
+ vfcmtType:string;
+
+
+ onImportVfc(file:any):void;
+ onImportVf(file:any):void;
+ openCreateModal(componentType:ComponentType, importedFile:any):void;
+ openWhatsNewModal(version:string):void;
+ openDesignerModal(isResource:boolean, uniqueId:string):void;
+ setSelectedFolder(folderItem:FoldersItemsMenu):void;
+ entitiesCount(folderItem:FoldersItemsMenu):number;
+ getCurrentFolderDistributed():Array<Component>;
+ changeLifecycleState(entity:any, data:any):void;
+ goToComponent(component:Component):void;
+ wizardDebugEdit:Function;
+ notificationIconCallback:Function;
+}
+
+interface CheckboxesFilter {
+ // Statuses
+ selectedStatuses:Array<string>;
+ // distributed
+ distributed:Array<string>;
+}
+
+export interface IItemMenu {
+
+}
+
+export interface IMenuItemProperties {
+ text:string;
+ group:string;
+ state:string;
+ dist:string;
+ groupname:string;
+ states:Array<any>;
+}
+
+export class FoldersMenu {
+
+ private _folders:Array<FoldersItemsMenu> = [];
+
+ constructor(folders:Array<IMenuItemProperties>) {
+ let self = this;
+ folders.forEach(function (folder:IMenuItemProperties) {
+ if (folder.groupname) {
+ self._folders.push(new FoldersItemsMenuGroup(folder));
+ } else {
+ self._folders.push(new FoldersItemsMenu(folder));
+ }
+ });
+ self._folders[0].setSelected(true);
+ }
+
+ public getFolders = ():Array<FoldersItemsMenu> => {
+ return this._folders;
+ };
+
+ public getCurrentFolder = ():FoldersItemsMenu => {
+ let menuItem:FoldersItemsMenu = undefined;
+ this.getFolders().forEach(function (tmpFolder:FoldersItemsMenu) {
+ if (tmpFolder.isSelected()) {
+ menuItem = tmpFolder;
+ }
+ });
+ return menuItem;
+ };
+
+ public setSelected = (folder:FoldersItemsMenu):void => {
+ this.getFolders().forEach(function (tmpFolder:FoldersItemsMenu) {
+ tmpFolder.setSelected(false);
+ });
+ folder.setSelected(true);
+ }
+
+}
+
+export class FoldersItemsMenu implements IItemMenu {
+
+ public text:string;
+ public group:string;
+ public state:string;
+ public dist:string;
+ public states:Array<any>;
+
+ private selected:boolean = false;
+
+ constructor(menuProperties:IMenuItemProperties) {
+ this.text = menuProperties.text;
+ this.group = menuProperties.group;
+ this.state = menuProperties.state;
+ this.states = menuProperties.states;
+ this.dist = menuProperties.dist;
+ }
+
+ public isSelected = ():boolean => {
+ return this.selected;
+ };
+
+ public setSelected = (value:boolean):void => {
+ this.selected = value;
+ };
+
+ public isGroup = ():boolean => {
+ return false;
+ }
+
+}
+
+export class FoldersItemsMenuGroup extends FoldersItemsMenu {
+
+ public groupname:string;
+
+ constructor(menuProperties:IMenuItemProperties) {
+ super(menuProperties);
+ this.groupname = menuProperties.groupname;
+ }
+
+ public isGroup = ():boolean => {
+ return true;
+ }
+
+}
+
+export class DashboardViewModel {
+ static '$inject' = [
+ '$scope',
+ '$filter',
+ 'Sdc.Services.EntityService',
+ '$http',
+ 'sdcConfig',
+ 'sdcMenu',
+ '$state',
+ '$stateParams',
+ 'Sdc.Services.UserResourceService',
+ 'Sdc.Services.SharingService',
+ 'Sdc.Services.CacheService',
+ '$q',
+ 'ComponentFactory',
+ 'ChangeLifecycleStateHandler',
+ 'ModalsHandler',
+ 'MenuHandler'
+ ];
+
+ private components:Array<Component>;
+
+ constructor(private $scope:IDashboardViewModelScope,
+ private $filter:ng.IFilterService,
+ private entityService:EntityService,
+ private $http:ng.IHttpService,
+ private sdcConfig:IAppConfigurtaion,
+ private sdcMenu:IAppMenu,
+ private $state:any,
+ private $stateParams:any,
+ private userResourceService:IUserResourceClass,
+ private sharingService:SharingService,
+ private cacheService:CacheService,
+ private $q:ng.IQService,
+ private ComponentFactory:ComponentFactory,
+ private ChangeLifecycleStateHandler:ChangeLifecycleStateHandler,
+ private ModalsHandler:ModalsHandler,
+ private MenuHandler:MenuHandler) {
+ this.initScope();
+ this.initFolders();
+ this.initEntities(true);
+
+ if (this.$stateParams) {
+
+ if (this.$state.params.folder) {
+ let self = this;
+ let folderName = this.$state.params.folder.replaceAll("_", " ");
+
+ this.$scope.folders.getFolders().forEach(function (tmpFolder:FoldersItemsMenu) {
+ if (tmpFolder.text === folderName) {
+ self.$scope.setSelectedFolder(tmpFolder);
+ }
+ });
+ }
+
+ // Show the tutorial if needed when the dashboard page is opened.<script src="bower_components/angular-filter/dist/angular-filter.min.js"></script>
+ // This is called from the welcome page.
+ else if (this.$stateParams.show === 'tutorial') {
+ this.$scope.showTutorial = true;
+ this.$scope.isFirstTime = true;
+ }
+ }
+ }
+
+ private initFolders = ():void => {
+ if (this.$scope.user) {
+ this.$scope.folders = new FoldersMenu(this.$scope.roles[this.$scope.user.role].folder);
+ }
+ };
+
+ private initScope = ():void => {
+ let self = this;
+
+ this.$scope.version = this.cacheService.get('version');
+ this.$scope.sharingService = this.sharingService;
+ this.$scope.isLoading = false;
+ this.$scope.sdcConfig = this.sdcConfig;
+ this.$scope.sdcMenu = this.sdcMenu;
+ this.$scope.user = this.userResourceService.getLoggedinUser();
+ this.$scope.roles = this.sdcMenu.roles;
+ this.$scope.showTutorial = false;
+ this.$scope.isFirstTime = false;
+ this.$scope.vfcmtType = ResourceType.VFCMT;
+
+ // Open onboarding modal
+ this.$scope.notificationIconCallback = ():void => {
+ this.ModalsHandler.openOnboadrdingModal('Import').then(()=> {
+ // OK
+ }, ()=> {
+ // ERROR
+ });
+ };
+
+ // Checkboxes filter init
+ this.$scope.checkboxesFilter = <CheckboxesFilter>{};
+ this.$scope.checkboxesFilter.selectedStatuses = [];
+ this.$scope.checkboxesFilter.distributed = [];
+
+ this.$scope.onImportVf = (file:any):void => {
+ if (file && file.filename) {
+ // Check that the file has valid extension.
+ let fileExtension:string = file.filename.split(".").pop();
+ if (this.sdcConfig.csarFileExtension.indexOf(fileExtension.toLowerCase()) !== -1) {
+ this.$state.go('workspace.general', {
+ type: ComponentType.RESOURCE.toLowerCase(),
+ importedFile: file,
+ resourceType: ResourceType.VF
+ });
+ } else {
+ let data:IClientMessageModalModel = {
+ title: self.$filter('translate')("NEW_SERVICE_RESOURCE_ERROR_VALID_CSAR_EXTENSIONS_TITLE"),
+ message: self.$filter('translate')("NEW_SERVICE_RESOURCE_ERROR_VALID_CSAR_EXTENSIONS", "{'extensions': '" + this.sdcConfig.csarFileExtension + "'}"),
+ severity: SEVERITY.ERROR
+ };
+ this.ModalsHandler.openClientMessageModal(data);
+ }
+ }
+ };
+
+ this.$scope.onImportVfc = (file:any):void => {
+ if (file && file.filename) {
+ // Check that the file has valid extension.
+ let fileExtension:string = file.filename.split(".").pop();
+ if (this.sdcConfig.toscaFileExtension.indexOf(fileExtension.toLowerCase()) !== -1) {
+ this.$state.go('workspace.general', {
+ type: ComponentType.RESOURCE.toLowerCase(),
+ importedFile: file,
+ resourceType: ResourceType.VFC
+ });
+ } else {
+ let data:IClientMessageModalModel = {
+ title: self.$filter('translate')("NEW_SERVICE_RESOURCE_ERROR_VALID_TOSCA_EXTENSIONS_TITLE"),
+ message: self.$filter('translate')("NEW_SERVICE_RESOURCE_ERROR_VALID_TOSCA_EXTENSIONS", "{'extensions': '" + this.sdcConfig.toscaFileExtension + "'}"),
+ severity: SEVERITY.ERROR
+ };
+ this.ModalsHandler.openClientMessageModal(data);
+ }
+ }
+ };
+
+ this.$scope.openCreateModal = (componentType:string, importedFile:any):void => {
+ if (importedFile) {
+ this.initEntities(true); // Return from import
+ } else {
+ this.$state.go('workspace.general', {type: componentType.toLowerCase()});
+ }
+
+ };
+
+ this.$scope.entitiesCount = (folderItem:FoldersItemsMenu):any => {
+ let self = this;
+ let total:number = 0;
+ if (folderItem.isGroup()) {
+ this.$scope.folders.getFolders().forEach(function (tmpFolder:FoldersItemsMenu) {
+ if (tmpFolder.group && tmpFolder.group === (<FoldersItemsMenuGroup>folderItem).groupname) {
+ total = total + self._getTotalCounts(tmpFolder, self);
+ }
+ });
+ } else {
+ total = total + self._getTotalCounts(folderItem, self);
+ }
+ return total;
+ };
+
+ this.$scope.getCurrentFolderDistributed = ():Array<any> => {
+ let self = this;
+ let states = [];
+ if (this.$scope.folders) {
+ let folderItem:FoldersItemsMenu = this.$scope.folders.getCurrentFolder();
+ if (folderItem.isGroup()) {
+ this.$scope.folders.getFolders().forEach(function (tmpFolder:FoldersItemsMenu) {
+ if (tmpFolder.group && tmpFolder.group === (<FoldersItemsMenuGroup>folderItem).groupname) {
+ self._setStates(tmpFolder, states);
+ }
+ });
+ } else {
+ self._setStates(folderItem, states);
+ }
+ }
+ return states;
+ };
+
+ this.$scope.setSelectedFolder = (folderItem:FoldersItemsMenu):void => {
+ this.$scope.folders.setSelected(folderItem);
+ };
+
+ this.$scope.goToComponent = (component:Component):void => {
+ this.$scope.isLoading = true;
+ this.$state.go('workspace.general', {id: component.uniqueId, type: component.componentType.toLowerCase()});
+ };
+
+ };
+
+ private _getTotalCounts(tmpFolder, self):number {
+ let total:number = 0;
+ if (tmpFolder.dist !== undefined) {
+ let distributions = tmpFolder.dist.split(',');
+ distributions.forEach((item:any) => {
+ total = total + self.getEntitiesByStateDist(tmpFolder.state, item).length;
+ });
+ }
+ else {
+ total = total + self.getEntitiesByStateDist(tmpFolder.state, tmpFolder.dist).length;
+ }
+ return total;
+ }
+
+ private _setStates(tmpFolder, states) {
+ if (tmpFolder.states !== undefined) {
+ tmpFolder.states.forEach(function (item:any) {
+ states.push({"state": item.state, "dist": item.dist});
+ });
+ } else {
+ states.push({"state": tmpFolder.state, "dist": tmpFolder.dist});
+ }
+ }
+
+ private initEntities = (reload:boolean):void => {
+ this.$scope.isLoading = reload;
+ this.entityService.getAllComponents().then(
+ (components:Array<Component>) => {
+ this.components = components;
+ this.$scope.components = components;
+ this.$scope.isLoading = false;
+ });
+ };
+
+ private getEntitiesByStateDist = (state:string, dist:string):Array<Component> => {
+ let gObj:Array<Component>;
+ if (this.components && (state || dist)) {
+ gObj = this.components.filter(function (obj:Component) {
+ if (dist !== undefined && obj.distributionStatus === dist && obj.lifecycleState === state) {
+ return true;
+ } else if (dist === undefined && obj.lifecycleState === state) {
+ return true;
+ }
+ return false;
+ });
+ } else {
+ gObj = [];
+ }
+ return gObj;
+ }
+}
diff --git a/catalog-ui/src/app/view-models/dashboard/dashboard-view.html b/catalog-ui/src/app/view-models/dashboard/dashboard-view.html
new file mode 100644
index 0000000000..806bb8138d
--- /dev/null
+++ b/catalog-ui/src/app/view-models/dashboard/dashboard-view.html
@@ -0,0 +1,112 @@
+
+<div class="sdc-catalog-container">
+ <loader data-display="isLoading"></loader>
+ <!-- HEADER -->
+<!--
+ <ecomp-header menu-data="menuItems" version="{{version}}"></ecomp-header>
+-->
+
+ <div class="w-sdc-main-container">
+
+ <perfect-scrollbar include-padding="true" class="w-sdc-main-right-container">
+
+ <div class='w-sdc-row-flex-items'>
+
+ <!-- ADD Component -->
+ <div ng-if="user.role === 'DESIGNER' || user.role === 'PRODUCT_MANAGER'" class="w-sdc-dashboard-card-new"
+ data-ng-mouseleave="displayActions = false"
+ data-ng-mouseover="displayActions = true"
+ data-ng-init="displayActions = false">
+ <div class="w-sdc-dashboard-card-new-content" data-tests-id="AddButtonsArea">
+ <div class="w-sdc-dashboard-card-new-content-plus" data-ng-show="!displayActions"></div>
+ <div class="sdc-dashboard-create-element-container" data-ng-show="displayActions">
+ <button data-ng-if="roles[user.role].dashboard.showCreateNewProduct" data-tests-id="createProductButton" class="tlv-btn outline blue" data-ng-click="openCreateModal('PRODUCT')">Create Product</button>
+ <button data-ng-if="roles[user.role].dashboard.showCreateNew" data-tests-id="createResourceButton" class="tlv-btn outline blue" data-ng-click="openCreateModal('RESOURCE')">Add VF</button>
+ <button data-ng-if="roles[user.role].dashboard.showCreateNew" data-tests-id="createServiceButton" class="tlv-btn outline blue" data-ng-click="openCreateModal('SERVICE')">Add Service</button>
+ </div>
+ </div>
+ </div>
+
+ <!-- Import Component -->
+ <div ng-if="user.role === 'DESIGNER'" class="w-sdc-dashboard-card-new"
+ data-ng-mouseleave="displayActions = false"
+ data-ng-mouseover="displayActions = true"
+ data-ng-init="displayActions = false">
+ <div class="w-sdc-dashboard-card-new-content" data-tests-id="importButtonsArea" >
+ <div class="w-sdc-dashboard-card-import-content-plus" data-ng-show="!displayActions"></div>
+ <div class="sdc-dashboard-import-element-container" data-ng-show="displayActions">
+ <div data-ng-if="roles[user.role].dashboard.showCreateNew" class="tlv-btn outline blue">Import VFC
+ <file-opener on-file-upload="onImportVfc(file)" data-tests-id="importVFCbutton" extensions="{{sdcConfig.toscaFileExtension}}" data-ng-click="displayActions=false"></file-opener>
+ </div>
+ <div data-ng-if="roles[user.role].dashboard.showCreateNew" class="tlv-btn outline blue" data-ng-click="notificationIconCallback()">Import VSP</div>
+ <div data-ng-if="roles[user.role].dashboard.showCreateNew" class="tlv-btn outline blue import-dcae">Import DCAE asset
+ <file-opener on-file-upload="onImportVf(file)" data-tests-id="importVFbutton" extensions="{{sdcConfig.csarFileExtension}}" data-ng-click="displayActions=false"></file-opener>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- Tile new -->
+ <div class="sdc-tile-catalog sdc-tile-fix-width" data-ng-repeat="component in components | filter:{resourceType:('!'+vfcmtType)} | entityFilter:checkboxesFilter | filter:search">
+
+ <div class="sdc-tile-header">
+ <div class='sdc-tile-header-type' data-ng-class="{'purple': component.isResource(), 'blue': !component.isResource()}">
+ <div data-ng-if="component.isResource()" data-tests-id="asset-type">{{component.getComponentSubType()}}</div>
+ <div data-ng-if="component.isService()">S</div>
+ </div>
+ </div>
+ <div class='sdc-tile-content' data-tests-id="dashboard-Elements" data-ng-click="goToComponent(component)">
+ <div class='sdc-tile-content-icon'>
+ <div class="{{component.iconSprite}} {{component.icon}}"
+ data-ng-class="{'sprite-resource-icons': component.isResource(), 'sprite-services-icons': component.isService()}"
+ data-tests-id="{{component.name}}"></div>
+ </div>
+ <div class='sdc-tile-content-info'>
+ <div class="sdc-tile-content-info-item-name" data-tests-id="{{component.name | resourceName}}" sdc-smart-tooltip>{{component.name | resourceName}}</div>
+ <div class="sdc-tile-content-info-version-info">
+ <div class="sdc-tile-content-info-version-info-text" data-tests-id="{{component.name}}Version">V {{component.version}}</div>
+ </div>
+ </div>
+ </div>
+ <div class='sdc-tile-footer'>
+ <div class='sdc-tile-footer-text'>{{component.getStatus(sdcMenu)}}</div>
+ </div>
+
+ </div>
+ <!-- Tile new -->
+
+ </div>
+
+ </perfect-scrollbar>
+
+ <div class="w-sdc-left-sidebar">
+ <div class="i-sdc-left-sidebar-item "
+ data-ng-repeat="folder in folders.getFolders()"
+ data-ng-class="{'category-title': folder.isGroup(), 'selectedLink': folder.isSelected()}"
+ >
+ <span data-ng-if="folder.isGroup()">{{folder.text}}</span>
+
+ <sdc-checkbox data-ng-if="!folder.isGroup() && !folder.dist"
+ elem-id="checkbox-{{folder.text | lowercase | clearWhiteSpaces}}"
+ sdc-checklist-model="checkboxesFilter.selectedStatuses"
+ sdc-checklist-value="folder.state"
+ text="{{folder.text}}"></sdc-checkbox>
+
+ <sdc-checkbox data-ng-if="!folder.isGroup() && folder.dist"
+ elem-id="checkbox-{{folder.text | lowercase | clearWhiteSpaces}}"
+ sdc-checklist-model="checkboxesFilter.distributed"
+ sdc-checklist-value="folder.dist"
+ text="{{folder.text}}"></sdc-checkbox>
+ <span class="i-sdc-left-sidebar-item-state-count">{{entitiesCount(folder)}}</span>
+ </div>
+ </div>
+
+ </div>
+
+ <top-nav top-lvl-selected-index="0" version="{{version}}" search-bind="search.filterTerm" notification-icon-callback="notificationIconCallback" version="{{version}}"></top-nav>
+
+</div>
+<div data-ui-view=""></div>
+
+
+<ecomp-footer></ecomp-footer>
diff --git a/catalog-ui/app/scripts/view-models/dashboard/dashboard.less b/catalog-ui/src/app/view-models/dashboard/dashboard.less
index 7b2522113b..7993390769 100644
--- a/catalog-ui/app/scripts/view-models/dashboard/dashboard.less
+++ b/catalog-ui/src/app/view-models/dashboard/dashboard.less
@@ -42,11 +42,11 @@
.border-radius(2px);
cursor: pointer;
display: inline-block;
- height: 200px;
- margin: 9px;
+ height: 198px;
+ margin: 11px;
position: relative;
vertical-align: middle;
- width: 204px;
+ width: 202px;
}
.w-sdc-dashboard-card-new-content {
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
new file mode 100644
index 0000000000..9be7786f4d
--- /dev/null
+++ b/catalog-ui/src/app/view-models/dcae-app/dcae-app-view-model.ts
@@ -0,0 +1,112 @@
+'use strict';
+import {MenuItemGroup, MenuItem} from "app/utils";
+import {BreadcrumbsPath, BreadcrumbsMenu} from "../onboard-vendor/onboard-vendor-view-model";
+import {CacheService} from "app/services";
+import {IUserProperties} from "app/models";
+
+export class TestData {
+ breadcrumbs:BreadcrumbsPath;
+}
+
+export interface IDcaeAppViewModelScope extends ng.IScope {
+ testData:TestData;
+ onTestEvent:Function;
+ topNavMenuModel:Array<MenuItemGroup>;
+ topNavRootMenu:MenuItemGroup;
+ user:IUserProperties;
+ version:string;
+}
+
+export class DcaeAppViewModel {
+ static '$inject' = [
+ '$scope',
+ '$q',
+ 'Sdc.Services.CacheService'
+ ];
+
+ private firstControlledTopNavMenu:MenuItemGroup;
+
+ constructor(private $scope:IDcaeAppViewModelScope,
+ private $q:ng.IQService,
+ private cacheService:CacheService) {
+
+ this.$scope.testData = {
+ breadcrumbs: {
+ selectedKeys: []
+ }
+ };
+
+ this.$scope.version = this.cacheService.get('version');
+
+ this.$scope.onTestEvent = (eventName:string, data:any):void => {
+ switch (eventName) {
+ case 'breadcrumbsupdated':
+ this.handleBreadcrumbsUpdate(data);
+ break;
+ }
+ };
+
+ this.$scope.topNavMenuModel = [];
+
+ this.$scope.user = this.cacheService.get('user');
+ }
+
+ updateBreadcrumbsPath = (selectedKeys:Array<string>):ng.IPromise<boolean> => {
+ let topNavMenuModel = this.$scope.topNavMenuModel;
+ let startIndex = topNavMenuModel.indexOf(this.firstControlledTopNavMenu);
+ if (startIndex === -1) {
+ startIndex = topNavMenuModel.length;
+ }
+ topNavMenuModel.splice(startIndex + selectedKeys.length);
+ this.$scope.testData = {
+ breadcrumbs: {selectedKeys: selectedKeys}
+ };
+
+ return this.$q.when(true);
+ };
+
+ handleBreadcrumbsUpdate(breadcrumbsMenus:Array<BreadcrumbsMenu>):void {
+ let selectedKeys = [];
+ let topNavMenus = breadcrumbsMenus.map((breadcrumbMenu, breadcrumbIndex) => {
+ let topNavMenu = new MenuItemGroup();
+ topNavMenu.menuItems = breadcrumbMenu.menuItems.map(menuItem =>
+ new MenuItem(
+ menuItem.displayText,
+ this.updateBreadcrumbsPath,
+ null,
+ null,
+ [selectedKeys.concat([menuItem.key])]
+ )
+ );
+ topNavMenu.selectedIndex = _.findIndex(
+ breadcrumbMenu.menuItems,
+ menuItem => menuItem.key === breadcrumbMenu.selectedKey
+ );
+ selectedKeys.push(breadcrumbMenu.selectedKey);
+ return topNavMenu;
+ });
+
+ let topNavMenuModel = this.$scope.topNavMenuModel;
+ let len = topNavMenuModel.length;
+ let startIndex = topNavMenuModel.indexOf(this.firstControlledTopNavMenu);
+ if (startIndex === -1) {
+ startIndex = len;
+ }
+ topNavMenuModel.splice(startIndex, len - startIndex);
+ topNavMenuModel.push.apply(topNavMenuModel, topNavMenus);
+ this.firstControlledTopNavMenu = topNavMenus[0];
+
+ if (startIndex === 1 && this.$scope.topNavRootMenu == null) {
+ let topNavRootMenu = topNavMenuModel[0];
+ let onboardItem = topNavRootMenu.menuItems[topNavRootMenu.selectedIndex];
+ let originalCallback = onboardItem.callback;
+ onboardItem.callback = (...args) => {
+ let ret = this.updateBreadcrumbsPath([]);
+ return originalCallback && originalCallback.apply(undefined, args) || ret;
+ };
+ this.$scope.topNavRootMenu = topNavRootMenu;
+ }
+
+ this.updateBreadcrumbsPath(selectedKeys);
+ }
+}
diff --git a/catalog-ui/src/app/view-models/dcae-app/dcae-app-view.html b/catalog-ui/src/app/view-models/dcae-app/dcae-app-view.html
new file mode 100644
index 0000000000..af0d06787a
--- /dev/null
+++ b/catalog-ui/src/app/view-models/dcae-app/dcae-app-view.html
@@ -0,0 +1,17 @@
+<div class="sdc-catalog-container">
+
+ <loader data-display="gui.isLoading"></loader>
+<!--
+ <ecomp-header menu-data="menuItems" version="{{version}}"></ecomp-header>
+-->
+
+ <div class="w-sdc-main-container">
+ <!--<div ng-include="'/dcaeapp/index.html'"/>-->
+ <!--<div id="dcaeAppContainer"></div>-->
+ <!--<punch-out name="'dcaeApp'" data="vendorData" user="user" on-event="onTestEvent"></punch-out>-->
+ <div id="main" ui-view="main"></div>
+ </div>
+
+ <top-nav top-lvl-selected-index="3" search-bind="search.filterTerm" menu-model="topNavMenuModel" version="{{version}}"></top-nav>
+
+</div>
diff --git a/catalog-ui/src/app/view-models/dcae-app/dcae-app.less b/catalog-ui/src/app/view-models/dcae-app/dcae-app.less
new file mode 100644
index 0000000000..4a16ca2b5b
--- /dev/null
+++ b/catalog-ui/src/app/view-models/dcae-app/dcae-app.less
@@ -0,0 +1,303 @@
+.sdc-catalog-container {
+
+ .i-sdc-categories-list-item {
+ font-weight: normal;
+ }
+
+ // Checkboxes
+ .i-sdc-designer-leftbar-section-content-ul {
+ padding: 0;
+ margin: 0;
+
+ .i-sdc-catalog-subcategories-checkbox {
+ padding: 0 0 0 20px;
+ margin: 0;
+
+ .i-sdc-catalog-grouping-checkbox {
+ padding: 0 0 0 20px;
+ margin: 0;
+ }
+
+ }
+
+ }
+
+ .i-sdc-designer-leftbar-section-content-li {
+ &:last-child {
+ .i-sdc-categories-list-item {
+ margin: 0;
+ }
+ }
+ }
+
+ .i-sdc-categories-list-item {
+ display: block;
+ //margin-bottom: 5px;
+ //padding-left: 15px;
+ //text-indent: -24px;
+ vertical-align: top;
+ font-weight: bold;
+ }
+
+ .i-sdc-subcategories-list-item {
+ display: block;
+ //padding-left: 20px;
+ vertical-align: top;
+ font-weight: normal;
+ margin: 0;
+ //text-indent: -10px;
+ }
+
+ /*Added by - Ikram */
+ .i-sdc-product-input,
+ .i-sdc-product-select {
+ border: 1px solid @border_color_f;
+ min-height: 30px;
+ padding: 0;
+ width: 100%;
+ margin: 1px 0;
+ background-color: #F2F2F2;
+ outline: none;
+
+ &:disabled {
+ .disabled;
+ }
+ optgroup{
+ color: @color_u;
+ option{
+ color: @color_b;
+ }
+ }
+ }
+
+ .i-sdc-categories-list-item-icon {
+ display: inline-block;
+ float: right;
+ position: relative;
+ right: -8px;
+ top: 6px;
+ }
+
+ .i-sdc-categories-list-item {
+ margin-top: 7px;
+ &.NOT_CERTIFIED_CHECKOUT,
+ &.NOT_CERTIFIED_CHECKIN {
+ .i-sdc-categories-list-item-icon {
+ background: url('/assets/styles/images/sprites/sprite-global-old.png') no-repeat -53px -2889px;
+ width: 14px;
+ height: 14px;
+
+ }
+ }
+
+ &.CERTIFIED {
+ .i-sdc-categories-list-item-icon {
+ background: url('/assets/styles/images/sprites/sprite-global-old.png') no-repeat -53px -3034px;
+ width: 14px;
+ height: 16px;
+ }
+ }
+
+ &.READY_FOR_CERTIFICATION {
+ .i-sdc-categories-list-item-icon {
+ background: url('/assets/styles/images/sprites/sprite-global-old.png') no-repeat -53px -2985px;
+ width: 14px;
+ height: 16px;
+ }
+ }
+
+ &.CERTIFICATION_IN_PROGRESS {
+ .i-sdc-categories-list-item-icon {
+ background: url('/assets/styles/images/sprites/sprite-global-old.png') no-repeat -53px -2934px;
+ width: 14px;
+ height: 16px;
+ }
+ }
+
+ &.DISTRIBUTED,
+ &.TBD {
+ .i-sdc-categories-list-item-icon {
+ background: url('/assets/styles/images/sprites/sprite-global-old.png') no-repeat -43px -3087px;
+ width: 24px;
+ height: 14px;
+
+ }
+ }
+ }
+
+ .i-sdc-categories-list-input {
+ margin: 8px;
+
+ }
+
+ .i-sdc-subcategories-list-input {
+
+ margin: 8px;
+ }
+ .i-sdc-subcategories-list-input-container {
+ margin: 0px 0px 0px 20px;
+ padding: 2px;
+ }
+
+ .w-sdc-header-catalog-search-container {
+ display: table;
+ padding: 21px 0;
+ position: relative;
+
+ .w-sdc-designer-leftbar-search-input {
+ color: #000;
+ width: 300px;
+ }
+
+ // .magnification {
+ // .sprite;
+ // .sprite.magnification-glass;
+ // .hand;
+ // position: absolute;
+ // top: 40px;
+ // right: 42px;
+ // }
+ }
+
+ .w-sdc-catalog-main {
+ padding: 10px 12px;
+ }
+ .w-sdc-dashboard-catalog-header {
+ .b_9;
+ display: inline-block;
+ font-style: italic;
+ font-weight: bold;
+ padding-left: 10px;
+ }
+
+ .w-sdc-dashboard-catalog-header-order {
+ .b_9;
+ font-weight: 800;
+ }
+
+ .w-sdc-dashboard-catalog-sort {
+ .b_9;
+ font-weight: bold;
+ white-space:pre;
+ &:hover{
+ .hand;
+ text-decoration: none;
+ .a_9;
+ }
+ &.blue {
+ .a_9;
+ }
+ }
+
+ .w-sdc-catalog-sort-arrow{
+ display: inline-block;
+ &.up{
+ .b_9;
+ width: 0;
+ height: 0;
+ border-left: 5px solid transparent;
+ border-right: 5px solid transparent;
+ border-bottom: 5px solid ;
+ }
+ &.down{
+ .b_9;
+ width: 0;
+ height: 0;
+ border-left: 5px solid transparent;
+ border-right: 5px solid transparent;
+ border-top: 5px solid;
+ }
+ }
+
+
+
+
+ .w-sdc-dashboard-catalog-header-right{
+ float: right;
+ display: inline-block;
+ padding-right:34px;
+ }
+
+ .w-sdc-header-catalog-search-input {
+ width: 420px;
+ display: table-cell;
+ padding: 0 25px 1px 10px;
+ border: 1px solid #bcbcbc;
+ .border-radius(10px);
+ height: 30px;
+ margin: 10px 30px;
+ outline: none;
+ }
+
+ .sdc-catalog-type-filter-container {
+ margin-top: -1px;
+ }
+
+ .i-sdc-designer-leftbar-section-title {
+ text-transform: uppercase;
+ .l_14_m;
+ line-height: 30px;
+ }
+
+ .i-sdc-designer-leftbar-section-title-icon {
+ .hand;
+ .tlv-sprite;
+ .footer-close;
+ transition: .3s all;
+ margin-top: -4px;
+ }
+
+ .i-sdc-designer-leftbar-section-title-text {
+ margin-left: 20px;
+ }
+
+ .seperator-left,
+ .seperator-right {
+ border-right: solid 1px @color_m;
+ display: table-cell;
+ width: 2px;
+ }
+
+ // Rotate catalog left side arrows
+ .i-sdc-designer-leftbar-section-title.expanded .i-sdc-designer-leftbar-section-title-icon {
+ transform: rotate(180deg);
+ }
+
+ // Transform catalog left side sections
+ .i-sdc-designer-leftbar-section-title + .i-sdc-designer-leftbar-section-content {
+ max-height: 0px;
+ margin: 0 auto;
+ transition: all .3s;
+ overflow: hidden;
+ padding: 0 10px 0 18px;
+ }
+
+ .i-sdc-designer-leftbar-section-title.expanded + .i-sdc-designer-leftbar-section-content {
+ max-height: 9999px;
+ margin: 0 auto 1px;
+ transition: all .3s;
+ padding: 10px 18px 10px 18px;
+ overflow: hidden;
+ }
+
+}
+
+.w-sdc-search-icon{
+ position: absolute;
+ right: 40px;
+ top: 40px;
+ &.leftbar{
+ top: 19px;
+ right: 18px;
+ }
+ &.magnification {
+ .sprite;
+ .sprite.magnification-glass;
+ .hand;
+ }
+ &.cancel {
+ .sprite;
+ .sprite.clear-text;
+ .hand;
+ }
+}
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
new file mode 100644
index 0000000000..3e912706e0
--- /dev/null
+++ b/catalog-ui/src/app/view-models/forms/artifact-form/artifact-form-view-model.ts
@@ -0,0 +1,358 @@
+'use strict';
+import {ArtifactModel, Resource, Component} from "app/models";
+import {ArtifactsUtils, FormState, ValidationUtils, ArtifactType} from "app/utils";
+import {CacheService} from "app/services";
+
+export interface IEditArtifactModel {
+ artifactResource:ArtifactModel;
+ artifactTypes:Array<string>;
+ artifactFile:any;
+}
+
+export interface IArtifactResourceFormViewModelScope extends ng.IScope {
+ forms:any;
+ $$childTail:any;
+ isNew:boolean;
+ isLoading:boolean;
+ validationPattern:RegExp;
+ urlValidationPattern:RegExp;
+ labelValidationPattern:RegExp;
+ integerValidationPattern:RegExp;
+ commentValidationPattern:RegExp;
+ artifactType:string;
+ editArtifactResourceModel:IEditArtifactModel;
+ defaultHeatTimeout:number;
+ validExtensions:any;
+ originalArtifactName:string;
+ editForm:ng.IFormController;
+ footerButtons:Array<any>;
+ modalInstanceArtifact:ng.ui.bootstrap.IModalServiceInstance;
+
+ fileExtensions():string;
+ save(doNotCloseModal?:boolean):void;
+ saveAndAnother():void;
+ close():void;
+ getOptions():Array<string>;
+ isDeploymentHeat():boolean;
+ onFileChange():void;
+ setDefaultTimeout():void;
+ openEditEnvParametersModal(artifact:ArtifactModel):void;
+ getFormTitle():string;
+ fileUploadRequired():string;
+ isArtifactOwner():boolean;
+}
+
+export class ArtifactResourceFormViewModel {
+
+ static '$inject' = [
+ '$scope',
+ '$uibModalInstance',
+ 'artifact',
+ 'Sdc.Services.CacheService',
+ 'ValidationPattern',
+ 'UrlValidationPattern',
+ 'LabelValidationPattern',
+ 'IntegerValidationPattern',
+ 'CommentValidationPattern',
+ 'ValidationUtils',
+ '$base64',
+ '$state',
+ 'ArtifactsUtils',
+ '$uibModal',
+ 'component'
+ ];
+
+ private formState:FormState;
+ private entityId:string;
+
+ constructor(private $scope:IArtifactResourceFormViewModelScope,
+ private $uibModalInstance:ng.ui.bootstrap.IModalServiceInstance,
+ private artifact:ArtifactModel,
+ private cacheService:CacheService,
+ private ValidationPattern:RegExp,
+ private UrlValidationPattern:RegExp,
+ private LabelValidationPattern:RegExp,
+ private IntegerValidationPattern:RegExp,
+ private CommentValidationPattern:RegExp,
+ private ValidationUtils:ValidationUtils,
+ private $base64:any,
+ private $state:any,
+ private artifactsUtils:ArtifactsUtils,
+ private $uibModal:ng.ui.bootstrap.IModalService,
+ private component:Component) {
+
+
+ this.entityId = this.component.uniqueId;
+ this.formState = angular.isDefined(artifact.artifactLabel) ? FormState.UPDATE : FormState.CREATE;
+ this.initScope();
+ }
+
+ private initEntity = ():void => {
+ this.$scope.editArtifactResourceModel.artifactResource = this.artifact;
+ this.$scope.originalArtifactName = this.artifact.artifactName;
+ };
+
+
+ private initFooterButtons = ():void => {
+
+ this.$scope.footerButtons = [
+ {'name': 'Done', 'css': 'blue', 'callback': this.$scope.save}
+ ];
+ if (this.$scope.isNew) {
+ this.$scope.footerButtons.push({
+ 'name': 'Add Another',
+ 'css': 'grey',
+ 'disabled': !this.$scope.isNew && 'deployment' === this.$scope.artifactType,
+ 'callback': this.$scope.saveAndAnother
+ });
+ }
+ };
+
+ private filterDeploymentArtifactTypeByResourceType = (resourceType:string):any => {
+ let result = {};
+ _.each(this.$scope.validExtensions, function (typeSettings:any, typeName:string) {
+ if (!typeSettings.validForResourceTypes || typeSettings.validForResourceTypes.indexOf(resourceType) > -1) {
+ result[typeName] = typeSettings;
+ }
+ });
+
+ return result;
+ };
+
+ private initArtifactTypes = ():void => {
+
+ let artifactTypes:any = this.cacheService.get('UIConfiguration');
+
+ if ('deployment' === this.$scope.artifactType) {
+
+
+ if ('HEAT_ENV' == this.artifact.artifactType || this.component.selectedInstance) {
+ this.$scope.validExtensions = artifactTypes.artifacts.deployment.resourceInstanceDeploymentArtifacts;
+ } else if (this.component.isResource()) {
+ this.$scope.validExtensions = artifactTypes.artifacts.deployment.resourceDeploymentArtifacts;
+ this.$scope.validExtensions = this.filterDeploymentArtifactTypeByResourceType((<Resource>this.component).resourceType);
+ } else {
+ this.$scope.validExtensions = artifactTypes.artifacts.deployment.serviceDeploymentArtifacts;
+ }
+
+ if (this.$scope.validExtensions) {
+ this.$scope.editArtifactResourceModel.artifactTypes = Object.keys(this.$scope.validExtensions);
+ }
+ this.$scope.defaultHeatTimeout = artifactTypes.defaultHeatTimeout;
+ if (this.$scope.isNew) {
+ let isHeat = 'HEAT_ENV' == this.artifact.artifactType;
+ _.remove(this.$scope.editArtifactResourceModel.artifactTypes, (item:string)=> {
+ return 'HEAT' == item.substring(0, 4) || (!isHeat && item == "VF_MODULES_METADATA") ||
+ _.has(ArtifactType.THIRD_PARTY_RESERVED_TYPES, item);
+ });
+ }
+
+ }
+ if (this.$scope.artifactType === 'informational') {
+ this.$scope.editArtifactResourceModel.artifactTypes = artifactTypes.artifacts.other.map((element:any)=> {
+ return element.name;
+ });
+ _.remove(this.$scope.editArtifactResourceModel.artifactTypes, (item:string)=> {
+ return _.has(ArtifactType.THIRD_PARTY_RESERVED_TYPES, item) ||
+ _.has(ArtifactType.TOSCA, item);
+ })
+ }
+
+ if (this.component.isResource() && (<Resource>this.component).isCsarComponent()) {
+ _.remove(this.$scope.editArtifactResourceModel.artifactTypes, (item:string) => {
+ return this.artifactsUtils.isLicenseType(item);
+ })
+ }
+
+ };
+
+ private initEditArtifactResourceModel = ():void => {
+ this.$scope.editArtifactResourceModel = {
+ artifactResource: null,
+ artifactTypes: null,
+ artifactFile: {}
+ };
+
+ this.initEntity();
+ };
+
+ private initScope = ():void => {
+
+ this.$scope.validationPattern = this.ValidationPattern;
+ this.$scope.urlValidationPattern = this.UrlValidationPattern;
+ this.$scope.labelValidationPattern = this.LabelValidationPattern;
+ this.$scope.integerValidationPattern = this.IntegerValidationPattern;
+ this.$scope.commentValidationPattern = this.CommentValidationPattern;
+ this.$scope.isLoading = false;
+ this.$scope.isNew = (this.formState === FormState.CREATE);
+ this.$scope.artifactType = this.artifactsUtils.getArtifactTypeByState(this.$state.current.name);
+ this.$scope.modalInstanceArtifact = this.$uibModalInstance;
+
+ this.initEditArtifactResourceModel();
+ this.initArtifactTypes();
+
+ // In case of edit, show the file name in browse.
+ if (this.artifact.artifactName !== "" && 'HEAT_ENV' !== this.artifact.artifactType) {
+ this.$scope.editArtifactResourceModel.artifactFile = {};
+ this.$scope.editArtifactResourceModel.artifactFile.filename = this.artifact.artifactName;
+ }
+
+ //scope methods
+ this.$scope.isDeploymentHeat = ():boolean => {
+ return !this.$scope.isNew && this.$scope.artifactType === 'deployment'
+ && this.$scope.editArtifactResourceModel.artifactResource.isHEAT();
+
+ };
+ this.$scope.onFileChange = ():void => {
+ if (this.$scope.editArtifactResourceModel.artifactFile && this.$scope.editArtifactResourceModel.artifactFile.filename) {
+ this.$scope.editArtifactResourceModel.artifactResource.artifactName = this.$scope.editArtifactResourceModel.artifactFile.filename;
+ } else {
+ this.$scope.editArtifactResourceModel.artifactResource.artifactName = this.$scope.originalArtifactName;
+ }
+ };
+ this.$scope.setDefaultTimeout = ():void => {
+ if (this.$scope.isDeploymentHeat() && !this.$scope.editArtifactResourceModel.artifactResource.timeout) {
+ this.$scope.editArtifactResourceModel.artifactResource.timeout = this.$scope.defaultHeatTimeout;
+ }
+
+ if (this.$scope.editArtifactResourceModel.artifactFile.filename) {
+ this.$scope.editArtifactResourceModel.artifactFile = {};
+ this.$scope.forms.editForm.myArtifactFile.$setValidity('required', false);
+ }
+ };
+
+ this.$scope.fileExtensions = ():string => {
+ let type:string = this.$scope.editArtifactResourceModel.artifactResource.artifactType;
+ return type && this.$scope.validExtensions && this.$scope.validExtensions[type].acceptedTypes ?
+ this.$scope.validExtensions[type].acceptedTypes.join(',') : "";
+ };
+
+ this.$scope.save = (doNotCloseModal?:boolean):void => {
+ this.$scope.isLoading = true;
+ this.$scope.editArtifactResourceModel.artifactResource.description = this.ValidationUtils.stripAndSanitize(this.$scope.editArtifactResourceModel.artifactResource.description);
+
+ if (!this.$scope.isDeploymentHeat()) {
+ this.$scope.editArtifactResourceModel.artifactResource.timeout = null;
+ }
+
+ if (this.$scope.editArtifactResourceModel.artifactFile) {
+ this.$scope.editArtifactResourceModel.artifactResource.payloadData = this.$scope.editArtifactResourceModel.artifactFile.base64;
+ this.$scope.editArtifactResourceModel.artifactResource.artifactName = this.$scope.editArtifactResourceModel.artifactFile.filename;
+ }
+
+ let onFaild = (response):void => {
+ this.$scope.isLoading = false;
+ console.info('onFaild', response);
+ };
+
+ let onSuccess = (artifactResource:ArtifactModel):void => {
+ this.$scope.isLoading = false;
+ this.$scope.originalArtifactName = "";
+
+ if (this.$scope.isDeploymentHeat()) {
+ if (artifactResource.heatParameters) {
+ this.$scope.openEditEnvParametersModal(artifactResource);
+ }
+ }
+
+ if (!doNotCloseModal) {
+ this.$uibModalInstance.close();
+ } else {
+ this.$scope.editArtifactResourceModel.artifactFile = null;
+ angular.element("input[type='file']").val(null); // for support chrome when upload the same file
+ this.artifactsUtils.addAnotherAfterSave(this.$scope);
+ }
+
+ };
+
+ if ('HEAT_ENV' == this.artifact.artifactType) {
+ if (this.component.selectedInstance) {
+ this.component.uploadInstanceEnvFile(this.$scope.editArtifactResourceModel.artifactResource).then(onSuccess, onFaild);
+ } else {
+ this.component.addOrUpdateArtifact(this.$scope.editArtifactResourceModel.artifactResource).then(onSuccess, onFaild);
+
+ }
+ } else if (this.$scope.isArtifactOwner()) {
+ this.component.addOrUpdateInstanceArtifact(this.$scope.editArtifactResourceModel.artifactResource).then(onSuccess, onFaild);
+ } else {
+ this.component.addOrUpdateArtifact(this.$scope.editArtifactResourceModel.artifactResource).then(onSuccess, onFaild);
+ }
+ };
+
+ this.$scope.isArtifactOwner = ():boolean=> {
+ return this.component.isService() && !!this.component.selectedInstance;
+ };
+
+ this.$scope.saveAndAnother = ():void => {
+ this.$scope.save(true);
+ };
+
+ this.$scope.close = ():void => {
+ this.$uibModalInstance.close();
+ };
+
+ this.$scope.fileUploadRequired = ():string => {
+ if (this.$scope.editArtifactResourceModel.artifactFile.filename) {
+ // This is edit mode
+ return 'false';
+ } else {
+ return 'true';
+ }
+ };
+
+ this.$scope.getFormTitle = ():string => {
+ if ('HEAT_ENV' == this.artifact.artifactType) {
+ return 'Update HEAT ENV';
+ }
+ if (this.$scope.isDeploymentHeat()) {
+ if (!this.$scope.editArtifactResourceModel.artifactResource.artifactChecksum) {
+ return 'Add HEAT Template';
+ }
+ return 'Update HEAT Template';
+ }
+ if (this.$scope.isNew) {
+ return 'Add Artifact';
+ }
+ return 'Update Artifact';
+ };
+
+ this.$scope.openEditEnvParametersModal = (artifactResource:ArtifactModel):void => {
+
+ let modalOptions:ng.ui.bootstrap.IModalSettings = {
+ templateUrl: '../env-parameters-form/env-parameters-form.html',
+ controller: 'Sdc.ViewModels.EnvParametersFormViewModel',
+ size: 'sdc-md',
+ backdrop: 'static',
+ resolve: {
+ artifact: ():ArtifactModel => {
+ return artifactResource;
+ },
+ component: ():Component => {
+ return this.component;
+ }
+ }
+ };
+
+ let modalInstance:ng.ui.bootstrap.IModalServiceInstance = this.$uibModal.open(modalOptions);
+ modalInstance
+ .result
+ .then(():void => {
+ });
+ };
+
+ this.$scope.forms = {};
+
+ this.initFooterButtons();
+
+
+ this.$scope.$watch("forms.editForm.$invalid", (newVal, oldVal) => {
+ if(this.$scope.forms.editForm) {
+ this.$scope.footerButtons[0].disabled = this.$scope.forms.editForm.$invalid;
+ if (this.$scope.isNew) {
+ this.$scope.footerButtons[1].disabled = this.$scope.forms.editForm.$invalid;
+ }
+ }
+ });
+
+ }
+}
diff --git a/catalog-ui/app/scripts/view-models/forms/artifact-form/artifact-form-view.html b/catalog-ui/src/app/view-models/forms/artifact-form/artifact-form-view.html
index 74a19c8776..0984c6872d 100644
--- a/catalog-ui/app/scripts/view-models/forms/artifact-form/artifact-form-view.html
+++ b/catalog-ui/src/app/view-models/forms/artifact-form/artifact-form-view.html
@@ -1,4 +1,4 @@
-<sdc-modal modal="modalInstanceArtifact" type="classic" class="sdc-add-artifact" buttons="footerButtons" header="{{getFormTitle()}}" show-close-button="true" get-close-modal-response="close">
+<sdc-modal modal="modalInstanceArtifact" type="classic" class="sdc-add-artifact" buttons="footerButtons" header="{{getFormTitle()}}" show-close-button="true" get-close-modal-response="close" data-tests-id="sdc-add-artifact">
<loader data-display="isLoading"></loader>
@@ -19,7 +19,7 @@
data-ng-class="{'error': forms.editForm.myArtifactFile.$dirty && forms.editForm.myArtifactFile.$invalid}"></file-upload>
<div class="input-error-file-upload" data-ng-show="forms.editForm.myArtifactFile.$dirty && forms.editForm.myArtifactFile.$invalid">
- <span ng-show="forms.editForm.myArtifactFile.$error.required && !forms.editForm.myArtifactFile.$error.emptyFile" translate="ADD_ARTIFACT_ERROR_FILE_REQUIRED"></span>
+ <span ng-show="forms.editForm.myArtifactFile.$error.required || forms.editForm.myArtifactFile.$error.emptyFile" translate="ADD_ARTIFACT_ERROR_FILE_REQUIRED"></span>
<span ng-show="forms.editForm.myArtifactFile.$error.maxsize" translate="VALIDATION_ERROR_MAX_FILE_SIZE"></span>
<span ng-if="artifactType === 'deployment'" ng-show="forms.editForm.myArtifactFile.$error.filetype" translate="ADD_ARTIFACT_ERROR_VALID_EXTENSIONS" translate-values="{'extensions': '{{fileExtensions()}}' }"></span>
<span ng-show="forms.editForm.myArtifactFile.$error.emptyFile" translate="VALIDATION_ERROR_EMPTY_FILE"></span>
@@ -45,7 +45,7 @@
data-ng-pattern="labelValidationPattern"
maxlength="25"
data-ng-disabled="!isNew"
- data-tests-id="artifact-label"
+ data-tests-id="artifactLabel"
autofocus/>
<div class="input-error" data-ng-show="forms.editForm.artifactLabel.$dirty && forms.editForm.artifactLabel.$invalid">
diff --git a/catalog-ui/app/scripts/view-models/forms/artifact-form/artifact-form.less b/catalog-ui/src/app/view-models/forms/artifact-form/artifact-form.less
index 1f77958c88..1f77958c88 100644
--- a/catalog-ui/app/scripts/view-models/forms/artifact-form/artifact-form.less
+++ b/catalog-ui/src/app/view-models/forms/artifact-form/artifact-form.less
diff --git a/catalog-ui/app/scripts/view-models/forms/attribute-form/attribute-form-view.html b/catalog-ui/src/app/view-models/forms/attribute-form/attribute-form-view.html
index 432b32fbd3..90b8f67df4 100644
--- a/catalog-ui/app/scripts/view-models/forms/attribute-form/attribute-form-view.html
+++ b/catalog-ui/src/app/view-models/forms/attribute-form/attribute-form-view.html
@@ -106,11 +106,10 @@
data-ng-maxlength="100"
data-ng-disabled="editAttributeModel.attribute.readonly && !isAttributeValueOwner()"
maxlength="100"
- data-ng-model="editAttributeModel.attribute[isAttributeValueOwner()?'value':'defaultValue']"
+ data-ng-model="attributeValue.value"
type="text"
name="value"
data-custom-validation="" data-validation-func="validateUniqueKeys"
- data-tests-id="defaultvalue"
data-ng-pattern="validationPattern"
data-ng-model-options="{ debounce: 200 }"
data-ng-change="!forms.editForm.value.$error.pattern && ('integer'==editAttributeModel.attribute.type && forms.editForm.value.$setValidity('pattern', validateIntRange(editAttributeModel.attribute.value)) || onValueChange())"
@@ -121,7 +120,7 @@
data-ng-disabled="editAttributeModel.attribute.readonly && !isAttributeValueOwner()"
name="value"
data-ng-change="onValueChange()"
- data-ng-model="editAttributeModel.attribute[isAttributeValueOwner()?'value':'defaultValue']">
+ data-ng-model="attributeValue.value">
<option value="true">true</option>
<option value="false">false</option>
</select>
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
new file mode 100644
index 0000000000..122cf10ed2
--- /dev/null
+++ b/catalog-ui/src/app/view-models/forms/attribute-form/attribute-from-view-model.ts
@@ -0,0 +1,241 @@
+'use strict';
+import {AttributeModel, Component} from "app/models";
+import {IMapRegex, ValidationUtils, FormState, PROPERTY_TYPES} from "app/utils";
+
+export interface IEditAttributeModel {
+ attribute:AttributeModel;
+ types:Array<string>;
+ simpleTypes:Array<string>;
+}
+
+export class attributeValue {//in order to solve DE226783, we update the value on another obj
+ value:string;
+}
+
+interface IAttributeFormViewModelScope extends ng.IScope {
+ $$childTail:any;
+ forms:any;
+ editForm:ng.IFormController;
+ footerButtons:Array<any>;
+ isService:boolean;
+ editAttributeModel:IEditAttributeModel;
+ modalInstanceAttribute:ng.ui.bootstrap.IModalServiceInstance;
+ isNew:boolean;
+ listRegex:IMapRegex;
+ mapRegex:IMapRegex;
+ propertyNameValidationPattern:RegExp;
+ commentValidationPattern:RegExp;
+ isLoading:boolean;
+ validationPattern:RegExp;
+ attributeValue:attributeValue;
+
+ save():void;
+ close():void;
+ onTypeChange():void;
+ onValueChange():void;
+ isAttributeValueOwner():boolean;
+ validateIntRange(value:string):boolean;
+ validateUniqueKeys(viewValue:string):boolean;
+ getValidationTranslate():string;
+ showSchema():boolean;
+ isSchemaEditable():boolean;
+ validateName():void;
+}
+
+export class AttributeFormViewModel {
+
+ static '$inject' = [
+ '$scope',
+ '$uibModalInstance',
+ 'attribute',
+ 'ValidationUtils',
+ 'CommentValidationPattern',
+ 'PropertyNameValidationPattern',
+ 'component'
+ ];
+
+ private formState:FormState;
+
+
+ constructor(private $scope:IAttributeFormViewModelScope,
+ private $uibModalInstance:ng.ui.bootstrap.IModalServiceInstance,
+ private attribute:AttributeModel,
+ private ValidationUtils:ValidationUtils,
+ private CommentValidationPattern:RegExp,
+ private PropertyNameValidationPattern:RegExp,
+ private component:Component) {
+ this.formState = angular.isDefined(attribute.name) ? FormState.UPDATE : FormState.CREATE;
+ this.initScope();
+ }
+
+ private initResource = ():void => {
+ this.$scope.editAttributeModel.attribute = new AttributeModel(this.attribute);
+ if (this.$scope.editAttributeModel.types.indexOf(this.attribute.type) === -1) {//attribute defaulte type is string too?
+ this.attribute.type = "string";
+ }
+ };
+
+ private initEditAttributeModel = ():void => {
+ this.$scope.editAttributeModel = {
+ attribute: null,
+ types: ['integer', 'string', 'float', 'boolean', 'list', 'map'],
+ simpleTypes: ['integer', 'string', 'float', 'boolean']
+ };
+
+ this.initResource();
+ };
+
+ private initScope = ():void => {
+
+ //scope attributes
+ this.$scope.forms = {};
+ this.$scope.propertyNameValidationPattern = this.PropertyNameValidationPattern;
+ this.$scope.commentValidationPattern = this.CommentValidationPattern;
+
+ this.$scope.modalInstanceAttribute = this.$uibModalInstance;
+ this.$scope.listRegex = this.ValidationUtils.getPropertyListPatterns();
+ this.$scope.mapRegex = this.ValidationUtils.getPropertyMapPatterns();
+
+ this.$scope.isNew = (this.formState === FormState.CREATE);
+ this.$scope.isLoading = false;
+ this.$scope.attributeValue = new attributeValue();
+
+ this.initEditAttributeModel();
+ this.setValidationPattern();
+
+ //scope methods
+ this.$scope.save = ():void => {
+ if (!this.$scope.forms.editForm.$invalid) {
+ let attribute:AttributeModel = this.$scope.editAttributeModel.attribute;
+ this.$scope.editAttributeModel.attribute.description = this.ValidationUtils.stripAndSanitize(this.$scope.editAttributeModel.attribute.description);
+ ////if read only - just closes the modal
+ if (this.$scope.editAttributeModel.attribute.readonly && !this.$scope.isAttributeValueOwner()) {
+ this.$uibModalInstance.close();
+ return;
+ }
+ this.$scope.isLoading = true;
+ let onAttributeFaild = (response):void => {
+ console.info('onFaild', response);
+ this.$scope.isLoading = false;
+ };
+
+ let onAttributeSuccess = (attributeFromBE:AttributeModel):void => {
+ console.info('onAttributeResourceSuccess : ', attributeFromBE);
+ this.$scope.isLoading = false;
+ this.$uibModalInstance.close();
+ };
+
+ //in case we have uniqueId we call update method
+ if (this.$scope.isAttributeValueOwner()) {
+ attribute.value = this.$scope.attributeValue.value;
+ this.component.updateInstanceAttribute(attribute).then(onAttributeSuccess, onAttributeFaild);
+ } else {
+ attribute.defaultValue = this.$scope.attributeValue.value;
+ this.component.addOrUpdateAttribute(attribute).then(onAttributeSuccess, onAttributeFaild);
+ }
+ }
+ };
+
+ this.$scope.close = ():void => {
+ this.$uibModalInstance.close();
+ };
+
+ this.$scope.validateName = ():void => {
+ let existsAttr:AttributeModel = _.find(this.component.attributes, (attribute:AttributeModel) => {
+ return attribute.name === this.$scope.editAttributeModel.attribute.name;
+ });
+ if (existsAttr) {
+ this.$scope.forms.editForm["attributeName"].$setValidity('nameExist', false);
+ } else {
+ this.$scope.forms.editForm["attributeName"].$setValidity('nameExist', true);
+ }
+
+ };
+
+ this.$scope.onTypeChange = ():void => {
+ this.$scope.editAttributeModel.attribute.value = '';
+ this.$scope.editAttributeModel.attribute.defaultValue = '';
+ this.setValidationPattern();
+ };
+
+ this.$scope.isAttributeValueOwner = ():boolean=> {
+ return this.component.isService() || !!this.component.selectedInstance;
+ };
+
+ this.$scope.onValueChange = ():void => {
+ if (!this.$scope.editAttributeModel.attribute.value) {
+ if (this.$scope.isAttributeValueOwner()) {
+ this.$scope.editAttributeModel.attribute.value = this.$scope.editAttributeModel.attribute.defaultValue;
+ }
+ }
+ };
+
+
+ this.$scope.validateUniqueKeys = (viewValue:string):boolean => {
+ if (this.$scope.editAttributeModel.attribute.type === 'map') {
+ return this.ValidationUtils.validateUniqueKeys(viewValue);
+ }
+ else {
+ return true; //always valid if not a map
+ }
+ };
+
+ this.$scope.validateIntRange = (value:string):boolean => {
+ return !value || this.ValidationUtils.validateIntRange(value);
+ };
+
+ this.$scope.isSchemaEditable = ():boolean => {
+ let schemaType = this.$scope.editAttributeModel.attribute.schema.property.type;
+ return this.$scope.editAttributeModel.simpleTypes.indexOf(schemaType) > -1 || !schemaType;
+ };
+
+ this.$scope.showSchema = ():boolean => {
+ return ['list', 'map'].indexOf(this.$scope.editAttributeModel.attribute.type) > -1;
+ };
+
+ this.$scope.getValidationTranslate = ():string => {
+ let result = "ATTRIBUTE_EDIT_PATTERN";
+ if (this.$scope.showSchema()) {
+
+ result = "ATTRIBUTE_EDIT_" + this.$scope.editAttributeModel.attribute.type.toUpperCase();
+
+ if (this.$scope.editAttributeModel.attribute.schema.property.type === PROPERTY_TYPES.STRING) {
+ result += "_STRING";
+ } else if (this.$scope.editAttributeModel.attribute.schema.property.type === PROPERTY_TYPES.BOOLEAN) {
+ result += "_BOOLEAN";
+ } else {
+ result += "_GENERIC";
+ }
+ }
+
+ return result;
+ };
+
+ // Add the done button at the footer.
+ this.$scope.footerButtons = [
+ {'name': 'Done', 'css': 'blue', 'callback': this.$scope.save},
+ {'name': 'Cancel', 'css': 'grey', 'callback': this.$scope.close}
+ ];
+
+ this.$scope.$watchCollection("forms.editForm.$invalid", (newVal, oldVal) => {
+ this.$scope.footerButtons[0].disabled = this.$scope.forms.editForm.$invalid;
+ });
+
+ this.$scope.attributeValue.value = this.$scope.isAttributeValueOwner() ? this.$scope.editAttributeModel.attribute.value : this.$scope.editAttributeModel.attribute.defaultValue;
+ };
+
+
+ private setValidationPattern = ():void => {
+
+ if (this.$scope.editAttributeModel.attribute.type === 'list') {
+ this.$scope.validationPattern = this.$scope.listRegex[this.$scope.editAttributeModel.attribute.schema.property.type];
+ }
+ else if (this.$scope.editAttributeModel.attribute.type === 'map') {
+ this.$scope.validationPattern = this.$scope.mapRegex[this.$scope.editAttributeModel.attribute.schema.property.type];
+ }
+ else {
+ this.$scope.validationPattern = this.ValidationUtils.getValidationPattern(this.$scope.editAttributeModel.attribute.type);
+ }
+
+ };
+}
diff --git a/catalog-ui/src/app/view-models/forms/env-parameters-form/env-parameters-form.html b/catalog-ui/src/app/view-models/forms/env-parameters-form/env-parameters-form.html
new file mode 100644
index 0000000000..ae13844532
--- /dev/null
+++ b/catalog-ui/src/app/view-models/forms/env-parameters-form/env-parameters-form.html
@@ -0,0 +1,92 @@
+<sdc-modal modal="envParametersModal" type="classic" class="sdc-env-form-container" buttons="buttons" header="{{artifactResource.artifactDisplayName}}" show-close-button="true">
+ <div class="w-sdc-env-form-container">
+ <div class="w-sdc-env-search pull-left">
+ <input type="text" class="w-sdc-env-search-input" placeholder="Search" data-ng-model="searchText" data-tests-id="search-env-param-name"/>
+ <div class="search-icon-container">
+ <span class="w-sdc-search-icon env-search-icon magnification-white"></span>
+ </div>
+ </div>
+ <div class="table-container-flex">
+ <div class="table">
+ <div class="head flex-container">
+ <div class="table-header head-row flex-item" ng-repeat="header in tableHeadersList track by $index">
+ <info-tooltip class="header-info" data-ng-if="header.info" class="info-button" info-message-translate="{{header.info}}" direction="left"></info-tooltip>
+ {{header.title}}
+ </div>
+ </div>
+ <div class="body">
+ <perfect-scrollbar suppress-scroll-x="true" scroll-y-margin-offset="0" include-padding="true" class="scrollbar-container">
+ <ng-form name="forms.editForm" class="w-sdc-form">
+ <div data-ng-repeat="parameter in heatParameters| filter:{filterTerm:searchText} track by $index "
+ class="flex-container data-row"
+ data-ng-init="parameter.filterTerm=parameter.name + ' ' + parameter.currentValue + ' ' + parameter.defaultValue + ' ' +parameter.description">
+ <div class="table-col-general flex-item" data-tests-id="heatParameterName_{{parameter.name}}">
+ {{parameter.name}}
+ <span class="sprite-new show-desc hand"
+ uib-popover-template="templatePopover"
+ popover-class="parameter-description-popover top"
+ popover-title="Parameter Description"
+ popover-placement="top-left"
+ popover-is-open="selectedParameter.name == parameter.name"
+ popover-trigger="'none'"
+ popover-append-to-body="true"
+ data-ng-click="openDescPopover(parameter)"></span>
+ </div>
+
+ <div class="table-col-general flex-item text">
+ <span data-tests-id="default-value-of-{{parameter.name}}" tooltips tooltip-content="{{parameter.defaultValue}}">{{parameter.defaultValue}}</span>
+ </div>
+
+ <!--<div class="table-col-general flex-item">-->
+ <!--<input type="text" value="{{parameter.currentValue}}"/>-->
+ <!--</div>-->
+
+ <div class="table-col-general flex-item left-column-container">
+
+ <div class="i-sdc-form-item" data-ng-class="{error:(forms.editForm[parameter.name].$dirty && forms.editForm[parameter.name].$invalid), required: (parameter.defaultValue)}">
+ <span class="required-symbol">*</span>
+ <div class="input-parameter">
+ <input class="i-sdc-form-input" data-ng-class="{error: (forms.editForm[parameter.name].$invalid)}"
+ data-ng-model-options="{ debounce: 200 }"
+ data-ng-model="parameter.currentValue"
+ value="{{parameter.currentValue}}"
+ type="text"
+ name="{{parameter.name}}"
+ data-ng-pattern="getValidationPattern(parameter.type, 'heat')"
+ data-ng-required="parameter.defaultValue"
+ data-ng-change="'json'==parameter.type && forms.editForm[parameter.name].$setValidity('pattern', validateJson(parameter.currentValue))"
+ data-ng-blur="(forms.editForm[parameter.name].$error.required && (parameter.currentValue=parameter.defaultValue))"
+ data-tests-id="value-field-of-{{parameter.name}}"/>
+
+ <div class="action-button">
+ <div class="sprite-new revert-param" data-ng-if="parameter.defaultValue" data-ng-click="parameter.currentValue = parameter.defaultValue"
+ data-tests-id="revert-{{parameter.name}}">
+ </div>
+ <div class="sprite-new delete-param"
+ data-ng-if="!parameter.defaultValue"
+ data-ng-disabled="!parameter.currentValue"
+ data-ng-class="{disabled:!parameter.currentValue}"
+ data-ng-click="parameter.currentValue = ''"
+ data-tests-id="delete-{{parameter.name}}">
+ </div>
+ </div>
+ </div>
+ <div class="input-error" data-ng-show="forms.editForm[parameter.name].$invalid">
+ <span ng-show="forms.editForm[parameter.name].$error.required" translate="VALIDATION_ERROR_REQUIRED" translate-values="{'field': 'Value'}"></span>
+ <span ng-show="forms.editForm[parameter.name].$error.pattern && parameter.type==='string'" translate="VALIDATION_ERROR_SPECIAL_CHARS_NOT_ALLOWED"></span>
+ <span ng-show="forms.editForm[parameter.name].$error.pattern && !(parameter.type==='string')" translate="VALIDATION_ERROR_TYPE" translate-values="{'type': '{{parameter.type}}'}"></span>
+ </div>
+ </div>
+
+ </div>
+
+ </div>
+ </ng-form>
+
+ </perfect-scrollbar>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+</sdc-modal>
diff --git a/catalog-ui/src/app/view-models/forms/env-parameters-form/env-parameters-form.less b/catalog-ui/src/app/view-models/forms/env-parameters-form/env-parameters-form.less
new file mode 100644
index 0000000000..a25a2c5f62
--- /dev/null
+++ b/catalog-ui/src/app/view-models/forms/env-parameters-form/env-parameters-form.less
@@ -0,0 +1,178 @@
+
+.sdc-env-form-container{
+ .w-sdc-modal-body{
+ padding: 20px 10px 2px 10px;
+ }
+ .w-sdc-modal-body-content{
+ .b_6;
+ display: block;
+ }
+
+ .env-file-generation-label{
+ .p_9;
+ .bold;
+ margin-bottom: 20px;
+ }
+}
+
+.w-sdc-env-form-container {
+ height: 650px;
+
+ .w-sdc-env-search {
+ padding: 10px 20px 20px 0;
+ white-space: nowrap;
+ position: relative;
+ width: 60%;
+ height: 64px;
+
+ .env-search-icon {
+ top: 9px;
+ right: 11px;
+ }
+
+ .magnification-white {
+ .sprite-new;
+ .search-white-icon;
+ .hand;
+ }
+
+ .search-icon-container {
+ width: 35px;
+ height: 30px;
+ background-color: @main_color_a;
+ white-space: nowrap;
+ float: right;
+ position: relative;
+ bottom: 31px;
+ right: 1px;
+ border-radius: 0px 4px 4px 0px;
+ .hand
+ }
+
+ .w-sdc-env-search-input {
+ border: 1px solid @color_e;
+ .border-radius(4px);
+ height: 32px;
+ margin: 0;
+ padding: 0px 28px 3px 10px;
+ vertical-align: 4px;
+ width: 100%;
+ outline: none;
+ font-style: italic;
+ }
+ }
+
+ .table-container-flex {
+ height: 570px;
+
+ .table {
+ height: 100%;
+ .flex-item:nth-child(1) {
+ flex-grow: 20;
+ .show-desc{
+ float: right;
+ top: 10px;
+ position: relative;
+ }
+ }
+
+ .flex-item:nth-child(2) {
+ flex-grow: 10;
+ }
+
+ .flex-item:nth-child(3) {
+ flex-grow: 10;
+ }
+ .scrollbar-container{
+ max-height: 527px;
+ }
+ .left-column-container{
+ .required-symbol {
+ .m_14_m;
+ color: #f33;
+ display: none;
+ position: relative;
+ left: -4px;
+ top: 3px;
+ }
+
+ .i-sdc-form-item{
+ border-right: none;
+ margin: 0px;
+
+ .input-parameter{
+ border: none;
+ height: 30px;
+ width: 254px;
+ float: right;
+ input{
+ .m_13_m;
+ width: 100%;
+ display: inline-flex;
+ padding-right: 33px;
+ }
+ .action-button{
+ border-left: solid 1px @main_color_o;
+ position: relative;
+ height: 20px;
+ width: 25px;
+ top: -25px;
+ left: 228px;
+ padding-left: 6px;
+ background-color: @main_color_p;
+ div:not(.disable){
+ .hand;
+ }
+ }
+ }
+
+ &.required{
+ .required-symbol {
+ display: inline-flex;
+ }
+ .input-parameter {
+ width: 250px;
+ }
+ .action-button{
+ left: 224px;
+ }
+ }
+ }
+
+
+
+ }
+ }
+
+ .text{
+ overflow: hidden;
+ text-overflow: ellipsis;
+ display: inline-block;
+ white-space: nowrap;
+ }
+ }
+
+
+ .parameter-description{
+ background-color: @func_color_r;
+ border-left: 4px solid @main_color_a;
+ padding: 10px 30px;
+ }
+}
+
+.header-info{
+ float: right;
+}
+
+.parameter-description-popover{
+ z-index: 1100;
+ min-width: 210px;
+ .arrow{
+ left: 20px !important;
+ border-width: 7px;
+ bottom: -8px !important;
+ }
+ .popover-content{
+ .f-type._13_m;;
+ }
+}
diff --git a/catalog-ui/src/app/view-models/forms/env-parameters-form/env-parameters-form.ts b/catalog-ui/src/app/view-models/forms/env-parameters-form/env-parameters-form.ts
new file mode 100644
index 0000000000..476af4ada9
--- /dev/null
+++ b/catalog-ui/src/app/view-models/forms/env-parameters-form/env-parameters-form.ts
@@ -0,0 +1,153 @@
+'use strict';
+import {ValidationUtils} from "app/utils";
+import {ArtifactModel, HeatParameterModel, Component} from "app/models";
+
+export interface IEnvParametersFormViewModelScope extends ng.IScope {
+ isLoading:boolean;
+ type:string;
+ heatParameters:Array<HeatParameterModel>;
+ forms:any;
+ artifactResource:ArtifactModel;
+ buttons:Array<any>;
+ envParametersModal:ng.ui.bootstrap.IModalServiceInstance;
+ tableHeadersList:Array<any>;
+ selectedParameter:HeatParameterModel;
+ templatePopover:string;
+
+ getValidationPattern(type:string):RegExp;
+ isInstance():boolean;
+ validateJson(json:string):boolean;
+ close():void;
+ save():void;
+ openDescPopover(selectedParam:HeatParameterModel):void;
+ closeDescriptionPopover():void;
+}
+
+export class EnvParametersFormViewModel {
+
+ static '$inject' = [
+ '$scope',
+ '$templateCache',
+ '$state',
+ '$uibModalInstance',
+ 'artifact',
+ 'ValidationUtils',
+ 'component'
+ ];
+
+ constructor(private $scope:IEnvParametersFormViewModelScope,
+ private $templateCache:ng.ITemplateCacheService,
+ private $state:any,
+ private $uibModalInstance:ng.ui.bootstrap.IModalServiceInstance,
+ private artifact:ArtifactModel,
+ private ValidationUtils:ValidationUtils,
+ private component:Component) {
+
+
+ this.initScope();
+ }
+
+ private updateInstanceHeat = ():void => {
+ let success = (responseArtifact:ArtifactModel):void => {
+ this.$scope.isLoading = false;
+ this.$uibModalInstance.close();
+ };
+
+ let error = ():void => {
+ this.$scope.isLoading = false;
+ console.info('Failed to load save artifact');
+ };
+
+ this.component.addOrUpdateInstanceArtifact(this.$scope.artifactResource).then(success, error);
+ };
+
+ private initScope = ():void => {
+ this.$scope.forms = {};
+ this.$scope.envParametersModal = this.$uibModalInstance;
+ this.$scope.artifactResource = this.artifact;
+ this.$scope.heatParameters = angular.copy(this.artifact.heatParameters);
+
+ this.$scope.tableHeadersList = [
+ {title: "Parameter", property: "name"},
+ {title: "Default Value", property: "defaultValue", info: "DEFAULT_VALUE_INFO"},
+ {title: "Current Value", property: "currentValue", info: "CURRENT_VALUE_INFO"}
+ ];
+
+ this.$templateCache.put("env-parametr-description-popover.html", require('app/view-models/forms/env-parameters-form/env-parametr-description-popover.html'));
+ this.$scope.templatePopover = "env-parametr-description-popover.html";
+
+ this.$scope.getValidationPattern = (validationType:string, parameterType?:string):RegExp => {
+ return this.ValidationUtils.getValidationPattern(validationType, parameterType);
+ };
+
+ this.$scope.validateJson = (json:string):boolean => {
+ if (!json) {
+ return true;
+ }
+ return this.ValidationUtils.validateJson(json);
+ };
+
+ this.$scope.isInstance = ():boolean => {
+ return !!this.component.selectedInstance;
+ };
+
+ this.$scope.save = ():void => {
+ this.$scope.buttons[0].disabled = true;//prevent double click (DE246266)
+ this.$scope.isLoading = true;
+ this.artifact.heatParameters = this.$scope.heatParameters;
+ this.artifact.heatParameters.forEach((parameter:any):void => {
+ /* if ("" === parameter.currentValue) {
+ parameter.currentValue = null;
+ }else */
+ if (!parameter.currentValue && parameter.defaultValue) {
+ parameter.currentValue = parameter.defaultValue;
+ }
+ });
+
+ if (this.$scope.isInstance()) {
+ this.updateInstanceHeat();
+ return;
+ }
+
+ let success = (responseArtifact:ArtifactModel):void => {
+ this.$scope.isLoading = false;
+ this.$uibModalInstance.close();
+
+ };
+
+ let error = ():void => {
+ this.$scope.isLoading = false;
+ console.info('Failed to load save artifact');
+ };
+
+ this.component.addOrUpdateArtifact(this.$scope.artifactResource).then(success, error);
+ };
+
+ this.$scope.close = ():void => {
+ //this.artifact.heatParameters.forEach((parameter:any):void => {
+ // if (!parameter.currentValue && parameter.defaultValue) {
+ // parameter.currentValue = parameter.defaultValue;
+ // }
+ //});
+ this.$uibModalInstance.dismiss();
+ };
+
+ this.$scope.openDescPopover = (selectedParam:HeatParameterModel):void => {
+ this.$scope.selectedParameter = selectedParam;
+ };
+
+ this.$scope.closeDescriptionPopover = ():void => {
+ this.$scope.selectedParameter = null;
+ };
+
+ this.$scope.buttons = [
+ {'name': 'Save', 'css': 'blue', 'callback': this.$scope.save},
+ {'name': 'Cancel', 'css': 'grey', 'callback': this.$scope.close}
+ ];
+
+ this.$scope.$watch("forms.editForm.$invalid", (newVal, oldVal) => {
+ this.$scope.buttons[0].disabled = this.$scope.forms.editForm.$invalid;
+ });
+
+ };
+}
diff --git a/catalog-ui/src/app/view-models/forms/env-parameters-form/env-parametr-description-popover.html b/catalog-ui/src/app/view-models/forms/env-parameters-form/env-parametr-description-popover.html
new file mode 100644
index 0000000000..ed127c6bfb
--- /dev/null
+++ b/catalog-ui/src/app/view-models/forms/env-parameters-form/env-parametr-description-popover.html
@@ -0,0 +1,4 @@
+<div>
+ <span data-tests-id='popover-x-button' data-ng-click='closeDescriptionPopover()' class='tlv-sprite tlv-x-btn close-popover-btn'></span>
+ {{selectedParameter.description}}
+</div>
diff --git a/catalog-ui/src/app/view-models/forms/input-form/input-form-view-modal.ts b/catalog-ui/src/app/view-models/forms/input-form/input-form-view-modal.ts
new file mode 100644
index 0000000000..e87e5c6c7d
--- /dev/null
+++ b/catalog-ui/src/app/view-models/forms/input-form/input-form-view-modal.ts
@@ -0,0 +1,126 @@
+'use strict';
+import {FormState, PROPERTY_TYPES, ValidationUtils, PROPERTY_VALUE_CONSTRAINTS} from "app/utils";
+import {InputModel} from "app/models";
+
+export interface IInputEditModel {
+ editInput:InputModel;
+}
+
+export interface IInputFormViewModelScope extends ng.IScope {
+ forms:any;
+ editForm:ng.IFormController;
+ footerButtons:Array<any>;
+ isService:boolean;
+ modalInstanceInput:ng.ui.bootstrap.IModalServiceInstance;
+ isLoading:boolean;
+ inputEditModel:IInputEditModel;
+ myValue:any;
+ maxLength:number;
+
+ save():void;
+ close():void;
+ validateIntRange(value:string):boolean;
+ validateJson(json:string):boolean;
+ getValidationPattern(type:string):RegExp;
+ showSchema():boolean;
+}
+
+export class InputFormViewModel {
+
+ static '$inject' = [
+ '$scope',
+ '$uibModalInstance',
+ 'ValidationUtils',
+ 'input'
+ ];
+
+ private formState:FormState;
+
+
+ constructor(private $scope:IInputFormViewModelScope,
+ private $uibModalInstance:ng.ui.bootstrap.IModalServiceInstance,
+ private ValidationUtils:ValidationUtils,
+ private input:InputModel) {
+ this.initScope();
+ this.initMyValue();
+ }
+
+ private initMyValue = ():void => {
+ switch (this.$scope.inputEditModel.editInput.type) {
+ case PROPERTY_TYPES.MAP:
+ this.$scope.myValue = this.$scope.inputEditModel.editInput.defaultValue ? JSON.parse(this.$scope.inputEditModel.editInput.defaultValue) : {'': null};
+ break;
+ case PROPERTY_TYPES.LIST:
+ this.$scope.myValue = this.$scope.inputEditModel.editInput.defaultValue ? JSON.parse(this.$scope.inputEditModel.editInput.defaultValue) : [];
+ break;
+ }
+ };
+
+ private initDefaultValueMaxLength = ():void => {
+ switch (this.$scope.inputEditModel.editInput.type) {
+ case PROPERTY_TYPES.MAP:
+ case PROPERTY_TYPES.LIST:
+ this.$scope.maxLength = this.$scope.inputEditModel.editInput.schema.property.type == PROPERTY_TYPES.JSON ?
+ PROPERTY_VALUE_CONSTRAINTS.JSON_MAX_LENGTH :
+ PROPERTY_VALUE_CONSTRAINTS.MAX_LENGTH;
+ break;
+ case PROPERTY_TYPES.JSON:
+ this.$scope.maxLength = PROPERTY_VALUE_CONSTRAINTS.JSON_MAX_LENGTH;
+ break;
+ default:
+ this.$scope.maxLength = PROPERTY_VALUE_CONSTRAINTS.MAX_LENGTH;
+ }
+ };
+
+ private initScope = ():void => {
+ this.$scope.forms = {};
+ this.$scope.modalInstanceInput = this.$uibModalInstance;
+ this.$scope.inputEditModel = {
+ editInput: null
+ };
+ this.$scope.inputEditModel.editInput = this.input;
+ this.initDefaultValueMaxLength();
+
+ //scope methods
+ this.$scope.save = ():void => {
+ if (this.$scope.showSchema()) {
+ this.$scope.inputEditModel.editInput.defaultValue = JSON.stringify(this.$scope.myValue);
+ }
+ };
+
+ this.$scope.close = ():void => {
+ this.$uibModalInstance.close();
+ };
+
+ this.$scope.validateIntRange = (value:string):boolean => {
+ return !value || this.ValidationUtils.validateIntRange(value);
+ };
+
+ this.$scope.validateJson = (json:string):boolean => {
+ if (!json) {
+ return true;
+ }
+ return this.ValidationUtils.validateJson(json);
+ };
+
+ this.$scope.showSchema = ():boolean => {
+ return ['list', 'map'].indexOf(this.$scope.inputEditModel.editInput.type) > -1;
+ };
+
+ this.$scope.getValidationPattern = (type:string):RegExp => {
+ return this.ValidationUtils.getValidationPattern(type);
+ };
+
+ // Add the done button at the footer.
+ this.$scope.footerButtons = [
+ {'name': 'Done', 'css': 'blue', 'callback': this.$scope.save},
+ {'name': 'Cancel', 'css': 'grey', 'callback': this.$scope.close}
+ ];
+
+ this.$scope.$watchCollection("forms.editForm.$invalid", (newVal, oldVal) => {
+ this.$scope.footerButtons[0].disabled = this.$scope.forms.editForm.$invalid;
+ });
+
+ };
+}
+
diff --git a/catalog-ui/src/app/view-models/forms/input-form/input-form-view.html b/catalog-ui/src/app/view-models/forms/input-form/input-form-view.html
new file mode 100644
index 0000000000..1bf6dc4ca9
--- /dev/null
+++ b/catalog-ui/src/app/view-models/forms/input-form/input-form-view.html
@@ -0,0 +1,125 @@
+<sdc-modal modal="modalInstanceInput" type="classic" class="sdc-edit-input-container" buttons="footerButtons" header="Update Input" show-close-button="true">
+
+ <div class="sdc-edit-input-form-container" >
+ <form novalidate class="w-sdc-form two-columns" name="forms.editForm" >
+
+ <div class="w-sdc-form-columns-wrapper">
+
+ <div class="w-sdc-form-column">
+
+ <!-- Name -->
+ <div class="i-sdc-form-item">
+ <label class="i-sdc-form-label">Name</label>
+ <input class="i-sdc-form-input"
+ data-tests-id="inputName"
+ data-ng-maxlength="50"
+ data-ng-disabled="true"
+ maxlength="50"
+ data-ng-model="inputEditModel.editInput.name"
+ type="text"
+ name="inputName"
+ autofocus />
+ </div>
+
+ <!-- Description -->
+ <div class="i-sdc-form-item">
+ <label class="i-sdc-form-label">Description</label>
+ <textarea class="i-sdc-form-textarea"
+ data-ng-disabled="true"
+ name="description"
+ data-ng-model="inputEditModel.editInput.description"
+ data-tests-id="description"></textarea>
+ </div>
+
+
+ </div>
+
+ <div class="w-sdc-form-column">
+ <!-- Type -->
+ <div class="i-sdc-form-item">
+ <label class="i-sdc-form-label">Type</label>
+ <input class="i-sdc-form-input"
+ data-tests-id="type"
+ data-ng-disabled="true"
+ data-ng-model="inputEditModel.editInput.type"
+ type="text"
+ name="type"/>
+ </div>
+ <!-- schema -->
+ <div class="i-sdc-form-item"
+ data-ng-if="showSchema()">
+ <label class="i-sdc-form-label">Entry Schema</label>
+ <input class="i-sdc-form-input"
+ data-tests-id="schema"
+ data-ng-disabled="true"
+ data-ng-model="inputEditModel.editInput.schema.property.type"
+ type="text"
+ name="schema"/>
+ </div>
+ <!-- Default value -->
+ <div class="i-sdc-form-item" data-ng-class="{error:(forms.editForm.value.$dirty && forms.editForm.value.$invalid)}">
+ <label class="i-sdc-form-label">Default Value</label>
+ <div data-ng-switch="inputEditModel.editInput.type">
+ <div ng-switch-when="map">
+ <type-map value-obj-ref="myValue"
+ schema-property="inputEditModel.editInput.schema.property"
+ parent-form-obj="forms.editForm"
+ fields-prefix-name="'input-value-'"
+ read-only="true"
+ default-value=""
+ types="[]"
+ max-length="maxLength"></type-map>
+ </div>
+ <div ng-switch-when="list">
+ <type-list value-obj-ref="myValue"
+ schema-property="inputEditModel.editInput.schema.property"
+ parent-form-obj="forms.editForm"
+ fields-prefix-name="'input-value-'"
+ read-only="true"
+ default-value=""
+ types="[]"
+ max-length="maxLength"></type-list>
+ </div>
+ <div ng-switch-default>
+ <div class="i-sdc-form-item" data-ng-class="{error:(forms.editForm.value.$dirty && forms.editForm.value.$invalid)}">
+ <input class="i-sdc-form-input"
+ data-tests-id="defaultvalue"
+ ng-if="inputEditModel.editInput.type != 'boolean'"
+ data-ng-maxlength="maxLength"
+ data-ng-disabled="true"
+ maxlength="{{maxLength}}"
+ data-ng-model="inputEditModel.editInput.defaultValue"
+ type="text"
+ name="value"
+ data-ng-pattern="getValidationPattern(input.type)"
+ data-ng-model-options="{ debounce: 200 }"
+ data-ng-change="('json'==inputEditModel.editInput.type && forms.editForm.value.$setValidity('pattern', validateJson(inputEditModel.editInput.defaultValue)))
+ ||(!forms.editForm.value.$error.pattern && ('integer'==inputEditModel.editInput.type && forms.editForm.value.$setValidity('pattern', validateIntRange(inputEditModel.editInput.defaultValue)) || onValueChange()))"
+ autofocus />
+ <select class="i-sdc-form-select"
+ data-tests-id="booleantype"
+ ng-if="inputEditModel.editInput.type == 'boolean'"
+ data-ng-disabled="true"
+ name="value"
+ data-ng-model="inputEditModel.editInput.defaultValue">
+ <option value="true">true</option>
+ <option value="false">false</option>
+ </select>
+
+ <div class="input-error" data-ng-show="forms.editForm.value.$dirty && forms.editForm.value.$invalid">
+ <span ng-show="forms.editForm.value.$error.maxlength" translate="VALIDATION_ERROR_MAX_LENGTH" translate-values="{'max': '{{maxLength}}' }"></span>
+ <span ng-show="forms.editForm.value.$error.pattern" translate="PROPERTY_EDIT_PATTERN"></span>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ </div>
+
+ </div>
+
+ </form>
+ </div>
+
+</sdc-modal>
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
new file mode 100644
index 0000000000..1ba5a90bb4
--- /dev/null
+++ b/catalog-ui/src/app/view-models/forms/property-forms/base-property-form/property-form-base-model.ts
@@ -0,0 +1,204 @@
+/**
+ * Created by obarda on 1/19/2017.
+ */
+'use strict';
+import {DataTypesService} from "app/services/data-types-service";
+import {PropertyModel, DataTypesMap, Component} from "app/models";
+import {ValidationUtils, PROPERTY_DATA} from "app/utils";
+
+export interface IPropertyFormBaseViewScope extends ng.IScope {
+
+ forms:any;
+ editForm:ng.IFormController;
+
+ property:PropertyModel;
+ types:Array<string>;
+ nonPrimitiveTypes:Array<string>;
+ simpleTypes:Array<string>;
+
+ footerButtons:Array<any>;
+ modalPropertyFormBase:ng.ui.bootstrap.IModalServiceInstance;
+ currentPropertyIndex:number;
+ isLastProperty:boolean;
+ innerViewSrcUrl:string;
+
+ //Disabling filed - each child controller can change this when needed
+ isNew:boolean;
+ isTypeSelectorDisable:boolean;
+ isDeleteDisable:boolean;
+ isNameDisable:boolean;
+ isDescriptionDisable:boolean;
+ isPropertyValueDisable:boolean;
+ isArrowsDisabled:boolean;
+
+ //Validation pattern
+ validationPattern:RegExp;
+ propertyNameValidationPattern:RegExp;
+ commentValidationPattern:RegExp;
+ numberValidationPattern:RegExp;
+
+ dataTypes:DataTypesMap;
+
+ isLoading:boolean;
+
+ save():void;
+ close():void;
+ getNext():void;
+ getPrev():void;
+ getValidationPattern(type:string):RegExp;
+}
+
+export abstract class PropertyFormBaseView {
+
+
+ constructor(protected $scope:IPropertyFormBaseViewScope,
+ protected $uibModalInstance:ng.ui.bootstrap.IModalServiceInstance,
+ protected $injector:ng.auto.IInjectorService,
+ protected originalProperty:PropertyModel,
+ protected component:Component,
+ protected filteredProperties:Array<PropertyModel>,
+ protected DataTypesService:DataTypesService) {
+
+ this.initScope();
+
+ }
+
+ protected validationUtils:ValidationUtils;
+
+ protected isPropertyValueOwner = ():boolean => {
+ return this.component.isService() || !!this.component.selectedInstance;
+ };
+
+ private isDisable = ():boolean => {
+ return this.isPropertyValueOwner() || this.$scope.property.readonly;
+ };
+
+
+ //This is the difault state, Childs screens can change if needed
+ protected initButtonsState = ():void => {
+ let isDisable = this.isDisable();
+
+ this.$scope.isArrowsDisabled = false;
+ this.$scope.isDeleteDisable = isDisable;
+ this.$scope.isDescriptionDisable = isDisable;
+ this.$scope.isNameDisable = isDisable;
+ this.$scope.isTypeSelectorDisable = isDisable;
+ this.$scope.isPropertyValueDisable = this.$scope.property.readonly && !this.isPropertyValueOwner();
+ };
+
+ protected initValidations = ():void => {
+
+ this.$scope.validationPattern = this.$injector.get('ValidationPattern');
+ this.$scope.propertyNameValidationPattern = this.$injector.get('PropertyNameValidationPattern');
+ this.$scope.commentValidationPattern = this.$injector.get('CommentValidationPattern');
+ this.$scope.numberValidationPattern = this.$injector.get('NumberValidationPattern');
+ this.validationUtils = this.$injector.get('ValidationUtils');
+ };
+
+ //Functions implemented on child's scope if needed
+ abstract save(doNotCloseModal?:boolean):ng.IPromise<boolean>;
+
+ protected onPropertyChange():void {
+ };
+
+ private updatePropertyByIndex = (index:number):void => {
+ this.$scope.property = new PropertyModel(this.filteredProperties[index]);
+ this.$scope.isLastProperty = this.$scope.currentPropertyIndex == (this.filteredProperties.length - 1);
+ this.onPropertyChange();
+ };
+
+ private initScope = ():void => {
+
+ this.$scope.forms = {};
+ this.$scope.isLoading = false;
+ this.$scope.property = new PropertyModel(this.originalProperty); //we create a new Object so if user press cance we won't update the property
+ this.$scope.types = PROPERTY_DATA.TYPES; //All types - simple type + map + list
+ this.$scope.simpleTypes = PROPERTY_DATA.SIMPLE_TYPES; //All simple types
+ this.$scope.dataTypes = this.DataTypesService.getAllDataTypes(); //Get all data types in service
+ this.$scope.modalPropertyFormBase = this.$uibModalInstance;
+ this.$scope.isNew = !angular.isDefined(this.$scope.property.name);
+
+ this.initValidations();
+ this.initButtonsState();
+ this.filteredProperties = _.sortBy(this.filteredProperties, 'name');
+ this.$scope.currentPropertyIndex = _.findIndex(this.filteredProperties, propety => propety.uniqueId == this.$scope.property.uniqueId);
+ this.$scope.isLastProperty = this.$scope.currentPropertyIndex == (this.filteredProperties.length - 1);
+
+ this.$scope.nonPrimitiveTypes = _.filter(Object.keys(this.$scope.dataTypes), (type:string)=> {
+ return this.$scope.types.indexOf(type) == -1;
+ });
+
+ this.$scope.close = ():void => {
+ this.$uibModalInstance.close();
+ };
+
+ this.$scope.save = ():void => {
+
+ let onSuccess = ():void => {
+ this.$scope.isLoading = false;
+ };
+ let onFailed = ():void => {
+ this.$scope.isLoading = false;
+ };
+
+ this.$scope.isLoading = true;
+ this.save(true).then(onSuccess, onFailed); // Child controller implement save logic
+ };
+
+ // Add the done button at the footer.
+ this.$scope.footerButtons = [
+ {'name': 'Save', 'css': 'blue', 'callback': this.$scope.save},
+ {'name': 'Cancel', 'css': 'grey', 'callback': this.$scope.close}
+ ];
+
+
+ this.$scope.getPrev = ():void=> {
+
+ let onSuccess = ():void => {
+ this.$scope.isLoading = false;
+ this.updatePropertyByIndex(--this.$scope.currentPropertyIndex);
+ };
+ let onFailed = ():void => {
+ this.$scope.isLoading = false;
+ };
+
+ if (!this.$scope.property.readonly) {
+ this.$scope.isLoading = true;
+ this.save(false).then(onSuccess, onFailed);
+
+ } else {
+ this.updatePropertyByIndex(--this.$scope.currentPropertyIndex);
+ }
+
+ };
+
+ this.$scope.getNext = ():void=> {
+
+ let onSuccess = ():void => {
+ this.$scope.isLoading = false;
+ this.updatePropertyByIndex(++this.$scope.currentPropertyIndex);
+ };
+ let onFailed = ():void => {
+ this.$scope.isLoading = false;
+ };
+
+ if (!this.$scope.property.readonly) {
+ this.$scope.isLoading = true;
+ this.save(false).then(onSuccess, onFailed);
+ } else {
+ this.updatePropertyByIndex(++this.$scope.currentPropertyIndex);
+ }
+
+ };
+
+
+ this.$scope.$watch("forms.editForm.$invalid", (newVal, oldVal) => {
+ this.$scope.footerButtons[0].disabled = this.$scope.forms.editForm.$invalid;
+ });
+
+
+ this.$scope.getValidationPattern = (type:string):RegExp => {
+ return this.validationUtils.getValidationPattern(type);
+ };
+ }
+}
diff --git a/catalog-ui/src/app/view-models/forms/property-forms/base-property-form/property-form-base-view.html b/catalog-ui/src/app/view-models/forms/property-forms/base-property-form/property-form-base-view.html
new file mode 100644
index 0000000000..7cb05bf4ca
--- /dev/null
+++ b/catalog-ui/src/app/view-models/forms/property-forms/base-property-form/property-form-base-view.html
@@ -0,0 +1,132 @@
+<sdc-modal modal="modalPropertyFormBase" type="classic" class="sdc-edit-property-container" buttons="footerButtons" header="{{isNew ? 'Add' : 'Update' }} Property" show-close-button="true" data-tests-id="sdc-edit-property-container">
+ <loader data-display="isLoading" relative="false" size="medium"></loader>
+ <div class="sdc-modal-top-bar" data-ng-if="!isNew">
+ <div class="sdc-modal-top-bar-buttons">
+ <span ng-click="delete(property)" data-ng-class="{'disabled' : isDeleteDisable}" class="sprite-new delete-btn" data-tests-id="delete_property" sdc-smart-tooltip="">Delete</span>
+ <span class="delimiter"></span>
+ <span data-ng-click="getPrev()" data-ng-class="{'disabled' : !currentPropertyIndex || forms.editForm.$invalid || isArrowsDisabled}" class="sprite-new left-arrow" data-tests-id="get-prev" sdc-smart-tooltip="">Previous</span>
+ <span data-ng-click="getNext()" data-ng-class="{'disabled' : isLastProperty || forms.editForm.$invalid || isArrowsDisabled}" class="sprite-new right-arrow" data-tests-id="get-next" sdc-smart-tooltip="">Next</span>
+ </div>
+ </div>
+
+ <div class="sdc-edit-property-form-container" >
+ <perfect-scrollbar scroll-y-margin-offset="0" include-padding="true" class="scrollbar-container">
+ <form class="w-sdc-form two-columns" name="forms.editForm" >
+
+ <div class="w-sdc-form-columns-wrapper">
+
+ <div class="w-sdc-form-column">
+
+ <!-- Name -->
+ <div class="i-sdc-form-item" data-ng-class="{error:(forms.editForm.propertyName.$dirty && forms.editForm.propertyName.$invalid)}">
+ <label class="i-sdc-form-label" ng-class="{'required': !isService}">Name</label>
+ <input class="i-sdc-form-input"
+ data-tests-id="propertyName"
+ data-ng-maxlength="50"
+ data-ng-disabled="isNameDisable"
+ maxlength="50"
+ data-ng-model="property.name"
+ type="text"
+ name="propertyName"
+ data-ng-pattern="propertyNameValidationPattern"
+ data-required
+ data-ng-model-options="{ debounce: 200 }"
+ autofocus />
+
+ <div class="input-error" data-ng-show="forms.editForm.propertyName.$dirty && forms.editForm.propertyName.$invalid">
+ <span ng-show="forms.editForm.propertyName.$error.required" translate="VALIDATION_ERROR_REQUIRED" translate-values="{'field': 'Property name' }"></span>
+ <span ng-show="forms.editForm.propertyName.$error.maxlength" translate="VALIDATION_ERROR_MAX_LENGTH" translate-values="{'max': '50' }"></span>
+ <span ng-show="forms.editForm.propertyName.$error.pattern" translate="VALIDATION_ERROR_SPECIAL_CHARS_NOT_ALLOWED"></span>
+ </div>
+ </div>
+ </div>
+
+ <div class="w-sdc-form-column">
+ <div class="w-sdc-form-columns-wrapper">
+ <div class="w-sdc-form-column">
+ <!-- Type -->
+ <div class="i-sdc-form-item" data-ng-class="{error:(forms.editForm.type.$dirty && forms.editForm.type.$invalid)}">
+ <label class="i-sdc-form-label" ng-class="{'required': !isService}">Type</label>
+ <select class="i-sdc-form-select"
+ data-tests-id="propertyType"
+ data-required
+ data-ng-disabled="isTypeSelectorDisable"
+ name="type"
+ data-ng-change="onTypeChange()"
+ data-ng-model="property.type">
+ <option value="">Choose Type</option>
+ <option data-ng-repeat="type in types"
+ value="{{type}}">{{type}}</option>
+ <option data-ng-repeat="type in nonPrimitiveTypes"
+ value="{{type}}">{{type.replace("org.openecomp.datatypes.heat.","")}}</option>
+ </select>
+
+ <div class="input-error" data-ng-show="forms.editForm.type.$dirty && forms.editForm.type.$invalid">
+ <span ng-show="forms.editForm.type.$error.required" translate="VALIDATION_ERROR_REQUIRED" translate-values="{'field': 'Type' }"></span>
+ </div>
+ </div>
+ </div>
+ <div class="w-sdc-form-column" data-ng-if="showSchema()">
+ <!-- Entry Schema -->
+ <div class="i-sdc-form-item" data-ng-class="{error:(forms.editForm.schemaType.$dirty && forms.editForm.schemaType.$invalid)}">
+ <label class="i-sdc-form-label required">Entry Schema</label>
+ <select class="i-sdc-form-select"
+ data-required
+ data-tests-id="schema-type"
+ data-ng-disabled="isPropertyValueOwner() || property.readonly"
+ name="schemaType"
+ data-ng-change="onSchemaTypeChange()"
+ data-ng-model="property.schema.property.type">
+ <option value="">Choose Schema Type</option>
+ <option data-ng-repeat="type in simpleTypes"
+ value="{{type}}">{{type}}</option>
+ <option data-ng-repeat="type in nonPrimitiveTypes"
+ value="{{type}}">{{type.replace("org.openecomp.datatypes.heat.","")}}</option>
+ </select>
+
+ <div class="input-error" data-ng-show="forms.editForm.schemaType.$dirty && forms.editForm.schemaType.$invalid">
+ <span ng-show="forms.editForm.schemaType.$error.required" translate="VALIDATION_ERROR_REQUIRED" translate-values="{'field': 'Entry schema' }"></span>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- Constraints by type -->
+ <div class="i-sdc-form-item" data-ng-if="false">
+ <label class="i-sdc-form-label required">Constraints by type</label>
+ <div>
+ Should be constraints by type(TBD)
+ </div>
+ </div>
+
+ </div>
+
+ </div>
+ <!-- Description -->
+ <div class="i-sdc-form-item" data-ng-class="{error:(forms.editForm.description.$dirty && forms.editForm.description.$invalid)}">
+ <label class="i-sdc-form-label">Description</label>
+ <textarea class="i-sdc-form-textarea"
+ data-ng-maxlength="256"
+ data-ng-disabled="isDescriptionDisable"
+ maxlength="256"
+ data-ng-pattern="commentValidationPattern"
+ name="description"
+ data-ng-model="property.description"
+ data-ng-model-options="{ debounce: 200 }"
+ data-tests-id="description"
+ ></textarea>
+
+ <div class="input-error" data-ng-show="forms.editForm.description.$dirty && forms.editForm.description.$invalid">
+ <span ng-show="forms.editForm.description.$error.maxlength" translate="VALIDATION_ERROR_MAX_LENGTH" translate-values="{'max': '256' }"></span>
+ <span ng-show="forms.editForm.description.$error.pattern" translate="VALIDATION_ERROR_SPECIAL_CHARS_NOT_ALLOWED"></span>
+ <span ng-show="forms.editForm.description.$error.required" translate="VALIDATION_ERROR_REQUIRED" translate-values="{'field': 'Description' }"></span>
+ </div>
+ </div>
+ <!-- Default value - insert in dynamic template url -->
+ <ng-include src="innerViewSrcUrl"></ng-include>
+ <span class="w-sdc-form-note" data-ng-show="forms.editForm.$invalid && false" translate="LABEL_ALL_FIELDS_ARE_MANDATORY"></span>
+ </form>
+ </perfect-scrollbar>
+ </div>
+
+</sdc-modal>
diff --git a/catalog-ui/app/scripts/view-models/forms/property-form/property-form.less b/catalog-ui/src/app/view-models/forms/property-forms/base-property-form/property-form-base.less
index 15e30af4ee..15e30af4ee 100644
--- a/catalog-ui/app/scripts/view-models/forms/property-form/property-form.less
+++ b/catalog-ui/src/app/view-models/forms/property-forms/base-property-form/property-form-base.less
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
new file mode 100644
index 0000000000..b3557b055f
--- /dev/null
+++ b/catalog-ui/src/app/view-models/forms/property-forms/component-property-form/property-form-view-model.ts
@@ -0,0 +1,322 @@
+'use strict';
+import {
+ PROPERTY_TYPES, ModalsHandler, ValidationUtils, PROPERTY_VALUE_CONSTRAINTS, FormState, PROPERTY_DATA} from "app/utils";
+import {DataTypesService} from "app/services";
+import {PropertyModel, DataTypesMap, Component} from "app/models";
+
+export interface IEditPropertyModel {
+ property:PropertyModel;
+ types:Array<string>;
+ simpleTypes:Array<string>;
+}
+
+interface IPropertyFormViewModelScope extends ng.IScope {
+ forms:any;
+ editForm:ng.IFormController;
+ footerButtons:Array<any>;
+ isNew:boolean;
+ isLoading:boolean;
+ isService:boolean;
+ validationPattern:RegExp;
+ propertyNameValidationPattern:RegExp;
+ commentValidationPattern:RegExp;
+ editPropertyModel:IEditPropertyModel;
+ modalInstanceProperty:ng.ui.bootstrap.IModalServiceInstance;
+ currentPropertyIndex:number;
+ isLastProperty:boolean;
+ myValue:any;
+ nonPrimitiveTypes:Array<string>;
+ dataTypes:DataTypesMap;
+ isTypeDataType:boolean;
+ maxLength:number;
+ isPropertyValueOwner:boolean;
+
+ validateJson(json:string):boolean;
+ save(doNotCloseModal?:boolean):void;
+ getValidationPattern(type:string):RegExp;
+ validateIntRange(value:string):boolean;
+ close():void;
+ onValueChange():void;
+ onSchemaTypeChange():void;
+ onTypeChange(resetSchema:boolean):void;
+ showSchema():boolean;
+ delete(property:PropertyModel):void;
+ getPrev():void;
+ getNext():void;
+ isSimpleType(typeName:string):boolean;
+ getDefaultValue():any;
+}
+
+export class PropertyFormViewModel {
+
+ static '$inject' = [
+ '$scope',
+ 'Sdc.Services.DataTypesService',
+ '$uibModalInstance',
+ 'property',
+ 'ValidationPattern',
+ 'PropertyNameValidationPattern',
+ 'CommentValidationPattern',
+ 'ValidationUtils',
+ 'component',
+ '$filter',
+ 'ModalsHandler',
+ 'filteredProperties',
+ '$timeout',
+ 'isPropertyValueOwner'
+ ];
+
+ private formState:FormState;
+
+ constructor(private $scope:IPropertyFormViewModelScope,
+ private DataTypesService:DataTypesService,
+ private $uibModalInstance:ng.ui.bootstrap.IModalServiceInstance,
+ private property:PropertyModel,
+ private ValidationPattern:RegExp,
+ private PropertyNameValidationPattern:RegExp,
+ private CommentValidationPattern:RegExp,
+ private ValidationUtils:ValidationUtils,
+ private component:Component,
+ private $filter:ng.IFilterService,
+ private ModalsHandler:ModalsHandler,
+ private filteredProperties:Array<PropertyModel>,
+ private $timeout:ng.ITimeoutService,
+ private isPropertyValueOwner:boolean) {
+
+ this.formState = angular.isDefined(property.name) ? FormState.UPDATE : FormState.CREATE;
+ this.initScope();
+ }
+
+ private initResource = ():void => {
+ this.$scope.editPropertyModel.property = new PropertyModel(this.property);
+ this.$scope.editPropertyModel.property.type = this.property.type ? this.property.type : null;
+ this.setMaxLength();
+ this.initAddOnLabels();
+ };
+
+ //init property add-ons labels that show up at the left side of the input.
+ private initAddOnLabels = () => {
+ if (this.$scope.editPropertyModel.property.name == 'network_role' && this.$scope.isService) {
+ //the server sends back the normalized name. Remove it (to prevent interference with validation) and set the addon label to the component name directly.
+ //Note: this cant be done in properties.ts because we dont have access to the component
+ if (this.$scope.editPropertyModel.property.value) {
+ let splitProp = this.$scope.editPropertyModel.property.value.split(new RegExp(this.component.normalizedName + '.', "gi"));
+ this.$scope.editPropertyModel.property.value = splitProp.pop();
+ }
+ this.$scope.editPropertyModel.property.addOn = this.component.name;
+ }
+ }
+
+ private initEditPropertyModel = ():void => {
+ this.$scope.editPropertyModel = {
+ property: null,
+ types: PROPERTY_DATA.TYPES,
+ simpleTypes: PROPERTY_DATA.SIMPLE_TYPES
+ };
+
+ this.initResource();
+ };
+
+ private initForNotSimpleType = ():void => {
+ let property = this.$scope.editPropertyModel.property;
+ this.$scope.isTypeDataType = this.DataTypesService.isDataTypeForPropertyType(this.$scope.editPropertyModel.property);
+ if (property.type && this.$scope.editPropertyModel.simpleTypes.indexOf(property.type) == -1) {
+ if (!(property.value || property.defaultValue)) {
+ switch (property.type) {
+ case PROPERTY_TYPES.MAP:
+ this.$scope.myValue = {'': null};
+ break;
+ case PROPERTY_TYPES.LIST:
+ this.$scope.myValue = [];
+ break;
+ default:
+ this.$scope.myValue = {};
+ }
+ } else {
+ this.$scope.myValue = JSON.parse(property.value || property.defaultValue);
+ }
+ }
+ };
+
+ private setMaxLength = ():void => {
+ switch (this.$scope.editPropertyModel.property.type) {
+ case PROPERTY_TYPES.MAP:
+ case PROPERTY_TYPES.LIST:
+ this.$scope.maxLength = this.$scope.editPropertyModel.property.schema.property.type == PROPERTY_TYPES.JSON ?
+ PROPERTY_VALUE_CONSTRAINTS.JSON_MAX_LENGTH :
+ PROPERTY_VALUE_CONSTRAINTS.MAX_LENGTH;
+ break;
+ case PROPERTY_TYPES.JSON:
+ this.$scope.maxLength = PROPERTY_VALUE_CONSTRAINTS.JSON_MAX_LENGTH;
+ break;
+ default:
+ this.$scope.maxLength =PROPERTY_VALUE_CONSTRAINTS.MAX_LENGTH;
+ }
+ };
+
+
+ private initScope = ():void => {
+
+ //scope properties
+ this.$scope.forms = {};
+ this.$scope.validationPattern = this.ValidationPattern;
+ this.$scope.propertyNameValidationPattern = this.PropertyNameValidationPattern;
+ this.$scope.commentValidationPattern = this.CommentValidationPattern;
+ this.$scope.isLoading = false;
+ this.$scope.isNew = (this.formState === FormState.CREATE);
+ this.$scope.isService = this.component.isService();
+ this.$scope.modalInstanceProperty = this.$uibModalInstance;
+ this.$scope.currentPropertyIndex = _.findIndex(this.filteredProperties, i=> i.name == this.property.name);
+ this.$scope.isLastProperty = this.$scope.currentPropertyIndex == (this.filteredProperties.length - 1);
+ this.$scope.dataTypes = this.DataTypesService.getAllDataTypes();
+ this.$scope.isPropertyValueOwner = this.isPropertyValueOwner;
+ this.initEditPropertyModel();
+
+ this.$scope.nonPrimitiveTypes = _.filter(Object.keys(this.$scope.dataTypes), (type:string)=> {
+ return this.$scope.editPropertyModel.types.indexOf(type) == -1;
+ });
+ this.initForNotSimpleType();
+
+
+ this.$scope.validateJson = (json:string):boolean => {
+ if (!json) {
+ return true;
+ }
+ return this.ValidationUtils.validateJson(json);
+ };
+
+
+ //scope methods
+ this.$scope.save = (doNotCloseModal?:boolean):void => {
+ let property:PropertyModel = this.$scope.editPropertyModel.property;
+ this.$scope.editPropertyModel.property.description = this.ValidationUtils.stripAndSanitize(this.$scope.editPropertyModel.property.description);
+ //if read only - or no changes made - just closes the modal
+ //need to check for property.value changes manually to detect if map properties deleted
+ if ((this.$scope.editPropertyModel.property.readonly && !this.$scope.isPropertyValueOwner)
+ || (!this.$scope.forms.editForm.$dirty && angular.equals(JSON.stringify(this.$scope.myValue), this.$scope.editPropertyModel.property.value))) {
+ this.$uibModalInstance.close();
+ return;
+ }
+
+ this.$scope.isLoading = true;
+
+ let onPropertyFaild = (response):void => {
+ console.info('onFaild', response);
+ this.$scope.isLoading = false;
+ };
+
+ let onPropertySuccess = (propertyFromBE:PropertyModel):void => {
+ console.info('onPropertyResourceSuccess : ', propertyFromBE);
+ this.$scope.isLoading = false;
+
+ if (!doNotCloseModal) {
+ this.$uibModalInstance.close();
+ } else {
+ this.$scope.forms.editForm.$setPristine();
+ this.$scope.editPropertyModel.property = new PropertyModel();
+ }
+ };
+
+ //in case we have uniqueId we call update method
+ if (this.$scope.isPropertyValueOwner) {
+ if (!this.$scope.editPropertyModel.property.simpleType && !this.$scope.isSimpleType(property.type)) {
+ let myValueString:string = JSON.stringify(this.$scope.myValue);
+ property.value = myValueString;
+ }
+ this.component.updateInstanceProperty(property).then(onPropertySuccess, onPropertyFaild);
+ } else {
+ if (!this.$scope.editPropertyModel.property.simpleType && !this.$scope.isSimpleType(property.type)) {
+ let myValueString:string = JSON.stringify(this.$scope.myValue);
+ property.defaultValue = myValueString;
+ } else {
+ this.$scope.editPropertyModel.property.defaultValue = this.$scope.editPropertyModel.property.value;
+ }
+ this.component.addOrUpdateProperty(property).then(onPropertySuccess, onPropertyFaild);
+ }
+ };
+
+ this.$scope.getPrev = ():void=> {
+ this.property = this.filteredProperties[--this.$scope.currentPropertyIndex];
+ this.initResource();
+ this.initForNotSimpleType();
+ this.$scope.isLastProperty = false;
+ };
+
+ this.$scope.getNext = ():void=> {
+ this.property = this.filteredProperties[++this.$scope.currentPropertyIndex];
+ this.initResource();
+ this.initForNotSimpleType();
+ this.$scope.isLastProperty = this.$scope.currentPropertyIndex == (this.filteredProperties.length - 1);
+ };
+
+ this.$scope.isSimpleType = (typeName:string):boolean=> {
+ return typeName && this.$scope.editPropertyModel.simpleTypes.indexOf(typeName) != -1;
+ };
+
+ this.$scope.showSchema = ():boolean => {
+ return [PROPERTY_TYPES.LIST, PROPERTY_TYPES.MAP].indexOf(this.$scope.editPropertyModel.property.type) > -1;
+ };
+
+ this.$scope.getValidationPattern = (type:string):RegExp => {
+ return this.ValidationUtils.getValidationPattern(type);
+ };
+
+ this.$scope.validateIntRange = (value:string):boolean => {
+ return !value || this.ValidationUtils.validateIntRange(value);
+ };
+
+ this.$scope.close = ():void => {
+ this.$uibModalInstance.close();
+ };
+
+ // put default value when instance value is empty
+ this.$scope.onValueChange = ():void => {
+ if (!this.$scope.editPropertyModel.property.value) {
+ if (this.$scope.isPropertyValueOwner) {
+ this.$scope.editPropertyModel.property.value = this.$scope.editPropertyModel.property.defaultValue;
+ }
+ }
+ };
+
+ // Add the done button at the footer.
+ this.$scope.footerButtons = [
+ {'name': 'Save', 'css': 'blue', 'callback': this.$scope.save},
+ {'name': 'Cancel', 'css': 'grey', 'callback': this.$scope.close}
+ ];
+
+ this.$scope.$watch("forms.editForm.$invalid", (newVal, oldVal) => {
+ this.$scope.footerButtons[0].disabled = this.$scope.forms.editForm.$invalid;
+ });
+
+ this.$scope.getDefaultValue = ():any => {
+ return this.$scope.isPropertyValueOwner ? this.$scope.editPropertyModel.property.defaultValue : null;
+ };
+
+ this.$scope.onTypeChange = ():void => {
+ this.$scope.editPropertyModel.property.value = '';
+ this.$scope.editPropertyModel.property.defaultValue = '';
+ this.setMaxLength();
+ this.initForNotSimpleType();
+ };
+
+ this.$scope.onSchemaTypeChange = ():void => {
+ if (this.$scope.editPropertyModel.property.type == PROPERTY_TYPES.MAP) {
+ this.$scope.myValue = {'': null};
+ } else if (this.$scope.editPropertyModel.property.type == PROPERTY_TYPES.LIST) {
+ this.$scope.myValue = [];
+ }
+ this.setMaxLength();
+ };
+
+ this.$scope.delete = (property:PropertyModel):void => {
+ let onOk = ():void => {
+ this.component.deleteProperty(property.uniqueId).then(
+ this.$scope.close
+ );
+ };
+ let title:string = this.$filter('translate')("PROPERTY_VIEW_DELETE_MODAL_TITLE");
+ let message:string = this.$filter('translate')("PROPERTY_VIEW_DELETE_MODAL_TEXT", "{'name': '" + property.name + "'}");
+ this.ModalsHandler.openConfirmationModal(title, message, false).then(onOk);
+ };
+ }
+}
diff --git a/catalog-ui/app/scripts/view-models/forms/property-form/property-form-view.html b/catalog-ui/src/app/view-models/forms/property-forms/component-property-form/property-form-view.html
index d593d47a77..f92d9a5ddc 100644
--- a/catalog-ui/app/scripts/view-models/forms/property-form/property-form-view.html
+++ b/catalog-ui/src/app/view-models/forms/property-forms/component-property-form/property-form-view.html
@@ -1,7 +1,8 @@
<sdc-modal modal="modalInstanceProperty" type="classic" class="sdc-edit-property-container" buttons="footerButtons" header="{{isNew ? 'Add' : 'Update' }} Property" show-close-button="true" data-tests-id="sdc-edit-property-container">
+ <loader data-display="isLoading" relative="false" size="medium"></loader>
<div class="sdc-modal-top-bar" data-ng-if="!isNew">
<div class="sdc-modal-top-bar-buttons">
- <span ng-click="delete(editPropertyModel.property)" data-ng-class="{'disabled' : isPropertyValueOwner()||editPropertyModel.property.readonly}" class="sprite-new delete-btn" data-tests-id="delete_property" sdc-smart-tooltip="">Delete</span>
+ <span ng-click="delete(editPropertyModel.property)" data-ng-class="{'disabled' : isPropertyValueOwner || editPropertyModel.property.readonly}" class="sprite-new delete-btn" data-tests-id="delete_property" sdc-smart-tooltip="">Delete</span>
<span class="delimiter"></span>
<span data-ng-click="getPrev()" data-ng-class="{'disabled' : !currentPropertyIndex }" class="sprite-new left-arrow" data-tests-id="get-prev" sdc-smart-tooltip="">Previous</span>
<span data-ng-click="getNext()" data-ng-class="{'disabled' : isLastProperty }" class="sprite-new right-arrow" data-tests-id="get-next" sdc-smart-tooltip="">Next</span>
@@ -34,28 +35,10 @@
<div class="input-error" data-ng-show="forms.editForm.propertyName.$dirty && forms.editForm.propertyName.$invalid">
<span ng-show="forms.editForm.propertyName.$error.required" translate="VALIDATION_ERROR_REQUIRED" translate-values="{'field': 'Property name' }"></span>
- <span ng-show="forms.editForm.propertyName.$error.maxlength" translate="VALIDATION_ERROR_MAX_LENGTH" translate-values="{'max': '128' }"></span>
+ <span ng-show="forms.editForm.propertyName.$error.maxlength" translate="VALIDATION_ERROR_MAX_LENGTH" translate-values="{'max': '50' }"></span>
<span ng-show="forms.editForm.propertyName.$error.pattern" translate="VALIDATION_ERROR_SPECIAL_CHARS_NOT_ALLOWED"></span>
</div>
-
</div>
-
- <!-- Input source -->
- <!--div class="i-sdc-form-item" data-ng-class="{error:(forms.editForm.source.$dirty && forms.editForm.source.$invalid)}">
- <label class="i-sdc-form-label required">Input Source</label>
- <select class="i-sdc-form-select"
- data-required
- name="source"
- data-ng-model="editPropertyModel.property.source"
- data-ng-options="source for source in editPropertyModel.sources">
- <option value="" >Choose Input Source</option>
- </select>
- <sdc-error-tooltip data-ng-show="forms.editForm.source.$dirty && forms.editForm.source.$invalid">
- <span ng-show="forms.editForm.source.$error.required">source is required.</span>
- </sdc-error-tooltip>
- </div-->
-
-
</div>
<div class="w-sdc-form-column">
@@ -67,7 +50,7 @@
<select class="i-sdc-form-select"
data-tests-id="propertyType"
data-required
- data-ng-disabled="isPropertyValueOwner() || editPropertyModel.property.readonly"
+ data-ng-disabled="isPropertyValueOwner || editPropertyModel.property.readonly"
name="type"
data-ng-change="onTypeChange()"
data-ng-model="editPropertyModel.property.type">
@@ -90,7 +73,7 @@
<select class="i-sdc-form-select"
data-required
data-tests-id="schema-type"
- data-ng-disabled="isPropertyValueOwner() || editPropertyModel.property.readonly"
+ data-ng-disabled="isPropertyValueOwner || editPropertyModel.property.readonly"
name="schemaType"
data-ng-change="onSchemaTypeChange()"
data-ng-model="editPropertyModel.property.schema.property.type">
@@ -123,9 +106,9 @@
<div class="i-sdc-form-item" data-ng-class="{error:(forms.editForm.description.$dirty && forms.editForm.description.$invalid)}">
<label class="i-sdc-form-label">Description</label>
<textarea class="i-sdc-form-textarea"
- data-ng-maxlength="256"
- data-ng-disabled="isPropertyValueOwner() || editPropertyModel.property.readonly"
- maxlength="256"
+ data-ng-maxlength="400"
+ data-ng-disabled="isPropertyValueOwner || editPropertyModel.property.readonly"
+ maxlength="400"
data-ng-pattern="commentValidationPattern"
name="description"
data-ng-model="editPropertyModel.property.description"
@@ -141,16 +124,15 @@
</div>
<!-- Default value -->
- <div data-ng-if="dataTypes" class="default-value-section i-sdc-form-item">
+ <div class="default-value-section i-sdc-form-item">
<label class="i-sdc-form-label">Default Value</label>
<div data-ng-if="isTypeDataType">
<fields-structure value-obj-ref="myValue"
type-name="editPropertyModel.property.type"
parent-form-obj="forms.editForm"
fields-prefix-name="currentPropertyIndex"
- read-only="editPropertyModel.property.readonly && !isPropertyValueOwner()"
+ read-only="editPropertyModel.property.readonly && !isPropertyValueOwner"
default-value="{{getDefaultValue()}}"
- types="dataTypes"
expand-by-default="true"></fields-structure>
</div>
@@ -160,9 +142,8 @@
schema-property="editPropertyModel.property.schema.property"
parent-form-obj="forms.editForm"
fields-prefix-name="currentPropertyIndex"
- read-only="editPropertyModel.property.readonly && !isPropertyValueOwner()"
+ read-only="editPropertyModel.property.readonly && !isPropertyValueOwner"
default-value="{{getDefaultValue()}}"
- types="dataTypes"
max-length="maxLength"></type-map>
</div>
<div ng-switch-when="list">
@@ -170,30 +151,32 @@
schema-property="editPropertyModel.property.schema.property"
parent-form-obj="forms.editForm"
fields-prefix-name="currentPropertyIndex"
- read-only="editPropertyModel.property.readonly && !isPropertyValueOwner()"
+ read-only="editPropertyModel.property.readonly && !isPropertyValueOwner"
default-value="{{getDefaultValue()}}"
- types="dataTypes"
max-length="maxLength"></type-list>
</div>
<div ng-switch-default>
- <div class="i-sdc-form-item" data-ng-class="{error:(forms.editForm.value.$dirty && forms.editForm.value.$invalid)}">
+ <div class="i-sdc-form-item" data-ng-class="{error:(forms.editForm.value.$dirty && forms.editForm.value.$invalid), 'input-group' : editPropertyModel.property.addOn}">
+ <span ng-if="editPropertyModel.property.addOn" class="input-group-addon">{{editPropertyModel.property.addOn}}</span>
<input class="i-sdc-form-input"
data-tests-id="defaultvalue"
ng-if="!((editPropertyModel.property.simpleType||editPropertyModel.property.type) == 'boolean')"
data-ng-maxlength="maxLength"
- data-ng-disabled="editPropertyModel.property.readonly && !isPropertyValueOwner()"
+ data-ng-disabled="editPropertyModel.property.readonly && !isPropertyValueOwner"
maxlength="{{maxLength}}"
data-ng-model="editPropertyModel.property.value"
type="text"
name="value"
data-ng-pattern="getValidationPattern((editPropertyModel.property.simpleType||editPropertyModel.property.type))"
data-ng-model-options="{ debounce: 200 }"
- data-ng-change="!forms.editForm.value.$error.pattern && ('integer'==editPropertyModel.property.type && forms.editForm.value.$setValidity('pattern', validateIntRange(editPropertyModel.property.value)) || onValueChange())"
+ data-ng-change="('json'==editPropertyModel.property.type && forms.editForm.value.$setValidity('pattern', validateJson(editPropertyModel.property.value)))
+ ||(!forms.editForm.value.$error.pattern && ('integer'==editPropertyModel.property.type && forms.editForm.value.$setValidity('pattern', validateIntRange(editPropertyModel.property.value)) || onValueChange()))"
+ data-ng-change=""
autofocus />
<select class="i-sdc-form-select"
data-tests-id="booleantype"
ng-if="(editPropertyModel.property.simpleType||editPropertyModel.property.type) == 'boolean'"
- data-ng-disabled="editPropertyModel.property.readonly && !isPropertyValueOwner()"
+ data-ng-disabled="editPropertyModel.property.readonly && !isPropertyValueOwner"
name="value"
data-ng-change="onValueChange()"
data-ng-model="editPropertyModel.property.value">
@@ -205,7 +188,6 @@
<span ng-show="forms.editForm.value.$error.required" translate="VALIDATION_ERROR_REQUIRED" translate-values="{'field': 'Property' }"></span>
<span ng-show="forms.editForm.value.$error.maxlength" translate="VALIDATION_ERROR_MAX_LENGTH" translate-values="{'max': '{{maxLength}}' }"></span>
<span ng-show="forms.editForm.value.$error.pattern" translate="PROPERTY_EDIT_PATTERN"></span>
- <span ng-show="forms.editForm.value.$error.customValidation" translate="PROPERTY_EDIT_MAP_UNIQUE_KEYS"></span>
</div>
</div>
</div>
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
new file mode 100644
index 0000000000..7359ac0e91
--- /dev/null
+++ b/catalog-ui/src/app/view-models/forms/property-forms/module-property-modal/module-property-model.ts
@@ -0,0 +1,206 @@
+/**
+ * Created by obarda on 1/18/2017.
+ */
+'use strict';
+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";
+import {DataTypesService} from "app/services/data-types-service";
+
+export interface IModulePropertyViewScope extends IPropertyFormBaseViewScope {
+ onValueChange():void;
+}
+
+export class ModulePropertyView extends PropertyFormBaseView {
+
+ static '$inject' = [
+ '$scope',
+ '$templateCache',
+ '$uibModalInstance',
+ '$injector',
+ 'originalProperty',
+ 'component',
+ 'selectedModule',
+ 'Sdc.Services.DataTypesService',
+ '$q'
+ ];
+
+ constructor(protected $scope:IModulePropertyViewScope,
+ protected $templateCache:ng.ITemplateCacheService,
+ protected $uibModalInstance:ng.ui.bootstrap.IModalServiceInstance,
+ protected $injector:ng.auto.IInjectorService,
+ protected originalProperty:PropertyModel,
+ protected component:Component,
+ private selectedModule:DisplayModule,
+ protected DataTypesService:DataTypesService,
+ private $q:ng.IQService) {
+ super($scope, $uibModalInstance, $injector, originalProperty, component, selectedModule.properties, DataTypesService);
+
+ this.$templateCache.put("module-property-view.html", require('app/view-models/forms/property-forms/module-property-modal/module-property-view.html'));
+ this.$scope.innerViewSrcUrl = "module-property-view.html";
+ this.initChildScope();
+ }
+
+ private findPropertyByName = (propertyName:string):PropertyModel => {
+ let property:PropertyModel = _.find(this.filteredProperties, (property:PropertyModel) => {
+ return property.name === propertyName;
+ });
+ return property;
+ };
+
+ save(isNeedToCloseModal):ng.IPromise<boolean> {
+
+ let deferred = this.$q.defer();
+
+ let onSuccess = (properties:Array<PropertyModel>):void => {
+ deferred.resolve(true);
+ if (isNeedToCloseModal === true) {
+ this.$scope.close();
+ }
+ };
+
+ let onFailed = ():void => {
+ deferred.resolve(false);
+ };
+
+ let property = _.find(this.selectedModule.properties, (property) => {
+ return property.uniqueId === this.$scope.property.uniqueId;
+ });
+ if (property.value !== this.$scope.property.value) {
+ if (this.component.isResource()) {
+ (<Resource>this.component).updateResourceGroupProperties(this.selectedModule, [this.$scope.property]).then(onSuccess, onFailed); // for now we only update one property at a time
+ }
+ if (this.component.isService()) {
+ // Find the component instance of the group instance
+ let componentInstance:ComponentInstance = _.find(this.component.componentInstances, (componentInstance:ComponentInstance) => {
+ let groupInstance = _.find(componentInstance.groupInstances, {uniqueId: this.selectedModule.groupInstanceUniqueId});
+ return groupInstance !== undefined;
+
+ });
+ (<Service>this.component).updateGroupInstanceProperties(componentInstance.uniqueId, this.selectedModule, [this.$scope.property]).then(onSuccess, onFailed); // for now we only update one property at a time
+ }
+ } else {
+ deferred.resolve(true);
+ }
+ return deferred.promise;
+ }
+
+ onPropertyChange():void {
+ this.initValidation();
+ }
+
+ protected initValidation = ():void => {
+
+ this.$scope.isDeleteDisable = true;
+ this.$scope.isNameDisable = true;
+ this.$scope.isTypeSelectorDisable = true;
+ this.$scope.isDescriptionDisable = true;
+
+ switch (this.$scope.property.name) {
+ case UNIQUE_GROUP_PROPERTIES_NAME.IS_BASE:
+ case UNIQUE_GROUP_PROPERTIES_NAME.VF_MODULE_TYPE:
+ case UNIQUE_GROUP_PROPERTIES_NAME.VOLUME_GROUP:
+ case UNIQUE_GROUP_PROPERTIES_NAME.VF_MODULE_LABEL:
+ this.$scope.property.readonly = true;
+ break;
+ case UNIQUE_GROUP_PROPERTIES_NAME.VF_MODULE_DESCRIPTION:
+ if (this.component.isService()) {
+ this.$scope.property.readonly = true;
+ } else {
+ this.$scope.property.readonly = false;
+ }
+ break;
+ }
+ };
+
+ private isUniqueProperty = ():boolean => {
+ return this.$scope.property.name === UNIQUE_GROUP_PROPERTIES_NAME.MIN_VF_MODULE_INSTANCES ||
+ this.$scope.property.name === UNIQUE_GROUP_PROPERTIES_NAME.MAX_VF_MODULE_INSTANCES ||
+ this.$scope.property.name === UNIQUE_GROUP_PROPERTIES_NAME.INITIAL_COUNT;
+ };
+
+
+ private initChildScope = ():void => {
+
+ this.initValidation();
+
+ // put default value when instance value is empty
+ this.$scope.onValueChange = ():void => {
+
+ if (!this.$scope.property.value) { // Resetting to default value
+ if (this.isPropertyValueOwner()) {
+ if (this.component.isService()) {
+ this.$scope.property.value = this.$scope.property.parentValue;
+ } else {
+ this.$scope.property.value = this.$scope.property.defaultValue;
+ }
+ }
+ }
+
+ if (this.isUniqueProperty()) {
+
+ let isValid = true;
+ let maxProperty:PropertyModel = this.findPropertyByName(UNIQUE_GROUP_PROPERTIES_NAME.MAX_VF_MODULE_INSTANCES);
+ let minProperty:PropertyModel = this.findPropertyByName(UNIQUE_GROUP_PROPERTIES_NAME.MIN_VF_MODULE_INSTANCES);
+ let initialCountProperty:PropertyModel = this.findPropertyByName(UNIQUE_GROUP_PROPERTIES_NAME.INITIAL_COUNT);
+
+ let maxPropertyValue = parseInt(maxProperty.value);
+ let minPropertyValue = parseInt(minProperty.value);
+ let initialCountPropertyValue = parseInt(initialCountProperty.value);
+ let propertyValue = parseInt(this.$scope.property.value);
+ let parentPropertyValue = parseInt(this.$scope.property.parentValue);
+
+ switch (this.$scope.property.name) {
+
+ case UNIQUE_GROUP_PROPERTIES_NAME.MIN_VF_MODULE_INSTANCES:
+ if (!maxPropertyValue || maxPropertyValue === null) {
+ isValid = propertyValue <= initialCountPropertyValue;
+ }
+ else {
+ isValid = propertyValue && (propertyValue <= maxPropertyValue && propertyValue <= initialCountPropertyValue);
+ }
+ this.$scope.forms.editForm["value"].$setValidity('maxValidation', isValid);
+ if (this.component.isService()) {
+ if (!parentPropertyValue || parentPropertyValue === null) {
+ isValid = true;
+ } else {
+ isValid = propertyValue >= parentPropertyValue;
+ this.$scope.forms.editForm["value"].$setValidity('minValidationVfLevel', isValid);
+ }
+ }
+ break;
+ case UNIQUE_GROUP_PROPERTIES_NAME.MAX_VF_MODULE_INSTANCES:
+ if (!minPropertyValue || minPropertyValue === null) {
+ isValid = propertyValue >= initialCountPropertyValue;
+ } else {
+ isValid = !propertyValue || (propertyValue >= minPropertyValue && propertyValue >= initialCountPropertyValue);
+ }
+ this.$scope.forms.editForm["value"].$setValidity('minValidation', isValid);
+ if (this.component.isService()) {
+ if (!parentPropertyValue || parentPropertyValue === null) {
+ isValid = true;
+ }
+ else {
+ isValid = propertyValue <= parentPropertyValue;
+ this.$scope.forms.editForm["value"].$setValidity('maxValidationVfLevel', isValid);
+ }
+ }
+ break;
+ case UNIQUE_GROUP_PROPERTIES_NAME.INITIAL_COUNT:
+ if ((!minPropertyValue || minPropertyValue === null) && (!maxPropertyValue || maxPropertyValue === null)) {
+ isValid = true;
+ } else if (!minPropertyValue || minPropertyValue === null) {
+ isValid = propertyValue <= maxPropertyValue;
+ } else if (!maxPropertyValue || maxPropertyValue === null) {
+ isValid = propertyValue >= minPropertyValue;
+ } else {
+ isValid = minPropertyValue <= propertyValue && propertyValue <= maxPropertyValue;
+ }
+ this.$scope.forms.editForm["value"].$setValidity('minOrMaxValidation', isValid);
+ break;
+ }
+ }
+ ;
+ }
+ }
+}
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
new file mode 100644
index 0000000000..175f4c199b
--- /dev/null
+++ b/catalog-ui/src/app/view-models/forms/property-forms/module-property-modal/module-property-view.html
@@ -0,0 +1,41 @@
+<div class="default-value-section i-sdc-form-item">
+ <label class="i-sdc-form-label">Default Value</label>
+ <div class="i-sdc-form-item" data-ng-class="{error:(forms.editForm.value.$dirty && forms.editForm.value.$invalid)}">
+ <input class="i-sdc-form-input"
+ data-tests-id="defaultvalue"
+ ng-if="!((property.simpleType||property.type) == 'boolean')"
+ data-ng-maxlength="maxLength"
+ data-ng-disabled="property.readonly && !isPropertyValueOwner()"
+ maxlength="100"
+ data-ng-model="property.value"
+ type="text"
+ name="value"
+ data-ng-pattern="getValidationPattern(property.type)"
+ data-ng-model-options="{ debounce: 200 }"
+ data-ng-change="onValueChange()"
+ />
+ <select class="i-sdc-form-select"
+ data-tests-id="booleantype"
+ ng-if="(property.simpleType||property.type) == 'boolean'"
+ data-ng-disabled="property.readonly && !isPropertyValueOwner()"
+ name="value"
+ data-ng-model="property.value">
+ <option value="true">true</option>
+ <option value="false">false</option>
+ </select>
+
+ <div class="input-error" data-ng-show="forms.editForm.value.$dirty && forms.editForm.value.$invalid">
+ <span ng-show="forms.editForm.value.$error.required" translate="VALIDATION_ERROR_REQUIRED"
+ translate-values="{'field': 'Property' }"></span>
+ <span ng-show="forms.editForm.value.$error.maxlength" translate="VALIDATION_ERROR_MAX_LENGTH"
+ translate-values="{'max': '{{maxLength}}' }"></span>
+ <span ng-show="forms.editForm.value.$error.pattern" translate="PROPERTY_EDIT_PATTERN"></span>
+ <span ng-show="forms.editForm.value.$error.minValidation" translate="MIN_VALIDATION_ERROR"></span>
+ <span ng-show="forms.editForm.value.$error.maxValidation" translate="MAX_VALIDATION_ERROR"></span>
+ <span ng-show="forms.editForm.value.$error.minOrMaxValidation" translate="MIN_MAX_VALIDATION"></span>
+ <span ng-show="forms.editForm.value.$error.minValidationVfLevel" translate="MIN_VALIDATION_VF_LEVE_ERROR"></span>
+ <span ng-show="forms.editForm.value.$error.maxValidationVfLevel" translate="MAX_VALIDATION_VF_LEVE_ERROR"></span>
+
+ </div>
+ </div>
+</div>
diff --git a/catalog-ui/src/app/view-models/forms/property-forms/select-datatype-modal/select-datatype-modal-view-model.ts b/catalog-ui/src/app/view-models/forms/property-forms/select-datatype-modal/select-datatype-modal-view-model.ts
new file mode 100644
index 0000000000..48aa47fdd0
--- /dev/null
+++ b/catalog-ui/src/app/view-models/forms/property-forms/select-datatype-modal/select-datatype-modal-view-model.ts
@@ -0,0 +1,97 @@
+'use strict';
+import {DataTypesService} from "app/services/data-types-service";
+import {PropertyModel, InputPropertyBase, Component} from "app/models";
+import {IPropertyFormBaseViewScope, PropertyFormBaseView} from "../base-property-form/property-form-base-model";
+import {PROPERTY_TYPES} from "app/utils/constants";
+
+interface ISelectDataTypeViewModelScope extends IPropertyFormBaseViewScope {
+ selectedPropertiesName:string;
+ dataTypesService:DataTypesService;
+ path:string;
+ isTypeDataType:boolean;
+ myValue:any;
+ isReadOnly:boolean;
+}
+
+export class SelectDataTypeViewModel extends PropertyFormBaseView {
+
+ static '$inject' = [
+ '$scope',
+ '$templateCache',
+ '$uibModalInstance',
+ '$injector',
+ 'originalProperty',
+ 'component',
+ 'filteredProperties',
+ 'Sdc.Services.DataTypesService',
+ 'propertiesMap',
+ '$q'
+ ];
+
+ constructor(protected $scope:ISelectDataTypeViewModelScope,
+ protected $templateCache:ng.ITemplateCacheService,
+ protected $uibModalInstance:ng.ui.bootstrap.IModalServiceInstance,
+ protected $injector:ng.auto.IInjectorService,
+ protected originalProperty:PropertyModel,
+ protected component:Component,
+ protected filteredProperties:Array<PropertyModel>,
+ protected DataTypesService:DataTypesService,
+ private propertiesMap:Array<InputPropertyBase>,
+ private $q:ng.IQService) {
+ super($scope, $uibModalInstance, $injector, originalProperty, component, filteredProperties, DataTypesService);
+
+ this.$templateCache.put("select-datatype-modal-view.html", require('app/view-models/forms/property-forms/select-datatype-modal/select-datatype-modal-view.html'));
+ this.$scope.innerViewSrcUrl = "select-datatype-modal-view.html";
+ this.initChildScope();
+ }
+
+ //scope methods
+ save(isNeedToCloseModal):ng.IPromise<boolean> {
+ let deferred = this.$q.defer();
+ this.$scope.property.propertiesName = this.DataTypesService.selectedPropertiesName;
+ this.$scope.property.input = this.DataTypesService.selectedInput;
+ this.$scope.property.isAlreadySelected = true;
+ this.$uibModalInstance.close(this.$scope.property);
+ deferred.resolve(true);
+ return deferred.promise;
+ };
+
+ private initForNotSimpleType = ():void => {
+ let property = this.$scope.property;
+ this.$scope.isTypeDataType = this.DataTypesService.isDataTypeForPropertyType(this.$scope.property);
+ if (property.type && this.$scope.simpleTypes.indexOf(property.type) == -1) {
+ if (!(property.value || property.defaultValue)) {
+ switch (property.type) {
+ case PROPERTY_TYPES.MAP:
+ this.$scope.myValue = {'': null};
+ break;
+ case PROPERTY_TYPES.LIST:
+ this.$scope.myValue = [];
+ break;
+ default:
+ this.$scope.myValue = {};
+ }
+ } else {
+ this.$scope.myValue = JSON.parse(property.value || property.defaultValue);
+ }
+ }
+ };
+
+ //remove selection property on the modal
+ private removeSelected = ():void => {
+ this.DataTypesService.selectedPropertiesName = null;
+ this.DataTypesService.selectedInput = null;
+ };
+
+ private initChildScope = ():void => {
+ //scope properties
+ this.$scope.forms = {};
+ this.$scope.path = this.$scope.property.name;
+ this.$scope.isArrowsDisabled = true;
+ this.DataTypesService.alreadySelectedProperties = this.propertiesMap;
+ this.$scope.dataTypesService = this.DataTypesService;
+ this.$scope.isReadOnly = true;
+ this.initForNotSimpleType();
+ this.removeSelected();
+ }
+}
diff --git a/catalog-ui/src/app/view-models/forms/property-forms/select-datatype-modal/select-datatype-modal-view.html b/catalog-ui/src/app/view-models/forms/property-forms/select-datatype-modal/select-datatype-modal-view.html
new file mode 100644
index 0000000000..acb0f292ff
--- /dev/null
+++ b/catalog-ui/src/app/view-models/forms/property-forms/select-datatype-modal/select-datatype-modal-view.html
@@ -0,0 +1,74 @@
+<!--<div>selectedPropertiesName - {{dataTypesService.selectedPropertiesName}}</div>-->
+<!--<div>selectedInput - {{dataTypesService.selectedInput}}</div>-->
+
+<div data-ng-if="dataTypes" class="default-value-section i-sdc-form-item">
+ <label class="i-sdc-form-label">Default Value</label>
+ <div data-ng-if="isTypeDataType">
+ <select-fields-structure value-obj-ref="myValue"
+ type-name="property.type"
+ parent-form-obj="forms.editForm"
+ fields-prefix-name="currentPropertyIndex"
+ read-only="true"
+ default-value="{{getDefaultValue()}}"
+ path="{{property.name}}"
+ is-parent-already-input="false"
+ expand-by-default="true"></select-fields-structure>
+
+ </div>
+ <div data-ng-if="!isTypeDataType" ng-switch="property.type">
+ <div ng-switch-when="map">
+
+ <select-type-map value-obj-ref="myValue"
+ schema-property="property.schema.property"
+ parent-form-obj="forms.editForm"
+ fields-prefix-name="currentPropertyIndex"
+ read-only="true"
+ default-value="{{getDefaultValue()}}"
+ max-length="maxLength"></select-type-map>
+ </div>
+ <div ng-switch-when="list">
+ <select-type-list value-obj-ref="myValue"
+ schema-property="property.schema.property"
+ parent-form-obj="forms.editForm"
+ fields-prefix-name="currentPropertyIndex"
+ read-only="true"
+ default-value="{{getDefaultValue()}}"
+ max-length="maxLength"></select-type-list>
+ </div>
+ <div ng-switch-default>
+ <div class="i-sdc-form-item" data-ng-class="{error:(forms.editForm.value.$dirty && forms.editForm.value.$invalid)}">
+ <input class="i-sdc-form-input"
+ data-tests-id="defaultvalue"
+ ng-if="!((property.simpleType||property.type) == 'boolean')"
+ data-ng-maxlength="maxLength"
+ data-ng-disabled="isReadOnly"
+ maxlength="{{maxLength}}"
+ data-ng-model="property.value"
+ type="text"
+ name="value"
+ data-ng-pattern="getValidationPattern((property.simpleType||property.type))"
+ data-ng-model-options="{ debounce: 200 }"
+ data-ng-change="('json'==property.type && forms.editForm.value.$setValidity('pattern', validateJson(property.value)))
+ ||(!forms.editForm.value.$error.pattern && ('integer'==property.type && forms.editForm.value.$setValidity('pattern', validateIntRange(property.value)) || onValueChange()))"
+ data-ng-change=""
+ autofocus />
+ <select class="i-sdc-form-select"
+ data-tests-id="booleantype"
+ ng-if="(property.simpleType||property.type) == 'boolean'"
+ data-ng-disabled="isReadOnly"
+ name="value"
+ data-ng-change="onValueChange()"
+ data-ng-model="property.value">
+ <option value="true">true</option>
+ <option value="false">false</option>
+ </select>
+
+ <div class="input-error" data-ng-show="forms.editForm.value.$dirty && forms.editForm.value.$invalid">
+ <span ng-show="forms.editForm.value.$error.required" translate="VALIDATION_ERROR_REQUIRED" translate-values="{'field': 'Property' }"></span>
+ <span ng-show="forms.editForm.value.$error.maxlength" translate="VALIDATION_ERROR_MAX_LENGTH" translate-values="{'max': '{{maxLength}}' }"></span>
+ <span ng-show="forms.editForm.value.$error.pattern" translate="PROPERTY_EDIT_PATTERN"></span>
+ </div>
+ </div>
+ </div>
+ </div>
+</div>
diff --git a/catalog-ui/src/app/view-models/forms/property-forms/select-datatype-modal/select-datatype-modal.less b/catalog-ui/src/app/view-models/forms/property-forms/select-datatype-modal/select-datatype-modal.less
new file mode 100644
index 0000000000..15e30af4ee
--- /dev/null
+++ b/catalog-ui/src/app/view-models/forms/property-forms/select-datatype-modal/select-datatype-modal.less
@@ -0,0 +1,63 @@
+.sdc-edit-property-container {
+ .scrollbar-container{
+ height: 415px;
+ width: 830px;
+ .perfect-scrollbar;
+ }
+
+ form{
+ width: 813px;
+ [name="description"]{
+ min-height:50px;
+ }
+ }
+
+ .sdc-modal-top-bar{
+ height: 40px;
+ .sdc-modal-top-bar-buttons {
+ float: right;
+
+ > span:not(.delimiter){
+ vertical-align: middle;
+ .hand;
+
+ &.sprite-new {
+ text-indent: 100%;
+ }
+ &.disabled, &:hover.disabled {
+ pointer-events: none;
+ }
+ }
+
+ .delete-btn{
+ margin-right: 6px;
+ }
+
+ .left-arrow{
+ margin-right: 8px;
+ }
+
+ .delimiter {
+ height: 20px;
+ width: 1px;
+ background-color: #959595;
+ display: inline-block;
+ vertical-align: middle;
+ margin-right: 10px;
+ }
+ }
+ }
+
+ .w-sdc-form-note {
+ .h_9;
+ display: block;
+ position: relative;
+ top: 13px;
+ }
+
+ .default-value-section{
+ border-top: solid 1px @main_color_a;
+ padding-top: 15px;
+ margin-top: 15px;
+ }
+}
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
new file mode 100644
index 0000000000..869e3db584
--- /dev/null
+++ b/catalog-ui/src/app/view-models/forms/resource-instance-name-form/resource-instance-name-model.ts
@@ -0,0 +1,95 @@
+'use strict';
+import {ComponentInstanceFactory} from "app/utils";
+import {ComponentInstance} from "app/models";
+import {Requirement, Component, Capability} from "app/models";
+
+interface IResourceInstanceViewModelScope extends ng.IScope {
+
+ componentInstanceModel:ComponentInstance;
+ validationPattern:RegExp;
+ oldName:string;
+ isAlreadyPressed:boolean;
+ footerButtons:Array<any>;
+ forms:any;
+ modalInstanceName:ng.ui.bootstrap.IModalServiceInstance;
+
+ save():void;
+ close():void;
+}
+
+export class ResourceInstanceNameViewModel {
+
+ static '$inject' = [
+ '$scope',
+ 'ValidationPattern',
+ '$uibModalInstance',
+ 'component'
+ ];
+
+
+ constructor(private $scope:IResourceInstanceViewModelScope,
+ private ValidationPattern:RegExp,
+ private $uibModalInstance:ng.ui.bootstrap.IModalServiceInstance,
+ private component:Component) {
+
+ this.initScope();
+ }
+
+
+ private initScope = ():void => {
+ this.$scope.forms = {};
+ this.$scope.validationPattern = this.ValidationPattern;
+ this.$scope.componentInstanceModel = ComponentInstanceFactory.createComponentInstance(this.component.selectedInstance);
+ this.$scope.oldName = this.component.selectedInstance.name;
+ this.$scope.modalInstanceName = this.$uibModalInstance;
+
+ this.$scope.isAlreadyPressed = false;
+
+
+ this.$scope.close = ():void => {
+ this.$uibModalInstance.dismiss();
+ };
+
+ this.$scope.save = ():void => {
+
+ let onFailed = () => {
+ this.$scope.isAlreadyPressed = true;
+ };
+
+ let onSuccess = (componentInstance:ComponentInstance) => {
+ this.$uibModalInstance.close();
+ this.$scope.isAlreadyPressed = false;
+ this.$scope.componentInstanceModel = componentInstance;
+ //this.component.name = componentInstance.name;//DE219124
+ this.component.selectedInstance.name = componentInstance.name;
+ //update requirements and capabilities owner name
+ _.forEach(this.component.selectedInstance.requirements, (requirementsArray:Array<Requirement>) => {
+ _.forEach(requirementsArray, (requirement:Requirement):void => {
+ requirement.ownerName = componentInstance.name;
+ });
+ });
+
+ _.forEach(this.component.selectedInstance.capabilities, (capabilitiesArray:Array<Capability>) => {
+ _.forEach(capabilitiesArray, (capability:Capability):void => {
+ capability.ownerName = componentInstance.name;
+ });
+ });
+
+ };
+
+ this.$scope.isAlreadyPressed = true;
+ if (this.$scope.oldName != this.$scope.componentInstanceModel.name) {
+ this.component.updateComponentInstance(this.$scope.componentInstanceModel).then(onSuccess, onFailed);
+ }
+ };
+
+ this.$scope.footerButtons = [
+ {'name': 'OK', 'css': 'blue', 'callback': this.$scope.save},
+ {'name': 'Cancel', 'css': 'grey', 'callback': this.$scope.close}
+ ];
+
+ this.$scope.$watch("[forms.editNameForm.$invalid,componentInstanceModel.name,isAlreadyPressed]", (newVal, oldVal) => {
+ this.$scope.footerButtons[0].disabled = this.$scope.forms.editNameForm.$invalid || this.$scope.isAlreadyPressed || this.$scope.componentInstanceModel.name === this.$scope.oldName;
+ });
+ }
+}
diff --git a/catalog-ui/app/scripts/view-models/forms/resource-instance-name-form/resource-instance-name-view.html b/catalog-ui/src/app/view-models/forms/resource-instance-name-form/resource-instance-name-view.html
index e04343adbd..e04343adbd 100644
--- a/catalog-ui/app/scripts/view-models/forms/resource-instance-name-form/resource-instance-name-view.html
+++ b/catalog-ui/src/app/view-models/forms/resource-instance-name-form/resource-instance-name-view.html
diff --git a/catalog-ui/app/scripts/view-models/forms/resource-instance-name-form/resource-instance-name.less b/catalog-ui/src/app/view-models/forms/resource-instance-name-form/resource-instance-name.less
index 57698bef17..57698bef17 100644
--- a/catalog-ui/app/scripts/view-models/forms/resource-instance-name-form/resource-instance-name.less
+++ b/catalog-ui/src/app/view-models/forms/resource-instance-name-form/resource-instance-name.less
diff --git a/catalog-ui/src/app/view-models/modals/confirmation-modal/confirmation-modal-view-model.ts b/catalog-ui/src/app/view-models/modals/confirmation-modal/confirmation-modal-view-model.ts
new file mode 100644
index 0000000000..3d8b6c3053
--- /dev/null
+++ b/catalog-ui/src/app/view-models/modals/confirmation-modal/confirmation-modal-view-model.ts
@@ -0,0 +1,73 @@
+'use strict';
+import {ValidationUtils, ModalType} from "app/utils";
+
+export interface IConfirmationModalModel {
+ title:string;
+ message:string;
+ showComment:boolean;
+ type:ModalType;
+}
+
+interface IConfirmationModalViewModelScope {
+ modalInstanceConfirmation:ng.ui.bootstrap.IModalServiceInstance;
+ confirmationModalModel:IConfirmationModalModel;
+ comment:any;
+ commentValidationPattern:RegExp;
+ editForm:ng.IFormController;
+ okButtonColor:string;
+ hideCancelButton:boolean;
+ ok():any;
+ cancel():void;
+}
+
+export class ConfirmationModalViewModel {
+
+ static '$inject' = ['$scope', '$uibModalInstance', 'confirmationModalModel', 'CommentValidationPattern', 'ValidationUtils'];
+
+ constructor(private $scope:IConfirmationModalViewModelScope,
+ private $uibModalInstance:ng.ui.bootstrap.IModalServiceInstance,
+ confirmationModalModel:IConfirmationModalModel,
+ private CommentValidationPattern:RegExp,
+ private ValidationUtils:ValidationUtils) {
+
+ this.initScope(confirmationModalModel);
+ }
+
+ private initScope = (confirmationModalModel:IConfirmationModalModel):void => {
+ let self = this;
+ this.$scope.hideCancelButton = false;
+ this.$scope.modalInstanceConfirmation = this.$uibModalInstance;
+ this.$scope.confirmationModalModel = confirmationModalModel;
+ this.$scope.comment = {"text": ''};
+ this.$scope.commentValidationPattern = this.CommentValidationPattern;
+
+ this.$scope.ok = ():any => {
+ self.$uibModalInstance.close(this.ValidationUtils.stripAndSanitize(self.$scope.comment.text));
+ };
+
+ this.$scope.cancel = ():void => {
+ console.info('Cancel pressed on: ' + this.$scope.confirmationModalModel.title);
+ self.$uibModalInstance.dismiss();
+ };
+
+ // Set the OK button color according to modal type (standard, error, alert)
+ let _okButtonColor = 'blue'; // Default
+ switch (confirmationModalModel.type) {
+ case ModalType.STANDARD:
+ _okButtonColor = 'blue';
+ break;
+ case ModalType.ERROR:
+ _okButtonColor = 'red';
+ break;
+ case ModalType.ALERT:
+ this.$scope.hideCancelButton = true;
+ _okButtonColor = 'grey';
+ break;
+ default:
+ _okButtonColor = 'blue';
+ break;
+ }
+ this.$scope.okButtonColor = _okButtonColor;
+
+ }
+}
diff --git a/catalog-ui/app/scripts/view-models/modals/confirmation-modal/confirmation-modal-view.html b/catalog-ui/src/app/view-models/modals/confirmation-modal/confirmation-modal-view.html
index 09c27f8cd3..09c27f8cd3 100644
--- a/catalog-ui/app/scripts/view-models/modals/confirmation-modal/confirmation-modal-view.html
+++ b/catalog-ui/src/app/view-models/modals/confirmation-modal/confirmation-modal-view.html
diff --git a/catalog-ui/app/scripts/view-models/modals/confirmation-modal/confirmation-modal.less b/catalog-ui/src/app/view-models/modals/confirmation-modal/confirmation-modal.less
index 666c41d5ed..666c41d5ed 100644
--- a/catalog-ui/app/scripts/view-models/modals/confirmation-modal/confirmation-modal.less
+++ b/catalog-ui/src/app/view-models/modals/confirmation-modal/confirmation-modal.less
diff --git a/catalog-ui/src/app/view-models/modals/email-modal/email-modal-view-model.ts b/catalog-ui/src/app/view-models/modals/email-modal/email-modal-view-model.ts
new file mode 100644
index 0000000000..f1fb56d0ff
--- /dev/null
+++ b/catalog-ui/src/app/view-models/modals/email-modal/email-modal-view-model.ts
@@ -0,0 +1,96 @@
+'use strict';
+import {IAppConfigurtaion, Component, AsdcComment} from "app/models";
+import {ValidationUtils} from "app/utils";
+
+export interface IEmailModalModel_Email {
+ to:string;
+ subject:string;
+ message:string;
+}
+
+export interface IEmailModalModel_Data {
+ component:Component;
+ stateUrl:string;
+}
+
+export interface IEmailModalModel {
+ title:string;
+ email:IEmailModalModel_Email;
+ data:IEmailModalModel_Data;
+}
+
+interface IEmailModalViewModelScope {
+ modalInstanceEmail:ng.ui.bootstrap.IModalServiceInstance;
+ emailModalModel:IEmailModalModel;
+ submitInProgress:boolean;
+ commentValidationPattern:RegExp;
+ isLoading:boolean;
+ submit():any;
+ cancel():void;
+ validateField(field:any):boolean;
+}
+
+export class EmailModalViewModel {
+
+ static '$inject' = ['$scope', '$filter', 'sdcConfig', '$uibModalInstance', 'emailModalModel', 'ValidationUtils', 'CommentValidationPattern'];
+
+ constructor(private $scope:IEmailModalViewModelScope,
+ private $filter:ng.IFilterService,
+ private sdcConfig:IAppConfigurtaion,
+ private $uibModalInstance:ng.ui.bootstrap.IModalServiceInstance,
+ private emailModalModel:IEmailModalModel,
+ private ValidationUtils:ValidationUtils,
+ private CommentValidationPattern:RegExp) {
+
+ this.initScope(emailModalModel);
+ }
+
+ private initScope = (emailModalModel:IEmailModalModel):void => {
+ this.$scope.emailModalModel = emailModalModel;
+ this.$scope.submitInProgress = false;
+ this.$scope.commentValidationPattern = this.CommentValidationPattern;
+ this.$scope.modalInstanceEmail = this.$uibModalInstance;
+
+ this.$scope.submit = ():any => {
+
+ let onSuccess = (component:Component) => {
+ this.$scope.isLoading = false;
+ this.$scope.submitInProgress = false;
+ // showing the outlook modal according to the config json
+ if (this.sdcConfig.showOutlook) {
+ let link:string = encodeURI(this.sdcConfig.api.baseUrl + "?folder=Ready_For_Testing");
+ let outlook:string = this.$filter('translate')("EMAIL_OUTLOOK_MESSAGE", "{'to': '" + emailModalModel.email.to + "','subject': '" + emailModalModel.email.subject + "','message': '" + emailModalModel.email.message + "', 'entityNameAndVersion': '" + emailModalModel.email.subject + "','link': '" + link + "'}");
+ window.location.href = outlook; // Open outlook with the email to send
+ }
+ this.$uibModalInstance.close(component); // Close the dialog
+ };
+
+ let onError = () => {
+ this.$scope.isLoading = false;
+ this.$scope.submitInProgress = false;
+ this.$uibModalInstance.close(); // Close the dialog
+ };
+
+ // Submit to server
+ // Prevent from user pressing multiple times on submit.
+ if (this.$scope.submitInProgress === false) {
+ this.$scope.isLoading = true;
+ this.$scope.submitInProgress = true;
+ let comment:AsdcComment = new AsdcComment();
+ comment.userRemarks = emailModalModel.email.message;
+ emailModalModel.data.component.changeLifecycleState(emailModalModel.data.stateUrl, comment).then(onSuccess, onError);
+ }
+ };
+
+ this.$scope.cancel = ():void => {
+ this.$uibModalInstance.dismiss();
+ };
+
+ this.$scope.validateField = (field:any):boolean => {
+ if (field && field.$dirty && field.$invalid) {
+ return true;
+ }
+ return false;
+ };
+ }
+}
diff --git a/catalog-ui/app/scripts/view-models/modals/email-modal/email-modal-view.html b/catalog-ui/src/app/view-models/modals/email-modal/email-modal-view.html
index 82293a3091..bf65428033 100644
--- a/catalog-ui/app/scripts/view-models/modals/email-modal/email-modal-view.html
+++ b/catalog-ui/src/app/view-models/modals/email-modal/email-modal-view.html
@@ -1,7 +1,6 @@
<sdc-modal modal="modalInstanceEmail" type="classic" class="w-sdc-modal-email modal-type-standard" header="{{emailModalModel.title}}" show-close-button="true">
<loader data-display="isLoading"></loader>
<form novalidate class="w-sdc-form" name="editForm">
- <div class="w-sdc-modal-body">
<div class="i-sdc-form-item" data-ng-class="{'error': validateField(editForm.to)}">
<label class="i-sdc-form-label col-sm-2">To</label>
@@ -69,7 +68,6 @@
</div>
- </div>
</form>
<div class="w-sdc-modal-footer classic">
diff --git a/catalog-ui/app/scripts/view-models/modals/email-modal/email-modal.less b/catalog-ui/src/app/view-models/modals/email-modal/email-modal.less
index b946a097cd..471089fa1a 100644
--- a/catalog-ui/app/scripts/view-models/modals/email-modal/email-modal.less
+++ b/catalog-ui/src/app/view-models/modals/email-modal/email-modal.less
@@ -27,6 +27,7 @@
box-sizing: border-box;
width: 100%;
height: 127px;
+ margin-bottom: 20px;
}
label {.m_14_m; text-align: left;}
diff --git a/catalog-ui/src/app/view-models/modals/error-modal/error-403-view.html b/catalog-ui/src/app/view-models/modals/error-modal/error-403-view.html
new file mode 100644
index 0000000000..41b1c6df1d
--- /dev/null
+++ b/catalog-ui/src/app/view-models/modals/error-modal/error-403-view.html
@@ -0,0 +1,4 @@
+<div class="sdc-error-403-container" >
+ <div class="sdc-error-403-container-title" translate="GENERAL_ERROR_403_TITLE"></div>
+ <div class="w-sdc-error-403-text w-sdc-form" translate="GENERAL_ERROR_403_DESCRIPTION" translate-values="{{ mailtoJson }}"></div>
+</div>
diff --git a/catalog-ui/src/app/view-models/modals/error-modal/error-view-model.ts b/catalog-ui/src/app/view-models/modals/error-modal/error-view-model.ts
new file mode 100644
index 0000000000..f622a6f53b
--- /dev/null
+++ b/catalog-ui/src/app/view-models/modals/error-modal/error-view-model.ts
@@ -0,0 +1,19 @@
+'use strict';
+import {CookieService} from "app/services";
+
+interface IErrorViewModelScope {
+ mailto:string;
+}
+
+export class ErrorViewModel {
+
+ static ADMIN_EMAIL = 'dl-asdcaccessrequest@att.com';
+ static SUBJECT_PRFIEX = 'SDC Access Request for';
+
+ static '$inject' = ['$scope', 'Sdc.Services.CookieService', '$window'];
+
+ constructor($scope:IErrorViewModelScope, cookieService:CookieService, $window) {
+ let userDetails = cookieService.getFirstName() + ' ' + cookieService.getLastName() + ' (' + cookieService.getUserId() + ')';
+ $scope.mailto = ErrorViewModel.ADMIN_EMAIL + '?subject=' + $window.encodeURIComponent(ErrorViewModel.SUBJECT_PRFIEX + ' ' + userDetails);
+ }
+}
diff --git a/catalog-ui/app/scripts/view-models/modals/error-modal/error.less b/catalog-ui/src/app/view-models/modals/error-modal/error.less
index 8297b5053d..8297b5053d 100644
--- a/catalog-ui/app/scripts/view-models/modals/error-modal/error.less
+++ b/catalog-ui/src/app/view-models/modals/error-modal/error.less
diff --git a/catalog-ui/src/app/view-models/modals/message-modal/message-base-modal-model.ts b/catalog-ui/src/app/view-models/modals/message-modal/message-base-modal-model.ts
new file mode 100644
index 0000000000..3c9e75238a
--- /dev/null
+++ b/catalog-ui/src/app/view-models/modals/message-modal/message-base-modal-model.ts
@@ -0,0 +1,43 @@
+'use strict';
+import {SEVERITY} from "app/utils";
+
+export interface IMessageModalModel {
+ title:string;
+ message:string;
+ severity:SEVERITY;
+}
+
+export interface IMessageModalViewModelScope extends ng.IScope {
+ footerButtons:Array<any>;
+ messageModalModel:IMessageModalModel;
+ modalInstanceError:ng.ui.bootstrap.IModalServiceInstance;
+ ok():void;
+}
+
+export class MessageModalViewModel {
+
+ constructor(private $baseScope:IMessageModalViewModelScope,
+ private $baseModalInstance:ng.ui.bootstrap.IModalServiceInstance,
+ private baseMessageModalModel:IMessageModalModel) {
+
+ this.initScope(baseMessageModalModel);
+ }
+
+ private initScope = (messageModalViewModel:IMessageModalModel):void => {
+
+ this.$baseScope.messageModalModel = messageModalViewModel;
+ this.$baseScope.modalInstanceError = this.$baseModalInstance;
+
+ this.$baseScope.ok = ():void => {
+ this.$baseModalInstance.close();
+ };
+
+ this.$baseScope.footerButtons = [
+ {
+ 'name': 'OK',
+ 'css': 'grey',
+ 'callback': this.$baseScope.ok
+ }
+ ];
+ }
+}
diff --git a/catalog-ui/src/app/view-models/modals/message-modal/message-client-modal/client-message-modal-view-model.ts b/catalog-ui/src/app/view-models/modals/message-modal/message-client-modal/client-message-modal-view-model.ts
new file mode 100644
index 0000000000..053ea41ba3
--- /dev/null
+++ b/catalog-ui/src/app/view-models/modals/message-modal/message-client-modal/client-message-modal-view-model.ts
@@ -0,0 +1,22 @@
+'use strict';
+import {IMessageModalModel, MessageModalViewModel, IMessageModalViewModelScope} from "../message-base-modal-model";
+
+export interface IClientMessageModalModel extends IMessageModalModel {
+}
+
+export interface IClientMessageModalViewModelScope extends IMessageModalViewModelScope {
+ clientMessageModalModel:IClientMessageModalModel;
+}
+
+export class ClientMessageModalViewModel extends MessageModalViewModel {
+
+ static '$inject' = ['$scope', '$uibModalInstance', 'clientMessageModalModel'];
+
+ constructor(private $scope:IClientMessageModalViewModelScope,
+ private $uibModalInstance:ng.ui.bootstrap.IModalServiceInstance,
+ private clientMessageModalModel:IClientMessageModalModel) {
+
+ super($scope, $uibModalInstance, clientMessageModalModel);
+ }
+
+}
diff --git a/catalog-ui/app/scripts/view-models/modals/message-modal/message-client-modal/client-message-modal-view.html b/catalog-ui/src/app/view-models/modals/message-modal/message-client-modal/client-message-modal-view.html
index cfb0a35f69..cfb0a35f69 100644
--- a/catalog-ui/app/scripts/view-models/modals/message-modal/message-client-modal/client-message-modal-view.html
+++ b/catalog-ui/src/app/view-models/modals/message-modal/message-client-modal/client-message-modal-view.html
diff --git a/catalog-ui/app/scripts/view-models/modals/message-modal/message-server-modal/server-message-modal.less b/catalog-ui/src/app/view-models/modals/message-modal/message-client-modal/client-message-modal.less
index e69de29bb2..e69de29bb2 100644
--- a/catalog-ui/app/scripts/view-models/modals/message-modal/message-server-modal/server-message-modal.less
+++ b/catalog-ui/src/app/view-models/modals/message-modal/message-client-modal/client-message-modal.less
diff --git a/catalog-ui/src/app/view-models/modals/message-modal/message-server-modal/server-message-modal-view-model.ts b/catalog-ui/src/app/view-models/modals/message-modal/message-server-modal/server-message-modal-view-model.ts
new file mode 100644
index 0000000000..5f1d5e7a92
--- /dev/null
+++ b/catalog-ui/src/app/view-models/modals/message-modal/message-server-modal/server-message-modal-view-model.ts
@@ -0,0 +1,24 @@
+'use strict';
+import {IMessageModalModel, IMessageModalViewModelScope, MessageModalViewModel} from "../message-base-modal-model";
+
+export interface IServerMessageModalModel extends IMessageModalModel {
+ status:string;
+ messageId:string;
+}
+
+export interface IServerMessageModalViewModelScope extends IMessageModalViewModelScope {
+ serverMessageModalModel:IServerMessageModalModel;
+}
+
+export class ServerMessageModalViewModel extends MessageModalViewModel {
+
+ static '$inject' = ['$scope', '$uibModalInstance', 'serverMessageModalModel'];
+
+ constructor(private $scope:IServerMessageModalViewModelScope,
+ private $uibModalInstance:ng.ui.bootstrap.IModalServiceInstance,
+ private serverMessageModalModel:IServerMessageModalModel) {
+
+ super($scope, $uibModalInstance, serverMessageModalModel);
+ }
+
+}
diff --git a/catalog-ui/app/scripts/view-models/modals/message-modal/message-server-modal/server-message-modal-view.html b/catalog-ui/src/app/view-models/modals/message-modal/message-server-modal/server-message-modal-view.html
index 294dc76c4c..294dc76c4c 100644
--- a/catalog-ui/app/scripts/view-models/modals/message-modal/message-server-modal/server-message-modal-view.html
+++ b/catalog-ui/src/app/view-models/modals/message-modal/message-server-modal/server-message-modal-view.html
diff --git a/catalog-ui/src/app/view-models/modals/message-modal/message-server-modal/server-message-modal.less b/catalog-ui/src/app/view-models/modals/message-modal/message-server-modal/server-message-modal.less
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/catalog-ui/src/app/view-models/modals/message-modal/message-server-modal/server-message-modal.less
diff --git a/catalog-ui/src/app/view-models/modals/onboarding-modal/onboarding-modal-view-model.ts b/catalog-ui/src/app/view-models/modals/onboarding-modal/onboarding-modal-view-model.ts
new file mode 100644
index 0000000000..8e7e79c576
--- /dev/null
+++ b/catalog-ui/src/app/view-models/modals/onboarding-modal/onboarding-modal-view-model.ts
@@ -0,0 +1,249 @@
+'use strict';
+import {ComponentType, CHANGE_COMPONENT_CSAR_VERSION_FLAG, SEVERITY, FileUtils, ModalsHandler, ComponentFactory} from "app/utils";
+import {OnboardingService, CacheService} from "app/services";
+import {Component, IComponent, IUser, IAppConfigurtaion, Resource} from "app/models";
+import {IServerMessageModalModel} from "../message-modal/message-server-modal/server-message-modal-view-model";
+import {Dictionary} from "app/utils";
+import * as _ from 'underscore';
+
+interface IOnboardingModalViewModelScope {
+ modalOnboarding:ng.ui.bootstrap.IModalServiceInstance;
+ componentsList:Array<IComponent>;
+ tableHeadersList:Array<any>;
+ selectedComponent:Component;
+ componentFromServer:Component;
+ reverse:boolean;
+ sortBy:string;
+ searchBind:string;
+ okButtonText:string;
+ isCsarComponentExists:boolean;
+ user:IUser;
+ isLoading:boolean;
+
+ //this is for UI paging
+ numberOfItemsToDisplay:number;
+ allItemsDisplayed:boolean;
+
+ doSelectComponent(component:Component):void;
+ doUpdateCsar():void;
+ doImportCsar():void;
+ sort(sortBy:string):void;
+ downloadCsar(packageId:string):void;
+ increaseNumItemsToDisplay():void;
+}
+
+export class OnboardingModalViewModel {
+
+ static '$inject' = [
+ '$scope',
+ '$filter',
+ '$state',
+ 'sdcConfig',
+ '$uibModalInstance',
+ 'Sdc.Services.OnboardingService',
+ 'okButtonText',
+ 'currentCsarUUID',
+ 'Sdc.Services.CacheService',
+ 'FileUtils',
+ 'ComponentFactory',
+ 'ModalsHandler'
+ ];
+
+ constructor(private $scope:IOnboardingModalViewModelScope,
+ private $filter:ng.IFilterService,
+ private $state:any,
+ private sdcConfig:IAppConfigurtaion,
+ private $uibModalInstance:ng.ui.bootstrap.IModalServiceInstance,
+ private onBoardingService:OnboardingService,
+ private okButtonText:string,
+ private currentCsarUUID:string,
+ private cacheService:CacheService,
+ private fileUtils:FileUtils,
+ private componentFactory:ComponentFactory,
+ private modalsHandler:ModalsHandler) {
+
+ this.init();
+ }
+
+ /**
+ * Called from controller constructor, this will call onboarding service to get list
+ * of "mini" components (empty components created from CSAR).
+ * The list is inserted to componentsList on $scope.
+ * And then call initScope method.
+ */
+ private init = ():void => {
+ this.initOnboardingComponentsList();
+ };
+
+ private initScope = ():void => {
+
+ this.initSortedTableScope();
+ this.initModalScope();
+ this.$scope.sortBy = "name"; // Default sort by
+ this.$scope.user = this.cacheService.get('user');
+ this.$scope.okButtonText = this.okButtonText;
+ this.$scope.numberOfItemsToDisplay = 0;
+ this.$scope.allItemsDisplayed = false;
+
+ // Dismiss the modal and pass the "mini" component to workspace general page
+ this.$scope.doImportCsar = ():void => {
+ this.$uibModalInstance.dismiss();
+ this.$state.go('workspace.general', {
+ type: ComponentType.RESOURCE.toLowerCase(),
+ componentCsar: this.$scope.selectedComponent
+ });
+ };
+
+ this.$scope.doUpdateCsar = ():void => {
+ // In case user select on update the checkin and submit for testing buttons (in general page) should be disabled.
+ // to do that we need to pass to workspace.general state parameter to know to disable the buttons.
+ this.$uibModalInstance.close();
+ // Change the component version to the CSAR version we want to update.
+ /*(<Resource>this.$scope.componentFromServer).csarVersion = (<Resource>this.$scope.selectedComponent).csarVersion;
+ let component:Components.Component = this.componentFactory.createComponent(this.$scope.componentFromServer);
+ this.$state.go('workspace.general', {vspComponent: component, disableButtons: true });*/
+ this.cacheService.set(CHANGE_COMPONENT_CSAR_VERSION_FLAG, (<Resource>this.$scope.selectedComponent).csarVersion);
+ this.$state.go('workspace.general', {
+ id: this.$scope.componentFromServer.uniqueId,
+ type: this.$scope.componentFromServer.componentType.toLowerCase(),
+ disableButtons: true
+ });
+ };
+
+ this.$scope.downloadCsar = (packageId:string):void => {
+ this.$scope.isLoading = true;
+ this.onBoardingService.downloadOnboardingCsar(packageId).then(
+ (file:any):void => {
+ this.$scope.isLoading = false;
+ if (file) {
+ this.fileUtils.downloadFile(file, packageId + '.csar');
+ }
+ }, ():void => {
+ this.$scope.isLoading = false;
+ var data:IServerMessageModalModel = {
+ title: 'Download error',
+ message: "Error downloading file",
+ severity: SEVERITY.ERROR,
+ messageId: "",
+ status: ""
+ };
+ this.modalsHandler.openServerMessageModal(data);
+ }
+ );
+ };
+
+ this.$scope.increaseNumItemsToDisplay = ():void => {
+ this.$scope.numberOfItemsToDisplay = this.$scope.numberOfItemsToDisplay + 40;
+ if (this.$scope.componentsList) {
+ this.$scope.allItemsDisplayed = this.$scope.numberOfItemsToDisplay >= this.$scope.componentsList.length;
+ }
+ };
+
+ // When the user select a row, set the component as selectedComponent
+ this.$scope.doSelectComponent = (component:Component):void => {
+
+ if (this.$scope.selectedComponent === component) {
+ // Collapse the item
+ this.$scope.selectedComponent = undefined;
+ return;
+ }
+
+ this.$scope.isLoading = true;
+ this.$scope.componentFromServer = undefined;
+ this.$scope.selectedComponent = component;
+
+ let onSuccess = (componentFromServer:Component):void => {
+ this.$scope.isLoading = false;
+ if (componentFromServer) {
+ this.$scope.componentFromServer = componentFromServer;
+ this.$scope.isCsarComponentExists = true;
+ } else {
+ this.$scope.componentFromServer = component;
+ this.$scope.isCsarComponentExists = false;
+ }
+ };
+
+ let onError = ():void => {
+ this.$scope.isLoading = false;
+ this.$scope.componentFromServer = component;
+ this.$scope.isCsarComponentExists = false;
+ };
+
+ this.onBoardingService.getComponentFromCsarUuid((<Resource>component).csarUUID).then(onSuccess, onError);
+ };
+
+ };
+
+ private initSortedTableScope = ():void => {
+ this.$scope.tableHeadersList = [
+ {title: 'Name', property: 'name'},
+ {title: 'Vendor', property: 'vendorName'},
+ {title: 'Category', property: 'categories'},
+ {title: 'Version', property: 'csarVersion'},
+ {title: '#', property: 'importAndUpdate'}
+ //{title: 'Date', property: 'componentDate'}
+ ];
+
+ this.$scope.sort = (sortBy:string):void => {
+ this.$scope.reverse = (this.$scope.sortBy === sortBy) ? !this.$scope.reverse : false;
+ this.$scope.sortBy = sortBy;
+ };
+ };
+
+ private initModalScope = ():void => {
+ // Enable the modal directive to close
+ this.$scope.modalOnboarding = this.$uibModalInstance;
+ };
+
+ private initOnboardingComponentsList = ():void => {
+ let onSuccess = (onboardingResponse:Array<IComponent>):void => {
+ initMaxVersionOfItemsInList(onboardingResponse);
+
+ if (this.currentCsarUUID) {
+ //this.$scope.componentsList = this.$filter('filter')(this.$scope.componentsList, {csarUUID: this.currentCsarUUID});
+ this.$scope.componentsList = this.$filter('filter')(this.$scope.componentsList,
+ (input):boolean => {
+ return input.csarUUID === this.currentCsarUUID;
+ }
+ );
+ }
+ this.initScope();
+ };
+
+ let onError = ():void => {
+ console.log("Error getting onboarding list");
+ this.initScope();
+ };
+
+ let initMaxVersionOfItemsInList = (onboardingResponse:Array<IComponent>):void => {
+ // Get only the latest version of each item
+ this.$scope.componentsList = [];
+
+ // Get all unique items from the list
+ let uniqueItems:Array<any> = _.uniq(onboardingResponse, false, (item:any):void=>{
+ return item.packageId;
+ });
+
+ // Loop on all the items with unique packageId
+ _.each(uniqueItems, (item:any):void=> {
+ // Find all the items that has same packageId
+ let ItemsFound:Array<IComponent> = _.filter(onboardingResponse, (inListItem:any):any => {
+ return inListItem.packageId === item.packageId;
+ });
+
+ // Loop on all the items with same packageId and find the max version.
+ let maxItem:any;
+ _.each(ItemsFound, (ItemFound:any):void=> {
+ if (!maxItem) {
+ maxItem = ItemFound;
+ } else if (maxItem && parseInt(maxItem.csarVersion) < parseInt(ItemFound.csarVersion)) {
+ maxItem = ItemFound;
+ }
+ });
+ this.$scope.componentsList.push(maxItem);
+ });
+ };
+
+ this.onBoardingService.getOnboardingComponents().then(onSuccess, onError);
+ };
+}
diff --git a/catalog-ui/app/scripts/view-models/modals/onboarding-modal/onboarding-modal-view.html b/catalog-ui/src/app/view-models/modals/onboarding-modal/onboarding-modal-view.html
index 246915212c..3657fad017 100644
--- a/catalog-ui/app/scripts/view-models/modals/onboarding-modal/onboarding-modal-view.html
+++ b/catalog-ui/src/app/view-models/modals/onboarding-modal/onboarding-modal-view.html
@@ -28,15 +28,17 @@
<!-- Table body -->
<div class="body">
- <perfect-scrollbar suppress-scroll-x="true" scroll-y-margin-offset="0" include-padding="true" class="scrollbar-container">
+ <perfect-scrollbar suppress-scroll-x="true" scroll-y-margin-offset="0" include-padding="true" class="scrollbar-container" id="onboarding-modal-scrollbar-container">
<!-- In case the component list is empty -->
<div data-ng-if="!componentsList || componentsList.length===0" class="no-row-text">
There are no software product component to display
</div>
+ <div infinite-scroll-disabled='allItemsDisplayed' infinite-scroll="increaseNumItemsToDisplay()" infinite-scroll-container="'#onboarding-modal-scrollbar-container'">
+
<!-- Loop on components list -->
- <div data-ng-repeat-start="component in componentsList | filter: searchBind | orderBy:sortBy:reverse track by $index"
+ <div data-ng-repeat-start="component in componentsList | filter: searchBind | orderBy:sortBy:reverse | limitTo:numberOfItemsToDisplay track by $index"
class="flex-container data-row"
data-ng-class="{'selected': component === selectedComponent}"
data-ng-click="doSelectComponent(component);"
@@ -130,7 +132,7 @@
data-tests-id="download-csar"></span>
</div>
<loader data-display="isLoading" relative="true" size="small"></loader>
-
+ </div>
</div>
</perfect-scrollbar>
diff --git a/catalog-ui/app/scripts/view-models/modals/onboarding-modal/onboarding-modal.less b/catalog-ui/src/app/view-models/modals/onboarding-modal/onboarding-modal.less
index c745a86888..c745a86888 100644
--- a/catalog-ui/app/scripts/view-models/modals/onboarding-modal/onboarding-modal.less
+++ b/catalog-ui/src/app/view-models/modals/onboarding-modal/onboarding-modal.less
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
new file mode 100644
index 0000000000..faeaefb5e5
--- /dev/null
+++ b/catalog-ui/src/app/view-models/onboard-vendor/onboard-vendor-view-model.ts
@@ -0,0 +1,125 @@
+'use strict';
+import {IUserProperties} from "app/models";
+import {MenuItemGroup, MenuItem} from "app/utils";
+import {CacheService} from "app/services";
+
+export class BreadcrumbsMenuItem {
+ key:string;
+ displayText:string;
+}
+
+export class BreadcrumbsMenu {
+ selectedKey:string;
+ menuItems:Array<BreadcrumbsMenuItem>;
+}
+
+export class BreadcrumbsPath {
+ selectedKeys:Array<string>;
+}
+
+export class VendorData {
+ breadcrumbs:BreadcrumbsPath;
+}
+
+export interface IOnboardVendorViewModelScope extends ng.IScope {
+ vendorData:VendorData;
+ onVendorEvent:Function;
+ topNavMenuModel:Array<MenuItemGroup>;
+ topNavRootMenu:MenuItemGroup;
+ user:IUserProperties;
+ version:string;
+}
+
+export class OnboardVendorViewModel {
+ static '$inject' = [
+ '$scope',
+ '$q',
+ 'Sdc.Services.CacheService'
+ ];
+
+ private firstControlledTopNavMenu:MenuItemGroup;
+
+ constructor(private $scope:IOnboardVendorViewModelScope,
+ private $q:ng.IQService,
+ private cacheService:CacheService) {
+
+ this.$scope.vendorData = {
+ breadcrumbs: {
+ selectedKeys: []
+ }
+ };
+
+ this.$scope.version = this.cacheService.get('version');
+
+ this.$scope.onVendorEvent = (eventName:string, data:any):void => {
+ switch (eventName) {
+ case 'breadcrumbsupdated':
+ this.handleBreadcrumbsUpdate(data);
+ break;
+ }
+ };
+
+ this.$scope.topNavMenuModel = [];
+
+ this.$scope.user = this.cacheService.get('user');
+ }
+
+ updateBreadcrumbsPath = (selectedKeys:Array<string>):ng.IPromise<boolean> => {
+ let topNavMenuModel = this.$scope.topNavMenuModel;
+ let startIndex = topNavMenuModel.indexOf(this.firstControlledTopNavMenu);
+ if (startIndex === -1) {
+ startIndex = topNavMenuModel.length;
+ }
+ topNavMenuModel.splice(startIndex + selectedKeys.length);
+ this.$scope.vendorData = {
+ breadcrumbs: {selectedKeys: selectedKeys}
+ };
+
+ return this.$q.when(true);
+ };
+
+ handleBreadcrumbsUpdate(breadcrumbsMenus:Array<BreadcrumbsMenu>):void {
+ let selectedKeys = [];
+ let topNavMenus = breadcrumbsMenus.map((breadcrumbMenu, breadcrumbIndex) => {
+ let topNavMenu = new MenuItemGroup();
+ topNavMenu.menuItems = breadcrumbMenu.menuItems.map(menuItem =>
+ new MenuItem(
+ menuItem.displayText,
+ this.updateBreadcrumbsPath,
+ null,
+ null,
+ [selectedKeys.concat([menuItem.key])]
+ )
+ );
+ topNavMenu.selectedIndex = _.findIndex(
+ breadcrumbMenu.menuItems,
+ menuItem => menuItem.key === breadcrumbMenu.selectedKey
+ );
+ selectedKeys.push(breadcrumbMenu.selectedKey);
+ return topNavMenu;
+ });
+
+ let topNavMenuModel = this.$scope.topNavMenuModel;
+ let len = topNavMenuModel.length;
+ let startIndex = topNavMenuModel.indexOf(this.firstControlledTopNavMenu);
+ if (startIndex === -1) {
+ startIndex = len;
+ }
+ topNavMenuModel.splice(startIndex, len - startIndex);
+ topNavMenuModel.push.apply(topNavMenuModel, topNavMenus);
+ this.firstControlledTopNavMenu = topNavMenus[0];
+
+ if (startIndex === 1 && this.$scope.topNavRootMenu == null) {
+ let topNavRootMenu = topNavMenuModel[0];
+ let onboardItem = topNavRootMenu.menuItems[topNavRootMenu.selectedIndex];
+ let originalCallback = onboardItem.callback;
+ onboardItem.callback = (...args) => {
+ let ret = this.updateBreadcrumbsPath([]);
+ return originalCallback && originalCallback.apply(undefined, args) || ret;
+ };
+ this.$scope.topNavRootMenu = topNavRootMenu;
+ }
+
+ this.updateBreadcrumbsPath(selectedKeys);
+ }
+}
diff --git a/catalog-ui/app/scripts/view-models/onboard-vendor/onboard-vendor-view.html b/catalog-ui/src/app/view-models/onboard-vendor/onboard-vendor-view.html
index 733e2d0cc0..734fb93daf 100644
--- a/catalog-ui/app/scripts/view-models/onboard-vendor/onboard-vendor-view.html
+++ b/catalog-ui/src/app/view-models/onboard-vendor/onboard-vendor-view.html
@@ -11,4 +11,6 @@
<top-nav top-lvl-selected-index="2" search-bind="search.filterTerm" menu-model="topNavMenuModel" version="{{version}}" hide-search="true"></top-nav>
+ <ecomp-footer></ecomp-footer>
+
</div>
diff --git a/catalog-ui/app/scripts/view-models/onboard-vendor/onboard-vendor.less b/catalog-ui/src/app/view-models/onboard-vendor/onboard-vendor.less
index 2b43bbb321..4a16ca2b5b 100644
--- a/catalog-ui/app/scripts/view-models/onboard-vendor/onboard-vendor.less
+++ b/catalog-ui/src/app/view-models/onboard-vendor/onboard-vendor.less
@@ -83,7 +83,7 @@
&.NOT_CERTIFIED_CHECKOUT,
&.NOT_CERTIFIED_CHECKIN {
.i-sdc-categories-list-item-icon {
- background: url('../../../styles/images/sprites/sprite-global-old.png') no-repeat -53px -2889px;
+ background: url('/assets/styles/images/sprites/sprite-global-old.png') no-repeat -53px -2889px;
width: 14px;
height: 14px;
@@ -92,7 +92,7 @@
&.CERTIFIED {
.i-sdc-categories-list-item-icon {
- background: url('../../../styles/images/sprites/sprite-global-old.png') no-repeat -53px -3034px;
+ background: url('/assets/styles/images/sprites/sprite-global-old.png') no-repeat -53px -3034px;
width: 14px;
height: 16px;
}
@@ -100,7 +100,7 @@
&.READY_FOR_CERTIFICATION {
.i-sdc-categories-list-item-icon {
- background: url('../../../styles/images/sprites/sprite-global-old.png') no-repeat -53px -2985px;
+ background: url('/assets/styles/images/sprites/sprite-global-old.png') no-repeat -53px -2985px;
width: 14px;
height: 16px;
}
@@ -108,7 +108,7 @@
&.CERTIFICATION_IN_PROGRESS {
.i-sdc-categories-list-item-icon {
- background: url('../../../styles/images/sprites/sprite-global-old.png') no-repeat -53px -2934px;
+ background: url('/assets/styles/images/sprites/sprite-global-old.png') no-repeat -53px -2934px;
width: 14px;
height: 16px;
}
@@ -117,7 +117,7 @@
&.DISTRIBUTED,
&.TBD {
.i-sdc-categories-list-item-icon {
- background: url('../../../styles/images/sprites/sprite-global-old.png') no-repeat -43px -3087px;
+ background: url('/assets/styles/images/sprites/sprite-global-old.png') no-repeat -43px -3087px;
width: 24px;
height: 14px;
diff --git a/catalog-ui/app/scripts/view-models/preloading/preloading-view.html b/catalog-ui/src/app/view-models/preloading/preloading-view.html
index c0512dd9ec..c0512dd9ec 100644
--- a/catalog-ui/app/scripts/view-models/preloading/preloading-view.html
+++ b/catalog-ui/src/app/view-models/preloading/preloading-view.html
diff --git a/catalog-ui/src/app/view-models/preloading/preloading-view.ts b/catalog-ui/src/app/view-models/preloading/preloading-view.ts
new file mode 100644
index 0000000000..f299f2a30f
--- /dev/null
+++ b/catalog-ui/src/app/view-models/preloading/preloading-view.ts
@@ -0,0 +1,27 @@
+'use strict';
+
+interface IPreLoadingViewScope {
+ startZoomIn:boolean;
+}
+
+export class PreLoadingViewModel {
+
+ static '$inject' = ['$scope'];
+
+ constructor(private $scope:IPreLoadingViewScope) {
+ this.init($scope);
+ }
+
+ private init = ($scope:IPreLoadingViewScope):void => {
+ this.animate($('.caption1'), 'fadeInUp', 400);
+ this.animate($('.caption2'), 'fadeInUp', 800);
+ };
+
+ private animate = (element:any, animation:string, when:number):void => {
+ window.setTimeout(()=> {
+ element.addClass("animated " + animation);
+ element[0].style = "visibility: visible;";
+ }, when);
+ };
+
+}
diff --git a/catalog-ui/src/app/view-models/support/support-view-model.ts b/catalog-ui/src/app/view-models/support/support-view-model.ts
new file mode 100644
index 0000000000..2f43d87b18
--- /dev/null
+++ b/catalog-ui/src/app/view-models/support/support-view-model.ts
@@ -0,0 +1,16 @@
+'use strict';
+import {CacheService} from "app/services";
+
+interface ISupportViewModelScope {
+ version:string;
+}
+
+export class SupportViewModel {
+
+ static '$inject' = ['$scope', 'Sdc.Services.CacheService'];
+
+ constructor(private $scope:ISupportViewModelScope,
+ private cacheService:CacheService) {
+ this.$scope.version = this.cacheService.get('version');
+ }
+}
diff --git a/catalog-ui/app/scripts/view-models/support/support-view.html b/catalog-ui/src/app/view-models/support/support-view.html
index 0e6d09ddd7..88609774bb 100644
--- a/catalog-ui/app/scripts/view-models/support/support-view.html
+++ b/catalog-ui/src/app/view-models/support/support-view.html
@@ -3,7 +3,7 @@
<div class="w-sdc-header">
<div class="w-sdc-header-logo">
<div class="w-sdc-header-logo-icon sprite logo"></div>
- <a class="w-sdc-header-logo-link" data-ui-sref="dashboard">ASDC</a>
+ <a class="w-sdc-header-logo-link" data-ui-sref="dashboard" translate="PROJECT_TITLE"></a>
<div class="w-sdc-header-version"> v.{{version}}</div>
</div>
<div class="i-sdc-header-caption">Support</div>
@@ -27,7 +27,5 @@
<div class="i-sdc-left-sidebar-nav-item support" data-ui-sref="support">Support</div>
</div>
</div>
-
-
</div>
</div>
diff --git a/catalog-ui/app/scripts/view-models/support/support.less b/catalog-ui/src/app/view-models/support/support.less
index 8159e38320..8159e38320 100644
--- a/catalog-ui/app/scripts/view-models/support/support.less
+++ b/catalog-ui/src/app/view-models/support/support.less
diff --git a/catalog-ui/app/scripts/view-models/tabs/general-tab.less b/catalog-ui/src/app/view-models/tabs/general-tab.less
index a8b4f5b9be..936b3e3414 100644
--- a/catalog-ui/app/scripts/view-models/tabs/general-tab.less
+++ b/catalog-ui/src/app/view-models/tabs/general-tab.less
@@ -12,8 +12,7 @@
.f-color.a;
.f-type._14_m;
- padding: 0px 0px 15px 0px;
- margin: 0px 20px 0px 20px;
+ padding: 0px 0px 15px 20px;
border-bottom: 1px solid @main_color_o;
}
@@ -39,10 +38,6 @@
.expand-collapse-title {
.expand-collapse-title-icon {
.expand-collapse-minus-icon;
-
- &:hover {
- .expand-collapse-minus-icon.hover;
- }
}
}
}
@@ -59,10 +54,6 @@
.hand;
.sprite-new;
.expand-collapse-plus-icon;
- &:hover {
- .expand-collapse-plus-icon.hover;
- }
-
}
.expand-collapse-title-text {
max-width: 225px;
@@ -87,7 +78,7 @@
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
- padding-left: 43px;
+ padding: 10px 0 0 43px;
}
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
new file mode 100644
index 0000000000..7c505512c4
--- /dev/null
+++ b/catalog-ui/src/app/view-models/tabs/hierarchy/hierarchy-view-model.ts
@@ -0,0 +1,98 @@
+'use strict';
+import {ModalsHandler} from "app/utils";
+import {PropertyModel, DisplayModule, Component, ComponentInstance, Tab, Module} from "app/models";
+import {ExpandCollapseListData} from "app/directives/utils/expand-collapse-list-header/expand-collapse-list-header";
+
+export interface IHierarchyScope extends ng.IScope {
+ component:Component;
+ selectedIndex:number;
+ selectedModule:DisplayModule;
+ singleTab:Tab;
+ isLoading:boolean;
+ expandCollapseArtifactsList:ExpandCollapseListData;
+ expandCollapsePropertiesList:ExpandCollapseListData;
+ selectedInstanceId:string;
+
+ onModuleSelected(moduleId:string, selectedIndex:number):void;
+ onModuleNameChanged(module:DisplayModule):void;
+ updateHeatName():void;
+ loadInstanceModules(instance:ComponentInstance):ng.IPromise<boolean>;
+ openEditPropertyModal(property:PropertyModel):void;
+}
+
+export class HierarchyViewModel {
+
+ static '$inject' = [
+ '$scope',
+ '$q',
+ 'ModalsHandler'
+ ];
+
+ constructor(private $scope:IHierarchyScope, private $q:ng.IQService, private ModalsHandler:ModalsHandler) {
+ this.$scope.component = this.$scope.singleTab.data;
+ this.$scope.isLoading = false;
+ this.$scope.expandCollapseArtifactsList = new ExpandCollapseListData();
+ this.$scope.expandCollapsePropertiesList = new ExpandCollapseListData();
+ this.initScopeMethods();
+ }
+
+ private initScopeMethods():void {
+
+ let collapseModuleData = ():void => {
+ this.$scope.expandCollapseArtifactsList.expandCollapse = false;
+ this.$scope.expandCollapsePropertiesList.expandCollapse = false;
+ this.$scope.expandCollapseArtifactsList.orderByField = "artifactName";
+ this.$scope.expandCollapsePropertiesList.orderByField = "name";
+ };
+
+ this.$scope.onModuleSelected = (moduleId:string, selectedIndex:number, componentInstanceId?:string):void => {
+
+ let onSuccess = (module:DisplayModule) => {
+ console.log("Module Loaded: ", module);
+ this.$scope.selectedModule = module;
+ this.$scope.isLoading = false;
+ collapseModuleData();
+ };
+
+ let onFailed = () => {
+ this.$scope.isLoading = false;
+ };
+
+ this.$scope.selectedIndex = selectedIndex;
+ if (!this.$scope.selectedModule || (this.$scope.selectedModule && this.$scope.selectedModule.uniqueId != moduleId)) {
+ this.$scope.isLoading = true;
+ if (this.$scope.component.isService()) {
+ this.$scope.selectedInstanceId = componentInstanceId;
+ this.$scope.component.getModuleInstanceForDisplay(componentInstanceId, moduleId).then(onSuccess, onFailed);
+ } else {
+ this.$scope.component.getModuleForDisplay(moduleId).then(onSuccess, onFailed);
+ }
+ }
+ };
+
+ this.$scope.updateHeatName = () => {
+ this.$scope.isLoading = true;
+
+ let originalName:string = this.$scope.selectedModule.name;
+
+ let onSuccess = (module:Module) => {
+ console.log("Module name updated:", module.name);
+ this.$scope.selectedModule.name = module.name;
+ this.$scope.isLoading = false;
+ };
+
+ let onFailed = () => {
+ this.$scope.isLoading = false;
+ this.$scope.selectedModule.name = originalName;
+ };
+
+ this.$scope.selectedModule.updateName();
+ 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(() => {
+ });
+ }
+ }
+}
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
new file mode 100644
index 0000000000..9eaa3a0f76
--- /dev/null
+++ b/catalog-ui/src/app/view-models/tabs/hierarchy/hierarchy-view.html
@@ -0,0 +1,107 @@
+<div class="sdc-general-tab hierarchy-tab" ng-class="">
+ <loader data-display="isLoading" relative="true" size="medium"></loader>
+ <div class="sdc-general-tab-title" data-tests-id="tab-header" translate="DEPLOYMENT_TAB_TITLE"></div>
+
+ <div class="resizable-container">
+ <div data-ng-if="!component.isService()"class="resizable-section">
+
+ <perfect-scrollbar scroll-y-margin-offset="0" include-padding="true"
+ class="general-tab-scrollbar-container">
+ <div class="sdc-general-tab-sub-title" data-tests-id="tab-sub-header">{{component.name}}</div>
+ <expand-collapse expanded-selector=".hierarchy-module-member-list.{{$index}}"
+ class="general-tab-expand-collapse" is-close-on-init="true"
+ data-tests-id="hierarchy-module-{{$index}}"
+ data-ng-repeat-start="module in component.groups">
+ <div class="expand-collapse-title first-level" data-tests-id="hierarchy-module-{{$index}}-title" ng-class="{'selected': selectedIndex === $index}" data-ng-click="onModuleSelected(module.uniqueId, $index)">
+ <div class="expand-collapse-title-icon"></div>
+ <span class="expand-collapse-title-text" data-ng-bind="module.name" tooltips
+ tooltip-content="{{module.name}}"></span>
+
+ </div>
+ </expand-collapse>
+
+ <div data-ng-repeat-end="" class="hierarchy-module-member-list {{$index}}">
+ <div ng-repeat="(memberName, value) in ::module.members track by $index">
+ <div class="expand-collapse-sub-title" tooltips tooltip-content="{{memberName}}">{{memberName}}</div>
+ </div>
+ </div>
+ </perfect-scrollbar>
+ </div>
+ <div data-ng-if="component.isService()"class="resizable-section">
+ <perfect-scrollbar scroll-y-margin-offset="0" include-padding="true"
+ class="general-tab-scrollbar-container">
+ <expand-collapse expanded-selector=".hierarchy-modules-list.{{$index}}"
+ class="general-tab-expand-collapse" is-close-on-init="true"
+ data-tests-id="hierarchy-instance-{{$index}}"
+
+ data-ng-repeat-start="instance in component.componentInstances">
+ <div class="expand-collapse-title first-level" data-tests-id="hierarchy-instance-{{$index}}-title">
+ <div class="expand-collapse-title-icon"></div>
+ <span class="expand-collapse-title-text" data-ng-bind="instance.name" tooltips
+ tooltip-content="{{instance.name}}"></span>
+
+ </div>
+ </expand-collapse>
+ <!--TODO: Rachel : -->
+ <div data-ng-repeat-end="" class="hierarchy-modules-list {{$index}}">
+ <expand-collapse expanded-selector=".outer-index-{{$parent.$index}}.hierarchy-module-member-list.{{$index}}"
+ class="general-tab-expand-collapse" is-close-on-init="true"
+ data-tests-id="hierarchy-module-{{$index}}"
+ data-ng-repeat-start="module in instance.groupInstances">
+ <div class="expand-collapse-title second-level" data-tests-id="hierarchy-module-{{$index}}-title" ng-class="{'selected': selectedIndex === $index && selectedInstanceId === instance.uniqueId}" data-ng-click="onModuleSelected(module.uniqueId, $index, instance.uniqueId)">
+ <div class="expand-collapse-title-icon"></div>
+ <span class="expand-collapse-title-text" data-ng-bind="module.name" tooltips tooltip-content="{{module.name}}"></span>
+
+ </div>
+ </expand-collapse>
+
+ <div data-ng-repeat-end="" class="outer-index-{{$parent.$index}} hierarchy-module-member-list {{$index}}">
+ <div ng-repeat="(memberName, value) in ::module.members track by $index">
+ <div class="expand-collapse-sub-title" tooltips tooltip-content="{{memberName}}">{{memberName}}</div>
+ </div>
+ </div>
+ </div>
+ </perfect-scrollbar>
+ </div>
+
+ <div resizable r-directions="['top']" r-flex="true" ng-if="selectedModule" class="resizable-section module-data-container" data-tests-id="selected-module-data">
+ <perfect-scrollbar scroll-y-margin-offset="0" include-padding="true"
+ class="general-tab-scrollbar-container">
+ <div class="module-data">
+ <div>
+ <div class="module-name module-text-overflow" data-tests-id="selected-module-name" tooltips tooltip-content="{{selectedModule.name}}">{{selectedModule.name}}</div>
+ <div class="edit-name-container" data-ng-if="!component.isService()">
+ <edit-name-popover header="Edit Module Name" direction="auto top" module="selectedModule" on-save="updateHeatName()" ng-class="{'disabled': isViewOnly}" class="sdc-edit-icon" data-tests-id="edit-name-popover-icon"></edit-name-popover>
+ </div>
+ </div>
+ <div class="" data-tests-id="selected-module-group-uuid" tooltips tooltip-content="{{selectedModule.groupUUID}}"><span class="bold">Module ID:</span><br><span class="small-font">{{selectedModule.groupUUID}}</span></div>
+ <div class="" data-tests-id="selected-module-group-customization-uuid" data-ng-if="component.isService() && isViewOnly" tooltips tooltip-content="{{selectedModule.customizationUUID}}"><span class="bold">Customization ID:</span ><br><span class="small-font">{{selectedModule.customizationUUID}}</span></div>
+ <div class="" data-tests-id="selected-module-group-invariant-uuid" tooltips tooltip-content="{{selectedModule.invariantUUID}}"><span class="bold">Invariant UUID:</span><span class="small-font">{{selectedModule.invariantUUID}}</span></div>
+ <div data-tests-id="selected-module-version"><span class="bold">Version:</span> {{selectedModule.version}}</div>
+ <div data-tests-id="selected-module-is-base"><span class="bold">IsBase:</span> {{selectedModule.isBase}}</div>
+
+ </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 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>
+ </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>
+ </div>
+ </div>
+ <expand-collapse-list-header title="Artifacts" expand-collapse-list-data="expandCollapseArtifactsList"></expand-collapse-list-header>
+ <div ng-repeat="artifact in selectedModule.artifacts| filter: expandCollapseArtifactsList.filter | orderBy:expandCollapseArtifactsList.orderByField track by $index" data-ng-if="expandCollapseArtifactsList.expandCollapse">
+ <div class="list-item artifact-data" data-ng-class="{'last':$last}">
+ <div class="artifact-name module-text-overflow" data-tests-id="selected-module-artifact-name" tooltips tooltip-content="{{artifact.artifactName}}">{{artifact.artifactName}}</div>
+ <div class="module-text-overflow" tooltips data-tests-id="selected-module-artifact-uuid" tooltip-content="{{artifact.artifactUUID}}">UUID: {{artifact.artifactUUID}}</div>
+ <div data-tests-id="selected-module-artifact-version">Version: {{artifact.artifactVersion}}</div>
+ </div>
+ </div>
+ </perfect-scrollbar>
+ </div>
+ </div>
+</div>
diff --git a/catalog-ui/app/scripts/view-models/tabs/hierarchy/hierarchy.less b/catalog-ui/src/app/view-models/tabs/hierarchy/hierarchy.less
index 5e8572678d..dee0eeb38b 100644
--- a/catalog-ui/app/scripts/view-models/tabs/hierarchy/hierarchy.less
+++ b/catalog-ui/src/app/view-models/tabs/hierarchy/hierarchy.less
@@ -1,5 +1,5 @@
.hierarchy-tab{
-
+ width: 100%;
.hierarchy-module-list-container{
padding: 0px 20px 0px 20px;
}
@@ -23,35 +23,65 @@
.f-color.a;
padding: 10px 0px 10px 0px;
margin: 0px 20px 0px 20px;
- border-bottom: 1px solid rgba(0, 159, 219, 0.6);
+ //border-bottom: 1px solid rgba(0, 159, 219, 0.6);
+
+ .small-font{
+ font-size: 12px;
+ }
+ }
+
+ .list-item{
+ padding: 10px 0px 10px 0px;
+ margin: 0px 20px 0px 20px;
+ &:not(.last){
+ border-bottom: 1px solid rgba(0, 159, 219, 0.6);
+ }
}
.artifact-data{
.selectable;
.f-type._12_r;
.f-color.m;
-
- padding: 10px 0px 10px 0px;
- margin: 0px 20px 0px 20px;
- border-bottom: 1px solid rgba(0, 159, 219, 0.6);
.artifact-name {
.f-type._14_r;
font-weight: bold;
}
}
+ .property-data{
+ .property-name{
+ width: 100%;
+ .f-type._14_m;
+ font-weight: 400;
+ color: @main_color_a;
+ }
+ .property-info{
+ color: @func_color_s;
+ .f-type._14_r;
+ width: 100%;
+ }
+ }
+
.module-text-overflow {
max-width: 240px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
- display: inline-block;
+ //display: inline-block;
}
}
+ .hierarchy-modules-list{
+ .expand-collapse-title{
+ .expand-collapse-title-text{
+ max-width: 202px;
+ }
+ }
+ }
.hierarchy-module-member-list {
overflow: hidden;
+ background-color: @main_color_p;
}
.edit-name-container {
diff --git a/catalog-ui/app/scripts/view-models/tutorial-end/tutorial-end.html b/catalog-ui/src/app/view-models/tutorial-end/tutorial-end.html
index 6e478fc471..6e478fc471 100644
--- a/catalog-ui/app/scripts/view-models/tutorial-end/tutorial-end.html
+++ b/catalog-ui/src/app/view-models/tutorial-end/tutorial-end.html
diff --git a/catalog-ui/app/scripts/view-models/tutorial-end/tutorial-end.less b/catalog-ui/src/app/view-models/tutorial-end/tutorial-end.less
index 71648a4f86..30fa4f7e8b 100644
--- a/catalog-ui/app/scripts/view-models/tutorial-end/tutorial-end.less
+++ b/catalog-ui/src/app/view-models/tutorial-end/tutorial-end.less
@@ -11,7 +11,7 @@
display: flex;
align-items: center;
- background-image: url('../../../styles/images/welcome.png');
+ background-image: url('/assets/styles/images/welcome.png');
background-repeat: no-repeat;
background-position: bottom left;
diff --git a/catalog-ui/src/app/view-models/tutorial-end/tutorial-end.ts b/catalog-ui/src/app/view-models/tutorial-end/tutorial-end.ts
new file mode 100644
index 0000000000..1787cd5937
--- /dev/null
+++ b/catalog-ui/src/app/view-models/tutorial-end/tutorial-end.ts
@@ -0,0 +1,20 @@
+'use strict';
+
+interface ITutorialEndViewModelScope extends ng.IScope {
+}
+
+export class TutorialEndViewModel {
+
+ static '$inject' = [
+ '$scope'
+ ];
+
+ constructor(private $scope:ITutorialEndViewModelScope) {
+ this.init();
+ }
+
+ private init = ():void => {
+
+ }
+
+}
diff --git a/catalog-ui/src/app/view-models/welcome/welcome-view.html b/catalog-ui/src/app/view-models/welcome/welcome-view.html
new file mode 100644
index 0000000000..18ca4d51cd
--- /dev/null
+++ b/catalog-ui/src/app/view-models/welcome/welcome-view.html
@@ -0,0 +1,9 @@
+<div class="sdc-welcome-new-page">
+ <div data-ng-click="onCloseButtonClick()" class="sdc-welcome-close"></div>
+ <div class="sdc-welcome-wrapper">
+ <div class="sdc-welcome-cover"></div>
+ <div class="sdc-welcome-main">
+ <h1>Welcome to SDC</h1>
+ </div>
+ </div>
+</div>
diff --git a/catalog-ui/src/app/view-models/welcome/welcome-view.ts b/catalog-ui/src/app/view-models/welcome/welcome-view.ts
new file mode 100644
index 0000000000..154a70c301
--- /dev/null
+++ b/catalog-ui/src/app/view-models/welcome/welcome-view.ts
@@ -0,0 +1,57 @@
+'use strict';
+
+export interface IWelcomeViewMode {
+ onCloseButtonClick():void;
+}
+
+export class WelcomeViewModel {
+
+ firstLoad:boolean = true;
+ alreadyAnimated:Array<number> = [];
+
+ static '$inject' = [
+ '$scope',
+ '$state'
+ ];
+
+ constructor(private $scope:IWelcomeViewMode,
+ private $state:ng.ui.IStateService
+ ) {
+ this.init();
+ this.initScope();
+ window.setTimeout(():void => {
+ this.loadImages(():void=> {
+ window.setTimeout(():void =>{
+ $(".sdc-welcome-new-page").addClass("animated fadeIn");
+ },1000);
+ });
+ },0);
+ }
+
+ private initScope = ():void => {
+ this.$scope.onCloseButtonClick = ():void => {
+ this.$state.go("dashboard", {});
+ };
+ };
+
+ private init = ():void => {
+ let viewModelsHtmlBasePath:string = 'src/app/view-models/';
+ $('body').keyup((e):void=> {
+ if (e.keyCode == 27) { // escape key maps to keycode `27`
+ this.$state.go('dashboard');
+ }
+ });
+ };
+
+ private loadImages = (callback:Function):void => {
+ let src = $('.sdc-welcome-wrapper').css('background-image');
+ let url = src.match(/\((.*?)\)/)[1].replace(/('|")/g,'');
+
+ let img = new Image();
+ img.onload = function() {
+ callback();
+ };
+ img.src = url;
+ };
+
+}
diff --git a/catalog-ui/src/app/view-models/workspace/conformance-level-modal/conformance-level-modal-view-model.ts b/catalog-ui/src/app/view-models/workspace/conformance-level-modal/conformance-level-modal-view-model.ts
new file mode 100644
index 0000000000..61a83c88f7
--- /dev/null
+++ b/catalog-ui/src/app/view-models/workspace/conformance-level-modal/conformance-level-modal-view-model.ts
@@ -0,0 +1,29 @@
+'use strict';
+
+export interface IConformanceLevelModalModelScope {
+ footerButtons:Array<any>;
+ modalInstance:ng.ui.bootstrap.IModalServiceInstance;
+}
+
+export class ConformanceLevelModalViewModel {
+
+ static '$inject' = ['$scope', '$uibModalInstance'];
+
+ constructor(private $scope:IConformanceLevelModalModelScope,
+ private $uibModalInstance:ng.ui.bootstrap.IModalServiceInstance) {
+
+ this.initScope();
+ }
+
+ private initScope = ():void => {
+
+ this.$scope.modalInstance = this.$uibModalInstance;
+
+ this.$scope.footerButtons = [
+ {'name': 'Continue', 'css': 'grey', 'callback': this.$uibModalInstance.close},
+ {'name': 'Reject', 'css': 'blue', 'callback': this.$uibModalInstance.dismiss}
+ ];
+
+ };
+
+}
diff --git a/catalog-ui/src/app/view-models/workspace/conformance-level-modal/conformance-level-modal-view.html b/catalog-ui/src/app/view-models/workspace/conformance-level-modal/conformance-level-modal-view.html
new file mode 100644
index 0000000000..3577e4d77b
--- /dev/null
+++ b/catalog-ui/src/app/view-models/workspace/conformance-level-modal/conformance-level-modal-view.html
@@ -0,0 +1,22 @@
+<sdc-modal modal="modalInstance"
+ type="classic"
+ class="w-sdc-modal modal-type-alert conformance-level-modal"
+ header="Warning"
+ buttons="footerButtons"
+ show-close-button="false">
+
+ <perfect-scrollbar include-padding="true">
+ <div class="w-sdc-modal-body-content" data-tests-id="message">
+ <p>
+ You are about to distribute a service with models and artifacts created with an <b>older version of the platform</b>.
+ For such service, new properties, metadata and requirements needed by ECOMP components will not be available.
+ </p><p>
+ It is highly recommended that you upgrade the service models and artifacts.
+ </p><p>
+ Click "Continue" if you need to distribute the current service version.<br />
+ Click "Reject" if you need to stop the distribution and manually upgrade the service.
+ </p>
+ </div>
+ </perfect-scrollbar>
+
+</sdc-modal>
diff --git a/catalog-ui/src/app/view-models/workspace/conformance-level-modal/conformance-level-modal.less b/catalog-ui/src/app/view-models/workspace/conformance-level-modal/conformance-level-modal.less
new file mode 100644
index 0000000000..7f195ade83
--- /dev/null
+++ b/catalog-ui/src/app/view-models/workspace/conformance-level-modal/conformance-level-modal.less
@@ -0,0 +1,3 @@
+.conformance-level-modal{
+
+}
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/activity-log/activity-log.html b/catalog-ui/src/app/view-models/workspace/tabs/activity-log/activity-log.html
index 23c08f6ec6..23c08f6ec6 100644
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/activity-log/activity-log.html
+++ b/catalog-ui/src/app/view-models/workspace/tabs/activity-log/activity-log.html
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/activity-log/activity-log.less b/catalog-ui/src/app/view-models/workspace/tabs/activity-log/activity-log.less
index 61bb3e9f01..61bb3e9f01 100644
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/activity-log/activity-log.less
+++ b/catalog-ui/src/app/view-models/workspace/tabs/activity-log/activity-log.less
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
new file mode 100644
index 0000000000..ed583dc4c0
--- /dev/null
+++ b/catalog-ui/src/app/view-models/workspace/tabs/activity-log/activity-log.ts
@@ -0,0 +1,103 @@
+'use strict';
+import {IWorkspaceViewModelScope} from "app/view-models/workspace/workspace-view-model";
+import {Activity} from "app/models";
+import {ActivityLogService} from "app/services";
+
+export interface IActivityLogViewModelScope extends IWorkspaceViewModelScope {
+ activityDateArray:Array<any>; //this is in order to sort the dates
+ activityLog:Array<Activity>;
+ preVersion:string;
+
+ tableHeadersList:Array<any>;
+ reverse:boolean;
+ sortBy:string;
+ searchBind:string;
+
+ getActivityLog(uniqueId:string):void;
+ onVersionChanged(version:any):void;
+ parseAction(action:string):string;
+ sort(sortBy:string):void;
+}
+
+export class ActivityLogViewModel {
+
+ static '$inject' = [
+ '$scope',
+ '$state',
+ 'Sdc.Services.ActivityLogService'
+ ];
+
+ constructor(private $scope:IActivityLogViewModelScope,
+ private $state:ng.ui.IStateService,
+ private activityLogService:ActivityLogService) {
+
+ this.initScope();
+ this.$scope.setValidState(true);
+ this.initSortedTableScope();
+ this.$scope.updateSelectedMenuItem();
+
+ // Set default sorting
+ this.$scope.sortBy = 'logDate';
+ }
+
+ private initScope():void {
+
+ this.$scope.preVersion = this.$scope.component.version;
+
+ this.$scope.onVersionChanged = (version:any):void => {
+ if (version.versionNumber != this.$scope.component.version) {
+ this.$scope.isLoading = true;
+ this.$scope.getActivityLog(version.versionId);
+ }
+ };
+
+ this.$scope.getActivityLog = (uniqueId:any):void => {
+
+ let onError = (response) => {
+ this.$scope.isLoading = false;
+ console.info('onFaild', response);
+
+ };
+
+ let onSuccess = (response:Array<Activity>) => {
+ this.$scope.activityLog = _.sortBy(response, function (o) {
+ return o.TIMESTAMP;
+ }); //response; //
+ this.$scope.isLoading = false;
+ };
+
+ this.$scope.isLoading = true;
+ if (this.$scope.component.isResource()) {
+ this.activityLogService.getActivityLogService('resources', uniqueId).then(onSuccess, onError);
+ }
+ if (this.$scope.component.isService()) {
+ this.activityLogService.getActivityLogService('services', uniqueId).then(onSuccess, onError);
+ }
+
+ };
+
+ if (!this.$scope.activityLog || this.$scope.preVersion != this.$scope.component.version) {
+ this.$scope.getActivityLog(this.$scope.component.uniqueId);
+ }
+
+ this.$scope.parseAction = (action:string) => {
+ return action ? action.split(/(?=[A-Z])/).join(' ') : '';
+ };
+
+ }
+
+ private initSortedTableScope = ():void => {
+ this.$scope.tableHeadersList = [
+ {title: 'Date', property: 'logDate'},
+ {title: 'Action', property: 'logAction'},
+ {title: 'Comment', property: 'logComment'},
+ {title: 'Username', property: 'logUsername'},
+ {title: 'Status', property: 'logStatus'}
+ ];
+
+ this.$scope.sort = (sortBy:string):void => {
+ this.$scope.reverse = (this.$scope.sortBy === sortBy) ? !this.$scope.reverse : false;
+ this.$scope.sortBy = sortBy;
+ };
+ };
+}
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/attributes/attributes-view-model.ts b/catalog-ui/src/app/view-models/workspace/tabs/attributes/attributes-view-model.ts
new file mode 100644
index 0000000000..d8a60444be
--- /dev/null
+++ b/catalog-ui/src/app/view-models/workspace/tabs/attributes/attributes-view-model.ts
@@ -0,0 +1,80 @@
+'use strict';
+import {IWorkspaceViewModelScope} from "app/view-models/workspace/workspace-view-model";
+import {Component, AttributeModel} from "app/models";
+import {ModalsHandler} from "app/utils";
+import {ComponentServiceNg2} from "../../../../ng2/services/component-services/component.service";
+import {ComponentGenericResponse} from "../../../../ng2/services/responses/component-generic-response";
+
+interface IAttributesViewModelScope extends IWorkspaceViewModelScope {
+ tableHeadersList:Array<any>;
+ reverse:boolean;
+ sortBy:string;
+
+ addOrUpdateAttribute(attribute?:AttributeModel):void;
+ delete(attribute:AttributeModel):void;
+ sort(sortBy:string):void;
+}
+
+export class AttributesViewModel {
+
+ static '$inject' = [
+ '$scope',
+ '$filter',
+ '$uibModal',
+ 'ModalsHandler',
+ 'ComponentServiceNg2'
+ ];
+
+
+ constructor(private $scope:IAttributesViewModelScope,
+ private $filter:ng.IFilterService,
+ private $uibModal:ng.ui.bootstrap.IModalService,
+ private ModalsHandler:ModalsHandler,
+ private ComponentServiceNg2: ComponentServiceNg2) {
+
+ this.initComponentAttributes();
+ this.$scope.updateSelectedMenuItem();
+ }
+
+ private initComponentAttributes = () => {
+ if(this.$scope.component.attributes) {
+ this.initScope();
+ } else {
+ this.ComponentServiceNg2.getComponentAttributes(this.$scope.component).subscribe((response:ComponentGenericResponse) => {
+ this.$scope.component.attributes = response.attributes;
+ this.initScope();
+ });
+ }
+ }
+
+
+ private initScope = ():void => {
+
+ this.$scope.sortBy = 'name';
+ this.$scope.reverse = false;
+ this.$scope.setValidState(true);
+ this.$scope.tableHeadersList = [
+ {title: 'Name', property: 'name'},
+ {title: 'Type', property: 'type'},
+ {title: 'Default Value', property: 'defaultValue'}
+ ];
+ this.$scope.sort = (sortBy:string):void => {
+ this.$scope.reverse = (this.$scope.sortBy === sortBy) ? !this.$scope.reverse : false;
+ this.$scope.sortBy = sortBy;
+ };
+
+ this.$scope.addOrUpdateAttribute = (attribute?:AttributeModel):void => {
+ this.ModalsHandler.openEditAttributeModal(attribute ? attribute : new AttributeModel(), this.$scope.component);
+ };
+
+ this.$scope.delete = (attribute:AttributeModel):void => {
+
+ let onOk = ():void => {
+ this.$scope.component.deleteAttribute(attribute.uniqueId);
+ };
+ let title:string = this.$filter('translate')("ATTRIBUTE_VIEW_DELETE_MODAL_TITLE");
+ let message:string = this.$filter('translate')("ATTRIBUTE_VIEW_DELETE_MODAL_TEXT", "{'name': '" + attribute.name + "'}");
+ this.ModalsHandler.openConfirmationModal(title, message, false).then(onOk);
+ };
+ }
+}
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/attributes/attributes-view.html b/catalog-ui/src/app/view-models/workspace/tabs/attributes/attributes-view.html
index 59ba933a0a..59ba933a0a 100644
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/attributes/attributes-view.html
+++ b/catalog-ui/src/app/view-models/workspace/tabs/attributes/attributes-view.html
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/attributes/attributes.less b/catalog-ui/src/app/view-models/workspace/tabs/attributes/attributes.less
index ffd28afce4..ffd28afce4 100644
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/attributes/attributes.less
+++ b/catalog-ui/src/app/view-models/workspace/tabs/attributes/attributes.less
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
new file mode 100644
index 0000000000..e2d95280c8
--- /dev/null
+++ b/catalog-ui/src/app/view-models/workspace/tabs/composition/composition-view-model.ts
@@ -0,0 +1,242 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+'use strict';
+import {Component, Product, ComponentInstance, IAppMenu} from "app/models";
+import {SharingService, CacheService, EventListenerService, LeftPaletteLoaderService} from "app/services";
+import {ModalsHandler, GRAPH_EVENTS, ComponentFactory, ChangeLifecycleStateHandler, MenuHandler} 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";
+
+export interface ICompositionViewModelScope extends IWorkspaceViewModelScope {
+
+ currentComponent:Component;
+ selectedComponent:Component;
+ isLoading:boolean;
+ graphApi:any;
+ sharingService:SharingService;
+ sdcMenu:IAppMenu;
+ version:string;
+ isViewOnly:boolean;
+ isLoadingRightPanel:boolean;
+ onComponentInstanceVersionChange(component:Component);
+ isComponentInstanceSelected():boolean;
+ updateSelectedComponent():void
+ openUpdateModal();
+ deleteSelectedComponentInstance():void;
+ onBackgroundClick():void;
+ setSelectedInstance(componentInstance:ComponentInstance):void;
+ printScreen():void;
+
+ cacheComponentsInstancesFullData:Component;
+}
+
+export class CompositionViewModel {
+
+ static '$inject' = [
+ '$scope',
+ '$log',
+ 'sdcMenu',
+ 'MenuHandler',
+ '$uibModal',
+ '$state',
+ 'Sdc.Services.SharingService',
+ '$filter',
+ 'Sdc.Services.CacheService',
+ 'ComponentFactory',
+ 'ChangeLifecycleStateHandler',
+ 'LeftPaletteLoaderService',
+ 'ModalsHandler',
+ 'EventListenerService',
+ 'ComponentServiceNg2'
+ ];
+
+ constructor(private $scope:ICompositionViewModelScope,
+ private $log:ng.ILogService,
+ private sdcMenu:IAppMenu,
+ private MenuHandler:MenuHandler,
+ private $uibModal:ng.ui.bootstrap.IModalService,
+ private $state:ng.ui.IStateService,
+ private sharingService:SharingService,
+ private $filter:ng.IFilterService,
+ private cacheService:CacheService,
+ private ComponentFactory:ComponentFactory,
+ private ChangeLifecycleStateHandler:ChangeLifecycleStateHandler,
+ private LeftPaletteLoaderService:LeftPaletteLoaderService,
+ private ModalsHandler:ModalsHandler,
+ private eventListenerService:EventListenerService,
+ private ComponentServiceNg2: ComponentServiceNg2) {
+
+ this.$scope.setValidState(true);
+ this.initScope();
+ this.initGraphData();
+ this.$scope.updateSelectedMenuItem();
+ this.registerGraphEvents(this.$scope);
+ }
+
+
+ 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) => {
+ this.$scope.component.componentInstances = response.componentInstances;
+ this.$scope.component.componentInstancesRelations = response.componentInstancesRelations;
+ this.$scope.isLoading = false;
+ this.initComponent();
+ this.eventListenerService.notifyObservers(GRAPH_EVENTS.ON_COMPOSITION_GRAPH_DATA_LOADED);
+ });
+ } else {
+ this.eventListenerService.notifyObservers(GRAPH_EVENTS.ON_COMPOSITION_GRAPH_DATA_LOADED);
+ }
+ this.eventListenerService.unRegisterObserver(GRAPH_EVENTS.ON_COMPOSITION_GRAPH_DATA_LOADED);
+ };
+
+
+ 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 => {
+
+ this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_NODE_SELECTED, scope.setSelectedInstance);
+ this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_GRAPH_BACKGROUND_CLICKED, scope.onBackgroundClick);
+
+ };
+
+ private openUpdateComponentInstanceNameModal = ():void => {
+ this.ModalsHandler.openUpdateComponentInstanceNameModal(this.$scope.currentComponent).then(()=> {
+ this.eventListenerService.notifyObservers(GRAPH_EVENTS.ON_COMPONENT_INSTANCE_NAME_CHANGED, this.$scope.currentComponent.selectedInstance);
+
+ });
+ };
+
+ private removeSelectedComponentInstance = ():void => {
+ this.eventListenerService.notifyObservers(GRAPH_EVENTS.ON_DELETE_MULTIPLE_COMPONENTS);
+ };
+
+ private updateUuidMap = ():void => {
+ /**
+ * In case user press F5, the page is refreshed and this.sharingService.currentEntity will be undefined,
+ * but after loadService or loadResource this.sharingService.currentEntity will be defined.
+ * Need to update the uuidMap with the new resource or service.
+ */
+ this.sharingService.addUuidValue(this.$scope.currentComponent.uniqueId, this.$scope.currentComponent.uuid);
+ };
+
+ private initScope = ():void => {
+
+ this.$scope.sharingService = this.sharingService;
+ this.$scope.sdcMenu = this.sdcMenu;
+ this.$scope.isLoading = false;
+ this.$scope.isLoadingRightPanel = false;
+ this.$scope.graphApi = {};
+ this.$scope.version = this.cacheService.get('version');
+ this.initComponent();
+
+ this.cacheComponentsInstancesFullData = new Array<Component>();
+
+ this.$scope.isComponentInstanceSelected = ():boolean => {
+ return this.$scope.currentComponent && this.$scope.currentComponent.selectedInstance != undefined && this.$scope.currentComponent.selectedInstance != null;
+ };
+
+ this.$scope.updateSelectedComponent = ():void => {
+ if (this.$scope.currentComponent.selectedInstance) {
+
+ let componentParent = _.find(this.cacheComponentsInstancesFullData, (component) => {
+ return component.uniqueId === this.$scope.currentComponent.selectedInstance.componentUid;
+ });
+ if (componentParent) {
+ this.$scope.selectedComponent = componentParent;
+ }
+ else {
+ try {
+ let onSuccess = (component:Component) => {
+ this.$scope.isLoadingRightPanel = false;
+ this.$scope.selectedComponent = component;
+ this.cacheComponentsInstancesFullData.push(component);
+ };
+ let onError = (component:Component) => {
+ console.log("Error updating selected component");
+ this.$scope.isLoadingRightPanel = false;
+ };
+ this.ComponentFactory.getComponentFromServer(this.$scope.currentComponent.selectedInstance.originType, this.$scope.currentComponent.selectedInstance.componentUid).then(onSuccess, onError);
+ } catch (e) {
+ console.log("Error updating selected component", e);
+ this.$scope.isLoadingRightPanel = false;
+ }
+ }
+ }
+ else {
+
+ this.$scope.selectedComponent = this.$scope.currentComponent;
+ }
+ };
+
+ this.$scope.setSelectedInstance = (selectedComponent:ComponentInstance):void => {
+
+ this.$log.debug('composition-view-model::onNodeSelected:: with id: ' + selectedComponent.uniqueId);
+ this.$scope.currentComponent.setSelectedInstance(selectedComponent);
+ this.$scope.updateSelectedComponent();
+
+ if (this.$state.current.name === 'workspace.composition.api') {
+ this.$state.go('workspace.composition.details');
+ }
+ if (this.$state.current.name === 'workspace.composition.relations' && this.$scope.currentComponent.isProduct()) {
+ this.$state.go('workspace.composition.details');
+ }
+ };
+
+ this.$scope.onBackgroundClick = ():void => {
+ this.$scope.currentComponent.selectedInstance = null;
+ this.$scope.selectedComponent = this.$scope.currentComponent;
+
+ if (this.$state.current.name === 'workspace.composition.api') {
+ this.$state.go('workspace.composition.details');
+ }
+ };
+
+ this.$scope.openUpdateModal = ():void => {
+ this.openUpdateComponentInstanceNameModal();
+ };
+
+ 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);
+ };
+
+ this.$scope.onComponentInstanceVersionChange = (component:Product):void => {
+ this.$scope.currentComponent = component;
+ this.$scope.setComponent(this.$scope.currentComponent);
+ this.$scope.updateSelectedComponent();
+ }
+
+ }
+}
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/composition/composition-view.html b/catalog-ui/src/app/view-models/workspace/tabs/composition/composition-view.html
index 4efc74c31b..761ae53909 100644
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/composition/composition-view.html
+++ b/catalog-ui/src/app/view-models/workspace/tabs/composition/composition-view.html
@@ -1,17 +1,12 @@
<div class="workspace-composition">
<loader data-display="isLoading"></loader>
- <div class="w-sdc-designer-canvas" data-ng-class="{sidebaractive: displayDesignerRightSidebar}" >
- <palette components="leftPanelComponents"
- current-component="currentComponent"
+ <div class="w-sdc-designer-canvas" data-ng-class="{sidebaractive: displayDesignerRightSidebar}">
+ <palette current-component="currentComponent"
is-view-only="isViewOnly"
is-loading="isLoading"></palette>
- <composition-graph component="currentComponent" is-view-only="isViewOnly"></composition-graph>
- <!--<graph-creator left-panel-components="leftPanelComponents"-->
- <!--data-tests-id="canvas"-->
- <!--on-instance-selected="setSelectedInstance(componentInstance)"-->
- <!--on-background-click="onBackgroundClick()" current-component="currentComponent"-->
- <!--api="graphApi" is-view-only="isViewOnly" is-loading="isLoading"></graph-creator>-->
+ <composition-graph component="currentComponent" data-tests-id="canvas"
+ is-view-only="isViewOnly"></composition-graph>
</div>
<div class="w-sdc-designer-sidebar-toggle" data-ng-class="{'active': displayDesignerRightSidebar}"
@@ -50,14 +45,15 @@
<div class="w-sdc-designer-sidebar-tabs">
<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">
+ tooltips tooltip-class="tooltip-custom tab-tooltip" tooltip-content="Information"
+ data-tests-id="information-tab">
<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"
- ui-sref="workspace.composition.structure"
- tooltips tooltip-class="tooltip-custom tab-tooltip" tooltip-content="Composition">
- <div class="i-sdc-designer-sidebar-tab-icon sprite-new structure"></div>
- </button>
+ <!--<button class="i-sdc-designer-sidebar-tab" data-ui-sref-active="active"-->
+ <!--ui-sref="workspace.composition.structure"-->
+ <!--tooltips tooltip-class="tooltip-custom tab-tooltip" tooltip-content="Composition">-->
+ <!--<div class="i-sdc-designer-sidebar-tab-icon sprite-new structure"></div>-->
+ <!--</button>-->
<button class="i-sdc-designer-sidebar-tab" data-ui-sref-active="active"
data-ui-sref="workspace.composition.deployment"
tooltips tooltip-class="tooltip-custom tab-tooltip" tooltip-content="Deployment Artifacts"
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/composition/composition.less b/catalog-ui/src/app/view-models/workspace/tabs/composition/composition.less
index 4c4c0a87a5..501805be3f 100644
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/composition/composition.less
+++ b/catalog-ui/src/app/view-models/workspace/tabs/composition/composition.less
@@ -1,24 +1,25 @@
.composition{
.sdc-workspace-container{
- .w-sdc-main-container{
- .w-sdc-main-right-container{
- left:0;
- .sdc-workspace-top-bar {
- padding-left: 295px;
- .not-latest{
- left: 270px;
- }
- }
- .w-sdc-main-container-body-content{
- padding: 0 0 0 247px;
+ .w-sdc-main-container{
+ .w-sdc-main-right-container{
+ left:0;
+ //overflow-y: scroll;
+ .sdc-workspace-top-bar {
+ padding-left: 295px;
+ .not-latest{
+ left: 270px;
}
+ }
+ .w-sdc-main-container-body-content{
+ padding: 0 0 0 247px;
+ }
- > div:first-child{
- padding: 0;
- }
+ > div:first-child{
+ padding: 0;
}
}
+ }
}
}
@@ -67,7 +68,7 @@
.w-sdc-designer-sidebar {
background-color:@main_color_p ;
.noselect;
- bottom: 0;
+ bottom: @footer_height;
position: fixed;
right: -302px;
width: 302px;
@@ -146,7 +147,7 @@
height: 36px;
padding-top: 9px;
text-align: center;
- width: 50px;
+ width: 60px;
.hand;
&:focus {
@@ -156,7 +157,7 @@
/* .disabled; */
}
&.active, &:hover:enabled {
- background-color: @tlv_color_u;
+ background-color: @tlv_color_u;
.i-sdc-designer-sidebar-tab-icon {
opacity: 1;
@@ -173,7 +174,7 @@
.i-sdc-designer-sidebar-tab-icon {
margin-top: 5px ;
- // opacity: .4;
+ // opacity: .4;
}
.w-sdc-designer-sidebar-tab-content {
@@ -184,8 +185,9 @@
.w-sdc-designer-sidebar-tab-content-view {
position: absolute;
top: 156px;
- bottom: 0px;
+ bottom: 0;
width: 100%;
+ padding-bottom: 10px;
}
@@ -395,6 +397,13 @@
margin-top: 65px;
}
+ &.update-env {
+ background-color: transparent;
+ border: 0;
+ right: 15px;
+ margin-top: 65px;
+ }
+
&.attach {
background-color: transparent;
border: 0;
@@ -487,7 +496,7 @@
}
.w-scd-diagram-container {
- // left: 240px;
+ // left: 240px;
//right: 300px;
}
@@ -783,10 +792,10 @@
box-shadow: 0px 2px 2px 0px rgba(24, 24, 25, 0.1);
width: 91px;
-/* &.vl-type-select{
- width: 173px;
- }
-*/
+ /* &.vl-type-select{
+ width: 173px;
+ }
+ */
h3 {
color: @func_color_s;
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
new file mode 100644
index 0000000000..0ac5fd0799
--- /dev/null
+++ b/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/artifacts/artifacts-view-model.ts
@@ -0,0 +1,301 @@
+'use strict';
+import {
+ ArtifactModel,
+ Service,
+ IAppConfigurtaion,
+ Resource,
+ Component,
+ ComponentInstance,
+ ArtifactGroupModel,
+ IFileDownload
+} from "app/models";
+import {ICompositionViewModelScope} from "../../composition-view-model";
+import {ArtifactsUtils, ModalsHandler, ArtifactGroupType} from "app/utils";
+import {GRAPH_EVENTS} from "app/utils/constants";
+import {EventListenerService} from "app/services/event-listener-service";
+
+export interface IArtifactsViewModelScope extends ICompositionViewModelScope {
+ artifacts:Array<ArtifactModel>;
+ artifactType:string;
+ downloadFile:IFileDownload;
+ isLoading:boolean;
+
+ getTitle():string;
+ addOrUpdate(artifact:ArtifactModel):void;
+ delete(artifact:ArtifactModel):void;
+ download(artifact:ArtifactModel):void;
+ openEditEnvParametersModal(artifact:ArtifactModel):void;
+ getEnvArtifact(heatArtifact:ArtifactModel):any;
+ getEnvArtifactName(artifact:ArtifactModel):string;
+ isLicenseArtifact(artifact:ArtifactModel):boolean;
+ isVFiArtifact(artifact:ArtifactModel):boolean;
+}
+
+export class ResourceArtifactsViewModel {
+
+ static '$inject' = [
+ '$scope',
+ '$filter',
+ '$state',
+ 'sdcConfig',
+ 'ArtifactsUtils',
+ 'ModalsHandler',
+ '$q',
+ 'EventListenerService'
+ ];
+
+ constructor(private $scope:IArtifactsViewModelScope,
+ private $filter:ng.IFilterService,
+ private $state:any,
+ private sdcConfig:IAppConfigurtaion,
+ private artifactsUtils:ArtifactsUtils,
+ private ModalsHandler:ModalsHandler,
+ private $q:ng.IQService,
+ private eventListenerService: EventListenerService) {
+
+ this.initScope();
+ }
+
+
+ private initArtifactArr = (artifactType:string):void => {
+ let artifacts:Array<ArtifactModel> = [];
+
+ if (this.$scope.selectedComponent) {
+ if ('interface' == artifactType) {
+ let interfaces = this.$scope.currentComponent.interfaces;
+ if (interfaces && interfaces.standard && interfaces.standard.operations) {
+
+ angular.forEach(interfaces.standard.operations, (operation:any, interfaceName:string):void => {
+ let item:ArtifactModel = <ArtifactModel>{};
+ if (operation.implementation) {
+ item = <ArtifactModel> operation.implementation;
+ }
+ item.artifactDisplayName = interfaceName;
+ item.artifactLabel = interfaceName;
+ item.mandatory = false;
+ artifacts.push(item);
+ });
+ }
+ } else {
+ //init normal artifacts, deployment or api artifacts
+ let artifactsObj:ArtifactGroupModel;
+ switch (artifactType) {
+ case "api":
+ artifactsObj = (<Service>this.$scope.currentComponent).serviceApiArtifacts;
+ break;
+ case "deployment":
+ if (!this.$scope.isComponentInstanceSelected()) {
+ artifactsObj = this.$scope.currentComponent.deploymentArtifacts;
+ } else {
+ artifactsObj = this.$scope.currentComponent.selectedInstance.deploymentArtifacts;
+ }
+ break;
+ default:
+ //artifactsObj = this.$scope.selectedComponent.artifacts;
+ if (!this.$scope.isComponentInstanceSelected()) {
+ artifactsObj = this.$scope.currentComponent.artifacts;
+ } else {
+ artifactsObj = this.$scope.currentComponent.selectedInstance.artifacts;
+ }
+ break;
+ }
+ _.forEach(artifactsObj, (artifact:ArtifactModel, key) => {
+ artifacts.push(artifact);
+ });
+ }
+ }
+ this.$scope.artifacts = artifacts;
+ };
+
+
+ private convertToArtifactUrl = (artifactType:string):string => {
+
+ switch (artifactType) {
+ case 'deployment':
+ return 'DEPLOYMENT';
+ case 'api':
+ return 'SERVICE_API';
+ default:
+ return 'INFORMATIONAL';
+ }
+
+ }
+
+ private loadComponentArtifactIfNeeded = (forceLoad?: boolean) => {
+
+ let onGetComponentArtifactsSuccess = (artifacts:ArtifactGroupModel)=> {
+ switch (this.$scope.artifactType) {
+ case 'deployment':
+ this.$scope.currentComponent.deploymentArtifacts = artifacts;
+ break;
+ case 'api':
+ (<Service>this.$scope.currentComponent).serviceApiArtifacts = artifacts;
+ break;
+ default:
+ this.$scope.currentComponent.artifacts = artifacts;
+ break;
+ }
+ this.$scope.isLoading = false;
+ this.initArtifactArr(this.$scope.artifactType);
+ }
+
+ let onError = ()=> {
+ this.$scope.isLoading = false;
+ };
+
+ switch (this.$scope.artifactType) {
+ case 'deployment':
+ if(forceLoad || !this.$scope.currentComponent.deploymentArtifacts) {
+ this.$scope.component.getArtifactByGroupType(this.convertToArtifactUrl(this.$scope.artifactType)).then(onGetComponentArtifactsSuccess, onError);
+ } else {
+ this.initArtifactArr(this.$scope.artifactType);
+ }
+
+ break;
+ case 'api':
+ if(!(<Service>this.$scope.currentComponent).serviceApiArtifacts) {
+ this.$scope.component.getArtifactByGroupType(this.convertToArtifactUrl(this.$scope.artifactType)).then(onGetComponentArtifactsSuccess, onError);
+ } else {
+ this.initArtifactArr(this.$scope.artifactType);
+ }
+ break;
+ default:
+ if(!this.$scope.currentComponent.artifacts) {
+ this.$scope.component.getArtifactByGroupType(this.convertToArtifactUrl(this.$scope.artifactType)).then(onGetComponentArtifactsSuccess, onError);
+ } else {
+ this.initArtifactArr(this.$scope.artifactType);
+ }
+ break;
+ }
+ }
+ private loadArtifacts = (forceLoad?: boolean):void => {
+
+ let onGetInstanceArtifactsSuccess = (artifacts:ArtifactGroupModel)=> {
+ switch (this.$scope.artifactType) {
+ case 'deployment':
+ this.$scope.currentComponent.selectedInstance.deploymentArtifacts = artifacts;
+ break;
+ default:
+ this.$scope.currentComponent.selectedInstance.artifacts = artifacts;
+ break;
+ }
+ this.loadComponentArtifactIfNeeded();
+ };
+
+ let onError = ()=> {
+ this.$scope.isLoading = false;
+ };
+
+ this.$scope.isLoading = true;
+ if (this.$scope.isComponentInstanceSelected()) {
+ this.$scope.component.getComponentInstanceArtifactsByGroupType(this.$scope.component.selectedInstance.uniqueId, this.convertToArtifactUrl(this.$scope.artifactType)).then(onGetInstanceArtifactsSuccess, onError);
+ } else {
+ this.loadComponentArtifactIfNeeded(forceLoad);
+ }
+ }
+
+ private updateArtifactsIfNeeded = ():void => {
+ if (this.$scope.artifactType === "deployment") {
+ this.loadArtifacts(true);
+ } else {
+ this.initArtifactArr(this.$scope.artifactType);
+ }
+ };
+
+ private openEditArtifactModal = (artifact:ArtifactModel):void => {
+ this.ModalsHandler.openArtifactModal(artifact, this.$scope.currentComponent).then(():void => {
+ this.updateArtifactsIfNeeded();
+ });
+ };
+
+ private initScope = ():void => {
+
+ this.$scope.isLoading = false;
+ this.$scope.artifactType = this.artifactsUtils.getArtifactTypeByState(this.$state.current.name);
+ this.loadArtifacts();
+ this.$scope.getTitle = ():string => {
+ return this.artifactsUtils.getTitle(this.$scope.artifactType, this.$scope.currentComponent);
+ };
+
+ this.$scope.isVFiArtifact = (artifact:ArtifactModel):boolean=> {
+ if (artifact.artifactGroupType === ArtifactGroupType.INFORMATION) {//fix DE256847
+ return this.$scope.currentComponent.artifacts && (!this.$scope.currentComponent.artifacts[artifact.artifactLabel] || !this.$scope.currentComponent.artifacts[artifact.artifactLabel].artifactName);
+ }
+ return this.$scope.currentComponent.deploymentArtifacts && (!this.$scope.currentComponent.deploymentArtifacts[artifact.artifactLabel]);//fix DE251314
+ };
+
+ this.$scope.addOrUpdate = (artifact:ArtifactModel):void => {
+ this.artifactsUtils.setArtifactType(artifact, this.$scope.artifactType);
+ let artifactCopy = new ArtifactModel(artifact);
+ this.openEditArtifactModal(artifactCopy);
+ };
+
+
+ this.$scope.delete = (artifact:ArtifactModel):void => {
+
+ let onOk = ():void => {
+ this.$scope.isLoading = true;
+ this.artifactsUtils.removeArtifact(artifact, this.$scope.artifacts);
+
+ let success = (responseArtifact:ArtifactModel):void => {
+ this.initArtifactArr(this.$scope.artifactType);
+ this.$scope.isLoading = false;
+ };
+
+ let error = (error:any):void => {
+ console.log('Delete artifact returned error:', error);
+ this.initArtifactArr(this.$scope.artifactType);
+ this.$scope.isLoading = false;
+ };
+ if (this.$scope.isComponentInstanceSelected()) {
+ this.$scope.currentComponent.deleteInstanceArtifact(artifact.uniqueId, artifact.artifactLabel).then(success, error);
+ } else {
+ this.$scope.currentComponent.deleteArtifact(artifact.uniqueId, artifact.artifactLabel).then(success, error);//TODO simulate error (make sure error returns)
+ }
+ };
+ let title:string = this.$filter('translate')("ARTIFACT_VIEW_DELETE_MODAL_TITLE");
+ let message:string = this.$filter('translate')("ARTIFACT_VIEW_DELETE_MODAL_TEXT", "{'name': '" + artifact.artifactDisplayName + "'}");
+ this.ModalsHandler.openConfirmationModal(title, message, false).then(onOk);
+ };
+
+
+ this.$scope.getEnvArtifact = (heatArtifact:ArtifactModel):any=> {
+ return _.find(this.$scope.artifacts, (item:ArtifactModel)=> {
+ return item.generatedFromId === heatArtifact.uniqueId;
+ });
+ };
+
+ this.$scope.getEnvArtifactName = (artifact:ArtifactModel):string => {
+ let envArtifact = this.$scope.getEnvArtifact(artifact);
+ if (envArtifact) {
+ return envArtifact.artifactDisplayName;
+ }
+ };
+
+ this.$scope.isLicenseArtifact = (artifact:ArtifactModel):boolean => {
+ let isLicense:boolean = false;
+ if (this.$scope.component.isResource() && (<Resource>this.$scope.component).isCsarComponent()) {
+ isLicense = this.artifactsUtils.isLicenseType(artifact.artifactType);
+ }
+
+ return isLicense;
+ };
+
+ this.$scope.openEditEnvParametersModal = (artifact:ArtifactModel):void => {
+ this.ModalsHandler.openEditEnvParametersModal(artifact, this.$scope.currentComponent).then(()=> {
+ this.updateArtifactsIfNeeded();
+ }, ()=> {
+ // ERROR
+ });
+ };
+
+ this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_NODE_SELECTED, this.loadArtifacts);
+ this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_GRAPH_BACKGROUND_CLICKED, this.loadArtifacts);
+
+ this.$scope.$on('$destroy', () => {
+
+ this.eventListenerService.unRegisterObserver(GRAPH_EVENTS.ON_NODE_SELECTED, this.loadArtifacts);
+ this.eventListenerService.unRegisterObserver(GRAPH_EVENTS.ON_GRAPH_BACKGROUND_CLICKED, this.loadArtifacts);
+ });
+ }
+}
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/composition/tabs/artifacts/artifacts-view.html b/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/artifacts/artifacts-view.html
index 8c0138964f..b0d81b3437 100644
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/composition/tabs/artifacts/artifacts-view.html
+++ b/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/artifacts/artifacts-view.html
@@ -6,26 +6,29 @@
<div class="w-sdc-designer-sidebar-section-title-icon"></div>
</expand-collapse>
- <div class="w-sdc-designer-sidebar-section-content" data-ng-hide="'deployment' == artifactType && !selectedComponent.isComplex()">
+ <div class="w-sdc-designer-sidebar-section-content">
<div class="i-sdc-designer-sidebar-section-content-item">
<div class="i-sdc-designer-sidebar-section-content-item-artifact"
- data-ng-repeat="artifact in artifacts | orderBy: ['-mandatory', 'artifactDisplayName'] track by $index" data-ng-if="!isComponentInstanceSelected() || (isVFiArtifact(artifact)|| artifact.esId) && 'HEAT_ENV' !== artifact.artifactType">
- <span data-ng-if="isComponentInstanceSelected() && artifact.heatParameters.length" class="i-sdc-designer-sidebar-section-content-item-file-link"></span>
+ data-ng-repeat="artifact in artifacts | orderBy: ['-mandatory', 'artifactDisplayName'] track by $index"
+ data-ng-if="(!isComponentInstanceSelected() || isVFiArtifact(artifact)|| artifact.esId) && 'HEAT_ENV' !== artifact.artifactType"
+ data-tests-id="artifact-item-{{artifact.artifactDisplayName}}">
+ <span data-ng-if="artifact.heatParameters.length" class="i-sdc-designer-sidebar-section-content-item-file-link"></span>
<div class="i-sdc-designer-sidebar-section-content-item-artifact-details" data-ng-class="{'heat':artifact.isHEAT() && artifact.heatParameters.length}">
- <div class="i-sdc-designer-sidebar-section-content-item-artifact-filename" data-tests-id="artifactName"
- data-ng-class="{'hand enabled':!isComponentInstanceSelected() && artifact.heatParameters.length && !isViewMode()}"
+ <div class="i-sdc-designer-sidebar-section-content-item-artifact-filename" data-tests-id="artifactName-{{artifact.artifactDisplayName}}"
data-ng-bind="artifact.artifactName" tooltips tooltip-content="{{artifact.artifactName}}"
- data-ng-click="!isViewMode() && !isComponentInstanceSelected() && artifact.heatParameters.length && openEditEnvParametersModal(artifact)" data-ng-if="artifact.artifactName"></div>
+ data-ng-if="artifact.artifactName"></div>
<div>
<span class="i-sdc-designer-sidebar-section-content-item-artifact-details-name" data-tests-id="artifact_Display_Name-{{artifact.artifactDisplayName}}"
- data-ng-class="{'hand enabled': (!isComponentInstanceSelected()||isVFiArtifact(artifact)) && !isViewMode() && !artifact.isHEAT() && !artifact.isThirdParty() && !isLicenseArtifact(artifact)}"
+ data-ng-class="{'hand enabled': (isVFiArtifact(artifact)) && !isViewMode() && !artifact.isHEAT() && !artifact.isThirdParty() && !isLicenseArtifact(artifact)}"
data-ng-bind="artifact.artifactDisplayName" data-ng-click="!isViewMode() && !isLoading && (!isComponentInstanceSelected()||isVFiArtifact(artifact)) && !artifact.isHEAT() && !artifact.isThirdParty() && !isLicenseArtifact(artifact) && addOrUpdate(artifact)"
tooltips tooltip-content="{{artifact.artifactDisplayName}}"></span>
- <div class="i-sdc-designer-sidebar-section-content-item-artifact-heat-env" ng-if="isComponentInstanceSelected() && artifact.heatParameters.length">
- <span class="enabled" data-ng-bind="getEnvArtifactName(artifact)" data-ng-click="!isViewMode() && addOrUpdate(getEnvArtifact(artifact))"></span>
- <download-artifact class="i-sdc-designer-sidebar-section-content-item-button download-env sprite e-sdc-small-download hand" artifact="getEnvArtifact(artifact)"
- component="currentComponent" instance="true"
- data-tests-id="download"></download-artifact>
+ <div class="i-sdc-designer-sidebar-section-content-item-artifact-heat-env" ng-if="artifact.heatParameters.length">
+ <span data-ng-bind="getEnvArtifactName(artifact)"data-tests-id="heat_env_{{artifact.artifactDisplayName}}"></span>
+ <button class="i-sdc-designer-sidebar-section-content-item-button update-env sprite e-sdc-small-icon-pencil" data-tests-id="edit_{{artifact.artifactDisplayName}}"
+ data-ng-if="!isViewMode()" data-ng-click="addOrUpdate(getEnvArtifact(artifact))"></button>
+ <download-artifact class="i-sdc-designer-sidebar-section-content-item-button download-env sprite e-sdc-small-download hand" artifact="getEnvArtifact(artifact)"
+ component="currentComponent" instance="isComponentInstanceSelected()"
+ data-tests-id="download_env_{{artifact.artifactDisplayName}}"></download-artifact>
</div>
</div>
@@ -34,14 +37,23 @@
</div>
</div>
<button ng-if="!isViewMode() && artifact.esId && (!isComponentInstanceSelected()||isVFiArtifact(artifact)) && !artifact.isHEAT() && !artifact.isThirdParty() && !isLicenseArtifact(artifact)" class="i-sdc-designer-sidebar-section-content-item-button delete sprite e-sdc-small-icon-delete"
- data-tests-id="delete" data-ng-click="delete(artifact)" type="button"></button>
- <button ng-if="!isViewMode() && isComponentInstanceSelected() && (getEnvArtifact(artifact)).heatParameters.length"
+ data-tests-id="delete_{{artifact.artifactDisplayName}}" data-ng-click="delete(artifact)" type="button"></button>
+ <button ng-if="!isViewMode() && artifact.isHEAT() && isComponentInstanceSelected() && artifact.heatParameters.length"
class="i-sdc-designer-sidebar-section-content-item-button attach sprite e-sdc-small-icon-pad"
- data-ng-click="openEditEnvParametersModal(getEnvArtifact(artifact))" type="button"></button>
+ data-ng-click="openEditEnvParametersModal(getEnvArtifact(artifact))" type="button"
+ data-tests-id="edit-parameters-of-{{artifact.artifactDisplayName}}"></button>
+ <!--need to remove this button -->
+ <button ng-if="!isViewMode() && artifact.isHEAT() && !isComponentInstanceSelected() && artifact.heatParameters.length"
+ class="i-sdc-designer-sidebar-section-content-item-button attach sprite e-sdc-small-icon-pad"
+ data-ng-click="openEditEnvParametersModal(artifact)" type="button"
+ data-tests-id="edit-parameters-of-{{artifact.artifactDisplayName}}"></button>
+
<download-artifact ng-if="artifact.esId && 'deployment' != artifactType" class="i-sdc-designer-sidebar-section-content-item-button download sprite e-sdc-small-download hand"
- artifact="artifact" component="selectedComponent" data-tests-id="download"></download-artifact>
+ artifact="artifact" component="currentComponent" data-tests-id="download-{{artifact.artifactDisplayName}}" instance="isComponentInstanceSelected()"></download-artifact>
<download-artifact ng-if="artifact.esId && 'deployment' == artifactType" class="i-sdc-designer-sidebar-section-content-item-button download sprite e-sdc-small-download hand"
- artifact="artifact" component="currentComponent" instance="isComponentInstanceSelected()" data-tests-id="download"></download-artifact>
+ artifact="artifact" component="currentComponent" instance="isComponentInstanceSelected()" data-tests-id="download_{{artifact.artifactDisplayName}}"
+ show-loader="artifact.isHEAT()"
+ download-icon-class="i-sdc-designer-sidebar-section-content-item-button download sprite e-sdc-small-download hand"></download-artifact>
<button ng-if="!isViewMode() && !artifact.esId && artifactType==='deployment' && !isComponentInstanceSelected() && !artifact.isThirdParty()" class="i-sdc-designer-sidebar-section-content-item-button attach sprite e-sdc-small-icon-upload"
data-ng-click="addOrUpdate(artifact)" type="button" data-tests-id="add_Artifact"></button>
</div>
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/composition/tabs/artifacts/artifacts.less b/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/artifacts/artifacts.less
index 5726ca66fc..7c8b8315d9 100644
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/composition/tabs/artifacts/artifacts.less
+++ b/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/artifacts/artifacts.less
@@ -99,7 +99,7 @@
position: relative;
// line-height: 36px;
min-height: 61px;
- cursor: default;
+ //cursor: default;
display: flex;
align-items: center;
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
new file mode 100644
index 0000000000..a81bb9176e
--- /dev/null
+++ b/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/details/details-view-model.ts
@@ -0,0 +1,132 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+'use strict';
+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";
+
+export interface IEditResourceVersion {
+ allVersions:any;
+ changeVersion:string;
+}
+
+interface IDetailsViewModelScope extends ICompositionViewModelScope {
+ isLoading:boolean;
+ $parent:ICompositionViewModelScope;
+ expandedSection:Array<string>;
+ editForm:ng.IFormController;
+ editResourceVersion:IEditResourceVersion;
+
+ changeResourceVersion():void;
+}
+
+export class DetailsViewModel {
+
+ static '$inject' = [
+ '$scope',
+ 'LeftPaletteLoaderService',
+ 'EventListenerService'
+
+ ];
+
+ constructor(private $scope:IDetailsViewModelScope,
+ private LeftPaletteLoaderService:LeftPaletteLoaderService,
+ private eventListenerService:EventListenerService) {
+ this.initScope();
+ }
+
+ private clearSelectedVersion = ():void => {
+ this.$scope.editResourceVersion = {
+ allVersions: {},
+ changeVersion: null
+ };
+ };
+
+ private versioning:Function = (versionNumber:string):string => {
+ let version:Array<string> = versionNumber.split('.');
+ return '00000000'.slice(version[0].length) + version[0] + '.' + '00000000'.slice(version[1].length) + version[1];
+ };
+
+ private initEditResourceVersion = ():void => {
+ this.clearSelectedVersion();
+ this.$scope.editResourceVersion.allVersions[this.$scope.currentComponent.selectedInstance.componentVersion] = this.$scope.currentComponent.selectedInstance.componentUid;
+ _.merge(this.$scope.editResourceVersion.allVersions, angular.copy(this.$scope.selectedComponent.allVersions));
+ let sorted:any = _.sortBy(_.toPairs(this.$scope.editResourceVersion.allVersions), (item)=> {
+ return this.versioning(item[0]);
+ });
+ this.clearSelectedVersion();
+ _.forEach(sorted, (item)=> {
+ this.$scope.editResourceVersion.allVersions[item[0]] = item[1];
+ });
+
+ let highestVersion = _.last(Object.keys(this.$scope.selectedComponent.allVersions));
+
+ if (parseFloat(highestVersion) % 1) { //if highest is minor, make sure it is the latest checked in -
+ let latestVersionComponent:LeftPaletteComponent = _.find(this.LeftPaletteLoaderService.getLeftPanelComponentsForDisplay(this.$scope.currentComponent.componentType), (component:LeftPaletteComponent) => { //latest checked in
+ return (component.systemName === this.$scope.selectedComponent.systemName
+ || component.uuid === this.$scope.selectedComponent.uuid);
+ });
+ let latestVersion:string = latestVersionComponent ? latestVersionComponent.version : highestVersion;
+
+ if (highestVersion != latestVersion) { //highest is checked out - remove from options
+ this.$scope.editResourceVersion.allVersions = _.omit(this.$scope.editResourceVersion.allVersions, highestVersion);
+ }
+ }
+ this.$scope.editResourceVersion.changeVersion = this.$scope.currentComponent.selectedInstance.componentVersion;
+ };
+
+ private initScope = ():void => {
+ this.$scope.isLoading = false;
+ this.$scope.$parent.isLoading = false;
+ this.$scope.expandedSection = ['general', 'tags'];
+ //this.clearSelectedVersion();
+
+ this.$scope.$watch('selectedComponent', (component:Component) => {
+ if (this.$scope.isComponentInstanceSelected()) {
+ this.initEditResourceVersion();
+ }
+ });
+
+ this.$scope.changeResourceVersion = ():void => {
+ this.$scope.isLoading = true;
+ this.$scope.$parent.isLoading = true;
+
+ let onSuccess = (component:Component)=> {
+ this.$scope.isLoading = false;
+ this.$scope.$parent.isLoading = false;
+ this.$scope.onComponentInstanceVersionChange(component);
+
+ this.eventListenerService.notifyObservers(GRAPH_EVENTS.ON_VERSION_CHANGED, this.$scope.currentComponent);
+ };
+
+ let onFailed = (error:any)=> {
+ this.$scope.isLoading = false;
+ this.$scope.$parent.isLoading = false;
+ console.log(error);
+ };
+
+ let componentUid:string = this.$scope.editResourceVersion.allVersions[this.$scope.editResourceVersion.changeVersion];
+ this.$scope.currentComponent.changeComponentInstanceVersion(componentUid).then(onSuccess, onFailed);
+ };
+ }
+}
diff --git a/catalog-ui/app/scripts/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 6ae462760c..70dc58075a 100644
--- a/catalog-ui/app/scripts/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() || selectedComponent.isVl()" data-tests-id="rightTab_version" data-ng-bind="selectedComponent.version"></span>
<ng-form name="editForm" data-ng-if="isComponentInstanceSelected() && !selectedComponent.isVl()">
- <select data-ng-model="editResourceVersion.changeVersion" name="changeVersion" data-ng-disabled="$parent.isViewOnly"
+ <select data-ng-model="editResourceVersion.changeVersion" name="changeVersion" data-tests-id="changeVersion" data-ng-disabled="$parent.isViewOnly"
class="i-sdc-designer-sidebar-section-content-item-value i-sdc-form-select"
data-ng-class="{'minor': (editResourceVersion.changeVersion)%1}"
data-ng-change="changeResourceVersion()">
@@ -80,7 +80,12 @@
<div class="i-sdc-designer-sidebar-section-content-item">
<span class="i-sdc-designer-sidebar-section-content-item-label" translate="GENERAL_LABEL_CONTACT_ID"></span>
<span class="i-sdc-designer-sidebar-section-content-item-value" data-ng-bind="selectedComponent.contactId"
- data-tests-id="rightTab_userId"></span>
+ data-tests-id="rightTab_contactId"></span>
+ </div>
+ <div class="i-sdc-designer-sidebar-section-content-item" data-ng-if="isViewMode() && currentComponent.isService() && selectedComponent.isResource()">
+ <span class="i-sdc-designer-sidebar-section-content-item-label">Resource Customization UUID:</span><br>
+ <span class="customization-uuid selectable" data-ng-bind="currentComponent.selectedInstance.customizationUUID"
+ data-tests-id="rightTab_customizationModuleUUID"></span><br>
</div>
<div class="i-sdc-designer-sidebar-section-content-item description">
<span class="i-sdc-designer-sidebar-section-content-item-label">Description:
@@ -118,6 +123,8 @@
<div class="w-sdc-designer-sidebar-section-content tags">
<div class="i-sdc-designer-sidebar-section-content-item">
+ <span class="i-sdc-designer-sidebar-section-content-item-tag" data-ng-if="selectedComponent.tags.indexOf(selectedComponent.name)===-1" data-ng-bind="selectedComponent.name"
+ data-tests-id="rightTab_tag" tooltips tooltip-content="{{selectedComponent.name}}"></span>
<span class="i-sdc-designer-sidebar-section-content-item-tag" data-ng-repeat="tag in selectedComponent.tags track by $index" data-ng-bind="tag"
data-tests-id="rightTab_tag" tooltips tooltip-content="{{tag}}"></span>
</div>
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/composition/tabs/details/details.less b/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/details/details.less
index e88e130379..841ab3aa49 100644
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/composition/tabs/details/details.less
+++ b/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/details/details.less
@@ -59,6 +59,10 @@
font-weight: normal;
}
+ .customization-uuid{
+ .f-type._12_m;
+ }
+
.w-sdc-designer-sidebar-section.tags {
.i-sdc-designer-sidebar-section-content-item {
white-space: normal;
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
new file mode 100644
index 0000000000..84769d7a62
--- /dev/null
+++ b/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/properties-and-attributes/properties-view-model.ts
@@ -0,0 +1,217 @@
+'use strict';
+import {
+ AttributeModel,
+ AttributesGroup,
+ Component,
+ ComponentInstance,
+ PropertyModel,
+ PropertiesGroup
+} from "app/models";
+import {ICompositionViewModelScope} from "../../composition-view-model";
+import {ModalsHandler} from "app/utils";
+import {ComponentServiceNg2} from "app/ng2/services/component-services/component.service";
+import {ComponentGenericResponse} from "app/ng2/services/responses/component-generic-response";
+
+interface IResourcePropertiesAndAttributesViewModelScope extends ICompositionViewModelScope {
+ properties:PropertiesGroup;
+ attributes:AttributesGroup;
+ propertiesMessage:string;
+ groupPropertiesByInstance:boolean;
+ showGroupsOfInstanceProperties:Array<boolean>;
+ addProperty():void;
+ updateProperty(property:PropertyModel):void;
+ deleteProperty(property:PropertyModel):void;
+ viewAttribute(attribute:AttributeModel):void;
+ groupNameByKey(key:string):string;
+ isPropertyOwner():boolean;
+ getComponentInstanceNameFromInstanceByKey(key:string):string;
+}
+
+export class ResourcePropertiesViewModel {
+
+ static '$inject' = [
+ '$scope',
+ '$filter',
+ '$uibModal',
+ 'ModalsHandler',
+ 'ComponentServiceNg2'
+
+ ];
+
+
+ constructor(private $scope:IResourcePropertiesAndAttributesViewModelScope,
+ private $filter:ng.IFilterService,
+ private $uibModal:ng.ui.bootstrap.IModalService,
+ private ModalsHandler:ModalsHandler,
+ private ComponentServiceNg2:ComponentServiceNg2) {
+
+ this.getComponentInstancesPropertiesAndAttributes();
+ }
+
+ private initComponentProperties = ():void => {
+ let result:PropertiesGroup = {};
+
+ if (this.$scope.selectedComponent) {
+ this.$scope.propertiesMessage = undefined;
+ this.$scope.groupPropertiesByInstance = false;
+ if (this.$scope.isComponentInstanceSelected()) {
+ if (this.$scope.currentComponent.selectedInstance.originType === 'VF') {
+ this.$scope.groupPropertiesByInstance = true;
+ }
+ result[this.$scope.currentComponent.selectedInstance.uniqueId] = this.$scope.currentComponent.componentInstancesProperties[this.$scope.currentComponent.selectedInstance.uniqueId];
+ } else if (this.$scope.currentComponent.isService()) {
+ // Temporally fix to hide properties for service (UI stack when there are many properties)
+ result = this.$scope.currentComponent.componentInstancesProperties;
+ this.$scope.propertiesMessage = "Note: properties for service are disabled";
+ } else {
+ let key = this.$scope.selectedComponent.uniqueId;
+ result[key] = Array<PropertyModel>();
+ let derived = Array<PropertyModel>();
+ _.forEach(this.$scope.selectedComponent.properties, (property:PropertyModel) => {
+ if (key == property.parentUniqueId) {
+ result[key].push(property);
+ } else {
+ property.readonly = true;
+ derived.push(property);
+ }
+ });
+ if (derived.length) {
+ result['derived'] = derived;
+ }
+ }
+ this.$scope.properties = result;
+ }
+ };
+
+
+ private initComponentAttributes = ():void => {
+ let result:AttributesGroup = {};
+
+ if (this.$scope.selectedComponent) {
+ if (this.$scope.isComponentInstanceSelected()) {
+ result[this.$scope.currentComponent.selectedInstance.uniqueId] = this.$scope.currentComponent.componentInstancesAttributes[this.$scope.currentComponent.selectedInstance.uniqueId];
+ } else if (this.$scope.currentComponent.isService()) {
+ result = this.$scope.currentComponent.componentInstancesAttributes;
+ }
+ this.$scope.attributes = result;
+ }
+ };
+
+ /**
+ * This function is checking if the component is the value owner of the current property
+ * in order to notify the edit property modal which fields to disable
+ */
+ private isPropertyValueOwner = ():boolean => {
+ return this.$scope.currentComponent.isService() || !!this.$scope.currentComponent.selectedInstance;
+ };
+
+ /**
+ * The function opens the edit property modal.
+ * It checks if the property is from the VF or from one of it's resource instances and sends the needed property list.
+ * For create property reasons an empty array is transferd
+ *
+ * @param property the wanted property to edit/create
+ */
+ private openEditPropertyModal = (property:PropertyModel):void => {
+ this.ModalsHandler.openEditPropertyModal(property,
+ this.$scope.component,
+ (this.$scope.isPropertyOwner() ?
+ this.$scope.properties[property.parentUniqueId] :
+ this.$scope.properties[property.resourceInstanceUniqueId]) || [],
+ this.isPropertyValueOwner()).then(() => {
+ });
+ };
+
+ private openAttributeModal = (atrribute:AttributeModel):void => {
+
+ let modalOptions:ng.ui.bootstrap.IModalSettings = {
+ template: 'app/view-models/forms/attribute-form/attribute-form-view.html',
+ controller: 'Sdc.ViewModels.AttributeFormViewModel',
+ size: 'sdc-md',
+ backdrop: 'static',
+ keyboard: false,
+ resolve: {
+ attribute: ():AttributeModel => {
+ return atrribute;
+ },
+ component: ():Component => {
+ return this.$scope.currentComponent;
+ }
+ }
+ };
+ this.$uibModal.open(modalOptions);
+ };
+
+ private getComponentInstancesPropertiesAndAttributes = () => {
+
+ this.ComponentServiceNg2.getComponentInstanceAttributesAndProperties(this.$scope.currentComponent).subscribe((genericResponse:ComponentGenericResponse) => {
+ this.$scope.currentComponent.componentInstancesAttributes = genericResponse.componentInstancesAttributes;
+ this.$scope.currentComponent.componentInstancesProperties = genericResponse.componentInstancesProperties;
+ this.initScope();
+ });
+ };
+
+ private initScope = ():void => {
+
+
+ this.initComponentProperties();
+ this.initComponentAttributes();
+
+ this.$scope.$watchCollection('currentComponent.properties', (newData:any):void => {
+ this.initComponentProperties();
+ });
+
+ this.$scope.$watch('currentComponent.selectedInstance', (newInstance:ComponentInstance):void => {
+ if (angular.isDefined(newInstance)) {
+ this.initComponentProperties();
+ this.initComponentAttributes();
+
+ }
+ });
+
+ this.$scope.isPropertyOwner = ():boolean => {
+ return this.$scope.currentComponent && this.$scope.currentComponent.isResource() && !this.$scope.isComponentInstanceSelected();
+ };
+
+ this.$scope.updateProperty = (property:PropertyModel):void => {
+ this.openEditPropertyModal(property);
+ };
+
+ this.$scope.deleteProperty = (property:PropertyModel):void => {
+
+ let onOk = ():void => {
+ this.$scope.currentComponent.deleteProperty(property.uniqueId);
+ };
+
+ let title:string = this.$filter('translate')("PROPERTY_VIEW_DELETE_MODAL_TITLE");
+ let message:string = this.$filter('translate')("PROPERTY_VIEW_DELETE_MODAL_TEXT", "{'name': '" + property.name + "'}");
+ this.ModalsHandler.openConfirmationModal(title, message, false).then(onOk);
+ };
+
+ this.$scope.viewAttribute = (attribute:AttributeModel):void => {
+ this.openAttributeModal(attribute);
+ };
+
+ this.$scope.groupNameByKey = (key:string):string => {
+ switch (key) {
+ case 'derived':
+ return "Derived";
+
+ case this.$scope.currentComponent.uniqueId:
+ return this.$filter("resourceName")(this.$scope.currentComponent.name);
+
+ default:
+ return this.$filter("resourceName")((_.find(this.$scope.currentComponent.componentInstances, {uniqueId: key})).name);
+ }
+ };
+
+ this.$scope.getComponentInstanceNameFromInstanceByKey = (key:string):string => {
+ let instanceName:string = "";
+ if (key !== undefined && this.$scope.selectedComponent.uniqueId == this.$scope.currentComponent.selectedInstance.componentUid) {
+ instanceName = this.$filter("resourceName")((_.find(this.$scope.selectedComponent.componentInstances, {uniqueId: key})).name);
+ }
+ return instanceName;
+ };
+
+ }
+}
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/composition/tabs/properties-and-attributes/properties-view.html b/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/properties-and-attributes/properties-view.html
index 3022ee6e90..6df8b6a4d6 100644
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/composition/tabs/properties-and-attributes/properties-view.html
+++ b/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/properties-and-attributes/properties-view.html
@@ -1,4 +1,5 @@
-<perfect-scrollbar class="w-sdc-designer-sidebar-tab-content properties">
+<perfect-scrollbar class="w-sdc-designer-sidebar-tab-content properties" id="main-scroll">
+
<div class="w-sdc-designer-sidebar-section">
<!--expand-collapse data-ng-if="isPropertyOwner() && !currentComponent.properties.length" expanded-selector=".w-sdc-composition-sidebar-section-content.{{currentComponent.name}}"
@@ -7,52 +8,87 @@
data-ng-bind="(currentComponent.name | resourceName)+ ' Properties'"></span>
<div class="w-sdc-composition-sidebar-section-title-icon"></div>
</expand-collapse-->
-
-
<!--properties-->
<expand-collapse data-ng-repeat-start="(key, group) in properties"
- expanded-selector=".w-sdc-designer-sidebar-section-content.properties.{{$index}}" class="w-sdc-designer-sidebar-section-title">
- <span class="w-sdc-designer-sidebar-section-title-text" data-ng-bind="groupNameByKey(key) + ' Properties'"
- tooltips tooltip-content="{{groupNameByKey(key)}}&nbsp;Properties"></span>
- <div class="w-sdc-designer-sidebar-section-title-icon"></div>
+ expanded-selector=".w-sdc-designer-sidebar-section-content.properties.{{$index}}">
+ <div class="first-level">
+ <div class="expand-collapse-title-icon"></div>
+ <span class="w-sdc-designer-sidebar-section-title-text" data-ng-bind="groupNameByKey(key) + ' Properties'"
+ tooltips tooltip-content="{{groupNameByKey(key)}}&nbsp;Properties"
+ data-tests-id="vfi-properties"></span>
+ </div>
</expand-collapse>
<div data-ng-repeat-end="" class="w-sdc-designer-sidebar-section-content properties {{$index}}"> <!--data-ng-show="isShowDetailsSection" -->
- <div class="i-sdc-designer-sidebar-section-content-item">
+ <div class="i-sdc-designer-sidebar-section-content-item" data-ng-if="!groupPropertiesByInstance">
<div class="i-sdc-designer-sidebar-section-content-item-property-and-attribute" data-tests-id="propertyRow"
data-ng-repeat="property in group | orderBy: 'name' track by $index">
<div>
<span class="i-sdc-designer-sidebar-section-content-item-property-and-attribute-label"
data-ng-class="{'hand enabled': !$parent.isViewOnly}"
tooltips tooltip-content="{{property.name}}"
- data-ng-click="!$parent.isViewOnly && updateProperty(property)">{{property.name}}</span>
+ data-ng-click="!$parent.isViewOnly && updateProperty(property)"
+ data-tests-id="{{property.name}}">{{property.name}}</span>
</div>
<div>
<span class="i-sdc-designer-sidebar-section-content-item-property-value" data-ng-if="isPropertyOwner()"
tooltips tooltip-content="{{property.defaultValue}}">{{property.defaultValue}}</span>
<span class="i-sdc-designer-sidebar-section-content-item-property-value" data-ng-if="!isPropertyOwner()"
- tooltips tooltip-content="{{property.value}}">{{property.value}}</span>
+ tooltips tooltip-content="{{property.value}}"
+ data-tests-id="value_{{property.name}}">{{property.value}}</span>
</div>
<button class="i-sdc-designer-sidebar-section-content-item-button delete sprite e-sdc-small-icon-delete"
data-ng-if="!$parent.isViewOnly&&(isPropertyOwner() && !property.readonly)"
data-ng-click="deleteProperty(property)" type="button"></button>
</div>
</div>
-
- </div>
- <div class="w-sdc-designer-sidebar-section-footer">
- <button class="w-sdc-designer-sidebar-section-footer-action tlv-btn blue" data-ng-click="addProperty()" type="button" data-ng-if="!$parent.isViewOnly && isPropertyOwner()">
- Add Property
- </button>
+ <div class="i-sdc-designer-sidebar-section-content-item" data-ng-if="groupPropertiesByInstance">
+ <div data-ng-repeat-start="(instancesIds , InstanceProperties) in (group | groupBy:'path')"
+ class="vfci-properties-group"
+ data-ng-click="showGroupsOfInstanceProperties[$index]=!showGroupsOfInstanceProperties[$index]"
+ data-ng-class="{'expanded':showGroupsOfInstanceProperties[$index]}">
+ <div class="second-level">
+ <div class="expand-collapse-title-icon"></div>
+ <span class="w-sdc-designer-sidebar-section-title-text" data-ng-bind="getComponentInstanceNameFromInstanceByKey(InstanceProperties[0].path[1]) + ' Properties'"
+ tooltips tooltip-content="{{getComponentInstanceNameFromInstanceByKey(InstanceProperties[0].path[1])}}&nbsp;Properties"
+ data-tests-id="vfci-properties"></span>
+ </div>
+ </div>
+ <div data-ng-repeat-end="" class="w-sdc-designer-sidebar-section-content instance-properties {{$index}}" data-ng-if="showGroupsOfInstanceProperties[$index]">
+ <div class="i-sdc-designer-sidebar-section-content-item">
+ <div class="i-sdc-designer-sidebar-section-content-item-property-and-attribute" data-tests-id="propertyRow"
+ data-ng-repeat="instanceProperty in InstanceProperties | orderBy: 'name'">
+ <div>
+ <span class="i-sdc-designer-sidebar-section-content-item-property-and-attribute-label"
+ data-ng-class="{'hand enabled': !$parent.isViewOnly}"
+ tooltips tooltip-content="{{instanceProperty.name}}"
+ data-tests-id="vfci-property">{{instanceProperty.name}}</span>
+ </div>
+ <div>
+ <span class="i-sdc-designer-sidebar-section-content-item-property-value"
+ tooltips tooltip-content="{{instanceProperty.value === undefined ? instanceProperty.defaultValue : instanceProperty.value}}">
+ {{instanceProperty.value === undefined ? instanceProperty.defaultValue : instanceProperty.value}}</span>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ <!--<div class="w-sdc-designer-sidebar-section-footer" data-ng-if="(!$parent.isViewOnly && isPropertyOwner()) || showAddPropertyButton">-->
+ <!--<button class="w-sdc-designer-sidebar-section-footer-action tlv-btn blue" data-tests-id="addGrey" data-ng-click="addProperty()" type="button">-->
+ <!--Add Property-->
+ <!--</button>-->
+ <!--</div>-->
</div>
<!--attributes-->
<expand-collapse data-ng-repeat-start="(key, group) in attributes"
- expanded-selector=".w-sdc-designer-sidebar-section-content.attributes.{{$index}}" class="w-sdc-designer-sidebar-section-title">
- <span class="w-sdc-designer-sidebar-section-title-text" data-ng-bind="groupNameByKey(key) + ' Attributes'"
- tooltips tooltip-content="{{groupNameByKey(key)}}&nbsp;Attributes"></span>
- <div class="w-sdc-designer-sidebar-section-title-icon"></div>
+ expanded-selector=".w-sdc-designer-sidebar-section-content.attributes.{{$index}}">
+ <div class="first-level">
+ <div class="expand-collapse-title-icon"></div>
+ <span class="w-sdc-designer-sidebar-section-title-text" data-ng-bind="groupNameByKey(key) + ' Attributes'"
+ tooltips tooltip-content="{{groupNameByKey(key)}}&nbsp;Attributes"></span>
+ </div>
</expand-collapse>
<div data-ng-repeat-end="" class="w-sdc-designer-sidebar-section-content attributes {{$index}}"> <!--data-ng-show="isShowDetailsSection" -->
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/composition/tabs/properties-and-attributes/properties.less b/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/properties-and-attributes/properties.less
index 2ad87b9fca..41a90bff9d 100644
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/composition/tabs/properties-and-attributes/properties.less
+++ b/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/properties-and-attributes/properties.less
@@ -13,4 +13,26 @@
.s_14_m;
padding: 20px 20px;
}
+
+ .vfci-properties-group{
+ background-color: @func_color_r;
+ }
+
+ .expand-collapse-title-icon{
+ .hand;
+ .sprite-new;
+ .expand-collapse-plus-icon;
+ vertical-align: middle;
+ margin: 0 6px;
+ }
+
+ .expanded {
+ .expand-collapse-title-icon {
+ .expand-collapse-minus-icon;
+ }
+ }
+
+ .w-sdc-designer-sidebar-section-title-text{
+ vertical-align: middle;
+ }
}
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
new file mode 100644
index 0000000000..325f250ebe
--- /dev/null
+++ b/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/relations/relations-view-model.ts
@@ -0,0 +1,156 @@
+'use strict';
+import {ICompositionViewModelScope} from "../../composition-view-model";
+import {CapabilitiesGroup, Requirement, RequirementsGroup} from "app/models";
+import {ComponentServiceNg2} from "app/ng2/services/component-services/component.service";
+import {ComponentGenericResponse} from "app/ng2/services/responses/component-generic-response";
+import {GRAPH_EVENTS} from "app/utils";
+import {EventListenerService} from "app/services";
+import {ComponentInstance, Capability} from "app/models";
+
+interface IRelationsViewModelScope extends ICompositionViewModelScope {
+ isLoading:boolean;
+ $parent:ICompositionViewModelScope;
+ getRelation(requirement:any):any;
+ capabilities:Array<Capability>;
+ requirements:Array<Requirement>;
+
+ //for complex components
+ capabilitiesInstancesMap:InstanceCapabilitiesMap;
+ requirementsInstancesMap:InstanceRequirementsMap;
+}
+export class InstanceCapabilitiesMap {
+ [key:string]:Array<Capability>;
+}
+
+export class InstanceRequirementsMap {
+ [key:string]:Array<Requirement>;
+}
+
+export class RelationsViewModel {
+
+ static '$inject' = [
+ '$scope',
+ '$filter',
+ 'ComponentServiceNg2',
+ 'EventListenerService'
+ ];
+
+ constructor(private $scope:IRelationsViewModelScope,
+ private $filter:ng.IFilterService,
+ private ComponentServiceNg2:ComponentServiceNg2,
+ private eventListenerService:EventListenerService) {
+ this.initScope();
+ }
+
+ private loadComplexComponentData = () => {
+ this.$scope.isLoading = true;
+ this.ComponentServiceNg2.getCapabilitiesAndRequirements(this.$scope.currentComponent.componentType, this.$scope.currentComponent.uniqueId).subscribe((response:ComponentGenericResponse) => {
+ this.$scope.currentComponent.capabilities = response.capabilities;
+ this.$scope.currentComponent.requirements = response.requirements;
+ this.setScopeCapabilitiesRequirements(this.$scope.currentComponent.capabilities, this.$scope.currentComponent.requirements);
+ this.initInstancesMap();
+ this.$scope.isLoading = false;
+ });
+ }
+
+
+ private extractValuesFromMap = (map:CapabilitiesGroup | RequirementsGroup):Array<any> => {
+ let values = [];
+ _.forEach(map, (capabilitiesOrRequirements:Array<Capability> | Array<Requirement>, key) => {
+ values = values.concat(capabilitiesOrRequirements)
+ }
+ );
+ return values;
+ }
+
+ private setScopeCapabilitiesRequirements = (capabilities:CapabilitiesGroup, requirements:RequirementsGroup) => {
+ this.$scope.capabilities = this.extractValuesFromMap(capabilities);
+ this.$scope.requirements = this.extractValuesFromMap(requirements);
+ }
+
+
+ private initInstancesMap = ():void => {
+
+ this.$scope.capabilitiesInstancesMap = new InstanceCapabilitiesMap();
+ _.forEach(this.$scope.capabilities, (capability:Capability) => {
+ if (this.$scope.capabilitiesInstancesMap[capability.ownerName]) {
+ this.$scope.capabilitiesInstancesMap[capability.ownerName] = this.$scope.capabilitiesInstancesMap[capability.ownerName].concat(capability);
+ } else {
+ this.$scope.capabilitiesInstancesMap[capability.ownerName] = new Array<Capability>(capability);
+ }
+ });
+
+ this.$scope.requirementsInstancesMap = new InstanceRequirementsMap();
+ _.forEach(this.$scope.requirements, (requirement:Requirement) => {
+ if (this.$scope.requirementsInstancesMap[requirement.ownerName]) {
+ this.$scope.requirementsInstancesMap[requirement.ownerName] = this.$scope.requirementsInstancesMap[requirement.ownerName].concat(requirement);
+ } else {
+ this.$scope.requirementsInstancesMap[requirement.ownerName] = new Array<Requirement>(requirement);
+ }
+ });
+ }
+
+ private initRequirementsAndCapabilities = (needUpdate?: boolean) => {
+
+ // if instance selected, we take the requirement and capabilities of the instance - always exist because we load them with the graph
+ if (this.$scope.isComponentInstanceSelected()) {
+ this.$scope.isLoading = false;
+ this.setScopeCapabilitiesRequirements(this.$scope.currentComponent.selectedInstance.capabilities, this.$scope.currentComponent.selectedInstance.requirements);
+ if (this.$scope.currentComponent.selectedInstance.originType === 'VF') {
+ this.initInstancesMap();
+ }
+ } else {
+ // if instance not selected, we take the requirement and capabilities of the VF/SERVICE, if not exist we call api
+ if (needUpdate || !this.$scope.currentComponent.capabilities || !this.$scope.currentComponent.requirements) {
+ this.loadComplexComponentData();
+
+ } else {
+ this.$scope.isLoading = false;
+ this.setScopeCapabilitiesRequirements(this.$scope.currentComponent.capabilities, this.$scope.currentComponent.requirements);
+ this.initInstancesMap();
+ }
+ }
+ }
+
+ private updateRequirementCapabilities = () => {
+ if (!this.$scope.isComponentInstanceSelected()) {
+ this.loadComplexComponentData();
+ }
+ }
+
+ private initEvents = ():void => {
+ this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_NODE_SELECTED, this.initRequirementsAndCapabilities);
+ this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_GRAPH_BACKGROUND_CLICKED, this.updateRequirementCapabilities);
+ this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_CREATE_COMPONENT_INSTANCE, this.updateRequirementCapabilities);
+ this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_DELETE_COMPONENT_INSTANCE, this.updateRequirementCapabilities);
+ }
+
+ private initScope = ():void => {
+
+ this.$scope.requirements = [];
+ this.$scope.capabilities = [];
+
+ this.initEvents();
+ this.initRequirementsAndCapabilities();
+
+ this.$scope.isCurrentDisplayComponentIsComplex = ():boolean => {
+ if (this.$scope.isComponentInstanceSelected()) {
+ if (this.$scope.currentComponent.selectedInstance.originType === 'VF') {
+ return true;
+ }
+ return false;
+ } else {
+ return this.$scope.currentComponent.isComplex();
+ }
+ }
+
+ this.$scope.$on('$destroy', () => {
+
+ this.eventListenerService.unRegisterObserver(GRAPH_EVENTS.ON_NODE_SELECTED, this.initRequirementsAndCapabilities);
+ this.eventListenerService.unRegisterObserver(GRAPH_EVENTS.ON_GRAPH_BACKGROUND_CLICKED, this.updateRequirementCapabilities);
+ this.eventListenerService.unRegisterObserver(GRAPH_EVENTS.ON_CREATE_COMPONENT_INSTANCE, this.updateRequirementCapabilities);
+ this.eventListenerService.unRegisterObserver(GRAPH_EVENTS.ON_DELETE_COMPONENT_INSTANCE, this.updateRequirementCapabilities);
+ });
+
+ }
+}
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/relations/relations-view.html b/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/relations/relations-view.html
new file mode 100644
index 0000000000..5ecb12cd6f
--- /dev/null
+++ b/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/relations/relations-view.html
@@ -0,0 +1,61 @@
+<perfect-scrollbar class="w-sdc-designer-sidebar-tab-content sdc-general-tab relations">
+ <div ng-if="!isCurrentDisplayComponentIsComplex()">
+ <div class="w-sdc-designer-sidebar-section w-sdc-designer-sidebar-section-relations">
+ <expand-collapse expanded-selector=".w-sdc-designer-sidebar-section-content.capabilities" class="w-sdc-designer-sidebar-section-title"> Capabilities
+ <div class="w-sdc-designer-sidebar-section-title-icon"></div>
+ </expand-collapse>
+ <div class="w-sdc-designer-sidebar-section-content capabilities">
+ <capabilities-list capabilities="capabilities"></capabilities-list>
+ </div>
+ </div>
+ <div class="w-sdc-designer-sidebar-section w-sdc-designer-sidebar-section-relations">
+ <expand-collapse expanded-selector=".w-sdc-designer-sidebar-section-content.requirements" class="w-sdc-designer-sidebar-section-title"> Requirements
+ <div class="w-sdc-designer-sidebar-section-title-icon"></div>
+ </expand-collapse>
+
+ <div class="w-sdc-designer-sidebar-section-content requirements">
+ <requirements-list component='currentComponent' requirements="requirements"></requirements-list>
+ </div>
+ </div>
+ </div>
+
+ <div ng-if="isCurrentDisplayComponentIsComplex()">
+ <div class="w-sdc-designer-sidebar-section w-sdc-designer-sidebar-section-relations">
+ <expand-collapse expanded-selector=".w-sdc-designer-sidebar-section-content.capabilities" class="w-sdc-designer-sidebar-section-title"> Capabilities
+ <div class="w-sdc-designer-sidebar-section-title-icon"></div>
+ </expand-collapse>
+ </div>
+ <div class="w-sdc-designer-sidebar-section-content capabilities">
+ <expand-collapse expanded-selector=".capabilities-component-instances.{{$index}}" is-close-on-init="true" class="general-tab-expand-collapse"
+ data-ng-repeat-start="(key, instanceCapabilities) in capabilitiesInstancesMap track by $index">
+ <div class="expand-collapse-title second-level">
+ <div class="expand-collapse-title-icon"></div>
+ <span class="expand-collapse-title-text" data-ng-bind="key"></span>
+ </div>
+ </expand-collapse>
+
+ <div data-ng-repeat-end="" class="capabilities-component-instances {{$index}}">
+ <capabilities-list capabilities="instanceCapabilities"></capabilities-list>
+ </div>
+ </div>
+
+ <div class="w-sdc-designer-sidebar-section w-sdc-designer-sidebar-section-relations">
+ <expand-collapse expanded-selector=".w-sdc-designer-sidebar-section-content.requirements" class="w-sdc-designer-sidebar-section-title"> Requirements
+ <div class="w-sdc-designer-sidebar-section-title-icon"></div>
+ </expand-collapse>
+ </div>
+ <div class="w-sdc-designer-sidebar-section-content requirements">
+ <expand-collapse expanded-selector=".requirements-component-instances.{{$index}}" is-close-on-init="true" class="general-tab-expand-collapse"
+ data-ng-repeat-start="(key, instanceRequirements) in requirementsInstancesMap track by $index">
+ <div class="expand-collapse-title second-level">
+ <div class="expand-collapse-title-icon"></div>
+ <span class="expand-collapse-title-text" data-ng-bind="key"></span>
+ </div>
+ </expand-collapse>
+
+ <div data-ng-repeat-end="" class="requirements-component-instances {{$index}}">
+ <requirements-list component='currentComponent' requirements="instanceRequirements"></requirements-list>
+ </div>
+ </div>
+ </div>
+</perfect-scrollbar>
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/relations/relations.less b/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/relations/relations.less
new file mode 100644
index 0000000000..c3b224d5a6
--- /dev/null
+++ b/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/relations/relations.less
@@ -0,0 +1,14 @@
+.w-sdc-designer-sidebar-tab-content.relations {
+
+ .w-sdc-designer-sidebar-section-content {
+ padding: 0;
+ }
+
+ .w-sdc-designer-sidebar-section-title {
+ &.expanded {
+ margin-bottom: 0;
+ }
+ }
+}
+
+
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/composition/tabs/structure/structure-view.html b/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/structure/structure-view.html
index 2070041990..2070041990 100644
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/composition/tabs/structure/structure-view.html
+++ b/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/structure/structure-view.html
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/structure/structure-view.ts b/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/structure/structure-view.ts
new file mode 100644
index 0000000000..1c28a46d37
--- /dev/null
+++ b/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/structure/structure-view.ts
@@ -0,0 +1,14 @@
+'use strict';
+import {ICompositionViewModelScope} from "../../composition-view-model";
+
+interface IStructureViewModel extends ICompositionViewModelScope {
+}
+
+export class StructureViewModel {
+ static '$inject' = [
+ '$scope'
+ ];
+
+ constructor(private $scope:IStructureViewModel) {
+ }
+}
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts-description-popover.html b/catalog-ui/src/app/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts-description-popover.html
new file mode 100644
index 0000000000..0d7d5dc8f4
--- /dev/null
+++ b/catalog-ui/src/app/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts-description-popover.html
@@ -0,0 +1,23 @@
+<!-- Description Popover -->
+<div >
+ <span data-tests-id='popover-x-button' data-ng-click='closeDescriptionPopover()' class='tlv-sprite tlv-x-btn close-popover-btn'></span>
+ <div class="w-sdc-form-item" ng-form="descriptionForm" data-ng-class="{error:(descriptionForm.$dirty && descriptionForm.$invalid)}">
+ <textarea class="i-sdc-form-textarea {{$index}}" data-ng-class="{'view-mode': isViewMode()}"
+ data-ng-maxlength="256"
+ maxlength="256"
+ data-ng-required="true"
+ name="description"
+ data-ng-model="artifact.description"
+ data-ng-model-options="{ debounce: 200 }"
+ data-ng-pattern="getValidationPattern('string')"
+ ng-readonly="isViewMode()"
+ data-tests-id="description">
+ </textarea>
+
+ <div class="input-error" data-ng-show="descriptionForm.$dirty && descriptionForm.$invalid">
+ <span ng-show="descriptionForm.$error.required" translate="ADD_ARTIFACT_ERROR_DESCRIPTION_REQUIRED"></span>
+ <span ng-show="descriptionForm.$error.maxlength" translate="VALIDATION_ERROR_MAX_LENGTH" translate-values="{'max': '256' }"></span>
+ <span ng-show="descriptionForm.$error.pattern" translate="VALIDATION_ERROR_SPECIAL_CHARS_NOT_ALLOWED"></span>
+ </div>
+ </div>
+</div>
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
new file mode 100644
index 0000000000..2816c312f9
--- /dev/null
+++ b/catalog-ui/src/app/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts-view-model.ts
@@ -0,0 +1,276 @@
+//@require "./*.html"
+'use strict';
+import {IWorkspaceViewModelScope} from "app/view-models/workspace/workspace-view-model";
+import {ArtifactModel, ArtifactGroupModel, Resource} from "app/models";
+import {ArtifactsUtils, ModalsHandler, ValidationUtils} from "app/utils";
+import {ComponentServiceNg2} from "app/ng2/services/component-services/component.service";
+import {ComponentGenericResponse} from "../../../../ng2/services/responses/component-generic-response";
+
+interface IDeploymentArtifactsViewModelScope extends IWorkspaceViewModelScope {
+ tableHeadersList:Array<any>;
+ reverse:boolean;
+ sortBy:string;
+ artifacts:Array<ArtifactModel>;
+ editForm:ng.IFormController;
+ isLoading:boolean;
+ artifactDescriptions:any;
+ selectedArtifactId:string;
+ popoverTemplate:string;
+
+ addOrUpdate(artifact:ArtifactModel):void;
+ updateSelectedArtifact():void;
+ delete(artifact:ArtifactModel):void;
+ sort(sortBy:string):void;
+ noArtifactsToShow():boolean;
+ getValidationPattern(validationType:string, parameterType?:string):RegExp;
+ validateJson(json:string):boolean;
+ resetValue(parameter:any):void;
+ viewModeOrCsarComponent():boolean;
+ isLicenseArtifact(artifact:ArtifactModel):void;
+ getEnvArtifact(heatArtifact:ArtifactModel):ArtifactModel;
+ getEnvArtifactName(artifact:ArtifactModel):string;
+ openEditEnvParametersModal(artifact:ArtifactModel):void;
+ openDescriptionPopover(artifactId:string):void;
+ closeDescriptionPopover():void;
+}
+
+export class DeploymentArtifactsViewModel {
+
+ static '$inject' = [
+ '$scope',
+ '$templateCache',
+ '$filter',
+ 'ValidationUtils',
+ 'ArtifactsUtils',
+ 'ModalsHandler',
+ 'ComponentServiceNg2'
+ ];
+
+ constructor(private $scope:IDeploymentArtifactsViewModelScope,
+ private $templateCache:ng.ITemplateCacheService,
+ private $filter:ng.IFilterService,
+ private validationUtils:ValidationUtils,
+ private artifactsUtils:ArtifactsUtils,
+ private ModalsHandler:ModalsHandler,
+ private ComponentServiceNg2: ComponentServiceNg2) {
+ this.initScope();
+ this.$scope.updateSelectedMenuItem();
+ }
+
+ private initDescriptions = ():void => {
+ this.$scope.artifactDescriptions = {};
+ _.forEach(this.$scope.component.deploymentArtifacts, (artifact:ArtifactModel):void => {
+ this.$scope.artifactDescriptions[artifact.artifactLabel] = artifact.description;
+ });
+ };
+
+ private setArtifact = (artifact:ArtifactModel):void => {
+ if (!artifact.description || !this.$scope.getValidationPattern('string').test(artifact.description)) {
+ artifact.description = this.$scope.artifactDescriptions[artifact.artifactLabel];
+ }
+ };
+
+ private initScopeArtifacts = ()=> {
+ this.$scope.artifacts = <ArtifactModel[]>_.values(this.$scope.component.deploymentArtifacts);
+ _.forEach(this.$scope.artifacts, (artifact:ArtifactModel):void => {
+ artifact.envArtifact = this.getEnvArtifact(artifact);
+ });
+ };
+
+ private initArtifacts = (loadFromServer:boolean):void => {
+ if (loadFromServer) {
+ this.$scope.isLoading = true;
+ this.ComponentServiceNg2.getComponentDeploymentArtifacts(this.$scope.component).subscribe((response:ComponentGenericResponse) => {
+ this.$scope.component.deploymentArtifacts = response.deploymentArtifacts;
+ this.initScopeArtifacts();
+ this.$scope.isLoading = false;
+ });
+ } else {
+ this.initScopeArtifacts();
+ }
+
+ };
+
+ private getEnvArtifact = (heatArtifact:ArtifactModel):ArtifactModel=> {
+ return _.find(this.$scope.artifacts, (item:ArtifactModel)=> {
+ return item.generatedFromId === heatArtifact.uniqueId;
+ });
+ };
+
+ private getCurrentArtifact = ():ArtifactModel => {
+ if (!this.$scope.selectedArtifactId) {
+ return null;
+ }
+ let artifact:ArtifactModel = this.$scope.artifacts.filter((art) => {
+ return art.uniqueId == this.$scope.selectedArtifactId;
+ })[0];
+ return artifact;
+ }
+
+ private initScope = ():void => {
+ let self = this;
+ this.$scope.isLoading = false;
+ this.$scope.selectedArtifactId = null;
+ this.initDescriptions();
+ if(this.$scope.component.deploymentArtifacts) {
+ this.initArtifacts(false);
+ } else {
+ this.initArtifacts(true);
+ }
+ this.$scope.setValidState(true);
+
+ this.$scope.tableHeadersList = [
+ {title: 'Name', property: 'artifactDisplayName'},
+ {title: 'Type', property: 'artifactType'},
+ {title: 'Deployment timeout', property: 'timeout'},
+ {title: 'Version', property: 'artifactVersion'},
+ {title: 'UUID', property: 'artifactUUID'}
+ ];
+
+ this.$templateCache.put("deployment-artifacts-description-popover.html", require('app/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts-description-popover.html'));
+ this.$scope.popoverTemplate = "deployment-artifacts-description-popover.html";
+
+ this.$scope.isLicenseArtifact = (artifact:ArtifactModel):boolean => {
+ let isLicense:boolean = false;
+ if (this.$scope.component.isResource() && (<Resource>this.$scope.component).isCsarComponent()) {
+
+ isLicense = this.artifactsUtils.isLicenseType(artifact.artifactType);
+ }
+
+ return isLicense;
+ };
+
+ this.$scope.sort = (sortBy:string):void => {
+ this.$scope.reverse = (this.$scope.sortBy === sortBy) ? !this.$scope.reverse : false;
+ this.$scope.sortBy = sortBy;
+ };
+
+ this.$scope.getValidationPattern = (validationType:string, parameterType?:string):RegExp => {
+ return this.validationUtils.getValidationPattern(validationType, parameterType);
+ };
+
+ this.$scope.validateJson = (json:string):boolean => {
+ if (!json) {
+ return true;
+ }
+ return this.validationUtils.validateJson(json);
+ };
+
+ this.$scope.viewModeOrCsarComponent = ():boolean => {
+ return this.$scope.isViewMode() || (this.$scope.component.isResource() && (<Resource>this.$scope.component).isCsarComponent());
+ };
+
+ this.$scope.addOrUpdate = (artifact:ArtifactModel):void => {
+ artifact.artifactGroupType = 'DEPLOYMENT';
+ let artifactCopy = new ArtifactModel(artifact);
+
+ let success = (response:any):void => {
+ this.$scope.artifactDescriptions[artifactCopy.artifactLabel] = artifactCopy.description;
+ this.initArtifacts(true);
+ // this.$scope.artifacts = _.values(this.$scope.component.deploymentArtifacts);
+ };
+
+ let error = (err:any):void => {
+ console.log(err);
+ this.initArtifacts(true);
+ // self.$scope.artifacts = _.values(self.$scope.component.deploymentArtifacts);
+ };
+
+ this.ModalsHandler.openArtifactModal(artifactCopy, this.$scope.component).then(success, error);
+ };
+
+ this.$scope.noArtifactsToShow = ():boolean => {
+ return !_.some(this.$scope.artifacts, 'esId');
+ };
+
+ this.$scope.resetValue = (parameter:any):void => {
+ if (!parameter.currentValue && parameter.defaultValue) {
+ parameter.currentValue = parameter.defaultValue;
+ }
+ else if ('boolean' == parameter.type) {
+ parameter.currentValue = parameter.currentValue.toUpperCase();
+ }
+ };
+
+ this.$scope.$watch('editForm.$valid', ():void => {
+ if (this.$scope.editForm) {
+ // this.$scope.setValidState(this.$scope.editForm.$valid);
+ }
+ });
+
+ this.$scope.updateSelectedArtifact = ():void => {
+ if (!this.$scope.isViewMode() && !this.$scope.isLoading) {
+ let artifact:ArtifactModel = this.getCurrentArtifact();
+ this.setArtifact(artifact); //resets artifact description to original value if invalid.
+ if (artifact && artifact.originalDescription != artifact.description) {
+ this.$scope.isLoading = true;
+ let onSuccess = (responseArtifact:ArtifactModel):void => {
+ this.$scope.artifactDescriptions[responseArtifact.artifactLabel] = responseArtifact.description;
+ // this.$scope.artifacts = _.values(this.$scope.component.deploymentArtifacts);
+ this.initArtifacts(true);
+ this.$scope.isLoading = false;
+ };
+
+ let onFailed = (error:any):void => {
+ console.log('Delete artifact returned error:', error);
+ this.$scope.isLoading = false;
+ };
+
+ this.$scope.component.addOrUpdateArtifact(artifact).then(onSuccess, onFailed);
+ }
+ }
+ };
+
+ this.$scope.delete = (artifact:ArtifactModel):void => {
+ let onOk = ():void => {
+ this.$scope.isLoading = true;
+ let onSuccess = ():void => {
+ this.$scope.isLoading = false;
+ this.initArtifacts(true);
+ //this.$scope.artifacts = _.values(this.$scope.component.deploymentArtifacts);
+ };
+
+ let onFailed = (error:any):void => {
+ this.$scope.isLoading = false;
+ console.log('Delete artifact returned error:', error);
+ };
+
+ this.$scope.component.deleteArtifact(artifact.uniqueId, artifact.artifactLabel).then(onSuccess, onFailed);
+ };
+
+ let title:string = self.$filter('translate')("ARTIFACT_VIEW_DELETE_MODAL_TITLE");
+ let message:string = self.$filter('translate')("ARTIFACT_VIEW_DELETE_MODAL_TEXT", "{'name': '" + artifact.artifactDisplayName + "'}");
+ this.ModalsHandler.openConfirmationModal(title, message, false).then(onOk);
+ };
+
+ this.$scope.getEnvArtifactName = (artifact:ArtifactModel):string => {
+ let envArtifact = this.$scope.getEnvArtifact(artifact);
+ if (envArtifact) {
+ return envArtifact.artifactDisplayName;
+ }
+ };
+
+ this.$scope.openEditEnvParametersModal = (artifact:ArtifactModel):void => {
+ this.ModalsHandler.openEditEnvParametersModal(artifact, this.$scope.component).then(()=> {
+ this.initArtifacts(true);
+ }, ()=> {
+ this.initArtifacts(true);
+ });
+ };
+
+ this.$scope.openDescriptionPopover = (artifactId:string):void => {
+ if (this.$scope.selectedArtifactId && this.$scope.selectedArtifactId != artifactId) {
+ this.$scope.updateSelectedArtifact();
+ }
+ this.$scope.selectedArtifactId = artifactId;
+
+ };
+
+ this.$scope.closeDescriptionPopover = ():void => {
+ if (this.$scope.selectedArtifactId) {
+ this.$scope.updateSelectedArtifact();
+ this.$scope.selectedArtifactId = null;
+ }
+ };
+ };
+}
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts-view.html b/catalog-ui/src/app/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts-view.html
new file mode 100644
index 0000000000..cc914b07a8
--- /dev/null
+++ b/catalog-ui/src/app/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts-view.html
@@ -0,0 +1,126 @@
+<div class="workspace-deployment-artifact">
+
+ <div data-tests-id="add-deployment-artifact-button" ng-if="!isViewMode()" data-ng-class="{'disabled': isDisableMode()}" data-tests-id="add-property-button" class="add-btn" data-ng-click="addOrUpdate({})">Add</div>
+
+ <div class="table-container-flex">
+
+ <div class="table" data-ng-class="{'view-mode': isViewMode()}">
+ <loader data-display="isLoading"></loader>
+ <div class="head flex-container">
+ <div class="table-header head-row hand flex-item" data-ng-repeat="header in tableHeadersList track by $index" data-ng-click="sort(header.property)">{{header.title}}
+ <span data-ng-if="sortBy === header.property" class="table-header-sort-arrow" data-ng-class="{'down': reverse, 'up':!reverse}"> </span>
+ </div>
+ <div class="table-no-text-header head-row flex-item"></div>
+ </div>
+
+ <form class="body" name="editForm">
+
+ <perfect-scrollbar scroll-y-margin-offset="0" include-padding="true" class="scrollbar-container">
+
+ <!-- Artifact row -->
+ <div ng-if="noArtifactsToShow()" data-ng-class="{'disabled': isDisableMode()}" class="no-row-text" translate="DEPLOYMENT_ARTIFACT_NO_ARTIFACTS_TO_DISPLAY"></div>
+ <div data-ng-repeat-start="artifact in artifacts | orderBy:sortBy:reverse track by $index"
+ class="flex-container data-row"
+ data-ng-class="{'selected': selectedArtifactId == artifact.uniqueId }"
+ data-ng-if="artifact.esId && 'HEAT_ENV' !== artifact.artifactType"
+ data-tests-id="artifact-item-{{artifact.artifactDisplayName}}">
+ <div class="table-col-general flex-item" >
+ <div class="heat-env-connect-container" ng-class="{'heat-env-connect-container-view-mode': isViewMode()}" data-ng-if="artifact.envArtifact">
+ <span class="heat-env-connect"></span>
+ </div>
+ <span data-tests-id="artifactDisplayName_{{artifact.artifactDisplayName}}" sdc-smart-tooltip class="artifact-name">{{artifact.artifactDisplayName}}</span>
+
+ <span class="sprite-new show-desc hand description-popover-icon"
+ uib-popover-template="popoverTemplate"
+ popover-class="parameter-description-popover deployment-artifact-view top"
+ popover-title="Description"
+ popover-placement="top-left"
+ popover-is-open="selectedArtifactId == artifact.uniqueId && !isLoading"
+ popover-trigger="'none'"
+ popover-append-to-body="true"
+ data-ng-click="openDescriptionPopover(artifact.uniqueId)"
+ data-tests-id="descriptionIcon_{{artifact.artifactDisplayName}}"></span>
+ </div>
+
+ <div class="table-col-general flex-item text" data-tests-id="artifactType_{{artifact.artifactDisplayName}}" tooltips tooltip-content="{{artifact.artifactType}}">
+ {{artifact.artifactType}}
+ </div>
+ <div class="table-col-general flex-item" data-tests-id="timeout_{{artifact.artifactDisplayName}}">
+ {{artifact.timeout? artifact.timeout:''}}
+ </div>
+ <div class="table-col-general flex-item" data-tests-id="artifactVersion_{{artifact.artifactDisplayName}}">
+ {{artifact.artifactVersion}}
+ </div>
+ <div class="table-col-general flex-item text" data-tests-id="artifactUUID_{{artifact.artifactDisplayName}}" tooltips tooltip-content="{{artifact.artifactUUID}}">
+ <span>{{artifact.artifactUUID}}</span>
+ </div>
+
+ <div class="table-btn-col flex-item">
+ <button class="table-edit-btn" data-tests-id="edit_{{artifact.artifactDisplayName}}"
+ data-ng-if="!isViewMode() && !artifact.isHEAT() && !artifact.isThirdParty() && !isLicenseArtifact(artifact)" data-ng-click="addOrUpdate(artifact)"></button>
+ <button class="table-delete-btn" data-tests-id="delete_{{artifact.artifactDisplayName}}"
+ data-ng-if="!isViewMode() && !artifact.isHEAT() && !artifact.isThirdParty() && !isLicenseArtifact(artifact)" data-ng-click="delete(artifact)"> </button>
+ <button class="table-download-btn" download-artifact data-tests-id="download_{{artifact.artifactDisplayName}}"
+ data-ng-if="artifact.artifactDisplayName" component="component" artifact="artifact"></button>
+ <button ng-if="!isViewMode() && artifact.isHEAT()"
+ class="sprite e-sdc-small-icon-pad edit-paramtes-button"
+ data-ng-click="openEditEnvParametersModal(artifact)" type="button"
+ data-tests-id="edit-parameters-of-{{artifact.artifactDisplayName}}"></button>
+ </div>
+ </div>
+ <div data-ng-repeat-end="" class="flex-container data-row" data-ng-if="artifact.envArtifact">
+
+ <div class="table-col-general flex-item" zzdata-ng-click="!isViewMode() && addOrUpdate(artifact.envArtifact)">
+ <span>{{artifact.envArtifact.artifactDisplayName}}</span>
+ </div>
+
+ <div class="table-col-general flex-item" data-tests-id="{{artifact.envArtifact.artifactType}}">
+ {{artifact.envArtifact.artifactType}}
+ </div>
+ <div class="table-col-general flex-item" data-tests-id="{{artifact.envArtifact.timeout}}">
+ {{artifact.envArtifact.timeout? artifact.envArtifact.timeout:''}}
+ </div>
+ <div class="table-col-general flex-item" data-tests-id="artifactEnvVersion_{{artifact.artifactDisplayName}}">
+ {{artifact.envArtifact.artifactVersion}}
+ </div>
+ <div class="table-col-general flex-item text" data-tests-id="{{artifact.envArtifact.artifactUUID}}" tooltips tooltip-content="{{artifact.envArtifact.artifactUUID}}">
+ <span>{{artifact.envArtifact.artifactUUID}}</span>
+ </div>
+
+
+ <div class="table-btn-col flex-item" >
+ <button class="table-edit-btn" data-tests-id="edit_{{artifact.artifactLabel}}env"
+ data-ng-if="!isViewMode()" data-ng-click="addOrUpdate(artifact.envArtifact)"></button>
+ <button class="table-download-btn" data-tests-id="download_env_{{artifact.artifactDisplayName}}" download-artifact
+ data-ng-if="artifact.artifactName" component="component" artifact="artifact.envArtifact"></button>
+
+ </div>
+ </div>
+
+ <!--<div class="i-sdc-designer-sidebar-section-content-item-artifact-heat-env" ng-if="artifact.heatParameters.length">-->
+ <!--<span class="enabled" data-ng-bind="getEnvArtifactName(artifact)" data-ng-click="!isViewMode() && addOrUpdate(getEnvArtifact(artifact))"></span>-->
+ <!--<download-artifact class="i-sdc-designer-sidebar-section-content-item-button download-env sprite e-sdc-small-download hand" artifact="getEnvArtifact(artifact)"-->
+ <!--component="currentComponent" instance="true"-->
+ <!--data-tests-id="download"></download-artifact>-->
+ <!--</div>-->
+
+
+
+ <!-- Add artifacts buttons -->
+ <!--<button class="add-button" data-ng-repeat="artifact in artifacts track by $index"-->
+ <!--type="button"-->
+ <!--data-ng-show="!artifact.esId"-->
+ <!--data-ng-if="!viewModeOrCsarComponent()"-->
+ <!--data-ng-class="{'disabled': isDisableMode() || component.isCsarComponent()}"-->
+ <!--data-tests-id="{{artifact.artifactDisplayName}} deployment_artifact"-->
+ <!--translate="DEPLOYMENT_ARTIFACT_BUTTON_ADD_HEAT"-->
+ <!--translate-values="{'name': '{{artifact.artifactDisplayName}}'}"-->
+ <!--data-ng-click="addOrUpdate(artifact)"></button>-->
+
+ <!-- Top add button -->
+ <button class="add-button" type="button" data-ng-if="!isViewMode()" data-ng-class="{'disabled': isDisableMode()}" translate="DEPLOYMENT_ARTIFACT_BUTTON_ADD_OTHER" data-ng-click="addOrUpdate({})"></button>
+ </perfect-scrollbar>
+ </form>
+ </div>
+ </div>
+</div>
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts.less b/catalog-ui/src/app/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts.less
index 9f90a47d5a..dd3b16447c 100644
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts.less
+++ b/catalog-ui/src/app/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts.less
@@ -11,6 +11,47 @@
margin-bottom: 10px;
}
+
+ .heat-env-connect-container{
+ background-color: white;
+ position: absolute;
+ height: 70px;
+ width:20px;
+ left: 0;
+ top:0;
+ }
+ .heat-env-connect-container-view-mode{
+ background-color: @tlv_color_t;
+ }
+ .heat-env-connect{
+ border-left: 1px #848586 solid;
+ height: 50px;
+ margin-left: 10px;
+ margin-top: 10px;
+ border-top: 1px #848586 solid;
+ border-bottom: 1px #848586 solid;
+ width: 11px;
+ float: left;
+
+ }
+
+ .artifact-name{
+ width:85%;
+ }
+
+ .table-container-flex .table .body .data-row div .heat-env-connect-container{
+ border-right: none;
+ }
+
+ .i-sdc-designer-sidebar-section-content-item-file-link::before{
+ content:"";
+ background-color: white;
+ width: 12px;
+
+ }
+
+
+
.table {
height:490px;
margin-bottom: 0;
@@ -32,12 +73,25 @@
margin-top: 27px;
+ .text{
+ overflow: hidden;
+ text-overflow: ellipsis;
+ display: inline-block;
+ white-space: nowrap;
+ }
+
.flex-item:nth-child(1) {
flex-grow: 15;
.hand;
+ padding-left: 30px;
+ position: relative;
span.table-arrow {
margin-right: 7px;
}
+ .description-popover-icon{
+ float:right;
+ margin-top:6px;
+ }
}
.flex-item:nth-child(2) {
@@ -50,7 +104,30 @@
.flex-item:nth-child(4) {
flex-grow: 3;
- padding-top: 10px;
+ }
+
+ .flex-item:nth-child(5) {
+ flex-grow: 20;
+ }
+
+ .flex-item:nth-child(6) {
+ flex-grow: 5;
+
+ &.table-btn-col {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+
+ button {
+ flex: 0 1 auto;
+ background-color: transparent;
+ border: 0;
+ margin: 0;
+ }
+ .edit-paramtes-button {
+ order: -1;
+ }
+ }
}
}
.w-sdc-form{
@@ -100,3 +177,20 @@
}
}
}
+
+.parameter-description-popover.deployment-artifact-view {
+ margin-left: -10px;
+ z-index: 1040;
+ min-width: 300px;
+ .input-error {
+ .q_12_m;
+ }
+ .error textarea{
+ border-color: @main_color_g;
+ color: @color_h;
+ outline: none;
+ }
+ .popover-content textarea {
+ width:100%;
+ }
+}
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/deployment/deployment-view-model.ts b/catalog-ui/src/app/view-models/workspace/tabs/deployment/deployment-view-model.ts
new file mode 100644
index 0000000000..c94342a51e
--- /dev/null
+++ b/catalog-ui/src/app/view-models/workspace/tabs/deployment/deployment-view-model.ts
@@ -0,0 +1,127 @@
+'use strict';
+import {IWorkspaceViewModelScope} from "app/view-models/workspace/workspace-view-model";
+import {ComponentFactory, MenuHandler, ChangeLifecycleStateHandler, ModalsHandler} from "app/utils";
+import {LeftPaletteLoaderService, CacheService, SharingService} from "app/services";
+import {Component, IAppMenu, Tab, ComponentInstance} from "app/models";
+import {GRAPH_EVENTS} from "../../../../utils/constants";
+import {ComponentGenericResponse} from "../../../../ng2/services/responses/component-generic-response";
+import {EventListenerService} from "../../../../services/event-listener-service";
+import {ComponentServiceNg2} from "../../../../ng2/services/component-services/component.service";
+
+export interface IDeploymentViewModelScope extends IWorkspaceViewModelScope {
+
+ currentComponent:Component;
+ selectedComponent:Component;
+ isLoading:boolean;
+ sharingService:SharingService;
+ sdcMenu:IAppMenu;
+ version:string;
+ isViewOnly:boolean;
+ tabs:Array<Tab>;
+ selectedTab: Tab;
+ isComponentInstanceSelected():boolean;
+ updateSelectedComponent():void
+ openUpdateModal();
+ deleteSelectedComponentInstance():void;
+ onBackgroundClick():void;
+ setSelectedInstance(componentInstance:ComponentInstance):void;
+ printScreen():void;
+
+}
+
+export class DeploymentViewModel {
+
+ static '$inject' = [
+ '$scope',
+ '$templateCache',
+ 'sdcMenu',
+ 'MenuHandler',
+ '$state',
+ 'Sdc.Services.SharingService',
+ '$filter',
+ 'Sdc.Services.CacheService',
+ 'ComponentFactory',
+ 'ChangeLifecycleStateHandler',
+ 'LeftPaletteLoaderService',
+ 'ModalsHandler',
+ 'EventListenerService',
+ 'ComponentServiceNg2'
+ ];
+
+ constructor(private $scope:IDeploymentViewModelScope,
+ private $templateCache:ng.ITemplateCacheService,
+ private sdcMenu:IAppMenu,
+ private MenuHandler:MenuHandler,
+ private $state:ng.ui.IStateService,
+ private sharingService:SharingService,
+ private $filter:ng.IFilterService,
+ private cacheService:CacheService,
+ private ComponentFactory:ComponentFactory,
+ private ChangeLifecycleStateHandler:ChangeLifecycleStateHandler,
+ private LeftPaletteLoaderService:LeftPaletteLoaderService,
+ private ModalsHandler:ModalsHandler,
+ private eventListenerService: EventListenerService,
+ private ComponentServiceNg2: ComponentServiceNg2) {
+
+ this.$scope.setValidState(true);
+ this.initScope();
+ this.initGraphData();
+ this.$scope.updateSelectedMenuItem();
+ }
+
+
+ private initComponent = ():void => {
+
+ this.$scope.currentComponent = this.$scope.component;
+ this.$scope.selectedComponent = this.$scope.currentComponent;
+ this.updateUuidMap();
+ this.$scope.isViewOnly = this.$scope.isViewMode();
+ };
+
+
+ private updateUuidMap = ():void => {
+ /**
+ * In case user press F5, the page is refreshed and this.sharingService.currentEntity will be undefined,
+ * but after loadService or loadResource this.sharingService.currentEntity will be defined.
+ * Need to update the uuidMap with the new resource or service.
+ */
+ this.sharingService.addUuidValue(this.$scope.currentComponent.uniqueId, this.$scope.currentComponent.uuid);
+ };
+
+ private initRightTabs = ()=> {
+ if (this.$scope.currentComponent.groups) {
+ this.$templateCache.put("hierarchy-view.html", require('app/view-models/tabs/hierarchy/hierarchy-view.html'));
+ let hierarchyTab = new Tab("hierarchy-view.html", 'Sdc.ViewModels.HierarchyViewModel', 'hierarchy', this.$scope.isViewMode(), this.$scope.currentComponent, 'hierarchy');
+ this.$scope.tabs.push(hierarchyTab)
+ }
+ }
+
+ private initGraphData = ():void => {
+ if(!this.$scope.component.componentInstances || !this.$scope.component.componentInstancesRelations || !this.$scope.component.groups) {
+ this.ComponentServiceNg2.getDeploymentGraphData(this.$scope.component).subscribe((response:ComponentGenericResponse) => {
+ this.$scope.component.componentInstances = response.componentInstances;
+ this.$scope.component.componentInstancesRelations = response.componentInstancesRelations;
+ this.$scope.component.groups = response.groups;
+ this.$scope.isLoading = false;
+ this.initComponent();
+ this.initRightTabs();
+ this.eventListenerService.notifyObservers(GRAPH_EVENTS.ON_DEPLOYMENT_GRAPH_DATA_LOADED);
+ this.$scope.selectedTab = this.$scope.tabs[0];
+ });
+ } else {
+ this.$scope.isLoading = false;
+ this.initRightTabs();
+ this.eventListenerService.notifyObservers(GRAPH_EVENTS.ON_DEPLOYMENT_GRAPH_DATA_LOADED);
+
+ }
+ };
+
+ private initScope = ():void => {
+ this.$scope.isLoading = true;
+ this.$scope.sharingService = this.sharingService;
+ this.$scope.sdcMenu = this.sdcMenu;
+ this.$scope.version = this.cacheService.get('version');
+ this.initComponent();
+ this.$scope.tabs = Array<Tab>();
+ }
+}
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/deployment/deployment-view.html b/catalog-ui/src/app/view-models/workspace/tabs/deployment/deployment-view.html
index 9e26656f5f..f8b5f23a25 100644
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/deployment/deployment-view.html
+++ b/catalog-ui/src/app/view-models/workspace/tabs/deployment/deployment-view.html
@@ -1,10 +1,10 @@
<div class="deployment-view">
+ <loader display="isLoading"></loader>
<div class="w-sdc-deployment-canvas" data-ng-class="{sidebaractive: displayDesignerRightSidebar}">
- <!--<module-graph data-tests-id="canvas" current-component="currentComponent" is-view-only="isViewOnly" is-loading="isLoading"></module-graph>-->
<deployment-graph component="currentComponent" is-view-only="isViewOnly"></deployment-graph>
</div>
<div class="w-sdc-deployment-right-bar">
- <sdc-tabs tabs="tabs" is-view-only="isViewOnly"></sdc-tabs>
+ <sdc-tabs tabs="tabs" is-view-only="isViewOnly" selected-tab="selectedTab"></sdc-tabs>
</div>
</div>
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/deployment/deployment.less b/catalog-ui/src/app/view-models/workspace/tabs/deployment/deployment.less
index 0439ccd0fa..4c548c7331 100644
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/deployment/deployment.less
+++ b/catalog-ui/src/app/view-models/workspace/tabs/deployment/deployment.less
@@ -1,4 +1,4 @@
-.deployment-view{
+.deployment-view {
display: inline-block;
text-align: left;
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
new file mode 100644
index 0000000000..ce2e0169bf
--- /dev/null
+++ b/catalog-ui/src/app/view-models/workspace/tabs/distribution/disribution-status-modal/disribution-status-modal-view-model.ts
@@ -0,0 +1,83 @@
+'use strict';
+import {Distribution, DistributionComponent, ExportExcel} from "app/models";
+
+interface IDistributionStatusModalViewModelScope {
+ distribution:Distribution;
+ status:string;
+ getStatusCount(distributionComponent:Array<DistributionComponent>):any;
+ getUrlName(url:string):string;
+ modalDitributionStatus:ng.ui.bootstrap.IModalServiceInstance;
+ footerButtons:Array<any>;
+ //exportExcelData:ExportExcel;
+ close():void;
+ initDataForExportExcel():ExportExcel;
+}
+
+export class DistributionStatusModalViewModel {
+
+ static '$inject' = ['$scope', '$uibModalInstance', 'data', '$filter'];
+
+ constructor(private $scope:IDistributionStatusModalViewModelScope,
+ private $uibModalInstance:ng.ui.bootstrap.IModalServiceInstance,
+ private data:any,
+ private $filter:ng.IFilterService) {
+ this.initScope();
+ }
+
+ private generateMetaDataForExportExcel = ():Array<string>=> {
+ let metaData = [];
+ metaData[0] = 'Name:' + this.data.component.name + '| UUID:' + this.data.component.uuid + '| Invariant UUID:' + this.data.component.invariantUUID;
+ metaData[1] = 'Distribution ID:' + this.$scope.distribution.distributionID +
+ '| USER ID:' + this.$scope.distribution.userId +
+ '| Time[UTC]:' + this.$filter('date')(this.$scope.distribution.timestamp, 'MM/dd/yyyy h:mma', 'UTC') +
+ '| Status:' + this.$scope.distribution.deployementStatus;
+ return metaData;
+ };
+
+ private generateDataObjectForExportExcel = ():any=> {
+ let correctFormatDataObj = [];
+ _.each(this.$scope.distribution.distributionComponents, (dComponent:DistributionComponent) => {
+ if (dComponent.status == this.$scope.status) {
+ correctFormatDataObj.push({
+ 'omfComponentID': dComponent.omfComponentID,
+ 'artiFactName': this.$scope.getUrlName(dComponent.url),
+ 'url': dComponent.url,
+ 'timestamp': this.$filter('date')(dComponent.timestamp, 'MM/dd/yyyy h:mma', 'UTC'),
+ 'status': dComponent.status
+ });
+ }
+ });
+ return correctFormatDataObj;
+ };
+
+ private initScope = ():void => {
+ this.$scope.distribution = this.data.distribution;
+ this.$scope.status = this.data.status;
+ this.$scope.modalDitributionStatus = this.$uibModalInstance;
+
+
+ this.$scope.getUrlName = (url:string):string => {
+ let urlName:string = _.last(url.split('/'));
+ return urlName;
+ };
+
+ this.$scope.initDataForExportExcel = ():ExportExcel => {
+ let exportExcelData = new ExportExcel();
+ exportExcelData.fileName = this.$scope.status;
+ exportExcelData.groupByField = "omfComponentID";
+ exportExcelData.tableHeaders = ["Component ID", "Artifact Name", "URL", "Time(UTC)", "Status"];
+ exportExcelData.metaData = this.generateMetaDataForExportExcel();
+ exportExcelData.dataObj = this.generateDataObjectForExportExcel();
+ return exportExcelData;
+ };
+
+ this.$scope.close = ():void => {
+ this.$uibModalInstance.close();
+ };
+
+ this.$scope.footerButtons = [
+ {'name': 'Close', 'css': 'blue', 'callback': this.$scope.close}
+ ];
+
+ };
+}
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/distribution/disribution-status-modal/disribution-status-modal-view.html b/catalog-ui/src/app/view-models/workspace/tabs/distribution/disribution-status-modal/disribution-status-modal-view.html
index b3393e99e0..3367193fc7 100644
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/distribution/disribution-status-modal/disribution-status-modal-view.html
+++ b/catalog-ui/src/app/view-models/workspace/tabs/distribution/disribution-status-modal/disribution-status-modal-view.html
@@ -5,6 +5,10 @@
</div>
+ <div class="actions-buttons">
+ <json-export-excel init-export-excel-data="initDataForExportExcel()">
+ </json-export-excel>
+ </div>
<perfect-scrollbar include-padding="true" class="w-sdc-distribution-view-content">
<div class="w-sdc-distribution-view-content-section w-sdc-distribute-parent-block">
@@ -34,7 +38,7 @@
</div>
<div class="w-sdc-distribute-status-block" data-ng-show="distribution.statusCount">
<div class="status-item-1">Status: {{status}} <span data-ng-bind="(distribution.distributionComponents | filter:status:true).length"
- class="blue-font"></span></div>
+ class="blue-font"></span></div>
</div>
</div>
@@ -48,7 +52,7 @@
<div class="w-sdc-distribution-arrow-btn" data-ng-click="omfComponentListExtends=!omfComponentListExtends"
ng-class="{'extends': omfComponentListExtends}"
data-ng-init="omfComponentListExtends=false"
- ></div>
+ ></div>
<div class="w-sdc-distribute-status-block">
<div class="status-item-1">{{omfComponentID}} <span class="blue-font">{{omfComponentList.length}}</span>
</div>
@@ -73,7 +77,7 @@
<div class="w-sdc-distribution-arrow-btn" data-ng-click="urlListExtends=!urlListExtends"
data-ng-class="{'extends': urlListExtends}"
data-ng-init="urlListListExtends=false"
- ></div>
+ ></div>
{{urlList[0].omfComponentID}}
</div>
<div class="w-sdc-distribute-cell item-2" sdc-smart-tooltip>
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/distribution/disribution-status-modal/disribution-status-modal.less b/catalog-ui/src/app/view-models/workspace/tabs/distribution/disribution-status-modal/disribution-status-modal.less
index 02321b6e2f..d167083a2b 100644
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/distribution/disribution-status-modal/disribution-status-modal.less
+++ b/catalog-ui/src/app/view-models/workspace/tabs/distribution/disribution-status-modal/disribution-status-modal.less
@@ -1,9 +1,16 @@
.w-sdc-classic-top-line-modal {
.w-sdc-modal-head {
- // border-bottom: none;
+ // border-bottom: none;
}
.w-sdc-distribution-view {
+ .actions-buttons {
+ height: 29px;
+ padding: 0 25px 0 0px;
+ span{
+ float: right;
+ }
+ }
.w-sdc-distribution-view-content {
height: 500px;
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
new file mode 100644
index 0000000000..002b16f63f
--- /dev/null
+++ b/catalog-ui/src/app/view-models/workspace/tabs/distribution/distribution-view-model.ts
@@ -0,0 +1,111 @@
+'use strict';
+import {Distribution, DistributionComponent, Service} from "app/models";
+import {ModalsHandler, Dictionary} from "app/utils";
+import {IWorkspaceViewModelScope} from "app/view-models/workspace/workspace-view-model";
+
+interface IDistributionViewModel extends IWorkspaceViewModelScope {
+ modalDistribution:ng.ui.bootstrap.IModalServiceInstance;
+ service:Service;
+ distributions:Array<Distribution>;
+ showComponents(distribution:Distribution):void;
+ markAsDeployed(distribution:Distribution):void;
+ getStatusCount(distributionComponent:Array<DistributionComponent>):any;
+ initDistributions():void;
+ getUrlName(url:string):string;
+ close():void;
+ openDisributionStatusModal:Function;
+}
+
+export class DistributionViewModel {
+
+ static '$inject' = [
+ '$scope',
+ 'ModalsHandler'
+
+ ];
+
+ constructor(private $scope:IDistributionViewModel,
+ private ModalsHandler:ModalsHandler) {
+ this.initScope();
+ this.$scope.setValidState(true);
+ this.$scope.updateSelectedMenuItem();
+ }
+
+ private initScope = ():void => {
+ this.$scope.service = <Service>this.$scope.component;
+
+
+ // Open Distribution status modal
+ this.$scope.openDisributionStatusModal = (distribution:Distribution, status:string):void => {
+ this.ModalsHandler.openDistributionStatusModal(distribution, status, this.$scope.component).then(()=> {
+ // OK
+ }, ()=> {
+ // ERROR
+ });
+ };
+
+
+ this.$scope.showComponents = (distribution:Distribution):void => {
+ let onError = (response) => {
+ console.info('onError showComponents', response);
+ };
+ let onSuccess = (distributionComponents:Array<DistributionComponent>) => {
+ distribution.distributionComponents = distributionComponents;
+ distribution.statusCount = this.$scope.getStatusCount(distribution.distributionComponents);
+ // distribution.components = this.aggregateDistributionComponent(distributionComponents);;
+ };
+ this.$scope.service.getDistributionsComponent(distribution.distributionID).then(onSuccess, onError);
+ };
+
+ this.$scope.getStatusCount = (distributionComponent:Array<DistributionComponent>):any => {
+ return _.countBy(distributionComponent, 'status')
+ };
+
+ this.$scope.getUrlName = (url:string):string => {
+ let urlName:string = _.last(url.split('/'));
+ return urlName;
+ };
+
+ this.$scope.markAsDeployed = (distribution:Distribution):void => {
+ let onError = (response) => {
+ console.info('onError markAsDeployed', response);
+ };
+ let onSuccess = (result:any) => {
+ distribution.deployementStatus = 'Deployed';
+ };
+ this.$scope.service.markAsDeployed(distribution.distributionID).then(onSuccess, onError);
+
+ };
+
+ this.$scope.initDistributions = ():void => {
+ let onError = (response) => {
+ console.info('onError initDistributions', response);
+ };
+ let onSuccess = (distributions:Array<Distribution>) => {
+ this.$scope.distributions = distributions;
+ };
+ this.$scope.service.getDistributionsList().then(onSuccess, onError);
+ };
+
+ this.$scope.initDistributions();
+
+ };
+
+
+ private aggregateDistributionComponent = (distributionComponents:Array<DistributionComponent>):any => {
+ let aggregateDistributions:Dictionary<string,Dictionary<string,Array<DistributionComponent>>> = new Dictionary<string,Dictionary<string,Array<DistributionComponent>>>();
+ let tempAggregateDistributions:any = _.groupBy(distributionComponents, 'omfComponentID');
+ let aa = new Dictionary<string,Array<DistributionComponent>>();
+
+ let tempAggregate:any;
+ _.forEach(tempAggregateDistributions, (distributionComponents:Array<DistributionComponent>, omfComponentID:string)=> {
+
+ let urls:any = _.groupBy(distributionComponents, 'url');
+ aggregateDistributions.setValue(omfComponentID, urls);
+ // aggregateDistributions[omfComponentID] = ;
+
+ });
+ console.log(aggregateDistributions);
+ return aggregateDistributions;
+ };
+}
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/distribution/distribution-view.html b/catalog-ui/src/app/view-models/workspace/tabs/distribution/distribution-view.html
index 1ab0f1e111..710336af15 100644
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/distribution/distribution-view.html
+++ b/catalog-ui/src/app/view-models/workspace/tabs/distribution/distribution-view.html
@@ -54,29 +54,34 @@
data-ng-click="(item.deployementStatus==='Deployed') || markAsDeployed(item)"></div>
</div>
</div>
- <div class="w-sdc-distribute-status-block" data-ng-show="item.statusCount">
+ <div class="w-sdc-distribute-status-block" data-ng-if="item.statusCount">
<div class="status-item-1">Total Artifacts:<span data-ng-bind="(item.statusCount.NOT_NOTIFIED || 0) + (item.statusCount.NOTIFIED || 0) "
class="blue-font" data-tests-id="totalArtifacts_{{$index}}"></span></div>
<div class="status-item-2 " ><sapn class="link" data-ng-click="openDisributionStatusModal(item,'NOTIFIED')">Notified:</sapn><span
data-ng-bind="item.statusCount.NOTIFIED || 0" class="blue-font" data-tests-id="notified_{{$index}}"></span></div>
+
<div class="status-item-3 link" ><sapn class="link" data-ng-click="openDisributionStatusModal(item,'DOWNLOAD_OK')">Downloaded:</sapn><span
data-ng-bind="item.statusCount.DOWNLOAD_OK || 0" class="blue-font" data-tests-id="downloaded_{{$index}}"></span></div>
+
<div class="status-item-4 link"><sapn class="link" data-ng-click="openDisributionStatusModal(item,'DEPLOY_OK')">Deployed:</sapn><span
data-ng-bind="item.statusCount.DEPLOY_OK || 0" class="blue-font" data-tests-id="deployed_{{$index}}" ></span><span
data-ng-class="{'deployed':(item.statusCount.DEPLOY_OK > 0)}"></span></div>
<div class="status-item-5 link" ><sapn class="link" data-ng-click="openDisributionStatusModal(item,'NOT_NOTIFIED')">Not Notified:</sapn><span
data-ng-bind="item.statusCount.NOT_NOTIFIED || 0" class="blue-font" data-tests-id="NotNotified_{{$index}}"></span></div>
- <div class="status-item-6"><sapn class="link" data-ng-click="openDisributionStatusModal(item,'DOWNLOAD_ERROR')" >Errors:</sapn><span
+ <div class="status-item-6"><sapn class="link" data-ng-click="openDisributionStatusModal(item,'DEPLOY_ERROR')" >Deploy Errors:</sapn><span
+ data-ng-bind="item.statusCount.DEPLOY_ERROR || 0" class="red-font "></span><span
+ data-ng-class="{'error':(item.statusCount.DEPLOY_ERROR > 0)}" data-tests-id="errors_{{$index}}"></span></div>
+ <div class="status-item-7"><sapn class="link" data-ng-click="openDisributionStatusModal(item,'DOWNLOAD_ERROR')" >Download Errors:</sapn><span
data-ng-bind="item.statusCount.DOWNLOAD_ERROR || 0" class="red-font "></span><span
data-ng-class="{'error':(item.statusCount.DOWNLOAD_ERROR > 0)}" data-tests-id="errors_{{$index}}"></span></div>
</div>
</div>
</div>
- <ul data-ng-show="item.showDetails && item.distributionComponents.length"
+ <ul data-ng-if="item.showDetails && item.distributionComponents.length"
class="w-sdc-distribute-components-block disable-hover">
- <li data-ng-repeat="(omfComponentID,omfComponentList) in item.distributionComponents | orderBy: '-timestamp' | filter:searchBind | groupBy:'omfComponentID' "
+ <li data-ng-repeat="(omfComponentID,omfComponentList) in ::item.distributionComponents | orderBy: '-timestamp' | filter:searchBind | groupBy:'omfComponentID' "
class="disable-hover"
data-ng-init="statusCount = getStatusCount(omfComponentList);">
<div class="w-sdc-distribute-row omf-component-row w-sdc-distribute-row-extends"
@@ -97,12 +102,15 @@
data-ng-class="{'deployed':(statusCount.DEPLOY_OK > 0)}"></span></div>
<div class="status-item-5">Not Notified:<span
data-ng-bind="statusCount.NOT_NOTIFIED || 0" class="blue-font"></span></div>
- <div class="status-item-6">Errors:<span
+ <div class="status-item-6">Deploy Errors:<span
+ data-ng-bind="statusCount.DEPLOY_ERROR || 0" class="red-font"></span><span
+ data-ng-class="{'error':(statusCount.DEPLOY_ERROR > 0)}"></span></div>
+ <div class="status-item-7">Download Errors:<span
data-ng-bind="statusCount.DOWNLOAD_ERROR || 0" class="red-font"></span><span
data-ng-class="{'error':(statusCount.DOWNLOAD_ERROR > 0)}"></span></div>
</div>
</div>
- <div data-ng-show="omfComponentListExtends"
+ <div data-ng-if="omfComponentListExtends"
class="w-sdc-distribute-omfComponent-block disable-hover">
<div class="w-sdc-distribute-row-extends disable-hover">
<div class="disable-hover">
@@ -115,17 +123,17 @@
</div>
<div class="w-sdc-distribute-row omfComponent-table-row"
- data-ng-repeat-start="(url,urlList) in omfComponentList | orderBy: '-timestamp' | groupBy:'url'"
+ data-ng-repeat-start="(url,urlList) in ::omfComponentList | orderBy: '-timestamp' | groupBy:'url'"
data-ng-class="urlListExtends?'extends row-{{$index}}':'row-{{$index}}'">
- <div class="w-sdc-distribute-cell item-1">
+ <div class="w-sdc-distribute-cell item-1" sdc-smart-tooltip>
<div class="w-sdc-distribution-arrow-btn" data-ng-click="urlListExtends=!urlListExtends"
data-ng-class="{'extends': urlListExtends}"
- data-ng-init="urlListListExtends=false"
+ data-ng-init="urlListListExtends=false;urlList[0].displayUrl=getUrlName(urlList[0].url)"
></div>
{{urlList[0].omfComponentID}}
</div>
<div class="w-sdc-distribute-cell item-2" sdc-smart-tooltip>
- {{getUrlName(urlList[0].url)}}
+ {{urlList[0].displayUrl}}
</div>
<div class="w-sdc-distribute-cell item-3 disable-hover">
<div sdc-smart-tooltip class="distribution-url">{{urlList[0].url}}</div>
@@ -135,15 +143,17 @@
<div class="w-sdc-distribute-cell item-4"><span
data-ng-bind="urlList[0].timestamp | date: 'MM/dd/yyyy h:mma':'UTC'"></span>
</div>
- <div class="w-sdc-distribute-cell item-5">{{urlList[0].status}}</div>
+ <div class="w-sdc-distribute-cell item-5" sdc-smart-tooltip>
+ {{urlList[0].status}}
+ </div>
</div>
- <div data-ng-repeat-end data-ng-show="urlListExtends" class="disable-hover" >
+ <div data-ng-repeat-end data-ng-if="urlListExtends" class="disable-hover" >
<div class="w-sdc-distribute-row extends disable-hover">
- <ul data-ng-show="urlListExtends"
+ <ul data-ng-if="urlListExtends"
class="w-sdc-distribute-url-block disable-hover">
- <li data-ng-repeat="distributionComponent in urlList | orderBy: '-timestamp'"
+ <li data-ng-repeat="distributionComponent in ::urlList | orderBy: '-timestamp'"
class="disable-hover">
<span
data-ng-bind="distributionComponent.timestamp | date: 'MM/dd/yyyy h:mma':'UTC'"
@@ -151,9 +161,9 @@
<span
class="disable-hover">{{distributionComponent.status}}</span>
<span
- class="disable-hover reason" data-ng-show="distributionComponent.status == 'NOT_NOTIFIED'">Reason: Component has determined artifact is not needed.</span>
+ class="disable-hover reason" data-ng-if="distributionComponent.status == 'NOT_NOTIFIED'">Reason: Component has determined artifact is not needed.</span>
<span
- class="disable-hover reason" data-ng-show="distributionComponent.errorReason">Reason: {{distributionComponent.errorReason}}</span>
+ class="disable-hover reason" data-ng-if="distributionComponent.errorReason">Reason: {{distributionComponent.errorReason}}</span>
</li>
</ul>
</div>
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/distribution/distribution.less b/catalog-ui/src/app/view-models/workspace/tabs/distribution/distribution.less
index 8ad8c1793e..ee1f7ed2d6 100644
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/distribution/distribution.less
+++ b/catalog-ui/src/app/view-models/workspace/tabs/distribution/distribution.less
@@ -147,6 +147,7 @@
.sprite-new;
.arrow-up-small;
margin: 0 6px;
+ display: inline-table;
}
.extends.w-sdc-distribution-arrow-btn {
-webkit-transform: rotate(180deg);
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
new file mode 100644
index 0000000000..44953985fc
--- /dev/null
+++ b/catalog-ui/src/app/view-models/workspace/tabs/general/general-view-model.ts
@@ -0,0 +1,349 @@
+'use strict';
+import {ModalsHandler, ValidationUtils, EVENTS, CHANGE_COMPONENT_CSAR_VERSION_FLAG, ComponentType, DEFAULT_ICON,
+ ResourceType} from "app/utils";
+import {CacheService, EventListenerService, ProgressService} from "app/services";
+import {IAppConfigurtaion, Product, IValidate, IMainCategory, Resource, ISubCategory,Service} from "app/models";
+import {IWorkspaceViewModelScope} from "app/view-models/workspace/workspace-view-model";
+
+export class Validation {
+ componentNameValidationPattern:RegExp;
+ contactIdValidationPattern:RegExp;
+ tagValidationPattern:RegExp;
+ vendorValidationPattern:RegExp;
+ commentValidationPattern:RegExp;
+ projectCodeValidationPattern:RegExp;
+}
+
+export class componentCategories {//categories field bind to this obj in order to solve this bug: DE242059
+ selectedCategory:string;
+}
+
+export interface IGeneralScope extends IWorkspaceViewModelScope {
+ validation:Validation;
+ editForm:ng.IFormController;
+ categories:Array<IMainCategory>;
+ latestCategoryId:string;
+ latestVendorName:string;
+ importedFileExtension:any;
+ isCreate:boolean;
+ isShowFileBrowse:boolean;
+ isShowOnboardingSelectionBrowse:boolean;
+ importedToscaBrowseFileText:string;
+ importCsarProgressKey:string;
+ browseFileLabel:string;
+ componentCategories:componentCategories;
+
+ onToscaFileChange():void
+ validateField(field:any):boolean;
+ validateName(isInit:boolean):void;
+ calculateUnique(mainCategory:string, subCategory:string):string; // Build unique string from main and sub category
+ onVendorNameChange(oldVendorName:string):void;
+ convertCategoryStringToOneArray(category:string, subcategory:string):Array<IMainCategory>;
+ onCategoryChange():void;
+ onEcompGeneratedNamingChange():void;
+ openOnBoardingModal():void;
+ initCategoreis():void;
+}
+
+export class GeneralViewModel {
+
+ static '$inject' = [
+ '$scope',
+ 'Sdc.Services.CacheService',
+ 'ComponentNameValidationPattern',
+ 'ContactIdValidationPattern',
+ 'TagValidationPattern',
+ 'VendorValidationPattern',
+ 'CommentValidationPattern',
+ 'ValidationUtils',
+ 'sdcConfig',
+ 'ProjectCodeValidationPattern',
+ '$state',
+ 'ModalsHandler',
+ 'EventListenerService',
+ 'Notification',
+ 'Sdc.Services.ProgressService',
+ '$interval',
+ '$filter',
+ '$timeout'
+ ];
+
+ constructor(private $scope:IGeneralScope,
+ private cacheService:CacheService,
+ private ComponentNameValidationPattern:RegExp,
+ private ContactIdValidationPattern:RegExp,
+ private TagValidationPattern:RegExp,
+ private VendorValidationPattern:RegExp,
+ private CommentValidationPattern:RegExp,
+ private ValidationUtils:ValidationUtils,
+ private sdcConfig:IAppConfigurtaion,
+ private ProjectCodeValidationPattern:RegExp,
+ private $state:ng.ui.IStateService,
+ private ModalsHandler:ModalsHandler,
+ private EventListenerService:EventListenerService,
+ private Notification:any,
+ private progressService:ProgressService,
+ protected $interval:any,
+ private $filter:ng.IFilterService,
+ private $timeout:ng.ITimeoutService) {
+
+ this.initScopeValidation();
+ this.initScopeMethods();
+ this.initScope();
+ this.$scope.updateSelectedMenuItem();
+ }
+
+
+
+
+ private initScopeValidation = ():void => {
+ this.$scope.validation = new Validation();
+ this.$scope.validation.componentNameValidationPattern = this.ComponentNameValidationPattern;
+ this.$scope.validation.contactIdValidationPattern = this.ContactIdValidationPattern;
+ this.$scope.validation.tagValidationPattern = this.TagValidationPattern;
+ this.$scope.validation.vendorValidationPattern = this.VendorValidationPattern;
+ this.$scope.validation.commentValidationPattern = this.CommentValidationPattern;
+ this.$scope.validation.projectCodeValidationPattern = this.ProjectCodeValidationPattern;
+ };
+
+ private initScope = ():void => {
+
+ // Work around to change the csar version
+ if (this.cacheService.get(CHANGE_COMPONENT_CSAR_VERSION_FLAG)) {
+ (<Resource>this.$scope.component).csarVersion = this.cacheService.get(CHANGE_COMPONENT_CSAR_VERSION_FLAG);
+ }
+
+ this.$scope.importedToscaBrowseFileText = this.$scope.component.name + " (" + (<Resource>this.$scope.component).csarVersion + ")";
+ this.$scope.importCsarProgressKey = "importCsarProgressKey";
+ this.$scope.browseFileLabel = this.$scope.component.isResource() && (<Resource>this.$scope.component).resourceType === ResourceType.VF ? "Upload file" : "Upload VFC";
+ this.$scope.progressService = this.progressService;
+ this.$scope.componentCategories = new componentCategories();
+ this.$scope.componentCategories.selectedCategory = this.$scope.component.selectedCategory;
+
+ // Workaround to short vendor name to 25 chars
+ // Amdocs send 27 chars, and the validation pattern is 25 chars.
+ if (this.$scope.component.vendorName) {
+ this.$scope.component.vendorName = this.$scope.component.vendorName.substr(0, 25);
+ }
+
+ // Init UIModel
+ this.$scope.component.tags = _.without(this.$scope.component.tags, this.$scope.component.name);
+
+ // Init categories
+ this.$scope.initCategoreis();
+
+ // Init the decision if to show file browse.
+ this.$scope.isShowFileBrowse = false;
+ if (this.$scope.component.isResource()) {
+ let resource:Resource = <Resource>this.$scope.component;
+ console.log(resource.name + ": " + resource.csarUUID);
+ if (resource.importedFile) { // Component has imported file.
+ this.$scope.isShowFileBrowse = true;
+ }
+ if (this.$scope.isEditMode() && resource.resourceType == ResourceType.VF && !resource.csarUUID) {
+ this.$scope.isShowFileBrowse = true;
+ }
+ }
+ ;
+
+ // Init the decision if to show onboarding
+ this.$scope.isShowOnboardingSelectionBrowse = false;
+ if (this.$scope.component.isResource() &&
+ this.$scope.isEditMode() &&
+ (<Resource>this.$scope.component).resourceType == ResourceType.VF &&
+ (<Resource>this.$scope.component).csarUUID) {
+ this.$scope.isShowOnboardingSelectionBrowse = true;
+ }
+
+ //init file extensions based on the file that was imported.
+ if (this.$scope.component.isResource() && (<Resource>this.$scope.component).importedFile) {
+ let fileName:string = (<Resource>this.$scope.component).importedFile.filename;
+ let fileExtension:string = fileName.split(".").pop();
+ if (this.sdcConfig.csarFileExtension.indexOf(fileExtension.toLowerCase()) !== -1) {
+ this.$scope.importedFileExtension = this.sdcConfig.csarFileExtension;
+ (<Resource>this.$scope.component).importedFile.filetype = "csar";
+ } else if (this.sdcConfig.toscaFileExtension.indexOf(fileExtension.toLowerCase()) !== -1) {
+ (<Resource>this.$scope.component).importedFile.filetype = "yaml";
+ this.$scope.importedFileExtension = this.sdcConfig.toscaFileExtension;
+ }
+ } else if (this.$scope.isEditMode() && (<Resource>this.$scope.component).resourceType === ResourceType.VF) {
+ this.$scope.importedFileExtension = this.sdcConfig.csarFileExtension;
+ //(<Resource>this.$scope.component).importedFile.filetype="csar";
+ }
+
+ this.$scope.setValidState(true);
+
+ this.$scope.calculateUnique = (mainCategory:string, subCategory:string):string => {
+ let uniqueId:string = mainCategory;
+ if (subCategory) {
+ uniqueId += "_#_" + subCategory; // Set the select category combobox to show the selected category.
+ }
+ return uniqueId;
+ };
+
+ //TODO remove this after handling contact in UI
+ if (this.$scope.component.isProduct() && this.$scope.isCreateMode()) {
+ (<Product>this.$scope.component).contacts = [];
+ (<Product>this.$scope.component).contacts.push(this.cacheService.get("user").userId);
+ } else if (this.$scope.isCreateMode()) {
+ this.$scope.component.contactId = this.cacheService.get("user").userId;
+ }
+
+ };
+
+ // Convert category string MainCategory_#_SubCategory to Array with one item (like the server except)
+ private convertCategoryStringToOneArray = ():Array<IMainCategory> => {
+ let tmp = this.$scope.component.selectedCategory.split("_#_");
+ let mainCategory = tmp[0];
+ let subCategory = tmp[1];
+
+ // Find the selected category and add the relevant sub category.
+ let selectedMainCategory:IMainCategory = <IMainCategory>_.find(this.$scope.categories, function (item) {
+ return item["name"] === mainCategory;
+
+ });
+
+ let mainCategoryClone = angular.copy(selectedMainCategory);
+ if (subCategory) {
+ let selectedSubcategory = <ISubCategory>_.find(selectedMainCategory.subcategories, function (item) {
+ return item["name"] === subCategory;
+ });
+ mainCategoryClone['subcategories'] = [angular.copy(selectedSubcategory)];
+ }
+ let tmpSelected = <IMainCategory> mainCategoryClone;
+
+ let result:Array<IMainCategory> = [];
+ result.push(tmpSelected);
+
+ return result;
+ };
+
+ private updateComponentNameInBreadcrumbs = ():void => {
+ //update breadcrum after changing name
+ this.$scope.breadcrumbsModel[1].updateSelectedMenuItemText(this.$scope.component.getComponentSubType() + ': ' + this.$scope.component.name);
+ this.$scope.updateMenuComponentName(this.$scope.component.name);
+ };
+
+ private initScopeMethods = ():void => {
+
+ this.$scope.initCategoreis = ():void => {
+ if (this.$scope.componentType === ComponentType.RESOURCE) {
+ this.$scope.categories = this.cacheService.get('resourceCategories');
+
+ }
+ if (this.$scope.componentType === ComponentType.SERVICE) {
+ this.$scope.categories = this.cacheService.get('serviceCategories');
+ }
+ };
+
+ this.$scope.validateField = (field:any):boolean => {
+ if (field && field.$dirty && field.$invalid) {
+ return true;
+ }
+ return false;
+ };
+
+ this.$scope.openOnBoardingModal = ():void => {
+ let csarUUID = (<Resource>this.$scope.component).csarUUID;
+ this.ModalsHandler.openOnboadrdingModal('Update', csarUUID).then(()=> {
+ // OK
+ this.$scope.uploadFileChangedInGeneralTab();
+ }, ()=> {
+ // ERROR
+ });
+ };
+
+ this.$scope.validateName = (isInit:boolean):void => {
+ if (isInit === undefined) {
+ isInit = false;
+ }
+
+ let name = this.$scope.component.name;
+ if (!name || name === "") {
+ if (this.$scope.editForm
+ && this.$scope.editForm["componentName"]
+ && this.$scope.editForm["componentName"].$error) {
+
+ // Clear the error name already exists
+ this.$scope.editForm["componentName"].$setValidity('nameExist', true);
+ }
+
+ return;
+ }
+ //?????????????????????????
+ let subtype:string = ComponentType.RESOURCE == this.$scope.componentType ? this.$scope.component.getComponentSubType() : undefined;
+
+ let onFailed = (response) => {
+ //console.info('onFaild', response);
+ //this.$scope.isLoading = false;
+ };
+
+ let onSuccess = (validation:IValidate) => {
+ this.$scope.editForm["componentName"].$setValidity('nameExist', validation.isValid);
+ if (validation.isValid) {
+ //update breadcrumb after changing name
+ this.updateComponentNameInBreadcrumbs();
+ }
+ };
+
+ if (isInit) {
+ // When page is init after update
+ if (this.$scope.component.name !== this.$scope.originComponent.name) {
+ if (!(this.$scope.componentType === ComponentType.RESOURCE && (<Resource>this.$scope.component).csarUUID !== undefined)
+ ) {
+ this.$scope.component.validateName(name, subtype).then(onSuccess, onFailed);
+ }
+ }
+ } else {
+ // Validating on change (has debounce)
+ if (this.$scope.editForm
+ && this.$scope.editForm["componentName"]
+ && this.$scope.editForm["componentName"].$error
+ && !this.$scope.editForm["componentName"].$error.pattern
+ && (!this.$scope.originComponent.name || this.$scope.component.name.toUpperCase() !== this.$scope.originComponent.name.toUpperCase())
+ ) {
+ if (!(this.$scope.componentType === ComponentType.RESOURCE && (<Resource>this.$scope.component).csarUUID !== undefined)
+ ) {
+ this.$scope.component.validateName(name, subtype).then(onSuccess, onFailed);
+ }
+ } else if (this.$scope.originComponent.name && this.$scope.component.name.toUpperCase() === this.$scope.originComponent.name.toUpperCase()) {
+ // Clear the error
+ this.$scope.editForm["componentName"].$setValidity('nameExist', true);
+ }
+ }
+ };
+
+ this.$scope.$watchCollection('component.name', (newData:any):void => {
+ this.$scope.validateName(false);
+ });
+
+ // Notify the parent if this step valid or not.
+ this.$scope.$watch("editForm.$valid", (newVal, oldVal) => {
+ this.$scope.setValidState(newVal);
+ });
+
+ this.$scope.$watch("editForm.$dirty", (newVal, oldVal) => {
+ if (newVal !== oldVal) {
+ this.$state.current.data.unsavedChanges = newVal && !this.$scope.isCreateMode();
+ }
+ });
+
+ this.$scope.onCategoryChange = ():void => {
+ this.$scope.component.selectedCategory = this.$scope.componentCategories.selectedCategory;
+ this.$scope.component.categories = this.convertCategoryStringToOneArray();
+ this.$scope.component.icon = DEFAULT_ICON;
+ };
+
+ this.$scope.onEcompGeneratedNamingChange = ():void =>{
+ if(!(<Service>this.$scope.component).ecompGeneratedNaming){
+ (<Service>this.$scope.component).namingPolicy = '';
+ }
+ };
+
+ this.$scope.onVendorNameChange = (oldVendorName:string):void => {
+ if (this.$scope.component.icon === oldVendorName) {
+ this.$scope.component.icon = DEFAULT_ICON;
+ }
+ };
+ };
+}
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/general/general-view.html b/catalog-ui/src/app/view-models/workspace/tabs/general/general-view.html
index 1c1d4fedad..2ad0cbacd6 100644
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/general/general-view.html
+++ b/catalog-ui/src/app/view-models/workspace/tabs/general/general-view.html
@@ -1,12 +1,12 @@
<div include-padding="true" class="sdc-workspace-general-step">
- <form novalidate class="w-sdc-form" name="editForm">
+ <form novalidate class="w-sdc-form" name="editForm" validation-on-load form-to-validate="editForm">
<div class="w-sdc-form-section-container">
<!--------------------- IMPORT TOSCA FILE USING BROWSE (ALSO VFC) -------------------->
<div class="i-sdc-form-item" ng-if="isShowFileBrowse">
- <label class="i-sdc-form-label required">{{browseFileLabel}}</label>
+ <label class="i-sdc-form-label" data-ng-class="{'required':isCreateMode()}">{{browseFileLabel}}</label>
<file-upload id="fileUploadElement"
class="i-sdc-form-input"
element-name="fileElement"
@@ -58,7 +58,7 @@
type="text"
data-required
data-ng-model-options="{ debounce: 500 }"
- data-ng-pattern="validation.validationPattern"
+ data-ng-pattern="validation.componentNameValidationPattern"
data-ng-disabled="component.isAlreadyCertified()"
data-tests-id="name"
autofocus
@@ -70,7 +70,7 @@
<span ng-show="editForm.componentName.$error.maxlength" translate="VALIDATION_ERROR_MAX_LENGTH" translate-values="{'max': '50' }"></span>
<span ng-show="editForm.componentName.$error.minlength" translate="VALIDATION_ERROR_MIN_LENGTH" translate-values="{'min': '4' }"></span>
<span ng-show="editForm.componentName.$error.nameExist" translate="NEW_SERVICE_RESOURCE_ERROR_NAME_EXISTS"></span>
- <span ng-show="editForm.componentName.$error.pattern" translate="VALIDATION_ERROR_SPECIAL_CHARS_NOT_ALLOWED"></span>
+ <span ng-show="editForm.componentName.$error.pattern" translate="VALIDATION_ERROR_INVALID_NAME"></span>
</div>
</div>
<!--------------------- NAME -------------------->
@@ -142,13 +142,13 @@
data-ng-class="{'view-mode': isViewMode()}"
data-ng-change="onCategoryChange()"
data-ng-disabled="component.isAlreadyCertified() || (component.isCsarComponent() && component.selectedCategory && component.selectedCategory!=='')"
- data-ng-model="component.selectedCategory"
+ data-ng-model="componentCategories.selectedCategory"
data-tests-id="selectGeneralCategory"
>
<option value="">Select category</option>
<optgroup ng-if="component.isResource()" data-ng-repeat="mainCategory in categories | orderBy:['name']" label="{{mainCategory.name}}" data-tests-id="{{mainCategory.name}}">
<option data-ng-repeat="subCategory in mainCategory.subcategories track by $index"
- data-ng-selected="component.selectedCategory === calculateUnique(mainCategory.name,subCategory.name)"
+ data-ng-selected="componentCategories.selectedCategory === calculateUnique(mainCategory.name,subCategory.name)"
data-tests-id="{{subCategory.name}}"
value="{{calculateUnique(mainCategory.name, subCategory.name)}}">{{subCategory.name}}
@@ -174,11 +174,10 @@
data-ng-model="component.projectCode"
data-ng-class="{'view-mode': isViewMode()}"
data-ng-model-options="{ debounce: 500 }"
- data-ng-maxlength="128"
+ maxlength="50"
data-required
name="projectCode"
data-ng-pattern="validation.projectCodeValidationPattern"
- maxlength="50"
data-tests-id="projectCode"
/>
@@ -188,6 +187,54 @@
</div>
</div>
+
+ <!--------------------- ECOMPGENERATEDNAMING -------------------->
+
+ <div class="i-sdc-form-item"
+ data-ng-class="{'error': validateField(editForm.ecompGeneratedNaming)}"
+ data-ng-if="component.isService()">
+ <label class="i-sdc-form-label">Ecomp Generated Naming</label>
+ <select class="i-sdc-form-select"
+ data-required
+ name="ecompGeneratedNaming"
+ data-ng-change="onEcompGeneratedNamingChange()"
+ data-ng-class="{'view-mode': isViewMode()}"
+ data-ng-model="component.ecompGeneratedNaming"
+ data-tests-id="ecompGeneratedNaming">
+ <option ng-value="true">true</option>
+ <option ng-value="false">false</option>
+ </select>
+ <div class="input-error" data-ng-show="validateField(editForm.ecompGeneratedNaming)">
+
+ </div>
+ </div>
+ <!--------------------- CATEGORIES -------------------->
+
+ <!--------------------- NAMING POLICY -------------------->
+ <div ng-if="component.isService()" class="i-sdc-form-item" data-ng-class="{'error': validateField(editForm.namingPolicy)}">
+ <label class="i-sdc-form-label">Naming policy</label>
+ <input class="i-sdc-form-input"
+ name="fullName"
+ data-ng-class="{'view-mode': isViewMode() || !component.ecompGeneratedNaming}"
+ data-ng-maxlength="100"
+ maxlength="100"
+ data-ng-model="component.namingPolicy"
+ type="text"
+ data-ng-model-options="{ debounce: 500 }"
+ data-ng-pattern="validation.commentValidationPattern"
+ data-tests-id="namingPolicy"
+ autofocus
+ ng-readonly="isViewMode() || !component.ecompGeneratedNaming"
+ />
+
+ <div class="input-error" data-ng-show="validateField(editForm.namingPolicy)">
+ <span ng-show="editForm.namingPolicy.$error.maxlength" translate="VALIDATION_ERROR_MAX_LENGTH" translate-values="{'max': '100' }"></span>
+ <span ng-show="editForm.namingPolicy.$error.pattern" translate="VALIDATION_ERROR_SPECIAL_CHARS_NOT_ALLOWED"></span>
+ </div>
+ </div>
+ <!--------------------- NAMING POLICY -------------------->
+
+
<!--------------------- VENDOR NAME -------------------->
<div ng-if="component.isResource()" class="i-sdc-form-item" data-ng-class="{'error': validateField(editForm.vendorName)}">
<label class="i-sdc-form-label required">Vendor</label>
@@ -265,7 +312,7 @@
</div>
<!--------------------- RESOURCE TAGS -------------------->
- <!--------------------- CONTACT ID -------------------->
+ <!--------------------- USER ID -------------------->
<div class="i-sdc-form-item" data-ng-class="{'error': validateField(editForm.contactId)}">
<label class="i-sdc-form-label " data-ng-class="{'required':!component.isProduct()}" translate="GENERAL_LABEL_CONTACT_ID"></label>
<input class="i-sdc-form-input" type="text" data-ng-if="!component.isProduct()"
@@ -275,7 +322,7 @@
name="contactId"
data-ng-pattern="validation.contactIdValidationPattern"
data-ng-model-options="{ debounce: 500 }"
- data-tests-id="userId"
+ data-tests-id="contactId"
maxlength="50"
/>
<input class="i-sdc-form-input" type="text" data-ng-if="component.isProduct()"
@@ -285,7 +332,7 @@
name="contactId"
data-ng-pattern="validation.contactIdValidationPattern"
data-ng-model-options="{ debounce: 500 }"
- data-tests-id="userId"
+ data-tests-id="contactId"
maxlength="50"
/>
@@ -294,7 +341,7 @@
<span ng-show="editForm.contactId.$error.pattern" translate="NEW_SERVICE_RESOURCE_ERROR_CONTACT_NOT_VALID"></span>
</div>
</div>
- <!--------------------- CONTACT ID -------------------->
+ <!--------------------- USER ID -------------------->
</div><!-- Close w-sdc-form-column -->
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/general/general.less b/catalog-ui/src/app/view-models/workspace/tabs/general/general.less
index 1861d02e98..1861d02e98 100644
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/general/general.less
+++ b/catalog-ui/src/app/view-models/workspace/tabs/general/general.less
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/icons/icons-view-model.ts b/catalog-ui/src/app/view-models/workspace/tabs/icons/icons-view-model.ts
new file mode 100644
index 0000000000..03dad2cc06
--- /dev/null
+++ b/catalog-ui/src/app/view-models/workspace/tabs/icons/icons-view-model.ts
@@ -0,0 +1,111 @@
+/**
+ * Created by obarda on 4/4/2016.
+ */
+'use strict';
+import {ComponentFactory} from "app/utils";
+import {AvailableIconsService} from "app/services";
+import {IWorkspaceViewModelScope} from "app/view-models/workspace/workspace-view-model";
+import {IMainCategory, ISubCategory} from "app/models";
+
+export interface IIconsScope extends IWorkspaceViewModelScope {
+ icons:Array<string>;
+ iconSprite:string;
+ setComponentIcon(iconSrc:string):void;
+}
+
+export class IconsViewModel {
+
+ static '$inject' = [
+ '$scope',
+ 'Sdc.Services.AvailableIconsService',
+ 'ComponentFactory',
+ '$state'
+ ];
+
+ constructor(private $scope:IIconsScope,
+ private availableIconsService:AvailableIconsService,
+ private ComponentFactory:ComponentFactory,
+ private $state:ng.ui.IStateService) {
+
+
+ this.initScope();
+ this.initIcons();
+ this.$scope.updateSelectedMenuItem();
+ this.$scope.iconSprite = this.$scope.component.iconSprite;
+
+ if (this.$scope.component.isResource()) {
+ this.initVendor();
+ }
+ }
+
+ private initialIcon:string = this.$scope.component.icon;
+ private initIcons = ():void => {
+
+ // For subcategories that where created by admin, there is no icons
+ this.$scope.icons = new Array<string>();
+ if (this.$scope.component.categories && this.$scope.component.categories.length > 0) {
+
+ _.forEach(this.$scope.component.categories, (category:IMainCategory):void => {
+ if (category.icons) {
+ this.$scope.icons = this.$scope.icons.concat(category.icons);
+ }
+ if (category.subcategories) {
+ _.forEach(category.subcategories, (subcategory:ISubCategory):void => {
+ if (subcategory.icons) {
+ this.$scope.icons = this.$scope.icons.concat(subcategory.icons);
+ }
+ });
+ }
+ });
+ }
+
+ if (this.$scope.component.isResource()) {
+ let resourceType:string = this.$scope.component.getComponentSubType();
+ if (resourceType === 'VL') {
+ this.$scope.icons = ['vl'];
+ }
+ if (resourceType === 'CP') {
+ this.$scope.icons = ['cp'];
+ }
+ }
+
+ if (this.$scope.icons.length === 0) {
+ this.$scope.icons = this.availableIconsService.getIcons(this.$scope.component.componentType);
+ }
+ //we always add the defual icon to the list
+ this.$scope.icons.push('defaulticon');
+ };
+
+ private initVendor = ():void => {
+ let vendors:Array<string> = this.availableIconsService.getIcons(this.$scope.component.componentType).slice(5, 19);
+ let vendorName = this.$scope.component.vendorName.toLowerCase();
+ if ('at&t' === vendorName) {
+ vendorName = 'att';
+ }
+ if ('nokia' === vendorName) {
+ vendorName = 'nokiasiemens';
+ }
+ let vendor:string = _.find(vendors, (vendor:string)=> {
+ return vendor.replace(/[_]/g, '').toLowerCase() === vendorName;
+ });
+
+ if (vendor && this.$scope.icons.indexOf(vendor) === -1) {
+ this.$scope.icons.push(vendor);
+ }
+ };
+
+ private initScope():void {
+ this.$scope.icons = [];
+ this.$scope.setValidState(true);
+ //if(this.$scope.component.icon === DEFAULT_ICON){
+ // //this.$scope.setValidState(false);
+ //}
+
+ this.$scope.setComponentIcon = (iconSrc:string):void => {
+ this.$state.current.data.unsavedChanges = !this.$scope.isViewMode() && (iconSrc != this.initialIcon);
+ this.$scope.component.icon = iconSrc;
+ // this.$scope.setValidState(true);
+ };
+
+ }
+}
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/icons/icons-view.html b/catalog-ui/src/app/view-models/workspace/tabs/icons/icons-view.html
index aac14e0e84..aac14e0e84 100644
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/icons/icons-view.html
+++ b/catalog-ui/src/app/view-models/workspace/tabs/icons/icons-view.html
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/icons/icons.less b/catalog-ui/src/app/view-models/workspace/tabs/icons/icons.less
index 65f946f395..65f946f395 100644
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/icons/icons.less
+++ b/catalog-ui/src/app/view-models/workspace/tabs/icons/icons.less
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
new file mode 100644
index 0000000000..e10a9944d3
--- /dev/null
+++ b/catalog-ui/src/app/view-models/workspace/tabs/information-artifacts/information-artifacts-view-model.ts
@@ -0,0 +1,138 @@
+'use strict';
+import {ModalsHandler} from "app/utils";
+import {SharingService} from "app/services";
+import {IAppConfigurtaion, ArtifactModel, IFileDownload} from "app/models";
+import {IWorkspaceViewModelScope} from "app/view-models/workspace/workspace-view-model";
+import {ComponentServiceNg2} from "../../../../ng2/services/component-services/component.service";
+import {ArtifactGroupModel} from "../../../../models/artifacts";
+import {ComponentGenericResponse} from "../../../../ng2/services/responses/component-generic-response";
+
+export interface IInformationArtifactsScope extends IWorkspaceViewModelScope {
+ artifacts:Array<ArtifactModel>;
+ tableHeadersList:Array<any>;
+ artifactType:string;
+ isResourceInstance:boolean;
+ downloadFile:IFileDownload;
+ isLoading:boolean;
+ sortBy:string;
+ reverse:boolean;
+
+ getTitle():string;
+ addOrUpdate(artifact:ArtifactModel):void;
+ delete(artifact:ArtifactModel):void;
+ download(artifact:ArtifactModel):void;
+ clickArtifactName(artifact:any):void;
+ openEditEnvParametersModal(artifactResource:ArtifactModel):void;
+ sort(sortBy:string):void;
+ showNoArtifactMessage():boolean;
+}
+
+export class InformationArtifactsViewModel {
+
+ static '$inject' = [
+ '$scope',
+ '$filter',
+ '$state',
+ 'sdcConfig',
+ 'ModalsHandler',
+ 'ComponentServiceNg2'
+ ];
+
+ constructor(private $scope:IInformationArtifactsScope,
+ private $filter:ng.IFilterService,
+ private $state:any,
+ private sdcConfig:IAppConfigurtaion,
+ private ModalsHandler:ModalsHandler,
+ private ComponentServiceNg2: ComponentServiceNg2) {
+ this.initInformationalArtifacts();
+ this.$scope.updateSelectedMenuItem();
+ }
+
+ private initInformationalArtifacts = ():void => {
+ if(!this.$scope.component.artifacts) {
+ this.$scope.isLoading = true;
+ this.ComponentServiceNg2.getComponentInformationalArtifacts(this.$scope.component).subscribe((response:ComponentGenericResponse) => {
+ this.$scope.component.artifacts = response.artifacts;
+ this.initScope();
+ this.$scope.isLoading = false;
+ });
+ } else {
+ this.initScope();
+ }
+ }
+
+ private initScope = ():void => {
+
+ this.$scope.isLoading = false;
+ this.$scope.sortBy = 'artifactDisplayName';
+ this.$scope.reverse = false;
+ this.$scope.setValidState(true);
+ this.$scope.artifactType = 'informational';
+ this.$scope.getTitle = ():string => {
+ return this.$filter("resourceName")(this.$scope.component.name) + ' Artifacts';
+
+ };
+
+ this.$scope.tableHeadersList = [
+ {title: 'Name', property: 'artifactDisplayName'},
+ {title: 'Type', property: 'artifactType'},
+ {title: 'Version', property: 'artifactVersion'},
+ {title: 'UUID', property: 'artifactUUID'}
+ ];
+
+ this.$scope.artifacts = <ArtifactModel[]>_.values(this.$scope.component.artifacts);
+ this.$scope.sort = (sortBy:string):void => {
+ this.$scope.reverse = (this.$scope.sortBy === sortBy) ? !this.$scope.reverse : false;
+ this.$scope.sortBy = sortBy;
+ };
+
+
+ this.$scope.addOrUpdate = (artifact:ArtifactModel):void => {
+ artifact.artifactGroupType = 'INFORMATIONAL';
+ this.ModalsHandler.openArtifactModal(artifact, this.$scope.component).then(() => {
+ this.$scope.artifacts = <ArtifactModel[]>_.values(this.$scope.component.artifacts);
+ });
+ };
+
+ this.$scope.showNoArtifactMessage = ():boolean => {
+ let artifacts:any = [];
+ artifacts = _.filter(this.$scope.artifacts, (artifact:ArtifactModel)=> {
+ return artifact.esId;
+ });
+
+ if (artifacts.length === 0) {
+ return true;
+ }
+ return false;
+ };
+
+ this.$scope.delete = (artifact:ArtifactModel):void => {
+
+ let onOk = ():void => {
+ this.$scope.isLoading = true;
+ let onSuccess = ():void => {
+ this.$scope.isLoading = false;
+ this.$scope.artifacts = <ArtifactModel[]>_.values(this.$scope.component.artifacts);
+ };
+
+ let onFailed = (error:any):void => {
+ console.log('Delete artifact returned error:', error);
+ this.$scope.isLoading = false;
+ };
+
+ this.$scope.component.deleteArtifact(artifact.uniqueId, artifact.artifactLabel).then(onSuccess, onFailed);
+ };
+
+ let title:string = this.$filter('translate')("ARTIFACT_VIEW_DELETE_MODAL_TITLE");
+ let message:string = this.$filter('translate')("ARTIFACT_VIEW_DELETE_MODAL_TEXT", "{'name': '" + artifact.artifactDisplayName + "'}");
+ this.ModalsHandler.openConfirmationModal(title, message, false).then(onOk);
+ };
+
+ this.$scope.clickArtifactName = (artifact:any) => {
+ if (!artifact.esId) {
+ this.$scope.addOrUpdate(artifact);
+ }
+
+ };
+ }
+}
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/information-artifacts/information-artifacts-view.html b/catalog-ui/src/app/view-models/workspace/tabs/information-artifacts/information-artifacts-view.html
index 790117b2fd..7c843e9fe8 100644
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/information-artifacts/information-artifacts-view.html
+++ b/catalog-ui/src/app/view-models/workspace/tabs/information-artifacts/information-artifacts-view.html
@@ -20,15 +20,24 @@
data-ng-class="{'selected': artifact.selected}"
data-ng-if="artifact.esId">
- <div class="table-col-general flex-item" data-ng-click="artifact.selected = !artifact.selected">
- <span class="sprite table-arrow" data-ng-class="{'opened': artifact.selected}" data-tests-id="{{artifact.artifactDisplayName}}"></span>
+ <div class="table-col-general flex-item" data-ng-click="artifact.selected = !artifact.selected" data-tests-id="artifactDisplayName_{{artifact.artifactDisplayName}}">
+ <span class="sprite table-arrow" data-ng-class="{'opened': artifact.selected}" data-tests-id="artifact_arrow_{{artifact.artifactDisplayName}}"></span>
{{artifact.artifactDisplayName}}
</div>
- <div class="table-col-general flex-item" data-ng-click="artifact.selected = !artifact.selected" data-tests-id="{{artifact.artifactType}}">
+ <div class="table-col-general flex-item" data-ng-click="artifact.selected = !artifact.selected" data-tests-id="artifactType_{{artifact.artifactDisplayName}}">
{{artifact.artifactType}}
</div>
+ <div class="table-col-general flex-item" data-ng-click="artifact.selected = !artifact.selected" data-tests-id="artifactVersion_{{artifact.artifactDisplayName}}">
+ {{artifact.artifactVersion}}
+ </div>
+
+ <div class="table-col-general flex-item text" data-ng-click="artifact.selected = !artifact.selected" data-tests-id="artifactUUID_{{artifact.artifactDisplayName}}"
+ tooltips tooltip-content="{{artifact.artifactUUID}}">
+ <span>{{artifact.artifactUUID}}</span>
+ </div>
+
<div class="table-btn-col flex-item">
<button class="table-edit-btn" data-tests-id="edit_{{artifact.artifactDisplayName}}" data-ng-if="!isViewMode() && !artifact.isThirdParty()" data-ng-click="addOrUpdate(artifact)" data-ng-class="{'disabled': isDisableMode()}"></button>
<button class="table-delete-btn" data-tests-id="delete_{{artifact.artifactDisplayName}}" data-ng-if="!isViewMode() && !artifact.isThirdParty()" data-ng-click="delete(artifact)" data-ng-class="{'disabled': isDisableMode()}"> </button>
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/information-artifacts/information-artifacts.less b/catalog-ui/src/app/view-models/workspace/tabs/information-artifacts/information-artifacts.less
index d3fe14d945..3ba9cf47d5 100644
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/information-artifacts/information-artifacts.less
+++ b/catalog-ui/src/app/view-models/workspace/tabs/information-artifacts/information-artifacts.less
@@ -18,6 +18,12 @@
word-wrap: break-word;
}
+ .text{
+ overflow: hidden;
+ text-overflow: ellipsis;
+ display: inline-block;
+ white-space: nowrap;
+ }
.flex-item:nth-child(1) {
flex-grow: 15;
@@ -33,11 +39,15 @@
.flex-item:nth-child(3) {
flex-grow: 3;
- padding-top: 10px;
}
.flex-item:nth-child(4) {
- flex-grow: 1;
+ flex-grow: 20;
+ }
+
+ .flex-item:nth-child(5) {
+ flex-grow: 5;
+ padding-top: 10px;
}
}
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/inputs/inputs.less b/catalog-ui/src/app/view-models/workspace/tabs/inputs/inputs.less
index 76a82c69ee..eff5c5395b 100644
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/inputs/inputs.less
+++ b/catalog-ui/src/app/view-models/workspace/tabs/inputs/inputs.less
@@ -1,23 +1,35 @@
.workspace-inputs {
.sdc-workspace-container .w-sdc-main-right-container .w-sdc-main-container-body-content {
- padding: 25px 8% 0px 8%;
+ padding: 25px 8% 25px 8%;
}
+ .w-sdc-main-container .w-sdc-main-right-container > div:first-child {
+ /* scroll fix */
+ padding-bottom: 0px;
+ }
+
+
width: 100%;
display: flex;
.text {
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
padding-left: 15px;
+ .no-overflow;
}
.title-text {
color: @main_color_m;
.f-type._13_m;
.bold;
+ text-overflow: ellipsis;
+ overflow: hidden;
+ }
+
+ .no-overflow {
+ text-overflow: ellipsis;
+ overflow: hidden;
+ white-space: nowrap;
}
.title-blue-text {
@@ -28,6 +40,7 @@
padding-right: 13px;
border-right: 1px solid rgba(120, 136, 148, 0.26);
flex-grow: 1;
+ .no-overflow;
}
}
@@ -106,25 +119,6 @@
}
- .property-row {
- border-bottom: 1px solid @border_color_d;
- padding-left: 10px;
- .property-name-container {
- display: flex;
- flex-grow: 4;
- }
-
- .type-schema-container {
- flex-grow: 1;
- border-left: 1px solid @border_color_d;
- text-align: left;
- line-height: 30px;
- text-transform: capitalize;
- width: 10px;
- }
-
- }
-
.table-container-flex {
.flex-item {
@@ -132,15 +126,6 @@
}
.expand-collapse-table-row {
- &.expanded {
- .flex-container {
- .expand-collapse-inputs-table-icon {
- transform: rotate(180deg);
- left: 0px;
- }
- }
- }
-
.data-row {
background: @tlv_color_u;
.hand;
@@ -153,48 +138,6 @@
.data-row:hover {
.bg_j;
}
-
- .input-row {
- padding-left: 45px;
- background: @tlv_color_t;
- border: @main_color_o solid 1px;
- align-items: center;
- .hand;
- margin: 1px 0px 1px 0px;
-
- &.service-input-row {
- background: @tlv_color_u;
- &.new-input {
- background: @tlv_color_v;
- }
- }
- &.selected {
- background-color: @tlv_color_v;
- }
- .flex-item {
- min-height: 60px;
- padding: 0 15px;
- }
- .input-check-box {
- padding-right: 10px;
- margin-top: 9px;
- }
- &>.title-text{
- text-align: start;
- padding: 4px 0 0 35px;
- }
-
- .expand-collapse-inputs-table-icon{
- margin-top: 15px;
- }
-
- }
-
- .input-row:hover {
- .bg_j;
- }
-
-
}
}
@@ -224,10 +167,6 @@
background-color: #e6e6e6;
}
- .property-row:hover{
- background-color: @func_color_r;
- }
-
.body {
.scrollbar-container {
.perfect-scrollbar;
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
new file mode 100644
index 0000000000..49fedd6e21
--- /dev/null
+++ b/catalog-ui/src/app/view-models/workspace/tabs/inputs/resource-input/resource-inputs-view-model.ts
@@ -0,0 +1,117 @@
+'use strict';
+import {IWorkspaceViewModelScope} from "app/view-models/workspace/workspace-view-model";
+import {ComponentInstance, InstancesInputsOrPropertiesMapData, Resource, PropertyModel, InputModel} from "app/models";
+import {ModalsHandler} from "app/utils";
+
+export interface IInputsViewModelScope extends IWorkspaceViewModelScope {
+ InstanceInputsProperties:InstancesInputsOrPropertiesMapData; //this is tha map object that hold the selected inputs and the inputs we already used
+ vfInstancesList:Array<ComponentInstance>;
+ component:Resource;
+
+ onArrowPressed():void;
+ getInputPropertiesForInstance(instanceId:string, instance:ComponentInstance):ng.IPromise<boolean> ;
+ loadInputPropertiesForInstance(instanceId:string, input:InputModel):ng.IPromise<boolean> ;
+ openEditValueModal(input:InputModel):void;
+ openEditPropertyModal(property:PropertyModel):void;
+}
+
+export class ResourceInputsViewModel {
+
+ static '$inject' = [
+ '$scope',
+ '$q',
+ 'ModalsHandler'
+ ];
+
+ constructor(private $scope:IInputsViewModelScope, private $q:ng.IQService, private ModalsHandler:ModalsHandler) {
+ this.initScope();
+ this.$scope.updateSelectedMenuItem();
+ }
+
+ private initScope = ():void => {
+
+ this.$scope.InstanceInputsProperties = new InstancesInputsOrPropertiesMapData();
+ this.$scope.vfInstancesList = this.$scope.component.componentInstances;
+
+ // Need to cast all inputs to InputModel for the search to work
+ let tmpInputs:Array<InputModel> = new Array<InputModel>();
+ _.each(this.$scope.component.inputs, (input):void => {
+ tmpInputs.push(new InputModel(input));
+ });
+ this.$scope.component.inputs = tmpInputs;
+ // This function is not supported for resource
+ //this.$scope.component.getComponentInputs();
+
+ /*
+ * When clicking on instance input in the left or right table, this function will load all properties of the selected input
+ */
+ this.$scope.getInputPropertiesForInstance = (instanceId:string, instance:ComponentInstance):ng.IPromise<boolean> => {
+ let deferred = this.$q.defer();
+ instance.properties = this.$scope.component.componentInstancesProperties[instanceId];
+ deferred.resolve(true);
+ return deferred.promise;
+ };
+
+ /*
+ * When clicking on instance input in the left or right table, this function will load all properties of the selected input
+ */
+ this.$scope.loadInputPropertiesForInstance = (instanceId:string, input:InputModel):ng.IPromise<boolean> => {
+ let deferred = this.$q.defer();
+
+ let onSuccess = (properties:Array<PropertyModel>) => {
+ input.properties = properties;
+ deferred.resolve(true);
+ };
+
+ let onError = () => {
+ deferred.resolve(false)
+ };
+
+ if (!input.properties) {
+ this.$scope.component.getComponentInstanceInputProperties(instanceId, input.uniqueId).then(onSuccess, onError);
+ } else {
+ deferred.resolve(true);
+ }
+ return deferred.promise;
+ };
+
+ /*
+ * When pressing the arrow, we create service inputs from the inputs selected
+ */
+ this.$scope.onArrowPressed = ():void => {
+ let onSuccess = (inputsCreated:Array<InputModel>) => {
+
+ //disabled all the inputs in the left table
+ _.forEach(this.$scope.InstanceInputsProperties, (properties:Array<PropertyModel>) => {
+ _.forEach(properties, (property:PropertyModel) => {
+ property.isAlreadySelected = true;
+ });
+ });
+
+ // Adding color to the new inputs (right table)
+ _.forEach(inputsCreated, (input) => {
+ input.isNew = true;
+ });
+
+ // Removing color to the new inputs (right table)
+ setTimeout(() => {
+ _.forEach(inputsCreated, (input) => {
+ input.isNew = false;
+ });
+ this.$scope.$apply();
+ }, 3000);
+ };
+
+ this.$scope.component.createInputsFormInstances(this.$scope.InstanceInputsProperties).then(onSuccess);
+ };
+
+ this.$scope.openEditValueModal = (input:InputModel) => {
+ this.ModalsHandler.openEditInputValueModal(input);
+ };
+
+ this.$scope.openEditPropertyModal = (property:PropertyModel):void => {
+ this.ModalsHandler.openEditPropertyModal(property, this.$scope.component, this.$scope.component.componentInstancesProperties[property.resourceInstanceUniqueId], false).then(() => {
+ });
+ }
+ }
+}
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/inputs/resource-input/resource-inputs-view.html b/catalog-ui/src/app/view-models/workspace/tabs/inputs/resource-input/resource-inputs-view.html
new file mode 100644
index 0000000000..a0715973ab
--- /dev/null
+++ b/catalog-ui/src/app/view-models/workspace/tabs/inputs/resource-input/resource-inputs-view.html
@@ -0,0 +1,86 @@
+<div class="workspace-inputs">
+ <div class="table-container-flex">
+ <div class="w-sdc-inputs-search pull-left hideme">
+ <input type="text" class="w-sdc-inputs-search-input" placeholder="Search"/>
+ <div class="search-icon-container">
+ <span class="w-sdc-search-icon inputs-search-icon magnification-white"></span>
+ </div>
+ </div>
+ <div class="table">
+ <div class="table-header">VFC instances inputs</div>
+ <div class="body">
+ <div class="table-loader" ng-class="{'tlv-loader large loader': isLoading}"></div>
+ <perfect-scrollbar scroll-y-margin-offset="0" class="scrollbar-container">
+
+ <expand-collapse expanded-selector=".vf-instance-list.{{$index}}"
+ class="expand-collapse-table-row"
+ load-data-function="getInputPropertiesForInstance(instance.uniqueId, instance)"
+ is-close-on-init="true"
+ data-ng-repeat-start="instance in vfInstancesList track by $index">
+ <div class="flex-container data-row" data-tests-id="input-instance-{{$index}}">
+ <div class="expand-collapse-inputs-table-icon"></div>
+ <div class="table-col-general flex-item text">
+ <span class="title-text">{{instance.name}}</span>
+ </div>
+ </div>
+
+ </expand-collapse>
+
+ <div data-ng-repeat-end="" class="vf-instance-list {{$index}}">
+ <div class="empty-row" data-tests-id="empty-row" ng-if="instance.properties.length===0">No properties to display </div>
+ <div ng-repeat="property in instance.properties track by $index">
+ <property-row property="property" instance-name="instance.name" on-name-clicked="openEditPropertyModal(property)"></property-row>
+ </div>
+
+ </div>
+
+ </perfect-scrollbar>
+ </div>
+ </div>
+ </div>
+
+ <div class="inputs-button-container pull-left">
+ <!--<div ng-click="onArrowPressed()" class="right-arrow-btn"></div>-->
+ </div>
+
+ <div class="table-container-flex">
+ <div class="w-sdc-inputs-search pull-left">
+ <input type="text" class="w-sdc-inputs-search-input" data-ng-model="search.filterTerm" placeholder="Search"
+ data-ng-model-options="{debounce: 200}"/>
+ <div class="search-icon-container">
+ <span class="w-sdc-search-icon inputs-search-icon magnification-white"></span>
+ </div>
+ </div>
+ <div class="table">
+ <div class="body">
+ <div class="table-header">VF inputs</div>
+ <perfect-scrollbar scroll-y-margin-offset="0" include-padding="true" class="scrollbar-container">
+ <expand-collapse expanded-selector=".resource-inputs.{{$index}}"
+ class="expand-collapse-table-row"
+ load-data-function="loadInputPropertiesForInstance(resourceInput.uniqueId, resourceInput)"
+ is-close-on-init="true"
+ data-ng-repeat-start="resourceInput in component.inputs | filter:search track by $index ">
+ <div class="input-row service-input-row">
+ <input-row input="resourceInput" is-view-only='isViewOnly'
+ instance-name='resourceInput.name'
+ data-tests-id="resource-input-{{$index}}"
+ class="service-input-row"
+ on-name-clicked="openEditValueModal(resourceInput)"
+ ng-class="resourceInput.isNew ? 'new-input': ''">
+
+ </input-row>
+ </div>
+ </expand-collapse>
+
+ <div data-ng-repeat-end="" class="input-inputs-list resource-inputs {{$index}}">
+ <div class="empty-row" ng-if="resourceInput.properties.length===0">No properties to display </div>
+ <div ng-repeat="property in resourceInput.properties track by $index">
+ <property-row property="property" instance-name="property.name"></property-row>
+ </div>
+ </div>
+
+ </perfect-scrollbar>
+ </div>
+ </div>
+ </div>
+</div>
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/inputs/resource-input/resource-inputs.less b/catalog-ui/src/app/view-models/workspace/tabs/inputs/resource-input/resource-inputs.less
index ebb32fbdb2..ebb32fbdb2 100644
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/inputs/resource-input/resource-inputs.less
+++ b/catalog-ui/src/app/view-models/workspace/tabs/inputs/resource-input/resource-inputs.less
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
new file mode 100644
index 0000000000..f3b2de0943
--- /dev/null
+++ b/catalog-ui/src/app/view-models/workspace/tabs/inputs/service-input/service-inputs-view-model.ts
@@ -0,0 +1,378 @@
+'use strict';
+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";
+import {ModalsHandler, ResourceType} from "app/utils";
+
+
+interface IServiceInputsViewModelScope extends IWorkspaceViewModelScope {
+
+ vfInstancesList:Array<ComponentInstance>;
+ instanceInputsMap:InstancesInputsOrPropertiesMapData; //this is tha map object that hold the selected inputs and the inputs we already used
+ instancePropertiesMap:InstancesInputsOrPropertiesMapData;
+ component:Service;
+ sdcMenu:IAppMenu;
+ isViewOnly:boolean;
+ isArrowDisabled:boolean;
+ onArrowPressed():void;
+ checkArrowState():void;
+ loadComponentInputs():void;
+ loadInstanceInputs(instance:ComponentInstance):ng.IPromise<boolean> ;
+ loadInstanceProperties(instance:ComponentInstance):ng.IPromise<boolean> ;
+ loadInputPropertiesForInstance(instanceId:string, input:InputModel):ng.IPromise<boolean> ;
+ loadInputInputs(input:InputModel):ng.IPromise<boolean>;
+ deleteInput(input:InputModel):void
+ openEditValueModal(input:InputModel):void;
+ openSelectPropertyDataTypeViewModel(instanceId:string, property:PropertyModel):void;
+ openEditPropertyDataTypeViewModel(property:PropertyModel):void;
+ dataTypesService:DataTypesService;
+}
+
+export class ServiceInputsViewModel {
+
+ static '$inject' = [
+ '$scope',
+ '$q',
+ 'ModalsHandler',
+ 'Sdc.Services.DataTypesService'
+ ];
+
+ constructor(private $scope:IServiceInputsViewModelScope,
+ private $q:ng.IQService,
+ private ModalsHandler:ModalsHandler,
+ private DataTypesService:DataTypesService) {
+ this.initScope();
+ this.$scope.updateSelectedMenuItem();
+ this.$scope.isViewOnly = this.$scope.isViewMode();
+ }
+
+
+ private getInputsOrPropertiesAlreadySelected = (instanceNormalizeName:string, arrayToFilter:Array<InputPropertyBase>):Array<any> => {
+ let alreadySelectedInput = [];
+ _.forEach(arrayToFilter, (inputOrProperty:InputPropertyBase) => {
+ let expectedServiceInputName = instanceNormalizeName + '_' + inputOrProperty.name;
+ let inputAlreadyInService = _.find(this.$scope.component.inputs, (serviceInput:InputModel) => {
+ //Checking if the input prefix is the instance name + '_' + property/input name (prefix because we don't need to check full name for complex dataType)
+ return serviceInput.name.substring(0, expectedServiceInputName.length) === expectedServiceInputName;
+ });
+ if (inputAlreadyInService) {
+ inputOrProperty.isAlreadySelected = true;
+ alreadySelectedInput.push(inputOrProperty);
+ } else {
+ inputOrProperty.isAlreadySelected = false;
+ }
+ });
+ return alreadySelectedInput;
+ };
+
+
+ /*
+ * When loading the screen again, we need to disabled the inputs that already created on the service,
+ * we do that by comparing the service input name, to the instance name + '_' + the resource instance input name.
+ */
+ private disableEnableSelectedInputsOrPropertiesOnInit = (instance:ComponentInstance):void => {
+
+ if (instance.originType === ResourceType.VF) {
+ this.$scope.instanceInputsMap[instance.uniqueId] = this.getInputsOrPropertiesAlreadySelected(instance.normalizedName, instance.inputs);
+ } else {
+ this.$scope.instancePropertiesMap[instance.uniqueId] = this.getInputsOrPropertiesAlreadySelected(instance.normalizedName, instance.properties);
+ }
+ };
+
+ /*
+ * Enable Input/Property after delete
+ */
+ private enableInputsAfterDelete = (propertiesOrInputsDeletes:Array<InputPropertyBase>):void => {
+
+ _.forEach(propertiesOrInputsDeletes, (deletedInputInput:InputPropertyBase) => { //Enable all component instance inputs deleted
+
+ let inputOrPropertyDeleted:InputPropertyBase = _.find(this.$scope.instanceInputsMap[deletedInputInput.componentInstanceId], (inputOrProperty:InputPropertyBase) => {
+ return inputOrProperty.uniqueId === deletedInputInput.uniqueId;
+ });
+ inputOrPropertyDeleted.isAlreadySelected = false;
+ delete _.remove(this.$scope.instanceInputsMap[deletedInputInput.componentInstanceId], {uniqueId: inputOrPropertyDeleted.uniqueId})[0];
+ });
+ };
+
+ /*
+ * Enable Input/Property after delete
+ */
+ private enablePropertiesAfterDelete = (propertiesOrInputsDeletes:Array<InputPropertyBase>):void => {
+
+ _.forEach(propertiesOrInputsDeletes, (deletedInputInput:InputPropertyBase) => { //Enable all component instance inputs deleted
+ let componentInstance = _.find(this.$scope.vfInstancesList, (instance:ComponentInstance) => {
+ return instance.uniqueId === deletedInputInput.componentInstanceId;
+ });
+ let inputOrPropertyDeleted:InputPropertyBase = _.find(this.$scope.instancePropertiesMap[deletedInputInput.componentInstanceId], (inputOrProperty:InputPropertyBase) => {
+ return inputOrProperty.uniqueId === deletedInputInput.uniqueId;
+ });
+
+ let expectedName = componentInstance.normalizedName + '_' + inputOrPropertyDeleted.name;
+ let isAnotherInputExist = _.find(this.$scope.component.inputs, (input:InputModel) => {
+ return input.name.substring(0, expectedName.length) === expectedName;
+ });
+ if (!isAnotherInputExist) {
+ inputOrPropertyDeleted.isAlreadySelected = false;
+ delete _.remove(this.$scope.instancePropertiesMap[deletedInputInput.componentInstanceId], {uniqueId: inputOrPropertyDeleted.uniqueId})[0];
+ }
+ });
+ };
+
+ private initScope = ():void => {
+
+ this.$scope.instanceInputsMap = new InstancesInputsOrPropertiesMapData();
+ this.$scope.instancePropertiesMap = new InstancesInputsOrPropertiesMapData();
+ this.$scope.isLoading = true;
+ this.$scope.isArrowDisabled = true;
+ // Why do we need this? we call this later.
+ //this.$scope.component.getComponentInputs();
+
+ let onSuccess = (componentInstances:Array<ComponentInstance>) => {
+ console.log("component instances loaded: ", componentInstances);
+ this.$scope.vfInstancesList = componentInstances;
+ this.$scope.isLoading = false;
+ };
+
+ //This function will get al component instance for the left table - in
+ // future the instances will be filter according to search text
+ this.$scope.component.getComponentInstancesFilteredByInputsAndProperties().then(onSuccess);
+
+ // This function will get the service inputs for the right table
+ this.$scope.component.getComponentInputs();
+
+ /*
+ * When clicking on instance in the left table, this function will load all instance inputs
+ */
+ this.$scope.loadInstanceInputs = (instance:ComponentInstance):ng.IPromise<boolean> => {
+ let deferred = this.$q.defer();
+
+ let onSuccess = (inputs:Array<InputModel>) => {
+ instance.inputs = inputs;
+ this.disableEnableSelectedInputsOrPropertiesOnInit(instance);
+ deferred.resolve(true);
+ };
+
+ let onError = () => {
+ deferred.resolve(false);
+ };
+
+ if (!instance.inputs) {
+ this.$scope.component.getComponentInstanceInputs(instance.uniqueId, instance.componentUid).then(onSuccess, onError);
+ //this.disableEnableSelectedInputs(instance);
+ } else {
+ deferred.resolve(true);
+ }
+ return deferred.promise;
+ };
+
+
+ this.$scope.loadInstanceProperties = (instance:ComponentInstance):ng.IPromise<boolean> => {
+ let deferred = this.$q.defer();
+
+ let onSuccess = (properties:Array<PropertyModel>) => {
+ instance.properties = properties;
+ this.disableEnableSelectedInputsOrPropertiesOnInit(instance);
+ deferred.resolve(true);
+ };
+
+ let onError = () => {
+ deferred.resolve(false);
+ };
+
+ if (!instance.properties) {
+ this.$scope.component.getComponentInstanceProperties(instance.uniqueId).then(onSuccess, onError);
+ } else {
+ deferred.resolve(true);
+ }
+ return deferred.promise;
+ };
+
+ /*
+ * When clicking on instance input in the left or right table, this function will load all properties of the selected input
+ */
+ this.$scope.loadInputPropertiesForInstance = (instanceId:string, input:InputModel):ng.IPromise<boolean> => {
+ let deferred = this.$q.defer();
+
+ let onSuccess = (properties:Array<PropertyModel>) => {
+ input.properties = properties;
+ deferred.resolve(true);
+ };
+
+ let onError = () => {
+ deferred.resolve(false)
+ };
+
+ if (!input.properties) {
+ this.$scope.component.getComponentInstanceInputProperties(instanceId, input.uniqueId).then(onSuccess, onError);
+ } else {
+ deferred.resolve(true);
+ }
+ return deferred.promise;
+ };
+
+ /*
+ * When clicking on input in the right table, this function will load all inputs of the selected input
+ */
+ this.$scope.loadInputInputs = (input:InputModel):ng.IPromise<boolean> => {
+ let deferred = this.$q.defer();
+
+ let onSuccess = () => {
+ deferred.resolve(true);
+ };
+ let onError = () => {
+ deferred.resolve(false);
+ };
+
+ if (!input.inputs) { // Caching, if exists do not get it.
+ this.$scope.component.getServiceInputInputsAndProperties(input.uniqueId).then(onSuccess, onError);
+ } else {
+ deferred.resolve(true);
+ }
+ return deferred.promise;
+ };
+
+ /*
+ * When pressing the arrow, we create service inputs from the inputs selected
+ */
+ this.$scope.onArrowPressed = ():void => {
+ let onSuccess = (inputsCreated:Array<InputModel>) => {
+
+ //disabled all the inputs in the left table
+ _.forEach(this.$scope.instanceInputsMap, (inputs:Array<InputModel>, instanceId:string) => {
+ _.forEach(inputs, (input:InputModel) => {
+ input.isAlreadySelected = true;
+ });
+ });
+ _.forEach(this.$scope.instancePropertiesMap, (properties:Array<PropertyModel>, instanceId:string) => {
+ _.forEach(properties, (property:PropertyModel) => {
+ property.isAlreadySelected = true;
+ });
+ });
+ this.addColorToItems(inputsCreated);
+ };
+
+ let onFailed = (error:any) => {
+ this.$scope.isArrowDisabled = false;
+ console.log("Error declaring input/property");
+ };
+
+ this.$scope.isArrowDisabled = true;
+ this.$scope.component.createInputsFormInstances(this.$scope.instanceInputsMap, this.$scope.instancePropertiesMap).then(onSuccess, onFailed);
+ };
+
+
+ /* Iterates through array of selected inputs and properties and returns true if there is at least one new selection on left */
+ this.$scope.checkArrowState = ()=> {
+
+ let newInputSelected:boolean = _.some(this.$scope.instanceInputsMap, (inputs:Array<InputModel>) => {
+ return _.some(inputs, (input:InputModel)=> {
+ return input.isAlreadySelected === false;
+ });
+ });
+
+ let newPropSelected:boolean = _.some(this.$scope.instancePropertiesMap, (properties:Array<PropertyModel>) => {
+ return _.some(properties, (property:PropertyModel) => {
+ return property.isAlreadySelected === false;
+ });
+ });
+
+ this.$scope.isArrowDisabled = !(newInputSelected || newPropSelected);
+
+ };
+
+ this.$scope.deleteInput = (inputToDelete:InputModel):void => {
+
+ let onDelete = ():void => {
+
+ let onSuccess = (deletedInput:InputModel):void => {
+ if (deletedInput.inputs && deletedInput.inputs.length > 0) { // Enable input declared from input
+ this.enableInputsAfterDelete(deletedInput.inputs);
+ }
+
+ if (deletedInput.properties && deletedInput.properties.length > 0) { // Enable properties
+ this.enablePropertiesAfterDelete(deletedInput.properties);
+ }
+ deletedInput.isDeleteDisabled = false;
+ this.$scope.checkArrowState();
+
+ };
+
+ let onFailed = (error:any):void => {
+ console.log("Error deleting input");
+ inputToDelete.isDeleteDisabled = false;
+ };
+
+ inputToDelete.isDeleteDisabled = true;
+ this.addColorToItems([inputToDelete]);
+ this.$scope.component.deleteServiceInput(inputToDelete.uniqueId).then((deletedInput:InputModel):void => {
+ onSuccess(deletedInput);
+ }, onFailed);
+ };
+
+ // Get confirmation modal text from menu.json
+ let state = "deleteInput";
+ let title:string = this.$scope.sdcMenu.alertMessages[state].title;
+ let message:string = this.$scope.sdcMenu.alertMessages[state].message.format([inputToDelete.name]);
+
+ // Open confirmation modal
+ this.ModalsHandler.openAlertModal(title, message).then(onDelete);
+ };
+
+ this.$scope.openEditValueModal = (input:InputModel) => {
+ this.ModalsHandler.openEditInputValueModal(input);
+ };
+
+ this.$scope.openSelectPropertyDataTypeViewModel = (instanceId:string, property:PropertyModel) => {
+ //to open the select data type modal
+ let selectedInstance = _.find(this.$scope.vfInstancesList, {uniqueId: instanceId});
+ this.DataTypesService.selectedInstance = selectedInstance; //set the selected instance on the service for compering the input name on the service & the complex property
+ this.DataTypesService.selectedComponentInputs = this.$scope.component.inputs; // set all the service inputs on the data type service
+ let filteredPropertiesMap = _.filter(this.$scope.instancePropertiesMap[instanceId], (instanceProperty)=> {
+ return instanceProperty.name == property.name;
+ });//get all properties under the specific property
+ this.DataTypesService.selectedPropertiesName = property.propertiesName;
+
+ this.ModalsHandler.openSelectDataTypeModal(property, this.$scope.component, this.$scope.component.properties, filteredPropertiesMap).then((selectedProperty:PropertyModel)=> {
+ if (selectedProperty && selectedProperty.propertiesName) {
+ let propertyToUpdate:PropertyModel = _.find(selectedInstance.properties, {uniqueId: selectedProperty.uniqueId});
+ let existingProperty:PropertyModel = (<PropertyModel>_.find(this.$scope.instancePropertiesMap[instanceId], {uniqueId: propertyToUpdate.uniqueId}));
+
+ if (existingProperty) {
+ existingProperty.propertiesName = selectedProperty.propertiesName;
+ existingProperty.input = selectedProperty.input;
+ existingProperty.isAlreadySelected = false;
+ } else {
+ propertyToUpdate.propertiesName = selectedProperty.propertiesName;
+ propertyToUpdate.input = selectedProperty.input;
+ this.$scope.instancePropertiesMap[instanceId].push(propertyToUpdate);
+
+ }
+ this.$scope.checkArrowState();
+
+ }
+ });
+ };
+
+
+ this.$scope.openEditPropertyDataTypeViewModel = (property:PropertyModel)=> {
+ this.ModalsHandler.openEditPropertyModal(property, this.$scope.component, this.$scope.component.properties, false).then(() => {
+ });
+ }
+ };
+
+ private addColorToItems = (inputsCreated:Array<InputModel>):void => {
+
+ // Adding color to the new inputs (right table)
+ _.forEach(inputsCreated, (input) => {
+ input.isNew = true;
+ });
+
+ // Removing color to the new inputs (right table)
+ setTimeout(() => {
+ _.forEach(inputsCreated, (input) => {
+ input.isNew = false;
+ });
+ this.$scope.$apply();
+ }, 3000);
+ };
+}
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/inputs/service-input/service-inputs-view.html b/catalog-ui/src/app/view-models/workspace/tabs/inputs/service-input/service-inputs-view.html
new file mode 100644
index 0000000000..cb4d853f58
--- /dev/null
+++ b/catalog-ui/src/app/view-models/workspace/tabs/inputs/service-input/service-inputs-view.html
@@ -0,0 +1,134 @@
+<div class="workspace-inputs">
+ <div class="table-container-flex">
+ <div class="w-sdc-inputs-search pull-left hideme">
+ <input type="text" class="w-sdc-inputs-search-input" placeholder="Search"/>
+ <div class="search-icon-container">
+ <span class="w-sdc-search-icon inputs-search-icon magnification-white"></span>
+ </div>
+ </div>
+ <div class="table">
+ <div class="table-header">Resource instance inputs</div>
+ <div class="body">
+ <div class="table-loader" ng-class="{'tlv-loader large loader': isLoading}"></div>
+ <perfect-scrollbar scroll-y-margin-offset="0" class="scrollbar-container">
+
+ <expand-collapse expanded-selector=".vf-instance-list.{{$index}}"
+ class="expand-collapse-table-row"
+ load-data-function="instance.originType=='VF' ? loadInstanceInputs(instance):loadInstanceProperties(instance)"
+ is-close-on-init="true"
+ data-ng-repeat-start="instance in vfInstancesList track by $index">
+ <div class="flex-container data-row">
+ <div class="expand-collapse-inputs-table-icon"></div>
+ <div class="table-col-general flex-item text" data-tests-id="inputs-vf-instance-{{$index}}">
+ <span class="title-text">{{instance.name}}</span>
+ </div>
+ </div>
+ </expand-collapse>
+
+ <div data-ng-repeat-end="" class="vf-instance-list {{$index}}">
+ <div data-ng-if="instance.originType=='VF'">
+
+ <expand-collapse expanded-selector=".input-list.{{$parent.$index}}-{{$index}}"
+ class="expand-collapse-table-row"
+ load-data-function="loadInputPropertiesForInstance(instance.uniqueId, input)"
+ is-close-on-init="true"
+ data-ng-repeat-start="input in instance.inputs track by $index">
+ <input-row input="input"
+ is-view-only='isViewOnly'
+ instance-id='instance.uniqueId'
+ instance-name='instance.name'
+ instance-inputs-map="instanceInputsMap"
+ on-checkbox-clicked="checkArrowState()"></input-row>
+ </expand-collapse>
+
+ <div data-ng-repeat-end="" class="input-list {{$parent.$index}}-{{$index}}">
+ <div class="empty-row" ng-if="input.properties.length===0">No properties to display
+ </div>
+ <div ng-repeat="property in input.properties track by $index">
+ <property-row property="property" instance-name="instance.name"></property-row>
+ </div>
+ </div>
+ </div>
+ <div data-ng-if="instance.originType!='VF'">
+ <div class="empty-row" data-tests-id="empty-row" ng-if="instance.properties.length===0"> No
+ properties to display
+ </div>
+ <div ng-repeat="property in instance.properties track by $index">
+ <property-row instance-properties-map="instancePropertiesMap" property="property"
+ on-name-clicked="openSelectPropertyDataTypeViewModel(instance.uniqueId,property)"
+ on-checkbox-clicked="checkArrowState()"
+ instance-name="instance.name"
+ instance-id='instance.uniqueId'></property-row>
+ </div>
+ </div>
+ </div>
+
+ </perfect-scrollbar>
+ </div>
+ </div>
+ </div>
+
+ <div class="inputs-button-container pull-left">
+ <div ng-click="onArrowPressed()" ng-class="{disabled: isArrowDisabled || isViewOnly}" data-ng-disabled="isArrowDisabled || isViewOnly" class="right-arrow-btn" data-tests-id="add-inputs-to-service-button"></div>
+ </div>
+
+ <div class="table-container-flex">
+ <div class="w-sdc-inputs-search pull-left">
+ <input type="text" class="w-sdc-inputs-search-input" data-ng-model="search.filterTerm" placeholder="Search"
+ data-ng-model-options="{debounce: 200}"/>
+ <div class="search-icon-container">
+ <span class="w-sdc-search-icon inputs-search-icon magnification-white"></span>
+ </div>
+ </div>
+ <div class="table">
+ <div class="body">
+ <div class="table-header">Service inputs</div>
+ <perfect-scrollbar scroll-y-margin-offset="0" include-padding="true" class="scrollbar-container">
+ <expand-collapse expanded-selector=".service-inputs.{{$index}}"
+ class="expand-collapse-table-row"
+ load-data-function="loadInputInputs(serviceInput)"
+ is-close-on-init="true"
+ data-ng-repeat-start="serviceInput in component.inputs | filter:search track by $index ">
+ <input-row input="serviceInput" is-view-only='isViewOnly' instance-name='serviceInput.name'
+ delete-input='deleteInput(serviceInput)'
+ data-tests-id="service-input-{{$index}}"
+ class="service-input-row"
+ on-name-clicked="openEditValueModal(serviceInput)"
+ ng-class="serviceInput.isNew ? 'new-input': ''"
+ ></input-row>
+ </expand-collapse>
+
+ <div data-ng-repeat-end="" class="service-inputs {{$index}}">
+ <div ng-if="serviceInput.inputs.length > 0">
+ <expand-collapse expanded-selector=".input-inputs-list.{{$parent.$index}}-{{$index}}"
+ class="expand-collapse-table-row"
+ load-data-function="loadInputPropertiesForInstance(input.componentInstanceId, input)"
+ is-close-on-init="true"
+ data-ng-repeat-start="input in serviceInput.inputs track by $index">
+ <input-row input="input"
+ is-view-only='isViewOnly'
+ instance-name='input.componentInstanceName'></input-row>
+ </expand-collapse>
+
+ <div data-ng-repeat-end="" class="input-inputs-list {{$parent.$index}}-{{$index}}">
+ <div class="empty-row" ng-if="input.properties.length===0">No properties to display
+ </div>
+ <div ng-repeat="property in input.properties track by $index">
+ <property-row property="property" instance-name="property.name" is-clickable="false"></property-row>
+ </div>
+ </div>
+ </div>
+ <div ng-if="serviceInput.properties.length > 0">
+ <div class="empty-row" ng-if="serviceInput.properties.length===0">No properties to display</div>
+ <div ng-repeat="property in serviceInput.properties track by $index">
+ <property-row property="property" instance-name="property.name" is-clickable="false"></property-row>
+ </div>
+ </div>
+ </div>
+
+
+ </perfect-scrollbar>
+ </div>
+ </div>
+ </div>
+</div>
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/inputs/service-input/service-inputs.less b/catalog-ui/src/app/view-models/workspace/tabs/inputs/service-input/service-inputs.less
index 11e613b56e..f783d0b6d6 100644
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/inputs/service-input/service-inputs.less
+++ b/catalog-ui/src/app/view-models/workspace/tabs/inputs/service-input/service-inputs.less
@@ -32,22 +32,15 @@
border: none;
border-bottom: rgba(120, 136, 148, 0.26) solid 1px;
- .delete {
- width: 50px;
- padding: 0;
- position: relative;
+ &.service-input-row {
+ background: @tlv_color_u;
+ &.new-input {
+ background: @tlv_color_v;
+ }
}
+ }
- .remove-input-icon {
- position: absolute;
- top: 12px;
- right: 18px;
- }
- .remove-input-icon:hover {
- .delete-icon-hover;
- }
- }
}
}
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/management-workflow/management-workflow-view-model.ts b/catalog-ui/src/app/view-models/workspace/tabs/management-workflow/management-workflow-view-model.ts
index 2fab118378..b7428e990b 100644
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/management-workflow/management-workflow-view-model.ts
+++ b/catalog-ui/src/app/view-models/workspace/tabs/management-workflow/management-workflow-view-model.ts
@@ -1,32 +1,17 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-/// <reference path="../../../../references"/>
-module Sdc.ViewModels {
'use strict';
+ import {ArtifactType} from "app/utils";
+ import {ArtifactGroupModel} from "app/models";
+ import {participant} from "app/view-models/workspace/tabs/network-call-flow/network-call-flow-view-model";
+ import {IWorkspaceViewModelScope} from "app/view-models/workspace/workspace-view-model";
+ import {ComponentGenericResponse} from "../../../../ng2/services/responses/component-generic-response";
+ import {ComponentServiceNg2} from "../../../../ng2/services/component-services/component.service";
export interface IManagementWorkflowViewModelScope extends IWorkspaceViewModelScope {
vendorModel:VendorModel;
}
export class VendorModel {
- artifacts: Models.ArtifactGroupModel;
+ artifacts: ArtifactGroupModel;
serviceID: string;
readonly: boolean;
sessionID: string;
@@ -34,7 +19,7 @@ module Sdc.ViewModels {
diagramType: string;
participants:Array<participant>;
- constructor(artifacts: Models.ArtifactGroupModel, serviceID:string, readonly:boolean, sessionID:string,
+ constructor(artifacts: ArtifactGroupModel, serviceID:string, readonly:boolean, sessionID:string,
requestID:string, diagramType:string, participants:Array<participant>){
this.artifacts = artifacts;
this.serviceID = serviceID;
@@ -50,17 +35,32 @@ module Sdc.ViewModels {
static '$inject' = [
'$scope',
- 'uuid4'
+ 'uuid4',
+ 'ComponentServiceNg2'
];
constructor(private $scope:IManagementWorkflowViewModelScope,
- private uuid4:any) {
+ private uuid4:any,
+ private ComponentServiceNg2: ComponentServiceNg2) {
- this.initScope();
+ this.initInformationalArtifacts();
this.$scope.updateSelectedMenuItem();
}
+ private initInformationalArtifacts = ():void => {
+ if(!this.$scope.component.artifacts) {
+ this.$scope.isLoading = true;
+ this.ComponentServiceNg2.getComponentInformationalArtifacts(this.$scope.component).subscribe((response:ComponentGenericResponse) => {
+ this.$scope.component.artifacts = response.artifacts;
+ this.initScope();
+ this.$scope.isLoading = false;
+ });
+ } else {
+ this.initScope();
+ }
+ }
+
private static getParticipants():Array<participant> {
return [
{
@@ -112,12 +112,12 @@ module Sdc.ViewModels {
private initScope():void {
this.$scope.vendorModel = new VendorModel(
- this.$scope.component.artifacts.filteredByType(Utils.Constants.ArtifactType.THIRD_PARTY_RESERVED_TYPES.WORKFLOW),
+ this.$scope.component.artifacts.filteredByType(ArtifactType.THIRD_PARTY_RESERVED_TYPES.WORKFLOW),
this.$scope.component.uniqueId,
this.$scope.isViewMode(),
this.$scope.user.userId,
this.uuid4.generate(),
- Utils.Constants.ArtifactType.THIRD_PARTY_RESERVED_TYPES.WORKFLOW,
+ ArtifactType.THIRD_PARTY_RESERVED_TYPES.WORKFLOW,
ManagementWorkflowViewModel.getParticipants()
);
@@ -125,4 +125,3 @@ module Sdc.ViewModels {
this.$scope.setValidState(true);
}
}
-}
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/management-workflow/management-workflow-view.html b/catalog-ui/src/app/view-models/workspace/tabs/management-workflow/management-workflow-view.html
index bd196daec8..bd196daec8 100644
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/management-workflow/management-workflow-view.html
+++ b/catalog-ui/src/app/view-models/workspace/tabs/management-workflow/management-workflow-view.html
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
new file mode 100644
index 0000000000..511c17eb60
--- /dev/null
+++ b/catalog-ui/src/app/view-models/workspace/tabs/network-call-flow/network-call-flow-view-model.ts
@@ -0,0 +1,79 @@
+'use strict';
+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";
+import {ComponentInstance} from "app/models";
+import {ComponentGenericResponse} from "../../../../ng2/services/responses/component-generic-response";
+import {ComponentServiceNg2} from "../../../../ng2/services/component-services/component.service";
+
+export interface INetworkCallFlowViewModelScope extends IWorkspaceViewModelScope {
+ vendorMessageModel:VendorModel;
+}
+
+export class participant {
+ name:string;
+ id:string;
+
+ constructor(instance:ComponentInstance) {
+ this.name = instance.name;
+ this.id = instance.uniqueId;
+ }
+}
+
+
+export class NetworkCallFlowViewModel {
+
+ static '$inject' = [
+ '$scope',
+ 'uuid4',
+ 'ComponentServiceNg2'
+ ];
+
+ constructor(private $scope:INetworkCallFlowViewModelScope,
+ private uuid4:any,
+ private ComponentServiceNg2: ComponentServiceNg2) {
+
+ this.initComponentInstancesAndInformationalArtifacts();
+ this.$scope.updateSelectedMenuItem();
+ }
+
+ private getVFParticipantsFromInstances(instances:Array<ComponentInstance>):Array<participant> {
+ let participants = [];
+ _.forEach(instances, (instance)=> {
+ if (ResourceType.VF == instance.originType) {
+ participants.push(new participant(instance));
+ }
+ });
+ return participants;
+ }
+
+ private initComponentInstancesAndInformationalArtifacts = ():void => {
+ if(!this.$scope.component.artifacts || !this.$scope.component.componentInstances) {
+ this.$scope.isLoading = true;
+ this.ComponentServiceNg2.getComponentInformationalArtifactsAndInstances(this.$scope.component).subscribe((response:ComponentGenericResponse) => {
+ this.$scope.component.artifacts = response.artifacts;
+ this.$scope.component.componentInstances = response.componentInstances;
+ this.initScope();
+ this.$scope.isLoading = false;
+ });
+ } else {
+ this.initScope();
+ }
+ }
+
+ private initScope():void {
+ this.$scope.vendorMessageModel = new VendorModel(
+ this.$scope.component.artifacts.filteredByType(ArtifactType.THIRD_PARTY_RESERVED_TYPES.NETWORK_CALL_FLOW),
+ this.$scope.component.uniqueId,
+ this.$scope.isViewMode(),
+ this.$scope.user.userId,
+ this.uuid4.generate(),
+ ArtifactType.THIRD_PARTY_RESERVED_TYPES.NETWORK_CALL_FLOW,
+ this.getVFParticipantsFromInstances(this.$scope.component.componentInstances)
+ );
+
+ this.$scope.thirdParty = true;
+ this.$scope.setValidState(true);
+ }
+
+}
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/network-call-flow/network-call-flow-view.html b/catalog-ui/src/app/view-models/workspace/tabs/network-call-flow/network-call-flow-view.html
index 6ce3e8e2b7..6ce3e8e2b7 100644
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/network-call-flow/network-call-flow-view.html
+++ b/catalog-ui/src/app/view-models/workspace/tabs/network-call-flow/network-call-flow-view.html
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/product-hierarchy/product-hierarchy-view-model.ts b/catalog-ui/src/app/view-models/workspace/tabs/product-hierarchy/product-hierarchy-view-model.ts
new file mode 100644
index 0000000000..233b12952b
--- /dev/null
+++ b/catalog-ui/src/app/view-models/workspace/tabs/product-hierarchy/product-hierarchy-view-model.ts
@@ -0,0 +1,109 @@
+'use strict';
+import {ComponentFactory} from "app/utils";
+import {Product, IGroup, ISubCategory, IMainCategory} from "app/models";
+import {IWorkspaceViewModelScope} from "app/view-models/workspace/workspace-view-model";
+import {CacheService} from "app/services";
+
+export interface IProductHierarchyScope extends IWorkspaceViewModelScope {
+
+ categoriesOptions:Array<IMainCategory>;
+ product:Product;
+ isLoading:boolean;
+ showDropDown:boolean;
+
+ onInputTextClicked():void;
+ onGroupSelected(category:IMainCategory, subcategory:ISubCategory, group:IGroup):void;
+ clickOutside():void;
+ deleteGroup(uniqueId:string):void;
+}
+
+export class ProductHierarchyViewModel {
+
+ static '$inject' = [
+ '$scope',
+ 'Sdc.Services.CacheService',
+ 'ComponentFactory',
+ '$state'
+ ];
+
+ constructor(private $scope:IProductHierarchyScope,
+ private cacheService:CacheService,
+ private ComponentFactory:ComponentFactory,
+ private $state:ng.ui.IStateService) {
+
+
+ this.$scope.product = <Product>this.$scope.getComponent();
+ this.$scope.setValidState(true);
+ this.initScope();
+ this.$scope.updateSelectedMenuItem();
+ }
+
+ private initCategories = () => {
+ this.$scope.categoriesOptions = angular.copy(this.cacheService.get('productCategories'));
+ let selectedGroup:Array<IGroup> = [];
+ _.forEach(this.$scope.product.categories, (category:IMainCategory) => {
+ _.forEach(category.subcategories, (subcategory:ISubCategory) => {
+ selectedGroup = selectedGroup.concat(subcategory.groupings);
+ });
+ });
+ _.forEach(this.$scope.categoriesOptions, (category:IMainCategory) => {
+ _.forEach(category.subcategories, (subcategory:ISubCategory) => {
+ _.forEach(subcategory.groupings, (group:ISubCategory) => {
+ let componentGroup:IGroup = _.find(selectedGroup, (componentGroupObj) => {
+ return componentGroupObj.uniqueId == group.uniqueId;
+ });
+ if (componentGroup) {
+ group.isDisabled = true;
+ }
+ });
+ });
+ });
+ };
+
+ private setFormValidation = ():void => {
+
+ this.$scope.setValidState(true);
+
+ };
+
+ private initScope = ():void => {
+ this.$scope.isLoading = false;
+ this.$scope.showDropDown = false;
+ this.initCategories();
+ this.setFormValidation();
+
+ this.$scope.onGroupSelected = (category:IMainCategory, subcategory:ISubCategory, group:IGroup):void => {
+ this.$scope.product.addGroup(category, subcategory, group);
+ this.$state.current.data.unsavedChanges = !this.$scope.isViewMode();
+ group.isDisabled = true;
+ this.$scope.showDropDown = false;
+ this.setFormValidation();
+ };
+
+ this.$scope.onInputTextClicked = ():void => {//just edit the component in place, no pop up nor server update ?
+ this.$scope.showDropDown = !this.$scope.showDropDown;
+ };
+
+ this.$scope.clickOutside = ():any => {
+ this.$scope.showDropDown = false;
+ };
+
+ this.$scope.deleteGroup = (uniqueId:string):void => {
+ //delete group from component
+ this.$scope.product.deleteGroup(uniqueId);
+ this.$state.current.data.unsavedChanges = !this.$scope.isViewMode();
+ this.setFormValidation();
+ //enabled group
+ _.forEach(this.$scope.categoriesOptions, (category:IMainCategory) => {
+ _.forEach(category.subcategories, (subcategory:ISubCategory) => {
+ let groupObj:IGroup = _.find(subcategory.groupings, (group) => {
+ return group.uniqueId === uniqueId;
+ });
+ if (groupObj) {
+ groupObj.isDisabled = false;
+ }
+ });
+ });
+ }
+ };
+}
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/product-hierarchy/product-hierarchy-view.html b/catalog-ui/src/app/view-models/workspace/tabs/product-hierarchy/product-hierarchy-view.html
index 2335ad7c74..2335ad7c74 100644
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/product-hierarchy/product-hierarchy-view.html
+++ b/catalog-ui/src/app/view-models/workspace/tabs/product-hierarchy/product-hierarchy-view.html
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/product-hierarchy/product-hierarchy.less b/catalog-ui/src/app/view-models/workspace/tabs/product-hierarchy/product-hierarchy.less
index c992558ed2..c992558ed2 100644
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/product-hierarchy/product-hierarchy.less
+++ b/catalog-ui/src/app/view-models/workspace/tabs/product-hierarchy/product-hierarchy.less
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/properties/properties-view-model.ts b/catalog-ui/src/app/view-models/workspace/tabs/properties/properties-view-model.ts
new file mode 100644
index 0000000000..923cc58a7e
--- /dev/null
+++ b/catalog-ui/src/app/view-models/workspace/tabs/properties/properties-view-model.ts
@@ -0,0 +1,92 @@
+'use strict';
+import {IWorkspaceViewModelScope} from "app/view-models/workspace/workspace-view-model";
+import {PropertyModel} from "app/models";
+import {ModalsHandler} from "app/utils";
+import {COMPONENT_FIELDS} from "../../../../utils/constants";
+import {ComponentGenericResponse} from "../../../../ng2/services/responses/component-generic-response";
+import {ComponentServiceNg2} from "../../../../ng2/services/component-services/component.service";
+
+interface IPropertiesViewModelScope extends IWorkspaceViewModelScope {
+ tableHeadersList:Array<any>;
+ reverse:boolean;
+ sortBy:string;
+ filteredProperties:Array<PropertyModel>;
+
+ addOrUpdateProperty(property?:PropertyModel):void;
+ delete(property:PropertyModel):void;
+ sort(sortBy:string):void;
+}
+
+export class PropertiesViewModel {
+
+ static '$inject' = [
+ '$scope',
+ '$filter',
+ 'ModalsHandler',
+ 'ComponentServiceNg2'
+ ];
+
+
+ constructor(private $scope:IPropertiesViewModelScope,
+ private $filter:ng.IFilterService,
+ private ModalsHandler:ModalsHandler,
+ private ComponentServiceNg2:ComponentServiceNg2) {
+ this.initComponentProperties();
+ this.$scope.updateSelectedMenuItem();
+ }
+
+ private initComponentProperties = ():void => {
+
+ if(!this.$scope.component.properties) {
+ this.$scope.isLoading = true;
+ this.ComponentServiceNg2.getComponentProperties(this.$scope.component).subscribe((response:ComponentGenericResponse) => {
+ this.$scope.component.properties = response.properties;
+ this.initScope();
+ this.$scope.isLoading = false;
+ }, () => {
+ this.$scope.isLoading = false;
+ });
+ } else {
+ this.initScope();
+ }
+ }
+
+ private openEditPropertyModal = (property:PropertyModel):void => {
+ this.ModalsHandler.openEditPropertyModal(property, this.$scope.component, this.$scope.filteredProperties, false).then(() => {
+ });
+ };
+
+ private initScope = ():void => {
+
+ //let self = this;
+ this.$scope.filteredProperties = this.$scope.component.properties;
+ this.$scope.sortBy = 'name';
+ this.$scope.reverse = false;
+ this.$scope.setValidState(true);
+ this.$scope.tableHeadersList = [
+ {title: 'Name', property: 'name'},
+ {title: 'Type', property: 'type'},
+ {title: 'Schema', property: 'schema.property.type'},
+ {title: 'Description', property: 'description'},
+ ];
+ this.$scope.sort = (sortBy:string):void => {
+ this.$scope.reverse = (this.$scope.sortBy === sortBy) ? !this.$scope.reverse : false;
+ this.$scope.sortBy = sortBy;
+ };
+
+
+ this.$scope.addOrUpdateProperty = (property?:PropertyModel):void => {
+ this.openEditPropertyModal(property ? property : new PropertyModel());
+ };
+
+ this.$scope.delete = (property:PropertyModel):void => {
+
+ let onOk = ():void => {
+ this.$scope.component.deleteProperty(property.uniqueId);
+ };
+ let title:string = this.$filter('translate')("PROPERTY_VIEW_DELETE_MODAL_TITLE");
+ let message:string = this.$filter('translate')("PROPERTY_VIEW_DELETE_MODAL_TEXT", "{'name': '" + property.name + "'}");
+ this.ModalsHandler.openConfirmationModal(title, message, false).then(onOk);
+ };
+ }
+}
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/properties/properties-view.html b/catalog-ui/src/app/view-models/workspace/tabs/properties/properties-view.html
index e9a4c3879d..d1e0582386 100644
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/properties/properties-view.html
+++ b/catalog-ui/src/app/view-models/workspace/tabs/properties/properties-view.html
@@ -23,30 +23,27 @@
<span ng-if="!isViewMode()"> click <a data-ng-click="addOrUpdateProperty()">here</a> to add one </span>
</div>
- <div data-ng-repeat="property in filteredProperties.properties=(component.properties | orderBy:sortBy:reverse | filter: {filterTerm:filterTerms}) track by $index"
+ <div data-ng-repeat="property in filteredProperties=(component.properties | orderBy:sortBy:reverse | filter: {filterTerm:filterTerms}) track by $index"
data-tests-id="propertyRow" data-ng-class="{'selected': property.selected}"
class="flex-container data-row">
- <div class="table-col-general flex-item text">
- <a data-tests-id="{{property.name}}"
- tooltips tooltip-content="{{property.name}}"
+ <div class="table-col-general flex-item text" tooltips tooltip-content="{{property.name}}">
+ <a data-tests-id="propertyName_{{property.name}}"
data-ng-click="addOrUpdateProperty(property); $event.stopPropagation();"
data-ng-class="{'disabled': isViewMode()}">{{property.name}}</a>
</div>
<div class="table-col-general flex-item text"
- data-tests-id="{{property.type}}"
- tooltips tooltip-content="{{property.type}}"
- data-ng-bind="property.type">
+ tooltips tooltip-content="{{property.type}}">
+ <span data-tests-id="propertyType_{{property.name}}"> {{property.type.replace("org.openecomp.datatypes.heat.","")}}</span>
</div>
<div class="table-col-general flex-item text"
- data-tests-id="{{property.schema.property.type}}"
- tooltips tooltip-content="{{property.schema.property.type}}"
- data-ng-bind="property.schema.property.type">
+ tooltips tooltip-content="{{property.schema.property.type}}">
+ <span data-tests-id="propertySchema_{{property.name}}"> {{property.schema.property.type.replace("org.openecomp.datatypes.heat.","")}}</span>
</div>
- <div class="table-col-general flex-item text">
- <span tooltips tooltip-content="{{property.description}}" data-tests-id="{{property.description}}" data-ng-bind="property.description"></span>
+ <div class="table-col-general flex-item text" tooltips tooltip-content="{{property.description}}">
+ <span data-tests-id="propertyDescription_{{property.name}}" data-ng-bind="property.description"></span>
</div>
<div class="table-btn-col flex-item" ng-if="!isViewMode()">
<button class="table-delete-btn" data-tests-id="delete_{{property.name}}" data-ng-if="property.parentUniqueId==component.uniqueId"
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/properties/properties.less b/catalog-ui/src/app/view-models/workspace/tabs/properties/properties.less
index 3e8d6c3fbd..3e8d6c3fbd 100644
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/properties/properties.less
+++ b/catalog-ui/src/app/view-models/workspace/tabs/properties/properties.less
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
new file mode 100644
index 0000000000..4ac99edf8a
--- /dev/null
+++ b/catalog-ui/src/app/view-models/workspace/tabs/req-and-capabilities/req-and-capabilities-view-model.ts
@@ -0,0 +1,147 @@
+/**
+ * Created by rcohen on 9/22/2016.
+ */
+'use strict';
+import {IWorkspaceViewModelScope} from "app/view-models/workspace/workspace-view-model";
+import {ModalsHandler} from "app/utils";
+import {Capability, PropertyModel, Requirement} from "app/models";
+import {ComponentGenericResponse} from "../../../../ng2/services/responses/component-generic-response";
+import {ComponentServiceNg2} from "../../../../ng2/services/component-services/component.service";
+
+export class SortTableDefined {
+ reverse:boolean;
+ sortByField:string;
+}
+
+interface IReqAndCapabilitiesViewModelScope extends IWorkspaceViewModelScope {
+ requirementsTableHeadersList:Array<any>;
+ capabilitiesTableHeadersList:Array<any>;
+ capabilityPropertiesTableHeadersList:Array<any>;
+ requirementsSortTableDefined:SortTableDefined;
+ capabilitiesSortTableDefined:SortTableDefined;
+ propertiesSortTableDefined:SortTableDefined;
+ requirements:Array<Requirement>;
+ capabilities:Array<Capability>;
+ mode:string;
+ filteredProperties:Array<Array<PropertyModel>>;
+ searchText:string;
+
+ sort(sortBy:string, sortByTableDefined:SortTableDefined):void;
+ updateProperty(property:PropertyModel, indexInFilteredProperties:number):void;
+ allCapabilitiesSelected(selected:boolean):void;
+}
+
+export class ReqAndCapabilitiesViewModel {
+
+ static '$inject' = [
+ '$scope',
+ '$filter',
+ 'ModalsHandler',
+ 'ComponentServiceNg2'
+ ];
+
+
+ constructor(private $scope:IReqAndCapabilitiesViewModelScope,
+ private $filter:ng.IFilterService,
+ private ModalsHandler:ModalsHandler,
+ private ComponentServiceNg2: ComponentServiceNg2) {
+
+ this.initCapabilitiesAndRequirements();
+ this.$scope.updateSelectedMenuItem();
+ }
+
+ private initCapabilitiesAndRequirements = (): void => {
+
+ if(!this.$scope.component.capabilities || !this.$scope.component.requirements) {
+ this.$scope.isLoading = true;
+ this.ComponentServiceNg2.getCapabilitiesAndRequirements(this.$scope.component.componentType, this.$scope.component.uniqueId).subscribe((response:ComponentGenericResponse) => {
+ this.$scope.component.capabilities = response.capabilities;
+ this.$scope.component.requirements = response.requirements;
+ this.initScope();
+ this.$scope.isLoading = false;
+ }, () => {
+ this.$scope.isLoading = false;
+ });
+ } else {
+ this.initScope();
+ }
+
+ }
+
+ private openEditPropertyModal = (property:PropertyModel, indexInFilteredProperties:number):void => {
+ //...because there is not be api
+ _.forEach(this.$scope.filteredProperties[indexInFilteredProperties], (prop:PropertyModel)=> {
+ prop.readonly = true;
+ });
+ this.ModalsHandler.openEditPropertyModal(property, this.$scope.component, this.$scope.filteredProperties[indexInFilteredProperties], false).then(() => {
+
+ });
+ };
+
+ private initScope = ():void => {
+
+ this.$scope.requirementsSortTableDefined = {
+ reverse: false,
+ sortByField: 'name'
+ };
+ this.$scope.capabilitiesSortTableDefined = {
+ reverse: false,
+ sortByField: 'name'
+ };
+ this.$scope.propertiesSortTableDefined = {
+ reverse: false,
+ sortByField: 'name'
+ };
+
+ this.$scope.setValidState(true);
+ this.$scope.requirementsTableHeadersList = [
+ {title: 'Name', property: 'name'},
+ {title: 'Capability', property: 'capability'},
+ {title: 'Node', property: 'node'},
+ {title: 'Relationship', property: 'relationship'},
+ {title: 'Connected To', property: ''},
+ {title: 'Occurrences', property: ''}
+ ];
+ this.$scope.capabilitiesTableHeadersList = [
+ {title: 'Name', property: 'name'},
+ {title: 'Type', property: 'type'},
+ {title: 'Description', property: ''},
+ {title: 'Valid Source', property: ''},
+ {title: 'Occurrences', property: ''}
+ ];
+ this.$scope.capabilityPropertiesTableHeadersList = [
+ {title: 'Name', property: 'name'},
+ {title: 'Type', property: 'type'},
+ {title: 'Schema', property: 'schema.property.type'},
+ {title: 'Description', property: 'description'},
+ ];
+ this.$scope.filteredProperties = [];
+
+ this.$scope.mode = 'requirements';
+ this.$scope.requirements = [];
+ _.forEach(this.$scope.component.requirements, (req:Array<Requirement>, capName)=> {
+ this.$scope.requirements = this.$scope.requirements.concat(req);
+ });
+
+ this.$scope.capabilities = [];
+ _.forEach(this.$scope.component.capabilities, (cap:Array<Capability>, capName)=> {
+ this.$scope.capabilities = this.$scope.capabilities.concat(cap);
+ });
+
+ this.$scope.sort = (sortBy:string, sortByTableDefined:SortTableDefined):void => {
+ sortByTableDefined.reverse = (sortByTableDefined.sortByField === sortBy) ? !sortByTableDefined.reverse : false;
+ sortByTableDefined.sortByField = sortBy;
+ };
+
+ this.$scope.updateProperty = (property:PropertyModel, indexInFilteredProperties:number):void => {
+ this.openEditPropertyModal(property, indexInFilteredProperties);
+ };
+
+ this.$scope.allCapabilitiesSelected = (selected:boolean):void => {
+ _.forEach(this.$scope.capabilities, (cap:Capability)=> {
+ cap.selected = selected;
+ });
+ };
+ }
+}
+
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/req-and-capabilities/req-and-capabilities-view.html b/catalog-ui/src/app/view-models/workspace/tabs/req-and-capabilities/req-and-capabilities-view.html
index 047768689a..3d6ccb9d00 100644
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/req-and-capabilities/req-and-capabilities-view.html
+++ b/catalog-ui/src/app/view-models/workspace/tabs/req-and-capabilities/req-and-capabilities-view.html
@@ -30,21 +30,21 @@
<div data-ng-repeat="req in requirements | orderBy:requirementsSortTableDefined.sortByField:requirementsSortTableDefined.reverse | filter: {filterTerm:filterTerms} track by $index"
class="flex-container data-row" data-tests-id="reqRow">
- <div class="table-col-general flex-item text">
- <span data-tests-id="{{req.name}}" tooltips tooltip-content="{{req.name}}">{{req.name}}</span>
+ <div class="table-col-general flex-item text" tooltips tooltip-content="{{req.name}}">
+ <span data-tests-id="{{req.name}}">{{req.name}}</span>
</div>
- <div class="table-col-general flex-item text">
- <span data-tests-id="{{req.capability}}" tooltips tooltip-content="{{req.capability}}">{{req.capability.substring("tosca.capabilities.".length)}}</span>
+ <div class="table-col-general flex-item text" tooltips tooltip-content="{{req.capability}}">
+ <span data-tests-id="{{req.capability}}">{{req.capability.substring("tosca.capabilities.".length)}}</span>
</div>
- <div class="table-col-general flex-item text">
- <span data-tests-id="{{req.node}}" tooltips tooltip-content="{{req.node}}">{{req.node.substring("tosca.nodes.".length)}}</span>
+ <div class="table-col-general flex-item text" tooltips tooltip-content="{{req.node}}">
+ <span data-tests-id="{{req.node}}">{{req.node.substring("tosca.nodes.".length)}}</span>
</div>
- <div class="table-col-general flex-item text">
- <span data-tests-id="{{req.relationship}}" tooltips tooltip-content="{{req.relationship}}">{{req.relationship.substring("tosca.relationships.".length)}}</span>
+ <div class="table-col-general flex-item text" tooltips tooltip-content="{{req.relationship}}">
+ <span data-tests-id="{{req.relationship}}">{{req.relationship.substring("tosca.relationships.".length)}}</span>
</div>
<div class="table-col-general flex-item text" data-tests-id="{{}}" data-ng-bind=""></div>
- <div class="table-col-general flex-item text">
- <span data-tests-id="{{req.minOccurrences}},{{req.maxOccurrences}}" tooltips tooltip-content="{{req.minOccurrences}},{{req.maxOccurrences}}">{{req.minOccurrences}},{{req.maxOccurrences}}</span>
+ <div class="table-col-general flex-item text" tooltips tooltip-content="{{req.minOccurrences}},{{req.maxOccurrences}}">
+ <span data-tests-id="{{req.minOccurrences}},{{req.maxOccurrences}}">{{req.minOccurrences}},{{req.maxOccurrences}}</span>
</div>
</div>
</perfect-scrollbar>
@@ -70,24 +70,24 @@
class="flex-container data-row" data-ng-class="{'selected': capability.selected}"
data-ng-click="capability.selected = !capability.selected" data-tests-id="capabilities-table-row">
- <div class="table-col-general flex-item text">
+ <div class="table-col-general flex-item text" tooltips tooltip-content="{{capability.name}}">
<span class="sprite-new arrow-up-small" data-ng-class="{'opened': capability.selected}"></span>
- <span data-tests-id="{{capability.name}}" tooltips tooltip-content="{{capability.name}}">{{capability.name}}</span>
+ <span data-tests-id="{{capability.name}}">{{capability.name}}</span>
</div>
- <div class="table-col-general flex-item text">
- <span data-tests-id="{{capability.type}}" tooltips tooltip-content="{{capability.type}}">{{capability.type.substring("tosca.capabilities.".length)}}</span>
+ <div class="table-col-general flex-item text" tooltips tooltip-content="{{capability.type}}">
+ <span data-tests-id="{{capability.type}}">{{capability.type.replace("tosca.capabilities.","")}}</span>
</div>
- <div class="table-col-general flex-item text">
- <span data-tests-id="{{capability.description}}" tooltips tooltip-content="{{capability.description}}">{{capability.description}}</span>
+ <div class="table-col-general flex-item text" tooltips tooltip-content="{{capability.description}}">
+ <span data-tests-id="{{capability.description}}">{{capability.description}}</span>
</div>
- <div class="table-col-general flex-item text">
- <span data-tests-id="{{capability.validSourceTypes.join(',')}}" tooltips tooltip-content="{{capability.validSourceTypes.join(',')}}">{{capability.validSourceTypes.join(',')}}</span>
+ <div class="table-col-general flex-item text" tooltips tooltip-content="{{capability.validSourceTypes.join(',')}}">
+ <span data-tests-id="{{capability.validSourceTypes.join(',')}}">{{capability.validSourceTypes.join(',')}}</span>
</div>
- <div class="table-col-general flex-item text">
- <span data-tests-id="{{capability.minOccurrences}},{{capability.maxOccurrences}}" tooltips tooltip-content="{{capability.minOccurrences}},{{capability.maxOccurrences}}">{{capability.minOccurrences}},{{capability.maxOccurrences}}</span>
+ <div class="table-col-general flex-item text" tooltips tooltip-content="{{capability.minOccurrences}},{{capability.maxOccurrences}}">
+ <span data-tests-id="{{capability.minOccurrences}},{{capability.maxOccurrences}}">{{capability.minOccurrences}},{{capability.maxOccurrences}}</span>
</div>
</div>
<div data-ng-repeat-end="" data-ng-if="capability.selected" class="item-opened">
@@ -108,9 +108,8 @@
data-tests-id="propertyRow"
class="flex-container data-row">
- <div class="table-col-general flex-item text">
+ <div class="table-col-general flex-item text" tooltips tooltip-content="{{property.name}}">
<a data-tests-id="{{property.name}}"
- tooltips tooltip-content="{{property.name}}"
data-ng-click="updateProperty(property, $parent.$index); $event.stopPropagation();"
data-ng-class="{'disabled': isViewMode()}">{{property.name}}</a>
@@ -126,8 +125,8 @@
tooltips tooltip-content="{{property.schema.property.type}}"
data-ng-bind="property.schema.property.type">
</div>
- <div class="table-col-general flex-item text">
- <span tooltips tooltip-content="{{property.description}}" data-tests-id="{{property.description}}" data-ng-bind="property.description"></span>
+ <div class="table-col-general flex-item text" tooltips tooltip-content="{{property.description}}">
+ <span data-tests-id="{{property.description}}" data-ng-bind="property.description"></span>
</div>
</div>
</div>
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/req-and-capabilities/req-and-capabilities.less b/catalog-ui/src/app/view-models/workspace/tabs/req-and-capabilities/req-and-capabilities.less
index 9b52fad411..9b52fad411 100644
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/req-and-capabilities/req-and-capabilities.less
+++ b/catalog-ui/src/app/view-models/workspace/tabs/req-and-capabilities/req-and-capabilities.less
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
new file mode 100644
index 0000000000..06022786ee
--- /dev/null
+++ b/catalog-ui/src/app/view-models/workspace/tabs/tosca-artifacts/tosca-artifacts-view-model.ts
@@ -0,0 +1,84 @@
+'use strict';
+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>;
+ artifactType:string;
+ downloadFile:IFileDownload;
+ isLoading:boolean;
+ sortBy:string;
+ reverse:boolean;
+
+ getTitle():string;
+ download(artifact:ArtifactModel):void;
+ sort(sortBy:string):void;
+ showNoArtifactMessage():boolean;
+}
+
+export class ToscaArtifactsViewModel {
+
+ static '$inject' = [
+ '$scope',
+ '$filter',
+ 'ComponentServiceNg2'
+ ];
+
+ constructor(private $scope:IToscaArtifactsScope,
+ private $filter:ng.IFilterService,
+ private ComponentServiceNg2:ComponentServiceNg2) {
+ this.initToscaArtifacts();
+ this.$scope.updateSelectedMenuItem();
+ }
+
+ private initToscaArtifacts = (): void => {
+
+ if(!this.$scope.component.toscaArtifacts) {
+ this.$scope.isLoading = true;
+ this.ComponentServiceNg2.getComponentToscaArtifacts(this.$scope.component).subscribe((response:ComponentGenericResponse) => {
+ this.$scope.component.toscaArtifacts = response.toscaArtifacts;
+ this.initScope();
+ this.$scope.isLoading = false;
+ }, () => {
+ this.$scope.isLoading = false;
+ });
+ } else {
+ this.initScope();
+ }
+ }
+
+ private initScope = ():void => {
+ this.$scope.isLoading = false;
+ this.$scope.sortBy = 'artifactDisplayName';
+ this.$scope.reverse = false;
+ this.$scope.setValidState(true);
+ this.$scope.artifactType = 'informational';
+ this.$scope.getTitle = ():string => {
+ return this.$filter("resourceName")(this.$scope.component.name) + ' Artifacts';
+
+ };
+
+ this.$scope.tableHeadersList = [
+ {title: 'Name', property: 'artifactDisplayName'},
+ {title: 'Type', property: 'artifactType'},
+ {title: 'Version', property: 'artifactVersion'}
+ ];
+
+ this.$scope.artifacts = <ArtifactModel[]>_.values(this.$scope.component.toscaArtifacts);
+ this.$scope.sort = (sortBy:string):void => {
+ this.$scope.reverse = (this.$scope.sortBy === sortBy) ? !this.$scope.reverse : false;
+ this.$scope.sortBy = sortBy;
+ };
+
+
+ this.$scope.showNoArtifactMessage = ():boolean => {
+ if (this.$scope.artifacts.length === 0) {
+ return true;
+ }
+ return false;
+ };
+
+ }
+}
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/tosca-artifacts/tosca-artifacts-view.html b/catalog-ui/src/app/view-models/workspace/tabs/tosca-artifacts/tosca-artifacts-view.html
index 947b37db93..5df6b5c11f 100644
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/tosca-artifacts/tosca-artifacts-view.html
+++ b/catalog-ui/src/app/view-models/workspace/tabs/tosca-artifacts/tosca-artifacts-view.html
@@ -13,24 +13,28 @@
There are no TOSCA artifacts to display
</div>
<div data-ng-repeat-start="artifact in artifacts| orderBy:sortBy:reverse track by $index"
- class="flex-container data-row"
+ class="flex-container data-row" data-tests-id="{{artifact.artifactDisplayName}}"
data-ng-class="{'selected': artifact.selected}">
- <div class="table-col-general flex-item" data-ng-click="artifact.selected = !artifact.selected">
- <span class="sprite table-arrow" data-ng-class="{'opened': artifact.selected}" data-tests-id="{{artifact.artifactDisplayName}}"></span>
+ <div class="table-col-general flex-item" data-ng-click="artifact.selected = !artifact.selected" data-tests-id="name-{{$index}}">
+ <span class="sprite table-arrow" data-ng-class="{'opened': artifact.selected}"></span>
{{artifact.artifactDisplayName}}
</div>
- <div class="table-col-general flex-item" data-ng-click="artifact.selected = !artifact.selected" data-tests-id="{{artifact.artifactType}}">
+ <div class="table-col-general flex-item" data-ng-click="artifact.selected = !artifact.selected" data-tests-id="type-{{$index}}">
{{artifact.artifactType}}
</div>
+ <div class="table-col-general flex-item" data-ng-click="artifact.selected = !artifact.selected" data-tests-id="version-{{$index}}">
+ {{artifact.artifactVersion}}
+ </div>
+
<div class="table-btn-col flex-item download-icon-container">
- <button class="table-download-btn tosca" download-artifact data-tests-id="download_{{artifact.artifactDisplayName}}"
+ <button class="table-download-btn tosca" download-artifact data-tests-id="download-{{artifact.artifactDisplayName}}"
data-ng-if="artifact.artifactName" component="component" artifact="artifact" show-loader="true"></button>
</div>
</div>
- <div data-ng-repeat-end="" data-ng-if="artifact.selected" class="item-opened">
+ <div data-ng-repeat-end="" data-ng-if="artifact.selected" class="item-opened" data-tests-id="details-{{$index}}">
<div><span class="details-title">Label:</span> {{artifact.artifactLabel}}</div>
<div><span class="details-title">UUID:</span> {{artifact.uniqueId}}</div>
<div><span class="details-title">Description:</span> {{artifact.description}}</div>
diff --git a/catalog-ui/app/scripts/view-models/workspace/tabs/tosca-artifacts/tosca-artifacts.less b/catalog-ui/src/app/view-models/workspace/tabs/tosca-artifacts/tosca-artifacts.less
index f792bb8c53..6dfec2980f 100644
--- a/catalog-ui/app/scripts/view-models/workspace/tabs/tosca-artifacts/tosca-artifacts.less
+++ b/catalog-ui/src/app/view-models/workspace/tabs/tosca-artifacts/tosca-artifacts.less
@@ -41,6 +41,10 @@
flex-grow: 1;
}
+ .flex-item:nth-child(4) {
+ flex-grow: 1;
+ }
+
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
new file mode 100644
index 0000000000..ff4636e002
--- /dev/null
+++ b/catalog-ui/src/app/view-models/workspace/workspace-view-model.ts
@@ -0,0 +1,718 @@
+/**
+ * Created by obarda on 3/30/2016.
+ */
+'use strict';
+import {IUserProperties, IAppMenu, Resource, Component} from "app/models";
+import {
+ WorkspaceMode, ComponentFactory, ChangeLifecycleStateHandler, Role, ComponentState, MenuItemGroup, MenuHandler,
+ MenuItem, ModalsHandler, States, EVENTS, CHANGE_COMPONENT_CSAR_VERSION_FLAG, ResourceType
+} from "app/utils";
+import {
+ EventListenerService,
+ EntityService,
+ ProgressService,
+ CacheService,
+ LeftPaletteLoaderService
+} from "app/services";
+import {FileUploadModel} from "../../directives/file-upload/file-upload";
+
+
+export interface IWorkspaceViewModelScope extends ng.IScope {
+
+ isLoading:boolean;
+ isCreateProgress:boolean;
+ component:Component;
+ originComponent:Component;
+ componentType:string;
+ importFile:any;
+ leftBarTabs:MenuItemGroup;
+ isNew:boolean;
+ isFromImport:boolean;
+ isValidForm:boolean;
+ mode:WorkspaceMode;
+ breadcrumbsModel:Array<MenuItemGroup>;
+ sdcMenu:IAppMenu;
+ changeLifecycleStateButtons:any;
+ version:string;
+ versionsList:Array<any>;
+ changeVersion:any;
+ isComposition:boolean;
+ isDeployment:boolean;
+ $state:ng.ui.IStateService;
+ user:IUserProperties;
+ thirdParty:boolean;
+ disabledButtons:boolean;
+ menuComponentTitle:string;
+ progressService:ProgressService;
+ progressMessage:string;
+ // leftPanelComponents:Array<Models.Components.Component>; //this is in order to load the left panel once, and not wait long time when moving to composition
+
+ showChangeStateButton():boolean;
+ getComponent():Component;
+ setComponent(component:Component):void;
+ onMenuItemPressed(state:string):ng.IPromise<boolean>;
+ save():ng.IPromise<boolean>;
+ setValidState(isValid:boolean):void;
+ revert():void;
+ changeLifecycleState(state:string):void;
+ enabledTabs():void
+ isDesigner():boolean;
+ isProductManager():boolean;
+ isViewMode():boolean;
+ isEditMode():boolean;
+ isCreateMode():boolean;
+ isDisableMode():boolean;
+ showFullIcons():boolean;
+ goToBreadcrumbHome():void;
+ onVersionChanged(selectedId:string):void;
+ getLatestVersion():void;
+ getStatus():string;
+ showLifecycleIcon():boolean;
+ updateSelectedMenuItem():void;
+ uploadFileChangedInGeneralTab():void;
+ updateMenuComponentName(ComponentName:string):void;
+}
+
+export class WorkspaceViewModel {
+
+ static '$inject' = [
+ '$scope',
+ 'injectComponent',
+ 'ComponentFactory',
+ '$state',
+ 'sdcMenu',
+ '$q',
+ 'MenuHandler',
+ 'Sdc.Services.CacheService',
+ 'ChangeLifecycleStateHandler',
+ 'ModalsHandler',
+ 'LeftPaletteLoaderService',
+ '$filter',
+ 'EventListenerService',
+ 'Sdc.Services.EntityService',
+ 'Notification',
+ '$stateParams',
+ 'Sdc.Services.ProgressService'
+ ];
+
+ constructor(private $scope:IWorkspaceViewModelScope,
+ private injectComponent:Component,
+ private ComponentFactory:ComponentFactory,
+ private $state:ng.ui.IStateService,
+ private sdcMenu:IAppMenu,
+ private $q:ng.IQService,
+ private MenuHandler:MenuHandler,
+ private cacheService:CacheService,
+ private ChangeLifecycleStateHandler:ChangeLifecycleStateHandler,
+ private ModalsHandler:ModalsHandler,
+ private LeftPaletteLoaderService:LeftPaletteLoaderService,
+ private $filter:ng.IFilterService,
+ private EventListenerService:EventListenerService,
+ private EntityService:EntityService,
+ private Notification:any,
+ private $stateParams:any,
+ private progressService:ProgressService) {
+
+ this.initScope();
+ this.initAfterScope();
+ }
+
+ private role:string;
+ private components:Array<Component>;
+
+ private initViewMode = ():WorkspaceMode => {
+ let mode = WorkspaceMode.VIEW;
+
+ if (!this.$state.params['id']) { //&& !this.$state.params['vspComponent']
+ mode = WorkspaceMode.CREATE;
+ } else {
+ if (this.$scope.component.lifecycleState === ComponentState.NOT_CERTIFIED_CHECKOUT &&
+ this.$scope.component.lastUpdaterUserId === this.cacheService.get("user").userId) {
+ if (this.$scope.component.isProduct() && this.role == Role.PRODUCT_MANAGER) {
+ mode = WorkspaceMode.EDIT;
+ }
+ if ((this.$scope.component.isService() || this.$scope.component.isResource()) && this.role == Role.DESIGNER) {
+ mode = WorkspaceMode.EDIT;
+ }
+ }
+ }
+ return mode;
+ };
+
+ private initChangeLifecycleStateButtons = ():void => {
+ let state = this.$scope.component.isService() && (Role.OPS == this.role || Role.GOVERNOR == this.role) ? this.$scope.component.distributionStatus : this.$scope.component.lifecycleState;
+ this.$scope.changeLifecycleStateButtons = this.sdcMenu.roles[this.role].changeLifecycleStateButtons[state];
+ };
+
+ private isNeedSave = ():boolean => {
+ return this.$scope.isEditMode() &&
+ this.$state.current.data && this.$state.current.data.unsavedChanges;
+ };
+
+ private initLeftPalette = ():void => {
+ this.LeftPaletteLoaderService.loadLeftPanel(this.$scope.component.componentType);
+ };
+
+ private initScope = ():void => {
+
+ this.$scope.component = this.injectComponent;
+ this.initLeftPalette();
+ this.$scope.menuComponentTitle = this.$scope.component.name;
+ this.$scope.disabledButtons = false;
+ this.$scope.originComponent = this.ComponentFactory.createComponent(this.$scope.component);
+ this.$scope.componentType = this.$scope.component.componentType;
+ this.$scope.version = this.cacheService.get('version');
+ this.$scope.user = this.cacheService.get("user");
+ this.role = this.$scope.user.role;
+ this.$scope.mode = this.initViewMode();
+ this.$scope.isValidForm = true;
+ this.initChangeLifecycleStateButtons();
+ this.initVersionObject();
+ this.$scope.$state = this.$state;
+ this.$scope.isLoading = false;
+ this.$scope.isComposition = (this.$state.current.name.indexOf(States.WORKSPACE_COMPOSITION) > -1);
+ this.$scope.isDeployment = (this.$state.current.name.indexOf(States.WORKSPACE_DEPLOYMENT) > -1);
+ this.$scope.progressService = this.progressService;
+
+ this.$scope.getComponent = ():Component => {
+ return this.$scope.component;
+ };
+
+ this.$scope.updateMenuComponentName = (ComponentName:string):void => {
+ this.$scope.menuComponentTitle = ComponentName;
+ };
+
+ this.$scope.sdcMenu = this.sdcMenu;
+ // Will be called from each step after save to update the resource.
+ this.$scope.setComponent = (component:Component):void => {
+ this.$scope.component = component;
+ };
+
+ this.$scope.uploadFileChangedInGeneralTab = ():void => {
+ // In case user select browse file, and in update mode, need to disable submit for testing and checkin buttons.
+ if (this.$scope.isEditMode() && this.$scope.component.isResource() && (<Resource>this.$scope.component).resourceType == ResourceType.VF) {
+ this.$scope.disabledButtons = true;
+ }
+ };
+
+ this.$scope.onMenuItemPressed = (state:string):ng.IPromise<boolean> => {
+ let deferred = this.$q.defer();
+ let goToState = ():void => {
+ this.$state.go(state, {
+ id: this.$scope.component.uniqueId,
+ type: this.$scope.component.componentType.toLowerCase(),
+ components: this.components
+ });
+ deferred.resolve(true);
+ };
+ if (this.isNeedSave()) {
+ if (this.$scope.isValidForm) {
+ this.$scope.save().then(goToState);
+ } else {
+ console.log('form is not valid');
+ deferred.reject(false);
+ }
+ } else if (this.$scope.isEditMode() && //this is a workaround for amdocs - we need to get the artifact in order to avoid saving the vf when moving from their tabs
+ (this.$state.current.name === States.WORKSPACE_MANAGEMENT_WORKFLOW || this.$state.current.name === States.WORKSPACE_NETWORK_CALL_FLOW)) {
+ let onGetSuccess = (component:Component) => {
+ this.$scope.isLoading = false;
+ // Update the components
+ this.$scope.component = component;
+ goToState();
+ };
+ let onFailed = () => {
+ this.EventListenerService.notifyObservers(EVENTS.ON_WORKSPACE_SAVE_BUTTON_ERROR);
+ this.$scope.isLoading = false; // stop the progress.
+ deferred.reject(false);
+ };
+ this.$scope.component.getComponent().then(onGetSuccess, onFailed);
+ } else {
+ goToState();
+ }
+ return deferred.promise;
+ };
+
+ this.$scope.setValidState = (isValid:boolean):void => {
+ this.$scope.isValidForm = isValid;
+ };
+
+ this.$scope.onVersionChanged = (selectedId:string):void => {
+ if (this.$state.current.data && this.$state.current.data.unsavedChanges) {
+ this.$scope.changeVersion.selectedVersion = _.find(this.$scope.versionsList, {versionId: this.$scope.component.uniqueId});
+ }
+ this.$scope.isLoading = true;
+ this.$state.go(this.$state.current.name, {
+ id: selectedId,
+ type: this.$scope.componentType.toLowerCase(),
+ mode: WorkspaceMode.VIEW,
+ components: this.$state.params['components']
+ });
+
+ };
+
+ this.$scope.getLatestVersion = ():void => {
+ this.$scope.onVersionChanged(_.first(this.$scope.versionsList).versionId);
+ };
+
+ this.$scope.save = (state?:string):ng.IPromise<boolean> => {
+ this.EventListenerService.notifyObservers(EVENTS.ON_WORKSPACE_SAVE_BUTTON_CLICK);
+
+ this.progressService.initCreateComponentProgress(this.$scope.component.uniqueId);
+
+ let deferred = this.$q.defer();
+ let modalInstance:ng.ui.bootstrap.IModalServiceInstance;
+
+ let onFailed = () => {
+ _.first(this.$scope.leftBarTabs.menuItems).isDisabled = false;//enabled click on general tab (DE246274)
+ this.EventListenerService.notifyObservers(EVENTS.ON_WORKSPACE_SAVE_BUTTON_ERROR);
+ this.progressService.deleteProgressValue(this.$scope.component.uniqueId);
+ modalInstance && modalInstance.close(); // Close the modal in case it is opened.
+ this.$scope.component.tags = _.without(this.$scope.component.tags, this.$scope.component.name);// for fix DE246217
+ this.$scope.isCreateProgress = false;
+ this.$scope.isLoading = false; // stop the progress.
+
+ this.$scope.setValidState(true); // Set the form valid (if sent form is valid, the error from server).
+ if (!this.$scope.isCreateMode()) {
+ this.$scope.component = this.ComponentFactory.createComponent(this.$scope.originComponent); // Set the component back to the original.
+ this.enableMenuItems(); // Enable the menu items (left tabs), so user can press on them.
+ this.$scope.disabledButtons = false; // Enable "submit for testing" & checking buttons.
+ }
+
+ deferred.reject(false);
+ };
+
+ let onSuccessCreate = (component:Component) => {
+
+ this.showSuccessNotificationMessage();
+ this.progressService.deleteProgressValue(this.$scope.component.uniqueId);
+ //update components for breadcrumbs
+ this.components.unshift(component);
+ this.$state.go(States.WORKSPACE_GENERAL, {
+ id: component.uniqueId,
+ type: component.componentType.toLowerCase(),
+ components: this.components
+ });
+
+ deferred.resolve(true);
+ };
+
+ let onSuccessUpdate = (component:Component) => {
+ this.$scope.isCreateProgress = false;
+ this.$scope.disabledButtons = false;
+ this.showSuccessNotificationMessage();
+ this.progressService.deleteProgressValue(this.$scope.component.uniqueId);
+
+ // Stop the circle loader.
+ this.$scope.isLoading = false;
+
+ component.tags = _.reject(component.tags, (item)=> {
+ return item === component.name
+ });
+
+ // Update the components
+ 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;
+ }
+
+ deferred.resolve(true);
+ };
+
+ if (this.$scope.isCreateMode()) {
+ this.$scope.progressMessage = "Creating Asset...";
+ // CREATE MODE
+ this.$scope.isCreateProgress = true;
+
+ _.first(this.$scope.leftBarTabs.menuItems).isDisabled = true;//disabled click on general tab (DE246274)
+
+ // Start creating the component
+ this.ComponentFactory.createComponentOnServer(this.$scope.component).then(onSuccessCreate, onFailed);
+
+ // In case we import CSAR. Notify user that import VF will take long time (the create is performed in the background).
+ if (this.$scope.component.isResource() && (<Resource>this.$scope.component).csarUUID) {
+ this.Notification.info({
+ message: this.$filter('translate')("IMPORT_VF_MESSAGE_CREATE_TAKES_LONG_TIME_DESCRIPTION"),
+ title: this.$filter('translate')("IMPORT_VF_MESSAGE_CREATE_TAKES_LONG_TIME_TITLE")
+ });
+ }
+ } else {
+ // UPDATE MODE
+ this.$scope.isCreateProgress = true;
+ this.$scope.progressMessage = "Updating Asset...";
+ this.disableMenuItems();
+
+
+ // Work around to change the csar version
+ if (this.cacheService.get(CHANGE_COMPONENT_CSAR_VERSION_FLAG)) {
+ (<Resource>this.$scope.component).csarVersion = this.cacheService.get(CHANGE_COMPONENT_CSAR_VERSION_FLAG);
+ this.cacheService.remove(CHANGE_COMPONENT_CSAR_VERSION_FLAG);
+ }
+
+ this.$scope.component.updateComponent().then(onSuccessUpdate, onFailed);
+ }
+ return deferred.promise;
+ };
+
+ this.$scope.revert = ():void => {
+ //in state of import file leave the file in place
+ if (this.$scope.component.isResource() && (<Resource>this.$scope.component).importedFile) {
+ let tempFile:FileUploadModel = (<Resource>this.$scope.component).importedFile;
+ this.$scope.component = this.ComponentFactory.createComponent(this.$scope.originComponent);
+ (<Resource>this.$scope.component).importedFile = tempFile;
+ } else {
+ this.$scope.component = this.ComponentFactory.createComponent(this.$scope.originComponent);
+ }
+
+ };
+
+ this.$scope.changeLifecycleState = (state:string):void => {
+ if (this.isNeedSave() && state !== 'deleteVersion') {
+ this.$scope.save().then(() => {
+ changeLifecycleState(state);
+ })
+ } else {
+ changeLifecycleState(state);
+ }
+ };
+
+ let defaultActionAfterChangeLifecycleState = ():void => {
+ if (this.$state.current.data && this.$state.current.data.unsavedChanges) {
+ this.$state.current.data.unsavedChanges = false;
+ }
+ this.$state.go('dashboard');
+ };
+
+ let changeLifecycleState = (state:string) => {
+ if ('monitor' === state) {
+ this.$state.go('workspace.distribution');
+ return;
+ }
+
+ let data = this.$scope.changeLifecycleStateButtons[state];
+ let onSuccess = (component:Component, url:string):void => {
+ //Updating the component from server response
+
+ //the server returns only metaData (small component) except checkout (Full component) ,so we update only the statuses of distribution & lifecycle
+ this.$scope.component.lifecycleState = component.lifecycleState;
+ this.$scope.component.distributionStatus = component.distributionStatus;
+
+ switch (url) {
+ case 'lifecycleState/CHECKOUT':
+ // only checkOut get the full component from server
+ this.$scope.component = component;
+ // Work around to change the csar version
+ if (this.cacheService.get(CHANGE_COMPONENT_CSAR_VERSION_FLAG)) {
+ (<Resource>this.$scope.component).csarVersion = this.cacheService.get(CHANGE_COMPONENT_CSAR_VERSION_FLAG);
+ }
+
+ //when checking out a minor version uuid remains
+ let bcComponent:Component = _.find(this.components, (item) => {
+ return item.uuid === component.uuid;
+ });
+ if (bcComponent) {
+ this.components[this.components.indexOf(bcComponent)] = component;
+ } else {
+ //when checking out a major(certified) version
+ this.components.unshift(component);
+ }
+
+ this.$state.go(this.$state.current.name, {
+ id: component.uniqueId,
+ type: component.componentType.toLowerCase(),
+ components: this.components
+ });
+ this.Notification.success({
+ message: this.$filter('translate')("CHECKOUT_SUCCESS_MESSAGE_TEXT"),
+ title: this.$filter('translate')("CHECKOUT_SUCCESS_MESSAGE_TITLE")
+ });
+ break;
+ case 'lifecycleState/CHECKIN':
+ defaultActionAfterChangeLifecycleState();
+ this.Notification.success({
+ message: this.$filter('translate')("CHECKIN_SUCCESS_MESSAGE_TEXT"),
+ title: this.$filter('translate')("CHECKIN_SUCCESS_MESSAGE_TITLE")
+ });
+ break;
+ case 'lifecycleState/UNDOCHECKOUT':
+ defaultActionAfterChangeLifecycleState();
+ this.Notification.success({
+ message: this.$filter('translate')("DELETE_SUCCESS_MESSAGE_TEXT"),
+ title: this.$filter('translate')("DELETE_SUCCESS_MESSAGE_TITLE")
+ });
+ break;
+ case 'lifecycleState/certificationRequest':
+ defaultActionAfterChangeLifecycleState();
+ this.Notification.success({
+ message: this.$filter('translate')("SUBMIT_FOR_TESTING_SUCCESS_MESSAGE_TEXT"),
+ title: this.$filter('translate')("SUBMIT_FOR_TESTING_SUCCESS_MESSAGE_TITLE")
+ });
+ break;
+ //Tester Role
+ case 'lifecycleState/failCertification':
+ defaultActionAfterChangeLifecycleState();
+ this.Notification.success({
+ message: this.$filter('translate')("REJECT_SUCCESS_MESSAGE_TEXT"),
+ title: this.$filter('translate')("REJECT_SUCCESS_MESSAGE_TITLE")
+ });
+ break;
+ case 'lifecycleState/certify':
+ defaultActionAfterChangeLifecycleState();
+ this.Notification.success({
+ message: this.$filter('translate')("ACCEPT_TESTING_SUCCESS_MESSAGE_TEXT"),
+ title: this.$filter('translate')("ACCEPT_TESTING_SUCCESS_MESSAGE_TITLE")
+ });
+ break;
+ //DE203504 Bug Fix Start
+ case 'lifecycleState/startCertification':
+ this.initChangeLifecycleStateButtons();
+ this.Notification.success({
+ message: this.$filter('translate')("START_TESTING_SUCCESS_MESSAGE_TEXT"),
+ title: this.$filter('translate')("START_TESTING_SUCCESS_MESSAGE_TITLE")
+ });
+ break;
+ case 'lifecycleState/cancelCertification':
+ this.initChangeLifecycleStateButtons();
+ this.Notification.success({
+ message: this.$filter('translate')("CANCEL_TESTING_SUCCESS_MESSAGE_TEXT"),
+ title: this.$filter('translate')("CANCEL_TESTING_SUCCESS_MESSAGE_TITLE")
+ });
+ break;
+ //Ops Role
+ case 'distribution/PROD/activate':
+ this.initChangeLifecycleStateButtons();
+ this.Notification.success({
+ message: this.$filter('translate')("DISTRIBUTE_SUCCESS_MESSAGE_TEXT"),
+ title: this.$filter('translate')("DISTRIBUTE_SUCCESS_MESSAGE_TITLE")
+ });
+ break;
+ //Governor Role
+ case 'distribution-state/reject':
+ this.initChangeLifecycleStateButtons();
+ this.Notification.success({
+ message: this.$filter('translate')("REJECT_SUCCESS_MESSAGE_TEXT"),
+ title: this.$filter('translate')("REJECT_SUCCESS_MESSAGE_TITLE")
+ });
+ break;
+ case 'distribution-state/approve':
+ this.initChangeLifecycleStateButtons();
+ this.$state.go('catalog');
+ this.Notification.success({
+ message: this.$filter('translate')("APPROVE_SUCCESS_MESSAGE_TEXT"),
+ title: this.$filter('translate')("APPROVE_SUCCESS_MESSAGE_TITLE")
+ });
+ break;
+ //DE203504 Bug Fix End
+
+ default :
+ defaultActionAfterChangeLifecycleState();
+
+ }
+ if (data.url != 'lifecycleState/CHECKOUT') {
+ this.$scope.isLoading = false;
+ }
+ };
+ //this.$scope.isLoading = true;
+ this.ChangeLifecycleStateHandler.changeLifecycleState(this.$scope.component, data, this.$scope, onSuccess);
+ };
+
+ this.$scope.enabledTabs = ():void => {
+ this.$scope.leftBarTabs.menuItems.forEach((item:MenuItem) => {
+ item.isDisabled = false;
+ });
+ };
+
+ this.$scope.isViewMode = ():boolean => {
+ return this.$scope.mode === WorkspaceMode.VIEW;
+ };
+
+ this.$scope.isDesigner = ():boolean => {
+ return this.role == Role.DESIGNER;
+ };
+
+ this.$scope.isProductManager = ():boolean => {
+ return this.role == Role.PRODUCT_MANAGER;
+ };
+
+ this.$scope.isDisableMode = ():boolean => {
+ return this.$scope.mode === WorkspaceMode.VIEW && this.$scope.component.lifecycleState === ComponentState.NOT_CERTIFIED_CHECKIN;
+ };
+
+ this.$scope.showFullIcons = ():boolean => {
+ //we show revert and save icons only in general\icon view
+ return this.$state.current.name === States.WORKSPACE_GENERAL ||
+ this.$state.current.name === States.WORKSPACE_ICONS;
+ };
+
+ this.$scope.isCreateMode = ():boolean => {
+ return this.$scope.mode === WorkspaceMode.CREATE;
+ };
+
+ this.$scope.isEditMode = ():boolean => {
+ return this.$scope.mode === WorkspaceMode.EDIT;
+ };
+
+ this.$scope.goToBreadcrumbHome = ():void => {
+ let bcHome:MenuItemGroup = this.$scope.breadcrumbsModel[0];
+ this.$state.go(bcHome.menuItems[bcHome.selectedIndex].state);
+ };
+
+ this.$scope.showLifecycleIcon = ():boolean => {
+ return this.role == Role.DESIGNER ||
+ this.role == Role.PRODUCT_MANAGER;
+ };
+
+ this.$scope.getStatus = ():string => {
+ if (this.$scope.isCreateMode()) {
+ return 'IN DESIGN';
+ }
+
+ return this.$scope.component.getStatus(this.sdcMenu);
+ };
+
+ this.initMenuItems();
+
+ this.$scope.showChangeStateButton = ():boolean => {
+ let result:boolean = true;
+ if (!this.$scope.component.isLatestVersion() && Role.OPS != this.role && Role.GOVERNOR != this.role) {
+ result = false;
+ }
+ if (this.role === Role.PRODUCT_MANAGER && !this.$scope.component.isProduct()) {
+ result = false;
+ }
+ if ((this.role === Role.DESIGNER || this.role === Role.TESTER)
+ && this.$scope.component.isProduct()) {
+ result = false;
+ }
+ if (ComponentState.NOT_CERTIFIED_CHECKOUT === this.$scope.component.lifecycleState && this.$scope.isViewMode()) {
+ result = false;
+ }
+ if (ComponentState.CERTIFIED != this.$scope.component.lifecycleState &&
+ (Role.OPS == this.role || Role.GOVERNOR == this.role)) {
+ result = false;
+ }
+ return result;
+ };
+
+ this.$scope.updateSelectedMenuItem = ():void => {
+ let selectedItem:MenuItem = _.find(this.$scope.leftBarTabs.menuItems, (item:MenuItem) => {
+ return item.state === this.$state.current.name;
+ });
+ this.$scope.leftBarTabs.selectedIndex = selectedItem ? this.$scope.leftBarTabs.menuItems.indexOf(selectedItem) : 0;
+ };
+
+ this.$scope.$watch('$state.current.name', (newVal:string):void => {
+ if (newVal) {
+ this.$scope.isComposition = (newVal.indexOf(States.WORKSPACE_COMPOSITION) > -1);
+ this.$scope.isDeployment = (newVal.indexOf(States.WORKSPACE_DEPLOYMENT) > -1);
+ }
+ });
+ };
+
+ private initAfterScope = ():void => {
+ // In case user select csar from the onboarding modal, need to disable checkout and submit for testing.
+ if (this.$state.params['disableButtons'] === true) {
+ this.$scope.uploadFileChangedInGeneralTab();
+ }
+ };
+
+ private initVersionObject = ():void => {
+ this.$scope.versionsList = (this.$scope.component.getAllVersionsAsSortedArray()).reverse();
+ this.$scope.changeVersion = {selectedVersion: _.find(this.$scope.versionsList, {versionId: this.$scope.component.uniqueId})};
+ };
+
+ private getNewComponentBreadcrumbItem = ():MenuItem => {
+ let text = "";
+ if (this.$scope.component.isResource() && (<Resource>this.$scope.component).isCsarComponent()) {
+ text = this.$scope.component.getComponentSubType() + ': ' + this.$scope.component.name;
+ } else {
+ text = 'Create new ' + this.$state.params['type'];
+ }
+ return new MenuItem(text, null, States.WORKSPACE_GENERAL, 'goToState', [this.$state.params]);
+ };
+
+ 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);
+ }
+ });
+ return tempMenuItems;
+ };
+
+ private initBreadcrumbs = () => {
+ this.components = this.cacheService.get('breadcrumbsComponents');
+ let breadcrumbsComponentsLvl = this.MenuHandler.generateBreadcrumbsModelFromComponents(this.components, this.$scope.component);
+
+ if (this.$scope.isCreateMode()) {
+ let createItem = this.getNewComponentBreadcrumbItem();
+ if (!breadcrumbsComponentsLvl.menuItems) {
+ breadcrumbsComponentsLvl.menuItems = [];
+ }
+ breadcrumbsComponentsLvl.menuItems.unshift(createItem);
+ breadcrumbsComponentsLvl.selectedIndex = 0;
+ }
+
+ this.$scope.breadcrumbsModel = [breadcrumbsComponentsLvl, this.$scope.leftBarTabs];
+ };
+
+ private initMenuItems() {
+
+ let inCreateMode = this.$scope.isCreateMode();
+ this.$scope.leftBarTabs = new MenuItemGroup();
+ this.$scope.leftBarTabs.menuItems = this.updateMenuItemByRole(this.sdcMenu.component_workspace_menu_option[this.$scope.component.getComponentSubType()], this.role);
+
+ this.$scope.leftBarTabs.menuItems.forEach((item:MenuItem) => {
+ item.params = [item.state];
+ item.callback = this.$scope.onMenuItemPressed;
+ item.isDisabled = (inCreateMode && States.WORKSPACE_GENERAL != item.state) ||
+ (States.WORKSPACE_DEPLOYMENT === item.state && this.$scope.component.groups && this.$scope.component.groups.length === 0 && this.$scope.component.isResource());
+ });
+
+ if (this.cacheService.get('breadcrumbsComponents')) {
+ this.initBreadcrumbs();
+ } else {
+ let onSuccess = (components:Array<Component>) => {
+ this.cacheService.set('breadcrumbsComponents', components);
+ this.initBreadcrumbs();
+ };
+ this.EntityService.getCatalog().then(onSuccess); //getAllComponents() doesnt return components from catalog
+ }
+ }
+
+ private disableMenuItems() {
+ this.$scope.leftBarTabs.menuItems.forEach((item:MenuItem) => {
+ item.params = [item.state];
+ item.callback = this.$scope.onMenuItemPressed;
+ item.isDisabled = (States.WORKSPACE_GENERAL != item.state);
+ });
+ }
+
+ private enableMenuItems() {
+ this.$scope.leftBarTabs.menuItems.forEach((item:MenuItem) => {
+ item.params = [item.state];
+ item.callback = this.$scope.onMenuItemPressed;
+ item.isDisabled = false;
+ });
+ }
+
+ private showSuccessNotificationMessage = ():void => {
+ this.Notification.success({
+ message: this.$filter('translate')("IMPORT_VF_MESSAGE_CREATE_FINISHED_DESCRIPTION"),
+ title: this.$filter('translate')("IMPORT_VF_MESSAGE_CREATE_FINISHED_TITLE")
+ });
+ };
+
+}
+
+
diff --git a/catalog-ui/app/scripts/view-models/workspace/workspace-view.html b/catalog-ui/src/app/view-models/workspace/workspace-view.html
index 118f7474be..dbb7fa6d63 100644
--- a/catalog-ui/app/scripts/view-models/workspace/workspace-view.html
+++ b/catalog-ui/src/app/view-models/workspace/workspace-view.html
@@ -1,11 +1,5 @@
<div class="sdc-workspace-container">
<loader data-display="isLoading"></loader>
-
- <!-- HEADER -->
-<!--
- <ecomp-header menu-data="menuItems" version="{{version}}"></ecomp-header>
--->
-
<div class="w-sdc-main-container">
<div class="w-sdc-left-sidebar" data-ng-if="!isComposition">
@@ -15,14 +9,11 @@
</div>
<div include-padding="true" class="w-sdc-main-right-container" data-ng-class="{'composition':isComposition}">
-
- <!--<div class="w-sdc-main-right-container" data-ng-class="{'composition':isComposition}">-->
- <loader data-display="isCreateProgress" relative="true"></loader>
+ <loader data-display="isCreateProgress" data-ng-show="isCreateProgress" relative="false"></loader>
<div class="sdc-workspace-top-bar">
<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"
ng-options="'V'+version.versionNumber for version in versionsList" data-ng-change="onVersionChanged(changeVersion.selectedVersion.versionId)">
@@ -63,7 +54,7 @@
<button ng-if="!isViewMode() && isCreateMode()" data-ng-disabled="!isValidForm || isDisableMode() || isLoading" ng-click="save()" class="tlv-btn outline green" data-tests-id="create/save">Create</button>
- <span data-ng-if="isDesigner() && !isCreateMode() && component.lifecycleState === 'NOT_CERTIFIED_CHECKOUT'" sdc-smart-tooltip=""
+ <span data-ng-if="(isDesigner() || isProductManager()) && !isCreateMode() && component.lifecycleState === 'NOT_CERTIFIED_CHECKOUT'" sdc-smart-tooltip=""
data-ng-class="{'disabled' : !isValidForm || isDisableMode() || isViewMode()}" ng-click="changeLifecycleState('deleteVersion')"
class="sprite-new delete-btn" data-tests-id="delete_version" sdc-smart-tooltip="">Delete</span>
@@ -83,4 +74,5 @@
</div>
</div>
<top-nav search-bind="search.filterTerm" hide-search="true" menu-model="breadcrumbsModel" version="{{version}}"></top-nav>
+ <ecomp-footer></ecomp-footer>
</div>
diff --git a/catalog-ui/src/app/view-models/workspace/workspace.less b/catalog-ui/src/app/view-models/workspace/workspace.less
new file mode 100644
index 0000000000..6cf024e335
--- /dev/null
+++ b/catalog-ui/src/app/view-models/workspace/workspace.less
@@ -0,0 +1,150 @@
+.sdc-workspace-container {
+ .bg_p;
+
+ .add-btn {
+ .f-color.a;
+ .f-type._12_m;
+ .hand;
+ float: right;
+ margin-bottom: 15px;
+
+ &:before {
+ .sprite-new;
+ .plus-icon;
+ margin-right: 5px;
+ content: "";
+
+ }
+ &:hover {
+ .f-color.b;
+ &:before {
+ .sprite-new;
+ .plus-icon-hover;
+ }
+ }
+
+ }
+ .w-sdc-left-sidebar {
+ padding: 3px 3px 0px 0px;
+ background-color: @main_color_p;
+ box-shadow: 7px -3px 6px -8px @main_color_n;
+ z-index: 2;
+ }
+
+ .sdc-asset-creation-info {
+ .n_12_r;
+ float: right;
+ margin: 8px 20px 0 0;
+ }
+
+ .w-sdc-main-right-container {
+
+ padding: 0px 0px 0px 0px;
+ background-color: @main_color_p;
+ z-index: 1;
+
+ .sdc-workspace-top-bar {
+ height: @action_nav_height;
+ padding: 12px 10px 0px 50px;
+ border-bottom: 1px solid @main_color_o;
+ display: flex;
+ justify-content: space-between;
+
+ .version-container {
+
+ }
+
+ .progress-container {
+ flex-grow: 4;
+ z-index: 10000000;
+
+ .general-view-top-progress {
+ width: 30%;
+ margin: 0 auto;
+ min-width: 200px;
+ }
+ }
+
+ .not-latest {
+ position: absolute;
+ left: 24px;
+ top: 20px;
+ .sprite-new;
+ .asdc-warning;
+ }
+
+ .sdc-workspace-top-bar-buttons {
+
+ > button, > span:not(.delimiter) {
+ margin-right: 10px;
+ vertical-align: middle;
+ .hand;
+
+ &.sprite-new {
+ text-indent: 100%;
+ }
+ &.disabled, &:hover.disabled {
+ pointer-events: none;
+ }
+ }
+ .delimiter {
+ height: 32px;
+ width: 1px;
+ background-color: #959595;
+ display: inline-block;
+ vertical-align: middle;
+ margin-right: 20px;
+ }
+
+ }
+
+ .lifecycle-state {
+ padding: 7px 0 0 10px;
+ margin: 2px 0 7px 10px;
+ border-left: 1px solid @main_color_o;
+ line-height: 15px;
+ font-family: @font-omnes-medium;
+ color: @main_color_m;
+
+ .lifecycle-state-icon {
+ .sprite-new;
+ }
+ .lifecycle-state-text {
+
+ font-weight: bold;
+ text-transform: uppercase;
+ vertical-align: top;
+ padding: 3px;
+ }
+ }
+
+ .version-selector {
+ // float:left;
+ background-color: transparent;
+ border: none;
+ margin-top: 6px;
+ }
+ }
+ .w-sdc-main-container-body-content {
+ height:calc(~'100% - @{action_nav_height}');
+
+ text-align: center;
+ align-items: center;
+ padding: 40px 14% 20px 14%;
+ &.third-party {
+ text-align: left;
+ padding: 0;
+ position: absolute;
+ top: @action_nav_height;
+ left: 0;
+ right: 0;
+ bottom: 0;
+ }
+ }
+ }
+}
+
+
+.properties-assignment .sdc-workspace-container .w-sdc-main-right-container .w-sdc-main-container-body-content{
+ padding: 80px 2% 40px 2%;
+} \ No newline at end of file
diff --git a/catalog-ui/src/assets/.gitkeep b/catalog-ui/src/assets/.gitkeep
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/catalog-ui/src/assets/.gitkeep
diff --git a/catalog-ui/app/languages/en_US_OS.json b/catalog-ui/src/assets/languages/en_US.json
index d7f639e076..5f752333cd 100644
--- a/catalog-ui/app/languages/en_US_OS.json
+++ b/catalog-ui/src/assets/languages/en_US.json
@@ -1,4 +1,6 @@
{
+ "PROJECT_TITLE": "SDC",
+
"=========== VALIDATION ===========": "",
"VALIDATION_ERROR_MAX_LENGTH": "Max length {{max}} characters.",
"VALIDATION_ERROR_MIN_LENGTH": "Min length {{min}} characters.",
@@ -12,6 +14,7 @@
"VALIDATION_ERROR_MAX_FILE_SIZE": "Max file size is 10 MB.",
"VALIDATION_ERROR_EMPTY_FILE": "The file you uploaded was empty, please upload a valid file.",
"VALIDATION_ERROR_VALUE_MUST_BE_CHANGED": "Value must be changed",
+ "VALIDATION_ERROR_INVALID_NAME": "Invalid name.",
"=========== GENERAL ===========": "",
"GENERAL_LABEL_TYPE": "Type:",
@@ -31,7 +34,10 @@
"GENERAL_LABEL_LICENSE_TYPE": "License Type:",
"GENERAL_LABEL_SERVICE": "Service:",
"GENERAL_LABEL_RESOURCE": "Resource:",
- "GENERAL_LABEL_PRODUCT": "Product:",
+ "GENERAL_LABEL_LIFE_CYCLE_STATUS": "Life Cycle Status:",
+ "GENERAL_LABEL_DISTRIBUTION_STATUS": "Distribution Status:",
+ "GENERAL_LABEL_SYSTEM_NAME": "System Name:",
+
"=========== GENERAL ERROR PAGES ===========": "",
"GENERAL_ERROR_403_TITLE": "SDC",
@@ -45,6 +51,7 @@
"TOP_MENU_HOME_BUTTON": "HOME",
"TOP_MENU_CATALOG_BUTTON": "CATALOG",
"TOP_MENU_ON_BOARD_BUTTON": "ONBOARD",
+ "TOP_MENU_DCAE_BUTTON": "DCAE",
"=========== SIGN IN PAGE ===========": "",
"SIGN_IN_CAPTION": "Signing in",
@@ -258,6 +265,7 @@
"compute": "Compute",
"gateway": "Gateway",
"defaulticon": "Default Icon",
+ "monitoring_template": "Monitoring Template",
"=========== ADD ARTIFACT FROM ===========": "",
"ADD_ARTIFACT_ERROR_VALID_EXTENSIONS": "File extension should be {{extensions}}.",
@@ -366,8 +374,8 @@
"CREATE_CATEGORY_MODAL_PATTERN": "{{modelType}} name is not valid"
,"=========== PDF FILE ===========": "",
- "PDF_FILE_DECLARATION_BOLD": "AT&T Proprietary (Restricted)",
- "PDF_FILE_DECLARATION": "Only for use by authorized individuals or any above-designated team(s) within the AT&T companies and not for general distribution"
+ "PDF_FILE_DECLARATION_BOLD": "",
+ "PDF_FILE_DECLARATION": ""
,"=========== DEPLOYMENT ARTIFACTS ===========": "",
"DEPLOYMENT_ARTIFACT_NO_ARTIFACTS_TO_DISPLAY": "There are no deployment artifacts to display",
@@ -377,7 +385,7 @@
"DEPLOYMENT_ARTIFACT_BUTTON_ADD_VOLUME_HEAT": "Add Volume HEAT Artifact",
"DEPLOYMENT_ARTIFACT_BUTTON_ADD_OTHER": "Add Other Artifact"
-,"=========== IMPORT VF ===========": "",
+ ,"=========== IMPORT VF ===========": "",
"IMPORT_VF_MESSAGE_CREATE_TAKES_LONG_TIME_TITLE": "Create VF",
"IMPORT_VF_MESSAGE_CREATE_TAKES_LONG_TIME_DESCRIPTION": "Your VF is being created.<br/>It can take up to 10 minutes.<br/>When done, you can view it in SDC Catalog.",
"IMPORT_VF_MESSAGE_CREATE_FINISHED_TITLE": "Create/Update",
@@ -387,6 +395,7 @@
"=========== TABS TITLE ===========": "",
"HIERARCHY_TAB_TITLE": "HIERARCHY",
+ "DEPLOYMENT_TAB_TITLE": "DEPLOYMENT",
"=========== DISTRIBUTION VIEW ===========": "",
"DISTRIBUTION_VIEW_TITLE_USER_ID": "User id:",
@@ -416,5 +425,17 @@
"=========== ON BOARDING MODAL INFO MESSAGES ===========": "",
"ON_BOARDING_GENERAL_INFO": "Displays a table of VSPs created using Onboarding.<br/> Each row displays details for a single VSP.<br/> When expanded you can either import CSAR files that are yet to be imported or update CSAR files that were previously imported.",
"ON_BOARDING_IMPORT_INFO": "Displays the Onboarding repository and supports importing on-boarded CSAR files.<br/> Select an imported CSAR file to create a VF from the on-boarded and imported information.",
- "ON_BOARDING_UPDATE_INFO": "Displays the Onboarding repository and supports updating on-boarded and previously imported CSAR files.<br/> Clicking Update, updates the existing VF with information available from a new version of the CSAR file."
+ "ON_BOARDING_UPDATE_INFO": "Displays the Onboarding repository and supports updating on-boarded and previously imported CSAR files.<br/> Clicking Update, updates the existing VF with information available from a new version of the CSAR file.",
+
+ "=========== HEAT PARAMETERS MODAL INFO MESSAGES ===========": "",
+ "DEFAULT_VALUE_INFO": "This column indicates all the default values that were declared in the Main Heat ",
+ "CURRENT_VALUE_INFO": "This column indicates:<br/>• Default values that were declared in the main HEAT & does not have a value in the ENV<br/>• Values that were declared in the ENV<br/>• All the values that appear in the current value fields will be generated into the ENV",
+
+ "=========== MODULE PROPERTY FORM ===========": "",
+ "MIN_VALIDATION_ERROR": "Value cannot be lower than the 'min_vf_module_instances' and 'initial_count'",
+ "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"
+
}
diff --git a/catalog-ui/app/styles/animation.less b/catalog-ui/src/assets/styles/animation.less
index 014b33a454..014b33a454 100644
--- a/catalog-ui/app/styles/animation.less
+++ b/catalog-ui/src/assets/styles/animation.less
diff --git a/catalog-ui/src/assets/styles/app.less b/catalog-ui/src/assets/styles/app.less
new file mode 100644
index 0000000000..1ce1801d9b
--- /dev/null
+++ b/catalog-ui/src/assets/styles/app.less
@@ -0,0 +1,119 @@
+.sdc-main-container{
+ width: 100%;
+ height: 100%;
+}
+
+@import 'variables.less';
+@import 'variables-old.less';
+@import 'mixins.less';
+@import 'mixins_old.less';
+@import 'global.less';
+
+@import 'sprite-old.less';
+@import 'sprite.less';
+@import 'sprite-product-icons.less';
+@import 'sprite-resource-icons.less';
+@import 'sprite-services-icons.less';
+
+@import 'animation.less';
+@import 'buttons.less';
+@import 'dark-header.less';
+@import 'fonts.less';
+@import 'form-elements.less';
+@import 'layout/header.less';
+@import 'layout/main.less';
+@import 'layout/sidebar.less';
+@import 'modal.less';
+@import 'multi-level-expand-collapse.less';
+@import 'scroller.less';
+@import 'table-flex.less';
+@import 'tlv-buttons.less';
+@import 'tlv-checkbox.less';
+@import 'tlv-loader.less';
+@import 'tlv-sprite.less';
+@import 'tooltips.less';
+@import 'welcome-sprite.less';
+@import 'welcome-style.less';
+@import 'sdc-ui.css';
+
+// Less insides specific files.
+@import '../../app/directives/ecomp-footer/ecomp-footer.less';
+@import '../../app/directives/ecomp-header/ecomp-header.less';
+@import '../../app/directives/edit-name-popover/edit-name-popover.less';
+@import '../../app/directives/elements/checkbox/checkbox.less';
+@import '../../app/directives/elements/radiobutton/radiobutton.less';
+@import '../../app/directives/ellipsis/ellipsis-directive.less';
+@import '../../app/directives/file-upload/file-upload.less';
+@import '../../app/directives/graphs-v2/composition-graph/composition-graph.less';
+@import '../../app/directives/graphs-v2/deployment-graph/deployment-graph.less';
+@import '../../app/directives/graphs-v2/palette/palette.less';
+@import '../../app/directives/graphs-v2/relation-menu/relation-menu.less';
+@import '../../app/directives/capabilities-and-requirements/capabilities-requirements-list.less';
+// @import '../../app/directives/graphs-v2/asset-popover/asset-popover.less';
+@import '../../app/directives/info-tooltip/info-tooltip.less';
+@import '../../app/directives/inputs-and-properties/inputs/input-row.less';
+@import '../../app/directives/inputs-and-properties/properties/property-row-view.less';
+@import '../../app/directives/layout/top-nav/top-nav.less';
+@import '../../app/directives/layout/top-progress/top-progress.less';
+@import '../../app/directives/loader/loader-directive.less';
+@import '../../app/directives/modal/sdc-modal.less';
+@import '../../app/directives/property-types/data-type-fields-structure/data-type-fields-structure.less';
+@import '../../app/directives/property-types/type-list/type-list-directive.less';
+@import '../../app/directives/property-types/type-map/type-map-directive.less';
+@import '../../app/directives/sdc-tabs/sdc-single-tab/sdc-single-tab.less';
+@import '../../app/directives/sdc-tabs/sdc-tabs.less';
+@import '../../app/directives/select-property-types/select-data-type-fields-structure/select-data-type-fields-structure.less';
+@import '../../app/directives/select-property-types/select-type-list/select-type-list-directive.less';
+@import '../../app/directives/select-property-types/select-type-map/select-type-map-directive.less';
+@import '../../app/directives/structure-tree/structure-tree-directive.less';
+@import '../../app/directives/tag/tag-directive.less';
+@import '../../app/directives/user-header-details/user-header-details-directive.less';
+@import '../../app/directives/utils/expand-collapse-list-header/expand-collapse-list-header.less';
+@import '../../app/directives/utils/expand-collapse-menu-box/expand-collapse-menu-box.less';
+@import '../../app/directives/utils/expand-collapse/expand-collapse.less';
+@import '../../app/directives/utils/sdc-tags/sdc-tags.less';
+@import '../../app/view-models/admin-dashboard/add-category-modal/add-category-modal-view.less';
+@import '../../app/view-models/admin-dashboard/admin-dashboard.less';
+@import '../../app/view-models/admin-dashboard/category-management/category-management.less';
+@import '../../app/view-models/admin-dashboard/user-management/user-management.less';
+@import '../../app/view-models/catalog/catalog.less';
+@import '../../app/view-models/dashboard/dashboard.less';
+@import '../../app/view-models/dcae-app/dcae-app.less';
+@import '../../app/view-models/forms/artifact-form/artifact-form.less';
+@import '../../app/view-models/forms/env-parameters-form/env-parameters-form.less';
+@import '../../app/view-models/forms/property-forms/base-property-form/property-form-base.less';
+@import '../../app/view-models/forms/property-forms/select-datatype-modal/select-datatype-modal.less';
+@import '../../app/view-models/forms/resource-instance-name-form/resource-instance-name.less';
+@import '../../app/view-models/modals/confirmation-modal/confirmation-modal.less';
+@import '../../app/view-models/modals/email-modal/email-modal.less';
+@import '../../app/view-models/modals/error-modal/error.less';
+@import '../../app/view-models/modals/message-modal/message-client-modal/client-message-modal.less';
+@import '../../app/view-models/modals/message-modal/message-server-modal/server-message-modal.less';
+@import '../../app/view-models/modals/onboarding-modal/onboarding-modal.less';
+@import '../../app/view-models/onboard-vendor/onboard-vendor.less';
+@import '../../app/view-models/support/support.less';
+@import '../../app/view-models/tabs/general-tab.less';
+@import '../../app/view-models/tabs/hierarchy/hierarchy.less';
+@import '../../app/view-models/tutorial-end/tutorial-end.less';
+@import '../../app/view-models/workspace/tabs/activity-log/activity-log.less';
+@import '../../app/view-models/workspace/tabs/attributes/attributes.less';
+@import '../../app/view-models/workspace/tabs/composition/composition.less';
+@import '../../app/view-models/workspace/tabs/composition/tabs/artifacts/artifacts.less';
+@import '../../app/view-models/workspace/tabs/composition/tabs/details/details.less';
+@import '../../app/view-models/workspace/tabs/composition/tabs/properties-and-attributes/properties.less';
+@import '../../app/view-models/workspace/tabs/composition/tabs/relations/relations.less';
+@import '../../app/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts.less';
+@import '../../app/view-models/workspace/tabs/deployment/deployment.less';
+@import '../../app/view-models/workspace/tabs/distribution/disribution-status-modal/disribution-status-modal.less';
+@import '../../app/view-models/workspace/tabs/distribution/distribution.less';
+@import '../../app/view-models/workspace/tabs/general/general.less';
+@import '../../app/view-models/workspace/tabs/icons/icons.less';
+@import '../../app/view-models/workspace/tabs/information-artifacts/information-artifacts.less';
+@import '../../app/view-models/workspace/tabs/inputs/inputs.less';
+@import '../../app/view-models/workspace/tabs/inputs/resource-input/resource-inputs.less';
+@import '../../app/view-models/workspace/tabs/inputs/service-input/service-inputs.less';
+@import '../../app/view-models/workspace/tabs/product-hierarchy/product-hierarchy.less';
+@import '../../app/view-models/workspace/tabs/properties/properties.less';
+@import '../../app/view-models/workspace/tabs/req-and-capabilities/req-and-capabilities.less';
+@import '../../app/view-models/workspace/tabs/tosca-artifacts/tosca-artifacts.less';
+@import '../../app/view-models/workspace/workspace.less';
diff --git a/catalog-ui/app/styles/buttons.less b/catalog-ui/src/assets/styles/buttons.less
index 7215d7a3d4..7215d7a3d4 100644
--- a/catalog-ui/app/styles/buttons.less
+++ b/catalog-ui/src/assets/styles/buttons.less
diff --git a/catalog-ui/app/styles/dark-header.less b/catalog-ui/src/assets/styles/dark-header.less
index 38b4175daa..38b4175daa 100644
--- a/catalog-ui/app/styles/dark-header.less
+++ b/catalog-ui/src/assets/styles/dark-header.less
diff --git a/catalog-ui/app/styles/fonts.less b/catalog-ui/src/assets/styles/fonts.less
index 752f41f86a..752f41f86a 100644
--- a/catalog-ui/app/styles/fonts.less
+++ b/catalog-ui/src/assets/styles/fonts.less
diff --git a/catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-Bd.eot b/catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-Bd.eot
index 83074fbe2b..83074fbe2b 100644
--- a/catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-Bd.eot
+++ b/catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-Bd.eot
Binary files differ
diff --git a/catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-Bd.svg b/catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-Bd.svg
index 564f750d99..564f750d99 100644
--- a/catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-Bd.svg
+++ b/catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-Bd.svg
diff --git a/catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-Bd.ttf b/catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-Bd.ttf
index 7bfb9d5cc2..7bfb9d5cc2 100644
--- a/catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-Bd.ttf
+++ b/catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-Bd.ttf
Binary files differ
diff --git a/catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-Bd.woff b/catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-Bd.woff
index b1f00eeac9..b1f00eeac9 100644
--- a/catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-Bd.woff
+++ b/catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-Bd.woff
Binary files differ
diff --git a/catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-BdIt.eot b/catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-BdIt.eot
index 22646213e6..22646213e6 100644
--- a/catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-BdIt.eot
+++ b/catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-BdIt.eot
Binary files differ
diff --git a/catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-BdIt.svg b/catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-BdIt.svg
index 0996bb5eec..0996bb5eec 100644
--- a/catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-BdIt.svg
+++ b/catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-BdIt.svg
diff --git a/catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-BdIt.ttf b/catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-BdIt.ttf
index 69b3c834e6..69b3c834e6 100644
--- a/catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-BdIt.ttf
+++ b/catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-BdIt.ttf
Binary files differ
diff --git a/catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-BdIt.woff b/catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-BdIt.woff
index f2850a6f53..f2850a6f53 100644
--- a/catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-BdIt.woff
+++ b/catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-BdIt.woff
Binary files differ
diff --git a/catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-Bk.eot b/catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-Bk.eot
index a945fb3592..a945fb3592 100644
--- a/catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-Bk.eot
+++ b/catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-Bk.eot
Binary files differ
diff --git a/catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-Bk.svg b/catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-Bk.svg
index 279204943f..279204943f 100644
--- a/catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-Bk.svg
+++ b/catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-Bk.svg
diff --git a/catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-Bk.ttf b/catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-Bk.ttf
index b4390461c6..b4390461c6 100644
--- a/catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-Bk.ttf
+++ b/catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-Bk.ttf
Binary files differ
diff --git a/catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-Bk.woff b/catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-Bk.woff
index 5373567803..5373567803 100644
--- a/catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-Bk.woff
+++ b/catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-Bk.woff
Binary files differ
diff --git a/catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-BkIt.eot b/catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-BkIt.eot
index 4ab6695752..4ab6695752 100644
--- a/catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-BkIt.eot
+++ b/catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-BkIt.eot
Binary files differ
diff --git a/catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-BkIt.svg b/catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-BkIt.svg
index c2337a7f89..c2337a7f89 100644
--- a/catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-BkIt.svg
+++ b/catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-BkIt.svg
diff --git a/catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-BkIt.ttf b/catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-BkIt.ttf
index 7e7aa05778..7e7aa05778 100644
--- a/catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-BkIt.ttf
+++ b/catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-BkIt.ttf
Binary files differ
diff --git a/catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-BkIt.woff b/catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-BkIt.woff
index 55fbfd6896..55fbfd6896 100644
--- a/catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-BkIt.woff
+++ b/catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-BkIt.woff
Binary files differ
diff --git a/catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-Lt.eot b/catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-Lt.eot
index 06a4bf9949..06a4bf9949 100644
--- a/catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-Lt.eot
+++ b/catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-Lt.eot
Binary files differ
diff --git a/catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-Lt.svg b/catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-Lt.svg
index 40656e14f8..40656e14f8 100644
--- a/catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-Lt.svg
+++ b/catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-Lt.svg
diff --git a/catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-Lt.ttf b/catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-Lt.ttf
index c9a45c0e51..c9a45c0e51 100644
--- a/catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-Lt.ttf
+++ b/catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-Lt.ttf
Binary files differ
diff --git a/catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-Lt.woff b/catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-Lt.woff
index 521ee2e918..521ee2e918 100644
--- a/catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-Lt.woff
+++ b/catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-Lt.woff
Binary files differ
diff --git a/catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-LtIt.eot b/catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-LtIt.eot
index 06772919e7..06772919e7 100644
--- a/catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-LtIt.eot
+++ b/catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-LtIt.eot
Binary files differ
diff --git a/catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-LtIt.svg b/catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-LtIt.svg
index bff63e5524..bff63e5524 100644
--- a/catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-LtIt.svg
+++ b/catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-LtIt.svg
diff --git a/catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-LtIt.ttf b/catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-LtIt.ttf
index bd7ac47137..bd7ac47137 100644
--- a/catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-LtIt.ttf
+++ b/catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-LtIt.ttf
Binary files differ
diff --git a/catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-LtIt.woff b/catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-LtIt.woff
index 7f8a274165..7f8a274165 100644
--- a/catalog-ui/app/styles/fonts/ClearviewATT/ClearviewATT-LtIt.woff
+++ b/catalog-ui/src/assets/styles/fonts/ClearviewATT/ClearviewATT-LtIt.woff
Binary files differ
diff --git a/catalog-ui/app/styles/fonts/OmnesATT/AT&T Variation ID.tab b/catalog-ui/src/assets/styles/fonts/OmnesATT/AT&T Variation ID.tab
index e0085fd9ac..e0085fd9ac 100644
--- a/catalog-ui/app/styles/fonts/OmnesATT/AT&T Variation ID.tab
+++ b/catalog-ui/src/assets/styles/fonts/OmnesATT/AT&T Variation ID.tab
diff --git a/catalog-ui/app/styles/fonts/OmnesATT/OmnesATTW02BoldItalic.eot b/catalog-ui/src/assets/styles/fonts/OmnesATT/OmnesATTW02BoldItalic.eot
index da1c1d1ebe..da1c1d1ebe 100644
--- a/catalog-ui/app/styles/fonts/OmnesATT/OmnesATTW02BoldItalic.eot
+++ b/catalog-ui/src/assets/styles/fonts/OmnesATT/OmnesATTW02BoldItalic.eot
Binary files differ
diff --git a/catalog-ui/app/styles/fonts/OmnesATT/OmnesATTW02BoldItalic.svg b/catalog-ui/src/assets/styles/fonts/OmnesATT/OmnesATTW02BoldItalic.svg
index 916075aa05..916075aa05 100644
--- a/catalog-ui/app/styles/fonts/OmnesATT/OmnesATTW02BoldItalic.svg
+++ b/catalog-ui/src/assets/styles/fonts/OmnesATT/OmnesATTW02BoldItalic.svg
diff --git a/catalog-ui/app/styles/fonts/OmnesATT/OmnesATTW02BoldItalic.ttf b/catalog-ui/src/assets/styles/fonts/OmnesATT/OmnesATTW02BoldItalic.ttf
index 4f35e1f9b8..4f35e1f9b8 100644
--- a/catalog-ui/app/styles/fonts/OmnesATT/OmnesATTW02BoldItalic.ttf
+++ b/catalog-ui/src/assets/styles/fonts/OmnesATT/OmnesATTW02BoldItalic.ttf
Binary files differ
diff --git a/catalog-ui/app/styles/fonts/OmnesATT/OmnesATTW02BoldItalic.woff b/catalog-ui/src/assets/styles/fonts/OmnesATT/OmnesATTW02BoldItalic.woff
index 1722dce99e..1722dce99e 100644
--- a/catalog-ui/app/styles/fonts/OmnesATT/OmnesATTW02BoldItalic.woff
+++ b/catalog-ui/src/assets/styles/fonts/OmnesATT/OmnesATTW02BoldItalic.woff
Binary files differ
diff --git a/catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02.eot b/catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02.eot
index 39e1eae7c7..39e1eae7c7 100644
--- a/catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02.eot
+++ b/catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02.eot
Binary files differ
diff --git a/catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02.svg b/catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02.svg
index 73923de097..73923de097 100644
--- a/catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02.svg
+++ b/catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02.svg
diff --git a/catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02.ttf b/catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02.ttf
index 2342be4be5..2342be4be5 100644
--- a/catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02.ttf
+++ b/catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02.ttf
Binary files differ
diff --git a/catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02.woff b/catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02.woff
index 0acf1f027f..0acf1f027f 100644
--- a/catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02.woff
+++ b/catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02.woff
Binary files differ
diff --git a/catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02Bold.eot b/catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02Bold.eot
index 0e5892d1e0..0e5892d1e0 100644
--- a/catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02Bold.eot
+++ b/catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02Bold.eot
Binary files differ
diff --git a/catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02Bold.svg b/catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02Bold.svg
index 9670981b29..9670981b29 100644
--- a/catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02Bold.svg
+++ b/catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02Bold.svg
diff --git a/catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02Bold.ttf b/catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02Bold.ttf
index 94934087bb..94934087bb 100644
--- a/catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02Bold.ttf
+++ b/catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02Bold.ttf
Binary files differ
diff --git a/catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02Bold.woff b/catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02Bold.woff
index 1dfd28f299..1dfd28f299 100644
--- a/catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02Bold.woff
+++ b/catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02Bold.woff
Binary files differ
diff --git a/catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02Italic.eot b/catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02Italic.eot
index 8723e66fa0..8723e66fa0 100644
--- a/catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02Italic.eot
+++ b/catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02Italic.eot
Binary files differ
diff --git a/catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02Italic.svg b/catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02Italic.svg
index dbf33a9768..dbf33a9768 100644
--- a/catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02Italic.svg
+++ b/catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02Italic.svg
diff --git a/catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02Italic.ttf b/catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02Italic.ttf
index 4ef76763bd..4ef76763bd 100644
--- a/catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02Italic.ttf
+++ b/catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02Italic.ttf
Binary files differ
diff --git a/catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02Italic.woff b/catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02Italic.woff
index 750d90d387..750d90d387 100644
--- a/catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02Italic.woff
+++ b/catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02Italic.woff
Binary files differ
diff --git a/catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02Light.eot b/catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02Light.eot
index 280d111fe4..280d111fe4 100644
--- a/catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02Light.eot
+++ b/catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02Light.eot
Binary files differ
diff --git a/catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02Light.svg b/catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02Light.svg
index 85f39f5008..85f39f5008 100644
--- a/catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02Light.svg
+++ b/catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02Light.svg
diff --git a/catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02Light.ttf b/catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02Light.ttf
index 273761ab3d..273761ab3d 100644
--- a/catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02Light.ttf
+++ b/catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02Light.ttf
Binary files differ
diff --git a/catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02Light.woff b/catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02Light.woff
index b12120a86e..b12120a86e 100644
--- a/catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02Light.woff
+++ b/catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02Light.woff
Binary files differ
diff --git a/catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02LightItalic.eot b/catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02LightItalic.eot
index 2da6a99ec6..2da6a99ec6 100644
--- a/catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02LightItalic.eot
+++ b/catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02LightItalic.eot
Binary files differ
diff --git a/catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02LightItalic.svg b/catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02LightItalic.svg
index ab6936ceeb..ab6936ceeb 100644
--- a/catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02LightItalic.svg
+++ b/catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02LightItalic.svg
diff --git a/catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02LightItalic.ttf b/catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02LightItalic.ttf
index 5153cee682..5153cee682 100644
--- a/catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02LightItalic.ttf
+++ b/catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02LightItalic.ttf
Binary files differ
diff --git a/catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02LightItalic.woff b/catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02LightItalic.woff
index cf9993a1d6..cf9993a1d6 100644
--- a/catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02LightItalic.woff
+++ b/catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02LightItalic.woff
Binary files differ
diff --git a/catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02Medium.eot b/catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02Medium.eot
index 37c715f5be..37c715f5be 100644
--- a/catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02Medium.eot
+++ b/catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02Medium.eot
Binary files differ
diff --git a/catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02Medium.svg b/catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02Medium.svg
index ad72d0be51..ad72d0be51 100644
--- a/catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02Medium.svg
+++ b/catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02Medium.svg
diff --git a/catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02Medium.ttf b/catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02Medium.ttf
index 2740425412..2740425412 100644
--- a/catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02Medium.ttf
+++ b/catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02Medium.ttf
Binary files differ
diff --git a/catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02Medium.woff b/catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02Medium.woff
index 5cff69add1..5cff69add1 100644
--- a/catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02Medium.woff
+++ b/catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02Medium.woff
Binary files differ
diff --git a/catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02MediumItalic.eot b/catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02MediumItalic.eot
index 84ba4acc6b..84ba4acc6b 100644
--- a/catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02MediumItalic.eot
+++ b/catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02MediumItalic.eot
Binary files differ
diff --git a/catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02MediumItalic.svg b/catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02MediumItalic.svg
index eca8f73836..eca8f73836 100644
--- a/catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02MediumItalic.svg
+++ b/catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02MediumItalic.svg
diff --git a/catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02MediumItalic.ttf b/catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02MediumItalic.ttf
index 46bfd531b0..46bfd531b0 100644
--- a/catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02MediumItalic.ttf
+++ b/catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02MediumItalic.ttf
Binary files differ
diff --git a/catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02MediumItalic.woff b/catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02MediumItalic.woff
index 20419ed3b3..20419ed3b3 100644
--- a/catalog-ui/app/styles/fonts/OmnesATT/Omnes_ATTW02MediumItalic.woff
+++ b/catalog-ui/src/assets/styles/fonts/OmnesATT/Omnes_ATTW02MediumItalic.woff
Binary files differ
diff --git a/catalog-ui/app/styles/fonts/OmnesATT/demo-async.htm b/catalog-ui/src/assets/styles/fonts/OmnesATT/demo-async.htm
index f7a43e6a34..f7a43e6a34 100644
--- a/catalog-ui/app/styles/fonts/OmnesATT/demo-async.htm
+++ b/catalog-ui/src/assets/styles/fonts/OmnesATT/demo-async.htm
diff --git a/catalog-ui/app/styles/fonts/OmnesATT/demo.htm b/catalog-ui/src/assets/styles/fonts/OmnesATT/demo.htm
index edb62ad34a..edb62ad34a 100644
--- a/catalog-ui/app/styles/fonts/OmnesATT/demo.htm
+++ b/catalog-ui/src/assets/styles/fonts/OmnesATT/demo.htm
diff --git a/catalog-ui/app/styles/form-elements.less b/catalog-ui/src/assets/styles/form-elements.less
index 9f8146d3f5..9f8146d3f5 100644
--- a/catalog-ui/app/styles/form-elements.less
+++ b/catalog-ui/src/assets/styles/form-elements.less
diff --git a/catalog-ui/app/styles/global.less b/catalog-ui/src/assets/styles/global.less
index 9faf4aeb0e..9faf4aeb0e 100644
--- a/catalog-ui/app/styles/global.less
+++ b/catalog-ui/src/assets/styles/global.less
diff --git a/catalog-ui/app/styles/images/anonymous.jpg b/catalog-ui/src/assets/styles/images/anonymous.jpg
index 863af35321..863af35321 100644
--- a/catalog-ui/app/styles/images/anonymous.jpg
+++ b/catalog-ui/src/assets/styles/images/anonymous.jpg
Binary files differ
diff --git a/catalog-ui/src/assets/styles/images/att-globe.svg b/catalog-ui/src/assets/styles/images/att-globe.svg
new file mode 100644
index 0000000000..dc9042f524
--- /dev/null
+++ b/catalog-ui/src/assets/styles/images/att-globe.svg
@@ -0,0 +1 @@
+<svg baseProfile="tiny" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 36 36"><path fill="#089EDA" d="M7.1 32c3 2.3 6.8 3.7 10.9 3.7 4.5 0 8.6-1.7 11.7-4.4-1.4.9-5.4 3-11.7 3-5.5 0-9-1.2-10.9-2.3m12.1.9c4.4 0 9.2-1.2 12-3.6.8-.6 1.5-1.5 2.2-2.6.4-.7.8-1.5 1.1-2.2-2.7 3.9-10.4 6.4-18.4 6.4-5.6 0-11.7-1.8-14.1-5.3 2.2 4.8 8.9 7.3 17.2 7.3m-4.8-7.8c-9.1 0-13.4-4.2-14.1-7.1 0 1 .1 2.2.3 3.1.1.4.4 1 .9 1.6 2.2 2.3 7.7 5.5 17.2 5.5 12.9 0 15.9-4.3 16.5-5.7.4-1 .7-2.8.7-4.4v-1c-.9 3.4-11.9 8-21.5 8m-12.5-14.7c-.5 1-1.1 2.8-1.3 3.7-.1.4 0 .6.1.9 1.1 2.3 6.6 6 19.4 6 7.8 0 13.9-1.9 14.9-5.4.2-.6.2-1.3 0-2.2-.3-1-.7-2.2-1.2-3.1.1 4.6-12.7 7.6-19.2 7.6-7 0-12.9-2.8-12.9-6.3.1-.5.2-.9.2-1.2m27.8-5.7c.1.1.1.2.1.4 0 2-6 5.4-15.6 5.4-7.1 0-8.4-2.6-8.4-4.3 0-.6.2-1.2.7-1.8-.9.9-1.7 1.7-2.5 2.7-.3.4-.5.8-.5 1 0 3.5 8.7 5.9 16.7 5.9 8.6 0 12.5-2.8 12.5-5.3 0-.9-.3-1.4-1.2-2.4-.6-.6-1.2-1.1-1.8-1.6m-2.6-1.9c-2.7-1.6-5.7-2.5-9.1-2.5-3.4 0-6.5.9-9.2 2.6-.8.4-1.3.8-1.3 1.3 0 1.5 3.5 3.1 9.7 3.1 6.1 0 10.9-1.8 10.9-3.5.1-.3-.3-.6-1-1"/></svg> \ No newline at end of file
diff --git a/catalog-ui/app/styles/images/att_logo_white.png b/catalog-ui/src/assets/styles/images/att_logo_white.png
index 6321b7582d..6321b7582d 100644
--- a/catalog-ui/app/styles/images/att_logo_white.png
+++ b/catalog-ui/src/assets/styles/images/att_logo_white.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/relationship-icons/AttachesTo.svg b/catalog-ui/src/assets/styles/images/relationship-icons/AttachesTo.svg
index 68b57a08c8..68b57a08c8 100644
--- a/catalog-ui/app/styles/images/relationship-icons/AttachesTo.svg
+++ b/catalog-ui/src/assets/styles/images/relationship-icons/AttachesTo.svg
diff --git a/catalog-ui/app/styles/images/relationship-icons/BindsTo.svg b/catalog-ui/src/assets/styles/images/relationship-icons/BindsTo.svg
index ae5647dda9..ae5647dda9 100644
--- a/catalog-ui/app/styles/images/relationship-icons/BindsTo.svg
+++ b/catalog-ui/src/assets/styles/images/relationship-icons/BindsTo.svg
diff --git a/catalog-ui/app/styles/images/relationship-icons/ConnectedTo.svg b/catalog-ui/src/assets/styles/images/relationship-icons/ConnectedTo.svg
index 4ee7672305..4ee7672305 100644
--- a/catalog-ui/app/styles/images/relationship-icons/ConnectedTo.svg
+++ b/catalog-ui/src/assets/styles/images/relationship-icons/ConnectedTo.svg
diff --git a/catalog-ui/app/styles/images/relationship-icons/DependsOn.svg b/catalog-ui/src/assets/styles/images/relationship-icons/DependsOn.svg
index e38808e2df..e38808e2df 100644
--- a/catalog-ui/app/styles/images/relationship-icons/DependsOn.svg
+++ b/catalog-ui/src/assets/styles/images/relationship-icons/DependsOn.svg
diff --git a/catalog-ui/app/styles/images/relationship-icons/HostedOn.svg b/catalog-ui/src/assets/styles/images/relationship-icons/HostedOn.svg
index 5daf84a334..5daf84a334 100644
--- a/catalog-ui/app/styles/images/relationship-icons/HostedOn.svg
+++ b/catalog-ui/src/assets/styles/images/relationship-icons/HostedOn.svg
diff --git a/catalog-ui/app/styles/images/relationship-icons/LinksTo.svg b/catalog-ui/src/assets/styles/images/relationship-icons/LinksTo.svg
index fb4c687774..fb4c687774 100644
--- a/catalog-ui/app/styles/images/relationship-icons/LinksTo.svg
+++ b/catalog-ui/src/assets/styles/images/relationship-icons/LinksTo.svg
diff --git a/catalog-ui/app/styles/images/relationship-icons/RoutesTo.svg b/catalog-ui/src/assets/styles/images/relationship-icons/RoutesTo.svg
index 4c3caf5886..4c3caf5886 100644
--- a/catalog-ui/app/styles/images/relationship-icons/RoutesTo.svg
+++ b/catalog-ui/src/assets/styles/images/relationship-icons/RoutesTo.svg
diff --git a/catalog-ui/app/styles/images/relationship-icons/arrow.png b/catalog-ui/src/assets/styles/images/relationship-icons/arrow.png
index d7c0ec8a86..d7c0ec8a86 100644
--- a/catalog-ui/app/styles/images/relationship-icons/arrow.png
+++ b/catalog-ui/src/assets/styles/images/relationship-icons/arrow.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/relationship-icons/arrow.svg b/catalog-ui/src/assets/styles/images/relationship-icons/arrow.svg
index 4696e50d57..4696e50d57 100644
--- a/catalog-ui/app/styles/images/relationship-icons/arrow.svg
+++ b/catalog-ui/src/assets/styles/images/relationship-icons/arrow.svg
diff --git a/catalog-ui/app/styles/images/relationship-icons/arrow_connection_right.svg b/catalog-ui/src/assets/styles/images/relationship-icons/arrow_connection_right.svg
index ea2d9f258d..ea2d9f258d 100644
--- a/catalog-ui/app/styles/images/relationship-icons/arrow_connection_right.svg
+++ b/catalog-ui/src/assets/styles/images/relationship-icons/arrow_connection_right.svg
diff --git a/catalog-ui/app/styles/images/relationship-icons/attach.png b/catalog-ui/src/assets/styles/images/relationship-icons/attach.png
index f01ebd86ca..f01ebd86ca 100644
--- a/catalog-ui/app/styles/images/relationship-icons/attach.png
+++ b/catalog-ui/src/assets/styles/images/relationship-icons/attach.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/relationship-icons/binding.png b/catalog-ui/src/assets/styles/images/relationship-icons/binding.png
index 15307d8267..15307d8267 100644
--- a/catalog-ui/app/styles/images/relationship-icons/binding.png
+++ b/catalog-ui/src/assets/styles/images/relationship-icons/binding.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/relationship-icons/conected.png b/catalog-ui/src/assets/styles/images/relationship-icons/conected.png
index 1243146c3f..1243146c3f 100644
--- a/catalog-ui/app/styles/images/relationship-icons/conected.png
+++ b/catalog-ui/src/assets/styles/images/relationship-icons/conected.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/relationship-icons/conected.svg b/catalog-ui/src/assets/styles/images/relationship-icons/conected.svg
index 4ee7672305..4ee7672305 100644
--- a/catalog-ui/app/styles/images/relationship-icons/conected.svg
+++ b/catalog-ui/src/assets/styles/images/relationship-icons/conected.svg
diff --git a/catalog-ui/app/styles/images/relationship-icons/dependency.png b/catalog-ui/src/assets/styles/images/relationship-icons/dependency.png
index 1bfd3e41c6..1bfd3e41c6 100644
--- a/catalog-ui/app/styles/images/relationship-icons/dependency.png
+++ b/catalog-ui/src/assets/styles/images/relationship-icons/dependency.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/relationship-icons/host.png b/catalog-ui/src/assets/styles/images/relationship-icons/host.png
index cf314d1d4a..cf314d1d4a 100644
--- a/catalog-ui/app/styles/images/relationship-icons/host.png
+++ b/catalog-ui/src/assets/styles/images/relationship-icons/host.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/relationship-icons/link.png b/catalog-ui/src/assets/styles/images/relationship-icons/link.png
index 9b81a4de57..9b81a4de57 100644
--- a/catalog-ui/app/styles/images/relationship-icons/link.png
+++ b/catalog-ui/src/assets/styles/images/relationship-icons/link.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/relationship-icons/local_storage.png b/catalog-ui/src/assets/styles/images/relationship-icons/local_storage.png
index f01ebd86ca..f01ebd86ca 100644
--- a/catalog-ui/app/styles/images/relationship-icons/local_storage.png
+++ b/catalog-ui/src/assets/styles/images/relationship-icons/local_storage.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/relationship-icons/local_storage.svg b/catalog-ui/src/assets/styles/images/relationship-icons/local_storage.svg
index e255a4f058..e255a4f058 100644
--- a/catalog-ui/app/styles/images/relationship-icons/local_storage.svg
+++ b/catalog-ui/src/assets/styles/images/relationship-icons/local_storage.svg
diff --git a/catalog-ui/app/styles/images/relationship-icons/rout.png b/catalog-ui/src/assets/styles/images/relationship-icons/rout.png
index 6a3aefac44..6a3aefac44 100644
--- a/catalog-ui/app/styles/images/relationship-icons/rout.png
+++ b/catalog-ui/src/assets/styles/images/relationship-icons/rout.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/Red_PLUS_HOVER.png b/catalog-ui/src/assets/styles/images/resource-icons/Red_PLUS_HOVER.png
index eb623b0204..eb623b0204 100644
--- a/catalog-ui/app/styles/images/resource-icons/Red_PLUS_HOVER.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/Red_PLUS_HOVER.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/Resource_Icons_NB_COLLABORATION-.png b/catalog-ui/src/assets/styles/images/resource-icons/Resource_Icons_NB_COLLABORATION-.png
index b0de76e4eb..b0de76e4eb 100644
--- a/catalog-ui/app/styles/images/resource-icons/Resource_Icons_NB_COLLABORATION-.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/Resource_Icons_NB_COLLABORATION-.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/Resource_Icons_NB_COMPUTE-AS-SERVICE-.png b/catalog-ui/src/assets/styles/images/resource-icons/Resource_Icons_NB_COMPUTE-AS-SERVICE-.png
index ec2723b766..ec2723b766 100644
--- a/catalog-ui/app/styles/images/resource-icons/Resource_Icons_NB_COMPUTE-AS-SERVICE-.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/Resource_Icons_NB_COMPUTE-AS-SERVICE-.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/Resource_Icons_NB_MESSAGING-.png b/catalog-ui/src/assets/styles/images/resource-icons/Resource_Icons_NB_MESSAGING-.png
index e745e20604..e745e20604 100644
--- a/catalog-ui/app/styles/images/resource-icons/Resource_Icons_NB_MESSAGING-.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/Resource_Icons_NB_MESSAGING-.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/Resource_Icons_NB_MOBILITY.png b/catalog-ui/src/assets/styles/images/resource-icons/Resource_Icons_NB_MOBILITY.png
index 4993ffe1f5..4993ffe1f5 100644
--- a/catalog-ui/app/styles/images/resource-icons/Resource_Icons_NB_MOBILITY.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/Resource_Icons_NB_MOBILITY.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/Resource_Icons_NB_NETWORK-.png b/catalog-ui/src/assets/styles/images/resource-icons/Resource_Icons_NB_NETWORK-.png
index fb7a2518c2..fb7a2518c2 100644
--- a/catalog-ui/app/styles/images/resource-icons/Resource_Icons_NB_NETWORK-.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/Resource_Icons_NB_NETWORK-.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/Resource_Icons_NB_NETWORK-CLOUD-.png b/catalog-ui/src/assets/styles/images/resource-icons/Resource_Icons_NB_NETWORK-CLOUD-.png
index a06093726a..a06093726a 100644
--- a/catalog-ui/app/styles/images/resource-icons/Resource_Icons_NB_NETWORK-CLOUD-.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/Resource_Icons_NB_NETWORK-CLOUD-.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/Resource_Icons_NB_NETWORK-L-1-3.png b/catalog-ui/src/assets/styles/images/resource-icons/Resource_Icons_NB_NETWORK-L-1-3.png
index a9f876afd9..a9f876afd9 100644
--- a/catalog-ui/app/styles/images/resource-icons/Resource_Icons_NB_NETWORK-L-1-3.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/Resource_Icons_NB_NETWORK-L-1-3.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/Resource_Icons_NB_NETWORK-L-4.png b/catalog-ui/src/assets/styles/images/resource-icons/Resource_Icons_NB_NETWORK-L-4.png
index e1023e743b..e1023e743b 100644
--- a/catalog-ui/app/styles/images/resource-icons/Resource_Icons_NB_NETWORK-L-4.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/Resource_Icons_NB_NETWORK-L-4.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/Resource_Icons_NB_NOTIFICATION-.png b/catalog-ui/src/assets/styles/images/resource-icons/Resource_Icons_NB_NOTIFICATION-.png
index dfa21d6d34..dfa21d6d34 100644
--- a/catalog-ui/app/styles/images/resource-icons/Resource_Icons_NB_NOTIFICATION-.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/Resource_Icons_NB_NOTIFICATION-.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/Resource_Icons_NB_ORPHAN.png b/catalog-ui/src/assets/styles/images/resource-icons/Resource_Icons_NB_ORPHAN.png
index 91619e0ae8..91619e0ae8 100644
--- a/catalog-ui/app/styles/images/resource-icons/Resource_Icons_NB_ORPHAN.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/Resource_Icons_NB_ORPHAN.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/Resource_Icons_NB_PLATFORM-AS-SERVICE-.png b/catalog-ui/src/assets/styles/images/resource-icons/Resource_Icons_NB_PLATFORM-AS-SERVICE-.png
index 8c763391e6..8c763391e6 100644
--- a/catalog-ui/app/styles/images/resource-icons/Resource_Icons_NB_PLATFORM-AS-SERVICE-.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/Resource_Icons_NB_PLATFORM-AS-SERVICE-.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/Resource_Icons_NB_SECURITY-.png b/catalog-ui/src/assets/styles/images/resource-icons/Resource_Icons_NB_SECURITY-.png
index c015ffe569..c015ffe569 100644
--- a/catalog-ui/app/styles/images/resource-icons/Resource_Icons_NB_SECURITY-.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/Resource_Icons_NB_SECURITY-.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/Resource_Icons_NB_SETTING-.png b/catalog-ui/src/assets/styles/images/resource-icons/Resource_Icons_NB_SETTING-.png
index b9db3ced5a..b9db3ced5a 100644
--- a/catalog-ui/app/styles/images/resource-icons/Resource_Icons_NB_SETTING-.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/Resource_Icons_NB_SETTING-.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/Resource_Icons_NB_avater.png b/catalog-ui/src/assets/styles/images/resource-icons/Resource_Icons_NB_avater.png
index 209e6e7e34..209e6e7e34 100644
--- a/catalog-ui/app/styles/images/resource-icons/Resource_Icons_NB_avater.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/Resource_Icons_NB_avater.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/Resource_Icons_STORAGE-AS-SERVICE.png b/catalog-ui/src/assets/styles/images/resource-icons/Resource_Icons_STORAGE-AS-SERVICE.png
index 86111d0842..86111d0842 100644
--- a/catalog-ui/app/styles/images/resource-icons/Resource_Icons_STORAGE-AS-SERVICE.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/Resource_Icons_STORAGE-AS-SERVICE.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/alcatelLucent.png b/catalog-ui/src/assets/styles/images/resource-icons/alcatelLucent.png
index 259096fea4..259096fea4 100644
--- a/catalog-ui/app/styles/images/resource-icons/alcatelLucent.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/alcatelLucent.png
Binary files differ
diff --git a/catalog-ui/src/assets/styles/images/resource-icons/allotted_resource.png b/catalog-ui/src/assets/styles/images/resource-icons/allotted_resource.png
new file mode 100644
index 0000000000..c494e89e19
--- /dev/null
+++ b/catalog-ui/src/assets/styles/images/resource-icons/allotted_resource.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/applicationServer.png b/catalog-ui/src/assets/styles/images/resource-icons/applicationServer.png
index f50b392249..f50b392249 100644
--- a/catalog-ui/app/styles/images/resource-icons/applicationServer.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/applicationServer.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/aricent.png b/catalog-ui/src/assets/styles/images/resource-icons/aricent.png
index 6cc36f679f..6cc36f679f 100644
--- a/catalog-ui/app/styles/images/resource-icons/aricent.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/aricent.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/att.png b/catalog-ui/src/assets/styles/images/resource-icons/att.png
index 80a814a34f..80a814a34f 100644
--- a/catalog-ui/app/styles/images/resource-icons/att.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/att.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/borderElement.png b/catalog-ui/src/assets/styles/images/resource-icons/borderElement.png
index b3525c2e55..b3525c2e55 100644
--- a/catalog-ui/app/styles/images/resource-icons/borderElement.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/borderElement.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/broadsoft.png b/catalog-ui/src/assets/styles/images/resource-icons/broadsoft.png
index 2539d30d57..2539d30d57 100644
--- a/catalog-ui/app/styles/images/resource-icons/broadsoft.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/broadsoft.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/brocade.png b/catalog-ui/src/assets/styles/images/resource-icons/brocade.png
index 29b713105c..29b713105c 100644
--- a/catalog-ui/app/styles/images/resource-icons/brocade.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/brocade.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/call_controll.png b/catalog-ui/src/assets/styles/images/resource-icons/call_controll.png
index afedac5ad3..afedac5ad3 100644
--- a/catalog-ui/app/styles/images/resource-icons/call_controll.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/call_controll.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/canvasPlusIcon-red.png b/catalog-ui/src/assets/styles/images/resource-icons/canvasPlusIcon-red.png
index bf56d13d6d..bf56d13d6d 100644
--- a/catalog-ui/app/styles/images/resource-icons/canvasPlusIcon-red.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/canvasPlusIcon-red.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/canvasPlusIcon.png b/catalog-ui/src/assets/styles/images/resource-icons/canvasPlusIcon.png
index f2c289cea6..f2c289cea6 100644
--- a/catalog-ui/app/styles/images/resource-icons/canvasPlusIcon.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/canvasPlusIcon.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/cisco.png b/catalog-ui/src/assets/styles/images/resource-icons/cisco.png
index e83c771bf3..e83c771bf3 100644
--- a/catalog-ui/app/styles/images/resource-icons/cisco.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/cisco.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/closeModule.png b/catalog-ui/src/assets/styles/images/resource-icons/closeModule.png
index 994cf2c4a5..994cf2c4a5 100644
--- a/catalog-ui/app/styles/images/resource-icons/closeModule.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/closeModule.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/closeModuleHover.png b/catalog-ui/src/assets/styles/images/resource-icons/closeModuleHover.png
index 47f7cb2c6a..47f7cb2c6a 100644
--- a/catalog-ui/app/styles/images/resource-icons/closeModuleHover.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/closeModuleHover.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/cloud.png b/catalog-ui/src/assets/styles/images/resource-icons/cloud.png
index 8e4c77694e..8e4c77694e 100644
--- a/catalog-ui/app/styles/images/resource-icons/cloud.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/cloud.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/cloudep.png b/catalog-ui/src/assets/styles/images/resource-icons/cloudep.png
index bdaadbd272..bdaadbd272 100644
--- a/catalog-ui/app/styles/images/resource-icons/cloudep.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/cloudep.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/compute.png b/catalog-ui/src/assets/styles/images/resource-icons/compute.png
index 6deb0a0db6..6deb0a0db6 100644
--- a/catalog-ui/app/styles/images/resource-icons/compute.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/compute.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/connector.png b/catalog-ui/src/assets/styles/images/resource-icons/connector.png
index c479eea892..c479eea892 100644
--- a/catalog-ui/app/styles/images/resource-icons/connector.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/connector.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/cp.png b/catalog-ui/src/assets/styles/images/resource-icons/cp.png
index f337d35afa..f337d35afa 100644
--- a/catalog-ui/app/styles/images/resource-icons/cp.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/cp.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/database.png b/catalog-ui/src/assets/styles/images/resource-icons/database.png
index b2e7684222..b2e7684222 100644
--- a/catalog-ui/app/styles/images/resource-icons/database.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/database.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/dcae_analytics.png b/catalog-ui/src/assets/styles/images/resource-icons/dcae_analytics.png
index dd7180479d..dd7180479d 100644
--- a/catalog-ui/app/styles/images/resource-icons/dcae_analytics.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/dcae_analytics.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/dcae_collector.png b/catalog-ui/src/assets/styles/images/resource-icons/dcae_collector.png
index 2870362601..2870362601 100644
--- a/catalog-ui/app/styles/images/resource-icons/dcae_collector.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/dcae_collector.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/dcae_database.png b/catalog-ui/src/assets/styles/images/resource-icons/dcae_database.png
index b2e7684222..b2e7684222 100644
--- a/catalog-ui/app/styles/images/resource-icons/dcae_database.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/dcae_database.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/dcae_microservice.png b/catalog-ui/src/assets/styles/images/resource-icons/dcae_microservice.png
index 933abb106e..933abb106e 100644
--- a/catalog-ui/app/styles/images/resource-icons/dcae_microservice.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/dcae_microservice.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/dcae_policy.png b/catalog-ui/src/assets/styles/images/resource-icons/dcae_policy.png
index befb65ecc6..befb65ecc6 100644
--- a/catalog-ui/app/styles/images/resource-icons/dcae_policy.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/dcae_policy.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/dcae_source.png b/catalog-ui/src/assets/styles/images/resource-icons/dcae_source.png
index 58bfa34553..58bfa34553 100644
--- a/catalog-ui/app/styles/images/resource-icons/dcae_source.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/dcae_source.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/dcae_utilty.png b/catalog-ui/src/assets/styles/images/resource-icons/dcae_utilty.png
index fd68ebf135..fd68ebf135 100644
--- a/catalog-ui/app/styles/images/resource-icons/dcae_utilty.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/dcae_utilty.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/default.png b/catalog-ui/src/assets/styles/images/resource-icons/default.png
index 91619e0ae8..91619e0ae8 100644
--- a/catalog-ui/app/styles/images/resource-icons/default.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/default.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/defaulticon.png b/catalog-ui/src/assets/styles/images/resource-icons/defaulticon.png
index 168859d253..168859d253 100644
--- a/catalog-ui/app/styles/images/resource-icons/defaulticon.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/defaulticon.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/ericsson.png b/catalog-ui/src/assets/styles/images/resource-icons/ericsson.png
index 7e3147593e..7e3147593e 100644
--- a/catalog-ui/app/styles/images/resource-icons/ericsson.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/ericsson.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/firewall.png b/catalog-ui/src/assets/styles/images/resource-icons/firewall.png
index 5650f2276d..5650f2276d 100644
--- a/catalog-ui/app/styles/images/resource-icons/firewall.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/firewall.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/fortinet.png b/catalog-ui/src/assets/styles/images/resource-icons/fortinet.png
index e4e52be0c4..e4e52be0c4 100644
--- a/catalog-ui/app/styles/images/resource-icons/fortinet.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/fortinet.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/gateway.png b/catalog-ui/src/assets/styles/images/resource-icons/gateway.png
index 478a3af494..478a3af494 100644
--- a/catalog-ui/app/styles/images/resource-icons/gateway.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/gateway.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/juniper.png b/catalog-ui/src/assets/styles/images/resource-icons/juniper.png
index ed9b183b3b..ed9b183b3b 100644
--- a/catalog-ui/app/styles/images/resource-icons/juniper.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/juniper.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/loadBalancer.png b/catalog-ui/src/assets/styles/images/resource-icons/loadBalancer.png
index 5c5e555883..5c5e555883 100644
--- a/catalog-ui/app/styles/images/resource-icons/loadBalancer.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/loadBalancer.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/metaswitch.png b/catalog-ui/src/assets/styles/images/resource-icons/metaswitch.png
index 970dfdd756..970dfdd756 100644
--- a/catalog-ui/app/styles/images/resource-icons/metaswitch.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/metaswitch.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/module.png b/catalog-ui/src/assets/styles/images/resource-icons/module.png
index 24574f5ac8..24574f5ac8 100644
--- a/catalog-ui/app/styles/images/resource-icons/module.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/module.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/mysql.png b/catalog-ui/src/assets/styles/images/resource-icons/mysql.png
index 07eeaa7d2a..07eeaa7d2a 100644
--- a/catalog-ui/app/styles/images/resource-icons/mysql.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/mysql.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/network.png b/catalog-ui/src/assets/styles/images/resource-icons/network.png
index c98eef324e..c98eef324e 100644
--- a/catalog-ui/app/styles/images/resource-icons/network.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/network.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/networkrules.png b/catalog-ui/src/assets/styles/images/resource-icons/networkrules.png
index 4fe91fa7e5..4fe91fa7e5 100644
--- a/catalog-ui/app/styles/images/resource-icons/networkrules.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/networkrules.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/nokia_siemens.png b/catalog-ui/src/assets/styles/images/resource-icons/nokia_siemens.png
index 37a702d79f..37a702d79f 100644
--- a/catalog-ui/app/styles/images/resource-icons/nokia_siemens.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/nokia_siemens.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/objectStorage.png b/catalog-ui/src/assets/styles/images/resource-icons/objectStorage.png
index 27212b71c8..27212b71c8 100644
--- a/catalog-ui/app/styles/images/resource-icons/objectStorage.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/objectStorage.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/openModule.png b/catalog-ui/src/assets/styles/images/resource-icons/openModule.png
index 291d0c0361..291d0c0361 100644
--- a/catalog-ui/app/styles/images/resource-icons/openModule.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/openModule.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/openModuleHover.png b/catalog-ui/src/assets/styles/images/resource-icons/openModuleHover.png
index 0206c5e4d3..0206c5e4d3 100644
--- a/catalog-ui/app/styles/images/resource-icons/openModuleHover.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/openModuleHover.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/oracle.png b/catalog-ui/src/assets/styles/images/resource-icons/oracle.png
index b58acc0823..b58acc0823 100644
--- a/catalog-ui/app/styles/images/resource-icons/oracle.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/oracle.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/ossep.png b/catalog-ui/src/assets/styles/images/resource-icons/ossep.png
index 0c921dbc76..0c921dbc76 100644
--- a/catalog-ui/app/styles/images/resource-icons/ossep.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/ossep.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/personep.png b/catalog-ui/src/assets/styles/images/resource-icons/personep.png
index 5b743b62d2..5b743b62d2 100644
--- a/catalog-ui/app/styles/images/resource-icons/personep.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/personep.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/port.png b/catalog-ui/src/assets/styles/images/resource-icons/port.png
index 95285b5b61..95285b5b61 100644
--- a/catalog-ui/app/styles/images/resource-icons/port.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/port.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/premisesep.png b/catalog-ui/src/assets/styles/images/resource-icons/premisesep.png
index bedd82073f..bedd82073f 100644
--- a/catalog-ui/app/styles/images/resource-icons/premisesep.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/premisesep.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/router.png b/catalog-ui/src/assets/styles/images/resource-icons/router.png
index 27d4897f33..27d4897f33 100644
--- a/catalog-ui/app/styles/images/resource-icons/router.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/router.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/securityrules.png b/catalog-ui/src/assets/styles/images/resource-icons/securityrules.png
index 520ab278cb..520ab278cb 100644
--- a/catalog-ui/app/styles/images/resource-icons/securityrules.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/securityrules.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/selectedCPInstance.png b/catalog-ui/src/assets/styles/images/resource-icons/selectedCPInstance.png
index 2f63077037..2f63077037 100644
--- a/catalog-ui/app/styles/images/resource-icons/selectedCPInstance.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/selectedCPInstance.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/selectedInstance.png b/catalog-ui/src/assets/styles/images/resource-icons/selectedInstance.png
index f2f5c90ac9..f2f5c90ac9 100644
--- a/catalog-ui/app/styles/images/resource-icons/selectedInstance.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/selectedInstance.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/selectedUcpeInstance.png b/catalog-ui/src/assets/styles/images/resource-icons/selectedUcpeInstance.png
index f168929ed6..f168929ed6 100644
--- a/catalog-ui/app/styles/images/resource-icons/selectedUcpeInstance.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/selectedUcpeInstance.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/selectedVLInstance.png b/catalog-ui/src/assets/styles/images/resource-icons/selectedVLInstance.png
index 17407f2609..17407f2609 100644
--- a/catalog-ui/app/styles/images/resource-icons/selectedVLInstance.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/selectedVLInstance.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/server.png b/catalog-ui/src/assets/styles/images/resource-icons/server.png
index b51305d58f..b51305d58f 100644
--- a/catalog-ui/app/styles/images/resource-icons/server.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/server.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/tropo.png b/catalog-ui/src/assets/styles/images/resource-icons/tropo.png
index 88a5ea5e68..88a5ea5e68 100644
--- a/catalog-ui/app/styles/images/resource-icons/tropo.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/tropo.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/ucpe.png b/catalog-ui/src/assets/styles/images/resource-icons/ucpe.png
index 8e8e430e3c..8e8e430e3c 100644
--- a/catalog-ui/app/styles/images/resource-icons/ucpe.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/ucpe.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/uncertified.png b/catalog-ui/src/assets/styles/images/resource-icons/uncertified.png
index 35d747a7d0..35d747a7d0 100644
--- a/catalog-ui/app/styles/images/resource-icons/uncertified.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/uncertified.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/vfw.png b/catalog-ui/src/assets/styles/images/resource-icons/vfw.png
index b8adc1f09c..b8adc1f09c 100644
--- a/catalog-ui/app/styles/images/resource-icons/vfw.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/vfw.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/vl.png b/catalog-ui/src/assets/styles/images/resource-icons/vl.png
index 1fb2fc07ce..1fb2fc07ce 100644
--- a/catalog-ui/app/styles/images/resource-icons/vl.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/vl.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/vrouter.png b/catalog-ui/src/assets/styles/images/resource-icons/vrouter.png
index 70e89e5125..70e89e5125 100644
--- a/catalog-ui/app/styles/images/resource-icons/vrouter.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/vrouter.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/resource-icons/wanx.png b/catalog-ui/src/assets/styles/images/resource-icons/wanx.png
index daa493a0f2..daa493a0f2 100644
--- a/catalog-ui/app/styles/images/resource-icons/wanx.png
+++ b/catalog-ui/src/assets/styles/images/resource-icons/wanx.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/service-icons/call_controll.png b/catalog-ui/src/assets/styles/images/service-icons/call_controll.png
index ef1d92757e..ef1d92757e 100644
--- a/catalog-ui/app/styles/images/service-icons/call_controll.png
+++ b/catalog-ui/src/assets/styles/images/service-icons/call_controll.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/service-icons/collaboration.png b/catalog-ui/src/assets/styles/images/service-icons/collaboration.png
index 3d34b914f5..3d34b914f5 100644
--- a/catalog-ui/app/styles/images/service-icons/collaboration.png
+++ b/catalog-ui/src/assets/styles/images/service-icons/collaboration.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/service-icons/collaboration1.png b/catalog-ui/src/assets/styles/images/service-icons/collaboration1.png
index 6780931e2b..6780931e2b 100644
--- a/catalog-ui/app/styles/images/service-icons/collaboration1.png
+++ b/catalog-ui/src/assets/styles/images/service-icons/collaboration1.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/service-icons/compute.png b/catalog-ui/src/assets/styles/images/service-icons/compute.png
index cb2b127ef1..cb2b127ef1 100644
--- a/catalog-ui/app/styles/images/service-icons/compute.png
+++ b/catalog-ui/src/assets/styles/images/service-icons/compute.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/service-icons/defaulticon.png b/catalog-ui/src/assets/styles/images/service-icons/defaulticon.png
index 5afead32d8..5afead32d8 100644
--- a/catalog-ui/app/styles/images/service-icons/defaulticon.png
+++ b/catalog-ui/src/assets/styles/images/service-icons/defaulticon.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/service-icons/messaging.png b/catalog-ui/src/assets/styles/images/service-icons/messaging.png
index eb5f14d178..eb5f14d178 100644
--- a/catalog-ui/app/styles/images/service-icons/messaging.png
+++ b/catalog-ui/src/assets/styles/images/service-icons/messaging.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/service-icons/mobility.png b/catalog-ui/src/assets/styles/images/service-icons/mobility.png
index 285c442aba..285c442aba 100644
--- a/catalog-ui/app/styles/images/service-icons/mobility.png
+++ b/catalog-ui/src/assets/styles/images/service-icons/mobility.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/service-icons/network_l_1-3.png b/catalog-ui/src/assets/styles/images/service-icons/network_l_1-3.png
index 128c2bec8b..128c2bec8b 100644
--- a/catalog-ui/app/styles/images/service-icons/network_l_1-3.png
+++ b/catalog-ui/src/assets/styles/images/service-icons/network_l_1-3.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/service-icons/network_l_4.png b/catalog-ui/src/assets/styles/images/service-icons/network_l_4.png
index 7b05e1b101..7b05e1b101 100644
--- a/catalog-ui/app/styles/images/service-icons/network_l_4.png
+++ b/catalog-ui/src/assets/styles/images/service-icons/network_l_4.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/service-icons/notification.png b/catalog-ui/src/assets/styles/images/service-icons/notification.png
index a5de34c40f..a5de34c40f 100644
--- a/catalog-ui/app/styles/images/service-icons/notification.png
+++ b/catalog-ui/src/assets/styles/images/service-icons/notification.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/service-icons/platform.png b/catalog-ui/src/assets/styles/images/service-icons/platform.png
index 934eae9136..934eae9136 100644
--- a/catalog-ui/app/styles/images/service-icons/platform.png
+++ b/catalog-ui/src/assets/styles/images/service-icons/platform.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/service-icons/storage.png b/catalog-ui/src/assets/styles/images/service-icons/storage.png
index 9abfd2d3a4..9abfd2d3a4 100644
--- a/catalog-ui/app/styles/images/service-icons/storage.png
+++ b/catalog-ui/src/assets/styles/images/service-icons/storage.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/service-icons/uncertified.png b/catalog-ui/src/assets/styles/images/service-icons/uncertified.png
index 35d747a7d0..35d747a7d0 100644
--- a/catalog-ui/app/styles/images/service-icons/uncertified.png
+++ b/catalog-ui/src/assets/styles/images/service-icons/uncertified.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/sprites/sprite-global-old.png b/catalog-ui/src/assets/styles/images/sprites/sprite-global-old.png
index a1014f55d7..a1014f55d7 100644
--- a/catalog-ui/app/styles/images/sprites/sprite-global-old.png
+++ b/catalog-ui/src/assets/styles/images/sprites/sprite-global-old.png
Binary files differ
diff --git a/catalog-ui/src/assets/styles/images/sprites/sprite-global.png b/catalog-ui/src/assets/styles/images/sprites/sprite-global.png
new file mode 100644
index 0000000000..f684d2de9c
--- /dev/null
+++ b/catalog-ui/src/assets/styles/images/sprites/sprite-global.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/sprites/sprite-product-icons.png b/catalog-ui/src/assets/styles/images/sprites/sprite-product-icons.png
index e85467a09c..e85467a09c 100644
--- a/catalog-ui/app/styles/images/sprites/sprite-product-icons.png
+++ b/catalog-ui/src/assets/styles/images/sprites/sprite-product-icons.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/sprites/sprite-resource-icons.png b/catalog-ui/src/assets/styles/images/sprites/sprite-resource-icons.png
index 61989d63e1..7d520a8628 100644
--- a/catalog-ui/app/styles/images/sprites/sprite-resource-icons.png
+++ b/catalog-ui/src/assets/styles/images/sprites/sprite-resource-icons.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/sprites/sprite-services-icons.png b/catalog-ui/src/assets/styles/images/sprites/sprite-services-icons.png
index ac19fa186b..ac19fa186b 100644
--- a/catalog-ui/app/styles/images/sprites/sprite-services-icons.png
+++ b/catalog-ui/src/assets/styles/images/sprites/sprite-services-icons.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/sprites/tlv-sprite.png b/catalog-ui/src/assets/styles/images/sprites/tlv-sprite.png
index 7f11c2ece1..7f11c2ece1 100644
--- a/catalog-ui/app/styles/images/sprites/tlv-sprite.png
+++ b/catalog-ui/src/assets/styles/images/sprites/tlv-sprite.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/tutorial/10.png b/catalog-ui/src/assets/styles/images/tutorial/10.png
index 312d48f99a..312d48f99a 100644
--- a/catalog-ui/app/styles/images/tutorial/10.png
+++ b/catalog-ui/src/assets/styles/images/tutorial/10.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/tutorial/11.png b/catalog-ui/src/assets/styles/images/tutorial/11.png
index 8c4f8aec39..8c4f8aec39 100644
--- a/catalog-ui/app/styles/images/tutorial/11.png
+++ b/catalog-ui/src/assets/styles/images/tutorial/11.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/tutorial/13.png b/catalog-ui/src/assets/styles/images/tutorial/13.png
index d2c35ddb47..d2c35ddb47 100644
--- a/catalog-ui/app/styles/images/tutorial/13.png
+++ b/catalog-ui/src/assets/styles/images/tutorial/13.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/tutorial/14.png b/catalog-ui/src/assets/styles/images/tutorial/14.png
index 0aabc9fd11..0aabc9fd11 100644
--- a/catalog-ui/app/styles/images/tutorial/14.png
+++ b/catalog-ui/src/assets/styles/images/tutorial/14.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/tutorial/15.png b/catalog-ui/src/assets/styles/images/tutorial/15.png
index d6720989c2..d6720989c2 100644
--- a/catalog-ui/app/styles/images/tutorial/15.png
+++ b/catalog-ui/src/assets/styles/images/tutorial/15.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/tutorial/16.png b/catalog-ui/src/assets/styles/images/tutorial/16.png
index 95005bd5a2..95005bd5a2 100644
--- a/catalog-ui/app/styles/images/tutorial/16.png
+++ b/catalog-ui/src/assets/styles/images/tutorial/16.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/tutorial/17.png b/catalog-ui/src/assets/styles/images/tutorial/17.png
index c22875e6d3..c22875e6d3 100644
--- a/catalog-ui/app/styles/images/tutorial/17.png
+++ b/catalog-ui/src/assets/styles/images/tutorial/17.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/tutorial/18.png b/catalog-ui/src/assets/styles/images/tutorial/18.png
index e5b9b5a8b0..e5b9b5a8b0 100644
--- a/catalog-ui/app/styles/images/tutorial/18.png
+++ b/catalog-ui/src/assets/styles/images/tutorial/18.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/tutorial/19.png b/catalog-ui/src/assets/styles/images/tutorial/19.png
index f7374928ba..f7374928ba 100644
--- a/catalog-ui/app/styles/images/tutorial/19.png
+++ b/catalog-ui/src/assets/styles/images/tutorial/19.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/tutorial/2.png b/catalog-ui/src/assets/styles/images/tutorial/2.png
index 4e141bd764..4e141bd764 100644
--- a/catalog-ui/app/styles/images/tutorial/2.png
+++ b/catalog-ui/src/assets/styles/images/tutorial/2.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/tutorial/20.png b/catalog-ui/src/assets/styles/images/tutorial/20.png
index c3849b0a17..c3849b0a17 100644
--- a/catalog-ui/app/styles/images/tutorial/20.png
+++ b/catalog-ui/src/assets/styles/images/tutorial/20.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/tutorial/21.png b/catalog-ui/src/assets/styles/images/tutorial/21.png
index aa60a153a0..aa60a153a0 100644
--- a/catalog-ui/app/styles/images/tutorial/21.png
+++ b/catalog-ui/src/assets/styles/images/tutorial/21.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/tutorial/22.png b/catalog-ui/src/assets/styles/images/tutorial/22.png
index 0d4a71c1e4..0d4a71c1e4 100644
--- a/catalog-ui/app/styles/images/tutorial/22.png
+++ b/catalog-ui/src/assets/styles/images/tutorial/22.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/tutorial/23.png b/catalog-ui/src/assets/styles/images/tutorial/23.png
index 6854d0e4e5..6854d0e4e5 100644
--- a/catalog-ui/app/styles/images/tutorial/23.png
+++ b/catalog-ui/src/assets/styles/images/tutorial/23.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/tutorial/24.png b/catalog-ui/src/assets/styles/images/tutorial/24.png
index 099fa28874..099fa28874 100644
--- a/catalog-ui/app/styles/images/tutorial/24.png
+++ b/catalog-ui/src/assets/styles/images/tutorial/24.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/tutorial/25.png b/catalog-ui/src/assets/styles/images/tutorial/25.png
index 718cf4a65f..718cf4a65f 100644
--- a/catalog-ui/app/styles/images/tutorial/25.png
+++ b/catalog-ui/src/assets/styles/images/tutorial/25.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/tutorial/26.png b/catalog-ui/src/assets/styles/images/tutorial/26.png
index cd4885ec4a..cd4885ec4a 100644
--- a/catalog-ui/app/styles/images/tutorial/26.png
+++ b/catalog-ui/src/assets/styles/images/tutorial/26.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/tutorial/27.png b/catalog-ui/src/assets/styles/images/tutorial/27.png
index 85c7378e39..85c7378e39 100644
--- a/catalog-ui/app/styles/images/tutorial/27.png
+++ b/catalog-ui/src/assets/styles/images/tutorial/27.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/tutorial/28.png b/catalog-ui/src/assets/styles/images/tutorial/28.png
index 54c5ada0d7..54c5ada0d7 100644
--- a/catalog-ui/app/styles/images/tutorial/28.png
+++ b/catalog-ui/src/assets/styles/images/tutorial/28.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/tutorial/29.png b/catalog-ui/src/assets/styles/images/tutorial/29.png
index ae07010492..ae07010492 100644
--- a/catalog-ui/app/styles/images/tutorial/29.png
+++ b/catalog-ui/src/assets/styles/images/tutorial/29.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/tutorial/3.png b/catalog-ui/src/assets/styles/images/tutorial/3.png
index ff1a86b4d0..ff1a86b4d0 100644
--- a/catalog-ui/app/styles/images/tutorial/3.png
+++ b/catalog-ui/src/assets/styles/images/tutorial/3.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/tutorial/30.png b/catalog-ui/src/assets/styles/images/tutorial/30.png
index ef83db0e01..ef83db0e01 100644
--- a/catalog-ui/app/styles/images/tutorial/30.png
+++ b/catalog-ui/src/assets/styles/images/tutorial/30.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/tutorial/4.png b/catalog-ui/src/assets/styles/images/tutorial/4.png
index dfc148868e..dfc148868e 100644
--- a/catalog-ui/app/styles/images/tutorial/4.png
+++ b/catalog-ui/src/assets/styles/images/tutorial/4.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/tutorial/5.png b/catalog-ui/src/assets/styles/images/tutorial/5.png
index f18e52527d..f18e52527d 100644
--- a/catalog-ui/app/styles/images/tutorial/5.png
+++ b/catalog-ui/src/assets/styles/images/tutorial/5.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/tutorial/6.png b/catalog-ui/src/assets/styles/images/tutorial/6.png
index 173dc55d1c..173dc55d1c 100644
--- a/catalog-ui/app/styles/images/tutorial/6.png
+++ b/catalog-ui/src/assets/styles/images/tutorial/6.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/tutorial/7.png b/catalog-ui/src/assets/styles/images/tutorial/7.png
index 3e31376143..3e31376143 100644
--- a/catalog-ui/app/styles/images/tutorial/7.png
+++ b/catalog-ui/src/assets/styles/images/tutorial/7.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/tutorial/8.png b/catalog-ui/src/assets/styles/images/tutorial/8.png
index 59f95dfa2e..59f95dfa2e 100644
--- a/catalog-ui/app/styles/images/tutorial/8.png
+++ b/catalog-ui/src/assets/styles/images/tutorial/8.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/welcome.png b/catalog-ui/src/assets/styles/images/welcome.png
index 8534a33088..8534a33088 100644
--- a/catalog-ui/app/styles/images/welcome.png
+++ b/catalog-ui/src/assets/styles/images/welcome.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/welcome/bg/002.png b/catalog-ui/src/assets/styles/images/welcome/002.png
index f3e7a7c3ed..f3e7a7c3ed 100644
--- a/catalog-ui/app/styles/images/welcome/bg/002.png
+++ b/catalog-ui/src/assets/styles/images/welcome/002.png
Binary files differ
diff --git a/catalog-ui/app/styles/images/welcome/sprite.png b/catalog-ui/src/assets/styles/images/welcome/sprite.png
index 3bb7542446..3bb7542446 100644
--- a/catalog-ui/app/styles/images/welcome/sprite.png
+++ b/catalog-ui/src/assets/styles/images/welcome/sprite.png
Binary files differ
diff --git a/catalog-ui/app/styles/layout/header.less b/catalog-ui/src/assets/styles/layout/header.less
index f8e95e8b41..f8e95e8b41 100644
--- a/catalog-ui/app/styles/layout/header.less
+++ b/catalog-ui/src/assets/styles/layout/header.less
diff --git a/catalog-ui/app/styles/layout/main.less b/catalog-ui/src/assets/styles/layout/main.less
index 925da09431..54f6b87d7c 100644
--- a/catalog-ui/app/styles/layout/main.less
+++ b/catalog-ui/src/assets/styles/layout/main.less
@@ -8,7 +8,7 @@
top: @header_height + @top_nav_height;
left: 0;
right: 0;
- bottom: 0;
+ bottom: @footer_height;
.w-sdc-main-right-container {
.bg_n;
@@ -20,13 +20,23 @@
top: 0;
overflow: hidden;
-
- & > div:first-child { /* scroll fix */
+ & > div:first-child {
padding-bottom: 80px;
}
+
+ .sdc-tile-catalog {
+ margin: 10px;
+ }
+
}
}
+.w-sdc-row-flex-items {
+ display: flex;
+ flex-wrap: wrap;
+ flex-direction: row;
+}
+
.sdc-loading-page {
display: flex;
align-items: center;
diff --git a/catalog-ui/app/styles/layout/sidebar.less b/catalog-ui/src/assets/styles/layout/sidebar.less
index 9b8dc240c7..9b8dc240c7 100644
--- a/catalog-ui/app/styles/layout/sidebar.less
+++ b/catalog-ui/src/assets/styles/layout/sidebar.less
diff --git a/catalog-ui/app/styles/mixins.less b/catalog-ui/src/assets/styles/mixins.less
index 7bd413ed05..7ce9906d88 100644
--- a/catalog-ui/app/styles/mixins.less
+++ b/catalog-ui/src/assets/styles/mixins.less
@@ -92,32 +92,6 @@
}
}
-.buildForColor(a);
-.buildForColor(b);
-.buildForColor(c);
-.buildForColor(d);
-.buildForColor(e);
-.buildForColor(f);
-.buildForColor(g);
-.buildForColor(h);
-.buildForColor(i);
-.buildForColor(j);
-.buildForColor(k);
-.buildForColor(l);
-.buildForColor(m);
-.buildForColor(n);
-.buildForColor(o);
-.buildForColor(p);
-
-.buildForFuncColor(q);
-.buildForFuncColor(r);
-.buildForFuncColor(s);
-
-.buildForTlvColor(t);
-.buildForTlvColor(u);
-.buildForTlvColor(v);
-
-
.buildForColor(@c){
.@{c}_36 { color: ~"@{main_color_@{c}}"; .f-type > ._36;}
.@{c}_24 { color: ~"@{main_color_@{c}}"; .f-type > ._24;}
@@ -173,6 +147,32 @@
.@{c}_12_i { color: ~"@{tlv_color_@{c}}"; .f-type > ._12_i;}
}
+.buildForColor(a);
+.buildForColor(b);
+.buildForColor(c);
+.buildForColor(d);
+.buildForColor(e);
+.buildForColor(f);
+.buildForColor(g);
+.buildForColor(h);
+.buildForColor(i);
+.buildForColor(j);
+.buildForColor(k);
+.buildForColor(l);
+.buildForColor(m);
+.buildForColor(n);
+.buildForColor(o);
+.buildForColor(p);
+
+.buildForFuncColor(q);
+.buildForFuncColor(r);
+.buildForFuncColor(s);
+
+.buildForTlvColor(t);
+.buildForTlvColor(u);
+.buildForTlvColor(v);
+
+
.disabled {
opacity: 0.4 !important;
cursor: auto;
diff --git a/catalog-ui/app/styles/mixins_old.less b/catalog-ui/src/assets/styles/mixins_old.less
index 8a4f609497..8a4f609497 100644
--- a/catalog-ui/app/styles/mixins_old.less
+++ b/catalog-ui/src/assets/styles/mixins_old.less
diff --git a/catalog-ui/app/styles/modal.less b/catalog-ui/src/assets/styles/modal.less
index 7c8bcd7c1d..eb9de92f80 100644
--- a/catalog-ui/app/styles/modal.less
+++ b/catalog-ui/src/assets/styles/modal.less
@@ -177,6 +177,7 @@ NEW DESIGN MODAL
box-shadow: 0px 0px 6px 0px rgba(0, 0, 0, 0.5);
min-height: 165px;
min-width: 430px;
+ word-wrap: break-word;
.w-sdc-modal-head {
flex-grow: 1;
diff --git a/catalog-ui/src/assets/styles/multi-level-expand-collapse.less b/catalog-ui/src/assets/styles/multi-level-expand-collapse.less
new file mode 100644
index 0000000000..090768f187
--- /dev/null
+++ b/catalog-ui/src/assets/styles/multi-level-expand-collapse.less
@@ -0,0 +1,33 @@
+.first-level{
+ background-color: @tlv_color_u;
+ padding:8px 20px 8px 8px !important;
+ border-bottom: 1px solid rgba(0,0,0,0.1);
+ box-shadow: inset 0px -1px 0px 0px rgba(255, 255, 255, 0.7);
+ height: 40px;
+}
+
+.second-level{
+ background-color: @tlv_color_t;
+ padding:4px 20px 4px 37px !important;
+ border-bottom: 1px solid @main_color_o;
+ height: 30px;
+}
+
+.expand-collapse-title-icon,.expand-collapse-title-text{
+ vertical-align: middle;
+}
+
+.expanded{
+ .first-level,.second-level{
+ background-color: @tlv_color_v;
+ border-left: solid @main_color_a 4px;
+ box-shadow: 0 0px 3px -1px rgba(0,0,0,0.3);
+ margin-bottom: 2px;
+ }
+ .first-level{
+ padding-left: 4px !important;
+ }
+ .second-level{
+ padding-left: 33px !important;
+ }
+}
diff --git a/catalog-ui/app/styles/scroller.less b/catalog-ui/src/assets/styles/scroller.less
index fcdaf12f3f..fcdaf12f3f 100644
--- a/catalog-ui/app/styles/scroller.less
+++ b/catalog-ui/src/assets/styles/scroller.less
diff --git a/catalog-ui/src/assets/styles/sdc-ui.css b/catalog-ui/src/assets/styles/sdc-ui.css
new file mode 100644
index 0000000000..5247ecda1a
--- /dev/null
+++ b/catalog-ui/src/assets/styles/sdc-ui.css
@@ -0,0 +1,361 @@
+@charset "UTF-8";
+/* Colors */
+.sdc-bc-blue {
+ background-color: #009fdb; }
+
+.sdc-bc-dark-blue {
+ background-color: #0568ae; }
+
+.sdc-bc-light-blue {
+ background-color: #71c5e8; }
+
+.sdc-bc-green {
+ background-color: #4ca90c; }
+
+.sdc-bc-dark-green {
+ background-color: #007a3e; }
+
+.sdc-bc-light-green {
+ background-color: #b5bd00; }
+
+.sdc-bc-orange {
+ background-color: #ea7400; }
+
+.sdc-bc-yellow {
+ background-color: #ffb81c; }
+
+.sdc-bc-dark-purple {
+ background-color: #702f8a; }
+
+.sdc-bc-purple {
+ background-color: #9063cd; }
+
+.sdc-bc-light-purple {
+ background-color: #caa2dd; }
+
+.sdc-bc-black {
+ background-color: #000000; }
+
+.sdc-bc-dark-gray {
+ background-color: #5a5a5a; }
+
+.sdc-bc-gray {
+ background-color: #959595; }
+
+.sdc-bc-light-gray {
+ background-color: #d2d2d2; }
+
+.sdc-bc-white {
+ background-color: #ffffff; }
+
+/* Prefix */
+/* Value Prefix*/
+/* Box sizing */
+/* Borders & Shadows */
+/* Opacity */
+/* Ellipsis */
+/* Vertical placement of multuple lines of text */
+/* transform-rotate */
+/* transform-translate */
+/* transform-scale */
+/**/
+/**/
+/*body {*/
+ /*-webkit-touch-callout: none;*/
+ /*-webkit-user-select: none;*/
+ /*-moz-user-select: none;*/
+ /*-ms-user-select: none;*/
+ /*user-select: none; }*/
+
+html {
+ font-size: 100%;
+ height: 100%; }
+
+body {
+ /* scrollbar styling for Internet Explorer */
+ scrollbar-face-color: #191919;
+ scrollbar-track-color: #191919;
+ height: 100%; }
+
+/* scrollbar styling for Google Chrome | Safari | Opera */
+::-webkit-scrollbar {
+ width: 8px;
+ height: 8px; }
+
+::-webkit-scrollbar-track {
+ background-color: transparent;
+ border-radius: 10px; }
+
+::-webkit-scrollbar-thumb {
+ border-radius: 10px;
+ background-color: #d2d2d2;
+ border-right: 2px solid #ffffff; }
+
+/* Mozilla Firefox currently doesn't support scrollbar styling */
+ul {
+ list-style: none; }
+
+h1, h2, h3, h4, h5, h6, ul {
+ margin: 0;
+ padding: 0; }
+
+.disabled {
+ opacity: 0.7 !important; }
+
+fieldset {
+ border: none; }
+
+fieldset label {
+ display: inline-block; }
+
+.nav-tabs > li > a:focus,
+.btn:focus,
+.btn:active:focus,
+.btn.active:focus {
+ outline: none; }
+
+/* Fonts */
+.text-lowercase {
+ text-transform: lowercase; }
+
+.text-uppercase, .heading-3-light, .heading-3, .heading-3-medium {
+ text-transform: uppercase; }
+
+.text-capitalize {
+ text-transform: capitalize; }
+
+.heading-1 {
+ font-weight: 300;
+ font-size: 36px; }
+
+.heading-2 {
+ font-weight: 300;
+ font-size: 24px; }
+
+.heading-3-light {
+ font-weight: 300;
+ font-size: 20px; }
+
+.heading-3 {
+ font-weight: 400;
+ font-size: 20px; }
+
+.heading-3-medium {
+ font-weight: 600;
+ font-size: 20px; }
+
+.heading-4 {
+ font-weight: 400;
+ font-size: 18px; }
+
+.heading-4-medium {
+ font-weight: 600;
+ font-size: 18px; }
+
+.heading-5 {
+ font-weight: 400;
+ font-size: 16px; }
+
+.heading-5-medium, .catalog-tile .catalog-tile-top .catalog-tile-item-name, .sdc-tile-catalog .sdc-tile-content .sdc-tile-content-info .sdc-tile-content-info-item-name {
+ font-weight: 400;
+ line-height: 16px;
+ font-size: 16px; }
+
+.body-1 {
+ font-weight: 400;
+ font-size: 14px; }
+
+.body-1-medium {
+ font-weight: 600;
+ font-size: 14px; }
+
+.body-1-light {
+ font-weight: 300;
+ font-size: 14px; }
+
+.body-2, .catalog-tile .catalog-tile-top .catalog-tile-entity-details .catalog-tile-version-info .catalog-tile-item-version, .catalog-tile .catalog-tile-content .catalog-tile-locking-user-name, .sdc-tile-catalog .sdc-tile-content .sdc-tile-content-info .sdc-tile-content-info-version-info .sdc-tile-content-info-version-info-text, .sdc-tile-catalog .sdc-tile-footer .sdc-tile-footer-text {
+ font-weight: 400;
+ font-size: 13px; }
+
+.body-2-medium, .catalog-tile .catalog-tile-content {
+ font-weight: 600;
+ font-size: 13px; }
+
+.body-3 {
+ font-weight: 400;
+ font-size: 12px; }
+
+.body-3-medium, .catalog-tile .catalog-tile-top .catalog-tile-entity-details .catalog-tile-vendor-name, .catalog-tile.vendor-type .catalog-tile-top .catalog-tile-vsp-count, .sdc-tile-catalog .sdc-tile-content .sdc-tile-content-info .sdc-tile-content-info-vendor-name {
+ font-weight: 600;
+ font-size: 12px; }
+
+.body-3-light {
+ font-weight: 300;
+ font-size: 12px; }
+
+.circle-icon-text {
+ font-weight: 600;
+ font-size: 14px; }
+
+.sdc-icon {
+ display: inline-block;
+ text-rendering: auto;
+ -webkit-font-smoothing: antialiased;
+ -moz-osx-font-smoothing: grayscale;
+ width: 16px;
+ height: 16px; }
+
+.sdc-icon-locked {
+ background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='11' height='15' viewBox='0 0 11 15' id='locked_icon'> <metadata><?xpacket begin='' id='W5M0MpCehiHzreSzNTczkc9d'?><x:xmpmeta xmlns:x='adobe:ns:meta/' x:xmptk='Adobe XMP Core 5.6-c138 79.159824, 2016/09/14-01:09:01 '> <rdf:RDF xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'> <rdf:Description rdf:about=''/> </rdf:RDF></x:xmpmeta><?xpacket end='w'?></metadata><defs> <style> .cls-1 { fill: #959595; fill-rule: evenodd; } </style> </defs> <path id='Shape_77_copy_10' data-name='Shape 77 copy 10' class='cls-1' d='M445,359a16.71,16.71,0,0,0-2.1-.009c-1.945.045-3.195,0.049-3.9,0.009v-5a1.743,1.743,0,0,1,2-2h1a1.743,1.743,0,0,1,2,2v5c0.474,0.063.343-.073,1,0,0.266,0.029,0,.279,0,0v-5a2.726,2.726,0,0,0-3-3h-1.142c-1.72-.125-2.715,1.562-2.858,3,0.088,0.009,0,7.338,0,5h0a1.891,1.891,0,0,0-2,1.689v3.461A1.823,1.823,0,0,0,437.775,366h7.448A1.823,1.823,0,0,0,447,364.15v-3.461A2.018,2.018,0,0,0,445,359Z' transform='translate(-436 -351)'/></svg>");
+ background-repeat: no-repeat; }
+
+.sdc-icon-plus {
+ background-image: url("data:image/svg+xml;utf8,<?xml version='1.0' encoding='utf-8'?><!-- Generator: Adobe Illustrator 21.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) --><svg version='1.1' id='plus_icon' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' viewBox='0 0 19 19' style='enable-background:new 0 0 19 19;' xml:space='preserve'><g><rect y='8' width='19' height='3'/><path id='Rectangle_2139_copy' d='M8,19V0h3v19H8z'/></g></svg>");
+ background-repeat: no-repeat; }
+
+.sdc-icon-unlocked {
+ background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='11' height='18' viewBox='0 0 11 18' id='unlocked_icon'> <metadata><?xpacket begin='' id='W5M0MpCehiHzreSzNTczkc9d'?><x:xmpmeta xmlns:x='adobe:ns:meta/' x:xmptk='Adobe XMP Core 5.6-c138 79.159824, 2016/09/14-01:09:01 '> <rdf:RDF xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'> <rdf:Description rdf:about=''/> </rdf:RDF></x:xmpmeta><?xpacket end='w'?></metadata><defs> <style> .cls-1 { fill: #959595; fill-rule: evenodd; } </style> </defs> <path id='Shape_77_copy_16' data-name='Shape 77 copy 16' class='cls-1' d='M663,358a16.723,16.723,0,0,0-2.1-.009c-1.944.045-3.194,0.049-3.9,0.009v-7a1.743,1.743,0,0,1,2-2h1a1.743,1.743,0,0,1,2,2v2c0.474,0.064.343-.073,1,0,0.266,0.029,0,.279,0,0v-2a2.726,2.726,0,0,0-3-3h-1.142c-1.72-.125-2.715,1.562-2.858,3,0.088,0.009,0,9.338,0,7h0a1.891,1.891,0,0,0-2,1.689v4.461a1.823,1.823,0,0,0,1.775,1.85h7.448A1.823,1.823,0,0,0,665,364.15v-4.461A2.018,2.018,0,0,0,663,358Zm1.05,6.15a0.827,0.827,0,0,1-.8.836H655.8a0.827,0.827,0,0,1-.8-0.836l0-4.15a1.164,1.164,0,0,1,.8-1.147h7.448A1.129,1.129,0,0,1,664,360Z' transform='translate(-654 -348)'/></svg>");
+ background-repeat: no-repeat; }
+
+.sdc-icon-vendor {
+ background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 53 47' id='vendor_icon'><title>vendor</title><g id='Layer_2' data-name='Layer 2'><g id='vlm_icon' data-name='vlm icon'><path d='M49,7,38.5,7V5.92A5.92,5.92,0,0,0,32.58,0H20.42A5.92,5.92,0,0,0,14.5,5.92V7.15L4,7.2a3.8,3.8,0,0,0-4,3.5V43.5C0,45.4,2,47,4.2,47L49,46.8a3.8,3.8,0,0,0,4-3.5V10.5A3.8,3.8,0,0,0,49,7ZM16.5,5.92A3.92,3.92,0,0,1,20.42,2H32.58A3.92,3.92,0,0,1,36.5,5.92V7.06l-20,.09ZM2,10.8A1.9,1.9,0,0,1,4,9l45-.2a1.9,1.9,0,0,1,2,1.8v8.87L32.94,24.18a6.49,6.49,0,0,0-12.89,0L2,19.51V10.8ZM31,25a4.5,4.5,0,1,1-4.5-4.5A4.5,4.5,0,0,1,31,25ZM49,45,4,45.2A1.9,1.9,0,0,1,2,43.4V21.57l18.13,4.73a6.5,6.5,0,0,0,12.74,0L51,21.53V43.21A1.9,1.9,0,0,1,49,45Z'/></g></g></svg>");
+ background-repeat: no-repeat; }
+
+.sdc-icon-vlm {
+ background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 45 53'><title>vlm_new_icon</title><g id='Layer_2' data-name='Layer 2'><g id='vlm_icon' data-name='vlm icon'><path d='M41,2a2,2,0,0,1,2,2l.19,45a2,2,0,0,1-2,2H4a2,2,0,0,1-2-2L1.81,4a2,2,0,0,1,2-2H41m-.15-2H4A4.2,4.2,0,0,0,0,4.24L.19,49a4,4,0,0,0,4,4H41a4,4,0,0,0,4-4L44.81,4a4,4,0,0,0-4-4Z'/><rect x='14' y='11' width='17' height='2'/><rect x='14' y='18' width='10' height='2'/><polygon points='20.56 38.85 13.87 33.14 15.16 31.62 20.39 36.08 29.08 26.63 30.55 27.98 20.56 38.85'/></g></g></svg>");
+ background-repeat: no-repeat; }
+
+.sdc-icon-vsp {
+ background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 59.5 40' id='vsp_icon'><title>vsp_new_icon</title><g id='Layer_2' data-name='Layer 2'><g id='vlm_icon' data-name='vlm icon'><path d='M58.28,30.74c-1.49-1.82-3-2.7-4.67-2.74a8.5,8.5,0,0,0-16.22-2.44,6.93,6.93,0,0,0-4.06.66A7.23,7.23,0,0,0,36.42,40H53.5a6,6,0,0,0,6-6A5.18,5.18,0,0,0,58.28,30.74ZM53.5,38H36.42a5.25,5.25,0,0,1-5.21-5.91,5.32,5.32,0,0,1,3-4.06,5,5,0,0,1,2.21-.53,5.25,5.25,0,0,1,1.35.18l.92.24L39,27A6.5,6.5,0,0,1,51.67,29v1.3l1.17-.2c1-.17,2.17-.17,3.91,2a3.18,3.18,0,0,1,.76,2A4,4,0,0,1,53.5,38Z'/><path d='M49,0,4,.17A3.79,3.79,0,0,0,0,3.69V7.94H0v2H0V36.31C0,38.35,2,40,4.25,40l20.84-.08a1,1,0,0,0,0-1.92L4,38.08a1.89,1.89,0,0,1-2-1.76V10H51v7a1,1,0,0,0,2,0V3.53A3.79,3.79,0,0,0,49,0ZM2,8V3.76A1.89,1.89,0,0,1,4,2l45-.16a1.89,1.89,0,0,1,2,1.76V8Z'/></g></g></svg>");
+ background-repeat: no-repeat; }
+
+.svg-icon.purple {
+ fill: #9063cd; }
+
+.svg-icon.purple-hover {
+ fill: #9063cd; }
+ .svg-icon.purple-hover:hover {
+ fill: #caa2dd; }
+
+.svg-icon.blue {
+ fill: #009fdb; }
+
+.svg-icon.blue-hover {
+ fill: #009fdb; }
+ .svg-icon.blue-hover:hover {
+ fill: #71c5e8; }
+
+.svg-icon.gray {
+ fill: #959595; }
+
+.svg-icon.gray-hover {
+ fill: #000000; }
+ .svg-icon.gray-hover:hover {
+ fill: #d2d2d2; }
+
+.svg-icon.black {
+ fill: #000000; }
+
+.svg-icon.black-hover {
+ fill: #000000; }
+ .svg-icon.black-hover:hover {
+ fill: #d2d2d2; }
+
+.sdc-tile, .sdc-tile-catalog {
+ box-sizing: border-box;
+ background-color: #ffffff;
+ display: flex;
+ flex-direction: column;
+ padding: 10px;
+ cursor: pointer;
+ border: 1px solid #eaeaea;
+ -webkit-box-shadow: 0.5px 0.8px 4px 0 rgba(24, 24, 25, 0.05);
+ -moz-box-shadow: 0.5px 0.8px 4px 0 rgba(24, 24, 25, 0.05);
+ box-shadow: 0.5px 0.8px 4px 0 rgba(24, 24, 25, 0.05); }
+ .sdc-tile:active, .sdc-tile-catalog:active {
+ border: 1px solid #71c5e8; }
+ .sdc-tile:hover, .sdc-tile-catalog:hover {
+ box-shadow: 0.3px 5px 12.8px 1.3px rgba(24, 24, 25, 0.15);
+ border: 1px solid #d2d2d2; }
+ .sdc-tile .sdc-tile-header, .sdc-tile-catalog .sdc-tile-header {
+ position: relative;
+ flex-shrink: 0;
+ display: flex;
+ align-items: flex-start;
+ flex-direction: column; }
+ .sdc-tile .sdc-tile-content, .sdc-tile-catalog .sdc-tile-content {
+ position: relative;
+ flex: 1;
+ display: flex;
+ align-items: flex-start;
+ flex-direction: column;
+ overflow: auto;
+ justify-content: space-between; }
+ .sdc-tile .sdc-tile-footer, .sdc-tile-catalog .sdc-tile-footer {
+ position: relative;
+ flex-shrink: 0;
+ display: flex;
+ align-items: flex-start;
+ flex-direction: column; }
+
+.sdc-tile-catalog {
+ width: 204px;
+ height: 200px; }
+ .sdc-tile-catalog .sdc-tile-header {
+ line-height: 16px; }
+ .sdc-tile-catalog .sdc-tile-header .sdc-tile-header-type {
+ font-size: 16px;
+ text-transform: uppercase; }
+ .sdc-tile-catalog .sdc-tile-header .sdc-tile-header-type.purple {
+ color: #9063cd; }
+ .sdc-tile-catalog .sdc-tile-header .sdc-tile-header-type.blue {
+ color: #009fdb; }
+ .sdc-tile-catalog .sdc-tile-content .sdc-tile-content-icon {
+ align-items: center;
+ display: flex;
+ flex-direction: column;
+ width: 100%;
+ padding-top: 25px; }
+ .sdc-tile-catalog .sdc-tile-content .sdc-tile-content-icon svg {
+ width: 60px;
+ height: 40px; }
+ .sdc-tile-catalog .sdc-tile-content .sdc-tile-content-info {
+ padding-bottom: 4px;
+ width: 180px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ width: auto;
+ white-space: nowrap;
+ display: inline-block;
+ max-width: 178px; }
+ .sdc-tile-catalog .sdc-tile-content .sdc-tile-content-info .sdc-tile-content-info-vendor-name {
+ color: #959595;
+ line-height: 12px; }
+ .sdc-tile-catalog .sdc-tile-content .sdc-tile-content-info .sdc-tile-content-info-item-name {
+ color: #191919; }
+ .sdc-tile-catalog .sdc-tile-content .sdc-tile-content-info .sdc-tile-content-info-version-info {
+ display: flex;
+ justify-content: space-between; }
+ .sdc-tile-catalog .sdc-tile-footer {
+ display: flex;
+ flex-direction: row;
+ border-top: 1px solid #eaeaea;
+ padding: 0;
+ width: 180px;
+ height: 20px; }
+ .sdc-tile-catalog .sdc-tile-footer .sdc-tile-footer-text {
+ flex: 1;
+ padding-top: 5px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ width: auto;
+ white-space: nowrap;
+ display: inline-block;
+ max-width: 164px; }
+ .sdc-tile-catalog .sdc-tile-footer .sdc-tile-footer-icon {
+ flex-shrink: 1;
+ overflow: hidden;
+ padding-top: 5px; }
+ .sdc-tile-catalog .sdc-tile-footer .sdc-tile-footer-icon svg {
+ width: 16px;
+ height: 20px; }
diff --git a/catalog-ui/app/styles/sprite-old.less b/catalog-ui/src/assets/styles/sprite-old.less
index cb2dc2fbe0..cb2dc2fbe0 100644
--- a/catalog-ui/app/styles/sprite-old.less
+++ b/catalog-ui/src/assets/styles/sprite-old.less
diff --git a/catalog-ui/app/styles/sprite-product-icons.less b/catalog-ui/src/assets/styles/sprite-product-icons.less
index 3485ec89a3..3485ec89a3 100644
--- a/catalog-ui/app/styles/sprite-product-icons.less
+++ b/catalog-ui/src/assets/styles/sprite-product-icons.less
diff --git a/catalog-ui/app/styles/sprite-resource-icons.less b/catalog-ui/src/assets/styles/sprite-resource-icons.less
index 0f36527dda..153e8c042c 100644
--- a/catalog-ui/app/styles/sprite-resource-icons.less
+++ b/catalog-ui/src/assets/styles/sprite-resource-icons.less
@@ -256,3 +256,13 @@
.sprite-resource-icons.dcae_policy.medium { background-position: -141px -4336px; width: 41px; height: 41px;}
.sprite-resource-icons.dcae_policy.large { background-position: -70px -4317px; width: 60px; height: 60px;}
+.sprite-resource-icons.monitoring_template { background-position: -283px -4824px; width: 54px; height: 36px;}
+.sprite-resource-icons.monitoring_template.small { background-position: -211px -4831px; width: 29px; height: 29px;}
+.sprite-resource-icons.monitoring_template.medium { background-position: -142px -4819px; width: 41px; height: 41px;}
+.sprite-resource-icons.monitoring_template.large { background-position: -71px -4800px; width: 60px; height: 60px;}
+
+.sprite-resource-icons.allotted_resource { background-position: -283px -4896px; width: 44px; height: 44px;}
+.sprite-resource-icons.allotted_resource.small { background-position: -210px -4910px; width: 29px; height: 29px;}
+.sprite-resource-icons.allotted_resource.medium { background-position: -141px -4898px; width: 41px; height: 41px;}
+.sprite-resource-icons.allotted_resource.large { background-position: -70px -4879px; width: 60px; height: 60px;}
+
diff --git a/catalog-ui/app/styles/sprite-services-icons.less b/catalog-ui/src/assets/styles/sprite-services-icons.less
index d1e666ff12..d1e666ff12 100644
--- a/catalog-ui/app/styles/sprite-services-icons.less
+++ b/catalog-ui/src/assets/styles/sprite-services-icons.less
diff --git a/catalog-ui/app/styles/sprite.html b/catalog-ui/src/assets/styles/sprite.html
index 875c26fe2a..875c26fe2a 100644
--- a/catalog-ui/app/styles/sprite.html
+++ b/catalog-ui/src/assets/styles/sprite.html
diff --git a/catalog-ui/app/styles/sprite.less b/catalog-ui/src/assets/styles/sprite.less
index b7c0146059..e9eed6e0c6 100644
--- a/catalog-ui/app/styles/sprite.less
+++ b/catalog-ui/src/assets/styles/sprite.less
@@ -29,7 +29,7 @@
.plus-icon { background-position: -50px -231px; width: 12px; height: 12px;}
.plus-icon-hover { background-position: -100px -231px; width: 12px; height: 12px;}
-.delete-icon { background-position: -650px -231px; width: 11px; height: 13px;}
+.delete-icon { background-position: -675px -231px; width: 11px; height: 13px;}
.delete-icon-hover { background-position: -702px -231px; width: 11px; height: 13px;}
.arrow-up { background-position: -350px -236px; width: 12px; height: 7px;}
@@ -155,9 +155,9 @@
.download-btn.disable { background-position: -530px -539px; width: 24px; height: 24px;}
.expand-collapse-plus-icon { background-position: -334px -888px; width: 14px; height: 14px;}
-.expand-collapse-plus-icon.hover { background-position: -422px -888px; width: 14px; height: 14px;}
+.expand-collapse-plus-icon:hover { background-position: -422px -888px; width: 14px; height: 14px;}
.expand-collapse-minus-icon { background-position: -378px -888px; width: 14px; height: 14px;}
-.expand-collapse-minus-icon.hover { background-position: -466px -888px; width: 14px; height: 14px;}
+.expand-collapse-minus-icon:hover { background-position: -466px -888px; width: 14px; height: 14px;}
//tabs
@@ -210,3 +210,42 @@
.expand-all:hover { background-position: -500px -449px; width: 20px; height: 22px;}
.collapse-all { background-position: -465px -420px; width: 20px; height: 22px;}
.collapse-all:hover { background-position: -465px -449px; width: 20px; height: 22px;}
+
+.delete-param:hover{ background-position: -702px -231px; width: 12px; height: 13px;}
+.delete-param{ background-position: -675px -231px; width: 12px; height: 13px;}
+.revert-param:hover{ background-position: -700px -48px; width: 12px; height: 11px;}
+.revert-param{ background-position: -676px -48px; width: 12px; height: 11px;}
+.show-desc:hover{ background-position: -635px -75px; width: 13px; height: 14px;}
+.show-desc{ background-position: -599px -75px; width: 13px; height: 14px;}
+.expand-list{background-position: -812px -66px; width: 21px; height: 21px;}
+.expand-list:hover{background-position: -812px -96px; width: 21px; height: 21px;}
+.expand-list.open{background-position: -853px -66px; width: 21px; height: 21px;}
+.expand-list.open:hover{background-position: -853px -96px; width: 21px; height: 21px;}
+//.search-icon{ background-position: -50px -279px; width: 14px; height: 14px;}
+.search-icon:hover,.search-icon.selected{ background-position: -894px -101px; width: 14px; height: 14px;}
+.search-icon{ background-position: -894px -71px; width: 14px; height: 14px;}
+.asc{background-position: -924px -71px; width: 8px; height: 12px;}
+.desc{background-position: -924px -101px; width: 8px; height: 12px;}
+.add-item-icon {background-position: -50px -960px; width: 19px; height: 19px;}
+.add-item-icon:hover {background-position: -100px -960px; width: 19px; height: 19px;}
+.delete-item-icon { background-position: -140px -1119px; width: 11px; height: 15px; }
+.filter-icon {background-position: -48px -1040px; width: 19px; height: 20px;}
+/*
+.sprite-new.expand-asset-icon { background-position: -740px -590px; width: 40px; height: 40px; }
+.sprite-new.view-info-icon { background-position: -739px -621px; width: 40px; height: 40px; }
+.sprite-new.cp-icon { background-position: -741px -652px; width: 40px; height: 40px; }
+.sprite-new.vl-icon { background-position: -740px -682px; width: 40px; height:40px; }
+.sprite-new.trash-icon { background-position: -740px -712px; width: 40px; height: 40px; }
+
+.sprite-new.expand-asset-icon:hover { background-position: -780px -590px; }
+.sprite-new.view-info-icon:hover { background-position: -779px -621px; }
+.sprite-new.cp-icon:hover { background-position: -781px -652px; }
+.sprite-new.vl-icon:hover { background-position: -780px -682px; }
+.sprite-new.trash-icon:hover { background-position: -780px -712px; }
+
+.sprite-new.expand-asset-icon:active, .sprite-new.expand-asset-icon.disabled-icon { background-position: -820px -590px;}
+.sprite-new.view-info-icon:active, .sprite-new.view-info-icon.disabled-icon { background-position: -819px -621px; }
+.sprite-new.cp-icon:active, .sprite-new.cp-icon.disabled-icon { background-position: -821px -652px; }
+.sprite-new.vl-icon:active, .sprite-new.vl-icon.disabled-icon { background-position: -820px -682px; }
+.sprite-new.trash-icon:active, .sprite-new.trash-icon.disabled-icon { background-position: -820px -712px; }
+*/
diff --git a/catalog-ui/app/styles/table-flex.less b/catalog-ui/src/assets/styles/table-flex.less
index 3ac014cc1b..3ac014cc1b 100644
--- a/catalog-ui/app/styles/table-flex.less
+++ b/catalog-ui/src/assets/styles/table-flex.less
diff --git a/catalog-ui/app/styles/tlv-buttons.less b/catalog-ui/src/assets/styles/tlv-buttons.less
index 0e42a92231..0e42a92231 100644
--- a/catalog-ui/app/styles/tlv-buttons.less
+++ b/catalog-ui/src/assets/styles/tlv-buttons.less
diff --git a/catalog-ui/app/styles/tlv-checkbox.less b/catalog-ui/src/assets/styles/tlv-checkbox.less
index 9dd5873545..9dd5873545 100644
--- a/catalog-ui/app/styles/tlv-checkbox.less
+++ b/catalog-ui/src/assets/styles/tlv-checkbox.less
diff --git a/catalog-ui/app/styles/tlv-loader.less b/catalog-ui/src/assets/styles/tlv-loader.less
index efe39916e2..efe39916e2 100644
--- a/catalog-ui/app/styles/tlv-loader.less
+++ b/catalog-ui/src/assets/styles/tlv-loader.less
diff --git a/catalog-ui/app/styles/tlv-sprite.less b/catalog-ui/src/assets/styles/tlv-sprite.less
index 472e2fb313..472e2fb313 100644
--- a/catalog-ui/app/styles/tlv-sprite.less
+++ b/catalog-ui/src/assets/styles/tlv-sprite.less
diff --git a/catalog-ui/app/styles/tooltips.less b/catalog-ui/src/assets/styles/tooltips.less
index f4c618e2dc..4528aea5d2 100644
--- a/catalog-ui/app/styles/tooltips.less
+++ b/catalog-ui/src/assets/styles/tooltips.less
@@ -27,20 +27,51 @@ div.tooltips {
}
// ---------------------------------------------------------------------------------------------------
-// Qtip
+// Tooltip
// ---------------------------------------------------------------------------------------------------
+.w-sdc-canvas-tooltip{
+
+ position: absolute;
+ z-index: 100;
+
+ .w-sdc-custom-tooltip {
+ .c_1;
+ position:relative;
+ color: white;
+ padding:10px;
+ height: 25px;
+ min-width: 100px;
+ background-color: rgba(80, 99, 113, 0.9);
+ border-radius: 2px;
+ line-height: 2px;
+ text-align: center;
+
+ .w-sdc-tooltip-arrow {
+ position: absolute;
+ bottom:25px;
+ right:20px;
+ width:0;height:0;
+ border-left: 5px solid transparent;
+ border-right: 5px solid transparent;
+ border-bottom: 5px solid rgba(80, 99, 113, 0.9);
+ border-top: transparent;
+ border-width:7px;
+ border-style:solid;
+ }
+
+ }
+}
+
.qtip-custom {
-moz-border-radius: 2px;
-webkit-border-radius: 2px;
border-radius: 2px;
- background-color: rgb(80,99,113);
- border-color:rgb(80,99,113);
- color:white;
- font-size:14px;
-
+ background-color: rgb(80, 99, 113);
+ border-color:rgb(80, 99, 113);
+ color: white;
+ font-size:13px;
}
-
.tooltip-custom {
background-color: rgba(80, 99, 113, 0.9);
z-index: 1100;
@@ -106,5 +137,18 @@ div.tooltips {
border-width: 0 6px 6px !important;
border-bottom-color: rgba(80, 99, 113, 0.9) !important;
}
+ /* &.right {
+ white-space: nowrap;
+ max-width: none;
+ .tooltip-arrow {
+ border-right-color: rgba(80, 99, 113, 0.9);
+ }
+ }
+ &.left {
+ white-space:nowrap;
+ max-width:none;
+ .tooltip-arrow {
+ border-left-color: rgba(80, 99, 113, 0.9);
+ }
+ }*/
}
-
diff --git a/catalog-ui/app/styles/variables-old.less b/catalog-ui/src/assets/styles/variables-old.less
index 29eb61de7c..a4e707a076 100644
--- a/catalog-ui/app/styles/variables-old.less
+++ b/catalog-ui/src/assets/styles/variables-old.less
@@ -1,7 +1,7 @@
/*---------------------------------------------- General ----------------------------------------------*/
@images: "images";
-// Colors
+/* Colors */
@color_a: #3b7b9b; // product category
@color_b: #666666;
@color_c: #ffffff;
@@ -31,7 +31,7 @@
@color_zz: #93deb6;
-// Color hover
+/* Color hover */
@color_a_hover: darken(@color_a, 10.0%);
@color_b_hover: darken(@color_b, 10.0%);
@color_c_hover: darken(@color_c, 10.0%);
@@ -69,7 +69,7 @@
@border_color_g: @color_a;
@border_color_view-mode: #ededed;
-// Fonts
+/* Fonts */
@font-omnes-light: omnes-light, sans-serif;
@font-omnes-regular: omnes-regular, sans-serif;
@font-omnes-medium: omnes-medium, sans-serif;
diff --git a/catalog-ui/app/styles/variables.less b/catalog-ui/src/assets/styles/variables.less
index bf8854a5bb..dbed6baf3f 100644
--- a/catalog-ui/app/styles/variables.less
+++ b/catalog-ui/src/assets/styles/variables.less
@@ -1,4 +1,4 @@
-// Fonts
+/* Fonts */
@font-omnes-light: omnes-light, sans-serif;
@font-omnes-regular: omnes-regular, sans-serif;
@font-omnes-medium: omnes-medium, sans-serif;
@@ -8,7 +8,7 @@
/*---------------------------------------------- General ----------------------------------------------*/
@images: "images";
-// Main Colors
+/* Main Colors */
@main_color_a: #009fdb;
@main_color_b: #056bae;
@main_color_c: #71c5eb;
@@ -25,8 +25,9 @@
@main_color_n: #959595;
@main_color_o: #d2d2d2;
@main_color_p: #ffffff;
+@main_color_q: #999999;
-// Functional Colors
+/* Functional Colors */
@func_color_q: #cf2a2a;
@func_color_r: #f2f2f2;
@func_color_s: #191919;
@@ -34,15 +35,17 @@
@func_color_e: #007a3e;
@func_color_h: #ffb81c;
-// Tlv Colors
+/* Tlv Colors */
@tlv_color_t: #f8f8f8;
@tlv_color_u: #eaeaea;
@tlv_color_v: #e6f6fb;
+@tlv_color_w: #c6e6f2;
+@tlv_color_x: #067ab4;
/*---------------------------------------------- Parameters ----------------------------------------------*/
@header_height: 0px;
@top_nav_height: 50px;
@top_nav_admin_height: 44px;
@action_nav_height: 53px;
-
-@border_color_view-mode: #ededed;
+@footer_height: 89px;
+@border_color_view-mode: #ededed; \ No newline at end of file
diff --git a/catalog-ui/app/styles/welcome-sprite.less b/catalog-ui/src/assets/styles/welcome-sprite.less
index 010d30c9ef..010d30c9ef 100644
--- a/catalog-ui/app/styles/welcome-sprite.less
+++ b/catalog-ui/src/assets/styles/welcome-sprite.less
diff --git a/catalog-ui/src/assets/styles/welcome-style.less b/catalog-ui/src/assets/styles/welcome-style.less
new file mode 100644
index 0000000000..d9cf16a72f
--- /dev/null
+++ b/catalog-ui/src/assets/styles/welcome-style.less
@@ -0,0 +1,63 @@
+
+html,
+body {
+ height: 100%;
+}
+
+* {
+ box-sizing: border-box;
+}
+
+.sdc-welcome-new-page {
+
+ opacity: 0;
+ height: 100%;
+ background-color: @main_color_p;
+
+ .sdc-welcome-close {
+ position: absolute;
+ right: 38px;
+ top: 30px;
+ z-index: 101;
+ cursor: pointer;
+
+ .sprite-welcome;
+ .sprite-welcome.close;
+
+ &:hover {
+ .sprite-welcome.close_white;
+ }
+ }
+
+ .sdc-welcome-wrapper {
+ height: 100vh;
+ width: 100%;
+ background-size: cover;
+ position: relative;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ background-image: url(images/welcome/002.png);
+ }
+
+ .sdc-welcome-main {
+ text-align: center;
+ position: absolute;
+ bottom: 40%;
+ z-index: 1;
+ color: #fff;
+ left: 0;
+ width: 100%;
+ }
+
+ .sdc-welcome-cover {
+ position: absolute;
+ top: 0px;
+ right: 0;
+ left: 0;
+ bottom: 0;
+ background-color: rgba(14, 13, 12, 0.8);
+ z-index: 0;
+ }
+
+}
diff --git a/catalog-ui/src/index.html b/catalog-ui/src/index.html
new file mode 100644
index 0000000000..c41532e01c
--- /dev/null
+++ b/catalog-ui/src/index.html
@@ -0,0 +1,26 @@
+<!doctype html>
+<html>
+<head>
+ <meta charset="utf-8">
+ <title>SDC</title>
+ <base href="/">
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+
+ <link rel="icon" type="image/x-icon" href="favicon.ico">
+</head>
+<body data-ng-class="bodyClass">
+
+ <!--<h1>Index.html</h1>-->
+ <app-root>Loading...</app-root>
+ <!--<h2>Before ui-view</h2>-->
+ <div ui-view style="height:100%"></div>
+ <!--<h2>After ui-view</h2>-->
+ <script type="text/javascript" src="/sdc1/scripts/inline.bundle.js"></script>
+ <script type="text/javascript" src="/sdc1/scripts/polyfills.bundle.js"></script>
+ <script type="text/javascript" src="/sdc1/scripts/vendor.bundle.js"></script>
+ <script type="text/javascript" src="/dcae/dcae-bundle.js"></script>
+ <script type="text/javascript" src="/sdc1/scripts/main.bundle.js"></script>
+ <script type="text/javascript" src="/sdc1/scripts/styles.bundle.js"></script></body>
+ <script type="text/javascript" src="/onboarding/punch-outs_en.js" async></script>
+
+</html>
diff --git a/catalog-ui/src/main.ts b/catalog-ui/src/main.ts
new file mode 100644
index 0000000000..7a321f7367
--- /dev/null
+++ b/catalog-ui/src/main.ts
@@ -0,0 +1,30 @@
+//import './app/app.ts';
+import {ng1appModule} from './app/app';
+import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
+import {enableProdMode} from '@angular/core';
+import {AppModule} from './app/ng2/app.module';
+import {UpgradeModule} from '@angular/upgrade/static';
+import {IAppConfigurtaion} from "./app/models/app-config";
+
+declare var __ENV__: string;
+export declare var sdc2Config: IAppConfigurtaion;
+
+if (__ENV__==='prod') {
+ sdc2Config = require('./../configurations/prod.js');
+ enableProdMode();
+} else {
+ sdc2Config = require('./../configurations/dev.js');
+}
+
+// Ugliy fix because the cookie recieved from webseal change his value after some seconds.
+declare var __ENV__: string;
+let timeout:number = 5000;
+if (__ENV__==='dev'){
+ timeout=0;
+}
+window.setTimeout(()=>{
+ platformBrowserDynamic().bootstrapModule(AppModule).then(platformRef => {
+ const upgrade = platformRef.injector.get(UpgradeModule) as UpgradeModule;
+ upgrade.bootstrap(document.body, [ng1appModule.name], {strictDi: true});
+ });
+},timeout);
diff --git a/catalog-ui/src/polyfills.ts b/catalog-ui/src/polyfills.ts
new file mode 100644
index 0000000000..3a5bfc592a
--- /dev/null
+++ b/catalog-ui/src/polyfills.ts
@@ -0,0 +1,39 @@
+// This file includes polyfills needed by Angular and is loaded before the app.
+// You can add your own extra polyfills to this file.
+import 'core-js/es6/symbol';
+import 'core-js/es6/object';
+import 'core-js/es6/function';
+import 'core-js/es6/parse-int';
+import 'core-js/es6/parse-float';
+import 'core-js/es6/number';
+import 'core-js/es6/math';
+import 'core-js/es6/string';
+import 'core-js/es6/date';
+import 'core-js/es6/array';
+import 'core-js/es6/regexp';
+import 'core-js/es6/map';
+import 'core-js/es6/set';
+import 'core-js/es6/reflect';
+
+import 'core-js/es7/reflect';
+import 'zone.js/dist/zone';
+
+
+// If you need to support the browsers/features below, uncomment the import
+// and run `npm install import-name-here';
+// Learn more in https://angular.io/docs/ts/latest/guide/browser-support.html
+
+// Needed for: IE9
+// import 'classlist.js';
+
+// Animations
+// Needed for: All but Chrome and Firefox, Not supported in IE9
+// import 'web-animations-js';
+
+// Date, currency, decimal and percent pipes
+// Needed for: All but Chrome, Firefox, Edge, IE11 and Safari 10
+// import 'intl';
+
+// NgClass on SVG elements
+// Needed for: IE10, IE11
+// import 'classlist.js';
diff --git a/catalog-ui/src/styles.less b/catalog-ui/src/styles.less
new file mode 100644
index 0000000000..795845e5fa
--- /dev/null
+++ b/catalog-ui/src/styles.less
@@ -0,0 +1,11 @@
+/* You can add global styles to this file, and also import other style files */
+@import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
+@import '../node_modules/angular-ui-bootstrap/dist/ui-bootstrap-csp.css';
+@import '../node_modules/angular-ui-notification/dist/angular-ui-notification.min.css';
+@import '../node_modules/perfect-scrollbar/dist/css/perfect-scrollbar.min.css';
+@import "../node_modules/qtip2/dist/jquery.qtip.min.css";
+@import '../node_modules/angular-resizable/angular-resizable.min.css';
+@import '../node_modules/angular-tooltips/dist/angular-tooltips.min.css';
+@import '../node_modules/animate.css/animate.min.css';
+@import './assets/styles/app.less';
+
diff --git a/catalog-ui/app/third-party/PunchOutRegistry.js b/catalog-ui/src/third-party/PunchOutRegistry.js
index bc93453dc1..db8e6875d6 100644
--- a/catalog-ui/app/third-party/PunchOutRegistry.js
+++ b/catalog-ui/src/third-party/PunchOutRegistry.js
@@ -95,4 +95,4 @@
window.PunchOutRegistry = PunchOutRegistry;
-})(this);
+})(window);
diff --git a/catalog-ui/non_bower_components/cytoscape.js-edge-editation/CytoscapeEdgeEditation.js b/catalog-ui/src/third-party/cytoscape.js-edge-editation/CytoscapeEdgeEditation.js
index 147f19ce54..2da6f786ea 100644
--- a/catalog-ui/non_bower_components/cytoscape.js-edge-editation/CytoscapeEdgeEditation.js
+++ b/catalog-ui/src/third-party/cytoscape.js-edge-editation/CytoscapeEdgeEditation.js
@@ -121,7 +121,7 @@
}
});
- scope.CytoscapeEdgeEditation = Class({
+ exports.CytoscapeEdgeEditation = Class({
init: function (cy, handleSize) {
this.DOUBLE_CLICK_INTERVAL = 300;
@@ -551,4 +551,5 @@
}
});
-})(this); \ No newline at end of file
+})(this);
+
diff --git a/catalog-ui/src/tsconfig.json b/catalog-ui/src/tsconfig.json
new file mode 100644
index 0000000000..2890b9b73c
--- /dev/null
+++ b/catalog-ui/src/tsconfig.json
@@ -0,0 +1,32 @@
+{
+ "compilerOptions": {
+ "baseUrl": ".",
+ "declaration": false,
+ "emitDecoratorMetadata": true,
+ "experimentalDecorators": true,
+ "allowJs": true,
+ "mapRoot": "./",
+ "module": "commonjs",
+ "moduleResolution": "node",
+ "outDir": "../dist/out-tsc",
+ "lib": [
+ "es6",
+ "dom"
+ ],
+ "sourceMap": true,
+ "target": "es5",
+ "typeRoots": [
+ "../node_modules/@types",
+ "./typings"
+ ],
+ "types": [
+ "jquery",
+ "core-js",
+ "node"
+ ]
+ },
+ "exclude": [
+ "test.ts",
+ "**/*.spec.ts"
+ ]
+} \ No newline at end of file
diff --git a/catalog-ui/typings/angular-ui-bootstrap/angular-ui-bootstrap.d.ts b/catalog-ui/src/typings/angular-ui-bootstrap/angular-ui-bootstrap.d.ts
index 4062f141f1..61bccd0425 100644
--- a/catalog-ui/typings/angular-ui-bootstrap/angular-ui-bootstrap.d.ts
+++ b/catalog-ui/src/typings/angular-ui-bootstrap/angular-ui-bootstrap.d.ts
@@ -252,7 +252,7 @@ declare module angular.ui.bootstrap {
/**
* a controller for a modal instance - it can initialize scope used by modal.
- * A controller can be injected with `$modalInstance`
+ * A controller can be injected with `$uibModalInstance`
*/
controller?: any;
diff --git a/catalog-ui/typings/angular-ui-router/angular-ui-router.d.ts b/catalog-ui/src/typings/angular-ui-router/angular-ui-router.d.ts
index c27425e39c..c27425e39c 100644
--- a/catalog-ui/typings/angular-ui-router/angular-ui-router.d.ts
+++ b/catalog-ui/src/typings/angular-ui-router/angular-ui-router.d.ts
diff --git a/catalog-ui/typings/angularjs/angular-mocks.d.ts b/catalog-ui/src/typings/angularjs/angular-mocks.d.ts
index 65b0ac1a09..597c596024 100644
--- a/catalog-ui/typings/angularjs/angular-mocks.d.ts
+++ b/catalog-ui/src/typings/angularjs/angular-mocks.d.ts
@@ -51,7 +51,7 @@ declare module angular {
interface IAngularStatic {
mock: IMockStatic;
}
-
+
// see https://docs.angularjs.org/api/ngMock/function/angular.mock.inject
interface IInjectStatic {
(...fns: Function[]): any;
@@ -123,27 +123,27 @@ declare module angular {
interface IHttpBackendService {
/**
* Flushes all pending requests using the trained responses.
- * @param count Number of responses to flush (in the order they arrived). If undefined, all pending requests will be flushed.
+ * @param count Number of responses to flush (in the order they arrived). If undefined, all pending requests will be flushed.
*/
flush(count?: number): void;
-
+
/**
* Resets all request expectations, but preserves all backend definitions.
*/
resetExpectations(): void;
-
+
/**
* Verifies that all of the requests defined via the expect api were made. If any of the requests were not made, verifyNoOutstandingExpectation throws an exception.
*/
verifyNoOutstandingExpectation(): void;
-
+
/**
* Verifies that there are no outstanding requests that need to be flushed.
*/
verifyNoOutstandingRequest(): void;
/**
- * Creates a new request expectation.
+ * Creates a new request expectation.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param method HTTP method.
@@ -179,17 +179,17 @@ declare module angular {
* @param headers HTTP headers object to be compared with the HTTP headers in the request.
*/
expectHEAD(url: string | RegExp | ((url: string) => boolean), headers?: Object): mock.IRequestHandler;
-
+
/**
* Creates a new request expectation for JSONP requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
- */
+ */
expectJSONP(url: string | RegExp | ((url: string) => boolean)): mock.IRequestHandler;
/**
- * Creates a new request expectation for PATCH requests.
+ * Creates a new request expectation for PATCH requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
@@ -199,7 +199,7 @@ declare module angular {
expectPATCH(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object): mock.IRequestHandler;
/**
- * Creates a new request expectation for POST requests.
+ * Creates a new request expectation for POST requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
@@ -209,7 +209,7 @@ declare module angular {
expectPOST(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object): mock.IRequestHandler;
/**
- * Creates a new request expectation for PUT requests.
+ * Creates a new request expectation for PUT requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
@@ -219,7 +219,7 @@ declare module angular {
expectPUT(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object): mock.IRequestHandler;
/**
- * Creates a new backend definition.
+ * Creates a new backend definition.
* Returns an object with respond method that controls how a matched request is handled.
* @param method HTTP method.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
@@ -229,7 +229,7 @@ declare module angular {
when(method: string, url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler;
/**
- * Creates a new backend definition for DELETE requests.
+ * Creates a new backend definition for DELETE requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
@@ -237,7 +237,7 @@ declare module angular {
whenDELETE(url: string | RegExp | ((url: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler;
/**
- * Creates a new backend definition for GET requests.
+ * Creates a new backend definition for GET requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
@@ -245,7 +245,7 @@ declare module angular {
whenGET(url: string | RegExp | ((url: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler;
/**
- * Creates a new backend definition for HEAD requests.
+ * Creates a new backend definition for HEAD requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
@@ -253,7 +253,7 @@ declare module angular {
whenHEAD(url: string | RegExp | ((url: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler;
/**
- * Creates a new backend definition for JSONP requests.
+ * Creates a new backend definition for JSONP requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
@@ -261,7 +261,7 @@ declare module angular {
whenJSONP(url: string | RegExp | ((url: string) => boolean)): mock.IRequestHandler;
/**
- * Creates a new backend definition for PATCH requests.
+ * Creates a new backend definition for PATCH requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
@@ -270,7 +270,7 @@ declare module angular {
whenPATCH(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler;
/**
- * Creates a new backend definition for POST requests.
+ * Creates a new backend definition for POST requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
@@ -279,7 +279,7 @@ declare module angular {
whenPOST(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler;
/**
- * Creates a new backend definition for PUT requests.
+ * Creates a new backend definition for PUT requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
@@ -291,16 +291,16 @@ declare module angular {
export module mock {
// returned interface by the the mocked HttpBackendService expect/when methods
interface IRequestHandler {
-
+
/**
- * Controls the response for a matched request using a function to construct the response.
+ * Controls the response for a matched request using a function to construct the response.
* Returns the RequestHandler object for possible overrides.
* @param func Function that receives the request HTTP method, url, data, and headers and returns an array containing response status (number), data, headers, and status text.
*/
respond(func: ((method: string, url: string, data: string | Object, headers: Object) => [number, string | Object, Object, string])): IRequestHandler;
/**
- * Controls the response for a matched request using supplied static data to construct the response.
+ * Controls the response for a matched request using supplied static data to construct the response.
* Returns the RequestHandler object for possible overrides.
* @param status HTTP status code to add to the response.
* @param data Data to add to the response.
@@ -310,7 +310,7 @@ declare module angular {
respond(status: number, data: string | Object, headers?: Object, responseText?: string): IRequestHandler;
/**
- * Controls the response for a matched request using the HTTP status code 200 and supplied static data to construct the response.
+ * Controls the response for a matched request using the HTTP status code 200 and supplied static data to construct the response.
* Returns the RequestHandler object for possible overrides.
* @param data Data to add to the response.
* @param headers Headers object to add to the response.
diff --git a/catalog-ui/typings/angularjs/angular-resource.d.ts b/catalog-ui/src/typings/angularjs/angular-resource.d.ts
index 969997b1bc..969997b1bc 100644
--- a/catalog-ui/typings/angularjs/angular-resource.d.ts
+++ b/catalog-ui/src/typings/angularjs/angular-resource.d.ts
diff --git a/catalog-ui/typings/angularjs/angular.d.ts b/catalog-ui/src/typings/angularjs/angular.d.ts
index a5f56c0ccd..a5f56c0ccd 100644
--- a/catalog-ui/typings/angularjs/angular.d.ts
+++ b/catalog-ui/src/typings/angularjs/angular.d.ts
diff --git a/catalog-ui/typings/angularjs/restangular.d.ts b/catalog-ui/src/typings/angularjs/restangular.d.ts
index 3428b0493f..3428b0493f 100644
--- a/catalog-ui/typings/angularjs/restangular.d.ts
+++ b/catalog-ui/src/typings/angularjs/restangular.d.ts
diff --git a/catalog-ui/typings/cytoscape/cytoscape-extension.js b/catalog-ui/src/typings/cytoscape/cytoscape-extension.js
index dbf22c37b9..dbf22c37b9 100644
--- a/catalog-ui/typings/cytoscape/cytoscape-extension.js
+++ b/catalog-ui/src/typings/cytoscape/cytoscape-extension.js
diff --git a/catalog-ui/typings/cytoscape/cytoscape-extension.ts b/catalog-ui/src/typings/cytoscape/cytoscape-extension.ts
index 88843af088..88843af088 100644
--- a/catalog-ui/typings/cytoscape/cytoscape-extension.ts
+++ b/catalog-ui/src/typings/cytoscape/cytoscape-extension.ts
diff --git a/catalog-ui/typings/cytoscape/cytoscape.d.ts b/catalog-ui/src/typings/cytoscape/cytoscape.d.ts
index e10b6273ae..3527281e5e 100644
--- a/catalog-ui/typings/cytoscape/cytoscape.d.ts
+++ b/catalog-ui/src/typings/cytoscape/cytoscape.d.ts
@@ -41,6 +41,8 @@
// - Cy.CollectionNodes
// The output is a collection of node elements OR single node.
+// import {CommonLinkBase} from "../../app/models/graph/graph-links/common-base-link";
+// import {CommonNodeBase} from "../../app/models/graph/nodes/base-common-node";
declare module Cy {
/**
* See http://js.cytoscape.org/#selectors for details about writing selectors.
@@ -64,6 +66,7 @@ declare module Cy {
type PositionDimension = string;
/**
+ *
* Usually temp or nonserialisable data can be stored.
*/
type Scratchpad = any;
@@ -1885,15 +1888,15 @@ declare module Cy {
}
interface ElementsDefinition {
- nodes: Sdc.Models.Graph.CommonNodeBase[];
- edges: Sdc.Models.CommonLinkBase[];
+ nodes: any[];
+ edges: any[];
}
interface ElementDefinition {
group?: ElementGroup;
- data: Sdc.Models.Graph.CommonNodeBase| Sdc.Models.CommonLinkBase;
+ data: any;
/**
* Scratchpad data (usually temp or nonserialisable data)
*/
@@ -1932,7 +1935,7 @@ declare module Cy {
*/
css?: Css.ElementCss;
}
-
+
// interface ElementDataDefinition {
// /**
// * elided id => autogenerated id
@@ -1943,7 +1946,7 @@ declare module Cy {
// label?: string;
// }
interface EdgeDefinition extends ElementDefinition {
- data: Sdc.Models.CommonLinkBase;
+ data: any;
}
// interface EdgeDataDefinition extends ElementDataDefinition { /**
@@ -1958,7 +1961,7 @@ declare module Cy {
// }
interface NodeDefinition extends ElementDefinition {
- data: Sdc.Models.Graph.CommonNodeBase;
+ data: any;
}
// interface NodeDataDefinition extends ElementDataDefinition {
@@ -2161,6 +2164,9 @@ declare module Cy {
* A convenience function to explicitly destroy the instance.
*/
destroy(): void;
+
+ scratch(namespace?:string): any;
+ removeScratch(namespace:string):void;
}
interface EventObject {
@@ -3092,4 +3098,4 @@ declare module "cytoscape" {
export = cytoscape;
}
-declare var cytoscape: Cy.Static; \ No newline at end of file
+declare var cytoscape: Cy.Static;
diff --git a/catalog-ui/typings/cytoscape/edge-editation.d.ts b/catalog-ui/src/typings/cytoscape/edge-editation.d.ts
index e5ebd709b2..c4b5df0617 100644
--- a/catalog-ui/typings/cytoscape/edge-editation.d.ts
+++ b/catalog-ui/src/typings/cytoscape/edge-editation.d.ts
@@ -25,4 +25,3 @@ interface Handle {
declare var CytoscapeEdgeEditation: CytoscapeEdgeEditation;
-declare function require(name:string); \ No newline at end of file
diff --git a/catalog-ui/typings/d3/d3.d.ts b/catalog-ui/src/typings/d3/d3.d.ts
index ff4335106c..ff4335106c 100644
--- a/catalog-ui/typings/d3/d3.d.ts
+++ b/catalog-ui/src/typings/d3/d3.d.ts
diff --git a/catalog-ui/typings/jasmine/jasmine.d.ts b/catalog-ui/src/typings/jasmine/jasmine.d.ts
index 99ccb91fed..99ccb91fed 100644
--- a/catalog-ui/typings/jasmine/jasmine.d.ts
+++ b/catalog-ui/src/typings/jasmine/jasmine.d.ts
diff --git a/catalog-ui/typings/jquery/jquery.d.ts b/catalog-ui/src/typings/jquery/jquery.d.ts
index cc20de588b..cc20de588b 100644
--- a/catalog-ui/typings/jquery/jquery.d.ts
+++ b/catalog-ui/src/typings/jquery/jquery.d.ts
diff --git a/catalog-ui/typings/jsMd5/md5.d.ts b/catalog-ui/src/typings/jsMd5/md5.d.ts
index 3f06a6f509..3f06a6f509 100644
--- a/catalog-ui/typings/jsMd5/md5.d.ts
+++ b/catalog-ui/src/typings/jsMd5/md5.d.ts
diff --git a/catalog-ui/typings/lodash/lodash.d.ts b/catalog-ui/src/typings/lodash/lodash.d.ts
index 9d23982103..72d35febb1 100644
--- a/catalog-ui/typings/lodash/lodash.d.ts
+++ b/catalog-ui/src/typings/lodash/lodash.d.ts
@@ -22946,4 +22946,4 @@ declare module "lodash.first" {
interface Set<T> {}
interface Map<K, V> {}
interface WeakSet<T> {}
-interface WeakMap<K, V> {} \ No newline at end of file
+//interface WeakMap<K extends object, V> {}
diff --git a/catalog-ui/typings/notifyjs/notifyjs.d.ts b/catalog-ui/src/typings/notifyjs/notifyjs.d.ts
index f72828fc06..f72828fc06 100644
--- a/catalog-ui/typings/notifyjs/notifyjs.d.ts
+++ b/catalog-ui/src/typings/notifyjs/notifyjs.d.ts
diff --git a/catalog-ui/typings/tsd.d.ts b/catalog-ui/src/typings/tsd.d.ts
index 4fe638ef72..4fe638ef72 100644
--- a/catalog-ui/typings/tsd.d.ts
+++ b/catalog-ui/src/typings/tsd.d.ts
diff --git a/catalog-ui/tests/karma.unit.conf.js b/catalog-ui/tests/karma.unit.conf.js
deleted file mode 100644
index 1b8277faed..0000000000
--- a/catalog-ui/tests/karma.unit.conf.js
+++ /dev/null
@@ -1,149 +0,0 @@
-// Karma configuration
-
-module.exports = function (config) {
- config.set({
-
- // base path, that will be used to resolve files and exclude
- basePath: '../',
-
-
- // frameworks to use
- frameworks: ['jasmine'],
-
- // list of files / patterns to load in the browser
- files: [
- 'bower_components/jquery/dist/jquery.js',
- 'bower_components/angular/angular.js',
- 'bower_components/angular-base64/angular-base64.js',
- 'bower_components/angular-base64-upload/src/angular-base64-upload.js',
- 'bower_components/angular-bootstrap/ui-bootstrap-tpls.js',
- 'bower_components/jquery-ui/jquery-ui.js',
- 'bower_components/angular-dragdrop/src/angular-dragdrop.js',
- 'bower_components/angular-filter/dist/angular-filter.min.js',
- 'bower_components/angular-md5/angular-md5.js',
- 'bower_components/perfect-scrollbar/src/perfect-scrollbar.js',
- 'bower_components/angular-perfect-scrollbar/src/angular-perfect-scrollbar.js',
- 'bower_components/angular-mocks/angular-mocks.js',
- 'bower_components/angular-resource/angular-resource.js',
- 'bower_components/angular-sanitize/angular-sanitize.js',
- 'bower_components/angular-tooltips/dist/angular-tooltips.min.js',
- 'bower_components/angular-translate/angular-translate.js',
- 'bower_components/angular-translate-loader-static-files/angular-translate-loader-static-files.js',
- 'bower_components/angular-ui-router/release/angular-ui-router.js',
- 'bower_components/angular-uuid4/angular-uuid4.js',
- 'bower_components/bootstrap/dist/js/bootstrap.js',
- 'bower_components/checklist-model/checklist-model.js',
- 'bower_components/angular-clipboard/angular-clipboard.js',
- 'bower_components/angular-resizable/src/angular-resizable.js',
- 'bower_components/angular-ui-notification/src/angular-ui-notification.js',
- 'bower_components/lodash/lodash.js',
- 'bower_components/restangular/dist/restangular.js',
- 'bower_components/jspdf/dist/jspdf.min.js',
- 'app/scripts/utils/**/*.js',
- 'app/scripts/services/**/*.js',
- 'app/scripts/models/**/*.js',
- 'app/scripts/view-models/**/*.js',
- 'app/scripts/filters/**/*.js',
- 'app/scripts/directives/**/*.js',
- 'app/scripts/modules/**/*.js',
-
- 'app/scripts/app.js',
- 'app/languages/**/*.js',
-
- 'app/scripts/templates.js',
-
-
-
-
-
- //'app/scripts/view-models/dashboard/dashboard-view-model-tests.js',
-
-
- 'app/scripts/**/*-tests.js',
- //'app/scripts/app.js',
-
-
- //definition to allow to debug TS tests file in browser
- {pattern: 'app/scripts/**/*-tests.ts', included: false},
- {pattern: 'app/scripts/**/*-tests.js.map', included: false},
-
-
- //definition to allow to debug TS sources files in browser
- {pattern: 'app/scripts/**/*.ts', included: false},
- {pattern: 'app/scripts/**/*.js.map', included: false}
-
- ],
-
- // list of files to exclude
- exclude: [
-
- ],
-
- junitReporter: {
- outputFile: 'tests/testOutput.xml',
- suite: ''
- },
-
- //NOTE: This is handled from gruntfile.js
- coverageReporter : {
- type : 'html',
- dir: 'tests/Coverage'
- },
- // test results reporter to use
- // possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
- reporters: [
- 'mocha',//uncomment this line if you need to debug your unit test and print out the 'describe' of the test
- 'junit',
- 'dots',
- 'progress',
- 'coverage'
- ],
-
- // web server port
- port: 9876,
-
-
- // enable / disable colors in the output (reporters and logs)
- colors: true,
-
-
- // level of logging
- // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
- // logLevel: config.LOG_INFO,
-
-
- // enable / disable watching file and executing tests whenever any file changes
- autoWatch: true,
-
- preprocessors: {
- '**/*.html': 'html2js',
- 'app/scripts/**/!(*-tests|*Tests|*Test).js': 'coverage'
- },
-
- //ngHtml2JsPreprocessor: {
- // stripPrefix: 'client/'
- //},
-
- // Start these browsers, currently available:
- // - Chrome
- // - ChromeCanary
- // - Firefox
- // - Opera (has to be installed with `npm install karma-opera-launcher`)
- // - Safari (only Mac; has to be installed with `npm install karma-safari-launcher`)
- // - PhantomJS
- // - IE (only Windows; has to be installed with `npm install karma-ie-launcher`)
-
- //NOTE: This is handled from gruntfile.js
-
- browsers: ['Chrome'],
-
-
- // If browser does not capture in given timeout [ms], kill it
- captureTimeout: 60000,
-
-
- // Continuous Integration mode
- // if true, it capture browsers, run tests and exit
- singleRun: false
- });
-};
diff --git a/catalog-ui/tsd.json b/catalog-ui/tsd.json
deleted file mode 100644
index 1f8ffec3cb..0000000000
--- a/catalog-ui/tsd.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
- "version": "v4",
- "repo": "borisyankov/DefinitelyTyped",
- "ref": "master",
- "path": "typings",
- "bundle": "typings/tsd.d.ts",
- "installed": {
- "notifyjs/notifyjs.d.ts": {
- "commit": "581563c4684d405afec14260ba79a89a52666c09"
- },
- "jasmine/jasmine.d.ts": {
- "commit": "14ab703f435375194360cdba3abab61afc879c18"
- }
- }
-}
diff --git a/catalog-ui/tslint.json b/catalog-ui/tslint.json
index 2cd2dece6f..86bc1841f3 100644
--- a/catalog-ui/tslint.json
+++ b/catalog-ui/tslint.json
@@ -1,58 +1,116 @@
{
- "rules": {
- "class-name": true,
- "comment-format": [
- false,
- "check-space"
- ],
- "indent": [
- true,
- "spaces"
- ],
- "no-duplicate-variable": true,
- "no-eval": true,
- "no-internal-module": true,
- "no-trailing-whitespace": true,
- "no-unsafe-finally": true,
- "no-var-keyword": true,
- "one-line": [
- true,
- "check-open-brace",
- "check-whitespace"
- ],
- "quotemark": [
- false,
- "single"
- ],
- "semicolon": [
- true,
- "always"
- ],
- "triple-equals": [
- true,
- "allow-null-check"
- ],
- "typedef-whitespace": [
- true,
- {
- "call-signature": "nospace",
- "index-signature": "nospace",
- "parameter": "nospace",
- "property-declaration": "nospace",
- "variable-declaration": "nospace"
- }
- ],
- "variable-name": [
- true,
- "ban-keywords"
- ],
- "whitespace": [
- false,
- "check-branch",
- "check-decl",
- "check-operator",
- "check-separator",
- "check-type"
- ]
- }
-} \ No newline at end of file
+ "rulesDirectory": [
+ "node_modules/codelyzer"
+ ],
+ "rules": {
+ "callable-types": true,
+ "class-name": true,
+ "comment-format": [
+ true,
+ "check-space"
+ ],
+ "curly": true,
+ "eofline": true,
+ "forin": true,
+ "import-blacklist": [true, "rxjs"],
+ "import-spacing": true,
+ "indent": [
+ true,
+ "spaces"
+ ],
+ "interface-over-type-literal": true,
+ "label-position": true,
+ "max-line-length": [
+ true,
+ 140
+ ],
+ "member-access": false,
+ "member-ordering": [
+ true,
+ "static-before-instance",
+ "variables-before-functions"
+ ],
+ "no-arg": true,
+ "no-bitwise": true,
+ "no-console": [
+ true,
+ "debug",
+ "info",
+ "time",
+ "timeEnd",
+ "trace"
+ ],
+ "no-construct": true,
+ "no-debugger": true,
+ "no-duplicate-variable": true,
+ "no-empty": false,
+ "no-empty-interface": true,
+ "no-eval": true,
+ "no-inferrable-types": true,
+ "no-shadowed-variable": true,
+ "no-string-literal": false,
+ "no-string-throw": true,
+ "no-switch-case-fall-through": true,
+ "no-trailing-whitespace": true,
+ "no-unused-expression": true,
+ "no-use-before-declare": true,
+ "no-var-keyword": true,
+ "object-literal-sort-keys": false,
+ "one-line": [
+ true,
+ "check-open-brace",
+ "check-catch",
+ "check-else",
+ "check-whitespace"
+ ],
+ "prefer-const": true,
+ "quotemark": [
+ true,
+ "single"
+ ],
+ "radix": true,
+ "semicolon": [
+ "always"
+ ],
+ "triple-equals": [
+ true,
+ "allow-null-check"
+ ],
+ "typedef-whitespace": [
+ true,
+ {
+ "call-signature": "nospace",
+ "index-signature": "nospace",
+ "parameter": "nospace",
+ "property-declaration": "nospace",
+ "variable-declaration": "nospace"
+ }
+ ],
+ "typeof-compare": true,
+ "unified-signatures": true,
+ "variable-name": false,
+ "whitespace": [
+ true,
+ "check-branch",
+ "check-decl",
+ "check-operator",
+ "check-separator",
+ "check-type"
+ ],
+
+ "directive-selector": [true, "attribute", "app", "camelCase"],
+ "component-selector": [true, "element", "app", "kebab-case"],
+ "use-input-property-decorator": true,
+ "use-output-property-decorator": true,
+ "use-host-property-decorator": true,
+ "no-input-rename": true,
+ "no-output-rename": true,
+ "use-life-cycle-interface": true,
+ "use-pipe-transform-interface": true,
+ "component-class-suffix": true,
+ "directive-class-suffix": true,
+ "no-access-missing-member": true,
+ "templates-use-public": true,
+ "invoke-injectable": true
+ }
+}
diff --git a/catalog-ui/typings/cytoscape/cytoscape-extension.js.map b/catalog-ui/typings/cytoscape/cytoscape-extension.js.map
deleted file mode 100644
index 5eeda401dc..0000000000
--- a/catalog-ui/typings/cytoscape/cytoscape-extension.js.map
+++ /dev/null
@@ -1 +0,0 @@
-{"version":3,"file":"cytoscape-extension.js","sourceRoot":"","sources":["cytoscape-extension.ts"],"names":[],"mappings":""} \ No newline at end of file
diff --git a/catalog-ui/webpack.common.js b/catalog-ui/webpack.common.js
new file mode 100644
index 0000000000..818d031776
--- /dev/null
+++ b/catalog-ui/webpack.common.js
@@ -0,0 +1,313 @@
+const path = require('path');
+const webpack = require('webpack');
+const ProgressPlugin = require('webpack/lib/ProgressPlugin');
+const HtmlWebpackPlugin = require('html-webpack-plugin');
+const ExtractTextPlugin = require('extract-text-webpack-plugin');
+const CleanWebpackPlugin = require('clean-webpack-plugin');
+const autoprefixer = require('autoprefixer');
+const postcssUrl = require('postcss-url');
+const {GlobCopyWebpackPlugin, BaseHrefWebpackPlugin} = require('@angular/cli/plugins/webpack');
+const {CommonsChunkPlugin} = require('webpack').optimize;
+const {AotPlugin} = require('@ngtools/webpack');
+
+const nodeModules = path.join(process.cwd(), 'node_modules');
+
+const bundledScripts = [
+ "script-loader!./node_modules/jquery/dist/jquery.min.js",
+ "script-loader!./node_modules/lodash/lodash.min.js",
+ "script-loader!./node_modules/angular/angular.min.js",
+ "script-loader!./node_modules/restangular/dist/restangular.min.js",
+ "script-loader!./node_modules/jqueryui/jquery-ui.min.js",
+ "script-loader!./node_modules/angular-ui-router/release/angular-ui-router.min.js",
+ "script-loader!./node_modules/angular-filter/dist/angular-filter.min.js",
+ "script-loader!./node_modules/angular-ui-bootstrap/dist/ui-bootstrap.js",
+ "script-loader!./node_modules/angular-ui-bootstrap/dist/ui-bootstrap-tpls.js",
+ "script-loader!./node_modules/angular-resource/angular-resource.min.js",
+ "script-loader!./node_modules/angular-base64/angular-base64.min.js",
+ "script-loader!./node_modules/angular-uuid4/angular-uuid4.min.js",
+ "script-loader!./node_modules/angular-translate/dist/angular-translate.min.js",
+ "script-loader!./node_modules/angular-translate-loader-static-files/angular-translate-loader-static-files.min.js",
+ "script-loader!./node_modules/angular-base64-upload/dist/angular-base64-upload.min.js",
+ "script-loader!./node_modules/angular-ui-notification/dist/angular-ui-notification.min.js",
+ "script-loader!./node_modules/cytoscape/dist/cytoscape.min.js",
+ "script-loader!./node_modules/checklist-model/checklist-model.js",
+ "script-loader!./node_modules/perfect-scrollbar/dist/js/perfect-scrollbar.jquery.min.js",
+ "script-loader!./node_modules/qtip2/dist/jquery.qtip.min.js",
+ "script-loader!./node_modules/cytoscape-qtip/cytoscape-qtip.js",
+ "script-loader!./node_modules/js-md5/build/md5.min.js",
+ "script-loader!./node_modules/angular-clipboard/angular-clipboard.js",
+ "script-loader!./node_modules/angular-resizable/angular-resizable.min.js",
+ "script-loader!./node_modules/angular-dragdrop/src/angular-dragdrop.min.js",
+ "script-loader!./node_modules/angular-tooltips/dist/angular-tooltips.min.js",
+ "script-loader!./node_modules/angular-sanitize/angular-sanitize.min.js"
+];
+const baseHref = undefined;
+const deployUrl = undefined;
+
+// Arguments pass from webpack
+const prod = process.argv.indexOf('-p') !== -1;
+
+module.exports = function(params) {
+
+ const webpackCommonConfig = {
+ resolve: {
+ extensions: [
+ ".ts",
+ ".js",
+ ".less"
+ ],
+ modules: [
+ "./node_modules"
+ ],
+ alias: {
+ directives: path.join(__dirname, 'app/directives/'),
+ }
+ },
+ resolveLoader: {
+ modules: [
+ "./node_modules"
+ ]
+ },
+ entry: {
+ 'scripts/main': [ './src/main.ts' ],
+ 'scripts/polyfills': [ './src/polyfills.ts' ],
+ 'scripts/vendor': bundledScripts,
+ 'scripts/styles': [ "./src/styles.less" ]
+ },
+ module: {
+ rules: [
+ {
+ enforce: "pre",
+ test: /\.js$/,
+ loader: "source-map-loader",
+ exclude: [ /\/node_modules\// ]
+ },
+ { test: /\.json$/, loader: "json-loader" },
+ { test: /\.html$/, loader: "html-loader" },
+ {
+ exclude: [ path.join(process.cwd(), "src/styles.less") ],
+ test: /\.css$/,
+ loaders: [
+ "exports-loader?module.exports.toString()",
+ "css-loader?{\"sourceMap\":false,\"importLoaders\":1}",
+ "postcss-loader"
+ ]
+ },
+ {
+ exclude: [ path.join(process.cwd(), "src/styles.less") ],
+ test: /\.scss$|\.sass$/,
+ loaders: [
+ "exports-loader?module.exports.toString()",
+ "css-loader?{\"sourceMap\":false,\"importLoaders\":1}",
+ "postcss-loader",
+ "sass-loader"
+ ]
+ },
+ {
+ exclude: [ path.join(process.cwd(), "src/styles.less") ],
+ test: /\.less$/,
+ loaders: [
+ "exports-loader?module.exports.toString()",
+ "css-loader?{\"sourceMap\":false,\"importLoaders\":1}",
+ "postcss-loader",
+ "less-loader"
+ ]
+ },
+ {
+ exclude: [ path.join(process.cwd(), "src/styles.less") ],
+ test: /\.styl$/,
+ loaders: [
+ "exports-loader?module.exports.toString()",
+ "css-loader?{\"sourceMap\":false,\"importLoaders\":1}",
+ "postcss-loader",
+ "stylus-loader?{\"sourceMap\":false,\"paths\":[]}"
+ ]
+ },
+ {
+ include: [ path.join(process.cwd(), "src/styles.less") ],
+ test: /\.css$/,
+ loaders: ExtractTextPlugin.extract({
+ use: [
+ "css-loader?{\"sourceMap\":false,\"importLoaders\":1}",
+ "postcss-loader"
+ ],
+ fallback: "style-loader",
+ publicPath: ""
+ })
+ },
+ {
+ include: [ path.join(process.cwd(), "src/styles.less") ],
+ test: /\.scss$|\.sass$/,
+ loaders: ExtractTextPlugin.extract({
+ use: [
+ "css-loader?{\"sourceMap\":false,\"importLoaders\":1}",
+ "postcss-loader",
+ "sass-loader"
+ ],
+ fallback: "style-loader",
+ publicPath: ""
+ })
+ },
+ {
+ include: [ path.join(process.cwd(), "src/styles.less") ],
+ test: /\.less$/,
+ loaders: ExtractTextPlugin.extract({
+ use: [
+ "css-loader?{\"sourceMap\":false,\"importLoaders\":1}",
+ "postcss-loader",
+ "less-loader"
+ ],
+ fallback: "style-loader",
+ publicPath: ""
+ })
+ },
+ {
+ include: [ path.join(process.cwd(), "src/styles.less") ],
+ test: /\.styl$/,
+ loaders: ExtractTextPlugin.extract({
+ use: [
+ "css-loader?{\"sourceMap\":false,\"importLoaders\":1}",
+ "postcss-loader",
+ "stylus-loader?{\"sourceMap\":false,\"paths\":[]}"
+ ],
+ fallback: "style-loader",
+ publicPath: ""
+ })
+ },
+ { test: /\.ts$/, loader: "@ngtools/webpack" }
+ ]
+ },
+ plugins: [
+ new CleanWebpackPlugin(['dist', 'build'], {
+ root: path.join(__dirname, ''),
+ verbose: true,
+ dry: false,
+ exclude: ['shared.js']
+ }),
+ new webpack.LoaderOptionsPlugin({
+ debug: false
+ }),
+ new webpack.DefinePlugin({
+ process: {
+ env: {
+ sdcConfig: prod? '"production"': '"development"'
+ }
+ }
+ }),
+ new webpack.NoEmitOnErrorsPlugin(),
+ new ProgressPlugin(),
+ // new HtmlWebpackPlugin({
+ // template: "./src/index.html",
+ // filename: "./index.html",
+ // hash: false,
+ // inject: true,
+ // compile: true,
+ // favicon: false,
+ // minify: false,
+ // cache: true,
+ // showErrors: true,
+ // chunks: "all",
+ // excludeChunks: [],
+ // title: "Webpack App",
+ // xhtml: true,
+ // chunksSortMode: function sort(left, right) {
+ // let paramsString = params.entryPoints + '';
+ // let leftString = left.names[0].replace('scripts/','');
+ // let rightString = right.names[0].replace('scripts/','');
+ // let leftIndex = paramsString.indexOf(leftString);
+ // let rightindex = paramsString.indexOf(rightString);
+ // //console.log("left: " + leftString + " | leftIndex: " + leftIndex);
+ // //console.log("right: " + rightString + " | rightindex: " + rightindex);
+ // //console.log("result: " + leftIndex-rightindex);
+ // //console.log("----------------------------------------");
+ // return leftIndex-rightindex;
+ // }
+ // }),
+ new GlobCopyWebpackPlugin({
+ patterns: [
+ "assets/languages",
+ "assets/styles/fonts",
+ "assets/styles/images",
+ "assets/styles/app.css"
+ ],
+ globOptions: {
+ cwd: path.join(process.cwd(), "src"),
+ dot: true,
+ ignore: "**/.gitkeep"
+ }
+ }),
+ new GlobCopyWebpackPlugin({
+ patterns: [
+ "configurations"
+ ],
+ globOptions: {
+ cwd: path.join(process.cwd(), ""),
+ dot: true,
+ ignore: "**/.gitkeep"
+ }
+ }),
+ new BaseHrefWebpackPlugin({}),
+ new CommonsChunkPlugin({
+ name: "scripts/inline",
+ minChunks: null
+ }),
+ new CommonsChunkPlugin({
+ name: "scripts/vendor",
+ minChunks: (module) => module.resource && module.resource.startsWith(nodeModules),
+ chunks: [
+ "main"
+ ]
+ }),
+ new ExtractTextPlugin({
+ filename: "[name].bundle.css",
+ disable: true
+ }),
+ new webpack.LoaderOptionsPlugin({
+ sourceMap: false,
+ options: {
+ postcss: [
+ autoprefixer(),
+ postcssUrl({
+ url: (URL) => {
+ // Only convert absolute URLs, which CSS-Loader won't process into require().
+ if (!URL.startsWith('/')) {
+ return URL;
+ }
+ // Join together base-href, deploy-url and the original URL.
+ // Also dedupe multiple slashes into single ones.
+ return `/${baseHref || ''}/${deployUrl || ''}/${URL}`.replace(/\/\/+/g, '/');
+ }
+ })
+ ],
+ sassLoader: {
+ sourceMap: false,
+ includePaths: []
+ },
+ lessLoader: {
+ sourceMap: false
+ },
+ context: ""
+ }
+ }),
+ new AotPlugin({
+ mainPath: "main.ts",
+ exclude: [],
+ tsConfigPath: "src/tsconfig.json",
+ skipCodeGeneration: true
+ })
+ ],
+ node: {
+ fs: "empty",
+ global: true,
+ crypto: "empty",
+ tls: "empty",
+ net: "empty",
+ process: true,
+ module: false,
+ clearImmediate: false,
+ setImmediate: false
+ }
+ }
+
+ return webpackCommonConfig;
+}
diff --git a/catalog-ui/webpack.config.js b/catalog-ui/webpack.config.js
new file mode 100644
index 0000000000..4f03b7c87c
--- /dev/null
+++ b/catalog-ui/webpack.config.js
@@ -0,0 +1,64 @@
+'use strict';
+
+const path = require('path');
+const merge = require('webpack-merge');
+const webpack = require('webpack');
+const ServerConfig = require('./webpack.server');
+const webpackCommonConfig = require('./webpack.common');
+const { BaseHrefWebpackPlugin} = require('@angular/cli/plugins/webpack');
+const CopyWebpackPlugin = require('copy-webpack-plugin');
+
+// Print server configuration
+//process.stdout.write('webpack.server: ' + JSON.stringify(ServerConfig) + '\n');
+//process.stdout.write('webpack.common: ' + JSON.stringify(webpackCommonConfig) + '\n');
+const params = {
+ // entryPoints: [
+ // '/scripts/inline',
+ // '/scripts/polyfills',
+ // '/scripts/vendor',
+ // '/scripts/main',
+ // '/scripts/sw-register',
+ // '/scripts/scripts',
+ // '/scripts/styles'
+ // ]
+};
+
+module.exports = function(env) {
+
+ const webpackDevConfig = {
+ devtool: "source-map",
+ devServer: ServerConfig(env),
+ module: {
+ rules: [
+ { test: /\.(eot|svg)$/, loader: "file-loader?name=scripts/fonts/[name].[hash:20].[ext]" },
+ { test: /\.(jpg|png|gif|otf|ttf|woff|woff2|cur|ani)$/, loader: "url-loader?name=scripts/images/[name].[hash:20].[ext]&limit=10000" }
+ ]
+ },
+ output: {
+ path: path.join(process.cwd(), "dist"),
+ filename: "[name].bundle.js",
+ chunkFilename: "[id].chunk.js"
+ //publicPath: "/"
+ },
+ plugins: [
+ // Replace /sdc1 inside index.html with '' (because /sdc1 is used only in production).
+ new CopyWebpackPlugin([
+ {
+ from: './src/index.html', transform: function(content, path) {
+ content = (content+'').replace(/\/sdc1/g,'');
+ return content;
+ }
+ }
+ ]),
+ new webpack.DefinePlugin({
+ __DEBUG__: JSON.stringify(true),
+ __ENV__: JSON.stringify('dev'),
+ __HMR__: JSON.stringify('HMR')
+ }),
+ new webpack.HotModuleReplacementPlugin()
+ ]
+
+ };
+
+ return merge(webpackDevConfig, webpackCommonConfig(params));
+} \ No newline at end of file
diff --git a/catalog-ui/webpack.production.js b/catalog-ui/webpack.production.js
new file mode 100644
index 0000000000..b93b8f2663
--- /dev/null
+++ b/catalog-ui/webpack.production.js
@@ -0,0 +1,59 @@
+'use strict';
+
+const path = require('path');
+const merge = require('webpack-merge');
+const webpack = require('webpack');
+const ServerConfig = require('./webpack.server');
+const webpackCommonConfig = require('./webpack.common');
+const {GlobCopyWebpackPlugin, BaseHrefWebpackPlugin} = require('@angular/cli/plugins/webpack');
+const CopyWebpackPlugin = require('copy-webpack-plugin');
+
+const params = {
+ // entryPoints: [
+ // '/sdc1/scripts/inline',
+ // '/sdc1/scripts/polyfills',
+ // '/sdc1/scripts/vendor',
+ // '/sdc1/scripts/main',
+ // '/sdc1/scripts/sw-register',
+ // '/sdc1/scripts/scripts',
+ // '/sdc1/scripts/styles'
+ // ]
+};
+
+const webpackProdConfig = {
+ module: {
+ rules: [
+ { test: /\.(eot|svg)$/, loader: "file-loader?name=/scripts/fonts/[name].[hash:20].[ext]" },
+ { test: /\.(jpg|png|gif|otf|ttf|woff|woff2|cur|ani)$/, loader: "url-loader?name=/scripts/images/[name].[hash:20].[ext]&limit=10000" }
+ ]
+ },
+ output: {
+ path: path.join(process.cwd(), "dist"),
+ filename: "[name].bundle.js",
+ chunkFilename: "[id].chunk.js",
+ publicPath: "/sdc1"
+ },
+ plugins: [
+ new webpack.DefinePlugin({
+ __DEBUG__: JSON.stringify(false),
+ __ENV__: JSON.stringify('prod')
+ }),
+ new CopyWebpackPlugin([
+ { from: './src/index.html'}
+ ]),
+ new webpack.optimize.UglifyJsPlugin({
+ beautify: false,
+ mangle: {
+ screw_ie8: true,
+ keep_fnames: true
+ },
+ compress: {
+ warnings: false,
+ screw_ie8: true
+ },
+ comments: false
+ })
+ ]
+};
+
+module.exports = merge(webpackProdConfig, webpackCommonConfig(params));
diff --git a/catalog-ui/webpack.server.js b/catalog-ui/webpack.server.js
new file mode 100644
index 0000000000..b8c79a6197
--- /dev/null
+++ b/catalog-ui/webpack.server.js
@@ -0,0 +1,80 @@
+let path = require('path');
+
+const mockApis = require('./configurations/mock.json').sdcConfig;
+const proxy = require('http-proxy-middleware');
+const devPort = 9000;
+const fePort = 8181;
+
+module.exports = function(env) {
+
+ // 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];
+
+ 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
+ }));
+
+ // 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 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(; )?/, '');
+ }
+ }
+ }));
+
+ 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 22b386053f..388cf45b34 100644
--- a/common-app-api/pom.xml
+++ b/common-app-api/pom.xml
@@ -1,193 +1,111 @@
<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>common-app-api</artifactId>
-
+
<parent>
<groupId>org.openecomp.sdc</groupId>
<artifactId>sdc-main</artifactId>
<version>1.1.0-SNAPSHOT</version>
</parent>
-
-
- <dependencies>
-
- <dependency>
- <groupId>org.testng</groupId>
- <artifactId>testng</artifactId>
- <version>6.9.10</version>
- <scope>test</scope>
- </dependency>
-
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-core</artifactId>
- <version>${spring.version}</version>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-beans</artifactId>
- <version>${spring.version}</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-context</artifactId>
- <version>${spring.version}</version>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-context-support</artifactId>
- <version>${spring.version}</version>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-messaging</artifactId>
- <version>${spring.version}</version>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-web</artifactId>
- <version>${spring.version}</version>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-webmvc</artifactId>
- <version>${spring.version}</version>
- <scope>provided</scope>
- </dependency>
+ <dependencies>
<dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-aop</artifactId>
- <version>${spring.version}</version>
+ <groupId>org.openecomp.sdc</groupId>
+ <artifactId>security-utils</artifactId>
+ <version>${project.version}</version>
<scope>provided</scope>
</dependency>
-
+ <!-- functional java -->
<dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-aspects</artifactId>
- <version>${spring.version}</version>
+ <groupId>org.functionaljava</groupId>
+ <artifactId>functionaljava</artifactId>
+ <version>${functionaljava.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-test</artifactId>
- <version>${spring.version}</version>
- <scope>test</scope>
- </dependency>
-
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-expression</artifactId>
- <version>${spring.version}</version>
- <scope>test</scope>
- </dependency>
-
-
- <dependency>
- <groupId>org.openecomp.sdc</groupId>
- <artifactId>security-utils</artifactId>
- <version>${security-utils.version}</version>
- <scope>provided</scope>
- </dependency>
- <!-- functional java -->
-
- <dependency>
- <groupId>org.functionaljava</groupId>
- <artifactId>functionaljava</artifactId>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
- <version>1.7.10</version>
+ <version>${slf4j-api.version}</version>
<scope>provided</scope>
</dependency>
-
+
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
+ <version>${servlet-api.version}</version>
<scope>provided</scope>
</dependency>
-
+
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
- <version>2.24</version>
+ <version>${jersey-bom.version}</version>
<scope>provided</scope>
</dependency>
-
+
<!-- yaml to object converter -->
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
- <version>1.14</version>
+ <version>${snakeyaml.version}</version>
<scope>provided</scope>
</dependency>
-
- <!-- listen to file changes -->
+
+ <!-- listen to file changes -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-jci-core</artifactId>
+ <version>${commons-jci-core.version}</version>
<scope>provided</scope>
</dependency>
-
+
<!-- Gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
- <version>2.3.1</version>
+ <version>${gson.version}</version>
<scope>provided</scope>
</dependency>
-
- <!-- http client -->
+
+ <!-- http client -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
- <version>${httpclient.version}</version>
+ <version>${httpclient.version}</version>
<scope>provided</scope>
</dependency>
-
+
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
- <version>${httpcore.version}</version>
+ <version>${httpcore.version}</version>
<scope>provided</scope>
</dependency>
-
+
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
- <version>1.2.1-SNAPSHOT</version>
+ <version>${commons-logging}</version>
<scope>provided</scope>
</dependency>
-
+
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
- <version>2.0-SNAPSHOT</version>
+ <version>${commons-codec}</version>
<scope>provided</scope>
</dependency>
-
+
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
+ <version>${jersey-bom.version}</version>
<scope>provided</scope>
</dependency>
@@ -195,9 +113,9 @@
<dependency>
<groupId>com.jcabi</groupId>
<artifactId>jcabi-aspects</artifactId>
+ <version>${jcabi.version}</version>
<scope>provided</scope>
</dependency>
-
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
@@ -208,10 +126,10 @@
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
- <version>${lang3.version}</version>
+ <version>${lang3.version}</version>
<scope>provided</scope>
</dependency>
-
+
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
@@ -236,47 +154,48 @@
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
- <version>${logback.version}</version>
+ <version>${logback.version}</version>
<scope>provided</scope>
</dependency>
<!-- logging end -->
- <!-- -->
- <dependency>
+
+ <dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
- <version>${guava.version}</version><!--$NO-MVN-MAN-VER$-->
+ <version>${guava.version}</version><!--$NO-MVN-MAN-VER$ -->
<scope>provided</scope>
</dependency>
-
+ <!-- System metrics -->
<dependency>
- <groupId>org.fusesource</groupId>
- <artifactId>sigar</artifactId>
- <scope>compile</scope>
+ <groupId>org.fusesource</groupId>
+ <artifactId>sigar</artifactId>
+ <version>${sigar.version}</version>
+ <scope>provided</scope>
</dependency>
-
+
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
- <version>4.12</version>
+ <version>${junit.version}</version>
<scope>test</scope>
</dependency>
-
+
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
- <version>1.10.19</version>
+ <version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<!-- jsoup HTML parser library @ http://jsoup.org/ -->
<dependency>
- <groupId>org.jsoup</groupId>
- <artifactId>jsoup</artifactId>
- <version>1.8.3</version>
+ <groupId>org.jsoup</groupId>
+ <artifactId>jsoup</artifactId>
+ <version>1.8.3</version>
</dependency>
<dependency>
- <groupId>commons-validator</groupId>
+ <groupId>commons-validator</groupId>
<artifactId>commons-validator</artifactId>
<version>1.5.1</version>
</dependency>
@@ -284,28 +203,51 @@
<dependency>
<groupId>org.codehaus.jettison</groupId>
<artifactId>jettison</artifactId>
- <version>1.3.8</version>
+ <version>1.3.3</version>
</dependency>
-
+
<dependency>
- <groupId>de.ruedigermoeller</groupId>
- <artifactId>fst</artifactId>
- <version>2.47</version>
- <scope>compile</scope>
+ <groupId>de.ruedigermoeller</groupId>
+ <artifactId>fst</artifactId>
+ <version>2.47</version>
+ <scope>compile</scope>
</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>
- </plugins>
-</build>
-
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-deploy-plugin</artifactId>
+ <version>2.7</version>
+ <configuration>
+ <skip>true</skip>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+ <profiles>
+ <profile>
+ <id>Fortify</id>
+ <activation>
+ <activeByDefault>false</activeByDefault>
+ </activation>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>com.fortify.ps.maven.plugin</groupId>
+ <artifactId>sca-maven-plugin</artifactId>
+ <version>4.30</version>
+ <configuration>
+ <source>1.8</source>
+ <buildId>${project.parent.artifactId}</buildId>
+ <toplevelArtifactId>${project.parent.artifactId}</toplevelArtifactId>
+ </configuration>
+ </plugin>
+
+ </plugins>
+ </build>
+ </profile>
+ </profiles>
</project>
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 96505f4e5d..47fd5a28f7 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
@@ -21,6 +21,7 @@
package org.openecomp.sdc.be.config;
import java.util.Date;
+import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -61,11 +62,14 @@ public class Configuration extends BasicConfiguration {
private Date released;
private String version = "1111";
+ private String toscaConformanceLevel = "3.0";
+ private String minToscaConformanceLevel = "3.0";
private List<String> protocols;
private Map<String, String> users;
private Map<String, Object> neo4j;
private ElasticSearchConfig elasticSearch;
private String titanCfgFile;
+ private String titanMigrationKeySpaceCfgFile;
private Boolean titanInMemoryGraph;
private Long titanLockTimeout;
private Long titanReconnectIntervalInSeconds;
@@ -73,7 +77,8 @@ public class Configuration extends BasicConfiguration {
private Long esReconnectIntervalInSeconds;
private Long uebHealthCheckReconnectIntervalInSeconds;
private Long uebHealthCheckReadTimeout;
-
+ private LinkedList<Map<String, Map<String, String>>> defaultImports;
+
private List<String> resourceTypes;
private List<String> excludeResourceCategory;
private Map<String, Object> deploymentResourceArtifacts;
@@ -81,10 +86,11 @@ public class Configuration extends BasicConfiguration {
private Map<String, Object> toscaArtifacts;
private Map<String, Object> informationalResourceArtifacts;
private Map<String, Object> informationalServiceArtifacts;
- private Map<String, DeploymentArtifactTypeConfig> resourceDeploymentArtifacts;
- private Map<String, DeploymentArtifactTypeConfig> serviceDeploymentArtifacts;
- private Map<String, DeploymentArtifactTypeConfig> resourceInstanceDeploymentArtifacts;
- private Map<String, DeploymentArtifactTypeConfig> resourceInformationalDeployedArtifacts;
+ private Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts;
+ private Map<String, ArtifactTypeConfig> serviceDeploymentArtifacts;
+ private Map<String, ArtifactTypeConfig> resourceInstanceDeploymentArtifacts;
+ private Map<String, ArtifactTypeConfig> resourceInformationalArtifacts;
+ private Map<String, ArtifactTypeConfig> resourceInformationalDeployedArtifacts;
private Map<String, Object> serviceApiArtifacts;
private List<String> excludeServiceCategory;
private Map<String, Set<String>> requirementsToFulfillBeforeCert;
@@ -120,6 +126,18 @@ public class Configuration extends BasicConfiguration {
private ToscaValidatorsConfig toscaValidators;
private boolean disableAudit;
+
+ private Map<String, VfModuleProperty> vfModuleProperties;
+
+ private Map<String, String> genericAssetNodeTypes;
+
+ public Map<String, String> getGenericAssetNodeTypes() {
+ return genericAssetNodeTypes;
+ }
+
+ public void setGenericAssetNodeTypes(Map<String, String> genericAssetNodeTypes) {
+ this.genericAssetNodeTypes = genericAssetNodeTypes;
+ }
public SwitchoverDetectorConfig getSwitchoverDetector() {
return switchoverDetector;
@@ -259,6 +277,14 @@ public class Configuration extends BasicConfiguration {
this.titanCfgFile = titanCfgFile;
}
+ public String getTitanMigrationKeySpaceCfgFile() {
+ return titanMigrationKeySpaceCfgFile;
+ }
+
+ public void setTitanMigrationKeySpaceCfgFile(String titanMigrationKeySpaceCfgFile) {
+ this.titanMigrationKeySpaceCfgFile = titanMigrationKeySpaceCfgFile;
+ }
+
public Boolean getTitanInMemoryGraph() {
return titanInMemoryGraph;
}
@@ -359,28 +385,28 @@ public class Configuration extends BasicConfiguration {
this.serviceApiArtifacts = serviceApiArtifacts;
}
- public Map<String, DeploymentArtifactTypeConfig> getServiceDeploymentArtifacts() {
+ public Map<String, ArtifactTypeConfig> getServiceDeploymentArtifacts() {
return serviceDeploymentArtifacts;
}
- public void setServiceDeploymentArtifacts(Map<String, DeploymentArtifactTypeConfig> serviceDeploymentArtifacts) {
+ public void setServiceDeploymentArtifacts(Map<String, ArtifactTypeConfig> serviceDeploymentArtifacts) {
this.serviceDeploymentArtifacts = serviceDeploymentArtifacts;
}
- public Map<String, DeploymentArtifactTypeConfig> getResourceDeploymentArtifacts() {
+ public Map<String, ArtifactTypeConfig> getResourceDeploymentArtifacts() {
return resourceDeploymentArtifacts;
}
- public void setResourceDeploymentArtifacts(Map<String, DeploymentArtifactTypeConfig> resourceDeploymentArtifacts) {
+ public void setResourceDeploymentArtifacts(Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts) {
this.resourceDeploymentArtifacts = resourceDeploymentArtifacts;
}
public void setResourceInstanceDeploymentArtifacts(
- Map<String, DeploymentArtifactTypeConfig> resourceInstanceDeploymentArtifacts) {
+ Map<String, ArtifactTypeConfig> resourceInstanceDeploymentArtifacts) {
this.resourceInstanceDeploymentArtifacts = resourceInstanceDeploymentArtifacts;
}
- public Map<String, DeploymentArtifactTypeConfig> getResourceInstanceDeploymentArtifacts() {
+ public Map<String, ArtifactTypeConfig> getResourceInstanceDeploymentArtifacts() {
return resourceInstanceDeploymentArtifacts;
}
@@ -779,7 +805,7 @@ public class Configuration extends BasicConfiguration {
}
}
- public static class DeploymentArtifactTypeConfig {
+ public static class ArtifactTypeConfig {
List<String> acceptedTypes;
List<String> validForResourceTypes;
@@ -1149,12 +1175,12 @@ public class Configuration extends BasicConfiguration {
this.artifactsIndex = artifactsIndex;
}
- public Map<String, DeploymentArtifactTypeConfig> getResourceInformationalDeployedArtifacts() {
+ public Map<String, ArtifactTypeConfig> getResourceInformationalDeployedArtifacts() {
return resourceInformationalDeployedArtifacts;
}
public void setResourceInformationalDeployedArtifacts(
- Map<String, DeploymentArtifactTypeConfig> resourceInformationalDeployedArtifacts) {
+ Map<String, ArtifactTypeConfig> resourceInformationalDeployedArtifacts) {
this.resourceInformationalDeployedArtifacts = resourceInformationalDeployedArtifacts;
}
@@ -1230,4 +1256,60 @@ public class Configuration extends BasicConfiguration {
this.disableAudit = enableAudit;
}
+ public Map<String, ArtifactTypeConfig> getResourceInformationalArtifacts() {
+ return resourceInformationalArtifacts;
+ }
+
+ public void setResourceInformationalArtifacts(Map<String, ArtifactTypeConfig> resourceInformationalArtifacts) {
+ this.resourceInformationalArtifacts = resourceInformationalArtifacts;
+ }
+
+ public Map<String, VfModuleProperty> getVfModuleProperties() {
+ return vfModuleProperties;
+ }
+
+ public void setVfModuleProperties(Map<String, VfModuleProperty> vfModuleProperties) {
+ this.vfModuleProperties = vfModuleProperties;
+ }
+
+ public String getToscaConformanceLevel() {
+ return toscaConformanceLevel;
+ }
+
+ public void setToscaConformanceLevel(String toscaConformanceLevel) {
+ this.toscaConformanceLevel = toscaConformanceLevel;
+ }
+
+ public String getMinToscaConformanceLevel() {
+ return minToscaConformanceLevel;
+ }
+
+ public void setMinToscaConformanceLevel(String toscaConformanceLevel) {
+ this.minToscaConformanceLevel = toscaConformanceLevel;
+ }
+
+ public static class VfModuleProperty {
+ private String forBaseModule;
+ private String forNonBaseModule;
+ public String getForBaseModule() {
+ return forBaseModule;
+ }
+ public void setForBaseModule(String forBaseModule) {
+ this.forBaseModule = forBaseModule;
+ }
+ public String getForNonBaseModule() {
+ return forNonBaseModule;
+ }
+ public void setForNonBaseModule(String forNonBaseModule) {
+ this.forNonBaseModule = forNonBaseModule;
+ }
+ }
+
+ public LinkedList<Map<String, Map<String, String>>> getDefaultImports() {
+ return defaultImports;
+ }
+
+ public void setDefaultImports(LinkedList<Map<String, Map<String, String>>> defaultImports) {
+ this.defaultImports = defaultImports;
+ }
}
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 e4a2092e2f..56e26ce55e 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
@@ -283,7 +283,8 @@ public class DistributionEngineConfiguration extends BasicConfiguration {
@Override
public String toString() {
- return "CreateTopicConfig [partitionCount=" + partitionCount + ", replicationCount=" + replicationCount + "]";
+ return "CreateTopicConfig [partitionCount=" + partitionCount + ", replicationCount=" + replicationCount
+ + "]";
}
}
@@ -357,7 +358,8 @@ public class DistributionEngineConfiguration extends BasicConfiguration {
@Override
public String toString() {
- return "DistributionStatusTopicConfig [pollingIntervalSec=" + pollingIntervalSec + ", fetchTimeSec=" + fetchTimeSec + ", consumerGroup=" + consumerGroup + ", consumerId=" + consumerId + "]";
+ return "DistributionStatusTopicConfig [pollingIntervalSec=" + pollingIntervalSec + ", fetchTimeSec="
+ + fetchTimeSec + ", consumerGroup=" + consumerGroup + ", consumerId=" + consumerId + "]";
}
}
@@ -394,7 +396,8 @@ public class DistributionEngineConfiguration extends BasicConfiguration {
@Override
public String toString() {
- return "DistributionNotificationTopicConfig [maxWaitingAfterSendingSeconds=" + maxWaitingAfterSendingSeconds + ", maxThreadPoolSize=" + maxThreadPoolSize + ", minThreadPoolSize=" + minThreadPoolSize + "]";
+ return "DistributionNotificationTopicConfig [maxWaitingAfterSendingSeconds=" + maxWaitingAfterSendingSeconds
+ + ", maxThreadPoolSize=" + maxThreadPoolSize + ", minThreadPoolSize=" + minThreadPoolSize + "]";
}
}
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..1f036678cf 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
@@ -82,8 +82,7 @@ public class BeMonitoringService {
}
public void start(int interval) {
- Configuration config = ((ConfigurationManager) context.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR))
- .getConfiguration();
+ Configuration config = ((ConfigurationManager) context.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).getConfiguration();
if (config.getSystemMonitoring().getEnabled()) {
log.info("BE monitoring service is enabled, interval is {} seconds", interval);
this.monitoringExecutor.scheduleAtFixedRate(new MonitoringScheduledTask(), 0, interval, TimeUnit.SECONDS);
@@ -95,10 +94,8 @@ 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());
+ 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);
String monitoringMetricsJson = gson.toJson(monitoringMetrics);
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/api/ArtifactGroupTypeEnum.java b/common-app-api/src/main/java/org/openecomp/sdc/common/api/ArtifactGroupTypeEnum.java
index b7968dc53f..c990d43f64 100644
--- a/common-app-api/src/main/java/org/openecomp/sdc/common/api/ArtifactGroupTypeEnum.java
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/api/ArtifactGroupTypeEnum.java
@@ -25,12 +25,7 @@ import java.util.List;
public enum ArtifactGroupTypeEnum {
- INFORMATIONAL("INFORMATIONAL"),
- DEPLOYMENT("DEPLOYMENT"),
- LIFE_CYCLE("LIFE_CYCLE"),
- SERVICE_API("SERVICE_API"),
- TOSCA("TOSCA"),
- OTHER("OTHER");
+ INFORMATIONAL("INFORMATIONAL"), DEPLOYMENT("DEPLOYMENT"), LIFE_CYCLE("LIFE_CYCLE"), SERVICE_API("SERVICE_API"), TOSCA("TOSCA"), OTHER("OTHER");
private String type;
@@ -56,7 +51,7 @@ public enum ArtifactGroupTypeEnum {
}
public static List<String> getAllTypes() {
- List<String> types = new ArrayList<String>();
+ List<String> types = new ArrayList<>();
for (ArtifactGroupTypeEnum ate : ArtifactGroupTypeEnum.values()) {
types.add(ate.getType());
}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/api/ArtifactTypeEnum.java b/common-app-api/src/main/java/org/openecomp/sdc/common/api/ArtifactTypeEnum.java
index c0fbad006a..6e7ebc1854 100644
--- a/common-app-api/src/main/java/org/openecomp/sdc/common/api/ArtifactTypeEnum.java
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/api/ArtifactTypeEnum.java
@@ -24,29 +24,22 @@ import java.util.ArrayList;
import java.util.List;
/**
- * Enum That Represents possible Artifacts Types.
+ * Enum That Represents possible Artifacts Types.
*
*/
public enum ArtifactTypeEnum {
- CHEF("CHEF"), PUPPET("PUPPET"), YANG("YANG"), SHELL_SCRIPT("SHELL_SCRIPT"), ICON( "ICON"),
- UNKNOWN("UNKNOWN"), HEAT("HEAT"), DG_XML("DG_XML"), MURANO_PKG( "MURANO_PKG"), HEAT_ENV("HEAT_ENV"),
- YANG_XML("YANG_XML"), HEAT_VOL("HEAT_VOL"), HEAT_NET("HEAT_NET"), OTHER("OTHER"), WORKFLOW("WORKFLOW"),
- NETWORK_CALL_FLOW("NETWORK_CALL_FLOW"), TOSCA_TEMPLATE("TOSCA_TEMPLATE"), TOSCA_CSAR("TOSCA_CSAR"),
- VNF_CATALOG("VNF_CATALOG"), VF_LICENSE("VF_LICENSE"),VENDOR_LICENSE("VENDOR_LICENSE"),
- MODEL_INVENTORY_PROFILE("MODEL_INVENTORY_PROFILE"), MODEL_QUERY_SPEC("MODEL_QUERY_SPEC"),
- APPC_CONFIG("APPC_CONFIG"), HEAT_NESTED("HEAT_NESTED"), HEAT_ARTIFACT("HEAT_ARTIFACT"),
- VF_MODULES_METADATA("VF_MODULES_METADATA"),
- //DCAE Artifacts
- DCAE_TOSCA("DCAE_TOSCA"), DCAE_JSON("DCAE_JSON"), DCAE_POLICY("DCAE_POLICY"), DCAE_DOC("DCAE_DOC"),
- DCAE_EVENT("DCAE_EVENT"), DCAE_INVENTORY_TOSCA("DCAE_INVENTORY_TOSCA"), DCAE_INVENTORY_JSON("DCAE_INVENTORY_JSON"),
- DCAE_INVENTORY_POLICY("DCAE_INVENTORY_POLICY"), DCAE_INVENTORY_DOC("DCAE_INVENTORY_DOC"),
- DCAE_INVENTORY_BLUEPRINT("DCAE_INVENTORY_BLUEPRINT"), DCAE_INVENTORY_EVENT("DCAE_INVENTORY_EVENT"),
- //AAI Artifacts
- AAI_SERVICE_MODEL("AAI_SERVICE_MODEL"), AAI_VF_MODEL("AAI_VF_MODEL"), AAI_VF_MODULE_MODEL("AAI_VF_MODULE_MODEL"),
- AAI_VF_INSTANCE_MODEL("AAI_VF_INSTANCE_MODEL")
+ CHEF("CHEF"), PUPPET("PUPPET"), YANG("YANG"), SHELL_SCRIPT("SHELL_SCRIPT"), SHELL("SHELL"), 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"), BPEL("BPEL"),
+ 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"),
+ // 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;
}
@@ -63,14 +56,14 @@ public enum ArtifactTypeEnum {
public static ArtifactTypeEnum findType(final String type) {
for (ArtifactTypeEnum ate : ArtifactTypeEnum.values()) {
- //According to Pavel/Ella
+ // 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()) {
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 673060cb0d..812b148984 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
@@ -62,7 +62,7 @@ public interface Constants {
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 SDC_RELEASE_VERSION_ATTR = "SDC-Version";
+ public static final String ASDC_RELEASE_VERSION_ATTR = "ASDC-Version";
// public static final String AUDITING_MANAGER = "auditingManager";
// public static final String USER_ADMIN_MANAGER = "userAdminManager";
public static final String YEAR = "year";
@@ -110,7 +110,8 @@ public interface Constants {
public static final String REQUIRED_ARTIFACTS = "requiredArtifacts";
public static final String ABSTRACT = "abstract";
- public static final String GLOBAL_SUBSTITUTION_TYPE_SERVICE_TEMPLATE = "Definitions/GlobalSubstitutionTypesServiceTemplate.yaml";
+ public static final String GLOBAL_SUBSTITUTION_TYPES_SERVICE_TEMPLATE = "Definitions/GlobalSubstitutionTypesServiceTemplate.yaml";
+ public static final String ABSTRACT_SUBSTITUTE_GLOBAL_TYPES_SERVICE_TEMPLATE = "Definitions/AbstractSubstituteGlobalTypesServiceTemplate.yaml";
public static final String VENDOR_LICENSE_MODEL = "vendor-license-model.xml";
public static final String VENDOR_LICENSE_LABEL = "vendorlicense";
@@ -121,6 +122,7 @@ public interface Constants {
public static final String VF_LICENSE_LABEL = "vflicense";
public static final String VF_LICENSE_DISPLAY_NAME = "VF License";
public static final String VF_LICENSE_DESCRIPTION = "VF license file";
- public static final String ARTIFACTS = "Artifacts/";
public static final String GET_INPUT = "get_input";
+ public static final String SERVICE_TEMPLATE_FILE_POSTFIX = "ServiceTemplate.yaml";
+ public static final String UNBOUNDED = "unbounded";
}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/api/ResponseInfo.java b/common-app-api/src/main/java/org/openecomp/sdc/common/api/ResponseInfo.java
index 337d5d1b8a..2a6b7e7055 100644
--- a/common-app-api/src/main/java/org/openecomp/sdc/common/api/ResponseInfo.java
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/api/ResponseInfo.java
@@ -26,12 +26,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
public class ResponseInfo {
public static enum ResponseStatusEnum {
- SUCCESS("success"),
- LOGIN_FAILED("loginFailed"),
- INTERNAL_ERROR("internalError"),
- MISSING_HEADERS("required headers are missing"),
- TIMEOUT("timeout"),
- PARSING_ERROR("parsingFailed");
+ SUCCESS("success"), LOGIN_FAILED("loginFailed"), INTERNAL_ERROR("internalError"), MISSING_HEADERS("required headers are missing"), TIMEOUT("timeout"), PARSING_ERROR("parsingFailed");
ResponseStatusEnum(String status) {
this.statusDescription = status;
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/api/UploadArtifactInfo.java b/common-app-api/src/main/java/org/openecomp/sdc/common/api/UploadArtifactInfo.java
index 9e1734135c..110dbf34a2 100644
--- a/common-app-api/src/main/java/org/openecomp/sdc/common/api/UploadArtifactInfo.java
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/api/UploadArtifactInfo.java
@@ -26,8 +26,7 @@ public class UploadArtifactInfo {
}
- public UploadArtifactInfo(String artifactName, String artifactPath, ArtifactTypeEnum artifactType,
- String artifactDescription) {
+ public UploadArtifactInfo(String artifactName, String artifactPath, ArtifactTypeEnum artifactType, String artifactDescription) {
super();
this.artifactName = artifactName;
this.artifactPath = artifactPath;
@@ -35,8 +34,7 @@ public class UploadArtifactInfo {
this.artifactDescription = artifactDescription;
}
- public UploadArtifactInfo(String artifactName, String artifactPath, ArtifactTypeEnum artifactType,
- String artifactDescription, String artifactData) {
+ public UploadArtifactInfo(String artifactName, String artifactPath, ArtifactTypeEnum artifactType, String artifactDescription, String artifactData) {
super();
this.artifactName = artifactName;
this.artifactPath = artifactPath;
@@ -139,9 +137,7 @@ public class UploadArtifactInfo {
@Override
public String toString() {
- return "UploadArtifactInfo [artifactName=" + artifactName + ", artifactPath=" + artifactPath + ", artifactType="
- + artifactType + ", artifactDescription=" + artifactDescription + ", artifactData=" + artifactData
- + "]";
+ return "UploadArtifactInfo [artifactName=" + artifactName + ", artifactPath=" + artifactPath + ", artifactType=" + artifactType + ", artifactDescription=" + artifactDescription + ", artifactData=" + artifactData + "]";
}
}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/api/UserRoleEnum.java b/common-app-api/src/main/java/org/openecomp/sdc/common/api/UserRoleEnum.java
index 6d333bf457..a750fa454a 100644
--- a/common-app-api/src/main/java/org/openecomp/sdc/common/api/UserRoleEnum.java
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/api/UserRoleEnum.java
@@ -21,13 +21,7 @@
package org.openecomp.sdc.common.api;
public enum UserRoleEnum {
- ADMIN("ADMIN"),
- DESIGNER("DESIGNER"),
- TESTER("TESTER"),
- GOVERNOR("GOVERNOR"),
- OPS("OPS"),
- PRODUCT_MANAGER("PRODUCT_MANAGER"),
- PRODUCT_STRATEGIST("PRODUCT_STRATEGIST");
+ ADMIN("ADMIN"), DESIGNER("DESIGNER"), TESTER("TESTER"), GOVERNOR("GOVERNOR"), OPS("OPS"), PRODUCT_MANAGER("PRODUCT_MANAGER"), PRODUCT_STRATEGIST("PRODUCT_STRATEGIST");
private String name;
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorLogUtil.java b/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorLogUtil.java
index 274625aae4..5051d8e645 100644
--- a/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorLogUtil.java
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorLogUtil.java
@@ -110,7 +110,7 @@ public class EcompErrorLogUtil {
logEcompError("logEcompError", mismatchErrorEnum, false, ecompErrorEnum.name().toString());
return;
} else {
- log.info("Failed to log the error code " + mismatchErrorEnum);
+ log.info("Failed to log the error code {}", mismatchErrorEnum);
return;
}
}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/config/generation/GenerateEcompErrorsCsv.java b/common-app-api/src/main/java/org/openecomp/sdc/common/config/generation/GenerateEcompErrorsCsv.java
index 275339ee20..584a1d8ad1 100644
--- a/common-app-api/src/main/java/org/openecomp/sdc/common/config/generation/GenerateEcompErrorsCsv.java
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/config/generation/GenerateEcompErrorsCsv.java
@@ -202,7 +202,6 @@ public class GenerateEcompErrorsCsv {
writer.flush();
writer.close();
} catch (IOException e) {
- // TODO Auto-generated catch block
e.printStackTrace();
}
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 263d446674..53aa2391d5 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
@@ -54,6 +54,7 @@ public enum AuditingFieldsKeysEnum {
AUDIT_RESOURCE_DPREV_STATUS(String.class, "DPREV_STATUS"),
AUDIT_RESOURCE_DCURR_STATUS(String.class, "DCURR_STATUS"),
AUDIT_RESOURCE_TOSCA_NODE_TYPE(String.class, "TOSCA_NODE_TYPE"),
+ AUDIT_RESOURCE_URL(String.class, "RESOURCE_URL"),
// Distribution Engine
AUDIT_DISTRIBUTION_ENVRIONMENT_NAME(String.class, "D_ENV"),
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 12ba17baa5..de94358ab4 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
@@ -20,9 +20,13 @@
package org.openecomp.sdc.common.datastructure;
+import java.io.Serializable;
+import java.util.List;
import java.util.function.Function;
import java.util.function.Supplier;
+import fj.data.Either;
+
/**
* Class For Functional interfaces And Functional Methods
*
@@ -32,9 +36,20 @@ import java.util.function.Supplier;
public class FunctionalInterfaces {
private static final int DEFAULT_REDO_INTERVAL_TIME_MS = 50;
private static final int DEFAULT_MAX_WAIT_TIME_MS = 10000;
+
+ /**
+ * This is an interface of a List that implements Serializable
+ * @author mshitrit
+ *
+ * @param <T>
+ */
+ public interface SerializableList<T> extends List<T> , Serializable {
+ }
/**
* @author mshitrit Consumer that takes two parameters
+ * @param <T1>
+ * @param <T2>
*/
public interface ConsumerTwoParam<T1, T2> {
/**
@@ -48,6 +63,9 @@ public class FunctionalInterfaces {
/**
* @author mshitrit Function that takes two parameters
+ * @param <T1>
+ * @param <T2>
+ * @param <R>
*/
public interface FunctionTwoParam<T1, T2, R> {
/**
@@ -62,6 +80,9 @@ public class FunctionalInterfaces {
/**
* @author mshitrit Function that throws an exception
+ * @param <T>
+ * @param <R>
+ * @param <E>
*/
public interface FunctionThrows<T, R, E extends Exception> {
/**
@@ -75,6 +96,8 @@ public class FunctionalInterfaces {
/**
* @author mshitrit Supplier that throws an exception
+ * @param <R>
+ * @param <E>
*/
public interface SupplierThrows<R, E extends Exception> {
/**
@@ -88,6 +111,8 @@ public class FunctionalInterfaces {
/**
* @author mshitrit Consumer that throws an exception
+ * @param <T>
+ * @param <E>
*/
public interface ConsumerThrows<T, E extends Exception> {
/**
@@ -101,6 +126,7 @@ public class FunctionalInterfaces {
/**
* @author mshitrit Runnable that throws an exception
+ * @param <E>
*/
public interface RunnableThrows<E extends Exception> {
/**
@@ -279,4 +305,39 @@ public class FunctionalInterfaces {
}
+ /**
+ * Converts Either containing right value to another either with different
+ * type of left value and the same type of right value.
+ *
+ * @param eitherToConvert
+ * @return
+ */
+ 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{
+ 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.
+ *
+ * @param eitherToConvert
+ * @return
+ */
+ 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());
+ }
+
+ }
+
}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/impl/ConfigFileChangeListener.java b/common-app-api/src/main/java/org/openecomp/sdc/common/impl/ConfigFileChangeListener.java
index 9b5debb53a..9364dad476 100644
--- a/common-app-api/src/main/java/org/openecomp/sdc/common/impl/ConfigFileChangeListener.java
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/impl/ConfigFileChangeListener.java
@@ -62,15 +62,13 @@ public class ConfigFileChangeListener extends FileChangeListener {
Class<? extends BasicConfiguration> configClass = configurationListener.getType();
- BasicConfiguration basicConfiguration = yamlToObjectConverter
- .convert(pFile.getAbsolutePath(), configClass);
+ BasicConfiguration basicConfiguration = yamlToObjectConverter.convert(pFile.getAbsolutePath(), configClass);
if (basicConfiguration == null) {
- log.warn(
- "Cannot update the listeners for file Change since the file content is invalid");
+ log.warn("Cannot update the listeners for file Change since the file content is invalid");
continue;
}
- log.debug("Loaded configuration after converting is " + basicConfiguration);
+ log.debug("Loaded configuration after converting is {}", basicConfiguration);
// System.out.println("New configuration is " +
// basicConfiguration);
@@ -80,7 +78,7 @@ public class ConfigFileChangeListener extends FileChangeListener {
}
} else {
- log.warn("Cannot calculate id from file " + pFile.getName());
+ log.warn("Cannot calculate id from file {}", pFile.getName());
}
}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/impl/FSConfigurationSource.java b/common-app-api/src/main/java/org/openecomp/sdc/common/impl/FSConfigurationSource.java
index 76f64ca278..a800305958 100644
--- a/common-app-api/src/main/java/org/openecomp/sdc/common/impl/FSConfigurationSource.java
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/impl/FSConfigurationSource.java
@@ -45,14 +45,11 @@ public class FSConfigurationSource implements ConfigurationSource {
}
/*
- * get and watch configuration changes. The file name we looking for is the
- * lower case of the class name separated by "-".
+ * get and watch configuration changes. The file name we looking for is the lower case of the class name separated by "-".
*
* (non-Javadoc)
*
- * @see
- * org.openecomp.sdc.common.api.ConfigurationSource#getAndWatchConfiguration
- * (java.lang.Class, org.openecomp.sdc.common.api.ConfigurationListener)
+ * @see org.openecomp.sdc.common.api.ConfigurationSource#getAndWatchConfiguration (java.lang.Class, org.openecomp.sdc.common.api.ConfigurationListener)
*/
public <T> T getAndWatchConfiguration(Class<T> className, ConfigurationListener configurationListener) {
@@ -80,9 +77,7 @@ public class FSConfigurationSource implements ConfigurationSource {
}
/**
- * convert camel case string to list of words separated by "-" where each
- * word is in lower case format. For example, MyClass will be calculated to
- * be my-class.yaml .
+ * convert camel case string to list of words separated by "-" where each word is in lower case format. For example, MyClass will be calculated to be my-class.yaml .
*
* @param className
* @return file name based on the class name
@@ -112,8 +107,7 @@ public class FSConfigurationSource implements ConfigurationSource {
return builder.toString() + Constants.YAML_SUFFIX;
/*
- * } else { return className.getSimpleName().toLowerCase() +
- * Constants.YAML_SUFFIX; }
+ * } else { return className.getSimpleName().toLowerCase() + Constants.YAML_SUFFIX; }
*/
}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/jsongraph/util/CommonUtility.java b/common-app-api/src/main/java/org/openecomp/sdc/common/jsongraph/util/CommonUtility.java
new file mode 100644
index 0000000000..8f94d8042c
--- /dev/null
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/jsongraph/util/CommonUtility.java
@@ -0,0 +1,60 @@
+package org.openecomp.sdc.common.jsongraph.util;
+
+import org.slf4j.Logger;
+
+/**
+ * Provides common utility: functionality, common fields and enumerations
+ *
+ */
+public class CommonUtility {
+ /**
+ * Provides list of logging level names
+ *
+ */
+ public enum LogLevelEnum {
+ ERROR,
+ WARNING,
+ INFO,
+ DEBUG,
+ TRACE,
+ }
+ /**
+ * Adds received message to log according to level in case if specified level is enabled
+ * @param logger
+ * @param logLevel
+ * @param format
+ * @param arguments
+ */
+ public static void addRecordToLog(Logger logger, LogLevelEnum logLevel, String format, Object... arguments ){
+ switch(logLevel){
+ case ERROR:
+ if(logger.isErrorEnabled()){
+ logger.error(format, arguments);
+ }
+ break;
+ case WARNING:
+ if(logger.isWarnEnabled()){
+ logger.warn(format, arguments);
+ }
+ break;
+ case INFO:
+ if(logger.isInfoEnabled()){
+ logger.info(format, arguments);
+ }
+ break;
+ case DEBUG:
+ if(logger.isDebugEnabled()){
+ logger.debug(format, arguments);
+ }
+ break;
+ case TRACE:
+ if(logger.isTraceEnabled()){
+ logger.trace(format, arguments);
+ }
+ break;
+ default:
+ break;
+ }
+ }
+
+}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/listener/AppContextListener.java b/common-app-api/src/main/java/org/openecomp/sdc/common/listener/AppContextListener.java
index 3f588e8aa2..45976c42d1 100644
--- a/common-app-api/src/main/java/org/openecomp/sdc/common/listener/AppContextListener.java
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/listener/AppContextListener.java
@@ -62,7 +62,8 @@ public class AppContextListener implements ServletContextListener {
String appConfigDir = configHome + File.separator + appName;
// ChangeListener changeListener = new ChangeListener();
- ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir);
+ ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(),
+ appConfigDir);
context.getServletContext().setAttribute(Constants.CONFIGURATION_SOURCE_ATTR, configurationSource);
@@ -78,7 +79,8 @@ public class AppContextListener implements ServletContextListener {
ExternalConfiguration.stopListenForFileChanges();
}
- private String setAndGetAttributeInContext(ServletContextEvent context, Map<String, String> manifestAttr, String attr) {
+ private String setAndGetAttributeInContext(ServletContextEvent context, Map<String, String> manifestAttr,
+ String attr) {
String name = manifestAttr.get(attr);
if (name != null) {
@@ -116,7 +118,6 @@ public class AppContextListener implements ServletContextListener {
try {
inputStream.close();
} catch (IOException e) {
- // TODO Auto-generated catch block
e.printStackTrace();
}
}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/monitoring/MonitoringEvent.java b/common-app-api/src/main/java/org/openecomp/sdc/common/monitoring/MonitoringEvent.java
index 61651f3ddc..8d96dbd61c 100644
--- a/common-app-api/src/main/java/org/openecomp/sdc/common/monitoring/MonitoringEvent.java
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/monitoring/MonitoringEvent.java
@@ -24,8 +24,7 @@ import org.openecomp.sdc.common.datastructure.ESTimeBasedEvent;
public class MonitoringEvent extends ESTimeBasedEvent {
- private static String MONITORING_EVENT_TEMPLATE = "hostid=\"%s\" hostcpu=\"%s\" hostmem=\"%s\" hostdisk=\"%s\" "
- + "jvmid=\"%s\" jvmcpu=\"%s\" jvmmem=\"%s\" jvmtnum=\"%s\" " + "appid=\"%s\" appstat=\"%s\"";
+ private static String MONITORING_EVENT_TEMPLATE = "hostid=\"%s\" hostcpu=\"%s\" hostmem=\"%s\" hostdisk=\"%s\" " + "jvmid=\"%s\" jvmcpu=\"%s\" jvmmem=\"%s\" jvmtnum=\"%s\" " + "appid=\"%s\" appstat=\"%s\"";
private String hostid;
private Long hostcpu;
@@ -120,7 +119,6 @@ public class MonitoringEvent extends ESTimeBasedEvent {
@Override
public String toString() {
- return getFormattedString(MONITORING_EVENT_TEMPLATE, hostid, hostcpu, hostmem, hostdisk, jvmid, jvmcpu, jvmmem,
- jvmtnum, appid, appstat);
+ return getFormattedString(MONITORING_EVENT_TEMPLATE, hostid, hostcpu, hostmem, hostdisk, jvmid, jvmcpu, jvmmem, jvmtnum, appid, appstat);
}
}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/monitoring/MonitoringMetricsFetcher.java b/common-app-api/src/main/java/org/openecomp/sdc/common/monitoring/MonitoringMetricsFetcher.java
index 9df1aea983..e5c62d4772 100644
--- a/common-app-api/src/main/java/org/openecomp/sdc/common/monitoring/MonitoringMetricsFetcher.java
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/monitoring/MonitoringMetricsFetcher.java
@@ -79,7 +79,6 @@ public class MonitoringMetricsFetcher {
monitoringEvent.setAppid(appName);
// this is probably from healthcheck
- // TODO
monitoringEvent.setAppstat("appStatus");
return monitoringEvent;
}
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
index b64b651913..6f652cc8a4 100644
--- 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
@@ -67,12 +67,10 @@ public class RestClientServiceExeption extends Exception {
*
* @param response
*
- * public RSClientServiceExeption(ClientResponse response) {
- * super(); this.response = response; }
+ * public RSClientServiceExeption(ClientResponse response) { super(); this.response = response; }
*
* public ClientResponse getResponse() { return response; }
*
- * public void setResponse(ClientResponse response) {
- * this.response = response; }
+ * public void setResponse(ClientResponse response) { this.response = response; }
*/
}
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
index 7175b41943..eed083ab68 100644
--- 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
@@ -94,7 +94,7 @@ public class HttpRestClientServiceImpl implements IRestClient {
boolean initialized = false;
- logger.debug("HttpRestClientServiceImpl::init - start. restConfigurationInfo=" + restConfigurationInfo);
+ logger.debug("HttpRestClientServiceImpl::init - start. restConfigurationInfo= {}", restConfigurationInfo);
try {
createHttpClient(restConfigurationInfo);
@@ -124,8 +124,7 @@ public class HttpRestClientServiceImpl implements IRestClient {
}
- private void createHttpClient(RestConfigurationInfo restConfigurationInfo)
- throws KeyManagementException, NoSuchAlgorithmException {
+ private void createHttpClient(RestConfigurationInfo restConfigurationInfo) throws KeyManagementException, NoSuchAlgorithmException {
PoolingClientConnectionManager cm = new PoolingClientConnectionManager();
@@ -141,10 +140,8 @@ public class HttpRestClientServiceImpl implements IRestClient {
this.httpClient = new DefaultHttpClient(cm);
- int timeoutInSec = restConfigurationInfo.getReadTimeoutInSec() == null ? 0
- : restConfigurationInfo.getReadTimeoutInSec();
- int connectTimeoutInSec = restConfigurationInfo.getConnectTimeoutInSec() == null ? DEFAULT_CONNECT_TIMEOUT
- : restConfigurationInfo.getConnectTimeoutInSec();
+ 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);
@@ -212,14 +209,12 @@ public class HttpRestClientServiceImpl implements IRestClient {
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 {
+ 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 {
+ public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws CertificateException {
// TODO Auto-generated method stub
}
@@ -271,7 +266,7 @@ public class HttpRestClientServiceImpl implements IRestClient {
* @return String
*/
public RestResponse doGET(String uri, Properties headers) {
- logger.debug("Before executing uri " + uri + ". headers = " + headers);
+ logger.debug("Before executing uri {}. headers = {}", uri, headers);
HttpGet httpGet = new HttpGet(uri);
@@ -292,8 +287,7 @@ public class HttpRestClientServiceImpl implements IRestClient {
public RestResponse doPOST(String uri, Properties headers, Object objectToCreate) {
- logger.debug("Before executing uri " + uri + ". body = "
- + (objectToCreate != null ? objectToCreate.toString() : null) + ". headers = " + headers);
+ logger.debug("Before executing uri {}. body = {}. headers = {}", uri, (objectToCreate != null ? objectToCreate.toString() : null), headers);
HttpPost httpPost = new HttpPost(uri);
@@ -321,8 +315,7 @@ public class HttpRestClientServiceImpl implements IRestClient {
public RestResponse doPUT(String uri, Properties headers, Object objectToCreate) {
- logger.debug("Before executing uri " + uri + ". body = "
- + (objectToCreate != null ? objectToCreate.toString() : null) + ". headers = " + headers);
+ logger.debug("Before executing uri {}. body = {}. headers = {}", uri, (objectToCreate != null ? objectToCreate.toString() : null), headers);
HttpPut httpPut = new HttpPut(uri);
@@ -373,8 +366,7 @@ public class HttpRestClientServiceImpl implements IRestClient {
} catch (Exception exception) {
httpRequestBase.abort();
- log.error("Failed to execute the " + httpRequestBase.getMethod() + " request " + httpRequestBase.getURI(),
- exception);
+ log.error("Failed to execute the {} request {}", httpRequestBase.getMethod(), httpRequestBase.getURI(), exception);
// processAndThrowException(exception);
return null;
}
@@ -384,7 +376,7 @@ public class HttpRestClientServiceImpl implements IRestClient {
if (logger.isDebugEnabled()) {
URI uri = httpRequestBase.getURI();
String url = uri.toString();
- logger.debug("After executing uri " + url + ". response = " + restResponse);
+ logger.debug("After executing uri {}. response = {}", url, restResponse);
}
return restResponse;
@@ -393,7 +385,7 @@ public class HttpRestClientServiceImpl implements IRestClient {
public RestResponse doDELETE(String uri, Properties headers) {
if (logger.isDebugEnabled()) {
- logger.debug("Before executing uri " + uri + ". headers = " + headers);
+ logger.debug("Before executing uri {}. headers = {}", uri, headers);
}
HttpDelete httpDelete = new HttpDelete(uri);
@@ -413,12 +405,11 @@ public class HttpRestClientServiceImpl implements IRestClient {
* name of method
*/
private void logResponse(String response, String method) {
- logger.debug(method + " response = " + response);
+ logger.debug("{} response = {}", method, response);
}
/**
- * Exception during client invocation usually it happens when status code
- * starting with 400 or 500 is returned
+ * Exception during client invocation usually it happens when status code starting with 400 or 500 is returned
*
* @param exception
* Exception
@@ -427,7 +418,7 @@ public class HttpRestClientServiceImpl implements IRestClient {
private void processAndThrowException(Exception exception) throws RestClientServiceExeption {
logger.debug("\n------------------------");
- logger.debug("FAILURE: " + exception.getMessage());
+ logger.debug("FAILURE: {}", exception.getMessage());
throw new RestClientServiceExeption(exception);
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/rest/impl/validator/RequestHeadersValidator.java b/common-app-api/src/main/java/org/openecomp/sdc/common/rest/impl/validator/RequestHeadersValidator.java
index 5e2ff37735..18ec011868 100644
--- a/common-app-api/src/main/java/org/openecomp/sdc/common/rest/impl/validator/RequestHeadersValidator.java
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/rest/impl/validator/RequestHeadersValidator.java
@@ -37,7 +37,7 @@ public class RequestHeadersValidator {
public static void validateContentType(HttpServletRequest request, MediaType expectedContentType,
Map<String, String> headersMap) throws RestRequestValidationException {
- log.debug("validateContentType - expected: " + expectedContentType);
+ log.debug("validateContentType - expected: {}", expectedContentType);
if (request == null || expectedContentType == null) {
throw new RestRequestValidationException("request or media-type are null");
}
@@ -58,9 +58,9 @@ public class RequestHeadersValidator {
String headerVal = request.getHeader(requiredHeader);
if (headerVal != null && !headerVal.isEmpty()) {
headersMap.put(requiredHeader, headerVal);
- log.debug("found header - " + requiredHeader + ": " + headerVal);
+ log.debug("found header - {} : {}", requiredHeader, headerVal);
} else {
- log.error("missing identification header: " + requiredHeader);
+ log.error("missing identification header: {}", requiredHeader);
throw new RestRequestValidationException("missing identification header: " + requiredHeader);
}
}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/GeneralUtility.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/GeneralUtility.java
index 0c62b03d14..c89eeaf535 100644
--- a/common-app-api/src/main/java/org/openecomp/sdc/common/util/GeneralUtility.java
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/GeneralUtility.java
@@ -40,11 +40,21 @@ public class GeneralUtility {
}
return isSuccessfull;
}
-
+
+ /**
+ * Use with care, usage is not advised!!!
+ * The method only checks if String does not contain special characters + length divided by 4 with no remainder.
+ * The methods contained in other common libraries do the same.
+ */
public static boolean isBase64Encoded(byte[] data) {
return Base64.isBase64(data);
}
-
+
+ /**
+ *Use with care, usage is not advised!!!
+ * The method only checks if String does not contain special characters + length divided by 4 with no remainder.
+ * The methods contained in other common libraries do the same.
+ */
public static boolean isBase64Encoded(String str) {
boolean isEncoded = false;
try {
@@ -66,8 +76,8 @@ public class GeneralUtility {
/**
* Checks whether the passed string exceeds a limit of number of characters.
*
- * @param str str
- * @param limit limit
+ * @param str
+ * @param limit
* @return the result of comparison, or false if str is null.
*/
public static boolean isExceedingLimit(String str, int limit) {
@@ -78,14 +88,12 @@ public class GeneralUtility {
}
/**
- * Checks the passed string list whether the cumulative length of strings
- * and delimiters between them exceeds a limit of number of characters. For
- * example for list ("one","two","three") with delimiter "," the length of
- * list is calculated 3+1+3+1+5=13
+ * Checks the passed string list whether the cumulative length of strings and delimiters between them exceeds a limit of number of characters. For example for list ("one","two","three") with delimiter "," the length of list is calculated
+ * 3+1+3+1+5=13
*
- * @param strList strList
- * @param limit Limit
- * @param delimiterLength delimiterLength
+ * @param strList
+ * @param limit
+ * @param delimiterLength
* - 0 if there is no delimeter.
* @return the result of comparison, or false if strList is null.
*/
@@ -110,11 +118,9 @@ public class GeneralUtility {
}
/**
- * Return the extension as the substring from the last dot. For input
- * "kuku.txt", "txt" will be returned. If no dot is found or input is null,
- * empty string is returned.
+ * Return the extension as the substring from the last dot. For input "kuku.txt", "txt" will be returned. If no dot is found or input is null, empty string is returned.
*
- * @param fileName fileName
+ * @param fileName
* @return extension
*/
public static String getFilenameExtension(String fileName) {
@@ -137,7 +143,7 @@ public class GeneralUtility {
/**
*
- * @param data data
+ * @param data
* @return
*/
public static String calculateMD5ByString(String data) {
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/PairUtils.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/PairUtils.java
new file mode 100644
index 0000000000..3dd313b824
--- /dev/null
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/PairUtils.java
@@ -0,0 +1,19 @@
+package org.openecomp.sdc.common.util;
+
+import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.apache.commons.lang3.tuple.Pair;
+
+import java.util.List;
+import java.util.stream.Collectors;
+
+public class PairUtils {
+
+ public static <L, R> List<L> leftSequence(List<ImmutablePair<L, R>> pairs) {
+ return pairs.stream().map(Pair::getLeft).collect(Collectors.toList());
+ }
+
+ public static <L, R> List<R> rightSequence(List<Pair<L, R>> pairs) {
+ return pairs.stream().map(Pair::getRight).collect(Collectors.toList());
+ }
+
+}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/SerializationUtils.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/SerializationUtils.java
index ee2895f9fa..4574d3ff86 100644
--- a/common-app-api/src/main/java/org/openecomp/sdc/common/util/SerializationUtils.java
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/SerializationUtils.java
@@ -77,9 +77,8 @@ public class SerializationUtils {
T castObject = clazz.cast(object);
return Either.left(castObject);
} catch (Exception e) {
- log.debug("Failed to deserialize object of type " + clazz + " and uid " + componentName, e);
- BeEcompErrorManager.getInstance().logInternalUnexpectedError("DeserializeObjectFromCache",
- "Failed to deserialize object of type " + clazz, ErrorSeverity.WARNING);
+ log.debug("Failed to deserialize object of type {} and uid {}",clazz,componentName, e);
+ BeEcompErrorManager.getInstance().logInternalUnexpectedError("DeserializeObjectFromCache", "Failed to deserialize object of type " + clazz, ErrorSeverity.WARNING);
return Either.right(false);
}
}
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 b2b0344b39..3ea780a7f9 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
@@ -40,34 +40,40 @@ import com.google.common.base.CharMatcher;
public class ValidationUtils {
public final static Integer COMPONENT_NAME_MAX_LENGTH = 1024;
- public final static Pattern COMPONENT_NAME_PATTERN = Pattern.compile("^[\\w \\.\\-\\_\\:\\+]{1," + COMPONENT_NAME_MAX_LENGTH + "}$");
+ public final static Pattern COMPONENT_NAME_PATTERN = Pattern
+ .compile("^[\\w][\\w \\.\\-\\_\\:\\+]{0," + (COMPONENT_NAME_MAX_LENGTH-1) + "}$");
public final static Integer ADDITIONAL_INFORMATION_KEY_MAX_LENGTH = 50;
- public final static Pattern ADDITIONAL_INFORMATION_KEY_PATTERN = Pattern.compile("^[\\w\\s\\.\\-\\_]{1," + COMPONENT_NAME_MAX_LENGTH + "}$");
+ public final static Pattern ADDITIONAL_INFORMATION_KEY_PATTERN = Pattern
+ .compile("^[\\w\\s\\.\\-\\_]{1," + COMPONENT_NAME_MAX_LENGTH + "}$");
public final static Integer RSI_NAME_MAX_LENGTH = 1024;
- public final static Pattern RSI_NAME_PATTERN = Pattern.compile("^[\\w \\s\\.\\-\\_\\:\\+]{1," + RSI_NAME_MAX_LENGTH + "}$");
+ public final static Pattern RSI_NAME_PATTERN = Pattern
+ .compile("^[\\w \\s\\.\\-\\_\\:\\+]{1," + RSI_NAME_MAX_LENGTH + "}$");
public final static Integer COMMENT_MAX_LENGTH = 256;
public final static Integer ICON_MAX_LENGTH = 25;
public final static Pattern ICON_PATTERN = Pattern.compile("^[\\w\\-]{1," + ICON_MAX_LENGTH + "}$");
- public final static Integer PROJECT_CODE_MAX_LEGTH = 10;
- //public final static Pattern PROJECT_CODE_PATTERN = Pattern.compile("^[\\d]{5," + PROJECT_CODE_MAX_LEGTH + "}$");
- public final static Pattern PROJECT_CODE_PATTERN = Pattern.compile("^[\\s\\w_.-]{1,50}$");
- public final static Integer CONNTACT_ID_MAX_LENGTH = 6;
- // Format : aannnX (where a=a-z or A-Z, n=0-9, and X=a-z,A-Z, or 0-9)
- //public final static Pattern CONTACT_ID_PATTERN = Pattern.compile("[mM]{1}[0-9]{5}|[a-zA-Z]{2}[0-9]{4}|[a-zA-Z]{2}[0-9]{3}[a-zA-Z]{1}");
+ public final static Integer PROJECT_CODE_MAX_LEGTH = 50;
+ public final static Pattern PROJECT_CODE_PATTERN = Pattern.compile("^[\\s\\w_.-]{5,50}$");
+
+ // USER_ID format : aannnX (where a=a-z or A-Z, n=0-9, and X=a-z,A-Z, or 0-9)
+ public final static Integer CONNTACT_ID_MAX_LENGTH = 50;
+// public final static Pattern CONTACT_ID_PATTERN = Pattern
+// .compile("[mM]{1}[0-9]{5}|[a-zA-Z]{2}[0-9]{4}|[a-zA-Z]{2}[0-9]{3}[a-zA-Z]{1}");
public final static Pattern CONTACT_ID_PATTERN = Pattern.compile("^[\\s\\w_.-]{1,50}$");
public final static Pattern OCTET_PATTERN = Pattern.compile("%[a-fA-F0-9]{2}");
public final static Pattern NONE_UTF8_PATTERN = Pattern.compile("[^\\x00-\\x7F]+");
- public final static Pattern URL_INVALIDE_PATTERN = Pattern.compile("[,#?&@$<>~^`\\\\\\[\\]{}|\")(*!+=;%]+");
+ public final static Pattern URL_INVALIDE_PATTERN = Pattern.compile("[,#?&@$<>~^`\\\\\\[\\]{}|\")(*!+=;%]+");// ,#?&@$<>~^`\\[]{}|")(*!
public final static Pattern ENGLISH_PATTERN = Pattern.compile("^[\\p{Graph}\\x20]+$");
public final static Integer COMPONENT_DESCRIPTION_MAX_LENGTH = 1024;
public final static Integer TAG_MAX_LENGTH = 1024;
public final static Integer TAG_LIST_MAX_LENGTH = 1024;
public final static Integer VENDOR_NAME_MAX_LENGTH = 25;
- public final static Pattern VENDOR_NAME_PATTERN = Pattern.compile("^[\\x20-\\x21\\x23-\\x29\\x2B-\\x2E\\x30-\\x39\\x3B\\x3D\\x40-\\x5B\\x5D-\\x7B\\x7D-\\xFF]+$");
+ public final static Pattern VENDOR_NAME_PATTERN = Pattern
+ .compile("^[\\x20-\\x21\\x23-\\x29\\x2B-\\x2E\\x30-\\x39\\x3B\\x3D\\x40-\\x5B\\x5D-\\x7B\\x7D-\\xFF]+$");
public final static Integer VENDOR_RELEASE_MAX_LENGTH = 25;
- public final static Pattern VENDOR_RELEASE_PATTERN = Pattern.compile("^[\\x20-\\x21\\x23-\\x29\\x2B-\\x2E\\x30-\\x39\\x3B\\x3D\\x40-\\x5B\\x5D-\\x7B\\x7D-\\xFF]+$");
+ public final static Pattern VENDOR_RELEASE_PATTERN = Pattern
+ .compile("^[\\x20-\\x21\\x23-\\x29\\x2B-\\x2E\\x30-\\x39\\x3B\\x3D\\x40-\\x5B\\x5D-\\x7B\\x7D-\\xFF]+$");
public final static Pattern CLEAN_FILENAME_PATTERN = Pattern.compile("[\\x00-\\x1f\\x80-\\x9f\\x5c/<?>\\*:|\"/]+");
@@ -83,11 +89,13 @@ public class ValidationUtils {
public final static Pattern COLON_PATTERN = Pattern.compile("[:]+");
public final static Pattern AT_PATTERN = Pattern.compile("[@]+");
public final static Pattern AND_PATTERN = Pattern.compile(" [aA][Nn][Dd] ");
- public final static Set<String> CATEGORY_CONJUNCTIONS = new HashSet<String>(Arrays.asList("of", "to", "for", "as", "a", "an", "the"));
+ public final static Set<String> CATEGORY_CONJUNCTIONS = new HashSet<String>(
+ Arrays.asList("of", "to", "for", "as", "a", "an", "the"));
public final static Pattern COST_PATTERN = Pattern.compile("^[0-9]{1,5}\\.[0-9]{1,3}$");
public final static Pattern ARTIFACT_LABEL_PATTERN = Pattern.compile("^[a-zA-Z0-9 \\-+]+$");
- public final static Integer ARTIFACT_LABEL_LENGTH = 25;
+ public final static Integer ARTIFACT_LABEL_LENGTH = 255;
+ public final static Pattern ARTIFACT_DISPLAY_NAME_PATTERN = Pattern.compile("^[a-zA-Z0-9][a-zA-Z0-9 &\\.'#=:@_\\-+]+$");
public final static Pattern CATEGORY_LABEL_PATTERN = Pattern.compile("^[a-zA-Z0-9][a-zA-Z0-9 &\\.'#=:@_\\-+]+$");
public final static Integer CATEGORY_LABEL_MIN_LENGTH = 4;
public final static Integer CATEGORY_LABEL_MAX_LENGTH = 25;
@@ -118,6 +126,10 @@ public class ValidationUtils {
public static boolean validateArtifactLabel(String label) {
return ARTIFACT_LABEL_PATTERN.matcher(label).matches();
}
+
+ public static boolean validateArtifactDisplayName(String displayName) {
+ return ARTIFACT_DISPLAY_NAME_PATTERN.matcher(displayName).matches();
+ }
public static boolean validateCategoryDisplayNameFormat(String label) {
boolean res = true;
@@ -171,11 +183,13 @@ public class ValidationUtils {
}
public static boolean validateCategoryDisplayNameLength(String label) {
- return (label != null && label.length() >= CATEGORY_LABEL_MIN_LENGTH && label.length() <= CATEGORY_LABEL_MAX_LENGTH);
+ return (label != null && label.length() >= CATEGORY_LABEL_MIN_LENGTH
+ && label.length() <= CATEGORY_LABEL_MAX_LENGTH);
}
public static boolean validateProductFullNameLength(String fullName) {
- return (fullName != null && fullName.length() >= PRODUCT_FULL_NAME_MIN_LENGTH && fullName.length() <= PRODUCT_FULL_NAME_MAX_LENGTH);
+ return (fullName != null && fullName.length() >= PRODUCT_FULL_NAME_MIN_LENGTH
+ && fullName.length() <= PRODUCT_FULL_NAME_MAX_LENGTH);
}
public static boolean validateArtifactLabelLength(String label) {
@@ -291,7 +305,7 @@ public class ValidationUtils {
}
public static boolean validateStringNotEmpty(String value) {
- if ((value == null) || (value.trim().isEmpty())) {
+ if ((value == null) || (value.isEmpty())) {
return false;
}
return true;
@@ -334,7 +348,7 @@ public class ValidationUtils {
}
- public static String normaliseComponentInstanceName(String name) {
+ public static String normalizeComponentInstanceName(String name) {
String[] split = splitComponentInctanceName(name);
StringBuffer sb = new StringBuffer();
for (String splitElement : split) {
@@ -421,6 +435,7 @@ public class ValidationUtils {
str = UNDERSCORE_PATTERN.matcher(str).replaceAll("");
str = PLUS_PATTERN.matcher(str).replaceAll("");
str = SPACE_PATTERN.matcher(str).replaceAll("");
+ str = DOT_PATTERN.matcher(str).replaceAll("");
str = str.toLowerCase();
return str;
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 75ac208432..242d74a9ca 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
@@ -30,17 +30,17 @@ import java.util.HashMap;
import java.util.Map;
import org.apache.commons.codec.binary.Base64;
-import org.openecomp.sdc.be.config.DistributionEngineConfiguration;
import org.openecomp.sdc.be.config.Configuration.ApplicationL1CacheConfig;
import org.openecomp.sdc.be.config.Configuration.ApplicationL2CacheConfig;
+import org.openecomp.sdc.be.config.Configuration.ArtifactTypeConfig;
import org.openecomp.sdc.be.config.Configuration.BeMonitoringConfig;
-import org.openecomp.sdc.be.config.Configuration.DeploymentArtifactTypeConfig;
import org.openecomp.sdc.be.config.Configuration.EcompPortalConfig;
import org.openecomp.sdc.be.config.Configuration.ElasticSearchConfig;
+import org.openecomp.sdc.be.config.Configuration.ElasticSearchConfig.IndicesTimeFrequencyEntry;
import org.openecomp.sdc.be.config.Configuration.OnboardingConfig;
import org.openecomp.sdc.be.config.Configuration.SwitchoverDetectorConfig;
import org.openecomp.sdc.be.config.Configuration.ToscaValidatorsConfig;
-import org.openecomp.sdc.be.config.Configuration.ElasticSearchConfig.IndicesTimeFrequencyEntry;
+import org.openecomp.sdc.be.config.DistributionEngineConfiguration;
import org.openecomp.sdc.be.config.DistributionEngineConfiguration.ComponentArtifactTypesConfig;
import org.openecomp.sdc.be.config.DistributionEngineConfiguration.CreateTopicConfig;
import org.openecomp.sdc.be.config.DistributionEngineConfiguration.DistributionNotificationTopicConfig;
@@ -102,9 +102,9 @@ public class YamlToObjectConverter {
// resourceDeploymentArtifacts and serviceDeploymentArtifacts
beConfDescription.putMapPropertyType("resourceDeploymentArtifacts", String.class,
- DeploymentArtifactTypeConfig.class);
+ ArtifactTypeConfig.class);
beConfDescription.putMapPropertyType("serviceDeploymentArtifacts", String.class,
- DeploymentArtifactTypeConfig.class);
+ ArtifactTypeConfig.class);
// onboarding
beConfDescription.putListPropertyType("onboarding", OnboardingConfig.class);
@@ -158,7 +158,7 @@ public class YamlToObjectConverter {
config = convert(fullFileName, className);
} catch (Exception e) {
- log.error("Failed to convert yaml file " + configFileName + " to object.", e);
+ log.error("Failed to convert yaml file {} to object.", configFileName,e);
}
return config;
@@ -214,13 +214,13 @@ public class YamlToObjectConverter {
// System.out.println(config.toString());
} catch (Exception e) {
- log.error("Failed to convert yaml file " + fullFileName + " to object.", e);
+ log.error("Failed to convert yaml file {} to object.", fullFileName, e);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
- // TODO Auto-generated catch block
+ log.debug("Failed to close input stream {} ", e.getMessage(), e);
e.printStackTrace();
}
}
@@ -249,7 +249,7 @@ public class YamlToObjectConverter {
try {
in.close();
} catch (IOException e) {
- // TODO Auto-generated catch block
+ log.debug("Failed to close input stream {} ", e.getMessage(), e);
e.printStackTrace();
}
}
@@ -258,11 +258,14 @@ public class YamlToObjectConverter {
return config;
}
+ public boolean isValidYamlEncoded64(byte[] fileContents) {
+ log.trace("Received Base64 data - decoding before validating...");
+ byte[] decodedFileContents = Base64.decodeBase64(fileContents);
+
+ return isValidYaml(decodedFileContents);
+ }
+
public boolean isValidYaml(byte[] fileContents) {
- if (Base64.isBase64(fileContents)) {
- log.trace("Received Base64 data - decoding before validating...");
- fileContents = Base64.decodeBase64(fileContents);
- }
try {
Map<String, Object> mappedToscaTemplate = (Map<String, Object>) defaultYaml
.load(new ByteArrayInputStream(fileContents));
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/ZipUtil.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/ZipUtil.java
index ac25c40cf7..386a66bafe 100644
--- a/common-app-api/src/main/java/org/openecomp/sdc/common/util/ZipUtil.java
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/ZipUtil.java
@@ -121,7 +121,6 @@ public class ZipUtil {
ZipUtil.readZip(zipAsBytes);
} catch (IOException e) {
- // TODO Auto-generated catch block
e.printStackTrace();
}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/exception/ResponseFormat.java b/common-app-api/src/main/java/org/openecomp/sdc/exception/ResponseFormat.java
index 5ccbc25d0e..9058647bdb 100644
--- a/common-app-api/src/main/java/org/openecomp/sdc/exception/ResponseFormat.java
+++ b/common-app-api/src/main/java/org/openecomp/sdc/exception/ResponseFormat.java
@@ -20,6 +20,8 @@
package org.openecomp.sdc.exception;
+import javax.ws.rs.core.Response;
+
/**
* Nested POJOs to express required JSON format of the error
*
@@ -188,4 +190,5 @@ public class ResponseFormat {
public String toString() {
return "ResponseFormat[" + "status=" + status + ", requestErrorWrapper=" + requestErrorWrapper + ']';
}
+
}
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 89953d671e..a8420a4834 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
@@ -48,7 +48,7 @@ public class Configuration extends BasicConfiguration {
private Integer healthCheckSocketTimeoutInMs;
private Integer healthCheckIntervalInSeconds;
-
+
private FeMonitoringConfig systemMonitoring;
private String kibanaHost;
@@ -114,7 +114,7 @@ public class Configuration extends BasicConfiguration {
public void setHealthCheckIntervalInSeconds(Integer healthCheckInterval) {
this.healthCheckIntervalInSeconds = healthCheckInterval;
}
-
+
/**
* be http context
*/
@@ -134,6 +134,7 @@ public class Configuration extends BasicConfiguration {
private List<List<String>> identificationHeaderFields;
private List<List<String>> optionalHeaderFields;
+ private List<String> forwardHeaderFields;
public Date getReleased() {
return released;
@@ -239,6 +240,14 @@ public class Configuration extends BasicConfiguration {
this.optionalHeaderFields = optionalHeaderFields;
}
+ public List<String> getForwardHeaderFields() {
+ return forwardHeaderFields;
+ }
+
+ public void setForwardHeaderFields(List<String> forwardHeaderFields) {
+ this.forwardHeaderFields = forwardHeaderFields;
+ }
+
public String getFeFqdn() {
return feFqdn;
}
diff --git a/common-app-api/src/test/java/org/openecomp/sdc/common/test/CommonUtilsTest.java b/common-app-api/src/test/java/org/openecomp/sdc/common/test/CommonUtilsTest.java
index 1a062576dc..50c2b79d63 100644
--- a/common-app-api/src/test/java/org/openecomp/sdc/common/test/CommonUtilsTest.java
+++ b/common-app-api/src/test/java/org/openecomp/sdc/common/test/CommonUtilsTest.java
@@ -29,9 +29,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import org.apache.commons.lang3.StringEscapeUtils;
-import org.jsoup.Jsoup;
-import org.jsoup.safety.Whitelist;
+import org.junit.Ignore;
import org.junit.Test;
import org.openecomp.sdc.common.api.Constants;
import org.openecomp.sdc.common.util.GeneralUtility;
@@ -40,7 +38,6 @@ import org.openecomp.sdc.common.util.ValidationUtils;
import org.openecomp.sdc.common.util.YamlToObjectConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.w3c.dom.html.HTMLStyleElement;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
@@ -62,7 +59,9 @@ public class CommonUtilsTest {
assertTrue(ValidationUtils.validateComponentNamePattern("1111222"));
assertFalse(ValidationUtils.validateComponentNamePattern("11!11222"));
assertFalse(ValidationUtils.validateComponentNamePattern("111|`1222"));
-
+ assertFalse(ValidationUtils.validateComponentNamePattern("."));
+ assertFalse(ValidationUtils.validateComponentNamePattern(""));
+ assertTrue(ValidationUtils.validateComponentNamePattern("s"));
}
@Test
@@ -104,38 +103,38 @@ public class CommonUtilsTest {
assertFalse(ValidationUtils.validateIconLength("ddddddddddddddddddddddsdfsddddddddddddddddddddddsdfs"));
}
- // 1610OS Support - Because of changes in the validation in the ui this test needs to be fixed
-// @Test
-// public void testValidateProjectCode() {
-//
-// assertTrue(ValidationUtils.validateProjectCode("15555"));
-// assertTrue(ValidationUtils.validateProjectCode("12434501"));
-// assertTrue(ValidationUtils.validateProjectCode("00000"));
-// assertFalse(ValidationUtils.validateProjectCode("something"));
-// assertFalse(ValidationUtils.validateProjectCode("som ething"));
-// assertFalse(ValidationUtils.validateProjectCode("3255 656"));
-// assertFalse(ValidationUtils.validateProjectCode("43535t636"));
-// assertFalse(ValidationUtils.validateProjectCode("098&656"));
-// }
+ @Test
+ public void testValidateProjectCode() {
+
+ assertTrue(ValidationUtils.validateProjectCode("15555"));
+ assertTrue(ValidationUtils.validateProjectCode("12434501"));
+ assertTrue(ValidationUtils.validateProjectCode("00000"));
+ assertTrue(ValidationUtils.validateProjectCode("something"));
+ assertTrue(ValidationUtils.validateProjectCode("som ething"));
+ assertTrue(ValidationUtils.validateProjectCode("3255 656"));
+ assertTrue(ValidationUtils.validateProjectCode("43535t636"));
+ assertFalse(ValidationUtils.validateProjectCode("098&656"));
+ }
@Test
public void testValidateProjectCodeLength() {
+
assertTrue(ValidationUtils.validateProjectCodeLegth("00000"));
assertFalse(ValidationUtils.validateProjectCodeLegth("ddddddddddddddddddddddsdfsddddddddddddddddddddddsdfs"));
+
}
- // 1610OS Support - Because of changes in the validation in the ui this test needs to be fixed
-// @Test
-// public void testValidateContactId() {
-//
-// assertTrue(ValidationUtils.validateContactId("ml7889"));
-// assertTrue(ValidationUtils.validateContactId("Ml7889"));
-// assertTrue(ValidationUtils.validateContactId("ml788r"));
-// assertFalse(ValidationUtils.validateContactId("something"));
-// assertFalse(ValidationUtils.validateContactId("mlk111"));
-// assertFalse(ValidationUtils.validateContactId("12ml89"));
-// assertFalse(ValidationUtils.validateContactId("!!78900"));
-// }
+ @Test
+ public void testValidateContactId() {
+
+ assertTrue(ValidationUtils.validateContactId("ml7889"));
+ assertTrue(ValidationUtils.validateContactId("Ml7889"));
+ assertTrue(ValidationUtils.validateContactId("ml788r"));
+ assertTrue(ValidationUtils.validateContactId("something"));
+ assertTrue(ValidationUtils.validateContactId("mlk111"));
+ assertTrue(ValidationUtils.validateContactId("12ml89"));
+ assertFalse(ValidationUtils.validateContactId("!!78900"));
+ }
@Test
public void testRemoveHtml() {
@@ -242,8 +241,8 @@ public class CommonUtilsTest {
public void validateStringNotEmptyTest() {
assertTrue(ValidationUtils.validateStringNotEmpty("fsdlfsdlk"));
assertFalse(ValidationUtils.validateStringNotEmpty(""));
- assertFalse(ValidationUtils.validateStringNotEmpty(" "));
- assertFalse(ValidationUtils.validateStringNotEmpty(" "));
+ assertFalse(!ValidationUtils.validateStringNotEmpty(" "));
+ assertFalse(!ValidationUtils.validateStringNotEmpty(" "));
}
@Test
@@ -475,13 +474,13 @@ public class CommonUtilsTest {
String str = yaml.dump(parameters);
log.debug(str);
}
-
+
@Test
public void yamlValidTest() {
StringBuffer sb = new StringBuffer();
sb.append("key: \"!@;/?:&=+$,_.~*'()[]\"");
- byte[] payload = sb.toString().getBytes();// Base64.decodeBase64(sb.toString());
+ byte[] payload = sb.toString().getBytes();
YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
@@ -492,7 +491,7 @@ public class CommonUtilsTest {
public void testRemoveOnlyHtmlTags() {
assertEquals("gooboo", HtmlCleaner.stripHtml("<b>goo<b></b></b><b>boo</b>"));
- String str = HtmlCleaner.stripHtml("<esofer><b>goo<b></b><</b><b>boo</b>");
+ /*String str = HtmlCleaner.stripHtml("<esofer><b>goo<b></b><</b><b>boo</b>");*/
String stripHtmlAndEscape = HtmlCleaner.stripHtml("<esofer><b>goo<b></b><</b><b>boo</b>");
assertEquals("<esofer>goo<boo", stripHtmlAndEscape);
diff --git a/common-app-api/src/test/java/org/openecomp/sdc/common/test/TestExternalConfiguration.java b/common-app-api/src/test/java/org/openecomp/sdc/common/test/TestExternalConfiguration.java
index aa3b2e4083..e27e442e84 100644
--- a/common-app-api/src/test/java/org/openecomp/sdc/common/test/TestExternalConfiguration.java
+++ b/common-app-api/src/test/java/org/openecomp/sdc/common/test/TestExternalConfiguration.java
@@ -67,23 +67,26 @@ public class TestExternalConfiguration {
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() {
- ConfigurationListener configurationListener = new ConfigurationListener(TestConfiguration.class, new FileChangeCallback() {
+ ConfigurationListener configurationListener = new ConfigurationListener(TestConfiguration.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);
+ }
- });
+ });
- TestConfiguration testConfiguration = configurationSource.getAndWatchConfiguration(TestConfiguration.class, configurationListener);
+ TestConfiguration testConfiguration = configurationSource.getAndWatchConfiguration(TestConfiguration.class,
+ configurationListener);
assertTrue(testConfiguration != null);
log.debug("{}", testConfiguration);
@@ -96,16 +99,18 @@ public class TestExternalConfiguration {
@Test
public void testNotExistConfigurationFile() {
- ConfigurationListener configurationListener = new ConfigurationListener(TestConfiguration.class, new FileChangeCallback() {
+ ConfigurationListener configurationListener = new ConfigurationListener(TestConfiguration.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);
+ }
- });
+ });
- TestNotExistConfiguration testConfiguration = configurationSource.getAndWatchConfiguration(TestNotExistConfiguration.class, configurationListener);
+ TestNotExistConfiguration testConfiguration = configurationSource
+ .getAndWatchConfiguration(TestNotExistConfiguration.class, configurationListener);
assertTrue(testConfiguration == null);
@@ -114,21 +119,23 @@ public class TestExternalConfiguration {
@Test
public void testUpdateConfigurationFile() {
- ConfigurationListener configurationListener = new ConfigurationListener(TestConfiguration.class, new FileChangeCallback() {
+ ConfigurationListener configurationListener = new ConfigurationListener(TestConfiguration.class,
+ new FileChangeCallback() {
- public void reconfigure(BasicConfiguration obj) {
- // TODO Auto-generated method stub
- log.debug("In reconfigure of {}", obj);
- // assertEquals(((TestConfiguration)obj).getBeSslPort(),
- // 8444);
+ public void reconfigure(BasicConfiguration obj) {
+ // TODO Auto-generated method stub
+ log.debug("In reconfigure of {}", obj);
+ // assertEquals(((TestConfiguration)obj).getBeSslPort(),
+ // 8444);
- // assertTrue(((TestConfiguration)obj).getBeSslPort() ==
- // 8444);
- }
+ // assertTrue(((TestConfiguration)obj).getBeSslPort() ==
+ // 8444);
+ }
- });
+ });
- TestConfiguration testConfiguration = configurationSource.getAndWatchConfiguration(TestConfiguration.class, configurationListener);
+ TestConfiguration testConfiguration = configurationSource.getAndWatchConfiguration(TestConfiguration.class,
+ configurationListener);
assertTrue(testConfiguration != null);
log.debug("{}", testConfiguration);
@@ -141,13 +148,13 @@ public class TestExternalConfiguration {
}
private void updateFileContent() {
- File file = new File(ExternalConfiguration.getConfigDir() + File.separator + ExternalConfiguration.getAppName() + File.separator + "test-configuration.yaml");
+ File file = new File(ExternalConfiguration.getConfigDir() + File.separator + ExternalConfiguration.getAppName()
+ + File.separator + "test-configuration.yaml");
replaceFile(file);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
- // TODO Auto-generated catch block
e.printStackTrace();
}
}
@@ -181,7 +188,6 @@ public class TestExternalConfiguration {
try {
br.close();
} catch (IOException e) {
- // TODO Auto-generated catch block
e.printStackTrace();
}
}
@@ -189,7 +195,6 @@ public class TestExternalConfiguration {
try {
fr.close();
} catch (IOException e) {
- // TODO Auto-generated catch block
e.printStackTrace();
}
}
@@ -197,7 +202,6 @@ public class TestExternalConfiguration {
try {
out.close();
} catch (IOException e) {
- // TODO Auto-generated catch block
e.printStackTrace();
}
}
@@ -205,7 +209,6 @@ public class TestExternalConfiguration {
try {
fw.close();
} catch (IOException e) {
- // TODO Auto-generated catch block
e.printStackTrace();
}
}
@@ -215,16 +218,18 @@ public class TestExternalConfiguration {
@Test
public void testReadDistributionEngineConfigurationFile() {
- ConfigurationListener configurationListener = new ConfigurationListener(TestConfiguration.class, new FileChangeCallback() {
+ ConfigurationListener configurationListener = new ConfigurationListener(TestConfiguration.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);
+ }
- });
+ });
- DistributionEngineConfiguration deConfiguration = configurationSource.getAndWatchConfiguration(DistributionEngineConfiguration.class, configurationListener);
+ DistributionEngineConfiguration deConfiguration = configurationSource
+ .getAndWatchConfiguration(DistributionEngineConfiguration.class, configurationListener);
assertTrue(deConfiguration != null);
log.debug("{}", deConfiguration);
diff --git a/common-app-api/src/test/java/org/openecomp/sdc/common/test/YamlTest.java b/common-app-api/src/test/java/org/openecomp/sdc/common/test/YamlTest.java
index 340bca9f1d..d45a61cebb 100644
--- a/common-app-api/src/test/java/org/openecomp/sdc/common/test/YamlTest.java
+++ b/common-app-api/src/test/java/org/openecomp/sdc/common/test/YamlTest.java
@@ -51,11 +51,11 @@ public class YamlTest {
@Test
public void testValidYamlBase64() {
- assertTrue(yamlToObjectConverter.isValidYaml(Base64.encodeBase64(validYaml.getBytes())));
+ assertTrue(yamlToObjectConverter.isValidYamlEncoded64(Base64.encodeBase64(validYaml.getBytes())));
}
@Test
public void testInvalidYamlBase64() {
- assertFalse(yamlToObjectConverter.isValidYaml(Base64.encodeBase64(invalidYaml.getBytes())));
+ assertFalse(yamlToObjectConverter.isValidYamlEncoded64(Base64.encodeBase64(invalidYaml.getBytes())));
}
}
diff --git a/common-be/pom.xml b/common-be/pom.xml
index 75481c354f..cafe1485d2 100644
--- a/common-be/pom.xml
+++ b/common-be/pom.xml
@@ -4,185 +4,49 @@
<groupId>org.openecomp.sdc.be</groupId>
<artifactId>common-be</artifactId>
-
+
<parent>
<groupId>org.openecomp.sdc</groupId>
<artifactId>sdc-main</artifactId>
<version>1.1.0-SNAPSHOT</version>
</parent>
-
- <properties>
- <aspectj.version>1.7.4</aspectj.version>
- <hibernate-validator.version>5.3.4.Final</hibernate-validator.version>
- <groovy.version>2.3.5</groovy.version>
- <lucene.version>4.10.2</lucene.version>
- <mockito.version>1.9.0</mockito.version>
- <regex.version>3.0.3</regex.version>
- <codehaus.jackson.core>1.9.2</codehaus.jackson.core>
- </properties>
-
-
<dependencies>
-
- <dependency>
- <groupId>org.mockito</groupId>
- <artifactId>mockito-all</artifactId>
- <version>1.10.19</version>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>org.testng</groupId>
- <artifactId>testng</artifactId>
- <version>6.9.10</version>
- <scope>test</scope>
- </dependency>
-
- <dependency>
- <groupId>org.apache.commons</groupId>
- <artifactId>commons-lang3</artifactId>
- <version>${lang3.version}</version>
- <scope>provided</scope>
- </dependency>
-
- <!-- yaml to object converter -->
- <dependency>
- <groupId>org.yaml</groupId>
- <artifactId>snakeyaml</artifactId>
- <version>1.14</version>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>com.google.code.gson</groupId>
- <artifactId>gson</artifactId>
- <version>2.3.1</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>commons-logging</groupId>
- <artifactId>commons-logging</artifactId>
- <version>1.2.1-SNAPSHOT</version>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>commons-codec</groupId>
- <artifactId>commons-codec</artifactId>
- <version>2.0-SNAPSHOT</version>
- <scope>provided</scope>
- </dependency>
+
<!-- Common of SD&C -->
<dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-core</artifactId>
- <version>${spring.version}</version>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-beans</artifactId>
- <version>${spring.version}</version>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-context</artifactId>
- <version>${spring.version}</version>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-context-support</artifactId>
- <version>${spring.version}</version>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-messaging</artifactId>
- <version>${spring.version}</version>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-web</artifactId>
- <version>${spring.version}</version>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-webmvc</artifactId>
- <version>${spring.version}</version>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-aop</artifactId>
- <version>${spring.version}</version>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-aspects</artifactId>
- <version>${spring.version}</version>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-test</artifactId>
- <version>${spring.version}</version>
- <scope>test</scope>
- </dependency>
-
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-expression</artifactId>
- <version>${spring.version}</version>
- <scope>test</scope>
- </dependency>
-
- <dependency>
<groupId>org.openecomp.sdc</groupId>
<artifactId>common-app-api</artifactId>
- <version>${common-app-api.version}</version>
+ <version>${project.version}</version>
<scope>provided</scope>
</dependency>
+
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
- <version>${logback.version}</version>
+ <version>${logback.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
- <version>${logback.version}</version>
+ <version>${logback.version}</version>
<scope>provided</scope>
</dependency>
-
+
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
- <version>1.7.10</version>
+ <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>
+ <artifactId>jackson-core-asl</artifactId>
+ <version>${codehaus.jackson.core}</version>
+ <scope>provided</scope>
</dependency>
<dependency>
@@ -191,17 +55,23 @@
<version>${guava.version}</version>
<scope>provided</scope>
</dependency>
-
- <!-- TEST -->
+ <dependency>
+ <groupId>org.functionaljava</groupId>
+ <artifactId>functionaljava</artifactId>
+ <version>${functionaljava.version}</version>
+ <scope>provided</scope>
+ </dependency>
+
+ <!-- TEST -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
- <version>4.12</version>
+ <version>${junit.version}</version>
<scope>test</scope>
</dependency>
-
</dependencies>
+
<build>
<pluginManagement>
<plugins>
@@ -243,4 +113,28 @@
</plugins>
</pluginManagement>
</build>
+
+ <profiles>
+ <profile>
+ <id>Fortify</id>
+ <activation>
+ <activeByDefault>false</activeByDefault>
+ </activation>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>com.fortify.ps.maven.plugin</groupId>
+ <artifactId>sca-maven-plugin</artifactId>
+ <version>4.30</version>
+ <configuration>
+ <source>1.8</source>
+ <buildId>${project.parent.artifactId}</buildId>
+ <toplevelArtifactId>${project.parent.artifactId}</toplevelArtifactId>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+ </profile>
+ </profiles>
</project>
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/category/CategoryDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/category/CategoryDataDefinition.java
index 754721a5a6..943c1191e5 100644
--- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/category/CategoryDataDefinition.java
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/category/CategoryDataDefinition.java
@@ -23,7 +23,9 @@ package org.openecomp.sdc.be.datatypes.category;
import java.io.Serializable;
import java.util.List;
-public class CategoryDataDefinition implements Serializable {
+import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+
+public class CategoryDataDefinition extends ToscaDataDefinition implements Serializable {
/**
*
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/category/GroupingDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/category/GroupingDataDefinition.java
index 87924e99d4..1483a0aa1b 100644
--- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/category/GroupingDataDefinition.java
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/category/GroupingDataDefinition.java
@@ -22,7 +22,9 @@ package org.openecomp.sdc.be.datatypes.category;
import java.io.Serializable;
-public class GroupingDataDefinition implements Serializable {
+import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+
+public class GroupingDataDefinition extends ToscaDataDefinition implements Serializable {
/**
*
*/
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/category/SubCategoryDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/category/SubCategoryDataDefinition.java
index 2774fe4e40..21d3abaf4b 100644
--- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/category/SubCategoryDataDefinition.java
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/category/SubCategoryDataDefinition.java
@@ -23,7 +23,9 @@ package org.openecomp.sdc.be.datatypes.category;
import java.io.Serializable;
import java.util.List;
-public class SubCategoryDataDefinition implements Serializable {
+import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+
+public class SubCategoryDataDefinition extends ToscaDataDefinition implements Serializable {
/**
*
*/
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 4af7a279a3..102c7dde6e 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
@@ -26,7 +26,10 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
-public abstract class ComponentMetadataDataDefinition implements Serializable {
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+
+public abstract class ComponentMetadataDataDefinition extends ToscaDataDefinition implements Serializable {
/**
*
@@ -51,6 +54,8 @@ public abstract class ComponentMetadataDataDefinition implements Serializable {
private List<String> tags;
+ private String conformanceLevel;
+
private String icon;
private String UUID;
@@ -75,6 +80,69 @@ public abstract class ComponentMetadataDataDefinition implements Serializable {
private String invariantUUID;
+ protected ComponentTypeEnum componentType;
+
+ // USER
+ private String creatorUserId;
+
+ private String creatorFullName;
+
+ private String lastUpdaterUserId;
+
+ private String lastUpdaterFullName;
+
+ public Boolean getIsHighestVersion() {
+ return isHighestVersion;
+ }
+
+ public void setIsHighestVersion(Boolean isHighestVersion) {
+ this.isHighestVersion = isHighestVersion;
+ }
+
+ public ComponentTypeEnum getComponentType() {
+ return componentType;
+ }
+
+ public void setComponentType(ComponentTypeEnum componentType) {
+ this.componentType = componentType;
+ }
+
+ 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 Boolean getIsDeleted() {
+ return isDeleted;
+ }
+
public ComponentMetadataDataDefinition() {
}
@@ -101,6 +169,7 @@ public abstract class ComponentMetadataDataDefinition implements Serializable {
this.csarVersion = other.csarVersion;
this.importedToscaChecksum = other.getImportedToscaChecksum();
this.invariantUUID = other.getInvariantUUID();
+
}
public String getUniqueId() {
@@ -270,16 +339,27 @@ public abstract class ComponentMetadataDataDefinition implements Serializable {
public void setImportedToscaChecksum(String importedToscaChecksum) {
this.importedToscaChecksum = importedToscaChecksum;
}
+
+ public String getConformanceLevel() {
+ return conformanceLevel;
+ }
+
+ public void setConformanceLevel(String conformanceLevel) {
+ this.conformanceLevel = conformanceLevel;
+ }
@Override
public String toString() {
return "ComponentMetadataDataDefinition [uniqueId=" + uniqueId + ", name=" + name + ", version=" + version
+ ", isHighestVersion=" + isHighestVersion + ", creationDate=" + creationDate + ", lastUpdateDate="
- + lastUpdateDate + ", description=" + description + ", state=" + state + ", tags=" + tags + ", icon="
- + icon + ", UUID=" + UUID + ", normalizedName=" + normalizedName + ", systemName=" + systemName
- + ", contactId=" + contactId + ", allVersions=" + allVersions + ", isDeleted=" + isDeleted
- + ", projectCode=" + projectCode + ", csarUUID=" + csarUUID + ", csarversion=" + csarVersion
- + ", importedToscaChecksum=" + importedToscaChecksum + ", invariantUUID=" + invariantUUID + "]";
+ + lastUpdateDate + ", description=" + description + ", state=" + state + ", tags=" + tags
+ + ", conformanceLevel=" + conformanceLevel + ", icon=" + icon + ", UUID=" + UUID + ", normalizedName="
+ + normalizedName + ", systemName=" + systemName + ", contactId=" + contactId + ", allVersions="
+ + allVersions + ", isDeleted=" + isDeleted + ", projectCode=" + projectCode + ", csarUUID=" + csarUUID
+ + ", csarVersion=" + csarVersion + ", importedToscaChecksum=" + importedToscaChecksum
+ + ", invariantUUID=" + invariantUUID + ", componentType=" + componentType + ", creatorUserId="
+ + creatorUserId + ", creatorFullName=" + creatorFullName + ", lastUpdaterUserId=" + lastUpdaterUserId
+ + ", lastUpdaterFullName=" + lastUpdaterFullName + "]";
}
@Override
@@ -288,25 +368,31 @@ public abstract class ComponentMetadataDataDefinition implements Serializable {
int result = 1;
result = prime * result + ((UUID == null) ? 0 : UUID.hashCode());
result = prime * result + ((allVersions == null) ? 0 : allVersions.hashCode());
+ result = prime * result + ((componentType == null) ? 0 : componentType.hashCode());
+ result = prime * result + ((conformanceLevel == null) ? 0 : conformanceLevel.hashCode());
result = prime * result + ((contactId == null) ? 0 : contactId.hashCode());
result = prime * result + ((creationDate == null) ? 0 : creationDate.hashCode());
+ result = prime * result + ((creatorFullName == null) ? 0 : creatorFullName.hashCode());
+ result = prime * result + ((creatorUserId == null) ? 0 : creatorUserId.hashCode());
+ result = prime * result + ((csarUUID == null) ? 0 : csarUUID.hashCode());
+ result = prime * result + ((csarVersion == null) ? 0 : csarVersion.hashCode());
result = prime * result + ((description == null) ? 0 : description.hashCode());
result = prime * result + ((icon == null) ? 0 : icon.hashCode());
+ result = prime * result + ((importedToscaChecksum == null) ? 0 : importedToscaChecksum.hashCode());
+ result = prime * result + ((invariantUUID == null) ? 0 : invariantUUID.hashCode());
result = prime * result + ((isDeleted == null) ? 0 : isDeleted.hashCode());
result = prime * result + ((isHighestVersion == null) ? 0 : isHighestVersion.hashCode());
result = prime * result + ((lastUpdateDate == null) ? 0 : lastUpdateDate.hashCode());
+ result = prime * result + ((lastUpdaterFullName == null) ? 0 : lastUpdaterFullName.hashCode());
+ result = prime * result + ((lastUpdaterUserId == null) ? 0 : lastUpdaterUserId.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((normalizedName == null) ? 0 : normalizedName.hashCode());
+ result = prime * result + ((projectCode == null) ? 0 : projectCode.hashCode());
result = prime * result + ((state == null) ? 0 : state.hashCode());
result = prime * result + ((systemName == null) ? 0 : systemName.hashCode());
result = prime * result + ((tags == null) ? 0 : tags.hashCode());
result = prime * result + ((uniqueId == null) ? 0 : uniqueId.hashCode());
result = prime * result + ((version == null) ? 0 : version.hashCode());
- result = prime * result + ((projectCode == null) ? 0 : projectCode.hashCode());
- result = prime * result + ((csarUUID == null) ? 0 : csarUUID.hashCode());
- result = prime * result + ((csarVersion == null) ? 0 : csarVersion.hashCode());
- result = prime * result + ((importedToscaChecksum == null) ? 0 : importedToscaChecksum.hashCode());
- result = prime * result + ((invariantUUID == null) ? 0 : invariantUUID.hashCode());
return result;
}
@@ -329,6 +415,13 @@ public abstract class ComponentMetadataDataDefinition implements Serializable {
return false;
} else if (!allVersions.equals(other.allVersions))
return false;
+ if (componentType != other.componentType)
+ return false;
+ if (conformanceLevel == null) {
+ if (other.conformanceLevel != null)
+ return false;
+ } else if (!conformanceLevel.equals(other.conformanceLevel))
+ return false;
if (contactId == null) {
if (other.contactId != null)
return false;
@@ -339,6 +432,26 @@ public abstract class ComponentMetadataDataDefinition implements Serializable {
return false;
} else if (!creationDate.equals(other.creationDate))
return false;
+ if (creatorFullName == null) {
+ if (other.creatorFullName != null)
+ return false;
+ } else if (!creatorFullName.equals(other.creatorFullName))
+ return false;
+ if (creatorUserId == null) {
+ if (other.creatorUserId != null)
+ return false;
+ } else if (!creatorUserId.equals(other.creatorUserId))
+ return false;
+ if (csarUUID == null) {
+ if (other.csarUUID != null)
+ return false;
+ } else if (!csarUUID.equals(other.csarUUID))
+ return false;
+ if (csarVersion == null) {
+ if (other.csarVersion != null)
+ return false;
+ } else if (!csarVersion.equals(other.csarVersion))
+ return false;
if (description == null) {
if (other.description != null)
return false;
@@ -349,6 +462,16 @@ public abstract class ComponentMetadataDataDefinition implements Serializable {
return false;
} else if (!icon.equals(other.icon))
return false;
+ if (importedToscaChecksum == null) {
+ if (other.importedToscaChecksum != null)
+ return false;
+ } else if (!importedToscaChecksum.equals(other.importedToscaChecksum))
+ return false;
+ if (invariantUUID == null) {
+ if (other.invariantUUID != null)
+ return false;
+ } else if (!invariantUUID.equals(other.invariantUUID))
+ return false;
if (isDeleted == null) {
if (other.isDeleted != null)
return false;
@@ -364,6 +487,16 @@ public abstract class ComponentMetadataDataDefinition implements Serializable {
return false;
} else if (!lastUpdateDate.equals(other.lastUpdateDate))
return false;
+ if (lastUpdaterFullName == null) {
+ if (other.lastUpdaterFullName != null)
+ return false;
+ } else if (!lastUpdaterFullName.equals(other.lastUpdaterFullName))
+ return false;
+ if (lastUpdaterUserId == null) {
+ if (other.lastUpdaterUserId != null)
+ return false;
+ } else if (!lastUpdaterUserId.equals(other.lastUpdaterUserId))
+ return false;
if (name == null) {
if (other.name != null)
return false;
@@ -374,6 +507,11 @@ public abstract class ComponentMetadataDataDefinition implements Serializable {
return false;
} else if (!normalizedName.equals(other.normalizedName))
return false;
+ if (projectCode == null) {
+ if (other.projectCode != null)
+ return false;
+ } else if (!projectCode.equals(other.projectCode))
+ return false;
if (state == null) {
if (other.state != null)
return false;
@@ -399,31 +537,7 @@ public abstract class ComponentMetadataDataDefinition implements Serializable {
return false;
} else if (!version.equals(other.version))
return false;
- if (projectCode == null) {
- if (other.projectCode != null)
- return false;
- } else if (!projectCode.equals(other.projectCode))
- return false;
- if (csarUUID == null) {
- if (other.csarUUID != null)
- return false;
- } else if (!csarUUID.equals(other.csarUUID))
- return false;
- if (csarVersion == null) {
- if (other.csarVersion != null)
- return false;
- } else if (!csarVersion.equals(other.csarVersion))
- return false;
- if (importedToscaChecksum == null) {
- if (other.importedToscaChecksum != null)
- return false;
- } else if (!importedToscaChecksum.equals(other.importedToscaChecksum))
- return false;
- if (invariantUUID == null) {
- if (other.invariantUUID != null)
- return false;
- } else if (!invariantUUID.equals(other.invariantUUID))
- return false;
return true;
}
+
}
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 2eb5e23352..7b112ce129 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
@@ -23,6 +23,7 @@ package org.openecomp.sdc.be.datatypes.components;
import java.io.Serializable;
import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
public class ResourceMetadataDataDefinition extends ComponentMetadataDataDefinition implements Serializable {
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 2ebbadcdaf..4f3486e457 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
@@ -22,15 +22,22 @@ package org.openecomp.sdc.be.datatypes.components;
import java.io.Serializable;
+import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+
public class ServiceMetadataDataDefinition extends ComponentMetadataDataDefinition implements Serializable {
/**
*
*/
private static final long serialVersionUID = -7661001892509435120L;
+ public static final String EMPTY_STR = "";
private String distributionStatus;
+ private Boolean ecompGeneratedNaming = true;
+
+ private String namingPolicy = EMPTY_STR;
+
public ServiceMetadataDataDefinition() {
super();
}
@@ -47,10 +54,27 @@ public class ServiceMetadataDataDefinition extends ComponentMetadataDataDefiniti
this.distributionStatus = distributionStatus;
}
+ public Boolean isEcompGeneratedNaming() {
+ return ecompGeneratedNaming;
+ }
+
+ public void setEcompGeneratedNaming(Boolean ecompGeneratedNaming) {
+ this.ecompGeneratedNaming = ecompGeneratedNaming;
+ }
+
+ public String getNamingPolicy() {
+ return namingPolicy;
+ }
+
+ public void setNamingPolicy(String namingPolicy) {
+ this.namingPolicy = namingPolicy;
+ }
+
@Override
public String toString() {
- return "ServiceMetadataDataDefinition [ distributionStatus=" + distributionStatus + ", parent="
- + super.toString() + "]";
+ return "ServiceMetadataDataDefinition [ distributionStatus=" + distributionStatus
+ + ", ecompGeneratedNaming=" + ecompGeneratedNaming + ", namingPolicy=" + namingPolicy
+ + ", parent=" + super.toString() + "]";
}
@Override
@@ -58,6 +82,8 @@ public class ServiceMetadataDataDefinition extends ComponentMetadataDataDefiniti
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((distributionStatus == null) ? 0 : distributionStatus.hashCode());
+ result = prime * result + ((ecompGeneratedNaming == null) ? 0 : ecompGeneratedNaming.hashCode());
+ result = prime * result + ((namingPolicy == null) ? 0 : namingPolicy.hashCode());
return result;
}
@@ -81,6 +107,16 @@ public class ServiceMetadataDataDefinition extends ComponentMetadataDataDefiniti
return false;
} else if (!distributionStatus.equals(other.distributionStatus))
return false;
+ if (ecompGeneratedNaming == null) {
+ if (other.ecompGeneratedNaming != null)
+ return false;
+ } else if (!ecompGeneratedNaming.equals(other.ecompGeneratedNaming))
+ return false;
+ if (namingPolicy == null) {
+ if (other.namingPolicy != null)
+ return false;
+ } else if (!namingPolicy.equals(other.namingPolicy))
+ return false;
return super.equals(obj);
}
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 4c062e3fab..f618458edf 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
@@ -21,8 +21,11 @@
package org.openecomp.sdc.be.datatypes.elements;
import java.io.Serializable;
+import java.util.List;
-public class AdditionalInfoParameterDataDefinition implements Serializable {
+import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+
+public class AdditionalInfoParameterDataDefinition extends ToscaDataDefinition implements Serializable {
/**
*
@@ -37,6 +40,8 @@ public class AdditionalInfoParameterDataDefinition implements Serializable {
private Integer lastCreatedCounter = 0;
+ private List<AdditionalInfoParameterInfo> parameters;
+
public AdditionalInfoParameterDataDefinition() {
}
@@ -46,6 +51,7 @@ public class AdditionalInfoParameterDataDefinition implements Serializable {
this.creationTime = p.creationTime;
this.modificationTime = p.modificationTime;
this.lastCreatedCounter = p.lastCreatedCounter;
+ this.parameters = p.parameters;
}
public String getUniqueId() {
@@ -79,7 +85,13 @@ public class AdditionalInfoParameterDataDefinition implements Serializable {
public void setLastCreatedCounter(Integer lastCreatedCounter) {
this.lastCreatedCounter = lastCreatedCounter;
}
+ public List<AdditionalInfoParameterInfo> getParameters() {
+ return parameters;
+ }
+ public void setParameters(List<AdditionalInfoParameterInfo> parameters) {
+ this.parameters = parameters;
+ }
@Override
public String toString() {
return "AdditionalInfoParameterDataDefinition [uniqueId=" + uniqueId + ", creationTime=" + creationTime
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/AdditionalInfoParameterInfo.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/AdditionalInfoParameterInfo.java
index 674681081c..cdfe75d156 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/AdditionalInfoParameterInfo.java
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/AdditionalInfoParameterInfo.java
@@ -18,11 +18,13 @@
* ============LICENSE_END=========================================================
*/
-package org.openecomp.sdc.be.model;
+package org.openecomp.sdc.be.datatypes.elements;
import java.io.Serializable;
-public class AdditionalInfoParameterInfo implements Serializable {
+import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+
+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 4baf09ea68..49c13a09cd 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,397 +20,387 @@
package org.openecomp.sdc.be.datatypes.elements;
+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 java.io.Serializable;
-
-public class ArtifactDataDefinition implements Serializable {
+//import com.google.gson.reflect.TypeToken;
+public class ArtifactDataDefinition extends ToscaDataDefinition implements Serializable {
/**
*
*/
private static final long serialVersionUID = -1691343090754083941L;
- /**
- * The unique id of the artifact
- */
- private String uniqueId;
-
- /**
- * Tosca logical name
- */
- // private String logicalName;
-
- /** This attribute specifies the type of this artifact. */
- private String artifactType;
-
- /** Specifies the reference of the artifact. uri to the SWIFT */
- private String artifactRef;
-
- /** Specifies the display name of the artifact. */
- private String artifactName;
-
- /**
- * Non TOSCA compliant property
- */
- private String artifactRepository;
-
- /**
- * Checksum value of the uploaded artifact file retrieved from "Content-MD5"?
- * header of the HTTP POST/PUT request. Should be updated each time when the
- * artifact file is updated.
- */
- private String artifactChecksum;
-
- /**
- * artifact creator
- */
- private String userIdCreator;
-
- /**
- * USER ID of the last resource (artifact) updater
- */
- private String userIdLastUpdater;
-
- /**
- * Full name of artifact creator
- */
- private String creatorFullName;
-
- /**
- * Full name of the last resource (artifact) updater
- */
- private String updaterFullName;
-
- /**
- * Timestamp of the resource (artifact) creation
- */
- private Long creationDate;
-
- /**
- * Timestamp of the last resource (artifact) creation
- */
- private Long lastUpdateDate;
-
- /**
- * Id of artifact data in ES
- */
- private String esId;
-
- /**
- * Logical artifact name. Used by TOSCA
- */
- private String artifactLabel;
-
- private String artifactCreator;
-
- private String description;
-
- private Boolean mandatory = Boolean.FALSE;
-
- private String artifactDisplayName;
-
- private String apiUrl;
+
- private Boolean serviceApi = Boolean.FALSE;
+ public ArtifactDataDefinition() {
+ super();
+ setArtifactVersion("0");
+ }
+
+ public ArtifactDataDefinition(Map<String, Object> art) {
+ super(art);
+ setArtifactVersion("0");
+ }
- /**
- * Flag that set to TRUE if generated from AI&I Artifact generator to
- * distinguish between manually uploaded and generated artifacts
- */
- private Boolean generated = Boolean.FALSE;
- private ArtifactGroupTypeEnum artifactGroupType;
- private Integer timeout;
- private String artifactVersion;
- private String artifactUUID;
- private Long payloadUpdateDate;
- private Long heatParamsUpdateDate;
-
- private List<String> requiredArtifacts;
- public ArtifactDataDefinition() {
- artifactVersion = "0";
- }
-
- public ArtifactDataDefinition(ArtifactDataDefinition a) {
- this.uniqueId = a.uniqueId;
- this.artifactType = a.artifactType;
- this.artifactRef = a.artifactRef;
- this.artifactName = a.artifactName;
- this.artifactRepository = a.artifactRepository;
- this.artifactChecksum = a.artifactChecksum;
- this.userIdCreator = a.userIdCreator;
- this.userIdLastUpdater = a.userIdLastUpdater;
- this.creatorFullName = a.creatorFullName;
- this.updaterFullName = a.updaterFullName;
- this.creationDate = a.creationDate;
- this.lastUpdateDate = a.lastUpdateDate;
- this.description = a.description;
- this.esId = a.esId;
- this.artifactLabel = a.artifactLabel;
- this.artifactCreator = a.artifactCreator;
- this.mandatory = a.mandatory;
- this.artifactDisplayName = a.artifactDisplayName;
- this.apiUrl = a.apiUrl;
- this.serviceApi = a.serviceApi;
- this.artifactGroupType = a.artifactGroupType;
- this.timeout = a.timeout;
- this.artifactVersion = a.artifactVersion;
- this.artifactUUID = a.artifactUUID;
- this.payloadUpdateDate = a.payloadUpdateDate;
- this.heatParamsUpdateDate = a.heatParamsUpdateDate;
+ public ArtifactDataDefinition(ArtifactDataDefinition a ) {
+ super();
+ this.setUniqueId(a.getUniqueId());
+ this.setArtifactType(a.getArtifactType());
+ this.setArtifactRef( a.getArtifactRef());
+ this.setArtifactName( a.getArtifactName());
+ this.setArtifactRepository( a.getArtifactRepository());
+ this.setArtifactChecksum( a.getArtifactChecksum());
+ this.setUserIdCreator( a.getUserIdCreator());
+ this.setUserIdLastUpdater( a.getUserIdLastUpdater());
+ this.setCreatorFullName( a.getCreatorFullName());
+ this.setUpdaterFullName( a.getUpdaterFullName());
+ this.setCreationDate ( a.getCreationDate());
+ this.setLastUpdateDate ( a.getLastUpdateDate());
+ this.setDescription ( a.getDescription());
+ this.setEsId ( a.getEsId());
+ this.setArtifactLabel( a.getArtifactLabel());
+ this.setArtifactCreator( a.getArtifactCreator());
+ this.setMandatory ( a.getMandatory());
+ this.setArtifactDisplayName( a.getArtifactDisplayName());
+ this.setApiUrl( a.getApiUrl());
+ this.setServiceApi ( a.getServiceApi());
+ this.setArtifactGroupType ( a.getArtifactGroupType());
+ this.setTimeout ( a.getTimeout());
+ this.setArtifactVersion( a.getArtifactVersion());
+ this.setArtifactUUID ( a.getArtifactUUID());
+ this.setPayloadUpdateDate ( a.getPayloadUpdateDate());
+ this.setHeatParamsUpdateDate ( a.getHeatParamsUpdateDate());
this.setGenerated(a.getGenerated());
- if (a.requiredArtifacts != null)
- this.requiredArtifacts = new ArrayList<>(a.getRequiredArtifacts());
+ this.setDuplicated(a.getDuplicated());
+ if (a.getRequiredArtifacts() != null)
+ this.setRequiredArtifacts(new ArrayList<>(a.getRequiredArtifacts()));
+ if (a.getHeatParameters() != null)
+ this.setHeatParameters(new ArrayList<>(a.getHeatParameters()));
+ this.setGeneratedFromId( a.getGeneratedFromId());
+
+
}
public String getArtifactName() {
- return artifactName != null ? artifactName : artifactRef;
+ return (String) getToscaPresentationValue(JsonPresentationFields.NAME);
+
}
public String getArtifactType() {
- return artifactType;
+ return (String) getToscaPresentationValue(JsonPresentationFields.ARTIFACT_TYPE);
}
- public void setArtifactType(String artifactType) {
- this.artifactType = artifactType;
+ public void setArtifactType(String artifactType) {
+ setToscaPresentationValue(JsonPresentationFields.ARTIFACT_TYPE, artifactType);
+
}
- public String getArtifactRef() {
- return artifactRef;
+ public String getArtifactRef() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.ARTIFACT_REF);
+
}
public void setArtifactRef(String artifactRef) {
- this.artifactRef = artifactRef;
+ setToscaPresentationValue(JsonPresentationFields.ARTIFACT_REF, artifactRef);
}
- public String getArtifactRepository() {
- return artifactRepository;
+ public String getArtifactRepository() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.ARTIFACT_REPOSITORY);
+
}
public void setArtifactRepository(String artifactRepository) {
- this.artifactRepository = artifactRepository;
+ setToscaPresentationValue(JsonPresentationFields.ARTIFACT_REPOSITORY, artifactRepository);
}
public void setArtifactName(String artifactName) {
- this.artifactName = artifactName;
+ setToscaPresentationValue(JsonPresentationFields.NAME, artifactName);
+
}
- public String getArtifactChecksum() {
- return artifactChecksum;
+ public String getArtifactChecksum() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.ARTIFACT_CHECKSUM);
}
public void setArtifactChecksum(String artifactChecksum) {
- this.artifactChecksum = artifactChecksum;
+ setToscaPresentationValue(JsonPresentationFields.ARTIFACT_CHECKSUM, artifactChecksum);
}
public String getUserIdCreator() {
- return userIdCreator;
+
+ return (String) getToscaPresentationValue(JsonPresentationFields.USER_ID_CREATOR);
}
public void setUserIdCreator(String userIdCreator) {
- this.userIdCreator = userIdCreator;
+ setToscaPresentationValue(JsonPresentationFields.USER_ID_CREATOR, userIdCreator);
}
public String getUserIdLastUpdater() {
- return userIdLastUpdater;
+ return (String) getToscaPresentationValue(JsonPresentationFields.USER_ID_LAST_UPDATER);
}
public void setUserIdLastUpdater(String userIdLastUpdater) {
- this.userIdLastUpdater = userIdLastUpdater;
+ setToscaPresentationValue(JsonPresentationFields.USER_ID_LAST_UPDATER, userIdLastUpdater);
}
public String getCreatorFullName() {
- return creatorFullName;
+ return (String) getToscaPresentationValue(JsonPresentationFields.CREATOR_FULL_NAME);
}
public void setCreatorFullName(String creatorFullName) {
- this.creatorFullName = creatorFullName;
+ setToscaPresentationValue(JsonPresentationFields.CREATOR_FULL_NAME, creatorFullName);
}
- public String getUpdaterFullName() {
- return updaterFullName;
+ public String getUpdaterFullName() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.UPDATER_FULL_NAME);
}
public void setUpdaterFullName(String updaterFullName) {
- this.updaterFullName = updaterFullName;
+ setToscaPresentationValue(JsonPresentationFields.UPDATER_FULL_NAME, updaterFullName);
}
public Long getCreationDate() {
- return creationDate;
+ return (Long) getToscaPresentationValue(JsonPresentationFields.CREATION_DATE);
}
public void setCreationDate(Long creationDate) {
- this.creationDate = creationDate;
+ setToscaPresentationValue(JsonPresentationFields.CREATION_DATE, creationDate);
}
- public Long getLastUpdateDate() {
- return lastUpdateDate;
+ public Long getLastUpdateDate() {
+ return (Long) getToscaPresentationValue(JsonPresentationFields.LAST_UPDATE_DATE);
}
public void setLastUpdateDate(Long lastUpdateDate) {
- this.lastUpdateDate = lastUpdateDate;
+ setToscaPresentationValue(JsonPresentationFields.LAST_UPDATE_DATE, lastUpdateDate);
}
public String getUniqueId() {
- return uniqueId;
+ return (String) getToscaPresentationValue(JsonPresentationFields.UNIQUE_ID);
}
public void setUniqueId(String uniqueId) {
- this.uniqueId = uniqueId;
+ setToscaPresentationValue(JsonPresentationFields.UNIQUE_ID, uniqueId);
}
public String getDescription() {
- return description;
+ return (String) getToscaPresentationValue(JsonPresentationFields.DESCRIPTION);
}
public void setDescription(String description) {
- this.description = description;
+ setToscaPresentationValue(JsonPresentationFields.DESCRIPTION, description);
}
public String getArtifactLabel() {
- return artifactLabel;
+ return (String) getToscaPresentationValue(JsonPresentationFields.ARTIFACT_LABEL);
}
public void setArtifactLabel(String artifactLabel) {
- this.artifactLabel = artifactLabel;
+ setToscaPresentationValue(JsonPresentationFields.ARTIFACT_LABEL, artifactLabel);
}
public String getEsId() {
- return esId;
+ return (String) getToscaPresentationValue(JsonPresentationFields.ES_ID);
}
public void setEsId(String esId) {
- this.esId = esId;
+ setToscaPresentationValue(JsonPresentationFields.ES_ID, esId);
}
public String getArtifactCreator() {
- return artifactCreator;
+ return (String) getToscaPresentationValue(JsonPresentationFields.ARTIFACT_CREATOR);
}
public void setArtifactCreator(String artifactCreator) {
- this.artifactCreator = artifactCreator;
+ setToscaPresentationValue(JsonPresentationFields.ARTIFACT_CREATOR, artifactCreator);
}
- public Boolean getMandatory() {
- return mandatory;
+ public Boolean getMandatory() {
+ Boolean isMandatory = (Boolean) getToscaPresentationValue(JsonPresentationFields.IS_ABSTRACT);
+ return isMandatory == null? Boolean.FALSE: isMandatory;
}
public void setMandatory(Boolean mandatory) {
- this.mandatory = mandatory;
+ setToscaPresentationValue(JsonPresentationFields.IS_ABSTRACT, mandatory);
}
- public String getArtifactDisplayName() {
- return artifactDisplayName;
+ public String getArtifactDisplayName() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.ARTIFACT_DISPLAY_NAME);
}
public void setArtifactDisplayName(String artifactDisplayName) {
- this.artifactDisplayName = artifactDisplayName;
+ setToscaPresentationValue(JsonPresentationFields.ARTIFACT_DISPLAY_NAME, artifactDisplayName);
}
- public String getApiUrl() {
- return apiUrl;
+ public String getApiUrl() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.API_URL);
}
public void setApiUrl(String apiUrl) {
- this.apiUrl = apiUrl;
+ setToscaPresentationValue(JsonPresentationFields.API_URL, apiUrl);
}
public Boolean getServiceApi() {
- return serviceApi;
+ Boolean serviceApi = (Boolean) getToscaPresentationValue(JsonPresentationFields.SERVICE_API);
+ return serviceApi == null? Boolean.FALSE: serviceApi;
}
public void setServiceApi(Boolean serviceApi) {
- this.serviceApi = serviceApi;
+ setToscaPresentationValue(JsonPresentationFields.SERVICE_API, serviceApi);
}
public ArtifactGroupTypeEnum getArtifactGroupType() {
+ ArtifactGroupTypeEnum artifactGroupType = null;
+ String groupType = (String) getToscaPresentationValue(JsonPresentationFields.ARTIFACT_GROUP_TYPE);
+ if (groupType != null && !groupType.isEmpty()) {
+
+ artifactGroupType = ArtifactGroupTypeEnum.findType(groupType);
+ }
return artifactGroupType;
}
public void setArtifactGroupType(ArtifactGroupTypeEnum artifactGroupType) {
- this.artifactGroupType = artifactGroupType;
+ if(artifactGroupType != null)
+ setToscaPresentationValue(JsonPresentationFields.ARTIFACT_GROUP_TYPE, artifactGroupType.getType());
}
- public Integer getTimeout() {
- return timeout;
+ public Integer getTimeout() {
+ return (Integer) getToscaPresentationValue(JsonPresentationFields.ARTIFACT_TIMEOUT);
}
public void setTimeout(Integer timeout) {
- this.timeout = timeout;
+ setToscaPresentationValue(JsonPresentationFields.ARTIFACT_TIMEOUT, timeout);
}
- public String getArtifactVersion() {
- return artifactVersion;
+ public String getArtifactVersion() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.ARTIFACT_VERSION);
}
public void setArtifactVersion(String artifactVersion) {
- this.artifactVersion = artifactVersion;
+ setToscaPresentationValue(JsonPresentationFields.ARTIFACT_VERSION, artifactVersion);
}
public String getArtifactUUID() {
- return artifactUUID;
+ return (String) getToscaPresentationValue(JsonPresentationFields.ARTIFACT_UUID);
}
public void setArtifactUUID(String artifactUUID) {
- this.artifactUUID = artifactUUID;
+ setToscaPresentationValue(JsonPresentationFields.ARTIFACT_UUID, artifactUUID);
}
- public Long getPayloadUpdateDate() {
- return payloadUpdateDate;
+ public Long getPayloadUpdateDate() {
+ return (Long) getToscaPresentationValue(JsonPresentationFields.PAYLOAD_UPDATE_DATE);
}
public void setPayloadUpdateDate(Long payloadUpdateDate) {
- this.payloadUpdateDate = payloadUpdateDate;
+ setToscaPresentationValue(JsonPresentationFields.PAYLOAD_UPDATE_DATE, payloadUpdateDate);
}
public Long getHeatParamsUpdateDate() {
- return heatParamsUpdateDate;
+ return (Long) getToscaPresentationValue(JsonPresentationFields.HEAT_PARAMS_UPDATE_DATE);
}
public void setHeatParamsUpdateDate(Long heatParamsUpdateDate) {
- this.heatParamsUpdateDate = heatParamsUpdateDate;
+ setToscaPresentationValue(JsonPresentationFields.HEAT_PARAMS_UPDATE_DATE, heatParamsUpdateDate);
}
public List<String> getRequiredArtifacts() {
- return requiredArtifacts;
+ return (List<String>) getToscaPresentationValue(JsonPresentationFields.REQUIRED_ARTIFACTS);
}
public void setRequiredArtifacts(List<String> requiredArtifacts) {
- this.requiredArtifacts = requiredArtifacts;
+ setToscaPresentationValue(JsonPresentationFields.REQUIRED_ARTIFACTS, requiredArtifacts);
}
- public Boolean getGenerated() {
- return generated;
+ public Boolean getGenerated() {
+ Boolean generated = (Boolean) getToscaPresentationValue(JsonPresentationFields.GENERATED);
+ return generated == null ? Boolean.FALSE: generated;
}
public void setGenerated(Boolean generated) {
- this.generated = generated;
+ setToscaPresentationValue(JsonPresentationFields.GENERATED, generated);
+ }
+
+ public Boolean getDuplicated() {
+ Boolean duplicated = (Boolean) getToscaPresentationValue(JsonPresentationFields.DUPLICATED);
+ return duplicated == null ? Boolean.FALSE: duplicated;
+ }
+
+ public void setDuplicated(Boolean duplicated) {
+ setToscaPresentationValue(JsonPresentationFields.DUPLICATED, duplicated);
}
+
+ public List<HeatParameterDataDefinition> getHeatParameters() {
+ return (List<HeatParameterDataDefinition>) getToscaPresentationValue(JsonPresentationFields.HEAT_PARAMETERS);
+ }
+
+ public void setHeatParameters(List<HeatParameterDataDefinition> properties) {
+ setToscaPresentationValue(JsonPresentationFields.HEAT_PARAMETERS, properties);
+ }
+
+ public String getGeneratedFromId() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.GENERATED_FROM_ID);
+ }
+
+ public void setGeneratedFromId(String generatedFromId) {
+ setToscaPresentationValue(JsonPresentationFields.GENERATED_FROM_ID, generatedFromId);
+ }
+
@Override
public String toString() {
- return "ArtifactDataDefinition [uniqueId=" + uniqueId + ", artifactType=" + artifactType + ", artifactRef="
- + artifactRef + ", artifactName=" + artifactName + ", artifactRepository=" + artifactRepository
- + ", artifactChecksum=" + artifactChecksum + ", userIdCreator=" + userIdCreator + ", userIdLastUpdater="
- + userIdLastUpdater + ", creatorFullName=" + creatorFullName + ", updaterFullName=" + updaterFullName
- + ", creationDate=" + creationDate + ", lastUpdateDate=" + lastUpdateDate + ", esId=" + esId
- + ", artifactLabel=" + artifactLabel + ", artifactCreator=" + artifactCreator + ", description="
- + description + ", mandatory=" + mandatory + ", artifactDisplayName=" + artifactDisplayName
- + ", apiUrl=" + apiUrl + ", serviceApi=" + serviceApi + ", artifactGroupType=" + artifactGroupType
- + ", timeout=" + timeout + ", artifactVersion=" + artifactVersion + ", artifactUUID=" + artifactUUID
- + ", payloadUpdateDate=" + payloadUpdateDate + ", heatParamsUpdateDate=" + heatParamsUpdateDate
- + ", requiredArtifacts=" + requiredArtifacts + "]";
+ return "ArtifactDataDefinition [uniqueId=" + getUniqueId() + ", artifactType=" + getArtifactType() + ", artifactRef=" + getArtifactRef() + ", artifactName=" + getArtifactName() + ", artifactRepository=" + getArtifactRepository() + ", artifactChecksum="
+ + getArtifactChecksum() + ", userIdCreator=" + getUserIdCreator() + ", userIdLastUpdater=" + getUserIdLastUpdater() + ", creatorFullName=" + getCreatorFullName() + ", updaterFullName=" + getUpdaterFullName() + ", creationDate=" + getCreationDate()
+ + ", lastUpdateDate=" + getLastUpdateDate() + ", esId=" + getEsId() + ", artifactLabel=" + getArtifactLabel() + ", artifactCreator=" + getArtifactCreator() + ", description=" + getDescription() + ", mandatory=" + getMandatory() + ", artifactDisplayName="
+ + getArtifactDisplayName() + ", apiUrl=" + getApiUrl() + ", serviceApi=" + getServiceApi() + ", artifactGroupType=" + getArtifactGroupType() + ", timeout=" + getTimeout() + ", artifactVersion=" + getArtifactVersion() + ", artifactUUID=" + getArtifactUUID()
+ + ", payloadUpdateDate=" + getPayloadUpdateDate() + ", heatParamsUpdateDate=" + getHeatParamsUpdateDate() + ", requiredArtifacts=" + getRequiredArtifacts() + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
+
+ String apiUrl = getApiUrl();
+ String artifactChecksum = getArtifactChecksum();
+ String artifactCreator = getArtifactCreator();
+ String artifactDisplayName = getArtifactDisplayName();
+ ArtifactGroupTypeEnum artifactGroupType = getArtifactGroupType();
+ String artifactLabel = getArtifactLabel();
+ String artifactName = getArtifactName();
+ String artifactRef = getArtifactRef();
+ String artifactRepository = getArtifactRepository();
+ String artifactType = getArtifactType();
+
+ String artifactUUID = getArtifactUUID();
+ String artifactVersion = getArtifactVersion();
+ String userIdCreator = getUserIdCreator();
+ String userIdLastUpdater = getUserIdLastUpdater();
+ Long creationDate = getCreationDate();
+
+ String creatorFullName = getCreatorFullName();
+ String description = getDescription();
+ String esId = getEsId();
+ Long heatParamsUpdateDate = getHeatParamsUpdateDate();
+ Long lastUpdateDate = getLastUpdateDate();
+ Boolean mandatory = getMandatory();
+
+ Long payloadUpdateDate = getPayloadUpdateDate();
+ List<String> requiredArtifacts = getRequiredArtifacts();
+ Boolean serviceApi = getServiceApi();
+ Integer timeout = getTimeout();
+ String uniqueId = getUniqueId();
+ String updaterFullName = getUpdaterFullName();
+
result = prime * result + ((apiUrl == null) ? 0 : apiUrl.hashCode());
result = prime * result + ((artifactChecksum == null) ? 0 : artifactChecksum.hashCode());
result = prime * result + ((artifactCreator == null) ? 0 : artifactCreator.hashCode());
@@ -450,137 +440,137 @@ public class ArtifactDataDefinition implements Serializable {
if (getClass() != obj.getClass())
return false;
ArtifactDataDefinition other = (ArtifactDataDefinition) obj;
- if (apiUrl == null) {
- if (other.apiUrl != null)
+ if (getApiUrl() == null) {
+ if (other.getApiUrl() != null)
return false;
- } else if (!apiUrl.equals(other.apiUrl))
+ } else if (!getApiUrl().equals(other.getApiUrl()))
return false;
- if (artifactChecksum == null) {
- if (other.artifactChecksum != null)
+ if (getArtifactChecksum() == null) {
+ if (other.getArtifactChecksum() != null)
return false;
- } else if (!artifactChecksum.equals(other.artifactChecksum))
+ } else if (!getArtifactChecksum().equals(other.getArtifactChecksum()))
return false;
- if (artifactCreator == null) {
- if (other.artifactCreator != null)
+ if (getArtifactCreator() == null) {
+ if (other.getArtifactCreator() != null)
return false;
- } else if (!artifactCreator.equals(other.artifactCreator))
+ } else if (!getArtifactCreator().equals(other.getArtifactCreator()))
return false;
- if (artifactDisplayName == null) {
- if (other.artifactDisplayName != null)
+ if (getArtifactDisplayName() == null) {
+ if (other.getArtifactDisplayName() != null)
return false;
- } else if (!artifactDisplayName.equals(other.artifactDisplayName))
+ } else if (!getArtifactDisplayName().equals(other.getArtifactDisplayName()))
return false;
- if (artifactGroupType != other.artifactGroupType)
+ if (getArtifactGroupType() != other.getArtifactGroupType())
return false;
- if (artifactLabel == null) {
- if (other.artifactLabel != null)
+ if (getArtifactLabel() == null) {
+ if (other.getArtifactLabel() != null)
return false;
- } else if (!artifactLabel.equals(other.artifactLabel))
+ } else if (!getArtifactLabel().equals(other.getArtifactLabel()))
return false;
- if (artifactName == null) {
- if (other.artifactName != null)
+ if (getArtifactName() == null) {
+ if (other.getArtifactName() != null)
return false;
- } else if (!artifactName.equals(other.artifactName))
+ } else if (!getArtifactName().equals(other.getArtifactName()))
return false;
- if (artifactRef == null) {
- if (other.artifactRef != null)
+ if (getArtifactRef() == null) {
+ if (other.getArtifactRef() != null)
return false;
- } else if (!artifactRef.equals(other.artifactRef))
+ } else if (!getArtifactRef().equals(other.getArtifactRef()))
return false;
- if (artifactRepository == null) {
- if (other.artifactRepository != null)
+ if (getArtifactRepository() == null) {
+ if (other.getArtifactRepository() != null)
return false;
- } else if (!artifactRepository.equals(other.artifactRepository))
+ } else if (!getArtifactRepository().equals(other.getArtifactRepository()))
return false;
- if (artifactType == null) {
- if (other.artifactType != null)
+ if (getArtifactType() == null) {
+ if (other.getArtifactType() != null)
return false;
- } else if (!artifactType.equals(other.artifactType))
+ } else if (!getArtifactType().equals(other.getArtifactType()))
return false;
- if (artifactUUID == null) {
- if (other.artifactUUID != null)
+ if (getArtifactUUID() == null) {
+ if (other.getArtifactUUID() != null)
return false;
- } else if (!artifactUUID.equals(other.artifactUUID))
+ } else if (!getArtifactUUID().equals(other.getArtifactUUID()))
return false;
- if (artifactVersion == null) {
- if (other.artifactVersion != null)
+ if (getArtifactVersion() == null) {
+ if (other.getArtifactVersion() != null)
return false;
- } else if (!artifactVersion.equals(other.artifactVersion))
+ } else if (!getArtifactVersion().equals(other.getArtifactVersion()))
return false;
- if (userIdCreator == null) {
- if (other.userIdCreator != null)
+ if (getUserIdCreator() == null) {
+ if (other.getUserIdCreator() != null)
return false;
- } else if (!userIdCreator.equals(other.userIdCreator))
+ } else if (!getUserIdCreator().equals(other.getUserIdCreator()))
return false;
- if (userIdLastUpdater == null) {
- if (other.userIdLastUpdater != null)
+ if (getUserIdLastUpdater() == null) {
+ if (other.getUserIdLastUpdater() != null)
return false;
- } else if (!userIdLastUpdater.equals(other.userIdLastUpdater))
+ } else if (!getUserIdLastUpdater().equals(other.getUserIdLastUpdater()))
return false;
- if (creationDate == null) {
- if (other.creationDate != null)
+ if (getCreationDate() == null) {
+ if (other.getCreationDate() != null)
return false;
- } else if (!creationDate.equals(other.creationDate))
+ } else if (!getCreationDate().equals(other.getCreationDate()))
return false;
- if (creatorFullName == null) {
- if (other.creatorFullName != null)
+ if (getCreatorFullName() == null) {
+ if (other.getCreatorFullName() != null)
return false;
- } else if (!creatorFullName.equals(other.creatorFullName))
+ } else if (!getCreatorFullName().equals(other.getCreatorFullName()))
return false;
- if (description == null) {
- if (other.description != null)
+ if (getDescription() == null) {
+ if (other.getDescription() != null)
return false;
- } else if (!description.equals(other.description))
+ } else if (!getDescription().equals(other.getDescription()))
return false;
- if (esId == null) {
- if (other.esId != null)
+ if (getEsId() == null) {
+ if (other.getEsId() != null)
return false;
- } else if (!esId.equals(other.esId))
+ } else if (!getEsId().equals(other.getEsId()))
return false;
- if (heatParamsUpdateDate == null) {
- if (other.heatParamsUpdateDate != null)
+ if (getHeatParamsUpdateDate() == null) {
+ if (other.getHeatParamsUpdateDate() != null)
return false;
- } else if (!heatParamsUpdateDate.equals(other.heatParamsUpdateDate))
+ } else if (!getHeatParamsUpdateDate().equals(other.getHeatParamsUpdateDate()))
return false;
- if (lastUpdateDate == null) {
- if (other.lastUpdateDate != null)
+ if (getLastUpdateDate() == null) {
+ if (other.getLastUpdateDate() != null)
return false;
- } else if (!lastUpdateDate.equals(other.lastUpdateDate))
+ } else if (!getLastUpdateDate().equals(other.getLastUpdateDate()))
return false;
- if (mandatory == null) {
- if (other.mandatory != null)
+ if (getMandatory() == null) {
+ if (other.getMandatory() != null)
return false;
- } else if (!mandatory.equals(other.mandatory))
+ } else if (!getMandatory().equals(other.getMandatory()))
return false;
- if (payloadUpdateDate == null) {
- if (other.payloadUpdateDate != null)
+ if (getPayloadUpdateDate() == null) {
+ if (other.getPayloadUpdateDate() != null)
return false;
- } else if (!payloadUpdateDate.equals(other.payloadUpdateDate))
+ } else if (!getPayloadUpdateDate().equals(other.getPayloadUpdateDate()))
return false;
- if (requiredArtifacts == null) {
- if (other.requiredArtifacts != null)
+ if (getRequiredArtifacts() == null) {
+ if (other.getRequiredArtifacts() != null)
return false;
- } else if (!requiredArtifacts.equals(other.requiredArtifacts))
+ } else if (!getRequiredArtifacts().equals(other.getRequiredArtifacts()))
return false;
- if (serviceApi == null) {
- if (other.serviceApi != null)
+ if (getServiceApi() == null) {
+ if (other.getServiceApi() != null)
return false;
- } else if (!serviceApi.equals(other.serviceApi))
+ } else if (!getServiceApi().equals(other.getServiceApi()))
return false;
- if (timeout == null) {
- if (other.timeout != null)
+ if (getTimeout() == null) {
+ if (other.getTimeout() != null)
return false;
- } else if (!timeout.equals(other.timeout))
+ } else if (!getTimeout().equals(other.getTimeout()))
return false;
- if (uniqueId == null) {
- if (other.uniqueId != null)
+ if (getUniqueId() == null) {
+ if (other.getUniqueId() != null)
return false;
- } else if (!uniqueId.equals(other.uniqueId))
+ } else if (!getUniqueId().equals(other.getUniqueId()))
return false;
- if (updaterFullName == null) {
- if (other.updaterFullName != null)
+ if (getUpdaterFullName() == null) {
+ if (other.getUpdaterFullName() != null)
return false;
- } else if (!updaterFullName.equals(other.updaterFullName))
+ } else if (!getUpdaterFullName().equals(other.getUpdaterFullName()))
return false;
return true;
}
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/AttributeDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/AttributeDataDefinition.java
index b52824697a..a753270bbd 100644
--- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/AttributeDataDefinition.java
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/AttributeDataDefinition.java
@@ -23,13 +23,16 @@ package org.openecomp.sdc.be.datatypes.elements;
import java.io.Serializable;
import java.util.Objects;
+import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
+import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+
/**
* Represents AttributeDataDefinition
*
* @author mshitrit
*
*/
-public class AttributeDataDefinition implements Serializable {
+public class AttributeDataDefinition extends ToscaDataDefinition implements Serializable {
/**
*
@@ -183,4 +186,24 @@ public class AttributeDataDefinition implements Serializable {
public void setValue(String value) {
this.value = value;
}
+
+ @Override
+ public Object getToscaPresentationValue(JsonPresentationFields field) {
+ switch (field) {
+ case NAME:
+ return name;
+ case UNIQUE_ID:
+ return uniqueId;
+ case TYPE:
+ return type;
+ case DESCRIPTION:
+ return description;
+ case VALUE:
+ return value;
+ case DEFAULT_VALUE:
+ return defaultValue;
+ default:
+ return super.getToscaPresentationValue(field);
+ }
+ }
}
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/CapabilityDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/CapabilityDataDefinition.java
new file mode 100644
index 0000000000..0a98a2abda
--- /dev/null
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/CapabilityDataDefinition.java
@@ -0,0 +1,310 @@
+package org.openecomp.sdc.be.datatypes.elements;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
+import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+
+
+
+public class CapabilityDataDefinition extends ToscaDataDefinition implements Serializable {
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = 7544984873506188920L;
+ public final static String MIN_OCCURRENCES = "1"; // occurrences
+ public final static String MAX_OCCURRENCES = "UNBOUNDED";
+
+
+ public CapabilityDataDefinition() {
+ super();
+ this.setMinOccurrences( MIN_OCCURRENCES );
+ this.setMaxOccurrences( MAX_OCCURRENCES);
+ this.setLeftOccurrences( MAX_OCCURRENCES);
+ }
+
+ public CapabilityDataDefinition(CapabilityDataDefinition a) {
+ super();
+ this.setUniqueId(a.getUniqueId());
+ this.setType(a.getType());
+ this.setDescription ( a.getDescription());
+ this.setName( a.getName());
+ this.setValidSourceTypes( a.getValidSourceTypes());
+ this.setCapabilitySources( a.getCapabilitySources());
+ this.setOwnerId( a.getOwnerId());
+ this.setOwnerName( a.getOwnerName());
+ this.setMinOccurrences( a.getMinOccurrences());
+ this.setMaxOccurrences( a.getMaxOccurrences());
+ this.setLeftOccurrences(a.getLeftOccurrences());
+ this.setPath(a.getPath());
+ this.setSource(a.getSource());
+
+ }
+
+
+
+ public String getOwnerId() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.OWNER_ID);
+ }
+
+ public void setOwnerId(String ownerId) {
+ setToscaPresentationValue(JsonPresentationFields.OWNER_ID, ownerId);
+ }
+
+ public String getOwnerName() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.OWNER_NAME);
+ }
+
+ public void setOwnerName(String ownerName) {
+ setToscaPresentationValue(JsonPresentationFields.OWNER_NAME, ownerName);
+ }
+
+ public String getMinOccurrences() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.MIN_OCCURRENCES);
+ }
+
+ public void setMinOccurrences(String minOccurrences) {
+ setToscaPresentationValue(JsonPresentationFields.MIN_OCCURRENCES, minOccurrences);
+ }
+
+ public String getMaxOccurrences() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.MAX_OCCURRENCES);
+ }
+
+ public void setMaxOccurrences(String maxOccurrences) {
+ setToscaPresentationValue(JsonPresentationFields.MAX_OCCURRENCES, maxOccurrences);
+ }
+ public String getLeftOccurrences() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.LEFT_OCCURRENCES);
+ }
+
+ public void setLeftOccurrences(String leftOccurrences) {
+ setToscaPresentationValue(JsonPresentationFields.LEFT_OCCURRENCES, leftOccurrences);
+ }
+
+ public String getUniqueId() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.UNIQUE_ID);
+ }
+
+ public void setUniqueId(String uniqueId) {
+ setToscaPresentationValue(JsonPresentationFields.UNIQUE_ID, uniqueId);
+ }
+
+ public String getDescription() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.DESCRIPTION);
+ }
+
+ public void setDescription(String description) {
+ setToscaPresentationValue(JsonPresentationFields.DESCRIPTION, description);
+ }
+
+ public String getName() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.NAME);
+ }
+
+ public void setName(String name) {
+ setToscaPresentationValue(JsonPresentationFields.NAME, name);
+ }
+
+ public String getType() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.TYPE);
+ }
+
+ public void setType(String type) {
+ setToscaPresentationValue(JsonPresentationFields.TYPE, type);
+ }
+
+ public List<String> getValidSourceTypes() {
+ return (List<String>) getToscaPresentationValue(JsonPresentationFields.VALID_SOURCE_TYPE);
+ }
+
+ public void setValidSourceTypes(List<String> validSourceTypes) {
+ setToscaPresentationValue(JsonPresentationFields.VALID_SOURCE_TYPE, validSourceTypes);
+ }
+
+ public List<String> getCapabilitySources() {
+ return (List<String>) getToscaPresentationValue(JsonPresentationFields.CAPABILITY_SOURCES);
+ }
+
+ public void setCapabilitySources(List<String> capabilitySources) {
+ setToscaPresentationValue(JsonPresentationFields.CAPABILITY_SOURCES, capabilitySources);
+ }
+
+ public void setPath(List<String> path){
+ setToscaPresentationValue(JsonPresentationFields.PATH, path);
+ }
+ public List<String> getPath() {
+ return (List<String>) getToscaPresentationValue(JsonPresentationFields.PATH);
+ }
+ public void setSource(String source){
+ setToscaPresentationValue(JsonPresentationFields.SOURCE, source);
+ }
+ public String getSource() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.SOURCE);
+ }
+ public void addToPath(String elementInPath){
+ List<String> path = getPath();
+ if ( path == null ){
+ path = new ArrayList<>();
+ }
+ path.add(elementInPath);
+ setPath(path);
+ }
+
+
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+
+ String uniqueId = this.getUniqueId();
+ String description = this.getDescription();
+ String name = this.getName();
+ String type = this.getType();
+ List<String> validSourceTypes = this.getValidSourceTypes();
+ List<String> capabilitySources = this.getCapabilitySources();
+ List<String> path = this.getPath();
+
+ String ownerId = this.getOwnerId();
+ String ownerName = this.getOwnerName();
+ String minOccurrences = this.getMinOccurrences();
+ String maxOccurrences = this.getMaxOccurrences();
+ String leftOccurrences = getLeftOccurrences();
+ String source = getSource();
+
+ result = prime * result + ((capabilitySources == null) ? 0 : capabilitySources.hashCode());
+ result = prime * result + ((description == null) ? 0 : description.hashCode());
+ result = prime * result + ((maxOccurrences == null) ? 0 : maxOccurrences.hashCode());
+ result = prime * result + ((minOccurrences == null) ? 0 : minOccurrences.hashCode());
+ result = prime * result + ((name == null) ? 0 : name.hashCode());
+ result = prime * result + ((ownerId == null) ? 0 : ownerId.hashCode());
+ result = prime * result + ((ownerName == null) ? 0 : ownerName.hashCode());
+
+ result = prime * result + ((type == null) ? 0 : type.hashCode());
+ result = prime * result + ((uniqueId == null) ? 0 : uniqueId.hashCode());
+ result = prime * result + ((validSourceTypes == null) ? 0 : validSourceTypes.hashCode());
+ result = prime * result + ((leftOccurrences == null) ? 0 : leftOccurrences.hashCode());
+ result = prime * result + ((path == null) ? 0 : path.hashCode());
+ result = prime * result + ((source == null) ? 0 : source.hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+
+ String uniqueId = this.getUniqueId();
+ String description = this.getDescription();
+ String name = this.getName();
+ String type = this.getType();
+ List<String> validSourceTypes = this.getValidSourceTypes();
+ List<String> capabilitySources = this.getCapabilitySources();
+ String ownerId = this.getOwnerId();
+ String ownerName = this.getOwnerName();
+ String minOccurrences = this.getMinOccurrences();
+ String maxOccurrences = this.getMaxOccurrences();
+ String leftOccurrences = getLeftOccurrences();
+ List<String> path = this.getPath();
+ String source = getSource();
+
+ if (this == obj)
+ return true;
+ if (obj == null)
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
+ CapabilityDataDefinition other = (CapabilityDataDefinition) obj;
+ if (capabilitySources == null) {
+ if (other.getCapabilitySources() != null)
+ return false;
+ } else if (!capabilitySources.equals(other.getCapabilitySources()))
+ return false;
+ if (description == null) {
+ if (other.getDescription() != null)
+ return false;
+ } else if (!description.equals(other.getDescription()))
+ return false;
+ if (maxOccurrences == null) {
+ if (other.getMaxOccurrences() != null)
+ return false;
+ } else if (!maxOccurrences.equals(other.getMaxOccurrences()))
+ return false;
+ if (minOccurrences == null) {
+ if (other.getMinOccurrences() != null)
+ return false;
+ } else if (!minOccurrences.equals(other.getMinOccurrences()))
+ return false;
+ if (name == null) {
+ if (other.getName() != null)
+ return false;
+ } else if (!name.equals(other.getName()))
+ return false;
+ if (ownerId == null) {
+ if (other.getOwnerId() != null)
+ return false;
+ } else if (!ownerId.equals(other.getOwnerId()))
+ return false;
+ if (ownerName == null) {
+ if (other.getOwnerName() != null)
+ return false;
+ } else if (!ownerName.equals(other.getOwnerName()))
+ return false;
+ if (type == null) {
+ if (other.getType() != null)
+ return false;
+ } else if (!type.equals(other.getType()))
+ return false;
+ if (uniqueId == null) {
+ if (other.getUniqueId() != null)
+ return false;
+ } else if (!uniqueId.equals(other.getUniqueId()))
+ return false;
+ if (validSourceTypes == null) {
+ if (other.getValidSourceTypes() != null)
+ return false;
+ } else if (!validSourceTypes.equals(other.getValidSourceTypes()))
+ return false;
+ if (leftOccurrences == null) {
+ if (other.getLeftOccurrences() != null)
+ return false;
+ } else if (!leftOccurrences.equals(other.getLeftOccurrences()))
+ return false;
+ if (path == null) {
+ if (other.getPath() != null)
+ return false;
+ } else if (!path.equals(other.getPath()))
+ return false;
+ if (source == null) {
+ if (other.getSource() != null)
+ return false;
+ } else if (!source.equals(other.getSource()))
+ return false;
+ return true;
+ }
+
+ @Override
+ public String toString() {
+ String uniqueId = this.getUniqueId();
+ String description = this.getDescription();
+ String name = this.getName();
+ String type = this.getType();
+ List<String> validSourceTypes = this.getValidSourceTypes();
+ List<String> capabilitySources = this.getCapabilitySources();
+ List<String> path = this.getPath();
+ String ownerId = this.getOwnerId();
+ String ownerName = this.getOwnerName();
+ String minOccurrences = this.getMinOccurrences();
+ String maxOccurrences = this.getMaxOccurrences();
+ String source = this.getSource();
+
+
+ return "CapabilityDefinition [uniqueId=" + uniqueId + ", description=" + description + ", name=" + name
+ + ", type=" + type + ", validSourceTypes=" + validSourceTypes + ", capabilitySources="
+ + capabilitySources + ", ownerId=" + ownerId + ", ownerName=" + ownerName
+ + ", minOccurrences=" + minOccurrences + ", maxOccurrences=" + maxOccurrences + ", path=" + path+ ", source=" + source + "]";
+ }
+
+}
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 f4de5b8c9d..110e08852b 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
@@ -23,103 +23,102 @@ package org.openecomp.sdc.be.datatypes.elements;
import java.io.Serializable;
import java.util.List;
-public class CapabilityTypeDataDefinition implements Serializable {
+import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
+import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+
+public class CapabilityTypeDataDefinition extends ToscaDataDefinition implements Serializable {
/**
*
*/
private static final long serialVersionUID = 3242123405337612089L;
- private String uniqueId;
-
- private String description;
-
- /** Identifies the type of the capability. */
- private String type;
-
- private List<String> validSourceTypes;
- private String version;
-
- private Long creationTime;
-
- private Long modificationTime;
// private String derivedFrom;
public CapabilityTypeDataDefinition(CapabilityTypeDataDefinition cdt) {
super();
- this.uniqueId = cdt.getUniqueId();
- this.description = cdt.getDescription();
- this.type = cdt.getType();
- this.validSourceTypes = cdt.getValidSourceTypes();
- this.version = cdt.getVersion();
- this.creationTime = cdt.getCreationTime();
- this.modificationTime = cdt.getModificationTime();
+ this.setUniqueId(cdt.getUniqueId());
+ this.setDescription ( cdt.getDescription());
+ this.setType(cdt.getType());
+ this.setValidSourceTypes( cdt.getValidSourceTypes());
+ this.setVersion( cdt.getVersion());
+ this.setCreationTime (cdt.getCreationTime());
+ this.setModificationTime (cdt.getModificationTime());
+
}
public CapabilityTypeDataDefinition() {
-
+ super();
}
public String getUniqueId() {
- return uniqueId;
+ return (String) getToscaPresentationValue(JsonPresentationFields.UNIQUE_ID);
}
public void setUniqueId(String uniqueId) {
- this.uniqueId = uniqueId;
+ setToscaPresentationValue(JsonPresentationFields.UNIQUE_ID, uniqueId);
}
public String getDescription() {
- return description;
+ return (String) getToscaPresentationValue(JsonPresentationFields.DESCRIPTION);
}
public void setDescription(String description) {
- this.description = description;
+ setToscaPresentationValue(JsonPresentationFields.DESCRIPTION, description);
}
public String getType() {
- return type;
+ return (String) getToscaPresentationValue(JsonPresentationFields.TYPE);
}
public void setType(String type) {
- this.type = type;
+ setToscaPresentationValue(JsonPresentationFields.TYPE, type);
}
public List<String> getValidSourceTypes() {
- return validSourceTypes;
+ return (List<String> ) getToscaPresentationValue(JsonPresentationFields.VALID_SOURCE_TYPE);
}
public void setValidSourceTypes(List<String> validSourceTypes) {
- this.validSourceTypes = validSourceTypes;
+ setToscaPresentationValue(JsonPresentationFields.VALID_SOURCE_TYPE, validSourceTypes);
}
public String getVersion() {
- return version;
+ return (String) getToscaPresentationValue(JsonPresentationFields.VERSION);
}
public void setVersion(String version) {
- this.version = version;
+ setToscaPresentationValue(JsonPresentationFields.VERSION, version);
}
public Long getCreationTime() {
- return creationTime;
+ return (Long) getToscaPresentationValue(JsonPresentationFields.CREATION_TIME);
}
public void setCreationTime(Long creationTime) {
- this.creationTime = creationTime;
+ setToscaPresentationValue(JsonPresentationFields.CREATION_TIME, creationTime);
}
public Long getModificationTime() {
- return modificationTime;
+ return (Long) getToscaPresentationValue(JsonPresentationFields.MODIFICATION_TIME);
}
public void setModificationTime(Long modificationTime) {
- this.modificationTime = modificationTime;
+ setToscaPresentationValue(JsonPresentationFields.MODIFICATION_TIME, modificationTime);
}
@Override
public String toString() {
+ String uniqueId = getUniqueId();
+ String description = getDescription();
+ String type = getType();
+ List<String> validSourceTypes = getValidSourceTypes();
+ String version = getVersion();
+ Long creationTime = getCreationTime();
+ Long modificationTime = getModificationTime();
+
return "CapabilityTypeDataDefinition [uniqueId=" + uniqueId + ", description=" + description + ", type=" + type
+ ", validSourceTypes=" + validSourceTypes + ", version=" + version + ", creationTime=" + creationTime
+ ", modificationTime=" + modificationTime + "]";
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 c9a9516f21..e236fcb963 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
@@ -23,17 +23,22 @@ package org.openecomp.sdc.be.datatypes.elements;
import java.io.Serializable;
import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
+import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
-public class ComponentInstanceDataDefinition implements Serializable {
+public class ComponentInstanceDataDefinition extends ToscaDataDefinition implements Serializable {
/**
*
*/
+
private static final long serialVersionUID = 7215033872921497743L;
+ private String icon;
+
private String uniqueId;
private String name;
+
private String normalizedName;
private String componentUid;
@@ -51,12 +56,17 @@ public class ComponentInstanceDataDefinition implements Serializable {
private Integer attributeValueCounter;
private Integer inputValueCounter = 1;
private OriginTypeEnum originType;
-
+ private String customizationUUID;
+ private String componentName;
+ private String componentVersion;
+ private String toscaComponentName;
+
public ComponentInstanceDataDefinition() {
super();
}
public ComponentInstanceDataDefinition(ComponentInstanceDataDefinition dataDefinition) {
+ this.icon = dataDefinition.icon;
this.uniqueId = dataDefinition.uniqueId;
this.name = dataDefinition.name;
this.componentUid = dataDefinition.componentUid;
@@ -68,9 +78,19 @@ public class ComponentInstanceDataDefinition implements Serializable {
this.propertyValueCounter = dataDefinition.propertyValueCounter;
this.normalizedName = dataDefinition.normalizedName;
this.originType = dataDefinition.originType;
-
+ this.customizationUUID = dataDefinition.customizationUUID;
+ this.componentName = dataDefinition.componentName;
+ this.componentVersion = dataDefinition.componentVersion;
+ this.toscaComponentName = dataDefinition.toscaComponentName;
+ }
+
+ public String getIcon() {
+ return icon;
}
+ public void setIcon(String icon) {
+ this.icon = icon;
+ }
public String getUniqueId() {
return uniqueId;
}
@@ -159,15 +179,6 @@ public class ComponentInstanceDataDefinition implements Serializable {
this.originType = originType;
}
- @Override
- public String toString() {
- return "ComponentInstanceDataDefinition [uniqueId=" + uniqueId + ", name=" + name + ", normalizedName="
- + normalizedName + ", componentUid=" + componentUid + ", creationTime=" + creationTime
- + ", modificationTime=" + modificationTime + ", description=" + description + ", posX=" + posX
- + ", posY=" + posY + ", propertyValueCounter=" + propertyValueCounter + ", originType=" + originType
- + "]";
- }
-
public Integer getAttributeValueCounter() {
return attributeValueCounter;
}
@@ -184,4 +195,43 @@ public class ComponentInstanceDataDefinition implements Serializable {
this.inputValueCounter = inputValueCounter;
}
+ public String getCustomizationUUID() {
+ return customizationUUID;
+ }
+
+ public void setCustomizationUUID(String customizationUUID) {
+ this.customizationUUID = customizationUUID;
+ }
+
+ public String getComponentName() {
+ return componentName;
+ }
+
+ public void setComponentName(String resourceName) {
+ this.componentName = resourceName;
+ }
+
+ public String getComponentVersion() {
+ return componentVersion;
+ }
+
+ public String getToscaComponentName() {
+ return toscaComponentName;
+ }
+
+ public void setToscaComponentName(String toscaComponentName) {
+ this.toscaComponentName = toscaComponentName;
+ }
+
+ public void setComponentVersion(String resourceVersion) {
+ this.componentVersion = resourceVersion;
+ }
+
+ @Override
+ public String toString() {
+ return "ComponentInstanceDataDefinition [icon=" + icon + ", uniqueId=" + uniqueId + ", name=" + name + ", normalizedName=" + normalizedName + ", componentUid=" + componentUid + ", creationTime=" + creationTime + ", modificationTime="
+ + modificationTime + ", description=" + description + ", posX=" + posX + ", posY=" + posY + ", propertyValueCounter=" + propertyValueCounter + ", attributeValueCounter=" + attributeValueCounter + ", inputValueCounter="
+ + inputValueCounter + ", originType=" + originType + ", customizationUUID=" + customizationUUID + ", componentName=" + componentName + ", componentVersion=" + componentVersion + ", toscaComponentName=" + toscaComponentName + "]";
+ }
+
}
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
new file mode 100644
index 0000000000..2ba460b9ab
--- /dev/null
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/CompositionDataDefinition.java
@@ -0,0 +1,40 @@
+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;
+
+public class CompositionDataDefinition extends ToscaDataDefinition {
+
+ public Map<String, ComponentInstanceDataDefinition> getComponentInstances() {
+ return (Map<String, ComponentInstanceDataDefinition>) getToscaPresentationValue(JsonPresentationFields.COMPONENT_INSTANCES);
+ }
+ public void setComponentInstances(Map<String, ComponentInstanceDataDefinition> componentInstances) {
+ setToscaPresentationValue(JsonPresentationFields.COMPONENT_INSTANCES, componentInstances);
+ }
+ public Map<String, RelationshipInstDataDefinition> getRelations() {
+ return (Map<String, RelationshipInstDataDefinition>) getToscaPresentationValue(JsonPresentationFields.RELATIONS);
+ }
+ public void setRelations(Map<String, RelationshipInstDataDefinition> relations) {
+ setToscaPresentationValue(JsonPresentationFields.RELATIONS, relations);
+ }
+ public void addInstance( String key, ComponentInstanceDataDefinition instance ){
+ Map<String, ComponentInstanceDataDefinition> instances = getComponentInstances();
+ if (instances == null ){
+ instances = new HashMap<>();
+ setToscaPresentationValue(JsonPresentationFields.COMPONENT_INSTANCES, instances );
+ }
+ instances.put(key, instance);
+ }
+
+ public void addRelation( String key, RelationshipInstDataDefinition relation ){
+ Map<String, RelationshipInstDataDefinition> relations = getRelations();
+ if (relations == null ){
+ relations = new HashMap<>();
+ setToscaPresentationValue(JsonPresentationFields.RELATIONS, relations );
+ }
+ relations.put(key, relation);
+ }
+}
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ConsumerDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ConsumerDataDefinition.java
index 6cd7d6c0fb..143c28d068 100644
--- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ConsumerDataDefinition.java
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ConsumerDataDefinition.java
@@ -20,7 +20,9 @@
package org.openecomp.sdc.be.datatypes.elements;
-public class ConsumerDataDefinition {
+import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+
+public class ConsumerDataDefinition extends ToscaDataDefinition {
// ECOMP Consumer Name - UTF-8 string up to 255 characters containing the
// following characters : ( maybe to limit 4-64 chars ? )
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 bfcfefc433..a048ceb096 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
@@ -22,7 +22,9 @@ package org.openecomp.sdc.be.datatypes.elements;
import java.io.Serializable;
-public class DataTypeDataDefinition implements Serializable {
+import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+
+public class DataTypeDataDefinition extends ToscaDataDefinition implements Serializable {
/**
*
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
new file mode 100644
index 0000000000..c913eaf0cb
--- /dev/null
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/GetInputValueDataDefinition.java
@@ -0,0 +1,166 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.datatypes.elements;
+
+import java.io.Serializable;
+import java.util.Map;
+
+import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+
+public class GetInputValueDataDefinition extends ToscaDataDefinition implements Serializable{
+ /**
+ *
+ */
+ private static final long serialVersionUID = 5466910697527037975L;
+ private String propName;
+ private String inputName;
+ private String inputId;
+ private Integer indexValue;
+ private GetInputValueDataDefinition getInputIndex;
+
+ boolean isList = false;
+
+ public GetInputValueDataDefinition(){
+ super();
+ }
+
+ public GetInputValueDataDefinition(Map<String, Object> pr) {
+ super(pr);
+
+ }
+
+ public GetInputValueDataDefinition(GetInputValueDataDefinition p) {
+
+
+ super();
+ this.setPropName(p.getPropName());
+ this.setInputName( p.getInputName());
+ this.setInputId( p.getInputId());
+ this.setIndexValue ( p.getIndexValue());
+ this.setGetInputIndex ( p.getGetInputIndex());
+ this.setList ( p.isList());
+
+
+ }
+
+ public String getPropName() {
+ return propName;
+ }
+
+ public void setPropName(String propName) {
+ this.propName = propName;
+ }
+
+ public String getInputName() {
+ return inputName;
+ }
+
+ public void setInputName(String inputName) {
+ this.inputName = inputName;
+ }
+
+ public Integer getIndexValue() {
+ return indexValue;
+ }
+
+ public void setIndexValue(Integer indexValue) {
+ this.indexValue = indexValue;
+ }
+
+ public GetInputValueDataDefinition getGetInputIndex() {
+ return getInputIndex;
+ }
+
+ public void setGetInputIndex(GetInputValueDataDefinition getInputIndex) {
+ this.getInputIndex = getInputIndex;
+ }
+
+ public boolean isList() {
+ return isList;
+ }
+
+ public void setList(boolean isList) {
+ this.isList = isList;
+ }
+
+
+ public String getInputId() {
+ return inputId;
+ }
+
+ public void setInputId(String inputId) {
+ this.inputId = inputId;
+ }
+
+ @Override
+ public String toString() {
+ return "GetInputValueDataDefinition [propName=" + propName + ", inputName=" + inputName + ", indexValue=" + indexValue + ", getInputIndex=" + getInputIndex + ", isList=" + isList + "]";
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((getInputIndex == null) ? 0 : getInputIndex.hashCode());
+ result = prime * result + ((indexValue == null) ? 0 : indexValue.hashCode());
+ result = prime * result + ((inputName == null) ? 0 : inputName.hashCode());
+ result = prime * result + (isList ? 1231 : 1237);
+ result = prime * result + ((propName == null) ? 0 : propName.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;
+ GetInputValueDataDefinition other = (GetInputValueDataDefinition) obj;
+ if (getInputIndex == null) {
+ if (other.getInputIndex != null)
+ return false;
+ } else if (!getInputIndex.equals(other.getInputIndex))
+ return false;
+ if (indexValue == null) {
+ if (other.indexValue != null)
+ return false;
+ } else if (!indexValue.equals(other.indexValue))
+ return false;
+ if (inputName == null) {
+ if (other.inputName != null)
+ return false;
+ } else if (!inputName.equals(other.inputName))
+ return false;
+ if (isList != other.isList)
+ return false;
+ if (propName == null) {
+ if (other.propName != null)
+ return false;
+ } else if (!propName.equals(other.propName))
+ return false;
+ return true;
+ }
+
+
+
+}
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 be3dd8c0ed..d4981a72ae 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
@@ -21,89 +21,107 @@
package org.openecomp.sdc.be.datatypes.elements;
import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
-public class GroupDataDefinition implements Serializable {
+import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
+import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+
+
+public class GroupDataDefinition extends ToscaDataDefinition implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1565606165279109427L;
- private String name;
-
- // the id is unique per group instance on graph.
- private String uniqueId;
-
- private String type;
-
- // 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;
-
- // this id is constant and does not changed (also not when changing
- // version). This field cannot be updated by user
- private String invariantUUID;
-
- // the group UUID should be changed when one of the artifacts/component
- // instances has been changed.
- private String groupUUID;
-
- private String description;
+ private String typeUid;
private Integer propertyValueCounter = 0;
public GroupDataDefinition() {
+ super();
+
+ }
+
+ public GroupDataDefinition(Map<String, Object> gr) {
+ super(gr);
+ propertyValueCounter = 0;
+ }
+
+ public GroupDataDefinition(GroupDataDefinition other) {
+ this.setName(other.getName());
+ this.setUniqueId(other.getUniqueId());
+ this.setType(other.getType());
+ this.setVersion(other.getVersion());
+ this.setInvariantUUID(other.getInvariantUUID());
+ this.setDescription(other.getDescription());
+ this.propertyValueCounter = other.propertyValueCounter;
+ this.setGroupUUID(other.getGroupUUID());
+
+ if (other.getMembers() != null) {
+ this.setMembers(new HashMap<String, String>(other.getMembers()));
+ }
+ if (other.getArtifacts() != null) {
+ this.setArtifacts(new ArrayList<String>(other.getArtifacts()));
+ }
+ if (other.getArtifactsUuid() != null) {
+ this.setArtifactsUuid( new ArrayList<String>(other.getArtifactsUuid()));
+ }
+ this.setTypeUid(other.typeUid);
+ this.setProperties(other.getProperties());
}
+
public String getName() {
- return name;
+ return (String) getToscaPresentationValue(JsonPresentationFields.NAME);
}
public void setName(String name) {
- this.name = name;
+ setToscaPresentationValue(JsonPresentationFields.NAME, name);
}
public String getUniqueId() {
- return uniqueId;
+ return (String) getToscaPresentationValue(JsonPresentationFields.UNIQUE_ID);
}
public void setUniqueId(String uniqueId) {
- this.uniqueId = uniqueId;
+ setToscaPresentationValue(JsonPresentationFields.UNIQUE_ID, uniqueId);
}
public String getType() {
- return type;
+ return (String) getToscaPresentationValue(JsonPresentationFields.TYPE);
}
public void setType(String type) {
- this.type = type;
+ setToscaPresentationValue(JsonPresentationFields.TYPE, type);
}
public String getVersion() {
- return version;
+ return (String) getToscaPresentationValue(JsonPresentationFields.VERSION);
}
public void setVersion(String version) {
- this.version = version;
+ setToscaPresentationValue(JsonPresentationFields.VERSION, version);
}
public String getInvariantUUID() {
- return invariantUUID;
+ return (String) getToscaPresentationValue(JsonPresentationFields.INVARIANT_UUID);
}
public void setInvariantUUID(String invariantUUID) {
- this.invariantUUID = invariantUUID;
+ setToscaPresentationValue(JsonPresentationFields.INVARIANT_UUID, invariantUUID);
}
public String getDescription() {
- return description;
+ return (String) getToscaPresentationValue(JsonPresentationFields.DESCRIPTION);
}
public void setDescription(String description) {
- this.description = description;
+ setToscaPresentationValue(JsonPresentationFields.DESCRIPTION, description);
}
public Integer getPropertyValueCounter() {
@@ -115,28 +133,63 @@ public class GroupDataDefinition implements Serializable {
}
public String getGroupUUID() {
- return groupUUID;
+ return (String) getToscaPresentationValue(JsonPresentationFields.GROUP_UUID);
}
public void setGroupUUID(String groupUUID) {
- this.groupUUID = groupUUID;
+ setToscaPresentationValue(JsonPresentationFields.GROUP_UUID, groupUUID);
}
- public GroupDataDefinition(GroupDataDefinition other) {
- this.name = other.name;
- this.uniqueId = other.uniqueId;
- this.type = other.type;
- this.version = other.version;
- this.invariantUUID = other.invariantUUID;
- this.description = other.description;
- this.propertyValueCounter = other.propertyValueCounter;
- this.groupUUID = other.groupUUID;
+ public Map<String, String> getMembers() {
+ return (Map<String, String>) getToscaPresentationValue(JsonPresentationFields.GROUP_MEMBER);
+ }
+
+ public void setMembers(Map<String, String> members) {
+ setToscaPresentationValue(JsonPresentationFields.GROUP_MEMBER, members);
+ }
+
+ public List<String> getArtifacts() {
+ return (List<String> ) getToscaPresentationValue(JsonPresentationFields.GROUP_ARTIFACTS);
+ }
+
+ public void setArtifacts(List<String> artifacts) {
+ setToscaPresentationValue(JsonPresentationFields.GROUP_ARTIFACTS, artifacts);
+ }
+
+ public List<String> getArtifactsUuid() {
+ return (List<String> ) getToscaPresentationValue(JsonPresentationFields.GROUP_ARTIFACTS_UUID);
+ }
+
+ public void setArtifactsUuid(List<String> artifactsUuid) {
+ setToscaPresentationValue(JsonPresentationFields.GROUP_ARTIFACTS_UUID, artifactsUuid);
+ }
+
+ public List<PropertyDataDefinition> getProperties() {
+ return (List<PropertyDataDefinition> ) getToscaPresentationValue(JsonPresentationFields.GROUP_PROPERTIES);
+ }
+
+ public void setProperties(List<PropertyDataDefinition> properties) {
+ setToscaPresentationValue(JsonPresentationFields.GROUP_PROPERTIES, properties);
+ }
+
+ public String getTypeUid() {
+ return typeUid;
+ }
+
+ public void setTypeUid(String typeUid) {
+ this.typeUid = typeUid;
}
@Override
public String toString() {
- return "GroupDataDefinition [name=" + name + ", uniqueId=" + uniqueId + ", type=" + type + ", version="
- + version + ", invariantUUID=" + invariantUUID + ", description=" + description
- + ", propertyValueCounter=" + propertyValueCounter + ", groupUUID=" + groupUUID + "]";
+ return "GroupDataDefinition [propertyValueCounter=" + propertyValueCounter + ", toscaPresentation=" + toscaPresentation + ", getName()=" + getName() + ", getUniqueId()=" + getUniqueId() + ", getType()=" + getType() + ", getVersion()="
+ + getVersion() + ", getInvariantUUID()=" + getInvariantUUID() + ", getDescription()=" + getDescription() + ", getPropertyValueCounter()=" + getPropertyValueCounter() + ", getGroupUUID()=" + getGroupUUID() + ", getMembers()="
+ + getMembers() + ", getArtifacts()=" + getArtifacts() + ", getArtifactsUuid()=" + getArtifactsUuid() + ", getClass()=" + getClass() + ", hashCode()=" + hashCode() + ", toString()="
+ + super.toString() + "]";
}
+
+
+
+
+
}
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
new file mode 100644
index 0000000000..03e8cc34bb
--- /dev/null
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/GroupInstanceDataDefinition.java
@@ -0,0 +1,246 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.datatypes.elements;
+
+import java.io.Serializable;
+import java.util.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;
+
+ public GroupInstanceDataDefinition() {
+ super();
+ }
+ public GroupInstanceDataDefinition(Map<String, Object> gi) {
+ super(gi);
+ }
+ public GroupInstanceDataDefinition(GroupInstanceDataDefinition other) {
+ this.setUniqueId(other.getUniqueId());
+ this.setName(other.getName());
+ this.setGroupUid(other.getGroupUid());
+ this.setCreationTime(other.getCreationTime());
+ this.setModificationTime(other.getModificationTime());
+ this.setPosX(other.getPosX());
+ this.setPosY(other.getPosY());
+ this.setPropertyValueCounter(other.getPropertyValueCounter());
+ this.setNormalizedName(other.getNormalizedName());
+ this.setCustomizationUUID(other.getCustomizationUUID());
+ this.setGroupName(other.getGroupName());
+ this.setInvariantUUID(other.getInvariantUUID());
+ this.setType(other.getType());
+ this.setGroupUUID(other.getGroupUUID());
+ this.setVersion(other.getVersion());
+ this.setDescription(other.getDescription());
+ if(other.getArtifacts() != null)
+ this.setArtifacts(new ArrayList<>(other.getArtifacts()));
+ if(other.getArtifactsUuid() != null)
+ this.setArtifactsUuid(new ArrayList<>(other.getArtifactsUuid()));
+ if(other.getGroupInstanceArtifacts() != null)
+ this.setGroupInstanceArtifacts(new ArrayList<>(other.getGroupInstanceArtifacts()));
+ if(other.getGroupInstanceArtifactsUuid() != null)
+ this.setGroupInstanceArtifactsUuid(new ArrayList<>(other.getGroupInstanceArtifactsUuid()));
+ if(other.getProperties() != null)
+ this.setProperties(new ArrayList<>(other.getProperties()));
+ }
+
+ public String getUniqueId() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.UNIQUE_ID);
+ }
+
+ public void setUniqueId(String uniqueId) {
+ setToscaPresentationValue(JsonPresentationFields.UNIQUE_ID, uniqueId);
+ }
+
+ public String getName() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.NAME);
+ }
+
+ public void setName(String name) {
+ setToscaPresentationValue(JsonPresentationFields.NAME, name);
+ }
+
+ public String getNormalizedName() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.NORMALIZED_NAME);
+ }
+
+ public void setNormalizedName(String normalizedName) {
+ setToscaPresentationValue(JsonPresentationFields.NORMALIZED_NAME, normalizedName);
+ }
+
+ public String getGroupUid() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.GROUP_UNIQUE_ID);
+ }
+
+ public void setGroupUid(String groupUid) {
+ setToscaPresentationValue(JsonPresentationFields.GROUP_UNIQUE_ID, groupUid);
+ }
+
+ public Long getCreationTime() {
+ return (Long) getToscaPresentationValue(JsonPresentationFields.CREATION_TIME);
+ }
+
+ public void setCreationTime(Long creationTime) {
+ setToscaPresentationValue(JsonPresentationFields.CREATION_TIME, creationTime);
+ }
+
+ public Long getModificationTime() {
+ return (Long) getToscaPresentationValue(JsonPresentationFields.MODIFICATION_TIME);
+ }
+
+ public void setModificationTime(Long modificationTime) {
+ setToscaPresentationValue(JsonPresentationFields.MODIFICATION_TIME, modificationTime);
+ }
+
+ public String getPosX() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.POS_X);
+ }
+
+ public void setPosX(String posX) {
+ setToscaPresentationValue(JsonPresentationFields.POS_X, posX);
+ }
+
+ public String getPosY() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.POS_Y);
+ }
+
+ public void setPosY(String posY) {
+ setToscaPresentationValue(JsonPresentationFields.POS_Y, posY);
+ }
+
+ public Integer getPropertyValueCounter() {
+ return (Integer) getToscaPresentationValue(JsonPresentationFields.PROPERTY_VALUE_COUNTER);
+ }
+
+ public void setPropertyValueCounter(Integer propertyValueCounter) {
+ setToscaPresentationValue(JsonPresentationFields.PROPERTY_VALUE_COUNTER, propertyValueCounter);
+ }
+
+ public String getCustomizationUUID() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.CUSTOMIZATION_UUID);
+ }
+
+ public void setCustomizationUUID(String customizationUUID) {
+ setToscaPresentationValue(JsonPresentationFields.CUSTOMIZATION_UUID, customizationUUID);
+ }
+
+ public String getGroupName() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.GROUP_NAME);
+ }
+
+ public void setGroupName(String groupName) {
+ setToscaPresentationValue(JsonPresentationFields.GROUP_NAME, groupName);
+ }
+
+ public String getInvariantUUID() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.INVARIANT_UUID);
+ }
+
+ public void setInvariantUUID(String invariantUUID) {
+ setToscaPresentationValue(JsonPresentationFields.INVARIANT_UUID, invariantUUID);
+ }
+
+ public String getType() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.TYPE);
+ }
+
+ public void setType(String type) {
+ setToscaPresentationValue(JsonPresentationFields.TYPE, type);
+ }
+
+ public String getGroupUUID() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.GROUP_UUID);
+ }
+
+ public void setGroupUUID(String groupUUID) {
+ setToscaPresentationValue(JsonPresentationFields.GROUP_UUID, groupUUID);
+ }
+
+ public String getVersion() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.VERSION);
+ }
+
+ public void setVersion(String version) {
+ setToscaPresentationValue(JsonPresentationFields.VERSION, version);
+ }
+
+ public String getDescription() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.DESCRIPTION);
+ }
+
+ public void setDescription(String description) {
+ setToscaPresentationValue(JsonPresentationFields.DESCRIPTION, description);
+ }
+
+ @SuppressWarnings("unchecked")
+ public List<String> getArtifacts() {
+ return (List<String>) getToscaPresentationValue(JsonPresentationFields.GROUP_ARTIFACTS);
+ }
+
+ public void setArtifacts(List<String> artifacts) {
+ setToscaPresentationValue(JsonPresentationFields.GROUP_ARTIFACTS, artifacts);
+ }
+
+ @SuppressWarnings("unchecked")
+ public List<String> getArtifactsUuid() {
+ return (List<String> ) getToscaPresentationValue(JsonPresentationFields.GROUP_ARTIFACTS_UUID);
+ }
+
+ public void setArtifactsUuid(List<String> artifactsUuid) {
+ setToscaPresentationValue(JsonPresentationFields.GROUP_ARTIFACTS_UUID, artifactsUuid);
+ }
+
+ @SuppressWarnings("unchecked")
+ public List<String> getGroupInstanceArtifacts() {
+ return (List<String>) getToscaPresentationValue(JsonPresentationFields.GROUP_INSTANCE_ARTIFACTS);
+ }
+
+ public void setGroupInstanceArtifacts(List<String> groupInstanceArtifacts) {
+ setToscaPresentationValue(JsonPresentationFields.GROUP_INSTANCE_ARTIFACTS, groupInstanceArtifacts);
+ }
+
+ @SuppressWarnings("unchecked")
+ public List<String> getGroupInstanceArtifactsUuid() {
+ return (List<String>) getToscaPresentationValue(JsonPresentationFields.GROUP_INSTANCE_ARTIFACTS_UUID);
+ }
+
+ public void setGroupInstanceArtifactsUuid(List<String> groupInstanceArtifactsUuid) {
+ setToscaPresentationValue(JsonPresentationFields.GROUP_INSTANCE_ARTIFACTS_UUID, groupInstanceArtifactsUuid);
+ }
+
+ @SuppressWarnings("unchecked")
+ public List<PropertyDataDefinition> getProperties() {
+ return (List<PropertyDataDefinition>) getToscaPresentationValue(JsonPresentationFields.GROUP_INSTANCE_PROPERTIES);
+ }
+
+ public void setProperties(List<PropertyDataDefinition> properties) {
+ setToscaPresentationValue(JsonPresentationFields.GROUP_INSTANCE_PROPERTIES, properties);
+ }
+
+ public static long getSerialversionuid() {
+ return serialVersionUID;
+ }
+}
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 1642d17252..a250ac4308 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
@@ -24,7 +24,9 @@ import java.io.Serializable;
import java.util.List;
import java.util.Map;
-public class GroupTypeDataDefinition implements Serializable {
+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 a84485bef6..33091473cf 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
@@ -22,7 +22,9 @@ package org.openecomp.sdc.be.datatypes.elements;
import java.io.Serializable;
-public class HeatParameterDataDefinition implements Serializable {
+import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+
+public class HeatParameterDataDefinition extends ToscaDataDefinition implements Serializable {
/**
*
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/InputDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/InputDataDefinition.java
new file mode 100644
index 0000000000..fd69127ed3
--- /dev/null
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/InputDataDefinition.java
@@ -0,0 +1,63 @@
+package org.openecomp.sdc.be.datatypes.elements;
+
+import java.util.Map;
+
+public class InputDataDefinition extends PropertyDataDefinition{
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = 8913646848974511031L;
+ String label;
+ Boolean hidden;
+ Boolean immutable;
+
+ public InputDataDefinition(){
+ super();
+ }
+
+ public InputDataDefinition(Map<String, Object> pr) {
+ super(pr);
+
+ }
+
+ public InputDataDefinition(InputDataDefinition p) {
+
+ super(p);
+ this.setLabel(p.getLabel());
+ this.setHidden( p.isHidden());
+ this.setImmutable( p.isImmutable());
+
+
+ }
+
+ public InputDataDefinition(PropertyDataDefinition p) {
+
+ super(p);
+ }
+
+ public Boolean isHidden() {
+ return hidden;
+ }
+
+ public void setHidden(Boolean hidden) {
+ this.hidden = hidden;
+ }
+
+ public Boolean isImmutable() {
+ return immutable;
+ }
+
+ public void setImmutable(Boolean immutable) {
+ this.immutable = immutable;
+ }
+
+ public String getLabel() {
+ return label;
+ }
+
+ public void setLabel(String label) {
+ this.label = label;
+ }
+
+}
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/InputsValueDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/InputsValueDataDefinition.java
index 87c163a3ae..b54c960cf2 100644
--- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/InputsValueDataDefinition.java
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/InputsValueDataDefinition.java
@@ -20,7 +20,9 @@
package org.openecomp.sdc.be.datatypes.elements;
-public class InputsValueDataDefinition {
+import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+
+public class InputsValueDataDefinition extends ToscaDataDefinition {
private String name;
private String value;
private String uniqueId;
@@ -33,7 +35,6 @@ public class InputsValueDataDefinition {
public InputsValueDataDefinition() {
super();
- // TODO Auto-generated constructor stub
}
public String getUniqueId() {
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 46c1ede031..301d888bd2 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
@@ -24,7 +24,9 @@ import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
-public class InterfaceDataDefinition implements Serializable {
+import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+
+public class InterfaceDataDefinition extends ToscaDataDefinition implements Serializable {
/**
*
@@ -46,10 +48,14 @@ public class InterfaceDataDefinition implements Serializable {
* Timestamp of the last resource (artifact) creation
*/
private Long lastUpdateDate;
-
+ /**
+ * Defines an operation available to manage particular aspects of the Node
+ * Type.
+ */
+ private Map<String, OperationDataDefinition> operations = new HashMap<String, OperationDataDefinition>();
+
public InterfaceDataDefinition() {
super();
- // TODO Auto-generated constructor stub
}
public InterfaceDataDefinition(String type, String description) {
@@ -105,5 +111,11 @@ public class InterfaceDataDefinition implements Serializable {
public void setDescription(String description) {
this.description = description;
}
+ public Map<String, OperationDataDefinition> getOperations() {
+ return operations;
+ }
+ public void setOperations(Map<String, OperationDataDefinition> operations) {
+ this.operations = operations;
+ }
}
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
new file mode 100644
index 0000000000..3057c72c67
--- /dev/null
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ListCapabilityDataDefinition.java
@@ -0,0 +1,42 @@
+package org.openecomp.sdc.be.datatypes.elements;
+
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+import org.codehaus.jackson.annotate.JsonCreator;
+import org.codehaus.jackson.annotate.JsonValue;
+
+public class ListCapabilityDataDefinition extends ListDataDefinition<CapabilityDataDefinition> {
+
+ public ListCapabilityDataDefinition(ListCapabilityDataDefinition cdt) {
+ super(cdt);
+
+ }
+
+ @JsonCreator
+ public ListCapabilityDataDefinition(List< CapabilityDataDefinition > listToscaDataDefinition) {
+ super(listToscaDataDefinition);
+ }
+ public ListCapabilityDataDefinition() {
+ super();
+
+ }
+ @JsonValue
+ @Override
+ public List<CapabilityDataDefinition> getListToscaDataDefinition() {
+ return listToscaDataDefinition;
+ }
+
+
+ public void setListToscaDataDefinition(List<CapabilityDataDefinition> listToscaDataDefinition) {
+ this.listToscaDataDefinition = listToscaDataDefinition;
+ }
+
+ public ListCapabilityDataDefinition mergeListItemsByName(ListCapabilityDataDefinition other){
+ Map<String, CapabilityDataDefinition> mapByName = listToMapByName();
+ Map<String, CapabilityDataDefinition> mapOtherByName = other.listToMapByName();
+ mapByName.putAll(mapOtherByName);
+ return new ListCapabilityDataDefinition(mapByName.values().stream().collect(Collectors.toList()));
+ }
+}
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ListDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ListDataDefinition.java
new file mode 100644
index 0000000000..2eb8dcad2e
--- /dev/null
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ListDataDefinition.java
@@ -0,0 +1,69 @@
+package org.openecomp.sdc.be.datatypes.elements;
+
+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.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 {
+
+ protected List<T> listToscaDataDefinition;
+
+ public ListDataDefinition(ListDataDefinition<T> cdt) {
+ super();
+ listToscaDataDefinition = cdt.listToscaDataDefinition;
+
+ }
+
+ @JsonCreator
+ public ListDataDefinition(List<T> listToscaDataDefinition) {
+ super();
+ this.listToscaDataDefinition = listToscaDataDefinition;
+ }
+
+ public ListDataDefinition() {
+ super();
+ }
+
+ public List<T> getListToscaDataDefinition() {
+ return listToscaDataDefinition;
+ }
+
+ public void add(T value) {
+ if (listToscaDataDefinition == null) {
+ listToscaDataDefinition = new ArrayList<T>();
+ }
+ listToscaDataDefinition.add(value);
+ }
+
+ public void delete(T value) {
+ if (listToscaDataDefinition != null) {
+ listToscaDataDefinition.remove(value);
+ }
+ }
+
+ @Override
+ public void setOwnerIdIfEmpty(String ownerId) {
+ if (listToscaDataDefinition != null) {
+ listToscaDataDefinition.forEach(e -> e.setOwnerIdIfEmpty(ownerId));
+ }
+ }
+
+
+ public Map<String, T> listToMapByName() {
+ Map<String, T> mapByName = new HashMap<>();
+ listToscaDataDefinition.forEach(e -> mapByName.put((String)e.getToscaPresentationValue(JsonPresentationFields.NAME), e));
+ return mapByName;
+ }
+
+
+
+
+}
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
new file mode 100644
index 0000000000..e611666d3e
--- /dev/null
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ListMapPropertiesDataDefinition.java
@@ -0,0 +1,36 @@
+package org.openecomp.sdc.be.datatypes.elements;
+
+import java.util.List;
+import java.util.Map;
+
+import org.codehaus.jackson.annotate.JsonCreator;
+import org.codehaus.jackson.annotate.JsonValue;
+
+public class ListMapPropertiesDataDefinition extends ListDataDefinition<MapPropertiesDataDefinition> {
+
+ public ListMapPropertiesDataDefinition(ListMapPropertiesDataDefinition cdt) {
+ super(cdt);
+
+ }
+
+ @JsonCreator
+ public ListMapPropertiesDataDefinition(List< MapPropertiesDataDefinition > listToscaDataDefinition) {
+ super(listToscaDataDefinition);
+ }
+ public ListMapPropertiesDataDefinition() {
+ super();
+
+ }
+ @JsonValue
+ @Override
+ public List<MapPropertiesDataDefinition> getListToscaDataDefinition() {
+ return listToscaDataDefinition;
+ }
+
+
+ public void setMapToscaDataDefinition(List<MapPropertiesDataDefinition> listToscaDataDefinition) {
+ this.listToscaDataDefinition = listToscaDataDefinition;
+ }
+
+
+}
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
new file mode 100644
index 0000000000..4c69958e62
--- /dev/null
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ListRequirementDataDefinition.java
@@ -0,0 +1,43 @@
+package org.openecomp.sdc.be.datatypes.elements;
+
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+import org.codehaus.jackson.annotate.JsonCreator;
+import org.codehaus.jackson.annotate.JsonValue;
+
+public class ListRequirementDataDefinition extends ListDataDefinition<RequirementDataDefinition> {
+
+ public ListRequirementDataDefinition(ListRequirementDataDefinition cdt) {
+ super(cdt);
+
+ }
+
+ @JsonCreator
+ public ListRequirementDataDefinition(List< RequirementDataDefinition > listToscaDataDefinition) {
+ super(listToscaDataDefinition);
+ }
+ public ListRequirementDataDefinition() {
+ super();
+
+ }
+ @JsonValue
+ @Override
+ public List<RequirementDataDefinition> getListToscaDataDefinition() {
+ return listToscaDataDefinition;
+ }
+
+
+ public void setListToscaDataDefinition(List<RequirementDataDefinition> listToscaDataDefinition) {
+ this.listToscaDataDefinition = listToscaDataDefinition;
+ }
+
+ public ListRequirementDataDefinition mergeListItemsByName(ListRequirementDataDefinition other){
+ Map<String, RequirementDataDefinition> mapByName = listToMapByName();
+ Map<String, RequirementDataDefinition> mapOtherByName = other.listToMapByName();
+ mapByName.putAll(mapOtherByName);
+ return new ListRequirementDataDefinition(mapByName.values().stream().collect(Collectors.toList()));
+ }
+
+}
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapArtifactDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapArtifactDataDefinition.java
new file mode 100644
index 0000000000..4c61dd2b81
--- /dev/null
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapArtifactDataDefinition.java
@@ -0,0 +1,45 @@
+package org.openecomp.sdc.be.datatypes.elements;
+
+import java.util.Map;
+
+import org.codehaus.jackson.annotate.JsonCreator;
+import org.codehaus.jackson.annotate.JsonValue;
+
+public class MapArtifactDataDefinition extends MapDataDefinition<ArtifactDataDefinition>{
+
+ private String parentName;
+
+ public MapArtifactDataDefinition(MapDataDefinition cdt, String parentName) {
+ super(cdt);
+ this.parentName = parentName;
+ }
+
+ @JsonCreator
+ public MapArtifactDataDefinition(Map<String, ArtifactDataDefinition > mapToscaDataDefinition) {
+ super(mapToscaDataDefinition);
+ }
+ public MapArtifactDataDefinition() {
+ super();
+
+ }
+ @JsonValue
+ @Override
+ public Map<String, ArtifactDataDefinition> getMapToscaDataDefinition() {
+ return mapToscaDataDefinition;
+ }
+
+
+ public void setMapToscaDataDefinition(Map<String, ArtifactDataDefinition> mapToscaDataDefinition) {
+ this.mapToscaDataDefinition = mapToscaDataDefinition;
+ }
+
+ public String getParentName() {
+ return parentName;
+ }
+
+ public void setParentName(String parentName) {
+ this.parentName = parentName;
+ }
+
+
+}
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapAttributesDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapAttributesDataDefinition.java
new file mode 100644
index 0000000000..817fbebd5c
--- /dev/null
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapAttributesDataDefinition.java
@@ -0,0 +1,45 @@
+package org.openecomp.sdc.be.datatypes.elements;
+
+import java.util.Map;
+
+import org.codehaus.jackson.annotate.JsonCreator;
+import org.codehaus.jackson.annotate.JsonValue;
+
+public class MapAttributesDataDefinition extends MapDataDefinition<AttributeDataDefinition>{
+
+ private String parentName;
+
+ public MapAttributesDataDefinition(MapDataDefinition cdt, String parentName) {
+ super(cdt);
+ this.parentName = parentName;
+ }
+
+ @JsonCreator
+ public MapAttributesDataDefinition(Map<String, AttributeDataDefinition > mapToscaDataDefinition) {
+ super(mapToscaDataDefinition);
+ }
+ public MapAttributesDataDefinition() {
+ super();
+
+ }
+ @JsonValue
+ @Override
+ public Map<String, AttributeDataDefinition> getMapToscaDataDefinition() {
+ return mapToscaDataDefinition;
+ }
+
+
+ public void setMapToscaDataDefinition(Map<String, AttributeDataDefinition> mapToscaDataDefinition) {
+ this.mapToscaDataDefinition = mapToscaDataDefinition;
+ }
+
+ public String getParentName() {
+ return parentName;
+ }
+
+ public void setParentName(String parentName) {
+ this.parentName = parentName;
+ }
+
+
+}
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapCapabiltyProperty.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapCapabiltyProperty.java
new file mode 100644
index 0000000000..42d3f49a7d
--- /dev/null
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapCapabiltyProperty.java
@@ -0,0 +1,27 @@
+package org.openecomp.sdc.be.datatypes.elements;
+
+import java.util.Map;
+
+import org.codehaus.jackson.annotate.JsonCreator;
+import org.codehaus.jackson.annotate.JsonValue;
+
+public class MapCapabiltyProperty extends MapDataDefinition<MapPropertiesDataDefinition> {
+ @JsonCreator
+ public MapCapabiltyProperty(Map<String, MapPropertiesDataDefinition > mapToscaDataDefinition) {
+ super(mapToscaDataDefinition);
+ }
+ public MapCapabiltyProperty() {
+ super();
+
+ }
+ @JsonValue
+ @Override
+ public Map<String, MapPropertiesDataDefinition> getMapToscaDataDefinition() {
+ return mapToscaDataDefinition;
+ }
+
+ public void setMapToscaDataDefinition(Map<String, MapPropertiesDataDefinition> mapToscaDataDefinition) {
+ this.mapToscaDataDefinition = mapToscaDataDefinition;
+ }
+
+}
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
new file mode 100644
index 0000000000..69eecf45c4
--- /dev/null
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapDataDefinition.java
@@ -0,0 +1,60 @@
+package org.openecomp.sdc.be.datatypes.elements;
+
+import java.util.HashMap;
+import java.util.Map;
+
+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;
+
+ public MapDataDefinition(MapDataDefinition<T> cdt) {
+ super();
+ mapToscaDataDefinition = cdt.mapToscaDataDefinition;
+
+ }
+ @JsonCreator
+ public MapDataDefinition(Map<String, T > mapToscaDataDefinition) {
+ super();
+ this.mapToscaDataDefinition = mapToscaDataDefinition;
+ }
+
+ public MapDataDefinition() {
+ super();
+ }
+ @JsonValue
+ public Map<String, T > getMapToscaDataDefinition() {
+ return mapToscaDataDefinition;
+ }
+
+ public void put(String key, T value){
+ if(mapToscaDataDefinition == null){
+ mapToscaDataDefinition = new HashMap<String, T>();
+ }
+ mapToscaDataDefinition.put(key, value);
+ }
+
+ public void delete(String key){
+ if(mapToscaDataDefinition != null && mapToscaDataDefinition.containsKey(key)){
+ mapToscaDataDefinition.remove(key);
+ }
+ }
+
+ public T findByKey(String key){
+ T value = null;
+ if(mapToscaDataDefinition != null && mapToscaDataDefinition.containsKey(key)){
+ value = mapToscaDataDefinition.get(key);
+ }
+ return value;
+ }
+ @Override
+ public void setOwnerIdIfEmpty(String ownerId) {
+ if ( mapToscaDataDefinition != null ){
+ mapToscaDataDefinition.entrySet().forEach(e -> e.getValue().setOwnerIdIfEmpty(ownerId));
+ }
+ }
+
+}
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
new file mode 100644
index 0000000000..acd1a182a6
--- /dev/null
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapGroupsDataDefinition.java
@@ -0,0 +1,45 @@
+package org.openecomp.sdc.be.datatypes.elements;
+
+import java.util.Map;
+
+import org.codehaus.jackson.annotate.JsonCreator;
+import org.codehaus.jackson.annotate.JsonValue;
+
+public class MapGroupsDataDefinition extends MapDataDefinition<GroupInstanceDataDefinition>{
+
+ private String parentName;
+
+ public MapGroupsDataDefinition(MapDataDefinition<GroupInstanceDataDefinition> cdt, String parentName) {
+ super(cdt);
+ this.parentName = parentName;
+ }
+
+ @JsonCreator
+ public MapGroupsDataDefinition(Map<String, GroupInstanceDataDefinition> mapToscaDataDefinition) {
+ super(mapToscaDataDefinition);
+ }
+ public MapGroupsDataDefinition() {
+ super();
+
+ }
+ @JsonValue
+ @Override
+ public Map<String, GroupInstanceDataDefinition> getMapToscaDataDefinition() {
+ return mapToscaDataDefinition;
+ }
+
+
+ public void setMapToscaDataDefinition(Map<String, GroupInstanceDataDefinition> mapToscaDataDefinition) {
+ this.mapToscaDataDefinition = mapToscaDataDefinition;
+ }
+
+ public String getParentName() {
+ return parentName;
+ }
+
+ public void setParentName(String parentName) {
+ this.parentName = parentName;
+ }
+
+
+}
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapListCapabiltyDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapListCapabiltyDataDefinition.java
new file mode 100644
index 0000000000..3053f99ab2
--- /dev/null
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapListCapabiltyDataDefinition.java
@@ -0,0 +1,49 @@
+package org.openecomp.sdc.be.datatypes.elements;
+
+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) {
+ super(cdt);
+
+ }
+
+ @JsonCreator
+ public MapListCapabiltyDataDefinition(Map<String, ListCapabilityDataDefinition> mapToscaDataDefinition) {
+ super(mapToscaDataDefinition);
+ }
+
+ public MapListCapabiltyDataDefinition() {
+ super();
+
+ }
+
+ @JsonValue
+ @Override
+ public Map<String, ListCapabilityDataDefinition> getMapToscaDataDefinition() {
+ return mapToscaDataDefinition;
+ }
+
+ public void add(String key, CapabilityDataDefinition value) {
+ if (mapToscaDataDefinition == null) {
+ mapToscaDataDefinition = new HashMap<>();
+ ListCapabilityDataDefinition newList = new ListCapabilityDataDefinition();
+ newList.add(value);
+ put(key, newList);
+ } else {
+ ListCapabilityDataDefinition existValue = mapToscaDataDefinition.get(key);
+ if (existValue == null) {
+ ListCapabilityDataDefinition newList = new ListCapabilityDataDefinition();
+ newList.add(value);
+ put(key, newList);
+ } else {
+ existValue.getListToscaDataDefinition().add(value);
+ }
+ }
+ }
+}
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
new file mode 100644
index 0000000000..80c2060333
--- /dev/null
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapListRequirementDataDefinition.java
@@ -0,0 +1,50 @@
+package org.openecomp.sdc.be.datatypes.elements;
+
+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) {
+ super(cdt);
+
+ }
+
+ @JsonCreator
+ public MapListRequirementDataDefinition(Map<String, ListRequirementDataDefinition> mapToscaDataDefinition) {
+ super(mapToscaDataDefinition);
+ }
+
+ public MapListRequirementDataDefinition() {
+ super();
+
+ }
+
+ @JsonValue
+ @Override
+ public Map<String, ListRequirementDataDefinition> getMapToscaDataDefinition() {
+ return mapToscaDataDefinition;
+ }
+
+ public void add(String key, RequirementDataDefinition value) {
+ if (mapToscaDataDefinition == null) {
+ mapToscaDataDefinition = new HashMap<>();
+ ListRequirementDataDefinition newList = new ListRequirementDataDefinition();
+ newList.add(value);
+ put(key, newList);
+ } else {
+ ListRequirementDataDefinition existValue = mapToscaDataDefinition.get(key);
+ if (existValue == null) {
+ ListRequirementDataDefinition newList = new ListRequirementDataDefinition();
+ newList.add(value);
+ put(key, newList);
+ } else {
+ existValue.getListToscaDataDefinition().add(value);
+ }
+ }
+ }
+
+}
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
new file mode 100644
index 0000000000..e90fc916e8
--- /dev/null
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapPropertiesDataDefinition.java
@@ -0,0 +1,45 @@
+package org.openecomp.sdc.be.datatypes.elements;
+
+import java.util.Map;
+
+import org.codehaus.jackson.annotate.JsonCreator;
+import org.codehaus.jackson.annotate.JsonValue;
+
+public class MapPropertiesDataDefinition extends MapDataDefinition<PropertyDataDefinition>{
+
+ private String parentName;
+
+ public MapPropertiesDataDefinition(MapDataDefinition cdt, String parentName) {
+ super(cdt);
+ this.parentName = parentName;
+ }
+
+ @JsonCreator
+ public MapPropertiesDataDefinition(Map<String, PropertyDataDefinition > mapToscaDataDefinition) {
+ super(mapToscaDataDefinition);
+ }
+ public MapPropertiesDataDefinition() {
+ super();
+
+ }
+ @JsonValue
+ @Override
+ public Map<String, PropertyDataDefinition> getMapToscaDataDefinition() {
+ return mapToscaDataDefinition;
+ }
+
+
+ public void setMapToscaDataDefinition(Map<String, PropertyDataDefinition> mapToscaDataDefinition) {
+ this.mapToscaDataDefinition = mapToscaDataDefinition;
+ }
+
+ public String getParentName() {
+ return parentName;
+ }
+
+ public void setParentName(String parentName) {
+ this.parentName = parentName;
+ }
+
+
+}
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/OperationDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/OperationDataDefinition.java
index 12c069b142..09370f8311 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
@@ -21,8 +21,11 @@
package org.openecomp.sdc.be.datatypes.elements;
import java.io.Serializable;
+import java.util.Map;
-public class OperationDataDefinition implements Serializable {
+import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+
+public class OperationDataDefinition extends ToscaDataDefinition implements Serializable {
/**
*
@@ -43,22 +46,29 @@ public class OperationDataDefinition implements Serializable {
/** Description of the operation. */
private String description;
+ /** Implementation artifact for the interface. */
+ private ArtifactDataDefinition implementation;
+ /**
+ * This OPTIONAL property contains a list of one or more input parameter
+ * definitions.
+ */
+ // @JsonDeserialize(contentUsing = OperationParameterDeserializer.class)
+ private Map<String, PropertyDataDefinition> inputs;
public OperationDataDefinition() {
super();
- // TODO Auto-generated constructor stub
}
public OperationDataDefinition(String description) {
super();
this.description = description;
-
}
public OperationDataDefinition(OperationDataDefinition p) {
this.uniqueId = p.uniqueId;
this.description = p.description;
-
+ this.implementation = p.implementation;
+ this.inputs = p.inputs;
}
public String getUniqueId() {
@@ -92,5 +102,19 @@ public class OperationDataDefinition implements Serializable {
public void setDescription(String description) {
this.description = description;
}
+ public ArtifactDataDefinition getImplementation() {
+ return implementation;
+ }
+ public void setImplementation(ArtifactDataDefinition implementation) {
+ this.implementation = implementation;
+ }
+
+ public Map<String, PropertyDataDefinition> getInputs() {
+ return inputs;
+ }
+
+ public void setInputs(Map<String, PropertyDataDefinition> inputs) {
+ this.inputs = inputs;
+ }
}
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 9b2b0659b1..8f73764234 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
@@ -24,7 +24,9 @@ import java.io.Serializable;
import java.util.List;
import java.util.Map;
-public class PolicyTypeDataDefinition implements Serializable {
+import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+
+public class PolicyTypeDataDefinition extends ToscaDataDefinition implements Serializable {
/**
*
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..11ad219df3 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
@@ -25,6 +25,7 @@ import java.util.ArrayList;
import java.util.List;
import org.openecomp.sdc.be.datatypes.components.ComponentMetadataDataDefinition;
+import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
public class ProductMetadataDataDefinition extends ComponentMetadataDataDefinition implements Serializable {
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 c522f3e0e9..ed94ce0d87 100644
--- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/PropertyDataDefinition.java
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/PropertyDataDefinition.java
@@ -21,8 +21,17 @@
package org.openecomp.sdc.be.datatypes.elements;
import java.io.Serializable;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
-public class PropertyDataDefinition implements Serializable {
+import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
+import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+
+import fj.data.Either;
+
+
+public class PropertyDataDefinition extends ToscaDataDefinition implements Serializable {
/**
*
@@ -34,7 +43,7 @@ public class PropertyDataDefinition implements Serializable {
// "boolean", "string", "float", "integer", "version" })
private String type;
- private Boolean required;
+ private Boolean required = Boolean.FALSE;
protected boolean definition = false;
@@ -46,18 +55,81 @@ public class PropertyDataDefinition implements Serializable {
private boolean password;
+ private String name;
+
+ private String value;
+
+ private String label;
+ private Boolean hidden = Boolean.FALSE;;
+ private Boolean immutable = Boolean.FALSE;
+
+ private String inputPath;
+
+
+
+ /**
+ * The resource id which this property belongs to
+ */
+ private String parentUniqueId;
+
+
+ private List<GetInputValueDataDefinition> getInputValues;
+
public PropertyDataDefinition() {
+ super();
+ }
+
+ public PropertyDataDefinition(Map<String, Object> pr) {
+ super(pr);
}
public PropertyDataDefinition(PropertyDataDefinition p) {
- this.uniqueId = p.uniqueId;
- this.required = p.required;
- this.defaultValue = p.defaultValue;
- this.description = p.description;
- this.schema = p.schema;
- this.password = p.password;
- this.type = p.type;
+
+ super();
+ this.setUniqueId(p.getUniqueId());
+ this.setRequired(p.isRequired());
+ this.setDefaultValue(p.getDefaultValue());
+ this.setDescription(p.getDescription());
+ this.setSchema(p.getSchema());
+ this.setPassword(p.isPassword());
+ this.setType(p.getType());
+ this.setName(p.getName());
+ this.setValue(p.getValue());
+ this.setRequired(p.isRequired());
+ this.setHidden(p.isHidden());
+ this.setLabel(p.getLabel());
+ this.setImmutable(p.isImmutable());
+ this.setParentUniqueId(p.getParentUniqueId());
+ this.setOwnerId(p.getOwnerId());
+ this.setGetInputValues(p.getInputValues);
+ this.setInputPath(p.getInputPath());
+
+ }
+
+ public String getInputPath() {
+ return inputPath;
+ }
+
+ public void setInputPath(String inputPath) {
+ this.inputPath = inputPath;
+ }
+
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+ public void setValue(String value) {
+ this.value = value;
}
// @Override
@@ -125,11 +197,50 @@ public class PropertyDataDefinition implements Serializable {
this.schema = entrySchema;
}
+ public String getLabel() {
+ return label;
+ }
+
+ public void setLabel(String label) {
+ this.label = label;
+ }
+
+ public Boolean isHidden() {
+ return hidden;
+ }
+
+ public void setHidden(Boolean hidden) {
+ this.hidden = hidden;
+ }
+
+ public Boolean isImmutable() {
+ return immutable;
+ }
+
+ public void setImmutable(Boolean immutable) {
+ this.immutable = immutable;
+ }
+
+
+ public String getParentUniqueId() {
+ return getOwnerId();
+ }
+
+ public void setParentUniqueId(String parentUniqueId) {
+ setOwnerId(parentUniqueId);
+ }
+
+
+ public List<GetInputValueDataDefinition> getGetInputValues() {
+ return getInputValues;
+ }
+
+ public void setGetInputValues(List<GetInputValueDataDefinition> getInputValues) {
+ this.getInputValues = getInputValues;
+ }
@Override
public String toString() {
- return "PropertyDataDefinition [uniqueId=" + uniqueId + ", type=" + type + ", required=" + required
- + ", defaultValue=" + defaultValue + ", description=" + description + ", entrySchema=" + schema
- + ", password=" + password + "]";
+ return "PropertyDataDefinition [uniqueId=" + uniqueId + ", type=" + type + ", required=" + required + ", defaultValue=" + defaultValue + ", description=" + description + ", entrySchema=" + schema + ", parentUniqueId=" + parentUniqueId + ", password=" + password + "]";
}
@Override
@@ -144,6 +255,7 @@ public class PropertyDataDefinition implements Serializable {
result = prime * result + ((schema == null) ? 0 : schema.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
result = prime * result + ((uniqueId == null) ? 0 : uniqueId.hashCode());
+ result = prime * result + ((parentUniqueId == null) ? 0 : parentUniqueId.hashCode());
return result;
}
@@ -185,6 +297,11 @@ public class PropertyDataDefinition implements Serializable {
return false;
} else if (!type.equals(other.type))
return false;
+ if (parentUniqueId == null) {
+ if (other.parentUniqueId != null)
+ return false;
+ } else if (!parentUniqueId.equals(other.parentUniqueId))
+ return false;
if (uniqueId == null) {
if (other.uniqueId != null)
return false;
@@ -192,4 +309,57 @@ public class PropertyDataDefinition implements Serializable {
return false;
return true;
}
+
+ @Override
+ public Object getToscaPresentationValue(JsonPresentationFields field) {
+ switch (field) {
+ case NAME:
+ return name;
+ case UNIQUE_ID:
+ return uniqueId;
+ case PASSWORD:
+ return password;
+ case TYPE:
+ return type;
+ case DEFINITION:
+ return definition;
+ case VALUE:
+ return value;
+ case DEFAULT_VALUE:
+ return defaultValue;
+ default:
+ return super.getToscaPresentationValue(field);
+ }
+ }
+
+ protected <T extends PropertyDataDefinition> T overrideDataDefinition(T other, boolean allowDefaultValueOverride){
+ if(this.getType().equals(other.getType())){
+ other.setOwnerId(getOwnerId());
+ if(allowDefaultValueOverride)
+ other.setDefaultValue(getDefaultValue());
+ return other;
+ }
+ return null;
+ }
+
+
+ //return Either.right(propertyName) if an illegal merge was attempted (overriding data type is forbidden)
+ public static <T extends PropertyDataDefinition> Either<Map<String, T>, String> mergeProperties(Map<String, T> derivedProps, Map<String, T> importedProps, boolean allowDefaultValueOverride){
+ for(T property : importedProps.values()){
+ derivedProps.merge(property.getName(), property, (derivedProp, importedProp) -> derivedProp.overrideDataDefinition(importedProp, allowDefaultValueOverride));
+ //validate merge success
+ if(!derivedProps.containsKey(property.getName()))
+ return Either.right(property.getName());
+ }
+ return Either.left(derivedProps);
+ }
+
+
+
+ public static <T extends PropertyDataDefinition> Map<String, T> listToMapByName(List<T> propertiesList) {
+ return propertiesList.stream()
+ .collect(Collectors.toMap(p -> p.getName(), p -> p));
+ }
+
+
}
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/PropertyRule.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/PropertyRule.java
index c9ef85ac66..c5297e273a 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
@@ -23,8 +23,9 @@ package org.openecomp.sdc.be.datatypes.elements;
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 implements Serializable {
+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
new file mode 100644
index 0000000000..de9127d08c
--- /dev/null
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/RelationshipInstDataDefinition.java
@@ -0,0 +1,193 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.datatypes.elements;
+
+import java.io.Serializable;
+import java.util.List;
+
+import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
+import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+
+public class RelationshipInstDataDefinition extends ToscaDataDefinition implements Serializable {
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1104043358598884458L;
+
+ public RelationshipInstDataDefinition(RelationshipInstDataDefinition cdt) {
+ super();
+ this.setUniqueId(cdt.getUniqueId());
+ this.setDescription(cdt.getDescription());
+ this.setType(cdt.getType());
+ this.setValidSourceTypes(cdt.getValidSourceTypes());
+ this.setVersion(cdt.getVersion());
+ this.setCreationTime(cdt.getCreationTime());
+ this.setModificationTime(cdt.getModificationTime());
+ this.setCapabilityOwnerId(cdt.getCapabilityOwnerId());
+ this.setRequirementOwnerId(cdt.getRequirementOwnerId());
+ this.setCapabiltyId(cdt.getCapabiltyId());
+ this.setRequirementId(cdt.getRequirementId());
+ this.setFromId(cdt.getFromId());
+ this.setToId(cdt.getToId());
+ this.setRequirement(cdt.getRequirement());
+ this.setCapability(cdt.getCapabilty());
+
+ }
+
+ public void setRequirement(String requirement) {
+ setToscaPresentationValue(JsonPresentationFields.REQUIREMENT, requirement);
+ }
+
+ public String getRequirement() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.REQUIREMENT);
+ }
+ public void setCapability(String capabilty) {
+ setToscaPresentationValue(JsonPresentationFields.CAPAPILITY, capabilty);
+ }
+
+ public String getCapabilty() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.CAPAPILITY);
+ }
+ public void setToId(Object toId) {
+ setToscaPresentationValue(JsonPresentationFields.TO_ID, toId);
+ }
+
+ public void setFromId(Object fromId) {
+ setToscaPresentationValue(JsonPresentationFields.FROM_ID, fromId);
+ }
+
+ public String getToId() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.TO_ID);
+ }
+
+ public String getFromId() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.FROM_ID);
+ }
+
+ public void setRequirementId(Object requirementId) {
+ setToscaPresentationValue(JsonPresentationFields.REQUIREMENT_ID, requirementId);
+ }
+
+ public void setCapabiltyId(Object capabiltyId) {
+ setToscaPresentationValue(JsonPresentationFields.CAPABILITY_ID, capabiltyId);
+ }
+
+ public String getRequirementId() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.REQUIREMENT_ID);
+ }
+
+ public String getCapabiltyId() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.CAPABILITY_ID);
+ }
+
+ public void setRequirementOwnerId(Object requirementOwnerId) {
+ setToscaPresentationValue(JsonPresentationFields.REQUIREMENT_OWNER_ID, requirementOwnerId);
+ }
+
+ public String getRequirementOwnerId() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.REQUIREMENT_OWNER_ID);
+ }
+
+ public void setCapabilityOwnerId(Object capabilityOwnerId) {
+ setToscaPresentationValue(JsonPresentationFields.CAPABILTY_OWNER_ID, capabilityOwnerId);
+ }
+
+ public String getCapabilityOwnerId() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.CAPABILTY_OWNER_ID);
+ }
+
+ public RelationshipInstDataDefinition() {
+ }
+
+ public String getUniqueId() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.UNIQUE_ID);
+ }
+
+ public void setUniqueId(String uniqueId) {
+ setToscaPresentationValue(JsonPresentationFields.UNIQUE_ID, uniqueId);
+ }
+
+ public String getDescription() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.DESCRIPTION);
+ }
+
+ public void setDescription(String description) {
+ setToscaPresentationValue(JsonPresentationFields.DESCRIPTION, description);
+ }
+
+ /** Identifies the type of the capability. */
+ public String getType() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.TYPE);
+ }
+
+ public void setType(String type) {
+ setToscaPresentationValue(JsonPresentationFields.TYPE, type);
+ }
+
+ public List<String> getValidSourceTypes() {
+ return (List<String>) getToscaPresentationValue(JsonPresentationFields.VALID_SOURCE_TYPES);
+ }
+
+ public void setValidSourceTypes(List<String> validSourceTypes) {
+ setToscaPresentationValue(JsonPresentationFields.VALID_SOURCE_TYPES, validSourceTypes);
+ }
+
+ public String getVersion() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.VERSION);
+ }
+
+ public void setVersion(String version) {
+ setToscaPresentationValue(JsonPresentationFields.VERSION, version);
+ }
+
+ public Long getCreationTime() {
+ return (Long) getToscaPresentationValue(JsonPresentationFields.CREATION_TIME);
+
+ }
+
+ public void setCreationTime(Long creationTime) {
+ setToscaPresentationValue(JsonPresentationFields.CREATION_TIME, creationTime);
+ }
+
+ public Long getModificationTime() {
+ return (Long) getToscaPresentationValue(JsonPresentationFields.MODIFICATION_TIME);
+ }
+
+ public void setModificationTime(Long modificationTime) {
+ setToscaPresentationValue(JsonPresentationFields.MODIFICATION_TIME, modificationTime);
+ }
+
+ @Override
+ public String toString() {
+ String uniqueId = getUniqueId();
+ String description = getDescription();
+ String type = getType();
+ List<String> validSourceTypes = getValidSourceTypes();
+ String version = getVersion();
+ Long creationTime = getCreationTime();
+ Long modificationTime = getModificationTime();
+
+ return "RelationshipTypeDataDefinition [uniqueId=" + uniqueId + ", description=" + description + ", type=" + type + ", validSourceTypes=" + validSourceTypes + ", version=" + version + ", creationTime=" + creationTime + ", modificationTime="
+ + modificationTime + "]";
+ }
+
+}
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/RelationshipTypeDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/RelationshipTypeDataDefinition.java
deleted file mode 100644
index 0f7c56842f..0000000000
--- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/RelationshipTypeDataDefinition.java
+++ /dev/null
@@ -1,128 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.datatypes.elements;
-
-import java.io.Serializable;
-import java.util.List;
-
-public class RelationshipTypeDataDefinition implements Serializable {
-
- /**
- *
- */
- private static final long serialVersionUID = 1104043358598884458L;
-
- private String uniqueId;
-
- private String description;
-
- /** Identifies the type of the capability. */
- private String type;
-
- private List<String> validSourceTypes;
-
- private String version;
-
- private Long creationTime;
-
- private Long modificationTime;
-
- // private String derivedFrom;
-
- public RelationshipTypeDataDefinition(RelationshipTypeDataDefinition cdt) {
- super();
- this.uniqueId = cdt.getUniqueId();
- this.description = cdt.getDescription();
- this.type = cdt.getType();
- this.validSourceTypes = cdt.getValidSourceTypes();
- this.version = cdt.getVersion();
- this.creationTime = cdt.getCreationTime();
- this.modificationTime = cdt.getModificationTime();
- }
-
- public RelationshipTypeDataDefinition() {
-
- }
-
- public String getUniqueId() {
- return uniqueId;
- }
-
- public void setUniqueId(String uniqueId) {
- this.uniqueId = uniqueId;
- }
-
- 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 List<String> getValidSourceTypes() {
- return validSourceTypes;
- }
-
- public void setValidSourceTypes(List<String> validSourceTypes) {
- this.validSourceTypes = validSourceTypes;
- }
-
- public String getVersion() {
- return version;
- }
-
- public void setVersion(String version) {
- this.version = version;
- }
-
- public Long getCreationTime() {
- return creationTime;
- }
-
- public void setCreationTime(Long creationTime) {
- this.creationTime = creationTime;
- }
-
- public Long getModificationTime() {
- return modificationTime;
- }
-
- public void setModificationTime(Long modificationTime) {
- this.modificationTime = modificationTime;
- }
-
- @Override
- public String toString() {
- return "RelationshipTypeDataDefinition [uniqueId=" + uniqueId + ", description=" + description + ", type="
- + type + ", validSourceTypes=" + validSourceTypes + ", version=" + version + ", creationTime="
- + creationTime + ", modificationTime=" + modificationTime + "]";
- }
-
-}
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
new file mode 100644
index 0000000000..7defd1df3c
--- /dev/null
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/RequirementDataDefinition.java
@@ -0,0 +1,308 @@
+package org.openecomp.sdc.be.datatypes.elements;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
+import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+
+public class RequirementDataDefinition extends ToscaDataDefinition implements Serializable {
+ /**
+ *
+ */
+ public final static String MIN_OCCURRENCES = "1";
+ public final static String MAX_OCCURRENCES = "UNBOUNDED";
+ public final static String MAX_DEFAULT_OCCURRENCES = "1";
+
+ private static final long serialVersionUID = -8840549489409274532L;
+
+ public RequirementDataDefinition() {
+ super();
+ this.setMinOccurrences( MIN_OCCURRENCES );
+ this.setMaxOccurrences( MAX_OCCURRENCES);
+ this.setLeftOccurrences( MAX_OCCURRENCES);
+ }
+
+ public RequirementDataDefinition(RequirementDataDefinition other) {
+ this.setUniqueId(other.getUniqueId());
+ this.setName(other.getName());
+ this.setCapability(other.getCapability());
+ this.setNode(other.getNode());
+ this.setRelationship(other.getRelationship());
+ this.setOwnerId(other.getOwnerId());
+ this.setOwnerName(other.getOwnerName());
+ this.setMinOccurrences(other.getMinOccurrences());
+ this.setMaxOccurrences(other.getMaxOccurrences());
+ this.setLeftOccurrences(other.getLeftOccurrences());
+ this.setPath(other.getPath());
+ this.setSource(other.getSource());
+
+ }
+
+ /**
+ * Unique id of the requirement
+ */
+ public String getUniqueId() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.UNIQUE_ID);
+ }
+
+ public void setUniqueId(String uniqueId) {
+ setToscaPresentationValue(JsonPresentationFields.UNIQUE_ID, uniqueId);
+ }
+
+ public String getName() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.NAME);
+ }
+
+ public void setName(String name) {
+ setToscaPresentationValue(JsonPresentationFields.NAME, name);
+ }
+
+ /**
+ * specify the capability type
+ */
+
+ public String getCapability() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.CAPAPILITY);
+ }
+
+ public void setCapability(String capability) {
+ setToscaPresentationValue(JsonPresentationFields.CAPAPILITY, capability);
+ }
+
+ /**
+ * specify the node type(Optional by tosca)
+ */
+ public String getNode() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.NODE);
+ }
+
+ public void setNode(String node) {
+ setToscaPresentationValue(JsonPresentationFields.NODE, node);
+ }
+
+ /**
+ * specify the relationship type(Optional by tosca)
+ */
+ public String getRelationship() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.RELATIONSHIP);
+ }
+
+ public void setRelationship(String relationship) {
+ setToscaPresentationValue(JsonPresentationFields.RELATIONSHIP, relationship);
+ }
+
+ // public RequirementImplDef getRequirementImpl() {
+ // return requirementImpl;
+ // }
+ //
+ // public void setRequirementImpl(RequirementImplDef requirementImpl) {
+ // this.requirementImpl = requirementImpl;
+ // }
+
+ // specifies the resource instance holding this requirement
+ public String getOwnerId() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.OWNER_ID);
+ }
+
+ public void setOwnerId(String ownerId) {
+ setToscaPresentationValue(JsonPresentationFields.OWNER_ID, ownerId);
+ }
+
+ public String getOwnerName() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.OWNER_NAME);
+ }
+
+ public void setOwnerName(String ownerName) {
+ setToscaPresentationValue(JsonPresentationFields.OWNER_NAME, ownerName);
+ }
+
+ public String getMinOccurrences() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.MIN_OCCURRENCES);
+ }
+
+ public void setMinOccurrences(String minOccurrences) {
+ setToscaPresentationValue(JsonPresentationFields.MIN_OCCURRENCES, minOccurrences);
+ }
+
+ public String getLeftOccurrences() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.LEFT_OCCURRENCES);
+ }
+
+ public void setLeftOccurrences(String leftOccurrences) {
+ setToscaPresentationValue(JsonPresentationFields.LEFT_OCCURRENCES, leftOccurrences);
+ }
+
+ public String getMaxOccurrences() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.MAX_OCCURRENCES);
+ }
+
+ public void setMaxOccurrences(String maxOccurrences) {
+ setToscaPresentationValue(JsonPresentationFields.MAX_OCCURRENCES, maxOccurrences);
+ }
+
+ public void setPath(List<String> path) {
+ setToscaPresentationValue(JsonPresentationFields.PATH, path);
+ }
+
+ public List<String> getPath() {
+ return (List<String>) getToscaPresentationValue(JsonPresentationFields.PATH);
+ }
+
+ public void setSource(String source) {
+ setToscaPresentationValue(JsonPresentationFields.SOURCE, source);
+ }
+
+ public String getSource() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.SOURCE);
+ }
+
+ public void addToPath(String elementInPath) {
+ List<String> path = getPath();
+ if (path == null) {
+ path = new ArrayList<>();
+ }
+ path.add(elementInPath);
+ setPath(path);
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ String name = getUniqueId();
+ String uniqueId = getUniqueId();
+ String capability = getCapability();
+ String node = getNode();
+ String relationship = getRelationship();
+ String ownerId = getOwnerId();
+ String ownerName = getOwnerName();
+ String minOccurrences = getMinOccurrences();
+ String maxOccurrences = getMaxOccurrences();
+ String leftOccurrences = getLeftOccurrences();
+
+ List<String> path = this.getPath();
+ String source = getSource();
+
+ result = prime * result + ((capability == null) ? 0 : capability.hashCode());
+ result = prime * result + ((name == null) ? 0 : name.hashCode());
+ result = prime * result + ((node == null) ? 0 : node.hashCode());
+ result = prime * result + ((ownerId == null) ? 0 : ownerId.hashCode());
+ result = prime * result + ((ownerName == null) ? 0 : ownerName.hashCode());
+ result = prime * result + ((relationship == null) ? 0 : relationship.hashCode());
+ result = prime * result + ((uniqueId == null) ? 0 : uniqueId.hashCode());
+ result = prime * result + ((minOccurrences == null) ? 0 : minOccurrences.hashCode());
+ result = prime * result + ((maxOccurrences == null) ? 0 : maxOccurrences.hashCode());
+ result = prime * result + ((leftOccurrences == null) ? 0 : leftOccurrences.hashCode());
+ result = prime * result + ((path == null) ? 0 : path.hashCode());
+ result = prime * result + ((source == null) ? 0 : source.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;
+ RequirementDataDefinition other = (RequirementDataDefinition) obj;
+
+ String name = getUniqueId();
+ String uniqueId = getUniqueId();
+ String capability = getCapability();
+ String node = getNode();
+ String relationship = getRelationship();
+ String ownerId = getOwnerId();
+ String ownerName = getOwnerName();
+ String minOccurrences = getMinOccurrences();
+ String maxOccurrences = getMaxOccurrences();
+ String leftOccurrences = getLeftOccurrences();
+ List<String> path = this.getPath();
+ String source = getSource();
+
+ if (capability == null) {
+ if (other.getCapability() != null)
+ return false;
+ } else if (!capability.equals(other.getCapability()))
+ return false;
+ if (name == null) {
+ if (other.getName() != null)
+ return false;
+ } else if (!name.equals(other.getName()))
+ return false;
+ if (node == null) {
+ if (other.getNode() != null)
+ return false;
+ } else if (!node.equals(other.getNode()))
+ return false;
+ if (ownerId == null) {
+ if (other.getOwnerId() != null)
+ return false;
+ } else if (!ownerId.equals(other.getOwnerId()))
+ return false;
+ if (ownerName == null) {
+ if (other.getOwnerName() != null)
+ return false;
+ } else if (!ownerName.equals(other.getOwnerName()))
+ return false;
+ if (relationship == null) {
+ if (other.getRelationship() != null)
+ return false;
+ } else if (!relationship.equals(other.getRelationship()))
+ return false;
+ if (uniqueId == null) {
+ if (other.getUniqueId() != null)
+ return false;
+ } else if (!uniqueId.equals(other.getUniqueId()))
+ return false;
+ if (minOccurrences == null) {
+ if (other.getMinOccurrences() != null)
+ return false;
+ } else if (!minOccurrences.equals(other.getMinOccurrences()))
+ return false;
+ if (maxOccurrences == null) {
+ if (other.getMaxOccurrences() != null)
+ return false;
+ } else if (!maxOccurrences.equals(other.getMaxOccurrences()))
+ return false;
+ if (leftOccurrences == null) {
+ if (other.getLeftOccurrences() != null)
+ return false;
+ } else if (!leftOccurrences.equals(other.getLeftOccurrences()))
+ return false;
+ if (path == null) {
+ if (other.getPath() != null)
+ return false;
+ } else if (!path.equals(other.getPath()))
+ return false;
+ if (source == null) {
+ if (other.getSource() != null)
+ return false;
+ } else if (!source.equals(other.getSource()))
+ return false;
+ return true;
+ }
+
+ @Override
+ public String toString() {
+ String name = getUniqueId();
+ String uniqueId = getUniqueId();
+ String capability = getCapability();
+ String node = getNode();
+ String relationship = getRelationship();
+ String ownerId = getOwnerId();
+ String ownerName = getOwnerName();
+ String minOccurrences = getMinOccurrences();
+ String maxOccurrences = getMaxOccurrences();
+ String leftOccurrences = getLeftOccurrences();
+ List<String> path = this.getPath();
+ String source = getSource();
+
+ return "RequirementDefinition [uniqueId=" + uniqueId + ", name=" + name + ", capability=" + capability + ", node=" + node + ", relationship=" + relationship + ", ownerId=" + ownerId + ", ownerName=" + ownerName + ", minOccurrences="
+ + minOccurrences + ", maxOccurrences=" + maxOccurrences + ",leftOccurrences=" + leftOccurrences + ", path=" + path + ", source=" + source + "]";
+ }
+
+}
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 3845a706b1..bc24efa411 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
@@ -21,34 +21,44 @@
package org.openecomp.sdc.be.datatypes.elements;
import java.io.Serializable;
+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;
+
/**
* Schema allows to create new types that can be used along TOSCA definitions.
*/
-public class SchemaDefinition implements Serializable {
+public class SchemaDefinition extends ToscaDataDefinition implements Serializable {
/**
*
*/
private static final long serialVersionUID = 7117891081909380577L;
-
+
private String derivedFrom;
private List<String> constraints;
private Map<String, PropertyDataDefinition> properties;
private PropertyDataDefinition property;
+
+
public SchemaDefinition() {
+ super();
}
public SchemaDefinition(String derivedFrom, List<String> constraints,
Map<String, PropertyDataDefinition> properties) {
- this.derivedFrom = derivedFrom;
- this.constraints = constraints;
- this.properties = properties;
+ super();
+
+ this.setDerivedFrom(derivedFrom);
+ this.setConstraints( constraints);
+ this.setProperties( properties);
+
}
public String getDerivedFrom() {
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
new file mode 100644
index 0000000000..78261ff07a
--- /dev/null
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/ComponentFieldsEnum.java
@@ -0,0 +1,51 @@
+package org.openecomp.sdc.be.datatypes.enums;
+
+public enum ComponentFieldsEnum {
+
+ PROPERTIES("properties"),
+ INPUTS("inputs"),
+ USERS("users"),
+ GROUPS("groups"),
+ COMPONENT_INSTANCES("componentInstances"),
+ COMPONENT_INSTANCES_PROPERTIES("componentInstancesProperties"),
+ CAPABILITIES("capabilities"),
+ REQUIREMENTS("requirements"),
+ ALL_VERSIONS("allVersions"),
+ ADDITIONAL_INFORMATION("additionalInformation"),
+ ARTIFACTS("artifacts"),
+ INTERFACES("interfaces"),
+ DERIVED_FROM("derivedFrom"),
+ ATTRIBUTES("attributes"),
+ COMPONENT_INSTANCES_ATTRIBUTES("componentInstancesAttributes"),
+ COMPONENT_INSTANCE_INPUTS("componentInstancesInputs"),
+ COMPONENT_INSTANCE_RELATION("componentInstancesRelations"),
+ DEPLOYMENT_ARTIFACTS("deploymentArtifacts"),
+ TOSCA_ARTIFACTS("toscaArtifacts"),
+ SERVICE_API_ARTIFACTS("serviceApiArtifacts"),
+ METADATA("metadata"),
+ CATEGORIES("categories"),
+ INSTANCE_CAPABILTY_PROPERTIES("instanceCapabiltyProperties");
+
+
+ private String value;
+
+ private ComponentFieldsEnum(String value) {
+ this.value = value;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+
+ public static ComponentFieldsEnum findByValue(String value) {
+ ComponentFieldsEnum ret = null;
+ for (ComponentFieldsEnum curr : ComponentFieldsEnum.values()) {
+ if (curr.getValue().equals(value)) {
+ ret = curr;
+ return ret;
+ }
+ }
+ return ret;
+ }
+}
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/ComponentTypeEnum.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/ComponentTypeEnum.java
index 9da0b81d3b..dbaab71c53 100644
--- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/ComponentTypeEnum.java
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/ComponentTypeEnum.java
@@ -21,7 +21,11 @@
package org.openecomp.sdc.be.datatypes.enums;
public enum ComponentTypeEnum {
- RESOURCE("Resource"), SERVICE("Service"), RESOURCE_INSTANCE("Resource Instance"), PRODUCT("Product"), SERVICE_INSTANCE("Service Instance");
+ RESOURCE("Resource"),
+ SERVICE("Service"),
+ RESOURCE_INSTANCE("Resource Instance"),
+ PRODUCT("Product"),
+ SERVICE_INSTANCE("Service Instance");
private String value;
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/FilterKeyEnum.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/FilterKeyEnum.java
index bf8ae79467..38d297a893 100644
--- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/FilterKeyEnum.java
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/FilterKeyEnum.java
@@ -25,7 +25,7 @@ import java.util.List;
import java.util.stream.Collectors;
public enum FilterKeyEnum {
- SUB_CATEGORY("subCategory"), CATEGORY("category"), DISTRIBUTION_STATUS("distributionStatus");
+ RESOURCE_TYPE("resourceType"), SUB_CATEGORY("subCategory"), CATEGORY("category"), DISTRIBUTION_STATUS("distributionStatus"), NAME_FRAGMENT("nameFragment");
private String name;
@@ -44,9 +44,9 @@ public enum FilterKeyEnum {
public static List<String> getValidFiltersByAssetType(ComponentTypeEnum assetType) {
switch (assetType) {
case RESOURCE:
- return getAllFilters().subList(0, 2);
+ return getAllFilters().subList(0, 3);
case SERVICE:
- return getAllFilters().subList(1, 3);
+ return getAllFilters().subList(2, 4);
default:
return null;
}
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/GraphPropertyEnum.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/GraphPropertyEnum.java
new file mode 100644
index 0000000000..5a7b2d40f3
--- /dev/null
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/GraphPropertyEnum.java
@@ -0,0 +1,103 @@
+package org.openecomp.sdc.be.datatypes.enums;
+
+import java.util.ArrayList;
+import java.util.List;
+
+
+
+public enum GraphPropertyEnum {
+// field name class type unique indexed
+// stored in graph index
+ UNIQUE_ID ("uid", String.class, true, true),
+ LABEL ("nodeLabel", String.class, false, true),
+ JSON ("json", String.class, false, false),
+ METADATA ("metadata", String.class, false, false),
+ VERSION ("version", String.class, false, true),
+ STATE ("state", String.class, false, true),
+ IS_HIGHEST_VERSION ("highestVersion", Boolean.class, false, true),
+ IS_DELETED ("deleted", Boolean.class, false, true),
+ NORMALIZED_NAME ("normalizedName", String.class, false, true),
+ NAME ("name", String.class, false, true),
+ TOSCA_RESOURCE_NAME ("toscaResourceName", String.class, false, true),
+ DISTRIBUTION_STATUS ("distributionStatus", String.class, false, false),
+ RESOURCE_TYPE ("resourceType", String.class, false, true),
+ COMPONENT_TYPE ("componentType", String.class, false, true),
+ UUID ("uuid", String.class, false, true),
+ SYSTEM_NAME ("systemName", String.class, false, true),
+ IS_ABSTRACT ("abstract", Boolean.class, false, true),
+ INVARIANT_UUID ("invariantUuid", String.class, false, true),
+ CSAR_UUID ("csarUuid", String.class, false, true),
+ //used for user (old format, no json for users)
+ USERID ("userId", String.class, true, true),
+ ROLE ("role", String.class, false, false),
+ FIRST_NAME ("firstName", String.class, false, false),
+ LAST_NAME ("lastName", String.class, false, false),
+ EMAIL ("email", String.class, false, false),
+ LAST_LOGIN_TIME ("lastLoginTime", Long.class, false, false),
+ //used for category (old format, no json for categories)
+ ICONS ("icons", String.class, false, false);
+
+ private String property;
+ private Class clazz;
+ private boolean unique;
+ private boolean indexed;
+
+ GraphPropertyEnum(String property, Class clazz, boolean unique, boolean indexed) {
+ this.property = property;
+ this.clazz = clazz;
+ this.unique = unique;
+ this.indexed = indexed;
+ }
+
+ public static GraphPropertyEnum getByProperty(String property){
+ for(GraphPropertyEnum currProperty :GraphPropertyEnum.values()){
+ if(currProperty.getProperty().equals(property)){
+ return currProperty;
+ }
+ }
+ return null;
+ }
+
+ public String getProperty() {
+ return property;
+ }
+
+ public void setProperty(String property) {
+ this.property = property;
+ }
+
+ public Class getClazz() {
+ return clazz;
+ }
+
+ public void setClazz(Class clazz) {
+ this.clazz = clazz;
+ }
+
+ public boolean isUnique() {
+ return unique;
+ }
+
+ public void setUnique(boolean unique) {
+ this.unique = unique;
+ }
+
+ public boolean isIndexed() {
+ return indexed;
+ }
+
+ public void setIndexed(boolean indexed) {
+ this.indexed = indexed;
+ }
+
+ public static List<String> getAllProperties() {
+
+ List<String> arrayList = new ArrayList<String>();
+
+ for (GraphPropertyEnum graphProperty : GraphPropertyEnum.values()) {
+ arrayList.add(graphProperty.getProperty());
+ }
+
+ return arrayList;
+ }
+}
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
new file mode 100644
index 0000000000..6004e65949
--- /dev/null
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/JsonPresentationFields.java
@@ -0,0 +1,192 @@
+package org.openecomp.sdc.be.datatypes.enums;
+
+import org.codehaus.jackson.annotate.JsonCreator;
+import org.codehaus.jackson.annotate.JsonValue;
+
+
+//@JsonDeserialize(using = MyDeserializer.class)
+
+public enum JsonPresentationFields {
+ UNIQUE_ID ("uniqueId", GraphPropertyEnum.UNIQUE_ID),
+ HIGHEST_VERSION ("highestVersion", GraphPropertyEnum.IS_HIGHEST_VERSION),
+ LIFECYCLE_STATE ("lifecycleState", GraphPropertyEnum.STATE),
+ CREATION_DATE ("creationDate", null),
+ LAST_UPDATE_DATE ("lastUpdateDate", null),
+ SYSTEM_NAME ("systemName", GraphPropertyEnum.SYSTEM_NAME),
+ NAME ("name", GraphPropertyEnum.NAME),
+ VERSION ("version", GraphPropertyEnum.VERSION),
+ NORMALIZED_NAME ("normalizedName", GraphPropertyEnum.NORMALIZED_NAME),
+ UUID ("UUID", GraphPropertyEnum.UUID),
+ RESOURCE_TYPE ("resourceType", GraphPropertyEnum.RESOURCE_TYPE),
+ COMPONENT_TYPE ("componentType", GraphPropertyEnum.COMPONENT_TYPE),
+ IS_DELETED ("isDeleted", GraphPropertyEnum.IS_DELETED),
+ ECOMP_GENERATED_NAMING ("ecompGeneratedNaming", null),
+ NAMING_POLICY ("namingPolicy", null),
+ TOSCA_RESOURCE_NAME ("toscaResourceName", GraphPropertyEnum.TOSCA_RESOURCE_NAME),
+ DESCRIPTION ("description", null),
+ TYPE ("type", null),
+ DERIVED_FROM ("derivedFrom", null),
+ VENDOR_NAME ("vendorName", null),
+ VENDOR_RELEASE ("vendorRelease", null),
+ CONFORMANCE_LEVEL ("conformanceLevel", null),
+ ICON ("icon", null),
+ TAGS ("tags", null),
+ INVARIANT_UUID ("invariantUuid", GraphPropertyEnum.INVARIANT_UUID),
+ CSAR_UUID ("csarUuid", GraphPropertyEnum.CSAR_UUID),
+ CSAR_VERSION ("csarVersion", null),
+ IMPORTED_TOSCA_CHECKSUM ("importedToscaChecksum", null),
+ CONTACT_ID ("contactId", null),
+ PROJECT_CODE ("projectCode", null),
+ DISTRIBUTION_STATUS ("distributionStatus", GraphPropertyEnum.DISTRIBUTION_STATUS),
+ DERIVED_FROM_GENERIC_TYPE("derivedFromGenericType", null),
+ DERIVED_FROM_GENERIC_VERSION("derivedFromGenericVersion", null),
+
+ ////Artifact
+ ARTIFACT_TYPE ("artifactType", null),
+ ARTIFACT_REF ("artifactRef", null),
+ ARTIFACT_REPOSITORY ("artifactRepository", null),
+ ARTIFACT_CHECKSUM ("artifactChecksum", null),
+ ARTIFACT_CREATOR ("artifactCreator", null),
+ USER_ID_CREATOR ("userIdCreator", null),
+ USER_ID_LAST_UPDATER ("userIdLastUpdater", null),
+ CREATOR_FULL_NAME ("creatorFullName", null),
+ UPDATER_FULL_NAME ("updaterFullName", null),
+
+ ES_ID ("esId", null),
+ ARTIFACT_LABEL ("artifactLabel", null),
+ IS_ABSTRACT ("mandatory", null),
+ ARTIFACT_DISPLAY_NAME ("artifactDisplayName", null),
+ API_URL ("apiUrl", null),
+ SERVICE_API ("serviceApi", null),
+ ARTIFACT_VERSION ("artifactVersion", null),
+ ARTIFACT_UUID ("artifactUUID", null),
+ PAYLOAD_UPDATE_DATE ("payloadUpdateDate", null),
+ HEAT_PARAMS_UPDATE_DATE ("heatParamsUpdateDate", null),
+ GENERATED ("generated", null),
+ ARTIFACT_GROUP_TYPE ("artifactGroupType", null),
+ ARTIFACT_TIMEOUT ("timeout", null),
+ REQUIRED_ARTIFACTS ("requiredArtifacts", null),
+ DUPLICATED ("duplicated", null),
+ HEAT_PARAMETERS ("heatParameters", null),
+ GENERATED_FROM_ID ("generatedFromId", null),
+
+
+ // end artifacts
+
+
+ //property
+ DEFINITION ("definition", null),
+ DEFAULT_VALUE ("defaultValue", null),
+ REQUIRED ("required", null),
+ PASSWORD ("password", null),
+ CONSTRAINTS ("constraints", null),
+ PROPERTIES ("properties", null),
+ PROPERTY ("property", null),
+ SCHEMA ("schema", null),
+ VALUE ("value", null),
+ PARENT_UNIQUE_ID ("parentUniqueId", null),
+
+ COMPONENT_INSTANCES ("componentInstances", null),
+ RELATIONS ("relations", null),
+
+
+ //capability
+ VALID_SOURCE_TYPE ("validSourceTypes", null),
+ CREATION_TIME ("creationTime", null),
+ MODIFICATION_TIME ("modificationTime", null),
+ CAPABILITY_SOURCES ("capabilitySources", null),
+ MAX_OCCURRENCES ("maxOccurrences", null),
+ MIN_OCCURRENCES ("minOccurrences", null),
+ OWNER_NAME ("ownerName", null),
+ OWNER_ID ("ownerId", null),
+ LEFT_OCCURRENCES ("leftOccurences", null),
+ CAPABILITY_ID ("capabiltyId", null),
+ PATH ("path", null),
+ SOURCE ("source", null),
+
+ //Requirement
+ CAPAPILITY ("capability", null),
+ NODE ("node", null),
+ RELATIONSHIP ("relationship", null),
+ VALID_SOURCE_TYPES ("validSourceTypes", null),
+ REQUIREMENT_ID ("requirementId", null),
+
+ //Relation
+ CAPABILTY_OWNER_ID ("capabilityOwnerId", null),
+ REQUIREMENT_OWNER_ID ("requirementOwnerId", null),
+ FROM_ID ("fromId", null),
+ TO_ID ("toId", null),
+ REQUIREMENT ("requirement", null),
+
+ //Groups
+
+ GROUP_INVARIANT_UUID ("invariantUUID", null),
+ GROUP_UUID ("groupUUID", null),
+ GROUP_MEMBER ("members", null),
+ GROUP_ARTIFACTS ("artifacts", null),
+ GROUP_ARTIFACTS_UUID (" artifactsUuid", null),
+ GROUP_PROPERTIES (" properties", null),
+ GROUP_UNIQUE_ID (" groupUid", null),
+ POS_X (" posX", null),
+ POS_Y (" posY", null),
+ PROPERTY_VALUE_COUNTER (" propertyValueCounter", null),
+ CUSTOMIZATION_UUID (" customizationUUID", null),
+ GROUP_NAME (" groupName", null),
+ GROUP_INSTANCE_ARTIFACTS (" groupInstanceArtifacts", null),
+ GROUP_INSTANCE_ARTIFACTS_UUID (" groupInstanceArtifactsUuid", null),
+ GROUP_INSTANCE_PROPERTIES (" groupInstancesProperties", null),
+
+ ;
+
+
+ private String presentation;
+ private GraphPropertyEnum storedAs;
+
+ JsonPresentationFields(String presentation, GraphPropertyEnum storedAs) {
+ this.presentation = presentation;
+ this.storedAs = storedAs;
+ }
+
+ @JsonValue
+ public String getPresentation() {
+ return presentation;
+ }
+
+ public void setPresentation(String presentation) {
+ this.presentation = presentation;
+ }
+
+ public GraphPropertyEnum getStoredAs() {
+ return storedAs;
+ }
+
+ public void setStoredAs(GraphPropertyEnum storedAs) {
+ this.storedAs = storedAs;
+ }
+
+ public static String getPresentationByGraphProperty(GraphPropertyEnum property) {
+ for(JsonPresentationFields currPresentation : JsonPresentationFields.values()){
+ if(currPresentation.getStoredAs() == property){
+ return currPresentation.getPresentation();
+ }
+ }
+ return null;
+ }
+
+ @Override
+ public String toString() {
+ // TODO Auto-generated method stub
+ return presentation;
+ }
+
+ @JsonCreator
+ public static JsonPresentationFields getByPresentation(String presentation) {
+ for (JsonPresentationFields inst : JsonPresentationFields.values()) {
+ if (inst.getPresentation().equals(presentation)) {
+ return inst;
+ }
+ }
+ return null;
+ }
+
+}
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/NodeTypeEnum.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/NodeTypeEnum.java
index 2938b4576a..a2ca46cff4 100644
--- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/NodeTypeEnum.java
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/NodeTypeEnum.java
@@ -60,7 +60,8 @@ public enum NodeTypeEnum {
PolicyType("policyType"),
Group("group"),
UserFunctionalMenu("userFunctionalMenu"),
- Input("input");
+ Input("input"),
+ GroupInstance("groupInstance"), ;
private String name;
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 14b3e4ef86..0d837762e2 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
@@ -23,10 +23,11 @@ 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),
+ 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);
+ VL("VL", "VL (Virtual Link)", "resource instance", ComponentTypeEnum.RESOURCE),
+ VFCMT("VFCMT", "VFCMT (VFC Monitoring Template)", "resource instance", ComponentTypeEnum.RESOURCE);
private String value;
private String displayValue;
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/ResourceTypeEnum.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/ResourceTypeEnum.java
index 7864a2cf5f..d3652c238f 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
@@ -20,14 +20,17 @@
package org.openecomp.sdc.be.datatypes.enums;
+/**
+ * Resource Type Enum
+ * @author mshitrit
+ *
+ */
public enum ResourceTypeEnum {
- VFC("VFC (Virtual Function Component)"),
- VF("VF"/* (Virtual Function)" */),
- CP("CP (Connection Point)"),
- VL("VL (Virtual Link)");
+ VFC("VFC (Virtual Function Component)"), VF("VF"/* (Virtual Function)" */), CP("CP (Connection Point)"),
+ VL( "VL (Virtual Link)"), VFCMT("VFCMT (VFC Monitoring Template)"), ABSTRACT("Abstract (Generic VFC/VF/Service Type)");
- String value;
+ private String value;
private ResourceTypeEnum(String value) {
this.value = value;
@@ -36,8 +39,43 @@ public enum ResourceTypeEnum {
public String getValue() {
return value;
}
-
- public static boolean contains(String type) {
+
+ public static ResourceTypeEnum getType(String type) {
+ for (ResourceTypeEnum e : ResourceTypeEnum.values()) {
+ if (e.name().equals(type)) {
+ return e;
+ }
+ }
+ return null;
+ }
+
+ public static ResourceTypeEnum getTypeByName(String type) {
+ for (ResourceTypeEnum e : ResourceTypeEnum.values()) {
+ if (e.name().equalsIgnoreCase(type)) {
+ return e;
+ }
+ }
+ return null;
+ }
+/**
+ * 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())) {
+ return e;
+ }
+ }
+ return null;
+ }
+ /**
+ * Checks if enum exist with given type
+ * @param type
+ * @return
+ */
+ public static boolean containsName(String type) {
for (ResourceTypeEnum e : ResourceTypeEnum.values()) {
if (e.name().equals(type)) {
@@ -46,4 +84,18 @@ public enum ResourceTypeEnum {
}
return false;
}
+ /**
+ * Checks if enum exist with given type ignare case
+ * @param type
+ * @return
+ */
+ public static boolean containsIgnoreCase(String type) {
+
+ for (ResourceTypeEnum e : ResourceTypeEnum.values()) {
+ if (e.name().toLowerCase().equals(type.toLowerCase())) {
+ return true;
+ }
+ }
+ return false;
+ }
}
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
new file mode 100644
index 0000000000..d0f480b588
--- /dev/null
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/tosca/ToscaDataDefinition.java
@@ -0,0 +1,50 @@
+package org.openecomp.sdc.be.datatypes.tosca;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.codehaus.jackson.annotate.JsonCreator;
+import org.codehaus.jackson.annotate.JsonIgnore;
+import org.codehaus.jackson.annotate.JsonValue;
+import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
+
+public abstract class ToscaDataDefinition {
+
+ protected Map<String, Object> toscaPresentation;
+
+
+ public ToscaDataDefinition(){
+ toscaPresentation = new HashMap<String, Object>();
+ }
+ @JsonCreator
+ public ToscaDataDefinition(Map<String, Object> art){
+ toscaPresentation = art;
+ }
+ @JsonValue
+ public Object getToscaPresentationValue(JsonPresentationFields name) {
+ if (toscaPresentation != null && toscaPresentation.containsKey(name.getPresentation())) {
+ return toscaPresentation.get(name.getPresentation());
+ }
+ return null;
+ }
+
+ public void setToscaPresentationValue(JsonPresentationFields name, Object value) {
+ if (toscaPresentation == null && value !=null) {
+ toscaPresentation = new HashMap<String, Object>();
+ }
+ toscaPresentation.put(name.getPresentation(), value);
+
+ }
+ public void setOwnerIdIfEmpty(String ownerId){
+ if ( getOwnerId() == null ){
+ setOwnerId(ownerId);
+ }
+ }
+ public void setOwnerId(String ownerId){
+ setToscaPresentationValue(JsonPresentationFields.OWNER_ID, ownerId);
+ }
+
+ public String getOwnerId(){
+ return (String) getToscaPresentationValue(JsonPresentationFields.OWNER_ID);
+ }
+}
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/utils/CommonBeUtils.java b/common-be/src/main/java/org/openecomp/sdc/be/utils/CommonBeUtils.java
index 54a55811e3..8ad45a31f1 100644
--- a/common-be/src/main/java/org/openecomp/sdc/be/utils/CommonBeUtils.java
+++ b/common-be/src/main/java/org/openecomp/sdc/be/utils/CommonBeUtils.java
@@ -24,19 +24,15 @@ import org.openecomp.sdc.common.api.Constants;
public class CommonBeUtils {
/**
- * Compares two ASDC versions of a component. It's for internal usage, so
- * the assumption is that the versions are in valid format.
+ * Compares two ASDC versions of a component. It's for internal usage, so the assumption is that the versions are in valid format.
*
* @param firstVersion
* - version in format major.minor or just major (e.g, 2.0 or 2)
* @param secondVersion
* - version in format major.minor or just major (e.g, 2.0 or 2)
* @return Returns true iff:<br>
- * 1) first version's major number is higher than second's (e.g.,
- * firstVersion = 1.1, secondVersion = 0.3)<br>
- * 2) major version are equal, but first's minor version is higher
- * than second's (e.g., firstVersion = 0.10, secondVersion = 0.9)
- * <br>
+ * 1) first version's major number is higher than second's (e.g., firstVersion = 1.1, secondVersion = 0.3)<br>
+ * 2) major version are equal, but first's minor version is higher than second's (e.g., firstVersion = 0.10, secondVersion = 0.9) <br>
*/
public static boolean compareAsdcComponentVersions(String firstVersion, String secondVersion) {
String[] firstVersionNums = firstVersion.split("\\.");
@@ -54,6 +50,39 @@ public class CommonBeUtils {
}
}
+
+ /**
+ * Compares two version strings.
+ *
+ * Use this instead of String.compareTo() for a non-lexicographical
+ * comparison that works for version strings. e.g. "1.10".compareTo("1.6").
+ *
+ * @note It does not work if "1.10" is supposed to be equal to "1.10.0".
+ *
+ * @param str1 a string of ordinal numbers separated by decimal points.
+ * @param str2 a string of ordinal numbers separated by decimal points.
+ * @return The result is a negative integer if str1 is _numerically_ less than str2.
+ * The result is a positive integer if str1 is _numerically_ greater than str2.
+ * The result is zero if the strings are _numerically_ equal.
+ */
+ public static int conformanceLevelCompare(String str1, String str2) {
+ String[] vals1 = str1.split("\\.");
+ String[] vals2 = str2.split("\\.");
+ int i = 0;
+ // set index to first non-equal ordinal or length of shortest version string
+ while (i < vals1.length && i < vals2.length && vals1[i].equals(vals2[i])) {
+ i++;
+ }
+ // compare first non-equal ordinal number
+ if (i < vals1.length && i < vals2.length) {
+ int diff = Integer.valueOf(vals1[i]).compareTo(Integer.valueOf(vals2[i]));
+ return Integer.signum(diff);
+ }
+ // the strings are equal or one string is a substring of the other
+ // e.g. "1.2.3" = "1.2.3" or "1.2.3" < "1.2.3.4"
+ return Integer.signum(vals1.length - vals2.length);
+ }
+
public static String generateToscaResourceName(String resourceType, String resourceSystemName) {
return Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + resourceType.toLowerCase() + "." + resourceSystemName;
}
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/workers/Worker.java b/common-be/src/main/java/org/openecomp/sdc/be/workers/Worker.java
index 83be4b2ee5..9fb81d0e12 100644
--- a/common-be/src/main/java/org/openecomp/sdc/be/workers/Worker.java
+++ b/common-be/src/main/java/org/openecomp/sdc/be/workers/Worker.java
@@ -63,7 +63,7 @@ public class Worker<T extends Job<E>, E> implements Runnable {
} catch (Exception e) {
BeEcompErrorManager.getInstance().logInternalFlowError("executingJobFailed",
"failed during job execution worker" + workerName, BeEcompErrorManager.ErrorSeverity.ERROR);
- log.debug("worker:" + workerName + " nothing to do stoping", e);
+ log.debug("worker: {} nothing to do stoping", workerName,e);
}
}
diff --git a/common-be/src/test/java/org/openecomp/sdc/be/utils/CommonBeUtilsTest.java b/common-be/src/test/java/org/openecomp/sdc/be/utils/CommonBeUtilsTest.java
index 9c3582ba8a..e11609b424 100644
--- a/common-be/src/test/java/org/openecomp/sdc/be/utils/CommonBeUtilsTest.java
+++ b/common-be/src/test/java/org/openecomp/sdc/be/utils/CommonBeUtilsTest.java
@@ -39,4 +39,17 @@ public class CommonBeUtilsTest {
assertFalse(CommonBeUtils.compareAsdcComponentVersions("1", "1.0"));
assertTrue(CommonBeUtils.compareAsdcComponentVersions("2", "1.15"));
}
+
+ @Test
+ public void testConformanceLevelCompare() {
+
+ assertTrue(CommonBeUtils.conformanceLevelCompare("1.1", "0.15") > 0);
+ assertTrue(CommonBeUtils.conformanceLevelCompare("0.5", "0.5") == 0);
+ assertTrue(CommonBeUtils.conformanceLevelCompare("0.5", "0.6") < 0);
+ assertTrue(CommonBeUtils.conformanceLevelCompare("1.5", "2.6") < 0);
+ assertTrue(CommonBeUtils.conformanceLevelCompare("1.5", "1.5.3") < 0);
+ assertTrue(CommonBeUtils.conformanceLevelCompare("2.5", "1.5.300") > 0);
+ assertTrue(CommonBeUtils.conformanceLevelCompare("0.10", "0.1") > 0);
+ assertTrue(CommonBeUtils.conformanceLevelCompare("2", "1.15") > 0);
+ }
}
diff --git a/distribution-ci/.gitignore b/distribution-ci/.gitignore
deleted file mode 100644
index ae3c172604..0000000000
--- a/distribution-ci/.gitignore
+++ /dev/null
@@ -1 +0,0 @@
-/bin/
diff --git a/distribution-ci/etc/asdc-client.jks b/distribution-ci/etc/asdc-client.jks
deleted file mode 100644
index eb0a0d35af..0000000000
--- a/distribution-ci/etc/asdc-client.jks
+++ /dev/null
Binary files differ
diff --git a/distribution-ci/etc/asdcclientstore.jks b/distribution-ci/etc/asdcclientstore.jks
deleted file mode 100644
index 5dc006db0c..0000000000
--- a/distribution-ci/etc/asdcclientstore.jks
+++ /dev/null
Binary files differ
diff --git a/distribution-ci/log4j.properties b/distribution-ci/log4j.properties
deleted file mode 100644
index 80b2ca8825..0000000000
--- a/distribution-ci/log4j.properties
+++ /dev/null
@@ -1,17 +0,0 @@
-log4j.rootCategory=DEBUG, CONSOLE, LOGFILE
-
-log4j.logger.org.openecomp.sdc=TRACE, CONSOLE, LOGFILE
-
-# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
-log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
-log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
-log4j.appender.CONSOLE.layout.ConversionPattern=%p %d{yyyy-MM-dd HH:mm:ss.SSS Z} %c{1} - %m%n
-
-# LOGFILE is set to be a File appender using a PatternLayout.
-log4j.appender.LOGFILE=org.apache.log4j.RollingFileAppender
-log4j.appender.LOGFILE.File=logs/wordnik.log
-log4j.appender.LOGFILE.Append=true
-log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
-log4j.appender.LOGFILE.layout.ConversionPattern=%p %d{yyyy-MM-dd HH:mm:ss.SSS Z} %c{1} - %m%n
-log4j.appender.LOGFILE.MaxFileSize=10MB
-log4j.appender.LOGFILE.MaxBackupIndex=10
diff --git a/distribution-ci/pom.xml b/distribution-ci/pom.xml
deleted file mode 100644
index d8603be39a..0000000000
--- a/distribution-ci/pom.xml
+++ /dev/null
@@ -1,107 +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>
- <groupId>org.openecomp.sdc.sdc-main</groupId>
- <artifactId>distribution-ci</artifactId>
-
- <parent>
- <groupId>org.openecomp.sdc</groupId>
- <artifactId>sdc-main</artifactId>
- <version>1610.1.3</version>
- </parent>
-
-
-
- <dependencies>
-
- <dependency>
- <groupId>org.testng</groupId>
- <artifactId>testng</artifactId>
- <version>6.9.10</version>
- <scope>test</scope>
- </dependency>
-
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-api</artifactId>
- <version>1.7.10</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>com.google.guava</groupId>
- <artifactId>guava</artifactId>
- <version>${guava.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>org.apache.commons</groupId>
- <artifactId>commons-lang3</artifactId>
- <version>${lang3.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <!-- yaml to object converter -->
- <dependency>
- <groupId>org.yaml</groupId>
- <artifactId>snakeyaml</artifactId>
- <version>1.14</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>com.google.code.gson</groupId>
- <artifactId>gson</artifactId>
- <version>2.3.1</version>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>org.json</groupId>
- <artifactId>json</artifactId>
- <version>20131018</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>org.openecomp.sdc</groupId>
- <artifactId>sdc-distribution-client</artifactId>
- <version>1.1.2</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>org.openecomp.sdc</groupId>
- <artifactId>asdc-tests</artifactId>
- <version>${asdc.full.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>4.12</version>
- <scope>compile</scope>
- </dependency>
-
- </dependencies>
-
- <build>
- <plugins>
-
- <!-- ================================================== -->
- <!-- Set the JDK compiler version. -->
- <!-- ================================================== -->
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-compiler-plugin</artifactId>
- <version>2.5.1</version>
- <inherited>true</inherited>
- <configuration>
- <source>1.8</source>
- <target>1.8</target>
- </configuration>
- </plugin>
- </plugins>
- </build>
-</project>
diff --git a/distribution-ci/src/main/java/org/openecomp/test/BaseInit.java b/distribution-ci/src/main/java/org/openecomp/test/BaseInit.java
deleted file mode 100644
index b056b35b75..0000000000
--- a/distribution-ci/src/main/java/org/openecomp/test/BaseInit.java
+++ /dev/null
@@ -1,122 +0,0 @@
-package org.openecomp.test;
-
-//import static org.junit.Assert.assertNotNull;
-//import static org.junit.Assert.assertTrue;
-//
-//import java.io.IOException;
-//
-//import org.junit.Before;
-//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.enums.NormativeTypesEnum;
-//import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
-//import org.openecomp.sdc.ci.tests.datatypes.enums.ServiceCategoriesEnum;
-//import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
-////import org.openecomp.sdc.ci.tests.execute.lifecycle.LCSbaseTest;
-//import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
-//import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails;
-//import org.openecomp.sdc.ci.tests.utils.ArtifactUtils;
-//import org.openecomp.sdc.ci.tests.utils.DbUtils;
-////import org.openecomp.sdc.ci.tests.utils.ResourceUtils;
-////import org.openecomp.sdc.ci.tests.utils.ServiceUtils;
-//import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
-//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.ServiceRestUtils;
-//import org.openecomp.sdc.common.api.ArtifactTypeEnum;
-
-public abstract class BaseInit {
-
-
-// protected ResourceReqDetails resourceDetails;
-// protected ResourceReqDetails resourceDetails1;
-// protected ServiceReqDetails serviceDetails;
-// protected ServiceReqDetails serviceDetails2;
-// protected ComponentInstanceReqDetails resourceInstanceReqDetails;
-// protected ComponentInstanceReqDetails resourceInstanceReqDetails2;
-// protected User sdncDesignerDetails1;
-// protected User sdncTesterDeatails1;
-// protected User sdncAdminDetails1;
-// protected ArtifactReqDetails heatArtifactDetails;
-//
-// protected ArtifactReqDetails defaultArtifactDetails;
-// //protected ResourceUtils resourceUtils;
-// protected ArtifactUtils artifactUtils;
-//
-//
-// //static ServiceUtils serviceUtils = new ServiceUtils();
-// public BaseInit(TestName testName, String className) {
-// super(testName, className);
-// }
-// @Before
-// public void before() throws Exception{
-//
-// initializeMembers();
-//
-// createComponents();
-//
-// }
-// public void initializeMembers() throws IOException, Exception {
-//
-// resourceDetails = ElementFactory.getDefaultResource();
-// resourceDetails1 = ElementFactory.getDefaultResource("secondResource", NormativeTypesEnum.ROOT);
-// serviceDetails = ElementFactory.getDefaultService();
-// serviceDetails2 = ElementFactory.getDefaultService("newTestService2", ServiceCategoriesEnum.MOBILITY, "al1976");
-// sdncDesignerDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
-// sdncTesterDeatails1 = ElementFactory.getDefaultUser(UserRoleEnum.TESTER);
-// sdncAdminDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
-// heatArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType());
-// resourceInstanceReqDetails = ElementFactory.getDefaultComponentInstance();
-// resourceInstanceReqDetails2 = ElementFactory.getDefaultComponentInstance();
-//
-// }
-// protected void createComponents() throws Exception{
-//
-//// Create resources
-// RestResponse response = ResourceRestUtils.createResource(resourceDetails, sdncDesignerDetails1);
-// assertTrue("create request returned status:" + response.getErrorCode(),response.getErrorCode() == 201);
-// assertNotNull("resource uniqueId is null:", resourceDetails.getUniqueId());
-//
-// response = ResourceRestUtils.createResource(resourceDetails1, sdncDesignerDetails1);
-// assertTrue("create request returned status:" + response.getErrorCode(),response.getErrorCode() == 201);
-// assertNotNull("resource uniqueId is null:", resourceDetails1.getUniqueId());
-//
-//// Create services
-// response = ServiceRestUtils.createService(serviceDetails, sdncDesignerDetails1);
-// assertTrue("create request returned status:" + response.getErrorCode(),response.getErrorCode() == 201);
-// assertNotNull("service uniqueId is null:", serviceDetails.getUniqueId());
-//
-// response = ServiceRestUtils.createService(serviceDetails2, sdncDesignerDetails1);
-// assertTrue("create request returned status:" + response.getErrorCode(),response.getErrorCode() == 201);
-// assertNotNull("service uniqueId is null:", serviceDetails2.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);
-//
-// ArtifactReqDetails heatArtifactDetails1 = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType());
-// response = ArtifactRestUtils.addInformationalArtifactToResource(heatArtifactDetails1, sdncDesignerDetails1, resourceDetails1.getUniqueId());
-// assertTrue("add HEAT artifact to resource request returned status:" + response.getErrorCode(),response.getErrorCode() == 200);
-//
-// // certified resources
-//// response = LCSbaseTest.certifyResource(resourceDetails);
-//// assertTrue("certify resource request returned status:" + response.getErrorCode(),response.getErrorCode() == 200);
-////
-//// response = LCSbaseTest.certifyResource(resourceDetails1);
-//// assertTrue("certify resource request returned status:" + response.getErrorCode(),response.getErrorCode() == 200);
-////
-//// add resource instance with HEAT deployment artifact to the service
-// resourceInstanceReqDetails.setUniqueId(resourceDetails.getUniqueId());
-//// response = ServiceUtils.createResourceInstance(resourceInstanceReqDetails, sdncDesignerDetails1, serviceDetails.getUniqueId());
-//// assertTrue("response code is not 200, returned: " + response.getErrorCode(),response.getErrorCode() == 200);
-//
-// DbUtils.cleanAllAudits();
-//
-//
-// }
-
-}
diff --git a/distribution-ci/src/main/java/org/openecomp/test/CallableTask.java b/distribution-ci/src/main/java/org/openecomp/test/CallableTask.java
deleted file mode 100644
index 814fe9ae46..0000000000
--- a/distribution-ci/src/main/java/org/openecomp/test/CallableTask.java
+++ /dev/null
@@ -1,57 +0,0 @@
-package org.openecomp.test;
-
-//import java.util.concurrent.Callable;
-//
-//import org.openecomp.sdc.api.IDistributionClient;
-//import org.openecomp.sdc.api.results.IDistributionClientResult;
-//import org.openecomp.sdc.impl.DistributionClientFactory;
-//import org.openecomp.sdc.be.model.Service;
-//import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
-
-public class CallableTask {
-
-// NotificationCallback notifCallback = null;
-// //private ServiceUtils serviceUtils;
-// private Service service;
-//
-// //public CallableTask(ServiceUtils serviceUtils, Service service) {
-// public CallableTask(Service service) {
-// //this.serviceUtils = serviceUtils;
-// this.service = service;
-// }
-//
-// public NotificationCallback getNotifCallback() {
-// return notifCallback;
-// }
-//
-// @Override
-// public Boolean call() throws Exception {
-//
-// IDistributionClient client = DistributionClientFactory.createDistributionClient();
-//
-// notifCallback = new NotificationCallback(client);
-// IDistributionClientResult result = client.init(new SimpleConfiguration(), notifCallback);
-//
-// System.out.println("result.getDistributionMessageResult: " + result.getDistributionMessageResult());
-//
-// System.out.println("Starting client...");
-// IDistributionClientResult start = client.start();
-// System.out.println(start.getDistributionMessageResult());
-//
-//// RestResponse changeStateToDISTRIBUTED = serviceUtils.changeStateToDISTRIBUTED(service, UserUtils.getGovernorDetails1());
-// ServiceReqDetails serviceDetails = new ServiceReqDetails();
-// serviceDetails.setUniqueId(service.getUniqueId());
-// //RestResponse changeStateToDISTRIBUTED = serviceUtils.changeDistributionStatus(serviceDetails, "1.0", UserUtils.getGovernorDetails1(), "change", DistributionStatusEnum.DISTRIBUTED);
-// //assertTrue("response code is not 200, returned :" + changeStateToDISTRIBUTED.getErrorCode(), changeStateToDISTRIBUTED.getErrorCode() == 200);
-//
-//
-//// while (simpleCallback.getSimpleCallbackResults().size()<3){
-// System.err.println("Sleeping...");
-// Thread.sleep(5000);
-// System.err.println("Finished Sleeping...");
-//// }
-//
-// return true;
-// }
-
-}
diff --git a/distribution-ci/src/main/java/org/openecomp/test/ClientTest.java b/distribution-ci/src/main/java/org/openecomp/test/ClientTest.java
deleted file mode 100644
index 1a10860828..0000000000
--- a/distribution-ci/src/main/java/org/openecomp/test/ClientTest.java
+++ /dev/null
@@ -1,33 +0,0 @@
-package org.openecomp.test;
-
-import org.slf4j.LoggerFactory;
-
-import org.openecomp.sdc.api.IDistributionClient;
-import org.openecomp.sdc.api.results.IDistributionClientResult;
-import org.openecomp.sdc.impl.DistributionClientFactory;
-
-import ch.qos.logback.classic.Level;
-import ch.qos.logback.classic.LoggerContext;
-
-public class ClientTest {
- public static void main(String[] args) throws InterruptedException {
-
- LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
- lc.getLogger("org.apache.http").setLevel(Level.INFO);
-
- IDistributionClient client = DistributionClientFactory.createDistributionClient();
-
- IDistributionClientResult result = client.init(new SimpleConfiguration(), new NotificationCallback(client));
- System.out.println(result.getDistributionMessageResult());
-
- System.out.println("Starting client...");
- IDistributionClientResult startResult = client.start();
-
- // Thread.sleep(10000);
- // client.stop();
-
- System.out.println(startResult.getDistributionMessageResult());
-
- }
-
-}
diff --git a/distribution-ci/src/main/java/org/openecomp/test/E2eFlows.java b/distribution-ci/src/main/java/org/openecomp/test/E2eFlows.java
deleted file mode 100644
index 521fc21312..0000000000
--- a/distribution-ci/src/main/java/org/openecomp/test/E2eFlows.java
+++ /dev/null
@@ -1,108 +0,0 @@
-package org.openecomp.test;
-
-import org.junit.rules.TestName;
-
-//import static org.junit.Assert.assertTrue;
-//
-//import java.util.concurrent.ExecutorService;
-//import java.util.concurrent.Executors;
-//import java.util.concurrent.Future;
-//import java.util.concurrent.TimeUnit;
-//
-//import org.junit.After;
-//import org.junit.Test;
-//import org.junit.rules.TestName;
-//
-//import org.openecomp.sdc.api.IDistributionClient;
-//import org.openecomp.sdc.api.notification.IArtifactInfo;
-//import org.openecomp.sdc.api.notification.INotificationData;
-//import org.openecomp.sdc.api.results.IDistributionClientResult;
-//import org.openecomp.sdc.impl.DistributionClientFactory;
-//import org.openecomp.sdc.utils.DistributionActionResultEnum;
-//import org.openecomp.sdc.be.model.DistributionStatusEnum;
-//import org.openecomp.sdc.be.model.Service;
-//import org.openecomp.sdc.ci.tests.execute.lifecycle.LCSbaseTest;
-//import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
-////import org.openecomp.sdc.ci.tests.users.UserUtils;
-//import org.openecomp.sdc.ci.tests.utils.DbUtils;
-//import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
-
-public class E2eFlows {
-
-
-
-// private IDistributionClient client = DistributionClientFactory.createDistributionClient();
-// private ExecutorService newSingleThreadExecutor = Executors.newSingleThreadExecutor();
-//
-// private CallableTask callableTask;
-// private NotificationCallback notifCallback;
-// private IArtifactInfo iArtifactInfo;
-//
-
-
-//
-// @After
-// public void after() throws Exception {
-// client.stop();
-// Thread.sleep(5000);
-// }
-//
-// // ---------------------------------Success
-// // scenario--------------------------------------------------------------------------------
-//
-// @Test
-// public void distributeService() throws Exception{
-// createServiceReadyForDistribution();
-// //RestResponse changeStateToDISTRIBUTED = serviceUtils.changeDistributionStatus(serviceDetails, "1.0", UserUtils.getGovernorDetails1(), "change", DistributionStatusEnum.DISTRIBUTED);
-// //assertTrue("response code is not 200, returned :" + changeStateToDISTRIBUTED.getErrorCode(), changeStateToDISTRIBUTED.getErrorCode() == 200);
-//
-// }
-// @Test
-// public void E2E_Success() throws Exception {
-// Service service = createServiceReadyForDistribution();
-//
-//// clean audit
-// DbUtils.cleanAllAudits();
-//
-// //Create task to run in BG
-// callableTask = new CallableTask(service);
-//
-// //Run the task in BG
-// System.err.println("Executing Task...");
-// Future<Boolean> f = newSingleThreadExecutor.submit(callableTask);
-//
-// //Wait for task to complete and return with result
-//
-//// while (!f.isDone()){
-// System.err.println("Waiting for result...");
-// // Thread.sleep(30000);
-//// }
-// Boolean result = f.get(15, TimeUnit.SECONDS);
-//
-// System.out.println("future:" + result);
-//
-// //Check Results
-// notifCallback = callableTask.getNotifCallback();
-//
-// INotificationData data = notifCallback.getData();
-//
-// System.out.println("result map size = "+ notifCallback.getSimpleCallbackResults().size());
-// IDistributionClientResult downloadResult = notifCallback.getSimpleCallbackResults().get("downloadResult");
-// assertTrue("response code is not SUCCESS, returned :"+ downloadResult.getDistributionActionResult(),downloadResult.getDistributionActionResult() == DistributionActionResultEnum.SUCCESS);
-//
-// }
-//
-//
-// private Service createServiceReadyForDistribution() throws Exception {
-//// RestResponse response = LCSbaseTest.certifyService(serviceDetails);
-//// assertTrue("response code is not 200, returned :" + response.getErrorCode(), response.getErrorCode() == 200);
-//// Service service = ResponseParser.convertServiceResponseToJavaObject(response.getResponse());
-////
-//// RestResponse changeDistributionStateToApprove = serviceUtils.changeDistributionStateToApprove(service,UserUtils.getGovernorDetails1());
-//// assertTrue("response code is not 200, returned :" + changeDistributionStateToApprove.getErrorCode(), changeDistributionStateToApprove.getErrorCode() == 200);
-//// service = ResponseParser.convertServiceResponseToJavaObject(changeDistributionStateToApprove.getResponse());
-//// return service;
-// return null;
-// }
-
-}
diff --git a/distribution-ci/src/main/java/org/openecomp/test/NotificationCallback.java b/distribution-ci/src/main/java/org/openecomp/test/NotificationCallback.java
deleted file mode 100644
index 247b9a9984..0000000000
--- a/distribution-ci/src/main/java/org/openecomp/test/NotificationCallback.java
+++ /dev/null
@@ -1,19 +0,0 @@
-package org.openecomp.test;
-
-import org.openecomp.sdc.api.IDistributionClient;
-import org.openecomp.sdc.api.notification.INotificationData;
-
-public class NotificationCallback extends SimpleCallback{
- INotificationData latestCallbackData;
- public INotificationData getData() {
- return latestCallbackData;
- }
- public NotificationCallback(IDistributionClient client) {
- super(client);
- }
-
- public void activateCallback(INotificationData data) {
- this.latestCallbackData = data;
- super.activateCallback(data);
- }
-}
diff --git a/distribution-ci/src/main/java/org/openecomp/test/SimpleCallback.java b/distribution-ci/src/main/java/org/openecomp/test/SimpleCallback.java
deleted file mode 100644
index a7b2311867..0000000000
--- a/distribution-ci/src/main/java/org/openecomp/test/SimpleCallback.java
+++ /dev/null
@@ -1,275 +0,0 @@
-package org.openecomp.test;
-
-import static org.junit.Assert.*;
-
-import java.io.UnsupportedEncodingException;
-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.openecomp.sdc.api.IDistributionClient;
-import org.openecomp.sdc.api.consumer.IDistributionStatusMessage;
-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.notification.IResourceInstance;
-import org.openecomp.sdc.api.notification.IVfModuleMetadata;
-import org.openecomp.sdc.api.results.IDistributionClientDownloadResult;
-import org.openecomp.sdc.api.results.IDistributionClientResult;
-import org.openecomp.sdc.utils.ArtifactTypeEnum;
-import org.openecomp.sdc.utils.DistributionActionResultEnum;
-import org.openecomp.sdc.utils.DistributionStatusEnum;
-import org.openecomp.sdc.ci.tests.utils.Decoder;
-import org.openecomp.sdc.ci.tests.utils.general.FileUtils;
-import com.google.common.io.BaseEncoding;
-
-public class SimpleCallback implements INotificationCallback {
- private IDistributionClient client;
- public List<IArtifactInfo> iArtifactInfo;
-
- public final Map<String, IDistributionClientResult> simpleCallbackResults = new HashMap<String, IDistributionClientResult>();
-
- public Map<String, IDistributionClientResult> getSimpleCallbackResults() {
- return simpleCallbackResults;
- }
-
- public List<IArtifactInfo> getIArtifactInfo() {
- return iArtifactInfo;
- }
-
- public SimpleCallback(IDistributionClient client) {
- this.client = client;
- }
-
- public void activateCallback(INotificationData data) {
-
- List<IArtifactInfo> artifacts = getArtifacts(data);
-
- for (IArtifactInfo iArtifactInfo : artifacts) {
-
- IArtifactInfo artifactMetadataByUUID = data.getArtifactMetadataByUUID(iArtifactInfo.getArtifactUUID());
- assertEquals("check artifact checksum", iArtifactInfo.getArtifactChecksum(), artifactMetadataByUUID.getArtifactChecksum());
- System.out.println(artifactMetadataByUUID.getArtifactURL());
- if (artifactMetadataByUUID.getArtifactType().equals(ArtifactTypeEnum.VF_MODULES_METADATA)) {
- IDistributionClientDownloadResult download = client.download(iArtifactInfo);
- if (download.getDistributionActionResult() == DistributionActionResultEnum.SUCCESS) {
- List<IVfModuleMetadata> decodeVfModuleArtifact = client.decodeVfModuleArtifact(download.getArtifactPayload());
- // assertEquals("decoded not equal to actual group amount ", decodeVfModuleArtifact.size(), 2);
- if (!decodeVfModuleArtifact.isEmpty()) {
- for (IVfModuleMetadata moduleMetadata : decodeVfModuleArtifact) {
- List<String> moduleArtifacts = moduleMetadata.getArtifacts();
- if (moduleArtifacts != null) {
-
- for (String artifactId : moduleArtifacts) {
-
- IArtifactInfo artifactInfo = data.getArtifactMetadataByUUID(artifactId);
- IDistributionClientDownloadResult downloadArt = client.download(artifactInfo);
- assertEquals(downloadArt.getDistributionActionResult(), DistributionActionResultEnum.SUCCESS);
-
- }
-
- }
- }
- }
- }
- }
- }
-
- for (IArtifactInfo relevantArtifact : artifacts) {
- // Download Artifact
- IDistributionClientDownloadResult downloadResult = client.download(relevantArtifact);
-
- postDownloadLogic(downloadResult);
-
- simpleCallbackResults.put("downloadResult", downloadResult);
- System.out.println("downloadResult: " + downloadResult.toString());
- System.out.println("<<<<<<<<<<< Artifact content >>>>>>>>>>");
- System.out.println(Decoder.encode(downloadResult.getArtifactPayload()));
-
- ///// Print artifact content to console///////
-
- // byte[] contentInBytes = BaseEncoding.base64().decode(Decoder.encode(downloadResult.getArtifactPayload()));
- // try {
- // System.out.println("Source content: " + new String(contentInBytes, "UTF-8"));
- // } catch (UnsupportedEncodingException e1) {
- // // TODO Auto-generated catch block
- // e1.printStackTrace();
- // }
- System.out.println("ArtInfo_timeout: " + relevantArtifact.getArtifactTimeout());
- System.out.println("ArtInfo_Art_description: " + relevantArtifact.getArtifactDescription());
- System.out.println("ArtInfo_Art_CheckSum: " + relevantArtifact.getArtifactChecksum());
- System.out.println("ArtInfo_Art_Url: " + relevantArtifact.getArtifactURL());
- System.out.println("ArtInfo_Art_Type: " + relevantArtifact.getArtifactType());
- System.out.println("ArtInfo_Art_Name: " + relevantArtifact.getArtifactName());
- System.out.println("ArtInfo_UUID: " + relevantArtifact.getArtifactUUID());
- System.out.println("ArtInfo_Version: " + relevantArtifact.getArtifactVersion());
- System.out.println("ArtInfo_RelatedArtifacts: " + relevantArtifact.getRelatedArtifacts());
-
- System.out.println("ArtInfo_Serv_description: " + data.getServiceDescription());
- System.out.println("ArtInfo_Serv_Name: " + data.getServiceName());
- System.out.println("Get_serviceVersion: " + data.getServiceVersion());
- System.out.println("Get_Service_UUID: " + data.getServiceUUID());
- System.out.println("ArtInfo_DistributionId: " + data.getDistributionID());
- System.out.println("ArtInfo_ServiceInvariantUUID: " + data.getServiceInvariantUUID());
-
- // assertTrue("response code is not 200, returned :" + downloadResult.getDistributionActionResult(), downloadResult.getDistributionActionResult() == DistributionActionResultEnum.SUCCESS );
-
- try {
- String payload = new String(downloadResult.getArtifactPayload());
- // System.out.println("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
- // System.out.println(payload);
- // System.out.println("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
-
- } catch (Exception e) {
- System.out.println("catch");
- // break;
- // TODO: handle exception
- }
-
- if (downloadResult.getDistributionActionResult() == DistributionActionResultEnum.SUCCESS) {
- handleSuccessfullDownload(data, relevantArtifact);
- } else {
- handleFailedDownload(data, relevantArtifact);
- }
- }
- // if (data != null){
- // iArtifactInfo.addAll(artifacts);
- // }
-
- }
-
- private List<IArtifactInfo> getArtifacts(INotificationData data) {
- List<IArtifactInfo> ret = new ArrayList<IArtifactInfo>();
- List<IResourceInstance> resources = data.getResources();
- // data.getArtifactMetadataByUUID(arg0)
- List<String> relevantArtifactTypes = client.getConfiguration().getRelevantArtifactTypes();
-
- List<IArtifactInfo> collect = resources.stream().flatMap(e -> e.getArtifacts().stream()).filter(p -> relevantArtifactTypes.contains(p.getArtifactType())).collect(Collectors.toList());
- // if( resources != null ){
- // for( IResourceInstance resourceInstance : resources){
- // if( resourceInstance.getArtifacts() != null ){
- //
- //
- //
- // ret.addAll(resourceInstance.getArtifacts());
- //
- //
- // }
- // }
- // }
- ret.addAll(collect);
-
- List<IArtifactInfo> servicesArt = data.getServiceArtifacts();
- if (servicesArt != null) {
- ret.addAll(servicesArt);
- }
-
- System.out.println("I am here: " + ret.toString());
- return ret;
- }
-
- private void handleFailedDownload(INotificationData data, IArtifactInfo relevantArtifact) {
- // Send Download Status
- IDistributionClientResult sendDownloadStatus = client.sendDownloadStatus(buildStatusMessage(client, data, relevantArtifact, DistributionStatusEnum.DOWNLOAD_ERROR));
- postDownloadStatusSendLogic(sendDownloadStatus);
- }
-
- private void handleSuccessfullDownload(INotificationData data, IArtifactInfo relevantArtifact) {
- // Send Download Status
- IDistributionClientResult sendDownloadStatus = client.sendDownloadStatus(buildStatusMessage(client, data, relevantArtifact, DistributionStatusEnum.DOWNLOAD_OK));
-
- simpleCallbackResults.put("sendDownloadStatus", sendDownloadStatus);
- // assertTrue("response code is not 200, returned :" + sendDownloadStatus.getDistributionActionResult(), sendDownloadStatus.getDistributionActionResult() == DistributionActionResultEnum.SUCCESS );
-
- // Doing deployment ...
- postDownloadStatusSendLogic(sendDownloadStatus);
- boolean isDeployedSuccessfully = handleDeployment();
- IDistributionClientResult deploymentStatus;
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- if (isDeployedSuccessfully) {
- deploymentStatus = client.sendDeploymentStatus(buildStatusMessage(client, data, relevantArtifact, DistributionStatusEnum.DEPLOY_OK));
-
- simpleCallbackResults.put("sendDeploymentStatus", deploymentStatus);
- // assertTrue("response code is not 200, returned :" + deploymentStatus.getDistributionActionResult(), deploymentStatus.getDistributionActionResult() == DistributionActionResultEnum.SUCCESS );
-
- } else {
- deploymentStatus = handleFailedDeployment(data, relevantArtifact);
- }
-
- postDeploymentStatusSendLogic(deploymentStatus);
- }
-
- private IDistributionClientResult handleFailedDeployment(INotificationData data, IArtifactInfo relevantArtifact) {
- IDistributionClientResult deploymentStatus;
- boolean isAlreadyDeployed = checkIsDeployed();
- if (isAlreadyDeployed) {
- deploymentStatus = client.sendDeploymentStatus(buildStatusMessage(client, data, relevantArtifact, DistributionStatusEnum.ALREADY_DEPLOYED));
- } else {
- deploymentStatus = client.sendDeploymentStatus(buildStatusMessage(client, data, relevantArtifact, DistributionStatusEnum.DEPLOY_ERROR));
- }
- return deploymentStatus;
- }
-
- private void postDownloadLogic(IDistributionClientDownloadResult downloadResult) {
- // TODO Auto-generated method stub
-
- }
-
- private void postDownloadStatusSendLogic(IDistributionClientResult sendDownloadStatus) {
- // TODO Auto-generated method stub
-
- }
-
- private void postDeploymentStatusSendLogic(IDistributionClientResult deploymentStatus) {
- // TODO Auto-generated method stub
-
- }
-
- private boolean checkIsDeployed() {
- return false;
- }
-
- private boolean handleDeployment() {
- return true;
- // to return deploy_error use return false
- // return false;
- }
-
- public static IDistributionStatusMessage buildStatusMessage(final IDistributionClient client, final INotificationData data, final IArtifactInfo relevantArtifact, final DistributionStatusEnum status) {
- IDistributionStatusMessage statusMessage = new IDistributionStatusMessage() {
-
- public long getTimestamp() {
- long currentTimeMillis = System.currentTimeMillis();
- return currentTimeMillis;
- }
-
- public DistributionStatusEnum getStatus() {
- return status;
- }
-
- public String getDistributionID() {
- return data.getDistributionID();
- }
-
- public String getConsumerID() {
- return client.getConfiguration().getConsumerID();
- }
-
- public String getArtifactURL() {
- return relevantArtifact.getArtifactURL();
- }
- };
- return statusMessage;
- }
-
-}
diff --git a/distribution-ci/src/main/java/org/openecomp/test/SimpleConfiguration.java b/distribution-ci/src/main/java/org/openecomp/test/SimpleConfiguration.java
deleted file mode 100644
index 7f2ff91906..0000000000
--- a/distribution-ci/src/main/java/org/openecomp/test/SimpleConfiguration.java
+++ /dev/null
@@ -1,149 +0,0 @@
-package org.openecomp.test;
-
-import java.util.List;
-
-import org.openecomp.sdc.api.consumer.IConfiguration;
-import org.openecomp.sdc.common.api.ArtifactTypeEnum;
-
-public class SimpleConfiguration implements IConfiguration{
-
-// public String getUser()
-// {
-// return System.getProperty("user");
-// }
-//
-// public List<String> getRelevantArtifactTypes() {
-// List<String> res = new ArrayList<String>();
-// for (ArtifactTypeEnum type : ArtifactTypeEnum.values()){
-// res.add(type.name());
-// }
-// return res;
-// }
-//
-// public int getPollingTimeout()
-// {
-// return 20;
-// }
-//
-// public int getPollingInterval()
-// {
-// return 20;
-// }
-//
-// public String getPassword()
-// {
-// return System.getProperty("password");
-// }
-//
-// public String getEnvironmentName()
-// {
-// return System.getProperty("env");
-// }
-//
-// public String getConsumerID()
-// {
-// return System.getProperty("consumerID");
-// }
-//
-// public String getConsumerGroup()
-// {
-// return System.getProperty("groupID");
-// }
-//
-// public String getAsdcAddress()
-// {
-// return System.getProperty("beAddress");
-// }
-//
-// public String getKeyStorePath()
-// {
-// return "";
-// }
-//
-// public String getKeyStorePassword()
-// {
-// return "Aa123456";
-// }
-//
-// public boolean activateServerTLSAuth()
-// {
-// return Boolean.parseBoolean(System.getProperty("auth"));
-//// res.add(ArtifactTypeEnum.HEAT_ARTIFACT);
-//// res.add(ArtifactTypeEnum.HEAT_ENV);
-//// res.add(ArtifactTypeEnum.MURANO_PKG);
-//// res.add(ArtifactTypeEnum.VF_LICENSE);
-//// res.add(ArtifactTypeEnum.APPC_CONFIG);
-//// res.add(ArtifactTypeEnum.MODEL_INVENTORY_PROFILE);
-//// res.add(ArtifactTypeEnum.VNF_CATALOG);
-//// res.add(ArtifactTypeEnum.APPC_CONFIG);
-//// res.add(ArtifactTypeEnum.VF_MODULES_METADATA);
-//// return "PROD-Tedy-Only";
-//// return "A-AI";
-//// return "A-AI";
-// }
-
-
-
- public String getUser() {
- return "ci";
- }
-
- public List<String> getRelevantArtifactTypes() {
-
-// List<String> res = new ArrayList<String>();
-// for (ArtifactTypeEnum type : AssetTypeEnum.values()){
-// res.add(type.name());
-// }
- return ArtifactTypeEnum.getAllTypes();
- }
-
-
- public int getPollingTimeout() {
- return 20;
- }
-
- public int getPollingInterval() {
- return 20;
- }
-
- public String getPassword() {
- return "123456";
- }
-
- public String getEnvironmentName() {
- return "PROD-Rom";
- }
-
- public String getConsumerID() {
- return "ys9693-groupVasya";
- }
-
- public String getConsumerGroup() {
-// return "mso-groupTedy";
- return "ys9693-consumerVasya";
- }
-
- public String getAsdcAddress() {
- return "127.0.0.1:8443";
-
- }
-
- @Override
- public String getKeyStorePath() {
- //return "";
- return "etc/asdc-client.jks";
- }
-
- @Override
- public String getKeyStorePassword() {
-
- return "Aa123456";
- }
-
- @Override
- public boolean activateServerTLSAuth() {
-
- return false;
- }
-
-}
diff --git a/distribution-ci/src/main/resources/ci/conf/log4j.properties b/distribution-ci/src/main/resources/ci/conf/log4j.properties
deleted file mode 100644
index 3e159ec8df..0000000000
--- a/distribution-ci/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/distribution-ci/src/main/resources/ci/conf/sdc-packages.yaml b/distribution-ci/src/main/resources/ci/conf/sdc-packages.yaml
deleted file mode 100644
index 34a78d9275..0000000000
--- a/distribution-ci/src/main/resources/ci/conf/sdc-packages.yaml
+++ /dev/null
@@ -1,10 +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 \ No newline at end of file
diff --git a/distribution-ci/src/main/resources/ci/conf/sdc.yaml b/distribution-ci/src/main/resources/ci/conf/sdc.yaml
deleted file mode 100644
index a9c449e672..0000000000
--- a/distribution-ci/src/main/resources/ci/conf/sdc.yaml
+++ /dev/null
@@ -1,35 +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
-
-resourceConfigDir: src/test/resources/CI/tests
-componentsConfigDir: src/test/resources/CI/components
-importResourceConfigDir: src/test/resources/CI/importResource
-importResourceTestsConfigDir: src/test/resources/CI/importResourceTests
-errorConfigurationFile: ../catalog-be/src/main/resources/config/error-configuration.yaml
-
-titanPropertiesFile: src/main/resources/ci/conf/titan.properties
-
-stopOnClassFailure: false
-
-#List of non-abstract resources to keep during titan cleanup between tests
-#Only 1.0 version will be kept
-resourcesNotToDelete:
- - tosca.nodes.Compute
- - tosca.nodes.Database
- - tosca.nodes.ObjectStorage
- - tosca.nodes.BlockStorage
- - tosca.nodes.LoadBalancer
- - org.openecomp.resource.cp.Port
- - org.openecomp.resource.vl.Network \ No newline at end of file
diff --git a/distribution-ci/src/main/resources/ci/conf/titan.properties b/distribution-ci/src/main/resources/ci/conf/titan.properties
deleted file mode 100644
index 691f4d6877..0000000000
--- a/distribution-ci/src/main/resources/ci/conf/titan.properties
+++ /dev/null
@@ -1,5 +0,0 @@
-storage.backend=cassandra
-storage.hostname=cassandrahost
-storage.port=9160
-
-cache.db-cache = false \ No newline at end of file
diff --git a/distribution-ci/src/main/resources/ci/scripts/startTest.sh b/distribution-ci/src/main/resources/ci/scripts/startTest.sh
deleted file mode 100644
index 88659a80b6..0000000000
--- a/distribution-ci/src/main/resources/ci/scripts/startTest.sh
+++ /dev/null
@@ -1,87 +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/sdc.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
-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}"
-
-#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/distribution-ci/src/test/java/org/openecomp/sdc/ci/tests/execute/downloadArtifactUGN/ClientDownloadArtifact.java b/distribution-ci/src/test/java/org/openecomp/sdc/ci/tests/execute/downloadArtifactUGN/ClientDownloadArtifact.java
deleted file mode 100644
index 7337c941a5..0000000000
--- a/distribution-ci/src/test/java/org/openecomp/sdc/ci/tests/execute/downloadArtifactUGN/ClientDownloadArtifact.java
+++ /dev/null
@@ -1,491 +0,0 @@
-package org.openecomp.sdc.ci.tests.execute.downloadArtifactUGN;
-
-import org.junit.Test;
-
-/**
- *
- * @author al714h
- * US510007 - Story : ASDC Distr Client - Download Artifact
- * following test set partially cover the US451327 - Story : API to download the specific artifact, cover the audit message.
- */
-
-//public class ClientDownloadArtifact extends AttSdcTest{
- public class ClientDownloadArtifact {
-
-// Logger logger = null;
-//
-// DistributionUtils distributionUtils = new DistributionUtils();
-// DownloadArtifactDetails downloadArtifactDetails = new DownloadArtifactDetails();
-// Utils utils = new Utils();
-// DbUtils dbUtils = new DbUtils();
-// UserUtils userUtils = new UserUtils();
-// ResourceUtils resourceUtils = new ResourceUtils();
-// ServiceUtils serviceUtils = new ServiceUtils();
-// ArtifactUtils artifactUtils = new ArtifactUtils();
-// private JSONParser jsonParser = new JSONParser();
-//
- String serviceBaseVersion = "0.1";
-//
-// @Before
-// public void before() throws Exception {
-//
-// distributionUtils.resetInit();
-// dbUtils.cleanAllAudits();
-// }
-// @Rule
-// public static TestName name = new TestName();
-//
-// }
-//
-// @Rule
-// public static TestName name = new TestName();
-//
-//// public ClientDownloadArtifact() {
-//// super(name, ClientDownloadArtifact.class.getName());
-//// }
-//
-// ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
-//// get default artifact info to upload
-// ArtifactDefinition uploadedResourceArtifactInfo = artifactUtils.constructDefaultArtifactInfo();
-//// set artifact info for download
-// downloadArtifactDetails.setArtifactName(uploadedResourceArtifactInfo.getArtifactName());
-// String artifactName = downloadArtifactDetails.getArtifactName();
-//// Andrey TODO String resourceArtifactUrl = String.format(Urls.DOWNLOAD_RESOURCE_ARTIFACT,);
-//
-// int numOfResourcArtifacts = 1;
-// RestResponse createCertifiedResourceWithArtifacts = resourceUtils.createCertifiedResourceWithArtifacts(resourceDetails, uploadedResourceArtifactInfo, numOfResourcArtifacts);
-//
-//
-//
-// try{
-// logger.debug("artifact detailes: "+ downloadArtifactDetails.toString());
-// RestResponse downloadArtifactRestResponse = distributionUtils.sendGetDownloadedArtifact(downloadArtifactDetails, null);
-// distributionUtils.verifyDownloadedArtifact(downloadArtifactRestResponse, uploadedResourceArtifactInfo);
-//
-// // validate audit message server side
-// ArtifactDownloadAuditMessageInfo expectedArtifactDownloadAuditMessageInfo = distributionUtils.constructDefaultArtifactDownloadAuditMessageInfo();
-// String action = "ArtifactDownload";
-// ArtifactDownloadAuditMessageInfo actualArtifactDownloadAuditMessageInfo = userUtils.parseDestributionAuditRespByAction(action);
-// distributionUtils.validateArtifactDownloadAuditMessage(actualArtifactDownloadAuditMessageInfo, expectedArtifactDownloadAuditMessageInfo);
-// }finally{
-//// delete created resource
-// resourceUtils.deleteResource_allVersions(resourceDetails, UserUtils.getAdminDetails());
-// }
-
-// }
-
-// send all mandatory headers only
- @Test
- public void downloadServiceArtifactSuccess() throws Exception{
-
-//// ServiceReqDetails serviceDetails = serviceUtils.createDefaultDetailsService();
-// ServiceReqDetails serviceDetails = ElementFactory.getDefaultService();
-// Service service = new Service();
-// try{
-//// get default artifact info to upload
-// ArtifactDefinition uploadedResourceArtifactInfo = artifactUtils.constructDefaultArtifactInfo();
-// uploadedResourceArtifactInfo.setArtifactType(ArtifactTypeEnum.HEAT.getType());
-// ArtifactDefinition uploadedServiceArtifactInfo = artifactUtils.constructDefaultArtifactInfo();
-// uploadedServiceArtifactInfo.setArtifactType(ArtifactTypeEnum.MURANO_PKG.getType());
-//
-//// set artifact info for download
-// downloadArtifactDetails.setArtifactName(uploadedServiceArtifactInfo.getArtifactName());
-// downloadArtifactDetails.setArtifactType(ArtifactTypeEnum.MURANO_PKG.getType());
-// String artifactName = downloadArtifactDetails.getArtifactName();
-//
-//// create default resource details
-// ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
-//
-// int numOfResourcArtifacts = 1;
-// service = serviceUtils.createCertifiedServiceWithResourceInstanceAndArtifacts(serviceDetails, resourceDetails, uploadedResourceArtifactInfo, uploadedServiceArtifactInfo , numOfResourcArtifacts);
-// logger.debug("service version = " + service.getVersion());
-// logger.debug("service distribution status = " + service.getDistributionStatus());
-// RestResponse changeDistributionStateToApprove = serviceUtils.changeDistributionStateToApprove(service, UserUtils.getGovernorDetails1());
-//
-// int status = changeDistributionStateToApprove.getErrorCode();
-// assertTrue("response code is not 200, returned :" + status, status == 200);
-//
-// serviceDetails.setVersion(service.getVersion());
-// serviceDetails.setUniqueId(service.getUniqueId());
-//
-// String responseString = changeDistributionStateToApprove.getResponse();
-// Gson gson = new Gson();
-// service = gson.fromJson(responseString, Service.class);
-// ServiceMetadataDataDefinition serviceMetadataDataDefinition = gson.fromJson(responseString, ServiceMetadataDataDefinition.class);
-// service.setDistributionStatus(DistributionStatusEnum.findState(serviceMetadataDataDefinition.getDistributionStatus()));
-// DistributionStatusEnum distributionStatus = service.getDistributionStatus();
-// assertNotNull("distribution state is null",distributionStatus.name());
-// assertTrue("the default distribution state is invalid", DistributionStatusEnum.DISTRIBUTION_APPROVED.equals(distributionStatus));
-//
-// String serviceArtifactUrl = String.format(Urls.DISTRIBUTION_DOWNLOAD_ARTIFACT,service.getName(), service.getVersion(), artifactName);
-// logger.debug("download service artifact url: "+ serviceArtifactUrl+ " serviceName = " + service.getName() + " service version = " + service.getVersion() + "service artifact name = " + artifactName);
-//
-//
-//// Log.debug("artifact detailes: "+ downloadArtifactDetails.toString());
-//// RestResponse downloadArtifactRestResponse = distributionUtils.sendGetDownloadedArtifact(downloadArtifactDetails, null);
-//// distributionUtils.verifyDownloadedArtifact(downloadArtifactRestResponse, uploadedArtifactInfo);
-////
-//// // validate audit message server side
-//// ArtifactDownloadAuditMessageInfo expectedArtifactDownloadAuditMessageInfo = distributionUtils.constructDefaultArtifactDownloadAuditMessageInfo();
-//// String action = "ArtifactDownload";
-//// ArtifactDownloadAuditMessageInfo actualArtifactDownloadAuditMessageInfo = userUtils.parseDestributionAuditRespByAction(action);
-//// distributionUtils.validateArtifactDownloadAuditMessage(actualArtifactDownloadAuditMessageInfo, expectedArtifactDownloadAuditMessageInfo);
-// }finally{
-//// delete created service
-// serviceUtils.deleteService_allVersions(serviceDetails, UserUtils.getAdminDetails());
-// }
-
-// @Test
-// public void downloadServiceArtifactSuccess() throws Exception{
-//
-//// ServiceReqDetails serviceDetails = serviceUtils.createDefaultDetailsService();
-// ServiceReqDetails serviceDetails = ElementFactory.getDefaultService();
-// Service service = new Service();
-// try{
-//// get default artifact info to upload
-// ArtifactDefinition uploadedResourceArtifactInfo = artifactUtils.constructDefaultArtifactInfo();
-// uploadedResourceArtifactInfo.setArtifactType(ArtifactTypeEnum.HEAT.getType());
-// ArtifactDefinition uploadedServiceArtifactInfo = artifactUtils.constructDefaultArtifactInfo();
-// uploadedServiceArtifactInfo.setArtifactType(ArtifactTypeEnum.MURANO_PKG.getType());
-//
-//// set artifact info for download
-// downloadArtifactDetails.setArtifactName(uploadedServiceArtifactInfo.getArtifactName());
-// downloadArtifactDetails.setArtifactType(ArtifactTypeEnum.MURANO_PKG.getType());
-// String artifactName = downloadArtifactDetails.getArtifactName();
-//
-//// create default resource details
-// ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
-//
-// int numOfResourcArtifacts = 1;
-// service = serviceUtils.createCertifiedServiceWithResourceInstanceAndArtifacts(serviceDetails, resourceDetails, uploadedResourceArtifactInfo, uploadedServiceArtifactInfo , numOfResourcArtifacts);
-// logger.debug("service version = " + service.getVersion());
-// logger.debug("service distribution status = " + service.getDistributionStatus());
-// RestResponse changeDistributionStateToApprove = serviceUtils.changeDistributionStateToApprove(service, UserUtils.getGovernorDetails1());
-//
-// int status = changeDistributionStateToApprove.getErrorCode();
-// assertTrue("response code is not 200, returned :" + status, status == 200);
-//
-// serviceDetails.setVersion(service.getVersion());
-// serviceDetails.setUniqueId(service.getUniqueId());
-//
-// String responseString = changeDistributionStateToApprove.getResponse();
-// Gson gson = new Gson();
-// service = gson.fromJson(responseString, Service.class);
-// ServiceMetadataDataDefinition serviceMetadataDataDefinition = gson.fromJson(responseString, ServiceMetadataDataDefinition.class);
-// service.setDistributionStatus(DistributionStatusEnum.findState(serviceMetadataDataDefinition.getDistributionStatus()));
-// DistributionStatusEnum distributionStatus = service.getDistributionStatus();
-// assertNotNull("distribution state is null",distributionStatus.name());
-// assertTrue("the default distribution state is invalid", DistributionStatusEnum.DISTRIBUTION_APPROVED.equals(distributionStatus));
-//
-// String serviceArtifactUrl = String.format(Urls.DISTRIBUTION_DOWNLOAD_ARTIFACT,service.getName(), service.getVersion(), artifactName);
-// logger.debug("download service artifact url: "+ serviceArtifactUrl+ " serviceName = " + service.getName() + " service version = " + service.getVersion() + "service artifact name = " + artifactName);
-//
-//
-//// Log.debug("artifact detailes: "+ downloadArtifactDetails.toString());
-//// RestResponse downloadArtifactRestResponse = distributionUtils.sendGetDownloadedArtifact(downloadArtifactDetails, null);
-//// distributionUtils.verifyDownloadedArtifact(downloadArtifactRestResponse, uploadedArtifactInfo);
-////
-//// // validate audit message server side
-//// ArtifactDownloadAuditMessageInfo expectedArtifactDownloadAuditMessageInfo = distributionUtils.constructDefaultArtifactDownloadAuditMessageInfo();
-//// String action = "ArtifactDownload";
-//// ArtifactDownloadAuditMessageInfo actualArtifactDownloadAuditMessageInfo = userUtils.parseDestributionAuditRespByAction(action);
-//// distributionUtils.validateArtifactDownloadAuditMessage(actualArtifactDownloadAuditMessageInfo, expectedArtifactDownloadAuditMessageInfo);
-// }finally{
-//// delete created service
-// serviceUtils.deleteService_allVersions(serviceDetails, UserUtils.getAdminDetails());
-// }
-//
-// }
-//
-//// Andrey not relevant, dev ci should cover, qa can't influence on sending headers
-////// send all headers mandatory and not mandatory
-//// @Test
-//// public void downloadArtifactSuccessMandatoryAndNotMandatoryHeaders() throws Exception{
-////
-//// Log.debug("artifact detailes: "+ downloadArtifactDetails.toString());
-////
-//// Map<String, String> headersMap = new HashMap<String,String>();
-//// headersMap.put(HttpHeaderEnum.X_ECOMP_InstanceID.getValue(), "instar_name"); // mandatory
-//// headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), "usernamePassword"); // mandatory
-//// headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), "application/octet-stream"); // not mandatory
-//// headersMap.put(HttpHeaderEnum.X_ECOMP_REQUEST_ID_HEADER.getValue(),downloadArtifactDetails.getResourceUUID());// not mandatory
-//// Log.debug("headers detailes: "+ headersMap.toString());
-////
-//// RestResponse downloadArtifactRestResponse = distributionUtils.sendGetDownloadedArtifact(downloadArtifactDetails, headersMap);
-//// distributionUtils.verifyDownloadedArtifact(downloadArtifactRestResponse);
-////
-////// validate audit message server side
-//// ArtifactDownloadAuditMessageInfo expectedArtifactDownloadAuditMessageInfo = distributionUtils.constructDefaultArtifactDownloadAuditMessageInfo();
-//// String action = "ArtifactDownload";
-//// ArtifactDownloadAuditMessageInfo actualArtifactDownloadAuditMessageInfo = userUtils.parseDestributionAuditRespByAction(action);
-//// distributionUtils.validateArtifactDownloadAuditMessage(actualArtifactDownloadAuditMessageInfo, expectedArtifactDownloadAuditMessageInfo);
-////
-//// }
-//
-//
-////---------------------------------Failure scenario--------------------------------------------------------------------------------
-//
-//// Andrey not relevant, dev ci should cover, qa can't influence on sending headers
-////// missing InstanceID mandatory header
-//// @Test
-//// public void downloadArtifactMissingInstanceIdHeader() throws Exception, JSONException{
-////
-//// Log.debug("artifact detailes: "+ downloadArtifactDetails.toString());
-////
-//// Map<String, String> headersMap = new HashMap<String,String>();
-//// headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), "usernamePassword"); // mandatory
-//// Log.debug("headers detailes: "+ headersMap.toString());
-////
-//// RestResponse downloadArtifactRestResponse = distributionUtils.sendGetDownloadedArtifact(downloadArtifactDetails, headersMap);
-////
-//// ErrorInfo errorInfo = utils.parseYaml(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID.name());
-//// assertEquals("Check response code after artifact download request", errorInfo.getCode(), downloadArtifactRestResponse.getErrorCode());
-////
-//// List<String> variables = Arrays.asList();
-//// utils.checkBodyResponseOnError(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID.name(), variables, downloadArtifactRestResponse.getResponse()));
-////
-//// }
-//
-//// Andrey not relevant, dev ci should cover, qa can't influence on sending headers
-////// missing Authorization mandatory header
-//// @Test
-//// public void downloadArtifactMissingAuthorizationHeader() throws Exception, JSONException{
-////
-//// Log.debug("artifact detailes: "+ downloadArtifactDetails.toString());
-////
-//// Map<String, String> headersMap = new HashMap<String,String>();
-//// headersMap.put(HttpHeaderEnum.X_ECOMP_InstanceID.getValue(), "usernamePassword"); // mandatory
-//// Log.debug("headers detailes: "+ headersMap.toString());
-////
-//// RestResponse downloadArtifactRestResponse = distributionUtils.sendGetDownloadedArtifact(downloadArtifactDetails, headersMap);
-////
-//// ErrorInfo errorInfo = utils.parseYaml(ActionStatus.ECOMP_RESEND_WITH_BASIC_AUTHENTICATION_CREDENTIALS.name());
-//// assertEquals("Check response code after artifact download request", errorInfo.getCode(), downloadArtifactRestResponse.getErrorCode());
-////
-//// List<String> variables = Arrays.asList();
-//// utils.checkBodyResponseOnError(ActionStatus.ECOMP_RESEND_WITH_BASIC_AUTHENTICATION_CREDENTIALS.name(), variables, downloadArtifactRestResponse.getResponse()));
-////
-//// }
-//
-//
-//// artifact not found
-// @Test
-// public void downloadArtifactArtifactNotFound() throws Exception, JSONException{
-//
-// downloadArtifactDetails.setArtifactName("artifactNotExist");
-// logger.debug("artifact detailes: "+ downloadArtifactDetails.toString());
-//
-// RestResponse downloadArtifactRestResponse = distributionUtils.sendGetDownloadedArtifact(downloadArtifactDetails, null);
-//
-// ErrorInfo errorInfo = utils.parseErrorConfigYaml(ActionStatus.DISTRIBUTION_ARTIFACT_NOT_FOUND.name());
-// assertEquals("Check response code after artifact download request", errorInfo.getCode(), downloadArtifactRestResponse.getErrorCode());
-//
-// List<String> variables = Arrays.asList();
-// utils.checkBodyResponseOnError(ActionStatus.DISTRIBUTION_ARTIFACT_NOT_FOUND.name(), variables, downloadArtifactRestResponse.getResponse());
-//
-//// validate audit message server side
-// ArtifactDownloadAuditMessageInfo expectedArtifactDownloadAuditMessageInfo = distributionUtils.constructDefaultArtifactDownloadAuditMessageInfo();
-// expectedArtifactDownloadAuditMessageInfo.setStatus(errorInfo.getCode().toString());
-// String desc = "Error: Artifact " + downloadArtifactDetails.getArtifactName() + " was not found";
-// expectedArtifactDownloadAuditMessageInfo.setDesc(desc);
-//
-// String action = "ArtifactDownload";
-// ArtifactDownloadAuditMessageInfo actualArtifactDownloadAuditMessageInfo = userUtils.parseDestributionAuditRespByAction(action);
-// distributionUtils.validateArtifactDownloadAuditMessage(actualArtifactDownloadAuditMessageInfo, expectedArtifactDownloadAuditMessageInfo);
-//
-// }
-//
-//// service not found
-// @Test
-// public void downloadArtifactServiceNameNotFound() throws Exception, JSONException{
-//
-// downloadArtifactDetails.setArtifactURL("/asdc/v1/services/serviceNotExist/0.1/artifacts/aaa.hh");
-// logger.debug("artifact detailes: "+ downloadArtifactDetails.toString());
-//
-// RestResponse downloadArtifactRestResponse = distributionUtils.sendGetDownloadedArtifact(downloadArtifactDetails, null);
-//
-// ErrorInfo errorInfo = utils.parseErrorConfigYaml(ActionStatus.SERVICE_NOT_FOUND.name());
-// assertEquals("Check response code after artifact download request", errorInfo.getCode(), downloadArtifactRestResponse.getErrorCode());
-//
-// List<String> variables = Arrays.asList();
-// utils.checkBodyResponseOnError(ActionStatus.SERVICE_NOT_FOUND.name(), variables, downloadArtifactRestResponse.getResponse());
-//
-//// validate audit message server side
-// ArtifactDownloadAuditMessageInfo expectedArtifactDownloadAuditMessageInfo = distributionUtils.constructDefaultArtifactDownloadAuditMessageInfo();
-// expectedArtifactDownloadAuditMessageInfo.setStatus(errorInfo.getCode().toString());
-//// TODO Andrey, change desc message
-// String desc = "Error: Artifact " + downloadArtifactDetails.getArtifactName() + " was not found";
-// expectedArtifactDownloadAuditMessageInfo.setDesc(desc);
-//
-// String action = "ArtifactDownload";
-// ArtifactDownloadAuditMessageInfo actualArtifactDownloadAuditMessageInfo = userUtils.parseDestributionAuditRespByAction(action);
-// distributionUtils.validateArtifactDownloadAuditMessage(actualArtifactDownloadAuditMessageInfo, expectedArtifactDownloadAuditMessageInfo);
-//
-// }
-//
-//
-//// service version not found
-// @Test
-// public void downloadArtifactServiceVersionNotFound() throws Exception, JSONException{
-//
-// downloadArtifactDetails.setArtifactURL("/asdc/v1/services/serviceName/0.888/artifacts/aaa.hh");
-// logger.debug("artifact detailes: "+ downloadArtifactDetails.toString());
-//
-// RestResponse downloadArtifactRestResponse = distributionUtils.sendGetDownloadedArtifact(downloadArtifactDetails, null);
-//
-// ErrorInfo errorInfo = utils.parseErrorConfigYaml(ActionStatus.COMPONENT_VERSION_NOT_FOUND.name());
-// assertEquals("Check response code after artifact download request", errorInfo.getCode(), downloadArtifactRestResponse.getErrorCode());
-//
-// List<String> variables = Arrays.asList();
-// utils.checkBodyResponseOnError(ActionStatus.COMPONENT_VERSION_NOT_FOUND.name(), variables, downloadArtifactRestResponse.getResponse());
-//
-//// validate audit message server side
-// ArtifactDownloadAuditMessageInfo expectedArtifactDownloadAuditMessageInfo = distributionUtils.constructDefaultArtifactDownloadAuditMessageInfo();
-// expectedArtifactDownloadAuditMessageInfo.setStatus(errorInfo.getCode().toString());
-//// TODO Andrey, change desc message
-// String desc = "Error: Artifact " + downloadArtifactDetails.getArtifactName() + " was not found";
-// expectedArtifactDownloadAuditMessageInfo.setDesc(desc);
-//
-// String action = "ArtifactDownload";
-// ArtifactDownloadAuditMessageInfo actualArtifactDownloadAuditMessageInfo = userUtils.parseDestributionAuditRespByAction(action);
-// distributionUtils.validateArtifactDownloadAuditMessage(actualArtifactDownloadAuditMessageInfo, expectedArtifactDownloadAuditMessageInfo);
-//
-// }
-//
-//// invalid HTTP method, PUT HTTP method
-// @Test
-// public void downloadArtifactByPutMethod() throws Exception, JSONException{
-//
-// String method = "PUT";
-//
-// logger.debug("artifact detailes: "+ downloadArtifactDetails.toString());
-//
-// RestResponse downloadArtifactRestResponse = distributionUtils.sendDownloadedArtifactByMethod(downloadArtifactDetails, null, method);
-//
-// ErrorInfo errorInfo = utils.parseErrorConfigYaml(ActionStatus.METHOD_NOT_ALLOWED_TO_DOWNLOAD_ARTIFACT.name());
-// assertEquals("Check response code after artifact download request", errorInfo.getCode(), downloadArtifactRestResponse.getErrorCode());
-//
-// List<String> variables = Arrays.asList();
-// utils.checkBodyResponseOnError(ActionStatus.METHOD_NOT_ALLOWED_TO_DOWNLOAD_ARTIFACT.name(), variables, downloadArtifactRestResponse.getResponse());
-//
-// }
-//
-//// invalid HTTP method, DELETE HTTP method
-// @Test
-// public void downloadArtifactByDeleteMethod() throws Exception, JSONException{
-//
-// String method = "DELETE";
-// downloadArtifactDetails.setArtifactName("artifactNotExist");
-// logger.debug("artifact detailes: "+ downloadArtifactDetails.toString());
-//
-// RestResponse downloadArtifactRestResponse = distributionUtils.sendGetDownloadedArtifact(downloadArtifactDetails, null);
-//
-// ErrorInfo errorInfo = utils.parseErrorConfigYaml(ActionStatus.DISTRIBUTION_ARTIFACT_NOT_FOUND.name());
-// assertEquals("Check response code after artifact download request", errorInfo.getCode(), downloadArtifactRestResponse.getErrorCode());
-//
-// List<String> variables = Arrays.asList();
-// utils.checkBodyResponseOnError(ActionStatus.DISTRIBUTION_ARTIFACT_NOT_FOUND.name(), variables, downloadArtifactRestResponse.getResponse());
-//
-//// validate audit message server side
-// ArtifactDownloadAuditMessageInfo expectedArtifactDownloadAuditMessageInfo = distributionUtils.constructDefaultArtifactDownloadAuditMessageInfo();
-// expectedArtifactDownloadAuditMessageInfo.setStatus(errorInfo.getCode().toString());
-// String desc = "Error: Artifact " + downloadArtifactDetails.getArtifactName() + " was not found";
-// expectedArtifactDownloadAuditMessageInfo.setDesc(desc);
-//
-// String action = "ArtifactDownload";
-// ArtifactDownloadAuditMessageInfo actualArtifactDownloadAuditMessageInfo = userUtils.parseDestributionAuditRespByAction(action);
-// distributionUtils.validateArtifactDownloadAuditMessage(actualArtifactDownloadAuditMessageInfo, expectedArtifactDownloadAuditMessageInfo);
-//
-// downloadArtifactDetails.setArtifactURL("/asdc/v1/services/serviceNotExist/0.1/artifacts/aaa.hh");
-// logger.debug("artifact detailes: "+ downloadArtifactDetails.toString());
-//
-// RestResponse downloadArtifactRestResponse = distributionUtils.sendGetDownloadedArtifact(downloadArtifactDetails, null);
-//
-// ErrorInfo errorInfo = utils.parseErrorConfigYaml(ActionStatus.SERVICE_NOT_FOUND.name());
-// assertEquals("Check response code after artifact download request", errorInfo.getCode(), downloadArtifactRestResponse.getErrorCode());
-//
-// List<String> variables = Arrays.asList();
-// utils.checkBodyResponseOnError(ActionStatus.SERVICE_NOT_FOUND.name(), variables, downloadArtifactRestResponse.getResponse());
-//
-//// validate audit message server side
-// ArtifactDownloadAuditMessageInfo expectedArtifactDownloadAuditMessageInfo = distributionUtils.constructDefaultArtifactDownloadAuditMessageInfo();
-// expectedArtifactDownloadAuditMessageInfo.setStatus(errorInfo.getCode().toString());
-//// TODO Andrey, change desc message
-// String desc = "Error: Artifact " + downloadArtifactDetails.getArtifactName() + " was not found";
-// expectedArtifactDownloadAuditMessageInfo.setDesc(desc);
-//
-// String action = "ArtifactDownload";
-// ArtifactDownloadAuditMessageInfo actualArtifactDownloadAuditMessageInfo = userUtils.parseDestributionAuditRespByAction(action);
-// distributionUtils.validateArtifactDownloadAuditMessage(actualArtifactDownloadAuditMessageInfo, expectedArtifactDownloadAuditMessageInfo);
-// downloadArtifactDetails.setArtifactURL("/asdc/v1/services/serviceName/0.888/artifacts/aaa.hh");
-// logger.debug("artifact detailes: "+ downloadArtifactDetails.toString());
-//
-// RestResponse downloadArtifactRestResponse = distributionUtils.sendGetDownloadedArtifact(downloadArtifactDetails, null);
-//
-// ErrorInfo errorInfo = utils.parseErrorConfigYaml(ActionStatus.COMPONENT_VERSION_NOT_FOUND.name());
-// assertEquals("Check response code after artifact download request", errorInfo.getCode(), downloadArtifactRestResponse.getErrorCode());
-//
-// List<String> variables = Arrays.asList();
-// utils.checkBodyResponseOnError(ActionStatus.COMPONENT_VERSION_NOT_FOUND.name(), variables, downloadArtifactRestResponse.getResponse());
-//
-//// validate audit message server side
-// ArtifactDownloadAuditMessageInfo expectedArtifactDownloadAuditMessageInfo = distributionUtils.constructDefaultArtifactDownloadAuditMessageInfo();
-// expectedArtifactDownloadAuditMessageInfo.setStatus(errorInfo.getCode().toString());
-//// TODO Andrey, change desc message
-// String desc = "Error: Artifact " + downloadArtifactDetails.getArtifactName() + " was not found";
-// expectedArtifactDownloadAuditMessageInfo.setDesc(desc);
-//
-// String action = "ArtifactDownload";
-// ArtifactDownloadAuditMessageInfo actualArtifactDownloadAuditMessageInfo = userUtils.parseDestributionAuditRespByAction(action);
-// distributionUtils.validateArtifactDownloadAuditMessage(actualArtifactDownloadAuditMessageInfo, expectedArtifactDownloadAuditMessageInfo);
-// logger.debug("artifact detailes: "+ downloadArtifactDetails.toString());
-//
-// RestResponse downloadArtifactRestResponse = distributionUtils.sendDownloadedArtifactByMethod(downloadArtifactDetails, null, method);
-//
-// ErrorInfo errorInfo = utils.parseErrorConfigYaml(ActionStatus.METHOD_NOT_ALLOWED_TO_DOWNLOAD_ARTIFACT.name());
-// assertEquals("Check response code after artifact download request", errorInfo.getCode(), downloadArtifactRestResponse.getErrorCode());
-//
-// List<String> variables = Arrays.asList();
-// utils.checkBodyResponseOnError(ActionStatus.METHOD_NOT_ALLOWED_TO_DOWNLOAD_ARTIFACT.name(), variables, downloadArtifactRestResponse.getResponse());
-// logger.debug("artifact detailes: "+ downloadArtifactDetails.toString());
-//
-// RestResponse downloadArtifactRestResponse = distributionUtils.sendDownloadedArtifactByMethod(downloadArtifactDetails, null, method);
-//
-// ErrorInfo errorInfo = utils.parseErrorConfigYaml(ActionStatus.METHOD_NOT_ALLOWED_TO_DOWNLOAD_ARTIFACT.name());
-// assertEquals("Check response code after artifact download request", errorInfo.getCode(), downloadArtifactRestResponse.getErrorCode());
-//
-// List<String> variables = Arrays.asList();
-// utils.checkBodyResponseOnError(ActionStatus.METHOD_NOT_ALLOWED_TO_DOWNLOAD_ARTIFACT.name(), variables, downloadArtifactRestResponse.getResponse());
-// downloadArtifactDetails.setArtifactChecksum("invalidChecksum");
-// logger.debug("artifact detailes: "+ downloadArtifactDetails.toString());
-//
-// RestResponse downloadArtifactRestResponse = distributionUtils.sendGetDownloadedArtifact(downloadArtifactDetails, null);
-//// TODO
-//
-//// ErrorInfo errorInfo = utils.parseYaml(ActionStatus.SPECIFIED_SERVICE_RESOURCE_VERSION_NOT_FOUND.name());
-//// assertEquals("Check response code after artifact download request", errorInfo.getCode(), downloadArtifactRestResponse.getErrorCode());
-////
-//// List<String> variables = Arrays.asList();
-//// utils.checkBodyResponseOnError(ActionStatus.SPECIFIED_SERVICE_RESOURCE_VERSION_NOT_FOUND.name(), variables, downloadArtifactRestResponse.getResponse()));
-//
-// downloadArtifactDetails.setArtifactChecksum("invalidChecksum");
-// logger.debug("artifact detailes: "+ downloadArtifactDetails.toString());
-//
-// RestResponse downloadArtifactRestResponse = distributionUtils.sendGetDownloadedArtifact(downloadArtifactDetails, null);
-//// TODO
-//
-//// ErrorInfo errorInfo = utils.parseYaml(ActionStatus.SPECIFIED_SERVICE_RESOURCE_VERSION_NOT_FOUND.name());
-//// assertEquals("Check response code after artifact download request", errorInfo.getCode(), downloadArtifactRestResponse.getErrorCode());
-////
-//// List<String> variables = Arrays.asList();
-//// utils.checkBodyResponseOnError(ActionStatus.SPECIFIED_SERVICE_RESOURCE_VERSION_NOT_FOUND.name(), variables, downloadArtifactRestResponse.getResponse()));
-//
-// }
-//
-//
-//
-//
-
- }
-
-}
diff --git a/pom.xml b/pom.xml
index 2888f9182f..6976a82dc1 100644
--- a/pom.xml
+++ b/pom.xml
@@ -336,7 +336,7 @@
</activation>
<modules>
<module>onboarding</module>
- <!--module>security-utils</module>
+ <module>security-utils</module>
<module>common-app-api</module>
<module>common-be</module>
<module>catalog-dao</module>
@@ -346,9 +346,9 @@
<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-->
+ <!--<module>test-apis-ci</module>-->
+ <!--<module>ui-ci</module>-->
+ <module>sdc-os-chef</module>
</modules>
</profile>
diff --git a/sdc-os-chef/pom.xml b/sdc-os-chef/pom.xml
index 451fc88a3e..f825426393 100644
--- a/sdc-os-chef/pom.xml
+++ b/sdc-os-chef/pom.xml
@@ -1,5 +1,5 @@
<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">
+ 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>
@@ -11,6 +11,7 @@
<version>1.1.0-SNAPSHOT</version>
</parent>
+
<properties>
<docker.tag>${project.version}-${maven.build.timestamp}</docker.tag>
<docker.latest.tag>${project.version}-latest</docker.latest.tag>
@@ -57,8 +58,12 @@
<docker.latest.tag>${project.version}-STAGING-latest</docker.latest.tag>
</properties>
</profile>
+
<profile>
<id>docker</id>
+ <activation>
+ <activeByDefault>false</activeByDefault>
+ </activation>
<build>
<plugins>
<plugin>
@@ -67,7 +72,6 @@
<executions>
<execution>
<id>copy-resources-be</id>
- <!-- here the phase you need -->
<phase>validate</phase>
<goals>
<goal>copy-resources</goal>
@@ -78,7 +82,7 @@
<resource>
<directory>${project.parent.basedir}/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/target</directory>
<includes>
- <include>onboarding-be-*.war</include>
+ <include>onboarding-be-${project.version}.war</include>
</includes>
</resource>
</resources>
@@ -86,26 +90,6 @@
</execution>
<execution>
<id>copy-resources-fe</id>
- <!-- here the phase you need -->
- <phase>validate</phase>
- <goals>
- <goal>copy-resources</goal>
- </goals>
- <configuration>
- <outputDirectory>${basedir}/sdc-frontend</outputDirectory>
- <resources>
- <resource>
- <directory>${project.parent.basedir}/openecomp-ui/target</directory>
- <includes>
- <include>onboarding-fe-${project.version}.war</include>
- </includes>
- </resource>
- </resources>
- </configuration>
- </execution>
- <execution>
- <id>copy-resources-sanity</id>
- <!-- here the phase you need -->
<phase>validate</phase>
<goals>
<goal>copy-resources</goal>
@@ -148,7 +132,6 @@
<tags>
<tag>${docker.tag}</tag>
<tag>${docker.latest.tag}</tag>
- <tag>1.1-STAGING-latest</tag>
</tags>
</build>
</image>
@@ -163,7 +146,6 @@
<tags>
<tag>${docker.tag}</tag>
<tag>${docker.latest.tag}</tag>
- <tag>1.1-STAGING-latest</tag>
</tags>
</build>
</image>
@@ -178,7 +160,6 @@
<tags>
<tag>${docker.tag}</tag>
<tag>${docker.latest.tag}</tag>
- <tag>1.1-STAGING-latest</tag>
</tags>
</build>
</image>
@@ -193,7 +174,6 @@
<tags>
<tag>${docker.tag}</tag>
<tag>${docker.latest.tag}</tag>
- <tag>1.1-STAGING-latest</tag>
</tags>
</build>
</image>
@@ -208,11 +188,10 @@
<tags>
<tag>${docker.tag}</tag>
<tag>${docker.latest.tag}</tag>
- <tag>1.1-STAGING-latest</tag>
</tags>
</build>
</image>
-
+
<!-- Build sanity image -->
<image>
<name>openecomp/sdc-sanity</name>
@@ -223,7 +202,6 @@
<tags>
<tag>${docker.tag}</tag>
<tag>${docker.latest.tag}</tag>
- <tag>1.1-STAGING-latest</tag>
</tags>
</build>
</image>
@@ -232,15 +210,15 @@
</configuration>
<executions>
<execution>
- <id>clean-images</id>
- <phase>pre-clean</phase>
- <goals>
- <goal>remove</goal>
- </goals>
- <configuration>
- <removeAll>true</removeAll>
- <image>openecomp/sdc-backend,openecomp/sdc-frontend,openecomp/sdc-elasticsearch,openecomp/sdc-kibana,openecomp/sdc-sanity</image>
- </configuration>
+ <id>clean-images</id>
+ <phase>pre-clean</phase>
+ <goals>
+ <goal>remove</goal>
+ </goals>
+ <configuration>
+ <removeAll>true</removeAll>
+ <image>openecomp/sdc-backend,openecomp/sdc-frontend,openecomp/sdc-elasticsearch,openecomp/sdc-kibana,openecomp/sdc-sanity</image>
+ </configuration>
</execution>
<execution>
@@ -252,19 +230,18 @@
</execution>
<execution>
- <id>push-images</id>
- <phase>deploy</phase>
- <goals>
+ <id>push-images</id>
+ <phase>deploy</phase>
+ <goals>
+ <goal>build</goal>
<goal>push</goal>
- </goals>
- <configuration>
- <image>openecomp/sdc-backend,openecomp/sdc-frontend,openecomp/sdc-elasticsearch,openecomp/sdc-kibana,openecomp/sdc-sanity</image>
- </configuration>
+ </goals>
+ <configuration>
+ <image>openecomp/sdc-backend,openecomp/sdc-frontend,openecomp/sdc-elasticsearch,openecomp/sdc-kibana,openecomp/sdc-sanity</image>
+ </configuration>
</execution>
</executions>
-
</plugin>
-
</plugins>
</build>
</profile>
diff --git a/sdc-os-chef/scripts/docker_build.sh b/sdc-os-chef/scripts/docker_build.sh
new file mode 100644
index 0000000000..03c922ee77
--- /dev/null
+++ b/sdc-os-chef/scripts/docker_build.sh
@@ -0,0 +1,196 @@
+#!/bin/bash
+#set -x
+
+
+function usage
+{
+ echo "usage: docker_run.sh [ -r|--release <RELEASE-NAME> ] [ -e|--environment <ENV-NAME> ] [ -p|--port <Docker-hub-port>] [ -h|--help ]"
+}
+
+
+function print_log () {
+ funcname=$1
+ lineno=$2
+ sev=$3
+ msg=$4
+ dd=`date +"%Y-%m-%d %H:%M:%S"`
+ case ${sev} in
+ "INFO")
+ COLOR="\033[1;32m" # GREEN
+ ;;
+ "ERROR")
+ COLOR="\033[1;31m" # RED
+ ;;
+ esac
+ echo -e "$dd: $fname, $funcname:$lineno --- ${COLOR} $msg\e[0m" |tee -a $LOG
+
+}
+
+
+
+function conf_proxy () {
+ grep http_proxy Dockerfile || /bin/sed -i '/FROM/a ARG http_proxy=http://one.proxy.att.com:8080\nARG https_proxy=http://one.proxy.att.com:8080' Dockerfile
+}
+
+###################################
+######### Parameters #########
+###################################
+
+WORKSPACE=$1
+WORK_DIR=/data/sdc-os-chef
+LOGFILE=`basename $0|awk -F. '{print $1".log"}'`
+LOG=$WORK_DIR/$LOGFILE
+DOCKER_REP=dockercentral.it.att.com:5100
+ECOMP_REP=${DOCKER_REP}/com.att.sdc/openecomp
+REL=`/usr/bin/xml_grep --text_only parent/version /data/sdc-os-chef/pom.xml`
+DOX_VER=` /bin/grep AMDOCS /data/sdc-os-chef/versions.properties | awk '{print $2}' | awk -F"." '{print $1}'`
+DOX_NUM=` /bin/grep AMDOCS /data/sdc-os-chef/versions.properties | awk '{print $2}' | awk -F"." '{print substr($NF,1,4)}' `
+VERSION=` /bin/grep ASDC /data/sdc-os-chef/versions.properties | awk '{print $2}' `
+MAVEN_REPO=mavencentral.it.att.com:8084/nexus/content/repositories
+ONBOARD_GR=com/att/asdc/onboarding/${DOX_VER}/${DOX_NUM}
+
+
+[ -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}
+
+[ -f /opt/config/nexus_username.txt ] && docker login -u $NEXUS_USERNAME -p $NEXUS_PASSWD $NEXUS_DOCKER_REPO
+#docker login -u m09875@sdc.att.com -p Aa1234%^! -e mg877n@att.com dockercentral.it.att.com:5100
+
+
+###################################
+######## MAIN ########
+###################################
+print_log Main $LINENO INFO "##### $0 completed #####"
+
+###################################
+######## sdc-elasticsearch ########
+###################################
+cd /data/sdc-os-chef/sdc-elasticsearch
+print_log Main $LINENO INFO "start creating sdc-elasticsearch ..."
+conf_proxy
+
+docker build -t ${ECOMP_REP}/sdc-elasticsearch:${VERSION} .
+docker tag ${ECOMP_REP}/sdc-elasticsearch:${VERSION} ${ECOMP_REP}/sdc-elasticsearch
+docker push ${ECOMP_REP}/sdc-elasticsearch:${VERSION}
+res=$?
+if [ ${res} -eq 0 ]; then
+ print_log Main $LINENO INFO "${ECOMP_REP}/sdc-elasticsearch:${VERSION} pushed successfully"
+else
+ print_log Main $LINENO ERROR "Error pushing ${ECOMP_REP}/sdc-elasticsearch:${VERSION}"
+fi
+
+
+###################################
+######## sdc-cassandra ########
+###################################
+cd /data/sdc-os-chef/sdc-cassandra
+print_log Main $LINENO INFO "start creating sdc-cassandra ..."
+
+conf_proxy
+
+docker build -t ${ECOMP_REP}/sdc-cassandra:${VERSION} .
+docker tag ${ECOMP_REP}/sdc-cassandra:$VERSION ${ECOMP_REP}/sdc-cassandra
+docker push ${ECOMP_REP}/sdc-cassandra:$VERSION
+res=$?
+if [ ${res} -eq 0 ]; then
+ print_log Main $LINENO INFO "${ECOMP_REP}/sdc-cassandra:${VERSION} pushed successfully"
+else
+ print_log Main $LINENO ERROR "Error pushing ${ECOMP_REP}/sdc-cassandra:${VERSION}"
+fi
+
+
+
+###################################
+######## sdc-kibana ########
+###################################
+cd /data/sdc-os-chef/sdc-kibana
+print_log Main $LINENO INFO "start creating sdc-kibana ..."
+
+conf_proxy
+
+docker build -t ${ECOMP_REP}/sdc-kibana:$VERSION .
+docker tag ${ECOMP_REP}/sdc-kibana:$VERSION ${ECOMP_REP}/sdc-kibana
+docker push ${ECOMP_REP}/sdc-kibana:$VERSION
+res=$?
+if [ ${res} -eq 0 ]; then
+ print_log Main $LINENO INFO "${ECOMP_REP}/sdc-kibana:${VERSION} pushed successfully"
+else
+ print_log Main $LINENO ERROR "Error pushing ${ECOMP_REP}/sdc-kibana:${VERSION}"
+fi
+
+
+###################################
+######## sdc-sanity ########
+###################################
+cd /data/sdc-os-chef/sdc-sanity
+print_log Main $LINENO INFO "start creating sdc-sanity ..."
+
+conf_proxy
+
+docker build -t ${ECOMP_REP}/sdc-sanity:$VERSION .
+docker tag ${ECOMP_REP}/sdc-sanity:$VERSION ${ECOMP_REP}/sdc-sanity
+docker push ${ECOMP_REP}/sdc-sanity:$VERSION
+res=$?
+if [ ${res} -eq 0 ]; then
+ print_log Main $LINENO INFO "${ECOMP_REP}/sdc-sanity:${VERSION} pushed successfully"
+else
+ print_log Main $LINENO ERROR "Error pushing ${ECOMP_REP}/sdc-sanity:${VERSION}"
+fi
+
+
+###################################
+######## sdc-backend ########
+###################################
+cd /data/sdc-os-chef/sdc-backend
+print_log Main $LINENO INFO "start creating sdc-backend ..."
+
+conf_proxy
+/bin/sed -i "s/__SDC-RELEASE__/${REL}/g" Dockerfile
+
+wget -q -nd -r --no-parent -A 'onboard-main*.tar' http://${MAVEN_REPO}/att-repository-snapshots/${ONBOARD_GR}/onboard-main
+if [ $? -ne 0 ] ; then
+ wget -q -nd -r --no-parent -A 'onboard-main*.tar' http://${MAVEN_REPO}/att-repository-releases/${ONBOARD_GR}/onboard-main
+fi
+/bin/tar -xf onboard-main-${DOX_VER}.*.tar --wildcards --no-anchored "onboarding-be-${DOX_VER}.*.war"
+rm onboard-main*.tar
+
+docker build -t ${ECOMP_REP}/sdc-backend:$VERSION .
+docker tag ${ECOMP_REP}/sdc-backend:$VERSION ${ECOMP_REP}/sdc-backend
+docker push ${ECOMP_REP}/sdc-backend:$VERSION
+res=$?
+if [ ${res} -eq 0 ]; then
+ print_log Main $LINENO INFO "${ECOMP_REP}/sdc-backend:${VERSION} pushed successfully"
+else
+ print_log Main $LINENO ERROR "Error pushing ${ECOMP_REP}/sdc-backend:${VERSION}"
+fi
+
+
+###################################
+######## sdc-frontend ########
+###################################
+cd /data/sdc-os-chef/sdc-frontend
+print_log Main $LINENO INFO "start creating sdc-frontend ..."
+
+conf_proxy
+
+/bin/sed -i "s/__SDC-RELEASE__/${REL}/g" Dockerfile
+wget -q -nd -r --no-parent -A 'onboard-main*.tar' http://${MAVEN_REPO}/att-repository-snapshots/${ONBOARD_GR}/onboard-main
+if [ $? -ne 0 ] ; then
+ wget -q -nd -r --no-parent -A 'onboard-main*.tar' http://${MAVEN_REPO}/att-repository-releases/${ONBOARD_GR}/onboard-main
+fi
+/bin/tar -xf onboard-main-${DOX_VER}.*.tar --wildcards --no-anchored "onboarding-fe-${DOX_VER}.*.war"
+rm onboard-main*.tar
+
+docker build -t ${ECOMP_REP}/sdc-frontend:$VERSION .
+docker tag ${ECOMP_REP}/sdc-frontend:$VERSION ${ECOMP_REP}/sdc-frontend
+docker push ${ECOMP_REP}/sdc-frontend:$VERSION
+res=$?
+if [ ${res} -eq 0 ]; then
+ print_log Main $LINENO INFO "${ECOMP_REP}/sdc-frontend:${VERSION} pushed successfully"
+else
+ print_log Main $LINENO ERROR "Error pushing ${ECOMP_REP}/sdc-frontend:${VERSION}"
+fi
+
+print_log Main $LINENO INFO "##### $0 completed #####"
diff --git a/sdc-os-chef/scripts/docker_clean.sh b/sdc-os-chef/scripts/docker_clean.sh
index 6fe1ff615d..3979de6e73 100755
--- a/sdc-os-chef/scripts/docker_clean.sh
+++ b/sdc-os-chef/scripts/docker_clean.sh
@@ -5,3 +5,4 @@ do
docker rm -f ${X}
done
+
diff --git a/sdc-os-chef/scripts/docker_health.sh b/sdc-os-chef/scripts/docker_health.sh
index 1db5282446..832b25a237 100755
--- a/sdc-os-chef/scripts/docker_health.sh
+++ b/sdc-os-chef/scripts/docker_health.sh
@@ -14,7 +14,7 @@ curl http://localhost:8181/sdc1/rest/healthCheck
echo ""
echo ""
res=`curl -s -X GET -H "Accept: application/json" -H "Content-Type: application/json" -H "USER_ID: jh0003" "http://localhost:8080/sdc2/rest/v1/user/demo" | wc -l`
-if [[ ! ${res} -eq 0 ]]
+if [[ ${res} != 0 ]]
then
echo "Error [${res}] while user existance check"
exit ${res}
diff --git a/sdc-os-chef/scripts/docker_run.sh b/sdc-os-chef/scripts/docker_run.sh
index f885c76d67..23c443e22d 100755
--- a/sdc-os-chef/scripts/docker_run.sh
+++ b/sdc-os-chef/scripts/docker_run.sh
@@ -73,12 +73,12 @@ docker run --detach --name sdc-es --env ENVNAME="${DEP_ENV}" --log-driver=json-f
# cassandra
echo "docker run sdc-cassandra..."
docker pull ${NEXUS_DOCKER_REPO}/openecomp/sdc-cassandra:${RELEASE}
-docker run --detach --name sdc-cs --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 /data/CS:/var/lib/cassandra --volume /data/environments:/root/chef-solo/environments --publish 9042:9042 --publish 9160:9160 ${NEXUS_DOCKER_REPO}/openecomp/sdc-cassandra:${RELEASE}
+docker run --detach --name sdc-cs --env RELEASE="${RELEASE}" --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 /data/CS:/var/lib/cassandra --volume /data/environments:/root/chef-solo/environments --publish 9042:9042 --publish 9160:9160 ${NEXUS_DOCKER_REPO}/openecomp/sdc-cassandra:${RELEASE}
echo "please wait while CS is starting..."
echo ""
-c=25 # seconds to wait
+c=120 # seconds to wait
REWRITE="\e[25D\e[1A\e[K"
while [ $c -gt 0 ]; do
c=$((c-1))
diff --git a/sdc-os-chef/sdc-backend/Dockerfile b/sdc-os-chef/sdc-backend/Dockerfile
index 128387ae14..e43a156d47 100644
--- a/sdc-os-chef/sdc-backend/Dockerfile
+++ b/sdc-os-chef/sdc-backend/Dockerfile
@@ -1,4 +1,4 @@
-FROM jetty:9.3.15-jre8
+FROM jetty:9.3-jre8
RUN apt-get -y update
RUN apt-get -y install apt-utils
@@ -16,12 +16,10 @@ RUN pip install pycurl
# install chef-solo
RUN curl -L https://omnitruck.chef.io/install.sh | bash
-ADD onboarding-be-__SDC-RELEASE__.war ${JETTY_BASE}/webapps/
-ADD catalog-be-__SDC-RELEASE__.war ${JETTY_BASE}/webapps/
+ADD onboarding-be-*.war ${JETTY_BASE}/webapps/
+ADD catalog-be-*.war ${JETTY_BASE}/webapps/
RUN chown -R jetty:jetty ${JETTY_BASE}/webapps
COPY startup.sh /root/
-
RUN chmod 770 /root/startup.sh
-
ENTRYPOINT [ "/root/startup.sh" ]
diff --git a/sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/attributes/default.rb b/sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/attributes/default.rb
index 4287ca8617..f011a51021 100644
--- a/sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/attributes/default.rb
+++ b/sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/attributes/default.rb
@@ -1 +1,3 @@
-# \ No newline at end of file
+#
+# Example to value after replacement : default['asdctool'][:version] = "1707.0.66.73.1"
+default['asdctool'][:version] = "__CATALOG-ASDCTOOL_TAR_NAME__" \ No newline at end of file
diff --git a/sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/recipes/BE_4_setup_configuration.rb b/sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/recipes/BE_4_setup_configuration.rb
index 4facd4247c..2c4a786d34 100644
--- a/sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/recipes/BE_4_setup_configuration.rb
+++ b/sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/recipes/BE_4_setup_configuration.rb
@@ -10,8 +10,8 @@ template "titan.properties" do
:CASSANDRA_IP => node['Nodes']['CS'],
:CASSANDRA_PWD => node['cassandra'][:cassandra_password],
:CASSANDRA_USR => node['cassandra'][:cassandra_user],
- :DC_NAME => "DC-"+node.chef_environment,
- :rep_factor => replication_factor
+ :rep_factor => replication_factor,
+ :DC_NAME => node['cassandra'][:cluster_name]+node.chef_environment
})
end
@@ -28,7 +28,7 @@ template "catalog-be-config" do
:ssl_port => node['BE'][:https_port],
:cassandra_ip => node['Nodes']['CS'],
:rep_factor => 1,
- :DC_NAME => "DC-"+node.chef_environment
+ :DC_NAME => node['cassandra'][:cluster_name]+node.chef_environment
})
end
diff --git a/sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/templates/default/BE-configuration.yaml.erb b/sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/templates/default/BE-configuration.yaml.erb
index c12c1b4ff6..97732908c4 100644
--- a/sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/templates/default/BE-configuration.yaml.erb
+++ b/sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/templates/default/BE-configuration.yaml.erb
@@ -22,6 +22,8 @@ beProtocol: http
beSslPort: <%= @ssl_port %>
version: 1.0
released: 2012-11-30
+toscaConformanceLevel: 3.0
+minToscaConformanceLevel: 3.0
titanCfgFile: /var/lib/jetty/config/catalog-be/titan.properties
titanInMemoryGraph: false
diff --git a/sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/templates/default/BE-titan.properties.erb b/sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/templates/default/BE-titan.properties.erb
index 27386d47ef..a42c7bf206 100644
--- a/sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/templates/default/BE-titan.properties.erb
+++ b/sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/templates/default/BE-titan.properties.erb
@@ -4,6 +4,7 @@ storage.port=9160
storage.username=<%= @CASSANDRA_USR %>
storage.password=<%= @CASSANDRA_PWD %>
storage.connection-timeout=10000
+storage.cassandra.keyspace=sdctitan
storage.cassandra.ssl.enabled=false
storage.cassandra.ssl.truststore.location=/var/lib/jetty/config/.truststore
diff --git a/sdc-os-chef/sdc-cassandra/Dockerfile b/sdc-os-chef/sdc-cassandra/Dockerfile
index 1ec802c39b..3e9295db5e 100644
--- a/sdc-os-chef/sdc-cassandra/Dockerfile
+++ b/sdc-os-chef/sdc-cassandra/Dockerfile
@@ -18,4 +18,4 @@ RUN curl -L https://omnitruck.chef.io/install.sh | bash
COPY startup.sh /root/
RUN chmod 770 /root/startup.sh
-ENTRYPOINT [ "/root/startup.sh" ] \ No newline at end of file
+ENTRYPOINT [ "/root/startup.sh" ]
diff --git a/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/files/default/alter_dox_db.cql b/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/files/default/alter_dox_db.cql
new file mode 100644
index 0000000000..e0250b6502
--- /dev/null
+++ b/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/files/default/alter_dox_db.cql
@@ -0,0 +1,7 @@
+USE dox;
+ALTER TABLE vsp_information ADD questionnaire_data text;
+ALTER TABLE vsp_information ADD vlm_version frozen<version>;
+ALTER TABLE vsp_process ADD type text;
+alter table entitlement_pool ADD version_uuid text;
+alter table license_key_group ADD version_uuid text;
+delete from application_config where namespace='vsp.monitoring' and key = 'component.ceilometer';
diff --git a/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/files/default/create_dox_db.cql b/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/files/default/create_dox_db.cql
new file mode 100644
index 0000000000..fa0831051a
--- /dev/null
+++ b/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/files/default/create_dox_db.cql
@@ -0,0 +1,52 @@
+USE dox;
+CREATE TYPE IF NOT EXISTS version (major int, minor int);
+CREATE TYPE IF NOT EXISTS user_candidate_version (version frozen<version>, user text);
+CREATE TABLE IF NOT EXISTS version_info (entity_type text, entity_id text, active_version frozen<version>, status text, candidate frozen<user_candidate_version>, viewable_versions set<frozen<version>>, latest_final_version frozen<version>, PRIMARY KEY (entity_type, entity_id));
+CREATE TABLE IF NOT EXISTS version_info_deleted (entity_type text, entity_id text, active_version frozen<version>, status text, candidate frozen<user_candidate_version>, viewable_versions set<frozen<version>>, latest_final_version frozen<version>, PRIMARY KEY (entity_type, entity_id));
+CREATE TABLE IF NOT EXISTS unique_value (type text, value text, PRIMARY KEY ((type, value)));
+CREATE TYPE IF NOT EXISTS choice_or_other (result text);
+CREATE TYPE IF NOT EXISTS multi_choice_or_other (results set<text>);
+CREATE TABLE IF NOT EXISTS vendor_license_model (vlm_id text, version frozen<version>, vendor_name text, description text, icon text, PRIMARY KEY ((vlm_id, version)));
+CREATE TABLE IF NOT EXISTS license_agreement (vlm_id text, version frozen<version>, la_id text, name text, description text, lic_term frozen<choice_or_other>, req_const text, fg_ids set<text>, PRIMARY KEY ((vlm_id, version), la_id));
+CREATE TABLE IF NOT EXISTS feature_group (vlm_id text, version frozen<version>, fg_id text, name text, description text, part_num text, ep_ids set<text>, lkg_ids set<text>, ref_la_ids set<text>, PRIMARY KEY ((vlm_id, version), fg_id));
+CREATE TABLE IF NOT EXISTS license_key_group (vlm_id text, version frozen<version>, lkg_id text,name text,description text, type text, operational_scope frozen<multi_choice_or_other>, ref_fg_ids set<text>, version_uuid text, PRIMARY KEY ((vlm_id, version), lkg_id));
+CREATE TABLE IF NOT EXISTS entitlement_pool (vlm_id text, version frozen<version>, ep_id text,name text,description text,threshold float,threshold_unit text,entitlement_metric frozen<choice_or_other>,increments text,aggregation_func frozen<choice_or_other>, operational_scope frozen<multi_choice_or_other>, time frozen<choice_or_other>,manufacturer_ref_num text,ref_fg_ids set<text>, version_uuid text, PRIMARY KEY ((vlm_id, version), ep_id));
+CREATE TABLE IF NOT EXISTS vsp_information (VSP_ID text, version frozen<version>, NAME text,DESCRIPTION text,CATEGORY text,SUB_CATEGORY text,ICON text,PACKAGE_NAME text,PACKAGE_VERSION text,vendor_name text, vendor_id text,LICENSE_AGREEMENT text,FEATURE_GROUPS list<text>,VALIDATION_DATA text,CONTENT_DATA blob, questionnaire_data text, vlm_version frozen<version>, is_old_version text, PRIMARY KEY ((VSP_ID, version)));
+CREATE TABLE IF NOT EXISTS package_details (VSP_ID text, version frozen<version>,DISPLAY_NAME text,vsp_name text,vsp_description text,VENDOR_NAME text,CATEGORY text,SUB_CATEGORY text,VENDOR_RELEASE text,PACKAGE_CHECKSUM text,PACKAGE_TYPE text,TRANSLATE_CONTENT blob,PRIMARY KEY ((VSP_ID, version)));
+CREATE TABLE IF NOT EXISTS vsp_network (vsp_id text, version frozen<version>, network_id text, composition_data text, questionnaire_data text, PRIMARY KEY ((vsp_id, version), network_id));
+CREATE TABLE IF NOT EXISTS vsp_component (vsp_id text, version frozen<version>, component_id text, composition_data text, questionnaire_data text, PRIMARY KEY ((vsp_id, version), component_id));
+CREATE TABLE IF NOT EXISTS vsp_component_nic (vsp_id text, version frozen<version>, component_id text, nic_id text, composition_data text, questionnaire_data text, PRIMARY KEY ((vsp_id, version), component_id, nic_id));
+CREATE TABLE IF NOT EXISTS vsp_process (vsp_id text, version frozen<version>, component_id text, process_id text, name text, description text, type text, artifact_name text, artifact blob, PRIMARY KEY ((vsp_id, version), component_id, process_id));
+CREATE TABLE IF NOT EXISTS vsp_service_artifact (vsp_id text, version frozen<version>, name text, content_data blob, PRIMARY KEY ((vsp_id, version), name));
+CREATE TABLE IF NOT EXISTS vsp_service_template (vsp_id text, version frozen<version>, base_name text static, name text, content_data blob, PRIMARY KEY ((vsp_id, version), name));
+CREATE TABLE IF NOT EXISTS vsp_enriched_service_template (vsp_id text, version frozen<version>, base_name text static, name text, content_data blob, PRIMARY KEY ((vsp_id, version), name));
+CREATE TABLE IF NOT EXISTS vsp_enriched_service_artifact (vsp_id text, version frozen<version>, name text, content_data blob, PRIMARY KEY ((vsp_id, version), name));
+CREATE TABLE IF NOT EXISTS application_config (namespace text, key text, value text, PRIMARY KEY (namespace, key));
+CREATE TABLE IF NOT EXISTS dox.Action (actionUUID text, actionInvariantUUID text, version frozen<version>, status text, name text, vendor_list set<text>, category_list set<text>, timestamp timestamp, user text, supportedModels set<text>, supportedComponents set<text>, data text, PRIMARY KEY ((actionInvariantUUID, version)));
+CREATE INDEX IF NOT EXISTS action_supportedComponents ON dox.Action (supportedComponents);
+CREATE INDEX IF NOT EXISTS action_category_list ON dox.Action (category_list);
+CREATE INDEX IF NOT EXISTS action_supportedModels ON dox.Action (supportedModels);
+CREATE INDEX IF NOT EXISTS action_vendor_list ON dox.Action (vendor_list);
+CREATE INDEX IF NOT EXISTS action_actionUUID ON dox.Action (actionUUID);
+CREATE TABLE IF NOT EXISTS dox.ecompcomponent(id text PRIMARY KEY, name text);
+CREATE TABLE IF NOT EXISTS vsp_component_artifact (vsp_id text, version frozen<version>, component_id text, artifact_type text, artifact_id text, name text, description text, artifact blob, PRIMARY KEY ((vsp_id, version), component_id, artifact_type, artifact_id));
+CREATE INDEX IF NOT EXISTS action_name ON dox.Action (name);
+CREATE TABLE IF NOT EXISTS action_artifact(artifactuuid text, effective_version int, artifact blob, PRIMARY KEY(artifactuuid, effective_version)) WITH CLUSTERING ORDER BY (effective_version DESC);
+CREATE TABLE IF NOT EXISTS vsp_orchestration_template_candidate (vsp_id text, version frozen<version>, files_data_structure text, content_data blob, PRIMARY KEY ((vsp_id, version)));
+CREATE TABLE IF NOT EXISTS vsp_component_dependency_model (vsp_id text, version frozen<version>, dependency_id text, sourcecomponent_id text, targetcomponent_id text, relation text, PRIMARY KEY ((vsp_id, version), dependency_id));
+CREATE TABLE IF NOT EXISTS activity_log (item_id text, version_id text, activity_id text, type text, user text, timestamp timestamp, success boolean, message text, comment text, PRIMARY KEY (item_id, version_id, activity_id));
+CREATE TABLE IF NOT EXISTS migration (id text, ismigrated boolean, primary key(id));
+INSERT INTO application_config (namespace,key,value) VALUES ('vsp.schemaTemplates', 'composition.network', '{ "$schema": "http://json-schema.org/draft-04/schema#", "type": "object", "properties": { "name": { "type": "string"<#if !manual>, "enum": [ "${network.name}" ], "default": "${network.name}"</#if> }, "dhcp": { "type": "boolean"<#if !manual>, "enum": [ ${network.dhcp?c} ], "default": ${network.dhcp?c}</#if> } }, "additionalProperties": false, "required": [ "name", "dhcp" ] }');
+INSERT INTO application_config (namespace,key,value) VALUES ('vsp.schemaTemplates', 'composition.component', '{ "$schema": "http://json-schema.org/draft-04/schema#", "type": "object", "properties": { "name": { "type": "string"<#if !manual>, "enum": [ "${component.name}" ], "default": "${component.name}"</#if> }, "displayName": { "type": "string"<#if !manual && component.displayName??>, "enum": [ "${component.displayName}" ], "default": "${component.displayName}"</#if> }, "vfcCode": { "type": "string" }, "description": { "type": "string" } }, "additionalProperties": false, "required": [ "name"<#if !manual && component.displayName??>, "displayName"</#if> ] }');
+INSERT INTO application_config (namespace,key,value) VALUES ('vsp.schemaTemplates', 'composition.nic', '{ "$schema": "http://json-schema.org/draft-04/schema#", "type": "object", "properties": { "name": { "type": "string"<#if !manual>, "enum": [ "${nic.name}" ], "default": "${nic.name}" </#if> }, "description": { "type": "string" }<#if !manual><#if nic.networkId??>, "networkId": { "type": "string", "enum": [ "${nic.networkId}" ], "default": "${nic.networkId}" } </#if><#else>, "networkId": { "type": "string", "enum": [<#list networkIds as networkId> "${networkId}"<#sep>,</#list> ] } </#if> }, "additionalProperties": false, "required": [ "name" ] }');
+INSERT INTO application_config (namespace,key,value) VALUES ('vsp.schemaTemplates', 'questionnaire.nic', '{ "$schema": "http://json-schema.org/draft-04/schema#", "type": "object", "properties": { "protocols": { "type": "object", "properties": { "protocols": { "type": "array", "items": { "type": "string", "enum": [ "", "TCP", "UDP", "SCTP", "IPsec" ], "default": "" }, "minItems": 1 }, "protocolWithHighestTrafficProfile": { "$ref": "#/properties/protocols/properties/protocols/items" } }, "additionalProperties": false }, "ipConfiguration": { "type": "object", "properties": { "ipv4Required": { "type": "boolean", "default": true }, "ipv6Required": { "type": "boolean", "default": false } }, "additionalProperties": false }, "network": { "type": "object", "properties": { "networkDescription": { "type": "string", "pattern": "[A-Za-z]+", "maxLength": 300 } }, "additionalProperties": false }, "sizing": { "type": "object", "definitions": { "peakAndAvg": { "type": "object", "properties": { "peak": { "type": "number" }, "avg": { "type": "number" } }, "additionalProperties": false }, "packetsAndBytes": { "type": "object", "properties": { "packets": { "$ref": "#/properties/sizing/definitions/peakAndAvg" }, "bytes": { "$ref": "#/properties/sizing/definitions/peakAndAvg" } }, "additionalProperties": false } }, "properties": { "describeQualityOfService": { "type": "string" }, "inflowTrafficPerSecond": { "$ref": "#/properties/sizing/definitions/packetsAndBytes" }, "outflowTrafficPerSecond": { "$ref": "#/properties/sizing/definitions/packetsAndBytes" }, "flowLength": { "$ref": "#/properties/sizing/definitions/packetsAndBytes" }, "acceptableJitter": { "type": "object", "properties": { "mean": { "type": "number" }, "max": { "type": "number" }, "variable": { "type": "number" } }, "additionalProperties": false }, "acceptablePacketLoss": { "type": "number", "minimum": 0, "maximum": 100 } }, "additionalProperties": false } }, "additionalProperties": false }');
+INSERT INTO application_config (namespace,key,value) VALUES ('vsp.schemaTemplates', 'questionnaire.vsp', '{ "$schema": "http://json-schema.org/draft-04/schema#", "type": "object", "properties": { "general": { "type": "object", "properties": { "affinityData": { "type": "string", "enum": [ "", "Affinity", "Anti Affinity", "None" ], "default": "" }, "availability": { "type": "object", "properties": { "useAvailabilityZonesForHighAvailability": { "type": "boolean", "default": false } }, "additionalProperties": false }, "regionsData": { "type": "object", "properties": { "multiRegion": { "type": "boolean", "default": false }, "regions": { "type": "array", "items": { "type": "string", "enum": [ "", "Alphareta", "Birmingham", "Dallas", "Fairfield CA", "Hayward CA", "Lisle", "Mission", "San Diego", "Secaucus" ], "default": "" } } }, "additionalProperties": false }, "storageDataReplication": { "type": "object", "properties": { "storageReplicationAcrossRegion": { "type": "boolean", "default": false }, "storageReplicationSize": { "type": "number", "maximum": 100, "exclusiveMaximum": true }, "storageReplicationFrequency": { "type": "number", "minimum": 5 }, "storageReplicationSource": { "type": "string", "maxLength": 300 }, "storageReplicationDestination": { "type": "string", "maxLength": 300 } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }');
+INSERT INTO application_config (namespace,key,value) VALUES ('vsp.schemaTemplates', 'questionnaire.component', '{ "$schema": "http://json-schema.org/draft-04/schema#", "type": "object", "properties": { "general": { "type": "object", "properties": { "hypervisor": { "type": "object", "properties": { "hypervisor": { "type": "string", "enum": [ "KVM", "VMWare ESXi" ], "default": "KVM" }, "drivers": { "type": "string", "maxLength": 300, "pattern": "^[A-Za-z0-9_,-]*$" }, "containerFeaturesDescription": { "type": "string", "maxLength": 1000, "pattern": "^[A-Za-z0-9_, -]*$" } }, "additionalProperties": false }, "image": { "type": "object", "properties": { "format": { "type": "string", "enum": [ "aki", "ami", "ari", "iso", "qcow2", "raw", "vdi", "vhd", "vmdk" ], "default": "qcow2" }, "providedBy": { "type": "string", "enum": [ "AIC", "Vendor" ], "default": "AIC" }, "bootDiskSizePerVM": { "type": "number", "maximum": 100 }, "ephemeralDiskSizePerVM": { "type": "number", "maximum": 400 } }, "additionalProperties": false }, "recovery": { "type": "object", "properties": { "pointObjective": { "type": "number", "minimum": 0, "exclusiveMinimum": true, "maximum": 15, "exclusiveMaximum ": true }, "timeObjective": { "type": "number", "minimum": 0, "exclusiveMinimum": true, "maximum": 300, "exclusiveMaximum ": true }, "vmProcessFailuresHandling": { "type": "string" } }, "additionalProperties": false }, "dnsConfiguration": { "type": "string" }, "vmCloneUsage": { "type": "string", "maxLength": 300 } }, "additionalProperties": false }, "compute": { "type": "object", "properties": { "vmSizing": { "type": "object", "properties": { "numOfCPUs": { "type": "number", "minimum": 0, "exclusiveMinimum": true, "maximum": 16, "default": 2 }, "fileSystemSizeGB": { "type": "number", "minimum": 0, "exclusiveMinimum": true, "default": 5 }, "persistentStorageVolumeSize": { "type": "number", "minimum": 0, "exclusiveMinimum": true }, "IOOperationsPerSec": { "type": "number", "minimum": 0, "exclusiveMinimum": true } }, "additionalProperties": false }, "numOfVMs": { "type": "object", "properties": { "minimum": { "type": "number", "minimum": 0, "exclusiveMinimum": true, "maximum": 100 }, "maximum": { "type": "number", "minimum": <#if (componentQuestionnaireData.compute.numOfVMs.minimum)?? && (componentQuestionnaireData.compute.numOfVMs.minimum)?is_number && ((componentQuestionnaireData.compute.numOfVMs.minimum) > 0 && (componentQuestionnaireData.compute.numOfVMs.minimum) <= 100)> ${componentQuestionnaireData.compute.numOfVMs.minimum}<#else> 0</#if> , "exclusiveMinimum": true, "maximum": 100 }, "CpuOverSubscriptionRatio": { "type": "string", "enum": [ "1:1", "4:1", "16:1" ], "default": "4:1" }, "MemoryRAM": { "type": "string", "enum": [ "2 GB", "4 GB", "8 GB" ], "default": "2 GB" } }, "additionalProperties": false }, "guestOS": { "type": "object", "properties": { "name": { "type": "string", "maxLength": 50 }, "bitSize": { "type": "number", "enum": [ 64, 32 ], "default": 64 }, "tools": { "type": "string" } }, "additionalProperties": false } }, "additionalProperties": false }, "highAvailabilityAndLoadBalancing": { "type": "object", "properties": { "isComponentMandatory": { "type": "string", "enum": ["","YES", "NO"], "default": "" }, "highAvailabilityMode": { "type": "string", "enum": ["","geo-activeactive", "geo-activestandby", "local-activeactive", "local-activestandby"], "default": "" }, "failureLoadDistribution": { "type": "string", "maxLength": 1000 }, "nkModelImplementation": { "type": "string", "maxLength": 1000 }, "architectureChoice": { "type": "string", "maxLength": 1000 }, "slaRequirements": { "type": "string", "maxLength": 1000 }, "horizontalScaling": { "type": "string", "maxLength": 1000 }, "loadDistributionMechanism": { "type": "string", "maxLength": 1000 } }, "additionalProperties": false }, "network": { "type": "object", "properties": { "networkCapacity": { "type": "object", "properties": { "protocolWithHighestTrafficProfileAcrossAllNICs": { "type": "string", "enum": [ "", "TCP", "UDP", "SCTP", "IPsec" ], "default": "" }, "networkTransactionsPerSecond": { "type": "number" } }, "additionalProperties": false } }, "additionalProperties": false }, "storage": { "type": "object", "properties": { "backup": { "type": "object", "properties": { "backupType": { "type": "string", "enum": [ "On Site", "Off Site" ], "default": "On Site" }, "backupStorageSize": { "type": "number" }, "backupSolution": { "type": "string" }, "backupNIC": { "type": "string", "enum": [ ""<#if nicNames??><#list nicNames as nicName> , "${nicName}"</#list></#if> ], "default": "" } }, "additionalProperties": false }, "snapshotBackup": { "type": "object", "properties": { "snapshotFrequency": { "type": "number", "default": 24, "minimum": 1, "exclusiveMinimum": true } }, "additionalProperties": false }, "logBackup": { "type": "object", "properties": { "sizeOfLogFiles": { "type": "number", "maximum": 5, "exclusiveMaximum": true }, "logBackupFrequency": { "type": "number", "maximum": 4, "exclusiveMaximum": true }, "logRetentionPeriod": { "type": "number", "maximum": 15, "exclusiveMaximum": true }, "logFileLocation": { "type": "string", "maxLength": 300 } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }');
+INSERT INTO application_config (namespace,key,value) VALUES ('vsp.monitoring', 'compute.ceilometer', '{ "ceilometerMetricList": [ { "name": "instance", "type": "Gauge", "unit": "instance", "category": "compute", "description": "Existence of instance" }, { "name": "memory", "type": "Gauge", "unit": "MB", "category": "compute", "description": "Volume of RAM allocated to the instance" }, { "name": "memory.usage", "type": "Gauge", "unit": "MB", "category": "compute", "description": "Volume of RAM used by the instance from the amount of its allocated memory" }, { "name": "memory.resident", "type": "Gauge", "unit": "MB", "category": "compute", "description": "Volume of RAM used by the instance on the physical machine" }, { "name": "cpu", "type": "Cumulative", "unit": "ns", "category": "compute", "description": "CPU time used" }, { "name": "cpu_util", "type": "Gauge", "unit": "%", "category": "compute", "description": "Average CPU utilization" }, { "name": "cpu.delta", "type": "Delta", "unit": "ns", "category": "compute", "description": "CPU time used since previous datapoint" }, { "name": "vcpus", "type": "Gauge", "unit": "vcpu", "category": "compute", "description": "Number of virtual CPUs allocated to the instance" }, { "name": "disk.latency", "type": "Gauge", "unit": "ms", "category": "disk", "description": "Average disk latency" }, { "name": "disk.iops", "type": "Gauge", "unit": "count/s", "category": "disk", "description": "Average disk iops" }, { "name": "disk.device.latency", "type": "Gauge", "unit": "ms", "category": "disk", "description": "Average disk latency per device" }, { "name": "disk.device.iops", "type": "Gauge", "unit": "count/s", "category": "disk", "description": "Average disk iops per device" }, { "name": "disk.capacity", "type": "Gauge", "unit": "B", "category": "disk", "description": "The amount of disk that the instance can see" }, { "name": "disk.allocation", "type": "Gauge", "unit": "B", "category": "disk", "description": "The amount of disk occupied by the instance on the host machine" }, { "name": "disk.usage", "type": "Gauge", "unit": "B", "category": "disk", "description": "The physical size in bytes of the image container on the host" }, { "name": "disk.device.capacity", "type": "Gauge", "unit": "B", "category": "disk", "description": "The amount of disk per device that the instance can see" }, { "name": "disk.device.allocation", "type": "Gauge", "unit": "B", "category": "disk", "description": "The amount of disk per device occupied by the instance on the host machine" }, { "name": "disk.device.usage", "type": "Gauge", "unit": "B", "category": "disk", "description": "The physical size in bytes of the image container on the host per device" }, { "name": "disk.device.read.requests", "type": "Cumulative", "unit": "request", "category": "disk", "description": "Number of read requests" }, { "name": "disk.device.read.requests.rate", "type": "Gauge", "unit": "request/s", "category": "disk", "description": "Average rate of read requests" }, { "name": "disk.device.write.requests", "type": "Cumulative", "unit": "request", "category": "disk", "description": "Number of write requests" }, { "name": "disk.device.write.requests.rate", "type": "Gauge", "unit": "request/s", "category": "disk", "description": "Average rate of write requests" }, { "name": "disk.device.read.bytes", "type": "Cumulative", "unit": "B", "category": "disk", "description": "Volume of reads" }, { "name": "disk.device.read.bytes.rate", "type": "Gauge", "unit": "B/s", "category": "disk", "description": "Average rate of reads" }, { "name": "disk.device.write.bytes", "type": "Cumulative", "unit": "B", "category": "disk", "description": "Volume of writes" }, { "name": "disk.device.write.bytes.rate", "type": "Gauge", "unit": "B/s", "category": "disk", "description": "Average rate of writes" }, { "name": "disk.write.requests", "type": "Cumulative", "unit": "request", "category": "compute", "description": "Number of write requests" }, { "name": "disk.write.requests.rate", "type": "Gauge", "unit": "request/s", "category": "compute", "description": "Average rate of write requests" }, { "name": "disk.read.bytes", "type": "Cumulative", "unit": "B", "category": "compute", "description": "Volume of reads" }, { "name": "disk.read.bytes.rate", "type": "Gauge", "unit": "B/s", "category": "compute", "description": "Average rate of reads" }, { "name": "disk.write.bytes", "type": "Cumulative", "unit": "B", "category": "compute", "description": "Volume of writes" }, { "name": "disk.write.bytes.rate", "type": "Gauge", "unit": "B/s", "category": "compute", "description": "Average rate of writes" }, { "name": "disk.read.requests", "type": "Cumulative", "unit": "request", "category": "compute", "description": "Number of read requests" }, { "name": "disk.root.size", "type": "Gauge", "unit": "GB", "category": "compute", "description": "Size of root disk" }, { "name": "disk.ephemeral.size", "type": "Gauge", "unit": "GB", "category": "compute", "description": "Size of ephemeral disk" } ] }');
+INSERT INTO application_config (namespace,key,value) VALUES ('vsp.monitoring', 'port.ceilometer', '{ "ceilometerMetricList": [ { "name": "network.incoming.bytes", "type": "Cumulative", "unit": "B", "category": "network", "description": "Number of incoming bytes" }, { "name": "network.incoming.bytes.rate", "type": "Gauge", "unit": "B/s", "category": "network", "description": "Average rate of incoming bytes" }, { "name": "network.outgoing.bytes", "type": "Cumulative", "unit": "B", "category": "network", "description": "Number of outgoing bytes" }, { "name": "network.outgoing.bytes.rate", "type": "Gauge", "unit": "B/s", "category": "network", "description": "Average rate of outgoing bytes" }, { "name": "network.incoming.packets", "type": "Cumulative", "unit": "packet", "category": "network", "description": "Number of incoming packets" }, { "name": "network.incoming.packets.rate", "type": "Gauge", "unit": "packet/s", "category": "network", "description": "Average rate of incoming packets" }, { "name": "network.outpoing.packets", "type": "Cumulative", "unit": "packet", "category": "network", "description": "Number of outgoing packets" }, { "name": "network.outgoing.packets.rate", "type": "Gauge", "unit": "packet/s", "category": "network", "description": "Average rate of outgoing packets" } ] }');
+USE zusammen_dox;
+CREATE TABLE IF NOT EXISTS item (item_id text primary key, item_info text, creation_time timestamp, modification_time timestamp);
+CREATE TABLE IF NOT EXISTS version (space text, item_id text, version_id text,base_version_id text,info text,relations text,creation_time timestamp,modification_time timestamp,PRIMARY KEY (( space, item_id ), version_id));
+CREATE TABLE IF NOT EXISTS version_elements (space text,item_id text,version_id text,element_ids set<text>,PRIMARY KEY (( space, item_id, version_id )));
+CREATE TABLE IF NOT EXISTS element_namespace (space text, item_id text, element_id text, namespace text, PRIMARY KEY ((space, item_id, element_id)));
+CREATE TABLE IF NOT EXISTS element (space text,item_id text,version_id text,element_id text,parent_id text,namespace text,info text,relations text,data blob,searchable_data blob,visualization blob,sub_element_ids set<text>,PRIMARY KEY (( space, item_id, version_id, element_id )));
diff --git a/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/files/default/titan.properties b/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/files/default/titan.properties
new file mode 100644
index 0000000000..43944eae47
--- /dev/null
+++ b/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/files/default/titan.properties
@@ -0,0 +1,6 @@
+storage.backend=cassandra
+storage.hostname=localhost
+storage.port=9160
+storage.username=asdc_user
+storage.password=Aa1234%^!
+storage.cassandra.keyspace=sdctitan \ No newline at end of file
diff --git a/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/files/default/zusammen.tgz b/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/files/default/zusammen.tgz
new file mode 100644
index 0000000000..0a9842917d
--- /dev/null
+++ b/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/files/default/zusammen.tgz
Binary files differ
diff --git a/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/recipes/01-configureCassandra.rb b/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/recipes/01-configureCassandra.rb
index 9313aa87ff..f167c3ec8d 100644
--- a/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/recipes/01-configureCassandra.rb
+++ b/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/recipes/01-configureCassandra.rb
@@ -16,6 +16,7 @@ end
template "cassandra-yaml-config" do
path "/etc/cassandra/cassandra.yaml"
source "cassandra.yaml.erb"
+ sensitive true
owner "cassandra"
group "cassandra"
mode "0755"
@@ -43,7 +44,7 @@ template "cassandra-rackdc.properties" do
group "cassandra"
mode "0755"
variables ({
- :dc => "DC-"+node.chef_environment,
+ :dc => cluster_name,
:rack => "Rack"+"#{rackNum}-"+node.chef_environment
})
end
diff --git a/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/recipes/02-createCsUser.rb b/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/recipes/02-createCsUser.rb
index 627bd6fe7e..1ebc80d5e4 100644
--- a/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/recipes/02-createCsUser.rb
+++ b/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/recipes/02-createCsUser.rb
@@ -1,8 +1,15 @@
template "/tmp/create_cassandra_user.sh" do
source "create_cassandra_user.sh.erb"
+ sensitive true
mode 0755
variables({
:cassandra_ip => "HOSTIP"
})
end
+
+bash "create-sdc-user" do
+ code <<-EOH
+ cd /tmp ; /tmp/create_cassandra_user.sh
+ EOH
+end
diff --git a/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/recipes/03-createDoxKeyspace.rb b/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/recipes/03-createDoxKeyspace.rb
index 92a81eb7dc..e54932d1c4 100644
--- a/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/recipes/03-createDoxKeyspace.rb
+++ b/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/recipes/03-createDoxKeyspace.rb
@@ -1,8 +1,32 @@
template "/tmp/create_dox_keyspace.sh" do
source "create_dox_keyspace.sh.erb"
+ sensitive true
mode 0755
variables({
- :cassandra_ip => "HOSTIP"
+ :cassandra_ip => "HOSTIP",
+ :DC_NAME => node['cassandra'][:cluster_name]+node.chef_environment
})
end
+
+cookbook_file "/tmp/create_dox_db.cql" do
+ sensitive true
+ source "create_dox_db.cql"
+ mode 0755
+end
+
+cookbook_file "/tmp/alter_dox_db.cql" do
+ sensitive true
+ source "alter_dox_db.cql"
+ mode 0755
+end
+
+
+bash "create-DOX-schema" do
+ ignore_failure true
+ code <<-EOH
+ cd /tmp
+ chmod +x /tmp/create_dox_keyspace.sh
+ /tmp/create_dox_keyspace.sh
+ EOH
+end
diff --git a/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/recipes/04-schemaCreation.rb b/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/recipes/04-schemaCreation.rb
index 7c40c509c2..5890603829 100644
--- a/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/recipes/04-schemaCreation.rb
+++ b/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/recipes/04-schemaCreation.rb
@@ -7,12 +7,24 @@ end
bash "install tar" do
cwd "/tmp"
code <<-EOH
- /bin/tar xvf /tmp/sdctool.tar -C /tmp
+ /bin/tar xf /tmp/sdctool.tar -C /tmp
EOH
end
+template "titan.properties" do
+ sensitive true
+ path "/tmp/sdctool/config/titan.properties"
+ source "titan.properties.erb"
+ mode "0755"
+ variables({
+ :DC_NAME => node['cassandra'][:cluster_name]+node.chef_environment
+ })
+end
+
+
template "/tmp/sdctool/config/configuration.yaml" do
+ sensitive true
source "configuration.yaml.erb"
mode 0755
variables({
@@ -21,11 +33,14 @@ template "/tmp/sdctool/config/configuration.yaml" do
:ssl_port => node['BE'][:https_port],
:cassandra_ip => node['Nodes']['CS'],
:rep_factor => 1,
- :dc1 => "DC-"+node.chef_environment
+ :DC_NAME => node['cassandra'][:cluster_name]+node.chef_environment,
+ :titan_Path => "/tmp/sdctool/config/"
})
end
+
template "/tmp/sdctool/config/elasticsearch.yml" do
+ sensitive true
source "elasticsearch.yml.erb"
mode 0755
variables({
@@ -33,3 +48,11 @@ template "/tmp/sdctool/config/elasticsearch.yml" do
})
end
+
+bash "excuting-schema-creation" do
+ code <<-EOH
+ cd /tmp
+ chmod +x /tmp/sdctool/scripts/schemaCreation.sh
+ /tmp/sdctool/scripts/schemaCreation.sh /tmp/sdctool/config
+ EOH
+end
diff --git a/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/recipes/05-titanSchemaCreation.rb b/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/recipes/05-titanSchemaCreation.rb
new file mode 100644
index 0000000000..a3af2f490f
--- /dev/null
+++ b/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/recipes/05-titanSchemaCreation.rb
@@ -0,0 +1,61 @@
+cookbook_file "/tmp/sdctool.tar" do
+ sensitive true
+ source "sdctool.tar"
+ mode 0755
+end
+
+## extract sdctool.tar
+bash "install tar" do
+ cwd "/tmp"
+ code <<-EOH
+ /bin/tar xf /tmp/sdctool.tar -C /tmp
+ EOH
+end
+
+
+template "titan.properties" do
+ sensitive true
+ path "/tmp/sdctool/config/titan.properties"
+ source "titan.properties.erb"
+ mode "0755"
+ variables({
+ :DC_NAME => node['cassandra'][:cluster_name]+node.chef_environment
+ })
+end
+
+
+template "/tmp/sdctool/config/configuration.yaml" do
+ sensitive true
+ source "configuration.yaml.erb"
+ mode 0755
+ variables({
+ :host_ip => node['HOST_IP'],
+ :catalog_port => node['BE'][:http_port],
+ :ssl_port => node['BE'][:https_port],
+ :cassandra_ip => node['Nodes']['CS'],
+ :rep_factor => 1,
+ :DC_NAME => node['cassandra'][:cluster_name]+node.chef_environment,
+ :titan_Path => "/tmp/sdctool/config"
+ })
+end
+
+template "/tmp/sdctool/config/elasticsearch.yml" do
+ sensitive true
+ source "elasticsearch.yml.erb"
+ mode 0755
+ variables({
+ :elastic_ip => "HOSTIP"
+ })
+end
+
+
+bash "excuting-titanSchemaCreation.sh" do
+ code <<-EOH
+ echo "XXXXXXXXXXXX executing /tmp/sdctool/scripts/titanSchemaCreation.sh XXXXXXXXXXXX"
+ chmod +x /tmp/sdctool/scripts/titanSchemaCreation.sh
+ /tmp/sdctool/scripts/titanSchemaCreation.sh /tmp/sdctool/config
+ EOH
+end
+
+
+
diff --git a/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/recipes/06-migrateZusammenFromDox.rb b/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/recipes/06-migrateZusammenFromDox.rb
new file mode 100644
index 0000000000..e1fcf4f556
--- /dev/null
+++ b/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/recipes/06-migrateZusammenFromDox.rb
@@ -0,0 +1,14 @@
+#onboarding_version = "#{node['onboarding'][:version]}"
+#GROUP_ID = "com/att/asdc/onboarding/#{onboarding_version}"
+#NEXUS_IP = "#{node['nexus_ip']}"
+
+bash "Excuting openecomp-zusammen-migration-1707.0.0-SNAPSHOT.jar" do
+ code <<-EOH
+ [ -d /var/tmp/onboarding/migration ] && rm -rf /var/tmp/onboarding || mkdir -p /var/tmp/onboarding/migration
+ cd /var/tmp/onboarding/migration
+ /bin/tar -xzf /root/chef-solo/cookbooks/cassandra-actions/files/default/zusammen.tgz -C /var/tmp/onboarding/migration
+ cd /var/tmp/onboarding/migration
+ java -Dlog.home=/var/tmp/onboarding/migration/logs -Dconfiguration.yaml=/tmp/sdctool/config/configuration.yaml -jar openecomp-zusammen-migration-1707.0.0-SNAPSHOT.jar org.openecomp.core.migration.MigrationMain
+ EOH
+end
+
diff --git a/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/templates/default/configuration.yaml.erb b/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/templates/default/configuration.yaml.erb
index e33ece4890..4d5f979f56 100644
--- a/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/templates/default/configuration.yaml.erb
+++ b/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/templates/default/configuration.yaml.erb
@@ -22,8 +22,9 @@ beProtocol: http
beSslPort: <%= @ssl_port %>
version: 1.0
released: 2012-11-30
+toscaConformanceLevel: 3.0
-titanCfgFile: /var/lib/jetty/config/catalog-be/titan.properties
+titanCfgFile: <%= @titan_Path %>/titan.properties
titanInMemoryGraph: false
titanLockTimeout: 1800
# The interval to try and reconnect to titan DB when it is down during ASDC startup:
@@ -43,6 +44,21 @@ 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
@@ -60,10 +76,10 @@ cassandraConfig:
truststorePath : /config/.truststore
truststorePassword : Aa123456
keySpaces:
- - { name: dox, replicationStrategy: NetworkTopologyStrategy, replicationInfo: ['<%= @dc1 %>','<%= @rep_factor %>']}
- - { name: sdcaudit, replicationStrategy: NetworkTopologyStrategy, replicationInfo: ['<%= @dc1 %>','<%= @rep_factor %>']}
- - { name: sdcartifact, replicationStrategy: NetworkTopologyStrategy, replicationInfo: ['<%= @dc1 %>','<%= @rep_factor %>']}
- - { name: sdccomponent, replicationStrategy: NetworkTopologyStrategy, replicationInfo: ['<%= @dc1 %>','<%= @rep_factor %>']}
+ - { name: dox, replicationStrategy: NetworkTopologyStrategy, replicationInfo: ['<%= @DC_NAME %>','<%= @rep_factor %>']}
+ - { name: sdcaudit, replicationStrategy: NetworkTopologyStrategy, replicationInfo: ['<%= @DC_NAME %>','<%= @rep_factor %>']}
+ - { name: sdcartifact, replicationStrategy: NetworkTopologyStrategy, replicationInfo: ['<%= @DC_NAME %>','<%= @rep_factor %>']}
+ - { name: sdccomponent, replicationStrategy: NetworkTopologyStrategy, replicationInfo: ['<%= @DC_NAME %>','<%= @rep_factor %>']}
#Application-specific settings of ES
elasticSearch:
@@ -106,7 +122,9 @@ artifactTypes:
- AAI_VF_MODULE_MODEL
- AAI_VF_INSTANCE_MODEL
- OTHER
-
+ - SNMP_POLL
+ - SNMP_TRAP
+ - GUIDE
licenseTypes:
- User
@@ -119,6 +137,8 @@ resourceTypes: &allResourceTypes
- CP
- VL
- VF
+ - VFCMT
+ - Abstract
# validForResourceTypes usage
# validForResourceTypes:
@@ -133,6 +153,11 @@ deploymentResourceInstanceArtifacts:
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:
@@ -163,7 +188,7 @@ informationalResourceArtifacts:
testScripts:
displayName: Test Scripts
type: OTHER
- cloudQuestionnaire:
+ CloudQuestionnaire:
displayName: Cloud Questionnaire (completed)
type: OTHER
HEATTemplateFromVendor:
@@ -319,36 +344,55 @@ resourceDeploymentArtifacts:
acceptedTypes:
- xml
validForResourceTypes: *allResourceTypes
+ LIFECYCLE_OPERATIONS:
+ acceptedTypes:
+ - yaml
+ - yml
+ validForResourceTypes:
+ - VF
+ - VFC
+ VES_EVENTS:
+ acceptedTypes:
+ - yaml
+ - yml
+ validForResourceTypes: *allResourceTypes
+ PERFORMANCE_COUNTER:
+ acceptedTypes:
+ - csv
+ validForResourceTypes: *allResourceTypes
APPC_CONFIG:
acceptedTypes:
validForResourceTypes:
- VF
- #DCAE Artifacts
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
+ - VF
+ - VFCMT
DCAE_EVENT:
acceptedTypes:
validForResourceTypes:
- VF
-#AAI Artifacts
+ - VFCMT
AAI_VF_MODEL:
acceptedTypes:
- xml
@@ -362,6 +406,12 @@ resourceDeploymentArtifacts:
OTHER:
acceptedTypes:
validForResourceTypes: *allResourceTypes
+ SNMP_POLL:
+ acceptedTypes:
+ validForResourceTypes: *allResourceTypes
+ SNMP_TRAP:
+ acceptedTypes:
+ validForResourceTypes: *allResourceTypes
resourceInstanceDeploymentArtifacts:
HEAT_ENV:
@@ -370,7 +420,13 @@ resourceInstanceDeploymentArtifacts:
VF_MODULES_METADATA:
acceptedTypes:
- json
-#DCAE_VF Instance Artifacts
+ VES_EVENTS:
+ acceptedTypes:
+ - yaml
+ - yml
+ PERFORMANCE_COUNTER:
+ acceptedTypes:
+ - csv
DCAE_INVENTORY_TOSCA:
acceptedTypes:
- yml
@@ -387,6 +443,56 @@ resourceInstanceDeploymentArtifacts:
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: *allResourceTypes
+ SNMP_POLL:
+ acceptedTypes:
+ validForResourceTypes: *allResourceTypes
+ SNMP_TRAP:
+ acceptedTypes:
+ validForResourceTypes: *allResourceTypes
+ GUIDE:
+ acceptedTypes:
+ validForResourceTypes:
+ - VF
+ - VFC
+
resourceInformationalDeployedArtifacts:
@@ -405,10 +511,8 @@ cleanComponentsConfiguration:
artifactsIndex: resources
-heatEnvArtifactHeader:
- ""
-heatEnvArtifactFooter:
- ""
+heatEnvArtifactHeader: ""
+heatEnvArtifactFooter: ""
onboarding:
protocol: http
@@ -454,6 +558,24 @@ applicationL2Cache:
numberOfCacheWorkers: 4
toscaValidators:
- stringMaxLength: 65536
+ stringMaxLength: 2500
disableAudit: false
+vfModuleProperties:
+ min_vf_module_instances:
+ forBaseModule: 1
+ forNonBaseModule: 0
+ max_vf_module_instances:
+ forBaseModule: 1
+ forNonBaseModule:
+ initial_count:
+ forBaseModule: 1
+ forNonBaseModule: 0
+ vf_module_type:
+ forBaseModule: Base
+ forNonBaseModule: Expansion
+
+genericAssetNodeTypes:
+ VFC: org.openecomp.resource.abstract.nodes.VFC
+ VF : org.openecomp.resource.abstract.nodes.VF
+ Service: org.openecomp.resource.abstract.nodes.service \ No newline at end of file
diff --git a/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/templates/default/create_dox_keyspace.sh.erb b/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/templates/default/create_dox_keyspace.sh.erb
index 701d320b67..da6bbb184c 100644
--- a/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/templates/default/create_dox_keyspace.sh.erb
+++ b/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/templates/default/create_dox_keyspace.sh.erb
@@ -1,77 +1,52 @@
#!/bin/bash
-CASSANDRA_USER=cassandra
-CASSANDRA_PASS=Aa1234%^!
-CASSANDRA_IP=<%= @cassandra_ip %>
+CASSANDRA_USER=asdc_user
+CASSANDRA_PASS='Aa1234%^!'
-REPLICATION_FACTOR=1
-KEYSPACE="CREATE KEYSPACE IF NOT EXISTS dox WITH REPLICATION = { 'class' : 'SimpleStrategy', 'replication_factor' : $REPLICATION_FACTOR };"
+KEYSPACE="CREATE KEYSPACE IF NOT EXISTS dox WITH REPLICATION = { 'class' : 'NetworkTopologyStrategy', '<%= @DC_NAME %>': '1'};"
+KEYSPACE1="CREATE KEYSPACE IF NOT EXISTS zusammen_dox WITH REPLICATION = { 'class' : 'NetworkTopologyStrategy', '<%= @DC_NAME %>': '1'};"
-keyspaces=`echo "describe keyspaces" | cqlsh -u $CASSANDRA_USER -p $CASSANDRA_PASS $CASSANDRA_IP 2>/dev/null`
-if [ "$keyspaces" == "" ] ; then
- echo "keyspace is empty, probably connection error. Exit..."
- exit 1
-fi
-
-echo "run create_dox_db.cql"
-echo $KEYSPACE > /tmp/create_dox_db.cql
-cat <<'EOF' >> /tmp/create_dox_db.cql
-USE dox;
-CREATE TYPE IF NOT EXISTS version (major int, minor int);
-CREATE TYPE IF NOT EXISTS user_candidate_version (version frozen<version>, user text);
-CREATE TABLE IF NOT EXISTS version_info (entity_type text, entity_id text, active_version frozen<version>, status text, candidate frozen<user_candidate_version>, viewable_versions set<frozen<version>>, latest_final_version frozen<version>, PRIMARY KEY (entity_type, entity_id));
-CREATE TABLE IF NOT EXISTS version_info_deleted (entity_type text, entity_id text, active_version frozen<version>, status text, candidate frozen<user_candidate_version>, viewable_versions set<frozen<version>>, latest_final_version frozen<version>, PRIMARY KEY (entity_type, entity_id));
-CREATE TABLE IF NOT EXISTS unique_value (type text, value text, PRIMARY KEY ((type, value)));
-CREATE TYPE IF NOT EXISTS choice_or_other (result text);
-CREATE TYPE IF NOT EXISTS multi_choice_or_other (results set<text>);
-CREATE TABLE IF NOT EXISTS vendor_license_model (vlm_id text, version frozen<version>, vendor_name text, description text, icon text, PRIMARY KEY ((vlm_id, version)));
-CREATE TABLE IF NOT EXISTS license_agreement (vlm_id text, version frozen<version>, la_id text, name text, description text, lic_term frozen<choice_or_other>, req_const text, fg_ids set<text>, PRIMARY KEY ((vlm_id, version), la_id));
-CREATE TABLE IF NOT EXISTS feature_group (vlm_id text, version frozen<version>, fg_id text, name text, description text, part_num text, ep_ids set<text>, lkg_ids set<text>, ref_la_ids set<text>, PRIMARY KEY ((vlm_id, version), fg_id));
-CREATE TABLE IF NOT EXISTS license_key_group (vlm_id text, version frozen<version>, lkg_id text,name text,description text, type text, operational_scope frozen<multi_choice_or_other>, ref_fg_ids set<text>,version_uuid text,PRIMARY KEY ((vlm_id, version), lkg_id));
-CREATE TABLE IF NOT EXISTS entitlement_pool (vlm_id text, version frozen<version>, ep_id text,name text,description text,threshold float,threshold_unit text,entitlement_metric frozen<choice_or_other>,increments text,aggregation_func frozen<choice_or_other>, operational_scope frozen<multi_choice_or_other>, time frozen<choice_or_other>,manufacturer_ref_num text,ref_fg_ids set<text>,version_uuid text,PRIMARY KEY ((vlm_id, version), ep_id));
-CREATE TABLE IF NOT EXISTS vsp_information (VSP_ID text, version frozen<version>,NAME text,DESCRIPTION text,CATEGORY text,SUB_CATEGORY text,ICON text,PACKAGE_NAME text,PACKAGE_VERSION text,vendor_name text, vendor_id text,LICENSE_AGREEMENT text,FEATURE_GROUPS list<text>,VALIDATION_DATA text,CONTENT_DATA blob, questionnaire_data text, vlm_version frozen<version>, PRIMARY KEY ((VSP_ID, version)));
-CREATE TABLE IF NOT EXISTS package_details (VSP_ID text, version frozen<version>,DISPLAY_NAME text,vsp_name text,vsp_description text,VENDOR_NAME text,CATEGORY text,SUB_CATEGORY text,VENDOR_RELEASE text,PACKAGE_CHECKSUM text,PACKAGE_TYPE text,TRANSLATE_CONTENT blob,PRIMARY KEY ((VSP_ID, version)));
-CREATE TABLE IF NOT EXISTS vsp_network (vsp_id text, version frozen<version>, network_id text, composition_data text, questionnaire_data text, PRIMARY KEY ((vsp_id, version), network_id));
-CREATE TABLE IF NOT EXISTS vsp_component (vsp_id text, version frozen<version>, component_id text, composition_data text, questionnaire_data text, PRIMARY KEY ((vsp_id, version), component_id));
-CREATE TABLE IF NOT EXISTS vsp_component_nic (vsp_id text, version frozen<version>, component_id text, nic_id text, composition_data text, questionnaire_data text, PRIMARY KEY ((vsp_id, version), component_id, nic_id));
-CREATE TABLE IF NOT EXISTS vsp_process (vsp_id text, version frozen<version>, component_id text, process_id text, name text, description text, artifact_name text, artifact blob, PRIMARY KEY ((vsp_id, version), component_id, process_id));
-CREATE TABLE IF NOT EXISTS vsp_service_artifact (vsp_id text, version frozen<version>, name text, content_data blob, PRIMARY KEY ((vsp_id, version), name));
-CREATE TABLE IF NOT EXISTS vsp_service_template (vsp_id text, version frozen<version>, base_name text static, name text, content_data blob, PRIMARY KEY ((vsp_id, version), name));
-CREATE TABLE IF NOT EXISTS vsp_enriched_service_template (vsp_id text, version frozen<version>, base_name text static, name text, content_data blob, PRIMARY KEY ((vsp_id, version), name));
-CREATE TABLE IF NOT EXISTS vsp_enriched_service_artifact (vsp_id text, version frozen<version>, name text, content_data blob, PRIMARY KEY ((vsp_id, version), name));
-CREATE TABLE IF NOT EXISTS application_config (namespace text, key text, value text, PRIMARY KEY (namespace, key));
-CREATE TABLE IF NOT EXISTS dox.Action (actionUUID text, actionInvariantUUID text, version frozen<version>, status text, name text, vendor_list set<text>, category_list set<text>, timestamp timestamp, user text, supportedModels set<text>, supportedComponents set<text>, data text, PRIMARY KEY ((actionInvariantUUID, version)));
-CREATE INDEX IF NOT EXISTS action_supportedComponents ON dox.Action (supportedComponents);
-CREATE INDEX IF NOT EXISTS action_category_list ON dox.Action (category_list);
-CREATE INDEX IF NOT EXISTS action_supportedModels ON dox.Action (supportedModels);
-CREATE INDEX IF NOT EXISTS action_vendor_list ON dox.Action (vendor_list);
-CREATE INDEX IF NOT EXISTS action_actionUUID ON dox.Action (actionUUID);
-CREATE TABLE IF NOT EXISTS dox.ecompcomponent(id text PRIMARY KEY, name text);
-CREATE TABLE IF NOT EXISTS vsp_component_artifact (vsp_id text, version frozen<version>, component_id text, artifact_type text, artifact_id text, name text, description text, artifact blob, PRIMARY KEY ((vsp_id, version), component_id, artifact_type, artifact_id));
-CREATE INDEX IF NOT EXISTS action_name ON dox.Action (name);
-CREATE TABLE IF NOT EXISTS action_artifact(artifactuuid text, effective_version int, artifact blob, PRIMARY KEY(artifactuuid, effective_version)) WITH CLUSTERING ORDER BY (effective_version DESC);
-INSERT INTO application_config (namespace,key,value) VALUES ('vsp.schemaTemplates', 'composition.component', '{ "$schema": "http://json-schema.org/draft-04/schema#", "type": "object", "properties": { "name": { "type": "string"<#if !manual>, "enum": [ "${component.name}" ], "default": "${component.name}"</#if> }, "displayName": { "type": "string"<#if !manual && component.displayName??>, "enum": [ "${component.displayName}" ], "default": "${component.displayName}"</#if> }, "description": { "type": "string" } }, "additionalProperties": false, "required": [ "name"<#if !manual && component.displayName??>, "displayName"</#if> ] }');
-INSERT INTO application_config (namespace,key,value) VALUES ('vsp.schemaTemplates', 'composition.network', '{ "$schema": "http://json-schema.org/draft-04/schema#", "type": "object", "properties": { "name": { "type": "string"<#if !manual>, "enum": [ "${network.name}" ], "default": "${network.name}"</#if> }, "dhcp": { "type": "boolean"<#if !manual>, "enum": [ ${network.dhcp?c} ], "default": ${network.dhcp?c}</#if> } }, "additionalProperties": false, "required": [ "name", "dhcp" ] }');
-INSERT INTO application_config (namespace,key,value) VALUES ('vsp.schemaTemplates', 'composition.nic', '{ "$schema": "http://json-schema.org/draft-04/schema#", "type": "object", "properties": { "name": { "type": "string"<#if !manual>, "enum": [ "${nic.name}" ], "default": "${nic.name}" </#if> }, "description": { "type": "string" }<#if !manual><#if nic.networkId??>, "networkId": { "type": "string", "enum": [ "${nic.networkId}" ], "default": "${nic.networkId}" } </#if><#else>, "networkId": { "type": "string", "enum": [<#list networkIds as networkId> "${networkId}"<#sep>,</#list> ] } </#if> }, "additionalProperties": false, "required": [ "name" ] }');
-INSERT INTO application_config (namespace,key,value) VALUES ('vsp.schemaTemplates', 'questionnaire.component', '{ "$schema": "http://json-schema.org/draft-04/schema#", "type": "object", "properties": { "general": { "type": "object", "properties": { "hypervisor": { "type": "object", "properties": { "hypervisor": { "type": "string", "enum": [ "KVM", "VMWare ESXi" ], "default": "KVM" }, "drivers": { "type": "string", "maxLength": 300, "pattern": "^[A-Za-z0-9_,-]*$" }, "containerFeaturesDescription": { "type": "string", "maxLength": 1000, "pattern": "^[A-Za-z0-9_, -]*$" } }, "additionalProperties": false }, "image": { "type": "object", "properties": { "format": { "type": "string", "enum": [ "aki", "ami", "ari", "iso", "qcow2", "raw", "vdi", "vhd", "vmdk" ], "default": "qcow2" }, "providedBy": { "type": "string", "enum": [ "OPENECOMP", "Vendor" ], "default": "OPENECOMP" }, "bootDiskSizePerVM": { "type": "number", "maximum": 100 }, "ephemeralDiskSizePerVM": { "type": "number", "maximum": 400 } }, "additionalProperties": false }, "recovery": { "type": "object", "properties": { "pointObjective": { "type": "number", "minimum": 0, "exclusiveMinimum": true, "maximum": 15, "exclusiveMaximum ": true }, "timeObjective": { "type": "number", "minimum": 0, "exclusiveMinimum": true, "maximum": 300, "exclusiveMaximum ": true }, "vmProcessFailuresHandling": { "type": "string" } }, "additionalProperties": false }, "dnsConfiguration": { "type": "string" }, "vmCloneUsage": { "type": "string", "maximum": 300 } }, "additionalProperties": false }, "compute": { "type": "object", "properties": { "vmSizing": { "type": "object", "properties": { "numOfCPUs": { "type": "number", "minimum": 0, "exclusiveMinimum": true, "maximum": 16, "default": 2 }, "fileSystemSizeGB": { "type": "number", "minimum": 0, "exclusiveMinimum": true, "default": 5 }, "persistentStorageVolumeSize": { "type": "number", "minimum": 0, "exclusiveMinimum": true }, "IOOperationsPerSec": { "type": "number", "minimum": 0, "exclusiveMinimum": true } }, "additionalProperties": false }, "numOfVMs": { "type": "object", "properties": { "minimum": { "type": "number", "minimum": 0, "exclusiveMinimum": true, "maximum": 100 }, "maximum": { "type": "number", "minimum": <#if (componentQuestionnaireData.compute.numOfVMs.minimum)?? && (componentQuestionnaireData.compute.numOfVMs.minimum)?is_number && ((componentQuestionnaireData.compute.numOfVMs.minimum) > 0 && (componentQuestionnaireData.compute.numOfVMs.minimum) <= 100)> ${componentQuestionnaireData.compute.numOfVMs.minimum}<#else> 0</#if>, "exclusiveMinimum": true, "maximum": 100 }, "CpuOverSubscriptionRatio": { "type": "string", "enum": [ "1:1", "4:1", "16:1" ], "default": "4:1" }, "MemoryRAM": { "type": "string", "enum": [ "2 GB", "4 GB", "8 GB" ], "default": "2 GB" } }, "additionalProperties": false }, "guestOS": { "type": "object", "properties": { "name": { "type": "string", "maxLength": 50 }, "bitSize": { "type": "number", "enum": [ 64, 32 ], "default": 64 }, "tools": { "type": "string" } }, "additionalProperties": false } }, "additionalProperties": false }, "highAvailabilityAndLoadBalancing": { "type": "object", "properties": { "failureLoadDistribution": { "type": "string", "maxLength": 1000 }, "nkModelImplementation": { "type": "string", "maxLength": 1000 }, "architectureChoice": { "type": "string", "maxLength": 1000 }, "slaRequirements": { "type": "string", "maxLength": 1000 }, "horizontalScaling": { "type": "string", "maxLength": 1000 }, "loadDistributionMechanism": { "type": "string", "maxLength": 1000 } }, "additionalProperties": false }, "network": { "type": "object", "properties": { "networkCapacity": { "type": "object", "properties": { "protocolWithHighestTrafficProfileAcrossAllNICs": { "type": "string", "enum": [ "TCP", "UDP", "SCTP", "IPsec" ] }, "networkTransactionsPerSecond": { "type": "number" } }, "additionalProperties": false } }, "additionalProperties": false }, "storage": { "type": "object", "properties": { "backup": { "type": "object", "properties": { "backupType": { "type": "string", "enum": [ "On Site", "Off Site" ], "default": "On Site" }, "backupStorageSize": { "type": "number" }, "backupSolution": { "type": "string" }, "backupNIC": { "type": "string", "enum": [<#if nicNames??><#list nicNames as nicName> "${nicName}"<#sep>,</#list></#if> ] } }, "additionalProperties": false }, "snapshotBackup": { "type": "object", "properties": { "snapshotFrequency": { "type": "number", "default": 24, "minimum": 1, "exclusiveMinimum": true } }, "additionalProperties": false }, "logBackup": { "type": "object", "properties": { "sizeOfLogFiles": { "type": "number", "maximum": 5, "exclusiveMaximum": true }, "logBackupFrequency": { "type": "number", "maximum": 4, "exclusiveMaximum": true }, "logRetentionPeriod": { "type": "number", "maximum": 15, "exclusiveMaximum": true }, "logFileLocation": { "type": "string", "maxLength": 300 } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }');
-INSERT INTO application_config (namespace,key,value) VALUES ('vsp.schemaTemplates', 'questionnaire.nic', '{ "$schema": "http://json-schema.org/draft-04/schema#", "definitions": { "protocol": { "type": "string", "enum": [ "TCP", "UDP", "SCTP", "IPsec" ] } }, "type": "object", "properties": { "protocols": { "type": "object", "properties": { "protocols": { "type": "array", "items": { "$ref": "#/definitions/protocol" }, "minItems": 1 }, "protocolWithHighestTrafficProfile": { "$ref": "#/definitions/protocol" } }, "additionalProperties": false }, "ipConfiguration": { "type": "object", "properties": { "ipv4Required": { "type": "boolean", "default": true }, "ipv6Required": { "type": "boolean", "default": false } }, "additionalProperties": false }, "network": { "type": "object", "properties": { "networkDescription": { "type": "string", "pattern": "[A-Za-z]+", "maxLength": 300 } }, "additionalProperties": false }, "sizing": { "type": "object", "definitions": { "peakAndAvg": { "type": "object", "properties": { "peak": { "type": "number" }, "avg": { "type": "number" } }, "additionalProperties": false }, "packetsAndBytes": { "type": "object", "properties": { "packets": { "$ref": "#/properties/sizing/definitions/peakAndAvg" }, "bytes": { "$ref": "#/properties/sizing/definitions/peakAndAvg" } }, "additionalProperties": false } }, "properties": { "describeQualityOfService": { "type": "string" }, "inflowTrafficPerSecond": { "$ref": "#/properties/sizing/definitions/packetsAndBytes" }, "outflowTrafficPerSecond": { "$ref": "#/properties/sizing/definitions/packetsAndBytes" }, "flowLength": { "$ref": "#/properties/sizing/definitions/packetsAndBytes" }, "acceptableJitter": { "type": "object", "properties": { "mean": { "type": "number" }, "max": { "type": "number" }, "variable": { "type": "number" } }, "additionalProperties": false }, "acceptablePacketLoss": { "type": "number", "minimum": 0, "maximum": 100 } }, "additionalProperties": false } }, "additionalProperties": false }');
-INSERT INTO application_config (namespace,key,value) VALUES ('vsp.schemaTemplates', 'questionnaire.vsp', '{ "$schema": "http://json-schema.org/draft-04/schema#", "type": "object", "properties": { "general": { "type": "object", "properties": { "affinityData": { "type": "string", "enum": [ "Affinity", "Anti Affinity", "None" ] }, "availability": { "type": "object", "properties": { "useAvailabilityZonesForHighAvailability": { "type": "boolean", "default": false } }, "additionalProperties": false }, "regionsData": { "type": "object", "properties": { "multiRegion": { "type": "boolean", "default": false }, "regions": { "type": "array", "items": { "type": "string", "enum": [ "Alphareta", "Birmingham", "Dallas", "Fairfield CA", "Hayward CA", "Lisle", "Mission", "San Diego", "Secaucus" ] } } }, "additionalProperties": false }, "storageDataReplication": { "type": "object", "properties": { "storageReplicationAcrossRegion": { "type": "boolean", "default": false }, "storageReplicationSize": { "type": "number", "maximum": 100, "exclusiveMaximum": true }, "storageReplicationFrequency": { "type": "number", "minimum": 5 }, "storageReplicationSource": { "type": "string", "maxLength": 300 }, "storageReplicationDestination": { "type": "string", "maxLength": 300 } }, "additionalProperties": false } }, "additionalProperties": false } }, "additionalProperties": false }');
-INSERT INTO application_config (namespace,key,value) VALUES ('vsp.monitoring', 'component.ceilometer', '{ "ceilometerInfoList": [ { "name": "instance", "type": "Gauge", "unit": "instance", "category": "compute", "description": "Existence of instance" }, { "name": "instance:type", "type": "Gauge", "unit": "instance", "category": "compute", "description": "Existence of instance <type> (OpenStack types)" }, { "name": "memory", "type": "Gauge", "unit": "MB", "category": "compute", "description": "Volume of RAM allocated to the instance" }, { "name": "memory.usage", "type": "Gauge", "unit": "MB", "category": "compute", "description": "Volume of RAM used by the instance from the amount of its allocated memory" }, { "name": "memory.resident", "type": "Gauge", "unit": "MB", "category": "compute", "description": "Volume of RAM used by the instance on the physical machine" }, { "name": "cpu", "type": "Cumulative", "unit": "ns", "category": "compute", "description": "CPU time used" }, { "name": "cpu_util", "type": "Gauge", "unit": "%", "category": "compute", "description": "Average CPU utilization" }, { "name": "cpu.delta", "type": "Delta", "unit": "ns", "category": "compute", "description": "CPU time used since previous datapoint" }, { "name": "vcpus", "type": "Gauge", "unit": "ms", "category": "compute", "description": "Average disk latency" } ] }');
-ALTER TABLE vsp_information ADD questionnaire_data text;
-ALTER TABLE vsp_information ADD vlm_version frozen<version>;
-ALTER TABLE entitlement_pool ADD version_uuid text;
-ALTER TABLE license_key_group ADD version_uuid text;
-
-EOF
+echo "run create_dox_keyspace.cql"
+echo -e "$KEYSPACE\n$KEYSPACE1" > /tmp/create_dox_keyspace.cql
-chmod 777 /tmp/create_dox_db.cql
-cqlsh -u $CASSANDRA_USER -p $CASSANDRA_PASS $CASSANDRA_IP -f /tmp/create_dox_db.cql > /dev/null 2>&1
+chmod 755 /tmp/create_dox_keyspace.cql
+cqlsh -u $CASSANDRA_USER -p $CASSANDRA_PASS -f /tmp/create_dox_keyspace.cql > /dev/null 2>&1
-res=`echo "select keyspace_name from system.schema_keyspaces ;" | cqlsh -u $CASSANDRA_USER -p $CASSANDRA_PASS $CASSANDRA_IP |grep -c dox 2>/dev/null`
+CS_VERSION=`cassandra -v`
+CS_MAJOR_VERSION=`cassandra -v | cut -c1`
+if [ ${CS_MAJOR_VERSION} -gt 2 ]; then
+ echo "`date` --- CS [${CS_VERSION}] uses system_schema.keyspaces"
+ res=`echo "select keyspace_name from system_schema.keyspaces ;" | cqlsh -u $CASSANDRA_USER -p $CASSANDRA_PASS |grep -c dox 2>/dev/null`
+else
+ echo "`date` --- CS [${CS_VERSION}] uses system.schema_keyspaces"
+ res=`echo "select keyspace_name from system.schema_keyspaces ;" | cqlsh -u $CASSANDRA_USER -p $CASSANDRA_PASS |grep -c dox 2>/dev/null`
+fi
-if [ $res -eq 1 ]; then
+if [ $res -gt 0 ]; then
echo "`date` --- dox keyspace was created "
else
echo "`date` --- Failed to create dox keyspace"
fi
+
+echo "run create_dox_db.cql"
+chmod 755 /tmp/create_dox_db.cql
+cqlsh -u $CASSANDRA_USER -p $CASSANDRA_PASS -f /tmp/create_dox_db.cql > /dev/null 2>&1
+$res=$?
+if [ $res -gt 0 ]; then
+ echo "`date` --- dox keyspace: create_dox_db.cql failed ! "
+else
+ echo "`date` --- dox keyspace: create_dox_db.cql completed successfully "
+fi
+
+sleep 10
+
+echo "run alter_dox_db.cql"
+chmod 755 /tmp/alter_dox_db.cql
+cqlsh -u $CASSANDRA_USER -p $CASSANDRA_PASS -f /tmp/alter_dox_db.cql > /dev/null 2>&1
+$res=$?
+if [ $res -gt 0 ]; then
+ echo "`date` --- dox keyspace: alter_dox_db.cql failed !"
+else
+ echo "`date` --- dox keyspace: alter_dox_db.cql completed successfully "
+fi
diff --git a/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/templates/default/titan.properties.erb b/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/templates/default/titan.properties.erb
new file mode 100644
index 0000000000..bccf2210af
--- /dev/null
+++ b/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/templates/default/titan.properties.erb
@@ -0,0 +1,25 @@
+storage.backend=cassandra
+storage.hostname=localhost
+storage.port=9160
+storage.username=asdc_user
+storage.password=Aa1234%^!
+storage.cassandra.keyspace=sdctitan
+
+storage.cassandra.ssl.enabled=false
+storage.cassandra.ssl.truststore.location=/var/lib/jetty/config/.truststore
+storage.cassandra.ssl.truststore.password=Aa123456
+
+cache.db-cache = false
+cache.db-cache-clean-wait = 20
+cache.db-cache-time = 180000
+cache.db-cache-size = 0.5
+
+storage.cassandra.read-consistency-level=LOCAL_QUORUM
+storage.cassandra.write-consistency-level=LOCAL_QUORUM
+storage.cassandra.replication-strategy-class=org.apache.cassandra.locator.NetworkTopologyStrategy
+storage.cassandra.replication-strategy-options=<%= @DC_NAME %>,1
+storage.cassandra.astyanax.local-datacenter=<%= @DC_NAME %>
+
+storage.lock.retries=5
+storage.lock.wait-time=500
+
diff --git a/sdc-os-chef/sdc-cassandra/chef-solo/roles/cassandra-actions.json b/sdc-os-chef/sdc-cassandra/chef-solo/roles/cassandra-actions.json
index 8d8931c2b5..d8155e2068 100644
--- a/sdc-os-chef/sdc-cassandra/chef-solo/roles/cassandra-actions.json
+++ b/sdc-os-chef/sdc-cassandra/chef-solo/roles/cassandra-actions.json
@@ -12,7 +12,9 @@
"run_list": [
"recipe[cassandra-actions::02-createCsUser]",
"recipe[cassandra-actions::03-createDoxKeyspace]",
- "recipe[cassandra-actions::04-schemaCreation]"
+ "recipe[cassandra-actions::04-schemaCreation]",
+ "recipe[cassandra-actions::05-titanSchemaCreation]",
+ "recipe[cassandra-actions::07-importComformance]"
],
"env_run_lists": {
diff --git a/sdc-os-chef/sdc-cassandra/startup.sh b/sdc-os-chef/sdc-cassandra/startup.sh
index 89d95ea022..3c001dfbab 100755
--- a/sdc-os-chef/sdc-cassandra/startup.sh
+++ b/sdc-os-chef/sdc-cassandra/startup.sh
@@ -1,6 +1,10 @@
#!/bin/bash
cd /root/chef-solo
+mkdir -p /root/chef-solo/cookbooks/cassandra-actions/attributes
+echo "normal['version'] = \"${RELEASE}\"" > /root/chef-solo/cookbooks/cassandra-actions/attributes/default.rb
+echo "normal['HOST_IP'] = \"${HOST_IP}\"" >> /root/chef-solo/cookbooks/cassandra-actions/attributes/default.rb
+
export CHEFNAME=${ENVNAME}
sed -i "s/HOSTIP/${HOST_IP}/g" /root/chef-solo/cookbooks/cassandra-actions/recipes/02-createCsUser.rb
@@ -15,14 +19,9 @@ echo "########### starting cassandra ###########"
# start cassandra
/docker-entrypoint.sh cassandra -f &
-chef-solo -c solo.rb -E ${CHEFNAME}
+sleep 10
-cd /tmp/
-/tmp/create_cassandra_user.sh
-/tmp/create_dox_keyspace.sh
-/bin/chmod +x sdctool/scripts/*.sh
-./sdctool/scripts/schemaCreation.sh /tmp/sdctool/config
+chef-solo -c solo.rb -E ${CHEFNAME}
while true; do sleep 2; done
-
diff --git a/sdc-os-chef/sdc-elasticsearch/Dockerfile b/sdc-os-chef/sdc-elasticsearch/Dockerfile
index 9dee9dcd8b..de3d43e7f9 100644
--- a/sdc-os-chef/sdc-elasticsearch/Dockerfile
+++ b/sdc-os-chef/sdc-elasticsearch/Dockerfile
@@ -9,14 +9,10 @@ RUN mkdir -p /var/chef/nodes
COPY chef-solo /root/chef-solo/
COPY chef-repo/cookbooks /root/chef-solo/cookbooks/
-ENV BASE_NEXUS zl999y:ChangeMe@10.208.197.75:8443/repository/maven-public/org/openecomp/sdc
-
# install chef-solo
RUN curl -L https://omnitruck.chef.io/install.sh | bash
-
COPY startup.sh /root/
-
RUN chmod 770 /root/startup.sh
ENTRYPOINT [ "/root/startup.sh" ]
diff --git a/sdc-os-chef/sdc-elasticsearch/chef-repo/cookbooks/sdc-elasticsearch/recipes/ES_6_create_kibana_dashboard_virtualization.rb b/sdc-os-chef/sdc-elasticsearch/chef-repo/cookbooks/sdc-elasticsearch/recipes/ES_6_create_kibana_dashboard_virtualization.rb
index 5f86391199..a3b15073a1 100644
--- a/sdc-os-chef/sdc-elasticsearch/chef-repo/cookbooks/sdc-elasticsearch/recipes/ES_6_create_kibana_dashboard_virtualization.rb
+++ b/sdc-os-chef/sdc-elasticsearch/chef-repo/cookbooks/sdc-elasticsearch/recipes/ES_6_create_kibana_dashboard_virtualization.rb
@@ -1,3 +1,11 @@
+cookbook_file "/usr/share/elasticsearch/config/kibana_dashboard_virtualization.json" do
+ source "kibana_dashboard_virtualization.json"
+ owner "elasticsearch"
+ group "elasticsearch"
+ mode "0755"
+end
+
+
ruby_block "check_ElasticSearch_Cluster_Health" do
block do
diff --git a/sdc-os-chef/sdc-frontend/Dockerfile b/sdc-os-chef/sdc-frontend/Dockerfile
index 79fd9186d6..a59d868f7f 100644
--- a/sdc-os-chef/sdc-frontend/Dockerfile
+++ b/sdc-os-chef/sdc-frontend/Dockerfile
@@ -14,7 +14,7 @@ RUN curl -L https://omnitruck.chef.io/install.sh | bash
RUN cp ${JETTY_HOME}/resources/log4j.properties ${JETTY_BASE}/resources/log4j.properties
ADD onboarding*.war ${JETTY_BASE}/webapps/
-ADD catalog-fe-__SDC-RELEASE__.war ${JETTY_BASE}/webapps/
+ADD catalog-fe-*.war ${JETTY_BASE}/webapps/
RUN chown -R jetty:jetty ${JETTY_BASE}/webapps
COPY startup.sh /root/
diff --git a/sdc-os-chef/sdc-kibana/Dockerfile b/sdc-os-chef/sdc-kibana/Dockerfile
index 54aeb2c685..be5446e2e9 100644
--- a/sdc-os-chef/sdc-kibana/Dockerfile
+++ b/sdc-os-chef/sdc-kibana/Dockerfile
@@ -7,12 +7,9 @@ RUN apt-get -y install vim
COPY chef-solo /root/chef-solo/
COPY chef-repo/cookbooks/. /root/chef-solo/cookbooks/
-
# install chef-solo
RUN curl -L https://omnitruck.chef.io/install.sh | bash
-
-
COPY startup.sh /root/
RUN chmod 770 /root/startup.sh
diff --git a/sdc-os-chef/sdc-sanity/Dockerfile b/sdc-os-chef/sdc-sanity/Dockerfile
index 3c63c1d156..dd486102c5 100644
--- a/sdc-os-chef/sdc-sanity/Dockerfile
+++ b/sdc-os-chef/sdc-sanity/Dockerfile
@@ -5,16 +5,12 @@ RUN apt-get -y install vim
RUN apt-get -y install default-jre && apt-get -y install openjdk-8-jdk
RUN update-alternatives --set java /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java
-
COPY chef-solo /root/chef-solo/
COPY chef-repo/cookbooks/. /root/chef-solo/cookbooks/
-
# install chef-solo
RUN curl -L https://omnitruck.chef.io/install.sh | bash
COPY startup.sh /root/
-
RUN chmod 770 /root/startup.sh
-
ENTRYPOINT [ "/root/startup.sh" ]
diff --git a/security-utils/pom.xml b/security-utils/pom.xml
index 42da43c63d..c98a6ba11c 100644
--- a/security-utils/pom.xml
+++ b/security-utils/pom.xml
@@ -1,4 +1,5 @@
-<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">
+<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>
@@ -11,13 +12,44 @@
<version>1.1.0-SNAPSHOT</version>
</parent>
-
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
- <version>4.12</version>
+ <version>${junit.version}</version>
+ <scope>test</scope>
</dependency>
</dependencies>
+ <profiles>
+ <profile>
+ <id>Fortify</id>
+ <activation>
+ <activeByDefault>false</activeByDefault>
+ </activation>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>com.fortify.ps.maven.plugin</groupId>
+ <artifactId>sca-maven-plugin</artifactId>
+ <version>4.30</version>
+ <configuration>
+ <source>1.8</source>
+ <buildId>${project.parent.artifactId}</buildId>
+ <toplevelArtifactId>${project.parent.artifactId}</toplevelArtifactId>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-deploy-plugin</artifactId>
+ <version>2.7</version>
+ <configuration>
+ <skip>true</skip>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+ </profile>
+ </profiles>
</project>
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 b33ab9166d..0000000000
--- a/ui-ci-dev/pom.xml
+++ /dev/null
@@ -1,283 +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>1610.2.1</version>
- </parent>
-
- <artifactId>ui-ci-dev</artifactId>
- <description>Selenium tests for the SDnC Application</description>
-
-
-
- <dependencies>
-
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-api</artifactId>
- <version>1.7.10</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>com.google.guava</groupId>
- <artifactId>guava</artifactId>
- <version>${guava.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>org.apache.commons</groupId>
- <artifactId>commons-lang3</artifactId>
- <version>${lang3.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.openecomp.sdc</groupId>
- <artifactId>catalog-be</artifactId>
- <version>${asdc-tests.version}</version>
- </dependency> -->
-
- <dependency>
- <groupId>org.yaml</groupId>
- <artifactId>snakeyaml</artifactId>
- <version>1.14</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>com.google.code.gson</groupId>
- <artifactId>gson</artifactId>
- <version>2.3.1</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>
- <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>-->
- <version>${jackson.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-core</artifactId>
- <!--<version>2.3.1</version>-->
- <version>${jackson.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>org.openecomp.sdc</groupId>
- <artifactId>sdc-distribution-client</artifactId>
- <version>1.1.2</version>
- </dependency>
-
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>4.12</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>org.testng</groupId>
- <artifactId>testng</artifactId>
- <version>6.9.10</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>1.1</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>com.relevantcodes</groupId>
- <artifactId>extentreports</artifactId>
- <version>2.41.1</version>
- </dependency>
-
- <dependency>
- <groupId>org.apache.commons</groupId>
- <artifactId>commons-jci-core</artifactId>
- <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>
- <scope>compile</scope>
- </dependency>
- </dependencies>
-
-
-
- <build>
- <plugins>
-
-
-
- <!-- ============================================= -->
- <!-- 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>
-
-
- <execution>
- <id>tarball</id>
- <phase>package</phase>
- <goals>
- <goal>single</goal>
- </goals>
- <configuration>
- <finalName>${project.artifactId}-${full.release.version}${build.type}</finalName>
- <appendAssemblyId>false</appendAssemblyId>
- <descriptor>${project.basedir}/tarball.xml</descriptor>
- <attach>false</attach>
- </configuration>
- </execution>
- </executions>
- </plugin>
-
-
- <!-- =========================== -->
- <!-- HP Fortifay 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 ad0281dd74..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 64db12a422..0000000000
--- a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/datatypes/DataTestIdEnum.java
+++ /dev/null
@@ -1,428 +0,0 @@
-package org.openecomp.sdc.uici.tests.datatypes;
-
-public final class DataTestIdEnum {
- private DataTestIdEnum() {
- };
-
- 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"),
- 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 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("artifact-label"), 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"),
- VMMC(LEFT_PANEL_PREFIX + "vmmc_work");
-
- 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 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 42e9f137ec..0000000000
--- a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/execute/base/SetupCDTest.java
+++ /dev/null
@@ -1,408 +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.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.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.BeforeSuite;
-import org.testng.annotations.Optional;
-import org.testng.annotations.Parameters;
-
-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 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;
-
- /****************
- * BEFORE
- *
- * @throws FileNotFoundException
- ****************/
-
- @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() throws Exception {
- CleanTypeEnum cleanType = getCleanMode();
- switch (cleanType) {
- case FULL: {
- super.beforeState(null);
- 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() throws Exception {
- CleanTypeEnum cleanType = getCleanMode();
- switch (cleanType) {
- case FULL: {
- super.afterState(null);
- 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")) {
- 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/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 918ac934c6..0000000000
--- a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/execute/vf/VfBasicTests.java
+++ /dev/null
@@ -1,234 +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 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.verificator.VfVerificator;
-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.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);
- }
-
- @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));
- }
-
- 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 ef21e40c61..0000000000
--- a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/execute/vfc/VfcBasicTests.java
+++ /dev/null
@@ -1,219 +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 8232738660..0000000000
--- a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/run/StartTest.java
+++ /dev/null
@@ -1,394 +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);
-
- }
- }
-
- // 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 " + testClass.getName() + " finished " +
- // (result.wasSuccessful() ? "OK." : " WITH ERROR."));
- // List<Failure> failures = result.getFailures();
- // if (failures != null) {
- // for (Failure failure : failures) {
- // logger.error("Test class " + testClass.getName() + " failure test " +
- // 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 " + testClass.getName() + " Failed tests " +
- // (failuresPerClass * 1.0) / runsPerClass * 100 + " %");
- // logger.debug("class " + testClass.getName() + " Ignored tests " +
- // (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/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 4414499f69..0000000000
--- a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/utilities/GeneralUIUtils.java
+++ /dev/null
@@ -1,346 +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();
- WebElement successNotification = driver.findElement(By.className("ui-notification"));
- if (successNotification != null) {
- successNotification.click();
- }
- getWebElementWaitForVisible(DataTestIdEnum.LifeCyleChangeButtons.CHECK_IN.getValue());
- }
-
- public static void clickSaveButton() {
- WebElement createButton = getWebElementWaitForClickable(DataTestIdEnum.LifeCyleChangeButtons.CREATE.getValue());
- createButton.click();
- }
-
- public static void closeNotificatin() {
- WebElement notification = driver.findElement(By.className("ui-notification"));
- if (notification != null) {
- notification.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("userId");
- 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 477cc0c3bb..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();
- // 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 abcc3b3ade..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 projectCodeTextbox = GeneralUIUtils.getWebElementWaitForVisible("projectCode");
- projectCodeTextbox.clear();
- projectCodeTextbox.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/Files/CP.yml b/ui-ci-dev/src/main/resources/Files/CP.yml
deleted file mode 100644
index 48b592265f..0000000000
--- a/ui-ci-dev/src/main/resources/Files/CP.yml
+++ /dev/null
@@ -1,65 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-
-node_types:
- org.openecomp.resource.cp.CP:
- derived_from: tosca.nodes.Root
- properties:
- att-ucpe-part-number:
- type: string
- vendor-name:
- type: string
- required: true
- vendor-model:
- type: string
- required: true
- total-vcpu:
- type: integer
- description: number of vCPUs
- total-memory:
- type: integer
- description: GB
- total-disk:
- type: integer
- description: GB
- base-system-image-file-name:
- type: string
- linux-host-vendor:
- type: string
- linux-host-os-version:
- type: version
- base-system-software:
- type: string
- jdm-vcpu:
- type: integer
- jdm-memory:
- type: integer
- description: GB
- jdm-disk:
- type: integer
- description: GB
- jdm-version:
- type: string
- jcp-vcpu:
- type: integer
- jcp-memory:
- type: integer
- description: GB
- jcp-disk:
- type: integer
- description: GB
- jcp-version:
- type: version
- capabilities:
- vnf_hosting:
- type: tosca.capabilities.Container
- description: Provides hosting capability for VNFs
- WAN_connectivity:
- type: tosca.capabilities.network.Bindable
- valid_source_types: [org.openecomp.cp.Wan]
- description: external WAN1 n/w interface
- occurrences: [1,2]
- LAN_connectivity:
- type: tosca.capabilities.network.Bindable
- valid_source_types: [org.openecomp.cp.Lan]
- description: external LAN n/w interface
- occurrences: [1,8] \ No newline at end of file
diff --git a/ui-ci-dev/src/main/resources/Files/CP_LAN - Copy.yml b/ui-ci-dev/src/main/resources/Files/CP_LAN - Copy.yml
deleted file mode 100644
index 224d61f2c9..0000000000
--- a/ui-ci-dev/src/main/resources/Files/CP_LAN - Copy.yml
+++ /dev/null
@@ -1,13 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-
-node_types:
- org.openecomp.resource.vfc.uCPE:
- derived_from: tosca.nodes.Root
- properties:
- type:
- type: string
- required: false
- requirements:
- - virtualLink:
- capability: tosca.capabilities.network.Linkable
- relationship: tosca.relationships.network.LinksTo
diff --git a/ui-ci-dev/src/main/resources/Files/CP_LAN.yml b/ui-ci-dev/src/main/resources/Files/CP_LAN.yml
deleted file mode 100644
index a96084ba34..0000000000
--- a/ui-ci-dev/src/main/resources/Files/CP_LAN.yml
+++ /dev/null
@@ -1,19 +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_in:
- capability: tosca.capabilities.network.Linkable
- relationship: tosca.relationships.network.LinksTo
- - virtualLink_out:
- capability: tosca.capabilities.network.Linkable
- relationship: tosca.relationships.network.LinksTo
- - virtualbinding:
- capability: tosca.capabilities.network.Bindable
- relationship: tosca.relationships.network.BindsTo \ No newline at end of file
diff --git a/ui-ci-dev/src/main/resources/Files/CP_WAN.yml b/ui-ci-dev/src/main/resources/Files/CP_WAN.yml
deleted file mode 100644
index 1bce457d43..0000000000
--- a/ui-ci-dev/src/main/resources/Files/CP_WAN.yml
+++ /dev/null
@@ -1,19 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-
-node_types:
- org.openecomp.resource.cp.WAN:
- derived_from: org.openecomp.resource.cp.CP
- properties:
- type:
- type: string
- required: false
- requirements:
- - virtualLink_in:
- capability: tosca.capabilities.network.Linkable
- relationship: tosca.relationships.network.LinksTo
- - virtualLink_out:
- capability: tosca.capabilities.network.Linkable
- relationship: tosca.relationships.network.LinksTo
- - virtualbinding:
- capability: tosca.capabilities.network.Bindable
- relationship: tosca.relationships.network.BindsTo \ No newline at end of file
diff --git a/ui-ci-dev/src/main/resources/Files/Heat-File 1.yaml b/ui-ci-dev/src/main/resources/Files/Heat-File 1.yaml
deleted file mode 100644
index d332078d35..0000000000
--- a/ui-ci-dev/src/main/resources/Files/Heat-File 1.yaml
+++ /dev/null
@@ -1,791 +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_2:
- type: OS::Neutron::Port
- properties:
- network_id: { get_resource: Clustering_Network }
-
- 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/ui-ci-dev/src/main/resources/Files/Heat-File 2.yaml b/ui-ci-dev/src/main/resources/Files/Heat-File 2.yaml
deleted file mode 100644
index d332078d35..0000000000
--- a/ui-ci-dev/src/main/resources/Files/Heat-File 2.yaml
+++ /dev/null
@@ -1,791 +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_2:
- type: OS::Neutron::Port
- properties:
- network_id: { get_resource: Clustering_Network }
-
- 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/ui-ci-dev/src/main/resources/Files/Heat-File.yaml b/ui-ci-dev/src/main/resources/Files/Heat-File.yaml
deleted file mode 100644
index d332078d35..0000000000
--- a/ui-ci-dev/src/main/resources/Files/Heat-File.yaml
+++ /dev/null
@@ -1,791 +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_2:
- type: OS::Neutron::Port
- properties:
- network_id: { get_resource: Clustering_Network }
-
- 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/ui-ci-dev/src/main/resources/Files/InValid_tosca_File .yml b/ui-ci-dev/src/main/resources/Files/InValid_tosca_File .yml
deleted file mode 100644
index 4eea0a15ac..0000000000
--- a/ui-ci-dev/src/main/resources/Files/InValid_tosca_File .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
diff --git a/ui-ci-dev/src/main/resources/Files/JDM_vf.yml b/ui-ci-dev/src/main/resources/Files/JDM_vf.yml
deleted file mode 100644
index 5a7edd4aaf..0000000000
--- a/ui-ci-dev/src/main/resources/Files/JDM_vf.yml
+++ /dev/null
@@ -1,57 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-
-node_types:
- org.openecomp.resource.vf.JDM:
- derived_from: tosca.nodes.Root
- properties:
- att-part-number:
- type: string
- vendor-name:
- type: string
- vendor-part-number:
- type: string
- vendor-model:
- type: string
- vendor-model-description:
- type: string
- vcpu-default:
- type: integer
- vcpu-min:
- type: integer
- vcpu-max:
- type: integer
- vmemory-default:
- type: integer
- vmemory-units:
- type: string
- default: "GB"
- vmemory-min:
- type: integer
- vmemory-max:
- type: integer
- vdisk-default:
- type: integer
- vdisk-units:
- type: string
- default: "GB"
- vdisk-min:
- type: integer
- vdisk-max:
- type: integer
- vnf-type:
- type: string
- software-version:
- type: string
- software-version-state:
- type: integer
- software-file-name:
- type: string
- vnf-feature:
- type: string
- requirements:
- - host:
- capability: tosca.capabilities.Container
- relationship: tosca.relationships.HostedOn
- capabilities:
- binding:
- type: tosca.capabilities.network.Bindable \ No newline at end of file
diff --git a/ui-ci-dev/src/main/resources/Files/JDM_vfc.yml b/ui-ci-dev/src/main/resources/Files/JDM_vfc.yml
deleted file mode 100644
index b9c9ca0c4a..0000000000
--- a/ui-ci-dev/src/main/resources/Files/JDM_vfc.yml
+++ /dev/null
@@ -1,57 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-
-node_types:
- org.openecomp.resource.vfc.JDM:
- derived_from: tosca.nodes.Root
- properties:
- att-part-number:
- type: string
- vendor-name:
- type: string
- vendor-part-number:
- type: string
- vendor-model:
- type: string
- vendor-model-description:
- type: string
- vcpu-default:
- type: integer
- vcpu-min:
- type: integer
- vcpu-max:
- type: integer
- vmemory-default:
- type: integer
- vmemory-units:
- type: string
- default: "GB"
- vmemory-min:
- type: integer
- vmemory-max:
- type: integer
- vdisk-default:
- type: integer
- vdisk-units:
- type: string
- default: "GB"
- vdisk-min:
- type: integer
- vdisk-max:
- type: integer
- vnf-type:
- type: string
- software-version:
- type: string
- software-version-state:
- type: integer
- software-file-name:
- type: string
- vnf-feature:
- type: string
- requirements:
- - host:
- capability: tosca.capabilities.Container
- relationship: tosca.relationships.HostedOn
- capabilities:
- binding:
- type: tosca.capabilities.network.Bindable \ No newline at end of file
diff --git a/ui-ci-dev/src/main/resources/Files/Sample_CSAR.csar b/ui-ci-dev/src/main/resources/Files/Sample_CSAR.csar
deleted file mode 100644
index fe95e79473..0000000000
--- a/ui-ci-dev/src/main/resources/Files/Sample_CSAR.csar
+++ /dev/null
Binary files differ
diff --git a/ui-ci-dev/src/main/resources/Files/Sample_CSAR2.csar b/ui-ci-dev/src/main/resources/Files/Sample_CSAR2.csar
deleted file mode 100644
index 3001fe8222..0000000000
--- a/ui-ci-dev/src/main/resources/Files/Sample_CSAR2.csar
+++ /dev/null
Binary files differ
diff --git a/ui-ci-dev/src/main/resources/Files/UCPE_VFC.yml b/ui-ci-dev/src/main/resources/Files/UCPE_VFC.yml
deleted file mode 100644
index ef3966b68f..0000000000
--- a/ui-ci-dev/src/main/resources/Files/UCPE_VFC.yml
+++ /dev/null
@@ -1,65 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-
-node_types:
- org.openecomp.resource.vfc.uCPE:
- derived_from: tosca.nodes.Root
- properties:
- att-ucpe-part-number:
- type: string
- vendor-name:
- type: string
- required: true
- vendor-model:
- type: string
- required: true
- total-vcpu:
- type: integer
- description: number of vCPUs
- total-memory:
- type: integer
- description: GB
- total-disk:
- type: integer
- description: GB
- base-system-image-file-name:
- type: string
- linux-host-vendor:
- type: string
- linux-host-os-version:
- type: version
- base-system-software:
- type: string
- jdm-vcpu:
- type: integer
- jdm-memory:
- type: integer
- description: GB
- jdm-disk:
- type: integer
- description: GB
- jdm-version:
- type: string
- jcp-vcpu:
- type: integer
- jcp-memory:
- type: integer
- description: GB
- jcp-disk:
- type: integer
- description: GB
- jcp-version:
- type: version
- capabilities:
- vnf_hosting:
- type: tosca.capabilities.Container
- description: Provides hosting capability for VNFs
- WAN_connectivity:
- type: tosca.capabilities.network.Bindable
- valid_source_types: [org.openecomp.cp.Wan]
- description: external WAN1 n/w interface
- occurrences: [1,2]
- LAN_connectivity:
- type: tosca.capabilities.network.Bindable
- valid_source_types: [org.openecomp.cp.Lan]
- description: external LAN n/w interface
- occurrences: [1,8] \ No newline at end of file
diff --git a/ui-ci-dev/src/main/resources/Files/VF.yml b/ui-ci-dev/src/main/resources/Files/VF.yml
deleted file mode 100644
index ec089900ad..0000000000
--- a/ui-ci-dev/src/main/resources/Files/VF.yml
+++ /dev/null
@@ -1,17 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-
-node_types:
- org.openecomp.resource.vf.VFF:
- derived_from: tosca.nodes.Root
- properties:
- vendor:
- type: string
- required: false
- vl_name:
- type: string
- required: false
- capabilities:
- virtual_linkable:
- type: tosca.capabilities.network.Linkable
-
- \ No newline at end of file
diff --git a/ui-ci-dev/src/main/resources/Files/VFC.yml b/ui-ci-dev/src/main/resources/Files/VFC.yml
deleted file mode 100644
index 853ed35374..0000000000
--- a/ui-ci-dev/src/main/resources/Files/VFC.yml
+++ /dev/null
@@ -1,77 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-
-node_types:
- org.openecomp.resource.vfc.vRouter:
- derived_from: tosca.nodes.Root
- properties:
- att-part-number:
- type: string
- vendor-name:
- type: string
- vendor-part-number:
- type: string
- vendor-model:
- type: string
- vendor-model-description:
- type: string
- vcpu-default:
- type: integer
- vcpu-min:
- type: integer
- vcpu-max:
- type: integer
- vmemory-default:
- type: integer
- vmemory-units:
- type: string
- default: "GB"
- vmemory-min:
- type: integer
- vmemory-max:
- type: integer
- vdisk-default:
- type: integer
- vdisk-units:
- type: string
- default: "GB"
- vdisk-min:
- type: integer
- vdisk-max:
- type: integer
- vnf-type:
- type: string
- software-version:
- type: string
- software-version-state:
- type: integer
- software-file-name:
- type: string
- vnf-feature:
- type: string
- management-v6-address:
- type: string
- nm-lan-v6-address:
- type: string
- nm-lan-v6-prefix-length:
- type: string
- management-v4-address:
- type: string
- nm-lan-v4-address:
- type: string
- nm-lan-v4-prefix-length:
- type: string
- routing-instance-name:
- type: string
- routing-instances:
- type: map
- entry_schema:
- type: string
- requirements:
- - host:
- capability: tosca.capabilities.Container
- relationship: tosca.relationships.HostedOn
- capabilities:
- binding:
- type: tosca.capabilities.network.Bindable
- occurrences: [1,UNBOUNDED]
- \ No newline at end of file
diff --git a/ui-ci-dev/src/main/resources/Files/VFCWithAttributes.yml b/ui-ci-dev/src/main/resources/Files/VFCWithAttributes.yml
deleted file mode 100644
index 133fd02cef..0000000000
--- a/ui-ci-dev/src/main/resources/Files/VFCWithAttributes.yml
+++ /dev/null
@@ -1,43 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-
-node_types:
- org.openecomp.resource.vfc.VFC:
- derived_from: tosca.nodes.Root
- properties:
- jcp-memory:
- type: integer
- description: GB
- jcp-disk:
- type: integer
- description: GB
- jcp-version:
- type: version
- attributes:
- my_attr:
- type: integer
- 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:
- vnf_hosting:
- type: tosca.capabilities.Container
- description: Provides hosting capability for VNFs
- WAN_connectivity:
- type: tosca.capabilities.network.Bindable
- valid_source_types: [org.openecomp.cp.Wan]
- description: external WAN1 n/w interface
- occurrences: [1,2]
- LAN_connectivity:
- type: tosca.capabilities.network.Bindable
- valid_source_types: [org.openecomp.cp.Lan]
- description: external LAN n/w interface
- occurrences: [1,8] \ No newline at end of file
diff --git a/ui-ci-dev/src/main/resources/Files/VL.yml b/ui-ci-dev/src/main/resources/Files/VL.yml
deleted file mode 100644
index 74a2405af2..0000000000
--- a/ui-ci-dev/src/main/resources/Files/VL.yml
+++ /dev/null
@@ -1,17 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-
-node_types:
- org.openecomp.resource.vl.VL1we23:
- derived_from: tosca.nodes.Root
- properties:
- vendor:
- type: string
- required: false
- vl_name:
- type: string
- required: false
- capabilities:
- virtual_linkable:
- type: tosca.capabilities.network.Linkable
-
- \ No newline at end of file
diff --git a/ui-ci-dev/src/main/resources/Files/Valid xml.xml b/ui-ci-dev/src/main/resources/Files/Valid xml.xml
deleted file mode 100644
index 0d67e48340..0000000000
--- a/ui-ci-dev/src/main/resources/Files/Valid xml.xml
+++ /dev/null
@@ -1,4 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" standalone="no"?>
-<dirs>
-<entry loc="C:\Program Files\Java\jdk1.7.0_79" stamp="1449076618518"/>
-</dirs>
diff --git a/ui-ci-dev/src/main/resources/Files/Valid_tosca_Mycompute.yml b/ui-ci-dev/src/main/resources/Files/Valid_tosca_Mycompute.yml
deleted file mode 100644
index 8fac5e16a8..0000000000
--- a/ui-ci-dev/src/main/resources/Files/Valid_tosca_Mycompute.yml
+++ /dev/null
@@ -1,35 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- org.openecomp.resource.vf.Database:
- 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/ui-ci-dev/src/main/resources/Files/Valid_tosca_ReplaceTest.yml b/ui-ci-dev/src/main/resources/Files/Valid_tosca_ReplaceTest.yml
deleted file mode 100644
index 90e771dab1..0000000000
--- a/ui-ci-dev/src/main/resources/Files/Valid_tosca_ReplaceTest.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/ui-ci-dev/src/main/resources/Files/hot-nimbus-oam-volumes_v0.3.env b/ui-ci-dev/src/main/resources/Files/hot-nimbus-oam-volumes_v0.3.env
deleted file mode 100644
index b494d8c270..0000000000
--- a/ui-ci-dev/src/main/resources/Files/hot-nimbus-oam-volumes_v0.3.env
+++ /dev/null
@@ -1,6 +0,0 @@
-parameters:
- pcrf_oam_vol_size: 500
- pcrf_oam_volume_silver-1: Silver
- pcrf_oam_volume_silver-2: Silver
- pcrf_oam_vol_name_1: sde1-pcrfx01-oam001-vol-1
- pcrf_oam_vol_name_2: sde1-pcrfx01-oam001-vol-2 \ No newline at end of file
diff --git a/ui-ci-dev/src/main/resources/Files/hot-nimbus-oam_v0.6.env b/ui-ci-dev/src/main/resources/Files/hot-nimbus-oam_v0.6.env
deleted file mode 100644
index cf7cf710ce..0000000000
--- a/ui-ci-dev/src/main/resources/Files/hot-nimbus-oam_v0.6.env
+++ /dev/null
@@ -1,18 +0,0 @@
-parameters:
- pcrf_oam_server_names: ZRDM1PCRF01OAM001,ZRDM1PCRF01OAM002
- pcrf_oam_image_name: PCRF_8.995-ATTM1.0.3.qcow2
- pcrf_oam_flavor_name: lc.4xlarge4
- availabilityzone_name: nova
- pcrf_cps_net_name: int_pcrf_net_0
- pcrf_cps_net_ips: 172.26.16.111,172.26.16.112
- pcrf_arbiter_vip: 172.26.16.115
- pcrf_cps_net_mask: 255.255.255.0
- pcrf_oam_net_name: oam_protected_net_0
- pcrf_oam_net_ips: 107.239.64.117,107.239.64.118
- pcrf_oam_net_gw: 107.239.64.1
- pcrf_oam_net_mask: 255.255.248.0
- pcrf_oam_volume_id_1: a4aa05fb-fcdc-457b-8077-6845fdfc3257
- pcrf_oam_volume_id_2: 93d8fc1f-f1c3-4933-86b2-039881ee910f
- pcrf_security_group_name: nimbus_security_group
- pcrf_vnf_id: 730797234b4a40aa99335157b02871cd
-
diff --git a/ui-ci-dev/src/main/resources/Files/hot-nimbus-oam_v0.6.yaml b/ui-ci-dev/src/main/resources/Files/hot-nimbus-oam_v0.6.yaml
deleted file mode 100644
index 6636eba210..0000000000
--- a/ui-ci-dev/src/main/resources/Files/hot-nimbus-oam_v0.6.yaml
+++ /dev/null
@@ -1,108 +0,0 @@
-heat_template_version: 2013-05-23
-
-description: heat template that creates multiple PCRF OAM nodes stack
-
-parameters:
- pcrf_oam_server_names:
- type: comma_delimited_list
- label: PCRF OAM server names
- description: name of the PCRF OAM instance
- pcrf_oam_image_name:
- type: string
- label: PCRF OAM image name
- description: PCRF OAM image name
- pcrf_oam_flavor_name:
- type: string
- label: PCRF OAM flavor name
- description: flavor name of PCRF OAM instance
- availabilityzone_name:
- type: string
- label: availabilityzone name
- description: availabilityzone name
- pcrf_cps_net_name:
- type: string
- label: CPS network name
- description: CPS network name
- pcrf_cps_net_ips:
- type: comma_delimited_list
- label: CPS network ips
- description: CPS network ips
- pcrf_cps_net_mask:
- type: string
- label: CPS network mask
- description: CPS network mask
- pcrf_arbiter_vip:
- type: string
- label: OAM Arbiter LB VIP
- description: OAM Arbiter LB VIP
- pcrf_oam_net_name:
- type: string
- label: OAM network name
- description: OAM network name
- pcrf_oam_net_ips:
- type: comma_delimited_list
- label: OAM network ips
- description: OAM network ips
- pcrf_oam_net_gw:
- type: string
- label: CPS network gateway
- description: CPS network gateway
- pcrf_oam_net_mask:
- type: string
- label: CPS network mask
- description: CPS network mask
- pcrf_oam_volume_id_1:
- type: string
- label: CPS OAM 001 Cinder Volume
- description: CPS OAM 001 Cinder Volumes
- pcrf_oam_volume_id_2:
- type: string
- label: CPS OAM 002 Cinder Volume
- description: CPS OAM 002 Cinder Volumes
- pcrf_security_group_name:
- type: string
- label: security group name
- description: the name of security group
- pcrf_vnf_id:
- type: string
- label: PCRF VNF Id
- description: PCRF VNF Id
-
-resources:
- server_pcrf_oam_001:
- type: nested-oam_v0.2.yaml
- properties:
- pcrf_oam_server_name: { get_param: [pcrf_oam_server_names, 0] }
- pcrf_oam_image_name: { get_param: pcrf_oam_image_name }
- pcrf_oam_flavor_name: { get_param: pcrf_oam_flavor_name }
- availabilityzone_name: { get_param: availabilityzone_name }
- pcrf_security_group_name: { get_param: pcrf_security_group_name }
- pcrf_oam_volume_id: { get_param: pcrf_oam_volume_id_1 }
- pcrf_cps_net_name: { get_param: pcrf_cps_net_name }
- pcrf_cps_net_ip: { get_param: [pcrf_cps_net_ips, 0] }
- pcrf_cps_net_mask: { get_param: pcrf_cps_net_mask }
- pcrf_oam_net_name: { get_param: pcrf_oam_net_name }
- pcrf_oam_net_ip: { get_param: [pcrf_oam_net_ips, 0] }
- pcrf_oam_net_mask: { get_param: pcrf_oam_net_mask }
- pcrf_oam_net_gw: { get_param: pcrf_oam_net_gw }
- pcrf_arbiter_vip: { get_param: pcrf_arbiter_vip }
- pcrf_vnf_id: {get_param: pcrf_vnf_id}
-
- server_pcrf_oam_002:
- type: nested-oam_v0.2.yaml
- properties:
- pcrf_oam_server_name: { get_param: [pcrf_oam_server_names, 1] }
- pcrf_oam_image_name: { get_param: pcrf_oam_image_name }
- pcrf_oam_flavor_name: { get_param: pcrf_oam_flavor_name }
- availabilityzone_name: { get_param: availabilityzone_name }
- pcrf_security_group_name: { get_param: pcrf_security_group_name }
- pcrf_oam_volume_id: { get_param: pcrf_oam_volume_id_2 }
- pcrf_cps_net_name: { get_param: pcrf_cps_net_name }
- pcrf_cps_net_ip: { get_param: [pcrf_cps_net_ips, 1] }
- pcrf_cps_net_mask: { get_param: pcrf_cps_net_mask }
- pcrf_oam_net_name: { get_param: pcrf_oam_net_name }
- pcrf_oam_net_ip: { get_param: [pcrf_oam_net_ips, 1] }
- pcrf_oam_net_mask: { get_param: pcrf_oam_net_mask }
- pcrf_oam_net_gw: { get_param: pcrf_oam_net_gw }
- pcrf_arbiter_vip: { get_param: pcrf_arbiter_vip }
- pcrf_vnf_id: {get_param: pcrf_vnf_id}
diff --git a/ui-ci-dev/src/main/resources/Files/hot-nimbus-pcm_v0.6.yaml b/ui-ci-dev/src/main/resources/Files/hot-nimbus-pcm_v0.6.yaml
deleted file mode 100644
index 564104174a..0000000000
--- a/ui-ci-dev/src/main/resources/Files/hot-nimbus-pcm_v0.6.yaml
+++ /dev/null
@@ -1,80 +0,0 @@
-heat_template_version: 2013-05-23
-
-description: heat template that creates PCRF Cluman stack
-
-parameters:
- pcrf_pcm_server_names:
- type: comma_delimited_list
- label: PCRF CM server names
- description: name of the PCRF CM instance
- pcrf_pcm_image_name:
- type: string
- label: PCRF CM image name
- description: PCRF CM image name
- pcrf_pcm_flavor_name:
- type: string
- label: PCRF CM flavor name
- description: flavor name of PCRF CM instance
- availabilityzone_name:
- type: string
- label: availabilityzone name
- description: availabilityzone name
- pcrf_cps_net_name:
- type: string
- label: CPS network name
- description: CPS network name
- pcrf_cps_net_ips:
- type: comma_delimited_list
- label: CPS network ips
- description: CPS network ips
- pcrf_cps_net_mask:
- type: string
- label: CPS network mask
- description: CPS network mask
- pcrf_oam_net_name:
- type: string
- label: OAM network name
- description: OAM network name
- pcrf_oam_net_ips:
- type: comma_delimited_list
- label: OAM network ips
- description: OAM network ips
- pcrf_oam_net_gw:
- type: string
- label: CPS network gateway
- description: CPS network gateway
- pcrf_oam_net_mask:
- type: string
- label: CPS network mask
- description: CPS network mask
- pcrf_pcm_volume_id_1:
- type: string
- label: CPS Cluman Cinder Volume
- description: CPS Cluman Cinder Volume
- pcrf_security_group_name:
- type: string
- label: security group name
- description: the name of security group
- pcrf_vnf_id:
- type: string
- label: PCRF VNF Id
- description: PCRF VNF Id
-
-resources:
- server_pcrf_pcm_001:
- type: nested-pcm_v0.2.yaml
- properties:
- pcrf_pcm_server_name: { get_param: [pcrf_pcm_server_names, 0] }
- pcrf_pcm_image_name: { get_param: pcrf_pcm_image_name }
- pcrf_pcm_flavor_name: { get_param: pcrf_pcm_flavor_name }
- availabilityzone_name: { get_param: availabilityzone_name }
- pcrf_security_group_name: { get_param: pcrf_security_group_name }
- pcrf_pcm_volume_id: { get_param: pcrf_pcm_volume_id_1 }
- pcrf_cps_net_name: { get_param: pcrf_cps_net_name }
- pcrf_cps_net_ip: { get_param: [pcrf_cps_net_ips, 0] }
- pcrf_cps_net_mask: { get_param: pcrf_cps_net_mask }
- pcrf_oam_net_name: { get_param: pcrf_oam_net_name }
- pcrf_oam_net_ip: { get_param: [pcrf_oam_net_ips, 0] }
- pcrf_oam_net_mask: { get_param: pcrf_oam_net_mask }
- pcrf_oam_net_gw: { get_param: pcrf_oam_net_gw }
- pcrf_vnf_id: {get_param: pcrf_vnf_id}
diff --git a/ui-ci-dev/src/main/resources/Files/myYang.xml b/ui-ci-dev/src/main/resources/Files/myYang.xml
deleted file mode 100644
index 0d86d213e6..0000000000
--- a/ui-ci-dev/src/main/resources/Files/myYang.xml
+++ /dev/null
@@ -1,8 +0,0 @@
-<beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
-
- <bean id="muranoLogic" class="org.openecomp.sdc.impl.MuranoLogic"> </bean>
-
-</beans> \ No newline at end of file
diff --git a/ui-ci-dev/src/main/resources/Files/mycompute.yml b/ui-ci-dev/src/main/resources/Files/mycompute.yml
deleted file mode 100644
index c8a0c03384..0000000000
--- a/ui-ci-dev/src/main/resources/Files/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/ui-ci-dev/src/main/resources/Files/service_with_inputs.csar b/ui-ci-dev/src/main/resources/Files/service_with_inputs.csar
deleted file mode 100644
index c4d4881fec..0000000000
--- a/ui-ci-dev/src/main/resources/Files/service_with_inputs.csar
+++ /dev/null
Binary files differ
diff --git a/ui-ci-dev/src/main/resources/Files/vADTRAN.zip b/ui-ci-dev/src/main/resources/Files/vADTRAN.zip
deleted file mode 100644
index 3ecde2c7ec..0000000000
--- a/ui-ci-dev/src/main/resources/Files/vADTRAN.zip
+++ /dev/null
Binary files differ
diff --git a/ui-ci-dev/src/main/resources/Files/vCDN.zip b/ui-ci-dev/src/main/resources/Files/vCDN.zip
deleted file mode 100644
index 51e654a841..0000000000
--- a/ui-ci-dev/src/main/resources/Files/vCDN.zip
+++ /dev/null
Binary files differ
diff --git a/ui-ci-dev/src/main/resources/Files/vFW_VF.yml b/ui-ci-dev/src/main/resources/Files/vFW_VF.yml
deleted file mode 100644
index 100883e399..0000000000
--- a/ui-ci-dev/src/main/resources/Files/vFW_VF.yml
+++ /dev/null
@@ -1,58 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-
-node_types:
-
- org.openecomp.resource.vf.vFW:
- derived_from: tosca.nodes.Root
- properties:
- att-part-number:
- type: string
- vendor-name:
- type: string
- vendor-part-number:
- type: string
- vendor-model:
- type: string
- vendor-model-description:
- type: string
- vcpu-default:
- type: integer
- vcpu-min:
- type: integer
- vcpu-max:
- type: integer
- vmemory-default:
- type: integer
- vmemory-units:
- type: string
- default: "GB"
- vmemory-min:
- type: integer
- vmemory-max:
- type: integer
- vdisk-default:
- type: integer
- vdisk-units:
- type: string
- default: "GB"
- vdisk-min:
- type: integer
- vdisk-max:
- type: integer
- vnf-type:
- type: string
- software-version:
- type: version
- software-version-state:
- type: integer
- software-file-name:
- type: string
- vnf-feature:
- type: string
- requirements:
- - host:
- capability: tosca.capabilities.Container
- relationship: tosca.relationships.HostedOn
- capabilities:
- binding:
- type: tosca.capabilities.network.Bindable \ No newline at end of file
diff --git a/ui-ci-dev/src/main/resources/Files/vFW_VFC.yml b/ui-ci-dev/src/main/resources/Files/vFW_VFC.yml
deleted file mode 100644
index d0814c43aa..0000000000
--- a/ui-ci-dev/src/main/resources/Files/vFW_VFC.yml
+++ /dev/null
@@ -1,58 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-
-node_types:
-
- org.openecomp.resource.vfc.vFW:
- derived_from: tosca.nodes.Root
- properties:
- att-part-number:
- type: string
- vendor-name:
- type: string
- vendor-part-number:
- type: string
- vendor-model:
- type: string
- vendor-model-description:
- type: string
- vcpu-default:
- type: integer
- vcpu-min:
- type: integer
- vcpu-max:
- type: integer
- vmemory-default:
- type: integer
- vmemory-units:
- type: string
- default: "GB"
- vmemory-min:
- type: integer
- vmemory-max:
- type: integer
- vdisk-default:
- type: integer
- vdisk-units:
- type: string
- default: "GB"
- vdisk-min:
- type: integer
- vdisk-max:
- type: integer
- vnf-type:
- type: string
- software-version:
- type: version
- software-version-state:
- type: integer
- software-file-name:
- type: string
- vnf-feature:
- type: string
- requirements:
- - host:
- capability: tosca.capabilities.Container
- relationship: tosca.relationships.HostedOn
- capabilities:
- binding:
- type: tosca.capabilities.network.Bindable \ No newline at end of file
diff --git a/ui-ci-dev/src/main/resources/Files/vRouter_vfc.yml b/ui-ci-dev/src/main/resources/Files/vRouter_vfc.yml
deleted file mode 100644
index 95ffe959de..0000000000
--- a/ui-ci-dev/src/main/resources/Files/vRouter_vfc.yml
+++ /dev/null
@@ -1,78 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-
-
-node_types:
- org.openecomp.resource.vfc.vRouter:
- derived_from: tosca.nodes.Root
- properties:
- att-part-number:
- type: string
- vendor-name:
- type: string
- vendor-part-number:
- type: string
- vendor-model:
- type: string
- vendor-model-description:
- type: string
- vcpu-default:
- type: integer
- vcpu-min:
- type: integer
- vcpu-max:
- type: integer
- vmemory-default:
- type: integer
- vmemory-units:
- type: string
- default: "GB"
- vmemory-min:
- type: integer
- vmemory-max:
- type: integer
- vdisk-default:
- type: integer
- vdisk-units:
- type: string
- default: "GB"
- vdisk-min:
- type: integer
- vdisk-max:
- type: integer
- vnf-type:
- type: string
- software-version:
- type: string
- software-version-state:
- type: integer
- software-file-name:
- type: string
- vnf-feature:
- type: string
- management-v6-address:
- type: string
- nm-lan-v6-address:
- type: string
- nm-lan-v6-prefix-length:
- type: string
- management-v4-address:
- type: string
- nm-lan-v4-address:
- type: string
- nm-lan-v4-prefix-length:
- type: string
- routing-instance-name:
- type: string
- routing-instances:
- type: map
- entry_schema:
- type: string
- requirements:
- - host:
- capability: tosca.capabilities.Container
- relationship: tosca.relationships.HostedOn
- capabilities:
- binding:
- type: tosca.capabilities.network.Bindable
- occurrences: [1,UNBOUNDED]
- \ No newline at end of file
diff --git a/ui-ci-dev/src/main/resources/Files/valid HEAT_ENV files.env b/ui-ci-dev/src/main/resources/Files/valid HEAT_ENV files.env
deleted file mode 100644
index e576c0f67d..0000000000
--- a/ui-ci-dev/src/main/resources/Files/valid HEAT_ENV files.env
+++ /dev/null
@@ -1,54 +0,0 @@
-parameters:
- flavor_scp_be_id: m1.small
- flavor_scp_fe_id: m1.small
- flavor_smp_id: m1.small
- flavor_db_id: m1.small
- image_scp_be_id: CCLINUX
- image_scp_fe_id: CCLINUX
- image_smp_id: CCLINUX
- image_db_id: CCLINUX
-
- int_vscp_fe_cluster_net_id: int_vscp_fe_cluster_net
- int_vscp_fe_cluster_cidr: 172.26.2.0/24
- int_vscp_cluster_net_id: int_vscp_cluster_net
- int_vscp_cluster_cidr: 172.26.3.0/24
- int_vscp_db_network_net_id: int_vscp_db_network_net
- int_vscp_db_network_cidr: 172.26.1.0/24
-
- SIGNET_vrf_A1_direct_net_id: SIGNET_vrf_A1_direct_net
- SIGNET_vrf_B1_direct_net_id: SIGNET_vrf_B1_direct_net
- Cricket_OCS_protected_net_id: Cricket_OCS_protected_net
-# OAM_direct_net_id: OAM_net
-# OAM_direct_net_id: oam-direct-net
- OAM_direct_net_id: Marks_OAM_direct_net
-
- be0_Cricket_OCS_protected_ips: 107.239.15.17
- be1_Cricket_OCS_protected_ips: 107.239.15.18
- be2_Cricket_OCS_protected_ips: 107.239.15.19
- be3_Cricket_OCS_protected_ips: 107.239.15.20
- be4_Cricket_OCS_protected_ips: 107.239.15.21
- be0_OAM_direct_ips: 10.250.10.33
- be1_OAM_direct_ips: 10.250.10.34
- be2_OAM_direct_ips: 10.250.10.35
- be3_OAM_direct_ips: 10.250.10.36
- be4_OAM_direct_ips: 10.250.10.37
- fe0_SIGNET_vrf_A1_direct_ips: 172.26.4.1
- fe0_OAM_direct_ips: 10.250.10.38
- fe1_SIGNET_vrf_B1_direct_ips: 172.26.4.5
- fe1_OAM_direct_ips: 10.250.10.39
- smp0_OAM_direct_ips: 10.250.10.40
- smp1_OAM_direct_ips: 10.250.10.41
- db0_OAM_direct_ips: 10.250.10.42
- db1_OAM_direct_ips: 10.250.10.43
-
- vm_scp_be0_name: vSCP_BE0
- vm_scp_be1_name: vSCP_BE1
- vm_scp_be2_name: vSCP_BE2
- vm_scp_be3_name: vSCP_BE3
- vm_scp_be4_name: vSCP_BE4
- vm_scp_fe0_name: vSCP_FE0
- vm_scp_fe1_name: vSCP_FE1
- vm_smp0_name: vSMP0
- vm_smp1_name: vSMP1
- vm_db0_name: vDB0
- vm_db1_name: vDB1
diff --git a/ui-ci-dev/src/main/resources/Files/validHEATfiles.yaml b/ui-ci-dev/src/main/resources/Files/validHEATfiles.yaml
deleted file mode 100644
index 6835485ca1..0000000000
--- a/ui-ci-dev/src/main/resources/Files/validHEATfiles.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/ui-ci-dev/src/main/resources/Files/valid_vf.csar b/ui-ci-dev/src/main/resources/Files/valid_vf.csar
deleted file mode 100644
index 01bf159071..0000000000
--- a/ui-ci-dev/src/main/resources/Files/valid_vf.csar
+++ /dev/null
Binary files differ
diff --git a/ui-ci-dev/src/main/resources/Files/yamlSample.yml b/ui-ci-dev/src/main/resources/Files/yamlSample.yml
deleted file mode 100644
index 10ccf71d51..0000000000
--- a/ui-ci-dev/src/main/resources/Files/yamlSample.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/ui-ci-dev/src/main/resources/Files/yamlSample2.yml b/ui-ci-dev/src/main/resources/Files/yamlSample2.yml
deleted file mode 100644
index 10ccf71d51..0000000000
--- a/ui-ci-dev/src/main/resources/Files/yamlSample2.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/ui-ci-dev/src/main/resources/ci/conf/credentials.yaml b/ui-ci-dev/src/main/resources/ci/conf/credentials.yaml
deleted file mode 100644
index 63a4280264..0000000000
--- a/ui-ci-dev/src/main/resources/ci/conf/credentials.yaml
+++ /dev/null
@@ -1,48 +0,0 @@
- designer: {
- username: m99121,
- password: 66-Percent,
- firstname: ASDC,
- lastname: KASPIN
- }
- admin: {
- username: m99122,
- password: 98-Degrees,
- firstname: ASDC,
- lastname: KASPIN
- }
- ops: {
- username: m99123,
- password: 17-Diameter,
- firstname: ASDC,
- lastname: KASPIN
- }
- tester: {
- username: m99124,
- password: 802-NotaGroup,
- firstname: ASDC,
- lastname: KASPIN
- }
- governor: {
- username: m99125,
- password: 142-Officiant,
- firstname: ASDC,
- lastname: KASPIN
- }
- product_strategist: {
- username: m99126,
- password: 1910-FruitGum,
- firstname: ASDC,
- lastname: KASPIN
- }
- product_manager: {
- username: m99127,
- password: 747-Airplane,
- firstname: ASDC,
- lastname: KASPIN
- }
- product_local: {
- username: pm0001,
- password: 123123a,
- firstname: ASDC,
- lastname: KASPIN
- } \ No newline at end of file
diff --git a/ui-ci-dev/src/main/resources/ci/conf/log4j.properties b/ui-ci-dev/src/main/resources/ci/conf/log4j.properties
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/sdc-packages.yaml b/ui-ci-dev/src/main/resources/ci/conf/sdc-packages.yaml
deleted file mode 100644
index dcb78eefc1..0000000000
--- a/ui-ci-dev/src/main/resources/ci/conf/sdc-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/sdc.yaml b/ui-ci-dev/src/main/resources/ci/conf/sdc.yaml
deleted file mode 100644
index bdca2ab972..0000000000
--- a/ui-ci-dev/src/main/resources/ci/conf/sdc.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:9000/#/dashboard
-url: http://localhost:8181/sdc1/proxy-designer1#/dashboard
-
-webSealSimulatorUrl: http://localhost:8285/sdc1
-remoteTestingMachineIP: 1.2.3.4
-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
-
-#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/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 27933699a5..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/sdc.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-dev/tarball.xml b/ui-ci-dev/tarball.xml
deleted file mode 100644
index 9262e6f02b..0000000000
--- a/ui-ci-dev/tarball.xml
+++ /dev/null
@@ -1,66 +0,0 @@
-<assembly
- xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
- <id>bin</id>
- <formats>
- <format>tar</format>
- </formats>
- <files>
- <file>
- <source>${project.build.directory}/${project.artifactId}-${project.version}-jar-with-dependencies.jar</source>
- <outputDirectory>./</outputDirectory>
- <destName>${project.artifactId}-${project.version}-jar-with-dependencies.jar</destName>
- </file>
- <file>
- <source>../asdc-tests/src/main/resources/ci/scripts/startTest.sh</source>
- <outputDirectory>./</outputDirectory>
- <destName>startTest.sh</destName>
- </file>
- <!--file> <source>src/main/resources/ci/scripts/postinstall</source> <outputDirectory>./</outputDirectory>
- <destName>postinstall</destName> </file -->
- <file>
- <source>../asdc-tests/src/main/resources/ci/conf/sdc.yaml</source>
- <outputDirectory>conf</outputDirectory>
- <destName>sdc.yaml</destName>
- </file>
- <file>
- <source>src/main/resources/ci/conf/sdc-packages.yaml</source>
- <outputDirectory>conf</outputDirectory>
- <destName>sdc-packages.yaml</destName>
- </file>
- <file>
- <source>../asdc-tests/src/main/resources/ci/conf/log4j.properties</source>
- <outputDirectory>conf</outputDirectory>
- <destName>log4j.properties</destName>
- </file>
-<!-- <file>
- <source>src/main/resources/ci/conf/titan.properties</source>
- <outputDirectory>conf</outputDirectory>
- <destName>titan.properties</destName>
- </file> -->
-<!-- <file>
- <source>${project.basedir}/../catalog-be/src/main/resources/config/error-configuration.yaml</source>
- <outputDirectory>conf</outputDirectory>
- <destName>error-configuration.yaml</destName>
- </file> -->
- <file>
- <source>src/main/resources/ci/conf/credentials.yaml</source>
- <outputDirectory>conf</outputDirectory>
- <destName>credentials.yaml</destName>
- </file>
-
- </files>
-
- <fileSets>
- <fileSet>
- <directory>src/test/resources</directory>
- <outputDirectory>./</outputDirectory>
- </fileSet>
- <fileSet>
- <directory>src/main/resources/ci/testSuites</directory>
- <outputDirectory>./testSuites</outputDirectory>
- </fileSet>
- </fileSets>
-
-</assembly>
diff --git a/ui-ci/.gitignore b/ui-ci/.gitignore
deleted file mode 100644
index a3b2274a53..0000000000
--- a/ui-ci/.gitignore
+++ /dev/null
@@ -1,3 +0,0 @@
-/bin/
-test-output/
-/target/
diff --git a/ui-ci/pom.xml b/ui-ci/pom.xml
deleted file mode 100644
index b221f8fab3..0000000000
--- a/ui-ci/pom.xml
+++ /dev/null
@@ -1,290 +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>ui-ci</artifactId>
- <description>Selenium tests for the SDnC Application</description>
-
- <parent>
- <groupId>org.openecomp.sdc</groupId>
- <artifactId>sdc-main</artifactId>
- <version>1.1.0-SNAPSHOT</version>
-
- </parent>
-
- <dependencies>
-
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-api</artifactId>
- <version>1.7.10</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>com.google.guava</groupId>
- <artifactId>guava</artifactId>
- <version>${guava.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>org.apache.commons</groupId>
- <artifactId>commons-lang3</artifactId>
- <version>${lang3.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>org.seleniumhq.selenium</groupId>
- <artifactId>selenium-java</artifactId>
- <version>2.48.0</version>
- </dependency>
-
- <dependency>
- <groupId>org.seleniumhq.selenium</groupId>
- <artifactId>selenium-server</artifactId>
- <version>2.53.1</version>
- <scope>runtime</scope>
- </dependency>
-
-<!-- <dependency>
- <groupId>org.seleniumhq.selenium</groupId>
- <artifactId>selenium-firefox-driver</artifactId>
- <version>3.0.1</version>
- </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>1.14</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>com.google.code.gson</groupId>
- <artifactId>gson</artifactId>
- <version>2.3.1</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>1.2.1-SNAPSHOT</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>-->
- <version>${jackson.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-core</artifactId>
- <!--<version>2.3.1</version>-->
- <version>${jackson.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>org.openecomp.sdc</groupId>
- <artifactId>sdc-distribution-client</artifactId>
- <version>1.0.0-SNAPSHOT</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>4.12</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>org.testng</groupId>
- <artifactId>testng</artifactId>
- <version>6.9.10</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>1.1</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>org.apache.commons</groupId>
- <artifactId>commons-jci-core</artifactId>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>commons-codec</groupId>
- <artifactId>commons-codec</artifactId>
- <version>2.0-SNAPSHOT</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>com.relevantcodes</groupId>
- <artifactId>extentreports</artifactId>
- <version>2.41.1</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>
- <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>
- </plugins>
- </build>
-
-
-
- <profiles>
- <profile>
- <id>CI</id>
- <activation>
- <activeByDefault>false</activeByDefault>
- </activation>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-assembly-plugin</artifactId>
- <version>2.5.5</version>
- <executions>
- <execution>
- <id>tarball</id>
- <phase>package</phase>
- <goals>
- <goal>single</goal>
- </goals>
- <configuration>
- <finalName>${project.artifactId}-${full.release.version}${build.type}</finalName>
- <appendAssemblyId>false</appendAssemblyId>
- <descriptor>${project.basedir}/tarball.xml</descriptor>
- <attach>false</attach>
- </configuration>
- </execution>
- </executions>
- </plugin>
- </plugins>
- </build>
- </profile>
- </profiles>
-</project>
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ArtifactInfo.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ArtifactInfo.java
deleted file mode 100644
index 4de9ae8436..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ArtifactInfo.java
+++ /dev/null
@@ -1,85 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.datatypes;
-
-public class ArtifactInfo {
-
- private String filepath;
- private String filename;
- private String description;
- private String artifactType;
- private String artifactLabel;
-
- public ArtifactInfo(String filepath, String filename, String description, String artifactLabel,
- String artifactType) {
- super();
- this.filepath = filepath;
- this.filename = filename;
- this.description = description;
- this.artifactType = artifactType;
- this.artifactLabel = artifactLabel;
- }
-
- public ArtifactInfo() {
- super();
- }
-
- public String getFilepath() {
- return filepath;
- }
-
- public void setFilepath(String filepath) {
- this.filepath = filepath;
- }
-
- public String getFilename() {
- return filename;
- }
-
- public void setFilename(String filename) {
- this.filename = filename;
- }
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- public String getArtifactType() {
- return artifactType;
- }
-
- public void setArtifactType(String artifactType) {
- this.artifactType = artifactType;
- }
-
- public String getArtifactLabel() {
- return artifactLabel;
- }
-
- public void setArtifactLabel(String artifactLabel) {
- this.artifactLabel = artifactLabel;
- }
-
-}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/CanvasElement.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/CanvasElement.java
deleted file mode 100644
index 818b488d64..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/CanvasElement.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.datatypes;
-
-import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.LeftPanelCanvasItems;
-
-public final class CanvasElement {
- private final String uniqueId;
- private ImmutablePair<Integer, Integer> location;
- private LeftPanelCanvasItems normativeElementType;
- private String elementType;
-
- CanvasElement(String name, ImmutablePair<Integer, Integer> location, LeftPanelCanvasItems canvasItem) {
- super();
- this.uniqueId = name;
- this.location = location;
- normativeElementType = canvasItem;
- }
-
- CanvasElement(String name, ImmutablePair<Integer, Integer> location, String canvasItem) {
- super();
- this.uniqueId = name;
- this.location = location;
- elementType = canvasItem;
- }
-
- public String getUniqueId() {
- return uniqueId;
- }
-
- public ImmutablePair<Integer, Integer> getLocation() {
- return location;
- }
-
- public void setLocation(ImmutablePair<Integer, Integer> location) {
- this.location = location;
- }
-
- public LeftPanelCanvasItems getNormativeElementType() {
- return normativeElementType;
- }
-
- public String getElementType() {
- return elementType;
- }
-}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/CanvasManager.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/CanvasManager.java
deleted file mode 100644
index d5c76d1ef1..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/CanvasManager.java
+++ /dev/null
@@ -1,250 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 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.assertNotNull;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Random;
-import java.util.UUID;
-import java.util.stream.Collectors;
-
-import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.LeftPanelCanvasItems;
-import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest;
-import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils;
-import org.openecomp.sdc.ci.tests.verificator.VfVerificator;
-import org.openecomp.sdc.common.api.ArtifactTypeEnum;
-import org.openqa.selenium.By;
-import org.openqa.selenium.StaleElementReferenceException;
-import org.openqa.selenium.WebElement;
-import org.openqa.selenium.interactions.Actions;
-import org.testng.Assert;
-
-import com.relevantcodes.extentreports.LogStatus;
-
-public final class CanvasManager {
- private static final String LEFT_PANEL_ELEMENT_NAME_PREFIX = "leftbar-section-content-item-";
- 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());
- canvas = GeneralUIUtils.waitForClassNameVisibility("w-sdc-designer-canvas");
- 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)
- throws Exception {
- 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 moveToFreeLocation(String containerName) {
- int maxWait = 5000;
- int sumOfWaiting = 0;
- int napPeriod = 200;
- boolean isKeepWaiting = false;
- while (!isKeepWaiting) {
- ImmutablePair<Integer, Integer> freePosition = getFreePosition();
- actions.moveToElement(canvas, freePosition.left, freePosition.right);
- actions.clickAndHold();
- actions.release();
- actions.perform();
- GeneralUIUtils.sleep(napPeriod);
- isKeepWaiting = GeneralUIUtils.getWebElementWaitForVisible("selectedCompTitle").getText()
- .equals(containerName);
- sumOfWaiting += napPeriod;
- if (sumOfWaiting > maxWait) {
- Assert.fail("Can't click on VF");
- }
- }
- }
-
- public void clickOnCanvaElement(CanvasElement canvasElement) {
- actions.moveToElement(canvas, canvasElement.getLocation().left, canvasElement.getLocation().right);
- actions.clickAndHold();
- actions.release();
- actions.perform();
- }
-
- public void moveElementOnCanvas(CanvasElement canvasElement) throws Exception {
- moveElementOnCanvas(canvasElement, getFreePosition());
- }
-
- public void deleteElementFromCanvas(CanvasElement canvasElement) throws Exception {
- GeneralUIUtils.waitForLoader();
- actions.moveToElement(canvas, canvasElement.getLocation().left, canvasElement.getLocation().right);
- actions.click();
- actions.perform();
- GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.GeneralCanvasItems.DELETE_INSTANCE_BUTTON.getValue())
- .click();
- GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.ModalItems.OK.getValue()).click();
- canvasElements.remove(canvasElement.getUniqueId());
- GeneralUIUtils.waitForLoader();
- }
-
- private WebElement findClickElement(String dataTestId) {
- int attempts = 0;
- while (attempts < 2) {
- try {
- return GeneralUIUtils.getWebElementWaitForVisible(dataTestId);
- } catch (StaleElementReferenceException e) {
- }
- attempts++;
- }
- return null;
- }
-
- public CanvasElement createElementOnCanvas(String elementName) throws Exception {
- final String elementDataTestId = LEFT_PANEL_ELEMENT_NAME_PREFIX + elementName;
- try {
- WebElement element = findClickElement(elementDataTestId);
- ImmutablePair<Integer, Integer> freePosition = getFreePosition();
- actions.moveToElement(element, 0, 0);
- actions.clickAndHold();
- actions.moveToElement(canvas, freePosition.left, freePosition.right);
- actions.release();
- actions.perform();
- GeneralUIUtils.waitForLoader();
- String uniqueId = elementDataTestId + "_" + UUID.randomUUID().toString();
- CanvasElement canvasElement = new CanvasElement(uniqueId, freePosition, elementDataTestId);
- addCanvasElement(canvasElement);
- SetupCDTest.getExtendTest().log(LogStatus.PASS,
- String.format("element %s is in canvas now..", elementName));
- return canvasElement;
- } catch (Exception e) {
- System.out.println("Can't create element on canvas");
- e.printStackTrace();
- }
- return null;
- }
-
- public CanvasElement createElementOnCanvas(LeftPanelCanvasItems canvasItem) throws Exception {
- return createElementOnCanvas(canvasItem.getValue());
- }
-
- private ImmutablePair<Integer, Integer> getFreePosition() {
- 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);
- }
-
- public void linkElements(CanvasElement firstElement, CanvasElement secondElement) throws Exception {
- drawSimpleLink(firstElement, secondElement);
- selectReqAndCapAndConnect();
- }
-
- private void selectReqAndCapAndConnect() throws Exception {
- // Select First Cap
- GeneralUIUtils.getWebElementsListByDataTestId(DataTestIdEnum.LinkMenuItems.LINK_ITEM_CAP.getValue()).get(0)
- .click();
- // Select First Req
- GeneralUIUtils.getWebElementsListByDataTestId(DataTestIdEnum.LinkMenuItems.LINK_ITEM_REQ.getValue()).get(0)
- .click();
- // Connect
- GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.LinkMenuItems.CONNECT_BUTTON.getValue()).click();
-
- GeneralUIUtils.waitForLoader();
- }
-
- private void drawSimpleLink(CanvasElement firstElement, CanvasElement secondElement) throws Exception {
- int yOffset = CANVAS_ELEMENT_Y_OFFSET;
- int xOffset = CANVAS_ELEMENT_X_OFFSET;
-
- actions.moveToElement(canvas, firstElement.getLocation().left + xOffset, firstElement.getLocation().right - yOffset);
- actions.clickAndHold();
- actions.moveToElement(canvas, secondElement.getLocation().left + xOffset, secondElement.getLocation().right - yOffset);
- actions.release();
- actions.perform();
- GeneralUIUtils.ultimateWait();
- SetupCDTest.getExtendTest().log(LogStatus.INFO, String.format("Elements %s and %s now connected", firstElement.getElementType().split("-")[4], secondElement.getElementType().split("-")[4]));
- }
-
- public String updateElementNameInCanvas(CanvasElement canvasElement, String newInstanceName) throws Exception {
- GeneralUIUtils.waitForLoader();
- actions.moveToElement(canvas, canvasElement.getLocation().left, canvasElement.getLocation().right);
- actions.click();
- actions.perform();
- WebElement updateInstanceName = GeneralUIUtils.getDriver().findElement(By.id("editPencil"));
- updateInstanceName.click();
- WebElement instanceNameField = GeneralUIUtils
- .getWebElementWaitForVisible(DataTestIdEnum.GeneralCanvasItems.INSTANCE_NAME_FIELD.getValue());
- String oldInstanceName = instanceNameField.getText();
- instanceNameField.clear();
- instanceNameField.sendKeys(newInstanceName);
- GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.ModalItems.OK.getValue()).click();
- GeneralUIUtils.waitForLoader();
- return oldInstanceName;
- }
-}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/CheckBoxStatusEnum.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/CheckBoxStatusEnum.java
deleted file mode 100644
index ffa17ee607..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/CheckBoxStatusEnum.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.datatypes;
-
-public enum CheckBoxStatusEnum {
- CHECKOUT("", "checkbox-checkout"),
- CHECKIN("", "checkbox-checkin"),
- READY_FOR_TESTING("checkbox-readyfortesting","checkbox-1"),
- IN_TESTING("checkbox-intesting", "checkbox-2"),
- WAITING_FOR_DISTRIBUTION("", "checkbox-waitingforapproval"),
- DISTRIBUTION_REJECTED("", "checkbox-distributionrejected"),
- DISTRIBUTION_APPROVED("", "checkbox-distributionapproved"),
- CERTIFIED("checkbox-certified", "checkbox-3"),
- DISTRIBUTED("", "checkbox-4"),
- IN_DESIGN("", "checkbox-0");
-
- private String value;
- private String value2;
-
- public String getValue() {
- return value;
- }
-
- public String getCatalogValue() {
- return value2;
- }
-
- private CheckBoxStatusEnum(String value, String value2) {
- this.value = value;
- this.value2 = value2;
- }
-}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/CreateAndImportButtonsEnum.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/CreateAndImportButtonsEnum.java
deleted file mode 100644
index a49c5024a6..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/CreateAndImportButtonsEnum.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.ci.tests.datatypes;
-
-public enum CreateAndImportButtonsEnum {
-
- IMPORT_VF, IMPORT_VFC, IMPORT_CP, IMPORT_VL, CREATE_VF, CREATE_SERVICE, CREATE_PRODUCT;
-
-}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/CreateAndUpdateStepsEnum.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/CreateAndUpdateStepsEnum.java
deleted file mode 100644
index ffa7400338..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/CreateAndUpdateStepsEnum.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;
-
-// public enum CreateAndUpdateStepsEnum {
-// GENERAL("Generalstep"),
-// ICON("Iconstep"),
-// DEPLOYMENT_ARTIFACT("Deployment Artifactstep"),
-// INFORMATION_ARTIFACT("Information Artifactstep"),
-// PROPERTIES("Propertiesstep"),
-// COMPOSITION("Compositionstep"),
-// ACTIVITY_LOG("Activity Logstep"),
-// DEPLOYMENT_VIEW("Deploymentstep");
-//
-//
-// private String value;
-//
-// public String getValue(){
-// return value;
-// }
-//
-// private CreateAndUpdateStepsEnum(String value) {
-// this.value = value;
-// }
-//
-//
-// }
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
deleted file mode 100644
index 16593fc62f..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/DataTestIdEnum.java
+++ /dev/null
@@ -1,380 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 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 final class DataTestIdEnum {
- private DataTestIdEnum() {
- };
-
- 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");
-
- private String value;
-
- public String getValue() {
- return value;
- }
-
- private LifeCyleChangeButtons(String value) {
- this.value = value;
- }
- }
-
- public enum DistributionChangeButtons {
- APPROVE("approve"), REJECT("reject"),
- DISTRIBUTE("distribute"),
- MONITOR("monitor"),
- APPROVE_MESSAGE("checkindialog"),
- RE_DISTRIBUTE("redistribute");
-
- private String value;
-
- public String getValue() {
- return value;
- }
-
- private DistributionChangeButtons(String value) {
- this.value = value;
- }
- }
-
- public enum InformationalArtifacts {
- CLOUD_QUESTIONNAIRE("Cloud Questionnaire (completed)"),
- FEATURES("Features"),
- VENDOR_TEST_RESULT("Vendor Test Result"),
- TEST_SCRIPTS("Test Scripts"),
- RESOURCE_SECURITY_TEMPLATE("Resource Security Template"),
- HEAT_TEMPLATE_FROM_VENDOR("HEAT Template from Vendor"),
- CAPACITY("Capacity");
-
- private String value;
-
- public String getValue() {
- return value;
- }
-
- private InformationalArtifacts(String value) {
- this.value = value;
- }
-
- }
-
- public enum ModalItems {
- BROWSE_BUTTON("browseButton"),
- ADD("Add"),
- DESCRIPTION("description"),
- SUMBIT_FOR_TESTING_MESSAGE("changeLifeCycleMessage"),
- OK("OK"),
- CANCEL("Cancel"),
- ACCEP_TESTING_MESSAGE("checkindialog");
-
- private String value;
-
- public String getValue() {
- return value;
- }
-
- private ModalItems(String value) {
- this.value = value;
- }
- }
-
- public enum LeftPanelCanvasItems {
- BLOCK_STORAGE("BlockStorage"),
- CINDER_VOLUME("CinderVolume"),
- COMPUTE("Compute"),
- LOAD_BALANCER("LoadBalancer"),
- NOVA_SERVER("NovaServer"),
- OBJECT_STORAGE("ObjectStorage"),
- NEUTRON_PORT("NeutronPort"),
- PORT("Port"),
- DATABASE("Database");
-
- private String value;
-
- public String getValue() {
- return value;
- }
-
- private LeftPanelCanvasItems(String value) {
- this.value = value;
- }
- }
-
- public enum LinkMenuItems {
- CANCEL_BUTTON("link-menu-button-cancel"),
- CONNECT_BUTTON("link-menu-button-connect"),
- LINK_ITEM_CAP("link-item-capabilities"),
- LINK_ITEM_REQ("link-item-requirements"),
- LINK_MENU("link-menu-open");
-
- private String value;
-
- public String getValue() {
- return value;
- }
-
- private LinkMenuItems(String value) {
- this.value = value;
- }
- }
-
- public enum GeneralCanvasItems {
- CANVAS("canvas"),
- CANVAS_RIGHT_PANEL("w-sdc-designer-sidebar-head"),
- DELETE_INSTANCE_BUTTON("e-sdc-small-icon-delete"),
- UPDATE_INSTANCE_NAME("e-sdc-small-icon-update"),
- INSTANCE_NAME_FIELD("instanceName");
-
- private String value;
-
- public String getValue() {
- return value;
- }
-
- private GeneralCanvasItems(String value) {
- this.value = value;
- }
-
- }
-
- public enum ResourceMetadataEnum {
- RESOURCE_NAME("name"),
- DESCRIPTION("description"),
- CATEGORY("selectGeneralCategory"),
- VENDOR_NAME("vendorName"),
- VENDOR_RELEASE("vendorRelease"),
- TAGS("i-sdc-tag-input"),
- CONTACT_ID("contactId"),
- ICON(" iconBox");
-
- private String value;
-
- public String getValue() {
- return value;
- }
-
- private ResourceMetadataEnum(String value) {
- this.value = value;
- }
-
- }
-
- public enum GeneralElementsEnum {
- CREATE_BUTTON("create/save"),
- CHECKIN_BUTTON("check_in"),
- SUBMIT_FOR_TESTING_BUTTON("submit_for_testing"),
- DELETE_VERSION_BUTTON("delete_version"),
- REVERT_BUTTON("revert"),
- LIFECYCLE_STATE("lifecyclestate"),
- VERSION_HEADER("versionHeader");
-
- private String value;
-
- public String getValue() {
- return value;
- }
-
- private GeneralElementsEnum(String value) {
- this.value = value;
- }
-
- }
-
- public enum ArtifactPageEnum {
-
- ADD_INFORMATIONAL_ARTIFACT("add-information-artifact-button"),
- ADD_DEPLOYMENT_ARTIFACT("add-deployment-artifact-button"),
- ADD_ANOTHER_ARTIFACT("add-another-artifact-button"),
- EDIT_ARTIFACT("edit_"),
- DELETE_ARTIFACT("delete_"),
- DOWNLOAD_ARTIFACT("download_"),
- GET_DEPLOYMENT_ARTIFACT_DESCRIPTION("description"),
- GET_INFORMATIONAL_ARTIFACT_DESCRIPTION("Description")
-
- ;
- private String value;
-
- public String getValue() {
- return value;
- }
-
- private ArtifactPageEnum(String value) {
- this.value = value;
- }
- }
-
- public enum PropertiesPageEnum {
-
- ADD_NEW_PROPERTY("addGrey"),
- EDIT_PROPERTY("edit_"),
- DELETE_PROPERTY("delete_"),
- PROPERTY_NAME("propertyName"),
- PROPERTY_VALUE("defaultvalue"),
- PROPERTY_DESCRIPTION("description"),
- PROPERTY_TYPE("propertyType"),
- ADD("Add"),
- CANCEL("Cancel"),
- DONE("Done"),
- PROPERTY_ROW("propertyRow"),
- SAVE("Save");
-
- private String value;
-
- public String getValue() {
- return value;
- }
-
- private PropertiesPageEnum(String value) {
- this.value = value;
- }
- }
-
- public enum MainMenuButtons {
- HOME_BUTTON("main-menu-button-home"),
- CATALOG_BUTTON("main-menu-button-catalog"),
- ONBOARD_BUTTON("main-menu-button-onboard");
-
- private String value;
-
- public String getValue() {
- return value;
- }
-
- private MainMenuButtons(String value) {
- this.value = value;
- }
-
- }
-
- public enum MenuOptionsEnum {
- EDIT("Edit"),
- CHECK_IN("Check in"),
- CHECK_OUT("Check out"),
- VIEW("View"),
- SUBMIT_FOR_TEST("Submit For Test"),
- ACCEPT("Accept"),
- REJECT("Reject"),
- START_TEST("Start test"),
- DISTREBUTE("Distribute");
-
- private String value;
-
- public String getValue() {
- return value;
- }
-
- private MenuOptionsEnum(String value) {
- this.value = value;
- }
- }
-
- public enum StepsEnum {
- GENERAL("Generalstep"),
- ICON("Iconstep"),
- DEPLOYMENT_ARTIFACT("Deployment Artifactstep"),
- INFORMATION_ARTIFACT("Information Artifactstep"),
- PROPERTIES("Propertiesstep"),
- COMPOSITION("Compositionstep"),
- ACTIVITY_LOG("Activity Logstep"),
- DEPLOYMENT_VIEW("Deploymentstep"),
- TOSCA_ARTIFACTS("TOSCA Artifactsstep"),
- MONITOR("Monitor step");
-
- private String value;
-
- public String getValue() {
- return value;
- }
-
- private StepsEnum(String value) {
- this.value = value;
- }
-
- }
-
- public enum ArtifactPopup {
-
- BROWSE("browseButton"),
- ARTIFACT_DESCRIPTION("description"),
- ARTIFACT_LABEL("selectArtifact"),
- ARTIFACT_TYPE("artifacttype"),
- ADD_BUTTON("Add"),
- CANCEL_BUTTON("Cancel"),
- UPDATE_BUTTON("Update");
-
- private String value;
-
- public String getValue() {
- return value;
- }
-
- private ArtifactPopup(String value) {
- this.value = value;
- }
-
- }
-
- public enum ServiceMetadataEnum {
- SERVICE_NAME("name"),
- DESCRIPTION("description"),
- CATEGORY("selectGeneralCategory"),
- PROJECT_CODE("projectCode"),
- TAGS("i-sdc-tag-input"),
- CONTACT_ID("contactId"),
- ICON(" iconBox");
-
- private String value;
-
- public String getValue() {
- return value;
- }
-
- private ServiceMetadataEnum(String value) {
- this.value = value;
- }
-
- }
-
-}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/LifeCycleStateEnum.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/LifeCycleStateEnum.java
deleted file mode 100644
index 29274179d1..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/LifeCycleStateEnum.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;
-
-public enum LifeCycleStateEnum {
-
- CHECKOUT("IN DESIGN CHECK OUT"),
- CHECKIN("IN DESIGN CHECK IN"),
- READY_FOR_TESTING("READY FOR TESTING"),
- IN_TESTING("IN TESTING"),
- WAITING_FOR_DISTRIBUTION("WAITING FOR DISTRIBUTION"),
- DISTRIBUTION_REJECTED("DISTRIBUTION REJECTED"),
- DISTRIBUTION_APPROVED("DISTRIBUTION APPROVED"),
- CERTIFIED("CERTIFIED"),
- DISTRIBUTED("DISTRIBUTED");
-
- private String value;
- private String value2;
-
- public String getValue() {
- return value;
- }
-
- private LifeCycleStateEnum(String value) {
- this.value = value;
- }
-
-}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/MenuOptionsEnum.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/MenuOptionsEnum.java
deleted file mode 100644
index d23ab18f10..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/MenuOptionsEnum.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;
-
-public enum MenuOptionsEnum {
-
- EDIT("Edit"),
- CHECK_IN("Check in"),
- CHECK_OUT("Check out"),
- VIEW("View"),
- SUBMIT_FOR_TEST("Submit For Test"),
- ACCEPT("Accept"),
- REJECT("Reject"),
- START_TEST("Start test"),
- DISTREBUTE("Distribute");
-
- private String value;
-
- public String getValue() {
- return value;
- }
-
- private MenuOptionsEnum(String value) {
- this.value = value;
- }
-
-}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceCategoriesNameEnum.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceCategoriesNameEnum.java
deleted file mode 100644
index 921493f932..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceCategoriesNameEnum.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.datatypes;
-
-public enum ResourceCategoriesNameEnum {
-
- GENERIC("checkbox-resourcenewcategory.generic"),
- NETWORK_CONNECTIVITY("checkbox-resourcenewcategory.networkconnectivity"),
- NETWORK_ELEMENTS("checkbox-resourcenewcategory.generic.networkelements"),
- ABSTRACT("checkbox-resourcenewcategory.generic.abstract"),
- DATABASE_GENERIC("checkbox-resourcenewcategory.generic.database"),
- INFRASTRUCTURE("checkbox-resourcenewcategory.generic.infrastructure"),
- VIRTUAL_LINKS("checkbox-resourcenewcategory.networkconnectivity.virtuallinks"),
- CONNECTION_POINTS("checkbox-resourcenewcategory.networkconnectivity.connectionpoints"),
- NETWORKL4("checkbox-resourcenewcategory.networkl4+"),
- COMMON_NETWORK_RESOURCES("checkbox-resourcenewcategory.networkl4+.commonnetworkresources"),
- APPLICATIONL4("checkbox-resourcenewcategory.applicationl4+"),
- WEB_SERVER("checkbox-resourcenewcategory.applicationl4+.webserver"),
- APPLICATION_SERVER("checkbox-resourcenewcategory.applicationl4+.applicationserver"),
- CALL_CONTROL("checkbox-resourcenewcategory.applicationl4+.callcontrol"),
- BORDER_ELEMENT("checkbox-resourcenewcategory.applicationl4+.borderelement"),
- MEDIA_SERVERS("checkbox-resourcenewcategory.applicationl4+.mediaservers"),
- DATABASE("checkbox-resourcenewcategory.applicationl4+.database"),
- FIREWALL("checkbox-resourcenewcategory.applicationl4+.firewall"),
- LOAD_BALANCER("checkbox-resourcenewcategory.applicationl4+.loadbalancer"),
- NETWORK_L23("checkbox-resourcenewcategory.networkl2-3"),
- Router("checkbox-resourcenewcategory.networkl2-3.router"),
- WAN_Connectors("checkbox-resourcenewcategory.networkl2-3.wanconnectors"),
- LAN_CONNECTORS("checkbox-resourcenewcategory.networkl2-3.lanconnectors"),
- GATEWAY("checkbox-resourcenewcategory.networkl2-3.gateway"),
- INFRASTRUCTUREL23("checkbox-resourcenewcategory.networkl2-3.infrastructure");
-
-
- private String value;
-
- public String getValue(){
- return value;
- }
-
- private ResourceCategoriesNameEnum(String value) {
- this.value = value;
- }
-
-
-}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceCategoriesNameEnum.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceCategoriesNameEnum.java
deleted file mode 100644
index d39bba5594..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceCategoriesNameEnum.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.datatypes;
-
-public enum ServiceCategoriesNameEnum {
-
- NETWORK_L13("checkbox-servicenewcategory.networkl1-3"),
- VOIPCALL_CONTROL("checkbox-servicenewcategory.voipcallcontrol"),
- NETWORKL4("checkbox-servicenewcategory.networkl4+"),
- MOBILITY("checkbox-servicenewcategory.mobility");
-
- private String value;
-
- public String getValue() {
- return value;
- }
-
- private ServiceCategoriesNameEnum(String value) {
- this.value = value;
- }
-}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/UserCredentials.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/UserCredentials.java
deleted file mode 100644
index 870d2879bb..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/UserCredentials.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 org.openecomp.sdc.be.model.User;
-
-public class UserCredentials extends User {
-
- // private String userName;
- private String password;
-
- public UserCredentials(String userId, String password, String firstname, String lastname) {
- super();
- setUserId(userId);
- // this.userName = userName;
- this.password = password;
- setFirstName(firstname);
- setLastName(lastname);
- }
-
- public UserCredentials() {
- super();
- }
-
- // public String getUserName() {
- // return userName;
- // }
- // public void setUserName(String userName) {
- // this.userName = userName;
- // }
- public String getPassword() {
- return password;
- }
-
- public void setPassword(String password) {
- this.password = password;
- }
-
-}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/WorkMode.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/WorkMode.java
deleted file mode 100644
index 199fa6990a..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/WorkMode.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.datatypes;
-
-public enum WorkMode {
- DEV, CD;
-}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/environmentLocal b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/environmentLocal
deleted file mode 100644
index ea93ddfe85..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/environmentLocal
+++ /dev/null
@@ -1,10 +0,0 @@
-//URL designer
-urlDesigner=http://172.20.43.136:8080/sdc1/proxy-designer1#/dashboard
-//URL tester
-urlTester=http://172.20.43.136:8080/sdc1/proxy-tester1
-//URL Vagrant
-urlDesignerVagrant=http://localhost:8181/sdc1/proxy-designer1#/dashboard
-//UrlStaging
-UrlStaging=https://www.e-access.att.com/sdcpstage/sdc1/portal#/dashboard
-//UrlAdmin
-UrlAdmin=http://172.20.43.136:8080/sdc1/proxy-admin1#/adminDashboard \ No newline at end of file
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/adminworkspace/AdminUserManagment.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/adminworkspace/AdminUserManagment.java
deleted file mode 100644
index 19a0d6414f..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/adminworkspace/AdminUserManagment.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.execute.adminworkspace;
-
-import java.util.Collection;
-import java.util.Collections;
-import java.util.List;
-
-import javax.validation.constraints.AssertTrue;
-
-import org.junit.rules.TestName;
-import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
-import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest;
-import org.openecomp.sdc.ci.tests.utilities.AdminWorkspaceUIUtilies;
-import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils;
-import org.openecomp.sdc.ci.tests.utilities.ResourceUIUtils;
-import org.openqa.selenium.WebDriver;
-import org.openqa.selenium.WebElement;
-import org.testng.Assert;
-import org.testng.annotations.Test;
-
-import com.google.common.collect.Ordering;
-
-public class AdminUserManagment extends SetupCDTest {
- //
- // public AdminUserManagment() {
- // super(new TestName(), AdminUserManagment.class.getName());
- // }
-
- private WebDriver driver = GeneralUIUtils.getDriver();
-
- // Create new USER_ID user
- @Test
- public void creatUserIdNewUserTest() throws Exception {
- String userId = AdminWorkspaceUIUtilies.defineNewUserId("th0695");
- String role = AdminWorkspaceUIUtilies.selectUserRole("designer");
- AdminWorkspaceUIUtilies.deleteuser(userId);
- GeneralUIUtils.getWebButton("creategreen").click();
- AdminWorkspaceUIUtilies.typeToSearchBox(userId);
- String createdUserUserId = GeneralUIUtils.getWebElementWaitForVisible("tdUSER_ID").getText();
- userId.equals(createdUserUserId);
- GeneralUIUtils.getWebElementWaitForVisible("tdLast Active").getText().equals("Waiting");
- GeneralUIUtils.getWebElementWaitForVisible("tdRole").getText().equals(role);
- AdminWorkspaceUIUtilies.deleteuser(userId);
-
- }
-
- // Create new MacId user
- @Test
- public void creatMacIdNewUserTest() throws Exception {
-
- String macId = AdminWorkspaceUIUtilies.defineNewUserId("m12345");
- String role = AdminWorkspaceUIUtilies.selectUserRole("designer");
- AdminWorkspaceUIUtilies.deleteuser(macId);
- GeneralUIUtils.getWebButton("creategreen").click();
- AdminWorkspaceUIUtilies.typeToSearchBox(macId);
- String createdUserUserId = GeneralUIUtils.getWebElementWaitForVisible("tdUSER_ID").getText();
- macId.equals(createdUserUserId);
- GeneralUIUtils.getWebElementWaitForVisible("tdLast Active").getText().equals("Waiting");
- GeneralUIUtils.getWebElementWaitForVisible("tdRole").getText().equals(role);
- AdminWorkspaceUIUtilies.deleteuser(macId);
- }
-
- // Create exist user and get error already exist .
- @Test
- public void createxistUserTest() throws Exception {
- String userId = AdminWorkspaceUIUtilies.defineNewUserId("th0695");
- String role = AdminWorkspaceUIUtilies.selectUserRole("designer");
- AdminWorkspaceUIUtilies.deleteuser(userId);
- GeneralUIUtils.getWebButton("creategreen").click();
- AdminWorkspaceUIUtilies.defineNewUserId(userId);
- AdminWorkspaceUIUtilies.selectUserRole("admin");
- GeneralUIUtils.getWebButton("creategreen").click();
- ResourceUIUtils.getErrorMessageText("w-sdc-modal-body-content")
- .equals("User with '" + userId + "' ID already exists.");
- GeneralUIUtils.clickOkButton();
- AdminWorkspaceUIUtilies.deleteuser(userId);
-
- }
-
- // enter Special chars and the create button disabled.
- @Test
- public void insertSpacialcharsTest() throws Exception {
- AdminWorkspaceUIUtilies.defineNewUserId("!@DER%");
- AdminWorkspaceUIUtilies.selectUserRole("designer");
- WebElement createbutton = GeneralUIUtils.getWebElementWaitForVisible("creategreen");
- Assert.assertFalse(createbutton.isEnabled());
- }
-
- // enter invalid macid and create button shall be disabled.
- @Test
- public void insertInvalidUserMacidTest() throws Exception {
- AdminWorkspaceUIUtilies.defineNewUserId("k12345");
- AdminWorkspaceUIUtilies.selectUserRole("designer");
- WebElement createbutton = GeneralUIUtils.getWebElementWaitForVisible("creategreen");
- Assert.assertFalse(createbutton.isEnabled());
- }
-
- // enter invalid userId and create button shall be disabled.
- @Test
- public void insertInvalidUserUserIdTest() throws Exception {
- AdminWorkspaceUIUtilies.defineNewUserId("ac1c23");
- AdminWorkspaceUIUtilies.selectUserRole("designer");
- WebElement createbutton = GeneralUIUtils.getWebElementWaitForVisible("creategreen");
- Assert.assertFalse(createbutton.isEnabled());
- }
-
- // display users list and sort by column name.
- @Test
- public void displayuserslistandsorting() throws Exception {
- GeneralUIUtils.getWebElementWaitForVisible("thFirst Name").click();
- Collection<WebElement> usersFname = GeneralUIUtils.getWebElements("tdFirst Name");
- for (WebElement webElement : usersFname) {
- System.out.println(webElement.getText());
- }
- }
-
- @Override
- protected UserRoleEnum getRole() {
- return UserRoleEnum.ADMIN;
- }
-
-}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resourceui/CatalogLeftFilterPanelCheckBoxTest.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resourceui/CatalogLeftFilterPanelCheckBoxTest.java
deleted file mode 100644
index 39755a9db8..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resourceui/CatalogLeftFilterPanelCheckBoxTest.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.execute.resourceui;
-
-import static org.testng.AssertJUnit.assertTrue;
-
-import java.io.FileWriter;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.openecomp.sdc.ci.tests.datatypes.BreadCrumbsButtonsEnum;
-import org.openecomp.sdc.ci.tests.datatypes.CatalogFilterTitlesEnum;
-import org.openecomp.sdc.ci.tests.datatypes.CheckBoxStatusEnum;
-import org.openecomp.sdc.ci.tests.datatypes.CreateAndImportButtonsEnum;
-import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
-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.utilities.CatalogUIUtilitis;
-import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils;
-import org.openecomp.sdc.ci.tests.utilities.ResourceUIUtils;
-import org.openecomp.sdc.ci.tests.utilities.RestCDUtils;
-import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
-import org.openqa.selenium.By;
-import org.openqa.selenium.WebElement;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-public class CatalogLeftFilterPanelCheckBoxTest extends SetupCDTest {
-
- public CatalogLeftFilterPanelCheckBoxTest() {
- // TODO Auto-generated constructor stub
- }
-
- private ResourceReqDetails resourceDetails;
- FileWriter filwriter = GeneralUIUtils.InitializeprintToTxt("CatalogLeftFilterPanelCheckBoxTest");
-
- @BeforeMethod
- public void beforTest() {
- resourceDetails = ElementFactory.getDefaultResource();
- }
-
- // filter by Type Resource in catalog
- @Test
- public void filterByAssetTypeResource() throws Exception {
- List<WebElement> elements = null;
- List<String> validValues = Arrays.asList("VF", "VL", "CP", "VFC");
- GeneralUIUtils.checkIn();
- GeneralUIUtils.clickBreadCrumbs(BreadCrumbsButtonsEnum.CATALOG);
- GeneralUIUtils.catalogFilterTypeChecBox(TypesEnum.RESOURCE);
- GeneralUIUtils.getWorkspaceElements();
- elements = GeneralUIUtils.waitForElementsListVisibilityTestMethod("asset-type");
- for (WebElement webElement : elements) {
- assertTrue(validValues.contains(webElement.getAttribute("class")));
- }
- }
-
- @Test
- public void filterByResourceTypeVF() throws Exception {
- List<WebElement> elements = null;
- List<String> validValues = Arrays.asList("VF");
- GeneralUIUtils.checkIn();
- GeneralUIUtils.clickBreadCrumbs(BreadCrumbsButtonsEnum.CATALOG);
- GeneralUIUtils.catalogFilterTypeChecBox(TypesEnum.VF);
- GeneralUIUtils.getWorkspaceElements();
- elements = GeneralUIUtils.waitForElementsListVisibilityTestMethod("asset-type");
- for (WebElement webElement : elements) {
- assertTrue(validValues.contains(webElement.getAttribute("class")));
- }
- }
-
- @Test
- public void filterByResourceTypeVFC() throws Exception {
- List<WebElement> elements = null;
- List<String> validValues = Arrays.asList("VFC");
- GeneralUIUtils.checkIn();
- GeneralUIUtils.clickBreadCrumbs(BreadCrumbsButtonsEnum.CATALOG);
- GeneralUIUtils.catalogFilterTypeChecBox(TypesEnum.VFC);
- GeneralUIUtils.getWorkspaceElements();
- elements = GeneralUIUtils.waitForElementsListVisibilityTestMethod("asset-type");
- for (WebElement webElement : elements) {
- assertTrue(validValues.contains(webElement.getAttribute("class")));
- }
- }
-
- @Test
- public void filterByResourceTypeCP() throws Exception {
- List<WebElement> elements = null;
- List<String> validValues = Arrays.asList("CP");
- GeneralUIUtils.checkIn();
- GeneralUIUtils.clickBreadCrumbs(BreadCrumbsButtonsEnum.CATALOG);
- GeneralUIUtils.catalogFilterTypeChecBox(TypesEnum.CP);
- GeneralUIUtils.getWorkspaceElements();
- elements = GeneralUIUtils.waitForElementsListVisibilityTestMethod("asset-type");
- for (WebElement webElement : elements) {
- assertTrue(validValues.contains(webElement.getAttribute("class")));
- }
- }
-
- @Test
- public void filterByResourceTypeVL() throws Exception {
- List<WebElement> elements = null;
- List<String> validValues = Arrays.asList("VL");
- GeneralUIUtils.checkIn();
- GeneralUIUtils.clickBreadCrumbs(BreadCrumbsButtonsEnum.CATALOG);
- GeneralUIUtils.catalogFilterTypeChecBox(TypesEnum.VL);
- GeneralUIUtils.getWorkspaceElements();
- elements = GeneralUIUtils.waitForElementsListVisibilityTestMethod("asset-type");
- for (WebElement webElement : elements) {
- assertTrue(validValues.contains(webElement.getAttribute("class")));
- }
- }
-
- // @Test
- // public void filterByProducTType() throws Exception{
- // List<WebElement> elements = null;
- // List<String> validValues = Arrays.asList("PRODUCT");
- // GeneralUIUtils.checkIn();
- // GeneralUIUtils.clickBreadCrumbs(BreadCrumbsButtonsEnum.CATALOG);
- // GeneralUIUtils.catalogFilterTypeChecBox(TypesEnum.PRODUCT);
- // GeneralUIUtils.getWorkspaceElements();
- // try {
- // elements =
- // GeneralUIUtils.getEelementsByClassName1("w-sdc-dashboard-card-avatar");
- // for (WebElement webElement : elements) {
- // assertTrue(validValues.contains(webElement.findElement(By.xpath(".//*")).getAttribute("class")));
- // }
- // } catch (Exception e) {
- // System.out.println("No Elements founds!");
- // }
- // }
-
- @Test
- public void filterByResourceCategories() throws Exception {
- List<WebElement> elements = null;
- List<String> validValues = null;
- GeneralUIUtils.checkIn();
- GeneralUIUtils.clickBreadCrumbs(BreadCrumbsButtonsEnum.CATALOG);
- Thread.sleep(2000);
- GeneralUIUtils.minimizeCatalogFilterByTitle(CatalogFilterTitlesEnum.TYPE);
- List<String> categories = CatalogUIUtilitis.abcd();
- for (String category : categories) {
- validValues = CatalogUIUtilitis.getAllSubcategoriesByUniqueId(category);
- boolean bool = false;
- try {
- GeneralUIUtils.getWebElementWaitForVisible(category).click();
- bool = true;
- } catch (Exception e) {
- while (!bool) {
- GeneralUIUtils.scrollDown();
- try {
- GeneralUIUtils.getWebElementWaitForVisible(category).click();
- bool = true;
- } catch (Exception e2) {
-
- }
- }
- }
- String checkBox = GeneralUIUtils.getWebElementWaitForVisible(category).findElement(By.xpath(".//input"))
- .getAttribute("class");
- if (checkBox.contains("ng-not-empty") && validValues != null) {
- try {
- GeneralUIUtils.getWorkspaceElements();
- elements = GeneralUIUtils.getEelementsBycontainsClassName("sprite-resource-icons");
- for (WebElement webElement : elements) {
- String elementUniqueId = webElement.getAttribute("data-tests-id");
- if (!validValues.contains(elementUniqueId)) {
- System.out.println("assert error!");
- }
- }
- GeneralUIUtils.getWebElementWaitForVisible(category).click();
- } catch (Exception e) {
- GeneralUIUtils.getWebElementWaitForVisible(category).click();
- System.out.println("No Elements founds!");
- }
- }
- }
- }
-
- @SuppressWarnings("null")
- @Test
- public void filterByStatus() throws Exception {
-
- List<WebElement> elements = null;
- List<String> validValues = null;
- List<ResourceReqDetails> createdComponents = new ArrayList<ResourceReqDetails>();
- List<String> catalogStatuses = Arrays.asList("IN_DESIGN", "READY_FOR_TESTING", "IN_TESTING", "CERTIFIED",
- "DISTRIBUTED");
- GeneralUIUtils.checkIn();
- for (int i = 1; i < catalogStatuses.size() - 1; i++) {
- GeneralUIUtils.sleep(3000);
- GeneralUIUtils.createAndImportButtons(CreateAndImportButtonsEnum.CREATE_VF, GeneralUIUtils.getDriver());
- resourceDetails.setName(getRandomComponentName("ResourceCDTest-"));
- ResourceUIUtils.createResourceInUI(resourceDetails, getUser());
- GeneralUIUtils.clickSubmitForTest();
- if (catalogStatuses.get(i) == "IN_TESTING") {
- GeneralUIUtils.testerUser(true, false, resourceDetails);
- GeneralUIUtils.sleep(3000);
- navigateToUrl(getUrl());
-
- }
- if (catalogStatuses.get(i) == "CERTIFIED") {
- GeneralUIUtils.testerUser(true, true, resourceDetails);
- GeneralUIUtils.sleep(3000);
- navigateToUrl(getUrl());
- }
- if (catalogStatuses.get(i) == "DISTRIBUTED") {
- GeneralUIUtils.testerUser(true, true, resourceDetails);
- GeneralUIUtils.governorUser(false, true, resourceDetails);
- GeneralUIUtils.opsUser(true, false, resourceDetails);
- GeneralUIUtils.sleep(3000);
- navigateToUrl(getUrl());
-
- }
- createdComponents.add(resourceDetails);
- }
- GeneralUIUtils.clickBreadCrumbs(BreadCrumbsButtonsEnum.CATALOG);
- // get filters title close.
- Thread.sleep(2000);
- GeneralUIUtils.minimizeCatalogFilterByTitle(CatalogFilterTitlesEnum.TYPE);
- GeneralUIUtils.minimizeCatalogFilterByTitle(CatalogFilterTitlesEnum.CATEGORIES);
- for (CheckBoxStatusEnum statusEnum : CheckBoxStatusEnum.values()) {
- if (catalogStatuses.contains(statusEnum.name().toString())) {
- validValues = GeneralUIUtils.catalogFilterStatusChecBox(statusEnum);
- if (GeneralUIUtils.getWorkspaceElements().size() > 0) {
- String checkBox = GeneralUIUtils.getWebElementByName(statusEnum.getCatalogValue())
- .getAttribute("class");
- if (checkBox.contains("ng-not-empty") && validValues != null) {
- try {
- elements = GeneralUIUtils.getEelementsBycontainsClassName("w-sdc-dashboard-card-edit");
- for (WebElement webElement : elements) {
- String className = webElement.getAttribute("class");
- String textCategory = className.substring(className.indexOf(" "));
- assertTrue(validValues.contains(textCategory.replace(" ", "")));
- }
- GeneralUIUtils.catalogFilterStatusChecBox(statusEnum);
- } catch (Exception e) {
- GeneralUIUtils.catalogFilterStatusChecBox(statusEnum);
- System.out.println("No Elements founds!");
- }
- }
- } else {
- break;
- }
- }
- }
- }
-
- @Override
- protected UserRoleEnum getRole() {
- return UserRoleEnum.DESIGNER;
- }
-}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resourceui/CatalogSearchBoxTest.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resourceui/CatalogSearchBoxTest.java
deleted file mode 100644
index efdb9532a4..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resourceui/CatalogSearchBoxTest.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.execute.resourceui;
-
-import static org.testng.AssertJUnit.assertTrue;
-
-import java.io.FileWriter;
-import java.util.List;
-
-import org.openecomp.sdc.ci.tests.datatypes.BreadCrumbsButtonsEnum;
-import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.StepsEnum;
-import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
-import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest;
-import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils;
-import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
-import org.openqa.selenium.WebElement;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-public class CatalogSearchBoxTest extends SetupCDTest {
-
- private ResourceReqDetails resourceDetails;
-
- @BeforeMethod
- public void beforTest() {
- resourceDetails = ElementFactory.getDefaultResource();
- }
-
- // search by ResourceName
- @Test
- public void searchResourceInCatalogMenuTest() throws Exception {
- GeneralUIUtils.checkIn();
- GeneralUIUtils.clickBreadCrumbs(BreadCrumbsButtonsEnum.CATALOG);
- GeneralUIUtils.catalogSearchBox(resourceDetails.getName());
- Thread.sleep(500);
- assertTrue(GeneralUIUtils.getWorkspaceElements().size() == 1);
- }
-
- // search by Description
- @Test
- public void searchResourceInCatalogMenuByDescriptionTest() throws Exception {
- GeneralUIUtils.checkIn();
- GeneralUIUtils.clickBreadCrumbs(BreadCrumbsButtonsEnum.CATALOG);
- GeneralUIUtils.catalogSearchBox(resourceDetails.getDescription());
- Thread.sleep(2000);
- List<WebElement> assets = GeneralUIUtils.getWorkspaceElements();
-
- int count = 0;
- for (WebElement webElement : assets) {
- if (count != 0) {
- GeneralUIUtils.catalogSearchBox(resourceDetails.getDescription());
- }
- if (count == 0) {
- webElement.click();
- } else {
- List<WebElement> assets1 = GeneralUIUtils.getWorkspaceElements();
- assets1.get(count).click();
- }
- GeneralUIUtils.getWebElementWaitForVisible("description").getText()
- .equals(resourceDetails.getDescription());
- GeneralUIUtils.clickExitSign();
- Thread.sleep(500);
- count++;
- }
- }
-
- // search by tags
- @Test
- public void searchResourceInCatalogMenuBytagsTest() throws Exception {
- GeneralUIUtils.checkIn();
- GeneralUIUtils.clickBreadCrumbs(BreadCrumbsButtonsEnum.CATALOG);
- GeneralUIUtils.catalogSearchBox(resourceDetails.getTags().get(0));
- Thread.sleep(500);
- GeneralUIUtils.getWorkspaceElements().get(0).click();
- List<WebElement> expectedTagsList = GeneralUIUtils.getWebElements("i-sdc-tag-text");
- for (int i = 0; i < expectedTagsList.size(); i++) {
- expectedTagsList.get(i).equals(resourceDetails.getTags().get(i));
- }
-
- }
-
- // search by Version
- @Test
- public void searchResourceInCatalogMenuByVersionTest() throws Exception {
- GeneralUIUtils.checkIn();
- GeneralUIUtils.clickBreadCrumbs(BreadCrumbsButtonsEnum.CATALOG);
- GeneralUIUtils.catalogSearchBox(resourceDetails.getVersion().replace("V", ""));
- Thread.sleep(500);
- GeneralUIUtils.getWorkspaceElements().get(0).click();
- GeneralUIUtils.getSelectList(null, "versionHeader").getFirstSelectedOption().getText()
- .equals(resourceDetails.getVersion());
- }
-
- // search by SpecialCharacters
- @Test
- public void searchResourceInCatalogMenuBySpecialCharactersTest() throws Exception {
- GeneralUIUtils.moveToStep(StepsEnum.GENERAL);
- GeneralUIUtils.defineDescription(resourceDetails.getDescription() + "!@#$%^&*");
- GeneralUIUtils.checkIn();
- GeneralUIUtils.clickBreadCrumbs(BreadCrumbsButtonsEnum.CATALOG);
- GeneralUIUtils.catalogSearchBox("!@#$%^&*");
- Thread.sleep(500);
- GeneralUIUtils.getWorkspaceElements().get(0).click();
- GeneralUIUtils.getWebElementWaitForVisible("description").getText().equals(resourceDetails.getDescription());
- }
-
- @Override
- protected UserRoleEnum getRole() {
- return UserRoleEnum.DESIGNER;
- }
-}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resourceui/ChangeLifeCycleStatFromCatalogTest.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resourceui/ChangeLifeCycleStatFromCatalogTest.java
deleted file mode 100644
index a75240d2b2..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resourceui/ChangeLifeCycleStatFromCatalogTest.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.resourceui;
-
-import static org.testng.AssertJUnit.assertTrue;
-
-import java.util.List;
-
-import org.openecomp.sdc.ci.tests.datatypes.BreadCrumbsButtonsEnum;
-import org.openecomp.sdc.ci.tests.datatypes.LifeCycleStateEnum;
-import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
-import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest;
-import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils;
-import org.openecomp.sdc.ci.tests.utilities.ResourceUIUtils;
-import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
-import org.openqa.selenium.WebElement;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-public class ChangeLifeCycleStatFromCatalogTest extends SetupCDTest {
-
- public ChangeLifeCycleStatFromCatalogTest() {
- // TODO Auto-generated constructor stub
- }
-
- // This test check the status filter .
-
- private ResourceReqDetails resourceDetails;
-
- @BeforeMethod
- public void beforTest() {
- resourceDetails = ElementFactory.getDefaultResource();
- }
-
- @Test
- public void checkInFromCatalog() throws InterruptedException {
- GeneralUIUtils.clickSaveIcon();
- GeneralUIUtils.clickASDCLogo();
- GeneralUIUtils.clickBreadCrumbs(BreadCrumbsButtonsEnum.CATALOG);
- GeneralUIUtils.catalogSearchBox(resourceDetails.getName());
- List<WebElement> assets = GeneralUIUtils.getWorkspaceElements();
- if (assets.isEmpty()) {
- System.out.println("error elements not found.");
- } else {
- for (WebElement webElement : assets) {
- webElement.click();
- GeneralUIUtils.checkIn();
- GeneralUIUtils.getWebElementWaitForVisible(resourceDetails.getName()).click();
- Thread.sleep(2000);
- System.out.println(ResourceUIUtils.lifeCycleStateUI());
- System.out.println(LifeCycleStateEnum.CHECKIN.getValue());
- assertTrue(ResourceUIUtils.lifeCycleStateUI().contentEquals(LifeCycleStateEnum.CHECKIN.getValue()));
-
- }
- }
-
- }
-
- @Test
- public void checkOutFromCatalog() throws Exception {
- GeneralUIUtils.clickSaveIcon();
- GeneralUIUtils.clickASDCLogo();
- GeneralUIUtils.clickBreadCrumbs(BreadCrumbsButtonsEnum.CATALOG);
- GeneralUIUtils.catalogSearchBox(resourceDetails.getName());
- List<WebElement> assets = GeneralUIUtils.getWorkspaceElements();
- if (assets.isEmpty()) {
- System.out.println("error elements not found.");
- } else {
- for (WebElement webElement : assets) {
- webElement.click();
- GeneralUIUtils.checkinCheckout(resourceDetails.getName());
- assertTrue(ResourceUIUtils.lifeCycleStateUI().contentEquals(LifeCycleStateEnum.CHECKOUT.getValue()));
-
- }
- }
-
- }
-
- @Override
- protected UserRoleEnum getRole() {
- return UserRoleEnum.DESIGNER;
- }
-
-}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resourceui/ImportAssetInUITest.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resourceui/ImportAssetInUITest.java
deleted file mode 100644
index 8e9df40068..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resourceui/ImportAssetInUITest.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.resourceui;
-
-import static org.testng.Assert.assertNotEquals;
-import static org.testng.AssertJUnit.assertTrue;
-
-import java.util.List;
-import java.util.Map;
-
-import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
-import org.openecomp.sdc.ci.tests.datatypes.CreateAndImportButtonsEnum;
-import org.openecomp.sdc.ci.tests.datatypes.LifeCycleStateEnum;
-import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.StepsEnum;
-import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
-import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest;
-import org.openecomp.sdc.ci.tests.utilities.ArtifactUIUtils;
-import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils;
-import org.openecomp.sdc.ci.tests.utilities.ImportAssetUIUtils;
-import org.openecomp.sdc.ci.tests.utilities.PropertiesUIUtils;
-import org.openecomp.sdc.ci.tests.utilities.ResourceUIUtils;
-import org.openecomp.sdc.ci.tests.utilities.RestCDUtils;
-import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
-import org.openqa.selenium.By;
-import org.openqa.selenium.WebElement;
-import org.testng.AssertJUnit;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-public class ImportAssetInUITest extends SetupCDTest {
-
- private ResourceReqDetails resourceDetails;
-
- @BeforeMethod(alwaysRun = true)
- public void inializeBeforeImportTest() {
- GeneralUIUtils.fileName = "JDM_vfc.yml";
- resourceDetails = ElementFactory.getDefaultResource();
- resourceDetails.setResourceType(ResourceTypeEnum.VFC.toString());
- }
-
- @Test
- public void importAssetFillGeneralInfoAndSelectIconTest() throws Exception {
- ResourceUIUtils.importFileWithSendKey(GeneralUIUtils.FILE_PATH, GeneralUIUtils.fileName,
- CreateAndImportButtonsEnum.IMPORT_CP);
- ResourceUIUtils.fillGeneralInfoValuesAndIcon(resourceDetails, getUser());
- GeneralUIUtils.checkIn();
- GeneralUIUtils.getWebElementWaitForVisible(resourceDetails.getName()).click();
- ResourceUIUtils.getVFCGeneralInfoAndValidate(resourceDetails, getUser());
- }
-
- @Test
- public void changeImportedAssetFileTest() throws Exception {
- ImportAssetUIUtils.importAsssetAndFillGeneralInfo(GeneralUIUtils.FILE_PATH, GeneralUIUtils.fileName,
- resourceDetails, getUser(), CreateAndImportButtonsEnum.IMPORT_CP);
- String firstFileName = GeneralUIUtils.getWebElementWaitForVisible("filename").getText();
- AssertJUnit.assertTrue(firstFileName.equals(GeneralUIUtils.fileName));
- String secondFileName = "Valid_tosca_ReplaceTest.yml";
- ResourceUIUtils.importFileWithSendKeyBrowse(GeneralUIUtils.FILE_PATH, secondFileName);
- String secondFileNameFromField = GeneralUIUtils.getWebElementWaitForVisible("filename").getText();
- // assertThat(fileName, not(secondFileNameFromField));
- assertNotEquals(GeneralUIUtils.fileName, secondFileNameFromField);
- }
-
- @Test
- public void duplicateFileTest() throws Exception {
- ResourceUIUtils.importFileWithSendKey(GeneralUIUtils.FILE_PATH, GeneralUIUtils.fileName,
- CreateAndImportButtonsEnum.IMPORT_CP);
- ResourceUIUtils.fillGeneralInfoValuesAndIcon(resourceDetails, getUser());
- String nameofresource = resourceDetails.getName();
- resourceDetails.setName(getRandomComponentName("SecondImportCDTest"));
- GeneralUIUtils.checkIn();
- ImportAssetUIUtils.importAsssetAndFillGeneralInfo(GeneralUIUtils.FILE_PATH, GeneralUIUtils.fileName,
- resourceDetails, getUser(), CreateAndImportButtonsEnum.IMPORT_CP);
- GeneralUIUtils.clickSaveIcon();
- equals(ResourceUIUtils.getErrorMessageText("w-sdc-modal-body-content") == GeneralUIUtils.allReadyExistErro);
- GeneralUIUtils.clickOkButton();
- resourceDetails.setName(nameofresource);
-
- }
-
- @Test
- public void importInvalidFileTest() throws Exception {
- GeneralUIUtils.fileName = "InValid_tosca_File .yml";
- ImportAssetUIUtils.importAsssetAndFillGeneralInfo(GeneralUIUtils.FILE_PATH, GeneralUIUtils.fileName,
- resourceDetails, getUser(), CreateAndImportButtonsEnum.IMPORT_CP);
- GeneralUIUtils.clickSaveIcon();
- equals(ResourceUIUtils.getErrorMessageText("w-sdc-modal-body-content") == GeneralUIUtils.toscaErrorMessage);
- GeneralUIUtils.clickOkButton();
- }
-
- @Test
- public void deleteImportAssetFileTest() throws Exception {
- ImportAssetUIUtils.importAsssetAndFillGeneralInfo(GeneralUIUtils.FILE_PATH, GeneralUIUtils.fileName,
- resourceDetails, getUser(), CreateAndImportButtonsEnum.IMPORT_CP);
- WebElement deleteFileButton = GeneralUIUtils.getDriver()
- .findElement(By.className("i-sdc-form-file-upload-x-btn"));
- deleteFileButton.click();
- WebElement filefield = GeneralUIUtils.getWebElementWaitForVisible("filename");
- AssertJUnit.assertEquals("", filefield.getText());
- }
-
- // Add artifact by Clicking the Place holders button.
- @Test
- public void importAssetAddInformationArtifactPlaceHoldersTest() throws Exception {
- // fileName = "CP_WAN.yml";
- String artifactByname = "placeHolder";
- ImportAssetUIUtils.importAsssetFillGeneralInfoAndSelectIcon(GeneralUIUtils.FILE_PATH, GeneralUIUtils.fileName,
- resourceDetails, getUser(), CreateAndImportButtonsEnum.IMPORT_CP);
- GeneralUIUtils.moveToStep(StepsEnum.INFORMATION_ARTIFACT);
- GeneralUIUtils.getWebElementWaitForVisible("Features");
- List<WebElement> Placholders = GeneralUIUtils.getDriver().findElements(By.className("add-button"));
- for (WebElement element : Placholders) {
- Thread.sleep(500);
- element.click();
- // Placholders.get(4).click();
- System.out.println(element.getText());
- if (element.getText().equalsIgnoreCase("Add Other Artifact")) {
- ArtifactUIUtils.valideArtifact(ArtifactUIUtils.addInformationalArtifact("Create New Artifact"), false);
- } else {
- ArtifactUIUtils.valideArtifact(ArtifactUIUtils.addInformationalArtifact(null), false);
- }
- }
- }
-
- // Add information artifact by Clicking the Add button.
- @Test
- public void importAssetAddInformationArtifactAddButtonTest() throws Exception {
- String type = "Create New Artifact";
- // fileName = "CP_WAN.yml";
- ImportAssetUIUtils.importAsssetFillGeneralInfoAndSelectIcon(GeneralUIUtils.FILE_PATH, GeneralUIUtils.fileName,
- resourceDetails, getUser(), CreateAndImportButtonsEnum.IMPORT_CP);
- GeneralUIUtils.moveToStep(StepsEnum.INFORMATION_ARTIFACT);
- GeneralUIUtils.actionBuild(GeneralUIUtils.getWebButton("add-information-artifact-button")).click();
- ;
- ;
- Map<String, String> expected = ArtifactUIUtils.addInformationalArtifact(type);
- Thread.sleep(1000);
- ResourceUIUtils.scrollDownPage();
- ArtifactUIUtils.valideArtifact(expected, false);
- }
-
- // Add New property String Type.
- @Test
- public void importAssetAddStringPropertyTest() throws Exception {
- WebElement prop = null;
- // fileName = "CP_WAN.yml";
- ImportAssetUIUtils.importAsssetFillGeneralInfoAndSelectIcon(GeneralUIUtils.FILE_PATH, GeneralUIUtils.fileName,
- resourceDetails, getUser(), CreateAndImportButtonsEnum.IMPORT_CP);
- Thread.sleep(500);
- GeneralUIUtils.moveToStep(StepsEnum.PROPERTIES);
- GeneralUIUtils.getEelementBycontainsClassName("data-row");
- GeneralUIUtils.getWebButton("addGrey").click();
- Map<String, String> propertyValues = PropertiesUIUtils.addProperties("String-Property", "string",
- "!This is strig123456@#$%$", "This is description.", null);
- WebElement elementTohover = GeneralUIUtils.getEelementBycontainsClassName("table-arrow");
- GeneralUIUtils.actionBuild(elementTohover).click();
- int counter = 0;
- try {
- prop = GeneralUIUtils.getWebElementWaitForVisible(propertyValues.get("name"));
- } catch (Exception e) {
- ResourceUIUtils.scrollDownPage();
- prop = GeneralUIUtils.getDriver()
- .findElement(By.xpath("//*[@data-tests-id='" + propertyValues.get("name") + "']"));
- } finally {
- if (prop.isDisplayed()) {
- counter++;
- }
- }
- PropertiesUIUtils.vlidateProperties(propertyValues);
- }
-
- // Add New property Integer Type.
- @Test
- public void importAssetAddIntegerPropertyTest() throws Exception {
- WebElement prop;
- // fileName = "CP_WAN.yml";
- ImportAssetUIUtils.importAsssetFillGeneralInfoAndSelectIcon(GeneralUIUtils.FILE_PATH, GeneralUIUtils.fileName,
- resourceDetails, getUser(), CreateAndImportButtonsEnum.IMPORT_CP);
- Thread.sleep(500);
- GeneralUIUtils.moveToStep(StepsEnum.PROPERTIES);
- GeneralUIUtils.getEelementBycontainsClassName("data-row");
- GeneralUIUtils.getWebButton("addGrey").click();
- Map<String, String> propertyValues = PropertiesUIUtils.addProperties("Integer-Property", "integer", "123456",
- "This is description.", null);
- WebElement elementTohover = GeneralUIUtils.getEelementBycontainsClassName("table-arrow");
- GeneralUIUtils.actionBuild(elementTohover);
- int counter = 0;
- prop = GeneralUIUtils.getWebElementWaitForVisible(propertyValues.get("name"));
- if (prop.isDisplayed()) {
- counter++;
- }
- if (counter == 0) {
- ResourceUIUtils.scrollDownPage();
- prop = GeneralUIUtils.getDriver()
- .findElement(By.xpath("//*[@data-tests-id='" + propertyValues.get("name") + "']"));
- counter++;
- }
- PropertiesUIUtils.vlidateProperties(propertyValues);
- }
-
- // Add New property boolean Type.
- @Test
- public void importAssetAddBooleanPropertyTest() throws Exception {
- // fileName = "CP_WAN.yml";
- WebElement prop;
- ImportAssetUIUtils.importAsssetFillGeneralInfoAndSelectIcon(GeneralUIUtils.FILE_PATH, GeneralUIUtils.fileName,
- resourceDetails, getUser(), CreateAndImportButtonsEnum.IMPORT_CP);
- GeneralUIUtils.moveToStep(StepsEnum.PROPERTIES);
- GeneralUIUtils.getEelementBycontainsClassName("data-row");
- GeneralUIUtils.getWebButton("addGrey").click();
- Map<String, String> propertyValues = PropertiesUIUtils.addProperties("Boolean-Property", "boolean", "true",
- "This is boolean description.", null);
- int counter = 0;
- WebElement elementTohover = GeneralUIUtils.getDriver().findElement(By.className("table-arrow"));
- GeneralUIUtils.actionBuild(elementTohover);
- prop = GeneralUIUtils.getDriver()
- .findElement(By.xpath("//*[@data-tests-id='" + propertyValues.get("name") + "']"));
- if (prop.isDisplayed()) {
- counter++;
- }
- if (counter == 0) {
- ResourceUIUtils.scrollDownPage();
- prop = GeneralUIUtils.getDriver()
- .findElement(By.xpath("//*[@data-tests-id='" + propertyValues.get("name") + "']"));
- counter++;
- }
- AssertJUnit.assertEquals(1, counter);
- }
-
- // Add New property float Type.
- @Test
- public void importAssetAddFloatPropertyTest() throws Exception {
- WebElement prop;
- // fileName = "CP_WAN.yml";
- ImportAssetUIUtils.importAsssetFillGeneralInfoAndSelectIcon(GeneralUIUtils.FILE_PATH, GeneralUIUtils.fileName,
- resourceDetails, getUser(), CreateAndImportButtonsEnum.IMPORT_CP);
- GeneralUIUtils.moveToStep(StepsEnum.PROPERTIES);
- GeneralUIUtils.getEelementBycontainsClassName("data-row");
- GeneralUIUtils.getWebButton("addGrey").click();
- Map<String, String> propertyValues = PropertiesUIUtils.addProperties("floatProperty", "float", "22.5",
- "This is description.", null);
- int counter = 0;
- WebElement elementTohover = GeneralUIUtils.getDriver().findElement(By.className("table-arrow"));
- GeneralUIUtils.actionBuild(elementTohover);
- prop = GeneralUIUtils.getDriver()
- .findElement(By.xpath("//*[@data-tests-id='" + propertyValues.get("name") + "']"));
- if (prop.isDisplayed()) {
- counter++;
- }
- if (counter == 0) {
- ResourceUIUtils.scrollDownPage();
- prop = GeneralUIUtils.getDriver()
- .findElement(By.xpath("//*[@data-tests-id='" + propertyValues.get("name") + "']"));
- counter++;
- }
- PropertiesUIUtils.vlidateProperties(propertyValues);
- }
-
- // Edit property.
- @Test
- public void importAssetEditPropertiesTest() throws Exception {
- // fileName = "CP_WAN.yml";
- Map<String, String> expected = null;
- ImportAssetUIUtils.importAsssetFillGeneralInfoAndSelectIcon(GeneralUIUtils.FILE_PATH, GeneralUIUtils.fileName,
- resourceDetails, getUser(), CreateAndImportButtonsEnum.IMPORT_CP);
- GeneralUIUtils.moveToStep(StepsEnum.PROPERTIES);
- GeneralUIUtils.getEelementBycontainsClassName("table-col-general");
- GeneralUIUtils.getWebButton("addGrey").click();
- expected = PropertiesUIUtils.addProperties("BooleanProperty", "boolean", "true", "This is boolean description.",
- null);
- GeneralUIUtils.getWebElement(GeneralUIUtils.getDriver(), "table-edit-btn").click();
- ;
- List<WebElement> properties = GeneralUIUtils.getDriver().findElements(By.xpath("//*[@*='table-edit-btn']"));
- ;
- for (WebElement webElement : properties) {
- webElement.click();
- GeneralUIUtils.defineDescription("This is Property update");
- GeneralUIUtils.getWebButton("Update").click();
- break;
- }
- Thread.sleep(2000);
- GeneralUIUtils.getDriver().findElement(By.xpath("//*[@data-tests-id='BooleanProperty']")).click();
- Thread.sleep(1000);
- String actual = GeneralUIUtils.getDriver()
- .findElement(By.xpath("//*[@class='item-opened ng-binding ng-scope']")).getText();
- assertNotEquals(expected.get("name"), actual);
- // assertThat(expected.get("name"),not(actual));
- }
-
- // **************************************************************************************************
- // change VFC version
-
- // this test return error 500;
- @Test(alwaysRun = false)
- public void importAssetChangeVersionOfVFCTest() throws Exception {
- // fileName = "VFC.yml";
- // resourceDetails.setResourceType(ResourceTypeEnum.VFC.toString());
- ImportAssetUIUtils.importAsssetFillGeneralInfoAndSelectIcon(GeneralUIUtils.FILE_PATH, GeneralUIUtils.fileName,
- resourceDetails, getUser(), CreateAndImportButtonsEnum.IMPORT_CP);
- GeneralUIUtils.clickSaveIcon();
- GeneralUIUtils.checkinCheckout(resourceDetails.getName());
- resourceDetails.setVersion("0.2");
- String version = GeneralUIUtils.getWebElementWaitForVisible("versionHeader").getText();
- version.equals("0.2");
- }
-
- // change VL version
- // this test return error 500;
- @Test
- public void importAssetChangeVersionOfVLTest() throws Exception {
- GeneralUIUtils.fileName = "VL.yml";
- resourceDetails.setResourceType(ResourceTypeEnum.VL.getValue());
- ImportAssetUIUtils.importAsssetFillGeneralInfoAndSelectIcon(GeneralUIUtils.FILE_PATH, GeneralUIUtils.fileName,
- resourceDetails, getUser(), CreateAndImportButtonsEnum.IMPORT_CP);
- GeneralUIUtils.checkinCheckout(resourceDetails.getName());
- resourceDetails.setVersion("0.2");
- String version = GeneralUIUtils.getWebElementWaitForVisible("versionHeader").getText();
- version.equals("0.2");
- }
- // change CP version
-
- @Test
- public void importAssetChangeVersionOfCPTest() throws Exception {
- GeneralUIUtils.fileName = "CP_LAN.yml";
- resourceDetails.setResourceType(ResourceTypeEnum.CP.toString());
- ImportAssetUIUtils.importAsssetFillGeneralInfoAndSelectIcon(GeneralUIUtils.FILE_PATH, GeneralUIUtils.fileName,
- resourceDetails, getUser(), CreateAndImportButtonsEnum.IMPORT_CP);
- GeneralUIUtils.checkinCheckout(resourceDetails.getName());
- resourceDetails.setVersion("0.2");
- String version = GeneralUIUtils.getWebElementWaitForVisible("versionHeader").getText();
- version.equals("0.2");
- }
-
- // @Test
- // public void viewPageActivityLogTest() throws Exception {
- // resourceDetails.setResourceType(ResourceTypeEnum.VF.toString());
- // ImportAssetUIUtils.importAsssetFillGeneralInfoAndSelectIcon(GeneralUIUtils.FILE_PATH,
- // GeneralUIUtils.fileName , resourceDetails, getUser(),
- // CreateAndImportButtonsEnum.IMPORT_CP);
- // ResourceUIUtils.waitToFinishButtonEnabled().click();
- // RestCDUtils.getResource(resourceDetails, getUser());
- // GeneralUIUtils.checkIn();
- // GeneralUIUtils.openObjectMenuAndSelectOption(resourceDetails.getUniqueId(),
- // MenuOptionsEnum.VIEW);
- // ResourceUIUtils.lifeCycleState();
- // Thread.sleep(1000);
- // ViewPageUIUtils.validateActivityLog("Action: Checkin Performed by: Carlos
- // Santana(cs0008) Status: 200");
- // }
-
- // @Test
- // public void downloadArtifactViewPaage() throws Exception {
- // importAssetAddInformationArtifactAddButton();
- // ResourceUIUtils.waitToFinishButtonEnabled().click();
- // ViewPageUIUtils.openDropDownListOfObject(resourceDetails.getName(),
- // ImportAssetUIUtils.getAllObjectsOnWorkspace(GeneralUIUtils.getDriver()),
- // "View",
- // ImportAssetUIUtils.scrollElement(GeneralUIUtils.getDriver()));
- // ValidateViewPageParameters.ViewPagedownloadArtifact();
- // String myheatfile="Heat-File.yaml";
- // //Assert.assertTrue((GeneralUIUtils.FILE_PATH, "mailmerge.xls"), "Failed
- // to download
- // Expected document");
- // String dowloadedfile=
- // "C:\\Git_work\\ASDC\\d2-sdnc\\ui-ci\\src\\main\\resources\\Downloads\\"+fileName+"";
- // int index=dowloadedfile.lastIndexOf("\\");
- // System.out.println(dowloadedfile.substring(index+1));
- // File getLatestFile = getLatestFilefromDir();
- // String fileName = getLatestFile.getName();
- // Assert.assertTrue(fileName.equals("mailmerge.xls"), "Downloaded file name
- // is not matching with expected file name");
- //
- // }
-
- @Test
- public void importAssetcheckInVFCTest() throws Exception {
- ImportAssetUIUtils.importAsssetFillGeneralInfoAndSelectIcon(GeneralUIUtils.FILE_PATH, GeneralUIUtils.fileName,
- resourceDetails, getUser(), CreateAndImportButtonsEnum.IMPORT_CP);
- GeneralUIUtils.clickSaveIcon();
- GeneralUIUtils.checkIn();
- GeneralUIUtils.getWebElementWaitForVisible(resourceDetails.getName()).click();
- assertTrue(ResourceUIUtils.lifeCycleStateUI().contentEquals(LifeCycleStateEnum.CHECKIN.getValue()));
- }
-
- @Test
- public void importAssetcheckOutVFCTest() throws Exception {
- ImportAssetUIUtils.importAsssetFillGeneralInfoAndSelectIcon(GeneralUIUtils.FILE_PATH, GeneralUIUtils.fileName,
- resourceDetails, getUser(), CreateAndImportButtonsEnum.IMPORT_CP);
- GeneralUIUtils.clickSaveIcon();
- GeneralUIUtils.checkinCheckout(resourceDetails.getName());
- GeneralUIUtils.clickASDCLogo();
- GeneralUIUtils.getWebElementWaitForVisible(resourceDetails.getName()).click();
- assertTrue(ResourceUIUtils.lifeCycleStateUI().contentEquals(LifeCycleStateEnum.CHECKOUT.getValue()));
- }
-
- @Test
- public void importAssetDeleteVFCVersionTest() throws Exception {
- ImportAssetUIUtils.importAsssetFillGeneralInfoAndSelectIcon(GeneralUIUtils.FILE_PATH, GeneralUIUtils.fileName,
- resourceDetails, getUser(), CreateAndImportButtonsEnum.IMPORT_CP);
- GeneralUIUtils.checkinCheckout(resourceDetails.getName());
- GeneralUIUtils.deleteVersionInUI();
- Thread.sleep(1000);
- GeneralUIUtils.getWebElementWaitForVisible(resourceDetails.getName()).click();
- String version = GeneralUIUtils.getWebElementWaitForVisible("versionHeader").getText();
- AssertJUnit.assertEquals("0.1", version.replace("V", ""));
- }
-
- // @Test(enabled = false)
- // public void importAssetVFCPrintScreenTest() throws Exception {
- // ImportAssetUIUtils.importAsssetFillGeneralInfoAndSelectIcon(GeneralUIUtils.FILE_PATH,
- // GeneralUIUtils.fileName , resourceDetails, getUser());
- // ResourceUIUtils.waitToFinishButtonEnabled().click();
- // ResourceUIUtils.openDropDownListOfObject(resourceDetails.getName(),
- // ResourceUIUtils.getAllObjectsOnWorkspace(driver,resourceDetails), "Edit",
- // ResourceUIUtils.scrollElement(driver));
- // ResourceUIUtils.waitfunctionforelements("sprite-resource-icons", 7);
- // Thread.sleep(2000);
- // WebElement element =
- // GeneralUIUtils.getDriver().findElement(By.className("network"));
- // WebElement target =
- // GeneralUIUtils.getDriver().findElement(By.className("dropzone"));
- // (new Actions(GeneralUIUtils.getDriver())).dragAndDrop(element,
- // target).perform();
- // WebElement element1 =
- // GeneralUIUtils.getDriver().findElement(By.className("network"));
- // (new Actions(GeneralUIUtils.getDriver())).dragAndDrop(element1,
- // target).perform();
- // ResourceUIUtils.clickPrintScreen();
- //
- // // the firefox not support print screen.
- // }
-
- @Test
- public void importAssetVFCSubmitForTestingTest() throws Exception {
- ImportAssetUIUtils.importAsssetFillGeneralInfoAndSelectIcon(GeneralUIUtils.FILE_PATH, GeneralUIUtils.fileName,
- resourceDetails, getUser(), CreateAndImportButtonsEnum.IMPORT_CP);
- String name = "";
- GeneralUIUtils.clickSubmitForTest();
- Thread.sleep(2000);
- String url = "http://localhost:8181/sdc1/proxy-tester1#/dashboard";
- navigateToUrl(url);
- GeneralUIUtils.getWebElementWaitForVisible("w-sdc-dashboard-card-info");
- int counter = 0;
- for (WebElement object : ResourceUIUtils.getAllObjectsOnWorkspace(GeneralUIUtils.getDriver(),
- resourceDetails)) {
- if (object.getText().equals(resourceDetails.getName())) {
- name = object.getText();
- counter++;
- }
- }
- AssertJUnit.assertEquals(1, counter);
-
- }
-
- @Override
- protected UserRoleEnum getRole() {
- return UserRoleEnum.DESIGNER;
- }
-
-}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resourceui/VFCanvasTest.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resourceui/VFCanvasTest.java
deleted file mode 100644
index 51454173de..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resourceui/VFCanvasTest.java
+++ /dev/null
@@ -1,91 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.execute.resourceui;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Random;
-
-import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.StepsEnum;
-import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
-import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest;
-import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils;
-import org.openqa.selenium.WebElement;
-import org.openqa.selenium.interactions.Action;
-import org.openqa.selenium.interactions.Actions;
-import org.testng.annotations.Test;
-
-public class VFCanvasTest extends SetupCDTest {
-
- public List<Integer> getposition(WebElement canvas, int width, int height) {
-
- width = canvas.getSize().getWidth();
- height = canvas.getSize().getHeight();
- Random r = new Random();
- int Resultx = r.nextInt(width);
- int Resulty = r.nextInt(height);
- List<Integer> position = new ArrayList<Integer>();
- position.add(Resultx);
- position.add(Resulty);
- return position;
- }
-
- @Test
- public void VFCanvasTest1() throws Exception {
- // GeneralUIUtils.waitForContainsdataTestIdVisibility("left-sectioin-element-QA");
-
- GeneralUIUtils.moveToStep(StepsEnum.COMPOSITION);
- Thread.sleep(2000);
- List<Integer> position = null;
- WebElement canvas = GeneralUIUtils.getWebElementWaitForVisible("canvas");
- int xPos = 0;
- int yPos = 0;
- position = getposition(canvas, xPos, yPos);
- WebElement otherElement = GeneralUIUtils
- .getWebElementWaitForVisible("left-sectioin-element-QA left-section-NeutronPort");
- for (int i = 0; i < 8; i++) {
- Actions builder = new Actions(GeneralUIUtils.getDriver());
- Action dragAndDrop = builder.clickAndHold(otherElement)
- .moveToElement(canvas, position.get(0), position.get(1)).release().build();
- dragAndDrop.perform();
- Thread.sleep(2000);
- }
- Thread.sleep(2000);
- Actions builder = new Actions(GeneralUIUtils.getDriver());
- builder.moveToElement(canvas, position.get(0), position.get(1));
- builder.clickAndHold();
- position = getposition(canvas, xPos, yPos);
- builder.moveToElement(canvas, position.get(0), position.get(1));
- builder.release();
- builder.build();
- builder.perform();
- builder.moveToElement(canvas, 200, 300);
- builder.release();
- builder.perform();
-
- }
-
- @Override
- protected UserRoleEnum getRole() {
- return UserRoleEnum.DESIGNER;
- }
-
-}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resourceui/VFUITest.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resourceui/VFUITest.java
deleted file mode 100644
index eec04bc297..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resourceui/VFUITest.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.execute.resourceui;
-
-import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
-import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest;
-
-public class VFUITest extends SetupCDTest {
-
- public VFUITest() {
- super();
- }
-
- @Override
- protected UserRoleEnum getRole() {
- return UserRoleEnum.DESIGNER;
- }
-
-}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resourceui/VfTests.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resourceui/VfTests.java
deleted file mode 100644
index 5550287aba..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resourceui/VfTests.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.execute.resourceui;
-
-import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
-import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest;
-
-public class VfTests extends SetupCDTest {
-
- @Override
- protected UserRoleEnum getRole() {
- return UserRoleEnum.DESIGNER;
- }
-
-}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resourceui/WorkspaceCheckBoxFilterTest.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resourceui/WorkspaceCheckBoxFilterTest.java
deleted file mode 100644
index 792d687a72..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resourceui/WorkspaceCheckBoxFilterTest.java
+++ /dev/null
@@ -1,120 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.execute.resourceui;
-
-import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
-import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest;
-import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils;
-import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
-import org.testng.AssertJUnit;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-public class WorkspaceCheckBoxFilterTest extends SetupCDTest {
-
- // This test check the status filter .
-
- private ResourceReqDetails resourceDetails;
-
- @BeforeMethod
- public void beforTest() {
- resourceDetails = ElementFactory.getDefaultResource();
- }
-
- @Test
- public void selectCheckOutMenuTest() throws Exception {
- GeneralUIUtils.clickSaveIcon();
- GeneralUIUtils.clickASDCLogo();
- String Status = GeneralUIUtils
- .checkBoxLifeCyclestate(org.openecomp.sdc.ci.tests.datatypes.CheckBoxStatusEnum.CHECKOUT);
- Thread.sleep(500);
- GeneralUIUtils.getWebElementWaitForVisible(resourceDetails.getName()).click();
- AssertJUnit.assertEquals(Status, GeneralUIUtils.getWebElementWaitForVisible("lifecyclestate").getText());
- }
-
- @Test
- public void selectCheckInMenuTest() throws Exception {
- GeneralUIUtils.clickSaveIcon();
- GeneralUIUtils.checkIn();
- String Status = GeneralUIUtils
- .checkBoxLifeCyclestate(org.openecomp.sdc.ci.tests.datatypes.CheckBoxStatusEnum.CHECKIN);
- Thread.sleep(500);
- GeneralUIUtils.getWebElementWaitForVisible(resourceDetails.getName()).click();
- AssertJUnit.assertEquals(Status, GeneralUIUtils.getWebElementWaitForVisible("lifecyclestate").getText());
- }
-
- @Test
- public void selectReadyForTestingMenuTest() throws Exception {
- GeneralUIUtils.clickSaveIcon();
- GeneralUIUtils.clickSubmitForTest();
- String Status = GeneralUIUtils
- .checkBoxLifeCyclestate(org.openecomp.sdc.ci.tests.datatypes.CheckBoxStatusEnum.READY_FOR_TESTING);
- Thread.sleep(500);
- GeneralUIUtils.getWebElementWaitForVisible(resourceDetails.getName()).click();
-
- AssertJUnit.assertEquals(Status, GeneralUIUtils.getWebElementWaitForVisible("lifecyclestate").getText());
- }
-
- @Test
- public void selectInTestIngMenuTest() throws Exception {
- GeneralUIUtils.clickSaveIcon();
- GeneralUIUtils.clickSubmitForTest();
- GeneralUIUtils.waitForClassNameVisibility("w-sdc-dashboard-card-footer");
- GeneralUIUtils.getDriver().navigate().to(SetupCDTest.getUrl().replace("designer", "tester"));
- GeneralUIUtils.getWebElementWaitForVisible(resourceDetails.getName()).click();
- GeneralUIUtils.clickStartTesting();
- GeneralUIUtils.clickASDCLogo();
- GeneralUIUtils.waitForClassNameVisibility("w-sdc-dashboard-card-footer");
- GeneralUIUtils.getDriver().navigate().to(SetupCDTest.getUrl().replace("tester", "designer"));
- String Status = GeneralUIUtils
- .checkBoxLifeCyclestate(org.openecomp.sdc.ci.tests.datatypes.CheckBoxStatusEnum.IN_TESTING);
- Thread.sleep(500);
- GeneralUIUtils.getWebElementWaitForVisible(resourceDetails.getName()).click();
-
- AssertJUnit.assertEquals(Status, GeneralUIUtils.getWebElementWaitForVisible("lifecyclestate").getText());
- }
-
- @Test
- public void selectCertifiedMenuTest() throws Exception {
- GeneralUIUtils.clickSaveIcon();
- GeneralUIUtils.clickSubmitForTest();
- GeneralUIUtils.waitForClassNameVisibility("w-sdc-dashboard-card-footer");
- GeneralUIUtils.getDriver().navigate().to(SetupCDTest.getUrl().replace("designer", "tester"));
- GeneralUIUtils.getWebElementWaitForVisible(resourceDetails.getName()).click();
- GeneralUIUtils.clickStartTesting();
- GeneralUIUtils.clickAccept();
- GeneralUIUtils.waitForClassNameVisibility("w-sdc-dashboard-card-footer");
- GeneralUIUtils.getDriver().navigate().to(SetupCDTest.getUrl().replace("tester", "designer"));
- String Status = GeneralUIUtils
- .checkBoxLifeCyclestate(org.openecomp.sdc.ci.tests.datatypes.CheckBoxStatusEnum.CERTIFIED);
- Thread.sleep(500);
- GeneralUIUtils.getWebElementWaitForVisible(resourceDetails.getName()).click();
-
- AssertJUnit.assertEquals(Status, GeneralUIUtils.getWebElementWaitForVisible("lifecyclestate").getText());
- }
-
- @Override
- protected UserRoleEnum getRole() {
- return UserRoleEnum.DESIGNER;
- }
-
-}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Import.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Import.java
deleted file mode 100644
index c5017a4f34..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Import.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.execute.sanity;
-
-import static org.testng.AssertJUnit.assertEquals;
-import static org.testng.AssertJUnit.assertTrue;
-
-import java.util.List;
-import java.util.function.Supplier;
-
-import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
-import org.openecomp.sdc.ci.tests.datatypes.ArtifactInfo;
-import org.openecomp.sdc.ci.tests.datatypes.BreadCrumbsButtonsEnum;
-import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.InformationalArtifacts;
-import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum;
-import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum;
-import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
-import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest;
-import org.openecomp.sdc.ci.tests.pages.GeneralPageElements;
-import org.openecomp.sdc.ci.tests.pages.InformationalArtifactPage;
-import org.openecomp.sdc.ci.tests.pages.ResourceGeneralPage;
-import org.openecomp.sdc.ci.tests.pages.TesterOperationPage;
-import org.openecomp.sdc.ci.tests.pages.ToscaArtifactsPage;
-import org.openecomp.sdc.ci.tests.utilities.ArtifactUIUtils;
-import org.openecomp.sdc.ci.tests.utilities.FileHandling;
-import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils;
-import org.openecomp.sdc.ci.tests.utilities.ResourceUIUtils;
-import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
-import org.openqa.selenium.ElementNotVisibleException;
-import org.openqa.selenium.WebElement;
-import org.openqa.selenium.support.ui.Select;
-import org.testng.annotations.Test;
-
-public class Import extends SetupCDTest {
-
- @Test
- public void importResource() throws Exception {
-
- String filePath = FileHandling.getResourcesFilesPath();
- String fileName = "CPWithAttributes.yml";
-
- // import Resource
- ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VFC, getUser());
- ResourceUIUtils.importVfc(resourceMetaData, filePath, fileName, getUser());
-
- }
-
- @Test
- public void certifyVFC() throws Exception {
- String filePath = FileHandling.getResourcesFilesPath();
- String fileName = "CPWithAttributes.yml";
- ResourceReqDetails atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(
- ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser());
- ResourceUIUtils.importVfc(atomicResourceMetaData, filePath, fileName, getUser());
- ResourceGeneralPage.clickCheckinButton(atomicResourceMetaData.getName());
- ResourceGeneralPage.clickSubmitForTestingButton(atomicResourceMetaData.getName());
- quitAndReLogin(UserRoleEnum.TESTER);
- GeneralUIUtils.findComponentAndClick(atomicResourceMetaData.getName());
- TesterOperationPage.certifyComponent(atomicResourceMetaData.getName());
-
- quitAndReLogin(UserRoleEnum.DESIGNER);
- // GeneralUIUtils.clickBreadCrumbs(BreadCrumbsButtonsEnum.CATALOG);
- String cpVersion = GeneralUIUtils.getComponentVersion(atomicResourceMetaData.getName());
- assertTrue("V 1.0".equals(cpVersion));
- }
-
- @Test
- public void uploadAllInformationalArtifactPlaceholdersInVFC() throws Exception {
- String filePath = FileHandling.getResourcesFilesPath();
- String fileName = "CPWithAttributes.yml";
- ResourceReqDetails atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(
- ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser());
- ResourceUIUtils.importVfc(atomicResourceMetaData, filePath, fileName, getUser());
-
- ResourceGeneralPage.getLeftMenu().moveToInformationalArtifactScreen();
-
- for (InformationalArtifacts infoArtifact : InformationalArtifacts.values()) {
- ArtifactUIUtils.fillPlaceHolderInformationalArtifact(infoArtifact, filePath, "Heat-File 1.yaml",
- infoArtifact.name());
- }
-
- assertTrue(InformationalArtifactPage.checkElementsCountInTable(InformationalArtifacts.values().length,
- () -> InformationalArtifactPage.getElemenetsFromTable()));
-
- InformationalArtifactPage.clickAddNewArtifact();
- Select artifactLabelList = InformationalArtifactPage.artifactPopup().defineArtifactLabel("");
- assertEquals(1, artifactLabelList.getAllSelectedOptions().size());
-
- }
-
- @Test(expectedExceptions = ElementNotVisibleException.class)
- public void uploadInformationaArtifactMetdataTest() throws Exception {
- String filePath = FileHandling.getResourcesFilesPath();
- String fileName = "CPWithAttributes.yml";
- ResourceReqDetails atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(
- ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser());
- ResourceUIUtils.importVfc(atomicResourceMetaData, filePath, fileName, getUser());
-
- ResourceGeneralPage.getLeftMenu().moveToInformationalArtifactScreen();
- assertTrue(InformationalArtifactPage.checkElementsCountInTable(0,
- () -> InformationalArtifactPage.getElemenetsFromTable()));
-
- ArtifactInfo artifactInfo = new ArtifactInfo(filePath, "Heat-File 1.yaml", "new artifact", "artifact1",
- "OTHER");
- InformationalArtifactPage.clickAddNewArtifact();
- ArtifactUIUtils.fillAndAddNewArtifactParameters(artifactInfo);
-
- assertTrue(InformationalArtifactPage.checkElementsCountInTable(1,
- () -> InformationalArtifactPage.getElemenetsFromTable()));
-
- String actulaArtifactDescription = InformationalArtifactPage
- .getArtifactDescription(artifactInfo.getArtifactLabel());
- assertTrue(artifactInfo.getDescription().equals(actulaArtifactDescription));
-
- InformationalArtifactPage.clickEditArtifact(artifactInfo.getArtifactLabel());
- InformationalArtifactPage.artifactPopup().defineArtifactLabel("artifact2");
- }
-
- // @Test()
- // public void updateInformationalArtifact(){
- // ArtifactInfo artifactInfo = new ArtifactInfo("", "", "new artifact",
- // "artifact1", "");
- // InformationalArtifactPage.clickEditArtifact("artifact1");
- // String newDesc = "newDesc";
- // InformationalArtifactPage.artifactPopup().insertDescription(newDesc);
- // InformationalArtifactPage.artifactPopup().clickUpdateButton();
- // String actulaArtifactDescription =
- // InformationalArtifactPage.getArtifactDescription(artifactInfo.getArtifactLabel());
- // assertTrue(newDesc.equals(actulaArtifactDescription));
- // InformationalArtifactPage.clickEditArtifact(artifactInfo.getArtifactLabel());
- // InformationalArtifactPage.artifactPopup().defineArtifactLabel("artifact2");
- // InformationalArtifactPage.artifactPopup().selectArtifactType(artifactInfo.getArtifactType());
- // }
-
- @Test
- public void verifyTwoToscaArtifacts() throws Exception {
- String filePath = FileHandling.getResourcesFilesPath();
- String fileName = "CPWithAttributes.yml";
- ResourceReqDetails atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(
- ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser());
- ResourceUIUtils.importVfc(atomicResourceMetaData, filePath, fileName, getUser());
-
- ResourceGeneralPage.getLeftMenu().moveToToscaArtifactsScreen();
-
- // List<WebElement> elemenetsFromTable =
- // GeneralPageElements.getElemenetsFromTable();
- // Supplier<List<WebElement>> supplier = () -> elemenetsFromTable;
- // assertTrue(ToscaArtifactsPage.checkElementsCountInTable(2,
- // supplier));
- assertTrue(ToscaArtifactsPage.checkElementsCountInTable(2));
- }
-
- @Override
- protected UserRoleEnum getRole() {
- return UserRoleEnum.DESIGNER;
- }
-
-}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Onboard.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Onboard.java
deleted file mode 100644
index 713bc4df41..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Onboard.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.execute.sanity;
-
-import static org.testng.AssertJUnit.assertNotNull;
-
-import java.awt.AWTException;
-import java.io.File;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.openecomp.sdc.ci.tests.datatypes.CanvasElement;
-import org.openecomp.sdc.ci.tests.datatypes.CanvasManager;
-import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum;
-import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.enums.ServiceCategoriesEnum;
-import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
-import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest;
-import org.openecomp.sdc.ci.tests.pages.CompositionPage;
-import org.openecomp.sdc.ci.tests.pages.GeneralPageElements;
-import org.openecomp.sdc.ci.tests.pages.GovernorOperationPage;
-import org.openecomp.sdc.ci.tests.pages.OpsOperationPage;
-import org.openecomp.sdc.ci.tests.pages.ResourceGeneralPage;
-import org.openecomp.sdc.ci.tests.pages.ServiceGeneralPage;
-import org.openecomp.sdc.ci.tests.pages.TesterOperationPage;
-import org.openecomp.sdc.ci.tests.utilities.FileHandling;
-import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils;
-import org.openecomp.sdc.ci.tests.utilities.OnboardingUtils;
-import org.openecomp.sdc.ci.tests.utilities.ServiceUIUtils;
-import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
-import org.openecomp.sdc.ci.tests.verificator.ServiceVerificator;
-import org.openqa.selenium.By;
-import org.openqa.selenium.WebElement;
-import org.openqa.selenium.support.ui.ExpectedConditions;
-import org.openqa.selenium.support.ui.WebDriverWait;
-import org.testng.Assert;
-import org.testng.AssertJUnit;
-import org.testng.annotations.DataProvider;
-import org.testng.annotations.Test;
-
-import com.relevantcodes.extentreports.LogStatus;
-
-public class Onboard extends SetupCDTest {
-
-
- public static Object[][] provideData(Object[] fileNamesFromFolder, String filepath) {
- Object[][] arObject = new Object[fileNamesFromFolder.length][];
-
- int index = 0;
- for (Object obj : fileNamesFromFolder) {
- arObject[index++] = new Object[] { filepath, obj };
- }
- return arObject;
- }
-
- @DataProvider(name = "VNF_List")
- private static final Object[][] VnfList() throws Exception {
- String filepath = getFilePath();
- Object[] fileNamesFromFolder = OnboardingUtils.getZipFileNamesFromFolder(filepath);
- System.out.println(String.format("There are %s zip file(s) to test", fileNamesFromFolder.length));
- return provideData(fileNamesFromFolder, filepath);
- }
-
- @Test(dataProvider = "VNF_List")
- public void onboardVNFTest(String filepath, String vnfFile) throws Exception, Throwable {
- SetupCDTest.setScreenshotFile(vnfFile);
- extendTest.setDescription(vnfFile);
-
- String vspName = onboardVNF(filepath, vnfFile);
-
- ResourceGeneralPage.clickSubmitForTestingButton(vspName);
-
- quitAndReLogin(UserRoleEnum.TESTER);
- GeneralUIUtils.findComponentAndClick(vspName);
- TesterOperationPage.certifyComponent(vspName);
-
- quitAndReLogin(UserRoleEnum.DESIGNER);
- // create service
- ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService();
- ServiceUIUtils.createService(serviceMetadata, getUser());
-
- ServiceGeneralPage.getLeftMenu().moveToCompositionScreen();
- CompositionPage.searchForElement(vspName);
- CanvasManager serviceCanvasManager = CanvasManager.getCanvasManager();
- CanvasElement vfElement = serviceCanvasManager.createElementOnCanvas(vspName);
- assertNotNull(vfElement);
- ServiceVerificator.verifyNumOfComponentInstances(serviceMetadata, "0.1", 1, getUser());
-
- ServiceGeneralPage.clickSubmitForTestingButton(serviceMetadata.getName());
-
- quitAndReLogin(UserRoleEnum.TESTER);
- GeneralUIUtils.findComponentAndClick(serviceMetadata.getName());
- TesterOperationPage.certifyComponent(serviceMetadata.getName());
-
- quitAndReLogin(UserRoleEnum.GOVERNOR);
- GeneralUIUtils.findComponentAndClick(serviceMetadata.getName());
- GovernorOperationPage.approveSerivce(serviceMetadata.getName());
-
-// quitAndReLogin(UserRoleEnum.OPS);
-// GeneralUIUtils.findComponentAndClick(serviceMetadata.getName());
-// OpsOperationPage.distributeService();
-// OpsOperationPage.displayMonitor();
-//
-// List<WebElement> rowsFromMonitorTable = OpsOperationPage.getRowsFromMonitorTable();
-// AssertJUnit.assertEquals(1, rowsFromMonitorTable.size());
-//
-// OpsOperationPage.waitUntilArtifactsDistributed(0);
-//
-// extendTest.log(LogStatus.PASS, String.format("onboarding %s test is passed ! ", vnfFile));
- }
-
- private String onboardVNF(String filepath, String vnfFile) throws Exception, Throwable {
- extendTest.log(LogStatus.INFO, String.format("going to onboard the VNF %s......", vnfFile));
- System.out.println(String.format("going to onboard the VNF %s......", vnfFile));
-
- OnboardingUtils.createVendorLicense(getUser());
- String vspName = OnboardingUtils.createVendorSoftwareProduct(vnfFile, filepath, getUser());
- GeneralUIUtils.getWebButton("repository-icon").click();
- extendTest.log(LogStatus.INFO, String.format("searching for onboarded %s", vnfFile));
- GeneralUIUtils.getWebElementWaitForVisible("onboarding-search").sendKeys(vspName);
- AssertJUnit.assertTrue(GeneralPageElements.checkElementsCountInTable(2));
-
- List<WebElement> elemenetsFromTable = GeneralPageElements.getElemenetsFromTable();
- GeneralUIUtils.waitForLoader();
- WebDriverWait wait = new WebDriverWait(GeneralUIUtils.getDriver(), 30);
- WebElement findElement = wait.until(ExpectedConditions.visibilityOf(elemenetsFromTable.get(1)));
- findElement.click();
- GeneralUIUtils.waitForLoader();
- extendTest.log(LogStatus.INFO,
- String.format("going to import %s......", vnfFile.substring(0, vnfFile.indexOf("."))));
- GeneralUIUtils.getWebElementWaitForVisible("import-csar").click();
- GeneralUIUtils.getWebButton("create/save").click();
- GeneralUIUtils.waitForLoaderOnboarding();
- WebDriverWait wait2 = new WebDriverWait(GeneralUIUtils.getDriver(), 2 * 60);
- wait2.until(ExpectedConditions.visibilityOfElementLocated(
- By.xpath("//*[@data-tests-id='" + DataTestIdEnum.LifeCyleChangeButtons.CHECK_IN.getValue() + "']")));
- extendTest.log(LogStatus.PASS,
- String.format("succeeded to import %s......", vnfFile.substring(0, vnfFile.indexOf("."))));
- return vspName;
- }
-
- public static String getFilePath() {
- String filepath = System.getProperty("filepath");
- if (filepath == null && System.getProperty("os.name").contains("Windows")) {
- filepath = FileHandling.getResourcesFilesPath();
- }
-
- else if(filepath.isEmpty() && !System.getProperty("os.name").contains("Windows")){
- filepath = FileHandling.getBasePath() + File.separator + "Files";
- }
- return filepath;
- }
-
- @Test
- public void twoOnboardedVNFsInService() throws Exception, Throwable{
-
- String filepath = getFilePath();
-
- final String dnsScaling = "DNSscaling12.8.16.zip";
- final String vLB = "vLB12.8.16.zip";
-
- String[] onboardList = {dnsScaling, vLB};
-
- Map<String, String> vspMap = new HashMap<String,String>();
-
- for (String vnf : onboardList){
- GeneralUIUtils.waitForElementsListInvisibility(By.className("ui-notification"));
- String vspName = onboardVNF(filepath, vnf);
- vspMap.put(vnf, vspName);
- ResourceGeneralPage.clickSubmitForTestingButton(vspName);
- }
-
- quitAndReLogin(UserRoleEnum.TESTER);
- for (String vspName : vspMap.values()){
- GeneralUIUtils.waitForElementsListInvisibility(By.className("ui-notification"));
- GeneralUIUtils.findComponentAndClick(vspName);
- TesterOperationPage.certifyComponent(vspName);
- }
-
- quitAndReLogin(UserRoleEnum.DESIGNER);
- ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService();
- ServiceUIUtils.createService(serviceMetadata, getUser());
- ServiceGeneralPage.getLeftMenu().moveToCompositionScreen();
- CanvasManager serviceCanvasManager = CanvasManager.getCanvasManager();
-
- Map<String, CanvasElement> canvasElements = new HashMap<String,CanvasElement>();
- for (String vspName : vspMap.values()){
- CompositionPage.searchForElement(vspName);
- CanvasElement vfElement = serviceCanvasManager.createElementOnCanvas(vspName);
- assertNotNull(vfElement);
- canvasElements.put(vspName, vfElement);
- }
- ServiceVerificator.verifyNumOfComponentInstances(serviceMetadata, "0.1", 2, getUser());
-
- }
-
- @Override
- protected UserRoleEnum getRole() {
- return UserRoleEnum.DESIGNER;
- }
-
-}
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
deleted file mode 100644
index 96a22ef2fe..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Vf.java
+++ /dev/null
@@ -1,377 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.execute.sanity;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
-import org.openecomp.sdc.ci.tests.datatypes.ArtifactInfo;
-import org.openecomp.sdc.ci.tests.datatypes.CanvasElement;
-import org.openecomp.sdc.ci.tests.datatypes.CanvasManager;
-import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum;
-import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.InformationalArtifacts;
-import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.LeftPanelCanvasItems;
-import org.openecomp.sdc.ci.tests.datatypes.PropertyInfo;
-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.PropertyTypeEnum;
-import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum;
-import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
-import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest;
-import org.openecomp.sdc.ci.tests.pages.CompositionPage;
-import org.openecomp.sdc.ci.tests.pages.DeploymentArtifactPage;
-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.utilities.ArtifactUIUtils;
-import org.openecomp.sdc.ci.tests.utilities.FileHandling;
-import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils;
-import org.openecomp.sdc.ci.tests.utilities.PropertiesUIUtils;
-import org.openecomp.sdc.ci.tests.utilities.ResourceUIUtils;
-import org.openecomp.sdc.ci.tests.utilities.ServiceUIUtils;
-import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
-import org.openecomp.sdc.ci.tests.verificator.ServiceVerificator;
-import org.openecomp.sdc.ci.tests.verificator.VfVerificator;
-import org.openqa.selenium.By;
-import org.openqa.selenium.WebElement;
-import org.openqa.selenium.support.ui.Select;
-import org.testng.AssertJUnit;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-public class Vf extends SetupCDTest {
-
- private String filePath;
-
- @BeforeMethod
- public void beforeTest() {
- filePath = System.getProperty("filepath");
- if (filePath == null) {
- filePath = FileHandling.getResourcesFilesPath();
- }
- }
-
- @Test
- public void createVF() throws Exception {
-
- // create Resource
- ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser());
- ResourceUIUtils.createResource(resourceMetaData, getUser());
-
- }
-
- @Test
- public void updateVF() throws Exception {
-
- // create Resource
- ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser());
- ResourceUIUtils.createResource(resourceMetaData, getUser());
-
- // update Resource
- String expectedDesc = "kuku";
- resourceMetaData.setDescription(expectedDesc);
- ResourceGeneralPage.defineDescription(expectedDesc);
- GeneralUIUtils.clickUpdateButton();
-
- VfVerificator.verifyVFUpdatedInUI(resourceMetaData);
- }
-
- @Test
- public void vfcLinkedToComputeInVfWithArtifactsFlow() throws Exception {
- // String filePath = FileHandling.getResourcesFilesPath();
- String fileName = "vFW_VFC.yml";
-
- // import Resource
- ResourceReqDetails atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(
- ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser());
- ResourceUIUtils.importVfc(atomicResourceMetaData, filePath, fileName, getUser());
- ResourceGeneralPage.getLeftMenu().moveToInformationalArtifactScreen();
- ArtifactUIUtils.fillPlaceHolderInformationalArtifact(InformationalArtifacts.CAPACITY, filePath,
- "asc_heat 0 2.yaml", "capacity");
- ArtifactUIUtils.fillPlaceHolderInformationalArtifact(InformationalArtifacts.FEATURES, filePath,
- "asc_heat 0 2.yaml", "features");
- ResourceGeneralPage.clickSubmitForTestingButton(atomicResourceMetaData.getName());
-
- quitAndReLogin(UserRoleEnum.TESTER);
- GeneralUIUtils.findComponentAndClick(atomicResourceMetaData.getName());
- TesterOperationPage.certifyComponent(atomicResourceMetaData.getName());
-
- quitAndReLogin(UserRoleEnum.DESIGNER);
-
- // create Resource
- ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser());
- ResourceUIUtils.createResource(vfMetaData, getUser());
-
- ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen();
-
- ArtifactInfo artifact1 = new ArtifactInfo(filePath, "asc_heat 0 2.yaml", "kuku", "artifact1", "OTHER");
- DeploymentArtifactPage.clickAddNewArtifact();
- ArtifactUIUtils.fillAndAddNewArtifactParameters(artifact1);
- ArtifactInfo artifact2 = new ArtifactInfo(filePath, "sample-xml-alldata-1-1.xml", "kuku", "artifact2",
- "YANG_XML");
- DeploymentArtifactPage.clickAddNewArtifact();
- ArtifactUIUtils.fillAndAddNewArtifactParameters(artifact2);
-
- DeploymentArtifactPage.getLeftMenu().moveToCompositionScreen();
- CanvasManager canvasManager = CanvasManager.getCanvasManager();
- 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);
-
- }
-
- @Test
- public void addingDeploymentArtifactToVFInstanceInService() throws Exception {
- // String filePath = FileHandling.getResourcesFilesPath();
- // create Resource
- ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser());
- ResourceUIUtils.createResource(vfMetaData, getUser());
-
- 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);
- }
-
- ResourceGeneralPage.clickSubmitForTestingButton(vfMetaData.getName());
- GeneralUIUtils.clickASDCLogo();
-
- ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService();
- ServiceUIUtils.createService(serviceMetadata, getUser());
-
- ServiceGeneralPage.getLeftMenu().moveToCompositionScreen();
- CompositionPage.searchForElement(vfMetaData.getName());
- CanvasManager serviceCanvasManager = CanvasManager.getCanvasManager();
- CanvasElement vfElement = serviceCanvasManager.createElementOnCanvas(vfMetaData.getName());
-
- serviceCanvasManager.clickOnCanvaElement(vfElement);
- GeneralUIUtils.waitFordataTestIdVisibility("deployment-artifact-tab").click();
- GeneralUIUtils.waitFordataTestIdVisibility("add_Artifact_Button").click();
- GeneralUIUtils.waitForLoader();
- ArtifactInfo artifact3 = new ArtifactInfo(filePath, "Heat-File.yaml", "kuku", "artifact3",
- "DCAE_INVENTORY_TOSCA");
- deploymentArtifactList.add(artifact3);
- GeneralUIUtils.getWebElementWaitForVisible("artifact-label").sendKeys(artifact3.getArtifactLabel());
- DeploymentArtifactPage.artifactPopup().selectArtifactType(artifact3.getArtifactType());
- DeploymentArtifactPage.artifactPopup().insertDescription(artifact3.getDescription());
- DeploymentArtifactPage.artifactPopup().loadFile(artifact3.getFilepath(), artifact3.getFilename());
- GeneralUIUtils.getWebElementWaitForVisible("Done").click();
- GeneralUIUtils.waitForLoader();
-
- List<WebElement> actualArtifactList = GeneralUIUtils
- .waitForElementsListVisibility(By.className("i-sdc-designer-sidebar-section-content-item-artifact"));
- AssertJUnit.assertEquals(deploymentArtifactList.size(), actualArtifactList.size());
-
- }
-
- @Test
- public void distibuteVFCInVFInServiceTest() throws Exception {
- // String filePath = FileHandling.getResourcesFilesPath();
- String fileName = "vFW_VFC.yml";
-
- // import Resource
- ResourceReqDetails atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(
- ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser());
- ResourceUIUtils.importVfc(atomicResourceMetaData, filePath, fileName, getUser());
- ResourceGeneralPage.getLeftMenu().moveToInformationalArtifactScreen();
- ArtifactUIUtils.fillPlaceHolderInformationalArtifact(InformationalArtifacts.CAPACITY, filePath,
- "asc_heat 0 2.yaml", "capacity");
- ArtifactUIUtils.fillPlaceHolderInformationalArtifact(InformationalArtifacts.FEATURES, filePath,
- "asc_heat 0 2.yaml", "features");
- ResourceGeneralPage.clickSubmitForTestingButton(atomicResourceMetaData.getName());
-
- quitAndReLogin(UserRoleEnum.TESTER);
- GeneralUIUtils.findComponentAndClick(atomicResourceMetaData.getName());
- TesterOperationPage.certifyComponent(atomicResourceMetaData.getName());
-
- quitAndReLogin(UserRoleEnum.DESIGNER);
-
- // create Resource
- ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser());
- ResourceUIUtils.createResource(vfMetaData, getUser());
-
- 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", "kuku", "artifact2", "YANG_XML"));
- for (ArtifactInfo deploymentArtifact : deploymentArtifactList) {
- DeploymentArtifactPage.clickAddNewArtifact();
- ArtifactUIUtils.fillAndAddNewArtifactParameters(deploymentArtifact);
- }
-
- DeploymentArtifactPage.getLeftMenu().moveToCompositionScreen();
- CanvasManager vfCanvasManager = CanvasManager.getCanvasManager();
- CanvasElement computeElement = vfCanvasManager.createElementOnCanvas(LeftPanelCanvasItems.COMPUTE);
- CompositionPage.searchForElement(atomicResourceMetaData.getName());
- CanvasElement cpElement = vfCanvasManager.createElementOnCanvas(atomicResourceMetaData.getName());
-
- vfCanvasManager.linkElements(cpElement, computeElement);
-
- ResourceGeneralPage.clickSubmitForTestingButton(vfMetaData.getName());
-
- quitAndReLogin(UserRoleEnum.TESTER);
- GeneralUIUtils.findComponentAndClick(vfMetaData.getName());
- TesterOperationPage.certifyComponent(vfMetaData.getName());
-
- quitAndReLogin(UserRoleEnum.DESIGNER);
-
- // create service
- ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService();
- ServiceUIUtils.createService(serviceMetadata, getUser());
-
- ServiceGeneralPage.getLeftMenu().moveToCompositionScreen();
- CompositionPage.searchForElement(vfMetaData.getName());
- CanvasManager serviceCanvasManager = CanvasManager.getCanvasManager();
- CanvasElement vfElement = serviceCanvasManager.createElementOnCanvas(vfMetaData.getName());
-
- ServiceGeneralPage.clickSubmitForTestingButton(serviceMetadata.getName());
-
- quitAndReLogin(UserRoleEnum.TESTER);
- GeneralUIUtils.findComponentAndClick(serviceMetadata.getName());
- TesterOperationPage.certifyComponent(serviceMetadata.getName());
-
- quitAndReLogin(UserRoleEnum.GOVERNOR);
- GeneralUIUtils.findComponentAndClick(serviceMetadata.getName());
- GovernorOperationPage.approveSerivce(serviceMetadata.getName());
-
- quitAndReLogin(UserRoleEnum.OPS);
- GeneralUIUtils.findComponentAndClick(serviceMetadata.getName());
- OpsOperationPage.distributeService();
- OpsOperationPage.displayMonitor();
-
- List<WebElement> rowsFromMonitorTable = OpsOperationPage.getRowsFromMonitorTable();
- AssertJUnit.assertEquals(1, rowsFromMonitorTable.size());
-
- String deploymentArtifactsSize = String.valueOf(deploymentArtifactList.size() + 1);
-
- OpsOperationPage.waitUntilArtifactsDistributed(deploymentArtifactsSize, 0);
-
- }
-
- @Test
- public void changesInVFCInstanceInVF() throws Exception {
- // String filePath = FileHandling.getResourcesFilesPath();
- String fileName = "vFW_VFC.yml";
-
- // import Resource
- ResourceReqDetails atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(
- ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser());
- ResourceUIUtils.importVfc(atomicResourceMetaData, filePath, fileName, getUser());
- ResourceGeneralPage.getLeftMenu().moveToInformationalArtifactScreen();
- ArtifactUIUtils.fillPlaceHolderInformationalArtifact(InformationalArtifacts.CAPACITY, filePath,
- "asc_heat 0 2.yaml", "capacity");
-
- InformationalArtifactPage.getLeftMenu().moveToPropertiesScreen();
- int propertiesCount = PropertiesPage.getElemenetsFromTable().size();
-
- PropertyInfo prop1 = new PropertyInfo("p1", "v1", "prop1", PropertyTypeEnum.STRING);
-
- PropertiesPage.clickAddPropertyArtifact();
- PropertiesUIUtils.addNewProperty(prop1);
- AssertJUnit.assertTrue(PropertiesPage.checkElementsCountInTable(propertiesCount + 1,
- () -> PropertiesPage.getElemenetsFromTable()));
-
- ResourceGeneralPage.clickSubmitForTestingButton(atomicResourceMetaData.getName());
-
- ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser());
- ResourceUIUtils.createResource(vfMetaData, getUser());
-
- DeploymentArtifactPage.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();
- for (int i = 0; i < 2; i++) {
- // WebDriverWait wait = new WebDriverWait(GeneralUIUtils.getDriver()
- // , 30);
- // WebElement findElement =
- // wait.until(ExpectedConditions.visibilityOf(properties.get(i).findElement(By.className("i-sdc-designer-sidebar-section-content-item-property-and-attribute-label"))));
- WebElement findElement = properties.get(i).findElement(
- By.className("i-sdc-designer-sidebar-section-content-item-property-and-attribute-label"));
- findElement.click();
- PropertiesPage.getPropertyPopup().insertPropertyDefaultValue("abc123");
- PropertiesPage.getPropertyPopup().clickSave();
- GeneralUIUtils.waitForInvisibileElement(DataTestIdEnum.PropertiesPageEnum.SAVE.getValue());
- }
- vfCanvasManager.moveToFreeLocation(vfMetaData.getName());
- GeneralUIUtils.waitFordataTestIdVisibility("deployment-artifact-tab").click();
- GeneralUIUtils.waitFordataTestIdVisibility("add_Artifact_Button").click();
- GeneralUIUtils.waitForLoader();
- ArtifactInfo artifact3 = new ArtifactInfo(filePath, "Heat-File.yaml", "kuku", "artifact3", "OTHER");
- GeneralUIUtils.getWebElementWaitForVisible("artifact-label").sendKeys(artifact3.getArtifactLabel());
- DeploymentArtifactPage.artifactPopup().selectArtifactType(artifact3.getArtifactType());
- DeploymentArtifactPage.artifactPopup().insertDescription(artifact3.getDescription());
- DeploymentArtifactPage.artifactPopup().loadFile(artifact3.getFilepath(), artifact3.getFilename());
- GeneralUIUtils.getWebElementWaitForVisible("Done").click();
- GeneralUIUtils.waitForLoader();
-
- quitAndReLogin(UserRoleEnum.TESTER);
- GeneralUIUtils.findComponentAndClick(atomicResourceMetaData.getName());
- TesterOperationPage.certifyComponent(atomicResourceMetaData.getName());
-
- quitAndReLogin(UserRoleEnum.DESIGNER);
- GeneralUIUtils.findComponentAndClick(vfMetaData.getName());
- ResourceGeneralPage.getLeftMenu().moveToCompositionScreen();
- vfCanvasManager = CanvasManager.getCanvasManager();
- vfCanvasManager.clickOnCanvaElement(vfcElement);
- // change version
- GeneralUIUtils.getWebElementByName("changeVersion");
- Select selectlist = new Select(GeneralUIUtils.getWebElementByName("changeVersion"));
- selectlist.selectByVisibleText("1.0");
- GeneralUIUtils.waitForLoader();
-
- // GeneralUIUtils.waitUntilClickableButton(DataTestIdEnum.LifeCyleChangeButtons.SUBMIT_FOR_TESTING.getValue()).click();
- // ResourceGeneralPage.clickSubmitForTestingButton(vfMetaData.getName());
- //
- // vfMetaData.setVersion("0.1");
- // VfVerificator.verifyVFLifecycle(vfMetaData, getUser(),
- // LifecycleStateEnum.READY_FOR_CERTIFICATION);
- }
-
- @Override
- protected UserRoleEnum getRole() {
- return UserRoleEnum.DESIGNER;
- }
-
-}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/OnboardCSVReport.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/OnboardCSVReport.java
deleted file mode 100644
index 03c9b0281f..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/OnboardCSVReport.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.execute.setup;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.PrintWriter;
-
-public class OnboardCSVReport {
-
- private StringBuilder sb;
- private PrintWriter pw;
-
- public OnboardCSVReport(String filepath, String filename) {
- sb = new StringBuilder();
- try {
- File csvFile = new File(filepath + filename);
- pw = new PrintWriter(csvFile);
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- }
-
- }
-
- public StringBuilder appendStringToFile(String content) {
- return sb.append(content + ",");
- }
-
- public void openNewRow() {
- sb.append("\n");
- }
-
- public void writeRow(String... content) {
- for (String str : content) {
- appendStringToFile(str);
- }
- openNewRow();
- }
-
- public void closeFile() {
- pw.write(sb.toString());
- pw.close();
- }
-
-}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/RemoteWebDriverTest.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/RemoteWebDriverTest.java
deleted file mode 100644
index e5fcafb664..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/RemoteWebDriverTest.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.execute.setup;
-
-import java.net.URL;
-
-import org.junit.Ignore;
-import org.junit.Test;
-import org.openqa.selenium.Platform;
-import org.openqa.selenium.firefox.FirefoxDriver;
-import org.openqa.selenium.remote.DesiredCapabilities;
-import org.openqa.selenium.remote.RemoteWebDriver;
-
-public class RemoteWebDriverTest {
-
- // @Test
- public void remoteTest() throws Exception {
- DesiredCapabilities cap = new DesiredCapabilities().firefox();
- cap.setPlatform(Platform.WINDOWS);
- cap.setBrowserName("firefox");
-
- RemoteWebDriver remoteDriver = new RemoteWebDriver(new URL("http://1.2.3.4:5555/wd/hub"), cap);
- remoteDriver.navigate().to("http://www.google.co.il");
- remoteDriver.findElementByName("q").sendKeys("execute automation");
- remoteDriver.findElementByName("btnK").click();
- }
-}
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
deleted file mode 100644
index a72168e4c2..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/SetupCDTest.java
+++ /dev/null
@@ -1,538 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.execute.setup;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Map;
-import java.util.Random;
-import java.util.stream.Collectors;
-
-import org.apache.commons.io.FileUtils;
-import org.apache.log4j.Logger;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.ci.tests.config.Config;
-import org.openecomp.sdc.ci.tests.datatypes.UserCredentials;
-import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
-import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
-import org.openecomp.sdc.ci.tests.run.StartTest;
-import org.openecomp.sdc.ci.tests.utilities.FileHandling;
-import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils;
-import org.openecomp.sdc.ci.tests.utils.Utils;
-import org.openecomp.sdc.ci.tests.utils.rest.CatalogRestUtils;
-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.openqa.selenium.By;
-import org.openqa.selenium.WebDriver;
-import org.openqa.selenium.WebElement;
-import org.openqa.selenium.support.ui.ExpectedConditions;
-import org.openqa.selenium.support.ui.WebDriverWait;
-import org.testng.Assert;
-import org.testng.AssertJUnit;
-import org.testng.ITestResult;
-import org.testng.annotations.AfterClass;
-import org.testng.annotations.AfterMethod;
-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;
-
-public abstract class SetupCDTest {
-
- public SetupCDTest() {
- // LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
- // lc.getLogger("org.apache").setLevel(Level.INFO);
- //// System.setProperty("org.apache.commons.logging.Log",
- // "org.apache.commons.logging.impl.SimpleLog");
- //// System.setProperty("org.apache.commons.logging.simplelog.log.httpclient.wire",
- // "OFF");
- //// System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient",
- // "OFF");
-
- }
-
- public static Logger logger = Logger.getLogger(SetupCDTest.class.getName());
-
- /**************** CONSTANTS ****************/
- private static final String CREDENTIALS_FILE = "credentials.yaml";
- private static final String REPORT_FILE_NAME = "ASDC_UI_Extent_Report.html";
- public static final String REPORT_FOLDER = "./ExtentReport/";
- public static final String SELENIUM_NODE_URL = "http://%s:%s/wd/hub";
- private static final String SCREENSHOT_FOLDER = REPORT_FOLDER + "screenshots/";
- private static final String SHORT_CSV_REPORT_FILE_NAME = "ShortReport.csv";
- private static final int NUM_OF_ATTEMPTS_TO_REFTRESH = 2;
-
- /**************** USERS ****************/
- protected static User designerUser;
- protected static User adminUser;
- protected static User testerUser;
- protected static User governorUser;
- protected static User opsUser;
- protected static User productManagerUser;
-
- public static Config config;
-
- /**************** PRIVATES ****************/
- private Map<?, ?> credentialsYamlFileMap;
- private static String url;
- private User user;
- private static boolean localEnv = true;
- private int refreshAttempts = 0;
-
- protected abstract UserRoleEnum getRole();
-
- protected ExtentReports extentReport;
- protected static ExtentTest extendTest;
- private static String screenshotFile;
-
- public static String getScreenshotFile() {
- return screenshotFile;
- }
-
- public static void setScreenshotFile(String screenshotFile) {
- SetupCDTest.screenshotFile = screenshotFile;
- }
-
- public static ExtentTest getExtendTest() {
- return extendTest;
- }
-
- private OnboardCSVReport csvReport;
-
- public OnboardCSVReport getCsvReport() {
- return csvReport;
- }
-
- /**************** BEFORE ****************/
-
- @BeforeSuite(alwaysRun = true)
- public void setEnvParameters() throws Exception {
-
- File dir = new File(REPORT_FOLDER);
- try {
- FileUtils.deleteDirectory(dir);
- } catch (IOException e) {
- }
- extentReport = new ExtentReports(REPORT_FOLDER + REPORT_FILE_NAME);
- csvReport = new OnboardCSVReport(REPORT_FOLDER, SHORT_CSV_REPORT_FILE_NAME);
-
- System.out.println("Setup....");
- config = Utils.getConfig();
- setUrl();
- }
-
- @BeforeMethod(alwaysRun = true)
- public void setBrowserBeforeTest(java.lang.reflect.Method method) throws Exception {
- extendTest = extentReport.startTest(method.getName());
- extendTest.log(LogStatus.INFO, "Test started");
- setBrowserBeforeTest(getRole());
- }
-
- /**************** AFTER ****************/
- @AfterMethod(alwaysRun = true)
- public void quitAfterTest(ITestResult result) throws Exception {
-
- StringBuilder sb = new StringBuilder();
- if (result.getParameters().length != 0) {
- for (int i = 0; i < result.getParameters().length - 1; i++) {
- sb.append(result.getParameters()[i].toString() + ",");
- }
- sb.append(result.getParameters()[result.getParameters().length - 1].toString());
- }
-
- File imageFilePath = GeneralUIUtils.takeScreenshot(screenshotFile, SCREENSHOT_FOLDER, result.getName());
- final String absolutePath = new File(REPORT_FOLDER).toURI().relativize(imageFilePath.toURI()).getPath();
- if (result.getStatus() == ITestResult.SUCCESS) {
- extendTest.log(LogStatus.PASS, "Test Result : <span class='label success'>Success</span>");
- extendTest.log(LogStatus.PASS,
- "Finished the test with the following screenshot : " + extendTest.addScreenCapture(absolutePath));
- csvReport.writeRow(result.getName(), sb.toString(), "PASS");
- } else if (result.getStatus() == ITestResult.FAILURE || result.getStatus() == ITestResult.SKIP) {
- extendTest.log(LogStatus.ERROR, "ERROR - The following exepction occured");
- extendTest.log(LogStatus.ERROR, result.getThrowable());
- extendTest.log(LogStatus.ERROR,
- "Failure is described in the following screenshot : " + extendTest.addScreenCapture(absolutePath));
- extendTest.log(LogStatus.FAIL, "<span class='label failure'>Failure</span>");
- csvReport.writeRow(result.getName(), sb.toString(), "FAIL");
- }
-
- extentReport.endTest(extendTest);
- extentReport.flush();
-
- quitBrowser();
-// deleteCreatedComponents2(getCatalogAsMap());
- }
-
- @AfterClass(alwaysRun = true)
- public void afterSuite() {
- csvReport.closeFile();
- }
-
- /*************************************/
-
- private Map<String, ArrayList<Component>> getCatalogAsMap() throws IOException {
- RestResponse catalog = CatalogRestUtils.getCatalog(getUser().getUserId());
- Map<String, ArrayList<Component>> convertCatalogResponseToJavaObject = ResponseParser
- .convertCatalogResponseToJavaObject(catalog.getResponse());
- return convertCatalogResponseToJavaObject;
- }
-
- private void deleteCreatedComponents2(Map<String, ArrayList<Component>> convertCatalogResponseToJavaObject)
- throws IOException {
- final String userId = getUser().getUserId();
- ArrayList<Component> resourcesArrayList = convertCatalogResponseToJavaObject.get("resources");
-
- List<String> collect = resourcesArrayList.stream().filter(s -> s.getName().startsWith("ci"))
- .map(e -> e.getUniqueId()).collect(Collectors.toList());
- for (String uId : collect) {
- ResourceRestUtils.deleteResource(uId, userId);
- }
-
- resourcesArrayList = convertCatalogResponseToJavaObject.get("services");
- collect = resourcesArrayList.stream().filter(s -> s.getName().startsWith("ci")).map(e -> e.getUniqueId())
- .collect(Collectors.toList());
- for (String uId : collect) {
- ServiceRestUtils.deleteServiceById(uId, userId);
- }
-
- resourcesArrayList = convertCatalogResponseToJavaObject.get("products");
- collect = resourcesArrayList.stream().filter(s -> s.getName().startsWith("ci")).map(e -> e.getUniqueId())
- .collect(Collectors.toList());
- for (String uId : collect) {
- ProductRestUtils.deleteProduct(uId, userId);
- }
-
- }
-
- /**************** MAIN ****************/
- public static void main(String[] args) {
- System.out.println("---------------------");
- System.out.println("running test from CLI");
- System.out.println("---------------------");
-
- String attsdcFilePath = FileHandling.getBasePath() + File.separator + "conf" + File.separator + "sdc.yaml";
- System.setProperty("config.resource", attsdcFilePath);
- System.out.println("sdc.yaml file path is : " + attsdcFilePath);
-
- Object[] testSuitsList = FileHandling
- .getFileNamesFromFolder(FileHandling.getBasePath() + File.separator + "testSuites", ".xml");
- if (testSuitsList != null) {
- System.out.println(String.format("Found %s testSuite(s)", testSuitsList.length));
- args = Arrays.copyOf(testSuitsList, testSuitsList.length, String[].class);
- StartTest.main(args);
- }
- }
-
- /***********************************************************************************/
-
- protected static String setUrl() {
- url = config.getUrl();
- if (url == null) {
- String message = "no URL found";
- System.out.println(message);
- Assert.fail(message);
- } else if (!url.contains("localhost") && !url.contains("127.0.0.1")) {
- localEnv = false;
- }
- return url;
- }
-
- private Map<String, String> loadCredentialsFile() throws Exception {
- File credentialsFile = new File(
- FileHandling.getBasePath() + File.separator + "conf" + File.separator + CREDENTIALS_FILE);
- if (!credentialsFile.exists()) {
- credentialsFile = new File(FileHandling.getConfFilesPath() + CREDENTIALS_FILE);
- }
- credentialsYamlFileMap = (Map<String, String>) FileHandling.parseYamlFile(credentialsFile.getAbsolutePath());
- 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 UserCredentials updateUserUserId(String role) throws Exception {
- System.out.println("updating...");
- UserCredentials designerCredentialsFromFile = null;
- UserCredentials testerCredentialsFromFile = null;
- UserCredentials adminCredentialsFromFile = null;
- UserCredentials opsCredentialsFromFile = null;
- UserCredentials governorCredentialsFromFile = null;
- UserCredentials productCredentialsFromFile = null;
- UserCredentials productManagerCredentialsFromFile = null;
-
- String lowerCaseRole = role.toLowerCase();
- try {
- if (lowerCaseRole.equals("designer")) {
- designerCredentialsFromFile = getUserCredentialsFromFile("designer");
- designerUser.setUserId(designerCredentialsFromFile.getUserId());
- designerUser.setFirstName(designerCredentialsFromFile.getFirstName());
- designerUser.setLastName(designerCredentialsFromFile.getLastName());
- return designerCredentialsFromFile;
- } else if (lowerCaseRole.equals("tester")) {
- testerCredentialsFromFile = getUserCredentialsFromFile("tester");
- testerUser.setUserId(testerCredentialsFromFile.getUserId());
- testerUser.setFirstName(testerCredentialsFromFile.getFirstName());
- testerUser.setLastName(testerCredentialsFromFile.getLastName());
- return testerCredentialsFromFile;
- } else if (lowerCaseRole.equals("admin")) {
- adminCredentialsFromFile = getUserCredentialsFromFile("admin");
- adminUser.setUserId(adminCredentialsFromFile.getUserId());
- adminUser.setFirstName(adminCredentialsFromFile.getFirstName());
- adminUser.setLastName(adminCredentialsFromFile.getLastName());
- return adminCredentialsFromFile;
- } else if (lowerCaseRole.equals("ops")) {
- opsCredentialsFromFile = getUserCredentialsFromFile("ops");
- opsUser.setUserId(opsCredentialsFromFile.getUserId());
- opsUser.setFirstName(opsCredentialsFromFile.getFirstName());
- opsUser.setLastName(opsCredentialsFromFile.getLastName());
- return opsCredentialsFromFile;
- } else if (lowerCaseRole == "governor") {
- governorCredentialsFromFile = getUserCredentialsFromFile("governor");
- governorUser.setUserId(governorCredentialsFromFile.getUserId());
- governorUser.setFirstName(governorCredentialsFromFile.getFirstName());
- governorUser.setLastName(governorCredentialsFromFile.getLastName());
- return governorCredentialsFromFile;
- } else if (lowerCaseRole == "product_local") {
- productCredentialsFromFile = getUserCredentialsFromFile("product_local");
- productManagerUser.setUserId(productCredentialsFromFile.getUserId());
- productManagerUser.setFirstName(productCredentialsFromFile.getFirstName());
- productManagerUser.setLastName(productCredentialsFromFile.getLastName());
- return productCredentialsFromFile;
- } else if (lowerCaseRole == "product_manager") {
- productManagerCredentialsFromFile = getUserCredentialsFromFile("product_manager");
- productManagerUser.setUserId(productManagerCredentialsFromFile.getUserId());
- productManagerUser.setFirstName(productManagerCredentialsFromFile.getFirstName());
- productManagerUser.setLastName(productManagerCredentialsFromFile.getLastName());
- return productManagerCredentialsFromFile;
- }
- }
-
- catch (Exception e) {
- System.out.print("An exception occured...");
- System.out.println("->exception message is : " + e.getMessage());
- }
-
- return null;
- }
-
- public static void navigateToUrl(String url) throws Exception {
-
- try {
- WebDriver driver = GeneralUIUtils.getDriver();
- System.out.println("navigating to URL :" + url);
- driver.manage().window().maximize();
- driver.manage().deleteAllCookies();
- driver.navigate().to(url);
- GeneralUIUtils.windowZoomOut();
- GeneralUIUtils.waitForLoader();
- } catch (Exception e) {
- System.out.println("browser is unreachable");
- extendTest.log(LogStatus.ERROR, "browser is unreachable");
- Assert.fail("browser is unreachable");
- }
- }
-
- protected void loginToSystem(UserCredentials credentials, UserRoleEnum role) throws Exception {
-
- sendUserAndPasswordKeys(credentials);
- refreshAttempts = (refreshAttempts == 0) ? NUM_OF_ATTEMPTS_TO_REFTRESH : refreshAttempts;
- if (!getRole().equals(UserRoleEnum.ADMIN)) {
- try {
- if(!localEnv){
-// GeneralUIUtils.ultimateWait();
- WebDriverWait wait = new WebDriverWait(GeneralUIUtils.getDriver(), 3 * 60);
- WebElement sdcApp = wait.until(ExpectedConditions.elementToBeClickable(By.id("app-image-SDC")));
- sdcApp.click();
- GeneralUIUtils.getDriver().switchTo().frame(1);
- GeneralUIUtils.waitFordataTestIdVisibility("main-menu-input-search");
- }
- else{
- enterToUserWorkspace();
- }
-
- } catch (Exception e) {
- refreshAttempts--;
- if (refreshAttempts <= 0) {
- System.out.println("ERR : Something is wrong with browser!");
- Assert.fail("ERR : Something is wrong with browser!");
- }
- System.out.println("trying again...");
- System.out.println(String.format("%s attempt(s) left", refreshAttempts));
- extendTest.log(LogStatus.INFO, "trying again...");
- extendTest.log(LogStatus.INFO, String.format("%s attempt(s) left", refreshAttempts));
-
- quitAndReLogin(role);
- }
- }
- }
-
- private void sendUserAndPasswordKeys(UserCredentials userId) {
-
- if (localEnv){
- System.out.println("Login with user : " + userId.getUserId());
- WebElement userNameTextbox = GeneralUIUtils.waitForElementVisibility(By.name("userid"));
- userNameTextbox.sendKeys(userId.getUserId());
- WebElement passwordTextbox = GeneralUIUtils.waitForElementVisibility(By.name("password"));
- passwordTextbox.sendKeys(userId.getPassword());
-
- WebElement submitButton = GeneralUIUtils.waitForElementVisibility(By.name("btnSubmit"));
- submitButton.click();
- WebElement buttonOK = GeneralUIUtils.waitForElementVisibility(By.name("successOK"));
- AssertJUnit.assertTrue(buttonOK.isDisplayed());
- buttonOK.click();
- }
- else
- {
- System.out.println("Login with user : " + userId.getUserId());
- WebElement userNameTextbox = GeneralUIUtils.getDriver().findElement(By.cssSelector("input[type='text']"));
- userNameTextbox.sendKeys(userId.getUserId());
- WebElement passwordTextbox = GeneralUIUtils.getDriver().findElement(By.cssSelector("input[type='password']"));
- passwordTextbox.sendKeys(userId.getPassword());
-
- GeneralUIUtils.getDriver().findElement(By.id("loginBtn")).click();
- }
-
-
- }
-
- public static String getUrl() {
- return url;
- }
-
- public static void setUrl(String url) {
- SetupCDTest.url = url;
- }
-
- public static Config getConfig() {
- return config;
- }
-
- public void loginToSystem(UserRoleEnum role){
- WebDriver driver = GeneralUIUtils.getDriver();
- WebDriverWait wait = new WebDriverWait(driver, 30);
-
- wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.xpath("//*[@method='" + "post" + "']"))));
-
- WebElement userIdTextbox = GeneralUIUtils.waitForElementVisibility(By.name("userId"));
- userIdTextbox.sendKeys(role.getUserId());
- WebElement passwordTextbox = GeneralUIUtils.waitForElementVisibility(By.name("password"));
- passwordTextbox.sendKeys("123123a");
-
- wait.until(ExpectedConditions.elementToBeClickable(driver.findElement(By.xpath("//*[@value='" + "Submit" + "']")))).click();
-
- GeneralUIUtils.waitForLoader();
- }
-
- public void loginWithUser(UserRoleEnum role) {
- setUser(role);
- try {
- navigateToUrl(url);
- extendTest.log(LogStatus.INFO, String.format("login with user %s", role.name().toUpperCase()));
- if (localEnv) {
- loginToSystem(role);
- enterToUserWorkspace();
- }
- else{
- loadCredentialsFile();
- UserCredentials credentials = getUserCredentialsFromFile(role.name().toLowerCase());
- loginToSystem(credentials, role);
- user = credentials;
- }
-
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
-
- private void enterToUserWorkspace() {
- WebElement enterToUserWorkspaceButton = GeneralUIUtils.waitForElementVisibility(By.className("asdc-welcome-main-back-btn"), 3 * 60);
- enterToUserWorkspaceButton.click();
- System.out.println("Entering to system...");
- GeneralUIUtils.waitForLoader();
- }
-
- private void setUser(UserRoleEnum role) {
- user = new User();
- user.setUserId(role.getUserId());
- user.setFirstName(role.getFirstName());
- user.setRole(role.name());
- user.setLastName(role.getLastName());
- }
-
- public User getUser() {
- return user;
- }
-
- protected void setBrowserBeforeTest(UserRoleEnum role) {
- refreshAttempts = 0;
- System.out.println(String.format("Setup before test as %s", role.toString().toUpperCase()));
- GeneralUIUtils.initDriver();
- loginWithUser(role);
- }
-
- public User getUser(UserRoleEnum role) {
- User user = new User();
- user = new User();
- user.setUserId(role.getUserId());
- user.setFirstName(role.getFirstName());
- user.setRole(role.name());
- return user;
- }
-
- protected void quitAndReLogin(UserRoleEnum role) throws Exception {
- quitBrowser();
- if (localEnv) {
- loginToSystem(role);
- }
- setBrowserBeforeTest(role);
- }
-
- private void quitBrowser() {
- System.out.println("Closing browser...");
- GeneralUIUtils.getDriver().quit();
- }
-
-
- protected String getRandomComponentName(String prefix) {
- return prefix + randomNumber();
- }
-
- protected int randomNumber() {
- Random r = new Random();
- return r.nextInt(10000);
- }
-
-}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ComponentLeftMenu.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ComponentLeftMenu.java
deleted file mode 100644
index d795599f24..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ComponentLeftMenu.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.pages;
-
-public interface ComponentLeftMenu {
-
-}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/CompositionPage.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/CompositionPage.java
deleted file mode 100644
index e515ce9d64..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/CompositionPage.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.pages;
-
-import java.util.List;
-
-import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum;
-import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils;
-import org.openqa.selenium.WebElement;
-
-public class CompositionPage extends GeneralPageElements {
-
- public CompositionPage() {
- super();
- }
-
- public static void searchForElement(String elementName) {
- WebElement searchField = GeneralUIUtils.getWebElementWaitForVisible("searchAsset");
- searchField.clear();
- searchField.sendKeys(elementName);
- GeneralUIUtils.waitForLoader();
- GeneralUIUtils.sleep(500);
- }
-
- public static void showDeploymentArtifactTab() {
- GeneralUIUtils.waitFordataTestIdVisibility("deployment-artifact-tab").click();
- GeneralUIUtils.waitForLoader();
- }
-
- public static void showPropertiesAndAttributesTab() {
- GeneralUIUtils.waitFordataTestIdVisibility("properties-and-attributes-tab").click();
- GeneralUIUtils.waitForLoader();
- }
-
- public static List<WebElement> getProperties() {
- return PropertiesPage.getElemenetsFromTable();
- }
-}
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
deleted file mode 100644
index 4c4edd8684..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/DeploymentArtifactPage.java
+++ /dev/null
@@ -1,91 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.pages;
-
-import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum;
-import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils;
-import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
-import org.openqa.selenium.WebElement;
-
-public class DeploymentArtifactPage extends GeneralPageElements {
-
- public DeploymentArtifactPage() {
- super();
- }
-
- public static ResourceLeftMenu getLeftPanel() {
- return new ResourceLeftMenu();
- }
-
- public static UploadArtifactPopup artifactPopup() {
- return new UploadArtifactPopup();
- }
-
- protected static void addNewArtifact(ArtifactGroupTypeEnum artifactGroupType) {
- switch (artifactGroupType) {
- case DEPLOYMENT:
- GeneralUIUtils.getWebButton(DataTestIdEnum.ArtifactPageEnum.ADD_DEPLOYMENT_ARTIFACT.getValue()).click();
- break;
- case INFORMATIONAL:
- GeneralUIUtils.getWebButton(DataTestIdEnum.ArtifactPageEnum.ADD_INFORMATIONAL_ARTIFACT.getValue()).click();
- break;
- default:
- break;
- }
- }
-
- public static void clickAddNewArtifact() {
- addNewArtifact(ArtifactGroupTypeEnum.DEPLOYMENT);
- }
-
- public static void clickAddAnotherArtifact() {
- GeneralUIUtils.getWebButton(DataTestIdEnum.ArtifactPageEnum.ADD_ANOTHER_ARTIFACT.getValue()).click();
- }
-
- public static void clickEditArtifact(String artifactLabel) {
- GeneralUIUtils.getWebButton(DataTestIdEnum.ArtifactPageEnum.EDIT_ARTIFACT.getValue() + artifactLabel).click();
- }
-
- public static void clickDeleteArtifact(String artifactLabel) {
- GeneralUIUtils.getWebButton(DataTestIdEnum.ArtifactPageEnum.DELETE_ARTIFACT.getValue() + artifactLabel).click();
- }
-
- public static void clickDownloadArtifact(String artifactLabel) {
- GeneralUIUtils.getWebButton(DataTestIdEnum.ArtifactPageEnum.DOWNLOAD_ARTIFACT.getValue() + artifactLabel)
- .click();
- }
-
- public static String getArtifactDescription(String artifactLabel) throws Exception {
- clickOnArtifact(artifactLabel); // open artifact
- WebElement artifactDescriptionElement = GeneralUIUtils.getWebElementWaitForVisible(
- DataTestIdEnum.ArtifactPageEnum.GET_DEPLOYMENT_ARTIFACT_DESCRIPTION.getValue());
- String artifactDesc = artifactDescriptionElement.getText();
- clickOnArtifact(artifactLabel); // close artifact
-
- return artifactDesc;
- }
-
- public static void clickOnArtifact(String artifactLabel) throws Exception {
- GeneralUIUtils.getWebButton(artifactLabel).click();
- GeneralUIUtils.waitForLoader();
- }
-
-}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/GeneralPageElements.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/GeneralPageElements.java
deleted file mode 100644
index fea3843b7a..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/GeneralPageElements.java
+++ /dev/null
@@ -1,139 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.pages;
-
-import static org.testng.AssertJUnit.assertTrue;
-import java.util.List;
-import java.util.function.Supplier;
-
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum;
-import org.openecomp.sdc.ci.tests.datatypes.LifeCycleStateEnum;
-import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest;
-import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils;
-import org.openqa.selenium.By;
-import org.openqa.selenium.WebElement;
-
-import com.relevantcodes.extentreports.LogStatus;
-
-public class GeneralPageElements {
-
- public GeneralPageElements() {
- super();
- }
-
- public static ResourceLeftMenu getLeftMenu() {
- return new ResourceLeftMenu();
- }
-
- public static void clickCreateButton() {
- SetupCDTest.getExtendTest().log(LogStatus.INFO, "creating...");
- GeneralUIUtils.getWebButton(DataTestIdEnum.GeneralElementsEnum.CREATE_BUTTON.getValue()).click();
- GeneralUIUtils.waitForLoader();
- }
-
- public static void clickCheckinButton(String componentName) throws Exception {
- SetupCDTest.getExtendTest().log(LogStatus.INFO, "clicking on checkin");
- GeneralUIUtils.getWebButton(DataTestIdEnum.GeneralElementsEnum.CHECKIN_BUTTON.getValue()).click();
- GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.ModalItems.ACCEP_TESTING_MESSAGE.getValue())
- .sendKeys("Checkin " + componentName);
- GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.ModalItems.OK.getValue()).click();
- GeneralUIUtils.waitForLoader();
- assertTrue(GeneralUIUtils.getWebElementWaitForVisible("formlifecyclestate").getText()
- .equals(LifeCycleStateEnum.CHECKIN.getValue()));
- }
-
- public static void clickSubmitForTestingButton(String componentName) throws Exception {
- try {
- SetupCDTest.getExtendTest().log(LogStatus.INFO, "submiting for testing");
- GeneralUIUtils
- .getWebElementWaitForVisible(DataTestIdEnum.LifeCyleChangeButtons.SUBMIT_FOR_TESTING.getValue())
- .click();
- GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.ModalItems.SUMBIT_FOR_TESTING_MESSAGE.getValue())
- .sendKeys("Submit for testing for " + componentName);
- GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.ModalItems.OK.getValue()).click();
- GeneralUIUtils.waitForLoader();
- GeneralUIUtils.sleep(2000);
- GeneralUIUtils.getWebElementWaitForVisible("main-menu-input-search");
- } catch (Exception e) {
- throw e;
- }
- }
-
- public static void clickDeleteVersionButton() {
- GeneralUIUtils.getWebButton(DataTestIdEnum.GeneralElementsEnum.DELETE_VERSION_BUTTON.getValue()).click();
- }
-
- public static void clickRevertButton() {
- GeneralUIUtils.getWebButton(DataTestIdEnum.GeneralElementsEnum.REVERT_BUTTON.getValue()).click();
- }
-
- public static String getLifeCycleState() {
- return GeneralUIUtils.getWebButton(DataTestIdEnum.GeneralElementsEnum.LIFECYCLE_STATE.getValue()).getText();
- }
-
- public static void selectVersion(String version) {
- GeneralUIUtils.getSelectList(version, DataTestIdEnum.GeneralElementsEnum.VERSION_HEADER.getValue());
- }
-
- public static List<WebElement> getElemenetsFromTable() {
- GeneralUIUtils.waitForLoader();
- return GeneralUIUtils.getElemenetsFromTable(By.className("flex-container"));
- }
-
- public static boolean checkElementsCountInTable(int expectedElementsCount) {
- // int maxWaitingPeriodMS = 1000;
- // int napPeriodMS = 100;
- // int sumOfWaiting = 0;
- // List<WebElement> elememts = null;
- // boolean isKeepWaiting = false;
- // while (!isKeepWaiting){
- // GeneralUIUtils.sleep(napPeriodMS);
- // sumOfWaiting += napPeriodMS;
- // elememts = getElemenetsFromTable();
- // isKeepWaiting = ( expectedElementsCount == elememts.size() );
- // if (sumOfWaiting > maxWaitingPeriodMS)
- // return false;
- // }
- //
- // return true;
- SetupCDTest.getExtendTest().log(LogStatus.INFO, "checking number of elements in table");
- return checkElementsCountInTable(expectedElementsCount, () -> getElemenetsFromTable());
- }
-
- public static boolean checkElementsCountInTable(int expectedElementsCount, Supplier<List<WebElement>> func) {
- int maxWaitingPeriodMS = 10000;
- int napPeriodMS = 100;
- int sumOfWaiting = 0;
- List<WebElement> elements = null;
- boolean isKeepWaiting = false;
- while (!isKeepWaiting) {
- GeneralUIUtils.sleep(napPeriodMS);
- sumOfWaiting += napPeriodMS;
- elements = func.get();
- isKeepWaiting = (expectedElementsCount == elements.size());
- if (sumOfWaiting > maxWaitingPeriodMS)
- return false;
- }
- return true;
- }
-
-}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/GovernorOperationPage.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/GovernorOperationPage.java
deleted file mode 100644
index 9e7eaf1497..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/GovernorOperationPage.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.pages;
-
-import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum;
-import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest;
-import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils;
-
-import com.relevantcodes.extentreports.LogStatus;
-
-public class GovernorOperationPage {
-
- public GovernorOperationPage() {
- super();
- }
-
- public static void approveSerivce(String serviceName) {
- SetupCDTest.getExtendTest().log(LogStatus.INFO, "approving distrbution the service " + serviceName);
- GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.DistributionChangeButtons.APPROVE.getValue()).click();
- GeneralUIUtils.waitForLoader();
- GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.DistributionChangeButtons.APPROVE_MESSAGE.getValue())
- .sendKeys("service " + serviceName + " tested successfuly");
- GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.ModalItems.OK.getValue()).click();
- GeneralUIUtils.waitForLoader();
- GeneralUIUtils.getWebElementWaitForVisible("main-menu-input-search");
- }
-
-}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/IconPage.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/IconPage.java
deleted file mode 100644
index 240272ae30..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/IconPage.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.pages;
-
-import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum;
-import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum;
-import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils;
-
-public class IconPage extends GeneralPageElements {
-
- public IconPage() {
- super();
- }
-
- public static void clickOnIcon(ResourceCategoryEnum iconName) {
- GeneralUIUtils.getWebButton(iconStringBuilder(iconName) + DataTestIdEnum.ServiceMetadataEnum.ICON.getValue())
- .click();
- }
-
- private static String iconStringBuilder(ResourceCategoryEnum icon) {
- String iconName = icon.getSubCategory();
- String[] splitedIconName = iconName.split(" ");
- splitedIconName[0] = splitedIconName[0].toLowerCase();
-
- StringBuilder sb = new StringBuilder();
- for (String word : splitedIconName) {
- sb.append(word);
- }
-
- return sb.toString();
- }
-
-}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/InformationalArtifactPage.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/InformationalArtifactPage.java
deleted file mode 100644
index 1dbf4dfa61..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/InformationalArtifactPage.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.pages;
-
-import java.util.List;
-
-import javax.lang.model.util.Elements;
-
-import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum;
-import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils;
-import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
-import org.openqa.selenium.By;
-import org.openqa.selenium.WebElement;
-
-public class InformationalArtifactPage extends DeploymentArtifactPage {
-
- public InformationalArtifactPage() {
- super();
- }
-
- public static void clickAddNewArtifact() {
- addNewArtifact(ArtifactGroupTypeEnum.INFORMATIONAL);
- }
-
- public static String getArtifactDescription(String artifactName) throws Exception {
- clickOnArtifact(artifactName);
- String artifactDesc = GeneralUIUtils.getWebElementWaitForVisible(
- artifactName + DataTestIdEnum.ArtifactPageEnum.GET_INFORMATIONAL_ARTIFACT_DESCRIPTION.getValue())
- .getText();
- clickOnArtifact(artifactName); // close artifact
- return artifactDesc;
- }
-
- public static List<WebElement> getElemenetsFromTable() {
- return GeneralUIUtils.getWebElementsListByDataTestId("InformationalArtifactRow");
- }
-
-}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/OpsOperationPage.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/OpsOperationPage.java
deleted file mode 100644
index e7151078f9..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/OpsOperationPage.java
+++ /dev/null
@@ -1,183 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.pages;
-
-import static org.testng.AssertJUnit.assertEquals;
-
-import java.util.Iterator;
-import java.util.List;
-
-import org.junit.Assert;
-import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum;
-import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.StepsEnum;
-import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest;
-import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils;
-import org.openqa.selenium.By;
-import org.openqa.selenium.WebElement;
-import org.openqa.selenium.support.ui.ExpectedConditions;
-import org.openqa.selenium.support.ui.WebDriverWait;
-
-import com.relevantcodes.extentreports.LogStatus;
-
-public class OpsOperationPage {
-
- public OpsOperationPage() {
- super();
- }
-
- public static void distributeService() {
- SetupCDTest.getExtendTest().log(LogStatus.INFO, "distributing...");
- clickOnButton(DataTestIdEnum.DistributionChangeButtons.DISTRIBUTE);
- GeneralUIUtils.getWebButton(DataTestIdEnum.DistributionChangeButtons.MONITOR.getValue());
- }
-
- public static void displayMonitor() {
- SetupCDTest.getExtendTest().log(LogStatus.INFO, "clicking on monitor button");
- // clickOnButton(DataTestIdEnum.DistributionChangeButtons.MONITOR);
- GeneralUIUtils.moveToStep(StepsEnum.MONITOR);
- }
-
- public static void re_distributeService() {
- SetupCDTest.getExtendTest().log(LogStatus.INFO, "redistributing...");
- clickOnButton(DataTestIdEnum.DistributionChangeButtons.RE_DISTRIBUTE);
- GeneralUIUtils.getWebButton(DataTestIdEnum.DistributionChangeButtons.MONITOR.getValue());
- }
-
- private static void clickOnButton(DataTestIdEnum.DistributionChangeButtons button) {
- GeneralUIUtils.getWebElementWaitForVisible(button.getValue()).click();
- GeneralUIUtils.waitForLoader();
- }
-
- public static List<WebElement> getRowsFromMonitorTable() {
- SetupCDTest.getExtendTest().log(LogStatus.INFO, "getting number of rows from distribution table");
- GeneralPageElements.checkElementsCountInTable(1, () -> GeneralUIUtils.waitForElementsListVisibility("ditributionTable"));
- List<WebElement> distributionRecords = GeneralUIUtils.waitForElementsListVisibility("ditributionTable");
- List<WebElement> findElements = distributionRecords.get(0).findElements(By.className("w-sdc-distribute-parent-block"));
- return findElements;
-
-
-
- }
-
- public static void showDistributionStatus(int rowIndex) {
- GeneralUIUtils.getWebElementWaitForVisible("ShowRecordButton_" + String.valueOf(rowIndex)).click();
- GeneralUIUtils.waitForLoader();
- }
-
- public static String getTotalArtifactsSum(int rowIndex) {
- return GeneralUIUtils.waitFordataTestIdVisibility("totalArtifacts_" + String.valueOf(rowIndex)).getText();
- }
-
- public static String getNotifiedArtifactsSum(int rowIndex) {
- return GeneralUIUtils.waitFordataTestIdVisibility("notified_" + String.valueOf(rowIndex)).getText();
- }
-
- public static String getDownloadedArtifactsSum(int rowIndex) {
- return GeneralUIUtils.waitFordataTestIdVisibility("downloaded_" + String.valueOf(rowIndex)).getText();
- }
-
- public static String getDeployedArtifactsSum(int rowIndex) {
- return GeneralUIUtils.waitFordataTestIdVisibility("deployed_" + String.valueOf(rowIndex)).getText();
- }
-
- public static String getNotNotifiedArtifactsSum(int rowIndex) {
- return GeneralUIUtils.waitFordataTestIdVisibility("NotNotified_" + String.valueOf(rowIndex)).getText();
- }
-
- public static String getErrorsSum(int rowIndex) {
- return GeneralUIUtils.waitFordataTestIdVisibility("errors_" + String.valueOf(rowIndex)).getText();
- }
-
- public static void clickRefreshTableButton(int rowIndex) {
- // SetupCDTest.getExtendTest().log(LogStatus.INFO, "refreshing
- // distribution table");
- GeneralUIUtils.getWebElementWaitForVisible("refreshButton").click();
-
- // wait until total artifacts field disappear
- WebDriverWait wait = new WebDriverWait(GeneralUIUtils.getDriver(), 30);
- wait.until(ExpectedConditions.invisibilityOfElementLocated(
- By.xpath("//*[@data-tests-id='" + "totalArtifacts_" + String.valueOf(rowIndex) + "']")));
- }
-
- public static void waitUntilArtifactsDistributed(int rowIndex) throws Exception {
- waitUntilArtifactsDistributed("0", 0);
- }
-
- public static void waitUntilArtifactsDistributed(String expectedArtifactsSum, int rowIndex) throws Exception {
- SetupCDTest.getExtendTest().log(LogStatus.INFO, "waiting until all artifacts distributed");
- boolean isKeepWaiting = true;
- int maxWaitingPeriodMS = 5 * 60 * 1000;
- int sumWaitingTime = 0;
- int napPeriod = 1000;
- while (isKeepWaiting) {
- showDistributionStatus(rowIndex);
- String actualTotalArtifactsSize = getTotalArtifactsSum(rowIndex);
- String actualNotifiedArtifactsSize = getNotifiedArtifactsSum(rowIndex);
- String actualDownloadedArtifactsSize = getDownloadedArtifactsSum(rowIndex);
- String actualDeployedArtifactsSize = getDeployedArtifactsSum(rowIndex);
- String actualNotNotifedArtifactsSize = getNotNotifiedArtifactsSum(rowIndex);
- isKeepWaiting = !actualTotalArtifactsSize.equals(actualDownloadedArtifactsSize)
- || !actualTotalArtifactsSize.equals(actualNotifiedArtifactsSize)
- || !actualTotalArtifactsSize.equals(actualDeployedArtifactsSize)
- || actualTotalArtifactsSize.equals("0") || actualDownloadedArtifactsSize.equals("0")
- || actualNotifiedArtifactsSize.equals("0") || actualDeployedArtifactsSize.equals("0");
- // isKeepWaiting =
- // !expectedArtifactsSum.equals(actualTotalArtifactsSize) &&
- // !expectedArtifactsSum.equals(actualNotifiedArtifactsSize) &&
- // !expectedArtifactsSum.equals(actualDownloadedArtifactsSize) &&
- // !expectedArtifactsSum.equals(actualDeployedArtifactsSize) &&
- // actualNotNotifedArtifactsSize.equals("0");
- // if (Integer.valueOf(actualTotalArtifactsSize) >
- // Integer.valueOf(expectedArtifactsSum)){
- // isKeepWaiting = false;
- // throw new Exception(String.format("MORE ARTIFACTS THEN EXPECTED -
- // actual: %s, expected: %s", actualTotalArtifactsSize,
- // expectedArtifactsSum));
- //// Assert.fail(String.format("MORE ARTIFACTS THEN EXPECTED -
- // actual: %s, expected: %s", actualTotalArtifactsSize,
- // expectedArtifactsSum));
- // }
- if (isKeepWaiting) {
-
- if (Integer.parseInt(actualNotNotifedArtifactsSize) > 1) {
- SetupCDTest.getExtendTest().log(LogStatus.INFO, "Some artifacts are not notified...");
- isKeepWaiting = false;
- throw new Exception("Some artifacts are not notified... check distribution client");
- }
-
- GeneralUIUtils.sleep(napPeriod);
- sumWaitingTime += napPeriod;
-
- if (sumWaitingTime > maxWaitingPeriodMS) {
- SetupCDTest.getExtendTest().log(LogStatus.FAIL, "not all artifacts are displayed");
- isKeepWaiting = false;
- throw new Exception(String.format("NOT ALL ARTIFACTS ARE DISPLAYED WITHIN %s SECONDS",
- String.valueOf(maxWaitingPeriodMS / 1000)));
- }
-
- clickRefreshTableButton(rowIndex);
- }
- }
-
- SetupCDTest.getExtendTest().log(LogStatus.PASS, "all artifacts are distributed successfully");
- }
-
-}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/PropertiesPage.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/PropertiesPage.java
deleted file mode 100644
index 614fa0a81a..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/PropertiesPage.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.pages;
-
-import java.util.List;
-
-import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum;
-import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils;
-import org.openqa.selenium.By;
-import org.openqa.selenium.WebElement;
-
-public class PropertiesPage extends GeneralPageElements {
-
- public PropertiesPage() {
- super();
- }
-
- public static List<WebElement> getElemenetsFromTable() {
- return GeneralUIUtils.getWebElementsListByDataTestId(DataTestIdEnum.PropertiesPageEnum.PROPERTY_ROW.getValue());
- }
-
- public static void clickAddPropertyArtifact() {
- GeneralUIUtils.getWebButton(DataTestIdEnum.PropertiesPageEnum.ADD_NEW_PROPERTY.getValue()).click();
- }
-
- public static void clickEditPropertyArtifact(String propertyName) {
- GeneralUIUtils.getWebButton(DataTestIdEnum.PropertiesPageEnum.EDIT_PROPERTY.getValue() + propertyName).click();
- }
-
- public static void clickDeletePropertyArtifact(String propertyName) {
- GeneralUIUtils.getWebButton(DataTestIdEnum.PropertiesPageEnum.DELETE_PROPERTY.getValue() + propertyName)
- .click();
- }
-
- public static void clickOnProperty(String propertyName) {
- GeneralUIUtils.getWebButton(propertyName).click();
- }
-
- public static PropertyPopup getPropertyPopup() {
- return new PropertyPopup();
- }
-
-}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/PropertyPopup.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/PropertyPopup.java
deleted file mode 100644
index 11cbea3093..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/PropertyPopup.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.pages;
-
-import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum;
-import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils;
-import org.openqa.selenium.WebElement;
-
-public class PropertyPopup {
-
- public PropertyPopup() {
- }
-
- public void insertPropertyName(String name) {
- WebElement propertyNameField = GeneralUIUtils
- .getWebElementWaitForVisible(DataTestIdEnum.PropertiesPageEnum.PROPERTY_NAME.getValue());
- propertyNameField.clear();
- propertyNameField.sendKeys(name);
- }
-
- public void insertPropertyDefaultValue(String value) {
- WebElement propertyValue = GeneralUIUtils
- .getWebElementWaitForVisible(DataTestIdEnum.PropertiesPageEnum.PROPERTY_VALUE.getValue());
- propertyValue.clear();
- propertyValue.sendKeys(value);
- }
-
- public void insertPropertyDescription(String description) {
- WebElement propertyDescription = GeneralUIUtils
- .getWebElementWaitForVisible(DataTestIdEnum.PropertiesPageEnum.PROPERTY_DESCRIPTION.getValue());
- propertyDescription.clear();
- propertyDescription.sendKeys(description);
- }
-
- public void selectPropertyType(String propertyType) {
- GeneralUIUtils.getSelectList(propertyType, DataTestIdEnum.PropertiesPageEnum.PROPERTY_TYPE.getValue());
- }
-
- public void clickAdd() {
- GeneralUIUtils.getWebButton(DataTestIdEnum.PropertiesPageEnum.ADD.getValue()).click();
- GeneralUIUtils.waitForLoader();
- }
-
- public void clickSave() {
- GeneralUIUtils.getWebButton(DataTestIdEnum.PropertiesPageEnum.SAVE.getValue()).click();
- GeneralUIUtils.waitForLoader();
- }
-
- public void clickCancel() {
- GeneralUIUtils.getWebButton(DataTestIdEnum.PropertiesPageEnum.CANCEL.getValue()).click();
- GeneralUIUtils.waitForLoader();
- }
-
- public void clickDone() {
- GeneralUIUtils.getWebButton(DataTestIdEnum.PropertiesPageEnum.DONE.getValue()).click();
- GeneralUIUtils.waitForLoader();
- }
-
-}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ResourceGeneralPage.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ResourceGeneralPage.java
deleted file mode 100644
index 2494282e1c..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ResourceGeneralPage.java
+++ /dev/null
@@ -1,154 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.pages;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.ci.tests.datatypes.ComponentReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum;
-import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.enums.ComponentType;
-import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils;
-import org.openecomp.sdc.ci.tests.utilities.ResourceUIUtils;
-import org.openqa.selenium.Keys;
-import org.openqa.selenium.WebElement;
-import org.openqa.selenium.interactions.Actions;
-import org.openqa.selenium.support.ui.Select;
-
-public class ResourceGeneralPage extends GeneralPageElements {
-
- public ResourceGeneralPage() {
- super();
- }
-
- private static WebElement getNameField() {
- return GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.ResourceMetadataEnum.RESOURCE_NAME.getValue());
- }
-
- private static WebElement getDescriptionField() {
- return GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.ServiceMetadataEnum.DESCRIPTION.getValue());
- }
-
- private static String getCategoryField() {
- return DataTestIdEnum.ResourceMetadataEnum.CATEGORY.getValue();
- }
-
- private static WebElement getVendorNameField() {
- return GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.ResourceMetadataEnum.VENDOR_NAME.getValue());
- }
-
- private static WebElement getVendorReleaseField() {
- return GeneralUIUtils
- .getWebElementWaitForVisible(DataTestIdEnum.ResourceMetadataEnum.VENDOR_RELEASE.getValue());
- }
-
- private static WebElement getTagsField() {
- return GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.ResourceMetadataEnum.TAGS.getValue());
- }
-
- private static WebElement getUserIdField() {
- return GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.ResourceMetadataEnum.CONTACT_ID.getValue());
- }
-
- /***************************************************************/
-
- public static String getNameText() {
- return getNameField().getAttribute("value");
- }
-
- public static void defineName(String resourceName) {
- WebElement resourceNameTextbox = getNameField();
- resourceNameTextbox.clear();
- resourceNameTextbox.sendKeys(resourceName);
- }
-
- public static String getDescriptionText() {
- return getDescriptionField().getAttribute("value");
- }
-
- public static void defineDescription(String description) {
- WebElement descriptionTextbox = getDescriptionField();
- descriptionTextbox.clear();
- descriptionTextbox.sendKeys(description);
- }
-
- public static String getVendorNameText() {
- return getVendorNameField().getAttribute("value");
- }
-
- public static void defineVendorName(String vendorName) {
- WebElement vendorNameTextbox = getVendorNameField();
- vendorNameTextbox.clear();
- vendorNameTextbox.sendKeys(vendorName);
- }
-
- public static String getVendorReleaseText() {
- return getVendorReleaseField().getAttribute("value");
- }
-
- public static void defineVendorRelease(String vendorRelease) {
- WebElement vendorReleaseTextbox = getVendorReleaseField();
- vendorReleaseTextbox.clear();
- vendorReleaseTextbox.sendKeys(vendorRelease);
- }
-
- public static void defineTag(String resourceTags) {
- WebElement tagTextbox = getTagsField();
- tagTextbox.clear();
- tagTextbox.sendKeys(resourceTags);
- tagTextbox.sendKeys(Keys.ENTER);
- }
-
- public static void defineTagsList(ComponentReqDetails resource, String[] resourceTags) {
- List<String> taglist = new ArrayList<String>();
- ;
- WebElement resourceTagsTextbox = getTagsField();
- for (String tag : resourceTags) {
- resourceTagsTextbox.clear();
- resourceTagsTextbox.sendKeys(tag);
- GeneralUIUtils.sleep(1000);
- resourceTagsTextbox.sendKeys(Keys.ENTER);
- taglist.add(tag);
- }
- resource.setTags(taglist);
- }
-
- public static void defineCategory(String category) {
-// GeneralUIUtils.getSelectList(category, getCategoryField());
-
- Actions action = new Actions(GeneralUIUtils.getDriver());
- action.click(GeneralUIUtils.getWebElementByDataTestId(getCategoryField()));
- action.sendKeys(category).perform();
- }
-
- public static String getUserIdContactText() {
- return getUserIdField().getAttribute("value");
- }
-
- public static void defineUserIdContact(String userId) {
- WebElement contactIdTextbox = getUserIdField();
- contactIdTextbox.clear();
- contactIdTextbox.sendKeys(userId);
- }
-
-}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ResourceLeftMenu.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ResourceLeftMenu.java
deleted file mode 100644
index bd93f18d2a..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ResourceLeftMenu.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.pages;
-
-import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.StepsEnum;
-import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils;
-
-public class ResourceLeftMenu implements ComponentLeftMenu {
-
- public void moveToGeneralScreen() throws Exception {
- GeneralUIUtils.moveToStep(StepsEnum.GENERAL);
- }
-
- public void moveToIconScreen() throws Exception {
- GeneralUIUtils.moveToStep(StepsEnum.ICON);
- }
-
- public void moveToDeploymentArtifactScreen() {
- GeneralUIUtils.moveToStep(StepsEnum.DEPLOYMENT_ARTIFACT);
- }
-
- public void moveToInformationalArtifactScreen() {
- GeneralUIUtils.moveToStep(StepsEnum.INFORMATION_ARTIFACT);
- }
-
- public void moveToPropertiesScreen() throws Exception {
- GeneralUIUtils.moveToStep(StepsEnum.PROPERTIES);
- }
-
- public void moveToCompositionScreen() throws Exception {
- GeneralUIUtils.moveToStep(StepsEnum.COMPOSITION);
- }
-
- public void moveToActivityLogScreen() throws Exception {
- GeneralUIUtils.moveToStep(StepsEnum.ACTIVITY_LOG);
- }
-
- public void moveToDeploymentViewScreen() throws Exception {
- GeneralUIUtils.moveToStep(StepsEnum.DEPLOYMENT_VIEW);
- }
-
- public void moveToToscaArtifactsScreen() {
- GeneralUIUtils.moveToStep(StepsEnum.TOSCA_ARTIFACTS);
- }
-}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ServiceGeneralPage.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ServiceGeneralPage.java
deleted file mode 100644
index 9e8c4b2265..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ServiceGeneralPage.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.pages;
-
-import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum;
-import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils;
-import org.openqa.selenium.WebElement;
-
-public class ServiceGeneralPage extends ResourceGeneralPage {
-
- public ServiceGeneralPage() {
- super();
- }
-
- public static void defineName(String serviceName) {
- WebElement serviceNameTextbox = GeneralUIUtils
- .getWebElementWaitForVisible(DataTestIdEnum.ServiceMetadataEnum.SERVICE_NAME.getValue());
- serviceNameTextbox.clear();
- serviceNameTextbox.sendKeys(serviceName);
- }
-
- public static void defineProjectCode(String pmat) {
- WebElement projectCodeTextbox = GeneralUIUtils
- .getWebElementWaitForVisible(DataTestIdEnum.ServiceMetadataEnum.PROJECT_CODE.getValue());
- projectCodeTextbox.clear();
- projectCodeTextbox.sendKeys(pmat);
- }
-
-}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/TesterOperationPage.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/TesterOperationPage.java
deleted file mode 100644
index 6c18561492..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/TesterOperationPage.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.pages;
-
-import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum;
-import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest;
-import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils;
-import org.openqa.selenium.Keys;
-import org.openqa.selenium.interactions.Actions;
-import org.testng.annotations.Test;
-
-import com.relevantcodes.extentreports.LogStatus;
-
-public class TesterOperationPage {
-
- public TesterOperationPage() {
- super();
- }
-
- public static void certifyComponent(String componentName) throws Exception {
- clickStartTestingButton();
- clickAccpetCertificationButton(componentName);
-
- }
-
- public static void clickAccpetCertificationButton(String componentName) {
- SetupCDTest.getExtendTest().log(LogStatus.INFO, "clicking on accept certification button");
- GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.LifeCyleChangeButtons.ACCEPT.getValue()).click();
- GeneralUIUtils.waitForLoader();
- GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.ModalItems.ACCEP_TESTING_MESSAGE.getValue())
- .sendKeys(componentName + " tested successfuly");
- GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.ModalItems.OK.getValue()).click();
- GeneralUIUtils.waitForLoader();
- GeneralUIUtils.sleep(2000);
- GeneralUIUtils.getWebElementWaitForVisible("main-menu-input-search");
- SetupCDTest.getExtendTest().log(LogStatus.INFO, componentName + " is certifed ");
- }
-
- public static void clickStartTestingButton() {
- SetupCDTest.getExtendTest().log(LogStatus.INFO, "start testing");
- GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.LifeCyleChangeButtons.START_TESTING.getValue())
- .click();
- GeneralUIUtils.waitForLoader();
- GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.LifeCyleChangeButtons.ACCEPT.getValue());
- GeneralUIUtils.sleep(1000);
-
- // bug
- // Actions actionObject = new Actions(GeneralUIUtils.getDriver());
- // actionObject.keyDown(Keys.CONTROL).sendKeys(Keys.F5).perform();
- //
- }
-
-}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/UploadArtifactPopup.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/UploadArtifactPopup.java
deleted file mode 100644
index 5d27809774..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/UploadArtifactPopup.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.pages;
-
-import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum;
-import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils;
-import org.openqa.selenium.By;
-import org.openqa.selenium.WebElement;
-import org.openqa.selenium.support.ui.Select;
-
-public class UploadArtifactPopup {
-
- public UploadArtifactPopup() {
- super();
- }
-
- public void loadFile(String path, String filename) {
- final WebElement browseWebElement = GeneralUIUtils
- .getWebElementByDataTestId(DataTestIdEnum.ArtifactPopup.BROWSE.getValue());
- browseWebElement.sendKeys(path + "\\" + filename);
- }
-
- public void insertDescription(String artifactDescriptoin) {
- WebElement artifactDescriptionTextbox = GeneralUIUtils
- .getWebElementWaitForVisible(DataTestIdEnum.ArtifactPopup.ARTIFACT_DESCRIPTION.getValue());
- artifactDescriptionTextbox.clear();
- artifactDescriptionTextbox.sendKeys(artifactDescriptoin);
- }
-
- public Select defineArtifactLabel(String requiredArtifactLabel) {
- Select selectList = GeneralUIUtils.getSelectList("Create New Artifact",
- DataTestIdEnum.ArtifactPopup.ARTIFACT_LABEL.getValue());
- WebElement artifactLabelWebElement = GeneralUIUtils.getDriver().findElement(By.name("artifactLabel"));
- artifactLabelWebElement.clear();
- artifactLabelWebElement.sendKeys(requiredArtifactLabel);
- return selectList;
- }
-
- public Select selectArtifactType(String artifactType) {
- return GeneralUIUtils.getSelectList(artifactType, DataTestIdEnum.ArtifactPopup.ARTIFACT_TYPE.getValue());
- }
-
- public void clickAddButton() throws Exception {
- GeneralUIUtils.getWebButton(DataTestIdEnum.ArtifactPopup.ADD_BUTTON.getValue()).click();
- GeneralUIUtils.waitForLoader();
- }
-
- public void clickCancelButton() throws Exception {
- GeneralUIUtils.getWebButton(DataTestIdEnum.ArtifactPopup.CANCEL_BUTTON.getValue()).click();
- GeneralUIUtils.waitForLoader();
- }
-
- public void clickUpdateButton() throws Exception {
- GeneralUIUtils.getWebButton(DataTestIdEnum.ArtifactPopup.UPDATE_BUTTON.getValue()).click();
- GeneralUIUtils.waitForLoader();
- }
-
-}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/AdditionalConditions.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/AdditionalConditions.java
deleted file mode 100644
index 1b7f4c3641..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/AdditionalConditions.java
+++ /dev/null
@@ -1,84 +0,0 @@
-package org.openecomp.sdc.ci.tests.utilities;
-
-import org.openqa.selenium.JavascriptExecutor;
-import org.openqa.selenium.WebDriver;
-import org.openqa.selenium.support.ui.ExpectedCondition;
-
-public class AdditionalConditions {
-
- public static ExpectedCondition<Boolean> jQueryAJAXCallsHaveCompleted() {
- return new ExpectedCondition<Boolean>() {
- @Override
- public Boolean apply(WebDriver driver) {
- return (Boolean) ((JavascriptExecutor)driver).
- executeScript("return (window.jQuery!= null) && (jQuery.active === 0);");
- }
- };
- }
-
- public static ExpectedCondition <Boolean> angularHasFinishedProcessing() {
- return new ExpectedCondition<Boolean>() {
- @Override
- public Boolean apply(WebDriver driver) {
- String scriptJS = "return (window.angular !==undefined) &&"
- + " (angular.element(document).injector() !==undefined) &&"
- + " (angular.element(document).injector().get('$http').pendingRequests.length === 0)";
- return Boolean.valueOf(( (JavascriptExecutor) driver).executeScript(scriptJS).toString());
- }
- };
- }
-
- public static ExpectedCondition <Boolean> pageLoadWait() {
- return new ExpectedCondition<Boolean>() {
- @Override
- public Boolean apply(WebDriver driver) {
- String scriptJS =
- "try {\r\n" +
- " if (document.readyState !== 'complete') {\r\n" +
- " return false; // Page not loaded yet\r\n" +
- " }\r\n" +
- " if (window.jQuery) {\r\n" +
- " if (window.jQuery.active) {\r\n" +
- " return false;\r\n" +
- " } else if (window.jQuery.ajax && window.jQuery.ajax.active) {\r\n" +
- " return false;\r\n" +
- " }\r\n" +
- " }\r\n" +
- " if (window.angular) {\r\n" +
- " if (!window.qa) {\r\n" +
- " // Used to track the render cycle finish after loading is complete\r\n" +
- " window.qa = {\r\n" +
- " doneRendering: false\r\n" +
- " };\r\n" +
- " }\r\n" +
- " // Get the angular injector for this app (change element if necessary)\r\n" +
- " var injector = window.angular.element('body').injector();\r\n" +
- " // Store providers to use for these checks\r\n" +
- " var $rootScope = injector.get('$rootScope');\r\n" +
- " var $http = injector.get('$http');\r\n" +
- " var $timeout = injector.get('$timeout');\r\n" +
- " // Check if digest\r\n" +
- " if ($rootScope.$$phase === '$apply' || $rootScope.$$phase === '$digest' || $http.pendingRequests.length !== 0) {\r\n" +
- " window.qa.doneRendering = false;\r\n" +
- " return false; // Angular digesting or loading data\r\n" +
- " }\r\n" +
- " if (!window.qa.doneRendering) {\r\n" +
- " // Set timeout to mark angular rendering as finished\r\n" +
- " $timeout(function() {\r\n" +
- " window.qa.doneRendering = true;\r\n" +
- " }, 0);\r\n" +
- " return false;\r\n" +
- " }\r\n" +
- " }\r\n" +
- " return true;\r\n" +
- "} catch (ex) {\r\n" +
- " return false;\r\n" +
- "}";
- return Boolean.valueOf(( (JavascriptExecutor) driver).executeScript(scriptJS).toString());
- }
- };
- }
-
-
-
-}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/AdminWorkspaceUIUtilies.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/AdminWorkspaceUIUtilies.java
deleted file mode 100644
index 472b69fd0b..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/AdminWorkspaceUIUtilies.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.utilities;
-
-import org.junit.rules.TestName;
-import org.openqa.selenium.WebDriver;
-import org.openqa.selenium.support.ui.Select;
-
-public class AdminWorkspaceUIUtilies {
-
- public AdminWorkspaceUIUtilies(TestName name, String className) {
- super();
- // TODO Auto-generated constructor stub
- }
-
- protected static WebDriver driver;
-
- public static void deleteuser(String userId) throws Exception {
- typeToSearchBox(userId);
- if (GeneralUIUtils.getWebElements("tdRow") != null) {
- GeneralUIUtils.getWebElementWaitForVisible("delete" + userId + "").click();
- GeneralUIUtils.clickOkButton();
- }
- }
-
- public static String defineNewUserId(String userId) {
- GeneralUIUtils.getWebElementWaitForVisible("newUserId").clear();
- GeneralUIUtils.getWebElementWaitForVisible("newUserId").sendKeys(userId);
- ;
- return userId;
- }
-
- public static String defineNewMacUid(String MacUid) {
- GeneralUIUtils.getWebElementWaitForVisible("newUserId").clear();
- GeneralUIUtils.getWebElementWaitForVisible("newUserId").sendKeys(MacUid);
- ;
- return MacUid;
- }
-
- public static String selectUserRole(String Role) {
- Select selectrole = new Select(GeneralUIUtils.getWebElementWaitForVisible("selectrole"));
- selectrole.deselectByVisibleText(Role);
- selectrole.selectByVisibleText(Role);
- return Role;
- }
-
- public static void typeToSearchBox(String Text) throws Exception {
- GeneralUIUtils.getWebElementWaitForVisible("searchbox").clear();
- GeneralUIUtils.getWebElementWaitForVisible("searchbox").sendKeys(Text);
- Thread.sleep(1000);
- }
-
-}
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
deleted file mode 100644
index f22d52d3bd..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/ArtifactUIUtils.java
+++ /dev/null
@@ -1,302 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.utilities;
-
-import static org.junit.Assert.assertEquals;
-
-import java.awt.AWTException;
-import java.awt.Robot;
-import java.awt.Toolkit;
-import java.awt.datatransfer.StringSelection;
-import java.awt.event.KeyEvent;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.json.simple.JSONObject;
-import org.json.simple.JSONValue;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.ci.tests.datatypes.ArtifactInfo;
-import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum;
-import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.InformationalArtifacts;
-import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
-import org.openecomp.sdc.ci.tests.pages.DeploymentArtifactPage;
-import org.openecomp.sdc.ci.tests.pages.InformationalArtifactPage;
-import org.openqa.selenium.By;
-import org.openqa.selenium.WebElement;
-
-import com.thinkaurelius.titan.diskstorage.util.StaticArrayBuffer;
-
-public final class ArtifactUIUtils {
-
- private ArtifactUIUtils() {
- }
-
- public static void fillAndAddNewArtifactParameters(ArtifactInfo artifactInfo) throws Exception {
- DeploymentArtifactPage.artifactPopup().loadFile(artifactInfo.getFilepath(), artifactInfo.getFilename());
- DeploymentArtifactPage.artifactPopup().insertDescription(artifactInfo.getDescription());
- DeploymentArtifactPage.artifactPopup().defineArtifactLabel(artifactInfo.getArtifactLabel());
- DeploymentArtifactPage.artifactPopup().selectArtifactType(artifactInfo.getArtifactType());
- DeploymentArtifactPage.artifactPopup().clickAddButton();
- }
-
- public static void fillPlaceHolderInformationalArtifact(DataTestIdEnum.InformationalArtifacts artifactLabel,
- String filepath, String filename, String description) throws Exception {
- GeneralUIUtils.getWebButton(artifactLabel.getValue()).click();
- InformationalArtifactPage.artifactPopup().loadFile(filepath, filename);
- InformationalArtifactPage.artifactPopup().insertDescription(description);
- InformationalArtifactPage.artifactPopup().clickAddButton();
- }
-
- public static RestResponse deploymentArtifactResourceInUI(ResourceReqDetails resource, User user,
- ArtifactReqDetails artifact, String file) throws Exception {
- Thread.sleep(1000);
-
- List<WebElement> listFormInput = GeneralUIUtils.getDriver()
- .findElements(By.className("i-sdc-designer-sidebar-tab"));
- WebElement addArtifactElement = listFormInput.get(2);
- addArtifactElement.click();
-
- WebElement addArtifact = GeneralUIUtils.getDriver()
- .findElement(By.className("i-sdc-designer-sidebar-section-content-item-artifact-details-name"));
- addArtifact.click();
-
- Thread.sleep(1000);
- WebElement descriptionProperty = GeneralUIUtils.getDriver().findElement(By.className("i-sdc-form-textarea"));
- descriptionProperty.clear();
- descriptionProperty.sendKeys(artifact.getDescription());
-
- WebElement uploadFile = GeneralUIUtils.getDriver().findElement(By.className("i-sdc-form-label-upload"));
- uploadFile.click();
-
- StringSelection sel = new StringSelection(file);
- Toolkit.getDefaultToolkit().getSystemClipboard().setContents(sel, null);
- // System.out.println("selection" + sel);
- Thread.sleep(1000);
-
- Robot robot = new Robot();
- Thread.sleep(1000);
-
- Thread.sleep(2000);
-
- robot.keyPress(KeyEvent.VK_ENTER);
-
- // Release Enter
- robot.keyRelease(KeyEvent.VK_ENTER);
-
- // Press CTRL+V
- robot.keyPress(KeyEvent.VK_CONTROL);
- robot.keyPress(KeyEvent.VK_V);
-
- // Release CTRL+V
- robot.keyRelease(KeyEvent.VK_CONTROL);
- robot.keyRelease(KeyEvent.VK_V);
- Thread.sleep(1000);
-
- // Press Enter
- robot.keyPress(KeyEvent.VK_ENTER);
- robot.keyRelease(KeyEvent.VK_ENTER);
- Thread.sleep(3000);
-
- WebElement clickDone = GeneralUIUtils.getDriver().findElement(By.className("w-sdc-form-action"));
- clickDone.click();
-
- Thread.sleep(3500);
-
- GeneralUIUtils.getDriver().findElement(By.cssSelector("button[data-ng-click^=save]")).click();
-
- RestResponse getResource = RestCDUtils.getResource(resource, user);
- assertEquals("Did not succeed to get resource after create", 200, getResource.getErrorCode().intValue());
- return getResource;
- }
-
- public static void addInformationArtifact(ArtifactReqDetails artifact, String filePath,
- final InformationalArtifacts dataTestEnum) throws Exception {
- GeneralUIUtils.waitForLoader();
- GeneralUIUtils.sleep(2000);
- GeneralUIUtils.getWebElementWaitForVisible(dataTestEnum.getValue()).click();
-
- final WebElement browseWebElement = GeneralUIUtils.retryMethodOnException(
- () -> GeneralUIUtils.getWebElementByDataTestId(DataTestIdEnum.ModalItems.BROWSE_BUTTON.getValue()));
- browseWebElement.sendKeys(filePath);
-
- GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.ModalItems.DESCRIPTION.getValue())
- .sendKeys(artifact.getDescription());
- GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.ModalItems.ADD.getValue()).click();
-
- }
-
- private static void addFileToWindowBrowse(String file) throws InterruptedException, AWTException {
- StringSelection sel = new StringSelection(file);
- Toolkit.getDefaultToolkit().getSystemClipboard().setContents(sel, null);
- // System.out.println("selection" + sel);
- Thread.sleep(1000);
-
- Robot robot = new Robot();
-
- robot.keyPress(KeyEvent.VK_ENTER);
-
- // Release Enter
- robot.keyRelease(KeyEvent.VK_ENTER);
-
- // Press CTRL+V
- robot.keyPress(KeyEvent.VK_CONTROL);
- robot.keyPress(KeyEvent.VK_V);
-
- // Release CTRL+V
- robot.keyRelease(KeyEvent.VK_CONTROL);
- robot.keyRelease(KeyEvent.VK_V);
- Thread.sleep(1000);
-
- // Press Enter
- robot.keyPress(KeyEvent.VK_ENTER);
- robot.keyRelease(KeyEvent.VK_ENTER);
- Thread.sleep(3000);
- }
-
- static WebElement ArtifactLabel;
-
- public static Map<String, String> addInformationalArtifact(String artifactLabel) throws Exception {
- String type = GeneralUIUtils.getSelectList(null, "artifacttype").getFirstSelectedOption().getText();
- Map<String, String> artifactValues = new HashMap<String, String>();
- String labelName = GeneralUIUtils.getSelectList(artifactLabel, "selectArtifact").getFirstSelectedOption()
- .getText();
- ArtifactLabel = GeneralUIUtils.getDriver().findElement(By.name("artifactLabel"));
- if (ArtifactLabel.getAttribute("value").equals("")) {
- labelName = "New-Test-Artifact";
- ArtifactLabel.sendKeys(labelName);
- type = GeneralUIUtils.getSelectList("HEAT", "artifacttype").getFirstSelectedOption().getText();
- }
- String description = "This is Description";
- String fileName = "Heat-File.yaml";
- GeneralUIUtils.defineDescription(description);
- ResourceUIUtils.importFileWithSendKeyBrowse(GeneralUIUtils.FILE_PATH, fileName);
- GeneralUIUtils.getWebButton("Add").click();
- GeneralUIUtils.waitFordataTestIdVisibility(labelName);
-
- artifactValues.put("type", type);
- artifactValues.put("description", description);
- artifactValues.put("name", labelName);
- artifactValues.put("fileName", fileName);
- return artifactValues;
- }
-
- public static Map<String, String> addDeploymentArtifact(String artifactLabel, String artifactType, String fileName)
- throws Exception {
- String type = null;
- String labelName;
- Map<String, String> artifactValues = new HashMap<String, String>();
- try {
- labelName = GeneralUIUtils.getSelectList(artifactLabel, "selectArtifact").getOptions().get(1).getText();
- GeneralUIUtils.getSelectList(artifactLabel, "selectArtifact").selectByVisibleText(labelName);
- } catch (Exception e) {
- labelName = GeneralUIUtils.getWebElementByName(artifactLabel).getText();
- }
- ArtifactLabel = GeneralUIUtils.getDriver().findElement(By.name("artifactLabel"));
- if (ArtifactLabel.getText().equals("")) {
- labelName = "New-Test-Artifact";
- ArtifactLabel.sendKeys(labelName);
- type = GeneralUIUtils.getSelectList(artifactType, "artifacttype").getFirstSelectedOption().getText();
- }
- String description = "This is Description";
- GeneralUIUtils.defineDescription(description);
- ResourceUIUtils.importFileWithSendKeyBrowse(GeneralUIUtils.FILE_PATH, fileName);
- try {
- GeneralUIUtils.getWebButton("Add").click();
- } catch (Exception e) {
- GeneralUIUtils.getButtonByClassName("w-sdc-form-action add-property").click();
- }
-
- artifactValues.put("type", artifactType);
- artifactValues.put("description", description);
- artifactValues.put("name", labelName);
- artifactValues.put("fileName", fileName);
- return artifactValues;
- }
-
- public static Map<String, String> addDeploymentArtifactFromCanvas(String artifactLabel) throws Exception {
- String type = null;
- Map<String, String> artifactValues = new HashMap<String, String>();
- String labelName = GeneralUIUtils.getSelectList(artifactLabel, "selectArtifact").getFirstSelectedOption()
- .getText();
- ArtifactLabel = GeneralUIUtils.getDriver().findElement(By.name("artifactLabel"));
- if (ArtifactLabel.getText().equals("")) {
- labelName = "New-Test-Artifact";
- ArtifactLabel.sendKeys(labelName);
- type = GeneralUIUtils.getSelectList("OTHER", "artifacttype").getFirstSelectedOption().getText();
- }
- String description = "This is Description";
- String filePath = "C:\\Git_work\\ASDC\\d2-sdnc\\ui-ci\\src\\main\\resources\\Files\\";
- String fileName = "Heat-File.yaml";
- GeneralUIUtils.defineDescription(description);
- ResourceUIUtils.importFileWithSendKeyBrowse(filePath, fileName);
- GeneralUIUtils.getWebButton("Add").click();
- artifactValues.put("type", type);
- artifactValues.put("description", description);
- artifactValues.put("name", labelName);
- artifactValues.put("fileName", fileName);
- return artifactValues;
- }
-
- public static Map<String, String> valideArtifact(Map<String, String> artifactValues, Boolean condition)
- throws Exception {
- if (condition) {
- GeneralUIUtils.getEelementBycontainsClassName("table-edit-btn").click();
- } else {
- System.out.println(artifactValues.get("name"));
- GeneralUIUtils.getWebElementWaitForVisible("edit_" + artifactValues.get("name")).click();
- }
- Thread.sleep(1000);
- String labelname = GeneralUIUtils.getWebElementByName("artifactLabel").getAttribute("value");
- String filename = GeneralUIUtils.getWebElementWaitForVisible("filename").getText();
- String description = GeneralUIUtils.getWebElementWaitForVisible("description").getAttribute("value");
- String type = GeneralUIUtils.getSelectList(null, "artifacttype").getFirstSelectedOption().getText();
- labelname.compareToIgnoreCase(artifactValues.get("name").replaceAll("-", ""));
- assertEquals(filename, artifactValues.get("fileName").replaceAll(" ", "-"));
- assertEquals(type, artifactValues.get("type"));
- assertEquals(description, artifactValues.get("description"));
- GeneralUIUtils.getWebButton("Update").click();
- return artifactValues;
- }
-
- public static void valideArtifactFromCanvas(Map<String, String> artifactValues) throws Exception {
- GeneralUIUtils.getWebElementWaitForVisible("artifactDisplayName-" + artifactValues.get("name")).click();
- Thread.sleep(1000);
- String labelname = GeneralUIUtils.getWebElementByName("artifactLabel").getAttribute("value");
- String filename = GeneralUIUtils.getWebElementWaitForVisible("filename").getText();
- String description = GeneralUIUtils.getWebElementWaitForVisible("description").getAttribute("value");
- String type = GeneralUIUtils.getSelectList(null, "artifacttype").getFirstSelectedOption().getText();
- labelname.compareToIgnoreCase(artifactValues.get("name").replaceAll("-", ""));
- assertEquals(filename, artifactValues.get("fileName"));
- assertEquals(type, artifactValues.get("type"));
- assertEquals(description, artifactValues.get("description"));
- }
-
- public static Map<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;
- }
-
-}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/AuditCDUtils.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/AuditCDUtils.java
deleted file mode 100644
index c53fef596a..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/AuditCDUtils.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.utilities;
-
-import org.codehaus.jettison.json.JSONObject;
-import org.openecomp.sdc.be.model.LifecycleStateEnum;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedResourceAuditJavaObject;
-import org.openecomp.sdc.ci.tests.utils.general.Convertor;
-import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils;
-
-public class AuditCDUtils {
-
- public static void validateResourceSuccessAudit(ResourceReqDetails resource, User user, String action)
- throws Exception {
- JSONObject auditBody = AuditValidationUtils.filterAuditByUuid(action, resource.getUUID());
- ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor
- .constructFieldsForAuditValidation(resource, resource.getVersion(), user);
- String auditAction = "Create";
- expectedResourceAuditJavaObject.setAction(auditAction);
- expectedResourceAuditJavaObject.setPrevVersion("");
- expectedResourceAuditJavaObject.setPrevState("");
- expectedResourceAuditJavaObject.setStatus("201");
- expectedResourceAuditJavaObject.setDesc("OK");
- AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, auditBody.toString(), false);
- }
-
- public static void validateServiceSuccessAudit(ServiceReqDetails service, User user, String action)
- throws Exception {
- validateServiceSuccessAudit(service, user, action, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
- }
-
- public static void validateServiceSuccessAudit(ServiceReqDetails service, User user, String action,
- LifecycleStateEnum lifecycleStatus) throws Exception {
- ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = AuditValidationUtils
- .constructFieldsForAuditValidation(service, service.getVersion(), user);
- String body = AuditValidationUtils.filterAuditByUuid(action, service.getUUID()).toString();
- expectedResourceAuditJavaObject.setAction(action);
- expectedResourceAuditJavaObject.setPrevState("");
- expectedResourceAuditJavaObject.setPrevVersion("");
- expectedResourceAuditJavaObject.setCurrState(lifecycleStatus.toString());
- expectedResourceAuditJavaObject.setStatus("201");
- expectedResourceAuditJavaObject.setDesc("OK");
- AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, action, body, false);
- }
-
-}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/CanvasElement.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/CanvasElement.java
deleted file mode 100644
index fbe8c04036..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/CanvasElement.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.utilities;
-
-import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.LeftPanelCanvasItems;
-import org.openqa.selenium.WebElement;
-
-public final class CanvasElement {
- private final String uniqueId;
- private ImmutablePair<Integer, Integer> location;
- private WebElement elementType;
-
- CanvasElement(String name, ImmutablePair<Integer, Integer> location, WebElement canvasItem) {
- super();
- this.uniqueId = name;
- this.location = location;
- elementType = canvasItem;
- }
-
- public String getUniqueId() {
- return uniqueId;
- }
-
- public ImmutablePair<Integer, Integer> getLocation() {
- return location;
- }
-
- public void setLocation(ImmutablePair<Integer, Integer> location) {
- this.location = location;
- }
-
- public WebElement getElementType() {
- return elementType;
- }
-}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/CanvasManager.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/CanvasManager.java
deleted file mode 100644
index a52367a454..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/CanvasManager.java
+++ /dev/null
@@ -1,181 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.utilities;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Random;
-import java.util.UUID;
-import java.util.stream.Collectors;
-
-import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum;
-import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.LeftPanelCanvasItems;
-import org.openecomp.sdc.ci.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)
- throws Exception {
- GeneralUIUtils.waitForLoader();
- Thread.sleep(500);
- actions.moveToElement(canvas, canvasElement.getLocation().left, canvasElement.getLocation().right);
- actions.clickAndHold();
- actions.moveToElement(canvas, newLocation.left, newLocation.right);
- actions.release();
- actions.perform();
- canvasElement.setLocation(newLocation);
- GeneralUIUtils.waitForLoader();
-
- }
-
- public void moveElementOnCanvas(CanvasElement canvasElement) throws Exception {
- moveElementOnCanvas(canvasElement, getFreePosition());
- }
-
- public void deleteElementFromCanvas(CanvasElement canvasElement) throws Exception {
- GeneralUIUtils.waitForLoader();
- actions.moveToElement(canvas, canvasElement.getLocation().left, canvasElement.getLocation().right);
- actions.click();
- actions.perform();
- GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.GeneralCanvasItems.DELETE_INSTANCE_BUTTON.getValue())
- .click();
- GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.ModalItems.OK.getValue()).click();
- canvasElements.remove(canvasElement.getUniqueId());
- GeneralUIUtils.waitForLoader();
- }
-
- private String getItemName(WebElement canvasItem) {
- String canvasItemName = canvasItem.getAttribute("data-tests-id");
-
- return canvasItemName.substring(canvasItemName.lastIndexOf("-"));
- }
-
- public CanvasElement createElementOnCanvas(WebElement canvasItem) throws Exception {
- GeneralUIUtils.waitForLoader();
- ImmutablePair<Integer, Integer> freePosition = getFreePosition();
- actions.moveToElement(canvasItem, 0, 0);
- actions.clickAndHold();
- actions.moveToElement(canvas, freePosition.left, freePosition.right);
- actions.release();
- actions.perform();
-
- String uniqueId = getItemName(canvasItem) + "_" + UUID.randomUUID().toString();
- CanvasElement canvasElement = new CanvasElement(uniqueId, freePosition, canvasItem);
- addCanvasElement(canvasElement);
- GeneralUIUtils.waitForLoader();
- return canvasElement;
- }
-
- private ImmutablePair<Integer, Integer> getFreePosition() {
- // TODO mshitrit 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);
- }
-
- public void linkElements(CanvasElement firstElement, CanvasElement secondElement) throws Exception {
- GeneralUIUtils.waitForLoader();
- drawSimpleLink(firstElement, secondElement);
-
- selectReqAndCapAndConnect();
-
- GeneralUIUtils.waitForLoader();
-
- }
-
- private void selectReqAndCapAndConnect() {
- // Select First Cap
- GeneralUIUtils.getWebElements(DataTestIdEnum.LinkMenuItems.LINK_ITEM_CAP.getValue()).get(0).click();
- // Select First Req
- GeneralUIUtils.getWebElements(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();
- }
-}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/CaptureFailedTests.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/CaptureFailedTests.java
deleted file mode 100644
index e2b2f8800b..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/CaptureFailedTests.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.utilities;
-
-import java.io.File;
-import java.io.IOException;
-
-import org.apache.commons.io.FileUtils;
-import org.openqa.selenium.OutputType;
-import org.openqa.selenium.TakesScreenshot;
-import org.testng.ITestResult;
-import org.testng.Reporter;
-import org.testng.TestListenerAdapter;
-
-public class CaptureFailedTests extends TestListenerAdapter {
-
- @Override
- public void onTestFailure(ITestResult tr) {
-
- String testName = tr.getName();
- String parameter = tr.getParameters().length == 1 ? tr.getParameters()[0].toString() : "";
- File folder = new File(String.format("test-output\\failure_screenshots\\%s_%s.png", testName, parameter));
-
- File scrFile = ((TakesScreenshot) GeneralUIUtils.getDriver()).getScreenshotAs(OutputType.FILE);
-
- try {
- FileUtils.copyFile(scrFile, folder);
- } catch (IOException e) {
- e.printStackTrace();
- }
- Reporter.setEscapeHtml(false);
- String screenPath = String.format("<img src=%s />", folder.getAbsolutePath());
- Reporter.log(screenPath);
- }
-
-}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/CatalogUIUtilitis.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/CatalogUIUtilitis.java
deleted file mode 100644
index d204645566..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/CatalogUIUtilitis.java
+++ /dev/null
@@ -1,148 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.utilities;
-
-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 javax.json.Json;
-
-import org.codehaus.jettison.json.JSONArray;
-import org.codehaus.jettison.json.JSONException;
-import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
-import org.openecomp.sdc.ci.tests.utils.rest.CatalogRestUtils;
-import org.testng.annotations.Test;
-
-public class CatalogUIUtilitis {
-
- // Get all Categories , Subcategories and Icons.
- public void getAllCategoriesAndSubcategories() throws IOException, JSONException {
- RestResponse allcategoriesJson = CatalogRestUtils.getAllCategoriesTowardsCatalogBe();
- JSONArray categories = new JSONArray(allcategoriesJson.getResponse());
- for (int i = 0; i < categories.length(); i++) {
- String categoryname = (String) categories.getJSONObject(i).get("name");
- JSONArray subcategories = (JSONArray) categories.getJSONObject(i).get("subcategories");
- for (int j = 0; j < subcategories.length(); j++) {
- String subcategoryname = (String) subcategories.getJSONObject(j).get("name");
- System.out.println(subcategoryname);
- }
- for (int j = 0; j < subcategories.length(); j++) {
- JSONArray icons = (JSONArray) subcategories.getJSONObject(j).get("icons");
- for (int k = 0; k < icons.length(); k++) {
- System.out.println(icons.get(k));
- }
- }
- System.out.println("-------------------------------");
- }
- }
-
- @Test
- // FOr testing---delete.
- public static List<String> abcd() throws IOException, JSONException {
- RestResponse allcategoriesJson = CatalogRestUtils.getAllCategoriesTowardsCatalogBe();
- JSONArray categories = new JSONArray(allcategoriesJson.getResponse());
- List<String> allcat = new ArrayList<>();
- String uniqueId = null;
- for (int i = 0; i < categories.length(); i++) {
- String categoryname = (String) categories.getJSONObject(i).get("name");
- uniqueId = (String) categories.getJSONObject(i).get("uniqueId");
- allcat.add(uniqueId);
- JSONArray subcategories = (JSONArray) categories.getJSONObject(i).get("subcategories");
- for (int j = 0; j < subcategories.length(); j++) {
- String subcategoryname = (String) subcategories.getJSONObject(j).get("name");
- uniqueId = (String) subcategories.getJSONObject(j).get("uniqueId");
- allcat.add(uniqueId);
- }
- }
- return allcat;
-
- }
-
- // Get all Categories uniqueID .//The parent categories.
- public static List<String> getCategories() throws IOException, JSONException {
- List<String> allCategoriesList = new ArrayList<>();
- RestResponse allcategoriesJson = CatalogRestUtils.getAllCategoriesTowardsCatalogBe();
- JSONArray categories = new JSONArray(allcategoriesJson.getResponse());
- for (int i = 0; i < categories.length(); i++) {
- String categoryname = (String) categories.getJSONObject(i).get("name");
- System.out.println(categoryname);
- allCategoriesList.add(categoryname);
- }
- return allCategoriesList;
- }
-
- @Test
- // Get Subcategories by Category name
- public static List<String> getAllSubcategoriesByUniqueId(String uniqueId) throws IOException, JSONException {
-
- RestResponse allcategoriesJson = CatalogRestUtils.getAllCategoriesTowardsCatalogBe();
- JSONArray categories = new JSONArray(allcategoriesJson.getResponse());
- List<String> subCategories = new ArrayList<>();// subCategories to
- // return.
- JSONArray subcategories = null;
-
- for (int i = 0; i < categories.length(); i++) {
-
- String categoryuniqueId = (String) categories.getJSONObject(i).get("uniqueId");
-
- if (categoryuniqueId.contentEquals(uniqueId)) {
- subcategories = (JSONArray) categories.getJSONObject(i).get("subcategories");
-
- for (int j = 0; j < subcategories.length(); j++) {
-
- subCategories.add((String) subcategories.getJSONObject(j).get("uniqueId"));
- }
-
- break;
- }
- }
- if (subcategories == null) {
- subCategories.add(uniqueId);
- }
- return subCategories;
- }
-
- @Test
- // Get icons by category name
- public void getSubCategoryIcons() throws IOException, JSONException {
- RestResponse allcategoriesJson = CatalogRestUtils.getAllCategoriesTowardsCatalogBe();
-
- JSONArray categories = new JSONArray(allcategoriesJson.getResponse());
- for (int i = 0; i < categories.length(); i++) {
- String subcategoryname = (String) categories.getJSONObject(i).get("name");
- if (subcategoryname.contentEquals("Generic")) {
- JSONArray subcategories = (JSONArray) categories.getJSONObject(i).get("subcategories");
- for (int j = 0; j < subcategories.length(); j++) {
- JSONArray icons = (JSONArray) subcategories.getJSONObject(j).get("icons");
- for (int k = 0; k < icons.length(); k++) {
- System.out.println(icons.get(k));
- }
- }
- break;
- }
- }
- }
-
-}
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
deleted file mode 100644
index 9533b6485e..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/FileHandling.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.utilities;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FilenameFilter;
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-
-import org.yaml.snakeyaml.Yaml;
-
-public class FileHandling {
-
- public static Map<?, ?> parseYamlFile(String filePath) throws Exception {
- Yaml yaml = new Yaml();
- File file = new File(filePath);
- InputStream inputStream = new FileInputStream(file);
- Map<?, ?> map = (Map<?, ?>) yaml.load(inputStream);
- return map;
- }
-
- 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;
- }
-
- public static String getCiFilesPath() {
- return getBasePath() + File.separator + "src" + File.separator + "main" + File.separator + "resources"
- + File.separator + "ci";
- }
-
- public static String getConfFilesPath() {
- return getCiFilesPath() + File.separator + "conf" + File.separator;
- }
-
- public static String getTestSuitesFilesPath() {
- return getCiFilesPath() + File.separator + "testSuites" + File.separator;
- }
-
- public static Object[] getFileNamesFromFolder(String filepath, String extension) {
- try {
- File dir = new File(filepath);
- List<String> filenames = new ArrayList<String>();
- if (dir.isDirectory()) {
- for (File file : dir.listFiles(new FilenameFilter() {
- @Override
- public boolean accept(File dir, String name) {
- return name.endsWith(extension);
- }
- })) {
-
- filenames.add(file.getName());
- }
- return filenames.toArray();
- }
-
- } catch (Exception e) {
- e.printStackTrace();
- }
- return null;
- }
-
-}
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
deleted file mode 100644
index 4fd36955ae..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/GeneralUIUtils.java
+++ /dev/null
@@ -1,1081 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.utilities;
-
-import java.awt.AWTException;
-import java.awt.Robot;
-import java.awt.Toolkit;
-import java.awt.datatransfer.StringSelection;
-import java.awt.event.KeyEvent;
-import java.io.File;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.lang.reflect.Method;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Date;
-import java.util.List;
-import java.util.concurrent.TimeUnit;
-import java.util.function.Supplier;
-
-import org.apache.commons.io.FileUtils;
-import org.apache.commons.lang3.time.StopWatch;
-import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.ci.tests.datatypes.BreadCrumbsButtonsEnum;
-import org.openecomp.sdc.ci.tests.datatypes.CatalogFilterTitlesEnum;
-import org.openecomp.sdc.ci.tests.datatypes.CheckBoxStatusEnum;
-import org.openecomp.sdc.ci.tests.datatypes.CreateAndImportButtonsEnum;
-import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum;
-import org.openecomp.sdc.ci.tests.datatypes.MenuOptionsEnum;
-import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.TypesEnum;
-import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest;
-import org.openqa.selenium.By;
-import org.openqa.selenium.Keys;
-import org.openqa.selenium.OutputType;
-import org.openqa.selenium.Platform;
-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.remote.DesiredCapabilities;
-import org.openqa.selenium.remote.RemoteWebDriver;
-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.testng.Reporter;
-
-import com.relevantcodes.extentreports.LogStatus;
-
-public final class GeneralUIUtils {
-
- private static int timeOut=60*3;
-
- public static final String FILE_NAME = "Valid_tosca_Mycompute.yml";
-
- /**************** DRIVERS ****************/
- private static WebDriver driver;
-
- public static void findComponentAndClick(String componentName) throws Exception {
- SetupCDTest.getExtendTest().log(LogStatus.INFO, "finding component " + componentName);
- waitFordataTestIdVisibility("main-menu-input-search").sendKeys(componentName);
- WebElement foundComp = null;
- try {
- foundComp = waitFordataTestIdVisibility(componentName);
- foundComp.click();
- GeneralUIUtils.waitForLoader();
- waitFordataTestIdVisibility("formlifecyclestate");
- } catch (Exception e) {
- String msg = String.format("DID NOT FIND A COMPONENT NAMED %s", componentName);
- SetupCDTest.getExtendTest().log(LogStatus.FAIL, msg);
- System.out.println(msg);
- Assert.fail(msg);
- }
- }
-
- public static List<WebElement> getElemenetsFromTable(By by) {
- return GeneralUIUtils.getDriver().findElements(by);
- }
-
- private static List<WebElement> getNewButtonsList() {
- WebElement createButtonsArea = driver.findElement(By.className("w-sdc-dashboard-card-new"));
- createButtonsArea.click();
- List<WebElement> buttonsList = driver.findElements(By.className("w-sdc-dashboard-card-new-button"));
- return buttonsList;
- }
-
- public static final String FILE_PATH = System.getProperty("user.dir") + "\\src\\main\\resources\\Files\\";
- public static String fileName = "JDM_vfc.yml";
- public static final String toscaErrorMessage = "Invalid TOSCA template.";
- public static final String yamlError = "Invalid YAML file.";
- public static final String allReadyExistErro = "Imported resource already exists in ASDC Catalog.";
-
- public static WebElement hoverOnArea(String areaId) {
- Actions actions = new Actions(driver);
- WebElement area = getWebElementWaitForVisible(areaId);
- actions.moveToElement(area).perform();
- return area;
- }
-
- public static WebElement actionBuild(WebElement element) throws InterruptedException {
- // make an action on page//hover on element
- Actions build = new Actions(driver); // here you state ActionBuider
- build.moveToElement(element).build().perform();// hover the element.
- Thread.sleep(1000);
- return element;
- }
-
- public static File takeScreenshot(String zipFile, String dir, String testName) throws IOException {
- if (zipFile == null) {
- zipFile = testName;
- }
- try {
- File scrFile = ((TakesScreenshot) GeneralUIUtils.getDriver()).getScreenshotAs(OutputType.FILE);
- File filePath = new File(String.format("%s/%s.png", dir, zipFile));
- new File(dir).mkdirs();
- FileUtils.copyFile(scrFile, filePath);
- return filePath;
- } catch (IOException e1) {
- e1.printStackTrace();
- }
- return null;
- }
-
- public static void errorMessagePopupHandle(@SuppressWarnings("rawtypes") Supplier func) throws Exception {
- try {
- WebElement errorMessagePopupHeader = getDriver().findElement(By.className("w-sdc-modal-head-text"));
- if (errorMessagePopupHeader.getText().equals("Error")) {
- WebElement okButton = getWebButton("OK");
- if (okButton.isDisplayed()) {
- okButton.click();
- func.get();
- }
- }
- } catch (Exception e) {
- throw new Exception("something went wrong, can't do anything");
- }
- }
-
- public static void waitForLoader() {
- waitForElements(By.className("tlv-loader"), 200, 3 * 60 * 1000);
- }
-
- public static void waitForLoaderOnboarding() {
- waitForElements(By.className("tlv-loader"), 200, 13 * 60 * 1000);
- }
-
- public static List<WebElement> waitForElements(By by, int napPeriod, int maxWaitMS) {
- boolean isKeepWaiting = true;
- int currentWaitTimeMS = 0;
- List<WebElement> elements = null;
- while (isKeepWaiting) {
- elements = getDriver().findElements(by);
- isKeepWaiting = elements.size() > 0;
- if (isKeepWaiting) {
- sleep(napPeriod);
- currentWaitTimeMS += napPeriod;
- if (currentWaitTimeMS > maxWaitMS) {
- isKeepWaiting = false;
- }
- }
- }
-
- return elements;
-
- }
-
- public static WebDriver getDriver() {
- return driver;
- }
-
- public static WebElement rihtPanelAPI() {
- return getWebElementWaitForVisible("tab-api");
- }
-
- public static void scrollDown() throws AWTException {
- Robot robot = new Robot();
- robot.keyPress(KeyEvent.VK_DOWN);
- robot.keyRelease(KeyEvent.VK_DOWN);
- }
-
- // solution for "element not attached to the DOM anymore"
- public static List<WebElement> getWorkspaceElements() throws InterruptedException {
- Thread.sleep(1000);
- List<WebElement> assets = GeneralUIUtils.getEelementsByClassName("w-sdc-dashboard-card-body");
- return assets;
- }
-
- public static String getMethodName(Method method) {
- return method.getName();
- }
-
- public static FileWriter InitializeprintToTxt(String testName) {
- String idForTxtFile = new SimpleDateFormat("dd.MM.yyyy_HH.mm.ss").format(new Date());
- File file = new File(testName + idForTxtFile);
- FileWriter fw = null;
- try {
- fw = new FileWriter(file, true);
-
- } catch (IOException e) {
- e.printStackTrace();
- System.out.println(e.getLocalizedMessage());
- }
- return fw;
- }
-
- public static void closeFileWriter(FileWriter file) throws IOException {
- file.flush();
- file.close();
- }
-
- public static WebElement createAndImportButtons(CreateAndImportButtonsEnum type, WebDriver driver)
- throws InterruptedException {
- switch (type) {
- case IMPORT_CP:
- case IMPORT_VFC:
- case IMPORT_VL:
- hoverOnArea("importButtonsArea");
- return GeneralUIUtils.getWebElementWaitForVisible("importVFCbutton");
-
- case IMPORT_VF:
- hoverOnArea("importButtonsArea");
- return GeneralUIUtils.getWebElement(driver, "importVFbutton");
- case CREATE_SERVICE:
- hoverOnArea("AddButtonsArea", driver);
- GeneralUIUtils.getWebElementWaitForVisible("createServiceButton").click();
- ;
- break;
-
- case CREATE_PRODUCT:
- GeneralUIUtils.getWebElement(driver, "createServiceButton").click();
- GeneralUIUtils.getWebElementWaitForVisible("createServiceButton").click();
- break;
-
- default:
- hoverOnArea("AddButtonsArea");
- driver.findElement(By.xpath("//*[@data-tests-id='createResourceButton']")).click();
- break;
- }
- return null;
-
- }
-
- public static String checkBoxLifeCyclestate(CheckBoxStatusEnum lifeCycle) {
- String Status = "IN DESIGN CHECK OUT";
- switch (lifeCycle) {
- case CHECKIN:
- Status = "IN DESIGN CHECK IN";
- if (GeneralUIUtils.getWebElementWaitForVisible(lifeCycle.getValue()).isDisplayed()) {
- GeneralUIUtils.getWebElementWaitForVisible(lifeCycle.getValue()).click();
- }
- break;
- case CHECKOUT:
- GeneralUIUtils.getWebElementWaitForVisible(lifeCycle.getValue()).click();
- Status = "IN DESIGN CHECK OUT";
- break;
- case IN_TESTING:
- GeneralUIUtils.getWebElementWaitForVisible(lifeCycle.getValue()).click();
- Status = "IN TESTING";
- break;
- case READY_FOR_TESTING:
- GeneralUIUtils.getWebElementWaitForVisible(lifeCycle.getValue()).click();
- Status = "READY FOR TESTING";
- break;
- case CERTIFIED:
- GeneralUIUtils.getWebElementWaitForVisible(lifeCycle.getValue()).click();
- Status = "CERTIFIED";
- break;
- }
- return Status;
- }
-
- public static String setFileTypeAndGetUniqId(ResourceTypeEnum fileType, ResourceReqDetails resourceDetails,
- User user) throws IOException, Exception {
- resourceDetails.setResourceType(fileType.toString());
- RestCDUtils.getResource(resourceDetails, user);
- return resourceDetails.getUniqueId();
- }
-
- public static void minimizeCatalogFilterByTitle(CatalogFilterTitlesEnum titlesEnum) {
-
- switch (titlesEnum) {
- case CATEGORIES:
- GeneralUIUtils.getWebElementWaitForVisible(titlesEnum.getValue()).click();
- break;
- case STATUS:
- GeneralUIUtils.getWebElementWaitForVisible(titlesEnum.getValue()).click();
- break;
- case TYPE:
- GeneralUIUtils.getWebElementWaitForVisible(titlesEnum.getValue()).click();
- break;
- default:
- break;
- }
- // webElementWaitForVisible.get(0).click();
- // }
- }
-
- public static WebElement getWebElementWaitForVisible(String dataTestId) {
- // try{
- return waitFordataTestIdVisibility(dataTestId);
- // }
- // catch(Exception e){
- // try{
- // WebElement errorMessagePopupHeader =
- // GeneralUIUtils.getDriver().findElement(By.className("w-sdc-modal-head-text"));
- // if (errorMessagePopupHeader.getText().equals("Error")){
- // WebElement okButton = GeneralUIUtils.getWebButton("OK");
- // if (okButton.isDisplayed()){
- //// takeScreenshot(LocalDateTime.now().toString().replaceAll(":", ""),
- // SetupCDTest.SCREENSHOT_LOG_DIR);
- // okButton.click();
- // return getWebElementWaitForVisible(dataTestId);
- // }
- // }
- // }
- // catch(Exception exception){
- // System.out.println(String.format("didn't find element with
- // data-tests-id of %s", dataTestId));
- // }
- // }
- // return null;
-
- }
-
- public static WebElement getWebElementById(String id) {
- WebDriverWait wait = new WebDriverWait(driver, 5);
- return wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id='" + id + "']")));
- }
-
- public static WebElement getWebElementByName(String name) {
- return driver.findElement(By.name(name));
- }
-
- // New tedy , this function will get the web elements by The new attribute
- // value(data-tests-id)
- public static List<WebElement> getWebElements(String dataTestId) {
- return waitForElementsListVisibility(dataTestId);
- }
-
- // New tedy , this function will get the web element Button by The new
- // attribute value(data-tests-id)
- public static WebElement getWebButton(String dataTestId) {
- WebDriverWait wait = new WebDriverWait(driver, 3 * 60);
- return wait
- .until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@data-tests-id='" + dataTestId + "']")));
- }
-
- // New tedy , this function will wait till the web element be
- // visible(data-tests-id)
- public static Boolean waitForInvisibileElement(String dataTestId) {
- WebDriverWait wait = new WebDriverWait(driver, 3 * 60);
- return wait.until(
- ExpectedConditions.invisibilityOfElementLocated(By.xpath("//*[@data-tests-id='" + dataTestId + "']")));
- }
-
- public static WebElement waitFordataTestIdVisibility(String dataTestId) {
- WebDriverWait wait = new WebDriverWait(driver, 3 * 60);
- return wait.until(
- ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@data-tests-id='" + dataTestId + "']")));
- }
-
- public static boolean clickcheckbox(String category) {
- try {
-
- } catch (Exception e) {
- return false;
- }
- return true;
- }
-
- public static WebElement waitForContainsdataTestIdVisibility2(String dataTestId) {
- WebDriverWait wait = new WebDriverWait(driver, 5);
- return wait.until(ExpectedConditions
- .visibilityOfElementLocated(By.xpath("//*[contains (@data-tests-id, '" + dataTestId + "'])")));
- }
-
- public static List<WebElement> waitForContainsdataTestIdVisibility(String dataTestId) {
- WebDriverWait wait = new WebDriverWait(driver, 5);
- return wait.until(ExpectedConditions
- .visibilityOfAllElementsLocatedBy(By.xpath("//*[contains (@data-tests-id, '" + dataTestId + "'])")));
- }
-
- public static WebElement waitForClassNameVisibility(String className) {
- return waitForElementVisibility(By.className(className));
- }
-
- public static WebElement waitForElementVisibility(By by) {
- return waitForElementVisibility(by, 3 * 60);
- }
-
- public static WebElement waitForElementVisibility(By by, int duration) {
- WebDriverWait wait = new WebDriverWait(driver, duration);
- return wait.until(ExpectedConditions.visibilityOf(driver.findElement(by)));
- }
-
- public static List<WebElement> waitForElementsListVisibility(By by) {
- WebDriverWait wait = new WebDriverWait(driver, 3 * 60);
- return wait.until(ExpectedConditions.visibilityOfAllElements(driver.findElements(by)));
- }
-
- public static boolean waitForElementsListInvisibility(By by) {
- WebDriverWait wait = new WebDriverWait(driver, 3 * 60);
- return wait.until(ExpectedConditions.invisibilityOfElementLocated(by));
- }
-
- // New tedy , this function will wait till the web elements be
- // visible(data-tests-id)
- public static List<WebElement> waitForElementsListVisibility(String dataTestId) {
- WebDriverWait wait = new WebDriverWait(driver, 3 * 60);
- List<WebElement> findElements = wait.until(ExpectedConditions
- .visibilityOfAllElementsLocatedBy(By.xpath("//*[@data-tests-id='" + dataTestId + "']")));
- if (findElements.size() > 0) {
- return findElements;
- }
- System.out.println("Elements not Exist!");
- return null;
- }
-
- public static List<WebElement> waitForElementsListVisibilityTestMethod(String dataTestId) {
- return driver.findElements(By.xpath("//*[@data-tests-id='" + dataTestId + "']"));
- }
-
- public static WebElement waitForBrowseButton(String dataTestId) {
-
- return driver.findElement(By.xpath("//*[@data-tests-id='" + dataTestId + "']"));
- }
-
- public static List<WebElement> getWebElementsListByDataTestId(String dataTestId) {
- return driver.findElements(By.xpath("//*[@data-tests-id='" + dataTestId + "']"));
-
- }
-
- public static WebElement getWebElementByDataTestId(String dataTestId) {
- return driver.findElement(By.xpath("//*[@data-tests-id='" + dataTestId + "']"));
- }
-
- public static WebElement waitUntilClickableButton(String dataTestId) {
- WebDriverWait wait = new WebDriverWait(driver, 3 * 60);
- return wait.until(ExpectedConditions
- .elementToBeClickable(driver.findElement(By.xpath("//*[@data-tests-id='" + dataTestId + "']"))));
- }
-
- // interface Throws {
- // <T,R, E extends Exception> R apply(T t) throws E;
- // }
- // public static <R> R swallowException(Throws<T,R,E> supplier){
- // R returnValue;
- // try{
- // returnValue = supplier.get();
- // }
- // catch(Exception e){
- // returnValue = null;
- // }
- // return returnValue;
- // }
- // Use this method only for special cases, otherwise use
- // org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils.getWebElementWaitForVisible(WebDriver,
- // String)
-
- public static boolean isElementPresent(String dataTestId) {
- try {
- driver.findElement(By.xpath("//*[@data-tests-id='" + dataTestId + "']"));
- return true;
- } catch (org.openqa.selenium.NoSuchElementException e) {
- return false;
- }
- }
-
- public static <R> R retryMethodOnException(Supplier<R> supplier) {
- boolean stopSearch = false;
- R ret = null;
- Exception throwMe = null;
- int timeElapsed = 0;
- while (!stopSearch) {
- try {
- ret = supplier.get();
- } catch (Exception e) {
- throwMe = e;
- GeneralUIUtils.sleep(250);
- timeElapsed += 250;
- if (timeElapsed > 5000) {
- stopSearch = true;
- }
-
- } finally {
- if (ret != null) {
- stopSearch = true;
- }
- }
- }
- if (ret == null) {
- throw new RuntimeException(throwMe);
- } else {
- return ret;
- }
-
- }
-
- // this method will login as tester and start test or accept Assets.
- public static void testerUser(Boolean startTest, Boolean accept, ResourceReqDetails resource) throws Exception {
- // GeneralUIUtils.getWebElement(ResourceUIUtils.getName()).click();
- String url = "http://localhost:8181/sdc1/proxy-tester1#/dashboard";
- sleep(2000);
- SetupCDTest.navigateToUrl(url);
- GeneralUIUtils.getWebElementWaitForVisible(resource.getName()).click();
-
- if (startTest) {
- clickStartTesting();
- }
-
- if (accept) {
- clickAccept();
- }
- }
-
- public static void governorUser(Boolean reject, Boolean approve, ResourceReqDetails resource) throws Exception {
- // GeneralUIUtils.getWebElement(ResourceUIUtils.getName()).click();
- String url = "http://localhost:8181/sdc1/proxy-governor1#/dashboard";
- sleep(2000);
- SetupCDTest.navigateToUrl(url);
- GeneralUIUtils.getWebElementWaitForVisible("w-sdc-dashboard-card-info");
- GeneralUIUtils.getWebElementWaitForVisible(resource.getName()).click();
- if (reject) {
- clickReject();
- }
- if (approve) {
- clickApprove();
- }
- sleep(1000);
- }
-
- public static void opsUser(Boolean disribute, Boolean reDisribute, ResourceReqDetails resource) throws Exception {
- // GeneralUIUtils.getWebElement(ResourceUIUtils.getName()).click();
- String url = "http://localhost:8181/sdc1/proxy-ops1#/dashboard";
- sleep(2000);
- SetupCDTest.navigateToUrl(url);
- sleep(2000);
- GeneralUIUtils.getWebElementWaitForVisible("w-sdc-dashboard-card-info");
- GeneralUIUtils.getWebElementWaitForVisible(resource.getName()).click();
- if (reDisribute) {
- clickReDistribute();
- }
- if (disribute) {
- clickDistribute();
- }
- sleep(1000);
- }
-
- // this function located select list by the data-test-id value and the item
- // to be selected..
- public static Select getSelectList(String item, String datatestsid) {
- Select selectlist = new Select(waitFordataTestIdVisibility(datatestsid));
- 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;
- }
-
- public static WebElement catalogSearchBox(String searchText) {
- WebElement searchBox = GeneralUIUtils.getWebElementWaitForVisible("main-menu-input-search");
- searchBox.clear();
- searchBox.sendKeys(searchText);
- return searchBox;
- }
-
- // enum
- public static void selectMenuOptionbyname(List<WebElement> options, MenuOptionsEnum optionName)
- throws InterruptedException {
-
- for (WebElement webElement : options) {
- if (webElement.getText().equals(optionName.getValue())) {
- actionBuild(webElement).click();
- } else {
- System.out.println("No such element!");
- }
- }
-
- }
-
- // back to workspace by Clicking the ASDC Logo.!
- public static void clickASDCLogo() {
- WebDriverWait wait = new WebDriverWait(driver, 15);
- wait.until(ExpectedConditions.visibilityOfElementLocated(By.linkText("ASDC")));
- WebElement ClickASDCLogo = driver.findElement(By.linkText("ASDC"));
- ClickASDCLogo.click();
- GeneralUIUtils.waitForLoader();
- }
-
- public static void clickExitSign() throws InterruptedException {
- WebElement exitSign = driver.findElement(By.xpath("//*[contains(@class, 'x-btn')]"));
- actionBuild(exitSign);
- Thread.sleep(1000);
- driver.findElement(By.xpath("//*[contains(@class, 'x-btn')]")).click();
- }
-
- public static void clickCreateButton() throws Exception {
- getWebButton("create/save").click();
- GeneralUIUtils.waitForLoader();
- getWebElementWaitForVisible(DataTestIdEnum.LifeCyleChangeButtons.CHECK_IN.getValue());
- }
-
- public static void clickUpdateButton() throws Exception {
- GeneralUIUtils.sleep(500);
- clickCreateButton();
- }
-
- public static void checkOut() throws InterruptedException, AWTException {
- actionBuild(getWebButton("check_out"));
- getWebButton("check_out").click();
- waitForInvisibileElement("check_out");
- }
-
- public static void clickStartTesting() throws InterruptedException {
- actionBuild(getWebButton("start_testing"));
- getWebButton("start_testing").click();
- waitForInvisibileElement("start_testing");
- getWebButton("create/save").click();
- }
-
- public static void clickAccept() throws InterruptedException {
- actionBuild(getWebButton("accept"));
- getWebButton("accept").click();
- getWebElementWaitForVisible("checkindialog").sendKeys("Accept!");
- clickOkButton();
- sleep(1000);
- }
-
- public static void clickReject() throws InterruptedException {
- actionBuild(getWebButton("reject"));
- getWebButton("reject").click();
- waitForInvisibileElement("reject");
- }
-
- public static void clickApprove() throws InterruptedException {
- actionBuild(getWebButton("approve"));
- getWebButton("approve").click();
- waitForInvisibileElement("approve");
- }
-
- public static void clickDistribute() throws InterruptedException {
- actionBuild(getWebButton("distribute"));
- getWebButton("distribute").click();
- waitForInvisibileElement("redistribute");
- }
-
- public static void clickReDistribute() throws InterruptedException {
- actionBuild(getWebButton("redistribute"));
- getWebButton("redistribute").click();
- }
-
- public static void clickCancel() {
- getWebButton("cancel").click();
- waitForInvisibileElement("cancel");
- }
-
- public static void checkIn() throws InterruptedException {
- actionBuild(getWebButton("check_in"));
- getWebButton("check_in").click();
- getWebElementWaitForVisible("checkindialog").sendKeys("Check in!");
- clickOkButton();
- waitForInvisibileElement("checkindialog");
- }
-
- public static void clickSaveIcon() throws InterruptedException {
- actionBuild(GeneralUIUtils.waitFordataTestIdVisibility("create/save"));
- GeneralUIUtils.getWebButton(/* "delete_version" */"create/save").click();
- Thread.sleep(1000);
-
- }
-
- // Open menu of Created Object and select option.
- public static void openObjectMenuAndSelectOption(String uniqid, MenuOptionsEnum optionName)
- throws InterruptedException, AWTException {
- WebElement hoverOnMenu = actionBuild(getWebElementWaitForVisible(uniqid));
- List<WebElement> menuOptions = hoverOnMenu.findElement(By.xpath("./following-sibling::*[1]"))
- .findElements(By.xpath(".//*"));
- selectMenuOptionbyname(menuOptions, optionName);
- }
-
- // Get elements by className.
- public static WebElement getEelementByClassName(String element) {
- try {
- WebDriverWait wait = new WebDriverWait(driver, 3 * 60);
- return wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@class='" + element + "']")));
- } catch (Exception e) {
- return null;
- }
- }
-
- public static List<WebElement> getEelementsByClassName(String element) {
- WebDriverWait wait = new WebDriverWait(driver, 3 * 60);
- return wait
- .until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//*[@class='" + element + "']")));
- }
-
- public static WebElement getEelementByContainsdatatestsid(String datatestId) {
- WebDriverWait wait = new WebDriverWait(driver, 3 * 60);
- return wait.until(ExpectedConditions
- .visibilityOfElementLocated(By.xpath("//*[contains(@data-tests-id, '" + datatestId + "')]")));
- }
-
- // list
- public static List<WebElement> getEelementsByContainsDataTestsId(String datatestId) {
- WebDriverWait wait = new WebDriverWait(driver, 3 * 60);
- return wait.until(ExpectedConditions
- .visibilityOfAllElementsLocatedBy(By.xpath("//*[contains(@data-tests-id, '" + datatestId + "')]")));
- }
-
- public static WebElement getEelementBycontainsClassName(String classname) {
- WebDriverWait wait = new WebDriverWait(driver, 3 * 60);
- return wait.until(
- ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[contains(@class, '" + classname + "')]")));
- }
-
- public static WebElement getEelementByLinkText(String linkText) {
- WebDriverWait wait = new WebDriverWait(driver, 3 * 60);
- return wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@text='" + linkText + "']")));
- }
-
- public static List<WebElement> getEelementsBycontainsClassName(String classname) {
- WebDriverWait wait = new WebDriverWait(driver, 3 * 60);
- return wait.until(ExpectedConditions
- .visibilityOfAllElementsLocatedBy(By.xpath("//*[contains(@class, '" + classname + "')]")));
- }
-
- public static WebElement getButtonByClassName(String element) {
- WebDriverWait wait = new WebDriverWait(driver, 3 * 60);
- return wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//button[@class='" + element + "']")));
- }
-
- public static void checkinCheckout(String elementName) throws Exception, Exception {
- checkIn();
- getWebElementWaitForVisible(elementName).click();
- ;
- checkOut();
-
- }
-
- public static void moveToStep(DataTestIdEnum.StepsEnum Stepname) {
- moveToStep(Stepname.getValue());
- }
-
- public static void moveToStep(String dataTestId) {
- getWebButton(dataTestId).click();
- waitForLoader();
- }
-
- public static void editFile(String name) {
- WebElement editfilebutton = driver.findElement(By.id("edit" + name + ""));
- editfilebutton.click();
- }
-
- public static void deleteFile(String name) {
- WebElement deletebutton = driver.findElement(By.id("delete" + name + ""));
- deletebutton.click();
- }
-
- public static void downloadFile(String name) {
- WebElement downloadbutton = driver.findElement(By.id("download" + name + ""));
- downloadbutton.click();
- }
-
- public static void sleep(int duration) {
- try {
- Thread.sleep(duration);
- } catch (InterruptedException e) {
- throw new RuntimeException(e);
- }
- }
-
- public static void hasDriver() {
- try {
- driver.getCurrentUrl();
- driver.quit();
- } catch (NullPointerException e) {
- }
- }
-
- public static void initDriver() {
- try {
- boolean remoteTesting = SetupCDTest.config.isRemoteTesting();
- if (!remoteTesting) {
- System.out.println("opening LOCAL browser");
- driver = new FirefoxDriver();
-
- } else {
- System.out.println("opening REMOTE browser");
- 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);
- driver = new RemoteWebDriver(new URL(remoteNodeUrl), cap);
- }
-
-
- } catch (MalformedURLException e) {
- throw new RuntimeException(e);
- }
-
- }
-
- public static void windowZoomOut() {
- final int zoomOutFactor = 2;
- for (int i = 0; i < zoomOutFactor; i++) {
- driver.findElement(By.tagName("html")).sendKeys(Keys.chord(Keys.CONTROL, Keys.SUBTRACT));
- }
- }
-
- public static void defineTagsList(ResourceReqDetails resource, String[] resourceTags) {
- List<String> taglist = new ArrayList<String>();
- ;
- WebElement resourceTagsTextbox = getWebElementWaitForVisible("i-sdc-tag-input");
- for (String tag : resourceTags) {
- resourceTagsTextbox.clear();
- resourceTagsTextbox.sendKeys(tag);
- resourceTagsTextbox.sendKeys(Keys.ENTER);
- taglist.add(tag);
- // waitForElements(By.className("sdc-loader"), 250, 15000);
- }
- }
-
- // public static List<WebElement> waitForElements(By by, int napPeriod, int
- // maxWaitMS){
- // List<WebElement> elements = null;
- //
- // elements = getDriver().findElements(by);
- // if( currentWaitTimeMS > maxWaitMS){
- // }
- // resource.setTags(taglist);
- // return elements;
- // }
- public static void selectTabInRightPallete(String className) throws Exception {
- WebElement tab = getEelementBycontainsClassName(className);
- tab.click();
- }
-
- public static WebElement getWebElement(WebDriver driver, String dataTestId) {
- return waitForElementVisibility(dataTestId);
- }
-
- public static void clickOkButton() throws InterruptedException {
- // actionBuild(getWebButton("OK"));
- // sleep(2000);
- getWebButton("OK").click();
- }
-
- public static WebElement waitForElementVisibility(String dataTestId) {
- WebDriverWait wait = new WebDriverWait(GeneralUIUtils.getDriver(), 30);
- return wait.until(
- ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@data-tests-id='" + dataTestId + "']")));
- }
-
- public static WebElement deleteVersion() {
- return GeneralUIUtils.waitFordataTestIdVisibility("delete_version");
- }
-
- // public static List<WebElement> getFilterTitles() throws Exception {
- //
- // return
- // GeneralUIUtils.getEelementsByClassName("i-sdc-designer-leftbar-section-title-text");
- //
- // }
-
- public static void deleteVersionInUI() throws Exception {
-
- actionBuild(deleteVersion());
- deleteVersion().click();
- GeneralUIUtils.clickOkButton();
- }
-
- public static void uploadFileWithJavaRobot(String FilePath, String FileName) throws Exception {
- StringSelection sel = new StringSelection(FilePath + FileName);
- Toolkit.getDefaultToolkit().getSystemClipboard().setContents(sel, null);
- Thread.sleep(1000);
- Robot robot = new Robot();
- robot.delay(1000);
-
- // Release Enter
- robot.keyRelease(KeyEvent.VK_ENTER);
-
- // Press CTRL+V
- robot.keyPress(KeyEvent.VK_CONTROL);
- robot.keyPress(KeyEvent.VK_V);
-
- // Release CTRL+V
- robot.keyRelease(KeyEvent.VK_CONTROL);
- robot.keyRelease(KeyEvent.VK_V);
- Thread.sleep(1000);
-
- // Press Enter
- robot.keyPress(KeyEvent.VK_ENTER);
- robot.keyRelease(KeyEvent.VK_ENTER);
- Thread.sleep(3000);
- }
-
- public static String catalogFilterTypeChecBox(TypesEnum enumtype) throws Exception {
- String Type = enumtype.toString().toLowerCase();
- getWebElementWaitForVisible(enumtype.getValue()).click();
- return Type;
- }
-
- public static List<String> catalogFilterStatusChecBox(CheckBoxStatusEnum statusEnum) throws Exception {
- List<String> status = null;
- switch (statusEnum) {
- case IN_DESIGN:
- status = Arrays.asList("NOT_CERTIFIED_CHECKIN", "NOT_CERTIFIED_CHECKOUT");
- getWebElementWaitForVisible(statusEnum.getCatalogValue()).click();
- break;
- case READY_FOR_TESTING:
- status = Arrays.asList("READY_FOR_CERTIFICATION");
- getWebElementWaitForVisible(statusEnum.getCatalogValue()).click();
- break;
- case IN_TESTING:
- status = Arrays.asList("CERTIFICATION_IN_PROGRESS");
- getWebElementWaitForVisible(statusEnum.getCatalogValue()).click();
- break;
- case CERTIFIED:
- status = Arrays.asList("CERTIFIED");
- getWebElementWaitForVisible(statusEnum.getCatalogValue()).click();
- break;
- case DISTRIBUTED:
- status = Arrays.asList("CERTIFIED");
- getWebElementWaitForVisible(statusEnum.getCatalogValue()).click();
- break;
- }
- return status;
- }
-
- public static void clickBreadCrumbs(BreadCrumbsButtonsEnum button) {
- switch (button) {
- case CATALOG:
- GeneralUIUtils.getWebButton(button.getButton()).click();
- break;
- case HOME:
- GeneralUIUtils.getWebButton(button.getButton()).click();
- break;
- case ON_BOARDING:
- GeneralUIUtils.getWebButton(button.getButton()).click();
- break;
- default:
- break;
- }
- }
-
- public static void clickPrintScreen() {
- getEelementByClassName("e-sdc-small-print-screen").click();
- }
-
- public static void clickSubmitForTest() throws InterruptedException {
- getWebButton("submit_for_testing").click();
- WebElement commentText = getDriver().findElement(By.className("w-sdc-modal-body-email"));
- commentText.sendKeys("Submit For Test");
- sleep(3000);
- clickOkButton();
- }
-
- public static WebElement hoverOnArea(String areaId, WebDriver driver) {
- Actions actions = new Actions(driver);
- WebElement area = getWebElement(driver, areaId);
- actions.moveToElement(area).perform();
- return area;
- }
-
- public static WebElement moveToNextStep(DataTestIdEnum.StepsEnum Stepname) {
- return getWebButton(Stepname.getValue());
- }
-
- public static String getComponentVersion(String componentName) {
- return GeneralUIUtils.getWebElementWaitForVisible(componentName + "Version").getText();
- }
-
- public static void clickOnHTMLElementByDataTestId(String dataTestId) throws Exception {
- WebDriverWait wait = new WebDriverWait(GeneralUIUtils.getDriver(), 20);
- StopWatch performanceMesuring = new StopWatch();
- performanceMesuring.start();
- WebElement element = wait
- .until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@data-tests-id='" + dataTestId + "']")));
- performanceMesuring.stop();
- element.click();
- performanceMesuring(dataTestId, performanceMesuring);
-
- }
-
- private static void performanceMesuring(String dataTestId, StopWatch performanceMesuring) {
- Reporter.log("click on: " + dataTestId);
- System.out.println("click on: " + dataTestId);
- Reporter.log("Total Load Time Until click on button : " + dataTestId + " "
- + (((double) performanceMesuring.getTime()) / 1000) + " seconds");
- System.out.println("Total Load Time Until click on button : " + dataTestId + " "
- + (((double) performanceMesuring.getTime()) / 1000) + " seconds");
- performanceMesuring.reset();
- performanceMesuring.start();
- Boolean waitForElementInVisibilityByClassName = GeneralUIUtils.waitForElementInVisibilityByClassName(driver,
- "tlv-loader");
- performanceMesuring.stop();
- Reporter.log("Total time before loader disappear: " + (((double) performanceMesuring.getTime()) / 1000)
- + " seconds");
- System.out.println("Total time before loader disappear: " + (((double) performanceMesuring.getTime()) / 1000)
- + " seconds");
- }
-
- public static Boolean waitForElementInVisibilityByClassName(WebDriver driver, String className) {
- WebDriverWait wait = new WebDriverWait(driver, 30);
- return wait.until(ExpectedConditions.invisibilityOfElementLocated(By.className(className)));
- }
-
- public static void findComponentAndClick(ResourceReqDetails resource) throws Exception {
-
- WebElement searchTextbox = GeneralUIUtils.getWebElementWaitForVisible("main-menu-input-search");
- searchTextbox.clear();
- searchTextbox.sendKeys(resource.getName());
- clickOnHTMLElementByDataTestId(resource.getName());
- }
-
- public static void clickOnHTMLElementBylinkText(String linkText) throws Exception {
- WebDriverWait wait = new WebDriverWait(GeneralUIUtils.getDriver(), 20);
- StopWatch performanceMesuring = new StopWatch();
- performanceMesuring.start();
- WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.linkText(linkText)));
- performanceMesuring.stop();
- element.click();
- performanceMesuring(linkText, performanceMesuring);
- }
-
- public static void ultimateWait(){
- long startTime = System.nanoTime();
-
- GeneralUIUtils.waitForLoader();
- GeneralUIUtils.waitForAngular();
-
- long estimateTime = System.nanoTime();
- long duration = TimeUnit.NANOSECONDS.toSeconds(estimateTime - startTime);
- if(duration > timeOut){
- SetupCDTest.getExtendTest().log(LogStatus.WARNING, String.format("Delays on page, %d seconds", duration));
- }
- }
-
- public static void waitForAngular(){
- WebDriverWait wait = new WebDriverWait(getDriver(), 90, 100);
- wait.until(AdditionalConditions.pageLoadWait());
- wait.until(AdditionalConditions.angularHasFinishedProcessing());
- }
-
-}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/ImportAssetUIUtils.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/ImportAssetUIUtils.java
deleted file mode 100644
index f917a4784f..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/ImportAssetUIUtils.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.utilities;
-
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.ci.tests.datatypes.CreateAndImportButtonsEnum;
-import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
-import org.openqa.selenium.By;
-import org.openqa.selenium.WebDriver;
-
-public class ImportAssetUIUtils {
-
- public static void importAsssetAndFillGeneralInfo(String FILE_PATH, String fileName,
- ResourceReqDetails resourceDetails, User user, CreateAndImportButtonsEnum type) throws Exception {
- ResourceUIUtils.importFileWithSendKey(FILE_PATH, fileName, type);
- ResourceUIUtils.fillResourceGeneralInformationPage(resourceDetails, user);
- }
-
- public static void importAsssetFillGeneralInfoAndSelectIcon(String FILE_PATH, String fileName,
- ResourceReqDetails resourceDetails, User user, CreateAndImportButtonsEnum type) throws Exception {
- importAsssetAndFillGeneralInfo(FILE_PATH, fileName, resourceDetails, user, type);
- GeneralUIUtils.clickCreateButton();
- ResourceUIUtils.selectRandomResourceIcon();
- }
-
- // checking or unchecking the checkbox on right palette at designer
- // workspace
- public static void checkbox(String checkBoxname, WebDriver driver) {
- driver.findElement(By.xpath("//label[@for='" + checkBoxname + "']")).click();
- }
-
-}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/OnboardingUtils.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/OnboardingUtils.java
deleted file mode 100644
index db6bada41e..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/OnboardingUtils.java
+++ /dev/null
@@ -1,457 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.utilities;
-
-import static org.testng.AssertJUnit.assertEquals;
-
-import java.io.File;
-import java.io.FilenameFilter;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.StringWriter;
-import java.nio.file.FileSystems;
-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.UUID;
-import java.util.zip.ZipFile;
-
-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.JSONObject;
-import org.openecomp.sdc.be.model.User;
-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.execute.setup.SetupCDTest;
-import org.openecomp.sdc.ci.tests.utils.Utils;
-import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
-import org.testng.Assert;
-
-import com.relevantcodes.extentreports.LogStatus;
-
-public class OnboardingUtils {
-
- public OnboardingUtils() {
- }
-
- private static String vendorId;
- private static String vendorLicenseName;
- private static String vendorLicenseAgreementId;
- private static String featureGroupId;
-
- public int countFilesInZipDirectory(String filepath, String filename) throws Exception, Throwable {
- ZipFile zipFile = new ZipFile(filepath + filename);
- return zipFile.size() - 1;
- }
-
- public static Object[] getZipFileNamesFromFolder(String filepath) {
- return FileHandling.getFileNamesFromFolder(filepath, ".zip");
- }
-
- public static String createVendorSoftwareProduct(String HeatFileName, String filepath, User user)
- throws Exception, Throwable {
- String vspName = handleFilename(HeatFileName);
- SetupCDTest.getExtendTest().log(LogStatus.INFO, "Starting to create vendor software product");
-
- RestResponse createNewVendorSoftwareProduct = createNewVendorSoftwareProduct(vspName, vendorLicenseName,
- vendorId, vendorLicenseAgreementId, featureGroupId, user);
- assertEquals("did not succeed to create new VSP", 200,
- createNewVendorSoftwareProduct.getErrorCode().intValue());
- String vspid = ResponseParser.getValueFromJsonResponse(createNewVendorSoftwareProduct.getResponse(), "vspId");
-
- RestResponse uploadHeatPackage = uploadHeatPackage(filepath, HeatFileName, vspid, user);
- assertEquals("did not succeed to upload HEAT package", 200, uploadHeatPackage.getErrorCode().intValue());
-
- RestResponse checkin = checkinVendorSoftwareProduct(vspid, user);
- assertEquals("did not succeed to checking new VSP", 200, checkin.getErrorCode().intValue());
-
- RestResponse submit = submitVendorSoftwareProduct(vspid, user);
- assertEquals("did not succeed to submit new VSP", 200, submit.getErrorCode().intValue());
-
- RestResponse createPackage = createPackageOfVendorSoftwareProduct(vspid, user);
- assertEquals("did not succeed to create package of new VSP ", 200, createPackage.getErrorCode().intValue());
-
- SetupCDTest.getExtendTest().log(LogStatus.INFO, "Succeeded to create vendor software product");
-
- return vspName;
- }
-
- private static String handleFilename(String heatFileName) {
- final String namePrefix = "ciVFOnboarded-";
- final String nameSuffix = "-" + getShortUUID();
-
- String subHeatFileName = heatFileName.substring(0, heatFileName.lastIndexOf("."));
-
- if ((namePrefix + subHeatFileName + nameSuffix).length() >= 50) {
- subHeatFileName = subHeatFileName.substring(0, 50 - namePrefix.length() - nameSuffix.length());
- }
-
- if (subHeatFileName.contains("(") || subHeatFileName.contains(")")) {
- subHeatFileName = subHeatFileName.replace("(", "-");
- subHeatFileName = subHeatFileName.replace(")", "-");
- }
-
- String vnfName = namePrefix + subHeatFileName + nameSuffix;
- return vnfName;
- }
-
- public static void createVendorLicense(User user) throws Exception {
- SetupCDTest.getExtendTest().log(LogStatus.INFO, "Starting to create vendor license");
- vendorLicenseName = "ciLicense" + getShortUUID();
- RestResponse vendorLicenseResponse = createVendorLicenseModels_1(vendorLicenseName, user);
- assertEquals("did not succeed to create vendor license model", 200,
- vendorLicenseResponse.getErrorCode().intValue());
- vendorId = ResponseParser.getValueFromJsonResponse(vendorLicenseResponse.getResponse(), "value");
-
- RestResponse vendorKeyGroupsResponse = createVendorKeyGroups_2(vendorId, user);
- assertEquals("did not succeed to create vendor key groups", 200,
- vendorKeyGroupsResponse.getErrorCode().intValue());
- String keyGroupId = ResponseParser.getValueFromJsonResponse(vendorKeyGroupsResponse.getResponse(), "value");
-
- RestResponse vendorEntitlementPool = createVendorEntitlementPool_3(vendorId, user);
- assertEquals("did not succeed to create vendor entitlement pool", 200,
- vendorEntitlementPool.getErrorCode().intValue());
- String entitlementPoolId = ResponseParser.getValueFromJsonResponse(vendorEntitlementPool.getResponse(),
- "value");
-
- RestResponse vendorLicenseFeatureGroups = createVendorLicenseFeatureGroups_4(vendorId, keyGroupId,
- entitlementPoolId, user);
- assertEquals("did not succeed to create vendor license feature groups", 200,
- vendorLicenseFeatureGroups.getErrorCode().intValue());
- featureGroupId = ResponseParser.getValueFromJsonResponse(vendorLicenseFeatureGroups.getResponse(), "value");
-
- RestResponse vendorLicenseAgreement = createVendorLicenseAgreement_5(vendorId, featureGroupId, user);
- assertEquals("did not succeed to create vendor license agreement", 200,
- vendorLicenseAgreement.getErrorCode().intValue());
- vendorLicenseAgreementId = ResponseParser.getValueFromJsonResponse(vendorLicenseAgreement.getResponse(),
- "value");
-
- RestResponse checkinVendorLicense = checkinVendorLicense(vendorId, user);
- assertEquals("did not succeed to checkin vendor license", 200, checkinVendorLicense.getErrorCode().intValue());
-
- RestResponse submitVendorLicense = submitVendorLicense(vendorId, user);
- assertEquals("did not succeed to submit vendor license", 200, submitVendorLicense.getErrorCode().intValue());
-
- SetupCDTest.getExtendTest().log(LogStatus.INFO, "Succeeded to create vendor license");
- }
-
- private static String getShortUUID() {
- return UUID.randomUUID().toString().split("-")[0];
- }
-
- private static RestResponse actionOnComponent(String vspid, String action, String onboardComponent, User user) throws Exception {
- Config config = Utils.getConfig();
- String url = String.format("http://%s:%s/onboarding-api/v1.0/" + onboardComponent + "/%s/actions", config.getCatalogBeHost(), config.getCatalogBePort(), vspid);
- 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;
- }
-
- private static RestResponse checkinVendorLicense(String vspid, User user) throws Exception {
- return actionOnComponent(vspid, "Checkin", "vendor-license-models", user);
- }
-
- private static RestResponse submitVendorLicense(String vspid, User user) throws Exception {
- return actionOnComponent(vspid, "Submit", "vendor-license-models", user);
- }
-
- private static RestResponse createVendorLicenseModels_1(String name, User user) throws Exception {
- Config config = Utils.getConfig();
- String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-license-models", config.getCatalogBeHost(), config.getCatalogBePort());
- String userId = user.getUserId();
- JSONObject jObject = new JSONObject();
- jObject.put("vendorName", name);
- jObject.put("description", "new vendor license model");
- jObject.put("iconRef", "icon");
-
- Map<String, String> headersMap = prepareHeadersMap(userId);
-
- HttpRequest http = new HttpRequest();
- RestResponse response = http.httpSendPost(url, jObject.toString(), headersMap);
- return response;
-
- }
-
- private static RestResponse createVendorLicenseAgreement_5(String vspid, String featureGroupId, User user)
- throws Exception {
- Config config = Utils.getConfig();
- String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-license-models/%s/license-agreements",
- config.getCatalogBeHost(), config.getCatalogBePort(), vspid);
-
- String userId = user.getUserId();
-
- JSONObject licenseTermpObject = new JSONObject();
- licenseTermpObject.put("choice", "Fixed_Term");
- licenseTermpObject.put("other", "");
-
- JSONObject jObjectBody = new JSONObject();
- jObjectBody.put("name", "abc");
- jObjectBody.put("description", "new vendor license agreement");
- jObjectBody.put("requirementsAndConstrains", "abc");
- jObjectBody.put("licenseTerm", licenseTermpObject);
- jObjectBody.put("addedFeatureGroupsIds", Arrays.asList(featureGroupId).toArray());
-
- Map<String, String> headersMap = prepareHeadersMap(userId);
-
- HttpRequest http = new HttpRequest();
- RestResponse response = http.httpSendPost(url, jObjectBody.toString(), headersMap);
- return response;
- }
-
- private static RestResponse createVendorLicenseFeatureGroups_4(String vspid, String licenseKeyGroupId,
- String entitlementPoolId, User user) throws Exception {
- Config config = Utils.getConfig();
- String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-license-models/%s/feature-groups",
- config.getCatalogBeHost(), config.getCatalogBePort(), vspid);
-
- String userId = user.getUserId();
-
- JSONObject jObject = new JSONObject();
- jObject.put("name", "xyz");
- jObject.put("description", "new vendor license feature groups");
- jObject.put("partNumber", "123abc456");
- jObject.put("addedLicenseKeyGroupsIds", Arrays.asList(licenseKeyGroupId).toArray());
- jObject.put("addedEntitlementPoolsIds", Arrays.asList(entitlementPoolId).toArray());
-
- Map<String, String> headersMap = prepareHeadersMap(userId);
-
- HttpRequest http = new HttpRequest();
- RestResponse response = http.httpSendPost(url, jObject.toString(), headersMap);
- return response;
-
- }
-
- private static RestResponse createVendorEntitlementPool_3(String vspid, User user) throws Exception {
- Config config = Utils.getConfig();
- String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-license-models/%s/entitlement-pools",
- config.getCatalogBeHost(), config.getCatalogBePort(), vspid);
-
- String userId = user.getUserId();
-
- JSONObject jEntitlementMetricObject = new JSONObject();
- jEntitlementMetricObject.put("choice", "CPU");
- jEntitlementMetricObject.put("other", "");
-
- JSONObject jAggregationFunctionObject = new JSONObject();
- jAggregationFunctionObject.put("choice", "Peak");
- jAggregationFunctionObject.put("other", "");
-
- JSONObject jOperationalScope = new JSONObject();
- jOperationalScope.put("choices", Arrays.asList("Availability_Zone").toArray());
- jOperationalScope.put("other", "");
-
- JSONObject jTimeObject = new JSONObject();
- jTimeObject.put("choice", "Hour");
- jTimeObject.put("other", "");
-
- JSONObject jObjectBody = new JSONObject();
- jObjectBody.put("name", "def");
- jObjectBody.put("description", "new vendor license entitlement pool");
- jObjectBody.put("thresholdValue", "23");
- jObjectBody.put("thresholdUnits", "Absolute");
- jObjectBody.put("entitlementMetric", jEntitlementMetricObject);
- jObjectBody.put("increments", "abcd");
- jObjectBody.put("aggregationFunction", jAggregationFunctionObject);
- jObjectBody.put("operationalScope", jOperationalScope);
- jObjectBody.put("time", jTimeObject);
- jObjectBody.put("manufacturerReferenceNumber", "123aaa");
-
- Map<String, String> headersMap = prepareHeadersMap(userId);
-
- HttpRequest http = new HttpRequest();
- RestResponse response = http.httpSendPost(url, jObjectBody.toString(), headersMap);
- return response;
- }
-
- private static RestResponse createVendorKeyGroups_2(String vspid, User user) throws Exception {
- Config config = Utils.getConfig();
- String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-license-models/%s/license-key-groups",
- config.getCatalogBeHost(), config.getCatalogBePort(), vspid);
-
- String userId = user.getUserId();
-
- JSONObject jOperationalScope = new JSONObject();
- jOperationalScope.put("choices", Arrays.asList("Tenant").toArray());
- jOperationalScope.put("other", "");
-
- JSONObject jObjectBody = new JSONObject();
- jObjectBody.put("name", "keyGroup");
- jObjectBody.put("description", "new vendor license key group");
- jObjectBody.put("operationalScope", jOperationalScope);
- jObjectBody.put("type", "Universal");
-
- Map<String, String> headersMap = prepareHeadersMap(userId);
-
- HttpRequest http = new HttpRequest();
- RestResponse response = http.httpSendPost(url, jObjectBody.toString(), headersMap);
- return response;
- }
-
- private static RestResponse createNewVendorSoftwareProduct(String name, String vendorName, String vendorId,
- String licenseAgreementId, String featureGroupsId, User user) throws Exception {
- Config config = Utils.getConfig();
- String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-software-products",
- config.getCatalogBeHost(), config.getCatalogBePort());
-
- String userId = user.getUserId();
-
- JSONObject jlicensingDataObj = new JSONObject();
- jlicensingDataObj.put("licenseAgreement", licenseAgreementId);
- jlicensingDataObj.put("featureGroups", Arrays.asList(featureGroupsId).toArray());
-
- JSONObject jObject = new JSONObject();
- jObject.put("name", name);
- jObject.put("description", "new VSP description");
- jObject.put("category", "resourceNewCategory.generic");
- jObject.put("subCategory", "resourceNewCategory.generic.database");
- jObject.put("licensingVersion", "1.0");
- jObject.put("vendorName", vendorName);
- jObject.put("vendorId", vendorId);
- 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, User user)
- throws Exception {
- Config config = Utils.getConfig();
- CloseableHttpResponse response = null;
-
- MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
- mpBuilder.addPart("upload", 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(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();
- 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();
- }
-
- private static RestResponse checkinVendorSoftwareProduct(String vspid, User user) throws Exception {
- return actionOnComponent(vspid, "Checkin", "vendor-software-products", user);
- }
-
- private static RestResponse submitVendorSoftwareProduct(String vspid, User user) throws Exception {
- return actionOnComponent(vspid, "Submit", "vendor-software-products", user);
- }
-
- private static RestResponse createPackageOfVendorSoftwareProduct(String vspid, User user) throws Exception {
- return actionOnComponent(vspid, "Create_Package", "vendor-software-products", user);
- }
-
- 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;
- }
-
-}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/PropertiesUIUtils.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/PropertiesUIUtils.java
deleted file mode 100644
index a625630196..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/PropertiesUIUtils.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.utilities;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.openecomp.sdc.ci.tests.datatypes.PropertyInfo;
-import org.openecomp.sdc.ci.tests.pages.PropertiesPage;
-import org.openqa.selenium.WebElement;
-
-public class PropertiesUIUtils {
-
- // public static void addPropertByType(String type,String name,String
- // defaultValue,String description) throws Exception{
- //
- // ResourceUIUtils.defineNewSelectList(type);
- // ResourceUIUtils.definePropertyName(name);
- // ResourceUIUtils.defineDefaultValueByType(defaultValue);
- // ResourceUIUtils.defineDescription(description);
- // Thread.sleep(2000);
- // ResourceUIUtils.clickButton("Add");
- // }
- public static Map<String, String> addProperties(String name, String itemType, String defaultValue,
- String description, String schemaType) throws Exception {
- Map<String, String> propertyvalues = new HashMap<String, String>();
- GeneralUIUtils.getSelectList(itemType, "propertyType");
- ResourceUIUtils.definePropertyName(name);
- if (itemType == "boolean") {
- ResourceUIUtils.defineBoolenDefaultValue(defaultValue);
- GeneralUIUtils.defineDescription(description);
- Thread.sleep(2000);
- GeneralUIUtils.getWebButton("Add").click();
- ;
- } else if (itemType == "list" || itemType == "map") {
- GeneralUIUtils.getSelectList(schemaType, "schemaType");
- }
- if (!(itemType == "boolean")) {
- ResourceUIUtils.defineDefaultValueByType(defaultValue);
- GeneralUIUtils.defineDescription(description);
- GeneralUIUtils.getWebButton("Add").click();
- ;
- Thread.sleep(2000);
- }
- propertyvalues.put("type", itemType);
- propertyvalues.put("defaultValue", defaultValue);
- propertyvalues.put("description", description);
- propertyvalues.put("name", name);
-
- return propertyvalues;
- }
-
- public static void vlidateProperties(Map<String, String> propertyValues) throws InterruptedException {
- WebElement name = GeneralUIUtils
- .actionBuild(GeneralUIUtils.getWebElementWaitForVisible(propertyValues.get("name")));
- name.getText().equalsIgnoreCase(propertyValues.get("name"));
- WebElement defaultValue = GeneralUIUtils
- .actionBuild(GeneralUIUtils.getWebElementWaitForVisible(propertyValues.get("name")));
- defaultValue.getText().equalsIgnoreCase(propertyValues.get("defaultValue"));
- WebElement type = GeneralUIUtils
- .actionBuild(GeneralUIUtils.getWebElementWaitForVisible(propertyValues.get("type")));
- type.getText().equalsIgnoreCase(propertyValues.get("type"));
- }
-
- public static void addNewProperty(PropertyInfo property) {
- PropertiesPage.getPropertyPopup().insertPropertyName(property.getName());
- PropertiesPage.getPropertyPopup().selectPropertyType(property.getType().getType());
- PropertiesPage.getPropertyPopup().insertPropertyDescription(property.getDescription());
- PropertiesPage.getPropertyPopup().insertPropertyDefaultValue(property.getValue());
-
- PropertiesPage.getPropertyPopup().clickSave();
- }
-
-}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/ResourceUIUtils.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/ResourceUIUtils.java
deleted file mode 100644
index 9b374c10b8..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/ResourceUIUtils.java
+++ /dev/null
@@ -1,864 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.utilities;
-
-import static org.testng.AssertJUnit.assertEquals;
-import static org.testng.AssertJUnit.assertNotNull;
-import static org.testng.AssertJUnit.assertTrue;
-
-import java.awt.AWTException;
-import java.awt.Robot;
-import java.awt.event.KeyEvent;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Random;
-
-import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.apache.http.HttpStatus;
-import org.json.simple.JSONArray;
-import org.json.simple.JSONObject;
-import org.json.simple.JSONValue;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.ci.tests.datatypes.CheckBoxStatusEnum;
-import org.openecomp.sdc.ci.tests.datatypes.CreateAndImportButtonsEnum;
-import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum;
-import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.Dashboard;
-import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.StepsEnum;
-import org.openecomp.sdc.ci.tests.datatypes.ResourceCategoriesNameEnum;
-import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
-import org.openecomp.sdc.ci.tests.pages.ResourceGeneralPage;
-import org.openqa.selenium.By;
-import org.openqa.selenium.WebDriver;
-import org.openqa.selenium.WebElement;
-import org.openqa.selenium.interactions.Actions;
-import org.openqa.selenium.support.ui.ExpectedConditions;
-import org.openqa.selenium.support.ui.Select;
-import org.openqa.selenium.support.ui.WebDriverWait;
-import org.testng.AssertJUnit;
-
-public final class ResourceUIUtils {
- public static final String RESOURCE_NAME_PREFIX = "ResourceCDTest-";
- protected static final boolean IS_BEFORE_TEST = true;
- public static final String INITIAL_VERSION = "0.1";
- public static final String ICON_RESOURCE_NAME = "call_controll";
- protected static final String UPDATED_RESOURCE_ICON_NAME = "objectStorage";
-
- private ResourceUIUtils() {
- }
-
- static WebDriver driver = GeneralUIUtils.getDriver();
-
- public static void defineResourceName(String resourceName) {
-
- WebElement resourceNameTextbox = GeneralUIUtils.getDriver().findElement(By.name("componentName"));
- resourceNameTextbox.clear();
- resourceNameTextbox.sendKeys(resourceName);
- }
-
- public static void defineResourceCategory(String category, String datatestsid) {
-
- GeneralUIUtils.getSelectList(category, datatestsid);
- }
-
- public static void importFileWithSendKey(String FilePath, String FileName, CreateAndImportButtonsEnum type)
- throws Exception {
- WebElement importButton = GeneralUIUtils.createAndImportButtons(type, driver).findElement(By.tagName("input"));
- importButton.sendKeys(FilePath + FileName);
- }
-
- public static void importFileWithSendKeyBrowse(String FilePath, String FileName) throws Exception {
- WebElement browsebutton = GeneralUIUtils.waitForBrowseButton("browseButton");
- browsebutton.sendKeys(FilePath + FileName);
- }
-
- public static String defineUserId(String userId) {
- WebElement resourceUserIdTextbox = GeneralUIUtils.getWebElementWaitForVisible("contactId");
- resourceUserIdTextbox.clear();
- resourceUserIdTextbox.sendKeys(userId);
- return userId;
- }
-
- public static void defineVendorRelease(String resourceVendorRelease) {
-
- WebElement resourceVendorReleaseTextbox = GeneralUIUtils.getWebElementWaitForVisible("vendorRelease");
- resourceVendorReleaseTextbox.clear();
- resourceVendorReleaseTextbox.sendKeys(resourceVendorRelease);
- }
-
- public static void selectResourceIcon(String resourceIcon) throws Exception {
- WebDriverWait wait = new WebDriverWait(GeneralUIUtils.getDriver(), 10);
- wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//div[@data-tests-id='" + resourceIcon + "']")))
- .click();
- }
-
- public static String definePropertyName(String name) {
-
- WebElement nameProperty = GeneralUIUtils.getDriver().findElement(By.name("propertyName"));
- nameProperty.sendKeys(name);
- return name;
- }
-
- public static void selectRandomResourceIcon() throws Exception {
- GeneralUIUtils.moveToStep(StepsEnum.ICON);
- WebDriverWait wait = new WebDriverWait(GeneralUIUtils.getDriver(), 4);
- wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[contains(@data-tests-id, 'iconBox')]")));
- List<WebElement> iconElement = GeneralUIUtils.getDriver()
- .findElements(By.xpath("//*[contains(@data-tests-id, 'iconBox')]"));
- iconElement.get(0).click();
- }
-
- public static List<WebElement> getAllObjectsOnWorkspace(WebDriver driver, ResourceReqDetails resource)
- throws Exception {
-
- WebDriverWait wait = new WebDriverWait(GeneralUIUtils.getDriver(), 10);
- wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@*='" + resource.getName() + "']")));
- return GeneralUIUtils.getDriver()
- .findElements(By.xpath("//div[@class='" + "w-sdc-dashboard-card-info-name" + "']"));
-
- }
-
- public static String getErrorMessageText(String text) throws Exception {
-
- return GeneralUIUtils.getEelementBycontainsClassName(text).getText();
-
- }
-
- public static WebElement scrollElement(WebDriver driver) throws Exception {
-
- return GeneralUIUtils.getDriver().findElement(By.className("ps-scrollbar-y"));
- }
-
- public static void scrollDownPage() throws AWTException, InterruptedException {
- Robot robot = new Robot();
- robot.keyPress(KeyEvent.VK_PAGE_DOWN);
- robot.keyRelease(KeyEvent.VK_PAGE_DOWN);
- robot.keyPress(KeyEvent.VK_PAGE_DOWN);
- robot.keyRelease(KeyEvent.VK_PAGE_DOWN);
- robot.keyPress(KeyEvent.VK_PAGE_DOWN);
- robot.keyRelease(KeyEvent.VK_PAGE_DOWN);
- robot.keyPress(KeyEvent.VK_PAGE_DOWN);
- robot.keyRelease(KeyEvent.VK_PAGE_DOWN);
- robot.keyPress(KeyEvent.VK_PAGE_DOWN);
- robot.keyRelease(KeyEvent.VK_PAGE_DOWN);
- robot.keyPress(KeyEvent.VK_PAGE_DOWN);
- robot.keyRelease(KeyEvent.VK_PAGE_DOWN);
- robot.keyPress(KeyEvent.VK_PAGE_DOWN);
- robot.keyRelease(KeyEvent.VK_PAGE_DOWN);
- }
-
- public static void defineNewSelectList(String Text) {
- WebElement mySelectElm = GeneralUIUtils.getDriver().findElement(By.className("i-sdc-form-select"));
- Select mySelectString = new Select(mySelectElm);
- mySelectString.selectByVisibleText(Text);
- }
-
- public static void defineDefaultValueByType(String Value) {
-
- WebElement valueString = GeneralUIUtils.getDriver().findElement(By.name("value"));
- valueString.clear();
- valueString.sendKeys(Value);
- }
-
- public static void defineBoolenDefaultValue(String Value) {
-
- WebElement elementBoolean = GeneralUIUtils.getDriver().findElement(By.name("value"));
- Select se = new Select(elementBoolean);
- se.selectByValue(Value);
- }
-
- public static void clickButtonBlue() {
- WebElement clickButtonBlue = GeneralUIUtils.getDriver().findElement(By.className("w-sdc-btn-blue"));
- clickButtonBlue.click();
- }
-
- public static void clickButton(String selectButton) {
-
- WebElement clickButton = GeneralUIUtils.getDriver()
- .findElement(By.xpath("//*[@data-tests-id='" + selectButton + "']"));
- clickButton.click();
- }
-
- public static WebElement Waitfunctionforbuttons(String element, int timeout) {
- WebDriverWait wait = new WebDriverWait(GeneralUIUtils.getDriver(), timeout);
- return wait.until(ExpectedConditions.elementToBeClickable(By.xpath(element)));
- }
-
- public static WebElement waitToButtonSubmitForTesting() {
- return Waitfunctionforbuttons("//*[@data-tests-id='submitForTesting']", 10);
- }
-
- public static WebElement waitToFinishButtonEnabled() {
- return Waitfunctionforbuttons("//button[@data-tests-id='Finish']", 10);
- }
-
- public static WebElement waitToNextButtonEnabled() {
- return Waitfunctionforbuttons("//button[@data-tests-id='Next']", 10);
- }
-
- public static WebElement waitToHomeMenu() {
- return Waitfunctionforbuttons("//*[@data-tests-id='main-menu-button-home']", 10);
- }
-
- public static WebElement waitToCatalogMenu() {
- return Waitfunctionforbuttons("//*[@data-tests-id='main-menu-button-catalog']", 10);
- }
-
- public static WebElement waitSearch() {
- return Waitfunctionforbuttons("//*[@data-tests-id='main-menu-input-search']", 10);
- }
-
- public static WebElement waitSubmitforTestingCard() {
- return Waitfunctionforbuttons("//*[@data-tests-id='i-sdc-dashboard-card-menu-item-SubmitforTesting']", 10);
- }
-
- public static WebElement waitViewCard() {
- return Waitfunctionforbuttons("//*[@data-tests-id='i-sdc-dashboard-card-menu-item-View']", 5);
- }
-
- public static void waitOpenCard(String requiredElementUniqueId) throws Exception {
- WebElement menu = GeneralUIUtils.getDriver()
- .findElement(By.xpath("//*[@data-tests-id='" + requiredElementUniqueId + "']"));
- GeneralUIUtils.actionBuild(menu);
- }
-
- public static void fillResourceGeneralInformationPage(ResourceReqDetails resource, User user) {
- try {
-
- ResourceGeneralPage.defineName(resource.getName());
- ResourceGeneralPage.defineDescription(resource.getDescription());
- ResourceGeneralPage.defineCategory(resource.getCategories().get(0).getSubcategories().get(0).getName());
- ResourceGeneralPage.defineVendorName(resource.getVendorName());
- ResourceGeneralPage.defineVendorRelease(resource.getVendorRelease());
- ResourceGeneralPage.defineTagsList(resource, new String[] { "This-is-tag", "another-tag", "Test-automation-tag" });
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
-
- public static void fillNewResourceValues(ResourceReqDetails resource, User user) throws Exception {
- fillResourceGeneralInformationPage(resource, user);
- GeneralUIUtils.clickCreateButton();
- }
-
- // coded by teddy.
- public static WebElement waitfunctionforallelements(String element) {
- WebDriverWait wait = new WebDriverWait(GeneralUIUtils.getDriver(), 5);
- return wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@*='" + element + "']")));
- }
-
- public static WebElement waitFunctionForaGetElements(String element, int timeout) {
- WebDriverWait wait = new WebDriverWait(GeneralUIUtils.getDriver(), timeout);
- return wait.until(
- ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@data-tests-id='" + element + "']")));
- }
-
- public static void getVFCGeneralInfo(ResourceReqDetails resource, User user) throws InterruptedException {
- Thread.sleep(2000);
- String version = GeneralUIUtils.getWebElements("versionvalue").get(0).getText().substring(1);
- String name = GeneralUIUtils.getWebElementWaitForVisible("name").getAttribute("value");
- String description = GeneralUIUtils.getWebElementWaitForVisible("description").getAttribute("value");
- String category = GeneralUIUtils.getSelectList(null, "selectGeneralCategory").getFirstSelectedOption()
- .getText();
- String vendorName = GeneralUIUtils.getWebElementWaitForVisible("vendorName").getAttribute("value");
- String vendorRelease = GeneralUIUtils.getWebElementWaitForVisible("vendorRelease").getAttribute("value");
- List<WebElement> tags = GeneralUIUtils.waitForElementsListVisibility("i-sdc-tag-text");
- String type = GeneralUIUtils.waitForElementsListVisibility("type").get(1).getText();
- int index = type.lastIndexOf(":");
- System.out.println(type.substring(0, index));
- String ContactId = GeneralUIUtils.getWebElementWaitForVisible("contactId").getAttribute("value");
- System.out.println(resource.getVersion());
- assertTrue(resource.getVersion().equals(version));
- assertTrue(resource.getName().equals(name));
- assertTrue(resource.getDescription().equals(description));
- System.out.println(resource.getVendorName());
- System.out.println(resource.getVendorRelease());
- assertTrue(resource.getCategories().get(0).getSubcategories().get(0).getName().equals(category));
- assertTrue(resource.getVendorName().equals(vendorName));
- assertTrue(resource.getVendorRelease().equals(vendorRelease));
- assertTrue(resource.getCreatorUserId().equals(ContactId));
- assertEquals(type.substring(0, index), resource.getResourceType());
-
- for (int i = 0; i < tags.size(); i++) {
- assertEquals(resource.getTags().get(i), tags.get(i).getText());
- }
- }
-
- public static void getGeneralInfo(ResourceReqDetails resource, User user) {
- List<WebElement> tags = GeneralUIUtils.waitForElementsListVisibility("tag");
-
- for (WebElement tag : tags) {
- System.out.println(resource.getTags().get(0));
- }
- }
-
- public static void getGeneralInfoForTags(ResourceReqDetails resource, User user) {
-
- clickMore();
- String componentType = waitFunctionForaGetElements("componentType", 3).getText();
- String version = waitFunctionForaGetElements("version", 3).getText();
- String category = waitFunctionForaGetElements("category", 3).getText();// get
- // right
- // panel
- // Category.
- String resourceType = waitFunctionForaGetElements("resourceType", 3).getText();// get
- // right
- // panel
- // SubCategory.
- String date = GeneralUIUtils.getEelementByClassName("creationDate").getText();
- String aouthor = waitfunctionforallelements("author'").getText();
- String vendorName = waitFunctionForaGetElements("vendorName", 3).getText();
- String vendorRelease = waitFunctionForaGetElements("vendorRelease", 3).getText();
- String contactId = waitFunctionForaGetElements("contactId", 3).getText();
- String description = waitFunctionForaGetElements("description", 3).getText();
- List<WebElement> tags = GeneralUIUtils.waitForElementsListVisibility("tag");
- assertTrue(componentType.equals("RESOURCE"));
- assertTrue(version.equals(resource.getVersion()));
- assertTrue(category.equals(resource.getCategories().get(0).getName()));
- assertEquals(resourceType, resource.getResourceType());
- // assertEquals(Date,resource.getCreationDate());
- // assertEquals(Aouthor,resource.getCreatorFullName());
- assertTrue(vendorName.equals(resource.getVendorName()));
- assertTrue(vendorRelease.equals(resource.getVendorRelease()));
- assertTrue(contactId.equals(resource.getContactId()));
- assertTrue(description.equals(resource.getDescription() + "\nLess"));
- assertTrue(tags.equals("Tag-150"));
- }
-
- public static WebElement searchVFNameInWorkspace(ResourceReqDetails resource, User user) throws Exception {
-
- List<WebElement> findElements = GeneralUIUtils.getDriver()
- .findElements(By.xpath("//div[@data-tests-id='" + resource.getUniqueId() + "']"));
- assertNotNull("did not find any elements", findElements);
- for (WebElement webElement : findElements) {
- if (webElement.getText().contains(resource.getUniqueId())) {
- System.out.println("I find it");
- return webElement;
- }
- }
- return null;
- }
-
- public static Boolean searchCheckOutWorkspace(ResourceReqDetails resource, User user,
- CheckBoxStatusEnum checkBoxStatusEnum) throws Exception {
-
- List<WebElement> findElements = GeneralUIUtils.getDriver()
- .findElements(By.xpath("//div[@data-tests-id='component.lifecycleState']"));
- assertNotNull("did not find any elements", findElements);
- for (WebElement webElement : findElements) {
- if (!webElement.getAttribute("class").contains(checkBoxStatusEnum.name())) {
- return false;
- }
- }
- return true;
- }
-
- // coded by tedy.
- public static void validateWithRightPalett(ResourceReqDetails resource, User user) {
- // String
- // Type=Waitfunctionforallelements("sharingService.selectedEntity.getTypeForView()",3).getText();
- String ResourceType = waitfunctionforallelements("selectedComponent.resourceType").getText();
- System.out.println(ResourceType);
- String Version = waitfunctionforallelements("selectedComponent.version").getText();
- String Category = waitfunctionforallelements("selectedComponent.categories[0].name").getText();// get
- // right
- // panel
- // Category.
- String CanvasSubCategory = waitfunctionforallelements("selectedComponent.categories[0].subcategories[0].name")
- .getText();// get right panel SubCategory.
- // String Date=Waitfunctionforelements("selectedComponent.creationDate |
- // date: 'MM/dd/yyyy'").getText();
- // String
- // Aouthor=waitfunctionforallelements("selectedComponent.creatorFullName'").getText();
- String VendorName = waitfunctionforallelements("selectedComponent.vendorName").getText();
- String VendorRelease = waitfunctionforallelements("selectedComponent.vendorRelease").getText();
- String contactId = waitfunctionforallelements("selectedComponent.contactId").getText();
- String Description = waitfunctionforallelements("selectedComponent.description").getText();
- String TagVF = waitfunctionforallelements("tag").getText();
- AssertJUnit.assertEquals(ResourceType, resource.getResourceType());
- AssertJUnit.assertEquals(Version, resource.getVersion());
- AssertJUnit.assertEquals(Category, resource.getCategories().get(0).getName());
- AssertJUnit.assertEquals(CanvasSubCategory,
- resource.getCategories().get(0).getSubcategories().get(0).getName());
- // assertEquals(Date,resource.getCreationDate());
- // assertEquals(Aouthor,resource.getCreatorFullName());
- AssertJUnit.assertEquals(VendorName, resource.getVendorName());
- AssertJUnit.assertEquals(VendorRelease, resource.getVendorRelease());
- AssertJUnit.assertEquals(contactId, resource.getContactId());
- AssertJUnit.assertEquals(Description, resource.getDescription() + "\nLess");
- AssertJUnit.assertEquals(TagVF, "qa123");
- }
-
- public static void clickMore() {
- WebElement clickButtonSubmit = GeneralUIUtils.getDriver()
- .findElement(By.className("ellipsis-directive-more-less"));
- clickButtonSubmit.click();
- }
-
- public static RestResponse createResourceInUI(ResourceReqDetails resource, User user)
- throws Exception, AWTException {
- System.out.println("creating resource...");
- fillNewResourceValues(resource, user);
- RestResponse getCreatedResource = RestCDUtils.getResource(resource, user);
- AssertJUnit.assertEquals("Did not succeed to get any resource", HttpStatus.SC_OK,
- getCreatedResource.getErrorCode().intValue());
-
- return getCreatedResource;
- }
-
- public static RestResponse createResource(ResourceReqDetails resource, User user) throws Exception, AWTException {
-
- ResourceUIUtils.moveToHTMLElementByClassName("w-sdc-dashboard-card-new");
- ResourceUIUtils.clickOnHTMLElementByDataTestId(DataTestIdEnum.Dashboard.BUTTON_ADD_VF.getValue());
- GeneralUIUtils.waitForLoader();
- // GeneralUIUtils.sleep(1000);
- fillResourceGeneralInformationPage(resource, user);
- GeneralUIUtils.clickCreateButton();
- return null;
-
- }
-
- public static RestResponse updateResourceInformationPage(ResourceReqDetails resource, User user)
- throws Exception, AWTException {
-
- fillResourceGeneralInformationPage(resource, user);
- GeneralUIUtils.clickCreateButton();
- return null;
-
- }
-
- public static RestResponse checkInResourceInUI(ResourceReqDetails resource, User user) throws Exception {
-
- WebElement ASDCLink = GeneralUIUtils.getDriver().findElement(By.className("w-sdc-header-logo-link"));
- ASDCLink.click();
- Thread.sleep(2000);
-
- List<WebElement> listFormInput = GeneralUIUtils.getDriver()
- .findElements(By.className("i-sdc-left-sidebar-nav-item"));
- WebElement addPropertyElement = listFormInput.get(0);
- addPropertyElement.click();
- Thread.sleep(2000);
-
- WebElement searchResource = GeneralUIUtils.getDriver()
- .findElement(By.className("w-sdc-header-catalog-search-input"));
- searchResource.sendKeys("newresource4test");
-
- Thread.sleep(1000);
-
- WebElement buttonClickMenu = GeneralUIUtils.getDriver()
- .findElement(By.className("w-sdc-dashboard-card-menu-button"));
- buttonClickMenu.click();
-
- WebElement clickMenu = GeneralUIUtils.getDriver().findElement(By.className("w-sdc-dashboard-card-menu"));
- clickMenu.click();
-
- List<WebElement> clickCheckIn = GeneralUIUtils.getDriver()
- .findElements(By.className("i-sdc-dashboard-card-menu-item"));
- WebElement clickCheckInMenu = clickCheckIn.get(1);
- clickCheckInMenu.click();
-
- WebElement descriptionForSubmit = GeneralUIUtils.getDriver()
- .findElement(By.className("w-sdc-modal-body-comment"));
- descriptionForSubmit.sendKeys("checkin resource");
- Thread.sleep(2000);
- WebElement clickButtonSubmitTwo = GeneralUIUtils.getDriver().findElement(By.className("w-sdc-btn-blue"));
- clickButtonSubmitTwo.click();
- Thread.sleep(2000);
-
- WebElement buttonClickMenu1 = GeneralUIUtils.getDriver()
- .findElement(By.className("w-sdc-dashboard-card-menu-button"));
- buttonClickMenu1.click();
-
- WebElement clickMenu1 = GeneralUIUtils.getDriver().findElement(By.className("w-sdc-dashboard-card-menu"));
- clickMenu1.click();
-
- List<WebElement> clickCheckOut = GeneralUIUtils.getDriver()
- .findElements(By.className("i-sdc-dashboard-card-menu-item"));
- WebElement clickCheckOutMenu = clickCheckOut.get(0);
- clickCheckOutMenu.click();
-
- Thread.sleep(3000);
- RestResponse getResource = RestCDUtils.getResource(resource, user);
- AssertJUnit.assertEquals("Did not succeed to get resource after create", 200,
- getResource.getErrorCode().intValue());
- return getResource;
-
- }
-
- public static String lifeCycleStateUI() throws InterruptedException {
- return GeneralUIUtils.getWebElementWaitForVisible("formlifecyclestate").getText();
- }
-
- public static List<String> catalogFilterResourceCategoriesChecBox(ResourceCategoriesNameEnum enumName)
- throws Exception {
- List<String> categories = Arrays.asList();
- switch (enumName) {
- case APPLICATIONL4:
- GeneralUIUtils.getWebElementWaitForVisible(enumName.getValue()).click();
- categories = Arrays.asList("applicationServer", "defaulticon", "vl", "cp", "call_controll", "borderElement",
- "network", "firewall", "database", "loadBalancer");
- break;
- case APPLICATION_SERVER:
- GeneralUIUtils.getWebElementWaitForVisible(enumName.getValue()).click();
- categories = Arrays.asList("applicationServer", "vl", "cp", "defaulticon");
- break;
- case BORDER_ELEMENT:
- GeneralUIUtils.getWebElementWaitForVisible(enumName.getValue()).click();
- categories = Arrays.asList("borderElement", "vl", "cp", "defaulticon");
- break;
- case CALL_CONTROL:
- GeneralUIUtils.getWebElementWaitForVisible(enumName.getValue()).click();
- categories = Arrays.asList("call_controll", "vl", "cp", "defaulticon");
- break;
- case COMMON_NETWORK_RESOURCES:
- GeneralUIUtils.getEelementByLinkText("Common Network Resources").click();
- categories = Arrays.asList("network", "vl", "cp", "defaulticon");
- break;
- case CONNECTION_POINTS:
- GeneralUIUtils.getWebElementWaitForVisible(enumName.getValue()).click();
- categories = Arrays.asList("cp", "defaulticon");
- break;
- case DATABASE:
- GeneralUIUtils.getWebElementWaitForVisible(enumName.getValue()).click();
- categories = Arrays.asList("database", "vl", "cp", "defaulticon");
- break;
- case DATABASE_GENERIC:
- GeneralUIUtils.getWebElementWaitForVisible(enumName.getValue()).click();
- categories = Arrays.asList("database", "vl", "cp", "defaulticon");
- break;
- case FIREWALL:
- GeneralUIUtils.getWebElementWaitForVisible(enumName.getValue()).click();
- categories = Arrays.asList("firewall", "vl", "cp", "defaulticon");
- break;
- case GATEWAY:
- GeneralUIUtils.getWebElementWaitForVisible(enumName.getValue()).click();
- categories = Arrays.asList("gateway", "vl", "cp", "defaulticon");
- break;
- case INFRASTRUCTURE:
- GeneralUIUtils.getWebElementWaitForVisible(enumName.getValue()).click();
- categories = Arrays.asList("connector", "vl", "cp", "defaulticon");
- break;
- case INFRASTRUCTUREL23:
- GeneralUIUtils.getWebElementWaitForVisible(enumName.getValue()).click();
- categories = Arrays.asList("ucpe", "vl", "cp", "defaulticon");
- break;
- case LAN_CONNECTORS:
- GeneralUIUtils.getWebElementWaitForVisible(enumName.getValue()).click();
- categories = Arrays.asList("network", "port", "connector", "vl", "cp", "defaulticon");
- break;
- case LOAD_BALANCER:
- GeneralUIUtils.getWebElementWaitForVisible(enumName.getValue()).click();
- categories = Arrays.asList("loadBalancer", "vl", "cp", "defaulticon");
- break;
- case MEDIA_SERVERS:
- GeneralUIUtils.getWebElementWaitForVisible(enumName.getValue()).click();
- categories = Arrays.asList("network", "vl", "cp", "defaulticon");
- break;
- case NETWORKL4:
- GeneralUIUtils.getWebElementWaitForVisible(enumName.getValue()).click();
- categories = Arrays.asList("network", "vl", "cp", "defaulticon");
- break;
- case NETWORK_ELEMENTS:
- GeneralUIUtils.getWebElementWaitForVisible(enumName.getValue()).click();
- categories = Arrays.asList("port", "defaulticon", "network", "connector", "vl", "cp");
- break;
- case NETWORK_L23:
- GeneralUIUtils.getWebElementWaitForVisible(enumName.getValue()).click();
- categories = Arrays.asList("network", "vl", "defaulticon", "cp", "router", "port", "connector", "gateway",
- "ucpe");
- break;
- case NETWORK_CONNECTIVITY:
- GeneralUIUtils.getWebElementWaitForVisible(enumName.getValue()).click();
- categories = Arrays.asList("network", "vl", "cp", "defaulticon");
- break;
- case GENERIC:
- GeneralUIUtils.getWebElementWaitForVisible(enumName.getValue()).click();
- categories = Arrays.asList("database", "port", "loadBalancer", "vl", "cp", "objectStorage", "compute",
- "defaulticon", "ucpe", "network", "connector");
- break;
- case ABSTRACT:
- GeneralUIUtils.getWebElementWaitForVisible(enumName.getValue()).click();
- categories = Arrays.asList("objectStorage", "compute", "defaulticon", "cp", "vl");
- break;
- case Router:
- GeneralUIUtils.getWebElementWaitForVisible(enumName.getValue()).click();
- categories = Arrays.asList("router", "vl", "cp", "defaulticon");
- break;
- case VIRTUAL_LINKS:
- GeneralUIUtils.getWebElementWaitForVisible(enumName.getValue()).click();
- categories = Arrays.asList("vl", "defaulticon");
- break;
- case WAN_Connectors:
- GeneralUIUtils.getWebElementWaitForVisible(enumName.getValue()).click();
- categories = Arrays.asList("network", "port", "connector", "vl", "cp", "defaulticon");
- break;
- case WEB_SERVER:
- GeneralUIUtils.getWebElementWaitForVisible(enumName.getValue()).click();
- categories = Arrays.asList("applicationServer", "vl", "cp", "defaulticon");
- break;
- }
- return categories;
- }
-
- public static void deleteVersionInUI() throws Exception {
-
- waitToDeleteVersion().click();
- ResourceUIUtils.clickButtonBlue();
- }
-
- public static void selectTabInRightPallete(String className) throws Exception {
- WebElement tab = GeneralUIUtils.getEelementBycontainsClassName(className);
- tab.click();
- }
-
- public static WebElement waitToDeleteVersion() {
- return Waitfunctionforbuttons("//*[@data-tests-id='deleteVersion']", 10);
- }
-
- public static WebElement rihtPanelAPI() {
- return waitFunctionForaGetElements("tab-api", 10);
- }
-
- /**
- * Click on HTML element.
- *
- * @param dataTestId
- * @throws Exception
- */
- public static void clickOnHTMLElementByDataTestId(String dataTestId) throws Exception {
- WebDriverWait wait = new WebDriverWait(GeneralUIUtils.getDriver(), 20);
- WebElement element = wait
- .until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@data-tests-id='" + dataTestId + "']")));
- element.click();
- // wait.until(ExpectedConditions.elemetto)
- // WebElement serviceButton =
- // GeneralUIUtils.getDriver().findElement(By.xpath("//*[@data-tests-id='"
- // + dataTestId + "']"));
- // serviceButton.
- // serviceButton.click();
- }
-
- /**
- * Move to HTML element by class name. When moving to the HTML element, it
- * will raise hover event.
- *
- * @param className
- */
- public static void moveToHTMLElementByClassName(String className) {
- Actions actions = new Actions(GeneralUIUtils.getDriver());
- final WebElement createButtonsArea = GeneralUIUtils
- .retryMethodOnException(() -> GeneralUIUtils.getDriver().findElement(By.className(className)));
- actions.moveToElement(createButtonsArea).perform();
- }
-
- /**
- * Move to HTML element by element id. When moving to the HTML element, it
- * will raise hover event.
- *
- * @param className
- */
- static void moveToHTMLElementByDataTestId(String dataTestId) {
- // WebElement hoverArea =
- // GeneralUIUtils.getDriver().findElement(By.xpath("//*[@data-tests-id='"
- // + dataTestId + "']"));
- WebElement hoverArea = GeneralUIUtils.waitForElementVisibility(dataTestId);
- // WebDriverWait wait = new WebDriverWait(GeneralUIUtils.getDriver(),
- // 30);
- // wait.until(ExpectedConditions.visibilityOf(hoverArea));
-
- Actions actions = new Actions(GeneralUIUtils.getDriver());
- actions.moveToElement(hoverArea).perform();
- }
-
- // public static ResourceReqDetails createResourceInUI(User user){
- // try{
- // ResourceReqDetails defineResourceDetails =
- // defineResourceDetails(ResourceTypeEnum.VF);
- // ResourceUIUtils.moveToHTMLElementByClassName("w-sdc-dashboard-card-new");
- // ResourceUIUtils.clickOnHTMLElementByDataTestId(DataTestIdEnum.Dashboard.BUTTON_ADD_VF.getValue());
- // GeneralUIUtils.waitForLoader();
- //// GeneralUIUtils.sleep(1000);
- // fillResourceGeneralInformationPage(defineResourceDetails, user);
- // GeneralUIUtils.clickCreateButton();
- // return defineResourceDetails;
- // }
- // catch( Exception e){
- // throw new RuntimeException(e);
- // }
- // }
-
- /**
- * Import VFC
- *
- * @param user
- * @param filePath
- * @param fileName
- * @return
- * @throws Exception
- */
-
- public static void importVfc(ResourceReqDetails resourceMetaData, String filePath, String fileName, User user)
- throws Exception {
- GeneralUIUtils.hoverOnArea(Dashboard.IMPORT_AREA.getValue());
- // Insert file to the browse dialog
- final WebElement browseWebElement = GeneralUIUtils
- .getWebElementByDataTestId(DataTestIdEnum.Dashboard.IMPORT_VFC_FILE.getValue());
- browseWebElement.sendKeys(filePath + fileName);
-
- // Fill the general page fields.
- GeneralUIUtils.waitForLoader();
- fillResourceGeneralInformationPage(resourceMetaData, user);
- GeneralUIUtils.clickCreateButton();
-
- }
-
- // public static ResourceReqDetails importVfcInUI(User user, String
- // filePath, String fileName, ResourceTypeEnum resourceType) {
- // ResourceReqDetails defineResourceDetails =
- // defineResourceDetails(resourceType);
- // ResourceUIUtils.moveToHTMLElementByDataTestId(Dashboard.IMPORT_AREA.getValue());
- //
- // // Insert file to the browse dialog
- // final WebElement browseWebElement =
- // GeneralUIUtils.getWebElementByDataTestId(DataTestIdEnum.Dashboard.IMPORT_VFC_FILE.getValue());
- // browseWebElement.sendKeys(filePath + fileName);
- //
- // // Fill the general page fields.
- // GeneralUIUtils.waitForLoader();
- // fillResourceGeneralInformationPage(defineResourceDetails, user);
- // GeneralUIUtils.clickCreateButton();
- // return defineResourceDetails;
- // }
-
- /**
- * Import VF
- *
- * @param user
- * @param filePath
- * @param fileName
- * @return
- * @throws Exception
- */
- // public static ResourceReqDetails importVfInUI(User user, String filePath,
- // String fileName) throws Exception {
- // ResourceReqDetails defineResourceDetails =
- // defineResourceDetails(ResourceTypeEnum.VF);
- // ResourceUIUtils.moveToHTMLElementByDataTestId(Dashboard.IMPORT_AREA.getValue());
- //
- // // Insert file to the browse dialog
- // final WebElement browseWebElement =
- // GeneralUIUtils.getWebElementByDataTestId(DataTestIdEnum.Dashboard.IMPORT_VF_FILE.getValue());
- // browseWebElement.sendKeys(filePath + fileName);
- //
- // // Fill the general page fields.
- // GeneralUIUtils.waitForLoader();
- // fillResourceGeneralInformationPage(defineResourceDetails, user);
- // GeneralUIUtils.clickCreateButton();
- // return defineResourceDetails;
- // }
-
- // public static ResourceReqDetails defineResourceDetails(ResourceTypeEnum
- // resourceType) {
- // ResourceReqDetails resource = new ResourceReqDetails();
- // resource = ElementFactory.getDefaultResource(NormativeTypesEnum.ROOT,
- // ResourceCategoryEnum.APPLICATION_L4_CALL_CONTROL);
- // resource.setVersion(INITIAL_VERSION);
- // resource.setIcon(ICON_RESOURCE_NAME);
- // resource.setResourceType(resourceType.toString());
- // resource.setName(getRandomComponentName(RESOURCE_NAME_PREFIX));
- //
- // SetupCDTest.setCreatedComponents(Arrays.asList(resource));
- //
- // return resource;
- // }
-
- protected static String getRandomComponentName(String prefix) {
- return prefix + new Random().nextInt(10000);
- }
-
- public static ImmutablePair<String, String> getFirstRIPos(ResourceReqDetails createResourceInUI, User user) {
- String responseAfterDrag = RestCDUtils.getResource(createResourceInUI, user).getResponse();
- JSONObject jsonResource = (JSONObject) JSONValue.parse(responseAfterDrag);
- String xPosPostDrag = (String) ((JSONObject) ((JSONArray) jsonResource.get("componentInstances")).get(0))
- .get("posX");
- String yPosPostDrag = (String) ((JSONObject) ((JSONArray) jsonResource.get("componentInstances")).get(0))
- .get("posY");
- return new ImmutablePair<String, String>(xPosPostDrag, yPosPostDrag);
-
- }
-
- public static WebElement getErrorMessageText(WebDriver driver, String text) throws Exception {
-
- return GeneralUIUtils.getEelementBycontainsClassName(text);
-
- }
-
- public static void fillGeneralInfoValuesAndIcon(ResourceReqDetails resource, User user) throws Exception {
- fillResourceGeneralInformationPage(resource, user);
- GeneralUIUtils.clickCreateButton();
-
- selectRandomResourceIcon();
- }
-
- // coded by teddy.
- public static void getVFCGeneralInfoAndValidate(ResourceReqDetails resource, User user)
- throws InterruptedException {
- Thread.sleep(2000);
- WebDriver driver = GeneralUIUtils.getDriver();
- String version = GeneralUIUtils.getSelectList(null, "versionHeader").getFirstSelectedOption().getText();
- String name = GeneralUIUtils.getWebElement(driver, "name").getAttribute("value");
- String description = GeneralUIUtils.getWebElement(driver, "description").getAttribute("value");
- String category = GeneralUIUtils.getSelectList(null, "selectGeneralCategory").getFirstSelectedOption()
- .getText();
- String vendorName = GeneralUIUtils.getWebElement(driver, "vendorName").getAttribute("value");
- String vendorRelease = GeneralUIUtils.getWebElement(driver, "vendorRelease").getAttribute("value");
- List<WebElement> tags = GeneralUIUtils.waitForElementsListVisibility("i-sdc-tag-text");
- String type = GeneralUIUtils.waitForElementsListVisibility("type").get(1).getText();
- int index = type.lastIndexOf(":");
- System.out.println(type.substring(0, index));
- String contactId = GeneralUIUtils.getWebElement(driver, "contactId").getAttribute("value");
- System.out.println(resource.getVersion());
- assertTrue(resource.getVersion().equals(version.substring(1)));
- assertTrue(resource.getName().equals(name));
- assertTrue(resource.getDescription().equals(description));
- System.out.println(resource.getVendorName());
- System.out.println(resource.getVendorRelease());
- assertTrue(resource.getCategories().get(0).getSubcategories().get(0).getName().equals(category));
- assertTrue(resource.getVendorName().equals(vendorName));
- assertTrue(resource.getVendorRelease().equals(vendorRelease));
- assertTrue(resource.getCreatorUserId().equals(contactId));
- assertEquals(type.substring(0, index), resource.getResourceType());
-
- for (int i = 0; i < tags.size(); i++) {
- assertEquals(resource.getTags().get(i), tags.get(i).getText());
- }
- }
-
- public static RestResponse createResourceNG(ResourceReqDetails resource, User user) throws Exception, AWTException {
-
- ResourceUIUtils.moveToHTMLElementByClassName("w-sdc-dashboard-card-new");
- ResourceUIUtils.clickOnHTMLElementByDataTestId(DataTestIdEnum.Dashboard.BUTTON_ADD_VF.getValue());
- fillResourceGeneralInformationPage(resource, user);
- GeneralUIUtils.clickOnHTMLElementByDataTestId(DataTestIdEnum.LifeCyleChangeButtons.CREATE.getValue());
- return null;
-
- }
-}
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
deleted file mode 100644
index 10535e0157..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/RestCDUtils.java
+++ /dev/null
@@ -1,182 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.utilities;
-
-import static org.testng.AssertJUnit.assertTrue;
-
-import java.io.IOException;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-
-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.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 getResource(ResourceReqDetails resource, User user) {
- try {
- System.out.println("trying to get resource");
- GeneralUIUtils.sleep(1000);
- RestResponse getResourceResponse = null;
- String reourceUniqueId = resource.getUniqueId();
- if (reourceUniqueId != null) {
- getResourceResponse = ResourceRestUtils.getResource(reourceUniqueId);
- if (getResourceResponse.getErrorCode().intValue() == 200) {
- System.out.println("succeeded to get resource");
- }
- return getResourceResponse;
- }
- JSONObject getResourceJSONObject = null;
- getResourceResponse = ResourceRestUtils.getResourceByNameAndVersion(user.getUserId(), resource.getName(),
- resource.getVersion());
- if (getResourceResponse.getErrorCode().intValue() == 200) {
- JSONArray jArray = new JSONArray(getResourceResponse.getResponse());
- for (int i = 0; i < jArray.length(); i++) {
- getResourceJSONObject = jArray.getJSONObject(i);
- String resourceType = ResponseParser.getValueFromJsonResponse(getResourceJSONObject.toString(),
- "resourceType");
- if (resourceType.equals(resource.getResourceType())) {
- getResourceResponse.setResponse(getResourceJSONObject.toString());
- setResourceUniqueIdAndUUID(resource, getResourceResponse);
- 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) {
- try {
- Thread.sleep(3500);
- RestResponse getServiceResponse = ServiceRestUtils.getServiceByNameAndVersion(user, service.getName(),
- service.getVersion());
- if (getServiceResponse.getErrorCode().intValue() == 200) {
- setResourceUniqueIdAndUUID(service, getServiceResponse);
- }
- return getServiceResponse;
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
-
- }
-
- public static RestResponse getProduct(ProductReqDetails product, User user) {
- try {
- Thread.sleep(3500);
- RestResponse getProductResponse = ProductRestUtils.getProductByNameAndVersion(product.getName(),
- product.getVersion(), user.getUserId());
- if (getProductResponse.getErrorCode().intValue() == 200) {
- setResourceUniqueIdAndUUID(product, getProductResponse);
- }
- return getProductResponse;
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
-
- public static Map<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) {
- try {
- deleteAllComponentVersion(false, componentDetails, getObjectResponse, user);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- public static void deleteAllResourceVersionsBeforeTest(ComponentReqDetails componentDetails,
- RestResponse getObjectResponse, User user) throws Exception {
- deleteAllComponentVersion(true, componentDetails, getObjectResponse, user);
- }
-
- public static void deleteAllComponentVersion(boolean isBeforeTest, ComponentReqDetails componentDetails,
- RestResponse getObjectResponse, User user) throws Exception {
- if (getObjectResponse.getErrorCode().intValue() == 404)
- return;
- Map<String, String> componentVersionsMap = getAllElementVersionsFromResponse(getObjectResponse);
- System.out.println("deleting...");
- deleteElementVersions(componentVersionsMap, isBeforeTest, componentDetails, user);
- componentDetails.setUniqueId(null);
- }
-
-}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/ServiceUIUtils.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/ServiceUIUtils.java
deleted file mode 100644
index 5c2608b51e..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/ServiceUIUtils.java
+++ /dev/null
@@ -1,241 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.utilities;
-
-import static org.testng.AssertJUnit.assertEquals;
-import static org.testng.AssertJUnit.assertTrue;
-
-import java.awt.AWTException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.junit.rules.TestName;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum;
-import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.StepsEnum;
-import org.openecomp.sdc.ci.tests.datatypes.ServiceCategoriesNameEnum;
-import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
-import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest;
-import org.openecomp.sdc.ci.tests.pages.ServiceGeneralPage;
-import org.openqa.selenium.By;
-import org.openqa.selenium.Keys;
-import org.openqa.selenium.WebDriver;
-import org.openqa.selenium.WebElement;
-import org.openqa.selenium.interactions.Actions;
-import org.openqa.selenium.support.ui.ExpectedConditions;
-import org.openqa.selenium.support.ui.Select;
-import org.openqa.selenium.support.ui.WebDriverWait;
-
-import com.relevantcodes.extentreports.LogStatus;
-
-public class ServiceUIUtils {
-
- protected static WebDriver driver;
-
- public ServiceUIUtils(TestName name, String className) {
- super();
- }
-
- public static String defineServiceName(String Name) {
- WebElement serviceName = GeneralUIUtils.getWebElementWaitForVisible("name");
- serviceName.clear();
- serviceName.sendKeys(Name);
- return Name;
- }
-
- public void moveResourceInstanceToCanvasUI() throws Exception {
- List<WebElement> moveResource = driver.findElements(By.className("sprite-resource-icons"));
- WebElement moveResourceToCanvasResourceOne = moveResource.get(0);
- // WebElement moveResource =
- // driver.findElement(By.className("sprite-resource-icons"));
- Actions action = new Actions(driver);
- action.moveToElement(moveResourceToCanvasResourceOne);
- action.clickAndHold(moveResourceToCanvasResourceOne);
- action.moveByOffset(635, 375);
- action.release();
- action.perform();
- WebElement moveResourceToCanvasResourceTwo = moveResource.get(1);
- action.moveToElement(moveResourceToCanvasResourceTwo);
- action.clickAndHold(moveResourceToCanvasResourceTwo);
- action.moveByOffset(535, 375);
- action.release();
- action.perform();
- WebElement moveResourceToCanvasResourceTree = moveResource.get(2);
- action.moveToElement(moveResourceToCanvasResourceTree);
- action.clickAndHold(moveResourceToCanvasResourceTree);
- action.moveByOffset(435, 375);
- action.release();
- action.perform();
- Thread.sleep(2000);
- }
-
- public static String catalogFilterServiceCategoriesChecBox(ServiceCategoriesNameEnum enumName) throws Exception {
- String Type = null;
- GeneralUIUtils.getWebElementWaitForVisible(enumName.getValue()).click();
- return Type;
- }
-
- public static List<String> catalogServiceTypeChecBox(ServiceCategoriesNameEnum enumtype) throws Exception {
- List<String> categories = null;
- switch (enumtype) {
- case NETWORK_L13:
- GeneralUIUtils.getWebElementWaitForVisible(enumtype.getValue()).click();
- categories = Arrays.asList("network_l_1-3");
- break;
- case NETWORKL4:
- GeneralUIUtils.getWebElementWaitForVisible(enumtype.getValue()).click();
- categories = Arrays.asList("network_l_4 ");
- break;
- case MOBILITY:
- GeneralUIUtils.getWebElementWaitForVisible(enumtype.getValue()).click();
- categories = Arrays.asList("mobility");
- break;
- case VOIPCALL_CONTROL:
- GeneralUIUtils.getWebElementWaitForVisible(enumtype.getValue()).click();
- categories = Arrays.asList("call_controll ");
- break;
- }
- return categories;
- }
-
- public static WebElement waitToNextButtonEnabled() {
- return GeneralUIUtils.getWebButton("Next");
- }
-
- public static WebElement waitToFinishButtonEnabled() {
- return GeneralUIUtils.getWebButton("Finish");
- }
-
- public static WebElement deleteServiceInUI() {
-
- return GeneralUIUtils.getWebButton("deleteVersion");
- }
-
- // get the service view data for validate.
- // created by tedy.
- public static void getServiceGeneralInfo(ServiceReqDetails service, User user) throws InterruptedException {
- Thread.sleep(2000);
- String version = GeneralUIUtils.getSelectList(null, "versionHeader").getFirstSelectedOption().getText()
- .substring(1);
- String name = GeneralUIUtils.getWebElementWaitForVisible("name").getAttribute("value");
- String description = GeneralUIUtils.getWebElementWaitForVisible("description").getAttribute("value");
- String category = GeneralUIUtils.getSelectList(null, "selectGeneralCategory").getFirstSelectedOption()
- .getText();
- List<WebElement> tags = GeneralUIUtils.waitForElementsListVisibility("i-sdc-tag-text");
- String type = GeneralUIUtils.waitForElementsListVisibility("type").get(1).getText();
- int index = type.lastIndexOf(":");
- System.out.println(type.substring(0, index));
- String contactId = GeneralUIUtils.getWebElementWaitForVisible("contactId").getAttribute("value");
- String projectCode = GeneralUIUtils.getWebElementWaitForVisible("projectCode").getAttribute("value");
- System.out.println(service.getVersion());
- assertTrue(service.getVersion().equals(version));
- assertTrue(service.getName().equals(name));
- assertTrue(service.getDescription().equals(description));
- assertTrue(service.getCategories().get(0).getName().equals(category));
- System.out.println(service.getContactId());
- assertTrue(service.getContactId().equals(contactId));
- assertTrue(service.getProjectCode().equals(projectCode));
- for (int i = 0; i < tags.size(); i++) {
- assertEquals(service.getTags().get(i), tags.get(i).getText());
- }
-
- }
-
- public static void defineTagsList(ServiceReqDetails service, String[] serviceTags) {
- List<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");
- }
-
- public static void defineServiceProjectCode(String projectCode) {
- WebElement projectCodeTextbox = GeneralUIUtils.getWebElementWaitForVisible("projectCode");
- projectCodeTextbox.clear();
- projectCodeTextbox.sendKeys(projectCode);
- }
-
- public static void selectRandomResourceIcon() throws Exception {
- GeneralUIUtils.moveToStep(StepsEnum.ICON);
- WebDriverWait wait = new WebDriverWait(driver, 6);
- wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[contains(@data-tests-id, 'iconBox')]")));
- List<WebElement> iconElement = driver.findElements(By.xpath("//*[contains(@data-tests-id, 'iconBox')]"));
- iconElement.get(0).click();
- }
-
- public static String defineDescription(String description) {
- WebElement descriptionTextbox = GeneralUIUtils.getWebElementWaitForVisible("description");
- descriptionTextbox.clear();
- descriptionTextbox.sendKeys(description);
- return description;
- }
-
- public static void defineContactId(String userId) {
- WebElement contactId = GeneralUIUtils.getWebElementWaitForVisible("contactId");
- contactId.clear();
- contactId.sendKeys(userId);
- }
-
- public static WebElement clickAddArtifact() {
-
- return GeneralUIUtils.getWebButton("addArtifactButton");
- }
-
- public static WebElement getArtifactName() {
- return GeneralUIUtils.getWebButton("artifactName");
- }
-
- public static WebElement getArtifactDetails() {
- return GeneralUIUtils.getWebButton("artifactDisplayName");
- }
-
- public static void fillServiceGeneralPage(ServiceReqDetails service, User user) throws Exception {
- ServiceGeneralPage.defineName(service.getName());
- ServiceGeneralPage.defineDescription(service.getDescription());
- ServiceGeneralPage.defineCategory(service.getCategories().get(0).getName());
- ServiceGeneralPage.defineProjectCode(service.getProjectCode());
- ServiceGeneralPage.defineTagsList(service, new String[] { "This-is-tag", "another-tag" });
-
- }
-
- public static void createService(ServiceReqDetails service, User user) throws Exception, AWTException {
-
- ResourceUIUtils.moveToHTMLElementByClassName("w-sdc-dashboard-card-new");
- ResourceUIUtils.clickOnHTMLElementByDataTestId(DataTestIdEnum.Dashboard.BUTTON_ADD_SERVICE.getValue());
- GeneralUIUtils.waitForLoader();
- fillServiceGeneralPage(service, user);
- GeneralUIUtils.clickCreateButton();
- SetupCDTest.getExtendTest().log(LogStatus.INFO, String.format("Service %s created", service.getName()));
- }
-
-}
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
deleted file mode 100644
index cbad80d344..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/ServiceVerificator.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.verificator;
-
-import static org.testng.AssertJUnit.assertTrue;
-
-import org.json.simple.JSONArray;
-import org.json.simple.JSONObject;
-import org.json.simple.JSONValue;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.ci.tests.datatypes.ComponentReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
-import org.openecomp.sdc.ci.tests.utilities.RestCDUtils;
-
-public class ServiceVerificator {
-
- private ServiceVerificator() {
- }
-
- public static void verifyNumOfComponentInstances(ComponentReqDetails component, String version, int numOfVFC,
- User user) {
- String responseAfterDrag = null;
- component.setVersion(version);
- if (component instanceof ServiceReqDetails) {
- responseAfterDrag = RestCDUtils.getService((ServiceReqDetails) component, user).getResponse();
- } else if (component instanceof ResourceReqDetails) {
- responseAfterDrag = RestCDUtils.getResource((ResourceReqDetails) component, user).getResponse();
- }
- JSONObject jsonResource = (JSONObject) JSONValue.parse(responseAfterDrag);
- int size = ((JSONArray) jsonResource.get("componentInstances")).size();
- assertTrue(size == numOfVFC);
- }
-
- public static void verifyLinkCreated(ServiceReqDetails createServiceInUI, User user, int expectedRelationsSize) {
- String responseAfterDrag = RestCDUtils.getService(createServiceInUI, user).getResponse();
- JSONObject jsonResource = (JSONObject) JSONValue.parse(responseAfterDrag);
- assertTrue(((JSONArray) jsonResource.get("componentInstancesRelations")).size() == expectedRelationsSize);
-
- }
-
-}
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
deleted file mode 100644
index 1ffde75414..0000000000
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/VfVerificator.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.verificator;
-
-import static org.testng.AssertJUnit.assertTrue;
-
-import java.util.Iterator;
-
-import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.json.simple.JSONArray;
-import org.json.simple.JSONObject;
-import org.json.simple.JSONValue;
-import org.openecomp.sdc.be.model.LifecycleStateEnum;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
-import org.openecomp.sdc.ci.tests.pages.ResourceGeneralPage;
-import org.openecomp.sdc.ci.tests.utilities.ResourceUIUtils;
-import org.openecomp.sdc.ci.tests.utilities.RestCDUtils;
-import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
-
-public final class VfVerificator {
- private VfVerificator() {
- }
-
- public static void verifyNumOfComponentInstances(ResourceReqDetails createResourceInUI, int numOfVFC, User user) {
- String responseAfterDrag = RestCDUtils.getResource(createResourceInUI, user).getResponse();
- JSONObject jsonResource = (JSONObject) JSONValue.parse(responseAfterDrag);
- int size = ((JSONArray) jsonResource.get("componentInstances")).size();
- assertTrue(size == numOfVFC);
- }
-
- public static void verifyRILocationChanged(ResourceReqDetails createResourceInUI,
- ImmutablePair<String, String> prevRIPos, User user) {
-
- ImmutablePair<String, String> currRIPos = ResourceUIUtils.getFirstRIPos(createResourceInUI, user);
- assertTrue(!prevRIPos.left.equals(currRIPos.left) || !prevRIPos.right.equals(currRIPos.right));
- }
-
- public static void verifyLinkCreated(ResourceReqDetails createResourceInUI, User user, int expectedRelationsSize) {
- String responseAfterDrag = RestCDUtils.getResource(createResourceInUI, user).getResponse();
- JSONObject jsonResource = (JSONObject) JSONValue.parse(responseAfterDrag);
- assertTrue(((JSONArray) jsonResource.get("componentInstancesRelations")).size() == expectedRelationsSize);
-
- }
-
- public static void verifyVFUpdatedInUI(ResourceReqDetails vf) {
- assertTrue(vf.getName().equals(ResourceGeneralPage.getNameText()));
- assertTrue(vf.getDescription().equals(ResourceGeneralPage.getDescriptionText()));
- assertTrue(vf.getVendorName().equals(ResourceGeneralPage.getVendorNameText()));
- assertTrue(vf.getVendorRelease().equals(ResourceGeneralPage.getVendorReleaseText()));
- assertTrue(vf.getContactId().equals(ResourceGeneralPage.getUserIdContactText()));
- }
-
- public static void verifyVFUpdated(ResourceReqDetails vf, User user) {
- String response = RestCDUtils.getResource(vf, user).getResponse();
- Resource resource = ResponseParser.convertResourceResponseToJavaObject(response);
- assertTrue(vf.getName().equals(resource.getName()));
- assertTrue(vf.getDescription().equals(resource.getDescription()));
- assertTrue(vf.getCategories().equals(resource.getCategories()));
- assertTrue(vf.getVendorName().equals(resource.getVendorName()));
- assertTrue(vf.getVendorRelease().equals(resource.getVendorRelease()));
- assertTrue(vf.getTags().equals(resource.getTags()));
- assertTrue(vf.getContactId().equals(resource.getContactId()));
- }
-
- public static void verifyVFLifecycle(ResourceReqDetails vf, User user, LifecycleStateEnum expectedLifecycleState) {
- String responseAfterDrag = RestCDUtils.getResource(vf, user).getResponse();
- JSONObject jsonResource = (JSONObject) JSONValue.parse(responseAfterDrag);
- String actualLifecycleState = jsonResource.get("lifecycleState").toString();
- assertTrue("actual: " + actualLifecycleState + "--expected: " + expectedLifecycleState,
- expectedLifecycleState.name().equals(actualLifecycleState));
- }
-}
diff --git a/ui-ci/src/main/resources/Downloads/CP_WAN.yml b/ui-ci/src/main/resources/Downloads/CP_WAN.yml
deleted file mode 100644
index eeabbb8490..0000000000
--- a/ui-ci/src/main/resources/Downloads/CP_WAN.yml
+++ /dev/null
@@ -1,23 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-
-node_types:
- org.openecomp.resource.cp.WANTedy: derived_from: org.openecomp.resource.cp.CPTedy
- properties:
- type:
- type: string
- required: false
- requirements:
- - virtualLink_in:
- capability: tosca.capabilities.network.Linkable relationship: tosca.relationships.network.LinksTo
- - virtualLink_out:
- capability: tosca.capabilities.network.Linkable relationship: tosca.relationships.network.LinksTo
- - virtualLink_in1:
- capability: tosca.capabilities.network.Linkable relationship: tosca.relationships.network.LinksTo
- - virtualLink_out1:
- capability: tosca.capabilities.network.Linkable relationship: tosca.relationships.network.LinksTo
- - virtualLink_in2:
- capability: tosca.capabilities.network.Linkable relationship: tosca.relationships.network.LinksTo
- - virtualLink_out2:
- capability: tosca.capabilities.network.Linkable relationship: tosca.relationships.network.LinksTo
- - virtualbinding:
- capability: tosca.capabilities.network.Bindable relationship: tosca.relationships.network.BindsTo \ No newline at end of file
diff --git a/ui-ci/src/main/resources/Downloads/Fortigate02_vFW_VFC.yml b/ui-ci/src/main/resources/Downloads/Fortigate02_vFW_VFC.yml
deleted file mode 100644
index a24d004929..0000000000
--- a/ui-ci/src/main/resources/Downloads/Fortigate02_vFW_VFC.yml
+++ /dev/null
@@ -1,63 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-
-node_types:
-
- org.openecomp.resource.vfc.vFW.Fortigate02Tedy:
- derived_from: org.openecomp.resource.vfc.vFWTedy
-
- properties:
- att-part-number:
- type: string
- default: "ATT-FortiGate-VM02"
- vendor-name:
- type: string
- default: “FORTINET”
- vendor-model:
- type: string
- default: "VM02"
- vendor-model-description:
- type: string
- vcpu-default:
- type: integer
- default: 2
- vcpu-min:
- type: integer
- default: 1
- vcpu-max:
- type: integer
- default: 2
- vmemory-default:
- default: 4
- type: integer
- vmemory-units:
- type: string
- default: "GB"
- vmemory-min:
- type: integer
- default: 1
- vmemory-max:
- type: integer
- default: 4
- vdisk-default:
- type: integer
- default: 20
- vdisk-units:
- type: string
- default: "GB"
- vdisk-min:
- type: integer
- default: 2
- vdisk-max:
- type: integer
- default: 20
- vnf-type:
- type: string
- default: “Advanced FW”
- software-version:
- type: string
- default: “5.2.4”
- software-file-name:
- type: string
- vnf-feature:
- type: string
- default: “IPS, AntiVirus, URL Filter, APPID” \ No newline at end of file
diff --git a/ui-ci/src/main/resources/Files/CP.yml b/ui-ci/src/main/resources/Files/CP.yml
deleted file mode 100644
index 48b592265f..0000000000
--- a/ui-ci/src/main/resources/Files/CP.yml
+++ /dev/null
@@ -1,65 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-
-node_types:
- org.openecomp.resource.cp.CP:
- derived_from: tosca.nodes.Root
- properties:
- att-ucpe-part-number:
- type: string
- vendor-name:
- type: string
- required: true
- vendor-model:
- type: string
- required: true
- total-vcpu:
- type: integer
- description: number of vCPUs
- total-memory:
- type: integer
- description: GB
- total-disk:
- type: integer
- description: GB
- base-system-image-file-name:
- type: string
- linux-host-vendor:
- type: string
- linux-host-os-version:
- type: version
- base-system-software:
- type: string
- jdm-vcpu:
- type: integer
- jdm-memory:
- type: integer
- description: GB
- jdm-disk:
- type: integer
- description: GB
- jdm-version:
- type: string
- jcp-vcpu:
- type: integer
- jcp-memory:
- type: integer
- description: GB
- jcp-disk:
- type: integer
- description: GB
- jcp-version:
- type: version
- capabilities:
- vnf_hosting:
- type: tosca.capabilities.Container
- description: Provides hosting capability for VNFs
- WAN_connectivity:
- type: tosca.capabilities.network.Bindable
- valid_source_types: [org.openecomp.cp.Wan]
- description: external WAN1 n/w interface
- occurrences: [1,2]
- LAN_connectivity:
- type: tosca.capabilities.network.Bindable
- valid_source_types: [org.openecomp.cp.Lan]
- description: external LAN n/w interface
- occurrences: [1,8] \ No newline at end of file
diff --git a/ui-ci/src/main/resources/Files/CPWithAttributes.yml b/ui-ci/src/main/resources/Files/CPWithAttributes.yml
deleted file mode 100644
index 847181b5c9..0000000000
--- a/ui-ci/src/main/resources/Files/CPWithAttributes.yml
+++ /dev/null
@@ -1,78 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-
-node_types:
- org.openecomp.resource.cp.CP:
- derived_from: tosca.nodes.Root
- properties:
- att-ucpe-part-number:
- type: string
- vendor-name:
- type: string
- required: true
- vendor-model:
- type: string
- required: true
- total-vcpu:
- type: integer
- description: number of vCPUs
- total-memory:
- type: integer
- description: GB
- total-disk:
- type: integer
- description: GB
- base-system-image-file-name:
- type: string
- linux-host-vendor:
- type: string
- linux-host-os-version:
- type: version
- base-system-software:
- type: string
- jdm-vcpu:
- type: integer
- jdm-memory:
- type: integer
- description: GB
- jdm-disk:
- type: integer
- description: GB
- jdm-version:
- type: string
- jcp-vcpu:
- type: integer
- jcp-memory:
- type: integer
- description: GB
- jcp-disk:
- type: integer
- description: GB
- jcp-version:
- type: version
- 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:
- vnf_hosting:
- type: tosca.capabilities.Container
- description: Provides hosting capability for VNFs
- WAN_connectivity:
- type: tosca.capabilities.network.Bindable
- valid_source_types: [org.openecomp.cp.Wan]
- description: external WAN1 n/w interface
- occurrences: [1,2]
- LAN_connectivity:
- type: tosca.capabilities.network.Bindable
- valid_source_types: [org.openecomp.cp.Lan]
- description: external LAN n/w interface
- occurrences: [1,8] \ No newline at end of file
diff --git a/ui-ci/src/main/resources/Files/CP_LAN - Copy.yml b/ui-ci/src/main/resources/Files/CP_LAN - Copy.yml
deleted file mode 100644
index 5663168e4a..0000000000
--- a/ui-ci/src/main/resources/Files/CP_LAN - Copy.yml
+++ /dev/null
@@ -1,12 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-
-node_types:
- org.openecomp.resource.vfc.uCPE: derived_from: tosca.nodes.Root
- properties:
- type:
- type: string
- required: false
- requirements:
- - virtualLink:
- capability: tosca.capabilities.network.Linkable
- relationship: tosca.relationships.network.LinksTo
diff --git a/ui-ci/src/main/resources/Files/CP_LAN.yml b/ui-ci/src/main/resources/Files/CP_LAN.yml
deleted file mode 100644
index 3420a3cfcb..0000000000
--- a/ui-ci/src/main/resources/Files/CP_LAN.yml
+++ /dev/null
@@ -1,19 +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_in:
- capability: tosca.capabilities.network.Linkable
- relationship: tosca.relationships.network.LinksTo
- - virtualLink_out:
- capability: tosca.capabilities.network.Linkable
- relationship: tosca.relationships.network.LinksTo
- - virtualbinding:
- capability: tosca.capabilities.network.Bindable
- relationship: tosca.relationships.network.BindsTo \ No newline at end of file
diff --git a/ui-ci/src/main/resources/Files/CP_WAN.yml b/ui-ci/src/main/resources/Files/CP_WAN.yml
deleted file mode 100644
index 9f21b902d9..0000000000
--- a/ui-ci/src/main/resources/Files/CP_WAN.yml
+++ /dev/null
@@ -1,19 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-
-node_types:
- org.openecomp.resource.cp1.WAN:
- derived_from: org.openecomp.resource.cp.CP
- properties:
- type:
- type: string
- required: false
- requirements:
- - virtualLink_in:
- capability: tosca.capabilities.network.Linkable
- relationship: tosca.relationships.network.LinksTo
- - virtualLink_out:
- capability: tosca.capabilities.network.Linkable
- relationship: tosca.relationships.network.LinksTo
- - virtualbinding:
- capability: tosca.capabilities.network.Bindable
- relationship: tosca.relationships.network.BindsTo \ No newline at end of file
diff --git a/ui-ci/src/main/resources/Files/DNSscaling12.8.16.zip b/ui-ci/src/main/resources/Files/DNSscaling12.8.16.zip
deleted file mode 100644
index cadb6138e7..0000000000
--- a/ui-ci/src/main/resources/Files/DNSscaling12.8.16.zip
+++ /dev/null
Binary files differ
diff --git a/ui-ci/src/main/resources/Files/Heat-File 1.yaml b/ui-ci/src/main/resources/Files/Heat-File 1.yaml
deleted file mode 100644
index d332078d35..0000000000
--- a/ui-ci/src/main/resources/Files/Heat-File 1.yaml
+++ /dev/null
@@ -1,791 +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_2:
- type: OS::Neutron::Port
- properties:
- network_id: { get_resource: Clustering_Network }
-
- 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/ui-ci/src/main/resources/Files/Heat-File 2.yaml b/ui-ci/src/main/resources/Files/Heat-File 2.yaml
deleted file mode 100644
index d332078d35..0000000000
--- a/ui-ci/src/main/resources/Files/Heat-File 2.yaml
+++ /dev/null
@@ -1,791 +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_2:
- type: OS::Neutron::Port
- properties:
- network_id: { get_resource: Clustering_Network }
-
- 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/ui-ci/src/main/resources/Files/Heat-File.yaml b/ui-ci/src/main/resources/Files/Heat-File.yaml
deleted file mode 100644
index d332078d35..0000000000
--- a/ui-ci/src/main/resources/Files/Heat-File.yaml
+++ /dev/null
@@ -1,791 +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_2:
- type: OS::Neutron::Port
- properties:
- network_id: { get_resource: Clustering_Network }
-
- 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/ui-ci/src/main/resources/Files/InValid_tosca_File .yml b/ui-ci/src/main/resources/Files/InValid_tosca_File .yml
deleted file mode 100644
index 4eea0a15ac..0000000000
--- a/ui-ci/src/main/resources/Files/InValid_tosca_File .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
diff --git a/ui-ci/src/main/resources/Files/JDM_vf.yml b/ui-ci/src/main/resources/Files/JDM_vf.yml
deleted file mode 100644
index 5a7edd4aaf..0000000000
--- a/ui-ci/src/main/resources/Files/JDM_vf.yml
+++ /dev/null
@@ -1,57 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-
-node_types:
- org.openecomp.resource.vf.JDM:
- derived_from: tosca.nodes.Root
- properties:
- att-part-number:
- type: string
- vendor-name:
- type: string
- vendor-part-number:
- type: string
- vendor-model:
- type: string
- vendor-model-description:
- type: string
- vcpu-default:
- type: integer
- vcpu-min:
- type: integer
- vcpu-max:
- type: integer
- vmemory-default:
- type: integer
- vmemory-units:
- type: string
- default: "GB"
- vmemory-min:
- type: integer
- vmemory-max:
- type: integer
- vdisk-default:
- type: integer
- vdisk-units:
- type: string
- default: "GB"
- vdisk-min:
- type: integer
- vdisk-max:
- type: integer
- vnf-type:
- type: string
- software-version:
- type: string
- software-version-state:
- type: integer
- software-file-name:
- type: string
- vnf-feature:
- type: string
- requirements:
- - host:
- capability: tosca.capabilities.Container
- relationship: tosca.relationships.HostedOn
- capabilities:
- binding:
- type: tosca.capabilities.network.Bindable \ No newline at end of file
diff --git a/ui-ci/src/main/resources/Files/JDM_vfc.yml b/ui-ci/src/main/resources/Files/JDM_vfc.yml
deleted file mode 100644
index b9c9ca0c4a..0000000000
--- a/ui-ci/src/main/resources/Files/JDM_vfc.yml
+++ /dev/null
@@ -1,57 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-
-node_types:
- org.openecomp.resource.vfc.JDM:
- derived_from: tosca.nodes.Root
- properties:
- att-part-number:
- type: string
- vendor-name:
- type: string
- vendor-part-number:
- type: string
- vendor-model:
- type: string
- vendor-model-description:
- type: string
- vcpu-default:
- type: integer
- vcpu-min:
- type: integer
- vcpu-max:
- type: integer
- vmemory-default:
- type: integer
- vmemory-units:
- type: string
- default: "GB"
- vmemory-min:
- type: integer
- vmemory-max:
- type: integer
- vdisk-default:
- type: integer
- vdisk-units:
- type: string
- default: "GB"
- vdisk-min:
- type: integer
- vdisk-max:
- type: integer
- vnf-type:
- type: string
- software-version:
- type: string
- software-version-state:
- type: integer
- software-file-name:
- type: string
- vnf-feature:
- type: string
- requirements:
- - host:
- capability: tosca.capabilities.Container
- relationship: tosca.relationships.HostedOn
- capabilities:
- binding:
- type: tosca.capabilities.network.Bindable \ No newline at end of file
diff --git a/ui-ci/src/main/resources/Files/Sample_CSAR.csar b/ui-ci/src/main/resources/Files/Sample_CSAR.csar
deleted file mode 100644
index 3001fe8222..0000000000
--- a/ui-ci/src/main/resources/Files/Sample_CSAR.csar
+++ /dev/null
Binary files differ
diff --git a/ui-ci/src/main/resources/Files/UCPE_VFC.yml b/ui-ci/src/main/resources/Files/UCPE_VFC.yml
deleted file mode 100644
index ef3966b68f..0000000000
--- a/ui-ci/src/main/resources/Files/UCPE_VFC.yml
+++ /dev/null
@@ -1,65 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-
-node_types:
- org.openecomp.resource.vfc.uCPE:
- derived_from: tosca.nodes.Root
- properties:
- att-ucpe-part-number:
- type: string
- vendor-name:
- type: string
- required: true
- vendor-model:
- type: string
- required: true
- total-vcpu:
- type: integer
- description: number of vCPUs
- total-memory:
- type: integer
- description: GB
- total-disk:
- type: integer
- description: GB
- base-system-image-file-name:
- type: string
- linux-host-vendor:
- type: string
- linux-host-os-version:
- type: version
- base-system-software:
- type: string
- jdm-vcpu:
- type: integer
- jdm-memory:
- type: integer
- description: GB
- jdm-disk:
- type: integer
- description: GB
- jdm-version:
- type: string
- jcp-vcpu:
- type: integer
- jcp-memory:
- type: integer
- description: GB
- jcp-disk:
- type: integer
- description: GB
- jcp-version:
- type: version
- capabilities:
- vnf_hosting:
- type: tosca.capabilities.Container
- description: Provides hosting capability for VNFs
- WAN_connectivity:
- type: tosca.capabilities.network.Bindable
- valid_source_types: [org.openecomp.cp.Wan]
- description: external WAN1 n/w interface
- occurrences: [1,2]
- LAN_connectivity:
- type: tosca.capabilities.network.Bindable
- valid_source_types: [org.openecomp.cp.Lan]
- description: external LAN n/w interface
- occurrences: [1,8] \ No newline at end of file
diff --git a/ui-ci/src/main/resources/Files/VF.yml b/ui-ci/src/main/resources/Files/VF.yml
deleted file mode 100644
index ec089900ad..0000000000
--- a/ui-ci/src/main/resources/Files/VF.yml
+++ /dev/null
@@ -1,17 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-
-node_types:
- org.openecomp.resource.vf.VFF:
- derived_from: tosca.nodes.Root
- properties:
- vendor:
- type: string
- required: false
- vl_name:
- type: string
- required: false
- capabilities:
- virtual_linkable:
- type: tosca.capabilities.network.Linkable
-
- \ No newline at end of file
diff --git a/ui-ci/src/main/resources/Files/VFC.yml b/ui-ci/src/main/resources/Files/VFC.yml
deleted file mode 100644
index 853ed35374..0000000000
--- a/ui-ci/src/main/resources/Files/VFC.yml
+++ /dev/null
@@ -1,77 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-
-node_types:
- org.openecomp.resource.vfc.vRouter:
- derived_from: tosca.nodes.Root
- properties:
- att-part-number:
- type: string
- vendor-name:
- type: string
- vendor-part-number:
- type: string
- vendor-model:
- type: string
- vendor-model-description:
- type: string
- vcpu-default:
- type: integer
- vcpu-min:
- type: integer
- vcpu-max:
- type: integer
- vmemory-default:
- type: integer
- vmemory-units:
- type: string
- default: "GB"
- vmemory-min:
- type: integer
- vmemory-max:
- type: integer
- vdisk-default:
- type: integer
- vdisk-units:
- type: string
- default: "GB"
- vdisk-min:
- type: integer
- vdisk-max:
- type: integer
- vnf-type:
- type: string
- software-version:
- type: string
- software-version-state:
- type: integer
- software-file-name:
- type: string
- vnf-feature:
- type: string
- management-v6-address:
- type: string
- nm-lan-v6-address:
- type: string
- nm-lan-v6-prefix-length:
- type: string
- management-v4-address:
- type: string
- nm-lan-v4-address:
- type: string
- nm-lan-v4-prefix-length:
- type: string
- routing-instance-name:
- type: string
- routing-instances:
- type: map
- entry_schema:
- type: string
- requirements:
- - host:
- capability: tosca.capabilities.Container
- relationship: tosca.relationships.HostedOn
- capabilities:
- binding:
- type: tosca.capabilities.network.Bindable
- occurrences: [1,UNBOUNDED]
- \ No newline at end of file
diff --git a/ui-ci/src/main/resources/Files/Valid xml.xml b/ui-ci/src/main/resources/Files/Valid xml.xml
deleted file mode 100644
index 0d67e48340..0000000000
--- a/ui-ci/src/main/resources/Files/Valid xml.xml
+++ /dev/null
@@ -1,4 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" standalone="no"?>
-<dirs>
-<entry loc="C:\Program Files\Java\jdk1.7.0_79" stamp="1449076618518"/>
-</dirs>
diff --git a/ui-ci/src/main/resources/Files/Valid_tosca_Mycompute.yml b/ui-ci/src/main/resources/Files/Valid_tosca_Mycompute.yml
deleted file mode 100644
index 8fac5e16a8..0000000000
--- a/ui-ci/src/main/resources/Files/Valid_tosca_Mycompute.yml
+++ /dev/null
@@ -1,35 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- org.openecomp.resource.vf.Database:
- 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/ui-ci/src/main/resources/Files/Valid_tosca_ReplaceTest.yml b/ui-ci/src/main/resources/Files/Valid_tosca_ReplaceTest.yml
deleted file mode 100644
index 90e771dab1..0000000000
--- a/ui-ci/src/main/resources/Files/Valid_tosca_ReplaceTest.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/ui-ci/src/main/resources/Files/asc_heat 0 2.yaml b/ui-ci/src/main/resources/Files/asc_heat 0 2.yaml
deleted file mode 100644
index 6835485ca1..0000000000
--- a/ui-ci/src/main/resources/Files/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/ui-ci/src/main/resources/Files/hot-nimbus-oam-volumes_v0.3.env b/ui-ci/src/main/resources/Files/hot-nimbus-oam-volumes_v0.3.env
deleted file mode 100644
index b494d8c270..0000000000
--- a/ui-ci/src/main/resources/Files/hot-nimbus-oam-volumes_v0.3.env
+++ /dev/null
@@ -1,6 +0,0 @@
-parameters:
- pcrf_oam_vol_size: 500
- pcrf_oam_volume_silver-1: Silver
- pcrf_oam_volume_silver-2: Silver
- pcrf_oam_vol_name_1: sde1-pcrfx01-oam001-vol-1
- pcrf_oam_vol_name_2: sde1-pcrfx01-oam001-vol-2 \ No newline at end of file
diff --git a/ui-ci/src/main/resources/Files/hot-nimbus-oam_v0.6.env b/ui-ci/src/main/resources/Files/hot-nimbus-oam_v0.6.env
deleted file mode 100644
index cf7cf710ce..0000000000
--- a/ui-ci/src/main/resources/Files/hot-nimbus-oam_v0.6.env
+++ /dev/null
@@ -1,18 +0,0 @@
-parameters:
- pcrf_oam_server_names: ZRDM1PCRF01OAM001,ZRDM1PCRF01OAM002
- pcrf_oam_image_name: PCRF_8.995-ATTM1.0.3.qcow2
- pcrf_oam_flavor_name: lc.4xlarge4
- availabilityzone_name: nova
- pcrf_cps_net_name: int_pcrf_net_0
- pcrf_cps_net_ips: 172.26.16.111,172.26.16.112
- pcrf_arbiter_vip: 172.26.16.115
- pcrf_cps_net_mask: 255.255.255.0
- pcrf_oam_net_name: oam_protected_net_0
- pcrf_oam_net_ips: 107.239.64.117,107.239.64.118
- pcrf_oam_net_gw: 107.239.64.1
- pcrf_oam_net_mask: 255.255.248.0
- pcrf_oam_volume_id_1: a4aa05fb-fcdc-457b-8077-6845fdfc3257
- pcrf_oam_volume_id_2: 93d8fc1f-f1c3-4933-86b2-039881ee910f
- pcrf_security_group_name: nimbus_security_group
- pcrf_vnf_id: 730797234b4a40aa99335157b02871cd
-
diff --git a/ui-ci/src/main/resources/Files/hot-nimbus-oam_v0.6.yaml b/ui-ci/src/main/resources/Files/hot-nimbus-oam_v0.6.yaml
deleted file mode 100644
index 6636eba210..0000000000
--- a/ui-ci/src/main/resources/Files/hot-nimbus-oam_v0.6.yaml
+++ /dev/null
@@ -1,108 +0,0 @@
-heat_template_version: 2013-05-23
-
-description: heat template that creates multiple PCRF OAM nodes stack
-
-parameters:
- pcrf_oam_server_names:
- type: comma_delimited_list
- label: PCRF OAM server names
- description: name of the PCRF OAM instance
- pcrf_oam_image_name:
- type: string
- label: PCRF OAM image name
- description: PCRF OAM image name
- pcrf_oam_flavor_name:
- type: string
- label: PCRF OAM flavor name
- description: flavor name of PCRF OAM instance
- availabilityzone_name:
- type: string
- label: availabilityzone name
- description: availabilityzone name
- pcrf_cps_net_name:
- type: string
- label: CPS network name
- description: CPS network name
- pcrf_cps_net_ips:
- type: comma_delimited_list
- label: CPS network ips
- description: CPS network ips
- pcrf_cps_net_mask:
- type: string
- label: CPS network mask
- description: CPS network mask
- pcrf_arbiter_vip:
- type: string
- label: OAM Arbiter LB VIP
- description: OAM Arbiter LB VIP
- pcrf_oam_net_name:
- type: string
- label: OAM network name
- description: OAM network name
- pcrf_oam_net_ips:
- type: comma_delimited_list
- label: OAM network ips
- description: OAM network ips
- pcrf_oam_net_gw:
- type: string
- label: CPS network gateway
- description: CPS network gateway
- pcrf_oam_net_mask:
- type: string
- label: CPS network mask
- description: CPS network mask
- pcrf_oam_volume_id_1:
- type: string
- label: CPS OAM 001 Cinder Volume
- description: CPS OAM 001 Cinder Volumes
- pcrf_oam_volume_id_2:
- type: string
- label: CPS OAM 002 Cinder Volume
- description: CPS OAM 002 Cinder Volumes
- pcrf_security_group_name:
- type: string
- label: security group name
- description: the name of security group
- pcrf_vnf_id:
- type: string
- label: PCRF VNF Id
- description: PCRF VNF Id
-
-resources:
- server_pcrf_oam_001:
- type: nested-oam_v0.2.yaml
- properties:
- pcrf_oam_server_name: { get_param: [pcrf_oam_server_names, 0] }
- pcrf_oam_image_name: { get_param: pcrf_oam_image_name }
- pcrf_oam_flavor_name: { get_param: pcrf_oam_flavor_name }
- availabilityzone_name: { get_param: availabilityzone_name }
- pcrf_security_group_name: { get_param: pcrf_security_group_name }
- pcrf_oam_volume_id: { get_param: pcrf_oam_volume_id_1 }
- pcrf_cps_net_name: { get_param: pcrf_cps_net_name }
- pcrf_cps_net_ip: { get_param: [pcrf_cps_net_ips, 0] }
- pcrf_cps_net_mask: { get_param: pcrf_cps_net_mask }
- pcrf_oam_net_name: { get_param: pcrf_oam_net_name }
- pcrf_oam_net_ip: { get_param: [pcrf_oam_net_ips, 0] }
- pcrf_oam_net_mask: { get_param: pcrf_oam_net_mask }
- pcrf_oam_net_gw: { get_param: pcrf_oam_net_gw }
- pcrf_arbiter_vip: { get_param: pcrf_arbiter_vip }
- pcrf_vnf_id: {get_param: pcrf_vnf_id}
-
- server_pcrf_oam_002:
- type: nested-oam_v0.2.yaml
- properties:
- pcrf_oam_server_name: { get_param: [pcrf_oam_server_names, 1] }
- pcrf_oam_image_name: { get_param: pcrf_oam_image_name }
- pcrf_oam_flavor_name: { get_param: pcrf_oam_flavor_name }
- availabilityzone_name: { get_param: availabilityzone_name }
- pcrf_security_group_name: { get_param: pcrf_security_group_name }
- pcrf_oam_volume_id: { get_param: pcrf_oam_volume_id_2 }
- pcrf_cps_net_name: { get_param: pcrf_cps_net_name }
- pcrf_cps_net_ip: { get_param: [pcrf_cps_net_ips, 1] }
- pcrf_cps_net_mask: { get_param: pcrf_cps_net_mask }
- pcrf_oam_net_name: { get_param: pcrf_oam_net_name }
- pcrf_oam_net_ip: { get_param: [pcrf_oam_net_ips, 1] }
- pcrf_oam_net_mask: { get_param: pcrf_oam_net_mask }
- pcrf_oam_net_gw: { get_param: pcrf_oam_net_gw }
- pcrf_arbiter_vip: { get_param: pcrf_arbiter_vip }
- pcrf_vnf_id: {get_param: pcrf_vnf_id}
diff --git a/ui-ci/src/main/resources/Files/hot-nimbus-pcm_v0.6.yaml b/ui-ci/src/main/resources/Files/hot-nimbus-pcm_v0.6.yaml
deleted file mode 100644
index 564104174a..0000000000
--- a/ui-ci/src/main/resources/Files/hot-nimbus-pcm_v0.6.yaml
+++ /dev/null
@@ -1,80 +0,0 @@
-heat_template_version: 2013-05-23
-
-description: heat template that creates PCRF Cluman stack
-
-parameters:
- pcrf_pcm_server_names:
- type: comma_delimited_list
- label: PCRF CM server names
- description: name of the PCRF CM instance
- pcrf_pcm_image_name:
- type: string
- label: PCRF CM image name
- description: PCRF CM image name
- pcrf_pcm_flavor_name:
- type: string
- label: PCRF CM flavor name
- description: flavor name of PCRF CM instance
- availabilityzone_name:
- type: string
- label: availabilityzone name
- description: availabilityzone name
- pcrf_cps_net_name:
- type: string
- label: CPS network name
- description: CPS network name
- pcrf_cps_net_ips:
- type: comma_delimited_list
- label: CPS network ips
- description: CPS network ips
- pcrf_cps_net_mask:
- type: string
- label: CPS network mask
- description: CPS network mask
- pcrf_oam_net_name:
- type: string
- label: OAM network name
- description: OAM network name
- pcrf_oam_net_ips:
- type: comma_delimited_list
- label: OAM network ips
- description: OAM network ips
- pcrf_oam_net_gw:
- type: string
- label: CPS network gateway
- description: CPS network gateway
- pcrf_oam_net_mask:
- type: string
- label: CPS network mask
- description: CPS network mask
- pcrf_pcm_volume_id_1:
- type: string
- label: CPS Cluman Cinder Volume
- description: CPS Cluman Cinder Volume
- pcrf_security_group_name:
- type: string
- label: security group name
- description: the name of security group
- pcrf_vnf_id:
- type: string
- label: PCRF VNF Id
- description: PCRF VNF Id
-
-resources:
- server_pcrf_pcm_001:
- type: nested-pcm_v0.2.yaml
- properties:
- pcrf_pcm_server_name: { get_param: [pcrf_pcm_server_names, 0] }
- pcrf_pcm_image_name: { get_param: pcrf_pcm_image_name }
- pcrf_pcm_flavor_name: { get_param: pcrf_pcm_flavor_name }
- availabilityzone_name: { get_param: availabilityzone_name }
- pcrf_security_group_name: { get_param: pcrf_security_group_name }
- pcrf_pcm_volume_id: { get_param: pcrf_pcm_volume_id_1 }
- pcrf_cps_net_name: { get_param: pcrf_cps_net_name }
- pcrf_cps_net_ip: { get_param: [pcrf_cps_net_ips, 0] }
- pcrf_cps_net_mask: { get_param: pcrf_cps_net_mask }
- pcrf_oam_net_name: { get_param: pcrf_oam_net_name }
- pcrf_oam_net_ip: { get_param: [pcrf_oam_net_ips, 0] }
- pcrf_oam_net_mask: { get_param: pcrf_oam_net_mask }
- pcrf_oam_net_gw: { get_param: pcrf_oam_net_gw }
- pcrf_vnf_id: {get_param: pcrf_vnf_id}
diff --git a/ui-ci/src/main/resources/Files/sample-xml-alldata-1-1.xml b/ui-ci/src/main/resources/Files/sample-xml-alldata-1-1.xml
deleted file mode 100644
index 1723f6b312..0000000000
--- a/ui-ci/src/main/resources/Files/sample-xml-alldata-1-1.xml
+++ /dev/null
@@ -1,298 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
-<ns2:vnf-catalog xmlns:ns2="http://com/att/co/db-definition">
- <ns2:part-number-list>
- <ns2:part-number>FG-VM00*</ns2:part-number>
- <ns2:vnf-type>FW</ns2:vnf-type>
- <ns2:vendor-info>
- <ns2:vendor-name>FORTINET</ns2:vendor-name>
- <ns2:vendor-part-number>FG-VM00*</ns2:vendor-part-number>
- <ns2:vendor-model>VM00</ns2:vendor-model>
- </ns2:vendor-info>
- <ns2:vcpu>
- <ns2:vcpu-default>1</ns2:vcpu-default>
- <ns2:vcpu-min>1</ns2:vcpu-min>
- <ns2:vcpu-max>1</ns2:vcpu-max>
- </ns2:vcpu>
- <ns2:vmemory>
- <ns2:vmemory-default>1</ns2:vmemory-default>
- <ns2:vmemory-units>GB</ns2:vmemory-units>
- <ns2:vmemory-min>1</ns2:vmemory-min>
- <ns2:vmemory-max>1</ns2:vmemory-max>
- </ns2:vmemory>
- <ns2:vdisk>
- <ns2:vdisk-default>20</ns2:vdisk-default>
- <ns2:vdisk-units>GB</ns2:vdisk-units>
- <ns2:vdisk-min>20</ns2:vdisk-min>
- <ns2:vdisk-max>20</ns2:vdisk-max>
- </ns2:vdisk>
- <software-version-list>
- <software-version>5.2.4</software-version>
- <software-version-state>0</software-version-state>
- <software-filename>fg-5.2.4.qcow</software-filename >
- </software-version-list>
- <software-version-list>
- <software-version>5.2.3</software-version>
- <software-version-state>1</software-version-state>
- <software-filename>fg-5.2.3.qcow</software-filename >
- </software-version-list>
- <software-version-list>
- <software-version>5.2.2</software-version>
- <software-version-state>2</software-version-state>
- <software-filename>fg-5.2.2.qcow</software-filename >
- </software-version-list>
- <vnf-features-list>
- <vnf-feature>IPS-IDS</vnf-feature>
- </vnf-features-list>
- <vnf-features-list>
- <vnf-feature>URLF</vnf-feature>
- </vnf-features-list>
- <vnf-features-list>
- <vnf-feature>Anti-Virus</vnf-feature>
- </vnf-features-list>
- <supported-hardware-list>
- <ucpe-model>U401</ucpe-model >
- </supported-hardware-list>
- <supported-hardware-list>
- <ucpe-model>U410</ucpe-model >
- </supported-hardware-list>
- <supported-hardware-list>
- <ucpe-model>U412</ucpe-model >
- </supported-hardware-list>
- </ns2:part-number-list>
- <ns2:part-number-list>
- <ns2:part-number>FG-VM01*</ns2:part-number>
- <ns2:vnf-type>FW</ns2:vnf-type>
- <ns2:vendor-info>
- <ns2:vendor-name> FORTINET</ns2:vendor-name>
- <ns2:vendor-part-number>FG-VM01*</ns2:vendor-part-number>
- <ns2:vendor-model>VM01</ns2:vendor-model>
- </ns2:vendor-info>
- <ns2:vcpu>
- <ns2:vcpu-default>1</ns2:vcpu-default>
- <ns2:vcpu-min>1</ns2:vcpu-min>
- <ns2:vcpu-max>1</ns2:vcpu-max>
- </ns2:vcpu>
- <ns2:vmemory>
- <ns2:vmemory-default>2</ns2:vmemory-default>
- <ns2:vmemory-units>GB</ns2:vmemory-units>
- <ns2:vmemory-min>1</ns2:vmemory-min>
- <ns2:vmemory-max>2</ns2:vmemory-max>
- </ns2:vmemory>
- <ns2:vdisk>
- <ns2:vdisk-default>20</ns2:vdisk-default>
- <ns2:vdisk-units>GB</ns2:vdisk-units>
- <ns2:vdisk-min>20</ns2:vdisk-min>
- <ns2:vdisk-max>20</ns2:vdisk-max>
- </ns2:vdisk>
- <software-version-list>
- <software-version>5.2.4</software-version>
- <software-version-state>0</software-version-state>
- <software-filename>fg-5.2.4.qcow</software-filename >
- </software-version-list>
- <software-version-list>
- <software-version>5.2.3</software-version>
- <software-version-state>1</software-version-state>
- <software-filename>fg-5.2.3.qcow</software-filename >
- </software-version-list>
- <software-version-list>
- <software-version>5.2.2</software-version>
- <software-version-state>2</software-version-state>
- <software-filename>fg-5.2.2.qcow</software-filename >
- </software-version-list>
- <vnf-features-list>
- <vnf-feature>IPS-IDS</vnf-feature>
- </vnf-features-list>
- <vnf-features-list>
- <vnf-feature>URLF</vnf-feature>
- </vnf-features-list>
- <vnf-features-list>
- <vnf-feature>Anti-Virus</vnf-feature>
- </vnf-features-list>
- <supported-hardware-list>
- <ucpe-model>U401</ucpe-model >
- </supported-hardware-list>
- <supported-hardware-list>
- <ucpe-model>U410</ucpe-model >
- </supported-hardware-list>
- <supported-hardware-list>
- <ucpe-model>U412</ucpe-model >
- </supported-hardware-list>
- </ns2:part-number-list>
- <ns2:part-number-list>
- <ns2:part-number>FG-VM02*</ns2:part-number>
- <ns2:vnf-type>FW</ns2:vnf-type>
- <ns2:vendor-info>
- <ns2:vendor-name> FORTINET</ns2:vendor-name>
- <ns2:vendor-part-number>FG-VM02*</ns2:vendor-part-number>
- <ns2:vendor-model>VM02</ns2:vendor-model>
- </ns2:vendor-info>
- <ns2:vcpu>
- <ns2:vcpu-default>2</ns2:vcpu-default>
- <ns2:vcpu-min>1</ns2:vcpu-min>
- <ns2:vcpu-max>2</ns2:vcpu-max>
- </ns2:vcpu>
- <ns2:vmemory>
- <ns2:vmemory-default>4</ns2:vmemory-default>
- <ns2:vmemory-units>GB</ns2:vmemory-units>
- <ns2:vmemory-min>1</ns2:vmemory-min>
- <ns2:vmemory-max>4</ns2:vmemory-max>
- </ns2:vmemory>
- <ns2:vdisk>
- <ns2:vdisk-default>20</ns2:vdisk-default>
- <ns2:vdisk-units>GB</ns2:vdisk-units>
- <ns2:vdisk-min>20</ns2:vdisk-min>
- <ns2:vdisk-max>20</ns2:vdisk-max>
- </ns2:vdisk>
- <software-version-list>
- <software-version>5.2.4</software-version>
- <software-version-state>0</software-version-state>
- <software-filename>fg-5.2.4.qcow</software-filename >
- </software-version-list>
- <software-version-list>
- <software-version>5.2.3</software-version>
- <software-version-state>1</software-version-state>
- <software-filename>fg-5.2.3.qcow</software-filename >
- </software-version-list>
- <software-version-list>
- <software-version>5.2.2</software-version>
- <software-version-state>2</software-version-state>
- <software-filename>fg-5.2.2.qcow</software-filename >
- </software-version-list>
- <vnf-features-list>
- <vnf-feature>IPS-IDS</vnf-feature>
- </vnf-features-list>
- <vnf-features-list>
- <vnf-feature>URLF</vnf-feature>
- </vnf-features-list>
- <vnf-features-list>
- <vnf-feature>Anti-Virus</vnf-feature>
- </vnf-features-list>
- <supported-hardware-list>
- <ucpe-model>U401</ucpe-model >
- </supported-hardware-list>
- <supported-hardware-list>
- <ucpe-model>U410</ucpe-model >
- </supported-hardware-list>
- <supported-hardware-list>
- <ucpe-model>U412</ucpe-model >
- </supported-hardware-list>
- </ns2:part-number-list>
- <ns2:part-number-list>
- <ns2:part-number>FG-VM04*</ns2:part-number>
- <ns2:vnf-type>FW</ns2:vnf-type>
- <ns2:vendor-info>
- <ns2:vendor-name>FORTINET</ns2:vendor-name>
- <ns2:vendor-part-number>FG-VM04*</ns2:vendor-part-number>
- <ns2:vendor-model>VM04</ns2:vendor-model>
- </ns2:vendor-info>
- <ns2:vcpu>
- <ns2:vcpu-default>4</ns2:vcpu-default>
- <ns2:vcpu-min>1</ns2:vcpu-min>
- <ns2:vcpu-max>4</ns2:vcpu-max>
- </ns2:vcpu>
- <ns2:vmemory>
- <ns2:vmemory-default>6</ns2:vmemory-default>
- <ns2:vmemory-units>GB</ns2:vmemory-units>
- <ns2:vmemory-min>1</ns2:vmemory-min>
- <ns2:vmemory-max>6</ns2:vmemory-max>
- </ns2:vmemory>
- <ns2:vdisk>
- <ns2:vdisk-default>20</ns2:vdisk-default>
- <ns2:vdisk-units>GB</ns2:vdisk-units>
- <ns2:vdisk-min>20</ns2:vdisk-min>
- <ns2:vdisk-max>20</ns2:vdisk-max>
- </ns2:vdisk>
- <software-version-list>
- <software-version>5.2.4</software-version>
- <software-version-state>0</software-version-state>
- <software-filename>fg-5.2.4.qcow</software-filename >
- </software-version-list>
- <software-version-list>
- <software-version>5.2.3</software-version>
- <software-version-state>1</software-version-state>
- <software-filename>fg-5.2.3.qcow</software-filename >
- </software-version-list>
- <software-version-list>
- <software-version>5.2.2</software-version>
- <software-version-state>2</software-version-state>
- <software-filename>fg-5.2.2.qcow</software-filename >
- </software-version-list>
- <vnf-features-list>
- <vnf-feature>IPS-IDS</vnf-feature>
- </vnf-features-list>
- <vnf-features-list>
- <vnf-feature>URLF</vnf-feature>
- </vnf-features-list>
- <vnf-features-list>
- <vnf-feature>Anti-Virus</vnf-feature>
- </vnf-features-list>
- <supported-hardware-list>
- <ucpe-model>U401</ucpe-model >
- </supported-hardware-list>
- <supported-hardware-list>
- <ucpe-model>U410</ucpe-model >
- </supported-hardware-list>
- <supported-hardware-list>
- <ucpe-model>U412</ucpe-model >
- </supported-hardware-list>
- </ns2:part-number-list>
- <ns2:part-number-list>
- <ns2:part-number>FG-VM08*</ns2:part-number>
- <ns2:vnf-type>FW</ns2:vnf-type>
- <ns2:vendor-info>
- <ns2:vendor-name>FORTINET</ns2:vendor-name>
- <ns2:vendor-part-number>FG-VM08*</ns2:vendor-part-number>
- <ns2:vendor-model>VM08</ns2:vendor-model>
- </ns2:vendor-info>
- <ns2:vcpu>
- <ns2:vcpu-default>8</ns2:vcpu-default>
- <ns2:vcpu-min>1</ns2:vcpu-min>
- <ns2:vcpu-max>8</ns2:vcpu-max>
- </ns2:vcpu>
- <ns2:vmemory>
- <ns2:vmemory-default>12</ns2:vmemory-default>
- <ns2:vmemory-units>GB</ns2:vmemory-units>
- <ns2:vmemory-min>1</ns2:vmemory-min>
- <ns2:vmemory-max>12</ns2:vmemory-max>
- </ns2:vmemory>
- <ns2:vdisk>
- <ns2:vdisk-default>20</ns2:vdisk-default>
- <ns2:vdisk-units>GB</ns2:vdisk-units>
- <ns2:vdisk-min>20</ns2:vdisk-min>
- <ns2:vdisk-max>20</ns2:vdisk-max>
- </ns2:vdisk>
- <software-version-list>
- <software-version>5.2.4</software-version>
- <software-version-state>0</software-version-state>
- <software-filename>fg-5.2.4.qcow</software-filename >
- </software-version-list>
- <software-version-list>
- <software-version>5.2.3</software-version>
- <software-version-state>1</software-version-state>
- <software-filename>fg-5.2.3.qcow</software-filename >
- </software-version-list>
- <software-version-list>
- <software-version>5.2.2</software-version>
- <software-version-state>2</software-version-state>
- <software-filename>fg-5.2.2.qcow</software-filename >
- </software-version-list>
- <vnf-features-list>
- <vnf-feature>IPS-IDS</vnf-feature>
- </vnf-features-list>
- <vnf-features-list>
- <vnf-feature>URLF</vnf-feature>
- </vnf-features-list>
- <vnf-features-list>
- <vnf-feature>Anti-Virus</vnf-feature>
- </vnf-features-list>
- <supported-hardware-list>
- <ucpe-model>U401</ucpe-model >
- </supported-hardware-list>
- <supported-hardware-list>
- <ucpe-model>U410</ucpe-model >
- </supported-hardware-list>
- <supported-hardware-list>
- <ucpe-model>U412</ucpe-model >
- </supported-hardware-list>
- </ns2:part-number-list>
-</ns2:vnf-catalog> \ No newline at end of file
diff --git a/ui-ci/src/main/resources/Files/vFW_8.12.16.zip b/ui-ci/src/main/resources/Files/vFW_8.12.16.zip
deleted file mode 100644
index 006c56ca4b..0000000000
--- a/ui-ci/src/main/resources/Files/vFW_8.12.16.zip
+++ /dev/null
Binary files differ
diff --git a/ui-ci/src/main/resources/Files/vFW_VF.yml b/ui-ci/src/main/resources/Files/vFW_VF.yml
deleted file mode 100644
index 100883e399..0000000000
--- a/ui-ci/src/main/resources/Files/vFW_VF.yml
+++ /dev/null
@@ -1,58 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-
-node_types:
-
- org.openecomp.resource.vf.vFW:
- derived_from: tosca.nodes.Root
- properties:
- att-part-number:
- type: string
- vendor-name:
- type: string
- vendor-part-number:
- type: string
- vendor-model:
- type: string
- vendor-model-description:
- type: string
- vcpu-default:
- type: integer
- vcpu-min:
- type: integer
- vcpu-max:
- type: integer
- vmemory-default:
- type: integer
- vmemory-units:
- type: string
- default: "GB"
- vmemory-min:
- type: integer
- vmemory-max:
- type: integer
- vdisk-default:
- type: integer
- vdisk-units:
- type: string
- default: "GB"
- vdisk-min:
- type: integer
- vdisk-max:
- type: integer
- vnf-type:
- type: string
- software-version:
- type: version
- software-version-state:
- type: integer
- software-file-name:
- type: string
- vnf-feature:
- type: string
- requirements:
- - host:
- capability: tosca.capabilities.Container
- relationship: tosca.relationships.HostedOn
- capabilities:
- binding:
- type: tosca.capabilities.network.Bindable \ No newline at end of file
diff --git a/ui-ci/src/main/resources/Files/vFW_VFC.yml b/ui-ci/src/main/resources/Files/vFW_VFC.yml
deleted file mode 100644
index d0814c43aa..0000000000
--- a/ui-ci/src/main/resources/Files/vFW_VFC.yml
+++ /dev/null
@@ -1,58 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-
-node_types:
-
- org.openecomp.resource.vfc.vFW:
- derived_from: tosca.nodes.Root
- properties:
- att-part-number:
- type: string
- vendor-name:
- type: string
- vendor-part-number:
- type: string
- vendor-model:
- type: string
- vendor-model-description:
- type: string
- vcpu-default:
- type: integer
- vcpu-min:
- type: integer
- vcpu-max:
- type: integer
- vmemory-default:
- type: integer
- vmemory-units:
- type: string
- default: "GB"
- vmemory-min:
- type: integer
- vmemory-max:
- type: integer
- vdisk-default:
- type: integer
- vdisk-units:
- type: string
- default: "GB"
- vdisk-min:
- type: integer
- vdisk-max:
- type: integer
- vnf-type:
- type: string
- software-version:
- type: version
- software-version-state:
- type: integer
- software-file-name:
- type: string
- vnf-feature:
- type: string
- requirements:
- - host:
- capability: tosca.capabilities.Container
- relationship: tosca.relationships.HostedOn
- capabilities:
- binding:
- type: tosca.capabilities.network.Bindable \ No newline at end of file
diff --git a/ui-ci/src/main/resources/Files/vLB12.8.16.zip b/ui-ci/src/main/resources/Files/vLB12.8.16.zip
deleted file mode 100644
index 2f61e5ac40..0000000000
--- a/ui-ci/src/main/resources/Files/vLB12.8.16.zip
+++ /dev/null
Binary files differ
diff --git a/ui-ci/src/main/resources/Files/vRouter_vfc.yml b/ui-ci/src/main/resources/Files/vRouter_vfc.yml
deleted file mode 100644
index 95ffe959de..0000000000
--- a/ui-ci/src/main/resources/Files/vRouter_vfc.yml
+++ /dev/null
@@ -1,78 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-
-
-node_types:
- org.openecomp.resource.vfc.vRouter:
- derived_from: tosca.nodes.Root
- properties:
- att-part-number:
- type: string
- vendor-name:
- type: string
- vendor-part-number:
- type: string
- vendor-model:
- type: string
- vendor-model-description:
- type: string
- vcpu-default:
- type: integer
- vcpu-min:
- type: integer
- vcpu-max:
- type: integer
- vmemory-default:
- type: integer
- vmemory-units:
- type: string
- default: "GB"
- vmemory-min:
- type: integer
- vmemory-max:
- type: integer
- vdisk-default:
- type: integer
- vdisk-units:
- type: string
- default: "GB"
- vdisk-min:
- type: integer
- vdisk-max:
- type: integer
- vnf-type:
- type: string
- software-version:
- type: string
- software-version-state:
- type: integer
- software-file-name:
- type: string
- vnf-feature:
- type: string
- management-v6-address:
- type: string
- nm-lan-v6-address:
- type: string
- nm-lan-v6-prefix-length:
- type: string
- management-v4-address:
- type: string
- nm-lan-v4-address:
- type: string
- nm-lan-v4-prefix-length:
- type: string
- routing-instance-name:
- type: string
- routing-instances:
- type: map
- entry_schema:
- type: string
- requirements:
- - host:
- capability: tosca.capabilities.Container
- relationship: tosca.relationships.HostedOn
- capabilities:
- binding:
- type: tosca.capabilities.network.Bindable
- occurrences: [1,UNBOUNDED]
- \ No newline at end of file
diff --git a/ui-ci/src/main/resources/Files/valid HEAT_ENV files.env b/ui-ci/src/main/resources/Files/valid HEAT_ENV files.env
deleted file mode 100644
index e576c0f67d..0000000000
--- a/ui-ci/src/main/resources/Files/valid HEAT_ENV files.env
+++ /dev/null
@@ -1,54 +0,0 @@
-parameters:
- flavor_scp_be_id: m1.small
- flavor_scp_fe_id: m1.small
- flavor_smp_id: m1.small
- flavor_db_id: m1.small
- image_scp_be_id: CCLINUX
- image_scp_fe_id: CCLINUX
- image_smp_id: CCLINUX
- image_db_id: CCLINUX
-
- int_vscp_fe_cluster_net_id: int_vscp_fe_cluster_net
- int_vscp_fe_cluster_cidr: 172.26.2.0/24
- int_vscp_cluster_net_id: int_vscp_cluster_net
- int_vscp_cluster_cidr: 172.26.3.0/24
- int_vscp_db_network_net_id: int_vscp_db_network_net
- int_vscp_db_network_cidr: 172.26.1.0/24
-
- SIGNET_vrf_A1_direct_net_id: SIGNET_vrf_A1_direct_net
- SIGNET_vrf_B1_direct_net_id: SIGNET_vrf_B1_direct_net
- Cricket_OCS_protected_net_id: Cricket_OCS_protected_net
-# OAM_direct_net_id: OAM_net
-# OAM_direct_net_id: oam-direct-net
- OAM_direct_net_id: Marks_OAM_direct_net
-
- be0_Cricket_OCS_protected_ips: 107.239.15.17
- be1_Cricket_OCS_protected_ips: 107.239.15.18
- be2_Cricket_OCS_protected_ips: 107.239.15.19
- be3_Cricket_OCS_protected_ips: 107.239.15.20
- be4_Cricket_OCS_protected_ips: 107.239.15.21
- be0_OAM_direct_ips: 10.250.10.33
- be1_OAM_direct_ips: 10.250.10.34
- be2_OAM_direct_ips: 10.250.10.35
- be3_OAM_direct_ips: 10.250.10.36
- be4_OAM_direct_ips: 10.250.10.37
- fe0_SIGNET_vrf_A1_direct_ips: 172.26.4.1
- fe0_OAM_direct_ips: 10.250.10.38
- fe1_SIGNET_vrf_B1_direct_ips: 172.26.4.5
- fe1_OAM_direct_ips: 10.250.10.39
- smp0_OAM_direct_ips: 10.250.10.40
- smp1_OAM_direct_ips: 10.250.10.41
- db0_OAM_direct_ips: 10.250.10.42
- db1_OAM_direct_ips: 10.250.10.43
-
- vm_scp_be0_name: vSCP_BE0
- vm_scp_be1_name: vSCP_BE1
- vm_scp_be2_name: vSCP_BE2
- vm_scp_be3_name: vSCP_BE3
- vm_scp_be4_name: vSCP_BE4
- vm_scp_fe0_name: vSCP_FE0
- vm_scp_fe1_name: vSCP_FE1
- vm_smp0_name: vSMP0
- vm_smp1_name: vSMP1
- vm_db0_name: vDB0
- vm_db1_name: vDB1
diff --git a/ui-ci/src/main/resources/Files/validHEATfiles.yaml b/ui-ci/src/main/resources/Files/validHEATfiles.yaml
deleted file mode 100644
index 6835485ca1..0000000000
--- a/ui-ci/src/main/resources/Files/validHEATfiles.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/ui-ci/src/main/resources/ci/conf/credentials.yaml b/ui-ci/src/main/resources/ci/conf/credentials.yaml
deleted file mode 100644
index a30d8ce538..0000000000
--- a/ui-ci/src/main/resources/ci/conf/credentials.yaml
+++ /dev/null
@@ -1,48 +0,0 @@
- designer: {
- username: cs0008,
- password: demo,
- firstname: ASDC,
- lastname: KASPIN
- }
- admin: {
- username: jh0003,
- password: demo,
- firstname: ASDC,
- lastname: KASPIN
- }
- ops: {
- username: op0001,
- password: demo,
- firstname: ASDC,
- lastname: KASPIN
- }
- tester: {
- username: jm0007,
- password: demo,
- firstname: ASDC,
- lastname: KASPIN
- }
- governor: {
- username: gv0001,
- password: demo,
- firstname: ASDC,
- lastname: KASPIN
- }
- product_strategist: {
- username: ps0001,
- password: demo,
- firstname: ASDC,
- lastname: KASPIN
- }
- product_manager: {
- username: pm0001,
- password: demo,
- firstname: ASDC,
- lastname: KASPIN
- }
- product_local: {
- username: pm0001,
- password: 123123a,
- firstname: ASDC,
- lastname: KASPIN
- } \ No newline at end of file
diff --git a/ui-ci/src/main/resources/ci/conf/log4j.properties b/ui-ci/src/main/resources/ci/conf/log4j.properties
deleted file mode 100644
index 3e159ec8df..0000000000
--- a/ui-ci/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/src/main/resources/ci/conf/sdc-packages.yaml b/ui-ci/src/main/resources/ci/conf/sdc-packages.yaml
deleted file mode 100644
index dcb78eefc1..0000000000
--- a/ui-ci/src/main/resources/ci/conf/sdc-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/src/main/resources/ci/conf/sdc.yaml b/ui-ci/src/main/resources/ci/conf/sdc.yaml
deleted file mode 100644
index 8e84fecf3b..0000000000
--- a/ui-ci/src/main/resources/ci/conf/sdc.yaml
+++ /dev/null
@@ -1,57 +0,0 @@
-outputFolder: target
-reportName: index.html
-catalogBeHost: localhost
-catalogFeHost: localhost
-esHost: eshost
-disributionClientHost: disClient
-catalogFePort: 8181
-catalogBePort: 8080
-disributionClientPort: 8181
-esPort: 9200
-neoHost: neoHost
-neoPort: 7474
-neoDBusername: neo4j
-neoDBpassword: 123456
-url: http://localhost:8285/sdc1
-remoteTestingMachineIP: 1.2.3.4
-remoteTestingMachinePort: 5555
-remoteTesting: false
-
-resourceConfigDir: src/test/resources/CI/tests
-componentsConfigDir: src/test/resources/CI/components
-importResourceConfigDir: src/test/resources/CI/importResource
-importResourceTestsConfigDir: src/test/resources/CI/importResourceTests
-errorConfigurationFile: ../catalog-be/src/main/resources/config/error-configuration.yaml
-configurationFile: ../catalog-be/src/main/resources/config/configuration.yaml
-importTypesConfigDir: src/test/resources/CI/importTypesTest
-
-
-titanPropertiesFile: src/main/resources/ci/conf/titan.properties
-
-stopOnClassFailure: false
-
-#List of non-abstract resources to keep during titan cleanup between tests
-#Only 1.0 version will be kept
-resourcesNotToDelete:
- - tosca.nodes.Compute
- - tosca.nodes.Database
- - tosca.nodes.ObjectStorage
- - tosca.nodes.BlockStorage
- - tosca.nodes.LoadBalancer
- - org.openecomp.resource.cp.Port
- - org.openecomp.resource.vl.Network
-
-#Resource categories to keep (including all their subcategories)
-resourceCategoriesNotToDelete:
- - Generic
- - Network L2-3
- - Network L4+
- - Application L4+
- - Network Connectivity
-
-#Service categories to keep
-serviceCategoriesNotToDelete:
- - Mobility
- - Network L1-3
- - Network L4
- - VoIP Call Control \ No newline at end of file
diff --git a/ui-ci/src/main/resources/ci/conf/titan.properties b/ui-ci/src/main/resources/ci/conf/titan.properties
deleted file mode 100644
index 94d12cfba0..0000000000
--- a/ui-ci/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/src/main/resources/ci/scripts/startTest.sh b/ui-ci/src/main/resources/ci/scripts/startTest.sh
deleted file mode 100644
index b4b2cb114e..0000000000
--- a/ui-ci/src/main/resources/ci/scripts/startTest.sh
+++ /dev/null
@@ -1,96 +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/sdc.yaml
-
-DEBUG=true
-MainClass=org.openecomp.sdc.ci.tests.run.StartTest
-
-JAR_FILE=$1
-SUITE_FILE=$2
-FILES_TEST=$3
-
-if [ -z "$3" ]
-then
- FILES_TEST=${FULL_PATH}/Files
- echo "$3"
-fi
-
-#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="nohup java $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 &"
-
-#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/ui-ci/src/main/resources/ci/testSuites/ui-ci.xml b/ui-ci/src/main/resources/ci/testSuites/ui-ci.xml
deleted file mode 100644
index a6c2584a2c..0000000000
--- a/ui-ci/src/main/resources/ci/testSuites/ui-ci.xml
+++ /dev/null
@@ -1,16 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
-<suite name="uitests" configfailurepolicy="continue">
- <test name="uitests">
- <classes>
- <!--onboard-->
- <class name="org.openecomp.sdc.ci.tests.execute.sanity.Onboard">
- <methods>
- <include name="onboardVNFTest"/>
- </methods>
- </class>
- <!--vf-->
- <class name="org.openecomp.sdc.ci.tests.execute.sanity.Vf"/>
- </classes>
- </test> <!-- uitests -->
-</suite> <!-- uisuite --> \ No newline at end of file
diff --git a/ui-ci/src/main/resources/images/gizmorambo.jpg b/ui-ci/src/main/resources/images/gizmorambo.jpg
deleted file mode 100644
index c9a8fe8a64..0000000000
--- a/ui-ci/src/main/resources/images/gizmorambo.jpg
+++ /dev/null
Binary files differ
diff --git a/ui-ci/src/test/Completetheform.js b/ui-ci/src/test/Completetheform.js
deleted file mode 100644
index 13779e24b8..0000000000
--- a/ui-ci/src/test/Completetheform.js
+++ /dev/null
@@ -1,23 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-/**
- * New node file
- */
diff --git a/ui-ci/tarball.xml b/ui-ci/tarball.xml
deleted file mode 100644
index 1413038c94..0000000000
--- a/ui-ci/tarball.xml
+++ /dev/null
@@ -1,60 +0,0 @@
-<assembly
- xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
- <id>bin</id>
- <formats>
- <format>tar</format>
- </formats>
- <files>
- <file>
- <source>${project.build.directory}/${project.artifactId}-${project.version}-jar-with-dependencies.jar</source>
- <outputDirectory>./</outputDirectory>
- <destName>${project.artifactId}-${project.version}-jar-with-dependencies.jar</destName>
- </file>
- <file>
- <source>src/main/resources/ci/scripts/startTest.sh</source>
- <outputDirectory>./</outputDirectory>
- <destName>startTest.sh</destName>
- </file>
- <!--file> <source>src/main/resources/ci/scripts/postinstall</source> <outputDirectory>./</outputDirectory>
- <destName>postinstall</destName> </file -->
- <file>
- <source>src/main/resources/ci/conf/sdc.yaml</source>
- <outputDirectory>conf</outputDirectory>
- <destName>sdc.yaml</destName>
- </file>
- <file>
- <source>src/main/resources/ci/conf/sdc-packages.yaml</source>
- <outputDirectory>conf</outputDirectory>
- <destName>sdc-packages.yaml</destName>
- </file>
- <file>
- <source>../asdc-tests/src/main/resources/ci/conf/log4j.properties</source>
- <outputDirectory>conf</outputDirectory>
- <destName>log4j.properties</destName>
- </file>
- <file>
- <source>src/main/resources/ci/conf/credentials.yaml</source>
- <outputDirectory>conf</outputDirectory>
- <destName>credentials.yaml</destName>
- </file>
-
- </files>
-
- <fileSets>
- <fileSet>
- <directory>src/test/resources</directory>
- <outputDirectory>./</outputDirectory>
- </fileSet>
- <fileSet>
- <directory>src/main/resources/ci/testSuites</directory>
- <outputDirectory>./testSuites</outputDirectory>
- </fileSet>
- <fileSet>
- <directory>src/main/resources/Files</directory>
- <outputDirectory>./Files</outputDirectory>
- </fileSet>
- </fileSets>
-
-</assembly>
diff --git a/webseal-simulator/README.txt b/utils/webseal-simulator/README.txt
index 46fd622bc8..46fd622bc8 100644
--- a/webseal-simulator/README.txt
+++ b/utils/webseal-simulator/README.txt
diff --git a/utils/webseal-simulator/pom.xml b/utils/webseal-simulator/pom.xml
new file mode 100644
index 0000000000..7d5df432fe
--- /dev/null
+++ b/utils/webseal-simulator/pom.xml
@@ -0,0 +1,110 @@
+<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/maven-v4_0_0.xsd">
+
+ <modelVersion>4.0.0</modelVersion>
+ <groupId>org.openecomp.sdc</groupId>
+ <artifactId>webseal-simulator</artifactId>
+ <packaging>war</packaging>
+ <version>0.0.1-SNAPSHOT</version>
+
+ <properties>
+ <jetty-version>9.2.10.v20150310</jetty-version>
+ </properties>
+
+ <dependencies>
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <version>4.12</version>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>javax.servlet</groupId>
+ <artifactId>servlet-api</artifactId>
+ <version>2.5</version>
+ <scope>compile</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>commons-httpclient</groupId>
+ <artifactId>commons-httpclient</artifactId>
+ <version>3.1</version>
+ </dependency>
+
+ <dependency>
+ <groupId>commons-logging</groupId>
+ <artifactId>commons-logging-api</artifactId>
+ <version>1.0.4</version>
+ </dependency>
+
+ <dependency>
+ <groupId>commons-io</groupId>
+ <artifactId>commons-io</artifactId>
+ <version>2.4</version>
+ </dependency>
+
+ <dependency>
+ <groupId>commons-codec</groupId>
+ <artifactId>commons-codec</artifactId>
+ <version>2.0-SNAPSHOT</version>
+ <scope>compile</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.eclipse.jetty</groupId>
+ <artifactId>jetty-proxy</artifactId>
+ <version>9.2.10.v20150310</version>
+ <scope>compile</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.eclipse.jetty</groupId>
+ <artifactId>jetty-servlets</artifactId>
+ <version>${jetty-version}</version>
+ <scope>compile</scope>
+ </dependency>
+
+ <!-- Proxy servlet -->
+ <dependency>
+ <groupId>com.typesafe</groupId>
+ <artifactId>config</artifactId>
+ <version>1.0.2</version>
+ <scope>compile</scope>
+ </dependency>
+
+ </dependencies>
+ <build>
+ <finalName>WSSimulator</finalName>
+ <plugins>
+ <!-- ================================================== -->
+ <!-- Set the JDK compiler version. -->
+ <!-- ================================================== -->
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <version>2.5.1</version>
+ <inherited>true</inherited>
+ <configuration>
+ <source>1.8</source>
+ <target>1.8</target>
+ </configuration>
+ </plugin>
+
+ <plugin>
+ <groupId>org.eclipse.jetty</groupId>
+ <artifactId>jetty-maven-plugin</artifactId>
+ <version>${jetty-version}</version>
+ <configuration>
+ <contextPath>/</contextPath>
+ <webApp>
+ <contextPath>/</contextPath>
+ <webInfIncludeJarPattern>.*/.*jersey-[^/]\.jar$</webInfIncludeJarPattern>
+ </webApp>
+ <war>WSSimulator.war</war>
+ </configuration>
+ </plugin>
+
+ </plugins>
+ </build>
+</project>
diff --git a/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/Login.java b/utils/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/Login.java
index b345824bd6..bc6dee0ce4 100644
--- a/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/Login.java
+++ b/utils/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/Login.java
@@ -3,6 +3,7 @@ package org.openecomp.sdc.webseal.simulator;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
+import java.util.Iterator;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
@@ -48,8 +49,10 @@ public class Login extends HttpServlet {
writer.println("h2 {margin-top: 20px;}");
writer.println(".label {width: 100px; float:left;}");
writer.println(".break {display: block; margin-bottom: 10px;}");
- writer.println("li {margin-bottom: 10px;}");
- writer.println("</style>");
+ writer.println("tr {padding: 4px 10px;}");
+ writer.println("th {padding: 4px 10px; text-align: left; background-color: #dddddd;}");
+ writer.println("td {padding: 4px 10px; text-align: left;}");
+ writer.println("</style>");
writer.println("</head>");
writer.println("<body>");
@@ -72,10 +75,27 @@ public class Login extends HttpServlet {
writer.println("<hr/>");
writer.println("<h2>Quick links:</h2>");
- writer.println("<ul>");
- allUsers.forEach(u -> writer.println("<li>" + u.getUserRef() + " (" + u.getUserId() + ")" + "</li>"));
- writer.println("</ul>");
+ writer.println("<table>");
+ writer.println("<tr>");
+ writer.println("<th>full name</th>");
+ writer.println("<th>user id</th>");
+ writer.println("<th>role</th>");
+ writer.println("<th>action</th>");
+ writer.println("</tr>");
+ Iterator<User> iterator = allUsers.iterator();
+ while (iterator.hasNext()) {
+ User user = iterator.next();
+ writer.println("<tr>");
+ writer.println("<td>" + user.getUserRef() + "</td>");
+ writer.println("<td>" + user.getUserId() + "</td>");
+ writer.println("<td>" + user.getRole() + "</td>");
+ writer.println("<td>" + user.getUserCreateRef() + "</td>");
+ writer.println("</tr>");
+ }
+ writer.println("</table>");
+ writer.println("<hr/><iframe name='resultFrame' width='400' height='50'></iframe>");
+
writer.println("</body>");
writer.println("</html>");
@@ -90,19 +110,19 @@ public class Login extends HttpServlet {
System.out.println("Login -> doPOst userId=" + userId);
User user = getUser(userId, password);
if (user == null) {
- request.setAttribute("message", "ERROR: attuid or password incorect");
+ request.setAttribute("message", "ERROR: userId or password incorect");
doGet(request, response);
} else {
System.out.println("Login -> doPOst redirext to /sdc1 (to proxy)");
Cookie cookieUser = new Cookie("HTTP_IV_USER", user.getUserId());
- Cookie cookieAttuid = new Cookie("USER_ID", user.getUserId());
+ Cookie cookieUserId = new Cookie("USER_ID", user.getUserId());
Cookie cookieFirstName = new Cookie("HTTP_CSP_FIRSTNAME", user.getFirstName());
Cookie cookieEmail = new Cookie("HTTP_CSP_EMAIL", user.getEmail());
Cookie cookieLastName = new Cookie("HTTP_CSP_LASTNAME", user.getLastName());
Cookie cookieRemoteAddress = new Cookie("HTTP_IV_REMOTE_ADDRESS", "0.0.0.0");
Cookie cookieWsType = new Cookie("HTTP_CSP_WSTYPE", "Intranet");
response.addCookie(cookieUser);
- response.addCookie(cookieAttuid);
+ response.addCookie(cookieUserId);
response.addCookie(cookieFirstName);
response.addCookie(cookieEmail);
response.addCookie(cookieLastName);
diff --git a/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/MethodEnum.java b/utils/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/MethodEnum.java
index 6b9b01d259..6b9b01d259 100644
--- a/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/MethodEnum.java
+++ b/utils/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/MethodEnum.java
diff --git a/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/MutableHttpServletRequest.java b/utils/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/MutableHttpServletRequest.java
index 74c8a15c80..74c8a15c80 100644
--- a/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/MutableHttpServletRequest.java
+++ b/utils/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/MutableHttpServletRequest.java
diff --git a/utils/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/RequestsClient.java b/utils/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/RequestsClient.java
new file mode 100644
index 0000000000..5f4cfa93d2
--- /dev/null
+++ b/utils/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/RequestsClient.java
@@ -0,0 +1,120 @@
+package org.openecomp.sdc.webseal.simulator;
+
+import java.io.BufferedReader;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.PrintWriter;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.commons.io.IOUtils;
+
+public class RequestsClient extends HttpServlet {
+
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ protected void doGet(final HttpServletRequest request, final HttpServletResponse response)
+ throws ServletException, IOException {
+
+ String userId = request.getParameter("userId");
+ String role = request.getParameter("role");
+ String firstName = request.getParameter("firstName");
+ String lastName = request.getParameter("lastName");
+ String email = request.getParameter("email");
+
+ String hostname = request.getParameter("hostname") != null?request.getParameter("hostname"):"127.0.0.1";
+ String port = request.getParameter("port") != null?request.getParameter("port"):"8080";
+ String adminId = request.getParameter("adminId") != null?request.getParameter("adminId"):"jh0003";
+
+ response.setContentType("text/html");
+ PrintWriter writer = response.getWriter();
+ writer.println("userId: " + userId);
+ writer.println("role: " + role);
+
+ // Fill the data of the request
+ String url = "http://" + hostname + ":" + port + "/sdc2/rest/v1/user";
+ String body = "{'firstName':'" + firstName + "', 'lastName':'" + lastName + "', 'userId':'" + userId + "', 'email':'" + email + "','role':'" + role + "'}";
+ HashMap<String, String> headers = new HashMap<String, String>();
+ headers.put("Content-Type", "application/json");
+ headers.put("USER_ID", adminId);
+ sendHttpPost(url, body, headers);
+
+ }
+
+ private String sendHttpPost(String url, String body, Map<String, String> headers) throws IOException {
+
+ String responseString="";
+ 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();
+ }
+
+ 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);
+
+ if (response != null) {
+ responseString = response.toString();
+ }
+
+ //Map<String, List<String>> headerFields = con.getHeaderFields();
+ //String responseMessage = con.getResponseMessage();
+
+ con.disconnect();
+ return responseString;
+
+ }
+
+}
diff --git a/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 674f39ff36..48e3a71aa5 100644
--- a/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
@@ -46,7 +46,7 @@ public class SdcProxy extends HttpServlet {
private final String SCRIPTS = "/scripts";
private final String STYLES = "/styles";
private final String LANGUAGES = "/languages";
-
+ private final String CONFIGURATIONS = "/configurations";
public void init(ServletConfig config) throws ServletException {
super.init(config);
@@ -164,6 +164,7 @@ public class SdcProxy extends HttpServlet {
contextPaths.add(STYLES);
contextPaths.add(SCRIPTS);
contextPaths.add(LANGUAGES);
+ contextPaths.add(CONFIGURATIONS);
return contextPaths;
}
diff --git a/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/User.java b/utils/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/User.java
index 7ec1d936ba..9417e93ee0 100644
--- a/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/User.java
+++ b/utils/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/User.java
@@ -6,6 +6,7 @@ public class User {
private String lastName;
private String email;
private String userId;
+ private String role;
private String password;
@@ -15,13 +16,14 @@ public class User {
public User(String userId){
setUserId(userId);
}
-
- public User(String firstName,String lastName,String email,String userId,String password){
+
+ public User(String firstName,String lastName,String email,String userId, String role, String password){
setUserId(userId);
setFirstName(firstName);
setLastName(lastName);
setEmail(email);
setPassword(password);
+ setRole(role);
}
public String getFirstName() {
@@ -56,9 +58,26 @@ public class User {
this.password = password;
}
+ public String getRole() {
+ return role;
+ }
+
+ public void setRole(String role) {
+ this.role = role;
+ }
+
public String getUserRef() {
return "<a href='?userId="+getUserId()+"&password="+getPassword()+"'>"+getFirstName()+" "+getLastName()+"</a>";
}
-
+ public String getUserCreateRef() {
+ return "<a href='create?userId="+getUserId()+"&firstName="+getFirstName()+"&lastName="+getLastName()+"&role=" + getRole() + "&email=" + getEmail() + "' target='resultFrame'>create</a>";
+ }
+
+ @Override
+ public String toString() {
+ return "User [firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + ", userId=" + userId
+ + ", role=" + role + ", password=" + password + "]";
+ }
+
}
diff --git a/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/conf/Conf.java b/utils/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/conf/Conf.java
index cde77c6c96..c00af32734 100644
--- a/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/conf/Conf.java
+++ b/utils/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/conf/Conf.java
@@ -37,7 +37,8 @@ public class Conf {
String firstName = conf.getString("firstName");
String lastName = conf.getString("lastName");
String email = conf.getString("email");
- users.put(userId,new User(firstName,lastName,email,userId,password));
+ String role = conf.getString("role");
+ users.put(userId,new User(firstName,lastName,email,userId,role,password));
}
}catch(Exception e){
diff --git a/webseal-simulator/src/main/resources/webseal.conf b/utils/webseal-simulator/src/main/resources/webseal.conf
index 4f6455210a..869b17bebc 100644
--- a/webseal-simulator/src/main/resources/webseal.conf
+++ b/utils/webseal-simulator/src/main/resources/webseal.conf
@@ -7,41 +7,39 @@
password="123123a"
firstName="Carlos"
lastName="Santana"
- email="csantana@att.com"
- },
+ role="Desiner"
+ email="csantana@sdc.com"
+ },
{
- userId="af0006"
+ userId="op0001"
password="123123a"
firstName="Aretha"
lastName="Franklin"
- email="afranklin@att.com"
+ role="Ops"
+ email="afranklin@sdc.com"
},
{
userId="jh0003"
password="123123a"
firstName="Jimmy"
lastName="Hendrix"
+ role="Admin"
email="admin@sdc.com"
},
{
- userId="kb0004"
+ userId="jm0007"
password="123123a"
- firstName="Kate"
- lastName="Bush"
+ firstName="Johnny"
+ lastName="Depp"
+ role="Tester"
email="tester@sdc.com"
},
{
- userId="op0001"
- password="123123a"
- firstName="Steve"
- lastName="Regev"
- email="ops@sdc.com"
- },
- {
userId="gv0001"
password="123123a"
firstName="David"
lastName="Shadmi"
+ role="Governor"
email="governor@sdc.com"
},
{
@@ -49,6 +47,7 @@
password="123123a"
firstName="Teddy"
lastName="Isashar"
+ role="Product Manager"
email="pm1@sdc.com"
},
{
@@ -56,9 +55,11 @@
password="123123a"
firstName="Eden"
lastName="Rozin"
+ role="Product Strategist"
email="ps1@sdc.com"
}
]
}
-} \ No newline at end of file
+}
+
diff --git a/utils/webseal-simulator/src/main/webapp/WEB-INF/jetty-web.xml b/utils/webseal-simulator/src/main/webapp/WEB-INF/jetty-web.xml
new file mode 100644
index 0000000000..dc85045b36
--- /dev/null
+++ b/utils/webseal-simulator/src/main/webapp/WEB-INF/jetty-web.xml
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "http://www.eclipse.org/jetty/configure.dtd">
+
+<Configure class="org.eclipse.jetty.webapp.WebAppContext">
+ <Set name="contextPath">/</Set>
+</Configure> \ No newline at end of file
diff --git a/webseal-simulator/src/main/webapp/WEB-INF/web.xml b/utils/webseal-simulator/src/main/webapp/WEB-INF/web.xml
index 787335ea20..7535e1bdf8 100644
--- a/webseal-simulator/src/main/webapp/WEB-INF/web.xml
+++ b/utils/webseal-simulator/src/main/webapp/WEB-INF/web.xml
@@ -1,9 +1,8 @@
-<!DOCTYPE web-app PUBLIC
- "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
- "http://java.sun.com/dtd/web-app_2_3.dtd" >
-
-<web-app>
-
+<?xml version="1.0" encoding="UTF-8"?>
+<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
+ version="3.0">
+
<display-name>Archetype Created Web Application</display-name>
<servlet>
@@ -24,6 +23,15 @@
<url-pattern>/login</url-pattern>
</servlet-mapping>
+ <servlet>
+ <servlet-name>CreateUser</servlet-name>
+ <servlet-class>org.openecomp.sdc.webseal.simulator.RequestsClient</servlet-class>
+ </servlet>
+ <servlet-mapping>
+ <servlet-name>CreateUser</servlet-name>
+ <url-pattern>/create</url-pattern>
+ </servlet-mapping>
+
<welcome-file-list>
<welcome-file>login</welcome-file>
</welcome-file-list>
diff --git a/webseal-simulator/src/main/webapp/login.html b/utils/webseal-simulator/src/main/webapp/login.html
index 1760fcf8e6..084a0b4255 100644
--- a/webseal-simulator/src/main/webapp/login.html
+++ b/utils/webseal-simulator/src/main/webapp/login.html
@@ -4,8 +4,8 @@ Login
<form action="access" method="post">
- ATTUID:<br>
- <input type="text" name="attuid" >
+ UserId:<br>
+ <input type="text" name="userId" >
<br>
PASSWORD:<br>
<input type="password" name="password" >
diff --git a/webseal-simulator/Dockerfile b/webseal-simulator/Dockerfile
deleted file mode 100644
index 9d01611dc9..0000000000
--- a/webseal-simulator/Dockerfile
+++ /dev/null
@@ -1,20 +0,0 @@
-FROM jetty:9.3.15-jre8
-
-RUN apt-get -y update
-RUN apt-get -y install apt-utils
-RUN apt-get -y install curl
-RUN apt-get -y install vim
-
-
-
-
-
-ADD ./../target/WSSimulator.war ${JETTY_BASE}/webapps/
-RUN chown -R jetty:jetty ${JETTY_BASE}/webapps
-ADD ./
-
-COPY startup.sh /root/
-
-RUN chmod 770 /root/startup.sh
-
-ENTRYPOINT [ "/root/startup.sh" ]
diff --git a/webseal-simulator/pom.xml b/webseal-simulator/pom.xml
deleted file mode 100644
index cbfcd7185f..0000000000
--- a/webseal-simulator/pom.xml
+++ /dev/null
@@ -1,133 +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/maven-v4_0_0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <groupId>org.openecomp.sdc</groupId>
- <artifactId>webseal-simulator</artifactId>
- <packaging>war</packaging>
- <version>0.0.1-SNAPSHOT</version>
-
-<parent>
- <groupId>org.openecomp.sdc</groupId>
- <artifactId>sdc-main</artifactId>
- <version>1610.2.4</version>
-</parent>
-
-
- <properties>
- <jetty-version>9.2.10.v20150310</jetty-version>
- </properties>
-
-
- <dependencies>
-
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-api</artifactId>
- <version>1.7.10</version>
- <scope>compile</scope>
- </dependency>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>4.12</version>
- <scope>test</scope>
- </dependency>
-
- <dependency>
- <groupId>javax.servlet</groupId>
- <artifactId>servlet-api</artifactId>
- <version>2.5</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>commons-httpclient</groupId>
- <artifactId>commons-httpclient</artifactId>
- <version>3.1</version>
- </dependency>
-
- <dependency>
- <groupId>commons-logging</groupId>
- <artifactId>commons-logging-api</artifactId>
- <version>1.0.4</version>
- </dependency>
-
- <dependency>
- <groupId>commons-codec</groupId>
- <artifactId>commons-codec</artifactId>
- <version>2.0-SNAPSHOT</version>
- <scope>compile</scope>
- </dependency>
-
-
-
- <!-- Jetty Proxy -->
-
- <dependency>
- <groupId>org.eclipse.jetty</groupId>
- <artifactId>jetty-webapp</artifactId>
- <version>9.2.10.v20150310</version>
- <scope>provided</scope>
- </dependency>
-
-
- <dependency>
- <groupId>org.eclipse.jetty</groupId>
- <artifactId>jetty-proxy</artifactId>
- <version>9.2.10.v20150310</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>org.eclipse.jetty</groupId>
- <artifactId>jetty-servlets</artifactId>
- <version>9.2.10.v20150310</version>
- <scope>compile</scope>
- </dependency>
-
- <!-- Proxy servlet -->
-
-
- <dependency>
- <groupId>com.typesafe</groupId>
- <artifactId>config</artifactId>
- <version>1.0.2</version>
- <scope>compile</scope>
- </dependency>
-
- </dependencies>
- <build>
- <finalName>WSSimulator</finalName>
- <plugins>
- <!-- ================================================== -->
- <!-- Set the JDK compiler version. -->
- <!-- ================================================== -->
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-compiler-plugin</artifactId>
- <version>2.5.1</version>
- <inherited>true</inherited>
- <configuration>
- <source>1.8</source>
- <target>1.8</target>
- </configuration>
- </plugin>
-
-
- <plugin>
- <groupId>org.eclipse.jetty</groupId>
- <artifactId>jetty-maven-plugin</artifactId>
- <version>9.2.10.v20150310</version>
- <configuration>
- <contextPath>/</contextPath>
- <webApp>
- <contextPath>/</contextPath>
- <webInfIncludeJarPattern>.*/.*jersey-[^/]\.jar$</webInfIncludeJarPattern>
- </webApp>
- <war>WSSimulator.war</war>
- </configuration>
- </plugin>
-
- </plugins>
- </build>
-</project>
diff --git a/webseal-simulator/src/main/webapp/WEB-INF/jetty-web.xml b/webseal-simulator/src/main/webapp/WEB-INF/jetty-web.xml
deleted file mode 100644
index 2e287bcc90..0000000000
--- a/webseal-simulator/src/main/webapp/WEB-INF/jetty-web.xml
+++ /dev/null
@@ -1,8 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE Configure PUBLIC
- "-//Mort Bay Consulting//DTD Configure//EN"
- "http://www.eclipse.org/jetty/configure_9_0.dtd">
-
-<Configure class="org.eclipse.jetty.webapp.WebAppContext">
- <Set name="contextPath">/</Set>
-</Configure>